blob: f86bb999490679ef4af5723c40137e1a98d17f69 [file] [log] [blame]
Eric Tanace588c2018-09-12 11:44:43 -07001/*
2 * Copyright (C) 2018 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 "NBLog"
18//#define LOG_NDEBUG 0
19
20#include <memory>
21#include <stddef.h>
22#include <string>
23#include <unordered_set>
24
25#include <audio_utils/fifo.h>
26#include <binder/IMemory.h>
27#include <media/nblog/Entry.h>
28#include <media/nblog/Events.h>
29#include <media/nblog/Reader.h>
30#include <media/nblog/Timeline.h>
31#include <utils/Log.h>
32#include <utils/String8.h>
33
34namespace android {
35namespace NBLog {
36
37Reader::Reader(const void *shared, size_t size, const std::string &name)
38 : mName(name),
39 mShared((/*const*/ Shared *) shared), /*mIMemory*/
40 mFifo(mShared != NULL ?
41 new audio_utils_fifo(size, sizeof(uint8_t),
42 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
43 mFifoReader(mFifo != NULL ? new audio_utils_fifo_reader(*mFifo) : NULL)
44{
45}
46
47Reader::Reader(const sp<IMemory>& iMemory, size_t size, const std::string &name)
48 : Reader(iMemory != 0 ? (Shared *) iMemory->pointer() : NULL, size, name)
49{
50 mIMemory = iMemory;
51}
52
53Reader::~Reader()
54{
55 delete mFifoReader;
56 delete mFifo;
57}
58
59// Copies content of a Reader FIFO into its Snapshot
60// The Snapshot has the same raw data, but represented as a sequence of entries
61// and an EntryIterator making it possible to process the data.
62std::unique_ptr<Snapshot> Reader::getSnapshot()
63{
64 if (mFifoReader == NULL) {
65 return std::unique_ptr<Snapshot>(new Snapshot());
66 }
67
68 // This emulates the behaviour of audio_utils_fifo_reader::read, but without incrementing the
69 // reader index. The index is incremented after handling corruption, to after the last complete
70 // entry of the buffer
71 size_t lost = 0;
72 audio_utils_iovec iovec[2];
73 const size_t capacity = mFifo->capacity();
74 ssize_t availToRead;
75 // A call to audio_utils_fifo_reader::obtain() places the read pointer one buffer length
76 // before the writer's pointer (since mFifoReader was constructed with flush=false). The
77 // do while loop is an attempt to read all of the FIFO's contents regardless of how behind
78 // the reader is with respect to the writer. However, the following scheduling sequence is
79 // possible and can lead to a starvation situation:
80 // - Writer T1 writes, overrun with respect to Reader T2
81 // - T2 calls obtain() and gets EOVERFLOW, T2 ptr placed one buffer size behind T1 ptr
82 // - T1 write, overrun
83 // - T2 obtain(), EOVERFLOW (and so on...)
84 // To address this issue, we limit the number of tries for the reader to catch up with
85 // the writer.
86 int tries = 0;
87 size_t lostTemp;
88 do {
89 availToRead = mFifoReader->obtain(iovec, capacity, NULL /*timeout*/, &lostTemp);
90 lost += lostTemp;
91 } while (availToRead < 0 || ++tries <= kMaxObtainTries);
92
93 if (availToRead <= 0) {
94 ALOGW_IF(availToRead < 0, "NBLog Reader %s failed to catch up with Writer", mName.c_str());
95 return std::unique_ptr<Snapshot>(new Snapshot());
96 }
97
98 // Change to #if 1 for debugging. This statement is useful for checking buffer fullness levels
99 // (as seen by reader) and how much data was lost. If you find that the fullness level is
100 // getting close to full, or that data loss is happening to often, then you should
101 // probably try some of the following:
102 // - log less data
103 // - log less often
104 // - increase the initial shared memory allocation for the buffer
105#if 0
106 ALOGD("getSnapshot name=%s, availToRead=%zd, capacity=%zu, fullness=%.3f, lost=%zu",
107 name().c_str(), availToRead, capacity, (double)availToRead / (double)capacity, lost);
108#endif
109 std::unique_ptr<Snapshot> snapshot(new Snapshot(availToRead));
110 memcpy(snapshot->mData, (const char *) mFifo->buffer() + iovec[0].mOffset, iovec[0].mLength);
111 if (iovec[1].mLength > 0) {
112 memcpy(snapshot->mData + (iovec[0].mLength),
113 (const char *) mFifo->buffer() + iovec[1].mOffset, iovec[1].mLength);
114 }
115
116 // Handle corrupted buffer
117 // Potentially, a buffer has corrupted data on both beginning (due to overflow) and end
118 // (due to incomplete format entry). But even if the end format entry is incomplete,
119 // it ends in a complete entry (which is not an FMT_END). So is safe to traverse backwards.
120 // TODO: handle client corruption (in the middle of a buffer)
121
122 const uint8_t *back = snapshot->mData + availToRead;
123 const uint8_t *front = snapshot->mData;
124
125 // Find last FMT_END. <back> is sitting on an entry which might be the middle of a FormatEntry.
126 // We go backwards until we find an EVENT_FMT_END.
127 const uint8_t *lastEnd = findLastValidEntry(front, back, invalidEndTypes);
128 if (lastEnd == nullptr) {
129 snapshot->mEnd = snapshot->mBegin = EntryIterator(front);
130 } else {
131 // end of snapshot points to after last FMT_END entry
132 snapshot->mEnd = EntryIterator(lastEnd).next();
133 // find first FMT_START
134 const uint8_t *firstStart = nullptr;
135 const uint8_t *firstStartTmp = snapshot->mEnd;
136 while ((firstStartTmp = findLastValidEntry(front, firstStartTmp, invalidBeginTypes))
137 != nullptr) {
138 firstStart = firstStartTmp;
139 }
140 // firstStart is null if no FMT_START entry was found before lastEnd
141 if (firstStart == nullptr) {
142 snapshot->mBegin = snapshot->mEnd;
143 } else {
144 snapshot->mBegin = EntryIterator(firstStart);
145 }
146 }
147
148 // advance fifo reader index to after last entry read.
149 mFifoReader->release(snapshot->mEnd - front);
150
151 snapshot->mLost = lost;
152 return snapshot;
153}
154
155bool Reader::isIMemory(const sp<IMemory>& iMemory) const
156{
157 return iMemory != 0 && mIMemory != 0 && iMemory->pointer() == mIMemory->pointer();
158}
159
160// We make a set of the invalid types rather than the valid types when aligning
161// Snapshot EntryIterators to valid entries during log corruption checking.
162// This is done in order to avoid the maintenance overhead of adding a new Event
163// type to the two sets below whenever a new Event type is created, as it is
164// very likely that new types added will be valid types.
165// Currently, invalidBeginTypes and invalidEndTypes are used to handle the special
166// case of a Format Entry, which consists of a variable number of simple log entries.
167// If a new Event is added that consists of a variable number of simple log entries,
168// then these sets need to be updated.
169
170// We want the beginning of a Snapshot to point to an entry that is not in
171// the middle of a formatted entry and not an FMT_END.
172const std::unordered_set<Event> Reader::invalidBeginTypes {
173 EVENT_FMT_AUTHOR,
174 EVENT_FMT_END,
175 EVENT_FMT_FLOAT,
176 EVENT_FMT_HASH,
177 EVENT_FMT_INTEGER,
178 EVENT_FMT_PID,
179 EVENT_FMT_STRING,
180 EVENT_FMT_TIMESTAMP,
181};
182
183// We want the end of a Snapshot to point to an entry that is not in
184// the middle of a formatted entry and not a FMT_START.
185const std::unordered_set<Event> Reader::invalidEndTypes {
186 EVENT_FMT_AUTHOR,
187 EVENT_FMT_FLOAT,
188 EVENT_FMT_HASH,
189 EVENT_FMT_INTEGER,
190 EVENT_FMT_PID,
191 EVENT_FMT_START,
192 EVENT_FMT_STRING,
193 EVENT_FMT_TIMESTAMP,
194};
195
196const uint8_t *Reader::findLastValidEntry(const uint8_t *front, const uint8_t *back,
197 const std::unordered_set<Event> &invalidTypes) {
198 if (front == nullptr || back == nullptr) {
199 return nullptr;
200 }
201 while (back + Entry::kPreviousLengthOffset >= front) {
202 const uint8_t *prev = back - back[Entry::kPreviousLengthOffset] - Entry::kOverhead;
203 const Event type = (const Event)prev[offsetof(entry, type)];
204 if (prev < front
205 || prev + prev[offsetof(entry, length)] + Entry::kOverhead != back
206 || type <= EVENT_RESERVED || type >= EVENT_UPPER_BOUND) {
207 // prev points to an out of limits or inconsistent entry
208 return nullptr;
209 }
210 // if invalidTypes does not contain the type, then the type is valid.
211 if (invalidTypes.find(type) == invalidTypes.end()) {
212 return prev;
213 }
214 back = prev;
215 }
216 return nullptr; // no entry found
217}
218
219// TODO for future compatibility, would prefer to have a dump() go to string, and then go
220// to fd only when invoked through binder.
221void DumpReader::dump(int fd, size_t indent)
222{
223 if (fd < 0) return;
224 std::unique_ptr<Snapshot> snapshot = getSnapshot();
225 if (snapshot == nullptr) {
226 return;
227 }
228 String8 timestamp, body;
229
230 // TODO all logged types should have a printable format.
231 for (EntryIterator it = snapshot->begin(); it != snapshot->end(); ++it) {
232 switch (it->type) {
233 case EVENT_FMT_START:
234 it = handleFormat(FormatEntry(it), &timestamp, &body);
235 break;
236 case EVENT_WORK_TIME: {
237 const int64_t monotonicNs = it.payload<int64_t>();
238 body.appendFormat("Thread cycle: %ld ns", (long)monotonicNs);
239 } break;
240 case EVENT_LATENCY: {
241 const double latencyMs = it.payload<double>();
242 body.appendFormat("latency: %.3f ms", latencyMs);
243 } break;
244 case EVENT_WARMUP_TIME: {
245 const double timeMs = it.payload<double>();
246 body.appendFormat("warmup time: %.3f ms", timeMs);
247 } break;
248 case EVENT_UNDERRUN:
249 body.appendFormat("underrun");
250 break;
251 case EVENT_OVERRUN:
252 body.appendFormat("overrun");
253 break;
254 case EVENT_FMT_END:
255 case EVENT_RESERVED:
256 case EVENT_UPPER_BOUND:
257 body.appendFormat("warning: unexpected event %d", it->type);
258 default:
259 break;
260 }
261 if (!body.isEmpty()) {
262 dprintf(fd, "%.*s%s %s\n", (int)indent, "", timestamp.string(), body.string());
263 body.clear();
264 }
265 timestamp.clear();
266 }
267}
268
269EntryIterator DumpReader::handleFormat(const FormatEntry &fmtEntry,
270 String8 *timestamp, String8 *body)
271{
272 // log timestamp
273 const int64_t ts = fmtEntry.timestamp();
274 timestamp->clear();
275 timestamp->appendFormat("[%d.%03d]", (int) (ts / (1000 * 1000 * 1000)),
276 (int) ((ts / (1000 * 1000)) % 1000));
277
278 // log unique hash
279 log_hash_t hash = fmtEntry.hash();
280 // print only lower 16bit of hash as hex and line as int to reduce spam in the log
281 body->appendFormat("%.4X-%d ", (int)(hash >> 16) & 0xFFFF, (int) hash & 0xFFFF);
282
283 // log author (if present)
284 handleAuthor(fmtEntry, body);
285
286 // log string
287 EntryIterator arg = fmtEntry.args();
288
289 const char* fmt = fmtEntry.formatString();
290 size_t fmt_length = fmtEntry.formatStringLength();
291
292 for (size_t fmt_offset = 0; fmt_offset < fmt_length; ++fmt_offset) {
293 if (fmt[fmt_offset] != '%') {
294 body->append(&fmt[fmt_offset], 1); // TODO optimize to write consecutive strings at once
295 continue;
296 }
297 // case "%%""
298 if (fmt[++fmt_offset] == '%') {
299 body->append("%");
300 continue;
301 }
302 // case "%\0"
303 if (fmt_offset == fmt_length) {
304 continue;
305 }
306
307 Event event = (Event) arg->type;
308 size_t length = arg->length;
309
310 // TODO check length for event type is correct
311
312 if (event == EVENT_FMT_END) {
313 break;
314 }
315
316 // TODO: implement more complex formatting such as %.3f
317 const uint8_t *datum = arg->data; // pointer to the current event args
318 switch(fmt[fmt_offset])
319 {
320 case 's': // string
321 ALOGW_IF(event != EVENT_FMT_STRING,
322 "NBLog Reader incompatible event for string specifier: %d", event);
323 body->append((const char*) datum, length);
324 break;
325
326 case 't': // timestamp
327 ALOGW_IF(event != EVENT_FMT_TIMESTAMP,
328 "NBLog Reader incompatible event for timestamp specifier: %d", event);
329 appendTimestamp(body, datum);
330 break;
331
332 case 'd': // integer
333 ALOGW_IF(event != EVENT_FMT_INTEGER,
334 "NBLog Reader incompatible event for integer specifier: %d", event);
335 appendInt(body, datum);
336 break;
337
338 case 'f': // float
339 ALOGW_IF(event != EVENT_FMT_FLOAT,
340 "NBLog Reader incompatible event for float specifier: %d", event);
341 appendFloat(body, datum);
342 break;
343
344 case 'p': // pid
345 ALOGW_IF(event != EVENT_FMT_PID,
346 "NBLog Reader incompatible event for pid specifier: %d", event);
347 appendPID(body, datum, length);
348 break;
349
350 default:
351 ALOGW("NBLog Reader encountered unknown character %c", fmt[fmt_offset]);
352 }
353 ++arg;
354 }
355 ALOGW_IF(arg->type != EVENT_FMT_END, "Expected end of format, got %d", arg->type);
356 return arg;
357}
358
359void DumpReader::appendInt(String8 *body, const void *data)
360{
361 if (body == nullptr || data == nullptr) {
362 return;
363 }
364 //int x = *((int*) data);
365 int x;
366 memcpy(&x, data, sizeof(x));
367 body->appendFormat("<%d>", x);
368}
369
370void DumpReader::appendFloat(String8 *body, const void *data)
371{
372 if (body == nullptr || data == nullptr) {
373 return;
374 }
375 float f;
376 memcpy(&f, data, sizeof(f));
377 body->appendFormat("<%f>", f);
378}
379
380void DumpReader::appendPID(String8 *body, const void* data, size_t length)
381{
382 if (body == nullptr || data == nullptr) {
383 return;
384 }
385 pid_t id = *((pid_t*) data);
386 char * name = &((char*) data)[sizeof(pid_t)];
387 body->appendFormat("<PID: %d, name: %.*s>", id, (int) (length - sizeof(pid_t)), name);
388}
389
390void DumpReader::appendTimestamp(String8 *body, const void *data)
391{
392 if (body == nullptr || data == nullptr) {
393 return;
394 }
395 int64_t ts;
396 memcpy(&ts, data, sizeof(ts));
397 body->appendFormat("[%d.%03d]", (int) (ts / (1000 * 1000 * 1000)),
398 (int) ((ts / (1000 * 1000)) % 1000));
399}
400
401String8 DumpReader::bufferDump(const uint8_t *buffer, size_t size)
402{
403 String8 str;
404 if (buffer == nullptr) {
405 return str;
406 }
407 str.append("[ ");
408 for(size_t i = 0; i < size; i++) {
409 str.appendFormat("%d ", buffer[i]);
410 }
411 str.append("]");
412 return str;
413}
414
415String8 DumpReader::bufferDump(const EntryIterator &it)
416{
417 return bufferDump(it, it->length + Entry::kOverhead);
418}
419
420} // namespace NBLog
421} // namespace android