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