blob: d9185d90455c43cd77861d6218d6eb2d8a1a41dc [file] [log] [blame]
James Hawkinsabd73e62016-01-19 15:10:38 -08001/*
2 * Copyright (C) 2016 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// The bootstat command provides options to persist boot events with the current
18// timestamp, dump the persisted events, and log all events to EventLog to be
19// uploaded to Android log storage via Tron.
20
James Hawkinsa4a1a4a2016-02-09 15:32:38 -080021#include <getopt.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070022#include <sys/klog.h>
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -070023#include <unistd.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070024
James Hawkinse78ea772017-03-24 11:43:02 -070025#include <chrono>
James Hawkins0660b302016-03-08 16:18:15 -080026#include <cmath>
James Hawkinsabd73e62016-01-19 15:10:38 -080027#include <cstddef>
28#include <cstdio>
James Hawkins500d7152016-02-16 15:05:54 -080029#include <ctime>
James Hawkinsa4a1a4a2016-02-09 15:32:38 -080030#include <map>
James Hawkinsabd73e62016-01-19 15:10:38 -080031#include <memory>
32#include <string>
James Hawkinsbe46fd12017-02-02 16:21:25 -080033#include <vector>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070034
James Hawkinse78ea772017-03-24 11:43:02 -070035#include <android-base/chrono_utils.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070036#include <android-base/file.h>
James Hawkinseabe08b2016-01-19 16:54:35 -080037#include <android-base/logging.h>
James Hawkins4dded612016-07-28 11:50:23 -070038#include <android-base/parseint.h>
James Hawkinsbe46fd12017-02-02 16:21:25 -080039#include <android-base/strings.h>
James Hawkinse78ea772017-03-24 11:43:02 -070040#include <android/log.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070041#include <cutils/android_reboot.h>
James Hawkinsa4a1a4a2016-02-09 15:32:38 -080042#include <cutils/properties.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070043#include <log/logcat.h>
James Hawkins9aec9262017-01-31 11:42:24 -080044#include <metricslogger/metrics_logger.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070045
James Hawkinsabd73e62016-01-19 15:10:38 -080046#include "boot_event_record_store.h"
James Hawkinsabd73e62016-01-19 15:10:38 -080047
48namespace {
49
James Hawkinsabd73e62016-01-19 15:10:38 -080050// Scans the boot event record store for record files and logs each boot event
51// via EventLog.
52void LogBootEvents() {
53 BootEventRecordStore boot_event_store;
54
55 auto events = boot_event_store.GetAllBootEvents();
56 for (auto i = events.cbegin(); i != events.cend(); ++i) {
James Hawkins9aec9262017-01-31 11:42:24 -080057 android::metricslogger::LogHistogram(i->first, i->second);
James Hawkinsabd73e62016-01-19 15:10:38 -080058 }
59}
60
James Hawkinsc6275582016-03-22 10:47:44 -070061// Records the named boot |event| to the record store. If |value| is non-empty
62// and is a proper string representation of an integer value, the converted
63// integer value is associated with the boot event.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -070064void RecordBootEventFromCommandLine(const std::string& event, const std::string& value_str) {
James Hawkinsc6275582016-03-22 10:47:44 -070065 BootEventRecordStore boot_event_store;
66 if (!value_str.empty()) {
67 int32_t value = 0;
Elliott Hughesda46b392016-10-11 17:09:00 -070068 if (android::base::ParseInt(value_str, &value)) {
James Hawkins4dded612016-07-28 11:50:23 -070069 boot_event_store.AddBootEventWithValue(event, value);
70 }
James Hawkinsc6275582016-03-22 10:47:44 -070071 } else {
72 boot_event_store.AddBootEvent(event);
73 }
74}
75
James Hawkinsabd73e62016-01-19 15:10:38 -080076void PrintBootEvents() {
77 printf("Boot events:\n");
78 printf("------------\n");
79
80 BootEventRecordStore boot_event_store;
81 auto events = boot_event_store.GetAllBootEvents();
82 for (auto i = events.cbegin(); i != events.cend(); ++i) {
83 printf("%s\t%d\n", i->first.c_str(), i->second);
84 }
85}
86
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -070087void ShowHelp(const char* cmd) {
James Hawkinsabd73e62016-01-19 15:10:38 -080088 fprintf(stderr, "Usage: %s [options]\n", cmd);
89 fprintf(stderr,
90 "options include:\n"
Yongqin Liu78b2b942017-07-07 13:26:49 +080091 " -h, --help Show this help\n"
92 " -l, --log Log all metrics to logstorage\n"
93 " -p, --print Dump the boot event records to the console\n"
94 " -r, --record Record the timestamp of a named boot event\n"
95 " --value Optional value to associate with the boot event\n"
96 " --record_boot_complete Record metrics related to the time for the device boot\n"
97 " --record_boot_reason Record the reason why the device booted\n"
James Hawkins53684ea2016-02-23 16:18:19 -080098 " --record_time_since_factory_reset Record the time since the device was reset\n");
James Hawkinsabd73e62016-01-19 15:10:38 -080099}
100
101// Constructs a readable, printable string from the givencommand line
102// arguments.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700103std::string GetCommandLine(int argc, char** argv) {
James Hawkinsabd73e62016-01-19 15:10:38 -0800104 std::string cmd;
105 for (int i = 0; i < argc; ++i) {
106 cmd += argv[i];
107 cmd += " ";
108 }
109
110 return cmd;
111}
112
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800113// Convenience wrapper over the property API that returns an
114// std::string.
115std::string GetProperty(const char* key) {
116 std::vector<char> temp(PROPERTY_VALUE_MAX);
117 const int len = property_get(key, &temp[0], nullptr);
118 if (len < 0) {
119 return "";
120 }
121 return std::string(&temp[0], len);
122}
123
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700124void SetProperty(const char* key, const std::string& val) {
125 property_set(key, val.c_str());
126}
127
128void SetProperty(const char* key, const char* val) {
129 property_set(key, val);
130}
131
James Hawkins25f71222017-10-10 16:37:05 -0700132constexpr int32_t kEmptyBootReason = 0;
James Hawkins6f74c0b2016-02-12 15:49:16 -0800133constexpr int32_t kUnknownBootReason = 1;
134
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800135// A mapping from boot reason string, as read from the ro.boot.bootreason
136// system property, to a unique integer ID. Viewers of log data dashboards for
137// the boot_reason metric may refer to this mapping to discern the histogram
138// values.
James Hawkins6f74c0b2016-02-12 15:49:16 -0800139const std::map<std::string, int32_t> kBootReasonMap = {
James Hawkins25f71222017-10-10 16:37:05 -0700140 {"empty", kEmptyBootReason},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700141 {"unknown", kUnknownBootReason},
142 {"normal", 2},
143 {"recovery", 3},
144 {"reboot", 4},
145 {"PowerKey", 5},
146 {"hard_reset", 6},
147 {"kernel_panic", 7},
148 {"rpm_err", 8},
149 {"hw_reset", 9},
150 {"tz_err", 10},
151 {"adsp_err", 11},
152 {"modem_err", 12},
153 {"mba_err", 13},
154 {"Watchdog", 14},
155 {"Panic", 15},
156 {"power_key", 16},
157 {"power_on", 17},
158 {"Reboot", 18},
159 {"rtc", 19},
160 {"edl", 20},
161 {"oem_pon1", 21},
162 {"oem_powerkey", 22},
163 {"oem_unknown_reset", 23},
164 {"srto: HWWDT reset SC", 24},
165 {"srto: HWWDT reset platform", 25},
166 {"srto: bootloader", 26},
167 {"srto: kernel panic", 27},
168 {"srto: kernel watchdog reset", 28},
169 {"srto: normal", 29},
170 {"srto: reboot", 30},
171 {"srto: reboot-bootloader", 31},
172 {"srto: security watchdog reset", 32},
173 {"srto: wakesrc", 33},
174 {"srto: watchdog", 34},
175 {"srto:1-1", 35},
176 {"srto:omap_hsmm", 36},
177 {"srto:phy0", 37},
178 {"srto:rtc0", 38},
179 {"srto:touchpad", 39},
180 {"watchdog", 40},
181 {"watchdogr", 41},
182 {"wdog_bark", 42},
183 {"wdog_bite", 43},
184 {"wdog_reset", 44},
185 {"shutdown,", 45}, // Trailing comma is intentional.
186 {"shutdown,userrequested", 46},
187 {"reboot,bootloader", 47},
188 {"reboot,cold", 48},
189 {"reboot,recovery", 49},
190 {"thermal_shutdown", 50},
191 {"s3_wakeup", 51},
192 {"kernel_panic,sysrq", 52},
193 {"kernel_panic,NULL", 53},
194 {"kernel_panic,BUG", 54},
195 {"bootloader", 55},
196 {"cold", 56},
197 {"hard", 57},
198 {"warm", 58},
199 {"recovery", 59},
200 {"thermal-shutdown", 60},
201 {"shutdown,thermal", 61},
202 {"shutdown,battery", 62},
203 {"reboot,ota", 63},
204 {"reboot,factory_reset", 64},
205 {"reboot,", 65},
206 {"reboot,shell", 66},
207 {"reboot,adb", 67},
Mark Salyzyn9033bf52017-09-21 11:30:29 -0700208 {"reboot,userrequested", 68},
Mark Salyzyn161b8622017-09-26 08:26:12 -0700209 {"shutdown,container", 69}, // Host OS asking Android Container to shutdown
Mark Salyzyn243fa292017-10-11 09:02:04 -0700210 {"cold,powerkey", 70},
211 {"warm,s3_wakeup", 71},
212 {"hard,hw_reset", 72},
213 {"shutdown,suspend", 73}, // Suspend to RAM
214 {"shutdown,hibernate", 74}, // Suspend to DISK
James Hawkins34073b52017-10-17 15:53:27 -0700215 {"power_on_key", 75},
216 {"reboot_by_key", 76},
217 {"wdt_by_pass_pwk", 77},
218 {"reboot_longkey", 78},
219 {"powerkey", 79},
220 {"usb", 80},
221 {"wdt", 81},
222 {"tool_by_pass_pwk", 82},
223 {"2sec_reboot", 83},
224 {"reboot,by_key", 84},
225 {"reboot,longkey", 85},
Mark Salyzyncabbe4f2017-10-23 13:52:39 -0700226 {"reboot,2sec", 86},
Mark Salyzync89f9da2017-10-24 15:35:34 -0700227 {"shutdown,thermal,battery", 87},
Mark Salyzyn72a8ea32017-10-25 09:23:19 -0700228 {"reboot,its_just_so_hard", 88}, // produced by boot_reason_test
229 {"reboot,Its Just So Hard", 89}, // produced by boot_reason_test
James Hawkins8ac79bc2017-10-31 10:07:34 -0700230 {"usb", 90},
James Hawkins74b17582017-11-20 14:13:41 -0800231 {"charge", 91},
232 {"oem_tz_crash", 92},
233 {"uvlo", 93},
234 {"oem_ps_hold", 94},
235 {"abnormal_reset", 95},
236 {"oemerr_unknown", 96},
237 {"reboot_fastboot_mode", 97},
James Hawkins5f85f832017-11-29 14:30:06 -0800238 {"watchdog_apps_bite", 98},
239 {"xpu_err", 99},
240 {"power_on_usb", 100},
James Hawkinsf4444f02017-11-30 15:01:40 -0800241 {"watchdog_rpm", 101},
242 {"watchdog_nonsec", 102},
243 {"watchdog_apps_bark", 103},
244 {"reboot_dmverity_corrupted", 104},
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800245};
246
247// Converts a string value representing the reason the system booted to an
248// integer representation. This is necessary for logging the boot_reason metric
249// via Tron, which does not accept non-integer buckets in histograms.
250int32_t BootReasonStrToEnum(const std::string& boot_reason) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800251 auto mapping = kBootReasonMap.find(boot_reason);
252 if (mapping != kBootReasonMap.end()) {
253 return mapping->second;
254 }
255
James Hawkins25f71222017-10-10 16:37:05 -0700256 if (boot_reason.empty()) {
257 return kEmptyBootReason;
258 }
259
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800260 LOG(INFO) << "Unknown boot reason: " << boot_reason;
261 return kUnknownBootReason;
262}
263
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700264// Canonical list of supported primary reboot reasons.
265const std::vector<const std::string> knownReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700266 // clang-format off
267 // kernel
268 "watchdog",
269 "kernel_panic",
270 // strong
271 "recovery", // Should not happen from ro.boot.bootreason
272 "bootloader", // Should not happen from ro.boot.bootreason
273 // blunt
274 "cold",
275 "hard",
276 "warm",
Mark Salyzyn62909822017-10-09 09:27:16 -0700277 // super blunt
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700278 "shutdown", // Can not happen from ro.boot.bootreason
279 "reboot", // Default catch-all for anything unknown
280 // clang-format on
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700281};
282
283// Returns true if the supplied reason prefix is considered detailed enough.
284bool isStrongRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700285 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700286 if (s == "cold") break;
287 // Prefix defined as terminated by a nul or comma (,).
288 if (android::base::StartsWith(r, s.c_str()) &&
289 ((r.length() == s.length()) || (r[s.length()] == ','))) {
290 return true;
291 }
292 }
293 return false;
294}
295
296// Returns true if the supplied reason prefix is associated with the kernel.
297bool isKernelRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700298 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700299 if (s == "recovery") break;
300 // Prefix defined as terminated by a nul or comma (,).
301 if (android::base::StartsWith(r, s.c_str()) &&
302 ((r.length() == s.length()) || (r[s.length()] == ','))) {
303 return true;
304 }
305 }
306 return false;
307}
308
309// Returns true if the supplied reason prefix is considered known.
310bool isKnownRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700311 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700312 // Prefix defined as terminated by a nul or comma (,).
313 if (android::base::StartsWith(r, s.c_str()) &&
314 ((r.length() == s.length()) || (r[s.length()] == ','))) {
315 return true;
316 }
317 }
318 return false;
319}
320
321// If the reboot reason should be improved, report true if is too blunt.
322bool isBluntRebootReason(const std::string& r) {
323 if (isStrongRebootReason(r)) return false;
324
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700325 if (!isKnownRebootReason(r)) return true; // Can not support unknown as detail
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700326
327 size_t pos = 0;
328 while ((pos = r.find(',', pos)) != std::string::npos) {
329 ++pos;
330 std::string next(r.substr(pos));
331 if (next.length() == 0) break;
332 if (next[0] == ',') continue;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700333 if (!isKnownRebootReason(next)) return false; // Unknown subreason is good.
334 if (isStrongRebootReason(next)) return false; // eg: reboot,reboot
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700335 }
336 return true;
337}
338
Mark Salyzyn64610892017-09-18 10:41:14 -0700339bool readPstoreConsole(std::string& console) {
340 if (android::base::ReadFileToString("/sys/fs/pstore/console-ramoops-0", &console)) {
341 return true;
342 }
343 return android::base::ReadFileToString("/sys/fs/pstore/console-ramoops", &console);
344}
345
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700346// Implement a variant of std::string::rfind that is resilient to errors in
347// the data stream being inspected.
348class pstoreConsole {
349 private:
350 const size_t kBitErrorRate = 8; // number of bits per error
351 const std::string& console;
352
353 // Number of bits that differ between the two arguments l and r.
354 // Returns zero if the values for l and r are identical.
355 size_t numError(uint8_t l, uint8_t r) const { return std::bitset<8>(l ^ r).count(); }
356
357 // A string comparison function, reports the number of errors discovered
358 // in the match to a maximum of the bitLength / kBitErrorRate, at that
359 // point returning npos to indicate match is too poor.
360 //
361 // Since called in rfind which works backwards, expect cache locality will
362 // help if we check in reverse here as well for performance.
363 //
364 // Assumption: l (from console.c_str() + pos) is long enough to house
365 // _r.length(), checked in rfind caller below.
366 //
367 size_t numError(size_t pos, const std::string& _r) const {
368 const char* l = console.c_str() + pos;
369 const char* r = _r.c_str();
370 size_t n = _r.length();
371 const uint8_t* le = reinterpret_cast<const uint8_t*>(l) + n;
372 const uint8_t* re = reinterpret_cast<const uint8_t*>(r) + n;
373 size_t count = 0;
374 n = 0;
375 do {
376 // individual character bit error rate > threshold + slop
377 size_t num = numError(*--le, *--re);
378 if (num > ((8 + kBitErrorRate) / kBitErrorRate)) return std::string::npos;
379 // total bit error rate > threshold + slop
380 count += num;
381 ++n;
382 if (count > ((n * 8 + kBitErrorRate - (n > 2)) / kBitErrorRate)) {
383 return std::string::npos;
384 }
385 } while (le != reinterpret_cast<const uint8_t*>(l));
386 return count;
387 }
388
389 public:
390 explicit pstoreConsole(const std::string& console) : console(console) {}
391 // scope of argument must be equal to or greater than scope of pstoreConsole
392 explicit pstoreConsole(const std::string&& console) = delete;
393 explicit pstoreConsole(std::string&& console) = delete;
394
395 // Our implementation of rfind, use exact match first, then resort to fuzzy.
396 size_t rfind(const std::string& needle) const {
397 size_t pos = console.rfind(needle); // exact match?
398 if (pos != std::string::npos) return pos;
399
400 // Check to make sure needle fits in console string.
401 pos = console.length();
402 if (needle.length() > pos) return std::string::npos;
403 pos -= needle.length();
404 // fuzzy match to maximum kBitErrorRate
405 do {
406 if (numError(pos, needle) != std::string::npos) return pos;
407 } while (pos-- != 0);
408 return std::string::npos;
409 }
410
411 // Our implementation of find, use only fuzzy match.
412 size_t find(const std::string& needle, size_t start = 0) const {
413 // Check to make sure needle fits in console string.
414 if (needle.length() > console.length()) return std::string::npos;
415 const size_t last_pos = console.length() - needle.length();
416 // fuzzy match to maximum kBitErrorRate
417 for (size_t pos = start; pos <= last_pos; ++pos) {
418 if (numError(pos, needle) != std::string::npos) return pos;
419 }
420 return std::string::npos;
421 }
422};
423
424// If bit error match to needle, correct it.
425// Return true if any corrections were discovered and applied.
426bool correctForBer(std::string& reason, const std::string& needle) {
427 bool corrected = false;
428 if (reason.length() < needle.length()) return corrected;
429 const pstoreConsole console(reason);
430 const size_t last_pos = reason.length() - needle.length();
431 for (size_t pos = 0; pos <= last_pos; pos += needle.length()) {
432 pos = console.find(needle, pos);
433 if (pos == std::string::npos) break;
434
435 // exact match has no malice
436 if (needle == reason.substr(pos, needle.length())) continue;
437
438 corrected = true;
439 reason = reason.substr(0, pos) + needle + reason.substr(pos + needle.length());
440 }
441 return corrected;
442}
443
444bool addKernelPanicSubReason(const pstoreConsole& console, std::string& ret) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700445 // Check for kernel panic types to refine information
446 if (console.rfind("SysRq : Trigger a crash") != std::string::npos) {
447 // Can not happen, except on userdebug, during testing/debugging.
448 ret = "kernel_panic,sysrq";
449 return true;
450 }
451 if (console.rfind("Unable to handle kernel NULL pointer dereference at virtual address") !=
452 std::string::npos) {
453 ret = "kernel_panic,NULL";
454 return true;
455 }
456 if (console.rfind("Kernel BUG at ") != std::string::npos) {
457 ret = "kernel_panic,BUG";
458 return true;
459 }
460 return false;
461}
462
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700463bool addKernelPanicSubReason(const std::string& content, std::string& ret) {
464 return addKernelPanicSubReason(pstoreConsole(content), ret);
465}
466
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700467// std::transform Helper callback functions:
468// Converts a string value representing the reason the system booted to a
469// string complying with Android system standard reason.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700470char tounderline(char c) {
471 return ::isblank(c) ? '_' : c;
472}
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700473
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700474char toprintable(char c) {
475 return ::isprint(c) ? c : '?';
476}
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700477
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700478// Cleanup boot_reason regarding acceptable character set
479void transformReason(std::string& reason) {
480 std::transform(reason.begin(), reason.end(), reason.begin(), ::tolower);
481 std::transform(reason.begin(), reason.end(), reason.begin(), tounderline);
482 std::transform(reason.begin(), reason.end(), reason.begin(), toprintable);
483}
484
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700485const char system_reboot_reason_property[] = "sys.boot.reason";
486const char last_reboot_reason_property[] = LAST_REBOOT_REASON_PROPERTY;
487const char bootloader_reboot_reason_property[] = "ro.boot.bootreason";
488
489// Scrub, Sanitize, Standardize and Enhance the boot reason string supplied.
490std::string BootReasonStrToReason(const std::string& boot_reason) {
Mark Salyzyna16e4372017-09-20 08:36:12 -0700491 static const size_t max_reason_length = 256;
492
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700493 std::string ret(GetProperty(system_reboot_reason_property));
494 std::string reason(boot_reason);
495 // If sys.boot.reason == ro.boot.bootreason, let's re-evaluate
496 if (reason == ret) ret = "";
497
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700498 transformReason(reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700499
500 // Is the current system boot reason sys.boot.reason valid?
501 if (!isKnownRebootReason(ret)) ret = "";
502
503 if (ret == "") {
504 // Is the bootloader boot reason ro.boot.bootreason known?
505 std::vector<std::string> words(android::base::Split(reason, ",_-"));
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700506 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700507 std::string blunt;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700508 for (auto& r : words) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700509 if (r == s) {
510 if (isBluntRebootReason(s)) {
511 blunt = s;
512 } else {
513 ret = s;
514 break;
515 }
516 }
517 }
518 if (ret == "") ret = blunt;
519 if (ret != "") break;
520 }
521 }
522
523 if (ret == "") {
524 // A series of checks to take some officially unsupported reasons
525 // reported by the bootloader and find some logical and canonical
526 // sense. In an ideal world, we would require those bootloaders
527 // to behave and follow our standards.
528 static const std::vector<std::pair<const std::string, const std::string>> aliasReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700529 {"watchdog", "wdog"},
530 {"cold,powerkey", "powerkey"},
531 {"kernel_panic", "panic"},
532 {"shutdown,thermal", "thermal"},
533 {"warm,s3_wakeup", "s3_wakeup"},
534 {"hard,hw_reset", "hw_reset"},
Mark Salyzyncabbe4f2017-10-23 13:52:39 -0700535 {"reboot,2sec", "2sec_reboot"},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700536 {"bootloader", ""},
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700537 };
538
539 // Either the primary or alias is found _somewhere_ in the reason string.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700540 for (auto& s : aliasReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700541 if (reason.find(s.first) != std::string::npos) {
542 ret = s.first;
543 break;
544 }
545 if (s.second.size() && (reason.find(s.second) != std::string::npos)) {
546 ret = s.first;
547 break;
548 }
549 }
550 }
551
552 // If watchdog is the reason, see if there is a security angle?
553 if (ret == "watchdog") {
554 if (reason.find("sec") != std::string::npos) {
555 ret += ",security";
556 }
557 }
558
Mark Salyzyn64610892017-09-18 10:41:14 -0700559 if (ret == "kernel_panic") {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700560 // Check to see if last klog has some refinement hints.
561 std::string content;
Mark Salyzyn64610892017-09-18 10:41:14 -0700562 if (readPstoreConsole(content)) {
563 addKernelPanicSubReason(content, ret);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700564 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700565 } else if (isBluntRebootReason(ret)) {
566 // Check the other available reason resources if the reason is still blunt.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700567
Mark Salyzyn64610892017-09-18 10:41:14 -0700568 // Check to see if last klog has some refinement hints.
569 std::string content;
570 if (readPstoreConsole(content)) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700571 const pstoreConsole console(content);
Mark Salyzyn64610892017-09-18 10:41:14 -0700572 // The toybox reboot command used directly (unlikely)? But also
573 // catches init's response to Android's more controlled reboot command.
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700574 if (console.rfind("reboot: Power down") != std::string::npos) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700575 ret = "shutdown"; // Still too blunt, but more accurate.
576 // ToDo: init should record the shutdown reason to kernel messages ala:
577 // init: shutdown system with command 'last_reboot_reason'
578 // so that if pstore has persistence we can get some details
579 // that could be missing in last_reboot_reason_property.
580 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700581
Mark Salyzyn64610892017-09-18 10:41:14 -0700582 static const char cmd[] = "reboot: Restarting system with command '";
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700583 size_t pos = console.rfind(cmd);
Mark Salyzyn64610892017-09-18 10:41:14 -0700584 if (pos != std::string::npos) {
585 pos += strlen(cmd);
Mark Salyzyna16e4372017-09-20 08:36:12 -0700586 std::string subReason(content.substr(pos, max_reason_length));
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700587 // Correct against any known strings that Bit Error Match
588 for (const auto& s : knownReasons) {
589 correctForBer(subReason, s);
590 }
591 for (const auto& m : kBootReasonMap) {
592 if (m.first.length() <= strlen("cold")) continue; // too short?
593 if (correctForBer(subReason, m.first + "'")) continue;
594 if (m.first.length() <= strlen("reboot,cold")) continue; // short?
595 if (!android::base::StartsWith(m.first, "reboot,")) continue;
596 correctForBer(subReason, m.first.substr(strlen("reboot,")) + "'");
597 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700598 for (pos = 0; pos < subReason.length(); ++pos) {
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700599 char c = subReason[pos];
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700600 // #, &, %, / are common single bit error for ' that we can block
601 if (!::isprint(c) || (c == '\'') || (c == '#') || (c == '&') || (c == '%') || (c == '/')) {
Mark Salyzyna16e4372017-09-20 08:36:12 -0700602 subReason.erase(pos);
603 break;
604 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700605 }
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700606 transformReason(subReason);
Mark Salyzyn64610892017-09-18 10:41:14 -0700607 if (subReason != "") { // Will not land "reboot" as that is too blunt.
608 if (isKernelRebootReason(subReason)) {
609 ret = "reboot," + subReason; // User space can't talk kernel reasons.
Mark Salyzyndafced92017-09-20 08:37:46 -0700610 } else if (isKnownRebootReason(subReason)) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700611 ret = subReason;
Mark Salyzyndafced92017-09-20 08:37:46 -0700612 } else {
613 ret = "reboot," + subReason; // legitimize unknown reasons
Mark Salyzyn64610892017-09-18 10:41:14 -0700614 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700615 }
616 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700617
Mark Salyzyn64610892017-09-18 10:41:14 -0700618 // Check for kernel panics, allowed to override reboot command.
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700619 if (!addKernelPanicSubReason(console, ret) &&
Mark Salyzyn64610892017-09-18 10:41:14 -0700620 // check for long-press power down
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700621 ((console.rfind("Power held for ") != std::string::npos) ||
622 (console.rfind("charger: [") != std::string::npos))) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700623 ret = "cold";
624 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700625 }
626
627 // The following battery test should migrate to a default system health HAL
628
629 // Let us not worry if the reboot command was issued, for the cases of
630 // reboot -p, reboot <no reason>, reboot cold, reboot warm and reboot hard.
631 // Same for bootloader and ro.boot.bootreasons of this set, but a dead
632 // battery could conceivably lead to these, so worthy of override.
633 if (isBluntRebootReason(ret)) {
634 // Heuristic to determine if shutdown possibly because of a dead battery?
635 // Really a hail-mary pass to find it in last klog content ...
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700636 static const int battery_dead_threshold = 2; // percent
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700637 static const char battery[] = "healthd: battery l=";
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700638 const pstoreConsole console(content);
639 size_t pos = console.rfind(battery); // last one
Mark Salyzyna16e4372017-09-20 08:36:12 -0700640 std::string digits;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700641 if (pos != std::string::npos) {
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700642 digits = content.substr(pos + strlen(battery), strlen("100 "));
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700643 // correct common errors
644 correctForBer(digits, "100 ");
645 if (digits[0] == '!') digits[0] = '1';
646 if (digits[1] == '!') digits[1] = '1';
Mark Salyzyna16e4372017-09-20 08:36:12 -0700647 }
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700648 const char* endptr = digits.c_str();
649 unsigned level = 0;
650 while (::isdigit(*endptr)) {
651 level *= 10;
652 level += *endptr++ - '0';
653 // make sure no leading zeros, except zero itself, and range check.
654 if ((level == 0) || (level > 100)) break;
655 }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700656 // example bit error rate issues for 10%
657 // 'l=10 ' no bits in error
658 // 'l=00 ' single bit error (fails above)
659 // 'l=1 ' single bit error
660 // 'l=0 ' double bit error
661 // There are others, not typically critical because of 2%
662 // battery_dead_threshold. KISS check, make sure second
663 // character after digit sequence is not a space.
664 if ((level <= 100) && (endptr != digits.c_str()) && (endptr[0] == ' ') && (endptr[1] != ' ')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700665 LOG(INFO) << "Battery level at shutdown " << level << "%";
666 if (level <= battery_dead_threshold) {
667 ret = "shutdown,battery";
668 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700669 } else { // Most likely
670 digits = ""; // reset digits
671
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700672 // Content buffer no longer will have console data. Beware if more
673 // checks added below, that depend on parsing console content.
674 content = "";
675
676 LOG(DEBUG) << "Can not find last low battery in last console messages";
677 android_logcat_context ctx = create_android_logcat();
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700678 FILE* fp = android_logcat_popen(&ctx, "logcat -b kernel -v brief -d");
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700679 if (fp != nullptr) {
680 android::base::ReadFdToString(fileno(fp), &content);
681 }
682 android_logcat_pclose(&ctx, fp);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700683 static const char logcat_battery[] = "W/healthd ( 0): battery l=";
684 const char* match = logcat_battery;
685
686 if (content == "") {
687 // Service logd.klog not running, go to smaller buffer in the kernel.
688 int rc = klogctl(KLOG_SIZE_BUFFER, nullptr, 0);
689 if (rc > 0) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700690 ssize_t len = rc + 1024; // 1K Margin should it grow between calls.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700691 std::unique_ptr<char[]> buf(new char[len]);
692 rc = klogctl(KLOG_READ_ALL, buf.get(), len);
693 if (rc < len) {
694 len = rc + 1;
695 }
696 buf[--len] = '\0';
697 content = buf.get();
698 }
699 match = battery;
700 }
701
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700702 pos = content.find(match); // The first one it finds.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700703 if (pos != std::string::npos) {
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700704 digits = content.substr(pos + strlen(match), strlen("100 "));
Mark Salyzyna16e4372017-09-20 08:36:12 -0700705 }
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700706 endptr = digits.c_str();
707 level = 0;
708 while (::isdigit(*endptr)) {
709 level *= 10;
710 level += *endptr++ - '0';
711 // make sure no leading zeros, except zero itself, and range check.
712 if ((level == 0) || (level > 100)) break;
713 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700714 if ((level <= 100) && (endptr != digits.c_str()) && (*endptr == ' ')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700715 LOG(INFO) << "Battery level at startup " << level << "%";
716 if (level <= battery_dead_threshold) {
717 ret = "shutdown,battery";
718 }
719 } else {
720 LOG(DEBUG) << "Can not find first battery level in dmesg or logcat";
721 }
722 }
723 }
724
725 // Is there a controlled shutdown hint in last_reboot_reason_property?
726 if (isBluntRebootReason(ret)) {
727 // Content buffer no longer will have console data. Beware if more
728 // checks added below, that depend on parsing console content.
729 content = GetProperty(last_reboot_reason_property);
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700730 transformReason(content);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700731
Mark Salyzyn62909822017-10-09 09:27:16 -0700732 // Anything in last is better than 'super-blunt' reboot or shutdown.
733 if ((ret == "") || (ret == "reboot") || (ret == "shutdown") || !isBluntRebootReason(content)) {
734 ret = content;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700735 }
736 }
737
738 // Other System Health HAL reasons?
739
740 // ToDo: /proc/sys/kernel/boot_reason needs a HAL interface to
741 // possibly offer hardware-specific clues from the PMIC.
742 }
743
744 // If unknown left over from above, make it "reboot,<boot_reason>"
745 if (ret == "") {
746 ret = "reboot";
747 if (android::base::StartsWith(reason, "reboot")) {
748 reason = reason.substr(strlen("reboot"));
Mark Salyzyn0af71a52017-10-05 13:58:04 -0700749 while ((reason[0] == ',') || (reason[0] == '_')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700750 reason = reason.substr(1);
751 }
752 }
753 if (reason != "") {
754 ret += ",";
755 ret += reason;
756 }
757 }
758
759 LOG(INFO) << "Canonical boot reason: " << ret;
760 if (isKernelRebootReason(ret) && (GetProperty(last_reboot_reason_property) != "")) {
761 // Rewrite as it must be old news, kernel reasons trump user space.
762 SetProperty(last_reboot_reason_property, ret);
763 }
764 return ret;
765}
766
James Hawkinsb9cf7712016-04-08 15:32:19 -0700767// Returns the appropriate metric key prefix for the boot_complete metric such
768// that boot metrics after a system update are labeled as ota_boot_complete;
769// otherwise, they are labeled as boot_complete. This method encapsulates the
770// bookkeeping required to track when a system update has occurred by storing
771// the UTC timestamp of the system build date and comparing against the current
772// system build date.
773std::string CalculateBootCompletePrefix() {
774 static const std::string kBuildDateKey = "build_date";
775 std::string boot_complete_prefix = "boot_complete";
776
777 std::string build_date_str = GetProperty("ro.build.date.utc");
James Hawkins4dded612016-07-28 11:50:23 -0700778 int32_t build_date;
Elliott Hughesda46b392016-10-11 17:09:00 -0700779 if (!android::base::ParseInt(build_date_str, &build_date)) {
James Hawkins4dded612016-07-28 11:50:23 -0700780 return std::string();
781 }
James Hawkinsb9cf7712016-04-08 15:32:19 -0700782
783 BootEventRecordStore boot_event_store;
784 BootEventRecordStore::BootEventRecord record;
James Hawkins0bc4ad42017-05-30 15:03:15 -0700785 if (!boot_event_store.GetBootEvent(kBuildDateKey, &record)) {
786 boot_complete_prefix = "factory_reset_" + boot_complete_prefix;
787 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700788 LOG(INFO) << "Canonical boot reason: reboot,factory_reset";
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700789 SetProperty(system_reboot_reason_property, "reboot,factory_reset");
James Hawkins0bc4ad42017-05-30 15:03:15 -0700790 } else if (build_date != record.second) {
James Hawkinsb9cf7712016-04-08 15:32:19 -0700791 boot_complete_prefix = "ota_" + boot_complete_prefix;
792 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700793 LOG(INFO) << "Canonical boot reason: reboot,ota";
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700794 SetProperty(system_reboot_reason_property, "reboot,ota");
James Hawkinsb9cf7712016-04-08 15:32:19 -0700795 }
796
797 return boot_complete_prefix;
798}
799
James Hawkinsef0a0902017-01-06 14:38:23 -0800800// Records the value of a given ro.boottime.init property in milliseconds.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700801void RecordInitBootTimeProp(BootEventRecordStore* boot_event_store, const char* property) {
James Hawkinsef0a0902017-01-06 14:38:23 -0800802 std::string value = GetProperty(property);
803
James Hawkins27c05222017-01-26 11:55:44 -0800804 int32_t time_in_ms;
805 if (android::base::ParseInt(value, &time_in_ms)) {
James Hawkinsef0a0902017-01-06 14:38:23 -0800806 boot_event_store->AddBootEventWithValue(property, time_in_ms);
807 }
808}
809
James Hawkins1bfcaec2017-05-19 14:27:27 -0700810// A map from bootloader timing stage to the time that stage took during boot.
811typedef std::map<std::string, int32_t> BootloaderTimingMap;
812
813// Returns a mapping from bootloader stage names to the time those stages
814// took to boot.
815const BootloaderTimingMap GetBootLoaderTimings() {
816 BootloaderTimingMap timings;
817
818 // |ro.boot.boottime| is of the form 'stage1:time1,...,stageN:timeN',
819 // where timeN is in milliseconds.
James Hawkinsbe46fd12017-02-02 16:21:25 -0800820 std::string value = GetProperty("ro.boot.boottime");
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800821 if (value.empty()) {
822 // ro.boot.boottime is not reported on all devices.
James Hawkins1bfcaec2017-05-19 14:27:27 -0700823 return BootloaderTimingMap();
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800824 }
James Hawkinsbe46fd12017-02-02 16:21:25 -0800825
826 auto stages = android::base::Split(value, ",");
James Hawkins1bfcaec2017-05-19 14:27:27 -0700827 for (const auto& stageTiming : stages) {
James Hawkinsbe46fd12017-02-02 16:21:25 -0800828 // |stageTiming| is of the form 'stage:time'.
829 auto stageTimingValues = android::base::Split(stageTiming, ":");
James Hawkins0bc4ad42017-05-30 15:03:15 -0700830 DCHECK_EQ(2U, stageTimingValues.size());
James Hawkinsbe46fd12017-02-02 16:21:25 -0800831
832 std::string stageName = stageTimingValues[0];
833 int32_t time_ms;
834 if (android::base::ParseInt(stageTimingValues[1], &time_ms)) {
James Hawkins1bfcaec2017-05-19 14:27:27 -0700835 timings[stageName] = time_ms;
James Hawkinsbe46fd12017-02-02 16:21:25 -0800836 }
837 }
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800838
James Hawkins1bfcaec2017-05-19 14:27:27 -0700839 return timings;
840}
841
842// Parses and records the set of bootloader stages and associated boot times
843// from the ro.boot.boottime system property.
844void RecordBootloaderTimings(BootEventRecordStore* boot_event_store,
845 const BootloaderTimingMap& bootloader_timings) {
846 int32_t total_time = 0;
847 for (const auto& timing : bootloader_timings) {
848 total_time += timing.second;
849 boot_event_store->AddBootEventWithValue("boottime.bootloader." + timing.first, timing.second);
850 }
851
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800852 boot_event_store->AddBootEventWithValue("boottime.bootloader.total", total_time);
James Hawkinsbe46fd12017-02-02 16:21:25 -0800853}
854
James Hawkins1bfcaec2017-05-19 14:27:27 -0700855// Records the closest estimation to the absolute device boot time, i.e.,
856// from power on to boot_complete, including bootloader times.
857void RecordAbsoluteBootTime(BootEventRecordStore* boot_event_store,
858 const BootloaderTimingMap& bootloader_timings,
859 std::chrono::milliseconds uptime) {
860 int32_t bootloader_time_ms = 0;
861
862 for (const auto& timing : bootloader_timings) {
863 if (timing.first.compare("SW") != 0) {
864 bootloader_time_ms += timing.second;
865 }
866 }
867
868 auto bootloader_duration = std::chrono::milliseconds(bootloader_time_ms);
869 auto absolute_total =
870 std::chrono::duration_cast<std::chrono::seconds>(bootloader_duration + uptime);
871 boot_event_store->AddBootEventWithValue("absolute_boot_time", absolute_total.count());
872}
873
James Hawkinsc08e9962016-03-11 14:59:50 -0800874// Records several metrics related to the time it takes to boot the device,
875// including disambiguating boot time on encrypted or non-encrypted devices.
876void RecordBootComplete() {
877 BootEventRecordStore boot_event_store;
James Hawkinsb9cf7712016-04-08 15:32:19 -0700878 BootEventRecordStore::BootEventRecord record;
James Hawkins2d8b3e62016-04-14 14:13:20 -0700879
James Hawkins1bfcaec2017-05-19 14:27:27 -0700880 auto time_since_epoch = android::base::boot_clock::now().time_since_epoch();
881 auto uptime = std::chrono::duration_cast<std::chrono::seconds>(time_since_epoch);
James Hawkins2d8b3e62016-04-14 14:13:20 -0700882 time_t current_time_utc = time(nullptr);
883
884 if (boot_event_store.GetBootEvent("last_boot_time_utc", &record)) {
885 time_t last_boot_time_utc = record.second;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700886 time_t time_since_last_boot = difftime(current_time_utc, last_boot_time_utc);
887 boot_event_store.AddBootEventWithValue("time_since_last_boot", time_since_last_boot);
James Hawkins2d8b3e62016-04-14 14:13:20 -0700888 }
889
890 boot_event_store.AddBootEventWithValue("last_boot_time_utc", current_time_utc);
James Hawkinsc08e9962016-03-11 14:59:50 -0800891
James Hawkinsb9cf7712016-04-08 15:32:19 -0700892 // The boot_complete metric has two variants: boot_complete and
893 // ota_boot_complete. The latter signifies that the device is booting after
894 // a system update.
895 std::string boot_complete_prefix = CalculateBootCompletePrefix();
James Hawkins4dded612016-07-28 11:50:23 -0700896 if (boot_complete_prefix.empty()) {
897 // The system is hosed because the build date property could not be read.
898 return;
899 }
James Hawkinsc08e9962016-03-11 14:59:50 -0800900
901 // post_decrypt_time_elapsed is only logged on encrypted devices.
902 if (boot_event_store.GetBootEvent("post_decrypt_time_elapsed", &record)) {
903 // Log the amount of time elapsed until the device is decrypted, which
904 // includes the variable amount of time the user takes to enter the
905 // decryption password.
James Hawkinse78ea772017-03-24 11:43:02 -0700906 boot_event_store.AddBootEventWithValue("boot_decryption_complete", uptime.count());
James Hawkinsc08e9962016-03-11 14:59:50 -0800907
908 // Subtract the decryption time to normalize the boot cycle timing.
James Hawkinse78ea772017-03-24 11:43:02 -0700909 std::chrono::seconds boot_complete = std::chrono::seconds(uptime.count() - record.second);
James Hawkinsb9cf7712016-04-08 15:32:19 -0700910 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_post_decrypt",
James Hawkinse78ea772017-03-24 11:43:02 -0700911 boot_complete.count());
James Hawkinsc08e9962016-03-11 14:59:50 -0800912 } else {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700913 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_no_encryption", uptime.count());
James Hawkinsc08e9962016-03-11 14:59:50 -0800914 }
915
916 // Record the total time from device startup to boot complete, regardless of
917 // encryption state.
James Hawkinse78ea772017-03-24 11:43:02 -0700918 boot_event_store.AddBootEventWithValue(boot_complete_prefix, uptime.count());
James Hawkinsef0a0902017-01-06 14:38:23 -0800919
920 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init");
921 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.selinux");
922 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.cold_boot_wait");
James Hawkinsbe46fd12017-02-02 16:21:25 -0800923
James Hawkins1bfcaec2017-05-19 14:27:27 -0700924 const BootloaderTimingMap bootloader_timings = GetBootLoaderTimings();
925 RecordBootloaderTimings(&boot_event_store, bootloader_timings);
926
927 auto uptime_ms = std::chrono::duration_cast<std::chrono::milliseconds>(time_since_epoch);
928 RecordAbsoluteBootTime(&boot_event_store, bootloader_timings, uptime_ms);
James Hawkinsc08e9962016-03-11 14:59:50 -0800929}
930
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800931// Records the boot_reason metric by querying the ro.boot.bootreason system
932// property.
933void RecordBootReason() {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700934 const std::string reason(GetProperty(bootloader_reboot_reason_property));
James Hawkins25f71222017-10-10 16:37:05 -0700935
936 if (reason.empty()) {
937 // Log an empty boot reason value as '<EMPTY>' to ensure the value is intentional
938 // (and not corruption anywhere else in the reporting pipeline).
939 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
940 android::metricslogger::FIELD_PLATFORM_REASON, "<EMPTY>");
941 } else {
942 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
943 android::metricslogger::FIELD_PLATFORM_REASON, reason);
944 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700945
946 // Log the raw bootloader_boot_reason property value.
947 int32_t boot_reason = BootReasonStrToEnum(reason);
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800948 BootEventRecordStore boot_event_store;
949 boot_event_store.AddBootEventWithValue("boot_reason", boot_reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700950
951 // Log the scrubbed system_boot_reason.
952 const std::string system_reason(BootReasonStrToReason(reason));
953 int32_t system_boot_reason = BootReasonStrToEnum(system_reason);
954 boot_event_store.AddBootEventWithValue("system_boot_reason", system_boot_reason);
955
956 // Record the scrubbed system_boot_reason to the property
957 SetProperty(system_reboot_reason_property, system_reason);
958 if (reason == "") {
959 SetProperty(bootloader_reboot_reason_property, system_reason);
960 }
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800961}
962
James Hawkins500d7152016-02-16 15:05:54 -0800963// Records two metrics related to the user resetting a device: the time at
964// which the device is reset, and the time since the user last reset the
965// device. The former is only set once per-factory reset.
966void RecordFactoryReset() {
967 BootEventRecordStore boot_event_store;
968 BootEventRecordStore::BootEventRecord record;
969
970 time_t current_time_utc = time(nullptr);
971
James Hawkins0660b302016-03-08 16:18:15 -0800972 if (current_time_utc < 0) {
973 // UMA does not display negative values in buckets, so convert to positive.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700974 android::metricslogger::LogHistogram("factory_reset_current_time_failure",
975 std::abs(current_time_utc));
James Hawkinsfff95ba2016-03-29 16:13:49 -0700976
James Hawkins9aec9262017-01-31 11:42:24 -0800977 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -0700978 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700979 boot_event_store.AddBootEventWithValue("factory_reset_current_time_failure",
980 std::abs(current_time_utc));
James Hawkins0660b302016-03-08 16:18:15 -0800981 return;
982 } else {
James Hawkins9aec9262017-01-31 11:42:24 -0800983 android::metricslogger::LogHistogram("factory_reset_current_time", current_time_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -0700984
James Hawkins9aec9262017-01-31 11:42:24 -0800985 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -0700986 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700987 boot_event_store.AddBootEventWithValue("factory_reset_current_time", current_time_utc);
James Hawkins0660b302016-03-08 16:18:15 -0800988 }
989
James Hawkins500d7152016-02-16 15:05:54 -0800990 // The factory_reset boot event does not exist after the device is reset, so
991 // use this signal to mark the time of the factory reset.
992 if (!boot_event_store.GetBootEvent("factory_reset", &record)) {
993 boot_event_store.AddBootEventWithValue("factory_reset", current_time_utc);
James Hawkins3bf9b142016-03-03 14:50:24 -0800994
995 // Don't log the time_since_factory_reset until some time has elapsed.
996 // The data is not meaningful yet and skews the histogram buckets.
James Hawkins500d7152016-02-16 15:05:54 -0800997 return;
998 }
999
1000 // Calculate and record the difference in time between now and the
1001 // factory_reset time.
1002 time_t factory_reset_utc = record.second;
James Hawkins9aec9262017-01-31 11:42:24 -08001003 android::metricslogger::LogHistogram("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001004
James Hawkins9aec9262017-01-31 11:42:24 -08001005 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001006 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001007 boot_event_store.AddBootEventWithValue("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001008
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001009 time_t time_since_factory_reset = difftime(current_time_utc, factory_reset_utc);
1010 boot_event_store.AddBootEventWithValue("time_since_factory_reset", time_since_factory_reset);
James Hawkins500d7152016-02-16 15:05:54 -08001011}
1012
James Hawkinsabd73e62016-01-19 15:10:38 -08001013} // namespace
1014
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001015int main(int argc, char** argv) {
James Hawkinsabd73e62016-01-19 15:10:38 -08001016 android::base::InitLogging(argv);
1017
1018 const std::string cmd_line = GetCommandLine(argc, argv);
1019 LOG(INFO) << "Service started: " << cmd_line;
1020
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001021 int option_index = 0;
James Hawkinsc6275582016-03-22 10:47:44 -07001022 static const char value_str[] = "value";
James Hawkinsc08e9962016-03-11 14:59:50 -08001023 static const char boot_complete_str[] = "record_boot_complete";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001024 static const char boot_reason_str[] = "record_boot_reason";
James Hawkins53684ea2016-02-23 16:18:19 -08001025 static const char factory_reset_str[] = "record_time_since_factory_reset";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001026 static const struct option long_options[] = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001027 // clang-format off
1028 { "help", no_argument, NULL, 'h' },
1029 { "log", no_argument, NULL, 'l' },
1030 { "print", no_argument, NULL, 'p' },
1031 { "record", required_argument, NULL, 'r' },
1032 { value_str, required_argument, NULL, 0 },
1033 { boot_complete_str, no_argument, NULL, 0 },
1034 { boot_reason_str, no_argument, NULL, 0 },
1035 { factory_reset_str, no_argument, NULL, 0 },
1036 { NULL, 0, NULL, 0 }
1037 // clang-format on
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001038 };
1039
James Hawkinsc6275582016-03-22 10:47:44 -07001040 std::string boot_event;
1041 std::string value;
James Hawkinsabd73e62016-01-19 15:10:38 -08001042 int opt = 0;
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001043 while ((opt = getopt_long(argc, argv, "hlpr:", long_options, &option_index)) != -1) {
James Hawkinsabd73e62016-01-19 15:10:38 -08001044 switch (opt) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001045 // This case handles long options which have no single-character mapping.
1046 case 0: {
1047 const std::string option_name = long_options[option_index].name;
James Hawkinsc6275582016-03-22 10:47:44 -07001048 if (option_name == value_str) {
1049 // |optarg| is an external variable set by getopt representing
1050 // the option argument.
1051 value = optarg;
1052 } else if (option_name == boot_complete_str) {
James Hawkinsc08e9962016-03-11 14:59:50 -08001053 RecordBootComplete();
1054 } else if (option_name == boot_reason_str) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001055 RecordBootReason();
James Hawkins500d7152016-02-16 15:05:54 -08001056 } else if (option_name == factory_reset_str) {
1057 RecordFactoryReset();
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001058 } else {
1059 LOG(ERROR) << "Invalid option: " << option_name;
1060 }
1061 break;
1062 }
1063
James Hawkinsabd73e62016-01-19 15:10:38 -08001064 case 'h': {
1065 ShowHelp(argv[0]);
1066 break;
1067 }
1068
1069 case 'l': {
1070 LogBootEvents();
1071 break;
1072 }
1073
1074 case 'p': {
1075 PrintBootEvents();
1076 break;
1077 }
1078
1079 case 'r': {
1080 // |optarg| is an external variable set by getopt representing
1081 // the option argument.
James Hawkinsc6275582016-03-22 10:47:44 -07001082 boot_event = optarg;
James Hawkinsabd73e62016-01-19 15:10:38 -08001083 break;
1084 }
1085
1086 default: {
1087 DCHECK_EQ(opt, '?');
1088
1089 // |optopt| is an external variable set by getopt representing
1090 // the value of the invalid option.
1091 LOG(ERROR) << "Invalid option: " << optopt;
1092 ShowHelp(argv[0]);
1093 return EXIT_FAILURE;
1094 }
1095 }
1096 }
1097
James Hawkinsc6275582016-03-22 10:47:44 -07001098 if (!boot_event.empty()) {
1099 RecordBootEventFromCommandLine(boot_event, value);
1100 }
1101
James Hawkinsabd73e62016-01-19 15:10:38 -08001102 return 0;
1103}