// SPDX-License-Identifier: BSD-2-Clause
/*
 * Copyright (C) 2017 The Android Open Source Project
 */
#include <android_ab.h>
#include <android_bootloader_message.h>
#include <log.h>
#include <string.h>
#include <errno.h>
#ifndef ENODATA
#define ENODATA 61
#endif
#include <crc.h>

#include <dma.h>
#include <mem_io.h>
#include <rpc.h>
#include <rpcqspidrv.h>
#include <spiflash2drv.h>
#include <image_load_flash.h>
typedef unsigned long int	ulong;
typedef uint32_t	u32;
#define typeof(x)	__typeof__(x)
#define DIV_ROUND_UP(n,d)	(((n) + (d) - 1) / (d))
#define ARRAY_SIZE(x)		(sizeof(x) / sizeof((x)[0]))

#define QSPI_MISC_START		(FLASH_BASE + 0x00740000U)
#define QSPI_AB_OFFSET		(2048)
#define QSPI_AB_CONTROL		(QSPI_MISC_START + QSPI_AB_OFFSET)
#define QSPI_AB_SIZE		(1024U)

#include <remap.h>
#undef DISK_BUFFER_ADDR
#define DISK_BUFFER_ADDR	(BASE_RTSRAM_ADDR + (0x0002E000U))	// 0xEB22E000U
volatile uint8_t *_disk_buffer = 0;
#undef AB_INFO_FLAG_ADDR
#define AB_INFO_FLAG_ADDR	(BASE_RTSRAM_ADDR + (0x0002FFFCU))	// 0xEB22FFFCU
#define TMP_BUFFER_ADDR		(BASE_RTSRAM_ADDR + (0x0002D000U))	// 0xEB22D000U

/**
 * 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.
 *
 * @param[in] abc bootloader control block
 *
 * @return crc32 sum
 */
static uint32_t ab_control_compute_crc(struct bootloader_control *abc)
{
	return crc32(0, (void *)abc, offsetof(typeof(*abc), crc32_le));
}

/**
 * Initialize bootloader_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.
 *
 * @param[in] abc bootloader control block
 *
 * @return 0 on success and a negative on error
 */
static int ab_control_default(struct bootloader_control *abc)
{
	int i;
	const struct slot_metadata metadata = {
		.priority = 15,
		.tries_remaining = 7,
		.successful_boot = 0,
		.verity_corrupted = 0,
		.reserved = 0
	};

	if (!abc)
		return -EFAULT;

	memcpy(abc->slot_suffix, "a\0\0\0", 4);
	abc->magic = BOOT_CTRL_MAGIC;
	abc->version = BOOT_CTRL_VERSION;
	abc->nb_slot = 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[out] pointer to pointer to bootloader_control data
 * @return 0 on success and a negative on error
 */
static int ab_control_create_from_disk(struct bootloader_control **abc)
{
	uint32_t phys_dst = remap_get_phys_addr(DISK_BUFFER_ADDR);	// 0xEB22E000U
	uint32_t phys_src = QSPI_AB_CONTROL;
	uint32_t size     = QSPI_AB_SIZE;

	/* Load content */
	dma_trans_start(phys_dst, phys_src, size);

	/* End loading */
	load_end();

	*abc = (struct bootloader_control *)_disk_buffer;
	return 0;
}

/**
 * Store the loaded boot_control block.
 *
 * Store back to the same location it was read from with
 * ab_control_create_from_misc().
 *
 * @return 0 on success and a negative on error
 */
static int ab_control_store(struct bootloader_control *abc)
{
	uint32_t phys_dst = QSPI_AB_CONTROL;
	uint32_t phys_src = remap_get_phys_addr((uint32_t)abc);
	uint32_t size = sizeof(struct bootloader_control);

	init_rpc_qspi_flash();
	qspi_flash_rw_init();
	NOTICE("we're storing bootloader control block.(%d)\n", size);

	phys_dst -= FLASH_BASE;

	/* Sector Erase */
	sector_erase_qspi_flash(phys_dst, phys_dst + 4096 - 1);

	clear_bp_qspi_flash();
	save_data_with_buf_qspi_flash(phys_src, phys_dst, size);

	/* set read mode, it's slower than before */
	init_rpc_qspi_flash_4fastread_ext_mode();
	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 slot_metadata *a,
			    const struct 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(void)
{
	struct bootloader_control *abc = NULL;
	u32 crc32_le;
	int slot, i, ret;
	bool store_needed = false;
	char slot_suffix[4];
	// uint32_t ab_info_addr = remap_get_phys_addr(AB_INFO_FLAG_ADDR);	// 0xEB22FFFCU

	_disk_buffer = (uint8_t *)(DISK_BUFFER_ADDR);	// 0xEB22E000U
	mem_write32(AB_INFO_FLAG_ADDR, AB_INFO_FLAG_INIT);
	ret = ab_control_create_from_disk(&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) {
		ERROR("Invalid CRC-32 (expected %.8x, found %.8x),"
				"re-initializing A/B metadata.\n", crc32_le, abc->crc32_le);

		ret = ab_control_default(abc);
		if (ret < 0) {
			// free(abc);
			return -ENODATA;
		}
		store_needed = true;
	}

	if (abc->magic != BOOT_CTRL_MAGIC) {
		ERROR("Unknown A/B metadata: %.8x\n", abc->magic);
		// free(abc);
		return -ENODATA;
	}

	if (abc->version > BOOT_CTRL_VERSION) {
		ERROR("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);
		NOTICE("[%s:%d] abc->nb_slot > ARRAY_SIZE(abc->slot_info)\n", __func__, __LINE__);
		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) {
			NOTICE("unbootable slot %d tries: %d, corrupt: %d\n",
				  i, abc->slot_info[i].tries_remaining,
				  abc->slot_info[i].verity_corrupted);
			continue;
		}
		NOTICE("bootable slot %d pri: %d, tries: %d, "
				"corrupt: %d, successful: %d\n",
			  i, abc->slot_info[i].priority,
			  abc->slot_info[i].tries_remaining,
			  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) {
		ERROR("Attempting slot %d, tries remaining %d\n",
			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] = BOOT_SLOT_NAME(slot);
		if (memcmp(abc->slot_suffix, slot_suffix, sizeof(slot_suffix))) {
			NOTICE("slot_suffix is differ(%s:%s)\n",
				abc->slot_suffix, 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(abc);
		crc32_le = AB_INFO_FLAG_STORE;
	}
	else
		crc32_le = AB_INFO_FLAG_OK;
	// free(abc);

	if (slot == 1)
		crc32_le |= AB_INFO_SELECT_2nd;
	mem_write32(AB_INFO_FLAG_ADDR, crc32_le);

	if (slot < 0)
		return -EINVAL;

	return slot;
}
