blob: 778207548f7709661b13f388e74777e027c1a9ff [file] [log] [blame]
Jason Chiu5d247d12023-11-27 16:42:44 +08001/*
2 * Copyright (C) 2020 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#define LOG_TAG "bootcontrolhal"
18
19#include "BootControl.h"
20
21#include <android-base/file.h>
22#include <android-base/unique_fd.h>
23#include <bootloader_message/bootloader_message.h>
24#include <cutils/properties.h>
25#include <libboot_control/libboot_control.h>
26#include <log/log.h>
27#include <trusty/tipc.h>
28
29#include "DevInfo.h"
30#include "GptUtils.h"
31
32namespace android {
33namespace hardware {
34namespace boot {
35namespace V1_2 {
36namespace implementation {
37
38using android::bootable::GetMiscVirtualAbMergeStatus;
39using android::bootable::InitMiscVirtualAbMessageIfNeeded;
40using android::bootable::SetMiscVirtualAbMergeStatus;
41using android::hardware::boot::V1_0::BoolResult;
42using android::hardware::boot::V1_0::CommandResult;
43using android::hardware::boot::V1_1::MergeStatus;
44
45namespace {
46
47// clang-format off
48
49#define BOOT_A_PATH "/dev/block/by-name/boot_a"
50#define BOOT_B_PATH "/dev/block/by-name/boot_b"
51#define DEVINFO_PATH "/dev/block/by-name/devinfo"
52
53// slot flags
54#define AB_ATTR_PRIORITY_SHIFT 52
55#define AB_ATTR_PRIORITY_MASK (3UL << AB_ATTR_PRIORITY_SHIFT)
56#define AB_ATTR_ACTIVE_SHIFT 54
57#define AB_ATTR_ACTIVE (1UL << AB_ATTR_ACTIVE_SHIFT)
58#define AB_ATTR_RETRY_COUNT_SHIFT (55)
59#define AB_ATTR_RETRY_COUNT_MASK (7UL << AB_ATTR_RETRY_COUNT_SHIFT)
60#define AB_ATTR_SUCCESSFUL (1UL << 58)
61#define AB_ATTR_UNBOOTABLE (1UL << 59)
62
63#define AB_ATTR_MAX_PRIORITY 3UL
64#define AB_ATTR_MAX_RETRY_COUNT 3UL
65
66// clang-format on
67
68static std::string getDevPath(uint32_t slot) {
69 char real_path[PATH_MAX];
70
71 const char *path = slot == 0 ? BOOT_A_PATH : BOOT_B_PATH;
72
73 int ret = readlink(path, real_path, sizeof real_path);
74 if (ret < 0) {
75 ALOGE("readlink failed for boot device %s\n", strerror(errno));
76 return std::string();
77 }
78
79 std::string dp(real_path);
80 // extract /dev/sda.. part
81 return dp.substr(0, sizeof "/dev/block/sdX" - 1);
82}
83
84static bool isSlotFlagSet(uint32_t slot, uint64_t flag) {
85 std::string dev_path = getDevPath(slot);
86 if (dev_path.empty()) {
87 ALOGI("Could not get device path for slot %d\n", slot);
88 return false;
89 }
90
91 GptUtils gpt(dev_path);
92 if (gpt.Load()) {
93 ALOGI("failed to load gpt data\n");
94 return false;
95 }
96
97 gpt_entry *e = gpt.GetPartitionEntry(slot ? "boot_b" : "boot_a");
98 if (e == nullptr) {
99 ALOGI("failed to get gpt entry\n");
100 return false;
101 }
102
103 return !!(e->attr & flag);
104}
105
106static bool setSlotFlag(uint32_t slot, uint64_t flag) {
107 std::string dev_path = getDevPath(slot);
108 if (dev_path.empty()) {
109 ALOGI("Could not get device path for slot %d\n", slot);
110 return false;
111 }
112
113 GptUtils gpt(dev_path);
114 if (gpt.Load()) {
115 ALOGI("failed to load gpt data\n");
116 return false;
117 }
118
119 gpt_entry *e = gpt.GetPartitionEntry(slot ? "boot_b" : "boot_a");
120 if (e == nullptr) {
121 ALOGI("failed to get gpt entry\n");
122 return false;
123 }
124
125 e->attr |= flag;
126 gpt.Sync();
127
128 return true;
129}
130
131static bool is_devinfo_valid;
132static bool is_devinfo_initialized;
133static std::mutex devinfo_lock;
134static devinfo_t devinfo;
135
136static bool isDevInfoValid() {
137 const std::lock_guard<std::mutex> lock(devinfo_lock);
138
139 if (is_devinfo_initialized) {
140 return is_devinfo_valid;
141 }
142
143 is_devinfo_initialized = true;
144
145 android::base::unique_fd fd(open(DEVINFO_PATH, O_RDONLY));
146 android::base::ReadFully(fd, &devinfo, sizeof devinfo);
147
148 if (devinfo.magic != DEVINFO_MAGIC) {
149 return is_devinfo_valid;
150 }
151
152 uint32_t version = ((uint32_t)devinfo.ver_major << 16) | devinfo.ver_minor;
153 // only version 3.3+ supports A/B data
154 if (version >= 0x0003'0003) {
155 is_devinfo_valid = true;
156 }
157
158 return is_devinfo_valid;
159}
160
161static bool DevInfoSync() {
162 if (!isDevInfoValid()) {
163 return false;
164 }
165
166 android::base::unique_fd fd(open(DEVINFO_PATH, O_WRONLY | O_DSYNC));
167 return android::base::WriteFully(fd, &devinfo, sizeof devinfo);
168}
169
170static void DevInfoInitSlot(devinfo_ab_slot_data_t &slot_data) {
171 slot_data.retry_count = AB_ATTR_MAX_RETRY_COUNT;
172 slot_data.unbootable = 0;
173 slot_data.successful = 0;
174 slot_data.active = 1;
175 slot_data.fastboot_ok = 0;
176}
177
178static int blow_otp_AR(bool secure) {
179 static const char *dev_name = "/dev/trusty-ipc-dev0";
180 static const char *otp_name = "com.android.trusty.otp_manager.tidl";
181 int fd = 1, ret = 0;
182 uint32_t cmd = secure? OTP_CMD_write_antirbk_secure_ap : OTP_CMD_write_antirbk_non_secure_ap;
183 fd = tipc_connect(dev_name, otp_name);
184 if (fd < 0) {
185 ALOGI("Failed to connect to OTP_MGR ns TA - is it missing?\n");
186 ret = -1;
187 return ret;
188 }
189
190 struct otp_mgr_req_base req = {
191 .command = cmd,
192 .resp_payload_size = 0,
193 };
194 struct iovec iov[] = {
195 {
196 .iov_base = &req,
197 .iov_len = sizeof(req),
198 },
199 };
200
201 int rc = tipc_send(fd, iov, 1, NULL, 0);
202 if (rc != sizeof(req)) {
203 ALOGI("Send fail! %x\n", rc);
204 return rc;
205 }
206
207 struct otp_mgr_rsp_base resp;
208 rc = read(fd, &resp, sizeof(resp));
209 if (rc < 0) {
210 ALOGI("Read fail! %x\n", rc);
211 return rc;
212 }
213
214 if (rc < sizeof(resp)) {
215 ALOGI("Not enough data! %x\n", rc);
216 return -EIO;
217 }
218
219 if (resp.command != (cmd | OTP_RESP_BIT)) {
220 ALOGI("Wrong command! %x\n", resp.command);
221 return -EINVAL;
222 }
223
224 if (resp.result != 0) {
225 fprintf(stderr, "AR writing error! %x\n", resp.result);
226 return -EINVAL;
227 }
228
229 tipc_close(fd);
230 return 0;
231}
232
233static bool blowAR() {
234 int ret = blow_otp_AR(true);
235 if (ret) {
236 ALOGI("Blow secure anti-rollback OTP failed");
237 return false;
238 }
239
240 ret = blow_otp_AR(false);
241 if (ret) {
242 ALOGI("Blow non-secure anti-rollback OTP failed");
243 return false;
244 }
245
246 return true;
247}
248} // namespace
249
250// Methods from ::android::hardware::boot::V1_0::IBootControl follow.
251Return<uint32_t> BootControl::getNumberSlots() {
252 uint32_t slots = 0;
253
254 if (access(BOOT_A_PATH, F_OK) == 0)
255 slots++;
256
257 if (access(BOOT_B_PATH, F_OK) == 0)
258 slots++;
259
260 return slots;
261}
262
263Return<uint32_t> BootControl::getCurrentSlot() {
264 char suffix[PROPERTY_VALUE_MAX];
265 property_get("ro.boot.slot_suffix", suffix, "_a");
266 return std::string(suffix) == "_b" ? 1 : 0;
267}
268
269Return<void> BootControl::markBootSuccessful(markBootSuccessful_cb _hidl_cb) {
270 if (getNumberSlots() == 0) {
271 // no slots, just return true otherwise Android keeps trying
272 _hidl_cb({true, ""});
273 return Void();
274 }
275
276 bool ret;
277 if (isDevInfoValid()) {
278 auto const slot = getCurrentSlot();
279 devinfo.ab_data.slots[slot].successful = 1;
280 ret = DevInfoSync();
281 } else {
282 ret = setSlotFlag(getCurrentSlot(), AB_ATTR_SUCCESSFUL);
283 }
284
285 if (!ret) {
286 _hidl_cb({false, "Failed to set successful flag"});
287 return Void();
288 }
289
290 if (!blowAR()) {
291 ALOGE("Failed to blow anti-rollback counter");
292 // Ignore the error, since ABL will re-trigger it on reboot
293 }
294
295 _hidl_cb({true, ""});
296 return Void();
297}
298
299Return<void> BootControl::setActiveBootSlot(uint32_t slot, setActiveBootSlot_cb _hidl_cb) {
300 if (slot >= 2) {
301 _hidl_cb({false, "Invalid slot"});
302 return Void();
303 }
304
305 if (isDevInfoValid()) {
306 auto &active_slot_data = devinfo.ab_data.slots[slot];
307 auto &inactive_slot_data = devinfo.ab_data.slots[!slot];
308
309 inactive_slot_data.active = 0;
310 DevInfoInitSlot(active_slot_data);
311
312 if (!DevInfoSync()) {
313 _hidl_cb({false, "Could not update DevInfo data"});
314 return Void();
315 }
316 } else {
317 std::string dev_path = getDevPath(slot);
318 if (dev_path.empty()) {
319 _hidl_cb({false, "Could not get device path for slot"});
320 return Void();
321 }
322
323 GptUtils gpt(dev_path);
324 if (gpt.Load()) {
325 _hidl_cb({false, "failed to load gpt data"});
326 return Void();
327 }
328
329 gpt_entry *active_entry = gpt.GetPartitionEntry(slot == 0 ? "boot_a" : "boot_b");
330 gpt_entry *inactive_entry = gpt.GetPartitionEntry(slot == 0 ? "boot_b" : "boot_a");
331 if (active_entry == nullptr || inactive_entry == nullptr) {
332 _hidl_cb({false, "failed to get entries for boot partitions"});
333 return Void();
334 }
335
336 ALOGV("slot active attributes %lx\n", active_entry->attr);
337 ALOGV("slot inactive attributes %lx\n", inactive_entry->attr);
338
339 // update attributes for active and inactive
340 inactive_entry->attr &= ~AB_ATTR_ACTIVE;
341 active_entry->attr = AB_ATTR_ACTIVE | (AB_ATTR_MAX_PRIORITY << AB_ATTR_PRIORITY_SHIFT) |
342 (AB_ATTR_MAX_RETRY_COUNT << AB_ATTR_RETRY_COUNT_SHIFT);
343 }
344
345 char boot_dev[PROPERTY_VALUE_MAX];
346 property_get("ro.boot.bootdevice", boot_dev, "");
347 if (boot_dev[0] == '\0') {
348 _hidl_cb({false, "invalid ro.boot.bootdevice prop"});
349 return Void();
350 }
351
352 std::string boot_lun_path =
353 std::string("/sys/devices/platform/") + boot_dev + "/pixel/boot_lun_enabled";
354 int fd = open(boot_lun_path.c_str(), O_RDWR | O_DSYNC);
355 if (fd < 0) {
356 // Try old path for kernels < 5.4
357 // TODO: remove once kernel 4.19 support is deprecated
358 std::string boot_lun_path =
359 std::string("/sys/devices/platform/") + boot_dev + "/attributes/boot_lun_enabled";
360 fd = open(boot_lun_path.c_str(), O_RDWR | O_DSYNC);
361 if (fd < 0) {
362 _hidl_cb({false, "failed to open ufs attr boot_lun_enabled"});
363 return Void();
364 }
365 }
366
367 //
368 // bBootLunEn
369 // 0x1 => Boot LU A = enabled, Boot LU B = disable
370 // 0x2 => Boot LU A = disable, Boot LU B = enabled
371 //
372 int ret = android::base::WriteStringToFd(slot == 0 ? "1" : "2", fd);
373 close(fd);
374 if (ret < 0) {
375 _hidl_cb({false, "faied to write boot_lun_enabled attribute"});
376 return Void();
377 }
378
379 _hidl_cb({true, ""});
380 return Void();
381}
382
383Return<void> BootControl::setSlotAsUnbootable(uint32_t slot, setSlotAsUnbootable_cb _hidl_cb) {
384 if (slot >= 2) {
385 _hidl_cb({false, "Invalid slot"});
386 return Void();
387 }
388
389 if (isDevInfoValid()) {
390 auto &slot_data = devinfo.ab_data.slots[slot];
391 slot_data.unbootable = 1;
392 if (!DevInfoSync()) {
393 _hidl_cb({false, "Could not update DevInfo data"});
394 return Void();
395 }
396 } else {
397 std::string dev_path = getDevPath(slot);
398 if (dev_path.empty()) {
399 _hidl_cb({false, "Could not get device path for slot"});
400 return Void();
401 }
402
403 GptUtils gpt(dev_path);
404 gpt.Load();
405
406 gpt_entry *e = gpt.GetPartitionEntry(slot ? "boot_b" : "boot_a");
407 e->attr |= AB_ATTR_UNBOOTABLE;
408
409 gpt.Sync();
410 }
411
412 _hidl_cb({true, ""});
413 return Void();
414}
415
416Return<::android::hardware::boot::V1_0::BoolResult> BootControl::isSlotBootable(uint32_t slot) {
417 if (getNumberSlots() == 0)
418 return BoolResult::FALSE;
419 if (slot >= getNumberSlots())
420 return BoolResult::INVALID_SLOT;
421
422 bool unbootable;
423 if (isDevInfoValid()) {
424 auto &slot_data = devinfo.ab_data.slots[slot];
425 unbootable = !!slot_data.unbootable;
426 } else {
427 unbootable = isSlotFlagSet(slot, AB_ATTR_UNBOOTABLE);
428 }
429
430 return unbootable ? BoolResult::FALSE : BoolResult::TRUE;
431}
432
433Return<::android::hardware::boot::V1_0::BoolResult> BootControl::isSlotMarkedSuccessful(
434 uint32_t slot) {
435 if (getNumberSlots() == 0) {
436 // just return true so that we don't we another call trying to mark it as successful
437 // when there is no slots
438 return BoolResult::TRUE;
439 }
440 if (slot >= getNumberSlots())
441 return BoolResult::INVALID_SLOT;
442
443 bool successful;
444 if (isDevInfoValid()) {
445 auto &slot_data = devinfo.ab_data.slots[slot];
446 successful = !!slot_data.successful;
447 } else {
448 successful = isSlotFlagSet(slot, AB_ATTR_SUCCESSFUL);
449 }
450
451 return successful ? BoolResult::TRUE : BoolResult::FALSE;
452}
453
454Return<void> BootControl::getSuffix(uint32_t slot, getSuffix_cb _hidl_cb) {
455 _hidl_cb(slot == 0 ? "_a" : slot == 1 ? "_b" : "");
456 return Void();
457}
458
459// Methods from ::android::hardware::boot::V1_1::IBootControl follow.
460bool BootControl::Init() {
461 return InitMiscVirtualAbMessageIfNeeded();
462}
463
464Return<bool> BootControl::setSnapshotMergeStatus(
465 ::android::hardware::boot::V1_1::MergeStatus status) {
466 return SetMiscVirtualAbMergeStatus(getCurrentSlot(), status);
467}
468
469Return<::android::hardware::boot::V1_1::MergeStatus> BootControl::getSnapshotMergeStatus() {
470 MergeStatus status;
471 if (!GetMiscVirtualAbMergeStatus(getCurrentSlot(), &status)) {
472 return MergeStatus::UNKNOWN;
473 }
474 return status;
475}
476
477// Methods from ::android::hardware::boot::V1_2::IBootControl follow.
478Return<uint32_t> BootControl::getActiveBootSlot() {
479 if (getNumberSlots() == 0)
480 return 0;
481
482 if (isDevInfoValid())
483 return devinfo.ab_data.slots[1].active ? 1 : 0;
484 return isSlotFlagSet(1, AB_ATTR_ACTIVE) ? 1 : 0;
485}
486
487// Methods from ::android::hidl::base::V1_0::IBase follow.
488
489IBootControl *HIDL_FETCH_IBootControl(const char * /* name */) {
490 auto module = new BootControl();
491
492 module->Init();
493
494 return module;
495}
496
497} // namespace implementation
498} // namespace V1_2
499} // namespace boot
500} // namespace hardware
501} // namespace android