common: Drop part.h from common header
[oweals/u-boot.git] / common / android_ab.c
1 // SPDX-License-Identifier: BSD-2-Clause
2 /*
3  * Copyright (C) 2017 The Android Open Source Project
4  */
5 #include <common.h>
6 #include <android_ab.h>
7 #include <android_bootloader_message.h>
8 #include <blk.h>
9 #include <malloc.h>
10 #include <part.h>
11 #include <memalign.h>
12 #include <linux/err.h>
13 #include <u-boot/crc.h>
14 #include <u-boot/crc.h>
15
16 /**
17  * Compute the CRC-32 of the bootloader control struct.
18  *
19  * Only the bytes up to the crc32_le field are considered for the CRC-32
20  * calculation.
21  *
22  * @param[in] abc bootloader control block
23  *
24  * @return crc32 sum
25  */
26 static uint32_t ab_control_compute_crc(struct bootloader_control *abc)
27 {
28         return crc32(0, (void *)abc, offsetof(typeof(*abc), crc32_le));
29 }
30
31 /**
32  * Initialize bootloader_control to the default value.
33  *
34  * It allows us to boot all slots in order from the first one. This value
35  * should be used when the bootloader message is corrupted, but not when
36  * a valid message indicates that all slots are unbootable.
37  *
38  * @param[in] abc bootloader control block
39  *
40  * @return 0 on success and a negative on error
41  */
42 static int ab_control_default(struct bootloader_control *abc)
43 {
44         int i;
45         const struct slot_metadata metadata = {
46                 .priority = 15,
47                 .tries_remaining = 7,
48                 .successful_boot = 0,
49                 .verity_corrupted = 0,
50                 .reserved = 0
51         };
52
53         if (!abc)
54                 return -EFAULT;
55
56         memcpy(abc->slot_suffix, "a\0\0\0", 4);
57         abc->magic = BOOT_CTRL_MAGIC;
58         abc->version = BOOT_CTRL_VERSION;
59         abc->nb_slot = NUM_SLOTS;
60         memset(abc->reserved0, 0, sizeof(abc->reserved0));
61         for (i = 0; i < abc->nb_slot; ++i)
62                 abc->slot_info[i] = metadata;
63
64         memset(abc->reserved1, 0, sizeof(abc->reserved1));
65         abc->crc32_le = ab_control_compute_crc(abc);
66
67         return 0;
68 }
69
70 /**
71  * Load the boot_control struct from disk into newly allocated memory.
72  *
73  * This function allocates and returns an integer number of disk blocks,
74  * based on the block size of the passed device to help performing a
75  * read-modify-write operation on the boot_control struct.
76  * The boot_control struct offset (2 KiB) must be a multiple of the device
77  * block size, for simplicity.
78  *
79  * @param[in] dev_desc Device where to read the boot_control struct from
80  * @param[in] part_info Partition in 'dev_desc' where to read from, normally
81  *                      the "misc" partition should be used
82  * @param[out] pointer to pointer to bootloader_control data
83  * @return 0 on success and a negative on error
84  */
85 static int ab_control_create_from_disk(struct blk_desc *dev_desc,
86                                        const struct disk_partition *part_info,
87                                        struct bootloader_control **abc)
88 {
89         ulong abc_offset, abc_blocks, ret;
90
91         abc_offset = offsetof(struct bootloader_message_ab, slot_suffix);
92         if (abc_offset % part_info->blksz) {
93                 log_err("ANDROID: Boot control block not block aligned.\n");
94                 return -EINVAL;
95         }
96         abc_offset /= part_info->blksz;
97
98         abc_blocks = DIV_ROUND_UP(sizeof(struct bootloader_control),
99                                   part_info->blksz);
100         if (abc_offset + abc_blocks > part_info->size) {
101                 log_err("ANDROID: boot control partition too small. Need at");
102                 log_err(" least %lu blocks but have %lu blocks.\n",
103                         abc_offset + abc_blocks, part_info->size);
104                 return -EINVAL;
105         }
106         *abc = malloc_cache_aligned(abc_blocks * part_info->blksz);
107         if (!*abc)
108                 return -ENOMEM;
109
110         ret = blk_dread(dev_desc, part_info->start + abc_offset, abc_blocks,
111                         *abc);
112         if (IS_ERR_VALUE(ret)) {
113                 log_err("ANDROID: Could not read from boot ctrl partition\n");
114                 free(*abc);
115                 return -EIO;
116         }
117
118         log_debug("ANDROID: Loaded ABC, %lu blocks\n", abc_blocks);
119
120         return 0;
121 }
122
123 /**
124  * Store the loaded boot_control block.
125  *
126  * Store back to the same location it was read from with
127  * ab_control_create_from_misc().
128  *
129  * @param[in] dev_desc Device where we should write the boot_control struct
130  * @param[in] part_info Partition on the 'dev_desc' where to write
131  * @param[in] abc Pointer to the boot control struct and the extra bytes after
132  *                it up to the nearest block boundary
133  * @return 0 on success and a negative on error
134  */
135 static int ab_control_store(struct blk_desc *dev_desc,
136                             const struct disk_partition *part_info,
137                             struct bootloader_control *abc)
138 {
139         ulong abc_offset, abc_blocks, ret;
140
141         abc_offset = offsetof(struct bootloader_message_ab, slot_suffix) /
142                      part_info->blksz;
143         abc_blocks = DIV_ROUND_UP(sizeof(struct bootloader_control),
144                                   part_info->blksz);
145         ret = blk_dwrite(dev_desc, part_info->start + abc_offset, abc_blocks,
146                          abc);
147         if (IS_ERR_VALUE(ret)) {
148                 log_err("ANDROID: Could not write back the misc partition\n");
149                 return -EIO;
150         }
151
152         return 0;
153 }
154
155 /**
156  * Compare two slots.
157  *
158  * The function determines slot which is should we boot from among the two.
159  *
160  * @param[in] a The first bootable slot metadata
161  * @param[in] b The second bootable slot metadata
162  * @return Negative if the slot "a" is better, positive of the slot "b" is
163  *         better or 0 if they are equally good.
164  */
165 static int ab_compare_slots(const struct slot_metadata *a,
166                             const struct slot_metadata *b)
167 {
168         /* Higher priority is better */
169         if (a->priority != b->priority)
170                 return b->priority - a->priority;
171
172         /* Higher successful_boot value is better, in case of same priority */
173         if (a->successful_boot != b->successful_boot)
174                 return b->successful_boot - a->successful_boot;
175
176         /* Higher tries_remaining is better to ensure round-robin */
177         if (a->tries_remaining != b->tries_remaining)
178                 return b->tries_remaining - a->tries_remaining;
179
180         return 0;
181 }
182
183 int ab_select_slot(struct blk_desc *dev_desc, struct disk_partition *part_info)
184 {
185         struct bootloader_control *abc = NULL;
186         u32 crc32_le;
187         int slot, i, ret;
188         bool store_needed = false;
189         char slot_suffix[4];
190
191         ret = ab_control_create_from_disk(dev_desc, part_info, &abc);
192         if (ret < 0) {
193                 /*
194                  * This condition represents an actual problem with the code or
195                  * the board setup, like an invalid partition information.
196                  * Signal a repair mode and do not try to boot from either slot.
197                  */
198                 return ret;
199         }
200
201         crc32_le = ab_control_compute_crc(abc);
202         if (abc->crc32_le != crc32_le) {
203                 log_err("ANDROID: Invalid CRC-32 (expected %.8x, found %.8x),",
204                         crc32_le, abc->crc32_le);
205                 log_err("re-initializing A/B metadata.\n");
206
207                 ret = ab_control_default(abc);
208                 if (ret < 0) {
209                         free(abc);
210                         return -ENODATA;
211                 }
212                 store_needed = true;
213         }
214
215         if (abc->magic != BOOT_CTRL_MAGIC) {
216                 log_err("ANDROID: Unknown A/B metadata: %.8x\n", abc->magic);
217                 free(abc);
218                 return -ENODATA;
219         }
220
221         if (abc->version > BOOT_CTRL_VERSION) {
222                 log_err("ANDROID: Unsupported A/B metadata version: %.8x\n",
223                         abc->version);
224                 free(abc);
225                 return -ENODATA;
226         }
227
228         /*
229          * At this point a valid boot control metadata is stored in abc,
230          * followed by other reserved data in the same block. We select a with
231          * the higher priority slot that
232          *  - is not marked as corrupted and
233          *  - either has tries_remaining > 0 or successful_boot is true.
234          * If the selected slot has a false successful_boot, we also decrement
235          * the tries_remaining until it eventually becomes unbootable because
236          * tries_remaining reaches 0. This mechanism produces a bootloader
237          * induced rollback, typically right after a failed update.
238          */
239
240         /* Safety check: limit the number of slots. */
241         if (abc->nb_slot > ARRAY_SIZE(abc->slot_info)) {
242                 abc->nb_slot = ARRAY_SIZE(abc->slot_info);
243                 store_needed = true;
244         }
245
246         slot = -1;
247         for (i = 0; i < abc->nb_slot; ++i) {
248                 if (abc->slot_info[i].verity_corrupted ||
249                     !abc->slot_info[i].tries_remaining) {
250                         log_debug("ANDROID: unbootable slot %d tries: %d, ",
251                                   i, abc->slot_info[i].tries_remaining);
252                         log_debug("corrupt: %d\n",
253                                   abc->slot_info[i].verity_corrupted);
254                         continue;
255                 }
256                 log_debug("ANDROID: bootable slot %d pri: %d, tries: %d, ",
257                           i, abc->slot_info[i].priority,
258                           abc->slot_info[i].tries_remaining);
259                 log_debug("corrupt: %d, successful: %d\n",
260                           abc->slot_info[i].verity_corrupted,
261                           abc->slot_info[i].successful_boot);
262
263                 if (slot < 0 ||
264                     ab_compare_slots(&abc->slot_info[i],
265                                      &abc->slot_info[slot]) < 0) {
266                         slot = i;
267                 }
268         }
269
270         if (slot >= 0 && !abc->slot_info[slot].successful_boot) {
271                 log_err("ANDROID: Attempting slot %c, tries remaining %d\n",
272                         BOOT_SLOT_NAME(slot),
273                         abc->slot_info[slot].tries_remaining);
274                 abc->slot_info[slot].tries_remaining--;
275                 store_needed = true;
276         }
277
278         if (slot >= 0) {
279                 /*
280                  * Legacy user-space requires this field to be set in the BCB.
281                  * Newer releases load this slot suffix from the command line
282                  * or the device tree.
283                  */
284                 memset(slot_suffix, 0, sizeof(slot_suffix));
285                 slot_suffix[0] = BOOT_SLOT_NAME(slot);
286                 if (memcmp(abc->slot_suffix, slot_suffix,
287                            sizeof(slot_suffix))) {
288                         memcpy(abc->slot_suffix, slot_suffix,
289                                sizeof(slot_suffix));
290                         store_needed = true;
291                 }
292         }
293
294         if (store_needed) {
295                 abc->crc32_le = ab_control_compute_crc(abc);
296                 ab_control_store(dev_desc, part_info, abc);
297         }
298         free(abc);
299
300         if (slot < 0)
301                 return -EINVAL;
302
303         return slot;
304 }