| 1 | // Copyright (c) 2014-2022, The Monero Project |
| 2 | // |
| 3 | // All rights reserved. |
| 4 | // |
| 5 | // Redistribution and use in source and binary forms, with or without modification, are |
| 6 | // permitted provided that the following conditions are met: |
| 7 | // |
| 8 | // 1. Redistributions of source code must retain the above copyright notice, this list of |
| 9 | // conditions and the following disclaimer. |
| 10 | // |
| 11 | // 2. Redistributions in binary form must reproduce the above copyright notice, this list |
| 12 | // of conditions and the following disclaimer in the documentation and/or other |
| 13 | // materials provided with the distribution. |
| 14 | // |
| 15 | // 3. Neither the name of the copyright holder nor the names of its contributors may be |
| 16 | // used to endorse or promote products derived from this software without specific |
| 17 | // prior written permission. |
| 18 | // |
| 19 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY |
| 20 | // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF |
| 21 | // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL |
| 22 | // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, |
| 24 | // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 25 | // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, |
| 26 | // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF |
| 27 | // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 28 | // |
| 29 | // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers |
| 30 | |
| 31 | #include <sstream> |
| 32 | #include <numeric> |
| 33 | #include <boost/algorithm/string.hpp> |
| 34 | #include "misc_language.h" |
| 35 | #include "syncobj.h" |
| 36 | #include "cryptonote_basic_impl.h" |
| 37 | #include "cryptonote_format_utils.h" |
| 38 | #include "cryptonote_core/cryptonote_tx_utils.h" |
| 39 | #include "file_io_utils.h" |
| 40 | #include "common/command_line.h" |
| 41 | #include "common/util.h" |
| 42 | #include "string_coding.h" |
| 43 | #include "string_tools.h" |
| 44 | #include "storages/portable_storage_template_helper.h" |
| 45 | #include "boost/logic/tribool.hpp" |
| 46 | #include <boost/filesystem.hpp> |
| 47 | |
| 48 | #ifdef __APPLE__ |
| 49 | #include <sys/times.h> |
| 50 | #include <IOKit/IOKitLib.h> |
| 51 | #include <IOKit/ps/IOPSKeys.h> |
| 52 | #include <IOKit/ps/IOPowerSources.h> |
| 53 | #include <mach/mach_host.h> |
| 54 | #include <AvailabilityMacros.h> |
| 55 | #include <TargetConditionals.h> |
| 56 | #elif defined(__linux__) |
| 57 | #include <unistd.h> |
| 58 | #include <sys/resource.h> |
| 59 | #include <sys/times.h> |
| 60 | #include <time.h> |
| 61 | #elif defined(__FreeBSD__) |
| 62 | #include <devstat.h> |
| 63 | #include <errno.h> |
| 64 | #include <fcntl.h> |
| 65 | #if defined(__amd64__) || defined(__i386__) || defined(__x86_64__) |
| 66 | #include <machine/apm_bios.h> |
| 67 | #endif |
| 68 | #include <stdio.h> |
| 69 | #include <sys/resource.h> |
| 70 | #include <sys/sysctl.h> |
| 71 | #include <sys/times.h> |
| 72 | #include <sys/types.h> |
| 73 | #include <unistd.h> |
| 74 | #endif |
| 75 | |
| 76 | #undef MONERO_DEFAULT_LOG_CATEGORY |
| 77 | #define MONERO_DEFAULT_LOG_CATEGORY "miner" |
| 78 | |
| 79 | #define AUTODETECT_WINDOW 10 // seconds |
| 80 | #define AUTODETECT_GAIN_THRESHOLD 1.02f // 2% |
| 81 | |
| 82 | using namespace epee; |
| 83 | |
| 84 | #include "miner.h" |
| 85 | #include "crypto/hash.h" |
| 86 | |
| 87 | |
| 88 | extern "C" void slow_hash_allocate_state(); |
| 89 | extern "C" void slow_hash_free_state(); |
| 90 | namespace cryptonote |
| 91 | { |
| 92 | |
| 93 | namespace |
| 94 | { |
| 95 | const command_line::arg_descriptor<std::string> arg_extra_messages = {"extra-messages-file", "Specify file for extra messages to include into coinbase transactions", "", true}; |
| 96 | const command_line::arg_descriptor<std::string> arg_start_mining = {"start-mining", "Specify wallet address to mining for", "", true}; |
| 97 | const command_line::arg_descriptor<uint32_t> arg_mining_threads = {"mining-threads", "Specify mining threads count", 0, true}; |
| 98 | const command_line::arg_descriptor<bool> arg_bg_mining_enable = {"bg-mining-enable", "enable background mining", true, true}; |
| 99 | const command_line::arg_descriptor<bool> arg_bg_mining_ignore_battery = {"bg-mining-ignore-battery", "if true, assumes plugged in when unable to query system power status", false, true}; |
| 100 | const command_line::arg_descriptor<uint64_t> arg_bg_mining_min_idle_interval_seconds = {"bg-mining-min-idle-interval", "Specify min lookback interval in seconds for determining idle state", miner::BACKGROUND_MINING_DEFAULT_MIN_IDLE_INTERVAL_IN_SECONDS, true}; |
| 101 | const command_line::arg_descriptor<uint16_t> arg_bg_mining_idle_threshold_percentage = {"bg-mining-idle-threshold", "Specify minimum avg idle percentage over lookback interval", miner::BACKGROUND_MINING_DEFAULT_IDLE_THRESHOLD_PERCENTAGE, true}; |
| 102 | const command_line::arg_descriptor<uint16_t> arg_bg_mining_miner_target_percentage = {"bg-mining-miner-target", "Specify maximum percentage cpu use by miner(s)", miner::BACKGROUND_MINING_DEFAULT_MINING_TARGET_PERCENTAGE, true}; |
| 103 | } |
| 104 | |
| 105 | |
| 106 | miner::miner(i_miner_handler* phandler, const get_block_hash_t &gbh):m_stop(1), |
| 107 | m_template{}, |
| 108 | m_template_no(0), |
| 109 | m_diffic(0), |
| 110 | m_thread_index(0), |
| 111 | m_phandler(phandler), |
| 112 | m_gbh(gbh), |
| 113 | m_height(0), |
| 114 | m_threads_active(0), |
| 115 | m_pausers_count(0), |
| 116 | m_threads_total(0), |
| 117 | m_starter_nonce(0), |
| 118 | m_last_hr_merge_time(0), |
| 119 | m_hashes(0), |
| 120 | m_total_hashes(0), |
| 121 | m_do_print_hashrate(false), |
| 122 | m_do_mining(false), |
| 123 | m_current_hash_rate(0), |
| 124 | m_is_background_mining_enabled(false), |
| 125 | m_min_idle_seconds(BACKGROUND_MINING_DEFAULT_MIN_IDLE_INTERVAL_IN_SECONDS), |
| 126 | m_idle_threshold(BACKGROUND_MINING_DEFAULT_IDLE_THRESHOLD_PERCENTAGE), |
| 127 | m_mining_target(BACKGROUND_MINING_DEFAULT_MINING_TARGET_PERCENTAGE), |
| 128 | m_miner_extra_sleep(BACKGROUND_MINING_DEFAULT_MINER_EXTRA_SLEEP_MILLIS), |
| 129 | m_block_reward(0) |
| 130 | { |
| 131 | m_attrs.set_stack_size(THREAD_STACK_SIZE); |
| 132 | } |
| 133 | //----------------------------------------------------------------------------------------------------- |
| 134 | miner::~miner() |
| 135 | { |
| 136 | try { stop(); } |
| 137 | catch (...) { /* ignore */ } |
| 138 | } |
| 139 | //----------------------------------------------------------------------------------------------------- |
| 140 | bool miner::set_block_template(const block& bl, const difficulty_type& di, uint64_t height, uint64_t block_reward) |
| 141 | { |
| 142 | CRITICAL_REGION_LOCAL(m_template_lock); |
| 143 | m_template = bl; |
| 144 | m_diffic = di; |
| 145 | m_height = height; |
| 146 | m_block_reward = block_reward; |
| 147 | ++m_template_no; |
| 148 | m_starter_nonce = crypto::rand<uint32_t>(); |
| 149 | return true; |
| 150 | } |
| 151 | //----------------------------------------------------------------------------------------------------- |
| 152 | bool miner::on_block_chain_update() |
| 153 | { |
| 154 | if(!is_mining()) |
| 155 | return true; |
| 156 | |
| 157 | return request_block_template(); |
| 158 | } |
| 159 | //----------------------------------------------------------------------------------------------------- |
| 160 | bool miner::request_block_template() |
| 161 | { |
| 162 | block bl; |
| 163 | difficulty_type di = AUTO_VAL_INIT(di); |
| 164 | uint64_t height = AUTO_VAL_INIT(height); |
| 165 | uint64_t expected_reward; //only used for RPC calls - could possibly be useful here too? |
| 166 | |
| 167 | cryptonote::blobdata extra_nonce; |
| 168 | if(m_extra_messages.size() && m_config.current_extra_message_index < m_extra_messages.size()) |
| 169 | { |
| 170 | extra_nonce = m_extra_messages[m_config.current_extra_message_index]; |
| 171 | } |
| 172 | |
| 173 | uint64_t seed_height; |
| 174 | crypto::hash seed_hash; |
| 175 | if(!m_phandler->get_block_template(bl, m_mine_address, di, height, expected_reward, extra_nonce, seed_height, seed_hash)) |
| 176 | { |
| 177 | LOG_ERROR("Failed to get_block_template(), stopping mining"); |
| 178 | return false; |
| 179 | } |
| 180 | set_block_template(bl, di, height, expected_reward); |
| 181 | return true; |
| 182 | } |
| 183 | //----------------------------------------------------------------------------------------------------- |
| 184 | bool miner::on_idle() |
| 185 | { |
| 186 | m_update_block_template_interval.do_call([&](){ |
| 187 | if(is_mining())request_block_template(); |
| 188 | return true; |
| 189 | }); |
| 190 | |
| 191 | m_update_merge_hr_interval.do_call([&](){ |
| 192 | merge_hr(); |
| 193 | return true; |
| 194 | }); |
| 195 | |
| 196 | m_autodetect_interval.do_call([&](){ |
| 197 | update_autodetection(); |
| 198 | return true; |
| 199 | }); |
| 200 | |
| 201 | return true; |
| 202 | } |
| 203 | //----------------------------------------------------------------------------------------------------- |
| 204 | void miner::do_print_hashrate(bool do_hr) |
| 205 | { |
| 206 | m_do_print_hashrate = do_hr; |
| 207 | } |
| 208 | //----------------------------------------------------------------------------------------------------- |
| 209 | void miner::merge_hr() |
| 210 | { |
| 211 | if(m_last_hr_merge_time && is_mining()) |
| 212 | { |
| 213 | m_current_hash_rate = m_hashes * 1000 / ((misc_utils::get_tick_count() - m_last_hr_merge_time + 1)); |
| 214 | CRITICAL_REGION_LOCAL(m_last_hash_rates_lock); |
| 215 | m_last_hash_rates.push_back(m_current_hash_rate); |
| 216 | if(m_last_hash_rates.size() > 19) |
| 217 | m_last_hash_rates.pop_front(); |
| 218 | if(m_do_print_hashrate) |
| 219 | { |
| 220 | uint64_t total_hr = std::accumulate(m_last_hash_rates.begin(), m_last_hash_rates.end(), 0); |
| 221 | float hr = static_cast<float>(total_hr)/static_cast<float>(m_last_hash_rates.size()); |
| 222 | const auto flags = std::cout.flags(); |
| 223 | const auto precision = std::cout.precision(); |
| 224 | std::cout << "hashrate: " << std::setprecision(4) << std::fixed << hr << std::setiosflags(flags) << std::setprecision(precision) << ENDL; |
| 225 | } |
| 226 | } |
| 227 | m_last_hr_merge_time = misc_utils::get_tick_count(); |
| 228 | m_hashes = 0; |
| 229 | } |
| 230 | //----------------------------------------------------------------------------------------------------- |
| 231 | void miner::update_autodetection() |
| 232 | { |
| 233 | if (m_threads_autodetect.empty()) |
| 234 | return; |
| 235 | |
| 236 | uint64_t now = epee::misc_utils::get_ns_count(); |
| 237 | uint64_t dt = now - m_threads_autodetect.back().first; |
| 238 | if (dt < AUTODETECT_WINDOW * 1000000000ull) |
| 239 | return; |
| 240 | |
| 241 | // work out how many more hashes we got |
| 242 | m_threads_autodetect.back().first = dt; |
| 243 | uint64_t dh = m_total_hashes - m_threads_autodetect.back().second; |
| 244 | m_threads_autodetect.back().second = dh; |
| 245 | float hs = dh / (dt / (float)1000000000); |
| 246 | MGINFO("Mining autodetection: " << m_threads_autodetect.size() << " threads: " << hs << " H/s"); |
| 247 | |
| 248 | // when we don't increase by at least 2%, stop, otherwise check next |
| 249 | // if N and N+1 have mostly the same hash rate, we want to "lighter" one |
| 250 | bool found = false; |
| 251 | if (m_threads_autodetect.size() > 1) |
| 252 | { |
| 253 | int previdx = m_threads_autodetect.size() - 2; |
| 254 | float previous_hs = m_threads_autodetect[previdx].second / (m_threads_autodetect[previdx].first / (float)1000000000); |
| 255 | if (previous_hs > 0 && hs / previous_hs < AUTODETECT_GAIN_THRESHOLD) |
| 256 | { |
| 257 | m_threads_total = m_threads_autodetect.size() - 1; |
| 258 | m_threads_autodetect.clear(); |
| 259 | MGINFO("Optimal number of threads seems to be " << m_threads_total); |
| 260 | found = true; |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | if (!found) |
| 265 | { |
| 266 | // setup one more thread |
| 267 | m_threads_autodetect.push_back({now, m_total_hashes}); |
| 268 | m_threads_total = m_threads_autodetect.size(); |
| 269 | } |
| 270 | |
| 271 | // restart all threads |
| 272 | { |
| 273 | CRITICAL_REGION_LOCAL(m_threads_lock); |
| 274 | m_stop = true; |
| 275 | while (m_threads_active > 0) |
| 276 | misc_utils::sleep_no_w(100); |
| 277 | m_threads.clear(); |
| 278 | } |
| 279 | m_stop = false; |
| 280 | m_thread_index = 0; |
| 281 | for(size_t i = 0; i != m_threads_total; i++) |
| 282 | m_threads.push_back(boost::thread(m_attrs, boost::bind(&miner::worker_thread, this))); |
| 283 | } |
| 284 | //----------------------------------------------------------------------------------------------------- |
| 285 | void miner::init_options(boost::program_options::options_description& desc) |
| 286 | { |
| 287 | command_line::add_arg(desc, arg_extra_messages); |
| 288 | command_line::add_arg(desc, arg_start_mining); |
| 289 | command_line::add_arg(desc, arg_mining_threads); |
| 290 | command_line::add_arg(desc, arg_bg_mining_enable); |
| 291 | command_line::add_arg(desc, arg_bg_mining_ignore_battery); |
| 292 | command_line::add_arg(desc, arg_bg_mining_min_idle_interval_seconds); |
| 293 | command_line::add_arg(desc, arg_bg_mining_idle_threshold_percentage); |
| 294 | command_line::add_arg(desc, arg_bg_mining_miner_target_percentage); |
| 295 | } |
| 296 | //----------------------------------------------------------------------------------------------------- |
| 297 | bool miner::init(const boost::program_options::variables_map& vm, network_type nettype) |
| 298 | { |
| 299 | if(command_line::has_arg(vm, arg_extra_messages)) |
| 300 | { |
| 301 | std::string buff; |
| 302 | bool r = file_io_utils::load_file_to_string(command_line::get_arg(vm, arg_extra_messages), buff); |
| 303 | CHECK_AND_ASSERT_MES(r, false, "Failed to load file with extra messages: " << command_line::get_arg(vm, arg_extra_messages)); |
| 304 | std::vector<std::string> extra_vec; |
| 305 | boost::split(extra_vec, buff, boost::is_any_of("\n"), boost::token_compress_on ); |
| 306 | m_extra_messages.resize(extra_vec.size()); |
| 307 | for(size_t i = 0; i != extra_vec.size(); i++) |
| 308 | { |
| 309 | string_tools::trim(extra_vec[i]); |
| 310 | if(!extra_vec[i].size()) |
| 311 | continue; |
| 312 | std::string buff = string_encoding::base64_decode(extra_vec[i]); |
| 313 | if(buff != "0") |
| 314 | m_extra_messages[i] = buff; |
| 315 | } |
| 316 | m_config_folder_path = boost::filesystem::path(command_line::get_arg(vm, arg_extra_messages)).parent_path().string(); |
| 317 | m_config = AUTO_VAL_INIT(m_config); |
| 318 | const std::string filename = m_config_folder_path + "/" + MINER_CONFIG_FILE_NAME; |
| 319 | CHECK_AND_ASSERT_MES(epee::serialization::load_t_from_json_file(m_config, filename), false, "Failed to load data from " << filename); |
| 320 | MINFO("Loaded " << m_extra_messages.size() << " extra messages, current index " << m_config.current_extra_message_index); |
| 321 | } |
| 322 | |
| 323 | if(command_line::has_arg(vm, arg_start_mining)) |
| 324 | { |
| 325 | address_parse_info info; |
| 326 | if(!cryptonote::get_account_address_from_str(info, nettype, command_line::get_arg(vm, arg_start_mining)) || info.is_subaddress) |
| 327 | { |
| 328 | LOG_ERROR("Target account address " << command_line::get_arg(vm, arg_start_mining) << " has wrong format, starting daemon canceled"); |
| 329 | return false; |
| 330 | } |
| 331 | m_mine_address = info.address; |
| 332 | m_threads_total = 1; |
| 333 | m_do_mining = true; |
| 334 | if(command_line::has_arg(vm, arg_mining_threads)) |
| 335 | { |
| 336 | m_threads_total = command_line::get_arg(vm, arg_mining_threads); |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | // Background mining parameters |
| 341 | // Let init set all parameters even if background mining is not enabled, they can start later with params set |
| 342 | if(command_line::has_arg(vm, arg_bg_mining_enable)) |
| 343 | set_is_background_mining_enabled( command_line::get_arg(vm, arg_bg_mining_enable) ); |
| 344 | if(command_line::has_arg(vm, arg_bg_mining_ignore_battery)) |
| 345 | set_ignore_battery( command_line::get_arg(vm, arg_bg_mining_ignore_battery) ); |
| 346 | if(command_line::has_arg(vm, arg_bg_mining_min_idle_interval_seconds)) |
| 347 | set_min_idle_seconds( command_line::get_arg(vm, arg_bg_mining_min_idle_interval_seconds) ); |
| 348 | if(command_line::has_arg(vm, arg_bg_mining_idle_threshold_percentage)) |
| 349 | set_idle_threshold( command_line::get_arg(vm, arg_bg_mining_idle_threshold_percentage) ); |
| 350 | if(command_line::has_arg(vm, arg_bg_mining_miner_target_percentage)) |
| 351 | set_mining_target( command_line::get_arg(vm, arg_bg_mining_miner_target_percentage) ); |
| 352 | |
| 353 | return true; |
| 354 | } |
| 355 | //----------------------------------------------------------------------------------------------------- |
| 356 | bool miner::is_mining() const |
| 357 | { |
| 358 | return !m_stop; |
| 359 | } |
| 360 | //----------------------------------------------------------------------------------------------------- |
| 361 | const account_public_address& miner::get_mining_address() const |
| 362 | { |
| 363 | return m_mine_address; |
| 364 | } |
| 365 | //----------------------------------------------------------------------------------------------------- |
| 366 | uint32_t miner::get_threads_count() const { |
| 367 | return m_threads_total; |
| 368 | } |
| 369 | //----------------------------------------------------------------------------------------------------- |
| 370 | bool miner::start(const account_public_address& adr, size_t threads_count, bool do_background, bool ignore_battery) |
| 371 | { |
| 372 | m_block_reward = 0; |
| 373 | m_mine_address = adr; |
| 374 | m_threads_total = static_cast<uint32_t>(threads_count); |
| 375 | if (threads_count == 0) |
| 376 | { |
| 377 | m_threads_autodetect.clear(); |
| 378 | m_threads_autodetect.push_back({epee::misc_utils::get_ns_count(), m_total_hashes}); |
| 379 | m_threads_total = 1; |
| 380 | } |
| 381 | m_starter_nonce = crypto::rand<uint32_t>(); |
| 382 | CRITICAL_REGION_LOCAL(m_threads_lock); |
| 383 | if(is_mining()) |
| 384 | { |
| 385 | LOG_ERROR("Starting miner but it's already started"); |
| 386 | return false; |
| 387 | } |
| 388 | |
| 389 | if(!m_threads.empty()) |
| 390 | { |
| 391 | LOG_ERROR("Unable to start miner because there are active mining threads"); |
| 392 | return false; |
| 393 | } |
| 394 | |
| 395 | request_block_template();//lets update block template |
| 396 | |
| 397 | m_stop = false; |
| 398 | m_thread_index = 0; |
| 399 | set_is_background_mining_enabled(do_background); |
| 400 | set_ignore_battery(ignore_battery); |
| 401 | |
| 402 | for(size_t i = 0; i != m_threads_total; i++) |
| 403 | { |
| 404 | m_threads.push_back(boost::thread(m_attrs, boost::bind(&miner::worker_thread, this))); |
| 405 | } |
| 406 | |
| 407 | if (threads_count == 0) |
| 408 | MINFO("Mining has started, autodetecting optimal number of threads, good luck!" ); |
| 409 | else |
| 410 | MINFO("Mining has started with " << threads_count << " threads, good luck!" ); |
| 411 | |
| 412 | if( get_is_background_mining_enabled() ) |
| 413 | { |
| 414 | m_background_mining_thread = boost::thread(m_attrs, boost::bind(&miner::background_worker_thread, this)); |
| 415 | LOG_PRINT_L0("Background mining controller thread started" ); |
| 416 | } |
| 417 | |
| 418 | if(get_ignore_battery()) |
| 419 | { |
| 420 | MINFO("Ignoring battery"); |
| 421 | } |
| 422 | |
| 423 | return true; |
| 424 | } |
| 425 | //----------------------------------------------------------------------------------------------------- |
| 426 | uint64_t miner::get_speed() const |
| 427 | { |
| 428 | if(is_mining()) { |
| 429 | return m_current_hash_rate; |
| 430 | } |
| 431 | else { |
| 432 | return 0; |
| 433 | } |
| 434 | } |
| 435 | //----------------------------------------------------------------------------------------------------- |
| 436 | void miner::send_stop_signal() |
| 437 | { |
| 438 | m_stop = true; |
| 439 | } |
| 440 | //----------------------------------------------------------------------------------------------------- |
| 441 | bool miner::stop() |
| 442 | { |
| 443 | MTRACE("Miner has received stop signal"); |
| 444 | |
| 445 | CRITICAL_REGION_LOCAL(m_threads_lock); |
| 446 | bool mining = !m_threads.empty(); |
| 447 | if (!mining) |
| 448 | { |
| 449 | MTRACE("Not mining - nothing to stop" ); |
| 450 | return true; |
| 451 | } |
| 452 | |
| 453 | send_stop_signal(); |
| 454 | |
| 455 | // In case background mining was active and the miner threads are waiting |
| 456 | // on the background miner to signal start. |
| 457 | while (m_threads_active > 0) |
| 458 | { |
| 459 | m_is_background_mining_started_cond.notify_all(); |
| 460 | misc_utils::sleep_no_w(100); |
| 461 | } |
| 462 | |
| 463 | // The background mining thread could be sleeping for a long time, so we |
| 464 | // interrupt it just in case |
| 465 | m_background_mining_thread.interrupt(); |
| 466 | m_background_mining_thread.join(); |
| 467 | m_is_background_mining_enabled = false; |
| 468 | |
| 469 | MINFO("Mining has been stopped, " << m_threads.size() << " finished" ); |
| 470 | m_threads.clear(); |
| 471 | m_threads_autodetect.clear(); |
| 472 | return true; |
| 473 | } |
| 474 | //----------------------------------------------------------------------------------------------------- |
| 475 | bool miner::find_nonce_for_given_block(const get_block_hash_t &gbh, block& bl, const difficulty_type& diffic, uint64_t height, const crypto::hash *seed_hash) |
| 476 | { |
| 477 | for(; bl.nonce != std::numeric_limits<uint32_t>::max(); bl.nonce++) |
| 478 | { |
| 479 | crypto::hash h; |
| 480 | gbh(bl, height, seed_hash, diffic <= 100 ? 0 : tools::get_max_concurrency(), h); |
| 481 | |
| 482 | if(check_hash(h, diffic)) |
| 483 | { |
| 484 | bl.invalidate_hashes(); |
| 485 | return true; |
| 486 | } |
| 487 | } |
| 488 | bl.invalidate_hashes(); |
| 489 | return false; |
| 490 | } |
| 491 | //----------------------------------------------------------------------------------------------------- |
| 492 | void miner::on_synchronized() |
| 493 | { |
| 494 | if(m_do_mining) |
| 495 | { |
| 496 | start(m_mine_address, m_threads_total, get_is_background_mining_enabled(), get_ignore_battery()); |
| 497 | } |
| 498 | } |
| 499 | //----------------------------------------------------------------------------------------------------- |
| 500 | void miner::pause() |
| 501 | { |
| 502 | CRITICAL_REGION_LOCAL(m_miners_count_lock); |
| 503 | MDEBUG("miner::pause: " << m_pausers_count << " -> " << (m_pausers_count + 1)); |
| 504 | ++m_pausers_count; |
| 505 | if(m_pausers_count == 1 && is_mining()) |
| 506 | MDEBUG("MINING PAUSED"); |
| 507 | } |
| 508 | //----------------------------------------------------------------------------------------------------- |
| 509 | void miner::resume() |
| 510 | { |
| 511 | CRITICAL_REGION_LOCAL(m_miners_count_lock); |
| 512 | MDEBUG("miner::resume: " << m_pausers_count << " -> " << (m_pausers_count - 1)); |
| 513 | --m_pausers_count; |
| 514 | if(m_pausers_count < 0) |
| 515 | { |
| 516 | m_pausers_count = 0; |
| 517 | MERROR("Unexpected miner::resume() called"); |
| 518 | } |
| 519 | if(!m_pausers_count && is_mining()) |
| 520 | MDEBUG("MINING RESUMED"); |
| 521 | } |
| 522 | //----------------------------------------------------------------------------------------------------- |
| 523 | bool miner::worker_thread() |
| 524 | { |
| 525 | const uint32_t th_local_index = m_thread_index++; // atomically increment, getting value before increment |
| 526 | bool rx_set = false; |
| 527 | |
| 528 | MLOG_SET_THREAD_NAME(std::string("[miner ") + std::to_string(th_local_index) + "]"); |
| 529 | MGINFO("Miner thread was started ["<< th_local_index << "]"); |
| 530 | uint32_t nonce = m_starter_nonce + th_local_index; |
| 531 | uint64_t height = 0; |
| 532 | difficulty_type local_diff = 0; |
| 533 | uint32_t local_template_ver = 0; |
| 534 | block b; |
| 535 | slow_hash_allocate_state(); |
| 536 | ++m_threads_active; |
| 537 | while(!m_stop) |
| 538 | { |
| 539 | if(m_pausers_count)//anti split workaround |
| 540 | { |
| 541 | misc_utils::sleep_no_w(100); |
| 542 | continue; |
| 543 | } |
| 544 | else if( m_is_background_mining_enabled ) |
| 545 | { |
| 546 | misc_utils::sleep_no_w(m_miner_extra_sleep); |
| 547 | while( !m_is_background_mining_started ) |
| 548 | { |
| 549 | MGINFO("background mining is enabled, but not started, waiting until start triggers"); |
| 550 | boost::unique_lock<boost::mutex> started_lock( m_is_background_mining_started_mutex ); |
| 551 | m_is_background_mining_started_cond.wait( started_lock ); |
| 552 | if( m_stop ) break; |
| 553 | } |
| 554 | |
| 555 | if( m_stop ) continue; |
| 556 | } |
| 557 | |
| 558 | if(local_template_ver != m_template_no) |
| 559 | { |
| 560 | CRITICAL_REGION_BEGIN(m_template_lock); |
| 561 | b = m_template; |
| 562 | local_diff = m_diffic; |
| 563 | height = m_height; |
| 564 | CRITICAL_REGION_END(); |
| 565 | local_template_ver = m_template_no; |
| 566 | nonce = m_starter_nonce + th_local_index; |
| 567 | } |
| 568 | |
| 569 | if(!local_template_ver)//no any set_block_template call |
| 570 | { |
| 571 | LOG_PRINT_L2("Block template not set yet"); |
| 572 | epee::misc_utils::sleep_no_w(1000); |
| 573 | continue; |
| 574 | } |
| 575 | |
| 576 | b.nonce = nonce; |
| 577 | crypto::hash h; |
| 578 | |
| 579 | if ((b.major_version >= RX_BLOCK_VERSION) && !rx_set) |
| 580 | { |
| 581 | crypto::rx_set_miner_thread(th_local_index, tools::get_max_concurrency()); |
| 582 | rx_set = true; |
| 583 | } |
| 584 | |
| 585 | m_gbh(b, height, NULL, tools::get_max_concurrency(), h); |
| 586 | |
| 587 | if(check_hash(h, local_diff)) |
| 588 | { |
| 589 | //we lucky! |
| 590 | ++m_config.current_extra_message_index; |
| 591 | MGINFO_GREEN("Found block " << get_block_hash(b) << " at height " << height << " for difficulty: " << local_diff); |
| 592 | cryptonote::block_verification_context bvc; |
| 593 | if(!m_phandler->handle_block_found(b, bvc) || !bvc.m_added_to_main_chain) |
| 594 | { |
| 595 | --m_config.current_extra_message_index; |
| 596 | }else |
| 597 | { |
| 598 | //success update, lets update config |
| 599 | if (!m_config_folder_path.empty()) |
| 600 | epee::serialization::store_t_to_json_file(m_config, m_config_folder_path + "/" + MINER_CONFIG_FILE_NAME); |
| 601 | } |
| 602 | } |
| 603 | nonce+=m_threads_total; |
| 604 | ++m_hashes; |
| 605 | ++m_total_hashes; |
| 606 | } |
| 607 | slow_hash_free_state(); |
| 608 | MGINFO("Miner thread stopped ["<< th_local_index << "]"); |
| 609 | --m_threads_active; |
| 610 | return true; |
| 611 | } |
| 612 | //----------------------------------------------------------------------------------------------------- |
| 613 | bool miner::get_is_background_mining_enabled() const |
| 614 | { |
| 615 | return m_is_background_mining_enabled; |
| 616 | } |
| 617 | //----------------------------------------------------------------------------------------------------- |
| 618 | bool miner::get_ignore_battery() const |
| 619 | { |
| 620 | return m_ignore_battery; |
| 621 | } |
| 622 | //----------------------------------------------------------------------------------------------------- |
| 623 | /** |
| 624 | * This has differing behaviour depending on if mining has been started/etc. |
| 625 | * Note: add documentation |
| 626 | */ |
| 627 | bool miner::set_is_background_mining_enabled(bool is_background_mining_enabled) |
| 628 | { |
| 629 | m_is_background_mining_enabled = is_background_mining_enabled; |
| 630 | // Extra logic will be required if we make this function public in the future |
| 631 | // and allow toggling smart mining without start/stop |
| 632 | //m_is_background_mining_enabled_cond.notify_one(); |
| 633 | return true; |
| 634 | } |
| 635 | //----------------------------------------------------------------------------------------------------- |
| 636 | void miner::set_ignore_battery(bool ignore_battery) |
| 637 | { |
| 638 | m_ignore_battery = ignore_battery; |
| 639 | } |
| 640 | //----------------------------------------------------------------------------------------------------- |
| 641 | uint64_t miner::get_min_idle_seconds() const |
| 642 | { |
| 643 | return m_min_idle_seconds; |
| 644 | } |
| 645 | //----------------------------------------------------------------------------------------------------- |
| 646 | bool miner::set_min_idle_seconds(uint64_t min_idle_seconds) |
| 647 | { |
| 648 | if(min_idle_seconds > BACKGROUND_MINING_MAX_MIN_IDLE_INTERVAL_IN_SECONDS) return false; |
| 649 | if(min_idle_seconds < BACKGROUND_MINING_MIN_MIN_IDLE_INTERVAL_IN_SECONDS) return false; |
| 650 | m_min_idle_seconds = min_idle_seconds; |
| 651 | return true; |
| 652 | } |
| 653 | //----------------------------------------------------------------------------------------------------- |
| 654 | uint8_t miner::get_idle_threshold() const |
| 655 | { |
| 656 | return m_idle_threshold; |
| 657 | } |
| 658 | //----------------------------------------------------------------------------------------------------- |
| 659 | bool miner::set_idle_threshold(uint8_t idle_threshold) |
| 660 | { |
| 661 | if(idle_threshold > BACKGROUND_MINING_MAX_IDLE_THRESHOLD_PERCENTAGE) return false; |
| 662 | if(idle_threshold < BACKGROUND_MINING_MIN_IDLE_THRESHOLD_PERCENTAGE) return false; |
| 663 | m_idle_threshold = idle_threshold; |
| 664 | return true; |
| 665 | } |
| 666 | //----------------------------------------------------------------------------------------------------- |
| 667 | uint8_t miner::get_mining_target() const |
| 668 | { |
| 669 | return m_mining_target; |
| 670 | } |
| 671 | //----------------------------------------------------------------------------------------------------- |
| 672 | bool miner::set_mining_target(uint8_t mining_target) |
| 673 | { |
| 674 | if(mining_target > BACKGROUND_MINING_MAX_MINING_TARGET_PERCENTAGE) return false; |
| 675 | if(mining_target < BACKGROUND_MINING_MIN_MINING_TARGET_PERCENTAGE) return false; |
| 676 | m_mining_target = mining_target; |
| 677 | return true; |
| 678 | } |
| 679 | //----------------------------------------------------------------------------------------------------- |
| 680 | bool miner::background_worker_thread() |
| 681 | { |
| 682 | uint64_t prev_total_time, current_total_time; |
| 683 | uint64_t prev_idle_time, current_idle_time; |
| 684 | uint64_t previous_process_time = 0, current_process_time = 0; |
| 685 | m_is_background_mining_started = false; |
| 686 | |
| 687 | if(!get_system_times(prev_total_time, prev_idle_time)) |
| 688 | { |
| 689 | LOG_ERROR("get_system_times call failed, background mining will NOT work!"); |
| 690 | return false; |
| 691 | } |
| 692 | |
| 693 | while(!m_stop) |
| 694 | { |
| 695 | |
| 696 | try |
| 697 | { |
| 698 | // Commenting out the below since we're going with privatizing the bg mining enabled |
| 699 | // function, but I'll leave the code/comments here for anyone that wants to modify the |
| 700 | // patch in the future |
| 701 | // ------------------------------------------------------------------------------------- |
| 702 | // All of this might be overkill if we just enforced some simple requirements |
| 703 | // about changing this variable before/after the miner starts, but I envision |
| 704 | // in the future a checkbox that you can tick on/off for background mining after |
| 705 | // you've clicked "start mining". There's still an issue here where if background |
| 706 | // mining is disabled when start is called, this thread is never created, and so |
| 707 | // enabling after does nothing, something I have to fix in the future. However, |
| 708 | // this should take care of the case where mining is started with bg-enabled, |
| 709 | // and then the user decides to un-check background mining, and just do |
| 710 | // regular full-speed mining. I might just be over-doing it and thinking up |
| 711 | // non-existant use-cases, so if the consensus is to simplify, we can remove all this fluff. |
| 712 | /* |
| 713 | while( !m_is_background_mining_enabled ) |
| 714 | { |
| 715 | MGINFO("background mining is disabled, waiting until enabled!"); |
| 716 | boost::unique_lock<boost::mutex> enabled_lock( m_is_background_mining_enabled_mutex ); |
| 717 | m_is_background_mining_enabled_cond.wait( enabled_lock ); |
| 718 | } |
| 719 | */ |
| 720 | |
| 721 | // If we're already mining, then sleep for the miner monitor interval. |
| 722 | // If we're NOT mining, then sleep for the idle monitor interval |
| 723 | uint64_t sleep_for_seconds = BACKGROUND_MINING_MINER_MONITOR_INVERVAL_IN_SECONDS; |
| 724 | if( !m_is_background_mining_started ) sleep_for_seconds = get_min_idle_seconds(); |
| 725 | boost::this_thread::sleep_for(boost::chrono::seconds(sleep_for_seconds)); |
| 726 | } |
| 727 | catch(const boost::thread_interrupted&) |
| 728 | { |
| 729 | MDEBUG("background miner thread interrupted "); |
| 730 | continue; // if interrupted because stop called, loop should end .. |
| 731 | } |
| 732 | |
| 733 | bool on_ac_power = m_ignore_battery; |
| 734 | if(!m_ignore_battery) |
| 735 | { |
| 736 | boost::tribool battery_powered(on_battery_power()); |
| 737 | if(!indeterminate( battery_powered )) |
| 738 | { |
| 739 | on_ac_power = !(bool)battery_powered; |
| 740 | } |
| 741 | } |
| 742 | |
| 743 | if( m_is_background_mining_started ) |
| 744 | { |
| 745 | // figure out if we need to stop, and monitor mining usage |
| 746 | |
| 747 | // If we get here, then previous values are initialized. |
| 748 | // Let's get some current data for comparison. |
| 749 | |
| 750 | if(!get_system_times(current_total_time, current_idle_time)) |
| 751 | { |
| 752 | MERROR("get_system_times call failed"); |
| 753 | continue; |
| 754 | } |
| 755 | |
| 756 | if(!get_process_time(current_process_time)) |
| 757 | { |
| 758 | MERROR("get_process_time call failed!"); |
| 759 | continue; |
| 760 | } |
| 761 | |
| 762 | uint64_t total_diff = (current_total_time - prev_total_time); |
| 763 | uint64_t idle_diff = (current_idle_time - prev_idle_time); |
| 764 | uint64_t process_diff = (current_process_time - previous_process_time); |
| 765 | uint8_t idle_percentage = get_percent_of_total(idle_diff, total_diff); |
| 766 | uint8_t process_percentage = get_percent_of_total(process_diff, total_diff); |
| 767 | |
| 768 | MDEBUG("idle percentage is " << unsigned(idle_percentage) << "\%, miner percentage is " << unsigned(process_percentage) << "\%, ac power : " << on_ac_power); |
| 769 | if( idle_percentage + process_percentage < get_idle_threshold() || !on_ac_power ) |
| 770 | { |
| 771 | MINFO("cpu is " << unsigned(idle_percentage) << "% idle, idle threshold is " << unsigned(get_idle_threshold()) << "\%, ac power : " << on_ac_power << ", background mining stopping, thanks for your contribution!"); |
| 772 | m_is_background_mining_started = false; |
| 773 | |
| 774 | // reset process times |
| 775 | previous_process_time = 0; |
| 776 | current_process_time = 0; |
| 777 | } |
| 778 | else |
| 779 | { |
| 780 | previous_process_time = current_process_time; |
| 781 | |
| 782 | // adjust the miner extra sleep variable |
| 783 | int64_t miner_extra_sleep_change = (-1 * (get_mining_target() - process_percentage) ); |
| 784 | int64_t new_miner_extra_sleep = m_miner_extra_sleep + miner_extra_sleep_change; |
| 785 | // if you start the miner with few threads on a multicore system, this could |
| 786 | // fall below zero because all the time functions aggregate across all processors. |
| 787 | // I'm just hard limiting to 5 millis min sleep here, other options? |
| 788 | m_miner_extra_sleep = std::max( new_miner_extra_sleep , (int64_t)5 ); |
| 789 | MDEBUG("m_miner_extra_sleep " << m_miner_extra_sleep); |
| 790 | } |
| 791 | |
| 792 | prev_total_time = current_total_time; |
| 793 | prev_idle_time = current_idle_time; |
| 794 | } |
| 795 | else if( on_ac_power ) |
| 796 | { |
| 797 | // figure out if we need to start |
| 798 | |
| 799 | if(!get_system_times(current_total_time, current_idle_time)) |
| 800 | { |
| 801 | MERROR("get_system_times call failed"); |
| 802 | continue; |
| 803 | } |
| 804 | |
| 805 | uint64_t total_diff = (current_total_time - prev_total_time); |
| 806 | uint64_t idle_diff = (current_idle_time - prev_idle_time); |
| 807 | uint8_t idle_percentage = get_percent_of_total(idle_diff, total_diff); |
| 808 | |
| 809 | MDEBUG("idle percentage is " << unsigned(idle_percentage)); |
| 810 | if( idle_percentage >= get_idle_threshold() && on_ac_power ) |
| 811 | { |
| 812 | MINFO("cpu is " << unsigned(idle_percentage) << "% idle, idle threshold is " << unsigned(get_idle_threshold()) << "\%, ac power : " << on_ac_power << ", background mining started, good luck!"); |
| 813 | m_is_background_mining_started = true; |
| 814 | m_is_background_mining_started_cond.notify_all(); |
| 815 | |
| 816 | // Wait for a little mining to happen .. |
| 817 | boost::this_thread::sleep_for(boost::chrono::seconds( 1 )); |
| 818 | |
| 819 | // Starting data ... |
| 820 | if(!get_process_time(previous_process_time)) |
| 821 | { |
| 822 | m_is_background_mining_started = false; |
| 823 | MERROR("get_process_time call failed!"); |
| 824 | } |
| 825 | } |
| 826 | |
| 827 | prev_total_time = current_total_time; |
| 828 | prev_idle_time = current_idle_time; |
| 829 | } |
| 830 | } |
| 831 | |
| 832 | return true; |
| 833 | } |
| 834 | //----------------------------------------------------------------------------------------------------- |
| 835 | bool miner::get_system_times(uint64_t& total_time, uint64_t& idle_time) |
| 836 | { |
| 837 | #ifdef _WIN32 |
| 838 | |
| 839 | FILETIME idleTime; |
| 840 | FILETIME kernelTime; |
| 841 | FILETIME userTime; |
| 842 | if ( GetSystemTimes( &idleTime, &kernelTime, &userTime ) != -1 ) |
| 843 | { |
| 844 | total_time = |
| 845 | ( (((uint64_t)(kernelTime.dwHighDateTime)) << 32) | ((uint64_t)kernelTime.dwLowDateTime) ) |
| 846 | + ( (((uint64_t)(userTime.dwHighDateTime)) << 32) | ((uint64_t)userTime.dwLowDateTime) ); |
| 847 | |
| 848 | idle_time = ( (((uint64_t)(idleTime.dwHighDateTime)) << 32) | ((uint64_t)idleTime.dwLowDateTime) ); |
| 849 | |
| 850 | return true; |
| 851 | } |
| 852 | |
| 853 | #elif defined(__linux__) |
| 854 | |
| 855 | const std::string STAT_FILE_PATH = "/proc/stat"; |
| 856 | |
| 857 | if( !epee::file_io_utils::is_file_exist(STAT_FILE_PATH) ) |
| 858 | { |
| 859 | LOG_ERROR("'" << STAT_FILE_PATH << "' file does not exist"); |
| 860 | return false; |
| 861 | } |
| 862 | |
| 863 | std::ifstream stat_file_stream(STAT_FILE_PATH); |
| 864 | if( stat_file_stream.fail() ) |
| 865 | { |
| 866 | LOG_ERROR("failed to open '" << STAT_FILE_PATH << "'"); |
| 867 | return false; |
| 868 | } |
| 869 | |
| 870 | std::string line; |
| 871 | std::getline(stat_file_stream, line); |
| 872 | std::istringstream stat_file_iss(line); |
| 873 | stat_file_iss.ignore(65536, ' '); // skip cpu label ... |
| 874 | uint64_t utime, ntime, stime, itime; |
| 875 | if( !(stat_file_iss >> utime && stat_file_iss >> ntime && stat_file_iss >> stime && stat_file_iss >> itime) ) |
| 876 | { |
| 877 | LOG_ERROR("failed to read '" << STAT_FILE_PATH << "'"); |
| 878 | return false; |
| 879 | } |
| 880 | |
| 881 | idle_time = itime; |
| 882 | total_time = utime + ntime + stime + itime; |
| 883 | |
| 884 | return true; |
| 885 | |
| 886 | #elif defined(__APPLE__) |
| 887 | |
| 888 | mach_msg_type_number_t count; |
| 889 | kern_return_t status; |
| 890 | host_cpu_load_info_data_t stats; |
| 891 | count = HOST_CPU_LOAD_INFO_COUNT; |
| 892 | status = host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, (host_info_t)&stats, &count); |
| 893 | if(status != KERN_SUCCESS) |
| 894 | { |
| 895 | return false; |
| 896 | } |
| 897 | |
| 898 | idle_time = stats.cpu_ticks[CPU_STATE_IDLE]; |
| 899 | total_time = idle_time + stats.cpu_ticks[CPU_STATE_USER] + stats.cpu_ticks[CPU_STATE_SYSTEM]; |
| 900 | |
| 901 | return true; |
| 902 | |
| 903 | #elif defined(__FreeBSD__) |
| 904 | |
| 905 | struct statinfo s; |
| 906 | size_t n = sizeof(s.cp_time); |
| 907 | if( sysctlbyname("kern.cp_time", s.cp_time, &n, NULL, 0) == -1 ) |
| 908 | { |
| 909 | LOG_ERROR("sysctlbyname(\"kern.cp_time\"): " << strerror(errno)); |
| 910 | return false; |
| 911 | } |
| 912 | if( n != sizeof(s.cp_time) ) |
| 913 | { |
| 914 | LOG_ERROR("sysctlbyname(\"kern.cp_time\") output is unexpectedly " |
| 915 | << n << " bytes instead of the expected " << sizeof(s.cp_time) |
| 916 | << " bytes."); |
| 917 | return false; |
| 918 | } |
| 919 | |
| 920 | idle_time = s.cp_time[CP_IDLE]; |
| 921 | total_time = |
| 922 | s.cp_time[CP_USER] + |
| 923 | s.cp_time[CP_NICE] + |
| 924 | s.cp_time[CP_SYS] + |
| 925 | s.cp_time[CP_INTR] + |
| 926 | s.cp_time[CP_IDLE]; |
| 927 | |
| 928 | return true; |
| 929 | |
| 930 | #endif |
| 931 | |
| 932 | return false; // unsupported system |
| 933 | } |
| 934 | //----------------------------------------------------------------------------------------------------- |
| 935 | bool miner::get_process_time(uint64_t& total_time) |
| 936 | { |
| 937 | #ifdef _WIN32 |
| 938 | |
| 939 | FILETIME createTime; |
| 940 | FILETIME exitTime; |
| 941 | FILETIME kernelTime; |
| 942 | FILETIME userTime; |
| 943 | if ( GetProcessTimes( GetCurrentProcess(), &createTime, &exitTime, &kernelTime, &userTime ) != -1 ) |
| 944 | { |
| 945 | total_time = |
| 946 | ( (((uint64_t)(kernelTime.dwHighDateTime)) << 32) | ((uint64_t)kernelTime.dwLowDateTime) ) |
| 947 | + ( (((uint64_t)(userTime.dwHighDateTime)) << 32) | ((uint64_t)userTime.dwLowDateTime) ); |
| 948 | |
| 949 | return true; |
| 950 | } |
| 951 | |
| 952 | #elif (defined(__linux__) && defined(_SC_CLK_TCK)) || defined(__APPLE__) || defined(__FreeBSD__) |
| 953 | |
| 954 | struct tms tms; |
| 955 | if ( times(&tms) != (clock_t)-1 ) |
| 956 | { |
| 957 | total_time = tms.tms_utime + tms.tms_stime; |
| 958 | return true; |
| 959 | } |
| 960 | |
| 961 | #endif |
| 962 | |
| 963 | return false; // unsupported system |
| 964 | } |
| 965 | //----------------------------------------------------------------------------------------------------- |
| 966 | uint8_t miner::get_percent_of_total(uint64_t other, uint64_t total) |
| 967 | { |
| 968 | return (uint8_t)( ceil( (other * 1.f / total * 1.f) * 100) ); |
| 969 | } |
| 970 | //----------------------------------------------------------------------------------------------------- |
| 971 | boost::logic::tribool miner::on_battery_power() |
| 972 | { |
| 973 | #ifdef _WIN32 |
| 974 | |
| 975 | SYSTEM_POWER_STATUS power_status; |
| 976 | if ( GetSystemPowerStatus( &power_status ) != 0 ) |
| 977 | { |
| 978 | return boost::logic::tribool(power_status.ACLineStatus != 1); |
| 979 | } |
| 980 | |
| 981 | #elif defined(__APPLE__) |
| 982 | |
| 983 | #if TARGET_OS_MAC && (!defined(MAC_OS_X_VERSION_MIN_REQUIRED) || MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_7) |
| 984 | return boost::logic::tribool(IOPSGetTimeRemainingEstimate() != kIOPSTimeRemainingUnlimited); |
| 985 | #else |
| 986 | // iOS or OSX <10.7 |
| 987 | return boost::logic::tribool(boost::logic::indeterminate); |
| 988 | #endif |
| 989 | |
| 990 | #elif defined(__linux__) |
| 991 | |
| 992 | // Use the power_supply class http://lxr.linux.no/#linux+v4.10.1/Documentation/power/power_supply_class.txt |
| 993 | std::string power_supply_class_path = "/sys/class/power_supply"; |
| 994 | |
| 995 | boost::tribool on_battery = boost::logic::tribool(boost::logic::indeterminate); |
| 996 | if (boost::filesystem::is_directory(power_supply_class_path)) |
| 997 | { |
| 998 | const boost::filesystem::directory_iterator end_itr; |
| 999 | for (boost::filesystem::directory_iterator iter(power_supply_class_path); iter != end_itr; ++iter) |
| 1000 | { |
| 1001 | const boost::filesystem::path& power_supply_path = iter->path(); |
| 1002 | if (boost::filesystem::is_directory(power_supply_path)) |
| 1003 | { |
| 1004 | boost::filesystem::path power_supply_type_path = power_supply_path / "type"; |
| 1005 | if (boost::filesystem::is_regular_file(power_supply_type_path)) |
| 1006 | { |
| 1007 | std::ifstream power_supply_type_stream(power_supply_type_path.string()); |
| 1008 | if (power_supply_type_stream.fail()) |
| 1009 | { |
| 1010 | LOG_PRINT_L0("Unable to read from " << power_supply_type_path << " to check power supply type"); |
| 1011 | continue; |
| 1012 | } |
| 1013 | |
| 1014 | std::string power_supply_type; |
| 1015 | std::getline(power_supply_type_stream, power_supply_type); |
| 1016 | |
| 1017 | // If there is an AC adapter that's present and online we can break early |
| 1018 | if (boost::starts_with(power_supply_type, "Mains")) |
| 1019 | { |
| 1020 | boost::filesystem::path power_supply_online_path = power_supply_path / "online"; |
| 1021 | if (boost::filesystem::is_regular_file(power_supply_online_path)) |
| 1022 | { |
| 1023 | std::ifstream power_supply_online_stream(power_supply_online_path.string()); |
| 1024 | if (power_supply_online_stream.fail()) |
| 1025 | { |
| 1026 | LOG_PRINT_L0("Unable to read from " << power_supply_online_path << " to check ac power supply status"); |
| 1027 | continue; |
| 1028 | } |
| 1029 | |
| 1030 | if (power_supply_online_stream.get() == '1') |
| 1031 | { |
| 1032 | return boost::logic::tribool(false); |
| 1033 | } |
| 1034 | } |
| 1035 | } |
| 1036 | else if (boost::starts_with(power_supply_type, "Battery") && boost::logic::indeterminate(on_battery)) |
| 1037 | { |
| 1038 | boost::filesystem::path power_supply_status_path = power_supply_path / "status"; |
| 1039 | if (boost::filesystem::is_regular_file(power_supply_status_path)) |
| 1040 | { |
| 1041 | std::ifstream power_supply_status_stream(power_supply_status_path.string()); |
| 1042 | if (power_supply_status_stream.fail()) |
| 1043 | { |
| 1044 | LOG_PRINT_L0("Unable to read from " << power_supply_status_path << " to check battery power supply status"); |
| 1045 | continue; |
| 1046 | } |
| 1047 | |
| 1048 | // Possible status are Charging, Full, Discharging, Not Charging, and Unknown |
| 1049 | // We are only need to handle negative states right now |
| 1050 | std::string power_supply_status; |
| 1051 | std::getline(power_supply_status_stream, power_supply_status); |
| 1052 | if (boost::starts_with(power_supply_status, "Charging") || boost::starts_with(power_supply_status, "Full")) |
| 1053 | { |
| 1054 | on_battery = boost::logic::tribool(false); |
| 1055 | } |
| 1056 | |
| 1057 | if (boost::starts_with(power_supply_status, "Discharging")) |
| 1058 | { |
| 1059 | on_battery = boost::logic::tribool(true); |
| 1060 | } |
| 1061 | } |
| 1062 | } |
| 1063 | } |
| 1064 | } |
| 1065 | } |
| 1066 | } |
| 1067 | |
| 1068 | if (boost::logic::indeterminate(on_battery)) |
| 1069 | { |
| 1070 | static bool error_shown = false; |
| 1071 | if (!error_shown) |
| 1072 | { |
| 1073 | LOG_ERROR("couldn't query power status from " << power_supply_class_path); |
| 1074 | error_shown = true; |
| 1075 | } |
| 1076 | } |
| 1077 | return on_battery; |
| 1078 | |
| 1079 | #elif defined(__FreeBSD__) |
| 1080 | int ac; |
| 1081 | size_t n = sizeof(ac); |
| 1082 | if( sysctlbyname("hw.acpi.acline", &ac, &n, NULL, 0) == -1 ) |
| 1083 | { |
| 1084 | if( errno != ENOENT ) |
| 1085 | { |
| 1086 | LOG_ERROR("Cannot query battery status: " |
| 1087 | << "sysctlbyname(\"hw.acpi.acline\"): " << strerror(errno)); |
| 1088 | return boost::logic::tribool(boost::logic::indeterminate); |
| 1089 | } |
| 1090 | |
| 1091 | // If sysctl fails with ENOENT, then try querying /dev/apm. |
| 1092 | |
| 1093 | static const char* dev_apm = "/dev/apm"; |
| 1094 | const int fd = open(dev_apm, O_RDONLY); |
| 1095 | if( fd == -1 ) { |
| 1096 | LOG_ERROR("Cannot query battery status: " |
| 1097 | << "open(): " << dev_apm << ": " << strerror(errno)); |
| 1098 | return boost::logic::tribool(boost::logic::indeterminate); |
| 1099 | } |
| 1100 | |
| 1101 | #if defined(__amd64__) || defined(__i386__) || defined(__x86_64__) |
| 1102 | apm_info info; |
| 1103 | if( ioctl(fd, APMIO_GETINFO, &info) == -1 ) { |
| 1104 | close(fd); |
| 1105 | LOG_ERROR("Cannot query battery status: " |
| 1106 | << "ioctl(" << dev_apm << ", APMIO_GETINFO): " << strerror(errno)); |
| 1107 | return boost::logic::tribool(boost::logic::indeterminate); |
| 1108 | } |
| 1109 | |
| 1110 | close(fd); |
| 1111 | |
| 1112 | // See apm(8). |
| 1113 | switch( info.ai_acline ) |
| 1114 | { |
| 1115 | case 0: // off-line |
| 1116 | case 2: // backup power |
| 1117 | return boost::logic::tribool(true); |
| 1118 | case 1: // on-line |
| 1119 | return boost::logic::tribool(false); |
| 1120 | } |
| 1121 | switch( info.ai_batt_stat ) |
| 1122 | { |
| 1123 | case 0: // high |
| 1124 | case 1: // low |
| 1125 | case 2: // critical |
| 1126 | return boost::logic::tribool(true); |
| 1127 | case 3: // charging |
| 1128 | return boost::logic::tribool(false); |
| 1129 | } |
| 1130 | |
| 1131 | LOG_ERROR("Cannot query battery status: " |
| 1132 | << "sysctl hw.acpi.acline is not available and /dev/apm returns " |
| 1133 | << "unexpected ac-line status (" << info.ai_acline << ") and " |
| 1134 | << "battery status (" << info.ai_batt_stat << ")."); |
| 1135 | return boost::logic::tribool(boost::logic::indeterminate); |
| 1136 | } |
| 1137 | if( n != sizeof(ac) ) |
| 1138 | { |
| 1139 | LOG_ERROR("sysctlbyname(\"hw.acpi.acline\") output is unexpectedly " |
| 1140 | << n << " bytes instead of the expected " << sizeof(ac) << " bytes."); |
| 1141 | return boost::logic::tribool(boost::logic::indeterminate); |
| 1142 | #endif |
| 1143 | } |
| 1144 | return boost::logic::tribool(ac == 0); |
| 1145 | #endif |
| 1146 | |
| 1147 | LOG_ERROR("couldn't query power status"); |
| 1148 | return boost::logic::tribool(boost::logic::indeterminate); |
| 1149 | } |
| 1150 | } |