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