blob: 4e728057c786180cd1637e800059036024bfa41e [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') {
Jason Chiu2a201a72023-11-25 02:53:02 +0800348 ALOGI("failed to get ro.boot.bootdevice. try ro.boot.boot_devices\n");
349 property_get("ro.boot.boot_devices", boot_dev, "");
350 if (boot_dev[0] == '\0') {
351 _hidl_cb({false, "invalid ro.boot.bootdevice and ro.boot.boot_devices prop"});
352 return Void();
353 }
Jason Chiu5d247d12023-11-27 16:42:44 +0800354 }
355
356 std::string boot_lun_path =
357 std::string("/sys/devices/platform/") + boot_dev + "/pixel/boot_lun_enabled";
358 int fd = open(boot_lun_path.c_str(), O_RDWR | O_DSYNC);
359 if (fd < 0) {
360 // Try old path for kernels < 5.4
361 // TODO: remove once kernel 4.19 support is deprecated
362 std::string boot_lun_path =
363 std::string("/sys/devices/platform/") + boot_dev + "/attributes/boot_lun_enabled";
364 fd = open(boot_lun_path.c_str(), O_RDWR | O_DSYNC);
365 if (fd < 0) {
366 _hidl_cb({false, "failed to open ufs attr boot_lun_enabled"});
367 return Void();
368 }
369 }
370
371 //
372 // bBootLunEn
373 // 0x1 => Boot LU A = enabled, Boot LU B = disable
374 // 0x2 => Boot LU A = disable, Boot LU B = enabled
375 //
376 int ret = android::base::WriteStringToFd(slot == 0 ? "1" : "2", fd);
377 close(fd);
378 if (ret < 0) {
379 _hidl_cb({false, "faied to write boot_lun_enabled attribute"});
380 return Void();
381 }
382
383 _hidl_cb({true, ""});
384 return Void();
385}
386
387Return<void> BootControl::setSlotAsUnbootable(uint32_t slot, setSlotAsUnbootable_cb _hidl_cb) {
388 if (slot >= 2) {
389 _hidl_cb({false, "Invalid slot"});
390 return Void();
391 }
392
393 if (isDevInfoValid()) {
394 auto &slot_data = devinfo.ab_data.slots[slot];
395 slot_data.unbootable = 1;
396 if (!DevInfoSync()) {
397 _hidl_cb({false, "Could not update DevInfo data"});
398 return Void();
399 }
400 } else {
401 std::string dev_path = getDevPath(slot);
402 if (dev_path.empty()) {
403 _hidl_cb({false, "Could not get device path for slot"});
404 return Void();
405 }
406
407 GptUtils gpt(dev_path);
408 gpt.Load();
409
410 gpt_entry *e = gpt.GetPartitionEntry(slot ? "boot_b" : "boot_a");
411 e->attr |= AB_ATTR_UNBOOTABLE;
412
413 gpt.Sync();
414 }
415
416 _hidl_cb({true, ""});
417 return Void();
418}
419
420Return<::android::hardware::boot::V1_0::BoolResult> BootControl::isSlotBootable(uint32_t slot) {
421 if (getNumberSlots() == 0)
422 return BoolResult::FALSE;
423 if (slot >= getNumberSlots())
424 return BoolResult::INVALID_SLOT;
425
426 bool unbootable;
427 if (isDevInfoValid()) {
428 auto &slot_data = devinfo.ab_data.slots[slot];
429 unbootable = !!slot_data.unbootable;
430 } else {
431 unbootable = isSlotFlagSet(slot, AB_ATTR_UNBOOTABLE);
432 }
433
434 return unbootable ? BoolResult::FALSE : BoolResult::TRUE;
435}
436
437Return<::android::hardware::boot::V1_0::BoolResult> BootControl::isSlotMarkedSuccessful(
438 uint32_t slot) {
439 if (getNumberSlots() == 0) {
440 // just return true so that we don't we another call trying to mark it as successful
441 // when there is no slots
442 return BoolResult::TRUE;
443 }
444 if (slot >= getNumberSlots())
445 return BoolResult::INVALID_SLOT;
446
447 bool successful;
448 if (isDevInfoValid()) {
449 auto &slot_data = devinfo.ab_data.slots[slot];
450 successful = !!slot_data.successful;
451 } else {
452 successful = isSlotFlagSet(slot, AB_ATTR_SUCCESSFUL);
453 }
454
455 return successful ? BoolResult::TRUE : BoolResult::FALSE;
456}
457
458Return<void> BootControl::getSuffix(uint32_t slot, getSuffix_cb _hidl_cb) {
459 _hidl_cb(slot == 0 ? "_a" : slot == 1 ? "_b" : "");
460 return Void();
461}
462
463// Methods from ::android::hardware::boot::V1_1::IBootControl follow.
464bool BootControl::Init() {
465 return InitMiscVirtualAbMessageIfNeeded();
466}
467
468Return<bool> BootControl::setSnapshotMergeStatus(
469 ::android::hardware::boot::V1_1::MergeStatus status) {
470 return SetMiscVirtualAbMergeStatus(getCurrentSlot(), status);
471}
472
473Return<::android::hardware::boot::V1_1::MergeStatus> BootControl::getSnapshotMergeStatus() {
474 MergeStatus status;
475 if (!GetMiscVirtualAbMergeStatus(getCurrentSlot(), &status)) {
476 return MergeStatus::UNKNOWN;
477 }
478 return status;
479}
480
481// Methods from ::android::hardware::boot::V1_2::IBootControl follow.
482Return<uint32_t> BootControl::getActiveBootSlot() {
483 if (getNumberSlots() == 0)
484 return 0;
485
486 if (isDevInfoValid())
487 return devinfo.ab_data.slots[1].active ? 1 : 0;
488 return isSlotFlagSet(1, AB_ATTR_ACTIVE) ? 1 : 0;
489}
490
491// Methods from ::android::hidl::base::V1_0::IBase follow.
492
493IBootControl *HIDL_FETCH_IBootControl(const char * /* name */) {
494 auto module = new BootControl();
495
496 module->Init();
497
498 return module;
499}
500
501} // namespace implementation
502} // namespace V1_2
503} // namespace boot
504} // namespace hardware
505} // namespace android