blob: 42602e9ee08100f90f22fd1a63e814787080076f [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>
Woody Line5a09d82020-04-22 10:18:59 +080044#include <vector>
Mark Salyzynf089e142018-02-20 10:47:40 -080045
46#include <android-base/file.h>
47#include <android-base/logging.h>
48#include <android-base/parseint.h>
49#include <android-base/properties.h>
50#include <android-base/strings.h>
51#include <cutils/android_get_control_file.h>
52#include <log/log_main.h>
53
54#define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x)))
55
56#define TASK_COMM_LEN 16 // internal kernel, not uapi, from .../linux/include/linux/sched.h
57
58using namespace std::chrono_literals;
59using namespace std::chrono;
Mark Salyzyn52e54a62018-08-07 08:13:13 -070060using namespace std::literals;
Mark Salyzynf089e142018-02-20 10:47:40 -080061
62namespace {
63
64constexpr pid_t kernelPid = 0;
65constexpr pid_t initPid = 1;
66constexpr pid_t kthreaddPid = 2;
67
68constexpr char procdir[] = "/proc/";
69
70// Configuration
71milliseconds llkUpdate; // last check ms signature
72milliseconds llkCycle; // ms to next thread check
73bool llkEnable = LLK_ENABLE_DEFAULT; // llk daemon enabled
74bool llkRunning = false; // thread is running
75bool llkMlockall = LLK_MLOCKALL_DEFAULT; // run mlocked
Mark Salyzynafd66f22018-03-19 15:16:29 -070076bool llkTestWithKill = LLK_KILLTEST_DEFAULT; // issue test kills
Mark Salyzynf089e142018-02-20 10:47:40 -080077milliseconds llkTimeoutMs = LLK_TIMEOUT_MS_DEFAULT; // default timeout
Mark Salyzyn96505fa2018-08-07 08:13:13 -070078enum { // enum of state indexes
79 llkStateD, // Persistent 'D' state
80 llkStateZ, // Persistent 'Z' state
81#ifdef __PTRACE_ENABLED__ // Extra privileged states
82 llkStateStack, // stack signature
83#endif // End of extra privilege
84 llkNumStates, // Maxumum number of states
85}; // state indexes
Mark Salyzynf089e142018-02-20 10:47:40 -080086milliseconds llkStateTimeoutMs[llkNumStates]; // timeout override for each detection state
87milliseconds llkCheckMs; // checking interval to inspect any
88 // persistent live-locked states
89bool llkLowRam; // ro.config.low_ram
Mark Salyzynbd7c8562018-10-31 10:02:08 -070090bool llkEnableSysrqT = LLK_ENABLE_SYSRQ_T_DEFAULT; // sysrq stack trace dump
Mark Salyzynf089e142018-02-20 10:47:40 -080091bool khtEnable = LLK_ENABLE_DEFAULT; // [khungtaskd] panic
92// [khungtaskd] should have a timeout beyond the granularity of llkTimeoutMs.
93// Provides a wide angle of margin b/c khtTimeout is also its granularity.
94seconds khtTimeout = duration_cast<seconds>(llkTimeoutMs * (1 + LLK_CHECKS_PER_TIMEOUT_DEFAULT) /
95 LLK_CHECKS_PER_TIMEOUT_DEFAULT);
Mark Salyzyn96505fa2018-08-07 08:13:13 -070096#ifdef __PTRACE_ENABLED__
97// list of stack symbols to search for persistence.
98std::unordered_set<std::string> llkCheckStackSymbols;
99#endif
Mark Salyzynf089e142018-02-20 10:47:40 -0800100
Mark Salyzyn6d9e5152020-05-13 06:25:20 -0700101// Ignorelist variables, initialized with comma separated lists of high false
Mark Salyzynf089e142018-02-20 10:47:40 -0800102// positive and/or dangerous references, e.g. without self restart, for pid,
103// ppid, name and uid:
104
105// list of pids, or tids or names to skip. kernel pid (0), init pid (1),
106// [kthreadd] pid (2), ourselves, "init", "[kthreadd]", "lmkd", "llkd" or
107// combinations of watchdogd in kernel and user space.
Mark Salyzyn6d9e5152020-05-13 06:25:20 -0700108std::unordered_set<std::string> llkIgnorelistProcess;
Mark Salyzynf089e142018-02-20 10:47:40 -0800109// list of parent pids, comm or cmdline names to skip. default:
110// kernel pid (0), [kthreadd] (2), or ourselves, enforced and implied
Mark Salyzyn6d9e5152020-05-13 06:25:20 -0700111std::unordered_set<std::string> llkIgnorelistParent;
Mark Salyzynda2aeb02019-01-02 08:27:22 -0800112// list of parent and target processes to skip. default:
113// adbd *and* [setsid]
Mark Salyzyn6d9e5152020-05-13 06:25:20 -0700114std::unordered_map<std::string, std::unordered_set<std::string>> llkIgnorelistParentAndChild;
Mark Salyzynf089e142018-02-20 10:47:40 -0800115// list of uids, and uid names, to skip, default nothing
Mark Salyzyn6d9e5152020-05-13 06:25:20 -0700116std::unordered_set<std::string> llkIgnorelistUid;
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700117#ifdef __PTRACE_ENABLED__
Janis Danisevskis02843742021-03-15 09:17:58 -0700118// list of names to skip stack checking. "init", "lmkd", "llkd", "keystore",
119// "keystore2", or "logd" (if not userdebug).
Mark Salyzyn6d9e5152020-05-13 06:25:20 -0700120std::unordered_set<std::string> llkIgnorelistStack;
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700121#endif
Mark Salyzynf089e142018-02-20 10:47:40 -0800122
123class dir {
124 public:
125 enum level { proc, task, numLevels };
126
127 private:
128 int fd;
129 size_t available_bytes;
130 dirent* next;
131 // each directory level picked to be just north of 4K in size
132 static constexpr size_t buffEntries = 15;
133 static dirent buff[numLevels][buffEntries];
134
135 bool fill(enum level index) {
136 if (index >= numLevels) return false;
137 if (available_bytes != 0) return true;
138 if (__predict_false(fd < 0)) return false;
139 // getdents64 has no libc wrapper
140 auto rc = TEMP_FAILURE_RETRY(syscall(__NR_getdents64, fd, buff[index], sizeof(buff[0]), 0));
141 if (rc <= 0) return false;
142 available_bytes = rc;
143 next = buff[index];
144 return true;
145 }
146
147 public:
148 dir() : fd(-1), available_bytes(0), next(nullptr) {}
149
150 explicit dir(const char* directory)
151 : fd(__predict_true(directory != nullptr)
152 ? ::open(directory, O_CLOEXEC | O_DIRECTORY | O_RDONLY)
153 : -1),
154 available_bytes(0),
155 next(nullptr) {}
156
157 explicit dir(const std::string&& directory)
158 : fd(::open(directory.c_str(), O_CLOEXEC | O_DIRECTORY | O_RDONLY)),
159 available_bytes(0),
160 next(nullptr) {}
161
162 explicit dir(const std::string& directory)
163 : fd(::open(directory.c_str(), O_CLOEXEC | O_DIRECTORY | O_RDONLY)),
164 available_bytes(0),
165 next(nullptr) {}
166
167 // Don't need any copy or move constructors.
168 explicit dir(const dir& c) = delete;
169 explicit dir(dir& c) = delete;
170 explicit dir(dir&& c) = delete;
171
172 ~dir() {
173 if (fd >= 0) {
174 ::close(fd);
175 }
176 }
177
178 operator bool() const { return fd >= 0; }
179
180 void reset(void) {
181 if (fd >= 0) {
182 ::close(fd);
183 fd = -1;
184 available_bytes = 0;
185 next = nullptr;
186 }
187 }
188
189 dir& reset(const char* directory) {
190 reset();
191 // available_bytes will _always_ be zero here as its value is
192 // intimately tied to fd < 0 or not.
193 fd = ::open(directory, O_CLOEXEC | O_DIRECTORY | O_RDONLY);
194 return *this;
195 }
196
197 void rewind(void) {
198 if (fd >= 0) {
199 ::lseek(fd, off_t(0), SEEK_SET);
200 available_bytes = 0;
201 next = nullptr;
202 }
203 }
204
205 dirent* read(enum level index = proc, dirent* def = nullptr) {
206 if (!fill(index)) return def;
207 auto ret = next;
208 available_bytes -= next->d_reclen;
209 next = reinterpret_cast<dirent*>(reinterpret_cast<char*>(next) + next->d_reclen);
210 return ret;
211 }
212} llkTopDirectory;
213
214dirent dir::buff[dir::numLevels][dir::buffEntries];
215
216// helper functions
217
218bool llkIsMissingExeLink(pid_t tid) {
219 char c;
220 // CAP_SYS_PTRACE is required to prevent ret == -1, but ENOENT is signal
221 auto ret = ::readlink((procdir + std::to_string(tid) + "/exe").c_str(), &c, sizeof(c));
222 return (ret == -1) && (errno == ENOENT);
223}
224
225// Common routine where caller accepts empty content as error/passthrough.
226// Reduces the churn of reporting read errors in the callers.
227std::string ReadFile(std::string&& path) {
228 std::string content;
229 if (!android::base::ReadFileToString(path, &content)) {
230 PLOG(DEBUG) << "Read " << path << " failed";
231 content = "";
232 }
233 return content;
234}
235
236std::string llkProcGetName(pid_t tid, const char* node = "/cmdline") {
237 std::string content = ReadFile(procdir + std::to_string(tid) + node);
238 static constexpr char needles[] = " \t\r\n"; // including trailing nul
239 auto pos = content.find_first_of(needles, 0, sizeof(needles));
240 if (pos != std::string::npos) {
241 content.erase(pos);
242 }
243 return content;
244}
245
246uid_t llkProcGetUid(pid_t tid) {
247 // Get the process' uid. The following read from /status is admittedly
248 // racy, prone to corruption due to shape-changes. The consequences are
249 // not catastrophic as we sample a few times before taking action.
250 //
251 // If /loginuid worked on reliably, or on Android (all tasks report -1)...
252 // Android lmkd causes /cgroup to contain memory:/<dom>/uid_<uid>/pid_<pid>
253 // which is tighter, but also not reliable.
254 std::string content = ReadFile(procdir + std::to_string(tid) + "/status");
255 static constexpr char Uid[] = "\nUid:";
256 auto pos = content.find(Uid);
257 if (pos == std::string::npos) {
258 return -1;
259 }
260 pos += ::strlen(Uid);
261 while ((pos < content.size()) && ::isblank(content[pos])) {
262 ++pos;
263 }
264 content.erase(0, pos);
265 for (pos = 0; (pos < content.size()) && ::isdigit(content[pos]); ++pos) {
266 ;
267 }
268 // Content of form 'Uid: 0 0 0 0', newline is error
269 if ((pos >= content.size()) || !::isblank(content[pos])) {
270 return -1;
271 }
272 content.erase(pos);
273 uid_t ret;
Tom Cherrye0bc5a92018-10-05 14:29:47 -0700274 if (!android::base::ParseUint(content, &ret, uid_t(0))) {
Mark Salyzynf089e142018-02-20 10:47:40 -0800275 return -1;
276 }
277 return ret;
278}
279
280struct proc {
281 pid_t tid; // monitored thread id (in Z or D state).
282 nanoseconds schedUpdate; // /proc/<tid>/sched "se.avg.lastUpdateTime",
283 uint64_t nrSwitches; // /proc/<tid>/sched "nr_switches" for
284 // refined ABA problem detection, determine
285 // forward scheduling progress.
286 milliseconds update; // llkUpdate millisecond signature of last.
287 milliseconds count; // duration in state.
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700288#ifdef __PTRACE_ENABLED__ // Privileged state checking
289 milliseconds count_stack; // duration where stack is stagnant.
290#endif // End privilege
Mark Salyzynf089e142018-02-20 10:47:40 -0800291 pid_t pid; // /proc/<pid> before iterating through
292 // /proc/<pid>/task/<tid> for threads.
293 pid_t ppid; // /proc/<tid>/stat field 4 parent pid.
294 uid_t uid; // /proc/<tid>/status Uid: field.
295 unsigned time; // sum of /proc/<tid>/stat field 14 utime &
296 // 15 stime for coarse ABA problem detection.
297 std::string cmdline; // cached /cmdline content
298 char state; // /proc/<tid>/stat field 3: Z or D
299 // (others we do not monitor: S, R, T or ?)
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700300#ifdef __PTRACE_ENABLED__ // Privileged state checking
301 char stack; // index in llkCheckStackSymbols for matches
302#endif // and with maximum index PROP_VALUE_MAX/2.
Mark Salyzynf089e142018-02-20 10:47:40 -0800303 char comm[TASK_COMM_LEN + 3]; // space for adding '[' and ']'
304 bool exeMissingValid; // exeMissing has been cached
305 bool cmdlineValid; // cmdline has been cached
306 bool updated; // cleared before monitoring pass.
307 bool killed; // sent a kill to this thread, next panic...
Marco Ballesio38c735e2019-12-27 13:43:29 -0800308 bool frozen; // process is in frozen cgroup.
Mark Salyzynf089e142018-02-20 10:47:40 -0800309
310 void setComm(const char* _comm) { strncpy(comm + 1, _comm, sizeof(comm) - 2); }
311
Marco Ballesio38c735e2019-12-27 13:43:29 -0800312 void setFrozen(bool _frozen) { frozen = _frozen; }
313
314 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 -0800315 : tid(tid),
316 schedUpdate(0),
317 nrSwitches(0),
318 update(llkUpdate),
Mark Salyzynacecaf72018-08-10 08:15:57 -0700319 count(0ms),
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700320#ifdef __PTRACE_ENABLED__
321 count_stack(0ms),
322#endif
Mark Salyzynf089e142018-02-20 10:47:40 -0800323 pid(pid),
324 ppid(ppid),
325 uid(-1),
326 time(time),
327 state(state),
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700328#ifdef __PTRACE_ENABLED__
329 stack(-1),
330#endif
Mark Salyzynf089e142018-02-20 10:47:40 -0800331 exeMissingValid(false),
332 cmdlineValid(false),
333 updated(true),
Marco Ballesio38c735e2019-12-27 13:43:29 -0800334 killed(!llkTestWithKill),
335 frozen(frozen) {
Mark Salyzynf089e142018-02-20 10:47:40 -0800336 memset(comm, '\0', sizeof(comm));
337 setComm(_comm);
338 }
339
340 const char* getComm(void) {
341 if (comm[1] == '\0') { // comm Valid?
342 strncpy(comm + 1, llkProcGetName(tid, "/comm").c_str(), sizeof(comm) - 2);
343 }
344 if (!exeMissingValid) {
345 if (llkIsMissingExeLink(tid)) {
346 comm[0] = '[';
347 }
348 exeMissingValid = true;
349 }
350 size_t len = strlen(comm + 1);
351 if (__predict_true(len < (sizeof(comm) - 1))) {
352 if (comm[0] == '[') {
353 if ((comm[len] != ']') && __predict_true(len < (sizeof(comm) - 2))) {
354 comm[++len] = ']';
355 comm[++len] = '\0';
356 }
357 } else {
358 if (comm[len] == ']') {
359 comm[len] = '\0';
360 }
361 }
362 }
363 return &comm[comm[0] != '['];
364 }
365
366 const char* getCmdline(void) {
367 if (!cmdlineValid) {
368 cmdline = llkProcGetName(tid);
369 cmdlineValid = true;
370 }
371 return cmdline.c_str();
372 }
373
374 uid_t getUid(void) {
375 if (uid <= 0) { // Churn on root user, because most likely to setuid()
376 uid = llkProcGetUid(tid);
377 }
378 return uid;
379 }
380
Marco Ballesio38c735e2019-12-27 13:43:29 -0800381 bool isFrozen() { return frozen; }
382
Mark Salyzynf089e142018-02-20 10:47:40 -0800383 void reset(void) { // reset cache, if we detected pid rollover
384 uid = -1;
385 state = '?';
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700386#ifdef __PTRACE_ENABLED__
387 count_stack = 0ms;
388 stack = -1;
389#endif
Mark Salyzynf089e142018-02-20 10:47:40 -0800390 cmdline = "";
391 comm[0] = '\0';
392 exeMissingValid = false;
393 cmdlineValid = false;
394 }
395};
396
397std::unordered_map<pid_t, proc> tids;
398
399// Check range and setup defaults, in order of propagation:
400// llkTimeoutMs
401// llkCheckMs
402// ...
403// KISS to keep it all self-contained, and called multiple times as parameters
404// are interpreted so that defaults, llkCheckMs and llkCycle make sense.
405void llkValidate() {
406 if (llkTimeoutMs == 0ms) {
407 llkTimeoutMs = LLK_TIMEOUT_MS_DEFAULT;
408 }
409 llkTimeoutMs = std::max(llkTimeoutMs, LLK_TIMEOUT_MS_MINIMUM);
410 if (llkCheckMs == 0ms) {
411 llkCheckMs = llkTimeoutMs / LLK_CHECKS_PER_TIMEOUT_DEFAULT;
412 }
413 llkCheckMs = std::min(llkCheckMs, llkTimeoutMs);
414
415 for (size_t state = 0; state < ARRAY_SIZE(llkStateTimeoutMs); ++state) {
416 if (llkStateTimeoutMs[state] == 0ms) {
417 llkStateTimeoutMs[state] = llkTimeoutMs;
418 }
419 llkStateTimeoutMs[state] =
420 std::min(std::max(llkStateTimeoutMs[state], LLK_TIMEOUT_MS_MINIMUM), llkTimeoutMs);
421 llkCheckMs = std::min(llkCheckMs, llkStateTimeoutMs[state]);
422 }
423
424 llkCheckMs = std::max(llkCheckMs, LLK_CHECK_MS_MINIMUM);
425 if (llkCycle == 0ms) {
426 llkCycle = llkCheckMs;
427 }
428 llkCycle = std::min(llkCycle, llkCheckMs);
429}
430
431milliseconds llkGetTimespecDiffMs(timespec* from, timespec* to) {
432 return duration_cast<milliseconds>(seconds(to->tv_sec - from->tv_sec)) +
433 duration_cast<milliseconds>(nanoseconds(to->tv_nsec - from->tv_nsec));
434}
435
436std::string llkProcGetName(pid_t tid, const char* comm, const char* cmdline) {
437 if ((cmdline != nullptr) && (*cmdline != '\0')) {
438 return cmdline;
439 }
440 if ((comm != nullptr) && (*comm != '\0')) {
441 return comm;
442 }
443
444 // UNLIKELY! Here because killed before we kill it?
445 // Assume change is afoot, do not call llkTidAlloc
446
447 // cmdline ?
448 std::string content = llkProcGetName(tid);
449 if (content.size() != 0) {
450 return content;
451 }
452 // Comm instead?
453 content = llkProcGetName(tid, "/comm");
454 if (llkIsMissingExeLink(tid) && (content.size() != 0)) {
455 return '[' + content + ']';
456 }
457 return content;
458}
459
460int llkKillOneProcess(pid_t pid, char state, pid_t tid, const char* tcomm = nullptr,
461 const char* tcmdline = nullptr, const char* pcomm = nullptr,
462 const char* pcmdline = nullptr) {
463 std::string forTid;
464 if (tid != pid) {
465 forTid = " for '" + llkProcGetName(tid, tcomm, tcmdline) + "' (" + std::to_string(tid) + ")";
466 }
467 LOG(INFO) << "Killing '" << llkProcGetName(pid, pcomm, pcmdline) << "' (" << pid
468 << ") to check forward scheduling progress in " << state << " state" << forTid;
469 // CAP_KILL required
470 errno = 0;
471 auto r = ::kill(pid, SIGKILL);
472 if (r) {
473 PLOG(ERROR) << "kill(" << pid << ")=" << r << ' ';
474 }
475
476 return r;
477}
478
479// Kill one process
480int llkKillOneProcess(pid_t pid, proc* tprocp) {
481 return llkKillOneProcess(pid, tprocp->state, tprocp->tid, tprocp->getComm(),
482 tprocp->getCmdline());
483}
484
485// Kill one process specified by kprocp
486int llkKillOneProcess(proc* kprocp, proc* tprocp) {
487 if (kprocp == nullptr) {
488 return -2;
489 }
490
491 return llkKillOneProcess(kprocp->tid, tprocp->state, tprocp->tid, tprocp->getComm(),
492 tprocp->getCmdline(), kprocp->getComm(), kprocp->getCmdline());
493}
494
495// Acquire file descriptor from environment, or open and cache it.
496// NB: cache is unnecessary in our current context, pedantically
497// required to prevent leakage of file descriptors in the future.
498int llkFileToWriteFd(const std::string& file) {
499 static std::unordered_map<std::string, int> cache;
500 auto search = cache.find(file);
501 if (search != cache.end()) return search->second;
502 auto fd = android_get_control_file(file.c_str());
503 if (fd >= 0) return fd;
504 fd = TEMP_FAILURE_RETRY(::open(file.c_str(), O_WRONLY | O_CLOEXEC));
505 if (fd >= 0) cache.emplace(std::make_pair(file, fd));
506 return fd;
507}
508
509// Wrap android::base::WriteStringToFile to use android_get_control_file.
510bool llkWriteStringToFile(const std::string& string, const std::string& file) {
511 auto fd = llkFileToWriteFd(file);
512 if (fd < 0) return false;
513 return android::base::WriteStringToFd(string, fd);
514}
515
516bool llkWriteStringToFileConfirm(const std::string& string, const std::string& file) {
517 auto fd = llkFileToWriteFd(file);
518 auto ret = (fd < 0) ? false : android::base::WriteStringToFd(string, fd);
519 std::string content;
520 if (!android::base::ReadFileToString(file, &content)) return ret;
521 return android::base::Trim(content) == string;
522}
523
Mark Salyzynfbc3a752018-12-04 10:30:45 -0800524void llkPanicKernel(bool dump, pid_t tid, const char* state, const std::string& message = "") {
Mark Salyzyn3c3b14d2018-10-31 10:38:15 -0700525 if (!message.empty()) LOG(ERROR) << message;
Mark Salyzynf089e142018-02-20 10:47:40 -0800526 auto sysrqTriggerFd = llkFileToWriteFd("/proc/sysrq-trigger");
527 if (sysrqTriggerFd < 0) {
528 // DYB
529 llkKillOneProcess(initPid, 'R', tid);
530 // The answer to life, the universe and everything
531 ::exit(42);
532 // NOTREACHED
Mark Salyzynfbc3a752018-12-04 10:30:45 -0800533 return;
Mark Salyzynf089e142018-02-20 10:47:40 -0800534 }
Mark Salyzyn16649d22019-01-09 07:49:21 -0800535 // Wish could ::sync() here, if storage is locked up, we will not continue.
Mark Salyzynf089e142018-02-20 10:47:40 -0800536 if (dump) {
537 // Show all locks that are held
538 android::base::WriteStringToFd("d", sysrqTriggerFd);
Mark Salyzyn53e782d2018-10-31 16:03:45 -0700539 // Show all waiting tasks
540 android::base::WriteStringToFd("w", sysrqTriggerFd);
Mark Salyzynf089e142018-02-20 10:47:40 -0800541 // This can trigger hardware watchdog, that is somewhat _ok_.
542 // But useless if pstore configured for <256KB, low ram devices ...
Mark Salyzynbd7c8562018-10-31 10:02:08 -0700543 if (llkEnableSysrqT) {
Mark Salyzynf089e142018-02-20 10:47:40 -0800544 android::base::WriteStringToFd("t", sysrqTriggerFd);
Mark Salyzyn53e782d2018-10-31 16:03:45 -0700545 // Show all locks that are held (in case 't' overflows ramoops)
546 android::base::WriteStringToFd("d", sysrqTriggerFd);
547 // Show all waiting tasks (in case 't' overflows ramoops)
548 android::base::WriteStringToFd("w", sysrqTriggerFd);
Mark Salyzynf089e142018-02-20 10:47:40 -0800549 }
550 ::usleep(200000); // let everything settle
551 }
Mark Salyzyn3c3b14d2018-10-31 10:38:15 -0700552 // SysRq message matches kernel format, and propagates through bootstat
553 // ultimately to the boot reason into panic,livelock,<state>.
554 llkWriteStringToFile(message + (message.empty() ? "" : "\n") +
555 "SysRq : Trigger a crash : 'livelock,"s + state + "'\n",
556 "/dev/kmsg");
Mark Salyzynfbc3a752018-12-04 10:30:45 -0800557 // Because panic is such a serious thing to do, let us
558 // make sure that the tid being inspected still exists!
559 auto piddir = procdir + std::to_string(tid) + "/stat";
560 if (access(piddir.c_str(), F_OK) != 0) {
561 PLOG(WARNING) << piddir;
562 return;
563 }
Mark Salyzynf089e142018-02-20 10:47:40 -0800564 android::base::WriteStringToFd("c", sysrqTriggerFd);
565 // NOTREACHED
566 // DYB
567 llkKillOneProcess(initPid, 'R', tid);
568 // I sat at my desk, stared into the garden and thought '42 will do'.
569 // I typed it out. End of story
570 ::exit(42);
571 // NOTREACHED
572}
573
574void llkAlarmHandler(int) {
Mark Salyzynb3418a22018-11-19 15:24:03 -0800575 LOG(FATAL) << "alarm";
576 // NOTREACHED
577 llkPanicKernel(true, ::getpid(), "alarm");
Mark Salyzynf089e142018-02-20 10:47:40 -0800578}
579
580milliseconds GetUintProperty(const std::string& key, milliseconds def) {
581 return milliseconds(android::base::GetUintProperty(key, static_cast<uint64_t>(def.count()),
582 static_cast<uint64_t>(def.max().count())));
583}
584
585seconds GetUintProperty(const std::string& key, seconds def) {
586 return seconds(android::base::GetUintProperty(key, static_cast<uint64_t>(def.count()),
587 static_cast<uint64_t>(def.max().count())));
588}
589
590proc* llkTidLookup(pid_t tid) {
591 auto search = tids.find(tid);
592 if (search == tids.end()) {
593 return nullptr;
594 }
595 return &search->second;
596}
597
598void llkTidRemove(pid_t tid) {
599 tids.erase(tid);
600}
601
Marco Ballesio38c735e2019-12-27 13:43:29 -0800602proc* llkTidAlloc(pid_t tid, pid_t pid, pid_t ppid, const char* comm, int time, char state,
603 bool frozen) {
604 auto it = tids.emplace(std::make_pair(tid, proc(tid, pid, ppid, comm, time, state, frozen)));
Mark Salyzynf089e142018-02-20 10:47:40 -0800605 return &it.first->second;
606}
607
608std::string llkFormat(milliseconds ms) {
609 auto sec = duration_cast<seconds>(ms);
610 std::ostringstream s;
611 s << sec.count() << '.';
612 auto f = s.fill('0');
613 auto w = s.width(3);
614 s << std::right << (ms - sec).count();
615 s.width(w);
616 s.fill(f);
617 s << 's';
618 return s.str();
619}
620
621std::string llkFormat(seconds s) {
622 return std::to_string(s.count()) + 's';
623}
624
625std::string llkFormat(bool flag) {
626 return flag ? "true" : "false";
627}
628
Mark Salyzyn6d9e5152020-05-13 06:25:20 -0700629std::string llkFormat(const std::unordered_set<std::string>& ignorelist) {
Mark Salyzynf089e142018-02-20 10:47:40 -0800630 std::string ret;
Mark Salyzyn6d9e5152020-05-13 06:25:20 -0700631 for (const auto& entry : ignorelist) {
Mark Salyzyn8a5f0812019-01-03 08:39:38 -0800632 if (!ret.empty()) ret += ",";
Mark Salyzynf089e142018-02-20 10:47:40 -0800633 ret += entry;
634 }
635 return ret;
636}
637
Mark Salyzynda2aeb02019-01-02 08:27:22 -0800638std::string llkFormat(
Mark Salyzyn6d9e5152020-05-13 06:25:20 -0700639 const std::unordered_map<std::string, std::unordered_set<std::string>>& ignorelist,
Mark Salyzynda2aeb02019-01-02 08:27:22 -0800640 bool leading_comma = false) {
641 std::string ret;
Mark Salyzyn6d9e5152020-05-13 06:25:20 -0700642 for (const auto& entry : ignorelist) {
Mark Salyzynda2aeb02019-01-02 08:27:22 -0800643 for (const auto& target : entry.second) {
644 if (leading_comma || !ret.empty()) ret += ",";
645 ret += entry.first + "&" + target;
646 }
647 }
648 return ret;
649}
650
Mark Salyzyn8a5f0812019-01-03 08:39:38 -0800651// This function parses the properties as a list, incorporating the supplied
652// default. A leading comma separator means preserve the defaults and add
653// entries (with an optional leading + sign), or removes entries with a leading
654// - sign.
655//
Mark Salyzynf089e142018-02-20 10:47:40 -0800656// We only officially support comma separators, but wetware being what they
657// are will take some liberty and I do not believe they should be punished.
Mark Salyzyn8a5f0812019-01-03 08:39:38 -0800658std::unordered_set<std::string> llkSplit(const std::string& prop, const std::string& def) {
659 auto s = android::base::GetProperty(prop, def);
660 constexpr char separators[] = ", \t:;";
661 if (!s.empty() && (s != def) && strchr(separators, s[0])) s = def + s;
662
Mark Salyzynf089e142018-02-20 10:47:40 -0800663 std::unordered_set<std::string> result;
664
Mark Salyzynacecaf72018-08-10 08:15:57 -0700665 // Special case, allow boolean false to empty the list, otherwise expected
666 // source of input from android::base::GetProperty will supply the default
667 // value on empty content in the property.
668 if (s == "false") return result;
669
Mark Salyzynf089e142018-02-20 10:47:40 -0800670 size_t base = 0;
Mark Salyzynacecaf72018-08-10 08:15:57 -0700671 while (s.size() > base) {
Mark Salyzyn8a5f0812019-01-03 08:39:38 -0800672 auto found = s.find_first_of(separators, base);
673 // Only emplace unique content, empty entries are not an option
674 if (found != base) {
675 switch (s[base]) {
676 case '-':
677 ++base;
678 if (base >= s.size()) break;
679 if (base != found) {
680 auto have = result.find(s.substr(base, found - base));
681 if (have != result.end()) result.erase(have);
682 }
683 break;
684 case '+':
685 ++base;
686 if (base >= s.size()) break;
687 if (base == found) break;
688 // FALLTHRU (for gcc, lint, pcc, etc; following for clang)
689 FALLTHROUGH_INTENDED;
690 default:
691 result.emplace(s.substr(base, found - base));
692 break;
693 }
694 }
Mark Salyzynf089e142018-02-20 10:47:40 -0800695 if (found == s.npos) break;
696 base = found + 1;
697 }
698 return result;
699}
700
701bool llkSkipName(const std::string& name,
Mark Salyzyn6d9e5152020-05-13 06:25:20 -0700702 const std::unordered_set<std::string>& ignorelist = llkIgnorelistProcess) {
703 if (name.empty() || ignorelist.empty()) return false;
Mark Salyzynf089e142018-02-20 10:47:40 -0800704
Mark Salyzyn6d9e5152020-05-13 06:25:20 -0700705 return ignorelist.find(name) != ignorelist.end();
Mark Salyzynf089e142018-02-20 10:47:40 -0800706}
707
Mark Salyzyn8a5f0812019-01-03 08:39:38 -0800708bool llkSkipProc(proc* procp,
Mark Salyzyn6d9e5152020-05-13 06:25:20 -0700709 const std::unordered_set<std::string>& ignorelist = llkIgnorelistProcess) {
Mark Salyzyn8a5f0812019-01-03 08:39:38 -0800710 if (!procp) return false;
Mark Salyzyn6d9e5152020-05-13 06:25:20 -0700711 if (llkSkipName(std::to_string(procp->pid), ignorelist)) return true;
712 if (llkSkipName(procp->getComm(), ignorelist)) return true;
713 if (llkSkipName(procp->getCmdline(), ignorelist)) return true;
714 if (llkSkipName(android::base::Basename(procp->getCmdline()), ignorelist)) return true;
Mark Salyzyn8a5f0812019-01-03 08:39:38 -0800715 return false;
716}
717
Mark Salyzynda2aeb02019-01-02 08:27:22 -0800718const std::unordered_set<std::string>& llkSkipName(
719 const std::string& name,
Mark Salyzyn6d9e5152020-05-13 06:25:20 -0700720 const std::unordered_map<std::string, std::unordered_set<std::string>>& ignorelist) {
Mark Salyzynda2aeb02019-01-02 08:27:22 -0800721 static const std::unordered_set<std::string> empty;
Mark Salyzyn6d9e5152020-05-13 06:25:20 -0700722 if (name.empty() || ignorelist.empty()) return empty;
723 auto found = ignorelist.find(name);
724 if (found == ignorelist.end()) return empty;
Mark Salyzynda2aeb02019-01-02 08:27:22 -0800725 return found->second;
726}
727
728bool llkSkipPproc(proc* pprocp, proc* procp,
729 const std::unordered_map<std::string, std::unordered_set<std::string>>&
Mark Salyzyn6d9e5152020-05-13 06:25:20 -0700730 ignorelist = llkIgnorelistParentAndChild) {
731 if (!pprocp || !procp || ignorelist.empty()) return false;
732 if (llkSkipProc(procp, llkSkipName(std::to_string(pprocp->pid), ignorelist))) return true;
733 if (llkSkipProc(procp, llkSkipName(pprocp->getComm(), ignorelist))) return true;
734 if (llkSkipProc(procp, llkSkipName(pprocp->getCmdline(), ignorelist))) return true;
Mark Salyzynda2aeb02019-01-02 08:27:22 -0800735 return llkSkipProc(procp,
Mark Salyzyn6d9e5152020-05-13 06:25:20 -0700736 llkSkipName(android::base::Basename(pprocp->getCmdline()), ignorelist));
Mark Salyzynda2aeb02019-01-02 08:27:22 -0800737}
738
Mark Salyzynf089e142018-02-20 10:47:40 -0800739bool llkSkipPid(pid_t pid) {
Mark Salyzyn6d9e5152020-05-13 06:25:20 -0700740 return llkSkipName(std::to_string(pid), llkIgnorelistProcess);
Mark Salyzynf089e142018-02-20 10:47:40 -0800741}
742
743bool llkSkipPpid(pid_t ppid) {
Mark Salyzyn6d9e5152020-05-13 06:25:20 -0700744 return llkSkipName(std::to_string(ppid), llkIgnorelistParent);
Mark Salyzynf089e142018-02-20 10:47:40 -0800745}
746
747bool llkSkipUid(uid_t uid) {
748 // Match by number?
Mark Salyzyn6d9e5152020-05-13 06:25:20 -0700749 if (llkSkipName(std::to_string(uid), llkIgnorelistUid)) {
Mark Salyzynf089e142018-02-20 10:47:40 -0800750 return true;
751 }
752
753 // Match by name?
754 auto pwd = ::getpwuid(uid);
755 return (pwd != nullptr) && __predict_true(pwd->pw_name != nullptr) &&
Mark Salyzyn6d9e5152020-05-13 06:25:20 -0700756 __predict_true(pwd->pw_name[0] != '\0') && llkSkipName(pwd->pw_name, llkIgnorelistUid);
Mark Salyzynf089e142018-02-20 10:47:40 -0800757}
758
759bool getValidTidDir(dirent* dp, std::string* piddir) {
760 if (!::isdigit(dp->d_name[0])) {
761 return false;
762 }
763
764 // Corner case can not happen in reality b/c of above ::isdigit check
765 if (__predict_false(dp->d_type != DT_DIR)) {
766 if (__predict_false(dp->d_type == DT_UNKNOWN)) { // can't b/c procfs
767 struct stat st;
768 *piddir = procdir;
769 *piddir += dp->d_name;
770 return (lstat(piddir->c_str(), &st) == 0) && (st.st_mode & S_IFDIR);
771 }
772 return false;
773 }
774
775 *piddir = procdir;
776 *piddir += dp->d_name;
777 return true;
778}
779
780bool llkIsMonitorState(char state) {
781 return (state == 'Z') || (state == 'D');
782}
783
784// returns -1 if not found
785long long getSchedValue(const std::string& schedString, const char* key) {
786 auto pos = schedString.find(key);
787 if (pos == std::string::npos) {
788 return -1;
789 }
790 pos = schedString.find(':', pos);
791 if (__predict_false(pos == std::string::npos)) {
792 return -1;
793 }
794 while ((++pos < schedString.size()) && ::isblank(schedString[pos])) {
795 ;
796 }
797 long long ret;
798 if (!android::base::ParseInt(schedString.substr(pos), &ret, static_cast<long long>(0))) {
799 return -1;
800 }
801 return ret;
802}
803
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700804#ifdef __PTRACE_ENABLED__
805bool llkCheckStack(proc* procp, const std::string& piddir) {
806 if (llkCheckStackSymbols.empty()) return false;
807 if (procp->state == 'Z') { // No brains for Zombies
808 procp->stack = -1;
809 procp->count_stack = 0ms;
810 return false;
811 }
812
813 // Don't check process that are known to block ptrace, save sepolicy noise.
Mark Salyzyn6d9e5152020-05-13 06:25:20 -0700814 if (llkSkipProc(procp, llkIgnorelistStack)) return false;
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700815 auto kernel_stack = ReadFile(piddir + "/stack");
816 if (kernel_stack.empty()) {
Mark Salyzyn22e05fb2019-01-02 15:04:42 -0800817 LOG(VERBOSE) << piddir << "/stack empty comm=" << procp->getComm()
818 << " cmdline=" << procp->getCmdline();
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700819 return false;
820 }
821 // A scheduling incident that should not reset count_stack
822 if (kernel_stack.find(" cpu_worker_pools+0x") != std::string::npos) return false;
823 char idx = -1;
824 char match = -1;
Mark Salyzyn22e05fb2019-01-02 15:04:42 -0800825 std::string matched_stack_symbol = "<unknown>";
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700826 for (const auto& stack : llkCheckStackSymbols) {
827 if (++idx < 0) break;
Mark Salyzynbb1256a2018-10-18 14:39:27 -0700828 if ((kernel_stack.find(" "s + stack + "+0x") != std::string::npos) ||
829 (kernel_stack.find(" "s + stack + ".cfi+0x") != std::string::npos)) {
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700830 match = idx;
Mark Salyzyn22e05fb2019-01-02 15:04:42 -0800831 matched_stack_symbol = stack;
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700832 break;
833 }
834 }
835 if (procp->stack != match) {
836 procp->stack = match;
837 procp->count_stack = 0ms;
838 return false;
839 }
840 if (match == char(-1)) return false;
841 procp->count_stack += llkCycle;
Mark Salyzyn22e05fb2019-01-02 15:04:42 -0800842 if (procp->count_stack < llkStateTimeoutMs[llkStateStack]) return false;
843 LOG(WARNING) << "Found " << matched_stack_symbol << " in stack for pid " << procp->pid;
844 return true;
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700845}
846#endif
847
Mark Salyzynf089e142018-02-20 10:47:40 -0800848// Primary ABA mitigation watching last time schedule activity happened
849void llkCheckSchedUpdate(proc* procp, const std::string& piddir) {
850 // Audit finds /proc/<tid>/sched is just over 1K, and
851 // is rarely larger than 2K, even less on Android.
852 // For example, the "se.avg.lastUpdateTime" field we are
853 // interested in typically within the primary set in
854 // the first 1K.
855 //
856 // Proc entries can not be read >1K atomically via libbase,
857 // but if there are problems we assume at least a few
858 // samples of reads occur before we take any real action.
859 std::string schedString = ReadFile(piddir + "/sched");
Mark Salyzyn8a5f0812019-01-03 08:39:38 -0800860 if (schedString.empty()) {
Mark Salyzynf089e142018-02-20 10:47:40 -0800861 // /schedstat is not as standardized, but in 3.1+
862 // Android devices, the third field is nr_switches
863 // from /sched:
864 schedString = ReadFile(piddir + "/schedstat");
Mark Salyzyn8a5f0812019-01-03 08:39:38 -0800865 if (schedString.empty()) {
Mark Salyzynf089e142018-02-20 10:47:40 -0800866 return;
867 }
868 auto val = static_cast<unsigned long long>(-1);
869 if (((::sscanf(schedString.c_str(), "%*d %*d %llu", &val)) == 1) &&
870 (val != static_cast<unsigned long long>(-1)) && (val != 0) &&
871 (val != procp->nrSwitches)) {
872 procp->nrSwitches = val;
873 procp->count = 0ms;
Mark Salyzynafd66f22018-03-19 15:16:29 -0700874 procp->killed = !llkTestWithKill;
Mark Salyzynf089e142018-02-20 10:47:40 -0800875 }
876 return;
877 }
878
879 auto val = getSchedValue(schedString, "\nse.avg.lastUpdateTime");
880 if (val == -1) {
881 val = getSchedValue(schedString, "\nse.svg.last_update_time");
882 }
883 if (val != -1) {
884 auto schedUpdate = nanoseconds(val);
885 if (schedUpdate != procp->schedUpdate) {
886 procp->schedUpdate = schedUpdate;
887 procp->count = 0ms;
Mark Salyzynafd66f22018-03-19 15:16:29 -0700888 procp->killed = !llkTestWithKill;
Mark Salyzynf089e142018-02-20 10:47:40 -0800889 }
890 }
891
892 val = getSchedValue(schedString, "\nnr_switches");
893 if (val != -1) {
894 if (static_cast<uint64_t>(val) != procp->nrSwitches) {
895 procp->nrSwitches = val;
896 procp->count = 0ms;
Mark Salyzynafd66f22018-03-19 15:16:29 -0700897 procp->killed = !llkTestWithKill;
Mark Salyzynf089e142018-02-20 10:47:40 -0800898 }
899 }
900}
901
902void llkLogConfig(void) {
903 LOG(INFO) << "ro.config.low_ram=" << llkFormat(llkLowRam) << "\n"
Mark Salyzynbd7c8562018-10-31 10:02:08 -0700904 << LLK_ENABLE_SYSRQ_T_PROPERTY "=" << llkFormat(llkEnableSysrqT) << "\n"
Mark Salyzynf089e142018-02-20 10:47:40 -0800905 << LLK_ENABLE_PROPERTY "=" << llkFormat(llkEnable) << "\n"
906 << KHT_ENABLE_PROPERTY "=" << llkFormat(khtEnable) << "\n"
907 << LLK_MLOCKALL_PROPERTY "=" << llkFormat(llkMlockall) << "\n"
Mark Salyzynafd66f22018-03-19 15:16:29 -0700908 << LLK_KILLTEST_PROPERTY "=" << llkFormat(llkTestWithKill) << "\n"
Mark Salyzynf089e142018-02-20 10:47:40 -0800909 << KHT_TIMEOUT_PROPERTY "=" << llkFormat(khtTimeout) << "\n"
910 << LLK_TIMEOUT_MS_PROPERTY "=" << llkFormat(llkTimeoutMs) << "\n"
911 << LLK_D_TIMEOUT_MS_PROPERTY "=" << llkFormat(llkStateTimeoutMs[llkStateD]) << "\n"
912 << LLK_Z_TIMEOUT_MS_PROPERTY "=" << llkFormat(llkStateTimeoutMs[llkStateZ]) << "\n"
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700913#ifdef __PTRACE_ENABLED__
914 << LLK_STACK_TIMEOUT_MS_PROPERTY "=" << llkFormat(llkStateTimeoutMs[llkStateStack])
915 << "\n"
916#endif
Mark Salyzynf089e142018-02-20 10:47:40 -0800917 << LLK_CHECK_MS_PROPERTY "=" << llkFormat(llkCheckMs) << "\n"
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700918#ifdef __PTRACE_ENABLED__
919 << LLK_CHECK_STACK_PROPERTY "=" << llkFormat(llkCheckStackSymbols) << "\n"
Mark Salyzyn6d9e5152020-05-13 06:25:20 -0700920 << LLK_IGNORELIST_STACK_PROPERTY "=" << llkFormat(llkIgnorelistStack) << "\n"
Mark Salyzyn96505fa2018-08-07 08:13:13 -0700921#endif
Mark Salyzyn6d9e5152020-05-13 06:25:20 -0700922 << LLK_IGNORELIST_PROCESS_PROPERTY "=" << llkFormat(llkIgnorelistProcess) << "\n"
923 << LLK_IGNORELIST_PARENT_PROPERTY "=" << llkFormat(llkIgnorelistParent)
924 << llkFormat(llkIgnorelistParentAndChild, true) << "\n"
925 << LLK_IGNORELIST_UID_PROPERTY "=" << llkFormat(llkIgnorelistUid);
Mark Salyzynf089e142018-02-20 10:47:40 -0800926}
927
928void* llkThread(void* obj) {
Mark Salyzyn4832a8b2018-08-15 11:02:18 -0700929 prctl(PR_SET_DUMPABLE, 0);
930
Mark Salyzynf089e142018-02-20 10:47:40 -0800931 LOG(INFO) << "started";
932
933 std::string name = std::to_string(::gettid());
934 if (!llkSkipName(name)) {
Mark Salyzyn6d9e5152020-05-13 06:25:20 -0700935 llkIgnorelistProcess.emplace(name);
Mark Salyzynf089e142018-02-20 10:47:40 -0800936 }
937 name = static_cast<const char*>(obj);
938 prctl(PR_SET_NAME, name.c_str());
939 if (__predict_false(!llkSkipName(name))) {
Mark Salyzyn6d9e5152020-05-13 06:25:20 -0700940 llkIgnorelistProcess.insert(name);
Mark Salyzynf089e142018-02-20 10:47:40 -0800941 }
Mark Salyzyn6d9e5152020-05-13 06:25:20 -0700942 // No longer modifying llkIgnorelistProcess.
Mark Salyzynf089e142018-02-20 10:47:40 -0800943 llkRunning = true;
944 llkLogConfig();
945 while (llkRunning) {
946 ::usleep(duration_cast<microseconds>(llkCheck(true)).count());
947 }
948 // NOTREACHED
949 LOG(INFO) << "exiting";
950 return nullptr;
951}
952
953} // namespace
954
955milliseconds llkCheck(bool checkRunning) {
956 if (!llkEnable || (checkRunning != llkRunning)) {
957 return milliseconds::max();
958 }
959
960 // Reset internal watchdog, which is a healthy engineering margin of
961 // double the maximum wait or cycle time for the mainloop that calls us.
962 //
963 // This alarm is effectively the live lock detection of llkd, as
964 // we understandably can not monitor ourselves otherwise.
Peter Collingbournefb5eac92021-03-11 12:51:25 -0800965 ::alarm(duration_cast<seconds>(llkTimeoutMs * 2 * android::base::HwTimeoutMultiplier())
966 .count());
Mark Salyzynf089e142018-02-20 10:47:40 -0800967
968 // kernel jiffy precision fastest acquisition
969 static timespec last;
970 timespec now;
971 ::clock_gettime(CLOCK_MONOTONIC_COARSE, &now);
972 auto ms = llkGetTimespecDiffMs(&last, &now);
973 if (ms < llkCycle) {
974 return llkCycle - ms;
975 }
976 last = now;
977
978 LOG(VERBOSE) << "opendir(\"" << procdir << "\")";
979 if (__predict_false(!llkTopDirectory)) {
980 // gid containing AID_READPROC required
981 llkTopDirectory.reset(procdir);
982 if (__predict_false(!llkTopDirectory)) {
983 // Most likely reason we could be here is a resource limit.
984 // Keep our processing down to a minimum, but not so low that
985 // we do not recover in a timely manner should the issue be
986 // transitory.
987 LOG(DEBUG) << "opendir(\"" << procdir << "\") failed";
988 return llkTimeoutMs;
989 }
990 }
991
992 for (auto& it : tids) {
993 it.second.updated = false;
994 }
995
996 auto prevUpdate = llkUpdate;
997 llkUpdate += ms;
998 ms -= llkCycle;
999 auto myPid = ::getpid();
1000 auto myTid = ::gettid();
Mark Salyzynfbc3a752018-12-04 10:30:45 -08001001 auto dump = true;
Mark Salyzynf089e142018-02-20 10:47:40 -08001002 for (auto dp = llkTopDirectory.read(); dp != nullptr; dp = llkTopDirectory.read()) {
1003 std::string piddir;
1004
1005 if (!getValidTidDir(dp, &piddir)) {
1006 continue;
1007 }
1008
1009 // Get the process tasks
1010 std::string taskdir = piddir + "/task/";
1011 int pid = -1;
1012 LOG(VERBOSE) << "+opendir(\"" << taskdir << "\")";
1013 dir taskDirectory(taskdir);
1014 if (__predict_false(!taskDirectory)) {
1015 LOG(DEBUG) << "+opendir(\"" << taskdir << "\") failed";
1016 }
1017 for (auto tp = taskDirectory.read(dir::task, dp); tp != nullptr;
1018 tp = taskDirectory.read(dir::task)) {
1019 if (!getValidTidDir(tp, &piddir)) {
1020 continue;
1021 }
1022
1023 // Get the process stat
1024 std::string stat = ReadFile(piddir + "/stat");
Mark Salyzyn8a5f0812019-01-03 08:39:38 -08001025 if (stat.empty()) {
Mark Salyzynf089e142018-02-20 10:47:40 -08001026 continue;
1027 }
1028 unsigned tid = -1;
1029 char pdir[TASK_COMM_LEN + 1];
1030 char state = '?';
1031 unsigned ppid = -1;
1032 unsigned utime = -1;
1033 unsigned stime = -1;
1034 int dummy;
1035 pdir[0] = '\0';
1036 // tid should not change value
1037 auto match = ::sscanf(
1038 stat.c_str(),
1039 "%u (%" ___STRING(
1040 TASK_COMM_LEN) "[^)]) %c %u %*d %*d %*d %*d %*d %*d %*d %*d %*d %u %u %d",
1041 &tid, pdir, &state, &ppid, &utime, &stime, &dummy);
1042 if (pid == -1) {
1043 pid = tid;
1044 }
1045 LOG(VERBOSE) << "match " << match << ' ' << tid << " (" << pdir << ") " << state << ' '
1046 << ppid << " ... " << utime << ' ' << stime << ' ' << dummy;
1047 if (match != 7) {
1048 continue;
1049 }
1050
Marco Ballesio38c735e2019-12-27 13:43:29 -08001051 // Get the process cgroup
1052 auto cgroup = ReadFile(piddir + "/cgroup");
1053 auto frozen = cgroup.find(":freezer:/frozen") != std::string::npos;
1054
Mark Salyzynf089e142018-02-20 10:47:40 -08001055 auto procp = llkTidLookup(tid);
1056 if (procp == nullptr) {
Marco Ballesio38c735e2019-12-27 13:43:29 -08001057 procp = llkTidAlloc(tid, pid, ppid, pdir, utime + stime, state, frozen);
Mark Salyzynf089e142018-02-20 10:47:40 -08001058 } else {
1059 // comm can change ...
1060 procp->setComm(pdir);
Marco Ballesio38c735e2019-12-27 13:43:29 -08001061 // frozen can change, too...
1062 procp->setFrozen(frozen);
Mark Salyzynf089e142018-02-20 10:47:40 -08001063 procp->updated = true;
1064 // pid/ppid/tid wrap?
1065 if (((procp->update != prevUpdate) && (procp->update != llkUpdate)) ||
1066 (procp->ppid != ppid) || (procp->pid != pid)) {
1067 procp->reset();
1068 } else if (procp->time != (utime + stime)) { // secondary ABA.
1069 // watching utime+stime granularity jiffy
1070 procp->state = '?';
1071 }
1072 procp->update = llkUpdate;
1073 procp->pid = pid;
1074 procp->ppid = ppid;
1075 procp->time = utime + stime;
1076 if (procp->state != state) {
1077 procp->count = 0ms;
Mark Salyzynafd66f22018-03-19 15:16:29 -07001078 procp->killed = !llkTestWithKill;
Mark Salyzynf089e142018-02-20 10:47:40 -08001079 procp->state = state;
1080 } else {
1081 procp->count += llkCycle;
1082 }
1083 }
1084
1085 // Filter checks in intuitive order of CPU cost to evaluate
1086 // If tid unique continue, if ppid or pid unique break
1087
1088 if (pid == myPid) {
1089 break;
1090 }
Mark Salyzyn96505fa2018-08-07 08:13:13 -07001091#ifdef __PTRACE_ENABLED__
1092 // if no stack monitoring, we can quickly exit here
1093 if (!llkIsMonitorState(state) && llkCheckStackSymbols.empty()) {
Mark Salyzynf089e142018-02-20 10:47:40 -08001094 continue;
1095 }
Mark Salyzyn96505fa2018-08-07 08:13:13 -07001096#else
1097 if (!llkIsMonitorState(state)) continue;
1098#endif
Mark Salyzynf089e142018-02-20 10:47:40 -08001099 if ((tid == myTid) || llkSkipPid(tid)) {
1100 continue;
1101 }
Marco Ballesio38c735e2019-12-27 13:43:29 -08001102 if (procp->isFrozen()) {
1103 break;
1104 }
Mark Salyzynf089e142018-02-20 10:47:40 -08001105 if (llkSkipPpid(ppid)) {
1106 break;
1107 }
1108
Mark Salyzynda2aeb02019-01-02 08:27:22 -08001109 auto process_comm = procp->getComm();
1110 if (llkSkipName(process_comm)) {
Mark Salyzynf089e142018-02-20 10:47:40 -08001111 continue;
1112 }
1113 if (llkSkipName(procp->getCmdline())) {
1114 break;
1115 }
Mark Salyzyne81ede82018-10-22 15:52:32 -07001116 if (llkSkipName(android::base::Basename(procp->getCmdline()))) {
1117 break;
1118 }
Mark Salyzynf089e142018-02-20 10:47:40 -08001119
1120 auto pprocp = llkTidLookup(ppid);
1121 if (pprocp == nullptr) {
Marco Ballesio38c735e2019-12-27 13:43:29 -08001122 pprocp = llkTidAlloc(ppid, ppid, 0, "", 0, '?', false);
Mark Salyzynf089e142018-02-20 10:47:40 -08001123 }
Mark Salyzyn8a5f0812019-01-03 08:39:38 -08001124 if (pprocp) {
Mark Salyzynda2aeb02019-01-02 08:27:22 -08001125 if (llkSkipPproc(pprocp, procp)) break;
Mark Salyzyn6d9e5152020-05-13 06:25:20 -07001126 if (llkSkipProc(pprocp, llkIgnorelistParent)) break;
Mark Salyzyn8a5f0812019-01-03 08:39:38 -08001127 } else {
Mark Salyzyn6d9e5152020-05-13 06:25:20 -07001128 if (llkSkipName(std::to_string(ppid), llkIgnorelistParent)) break;
Mark Salyzynf089e142018-02-20 10:47:40 -08001129 }
1130
Mark Salyzyn6d9e5152020-05-13 06:25:20 -07001131 if ((llkIgnorelistUid.size() != 0) && llkSkipUid(procp->getUid())) {
Mark Salyzynf089e142018-02-20 10:47:40 -08001132 continue;
1133 }
1134
1135 // ABA mitigation watching last time schedule activity happened
1136 llkCheckSchedUpdate(procp, piddir);
1137
Mark Salyzyn96505fa2018-08-07 08:13:13 -07001138#ifdef __PTRACE_ENABLED__
1139 auto stuck = llkCheckStack(procp, piddir);
1140 if (llkIsMonitorState(state)) {
1141 if (procp->count >= llkStateTimeoutMs[(state == 'Z') ? llkStateZ : llkStateD]) {
1142 stuck = true;
1143 } else if (procp->count != 0ms) {
1144 LOG(VERBOSE) << state << ' ' << llkFormat(procp->count) << ' ' << ppid << "->"
Mark Salyzynda2aeb02019-01-02 08:27:22 -08001145 << pid << "->" << tid << ' ' << process_comm;
Mark Salyzyn96505fa2018-08-07 08:13:13 -07001146 }
1147 }
1148 if (!stuck) continue;
1149#else
1150 if (procp->count >= llkStateTimeoutMs[(state == 'Z') ? llkStateZ : llkStateD]) {
1151 if (procp->count != 0ms) {
1152 LOG(VERBOSE) << state << ' ' << llkFormat(procp->count) << ' ' << ppid << "->"
Mark Salyzynda2aeb02019-01-02 08:27:22 -08001153 << pid << "->" << tid << ' ' << process_comm;
Mark Salyzyn96505fa2018-08-07 08:13:13 -07001154 }
Mark Salyzynf089e142018-02-20 10:47:40 -08001155 continue;
1156 }
Mark Salyzyn96505fa2018-08-07 08:13:13 -07001157#endif
Mark Salyzynf089e142018-02-20 10:47:40 -08001158
1159 // We have to kill it to determine difference between live lock
1160 // and persistent state blocked on a resource. Is there something
1161 // wrong with a process that has no forward scheduling progress in
1162 // Z or D? Yes, generally means improper accounting in the
1163 // process, but not always ...
1164 //
1165 // Whomever we hit with a test kill must accept the Android
1166 // Aphorism that everything can be burned to the ground and
1167 // must survive.
1168 if (procp->killed == false) {
1169 procp->killed = true;
1170 // confirm: re-read uid before committing to a panic.
1171 procp->uid = -1;
1172 switch (state) {
1173 case 'Z': // kill ppid to free up a Zombie
1174 // Killing init will kernel panic without diagnostics
1175 // so skip right to controlled kernel panic with
1176 // diagnostics.
1177 if (ppid == initPid) {
1178 break;
1179 }
1180 LOG(WARNING) << "Z " << llkFormat(procp->count) << ' ' << ppid << "->"
Mark Salyzynda2aeb02019-01-02 08:27:22 -08001181 << pid << "->" << tid << ' ' << process_comm << " [kill]";
Mark Salyzynf089e142018-02-20 10:47:40 -08001182 if ((llkKillOneProcess(pprocp, procp) >= 0) ||
1183 (llkKillOneProcess(ppid, procp) >= 0)) {
1184 continue;
1185 }
1186 break;
1187
1188 case 'D': // kill tid to free up an uninterruptible D
1189 // If ABA is doing its job, we would not need or
1190 // want the following. Test kill is a Hail Mary
1191 // to make absolutely sure there is no forward
1192 // scheduling progress. The cost when ABA is
1193 // not working is we kill a process that likes to
1194 // stay in 'D' state, instead of panicing the
1195 // kernel (worse).
Mark Salyzyn96505fa2018-08-07 08:13:13 -07001196 default:
1197 LOG(WARNING) << state << ' ' << llkFormat(procp->count) << ' ' << pid
Mark Salyzynda2aeb02019-01-02 08:27:22 -08001198 << "->" << tid << ' ' << process_comm << " [kill]";
Mark Salyzynf089e142018-02-20 10:47:40 -08001199 if ((llkKillOneProcess(llkTidLookup(pid), procp) >= 0) ||
Mark Salyzyn96505fa2018-08-07 08:13:13 -07001200 (llkKillOneProcess(pid, state, tid) >= 0) ||
Mark Salyzynf089e142018-02-20 10:47:40 -08001201 (llkKillOneProcess(procp, procp) >= 0) ||
Mark Salyzyn96505fa2018-08-07 08:13:13 -07001202 (llkKillOneProcess(tid, state, tid) >= 0)) {
Mark Salyzynf089e142018-02-20 10:47:40 -08001203 continue;
1204 }
1205 break;
1206 }
1207 }
1208 // We are here because we have confirmed kernel live-lock
Woody Line5a09d82020-04-22 10:18:59 +08001209 std::vector<std::string> threads;
1210 auto taskdir = procdir + std::to_string(tid) + "/task/";
1211 dir taskDirectory(taskdir);
1212 for (auto tp = taskDirectory.read(); tp != nullptr; tp = taskDirectory.read()) {
1213 std::string piddir;
1214 if (getValidTidDir(tp, &piddir))
1215 threads.push_back(android::base::Basename(piddir));
1216 }
Mark Salyzyn3c3b14d2018-10-31 10:38:15 -07001217 const auto message = state + " "s + llkFormat(procp->count) + " " +
1218 std::to_string(ppid) + "->" + std::to_string(pid) + "->" +
Woody Line5a09d82020-04-22 10:18:59 +08001219 std::to_string(tid) + " " + process_comm + " [panic]\n" +
1220 " thread group: {" + android::base::Join(threads, ",") +
1221 "}";
Mark Salyzynfbc3a752018-12-04 10:30:45 -08001222 llkPanicKernel(dump, tid,
Mark Salyzyn3c3b14d2018-10-31 10:38:15 -07001223 (state == 'Z') ? "zombie" : (state == 'D') ? "driver" : "sleeping",
1224 message);
Mark Salyzynfbc3a752018-12-04 10:30:45 -08001225 dump = false;
Mark Salyzynf089e142018-02-20 10:47:40 -08001226 }
1227 LOG(VERBOSE) << "+closedir()";
1228 }
1229 llkTopDirectory.rewind();
1230 LOG(VERBOSE) << "closedir()";
1231
1232 // garbage collection of old process references
1233 for (auto p = tids.begin(); p != tids.end();) {
1234 if (!p->second.updated) {
1235 IF_ALOG(LOG_VERBOSE, LOG_TAG) {
1236 std::string ppidCmdline = llkProcGetName(p->second.ppid, nullptr, nullptr);
Mark Salyzyn8a5f0812019-01-03 08:39:38 -08001237 if (!ppidCmdline.empty()) ppidCmdline = "(" + ppidCmdline + ")";
Mark Salyzynf089e142018-02-20 10:47:40 -08001238 std::string pidCmdline;
1239 if (p->second.pid != p->second.tid) {
1240 pidCmdline = llkProcGetName(p->second.pid, nullptr, p->second.getCmdline());
Mark Salyzyn8a5f0812019-01-03 08:39:38 -08001241 if (!pidCmdline.empty()) pidCmdline = "(" + pidCmdline + ")";
Mark Salyzynf089e142018-02-20 10:47:40 -08001242 }
1243 std::string tidCmdline =
1244 llkProcGetName(p->second.tid, p->second.getComm(), p->second.getCmdline());
Mark Salyzyn8a5f0812019-01-03 08:39:38 -08001245 if (!tidCmdline.empty()) tidCmdline = "(" + tidCmdline + ")";
Mark Salyzynf089e142018-02-20 10:47:40 -08001246 LOG(VERBOSE) << "thread " << p->second.ppid << ppidCmdline << "->" << p->second.pid
1247 << pidCmdline << "->" << p->second.tid << tidCmdline << " removed";
1248 }
1249 p = tids.erase(p);
1250 } else {
1251 ++p;
1252 }
1253 }
1254 if (__predict_false(tids.empty())) {
1255 llkTopDirectory.reset();
1256 }
1257
1258 llkCycle = llkCheckMs;
1259
1260 timespec end;
1261 ::clock_gettime(CLOCK_MONOTONIC_COARSE, &end);
1262 auto milli = llkGetTimespecDiffMs(&now, &end);
1263 LOG((milli > 10s) ? ERROR : (milli > 1s) ? WARNING : VERBOSE) << "sample " << llkFormat(milli);
1264
1265 // cap to minimum sleep for 1 second since last cycle
1266 if (llkCycle < (ms + 1s)) {
1267 return 1s;
1268 }
1269 return llkCycle - ms;
1270}
1271
1272unsigned llkCheckMilliseconds() {
1273 return duration_cast<milliseconds>(llkCheck()).count();
1274}
1275
Mark Salyzynbd7c8562018-10-31 10:02:08 -07001276bool llkCheckEng(const std::string& property) {
1277 return android::base::GetProperty(property, "eng") == "eng";
1278}
1279
Mark Salyzynf089e142018-02-20 10:47:40 -08001280bool llkInit(const char* threadname) {
Mark Salyzyn96505fa2018-08-07 08:13:13 -07001281 auto debuggable = android::base::GetBoolProperty("ro.debuggable", false);
Mark Salyzynf089e142018-02-20 10:47:40 -08001282 llkLowRam = android::base::GetBoolProperty("ro.config.low_ram", false);
Mark Salyzynbd7c8562018-10-31 10:02:08 -07001283 llkEnableSysrqT &= !llkLowRam;
1284 if (debuggable) {
1285 llkEnableSysrqT |= llkCheckEng(LLK_ENABLE_SYSRQ_T_PROPERTY);
Suren Baghdasaryan2b925412021-11-04 15:29:01 -07001286 if (!LLK_ENABLE_DEFAULT) {
Mark Salyzynbd7c8562018-10-31 10:02:08 -07001287 khtEnable |= llkCheckEng(KHT_ENABLE_PROPERTY);
1288 }
Mark Salyzynd035dbb2018-03-26 08:23:00 -07001289 }
Mark Salyzynbd7c8562018-10-31 10:02:08 -07001290 llkEnableSysrqT = android::base::GetBoolProperty(LLK_ENABLE_SYSRQ_T_PROPERTY, llkEnableSysrqT);
Mark Salyzynf089e142018-02-20 10:47:40 -08001291 llkEnable = android::base::GetBoolProperty(LLK_ENABLE_PROPERTY, llkEnable);
1292 if (llkEnable && !llkTopDirectory.reset(procdir)) {
1293 // Most likely reason we could be here is llkd was started
1294 // incorrectly without the readproc permissions. Keep our
1295 // processing down to a minimum.
1296 llkEnable = false;
1297 }
1298 khtEnable = android::base::GetBoolProperty(KHT_ENABLE_PROPERTY, khtEnable);
1299 llkMlockall = android::base::GetBoolProperty(LLK_MLOCKALL_PROPERTY, llkMlockall);
Mark Salyzynafd66f22018-03-19 15:16:29 -07001300 llkTestWithKill = android::base::GetBoolProperty(LLK_KILLTEST_PROPERTY, llkTestWithKill);
Mark Salyzynf089e142018-02-20 10:47:40 -08001301 // if LLK_TIMOUT_MS_PROPERTY was not set, we will use a set
1302 // KHT_TIMEOUT_PROPERTY as co-operative guidance for the default value.
1303 khtTimeout = GetUintProperty(KHT_TIMEOUT_PROPERTY, khtTimeout);
1304 if (khtTimeout == 0s) {
1305 khtTimeout = duration_cast<seconds>(llkTimeoutMs * (1 + LLK_CHECKS_PER_TIMEOUT_DEFAULT) /
1306 LLK_CHECKS_PER_TIMEOUT_DEFAULT);
1307 }
1308 llkTimeoutMs =
1309 khtTimeout * LLK_CHECKS_PER_TIMEOUT_DEFAULT / (1 + LLK_CHECKS_PER_TIMEOUT_DEFAULT);
1310 llkTimeoutMs = GetUintProperty(LLK_TIMEOUT_MS_PROPERTY, llkTimeoutMs);
1311 llkValidate(); // validate llkTimeoutMs, llkCheckMs and llkCycle
1312 llkStateTimeoutMs[llkStateD] = GetUintProperty(LLK_D_TIMEOUT_MS_PROPERTY, llkTimeoutMs);
1313 llkStateTimeoutMs[llkStateZ] = GetUintProperty(LLK_Z_TIMEOUT_MS_PROPERTY, llkTimeoutMs);
Mark Salyzyn96505fa2018-08-07 08:13:13 -07001314#ifdef __PTRACE_ENABLED__
1315 llkStateTimeoutMs[llkStateStack] = GetUintProperty(LLK_STACK_TIMEOUT_MS_PROPERTY, llkTimeoutMs);
1316#endif
Mark Salyzynf089e142018-02-20 10:47:40 -08001317 llkCheckMs = GetUintProperty(LLK_CHECK_MS_PROPERTY, llkCheckMs);
1318 llkValidate(); // validate all (effectively minus llkTimeoutMs)
Mark Salyzyn96505fa2018-08-07 08:13:13 -07001319#ifdef __PTRACE_ENABLED__
1320 if (debuggable) {
Mark Salyzyn8a5f0812019-01-03 08:39:38 -08001321 llkCheckStackSymbols = llkSplit(LLK_CHECK_STACK_PROPERTY, LLK_CHECK_STACK_DEFAULT);
Mark Salyzyn96505fa2018-08-07 08:13:13 -07001322 }
Mark Salyzyn6d9e5152020-05-13 06:25:20 -07001323 std::string defaultIgnorelistStack(LLK_IGNORELIST_STACK_DEFAULT);
1324 if (!debuggable) defaultIgnorelistStack += ",logd,/system/bin/logd";
1325 llkIgnorelistStack = llkSplit(LLK_IGNORELIST_STACK_PROPERTY, defaultIgnorelistStack);
Mark Salyzyn96505fa2018-08-07 08:13:13 -07001326#endif
Mark Salyzyn6d9e5152020-05-13 06:25:20 -07001327 std::string defaultIgnorelistProcess(
1328 std::to_string(kernelPid) + "," + std::to_string(initPid) + "," +
1329 std::to_string(kthreaddPid) + "," + std::to_string(::getpid()) + "," +
1330 std::to_string(::gettid()) + "," LLK_IGNORELIST_PROCESS_DEFAULT);
Mark Salyzynf089e142018-02-20 10:47:40 -08001331 if (threadname) {
Mark Salyzyn6d9e5152020-05-13 06:25:20 -07001332 defaultIgnorelistProcess += ","s + threadname;
Mark Salyzynf089e142018-02-20 10:47:40 -08001333 }
1334 for (int cpu = 1; cpu < get_nprocs_conf(); ++cpu) {
Mark Salyzyn6d9e5152020-05-13 06:25:20 -07001335 defaultIgnorelistProcess += ",[watchdog/" + std::to_string(cpu) + "]";
Mark Salyzynf089e142018-02-20 10:47:40 -08001336 }
Mark Salyzyn6d9e5152020-05-13 06:25:20 -07001337 llkIgnorelistProcess = llkSplit(LLK_IGNORELIST_PROCESS_PROPERTY, defaultIgnorelistProcess);
Mark Salyzynf089e142018-02-20 10:47:40 -08001338 if (!llkSkipName("[khungtaskd]")) { // ALWAYS ignore as special
Mark Salyzyn6d9e5152020-05-13 06:25:20 -07001339 llkIgnorelistProcess.emplace("[khungtaskd]");
Mark Salyzynf089e142018-02-20 10:47:40 -08001340 }
Mark Salyzyn6d9e5152020-05-13 06:25:20 -07001341 llkIgnorelistParent = llkSplit(LLK_IGNORELIST_PARENT_PROPERTY,
1342 std::to_string(kernelPid) + "," + std::to_string(kthreaddPid) +
1343 "," LLK_IGNORELIST_PARENT_DEFAULT);
1344 // derive llkIgnorelistParentAndChild by moving entries with '&' from above
1345 for (auto it = llkIgnorelistParent.begin(); it != llkIgnorelistParent.end();) {
Mark Salyzynda2aeb02019-01-02 08:27:22 -08001346 auto pos = it->find('&');
1347 if (pos == std::string::npos) {
1348 ++it;
1349 continue;
1350 }
1351 auto parent = it->substr(0, pos);
1352 auto child = it->substr(pos + 1);
Mark Salyzyn6d9e5152020-05-13 06:25:20 -07001353 it = llkIgnorelistParent.erase(it);
Mark Salyzynda2aeb02019-01-02 08:27:22 -08001354
Mark Salyzyn6d9e5152020-05-13 06:25:20 -07001355 auto found = llkIgnorelistParentAndChild.find(parent);
1356 if (found == llkIgnorelistParentAndChild.end()) {
1357 llkIgnorelistParentAndChild.emplace(std::make_pair(
Mark Salyzynda2aeb02019-01-02 08:27:22 -08001358 std::move(parent), std::unordered_set<std::string>({std::move(child)})));
1359 } else {
1360 found->second.emplace(std::move(child));
1361 }
1362 }
1363
Mark Salyzyn6d9e5152020-05-13 06:25:20 -07001364 llkIgnorelistUid = llkSplit(LLK_IGNORELIST_UID_PROPERTY, LLK_IGNORELIST_UID_DEFAULT);
Mark Salyzynf089e142018-02-20 10:47:40 -08001365
1366 // internal watchdog
1367 ::signal(SIGALRM, llkAlarmHandler);
1368
1369 // kernel hung task configuration? Otherwise leave it as-is
1370 if (khtEnable) {
1371 // EUID must be AID_ROOT to write to /proc/sys/kernel/ nodes, there
1372 // are no capability overrides. For security reasons we do not want
1373 // to run as AID_ROOT. We may not be able to write them successfully,
1374 // we will try, but the least we can do is read the values back to
1375 // confirm expectations and report whether configured or not.
1376 auto configured = llkWriteStringToFileConfirm(std::to_string(khtTimeout.count()),
1377 "/proc/sys/kernel/hung_task_timeout_secs");
1378 if (configured) {
1379 llkWriteStringToFile("65535", "/proc/sys/kernel/hung_task_warnings");
1380 llkWriteStringToFile("65535", "/proc/sys/kernel/hung_task_check_count");
1381 configured = llkWriteStringToFileConfirm("1", "/proc/sys/kernel/hung_task_panic");
1382 }
1383 if (configured) {
1384 LOG(INFO) << "[khungtaskd] configured";
1385 } else {
1386 LOG(WARNING) << "[khungtaskd] not configurable";
1387 }
1388 }
1389
1390 bool logConfig = true;
1391 if (llkEnable) {
1392 if (llkMlockall &&
1393 // MCL_ONFAULT pins pages as they fault instead of loading
1394 // everything immediately all at once. (Which would be bad,
1395 // because as of this writing, we have a lot of mapped pages we
1396 // never use.) Old kernels will see MCL_ONFAULT and fail with
1397 // EINVAL; we ignore this failure.
1398 //
1399 // N.B. read the man page for mlockall. MCL_CURRENT | MCL_ONFAULT
1400 // pins ⊆ MCL_CURRENT, converging to just MCL_CURRENT as we fault
1401 // in pages.
1402
1403 // CAP_IPC_LOCK required
1404 mlockall(MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT) && (errno != EINVAL)) {
1405 PLOG(WARNING) << "mlockall failed ";
1406 }
1407
1408 if (threadname) {
1409 pthread_attr_t attr;
1410
1411 if (!pthread_attr_init(&attr)) {
1412 sched_param param;
1413
1414 memset(&param, 0, sizeof(param));
1415 pthread_attr_setschedparam(&attr, &param);
1416 pthread_attr_setschedpolicy(&attr, SCHED_BATCH);
1417 if (!pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)) {
1418 pthread_t thread;
1419 if (!pthread_create(&thread, &attr, llkThread, const_cast<char*>(threadname))) {
1420 // wait a second for thread to start
1421 for (auto retry = 50; retry && !llkRunning; --retry) {
1422 ::usleep(20000);
1423 }
1424 logConfig = !llkRunning; // printed in llkd context?
1425 } else {
1426 LOG(ERROR) << "failed to spawn llkd thread";
1427 }
1428 } else {
1429 LOG(ERROR) << "failed to detach llkd thread";
1430 }
1431 pthread_attr_destroy(&attr);
1432 } else {
1433 LOG(ERROR) << "failed to allocate attibutes for llkd thread";
1434 }
1435 }
1436 } else {
1437 LOG(DEBUG) << "[khungtaskd] left unconfigured";
1438 }
1439 if (logConfig) {
1440 llkLogConfig();
1441 }
1442
1443 return llkEnable;
1444}