/*
 * Init and Configure partitions seen by the Circular Storage Service.
 */
static void circular_storage_service_init(int id, void *queue)
{
	uint16_t flash_id = 0;
	int16_t partition_index = -1;
	flash_device_t flash;
	uint32_t i = 0;
	uint32_t j = 0;
	uint16_t partition_id;
	uint32_t first_block = 0;
	uint32_t block_count = 0;
	uint32_t elt_size = 0;

	/* for each storage configuration */
	for (i = 0; i < cir_storage_config.cir_storage_count; i++) {
		partition_id =
			cir_storage_config.cir_storage_list[i].partition_id;
		first_block =
			cir_storage_config.cir_storage_list[i].first_block;
		block_count =
			cir_storage_config.cir_storage_list[i].block_count;
		elt_size = cir_storage_config.cir_storage_list[i].element_size;
		/* Check storage configuration is valid */
		for (j = 0; j < cir_storage_config.no_part; j++) {
			if (cir_storage_config.partitions[j].partition_id ==
			    partition_id) {
				flash_id =
					cir_storage_config.partitions[j].
					flash_id;
				partition_index = j;
				break;
			}
		}
		assert(partition_index != -1);
		extern const flash_device_t flash_devices[];
		flash = flash_devices[flash_id];

		assert(flash.flash_location == SERIAL_FLASH);
		/* Initialise the configuration */
		cir_storage_config.cir_storage_list[i].storage =
			(void *)cir_storage_flash_spi_init(elt_size,
							   first_block,
							   block_count);
	}

	cfw_register_service(queue, &circular_storage_service, handle_message,
			     NULL);
}
void handle_cir_stor_init(struct cfw_message *msg)
{
	ll_storage_cir_stor_init_req_msg_t * req = (ll_storage_cir_stor_init_req_msg_t *) msg;
	ll_storage_cir_stor_init_rsp_msg_t * resp =
		(ll_storage_cir_stor_init_rsp_msg_t *) cfw_alloc_rsp_msg(msg,
		MSG_ID_LL_CIR_STOR_INIT_RSP, sizeof(*resp));
	DRIVER_API_RC ret = DRV_RC_FAIL;
	uint16_t flash_id = 0;
	int16_t partition_index = -1;
	uint32_t i = 0;
	flash_device_t flash;

	if (req->size == 0) {
		pr_debug(LOG_MODULE_MAIN, "LL Storage Service - Cir stor init: Invalid size");
		ret = DRV_RC_FAIL;
		goto send;
	}

	for (i = 0; i < ll_storage_config.no_part; i++) {
		if (ll_storage_config.partitions[i].partition_id == req->partition_id) {
			flash_id = ll_storage_config.partitions[i].flash_id;
			partition_index = i;
			break;
		}
	}

	if (partition_index == -1) {
		pr_debug(LOG_MODULE_MAIN, "LL Storage Service - Cir stor init: Invalid partition ID");
		ret = DRV_RC_FAIL;
		goto send;
	}
	flash = flash_devices[flash_id];

	if (flash.flash_location == SERIAL_FLASH) {
		resp->storage = (void *)cir_storage_flash_spi_init(req->size, req->block_start);
		if (resp->storage != NULL) {
			ret = DRV_RC_OK;
		} else {
			pr_debug(LOG_MODULE_MAIN, "LL Storage Service - Cir stor init: Flash SPI init failed");
			ret = DRV_RC_FAIL;
		}
	}

send:
	resp->rsp_header.status = ret;
	cfw_send_message(resp);
}