diff mbox series

[U-Boot,v3,3/7] common: Implement A/B metadata

Message ID 1550506917-25547-4-git-send-email-igor.opaniuk@linaro.org
State Superseded
Delegated to: Tom Rini
Headers show
Series android: implement A/B boot process | expand

Commit Message

Igor Opaniuk Feb. 18, 2019, 4:21 p.m. UTC
From: Ruslan Trofymenko <ruslan.trofymenko@linaro.org>

This patch determines the A/B-specific bootloader message structure
that is the basis for implementation of recovery and A/B update
functions. A/B metadata is stored in this structure and used to decide
which slot should we use to boot the device. Also some basic functions
for A/B metadata manipulation are implemented (like slot selection).

The patch was extracted from commits [1], [2] with some coding style
fixes.

[1] https://android-review.googlesource.com/c/platform/external/u-boot/+/729878/2
[2] https://android-review.googlesource.com/c/platform/external/u-boot/+/729880/2

Signed-off-by: Ruslan Trofymenko <ruslan.trofymenko@linaro.org>
Signed-off-by: Igor Opaniuk <igor.opaniuk@linaro.org>
Reviewed-by: Sam Protsenko <semen.protsenko@linaro.org>
---

Changes in v3:
  * Add multiple sanity checks
  * Fix mix. minor code formatting issues

Changes in v2:
  * Function return codes are clarified
  * Some types and constants are renamed (for compactness)
  * android_bootloader_message.h is renamed to android_bl_msg.h
  * 'debug' calls are changed to 'log_debug'
  * Order of headers is changed
  * android_bl_msg.h was synced with AOSP master counterpart

 common/Kconfig           |  10 ++
 common/Makefile          |   1 +
 common/android_ab.c      | 290 +++++++++++++++++++++++++++++++++++++++++++++++
 include/android_ab.h     |  34 ++++++
 include/android_bl_msg.h | 169 +++++++++++++++++++++++++++
 5 files changed, 504 insertions(+)
 create mode 100644 common/android_ab.c
 create mode 100644 include/android_ab.h
 create mode 100644 include/android_bl_msg.h

Comments

Eugeniu Rosca March 8, 2019, 5:28 p.m. UTC | #1
Hello Igor,

Thanks for the series. Some questions below.

First, my understanding is that the patches replace the deprecated
libavb_ab and make it trully obsolete, i.e. there should be no need to
import libavb_ab into U-Boot (unlike some of our suppliers still do).
Can you please confirm?

On Mon, Feb 18, 2019 at 5:25 PM Igor Opaniuk <igor.opaniuk@linaro.org> wrote:
>
[..]

> diff --git a/include/android_bl_msg.h b/include/android_bl_msg.h
> new file mode 100644
> index 0000000..f37e01a
> --- /dev/null
> +++ b/include/android_bl_msg.h
> @@ -0,0 +1,169 @@
> +/* SPDX-License-Identifier: BSD-2-Clause */
> +/*
> + * This file was taken from the AOSP Project.
> + * Repository: https://android.googlesource.com/platform/bootable/recovery/
> + * File: bootloader_message/include/bootloader_message/bootloader_message.h

I won't object on it and it's not my purpose to do any
teaching/mentoring, but I think it makes sense to decouple (i.e.
allocate standalone commits for) these two activities:
 - integration of external headers/libraries (e.g. libavb, dtc,
headers imported from linux/avb/recovery/etc trees)
 - in-tree U-Boot development around those headers/libraries

I think mixing these two activities creates more overhead for the
reviewers, so it's easy for various mistakes to slip in unnoticed. See
next comment as example.

> + * Commit: 8b309f6970ab3b7c53cc529c51a2cb44e1c7a7e1

The contents of out-of-tree "bootloader_message.h" at this commit
doesn't appear to contain any "Omaha" references:
https://android.googlesource.com/platform/bootable/recovery.git/+/8b309f6970ab3b/bootloader_message/include/bootloader_message/bootloader_message.h

The addition of "Omaha" comment is done in commit:
$ git log --oneline -G Omaha  8b309f6970ab..recovery/master --
bootloader_message/include/bootloader_message/bootloader_message.h
7191bf049216 Add update_channel field to bootloader_message_ab.

So, I believe there is a mismatch between the contents of the newly
created file and its documented version.

[..]

> +       u8 priority : 4;
> +       /* Number of times left attempting to boot this slot */
> +       u8 tries_remaining : 3;
> +       /* 1 if this slot has booted successfully, 0 otherwise */
> +       u8 successful_boot : 1;

The s/uint8_t/u8/ and s/uint32_t/u32/ conversion creates noise
comparing the in-tree versus out-of-tree files and will add some
overhead during integration. I still see a lot of U-Boot code saying
uint8_t/uint32_t, so I wonder if these can be preserved. BTW, some of
the patches from this series add code using uint32_t.

Looking forward to pick the patches from mainline!

Thanks and best regards,
Eugeniu.
Simon Glass March 10, 2019, 9:50 p.m. UTC | #2
Hi Igor,

On Mon, 18 Feb 2019 at 10:22, Igor Opaniuk <igor.opaniuk@linaro.org> wrote:
>
> From: Ruslan Trofymenko <ruslan.trofymenko@linaro.org>
>
> This patch determines the A/B-specific bootloader message structure
> that is the basis for implementation of recovery and A/B update
> functions. A/B metadata is stored in this structure and used to decide
> which slot should we use to boot the device. Also some basic functions
> for A/B metadata manipulation are implemented (like slot selection).
>
> The patch was extracted from commits [1], [2] with some coding style
> fixes.
>
> [1] https://android-review.googlesource.com/c/platform/external/u-boot/+/729878/2
> [2] https://android-review.googlesource.com/c/platform/external/u-boot/+/729880/2
>
> Signed-off-by: Ruslan Trofymenko <ruslan.trofymenko@linaro.org>
> Signed-off-by: Igor Opaniuk <igor.opaniuk@linaro.org>
> Reviewed-by: Sam Protsenko <semen.protsenko@linaro.org>
> ---
>
> Changes in v3:
>   * Add multiple sanity checks
>   * Fix mix. minor code formatting issues
>
> Changes in v2:
>   * Function return codes are clarified
>   * Some types and constants are renamed (for compactness)
>   * android_bootloader_message.h is renamed to android_bl_msg.h
>   * 'debug' calls are changed to 'log_debug'
>   * Order of headers is changed
>   * android_bl_msg.h was synced with AOSP master counterpart
>
>  common/Kconfig           |  10 ++
>  common/Makefile          |   1 +
>  common/android_ab.c      | 290 +++++++++++++++++++++++++++++++++++++++++++++++
>  include/android_ab.h     |  34 ++++++
>  include/android_bl_msg.h | 169 +++++++++++++++++++++++++++
>  5 files changed, 504 insertions(+)
>  create mode 100644 common/android_ab.c
>  create mode 100644 include/android_ab.h
>  create mode 100644 include/android_bl_msg.h
>

Reviewed-by: Simon Glass <sjg@chromium.org>

Minor comments below, could be addressed later.

> diff --git a/common/Kconfig b/common/Kconfig
> index 0a14bde..fc08e31 100644
> --- a/common/Kconfig
> +++ b/common/Kconfig
> @@ -767,6 +767,16 @@ config UPDATE_TFTP_MSEC_MAX
>         default 100
>         depends on UPDATE_TFTP
>
> +config ANDROID_AB
> +       bool "Android A/B updates"
> +       default n
> +       help
> +         If enabled, adds support for the new Android A/B update model. This
> +         allows the bootloader to select which slot to boot from based on the
> +         information provided by userspace via the Android boot_ctrl HAL. This
> +         allows a bootloader to try a new version of the system but roll back
> +         to previous version if the new one didn't boot all the way.
> +
>  endmenu
>
>  menu "Blob list"
> diff --git a/common/Makefile b/common/Makefile
> index ad390d0..dfa348c 100644
> --- a/common/Makefile
> +++ b/common/Makefile
> @@ -106,6 +106,7 @@ endif
>  endif
>
>  obj-y += image.o
> +obj-$(CONFIG_ANDROID_AB) += android_ab.o
>  obj-$(CONFIG_ANDROID_BOOT_IMAGE) += image-android.o
>  obj-$(CONFIG_$(SPL_TPL_)OF_LIBFDT) += image-fdt.o
>  obj-$(CONFIG_$(SPL_TPL_)FIT) += image-fit.o
> diff --git a/common/android_ab.c b/common/android_ab.c
> new file mode 100644
> index 0000000..3a6a52c
> --- /dev/null
> +++ b/common/android_ab.c
> @@ -0,0 +1,290 @@
> +// SPDX-License-Identifier: BSD-2-Clause
> +/*
> + * Copyright (C) 2017 The Android Open Source Project
> + */
> +
> +#include <android_ab.h>
> +#include <android_bl_msg.h>
> +#include <common.h>

Please put common.h first.

> +#include <memalign.h>
> +#include <u-boot/crc.h>
> +
> +/**
> + * Compute the CRC-32 of the bootloader control struct.
> + *
> + * Only the bytes up to the crc32_le field are considered for the CRC-32
> + * calculation.

For function comments please add @abc for arg and @return for return
value in every case.

> + */
> +static uint32_t ab_control_compute_crc(struct andr_bl_control *abc)
> +{
> +       return crc32(0, (void *)abc, offsetof(typeof(*abc), crc32_le));
> +}
> +
> +/**
> + * Initialize andr_bl_control to the default value.
> + *
> + * It allows us to boot all slots in order from the first one. This value
> + * should be used when the bootloader message is corrupted, but not when
> + * a valid message indicates that all slots are unbootable.
> + */
> +static int ab_control_default(struct andr_bl_control *abc)
> +{
> +       int i;
> +       const struct andr_slot_metadata metadata = {
> +               .priority = 15,
> +               .tries_remaining = 7,
> +               .successful_boot = 0,
> +               .verity_corrupted = 0,
> +               .reserved = 0
> +       };
> +
> +       if (!abc)
> +               return -EINVAL;

-EFAULT?

Also, does this actually happen>

> +
> +       memcpy(abc->slot_suffix, "a\0\0\0", 4);
> +       abc->magic = ANDROID_BOOT_CTRL_MAGIC;
> +       abc->version = ANDROID_BOOT_CTRL_VERSION;
> +       abc->nb_slot = ANDROID_NUM_SLOTS;
> +       memset(abc->reserved0, 0, sizeof(abc->reserved0));
> +       for (i = 0; i < abc->nb_slot; ++i)
> +               abc->slot_info[i] = metadata;
> +
> +       memset(abc->reserved1, 0, sizeof(abc->reserved1));
> +       abc->crc32_le = ab_control_compute_crc(abc);
> +
> +       return 0;
> +}
> +
> +/**
> + * Load the boot_control struct from disk into newly allocated memory.
> + *
> + * This function allocates and returns an integer number of disk blocks,
> + * based on the block size of the passed device to help performing a
> + * read-modify-write operation on the boot_control struct.
> + * The boot_control struct offset (2 KiB) must be a multiple of the device
> + * block size, for simplicity.
> + *
> + * @param[in] dev_desc Device where to read the boot_control struct from
> + * @param[in] part_info Partition in 'dev_desc' where to read from, normally
> + *                     the "misc" partition should be used
> + * @param[out] pointer to pointer to andr_bl_control data
> + * @return 0 on success and a negative on error
> + */
> +static int ab_control_create_from_disk(struct blk_desc *dev_desc,
> +                                      const disk_partition_t *part_info,
> +                                      struct andr_bl_control **abc)
> +{
> +       ulong abc_offset, abc_blocks;
> +
> +       abc_offset = offsetof(struct andr_bl_msg_ab, slot_suffix);
> +       if (abc_offset % part_info->blksz) {
> +               printf("ANDROID: Boot control block not block aligned.\n");

These strings bloat the code. Would it be worth changing them to
debug(), or recording a boot failure code somewhere?

> +               return -EINVAL;
> +       }
> +       abc_offset /= part_info->blksz;
> +
> +       abc_blocks = DIV_ROUND_UP(sizeof(struct andr_bl_control),
> +                                 part_info->blksz);
> +       if (abc_offset + abc_blocks > part_info->size) {
> +               printf("ANDROID: boot control partition too small. Need at");
> +               printf(" least %lu blocks but have %lu blocks.\n",
> +                      abc_offset + abc_blocks, part_info->size);
> +               return -EINVAL;
> +       }
> +       *abc = malloc_cache_aligned(abc_blocks * part_info->blksz);
> +       if (!*abc)
> +               return -ENOMEM;
> +
> +       if (blk_dread(dev_desc, part_info->start + abc_offset, abc_blocks,
> +                     *abc) != abc_blocks) {

blk_dread() actually returns an error number, so you should use
IS_ERR_VALUE() to check for error. No, that is not obvious from the
comment for blk_dread() unfortunately (patch welcome) but see struct
blk_ops.

> +               printf("ANDROID: Could not read from boot control partition\n");
> +               free(*abc);
> +               return -EIO;
> +       }
> +
> +       log_debug("ANDROID: Loaded ABC, %lu blocks\n", abc_blocks);
> +
> +       return 0;
> +}
> +
> +/**
> + * Store the loaded boot_control block.
> + *
> + * Store back to the same location it was read from with
> + * ab_control_create_from_misc().
> + *
> + * @param[in] dev_desc Device where we should write the boot_control struct
> + * @param[in] part_info Partition on the 'dev_desc' where to write
> + * @param[in] abc Pointer to the boot control struct and the extra bytes after
> + *                it up to the nearest block boundary
> + * @return 0 on success and a negative on error
> + */
> +static int ab_control_store(struct blk_desc *dev_desc,
> +                           const disk_partition_t *part_info,
> +                           struct andr_bl_control *abc)
> +{
> +       ulong abc_offset, abc_blocks;
> +
> +       abc_offset = offsetof(struct andr_bl_msg_ab, slot_suffix) /
> +                    part_info->blksz;
> +       abc_blocks = DIV_ROUND_UP(sizeof(struct andr_bl_control),
> +                                 part_info->blksz);
> +       if (blk_dwrite(dev_desc, part_info->start + abc_offset, abc_blocks,
> +                      abc) != abc_blocks) {

IS_ERR_VALUE()

> +               printf("ANDROID: Could not write back the misc partition\n");
> +               return -EIO;
> +       }
> +
> +       return 0;
> +}
> +
> +/**
> + * Compare two slots.
> + *
> + * The function determines slot which is should we boot from among the two.
> + *
> + * @param[in] a The first bootable slot metadata
> + * @param[in] b The second bootable slot metadata
> + * @return Negative if the slot "a" is better, positive of the slot "b" is
> + *         better or 0 if they are equally good.
> + */
> +static int ab_compare_slots(const struct andr_slot_metadata *a,
> +                           const struct andr_slot_metadata *b)
> +{
> +       /* Higher priority is better */
> +       if (a->priority != b->priority)
> +               return b->priority - a->priority;
> +
> +       /* Higher successful_boot value is better, in case of same priority */
> +       if (a->successful_boot != b->successful_boot)
> +               return b->successful_boot - a->successful_boot;
> +
> +       /* Higher tries_remaining is better to ensure round-robin */
> +       if (a->tries_remaining != b->tries_remaining)
> +               return b->tries_remaining - a->tries_remaining;
> +
> +       return 0;
> +}
> +
> +int ab_select_slot(struct blk_desc *dev_desc, disk_partition_t *part_info)
> +{
> +       struct andr_bl_control *abc = NULL;
> +       u32 crc32_le;
> +       int slot, i, ret;
> +       bool store_needed = false;
> +       char slot_suffix[4];
> +
> +       ret = ab_control_create_from_disk(dev_desc, part_info, &abc);
> +       if (ret < 0) {
> +               /*
> +                * This condition represents an actual problem with the code or
> +                * the board setup, like an invalid partition information.
> +                * Signal a repair mode and do not try to boot from either slot.
> +                */
> +               return ret;
> +       }
> +
> +       crc32_le = ab_control_compute_crc(abc);
> +       if (abc->crc32_le != crc32_le) {
> +               printf("ANDROID: Invalid CRC-32 (expected %.8x, found %.8x), ",
> +                      crc32_le, abc->crc32_le);
> +               printf("re-initializing A/B metadata.\n");
> +
> +               ret = ab_control_default(abc);
> +               if (ret < 0) {
> +                       free(abc);
> +                       return -ENODATA;
> +               }
> +               store_needed = true;
> +       }
> +
> +       if (abc->magic != ANDROID_BOOT_CTRL_MAGIC) {
> +               printf("ANDROID: Unknown A/B metadata: %.8x\n", abc->magic);
> +               free(abc);
> +               return -ENODATA;
> +       }
> +
> +       if (abc->version > ANDROID_BOOT_CTRL_VERSION) {
> +               printf("ANDROID: Unsupported A/B metadata version: %.8x\n",
> +                      abc->version);
> +               free(abc);
> +               return -ENODATA;
> +       }
> +
> +       /*
> +        * At this point a valid boot control metadata is stored in abc,
> +        * followed by other reserved data in the same block. We select a with
> +        * the higher priority slot that
> +        *  - is not marked as corrupted and
> +        *  - either has tries_remaining > 0 or successful_boot is true.
> +        * If the selected slot has a false successful_boot, we also decrement
> +        * the tries_remaining until it eventually becomes unbootable because
> +        * tries_remaining reaches 0. This mechanism produces a bootloader
> +        * induced rollback, typically right after a failed update.
> +        */
> +
> +       /* Safety check: limit the number of slots. */
> +       if (abc->nb_slot > ARRAY_SIZE(abc->slot_info)) {
> +               abc->nb_slot = ARRAY_SIZE(abc->slot_info);
> +               store_needed = true;
> +       }
> +
> +       slot = -1;
> +       for (i = 0; i < abc->nb_slot; ++i) {
> +               if (abc->slot_info[i].verity_corrupted ||
> +                   !abc->slot_info[i].tries_remaining) {
> +                       log_debug("ANDROID: unbootable slot %d tries: %d, ",
> +                                 i, abc->slot_info[i].tries_remaining);
> +                       log_debug("corrupt: %d\n",
> +                                 abc->slot_info[i].verity_corrupted);
> +                       continue;
> +               }
> +               log_debug("ANDROID: bootable slot %d pri: %d, tries: %d, ",
> +                         i, abc->slot_info[i].priority,
> +                         abc->slot_info[i].tries_remaining);
> +               log_debug("corrupt: %d, successful: %d\n",
> +                         abc->slot_info[i].verity_corrupted,
> +                         abc->slot_info[i].successful_boot);
> +
> +               if (slot < 0 ||
> +                   ab_compare_slots(&abc->slot_info[i],
> +                                    &abc->slot_info[slot]) < 0) {
> +                       slot = i;
> +               }
> +       }
> +
> +       if (slot >= 0 && !abc->slot_info[slot].successful_boot) {
> +               printf("ANDROID: Attempting slot %c, tries remaining %d\n",
> +                      ANDROID_BOOT_SLOT_NAME(slot),
> +                      abc->slot_info[slot].tries_remaining);
> +               abc->slot_info[slot].tries_remaining--;
> +               store_needed = true;
> +       }
> +
> +       if (slot >= 0) {
> +               /*
> +                * Legacy user-space requires this field to be set in the BCB.
> +                * Newer releases load this slot suffix from the command line
> +                * or the device tree.
> +                */
> +               memset(slot_suffix, 0, sizeof(slot_suffix));
> +               slot_suffix[0] = ANDROID_BOOT_SLOT_NAME(slot);
> +               if (memcmp(abc->slot_suffix, slot_suffix,
> +                          sizeof(slot_suffix))) {
> +                       memcpy(abc->slot_suffix, slot_suffix,
> +                              sizeof(slot_suffix));
> +                       store_needed = true;
> +               }
> +       }
> +
> +       if (store_needed) {
> +               abc->crc32_le = ab_control_compute_crc(abc);
> +               ab_control_store(dev_desc, part_info, abc);

Can this fail?

> +       }
> +       free(abc);
> +
> +       if (slot < 0)
> +               return -EINVAL;

I feel this error code is overused - is there another one that would
give more info?

> +
> +       return slot;
> +}
> diff --git a/include/android_ab.h b/include/android_ab.h
> new file mode 100644
> index 0000000..c1b901d
> --- /dev/null
> +++ b/include/android_ab.h
> @@ -0,0 +1,34 @@
> +/* SPDX-License-Identifier: BSD-2-Clause */
> +/*
> + * Copyright (C) 2017 The Android Open Source Project
> + */
> +
> +#ifndef __ANDROID_AB_H
> +#define __ANDROID_AB_H
> +
> +#include <common.h>
> +
> +/* Android standard boot slot names are 'a', 'b', 'c', ... */
> +#define ANDROID_BOOT_SLOT_NAME(slot_num) ('a' + (slot_num))
> +
> +/* Number of slots */
> +#define ANDROID_NUM_SLOTS 2
> +
> +/**
> + * Select the slot where to boot from.
> + *
> + * On Android devices with more than one boot slot (multiple copies of the
> + * kernel and system images) selects which slot should be used to boot from and
> + * registers the boot attempt. This is used in by the new A/B update model where
> + * one slot is updated in the background while running from the other slot. If
> + * the selected slot did not successfully boot in the past, a boot attempt is
> + * registered before returning from this function so it isn't selected
> + * indefinitely.
> + *
> + * @param[in] dev_desc Place to store the device description pointer
> + * @param[in] part_info Place to store the partition information
> + * @return The slot number (>= 0) on success, or a negative on error
> + */
> +int ab_select_slot(struct blk_desc *dev_desc, disk_partition_t *part_info);
> +
> +#endif /* __ANDROID_AB_H */
> diff --git a/include/android_bl_msg.h b/include/android_bl_msg.h
> new file mode 100644
> index 0000000..f37e01a
> --- /dev/null
> +++ b/include/android_bl_msg.h
> @@ -0,0 +1,169 @@
> +/* SPDX-License-Identifier: BSD-2-Clause */
> +/*
> + * This file was taken from the AOSP Project.
> + * Repository: https://android.googlesource.com/platform/bootable/recovery/
> + * File: bootloader_message/include/bootloader_message/bootloader_message.h
> + * Commit: 8b309f6970ab3b7c53cc529c51a2cb44e1c7a7e1
> + *
> + * Copyright (C) 2008 The Android Open Source Project
> + */
> +
> +#ifndef __ANDROID_BL_MSG_H
> +#define __ANDROID_BL_MSG_H
> +
> +/*
> + * compiler.h defines the types that otherwise are included from stdint.h and
> + * stddef.h
> + */
> +#include <compiler.h>
> +#include <linux/sizes.h>

Note if common.h is always included first, these are not needed.

Regards,
Simon
Eugeniu Rosca March 11, 2019, 5:27 p.m. UTC | #3
FWIW, below are some dangling struct name references due to:
 - s/bootloader_message/andr_bl_msg/
 - s/bootloader_message_ab/andr_bl_msg_ab/
 - s/bootloader_control/andr_bl_control/

On Mon, Feb 18, 2019 at 5:25 PM Igor Opaniuk <igor.opaniuk@linaro.org> wrote:
[..]
> + * uncrypt. Move it into struct bootloader_message_ab to avoid the
[..]
> +        * 1184-byte so that the entire bootloader_message struct rounds up
[..]
> + * stays after struct bootloader_message, which should be managed by
[..]
> + * not mandatory, to use 'struct bootloader_control' described below.
[..]
> + * be put in the 'slot_suffix' field of the 'bootloader_message'
[..]
> + * 'bootloader_control' structure to store the A/B metadata, but not

Best regards,
Eugeniu.
Eugeniu Rosca March 18, 2019, 6:04 p.m. UTC | #4
jFYI/FWIW, AOSP U-Boot [1] seems to currently import the bootloader
message header [2] at least twice:
 - as include/android_bl_msg.h via
   https://android.googlesource.com/platform/external/u-boot/+/86a4b492b5db%5E!/
 - as include/android_bootloader_message.h via
   https://android.googlesource.com/platform/external/u-boot/+/c7f85c5f75f9%5E!/

[1] https://android.googlesource.com/platform/external/u-boot
[2] bootable/recovery/bootloader_message/include/bootloader_message/bootloader_message.h

> Best regards,
> Eugeniu.
Eugeniu Rosca March 18, 2019, 8:21 p.m. UTC | #5
I received the following bounce:

> Thank you for your email.
>
> Igor Opaniuk no longer works for Linaro.
>
> If your email is related to Linaro business, please use the Contact
> form (https://www.linaro.org/contact/) if you do not have another
> Linaro email address to use.

I hope this is a glitch? Otherwise, any suggestions how to proceed here?

Thanks,
Eugeniu.
Praneeth Bajjuri March 18, 2019, 9:20 p.m. UTC | #6
Eugeniu,

On 3/18/2019 3:21 PM, Eugeniu Rosca wrote:
> I received the following bounce:
>
>> Thank you for your email.
>>
>> Igor Opaniuk no longer works for Linaro.
>>
>> If your email is related to Linaro business, please use the Contact
>> form (https://www.linaro.org/contact/) if you do not have another
>> Linaro email address to use.
> I hope this is a glitch? Otherwise, any suggestions how to proceed here?


Not a glitch, Igor's linaro email id is no longer active. He might 
respond with updated email
address soon.


>
> Thanks,
> Eugeniu.
Eugeniu Rosca March 19, 2019, 10:13 a.m. UTC | #7
Hi Praneeth, Igor,

On Mon, Mar 18, 2019 at 04:20:16PM -0500, Bajjuri, Praneeth wrote:
> Eugeniu,
[..]
> Not a glitch, Igor's linaro email id is no longer active. He might respond
> with updated email
> address soon.

Great news. Looking forward for v4 of this series.

Many thanks,
Eugeniu.
Igor Opaniuk March 21, 2019, 3:39 p.m. UTC | #8
Hi Eugeniu,

On Fri, Mar 8, 2019 at 7:29 PM Eugeniu Rosca <roscaeugeniu@gmail.com> wrote:
>
> Hello Igor,
>
> Thanks for the series. Some questions below.
>
> First, my understanding is that the patches replace the deprecated
> libavb_ab and make it trully obsolete, i.e. there should be no need to
> import libavb_ab into U-Boot (unlike some of our suppliers still do).
> Can you please confirm?

That's correct. Currently there is no any integration with AVB yet,
but it's planned to be the next step when these patches are merged.

>
> On Mon, Feb 18, 2019 at 5:25 PM Igor Opaniuk <igor.opaniuk@linaro.org> wrote:
> >
> [..]
>
> > diff --git a/include/android_bl_msg.h b/include/android_bl_msg.h
> > new file mode 100644
> > index 0000000..f37e01a
> > --- /dev/null
> > +++ b/include/android_bl_msg.h
> > @@ -0,0 +1,169 @@
> > +/* SPDX-License-Identifier: BSD-2-Clause */
> > +/*
> > + * This file was taken from the AOSP Project.
> > + * Repository: https://android.googlesource.com/platform/bootable/recovery/
> > + * File: bootloader_message/include/bootloader_message/bootloader_message.h
>
> I won't object on it and it's not my purpose to do any
> teaching/mentoring, but I think it makes sense to decouple (i.e.
> allocate standalone commits for) these two activities:
>  - integration of external headers/libraries (e.g. libavb, dtc,
> headers imported from linux/avb/recovery/etc trees)
>  - in-tree U-Boot development around those headers/libraries
>
> I think mixing these two activities creates more overhead for the
> reviewers, so it's easy for various mistakes to slip in unnoticed. See
> next comment as example.
>
> > + * Commit: 8b309f6970ab3b7c53cc529c51a2cb44e1c7a7e1
>
> The contents of out-of-tree "bootloader_message.h" at this commit
> doesn't appear to contain any "Omaha" references:
> https://android.googlesource.com/platform/bootable/recovery.git/+/8b309f6970ab3b/bootloader_message/include/bootloader_message/bootloader_message.h
>
> The addition of "Omaha" comment is done in commit:
> $ git log --oneline -G Omaha  8b309f6970ab..recovery/master --
> bootloader_message/include/bootloader_message/bootloader_message.h
> 7191bf049216 Add update_channel field to bootloader_message_ab.
>
> So, I believe there is a mismatch between the contents of the newly
> created file and its documented version.

Totally agree. These patch-series were initially introduced (v1 and
v2) by Ruslan (who was actually the main author),
so unfortunately I'm barely aware why in these particular commit both
external headers/libraries and in-tree U-boot stuff are mixed.
Will be fixed in v4.

>
> [..]
>
> > +       u8 priority : 4;
> > +       /* Number of times left attempting to boot this slot */
> > +       u8 tries_remaining : 3;
> > +       /* 1 if this slot has booted successfully, 0 otherwise */
> > +       u8 successful_boot : 1;
>
> The s/uint8_t/u8/ and s/uint32_t/u32/ conversion creates noise
> comparing the in-tree versus out-of-tree files and will add some
> overhead during integration. I still see a lot of U-Boot code saying
> uint8_t/uint32_t, so I wonder if these can be preserved. BTW, some of
> the patches from this series add code using uint32_t.

Agree.

>
> Looking forward to pick the patches from mainline!
>
> Thanks and best regards,
> Eugeniu.
> _______________________________________________
> U-Boot mailing list
> U-Boot@lists.denx.de
> https://lists.denx.de/listinfo/u-boot

Thanks for the review!
Eugeniu Rosca March 28, 2019, 4:30 p.m. UTC | #9
Hello Igor, All,

On Thu, Mar 21, 2019 at 05:39:36PM +0200, Igor Opaniuk wrote:
> Hi Eugeniu,
> 
> On Fri, Mar 8, 2019 at 7:29 PM Eugeniu Rosca <roscaeugeniu@gmail.com> wrote:
[..]
> >
> > The s/uint8_t/u8/ and s/uint32_t/u32/ conversion creates noise
> > comparing the in-tree versus out-of-tree files and will add some
> > overhead during integration. I still see a lot of U-Boot code saying
> > uint8_t/uint32_t, so I wonder if these can be preserved. BTW, some of
> > the patches from this series add code using uint32_t.
> 
> Agree.

Igor, many thanks for the recent replies.

WRT preserving the contents of the original bootloader_message.h from
https://android.googlesource.com/platform/bootable/recovery.git/ , I
wonder what's the chance of keeping the CPP comments in place when
importing the file in-tree, since it will make the diffs and subsequent
integration/updates easier from the source repository. Furthermore, we
don't expect any U-Boot specific development to be done in this file
in-tree. It should purely reflect the upstream state.

I wonder if there is any official position regarding that from the
U-Boot maintainers?

FTR/FWIW, there are around 24 .c/.h files in U-Boot master, carrying CPP
comments (SDPX identifiers carefully excluded):

$ git grep "^\s*//\s" -- "*.c" "*.h" | grep -v "SPDX" | awk '{print $1}' | sort -u | cut -d ':' -f 1
arch/arm/mach-tegra/board2.c
arch/riscv/include/asm/encoding.h
arch/xtensa/include/asm/arch-dc233c/tie-asm.h
arch/xtensa/include/asm/arch-de212/tie-asm.h
board/freescale/lx2160a/eth_lx2160aqds.c
board/renesas/blanche/qos.c
board/xilinx/zynq/zynq-microzed/ps7_init_gpl.c
board/xilinx/zynq/zynq-zc702/ps7_init_gpl.c
board/xilinx/zynq/zynq-zc706/ps7_init_gpl.c
board/xilinx/zynq/zynq-zed/ps7_init_gpl.c
drivers/video/stb_truetype.h
drivers/video/stb_truetype.h
fs/ubifs/ubifs.h
include/efi_api.h
include/linux/mtd/flashchip.h
include/linux/mtd/mtd.h
lib/efi_loader/efi_hii.c
lib/efi_selftest/efi_selftest_crc32.c
lib/efi_selftest/efi_selftest_hii_data.c
lib/libavb/avb_slot_verify.c
scripts/kconfig/expr.c
scripts/kconfig/gconf.c
scripts/kconfig/qconf.h
tools/mingw_support.c

> 
> > Thanks and best regards,
> > Eugeniu.
Tom Rini March 28, 2019, 7:58 p.m. UTC | #10
On Thu, Mar 28, 2019 at 05:30:30PM +0100, Eugeniu Rosca wrote:
> Hello Igor, All,
> 
> On Thu, Mar 21, 2019 at 05:39:36PM +0200, Igor Opaniuk wrote:
> > Hi Eugeniu,
> > 
> > On Fri, Mar 8, 2019 at 7:29 PM Eugeniu Rosca <roscaeugeniu@gmail.com> wrote:
> [..]
> > >
> > > The s/uint8_t/u8/ and s/uint32_t/u32/ conversion creates noise
> > > comparing the in-tree versus out-of-tree files and will add some
> > > overhead during integration. I still see a lot of U-Boot code saying
> > > uint8_t/uint32_t, so I wonder if these can be preserved. BTW, some of
> > > the patches from this series add code using uint32_t.
> > 
> > Agree.
> 
> Igor, many thanks for the recent replies.
> 
> WRT preserving the contents of the original bootloader_message.h from
> https://android.googlesource.com/platform/bootable/recovery.git/ , I
> wonder what's the chance of keeping the CPP comments in place when
> importing the file in-tree, since it will make the diffs and subsequent
> integration/updates easier from the source repository. Furthermore, we
> don't expect any U-Boot specific development to be done in this file
> in-tree. It should purely reflect the upstream state.
> 
> I wonder if there is any official position regarding that from the
> U-Boot maintainers?

Yes, for stuff that we're importing from another place, and really
really aren't touching otherwise, we should avoid changing it.
Eugeniu Rosca March 29, 2019, 8:36 a.m. UTC | #11
Hello,

On Thu, Mar 28, 2019 at 03:58:48PM -0400, Tom Rini wrote:
> On Thu, Mar 28, 2019 at 05:30:30PM +0100, Eugeniu Rosca wrote:
> > Hello Igor, All,
> > 
> > On Thu, Mar 21, 2019 at 05:39:36PM +0200, Igor Opaniuk wrote:
> > > Hi Eugeniu,
> > > 
> > > On Fri, Mar 8, 2019 at 7:29 PM Eugeniu Rosca <roscaeugeniu@gmail.com> wrote:
> > [..]
> > > >
> > > > The s/uint8_t/u8/ and s/uint32_t/u32/ conversion creates noise
> > > > comparing the in-tree versus out-of-tree files and will add some
> > > > overhead during integration. I still see a lot of U-Boot code saying
> > > > uint8_t/uint32_t, so I wonder if these can be preserved. BTW, some of
> > > > the patches from this series add code using uint32_t.
> > > 
> > > Agree.
> > 
> > Igor, many thanks for the recent replies.
> > 
> > WRT preserving the contents of the original bootloader_message.h from
> > https://android.googlesource.com/platform/bootable/recovery.git/ , I
> > wonder what's the chance of keeping the CPP comments in place when
> > importing the file in-tree, since it will make the diffs and subsequent
> > integration/updates easier from the source repository. Furthermore, we
> > don't expect any U-Boot specific development to be done in this file
> > in-tree. It should purely reflect the upstream state.
> > 
> > I wonder if there is any official position regarding that from the
> > U-Boot maintainers?
> 
> Yes, for stuff that we're importing from another place, and really
> really aren't touching otherwise, we should avoid changing it.

Tom, thanks for your prompt feedback.

Igor, unless you have any objections/comments, would you kindly leave
the CPP comments in the next revision of "bootloader_message.h", so
that we minimize the future integration/back-porting efforts?

I would also re-iterate on the need to import the header file in a
standalone commit, since certain users need it for implementing
A/B-unrelated use-cases/features (e.g. accessing A/B-unrelated
fields of the BCB, like boot reason [1]).

[1] https://source.android.com/devices/bootloader/boot-reason

Best regards,
Eugeniu.
diff mbox series

Patch

diff --git a/common/Kconfig b/common/Kconfig
index 0a14bde..fc08e31 100644
--- a/common/Kconfig
+++ b/common/Kconfig
@@ -767,6 +767,16 @@  config UPDATE_TFTP_MSEC_MAX
 	default 100
 	depends on UPDATE_TFTP
 
+config ANDROID_AB
+	bool "Android A/B updates"
+	default n
+	help
+	  If enabled, adds support for the new Android A/B update model. This
+	  allows the bootloader to select which slot to boot from based on the
+	  information provided by userspace via the Android boot_ctrl HAL. This
+	  allows a bootloader to try a new version of the system but roll back
+	  to previous version if the new one didn't boot all the way.
+
 endmenu
 
 menu "Blob list"
diff --git a/common/Makefile b/common/Makefile
index ad390d0..dfa348c 100644
--- a/common/Makefile
+++ b/common/Makefile
@@ -106,6 +106,7 @@  endif
 endif
 
 obj-y += image.o
+obj-$(CONFIG_ANDROID_AB) += android_ab.o
 obj-$(CONFIG_ANDROID_BOOT_IMAGE) += image-android.o
 obj-$(CONFIG_$(SPL_TPL_)OF_LIBFDT) += image-fdt.o
 obj-$(CONFIG_$(SPL_TPL_)FIT) += image-fit.o
diff --git a/common/android_ab.c b/common/android_ab.c
new file mode 100644
index 0000000..3a6a52c
--- /dev/null
+++ b/common/android_ab.c
@@ -0,0 +1,290 @@ 
+// SPDX-License-Identifier: BSD-2-Clause
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ */
+
+#include <android_ab.h>
+#include <android_bl_msg.h>
+#include <common.h>
+#include <memalign.h>
+#include <u-boot/crc.h>
+
+/**
+ * Compute the CRC-32 of the bootloader control struct.
+ *
+ * Only the bytes up to the crc32_le field are considered for the CRC-32
+ * calculation.
+ */
+static uint32_t ab_control_compute_crc(struct andr_bl_control *abc)
+{
+	return crc32(0, (void *)abc, offsetof(typeof(*abc), crc32_le));
+}
+
+/**
+ * Initialize andr_bl_control to the default value.
+ *
+ * It allows us to boot all slots in order from the first one. This value
+ * should be used when the bootloader message is corrupted, but not when
+ * a valid message indicates that all slots are unbootable.
+ */
+static int ab_control_default(struct andr_bl_control *abc)
+{
+	int i;
+	const struct andr_slot_metadata metadata = {
+		.priority = 15,
+		.tries_remaining = 7,
+		.successful_boot = 0,
+		.verity_corrupted = 0,
+		.reserved = 0
+	};
+
+	if (!abc)
+		return -EINVAL;
+
+	memcpy(abc->slot_suffix, "a\0\0\0", 4);
+	abc->magic = ANDROID_BOOT_CTRL_MAGIC;
+	abc->version = ANDROID_BOOT_CTRL_VERSION;
+	abc->nb_slot = ANDROID_NUM_SLOTS;
+	memset(abc->reserved0, 0, sizeof(abc->reserved0));
+	for (i = 0; i < abc->nb_slot; ++i)
+		abc->slot_info[i] = metadata;
+
+	memset(abc->reserved1, 0, sizeof(abc->reserved1));
+	abc->crc32_le = ab_control_compute_crc(abc);
+
+	return 0;
+}
+
+/**
+ * Load the boot_control struct from disk into newly allocated memory.
+ *
+ * This function allocates and returns an integer number of disk blocks,
+ * based on the block size of the passed device to help performing a
+ * read-modify-write operation on the boot_control struct.
+ * The boot_control struct offset (2 KiB) must be a multiple of the device
+ * block size, for simplicity.
+ *
+ * @param[in] dev_desc Device where to read the boot_control struct from
+ * @param[in] part_info Partition in 'dev_desc' where to read from, normally
+ *			the "misc" partition should be used
+ * @param[out] pointer to pointer to andr_bl_control data
+ * @return 0 on success and a negative on error
+ */
+static int ab_control_create_from_disk(struct blk_desc *dev_desc,
+				       const disk_partition_t *part_info,
+				       struct andr_bl_control **abc)
+{
+	ulong abc_offset, abc_blocks;
+
+	abc_offset = offsetof(struct andr_bl_msg_ab, slot_suffix);
+	if (abc_offset % part_info->blksz) {
+		printf("ANDROID: Boot control block not block aligned.\n");
+		return -EINVAL;
+	}
+	abc_offset /= part_info->blksz;
+
+	abc_blocks = DIV_ROUND_UP(sizeof(struct andr_bl_control),
+				  part_info->blksz);
+	if (abc_offset + abc_blocks > part_info->size) {
+		printf("ANDROID: boot control partition too small. Need at");
+		printf(" least %lu blocks but have %lu blocks.\n",
+		       abc_offset + abc_blocks, part_info->size);
+		return -EINVAL;
+	}
+	*abc = malloc_cache_aligned(abc_blocks * part_info->blksz);
+	if (!*abc)
+		return -ENOMEM;
+
+	if (blk_dread(dev_desc, part_info->start + abc_offset, abc_blocks,
+		      *abc) != abc_blocks) {
+		printf("ANDROID: Could not read from boot control partition\n");
+		free(*abc);
+		return -EIO;
+	}
+
+	log_debug("ANDROID: Loaded ABC, %lu blocks\n", abc_blocks);
+
+	return 0;
+}
+
+/**
+ * Store the loaded boot_control block.
+ *
+ * Store back to the same location it was read from with
+ * ab_control_create_from_misc().
+ *
+ * @param[in] dev_desc Device where we should write the boot_control struct
+ * @param[in] part_info Partition on the 'dev_desc' where to write
+ * @param[in] abc Pointer to the boot control struct and the extra bytes after
+ *                it up to the nearest block boundary
+ * @return 0 on success and a negative on error
+ */
+static int ab_control_store(struct blk_desc *dev_desc,
+			    const disk_partition_t *part_info,
+			    struct andr_bl_control *abc)
+{
+	ulong abc_offset, abc_blocks;
+
+	abc_offset = offsetof(struct andr_bl_msg_ab, slot_suffix) /
+		     part_info->blksz;
+	abc_blocks = DIV_ROUND_UP(sizeof(struct andr_bl_control),
+				  part_info->blksz);
+	if (blk_dwrite(dev_desc, part_info->start + abc_offset, abc_blocks,
+		       abc) != abc_blocks) {
+		printf("ANDROID: Could not write back the misc partition\n");
+		return -EIO;
+	}
+
+	return 0;
+}
+
+/**
+ * Compare two slots.
+ *
+ * The function determines slot which is should we boot from among the two.
+ *
+ * @param[in] a The first bootable slot metadata
+ * @param[in] b The second bootable slot metadata
+ * @return Negative if the slot "a" is better, positive of the slot "b" is
+ *         better or 0 if they are equally good.
+ */
+static int ab_compare_slots(const struct andr_slot_metadata *a,
+			    const struct andr_slot_metadata *b)
+{
+	/* Higher priority is better */
+	if (a->priority != b->priority)
+		return b->priority - a->priority;
+
+	/* Higher successful_boot value is better, in case of same priority */
+	if (a->successful_boot != b->successful_boot)
+		return b->successful_boot - a->successful_boot;
+
+	/* Higher tries_remaining is better to ensure round-robin */
+	if (a->tries_remaining != b->tries_remaining)
+		return b->tries_remaining - a->tries_remaining;
+
+	return 0;
+}
+
+int ab_select_slot(struct blk_desc *dev_desc, disk_partition_t *part_info)
+{
+	struct andr_bl_control *abc = NULL;
+	u32 crc32_le;
+	int slot, i, ret;
+	bool store_needed = false;
+	char slot_suffix[4];
+
+	ret = ab_control_create_from_disk(dev_desc, part_info, &abc);
+	if (ret < 0) {
+		/*
+		 * This condition represents an actual problem with the code or
+		 * the board setup, like an invalid partition information.
+		 * Signal a repair mode and do not try to boot from either slot.
+		 */
+		return ret;
+	}
+
+	crc32_le = ab_control_compute_crc(abc);
+	if (abc->crc32_le != crc32_le) {
+		printf("ANDROID: Invalid CRC-32 (expected %.8x, found %.8x), ",
+		       crc32_le, abc->crc32_le);
+		printf("re-initializing A/B metadata.\n");
+
+		ret = ab_control_default(abc);
+		if (ret < 0) {
+			free(abc);
+			return -ENODATA;
+		}
+		store_needed = true;
+	}
+
+	if (abc->magic != ANDROID_BOOT_CTRL_MAGIC) {
+		printf("ANDROID: Unknown A/B metadata: %.8x\n", abc->magic);
+		free(abc);
+		return -ENODATA;
+	}
+
+	if (abc->version > ANDROID_BOOT_CTRL_VERSION) {
+		printf("ANDROID: Unsupported A/B metadata version: %.8x\n",
+		       abc->version);
+		free(abc);
+		return -ENODATA;
+	}
+
+	/*
+	 * At this point a valid boot control metadata is stored in abc,
+	 * followed by other reserved data in the same block. We select a with
+	 * the higher priority slot that
+	 *  - is not marked as corrupted and
+	 *  - either has tries_remaining > 0 or successful_boot is true.
+	 * If the selected slot has a false successful_boot, we also decrement
+	 * the tries_remaining until it eventually becomes unbootable because
+	 * tries_remaining reaches 0. This mechanism produces a bootloader
+	 * induced rollback, typically right after a failed update.
+	 */
+
+	/* Safety check: limit the number of slots. */
+	if (abc->nb_slot > ARRAY_SIZE(abc->slot_info)) {
+		abc->nb_slot = ARRAY_SIZE(abc->slot_info);
+		store_needed = true;
+	}
+
+	slot = -1;
+	for (i = 0; i < abc->nb_slot; ++i) {
+		if (abc->slot_info[i].verity_corrupted ||
+		    !abc->slot_info[i].tries_remaining) {
+			log_debug("ANDROID: unbootable slot %d tries: %d, ",
+				  i, abc->slot_info[i].tries_remaining);
+			log_debug("corrupt: %d\n",
+				  abc->slot_info[i].verity_corrupted);
+			continue;
+		}
+		log_debug("ANDROID: bootable slot %d pri: %d, tries: %d, ",
+			  i, abc->slot_info[i].priority,
+			  abc->slot_info[i].tries_remaining);
+		log_debug("corrupt: %d, successful: %d\n",
+			  abc->slot_info[i].verity_corrupted,
+			  abc->slot_info[i].successful_boot);
+
+		if (slot < 0 ||
+		    ab_compare_slots(&abc->slot_info[i],
+				     &abc->slot_info[slot]) < 0) {
+			slot = i;
+		}
+	}
+
+	if (slot >= 0 && !abc->slot_info[slot].successful_boot) {
+		printf("ANDROID: Attempting slot %c, tries remaining %d\n",
+		       ANDROID_BOOT_SLOT_NAME(slot),
+		       abc->slot_info[slot].tries_remaining);
+		abc->slot_info[slot].tries_remaining--;
+		store_needed = true;
+	}
+
+	if (slot >= 0) {
+		/*
+		 * Legacy user-space requires this field to be set in the BCB.
+		 * Newer releases load this slot suffix from the command line
+		 * or the device tree.
+		 */
+		memset(slot_suffix, 0, sizeof(slot_suffix));
+		slot_suffix[0] = ANDROID_BOOT_SLOT_NAME(slot);
+		if (memcmp(abc->slot_suffix, slot_suffix,
+			   sizeof(slot_suffix))) {
+			memcpy(abc->slot_suffix, slot_suffix,
+			       sizeof(slot_suffix));
+			store_needed = true;
+		}
+	}
+
+	if (store_needed) {
+		abc->crc32_le = ab_control_compute_crc(abc);
+		ab_control_store(dev_desc, part_info, abc);
+	}
+	free(abc);
+
+	if (slot < 0)
+		return -EINVAL;
+
+	return slot;
+}
diff --git a/include/android_ab.h b/include/android_ab.h
new file mode 100644
index 0000000..c1b901d
--- /dev/null
+++ b/include/android_ab.h
@@ -0,0 +1,34 @@ 
+/* SPDX-License-Identifier: BSD-2-Clause */
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ */
+
+#ifndef __ANDROID_AB_H
+#define __ANDROID_AB_H
+
+#include <common.h>
+
+/* Android standard boot slot names are 'a', 'b', 'c', ... */
+#define ANDROID_BOOT_SLOT_NAME(slot_num) ('a' + (slot_num))
+
+/* Number of slots */
+#define ANDROID_NUM_SLOTS 2
+
+/**
+ * Select the slot where to boot from.
+ *
+ * On Android devices with more than one boot slot (multiple copies of the
+ * kernel and system images) selects which slot should be used to boot from and
+ * registers the boot attempt. This is used in by the new A/B update model where
+ * one slot is updated in the background while running from the other slot. If
+ * the selected slot did not successfully boot in the past, a boot attempt is
+ * registered before returning from this function so it isn't selected
+ * indefinitely.
+ *
+ * @param[in] dev_desc Place to store the device description pointer
+ * @param[in] part_info Place to store the partition information
+ * @return The slot number (>= 0) on success, or a negative on error
+ */
+int ab_select_slot(struct blk_desc *dev_desc, disk_partition_t *part_info);
+
+#endif /* __ANDROID_AB_H */
diff --git a/include/android_bl_msg.h b/include/android_bl_msg.h
new file mode 100644
index 0000000..f37e01a
--- /dev/null
+++ b/include/android_bl_msg.h
@@ -0,0 +1,169 @@ 
+/* SPDX-License-Identifier: BSD-2-Clause */
+/*
+ * This file was taken from the AOSP Project.
+ * Repository: https://android.googlesource.com/platform/bootable/recovery/
+ * File: bootloader_message/include/bootloader_message/bootloader_message.h
+ * Commit: 8b309f6970ab3b7c53cc529c51a2cb44e1c7a7e1
+ *
+ * Copyright (C) 2008 The Android Open Source Project
+ */
+
+#ifndef __ANDROID_BL_MSG_H
+#define __ANDROID_BL_MSG_H
+
+/*
+ * compiler.h defines the types that otherwise are included from stdint.h and
+ * stddef.h
+ */
+#include <compiler.h>
+#include <linux/sizes.h>
+
+/*
+ * Spaces used by misc partition are as below:
+ * 0   - 2K     Bootloader Message
+ * 2K  - 16K    Used by Vendor's bootloader (the 2K - 4K range may be optionally
+ *              used as bootloader_message_ab struct)
+ * 16K - 64K    Used by uncrypt and recovery to store wipe_package for A/B
+ *              devices
+ * Note that these offsets are admitted by bootloader, recovery and uncrypt, so
+ * they are not configurable without changing all of them.
+ */
+#define ANDROID_MISC_BM_OFFSET		0
+#define ANDROID_MISC_WIPE_OFFSET	SZ_16K
+
+/**
+ * Bootloader Message (2-KiB).
+ *
+ * This structure describes the content of a block in flash
+ * that is used for recovery and the bootloader to talk to
+ * each other.
+ *
+ * The command field is updated by linux when it wants to
+ * reboot into recovery or to update radio or bootloader firmware.
+ * It is also updated by the bootloader when firmware update
+ * is complete (to boot into recovery for any final cleanup)
+ *
+ * The status field is written by the bootloader after the
+ * completion of an "update-radio" or "update-hboot" command.
+ *
+ * The recovery field is only written by linux and used
+ * for the system to send a message to recovery or the
+ * other way around.
+ *
+ * The stage field is written by packages which restart themselves
+ * multiple times, so that the UI can reflect which invocation of the
+ * package it is.  If the value is of the format "#/#" (eg, "1/3"),
+ * the UI will add a simple indicator of that status.
+ *
+ * We used to have slot_suffix field for A/B boot control metadata in
+ * this struct, which gets unintentionally cleared by recovery or
+ * uncrypt. Move it into struct bootloader_message_ab to avoid the
+ * issue.
+ */
+struct andr_bl_msg {
+	char command[32];
+	char status[32];
+	char recovery[768];
+
+	/*
+	 * The 'recovery' field used to be 1024 bytes.  It has only ever
+	 * been used to store the recovery command line, so 768 bytes
+	 * should be plenty.  We carve off the last 256 bytes to store the
+	 * stage string (for multistage packages) and possible future
+	 * expansion.
+	 */
+	char stage[32];
+
+	/*
+	 * The 'reserved' field used to be 224 bytes when it was initially
+	 * carved off from the 1024-byte recovery field. Bump it up to
+	 * 1184-byte so that the entire bootloader_message struct rounds up
+	 * to 2048-byte.
+	 */
+	char reserved[1184];
+};
+
+/**
+ * The A/B-specific bootloader message structure (4-KiB).
+ *
+ * We separate A/B boot control metadata from the regular bootloader
+ * message struct and keep it here. Everything that's A/B-specific
+ * stays after struct bootloader_message, which should be managed by
+ * the A/B-bootloader or boot control HAL.
+ *
+ * The slot_suffix field is used for A/B implementations where the
+ * bootloader does not set the androidboot.ro.boot.slot_suffix kernel
+ * commandline parameter. This is used by fs_mgr to mount /system and
+ * other partitions with the slotselect flag set in fstab. A/B
+ * implementations are free to use all 32 bytes and may store private
+ * data past the first NUL-byte in this field. It is encouraged, but
+ * not mandatory, to use 'struct bootloader_control' described below.
+ *
+ * The update_channel field is used to store the Omaha update channel
+ * if update_engine is compiled with Omaha support.
+ */
+struct andr_bl_msg_ab {
+	struct andr_bl_msg message;
+	char slot_suffix[32];
+	char update_channel[128];
+
+	/* Round up the entire struct to 4096-byte */
+	char reserved[1888];
+};
+
+#define ANDROID_BOOT_CTRL_MAGIC   0x42414342 /* Bootloader Control AB */
+#define ANDROID_BOOT_CTRL_VERSION 1
+
+struct andr_slot_metadata {
+	/*
+	 * Slot priority with 15 meaning highest priority, 1 lowest
+	 * priority and 0 the slot is unbootable
+	 */
+	u8 priority : 4;
+	/* Number of times left attempting to boot this slot */
+	u8 tries_remaining : 3;
+	/* 1 if this slot has booted successfully, 0 otherwise */
+	u8 successful_boot : 1;
+	/*
+	 * 1 if this slot is corrupted from a dm-verity corruption,
+	 * 0 otherwise
+	 */
+	u8 verity_corrupted : 1;
+	/* Reserved for further use */
+	u8 reserved : 7;
+} __packed;
+
+/**
+ * Bootloader Control AB.
+ *
+ * This struct can be used to manage A/B metadata. It is designed to
+ * be put in the 'slot_suffix' field of the 'bootloader_message'
+ * structure described above. It is encouraged to use the
+ * 'bootloader_control' structure to store the A/B metadata, but not
+ * mandatory.
+ */
+struct andr_bl_control {
+	/* NULL terminated active slot suffix */
+	char slot_suffix[4];
+	/* Bootloader Control AB magic number (see BOOT_CTRL_MAGIC) */
+	u32 magic;
+	/* Version of struct being used (see BOOT_CTRL_VERSION) */
+	u8 version;
+	/* Number of slots being managed */
+	u8 nb_slot : 3;
+	/* Number of times left attempting to boot recovery */
+	u8 recovery_tries_remaining : 3;
+	/* Ensure 4-bytes alignment for slot_info field */
+	u8 reserved0[2];
+	/* Per-slot information. Up to 4 slots */
+	struct andr_slot_metadata slot_info[4];
+	/* Reserved for further use */
+	u8 reserved1[8];
+	/*
+	 * CRC32 of all 28 bytes preceding this field (little endian
+	 * format)
+	 */
+	u32 crc32_le;
+} __packed;
+
+#endif  /* __ANDROID_BL_MSG_H */