Coverage Report

Created: 2026-04-14 13:42

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/runtime/memory/jemalloc_control.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "runtime/memory/jemalloc_control.h"
19
20
#include <atomic>
21
#include <condition_variable>
22
23
namespace doris {
24
25
std::mutex JemallocControl::je_purge_dirty_pages_lock;
26
std::atomic<bool> JemallocControl::je_purge_dirty_pages_notify {false};
27
std::mutex JemallocControl::je_reset_dirty_decay_lock;
28
std::atomic<bool> JemallocControl::je_enable_dirty_page {true};
29
std::condition_variable JemallocControl::je_reset_dirty_decay_cv;
30
std::atomic<bool> JemallocControl::je_reset_dirty_decay_notify {false};
31
32
std::atomic<int64_t> JemallocControl::je_cache_bytes_ = 0;
33
std::atomic<int64_t> JemallocControl::je_tcache_mem_ = 0;
34
std::atomic<int64_t> JemallocControl::je_metadata_mem_ = 0;
35
std::atomic<int64_t> JemallocControl::je_dirty_pages_mem_ = std::numeric_limits<int64_t>::min();
36
std::atomic<int64_t> JemallocControl::je_virtual_memory_used_ = 0;
37
38
0
void JemallocControl::refresh_allocator_mem() {
39
0
#if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || defined(THREAD_SANITIZER)
40
#elif defined(USE_JEMALLOC)
41
    // jemalloc mallctl refer to : https://jemalloc.net/jemalloc.3.html
42
    // https://www.bookstack.cn/read/aliyun-rds-core/4a0cdf677f62feb3.md
43
    //  Check the Doris BE web page `http://ip:webserver_port/memory` to get the Jemalloc Profile.
44
45
    // 'epoch' is a special mallctl -- it updates the statistics. Without it, all
46
    // the following calls will return stale values. It increments and returns
47
    // the current epoch number, which might be useful to log as a sanity check.
48
    uint64_t epoch = 0;
49
    size_t sz = sizeof(epoch);
50
    jemallctl("epoch", &epoch, &sz, &epoch, sz);
51
52
    // Number of extents of the given type in this arena in the bucket corresponding to page size index.
53
    // Large size class starts at 16384, the extents have three sizes before 16384: 4096, 8192, and 12288, so + 3
54
    int64_t dirty_pages_bytes = 0;
55
    for (unsigned i = 0; i < get_jemallctl_value<unsigned>("arenas.nlextents") + 3; i++) {
56
        dirty_pages_bytes += get_je_all_arena_extents_metrics(i, "dirty_bytes");
57
    }
58
    je_dirty_pages_mem_.store(dirty_pages_bytes, std::memory_order_relaxed);
59
    je_tcache_mem_.store(get_je_all_arena_metrics("tcache_bytes"));
60
61
    // Doris uses Jemalloc as default Allocator, Jemalloc Cache consists of two parts:
62
    // - Thread Cache, cache a specified number of Pages in Thread Cache.
63
    // - Dirty Page, memory Page that can be reused in all Arenas.
64
    je_cache_bytes_.store(je_tcache_mem_ + dirty_pages_bytes, std::memory_order_relaxed);
65
    // Total number of bytes dedicated to metadata, which comprise base allocations used
66
    // for bootstrap-sensitive allocator metadata structures.
67
    je_metadata_mem_.store(get_jemallctl_value<int64_t>("stats.metadata"),
68
                           std::memory_order_relaxed);
69
    je_virtual_memory_used_.store(get_jemallctl_value<int64_t>("stats.mapped"),
70
                                  std::memory_order_relaxed);
71
#else
72
    je_cache_bytes_.store(get_tc_metrics("tcmalloc.pageheap_free_bytes") +
73
                                  get_tc_metrics("tcmalloc.central_cache_free_bytes") +
74
                                  get_tc_metrics("tcmalloc.transfer_cache_free_bytes") +
75
                                  get_tc_metrics("tcmalloc.thread_cache_free_bytes"),
76
                          std::memory_order_relaxed);
77
    je_virtual_memory_used_.store(get_tc_metrics("generic.total_physical_bytes") +
78
                                          get_tc_metrics("tcmalloc.pageheap_unmapped_bytes"),
79
                                  std::memory_order_relaxed);
80
#endif
81
0
}
82
83
#ifdef USE_JEMALLOC
84
void JemallocControl::action_jemallctl(const std::string& name) {
85
    try {
86
        int err = jemallctl(name.c_str(), nullptr, nullptr, nullptr, 0);
87
        if (err) {
88
            LOG(WARNING) << fmt::format("Failed, jemallctl action {}", name);
89
        }
90
    } catch (...) {
91
        LOG(WARNING) << fmt::format("Exception, jemallctl action {}", name);
92
    }
93
}
94
95
int64_t JemallocControl::get_je_all_arena_metrics(const std::string& name) {
96
    return get_jemallctl_value<int64_t>(
97
            fmt::format("stats.arenas.{}.{}", MALLCTL_ARENAS_ALL, name));
98
}
99
100
int64_t JemallocControl::get_je_all_arena_extents_metrics(int64_t page_size_index,
101
                                                          const std::string& extent_type) {
102
    return get_jemallctl_value<int64_t>(fmt::format(
103
            "stats.arenas.{}.extents.{}.{}", MALLCTL_ARENAS_ALL, page_size_index, extent_type));
104
}
105
106
void JemallocControl::je_purge_all_arena_dirty_pages() {
107
    // https://github.com/jemalloc/jemalloc/issues/2470
108
    // If there is a core dump here, it may cover up the real stack, if stack trace indicates heap corruption
109
    // (which led to invalid jemalloc metadata), like double free or use-after-free in the application.
110
    // Try sanitizers such as ASAN, or build jemalloc with --enable-debug to investigate further.
111
    action_jemallctl(fmt::format("arena.{}.purge", MALLCTL_ARENAS_ALL));
112
}
113
114
void JemallocControl::je_reset_all_arena_dirty_decay_ms(ssize_t dirty_decay_ms) {
115
    // Each time this interface is set, all currently unused dirty pages are considered
116
    // to have fully decayed, which causes immediate purging of all unused dirty pages unless
117
    // the decay time is set to -1
118
    //
119
    // NOTE: Using "arena.MALLCTL_ARENAS_ALL.dirty_decay_ms" to modify all arenas will fail or even crash,
120
    // which may be a bug.
121
    for (unsigned i = 0; i < get_jemallctl_value<unsigned>("arenas.narenas"); i++) {
122
        set_jemallctl_value<ssize_t>(fmt::format("arena.{}.dirty_decay_ms", i), dirty_decay_ms);
123
    }
124
}
125
126
void JemallocControl::je_decay_all_arena_dirty_pages() {
127
    // Trigger decay-based purging of unused dirty/muzzy pages for arena <i>, or for all arenas if <i> equals
128
    // MALLCTL_ARENAS_ALL. The proportion of unused dirty/muzzy pages to be purged depends on the
129
    // current time; see opt.dirty_decay_ms and opt.muzy_decay_ms for details.
130
    action_jemallctl(fmt::format("arena.{}.decay", MALLCTL_ARENAS_ALL));
131
}
132
133
void JemallocControl::je_thread_tcache_flush() {
134
    constexpr size_t TCACHE_LIMIT = (1ULL << 30); // 1G
135
    if (je_tcache_mem() > TCACHE_LIMIT) {
136
        action_jemallctl("thread.tcache.flush");
137
    }
138
}
139
140
#else
141
0
void JemallocControl::action_jemallctl(const std::string& name) {}
142
0
int64_t JemallocControl::get_je_all_arena_metrics(const std::string& name) {
143
0
    return 0;
144
0
}
145
int64_t JemallocControl::get_je_all_arena_extents_metrics(int64_t page_size_index,
146
0
                                                          const std::string& extent_type) {
147
0
    return 0;
148
0
}
149
0
void JemallocControl::je_purge_all_arena_dirty_pages() {}
150
0
void JemallocControl::je_reset_all_arena_dirty_decay_ms(ssize_t dirty_decay_ms) {}
151
0
void JemallocControl::je_decay_all_arena_dirty_pages() {}
152
0
void JemallocControl::je_thread_tcache_flush() {}
153
#endif
154
155
} // namespace doris