main.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. /*
  2. Copyright (c) 2018 tevador
  3. This file is part of RandomX.
  4. RandomX is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. RandomX is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with RandomX. If not, see<http://www.gnu.org/licenses/>.
  14. */
  15. //#define TRACE
  16. #include "InterpretedVirtualMachine.hpp"
  17. #include "CompiledVirtualMachine.hpp"
  18. #include "CompiledLightVirtualMachine.hpp"
  19. #include "AssemblyGeneratorX86.hpp"
  20. #include "Stopwatch.hpp"
  21. #include "blake2/blake2.h"
  22. #include "blake2/endian.h"
  23. #include <fstream>
  24. #include <iostream>
  25. #include <iomanip>
  26. #include <exception>
  27. #include <cstring>
  28. #include "Program.hpp"
  29. #include <string>
  30. #include <thread>
  31. #include <atomic>
  32. #include "dataset.hpp"
  33. #include "Cache.hpp"
  34. #include "hashAes1Rx4.hpp"
  35. #include "superscalarGenerator.hpp"
  36. #include "JitCompilerX86.hpp"
  37. const uint8_t seed[32] = { 191, 182, 222, 175, 249, 89, 134, 104, 241, 68, 191, 62, 162, 166, 61, 64, 123, 191, 227, 193, 118, 60, 188, 53, 223, 133, 175, 24, 123, 230, 55, 74 };
  38. const uint8_t blockTemplate__[] = {
  39. 0x07, 0x07, 0xf7, 0xa4, 0xf0, 0xd6, 0x05, 0xb3, 0x03, 0x26, 0x08, 0x16, 0xba, 0x3f, 0x10, 0x90, 0x2e, 0x1a, 0x14,
  40. 0x5a, 0xc5, 0xfa, 0xd3, 0xaa, 0x3a, 0xf6, 0xea, 0x44, 0xc1, 0x18, 0x69, 0xdc, 0x4f, 0x85, 0x3f, 0x00, 0x2b, 0x2e,
  41. 0xea, 0x00, 0x00, 0x00, 0x00, 0x77, 0xb2, 0x06, 0xa0, 0x2c, 0xa5, 0xb1, 0xd4, 0xce, 0x6b, 0xbf, 0xdf, 0x0a, 0xca,
  42. 0xc3, 0x8b, 0xde, 0xd3, 0x4d, 0x2d, 0xcd, 0xee, 0xf9, 0x5c, 0xd2, 0x0c, 0xef, 0xc1, 0x2f, 0x61, 0xd5, 0x61, 0x09
  43. };
  44. void dump(const char* buffer, uint64_t count, const char* name) {
  45. std::ofstream fout(name, std::ios::out | std::ios::binary);
  46. fout.write(buffer, count);
  47. fout.close();
  48. }
  49. constexpr char hexmap[] = "0123456789abcdef";
  50. void outputHex(std::ostream& os, const char* data, int length) {
  51. for (int i = 0; i < length; ++i) {
  52. os << hexmap[(data[i] & 0xF0) >> 4];
  53. os << hexmap[data[i] & 0x0F];
  54. }
  55. }
  56. void readOption(const char* option, int argc, char** argv, bool& out) {
  57. for (int i = 0; i < argc; ++i) {
  58. if (strcmp(argv[i], option) == 0) {
  59. out = true;
  60. return;
  61. }
  62. }
  63. out = false;
  64. }
  65. void readIntOption(const char* option, int argc, char** argv, int& out, int defaultValue) {
  66. for (int i = 0; i < argc - 1; ++i) {
  67. if (strcmp(argv[i], option) == 0 && (out = atoi(argv[i + 1])) > 0) {
  68. return;
  69. }
  70. }
  71. out = defaultValue;
  72. }
  73. void readInt(int argc, char** argv, int& out, int defaultValue) {
  74. for (int i = 0; i < argc; ++i) {
  75. if (*argv[i] != '-' && (out = atoi(argv[i])) > 0) {
  76. return;
  77. }
  78. }
  79. out = defaultValue;
  80. }
  81. class AtomicHash {
  82. public:
  83. AtomicHash() {
  84. for (int i = 0; i < 4; ++i)
  85. hash[i].store(0);
  86. }
  87. void xorWith(uint64_t update[4]) {
  88. for (int i = 0; i < 4; ++i)
  89. hash[i].fetch_xor(update[i]);
  90. }
  91. void print(std::ostream& os) {
  92. for (int i = 0; i < 4; ++i)
  93. print(hash[i], os);
  94. os << std::endl;
  95. }
  96. private:
  97. static void print(std::atomic<uint64_t>& hash, std::ostream& os) {
  98. auto h = hash.load();
  99. outputHex(std::cout, (char*)&h, sizeof(h));
  100. }
  101. std::atomic<uint64_t> hash[4];
  102. };
  103. void printUsage(const char* executable) {
  104. std::cout << "Usage: " << executable << " [OPTIONS]" << std::endl;
  105. std::cout << "Supported options:" << std::endl;
  106. std::cout << " --help shows this message" << std::endl;
  107. std::cout << " --mine mining mode: 2 GiB, x86-64 JIT compiled VM" << std::endl;
  108. std::cout << " --verify verification mode: 256 MiB" << std::endl;
  109. std::cout << " --jit x86-64 JIT compiled verification mode (default: interpreter)" << std::endl;
  110. std::cout << " --largePages use large pages" << std::endl;
  111. std::cout << " --softAes use software AES (default: x86 AES-NI)" << std::endl;
  112. std::cout << " --threads T use T threads (default: 1)" << std::endl;
  113. std::cout << " --init Q initialize dataset with Q threads (default: 1)" << std::endl;
  114. std::cout << " --nonces N run N nonces (default: 1000)" << std::endl;
  115. std::cout << " --genAsm generate x86-64 asm code for nonce N" << std::endl;
  116. std::cout << " --genNative generate RandomX code for nonce N" << std::endl;
  117. }
  118. template<bool softAes>
  119. void generateAsm(uint32_t nonce) {
  120. alignas(16) uint64_t hash[8];
  121. uint8_t blockTemplate[sizeof(blockTemplate__)];
  122. memcpy(blockTemplate, blockTemplate__, sizeof(blockTemplate));
  123. store32(blockTemplate + 39, nonce);
  124. blake2b(hash, sizeof(hash), blockTemplate, sizeof(blockTemplate), nullptr, 0);
  125. uint8_t scratchpad[RANDOMX_SCRATCHPAD_L3];
  126. fillAes1Rx4<softAes>((void*)hash, RANDOMX_SCRATCHPAD_L3, scratchpad);
  127. RandomX::AssemblyGeneratorX86 asmX86;
  128. RandomX::Program p;
  129. fillAes1Rx4<softAes>(hash, sizeof(p), &p);
  130. asmX86.generateProgram(p);
  131. asmX86.printCode(std::cout);
  132. }
  133. template<bool softAes>
  134. void generateNative(uint32_t nonce) {
  135. alignas(16) uint64_t hash[8];
  136. uint8_t blockTemplate[sizeof(blockTemplate__)];
  137. memcpy(blockTemplate, blockTemplate__, sizeof(blockTemplate));
  138. store32(blockTemplate + 39, nonce);
  139. blake2b(hash, sizeof(hash), blockTemplate, sizeof(blockTemplate), nullptr, 0);
  140. uint8_t scratchpad[RANDOMX_SCRATCHPAD_L3];
  141. fillAes1Rx4<softAes>((void*)hash, RANDOMX_SCRATCHPAD_L3, scratchpad);
  142. alignas(16) RandomX::Program prog;
  143. fillAes1Rx4<softAes>((void*)hash, sizeof(prog), &prog);
  144. for (int i = 0; i < RANDOMX_PROGRAM_SIZE; ++i) {
  145. prog(i).dst %= 8;
  146. prog(i).src %= 8;
  147. }
  148. std::cout << prog << std::endl;
  149. }
  150. template<bool softAes>
  151. void mine(RandomX::VirtualMachine* vm, std::atomic<uint32_t>& atomicNonce, AtomicHash& result, uint32_t noncesCount, int thread, uint8_t* scratchpad) {
  152. alignas(16) uint64_t hash[8];
  153. uint8_t blockTemplate[sizeof(blockTemplate__)];
  154. memcpy(blockTemplate, blockTemplate__, sizeof(blockTemplate));
  155. void* noncePtr = blockTemplate + 39;
  156. auto nonce = atomicNonce.fetch_add(1);
  157. while (nonce < noncesCount) {
  158. //std::cout << "Thread " << thread << " nonce " << nonce << std::endl;
  159. store32(noncePtr, nonce);
  160. blake2b(hash, sizeof(hash), blockTemplate, sizeof(blockTemplate), nullptr, 0);
  161. fillAes1Rx4<softAes>((void*)hash, RANDOMX_SCRATCHPAD_L3, scratchpad);
  162. //dump((char*)scratchpad, RANDOMX_SCRATCHPAD_L3, "spad-before.txt");
  163. vm->resetRoundingMode();
  164. vm->setScratchpad(scratchpad);
  165. for (int chain = 0; chain < RANDOMX_PROGRAM_COUNT - 1; ++chain) {
  166. fillAes1Rx4<softAes>((void*)hash, sizeof(RandomX::Program), vm->getProgramBuffer());
  167. vm->initialize();
  168. vm->execute();
  169. vm->getResult<false>(nullptr, 0, hash);
  170. }
  171. fillAes1Rx4<softAes>((void*)hash, sizeof(RandomX::Program), vm->getProgramBuffer());
  172. vm->initialize();
  173. vm->execute();
  174. /*if (RandomX::trace) {
  175. for (int j = 0; j < RandomX::ProgramLength; ++j) {
  176. uint64_t res = *(uint64_t*)(scratchpad + 8 * (RandomX::ProgramLength - 1 - j));
  177. std::cout << std::hex << std::setw(16) << std::setfill('0') << res << std::endl;
  178. }
  179. }*/
  180. vm->getResult<softAes>(scratchpad, RANDOMX_SCRATCHPAD_L3, hash);
  181. //dump((char*)scratchpad, RANDOMX_SCRATCHPAD_L3, "spad-after.txt");
  182. result.xorWith(hash);
  183. if (RandomX::trace) {
  184. std::cout << "Nonce: " << nonce << " ";
  185. outputHex(std::cout, (char*)hash, 16);
  186. std::cout << std::endl;
  187. }
  188. nonce = atomicNonce.fetch_add(1);
  189. }
  190. }
  191. int main(int argc, char** argv) {
  192. bool softAes, genAsm, miningMode, verificationMode, help, largePages, async, genNative, jit, genSuperscalar, legacy;
  193. int programCount, threadCount, initThreadCount, epoch;
  194. readOption("--softAes", argc, argv, softAes);
  195. readOption("--genAsm", argc, argv, genAsm);
  196. readOption("--mine", argc, argv, miningMode);
  197. readOption("--verify", argc, argv, verificationMode);
  198. readIntOption("--threads", argc, argv, threadCount, 1);
  199. readIntOption("--nonces", argc, argv, programCount, 1000);
  200. readIntOption("--init", argc, argv, initThreadCount, 1);
  201. readIntOption("--epoch", argc, argv, epoch, 0);
  202. readOption("--largePages", argc, argv, largePages);
  203. readOption("--jit", argc, argv, jit);
  204. readOption("--genNative", argc, argv, genNative);
  205. readOption("--help", argc, argv, help);
  206. readOption("--genSuperscalar", argc, argv, genSuperscalar);
  207. readOption("--legacy", argc, argv, legacy);
  208. if (genSuperscalar) {
  209. RandomX::SuperscalarProgram p;
  210. RandomX::Blake2Generator gen(seed, programCount);
  211. RandomX::generateSuperscalar(p, gen);
  212. RandomX::AssemblyGeneratorX86 asmX86;
  213. asmX86.generateAsm(p);
  214. //std::ofstream file("lightProg2.asm");
  215. asmX86.printCode(std::cout);
  216. return 0;
  217. }
  218. if (genAsm) {
  219. if (softAes)
  220. generateAsm<true>(programCount);
  221. else
  222. generateAsm<false>(programCount);
  223. return 0;
  224. }
  225. if (genNative) {
  226. if (softAes)
  227. generateNative<true>(programCount);
  228. else
  229. generateNative<false>(programCount);
  230. return 0;
  231. }
  232. if (help || (!miningMode && !verificationMode)) {
  233. printUsage(argv[0]);
  234. return 0;
  235. }
  236. if (softAes)
  237. std::cout << "Using software AES." << std::endl;
  238. std::atomic<uint32_t> atomicNonce(0);
  239. AtomicHash result;
  240. std::vector<RandomX::VirtualMachine*> vms;
  241. std::vector<std::thread> threads;
  242. RandomX::dataset_t dataset;
  243. const uint64_t cacheSize = (RANDOMX_ARGON_MEMORY + RANDOMX_ARGON_GROWTH * epoch) * RandomX::ArgonBlockSize;
  244. const uint64_t datasetSize = (RANDOMX_DATASET_SIZE + RANDOMX_DS_GROWTH * epoch);
  245. dataset.cache.size = cacheSize;
  246. RandomX::SuperscalarProgram programs[RANDOMX_CACHE_ACCESSES];
  247. std::cout << "RandomX - " << (miningMode ? "mining" : "verification") << " mode" << std::endl;
  248. std::cout << "Initializing";
  249. if(miningMode)
  250. std::cout << " (" << initThreadCount << " thread" << (initThreadCount > 1 ? "s)" : ")");
  251. std::cout << " ..." << std::endl;
  252. try {
  253. Stopwatch sw(true);
  254. RandomX::datasetInitCache(seed, dataset, largePages);
  255. if (RandomX::trace) {
  256. std::cout << "Cache: " << std::endl;
  257. outputHex(std::cout, (char*)dataset.cache.memory, sizeof(__m128i));
  258. std::cout << std::endl;
  259. }
  260. if (!legacy) {
  261. RandomX::Blake2Generator gen(seed, programCount);
  262. for (int i = 0; i < RANDOMX_CACHE_ACCESSES; ++i) {
  263. RandomX::generateSuperscalar(programs[i], gen);
  264. }
  265. }
  266. if (!miningMode) {
  267. std::cout << "Cache (" << cacheSize << " bytes) initialized in " << sw.getElapsed() << " s" << std::endl;
  268. }
  269. else {
  270. auto cache = dataset.cache;
  271. dataset.dataset.size = datasetSize;
  272. RandomX::datasetAlloc(dataset, largePages);
  273. const uint64_t datasetBlockCount = datasetSize / RandomX::CacheLineSize;
  274. if (!legacy) {
  275. RandomX::JitCompilerX86 jit86;
  276. jit86.generateSuperScalarHash(programs);
  277. RandomX::DatasetInitFunc dsfunc = jit86.getDatasetInitFunc();
  278. if (initThreadCount > 1) {
  279. auto perThread = datasetBlockCount / initThreadCount;
  280. auto remainder = datasetBlockCount % initThreadCount;
  281. uint32_t startBlock = 0;
  282. uint32_t endBlock = 0;
  283. for (int i = 0; i < initThreadCount; ++i) {
  284. auto count = perThread + (i == initThreadCount - 1 ? remainder : 0);
  285. endBlock += count;
  286. threads.push_back(std::thread(dsfunc, cache.memory, dataset.dataset.memory + startBlock * RandomX::CacheLineSize, startBlock, endBlock));
  287. startBlock += count;
  288. }
  289. for (unsigned i = 0; i < threads.size(); ++i) {
  290. threads[i].join();
  291. }
  292. }
  293. else {
  294. dsfunc(cache.memory, dataset.dataset.memory, 0, datasetBlockCount);
  295. }
  296. //dump((const char*)dataset.dataset.memory, RANDOMX_DATASET_SIZE, "dataset.dat");
  297. }
  298. else {
  299. if (initThreadCount > 1) {
  300. auto perThread = datasetBlockCount / initThreadCount;
  301. auto remainder = datasetBlockCount % initThreadCount;
  302. for (int i = 0; i < initThreadCount; ++i) {
  303. auto count = perThread + (i == initThreadCount - 1 ? remainder : 0);
  304. threads.push_back(std::thread(&RandomX::datasetInit, std::ref(cache), std::ref(dataset.dataset), i * perThread, count));
  305. }
  306. for (unsigned i = 0; i < threads.size(); ++i) {
  307. threads[i].join();
  308. }
  309. }
  310. else {
  311. RandomX::datasetInit(cache, dataset.dataset, 0, datasetBlockCount);
  312. }
  313. }
  314. RandomX::deallocCache(cache, largePages);
  315. threads.clear();
  316. std::cout << "Dataset (" << datasetSize << " bytes) initialized in " << sw.getElapsed() << " s" << std::endl;
  317. }
  318. std::cout << "Initializing " << threadCount << " virtual machine(s) ..." << std::endl;
  319. for (int i = 0; i < threadCount; ++i) {
  320. RandomX::VirtualMachine* vm;
  321. if (miningMode) {
  322. vm = new RandomX::CompiledVirtualMachine();
  323. }
  324. else {
  325. if (jit && !legacy)
  326. vm = new RandomX::CompiledLightVirtualMachine<true>();
  327. else if (jit)
  328. vm = new RandomX::CompiledLightVirtualMachine<false>();
  329. else if (!legacy)
  330. vm = new RandomX::InterpretedVirtualMachine<true>(softAes);
  331. else
  332. vm = new RandomX::InterpretedVirtualMachine<false>(softAes);
  333. }
  334. vm->setDataset(dataset, datasetSize, programs);
  335. vms.push_back(vm);
  336. }
  337. uint8_t* scratchpadMem;
  338. if (largePages) {
  339. scratchpadMem = (uint8_t*)allocLargePagesMemory(threadCount * RANDOMX_SCRATCHPAD_L3);
  340. }
  341. else {
  342. scratchpadMem = (uint8_t*)_mm_malloc(threadCount * RANDOMX_SCRATCHPAD_L3, RandomX::CacheLineSize);
  343. }
  344. std::cout << "Running benchmark (" << programCount << " nonces) ..." << std::endl;
  345. sw.restart();
  346. if (threadCount > 1) {
  347. for (unsigned i = 0; i < vms.size(); ++i) {
  348. if (softAes)
  349. threads.push_back(std::thread(&mine<true>, vms[i], std::ref(atomicNonce), std::ref(result), programCount, i, scratchpadMem + RANDOMX_SCRATCHPAD_L3 * i));
  350. else
  351. threads.push_back(std::thread(&mine<false>, vms[i], std::ref(atomicNonce), std::ref(result), programCount, i, scratchpadMem + RANDOMX_SCRATCHPAD_L3 * i));
  352. }
  353. for (unsigned i = 0; i < threads.size(); ++i) {
  354. threads[i].join();
  355. }
  356. }
  357. else {
  358. if(softAes)
  359. mine<true>(vms[0], std::ref(atomicNonce), std::ref(result), programCount, 0, scratchpadMem);
  360. else
  361. mine<false>(vms[0], std::ref(atomicNonce), std::ref(result), programCount, 0, scratchpadMem);
  362. /*if (miningMode)
  363. std::cout << "Average program size: " << ((RandomX::CompiledVirtualMachine*)vms[0])->getTotalSize() / programCount / RandomX::ChainLength << std::endl;*/
  364. }
  365. double elapsed = sw.getElapsed();
  366. std::cout << "Calculated result: ";
  367. result.print(std::cout);
  368. if(!legacy && programCount == 1000)
  369. std::cout << "Reference result: af72d8069bd95ef04b414d3a83772c7bd2df454940bad15ae0b48543aeef8ab2" << std::endl;
  370. if (!miningMode) {
  371. std::cout << "Performance: " << 1000 * elapsed / programCount << " ms per hash" << std::endl;
  372. }
  373. else {
  374. std::cout << "Performance: " << programCount / elapsed << " hashes per second" << std::endl;
  375. }
  376. }
  377. catch (std::exception& e) {
  378. std::cout << "ERROR: " << e.what() << std::endl;
  379. return 1;
  380. }
  381. return 0;
  382. }