blob: 6409db0d5dfccfe9d917887868f61a8d992665f2 [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>
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -070030#include <iterator>
James Hawkinsa4a1a4a2016-02-09 15:32:38 -080031#include <map>
James Hawkinsabd73e62016-01-19 15:10:38 -080032#include <memory>
Mark Salyzyn25900dd2018-03-16 09:05:59 -070033#include <regex>
James Hawkinsabd73e62016-01-19 15:10:38 -080034#include <string>
Mark Salyzyn853bb802018-03-16 08:44:56 -070035#include <utility>
James Hawkinsbe46fd12017-02-02 16:21:25 -080036#include <vector>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070037
James Hawkinse78ea772017-03-24 11:43:02 -070038#include <android-base/chrono_utils.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070039#include <android-base/file.h>
James Hawkinseabe08b2016-01-19 16:54:35 -080040#include <android-base/logging.h>
James Hawkins4dded612016-07-28 11:50:23 -070041#include <android-base/parseint.h>
Luis Hector Chavez583d34c2018-04-12 15:25:15 -070042#include <android-base/properties.h>
James Hawkinsbe46fd12017-02-02 16:21:25 -080043#include <android-base/strings.h>
James Hawkinse78ea772017-03-24 11:43:02 -070044#include <android/log.h>
Mark Salyzynb304f6d2017-08-04 13:35:51 -070045#include <cutils/android_reboot.h>
James Hawkinsa4a1a4a2016-02-09 15:32:38 -080046#include <cutils/properties.h>
James Hawkins9aec9262017-01-31 11:42:24 -080047#include <metricslogger/metrics_logger.h>
Tej Singh4eacd382018-01-25 17:59:57 -080048#include <statslog.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070049
James Hawkinsabd73e62016-01-19 15:10:38 -080050#include "boot_event_record_store.h"
James Hawkinsabd73e62016-01-19 15:10:38 -080051
52namespace {
53
James Hawkinsabd73e62016-01-19 15:10:38 -080054// Scans the boot event record store for record files and logs each boot event
55// via EventLog.
56void LogBootEvents() {
57 BootEventRecordStore boot_event_store;
58
59 auto events = boot_event_store.GetAllBootEvents();
60 for (auto i = events.cbegin(); i != events.cend(); ++i) {
James Hawkins9aec9262017-01-31 11:42:24 -080061 android::metricslogger::LogHistogram(i->first, i->second);
James Hawkinsabd73e62016-01-19 15:10:38 -080062 }
63}
64
James Hawkinsc6275582016-03-22 10:47:44 -070065// Records the named boot |event| to the record store. If |value| is non-empty
66// and is a proper string representation of an integer value, the converted
67// integer value is associated with the boot event.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -070068void RecordBootEventFromCommandLine(const std::string& event, const std::string& value_str) {
James Hawkinsc6275582016-03-22 10:47:44 -070069 BootEventRecordStore boot_event_store;
70 if (!value_str.empty()) {
71 int32_t value = 0;
Elliott Hughesda46b392016-10-11 17:09:00 -070072 if (android::base::ParseInt(value_str, &value)) {
James Hawkins4dded612016-07-28 11:50:23 -070073 boot_event_store.AddBootEventWithValue(event, value);
74 }
James Hawkinsc6275582016-03-22 10:47:44 -070075 } else {
76 boot_event_store.AddBootEvent(event);
77 }
78}
79
James Hawkinsabd73e62016-01-19 15:10:38 -080080void PrintBootEvents() {
81 printf("Boot events:\n");
82 printf("------------\n");
83
84 BootEventRecordStore boot_event_store;
85 auto events = boot_event_store.GetAllBootEvents();
86 for (auto i = events.cbegin(); i != events.cend(); ++i) {
87 printf("%s\t%d\n", i->first.c_str(), i->second);
88 }
89}
90
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -070091void ShowHelp(const char* cmd) {
Mark Salyzyn67ee8a82019-04-18 12:41:29 -070092 fprintf(stderr, "Usage: %s [options]...\n", cmd);
James Hawkinsabd73e62016-01-19 15:10:38 -080093 fprintf(stderr,
94 "options include:\n"
Yongqin Liu78b2b942017-07-07 13:26:49 +080095 " -h, --help Show this help\n"
96 " -l, --log Log all metrics to logstorage\n"
97 " -p, --print Dump the boot event records to the console\n"
98 " -r, --record Record the timestamp of a named boot event\n"
99 " --value Optional value to associate with the boot event\n"
100 " --record_boot_complete Record metrics related to the time for the device boot\n"
101 " --record_boot_reason Record the reason why the device booted\n"
Mark Salyzyn67ee8a82019-04-18 12:41:29 -0700102 " --record_time_since_factory_reset Record the time since the device was reset\n"
103 " --boot_reason_enum=<reason> Report the match to the kBootReasonMap table\n");
James Hawkinsabd73e62016-01-19 15:10:38 -0800104}
105
106// Constructs a readable, printable string from the givencommand line
107// arguments.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700108std::string GetCommandLine(int argc, char** argv) {
James Hawkinsabd73e62016-01-19 15:10:38 -0800109 std::string cmd;
110 for (int i = 0; i < argc; ++i) {
111 cmd += argv[i];
112 cmd += " ";
113 }
114
115 return cmd;
116}
117
James Hawkins25f71222017-10-10 16:37:05 -0700118constexpr int32_t kEmptyBootReason = 0;
James Hawkins6f74c0b2016-02-12 15:49:16 -0800119constexpr int32_t kUnknownBootReason = 1;
120
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800121// A mapping from boot reason string, as read from the ro.boot.bootreason
122// system property, to a unique integer ID. Viewers of log data dashboards for
123// the boot_reason metric may refer to this mapping to discern the histogram
Mark Salyzyn67ee8a82019-04-18 12:41:29 -0700124// values. Regex matching, to manage the scale, as a minimum require either
125// [, \ or * to be present in the string to switch to checking.
James Hawkins6f74c0b2016-02-12 15:49:16 -0800126const std::map<std::string, int32_t> kBootReasonMap = {
Mark Salyzyn67ee8a82019-04-18 12:41:29 -0700127 {"reboot,[empty]", kEmptyBootReason},
Mark Salyzyn2b820532018-03-16 08:53:34 -0700128 {"__BOOTSTAT_UNKNOWN__", kUnknownBootReason},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700129 {"normal", 2},
130 {"recovery", 3},
131 {"reboot", 4},
132 {"PowerKey", 5},
133 {"hard_reset", 6},
134 {"kernel_panic", 7},
135 {"rpm_err", 8},
136 {"hw_reset", 9},
137 {"tz_err", 10},
138 {"adsp_err", 11},
139 {"modem_err", 12},
140 {"mba_err", 13},
141 {"Watchdog", 14},
142 {"Panic", 15},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700143 {"power_key", 16}, // aliasReasons to cold,powerkey (Mediatek)
144 {"power_on", 17}, // aliasReasons to cold,powerkey
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700145 {"Reboot", 18},
146 {"rtc", 19},
147 {"edl", 20},
148 {"oem_pon1", 21},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700149 {"oem_powerkey", 22}, // aliasReasons to cold,powerkey
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700150 {"oem_unknown_reset", 23},
151 {"srto: HWWDT reset SC", 24},
152 {"srto: HWWDT reset platform", 25},
153 {"srto: bootloader", 26},
154 {"srto: kernel panic", 27},
155 {"srto: kernel watchdog reset", 28},
156 {"srto: normal", 29},
157 {"srto: reboot", 30},
158 {"srto: reboot-bootloader", 31},
159 {"srto: security watchdog reset", 32},
160 {"srto: wakesrc", 33},
161 {"srto: watchdog", 34},
162 {"srto:1-1", 35},
163 {"srto:omap_hsmm", 36},
164 {"srto:phy0", 37},
165 {"srto:rtc0", 38},
166 {"srto:touchpad", 39},
167 {"watchdog", 40},
168 {"watchdogr", 41},
169 {"wdog_bark", 42},
170 {"wdog_bite", 43},
171 {"wdog_reset", 44},
Mark Salyzyn274b5442018-08-07 08:45:13 -0700172 {"shutdown,", 45}, // Trailing comma is intentional. Do NOT use.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700173 {"shutdown,userrequested", 46},
174 {"reboot,bootloader", 47},
175 {"reboot,cold", 48},
176 {"reboot,recovery", 49},
177 {"thermal_shutdown", 50},
178 {"s3_wakeup", 51},
179 {"kernel_panic,sysrq", 52},
180 {"kernel_panic,NULL", 53},
Mark Salyzyn853bb802018-03-16 08:44:56 -0700181 {"kernel_panic,null", 53},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700182 {"kernel_panic,BUG", 54},
Mark Salyzyn853bb802018-03-16 08:44:56 -0700183 {"kernel_panic,bug", 54},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700184 {"bootloader", 55},
185 {"cold", 56},
186 {"hard", 57},
187 {"warm", 58},
Mark Salyzyn15199252018-03-16 09:26:05 -0700188 {"reboot,kernel_power_off_charging__reboot_system", 59}, // Can not happen
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700189 {"thermal-shutdown", 60},
190 {"shutdown,thermal", 61},
191 {"shutdown,battery", 62},
192 {"reboot,ota", 63},
193 {"reboot,factory_reset", 64},
194 {"reboot,", 65},
195 {"reboot,shell", 66},
196 {"reboot,adb", 67},
Mark Salyzyn9033bf52017-09-21 11:30:29 -0700197 {"reboot,userrequested", 68},
Mark Salyzyn161b8622017-09-26 08:26:12 -0700198 {"shutdown,container", 69}, // Host OS asking Android Container to shutdown
Mark Salyzyn243fa292017-10-11 09:02:04 -0700199 {"cold,powerkey", 70},
200 {"warm,s3_wakeup", 71},
201 {"hard,hw_reset", 72},
202 {"shutdown,suspend", 73}, // Suspend to RAM
203 {"shutdown,hibernate", 74}, // Suspend to DISK
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700204 {"power_on_key", 75}, // aliasReasons to cold,powerkey
205 {"reboot_by_key", 76}, // translated to reboot,by_key
206 {"wdt_by_pass_pwk", 77}, // Mediatek
207 {"reboot_longkey", 78}, // translated to reboot,longkey
208 {"powerkey", 79}, // aliasReasons to cold,powerkey
209 {"usb", 80}, // aliasReasons to cold,charger (Mediatek)
210 {"wdt", 81}, // Mediatek
211 {"tool_by_pass_pwk", 82}, // aliasReasons to reboot,tool (Mediatek)
212 {"2sec_reboot", 83}, // aliasReasons to cold,rtc,2sec (Mediatek)
James Hawkins34073b52017-10-17 15:53:27 -0700213 {"reboot,by_key", 84},
214 {"reboot,longkey", 85},
Mark Salyzyn186f6762018-03-16 11:00:26 -0700215 {"reboot,2sec", 86}, // Deprecate in two years, replaced with cold,rtc,2sec
Mark Salyzync89f9da2017-10-24 15:35:34 -0700216 {"shutdown,thermal,battery", 87},
Mark Salyzyn72a8ea32017-10-25 09:23:19 -0700217 {"reboot,its_just_so_hard", 88}, // produced by boot_reason_test
218 {"reboot,Its Just So Hard", 89}, // produced by boot_reason_test
Mark Salyzyn75046892018-05-03 13:11:15 -0700219 {"reboot,rescueparty", 90},
James Hawkins74b17582017-11-20 14:13:41 -0800220 {"charge", 91},
221 {"oem_tz_crash", 92},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700222 {"uvlo", 93}, // aliasReasons to reboot,undervoltage
James Hawkins74b17582017-11-20 14:13:41 -0800223 {"oem_ps_hold", 94},
224 {"abnormal_reset", 95},
225 {"oemerr_unknown", 96},
226 {"reboot_fastboot_mode", 97},
James Hawkins5f85f832017-11-29 14:30:06 -0800227 {"watchdog_apps_bite", 98},
228 {"xpu_err", 99},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700229 {"power_on_usb", 100}, // aliasReasons to cold,charger
James Hawkinsf4444f02017-11-30 15:01:40 -0800230 {"watchdog_rpm", 101},
231 {"watchdog_nonsec", 102},
232 {"watchdog_apps_bark", 103},
233 {"reboot_dmverity_corrupted", 104},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700234 {"reboot_smpl", 105}, // aliasReasons to reboot,powerloss
James Hawkins00433a22017-12-04 14:20:21 -0800235 {"watchdog_sdi_apps_reset", 106},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700236 {"smpl", 107}, // aliasReasons to reboot,powerloss
James Hawkins00433a22017-12-04 14:20:21 -0800237 {"oem_modem_failed_to_powerup", 108},
James Hawkinse2c27242017-12-18 13:40:27 -0800238 {"reboot_normal", 109},
239 {"oem_lpass_cfg", 110},
240 {"oem_xpu_ns_error", 111},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700241 {"power_key_press", 112}, // aliasReasons to cold,powerkey
James Hawkinse2c27242017-12-18 13:40:27 -0800242 {"hardware_reset", 113},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700243 {"reboot_by_powerkey", 114}, // aliasReasons to cold,powerkey (is this correct?)
James Hawkinse2c27242017-12-18 13:40:27 -0800244 {"reboot_verity", 115},
245 {"oem_rpm_undef_error", 116},
246 {"oem_crash_on_the_lk", 117},
247 {"oem_rpm_reset", 118},
Mark Salyzynf62983a2018-09-26 09:55:25 -0700248 {"reboot,powerloss", 119},
Mark Salyzynec7bafe2018-09-26 08:01:04 -0700249 {"reboot,undervoltage", 120},
James Hawkinse2c27242017-12-18 13:40:27 -0800250 {"factory_cable", 121},
251 {"oem_ar6320_failed_to_powerup", 122},
252 {"watchdog_rpm_bite", 123},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700253 {"power_on_cable", 124}, // aliasReasons to cold,charger
James Hawkinse2c27242017-12-18 13:40:27 -0800254 {"reboot_unknown", 125},
255 {"wireless_charger", 126},
256 {"0x776655ff", 127},
257 {"oem_thermal_bite_reset", 128},
258 {"charger", 129},
259 {"pon1", 130},
260 {"unknown", 131},
261 {"reboot_rtc", 132},
262 {"cold_boot", 133},
263 {"hard_rst", 134},
James Hawkinsb607dae2018-01-05 14:42:55 -0800264 {"power-on", 135},
265 {"oem_adsp_resetting_the_soc", 136},
266 {"kpdpwr", 137},
267 {"oem_modem_timeout_waiting", 138},
268 {"usb_chg", 139},
269 {"warm_reset_0x02", 140},
270 {"warm_reset_0x80", 141},
271 {"pon_reason_0xb0", 142},
272 {"reboot_download", 143},
James Hawkins79a4ee22018-01-26 14:31:04 -0800273 {"reboot_recovery_mode", 144},
274 {"oem_sdi_err_fatal", 145},
275 {"pmic_watchdog", 146},
276 {"software_master", 147},
Mark Salyzyn8aa36c62018-03-16 11:00:14 -0700277 {"cold,charger", 148},
278 {"cold,rtc", 149},
Mark Salyzyn4e7acf72018-03-16 11:00:26 -0700279 {"cold,rtc,2sec", 150}, // Mediatek
280 {"reboot,tool", 151}, // Mediatek
281 {"reboot,wdt", 152}, // Mediatek
282 {"reboot,unknown", 153}, // Mediatek
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700283 {"kernel_panic,audit", 154},
284 {"kernel_panic,atomic", 155},
285 {"kernel_panic,hung", 156},
286 {"kernel_panic,hung,rcu", 157},
287 {"kernel_panic,init", 158},
288 {"kernel_panic,oom", 159},
289 {"kernel_panic,stack", 160},
Mark Salyzynafd66f22018-03-19 15:16:29 -0700290 {"kernel_panic,sysrq,livelock,alarm", 161}, // llkd
291 {"kernel_panic,sysrq,livelock,driver", 162}, // llkd
292 {"kernel_panic,sysrq,livelock,zombie", 163}, // llkd
Mark Salyzyn8ad6e672018-06-01 08:59:05 -0700293 {"kernel_panic,modem", 164},
294 {"kernel_panic,adsp", 165},
295 {"kernel_panic,dsps", 166},
296 {"kernel_panic,wcnss", 167},
Mark Salyzyn78e54fd2018-06-08 10:19:16 -0700297 {"kernel_panic,_sde_encoder_phys_cmd_handle_ppdone_timeout", 168},
Mark Salyzyn6fc08292019-03-11 10:06:36 -0700298 {"recovery,quiescent", 169},
299 {"reboot,quiescent", 170},
Jone Choud51036d2019-03-20 19:38:05 +0800300 {"reboot,rtc", 171},
301 {"reboot,dm-verity_device_corrupted", 172},
302 {"reboot,dm-verity_enforcing", 173},
303 {"reboot,keys_clear", 174},
Jone Chou446d6c62019-04-18 15:43:26 +0800304 {"reboot,pmic_off_fault,.*", 175},
305 {"reboot,pmic_off_s3rst,.*", 176},
306 {"reboot,pmic_off_other,.*", 177},
Mark Salyzyn65d8b9b2019-05-23 09:07:54 -0700307 {"reboot,userrequested,fastboot", 178},
308 {"reboot,userrequested,recovery", 179},
309 {"reboot,userrequested,recovery,ui", 180},
310 {"shutdown,userrequested,fastboot", 181},
311 {"shutdown,userrequested,recovery", 182},
Mark Salyzyn8d1be802019-05-21 10:47:55 -0700312 {"reboot,unknown[0-9]*", 183},
Jone Choub9a80332019-06-10 23:24:39 +0800313 {"reboot,longkey,.*", 184},
Tom Cherrya76bfb22019-09-18 09:41:36 -0700314 {"reboot,boringssl-self-check-failed", 185},
Nikita Ioffe4a787d92020-01-15 23:23:13 +0000315 {"reboot,userspace_failed,shutdown_aborted", 186},
316 {"reboot,userspace_failed,watchdog_triggered", 187},
317 {"reboot,userspace_failed,watchdog_fork", 188},
318 {"reboot,userspace_failed,*", 189},
319 {"reboot,mount_userdata_failed", 190},
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800320};
321
322// Converts a string value representing the reason the system booted to an
323// integer representation. This is necessary for logging the boot_reason metric
324// via Tron, which does not accept non-integer buckets in histograms.
325int32_t BootReasonStrToEnum(const std::string& boot_reason) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800326 auto mapping = kBootReasonMap.find(boot_reason);
327 if (mapping != kBootReasonMap.end()) {
328 return mapping->second;
329 }
330
James Hawkins25f71222017-10-10 16:37:05 -0700331 if (boot_reason.empty()) {
332 return kEmptyBootReason;
333 }
334
Mark Salyzyn67ee8a82019-04-18 12:41:29 -0700335 for (const auto& [match, id] : kBootReasonMap) {
336 // Regex matches as a minimum require either [, \ or * to be present.
337 if (match.find_first_of("[\\*") == match.npos) continue;
338 // enforce match from beginning to end
339 auto exact = match;
340 if (exact[0] != '^') exact = "^" + exact;
341 if (exact[exact.size() - 1] != '$') exact = exact + "$";
342 if (std::regex_search(boot_reason, std::regex(exact))) return id;
343 }
344
James Hawkinsa4a1a4a2016-02-09 15:32:38 -0800345 LOG(INFO) << "Unknown boot reason: " << boot_reason;
346 return kUnknownBootReason;
347}
348
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700349// Canonical list of supported primary reboot reasons.
350const std::vector<const std::string> knownReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700351 // clang-format off
352 // kernel
353 "watchdog",
354 "kernel_panic",
355 // strong
356 "recovery", // Should not happen from ro.boot.bootreason
357 "bootloader", // Should not happen from ro.boot.bootreason
358 // blunt
359 "cold",
360 "hard",
361 "warm",
Mark Salyzyn62909822017-10-09 09:27:16 -0700362 // super blunt
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700363 "shutdown", // Can not happen from ro.boot.bootreason
364 "reboot", // Default catch-all for anything unknown
365 // clang-format on
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700366};
367
368// Returns true if the supplied reason prefix is considered detailed enough.
369bool isStrongRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700370 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700371 if (s == "cold") break;
372 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800373 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700374 return true;
375 }
376 }
377 return false;
378}
379
380// Returns true if the supplied reason prefix is associated with the kernel.
381bool isKernelRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700382 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700383 if (s == "recovery") break;
384 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800385 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700386 return true;
387 }
388 }
389 return false;
390}
391
392// Returns true if the supplied reason prefix is considered known.
393bool isKnownRebootReason(const std::string& r) {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700394 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700395 // Prefix defined as terminated by a nul or comma (,).
Elliott Hughes579e6822017-12-20 09:41:00 -0800396 if (android::base::StartsWith(r, s) && ((r.length() == s.length()) || (r[s.length()] == ','))) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700397 return true;
398 }
399 }
400 return false;
401}
402
403// If the reboot reason should be improved, report true if is too blunt.
404bool isBluntRebootReason(const std::string& r) {
405 if (isStrongRebootReason(r)) return false;
406
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700407 if (!isKnownRebootReason(r)) return true; // Can not support unknown as detail
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700408
409 size_t pos = 0;
410 while ((pos = r.find(',', pos)) != std::string::npos) {
411 ++pos;
412 std::string next(r.substr(pos));
413 if (next.length() == 0) break;
414 if (next[0] == ',') continue;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700415 if (!isKnownRebootReason(next)) return false; // Unknown subreason is good.
416 if (isStrongRebootReason(next)) return false; // eg: reboot,reboot
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700417 }
418 return true;
419}
420
Mark Salyzyn64610892017-09-18 10:41:14 -0700421bool readPstoreConsole(std::string& console) {
422 if (android::base::ReadFileToString("/sys/fs/pstore/console-ramoops-0", &console)) {
423 return true;
424 }
425 return android::base::ReadFileToString("/sys/fs/pstore/console-ramoops", &console);
426}
427
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700428// Implement a variant of std::string::rfind that is resilient to errors in
429// the data stream being inspected.
430class pstoreConsole {
431 private:
432 const size_t kBitErrorRate = 8; // number of bits per error
433 const std::string& console;
434
435 // Number of bits that differ between the two arguments l and r.
436 // Returns zero if the values for l and r are identical.
437 size_t numError(uint8_t l, uint8_t r) const { return std::bitset<8>(l ^ r).count(); }
438
439 // A string comparison function, reports the number of errors discovered
440 // in the match to a maximum of the bitLength / kBitErrorRate, at that
441 // point returning npos to indicate match is too poor.
442 //
443 // Since called in rfind which works backwards, expect cache locality will
444 // help if we check in reverse here as well for performance.
445 //
446 // Assumption: l (from console.c_str() + pos) is long enough to house
447 // _r.length(), checked in rfind caller below.
448 //
449 size_t numError(size_t pos, const std::string& _r) const {
450 const char* l = console.c_str() + pos;
451 const char* r = _r.c_str();
452 size_t n = _r.length();
453 const uint8_t* le = reinterpret_cast<const uint8_t*>(l) + n;
454 const uint8_t* re = reinterpret_cast<const uint8_t*>(r) + n;
455 size_t count = 0;
456 n = 0;
457 do {
458 // individual character bit error rate > threshold + slop
459 size_t num = numError(*--le, *--re);
460 if (num > ((8 + kBitErrorRate) / kBitErrorRate)) return std::string::npos;
461 // total bit error rate > threshold + slop
462 count += num;
463 ++n;
464 if (count > ((n * 8 + kBitErrorRate - (n > 2)) / kBitErrorRate)) {
465 return std::string::npos;
466 }
467 } while (le != reinterpret_cast<const uint8_t*>(l));
468 return count;
469 }
470
471 public:
472 explicit pstoreConsole(const std::string& console) : console(console) {}
473 // scope of argument must be equal to or greater than scope of pstoreConsole
474 explicit pstoreConsole(const std::string&& console) = delete;
475 explicit pstoreConsole(std::string&& console) = delete;
476
477 // Our implementation of rfind, use exact match first, then resort to fuzzy.
478 size_t rfind(const std::string& needle) const {
479 size_t pos = console.rfind(needle); // exact match?
480 if (pos != std::string::npos) return pos;
481
482 // Check to make sure needle fits in console string.
483 pos = console.length();
484 if (needle.length() > pos) return std::string::npos;
485 pos -= needle.length();
486 // fuzzy match to maximum kBitErrorRate
Ivan Lozano44d3cac2017-11-07 13:13:55 -0800487 for (;;) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700488 if (numError(pos, needle) != std::string::npos) return pos;
Ivan Lozano44d3cac2017-11-07 13:13:55 -0800489 if (pos == 0) break;
490 --pos;
491 }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700492 return std::string::npos;
493 }
494
495 // Our implementation of find, use only fuzzy match.
496 size_t find(const std::string& needle, size_t start = 0) const {
497 // Check to make sure needle fits in console string.
498 if (needle.length() > console.length()) return std::string::npos;
499 const size_t last_pos = console.length() - needle.length();
500 // fuzzy match to maximum kBitErrorRate
501 for (size_t pos = start; pos <= last_pos; ++pos) {
502 if (numError(pos, needle) != std::string::npos) return pos;
503 }
504 return std::string::npos;
505 }
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700506
507 operator const std::string&() const { return console; }
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700508};
509
510// If bit error match to needle, correct it.
511// Return true if any corrections were discovered and applied.
Mark Salyzyn1e7d1c72018-03-16 08:57:20 -0700512bool correctForBitError(std::string& reason, const std::string& needle) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700513 bool corrected = false;
514 if (reason.length() < needle.length()) return corrected;
515 const pstoreConsole console(reason);
516 const size_t last_pos = reason.length() - needle.length();
517 for (size_t pos = 0; pos <= last_pos; pos += needle.length()) {
518 pos = console.find(needle, pos);
519 if (pos == std::string::npos) break;
520
521 // exact match has no malice
522 if (needle == reason.substr(pos, needle.length())) continue;
523
524 corrected = true;
525 reason = reason.substr(0, pos) + needle + reason.substr(pos + needle.length());
526 }
527 return corrected;
528}
529
Mark Salyzyn1e7d1c72018-03-16 08:57:20 -0700530// If bit error match to needle, correct it.
531// Return true if any corrections were discovered and applied.
532// Try again if we can replace underline with spaces.
533bool correctForBitErrorOrUnderline(std::string& reason, const std::string& needle) {
534 bool corrected = correctForBitError(reason, needle);
535 std::string _needle(needle);
536 std::transform(_needle.begin(), _needle.end(), _needle.begin(),
537 [](char c) { return (c == '_') ? ' ' : c; });
538 if (needle != _needle) {
539 corrected |= correctForBitError(reason, _needle);
540 }
541 return corrected;
542}
543
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700544// Converts a string value representing the reason the system booted to a
545// string complying with Android system standard reason.
546void transformReason(std::string& reason) {
547 std::transform(reason.begin(), reason.end(), reason.begin(), ::tolower);
548 std::transform(reason.begin(), reason.end(), reason.begin(),
549 [](char c) { return ::isblank(c) ? '_' : c; });
550 std::transform(reason.begin(), reason.end(), reason.begin(),
551 [](char c) { return ::isprint(c) ? c : '?'; });
552}
553
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700554// Check subreasons for reboot,<subreason> kernel_panic,sysrq,<subreason> or
555// kernel_panic,<subreason>.
556//
557// If quoted flag is set, pull out and correct single quoted ('), newline (\n)
558// or unprintable character terminated subreason, pos is supplied just beyond
559// first quote. if quoted false, pull out and correct newline (\n) or
560// unprintable character terminated subreason.
561//
562// Heuristics to find termination is painted into a corner:
563
564// single bit error for quote ' that we can block. It is acceptable for
565// the others 7, g in reason. 2/9 chance will miss the terminating quote,
566// but there is always the terminating newline that usually immediately
567// follows to fortify our chances.
568bool likely_single_quote(char c) {
569 switch (static_cast<uint8_t>(c)) {
570 case '\'': // '\''
571 case '\'' ^ 0x01: // '&'
572 case '\'' ^ 0x02: // '%'
573 case '\'' ^ 0x04: // '#'
574 case '\'' ^ 0x08: // '/'
575 return true;
576 case '\'' ^ 0x10: // '7'
577 break;
578 case '\'' ^ 0x20: // '\a' (unprintable)
579 return true;
580 case '\'' ^ 0x40: // 'g'
581 break;
582 case '\'' ^ 0x80: // 0xA7 (unprintable)
583 return true;
584 }
585 return false;
586}
587
588// ::isprint(c) and likely_space() will prevent us from being called for
589// fundamentally printable entries, except for '\r' and '\b'.
590//
591// Except for * and J, single bit errors for \n, all others are non-
592// printable so easy catch. It is _acceptable_ for *, J or j to exist in
593// the reason string, so 2/9 chance we will miss the terminating newline.
594//
595// NB: J might not be acceptable, except if at the beginning or preceded
596// with a space, '(' or any of the quotes and their BER aliases.
597// NB: * might not be acceptable, except if at the beginning or preceded
598// with a space, another *, or any of the quotes or their BER aliases.
599//
600// To reduce the chances to closer to 1/9 is too complicated for the gain.
601bool likely_newline(char c) {
602 switch (static_cast<uint8_t>(c)) {
603 case '\n': // '\n' (unprintable)
604 case '\n' ^ 0x01: // '\r' (unprintable)
605 case '\n' ^ 0x02: // '\b' (unprintable)
606 case '\n' ^ 0x04: // 0x0E (unprintable)
607 case '\n' ^ 0x08: // 0x02 (unprintable)
608 case '\n' ^ 0x10: // 0x1A (unprintable)
609 return true;
610 case '\n' ^ 0x20: // '*'
611 case '\n' ^ 0x40: // 'J'
612 break;
613 case '\n' ^ 0x80: // 0x8A (unprintable)
614 return true;
615 }
616 return false;
617}
618
619// ::isprint(c) will prevent us from being called for all the printable
620// matches below. If we let unprintables through because of this, they
621// get converted to underscore (_) by the validation phase.
622bool likely_space(char c) {
623 switch (static_cast<uint8_t>(c)) {
624 case ' ': // ' '
625 case ' ' ^ 0x01: // '!'
626 case ' ' ^ 0x02: // '"'
627 case ' ' ^ 0x04: // '$'
628 case ' ' ^ 0x08: // '('
629 case ' ' ^ 0x10: // '0'
630 case ' ' ^ 0x20: // '\0' (unprintable)
631 case ' ' ^ 0x40: // 'P'
632 case ' ' ^ 0x80: // 0xA0 (unprintable)
633 case '\t': // '\t'
634 case '\t' ^ 0x01: // '\b' (unprintable) (likely_newline counters)
635 case '\t' ^ 0x02: // '\v' (unprintable)
636 case '\t' ^ 0x04: // '\r' (unprintable) (likely_newline counters)
637 case '\t' ^ 0x08: // 0x01 (unprintable)
638 case '\t' ^ 0x10: // 0x19 (unprintable)
639 case '\t' ^ 0x20: // ')'
640 case '\t' ^ 0x40: // '1'
641 case '\t' ^ 0x80: // 0x89 (unprintable)
642 return true;
643 }
644 return false;
645}
646
647std::string getSubreason(const std::string& content, size_t pos, bool quoted) {
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700648 static constexpr size_t max_reason_length = 256;
649
650 std::string subReason(content.substr(pos, max_reason_length));
651 // Correct against any known strings that Bit Error Match
652 for (const auto& s : knownReasons) {
653 correctForBitErrorOrUnderline(subReason, s);
654 }
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700655 std::string terminator(quoted ? "'" : "");
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700656 for (const auto& m : kBootReasonMap) {
657 if (m.first.length() <= strlen("cold")) continue; // too short?
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700658 if (correctForBitErrorOrUnderline(subReason, m.first + terminator)) continue;
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700659 if (m.first.length() <= strlen("reboot,cold")) continue; // short?
660 if (android::base::StartsWith(m.first, "reboot,")) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700661 correctForBitErrorOrUnderline(subReason, m.first.substr(strlen("reboot,")) + terminator);
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700662 } else if (android::base::StartsWith(m.first, "kernel_panic,sysrq,")) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700663 correctForBitErrorOrUnderline(subReason,
664 m.first.substr(strlen("kernel_panic,sysrq,")) + terminator);
665 } else if (android::base::StartsWith(m.first, "kernel_panic,")) {
666 correctForBitErrorOrUnderline(subReason, m.first.substr(strlen("kernel_panic,")) + terminator);
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700667 }
668 }
669 for (pos = 0; pos < subReason.length(); ++pos) {
670 char c = subReason[pos];
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700671 if (!(::isprint(c) || likely_space(c)) || likely_newline(c) ||
672 (quoted && likely_single_quote(c))) {
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700673 subReason.erase(pos);
674 break;
675 }
676 }
677 transformReason(subReason);
678 return subReason;
679}
680
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700681bool addKernelPanicSubReason(const pstoreConsole& console, std::string& ret) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700682 // Check for kernel panic types to refine information
Mark Salyzyn853bb802018-03-16 08:44:56 -0700683 if ((console.rfind("SysRq : Trigger a crash") != std::string::npos) ||
684 (console.rfind("PC is at sysrq_handle_crash+") != std::string::npos)) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700685 ret = "kernel_panic,sysrq";
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700686 // Invented for Android to allow daemons that specifically trigger sysrq
687 // to communicate more accurate boot subreasons via last console messages.
688 static constexpr char sysrqSubreason[] = "SysRq : Trigger a crash : '";
689 auto pos = console.rfind(sysrqSubreason);
690 if (pos != std::string::npos) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700691 ret += "," + getSubreason(console, pos + strlen(sysrqSubreason), /* quoted */ true);
Mark Salyzyn39cc3e72018-03-19 15:16:29 -0700692 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700693 return true;
694 }
695 if (console.rfind("Unable to handle kernel NULL pointer dereference at virtual address") !=
696 std::string::npos) {
Mark Salyzyn853bb802018-03-16 08:44:56 -0700697 ret = "kernel_panic,null";
Mark Salyzyn64610892017-09-18 10:41:14 -0700698 return true;
699 }
700 if (console.rfind("Kernel BUG at ") != std::string::npos) {
Mark Salyzyn853bb802018-03-16 08:44:56 -0700701 ret = "kernel_panic,bug";
Mark Salyzyn64610892017-09-18 10:41:14 -0700702 return true;
703 }
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700704
705 std::string panic("Kernel panic - not syncing: ");
706 auto pos = console.rfind(panic);
707 if (pos != std::string::npos) {
708 static const std::vector<std::pair<const std::string, const std::string>> panicReasons = {
709 {"Out of memory", "oom"},
710 {"out of memory", "oom"},
711 {"Oh boy, that early out of memory", "oom"}, // omg
712 {"BUG!", "bug"},
713 {"hung_task: blocked tasks", "hung"},
714 {"audit: ", "audit"},
715 {"scheduling while atomic", "atomic"},
716 {"Attempted to kill init!", "init"},
717 {"Requested init", "init"},
718 {"No working init", "init"},
719 {"Could not decompress init", "init"},
720 {"RCU Stall", "hung,rcu"},
721 {"stack-protector", "stack"},
722 {"kernel stack overflow", "stack"},
723 {"Corrupt kernel stack", "stack"},
724 {"low stack detected", "stack"},
725 {"corrupted stack end", "stack"},
Mark Salyzyn8ad6e672018-06-01 08:59:05 -0700726 {"subsys-restart: Resetting the SoC - modem crashed.", "modem"},
727 {"subsys-restart: Resetting the SoC - adsp crashed.", "adsp"},
728 {"subsys-restart: Resetting the SoC - dsps crashed.", "dsps"},
729 {"subsys-restart: Resetting the SoC - wcnss crashed.", "wcnss"},
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700730 };
731
732 ret = "kernel_panic";
733 for (auto& s : panicReasons) {
734 if (console.find(panic + s.first, pos) != std::string::npos) {
735 ret += "," + s.second;
736 return true;
737 }
738 }
739 auto reason = getSubreason(console, pos + panic.length(), /* newline */ false);
740 if (reason.length() > 3) {
741 ret += "," + reason;
742 }
743 return true;
744 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700745 return false;
746}
747
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700748bool addKernelPanicSubReason(const std::string& content, std::string& ret) {
749 return addKernelPanicSubReason(pstoreConsole(content), ret);
750}
751
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700752const char system_reboot_reason_property[] = "sys.boot.reason";
753const char last_reboot_reason_property[] = LAST_REBOOT_REASON_PROPERTY;
Mark Salyzynadc433d2018-06-05 08:17:35 -0700754const char last_last_reboot_reason_property[] = "sys.boot.reason.last";
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700755constexpr size_t history_reboot_reason_size = 4;
756const char history_reboot_reason_property[] = LAST_REBOOT_REASON_PROPERTY ".history";
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700757const char bootloader_reboot_reason_property[] = "ro.boot.bootreason";
758
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700759// Land system_boot_reason into system_reboot_reason_property.
760// Shift system_boot_reason into history_reboot_reason_property.
761void BootReasonAddToHistory(const std::string& system_boot_reason) {
762 if (system_boot_reason.empty()) return;
763 LOG(INFO) << "Canonical boot reason: " << system_boot_reason;
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800764 auto old_system_boot_reason = android::base::GetProperty(system_reboot_reason_property, "");
765 if (!android::base::SetProperty(system_reboot_reason_property, system_boot_reason)) {
766 android::base::SetProperty(system_reboot_reason_property,
767 system_boot_reason.substr(0, PROPERTY_VALUE_MAX - 1));
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700768 }
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800769 auto reason_history =
770 android::base::Split(android::base::GetProperty(history_reboot_reason_property, ""), "\n");
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700771 static auto mark = time(nullptr);
772 auto mark_str = std::string(",") + std::to_string(mark);
773 auto marked_system_boot_reason = system_boot_reason + mark_str;
774 if (!reason_history.empty()) {
775 // delete any entries that we just wrote in a previous
776 // call and leveraging duplicate line handling
777 auto last = old_system_boot_reason + mark_str;
778 // trim the list to (history_reboot_reason_size - 1)
779 ssize_t max = history_reboot_reason_size;
780 for (auto it = reason_history.begin(); it != reason_history.end();) {
781 if (it->empty() || (last == *it) || (marked_system_boot_reason == *it) || (--max <= 0)) {
782 it = reason_history.erase(it);
783 } else {
784 last = *it;
785 ++it;
786 }
787 }
788 }
789 // insert at the front, concatenating mark (<epoch time>) detail to the value.
790 reason_history.insert(reason_history.begin(), marked_system_boot_reason);
791 // If the property string is too long ( > PROPERTY_VALUE_MAX)
792 // we get an error, so trim out last entry and try again.
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800793 while (!android::base::SetProperty(history_reboot_reason_property,
794 android::base::Join(reason_history, '\n'))) {
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700795 auto it = std::prev(reason_history.end());
796 if (it == reason_history.end()) break;
797 reason_history.erase(it);
798 }
799}
800
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700801// Scrub, Sanitize, Standardize and Enhance the boot reason string supplied.
802std::string BootReasonStrToReason(const std::string& boot_reason) {
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800803 auto ret = android::base::GetProperty(system_reboot_reason_property, "");
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700804 std::string reason(boot_reason);
805 // If sys.boot.reason == ro.boot.bootreason, let's re-evaluate
806 if (reason == ret) ret = "";
807
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700808 transformReason(reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700809
810 // Is the current system boot reason sys.boot.reason valid?
811 if (!isKnownRebootReason(ret)) ret = "";
812
813 if (ret == "") {
814 // Is the bootloader boot reason ro.boot.bootreason known?
815 std::vector<std::string> words(android::base::Split(reason, ",_-"));
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700816 for (auto& s : knownReasons) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700817 std::string blunt;
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700818 for (auto& r : words) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700819 if (r == s) {
820 if (isBluntRebootReason(s)) {
821 blunt = s;
822 } else {
823 ret = s;
824 break;
825 }
826 }
827 }
828 if (ret == "") ret = blunt;
829 if (ret != "") break;
830 }
831 }
832
833 if (ret == "") {
834 // A series of checks to take some officially unsupported reasons
835 // reported by the bootloader and find some logical and canonical
836 // sense. In an ideal world, we would require those bootloaders
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700837 // to behave and follow our CTS standards.
838 //
839 // first member is the output
840 // second member is an unanchored regex for an alias
841 //
Mark Salyzyn28193282018-03-16 09:05:59 -0700842 // If output has a prefix of <bang> '!', we do not use it as a
843 // match needle (and drop the <bang> prefix when landing in output),
844 // otherwise look for it as well. This helps keep the scale of the
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700845 // following table smaller.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700846 static const std::vector<std::pair<const std::string, const std::string>> aliasReasons = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700847 {"watchdog", "wdog"},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700848 {"kernel_panic", "panic"},
849 {"shutdown,thermal", "thermal"},
850 {"warm,s3_wakeup", "s3_wakeup"},
851 {"hard,hw_reset", "hw_reset"},
Mark Salyzyn48d03ad2019-07-08 09:26:19 -0700852 {"cold,charger", "usb|power_on_cable"},
853 {"cold,powerkey", "powerkey|power_key|PowerKey|power_on"},
Mark Salyzyn8aa36c62018-03-16 11:00:14 -0700854 {"cold,rtc", "rtc"},
Mark Salyzyn186f6762018-03-16 11:00:26 -0700855 {"cold,rtc,2sec", "2sec_reboot"},
856 {"!warm", "wdt_by_pass_pwk"}, // change flavour of blunt
857 {"!reboot", "^wdt$"}, // change flavour of blunt
858 {"reboot,tool", "tool_by_pass_pwk"},
Mark Salyzyn88d1b4a2018-06-07 09:39:24 -0700859 {"!reboot,longkey", "reboot_longkey"},
860 {"!reboot,longkey", "kpdpwr"},
Mark Salyzynec7bafe2018-09-26 08:01:04 -0700861 {"!reboot,undervoltage", "uvlo"},
Mark Salyzynf62983a2018-09-26 09:55:25 -0700862 {"!reboot,powerloss", "smpl"},
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700863 {"bootloader", ""},
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700864 };
865
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -0700866 for (auto& s : aliasReasons) {
Mark Salyzyn28193282018-03-16 09:05:59 -0700867 size_t firstHasNot = s.first[0] == '!';
868 if (!firstHasNot && (reason.find(s.first) != std::string::npos)) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700869 ret = s.first;
870 break;
871 }
Mark Salyzyn25900dd2018-03-16 09:05:59 -0700872 if (s.second.size() && std::regex_search(reason, std::regex(s.second))) {
Mark Salyzyn28193282018-03-16 09:05:59 -0700873 ret = s.first.substr(firstHasNot);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700874 break;
875 }
876 }
877 }
878
879 // If watchdog is the reason, see if there is a security angle?
880 if (ret == "watchdog") {
881 if (reason.find("sec") != std::string::npos) {
882 ret += ",security";
883 }
884 }
885
Mark Salyzyn64610892017-09-18 10:41:14 -0700886 if (ret == "kernel_panic") {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700887 // Check to see if last klog has some refinement hints.
888 std::string content;
Mark Salyzyn64610892017-09-18 10:41:14 -0700889 if (readPstoreConsole(content)) {
890 addKernelPanicSubReason(content, ret);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700891 }
Mark Salyzyn64610892017-09-18 10:41:14 -0700892 } else if (isBluntRebootReason(ret)) {
893 // Check the other available reason resources if the reason is still blunt.
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700894
Mark Salyzyn64610892017-09-18 10:41:14 -0700895 // Check to see if last klog has some refinement hints.
896 std::string content;
897 if (readPstoreConsole(content)) {
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700898 const pstoreConsole console(content);
Mark Salyzyn64610892017-09-18 10:41:14 -0700899 // The toybox reboot command used directly (unlikely)? But also
900 // catches init's response to Android's more controlled reboot command.
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700901 if (console.rfind("reboot: Power down") != std::string::npos) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700902 ret = "shutdown"; // Still too blunt, but more accurate.
903 // ToDo: init should record the shutdown reason to kernel messages ala:
904 // init: shutdown system with command 'last_reboot_reason'
905 // so that if pstore has persistence we can get some details
906 // that could be missing in last_reboot_reason_property.
907 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700908
Mark Salyzyn64610892017-09-18 10:41:14 -0700909 static const char cmd[] = "reboot: Restarting system with command '";
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700910 size_t pos = console.rfind(cmd);
Mark Salyzyn64610892017-09-18 10:41:14 -0700911 if (pos != std::string::npos) {
Mark Salyzyn3f48fa92018-03-22 08:41:22 -0700912 std::string subReason(getSubreason(content, pos + strlen(cmd), /* quoted */ true));
Mark Salyzyn64610892017-09-18 10:41:14 -0700913 if (subReason != "") { // Will not land "reboot" as that is too blunt.
914 if (isKernelRebootReason(subReason)) {
915 ret = "reboot," + subReason; // User space can't talk kernel reasons.
Mark Salyzyndafced92017-09-20 08:37:46 -0700916 } else if (isKnownRebootReason(subReason)) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700917 ret = subReason;
Mark Salyzyndafced92017-09-20 08:37:46 -0700918 } else {
919 ret = "reboot," + subReason; // legitimize unknown reasons
Mark Salyzyn64610892017-09-18 10:41:14 -0700920 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700921 }
Mark Salyzyn15199252018-03-16 09:26:05 -0700922 // Some bootloaders shutdown results record in last kernel message.
923 if (!strcmp(ret.c_str(), "reboot,kernel_power_off_charging__reboot_system")) {
924 ret = "shutdown";
925 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700926 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700927
Mark Salyzyn64610892017-09-18 10:41:14 -0700928 // Check for kernel panics, allowed to override reboot command.
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700929 if (!addKernelPanicSubReason(console, ret) &&
Mark Salyzyn64610892017-09-18 10:41:14 -0700930 // check for long-press power down
Mark Salyzyn293cb3b2017-09-20 08:37:46 -0700931 ((console.rfind("Power held for ") != std::string::npos) ||
932 (console.rfind("charger: [") != std::string::npos))) {
Mark Salyzyn64610892017-09-18 10:41:14 -0700933 ret = "cold";
934 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700935 }
936
Elliott Hughes50a24eb2018-06-14 10:59:09 -0700937 // TODO: use the HAL to get battery level (http://b/77725702).
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700938
939 // Is there a controlled shutdown hint in last_reboot_reason_property?
940 if (isBluntRebootReason(ret)) {
941 // Content buffer no longer will have console data. Beware if more
942 // checks added below, that depend on parsing console content.
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800943 content = android::base::GetProperty(last_reboot_reason_property, "");
Mark Salyzyn88d692c2017-09-20 08:37:46 -0700944 transformReason(content);
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700945
Mark Salyzyn62909822017-10-09 09:27:16 -0700946 // Anything in last is better than 'super-blunt' reboot or shutdown.
947 if ((ret == "") || (ret == "reboot") || (ret == "shutdown") || !isBluntRebootReason(content)) {
948 ret = content;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700949 }
950 }
951
952 // Other System Health HAL reasons?
953
954 // ToDo: /proc/sys/kernel/boot_reason needs a HAL interface to
955 // possibly offer hardware-specific clues from the PMIC.
956 }
957
958 // If unknown left over from above, make it "reboot,<boot_reason>"
959 if (ret == "") {
960 ret = "reboot";
961 if (android::base::StartsWith(reason, "reboot")) {
962 reason = reason.substr(strlen("reboot"));
Mark Salyzyn0af71a52017-10-05 13:58:04 -0700963 while ((reason[0] == ',') || (reason[0] == '_')) {
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700964 reason = reason.substr(1);
965 }
966 }
967 if (reason != "") {
968 ret += ",";
969 ret += reason;
970 }
971 }
972
973 LOG(INFO) << "Canonical boot reason: " << ret;
Mark Salyzynb304f6d2017-08-04 13:35:51 -0700974 return ret;
975}
976
James Hawkinsb9cf7712016-04-08 15:32:19 -0700977// Returns the appropriate metric key prefix for the boot_complete metric such
978// that boot metrics after a system update are labeled as ota_boot_complete;
979// otherwise, they are labeled as boot_complete. This method encapsulates the
980// bookkeeping required to track when a system update has occurred by storing
981// the UTC timestamp of the system build date and comparing against the current
982// system build date.
983std::string CalculateBootCompletePrefix() {
984 static const std::string kBuildDateKey = "build_date";
985 std::string boot_complete_prefix = "boot_complete";
986
Mark Salyzyn88d308d2019-02-08 10:53:18 -0800987 auto build_date_str = android::base::GetProperty("ro.build.date.utc", "");
James Hawkins4dded612016-07-28 11:50:23 -0700988 int32_t build_date;
Elliott Hughesda46b392016-10-11 17:09:00 -0700989 if (!android::base::ParseInt(build_date_str, &build_date)) {
James Hawkins4dded612016-07-28 11:50:23 -0700990 return std::string();
991 }
James Hawkinsb9cf7712016-04-08 15:32:19 -0700992
993 BootEventRecordStore boot_event_store;
994 BootEventRecordStore::BootEventRecord record;
James Hawkins0bc4ad42017-05-30 15:03:15 -0700995 if (!boot_event_store.GetBootEvent(kBuildDateKey, &record)) {
996 boot_complete_prefix = "factory_reset_" + boot_complete_prefix;
997 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -0700998 BootReasonAddToHistory("reboot,factory_reset");
James Hawkins0bc4ad42017-05-30 15:03:15 -0700999 } else if (build_date != record.second) {
James Hawkinsb9cf7712016-04-08 15:32:19 -07001000 boot_complete_prefix = "ota_" + boot_complete_prefix;
1001 boot_event_store.AddBootEventWithValue(kBuildDateKey, build_date);
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -07001002 BootReasonAddToHistory("reboot,ota");
James Hawkinsb9cf7712016-04-08 15:32:19 -07001003 }
1004
1005 return boot_complete_prefix;
1006}
1007
James Hawkinsef0a0902017-01-06 14:38:23 -08001008// Records the value of a given ro.boottime.init property in milliseconds.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001009void RecordInitBootTimeProp(BootEventRecordStore* boot_event_store, const char* property) {
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001010 auto value = android::base::GetProperty(property, "");
James Hawkinsef0a0902017-01-06 14:38:23 -08001011
James Hawkins27c05222017-01-26 11:55:44 -08001012 int32_t time_in_ms;
1013 if (android::base::ParseInt(value, &time_in_ms)) {
James Hawkinsef0a0902017-01-06 14:38:23 -08001014 boot_event_store->AddBootEventWithValue(property, time_in_ms);
1015 }
1016}
1017
James Hawkins1bfcaec2017-05-19 14:27:27 -07001018// A map from bootloader timing stage to the time that stage took during boot.
1019typedef std::map<std::string, int32_t> BootloaderTimingMap;
1020
1021// Returns a mapping from bootloader stage names to the time those stages
1022// took to boot.
1023const BootloaderTimingMap GetBootLoaderTimings() {
1024 BootloaderTimingMap timings;
1025
1026 // |ro.boot.boottime| is of the form 'stage1:time1,...,stageN:timeN',
1027 // where timeN is in milliseconds.
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001028 auto value = android::base::GetProperty("ro.boot.boottime", "");
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001029 if (value.empty()) {
1030 // ro.boot.boottime is not reported on all devices.
James Hawkins1bfcaec2017-05-19 14:27:27 -07001031 return BootloaderTimingMap();
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001032 }
James Hawkinsbe46fd12017-02-02 16:21:25 -08001033
1034 auto stages = android::base::Split(value, ",");
James Hawkins1bfcaec2017-05-19 14:27:27 -07001035 for (const auto& stageTiming : stages) {
James Hawkinsbe46fd12017-02-02 16:21:25 -08001036 // |stageTiming| is of the form 'stage:time'.
1037 auto stageTimingValues = android::base::Split(stageTiming, ":");
James Hawkins0bc4ad42017-05-30 15:03:15 -07001038 DCHECK_EQ(2U, stageTimingValues.size());
James Hawkinsbe46fd12017-02-02 16:21:25 -08001039
Mark Salyzyn7c721162019-02-08 10:41:15 -08001040 if (stageTimingValues.size() < 2) continue;
James Hawkinsbe46fd12017-02-02 16:21:25 -08001041 std::string stageName = stageTimingValues[0];
1042 int32_t time_ms;
1043 if (android::base::ParseInt(stageTimingValues[1], &time_ms)) {
James Hawkins1bfcaec2017-05-19 14:27:27 -07001044 timings[stageName] = time_ms;
James Hawkinsbe46fd12017-02-02 16:21:25 -08001045 }
1046 }
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001047
James Hawkins1bfcaec2017-05-19 14:27:27 -07001048 return timings;
1049}
1050
Tej Singh4eacd382018-01-25 17:59:57 -08001051// Returns the total bootloader boot time from the ro.boot.boottime system property.
1052int32_t GetBootloaderTime(const BootloaderTimingMap& bootloader_timings) {
1053 int32_t total_time = 0;
1054 for (const auto& timing : bootloader_timings) {
1055 total_time += timing.second;
1056 }
1057
1058 return total_time;
1059}
1060
James Hawkins1bfcaec2017-05-19 14:27:27 -07001061// Parses and records the set of bootloader stages and associated boot times
1062// from the ro.boot.boottime system property.
1063void RecordBootloaderTimings(BootEventRecordStore* boot_event_store,
1064 const BootloaderTimingMap& bootloader_timings) {
1065 int32_t total_time = 0;
1066 for (const auto& timing : bootloader_timings) {
1067 total_time += timing.second;
1068 boot_event_store->AddBootEventWithValue("boottime.bootloader." + timing.first, timing.second);
1069 }
1070
James Hawkins6b5c5aa2017-02-16 11:53:03 -08001071 boot_event_store->AddBootEventWithValue("boottime.bootloader.total", total_time);
James Hawkinsbe46fd12017-02-02 16:21:25 -08001072}
1073
Tej Singh4eacd382018-01-25 17:59:57 -08001074// Returns the closest estimation to the absolute device boot time, i.e.,
James Hawkins1bfcaec2017-05-19 14:27:27 -07001075// from power on to boot_complete, including bootloader times.
Tej Singh4eacd382018-01-25 17:59:57 -08001076std::chrono::milliseconds GetAbsoluteBootTime(const BootloaderTimingMap& bootloader_timings,
1077 std::chrono::milliseconds uptime) {
James Hawkins1bfcaec2017-05-19 14:27:27 -07001078 int32_t bootloader_time_ms = 0;
1079
1080 for (const auto& timing : bootloader_timings) {
1081 if (timing.first.compare("SW") != 0) {
1082 bootloader_time_ms += timing.second;
1083 }
1084 }
1085
1086 auto bootloader_duration = std::chrono::milliseconds(bootloader_time_ms);
Tej Singh4eacd382018-01-25 17:59:57 -08001087 return bootloader_duration + uptime;
1088}
1089
1090// Records the closest estimation to the absolute device boot time in seconds.
1091// i.e. from power on to boot_complete, including bootloader times.
1092void RecordAbsoluteBootTime(BootEventRecordStore* boot_event_store,
1093 std::chrono::milliseconds absolute_total) {
1094 auto absolute_total_sec = std::chrono::duration_cast<std::chrono::seconds>(absolute_total);
1095 boot_event_store->AddBootEventWithValue("absolute_boot_time", absolute_total_sec.count());
1096}
1097
1098// Logs the total boot time and reason to statsd.
1099void LogBootInfoToStatsd(std::chrono::milliseconds end_time,
1100 std::chrono::milliseconds total_duration, int32_t bootloader_duration_ms,
1101 double time_since_last_boot_sec) {
Wei Wang699e3422019-05-22 09:46:02 -07001102 auto reason = android::base::GetProperty(bootloader_reboot_reason_property, "<EMPTY>");
1103 auto system_reason = android::base::GetProperty(system_reboot_reason_property, "<EMPTY>");
Tej Singh4eacd382018-01-25 17:59:57 -08001104 android::util::stats_write(android::util::BOOT_SEQUENCE_REPORTED, reason.c_str(),
1105 system_reason.c_str(), end_time.count(), total_duration.count(),
1106 (int64_t)bootloader_duration_ms,
1107 (int64_t)time_since_last_boot_sec * 1000);
James Hawkins1bfcaec2017-05-19 14:27:27 -07001108}
1109
Tej Singhfe3e7622018-02-06 15:57:38 -08001110void SetSystemBootReason() {
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001111 const auto bootloader_boot_reason =
1112 android::base::GetProperty(bootloader_reboot_reason_property, "");
Tej Singhfe3e7622018-02-06 15:57:38 -08001113 const std::string system_boot_reason(BootReasonStrToReason(bootloader_boot_reason));
1114 // Record the scrubbed system_boot_reason to the property
Mark Salyzyn5c58c9d2018-06-28 09:21:55 -07001115 BootReasonAddToHistory(system_boot_reason);
Mark Salyzynadc433d2018-06-05 08:17:35 -07001116 // Shift last_reboot_reason_property to last_last_reboot_reason_property
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001117 auto last_boot_reason = android::base::GetProperty(last_reboot_reason_property, "");
Mark Salyzynadc433d2018-06-05 08:17:35 -07001118 if (last_boot_reason.empty() || isKernelRebootReason(system_boot_reason)) {
1119 last_boot_reason = system_boot_reason;
1120 } else {
1121 transformReason(last_boot_reason);
1122 }
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001123 android::base::SetProperty(last_last_reboot_reason_property, last_boot_reason);
1124 android::base::SetProperty(last_reboot_reason_property, "");
Tej Singhfe3e7622018-02-06 15:57:38 -08001125}
1126
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001127// Gets the boot time offset. This is useful when Android is running in a
1128// container, because the boot_clock is not reset when Android reboots.
1129std::chrono::nanoseconds GetBootTimeOffset() {
1130 static const int64_t boottime_offset =
1131 android::base::GetIntProperty<int64_t>("ro.boot.boottime_offset", 0);
1132 return std::chrono::nanoseconds(boottime_offset);
1133}
1134
1135// Returns the current uptime, accounting for any offset in the CLOCK_BOOTTIME
1136// clock.
1137android::base::boot_clock::duration GetUptime() {
1138 return android::base::boot_clock::now().time_since_epoch() - GetBootTimeOffset();
1139}
1140
James Hawkinsc08e9962016-03-11 14:59:50 -08001141// Records several metrics related to the time it takes to boot the device,
1142// including disambiguating boot time on encrypted or non-encrypted devices.
1143void RecordBootComplete() {
1144 BootEventRecordStore boot_event_store;
James Hawkinsb9cf7712016-04-08 15:32:19 -07001145 BootEventRecordStore::BootEventRecord record;
James Hawkins2d8b3e62016-04-14 14:13:20 -07001146
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001147 auto uptime_ns = GetUptime();
1148 auto uptime_s = std::chrono::duration_cast<std::chrono::seconds>(uptime_ns);
James Hawkins2d8b3e62016-04-14 14:13:20 -07001149 time_t current_time_utc = time(nullptr);
Tej Singh4eacd382018-01-25 17:59:57 -08001150 time_t time_since_last_boot = 0;
James Hawkins2d8b3e62016-04-14 14:13:20 -07001151
1152 if (boot_event_store.GetBootEvent("last_boot_time_utc", &record)) {
1153 time_t last_boot_time_utc = record.second;
Tej Singh4eacd382018-01-25 17:59:57 -08001154 time_since_last_boot = difftime(current_time_utc, last_boot_time_utc);
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001155 boot_event_store.AddBootEventWithValue("time_since_last_boot", time_since_last_boot);
James Hawkins2d8b3e62016-04-14 14:13:20 -07001156 }
1157
1158 boot_event_store.AddBootEventWithValue("last_boot_time_utc", current_time_utc);
James Hawkinsc08e9962016-03-11 14:59:50 -08001159
James Hawkinsb9cf7712016-04-08 15:32:19 -07001160 // The boot_complete metric has two variants: boot_complete and
1161 // ota_boot_complete. The latter signifies that the device is booting after
1162 // a system update.
1163 std::string boot_complete_prefix = CalculateBootCompletePrefix();
James Hawkins4dded612016-07-28 11:50:23 -07001164 if (boot_complete_prefix.empty()) {
1165 // The system is hosed because the build date property could not be read.
1166 return;
1167 }
James Hawkinsc08e9962016-03-11 14:59:50 -08001168
1169 // post_decrypt_time_elapsed is only logged on encrypted devices.
1170 if (boot_event_store.GetBootEvent("post_decrypt_time_elapsed", &record)) {
1171 // Log the amount of time elapsed until the device is decrypted, which
1172 // includes the variable amount of time the user takes to enter the
1173 // decryption password.
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001174 boot_event_store.AddBootEventWithValue("boot_decryption_complete", uptime_s.count());
James Hawkinsc08e9962016-03-11 14:59:50 -08001175
1176 // Subtract the decryption time to normalize the boot cycle timing.
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001177 std::chrono::seconds boot_complete = std::chrono::seconds(uptime_s.count() - record.second);
James Hawkinsb9cf7712016-04-08 15:32:19 -07001178 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_post_decrypt",
James Hawkinse78ea772017-03-24 11:43:02 -07001179 boot_complete.count());
James Hawkinsc08e9962016-03-11 14:59:50 -08001180 } else {
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001181 boot_event_store.AddBootEventWithValue(boot_complete_prefix + "_no_encryption",
1182 uptime_s.count());
James Hawkinsc08e9962016-03-11 14:59:50 -08001183 }
1184
1185 // Record the total time from device startup to boot complete, regardless of
1186 // encryption state.
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001187 boot_event_store.AddBootEventWithValue(boot_complete_prefix, uptime_s.count());
James Hawkinsef0a0902017-01-06 14:38:23 -08001188
1189 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init");
Mark Salyzyn10377df2019-03-27 08:10:41 -07001190 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.first_stage");
James Hawkinsef0a0902017-01-06 14:38:23 -08001191 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.selinux");
1192 RecordInitBootTimeProp(&boot_event_store, "ro.boottime.init.cold_boot_wait");
James Hawkinsbe46fd12017-02-02 16:21:25 -08001193
James Hawkins1bfcaec2017-05-19 14:27:27 -07001194 const BootloaderTimingMap bootloader_timings = GetBootLoaderTimings();
Tej Singh4eacd382018-01-25 17:59:57 -08001195 int32_t bootloader_boot_duration = GetBootloaderTime(bootloader_timings);
James Hawkins1bfcaec2017-05-19 14:27:27 -07001196 RecordBootloaderTimings(&boot_event_store, bootloader_timings);
1197
Luis Hector Chavez583d34c2018-04-12 15:25:15 -07001198 auto uptime_ms = std::chrono::duration_cast<std::chrono::milliseconds>(uptime_ns);
Tej Singh4eacd382018-01-25 17:59:57 -08001199 auto absolute_boot_time = GetAbsoluteBootTime(bootloader_timings, uptime_ms);
1200 RecordAbsoluteBootTime(&boot_event_store, absolute_boot_time);
1201
1202 auto boot_end_time_point = std::chrono::system_clock::now().time_since_epoch();
1203 auto boot_end_time = std::chrono::duration_cast<std::chrono::milliseconds>(boot_end_time_point);
1204
1205 LogBootInfoToStatsd(boot_end_time, absolute_boot_time, bootloader_boot_duration,
1206 time_since_last_boot);
James Hawkinsc08e9962016-03-11 14:59:50 -08001207}
1208
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001209// Records the boot_reason metric by querying the ro.boot.bootreason system
1210// property.
1211void RecordBootReason() {
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001212 const auto reason = android::base::GetProperty(bootloader_reboot_reason_property, "");
James Hawkins25f71222017-10-10 16:37:05 -07001213
1214 if (reason.empty()) {
1215 // Log an empty boot reason value as '<EMPTY>' to ensure the value is intentional
1216 // (and not corruption anywhere else in the reporting pipeline).
1217 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
1218 android::metricslogger::FIELD_PLATFORM_REASON, "<EMPTY>");
1219 } else {
1220 android::metricslogger::LogMultiAction(android::metricslogger::ACTION_BOOT,
1221 android::metricslogger::FIELD_PLATFORM_REASON, reason);
1222 }
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001223
1224 // Log the raw bootloader_boot_reason property value.
1225 int32_t boot_reason = BootReasonStrToEnum(reason);
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001226 BootEventRecordStore boot_event_store;
1227 boot_event_store.AddBootEventWithValue("boot_reason", boot_reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001228
1229 // Log the scrubbed system_boot_reason.
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001230 const auto system_reason = android::base::GetProperty(system_reboot_reason_property, "");
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001231 int32_t system_boot_reason = BootReasonStrToEnum(system_reason);
1232 boot_event_store.AddBootEventWithValue("system_boot_reason", system_boot_reason);
1233
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001234 if (reason == "") {
Mark Salyzyn88d308d2019-02-08 10:53:18 -08001235 android::base::SetProperty(bootloader_reboot_reason_property, system_reason);
Mark Salyzynb304f6d2017-08-04 13:35:51 -07001236 }
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001237}
1238
James Hawkins500d7152016-02-16 15:05:54 -08001239// Records two metrics related to the user resetting a device: the time at
1240// which the device is reset, and the time since the user last reset the
1241// device. The former is only set once per-factory reset.
1242void RecordFactoryReset() {
1243 BootEventRecordStore boot_event_store;
1244 BootEventRecordStore::BootEventRecord record;
1245
1246 time_t current_time_utc = time(nullptr);
1247
James Hawkins0660b302016-03-08 16:18:15 -08001248 if (current_time_utc < 0) {
1249 // UMA does not display negative values in buckets, so convert to positive.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001250 android::metricslogger::LogHistogram("factory_reset_current_time_failure",
1251 std::abs(current_time_utc));
James Hawkinsfff95ba2016-03-29 16:13:49 -07001252
James Hawkins9aec9262017-01-31 11:42:24 -08001253 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001254 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001255 boot_event_store.AddBootEventWithValue("factory_reset_current_time_failure",
1256 std::abs(current_time_utc));
James Hawkins0660b302016-03-08 16:18:15 -08001257 return;
1258 } else {
James Hawkins9aec9262017-01-31 11:42:24 -08001259 android::metricslogger::LogHistogram("factory_reset_current_time", current_time_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001260
James Hawkins9aec9262017-01-31 11:42:24 -08001261 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001262 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001263 boot_event_store.AddBootEventWithValue("factory_reset_current_time", current_time_utc);
James Hawkins0660b302016-03-08 16:18:15 -08001264 }
1265
James Hawkins500d7152016-02-16 15:05:54 -08001266 // The factory_reset boot event does not exist after the device is reset, so
1267 // use this signal to mark the time of the factory reset.
1268 if (!boot_event_store.GetBootEvent("factory_reset", &record)) {
1269 boot_event_store.AddBootEventWithValue("factory_reset", current_time_utc);
James Hawkins3bf9b142016-03-03 14:50:24 -08001270
1271 // Don't log the time_since_factory_reset until some time has elapsed.
1272 // The data is not meaningful yet and skews the histogram buckets.
James Hawkins500d7152016-02-16 15:05:54 -08001273 return;
1274 }
1275
1276 // Calculate and record the difference in time between now and the
1277 // factory_reset time.
1278 time_t factory_reset_utc = record.second;
James Hawkins9aec9262017-01-31 11:42:24 -08001279 android::metricslogger::LogHistogram("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001280
James Hawkins9aec9262017-01-31 11:42:24 -08001281 // Logging via BootEventRecordStore to see if using android::metricslogger::LogHistogram
James Hawkinsfff95ba2016-03-29 16:13:49 -07001282 // is losing records somehow.
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001283 boot_event_store.AddBootEventWithValue("factory_reset_record_value", factory_reset_utc);
James Hawkinsfff95ba2016-03-29 16:13:49 -07001284
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001285 time_t time_since_factory_reset = difftime(current_time_utc, factory_reset_utc);
1286 boot_event_store.AddBootEventWithValue("time_since_factory_reset", time_since_factory_reset);
James Hawkins500d7152016-02-16 15:05:54 -08001287}
1288
Mark Salyzyn67ee8a82019-04-18 12:41:29 -07001289// List the associated boot reason(s), if arg is nullptr then all.
1290void PrintBootReasonEnum(const char* arg) {
1291 int value = -1;
1292 if (arg != nullptr) {
1293 value = BootReasonStrToEnum(arg);
1294 }
1295 for (const auto& [match, id] : kBootReasonMap) {
1296 if ((value < 0) || (value == id)) {
1297 printf("%u\t%s\n", id, match.c_str());
1298 }
1299 }
1300}
1301
James Hawkinsabd73e62016-01-19 15:10:38 -08001302} // namespace
1303
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001304int main(int argc, char** argv) {
James Hawkinsabd73e62016-01-19 15:10:38 -08001305 android::base::InitLogging(argv);
1306
1307 const std::string cmd_line = GetCommandLine(argc, argv);
1308 LOG(INFO) << "Service started: " << cmd_line;
1309
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001310 int option_index = 0;
James Hawkinsc6275582016-03-22 10:47:44 -07001311 static const char value_str[] = "value";
Tej Singhfe3e7622018-02-06 15:57:38 -08001312 static const char system_boot_reason_str[] = "set_system_boot_reason";
James Hawkinsc08e9962016-03-11 14:59:50 -08001313 static const char boot_complete_str[] = "record_boot_complete";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001314 static const char boot_reason_str[] = "record_boot_reason";
James Hawkins53684ea2016-02-23 16:18:19 -08001315 static const char factory_reset_str[] = "record_time_since_factory_reset";
Mark Salyzyn67ee8a82019-04-18 12:41:29 -07001316 static const char boot_reason_enum_str[] = "boot_reason_enum";
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001317 static const struct option long_options[] = {
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001318 // clang-format off
Tej Singhfe3e7622018-02-06 15:57:38 -08001319 { "help", no_argument, NULL, 'h' },
1320 { "log", no_argument, NULL, 'l' },
1321 { "print", no_argument, NULL, 'p' },
1322 { "record", required_argument, NULL, 'r' },
1323 { value_str, required_argument, NULL, 0 },
1324 { system_boot_reason_str, no_argument, NULL, 0 },
1325 { boot_complete_str, no_argument, NULL, 0 },
1326 { boot_reason_str, no_argument, NULL, 0 },
1327 { factory_reset_str, no_argument, NULL, 0 },
Mark Salyzyn67ee8a82019-04-18 12:41:29 -07001328 { boot_reason_enum_str, optional_argument, NULL, 0 },
Tej Singhfe3e7622018-02-06 15:57:38 -08001329 { NULL, 0, NULL, 0 }
Mark Salyzyn14b1e6d2017-09-18 10:41:14 -07001330 // clang-format on
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001331 };
1332
James Hawkinsc6275582016-03-22 10:47:44 -07001333 std::string boot_event;
1334 std::string value;
James Hawkinsabd73e62016-01-19 15:10:38 -08001335 int opt = 0;
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001336 while ((opt = getopt_long(argc, argv, "hlpr:", long_options, &option_index)) != -1) {
James Hawkinsabd73e62016-01-19 15:10:38 -08001337 switch (opt) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001338 // This case handles long options which have no single-character mapping.
1339 case 0: {
1340 const std::string option_name = long_options[option_index].name;
James Hawkinsc6275582016-03-22 10:47:44 -07001341 if (option_name == value_str) {
1342 // |optarg| is an external variable set by getopt representing
1343 // the option argument.
1344 value = optarg;
Tej Singhfe3e7622018-02-06 15:57:38 -08001345 } else if (option_name == system_boot_reason_str) {
1346 SetSystemBootReason();
James Hawkinsc6275582016-03-22 10:47:44 -07001347 } else if (option_name == boot_complete_str) {
James Hawkinsc08e9962016-03-11 14:59:50 -08001348 RecordBootComplete();
1349 } else if (option_name == boot_reason_str) {
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001350 RecordBootReason();
James Hawkins500d7152016-02-16 15:05:54 -08001351 } else if (option_name == factory_reset_str) {
1352 RecordFactoryReset();
Mark Salyzyn67ee8a82019-04-18 12:41:29 -07001353 } else if (option_name == boot_reason_enum_str) {
1354 PrintBootReasonEnum(optarg);
James Hawkinsa4a1a4a2016-02-09 15:32:38 -08001355 } else {
1356 LOG(ERROR) << "Invalid option: " << option_name;
1357 }
1358 break;
1359 }
1360
James Hawkinsabd73e62016-01-19 15:10:38 -08001361 case 'h': {
1362 ShowHelp(argv[0]);
1363 break;
1364 }
1365
1366 case 'l': {
1367 LogBootEvents();
1368 break;
1369 }
1370
1371 case 'p': {
1372 PrintBootEvents();
1373 break;
1374 }
1375
1376 case 'r': {
1377 // |optarg| is an external variable set by getopt representing
1378 // the option argument.
James Hawkinsc6275582016-03-22 10:47:44 -07001379 boot_event = optarg;
James Hawkinsabd73e62016-01-19 15:10:38 -08001380 break;
1381 }
1382
1383 default: {
1384 DCHECK_EQ(opt, '?');
1385
1386 // |optopt| is an external variable set by getopt representing
1387 // the value of the invalid option.
1388 LOG(ERROR) << "Invalid option: " << optopt;
1389 ShowHelp(argv[0]);
1390 return EXIT_FAILURE;
1391 }
1392 }
1393 }
1394
James Hawkinsc6275582016-03-22 10:47:44 -07001395 if (!boot_event.empty()) {
1396 RecordBootEventFromCommandLine(boot_event, value);
1397 }
1398
James Hawkinsabd73e62016-01-19 15:10:38 -08001399 return 0;
1400}