File: TraceIntelPTMultiCpuDecoder.cpp

package info (click to toggle)
llvm-toolchain-17 1%3A17.0.6-22
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,799,624 kB
  • sloc: cpp: 6,428,607; ansic: 1,383,196; asm: 793,408; python: 223,504; objc: 75,364; f90: 60,502; lisp: 33,869; pascal: 15,282; sh: 9,684; perl: 7,453; ml: 4,937; awk: 3,523; makefile: 2,889; javascript: 2,149; xml: 888; fortran: 619; cs: 573
file content (238 lines) | stat: -rw-r--r-- 8,427 bytes parent folder | download | duplicates (12)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
//===-- TraceIntelPTMultiCpuDecoder.cpp -----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "TraceIntelPTMultiCpuDecoder.h"
#include "TraceIntelPT.h"
#include "llvm/Support/Error.h"
#include <optional>

using namespace lldb;
using namespace lldb_private;
using namespace lldb_private::trace_intel_pt;
using namespace llvm;

TraceIntelPTMultiCpuDecoder::TraceIntelPTMultiCpuDecoder(
    TraceIntelPTSP trace_sp)
    : m_trace_wp(trace_sp) {
  for (Process *proc : trace_sp->GetAllProcesses()) {
    for (ThreadSP thread_sp : proc->GetThreadList().Threads()) {
      m_tids.insert(thread_sp->GetID());
    }
  }
}

TraceIntelPTSP TraceIntelPTMultiCpuDecoder::GetTrace() {
  return m_trace_wp.lock();
}

bool TraceIntelPTMultiCpuDecoder::TracesThread(lldb::tid_t tid) const {
  return m_tids.count(tid);
}

Expected<std::optional<uint64_t>> TraceIntelPTMultiCpuDecoder::FindLowestTSC() {
  std::optional<uint64_t> lowest_tsc;
  TraceIntelPTSP trace_sp = GetTrace();

  Error err = GetTrace()->OnAllCpusBinaryDataRead(
      IntelPTDataKinds::kIptTrace,
      [&](const DenseMap<cpu_id_t, ArrayRef<uint8_t>> &buffers) -> Error {
        for (auto &cpu_id_to_buffer : buffers) {
          Expected<std::optional<uint64_t>> tsc =
              FindLowestTSCInTrace(*trace_sp, cpu_id_to_buffer.second);
          if (!tsc)
            return tsc.takeError();
          if (*tsc && (!lowest_tsc || *lowest_tsc > **tsc))
            lowest_tsc = **tsc;
        }
        return Error::success();
      });
  if (err)
    return std::move(err);
  return lowest_tsc;
}

Expected<DecodedThreadSP> TraceIntelPTMultiCpuDecoder::Decode(Thread &thread) {
  if (Error err = CorrelateContextSwitchesAndIntelPtTraces())
    return std::move(err);

  TraceIntelPTSP trace_sp = GetTrace();

  return trace_sp->GetThreadTimer(thread.GetID())
      .TimeTask("Decoding instructions", [&]() -> Expected<DecodedThreadSP> {
        auto it = m_decoded_threads.find(thread.GetID());
        if (it != m_decoded_threads.end())
          return it->second;

        DecodedThreadSP decoded_thread_sp = std::make_shared<DecodedThread>(
            thread.shared_from_this(), trace_sp->GetPerfZeroTscConversion());

        Error err = trace_sp->OnAllCpusBinaryDataRead(
            IntelPTDataKinds::kIptTrace,
            [&](const DenseMap<cpu_id_t, ArrayRef<uint8_t>> &buffers) -> Error {
              auto it =
                  m_continuous_executions_per_thread->find(thread.GetID());
              if (it != m_continuous_executions_per_thread->end())
                return DecodeSystemWideTraceForThread(
                    *decoded_thread_sp, *trace_sp, buffers, it->second);

              return Error::success();
            });
        if (err)
          return std::move(err);

        m_decoded_threads.try_emplace(thread.GetID(), decoded_thread_sp);
        return decoded_thread_sp;
      });
}

static Expected<std::vector<PSBBlock>> GetPSBBlocksForCPU(TraceIntelPT &trace,
                                                          cpu_id_t cpu_id) {
  std::vector<PSBBlock> psb_blocks;
  Error err = trace.OnCpuBinaryDataRead(
      cpu_id, IntelPTDataKinds::kIptTrace,
      [&](ArrayRef<uint8_t> data) -> Error {
        Expected<std::vector<PSBBlock>> split_trace =
            SplitTraceIntoPSBBlock(trace, data, /*expect_tscs=*/true);
        if (!split_trace)
          return split_trace.takeError();

        psb_blocks = std::move(*split_trace);
        return Error::success();
      });
  if (err)
    return std::move(err);
  return psb_blocks;
}

Expected<DenseMap<lldb::tid_t, std::vector<IntelPTThreadContinousExecution>>>
TraceIntelPTMultiCpuDecoder::DoCorrelateContextSwitchesAndIntelPtTraces() {
  DenseMap<lldb::tid_t, std::vector<IntelPTThreadContinousExecution>>
      continuous_executions_per_thread;
  TraceIntelPTSP trace_sp = GetTrace();

  std::optional<LinuxPerfZeroTscConversion> conv_opt =
      trace_sp->GetPerfZeroTscConversion();
  if (!conv_opt)
    return createStringError(
        inconvertibleErrorCode(),
        "TSC to nanoseconds conversion values were not found");

  LinuxPerfZeroTscConversion tsc_conversion = *conv_opt;

  for (cpu_id_t cpu_id : trace_sp->GetTracedCpus()) {
    Expected<std::vector<PSBBlock>> psb_blocks =
        GetPSBBlocksForCPU(*trace_sp, cpu_id);
    if (!psb_blocks)
      return psb_blocks.takeError();

    m_total_psb_blocks += psb_blocks->size();
    // We'll be iterating through the thread continuous executions and the intel
    // pt subtraces sorted by time.
    auto it = psb_blocks->begin();
    auto on_new_thread_execution =
        [&](const ThreadContinuousExecution &thread_execution) {
          IntelPTThreadContinousExecution execution(thread_execution);

          for (; it != psb_blocks->end() &&
                 *it->tsc < thread_execution.GetEndTSC();
               it++) {
            if (*it->tsc > thread_execution.GetStartTSC()) {
              execution.psb_blocks.push_back(*it);
            } else {
              m_unattributed_psb_blocks++;
            }
          }
          continuous_executions_per_thread[thread_execution.tid].push_back(
              execution);
        };
    Error err = trace_sp->OnCpuBinaryDataRead(
        cpu_id, IntelPTDataKinds::kPerfContextSwitchTrace,
        [&](ArrayRef<uint8_t> data) -> Error {
          Expected<std::vector<ThreadContinuousExecution>> executions =
              DecodePerfContextSwitchTrace(data, cpu_id, tsc_conversion);
          if (!executions)
            return executions.takeError();
          for (const ThreadContinuousExecution &exec : *executions)
            on_new_thread_execution(exec);
          return Error::success();
        });
    if (err)
      return std::move(err);

    m_unattributed_psb_blocks += psb_blocks->end() - it;
  }
  // We now sort the executions of each thread to have them ready for
  // instruction decoding
  for (auto &tid_executions : continuous_executions_per_thread)
    std::sort(tid_executions.second.begin(), tid_executions.second.end());

  return continuous_executions_per_thread;
}

Error TraceIntelPTMultiCpuDecoder::CorrelateContextSwitchesAndIntelPtTraces() {
  if (m_setup_error)
    return createStringError(inconvertibleErrorCode(), m_setup_error->c_str());

  if (m_continuous_executions_per_thread)
    return Error::success();

  Error err = GetTrace()->GetGlobalTimer().TimeTask(
      "Context switch and Intel PT traces correlation", [&]() -> Error {
        if (auto correlation = DoCorrelateContextSwitchesAndIntelPtTraces()) {
          m_continuous_executions_per_thread.emplace(std::move(*correlation));
          return Error::success();
        } else {
          return correlation.takeError();
        }
      });
  if (err) {
    m_setup_error = toString(std::move(err));
    return createStringError(inconvertibleErrorCode(), m_setup_error->c_str());
  }
  return Error::success();
}

size_t TraceIntelPTMultiCpuDecoder::GetNumContinuousExecutionsForThread(
    lldb::tid_t tid) const {
  if (!m_continuous_executions_per_thread)
    return 0;
  auto it = m_continuous_executions_per_thread->find(tid);
  if (it == m_continuous_executions_per_thread->end())
    return 0;
  return it->second.size();
}

size_t TraceIntelPTMultiCpuDecoder::GetTotalContinuousExecutionsCount() const {
  if (!m_continuous_executions_per_thread)
    return 0;
  size_t count = 0;
  for (const auto &kv : *m_continuous_executions_per_thread)
    count += kv.second.size();
  return count;
}

size_t
TraceIntelPTMultiCpuDecoder::GePSBBlocksCountForThread(lldb::tid_t tid) const {
  if (!m_continuous_executions_per_thread)
    return 0;
  size_t count = 0;
  auto it = m_continuous_executions_per_thread->find(tid);
  if (it == m_continuous_executions_per_thread->end())
    return 0;
  for (const IntelPTThreadContinousExecution &execution : it->second)
    count += execution.psb_blocks.size();
  return count;
}

size_t TraceIntelPTMultiCpuDecoder::GetUnattributedPSBBlocksCount() const {
  return m_unattributed_psb_blocks;
}

size_t TraceIntelPTMultiCpuDecoder::GetTotalPSBBlocksCount() const {
  return m_total_psb_blocks;
}