1 /*
2 * Copyright (C) 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #define LOG_TAG "NetworkTrace"
18 #define ATRACE_TAG ATRACE_TAG_NETWORK
19
20 #include "netdbpf/NetworkTracePoller.h"
21
22 #include <bpf/BpfUtils.h>
23 #include <cutils/trace.h>
24 #include <log/log.h>
25 #include <perfetto/tracing/platform.h>
26 #include <perfetto/tracing/tracing.h>
27
28 namespace android {
29 namespace bpf {
30 namespace internal {
31
SchedulePolling()32 void NetworkTracePoller::SchedulePolling() {
33 // Schedules another run of ourselves to recursively poll periodically.
34 mTaskRunner->PostDelayedTask(
35 [this]() {
36 mMutex.lock();
37 SchedulePolling();
38 ConsumeAllLocked();
39 mMutex.unlock();
40 },
41 mPollMs);
42 }
43
Start(uint32_t pollMs)44 bool NetworkTracePoller::Start(uint32_t pollMs) {
45 ALOGD("Starting datasource");
46
47 std::scoped_lock<std::mutex> lock(mMutex);
48 if (mSessionCount > 0) {
49 if (mPollMs != pollMs) {
50 // Nothing technical prevents mPollMs from changing, it's just unclear
51 // what the right behavior is. Taking the min of active values could poll
52 // too frequently giving some sessions too much data. Taking the max could
53 // be too infrequent. For now, do nothing.
54 ALOGI("poll_ms can't be changed while running, ignoring poll_ms=%d",
55 pollMs);
56 }
57 mSessionCount++;
58 return true;
59 }
60
61 auto status = mConfigurationMap.init(PACKET_TRACE_ENABLED_MAP_PATH);
62 if (!status.ok()) {
63 ALOGW("Failed to bind config map: %s", status.error().message().c_str());
64 return false;
65 }
66
67 auto rb = BpfRingbuf<PacketTrace>::Create(PACKET_TRACE_RINGBUF_PATH);
68 if (!rb.ok()) {
69 ALOGW("Failed to create ringbuf: %s", rb.error().message().c_str());
70 return false;
71 }
72
73 mRingBuffer = std::move(*rb);
74
75 auto res = mConfigurationMap.writeValue(0, true, BPF_ANY);
76 if (!res.ok()) {
77 ALOGW("Failed to enable tracing: %s", res.error().message().c_str());
78 return false;
79 }
80
81 // Start a task runner to run ConsumeAll every mPollMs milliseconds.
82 mTaskRunner = perfetto::Platform::GetDefaultPlatform()->CreateTaskRunner({});
83 mPollMs = pollMs;
84 SchedulePolling();
85
86 mSessionCount++;
87 return true;
88 }
89
Stop()90 bool NetworkTracePoller::Stop() {
91 ALOGD("Stopping datasource");
92
93 std::scoped_lock<std::mutex> lock(mMutex);
94 if (mSessionCount == 0) return false; // This should never happen
95
96 // If this isn't the last session, don't clean up yet.
97 if (--mSessionCount > 0) return true;
98
99 auto res = mConfigurationMap.writeValue(0, false, BPF_ANY);
100 if (!res.ok()) {
101 ALOGW("Failed to disable tracing: %s", res.error().message().c_str());
102 }
103
104 // Make sure everything in the system has actually seen the 'false' we just
105 // wrote, things should now be well and truly disabled.
106 synchronizeKernelRCU();
107
108 // Drain remaining events from the ring buffer now that tracing is disabled.
109 // This prevents the next trace from seeing stale events and allows writing
110 // the last batch of events to Perfetto.
111 ConsumeAllLocked();
112
113 mTaskRunner.reset();
114 mRingBuffer.reset();
115
116 return res.ok();
117 }
118
ConsumeAll()119 bool NetworkTracePoller::ConsumeAll() {
120 std::scoped_lock<std::mutex> lock(mMutex);
121 return ConsumeAllLocked();
122 }
123
ConsumeAllLocked()124 bool NetworkTracePoller::ConsumeAllLocked() {
125 if (mRingBuffer == nullptr) {
126 ALOGW("Tracing is not active");
127 return false;
128 }
129
130 std::vector<PacketTrace> packets;
131 base::Result<int> ret = mRingBuffer->ConsumeAll(
132 [&](const PacketTrace& pkt) { packets.push_back(pkt); });
133 if (!ret.ok()) {
134 ALOGW("Failed to poll ringbuf: %s", ret.error().message().c_str());
135 return false;
136 }
137
138 ATRACE_INT("NetworkTracePackets", packets.size());
139
140 mCallback(packets);
141
142 return true;
143 }
144
145 } // namespace internal
146 } // namespace bpf
147 } // namespace android
148