forked from MakisChristou/rieMiner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Miner.cpp
1386 lines (1320 loc) · 72 KB
/
Miner.cpp
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
/* (c) 2017-2022 Pttn (https://riecoin.dev/en/rieMiner)
(c) 2018-2020 Michael Bell/Rockhawk (assembly optimizations, improvements of work management between threads, and some more) (https://github.com/MichaelBell/) */
#include <gmpxx.h> // With Uint64_Ts, we still need to use the Mpz_ functions, otherwise there are "ambiguous overload" errors on Windows...
#include "Miner.hpp"
#ifdef __SSE2__
#include "external/gmp_util.h"
extern "C" {
void rie_mod_1s_4p_cps(uint64_t *cps, uint64_t p);
mp_limb_t rie_mod_1s_4p(mp_srcptr ap, mp_size_t n, uint64_t ps, uint64_t cnt, uint64_t* cps);
mp_limb_t rie_mod_1s_2p_4times(mp_srcptr ap, mp_size_t n, uint32_t* ps, uint32_t cnt, uint64_t* cps, uint64_t* remainders);
#ifdef __AVX2__
mp_limb_t rie_mod_1s_2p_8times(mp_srcptr ap, mp_size_t n, uint32_t* ps, uint32_t cnt, uint64_t* cps, uint64_t* remainders);
#endif
}
#else
uint64_t mulMod(const uint64_t a, const uint64_t b, const uint64_t c) { // (ab) % c without assembly optimizations
#ifdef __SIZEOF_INT128__
return (static_cast<__uint128_t>(a)*b) % c;
#else
mpz_class tmp;
mpz_set_ui(tmp.get_mpz_t(), a);
mpz_mul_ui(tmp.get_mpz_t(), tmp.get_mpz_t(), b);
return mpz_tdiv_ui(tmp.get_mpz_t(), c);
#endif
}
#endif
constexpr uint64_t nPrimesTo2p32(203280221);
constexpr int factorsCacheSize(16384);
constexpr uint16_t maxSieveWorkers(64); // There is a noticeable performance penalty using Std Vector or Arrays so we are using Raw Arrays.
thread_local uint64_t** factorsCache{nullptr};
thread_local uint64_t** factorsCacheCounts{nullptr};
thread_local uint16_t threadId(65535);
void Miner::init(const MinerParameters &minerParameters) {
_tupleFound = false;
_shouldRestart = false;
if (_inited) {
logger.log("The miner is already initialized\n"s, MessageType::ERROR);
return;
}
if (_client == nullptr) {
logger.log("The miner cannot be initialized without a client\n"s, MessageType::ERROR);
return;
}
Job job(_client->getJob(true));
if (job.powVersion == 0) { // Using this check rather than Height = 0 to make Benchmark Mode work
logger.log("Could not get data from Client\n"s, MessageType::ERROR);
return;
}
_difficultyAtInit = job.difficulty;
logger.log("Initializing miner...\n"s);
// Get settings from Configuration File.
_parameters = minerParameters;
if (_parameters.threads == 0) {
_parameters.threads = std::thread::hardware_concurrency();
if (_parameters.threads == 0) {
logger.log("Could not detect number of Threads, setting to 1.\n"s, MessageType::WARNING);
_parameters.threads = 1;
}
}
if (_parameters.primorialOffsets.size() == 0) { // Set the default Primorial Offsets if not chosen (must be chosen if the chosen pattern is not hardcoded)
auto defaultPrimorialOffsetsIterator(std::find_if(defaultConstellationData.begin(), defaultConstellationData.end(), [this](const auto& constellationData) {return constellationData.first == _parameters.pattern;}));
if (defaultPrimorialOffsetsIterator == defaultConstellationData.end()) {
logger.log("No hardcoded Constellation Offsets chosen and no Primorial Offset set.\n"s, MessageType::ERROR);
return;
}
else
_parameters.primorialOffsets = defaultPrimorialOffsetsIterator->second;
}
_primorialOffsets = v64ToVMpz(_parameters.primorialOffsets);
if (_parameters.sieveWorkers == 0) {
double proportion;
if (_parameters.pattern.size() >= 7) proportion = 0.85 - _difficultyAtInit/1920.;
else if (_parameters.pattern.size() == 6) proportion = 0.75 - _difficultyAtInit/1792.;
else if (_parameters.pattern.size() == 5) proportion = 0.7 - _difficultyAtInit/1280.;
else if (_parameters.pattern.size() == 4) proportion = 0.5 - _difficultyAtInit/1280.;
else proportion = 0.;
if (proportion < 0.) proportion = 0.;
if (proportion > 1.) proportion = 1.;
_parameters.sieveWorkers = std::ceil(proportion*static_cast<double>(_parameters.threads));
}
_parameters.sieveWorkers = std::min(static_cast<int>(_parameters.sieveWorkers), static_cast<int>(_parameters.threads) - 1);
_parameters.sieveWorkers = std::max(static_cast<int>(_parameters.sieveWorkers), 1);
_parameters.sieveWorkers = std::min(_parameters.sieveWorkers, maxSieveWorkers);
_parameters.sieveWorkers = std::min(static_cast<int>(_parameters.sieveWorkers), static_cast<int>(_primorialOffsets.size()));
logger.log("Threads: "s + std::to_string(_parameters.threads) + " ("s + std::to_string(_parameters.sieveWorkers) + " Sieve Worker(s))\n"s);
std::vector<uint64_t> cumulativeOffsets(_parameters.pattern.size(), 0);
std::partial_sum(_parameters.pattern.begin(), _parameters.pattern.end(), cumulativeOffsets.begin(), std::plus<uint64_t>());
logger.log("Constellation pattern: n + ("s + formatContainer(cumulativeOffsets) + "), length "s + std::to_string(_parameters.pattern.size()) + "\n"s);
if (_mode == "Search") {
if (_parameters.tupleLengthMin < 1 || _parameters.tupleLengthMin > _parameters.pattern.size())
_parameters.tupleLengthMin = std::max(1, static_cast<int>(_parameters.pattern.size()) - 1);
logger.log("Will show tuples of at least length "s + std::to_string(_parameters.tupleLengthMin) + "\n"s);
}
if (_parameters.primeTableLimit == 0) {
uint64_t primeTableLimitMax(2147483648ULL);
if (sysInfo.getPhysicalMemory() < 536870912ULL)
primeTableLimitMax = 67108864ULL;
else if (sysInfo.getPhysicalMemory() < 17179869184ULL)
primeTableLimitMax = sysInfo.getPhysicalMemory()/8ULL;
_parameters.primeTableLimit = std::pow(_difficultyAtInit, 6.)/std::pow(2., 3.*static_cast<double>(_parameters.pattern.size()) + 7.);
if (_parameters.threads > 16) {
_parameters.primeTableLimit *= 16;
_parameters.primeTableLimit /= static_cast<double>(_parameters.threads);
}
_parameters.primeTableLimit = std::min(_parameters.primeTableLimit, primeTableLimitMax);
}
logger.log("Prime Table Limit: "s + std::to_string(_parameters.primeTableLimit) + "\n"s);
std::transform(_parameters.pattern.begin(), _parameters.pattern.end(), std::back_inserter(_halfPattern), [](uint64_t n) {return n >> 1;});
std::vector<uint64_t> primes;
uint64_t primeTableFileBytes, savedPrimes(0), largestSavedPrime;
std::fstream file(primeTableFile);
if (file) {
file.seekg(0, std::ios::end);
primeTableFileBytes = file.tellg();
savedPrimes = primeTableFileBytes/sizeof(decltype(primes)::value_type);
if (savedPrimes > 0) {
file.seekg(-static_cast<int64_t>(sizeof(decltype(primes)::value_type)), std::ios::end);
file.read(reinterpret_cast<char*>(&largestSavedPrime), sizeof(decltype(primes)::value_type));
}
}
std::chrono::time_point<std::chrono::steady_clock> t0(std::chrono::steady_clock::now());
if (savedPrimes > 0 && _parameters.primeTableLimit >= 1048576 && _parameters.primeTableLimit <= largestSavedPrime) {
logger.log("Extracting prime numbers from "s + primeTableFile + " ("s + std::to_string(primeTableFileBytes) + " bytes, "s + std::to_string(savedPrimes) + " primes, largest "s + std::to_string(largestSavedPrime) + ")...\n"s);
uint64_t nPrimesUpperBound(std::min(1.085*static_cast<double>(_parameters.primeTableLimit)/std::log(static_cast<double>(_parameters.primeTableLimit)), static_cast<double>(savedPrimes))); // 1.085 = max(π(p)log(p)/p) for p >= 2^20
try {
primes = std::vector<uint64_t>(nPrimesUpperBound);
}
catch (std::bad_alloc& ba) {
logger.log("Unable to allocate memory for the prime table\n"s, MessageType::ERROR);
_suggestLessMemoryIntensiveOptions(_parameters.primeTableLimit/8, _parameters.sieveWorkers);
return;
}
file.seekg(0, std::ios::beg);
file.read(reinterpret_cast<char*>(primes.data()), nPrimesUpperBound*sizeof(decltype(primes)::value_type));
file.close();
for (auto i(primes.size() - 1) ; i > 0 ; i--) {
if (primes[i] <= _parameters.primeTableLimit) {
primes.resize(i + 1);
break;
}
}
logger.log(std::to_string(primes.size()) + " first primes extracted in "s + doubleToString(timeSince(t0)) + " s ("s + std::to_string(primes.size()*sizeof(decltype(primes)::value_type)) + " bytes).\n"s);
}
else {
logger.log("Generating prime table using sieve of Eratosthenes...\n"s);
try {
primes = generatePrimeTable(_parameters.primeTableLimit);
}
catch (std::bad_alloc& ba) {
logger.log("Unable to allocate memory for the prime table\n"s, MessageType::ERROR);
_suggestLessMemoryIntensiveOptions(_parameters.primeTableLimit/8, _parameters.sieveWorkers);
return;
}
logger.log("Table with all "s + std::to_string(primes.size()) + " first primes generated in "s + doubleToString(timeSince(t0)) + " s ("s + std::to_string(primes.size()*sizeof(decltype(primes)::value_type)) + " bytes)...\n"s);
}
if (primes.size() % 2 == 1) // Needs to be even to use SIMD sieving optimizations
primes.pop_back();
try {
_primes32.reserve(std::min(static_cast<decltype(_primes32)::value_type>(nPrimesTo2p32), static_cast<decltype(_primes32)::value_type>(primes.size())));
if (primes.size() > nPrimesTo2p32) _primes64.reserve(primes.size() - nPrimesTo2p32);
}
catch (std::bad_alloc& ba) {
logger.log("Unable to allocate memory for the prime table\n"s, MessageType::ERROR);
_suggestLessMemoryIntensiveOptions(_parameters.primeTableLimit/8, _parameters.sieveWorkers);
return;
}
for (size_t i = 0; i < primes.size(); ++i) {
if (primes[i] < (1ULL << 32)) _primes32.push_back(primes[i]);
else _primes64.push_back(primes[i]);
}
_nPrimes = primes.size();
_nPrimes32 = _primes32.size();
primes.clear();
if (_parameters.sieveBits == 0) {
if (sysInfo.getCpuArchitecture() == "x64")
_parameters.sieveBits = _parameters.sieveWorkers <= 4 ? 25 : 24;
else
_parameters.sieveBits = _parameters.sieveWorkers <= 4 ? 23 : 22;
}
_parameters.sieveSize = 1 << _parameters.sieveBits;
_parameters.sieveWords = _parameters.sieveSize/64;
logger.log("Sieve Size: 2^"s + std::to_string(_parameters.sieveBits) + " = "s + std::to_string(_parameters.sieveSize) + " ("s + std::to_string(_parameters.sieveWords) + " words)\n"s);
if (_parameters.sieveIterations == 0)
_parameters.sieveIterations = 16;
logger.log("Sieve Iterations: "s + std::to_string(_parameters.sieveIterations) + "\n"s);
_factorMax = _parameters.sieveIterations*_parameters.sieveSize;
logger.log("Primorial Factor Max: "s + std::to_string(_factorMax) + "\n"s);
uint32_t bitsForOffset;
// The primorial times the maximum factor should be smaller than the allowed limit for the target offset.
if (_mode == "Solo" || _mode == "Pool")
bitsForOffset = std::floor(static_cast<double>(_difficultyAtInit)/_parameters.restartDifficultyFactor - 265.); // 1 . leading 8 bits . hash (256 bits) . remaining bits for the offset, and some margin to take in account the Difficulty fluctuations
else if (_mode == "Search")
bitsForOffset = std::floor(_difficultyAtInit - 97.); // 1 . leading 16 bits . random 80 bits . remaining bits for the offset
else
bitsForOffset = std::floor(_difficultyAtInit - 81.); // 1 . leading 16 bits . constructed 64 bits . remaining bits for the offset
mpz_class primorialLimit(1);
primorialLimit <<= bitsForOffset;
primorialLimit /= u64ToMpz(_factorMax);
if (primorialLimit == 0) {
logger.log("The Difficulty is too low. Try to increase it or decrease the Sieve Size/Iterations.\n"s
"Available digits for the offsets: "s + std::to_string(bitsForOffset) + "\n"s, MessageType::ERROR);
return;
}
mpz_set_ui(_primorial.get_mpz_t(), 1);
for (uint64_t i(0) ; i < _primes32.size() ; i++) {
if (i == _parameters.primorialNumber && _parameters.primorialNumber != 0)
break;
else {
if (_primorial*_primes32[i] >= primorialLimit) {
if (_parameters.primorialNumber != 0)
logger.log("The provided Primorial Number "s + std::to_string(_parameters.primorialNumber) + " is too large and will be reduced.\n"s, MessageType::WARNING);
_parameters.primorialNumber = i;
break;
}
}
_primorial *= _primes32[i];
if (i + 1 == _primes32.size())
_parameters.primorialNumber = i + 1;
}
logger.log("Primorial Number: "s + std::to_string(_parameters.primorialNumber) + "\n"s);
logger.log("Primorial: p"s + std::to_string(_parameters.primorialNumber) + "# = "s + std::to_string(_primes32[_parameters.primorialNumber - 1]) + "# = "s);
if (mpz_sizeinbase(_primorial.get_mpz_t(), 10) < 18)
logger.log(_primorial.get_str());
else
logger.log("~"s + _primorial.get_str()[0] + "."s + _primorial.get_str().substr(1, 12) + "*10^"s + std::to_string(_primorial.get_str().size() - 1));
logger.log(" ("s + std::to_string(mpz_sizeinbase(_primorial.get_mpz_t(), 2)) + " bits)\n"s);
logger.log("Primorial Offsets: "s + std::to_string(_primorialOffsets.size()) + "\n"s);
_primorialOffsetDiff.resize(_parameters.sieveWorkers - 1);
const uint64_t constellationDiameter(cumulativeOffsets.back());
for (int j(1) ; j < _parameters.sieveWorkers ; j++)
_primorialOffsetDiff[j - 1] = _parameters.primorialOffsets[j] - _parameters.primorialOffsets[j - 1] - constellationDiameter;
uint64_t additionalFactorsCountEstimation(0); // tupleSize*factorMax*(sum of 1/p, for p in the prime table >= factorMax); it is the estimation of how many such p will eliminate a factor (factorMax/p being the probability of the modulo p being < factorMax)
double sumInversesOfPrimes(0.);
_primesIndexThreshold = 0; // Number of prime numbers smaller than factorMax in the table
for (uint64_t i(0) ; i < _nPrimes ; i++) {
const uint64_t p(_getPrime(i));
if (p >= _factorMax) {
if (_primesIndexThreshold == 0) {
_primesIndexThreshold = i;
if (_primesIndexThreshold % 2 == 1) // Needs to be even to use SIMD sieving optimizations
_primesIndexThreshold--;
}
sumInversesOfPrimes += 1./static_cast<double>(p);
}
}
if (_primesIndexThreshold == 0)
_primesIndexThreshold = _nPrimes;
logger.log("Prime index threshold: "s + std::to_string(_primesIndexThreshold) + "\n"s);
const uint64_t factorsToEliminateEntries(_parameters.pattern.size()*_primesIndexThreshold); // PatternLength entries for every prime < factorMax
additionalFactorsCountEstimation = _parameters.pattern.size()*ceil(static_cast<double>(_factorMax)*sumInversesOfPrimes);
const uint64_t additionalFactorsEntriesPerIteration(17ULL*(additionalFactorsCountEstimation/_parameters.sieveIterations)/16ULL + 64ULL); // Have some margin
logger.log("Estimated additional factors: "s + std::to_string(additionalFactorsCountEstimation) + " (allocated per iteration: " + std::to_string(additionalFactorsEntriesPerIteration) + ")\n"s);
{
#ifdef __SSE2__
logger.log("Precomputing modular inverses and division data...\n"s); // The precomputed data is used to speed up computations in _doPresieveTask.
#else
logger.log("Precomputing modular inverses...\n"s);
#endif
t0 = std::chrono::steady_clock::now();
#ifdef __SSE2__
const uint64_t precompPrimes(std::min(_nPrimes, 5586502348UL)); // Precomputation only works up to p = 2^37
#endif
try {
_modularInverses32.resize(_primes32.size());
_modularInverses64.resize(_primes64.size()); // Table of inverses of the primorial modulo a prime number in the table with index >= primorialNumber.
#ifdef __SSE2__
_modPrecompute.resize(precompPrimes);
#endif
}
catch (std::bad_alloc& ba) {
logger.log("Unable to allocate memory for the precomputed data\n"s, MessageType::ERROR);
_suggestLessMemoryIntensiveOptions(_parameters.primeTableLimit/4, _parameters.sieveWorkers);
return;
}
const uint64_t blockSize((_nPrimes - _parameters.primorialNumber + _parameters.threads - 1)/_parameters.threads);
std::thread threads[_parameters.threads];
for (uint16_t j(0) ; j < _parameters.threads ; j++) {
threads[j] = std::thread([&, j]() {
mpz_class modularInverse, prime;
const uint64_t endIndex(std::min(_parameters.primorialNumber + (j + 1)*blockSize, _nPrimes));
for (uint64_t i(_parameters.primorialNumber + j*blockSize) ; i < endIndex ; i++) {
uint64_t p(_getPrime(i));
mpz_set_ui(prime.get_mpz_t(), p);
mpz_invert(modularInverse.get_mpz_t(), _primorial.get_mpz_t(), prime.get_mpz_t()); // modularInverse*primorial ≡ 1 (mod prime)
if (i < nPrimesTo2p32) _modularInverses32[i] = static_cast<uint32_t>(mpz_get_ui(modularInverse.get_mpz_t()));
else _modularInverses64[i - nPrimesTo2p32] = mpz_get_ui(modularInverse.get_mpz_t());
#ifdef __SSE2__
if (i < precompPrimes)
rie_mod_1s_4p_cps(&_modPrecompute[i], p);
#endif
}
});
}
for (uint16_t j(0) ; j < _parameters.threads ; j++) threads[j].join();
#ifdef __SSE2__
logger.log("Tables of "s + std::to_string(_modularInverses32.size() + _modularInverses64.size() - _parameters.primorialNumber) + " modular inverses and "s + std::to_string(precompPrimes - _parameters.primorialNumber) + " division entries generated in "s + doubleToString(timeSince(t0)) + " s ("s + std::to_string((_modularInverses64.size() + precompPrimes)*sizeof(decltype(_modularInverses64)::value_type) + _modularInverses32.size()*sizeof(decltype(_modularInverses32)::value_type)) + " bytes).\n"s);
#else
logger.log("Tables of "s + std::to_string(_modularInverses32.size() + _modularInverses64.size() - _parameters.primorialNumber) + " modular inverses generated in "s + doubleToString(timeSince(t0)) + " s ("s + std::to_string(_modularInverses64.size()*sizeof(decltype(_modularInverses64)::value_type) + _modularInverses32.size()*sizeof(decltype(_modularInverses32)::value_type)) + " bytes).\n"s);
#endif
}
try {
std::vector<Sieve> sieves(_parameters.sieveWorkers);
_sieves.swap(sieves);
for (std::vector<Sieve>::size_type i(0) ; i < _sieves.size() ; i++) {
_sieves[i].id = i;
_sieves[i].additionalFactorsToEliminateCounts = new std::atomic<uint64_t>[_parameters.sieveIterations];
}
logger.log("Allocating "s + std::to_string(sizeof(uint64_t)*_parameters.sieveWorkers*_parameters.sieveWords) + " bytes for the primorial factors tables...\n"s);
for (auto &sieve : _sieves)
sieve.factorsTable = new uint64_t[_parameters.sieveWords];
}
catch (std::bad_alloc& ba) {
logger.log("Unable to allocate memory for the primorial factors tables\n"s, MessageType::ERROR);
_suggestLessMemoryIntensiveOptions(_parameters.primeTableLimit/3, _parameters.sieveWorkers);
return;
}
try {
logger.log("Allocating "s + std::to_string(sizeof(uint32_t)*_parameters.sieveWorkers*factorsToEliminateEntries) + " bytes for the primorial factors...\n"s);
for (auto &sieve : _sieves) {
#ifdef __SSE2__
sieve.factorsToEliminate = reinterpret_cast<uint32_t*>(new __m256i[(factorsToEliminateEntries + 7) / 8]);
#else
sieve.factorsToEliminate = new uint32_t[factorsToEliminateEntries];
#endif
memset(sieve.factorsToEliminate, 0, sizeof(uint32_t)*factorsToEliminateEntries);
}
}
catch (std::bad_alloc& ba) {
logger.log("Unable to allocate memory for the primorial factors\n"s, MessageType::ERROR);
_suggestLessMemoryIntensiveOptions(_parameters.primeTableLimit/2, std::max(static_cast<int>(_parameters.sieveWorkers) - 1, 1));
return;
}
try {
logger.log("Allocating "s + std::to_string(sizeof(uint32_t)*_parameters.sieveWorkers*_parameters.sieveIterations*additionalFactorsEntriesPerIteration) + " bytes for the additional primorial factors..\n"s);
for (auto &sieve : _sieves) {
sieve.additionalFactorsToEliminate = new uint32_t*[_parameters.sieveIterations];
for (uint64_t j(0) ; j < _parameters.sieveIterations ; j++)
sieve.additionalFactorsToEliminate[j] = new uint32_t[additionalFactorsEntriesPerIteration];
}
}
catch (std::bad_alloc& ba) {
logger.log("Unable to allocate memory for the additional primorial factors\n"s, MessageType::ERROR);
_suggestLessMemoryIntensiveOptions(2*_parameters.primeTableLimit/3, std::max(static_cast<int>(_parameters.sieveWorkers) - 1, 1));
return;
}
// Initial guess at a value for the threshold
_nRemainingCheckTasksThreshold = 32U*_parameters.threads*_parameters.sieveWorkers;
_inited = true;
logger.log("Done initializing miner.\n"s, MessageType::SUCCESS);
}
void Miner::startThreads() {
if (!_inited)
logger.log("The miner is not initialized!\n"s, MessageType::ERROR);
else if (_client == nullptr)
logger.log("The miner cannot start mining without a client!\n"s, MessageType::ERROR);
else if (_running)
logger.log("The miner is already running!\n"s, MessageType::ERROR);
else {
_running = true;
if (!_keepStats)
statManager.start(_parameters.pattern.size());
_keepStats = false;
logger.log("Starting the miner's master thread...\n"s);
_masterThread = std::thread(&Miner::_manageTasks, this);
logger.log("Starting " + std::to_string(_parameters.threads) + " miner's worker threads...\n"s);
for (uint16_t i(0) ; i < _parameters.threads ; i++)
_workerThreads.push_back(std::thread(&Miner::_doTasks, this, i));
logger.hr();
if (_mode == "Benchmark" || _mode == "Search")
logger.log(Stats::formattedTime(statManager.timeSinceStart()) + " Started "s + _mode + ", difficulty "s + doubleToString(_client->currentDifficulty(), 3U) + "\n"s, MessageType::BOLD);
else
logger.log(Stats::formattedClockTimeNow() + " Started mining at block "s + std::to_string(_client->currentHeight()) + ", difficulty "s + doubleToString(_client->currentDifficulty(), 3U) + "\n"s, MessageType::BOLD);
}
}
void Miner::stopThreads() {
if (!_running)
logger.log("The miner is already stopped!\n"s, MessageType::ERROR);
else {
_running = false;
if (_mode == "Benchmark" || _mode == "Search")
printTupleStats();
logger.log("Waiting for the miner's master thread to finish...\n"s);
_tasksDoneInfos.push_front(TaskDoneInfo{Task::Type::Dummy, {}}); // Unblock if master thread stuck in blocking_pop_front().
_masterThread.join();
logger.log("Waiting for the miner's worker threads to finish...\n"s);
for (uint16_t i(0) ; i < _parameters.threads ; i++)
_tasks.push_front(Task{Task::Type::Dummy, 0, {}}); // Unblock worker threads stuck in blocking_pop_front().
for (auto &workerThread : _workerThreads)
workerThread.join();
_workerThreads.clear();
logger.log("Miner threads stopped.\n"s, MessageType::SUCCESS);
_presieveTasks.clear();
_tasks.clear();
_tasksDoneInfos.clear();
for (auto &work : _works) work.clear();
}
}
void Miner::clear() {
if (_running)
logger.log("Cannot clear the miner while it is running!\n"s, MessageType::ERROR);
else if (!_inited)
logger.log("Cannot clear the miner if it is not initialized!\n"s, MessageType::ERROR);
else {
logger.log("Clearing miner's data...\n"s);
_inited = false;
for (auto &sieve : _sieves) {
delete[] sieve.factorsTable;
#ifdef __SSE2__
delete[] reinterpret_cast<__m256i*>(sieve.factorsToEliminate);
#else
delete[] sieve.factorsToEliminate;
#endif
for (uint64_t j(0) ; j < _parameters.sieveIterations ; j++)
delete[] sieve.additionalFactorsToEliminate[j];
delete[] sieve.additionalFactorsToEliminate;
delete[] sieve.additionalFactorsToEliminateCounts;
}
_sieves.clear();
_primes32.clear();
_primes64.clear();
_modularInverses32.clear();
_modularInverses64.clear();
#ifdef __SSE2__
_modPrecompute.clear();
#endif
_primorialOffsets.clear();
_halfPattern.clear();
_primorialOffsetDiff.clear();
_parameters = MinerParameters();
logger.log("Miner's data cleared.\n"s, MessageType::SUCCESS);
}
}
void Miner::_addCachedAdditionalFactorsToEliminate(Sieve& sieve, uint64_t *factorsCache, uint64_t *factorsCacheCounts, const int factorsCacheTotalCount) {
for (uint64_t i(0) ; i < _parameters.sieveIterations ; i++) // Initialize the counts for use as index and update the sieve's one
factorsCacheCounts[i] = sieve.additionalFactorsToEliminateCounts[i].fetch_add(factorsCacheCounts[i]);
for (int i(0) ; i < factorsCacheTotalCount ; i++) {
const uint64_t factor(factorsCache[i]),
sieveIteration(factor >> _parameters.sieveBits),
indexInFactorsTable(factorsCacheCounts[sieveIteration]);
sieve.additionalFactorsToEliminate[sieveIteration][indexInFactorsTable] = factor & (_parameters.sieveSize - 1); // factor % sieveSize
factorsCacheCounts[sieveIteration]++;
}
for (uint64_t i(0) ; i < _parameters.sieveIterations ; i++)
factorsCacheCounts[i] = 0;
}
void Miner::_doPresieveTask(const Task &task) {
const uint64_t workIndex(task.workIndex), firstPrimeIndex(task.presieve.start), lastPrimeIndex(task.presieve.end);
const mpz_class firstCandidate(_works[workIndex].primorialMultipleStart + _primorialOffsets[0]);
std::array<int, maxSieveWorkers> factorsCacheTotalCounts{0};
uint64_t** factorsCacheRef(factorsCache); // On Windows, caching these thread_local pointers on the stack makes a noticeable perf difference.
uint64_t** factorsCacheCountsRef(factorsCacheCounts);
#ifdef __SSE2__
const uint64_t precompLimit(_modPrecompute.size()), tupleSize(_parameters.pattern.size());
uint64_t avxLimit(0);
#ifdef __AVX2__
const uint64_t avxWidth(8);
#else
const uint64_t avxWidth(4);
#endif
if (sysInfo.hasAVX()) {
avxLimit = nPrimesTo2p32 - avxWidth;
avxLimit -= (avxLimit - firstPrimeIndex) & (avxWidth - 1); // Must be enough primes in range to use AVX
}
uint64_t nextRemainder[8];
uint64_t nextRemainderIndex(8);
#else
const uint64_t tupleSize(_parameters.pattern.size());
#endif
for (uint64_t i(firstPrimeIndex) ; i < lastPrimeIndex ; i++) {
const uint64_t p(_getPrime(i));
uint64_t mi[4];
mi[0] = _getModularInverse(i); // Modular inverse of the primorial: mi[0]*primorial ≡ 1 (mod p). The modularInverses were precomputed in init().
mi[1] = (mi[0] << 1); // mi[i] = (2*i*mi[0]) % p for i > 0.
if (mi[1] >= p) mi[1] -= p;
mi[2] = mi[1] << 1;
if (mi[2] >= p) mi[2] -= p;
mi[3] = mi[1] + mi[2];
if (mi[3] >= p) mi[3] -= p;
// Compute the first eliminated primorial factor for p fp, using precomputation speed up if available.
// fp is the solution of firstCandidate + primorial*f ≡ 0 (mod p) for 0 <= f < p: fp = (p - (firstCandidate % p))*mi[0] % p.
// In the sieving phase, numbers of the form firstCandidate + (p*i + fp)*primorial for 0 <= i < factorMax are eliminated as they are divisible by p.
// This is for the first number of the constellation. Later, the mi[1-3] will be used to adjust fp for the other elements of the constellation.
#ifdef __SSE2__
uint64_t fp, cnt(0ULL), ps(0ULL);
if (i < precompLimit) { // Assembly optimized computation of fp by Michael Bell
bool haveRemainder(false);
if (nextRemainderIndex < avxWidth) {
fp = nextRemainder[nextRemainderIndex++];
cnt = __builtin_clzll(p);
ps = p << cnt;
haveRemainder = true;
}
else if (i < avxLimit) {
cnt = __builtin_clz(static_cast<uint32_t>(p));
if (__builtin_clz(static_cast<uint32_t>(_primes32[i + avxWidth - 1])) == cnt) {
uint32_t ps32[8];
for (uint64_t j(0) ; j < avxWidth; j++) {
ps32[j] = static_cast<uint32_t>(_primes32[i + j]) << cnt;
nextRemainder[j] = _modularInverses32[i + j];
}
#ifdef __AVX2__
rie_mod_1s_2p_8times(firstCandidate.get_mpz_t()->_mp_d, firstCandidate.get_mpz_t()->_mp_size, &ps32[0], cnt, &_modPrecompute[i], &nextRemainder[0]);
#else
rie_mod_1s_2p_4times(firstCandidate.get_mpz_t()->_mp_d, firstCandidate.get_mpz_t()->_mp_size, &ps32[0], cnt, &_modPrecompute[i], &nextRemainder[0]);
#endif
haveRemainder = true;
fp = nextRemainder[0];
nextRemainderIndex = 1;
cnt += 32ULL;
ps = static_cast<uint64_t>(ps32[0]) << 32ULL;
}
}
if (!haveRemainder) {
cnt = __builtin_clzll(p);
ps = p << cnt;
const uint64_t remainder(rie_mod_1s_4p(firstCandidate.get_mpz_t()->_mp_d, firstCandidate.get_mpz_t()->_mp_size, ps, cnt, &_modPrecompute[i]));
const uint64_t pa(ps - remainder);
uint64_t r, n[2];
umul_ppmm(n[1], n[0], pa, mi[0]);
udiv_rnnd_preinv(r, n[1], n[0], ps, _modPrecompute[i]);
fp = r >> cnt;
}
}
else { // Basic computation of fp
const uint64_t remainder(mpz_tdiv_ui(firstCandidate.get_mpz_t(), p)), pa(p - remainder);
uint64_t q, n[2];
umul_ppmm(n[1], n[0], pa, mi[0]);
udiv_qrnnd(q, fp, n[1], n[0], p);
}
#else
const uint64_t remainder(mpz_tdiv_ui(firstCandidate.get_mpz_t(), p)), pa(p - remainder);
uint64_t fp(mulMod(pa, mi[0], p)); // (pa*mi[0]) % p
#endif
// We use a macro here to ensure the compiler inlines the code, and also make it easier to early
// out of the function completely if the current height has changed.
#define addFactorsToEliminateForP(sieveWorkerIndex) { \
if (i < _primesIndexThreshold) { \
_sieves[sieveWorkerIndex].factorsToEliminate[tupleSize*i] = fp; \
for (std::vector<uint64_t>::size_type f(1) ; f < _halfPattern.size() ; f++) { \
if (fp < mi[_halfPattern[f]]) fp += p; \
fp -= mi[_halfPattern[f]]; \
_sieves[sieveWorkerIndex].factorsToEliminate[tupleSize*i + f] = fp; \
} \
} \
else { \
if (factorsCacheTotalCounts[sieveWorkerIndex] + _halfPattern.size() >= factorsCacheSize) { \
if (_works[workIndex].job.height != _client->currentHeight()) \
return; \
_addCachedAdditionalFactorsToEliminate(_sieves[sieveWorkerIndex], factorsCacheRef[sieveWorkerIndex], factorsCacheCountsRef[sieveWorkerIndex], factorsCacheTotalCounts[sieveWorkerIndex]); \
factorsCacheTotalCounts[sieveWorkerIndex] = 0; \
} \
if (fp < _factorMax) { \
factorsCacheRef[sieveWorkerIndex][factorsCacheTotalCounts[sieveWorkerIndex]++] = fp; \
factorsCacheCountsRef[sieveWorkerIndex][fp >> _parameters.sieveBits]++; \
} \
for (std::vector<uint64_t>::size_type f(1) ; f < _halfPattern.size() ; f++) { \
if (fp < mi[_halfPattern[f]]) fp += p; \
fp -= mi[_halfPattern[f]]; \
if (fp < _factorMax) { \
factorsCacheRef[sieveWorkerIndex][factorsCacheTotalCounts[sieveWorkerIndex]++] = fp; \
factorsCacheCountsRef[sieveWorkerIndex][fp >> _parameters.sieveBits]++; \
} \
} \
} \
};
addFactorsToEliminateForP(0);
if (_parameters.sieveWorkers == 1) continue;
// Recompute fp to adjust to the PrimorialOffsets of other Sieve Workers.
#ifdef __SSE2__
uint64_t r;
#define recomputeFp(sieveWorkerIndex) { \
if (i < precompLimit && _primorialOffsetDiff[sieveWorkerIndex - 1] < p) { \
uint64_t n[2]; \
uint64_t os(_primorialOffsetDiff[sieveWorkerIndex - 1] << cnt); \
umul_ppmm(n[1], n[0], os, mi[0]); \
udiv_rnnd_preinv(r, n[1], n[0], ps, _modPrecompute[i]); \
r >>= cnt; \
} \
else { \
uint64_t q, n[2]; \
umul_ppmm(n[1], n[0], _primorialOffsetDiff[sieveWorkerIndex - 1], mi[0]); \
udiv_qrnnd(q, r, n[1], n[0], p); \
} \
}
recomputeFp(1);
#else
uint64_t r(mulMod(_primorialOffsetDiff[0], mi[0], p));
#endif
if (fp < r) fp += p;
fp -= r;
addFactorsToEliminateForP(1);
for (int j(2) ; j < _parameters.sieveWorkers ; j++) {
if (_primorialOffsetDiff[j - 1] != _primorialOffsetDiff[j - 2])
#ifdef __SSE2__
recomputeFp(j);
#else
r = mulMod(_primorialOffsetDiff[j - 1], mi[0], p);
#endif
if (fp < r) fp += p;
fp -= r;
addFactorsToEliminateForP(j);
}
}
if (lastPrimeIndex > _primesIndexThreshold) {
for (int j(0) ; j < _parameters.sieveWorkers ; j++) {
if (factorsCacheTotalCounts[j] > 0) {
_addCachedAdditionalFactorsToEliminate(_sieves[j], factorsCacheRef[j], factorsCacheCountsRef[j], factorsCacheTotalCounts[j]);
factorsCacheTotalCounts[j] = 0;
}
}
}
}
void Miner::_processSieve(uint64_t *factorsTable, uint32_t* factorsToEliminate, const uint64_t firstPrimeIndex, const uint64_t lastPrimeIndex) {
const uint64_t tupleSize(_parameters.pattern.size());
std::array<uint32_t, sieveCacheSize> sieveCache{0};
uint64_t sieveCachePos(0);
for (uint64_t i(firstPrimeIndex) ; i < lastPrimeIndex ; i++) {
const uint32_t p(_primes32[i]);
for (uint64_t f(0) ; f < tupleSize; f++) {
while (factorsToEliminate[i*tupleSize + f] < _parameters.sieveSize) { // Eliminate primorial factors of the form p*m + fp for every m*p in the current table.
_addToSieveCache(factorsTable, sieveCache, sieveCachePos, factorsToEliminate[i*tupleSize + f]);
factorsToEliminate[i*tupleSize + f] += p; // Increment the m
}
factorsToEliminate[i*tupleSize + f] -= _parameters.sieveSize; // Prepare for the next iteration
}
}
_endSieveCache(factorsTable, sieveCache);
}
#ifdef __SSE2__
void Miner::_processSieve6(uint64_t *factorsTable, uint32_t* factorsToEliminate, uint64_t firstPrimeIndex, const uint64_t lastPrimeIndex) { // Assembly optimized sieving for 6-tuples by Michael Bell
assert(_parameters.pattern.size() == 6);
assert((lastPrimeIndex & 1) == 0);
// Already eliminate for the first prime to sieve if it is odd to align for the optimizations
if ((firstPrimeIndex & 1) != 0) {
for (uint64_t f(0) ; f < 6 ; f++) {
while (factorsToEliminate[firstPrimeIndex*6 + f] < _parameters.sieveSize) {
factorsTable[factorsToEliminate[firstPrimeIndex*6 + f] >> 6U] |= (1ULL << ((factorsToEliminate[firstPrimeIndex*6 + f] & 63U)));
factorsToEliminate[firstPrimeIndex*6 + f] += _primes32[firstPrimeIndex];
}
factorsToEliminate[firstPrimeIndex*6 + f] -= _parameters.sieveSize;
}
firstPrimeIndex++;
}
xmmreg_t offsetmax;
offsetmax.m128 = _mm_set1_epi32(_parameters.sieveSize);
for (uint64_t i(firstPrimeIndex) ; i < lastPrimeIndex ; i += 2) {
xmmreg_t p1, p2, p3;
xmmreg_t factor1, factor2, factor3, nextIncr1, nextIncr2, nextIncr3;
xmmreg_t cmpres1, cmpres2, cmpres3;
p1.m128 = _mm_set1_epi32(_primes32[i]);
p3.m128 = _mm_set1_epi32(_primes32[i + 1]);
p2.m128 = _mm_castps_si128(_mm_shuffle_ps(_mm_castsi128_ps(p1.m128), _mm_castsi128_ps(p3.m128), _MM_SHUFFLE(0, 0, 0, 0)));
factor1.m128 = _mm_load_si128(reinterpret_cast<__m128i const*>(&factorsToEliminate[i*6 + 0]));
factor2.m128 = _mm_load_si128(reinterpret_cast<__m128i const*>(&factorsToEliminate[i*6 + 4]));
factor3.m128 = _mm_load_si128(reinterpret_cast<__m128i const*>(&factorsToEliminate[i*6 + 8]));
while (true) {
cmpres1.m128 = _mm_cmpgt_epi32(offsetmax.m128, factor1.m128);
cmpres2.m128 = _mm_cmpgt_epi32(offsetmax.m128, factor2.m128);
cmpres3.m128 = _mm_cmpgt_epi32(offsetmax.m128, factor3.m128);
const int mask1(_mm_movemask_epi8(cmpres1.m128));
const int mask2(_mm_movemask_epi8(cmpres2.m128));
const int mask3(_mm_movemask_epi8(cmpres3.m128));
if ((mask1 == 0) && (mask2 == 0) && (mask3 == 0)) break;
if (mask1 & 0x0008) factorsTable[factor1.v[0] >> 6] |= (1ULL << (factor1.v[0] & 63ULL));
if (mask1 & 0x0080) factorsTable[factor1.v[1] >> 6] |= (1ULL << (factor1.v[1] & 63ULL));
if (mask1 & 0x0800) factorsTable[factor1.v[2] >> 6] |= (1ULL << (factor1.v[2] & 63ULL));
if (mask1 & 0x8000) factorsTable[factor1.v[3] >> 6] |= (1ULL << (factor1.v[3] & 63ULL));
if (mask2 & 0x0008) factorsTable[factor2.v[0] >> 6] |= (1ULL << (factor2.v[0] & 63ULL));
if (mask2 & 0x0080) factorsTable[factor2.v[1] >> 6] |= (1ULL << (factor2.v[1] & 63ULL));
if (mask2 & 0x0800) factorsTable[factor2.v[2] >> 6] |= (1ULL << (factor2.v[2] & 63ULL));
if (mask2 & 0x8000) factorsTable[factor2.v[3] >> 6] |= (1ULL << (factor2.v[3] & 63ULL));
if (mask3 & 0x0008) factorsTable[factor3.v[0] >> 6] |= (1ULL << (factor3.v[0] & 63ULL));
if (mask3 & 0x0080) factorsTable[factor3.v[1] >> 6] |= (1ULL << (factor3.v[1] & 63ULL));
if (mask3 & 0x0800) factorsTable[factor3.v[2] >> 6] |= (1ULL << (factor3.v[2] & 63ULL));
if (mask3 & 0x8000) factorsTable[factor3.v[3] >> 6] |= (1ULL << (factor3.v[3] & 63ULL));
nextIncr1.m128 = _mm_and_si128(cmpres1.m128, p1.m128);
nextIncr2.m128 = _mm_and_si128(cmpres2.m128, p2.m128);
nextIncr3.m128 = _mm_and_si128(cmpres3.m128, p3.m128);
factor1.m128 = _mm_add_epi32(factor1.m128, nextIncr1.m128);
factor2.m128 = _mm_add_epi32(factor2.m128, nextIncr2.m128);
factor3.m128 = _mm_add_epi32(factor3.m128, nextIncr3.m128);
}
factor1.m128 = _mm_sub_epi32(factor1.m128, offsetmax.m128);
factor2.m128 = _mm_sub_epi32(factor2.m128, offsetmax.m128);
factor3.m128 = _mm_sub_epi32(factor3.m128, offsetmax.m128);
_mm_store_si128(reinterpret_cast<__m128i*>(&factorsToEliminate[i*6 + 0]), factor1.m128);
_mm_store_si128(reinterpret_cast<__m128i*>(&factorsToEliminate[i*6 + 4]), factor2.m128);
_mm_store_si128(reinterpret_cast<__m128i*>(&factorsToEliminate[i*6 + 8]), factor3.m128);
}
}
void Miner::_processSieve7(uint64_t *factorsTable, uint32_t* factorsToEliminate, uint64_t firstPrimeIndex, const uint64_t lastPrimeIndex) { // Assembly optimized sieving for 7-tuples by Michael Bell
assert(_parameters.pattern.size() == 7);
std::array<uint32_t, sieveCacheSize> sieveCache{0};
uint64_t sieveCachePos(0);
xmmreg_t offsetmax;
offsetmax.m128 = _mm_set1_epi32(_parameters.sieveSize);
for (uint64_t i(firstPrimeIndex) ; i < lastPrimeIndex ; i += 1) {
xmmreg_t p1;
xmmreg_t factor1, factor2, nextIncr1, nextIncr2;
xmmreg_t cmpres1, cmpres2;
p1.m128 = _mm_set1_epi32(_primes32[i]);
factor1.m128 = _mm_loadu_si128(reinterpret_cast<__m128i const*>(&factorsToEliminate[i*7 + 0]));
factor2.m128 = _mm_loadu_si128(reinterpret_cast<__m128i const*>(&factorsToEliminate[i*7 + 3]));
while (true) {
cmpres1.m128 = _mm_cmpgt_epi32(offsetmax.m128, factor1.m128);
cmpres2.m128 = _mm_cmpgt_epi32(offsetmax.m128, factor2.m128);
const int mask1(_mm_movemask_epi8(cmpres1.m128));
const int mask2(_mm_movemask_epi8(cmpres2.m128));
if ((mask1 == 0) && (mask2 == 0)) break;
if (mask1 & 0x0008) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor1.v[0]);
if (mask1 & 0x0080) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor1.v[1]);
if (mask1 & 0x0800) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor1.v[2]);
if (mask1 & 0x8000) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor1.v[3]);
if (mask2 & 0x0080) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor2.v[1]);
if (mask2 & 0x0800) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor2.v[2]);
if (mask2 & 0x8000) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor2.v[3]);
nextIncr1.m128 = _mm_and_si128(cmpres1.m128, p1.m128);
nextIncr2.m128 = _mm_and_si128(cmpres2.m128, p1.m128);
factor1.m128 = _mm_add_epi32(factor1.m128, nextIncr1.m128);
factor2.m128 = _mm_add_epi32(factor2.m128, nextIncr2.m128);
}
factor1.m128 = _mm_sub_epi32(factor1.m128, offsetmax.m128);
factor2.m128 = _mm_sub_epi32(factor2.m128, offsetmax.m128);
_mm_storeu_si128(reinterpret_cast<__m128i*>(&factorsToEliminate[i*7 + 0]), factor1.m128);
_mm_storeu_si128(reinterpret_cast<__m128i*>(&factorsToEliminate[i*7 + 3]), factor2.m128);
}
_endSieveCache(factorsTable, sieveCache);
}
void Miner::_processSieve8(uint64_t *factorsTable, uint32_t* factorsToEliminate, uint64_t firstPrimeIndex, const uint64_t lastPrimeIndex) { // Assembly optimized sieving for 8-tuples by Michael Bell
assert(_parameters.pattern.size() == 8);
std::array<uint32_t, sieveCacheSize> sieveCache{0};
uint64_t sieveCachePos(0);
xmmreg_t offsetmax;
offsetmax.m128 = _mm_set1_epi32(_parameters.sieveSize);
for (uint64_t i(firstPrimeIndex) ; i < lastPrimeIndex ; i += 1) {
xmmreg_t p1;
xmmreg_t factor1, factor2, nextIncr1, nextIncr2;
xmmreg_t cmpres1, cmpres2;
p1.m128 = _mm_set1_epi32(_primes32[i]);
factor1.m128 = _mm_load_si128(reinterpret_cast<__m128i const*>(&factorsToEliminate[i*8 + 0]));
factor2.m128 = _mm_load_si128(reinterpret_cast<__m128i const*>(&factorsToEliminate[i*8 + 4]));
while (true) {
cmpres1.m128 = _mm_cmpgt_epi32(offsetmax.m128, factor1.m128);
cmpres2.m128 = _mm_cmpgt_epi32(offsetmax.m128, factor2.m128);
const int mask1(_mm_movemask_epi8(cmpres1.m128));
const int mask2(_mm_movemask_epi8(cmpres2.m128));
if ((mask1 == 0) && (mask2 == 0)) break;
if (mask1 & 0x0008) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor1.v[0]);
if (mask1 & 0x0080) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor1.v[1]);
if (mask1 & 0x0800) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor1.v[2]);
if (mask1 & 0x8000) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor1.v[3]);
if (mask2 & 0x0008) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor2.v[0]);
if (mask2 & 0x0080) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor2.v[1]);
if (mask2 & 0x0800) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor2.v[2]);
if (mask2 & 0x8000) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor2.v[3]);
nextIncr1.m128 = _mm_and_si128(cmpres1.m128, p1.m128);
nextIncr2.m128 = _mm_and_si128(cmpres2.m128, p1.m128);
factor1.m128 = _mm_add_epi32(factor1.m128, nextIncr1.m128);
factor2.m128 = _mm_add_epi32(factor2.m128, nextIncr2.m128);
}
factor1.m128 = _mm_sub_epi32(factor1.m128, offsetmax.m128);
factor2.m128 = _mm_sub_epi32(factor2.m128, offsetmax.m128);
_mm_store_si128(reinterpret_cast<__m128i*>(&factorsToEliminate[i*8 + 0]), factor1.m128);
_mm_store_si128(reinterpret_cast<__m128i*>(&factorsToEliminate[i*8 + 4]), factor2.m128);
}
_endSieveCache(factorsTable, sieveCache);
}
#ifdef __AVX2__
void Miner::_processSieve7_avx2(uint64_t *factorsTable, uint32_t* factorsToEliminate, uint64_t firstPrimeIndex, const uint64_t lastPrimeIndex) { // Assembly optimized sieving for 7-tuples by Michael Bell
assert(_parameters.pattern.size() == 7);
std::array<uint32_t, sieveCacheSize> sieveCache{0};
uint64_t sieveCachePos(0);
assert((lastPrimeIndex & 1) == 0);
// Already eliminate for the first prime to sieve if it is odd to align for the optimizations
if ((firstPrimeIndex & 1) != 0) {
for (uint64_t f(0) ; f < 7 ; f++) {
while (factorsToEliminate[firstPrimeIndex*7 + f] < _parameters.sieveSize) {
_addToSieveCache(factorsTable, sieveCache, sieveCachePos, factorsToEliminate[firstPrimeIndex*7 + f]);
factorsToEliminate[firstPrimeIndex*7 + f] += _primes32[firstPrimeIndex];
}
factorsToEliminate[firstPrimeIndex*7 + f] -= _parameters.sieveSize;
}
firstPrimeIndex++;
}
ymmreg_t offsetmax;
offsetmax.m256 = _mm256_set1_epi32(_parameters.sieveSize);
ymmreg_t storemask;
storemask.m256 = _mm256_set1_epi32(0xffffffff);
storemask.v[0] = 0;
for (uint64_t i(firstPrimeIndex) ; i < lastPrimeIndex ; i += 2) {
ymmreg_t p1, p2;
ymmreg_t factor1, factor2, nextIncr1, nextIncr2;
ymmreg_t cmpres1, cmpres2;
p1.m256 = _mm256_set1_epi32(_primes32[i]);
p2.m256 = _mm256_set1_epi32(_primes32[i + 1]);
factor1.m256 = _mm256_loadu_si256(reinterpret_cast<__m256i const*>(&factorsToEliminate[i*7 + 0]));
factor2.m256 = _mm256_loadu_si256(reinterpret_cast<__m256i const*>(&factorsToEliminate[i*7 + 6]));
while (true) {
cmpres1.m256 = _mm256_cmpgt_epi32(offsetmax.m256, factor1.m256);
cmpres2.m256 = _mm256_cmpgt_epi32(offsetmax.m256, factor2.m256);
const int mask1(_mm256_movemask_epi8(cmpres1.m256));
const int mask2(_mm256_movemask_epi8(cmpres2.m256));
if ((mask1 == 0) && (mask2 == 0)) break;
if (mask1 & 0x00000008) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor1.v[0]);
if (mask1 & 0x00000080) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor1.v[1]);
if (mask1 & 0x00000800) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor1.v[2]);
if (mask1 & 0x00008000) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor1.v[3]);
if (mask1 & 0x00080000) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor1.v[4]);
if (mask1 & 0x00800000) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor1.v[5]);
if (mask1 & 0x08000000) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor1.v[6]);
if (mask2 & 0x00000080) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor2.v[1]);
if (mask2 & 0x00000800) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor2.v[2]);
if (mask2 & 0x00008000) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor2.v[3]);
if (mask2 & 0x00080000) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor2.v[4]);
if (mask2 & 0x00800000) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor2.v[5]);
if (mask2 & 0x08000000) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor2.v[6]);
if (mask2 & 0x80000000) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor2.v[7]);
nextIncr1.m256 = _mm256_and_si256(cmpres1.m256, p1.m256);
nextIncr2.m256 = _mm256_and_si256(cmpres2.m256, p2.m256);
factor1.m256 = _mm256_add_epi32(factor1.m256, nextIncr1.m256);
factor2.m256 = _mm256_add_epi32(factor2.m256, nextIncr2.m256);
}
factor1.m256 = _mm256_sub_epi32(factor1.m256, offsetmax.m256);
factor2.m256 = _mm256_sub_epi32(factor2.m256, offsetmax.m256);
_mm256_storeu_si256(reinterpret_cast<__m256i*>(&factorsToEliminate[i*7 + 0]), factor1.m256);
_mm256_maskstore_epi32(reinterpret_cast<int*>(&factorsToEliminate[i*7 + 6]), storemask.m256, factor2.m256);
}
_endSieveCache(factorsTable, sieveCache);
}
void Miner::_processSieve8_avx2(uint64_t *factorsTable, uint32_t* factorsToEliminate, uint64_t firstPrimeIndex, const uint64_t lastPrimeIndex) { // Assembly optimized sieving for 8-tuples by Michael Bell
assert(_parameters.pattern.size() == 8);
std::array<uint32_t, sieveCacheSize> sieveCache{0};
uint64_t sieveCachePos(0);
assert((lastPrimeIndex & 1) == 0);
// Already eliminate for the first prime to sieve if it is odd to align for the optimizations
if ((firstPrimeIndex & 1) != 0) {
for (uint64_t f(0) ; f < 8 ; f++) {
while (factorsToEliminate[firstPrimeIndex*8 + f] < _parameters.sieveSize) {
_addToSieveCache(factorsTable, sieveCache, sieveCachePos, factorsToEliminate[firstPrimeIndex*8 + f]);
factorsToEliminate[firstPrimeIndex*8 + f] += _primes32[firstPrimeIndex];
}
factorsToEliminate[firstPrimeIndex*8 + f] -= _parameters.sieveSize;
}
firstPrimeIndex++;
}
ymmreg_t offsetmax;
offsetmax.m256 = _mm256_set1_epi32(_parameters.sieveSize);
for (uint64_t i(firstPrimeIndex) ; i < lastPrimeIndex ; i += 2) {
ymmreg_t p1, p2;
ymmreg_t factor1, factor2, nextIncr1, nextIncr2;
ymmreg_t cmpres1, cmpres2;
p1.m256 = _mm256_set1_epi32(_primes32[i]);
p2.m256 = _mm256_set1_epi32(_primes32[i + 1]);
factor1.m256 = _mm256_load_si256(reinterpret_cast<__m256i const*>(&factorsToEliminate[i*8 + 0]));
factor2.m256 = _mm256_load_si256(reinterpret_cast<__m256i const*>(&factorsToEliminate[i*8 + 8]));
while (true) {
cmpres1.m256 = _mm256_cmpgt_epi32(offsetmax.m256, factor1.m256);
cmpres2.m256 = _mm256_cmpgt_epi32(offsetmax.m256, factor2.m256);
const int mask1(_mm256_movemask_epi8(cmpres1.m256));
const int mask2(_mm256_movemask_epi8(cmpres2.m256));
if ((mask1 == 0) && (mask2 == 0)) break;
if (mask1 & 0x00000008) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor1.v[0]);
if (mask1 & 0x00000080) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor1.v[1]);
if (mask1 & 0x00000800) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor1.v[2]);
if (mask1 & 0x00008000) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor1.v[3]);
if (mask1 & 0x00080000) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor1.v[4]);
if (mask1 & 0x00800000) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor1.v[5]);
if (mask1 & 0x08000000) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor1.v[6]);
if (mask1 & 0x80000000) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor1.v[7]);
if (mask2 & 0x00000008) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor2.v[0]);
if (mask2 & 0x00000080) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor2.v[1]);
if (mask2 & 0x00000800) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor2.v[2]);
if (mask2 & 0x00008000) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor2.v[3]);
if (mask2 & 0x00080000) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor2.v[4]);
if (mask2 & 0x00800000) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor2.v[5]);
if (mask2 & 0x08000000) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor2.v[6]);
if (mask2 & 0x80000000) _addToSieveCache(factorsTable, sieveCache, sieveCachePos, factor2.v[7]);
nextIncr1.m256 = _mm256_and_si256(cmpres1.m256, p1.m256);
nextIncr2.m256 = _mm256_and_si256(cmpres2.m256, p2.m256);
factor1.m256 = _mm256_add_epi32(factor1.m256, nextIncr1.m256);
factor2.m256 = _mm256_add_epi32(factor2.m256, nextIncr2.m256);
}
factor1.m256 = _mm256_sub_epi32(factor1.m256, offsetmax.m256);
factor2.m256 = _mm256_sub_epi32(factor2.m256, offsetmax.m256);
_mm256_store_si256(reinterpret_cast<__m256i*>(&factorsToEliminate[i*8 + 0]), factor1.m256);
_mm256_store_si256(reinterpret_cast<__m256i*>(&factorsToEliminate[i*8 + 8]), factor2.m256);
}
_endSieveCache(factorsTable, sieveCache);
}
#endif
#endif
void Miner::_doSieveTask(Task task) {
Sieve& sieve(_sieves[task.sieve.id]);
std::unique_lock<std::mutex> presieveLock(sieve.presieveLock, std::defer_lock);
const uint64_t workIndex(task.workIndex), sieveIteration(task.sieve.iteration), firstPrimeIndex(_parameters.primorialNumber);
std::array<uint32_t, sieveCacheSize> sieveCache{0};
uint64_t sieveCachePos(0);
Task checkTask{Task::Type::Check, workIndex, {}};
if (_works[workIndex].job.height != _client->currentHeight()) // Abort Sieve Task if new block (but count as Task done)
goto sieveEnd;
memset(sieve.factorsTable, 0, sizeof(uint64_t)*_parameters.sieveWords);
// Eliminate the p*i + fp factors (p < factorMax).
#ifdef __SSE2__
if (_parameters.pattern.size() == 6)
_processSieve6(sieve.factorsTable, sieve.factorsToEliminate, firstPrimeIndex, _primesIndexThreshold);
else if (_parameters.pattern.size() == 7)
#ifdef __AVX2__
_processSieve7_avx2(sieve.factorsTable, sieve.factorsToEliminate, firstPrimeIndex, _primesIndexThreshold);
#else
_processSieve7(sieve.factorsTable, sieve.factorsToEliminate, firstPrimeIndex, _primesIndexThreshold);
#endif
else if (_parameters.pattern.size() == 8)
#ifdef __AVX2__
_processSieve8_avx2(sieve.factorsTable, sieve.factorsToEliminate, firstPrimeIndex, _primesIndexThreshold);
#else
_processSieve8(sieve.factorsTable, sieve.factorsToEliminate, firstPrimeIndex, _primesIndexThreshold);
#endif
else
_processSieve(sieve.factorsTable, sieve.factorsToEliminate, firstPrimeIndex, _primesIndexThreshold);
#else
_processSieve(sieve.factorsTable, sieve.factorsToEliminate, firstPrimeIndex, _primesIndexThreshold);
#endif
if (_works[workIndex].job.height != _client->currentHeight())
goto sieveEnd;
// Wait for the presieve tasks that generate the additional factors to finish.
if (sieveIteration == 0) presieveLock.lock();
// Eliminate these factors.
for (uint64_t i(0), count(sieve.additionalFactorsToEliminateCounts[sieveIteration]); i < count ; i++)
_addToSieveCache(sieve.factorsTable, sieveCache, sieveCachePos, sieve.additionalFactorsToEliminate[sieveIteration][i]);
_endSieveCache(sieve.factorsTable, sieveCache);
if (_works[workIndex].job.height != _client->currentHeight())
goto sieveEnd;
checkTask.check.nCandidates = 0;
checkTask.check.offsetId = sieve.id;
checkTask.check.factorStart = sieveIteration*_parameters.sieveSize;
// Extract candidates from the sieve and create verify tasks of up to maxCandidatesPerCheckTask candidates.
for (uint32_t b(0) ; b < _parameters.sieveWords ; b++) {
uint64_t sieveWord(~sieve.factorsTable[b]); // ~ is the Bitwise Not: ones then indicate the candidates and zeros the previously eliminated numbers.
while (sieveWord != 0) {
const uint32_t nEliminatedUntilNext(__builtin_ctzll(sieveWord)), candidateIndex((b*64) + nEliminatedUntilNext); // __builtin_ctzll returns the number of leading 0s.
checkTask.check.factorOffsets[checkTask.check.nCandidates] = candidateIndex;
checkTask.check.nCandidates++;
if (checkTask.check.nCandidates == maxCandidatesPerCheckTask) {
if (_works[workIndex].job.height != _client->currentHeight()) // Low overhead but still often enough
goto sieveEnd;
_tasks.push_back(checkTask);
checkTask.check.nCandidates = 0;
_works[workIndex].nRemainingCheckTasks++;
}
sieveWord &= sieveWord - 1; // Change the candidate's bit from 1 to 0.
}
}
if (_works[workIndex].job.height != _client->currentHeight())
goto sieveEnd;
if (checkTask.check.nCandidates > 0) {