Coverage Report

Created: 2025-03-12 11:32

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