blob: 12aa84e273890d5b8714133128096451752ed31d [file] [log] [blame]
Mark Salyzyn12bac902014-02-26 09:50:16 -08001/*
2 * Copyright (C) 2012-2014 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
Mark Salyzyn4e756fb2014-05-06 07:34:59 -070017#include <ctype.h>
Mark Salyzyn88fe7cc2015-02-09 08:21:05 -080018#include <errno.h>
Mark Salyzyn12bac902014-02-26 09:50:16 -080019#include <stdio.h>
20#include <string.h>
Mark Salyzyn7b85c592014-05-09 17:44:18 -070021#include <sys/user.h>
Mark Salyzyn12bac902014-02-26 09:50:16 -080022#include <time.h>
23#include <unistd.h>
24
Mark Salyzyn6a404192015-05-19 09:12:30 -070025#include <unordered_map>
26
Mark Salyzyn4e756fb2014-05-06 07:34:59 -070027#include <cutils/properties.h>
Mark Salyzyn12bac902014-02-26 09:50:16 -080028#include <log/logger.h>
29
30#include "LogBuffer.h"
Mark Salyzyn2b4a7632015-09-08 08:56:32 -070031#include "LogKlog.h"
Mark Salyzyn4e756fb2014-05-06 07:34:59 -070032#include "LogReader.h"
Mark Salyzyn12bac902014-02-26 09:50:16 -080033
Mark Salyzync89839a2014-02-11 12:29:31 -080034// Default
Mark Salyzyn12bac902014-02-26 09:50:16 -080035#define LOG_BUFFER_SIZE (256 * 1024) // Tuned on a per-platform basis here?
Mark Salyzync89839a2014-02-11 12:29:31 -080036#define log_buffer_size(id) mMaxSize[id]
Mark Salyzyn7b85c592014-05-09 17:44:18 -070037#define LOG_BUFFER_MIN_SIZE (64 * 1024UL)
38#define LOG_BUFFER_MAX_SIZE (256 * 1024 * 1024UL)
39
40static bool valid_size(unsigned long value) {
41 if ((value < LOG_BUFFER_MIN_SIZE) || (LOG_BUFFER_MAX_SIZE < value)) {
42 return false;
43 }
44
45 long pages = sysconf(_SC_PHYS_PAGES);
46 if (pages < 1) {
47 return true;
48 }
49
50 long pagesize = sysconf(_SC_PAGESIZE);
51 if (pagesize <= 1) {
52 pagesize = PAGE_SIZE;
53 }
54
55 // maximum memory impact a somewhat arbitrary ~3%
56 pages = (pages + 31) / 32;
57 unsigned long maximum = pages * pagesize;
58
59 if ((maximum < LOG_BUFFER_MIN_SIZE) || (LOG_BUFFER_MAX_SIZE < maximum)) {
60 return true;
61 }
62
63 return value <= maximum;
64}
Mark Salyzyn12bac902014-02-26 09:50:16 -080065
Mark Salyzyn4e756fb2014-05-06 07:34:59 -070066static unsigned long property_get_size(const char *key) {
67 char property[PROPERTY_VALUE_MAX];
68 property_get(key, property, "");
69
70 char *cp;
71 unsigned long value = strtoul(property, &cp, 10);
72
73 switch(*cp) {
74 case 'm':
75 case 'M':
76 value *= 1024;
77 /* FALLTHRU */
78 case 'k':
79 case 'K':
80 value *= 1024;
81 /* FALLTHRU */
82 case '\0':
83 break;
84
85 default:
86 value = 0;
87 }
88
Mark Salyzyn7b85c592014-05-09 17:44:18 -070089 if (!valid_size(value)) {
90 value = 0;
91 }
92
Mark Salyzyn4e756fb2014-05-06 07:34:59 -070093 return value;
94}
95
Mark Salyzyn3fe25932015-03-10 16:45:17 -070096void LogBuffer::init() {
Mark Salyzyn7b85c592014-05-09 17:44:18 -070097 static const char global_tuneable[] = "persist.logd.size"; // Settings App
98 static const char global_default[] = "ro.logd.size"; // BoardConfig.mk
99
100 unsigned long default_size = property_get_size(global_tuneable);
101 if (!default_size) {
102 default_size = property_get_size(global_default);
Mark Salyzyn973d18c2015-12-14 13:07:12 -0800103 if (!default_size) {
104 default_size = property_get_bool("ro.config.low_ram", false) ?
105 LOG_BUFFER_MIN_SIZE : // 64K
106 LOG_BUFFER_SIZE; // 256K
107 }
Mark Salyzyn7b85c592014-05-09 17:44:18 -0700108 }
Mark Salyzyn4e756fb2014-05-06 07:34:59 -0700109
Mark Salyzync89839a2014-02-11 12:29:31 -0800110 log_id_for_each(i) {
Mark Salyzyn4e756fb2014-05-06 07:34:59 -0700111 char key[PROP_NAME_MAX];
Mark Salyzyn4e756fb2014-05-06 07:34:59 -0700112
Mark Salyzyn7b85c592014-05-09 17:44:18 -0700113 snprintf(key, sizeof(key), "%s.%s",
114 global_tuneable, android_log_id_to_name(i));
115 unsigned long property_size = property_get_size(key);
116
117 if (!property_size) {
118 snprintf(key, sizeof(key), "%s.%s",
119 global_default, android_log_id_to_name(i));
120 property_size = property_get_size(key);
121 }
122
123 if (!property_size) {
124 property_size = default_size;
125 }
126
127 if (!property_size) {
128 property_size = LOG_BUFFER_SIZE;
129 }
130
131 if (setSize(i, property_size)) {
132 setSize(i, LOG_BUFFER_MIN_SIZE);
133 }
Mark Salyzync89839a2014-02-11 12:29:31 -0800134 }
Mark Salyzyn2b4a7632015-09-08 08:56:32 -0700135 bool lastMonotonic = monotonic;
Mark Salyzyn2d4f9bc2015-12-01 15:57:25 -0800136 monotonic = android_log_clockid() == CLOCK_MONOTONIC;
Mark Salyzyn552b4752015-11-30 11:35:56 -0800137 if (lastMonotonic != monotonic) {
138 //
139 // Fixup all timestamps, may not be 100% accurate, but better than
140 // throwing what we have away when we get 'surprised' by a change.
141 // In-place element fixup so no need to check reader-lock. Entries
142 // should already be in timestamp order, but we could end up with a
143 // few out-of-order entries if new monotonics come in before we
144 // are notified of the reinit change in status. A Typical example would
145 // be:
146 // --------- beginning of system
147 // 10.494082 184 201 D Cryptfs : Just triggered post_fs_data
148 // --------- beginning of kernel
149 // 0.000000 0 0 I : Initializing cgroup subsys
150 // as the act of mounting /data would trigger persist.logd.timestamp to
151 // be corrected. 1/30 corner case YMMV.
152 //
153 pthread_mutex_lock(&mLogElementsLock);
154 LogBufferElementCollection::iterator it = mLogElements.begin();
155 while((it != mLogElements.end())) {
156 LogBufferElement *e = *it;
157 if (monotonic) {
158 if (!android::isMonotonic(e->mRealTime)) {
159 LogKlog::convertRealToMonotonic(e->mRealTime);
160 }
161 } else {
162 if (android::isMonotonic(e->mRealTime)) {
163 LogKlog::convertMonotonicToReal(e->mRealTime);
164 }
165 }
166 ++it;
167 }
168 pthread_mutex_unlock(&mLogElementsLock);
Mark Salyzyn2b4a7632015-09-08 08:56:32 -0700169 }
170
Mark Salyzyn552b4752015-11-30 11:35:56 -0800171 // We may have been triggered by a SIGHUP. Release any sleeping reader
172 // threads to dump their current content.
Mark Salyzyn2b4a7632015-09-08 08:56:32 -0700173 //
Mark Salyzyn552b4752015-11-30 11:35:56 -0800174 // NB: this is _not_ performed in the context of a SIGHUP, it is
175 // performed during startup, and in context of reinit administrative thread
176 LogTimeEntry::lock();
177
178 LastLogTimes::iterator times = mTimes.begin();
179 while(times != mTimes.end()) {
180 LogTimeEntry *entry = (*times);
181 if (entry->owned_Locked()) {
182 entry->triggerReader_Locked();
Mark Salyzyn2b4a7632015-09-08 08:56:32 -0700183 }
Mark Salyzyn552b4752015-11-30 11:35:56 -0800184 times++;
Mark Salyzyn2b4a7632015-09-08 08:56:32 -0700185 }
Mark Salyzyn552b4752015-11-30 11:35:56 -0800186
187 LogTimeEntry::unlock();
Mark Salyzyn12bac902014-02-26 09:50:16 -0800188}
189
Mark Salyzyn2b4a7632015-09-08 08:56:32 -0700190LogBuffer::LogBuffer(LastLogTimes *times):
Mark Salyzyn2d4f9bc2015-12-01 15:57:25 -0800191 monotonic(android_log_clockid() == CLOCK_MONOTONIC),
Mark Salyzyn2b4a7632015-09-08 08:56:32 -0700192 mTimes(*times) {
Mark Salyzyn3fe25932015-03-10 16:45:17 -0700193 pthread_mutex_init(&mLogElementsLock, NULL);
194
195 init();
196}
197
Mark Salyzyn88fe7cc2015-02-09 08:21:05 -0800198int LogBuffer::log(log_id_t log_id, log_time realtime,
199 uid_t uid, pid_t pid, pid_t tid,
200 const char *msg, unsigned short len) {
Mark Salyzyn12bac902014-02-26 09:50:16 -0800201 if ((log_id >= LOG_ID_MAX) || (log_id < 0)) {
Mark Salyzyn88fe7cc2015-02-09 08:21:05 -0800202 return -EINVAL;
Mark Salyzyn12bac902014-02-26 09:50:16 -0800203 }
Mark Salyzyn19c91112014-10-02 13:07:05 -0700204
Mark Salyzyn12bac902014-02-26 09:50:16 -0800205 LogBufferElement *elem = new LogBufferElement(log_id, realtime,
Mark Salyzyn3661dd02014-03-20 16:09:38 -0700206 uid, pid, tid, msg, len);
Mark Salyzyn8885daf2015-12-04 10:59:45 -0800207 if (log_id != LOG_ID_SECURITY) {
208 int prio = ANDROID_LOG_INFO;
209 const char *tag = NULL;
210 if (log_id == LOG_ID_EVENTS) {
211 tag = android::tagToName(elem->getTag());
212 } else {
213 prio = *msg;
214 tag = msg + 1;
215 }
216 if (!__android_log_is_loggable(prio, tag, ANDROID_LOG_VERBOSE)) {
217 // Log traffic received to total
218 pthread_mutex_lock(&mLogElementsLock);
219 stats.add(elem);
220 stats.subtract(elem);
221 pthread_mutex_unlock(&mLogElementsLock);
222 delete elem;
223 return -EACCES;
224 }
Mark Salyzyn19c91112014-10-02 13:07:05 -0700225 }
Mark Salyzyn12bac902014-02-26 09:50:16 -0800226
227 pthread_mutex_lock(&mLogElementsLock);
228
229 // Insert elements in time sorted order if possible
230 // NB: if end is region locked, place element at end of list
231 LogBufferElementCollection::iterator it = mLogElements.end();
232 LogBufferElementCollection::iterator last = it;
Mark Salyzyna222a772014-10-13 16:49:47 -0700233 while (last != mLogElements.begin()) {
234 --it;
Mark Salyzyn5b7a8d82014-02-18 11:23:53 -0800235 if ((*it)->getRealTime() <= realtime) {
Mark Salyzyn12bac902014-02-26 09:50:16 -0800236 break;
237 }
238 last = it;
239 }
Mark Salyzyn5b7a8d82014-02-18 11:23:53 -0800240
Mark Salyzyn12bac902014-02-26 09:50:16 -0800241 if (last == mLogElements.end()) {
242 mLogElements.push_back(elem);
243 } else {
Mark Salyzyn0aaf6cd2015-03-03 13:39:37 -0800244 uint64_t end = 1;
Mark Salyzyn12bac902014-02-26 09:50:16 -0800245 bool end_set = false;
246 bool end_always = false;
247
248 LogTimeEntry::lock();
249
250 LastLogTimes::iterator t = mTimes.begin();
251 while(t != mTimes.end()) {
252 LogTimeEntry *entry = (*t);
253 if (entry->owned_Locked()) {
254 if (!entry->mNonBlock) {
255 end_always = true;
256 break;
257 }
258 if (!end_set || (end <= entry->mEnd)) {
259 end = entry->mEnd;
260 end_set = true;
261 }
262 }
263 t++;
264 }
265
266 if (end_always
Mark Salyzyn0aaf6cd2015-03-03 13:39:37 -0800267 || (end_set && (end >= (*last)->getSequence()))) {
Mark Salyzyn12bac902014-02-26 09:50:16 -0800268 mLogElements.push_back(elem);
269 } else {
270 mLogElements.insert(last,elem);
271 }
272
273 LogTimeEntry::unlock();
274 }
275
Mark Salyzyn9cf5d402015-03-10 13:51:35 -0700276 stats.add(elem);
Mark Salyzyn12bac902014-02-26 09:50:16 -0800277 maybePrune(log_id);
278 pthread_mutex_unlock(&mLogElementsLock);
Mark Salyzyn88fe7cc2015-02-09 08:21:05 -0800279
280 return len;
Mark Salyzyn12bac902014-02-26 09:50:16 -0800281}
282
Mark Salyzyn95ff2482015-09-30 07:40:09 -0700283// Prune at most 10% of the log entries or maxPrune, whichever is less.
Mark Salyzyn12bac902014-02-26 09:50:16 -0800284//
285// mLogElementsLock must be held when this function is called.
286void LogBuffer::maybePrune(log_id_t id) {
Mark Salyzynd774bce2014-02-06 14:48:50 -0800287 size_t sizes = stats.sizes(id);
Mark Salyzyn4436d4c2015-08-10 10:23:56 -0700288 unsigned long maxSize = log_buffer_size(id);
289 if (sizes > maxSize) {
Mark Salyzyn63745722015-08-19 12:20:36 -0700290 size_t sizeOver = sizes - ((maxSize * 9) / 10);
Mark Salyzynd745c722015-09-30 07:40:09 -0700291 size_t elements = stats.realElements(id);
292 size_t minElements = elements / 100;
293 if (minElements < minPrune) {
294 minElements = minPrune;
295 }
Mark Salyzyn4436d4c2015-08-10 10:23:56 -0700296 unsigned long pruneRows = elements * sizeOver / sizes;
Mark Salyzyn95ff2482015-09-30 07:40:09 -0700297 if (pruneRows < minElements) {
Mark Salyzyn4436d4c2015-08-10 10:23:56 -0700298 pruneRows = minElements;
Mark Salyzyn9d4e34e2014-01-13 16:37:51 -0800299 }
Mark Salyzyn95ff2482015-09-30 07:40:09 -0700300 if (pruneRows > maxPrune) {
301 pruneRows = maxPrune;
Mark Salyzyn63745722015-08-19 12:20:36 -0700302 }
Mark Salyzyn9d4e34e2014-01-13 16:37:51 -0800303 prune(id, pruneRows);
Mark Salyzyn12bac902014-02-26 09:50:16 -0800304 }
305}
306
Mark Salyzyn57b82a62015-09-03 16:08:50 -0700307LogBufferElementCollection::iterator LogBuffer::erase(
Mark Salyzyn95ff2482015-09-30 07:40:09 -0700308 LogBufferElementCollection::iterator it, bool coalesce) {
Mark Salyzyn9cf5d402015-03-10 13:51:35 -0700309 LogBufferElement *e = *it;
Mark Salyzyncfcffdaf2015-08-19 17:06:11 -0700310 log_id_t id = e->getLogId();
Mark Salyzyn9cf5d402015-03-10 13:51:35 -0700311
Mark Salyzyn50e21082015-09-08 09:12:51 -0700312 LogBufferIteratorMap::iterator f = mLastWorstUid[id].find(e->getUid());
Mark Salyzyncfcffdaf2015-08-19 17:06:11 -0700313 if ((f != mLastWorstUid[id].end()) && (it == f->second)) {
314 mLastWorstUid[id].erase(f);
315 }
Mark Salyzyn9cf5d402015-03-10 13:51:35 -0700316 it = mLogElements.erase(it);
Mark Salyzyn95ff2482015-09-30 07:40:09 -0700317 if (coalesce) {
Mark Salyzyn57b82a62015-09-03 16:08:50 -0700318 stats.erase(e);
Mark Salyzyn95ff2482015-09-30 07:40:09 -0700319 } else {
320 stats.subtract(e);
Mark Salyzyn57b82a62015-09-03 16:08:50 -0700321 }
Mark Salyzyn9cf5d402015-03-10 13:51:35 -0700322 delete e;
323
324 return it;
325}
326
Mark Salyzynd84b27e2015-04-17 15:38:04 -0700327// Define a temporary mechanism to report the last LogBufferElement pointer
328// for the specified uid, pid and tid. Used below to help merge-sort when
329// pruning for worst UID.
330class LogBufferElementKey {
331 const union {
332 struct {
333 uint16_t uid;
334 uint16_t pid;
335 uint16_t tid;
336 uint16_t padding;
337 } __packed;
338 uint64_t value;
339 } __packed;
340
341public:
342 LogBufferElementKey(uid_t u, pid_t p, pid_t t):uid(u),pid(p),tid(t),padding(0) { }
343 LogBufferElementKey(uint64_t k):value(k) { }
344
345 uint64_t getKey() { return value; }
346};
347
Mark Salyzyn6a404192015-05-19 09:12:30 -0700348class LogBufferElementLast {
349
350 typedef std::unordered_map<uint64_t, LogBufferElement *> LogBufferElementMap;
351 LogBufferElementMap map;
Mark Salyzynd84b27e2015-04-17 15:38:04 -0700352
353public:
Mark Salyzynd84b27e2015-04-17 15:38:04 -0700354
Mark Salyzyn95ff2482015-09-30 07:40:09 -0700355 bool coalesce(LogBufferElement *e, unsigned short dropped) {
Mark Salyzynd84b27e2015-04-17 15:38:04 -0700356 LogBufferElementKey key(e->getUid(), e->getPid(), e->getTid());
Mark Salyzyn6a404192015-05-19 09:12:30 -0700357 LogBufferElementMap::iterator it = map.find(key.getKey());
358 if (it != map.end()) {
359 LogBufferElement *l = it->second;
Mark Salyzynd84b27e2015-04-17 15:38:04 -0700360 unsigned short d = l->getDropped();
361 if ((dropped + d) > USHRT_MAX) {
Mark Salyzyn6a404192015-05-19 09:12:30 -0700362 map.erase(it);
Mark Salyzynd84b27e2015-04-17 15:38:04 -0700363 } else {
364 l->setDropped(dropped + d);
365 return true;
366 }
367 }
368 return false;
369 }
370
Mark Salyzyn6a404192015-05-19 09:12:30 -0700371 void add(LogBufferElement *e) {
Mark Salyzynd84b27e2015-04-17 15:38:04 -0700372 LogBufferElementKey key(e->getUid(), e->getPid(), e->getTid());
Mark Salyzyn6a404192015-05-19 09:12:30 -0700373 map[key.getKey()] = e;
Mark Salyzynd84b27e2015-04-17 15:38:04 -0700374 }
375
Mark Salyzynbe1a30c2015-04-20 14:08:56 -0700376 inline void clear() {
Mark Salyzyn6a404192015-05-19 09:12:30 -0700377 map.clear();
Mark Salyzynbe1a30c2015-04-20 14:08:56 -0700378 }
379
380 void clear(LogBufferElement *e) {
Mark Salyzyn80c1fc62015-06-04 13:35:30 -0700381 uint64_t current = e->getRealTime().nsec()
382 - (EXPIRE_RATELIMIT * NS_PER_SEC);
Mark Salyzyn6a404192015-05-19 09:12:30 -0700383 for(LogBufferElementMap::iterator it = map.begin(); it != map.end();) {
384 LogBufferElement *l = it->second;
Mark Salyzyn4f199f32015-05-15 15:58:17 -0700385 if ((l->getDropped() >= EXPIRE_THRESHOLD)
386 && (current > l->getRealTime().nsec())) {
Mark Salyzyn6a404192015-05-19 09:12:30 -0700387 it = map.erase(it);
388 } else {
389 ++it;
Mark Salyzynbe1a30c2015-04-20 14:08:56 -0700390 }
391 }
392 }
393
Mark Salyzynd84b27e2015-04-17 15:38:04 -0700394};
395
Mark Salyzyn12bac902014-02-26 09:50:16 -0800396// prune "pruneRows" of type "id" from the buffer.
397//
Mark Salyzyn50e21082015-09-08 09:12:51 -0700398// This garbage collection task is used to expire log entries. It is called to
399// remove all logs (clear), all UID logs (unprivileged clear), or every
400// 256 or 10% of the total logs (whichever is less) to prune the logs.
401//
402// First there is a prep phase where we discover the reader region lock that
403// acts as a backstop to any pruning activity to stop there and go no further.
404//
405// There are three major pruning loops that follow. All expire from the oldest
406// entries. Since there are multiple log buffers, the Android logging facility
407// will appear to drop entries 'in the middle' when looking at multiple log
408// sources and buffers. This effect is slightly more prominent when we prune
409// the worst offender by logging source. Thus the logs slowly loose content
410// and value as you move back in time. This is preferred since chatty sources
411// invariably move the logs value down faster as less chatty sources would be
412// expired in the noise.
413//
414// The first loop performs blacklisting and worst offender pruning. Falling
415// through when there are no notable worst offenders and have not hit the
416// region lock preventing further worst offender pruning. This loop also looks
417// after managing the chatty log entries and merging to help provide
418// statistical basis for blame. The chatty entries are not a notification of
419// how much logs you may have, but instead represent how much logs you would
420// have had in a virtual log buffer that is extended to cover all the in-memory
421// logs without loss. They last much longer than the represented pruned logs
422// since they get multiplied by the gains in the non-chatty log sources.
423//
424// The second loop get complicated because an algorithm of watermarks and
425// history is maintained to reduce the order and keep processing time
426// down to a minimum at scale. These algorithms can be costly in the face
427// of larger log buffers, or severly limited processing time granted to a
428// background task at lowest priority.
429//
430// This second loop does straight-up expiration from the end of the logs
431// (again, remember for the specified log buffer id) but does some whitelist
432// preservation. Thus whitelist is a Hail Mary low priority, blacklists and
433// spam filtration all take priority. This second loop also checks if a region
434// lock is causing us to buffer too much in the logs to help the reader(s),
435// and will tell the slowest reader thread to skip log entries, and if
436// persistent and hits a further threshold, kill the reader thread.
437//
438// The third thread is optional, and only gets hit if there was a whitelist
439// and more needs to be pruned against the backstop of the region lock.
440//
Mark Salyzyn12bac902014-02-26 09:50:16 -0800441// mLogElementsLock must be held when this function is called.
Mark Salyzyn50e21082015-09-08 09:12:51 -0700442//
Mark Salyzyn7702c3e2015-09-16 15:34:00 -0700443bool LogBuffer::prune(log_id_t id, unsigned long pruneRows, uid_t caller_uid) {
Mark Salyzyn12bac902014-02-26 09:50:16 -0800444 LogTimeEntry *oldest = NULL;
Mark Salyzyn7702c3e2015-09-16 15:34:00 -0700445 bool busy = false;
Mark Salyzynd280d812015-09-16 15:34:00 -0700446 bool clearAll = pruneRows == ULONG_MAX;
Mark Salyzyn12bac902014-02-26 09:50:16 -0800447
448 LogTimeEntry::lock();
449
450 // Region locked?
451 LastLogTimes::iterator t = mTimes.begin();
452 while(t != mTimes.end()) {
453 LogTimeEntry *entry = (*t);
TraianX Schiau6ba427e2014-12-17 10:53:41 +0200454 if (entry->owned_Locked() && entry->isWatching(id)
Mark Salyzyn552b4752015-11-30 11:35:56 -0800455 && (!oldest ||
456 (oldest->mStart > entry->mStart) ||
457 ((oldest->mStart == entry->mStart) &&
458 (entry->mTimeout.tv_sec || entry->mTimeout.tv_nsec)))) {
Mark Salyzyn12bac902014-02-26 09:50:16 -0800459 oldest = entry;
460 }
461 t++;
462 }
463
Mark Salyzyn5c06ca42014-02-06 18:11:13 -0800464 LogBufferElementCollection::iterator it;
465
Mark Salyzyn276d5352014-06-12 11:16:16 -0700466 if (caller_uid != AID_ROOT) {
Mark Salyzynd280d812015-09-16 15:34:00 -0700467 // Only here if clearAll condition (pruneRows == ULONG_MAX)
Mark Salyzyn276d5352014-06-12 11:16:16 -0700468 for(it = mLogElements.begin(); it != mLogElements.end();) {
469 LogBufferElement *e = *it;
470
Mark Salyzynd280d812015-09-16 15:34:00 -0700471 if ((e->getLogId() != id) || (e->getUid() != caller_uid)) {
472 ++it;
473 continue;
474 }
475
Mark Salyzyn0aaf6cd2015-03-03 13:39:37 -0800476 if (oldest && (oldest->mStart <= e->getSequence())) {
Mark Salyzyn7702c3e2015-09-16 15:34:00 -0700477 busy = true;
Mark Salyzyn552b4752015-11-30 11:35:56 -0800478 if (oldest->mTimeout.tv_sec || oldest->mTimeout.tv_nsec) {
479 oldest->triggerReader_Locked();
480 } else {
481 oldest->triggerSkip_Locked(id, pruneRows);
482 }
Mark Salyzyn276d5352014-06-12 11:16:16 -0700483 break;
484 }
485
Mark Salyzynd280d812015-09-16 15:34:00 -0700486 it = erase(it);
487 pruneRows--;
Mark Salyzyn276d5352014-06-12 11:16:16 -0700488 }
489 LogTimeEntry::unlock();
Mark Salyzyn7702c3e2015-09-16 15:34:00 -0700490 return busy;
Mark Salyzyn276d5352014-06-12 11:16:16 -0700491 }
492
Mark Salyzyn5c06ca42014-02-06 18:11:13 -0800493 // prune by worst offender by uid
Mark Salyzyn8885daf2015-12-04 10:59:45 -0800494 bool hasBlacklist = (id != LOG_ID_SECURITY) && mPrune.naughty();
Mark Salyzynd280d812015-09-16 15:34:00 -0700495 while (!clearAll && (pruneRows > 0)) {
Mark Salyzyn5c06ca42014-02-06 18:11:13 -0800496 // recalculate the worst offender on every batched pass
497 uid_t worst = (uid_t) -1;
498 size_t worst_sizes = 0;
499 size_t second_worst_sizes = 0;
500
Mark Salyzyn0e765c62015-03-17 17:17:25 -0700501 if (worstUidEnabledForLogid(id) && mPrune.worstUidEnabled()) {
Mark Salyzynb921ab52015-12-17 09:58:43 -0800502 std::unique_ptr<const UidEntry *[]> sorted = stats.sort(
503 AID_ROOT, (pid_t)0, 2, id);
Mark Salyzyn9cf5d402015-03-10 13:51:35 -0700504
Mark Salyzyn1435b472015-03-16 08:26:05 -0700505 if (sorted.get()) {
Mark Salyzyn9cf5d402015-03-10 13:51:35 -0700506 if (sorted[0] && sorted[1]) {
Mark Salyzyn9cf5d402015-03-10 13:51:35 -0700507 worst_sizes = sorted[0]->getSizes();
Mark Salyzyn84a83982015-04-20 15:36:12 -0700508 // Calculate threshold as 12.5% of available storage
509 size_t threshold = log_buffer_size(id) / 8;
Mark Salyzyn2b9465b2015-10-12 13:45:51 -0700510 if ((worst_sizes > threshold)
511 // Allow time horizon to extend roughly tenfold, assume
512 // average entry length is 100 characters.
513 && (worst_sizes > (10 * sorted[0]->getDropped()))) {
Mark Salyzyn84a83982015-04-20 15:36:12 -0700514 worst = sorted[0]->getKey();
515 second_worst_sizes = sorted[1]->getSizes();
516 if (second_worst_sizes < threshold) {
517 second_worst_sizes = threshold;
518 }
519 }
Mark Salyzync89839a2014-02-11 12:29:31 -0800520 }
Mark Salyzyn5c06ca42014-02-06 18:11:13 -0800521 }
522 }
523
Mark Salyzyn9cf5d402015-03-10 13:51:35 -0700524 // skip if we have neither worst nor naughty filters
525 if ((worst == (uid_t) -1) && !hasBlacklist) {
526 break;
527 }
528
Mark Salyzyn5c06ca42014-02-06 18:11:13 -0800529 bool kick = false;
Mark Salyzyna69d5a42015-03-16 12:04:09 -0700530 bool leading = true;
Mark Salyzyncfcffdaf2015-08-19 17:06:11 -0700531 it = mLogElements.begin();
Mark Salyzyn50e21082015-09-08 09:12:51 -0700532 // Perform at least one mandatory garbage collection cycle in following
533 // - clear leading chatty tags
Mark Salyzyn95ff2482015-09-30 07:40:09 -0700534 // - coalesce chatty tags
Mark Salyzyn50e21082015-09-08 09:12:51 -0700535 // - check age-out of preserved logs
536 bool gc = pruneRows <= 1;
537 if (!gc && (worst != (uid_t) -1)) {
Mark Salyzyncfcffdaf2015-08-19 17:06:11 -0700538 LogBufferIteratorMap::iterator f = mLastWorstUid[id].find(worst);
539 if ((f != mLastWorstUid[id].end())
540 && (f->second != mLogElements.end())) {
541 leading = false;
542 it = f->second;
543 }
544 }
Mark Salyzyn4e29e172015-08-24 13:43:27 -0700545 static const timespec too_old = {
546 EXPIRE_HOUR_THRESHOLD * 60 * 60, 0
547 };
548 LogBufferElementCollection::iterator lastt;
549 lastt = mLogElements.end();
550 --lastt;
Mark Salyzynd84b27e2015-04-17 15:38:04 -0700551 LogBufferElementLast last;
Mark Salyzyncfcffdaf2015-08-19 17:06:11 -0700552 while (it != mLogElements.end()) {
Mark Salyzyn5c06ca42014-02-06 18:11:13 -0800553 LogBufferElement *e = *it;
554
Mark Salyzyn0aaf6cd2015-03-03 13:39:37 -0800555 if (oldest && (oldest->mStart <= e->getSequence())) {
Mark Salyzyn7702c3e2015-09-16 15:34:00 -0700556 busy = true;
Mark Salyzyn552b4752015-11-30 11:35:56 -0800557 if (oldest->mTimeout.tv_sec || oldest->mTimeout.tv_nsec) {
558 oldest->triggerReader_Locked();
559 }
Mark Salyzyn5c06ca42014-02-06 18:11:13 -0800560 break;
561 }
562
Mark Salyzync89839a2014-02-11 12:29:31 -0800563 if (e->getLogId() != id) {
564 ++it;
565 continue;
566 }
567
Mark Salyzyna69d5a42015-03-16 12:04:09 -0700568 unsigned short dropped = e->getDropped();
Mark Salyzync89839a2014-02-11 12:29:31 -0800569
Mark Salyzyna69d5a42015-03-16 12:04:09 -0700570 // remove any leading drops
571 if (leading && dropped) {
572 it = erase(it);
573 continue;
574 }
575
Mark Salyzyn95ff2482015-09-30 07:40:09 -0700576 if (dropped && last.coalesce(e, dropped)) {
577 it = erase(it, true);
Mark Salyzyna69d5a42015-03-16 12:04:09 -0700578 continue;
579 }
580
Mark Salyzyna69d5a42015-03-16 12:04:09 -0700581 if (hasBlacklist && mPrune.naughty(e)) {
Mark Salyzynbe1a30c2015-04-20 14:08:56 -0700582 last.clear(e);
Mark Salyzyna69d5a42015-03-16 12:04:09 -0700583 it = erase(it);
584 if (dropped) {
585 continue;
586 }
587
588 pruneRows--;
589 if (pruneRows == 0) {
590 break;
591 }
592
593 if (e->getUid() == worst) {
594 kick = true;
595 if (worst_sizes < second_worst_sizes) {
596 break;
597 }
598 worst_sizes -= e->getMsgLen();
599 }
600 continue;
601 }
602
Mark Salyzyn4e29e172015-08-24 13:43:27 -0700603 if ((e->getRealTime() < ((*lastt)->getRealTime() - too_old))
604 || (e->getRealTime() > (*lastt)->getRealTime())) {
605 break;
606 }
607
Mark Salyzyna69d5a42015-03-16 12:04:09 -0700608 if (dropped) {
Mark Salyzynd84b27e2015-04-17 15:38:04 -0700609 last.add(e);
Mark Salyzyn50e21082015-09-08 09:12:51 -0700610 if ((!gc && (e->getUid() == worst))
Mark Salyzyncb15c7c2015-08-24 13:43:27 -0700611 || (mLastWorstUid[id].find(e->getUid())
612 == mLastWorstUid[id].end())) {
613 mLastWorstUid[id][e->getUid()] = it;
614 }
Mark Salyzyn5c06ca42014-02-06 18:11:13 -0800615 ++it;
Mark Salyzyn9cf5d402015-03-10 13:51:35 -0700616 continue;
Mark Salyzyn5c06ca42014-02-06 18:11:13 -0800617 }
Mark Salyzyn9cf5d402015-03-10 13:51:35 -0700618
Mark Salyzyna69d5a42015-03-16 12:04:09 -0700619 if (e->getUid() != worst) {
Mark Salyzynfd318a82015-06-01 09:41:19 -0700620 leading = false;
Mark Salyzynbe1a30c2015-04-20 14:08:56 -0700621 last.clear(e);
Mark Salyzyna69d5a42015-03-16 12:04:09 -0700622 ++it;
623 continue;
624 }
625
Mark Salyzyn9cf5d402015-03-10 13:51:35 -0700626 pruneRows--;
627 if (pruneRows == 0) {
628 break;
629 }
630
Mark Salyzyn9cf5d402015-03-10 13:51:35 -0700631 kick = true;
Mark Salyzyna69d5a42015-03-16 12:04:09 -0700632
633 unsigned short len = e->getMsgLen();
Mark Salyzyn65ec8602015-05-22 10:03:31 -0700634
635 // do not create any leading drops
636 if (leading) {
637 it = erase(it);
Mark Salyzyna69d5a42015-03-16 12:04:09 -0700638 } else {
Mark Salyzyn65ec8602015-05-22 10:03:31 -0700639 stats.drop(e);
640 e->setDropped(1);
Mark Salyzyn95ff2482015-09-30 07:40:09 -0700641 if (last.coalesce(e, 1)) {
642 it = erase(it, true);
Mark Salyzyn65ec8602015-05-22 10:03:31 -0700643 } else {
644 last.add(e);
Mark Salyzyn50e21082015-09-08 09:12:51 -0700645 if (!gc || (mLastWorstUid[id].find(worst)
646 == mLastWorstUid[id].end())) {
647 mLastWorstUid[id][worst] = it;
648 }
Mark Salyzyn65ec8602015-05-22 10:03:31 -0700649 ++it;
650 }
Mark Salyzyna69d5a42015-03-16 12:04:09 -0700651 }
Mark Salyzyn9cf5d402015-03-10 13:51:35 -0700652 if (worst_sizes < second_worst_sizes) {
653 break;
654 }
655 worst_sizes -= len;
Mark Salyzyn5c06ca42014-02-06 18:11:13 -0800656 }
Mark Salyzynd84b27e2015-04-17 15:38:04 -0700657 last.clear();
Mark Salyzyn5c06ca42014-02-06 18:11:13 -0800658
Mark Salyzync402bc72014-04-01 17:19:47 -0700659 if (!kick || !mPrune.worstUidEnabled()) {
Mark Salyzyn5c06ca42014-02-06 18:11:13 -0800660 break; // the following loop will ask bad clients to skip/drop
661 }
662 }
663
Mark Salyzync89839a2014-02-11 12:29:31 -0800664 bool whitelist = false;
Mark Salyzyn8885daf2015-12-04 10:59:45 -0800665 bool hasWhitelist = (id != LOG_ID_SECURITY) && mPrune.nice() && !clearAll;
Mark Salyzyn5c06ca42014-02-06 18:11:13 -0800666 it = mLogElements.begin();
Mark Salyzyn12bac902014-02-26 09:50:16 -0800667 while((pruneRows > 0) && (it != mLogElements.end())) {
668 LogBufferElement *e = *it;
Mark Salyzyn9cf5d402015-03-10 13:51:35 -0700669
670 if (e->getLogId() != id) {
671 it++;
672 continue;
673 }
674
675 if (oldest && (oldest->mStart <= e->getSequence())) {
Mark Salyzyn7702c3e2015-09-16 15:34:00 -0700676 busy = true;
677
Mark Salyzyn9cf5d402015-03-10 13:51:35 -0700678 if (whitelist) {
Mark Salyzyn12bac902014-02-26 09:50:16 -0800679 break;
680 }
Mark Salyzync402bc72014-04-01 17:19:47 -0700681
Mark Salyzyn9cf5d402015-03-10 13:51:35 -0700682 if (stats.sizes(id) > (2 * log_buffer_size(id))) {
683 // kick a misbehaving log reader client off the island
684 oldest->release_Locked();
Mark Salyzyn552b4752015-11-30 11:35:56 -0800685 } else if (oldest->mTimeout.tv_sec || oldest->mTimeout.tv_nsec) {
686 oldest->triggerReader_Locked();
Mark Salyzyn9cf5d402015-03-10 13:51:35 -0700687 } else {
688 oldest->triggerSkip_Locked(id, pruneRows);
Mark Salyzync89839a2014-02-11 12:29:31 -0800689 }
Mark Salyzyn9cf5d402015-03-10 13:51:35 -0700690 break;
Mark Salyzyn12bac902014-02-26 09:50:16 -0800691 }
Mark Salyzyn9cf5d402015-03-10 13:51:35 -0700692
Mark Salyzynd910ca92015-05-21 12:50:31 -0700693 if (hasWhitelist && !e->getDropped() && mPrune.nice(e)) { // WhiteListed
Mark Salyzyn9cf5d402015-03-10 13:51:35 -0700694 whitelist = true;
695 it++;
696 continue;
697 }
698
699 it = erase(it);
700 pruneRows--;
Mark Salyzyn12bac902014-02-26 09:50:16 -0800701 }
702
Mark Salyzyn9cf5d402015-03-10 13:51:35 -0700703 // Do not save the whitelist if we are reader range limited
Mark Salyzync89839a2014-02-11 12:29:31 -0800704 if (whitelist && (pruneRows > 0)) {
705 it = mLogElements.begin();
706 while((it != mLogElements.end()) && (pruneRows > 0)) {
707 LogBufferElement *e = *it;
Mark Salyzyn9cf5d402015-03-10 13:51:35 -0700708
709 if (e->getLogId() != id) {
710 ++it;
711 continue;
Mark Salyzync89839a2014-02-11 12:29:31 -0800712 }
Mark Salyzyn9cf5d402015-03-10 13:51:35 -0700713
714 if (oldest && (oldest->mStart <= e->getSequence())) {
Mark Salyzyn7702c3e2015-09-16 15:34:00 -0700715 busy = true;
Mark Salyzyn9cf5d402015-03-10 13:51:35 -0700716 if (stats.sizes(id) > (2 * log_buffer_size(id))) {
717 // kick a misbehaving log reader client off the island
718 oldest->release_Locked();
Mark Salyzyn552b4752015-11-30 11:35:56 -0800719 } else if (oldest->mTimeout.tv_sec || oldest->mTimeout.tv_nsec) {
720 oldest->triggerReader_Locked();
Mark Salyzyn9cf5d402015-03-10 13:51:35 -0700721 } else {
722 oldest->triggerSkip_Locked(id, pruneRows);
723 }
724 break;
725 }
726
727 it = erase(it);
728 pruneRows--;
Mark Salyzync89839a2014-02-11 12:29:31 -0800729 }
730 }
Mark Salyzync89839a2014-02-11 12:29:31 -0800731
Mark Salyzyn12bac902014-02-26 09:50:16 -0800732 LogTimeEntry::unlock();
Mark Salyzyn7702c3e2015-09-16 15:34:00 -0700733
734 return (pruneRows > 0) && busy;
Mark Salyzyn12bac902014-02-26 09:50:16 -0800735}
736
737// clear all rows of type "id" from the buffer.
Mark Salyzyn7702c3e2015-09-16 15:34:00 -0700738bool LogBuffer::clear(log_id_t id, uid_t uid) {
739 bool busy = true;
740 // If it takes more than 4 tries (seconds) to clear, then kill reader(s)
741 for (int retry = 4;;) {
742 if (retry == 1) { // last pass
743 // Check if it is still busy after the sleep, we say prune
744 // one entry, not another clear run, so we are looking for
745 // the quick side effect of the return value to tell us if
746 // we have a _blocked_ reader.
747 pthread_mutex_lock(&mLogElementsLock);
748 busy = prune(id, 1, uid);
749 pthread_mutex_unlock(&mLogElementsLock);
750 // It is still busy, blocked reader(s), lets kill them all!
751 // otherwise, lets be a good citizen and preserve the slow
752 // readers and let the clear run (below) deal with determining
753 // if we are still blocked and return an error code to caller.
754 if (busy) {
755 LogTimeEntry::lock();
756 LastLogTimes::iterator times = mTimes.begin();
757 while (times != mTimes.end()) {
758 LogTimeEntry *entry = (*times);
759 // Killer punch
760 if (entry->owned_Locked() && entry->isWatching(id)) {
761 entry->release_Locked();
762 }
763 times++;
764 }
765 LogTimeEntry::unlock();
766 }
767 }
768 pthread_mutex_lock(&mLogElementsLock);
769 busy = prune(id, ULONG_MAX, uid);
770 pthread_mutex_unlock(&mLogElementsLock);
771 if (!busy || !--retry) {
772 break;
773 }
774 sleep (1); // Let reader(s) catch up after notification
775 }
776 return busy;
Mark Salyzyn12bac902014-02-26 09:50:16 -0800777}
778
779// get the used space associated with "id".
780unsigned long LogBuffer::getSizeUsed(log_id_t id) {
781 pthread_mutex_lock(&mLogElementsLock);
Mark Salyzynd774bce2014-02-06 14:48:50 -0800782 size_t retval = stats.sizes(id);
Mark Salyzyn12bac902014-02-26 09:50:16 -0800783 pthread_mutex_unlock(&mLogElementsLock);
784 return retval;
785}
786
Mark Salyzync89839a2014-02-11 12:29:31 -0800787// set the total space allocated to "id"
788int LogBuffer::setSize(log_id_t id, unsigned long size) {
789 // Reasonable limits ...
Mark Salyzyn7b85c592014-05-09 17:44:18 -0700790 if (!valid_size(size)) {
Mark Salyzync89839a2014-02-11 12:29:31 -0800791 return -1;
792 }
793 pthread_mutex_lock(&mLogElementsLock);
794 log_buffer_size(id) = size;
795 pthread_mutex_unlock(&mLogElementsLock);
796 return 0;
797}
798
799// get the total space allocated to "id"
800unsigned long LogBuffer::getSize(log_id_t id) {
801 pthread_mutex_lock(&mLogElementsLock);
802 size_t retval = log_buffer_size(id);
803 pthread_mutex_unlock(&mLogElementsLock);
804 return retval;
805}
806
Mark Salyzyn0aaf6cd2015-03-03 13:39:37 -0800807uint64_t LogBuffer::flushTo(
808 SocketClient *reader, const uint64_t start, bool privileged,
809 int (*filter)(const LogBufferElement *element, void *arg), void *arg) {
Mark Salyzyn12bac902014-02-26 09:50:16 -0800810 LogBufferElementCollection::iterator it;
Mark Salyzyn0aaf6cd2015-03-03 13:39:37 -0800811 uint64_t max = start;
Mark Salyzyn12bac902014-02-26 09:50:16 -0800812 uid_t uid = reader->getUid();
813
814 pthread_mutex_lock(&mLogElementsLock);
Dragoslav Mitrinovic81624f22015-01-15 09:29:43 -0600815
Mark Salyzyn0aaf6cd2015-03-03 13:39:37 -0800816 if (start <= 1) {
Dragoslav Mitrinovic81624f22015-01-15 09:29:43 -0600817 // client wants to start from the beginning
818 it = mLogElements.begin();
819 } else {
820 // Client wants to start from some specified time. Chances are
821 // we are better off starting from the end of the time sorted list.
822 for (it = mLogElements.end(); it != mLogElements.begin(); /* do nothing */) {
823 --it;
824 LogBufferElement *element = *it;
Mark Salyzyn0aaf6cd2015-03-03 13:39:37 -0800825 if (element->getSequence() <= start) {
Dragoslav Mitrinovic81624f22015-01-15 09:29:43 -0600826 it++;
827 break;
828 }
829 }
830 }
831
832 for (; it != mLogElements.end(); ++it) {
Mark Salyzyn12bac902014-02-26 09:50:16 -0800833 LogBufferElement *element = *it;
834
835 if (!privileged && (element->getUid() != uid)) {
836 continue;
837 }
838
Mark Salyzyn0aaf6cd2015-03-03 13:39:37 -0800839 if (element->getSequence() <= start) {
Mark Salyzyn12bac902014-02-26 09:50:16 -0800840 continue;
841 }
842
843 // NB: calling out to another object with mLogElementsLock held (safe)
Mark Salyzyn0aaf6cd2015-03-03 13:39:37 -0800844 if (filter) {
845 int ret = (*filter)(element, arg);
846 if (ret == false) {
847 continue;
848 }
849 if (ret != true) {
850 break;
851 }
Mark Salyzyn12bac902014-02-26 09:50:16 -0800852 }
853
854 pthread_mutex_unlock(&mLogElementsLock);
855
856 // range locking in LastLogTimes looks after us
Mark Salyzyn3443fda2015-12-03 15:38:35 -0800857 max = element->flushTo(reader, this, privileged);
Mark Salyzyn12bac902014-02-26 09:50:16 -0800858
859 if (max == element->FLUSH_ERROR) {
860 return max;
861 }
862
863 pthread_mutex_lock(&mLogElementsLock);
864 }
865 pthread_mutex_unlock(&mLogElementsLock);
866
867 return max;
868}
Mark Salyzynd774bce2014-02-06 14:48:50 -0800869
Mark Salyzynb921ab52015-12-17 09:58:43 -0800870std::string LogBuffer::formatStatistics(uid_t uid, pid_t pid,
871 unsigned int logMask) {
Mark Salyzynd774bce2014-02-06 14:48:50 -0800872 pthread_mutex_lock(&mLogElementsLock);
873
Mark Salyzynb921ab52015-12-17 09:58:43 -0800874 std::string ret = stats.format(uid, pid, logMask);
Mark Salyzynd774bce2014-02-06 14:48:50 -0800875
876 pthread_mutex_unlock(&mLogElementsLock);
Mark Salyzyn1c7b6fb2015-08-20 10:01:44 -0700877
878 return ret;
Mark Salyzynd774bce2014-02-06 14:48:50 -0800879}