Coverage Report

Created: 2025-09-11 18:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/be/src/util/cpu_info.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
// This file is copied from
18
// https://github.com/apache/impala/blob/branch-2.9.0/be/src/util/cpu-info.cpp
19
// and modified by Doris
20
21
#include "util/cpu_info.h"
22
23
#if defined(__GNUC__) && (defined(__x86_64__) || defined(__i386__))
24
#elif defined(__GNUC__) && defined(__ARM_NEON__)
25
/* GCC-compatible compiler, targeting ARM with NEON */
26
#include <arm_neon.h>
27
#elif defined(__GNUC__) && defined(__IWMMXT__)
28
/* GCC-compatible compiler, targeting ARM with WMMX */
29
#include <mmintrin.h>
30
#elif (defined(__GNUC__) || defined(__xlC__)) && (defined(__VEC__) || defined(__ALTIVEC__))
31
/* XLC or GCC-compatible compiler, targeting PowerPC with VMX/VSX */
32
#include <altivec.h>
33
#elif defined(__GNUC__) && defined(__SPE__)
34
/* GCC-compatible compiler, targeting PowerPC with SPE */
35
#include <spe.h>
36
#endif
37
38
#ifndef __APPLE__
39
#include <sys/sysinfo.h>
40
#else
41
#include <sys/sysctl.h>
42
#endif
43
44
#include <gen_cpp/Metrics_types.h>
45
#include <sched.h>
46
#include <stdlib.h>
47
#include <unistd.h>
48
49
#include <algorithm>
50
#include <boost/algorithm/string/predicate.hpp>
51
#include <boost/algorithm/string/trim.hpp>
52
// IWYU pragma: no_include <bits/chrono.h>
53
#include <chrono> // IWYU pragma: keep
54
#include <filesystem>
55
#include <fstream>
56
57
#include "absl/strings/substitute.h"
58
#include "common/config.h"
59
#include "common/env_config.h"
60
#include "gflags/gflags.h"
61
#include "util/cgroup_util.h"
62
#include "util/pretty_printer.h"
63
64
using boost::algorithm::contains;
65
using boost::algorithm::trim;
66
namespace fs = std::filesystem;
67
#include "common/compile_check_avoid_begin.h"
68
using std::max;
69
70
DECLARE_bool(abort_on_config_error);
71
DEFINE_int32(num_cores, 0,
72
             "(Advanced) If > 0, it sets the number of cores available to"
73
             " Impala. Setting it to 0 means Impala will use all available cores on the machine"
74
             " according to /proc/cpuinfo.");
75
76
namespace doris {
77
#include "common/compile_check_begin.h"
78
// Helper function to warn if a given file does not contain an expected string as its
79
// first line. If the file cannot be opened, no error is reported.
80
void WarnIfFileNotEqual(const std::string& filename, const std::string& expected,
81
0
                        const std::string& warning_text) {
82
0
    std::ifstream file(filename);
83
0
    if (!file) {
84
0
        return;
85
0
    }
86
0
    std::string line;
87
0
    getline(file, line);
88
0
    if (line != expected) {
89
0
        LOG(ERROR) << "Expected " << expected << ", actual " << line << std::endl << warning_text;
90
0
    }
91
0
}
92
93
bool CpuInfo::initialized_ = false;
94
int64_t CpuInfo::hardware_flags_ = 0;
95
int64_t CpuInfo::original_hardware_flags_;
96
int64_t CpuInfo::cycles_per_ms_;
97
int CpuInfo::num_cores_ = 1;
98
int CpuInfo::max_num_cores_ = 1;
99
std::string CpuInfo::model_name_ = "unknown";
100
int CpuInfo::max_num_numa_nodes_;
101
std::unique_ptr<int[]> CpuInfo::core_to_numa_node_;
102
std::vector<std::vector<int>> CpuInfo::numa_node_to_cores_;
103
std::vector<int> CpuInfo::numa_node_core_idx_;
104
105
static struct {
106
    std::string name;
107
    int64_t flag;
108
} flag_mappings[] = {
109
        {.name = "ssse3", .flag = CpuInfo::SSSE3},   {.name = "sse4_1", .flag = CpuInfo::SSE4_1},
110
        {.name = "sse4_2", .flag = CpuInfo::SSE4_2}, {.name = "popcnt", .flag = CpuInfo::POPCNT},
111
        {.name = "avx", .flag = CpuInfo::AVX},       {.name = "avx2", .flag = CpuInfo::AVX2},
112
};
113
114
// Helper function to parse for hardware flags.
115
// values contains a list of space-separated flags.  check to see if the flags we
116
// care about are present.
117
// Returns a bitmap of flags.
118
12
int64_t ParseCPUFlags(const std::string& values) {
119
12
    int64_t flags = 0;
120
72
    for (auto& flag_mapping : flag_mappings) {
121
72
        if (contains(values, flag_mapping.name)) {
122
72
            flags |= flag_mapping.flag;
123
72
        }
124
72
    }
125
12
    return flags;
126
12
}
127
128
10
void CpuInfo::init() {
129
10
    if (initialized_) {
130
9
        return;
131
9
    }
132
1
    std::string line;
133
1
    std::string name;
134
1
    std::string value;
135
136
1
    float max_mhz = 0;
137
1
    int physical_num_cores = 0;
138
139
    // maybe use std::thread::hardware_concurrency()?
140
    // Read from /proc/cpuinfo
141
1
    std::ifstream cpuinfo("/proc/cpuinfo");
142
326
    while (cpuinfo) {
143
325
        getline(cpuinfo, line);
144
325
        size_t colon = line.find(':');
145
325
        if (colon != std::string::npos) {
146
312
            name = line.substr(0, colon - 1);
147
312
            value = line.substr(colon + 1, std::string::npos);
148
312
            trim(name);
149
312
            trim(value);
150
312
            if (name == "flags") {
151
12
                hardware_flags_ |= ParseCPUFlags(value);
152
300
            } else if (name == "cpu MHz") {
153
                // Every core will report a different speed.  We'll take the max, assuming
154
                // that when impala is running, the core will not be in a lower power state.
155
                // TODO: is there a more robust way to do this, such as
156
                // Window's QueryPerformanceFrequency()
157
12
                float mhz = std::stof(value);
158
12
                max_mhz = max(mhz, max_mhz);
159
288
            } else if (name == "processor") {
160
12
                ++physical_num_cores;
161
276
            } else if (name == "model name") {
162
12
                model_name_ = value;
163
12
            }
164
312
        }
165
325
    }
166
167
#ifdef __APPLE__
168
    size_t len = sizeof(max_num_cores_);
169
    sysctlbyname("hw.physicalcpu", &physical_num_cores, &len, nullptr, 0);
170
#endif
171
172
1
    int num_cores = CGroupUtil::get_cgroup_limited_cpu_number(physical_num_cores);
173
1
    if (max_mhz != 0) {
174
1
        cycles_per_ms_ = int64_t(max_mhz) * 1000;
175
1
    } else {
176
0
        cycles_per_ms_ = 1000000;
177
0
    }
178
1
    original_hardware_flags_ = hardware_flags_;
179
180
1
    if (num_cores > 0) {
181
1
        num_cores_ = num_cores;
182
1
    } else {
183
0
        num_cores_ = 1;
184
0
    }
185
1
    if (config::num_cores > 0) {
186
0
        num_cores_ = config::num_cores;
187
0
    }
188
189
#ifdef __APPLE__
190
    sysctlbyname("hw.logicalcpu", &max_num_cores_, &len, nullptr, 0);
191
#else
192
1
    max_num_cores_ = get_nprocs_conf();
193
1
#endif
194
195
    // Print a warning if something is wrong with sched_getcpu().
196
1
#ifdef HAVE_SCHED_GETCPU
197
1
    if (sched_getcpu() == -1) {
198
0
        LOG(WARNING) << "Kernel does not support sched_getcpu(). Performance may be impacted.";
199
0
    }
200
#else
201
    LOG(WARNING) << "Built on a system without sched_getcpu() support. Performance may"
202
                 << " be impacted.";
203
#endif
204
205
1
    _init_numa();
206
1
    initialized_ = true;
207
1
}
208
209
1
void CpuInfo::_init_numa() {
210
    // Use the NUMA info in the /sys filesystem. which is part of the Linux ABI:
211
    // see https://www.kernel.org/doc/Documentation/ABI/stable/sysfs-devices-node and
212
    // https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-devices-system-cpu
213
    // The filesystem entries are only present if the kernel was compiled with NUMA support.
214
1
    core_to_numa_node_.reset(new int[max_num_cores_]);
215
216
1
    if (!fs::is_directory("/sys/devices/system/node")) {
217
0
        LOG(WARNING) << "/sys/devices/system/node is not present - no NUMA support";
218
        // Assume a single NUMA node.
219
0
        max_num_numa_nodes_ = 1;
220
0
        std::fill_n(core_to_numa_node_.get(), max_num_cores_, 0);
221
0
        _init_numa_node_to_cores();
222
0
        return;
223
0
    }
224
225
    // Search for node subdirectories - node0, node1, node2, etc to determine possible
226
    // NUMA nodes.
227
1
    fs::directory_iterator dir_it("/sys/devices/system/node");
228
1
    max_num_numa_nodes_ = 0;
229
9
    for (; dir_it != fs::directory_iterator(); ++dir_it) {
230
8
        const std::string filename = dir_it->path().filename().string();
231
8
        if (filename.starts_with("node")) {
232
1
            ++max_num_numa_nodes_;
233
1
        }
234
8
    }
235
1
    if (max_num_numa_nodes_ == 0) {
236
0
        LOG(WARNING) << "Could not find nodes in /sys/devices/system/node";
237
0
        max_num_numa_nodes_ = 1;
238
0
    }
239
240
    // Check which NUMA node each core belongs to based on the existence of a symlink
241
    // to the node subdirectory.
242
13
    for (int core = 0; core < max_num_cores_; ++core) {
243
12
        bool found_numa_node = false;
244
12
        for (int node = 0; node < max_num_numa_nodes_; ++node) {
245
12
            if (fs::exists(absl::Substitute("/sys/devices/system/cpu/cpu$0/node$1", core, node))) {
246
12
                core_to_numa_node_[core] = node;
247
12
                found_numa_node = true;
248
12
                break;
249
12
            }
250
12
        }
251
12
        if (!found_numa_node) {
252
0
            LOG(WARNING) << "Could not determine NUMA node for core " << core
253
0
                         << " from /sys/devices/system/cpu/";
254
0
            core_to_numa_node_[core] = 0;
255
0
        }
256
12
    }
257
1
    _init_numa_node_to_cores();
258
1
}
259
260
void CpuInfo::_init_fake_numa_for_test(int max_num_numa_nodes,
261
0
                                       const std::vector<int>& core_to_numa_node) {
262
0
    DCHECK_EQ(max_num_cores_, core_to_numa_node.size());
263
0
    max_num_numa_nodes_ = max_num_numa_nodes;
264
0
    for (int i = 0; i < max_num_cores_; ++i) {
265
0
        core_to_numa_node_[i] = core_to_numa_node[i];
266
0
    }
267
0
    numa_node_to_cores_.clear();
268
0
    _init_numa_node_to_cores();
269
0
}
270
271
1
void CpuInfo::_init_numa_node_to_cores() {
272
1
    DCHECK(numa_node_to_cores_.empty());
273
1
    numa_node_to_cores_.resize(max_num_numa_nodes_);
274
1
    numa_node_core_idx_.resize(max_num_cores_);
275
13
    for (int core = 0; core < max_num_cores_; ++core) {
276
12
        std::vector<int>* cores_of_node = &numa_node_to_cores_[core_to_numa_node_[core]];
277
12
        numa_node_core_idx_[core] = static_cast<int>(cores_of_node->size());
278
12
        cores_of_node->push_back(core);
279
12
    }
280
1
}
281
282
0
void CpuInfo::verify_cpu_requirements() {
283
0
    if (!CpuInfo::is_supported(CpuInfo::SSSE3)) {
284
0
        LOG(ERROR) << "CPU does not support the Supplemental SSE3 (SSSE3) instruction set. "
285
0
                   << "This setup is generally unsupported and Impala might be unstable.";
286
0
    }
287
0
}
288
289
0
void CpuInfo::verify_performance_governor() {
290
0
    for (int cpu_id = 0; cpu_id < CpuInfo::num_cores(); ++cpu_id) {
291
0
        const std::string governor_file =
292
0
                absl::Substitute("/sys/devices/system/cpu/cpu$0/cpufreq/scaling_governor", cpu_id);
293
0
        const std::string warning_text = absl::Substitute(
294
0
                "WARNING: CPU $0 is not using 'performance' governor. Note that changing the "
295
0
                "governor to 'performance' will reset the no_turbo setting to 0.",
296
0
                cpu_id);
297
0
        WarnIfFileNotEqual(governor_file, "performance", warning_text);
298
0
    }
299
0
}
300
301
0
void CpuInfo::verify_turbo_disabled() {
302
0
    WarnIfFileNotEqual(
303
0
            "/sys/devices/system/cpu/intel_pstate/no_turbo", "1",
304
0
            "WARNING: CPU turbo is enabled. This setting can change the clock frequency of CPU "
305
0
            "cores during the benchmark run, which can lead to inaccurate results. You can "
306
0
            "disable CPU turbo by writing a 1 to "
307
0
            "/sys/devices/system/cpu/intel_pstate/no_turbo. Note that changing the governor to "
308
0
            "'performance' will reset this to 0.");
309
0
}
310
311
0
void CpuInfo::enable_feature(long flag, bool enable) {
312
0
    DCHECK(initialized_);
313
0
    if (!enable) {
314
0
        hardware_flags_ &= ~flag;
315
0
    } else {
316
        // Can't turn something on that can't be supported
317
0
        DCHECK((original_hardware_flags_ & flag) != 0);
318
0
        hardware_flags_ |= flag;
319
0
    }
320
0
}
321
322
0
int CpuInfo::get_current_core() {
323
    // sched_getcpu() is not supported on some old kernels/glibcs (like the versions that
324
    // shipped with CentOS 5). In that case just pretend we're always running on CPU 0
325
    // so that we can build and run with degraded perf.
326
0
#ifdef HAVE_SCHED_GETCPU
327
0
    int cpu = sched_getcpu();
328
0
    if (cpu < 0) {
329
0
        return 0;
330
0
    }
331
0
    if (cpu >= max_num_cores_) {
332
0
        LOG_FIRST_N(WARNING, 5) << "sched_getcpu() return value " << cpu
333
0
                                << ", which is greater than get_nprocs_conf() retrun value "
334
0
                                << max_num_cores_ << ", now is " << get_nprocs_conf();
335
0
        cpu %= max_num_cores_;
336
0
    }
337
0
    return cpu;
338
#else
339
    return 0;
340
#endif
341
0
}
342
343
void CpuInfo::_get_cache_info(long cache_sizes[NUM_CACHE_LEVELS],
344
0
                              long cache_line_sizes[NUM_CACHE_LEVELS]) {
345
#ifdef __APPLE__
346
    // On Mac OS X use sysctl() to get the cache sizes
347
    size_t len = 0;
348
    sysctlbyname("hw.cachesize", nullptr, &len, nullptr, 0);
349
    uint64_t* data = static_cast<uint64_t*>(malloc(len));
350
    sysctlbyname("hw.cachesize", data, &len, nullptr, 0);
351
#ifndef __arm64__
352
    DCHECK(len / sizeof(uint64_t) >= 3);
353
    for (size_t i = 0; i < NUM_CACHE_LEVELS; ++i) {
354
        cache_sizes[i] = data[i];
355
    }
356
#else
357
    for (size_t i = 0; i < NUM_CACHE_LEVELS; ++i) {
358
        cache_sizes[i] = data[i + 1];
359
    }
360
#endif
361
    size_t linesize;
362
    size_t sizeof_linesize = sizeof(linesize);
363
    sysctlbyname("hw.cachelinesize", &linesize, &sizeof_linesize, nullptr, 0);
364
    for (size_t i = 0; i < NUM_CACHE_LEVELS; ++i) cache_line_sizes[i] = linesize;
365
#else
366
    // Call sysconf to query for the cache sizes
367
    // Note: on some systems (e.g. RHEL 5 on AWS EC2), this returns 0 instead of the
368
    // actual cache line size.
369
0
    cache_sizes[L1_CACHE] = sysconf(_SC_LEVEL1_DCACHE_SIZE);
370
0
    cache_sizes[L2_CACHE] = sysconf(_SC_LEVEL2_CACHE_SIZE);
371
0
    cache_sizes[L3_CACHE] = sysconf(_SC_LEVEL3_CACHE_SIZE);
372
373
0
    cache_line_sizes[L1_CACHE] = sysconf(_SC_LEVEL1_DCACHE_LINESIZE);
374
0
    cache_line_sizes[L2_CACHE] = sysconf(_SC_LEVEL2_CACHE_LINESIZE);
375
0
    cache_line_sizes[L3_CACHE] = sysconf(_SC_LEVEL3_CACHE_LINESIZE);
376
0
#endif
377
0
}
378
379
0
std::string CpuInfo::debug_string() {
380
0
    DCHECK(initialized_);
381
0
    std::stringstream stream;
382
0
    long cache_sizes[NUM_CACHE_LEVELS];
383
0
    long cache_line_sizes[NUM_CACHE_LEVELS];
384
0
    _get_cache_info(cache_sizes, cache_line_sizes);
385
386
0
    std::string L1 = absl::Substitute(
387
0
            "L1 Cache: $0 (Line: $1)",
388
0
            PrettyPrinter::print(static_cast<int64_t>(cache_sizes[L1_CACHE]), TUnit::BYTES),
389
0
            PrettyPrinter::print(static_cast<int64_t>(cache_line_sizes[L1_CACHE]), TUnit::BYTES));
390
0
    std::string L2 = absl::Substitute(
391
0
            "L2 Cache: $0 (Line: $1)",
392
0
            PrettyPrinter::print(static_cast<int64_t>(cache_sizes[L2_CACHE]), TUnit::BYTES),
393
0
            PrettyPrinter::print(static_cast<int64_t>(cache_line_sizes[L2_CACHE]), TUnit::BYTES));
394
0
    std::string L3 =
395
0
            cache_sizes[L3_CACHE]
396
0
                    ? absl::Substitute(
397
0
                              "L3 Cache: $0 (Line: $1)",
398
0
                              PrettyPrinter::print(static_cast<int64_t>(cache_sizes[L3_CACHE]),
399
0
                                                   TUnit::BYTES),
400
0
                              PrettyPrinter::print(static_cast<int64_t>(cache_line_sizes[L3_CACHE]),
401
0
                                                   TUnit::BYTES))
402
0
                    : "";
403
0
    stream << "Cpu Info:" << std::endl
404
0
           << "  Model: " << model_name_ << std::endl
405
0
           << "  Cores: " << num_cores_ << std::endl
406
0
           << "  Max Possible Cores: " << max_num_cores_ << std::endl
407
0
           << "  " << L1 << std::endl
408
0
           << "  " << L2 << std::endl
409
0
           << "  " << L3 << std::endl
410
0
           << "  Hardware Supports:" << std::endl;
411
0
    for (auto& flag_mapping : flag_mappings) {
412
0
        if (is_supported(flag_mapping.flag)) {
413
0
            stream << "    " << flag_mapping.name << std::endl;
414
0
        }
415
0
    }
416
0
    stream << "  Numa Nodes: " << max_num_numa_nodes_ << std::endl;
417
0
    stream << "  Numa Nodes of Cores:";
418
0
    for (int core = 0; core < max_num_cores_; ++core) {
419
0
        stream << " " << core << "->" << core_to_numa_node_[core] << " |";
420
0
    }
421
0
    stream << std::endl;
422
0
    return stream.str();
423
0
}
424
#include "common/compile_check_end.h"
425
} // namespace doris