blob: 2f639d22c2c21aa19443ae72ee56b7bce51020ec [file] [log] [blame]
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001/*
2 * Copyright (C) 2013 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
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070017/*
18* Documentation: Workflow summary for histogram data processing:
19* For more details on FIFO, please see system/media/audio_utils; doxygen
20* TODO: add this documentation to doxygen once it is further developed
Sanna Catherine de Treville Wager1bb68622017-06-14 14:18:31 -070021* 1) Writing buffer period timestamp to the circular buffer
22* onWork()
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070023* Called every period length (e.g., 4ms)
24* Calls LOG_HIST_TS
25* LOG_HIST_TS
Sanna Catherine de Treville Wagerd4a68f62017-06-23 16:09:41 -070026* Hashes file name and line number, and writes single timestamp to buffer
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -070027* calls NBLOG::Writer::logEventHistTS once
28* NBLOG::Writer::logEventHistTS
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070029* calls NBLOG::Writer::log on hash and current timestamp
30* time is in CLOCK_MONOTONIC converted to ns
31* NBLOG::Writer::log(Event, const void*, size_t)
32* Initializes Entry, a struct containing one log entry
33* Entry contains the event type (mEvent), data length (mLength),
34* and data pointer (mData)
35* TODO: why mLength (max length of buffer data) must be <= kMaxLength = 255?
36* calls NBLOG::Writer::log(Entry *, bool)
37* NBLog::Writer::log(Entry *, bool)
38* Calls copyEntryDataAt to format data as follows in temp array:
39* [type][length][data ... ][length]
40* calls audio_utils_fifo_writer.write on temp
41* audio_utils_fifo_writer.write
42* calls obtain(), memcpy (reference in doxygen)
43* returns number of frames written
44* ssize_t audio_utils_fifo_reader::obtain
45* Determines readable buffer section via pointer arithmetic on reader
46* and writer pointers
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -070047* Similarly, LOG_AUDIO_STATE() is called by onStateChange whenever audio is
48* turned on or off, and writes this notification to the FIFO.
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070049*
Sanna Catherine de Treville Wagerd4a68f62017-06-23 16:09:41 -070050* 2) reading the data from shared memory
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070051* Thread::threadloop()
52* TODO: add description?
53* NBLog::MergeThread::threadLoop()
54* calls NBLog::Merger::merge
55* NBLog::Merger::merge
Sanna Catherine de Treville Wager1bb68622017-06-14 14:18:31 -070056* Merges snapshots sorted by timestamp
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070057* for each reader in vector of class NamedReader,
58* callsNamedReader::reader()->getSnapshot
59* TODO: check whether the rest of this function is relevant
60* NBLog::Reader::getSnapshot
61* copies snapshot of reader's fifo buffer into its own buffer
62* calls mFifoReader->obtain to find readable data
63* sets snapshot.begin() and .end() iterators to boundaries of valid entries
64* moves the fifo reader index to after the last entry read
Sanna Catherine de Treville Wager1bb68622017-06-14 14:18:31 -070065* in this case, the buffer is in shared memory. in (4), the buffer is private
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070066*
Sanna Catherine de Treville Wagerd4a68f62017-06-23 16:09:41 -070067* 3) reading the data from private buffer
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070068* MediaLogService::dump
Sanna Catherine de Treville Wager9484bae2017-06-15 14:39:44 -070069* calls NBLog::Reader::dump(CONSOLE)
70* The private buffer contains all logs for all readers in shared memory
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070071* NBLog::Reader::dump(int)
72* calls getSnapshot on the current reader
73* calls dump(int, size_t, Snapshot)
74* NBLog::Reader::dump(int, size, snapshot)
75* iterates through snapshot's events and switches based on their type
76* (string, timestamp, etc...)
77* In the case of EVENT_HISTOGRAM_ENTRY_TS, adds a list of timestamp sequences
78* (histogram entry) to NBLog::mHists
Sanna Catherine de Treville Wagerd4a68f62017-06-23 16:09:41 -070079* TODO: add every HISTOGRAM_ENTRY_TS to two
Sanna Catherine de Treville Wager1bb68622017-06-14 14:18:31 -070080* circular buffers: one short-term and one long-term (can add even longer-term
81* structures in the future). When dump is called, print everything currently
82* in the buffer.
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -070083* NBLog::drawHistogram
84* input: timestamp array
85* buckets this to a histogram and prints
86*
87*/
88
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080089#define LOG_TAG "NBLog"
Sanna Catherine de Treville Wager1bb68622017-06-14 14:18:31 -070090// #define LOG_NDEBUG 0
Glenn Kasten11d8dfc2013-01-14 14:53:13 -080091
Sanna Catherine de Treville Wager697a8a52017-06-01 09:49:05 -070092#include <algorithm>
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -080093#include <climits>
Sanna Catherine de Treville Wager201079a2017-05-18 16:36:29 -070094#include <deque>
Sanna Catherine de Treville Wager697a8a52017-06-01 09:49:05 -070095#include <fstream>
96// #include <inttypes.h>
97#include <iostream>
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -070098#include <math.h>
Sanna Catherine de Treville Wager201079a2017-05-18 16:36:29 -070099#include <numeric>
Sanna Catherine de Treville Wager697a8a52017-06-01 09:49:05 -0700100#include <vector>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800101#include <stdarg.h>
102#include <stdint.h>
103#include <stdio.h>
104#include <string.h>
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800105#include <sys/prctl.h>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800106#include <time.h>
107#include <new>
Glenn Kasten535e1612016-12-05 12:19:36 -0800108#include <audio_utils/roundup.h>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800109#include <media/nbaio/NBLog.h>
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700110#include <media/nbaio/PerformanceAnalysis.h>
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700111#include <media/nbaio/ReportPerformance.h>
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700112// #include <utils/CallStack.h> // used to print callstack
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800113#include <utils/Log.h>
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700114#include <utils/String8.h>
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800115
Nicolas Roulet40a44982017-02-03 13:39:57 -0800116#include <queue>
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700117#include <utility>
Nicolas Roulet40a44982017-02-03 13:39:57 -0800118
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800119namespace android {
120
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700121int NBLog::Entry::copyEntryDataAt(size_t offset) const
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800122{
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700123 // FIXME This is too slow
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800124 if (offset == 0)
125 return mEvent;
126 else if (offset == 1)
127 return mLength;
128 else if (offset < (size_t) (mLength + 2))
129 return ((char *) mData)[offset - 2];
130 else if (offset == (size_t) (mLength + 2))
131 return mLength;
132 else
133 return 0;
134}
135
136// ---------------------------------------------------------------------------
137
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700138/*static*/
139std::unique_ptr<NBLog::AbstractEntry> NBLog::AbstractEntry::buildEntry(const uint8_t *ptr) {
Sanna Catherine de Treville Wagercced6742017-05-10 14:42:54 -0700140 const uint8_t type = EntryIterator(ptr)->type;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700141 switch (type) {
142 case EVENT_START_FMT:
143 return std::make_unique<FormatEntry>(FormatEntry(ptr));
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700144 case EVENT_AUDIO_STATE:
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700145 case EVENT_HISTOGRAM_ENTRY_TS:
146 return std::make_unique<HistogramEntry>(HistogramEntry(ptr));
147 default:
148 ALOGW("Tried to create AbstractEntry of type %d", type);
149 return nullptr;
150 }
Nicolas Roulet40a44982017-02-03 13:39:57 -0800151}
152
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700153NBLog::AbstractEntry::AbstractEntry(const uint8_t *entry) : mEntry(entry) {
154}
155
156// ---------------------------------------------------------------------------
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800157
Sanna Catherine de Treville Wagerdd92d7e2017-05-15 14:56:53 -0700158NBLog::EntryIterator NBLog::FormatEntry::begin() const {
159 return EntryIterator(mEntry);
160}
161
Nicolas Roulet40a44982017-02-03 13:39:57 -0800162const char *NBLog::FormatEntry::formatString() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800163 return (const char*) mEntry + offsetof(entry, data);
Nicolas Roulet40a44982017-02-03 13:39:57 -0800164}
165
166size_t NBLog::FormatEntry::formatStringLength() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800167 return mEntry[offsetof(entry, length)];
Nicolas Roulet40a44982017-02-03 13:39:57 -0800168}
169
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700170NBLog::EntryIterator NBLog::FormatEntry::args() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800171 auto it = begin();
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700172 // skip start fmt
173 ++it;
174 // skip timestamp
175 ++it;
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700176 // skip hash
177 ++it;
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700178 // Skip author if present
179 if (it->type == EVENT_AUTHOR) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800180 ++it;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800181 }
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700182 return it;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800183}
184
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700185int64_t NBLog::FormatEntry::timestamp() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800186 auto it = begin();
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700187 // skip start fmt
188 ++it;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700189 return it.payload<int64_t>();
Nicolas Roulet40a44982017-02-03 13:39:57 -0800190}
191
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700192NBLog::log_hash_t NBLog::FormatEntry::hash() const {
193 auto it = begin();
194 // skip start fmt
195 ++it;
196 // skip timestamp
197 ++it;
198 // unaligned 64-bit read not supported
199 log_hash_t hash;
200 memcpy(&hash, it->data, sizeof(hash));
201 return hash;
202}
203
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700204int NBLog::FormatEntry::author() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800205 auto it = begin();
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700206 // skip start fmt
207 ++it;
208 // skip timestamp
209 ++it;
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700210 // skip hash
211 ++it;
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700212 // if there is an author entry, return it, return -1 otherwise
213 if (it->type == EVENT_AUTHOR) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800214 return it.payload<int>();
Nicolas Roulet40a44982017-02-03 13:39:57 -0800215 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800216 return -1;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800217}
218
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700219NBLog::EntryIterator NBLog::FormatEntry::copyWithAuthor(
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800220 std::unique_ptr<audio_utils_fifo_writer> &dst, int author) const {
221 auto it = begin();
Nicolas Roulet40a44982017-02-03 13:39:57 -0800222 // copy fmt start entry
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800223 it.copyTo(dst);
Nicolas Roulet1ca75122017-03-16 14:19:59 -0700224 // copy timestamp
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700225 (++it).copyTo(dst); // copy hash
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700226 (++it).copyTo(dst);
Nicolas Roulet40a44982017-02-03 13:39:57 -0800227 // insert author entry
228 size_t authorEntrySize = NBLog::Entry::kOverhead + sizeof(author);
229 uint8_t authorEntry[authorEntrySize];
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800230 authorEntry[offsetof(entry, type)] = EVENT_AUTHOR;
231 authorEntry[offsetof(entry, length)] =
232 authorEntry[authorEntrySize + NBLog::Entry::kPreviousLengthOffset] =
233 sizeof(author);
234 *(int*) (&authorEntry[offsetof(entry, data)]) = author;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800235 dst->write(authorEntry, authorEntrySize);
236 // copy rest of entries
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800237 while ((++it)->type != EVENT_END_FMT) {
238 it.copyTo(dst);
Nicolas Roulet40a44982017-02-03 13:39:57 -0800239 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800240 it.copyTo(dst);
241 ++it;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800242 return it;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800243}
244
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700245void NBLog::EntryIterator::copyTo(std::unique_ptr<audio_utils_fifo_writer> &dst) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800246 size_t length = ptr[offsetof(entry, length)] + NBLog::Entry::kOverhead;
247 dst->write(ptr, length);
248}
Nicolas Roulet40a44982017-02-03 13:39:57 -0800249
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700250void NBLog::EntryIterator::copyData(uint8_t *dst) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800251 memcpy((void*) dst, ptr + offsetof(entry, data), ptr[offsetof(entry, length)]);
252}
253
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700254NBLog::EntryIterator::EntryIterator()
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800255 : ptr(nullptr) {}
256
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700257NBLog::EntryIterator::EntryIterator(const uint8_t *entry)
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800258 : ptr(entry) {}
259
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700260NBLog::EntryIterator::EntryIterator(const NBLog::EntryIterator &other)
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800261 : ptr(other.ptr) {}
262
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700263const NBLog::entry& NBLog::EntryIterator::operator*() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800264 return *(entry*) ptr;
265}
266
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700267const NBLog::entry* NBLog::EntryIterator::operator->() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800268 return (entry*) ptr;
269}
270
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700271NBLog::EntryIterator& NBLog::EntryIterator::operator++() {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800272 ptr += ptr[offsetof(entry, length)] + NBLog::Entry::kOverhead;
273 return *this;
274}
275
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700276NBLog::EntryIterator& NBLog::EntryIterator::operator--() {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800277 ptr -= ptr[NBLog::Entry::kPreviousLengthOffset] + NBLog::Entry::kOverhead;
278 return *this;
279}
280
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700281NBLog::EntryIterator NBLog::EntryIterator::next() const {
282 EntryIterator aux(*this);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800283 return ++aux;
284}
285
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700286NBLog::EntryIterator NBLog::EntryIterator::prev() const {
287 EntryIterator aux(*this);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800288 return --aux;
289}
290
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700291int NBLog::EntryIterator::operator-(const NBLog::EntryIterator &other) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800292 return ptr - other.ptr;
293}
294
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700295bool NBLog::EntryIterator::operator!=(const EntryIterator &other) const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800296 return ptr != other.ptr;
297}
298
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700299bool NBLog::EntryIterator::hasConsistentLength() const {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800300 return ptr[offsetof(entry, length)] == ptr[ptr[offsetof(entry, length)] +
301 NBLog::Entry::kOverhead + NBLog::Entry::kPreviousLengthOffset];
Nicolas Roulet40a44982017-02-03 13:39:57 -0800302}
303
304// ---------------------------------------------------------------------------
305
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700306int64_t NBLog::HistogramEntry::timestamp() const {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700307 return EntryIterator(mEntry).payload<HistTsEntry>().ts;
308}
309
310NBLog::log_hash_t NBLog::HistogramEntry::hash() const {
311 return EntryIterator(mEntry).payload<HistTsEntry>().hash;
312}
313
314int NBLog::HistogramEntry::author() const {
315 EntryIterator it(mEntry);
316 if (it->length == sizeof(HistTsEntryWithAuthor)) {
317 return it.payload<HistTsEntryWithAuthor>().author;
318 } else {
319 return -1;
320 }
321}
322
323NBLog::EntryIterator NBLog::HistogramEntry::copyWithAuthor(
324 std::unique_ptr<audio_utils_fifo_writer> &dst, int author) const {
325 // Current histogram entry has {type, length, struct HistTsEntry, length}.
326 // We now want {type, length, struct HistTsEntryWithAuthor, length}
327 uint8_t buffer[Entry::kOverhead + sizeof(HistTsEntryWithAuthor)];
328 // Copy content until the point we want to add the author
329 memcpy(buffer, mEntry, sizeof(entry) + sizeof(HistTsEntry));
330 // Copy the author
331 *(int*) (buffer + sizeof(entry) + sizeof(HistTsEntry)) = author;
332 // Update lengths
333 buffer[offsetof(entry, length)] = sizeof(HistTsEntryWithAuthor);
334 buffer[sizeof(buffer) + Entry::kPreviousLengthOffset] = sizeof(HistTsEntryWithAuthor);
335 // Write new buffer into FIFO
336 dst->write(buffer, sizeof(buffer));
337 return EntryIterator(mEntry).next();
338}
339
340// ---------------------------------------------------------------------------
341
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800342#if 0 // FIXME see note in NBLog.h
343NBLog::Timeline::Timeline(size_t size, void *shared)
344 : mSize(roundup(size)), mOwn(shared == NULL),
345 mShared((Shared *) (mOwn ? new char[sharedSize(size)] : shared))
346{
347 new (mShared) Shared;
348}
349
350NBLog::Timeline::~Timeline()
351{
352 mShared->~Shared();
353 if (mOwn) {
354 delete[] (char *) mShared;
355 }
356}
357#endif
358
359/*static*/
360size_t NBLog::Timeline::sharedSize(size_t size)
361{
Glenn Kastened99c2b2016-12-12 08:31:24 -0800362 // TODO fifo now supports non-power-of-2 buffer sizes, so could remove the roundup
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800363 return sizeof(Shared) + roundup(size);
364}
365
366// ---------------------------------------------------------------------------
367
368NBLog::Writer::Writer()
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800369 : mShared(NULL), mFifo(NULL), mFifoWriter(NULL), mEnabled(false), mPidTag(NULL), mPidTagSize(0)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800370{
371}
372
Glenn Kasten535e1612016-12-05 12:19:36 -0800373NBLog::Writer::Writer(void *shared, size_t size)
374 : mShared((Shared *) shared),
375 mFifo(mShared != NULL ?
376 new audio_utils_fifo(size, sizeof(uint8_t),
377 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
378 mFifoWriter(mFifo != NULL ? new audio_utils_fifo_writer(*mFifo) : NULL),
379 mEnabled(mFifoWriter != NULL)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800380{
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800381 // caching pid and process name
382 pid_t id = ::getpid();
383 char procName[16];
384 int status = prctl(PR_GET_NAME, procName);
385 if (status) { // error getting process name
386 procName[0] = '\0';
387 }
388 size_t length = strlen(procName);
389 mPidTagSize = length + sizeof(pid_t);
390 mPidTag = new char[mPidTagSize];
391 memcpy(mPidTag, &id, sizeof(pid_t));
392 memcpy(mPidTag + sizeof(pid_t), procName, length);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800393}
394
Glenn Kasten535e1612016-12-05 12:19:36 -0800395NBLog::Writer::Writer(const sp<IMemory>& iMemory, size_t size)
396 : Writer(iMemory != 0 ? (Shared *) iMemory->pointer() : NULL, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800397{
Glenn Kasten535e1612016-12-05 12:19:36 -0800398 mIMemory = iMemory;
399}
400
401NBLog::Writer::~Writer()
402{
403 delete mFifoWriter;
404 delete mFifo;
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800405 delete[] mPidTag;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800406}
407
408void NBLog::Writer::log(const char *string)
409{
410 if (!mEnabled) {
411 return;
412 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800413 LOG_ALWAYS_FATAL_IF(string == NULL, "Attempted to log NULL string");
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800414 size_t length = strlen(string);
Glenn Kasten535e1612016-12-05 12:19:36 -0800415 if (length > Entry::kMaxLength) {
416 length = Entry::kMaxLength;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800417 }
418 log(EVENT_STRING, string, length);
419}
420
421void NBLog::Writer::logf(const char *fmt, ...)
422{
423 if (!mEnabled) {
424 return;
425 }
426 va_list ap;
427 va_start(ap, fmt);
428 Writer::logvf(fmt, ap); // the Writer:: is needed to avoid virtual dispatch for LockedWriter
429 va_end(ap);
430}
431
432void NBLog::Writer::logvf(const char *fmt, va_list ap)
433{
434 if (!mEnabled) {
435 return;
436 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800437 char buffer[Entry::kMaxLength + 1 /*NUL*/];
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800438 int length = vsnprintf(buffer, sizeof(buffer), fmt, ap);
439 if (length >= (int) sizeof(buffer)) {
440 length = sizeof(buffer) - 1;
441 // NUL termination is not required
442 // buffer[length] = '\0';
443 }
444 if (length >= 0) {
445 log(EVENT_STRING, buffer, length);
446 }
447}
448
449void NBLog::Writer::logTimestamp()
450{
451 if (!mEnabled) {
452 return;
453 }
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700454 int64_t ts = get_monotonic_ns();
455 if (ts > 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800456 log(EVENT_TIMESTAMP, &ts, sizeof(ts));
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700457 } else {
458 ALOGE("Failed to get timestamp");
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800459 }
460}
461
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700462void NBLog::Writer::logTimestamp(const int64_t ts)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800463{
464 if (!mEnabled) {
465 return;
466 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800467 log(EVENT_TIMESTAMP, &ts, sizeof(ts));
468}
469
470void NBLog::Writer::logInteger(const int x)
471{
472 if (!mEnabled) {
473 return;
474 }
475 log(EVENT_INTEGER, &x, sizeof(x));
476}
477
478void NBLog::Writer::logFloat(const float x)
479{
480 if (!mEnabled) {
481 return;
482 }
483 log(EVENT_FLOAT, &x, sizeof(x));
484}
485
486void NBLog::Writer::logPID()
487{
488 if (!mEnabled) {
489 return;
490 }
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800491 log(EVENT_PID, mPidTag, mPidTagSize);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800492}
493
494void NBLog::Writer::logStart(const char *fmt)
495{
496 if (!mEnabled) {
497 return;
498 }
499 size_t length = strlen(fmt);
500 if (length > Entry::kMaxLength) {
501 length = Entry::kMaxLength;
502 }
503 log(EVENT_START_FMT, fmt, length);
504}
505
506void NBLog::Writer::logEnd()
507{
508 if (!mEnabled) {
509 return;
510 }
511 Entry entry = Entry(EVENT_END_FMT, NULL, 0);
512 log(&entry, true);
513}
514
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700515void NBLog::Writer::logHash(log_hash_t hash)
516{
517 if (!mEnabled) {
518 return;
519 }
520 log(EVENT_HASH, &hash, sizeof(hash));
521}
522
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700523void NBLog::Writer::logEventHistTs(Event event, log_hash_t hash)
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700524{
525 if (!mEnabled) {
526 return;
527 }
528 HistTsEntry data;
529 data.hash = hash;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700530 data.ts = get_monotonic_ns();
531 if (data.ts > 0) {
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700532 log(event, &data, sizeof(data));
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700533 } else {
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700534 ALOGE("Failed to get timestamp");
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700535 }
536}
537
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700538void NBLog::Writer::logFormat(const char *fmt, log_hash_t hash, ...)
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800539{
540 if (!mEnabled) {
541 return;
542 }
543
544 va_list ap;
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700545 va_start(ap, hash);
546 Writer::logVFormat(fmt, hash, ap);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800547 va_end(ap);
548}
549
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700550void NBLog::Writer::logVFormat(const char *fmt, log_hash_t hash, va_list argp)
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800551{
552 if (!mEnabled) {
553 return;
554 }
555 Writer::logStart(fmt);
556 int i;
557 double f;
558 char* s;
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700559 int64_t t;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800560 Writer::logTimestamp();
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700561 Writer::logHash(hash);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800562 for (const char *p = fmt; *p != '\0'; p++) {
563 // TODO: implement more complex formatting such as %.3f
564 if (*p != '%') {
565 continue;
566 }
567 switch(*++p) {
568 case 's': // string
569 s = va_arg(argp, char *);
570 Writer::log(s);
571 break;
572
573 case 't': // timestamp
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700574 t = va_arg(argp, int64_t);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800575 Writer::logTimestamp(t);
576 break;
577
578 case 'd': // integer
579 i = va_arg(argp, int);
580 Writer::logInteger(i);
581 break;
582
583 case 'f': // float
584 f = va_arg(argp, double); // float arguments are promoted to double in vararg lists
585 Writer::logFloat((float)f);
586 break;
587
588 case 'p': // pid
589 Writer::logPID();
590 break;
591
592 // the "%\0" case finishes parsing
593 case '\0':
594 --p;
595 break;
596
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800597 case '%':
598 break;
599
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800600 default:
601 ALOGW("NBLog Writer parsed invalid format specifier: %c", *p);
602 break;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800603 }
604 }
605 Writer::logEnd();
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800606}
607
608void NBLog::Writer::log(Event event, const void *data, size_t length)
609{
610 if (!mEnabled) {
611 return;
612 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800613 if (data == NULL || length > Entry::kMaxLength) {
614 // TODO Perhaps it makes sense to display truncated data or at least a
615 // message that the data is too long? The current behavior can create
616 // a confusion for a programmer debugging their code.
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800617 return;
618 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700619 // Ignore if invalid event
620 if (event == EVENT_RESERVED || event >= EVENT_UPPER_BOUND) {
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800621 return;
622 }
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700623 Entry etr(event, data, length);
624 log(&etr, true /*trusted*/);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800625}
626
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700627void NBLog::Writer::log(const NBLog::Entry *etr, bool trusted)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800628{
629 if (!mEnabled) {
630 return;
631 }
632 if (!trusted) {
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700633 log(etr->mEvent, etr->mData, etr->mLength);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800634 return;
635 }
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700636 size_t need = etr->mLength + Entry::kOverhead; // mEvent, mLength, data[mLength], mLength
637 // need = number of bytes written to FIFO
Glenn Kasten535e1612016-12-05 12:19:36 -0800638
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800639 // FIXME optimize this using memcpy for the data part of the Entry.
640 // The Entry could have a method copyTo(ptr, offset, size) to optimize the copy.
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700641 // checks size of a single log Entry: type, length, data pointer and ending
Glenn Kasten535e1612016-12-05 12:19:36 -0800642 uint8_t temp[Entry::kMaxLength + Entry::kOverhead];
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700643 // write this data to temp array
Glenn Kasten535e1612016-12-05 12:19:36 -0800644 for (size_t i = 0; i < need; i++) {
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700645 temp[i] = etr->copyEntryDataAt(i);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800646 }
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700647 // write to circular buffer
Glenn Kasten535e1612016-12-05 12:19:36 -0800648 mFifoWriter->write(temp, need);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800649}
650
651bool NBLog::Writer::isEnabled() const
652{
653 return mEnabled;
654}
655
656bool NBLog::Writer::setEnabled(bool enabled)
657{
658 bool old = mEnabled;
659 mEnabled = enabled && mShared != NULL;
660 return old;
661}
662
663// ---------------------------------------------------------------------------
664
665NBLog::LockedWriter::LockedWriter()
666 : Writer()
667{
668}
669
Glenn Kasten535e1612016-12-05 12:19:36 -0800670NBLog::LockedWriter::LockedWriter(void *shared, size_t size)
671 : Writer(shared, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800672{
673}
674
675void NBLog::LockedWriter::log(const char *string)
676{
677 Mutex::Autolock _l(mLock);
678 Writer::log(string);
679}
680
681void NBLog::LockedWriter::logf(const char *fmt, ...)
682{
683 // FIXME should not take the lock until after formatting is done
684 Mutex::Autolock _l(mLock);
685 va_list ap;
686 va_start(ap, fmt);
687 Writer::logvf(fmt, ap);
688 va_end(ap);
689}
690
691void NBLog::LockedWriter::logvf(const char *fmt, va_list ap)
692{
693 // FIXME should not take the lock until after formatting is done
694 Mutex::Autolock _l(mLock);
695 Writer::logvf(fmt, ap);
696}
697
698void NBLog::LockedWriter::logTimestamp()
699{
700 // FIXME should not take the lock until after the clock_gettime() syscall
701 Mutex::Autolock _l(mLock);
702 Writer::logTimestamp();
703}
704
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700705void NBLog::LockedWriter::logTimestamp(const int64_t ts)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800706{
707 Mutex::Autolock _l(mLock);
708 Writer::logTimestamp(ts);
709}
710
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800711void NBLog::LockedWriter::logInteger(const int x)
712{
713 Mutex::Autolock _l(mLock);
714 Writer::logInteger(x);
715}
716
717void NBLog::LockedWriter::logFloat(const float x)
718{
719 Mutex::Autolock _l(mLock);
720 Writer::logFloat(x);
721}
722
723void NBLog::LockedWriter::logPID()
724{
725 Mutex::Autolock _l(mLock);
726 Writer::logPID();
727}
728
729void NBLog::LockedWriter::logStart(const char *fmt)
730{
731 Mutex::Autolock _l(mLock);
732 Writer::logStart(fmt);
733}
734
735
736void NBLog::LockedWriter::logEnd()
737{
738 Mutex::Autolock _l(mLock);
739 Writer::logEnd();
740}
741
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -0700742void NBLog::LockedWriter::logHash(log_hash_t hash)
743{
744 Mutex::Autolock _l(mLock);
745 Writer::logHash(hash);
746}
747
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800748bool NBLog::LockedWriter::isEnabled() const
749{
750 Mutex::Autolock _l(mLock);
751 return Writer::isEnabled();
752}
753
754bool NBLog::LockedWriter::setEnabled(bool enabled)
755{
756 Mutex::Autolock _l(mLock);
757 return Writer::setEnabled(enabled);
758}
759
760// ---------------------------------------------------------------------------
761
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700762const std::set<NBLog::Event> NBLog::Reader::startingTypes {NBLog::Event::EVENT_START_FMT,
763 NBLog::Event::EVENT_HISTOGRAM_ENTRY_TS};
764const std::set<NBLog::Event> NBLog::Reader::endingTypes {NBLog::Event::EVENT_END_FMT,
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700765 NBLog::Event::EVENT_HISTOGRAM_ENTRY_TS,
766 NBLog::Event::EVENT_AUDIO_STATE};
767
Glenn Kasten535e1612016-12-05 12:19:36 -0800768NBLog::Reader::Reader(const void *shared, size_t size)
769 : mShared((/*const*/ Shared *) shared), /*mIMemory*/
770 mFd(-1), mIndent(0),
771 mFifo(mShared != NULL ?
772 new audio_utils_fifo(size, sizeof(uint8_t),
773 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -0700774 mFifoReader(mFifo != NULL ? new audio_utils_fifo_reader(*mFifo) : NULL)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800775{
776}
777
Glenn Kasten535e1612016-12-05 12:19:36 -0800778NBLog::Reader::Reader(const sp<IMemory>& iMemory, size_t size)
779 : Reader(iMemory != 0 ? (Shared *) iMemory->pointer() : NULL, size)
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800780{
Glenn Kasten535e1612016-12-05 12:19:36 -0800781 mIMemory = iMemory;
782}
783
784NBLog::Reader::~Reader()
785{
786 delete mFifoReader;
787 delete mFifo;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800788}
789
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700790const uint8_t *NBLog::Reader::findLastEntryOfTypes(const uint8_t *front, const uint8_t *back,
791 const std::set<Event> &types) {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800792 while (back + Entry::kPreviousLengthOffset >= front) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700793 const uint8_t *prev = back - back[Entry::kPreviousLengthOffset] - Entry::kOverhead;
794 if (prev < front || prev + prev[offsetof(entry, length)] +
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800795 Entry::kOverhead != back) {
796
797 // prev points to an out of limits or inconsistent entry
798 return nullptr;
799 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700800 if (types.find((const Event) prev[offsetof(entry, type)]) != types.end()) {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800801 return prev;
802 }
803 back = prev;
804 }
805 return nullptr; // no entry found
806}
807
Nicolas Roulet40a44982017-02-03 13:39:57 -0800808std::unique_ptr<NBLog::Reader::Snapshot> NBLog::Reader::getSnapshot()
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800809{
Glenn Kasten535e1612016-12-05 12:19:36 -0800810 if (mFifoReader == NULL) {
Nicolas Roulet40a44982017-02-03 13:39:57 -0800811 return std::unique_ptr<NBLog::Reader::Snapshot>(new Snapshot());
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800812 }
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800813 // make a copy to avoid race condition with writer
Glenn Kasten535e1612016-12-05 12:19:36 -0800814 size_t capacity = mFifo->capacity();
815
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800816 // This emulates the behaviour of audio_utils_fifo_reader::read, but without incrementing the
817 // reader index. The index is incremented after handling corruption, to after the last complete
818 // entry of the buffer
819 size_t lost;
820 audio_utils_iovec iovec[2];
821 ssize_t availToRead = mFifoReader->obtain(iovec, capacity, NULL /*timeout*/, &lost);
822 if (availToRead <= 0) {
823 return std::unique_ptr<NBLog::Reader::Snapshot>(new Snapshot());
824 }
Glenn Kasten535e1612016-12-05 12:19:36 -0800825
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800826 std::unique_ptr<Snapshot> snapshot(new Snapshot(availToRead));
827 memcpy(snapshot->mData, (const char *) mFifo->buffer() + iovec[0].mOffset, iovec[0].mLength);
828 if (iovec[1].mLength > 0) {
829 memcpy(snapshot->mData + (iovec[0].mLength),
830 (const char *) mFifo->buffer() + iovec[1].mOffset, iovec[1].mLength);
831 }
832
833 // Handle corrupted buffer
834 // Potentially, a buffer has corrupted data on both beginning (due to overflow) and end
835 // (due to incomplete format entry). But even if the end format entry is incomplete,
836 // it ends in a complete entry (which is not an END_FMT). So is safe to traverse backwards.
837 // TODO: handle client corruption (in the middle of a buffer)
838
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700839 const uint8_t *back = snapshot->mData + availToRead;
840 const uint8_t *front = snapshot->mData;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800841
842 // Find last END_FMT. <back> is sitting on an entry which might be the middle of a FormatEntry.
843 // We go backwards until we find an EVENT_END_FMT.
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700844 const uint8_t *lastEnd = findLastEntryOfTypes(front, back, endingTypes);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800845 if (lastEnd == nullptr) {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700846 snapshot->mEnd = snapshot->mBegin = EntryIterator(front);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800847 } else {
848 // end of snapshot points to after last END_FMT entry
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700849 snapshot->mEnd = EntryIterator(lastEnd).next();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800850 // find first START_FMT
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700851 const uint8_t *firstStart = nullptr;
852 const uint8_t *firstStartTmp = snapshot->mEnd;
853 while ((firstStartTmp = findLastEntryOfTypes(front, firstStartTmp, startingTypes))
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800854 != nullptr) {
855 firstStart = firstStartTmp;
856 }
857 // firstStart is null if no START_FMT entry was found before lastEnd
858 if (firstStart == nullptr) {
859 snapshot->mBegin = snapshot->mEnd;
860 } else {
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700861 snapshot->mBegin = EntryIterator(firstStart);
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800862 }
863 }
864
865 // advance fifo reader index to after last entry read.
866 mFifoReader->release(snapshot->mEnd - front);
867
868 snapshot->mLost = lost;
Nicolas Roulet40a44982017-02-03 13:39:57 -0800869 return snapshot;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800870
Nicolas Roulet40a44982017-02-03 13:39:57 -0800871}
872
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700873// TODO: move this to PerformanceAnalysis
874// TODO: make call to dump periodic so that data in shared FIFO does not get overwritten
Nicolas Roulet40a44982017-02-03 13:39:57 -0800875void NBLog::Reader::dump(int fd, size_t indent, NBLog::Reader::Snapshot &snapshot)
876{
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700877 mFd = fd;
878 mIndent = indent;
879 String8 timestamp, body;
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700880 // FIXME: this is not thread safe
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700881 // TODO: need a separate instance of performanceAnalysis for each thread
882 // used to store data and to call analysis functions
883 static ReportPerformance::PerformanceAnalysis performanceAnalysis;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700884 size_t lost = snapshot.lost() + (snapshot.begin() - EntryIterator(snapshot.data()));
Glenn Kastenc02c9612013-10-15 09:25:11 -0700885 if (lost > 0) {
Glenn Kasten95d287d2014-04-28 14:11:45 -0700886 body.appendFormat("warning: lost %zu bytes worth of events", lost);
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700887 // TODO timestamp empty here, only other choice to wait for the first timestamp event in the
Sanna Catherine de Treville Wager2d1631e2017-05-30 16:12:36 -0700888 // log to push it out. Consider keeping the timestamp/body between calls to copyEntryDataAt().
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700889 dumpLine(timestamp, body);
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800890 }
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700891
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800892 for (auto entry = snapshot.begin(); entry != snapshot.end();) {
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800893 switch (entry->type) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800894 case EVENT_START_FMT:
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800895 entry = handleFormat(FormatEntry(entry), &timestamp, &body);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800896 break;
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700897 case EVENT_HISTOGRAM_ENTRY_TS: {
898 HistTsEntryWithAuthor *data = (HistTsEntryWithAuthor *) (entry->data);
899 // TODO This memcpies are here to avoid unaligned memory access crash.
900 // There's probably a more efficient way to do it
901 log_hash_t hash;
902 memcpy(&hash, &(data->hash), sizeof(hash));
Nicolas Rouletad82aa62017-04-03 19:15:20 -0700903 int64_t ts;
904 memcpy(&ts, &data->ts, sizeof(ts));
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700905 performanceAnalysis.logTsEntry(ts);
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700906 ++entry;
907 break;
908 }
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700909 case EVENT_AUDIO_STATE: {
Sanna Catherine de Treville Wager80448082017-07-11 14:07:59 -0700910 performanceAnalysis.handleStateChange();
Sanna Catherine de Treville Wagera8a8a472017-07-11 09:41:25 -0700911 ++entry;
912 break;
913 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800914 case EVENT_END_FMT:
915 body.appendFormat("warning: got to end format event");
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800916 ++entry;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800917 break;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800918 case EVENT_RESERVED:
919 default:
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -0800920 body.appendFormat("warning: unexpected event %d", entry->type);
921 ++entry;
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800922 break;
923 }
Sanna Catherine de Treville Wager9484bae2017-06-15 14:39:44 -0700924 }
Sanna Catherine de Treville Wager41cad592017-06-29 14:57:59 -0700925 performanceAnalysis.reportPerformance(&body);
Sanna Catherine de Treville Wager9484bae2017-06-15 14:39:44 -0700926 if (!body.isEmpty()) {
927 dumpLine(timestamp, body);
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700928 }
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800929}
930
Nicolas Roulet40a44982017-02-03 13:39:57 -0800931void NBLog::Reader::dump(int fd, size_t indent)
932{
933 // get a snapshot, dump it
934 std::unique_ptr<Snapshot> snap = getSnapshot();
935 dump(fd, indent, *snap);
936}
937
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800938void NBLog::Reader::dumpLine(const String8 &timestamp, String8 &body)
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700939{
940 if (mFd >= 0) {
Elliott Hughes8b5f6422014-05-22 01:22:06 -0700941 dprintf(mFd, "%.*s%s %s\n", mIndent, "", timestamp.string(), body.string());
Glenn Kasten4e01ef62013-07-11 14:29:59 -0700942 } else {
943 ALOGI("%.*s%s %s", mIndent, "", timestamp.string(), body.string());
944 }
945 body.clear();
946}
947
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800948bool NBLog::Reader::isIMemory(const sp<IMemory>& iMemory) const
949{
Glenn Kasten481fb672013-09-30 14:39:28 -0700950 return iMemory != 0 && mIMemory != 0 && iMemory->pointer() == mIMemory->pointer();
Glenn Kasten11d8dfc2013-01-14 14:53:13 -0800951}
952
Glenn Kasten1c446272017-04-07 09:49:07 -0700953// ---------------------------------------------------------------------------
954
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800955void NBLog::appendTimestamp(String8 *body, const void *data) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700956 int64_t ts;
957 memcpy(&ts, data, sizeof(ts));
958 body->appendFormat("[%d.%03d]", (int) (ts / (1000 * 1000 * 1000)),
959 (int) ((ts / (1000 * 1000)) % 1000));
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800960}
961
962void NBLog::appendInt(String8 *body, const void *data) {
963 int x = *((int*) data);
964 body->appendFormat("<%d>", x);
965}
966
967void NBLog::appendFloat(String8 *body, const void *data) {
968 float f;
969 memcpy(&f, data, sizeof(float));
970 body->appendFormat("<%f>", f);
971}
972
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800973void NBLog::appendPID(String8 *body, const void* data, size_t length) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800974 pid_t id = *((pid_t*) data);
Nicolas Rouletc20cb502017-02-01 12:35:24 -0800975 char * name = &((char*) data)[sizeof(pid_t)];
976 body->appendFormat("<PID: %d, name: %.*s>", id, (int) (length - sizeof(pid_t)), name);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800977}
978
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700979String8 NBLog::bufferDump(const uint8_t *buffer, size_t size)
Nicolas Roulet2aedf372017-03-29 11:27:03 -0700980{
981 String8 str;
982 str.append("[ ");
983 for(size_t i = 0; i < size; i++)
984 {
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700985 str.appendFormat("%d ", buffer[i]);
Nicolas Roulet2aedf372017-03-29 11:27:03 -0700986 }
987 str.append("]");
988 return str;
989}
990
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700991String8 NBLog::bufferDump(const EntryIterator &it)
Nicolas Roulet2aedf372017-03-29 11:27:03 -0700992{
Nicolas Rouletf42f1562017-03-30 19:16:22 -0700993 return bufferDump(it, it->length + Entry::kOverhead);
Nicolas Roulet2aedf372017-03-29 11:27:03 -0700994}
995
Nicolas Roulet537ad7d2017-03-21 16:24:30 -0700996NBLog::EntryIterator NBLog::Reader::handleFormat(const FormatEntry &fmtEntry,
Nicolas Rouletcd5dd012017-02-13 12:09:28 -0800997 String8 *timestamp,
998 String8 *body) {
Nicolas Roulet40a44982017-02-03 13:39:57 -0800999 // log timestamp
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001000 int64_t ts = fmtEntry.timestamp();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001001 timestamp->clear();
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001002 timestamp->appendFormat("[%d.%03d]", (int) (ts / (1000 * 1000 * 1000)),
1003 (int) ((ts / (1000 * 1000)) % 1000));
Nicolas Roulet40a44982017-02-03 13:39:57 -08001004
Nicolas Rouletbd0c6b42017-03-16 13:54:23 -07001005 // log unique hash
1006 log_hash_t hash = fmtEntry.hash();
1007 // print only lower 16bit of hash as hex and line as int to reduce spam in the log
1008 body->appendFormat("%.4X-%d ", (int)(hash >> 16) & 0xFFFF, (int) hash & 0xFFFF);
1009
Nicolas Roulet40a44982017-02-03 13:39:57 -08001010 // log author (if present)
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001011 handleAuthor(fmtEntry, body);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001012
1013 // log string
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001014 NBLog::EntryIterator arg = fmtEntry.args();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001015
1016 const char* fmt = fmtEntry.formatString();
1017 size_t fmt_length = fmtEntry.formatStringLength();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001018
1019 for (size_t fmt_offset = 0; fmt_offset < fmt_length; ++fmt_offset) {
1020 if (fmt[fmt_offset] != '%') {
1021 body->append(&fmt[fmt_offset], 1); // TODO optimize to write consecutive strings at once
1022 continue;
1023 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001024 // case "%%""
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001025 if (fmt[++fmt_offset] == '%') {
1026 body->append("%");
1027 continue;
1028 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001029 // case "%\0"
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001030 if (fmt_offset == fmt_length) {
1031 continue;
1032 }
1033
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001034 NBLog::Event event = (NBLog::Event) arg->type;
1035 size_t length = arg->length;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001036
1037 // TODO check length for event type is correct
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001038
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001039 if (event == EVENT_END_FMT) {
1040 break;
1041 }
1042
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001043 // TODO: implement more complex formatting such as %.3f
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001044 const uint8_t *datum = arg->data; // pointer to the current event args
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001045 switch(fmt[fmt_offset])
1046 {
1047 case 's': // string
Nicolas Roulet4da78202017-02-03 12:53:39 -08001048 ALOGW_IF(event != EVENT_STRING,
1049 "NBLog Reader incompatible event for string specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001050 body->append((const char*) datum, length);
1051 break;
1052
1053 case 't': // timestamp
Nicolas Roulet4da78202017-02-03 12:53:39 -08001054 ALOGW_IF(event != EVENT_TIMESTAMP,
1055 "NBLog Reader incompatible event for timestamp specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001056 appendTimestamp(body, datum);
1057 break;
1058
1059 case 'd': // integer
Nicolas Roulet4da78202017-02-03 12:53:39 -08001060 ALOGW_IF(event != EVENT_INTEGER,
1061 "NBLog Reader incompatible event for integer specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001062 appendInt(body, datum);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001063 break;
1064
1065 case 'f': // float
Nicolas Roulet4da78202017-02-03 12:53:39 -08001066 ALOGW_IF(event != EVENT_FLOAT,
1067 "NBLog Reader incompatible event for float specifier: %d", event);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001068 appendFloat(body, datum);
1069 break;
1070
1071 case 'p': // pid
Nicolas Roulet4da78202017-02-03 12:53:39 -08001072 ALOGW_IF(event != EVENT_PID,
1073 "NBLog Reader incompatible event for pid specifier: %d", event);
Nicolas Rouletc20cb502017-02-01 12:35:24 -08001074 appendPID(body, datum, length);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001075 break;
1076
1077 default:
1078 ALOGW("NBLog Reader encountered unknown character %c", fmt[fmt_offset]);
1079 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001080 ++arg;
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001081 }
Nicolas Rouletcd5dd012017-02-13 12:09:28 -08001082 ALOGW_IF(arg->type != EVENT_END_FMT, "Expected end of format, got %d", arg->type);
1083 ++arg;
1084 return arg;
Nicolas Roulet40a44982017-02-03 13:39:57 -08001085}
1086
Nicolas Roulet40a44982017-02-03 13:39:57 -08001087NBLog::Merger::Merger(const void *shared, size_t size):
Nicolas Roulet40a44982017-02-03 13:39:57 -08001088 mShared((Shared *) shared),
1089 mFifo(mShared != NULL ?
1090 new audio_utils_fifo(size, sizeof(uint8_t),
1091 mShared->mBuffer, mShared->mRear, NULL /*throttlesFront*/) : NULL),
1092 mFifoWriter(mFifo != NULL ? new audio_utils_fifo_writer(*mFifo) : NULL)
1093 {}
1094
1095void NBLog::Merger::addReader(const NBLog::NamedReader &reader) {
Glenn Kasten1c446272017-04-07 09:49:07 -07001096 // FIXME This is called by binder thread in MediaLogService::registerWriter
1097 // but the access to shared variable mNamedReaders is not yet protected by a lock.
Nicolas Roulet40a44982017-02-03 13:39:57 -08001098 mNamedReaders.push_back(reader);
1099}
1100
1101// items placed in priority queue during merge
1102// composed by a timestamp and the index of the snapshot where the timestamp came from
1103struct MergeItem
1104{
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001105 int64_t ts;
Nicolas Roulet40a44982017-02-03 13:39:57 -08001106 int index;
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001107 MergeItem(int64_t ts, int index): ts(ts), index(index) {}
Nicolas Roulet40a44982017-02-03 13:39:57 -08001108};
1109
1110// operators needed for priority queue in merge
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001111// bool operator>(const int64_t &t1, const int64_t &t2) {
1112// return t1.tv_sec > t2.tv_sec || (t1.tv_sec == t2.tv_sec && t1.tv_nsec > t2.tv_nsec);
1113// }
Nicolas Roulet40a44982017-02-03 13:39:57 -08001114
1115bool operator>(const struct MergeItem &i1, const struct MergeItem &i2) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001116 return i1.ts > i2.ts || (i1.ts == i2.ts && i1.index > i2.index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001117}
1118
1119// Merge registered readers, sorted by timestamp
1120void NBLog::Merger::merge() {
Glenn Kasten1c446272017-04-07 09:49:07 -07001121 // FIXME This is called by merge thread
1122 // but the access to shared variable mNamedReaders is not yet protected by a lock.
Nicolas Roulet40a44982017-02-03 13:39:57 -08001123 int nLogs = mNamedReaders.size();
1124 std::vector<std::unique_ptr<NBLog::Reader::Snapshot>> snapshots(nLogs);
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001125 std::vector<NBLog::EntryIterator> offsets(nLogs);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001126 for (int i = 0; i < nLogs; ++i) {
1127 snapshots[i] = mNamedReaders[i].reader()->getSnapshot();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001128 offsets[i] = snapshots[i]->begin();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001129 }
1130 // initialize offsets
Nicolas Roulet40a44982017-02-03 13:39:57 -08001131 // TODO custom heap implementation could allow to update top, improving performance
1132 // for bursty buffers
1133 std::priority_queue<MergeItem, std::vector<MergeItem>, std::greater<MergeItem>> timestamps;
1134 for (int i = 0; i < nLogs; ++i)
1135 {
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001136 if (offsets[i] != snapshots[i]->end()) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001137 int64_t ts = AbstractEntry::buildEntry(offsets[i])->timestamp();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001138 timestamps.emplace(ts, i);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001139 }
1140 }
1141
1142 while (!timestamps.empty()) {
1143 // find minimum timestamp
1144 int index = timestamps.top().index;
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001145 // copy it to the log, increasing offset
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001146 offsets[index] = AbstractEntry::buildEntry(offsets[index])->copyWithAuthor(mFifoWriter,
1147 index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001148 // update data structures
Nicolas Roulet40a44982017-02-03 13:39:57 -08001149 timestamps.pop();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001150 if (offsets[index] != snapshots[index]->end()) {
Nicolas Rouletf42f1562017-03-30 19:16:22 -07001151 int64_t ts = AbstractEntry::buildEntry(offsets[index])->timestamp();
Nicolas Roulet6ea1d7e2017-02-14 16:17:31 -08001152 timestamps.emplace(ts, index);
Nicolas Roulet40a44982017-02-03 13:39:57 -08001153 }
1154 }
1155}
1156
Glenn Kasten1c446272017-04-07 09:49:07 -07001157const std::vector<NBLog::NamedReader>& NBLog::Merger::getNamedReaders() const {
1158 // FIXME This is returning a reference to a shared variable that needs a lock
1159 return mNamedReaders;
Nicolas Roulet40a44982017-02-03 13:39:57 -08001160}
1161
Glenn Kasten1c446272017-04-07 09:49:07 -07001162// ---------------------------------------------------------------------------
1163
Nicolas Roulet40a44982017-02-03 13:39:57 -08001164NBLog::MergeReader::MergeReader(const void *shared, size_t size, Merger &merger)
1165 : Reader(shared, size), mNamedReaders(merger.getNamedReaders()) {}
1166
Nicolas Roulet537ad7d2017-03-21 16:24:30 -07001167void NBLog::MergeReader::handleAuthor(const NBLog::AbstractEntry &entry, String8 *body) {
1168 int author = entry.author();
Glenn Kasten1c446272017-04-07 09:49:07 -07001169 // FIXME Needs a lock
1170 const char* name = mNamedReaders[author].name();
Nicolas Roulet40a44982017-02-03 13:39:57 -08001171 body->appendFormat("%s: ", name);
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08001172}
1173
Glenn Kasten1c446272017-04-07 09:49:07 -07001174// ---------------------------------------------------------------------------
1175
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08001176NBLog::MergeThread::MergeThread(NBLog::Merger &merger)
1177 : mMerger(merger),
1178 mTimeoutUs(0) {}
1179
1180NBLog::MergeThread::~MergeThread() {
1181 // set exit flag, set timeout to 0 to force threadLoop to exit and wait for the thread to join
1182 requestExit();
1183 setTimeoutUs(0);
1184 join();
1185}
1186
1187bool NBLog::MergeThread::threadLoop() {
1188 bool doMerge;
1189 {
1190 AutoMutex _l(mMutex);
1191 // If mTimeoutUs is negative, wait on the condition variable until it's positive.
1192 // If it's positive, wait kThreadSleepPeriodUs and then merge
1193 nsecs_t waitTime = mTimeoutUs > 0 ? kThreadSleepPeriodUs * 1000 : LLONG_MAX;
1194 mCond.waitRelative(mMutex, waitTime);
1195 doMerge = mTimeoutUs > 0;
1196 mTimeoutUs -= kThreadSleepPeriodUs;
1197 }
1198 if (doMerge) {
1199 mMerger.merge();
1200 }
1201 return true;
1202}
1203
1204void NBLog::MergeThread::wakeup() {
1205 setTimeoutUs(kThreadWakeupPeriodUs);
1206}
1207
1208void NBLog::MergeThread::setTimeoutUs(int time) {
1209 AutoMutex _l(mMutex);
1210 mTimeoutUs = time;
1211 mCond.signal();
1212}
1213
Glenn Kasten11d8dfc2013-01-14 14:53:13 -08001214} // namespace android