blob: ae0a401edbb396685b3ca9f9a3a92de939750cde [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 Hawkins00433a22017-12-04 14:20:21 -0800245 {"reboot_smpl", 105},
246 {"watchdog_sdi_apps_reset", 106},
247 {"smpl", 107},
248 {"oem_modem_failed_to_powerup", 108},
James Hawkinse2c27242017-12-18 13:40:27 -0800249 {"reboot_normal", 109},
250 {"oem_lpass_cfg", 110},
251 {"oem_xpu_ns_error", 111},
252 {"power_key_press", 112},
253 {"hardware_reset", 113},
254 {"reboot_by_powerkey", 114},
255 {"reboot_verity", 115},
256 {"oem_rpm_undef_error", 116},
257 {"oem_crash_on_the_lk", 117},
258 {"oem_rpm_reset", 118},
259 {"oem_lpass_cfg", 119},
260 {"oem_xpu_ns_error", 120},
261 {"factory_cable", 121},
262 {"oem_ar6320_failed_to_powerup", 122},
263 {"watchdog_rpm_bite", 123},
264 {"power_on_cable", 124},
265 {"reboot_unknown", 125},
266 {"wireless_charger", 126},
267 {"0x776655ff", 127},
268 {"oem_thermal_bite_reset", 128},
269 {"charger", 129},
270 {"pon1", 130},
271 {"unknown", 131},
272 {"reboot_rtc", 132},
273 {"cold_boot", 133},
274 {"hard_rst", 134},
James Hawkinsb607dae2018-01-05 14:42:55 -0800275 {"power-on", 135},
276 {"oem_adsp_resetting_the_soc", 136},
277 {"kpdpwr", 137},
278 {"oem_modem_timeout_waiting", 138},
279 {"usb_chg", 139},
280 {"warm_reset_0x02", 140},
281 {"warm_reset_0x80", 141},
282 {"pon_reason_0xb0", 142},
283 {"reboot_download", 143},
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800284};
285
286// Converts a string value representing the reason the system booted to an
287// integer representation. This is necessary for logging the boot_reason metric
288// via Tron, which does not accept non-integer buckets in histograms.
289int32_t BootReasonStrToEnum(const std::string& boot_reason) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800290 auto mapping = kBootReasonMap.find(boot_reason);
291 if (mapping != kBootReasonMap.end()) {
292 return mapping->second;
293 }
294
James Hawkins25f71222017-10-10 16:37:05 -0700295 if (boot_reason.empty()) {
296 return kEmptyBootReason;
297 }
298
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800299 LOG(INFO) << "Unknown boot reason: " << boot_reason;
300 return kUnknownBootReason;
301}
302
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700303// Canonical list of supported primary reboot reasons.
304const std::vector<const std::string> knownReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700305 // clang-format off
306 // kernel
307 "watchdog",
308 "kernel_panic",
309 // strong
310 "recovery", // Should not happen from ro.boot.bootreason
311 "bootloader", // Should not happen from ro.boot.bootreason
312 // blunt
313 "cold",
314 "hard",
315 "warm",
Mark Salyzyn62909822017-10-09 09:27:16 -0700316 // super blunt
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700317 "shutdown", // Can not happen from ro.boot.bootreason
318 "reboot", // Default catch-all for anything unknown
319 // clang-format on
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700320};
321
322// Returns true if the supplied reason prefix is considered detailed enough.
323bool isStrongRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700324 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700325 if (s == "cold") break;
326 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800327 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700328 return true;
329 }
330 }
331 return false;
332}
333
334// Returns true if the supplied reason prefix is associated with the kernel.
335bool isKernelRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700336 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700337 if (s == "recovery") break;
338 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800339 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700340 return true;
341 }
342 }
343 return false;
344}
345
346// Returns true if the supplied reason prefix is considered known.
347bool isKnownRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700348 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700349 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800350 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700351 return true;
352 }
353 }
354 return false;
355}
356
357// If the reboot reason should be improved, report true if is too blunt.
358bool isBluntRebootReason(const std::string& r) {
359 if (isStrongRebootReason(r)) return false;
360
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700361 if (!isKnownRebootReason(r)) return true; // Can not support unknown as detail
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700362
363 size_t pos = 0;
364 while ((pos = r.find(',', pos)) != std::string::npos) {
365 ++pos;
366 std::string next(r.substr(pos));
367 if (next.length() == 0) break;
368 if (next[0] == ',') continue;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700369 if (!isKnownRebootReason(next)) return false; // Unknown subreason is good.
370 if (isStrongRebootReason(next)) return false; // eg: reboot,reboot
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700371 }
372 return true;
373}
374
Mark Salyzyn64610892017-09-18 10:41:14 -0700375bool readPstoreConsole(std::string& console) {
376 if (android::base::ReadFileToString("/sys/fs/pstore/console-ramoops-0", &console)) {
377 return true;
378 }
379 return android::base::ReadFileToString("/sys/fs/pstore/console-ramoops", &console);
380}
381
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700382// Implement a variant of std::string::rfind that is resilient to errors in
383// the data stream being inspected.
384class pstoreConsole {
385 private:
386 const size_t kBitErrorRate = 8; // number of bits per error
387 const std::string& console;
388
389 // Number of bits that differ between the two arguments l and r.
390 // Returns zero if the values for l and r are identical.
391 size_t numError(uint8_t l, uint8_t r) const { return std::bitset<8>(l ^ r).count(); }
392
393 // A string comparison function, reports the number of errors discovered
394 // in the match to a maximum of the bitLength / kBitErrorRate, at that
395 // point returning npos to indicate match is too poor.
396 //
397 // Since called in rfind which works backwards, expect cache locality will
398 // help if we check in reverse here as well for performance.
399 //
400 // Assumption: l (from console.c_str() + pos) is long enough to house
401 // _r.length(), checked in rfind caller below.
402 //
403 size_t numError(size_t pos, const std::string& _r) const {
404 const char* l = console.c_str() + pos;
405 const char* r = _r.c_str();
406 size_t n = _r.length();
407 const uint8_t* le = reinterpret_cast<const uint8_t*>(l) + n;
408 const uint8_t* re = reinterpret_cast<const uint8_t*>(r) + n;
409 size_t count = 0;
410 n = 0;
411 do {
412 // individual character bit error rate > threshold + slop
413 size_t num = numError(*--le, *--re);
414 if (num > ((8 + kBitErrorRate) / kBitErrorRate)) return std::string::npos;
415 // total bit error rate > threshold + slop
416 count += num;
417 ++n;
418 if (count > ((n * 8 + kBitErrorRate - (n > 2)) / kBitErrorRate)) {
419 return std::string::npos;
420 }
421 } while (le != reinterpret_cast<const uint8_t*>(l));
422 return count;
423 }
424
425 public:
426 explicit pstoreConsole(const std::string& console) : console(console) {}
427 // scope of argument must be equal to or greater than scope of pstoreConsole
428 explicit pstoreConsole(const std::string&& console) = delete;
429 explicit pstoreConsole(std::string&& console) = delete;
430
431 // Our implementation of rfind, use exact match first, then resort to fuzzy.
432 size_t rfind(const std::string& needle) const {
433 size_t pos = console.rfind(needle); // exact match?
434 if (pos != std::string::npos) return pos;
435
436 // Check to make sure needle fits in console string.
437 pos = console.length();
438 if (needle.length() > pos) return std::string::npos;
439 pos -= needle.length();
440 // fuzzy match to maximum kBitErrorRate
Ivan Lozano44d3cac2017-11-07 13:13:55 -0800441 for (;;) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700442 if (numError(pos, needle) != std::string::npos) return pos;
Ivan Lozano44d3cac2017-11-07 13:13:55 -0800443 if (pos == 0) break;
444 --pos;
445 }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700446 return std::string::npos;
447 }
448
449 // Our implementation of find, use only fuzzy match.
450 size_t find(const std::string& needle, size_t start = 0) const {
451 // Check to make sure needle fits in console string.
452 if (needle.length() > console.length()) return std::string::npos;
453 const size_t last_pos = console.length() - needle.length();
454 // fuzzy match to maximum kBitErrorRate
455 for (size_t pos = start; pos <= last_pos; ++pos) {
456 if (numError(pos, needle) != std::string::npos) return pos;
457 }
458 return std::string::npos;
459 }
460};
461
462// If bit error match to needle, correct it.
463// Return true if any corrections were discovered and applied.
464bool correctForBer(std::string& reason, const std::string& needle) {
465 bool corrected = false;
466 if (reason.length() < needle.length()) return corrected;
467 const pstoreConsole console(reason);
468 const size_t last_pos = reason.length() - needle.length();
469 for (size_t pos = 0; pos <= last_pos; pos += needle.length()) {
470 pos = console.find(needle, pos);
471 if (pos == std::string::npos) break;
472
473 // exact match has no malice
474 if (needle == reason.substr(pos, needle.length())) continue;
475
476 corrected = true;
477 reason = reason.substr(0, pos) + needle + reason.substr(pos + needle.length());
478 }
479 return corrected;
480}
481
482bool addKernelPanicSubReason(const pstoreConsole& console, std::string& ret) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700483 // Check for kernel panic types to refine information
484 if (console.rfind("SysRq : Trigger a crash") != std::string::npos) {
485 // Can not happen, except on userdebug, during testing/debugging.
486 ret = "kernel_panic,sysrq";
487 return true;
488 }
489 if (console.rfind("Unable to handle kernel NULL pointer dereference at virtual address") !=
490 std::string::npos) {
491 ret = "kernel_panic,NULL";
492 return true;
493 }
494 if (console.rfind("Kernel BUG at ") != std::string::npos) {
495 ret = "kernel_panic,BUG";
496 return true;
497 }
498 return false;
499}
500
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700501bool addKernelPanicSubReason(const std::string& content, std::string& ret) {
502 return addKernelPanicSubReason(pstoreConsole(content), ret);
503}
504
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700505// std::transform Helper callback functions:
506// Converts a string value representing the reason the system booted to a
507// string complying with Android system standard reason.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700508char tounderline(char c) {
509 return ::isblank(c) ? '_' : c;
510}
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700511
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700512char toprintable(char c) {
513 return ::isprint(c) ? c : '?';
514}
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700515
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700516// Cleanup boot_reason regarding acceptable character set
517void transformReason(std::string& reason) {
518 std::transform(reason.begin(), reason.end(), reason.begin(), ::tolower);
519 std::transform(reason.begin(), reason.end(), reason.begin(), tounderline);
520 std::transform(reason.begin(), reason.end(), reason.begin(), toprintable);
521}
522
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700523const char system_reboot_reason_property[] = "sys.boot.reason";
524const char last_reboot_reason_property[] = LAST_REBOOT_REASON_PROPERTY;
525const char bootloader_reboot_reason_property[] = "ro.boot.bootreason";
526
527// Scrub, Sanitize, Standardize and Enhance the boot reason string supplied.
528std::string BootReasonStrToReason(const std::string& boot_reason) {
Mark Salyzyna16e4372017-09-20 08:36:12 -0700529 static const size_t max_reason_length = 256;
530
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700531 std::string ret(GetProperty(system_reboot_reason_property));
532 std::string reason(boot_reason);
533 // If sys.boot.reason == ro.boot.bootreason, let's re-evaluate
534 if (reason == ret) ret = "";
535
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700536 transformReason(reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700537
538 // Is the current system boot reason sys.boot.reason valid?
539 if (!isKnownRebootReason(ret)) ret = "";
540
541 if (ret == "") {
542 // Is the bootloader boot reason ro.boot.bootreason known?
543 std::vector<std::string> words(android::base::Split(reason, ",_-"));
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700544 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700545 std::string blunt;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700546 for (auto& r : words) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700547 if (r == s) {
548 if (isBluntRebootReason(s)) {
549 blunt = s;
550 } else {
551 ret = s;
552 break;
553 }
554 }
555 }
556 if (ret == "") ret = blunt;
557 if (ret != "") break;
558 }
559 }
560
561 if (ret == "") {
562 // A series of checks to take some officially unsupported reasons
563 // reported by the bootloader and find some logical and canonical
564 // sense. In an ideal world, we would require those bootloaders
565 // to behave and follow our standards.
566 static const std::vector<std::pair<const std::string, const std::string>> aliasReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700567 {"watchdog", "wdog"},
568 {"cold,powerkey", "powerkey"},
569 {"kernel_panic", "panic"},
570 {"shutdown,thermal", "thermal"},
571 {"warm,s3_wakeup", "s3_wakeup"},
572 {"hard,hw_reset", "hw_reset"},
Mark Salyzyncabbe4f2017-10-23 13:52:39 -0700573 {"reboot,2sec", "2sec_reboot"},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700574 {"bootloader", ""},
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700575 };
576
577 // Either the primary or alias is found _somewhere_ in the reason string.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700578 for (auto& s : aliasReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700579 if (reason.find(s.first) != std::string::npos) {
580 ret = s.first;
581 break;
582 }
583 if (s.second.size() && (reason.find(s.second) != std::string::npos)) {
584 ret = s.first;
585 break;
586 }
587 }
588 }
589
590 // If watchdog is the reason, see if there is a security angle?
591 if (ret == "watchdog") {
592 if (reason.find("sec") != std::string::npos) {
593 ret += ",security";
594 }
595 }
596
Mark Salyzyn64610892017-09-18 10:41:14 -0700597 if (ret == "kernel_panic") {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700598 // Check to see if last klog has some refinement hints.
599 std::string content;
Mark Salyzyn64610892017-09-18 10:41:14 -0700600 if (readPstoreConsole(content)) {
601 addKernelPanicSubReason(content, ret);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700602 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700603 } else if (isBluntRebootReason(ret)) {
604 // Check the other available reason resources if the reason is still blunt.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700605
Mark Salyzyn64610892017-09-18 10:41:14 -0700606 // Check to see if last klog has some refinement hints.
607 std::string content;
608 if (readPstoreConsole(content)) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700609 const pstoreConsole console(content);
Mark Salyzyn64610892017-09-18 10:41:14 -0700610 // The toybox reboot command used directly (unlikely)? But also
611 // catches init's response to Android's more controlled reboot command.
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700612 if (console.rfind("reboot: Power down") != std::string::npos) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700613 ret = "shutdown"; // Still too blunt, but more accurate.
614 // ToDo: init should record the shutdown reason to kernel messages ala:
615 // init: shutdown system with command 'last_reboot_reason'
616 // so that if pstore has persistence we can get some details
617 // that could be missing in last_reboot_reason_property.
618 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700619
Mark Salyzyn64610892017-09-18 10:41:14 -0700620 static const char cmd[] = "reboot: Restarting system with command '";
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700621 size_t pos = console.rfind(cmd);
Mark Salyzyn64610892017-09-18 10:41:14 -0700622 if (pos != std::string::npos) {
623 pos += strlen(cmd);
Mark Salyzyna16e4372017-09-20 08:36:12 -0700624 std::string subReason(content.substr(pos, max_reason_length));
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700625 // Correct against any known strings that Bit Error Match
626 for (const auto& s : knownReasons) {
627 correctForBer(subReason, s);
628 }
629 for (const auto& m : kBootReasonMap) {
630 if (m.first.length() <= strlen("cold")) continue; // too short?
631 if (correctForBer(subReason, m.first + "'")) continue;
632 if (m.first.length() <= strlen("reboot,cold")) continue; // short?
633 if (!android::base::StartsWith(m.first, "reboot,")) continue;
634 correctForBer(subReason, m.first.substr(strlen("reboot,")) + "'");
635 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700636 for (pos = 0; pos < subReason.length(); ++pos) {
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700637 char c = subReason[pos];
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700638 // #, &, %, / are common single bit error for ' that we can block
639 if (!::isprint(c) || (c == '\'') || (c == '#') || (c == '&') || (c == '%') || (c == '/')) {
Mark Salyzyna16e4372017-09-20 08:36:12 -0700640 subReason.erase(pos);
641 break;
642 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700643 }
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700644 transformReason(subReason);
Mark Salyzyn64610892017-09-18 10:41:14 -0700645 if (subReason != "") { // Will not land "reboot" as that is too blunt.
646 if (isKernelRebootReason(subReason)) {
647 ret = "reboot," + subReason; // User space can't talk kernel reasons.
Mark Salyzyndafced92017-09-20 08:37:46 -0700648 } else if (isKnownRebootReason(subReason)) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700649 ret = subReason;
Mark Salyzyndafced92017-09-20 08:37:46 -0700650 } else {
651 ret = "reboot," + subReason; // legitimize unknown reasons
Mark Salyzyn64610892017-09-18 10:41:14 -0700652 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700653 }
654 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700655
Mark Salyzyn64610892017-09-18 10:41:14 -0700656 // Check for kernel panics, allowed to override reboot command.
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700657 if (!addKernelPanicSubReason(console, ret) &&
Mark Salyzyn64610892017-09-18 10:41:14 -0700658 // check for long-press power down
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700659 ((console.rfind("Power held for ") != std::string::npos) ||
660 (console.rfind("charger: [") != std::string::npos))) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700661 ret = "cold";
662 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700663 }
664
665 // The following battery test should migrate to a default system health HAL
666
667 // Let us not worry if the reboot command was issued, for the cases of
668 // reboot -p, reboot <no reason>, reboot cold, reboot warm and reboot hard.
669 // Same for bootloader and ro.boot.bootreasons of this set, but a dead
670 // battery could conceivably lead to these, so worthy of override.
671 if (isBluntRebootReason(ret)) {
672 // Heuristic to determine if shutdown possibly because of a dead battery?
673 // Really a hail-mary pass to find it in last klog content ...
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700674 static const int battery_dead_threshold = 2; // percent
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700675 static const char battery[] = "healthd: battery l=";
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700676 const pstoreConsole console(content);
677 size_t pos = console.rfind(battery); // last one
Mark Salyzyna16e4372017-09-20 08:36:12 -0700678 std::string digits;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700679 if (pos != std::string::npos) {
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700680 digits = content.substr(pos + strlen(battery), strlen("100 "));
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700681 // correct common errors
682 correctForBer(digits, "100 ");
683 if (digits[0] == '!') digits[0] = '1';
684 if (digits[1] == '!') digits[1] = '1';
Mark Salyzyna16e4372017-09-20 08:36:12 -0700685 }
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700686 const char* endptr = digits.c_str();
687 unsigned level = 0;
688 while (::isdigit(*endptr)) {
689 level *= 10;
690 level += *endptr++ - '0';
691 // make sure no leading zeros, except zero itself, and range check.
692 if ((level == 0) || (level > 100)) break;
693 }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700694 // example bit error rate issues for 10%
695 // 'l=10 ' no bits in error
696 // 'l=00 ' single bit error (fails above)
697 // 'l=1 ' single bit error
698 // 'l=0 ' double bit error
699 // There are others, not typically critical because of 2%
700 // battery_dead_threshold. KISS check, make sure second
701 // character after digit sequence is not a space.
702 if ((level <= 100) && (endptr != digits.c_str()) && (endptr[0] == ' ') && (endptr[1] != ' ')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700703 LOG(INFO) << "Battery level at shutdown " << level << "%";
704 if (level <= battery_dead_threshold) {
705 ret = "shutdown,battery";
706 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700707 } else { // Most likely
708 digits = ""; // reset digits
709
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700710 // Content buffer no longer will have console data. Beware if more
711 // checks added below, that depend on parsing console content.
712 content = "";
713
714 LOG(DEBUG) << "Can not find last low battery in last console messages";
715 android_logcat_context ctx = create_android_logcat();
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700716 FILE* fp = android_logcat_popen(&ctx, "logcat -b kernel -v brief -d");
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700717 if (fp != nullptr) {
718 android::base::ReadFdToString(fileno(fp), &content);
719 }
720 android_logcat_pclose(&ctx, fp);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700721 static const char logcat_battery[] = "W/healthd ( 0): battery l=";
722 const char* match = logcat_battery;
723
724 if (content == "") {
725 // Service logd.klog not running, go to smaller buffer in the kernel.
726 int rc = klogctl(KLOG_SIZE_BUFFER, nullptr, 0);
727 if (rc > 0) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700728 ssize_t len = rc + 1024; // 1K Margin should it grow between calls.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700729 std::unique_ptr<char[]> buf(new char[len]);
730 rc = klogctl(KLOG_READ_ALL, buf.get(), len);
731 if (rc < len) {
732 len = rc + 1;
733 }
734 buf[--len] = '\0';
735 content = buf.get();
736 }
737 match = battery;
738 }
739
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700740 pos = content.find(match); // The first one it finds.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700741 if (pos != std::string::npos) {
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700742 digits = content.substr(pos + strlen(match), strlen("100 "));
Mark Salyzyna16e4372017-09-20 08:36:12 -0700743 }
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700744 endptr = digits.c_str();
745 level = 0;
746 while (::isdigit(*endptr)) {
747 level *= 10;
748 level += *endptr++ - '0';
749 // make sure no leading zeros, except zero itself, and range check.
750 if ((level == 0) || (level > 100)) break;
751 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700752 if ((level <= 100) && (endptr != digits.c_str()) && (*endptr == ' ')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700753 LOG(INFO) << "Battery level at startup " << level << "%";
754 if (level <= battery_dead_threshold) {
755 ret = "shutdown,battery";
756 }
757 } else {
758 LOG(DEBUG) << "Can not find first battery level in dmesg or logcat";
759 }
760 }
761 }
762
763 // Is there a controlled shutdown hint in last_reboot_reason_property?
764 if (isBluntRebootReason(ret)) {
765 // Content buffer no longer will have console data. Beware if more
766 // checks added below, that depend on parsing console content.
767 content = GetProperty(last_reboot_reason_property);
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700768 transformReason(content);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700769
Mark Salyzyn62909822017-10-09 09:27:16 -0700770 // Anything in last is better than 'super-blunt' reboot or shutdown.
771 if ((ret == "") || (ret == "reboot") || (ret == "shutdown") || !isBluntRebootReason(content)) {
772 ret = content;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700773 }
774 }
775
776 // Other System Health HAL reasons?
777
778 // ToDo: /proc/sys/kernel/boot_reason needs a HAL interface to
779 // possibly offer hardware-specific clues from the PMIC.
780 }
781
782 // If unknown left over from above, make it "reboot,<boot_reason>"
783 if (ret == "") {
784 ret = "reboot";
785 if (android::base::StartsWith(reason, "reboot")) {
786 reason = reason.substr(strlen("reboot"));
Mark Salyzyn0af71a52017-10-05 13:58:04 -0700787 while ((reason[0] == ',') || (reason[0] == '_')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700788 reason = reason.substr(1);
789 }
790 }
791 if (reason != "") {
792 ret += ",";
793 ret += reason;
794 }
795 }
796
797 LOG(INFO) << "Canonical boot reason: " << ret;
798 if (isKernelRebootReason(ret) && (GetProperty(last_reboot_reason_property) != "")) {
799 // Rewrite as it must be old news, kernel reasons trump user space.
800 SetProperty(last_reboot_reason_property, ret);
801 }
802 return ret;
803}
804
James Hawkinsb9cf7712016-04-08 15:32:19 -0700805// Returns the appropriate metric key prefix for the boot_complete metric such
806// that boot metrics after a system update are labeled as ota_boot_complete;
807// otherwise, they are labeled as boot_complete. This method encapsulates the
808// bookkeeping required to track when a system update has occurred by storing
809// the UTC timestamp of the system build date and comparing against the current
810// system build date.
811std::string CalculateBootCompletePrefix() {
812 static const std::string kBuildDateKey = "build_date";
813 std::string boot_complete_prefix = "boot_complete";
814
815 std::string build_date_str = GetProperty("ro.build.date.utc");
James Hawkins4dded612016-07-28 11:50:23 -0700816 int32_t build_date;
Elliott Hughesda46b392016-10-11 17:09:00 -0700817 if (!android::base::ParseInt(build_date_str, &build_date)) {
James Hawkins4dded612016-07-28 11:50:23 -0700818 return std::string();
819 }
James Hawkinsb9cf7712016-04-08 15:32:19 -0700820
821 BootEventRecordStore boot_event_store;
822 BootEventRecordStore::BootEventRecord record;
James Hawkins0bc4ad42017-05-30 15:03:15 -0700823 if (!boot_event_store.GetBootEvent(kBuildDateKey, &record)) {
824 boot_complete_prefix = "factory_reset_" + boot_complete_prefix;
825 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700826 LOG(INFO) << "Canonical boot reason: reboot,factory_reset";
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700827 SetProperty(system_reboot_reason_property, "reboot,factory_reset");
James Hawkins0bc4ad42017-05-30 15:03:15 -0700828 } else if (build_date != record.second) {
James Hawkinsb9cf7712016-04-08 15:32:19 -0700829 boot_complete_prefix = "ota_" + boot_complete_prefix;
830 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700831 LOG(INFO) << "Canonical boot reason: reboot,ota";
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700832 SetProperty(system_reboot_reason_property, "reboot,ota");
James Hawkinsb9cf7712016-04-08 15:32:19 -0700833 }
834
835 return boot_complete_prefix;
836}
837
James Hawkinsef0a0902017-01-06 14:38:23 -0800838// Records the value of a given ro.boottime.init property in milliseconds.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700839void RecordInitBootTimeProp(BootEventRecordStore* boot_event_store, const char* property) {
James Hawkinsef0a0902017-01-06 14:38:23 -0800840 std::string value = GetProperty(property);
841
James Hawkins27c05222017-01-26 11:55:44 -0800842 int32_t time_in_ms;
843 if (android::base::ParseInt(value, &time_in_ms)) {
James Hawkinsef0a0902017-01-06 14:38:23 -0800844 boot_event_store->AddBootEventWithValue(property, time_in_ms);
845 }
846}
847
James Hawkins1bfcaec2017-05-19 14:27:27 -0700848// A map from bootloader timing stage to the time that stage took during boot.
849typedef std::map<std::string, int32_t> BootloaderTimingMap;
850
851// Returns a mapping from bootloader stage names to the time those stages
852// took to boot.
853const BootloaderTimingMap GetBootLoaderTimings() {
854 BootloaderTimingMap timings;
855
856 // |ro.boot.boottime| is of the form 'stage1:time1,...,stageN:timeN',
857 // where timeN is in milliseconds.
James Hawkinsbe46fd12017-02-02 16:21:25 -0800858 std::string value = GetProperty("ro.boot.boottime");
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800859 if (value.empty()) {
860 // ro.boot.boottime is not reported on all devices.
James Hawkins1bfcaec2017-05-19 14:27:27 -0700861 return BootloaderTimingMap();
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800862 }
James Hawkinsbe46fd12017-02-02 16:21:25 -0800863
864 auto stages = android::base::Split(value, ",");
James Hawkins1bfcaec2017-05-19 14:27:27 -0700865 for (const auto& stageTiming : stages) {
James Hawkinsbe46fd12017-02-02 16:21:25 -0800866 // |stageTiming| is of the form 'stage:time'.
867 auto stageTimingValues = android::base::Split(stageTiming, ":");
James Hawkins0bc4ad42017-05-30 15:03:15 -0700868 DCHECK_EQ(2U, stageTimingValues.size());
James Hawkinsbe46fd12017-02-02 16:21:25 -0800869
870 std::string stageName = stageTimingValues[0];
871 int32_t time_ms;
872 if (android::base::ParseInt(stageTimingValues[1], &time_ms)) {
James Hawkins1bfcaec2017-05-19 14:27:27 -0700873 timings[stageName] = time_ms;
James Hawkinsbe46fd12017-02-02 16:21:25 -0800874 }
875 }
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800876
James Hawkins1bfcaec2017-05-19 14:27:27 -0700877 return timings;
878}
879
880// Parses and records the set of bootloader stages and associated boot times
881// from the ro.boot.boottime system property.
882void RecordBootloaderTimings(BootEventRecordStore* boot_event_store,
883 const BootloaderTimingMap& bootloader_timings) {
884 int32_t total_time = 0;
885 for (const auto& timing : bootloader_timings) {
886 total_time += timing.second;
887 boot_event_store->AddBootEventWithValue("boottime.bootloader." + timing.first, timing.second);
888 }
889
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800890 boot_event_store->AddBootEventWithValue("boottime.bootloader.total", total_time);
James Hawkinsbe46fd12017-02-02 16:21:25 -0800891}
892
James Hawkins1bfcaec2017-05-19 14:27:27 -0700893// Records the closest estimation to the absolute device boot time, i.e.,
894// from power on to boot_complete, including bootloader times.
895void RecordAbsoluteBootTime(BootEventRecordStore* boot_event_store,
896 const BootloaderTimingMap& bootloader_timings,
897 std::chrono::milliseconds uptime) {
898 int32_t bootloader_time_ms = 0;
899
900 for (const auto& timing : bootloader_timings) {
901 if (timing.first.compare("SW") != 0) {
902 bootloader_time_ms += timing.second;
903 }
904 }
905
906 auto bootloader_duration = std::chrono::milliseconds(bootloader_time_ms);
907 auto absolute_total =
908 std::chrono::duration_cast<std::chrono::seconds>(bootloader_duration + uptime);
909 boot_event_store->AddBootEventWithValue("absolute_boot_time", absolute_total.count());
910}
911
James Hawkinsc08e9962016-03-11 14:59:50 -0800912// Records several metrics related to the time it takes to boot the device,
913// including disambiguating boot time on encrypted or non-encrypted devices.
914void RecordBootComplete() {
915 BootEventRecordStore boot_event_store;
James Hawkinsb9cf7712016-04-08 15:32:19 -0700916 BootEventRecordStore::BootEventRecord record;
James Hawkins2d8b3e62016-04-14 14:13:20 -0700917
James Hawkins1bfcaec2017-05-19 14:27:27 -0700918 auto time_since_epoch = android::base::boot_clock::now().time_since_epoch();
919 auto uptime = std::chrono::duration_cast<std::chrono::seconds>(time_since_epoch);
James Hawkins2d8b3e62016-04-14 14:13:20 -0700920 time_t current_time_utc = time(nullptr);
921
922 if (boot_event_store.GetBootEvent("last_boot_time_utc", &record)) {
923 time_t last_boot_time_utc = record.second;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700924 time_t time_since_last_boot = difftime(current_time_utc, last_boot_time_utc);
925 boot_event_store.AddBootEventWithValue("time_since_last_boot", time_since_last_boot);
James Hawkins2d8b3e62016-04-14 14:13:20 -0700926 }
927
928 boot_event_store.AddBootEventWithValue("last_boot_time_utc", current_time_utc);
James Hawkinsc08e9962016-03-11 14:59:50 -0800929
James Hawkinsb9cf7712016-04-08 15:32:19 -0700930 // The boot_complete metric has two variants: boot_complete and
931 // ota_boot_complete. The latter signifies that the device is booting after
932 // a system update.
933 std::string boot_complete_prefix = CalculateBootCompletePrefix();
James Hawkins4dded612016-07-28 11:50:23 -0700934 if (boot_complete_prefix.empty()) {
935 // The system is hosed because the build date property could not be read.
936 return;
937 }
James Hawkinsc08e9962016-03-11 14:59:50 -0800938
939 // post_decrypt_time_elapsed is only logged on encrypted devices.
940 if (boot_event_store.GetBootEvent("post_decrypt_time_elapsed", &record)) {
941 // Log the amount of time elapsed until the device is decrypted, which
942 // includes the variable amount of time the user takes to enter the
943 // decryption password.
James Hawkinse78ea772017-03-24 11:43:02 -0700944 boot_event_store.AddBootEventWithValue("boot_decryption_complete", uptime.count());
James Hawkinsc08e9962016-03-11 14:59:50 -0800945
946 // Subtract the decryption time to normalize the boot cycle timing.
James Hawkinse78ea772017-03-24 11:43:02 -0700947 std::chrono::seconds boot_complete = std::chrono::seconds(uptime.count() - record.second);
James Hawkinsb9cf7712016-04-08 15:32:19 -0700948 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_post_decrypt",
James Hawkinse78ea772017-03-24 11:43:02 -0700949 boot_complete.count());
James Hawkinsc08e9962016-03-11 14:59:50 -0800950 } else {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700951 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_no_encryption", uptime.count());
James Hawkinsc08e9962016-03-11 14:59:50 -0800952 }
953
954 // Record the total time from device startup to boot complete, regardless of
955 // encryption state.
James Hawkinse78ea772017-03-24 11:43:02 -0700956 boot_event_store.AddBootEventWithValue(boot_complete_prefix, uptime.count());
James Hawkinsef0a0902017-01-06 14:38:23 -0800957
958 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init");
959 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.selinux");
960 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.cold_boot_wait");
James Hawkinsbe46fd12017-02-02 16:21:25 -0800961
James Hawkins1bfcaec2017-05-19 14:27:27 -0700962 const BootloaderTimingMap bootloader_timings = GetBootLoaderTimings();
963 RecordBootloaderTimings(&boot_event_store, bootloader_timings);
964
965 auto uptime_ms = std::chrono::duration_cast<std::chrono::milliseconds>(time_since_epoch);
966 RecordAbsoluteBootTime(&boot_event_store, bootloader_timings, uptime_ms);
James Hawkinsc08e9962016-03-11 14:59:50 -0800967}
968
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800969// Records the boot_reason metric by querying the ro.boot.bootreason system
970// property.
971void RecordBootReason() {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700972 const std::string reason(GetProperty(bootloader_reboot_reason_property));
James Hawkins25f71222017-10-10 16:37:05 -0700973
974 if (reason.empty()) {
975 // Log an empty boot reason value as '<EMPTY>' to ensure the value is intentional
976 // (and not corruption anywhere else in the reporting pipeline).
977 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
978 android::metricslogger::FIELD_PLATFORM_REASON, "<EMPTY>");
979 } else {
980 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
981 android::metricslogger::FIELD_PLATFORM_REASON, reason);
982 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700983
984 // Log the raw bootloader_boot_reason property value.
985 int32_t boot_reason = BootReasonStrToEnum(reason);
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800986 BootEventRecordStore boot_event_store;
987 boot_event_store.AddBootEventWithValue("boot_reason", boot_reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700988
989 // Log the scrubbed system_boot_reason.
990 const std::string system_reason(BootReasonStrToReason(reason));
991 int32_t system_boot_reason = BootReasonStrToEnum(system_reason);
992 boot_event_store.AddBootEventWithValue("system_boot_reason", system_boot_reason);
993
994 // Record the scrubbed system_boot_reason to the property
995 SetProperty(system_reboot_reason_property, system_reason);
996 if (reason == "") {
997 SetProperty(bootloader_reboot_reason_property, system_reason);
998 }
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800999}
1000
James Hawkins500d7152016-02-16 15:05:54 -08001001// Records two metrics related to the user resetting a device: the time at
1002// which the device is reset, and the time since the user last reset the
1003// device. The former is only set once per-factory reset.
1004void RecordFactoryReset() {
1005 BootEventRecordStore boot_event_store;
1006 BootEventRecordStore::BootEventRecord record;
1007
1008 time_t current_time_utc = time(nullptr);
1009
James Hawkins0660b302016-03-08 16:18:15 -08001010 if (current_time_utc < 0) {
1011 // UMA does not display negative values in buckets, so convert to positive.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001012 android::metricslogger::LogHistogram("factory_reset_current_time_failure",
1013 std::abs(current_time_utc));
James Hawkinsfff95ba2016-03-29 16:13:49 -07001014
James Hawkins9aec9262017-01-31 11:42:24 -08001015 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001016 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001017 boot_event_store.AddBootEventWithValue("factory_reset_current_time_failure",
1018 std::abs(current_time_utc));
James Hawkins0660b302016-03-08 16:18:15 -08001019 return;
1020 } else {
James Hawkins9aec9262017-01-31 11:42:24 -08001021 android::metricslogger::LogHistogram("factory_reset_current_time", current_time_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001022
James Hawkins9aec9262017-01-31 11:42:24 -08001023 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001024 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001025 boot_event_store.AddBootEventWithValue("factory_reset_current_time", current_time_utc);
James Hawkins0660b302016-03-08 16:18:15 -08001026 }
1027
James Hawkins500d7152016-02-16 15:05:54 -08001028 // The factory_reset boot event does not exist after the device is reset, so
1029 // use this signal to mark the time of the factory reset.
1030 if (!boot_event_store.GetBootEvent("factory_reset", &record)) {
1031 boot_event_store.AddBootEventWithValue("factory_reset", current_time_utc);
James Hawkins3bf9b142016-03-03 14:50:24 -08001032
1033 // Don't log the time_since_factory_reset until some time has elapsed.
1034 // The data is not meaningful yet and skews the histogram buckets.
James Hawkins500d7152016-02-16 15:05:54 -08001035 return;
1036 }
1037
1038 // Calculate and record the difference in time between now and the
1039 // factory_reset time.
1040 time_t factory_reset_utc = record.second;
James Hawkins9aec9262017-01-31 11:42:24 -08001041 android::metricslogger::LogHistogram("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001042
James Hawkins9aec9262017-01-31 11:42:24 -08001043 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001044 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001045 boot_event_store.AddBootEventWithValue("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001046
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001047 time_t time_since_factory_reset = difftime(current_time_utc, factory_reset_utc);
1048 boot_event_store.AddBootEventWithValue("time_since_factory_reset", time_since_factory_reset);
James Hawkins500d7152016-02-16 15:05:54 -08001049}
1050
James Hawkinsabd73e62016-01-19 15:10:38 -08001051} // namespace
1052
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001053int main(int argc, char** argv) {
James Hawkinsabd73e62016-01-19 15:10:38 -08001054 android::base::InitLogging(argv);
1055
1056 const std::string cmd_line = GetCommandLine(argc, argv);
1057 LOG(INFO) << "Service started: " << cmd_line;
1058
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001059 int option_index = 0;
James Hawkinsc6275582016-03-22 10:47:44 -07001060 static const char value_str[] = "value";
James Hawkinsc08e9962016-03-11 14:59:50 -08001061 static const char boot_complete_str[] = "record_boot_complete";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001062 static const char boot_reason_str[] = "record_boot_reason";
James Hawkins53684ea2016-02-23 16:18:19 -08001063 static const char factory_reset_str[] = "record_time_since_factory_reset";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001064 static const struct option long_options[] = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001065 // clang-format off
1066 { "help", no_argument, NULL, 'h' },
1067 { "log", no_argument, NULL, 'l' },
1068 { "print", no_argument, NULL, 'p' },
1069 { "record", required_argument, NULL, 'r' },
1070 { value_str, required_argument, NULL, 0 },
1071 { boot_complete_str, no_argument, NULL, 0 },
1072 { boot_reason_str, no_argument, NULL, 0 },
1073 { factory_reset_str, no_argument, NULL, 0 },
1074 { NULL, 0, NULL, 0 }
1075 // clang-format on
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001076 };
1077
James Hawkinsc6275582016-03-22 10:47:44 -07001078 std::string boot_event;
1079 std::string value;
James Hawkinsabd73e62016-01-19 15:10:38 -08001080 int opt = 0;
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001081 while ((opt = getopt_long(argc, argv, "hlpr:", long_options, &option_index)) != -1) {
James Hawkinsabd73e62016-01-19 15:10:38 -08001082 switch (opt) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001083 // This case handles long options which have no single-character mapping.
1084 case 0: {
1085 const std::string option_name = long_options[option_index].name;
James Hawkinsc6275582016-03-22 10:47:44 -07001086 if (option_name == value_str) {
1087 // |optarg| is an external variable set by getopt representing
1088 // the option argument.
1089 value = optarg;
1090 } else if (option_name == boot_complete_str) {
James Hawkinsc08e9962016-03-11 14:59:50 -08001091 RecordBootComplete();
1092 } else if (option_name == boot_reason_str) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001093 RecordBootReason();
James Hawkins500d7152016-02-16 15:05:54 -08001094 } else if (option_name == factory_reset_str) {
1095 RecordFactoryReset();
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001096 } else {
1097 LOG(ERROR) << "Invalid option: " << option_name;
1098 }
1099 break;
1100 }
1101
James Hawkinsabd73e62016-01-19 15:10:38 -08001102 case 'h': {
1103 ShowHelp(argv[0]);
1104 break;
1105 }
1106
1107 case 'l': {
1108 LogBootEvents();
1109 break;
1110 }
1111
1112 case 'p': {
1113 PrintBootEvents();
1114 break;
1115 }
1116
1117 case 'r': {
1118 // |optarg| is an external variable set by getopt representing
1119 // the option argument.
James Hawkinsc6275582016-03-22 10:47:44 -07001120 boot_event = optarg;
James Hawkinsabd73e62016-01-19 15:10:38 -08001121 break;
1122 }
1123
1124 default: {
1125 DCHECK_EQ(opt, '?');
1126
1127 // |optopt| is an external variable set by getopt representing
1128 // the value of the invalid option.
1129 LOG(ERROR) << "Invalid option: " << optopt;
1130 ShowHelp(argv[0]);
1131 return EXIT_FAILURE;
1132 }
1133 }
1134 }
1135
James Hawkinsc6275582016-03-22 10:47:44 -07001136 if (!boot_event.empty()) {
1137 RecordBootEventFromCommandLine(boot_event, value);
1138 }
1139
James Hawkinsabd73e62016-01-19 15:10:38 -08001140 return 0;
1141}