/* SPDX-FileCopyrightText: 2024 Google LLC */
/* SPDX-License-Identifier: Apache-2.0 */

#pragma once

#define SECTOR_SIZE_BYTES 0x20000
#define SECTOR_ADDR_MASK (~(SECTOR_SIZE_BYTES - 1))

#define FLASH_FILESYSTEM_BLOCK_SIZE 0x2000

#define SUBSECTOR_SIZE_BYTES 0x20000
#define SUBSECTOR_ADDR_MASK (~(SUBSECTOR_SIZE_BYTES - 1))

// FMC_BANK_1_BASE_ADDRESS
#define FLASH_MEMORY_MAPPABLE_ADDRESS 0x60000000
#define FLASH_MEMORY_MAPPABLE_SIZE BOARD_NOR_FLASH_SIZE

// Filesystem layout
///////////////////////////////////////

// Space for our flash logs
// NOTE: This range of memory is actually in the special "bottom boot" area of our flash chip
// where the erase sectors are smaller (32k instead of 128k everywhere else).
#define FLASH_REGION_DEBUG_DB_BEGIN 0x0
#define FLASH_REGION_DEBUG_DB_END   0x20000 // 128k
#define FLASH_DEBUG_DB_BLOCK_SIZE   BOTTOM_BOOT_SECTOR_SIZE

#define BOTTOM_BOOT_REGION_END 0x20000 // 128k
#define BOTTOM_BOOT_SECTOR_SIZE 0x8000 // 32k

// Regions after this point are in standard, 128kb sized sectors.

// 640kb gap here. We should save some space for non-filesystem things. It also aligns the
// subsequent sectors nicely.

// 1 128kb sector for storing bluetooth parings which are shared between normal fw and prf
#define FLASH_REGION_SHARED_PRF_STORAGE_BEGIN 0x0C0000
#define FLASH_REGION_SHARED_PRF_STORAGE_END   0x0E0000

// 1 128kb sector for storing mfg info, see fw/mfg/snowy/mfg_info.c
#define FLASH_REGION_MFG_INFO_BEGIN 0x0E0000
#define FLASH_REGION_MFG_INFO_END   0x100000

// Scratch space for firmware images (normal and recovery).
#define FLASH_REGION_FIRMWARE_SLOT_1_BEGIN 0x100000
#define FLASH_REGION_FIRMWARE_SLOT_1_END   0x200000 // 1024k

#define FLASH_REGION_SAFE_FIRMWARE_BEGIN 0x200000
#define FLASH_REGION_SAFE_FIRMWARE_END   0x300000 // 1024k

#define FLASH_REGION_SYSTEM_RESOURCES_BANK_0_BEGIN 0x300000
#define FLASH_REGION_SYSTEM_RESOURCES_BANK_0_END   0x380000 // 512k

#define FLASH_REGION_SYSTEM_RESOURCES_BANK_1_BEGIN 0x380000
#define FLASH_REGION_SYSTEM_RESOURCES_BANK_1_END   0x400000 // 512k

#define FLASH_REGION_FILESYSTEM_BEGIN 0x0400000
#define FLASH_REGION_FILESYSTEM_END   0x1000000 // 8mb+, aka the rest!

// Constants used for testing flash interface
// NOTE: This purposely overlaps the file system region since the flash test requires a non-critical
// region to operate on. Data in this region will get corrupted and will not get restored after the
// test runs. Any data in this region will have to be manually restored or reinitialized.
#define FLASH_TEST_ADDR_START 0x0800000 // 8MB
#define FLASH_TEST_ADDR_END   0x1000000 // 16MB
#define FLASH_TEST_ADDR_MSK   0x1FFFFFF // test all bits in the 16MB range

#define BOARD_NOR_FLASH_SIZE  0x1000000

#if ((FLASH_REGION_FILESYSTEM_BEGIN > FLASH_TEST_ADDR_START) || (FLASH_REGION_FILESYSTEM_END < FLASH_TEST_ADDR_END))
#error "ERROR: Flash Test space not withing expected range"
#endif

// 0x1000000 is the end of the SPI flash address space.

