blob: ea9feec27a39239b76eb58c5e99daee47d552d8f [file] [log] [blame]
Tom Cherry1a796bc2020-05-13 09:28:37 -07001/*
2 * Copyright (C) 2020 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#include "SerializedLogBuffer.h"
18
Tom Cherry1fdbdbe2020-06-22 08:28:45 -070019#include <sys/prctl.h>
20
Tom Cherry1a796bc2020-05-13 09:28:37 -070021#include <limits>
Tom Cherry1a796bc2020-05-13 09:28:37 -070022
23#include <android-base/logging.h>
24#include <android-base/scopeguard.h>
25
26#include "LogStatistics.h"
27#include "SerializedFlushToState.h"
28
29SerializedLogBuffer::SerializedLogBuffer(LogReaderList* reader_list, LogTags* tags,
30 LogStatistics* stats)
31 : reader_list_(reader_list), tags_(tags), stats_(stats) {
32 Init();
33}
34
Tom Cherry1fdbdbe2020-06-22 08:28:45 -070035SerializedLogBuffer::~SerializedLogBuffer() {
36 if (deleter_thread_.joinable()) {
37 deleter_thread_.join();
38 }
39}
Tom Cherry1a796bc2020-05-13 09:28:37 -070040
41void SerializedLogBuffer::Init() {
42 log_id_for_each(i) {
43 if (SetSize(i, __android_logger_get_buffer_size(i))) {
44 SetSize(i, LOG_BUFFER_MIN_SIZE);
45 }
46 }
47
48 // Release any sleeping reader threads to dump their current content.
49 auto reader_threads_lock = std::lock_guard{reader_list_->reader_threads_lock()};
50 for (const auto& reader_thread : reader_list_->reader_threads()) {
51 reader_thread->triggerReader_Locked();
52 }
53}
54
55bool SerializedLogBuffer::ShouldLog(log_id_t log_id, const char* msg, uint16_t len) {
56 if (log_id == LOG_ID_SECURITY) {
57 return true;
58 }
59
60 int prio = ANDROID_LOG_INFO;
61 const char* tag = nullptr;
62 size_t tag_len = 0;
63 if (IsBinary(log_id)) {
64 int32_t tag_int = MsgToTag(msg, len);
65 tag = tags_->tagToName(tag_int);
66 if (tag) {
67 tag_len = strlen(tag);
68 }
69 } else {
70 prio = *msg;
71 tag = msg + 1;
72 tag_len = strnlen(tag, len - 1);
73 }
74 return __android_log_is_loggable_len(prio, tag, tag_len, ANDROID_LOG_VERBOSE);
75}
76
77int SerializedLogBuffer::Log(log_id_t log_id, log_time realtime, uid_t uid, pid_t pid, pid_t tid,
78 const char* msg, uint16_t len) {
79 if (log_id >= LOG_ID_MAX || len == 0) {
80 return -EINVAL;
81 }
82
83 if (!ShouldLog(log_id, msg, len)) {
84 stats_->AddTotal(log_id, len);
85 return -EACCES;
86 }
87
88 auto sequence = sequence_.fetch_add(1, std::memory_order_relaxed);
89
90 auto lock = std::lock_guard{lock_};
91
92 if (logs_[log_id].empty()) {
93 logs_[log_id].push_back(SerializedLogChunk(max_size_[log_id] / 4));
94 }
95
96 auto total_len = sizeof(SerializedLogEntry) + len;
97 if (!logs_[log_id].back().CanLog(total_len)) {
98 logs_[log_id].back().FinishWriting();
99 logs_[log_id].push_back(SerializedLogChunk(max_size_[log_id] / 4));
100 }
101
102 auto entry = logs_[log_id].back().Log(sequence, realtime, uid, pid, tid, msg, len);
103 stats_->Add(entry->ToLogStatisticsElement(log_id));
104
105 MaybePrune(log_id);
106
107 reader_list_->NotifyNewLog(1 << log_id);
108 return len;
109}
110
111void SerializedLogBuffer::MaybePrune(log_id_t log_id) {
112 auto get_total_size = [](const auto& buffer) {
113 size_t total_size = 0;
114 for (const auto& chunk : buffer) {
115 total_size += chunk.PruneSize();
116 }
117 return total_size;
118 };
119 size_t total_size = get_total_size(logs_[log_id]);
120 if (total_size > max_size_[log_id]) {
121 Prune(log_id, total_size - max_size_[log_id], 0);
122 LOG(INFO) << "Pruned Logs from log_id: " << log_id << ", previous size: " << total_size
123 << " after size: " << get_total_size(logs_[log_id]);
124 }
125}
126
Tom Cherry1fdbdbe2020-06-22 08:28:45 -0700127void SerializedLogBuffer::StartDeleterThread() {
128 if (deleter_thread_running_) {
129 return;
130 }
131 if (deleter_thread_.joinable()) {
132 deleter_thread_.join();
133 }
134 auto new_thread = std::thread([this] { DeleterThread(); });
135 deleter_thread_.swap(new_thread);
136 deleter_thread_running_ = true;
137}
138
Tom Cherry1a796bc2020-05-13 09:28:37 -0700139// Decompresses the chunks, call LogStatistics::Subtract() on each entry, then delete the chunks and
140// the list. Note that the SerializedLogChunk objects have been removed from logs_ and their
141// references have been deleted from any SerializedFlushToState objects, so this can be safely done
Tom Cherry1fdbdbe2020-06-22 08:28:45 -0700142// without holding lock_. It is done in a separate thread to avoid delaying the writer thread.
143void SerializedLogBuffer::DeleterThread() {
144 prctl(PR_SET_NAME, "logd.deleter");
145 while (true) {
146 std::list<SerializedLogChunk> local_chunks_to_delete;
147 log_id_t log_id;
148 {
149 auto lock = std::lock_guard{lock_};
150 log_id_for_each(i) {
151 if (!chunks_to_delete_[i].empty()) {
152 local_chunks_to_delete = std::move(chunks_to_delete_[i]);
153 chunks_to_delete_[i].clear();
154 log_id = i;
155 break;
156 }
157 }
158 if (local_chunks_to_delete.empty()) {
159 deleter_thread_running_ = false;
160 return;
161 }
162 }
163
164 for (auto& chunk : local_chunks_to_delete) {
Tom Cherry1a796bc2020-05-13 09:28:37 -0700165 chunk.IncReaderRefCount();
166 int read_offset = 0;
167 while (read_offset < chunk.write_offset()) {
168 auto* entry = chunk.log_entry(read_offset);
169 stats_->Subtract(entry->ToLogStatisticsElement(log_id));
170 read_offset += entry->total_len();
171 }
172 chunk.DecReaderRefCount(false);
173 }
Tom Cherry1fdbdbe2020-06-22 08:28:45 -0700174 }
Tom Cherry1a796bc2020-05-13 09:28:37 -0700175}
176
177void SerializedLogBuffer::NotifyReadersOfPrune(
178 log_id_t log_id, const std::list<SerializedLogChunk>::iterator& chunk) {
179 for (const auto& reader_thread : reader_list_->reader_threads()) {
180 auto& state = reinterpret_cast<SerializedFlushToState&>(reader_thread->flush_to_state());
181 state.Prune(log_id, chunk);
182 }
183}
184
185bool SerializedLogBuffer::Prune(log_id_t log_id, size_t bytes_to_free, uid_t uid) {
186 // Don't prune logs that are newer than the point at which any reader threads are reading from.
187 LogReaderThread* oldest = nullptr;
188 auto reader_threads_lock = std::lock_guard{reader_list_->reader_threads_lock()};
189 for (const auto& reader_thread : reader_list_->reader_threads()) {
190 if (!reader_thread->IsWatching(log_id)) {
191 continue;
192 }
193 if (!oldest || oldest->start() > reader_thread->start() ||
194 (oldest->start() == reader_thread->start() &&
195 reader_thread->deadline().time_since_epoch().count() != 0)) {
196 oldest = reader_thread.get();
197 }
198 }
199
Tom Cherry1fdbdbe2020-06-22 08:28:45 -0700200 StartDeleterThread();
201
Tom Cherry1a796bc2020-05-13 09:28:37 -0700202 auto& log_buffer = logs_[log_id];
Tom Cherry1a796bc2020-05-13 09:28:37 -0700203 auto it = log_buffer.begin();
204 while (it != log_buffer.end()) {
205 if (oldest != nullptr && it->highest_sequence_number() >= oldest->start()) {
206 break;
207 }
208
209 // Increment ahead of time since we're going to splice this iterator from the list.
210 auto it_to_prune = it++;
211
212 // The sequence number check ensures that all readers have read all logs in this chunk, but
213 // they may still hold a reference to the chunk to track their last read log_position.
214 // Notify them to delete the reference.
215 NotifyReadersOfPrune(log_id, it_to_prune);
216
217 if (uid != 0) {
218 // Reorder the log buffer to remove logs from the given UID. If there are no logs left
219 // in the buffer after the removal, delete it.
220 if (it_to_prune->ClearUidLogs(uid, log_id, stats_)) {
221 log_buffer.erase(it_to_prune);
222 }
223 } else {
224 size_t buffer_size = it_to_prune->PruneSize();
Tom Cherry1fdbdbe2020-06-22 08:28:45 -0700225 chunks_to_delete_[log_id].splice(chunks_to_delete_[log_id].end(), log_buffer,
226 it_to_prune);
Tom Cherry1a796bc2020-05-13 09:28:37 -0700227 if (buffer_size >= bytes_to_free) {
228 return true;
229 }
230 bytes_to_free -= buffer_size;
231 }
232 }
233
234 // If we've deleted all buffers without bytes_to_free hitting 0, then we're called by Clear()
235 // and should return true.
236 if (it == log_buffer.end()) {
237 return true;
238 }
239
240 // Otherwise we are stuck due to a reader, so mitigate it.
Tom Cherry9b4246d2020-06-17 11:40:55 -0700241 CHECK(oldest != nullptr);
Tom Cherry1a796bc2020-05-13 09:28:37 -0700242 KickReader(oldest, log_id, bytes_to_free);
243 return false;
244}
245
246// If the selected reader is blocking our pruning progress, decide on
247// what kind of mitigation is necessary to unblock the situation.
248void SerializedLogBuffer::KickReader(LogReaderThread* reader, log_id_t id, size_t bytes_to_free) {
249 if (bytes_to_free >= max_size_[id]) { // +100%
250 // A misbehaving or slow reader is dropped if we hit too much memory pressure.
251 LOG(WARNING) << "Kicking blocked reader, " << reader->name()
252 << ", from LogBuffer::kickMe()";
253 reader->release_Locked();
254 } else if (reader->deadline().time_since_epoch().count() != 0) {
255 // Allow a blocked WRAP deadline reader to trigger and start reporting the log data.
256 reader->triggerReader_Locked();
257 } else {
258 // Tell slow reader to skip entries to catch up.
259 unsigned long prune_rows = bytes_to_free / 300;
260 LOG(WARNING) << "Skipping " << prune_rows << " entries from slow reader, " << reader->name()
261 << ", from LogBuffer::kickMe()";
262 reader->triggerSkip_Locked(id, prune_rows);
263 }
264}
265
266std::unique_ptr<FlushToState> SerializedLogBuffer::CreateFlushToState(uint64_t start,
267 LogMask log_mask) {
268 return std::make_unique<SerializedFlushToState>(start, log_mask);
269}
270
271bool SerializedLogBuffer::FlushTo(
272 LogWriter* writer, FlushToState& abstract_state,
273 const std::function<FilterResult(log_id_t log_id, pid_t pid, uint64_t sequence,
274 log_time realtime)>& filter) {
275 auto lock = std::unique_lock{lock_};
276
277 auto& state = reinterpret_cast<SerializedFlushToState&>(abstract_state);
278 state.InitializeLogs(logs_);
279 state.CheckForNewLogs();
280
281 while (state.HasUnreadLogs()) {
282 MinHeapElement top = state.PopNextUnreadLog();
283 auto* entry = top.entry;
284 auto log_id = top.log_id;
285
286 if (entry->sequence() < state.start()) {
287 continue;
288 }
289 state.set_start(entry->sequence());
290
291 if (!writer->privileged() && entry->uid() != writer->uid()) {
292 continue;
293 }
294
295 if (filter) {
296 auto ret = filter(log_id, entry->pid(), entry->sequence(), entry->realtime());
297 if (ret == FilterResult::kSkip) {
298 continue;
299 }
300 if (ret == FilterResult::kStop) {
301 break;
302 }
303 }
304
305 lock.unlock();
306 // We never prune logs equal to or newer than any LogReaderThreads' `start` value, so the
307 // `entry` pointer is safe here without the lock
308 if (!entry->Flush(writer, log_id)) {
309 return false;
310 }
311 lock.lock();
312
313 // Since we released the log above, buffers that aren't in our min heap may now have had
314 // logs added, so re-check them.
315 state.CheckForNewLogs();
316 }
317
318 state.set_start(state.start() + 1);
319 return true;
320}
321
322bool SerializedLogBuffer::Clear(log_id_t id, uid_t uid) {
323 // Try three times to clear, then disconnect the readers and try one final time.
324 for (int retry = 0; retry < 3; ++retry) {
325 {
326 auto lock = std::lock_guard{lock_};
327 bool prune_success = Prune(id, ULONG_MAX, uid);
328 if (prune_success) {
329 return true;
330 }
331 }
332 sleep(1);
333 }
334 // Check if it is still busy after the sleep, we try to prune one entry, not another clear run,
335 // so we are looking for the quick side effect of the return value to tell us if we have a
336 // _blocked_ reader.
337 bool busy = false;
338 {
339 auto lock = std::lock_guard{lock_};
340 busy = !Prune(id, 1, uid);
341 }
342 // It is still busy, disconnect all readers.
343 if (busy) {
344 auto reader_threads_lock = std::lock_guard{reader_list_->reader_threads_lock()};
345 for (const auto& reader_thread : reader_list_->reader_threads()) {
346 if (reader_thread->IsWatching(id)) {
347 LOG(WARNING) << "Kicking blocked reader, " << reader_thread->name()
348 << ", from LogBuffer::clear()";
349 reader_thread->release_Locked();
350 }
351 }
352 }
353 auto lock = std::lock_guard{lock_};
354 return Prune(id, ULONG_MAX, uid);
355}
356
357unsigned long SerializedLogBuffer::GetSize(log_id_t id) {
358 auto lock = std::lock_guard{lock_};
359 size_t retval = 2 * max_size_[id] / 3; // See the comment in SetSize().
360 return retval;
361}
362
363// New SerializedLogChunk objects will be allocated according to the new size, but older one are
364// unchanged. MaybePrune() is called on the log buffer to reduce it to an appropriate size if the
365// new size is lower.
366// ChattyLogBuffer/SimpleLogBuffer don't consider the 'Overhead' of LogBufferElement or the
367// std::list<> overhead as part of the log size. SerializedLogBuffer does by its very nature, so
368// the 'size' metric is not compatible between them. Their actual memory usage is between 1.5x and
369// 2x of what they claim to use, so we conservatively set our internal size as size + size / 2.
370int SerializedLogBuffer::SetSize(log_id_t id, unsigned long size) {
371 // Reasonable limits ...
372 if (!__android_logger_valid_buffer_size(size)) {
373 return -1;
374 }
375
376 auto lock = std::lock_guard{lock_};
377 max_size_[id] = size + size / 2;
378
379 MaybePrune(id);
380
381 return 0;
382}