blob: 7a6789435c54b57fc64d0c5a24100606d56905d5 [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>
Luis Hector Chavez583d34c2018-04-12 15:25:15 -070039#include <android-base/properties.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>
Tej Singh4eacd382018-01-25 17:59:57 -080046#include <statslog.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070047
James Hawkinsabd73e62016-01-19 15:10:38 -080048#include "boot_event_record_store.h"
James Hawkinsabd73e62016-01-19 15:10:38 -080049
50namespace {
51
James Hawkinsabd73e62016-01-19 15:10:38 -080052// Scans the boot event record store for record files and logs each boot event
53// via EventLog.
54void LogBootEvents() {
55 BootEventRecordStore boot_event_store;
56
57 auto events = boot_event_store.GetAllBootEvents();
58 for (auto i = events.cbegin(); i != events.cend(); ++i) {
James Hawkins9aec9262017-01-31 11:42:24 -080059 android::metricslogger::LogHistogram(i->first, i->second);
James Hawkinsabd73e62016-01-19 15:10:38 -080060 }
61}
62
James Hawkinsc6275582016-03-22 10:47:44 -070063// Records the named boot |event| to the record store. If |value| is non-empty
64// and is a proper string representation of an integer value, the converted
65// integer value is associated with the boot event.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -070066void RecordBootEventFromCommandLine(const std::string& event, const std::string& value_str) {
James Hawkinsc6275582016-03-22 10:47:44 -070067 BootEventRecordStore boot_event_store;
68 if (!value_str.empty()) {
69 int32_t value = 0;
Elliott Hughesda46b392016-10-11 17:09:00 -070070 if (android::base::ParseInt(value_str, &value)) {
James Hawkins4dded612016-07-28 11:50:23 -070071 boot_event_store.AddBootEventWithValue(event, value);
72 }
James Hawkinsc6275582016-03-22 10:47:44 -070073 } else {
74 boot_event_store.AddBootEvent(event);
75 }
76}
77
James Hawkinsabd73e62016-01-19 15:10:38 -080078void PrintBootEvents() {
79 printf("Boot events:\n");
80 printf("------------\n");
81
82 BootEventRecordStore boot_event_store;
83 auto events = boot_event_store.GetAllBootEvents();
84 for (auto i = events.cbegin(); i != events.cend(); ++i) {
85 printf("%s\t%d\n", i->first.c_str(), i->second);
86 }
87}
88
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -070089void ShowHelp(const char* cmd) {
James Hawkinsabd73e62016-01-19 15:10:38 -080090 fprintf(stderr, "Usage: %s [options]\n", cmd);
91 fprintf(stderr,
92 "options include:\n"
Yongqin Liu78b2b942017-07-07 13:26:49 +080093 " -h, --help Show this help\n"
94 " -l, --log Log all metrics to logstorage\n"
95 " -p, --print Dump the boot event records to the console\n"
96 " -r, --record Record the timestamp of a named boot event\n"
97 " --value Optional value to associate with the boot event\n"
98 " --record_boot_complete Record metrics related to the time for the device boot\n"
99 " --record_boot_reason Record the reason why the device booted\n"
James Hawkins53684ea2016-02-23 16:18:19 -0800100 " --record_time_since_factory_reset Record the time since the device was reset\n");
James Hawkinsabd73e62016-01-19 15:10:38 -0800101}
102
103// Constructs a readable, printable string from the givencommand line
104// arguments.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700105std::string GetCommandLine(int argc, char** argv) {
James Hawkinsabd73e62016-01-19 15:10:38 -0800106 std::string cmd;
107 for (int i = 0; i < argc; ++i) {
108 cmd += argv[i];
109 cmd += " ";
110 }
111
112 return cmd;
113}
114
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800115// Convenience wrapper over the property API that returns an
116// std::string.
117std::string GetProperty(const char* key) {
118 std::vector<char> temp(PROPERTY_VALUE_MAX);
119 const int len = property_get(key, &temp[0], nullptr);
120 if (len < 0) {
121 return "";
122 }
123 return std::string(&temp[0], len);
124}
125
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700126void SetProperty(const char* key, const std::string& val) {
127 property_set(key, val.c_str());
128}
129
130void SetProperty(const char* key, const char* val) {
131 property_set(key, val);
132}
133
James Hawkins25f71222017-10-10 16:37:05 -0700134constexpr int32_t kEmptyBootReason = 0;
James Hawkins6f74c0b2016-02-12 15:49:16 -0800135constexpr int32_t kUnknownBootReason = 1;
136
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800137// A mapping from boot reason string, as read from the ro.boot.bootreason
138// system property, to a unique integer ID. Viewers of log data dashboards for
139// the boot_reason metric may refer to this mapping to discern the histogram
140// values.
James Hawkins6f74c0b2016-02-12 15:49:16 -0800141const std::map<std::string, int32_t> kBootReasonMap = {
James Hawkins25f71222017-10-10 16:37:05 -0700142 {"empty", kEmptyBootReason},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700143 {"unknown", kUnknownBootReason},
144 {"normal", 2},
145 {"recovery", 3},
146 {"reboot", 4},
147 {"PowerKey", 5},
148 {"hard_reset", 6},
149 {"kernel_panic", 7},
150 {"rpm_err", 8},
151 {"hw_reset", 9},
152 {"tz_err", 10},
153 {"adsp_err", 11},
154 {"modem_err", 12},
155 {"mba_err", 13},
156 {"Watchdog", 14},
157 {"Panic", 15},
158 {"power_key", 16},
159 {"power_on", 17},
160 {"Reboot", 18},
161 {"rtc", 19},
162 {"edl", 20},
163 {"oem_pon1", 21},
164 {"oem_powerkey", 22},
165 {"oem_unknown_reset", 23},
166 {"srto: HWWDT reset SC", 24},
167 {"srto: HWWDT reset platform", 25},
168 {"srto: bootloader", 26},
169 {"srto: kernel panic", 27},
170 {"srto: kernel watchdog reset", 28},
171 {"srto: normal", 29},
172 {"srto: reboot", 30},
173 {"srto: reboot-bootloader", 31},
174 {"srto: security watchdog reset", 32},
175 {"srto: wakesrc", 33},
176 {"srto: watchdog", 34},
177 {"srto:1-1", 35},
178 {"srto:omap_hsmm", 36},
179 {"srto:phy0", 37},
180 {"srto:rtc0", 38},
181 {"srto:touchpad", 39},
182 {"watchdog", 40},
183 {"watchdogr", 41},
184 {"wdog_bark", 42},
185 {"wdog_bite", 43},
186 {"wdog_reset", 44},
187 {"shutdown,", 45}, // Trailing comma is intentional.
188 {"shutdown,userrequested", 46},
189 {"reboot,bootloader", 47},
190 {"reboot,cold", 48},
191 {"reboot,recovery", 49},
192 {"thermal_shutdown", 50},
193 {"s3_wakeup", 51},
194 {"kernel_panic,sysrq", 52},
195 {"kernel_panic,NULL", 53},
196 {"kernel_panic,BUG", 54},
197 {"bootloader", 55},
198 {"cold", 56},
199 {"hard", 57},
200 {"warm", 58},
201 {"recovery", 59},
202 {"thermal-shutdown", 60},
203 {"shutdown,thermal", 61},
204 {"shutdown,battery", 62},
205 {"reboot,ota", 63},
206 {"reboot,factory_reset", 64},
207 {"reboot,", 65},
208 {"reboot,shell", 66},
209 {"reboot,adb", 67},
Mark Salyzyn9033bf52017-09-21 11:30:29 -0700210 {"reboot,userrequested", 68},
Mark Salyzyn161b8622017-09-26 08:26:12 -0700211 {"shutdown,container", 69}, // Host OS asking Android Container to shutdown
Mark Salyzyn243fa292017-10-11 09:02:04 -0700212 {"cold,powerkey", 70},
213 {"warm,s3_wakeup", 71},
214 {"hard,hw_reset", 72},
215 {"shutdown,suspend", 73}, // Suspend to RAM
216 {"shutdown,hibernate", 74}, // Suspend to DISK
James Hawkins34073b52017-10-17 15:53:27 -0700217 {"power_on_key", 75},
218 {"reboot_by_key", 76},
219 {"wdt_by_pass_pwk", 77},
220 {"reboot_longkey", 78},
221 {"powerkey", 79},
222 {"usb", 80},
223 {"wdt", 81},
224 {"tool_by_pass_pwk", 82},
225 {"2sec_reboot", 83},
226 {"reboot,by_key", 84},
227 {"reboot,longkey", 85},
Mark Salyzyncabbe4f2017-10-23 13:52:39 -0700228 {"reboot,2sec", 86},
Mark Salyzync89f9da2017-10-24 15:35:34 -0700229 {"shutdown,thermal,battery", 87},
Mark Salyzyn72a8ea32017-10-25 09:23:19 -0700230 {"reboot,its_just_so_hard", 88}, // produced by boot_reason_test
231 {"reboot,Its Just So Hard", 89}, // produced by boot_reason_test
James Hawkins8ac79bc2017-10-31 10:07:34 -0700232 {"usb", 90},
James Hawkins74b17582017-11-20 14:13:41 -0800233 {"charge", 91},
234 {"oem_tz_crash", 92},
235 {"uvlo", 93},
236 {"oem_ps_hold", 94},
237 {"abnormal_reset", 95},
238 {"oemerr_unknown", 96},
239 {"reboot_fastboot_mode", 97},
James Hawkins5f85f832017-11-29 14:30:06 -0800240 {"watchdog_apps_bite", 98},
241 {"xpu_err", 99},
242 {"power_on_usb", 100},
James Hawkinsf4444f02017-11-30 15:01:40 -0800243 {"watchdog_rpm", 101},
244 {"watchdog_nonsec", 102},
245 {"watchdog_apps_bark", 103},
246 {"reboot_dmverity_corrupted", 104},
James Hawkins00433a22017-12-04 14:20:21 -0800247 {"reboot_smpl", 105},
248 {"watchdog_sdi_apps_reset", 106},
249 {"smpl", 107},
250 {"oem_modem_failed_to_powerup", 108},
James Hawkinse2c27242017-12-18 13:40:27 -0800251 {"reboot_normal", 109},
252 {"oem_lpass_cfg", 110},
253 {"oem_xpu_ns_error", 111},
254 {"power_key_press", 112},
255 {"hardware_reset", 113},
256 {"reboot_by_powerkey", 114},
257 {"reboot_verity", 115},
258 {"oem_rpm_undef_error", 116},
259 {"oem_crash_on_the_lk", 117},
260 {"oem_rpm_reset", 118},
261 {"oem_lpass_cfg", 119},
262 {"oem_xpu_ns_error", 120},
263 {"factory_cable", 121},
264 {"oem_ar6320_failed_to_powerup", 122},
265 {"watchdog_rpm_bite", 123},
266 {"power_on_cable", 124},
267 {"reboot_unknown", 125},
268 {"wireless_charger", 126},
269 {"0x776655ff", 127},
270 {"oem_thermal_bite_reset", 128},
271 {"charger", 129},
272 {"pon1", 130},
273 {"unknown", 131},
274 {"reboot_rtc", 132},
275 {"cold_boot", 133},
276 {"hard_rst", 134},
James Hawkinsb607dae2018-01-05 14:42:55 -0800277 {"power-on", 135},
278 {"oem_adsp_resetting_the_soc", 136},
279 {"kpdpwr", 137},
280 {"oem_modem_timeout_waiting", 138},
281 {"usb_chg", 139},
282 {"warm_reset_0x02", 140},
283 {"warm_reset_0x80", 141},
284 {"pon_reason_0xb0", 142},
285 {"reboot_download", 143},
James Hawkins79a4ee22018-01-26 14:31:04 -0800286 {"reboot_recovery_mode", 144},
287 {"oem_sdi_err_fatal", 145},
288 {"pmic_watchdog", 146},
289 {"software_master", 147},
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800290};
291
292// Converts a string value representing the reason the system booted to an
293// integer representation. This is necessary for logging the boot_reason metric
294// via Tron, which does not accept non-integer buckets in histograms.
295int32_t BootReasonStrToEnum(const std::string& boot_reason) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800296 auto mapping = kBootReasonMap.find(boot_reason);
297 if (mapping != kBootReasonMap.end()) {
298 return mapping->second;
299 }
300
James Hawkins25f71222017-10-10 16:37:05 -0700301 if (boot_reason.empty()) {
302 return kEmptyBootReason;
303 }
304
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800305 LOG(INFO) << "Unknown boot reason: " << boot_reason;
306 return kUnknownBootReason;
307}
308
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700309// Canonical list of supported primary reboot reasons.
310const std::vector<const std::string> knownReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700311 // clang-format off
312 // kernel
313 "watchdog",
314 "kernel_panic",
315 // strong
316 "recovery", // Should not happen from ro.boot.bootreason
317 "bootloader", // Should not happen from ro.boot.bootreason
318 // blunt
319 "cold",
320 "hard",
321 "warm",
Mark Salyzyn62909822017-10-09 09:27:16 -0700322 // super blunt
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700323 "shutdown", // Can not happen from ro.boot.bootreason
324 "reboot", // Default catch-all for anything unknown
325 // clang-format on
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700326};
327
328// Returns true if the supplied reason prefix is considered detailed enough.
329bool isStrongRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700330 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700331 if (s == "cold") break;
332 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800333 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700334 return true;
335 }
336 }
337 return false;
338}
339
340// Returns true if the supplied reason prefix is associated with the kernel.
341bool isKernelRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700342 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700343 if (s == "recovery") break;
344 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800345 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700346 return true;
347 }
348 }
349 return false;
350}
351
352// Returns true if the supplied reason prefix is considered known.
353bool isKnownRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700354 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700355 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800356 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700357 return true;
358 }
359 }
360 return false;
361}
362
363// If the reboot reason should be improved, report true if is too blunt.
364bool isBluntRebootReason(const std::string& r) {
365 if (isStrongRebootReason(r)) return false;
366
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700367 if (!isKnownRebootReason(r)) return true; // Can not support unknown as detail
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700368
369 size_t pos = 0;
370 while ((pos = r.find(',', pos)) != std::string::npos) {
371 ++pos;
372 std::string next(r.substr(pos));
373 if (next.length() == 0) break;
374 if (next[0] == ',') continue;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700375 if (!isKnownRebootReason(next)) return false; // Unknown subreason is good.
376 if (isStrongRebootReason(next)) return false; // eg: reboot,reboot
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700377 }
378 return true;
379}
380
Mark Salyzyn64610892017-09-18 10:41:14 -0700381bool readPstoreConsole(std::string& console) {
382 if (android::base::ReadFileToString("/sys/fs/pstore/console-ramoops-0", &console)) {
383 return true;
384 }
385 return android::base::ReadFileToString("/sys/fs/pstore/console-ramoops", &console);
386}
387
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700388// Implement a variant of std::string::rfind that is resilient to errors in
389// the data stream being inspected.
390class pstoreConsole {
391 private:
392 const size_t kBitErrorRate = 8; // number of bits per error
393 const std::string& console;
394
395 // Number of bits that differ between the two arguments l and r.
396 // Returns zero if the values for l and r are identical.
397 size_t numError(uint8_t l, uint8_t r) const { return std::bitset<8>(l ^ r).count(); }
398
399 // A string comparison function, reports the number of errors discovered
400 // in the match to a maximum of the bitLength / kBitErrorRate, at that
401 // point returning npos to indicate match is too poor.
402 //
403 // Since called in rfind which works backwards, expect cache locality will
404 // help if we check in reverse here as well for performance.
405 //
406 // Assumption: l (from console.c_str() + pos) is long enough to house
407 // _r.length(), checked in rfind caller below.
408 //
409 size_t numError(size_t pos, const std::string& _r) const {
410 const char* l = console.c_str() + pos;
411 const char* r = _r.c_str();
412 size_t n = _r.length();
413 const uint8_t* le = reinterpret_cast<const uint8_t*>(l) + n;
414 const uint8_t* re = reinterpret_cast<const uint8_t*>(r) + n;
415 size_t count = 0;
416 n = 0;
417 do {
418 // individual character bit error rate > threshold + slop
419 size_t num = numError(*--le, *--re);
420 if (num > ((8 + kBitErrorRate) / kBitErrorRate)) return std::string::npos;
421 // total bit error rate > threshold + slop
422 count += num;
423 ++n;
424 if (count > ((n * 8 + kBitErrorRate - (n > 2)) / kBitErrorRate)) {
425 return std::string::npos;
426 }
427 } while (le != reinterpret_cast<const uint8_t*>(l));
428 return count;
429 }
430
431 public:
432 explicit pstoreConsole(const std::string& console) : console(console) {}
433 // scope of argument must be equal to or greater than scope of pstoreConsole
434 explicit pstoreConsole(const std::string&& console) = delete;
435 explicit pstoreConsole(std::string&& console) = delete;
436
437 // Our implementation of rfind, use exact match first, then resort to fuzzy.
438 size_t rfind(const std::string& needle) const {
439 size_t pos = console.rfind(needle); // exact match?
440 if (pos != std::string::npos) return pos;
441
442 // Check to make sure needle fits in console string.
443 pos = console.length();
444 if (needle.length() > pos) return std::string::npos;
445 pos -= needle.length();
446 // fuzzy match to maximum kBitErrorRate
Ivan Lozano44d3cac2017-11-07 13:13:55 -0800447 for (;;) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700448 if (numError(pos, needle) != std::string::npos) return pos;
Ivan Lozano44d3cac2017-11-07 13:13:55 -0800449 if (pos == 0) break;
450 --pos;
451 }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700452 return std::string::npos;
453 }
454
455 // Our implementation of find, use only fuzzy match.
456 size_t find(const std::string& needle, size_t start = 0) const {
457 // Check to make sure needle fits in console string.
458 if (needle.length() > console.length()) return std::string::npos;
459 const size_t last_pos = console.length() - needle.length();
460 // fuzzy match to maximum kBitErrorRate
461 for (size_t pos = start; pos <= last_pos; ++pos) {
462 if (numError(pos, needle) != std::string::npos) return pos;
463 }
464 return std::string::npos;
465 }
466};
467
468// If bit error match to needle, correct it.
469// Return true if any corrections were discovered and applied.
470bool correctForBer(std::string& reason, const std::string& needle) {
471 bool corrected = false;
472 if (reason.length() < needle.length()) return corrected;
473 const pstoreConsole console(reason);
474 const size_t last_pos = reason.length() - needle.length();
475 for (size_t pos = 0; pos <= last_pos; pos += needle.length()) {
476 pos = console.find(needle, pos);
477 if (pos == std::string::npos) break;
478
479 // exact match has no malice
480 if (needle == reason.substr(pos, needle.length())) continue;
481
482 corrected = true;
483 reason = reason.substr(0, pos) + needle + reason.substr(pos + needle.length());
484 }
485 return corrected;
486}
487
488bool addKernelPanicSubReason(const pstoreConsole& console, std::string& ret) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700489 // Check for kernel panic types to refine information
490 if (console.rfind("SysRq : Trigger a crash") != std::string::npos) {
491 // Can not happen, except on userdebug, during testing/debugging.
492 ret = "kernel_panic,sysrq";
493 return true;
494 }
495 if (console.rfind("Unable to handle kernel NULL pointer dereference at virtual address") !=
496 std::string::npos) {
497 ret = "kernel_panic,NULL";
498 return true;
499 }
500 if (console.rfind("Kernel BUG at ") != std::string::npos) {
501 ret = "kernel_panic,BUG";
502 return true;
503 }
504 return false;
505}
506
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700507bool addKernelPanicSubReason(const std::string& content, std::string& ret) {
508 return addKernelPanicSubReason(pstoreConsole(content), ret);
509}
510
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700511// std::transform Helper callback functions:
512// Converts a string value representing the reason the system booted to a
513// string complying with Android system standard reason.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700514char tounderline(char c) {
515 return ::isblank(c) ? '_' : c;
516}
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700517
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700518char toprintable(char c) {
519 return ::isprint(c) ? c : '?';
520}
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700521
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700522// Cleanup boot_reason regarding acceptable character set
523void transformReason(std::string& reason) {
524 std::transform(reason.begin(), reason.end(), reason.begin(), ::tolower);
525 std::transform(reason.begin(), reason.end(), reason.begin(), tounderline);
526 std::transform(reason.begin(), reason.end(), reason.begin(), toprintable);
527}
528
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700529const char system_reboot_reason_property[] = "sys.boot.reason";
530const char last_reboot_reason_property[] = LAST_REBOOT_REASON_PROPERTY;
531const char bootloader_reboot_reason_property[] = "ro.boot.bootreason";
532
533// Scrub, Sanitize, Standardize and Enhance the boot reason string supplied.
534std::string BootReasonStrToReason(const std::string& boot_reason) {
Mark Salyzyna16e4372017-09-20 08:36:12 -0700535 static const size_t max_reason_length = 256;
536
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700537 std::string ret(GetProperty(system_reboot_reason_property));
538 std::string reason(boot_reason);
539 // If sys.boot.reason == ro.boot.bootreason, let's re-evaluate
540 if (reason == ret) ret = "";
541
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700542 transformReason(reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700543
544 // Is the current system boot reason sys.boot.reason valid?
545 if (!isKnownRebootReason(ret)) ret = "";
546
547 if (ret == "") {
548 // Is the bootloader boot reason ro.boot.bootreason known?
549 std::vector<std::string> words(android::base::Split(reason, ",_-"));
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700550 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700551 std::string blunt;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700552 for (auto& r : words) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700553 if (r == s) {
554 if (isBluntRebootReason(s)) {
555 blunt = s;
556 } else {
557 ret = s;
558 break;
559 }
560 }
561 }
562 if (ret == "") ret = blunt;
563 if (ret != "") break;
564 }
565 }
566
567 if (ret == "") {
568 // A series of checks to take some officially unsupported reasons
569 // reported by the bootloader and find some logical and canonical
570 // sense. In an ideal world, we would require those bootloaders
571 // to behave and follow our standards.
572 static const std::vector<std::pair<const std::string, const std::string>> aliasReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700573 {"watchdog", "wdog"},
574 {"cold,powerkey", "powerkey"},
575 {"kernel_panic", "panic"},
576 {"shutdown,thermal", "thermal"},
577 {"warm,s3_wakeup", "s3_wakeup"},
578 {"hard,hw_reset", "hw_reset"},
Mark Salyzyncabbe4f2017-10-23 13:52:39 -0700579 {"reboot,2sec", "2sec_reboot"},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700580 {"bootloader", ""},
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700581 };
582
583 // Either the primary or alias is found _somewhere_ in the reason string.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700584 for (auto& s : aliasReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700585 if (reason.find(s.first) != std::string::npos) {
586 ret = s.first;
587 break;
588 }
589 if (s.second.size() && (reason.find(s.second) != std::string::npos)) {
590 ret = s.first;
591 break;
592 }
593 }
594 }
595
596 // If watchdog is the reason, see if there is a security angle?
597 if (ret == "watchdog") {
598 if (reason.find("sec") != std::string::npos) {
599 ret += ",security";
600 }
601 }
602
Mark Salyzyn64610892017-09-18 10:41:14 -0700603 if (ret == "kernel_panic") {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700604 // Check to see if last klog has some refinement hints.
605 std::string content;
Mark Salyzyn64610892017-09-18 10:41:14 -0700606 if (readPstoreConsole(content)) {
607 addKernelPanicSubReason(content, ret);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700608 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700609 } else if (isBluntRebootReason(ret)) {
610 // Check the other available reason resources if the reason is still blunt.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700611
Mark Salyzyn64610892017-09-18 10:41:14 -0700612 // Check to see if last klog has some refinement hints.
613 std::string content;
614 if (readPstoreConsole(content)) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700615 const pstoreConsole console(content);
Mark Salyzyn64610892017-09-18 10:41:14 -0700616 // The toybox reboot command used directly (unlikely)? But also
617 // catches init's response to Android's more controlled reboot command.
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700618 if (console.rfind("reboot: Power down") != std::string::npos) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700619 ret = "shutdown"; // Still too blunt, but more accurate.
620 // ToDo: init should record the shutdown reason to kernel messages ala:
621 // init: shutdown system with command 'last_reboot_reason'
622 // so that if pstore has persistence we can get some details
623 // that could be missing in last_reboot_reason_property.
624 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700625
Mark Salyzyn64610892017-09-18 10:41:14 -0700626 static const char cmd[] = "reboot: Restarting system with command '";
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700627 size_t pos = console.rfind(cmd);
Mark Salyzyn64610892017-09-18 10:41:14 -0700628 if (pos != std::string::npos) {
629 pos += strlen(cmd);
Mark Salyzyna16e4372017-09-20 08:36:12 -0700630 std::string subReason(content.substr(pos, max_reason_length));
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700631 // Correct against any known strings that Bit Error Match
632 for (const auto& s : knownReasons) {
633 correctForBer(subReason, s);
634 }
635 for (const auto& m : kBootReasonMap) {
636 if (m.first.length() <= strlen("cold")) continue; // too short?
637 if (correctForBer(subReason, m.first + "'")) continue;
638 if (m.first.length() <= strlen("reboot,cold")) continue; // short?
639 if (!android::base::StartsWith(m.first, "reboot,")) continue;
640 correctForBer(subReason, m.first.substr(strlen("reboot,")) + "'");
641 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700642 for (pos = 0; pos < subReason.length(); ++pos) {
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700643 char c = subReason[pos];
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700644 // #, &, %, / are common single bit error for ' that we can block
645 if (!::isprint(c) || (c == '\'') || (c == '#') || (c == '&') || (c == '%') || (c == '/')) {
Mark Salyzyna16e4372017-09-20 08:36:12 -0700646 subReason.erase(pos);
647 break;
648 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700649 }
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700650 transformReason(subReason);
Mark Salyzyn64610892017-09-18 10:41:14 -0700651 if (subReason != "") { // Will not land "reboot" as that is too blunt.
652 if (isKernelRebootReason(subReason)) {
653 ret = "reboot," + subReason; // User space can't talk kernel reasons.
Mark Salyzyndafced92017-09-20 08:37:46 -0700654 } else if (isKnownRebootReason(subReason)) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700655 ret = subReason;
Mark Salyzyndafced92017-09-20 08:37:46 -0700656 } else {
657 ret = "reboot," + subReason; // legitimize unknown reasons
Mark Salyzyn64610892017-09-18 10:41:14 -0700658 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700659 }
660 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700661
Mark Salyzyn64610892017-09-18 10:41:14 -0700662 // Check for kernel panics, allowed to override reboot command.
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700663 if (!addKernelPanicSubReason(console, ret) &&
Mark Salyzyn64610892017-09-18 10:41:14 -0700664 // check for long-press power down
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700665 ((console.rfind("Power held for ") != std::string::npos) ||
666 (console.rfind("charger: [") != std::string::npos))) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700667 ret = "cold";
668 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700669 }
670
671 // The following battery test should migrate to a default system health HAL
672
673 // Let us not worry if the reboot command was issued, for the cases of
674 // reboot -p, reboot <no reason>, reboot cold, reboot warm and reboot hard.
675 // Same for bootloader and ro.boot.bootreasons of this set, but a dead
676 // battery could conceivably lead to these, so worthy of override.
677 if (isBluntRebootReason(ret)) {
678 // Heuristic to determine if shutdown possibly because of a dead battery?
679 // Really a hail-mary pass to find it in last klog content ...
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700680 static const int battery_dead_threshold = 2; // percent
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700681 static const char battery[] = "healthd: battery l=";
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700682 const pstoreConsole console(content);
683 size_t pos = console.rfind(battery); // last one
Mark Salyzyna16e4372017-09-20 08:36:12 -0700684 std::string digits;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700685 if (pos != std::string::npos) {
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700686 digits = content.substr(pos + strlen(battery), strlen("100 "));
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700687 // correct common errors
688 correctForBer(digits, "100 ");
689 if (digits[0] == '!') digits[0] = '1';
690 if (digits[1] == '!') digits[1] = '1';
Mark Salyzyna16e4372017-09-20 08:36:12 -0700691 }
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700692 const char* endptr = digits.c_str();
693 unsigned level = 0;
694 while (::isdigit(*endptr)) {
695 level *= 10;
696 level += *endptr++ - '0';
697 // make sure no leading zeros, except zero itself, and range check.
698 if ((level == 0) || (level > 100)) break;
699 }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700700 // example bit error rate issues for 10%
701 // 'l=10 ' no bits in error
702 // 'l=00 ' single bit error (fails above)
703 // 'l=1 ' single bit error
704 // 'l=0 ' double bit error
705 // There are others, not typically critical because of 2%
706 // battery_dead_threshold. KISS check, make sure second
707 // character after digit sequence is not a space.
708 if ((level <= 100) && (endptr != digits.c_str()) && (endptr[0] == ' ') && (endptr[1] != ' ')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700709 LOG(INFO) << "Battery level at shutdown " << level << "%";
710 if (level <= battery_dead_threshold) {
711 ret = "shutdown,battery";
712 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700713 } else { // Most likely
714 digits = ""; // reset digits
715
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700716 // Content buffer no longer will have console data. Beware if more
717 // checks added below, that depend on parsing console content.
718 content = "";
719
720 LOG(DEBUG) << "Can not find last low battery in last console messages";
721 android_logcat_context ctx = create_android_logcat();
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700722 FILE* fp = android_logcat_popen(&ctx, "logcat -b kernel -v brief -d");
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700723 if (fp != nullptr) {
724 android::base::ReadFdToString(fileno(fp), &content);
725 }
726 android_logcat_pclose(&ctx, fp);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700727 static const char logcat_battery[] = "W/healthd ( 0): battery l=";
728 const char* match = logcat_battery;
729
730 if (content == "") {
731 // Service logd.klog not running, go to smaller buffer in the kernel.
732 int rc = klogctl(KLOG_SIZE_BUFFER, nullptr, 0);
733 if (rc > 0) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700734 ssize_t len = rc + 1024; // 1K Margin should it grow between calls.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700735 std::unique_ptr<char[]> buf(new char[len]);
736 rc = klogctl(KLOG_READ_ALL, buf.get(), len);
737 if (rc < len) {
738 len = rc + 1;
739 }
740 buf[--len] = '\0';
741 content = buf.get();
742 }
743 match = battery;
744 }
745
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700746 pos = content.find(match); // The first one it finds.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700747 if (pos != std::string::npos) {
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700748 digits = content.substr(pos + strlen(match), strlen("100 "));
Mark Salyzyna16e4372017-09-20 08:36:12 -0700749 }
Mark Salyzyn747c0e62017-09-20 08:37:46 -0700750 endptr = digits.c_str();
751 level = 0;
752 while (::isdigit(*endptr)) {
753 level *= 10;
754 level += *endptr++ - '0';
755 // make sure no leading zeros, except zero itself, and range check.
756 if ((level == 0) || (level > 100)) break;
757 }
Mark Salyzyna16e4372017-09-20 08:36:12 -0700758 if ((level <= 100) && (endptr != digits.c_str()) && (*endptr == ' ')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700759 LOG(INFO) << "Battery level at startup " << level << "%";
760 if (level <= battery_dead_threshold) {
761 ret = "shutdown,battery";
762 }
763 } else {
764 LOG(DEBUG) << "Can not find first battery level in dmesg or logcat";
765 }
766 }
767 }
768
769 // Is there a controlled shutdown hint in last_reboot_reason_property?
770 if (isBluntRebootReason(ret)) {
771 // Content buffer no longer will have console data. Beware if more
772 // checks added below, that depend on parsing console content.
773 content = GetProperty(last_reboot_reason_property);
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700774 transformReason(content);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700775
Mark Salyzyn62909822017-10-09 09:27:16 -0700776 // Anything in last is better than 'super-blunt' reboot or shutdown.
777 if ((ret == "") || (ret == "reboot") || (ret == "shutdown") || !isBluntRebootReason(content)) {
778 ret = content;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700779 }
780 }
781
782 // Other System Health HAL reasons?
783
784 // ToDo: /proc/sys/kernel/boot_reason needs a HAL interface to
785 // possibly offer hardware-specific clues from the PMIC.
786 }
787
788 // If unknown left over from above, make it "reboot,<boot_reason>"
789 if (ret == "") {
790 ret = "reboot";
791 if (android::base::StartsWith(reason, "reboot")) {
792 reason = reason.substr(strlen("reboot"));
Mark Salyzyn0af71a52017-10-05 13:58:04 -0700793 while ((reason[0] == ',') || (reason[0] == '_')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700794 reason = reason.substr(1);
795 }
796 }
797 if (reason != "") {
798 ret += ",";
799 ret += reason;
800 }
801 }
802
803 LOG(INFO) << "Canonical boot reason: " << ret;
804 if (isKernelRebootReason(ret) && (GetProperty(last_reboot_reason_property) != "")) {
805 // Rewrite as it must be old news, kernel reasons trump user space.
806 SetProperty(last_reboot_reason_property, ret);
807 }
808 return ret;
809}
810
James Hawkinsb9cf7712016-04-08 15:32:19 -0700811// Returns the appropriate metric key prefix for the boot_complete metric such
812// that boot metrics after a system update are labeled as ota_boot_complete;
813// otherwise, they are labeled as boot_complete. This method encapsulates the
814// bookkeeping required to track when a system update has occurred by storing
815// the UTC timestamp of the system build date and comparing against the current
816// system build date.
817std::string CalculateBootCompletePrefix() {
818 static const std::string kBuildDateKey = "build_date";
819 std::string boot_complete_prefix = "boot_complete";
820
821 std::string build_date_str = GetProperty("ro.build.date.utc");
James Hawkins4dded612016-07-28 11:50:23 -0700822 int32_t build_date;
Elliott Hughesda46b392016-10-11 17:09:00 -0700823 if (!android::base::ParseInt(build_date_str, &build_date)) {
James Hawkins4dded612016-07-28 11:50:23 -0700824 return std::string();
825 }
James Hawkinsb9cf7712016-04-08 15:32:19 -0700826
827 BootEventRecordStore boot_event_store;
828 BootEventRecordStore::BootEventRecord record;
James Hawkins0bc4ad42017-05-30 15:03:15 -0700829 if (!boot_event_store.GetBootEvent(kBuildDateKey, &record)) {
830 boot_complete_prefix = "factory_reset_" + boot_complete_prefix;
831 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700832 LOG(INFO) << "Canonical boot reason: reboot,factory_reset";
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700833 SetProperty(system_reboot_reason_property, "reboot,factory_reset");
James Hawkins0bc4ad42017-05-30 15:03:15 -0700834 } else if (build_date != record.second) {
James Hawkinsb9cf7712016-04-08 15:32:19 -0700835 boot_complete_prefix = "ota_" + boot_complete_prefix;
836 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700837 LOG(INFO) << "Canonical boot reason: reboot,ota";
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700838 SetProperty(system_reboot_reason_property, "reboot,ota");
James Hawkinsb9cf7712016-04-08 15:32:19 -0700839 }
840
841 return boot_complete_prefix;
842}
843
James Hawkinsef0a0902017-01-06 14:38:23 -0800844// Records the value of a given ro.boottime.init property in milliseconds.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700845void RecordInitBootTimeProp(BootEventRecordStore* boot_event_store, const char* property) {
James Hawkinsef0a0902017-01-06 14:38:23 -0800846 std::string value = GetProperty(property);
847
James Hawkins27c05222017-01-26 11:55:44 -0800848 int32_t time_in_ms;
849 if (android::base::ParseInt(value, &time_in_ms)) {
James Hawkinsef0a0902017-01-06 14:38:23 -0800850 boot_event_store->AddBootEventWithValue(property, time_in_ms);
851 }
852}
853
James Hawkins1bfcaec2017-05-19 14:27:27 -0700854// A map from bootloader timing stage to the time that stage took during boot.
855typedef std::map<std::string, int32_t> BootloaderTimingMap;
856
857// Returns a mapping from bootloader stage names to the time those stages
858// took to boot.
859const BootloaderTimingMap GetBootLoaderTimings() {
860 BootloaderTimingMap timings;
861
862 // |ro.boot.boottime| is of the form 'stage1:time1,...,stageN:timeN',
863 // where timeN is in milliseconds.
James Hawkinsbe46fd12017-02-02 16:21:25 -0800864 std::string value = GetProperty("ro.boot.boottime");
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800865 if (value.empty()) {
866 // ro.boot.boottime is not reported on all devices.
James Hawkins1bfcaec2017-05-19 14:27:27 -0700867 return BootloaderTimingMap();
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800868 }
James Hawkinsbe46fd12017-02-02 16:21:25 -0800869
870 auto stages = android::base::Split(value, ",");
James Hawkins1bfcaec2017-05-19 14:27:27 -0700871 for (const auto& stageTiming : stages) {
James Hawkinsbe46fd12017-02-02 16:21:25 -0800872 // |stageTiming| is of the form 'stage:time'.
873 auto stageTimingValues = android::base::Split(stageTiming, ":");
James Hawkins0bc4ad42017-05-30 15:03:15 -0700874 DCHECK_EQ(2U, stageTimingValues.size());
James Hawkinsbe46fd12017-02-02 16:21:25 -0800875
876 std::string stageName = stageTimingValues[0];
877 int32_t time_ms;
878 if (android::base::ParseInt(stageTimingValues[1], &time_ms)) {
James Hawkins1bfcaec2017-05-19 14:27:27 -0700879 timings[stageName] = time_ms;
James Hawkinsbe46fd12017-02-02 16:21:25 -0800880 }
881 }
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800882
James Hawkins1bfcaec2017-05-19 14:27:27 -0700883 return timings;
884}
885
Tej Singh4eacd382018-01-25 17:59:57 -0800886// Returns the total bootloader boot time from the ro.boot.boottime system property.
887int32_t GetBootloaderTime(const BootloaderTimingMap& bootloader_timings) {
888 int32_t total_time = 0;
889 for (const auto& timing : bootloader_timings) {
890 total_time += timing.second;
891 }
892
893 return total_time;
894}
895
James Hawkins1bfcaec2017-05-19 14:27:27 -0700896// Parses and records the set of bootloader stages and associated boot times
897// from the ro.boot.boottime system property.
898void RecordBootloaderTimings(BootEventRecordStore* boot_event_store,
899 const BootloaderTimingMap& bootloader_timings) {
900 int32_t total_time = 0;
901 for (const auto& timing : bootloader_timings) {
902 total_time += timing.second;
903 boot_event_store->AddBootEventWithValue("boottime.bootloader." + timing.first, timing.second);
904 }
905
James Hawkins6b5c5aa2017-02-16 11:53:03 -0800906 boot_event_store->AddBootEventWithValue("boottime.bootloader.total", total_time);
James Hawkinsbe46fd12017-02-02 16:21:25 -0800907}
908
Tej Singh4eacd382018-01-25 17:59:57 -0800909// Returns the closest estimation to the absolute device boot time, i.e.,
James Hawkins1bfcaec2017-05-19 14:27:27 -0700910// from power on to boot_complete, including bootloader times.
Tej Singh4eacd382018-01-25 17:59:57 -0800911std::chrono::milliseconds GetAbsoluteBootTime(const BootloaderTimingMap& bootloader_timings,
912 std::chrono::milliseconds uptime) {
James Hawkins1bfcaec2017-05-19 14:27:27 -0700913 int32_t bootloader_time_ms = 0;
914
915 for (const auto& timing : bootloader_timings) {
916 if (timing.first.compare("SW") != 0) {
917 bootloader_time_ms += timing.second;
918 }
919 }
920
921 auto bootloader_duration = std::chrono::milliseconds(bootloader_time_ms);
Tej Singh4eacd382018-01-25 17:59:57 -0800922 return bootloader_duration + uptime;
923}
924
925// Records the closest estimation to the absolute device boot time in seconds.
926// i.e. from power on to boot_complete, including bootloader times.
927void RecordAbsoluteBootTime(BootEventRecordStore* boot_event_store,
928 std::chrono::milliseconds absolute_total) {
929 auto absolute_total_sec = std::chrono::duration_cast<std::chrono::seconds>(absolute_total);
930 boot_event_store->AddBootEventWithValue("absolute_boot_time", absolute_total_sec.count());
931}
932
933// Logs the total boot time and reason to statsd.
934void LogBootInfoToStatsd(std::chrono::milliseconds end_time,
935 std::chrono::milliseconds total_duration, int32_t bootloader_duration_ms,
936 double time_since_last_boot_sec) {
937 const std::string reason(GetProperty(bootloader_reboot_reason_property));
938
939 if (reason.empty()) {
940 android::util::stats_write(android::util::BOOT_SEQUENCE_REPORTED, "<EMPTY>", "<EMPTY>",
941 end_time.count(), total_duration.count(),
942 (int64_t)bootloader_duration_ms,
943 (int64_t)time_since_last_boot_sec * 1000);
944 return;
945 }
946
Tej Singhfe3e7622018-02-06 15:57:38 -0800947 const std::string system_reason(GetProperty(system_reboot_reason_property));
Tej Singh4eacd382018-01-25 17:59:57 -0800948 android::util::stats_write(android::util::BOOT_SEQUENCE_REPORTED, reason.c_str(),
949 system_reason.c_str(), end_time.count(), total_duration.count(),
950 (int64_t)bootloader_duration_ms,
951 (int64_t)time_since_last_boot_sec * 1000);
James Hawkins1bfcaec2017-05-19 14:27:27 -0700952}
953
Tej Singhfe3e7622018-02-06 15:57:38 -0800954void SetSystemBootReason() {
955 const std::string bootloader_boot_reason(GetProperty(bootloader_reboot_reason_property));
956 const std::string system_boot_reason(BootReasonStrToReason(bootloader_boot_reason));
957 // Record the scrubbed system_boot_reason to the property
958 SetProperty(system_reboot_reason_property, system_boot_reason);
959}
960
Luis Hector Chavez583d34c2018-04-12 15:25:15 -0700961// Gets the boot time offset. This is useful when Android is running in a
962// container, because the boot_clock is not reset when Android reboots.
963std::chrono::nanoseconds GetBootTimeOffset() {
964 static const int64_t boottime_offset =
965 android::base::GetIntProperty<int64_t>("ro.boot.boottime_offset", 0);
966 return std::chrono::nanoseconds(boottime_offset);
967}
968
969// Returns the current uptime, accounting for any offset in the CLOCK_BOOTTIME
970// clock.
971android::base::boot_clock::duration GetUptime() {
972 return android::base::boot_clock::now().time_since_epoch() - GetBootTimeOffset();
973}
974
James Hawkinsc08e9962016-03-11 14:59:50 -0800975// Records several metrics related to the time it takes to boot the device,
976// including disambiguating boot time on encrypted or non-encrypted devices.
977void RecordBootComplete() {
978 BootEventRecordStore boot_event_store;
James Hawkinsb9cf7712016-04-08 15:32:19 -0700979 BootEventRecordStore::BootEventRecord record;
James Hawkins2d8b3e62016-04-14 14:13:20 -0700980
Luis Hector Chavez583d34c2018-04-12 15:25:15 -0700981 auto uptime_ns = GetUptime();
982 auto uptime_s = std::chrono::duration_cast<std::chrono::seconds>(uptime_ns);
James Hawkins2d8b3e62016-04-14 14:13:20 -0700983 time_t current_time_utc = time(nullptr);
Tej Singh4eacd382018-01-25 17:59:57 -0800984 time_t time_since_last_boot = 0;
James Hawkins2d8b3e62016-04-14 14:13:20 -0700985
986 if (boot_event_store.GetBootEvent("last_boot_time_utc", &record)) {
987 time_t last_boot_time_utc = record.second;
Tej Singh4eacd382018-01-25 17:59:57 -0800988 time_since_last_boot = difftime(current_time_utc, last_boot_time_utc);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700989 boot_event_store.AddBootEventWithValue("time_since_last_boot", time_since_last_boot);
James Hawkins2d8b3e62016-04-14 14:13:20 -0700990 }
991
992 boot_event_store.AddBootEventWithValue("last_boot_time_utc", current_time_utc);
James Hawkinsc08e9962016-03-11 14:59:50 -0800993
James Hawkinsb9cf7712016-04-08 15:32:19 -0700994 // The boot_complete metric has two variants: boot_complete and
995 // ota_boot_complete. The latter signifies that the device is booting after
996 // a system update.
997 std::string boot_complete_prefix = CalculateBootCompletePrefix();
James Hawkins4dded612016-07-28 11:50:23 -0700998 if (boot_complete_prefix.empty()) {
999 // The system is hosed because the build date property could not be read.
1000 return;
1001 }
James Hawkinsc08e9962016-03-11 14:59:50 -08001002
1003 // post_decrypt_time_elapsed is only logged on encrypted devices.
1004 if (boot_event_store.GetBootEvent("post_decrypt_time_elapsed", &record)) {
1005 // Log the amount of time elapsed until the device is decrypted, which
1006 // includes the variable amount of time the user takes to enter the
1007 // decryption password.
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001008 boot_event_store.AddBootEventWithValue("boot_decryption_complete", uptime_s.count());
James Hawkinsc08e9962016-03-11 14:59:50 -08001009
1010 // Subtract the decryption time to normalize the boot cycle timing.
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001011 std::chrono::seconds boot_complete = std::chrono::seconds(uptime_s.count() - record.second);
James Hawkinsb9cf7712016-04-08 15:32:19 -07001012 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_post_decrypt",
James Hawkinse78ea772017-03-24 11:43:02 -07001013 boot_complete.count());
James Hawkinsc08e9962016-03-11 14:59:50 -08001014 } else {
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001015 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_no_encryption",
1016 uptime_s.count());
James Hawkinsc08e9962016-03-11 14:59:50 -08001017 }
1018
1019 // Record the total time from device startup to boot complete, regardless of
1020 // encryption state.
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001021 boot_event_store.AddBootEventWithValue(boot_complete_prefix, uptime_s.count());
James Hawkinsef0a0902017-01-06 14:38:23 -08001022
1023 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init");
1024 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.selinux");
1025 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.cold_boot_wait");
James Hawkinsbe46fd12017-02-02 16:21:25 -08001026
James Hawkins1bfcaec2017-05-19 14:27:27 -07001027 const BootloaderTimingMap bootloader_timings = GetBootLoaderTimings();
Tej Singh4eacd382018-01-25 17:59:57 -08001028 int32_t bootloader_boot_duration = GetBootloaderTime(bootloader_timings);
James Hawkins1bfcaec2017-05-19 14:27:27 -07001029 RecordBootloaderTimings(&boot_event_store, bootloader_timings);
1030
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001031 auto uptime_ms = std::chrono::duration_cast<std::chrono::milliseconds>(uptime_ns);
Tej Singh4eacd382018-01-25 17:59:57 -08001032 auto absolute_boot_time = GetAbsoluteBootTime(bootloader_timings, uptime_ms);
1033 RecordAbsoluteBootTime(&boot_event_store, absolute_boot_time);
1034
1035 auto boot_end_time_point = std::chrono::system_clock::now().time_since_epoch();
1036 auto boot_end_time = std::chrono::duration_cast<std::chrono::milliseconds>(boot_end_time_point);
1037
1038 LogBootInfoToStatsd(boot_end_time, absolute_boot_time, bootloader_boot_duration,
1039 time_since_last_boot);
James Hawkinsc08e9962016-03-11 14:59:50 -08001040}
1041
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001042// Records the boot_reason metric by querying the ro.boot.bootreason system
1043// property.
1044void RecordBootReason() {
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001045 const std::string reason(GetProperty(bootloader_reboot_reason_property));
James Hawkins25f71222017-10-10 16:37:05 -07001046
1047 if (reason.empty()) {
1048 // Log an empty boot reason value as '<EMPTY>' to ensure the value is intentional
1049 // (and not corruption anywhere else in the reporting pipeline).
1050 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
1051 android::metricslogger::FIELD_PLATFORM_REASON, "<EMPTY>");
1052 } else {
1053 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
1054 android::metricslogger::FIELD_PLATFORM_REASON, reason);
1055 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001056
1057 // Log the raw bootloader_boot_reason property value.
1058 int32_t boot_reason = BootReasonStrToEnum(reason);
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001059 BootEventRecordStore boot_event_store;
1060 boot_event_store.AddBootEventWithValue("boot_reason", boot_reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001061
1062 // Log the scrubbed system_boot_reason.
Tej Singhfe3e7622018-02-06 15:57:38 -08001063 const std::string system_reason(GetProperty(system_reboot_reason_property));
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001064 int32_t system_boot_reason = BootReasonStrToEnum(system_reason);
1065 boot_event_store.AddBootEventWithValue("system_boot_reason", system_boot_reason);
1066
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001067 if (reason == "") {
1068 SetProperty(bootloader_reboot_reason_property, system_reason);
1069 }
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001070}
1071
James Hawkins500d7152016-02-16 15:05:54 -08001072// Records two metrics related to the user resetting a device: the time at
1073// which the device is reset, and the time since the user last reset the
1074// device. The former is only set once per-factory reset.
1075void RecordFactoryReset() {
1076 BootEventRecordStore boot_event_store;
1077 BootEventRecordStore::BootEventRecord record;
1078
1079 time_t current_time_utc = time(nullptr);
1080
James Hawkins0660b302016-03-08 16:18:15 -08001081 if (current_time_utc < 0) {
1082 // UMA does not display negative values in buckets, so convert to positive.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001083 android::metricslogger::LogHistogram("factory_reset_current_time_failure",
1084 std::abs(current_time_utc));
James Hawkinsfff95ba2016-03-29 16:13:49 -07001085
James Hawkins9aec9262017-01-31 11:42:24 -08001086 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001087 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001088 boot_event_store.AddBootEventWithValue("factory_reset_current_time_failure",
1089 std::abs(current_time_utc));
James Hawkins0660b302016-03-08 16:18:15 -08001090 return;
1091 } else {
James Hawkins9aec9262017-01-31 11:42:24 -08001092 android::metricslogger::LogHistogram("factory_reset_current_time", current_time_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001093
James Hawkins9aec9262017-01-31 11:42:24 -08001094 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001095 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001096 boot_event_store.AddBootEventWithValue("factory_reset_current_time", current_time_utc);
James Hawkins0660b302016-03-08 16:18:15 -08001097 }
1098
James Hawkins500d7152016-02-16 15:05:54 -08001099 // The factory_reset boot event does not exist after the device is reset, so
1100 // use this signal to mark the time of the factory reset.
1101 if (!boot_event_store.GetBootEvent("factory_reset", &record)) {
1102 boot_event_store.AddBootEventWithValue("factory_reset", current_time_utc);
James Hawkins3bf9b142016-03-03 14:50:24 -08001103
1104 // Don't log the time_since_factory_reset until some time has elapsed.
1105 // The data is not meaningful yet and skews the histogram buckets.
James Hawkins500d7152016-02-16 15:05:54 -08001106 return;
1107 }
1108
1109 // Calculate and record the difference in time between now and the
1110 // factory_reset time.
1111 time_t factory_reset_utc = record.second;
James Hawkins9aec9262017-01-31 11:42:24 -08001112 android::metricslogger::LogHistogram("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001113
James Hawkins9aec9262017-01-31 11:42:24 -08001114 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001115 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001116 boot_event_store.AddBootEventWithValue("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001117
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001118 time_t time_since_factory_reset = difftime(current_time_utc, factory_reset_utc);
1119 boot_event_store.AddBootEventWithValue("time_since_factory_reset", time_since_factory_reset);
James Hawkins500d7152016-02-16 15:05:54 -08001120}
1121
James Hawkinsabd73e62016-01-19 15:10:38 -08001122} // namespace
1123
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001124int main(int argc, char** argv) {
James Hawkinsabd73e62016-01-19 15:10:38 -08001125 android::base::InitLogging(argv);
1126
1127 const std::string cmd_line = GetCommandLine(argc, argv);
1128 LOG(INFO) << "Service started: " << cmd_line;
1129
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001130 int option_index = 0;
James Hawkinsc6275582016-03-22 10:47:44 -07001131 static const char value_str[] = "value";
Tej Singhfe3e7622018-02-06 15:57:38 -08001132 static const char system_boot_reason_str[] = "set_system_boot_reason";
James Hawkinsc08e9962016-03-11 14:59:50 -08001133 static const char boot_complete_str[] = "record_boot_complete";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001134 static const char boot_reason_str[] = "record_boot_reason";
James Hawkins53684ea2016-02-23 16:18:19 -08001135 static const char factory_reset_str[] = "record_time_since_factory_reset";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001136 static const struct option long_options[] = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001137 // clang-format off
Tej Singhfe3e7622018-02-06 15:57:38 -08001138 { "help", no_argument, NULL, 'h' },
1139 { "log", no_argument, NULL, 'l' },
1140 { "print", no_argument, NULL, 'p' },
1141 { "record", required_argument, NULL, 'r' },
1142 { value_str, required_argument, NULL, 0 },
1143 { system_boot_reason_str, no_argument, NULL, 0 },
1144 { boot_complete_str, no_argument, NULL, 0 },
1145 { boot_reason_str, no_argument, NULL, 0 },
1146 { factory_reset_str, no_argument, NULL, 0 },
1147 { NULL, 0, NULL, 0 }
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001148 // clang-format on
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001149 };
1150
James Hawkinsc6275582016-03-22 10:47:44 -07001151 std::string boot_event;
1152 std::string value;
James Hawkinsabd73e62016-01-19 15:10:38 -08001153 int opt = 0;
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001154 while ((opt = getopt_long(argc, argv, "hlpr:", long_options, &option_index)) != -1) {
James Hawkinsabd73e62016-01-19 15:10:38 -08001155 switch (opt) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001156 // This case handles long options which have no single-character mapping.
1157 case 0: {
1158 const std::string option_name = long_options[option_index].name;
James Hawkinsc6275582016-03-22 10:47:44 -07001159 if (option_name == value_str) {
1160 // |optarg| is an external variable set by getopt representing
1161 // the option argument.
1162 value = optarg;
Tej Singhfe3e7622018-02-06 15:57:38 -08001163 } else if (option_name == system_boot_reason_str) {
1164 SetSystemBootReason();
James Hawkinsc6275582016-03-22 10:47:44 -07001165 } else if (option_name == boot_complete_str) {
James Hawkinsc08e9962016-03-11 14:59:50 -08001166 RecordBootComplete();
1167 } else if (option_name == boot_reason_str) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001168 RecordBootReason();
James Hawkins500d7152016-02-16 15:05:54 -08001169 } else if (option_name == factory_reset_str) {
1170 RecordFactoryReset();
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001171 } else {
1172 LOG(ERROR) << "Invalid option: " << option_name;
1173 }
1174 break;
1175 }
1176
James Hawkinsabd73e62016-01-19 15:10:38 -08001177 case 'h': {
1178 ShowHelp(argv[0]);
1179 break;
1180 }
1181
1182 case 'l': {
1183 LogBootEvents();
1184 break;
1185 }
1186
1187 case 'p': {
1188 PrintBootEvents();
1189 break;
1190 }
1191
1192 case 'r': {
1193 // |optarg| is an external variable set by getopt representing
1194 // the option argument.
James Hawkinsc6275582016-03-22 10:47:44 -07001195 boot_event = optarg;
James Hawkinsabd73e62016-01-19 15:10:38 -08001196 break;
1197 }
1198
1199 default: {
1200 DCHECK_EQ(opt, '?');
1201
1202 // |optopt| is an external variable set by getopt representing
1203 // the value of the invalid option.
1204 LOG(ERROR) << "Invalid option: " << optopt;
1205 ShowHelp(argv[0]);
1206 return EXIT_FAILURE;
1207 }
1208 }
1209 }
1210
James Hawkinsc6275582016-03-22 10:47:44 -07001211 if (!boot_event.empty()) {
1212 RecordBootEventFromCommandLine(boot_event, value);
1213 }
1214
James Hawkinsabd73e62016-01-19 15:10:38 -08001215 return 0;
1216}