Skip to content

Commit cf0c04f

Browse files
committed
Merge branch 'mempressure' into rbf_opts-28+knots
2 parents 1248d0d + 318c798 commit cf0c04f

File tree

7 files changed

+84
-2
lines changed

7 files changed

+84
-2
lines changed

configure.ac

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -927,6 +927,21 @@ AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <malloc.h>]],
927927
[ AC_MSG_RESULT([no])]
928928
)
929929

930+
AC_MSG_CHECKING(for compatible sysinfo call)
931+
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/sysinfo.h>]],
932+
[[
933+
struct sysinfo info;
934+
int rv = sysinfo(&info);
935+
unsigned long test = info.freeram + info.bufferram + info.mem_unit;
936+
]])],
937+
[
938+
AC_MSG_RESULT(yes);
939+
AC_DEFINE(HAVE_LINUX_SYSINFO, 1, [Define this symbol if you have a Linux-compatible sysinfo call])
940+
],[
941+
AC_MSG_RESULT(no)
942+
]
943+
)
944+
930945
dnl Check for posix_fallocate
931946
AC_MSG_CHECKING([for posix_fallocate])
932947
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[

src/common/system.cpp

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@
2222
#include <malloc.h>
2323
#endif
2424

25+
#ifdef HAVE_LINUX_SYSINFO
26+
#include <sys/sysinfo.h>
27+
#endif
28+
2529
#include <cstdlib>
2630
#include <locale>
2731
#include <stdexcept>
@@ -110,3 +114,39 @@ int64_t GetStartupTime()
110114
{
111115
return nStartupTime;
112116
}
117+
118+
size_t g_low_memory_threshold = 10 * 1024 * 1024 /* 10 MB */;
119+
120+
bool SystemNeedsMemoryReleased()
121+
{
122+
if (g_low_memory_threshold <= 0) {
123+
// Intentionally bypass other metrics when disabled entirely
124+
return false;
125+
}
126+
#ifdef WIN32
127+
MEMORYSTATUSEX mem_status;
128+
mem_status.dwLength = sizeof(mem_status);
129+
if (GlobalMemoryStatusEx(&mem_status)) {
130+
if (mem_status.dwMemoryLoad >= 99 ||
131+
mem_status.ullAvailPhys < g_low_memory_threshold ||
132+
mem_status.ullAvailVirtual < g_low_memory_threshold) {
133+
LogPrintf("%s: YES: %s%% memory load; %s available physical memory; %s available virtual memory\n", __func__, int(mem_status.dwMemoryLoad), size_t(mem_status.ullAvailPhys), size_t(mem_status.ullAvailVirtual));
134+
return true;
135+
}
136+
}
137+
#endif
138+
#ifdef HAVE_LINUX_SYSINFO
139+
struct sysinfo sys_info;
140+
if (!sysinfo(&sys_info)) {
141+
// Explicitly 64-bit in case of 32-bit userspace on 64-bit kernel
142+
const uint64_t free_ram = uint64_t(sys_info.freeram) * sys_info.mem_unit;
143+
const uint64_t buffer_ram = uint64_t(sys_info.bufferram) * sys_info.mem_unit;
144+
if (free_ram + buffer_ram < g_low_memory_threshold) {
145+
LogPrintf("%s: YES: %s free RAM + %s buffer RAM\n", __func__, free_ram, buffer_ram);
146+
return true;
147+
}
148+
}
149+
#endif
150+
// NOTE: sysconf(_SC_AVPHYS_PAGES) doesn't account for caches on at least Linux, so not safe to use here
151+
return false;
152+
}

src/common/system.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,10 @@ std::string ShellEscape(const std::string& arg);
2323
void runCommand(const std::string& strCommand);
2424
#endif
2525

26+
extern size_t g_low_memory_threshold;
27+
28+
bool SystemNeedsMemoryReleased();
29+
2630
/**
2731
* Return the number of cores available on the current system.
2832
* @note This does count virtual cores, such as those provided by HyperThreading.

src/init.cpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -492,6 +492,7 @@ void SetupServerArgs(ArgsManager& argsman)
492492
argsman.AddArg("-includeconf=<file>", "Specify additional configuration file, relative to the -datadir path (only useable from configuration file, not command line)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
493493
argsman.AddArg("-allowignoredconf", strprintf("For backwards compatibility, treat an unused %s file in the datadir as a warning, not an error.", BITCOIN_CONF_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
494494
argsman.AddArg("-loadblock=<file>", "Imports blocks from external file on startup", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
495+
argsman.AddArg("-lowmem=<n>", strprintf("If system available memory falls below <n> MiB, flush caches (0 to disable, default: %s)", g_low_memory_threshold / 1024 / 1024), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
495496
argsman.AddArg("-maxmempool=<n>", strprintf("Keep the transaction memory pool below <n> megabytes (default: %u)", DEFAULT_MAX_MEMPOOL_SIZE_MB), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
496497
argsman.AddArg("-maxorphantx=<n>", strprintf("Keep at most <n> unconnectable transactions in memory (default: %u)", DEFAULT_MAX_ORPHAN_TRANSACTIONS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
497498
argsman.AddArg("-mempoolexpiry=<n>", strprintf("Do not keep transactions in the mempool longer than <n> hours (default: %u)", DEFAULT_MEMPOOL_EXPIRY_HOURS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
@@ -1540,6 +1541,13 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
15401541
bool do_reindex{args.GetBoolArg("-reindex", false)};
15411542
const bool do_reindex_chainstate{args.GetBoolArg("-reindex-chainstate", false)};
15421543

1544+
if (gArgs.IsArgSet("-lowmem")) {
1545+
g_low_memory_threshold = gArgs.GetIntArg("-lowmem", 0 /* not used */) * 1024 * 1024;
1546+
}
1547+
if (g_low_memory_threshold > 0) {
1548+
LogPrintf("* Flushing caches if available system memory drops below %s MiB\n", g_low_memory_threshold / 1024 / 1024);
1549+
}
1550+
15431551
for (bool fLoaded = false; !fLoaded && !ShutdownRequested(node);) {
15441552
bilingual_str mempool_error;
15451553
node.mempool = std::make_unique<CTxMemPool>(mempool_opts, mempool_error);

src/test/validation_chainstate_tests.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
44
//
55
#include <chainparams.h>
6+
#include <common/system.h>
67
#include <consensus/validation.h>
78
#include <random.h>
89
#include <rpc/blockchain.h>
@@ -25,6 +26,8 @@ BOOST_FIXTURE_TEST_SUITE(validation_chainstate_tests, ChainTestingSetup)
2526
//!
2627
BOOST_AUTO_TEST_CASE(validation_chainstate_resize_caches)
2728
{
29+
g_low_memory_threshold = 0; // disable to get deterministic flushing
30+
2831
ChainstateManager& manager = *Assert(m_node.chainman);
2932
CTxMemPool& mempool = *Assert(m_node.mempool);
3033
Chainstate& c1 = WITH_LOCK(cs_main, return manager.InitializeChainstate(&mempool));

src/validation.cpp

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
#include <chain.h>
1212
#include <checkqueue.h>
1313
#include <clientversion.h>
14+
#include <common/system.h>
1415
#include <consensus/amount.h>
1516
#include <consensus/consensus.h>
1617
#include <consensus/merkle.h>
@@ -2847,8 +2848,15 @@ bool Chainstate::FlushStateToDisk(
28472848
}
28482849
// The cache is large and we're within 10% and 10 MiB of the limit, but we have time now (not in the middle of a block processing).
28492850
bool fCacheLarge = mode == FlushStateMode::PERIODIC && cache_state >= CoinsCacheSizeState::LARGE;
2850-
// The cache is over the limit, we have to write now.
2851-
bool fCacheCritical = mode == FlushStateMode::IF_NEEDED && cache_state >= CoinsCacheSizeState::CRITICAL;
2851+
bool fCacheCritical = false;
2852+
if (mode == FlushStateMode::IF_NEEDED) {
2853+
if (cache_state >= CoinsCacheSizeState::CRITICAL) {
2854+
// The cache is over the limit, we have to write now.
2855+
fCacheCritical = true;
2856+
} else if (SystemNeedsMemoryReleased()) {
2857+
fCacheCritical = true;
2858+
}
2859+
}
28522860
// It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash.
28532861
bool fPeriodicWrite = mode == FlushStateMode::PERIODIC && nNow > m_last_write + DATABASE_WRITE_INTERVAL;
28542862
// It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.

src/wallet/test/wallet_tests.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
#include <vector>
1111

1212
#include <addresstype.h>
13+
#include <common/system.h>
1314
#include <interfaces/chain.h>
1415
#include <key_io.h>
1516
#include <node/blockstorage.h>
@@ -819,6 +820,9 @@ BOOST_FIXTURE_TEST_CASE(wallet_descriptor_test, BasicTestingSetup)
819820
//! rescanning where new transactions in new blocks could be lost.
820821
BOOST_FIXTURE_TEST_CASE(CreateWallet, TestChain100Setup)
821822
{
823+
// FIXME: this test fails for some reason if there's a flush
824+
g_low_memory_threshold = 0;
825+
822826
m_args.ForceSetArg("-unsafesqlitesync", "1");
823827
// Create new wallet with known key and unload it.
824828
WalletContext context;

0 commit comments

Comments
 (0)