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