blob: 1c3acb82122e43f4cd757cbf9e8fc4148f5440e4 [file] [log] [blame]
Mark Salyzynf089e142018-02-20 10:47:40 -08001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "llkd.h"
18
19#include <ctype.h>
20#include <dirent.h> // opendir() and readdir()
21#include <errno.h>
22#include <fcntl.h>
23#include <pthread.h>
24#include <pwd.h> // getpwuid()
25#include <signal.h>
26#include <stdint.h>
Mark Salyzyn8a5f0812019-01-03 08:39:38 -080027#include <string.h>
Mark Salyzynf089e142018-02-20 10:47:40 -080028#include <sys/cdefs.h> // ___STRING, __predict_true() and _predict_false()
29#include <sys/mman.h> // mlockall()
30#include <sys/prctl.h>
31#include <sys/stat.h> // lstat()
32#include <sys/syscall.h> // __NR_getdents64
33#include <sys/sysinfo.h> // get_nprocs_conf()
34#include <sys/types.h>
35#include <time.h>
36#include <unistd.h>
37
38#include <chrono>
39#include <ios>
40#include <sstream>
41#include <string>
42#include <unordered_map>
43#include <unordered_set>
44
45#include <android-base/file.h>
46#include <android-base/logging.h>
47#include <android-base/parseint.h>
48#include <android-base/properties.h>
49#include <android-base/strings.h>
50#include <cutils/android_get_control_file.h>
51#include <log/log_main.h>
52
53#define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x)))
54
55#define TASK_COMM_LEN 16 // internal kernel, not uapi, from .../linux/include/linux/sched.h
56
57using namespace std::chrono_literals;
58using namespace std::chrono;
Mark Salyzyn52e54a62018-08-07 08:13:13 -070059using namespace std::literals;
Mark Salyzynf089e142018-02-20 10:47:40 -080060
61namespace {
62
63constexpr pid_t kernelPid = 0;
64constexpr pid_t initPid = 1;
65constexpr pid_t kthreaddPid = 2;
66
67constexpr char procdir[] = "/proc/";
68
69// Configuration
70milliseconds llkUpdate; // last check ms signature
71milliseconds llkCycle; // ms to next thread check
72bool llkEnable = LLK_ENABLE_DEFAULT; // llk daemon enabled
73bool llkRunning = false; // thread is running
74bool llkMlockall = LLK_MLOCKALL_DEFAULT; // run mlocked
Mark Salyzynafd66f22018-03-19 15:16:29 -070075bool llkTestWithKill = LLK_KILLTEST_DEFAULT; // issue test kills
Mark Salyzynf089e142018-02-20 10:47:40 -080076milliseconds llkTimeoutMs = LLK_TIMEOUT_MS_DEFAULT; // default timeout
Mark Salyzyn96505fa2018-08-07 08:13:13 -070077enum { // enum of state indexes
78 llkStateD, // Persistent 'D' state
79 llkStateZ, // Persistent 'Z' state
80#ifdef __PTRACE_ENABLED__ // Extra privileged states
81 llkStateStack, // stack signature
82#endif // End of extra privilege
83 llkNumStates, // Maxumum number of states
84}; // state indexes
Mark Salyzynf089e142018-02-20 10:47:40 -080085milliseconds llkStateTimeoutMs[llkNumStates]; // timeout override for each detection state
86milliseconds llkCheckMs; // checking interval to inspect any
87 // persistent live-locked states
88bool llkLowRam; // ro.config.low_ram
Mark Salyzynbd7c8562018-10-31 10:02:08 -070089bool llkEnableSysrqT = LLK_ENABLE_SYSRQ_T_DEFAULT; // sysrq stack trace dump
Mark Salyzynf089e142018-02-20 10:47:40 -080090bool khtEnable = LLK_ENABLE_DEFAULT; // [khungtaskd] panic
91// [khungtaskd] should have a timeout beyond the granularity of llkTimeoutMs.
92// Provides a wide angle of margin b/c khtTimeout is also its granularity.
93seconds khtTimeout = duration_cast<seconds>(llkTimeoutMs * (1 + LLK_CHECKS_PER_TIMEOUT_DEFAULT) /
94 LLK_CHECKS_PER_TIMEOUT_DEFAULT);
Mark Salyzyn96505fa2018-08-07 08:13:13 -070095#ifdef __PTRACE_ENABLED__
96// list of stack symbols to search for persistence.
97std::unordered_set<std::string> llkCheckStackSymbols;
98#endif
Mark Salyzynf089e142018-02-20 10:47:40 -080099
100// Blacklist variables, initialized with comma separated lists of high false
101// positive and/or dangerous references, e.g. without self restart, for pid,
102// ppid, name and uid:
103
104// list of pids, or tids or names to skip. kernel pid (0), init pid (1),
105// [kthreadd] pid (2), ourselves, "init", "[kthreadd]", "lmkd", "llkd" or
106// combinations of watchdogd in kernel and user space.
107std::unordered_set<std::string> llkBlacklistProcess;
108// list of parent pids, comm or cmdline names to skip. default:
109// kernel pid (0), [kthreadd] (2), or ourselves, enforced and implied
110std::unordered_set<std::string> llkBlacklistParent;
Mark Salyzynda2aeb02019-01-02 08:27:22 -0800111// list of parent and target processes to skip. default:
112// adbd *and* [setsid]
113std::unordered_map<std::string, std::unordered_set<std::string>> llkBlacklistParentAndChild;
Mark Salyzynf089e142018-02-20 10:47:40 -0800114// list of uids, and uid names, to skip, default nothing
115std::unordered_set<std::string> llkBlacklistUid;
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700116#ifdef __PTRACE_ENABLED__
117// list of names to skip stack checking. "init", "lmkd", "llkd", "keystore" or
118// "logd" (if not userdebug).
119std::unordered_set<std::string> llkBlacklistStack;
120#endif
Mark Salyzynf089e142018-02-20 10:47:40 -0800121
122class dir {
123 public:
124 enum level { proc, task, numLevels };
125
126 private:
127 int fd;
128 size_t available_bytes;
129 dirent* next;
130 // each directory level picked to be just north of 4K in size
131 static constexpr size_t buffEntries = 15;
132 static dirent buff[numLevels][buffEntries];
133
134 bool fill(enum level index) {
135 if (index >= numLevels) return false;
136 if (available_bytes != 0) return true;
137 if (__predict_false(fd < 0)) return false;
138 // getdents64 has no libc wrapper
139 auto rc = TEMP_FAILURE_RETRY(syscall(__NR_getdents64, fd, buff[index], sizeof(buff[0]), 0));
140 if (rc <= 0) return false;
141 available_bytes = rc;
142 next = buff[index];
143 return true;
144 }
145
146 public:
147 dir() : fd(-1), available_bytes(0), next(nullptr) {}
148
149 explicit dir(const char* directory)
150 : fd(__predict_true(directory != nullptr)
151 ? ::open(directory, O_CLOEXEC | O_DIRECTORY | O_RDONLY)
152 : -1),
153 available_bytes(0),
154 next(nullptr) {}
155
156 explicit dir(const std::string&& directory)
157 : fd(::open(directory.c_str(), O_CLOEXEC | O_DIRECTORY | O_RDONLY)),
158 available_bytes(0),
159 next(nullptr) {}
160
161 explicit dir(const std::string& directory)
162 : fd(::open(directory.c_str(), O_CLOEXEC | O_DIRECTORY | O_RDONLY)),
163 available_bytes(0),
164 next(nullptr) {}
165
166 // Don't need any copy or move constructors.
167 explicit dir(const dir& c) = delete;
168 explicit dir(dir& c) = delete;
169 explicit dir(dir&& c) = delete;
170
171 ~dir() {
172 if (fd >= 0) {
173 ::close(fd);
174 }
175 }
176
177 operator bool() const { return fd >= 0; }
178
179 void reset(void) {
180 if (fd >= 0) {
181 ::close(fd);
182 fd = -1;
183 available_bytes = 0;
184 next = nullptr;
185 }
186 }
187
188 dir& reset(const char* directory) {
189 reset();
190 // available_bytes will _always_ be zero here as its value is
191 // intimately tied to fd < 0 or not.
192 fd = ::open(directory, O_CLOEXEC | O_DIRECTORY | O_RDONLY);
193 return *this;
194 }
195
196 void rewind(void) {
197 if (fd >= 0) {
198 ::lseek(fd, off_t(0), SEEK_SET);
199 available_bytes = 0;
200 next = nullptr;
201 }
202 }
203
204 dirent* read(enum level index = proc, dirent* def = nullptr) {
205 if (!fill(index)) return def;
206 auto ret = next;
207 available_bytes -= next->d_reclen;
208 next = reinterpret_cast<dirent*>(reinterpret_cast<char*>(next) + next->d_reclen);
209 return ret;
210 }
211} llkTopDirectory;
212
213dirent dir::buff[dir::numLevels][dir::buffEntries];
214
215// helper functions
216
217bool llkIsMissingExeLink(pid_t tid) {
218 char c;
219 // CAP_SYS_PTRACE is required to prevent ret == -1, but ENOENT is signal
220 auto ret = ::readlink((procdir + std::to_string(tid) + "/exe").c_str(), &c, sizeof(c));
221 return (ret == -1) && (errno == ENOENT);
222}
223
224// Common routine where caller accepts empty content as error/passthrough.
225// Reduces the churn of reporting read errors in the callers.
226std::string ReadFile(std::string&& path) {
227 std::string content;
228 if (!android::base::ReadFileToString(path, &content)) {
229 PLOG(DEBUG) << "Read " << path << " failed";
230 content = "";
231 }
232 return content;
233}
234
235std::string llkProcGetName(pid_t tid, const char* node = "/cmdline") {
236 std::string content = ReadFile(procdir + std::to_string(tid) + node);
237 static constexpr char needles[] = " \t\r\n"; // including trailing nul
238 auto pos = content.find_first_of(needles, 0, sizeof(needles));
239 if (pos != std::string::npos) {
240 content.erase(pos);
241 }
242 return content;
243}
244
245uid_t llkProcGetUid(pid_t tid) {
246 // Get the process' uid. The following read from /status is admittedly
247 // racy, prone to corruption due to shape-changes. The consequences are
248 // not catastrophic as we sample a few times before taking action.
249 //
250 // If /loginuid worked on reliably, or on Android (all tasks report -1)...
251 // Android lmkd causes /cgroup to contain memory:/<dom>/uid_<uid>/pid_<pid>
252 // which is tighter, but also not reliable.
253 std::string content = ReadFile(procdir + std::to_string(tid) + "/status");
254 static constexpr char Uid[] = "\nUid:";
255 auto pos = content.find(Uid);
256 if (pos == std::string::npos) {
257 return -1;
258 }
259 pos += ::strlen(Uid);
260 while ((pos < content.size()) && ::isblank(content[pos])) {
261 ++pos;
262 }
263 content.erase(0, pos);
264 for (pos = 0; (pos < content.size()) && ::isdigit(content[pos]); ++pos) {
265 ;
266 }
267 // Content of form 'Uid: 0 0 0 0', newline is error
268 if ((pos >= content.size()) || !::isblank(content[pos])) {
269 return -1;
270 }
271 content.erase(pos);
272 uid_t ret;
Tom Cherrye0bc5a92018-10-05 14:29:47 -0700273 if (!android::base::ParseUint(content, &ret, uid_t(0))) {
Mark Salyzynf089e142018-02-20 10:47:40 -0800274 return -1;
275 }
276 return ret;
277}
278
279struct proc {
280 pid_t tid; // monitored thread id (in Z or D state).
281 nanoseconds schedUpdate; // /proc/<tid>/sched "se.avg.lastUpdateTime",
282 uint64_t nrSwitches; // /proc/<tid>/sched "nr_switches" for
283 // refined ABA problem detection, determine
284 // forward scheduling progress.
285 milliseconds update; // llkUpdate millisecond signature of last.
286 milliseconds count; // duration in state.
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700287#ifdef __PTRACE_ENABLED__ // Privileged state checking
288 milliseconds count_stack; // duration where stack is stagnant.
289#endif // End privilege
Mark Salyzynf089e142018-02-20 10:47:40 -0800290 pid_t pid; // /proc/<pid> before iterating through
291 // /proc/<pid>/task/<tid> for threads.
292 pid_t ppid; // /proc/<tid>/stat field 4 parent pid.
293 uid_t uid; // /proc/<tid>/status Uid: field.
294 unsigned time; // sum of /proc/<tid>/stat field 14 utime &
295 // 15 stime for coarse ABA problem detection.
296 std::string cmdline; // cached /cmdline content
297 char state; // /proc/<tid>/stat field 3: Z or D
298 // (others we do not monitor: S, R, T or ?)
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700299#ifdef __PTRACE_ENABLED__ // Privileged state checking
300 char stack; // index in llkCheckStackSymbols for matches
301#endif // and with maximum index PROP_VALUE_MAX/2.
Mark Salyzynf089e142018-02-20 10:47:40 -0800302 char comm[TASK_COMM_LEN + 3]; // space for adding '[' and ']'
303 bool exeMissingValid; // exeMissing has been cached
304 bool cmdlineValid; // cmdline has been cached
305 bool updated; // cleared before monitoring pass.
306 bool killed; // sent a kill to this thread, next panic...
Marco Ballesio38c735e2019-12-27 13:43:29 -0800307 bool frozen; // process is in frozen cgroup.
Mark Salyzynf089e142018-02-20 10:47:40 -0800308
309 void setComm(const char* _comm) { strncpy(comm + 1, _comm, sizeof(comm) - 2); }
310
Marco Ballesio38c735e2019-12-27 13:43:29 -0800311 void setFrozen(bool _frozen) { frozen = _frozen; }
312
313 proc(pid_t tid, pid_t pid, pid_t ppid, const char* _comm, int time, char state, bool frozen)
Mark Salyzynf089e142018-02-20 10:47:40 -0800314 : tid(tid),
315 schedUpdate(0),
316 nrSwitches(0),
317 update(llkUpdate),
Mark Salyzynacecaf72018-08-10 08:15:57 -0700318 count(0ms),
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700319#ifdef __PTRACE_ENABLED__
320 count_stack(0ms),
321#endif
Mark Salyzynf089e142018-02-20 10:47:40 -0800322 pid(pid),
323 ppid(ppid),
324 uid(-1),
325 time(time),
326 state(state),
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700327#ifdef __PTRACE_ENABLED__
328 stack(-1),
329#endif
Mark Salyzynf089e142018-02-20 10:47:40 -0800330 exeMissingValid(false),
331 cmdlineValid(false),
332 updated(true),
Marco Ballesio38c735e2019-12-27 13:43:29 -0800333 killed(!llkTestWithKill),
334 frozen(frozen) {
Mark Salyzynf089e142018-02-20 10:47:40 -0800335 memset(comm, '\0', sizeof(comm));
336 setComm(_comm);
337 }
338
339 const char* getComm(void) {
340 if (comm[1] == '\0') { // comm Valid?
341 strncpy(comm + 1, llkProcGetName(tid, "/comm").c_str(), sizeof(comm) - 2);
342 }
343 if (!exeMissingValid) {
344 if (llkIsMissingExeLink(tid)) {
345 comm[0] = '[';
346 }
347 exeMissingValid = true;
348 }
349 size_t len = strlen(comm + 1);
350 if (__predict_true(len < (sizeof(comm) - 1))) {
351 if (comm[0] == '[') {
352 if ((comm[len] != ']') && __predict_true(len < (sizeof(comm) - 2))) {
353 comm[++len] = ']';
354 comm[++len] = '\0';
355 }
356 } else {
357 if (comm[len] == ']') {
358 comm[len] = '\0';
359 }
360 }
361 }
362 return &comm[comm[0] != '['];
363 }
364
365 const char* getCmdline(void) {
366 if (!cmdlineValid) {
367 cmdline = llkProcGetName(tid);
368 cmdlineValid = true;
369 }
370 return cmdline.c_str();
371 }
372
373 uid_t getUid(void) {
374 if (uid <= 0) { // Churn on root user, because most likely to setuid()
375 uid = llkProcGetUid(tid);
376 }
377 return uid;
378 }
379
Marco Ballesio38c735e2019-12-27 13:43:29 -0800380 bool isFrozen() { return frozen; }
381
Mark Salyzynf089e142018-02-20 10:47:40 -0800382 void reset(void) { // reset cache, if we detected pid rollover
383 uid = -1;
384 state = '?';
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700385#ifdef __PTRACE_ENABLED__
386 count_stack = 0ms;
387 stack = -1;
388#endif
Mark Salyzynf089e142018-02-20 10:47:40 -0800389 cmdline = "";
390 comm[0] = '\0';
391 exeMissingValid = false;
392 cmdlineValid = false;
393 }
394};
395
396std::unordered_map<pid_t, proc> tids;
397
398// Check range and setup defaults, in order of propagation:
399// llkTimeoutMs
400// llkCheckMs
401// ...
402// KISS to keep it all self-contained, and called multiple times as parameters
403// are interpreted so that defaults, llkCheckMs and llkCycle make sense.
404void llkValidate() {
405 if (llkTimeoutMs == 0ms) {
406 llkTimeoutMs = LLK_TIMEOUT_MS_DEFAULT;
407 }
408 llkTimeoutMs = std::max(llkTimeoutMs, LLK_TIMEOUT_MS_MINIMUM);
409 if (llkCheckMs == 0ms) {
410 llkCheckMs = llkTimeoutMs / LLK_CHECKS_PER_TIMEOUT_DEFAULT;
411 }
412 llkCheckMs = std::min(llkCheckMs, llkTimeoutMs);
413
414 for (size_t state = 0; state < ARRAY_SIZE(llkStateTimeoutMs); ++state) {
415 if (llkStateTimeoutMs[state] == 0ms) {
416 llkStateTimeoutMs[state] = llkTimeoutMs;
417 }
418 llkStateTimeoutMs[state] =
419 std::min(std::max(llkStateTimeoutMs[state], LLK_TIMEOUT_MS_MINIMUM), llkTimeoutMs);
420 llkCheckMs = std::min(llkCheckMs, llkStateTimeoutMs[state]);
421 }
422
423 llkCheckMs = std::max(llkCheckMs, LLK_CHECK_MS_MINIMUM);
424 if (llkCycle == 0ms) {
425 llkCycle = llkCheckMs;
426 }
427 llkCycle = std::min(llkCycle, llkCheckMs);
428}
429
430milliseconds llkGetTimespecDiffMs(timespec* from, timespec* to) {
431 return duration_cast<milliseconds>(seconds(to->tv_sec - from->tv_sec)) +
432 duration_cast<milliseconds>(nanoseconds(to->tv_nsec - from->tv_nsec));
433}
434
435std::string llkProcGetName(pid_t tid, const char* comm, const char* cmdline) {
436 if ((cmdline != nullptr) && (*cmdline != '\0')) {
437 return cmdline;
438 }
439 if ((comm != nullptr) && (*comm != '\0')) {
440 return comm;
441 }
442
443 // UNLIKELY! Here because killed before we kill it?
444 // Assume change is afoot, do not call llkTidAlloc
445
446 // cmdline ?
447 std::string content = llkProcGetName(tid);
448 if (content.size() != 0) {
449 return content;
450 }
451 // Comm instead?
452 content = llkProcGetName(tid, "/comm");
453 if (llkIsMissingExeLink(tid) && (content.size() != 0)) {
454 return '[' + content + ']';
455 }
456 return content;
457}
458
459int llkKillOneProcess(pid_t pid, char state, pid_t tid, const char* tcomm = nullptr,
460 const char* tcmdline = nullptr, const char* pcomm = nullptr,
461 const char* pcmdline = nullptr) {
462 std::string forTid;
463 if (tid != pid) {
464 forTid = " for '" + llkProcGetName(tid, tcomm, tcmdline) + "' (" + std::to_string(tid) + ")";
465 }
466 LOG(INFO) << "Killing '" << llkProcGetName(pid, pcomm, pcmdline) << "' (" << pid
467 << ") to check forward scheduling progress in " << state << " state" << forTid;
468 // CAP_KILL required
469 errno = 0;
470 auto r = ::kill(pid, SIGKILL);
471 if (r) {
472 PLOG(ERROR) << "kill(" << pid << ")=" << r << ' ';
473 }
474
475 return r;
476}
477
478// Kill one process
479int llkKillOneProcess(pid_t pid, proc* tprocp) {
480 return llkKillOneProcess(pid, tprocp->state, tprocp->tid, tprocp->getComm(),
481 tprocp->getCmdline());
482}
483
484// Kill one process specified by kprocp
485int llkKillOneProcess(proc* kprocp, proc* tprocp) {
486 if (kprocp == nullptr) {
487 return -2;
488 }
489
490 return llkKillOneProcess(kprocp->tid, tprocp->state, tprocp->tid, tprocp->getComm(),
491 tprocp->getCmdline(), kprocp->getComm(), kprocp->getCmdline());
492}
493
494// Acquire file descriptor from environment, or open and cache it.
495// NB: cache is unnecessary in our current context, pedantically
496// required to prevent leakage of file descriptors in the future.
497int llkFileToWriteFd(const std::string& file) {
498 static std::unordered_map<std::string, int> cache;
499 auto search = cache.find(file);
500 if (search != cache.end()) return search->second;
501 auto fd = android_get_control_file(file.c_str());
502 if (fd >= 0) return fd;
503 fd = TEMP_FAILURE_RETRY(::open(file.c_str(), O_WRONLY | O_CLOEXEC));
504 if (fd >= 0) cache.emplace(std::make_pair(file, fd));
505 return fd;
506}
507
508// Wrap android::base::WriteStringToFile to use android_get_control_file.
509bool llkWriteStringToFile(const std::string& string, const std::string& file) {
510 auto fd = llkFileToWriteFd(file);
511 if (fd < 0) return false;
512 return android::base::WriteStringToFd(string, fd);
513}
514
515bool llkWriteStringToFileConfirm(const std::string& string, const std::string& file) {
516 auto fd = llkFileToWriteFd(file);
517 auto ret = (fd < 0) ? false : android::base::WriteStringToFd(string, fd);
518 std::string content;
519 if (!android::base::ReadFileToString(file, &content)) return ret;
520 return android::base::Trim(content) == string;
521}
522
Mark Salyzynfbc3a752018-12-04 10:30:45 -0800523void llkPanicKernel(bool dump, pid_t tid, const char* state, const std::string& message = "") {
Mark Salyzyn3c3b14d2018-10-31 10:38:15 -0700524 if (!message.empty()) LOG(ERROR) << message;
Mark Salyzynf089e142018-02-20 10:47:40 -0800525 auto sysrqTriggerFd = llkFileToWriteFd("/proc/sysrq-trigger");
526 if (sysrqTriggerFd < 0) {
527 // DYB
528 llkKillOneProcess(initPid, 'R', tid);
529 // The answer to life, the universe and everything
530 ::exit(42);
531 // NOTREACHED
Mark Salyzynfbc3a752018-12-04 10:30:45 -0800532 return;
Mark Salyzynf089e142018-02-20 10:47:40 -0800533 }
Mark Salyzyn16649d22019-01-09 07:49:21 -0800534 // Wish could ::sync() here, if storage is locked up, we will not continue.
Mark Salyzynf089e142018-02-20 10:47:40 -0800535 if (dump) {
536 // Show all locks that are held
537 android::base::WriteStringToFd("d", sysrqTriggerFd);
Mark Salyzyn53e782d2018-10-31 16:03:45 -0700538 // Show all waiting tasks
539 android::base::WriteStringToFd("w", sysrqTriggerFd);
Mark Salyzynf089e142018-02-20 10:47:40 -0800540 // This can trigger hardware watchdog, that is somewhat _ok_.
541 // But useless if pstore configured for <256KB, low ram devices ...
Mark Salyzynbd7c8562018-10-31 10:02:08 -0700542 if (llkEnableSysrqT) {
Mark Salyzynf089e142018-02-20 10:47:40 -0800543 android::base::WriteStringToFd("t", sysrqTriggerFd);
Mark Salyzyn53e782d2018-10-31 16:03:45 -0700544 // Show all locks that are held (in case 't' overflows ramoops)
545 android::base::WriteStringToFd("d", sysrqTriggerFd);
546 // Show all waiting tasks (in case 't' overflows ramoops)
547 android::base::WriteStringToFd("w", sysrqTriggerFd);
Mark Salyzynf089e142018-02-20 10:47:40 -0800548 }
549 ::usleep(200000); // let everything settle
550 }
Mark Salyzyn3c3b14d2018-10-31 10:38:15 -0700551 // SysRq message matches kernel format, and propagates through bootstat
552 // ultimately to the boot reason into panic,livelock,<state>.
553 llkWriteStringToFile(message + (message.empty() ? "" : "\n") +
554 "SysRq : Trigger a crash : 'livelock,"s + state + "'\n",
555 "/dev/kmsg");
Mark Salyzynfbc3a752018-12-04 10:30:45 -0800556 // Because panic is such a serious thing to do, let us
557 // make sure that the tid being inspected still exists!
558 auto piddir = procdir + std::to_string(tid) + "/stat";
559 if (access(piddir.c_str(), F_OK) != 0) {
560 PLOG(WARNING) << piddir;
561 return;
562 }
Mark Salyzynf089e142018-02-20 10:47:40 -0800563 android::base::WriteStringToFd("c", sysrqTriggerFd);
564 // NOTREACHED
565 // DYB
566 llkKillOneProcess(initPid, 'R', tid);
567 // I sat at my desk, stared into the garden and thought '42 will do'.
568 // I typed it out. End of story
569 ::exit(42);
570 // NOTREACHED
571}
572
573void llkAlarmHandler(int) {
Mark Salyzynb3418a22018-11-19 15:24:03 -0800574 LOG(FATAL) << "alarm";
575 // NOTREACHED
576 llkPanicKernel(true, ::getpid(), "alarm");
Mark Salyzynf089e142018-02-20 10:47:40 -0800577}
578
579milliseconds GetUintProperty(const std::string& key, milliseconds def) {
580 return milliseconds(android::base::GetUintProperty(key, static_cast<uint64_t>(def.count()),
581 static_cast<uint64_t>(def.max().count())));
582}
583
584seconds GetUintProperty(const std::string& key, seconds def) {
585 return seconds(android::base::GetUintProperty(key, static_cast<uint64_t>(def.count()),
586 static_cast<uint64_t>(def.max().count())));
587}
588
589proc* llkTidLookup(pid_t tid) {
590 auto search = tids.find(tid);
591 if (search == tids.end()) {
592 return nullptr;
593 }
594 return &search->second;
595}
596
597void llkTidRemove(pid_t tid) {
598 tids.erase(tid);
599}
600
Marco Ballesio38c735e2019-12-27 13:43:29 -0800601proc* llkTidAlloc(pid_t tid, pid_t pid, pid_t ppid, const char* comm, int time, char state,
602 bool frozen) {
603 auto it = tids.emplace(std::make_pair(tid, proc(tid, pid, ppid, comm, time, state, frozen)));
Mark Salyzynf089e142018-02-20 10:47:40 -0800604 return &it.first->second;
605}
606
607std::string llkFormat(milliseconds ms) {
608 auto sec = duration_cast<seconds>(ms);
609 std::ostringstream s;
610 s << sec.count() << '.';
611 auto f = s.fill('0');
612 auto w = s.width(3);
613 s << std::right << (ms - sec).count();
614 s.width(w);
615 s.fill(f);
616 s << 's';
617 return s.str();
618}
619
620std::string llkFormat(seconds s) {
621 return std::to_string(s.count()) + 's';
622}
623
624std::string llkFormat(bool flag) {
625 return flag ? "true" : "false";
626}
627
628std::string llkFormat(const std::unordered_set<std::string>& blacklist) {
629 std::string ret;
Chih-Hung Hsieh1b7b7972018-12-11 10:34:33 -0800630 for (const auto& entry : blacklist) {
Mark Salyzyn8a5f0812019-01-03 08:39:38 -0800631 if (!ret.empty()) ret += ",";
Mark Salyzynf089e142018-02-20 10:47:40 -0800632 ret += entry;
633 }
634 return ret;
635}
636
Mark Salyzynda2aeb02019-01-02 08:27:22 -0800637std::string llkFormat(
638 const std::unordered_map<std::string, std::unordered_set<std::string>>& blacklist,
639 bool leading_comma = false) {
640 std::string ret;
641 for (const auto& entry : blacklist) {
642 for (const auto& target : entry.second) {
643 if (leading_comma || !ret.empty()) ret += ",";
644 ret += entry.first + "&" + target;
645 }
646 }
647 return ret;
648}
649
Mark Salyzyn8a5f0812019-01-03 08:39:38 -0800650// This function parses the properties as a list, incorporating the supplied
651// default. A leading comma separator means preserve the defaults and add
652// entries (with an optional leading + sign), or removes entries with a leading
653// - sign.
654//
Mark Salyzynf089e142018-02-20 10:47:40 -0800655// We only officially support comma separators, but wetware being what they
656// are will take some liberty and I do not believe they should be punished.
Mark Salyzyn8a5f0812019-01-03 08:39:38 -0800657std::unordered_set<std::string> llkSplit(const std::string& prop, const std::string& def) {
658 auto s = android::base::GetProperty(prop, def);
659 constexpr char separators[] = ", \t:;";
660 if (!s.empty() && (s != def) && strchr(separators, s[0])) s = def + s;
661
Mark Salyzynf089e142018-02-20 10:47:40 -0800662 std::unordered_set<std::string> result;
663
Mark Salyzynacecaf72018-08-10 08:15:57 -0700664 // Special case, allow boolean false to empty the list, otherwise expected
665 // source of input from android::base::GetProperty will supply the default
666 // value on empty content in the property.
667 if (s == "false") return result;
668
Mark Salyzynf089e142018-02-20 10:47:40 -0800669 size_t base = 0;
Mark Salyzynacecaf72018-08-10 08:15:57 -0700670 while (s.size() > base) {
Mark Salyzyn8a5f0812019-01-03 08:39:38 -0800671 auto found = s.find_first_of(separators, base);
672 // Only emplace unique content, empty entries are not an option
673 if (found != base) {
674 switch (s[base]) {
675 case '-':
676 ++base;
677 if (base >= s.size()) break;
678 if (base != found) {
679 auto have = result.find(s.substr(base, found - base));
680 if (have != result.end()) result.erase(have);
681 }
682 break;
683 case '+':
684 ++base;
685 if (base >= s.size()) break;
686 if (base == found) break;
687 // FALLTHRU (for gcc, lint, pcc, etc; following for clang)
688 FALLTHROUGH_INTENDED;
689 default:
690 result.emplace(s.substr(base, found - base));
691 break;
692 }
693 }
Mark Salyzynf089e142018-02-20 10:47:40 -0800694 if (found == s.npos) break;
695 base = found + 1;
696 }
697 return result;
698}
699
700bool llkSkipName(const std::string& name,
701 const std::unordered_set<std::string>& blacklist = llkBlacklistProcess) {
Mark Salyzyn8a5f0812019-01-03 08:39:38 -0800702 if (name.empty() || blacklist.empty()) return false;
Mark Salyzynf089e142018-02-20 10:47:40 -0800703
704 return blacklist.find(name) != blacklist.end();
705}
706
Mark Salyzyn8a5f0812019-01-03 08:39:38 -0800707bool llkSkipProc(proc* procp,
708 const std::unordered_set<std::string>& blacklist = llkBlacklistProcess) {
709 if (!procp) return false;
710 if (llkSkipName(std::to_string(procp->pid), blacklist)) return true;
711 if (llkSkipName(procp->getComm(), blacklist)) return true;
712 if (llkSkipName(procp->getCmdline(), blacklist)) return true;
713 if (llkSkipName(android::base::Basename(procp->getCmdline()), blacklist)) return true;
714 return false;
715}
716
Mark Salyzynda2aeb02019-01-02 08:27:22 -0800717const std::unordered_set<std::string>& llkSkipName(
718 const std::string& name,
719 const std::unordered_map<std::string, std::unordered_set<std::string>>& blacklist) {
720 static const std::unordered_set<std::string> empty;
721 if (name.empty() || blacklist.empty()) return empty;
722 auto found = blacklist.find(name);
723 if (found == blacklist.end()) return empty;
724 return found->second;
725}
726
727bool llkSkipPproc(proc* pprocp, proc* procp,
728 const std::unordered_map<std::string, std::unordered_set<std::string>>&
729 blacklist = llkBlacklistParentAndChild) {
730 if (!pprocp || !procp || blacklist.empty()) return false;
731 if (llkSkipProc(procp, llkSkipName(std::to_string(pprocp->pid), blacklist))) return true;
732 if (llkSkipProc(procp, llkSkipName(pprocp->getComm(), blacklist))) return true;
733 if (llkSkipProc(procp, llkSkipName(pprocp->getCmdline(), blacklist))) return true;
734 return llkSkipProc(procp,
735 llkSkipName(android::base::Basename(pprocp->getCmdline()), blacklist));
736}
737
Mark Salyzynf089e142018-02-20 10:47:40 -0800738bool llkSkipPid(pid_t pid) {
739 return llkSkipName(std::to_string(pid), llkBlacklistProcess);
740}
741
742bool llkSkipPpid(pid_t ppid) {
743 return llkSkipName(std::to_string(ppid), llkBlacklistParent);
744}
745
746bool llkSkipUid(uid_t uid) {
747 // Match by number?
748 if (llkSkipName(std::to_string(uid), llkBlacklistUid)) {
749 return true;
750 }
751
752 // Match by name?
753 auto pwd = ::getpwuid(uid);
754 return (pwd != nullptr) && __predict_true(pwd->pw_name != nullptr) &&
755 __predict_true(pwd->pw_name[0] != '\0') && llkSkipName(pwd->pw_name, llkBlacklistUid);
756}
757
758bool getValidTidDir(dirent* dp, std::string* piddir) {
759 if (!::isdigit(dp->d_name[0])) {
760 return false;
761 }
762
763 // Corner case can not happen in reality b/c of above ::isdigit check
764 if (__predict_false(dp->d_type != DT_DIR)) {
765 if (__predict_false(dp->d_type == DT_UNKNOWN)) { // can't b/c procfs
766 struct stat st;
767 *piddir = procdir;
768 *piddir += dp->d_name;
769 return (lstat(piddir->c_str(), &st) == 0) && (st.st_mode & S_IFDIR);
770 }
771 return false;
772 }
773
774 *piddir = procdir;
775 *piddir += dp->d_name;
776 return true;
777}
778
779bool llkIsMonitorState(char state) {
780 return (state == 'Z') || (state == 'D');
781}
782
783// returns -1 if not found
784long long getSchedValue(const std::string& schedString, const char* key) {
785 auto pos = schedString.find(key);
786 if (pos == std::string::npos) {
787 return -1;
788 }
789 pos = schedString.find(':', pos);
790 if (__predict_false(pos == std::string::npos)) {
791 return -1;
792 }
793 while ((++pos < schedString.size()) && ::isblank(schedString[pos])) {
794 ;
795 }
796 long long ret;
797 if (!android::base::ParseInt(schedString.substr(pos), &ret, static_cast<long long>(0))) {
798 return -1;
799 }
800 return ret;
801}
802
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700803#ifdef __PTRACE_ENABLED__
804bool llkCheckStack(proc* procp, const std::string& piddir) {
805 if (llkCheckStackSymbols.empty()) return false;
806 if (procp->state == 'Z') { // No brains for Zombies
807 procp->stack = -1;
808 procp->count_stack = 0ms;
809 return false;
810 }
811
812 // Don't check process that are known to block ptrace, save sepolicy noise.
Mark Salyzyn8a5f0812019-01-03 08:39:38 -0800813 if (llkSkipProc(procp, llkBlacklistStack)) return false;
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700814 auto kernel_stack = ReadFile(piddir + "/stack");
815 if (kernel_stack.empty()) {
Mark Salyzyn22e05fb2019-01-02 15:04:42 -0800816 LOG(VERBOSE) << piddir << "/stack empty comm=" << procp->getComm()
817 << " cmdline=" << procp->getCmdline();
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700818 return false;
819 }
820 // A scheduling incident that should not reset count_stack
821 if (kernel_stack.find(" cpu_worker_pools+0x") != std::string::npos) return false;
822 char idx = -1;
823 char match = -1;
Mark Salyzyn22e05fb2019-01-02 15:04:42 -0800824 std::string matched_stack_symbol = "<unknown>";
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700825 for (const auto& stack : llkCheckStackSymbols) {
826 if (++idx < 0) break;
Mark Salyzynbb1256a2018-10-18 14:39:27 -0700827 if ((kernel_stack.find(" "s + stack + "+0x") != std::string::npos) ||
828 (kernel_stack.find(" "s + stack + ".cfi+0x") != std::string::npos)) {
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700829 match = idx;
Mark Salyzyn22e05fb2019-01-02 15:04:42 -0800830 matched_stack_symbol = stack;
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700831 break;
832 }
833 }
834 if (procp->stack != match) {
835 procp->stack = match;
836 procp->count_stack = 0ms;
837 return false;
838 }
839 if (match == char(-1)) return false;
840 procp->count_stack += llkCycle;
Mark Salyzyn22e05fb2019-01-02 15:04:42 -0800841 if (procp->count_stack < llkStateTimeoutMs[llkStateStack]) return false;
842 LOG(WARNING) << "Found " << matched_stack_symbol << " in stack for pid " << procp->pid;
843 return true;
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700844}
845#endif
846
Mark Salyzynf089e142018-02-20 10:47:40 -0800847// Primary ABA mitigation watching last time schedule activity happened
848void llkCheckSchedUpdate(proc* procp, const std::string& piddir) {
849 // Audit finds /proc/<tid>/sched is just over 1K, and
850 // is rarely larger than 2K, even less on Android.
851 // For example, the "se.avg.lastUpdateTime" field we are
852 // interested in typically within the primary set in
853 // the first 1K.
854 //
855 // Proc entries can not be read >1K atomically via libbase,
856 // but if there are problems we assume at least a few
857 // samples of reads occur before we take any real action.
858 std::string schedString = ReadFile(piddir + "/sched");
Mark Salyzyn8a5f0812019-01-03 08:39:38 -0800859 if (schedString.empty()) {
Mark Salyzynf089e142018-02-20 10:47:40 -0800860 // /schedstat is not as standardized, but in 3.1+
861 // Android devices, the third field is nr_switches
862 // from /sched:
863 schedString = ReadFile(piddir + "/schedstat");
Mark Salyzyn8a5f0812019-01-03 08:39:38 -0800864 if (schedString.empty()) {
Mark Salyzynf089e142018-02-20 10:47:40 -0800865 return;
866 }
867 auto val = static_cast<unsigned long long>(-1);
868 if (((::sscanf(schedString.c_str(), "%*d %*d %llu", &val)) == 1) &&
869 (val != static_cast<unsigned long long>(-1)) && (val != 0) &&
870 (val != procp->nrSwitches)) {
871 procp->nrSwitches = val;
872 procp->count = 0ms;
Mark Salyzynafd66f22018-03-19 15:16:29 -0700873 procp->killed = !llkTestWithKill;
Mark Salyzynf089e142018-02-20 10:47:40 -0800874 }
875 return;
876 }
877
878 auto val = getSchedValue(schedString, "\nse.avg.lastUpdateTime");
879 if (val == -1) {
880 val = getSchedValue(schedString, "\nse.svg.last_update_time");
881 }
882 if (val != -1) {
883 auto schedUpdate = nanoseconds(val);
884 if (schedUpdate != procp->schedUpdate) {
885 procp->schedUpdate = schedUpdate;
886 procp->count = 0ms;
Mark Salyzynafd66f22018-03-19 15:16:29 -0700887 procp->killed = !llkTestWithKill;
Mark Salyzynf089e142018-02-20 10:47:40 -0800888 }
889 }
890
891 val = getSchedValue(schedString, "\nnr_switches");
892 if (val != -1) {
893 if (static_cast<uint64_t>(val) != procp->nrSwitches) {
894 procp->nrSwitches = val;
895 procp->count = 0ms;
Mark Salyzynafd66f22018-03-19 15:16:29 -0700896 procp->killed = !llkTestWithKill;
Mark Salyzynf089e142018-02-20 10:47:40 -0800897 }
898 }
899}
900
901void llkLogConfig(void) {
902 LOG(INFO) << "ro.config.low_ram=" << llkFormat(llkLowRam) << "\n"
Mark Salyzynbd7c8562018-10-31 10:02:08 -0700903 << LLK_ENABLE_SYSRQ_T_PROPERTY "=" << llkFormat(llkEnableSysrqT) << "\n"
Mark Salyzynf089e142018-02-20 10:47:40 -0800904 << LLK_ENABLE_PROPERTY "=" << llkFormat(llkEnable) << "\n"
905 << KHT_ENABLE_PROPERTY "=" << llkFormat(khtEnable) << "\n"
906 << LLK_MLOCKALL_PROPERTY "=" << llkFormat(llkMlockall) << "\n"
Mark Salyzynafd66f22018-03-19 15:16:29 -0700907 << LLK_KILLTEST_PROPERTY "=" << llkFormat(llkTestWithKill) << "\n"
Mark Salyzynf089e142018-02-20 10:47:40 -0800908 << KHT_TIMEOUT_PROPERTY "=" << llkFormat(khtTimeout) << "\n"
909 << LLK_TIMEOUT_MS_PROPERTY "=" << llkFormat(llkTimeoutMs) << "\n"
910 << LLK_D_TIMEOUT_MS_PROPERTY "=" << llkFormat(llkStateTimeoutMs[llkStateD]) << "\n"
911 << LLK_Z_TIMEOUT_MS_PROPERTY "=" << llkFormat(llkStateTimeoutMs[llkStateZ]) << "\n"
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700912#ifdef __PTRACE_ENABLED__
913 << LLK_STACK_TIMEOUT_MS_PROPERTY "=" << llkFormat(llkStateTimeoutMs[llkStateStack])
914 << "\n"
915#endif
Mark Salyzynf089e142018-02-20 10:47:40 -0800916 << LLK_CHECK_MS_PROPERTY "=" << llkFormat(llkCheckMs) << "\n"
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700917#ifdef __PTRACE_ENABLED__
918 << LLK_CHECK_STACK_PROPERTY "=" << llkFormat(llkCheckStackSymbols) << "\n"
919 << LLK_BLACKLIST_STACK_PROPERTY "=" << llkFormat(llkBlacklistStack) << "\n"
920#endif
Mark Salyzynf089e142018-02-20 10:47:40 -0800921 << LLK_BLACKLIST_PROCESS_PROPERTY "=" << llkFormat(llkBlacklistProcess) << "\n"
Mark Salyzynda2aeb02019-01-02 08:27:22 -0800922 << LLK_BLACKLIST_PARENT_PROPERTY "=" << llkFormat(llkBlacklistParent)
923 << llkFormat(llkBlacklistParentAndChild, true) << "\n"
Mark Salyzynf089e142018-02-20 10:47:40 -0800924 << LLK_BLACKLIST_UID_PROPERTY "=" << llkFormat(llkBlacklistUid);
925}
926
927void* llkThread(void* obj) {
Mark Salyzyn4832a8b2018-08-15 11:02:18 -0700928 prctl(PR_SET_DUMPABLE, 0);
929
Mark Salyzynf089e142018-02-20 10:47:40 -0800930 LOG(INFO) << "started";
931
932 std::string name = std::to_string(::gettid());
933 if (!llkSkipName(name)) {
934 llkBlacklistProcess.emplace(name);
935 }
936 name = static_cast<const char*>(obj);
937 prctl(PR_SET_NAME, name.c_str());
938 if (__predict_false(!llkSkipName(name))) {
939 llkBlacklistProcess.insert(name);
940 }
941 // No longer modifying llkBlacklistProcess.
942 llkRunning = true;
943 llkLogConfig();
944 while (llkRunning) {
945 ::usleep(duration_cast<microseconds>(llkCheck(true)).count());
946 }
947 // NOTREACHED
948 LOG(INFO) << "exiting";
949 return nullptr;
950}
951
952} // namespace
953
954milliseconds llkCheck(bool checkRunning) {
955 if (!llkEnable || (checkRunning != llkRunning)) {
956 return milliseconds::max();
957 }
958
959 // Reset internal watchdog, which is a healthy engineering margin of
960 // double the maximum wait or cycle time for the mainloop that calls us.
961 //
962 // This alarm is effectively the live lock detection of llkd, as
963 // we understandably can not monitor ourselves otherwise.
964 ::alarm(duration_cast<seconds>(llkTimeoutMs * 2).count());
965
966 // kernel jiffy precision fastest acquisition
967 static timespec last;
968 timespec now;
969 ::clock_gettime(CLOCK_MONOTONIC_COARSE, &now);
970 auto ms = llkGetTimespecDiffMs(&last, &now);
971 if (ms < llkCycle) {
972 return llkCycle - ms;
973 }
974 last = now;
975
976 LOG(VERBOSE) << "opendir(\"" << procdir << "\")";
977 if (__predict_false(!llkTopDirectory)) {
978 // gid containing AID_READPROC required
979 llkTopDirectory.reset(procdir);
980 if (__predict_false(!llkTopDirectory)) {
981 // Most likely reason we could be here is a resource limit.
982 // Keep our processing down to a minimum, but not so low that
983 // we do not recover in a timely manner should the issue be
984 // transitory.
985 LOG(DEBUG) << "opendir(\"" << procdir << "\") failed";
986 return llkTimeoutMs;
987 }
988 }
989
990 for (auto& it : tids) {
991 it.second.updated = false;
992 }
993
994 auto prevUpdate = llkUpdate;
995 llkUpdate += ms;
996 ms -= llkCycle;
997 auto myPid = ::getpid();
998 auto myTid = ::gettid();
Mark Salyzynfbc3a752018-12-04 10:30:45 -0800999 auto dump = true;
Mark Salyzynf089e142018-02-20 10:47:40 -08001000 for (auto dp = llkTopDirectory.read(); dp != nullptr; dp = llkTopDirectory.read()) {
1001 std::string piddir;
1002
1003 if (!getValidTidDir(dp, &piddir)) {
1004 continue;
1005 }
1006
1007 // Get the process tasks
1008 std::string taskdir = piddir + "/task/";
1009 int pid = -1;
1010 LOG(VERBOSE) << "+opendir(\"" << taskdir << "\")";
1011 dir taskDirectory(taskdir);
1012 if (__predict_false(!taskDirectory)) {
1013 LOG(DEBUG) << "+opendir(\"" << taskdir << "\") failed";
1014 }
1015 for (auto tp = taskDirectory.read(dir::task, dp); tp != nullptr;
1016 tp = taskDirectory.read(dir::task)) {
1017 if (!getValidTidDir(tp, &piddir)) {
1018 continue;
1019 }
1020
1021 // Get the process stat
1022 std::string stat = ReadFile(piddir + "/stat");
Mark Salyzyn8a5f0812019-01-03 08:39:38 -08001023 if (stat.empty()) {
Mark Salyzynf089e142018-02-20 10:47:40 -08001024 continue;
1025 }
1026 unsigned tid = -1;
1027 char pdir[TASK_COMM_LEN + 1];
1028 char state = '?';
1029 unsigned ppid = -1;
1030 unsigned utime = -1;
1031 unsigned stime = -1;
1032 int dummy;
1033 pdir[0] = '\0';
1034 // tid should not change value
1035 auto match = ::sscanf(
1036 stat.c_str(),
1037 "%u (%" ___STRING(
1038 TASK_COMM_LEN) "[^)]) %c %u %*d %*d %*d %*d %*d %*d %*d %*d %*d %u %u %d",
1039 &tid, pdir, &state, &ppid, &utime, &stime, &dummy);
1040 if (pid == -1) {
1041 pid = tid;
1042 }
1043 LOG(VERBOSE) << "match " << match << ' ' << tid << " (" << pdir << ") " << state << ' '
1044 << ppid << " ... " << utime << ' ' << stime << ' ' << dummy;
1045 if (match != 7) {
1046 continue;
1047 }
1048
Marco Ballesio38c735e2019-12-27 13:43:29 -08001049 // Get the process cgroup
1050 auto cgroup = ReadFile(piddir + "/cgroup");
1051 auto frozen = cgroup.find(":freezer:/frozen") != std::string::npos;
1052
Mark Salyzynf089e142018-02-20 10:47:40 -08001053 auto procp = llkTidLookup(tid);
1054 if (procp == nullptr) {
Marco Ballesio38c735e2019-12-27 13:43:29 -08001055 procp = llkTidAlloc(tid, pid, ppid, pdir, utime + stime, state, frozen);
Mark Salyzynf089e142018-02-20 10:47:40 -08001056 } else {
1057 // comm can change ...
1058 procp->setComm(pdir);
Marco Ballesio38c735e2019-12-27 13:43:29 -08001059 // frozen can change, too...
1060 procp->setFrozen(frozen);
Mark Salyzynf089e142018-02-20 10:47:40 -08001061 procp->updated = true;
1062 // pid/ppid/tid wrap?
1063 if (((procp->update != prevUpdate) && (procp->update != llkUpdate)) ||
1064 (procp->ppid != ppid) || (procp->pid != pid)) {
1065 procp->reset();
1066 } else if (procp->time != (utime + stime)) { // secondary ABA.
1067 // watching utime+stime granularity jiffy
1068 procp->state = '?';
1069 }
1070 procp->update = llkUpdate;
1071 procp->pid = pid;
1072 procp->ppid = ppid;
1073 procp->time = utime + stime;
1074 if (procp->state != state) {
1075 procp->count = 0ms;
Mark Salyzynafd66f22018-03-19 15:16:29 -07001076 procp->killed = !llkTestWithKill;
Mark Salyzynf089e142018-02-20 10:47:40 -08001077 procp->state = state;
1078 } else {
1079 procp->count += llkCycle;
1080 }
1081 }
1082
1083 // Filter checks in intuitive order of CPU cost to evaluate
1084 // If tid unique continue, if ppid or pid unique break
1085
1086 if (pid == myPid) {
1087 break;
1088 }
Mark Salyzyn96505fa2018-08-07 08:13:13 -07001089#ifdef __PTRACE_ENABLED__
1090 // if no stack monitoring, we can quickly exit here
1091 if (!llkIsMonitorState(state) && llkCheckStackSymbols.empty()) {
Mark Salyzynf089e142018-02-20 10:47:40 -08001092 continue;
1093 }
Mark Salyzyn96505fa2018-08-07 08:13:13 -07001094#else
1095 if (!llkIsMonitorState(state)) continue;
1096#endif
Mark Salyzynf089e142018-02-20 10:47:40 -08001097 if ((tid == myTid) || llkSkipPid(tid)) {
1098 continue;
1099 }
Marco Ballesio38c735e2019-12-27 13:43:29 -08001100 if (procp->isFrozen()) {
1101 break;
1102 }
Mark Salyzynf089e142018-02-20 10:47:40 -08001103 if (llkSkipPpid(ppid)) {
1104 break;
1105 }
1106
Mark Salyzynda2aeb02019-01-02 08:27:22 -08001107 auto process_comm = procp->getComm();
1108 if (llkSkipName(process_comm)) {
Mark Salyzynf089e142018-02-20 10:47:40 -08001109 continue;
1110 }
1111 if (llkSkipName(procp->getCmdline())) {
1112 break;
1113 }
Mark Salyzyne81ede82018-10-22 15:52:32 -07001114 if (llkSkipName(android::base::Basename(procp->getCmdline()))) {
1115 break;
1116 }
Mark Salyzynf089e142018-02-20 10:47:40 -08001117
1118 auto pprocp = llkTidLookup(ppid);
1119 if (pprocp == nullptr) {
Marco Ballesio38c735e2019-12-27 13:43:29 -08001120 pprocp = llkTidAlloc(ppid, ppid, 0, "", 0, '?', false);
Mark Salyzynf089e142018-02-20 10:47:40 -08001121 }
Mark Salyzyn8a5f0812019-01-03 08:39:38 -08001122 if (pprocp) {
Mark Salyzynda2aeb02019-01-02 08:27:22 -08001123 if (llkSkipPproc(pprocp, procp)) break;
Mark Salyzyn8a5f0812019-01-03 08:39:38 -08001124 if (llkSkipProc(pprocp, llkBlacklistParent)) break;
1125 } else {
1126 if (llkSkipName(std::to_string(ppid), llkBlacklistParent)) break;
Mark Salyzynf089e142018-02-20 10:47:40 -08001127 }
1128
1129 if ((llkBlacklistUid.size() != 0) && llkSkipUid(procp->getUid())) {
1130 continue;
1131 }
1132
1133 // ABA mitigation watching last time schedule activity happened
1134 llkCheckSchedUpdate(procp, piddir);
1135
Mark Salyzyn96505fa2018-08-07 08:13:13 -07001136#ifdef __PTRACE_ENABLED__
1137 auto stuck = llkCheckStack(procp, piddir);
1138 if (llkIsMonitorState(state)) {
1139 if (procp->count >= llkStateTimeoutMs[(state == 'Z') ? llkStateZ : llkStateD]) {
1140 stuck = true;
1141 } else if (procp->count != 0ms) {
1142 LOG(VERBOSE) << state << ' ' << llkFormat(procp->count) << ' ' << ppid << "->"
Mark Salyzynda2aeb02019-01-02 08:27:22 -08001143 << pid << "->" << tid << ' ' << process_comm;
Mark Salyzyn96505fa2018-08-07 08:13:13 -07001144 }
1145 }
1146 if (!stuck) continue;
1147#else
1148 if (procp->count >= llkStateTimeoutMs[(state == 'Z') ? llkStateZ : llkStateD]) {
1149 if (procp->count != 0ms) {
1150 LOG(VERBOSE) << state << ' ' << llkFormat(procp->count) << ' ' << ppid << "->"
Mark Salyzynda2aeb02019-01-02 08:27:22 -08001151 << pid << "->" << tid << ' ' << process_comm;
Mark Salyzyn96505fa2018-08-07 08:13:13 -07001152 }
Mark Salyzynf089e142018-02-20 10:47:40 -08001153 continue;
1154 }
Mark Salyzyn96505fa2018-08-07 08:13:13 -07001155#endif
Mark Salyzynf089e142018-02-20 10:47:40 -08001156
1157 // We have to kill it to determine difference between live lock
1158 // and persistent state blocked on a resource. Is there something
1159 // wrong with a process that has no forward scheduling progress in
1160 // Z or D? Yes, generally means improper accounting in the
1161 // process, but not always ...
1162 //
1163 // Whomever we hit with a test kill must accept the Android
1164 // Aphorism that everything can be burned to the ground and
1165 // must survive.
1166 if (procp->killed == false) {
1167 procp->killed = true;
1168 // confirm: re-read uid before committing to a panic.
1169 procp->uid = -1;
1170 switch (state) {
1171 case 'Z': // kill ppid to free up a Zombie
1172 // Killing init will kernel panic without diagnostics
1173 // so skip right to controlled kernel panic with
1174 // diagnostics.
1175 if (ppid == initPid) {
1176 break;
1177 }
1178 LOG(WARNING) << "Z " << llkFormat(procp->count) << ' ' << ppid << "->"
Mark Salyzynda2aeb02019-01-02 08:27:22 -08001179 << pid << "->" << tid << ' ' << process_comm << " [kill]";
Mark Salyzynf089e142018-02-20 10:47:40 -08001180 if ((llkKillOneProcess(pprocp, procp) >= 0) ||
1181 (llkKillOneProcess(ppid, procp) >= 0)) {
1182 continue;
1183 }
1184 break;
1185
1186 case 'D': // kill tid to free up an uninterruptible D
1187 // If ABA is doing its job, we would not need or
1188 // want the following. Test kill is a Hail Mary
1189 // to make absolutely sure there is no forward
1190 // scheduling progress. The cost when ABA is
1191 // not working is we kill a process that likes to
1192 // stay in 'D' state, instead of panicing the
1193 // kernel (worse).
Mark Salyzyn96505fa2018-08-07 08:13:13 -07001194 default:
1195 LOG(WARNING) << state << ' ' << llkFormat(procp->count) << ' ' << pid
Mark Salyzynda2aeb02019-01-02 08:27:22 -08001196 << "->" << tid << ' ' << process_comm << " [kill]";
Mark Salyzynf089e142018-02-20 10:47:40 -08001197 if ((llkKillOneProcess(llkTidLookup(pid), procp) >= 0) ||
Mark Salyzyn96505fa2018-08-07 08:13:13 -07001198 (llkKillOneProcess(pid, state, tid) >= 0) ||
Mark Salyzynf089e142018-02-20 10:47:40 -08001199 (llkKillOneProcess(procp, procp) >= 0) ||
Mark Salyzyn96505fa2018-08-07 08:13:13 -07001200 (llkKillOneProcess(tid, state, tid) >= 0)) {
Mark Salyzynf089e142018-02-20 10:47:40 -08001201 continue;
1202 }
1203 break;
1204 }
1205 }
1206 // We are here because we have confirmed kernel live-lock
Mark Salyzyn3c3b14d2018-10-31 10:38:15 -07001207 const auto message = state + " "s + llkFormat(procp->count) + " " +
1208 std::to_string(ppid) + "->" + std::to_string(pid) + "->" +
Mark Salyzynda2aeb02019-01-02 08:27:22 -08001209 std::to_string(tid) + " " + process_comm + " [panic]";
Mark Salyzynfbc3a752018-12-04 10:30:45 -08001210 llkPanicKernel(dump, tid,
Mark Salyzyn3c3b14d2018-10-31 10:38:15 -07001211 (state == 'Z') ? "zombie" : (state == 'D') ? "driver" : "sleeping",
1212 message);
Mark Salyzynfbc3a752018-12-04 10:30:45 -08001213 dump = false;
Mark Salyzynf089e142018-02-20 10:47:40 -08001214 }
1215 LOG(VERBOSE) << "+closedir()";
1216 }
1217 llkTopDirectory.rewind();
1218 LOG(VERBOSE) << "closedir()";
1219
1220 // garbage collection of old process references
1221 for (auto p = tids.begin(); p != tids.end();) {
1222 if (!p->second.updated) {
1223 IF_ALOG(LOG_VERBOSE, LOG_TAG) {
1224 std::string ppidCmdline = llkProcGetName(p->second.ppid, nullptr, nullptr);
Mark Salyzyn8a5f0812019-01-03 08:39:38 -08001225 if (!ppidCmdline.empty()) ppidCmdline = "(" + ppidCmdline + ")";
Mark Salyzynf089e142018-02-20 10:47:40 -08001226 std::string pidCmdline;
1227 if (p->second.pid != p->second.tid) {
1228 pidCmdline = llkProcGetName(p->second.pid, nullptr, p->second.getCmdline());
Mark Salyzyn8a5f0812019-01-03 08:39:38 -08001229 if (!pidCmdline.empty()) pidCmdline = "(" + pidCmdline + ")";
Mark Salyzynf089e142018-02-20 10:47:40 -08001230 }
1231 std::string tidCmdline =
1232 llkProcGetName(p->second.tid, p->second.getComm(), p->second.getCmdline());
Mark Salyzyn8a5f0812019-01-03 08:39:38 -08001233 if (!tidCmdline.empty()) tidCmdline = "(" + tidCmdline + ")";
Mark Salyzynf089e142018-02-20 10:47:40 -08001234 LOG(VERBOSE) << "thread " << p->second.ppid << ppidCmdline << "->" << p->second.pid
1235 << pidCmdline << "->" << p->second.tid << tidCmdline << " removed";
1236 }
1237 p = tids.erase(p);
1238 } else {
1239 ++p;
1240 }
1241 }
1242 if (__predict_false(tids.empty())) {
1243 llkTopDirectory.reset();
1244 }
1245
1246 llkCycle = llkCheckMs;
1247
1248 timespec end;
1249 ::clock_gettime(CLOCK_MONOTONIC_COARSE, &end);
1250 auto milli = llkGetTimespecDiffMs(&now, &end);
1251 LOG((milli > 10s) ? ERROR : (milli > 1s) ? WARNING : VERBOSE) << "sample " << llkFormat(milli);
1252
1253 // cap to minimum sleep for 1 second since last cycle
1254 if (llkCycle < (ms + 1s)) {
1255 return 1s;
1256 }
1257 return llkCycle - ms;
1258}
1259
1260unsigned llkCheckMilliseconds() {
1261 return duration_cast<milliseconds>(llkCheck()).count();
1262}
1263
Mark Salyzynbd7c8562018-10-31 10:02:08 -07001264bool llkCheckEng(const std::string& property) {
1265 return android::base::GetProperty(property, "eng") == "eng";
1266}
1267
Mark Salyzynf089e142018-02-20 10:47:40 -08001268bool llkInit(const char* threadname) {
Mark Salyzyn96505fa2018-08-07 08:13:13 -07001269 auto debuggable = android::base::GetBoolProperty("ro.debuggable", false);
Mark Salyzynf089e142018-02-20 10:47:40 -08001270 llkLowRam = android::base::GetBoolProperty("ro.config.low_ram", false);
Mark Salyzynbd7c8562018-10-31 10:02:08 -07001271 llkEnableSysrqT &= !llkLowRam;
1272 if (debuggable) {
1273 llkEnableSysrqT |= llkCheckEng(LLK_ENABLE_SYSRQ_T_PROPERTY);
1274 if (!LLK_ENABLE_DEFAULT) { // NB: default is currently true ...
1275 llkEnable |= llkCheckEng(LLK_ENABLE_PROPERTY);
1276 khtEnable |= llkCheckEng(KHT_ENABLE_PROPERTY);
1277 }
Mark Salyzynd035dbb2018-03-26 08:23:00 -07001278 }
Mark Salyzynbd7c8562018-10-31 10:02:08 -07001279 llkEnableSysrqT = android::base::GetBoolProperty(LLK_ENABLE_SYSRQ_T_PROPERTY, llkEnableSysrqT);
Mark Salyzynf089e142018-02-20 10:47:40 -08001280 llkEnable = android::base::GetBoolProperty(LLK_ENABLE_PROPERTY, llkEnable);
1281 if (llkEnable && !llkTopDirectory.reset(procdir)) {
1282 // Most likely reason we could be here is llkd was started
1283 // incorrectly without the readproc permissions. Keep our
1284 // processing down to a minimum.
1285 llkEnable = false;
1286 }
1287 khtEnable = android::base::GetBoolProperty(KHT_ENABLE_PROPERTY, khtEnable);
1288 llkMlockall = android::base::GetBoolProperty(LLK_MLOCKALL_PROPERTY, llkMlockall);
Mark Salyzynafd66f22018-03-19 15:16:29 -07001289 llkTestWithKill = android::base::GetBoolProperty(LLK_KILLTEST_PROPERTY, llkTestWithKill);
Mark Salyzynf089e142018-02-20 10:47:40 -08001290 // if LLK_TIMOUT_MS_PROPERTY was not set, we will use a set
1291 // KHT_TIMEOUT_PROPERTY as co-operative guidance for the default value.
1292 khtTimeout = GetUintProperty(KHT_TIMEOUT_PROPERTY, khtTimeout);
1293 if (khtTimeout == 0s) {
1294 khtTimeout = duration_cast<seconds>(llkTimeoutMs * (1 + LLK_CHECKS_PER_TIMEOUT_DEFAULT) /
1295 LLK_CHECKS_PER_TIMEOUT_DEFAULT);
1296 }
1297 llkTimeoutMs =
1298 khtTimeout * LLK_CHECKS_PER_TIMEOUT_DEFAULT / (1 + LLK_CHECKS_PER_TIMEOUT_DEFAULT);
1299 llkTimeoutMs = GetUintProperty(LLK_TIMEOUT_MS_PROPERTY, llkTimeoutMs);
1300 llkValidate(); // validate llkTimeoutMs, llkCheckMs and llkCycle
1301 llkStateTimeoutMs[llkStateD] = GetUintProperty(LLK_D_TIMEOUT_MS_PROPERTY, llkTimeoutMs);
1302 llkStateTimeoutMs[llkStateZ] = GetUintProperty(LLK_Z_TIMEOUT_MS_PROPERTY, llkTimeoutMs);
Mark Salyzyn96505fa2018-08-07 08:13:13 -07001303#ifdef __PTRACE_ENABLED__
1304 llkStateTimeoutMs[llkStateStack] = GetUintProperty(LLK_STACK_TIMEOUT_MS_PROPERTY, llkTimeoutMs);
1305#endif
Mark Salyzynf089e142018-02-20 10:47:40 -08001306 llkCheckMs = GetUintProperty(LLK_CHECK_MS_PROPERTY, llkCheckMs);
1307 llkValidate(); // validate all (effectively minus llkTimeoutMs)
Mark Salyzyn96505fa2018-08-07 08:13:13 -07001308#ifdef __PTRACE_ENABLED__
1309 if (debuggable) {
Mark Salyzyn8a5f0812019-01-03 08:39:38 -08001310 llkCheckStackSymbols = llkSplit(LLK_CHECK_STACK_PROPERTY, LLK_CHECK_STACK_DEFAULT);
Mark Salyzyn96505fa2018-08-07 08:13:13 -07001311 }
1312 std::string defaultBlacklistStack(LLK_BLACKLIST_STACK_DEFAULT);
1313 if (!debuggable) defaultBlacklistStack += ",logd,/system/bin/logd";
Mark Salyzyn8a5f0812019-01-03 08:39:38 -08001314 llkBlacklistStack = llkSplit(LLK_BLACKLIST_STACK_PROPERTY, defaultBlacklistStack);
Mark Salyzyn96505fa2018-08-07 08:13:13 -07001315#endif
Mark Salyzynf089e142018-02-20 10:47:40 -08001316 std::string defaultBlacklistProcess(
1317 std::to_string(kernelPid) + "," + std::to_string(initPid) + "," +
1318 std::to_string(kthreaddPid) + "," + std::to_string(::getpid()) + "," +
1319 std::to_string(::gettid()) + "," LLK_BLACKLIST_PROCESS_DEFAULT);
1320 if (threadname) {
Mark Salyzyn52e54a62018-08-07 08:13:13 -07001321 defaultBlacklistProcess += ","s + threadname;
Mark Salyzynf089e142018-02-20 10:47:40 -08001322 }
1323 for (int cpu = 1; cpu < get_nprocs_conf(); ++cpu) {
1324 defaultBlacklistProcess += ",[watchdog/" + std::to_string(cpu) + "]";
1325 }
Mark Salyzyn8a5f0812019-01-03 08:39:38 -08001326 llkBlacklistProcess = llkSplit(LLK_BLACKLIST_PROCESS_PROPERTY, defaultBlacklistProcess);
Mark Salyzynf089e142018-02-20 10:47:40 -08001327 if (!llkSkipName("[khungtaskd]")) { // ALWAYS ignore as special
1328 llkBlacklistProcess.emplace("[khungtaskd]");
1329 }
Mark Salyzyn8a5f0812019-01-03 08:39:38 -08001330 llkBlacklistParent = llkSplit(LLK_BLACKLIST_PARENT_PROPERTY,
1331 std::to_string(kernelPid) + "," + std::to_string(kthreaddPid) +
1332 "," LLK_BLACKLIST_PARENT_DEFAULT);
Mark Salyzynda2aeb02019-01-02 08:27:22 -08001333 // derive llkBlacklistParentAndChild by moving entries with '&' from above
1334 for (auto it = llkBlacklistParent.begin(); it != llkBlacklistParent.end();) {
1335 auto pos = it->find('&');
1336 if (pos == std::string::npos) {
1337 ++it;
1338 continue;
1339 }
1340 auto parent = it->substr(0, pos);
1341 auto child = it->substr(pos + 1);
1342 it = llkBlacklistParent.erase(it);
1343
1344 auto found = llkBlacklistParentAndChild.find(parent);
1345 if (found == llkBlacklistParentAndChild.end()) {
1346 llkBlacklistParentAndChild.emplace(std::make_pair(
1347 std::move(parent), std::unordered_set<std::string>({std::move(child)})));
1348 } else {
1349 found->second.emplace(std::move(child));
1350 }
1351 }
1352
Mark Salyzyn8a5f0812019-01-03 08:39:38 -08001353 llkBlacklistUid = llkSplit(LLK_BLACKLIST_UID_PROPERTY, LLK_BLACKLIST_UID_DEFAULT);
Mark Salyzynf089e142018-02-20 10:47:40 -08001354
1355 // internal watchdog
1356 ::signal(SIGALRM, llkAlarmHandler);
1357
1358 // kernel hung task configuration? Otherwise leave it as-is
1359 if (khtEnable) {
1360 // EUID must be AID_ROOT to write to /proc/sys/kernel/ nodes, there
1361 // are no capability overrides. For security reasons we do not want
1362 // to run as AID_ROOT. We may not be able to write them successfully,
1363 // we will try, but the least we can do is read the values back to
1364 // confirm expectations and report whether configured or not.
1365 auto configured = llkWriteStringToFileConfirm(std::to_string(khtTimeout.count()),
1366 "/proc/sys/kernel/hung_task_timeout_secs");
1367 if (configured) {
1368 llkWriteStringToFile("65535", "/proc/sys/kernel/hung_task_warnings");
1369 llkWriteStringToFile("65535", "/proc/sys/kernel/hung_task_check_count");
1370 configured = llkWriteStringToFileConfirm("1", "/proc/sys/kernel/hung_task_panic");
1371 }
1372 if (configured) {
1373 LOG(INFO) << "[khungtaskd] configured";
1374 } else {
1375 LOG(WARNING) << "[khungtaskd] not configurable";
1376 }
1377 }
1378
1379 bool logConfig = true;
1380 if (llkEnable) {
1381 if (llkMlockall &&
1382 // MCL_ONFAULT pins pages as they fault instead of loading
1383 // everything immediately all at once. (Which would be bad,
1384 // because as of this writing, we have a lot of mapped pages we
1385 // never use.) Old kernels will see MCL_ONFAULT and fail with
1386 // EINVAL; we ignore this failure.
1387 //
1388 // N.B. read the man page for mlockall. MCL_CURRENT | MCL_ONFAULT
1389 // pins ⊆ MCL_CURRENT, converging to just MCL_CURRENT as we fault
1390 // in pages.
1391
1392 // CAP_IPC_LOCK required
1393 mlockall(MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT) && (errno != EINVAL)) {
1394 PLOG(WARNING) << "mlockall failed ";
1395 }
1396
1397 if (threadname) {
1398 pthread_attr_t attr;
1399
1400 if (!pthread_attr_init(&attr)) {
1401 sched_param param;
1402
1403 memset(&param, 0, sizeof(param));
1404 pthread_attr_setschedparam(&attr, &param);
1405 pthread_attr_setschedpolicy(&attr, SCHED_BATCH);
1406 if (!pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)) {
1407 pthread_t thread;
1408 if (!pthread_create(&thread, &attr, llkThread, const_cast<char*>(threadname))) {
1409 // wait a second for thread to start
1410 for (auto retry = 50; retry && !llkRunning; --retry) {
1411 ::usleep(20000);
1412 }
1413 logConfig = !llkRunning; // printed in llkd context?
1414 } else {
1415 LOG(ERROR) << "failed to spawn llkd thread";
1416 }
1417 } else {
1418 LOG(ERROR) << "failed to detach llkd thread";
1419 }
1420 pthread_attr_destroy(&attr);
1421 } else {
1422 LOG(ERROR) << "failed to allocate attibutes for llkd thread";
1423 }
1424 }
1425 } else {
1426 LOG(DEBUG) << "[khungtaskd] left unconfigured";
1427 }
1428 if (logConfig) {
1429 llkLogConfig();
1430 }
1431
1432 return llkEnable;
1433}