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/properties.h>
24 #include <android-base/unique_fd.h>
25 #include <bootloader_message/bootloader_message.h>
26 #include <cutils/properties.h>
27 #include <libboot_control/libboot_control.h>
28 #include <log/log.h>
29 #include <trusty/tipc.h>
30 
31 #include "DevInfo.h"
32 #include "GptUtils.h"
33 
34 using HIDLMergeStatus = ::android::bootable::BootControl::MergeStatus;
35 using ndk::ScopedAStatus;
36 
37 using android::bootable::GetMiscVirtualAbMergeStatus;
38 using android::bootable::InitMiscVirtualAbMessageIfNeeded;
39 using android::bootable::SetMiscVirtualAbMergeStatus;
40 
41 namespace aidl::android::hardware::boot {
42 
43 namespace {
44 
45 // clang-format off
46 
47 #define BOOT_A_PATH     "/dev/block/by-name/boot_a"
48 #define BOOT_B_PATH     "/dev/block/by-name/boot_b"
49 #define DEVINFO_PATH    "/dev/block/by-name/devinfo"
50 
51 #define BLOW_AR_PATH    "/sys/kernel/boot_control/blow_ar"
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 
getDevPath(int32_t in_slot)68 static std::string getDevPath(int32_t in_slot) {
69     char real_path[PATH_MAX];
70 
71     const char *path = in_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 
isSlotFlagSet(int32_t in_slot,uint64_t flag)84 static bool isSlotFlagSet(int32_t in_slot, uint64_t flag) {
85     std::string dev_path = getDevPath(in_slot);
86     if (dev_path.empty()) {
87         ALOGI("Could not get device path for slot %d\n", in_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(in_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 
setSlotFlag(int32_t in_slot,uint64_t flag)106 static bool setSlotFlag(int32_t in_slot, uint64_t flag) {
107     std::string dev_path = getDevPath(in_slot);
108     if (dev_path.empty()) {
109         ALOGI("Could not get device path for slot %d\n", in_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(in_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 
131 static bool is_devinfo_valid;
132 static bool is_devinfo_initialized;
133 static std::mutex devinfo_lock;
134 static devinfo_t devinfo;
135 
isDevInfoValid()136 static 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 
DevInfoSync()161 static 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 
DevInfoInitSlot(devinfo_ab_slot_data_t & slot_data)170 static 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 
blow_otp_AR(bool secure)178 static 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     size_t rc = tipc_send(fd, iov, 1, NULL, 0);
202     if (rc != sizeof(req)) {
203         ALOGI("Send fail! %zx\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! %zx\n", rc);
211         return rc;
212     }
213 
214     if (rc < sizeof(resp)) {
215         ALOGI("Not enough data! %zx\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 
blowAR_zuma()233 static bool blowAR_zuma() {
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 
blowAR_gs101()249 static bool blowAR_gs101() {
250     ::android::base::unique_fd fd(open(BLOW_AR_PATH, O_WRONLY | O_DSYNC));
251     return ::android::base::WriteStringToFd("1", fd);
252 }
253 
blowAR()254 static bool blowAR() {
255     const auto& platform = ::android::base::GetProperty("ro.boot.hardware.platform", "");
256 
257     if (platform == "gs101") {
258         return blowAR_gs101();
259     } else if (platform == "gs201" || platform == "zuma" || platform == "zumapro") {
260         return blowAR_zuma();
261     }
262 
263     return false;
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 < 0 || 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