blob: dfc46ea6186555fcc45f1ffafce0aa1e81ad26e6 [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>
Mark Salyzyn853bb802018-03-16 08:44:56 -070033#include <utility>
James Hawkinsbe46fd12017-02-02 16:21:25 -080034#include <vector>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070035
James Hawkinse78ea772017-03-24 11:43:02 -070036#include <android-base/chrono_utils.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070037#include <android-base/file.h>
James Hawkinseabe08b2016-01-19 16:54:35 -080038#include <android-base/logging.h>
James Hawkins4dded612016-07-28 11:50:23 -070039#include <android-base/parseint.h>
James Hawkinsbe46fd12017-02-02 16:21:25 -080040#include <android-base/strings.h>
James Hawkinse78ea772017-03-24 11:43:02 -070041#include <android/log.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070042#include <cutils/android_reboot.h>
James Hawkinsa4a1a4a2016-02-09 15:32:38 -080043#include <cutils/properties.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070044#include <log/logcat.h>
James Hawkins9aec9262017-01-31 11:42:24 -080045#include <metricslogger/metrics_logger.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},
Mark Salyzyn853bb802018-03-16 08:44:56 -0700195 {"kernel_panic,null", 53},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700196 {"kernel_panic,BUG", 54},
Mark Salyzyn853bb802018-03-16 08:44:56 -0700197 {"kernel_panic,bug", 54},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700198 {"bootloader", 55},
199 {"cold", 56},
200 {"hard", 57},
201 {"warm", 58},
202 {"recovery", 59},
203 {"thermal-shutdown", 60},
204 {"shutdown,thermal", 61},
205 {"shutdown,battery", 62},
206 {"reboot,ota", 63},
207 {"reboot,factory_reset", 64},
208 {"reboot,", 65},
209 {"reboot,shell", 66},
210 {"reboot,adb", 67},
Mark Salyzyn9033bf52017-09-21 11:30:29 -0700211 {"reboot,userrequested", 68},
Mark Salyzyn161b8622017-09-26 08:26:12 -0700212 {"shutdown,container", 69}, // Host OS asking Android Container to shutdown
Mark Salyzyn243fa292017-10-11 09:02:04 -0700213 {"cold,powerkey", 70},
214 {"warm,s3_wakeup", 71},
215 {"hard,hw_reset", 72},
216 {"shutdown,suspend", 73}, // Suspend to RAM
217 {"shutdown,hibernate", 74}, // Suspend to DISK
James Hawkins34073b52017-10-17 15:53:27 -0700218 {"power_on_key", 75},
219 {"reboot_by_key", 76},
220 {"wdt_by_pass_pwk", 77},
221 {"reboot_longkey", 78},
222 {"powerkey", 79},
223 {"usb", 80},
224 {"wdt", 81},
225 {"tool_by_pass_pwk", 82},
226 {"2sec_reboot", 83},
227 {"reboot,by_key", 84},
228 {"reboot,longkey", 85},
Mark Salyzyncabbe4f2017-10-23 13:52:39 -0700229 {"reboot,2sec", 86},
Mark Salyzync89f9da2017-10-24 15:35:34 -0700230 {"shutdown,thermal,battery", 87},
Mark Salyzyn72a8ea32017-10-25 09:23:19 -0700231 {"reboot,its_just_so_hard", 88}, // produced by boot_reason_test
232 {"reboot,Its Just So Hard", 89}, // produced by boot_reason_test
James Hawkins8ac79bc2017-10-31 10:07:34 -0700233 {"usb", 90},
James Hawkins74b17582017-11-20 14:13:41 -0800234 {"charge", 91},
235 {"oem_tz_crash", 92},
236 {"uvlo", 93},
237 {"oem_ps_hold", 94},
238 {"abnormal_reset", 95},
239 {"oemerr_unknown", 96},
240 {"reboot_fastboot_mode", 97},
James Hawkins5f85f832017-11-29 14:30:06 -0800241 {"watchdog_apps_bite", 98},
242 {"xpu_err", 99},
243 {"power_on_usb", 100},
James Hawkinsf4444f02017-11-30 15:01:40 -0800244 {"watchdog_rpm", 101},
245 {"watchdog_nonsec", 102},
246 {"watchdog_apps_bark", 103},
247 {"reboot_dmverity_corrupted", 104},
James Hawkins00433a22017-12-04 14:20:21 -0800248 {"reboot_smpl", 105},
249 {"watchdog_sdi_apps_reset", 106},
250 {"smpl", 107},
251 {"oem_modem_failed_to_powerup", 108},
James Hawkinse2c27242017-12-18 13:40:27 -0800252 {"reboot_normal", 109},
253 {"oem_lpass_cfg", 110},
254 {"oem_xpu_ns_error", 111},
255 {"power_key_press", 112},
256 {"hardware_reset", 113},
257 {"reboot_by_powerkey", 114},
258 {"reboot_verity", 115},
259 {"oem_rpm_undef_error", 116},
260 {"oem_crash_on_the_lk", 117},
261 {"oem_rpm_reset", 118},
262 {"oem_lpass_cfg", 119},
263 {"oem_xpu_ns_error", 120},
264 {"factory_cable", 121},
265 {"oem_ar6320_failed_to_powerup", 122},
266 {"watchdog_rpm_bite", 123},
267 {"power_on_cable", 124},
268 {"reboot_unknown", 125},
269 {"wireless_charger", 126},
270 {"0x776655ff", 127},
271 {"oem_thermal_bite_reset", 128},
272 {"charger", 129},
273 {"pon1", 130},
274 {"unknown", 131},
275 {"reboot_rtc", 132},
276 {"cold_boot", 133},
277 {"hard_rst", 134},
James Hawkinsb607dae2018-01-05 14:42:55 -0800278 {"power-on", 135},
279 {"oem_adsp_resetting_the_soc", 136},
280 {"kpdpwr", 137},
281 {"oem_modem_timeout_waiting", 138},
282 {"usb_chg", 139},
283 {"warm_reset_0x02", 140},
284 {"warm_reset_0x80", 141},
285 {"pon_reason_0xb0", 142},
286 {"reboot_download", 143},
James Hawkins79a4ee22018-01-26 14:31:04 -0800287 {"reboot_recovery_mode", 144},
288 {"oem_sdi_err_fatal", 145},
289 {"pmic_watchdog", 146},
290 {"software_master", 147},
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800291};
292
293// Converts a string value representing the reason the system booted to an
294// integer representation. This is necessary for logging the boot_reason metric
295// via Tron, which does not accept non-integer buckets in histograms.
296int32_t BootReasonStrToEnum(const std::string& boot_reason) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800297 auto mapping = kBootReasonMap.find(boot_reason);
298 if (mapping != kBootReasonMap.end()) {
299 return mapping->second;
300 }
301
James Hawkins25f71222017-10-10 16:37:05 -0700302 if (boot_reason.empty()) {
303 return kEmptyBootReason;
304 }
305
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800306 LOG(INFO) << "Unknown boot reason: " << boot_reason;
307 return kUnknownBootReason;
308}
309
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700310// Canonical list of supported primary reboot reasons.
311const std::vector<const std::string> knownReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700312 // clang-format off
313 // kernel
314 "watchdog",
315 "kernel_panic",
316 // strong
317 "recovery", // Should not happen from ro.boot.bootreason
318 "bootloader", // Should not happen from ro.boot.bootreason
319 // blunt
320 "cold",
321 "hard",
322 "warm",
Mark Salyzyn62909822017-10-09 09:27:16 -0700323 // super blunt
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700324 "shutdown", // Can not happen from ro.boot.bootreason
325 "reboot", // Default catch-all for anything unknown
326 // clang-format on
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700327};
328
329// Returns true if the supplied reason prefix is considered detailed enough.
330bool isStrongRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700331 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700332 if (s == "cold") break;
333 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800334 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700335 return true;
336 }
337 }
338 return false;
339}
340
341// Returns true if the supplied reason prefix is associated with the kernel.
342bool isKernelRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700343 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700344 if (s == "recovery") break;
345 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800346 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700347 return true;
348 }
349 }
350 return false;
351}
352
353// Returns true if the supplied reason prefix is considered known.
354bool isKnownRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700355 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700356 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800357 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700358 return true;
359 }
360 }
361 return false;
362}
363
364// If the reboot reason should be improved, report true if is too blunt.
365bool isBluntRebootReason(const std::string& r) {
366 if (isStrongRebootReason(r)) return false;
367
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700368 if (!isKnownRebootReason(r)) return true; // Can not support unknown as detail
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700369
370 size_t pos = 0;
371 while ((pos = r.find(',', pos)) != std::string::npos) {
372 ++pos;
373 std::string next(r.substr(pos));
374 if (next.length() == 0) break;
375 if (next[0] == ',') continue;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700376 if (!isKnownRebootReason(next)) return false; // Unknown subreason is good.
377 if (isStrongRebootReason(next)) return false; // eg: reboot,reboot
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700378 }
379 return true;
380}
381
Mark Salyzyn64610892017-09-18 10:41:14 -0700382bool readPstoreConsole(std::string& console) {
383 if (android::base::ReadFileToString("/sys/fs/pstore/console-ramoops-0", &console)) {
384 return true;
385 }
386 return android::base::ReadFileToString("/sys/fs/pstore/console-ramoops", &console);
387}
388
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700389// Implement a variant of std::string::rfind that is resilient to errors in
390// the data stream being inspected.
391class pstoreConsole {
392 private:
393 const size_t kBitErrorRate = 8; // number of bits per error
394 const std::string& console;
395
396 // Number of bits that differ between the two arguments l and r.
397 // Returns zero if the values for l and r are identical.
398 size_t numError(uint8_t l, uint8_t r) const { return std::bitset<8>(l ^ r).count(); }
399
400 // A string comparison function, reports the number of errors discovered
401 // in the match to a maximum of the bitLength / kBitErrorRate, at that
402 // point returning npos to indicate match is too poor.
403 //
404 // Since called in rfind which works backwards, expect cache locality will
405 // help if we check in reverse here as well for performance.
406 //
407 // Assumption: l (from console.c_str() + pos) is long enough to house
408 // _r.length(), checked in rfind caller below.
409 //
410 size_t numError(size_t pos, const std::string& _r) const {
411 const char* l = console.c_str() + pos;
412 const char* r = _r.c_str();
413 size_t n = _r.length();
414 const uint8_t* le = reinterpret_cast<const uint8_t*>(l) + n;
415 const uint8_t* re = reinterpret_cast<const uint8_t*>(r) + n;
416 size_t count = 0;
417 n = 0;
418 do {
419 // individual character bit error rate > threshold + slop
420 size_t num = numError(*--le, *--re);
421 if (num > ((8 + kBitErrorRate) / kBitErrorRate)) return std::string::npos;
422 // total bit error rate > threshold + slop
423 count += num;
424 ++n;
425 if (count > ((n * 8 + kBitErrorRate - (n > 2)) / kBitErrorRate)) {
426 return std::string::npos;
427 }
428 } while (le != reinterpret_cast<const uint8_t*>(l));
429 return count;
430 }
431
432 public:
433 explicit pstoreConsole(const std::string& console) : console(console) {}
434 // scope of argument must be equal to or greater than scope of pstoreConsole
435 explicit pstoreConsole(const std::string&& console) = delete;
436 explicit pstoreConsole(std::string&& console) = delete;
437
438 // Our implementation of rfind, use exact match first, then resort to fuzzy.
439 size_t rfind(const std::string& needle) const {
440 size_t pos = console.rfind(needle); // exact match?
441 if (pos != std::string::npos) return pos;
442
443 // Check to make sure needle fits in console string.
444 pos = console.length();
445 if (needle.length() > pos) return std::string::npos;
446 pos -= needle.length();
447 // fuzzy match to maximum kBitErrorRate
Ivan Lozano44d3cac2017-11-07 13:13:55 -0800448 for (;;) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700449 if (numError(pos, needle) != std::string::npos) return pos;
Ivan Lozano44d3cac2017-11-07 13:13:55 -0800450 if (pos == 0) break;
451 --pos;
452 }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700453 return std::string::npos;
454 }
455
456 // Our implementation of find, use only fuzzy match.
457 size_t find(const std::string& needle, size_t start = 0) const {
458 // Check to make sure needle fits in console string.
459 if (needle.length() > console.length()) return std::string::npos;
460 const size_t last_pos = console.length() - needle.length();
461 // fuzzy match to maximum kBitErrorRate
462 for (size_t pos = start; pos <= last_pos; ++pos) {
463 if (numError(pos, needle) != std::string::npos) return pos;
464 }
465 return std::string::npos;
466 }
467};
468
469// If bit error match to needle, correct it.
470// Return true if any corrections were discovered and applied.
471bool correctForBer(std::string& reason, const std::string& needle) {
472 bool corrected = false;
473 if (reason.length() < needle.length()) return corrected;
474 const pstoreConsole console(reason);
475 const size_t last_pos = reason.length() - needle.length();
476 for (size_t pos = 0; pos <= last_pos; pos += needle.length()) {
477 pos = console.find(needle, pos);
478 if (pos == std::string::npos) break;
479
480 // exact match has no malice
481 if (needle == reason.substr(pos, needle.length())) continue;
482
483 corrected = true;
484 reason = reason.substr(0, pos) + needle + reason.substr(pos + needle.length());
485 }
486 return corrected;
487}
488
489bool addKernelPanicSubReason(const pstoreConsole& console, std::string& ret) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700490 // Check for kernel panic types to refine information
Mark Salyzyn853bb802018-03-16 08:44:56 -0700491 if ((console.rfind("SysRq : Trigger a crash") != std::string::npos) ||
492 (console.rfind("PC is at sysrq_handle_crash+") != std::string::npos)) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700493 // Can not happen, except on userdebug, during testing/debugging.
494 ret = "kernel_panic,sysrq";
495 return true;
496 }
497 if (console.rfind("Unable to handle kernel NULL pointer dereference at virtual address") !=
498 std::string::npos) {
Mark Salyzyn853bb802018-03-16 08:44:56 -0700499 ret = "kernel_panic,null";
Mark Salyzyn64610892017-09-18 10:41:14 -0700500 return true;
501 }
502 if (console.rfind("Kernel BUG at ") != std::string::npos) {
Mark Salyzyn853bb802018-03-16 08:44:56 -0700503 ret = "kernel_panic,bug";
Mark Salyzyn64610892017-09-18 10:41:14 -0700504 return true;
505 }
506 return false;
507}
508
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700509bool addKernelPanicSubReason(const std::string& content, std::string& ret) {
510 return addKernelPanicSubReason(pstoreConsole(content), ret);
511}
512
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700513// std::transform Helper callback functions:
514// Converts a string value representing the reason the system booted to a
515// string complying with Android system standard reason.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700516char tounderline(char c) {
517 return ::isblank(c) ? '_' : c;
518}
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700519
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700520char toprintable(char c) {
521 return ::isprint(c) ? c : '?';
522}
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700523
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700524// Cleanup boot_reason regarding acceptable character set
525void transformReason(std::string& reason) {
526 std::transform(reason.begin(), reason.end(), reason.begin(), ::tolower);
527 std::transform(reason.begin(), reason.end(), reason.begin(), tounderline);
528 std::transform(reason.begin(), reason.end(), reason.begin(), toprintable);
529}
530
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700531const char system_reboot_reason_property[] = "sys.boot.reason";
532const char last_reboot_reason_property[] = LAST_REBOOT_REASON_PROPERTY;
533const char bootloader_reboot_reason_property[] = "ro.boot.bootreason";
534
535// Scrub, Sanitize, Standardize and Enhance the boot reason string supplied.
536std::string BootReasonStrToReason(const std::string& boot_reason) {
Mark Salyzyna16e4372017-09-20 08:36:12 -0700537 static const size_t max_reason_length = 256;
538
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700539 std::string ret(GetProperty(system_reboot_reason_property));
540 std::string reason(boot_reason);
541 // If sys.boot.reason == ro.boot.bootreason, let's re-evaluate
542 if (reason == ret) ret = "";
543
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700544 transformReason(reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700545
546 // Is the current system boot reason sys.boot.reason valid?
547 if (!isKnownRebootReason(ret)) ret = "";
548
549 if (ret == "") {
550 // Is the bootloader boot reason ro.boot.bootreason known?
551 std::vector<std::string> words(android::base::Split(reason, ",_-"));
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700552 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700553 std::string blunt;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700554 for (auto& r : words) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700555 if (r == s) {
556 if (isBluntRebootReason(s)) {
557 blunt = s;
558 } else {
559 ret = s;
560 break;
561 }
562 }
563 }
564 if (ret == "") ret = blunt;
565 if (ret != "") break;
566 }
567 }
568
569 if (ret == "") {
570 // A series of checks to take some officially unsupported reasons
571 // reported by the bootloader and find some logical and canonical
572 // sense. In an ideal world, we would require those bootloaders
573 // to behave and follow our standards.
574 static const std::vector<std::pair<const std::string, const std::string>> aliasReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700575 {"watchdog", "wdog"},
576 {"cold,powerkey", "powerkey"},
577 {"kernel_panic", "panic"},
578 {"shutdown,thermal", "thermal"},
579 {"warm,s3_wakeup", "s3_wakeup"},
580 {"hard,hw_reset", "hw_reset"},
Mark Salyzyncabbe4f2017-10-23 13:52:39 -0700581 {"reboot,2sec", "2sec_reboot"},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700582 {"bootloader", ""},
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700583 };
584
585 // Either the primary or alias is found _somewhere_ in the reason string.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700586 for (auto& s : aliasReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700587 if (reason.find(s.first) != std::string::npos) {
588 ret = s.first;
589 break;
590 }
591 if (s.second.size() && (reason.find(s.second) != std::string::npos)) {
592 ret = s.first;
593 break;
594 }
595 }
596 }
597
598 // If watchdog is the reason, see if there is a security angle?
599 if (ret == "watchdog") {
600 if (reason.find("sec") != std::string::npos) {
601 ret += ",security";
602 }
603 }
604
Mark Salyzyn64610892017-09-18 10:41:14 -0700605 if (ret == "kernel_panic") {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700606 // Check to see if last klog has some refinement hints.
607 std::string content;
Mark Salyzyn64610892017-09-18 10:41:14 -0700608 if (readPstoreConsole(content)) {
609 addKernelPanicSubReason(content, ret);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700610 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700611 } else if (isBluntRebootReason(ret)) {
612 // Check the other available reason resources if the reason is still blunt.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700613
Mark Salyzyn64610892017-09-18 10:41:14 -0700614 // Check to see if last klog has some refinement hints.
615 std::string content;
616 if (readPstoreConsole(content)) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700617 const pstoreConsole console(content);
Mark Salyzyn64610892017-09-18 10:41:14 -0700618 // The toybox reboot command used directly (unlikely)? But also
619 // catches init's response to Android's more controlled reboot command.
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700620 if (console.rfind("reboot: Power down") != std::string::npos) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700621 ret = "shutdown"; // Still too blunt, but more accurate.
622 // ToDo: init should record the shutdown reason to kernel messages ala:
623 // init: shutdown system with command 'last_reboot_reason'
624 // so that if pstore has persistence we can get some details
625 // that could be missing in last_reboot_reason_property.
626 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700627
Mark Salyzyn64610892017-09-18 10:41:14 -0700628 static const char cmd[] = "reboot: Restarting system with command '";
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700629 size_t pos = console.rfind(cmd);
Mark Salyzyn64610892017-09-18 10:41:14 -0700630 if (pos != std::string::npos) {
631 pos += strlen(cmd);
Mark Salyzyna16e4372017-09-20 08:36:12 -0700632 std::string subReason(content.substr(pos, max_reason_length));
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700633 // Correct against any known strings that Bit Error Match
634 for (const auto& s : knownReasons) {
635 correctForBer(subReason, s);
636 }
637 for (const auto& m : kBootReasonMap) {
638 if (m.first.length() <= strlen("cold")) continue; // too short?
639 if (correctForBer(subReason, m.first + "'")) continue;
640 if (m.first.length() <= strlen("reboot,cold")) continue; // short?
641 if (!android::base::StartsWith(m.first, "reboot,")) continue;
642 correctForBer(subReason, m.first.substr(strlen("reboot,")) + "'");
643 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700644 for (pos = 0; pos < subReason.length(); ++pos) {
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700645 char c = subReason[pos];
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700646 // #, &, %, / are common single bit error for ' that we can block
647 if (!::isprint(c) || (c == '\'') || (c == '#') || (c == '&') || (c == '%') || (c == '/')) {
Mark Salyzyna16e4372017-09-20 08:36:12 -0700648 subReason.erase(pos);
649 break;
650 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700651 }
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700652 transformReason(subReason);
Mark Salyzyn64610892017-09-18 10:41:14 -0700653 if (subReason != "") { // Will not land "reboot" as that is too blunt.
654 if (isKernelRebootReason(subReason)) {
655 ret = "reboot," + subReason; // User space can't talk kernel reasons.
Mark Salyzyndafced92017-09-20 08:37:46 -0700656 } else if (isKnownRebootReason(subReason)) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700657 ret = subReason;
Mark Salyzyndafced92017-09-20 08:37:46 -0700658 } else {
659 ret = "reboot," + subReason; // legitimize unknown reasons
Mark Salyzyn64610892017-09-18 10:41:14 -0700660 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700661 }
662 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700663
Mark Salyzyn64610892017-09-18 10:41:14 -0700664 // Check for kernel panics, allowed to override reboot command.
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700665 if (!addKernelPanicSubReason(console, ret) &&
Mark Salyzyn64610892017-09-18 10:41:14 -0700666 // check for long-press power down
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700667 ((console.rfind("Power held for ") != std::string::npos) ||
668 (console.rfind("charger: [") != std::string::npos))) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700669 ret = "cold";
670 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700671 }
672
673 // The following battery test should migrate to a default system health HAL
674
675 // Let us not worry if the reboot command was issued, for the cases of
676 // reboot -p, reboot <no reason>, reboot cold, reboot warm and reboot hard.
677 // Same for bootloader and ro.boot.bootreasons of this set, but a dead
678 // battery could conceivably lead to these, so worthy of override.
679 if (isBluntRebootReason(ret)) {
680 // Heuristic to determine if shutdown possibly because of a dead battery?
681 // Really a hail-mary pass to find it in last klog content ...
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700682 static const int battery_dead_threshold = 2; // percent
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700683 static const char battery[] = "healthd: battery l=";
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700684 const pstoreConsole console(content);
685 size_t pos = console.rfind(battery); // last one
Mark Salyzyna16e4372017-09-20 08:36:12 -0700686 std::string digits;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700687 if (pos != std::string::npos) {
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700688 digits = content.substr(pos + strlen(battery), strlen("100 "));
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700689 // correct common errors
690 correctForBer(digits, "100 ");
691 if (digits[0] == '!') digits[0] = '1';
692 if (digits[1] == '!') digits[1] = '1';
Mark Salyzyna16e4372017-09-20 08:36:12 -0700693 }
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700694 const char* endptr = digits.c_str();
695 unsigned level = 0;
696 while (::isdigit(*endptr)) {
697 level *= 10;
698 level += *endptr++ - '0';
699 // make sure no leading zeros, except zero itself, and range check.
700 if ((level == 0) || (level > 100)) break;
701 }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700702 // example bit error rate issues for 10%
703 // 'l=10 ' no bits in error
704 // 'l=00 ' single bit error (fails above)
705 // 'l=1 ' single bit error
706 // 'l=0 ' double bit error
707 // There are others, not typically critical because of 2%
708 // battery_dead_threshold. KISS check, make sure second
709 // character after digit sequence is not a space.
710 if ((level <= 100) && (endptr != digits.c_str()) && (endptr[0] == ' ') && (endptr[1] != ' ')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700711 LOG(INFO) << "Battery level at shutdown " << level << "%";
712 if (level <= battery_dead_threshold) {
713 ret = "shutdown,battery";
714 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700715 } else { // Most likely
716 digits = ""; // reset digits
717
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700718 // Content buffer no longer will have console data. Beware if more
719 // checks added below, that depend on parsing console content.
720 content = "";
721
722 LOG(DEBUG) << "Can not find last low battery in last console messages";
723 android_logcat_context ctx = create_android_logcat();
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700724 FILE* fp = android_logcat_popen(&ctx, "logcat -b kernel -v brief -d");
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700725 if (fp != nullptr) {
726 android::base::ReadFdToString(fileno(fp), &content);
727 }
728 android_logcat_pclose(&ctx, fp);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700729 static const char logcat_battery[] = "W/healthd ( 0): battery l=";
730 const char* match = logcat_battery;
731
732 if (content == "") {
733 // Service logd.klog not running, go to smaller buffer in the kernel.
734 int rc = klogctl(KLOG_SIZE_BUFFER, nullptr, 0);
735 if (rc > 0) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700736 ssize_t len = rc + 1024; // 1K Margin should it grow between calls.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700737 std::unique_ptr<char[]> buf(new char[len]);
738 rc = klogctl(KLOG_READ_ALL, buf.get(), len);
739 if (rc < len) {
740 len = rc + 1;
741 }
742 buf[--len] = '\0';
743 content = buf.get();
744 }
745 match = battery;
746 }
747
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700748 pos = content.find(match); // The first one it finds.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700749 if (pos != std::string::npos) {
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700750 digits = content.substr(pos + strlen(match), strlen("100 "));
Mark Salyzyna16e4372017-09-20 08:36:12 -0700751 }
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700752 endptr = digits.c_str();
753 level = 0;
754 while (::isdigit(*endptr)) {
755 level *= 10;
756 level += *endptr++ - '0';
757 // make sure no leading zeros, except zero itself, and range check.
758 if ((level == 0) || (level > 100)) break;
759 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700760 if ((level <= 100) && (endptr != digits.c_str()) && (*endptr == ' ')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700761 LOG(INFO) << "Battery level at startup " << level << "%";
762 if (level <= battery_dead_threshold) {
763 ret = "shutdown,battery";
764 }
765 } else {
766 LOG(DEBUG) << "Can not find first battery level in dmesg or logcat";
767 }
768 }
769 }
770
771 // Is there a controlled shutdown hint in last_reboot_reason_property?
772 if (isBluntRebootReason(ret)) {
773 // Content buffer no longer will have console data. Beware if more
774 // checks added below, that depend on parsing console content.
775 content = GetProperty(last_reboot_reason_property);
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700776 transformReason(content);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700777
Mark Salyzyn62909822017-10-09 09:27:16 -0700778 // Anything in last is better than 'super-blunt' reboot or shutdown.
779 if ((ret == "") || (ret == "reboot") || (ret == "shutdown") || !isBluntRebootReason(content)) {
780 ret = content;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700781 }
782 }
783
784 // Other System Health HAL reasons?
785
786 // ToDo: /proc/sys/kernel/boot_reason needs a HAL interface to
787 // possibly offer hardware-specific clues from the PMIC.
788 }
789
790 // If unknown left over from above, make it "reboot,<boot_reason>"
791 if (ret == "") {
792 ret = "reboot";
793 if (android::base::StartsWith(reason, "reboot")) {
794 reason = reason.substr(strlen("reboot"));
Mark Salyzyn0af71a52017-10-05 13:58:04 -0700795 while ((reason[0] == ',') || (reason[0] == '_')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700796 reason = reason.substr(1);
797 }
798 }
799 if (reason != "") {
800 ret += ",";
801 ret += reason;
802 }
803 }
804
805 LOG(INFO) << "Canonical boot reason: " << ret;
806 if (isKernelRebootReason(ret) && (GetProperty(last_reboot_reason_property) != "")) {
807 // Rewrite as it must be old news, kernel reasons trump user space.
808 SetProperty(last_reboot_reason_property, ret);
809 }
810 return ret;
811}
812
James Hawkinsb9cf7712016-04-08 15:32:19 -0700813// Returns the appropriate metric key prefix for the boot_complete metric such
814// that boot metrics after a system update are labeled as ota_boot_complete;
815// otherwise, they are labeled as boot_complete. This method encapsulates the
816// bookkeeping required to track when a system update has occurred by storing
817// the UTC timestamp of the system build date and comparing against the current
818// system build date.
819std::string CalculateBootCompletePrefix() {
820 static const std::string kBuildDateKey = "build_date";
821 std::string boot_complete_prefix = "boot_complete";
822
823 std::string build_date_str = GetProperty("ro.build.date.utc");
James Hawkins4dded612016-07-28 11:50:23 -0700824 int32_t build_date;
Elliott Hughesda46b392016-10-11 17:09:00 -0700825 if (!android::base::ParseInt(build_date_str, &build_date)) {
James Hawkins4dded612016-07-28 11:50:23 -0700826 return std::string();
827 }
James Hawkinsb9cf7712016-04-08 15:32:19 -0700828
829 BootEventRecordStore boot_event_store;
830 BootEventRecordStore::BootEventRecord record;
James Hawkins0bc4ad42017-05-30 15:03:15 -0700831 if (!boot_event_store.GetBootEvent(kBuildDateKey, &record)) {
832 boot_complete_prefix = "factory_reset_" + boot_complete_prefix;
833 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700834 LOG(INFO) << "Canonical boot reason: reboot,factory_reset";
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700835 SetProperty(system_reboot_reason_property, "reboot,factory_reset");
James Hawkins0bc4ad42017-05-30 15:03:15 -0700836 } else if (build_date != record.second) {
James Hawkinsb9cf7712016-04-08 15:32:19 -0700837 boot_complete_prefix = "ota_" + boot_complete_prefix;
838 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700839 LOG(INFO) << "Canonical boot reason: reboot,ota";
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700840 SetProperty(system_reboot_reason_property, "reboot,ota");
James Hawkinsb9cf7712016-04-08 15:32:19 -0700841 }
842
843 return boot_complete_prefix;
844}
845
James Hawkinsef0a0902017-01-06 14:38:23 -0800846// Records the value of a given ro.boottime.init property in milliseconds.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700847void RecordInitBootTimeProp(BootEventRecordStore* boot_event_store, const char* property) {
James Hawkinsef0a0902017-01-06 14:38:23 -0800848 std::string value = GetProperty(property);
849
James Hawkins27c05222017-01-26 11:55:44 -0800850 int32_t time_in_ms;
851 if (android::base::ParseInt(value, &time_in_ms)) {
James Hawkinsef0a0902017-01-06 14:38:23 -0800852 boot_event_store->AddBootEventWithValue(property, time_in_ms);
853 }
854}
855
James Hawkins1bfcaec2017-05-19 14:27:27 -0700856// A map from bootloader timing stage to the time that stage took during boot.
857typedef std::map<std::string, int32_t> BootloaderTimingMap;
858
859// Returns a mapping from bootloader stage names to the time those stages
860// took to boot.
861const BootloaderTimingMap GetBootLoaderTimings() {
862 BootloaderTimingMap timings;
863
864 // |ro.boot.boottime| is of the form 'stage1:time1,...,stageN:timeN',
865 // where timeN is in milliseconds.
James Hawkinsbe46fd12017-02-02 16:21:25 -0800866 std::string value = GetProperty("ro.boot.boottime");
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800867 if (value.empty()) {
868 // ro.boot.boottime is not reported on all devices.
James Hawkins1bfcaec2017-05-19 14:27:27 -0700869 return BootloaderTimingMap();
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800870 }
James Hawkinsbe46fd12017-02-02 16:21:25 -0800871
872 auto stages = android::base::Split(value, ",");
James Hawkins1bfcaec2017-05-19 14:27:27 -0700873 for (const auto& stageTiming : stages) {
James Hawkinsbe46fd12017-02-02 16:21:25 -0800874 // |stageTiming| is of the form 'stage:time'.
875 auto stageTimingValues = android::base::Split(stageTiming, ":");
James Hawkins0bc4ad42017-05-30 15:03:15 -0700876 DCHECK_EQ(2U, stageTimingValues.size());
James Hawkinsbe46fd12017-02-02 16:21:25 -0800877
878 std::string stageName = stageTimingValues[0];
879 int32_t time_ms;
880 if (android::base::ParseInt(stageTimingValues[1], &time_ms)) {
James Hawkins1bfcaec2017-05-19 14:27:27 -0700881 timings[stageName] = time_ms;
James Hawkinsbe46fd12017-02-02 16:21:25 -0800882 }
883 }
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800884
James Hawkins1bfcaec2017-05-19 14:27:27 -0700885 return timings;
886}
887
888// Parses and records the set of bootloader stages and associated boot times
889// from the ro.boot.boottime system property.
890void RecordBootloaderTimings(BootEventRecordStore* boot_event_store,
891 const BootloaderTimingMap& bootloader_timings) {
892 int32_t total_time = 0;
893 for (const auto& timing : bootloader_timings) {
894 total_time += timing.second;
895 boot_event_store->AddBootEventWithValue("boottime.bootloader." + timing.first, timing.second);
896 }
897
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800898 boot_event_store->AddBootEventWithValue("boottime.bootloader.total", total_time);
James Hawkinsbe46fd12017-02-02 16:21:25 -0800899}
900
James Hawkins1bfcaec2017-05-19 14:27:27 -0700901// Records the closest estimation to the absolute device boot time, i.e.,
902// from power on to boot_complete, including bootloader times.
903void RecordAbsoluteBootTime(BootEventRecordStore* boot_event_store,
904 const BootloaderTimingMap& bootloader_timings,
905 std::chrono::milliseconds uptime) {
906 int32_t bootloader_time_ms = 0;
907
908 for (const auto& timing : bootloader_timings) {
909 if (timing.first.compare("SW") != 0) {
910 bootloader_time_ms += timing.second;
911 }
912 }
913
914 auto bootloader_duration = std::chrono::milliseconds(bootloader_time_ms);
915 auto absolute_total =
916 std::chrono::duration_cast<std::chrono::seconds>(bootloader_duration + uptime);
917 boot_event_store->AddBootEventWithValue("absolute_boot_time", absolute_total.count());
918}
919
James Hawkinsc08e9962016-03-11 14:59:50 -0800920// Records several metrics related to the time it takes to boot the device,
921// including disambiguating boot time on encrypted or non-encrypted devices.
922void RecordBootComplete() {
923 BootEventRecordStore boot_event_store;
James Hawkinsb9cf7712016-04-08 15:32:19 -0700924 BootEventRecordStore::BootEventRecord record;
James Hawkins2d8b3e62016-04-14 14:13:20 -0700925
James Hawkins1bfcaec2017-05-19 14:27:27 -0700926 auto time_since_epoch = android::base::boot_clock::now().time_since_epoch();
927 auto uptime = std::chrono::duration_cast<std::chrono::seconds>(time_since_epoch);
James Hawkins2d8b3e62016-04-14 14:13:20 -0700928 time_t current_time_utc = time(nullptr);
929
930 if (boot_event_store.GetBootEvent("last_boot_time_utc", &record)) {
931 time_t last_boot_time_utc = record.second;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700932 time_t time_since_last_boot = difftime(current_time_utc, last_boot_time_utc);
933 boot_event_store.AddBootEventWithValue("time_since_last_boot", time_since_last_boot);
James Hawkins2d8b3e62016-04-14 14:13:20 -0700934 }
935
936 boot_event_store.AddBootEventWithValue("last_boot_time_utc", current_time_utc);
James Hawkinsc08e9962016-03-11 14:59:50 -0800937
James Hawkinsb9cf7712016-04-08 15:32:19 -0700938 // The boot_complete metric has two variants: boot_complete and
939 // ota_boot_complete. The latter signifies that the device is booting after
940 // a system update.
941 std::string boot_complete_prefix = CalculateBootCompletePrefix();
James Hawkins4dded612016-07-28 11:50:23 -0700942 if (boot_complete_prefix.empty()) {
943 // The system is hosed because the build date property could not be read.
944 return;
945 }
James Hawkinsc08e9962016-03-11 14:59:50 -0800946
947 // post_decrypt_time_elapsed is only logged on encrypted devices.
948 if (boot_event_store.GetBootEvent("post_decrypt_time_elapsed", &record)) {
949 // Log the amount of time elapsed until the device is decrypted, which
950 // includes the variable amount of time the user takes to enter the
951 // decryption password.
James Hawkinse78ea772017-03-24 11:43:02 -0700952 boot_event_store.AddBootEventWithValue("boot_decryption_complete", uptime.count());
James Hawkinsc08e9962016-03-11 14:59:50 -0800953
954 // Subtract the decryption time to normalize the boot cycle timing.
James Hawkinse78ea772017-03-24 11:43:02 -0700955 std::chrono::seconds boot_complete = std::chrono::seconds(uptime.count() - record.second);
James Hawkinsb9cf7712016-04-08 15:32:19 -0700956 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_post_decrypt",
James Hawkinse78ea772017-03-24 11:43:02 -0700957 boot_complete.count());
James Hawkinsc08e9962016-03-11 14:59:50 -0800958 } else {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700959 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_no_encryption", uptime.count());
James Hawkinsc08e9962016-03-11 14:59:50 -0800960 }
961
962 // Record the total time from device startup to boot complete, regardless of
963 // encryption state.
James Hawkinse78ea772017-03-24 11:43:02 -0700964 boot_event_store.AddBootEventWithValue(boot_complete_prefix, uptime.count());
James Hawkinsef0a0902017-01-06 14:38:23 -0800965
966 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init");
967 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.selinux");
968 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.cold_boot_wait");
James Hawkinsbe46fd12017-02-02 16:21:25 -0800969
James Hawkins1bfcaec2017-05-19 14:27:27 -0700970 const BootloaderTimingMap bootloader_timings = GetBootLoaderTimings();
971 RecordBootloaderTimings(&boot_event_store, bootloader_timings);
972
973 auto uptime_ms = std::chrono::duration_cast<std::chrono::milliseconds>(time_since_epoch);
974 RecordAbsoluteBootTime(&boot_event_store, bootloader_timings, uptime_ms);
James Hawkinsc08e9962016-03-11 14:59:50 -0800975}
976
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800977// Records the boot_reason metric by querying the ro.boot.bootreason system
978// property.
979void RecordBootReason() {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700980 const std::string reason(GetProperty(bootloader_reboot_reason_property));
James Hawkins25f71222017-10-10 16:37:05 -0700981
982 if (reason.empty()) {
983 // Log an empty boot reason value as '<EMPTY>' to ensure the value is intentional
984 // (and not corruption anywhere else in the reporting pipeline).
985 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
986 android::metricslogger::FIELD_PLATFORM_REASON, "<EMPTY>");
987 } else {
988 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
989 android::metricslogger::FIELD_PLATFORM_REASON, reason);
990 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700991
992 // Log the raw bootloader_boot_reason property value.
993 int32_t boot_reason = BootReasonStrToEnum(reason);
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800994 BootEventRecordStore boot_event_store;
995 boot_event_store.AddBootEventWithValue("boot_reason", boot_reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700996
997 // Log the scrubbed system_boot_reason.
998 const std::string system_reason(BootReasonStrToReason(reason));
999 int32_t system_boot_reason = BootReasonStrToEnum(system_reason);
1000 boot_event_store.AddBootEventWithValue("system_boot_reason", system_boot_reason);
1001
1002 // Record the scrubbed system_boot_reason to the property
1003 SetProperty(system_reboot_reason_property, system_reason);
1004 if (reason == "") {
1005 SetProperty(bootloader_reboot_reason_property, system_reason);
1006 }
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001007}
1008
James Hawkins500d7152016-02-16 15:05:54 -08001009// Records two metrics related to the user resetting a device: the time at
1010// which the device is reset, and the time since the user last reset the
1011// device. The former is only set once per-factory reset.
1012void RecordFactoryReset() {
1013 BootEventRecordStore boot_event_store;
1014 BootEventRecordStore::BootEventRecord record;
1015
1016 time_t current_time_utc = time(nullptr);
1017
James Hawkins0660b302016-03-08 16:18:15 -08001018 if (current_time_utc < 0) {
1019 // UMA does not display negative values in buckets, so convert to positive.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001020 android::metricslogger::LogHistogram("factory_reset_current_time_failure",
1021 std::abs(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_failure",
1026 std::abs(current_time_utc));
James Hawkins0660b302016-03-08 16:18:15 -08001027 return;
1028 } else {
James Hawkins9aec9262017-01-31 11:42:24 -08001029 android::metricslogger::LogHistogram("factory_reset_current_time", current_time_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001030
James Hawkins9aec9262017-01-31 11:42:24 -08001031 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001032 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001033 boot_event_store.AddBootEventWithValue("factory_reset_current_time", current_time_utc);
James Hawkins0660b302016-03-08 16:18:15 -08001034 }
1035
James Hawkins500d7152016-02-16 15:05:54 -08001036 // The factory_reset boot event does not exist after the device is reset, so
1037 // use this signal to mark the time of the factory reset.
1038 if (!boot_event_store.GetBootEvent("factory_reset", &record)) {
1039 boot_event_store.AddBootEventWithValue("factory_reset", current_time_utc);
James Hawkins3bf9b142016-03-03 14:50:24 -08001040
1041 // Don't log the time_since_factory_reset until some time has elapsed.
1042 // The data is not meaningful yet and skews the histogram buckets.
James Hawkins500d7152016-02-16 15:05:54 -08001043 return;
1044 }
1045
1046 // Calculate and record the difference in time between now and the
1047 // factory_reset time.
1048 time_t factory_reset_utc = record.second;
James Hawkins9aec9262017-01-31 11:42:24 -08001049 android::metricslogger::LogHistogram("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001050
James Hawkins9aec9262017-01-31 11:42:24 -08001051 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001052 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001053 boot_event_store.AddBootEventWithValue("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001054
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001055 time_t time_since_factory_reset = difftime(current_time_utc, factory_reset_utc);
1056 boot_event_store.AddBootEventWithValue("time_since_factory_reset", time_since_factory_reset);
James Hawkins500d7152016-02-16 15:05:54 -08001057}
1058
James Hawkinsabd73e62016-01-19 15:10:38 -08001059} // namespace
1060
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001061int main(int argc, char** argv) {
James Hawkinsabd73e62016-01-19 15:10:38 -08001062 android::base::InitLogging(argv);
1063
1064 const std::string cmd_line = GetCommandLine(argc, argv);
1065 LOG(INFO) << "Service started: " << cmd_line;
1066
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001067 int option_index = 0;
James Hawkinsc6275582016-03-22 10:47:44 -07001068 static const char value_str[] = "value";
James Hawkinsc08e9962016-03-11 14:59:50 -08001069 static const char boot_complete_str[] = "record_boot_complete";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001070 static const char boot_reason_str[] = "record_boot_reason";
James Hawkins53684ea2016-02-23 16:18:19 -08001071 static const char factory_reset_str[] = "record_time_since_factory_reset";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001072 static const struct option long_options[] = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001073 // clang-format off
1074 { "help", no_argument, NULL, 'h' },
1075 { "log", no_argument, NULL, 'l' },
1076 { "print", no_argument, NULL, 'p' },
1077 { "record", required_argument, NULL, 'r' },
1078 { value_str, required_argument, NULL, 0 },
1079 { boot_complete_str, no_argument, NULL, 0 },
1080 { boot_reason_str, no_argument, NULL, 0 },
1081 { factory_reset_str, no_argument, NULL, 0 },
1082 { NULL, 0, NULL, 0 }
1083 // clang-format on
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001084 };
1085
James Hawkinsc6275582016-03-22 10:47:44 -07001086 std::string boot_event;
1087 std::string value;
James Hawkinsabd73e62016-01-19 15:10:38 -08001088 int opt = 0;
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001089 while ((opt = getopt_long(argc, argv, "hlpr:", long_options, &option_index)) != -1) {
James Hawkinsabd73e62016-01-19 15:10:38 -08001090 switch (opt) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001091 // This case handles long options which have no single-character mapping.
1092 case 0: {
1093 const std::string option_name = long_options[option_index].name;
James Hawkinsc6275582016-03-22 10:47:44 -07001094 if (option_name == value_str) {
1095 // |optarg| is an external variable set by getopt representing
1096 // the option argument.
1097 value = optarg;
1098 } else if (option_name == boot_complete_str) {
James Hawkinsc08e9962016-03-11 14:59:50 -08001099 RecordBootComplete();
1100 } else if (option_name == boot_reason_str) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001101 RecordBootReason();
James Hawkins500d7152016-02-16 15:05:54 -08001102 } else if (option_name == factory_reset_str) {
1103 RecordFactoryReset();
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001104 } else {
1105 LOG(ERROR) << "Invalid option: " << option_name;
1106 }
1107 break;
1108 }
1109
James Hawkinsabd73e62016-01-19 15:10:38 -08001110 case 'h': {
1111 ShowHelp(argv[0]);
1112 break;
1113 }
1114
1115 case 'l': {
1116 LogBootEvents();
1117 break;
1118 }
1119
1120 case 'p': {
1121 PrintBootEvents();
1122 break;
1123 }
1124
1125 case 'r': {
1126 // |optarg| is an external variable set by getopt representing
1127 // the option argument.
James Hawkinsc6275582016-03-22 10:47:44 -07001128 boot_event = optarg;
James Hawkinsabd73e62016-01-19 15:10:38 -08001129 break;
1130 }
1131
1132 default: {
1133 DCHECK_EQ(opt, '?');
1134
1135 // |optopt| is an external variable set by getopt representing
1136 // the value of the invalid option.
1137 LOG(ERROR) << "Invalid option: " << optopt;
1138 ShowHelp(argv[0]);
1139 return EXIT_FAILURE;
1140 }
1141 }
1142 }
1143
James Hawkinsc6275582016-03-22 10:47:44 -07001144 if (!boot_event.empty()) {
1145 RecordBootEventFromCommandLine(boot_event, value);
1146 }
1147
James Hawkinsabd73e62016-01-19 15:10:38 -08001148 return 0;
1149}