blob: 1ec545181a426753e2d587b927f62371a444e7e2 [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>
Tej Singh4eacd382018-01-25 17:59:57 -080045#include <statslog.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070046
James Hawkinsabd73e62016-01-19 15:10:38 -080047#include "boot_event_record_store.h"
James Hawkinsabd73e62016-01-19 15:10:38 -080048
49namespace {
50
James Hawkinsabd73e62016-01-19 15:10:38 -080051// Scans the boot event record store for record files and logs each boot event
52// via EventLog.
53void LogBootEvents() {
54 BootEventRecordStore boot_event_store;
55
56 auto events = boot_event_store.GetAllBootEvents();
57 for (auto i = events.cbegin(); i != events.cend(); ++i) {
James Hawkins9aec9262017-01-31 11:42:24 -080058 android::metricslogger::LogHistogram(i->first, i->second);
James Hawkinsabd73e62016-01-19 15:10:38 -080059 }
60}
61
James Hawkinsc6275582016-03-22 10:47:44 -070062// Records the named boot |event| to the record store. If |value| is non-empty
63// and is a proper string representation of an integer value, the converted
64// integer value is associated with the boot event.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -070065void RecordBootEventFromCommandLine(const std::string& event, const std::string& value_str) {
James Hawkinsc6275582016-03-22 10:47:44 -070066 BootEventRecordStore boot_event_store;
67 if (!value_str.empty()) {
68 int32_t value = 0;
Elliott Hughesda46b392016-10-11 17:09:00 -070069 if (android::base::ParseInt(value_str, &value)) {
James Hawkins4dded612016-07-28 11:50:23 -070070 boot_event_store.AddBootEventWithValue(event, value);
71 }
James Hawkinsc6275582016-03-22 10:47:44 -070072 } else {
73 boot_event_store.AddBootEvent(event);
74 }
75}
76
James Hawkinsabd73e62016-01-19 15:10:38 -080077void PrintBootEvents() {
78 printf("Boot events:\n");
79 printf("------------\n");
80
81 BootEventRecordStore boot_event_store;
82 auto events = boot_event_store.GetAllBootEvents();
83 for (auto i = events.cbegin(); i != events.cend(); ++i) {
84 printf("%s\t%d\n", i->first.c_str(), i->second);
85 }
86}
87
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -070088void ShowHelp(const char* cmd) {
James Hawkinsabd73e62016-01-19 15:10:38 -080089 fprintf(stderr, "Usage: %s [options]\n", cmd);
90 fprintf(stderr,
91 "options include:\n"
Yongqin Liu78b2b942017-07-07 13:26:49 +080092 " -h, --help Show this help\n"
93 " -l, --log Log all metrics to logstorage\n"
94 " -p, --print Dump the boot event records to the console\n"
95 " -r, --record Record the timestamp of a named boot event\n"
96 " --value Optional value to associate with the boot event\n"
97 " --record_boot_complete Record metrics related to the time for the device boot\n"
98 " --record_boot_reason Record the reason why the device booted\n"
James Hawkins53684ea2016-02-23 16:18:19 -080099 " --record_time_since_factory_reset Record the time since the device was reset\n");
James Hawkinsabd73e62016-01-19 15:10:38 -0800100}
101
102// Constructs a readable, printable string from the givencommand line
103// arguments.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700104std::string GetCommandLine(int argc, char** argv) {
James Hawkinsabd73e62016-01-19 15:10:38 -0800105 std::string cmd;
106 for (int i = 0; i < argc; ++i) {
107 cmd += argv[i];
108 cmd += " ";
109 }
110
111 return cmd;
112}
113
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800114// Convenience wrapper over the property API that returns an
115// std::string.
116std::string GetProperty(const char* key) {
117 std::vector<char> temp(PROPERTY_VALUE_MAX);
118 const int len = property_get(key, &temp[0], nullptr);
119 if (len < 0) {
120 return "";
121 }
122 return std::string(&temp[0], len);
123}
124
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700125void SetProperty(const char* key, const std::string& val) {
126 property_set(key, val.c_str());
127}
128
129void SetProperty(const char* key, const char* val) {
130 property_set(key, val);
131}
132
James Hawkins25f71222017-10-10 16:37:05 -0700133constexpr int32_t kEmptyBootReason = 0;
James Hawkins6f74c0b2016-02-12 15:49:16 -0800134constexpr int32_t kUnknownBootReason = 1;
135
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800136// A mapping from boot reason string, as read from the ro.boot.bootreason
137// system property, to a unique integer ID. Viewers of log data dashboards for
138// the boot_reason metric may refer to this mapping to discern the histogram
139// values.
James Hawkins6f74c0b2016-02-12 15:49:16 -0800140const std::map<std::string, int32_t> kBootReasonMap = {
James Hawkins25f71222017-10-10 16:37:05 -0700141 {"empty", kEmptyBootReason},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700142 {"unknown", kUnknownBootReason},
143 {"normal", 2},
144 {"recovery", 3},
145 {"reboot", 4},
146 {"PowerKey", 5},
147 {"hard_reset", 6},
148 {"kernel_panic", 7},
149 {"rpm_err", 8},
150 {"hw_reset", 9},
151 {"tz_err", 10},
152 {"adsp_err", 11},
153 {"modem_err", 12},
154 {"mba_err", 13},
155 {"Watchdog", 14},
156 {"Panic", 15},
157 {"power_key", 16},
158 {"power_on", 17},
159 {"Reboot", 18},
160 {"rtc", 19},
161 {"edl", 20},
162 {"oem_pon1", 21},
163 {"oem_powerkey", 22},
164 {"oem_unknown_reset", 23},
165 {"srto: HWWDT reset SC", 24},
166 {"srto: HWWDT reset platform", 25},
167 {"srto: bootloader", 26},
168 {"srto: kernel panic", 27},
169 {"srto: kernel watchdog reset", 28},
170 {"srto: normal", 29},
171 {"srto: reboot", 30},
172 {"srto: reboot-bootloader", 31},
173 {"srto: security watchdog reset", 32},
174 {"srto: wakesrc", 33},
175 {"srto: watchdog", 34},
176 {"srto:1-1", 35},
177 {"srto:omap_hsmm", 36},
178 {"srto:phy0", 37},
179 {"srto:rtc0", 38},
180 {"srto:touchpad", 39},
181 {"watchdog", 40},
182 {"watchdogr", 41},
183 {"wdog_bark", 42},
184 {"wdog_bite", 43},
185 {"wdog_reset", 44},
186 {"shutdown,", 45}, // Trailing comma is intentional.
187 {"shutdown,userrequested", 46},
188 {"reboot,bootloader", 47},
189 {"reboot,cold", 48},
190 {"reboot,recovery", 49},
191 {"thermal_shutdown", 50},
192 {"s3_wakeup", 51},
193 {"kernel_panic,sysrq", 52},
194 {"kernel_panic,NULL", 53},
195 {"kernel_panic,BUG", 54},
196 {"bootloader", 55},
197 {"cold", 56},
198 {"hard", 57},
199 {"warm", 58},
200 {"recovery", 59},
201 {"thermal-shutdown", 60},
202 {"shutdown,thermal", 61},
203 {"shutdown,battery", 62},
204 {"reboot,ota", 63},
205 {"reboot,factory_reset", 64},
206 {"reboot,", 65},
207 {"reboot,shell", 66},
208 {"reboot,adb", 67},
Mark Salyzyn9033bf52017-09-21 11:30:29 -0700209 {"reboot,userrequested", 68},
Mark Salyzyn161b8622017-09-26 08:26:12 -0700210 {"shutdown,container", 69}, // Host OS asking Android Container to shutdown
Mark Salyzyn243fa292017-10-11 09:02:04 -0700211 {"cold,powerkey", 70},
212 {"warm,s3_wakeup", 71},
213 {"hard,hw_reset", 72},
214 {"shutdown,suspend", 73}, // Suspend to RAM
215 {"shutdown,hibernate", 74}, // Suspend to DISK
James Hawkins34073b52017-10-17 15:53:27 -0700216 {"power_on_key", 75},
217 {"reboot_by_key", 76},
218 {"wdt_by_pass_pwk", 77},
219 {"reboot_longkey", 78},
220 {"powerkey", 79},
221 {"usb", 80},
222 {"wdt", 81},
223 {"tool_by_pass_pwk", 82},
224 {"2sec_reboot", 83},
225 {"reboot,by_key", 84},
226 {"reboot,longkey", 85},
Mark Salyzyncabbe4f2017-10-23 13:52:39 -0700227 {"reboot,2sec", 86},
Mark Salyzync89f9da2017-10-24 15:35:34 -0700228 {"shutdown,thermal,battery", 87},
Mark Salyzyn72a8ea32017-10-25 09:23:19 -0700229 {"reboot,its_just_so_hard", 88}, // produced by boot_reason_test
230 {"reboot,Its Just So Hard", 89}, // produced by boot_reason_test
James Hawkins8ac79bc2017-10-31 10:07:34 -0700231 {"usb", 90},
James Hawkins74b17582017-11-20 14:13:41 -0800232 {"charge", 91},
233 {"oem_tz_crash", 92},
234 {"uvlo", 93},
235 {"oem_ps_hold", 94},
236 {"abnormal_reset", 95},
237 {"oemerr_unknown", 96},
238 {"reboot_fastboot_mode", 97},
James Hawkins5f85f832017-11-29 14:30:06 -0800239 {"watchdog_apps_bite", 98},
240 {"xpu_err", 99},
241 {"power_on_usb", 100},
James Hawkinsf4444f02017-11-30 15:01:40 -0800242 {"watchdog_rpm", 101},
243 {"watchdog_nonsec", 102},
244 {"watchdog_apps_bark", 103},
245 {"reboot_dmverity_corrupted", 104},
James Hawkins00433a22017-12-04 14:20:21 -0800246 {"reboot_smpl", 105},
247 {"watchdog_sdi_apps_reset", 106},
248 {"smpl", 107},
249 {"oem_modem_failed_to_powerup", 108},
James Hawkinse2c27242017-12-18 13:40:27 -0800250 {"reboot_normal", 109},
251 {"oem_lpass_cfg", 110},
252 {"oem_xpu_ns_error", 111},
253 {"power_key_press", 112},
254 {"hardware_reset", 113},
255 {"reboot_by_powerkey", 114},
256 {"reboot_verity", 115},
257 {"oem_rpm_undef_error", 116},
258 {"oem_crash_on_the_lk", 117},
259 {"oem_rpm_reset", 118},
260 {"oem_lpass_cfg", 119},
261 {"oem_xpu_ns_error", 120},
262 {"factory_cable", 121},
263 {"oem_ar6320_failed_to_powerup", 122},
264 {"watchdog_rpm_bite", 123},
265 {"power_on_cable", 124},
266 {"reboot_unknown", 125},
267 {"wireless_charger", 126},
268 {"0x776655ff", 127},
269 {"oem_thermal_bite_reset", 128},
270 {"charger", 129},
271 {"pon1", 130},
272 {"unknown", 131},
273 {"reboot_rtc", 132},
274 {"cold_boot", 133},
275 {"hard_rst", 134},
James Hawkinsb607dae2018-01-05 14:42:55 -0800276 {"power-on", 135},
277 {"oem_adsp_resetting_the_soc", 136},
278 {"kpdpwr", 137},
279 {"oem_modem_timeout_waiting", 138},
280 {"usb_chg", 139},
281 {"warm_reset_0x02", 140},
282 {"warm_reset_0x80", 141},
283 {"pon_reason_0xb0", 142},
284 {"reboot_download", 143},
James Hawkins79a4ee22018-01-26 14:31:04 -0800285 {"reboot_recovery_mode", 144},
286 {"oem_sdi_err_fatal", 145},
287 {"pmic_watchdog", 146},
288 {"software_master", 147},
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800289};
290
291// Converts a string value representing the reason the system booted to an
292// integer representation. This is necessary for logging the boot_reason metric
293// via Tron, which does not accept non-integer buckets in histograms.
294int32_t BootReasonStrToEnum(const std::string& boot_reason) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800295 auto mapping = kBootReasonMap.find(boot_reason);
296 if (mapping != kBootReasonMap.end()) {
297 return mapping->second;
298 }
299
James Hawkins25f71222017-10-10 16:37:05 -0700300 if (boot_reason.empty()) {
301 return kEmptyBootReason;
302 }
303
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800304 LOG(INFO) << "Unknown boot reason: " << boot_reason;
305 return kUnknownBootReason;
306}
307
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700308// Canonical list of supported primary reboot reasons.
309const std::vector<const std::string> knownReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700310 // clang-format off
311 // kernel
312 "watchdog",
313 "kernel_panic",
314 // strong
315 "recovery", // Should not happen from ro.boot.bootreason
316 "bootloader", // Should not happen from ro.boot.bootreason
317 // blunt
318 "cold",
319 "hard",
320 "warm",
Mark Salyzyn62909822017-10-09 09:27:16 -0700321 // super blunt
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700322 "shutdown", // Can not happen from ro.boot.bootreason
323 "reboot", // Default catch-all for anything unknown
324 // clang-format on
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700325};
326
327// Returns true if the supplied reason prefix is considered detailed enough.
328bool isStrongRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700329 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700330 if (s == "cold") break;
331 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800332 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700333 return true;
334 }
335 }
336 return false;
337}
338
339// Returns true if the supplied reason prefix is associated with the kernel.
340bool isKernelRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700341 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700342 if (s == "recovery") break;
343 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800344 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700345 return true;
346 }
347 }
348 return false;
349}
350
351// Returns true if the supplied reason prefix is considered known.
352bool isKnownRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700353 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700354 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800355 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700356 return true;
357 }
358 }
359 return false;
360}
361
362// If the reboot reason should be improved, report true if is too blunt.
363bool isBluntRebootReason(const std::string& r) {
364 if (isStrongRebootReason(r)) return false;
365
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700366 if (!isKnownRebootReason(r)) return true; // Can not support unknown as detail
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700367
368 size_t pos = 0;
369 while ((pos = r.find(',', pos)) != std::string::npos) {
370 ++pos;
371 std::string next(r.substr(pos));
372 if (next.length() == 0) break;
373 if (next[0] == ',') continue;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700374 if (!isKnownRebootReason(next)) return false; // Unknown subreason is good.
375 if (isStrongRebootReason(next)) return false; // eg: reboot,reboot
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700376 }
377 return true;
378}
379
Mark Salyzyn64610892017-09-18 10:41:14 -0700380bool readPstoreConsole(std::string& console) {
381 if (android::base::ReadFileToString("/sys/fs/pstore/console-ramoops-0", &console)) {
382 return true;
383 }
384 return android::base::ReadFileToString("/sys/fs/pstore/console-ramoops", &console);
385}
386
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700387// Implement a variant of std::string::rfind that is resilient to errors in
388// the data stream being inspected.
389class pstoreConsole {
390 private:
391 const size_t kBitErrorRate = 8; // number of bits per error
392 const std::string& console;
393
394 // Number of bits that differ between the two arguments l and r.
395 // Returns zero if the values for l and r are identical.
396 size_t numError(uint8_t l, uint8_t r) const { return std::bitset<8>(l ^ r).count(); }
397
398 // A string comparison function, reports the number of errors discovered
399 // in the match to a maximum of the bitLength / kBitErrorRate, at that
400 // point returning npos to indicate match is too poor.
401 //
402 // Since called in rfind which works backwards, expect cache locality will
403 // help if we check in reverse here as well for performance.
404 //
405 // Assumption: l (from console.c_str() + pos) is long enough to house
406 // _r.length(), checked in rfind caller below.
407 //
408 size_t numError(size_t pos, const std::string& _r) const {
409 const char* l = console.c_str() + pos;
410 const char* r = _r.c_str();
411 size_t n = _r.length();
412 const uint8_t* le = reinterpret_cast<const uint8_t*>(l) + n;
413 const uint8_t* re = reinterpret_cast<const uint8_t*>(r) + n;
414 size_t count = 0;
415 n = 0;
416 do {
417 // individual character bit error rate > threshold + slop
418 size_t num = numError(*--le, *--re);
419 if (num > ((8 + kBitErrorRate) / kBitErrorRate)) return std::string::npos;
420 // total bit error rate > threshold + slop
421 count += num;
422 ++n;
423 if (count > ((n * 8 + kBitErrorRate - (n > 2)) / kBitErrorRate)) {
424 return std::string::npos;
425 }
426 } while (le != reinterpret_cast<const uint8_t*>(l));
427 return count;
428 }
429
430 public:
431 explicit pstoreConsole(const std::string& console) : console(console) {}
432 // scope of argument must be equal to or greater than scope of pstoreConsole
433 explicit pstoreConsole(const std::string&& console) = delete;
434 explicit pstoreConsole(std::string&& console) = delete;
435
436 // Our implementation of rfind, use exact match first, then resort to fuzzy.
437 size_t rfind(const std::string& needle) const {
438 size_t pos = console.rfind(needle); // exact match?
439 if (pos != std::string::npos) return pos;
440
441 // Check to make sure needle fits in console string.
442 pos = console.length();
443 if (needle.length() > pos) return std::string::npos;
444 pos -= needle.length();
445 // fuzzy match to maximum kBitErrorRate
Ivan Lozano44d3cac2017-11-07 13:13:55 -0800446 for (;;) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700447 if (numError(pos, needle) != std::string::npos) return pos;
Ivan Lozano44d3cac2017-11-07 13:13:55 -0800448 if (pos == 0) break;
449 --pos;
450 }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700451 return std::string::npos;
452 }
453
454 // Our implementation of find, use only fuzzy match.
455 size_t find(const std::string& needle, size_t start = 0) const {
456 // Check to make sure needle fits in console string.
457 if (needle.length() > console.length()) return std::string::npos;
458 const size_t last_pos = console.length() - needle.length();
459 // fuzzy match to maximum kBitErrorRate
460 for (size_t pos = start; pos <= last_pos; ++pos) {
461 if (numError(pos, needle) != std::string::npos) return pos;
462 }
463 return std::string::npos;
464 }
465};
466
467// If bit error match to needle, correct it.
468// Return true if any corrections were discovered and applied.
469bool correctForBer(std::string& reason, const std::string& needle) {
470 bool corrected = false;
471 if (reason.length() < needle.length()) return corrected;
472 const pstoreConsole console(reason);
473 const size_t last_pos = reason.length() - needle.length();
474 for (size_t pos = 0; pos <= last_pos; pos += needle.length()) {
475 pos = console.find(needle, pos);
476 if (pos == std::string::npos) break;
477
478 // exact match has no malice
479 if (needle == reason.substr(pos, needle.length())) continue;
480
481 corrected = true;
482 reason = reason.substr(0, pos) + needle + reason.substr(pos + needle.length());
483 }
484 return corrected;
485}
486
487bool addKernelPanicSubReason(const pstoreConsole& console, std::string& ret) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700488 // Check for kernel panic types to refine information
489 if (console.rfind("SysRq : Trigger a crash") != std::string::npos) {
490 // Can not happen, except on userdebug, during testing/debugging.
491 ret = "kernel_panic,sysrq";
492 return true;
493 }
494 if (console.rfind("Unable to handle kernel NULL pointer dereference at virtual address") !=
495 std::string::npos) {
496 ret = "kernel_panic,NULL";
497 return true;
498 }
499 if (console.rfind("Kernel BUG at ") != std::string::npos) {
500 ret = "kernel_panic,BUG";
501 return true;
502 }
503 return false;
504}
505
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700506bool addKernelPanicSubReason(const std::string& content, std::string& ret) {
507 return addKernelPanicSubReason(pstoreConsole(content), ret);
508}
509
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700510// std::transform Helper callback functions:
511// Converts a string value representing the reason the system booted to a
512// string complying with Android system standard reason.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700513char tounderline(char c) {
514 return ::isblank(c) ? '_' : c;
515}
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700516
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700517char toprintable(char c) {
518 return ::isprint(c) ? c : '?';
519}
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700520
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700521// Cleanup boot_reason regarding acceptable character set
522void transformReason(std::string& reason) {
523 std::transform(reason.begin(), reason.end(), reason.begin(), ::tolower);
524 std::transform(reason.begin(), reason.end(), reason.begin(), tounderline);
525 std::transform(reason.begin(), reason.end(), reason.begin(), toprintable);
526}
527
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700528const char system_reboot_reason_property[] = "sys.boot.reason";
529const char last_reboot_reason_property[] = LAST_REBOOT_REASON_PROPERTY;
530const char bootloader_reboot_reason_property[] = "ro.boot.bootreason";
531
532// Scrub, Sanitize, Standardize and Enhance the boot reason string supplied.
533std::string BootReasonStrToReason(const std::string& boot_reason) {
Mark Salyzyna16e4372017-09-20 08:36:12 -0700534 static const size_t max_reason_length = 256;
535
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700536 std::string ret(GetProperty(system_reboot_reason_property));
537 std::string reason(boot_reason);
538 // If sys.boot.reason == ro.boot.bootreason, let's re-evaluate
539 if (reason == ret) ret = "";
540
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700541 transformReason(reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700542
543 // Is the current system boot reason sys.boot.reason valid?
544 if (!isKnownRebootReason(ret)) ret = "";
545
546 if (ret == "") {
547 // Is the bootloader boot reason ro.boot.bootreason known?
548 std::vector<std::string> words(android::base::Split(reason, ",_-"));
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700549 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700550 std::string blunt;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700551 for (auto& r : words) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700552 if (r == s) {
553 if (isBluntRebootReason(s)) {
554 blunt = s;
555 } else {
556 ret = s;
557 break;
558 }
559 }
560 }
561 if (ret == "") ret = blunt;
562 if (ret != "") break;
563 }
564 }
565
566 if (ret == "") {
567 // A series of checks to take some officially unsupported reasons
568 // reported by the bootloader and find some logical and canonical
569 // sense. In an ideal world, we would require those bootloaders
570 // to behave and follow our standards.
571 static const std::vector<std::pair<const std::string, const std::string>> aliasReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700572 {"watchdog", "wdog"},
573 {"cold,powerkey", "powerkey"},
574 {"kernel_panic", "panic"},
575 {"shutdown,thermal", "thermal"},
576 {"warm,s3_wakeup", "s3_wakeup"},
577 {"hard,hw_reset", "hw_reset"},
Mark Salyzyncabbe4f2017-10-23 13:52:39 -0700578 {"reboot,2sec", "2sec_reboot"},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700579 {"bootloader", ""},
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700580 };
581
582 // Either the primary or alias is found _somewhere_ in the reason string.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700583 for (auto& s : aliasReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700584 if (reason.find(s.first) != std::string::npos) {
585 ret = s.first;
586 break;
587 }
588 if (s.second.size() && (reason.find(s.second) != std::string::npos)) {
589 ret = s.first;
590 break;
591 }
592 }
593 }
594
595 // If watchdog is the reason, see if there is a security angle?
596 if (ret == "watchdog") {
597 if (reason.find("sec") != std::string::npos) {
598 ret += ",security";
599 }
600 }
601
Mark Salyzyn64610892017-09-18 10:41:14 -0700602 if (ret == "kernel_panic") {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700603 // Check to see if last klog has some refinement hints.
604 std::string content;
Mark Salyzyn64610892017-09-18 10:41:14 -0700605 if (readPstoreConsole(content)) {
606 addKernelPanicSubReason(content, ret);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700607 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700608 } else if (isBluntRebootReason(ret)) {
609 // Check the other available reason resources if the reason is still blunt.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700610
Mark Salyzyn64610892017-09-18 10:41:14 -0700611 // Check to see if last klog has some refinement hints.
612 std::string content;
613 if (readPstoreConsole(content)) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700614 const pstoreConsole console(content);
Mark Salyzyn64610892017-09-18 10:41:14 -0700615 // The toybox reboot command used directly (unlikely)? But also
616 // catches init's response to Android's more controlled reboot command.
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700617 if (console.rfind("reboot: Power down") != std::string::npos) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700618 ret = "shutdown"; // Still too blunt, but more accurate.
619 // ToDo: init should record the shutdown reason to kernel messages ala:
620 // init: shutdown system with command 'last_reboot_reason'
621 // so that if pstore has persistence we can get some details
622 // that could be missing in last_reboot_reason_property.
623 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700624
Mark Salyzyn64610892017-09-18 10:41:14 -0700625 static const char cmd[] = "reboot: Restarting system with command '";
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700626 size_t pos = console.rfind(cmd);
Mark Salyzyn64610892017-09-18 10:41:14 -0700627 if (pos != std::string::npos) {
628 pos += strlen(cmd);
Mark Salyzyna16e4372017-09-20 08:36:12 -0700629 std::string subReason(content.substr(pos, max_reason_length));
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700630 // Correct against any known strings that Bit Error Match
631 for (const auto& s : knownReasons) {
632 correctForBer(subReason, s);
633 }
634 for (const auto& m : kBootReasonMap) {
635 if (m.first.length() <= strlen("cold")) continue; // too short?
636 if (correctForBer(subReason, m.first + "'")) continue;
637 if (m.first.length() <= strlen("reboot,cold")) continue; // short?
638 if (!android::base::StartsWith(m.first, "reboot,")) continue;
639 correctForBer(subReason, m.first.substr(strlen("reboot,")) + "'");
640 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700641 for (pos = 0; pos < subReason.length(); ++pos) {
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700642 char c = subReason[pos];
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700643 // #, &, %, / are common single bit error for ' that we can block
644 if (!::isprint(c) || (c == '\'') || (c == '#') || (c == '&') || (c == '%') || (c == '/')) {
Mark Salyzyna16e4372017-09-20 08:36:12 -0700645 subReason.erase(pos);
646 break;
647 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700648 }
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700649 transformReason(subReason);
Mark Salyzyn64610892017-09-18 10:41:14 -0700650 if (subReason != "") { // Will not land "reboot" as that is too blunt.
651 if (isKernelRebootReason(subReason)) {
652 ret = "reboot," + subReason; // User space can't talk kernel reasons.
Mark Salyzyndafced92017-09-20 08:37:46 -0700653 } else if (isKnownRebootReason(subReason)) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700654 ret = subReason;
Mark Salyzyndafced92017-09-20 08:37:46 -0700655 } else {
656 ret = "reboot," + subReason; // legitimize unknown reasons
Mark Salyzyn64610892017-09-18 10:41:14 -0700657 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700658 }
659 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700660
Mark Salyzyn64610892017-09-18 10:41:14 -0700661 // Check for kernel panics, allowed to override reboot command.
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700662 if (!addKernelPanicSubReason(console, ret) &&
Mark Salyzyn64610892017-09-18 10:41:14 -0700663 // check for long-press power down
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700664 ((console.rfind("Power held for ") != std::string::npos) ||
665 (console.rfind("charger: [") != std::string::npos))) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700666 ret = "cold";
667 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700668 }
669
670 // The following battery test should migrate to a default system health HAL
671
672 // Let us not worry if the reboot command was issued, for the cases of
673 // reboot -p, reboot <no reason>, reboot cold, reboot warm and reboot hard.
674 // Same for bootloader and ro.boot.bootreasons of this set, but a dead
675 // battery could conceivably lead to these, so worthy of override.
676 if (isBluntRebootReason(ret)) {
677 // Heuristic to determine if shutdown possibly because of a dead battery?
678 // Really a hail-mary pass to find it in last klog content ...
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700679 static const int battery_dead_threshold = 2; // percent
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700680 static const char battery[] = "healthd: battery l=";
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700681 const pstoreConsole console(content);
682 size_t pos = console.rfind(battery); // last one
Mark Salyzyna16e4372017-09-20 08:36:12 -0700683 std::string digits;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700684 if (pos != std::string::npos) {
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700685 digits = content.substr(pos + strlen(battery), strlen("100 "));
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700686 // correct common errors
687 correctForBer(digits, "100 ");
688 if (digits[0] == '!') digits[0] = '1';
689 if (digits[1] == '!') digits[1] = '1';
Mark Salyzyna16e4372017-09-20 08:36:12 -0700690 }
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700691 const char* endptr = digits.c_str();
692 unsigned level = 0;
693 while (::isdigit(*endptr)) {
694 level *= 10;
695 level += *endptr++ - '0';
696 // make sure no leading zeros, except zero itself, and range check.
697 if ((level == 0) || (level > 100)) break;
698 }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700699 // example bit error rate issues for 10%
700 // 'l=10 ' no bits in error
701 // 'l=00 ' single bit error (fails above)
702 // 'l=1 ' single bit error
703 // 'l=0 ' double bit error
704 // There are others, not typically critical because of 2%
705 // battery_dead_threshold. KISS check, make sure second
706 // character after digit sequence is not a space.
707 if ((level <= 100) && (endptr != digits.c_str()) && (endptr[0] == ' ') && (endptr[1] != ' ')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700708 LOG(INFO) << "Battery level at shutdown " << level << "%";
709 if (level <= battery_dead_threshold) {
710 ret = "shutdown,battery";
711 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700712 } else { // Most likely
713 digits = ""; // reset digits
714
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700715 // Content buffer no longer will have console data. Beware if more
716 // checks added below, that depend on parsing console content.
717 content = "";
718
719 LOG(DEBUG) << "Can not find last low battery in last console messages";
720 android_logcat_context ctx = create_android_logcat();
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700721 FILE* fp = android_logcat_popen(&ctx, "logcat -b kernel -v brief -d");
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700722 if (fp != nullptr) {
723 android::base::ReadFdToString(fileno(fp), &content);
724 }
725 android_logcat_pclose(&ctx, fp);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700726 static const char logcat_battery[] = "W/healthd ( 0): battery l=";
727 const char* match = logcat_battery;
728
729 if (content == "") {
730 // Service logd.klog not running, go to smaller buffer in the kernel.
731 int rc = klogctl(KLOG_SIZE_BUFFER, nullptr, 0);
732 if (rc > 0) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700733 ssize_t len = rc + 1024; // 1K Margin should it grow between calls.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700734 std::unique_ptr<char[]> buf(new char[len]);
735 rc = klogctl(KLOG_READ_ALL, buf.get(), len);
736 if (rc < len) {
737 len = rc + 1;
738 }
739 buf[--len] = '\0';
740 content = buf.get();
741 }
742 match = battery;
743 }
744
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700745 pos = content.find(match); // The first one it finds.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700746 if (pos != std::string::npos) {
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700747 digits = content.substr(pos + strlen(match), strlen("100 "));
Mark Salyzyna16e4372017-09-20 08:36:12 -0700748 }
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700749 endptr = digits.c_str();
750 level = 0;
751 while (::isdigit(*endptr)) {
752 level *= 10;
753 level += *endptr++ - '0';
754 // make sure no leading zeros, except zero itself, and range check.
755 if ((level == 0) || (level > 100)) break;
756 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700757 if ((level <= 100) && (endptr != digits.c_str()) && (*endptr == ' ')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700758 LOG(INFO) << "Battery level at startup " << level << "%";
759 if (level <= battery_dead_threshold) {
760 ret = "shutdown,battery";
761 }
762 } else {
763 LOG(DEBUG) << "Can not find first battery level in dmesg or logcat";
764 }
765 }
766 }
767
768 // Is there a controlled shutdown hint in last_reboot_reason_property?
769 if (isBluntRebootReason(ret)) {
770 // Content buffer no longer will have console data. Beware if more
771 // checks added below, that depend on parsing console content.
772 content = GetProperty(last_reboot_reason_property);
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700773 transformReason(content);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700774
Mark Salyzyn62909822017-10-09 09:27:16 -0700775 // Anything in last is better than 'super-blunt' reboot or shutdown.
776 if ((ret == "") || (ret == "reboot") || (ret == "shutdown") || !isBluntRebootReason(content)) {
777 ret = content;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700778 }
779 }
780
781 // Other System Health HAL reasons?
782
783 // ToDo: /proc/sys/kernel/boot_reason needs a HAL interface to
784 // possibly offer hardware-specific clues from the PMIC.
785 }
786
787 // If unknown left over from above, make it "reboot,<boot_reason>"
788 if (ret == "") {
789 ret = "reboot";
790 if (android::base::StartsWith(reason, "reboot")) {
791 reason = reason.substr(strlen("reboot"));
Mark Salyzyn0af71a52017-10-05 13:58:04 -0700792 while ((reason[0] == ',') || (reason[0] == '_')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700793 reason = reason.substr(1);
794 }
795 }
796 if (reason != "") {
797 ret += ",";
798 ret += reason;
799 }
800 }
801
802 LOG(INFO) << "Canonical boot reason: " << ret;
803 if (isKernelRebootReason(ret) && (GetProperty(last_reboot_reason_property) != "")) {
804 // Rewrite as it must be old news, kernel reasons trump user space.
805 SetProperty(last_reboot_reason_property, ret);
806 }
807 return ret;
808}
809
James Hawkinsb9cf7712016-04-08 15:32:19 -0700810// Returns the appropriate metric key prefix for the boot_complete metric such
811// that boot metrics after a system update are labeled as ota_boot_complete;
812// otherwise, they are labeled as boot_complete. This method encapsulates the
813// bookkeeping required to track when a system update has occurred by storing
814// the UTC timestamp of the system build date and comparing against the current
815// system build date.
816std::string CalculateBootCompletePrefix() {
817 static const std::string kBuildDateKey = "build_date";
818 std::string boot_complete_prefix = "boot_complete";
819
820 std::string build_date_str = GetProperty("ro.build.date.utc");
James Hawkins4dded612016-07-28 11:50:23 -0700821 int32_t build_date;
Elliott Hughesda46b392016-10-11 17:09:00 -0700822 if (!android::base::ParseInt(build_date_str, &build_date)) {
James Hawkins4dded612016-07-28 11:50:23 -0700823 return std::string();
824 }
James Hawkinsb9cf7712016-04-08 15:32:19 -0700825
826 BootEventRecordStore boot_event_store;
827 BootEventRecordStore::BootEventRecord record;
James Hawkins0bc4ad42017-05-30 15:03:15 -0700828 if (!boot_event_store.GetBootEvent(kBuildDateKey, &record)) {
829 boot_complete_prefix = "factory_reset_" + 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,factory_reset";
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700832 SetProperty(system_reboot_reason_property, "reboot,factory_reset");
James Hawkins0bc4ad42017-05-30 15:03:15 -0700833 } else if (build_date != record.second) {
James Hawkinsb9cf7712016-04-08 15:32:19 -0700834 boot_complete_prefix = "ota_" + boot_complete_prefix;
835 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700836 LOG(INFO) << "Canonical boot reason: reboot,ota";
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700837 SetProperty(system_reboot_reason_property, "reboot,ota");
James Hawkinsb9cf7712016-04-08 15:32:19 -0700838 }
839
840 return boot_complete_prefix;
841}
842
James Hawkinsef0a0902017-01-06 14:38:23 -0800843// Records the value of a given ro.boottime.init property in milliseconds.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700844void RecordInitBootTimeProp(BootEventRecordStore* boot_event_store, const char* property) {
James Hawkinsef0a0902017-01-06 14:38:23 -0800845 std::string value = GetProperty(property);
846
James Hawkins27c05222017-01-26 11:55:44 -0800847 int32_t time_in_ms;
848 if (android::base::ParseInt(value, &time_in_ms)) {
James Hawkinsef0a0902017-01-06 14:38:23 -0800849 boot_event_store->AddBootEventWithValue(property, time_in_ms);
850 }
851}
852
James Hawkins1bfcaec2017-05-19 14:27:27 -0700853// A map from bootloader timing stage to the time that stage took during boot.
854typedef std::map<std::string, int32_t> BootloaderTimingMap;
855
856// Returns a mapping from bootloader stage names to the time those stages
857// took to boot.
858const BootloaderTimingMap GetBootLoaderTimings() {
859 BootloaderTimingMap timings;
860
861 // |ro.boot.boottime| is of the form 'stage1:time1,...,stageN:timeN',
862 // where timeN is in milliseconds.
James Hawkinsbe46fd12017-02-02 16:21:25 -0800863 std::string value = GetProperty("ro.boot.boottime");
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800864 if (value.empty()) {
865 // ro.boot.boottime is not reported on all devices.
James Hawkins1bfcaec2017-05-19 14:27:27 -0700866 return BootloaderTimingMap();
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800867 }
James Hawkinsbe46fd12017-02-02 16:21:25 -0800868
869 auto stages = android::base::Split(value, ",");
James Hawkins1bfcaec2017-05-19 14:27:27 -0700870 for (const auto& stageTiming : stages) {
James Hawkinsbe46fd12017-02-02 16:21:25 -0800871 // |stageTiming| is of the form 'stage:time'.
872 auto stageTimingValues = android::base::Split(stageTiming, ":");
James Hawkins0bc4ad42017-05-30 15:03:15 -0700873 DCHECK_EQ(2U, stageTimingValues.size());
James Hawkinsbe46fd12017-02-02 16:21:25 -0800874
875 std::string stageName = stageTimingValues[0];
876 int32_t time_ms;
877 if (android::base::ParseInt(stageTimingValues[1], &time_ms)) {
James Hawkins1bfcaec2017-05-19 14:27:27 -0700878 timings[stageName] = time_ms;
James Hawkinsbe46fd12017-02-02 16:21:25 -0800879 }
880 }
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800881
James Hawkins1bfcaec2017-05-19 14:27:27 -0700882 return timings;
883}
884
Tej Singh4eacd382018-01-25 17:59:57 -0800885// Returns the total bootloader boot time from the ro.boot.boottime system property.
886int32_t GetBootloaderTime(const BootloaderTimingMap& bootloader_timings) {
887 int32_t total_time = 0;
888 for (const auto& timing : bootloader_timings) {
889 total_time += timing.second;
890 }
891
892 return total_time;
893}
894
James Hawkins1bfcaec2017-05-19 14:27:27 -0700895// Parses and records the set of bootloader stages and associated boot times
896// from the ro.boot.boottime system property.
897void RecordBootloaderTimings(BootEventRecordStore* boot_event_store,
898 const BootloaderTimingMap& bootloader_timings) {
899 int32_t total_time = 0;
900 for (const auto& timing : bootloader_timings) {
901 total_time += timing.second;
902 boot_event_store->AddBootEventWithValue("boottime.bootloader." + timing.first, timing.second);
903 }
904
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800905 boot_event_store->AddBootEventWithValue("boottime.bootloader.total", total_time);
James Hawkinsbe46fd12017-02-02 16:21:25 -0800906}
907
Tej Singh4eacd382018-01-25 17:59:57 -0800908// Returns the closest estimation to the absolute device boot time, i.e.,
James Hawkins1bfcaec2017-05-19 14:27:27 -0700909// from power on to boot_complete, including bootloader times.
Tej Singh4eacd382018-01-25 17:59:57 -0800910std::chrono::milliseconds GetAbsoluteBootTime(const BootloaderTimingMap& bootloader_timings,
911 std::chrono::milliseconds uptime) {
James Hawkins1bfcaec2017-05-19 14:27:27 -0700912 int32_t bootloader_time_ms = 0;
913
914 for (const auto& timing : bootloader_timings) {
915 if (timing.first.compare("SW") != 0) {
916 bootloader_time_ms += timing.second;
917 }
918 }
919
920 auto bootloader_duration = std::chrono::milliseconds(bootloader_time_ms);
Tej Singh4eacd382018-01-25 17:59:57 -0800921 return bootloader_duration + uptime;
922}
923
924// Records the closest estimation to the absolute device boot time in seconds.
925// i.e. from power on to boot_complete, including bootloader times.
926void RecordAbsoluteBootTime(BootEventRecordStore* boot_event_store,
927 std::chrono::milliseconds absolute_total) {
928 auto absolute_total_sec = std::chrono::duration_cast<std::chrono::seconds>(absolute_total);
929 boot_event_store->AddBootEventWithValue("absolute_boot_time", absolute_total_sec.count());
930}
931
932// Logs the total boot time and reason to statsd.
933void LogBootInfoToStatsd(std::chrono::milliseconds end_time,
934 std::chrono::milliseconds total_duration, int32_t bootloader_duration_ms,
935 double time_since_last_boot_sec) {
936 const std::string reason(GetProperty(bootloader_reboot_reason_property));
937
938 if (reason.empty()) {
939 android::util::stats_write(android::util::BOOT_SEQUENCE_REPORTED, "<EMPTY>", "<EMPTY>",
940 end_time.count(), total_duration.count(),
941 (int64_t)bootloader_duration_ms,
942 (int64_t)time_since_last_boot_sec * 1000);
943 return;
944 }
945
946 const std::string system_reason(BootReasonStrToReason(reason));
947 android::util::stats_write(android::util::BOOT_SEQUENCE_REPORTED, reason.c_str(),
948 system_reason.c_str(), end_time.count(), total_duration.count(),
949 (int64_t)bootloader_duration_ms,
950 (int64_t)time_since_last_boot_sec * 1000);
James Hawkins1bfcaec2017-05-19 14:27:27 -0700951}
952
James Hawkinsc08e9962016-03-11 14:59:50 -0800953// Records several metrics related to the time it takes to boot the device,
954// including disambiguating boot time on encrypted or non-encrypted devices.
955void RecordBootComplete() {
956 BootEventRecordStore boot_event_store;
James Hawkinsb9cf7712016-04-08 15:32:19 -0700957 BootEventRecordStore::BootEventRecord record;
James Hawkins2d8b3e62016-04-14 14:13:20 -0700958
James Hawkins1bfcaec2017-05-19 14:27:27 -0700959 auto time_since_epoch = android::base::boot_clock::now().time_since_epoch();
960 auto uptime = std::chrono::duration_cast<std::chrono::seconds>(time_since_epoch);
James Hawkins2d8b3e62016-04-14 14:13:20 -0700961 time_t current_time_utc = time(nullptr);
Tej Singh4eacd382018-01-25 17:59:57 -0800962 time_t time_since_last_boot = 0;
James Hawkins2d8b3e62016-04-14 14:13:20 -0700963
964 if (boot_event_store.GetBootEvent("last_boot_time_utc", &record)) {
965 time_t last_boot_time_utc = record.second;
Tej Singh4eacd382018-01-25 17:59:57 -0800966 time_since_last_boot = difftime(current_time_utc, last_boot_time_utc);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700967 boot_event_store.AddBootEventWithValue("time_since_last_boot", time_since_last_boot);
James Hawkins2d8b3e62016-04-14 14:13:20 -0700968 }
969
970 boot_event_store.AddBootEventWithValue("last_boot_time_utc", current_time_utc);
James Hawkinsc08e9962016-03-11 14:59:50 -0800971
James Hawkinsb9cf7712016-04-08 15:32:19 -0700972 // The boot_complete metric has two variants: boot_complete and
973 // ota_boot_complete. The latter signifies that the device is booting after
974 // a system update.
975 std::string boot_complete_prefix = CalculateBootCompletePrefix();
James Hawkins4dded612016-07-28 11:50:23 -0700976 if (boot_complete_prefix.empty()) {
977 // The system is hosed because the build date property could not be read.
978 return;
979 }
James Hawkinsc08e9962016-03-11 14:59:50 -0800980
981 // post_decrypt_time_elapsed is only logged on encrypted devices.
982 if (boot_event_store.GetBootEvent("post_decrypt_time_elapsed", &record)) {
983 // Log the amount of time elapsed until the device is decrypted, which
984 // includes the variable amount of time the user takes to enter the
985 // decryption password.
James Hawkinse78ea772017-03-24 11:43:02 -0700986 boot_event_store.AddBootEventWithValue("boot_decryption_complete", uptime.count());
James Hawkinsc08e9962016-03-11 14:59:50 -0800987
988 // Subtract the decryption time to normalize the boot cycle timing.
James Hawkinse78ea772017-03-24 11:43:02 -0700989 std::chrono::seconds boot_complete = std::chrono::seconds(uptime.count() - record.second);
James Hawkinsb9cf7712016-04-08 15:32:19 -0700990 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_post_decrypt",
James Hawkinse78ea772017-03-24 11:43:02 -0700991 boot_complete.count());
James Hawkinsc08e9962016-03-11 14:59:50 -0800992 } else {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700993 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_no_encryption", uptime.count());
James Hawkinsc08e9962016-03-11 14:59:50 -0800994 }
995
996 // Record the total time from device startup to boot complete, regardless of
997 // encryption state.
James Hawkinse78ea772017-03-24 11:43:02 -0700998 boot_event_store.AddBootEventWithValue(boot_complete_prefix, uptime.count());
James Hawkinsef0a0902017-01-06 14:38:23 -0800999
1000 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init");
1001 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.selinux");
1002 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.cold_boot_wait");
James Hawkinsbe46fd12017-02-02 16:21:25 -08001003
James Hawkins1bfcaec2017-05-19 14:27:27 -07001004 const BootloaderTimingMap bootloader_timings = GetBootLoaderTimings();
Tej Singh4eacd382018-01-25 17:59:57 -08001005 int32_t bootloader_boot_duration = GetBootloaderTime(bootloader_timings);
James Hawkins1bfcaec2017-05-19 14:27:27 -07001006 RecordBootloaderTimings(&boot_event_store, bootloader_timings);
1007
1008 auto uptime_ms = std::chrono::duration_cast<std::chrono::milliseconds>(time_since_epoch);
Tej Singh4eacd382018-01-25 17:59:57 -08001009 auto absolute_boot_time = GetAbsoluteBootTime(bootloader_timings, uptime_ms);
1010 RecordAbsoluteBootTime(&boot_event_store, absolute_boot_time);
1011
1012 auto boot_end_time_point = std::chrono::system_clock::now().time_since_epoch();
1013 auto boot_end_time = std::chrono::duration_cast<std::chrono::milliseconds>(boot_end_time_point);
1014
1015 LogBootInfoToStatsd(boot_end_time, absolute_boot_time, bootloader_boot_duration,
1016 time_since_last_boot);
James Hawkinsc08e9962016-03-11 14:59:50 -08001017}
1018
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001019// Records the boot_reason metric by querying the ro.boot.bootreason system
1020// property.
1021void RecordBootReason() {
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001022 const std::string reason(GetProperty(bootloader_reboot_reason_property));
James Hawkins25f71222017-10-10 16:37:05 -07001023
1024 if (reason.empty()) {
1025 // Log an empty boot reason value as '<EMPTY>' to ensure the value is intentional
1026 // (and not corruption anywhere else in the reporting pipeline).
1027 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
1028 android::metricslogger::FIELD_PLATFORM_REASON, "<EMPTY>");
1029 } else {
1030 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
1031 android::metricslogger::FIELD_PLATFORM_REASON, reason);
1032 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001033
1034 // Log the raw bootloader_boot_reason property value.
1035 int32_t boot_reason = BootReasonStrToEnum(reason);
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001036 BootEventRecordStore boot_event_store;
1037 boot_event_store.AddBootEventWithValue("boot_reason", boot_reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001038
1039 // Log the scrubbed system_boot_reason.
1040 const std::string system_reason(BootReasonStrToReason(reason));
1041 int32_t system_boot_reason = BootReasonStrToEnum(system_reason);
1042 boot_event_store.AddBootEventWithValue("system_boot_reason", system_boot_reason);
1043
1044 // Record the scrubbed system_boot_reason to the property
1045 SetProperty(system_reboot_reason_property, system_reason);
1046 if (reason == "") {
1047 SetProperty(bootloader_reboot_reason_property, system_reason);
1048 }
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001049}
1050
James Hawkins500d7152016-02-16 15:05:54 -08001051// Records two metrics related to the user resetting a device: the time at
1052// which the device is reset, and the time since the user last reset the
1053// device. The former is only set once per-factory reset.
1054void RecordFactoryReset() {
1055 BootEventRecordStore boot_event_store;
1056 BootEventRecordStore::BootEventRecord record;
1057
1058 time_t current_time_utc = time(nullptr);
1059
James Hawkins0660b302016-03-08 16:18:15 -08001060 if (current_time_utc < 0) {
1061 // UMA does not display negative values in buckets, so convert to positive.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001062 android::metricslogger::LogHistogram("factory_reset_current_time_failure",
1063 std::abs(current_time_utc));
James Hawkinsfff95ba2016-03-29 16:13:49 -07001064
James Hawkins9aec9262017-01-31 11:42:24 -08001065 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001066 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001067 boot_event_store.AddBootEventWithValue("factory_reset_current_time_failure",
1068 std::abs(current_time_utc));
James Hawkins0660b302016-03-08 16:18:15 -08001069 return;
1070 } else {
James Hawkins9aec9262017-01-31 11:42:24 -08001071 android::metricslogger::LogHistogram("factory_reset_current_time", current_time_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001072
James Hawkins9aec9262017-01-31 11:42:24 -08001073 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001074 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001075 boot_event_store.AddBootEventWithValue("factory_reset_current_time", current_time_utc);
James Hawkins0660b302016-03-08 16:18:15 -08001076 }
1077
James Hawkins500d7152016-02-16 15:05:54 -08001078 // The factory_reset boot event does not exist after the device is reset, so
1079 // use this signal to mark the time of the factory reset.
1080 if (!boot_event_store.GetBootEvent("factory_reset", &record)) {
1081 boot_event_store.AddBootEventWithValue("factory_reset", current_time_utc);
James Hawkins3bf9b142016-03-03 14:50:24 -08001082
1083 // Don't log the time_since_factory_reset until some time has elapsed.
1084 // The data is not meaningful yet and skews the histogram buckets.
James Hawkins500d7152016-02-16 15:05:54 -08001085 return;
1086 }
1087
1088 // Calculate and record the difference in time between now and the
1089 // factory_reset time.
1090 time_t factory_reset_utc = record.second;
James Hawkins9aec9262017-01-31 11:42:24 -08001091 android::metricslogger::LogHistogram("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001092
James Hawkins9aec9262017-01-31 11:42:24 -08001093 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001094 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001095 boot_event_store.AddBootEventWithValue("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001096
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001097 time_t time_since_factory_reset = difftime(current_time_utc, factory_reset_utc);
1098 boot_event_store.AddBootEventWithValue("time_since_factory_reset", time_since_factory_reset);
James Hawkins500d7152016-02-16 15:05:54 -08001099}
1100
James Hawkinsabd73e62016-01-19 15:10:38 -08001101} // namespace
1102
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001103int main(int argc, char** argv) {
James Hawkinsabd73e62016-01-19 15:10:38 -08001104 android::base::InitLogging(argv);
1105
1106 const std::string cmd_line = GetCommandLine(argc, argv);
1107 LOG(INFO) << "Service started: " << cmd_line;
1108
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001109 int option_index = 0;
James Hawkinsc6275582016-03-22 10:47:44 -07001110 static const char value_str[] = "value";
James Hawkinsc08e9962016-03-11 14:59:50 -08001111 static const char boot_complete_str[] = "record_boot_complete";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001112 static const char boot_reason_str[] = "record_boot_reason";
James Hawkins53684ea2016-02-23 16:18:19 -08001113 static const char factory_reset_str[] = "record_time_since_factory_reset";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001114 static const struct option long_options[] = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001115 // clang-format off
1116 { "help", no_argument, NULL, 'h' },
1117 { "log", no_argument, NULL, 'l' },
1118 { "print", no_argument, NULL, 'p' },
1119 { "record", required_argument, NULL, 'r' },
1120 { value_str, required_argument, NULL, 0 },
1121 { boot_complete_str, no_argument, NULL, 0 },
1122 { boot_reason_str, no_argument, NULL, 0 },
1123 { factory_reset_str, no_argument, NULL, 0 },
1124 { NULL, 0, NULL, 0 }
1125 // clang-format on
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001126 };
1127
James Hawkinsc6275582016-03-22 10:47:44 -07001128 std::string boot_event;
1129 std::string value;
James Hawkinsabd73e62016-01-19 15:10:38 -08001130 int opt = 0;
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001131 while ((opt = getopt_long(argc, argv, "hlpr:", long_options, &option_index)) != -1) {
James Hawkinsabd73e62016-01-19 15:10:38 -08001132 switch (opt) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001133 // This case handles long options which have no single-character mapping.
1134 case 0: {
1135 const std::string option_name = long_options[option_index].name;
James Hawkinsc6275582016-03-22 10:47:44 -07001136 if (option_name == value_str) {
1137 // |optarg| is an external variable set by getopt representing
1138 // the option argument.
1139 value = optarg;
1140 } else if (option_name == boot_complete_str) {
James Hawkinsc08e9962016-03-11 14:59:50 -08001141 RecordBootComplete();
1142 } else if (option_name == boot_reason_str) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001143 RecordBootReason();
James Hawkins500d7152016-02-16 15:05:54 -08001144 } else if (option_name == factory_reset_str) {
1145 RecordFactoryReset();
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001146 } else {
1147 LOG(ERROR) << "Invalid option: " << option_name;
1148 }
1149 break;
1150 }
1151
James Hawkinsabd73e62016-01-19 15:10:38 -08001152 case 'h': {
1153 ShowHelp(argv[0]);
1154 break;
1155 }
1156
1157 case 'l': {
1158 LogBootEvents();
1159 break;
1160 }
1161
1162 case 'p': {
1163 PrintBootEvents();
1164 break;
1165 }
1166
1167 case 'r': {
1168 // |optarg| is an external variable set by getopt representing
1169 // the option argument.
James Hawkinsc6275582016-03-22 10:47:44 -07001170 boot_event = optarg;
James Hawkinsabd73e62016-01-19 15:10:38 -08001171 break;
1172 }
1173
1174 default: {
1175 DCHECK_EQ(opt, '?');
1176
1177 // |optopt| is an external variable set by getopt representing
1178 // the value of the invalid option.
1179 LOG(ERROR) << "Invalid option: " << optopt;
1180 ShowHelp(argv[0]);
1181 return EXIT_FAILURE;
1182 }
1183 }
1184 }
1185
James Hawkinsc6275582016-03-22 10:47:44 -07001186 if (!boot_event.empty()) {
1187 RecordBootEventFromCommandLine(boot_event, value);
1188 }
1189
James Hawkinsabd73e62016-01-19 15:10:38 -08001190 return 0;
1191}