Coverage Report

Created: 2025-05-19 15:53

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