From 18a48e11d26ed1f3c1ed37154a6b3d5873317bd8 Mon Sep 17 00:00:00 2001 From: psychocrypt Date: Sun, 24 Sep 2017 20:04:19 +0200 Subject: [PATCH] add cpu backend - move needed files from root to backend folder --- backend/cpu/autoAdjust.hpp | 173 +++++++++++ backend/cpu/autoAdjustHwloc.hpp | 211 +++++++++++++ backend/cpu/config.tpl | 90 ++++++ backend/cpu/jconf.cpp | 347 ++++++++++++++++++++++ backend/cpu/jconf.h | 59 ++++ backend/cpu/minethd.cpp | 506 ++++++++++++++++++++++++++++++++ backend/cpu/minethd.h | 74 +++++ 7 files changed, 1460 insertions(+) create mode 100644 backend/cpu/autoAdjust.hpp create mode 100644 backend/cpu/autoAdjustHwloc.hpp create mode 100644 backend/cpu/config.tpl create mode 100644 backend/cpu/jconf.cpp create mode 100644 backend/cpu/jconf.h create mode 100644 backend/cpu/minethd.cpp create mode 100644 backend/cpu/minethd.h diff --git a/backend/cpu/autoAdjust.hpp b/backend/cpu/autoAdjust.hpp new file mode 100644 index 0000000..67a2142 --- /dev/null +++ b/backend/cpu/autoAdjust.hpp @@ -0,0 +1,173 @@ +#pragma once +#include "jconf.h" +#include "../../console.h" +#include "../../ConfigEditor.hpp" +#include + +#ifdef _WIN32 +#include +#else +#include +#endif // _WIN32 + + +namespace xmrstak +{ +namespace cpu +{ +// Mask bits between h and l and return the value +// This enables us to put in values exactly like in the manual +// For example EBX[31:22] is get_masked(cpu_info[1], 31, 22) +inline int32_t get_masked(int32_t val, int32_t h, int32_t l) +{ + val &= (0x7FFFFFFF >> (31-(h-l))) << l; + return val >> l; +} + +class autoAdjust +{ +public: + + autoAdjust() + { + } + + bool printConfig() + { + + ConfigEditor configTpl{}; + + // load the template of the backend config into a char variable + const char *tpl = + #include "./config.tpl" + ; + configTpl.set( std::string(tpl) ); + + std::string conf; + conf += std::string("\"cpu_threads_conf\" :\n[\n"); + + if(!detectL3Size() || L3KB_size < 1024 || L3KB_size > 102400) + { + if(L3KB_size < 1024 || L3KB_size > 102400) + printer::inst()->print_msg(L0, "Autoconf failed: L3 size sanity check failed - %u KB.", L3KB_size); + + conf += std::string(" { \"low_power_mode\" : false, \"no_prefetch\" : true, \"affine_to_cpu\" : false },\n"); + printer::inst()->print_msg(L0, "Autoconf FAILED. Create config for a single thread. Please try to add new ones until the hashrate slows down."); + } + else + { + printer::inst()->print_msg(L0, "Autoconf L3 size detected at %u KB.", L3KB_size); + + detectCPUConf(); + + printer::inst()->print_msg(L0, "Autoconf core count detected as %u on %s.", corecnt, + linux_layout ? "Linux" : "Windows"); + + uint32_t aff_id = 0; + for(uint32_t i=0; i < corecnt; i++) + { + bool double_mode; + + if(L3KB_size <= 0) + break; + + double_mode = L3KB_size / 2048 > (int32_t)(corecnt-i); + + conf += std::string(" { \"low_power_mode\" : "); + conf += std::string(double_mode ? "true" : "false"); + conf += std::string(", \"no_prefetch\" : true, \"affine_to_cpu\" : "); + conf += std::to_string(aff_id); + conf += std::string(" },\n"); + + if(!linux_layout || old_amd) + { + aff_id += 2; + + if(aff_id >= corecnt) + aff_id = 1; + } + else + aff_id++; + + if(double_mode) + L3KB_size -= 4096; + else + L3KB_size -= 2048; + } + } + + conf += std::string("],\n\n"); + + configTpl.replace("CPUCONFIG",conf); + configTpl.write("cpu.txt"); + printer::inst()->print_msg(L0, "CPU configuration stored in file '%s'", "cpu.txt"); + + return true; + } + +private: + bool detectL3Size() + { + int32_t cpu_info[4]; + char cpustr[13] = {0}; + + xmrstak::cpu::jconf::cpuid(0, 0, cpu_info); + memcpy(cpustr, &cpu_info[1], 4); + memcpy(cpustr+4, &cpu_info[3], 4); + memcpy(cpustr+8, &cpu_info[2], 4); + + if(strcmp(cpustr, "GenuineIntel") == 0) + { + xmrstak::cpu::jconf::cpuid(4, 3, cpu_info); + + if(get_masked(cpu_info[0], 7, 5) != 3) + { + printer::inst()->print_msg(L0, "Autoconf failed: Couln't find L3 cache page."); + return false; + } + + L3KB_size = ((get_masked(cpu_info[1], 31, 22) + 1) * (get_masked(cpu_info[1], 21, 12) + 1) * + (get_masked(cpu_info[1], 11, 0) + 1) * (cpu_info[2] + 1)) / 1024; + + return true; + } + else if(strcmp(cpustr, "AuthenticAMD") == 0) + { + xmrstak::cpu::jconf::cpuid(0x80000006, 0, cpu_info); + + L3KB_size = get_masked(cpu_info[3], 31, 18) * 512; + + xmrstak::cpu::jconf::cpuid(1, 0, cpu_info); + if(get_masked(cpu_info[0], 11, 8) < 0x17) //0x17h is Zen + old_amd = true; + + return true; + } + else + { + printer::inst()->print_msg(L0, "Autoconf failed: Unknown CPU type: %s.", cpustr); + return false; + } + } + + void detectCPUConf() + { +#ifdef _WIN32 + SYSTEM_INFO info; + GetSystemInfo(&info); + corecnt = info.dwNumberOfProcessors; + linux_layout = false; +#else + corecnt = sysconf(_SC_NPROCESSORS_ONLN); + linux_layout = true; +#endif // _WIN32 + } + + int32_t L3KB_size = 0; + uint32_t corecnt; + bool old_amd = false; + bool linux_layout; +}; + +} // namespace cpu +} // namepsace xmrstak diff --git a/backend/cpu/autoAdjustHwloc.hpp b/backend/cpu/autoAdjustHwloc.hpp new file mode 100644 index 0000000..968aac7 --- /dev/null +++ b/backend/cpu/autoAdjustHwloc.hpp @@ -0,0 +1,211 @@ +#pragma once + +#include "../../console.h" +#include +#include + +#ifdef _WIN32 +#include +#else +#include +#endif // _WIN32 + +#include +#include "../../ConfigEditor.hpp" + +namespace xmrstak +{ +namespace cpu +{ + +class autoAdjust +{ +public: + + autoAdjust() + { + } + + bool printConfig() + { + + hwloc_topology_t topology; + hwloc_topology_init(&topology); + hwloc_topology_load(topology); + + std::string conf; + ConfigEditor configTpl{}; + + // load the template of the backend config into a char variable + const char *tpl = + #include "./config.tpl" + ; + configTpl.set( std::string(tpl) ); + + conf += std::string("\"cpu_threads_conf\" :\n[\n"); + try + { + std::vector tlcs; + tlcs.reserve(16); + results.reserve(16); + + findChildrenCaches(hwloc_get_root_obj(topology), + [&tlcs](hwloc_obj_t found) { tlcs.emplace_back(found); } ); + + if(tlcs.size() == 0) + throw(std::runtime_error("The CPU doesn't seem to have a cache.")); + + for(hwloc_obj_t obj : tlcs) + proccessTopLevelCache(obj); + + for(uint32_t id : results) + { + conf += std::string(" { \"low_power_mode\" : "); + conf += std::string((id & 0x8000000) != 0 ? "true" : "false"); + conf += std::string(", \"no_prefetch\" : true, \"affine_to_cpu\" : "); + conf += std::to_string(id & 0x7FFFFFF); + conf += std::string(" },\n"); + } + } + catch(const std::runtime_error& err) + { + // \todo add fallback to default auto adjust + conf += std::string(" { \"low_power_mode\" : false, \"no_prefetch\" : true, \"affine_to_cpu\" : false },\n"); + printer::inst()->print_msg(L0, "Autoconf FAILED: %s. Create config for a single thread.", err.what()); + } + conf += std::string("],\n\n"); + + configTpl.replace("CPUCONFIG",conf); + configTpl.write("cpu.txt"); + printer::inst()->print_msg(L0, "CPU configuration stored in file '%s'", "cpu.txt"); + /* Destroy topology object. */ + hwloc_topology_destroy(topology); + + return true; + } + +private: + static constexpr size_t hashSize = 2 * 1024 * 1024; + std::vector results; + + template + inline void findChildrenByType(hwloc_obj_t obj, hwloc_obj_type_t type, func lambda) + { + for(size_t i=0; i < obj->arity; i++) + { + if(obj->children[i]->type == type) + lambda(obj->children[i]); + else + findChildrenByType(obj->children[i], type, lambda); + } + } + + inline bool isCacheObject(hwloc_obj_t obj) + { +#if HWLOC_API_VERSION >= 0x20000 + return hwloc_obj_type_is_cache(obj->type); +#else + return obj->type == HWLOC_OBJ_CACHE; +#endif // HWLOC_API_VERSION + } + + template + inline void findChildrenCaches(hwloc_obj_t obj, func lambda) + { + for(size_t i=0; i < obj->arity; i++) + { + if(isCacheObject(obj->children[i])) + lambda(obj->children[i]); + else + findChildrenCaches(obj->children[i], lambda); + } + } + + inline bool isCacheExclusive(hwloc_obj_t obj) + { + const char* value = hwloc_obj_get_info_by_name(obj, "Inclusive"); + return value == nullptr || value[0] != '1'; + } + + // Top level cache isn't shared with other cores on the same package + // This will usually be 1 x L3, but can be 2 x L2 per package + void proccessTopLevelCache(hwloc_obj_t obj) + { + if(obj->attr == nullptr) + throw(std::runtime_error("Cache object hasn't got attributes.")); + + size_t PUs = 0; + findChildrenByType(obj, HWLOC_OBJ_PU, [&PUs](hwloc_obj_t found) { PUs++; } ); + + //Strange case, but we will handle it silently, surely there must be one PU somewhere? + if(PUs == 0) + return; + + if(obj->attr->cache.size == 0) + { + //We will always have one child if PUs > 0 + if(!isCacheObject(obj->children[0])) + throw(std::runtime_error("The CPU doesn't seem to have a cache.")); + + //Try our luck with lower level caches + for(size_t i=0; i < obj->arity; i++) + proccessTopLevelCache(obj->children[i]); + return; + } + + size_t cacheSize = obj->attr->cache.size; + if(isCacheExclusive(obj)) + { + for(size_t i=0; i < obj->arity; i++) + { + hwloc_obj_t l2obj = obj->children[i]; + //If L2 is exclusive and greater or equal to 2MB add room for one more hash + if(isCacheObject(l2obj) && l2obj->attr != nullptr && l2obj->attr->cache.size >= hashSize) + cacheSize += hashSize; + } + } + + std::vector cores; + cores.reserve(16); + findChildrenByType(obj, HWLOC_OBJ_CORE, [&cores](hwloc_obj_t found) { cores.emplace_back(found); } ); + + size_t cacheHashes = (cacheSize + hashSize/2) / hashSize; + + //Firstly allocate PU 0 of every CORE, then PU 1 etc. + size_t pu_id = 0; + while(cacheHashes > 0 && PUs > 0) + { + bool allocated_pu = false; + for(hwloc_obj_t core : cores) + { + if(core->arity <= pu_id || core->children[pu_id]->type != HWLOC_OBJ_PU) + continue; + + size_t os_id = core->children[pu_id]->os_index; + + if(cacheHashes > PUs) + { + cacheHashes -= 2; + os_id |= 0x8000000; //double hash marker bit + } + else + cacheHashes--; + PUs--; + + allocated_pu = true; + results.emplace_back(os_id); + + if(cacheHashes == 0) + break; + } + + if(!allocated_pu) + throw(std::runtime_error("Failed to allocate a PU.")); + + pu_id++; + } + } +}; + +} // namespace cpu +} // namepsace xmrstak diff --git a/backend/cpu/config.tpl b/backend/cpu/config.tpl new file mode 100644 index 0000000..43c1cb8 --- /dev/null +++ b/backend/cpu/config.tpl @@ -0,0 +1,90 @@ +R"===( +/* + * Thread configuration for each thread. Make sure it matches the number above. + * low_power_mode - This mode will double the cache usage, and double the single thread performance. It will + * consume much less power (as less cores are working), but will max out at around 80-85% of + * the maximum performance. + * + * no_prefetch - Some sytems can gain up to extra 5% here, but sometimes it will have no difference or make + * things slower. + * + * affine_to_cpu - This can be either false (no affinity), or the CPU core number. Note that on hyperthreading + * systems it is better to assign threads to physical cores. On Windows this usually means selecting + * even or odd numbered cpu numbers. For Linux it will be usually the lower CPU numbers, so for a 4 + * physical core CPU you should select cpu numbers 0-3. + * + * On the first run the miner will look at your system and suggest a basic configuration that will work, + * you can try to tweak it from there to get the best performance. + * + * A filled out configuration should look like this: + * "cpu_threads_conf" : + * [ + * { "low_power_mode" : false, "no_prefetch" : true, "affine_to_cpu" : 0 }, + * { "low_power_mode" : false, "no_prefetch" : true, "affine_to_cpu" : 1 }, + * ], + */ + +CPUCONFIG + +/* + * LARGE PAGE SUPPORT + * Large pages need a properly set up OS. It can be difficult if you are not used to systems administration, + * but the performance results are worth the trouble - you will get around 20% boost. Slow memory mode is + * meant as a backup, you won't get stellar results there. If you are running into trouble, especially + * on Windows, please read the common issues in the README. + * + * By default we will try to allocate large pages. This means you need to "Run As Administrator" on Windows. + * You need to edit your system's group policies to enable locking large pages. Here are the steps from MSDN + * + * 1. On the Start menu, click Run. In the Open box, type gpedit.msc. + * 2. On the Local Group Policy Editor console, expand Computer Configuration, and then expand Windows Settings. + * 3. Expand Security Settings, and then expand Local Policies. + * 4. Select the User Rights Assignment folder. + * 5. The policies will be displayed in the details pane. + * 6. In the pane, double-click Lock pages in memory. + * 7. In the Local Security Setting – Lock pages in memory dialog box, click Add User or Group. + * 8. In the Select Users, Service Accounts, or Groups dialog box, add an account that you will run the miner on + * 9. Reboot for change to take effect. + * + * Windows also tends to fragment memory a lot. If you are running on a system with 4-8GB of RAM you might need + * to switch off all the auto-start applications and reboot to have a large enough chunk of contiguous memory. + * + * On Linux you will need to configure large page support "sudo sysctl -w vm.nr_hugepages=128" and increase your + * ulimit -l. To do do this you need to add following lines to /etc/security/limits.conf - "* soft memlock 262144" + * and "* hard memlock 262144". You can also do it Windows-style and simply run-as-root, but this is NOT + * recommended for security reasons. + * + * Memory locking means that the kernel can't swap out the page to disk - something that is unlikely to happen on a + * command line system that isn't starved of memory. I haven't observed any difference on a CLI Linux system between + * locked and unlocked memory. If that is your setup see option "no_mlck". + */ + +/* + * use_slow_memory defines our behavior with regards to large pages. There are three possible options here: + * always - Don't even try to use large pages. Always use slow memory. + * warn - We will try to use large pages, but fall back to slow memory if that fails. + * no_mlck - This option is only relevant on Linux, where we can use large pages without locking memory. + * It will never use slow memory, but it won't attempt to mlock + * never - If we fail to allocate large pages we will print an error and exit. + */ +"use_slow_memory" : "warn", + +/* + * NiceHash mode + * nicehash_nonce - Limit the nonce to 3 bytes as required by nicehash. This cuts all the safety margins, and + * if a block isn't found within 30 minutes then you might run into nonce collisions. Number + * of threads in this mode is hard-limited to 32. + */ +"nicehash_nonce" : false, + +/* + * Manual hardware AES override + * + * Some VMs don't report AES capability correctly. You can set this value to true to enforce hardware AES or + * to false to force disable AES or null to let the miner decide if AES is used. + * + * WARNING: setting this to true on a CPU that doesn't support hardware AES will crash the miner. + */ +"aes_override" : null, + +)===" diff --git a/backend/cpu/jconf.cpp b/backend/cpu/jconf.cpp new file mode 100644 index 0000000..e919096 --- /dev/null +++ b/backend/cpu/jconf.cpp @@ -0,0 +1,347 @@ +/* + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * Additional permission under GNU GPL version 3 section 7 + * + * If you modify this Program, or any covered work, by linking or combining + * it with OpenSSL (or a modified version of that library), containing parts + * covered by the terms of OpenSSL License and SSLeay License, the licensors + * of this Program grant you additional permission to convey the resulting work. + * + */ + +#include "jconf.h" +#include "../../console.h" +#include + +#include +#include +#include + +#ifdef _WIN32 +#define strcasecmp _stricmp +#include +#else +#include +#endif + +#include "../../rapidjson/document.h" +#include "../../rapidjson/error/en.h" +#include "../../jext.h" + +namespace xmrstak +{ +namespace cpu +{ + +using namespace rapidjson; + +/* + * This enum needs to match index in oConfigValues, otherwise we will get a runtime error + */ +enum configEnum { aCpuThreadsConf, sUseSlowMem, bNiceHashMode, bAesOverride }; + +struct configVal { + configEnum iName; + const char* sName; + Type iType; +}; + +// Same order as in configEnum, as per comment above +// kNullType means any type +configVal oConfigValues[] = { + { aCpuThreadsConf, "cpu_threads_conf", kNullType }, + { sUseSlowMem, "use_slow_memory", kStringType }, + { bNiceHashMode, "nicehash_nonce", kTrueType }, + { bAesOverride, "aes_override", kNullType } +}; + +constexpr size_t iConfigCnt = (sizeof(oConfigValues)/sizeof(oConfigValues[0])); + +inline bool checkType(Type have, Type want) +{ + if(want == have) + return true; + else if(want == kNullType) + return true; + else if(want == kTrueType && have == kFalseType) + return true; + else if(want == kFalseType && have == kTrueType) + return true; + else + return false; +} + +struct jconf::opaque_private +{ + Document jsonDoc; + const Value* configValues[iConfigCnt]; //Compile time constant + + opaque_private() + { + } +}; + +jconf* jconf::oInst = nullptr; + +jconf::jconf() +{ + prv = new opaque_private(); +} + +bool jconf::GetThreadConfig(size_t id, thd_cfg &cfg) +{ + if(!prv->configValues[aCpuThreadsConf]->IsArray()) + return false; + + if(id >= prv->configValues[aCpuThreadsConf]->Size()) + return false; + + const Value& oThdConf = prv->configValues[aCpuThreadsConf]->GetArray()[id]; + + if(!oThdConf.IsObject()) + return false; + + const Value *mode, *no_prefetch, *aff; + mode = GetObjectMember(oThdConf, "low_power_mode"); + no_prefetch = GetObjectMember(oThdConf, "no_prefetch"); + aff = GetObjectMember(oThdConf, "affine_to_cpu"); + + if(mode == nullptr || no_prefetch == nullptr || aff == nullptr) + return false; + + if(!mode->IsBool() || !no_prefetch->IsBool()) + return false; + + if(!aff->IsNumber() && !aff->IsBool()) + return false; + + if(aff->IsNumber() && aff->GetInt64() < 0) + return false; + + cfg.bDoubleMode = mode->GetBool(); + cfg.bNoPrefetch = no_prefetch->GetBool(); + + if(aff->IsNumber()) + cfg.iCpuAff = aff->GetInt64(); + else + cfg.iCpuAff = -1; + + return true; +} + +jconf::slow_mem_cfg jconf::GetSlowMemSetting() +{ + const char* opt = prv->configValues[sUseSlowMem]->GetString(); + + if(strcasecmp(opt, "always") == 0) + return always_use; + else if(strcasecmp(opt, "no_mlck") == 0) + return no_mlck; + else if(strcasecmp(opt, "warn") == 0) + return print_warning; + else if(strcasecmp(opt, "never") == 0) + return never_use; + else + return unknown_value; +} + +size_t jconf::GetThreadCount() +{ + if(prv->configValues[aCpuThreadsConf]->IsArray()) + return prv->configValues[aCpuThreadsConf]->Size(); + else + return 0; +} + +bool jconf::NeedsAutoconf() +{ + return !prv->configValues[aCpuThreadsConf]->IsArray(); +} + +bool jconf::NiceHashMode() +{ + return prv->configValues[bNiceHashMode]->GetBool(); +} + +void jconf::cpuid(uint32_t eax, int32_t ecx, int32_t val[4]) +{ + memset(val, 0, sizeof(int32_t)*4); + +#ifdef _WIN32 + __cpuidex(val, eax, ecx); +#else + __cpuid_count(eax, ecx, val[0], val[1], val[2], val[3]); +#endif +} + +bool jconf::check_cpu_features() +{ + constexpr int AESNI_BIT = 1 << 25; + constexpr int SSE2_BIT = 1 << 26; + int32_t cpu_info[4]; + bool bHaveSse2; + + cpuid(1, 0, cpu_info); + + bHaveAes = (cpu_info[2] & AESNI_BIT) != 0; + bHaveSse2 = (cpu_info[3] & SSE2_BIT) != 0; + + return bHaveSse2; +} + +bool jconf::parse_config(const char* sFilename) +{ + FILE * pFile; + char * buffer; + size_t flen; + + if(!check_cpu_features()) + { + printer::inst()->print_msg(L0, "CPU support of SSE2 is required."); + return false; + } + + pFile = fopen(sFilename, "rb"); + if (pFile == NULL) + { + printer::inst()->print_msg(L0, "Failed to open config file %s.", sFilename); + return false; + } + + fseek(pFile,0,SEEK_END); + flen = ftell(pFile); + rewind(pFile); + + if(flen >= 64*1024) + { + fclose(pFile); + printer::inst()->print_msg(L0, "Oversized config file - %s.", sFilename); + return false; + } + + if(flen <= 16) + { + fclose(pFile); + printer::inst()->print_msg(L0, "File is empty or too short - %s.", sFilename); + return false; + } + + buffer = (char*)malloc(flen + 3); + if(fread(buffer+1, flen, 1, pFile) != 1) + { + free(buffer); + fclose(pFile); + printer::inst()->print_msg(L0, "Read error while reading %s.", sFilename); + return false; + } + fclose(pFile); + + //Replace Unicode BOM with spaces - we always use UTF-8 + unsigned char* ubuffer = (unsigned char*)buffer; + if(ubuffer[1] == 0xEF && ubuffer[2] == 0xBB && ubuffer[3] == 0xBF) + { + buffer[1] = ' '; + buffer[2] = ' '; + buffer[3] = ' '; + } + + buffer[0] = '{'; + buffer[flen] = '}'; + buffer[flen + 1] = '\0'; + + prv->jsonDoc.Parse(buffer, flen+2); + free(buffer); + + if(prv->jsonDoc.HasParseError()) + { + printer::inst()->print_msg(L0, "JSON config parse error(offset %llu): %s", + int_port(prv->jsonDoc.GetErrorOffset()), GetParseError_En(prv->jsonDoc.GetParseError())); + return false; + } + + if(!prv->jsonDoc.IsObject()) + { //This should never happen as we created the root ourselves + printer::inst()->print_msg(L0, "Invalid config file. No root?\n"); + return false; + } + + for(size_t i = 0; i < iConfigCnt; i++) + { + if(oConfigValues[i].iName != i) + { + printer::inst()->print_msg(L0, "Code error. oConfigValues are not in order."); + return false; + } + + prv->configValues[i] = GetObjectMember(prv->jsonDoc, oConfigValues[i].sName); + + if(prv->configValues[i] == nullptr) + { + printer::inst()->print_msg(L0, "Invalid config file. Missing value \"%s\".", oConfigValues[i].sName); + return false; + } + + if(!checkType(prv->configValues[i]->GetType(), oConfigValues[i].iType)) + { + printer::inst()->print_msg(L0, "Invalid config file. Value \"%s\" has unexpected type.", oConfigValues[i].sName); + return false; + } + } + + thd_cfg c; + for(size_t i=0; i < GetThreadCount(); i++) + { + if(!GetThreadConfig(i, c)) + { + printer::inst()->print_msg(L0, "Thread %llu has invalid config.", int_port(i)); + return false; + } + } + + if(NiceHashMode() && GetThreadCount() >= 32) + { + printer::inst()->print_msg(L0, "You need to use less than 32 threads in NiceHash mode."); + return false; + } + + if(GetSlowMemSetting() == unknown_value) + { + printer::inst()->print_msg(L0, + "Invalid config file. use_slow_memory must be \"always\", \"no_mlck\", \"warn\" or \"never\""); + return false; + } + +#ifdef _WIN32 + if(GetSlowMemSetting() == no_mlck) + { + printer::inst()->print_msg(L0, "On Windows large pages need mlock. Please use another option."); + return false; + } +#endif // _WIN32 + + //if(NeedsAutoconf()) + // return true; + + if(prv->configValues[bAesOverride]->IsBool()) + bHaveAes = prv->configValues[bAesOverride]->GetBool(); + + if(!bHaveAes) + printer::inst()->print_msg(L0, "Your CPU doesn't support hardware AES. Don't expect high hashrates."); + + return true; +} + +} // namespace cpu +} // namepsace xmrstak diff --git a/backend/cpu/jconf.h b/backend/cpu/jconf.h new file mode 100644 index 0000000..39fe6d9 --- /dev/null +++ b/backend/cpu/jconf.h @@ -0,0 +1,59 @@ +#pragma once +#include +#include + +namespace xmrstak +{ +namespace cpu +{ + +class jconf +{ +public: + static jconf* inst() + { + if (oInst == nullptr) oInst = new jconf; + return oInst; + }; + + bool parse_config(const char* sFilename = "cpu.txt"); + + struct thd_cfg { + bool bDoubleMode; + bool bNoPrefetch; + long long iCpuAff; + }; + + enum slow_mem_cfg { + always_use, + no_mlck, + print_warning, + never_use, + unknown_value + }; + + size_t GetThreadCount(); + bool GetThreadConfig(size_t id, thd_cfg &cfg); + bool NeedsAutoconf(); + + slow_mem_cfg GetSlowMemSetting(); + + bool NiceHashMode(); + + inline bool HaveHardwareAes() { return bHaveAes; } + + static void cpuid(uint32_t eax, int32_t ecx, int32_t val[4]); + +private: + jconf(); + static jconf* oInst; + + bool check_cpu_features(); + struct opaque_private; + opaque_private* prv; + + bool bHaveAes; +}; + +} // namespace cpu +} // namepsace xmrstak diff --git a/backend/cpu/minethd.cpp b/backend/cpu/minethd.cpp new file mode 100644 index 0000000..e6d1bd6 --- /dev/null +++ b/backend/cpu/minethd.cpp @@ -0,0 +1,506 @@ +/* + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * Additional permission under GNU GPL version 3 section 7 + * + * If you modify this Program, or any covered work, by linking or combining + * it with OpenSSL (or a modified version of that library), containing parts + * covered by the terms of OpenSSL License and SSLeay License, the licensors + * of this Program grant you additional permission to convey the resulting work. + * + */ + +#include +#include +#include +#include +#include +#include +#include "../../console.h" +#include "../IBackend.hpp" +#include "../GlobalStates.hpp" +#include "../../ConfigEditor.hpp" + +#include "../../executor.h" +#include "minethd.h" +#include "./jconf.h" +#include "../../crypto/cryptonight_aesni.h" +#include "../../hwlocMemory.hpp" +#include "../miner_work.h" + +#ifndef CONF_NO_HWLOC +# include "autoAdjustHwloc.hpp" +#else +# include "autoAdjust.hpp" +#endif + + +#ifdef _WIN32 +#include + +namespace xmrstak +{ +namespace cpu +{ +void minethd::thd_setaffinity(std::thread::native_handle_type h, uint64_t cpu_id) +{ + SetThreadAffinityMask(h, 1ULL << cpu_id); +} + +} // namespace cpu +} // namespace xmrstak + +#else +#include + +#if defined(__APPLE__) +#include +#include +#define SYSCTL_CORE_COUNT "machdep.cpu.core_count" +#elif defined(__FreeBSD__) +#include +#endif + +namespace xmrstak +{ +namespace cpu +{ + +void minethd::thd_setaffinity(std::thread::native_handle_type h, uint64_t cpu_id) +{ +#if defined(__APPLE__) + thread_port_t mach_thread; + thread_affinity_policy_data_t policy = { static_cast(cpu_id) }; + mach_thread = pthread_mach_thread_np(h); + thread_policy_set(mach_thread, THREAD_AFFINITY_POLICY, (thread_policy_t)&policy, 1); +#elif defined(__FreeBSD__) + cpuset_t mn; + CPU_ZERO(&mn); + CPU_SET(cpu_id, &mn); + pthread_setaffinity_np(h, sizeof(cpuset_t), &mn); +#else + cpu_set_t mn; + CPU_ZERO(&mn); + CPU_SET(cpu_id, &mn); + pthread_setaffinity_np(h, sizeof(cpu_set_t), &mn); +#endif +} + +} // namespace cpu +} // namespace xmrstak + +#endif // _WIN32 + + +namespace xmrstak +{ +namespace cpu +{ + +minethd::minethd(miner_work& pWork, size_t iNo, bool double_work, bool no_prefetch, int64_t affinity) +{ + oWork = pWork; + bQuit = 0; + iThreadNo = (uint8_t)iNo; + iJobNo = 0; + bNoPrefetch = no_prefetch; + this->affinity = affinity; + + std::lock_guard lock(work_thd_mtx); + if(double_work) + oWorkThd = std::thread(&minethd::double_work_main, this); + else + oWorkThd = std::thread(&minethd::work_main, this); +} + +cryptonight_ctx* minethd::minethd_alloc_ctx() +{ + cryptonight_ctx* ctx; + alloc_msg msg = { 0 }; + + switch (jconf::inst()->GetSlowMemSetting()) + { + case jconf::never_use: + ctx = cryptonight_alloc_ctx(1, 1, &msg); + if (ctx == NULL) + printer::inst()->print_msg(L0, "MEMORY ALLOC FAILED: %s", msg.warning); + return ctx; + + case jconf::no_mlck: + ctx = cryptonight_alloc_ctx(1, 0, &msg); + if (ctx == NULL) + printer::inst()->print_msg(L0, "MEMORY ALLOC FAILED: %s", msg.warning); + return ctx; + + case jconf::print_warning: + ctx = cryptonight_alloc_ctx(1, 1, &msg); + if (msg.warning != NULL) + printer::inst()->print_msg(L0, "MEMORY ALLOC FAILED: %s", msg.warning); + if (ctx == NULL) + ctx = cryptonight_alloc_ctx(0, 0, NULL); + return ctx; + + case jconf::always_use: + return cryptonight_alloc_ctx(0, 0, NULL); + + case jconf::unknown_value: + return NULL; //Shut up compiler + } + + return nullptr; //Should never happen +} + +bool minethd::self_test() +{ + alloc_msg msg = { 0 }; + size_t res; + bool fatal = false; + + switch (jconf::inst()->GetSlowMemSetting()) + { + case jconf::never_use: + res = cryptonight_init(1, 1, &msg); + fatal = true; + break; + + case jconf::no_mlck: + res = cryptonight_init(1, 0, &msg); + fatal = true; + break; + + case jconf::print_warning: + res = cryptonight_init(1, 1, &msg); + break; + + case jconf::always_use: + res = cryptonight_init(0, 0, &msg); + break; + + case jconf::unknown_value: + default: + return false; //Shut up compiler + } + + if(msg.warning != nullptr) + printer::inst()->print_msg(L0, "MEMORY INIT ERROR: %s", msg.warning); + + if(res == 0 && fatal) + return false; + + cryptonight_ctx *ctx0, *ctx1; + if((ctx0 = minethd_alloc_ctx()) == nullptr) + return false; + + if((ctx1 = minethd_alloc_ctx()) == nullptr) + { + cryptonight_free_ctx(ctx0); + return false; + } + + unsigned char out[64]; + bool bResult; + + cn_hash_fun hashf; + cn_hash_fun_dbl hashdf; + + hashf = func_selector(jconf::inst()->HaveHardwareAes(), false); + hashf("This is a test", 14, out, ctx0); + bResult = memcmp(out, "\xa0\x84\xf0\x1d\x14\x37\xa0\x9c\x69\x85\x40\x1b\x60\xd4\x35\x54\xae\x10\x58\x02\xc5\xf5\xd8\xa9\xb3\x25\x36\x49\xc0\xbe\x66\x05", 32) == 0; + + hashf = func_selector(jconf::inst()->HaveHardwareAes(), true); + hashf("This is a test", 14, out, ctx0); + bResult &= memcmp(out, "\xa0\x84\xf0\x1d\x14\x37\xa0\x9c\x69\x85\x40\x1b\x60\xd4\x35\x54\xae\x10\x58\x02\xc5\xf5\xd8\xa9\xb3\x25\x36\x49\xc0\xbe\x66\x05", 32) == 0; + + hashdf = func_dbl_selector(jconf::inst()->HaveHardwareAes(), false); + hashdf("The quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy log", 43, out, ctx0, ctx1); + bResult &= memcmp(out, "\x3e\xbb\x7f\x9f\x7d\x27\x3d\x7c\x31\x8d\x86\x94\x77\x55\x0c\xc8\x00\xcf\xb1\x1b\x0c\xad\xb7\xff\xbd\xf6\xf8\x9f\x3a\x47\x1c\x59" + "\xb4\x77\xd5\x02\xe4\xd8\x48\x7f\x42\xdf\xe3\x8e\xed\x73\x81\x7a\xda\x91\xb7\xe2\x63\xd2\x91\x71\xb6\x5c\x44\x3a\x01\x2a\x41\x22", 64) == 0; + + hashdf = func_dbl_selector(jconf::inst()->HaveHardwareAes(), true); + hashdf("The quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy log", 43, out, ctx0, ctx1); + bResult &= memcmp(out, "\x3e\xbb\x7f\x9f\x7d\x27\x3d\x7c\x31\x8d\x86\x94\x77\x55\x0c\xc8\x00\xcf\xb1\x1b\x0c\xad\xb7\xff\xbd\xf6\xf8\x9f\x3a\x47\x1c\x59" + "\xb4\x77\xd5\x02\xe4\xd8\x48\x7f\x42\xdf\xe3\x8e\xed\x73\x81\x7a\xda\x91\xb7\xe2\x63\xd2\x91\x71\xb6\x5c\x44\x3a\x01\x2a\x41\x22", 64) == 0; + + cryptonight_free_ctx(ctx0); + cryptonight_free_ctx(ctx1); + + if(!bResult) + printer::inst()->print_msg(L0, + "Cryptonight hash self-test failed. This might be caused by bad compiler optimizations."); + + return bResult; +} + +std::vector minethd::thread_starter(uint32_t threadOffset, miner_work& pWork) +{ + std::vector pvThreads; + + if(!ConfigEditor::file_exist("cpu.txt")) + { + autoAdjust adjust; + if(!adjust.printConfig()) + return pvThreads; + } + + if(!xmrstak::cpu::jconf::inst()->parse_config("cpu.txt")) + { + win_exit(); + } + + + //Launch the requested number of single and double threads, to distribute + //load evenly we need to alternate single and double threads + size_t i, n = jconf::inst()->GetThreadCount(); + pvThreads.reserve(n); + + jconf::thd_cfg cfg; + for (i = 0; i < n; i++) + { + jconf::inst()->GetThreadConfig(i, cfg); + + // \todo need thread offset + minethd* thd = new minethd(pWork, i + threadOffset, cfg.bDoubleMode, cfg.bNoPrefetch, cfg.iCpuAff); + pvThreads.push_back(thd); + + if(cfg.iCpuAff >= 0) + printer::inst()->print_msg(L1, "Starting %s thread, affinity: %d.", cfg.bDoubleMode ? "double" : "single", (int)cfg.iCpuAff); + else + printer::inst()->print_msg(L1, "Starting %s thread, no affinity.", cfg.bDoubleMode ? "double" : "single"); + } + + return pvThreads; +} + +void minethd::consume_work() +{ + memcpy(&oWork, &GlobalStates::oGlobalWork, sizeof(miner_work)); + iJobNo++; + GlobalStates::iConsumeCnt++; +} + +minethd::cn_hash_fun minethd::func_selector(bool bHaveAes, bool bNoPrefetch) +{ + // We have two independent flag bits in the functions + // therefore we will build a binary digit and select the + // function as a two digit binary + // Digit order SOFT_AES, NO_PREFETCH + + static const cn_hash_fun func_table[4] = { + cryptonight_hash<0x80000, MEMORY, false, false>, + cryptonight_hash<0x80000, MEMORY, false, true>, + cryptonight_hash<0x80000, MEMORY, true, false>, + cryptonight_hash<0x80000, MEMORY, true, true> + }; + + std::bitset<2> digit; + digit.set(0, !bNoPrefetch); + digit.set(1, !bHaveAes); + + return func_table[digit.to_ulong()]; +} + +void minethd::pin_thd_affinity() +{ + //Lock is needed because we need to use oWorkThd + std::lock_guard lock(work_thd_mtx); + + // pin memory to NUMA node + bindMemoryToNUMANode(affinity); + +#if defined(__APPLE__) + printer::inst()->print_msg(L1, "WARNING on MacOS thread affinity is only advisory."); +#endif + thd_setaffinity(oWorkThd.native_handle(), affinity); +} + +void minethd::work_main() +{ + if(affinity >= 0) //-1 means no affinity + pin_thd_affinity(); + + cn_hash_fun hash_fun; + cryptonight_ctx* ctx; + uint64_t iCount = 0; + uint64_t* piHashVal; + uint32_t* piNonce; + job_result result; + + hash_fun = func_selector(jconf::inst()->HaveHardwareAes(), bNoPrefetch); + ctx = minethd_alloc_ctx(); + + piHashVal = (uint64_t*)(result.bResult + 24); + piNonce = (uint32_t*)(oWork.bWorkBlob + 39); + GlobalStates::iConsumeCnt++; + + while (bQuit == 0) + { + if (oWork.bStall) + { + /* We are stalled here because the executor didn't find a job for us yet, + either because of network latency, or a socket problem. Since we are + raison d'etre of this software it us sensible to just wait until we have something*/ + + while (GlobalStates::iGlobalJobNo.load(std::memory_order_relaxed) == iJobNo) + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + + consume_work(); + continue; + } + + if(oWork.bNiceHash) + result.iNonce = calc_nicehash_nonce(*piNonce, oWork.iResumeCnt); + else + result.iNonce = calc_start_nonce(oWork.iResumeCnt); + + assert(sizeof(job_result::sJobID) == sizeof(pool_job::sJobID)); + memcpy(result.sJobID, oWork.sJobID, sizeof(job_result::sJobID)); + + while(GlobalStates::iGlobalJobNo.load(std::memory_order_relaxed) == iJobNo) + { + if ((iCount & 0xF) == 0) //Store stats every 16 hashes + { + using namespace std::chrono; + uint64_t iStamp = time_point_cast(high_resolution_clock::now()).time_since_epoch().count(); + iHashCount.store(iCount, std::memory_order_relaxed); + iTimestamp.store(iStamp, std::memory_order_relaxed); + } + iCount++; + + *piNonce = ++result.iNonce; + + hash_fun(oWork.bWorkBlob, oWork.iWorkSize, result.bResult, ctx); + + if (*piHashVal < oWork.iTarget) + executor::inst()->push_event(ex_event(result, oWork.iPoolId)); + + std::this_thread::yield(); + } + + consume_work(); + } + + cryptonight_free_ctx(ctx); +} + +minethd::cn_hash_fun_dbl minethd::func_dbl_selector(bool bHaveAes, bool bNoPrefetch) +{ + // We have two independent flag bits in the functions + // therefore we will build a binary digit and select the + // function as a two digit binary + // Digit order SOFT_AES, NO_PREFETCH + + static const cn_hash_fun_dbl func_table[4] = { + cryptonight_double_hash<0x80000, MEMORY, false, false>, + cryptonight_double_hash<0x80000, MEMORY, false, true>, + cryptonight_double_hash<0x80000, MEMORY, true, false>, + cryptonight_double_hash<0x80000, MEMORY, true, true> + }; + + std::bitset<2> digit; + digit.set(0, !bNoPrefetch); + digit.set(1, !bHaveAes); + + return func_table[digit.to_ulong()]; +} + +void minethd::double_work_main() +{ + if(affinity >= 0) //-1 means no affinity + pin_thd_affinity(); + + cn_hash_fun_dbl hash_fun; + cryptonight_ctx* ctx0; + cryptonight_ctx* ctx1; + uint64_t iCount = 0; + uint64_t *piHashVal0, *piHashVal1; + uint32_t *piNonce0, *piNonce1; + uint8_t bDoubleHashOut[64]; + uint8_t bDoubleWorkBlob[sizeof(miner_work::bWorkBlob) * 2]; + uint32_t iNonce; + job_result res; + + hash_fun = func_dbl_selector(jconf::inst()->HaveHardwareAes(), bNoPrefetch); + ctx0 = minethd_alloc_ctx(); + ctx1 = minethd_alloc_ctx(); + + piHashVal0 = (uint64_t*)(bDoubleHashOut + 24); + piHashVal1 = (uint64_t*)(bDoubleHashOut + 32 + 24); + piNonce0 = (uint32_t*)(bDoubleWorkBlob + 39); + piNonce1 = nullptr; + + GlobalStates::iConsumeCnt++; + + while (bQuit == 0) + { + if (oWork.bStall) + { + /* We are stalled here because the executor didn't find a job for us yet, + either because of network latency, or a socket problem. Since we are + raison d'etre of this software it us sensible to just wait until we have something*/ + + while (GlobalStates::iGlobalJobNo.load(std::memory_order_relaxed) == iJobNo) + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + + consume_work(); + memcpy(bDoubleWorkBlob, oWork.bWorkBlob, oWork.iWorkSize); + memcpy(bDoubleWorkBlob + oWork.iWorkSize, oWork.bWorkBlob, oWork.iWorkSize); + piNonce1 = (uint32_t*)(bDoubleWorkBlob + oWork.iWorkSize + 39); + continue; + } + + if(oWork.bNiceHash) + iNonce = calc_nicehash_nonce(*piNonce0, oWork.iResumeCnt); + else + iNonce = calc_start_nonce(oWork.iResumeCnt); + + assert(sizeof(job_result::sJobID) == sizeof(pool_job::sJobID)); + + while (GlobalStates::iGlobalJobNo.load(std::memory_order_relaxed) == iJobNo) + { + if ((iCount & 0x7) == 0) //Store stats every 16 hashes + { + using namespace std::chrono; + uint64_t iStamp = time_point_cast(high_resolution_clock::now()).time_since_epoch().count(); + iHashCount.store(iCount, std::memory_order_relaxed); + iTimestamp.store(iStamp, std::memory_order_relaxed); + } + + iCount += 2; + + *piNonce0 = ++iNonce; + *piNonce1 = ++iNonce; + + hash_fun(bDoubleWorkBlob, oWork.iWorkSize, bDoubleHashOut, ctx0, ctx1); + + if (*piHashVal0 < oWork.iTarget) + executor::inst()->push_event(ex_event(job_result(oWork.sJobID, iNonce-1, bDoubleHashOut), oWork.iPoolId)); + + if (*piHashVal1 < oWork.iTarget) + executor::inst()->push_event(ex_event(job_result(oWork.sJobID, iNonce, bDoubleHashOut + 32), oWork.iPoolId)); + + std::this_thread::yield(); + } + + consume_work(); + memcpy(bDoubleWorkBlob, oWork.bWorkBlob, oWork.iWorkSize); + memcpy(bDoubleWorkBlob + oWork.iWorkSize, oWork.bWorkBlob, oWork.iWorkSize); + piNonce1 = (uint32_t*)(bDoubleWorkBlob + oWork.iWorkSize + 39); + } + + cryptonight_free_ctx(ctx0); + cryptonight_free_ctx(ctx1); +} + +} // namespace cpu +} // namepsace xmrstak diff --git a/backend/cpu/minethd.h b/backend/cpu/minethd.h new file mode 100644 index 0000000..3997daa --- /dev/null +++ b/backend/cpu/minethd.h @@ -0,0 +1,74 @@ +#pragma once +#include +#include +#include +#include +#include "../../crypto/cryptonight.h" +#include "../miner_work.h" +#include "../IBackend.hpp" +#include "../GlobalStates.hpp" +#include + +namespace xmrstak +{ +namespace cpu +{ + +class minethd : public IBackend +{ +public: + static std::vector thread_starter(uint32_t threadOffset, miner_work& pWork); + static bool self_test(); + + typedef void (*cn_hash_fun)(const void*, size_t, void*, cryptonight_ctx*); + + static cn_hash_fun func_selector(bool bHaveAes, bool bNoPrefetch); + static void thd_setaffinity(std::thread::native_handle_type h, uint64_t cpu_id); + + static cryptonight_ctx* minethd_alloc_ctx(); + +private: + + typedef void (*cn_hash_fun_dbl)(const void*, size_t, void*, cryptonight_ctx* __restrict, cryptonight_ctx* __restrict); + static cn_hash_fun_dbl func_dbl_selector(bool bHaveAes, bool bNoPrefetch); + + minethd(miner_work& pWork, size_t iNo, bool double_work, bool no_prefetch, int64_t affinity); + + // We use the top 10 bits of the nonce for thread and resume + // This allows us to resume up to 128 threads 4 times before + // we get nonce collisions + // Bottom 22 bits allow for an hour of work at 1000 H/s + inline uint32_t calc_start_nonce(uint32_t resume) + { + return reverseBits(iThreadNo + GlobalStates::iThreadCount * resume); + } + + // Limited version of the nonce calc above + inline uint32_t calc_nicehash_nonce(uint32_t start, uint32_t resume) + { + return start | ( ( reverseBits(iThreadNo + GlobalStates::iThreadCount * resume) >> 4u ) ); + } + + void work_main(); + void double_work_main(); + void consume_work(); + + uint64_t iJobNo; + + static miner_work oGlobalWork; + miner_work oWork; + + void pin_thd_affinity(); + // Held by the creating context to prevent a race cond with oWorkThd = std::thread(...) + std::mutex work_thd_mtx; + + std::thread oWorkThd; + uint8_t iThreadNo; + int64_t affinity; + + bool bQuit; + bool bNoPrefetch; +}; + +} // namespace cpu +} // namepsace xmrstak