blob: f357cc2ca7732792516ee3d0d0a5337c5917e040 [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>
27#include <sys/cdefs.h> // ___STRING, __predict_true() and _predict_false()
28#include <sys/mman.h> // mlockall()
29#include <sys/prctl.h>
30#include <sys/stat.h> // lstat()
31#include <sys/syscall.h> // __NR_getdents64
32#include <sys/sysinfo.h> // get_nprocs_conf()
33#include <sys/types.h>
34#include <time.h>
35#include <unistd.h>
36
37#include <chrono>
38#include <ios>
39#include <sstream>
40#include <string>
41#include <unordered_map>
42#include <unordered_set>
43
44#include <android-base/file.h>
45#include <android-base/logging.h>
46#include <android-base/parseint.h>
47#include <android-base/properties.h>
48#include <android-base/strings.h>
49#include <cutils/android_get_control_file.h>
50#include <log/log_main.h>
51
52#define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x)))
53
54#define TASK_COMM_LEN 16 // internal kernel, not uapi, from .../linux/include/linux/sched.h
55
56using namespace std::chrono_literals;
57using namespace std::chrono;
58
59namespace {
60
61constexpr pid_t kernelPid = 0;
62constexpr pid_t initPid = 1;
63constexpr pid_t kthreaddPid = 2;
64
65constexpr char procdir[] = "/proc/";
66
67// Configuration
68milliseconds llkUpdate; // last check ms signature
69milliseconds llkCycle; // ms to next thread check
70bool llkEnable = LLK_ENABLE_DEFAULT; // llk daemon enabled
71bool llkRunning = false; // thread is running
72bool llkMlockall = LLK_MLOCKALL_DEFAULT; // run mlocked
Mark Salyzynafd66f22018-03-19 15:16:29 -070073bool llkTestWithKill = LLK_KILLTEST_DEFAULT; // issue test kills
Mark Salyzynf089e142018-02-20 10:47:40 -080074milliseconds llkTimeoutMs = LLK_TIMEOUT_MS_DEFAULT; // default timeout
75enum { llkStateD, llkStateZ, llkNumStates }; // state indexes
76milliseconds llkStateTimeoutMs[llkNumStates]; // timeout override for each detection state
77milliseconds llkCheckMs; // checking interval to inspect any
78 // persistent live-locked states
79bool llkLowRam; // ro.config.low_ram
80bool khtEnable = LLK_ENABLE_DEFAULT; // [khungtaskd] panic
81// [khungtaskd] should have a timeout beyond the granularity of llkTimeoutMs.
82// Provides a wide angle of margin b/c khtTimeout is also its granularity.
83seconds khtTimeout = duration_cast<seconds>(llkTimeoutMs * (1 + LLK_CHECKS_PER_TIMEOUT_DEFAULT) /
84 LLK_CHECKS_PER_TIMEOUT_DEFAULT);
85
86// Blacklist variables, initialized with comma separated lists of high false
87// positive and/or dangerous references, e.g. without self restart, for pid,
88// ppid, name and uid:
89
90// list of pids, or tids or names to skip. kernel pid (0), init pid (1),
91// [kthreadd] pid (2), ourselves, "init", "[kthreadd]", "lmkd", "llkd" or
92// combinations of watchdogd in kernel and user space.
93std::unordered_set<std::string> llkBlacklistProcess;
94// list of parent pids, comm or cmdline names to skip. default:
95// kernel pid (0), [kthreadd] (2), or ourselves, enforced and implied
96std::unordered_set<std::string> llkBlacklistParent;
97// list of uids, and uid names, to skip, default nothing
98std::unordered_set<std::string> llkBlacklistUid;
99
100class dir {
101 public:
102 enum level { proc, task, numLevels };
103
104 private:
105 int fd;
106 size_t available_bytes;
107 dirent* next;
108 // each directory level picked to be just north of 4K in size
109 static constexpr size_t buffEntries = 15;
110 static dirent buff[numLevels][buffEntries];
111
112 bool fill(enum level index) {
113 if (index >= numLevels) return false;
114 if (available_bytes != 0) return true;
115 if (__predict_false(fd < 0)) return false;
116 // getdents64 has no libc wrapper
117 auto rc = TEMP_FAILURE_RETRY(syscall(__NR_getdents64, fd, buff[index], sizeof(buff[0]), 0));
118 if (rc <= 0) return false;
119 available_bytes = rc;
120 next = buff[index];
121 return true;
122 }
123
124 public:
125 dir() : fd(-1), available_bytes(0), next(nullptr) {}
126
127 explicit dir(const char* directory)
128 : fd(__predict_true(directory != nullptr)
129 ? ::open(directory, O_CLOEXEC | O_DIRECTORY | O_RDONLY)
130 : -1),
131 available_bytes(0),
132 next(nullptr) {}
133
134 explicit dir(const std::string&& directory)
135 : fd(::open(directory.c_str(), O_CLOEXEC | O_DIRECTORY | O_RDONLY)),
136 available_bytes(0),
137 next(nullptr) {}
138
139 explicit dir(const std::string& directory)
140 : fd(::open(directory.c_str(), O_CLOEXEC | O_DIRECTORY | O_RDONLY)),
141 available_bytes(0),
142 next(nullptr) {}
143
144 // Don't need any copy or move constructors.
145 explicit dir(const dir& c) = delete;
146 explicit dir(dir& c) = delete;
147 explicit dir(dir&& c) = delete;
148
149 ~dir() {
150 if (fd >= 0) {
151 ::close(fd);
152 }
153 }
154
155 operator bool() const { return fd >= 0; }
156
157 void reset(void) {
158 if (fd >= 0) {
159 ::close(fd);
160 fd = -1;
161 available_bytes = 0;
162 next = nullptr;
163 }
164 }
165
166 dir& reset(const char* directory) {
167 reset();
168 // available_bytes will _always_ be zero here as its value is
169 // intimately tied to fd < 0 or not.
170 fd = ::open(directory, O_CLOEXEC | O_DIRECTORY | O_RDONLY);
171 return *this;
172 }
173
174 void rewind(void) {
175 if (fd >= 0) {
176 ::lseek(fd, off_t(0), SEEK_SET);
177 available_bytes = 0;
178 next = nullptr;
179 }
180 }
181
182 dirent* read(enum level index = proc, dirent* def = nullptr) {
183 if (!fill(index)) return def;
184 auto ret = next;
185 available_bytes -= next->d_reclen;
186 next = reinterpret_cast<dirent*>(reinterpret_cast<char*>(next) + next->d_reclen);
187 return ret;
188 }
189} llkTopDirectory;
190
191dirent dir::buff[dir::numLevels][dir::buffEntries];
192
193// helper functions
194
195bool llkIsMissingExeLink(pid_t tid) {
196 char c;
197 // CAP_SYS_PTRACE is required to prevent ret == -1, but ENOENT is signal
198 auto ret = ::readlink((procdir + std::to_string(tid) + "/exe").c_str(), &c, sizeof(c));
199 return (ret == -1) && (errno == ENOENT);
200}
201
202// Common routine where caller accepts empty content as error/passthrough.
203// Reduces the churn of reporting read errors in the callers.
204std::string ReadFile(std::string&& path) {
205 std::string content;
206 if (!android::base::ReadFileToString(path, &content)) {
207 PLOG(DEBUG) << "Read " << path << " failed";
208 content = "";
209 }
210 return content;
211}
212
213std::string llkProcGetName(pid_t tid, const char* node = "/cmdline") {
214 std::string content = ReadFile(procdir + std::to_string(tid) + node);
215 static constexpr char needles[] = " \t\r\n"; // including trailing nul
216 auto pos = content.find_first_of(needles, 0, sizeof(needles));
217 if (pos != std::string::npos) {
218 content.erase(pos);
219 }
220 return content;
221}
222
223uid_t llkProcGetUid(pid_t tid) {
224 // Get the process' uid. The following read from /status is admittedly
225 // racy, prone to corruption due to shape-changes. The consequences are
226 // not catastrophic as we sample a few times before taking action.
227 //
228 // If /loginuid worked on reliably, or on Android (all tasks report -1)...
229 // Android lmkd causes /cgroup to contain memory:/<dom>/uid_<uid>/pid_<pid>
230 // which is tighter, but also not reliable.
231 std::string content = ReadFile(procdir + std::to_string(tid) + "/status");
232 static constexpr char Uid[] = "\nUid:";
233 auto pos = content.find(Uid);
234 if (pos == std::string::npos) {
235 return -1;
236 }
237 pos += ::strlen(Uid);
238 while ((pos < content.size()) && ::isblank(content[pos])) {
239 ++pos;
240 }
241 content.erase(0, pos);
242 for (pos = 0; (pos < content.size()) && ::isdigit(content[pos]); ++pos) {
243 ;
244 }
245 // Content of form 'Uid: 0 0 0 0', newline is error
246 if ((pos >= content.size()) || !::isblank(content[pos])) {
247 return -1;
248 }
249 content.erase(pos);
250 uid_t ret;
251 if (!android::base::ParseInt(content, &ret, uid_t(0))) {
252 return -1;
253 }
254 return ret;
255}
256
257struct proc {
258 pid_t tid; // monitored thread id (in Z or D state).
259 nanoseconds schedUpdate; // /proc/<tid>/sched "se.avg.lastUpdateTime",
260 uint64_t nrSwitches; // /proc/<tid>/sched "nr_switches" for
261 // refined ABA problem detection, determine
262 // forward scheduling progress.
263 milliseconds update; // llkUpdate millisecond signature of last.
264 milliseconds count; // duration in state.
265 pid_t pid; // /proc/<pid> before iterating through
266 // /proc/<pid>/task/<tid> for threads.
267 pid_t ppid; // /proc/<tid>/stat field 4 parent pid.
268 uid_t uid; // /proc/<tid>/status Uid: field.
269 unsigned time; // sum of /proc/<tid>/stat field 14 utime &
270 // 15 stime for coarse ABA problem detection.
271 std::string cmdline; // cached /cmdline content
272 char state; // /proc/<tid>/stat field 3: Z or D
273 // (others we do not monitor: S, R, T or ?)
274 char comm[TASK_COMM_LEN + 3]; // space for adding '[' and ']'
275 bool exeMissingValid; // exeMissing has been cached
276 bool cmdlineValid; // cmdline has been cached
277 bool updated; // cleared before monitoring pass.
278 bool killed; // sent a kill to this thread, next panic...
279
280 void setComm(const char* _comm) { strncpy(comm + 1, _comm, sizeof(comm) - 2); }
281
282 proc(pid_t tid, pid_t pid, pid_t ppid, const char* _comm, int time, char state)
283 : tid(tid),
284 schedUpdate(0),
285 nrSwitches(0),
286 update(llkUpdate),
287 count(0),
288 pid(pid),
289 ppid(ppid),
290 uid(-1),
291 time(time),
292 state(state),
293 exeMissingValid(false),
294 cmdlineValid(false),
295 updated(true),
Mark Salyzynafd66f22018-03-19 15:16:29 -0700296 killed(!llkTestWithKill) {
Mark Salyzynf089e142018-02-20 10:47:40 -0800297 memset(comm, '\0', sizeof(comm));
298 setComm(_comm);
299 }
300
301 const char* getComm(void) {
302 if (comm[1] == '\0') { // comm Valid?
303 strncpy(comm + 1, llkProcGetName(tid, "/comm").c_str(), sizeof(comm) - 2);
304 }
305 if (!exeMissingValid) {
306 if (llkIsMissingExeLink(tid)) {
307 comm[0] = '[';
308 }
309 exeMissingValid = true;
310 }
311 size_t len = strlen(comm + 1);
312 if (__predict_true(len < (sizeof(comm) - 1))) {
313 if (comm[0] == '[') {
314 if ((comm[len] != ']') && __predict_true(len < (sizeof(comm) - 2))) {
315 comm[++len] = ']';
316 comm[++len] = '\0';
317 }
318 } else {
319 if (comm[len] == ']') {
320 comm[len] = '\0';
321 }
322 }
323 }
324 return &comm[comm[0] != '['];
325 }
326
327 const char* getCmdline(void) {
328 if (!cmdlineValid) {
329 cmdline = llkProcGetName(tid);
330 cmdlineValid = true;
331 }
332 return cmdline.c_str();
333 }
334
335 uid_t getUid(void) {
336 if (uid <= 0) { // Churn on root user, because most likely to setuid()
337 uid = llkProcGetUid(tid);
338 }
339 return uid;
340 }
341
342 void reset(void) { // reset cache, if we detected pid rollover
343 uid = -1;
344 state = '?';
345 cmdline = "";
346 comm[0] = '\0';
347 exeMissingValid = false;
348 cmdlineValid = false;
349 }
350};
351
352std::unordered_map<pid_t, proc> tids;
353
354// Check range and setup defaults, in order of propagation:
355// llkTimeoutMs
356// llkCheckMs
357// ...
358// KISS to keep it all self-contained, and called multiple times as parameters
359// are interpreted so that defaults, llkCheckMs and llkCycle make sense.
360void llkValidate() {
361 if (llkTimeoutMs == 0ms) {
362 llkTimeoutMs = LLK_TIMEOUT_MS_DEFAULT;
363 }
364 llkTimeoutMs = std::max(llkTimeoutMs, LLK_TIMEOUT_MS_MINIMUM);
365 if (llkCheckMs == 0ms) {
366 llkCheckMs = llkTimeoutMs / LLK_CHECKS_PER_TIMEOUT_DEFAULT;
367 }
368 llkCheckMs = std::min(llkCheckMs, llkTimeoutMs);
369
370 for (size_t state = 0; state < ARRAY_SIZE(llkStateTimeoutMs); ++state) {
371 if (llkStateTimeoutMs[state] == 0ms) {
372 llkStateTimeoutMs[state] = llkTimeoutMs;
373 }
374 llkStateTimeoutMs[state] =
375 std::min(std::max(llkStateTimeoutMs[state], LLK_TIMEOUT_MS_MINIMUM), llkTimeoutMs);
376 llkCheckMs = std::min(llkCheckMs, llkStateTimeoutMs[state]);
377 }
378
379 llkCheckMs = std::max(llkCheckMs, LLK_CHECK_MS_MINIMUM);
380 if (llkCycle == 0ms) {
381 llkCycle = llkCheckMs;
382 }
383 llkCycle = std::min(llkCycle, llkCheckMs);
384}
385
386milliseconds llkGetTimespecDiffMs(timespec* from, timespec* to) {
387 return duration_cast<milliseconds>(seconds(to->tv_sec - from->tv_sec)) +
388 duration_cast<milliseconds>(nanoseconds(to->tv_nsec - from->tv_nsec));
389}
390
391std::string llkProcGetName(pid_t tid, const char* comm, const char* cmdline) {
392 if ((cmdline != nullptr) && (*cmdline != '\0')) {
393 return cmdline;
394 }
395 if ((comm != nullptr) && (*comm != '\0')) {
396 return comm;
397 }
398
399 // UNLIKELY! Here because killed before we kill it?
400 // Assume change is afoot, do not call llkTidAlloc
401
402 // cmdline ?
403 std::string content = llkProcGetName(tid);
404 if (content.size() != 0) {
405 return content;
406 }
407 // Comm instead?
408 content = llkProcGetName(tid, "/comm");
409 if (llkIsMissingExeLink(tid) && (content.size() != 0)) {
410 return '[' + content + ']';
411 }
412 return content;
413}
414
415int llkKillOneProcess(pid_t pid, char state, pid_t tid, const char* tcomm = nullptr,
416 const char* tcmdline = nullptr, const char* pcomm = nullptr,
417 const char* pcmdline = nullptr) {
418 std::string forTid;
419 if (tid != pid) {
420 forTid = " for '" + llkProcGetName(tid, tcomm, tcmdline) + "' (" + std::to_string(tid) + ")";
421 }
422 LOG(INFO) << "Killing '" << llkProcGetName(pid, pcomm, pcmdline) << "' (" << pid
423 << ") to check forward scheduling progress in " << state << " state" << forTid;
424 // CAP_KILL required
425 errno = 0;
426 auto r = ::kill(pid, SIGKILL);
427 if (r) {
428 PLOG(ERROR) << "kill(" << pid << ")=" << r << ' ';
429 }
430
431 return r;
432}
433
434// Kill one process
435int llkKillOneProcess(pid_t pid, proc* tprocp) {
436 return llkKillOneProcess(pid, tprocp->state, tprocp->tid, tprocp->getComm(),
437 tprocp->getCmdline());
438}
439
440// Kill one process specified by kprocp
441int llkKillOneProcess(proc* kprocp, proc* tprocp) {
442 if (kprocp == nullptr) {
443 return -2;
444 }
445
446 return llkKillOneProcess(kprocp->tid, tprocp->state, tprocp->tid, tprocp->getComm(),
447 tprocp->getCmdline(), kprocp->getComm(), kprocp->getCmdline());
448}
449
450// Acquire file descriptor from environment, or open and cache it.
451// NB: cache is unnecessary in our current context, pedantically
452// required to prevent leakage of file descriptors in the future.
453int llkFileToWriteFd(const std::string& file) {
454 static std::unordered_map<std::string, int> cache;
455 auto search = cache.find(file);
456 if (search != cache.end()) return search->second;
457 auto fd = android_get_control_file(file.c_str());
458 if (fd >= 0) return fd;
459 fd = TEMP_FAILURE_RETRY(::open(file.c_str(), O_WRONLY | O_CLOEXEC));
460 if (fd >= 0) cache.emplace(std::make_pair(file, fd));
461 return fd;
462}
463
464// Wrap android::base::WriteStringToFile to use android_get_control_file.
465bool llkWriteStringToFile(const std::string& string, const std::string& file) {
466 auto fd = llkFileToWriteFd(file);
467 if (fd < 0) return false;
468 return android::base::WriteStringToFd(string, fd);
469}
470
471bool llkWriteStringToFileConfirm(const std::string& string, const std::string& file) {
472 auto fd = llkFileToWriteFd(file);
473 auto ret = (fd < 0) ? false : android::base::WriteStringToFd(string, fd);
474 std::string content;
475 if (!android::base::ReadFileToString(file, &content)) return ret;
476 return android::base::Trim(content) == string;
477}
478
Mark Salyzynafd66f22018-03-19 15:16:29 -0700479void llkPanicKernel(bool dump, pid_t tid, const char* state) __noreturn;
480void llkPanicKernel(bool dump, pid_t tid, const char* state) {
Mark Salyzynf089e142018-02-20 10:47:40 -0800481 auto sysrqTriggerFd = llkFileToWriteFd("/proc/sysrq-trigger");
482 if (sysrqTriggerFd < 0) {
483 // DYB
484 llkKillOneProcess(initPid, 'R', tid);
485 // The answer to life, the universe and everything
486 ::exit(42);
487 // NOTREACHED
488 }
489 ::sync();
490 if (dump) {
491 // Show all locks that are held
492 android::base::WriteStringToFd("d", sysrqTriggerFd);
493 // This can trigger hardware watchdog, that is somewhat _ok_.
494 // But useless if pstore configured for <256KB, low ram devices ...
495 if (!llkLowRam) {
496 android::base::WriteStringToFd("t", sysrqTriggerFd);
497 }
498 ::usleep(200000); // let everything settle
499 }
Mark Salyzynafd66f22018-03-19 15:16:29 -0700500 llkWriteStringToFile(std::string("SysRq : Trigger a crash : 'livelock,") + state + "'\n",
501 "/dev/kmsg");
Mark Salyzynf089e142018-02-20 10:47:40 -0800502 android::base::WriteStringToFd("c", sysrqTriggerFd);
503 // NOTREACHED
504 // DYB
505 llkKillOneProcess(initPid, 'R', tid);
506 // I sat at my desk, stared into the garden and thought '42 will do'.
507 // I typed it out. End of story
508 ::exit(42);
509 // NOTREACHED
510}
511
512void llkAlarmHandler(int) {
Mark Salyzynafd66f22018-03-19 15:16:29 -0700513 llkPanicKernel(false, ::getpid(), "alarm");
Mark Salyzynf089e142018-02-20 10:47:40 -0800514}
515
516milliseconds GetUintProperty(const std::string& key, milliseconds def) {
517 return milliseconds(android::base::GetUintProperty(key, static_cast<uint64_t>(def.count()),
518 static_cast<uint64_t>(def.max().count())));
519}
520
521seconds GetUintProperty(const std::string& key, seconds def) {
522 return seconds(android::base::GetUintProperty(key, static_cast<uint64_t>(def.count()),
523 static_cast<uint64_t>(def.max().count())));
524}
525
526proc* llkTidLookup(pid_t tid) {
527 auto search = tids.find(tid);
528 if (search == tids.end()) {
529 return nullptr;
530 }
531 return &search->second;
532}
533
534void llkTidRemove(pid_t tid) {
535 tids.erase(tid);
536}
537
538proc* llkTidAlloc(pid_t tid, pid_t pid, pid_t ppid, const char* comm, int time, char state) {
539 auto it = tids.emplace(std::make_pair(tid, proc(tid, pid, ppid, comm, time, state)));
540 return &it.first->second;
541}
542
543std::string llkFormat(milliseconds ms) {
544 auto sec = duration_cast<seconds>(ms);
545 std::ostringstream s;
546 s << sec.count() << '.';
547 auto f = s.fill('0');
548 auto w = s.width(3);
549 s << std::right << (ms - sec).count();
550 s.width(w);
551 s.fill(f);
552 s << 's';
553 return s.str();
554}
555
556std::string llkFormat(seconds s) {
557 return std::to_string(s.count()) + 's';
558}
559
560std::string llkFormat(bool flag) {
561 return flag ? "true" : "false";
562}
563
564std::string llkFormat(const std::unordered_set<std::string>& blacklist) {
565 std::string ret;
566 for (auto entry : blacklist) {
567 if (ret.size()) {
568 ret += ",";
569 }
570 ret += entry;
571 }
572 return ret;
573}
574
575// We only officially support comma separators, but wetware being what they
576// are will take some liberty and I do not believe they should be punished.
577std::unordered_set<std::string> llkSplit(const std::string& s,
578 const std::string& delimiters = ", \t:") {
579 std::unordered_set<std::string> result;
580
581 size_t base = 0;
582 size_t found;
583 while (true) {
584 found = s.find_first_of(delimiters, base);
585 result.emplace(s.substr(base, found - base));
586 if (found == s.npos) break;
587 base = found + 1;
588 }
589 return result;
590}
591
592bool llkSkipName(const std::string& name,
593 const std::unordered_set<std::string>& blacklist = llkBlacklistProcess) {
594 if ((name.size() == 0) || (blacklist.size() == 0)) {
595 return false;
596 }
597
598 return blacklist.find(name) != blacklist.end();
599}
600
601bool llkSkipPid(pid_t pid) {
602 return llkSkipName(std::to_string(pid), llkBlacklistProcess);
603}
604
605bool llkSkipPpid(pid_t ppid) {
606 return llkSkipName(std::to_string(ppid), llkBlacklistParent);
607}
608
609bool llkSkipUid(uid_t uid) {
610 // Match by number?
611 if (llkSkipName(std::to_string(uid), llkBlacklistUid)) {
612 return true;
613 }
614
615 // Match by name?
616 auto pwd = ::getpwuid(uid);
617 return (pwd != nullptr) && __predict_true(pwd->pw_name != nullptr) &&
618 __predict_true(pwd->pw_name[0] != '\0') && llkSkipName(pwd->pw_name, llkBlacklistUid);
619}
620
621bool getValidTidDir(dirent* dp, std::string* piddir) {
622 if (!::isdigit(dp->d_name[0])) {
623 return false;
624 }
625
626 // Corner case can not happen in reality b/c of above ::isdigit check
627 if (__predict_false(dp->d_type != DT_DIR)) {
628 if (__predict_false(dp->d_type == DT_UNKNOWN)) { // can't b/c procfs
629 struct stat st;
630 *piddir = procdir;
631 *piddir += dp->d_name;
632 return (lstat(piddir->c_str(), &st) == 0) && (st.st_mode & S_IFDIR);
633 }
634 return false;
635 }
636
637 *piddir = procdir;
638 *piddir += dp->d_name;
639 return true;
640}
641
642bool llkIsMonitorState(char state) {
643 return (state == 'Z') || (state == 'D');
644}
645
646// returns -1 if not found
647long long getSchedValue(const std::string& schedString, const char* key) {
648 auto pos = schedString.find(key);
649 if (pos == std::string::npos) {
650 return -1;
651 }
652 pos = schedString.find(':', pos);
653 if (__predict_false(pos == std::string::npos)) {
654 return -1;
655 }
656 while ((++pos < schedString.size()) && ::isblank(schedString[pos])) {
657 ;
658 }
659 long long ret;
660 if (!android::base::ParseInt(schedString.substr(pos), &ret, static_cast<long long>(0))) {
661 return -1;
662 }
663 return ret;
664}
665
666// Primary ABA mitigation watching last time schedule activity happened
667void llkCheckSchedUpdate(proc* procp, const std::string& piddir) {
668 // Audit finds /proc/<tid>/sched is just over 1K, and
669 // is rarely larger than 2K, even less on Android.
670 // For example, the "se.avg.lastUpdateTime" field we are
671 // interested in typically within the primary set in
672 // the first 1K.
673 //
674 // Proc entries can not be read >1K atomically via libbase,
675 // but if there are problems we assume at least a few
676 // samples of reads occur before we take any real action.
677 std::string schedString = ReadFile(piddir + "/sched");
678 if (schedString.size() == 0) {
679 // /schedstat is not as standardized, but in 3.1+
680 // Android devices, the third field is nr_switches
681 // from /sched:
682 schedString = ReadFile(piddir + "/schedstat");
683 if (schedString.size() == 0) {
684 return;
685 }
686 auto val = static_cast<unsigned long long>(-1);
687 if (((::sscanf(schedString.c_str(), "%*d %*d %llu", &val)) == 1) &&
688 (val != static_cast<unsigned long long>(-1)) && (val != 0) &&
689 (val != procp->nrSwitches)) {
690 procp->nrSwitches = val;
691 procp->count = 0ms;
Mark Salyzynafd66f22018-03-19 15:16:29 -0700692 procp->killed = !llkTestWithKill;
Mark Salyzynf089e142018-02-20 10:47:40 -0800693 }
694 return;
695 }
696
697 auto val = getSchedValue(schedString, "\nse.avg.lastUpdateTime");
698 if (val == -1) {
699 val = getSchedValue(schedString, "\nse.svg.last_update_time");
700 }
701 if (val != -1) {
702 auto schedUpdate = nanoseconds(val);
703 if (schedUpdate != procp->schedUpdate) {
704 procp->schedUpdate = schedUpdate;
705 procp->count = 0ms;
Mark Salyzynafd66f22018-03-19 15:16:29 -0700706 procp->killed = !llkTestWithKill;
Mark Salyzynf089e142018-02-20 10:47:40 -0800707 }
708 }
709
710 val = getSchedValue(schedString, "\nnr_switches");
711 if (val != -1) {
712 if (static_cast<uint64_t>(val) != procp->nrSwitches) {
713 procp->nrSwitches = val;
714 procp->count = 0ms;
Mark Salyzynafd66f22018-03-19 15:16:29 -0700715 procp->killed = !llkTestWithKill;
Mark Salyzynf089e142018-02-20 10:47:40 -0800716 }
717 }
718}
719
720void llkLogConfig(void) {
721 LOG(INFO) << "ro.config.low_ram=" << llkFormat(llkLowRam) << "\n"
722 << LLK_ENABLE_PROPERTY "=" << llkFormat(llkEnable) << "\n"
723 << KHT_ENABLE_PROPERTY "=" << llkFormat(khtEnable) << "\n"
724 << LLK_MLOCKALL_PROPERTY "=" << llkFormat(llkMlockall) << "\n"
Mark Salyzynafd66f22018-03-19 15:16:29 -0700725 << LLK_KILLTEST_PROPERTY "=" << llkFormat(llkTestWithKill) << "\n"
Mark Salyzynf089e142018-02-20 10:47:40 -0800726 << KHT_TIMEOUT_PROPERTY "=" << llkFormat(khtTimeout) << "\n"
727 << LLK_TIMEOUT_MS_PROPERTY "=" << llkFormat(llkTimeoutMs) << "\n"
728 << LLK_D_TIMEOUT_MS_PROPERTY "=" << llkFormat(llkStateTimeoutMs[llkStateD]) << "\n"
729 << LLK_Z_TIMEOUT_MS_PROPERTY "=" << llkFormat(llkStateTimeoutMs[llkStateZ]) << "\n"
730 << LLK_CHECK_MS_PROPERTY "=" << llkFormat(llkCheckMs) << "\n"
731 << LLK_BLACKLIST_PROCESS_PROPERTY "=" << llkFormat(llkBlacklistProcess) << "\n"
732 << LLK_BLACKLIST_PARENT_PROPERTY "=" << llkFormat(llkBlacklistParent) << "\n"
733 << LLK_BLACKLIST_UID_PROPERTY "=" << llkFormat(llkBlacklistUid);
734}
735
736void* llkThread(void* obj) {
737 LOG(INFO) << "started";
738
739 std::string name = std::to_string(::gettid());
740 if (!llkSkipName(name)) {
741 llkBlacklistProcess.emplace(name);
742 }
743 name = static_cast<const char*>(obj);
744 prctl(PR_SET_NAME, name.c_str());
745 if (__predict_false(!llkSkipName(name))) {
746 llkBlacklistProcess.insert(name);
747 }
748 // No longer modifying llkBlacklistProcess.
749 llkRunning = true;
750 llkLogConfig();
751 while (llkRunning) {
752 ::usleep(duration_cast<microseconds>(llkCheck(true)).count());
753 }
754 // NOTREACHED
755 LOG(INFO) << "exiting";
756 return nullptr;
757}
758
759} // namespace
760
761milliseconds llkCheck(bool checkRunning) {
762 if (!llkEnable || (checkRunning != llkRunning)) {
763 return milliseconds::max();
764 }
765
766 // Reset internal watchdog, which is a healthy engineering margin of
767 // double the maximum wait or cycle time for the mainloop that calls us.
768 //
769 // This alarm is effectively the live lock detection of llkd, as
770 // we understandably can not monitor ourselves otherwise.
771 ::alarm(duration_cast<seconds>(llkTimeoutMs * 2).count());
772
773 // kernel jiffy precision fastest acquisition
774 static timespec last;
775 timespec now;
776 ::clock_gettime(CLOCK_MONOTONIC_COARSE, &now);
777 auto ms = llkGetTimespecDiffMs(&last, &now);
778 if (ms < llkCycle) {
779 return llkCycle - ms;
780 }
781 last = now;
782
783 LOG(VERBOSE) << "opendir(\"" << procdir << "\")";
784 if (__predict_false(!llkTopDirectory)) {
785 // gid containing AID_READPROC required
786 llkTopDirectory.reset(procdir);
787 if (__predict_false(!llkTopDirectory)) {
788 // Most likely reason we could be here is a resource limit.
789 // Keep our processing down to a minimum, but not so low that
790 // we do not recover in a timely manner should the issue be
791 // transitory.
792 LOG(DEBUG) << "opendir(\"" << procdir << "\") failed";
793 return llkTimeoutMs;
794 }
795 }
796
797 for (auto& it : tids) {
798 it.second.updated = false;
799 }
800
801 auto prevUpdate = llkUpdate;
802 llkUpdate += ms;
803 ms -= llkCycle;
804 auto myPid = ::getpid();
805 auto myTid = ::gettid();
806 for (auto dp = llkTopDirectory.read(); dp != nullptr; dp = llkTopDirectory.read()) {
807 std::string piddir;
808
809 if (!getValidTidDir(dp, &piddir)) {
810 continue;
811 }
812
813 // Get the process tasks
814 std::string taskdir = piddir + "/task/";
815 int pid = -1;
816 LOG(VERBOSE) << "+opendir(\"" << taskdir << "\")";
817 dir taskDirectory(taskdir);
818 if (__predict_false(!taskDirectory)) {
819 LOG(DEBUG) << "+opendir(\"" << taskdir << "\") failed";
820 }
821 for (auto tp = taskDirectory.read(dir::task, dp); tp != nullptr;
822 tp = taskDirectory.read(dir::task)) {
823 if (!getValidTidDir(tp, &piddir)) {
824 continue;
825 }
826
827 // Get the process stat
828 std::string stat = ReadFile(piddir + "/stat");
829 if (stat.size() == 0) {
830 continue;
831 }
832 unsigned tid = -1;
833 char pdir[TASK_COMM_LEN + 1];
834 char state = '?';
835 unsigned ppid = -1;
836 unsigned utime = -1;
837 unsigned stime = -1;
838 int dummy;
839 pdir[0] = '\0';
840 // tid should not change value
841 auto match = ::sscanf(
842 stat.c_str(),
843 "%u (%" ___STRING(
844 TASK_COMM_LEN) "[^)]) %c %u %*d %*d %*d %*d %*d %*d %*d %*d %*d %u %u %d",
845 &tid, pdir, &state, &ppid, &utime, &stime, &dummy);
846 if (pid == -1) {
847 pid = tid;
848 }
849 LOG(VERBOSE) << "match " << match << ' ' << tid << " (" << pdir << ") " << state << ' '
850 << ppid << " ... " << utime << ' ' << stime << ' ' << dummy;
851 if (match != 7) {
852 continue;
853 }
854
855 auto procp = llkTidLookup(tid);
856 if (procp == nullptr) {
857 procp = llkTidAlloc(tid, pid, ppid, pdir, utime + stime, state);
858 } else {
859 // comm can change ...
860 procp->setComm(pdir);
861 procp->updated = true;
862 // pid/ppid/tid wrap?
863 if (((procp->update != prevUpdate) && (procp->update != llkUpdate)) ||
864 (procp->ppid != ppid) || (procp->pid != pid)) {
865 procp->reset();
866 } else if (procp->time != (utime + stime)) { // secondary ABA.
867 // watching utime+stime granularity jiffy
868 procp->state = '?';
869 }
870 procp->update = llkUpdate;
871 procp->pid = pid;
872 procp->ppid = ppid;
873 procp->time = utime + stime;
874 if (procp->state != state) {
875 procp->count = 0ms;
Mark Salyzynafd66f22018-03-19 15:16:29 -0700876 procp->killed = !llkTestWithKill;
Mark Salyzynf089e142018-02-20 10:47:40 -0800877 procp->state = state;
878 } else {
879 procp->count += llkCycle;
880 }
881 }
882
883 // Filter checks in intuitive order of CPU cost to evaluate
884 // If tid unique continue, if ppid or pid unique break
885
886 if (pid == myPid) {
887 break;
888 }
889 if (!llkIsMonitorState(state)) {
890 continue;
891 }
892 if ((tid == myTid) || llkSkipPid(tid)) {
893 continue;
894 }
895 if (llkSkipPpid(ppid)) {
896 break;
897 }
898
899 if (llkSkipName(procp->getComm())) {
900 continue;
901 }
902 if (llkSkipName(procp->getCmdline())) {
903 break;
904 }
905
906 auto pprocp = llkTidLookup(ppid);
907 if (pprocp == nullptr) {
908 pprocp = llkTidAlloc(ppid, ppid, 0, "", 0, '?');
909 }
910 if ((pprocp != nullptr) && (llkSkipName(pprocp->getComm(), llkBlacklistParent) ||
911 llkSkipName(pprocp->getCmdline(), llkBlacklistParent))) {
912 break;
913 }
914
915 if ((llkBlacklistUid.size() != 0) && llkSkipUid(procp->getUid())) {
916 continue;
917 }
918
919 // ABA mitigation watching last time schedule activity happened
920 llkCheckSchedUpdate(procp, piddir);
921
922 // Can only fall through to here if registered D or Z state !!!
923 if (procp->count < llkStateTimeoutMs[(state == 'Z') ? llkStateZ : llkStateD]) {
924 LOG(VERBOSE) << state << ' ' << llkFormat(procp->count) << ' ' << ppid << "->"
925 << pid << "->" << tid << ' ' << procp->getComm();
926 continue;
927 }
928
929 // We have to kill it to determine difference between live lock
930 // and persistent state blocked on a resource. Is there something
931 // wrong with a process that has no forward scheduling progress in
932 // Z or D? Yes, generally means improper accounting in the
933 // process, but not always ...
934 //
935 // Whomever we hit with a test kill must accept the Android
936 // Aphorism that everything can be burned to the ground and
937 // must survive.
938 if (procp->killed == false) {
939 procp->killed = true;
940 // confirm: re-read uid before committing to a panic.
941 procp->uid = -1;
942 switch (state) {
943 case 'Z': // kill ppid to free up a Zombie
944 // Killing init will kernel panic without diagnostics
945 // so skip right to controlled kernel panic with
946 // diagnostics.
947 if (ppid == initPid) {
948 break;
949 }
950 LOG(WARNING) << "Z " << llkFormat(procp->count) << ' ' << ppid << "->"
951 << pid << "->" << tid << ' ' << procp->getComm() << " [kill]";
952 if ((llkKillOneProcess(pprocp, procp) >= 0) ||
953 (llkKillOneProcess(ppid, procp) >= 0)) {
954 continue;
955 }
956 break;
957
958 case 'D': // kill tid to free up an uninterruptible D
959 // If ABA is doing its job, we would not need or
960 // want the following. Test kill is a Hail Mary
961 // to make absolutely sure there is no forward
962 // scheduling progress. The cost when ABA is
963 // not working is we kill a process that likes to
964 // stay in 'D' state, instead of panicing the
965 // kernel (worse).
966 LOG(WARNING) << "D " << llkFormat(procp->count) << ' ' << pid << "->" << tid
967 << ' ' << procp->getComm() << " [kill]";
968 if ((llkKillOneProcess(llkTidLookup(pid), procp) >= 0) ||
969 (llkKillOneProcess(pid, 'D', tid) >= 0) ||
970 (llkKillOneProcess(procp, procp) >= 0) ||
971 (llkKillOneProcess(tid, 'D', tid) >= 0)) {
972 continue;
973 }
974 break;
975 }
976 }
977 // We are here because we have confirmed kernel live-lock
978 LOG(ERROR) << state << ' ' << llkFormat(procp->count) << ' ' << ppid << "->" << pid
979 << "->" << tid << ' ' << procp->getComm() << " [panic]";
Mark Salyzynafd66f22018-03-19 15:16:29 -0700980 llkPanicKernel(true, tid, (state == 'Z') ? "zombie" : "driver");
Mark Salyzynf089e142018-02-20 10:47:40 -0800981 }
982 LOG(VERBOSE) << "+closedir()";
983 }
984 llkTopDirectory.rewind();
985 LOG(VERBOSE) << "closedir()";
986
987 // garbage collection of old process references
988 for (auto p = tids.begin(); p != tids.end();) {
989 if (!p->second.updated) {
990 IF_ALOG(LOG_VERBOSE, LOG_TAG) {
991 std::string ppidCmdline = llkProcGetName(p->second.ppid, nullptr, nullptr);
992 if (ppidCmdline.size()) {
993 ppidCmdline = "(" + ppidCmdline + ")";
994 }
995 std::string pidCmdline;
996 if (p->second.pid != p->second.tid) {
997 pidCmdline = llkProcGetName(p->second.pid, nullptr, p->second.getCmdline());
998 if (pidCmdline.size()) {
999 pidCmdline = "(" + pidCmdline + ")";
1000 }
1001 }
1002 std::string tidCmdline =
1003 llkProcGetName(p->second.tid, p->second.getComm(), p->second.getCmdline());
1004 if (tidCmdline.size()) {
1005 tidCmdline = "(" + tidCmdline + ")";
1006 }
1007 LOG(VERBOSE) << "thread " << p->second.ppid << ppidCmdline << "->" << p->second.pid
1008 << pidCmdline << "->" << p->second.tid << tidCmdline << " removed";
1009 }
1010 p = tids.erase(p);
1011 } else {
1012 ++p;
1013 }
1014 }
1015 if (__predict_false(tids.empty())) {
1016 llkTopDirectory.reset();
1017 }
1018
1019 llkCycle = llkCheckMs;
1020
1021 timespec end;
1022 ::clock_gettime(CLOCK_MONOTONIC_COARSE, &end);
1023 auto milli = llkGetTimespecDiffMs(&now, &end);
1024 LOG((milli > 10s) ? ERROR : (milli > 1s) ? WARNING : VERBOSE) << "sample " << llkFormat(milli);
1025
1026 // cap to minimum sleep for 1 second since last cycle
1027 if (llkCycle < (ms + 1s)) {
1028 return 1s;
1029 }
1030 return llkCycle - ms;
1031}
1032
1033unsigned llkCheckMilliseconds() {
1034 return duration_cast<milliseconds>(llkCheck()).count();
1035}
1036
1037bool llkInit(const char* threadname) {
1038 llkLowRam = android::base::GetBoolProperty("ro.config.low_ram", false);
Mark Salyzynd035dbb2018-03-26 08:23:00 -07001039 if (!LLK_ENABLE_DEFAULT && android::base::GetBoolProperty("ro.debuggable", false)) {
1040 llkEnable = android::base::GetProperty(LLK_ENABLE_PROPERTY, "eng") == "eng";
1041 khtEnable = android::base::GetProperty(KHT_ENABLE_PROPERTY, "eng") == "eng";
1042 }
Mark Salyzynf089e142018-02-20 10:47:40 -08001043 llkEnable = android::base::GetBoolProperty(LLK_ENABLE_PROPERTY, llkEnable);
1044 if (llkEnable && !llkTopDirectory.reset(procdir)) {
1045 // Most likely reason we could be here is llkd was started
1046 // incorrectly without the readproc permissions. Keep our
1047 // processing down to a minimum.
1048 llkEnable = false;
1049 }
1050 khtEnable = android::base::GetBoolProperty(KHT_ENABLE_PROPERTY, khtEnable);
1051 llkMlockall = android::base::GetBoolProperty(LLK_MLOCKALL_PROPERTY, llkMlockall);
Mark Salyzynafd66f22018-03-19 15:16:29 -07001052 llkTestWithKill = android::base::GetBoolProperty(LLK_KILLTEST_PROPERTY, llkTestWithKill);
Mark Salyzynf089e142018-02-20 10:47:40 -08001053 // if LLK_TIMOUT_MS_PROPERTY was not set, we will use a set
1054 // KHT_TIMEOUT_PROPERTY as co-operative guidance for the default value.
1055 khtTimeout = GetUintProperty(KHT_TIMEOUT_PROPERTY, khtTimeout);
1056 if (khtTimeout == 0s) {
1057 khtTimeout = duration_cast<seconds>(llkTimeoutMs * (1 + LLK_CHECKS_PER_TIMEOUT_DEFAULT) /
1058 LLK_CHECKS_PER_TIMEOUT_DEFAULT);
1059 }
1060 llkTimeoutMs =
1061 khtTimeout * LLK_CHECKS_PER_TIMEOUT_DEFAULT / (1 + LLK_CHECKS_PER_TIMEOUT_DEFAULT);
1062 llkTimeoutMs = GetUintProperty(LLK_TIMEOUT_MS_PROPERTY, llkTimeoutMs);
1063 llkValidate(); // validate llkTimeoutMs, llkCheckMs and llkCycle
1064 llkStateTimeoutMs[llkStateD] = GetUintProperty(LLK_D_TIMEOUT_MS_PROPERTY, llkTimeoutMs);
1065 llkStateTimeoutMs[llkStateZ] = GetUintProperty(LLK_Z_TIMEOUT_MS_PROPERTY, llkTimeoutMs);
1066 llkCheckMs = GetUintProperty(LLK_CHECK_MS_PROPERTY, llkCheckMs);
1067 llkValidate(); // validate all (effectively minus llkTimeoutMs)
1068 std::string defaultBlacklistProcess(
1069 std::to_string(kernelPid) + "," + std::to_string(initPid) + "," +
1070 std::to_string(kthreaddPid) + "," + std::to_string(::getpid()) + "," +
1071 std::to_string(::gettid()) + "," LLK_BLACKLIST_PROCESS_DEFAULT);
1072 if (threadname) {
1073 defaultBlacklistProcess += std::string(",") + threadname;
1074 }
1075 for (int cpu = 1; cpu < get_nprocs_conf(); ++cpu) {
1076 defaultBlacklistProcess += ",[watchdog/" + std::to_string(cpu) + "]";
1077 }
1078 defaultBlacklistProcess =
1079 android::base::GetProperty(LLK_BLACKLIST_PROCESS_PROPERTY, defaultBlacklistProcess);
1080 llkBlacklistProcess = llkSplit(defaultBlacklistProcess);
1081 if (!llkSkipName("[khungtaskd]")) { // ALWAYS ignore as special
1082 llkBlacklistProcess.emplace("[khungtaskd]");
1083 }
1084 llkBlacklistParent = llkSplit(android::base::GetProperty(
1085 LLK_BLACKLIST_PARENT_PROPERTY, std::to_string(kernelPid) + "," + std::to_string(kthreaddPid) +
1086 "," LLK_BLACKLIST_PARENT_DEFAULT));
1087 llkBlacklistUid =
1088 llkSplit(android::base::GetProperty(LLK_BLACKLIST_UID_PROPERTY, LLK_BLACKLIST_UID_DEFAULT));
1089
1090 // internal watchdog
1091 ::signal(SIGALRM, llkAlarmHandler);
1092
1093 // kernel hung task configuration? Otherwise leave it as-is
1094 if (khtEnable) {
1095 // EUID must be AID_ROOT to write to /proc/sys/kernel/ nodes, there
1096 // are no capability overrides. For security reasons we do not want
1097 // to run as AID_ROOT. We may not be able to write them successfully,
1098 // we will try, but the least we can do is read the values back to
1099 // confirm expectations and report whether configured or not.
1100 auto configured = llkWriteStringToFileConfirm(std::to_string(khtTimeout.count()),
1101 "/proc/sys/kernel/hung_task_timeout_secs");
1102 if (configured) {
1103 llkWriteStringToFile("65535", "/proc/sys/kernel/hung_task_warnings");
1104 llkWriteStringToFile("65535", "/proc/sys/kernel/hung_task_check_count");
1105 configured = llkWriteStringToFileConfirm("1", "/proc/sys/kernel/hung_task_panic");
1106 }
1107 if (configured) {
1108 LOG(INFO) << "[khungtaskd] configured";
1109 } else {
1110 LOG(WARNING) << "[khungtaskd] not configurable";
1111 }
1112 }
1113
1114 bool logConfig = true;
1115 if (llkEnable) {
1116 if (llkMlockall &&
1117 // MCL_ONFAULT pins pages as they fault instead of loading
1118 // everything immediately all at once. (Which would be bad,
1119 // because as of this writing, we have a lot of mapped pages we
1120 // never use.) Old kernels will see MCL_ONFAULT and fail with
1121 // EINVAL; we ignore this failure.
1122 //
1123 // N.B. read the man page for mlockall. MCL_CURRENT | MCL_ONFAULT
1124 // pins ⊆ MCL_CURRENT, converging to just MCL_CURRENT as we fault
1125 // in pages.
1126
1127 // CAP_IPC_LOCK required
1128 mlockall(MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT) && (errno != EINVAL)) {
1129 PLOG(WARNING) << "mlockall failed ";
1130 }
1131
1132 if (threadname) {
1133 pthread_attr_t attr;
1134
1135 if (!pthread_attr_init(&attr)) {
1136 sched_param param;
1137
1138 memset(&param, 0, sizeof(param));
1139 pthread_attr_setschedparam(&attr, &param);
1140 pthread_attr_setschedpolicy(&attr, SCHED_BATCH);
1141 if (!pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)) {
1142 pthread_t thread;
1143 if (!pthread_create(&thread, &attr, llkThread, const_cast<char*>(threadname))) {
1144 // wait a second for thread to start
1145 for (auto retry = 50; retry && !llkRunning; --retry) {
1146 ::usleep(20000);
1147 }
1148 logConfig = !llkRunning; // printed in llkd context?
1149 } else {
1150 LOG(ERROR) << "failed to spawn llkd thread";
1151 }
1152 } else {
1153 LOG(ERROR) << "failed to detach llkd thread";
1154 }
1155 pthread_attr_destroy(&attr);
1156 } else {
1157 LOG(ERROR) << "failed to allocate attibutes for llkd thread";
1158 }
1159 }
1160 } else {
1161 LOG(DEBUG) << "[khungtaskd] left unconfigured";
1162 }
1163 if (logConfig) {
1164 llkLogConfig();
1165 }
1166
1167 return llkEnable;
1168}