diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 0000000..a078858 --- /dev/null +++ b/Jenkinsfile @@ -0,0 +1,2 @@ +@Library('automated-testing-library') _ +pipelineSoftIPExamples() diff --git a/README.md b/README.md new file mode 100644 index 0000000..7e59600 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# README diff --git a/bootloaders/README.md b/bootloaders/README.md new file mode 100644 index 0000000..52da238 --- /dev/null +++ b/bootloaders/README.md @@ -0,0 +1 @@ +# README \ No newline at end of file diff --git a/bootloaders/miv-rv32-bootloader/.cproject b/bootloaders/miv-rv32-bootloader/.cproject new file mode 100644 index 0000000..5534074 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/.cproject @@ -0,0 +1,558 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bootloaders/miv-rv32-bootloader/.gitignore b/bootloaders/miv-rv32-bootloader/.gitignore new file mode 100644 index 0000000..d4d17e3 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/.gitignore @@ -0,0 +1,5 @@ +/*Debug*/ +/*Release*/ +/.settings*/ + +/Bootstrap/ diff --git a/bootloaders/miv-rv32-bootloader/.project b/bootloaders/miv-rv32-bootloader/.project new file mode 100644 index 0000000..9177863 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/.project @@ -0,0 +1,26 @@ + + + miv-rv32-bootloader + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/bootloaders/miv-rv32-bootloader/README.md b/bootloaders/miv-rv32-bootloader/README.md new file mode 100644 index 0000000..ea5cb4f --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/README.md @@ -0,0 +1,78 @@ + +# Mi-V Bootloader firmware + + This project allows you to write application executable into the SPI flash or + the I2C EEPROM. + The executable is expected to be preloaded in the LSRAM memory using the Libero + memory client configurator. + + Writing to the SPI flash is tested on PolarFire Eval Kit on-board SPI flash. + Writing to the EEPROM is tested on PolarFire Avalanche kit with MikroBus Dual + EE kit. + +## How to use this example + +This example project requires USB-UART interface to be connected to a host PC. +The host PC must connect to the serial port using a terminal emulator such as +HyperTerminal or PuTTY configured as follows: + - 115200 baud + - 8 data bits + - 1 stop bit + - no parity + - no flow control + +This program displays a self explainatory menu which can be used to perform +different actions. + +### Build configurations +The following build configurations are provided with this project + +| Configuration | Description | +| ----------- | ---------------------- | +| Bootloader-Debug | Run Bootloader in step-debug mode. RV32 IMC extensions. Links to default TCM base address 0x40000000. Not Optimized (-O0). | +| Bootstrap | Used to generate the elf file used by the DGC designs. Links to default TCM base address 0x40000000. Not Optimized (-O0).
For general usage, the *Bootloader-Debug* configuration is recommended| + +The Bootloader-Debug configuration provides additional YMODEM functionality to +download a hex file over UART terminal to the LSRAM at address 0x80000000. It can +then be copied into either the SPI flash or the LSRAM. + +The Bootstrap configuration assumes that the LSRAM is preloaded with the hex +file as a memory client in the Libero design flow as explained in the design guide. If you are using this flow, you may not need the YMODEM functionality. + +## Target hardware +The Libero designs that are compatible with the use cases provided by this example application are listed in the following table. + +| UART Menu option | Design Configuration | Feature | GitHub Repository | +| ----------- | ---------------------- | -------------------------- | -------------------------- | +| Copy to SPI flash | DGC1 | SPI Flash Bootstrap | [PolarFire® Evaluation Kit](https://github.com/Mi-V-Soft-RISC-V/PolarFire-Eval-Kit) | +| Copy to EEPROM | DGC2 | I2C Flash Bootstrap | [PolarFire® Avalanche board](https://github.com/Mi-V-Soft-RISC-V/Future-Avalanche-Board) | +| Download hex file to LSRAM | DGC1 and DGC2 can be used | Download hex file to LSRAM.
Both DGC1 and DGC2 designs boot with a default hex file attached to the LSRAM as a client.
Use this menu to overwrite the LSRAM with a new hex file.| See above | + +Notes: +- MikroBus Dual EE Click board is available from https://www.mikroe.com/dual-ee-click + +All the design specific definitions such as peripheral base addresses, system +clock frequency etc. are included in fpga_design_config.h. + +This example project can be used with another design using a different hardware +configuration. This can be achieved by overwriting the content of this example +project's _fpga_design_config.h_ file with the correct data from your Libero design. + +### Booting the system: + +The boot flow is as below: + - Run this project in step-debug mode from TCM address space + - Download new hex file to LSRAM address space using UART menu option 3. (This step is optional if the LSRAM is preloaded) + - Copy the downloaded hex file to EEPROM or SPI flash per your design using UART menu options 1 and 2 + - For SPI boot on PolarFire Eval Kit: + - Push and hold SW8 and press and release SW6 or SW7. + - For I2C boot on Avalanche board: + - Push and hold SW1 to disable BOOTSTRAP_BYPASS. + - Press and release SW2 to perform a system reset request. + - Release SW1 when the LEDs on the board are actively blinking. + +For more details, Refer **MIV_ESS_DG_50003259A.pdf** provided with MIV_ESS core +via Libero catalog and associate designs at [github Repository](https://github.com/Mi-V-Soft-RISC-V/Future-Avalanche-Board/tree/main/Libero_Projects/import/components/IMC_DGC2). + +## Silicon revision dependencies +This example is tested on PolarFire MPF300T and TS device. diff --git a/bootloaders/miv-rv32-bootloader/miv-rv32-bootloader debug.launch b/bootloaders/miv-rv32-bootloader/miv-rv32-bootloader debug.launch new file mode 100644 index 0000000..e36aad5 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/miv-rv32-bootloader debug.launch @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bootloaders/miv-rv32-bootloader/miv-rv32-bootloader hw debug.launch b/bootloaders/miv-rv32-bootloader/miv-rv32-bootloader hw debug.launch new file mode 100644 index 0000000..3e309cf --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/miv-rv32-bootloader hw debug.launch @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bootloaders/miv-rv32-bootloader/src/application/bootloader/bootloader.c b/bootloaders/miv-rv32-bootloader/src/application/bootloader/bootloader.c new file mode 100644 index 0000000..30de29a --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/application/bootloader/bootloader.c @@ -0,0 +1,929 @@ +/******************************************************************************* + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * Mi-V ESS Bootstrap support firmware. + * This project allows you to write executable into the SPI flash or the I2C + * EEPROM. The executable is expected to be available in the LSRAM memory using + * the Libero memory client configurator. + * + */ +#include +#include "miv_rv32_hal/miv_rv32_hal.h" +#include "drivers/fabric_ip/CoreUARTapb/core_uart_apb.h" +#include "drivers/fabric_ip/miv_i2c/miv_i2c.h" +#include "drivers/off_chip/spi_flash/spi_flash.h" +#include "ymodem/ymodem.h" + +#define FLASH_SECTOR_SIZE 65536 /* flash memory size */ +#define FLASH_SECTORS 128 // There are 126 sectors of 64kB size, using 124 +#define FLASH_BLOCK_SIZE 4096 //Sectors compose of 4kB eraseable blocks +#define FLASH_SEGMENT_SIZE 256 // Write segment size is 256 + +#define FLASH_BLOCK_SEGMENTS (FLASH_BLOCK_SIZE / FLASH_SEGMENT_SIZE) +#define FLASH_BYTE_SIZE (FLASH_SECTOR_SIZE * FLASH_SECTORS) +#define LAST_BLOCK_ADDR (FLASH_BYTE_SIZE - FLASH_BLOCK_SIZE) + +#ifdef __UNUSED_CODE +static int test_flash(void); +static void mem_test(uint8_t *address); +static int read_program_from_flash(uint8_t *read_buf, uint32_t read_byte_length); +static void Bootloader_JumpToApplication(uint32_t stack_location, uint32_t reset_vector); +#endif + +static int write_program_to_i2ceeprom(uint8_t *write_buf, uint32_t file_size); +static int write_program_to_flash(uint8_t *write_buf, uint32_t file_size); +static void copy_hex_to_i2ceeprom(void); +static void copy_hex_to_spiflash(void); +static uint32_t rx_app_file(uint8_t *dest_address); + +static uint8_t file_name[FILE_NAME_LENGTH + 1]; /* +1 for nul */ + +/* + * Base address of LSRAM memory where the program is loaded. + */ +#define LSRAM_BASE_ADDRESS_LOAD 0x80000000 +#define LSRAM_BASE_ADDRESS_WRITE 0x89000000 + +/* + * Key value used to determine if valid data is contained in the SPI flash. + */ +#define SPI_FLASH_VALID_CONTENT_KEY 0xB5006BB1 + +const uint8_t g_bootstrap_choice[] = +"\r\n\r\n\ +================================================================================\r\n\ + MIV_ESS Bootloader \r\n\ +================================================================================\r\n\ +\r\n\ +\r\n\ +This program supports writing HEX data from Source LSRAM (@ Address 0x800000000) into a Non-Volatile memory\r\n\ +\r\n\ +\r\n\ +Choose the destination Non-Volatile memory: \r\n\ + Type 0 to show this menu\r\n\ + Type 1 copy .hex from LSRAM to SPI Flash \r\n\ + Type 2 copy .hex from LSRAM to MikroBus EEPROM \r\n\ + Type 3 Download .hex from the host PC over UART terminal using YMODEM\r\n\ + "; + +/* + * Data structure stored at the beginning of SPI flash to indicate the size of + * data stored inside the SPI flash. This is to avoid having to read the entire + * flash content at boot time. + * This data structure is one flash segment long (256 bytes). + */ +typedef struct +{ + uint32_t validity_key; + uint32_t spi_content_byte_size; + uint32_t dummy[62]; +} flash_content_t; + +/****************************************************************************** + * CoreUARTapb instance data. + *****************************************************************************/ +UART_instance_t g_uart; + + +/****************************************************************************** + * I2C instance data. + *****************************************************************************/ +#define I2C_XFR_DATA_LEN 258u // 2 byte address + 256 bytes data +//#define I2C_XFR_DATA_LEN 16u +uint8_t target_slave_addr = 0x50; +uint8_t i2c_tx_buffer[I2C_XFR_DATA_LEN]; +miv_i2c_instance_t g_miv_i2c_inst; + +//uint8_t i2c_tx_buffer[7] = {0x0A,0x0B,0x0C,0x0A,0x0B,0x0C,0x0A}; +//uint16_t write_length;//DATA_LENGTH; + +volatile uint32_t g_10ms_count; + +const uint8_t g_greeting_msg_spi[] = + " ----> SPI Flash is chosen as destination memory \r\n"; + +const char * g_greeting_msg_i2c = +" ----> I2C EEPROM is chosen as destination memory \r\n"; + +/* + * Maximum UART receiver buffer size. + */ +#define UART_RX_BUF_SIZE 10 + +/* + * Used for bootstrap from SPI FLASH + * The LSRAM max size is 64K. + * Assuming the executable 32k byte. + * Copy the whole 32k chunk from LSRAM to flash. + */ +#define FLASH_EXECUTABLE_SIZE 32768u + +/* MIV I2C interrupt handler */ +void MSYS_EI2_IRQHandler(void) +{ + MIV_I2C_isr (&g_miv_i2c_inst); +} + + +void SysTick_Handler(void) +{ + g_10ms_count += 10; + + /* + * For neatness, if we roll over, reset cleanly back to 0 so the count + * always goes up in proper 10s. + */ + if(g_10ms_count < 10) + g_10ms_count = 0; + +} +/*-------------------------------------------------------------------------*//** + * main() function. + */ +int main() +{ + uint8_t rx_data[UART_RX_BUF_SIZE]; + size_t rx_size; + static uint32_t file_size = 0; + /************************************************************************** + * Initialize CoreUARTapb with its base address, baud value, and line + * configuration. + *************************************************************************/ + UART_init(&g_uart, COREUARTAPB0_BASE_ADDR,\ + BAUD_VALUE_115200, (DATA_8_BITS | NO_PARITY) ); + + /************************************************************************** + * Display greeting message message. + *************************************************************************/ + UART_polled_tx_string(&g_uart, g_bootstrap_choice); + + while (1u) + { + /********************************************************************** + * Read data received by the UART. + *********************************************************************/ + rx_size = UART_get_rx( &g_uart, rx_data, sizeof(rx_data) ); + + /********************************************************************** + * Echo back data received, if any. + *********************************************************************/ + if ( rx_size > 0 ) + { + UART_send( &g_uart, rx_data, rx_size ); + rx_size = 0u; + + switch(rx_data[0]) + { + case '0': + UART_polled_tx_string( &g_uart, g_bootstrap_choice); + break; + case '1': + copy_hex_to_spiflash(); + break; + case '2': + copy_hex_to_i2ceeprom(); + break; + case '3': + file_size = rx_app_file((uint8_t *)LSRAM_BASE_ADDRESS_LOAD); + break; + default: + UART_polled_tx_string( &g_uart, "Invalid selection. Try again...\r\n"); + break; + } + } + } + + return 0; +} + +/* + * Put image received via ymodem into memory + */ +static uint32_t rx_app_file(uint8_t *dest_address) +{ + uint32_t received; + uint8_t *g_bin_base = (uint8_t *)dest_address; + uint32_t g_rx_size = 1024 * 1024 * 8; + + MRV_systick_config(SYS_CLK_FREQ); + + UART_polled_tx_string( &g_uart, "\r\n------------------------ Starting YModem file transfer ------------------------\r\n" ); + UART_polled_tx_string( &g_uart, "Please select file and initiate transfer on host computer.\r\n" ); + + received = ymodem_receive(g_bin_base, g_rx_size, file_name); + + return received; +} + + +void copy_hex_to_i2ceeprom(void) +{ + uint8_t rx_size = 0u; + uint8_t rx_data[UART_RX_BUF_SIZE]; + + UART_polled_tx_string(&g_uart, g_greeting_msg_i2c); + MIV_I2C_init(&g_miv_i2c_inst, MIV_I2C_BASE_ADDR); //For ~100kHz I2C Clock + + MIV_I2C_config(&g_miv_i2c_inst, 0x0063); + + /* Enable the global external interrupt bit. + This must be done for all Mi-V cores to enable interrupts globally. */ + HAL_enable_interrupts(); + +#ifndef MIV_LEGACY_RV32 + MRV_enable_local_irq(MRV32_MSYS_EIE0_IRQn | + MRV32_MSYS_EIE1_IRQn | + MRV32_MSYS_EIE2_IRQn | + MRV32_MSYS_EIE3_IRQn | + MRV32_MSYS_EIE4_IRQn | + MRV32_MSYS_EIE5_IRQn); + +#endif + + MRV_systick_config(SYS_CLK_FREQ); + write_program_to_i2ceeprom((uint8_t *)LSRAM_BASE_ADDRESS_LOAD, FLASH_EXECUTABLE_SIZE); +} + +void copy_hex_to_spiflash(void) +{ + spi_flash_init(FLASH_CORE_SPI_BASE); + write_program_to_flash((uint8_t *)LSRAM_BASE_ADDRESS_LOAD, FLASH_EXECUTABLE_SIZE); +} + +/* + * Write to I2C EEPROM + */ +static int write_program_to_i2ceeprom(uint8_t *write_buf, uint32_t file_size) +{ + uint32_t mem_addr = 0x80000000; // source address + uint32_t mem_val; // read data word from source + uint8_t page_no; // I2C device page no. Each page is 256 Bytes. 256 x 64 = 16 Kb + miv_i2c_status_t status; + volatile uint8_t miv_i2c_status = 0u; + UART_polled_tx_string(&g_uart, + (const uint8_t *)"\r\nWriting Data into EEPROM using MIV_I2C\n\r"); + for (page_no = 0; page_no <= 127 ; page_no++) //32kb = 128 pages of 256 bytes + { + uint16_t n = 0; + i2c_tx_buffer[0] = page_no; // 1st word address byte (needs to increment for pages) + i2c_tx_buffer[1] = 0x00; // 2nd word address byte - always zero + + // write 256 byte loop + for (n = 0; n < (I2C_XFR_DATA_LEN-2); n = n + 4, mem_addr = mem_addr + 4) + { + mem_val = HW_get_32bit_reg (mem_addr); // get a word from source memory + i2c_tx_buffer[5+n] = mem_val >> 24; //bits 31:24 + i2c_tx_buffer[4+n] = mem_val >> 16; //bits 23:16 + i2c_tx_buffer[3+n] = mem_val >> 8; //bits 15:8 + i2c_tx_buffer[2+n] = mem_val; //bits 7:0 + } + + n = 0u; + // Write a page of data into EEPROM using the MIV_I2C + // The start address of each page is included in the first two bytes of the write + MIV_I2C_write(&g_miv_i2c_inst, + target_slave_addr, + i2c_tx_buffer, + I2C_XFR_DATA_LEN, + MIV_I2C_RELEASE_BUS, + MIV_I2C_ACK_POLLING_ENABLE); + do { + miv_i2c_status = g_miv_i2c_inst.master_status; + }while (MIV_I2C_IN_PROGRESS == miv_i2c_status); + } + UART_polled_tx_string(&g_uart, (const uint8_t *)"\r\nMIV_I2C Write Complete!\n\r"); + return 0u; +} +/* + * Write to flash memory + */ +static int write_program_to_flash(uint8_t *write_buf, uint32_t file_size) +{ + uint8_t write_buffer[FLASH_SEGMENT_SIZE]; + uint8_t read_buffer[FLASH_SEGMENT_SIZE]; + uint16_t status; + int flash_address = 0; + int count = 0; + spi_flash_status_t result; + struct device_Info DevInfo; + + UART_polled_tx_string( &g_uart, "\r\n---------------------- Writing SPI flash from DDR memory ----------------------\r\n" ); + UART_polled_tx_string( &g_uart, "This may take several minutes to complete if writing a large file.\r\n" ); + + spi_flash_control_hw( SPI_FLASH_RESET, 0, &status ); + + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + + /*-------------------------------------------------------------------------- + * First fetch status register. First byte in low 8 bits, second byte in + * upper 8 bits. + */ + result = spi_flash_control_hw( SPI_FLASH_GET_STATUS, 0, &status ); + + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + + /*-------------------------------------------------------------------------- + * Fetch protection register value for each of the 128 sectors. + * After power up these should all read as 0xFF + */ + for( count = 0; count != 128; ++count ) + { + result = spi_flash_control_hw(SPI_FLASH_GET_PROTECT, + count * FLASH_SECTOR_SIZE, + &read_buffer[count] ); + } + + //device D + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + + /*-------------------------------------------------------------------------- + * Show sector protection in action by: + * - unprotecting the first sector + * - erasing the sector + * - writing some data to the first 256 bytes + * - protecting the first sector + * - erasing the first sector + * - reading back the first 256 bytes of the first sector + * - unprotecting the first sector + * - erasing the sector + * - reading back the first 256 bytes of the first sector + * + * The first read should still show the written data in place as the erase + * will fail. the second read should show all 0xFFs. Step through the code + * in debug mode and examine the read buffer after the read operations to + * see this. + */ + result = spi_flash_control_hw( SPI_FLASH_SECTOR_UNPROTECT, flash_address, NULL ); + //device D works + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + result = spi_flash_control_hw( SPI_FLASH_4KBLOCK_ERASE, flash_address , NULL ); + + //device D-- now working + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + + memset( write_buffer, count, FLASH_SEGMENT_SIZE ); + strcpy( (char *)write_buffer, "Microsemi FLASH test" ); + spi_flash_write( flash_address, write_buffer, FLASH_SEGMENT_SIZE ); + //device D -- + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + + result = spi_flash_control_hw( SPI_FLASH_SECTOR_PROTECT, flash_address, NULL ); + //device D + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + result = spi_flash_control_hw( SPI_FLASH_4KBLOCK_ERASE, flash_address , NULL ); + //device D + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + result = spi_flash_control_hw( SPI_FLASH_GET_STATUS, 0, &status ); + //device D + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + + spi_flash_read ( flash_address, read_buffer, FLASH_SEGMENT_SIZE); + //device D + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + + result = spi_flash_control_hw( SPI_FLASH_SECTOR_UNPROTECT, flash_address, NULL ); + //device D + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + result = spi_flash_control_hw( SPI_FLASH_4KBLOCK_ERASE, flash_address , NULL ); + //device D + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + result = spi_flash_control_hw( SPI_FLASH_GET_STATUS, 0, &status ); + //device D + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + + result = spi_flash_control_hw( SPI_FLASH_SECTOR_UNPROTECT, flash_address, NULL ); + //device D + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + result = spi_flash_control_hw(SPI_FLASH_4KBLOCK_ERASE, flash_address , NULL ); + //device D + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + + spi_flash_read ( flash_address, read_buffer, FLASH_SEGMENT_SIZE ); + //device D + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + /*-------------------------------------------------------------------------- + * Read the protection registers again so you can see that the first sector + * is unprotected now. + */ + for( count = 0; count != 128; ++count ) + { + spi_flash_control_hw(SPI_FLASH_GET_PROTECT, + count * FLASH_SECTOR_SIZE, + &write_buffer[count]); + } + //device D + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + /*-------------------------------------------------------------------------- + * Write something to all 32768 blocks of 256 bytes in the 8MB FLASH. + */ + uint32_t nb_blocks_to_write; + nb_blocks_to_write = (file_size / FLASH_SEGMENT_SIZE); + + if ((file_size % FLASH_SEGMENT_SIZE) > 0) + { + ++nb_blocks_to_write; + } + + for( count = 0; count != nb_blocks_to_write; ++count ) + { + /*---------------------------------------------------------------------- + * Vary the fill for each chunk of 256 bytes + */ + memset( write_buffer, count, FLASH_SEGMENT_SIZE ); + strcpy( (char *)write_buffer, "Microsemi FLASH test" ); + /*---------------------------------------------------------------------- + * at the start of each sector we need to make sure it is unprotected + * so we can erase blocks within it. The spi_flash_write() function + * unprotects the sector as well but we need to start erasing before the + * first write takes place. + */ + if(0 == (flash_address % FLASH_SECTOR_SIZE)) + { + result = spi_flash_control_hw(SPI_FLASH_SECTOR_UNPROTECT, + flash_address, + NULL); + } + /*---------------------------------------------------------------------- + * At the start of each 4K block we issue an erase so that we are then + * free to write anything we want to the block. If we don't do this the + * write may fail as we can only effectively turn 1s to 0s when we + * write. For example if we have an erased location with 0xFF in it and + * we write 0xAA to it first and then later on write 0x55, the resulting + * value is 0x00... + */ + if(0 == (flash_address % FLASH_BLOCK_SIZE)) + { + result = spi_flash_control_hw(SPI_FLASH_4KBLOCK_ERASE, + flash_address, + NULL); + } + /*---------------------------------------------------------------------- + * Write our values to the FLASH, read them back and compare. + * Placing a breakpoint on the while statement below will allow + * you break on any failures. + */ + spi_flash_write( flash_address, write_buf, FLASH_SEGMENT_SIZE ); + + spi_flash_read ( flash_address, read_buffer, FLASH_SEGMENT_SIZE ); + if( memcmp( write_buf, read_buffer, FLASH_SEGMENT_SIZE ) ) + { + while(1) // Breakpoint here will trap write faults + { + + } + + } + write_buf += FLASH_SEGMENT_SIZE; + flash_address += FLASH_SEGMENT_SIZE; /* Step to the next 256 byte chunk */ + //show_progress(); + } + + /*-------------------------------------------------------------------------- + * Record the size written in the first SPI flash segment. + */ + { + flash_content_t flash_content; + + flash_content.validity_key = SPI_FLASH_VALID_CONTENT_KEY; + flash_content.spi_content_byte_size = file_size; + + flash_address = LAST_BLOCK_ADDR; + + /*---------------------------------------------------------------------- + * at the start of each sector we need to make sure it is unprotected + * so we can erase blocks within it. The spi_flash_write() function + * unprotects the sector as well but we need to start erasing before the + * first write takes place. + */ + if(0 == (flash_address % FLASH_SECTOR_SIZE)) + { + result = spi_flash_control_hw(SPI_FLASH_SECTOR_UNPROTECT, + flash_address, + NULL); + } + /*---------------------------------------------------------------------- + * At the start of each 4K block we issue an erase so that we are then + * free to write anything we want to the block. If we don't do this the + * write may fail as we can only effectively turn 1s to 0s when we + * write. For example if we have an erased location with 0xFF in it and + * we write 0xAA to it first and then later on write 0x55, the resulting + * value is 0x00... + */ + if(0 == (flash_address % FLASH_BLOCK_SIZE)) + { + result = spi_flash_control_hw(SPI_FLASH_4KBLOCK_ERASE, + flash_address, + NULL); + } + /*---------------------------------------------------------------------- + * Write our values to the FLASH, read them back and compare. + * Placing a breakpoint on the while statement below will allow + * you break on any failures. + */ + spi_flash_write( flash_address, (uint8_t *)(&flash_content), FLASH_SEGMENT_SIZE ); + + spi_flash_read ( flash_address, read_buffer, FLASH_SEGMENT_SIZE ); + + if( memcmp( (uint8_t *)&flash_content, read_buffer, FLASH_SEGMENT_SIZE ) ) + { + while(1) // Breakpoint here will trap write faults + { + + } + } + + write_buf += FLASH_SEGMENT_SIZE; + flash_address += FLASH_SEGMENT_SIZE; /* Step to the next 256 byte chunk */ + } + + /*-------------------------------------------------------------------------- + * One last look at the protection registers which should all be 0 now + */ + for( count = 0; count != 128; ++count ) + { + spi_flash_control_hw(SPI_FLASH_GET_PROTECT, + count * FLASH_SECTOR_SIZE, + &write_buffer[count]); + } + + UART_polled_tx_string( &g_uart, "Flash write success\r\n" ); + + return(0); +} + +#ifdef __UNUSED_CODE +/*-------------------------------------------------------------------------*//** + * Test flash on RTG4 + */ +static int test_flash(void) +{ + uint8_t write_buffer[FLASH_SEGMENT_SIZE]; + uint8_t read_buffer[FLASH_SEGMENT_SIZE]; + uint16_t status; + int flash_address = 0; + int count = 0; + spi_flash_status_t result; + struct device_Info DevInfo; + + spi_flash_control_hw( SPI_FLASH_RESET, 0, &status ); + + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + + /*-------------------------------------------------------------------------- + * First fetch status register. First byte in low 8 bits, second byte in + * upper 8 bits. + */ + result = spi_flash_control_hw( SPI_FLASH_GET_STATUS, 0, &status ); + + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + + /*-------------------------------------------------------------------------- + * Fetch protection register value for each of the 128 sectors. + * After power up these should all read as 0xFF + */ + for( count = 0; count != 128; ++count ) + { + result = spi_flash_control_hw( SPI_FLASH_GET_PROTECT, + count * FLASH_SECTOR_SIZE, + &read_buffer[count] ); + } + + //device D + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + + /*-------------------------------------------------------------------------- + * Show sector protection in action by: + * - unprotecting the first sector + * - erasing the sector + * - writing some data to the first 256 bytes + * - protecting the first sector + * - erasing the first sector + * - reading back the first 256 bytes of the first sector + * - unprotecting the first sector + * - erasing the sector + * - reading back the first 256 bytes of the first sector + * + * The first read should still show the written data in place as the erase + * will fail. the second read should show all 0xFFs. Step through the code + * in debug mode and examine the read buffer after the read operations to + * see this. + */ + result = spi_flash_control_hw( SPI_FLASH_SECTOR_UNPROTECT, flash_address, NULL ); + //device D works + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + result = spi_flash_control_hw( SPI_FLASH_4KBLOCK_ERASE, flash_address , NULL ); + //device D-- now working + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + memset( write_buffer, count, FLASH_SEGMENT_SIZE ); + strcpy( (char *)write_buffer, "Microsemi FLASH test" ); + + spi_flash_write( flash_address, write_buffer, FLASH_SEGMENT_SIZE ); + //device D -- + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + + result = spi_flash_control_hw( SPI_FLASH_SECTOR_PROTECT, flash_address, NULL ); + //device D + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + result = spi_flash_control_hw( SPI_FLASH_4KBLOCK_ERASE, flash_address , NULL ); + //device D + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + result = spi_flash_control_hw( SPI_FLASH_GET_STATUS, 0, &status ); + //device D + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + + spi_flash_read ( flash_address, read_buffer, FLASH_SEGMENT_SIZE); + //device D + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + + result = spi_flash_control_hw( SPI_FLASH_SECTOR_UNPROTECT, flash_address, NULL ); + //device D + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + result = spi_flash_control_hw( SPI_FLASH_4KBLOCK_ERASE, flash_address , NULL ); + //device D + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + result = spi_flash_control_hw( SPI_FLASH_GET_STATUS, 0, &status ); + //device D + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + + result = spi_flash_control_hw( SPI_FLASH_SECTOR_UNPROTECT, flash_address, NULL ); + //device D + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + result = spi_flash_control_hw( SPI_FLASH_4KBLOCK_ERASE, flash_address , NULL ); + //device D + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + + spi_flash_read ( flash_address, read_buffer, FLASH_SEGMENT_SIZE ); + //device D + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + /*-------------------------------------------------------------------------- + * Read the protection registers again so you can see that the first sector + * is unprotected now. + */ + for( count = 0; count != 128; ++count ) + { + spi_flash_control_hw( SPI_FLASH_GET_PROTECT, count * FLASH_SECTOR_SIZE, + &write_buffer[count] ); + } + //device D + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + /*-------------------------------------------------------------------------- + * Write something to all 32768 blocks of 256 bytes in the 8MB FLASH. + */ + for( count = 0; count != 1000 /*32768*/; ++count ) + { + /*---------------------------------------------------------------------- + * Vary the fill for each chunk of 256 bytes + */ + memset( write_buffer, count, FLASH_SEGMENT_SIZE ); + strcpy( (char *)write_buffer, "Microsemi FLASH test" ); + /*---------------------------------------------------------------------- + * at the start of each sector we need to make sure it is unprotected + * so we can erase blocks within it. The spi_flash_write() function + * unprotects the sector as well but we need to start erasing before the + * first write takes place. + */ + if(0 == (flash_address % FLASH_SECTOR_SIZE)) + { + result = spi_flash_control_hw( SPI_FLASH_SECTOR_UNPROTECT, flash_address, NULL ); + } + /*---------------------------------------------------------------------- + * At the start of each 4K block we issue an erase so that we are then + * free to write anything we want to the block. If we don't do this the + * write may fail as we can only effectively turn 1s to 0s when we + * write. For example if we have an erased location with 0xFF in it and + * we write 0xAA to it first and then later on write 0x55, the resulting + * value is 0x00... + */ + if(0 == (flash_address % FLASH_BLOCK_SIZE)) + { + result = spi_flash_control_hw( SPI_FLASH_4KBLOCK_ERASE, flash_address , NULL ); + } + /*---------------------------------------------------------------------- + * Write our values to the FLASH, read them back and compare. + * Placing a breakpoint on the while statement below will allow + * you break on any failures. + */ + spi_flash_write( flash_address, write_buffer, FLASH_SEGMENT_SIZE ); + spi_flash_read ( flash_address, read_buffer, FLASH_SEGMENT_SIZE ); + if( memcmp( write_buffer, read_buffer, FLASH_SEGMENT_SIZE ) ) + { + while(1) // Breakpoint here will trap write faults + { + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + spi_flash_control_hw( SPI_FLASH_RESET, 0, &status ); + + } + + } + + flash_address += FLASH_SEGMENT_SIZE; /* Step to the next 256 byte chunk */ + } + + /*-------------------------------------------------------------------------- + * One last look at the protection registers which should all be 0 now + */ + for( count = 0; count != 128; ++count ) + { + spi_flash_control_hw(SPI_FLASH_GET_PROTECT, + count * FLASH_SECTOR_SIZE, + &write_buffer[count]); + } + + UART_polled_tx_string( &g_uart, " Flash test success\r\n" ); + + return(0); +} + +/** + * Read from flash + */ +static int read_program_from_flash(uint8_t *read_buf, uint32_t read_byte_length) +{ + uint16_t status; + int flash_address = 0; + int count = 0; + uint32_t nb_segments_to_read; + spi_flash_status_t result; + struct device_Info DevInfo; + flash_content_t flash_content; + + UART_polled_tx_string( &g_uart, "\r\n------------------- Reading from SPI flash into DDR memory --------------------\r\n" ); + UART_polled_tx_string( &g_uart, "This will take several minutes to complete in order to read the full SPI flash \r\ncontent.\r\n" ); + + spi_flash_control_hw( SPI_FLASH_RESET, 0, &status ); + + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + + /*-------------------------------------------------------------------------- + * First fetch status register. First byte in low 8 bits, second byte in + * upper 8 bits. + */ + result = spi_flash_control_hw(SPI_FLASH_GET_STATUS, 0, &status); + + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + + /*-------------------------------------------------------------------------- + * Retrieve the size of the data previously written to SPI flash. + */ + spi_flash_read ( LAST_BLOCK_ADDR, (uint8_t *)&flash_content, FLASH_SEGMENT_SIZE ); + + if(SPI_FLASH_VALID_CONTENT_KEY == flash_content.validity_key) + { + read_byte_length = flash_content.spi_content_byte_size; + } + else + { + read_byte_length = 0; + } + + /*-------------------------------------------------------------------------- + * Read from flash 256 bytes increments (FLASH_SEGMENT_SIZE). + */ + nb_segments_to_read = read_byte_length / FLASH_SEGMENT_SIZE; + if((read_byte_length % FLASH_SEGMENT_SIZE) > 0) + { + ++nb_segments_to_read; + } + + for( count = 0; count != nb_segments_to_read; ++count ) + { + /*---------------------------------------------------------------------- + * Write our values to the FLASH, read them back and compare. + * Placing a breakpoint on the while statement below will allow + * you break on any failures. + */ + + spi_flash_read ( flash_address, read_buf, FLASH_SEGMENT_SIZE ); + read_buf += FLASH_SEGMENT_SIZE; + + flash_address += FLASH_SEGMENT_SIZE; /* Step to the next 256 byte chunk */ + } + + UART_polled_tx_string( &g_uart, " Flash read success\r\n" ); + + return(0); +} + +/* + * Simple sanity check + */ +static void mem_test(uint8_t *address) +{ + volatile uint8_t value=2; + volatile uint32_t value32=3; + *address = 1; + value = *address; + value32 = (uint32_t)*address; + + if((value32 == value) &&(value == 1)) + UART_polled_tx_string( &g_uart, " Read/Write success\r\n" ); + else + UART_polled_tx_string( &g_uart, " Read/Write fail\r\n" ); +} + +/*------------------------------------------------------------------------------ + * Call this function if you want to switch to another program + * de-init any loaded drivers before calling this function + */ +//volatile uint32_t cj_debug; +static void Bootloader_JumpToApplication(uint32_t stack_location, uint32_t reset_vector) +{ + /* + * The bootstrap is going to copy the program from NV memory to the TCM. + * The TCM start address is 0x40000000. Jump to that address. + */ + __asm__ volatile ("fence.i"); + __asm__ volatile("lui ra,0x40000"); + __asm__ volatile("ret"); + /*User application execution should now start and never return here.... */ +} + +#endif /*__UNUSED_CODE*/ diff --git a/bootloaders/miv-rv32-bootloader/src/application/bootstrap/bootstrap.c b/bootloaders/miv-rv32-bootloader/src/application/bootstrap/bootstrap.c new file mode 100644 index 0000000..7181bd4 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/application/bootstrap/bootstrap.c @@ -0,0 +1,902 @@ +/******************************************************************************* + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * Mi-V ESS Bootstrap support firmware. + * This project allows you to write executable into the SPI flash or the I2C + * EEPROM. The executable is expected to be available in the LSRAM memory using + * the Libero memory client configurator. + * + */ +#include +#include "miv_rv32_hal/miv_rv32_hal.h" +#include "drivers/fabric_ip/CoreUARTapb/core_uart_apb.h" +#include "drivers/fabric_ip/miv_i2c/miv_i2c.h" +#include "drivers/off_chip/spi_flash/spi_flash.h" + +#define FLASH_SECTOR_SIZE 65536 /* flash memory size */ +#define FLASH_SECTORS 128 // There are 126 sectors of 64kB size, using 124 +#define FLASH_BLOCK_SIZE 4096 //Sectors compose of 4kB eraseable blocks +#define FLASH_SEGMENT_SIZE 256 // Write segment size is 256 + +#define FLASH_BLOCK_SEGMENTS (FLASH_BLOCK_SIZE / FLASH_SEGMENT_SIZE) +#define FLASH_BYTE_SIZE (FLASH_SECTOR_SIZE * FLASH_SECTORS) +#define LAST_BLOCK_ADDR (FLASH_BYTE_SIZE - FLASH_BLOCK_SIZE) + +#ifdef __UNUSED_CODE +static int test_flash(void); +static void mem_test(uint8_t *address); +static int read_program_from_flash(uint8_t *read_buf, uint32_t read_byte_length); +static void Bootloader_JumpToApplication(uint32_t stack_location, uint32_t reset_vector); +#endif + +static int write_program_to_i2ceeprom(uint8_t *write_buf, uint32_t file_size); +static int write_program_to_flash(uint8_t *write_buf, uint32_t file_size); +static void copy_hex_to_i2ceeprom(void); +static void copy_hex_to_spiflash(void); + +/* + * Base address of LSRAM memory where the program is loaded. + */ +#define LSRAM_BASE_ADDRESS_LOAD 0x80000000 +#define LSRAM_BASE_ADDRESS_WRITE 0x89000000 + +/* + * Key value used to determine if valid data is contained in the SPI flash. + */ +#define SPI_FLASH_VALID_CONTENT_KEY 0xB5006BB1 + +const uint8_t g_bootstrap_choice[] = +"\r\n\r\n\ +======================================================================================\r\n\ + MIV_ESS Bootstrap support utility to load binary executable from LSRRAM to Non-Volatile memory \r\n\ +======================================================================================\r\n\ +\r\n\ +\r\n\ +This program supports writing HEX data from Source LSRAM (@ Address 0x800000000) into a Non-Volatile memory\r\n\ +\r\n\ +\r\n\ +Choose the destination Non-Volatile memory: \r\n\ + Type 0 to show this menu\r\n\ + Type 1 copy .hex from LSRAM to SPI Flash \r\n\ + Type 2 copy .hex from LSRAM to MikroBus EEPROM \r\n\ + "; + +/* + * Data structure stored at the beginning of SPI flash to indicate the size of + * data stored inside the SPI flash. This is to avoid having to read the entire + * flash content at boot time. + * This data structure is one flash segment long (256 bytes). + */ +typedef struct +{ + uint32_t validity_key; + uint32_t spi_content_byte_size; + uint32_t dummy[62]; +} flash_content_t; + +/****************************************************************************** + * CoreUARTapb instance data. + *****************************************************************************/ +UART_instance_t g_uart; + + +/****************************************************************************** + * I2C instance data. + *****************************************************************************/ +#define I2C_XFR_DATA_LEN 258u // 2 byte address + 256 bytes data +uint8_t target_slave_addr = 0x50; +uint8_t i2c_tx_buffer[I2C_XFR_DATA_LEN]; +miv_i2c_instance_t g_miv_i2c_inst; + + +volatile uint32_t g_10ms_count; + +const uint8_t g_greeting_msg_spi[] = +" ----> SPI Flash is chosen as destination memory \r\n"; + +const char * g_greeting_msg_i2c = +" ----> I2C EEPROM is chosen as destination memory \r\n"; + +/* + * Maximum UART receiver buffer size. + */ +#define UART_RX_BUF_SIZE 10 + +/* + * Used for bootstrap from SPI FLASH + * The LSRAM max size is 64K. + * Assuming the executable 32k byte. + * Copy the whole 32k chunk from LSRAM to flash. + */ +#define FLASH_EXECUTABLE_SIZE 32768u + +/* MIV I2C interrupt handler */ +void MSYS_EI2_IRQHandler(void) +{ + MIV_I2C_isr (&g_miv_i2c_inst); +} + +void SysTick_Handler(void) +{ + g_10ms_count += 10; + + /* + * For neatness, if we roll over, reset cleanly back to 0 so the count + * always goes up in proper 10s. + */ + if(g_10ms_count < 10) + g_10ms_count = 0; + +} +/*-------------------------------------------------------------------------*//** + * main() function. + */ +int main() +{ + uint8_t rx_data[UART_RX_BUF_SIZE]; + size_t rx_size; + static uint32_t file_size = 0; + /************************************************************************** + * Initialize CoreUARTapb with its base address, baud value, and line + * configuration. + *************************************************************************/ + UART_init(&g_uart, COREUARTAPB0_BASE_ADDR,\ + BAUD_VALUE_115200, (DATA_8_BITS | NO_PARITY) ); + + /************************************************************************** + * Display greeting message message. + *************************************************************************/ + UART_polled_tx_string(&g_uart, g_bootstrap_choice); + + while (1u) + { + /********************************************************************** + * Read data received by the UART. + *********************************************************************/ + rx_size = UART_get_rx( &g_uart, rx_data, sizeof(rx_data) ); + + /********************************************************************** + * Echo back data received, if any. + *********************************************************************/ + if ( rx_size > 0 ) + { + UART_send( &g_uart, rx_data, rx_size ); + + switch(rx_data[0]) + { + case '0': + UART_polled_tx_string( &g_uart, g_bootstrap_choice); + break; + case '1': + copy_hex_to_spiflash(); + break; + case '2': + copy_hex_to_i2ceeprom(); + break; + case '3': + UART_polled_tx_string( &g_uart, + "Run the Bootloader-* build configurations \ + if you are looking for YModem functionality \r\n"); + break; + default: + UART_polled_tx_string( &g_uart, + "Invalid selection. Try again...\r\n"); + break; + } + } + } + + return 0; +} + +void copy_hex_to_i2ceeprom(void) +{ + uint8_t rx_size = 0u; + uint8_t rx_data[UART_RX_BUF_SIZE]; + + UART_polled_tx_string(&g_uart, g_greeting_msg_i2c); + MIV_I2C_init(&g_miv_i2c_inst, MIV_I2C_BASE_ADDR); //For ~100kHz I2C Clock + + MIV_I2C_config(&g_miv_i2c_inst, 0x0063); + + /* Enable the global external interrupt bit. + This must be done for all Mi-V cores to enable interrupts globally. */ + HAL_enable_interrupts(); + +#ifndef MIV_LEGACY_RV32 + MRV_enable_local_irq(MRV32_MSYS_EIE0_IRQn | + MRV32_MSYS_EIE1_IRQn | + MRV32_MSYS_EIE2_IRQn | + MRV32_MSYS_EIE3_IRQn | + MRV32_MSYS_EIE4_IRQn | + MRV32_MSYS_EIE5_IRQn);; + +#endif + + MRV_systick_config(SYS_CLK_FREQ); + write_program_to_i2ceeprom((uint8_t *)LSRAM_BASE_ADDRESS_LOAD, FLASH_EXECUTABLE_SIZE); +} + +void copy_hex_to_spiflash(void) +{ + spi_flash_init(FLASH_CORE_SPI_BASE); + write_program_to_flash((uint8_t *)LSRAM_BASE_ADDRESS_LOAD, FLASH_EXECUTABLE_SIZE); +} + +/* + * Write to I2C EEPROM + */ +static int write_program_to_i2ceeprom(uint8_t *write_buf, uint32_t file_size) +{ + uint32_t mem_addr = 0x80000000; // source address + uint32_t mem_val; // read data word from source + uint8_t page_no; // I2C device page no. Each page is 256 Bytes. 256 x 64 = 16 Kb + miv_i2c_status_t status; + volatile uint8_t miv_i2c_status = 0u; + UART_polled_tx_string(&g_uart, + (const uint8_t *)"\r\nWriting Data into EEPROM using MIV_I2C\n\r"); + for (page_no = 0; page_no <= 127 ; page_no++) //32kb = 128 pages of 256 bytes + { + uint16_t n = 0; + i2c_tx_buffer[0] = page_no; // 1st word address byte (needs to increment for pages) + i2c_tx_buffer[1] = 0x00; // 2nd word address byte - always zero + + // write 256 byte loop + for (n = 0; n < (I2C_XFR_DATA_LEN-2); n = n + 4, mem_addr = mem_addr + 4) + { + mem_val = HW_get_32bit_reg (mem_addr); // get a word from source memory + i2c_tx_buffer[5+n] = mem_val >> 24; //bits 31:24 + i2c_tx_buffer[4+n] = mem_val >> 16; //bits 23:16 + i2c_tx_buffer[3+n] = mem_val >> 8; //bits 15:8 + i2c_tx_buffer[2+n] = mem_val; //bits 7:0 + } + + n = 0u; + // Write a page of data into EEPROM using the MIV_I2C + // The start address of each page is included in the first two bytes of the write + MIV_I2C_write(&g_miv_i2c_inst, + target_slave_addr, + i2c_tx_buffer, + I2C_XFR_DATA_LEN, + MIV_I2C_RELEASE_BUS, + MIV_I2C_ACK_POLLING_ENABLE); + do { + miv_i2c_status = g_miv_i2c_inst.master_status; + }while (MIV_I2C_IN_PROGRESS == miv_i2c_status); + } + UART_polled_tx_string(&g_uart, (const uint8_t *)"\r\nMIV_I2C Write Complete!\n\r"); + return 0u; +} +/* + * Write to flash memory + */ +static int write_program_to_flash(uint8_t *write_buf, uint32_t file_size) +{ + uint8_t write_buffer[FLASH_SEGMENT_SIZE]; + uint8_t read_buffer[FLASH_SEGMENT_SIZE]; + uint16_t status; + int flash_address = 0; + int count = 0; + spi_flash_status_t result; + struct device_Info DevInfo; + + UART_polled_tx_string( &g_uart, "\r\n---------------------- Writing SPI flash from DDR memory ----------------------\r\n" ); + UART_polled_tx_string( &g_uart, "This may take several minutes to complete if writing a large file.\r\n" ); + + spi_flash_control_hw( SPI_FLASH_RESET, 0, &status ); + + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + + /*-------------------------------------------------------------------------- + * First fetch status register. First byte in low 8 bits, second byte in + * upper 8 bits. + */ + result = spi_flash_control_hw( SPI_FLASH_GET_STATUS, 0, &status ); + + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + + /*-------------------------------------------------------------------------- + * Fetch protection register value for each of the 128 sectors. + * After power up these should all read as 0xFF + */ + for( count = 0; count != 128; ++count ) + { + result = spi_flash_control_hw(SPI_FLASH_GET_PROTECT, + count * FLASH_SECTOR_SIZE, + &read_buffer[count] ); + } + + //device D + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + + /*-------------------------------------------------------------------------- + * Show sector protection in action by: + * - unprotecting the first sector + * - erasing the sector + * - writing some data to the first 256 bytes + * - protecting the first sector + * - erasing the first sector + * - reading back the first 256 bytes of the first sector + * - unprotecting the first sector + * - erasing the sector + * - reading back the first 256 bytes of the first sector + * + * The first read should still show the written data in place as the erase + * will fail. the second read should show all 0xFFs. Step through the code + * in debug mode and examine the read buffer after the read operations to + * see this. + */ + result = spi_flash_control_hw( SPI_FLASH_SECTOR_UNPROTECT, flash_address, NULL ); + //device D works + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + result = spi_flash_control_hw( SPI_FLASH_4KBLOCK_ERASE, flash_address , NULL ); + + //device D-- now working + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + + memset( write_buffer, count, FLASH_SEGMENT_SIZE ); + strcpy( (char *)write_buffer, "Microsemi FLASH test" ); + spi_flash_write( flash_address, write_buffer, FLASH_SEGMENT_SIZE ); + //device D -- + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + + result = spi_flash_control_hw( SPI_FLASH_SECTOR_PROTECT, flash_address, NULL ); + //device D + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + result = spi_flash_control_hw( SPI_FLASH_4KBLOCK_ERASE, flash_address , NULL ); + //device D + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + result = spi_flash_control_hw( SPI_FLASH_GET_STATUS, 0, &status ); + //device D + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + + spi_flash_read ( flash_address, read_buffer, FLASH_SEGMENT_SIZE); + //device D + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + + result = spi_flash_control_hw( SPI_FLASH_SECTOR_UNPROTECT, flash_address, NULL ); + //device D + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + result = spi_flash_control_hw( SPI_FLASH_4KBLOCK_ERASE, flash_address , NULL ); + //device D + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + result = spi_flash_control_hw( SPI_FLASH_GET_STATUS, 0, &status ); + //device D + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + + result = spi_flash_control_hw( SPI_FLASH_SECTOR_UNPROTECT, flash_address, NULL ); + //device D + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + result = spi_flash_control_hw(SPI_FLASH_4KBLOCK_ERASE, flash_address , NULL ); + //device D + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + + spi_flash_read ( flash_address, read_buffer, FLASH_SEGMENT_SIZE ); + //device D + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + /*-------------------------------------------------------------------------- + * Read the protection registers again so you can see that the first sector + * is unprotected now. + */ + for( count = 0; count != 128; ++count ) + { + spi_flash_control_hw(SPI_FLASH_GET_PROTECT, + count * FLASH_SECTOR_SIZE, + &write_buffer[count]); + } + //device D + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + /*-------------------------------------------------------------------------- + * Write something to all 32768 blocks of 256 bytes in the 8MB FLASH. + */ + uint32_t nb_blocks_to_write; + nb_blocks_to_write = (file_size / FLASH_SEGMENT_SIZE); + + if ((file_size % FLASH_SEGMENT_SIZE) > 0) + { + ++nb_blocks_to_write; + } + + for( count = 0; count != nb_blocks_to_write; ++count ) + { + /*---------------------------------------------------------------------- + * Vary the fill for each chunk of 256 bytes + */ + memset( write_buffer, count, FLASH_SEGMENT_SIZE ); + strcpy( (char *)write_buffer, "Microsemi FLASH test" ); + /*---------------------------------------------------------------------- + * at the start of each sector we need to make sure it is unprotected + * so we can erase blocks within it. The spi_flash_write() function + * unprotects the sector as well but we need to start erasing before the + * first write takes place. + */ + if(0 == (flash_address % FLASH_SECTOR_SIZE)) + { + result = spi_flash_control_hw(SPI_FLASH_SECTOR_UNPROTECT, + flash_address, + NULL); + } + /*---------------------------------------------------------------------- + * At the start of each 4K block we issue an erase so that we are then + * free to write anything we want to the block. If we don't do this the + * write may fail as we can only effectively turn 1s to 0s when we + * write. For example if we have an erased location with 0xFF in it and + * we write 0xAA to it first and then later on write 0x55, the resulting + * value is 0x00... + */ + if(0 == (flash_address % FLASH_BLOCK_SIZE)) + { + result = spi_flash_control_hw(SPI_FLASH_4KBLOCK_ERASE, + flash_address, + NULL); + } + /*---------------------------------------------------------------------- + * Write our values to the FLASH, read them back and compare. + * Placing a breakpoint on the while statement below will allow + * you break on any failures. + */ + spi_flash_write( flash_address, write_buf, FLASH_SEGMENT_SIZE ); + + spi_flash_read ( flash_address, read_buffer, FLASH_SEGMENT_SIZE ); + if( memcmp( write_buf, read_buffer, FLASH_SEGMENT_SIZE ) ) + { + while(1) // Breakpoint here will trap write faults + { + + } + + } + write_buf += FLASH_SEGMENT_SIZE; + flash_address += FLASH_SEGMENT_SIZE; /* Step to the next 256 byte chunk */ + //show_progress(); + } + + /*-------------------------------------------------------------------------- + * Record the size written in the first SPI flash segment. + */ + { + flash_content_t flash_content; + + flash_content.validity_key = SPI_FLASH_VALID_CONTENT_KEY; + flash_content.spi_content_byte_size = file_size; + + flash_address = LAST_BLOCK_ADDR; + + /*---------------------------------------------------------------------- + * at the start of each sector we need to make sure it is unprotected + * so we can erase blocks within it. The spi_flash_write() function + * unprotects the sector as well but we need to start erasing before the + * first write takes place. + */ + if(0 == (flash_address % FLASH_SECTOR_SIZE)) + { + result = spi_flash_control_hw(SPI_FLASH_SECTOR_UNPROTECT, + flash_address, + NULL); + } + /*---------------------------------------------------------------------- + * At the start of each 4K block we issue an erase so that we are then + * free to write anything we want to the block. If we don't do this the + * write may fail as we can only effectively turn 1s to 0s when we + * write. For example if we have an erased location with 0xFF in it and + * we write 0xAA to it first and then later on write 0x55, the resulting + * value is 0x00... + */ + if(0 == (flash_address % FLASH_BLOCK_SIZE)) + { + result = spi_flash_control_hw(SPI_FLASH_4KBLOCK_ERASE, + flash_address, + NULL); + } + /*---------------------------------------------------------------------- + * Write our values to the FLASH, read them back and compare. + * Placing a breakpoint on the while statement below will allow + * you break on any failures. + */ + spi_flash_write( flash_address, (uint8_t *)(&flash_content), FLASH_SEGMENT_SIZE ); + + spi_flash_read ( flash_address, read_buffer, FLASH_SEGMENT_SIZE ); + + if( memcmp( (uint8_t *)&flash_content, read_buffer, FLASH_SEGMENT_SIZE ) ) + { + while(1) // Breakpoint here will trap write faults + { + + } + } + + write_buf += FLASH_SEGMENT_SIZE; + flash_address += FLASH_SEGMENT_SIZE; /* Step to the next 256 byte chunk */ + } + + /*-------------------------------------------------------------------------- + * One last look at the protection registers which should all be 0 now + */ + for( count = 0; count != 128; ++count ) + { + spi_flash_control_hw(SPI_FLASH_GET_PROTECT, + count * FLASH_SECTOR_SIZE, + &write_buffer[count]); + } + + UART_polled_tx_string( &g_uart, "Flash write success\r\n" ); + + return(0); +} + +#ifdef __UNUSED_CODE +/*-------------------------------------------------------------------------*//** + * Test flash on RTG4 + */ +static int test_flash(void) +{ + uint8_t write_buffer[FLASH_SEGMENT_SIZE]; + uint8_t read_buffer[FLASH_SEGMENT_SIZE]; + uint16_t status; + int flash_address = 0; + int count = 0; + spi_flash_status_t result; + struct device_Info DevInfo; + + spi_flash_control_hw( SPI_FLASH_RESET, 0, &status ); + + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + + /*-------------------------------------------------------------------------- + * First fetch status register. First byte in low 8 bits, second byte in + * upper 8 bits. + */ + result = spi_flash_control_hw( SPI_FLASH_GET_STATUS, 0, &status ); + + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + + /*-------------------------------------------------------------------------- + * Fetch protection register value for each of the 128 sectors. + * After power up these should all read as 0xFF + */ + for( count = 0; count != 128; ++count ) + { + result = spi_flash_control_hw( SPI_FLASH_GET_PROTECT, + count * FLASH_SECTOR_SIZE, + &read_buffer[count] ); + } + + //device D + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + + /*-------------------------------------------------------------------------- + * Show sector protection in action by: + * - unprotecting the first sector + * - erasing the sector + * - writing some data to the first 256 bytes + * - protecting the first sector + * - erasing the first sector + * - reading back the first 256 bytes of the first sector + * - unprotecting the first sector + * - erasing the sector + * - reading back the first 256 bytes of the first sector + * + * The first read should still show the written data in place as the erase + * will fail. the second read should show all 0xFFs. Step through the code + * in debug mode and examine the read buffer after the read operations to + * see this. + */ + result = spi_flash_control_hw( SPI_FLASH_SECTOR_UNPROTECT, flash_address, NULL ); + //device D works + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + result = spi_flash_control_hw( SPI_FLASH_4KBLOCK_ERASE, flash_address , NULL ); + //device D-- now working + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + memset( write_buffer, count, FLASH_SEGMENT_SIZE ); + strcpy( (char *)write_buffer, "Microsemi FLASH test" ); + + spi_flash_write( flash_address, write_buffer, FLASH_SEGMENT_SIZE ); + //device D -- + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + + result = spi_flash_control_hw( SPI_FLASH_SECTOR_PROTECT, flash_address, NULL ); + //device D + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + result = spi_flash_control_hw( SPI_FLASH_4KBLOCK_ERASE, flash_address , NULL ); + //device D + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + result = spi_flash_control_hw( SPI_FLASH_GET_STATUS, 0, &status ); + //device D + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + + spi_flash_read ( flash_address, read_buffer, FLASH_SEGMENT_SIZE); + //device D + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + + result = spi_flash_control_hw( SPI_FLASH_SECTOR_UNPROTECT, flash_address, NULL ); + //device D + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + result = spi_flash_control_hw( SPI_FLASH_4KBLOCK_ERASE, flash_address , NULL ); + //device D + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + result = spi_flash_control_hw( SPI_FLASH_GET_STATUS, 0, &status ); + //device D + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + + result = spi_flash_control_hw( SPI_FLASH_SECTOR_UNPROTECT, flash_address, NULL ); + //device D + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + result = spi_flash_control_hw( SPI_FLASH_4KBLOCK_ERASE, flash_address , NULL ); + //device D + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + + spi_flash_read ( flash_address, read_buffer, FLASH_SEGMENT_SIZE ); + //device D + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + /*-------------------------------------------------------------------------- + * Read the protection registers again so you can see that the first sector + * is unprotected now. + */ + for( count = 0; count != 128; ++count ) + { + spi_flash_control_hw( SPI_FLASH_GET_PROTECT, count * FLASH_SECTOR_SIZE, + &write_buffer[count] ); + } + //device D + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + /*-------------------------------------------------------------------------- + * Write something to all 32768 blocks of 256 bytes in the 8MB FLASH. + */ + for( count = 0; count != 1000 /*32768*/; ++count ) + { + /*---------------------------------------------------------------------- + * Vary the fill for each chunk of 256 bytes + */ + memset( write_buffer, count, FLASH_SEGMENT_SIZE ); + strcpy( (char *)write_buffer, "Microsemi FLASH test" ); + /*---------------------------------------------------------------------- + * at the start of each sector we need to make sure it is unprotected + * so we can erase blocks within it. The spi_flash_write() function + * unprotects the sector as well but we need to start erasing before the + * first write takes place. + */ + if(0 == (flash_address % FLASH_SECTOR_SIZE)) + { + result = spi_flash_control_hw( SPI_FLASH_SECTOR_UNPROTECT, flash_address, NULL ); + } + /*---------------------------------------------------------------------- + * At the start of each 4K block we issue an erase so that we are then + * free to write anything we want to the block. If we don't do this the + * write may fail as we can only effectively turn 1s to 0s when we + * write. For example if we have an erased location with 0xFF in it and + * we write 0xAA to it first and then later on write 0x55, the resulting + * value is 0x00... + */ + if(0 == (flash_address % FLASH_BLOCK_SIZE)) + { + result = spi_flash_control_hw( SPI_FLASH_4KBLOCK_ERASE, flash_address , NULL ); + } + /*---------------------------------------------------------------------- + * Write our values to the FLASH, read them back and compare. + * Placing a breakpoint on the while statement below will allow + * you break on any failures. + */ + spi_flash_write( flash_address, write_buffer, FLASH_SEGMENT_SIZE ); + spi_flash_read ( flash_address, read_buffer, FLASH_SEGMENT_SIZE ); + if( memcmp( write_buffer, read_buffer, FLASH_SEGMENT_SIZE ) ) + { + while(1) // Breakpoint here will trap write faults + { + result = spi_flash_control_hw( SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo ); + spi_flash_control_hw( SPI_FLASH_RESET, 0, &status ); + + } + + } + + flash_address += FLASH_SEGMENT_SIZE; /* Step to the next 256 byte chunk */ + } + + /*-------------------------------------------------------------------------- + * One last look at the protection registers which should all be 0 now + */ + for( count = 0; count != 128; ++count ) + { + spi_flash_control_hw(SPI_FLASH_GET_PROTECT, + count * FLASH_SECTOR_SIZE, + &write_buffer[count]); + } + + UART_polled_tx_string( &g_uart, " Flash test success\r\n" ); + + return(0); +} + +/** + * Read from flash + */ +static int read_program_from_flash(uint8_t *read_buf, uint32_t read_byte_length) +{ + uint16_t status; + int flash_address = 0; + int count = 0; + uint32_t nb_segments_to_read; + spi_flash_status_t result; + struct device_Info DevInfo; + flash_content_t flash_content; + + UART_polled_tx_string( &g_uart, "\r\n------------------- Reading from SPI flash into DDR memory --------------------\r\n" ); + UART_polled_tx_string( &g_uart, "This will take several minutes to complete in order to read the full SPI flash \r\ncontent.\r\n" ); + + spi_flash_control_hw( SPI_FLASH_RESET, 0, &status ); + + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + + /*-------------------------------------------------------------------------- + * First fetch status register. First byte in low 8 bits, second byte in + * upper 8 bits. + */ + result = spi_flash_control_hw(SPI_FLASH_GET_STATUS, 0, &status); + + result = spi_flash_control_hw(SPI_FLASH_READ_DEVICE_ID, + count * FLASH_SECTOR_SIZE, + &DevInfo); + + /*-------------------------------------------------------------------------- + * Retrieve the size of the data previously written to SPI flash. + */ + spi_flash_read ( LAST_BLOCK_ADDR, (uint8_t *)&flash_content, FLASH_SEGMENT_SIZE ); + + if(SPI_FLASH_VALID_CONTENT_KEY == flash_content.validity_key) + { + read_byte_length = flash_content.spi_content_byte_size; + } + else + { + read_byte_length = 0; + } + + /*-------------------------------------------------------------------------- + * Read from flash 256 bytes increments (FLASH_SEGMENT_SIZE). + */ + nb_segments_to_read = read_byte_length / FLASH_SEGMENT_SIZE; + if((read_byte_length % FLASH_SEGMENT_SIZE) > 0) + { + ++nb_segments_to_read; + } + + for( count = 0; count != nb_segments_to_read; ++count ) + { + /*---------------------------------------------------------------------- + * Write our values to the FLASH, read them back and compare. + * Placing a breakpoint on the while statement below will allow + * you break on any failures. + */ + + spi_flash_read ( flash_address, read_buf, FLASH_SEGMENT_SIZE ); + read_buf += FLASH_SEGMENT_SIZE; + + flash_address += FLASH_SEGMENT_SIZE; /* Step to the next 256 byte chunk */ + } + + UART_polled_tx_string( &g_uart, " Flash read success\r\n" ); + + return(0); +} + +/* + * Simple sanity check + */ +static void mem_test(uint8_t *address) +{ + volatile uint8_t value=2; + volatile uint32_t value32=3; + *address = 1; + value = *address; + value32 = (uint32_t)*address; + + if((value32 == value) &&(value == 1)) + UART_polled_tx_string( &g_uart, " Read/Write success\r\n" ); + else + UART_polled_tx_string( &g_uart, " Read/Write fail\r\n" ); +} + +/*------------------------------------------------------------------------------ + * Call this function if you want to switch to another program + * de-init any loaded drivers before calling this function + */ +//volatile uint32_t cj_debug; +static void Bootloader_JumpToApplication(uint32_t stack_location, uint32_t reset_vector) +{ + /* + * The bootstrap is going to copy the program from NV memory to the TCM. + * The TCM start address is 0x40000000. Jump to that address. + */ + __asm__ volatile ("fence.i"); + __asm__ volatile("lui ra,0x40000"); + __asm__ volatile("ret"); + /*User application execution should now start and never return here.... */ +} + +#endif /*__UNUSED_CODE*/ diff --git a/bootloaders/miv-rv32-bootloader/src/boards/polarfire-eval-kit/fpga_design/design_description/readme.md b/bootloaders/miv-rv32-bootloader/src/boards/polarfire-eval-kit/fpga_design/design_description/readme.md new file mode 100644 index 0000000..1cfab05 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/boards/polarfire-eval-kit/fpga_design/design_description/readme.md @@ -0,0 +1,3 @@ +# Desgin desctription + + The Libero generated design desctription will be stored here. \ No newline at end of file diff --git a/bootloaders/miv-rv32-bootloader/src/boards/polarfire-eval-kit/fpga_design_config/fpga_design_config.h b/bootloaders/miv-rv32-bootloader/src/boards/polarfire-eval-kit/fpga_design_config/fpga_design_config.h new file mode 100644 index 0000000..cb2d5d6 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/boards/polarfire-eval-kit/fpga_design_config/fpga_design_config.h @@ -0,0 +1,155 @@ +/******************************************************************************* + * Copyright 2021 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file sample_fpga_design_config.h + * @author Microchip FPGA Embedded Systems Solutions + * @brief Sample design configuration settings + * + */ + /*========================================================================*//** + @mainpage + Example file detailing how the fpga_design_config.h should be constructed + for the SoftConsole project targeted for Mi-V processors. + + @section intro_sec Introduction + The SoftConsole project targeted for Mi-V processors now have an improved + folder structure. Detailed description of the folder structure is available + at https://github.com/Mi-V-Soft-RISC-V/miv-rv32-documentation. + + The fpga_design_config.h must be stored as shown below + /boards//fpga_design_config.h + + Currently this file must be hand crafted when using the Mi-V Soft Processor. + In future, all the design and soft IP configurations will be automatically + generated from the Libero design description data. + + You can use this sample file as an example. + Rename this file from sample_fpga_design_config.h to fpga_design_config.h + and then customize it per your hardware design. + + @section driver_configuration Project configuration Instructions + 1. Change SYS_CLK_FREQ define to frequency of Mi-V Soft processor clock + 2 Add all the soft IP core BASE addresses + 3. Add the peripheral Core Interrupts to Mi-V Soft processor IRQ number + mappings + 4. Define MSCC_STDIO_UART_BASE_ADDR if you want a CoreUARTapb mapped to + STDIO + + **NOTE** + In the legacy folder structures, the file hw_config.h as was used at the + root of the project folder. This file is now deprecated. + +*//*=========================================================================*/ + +#ifndef FPGA_DESIGN_CONFIG_H_ +#define FPGA_DESIGN_CONFIG_H_ + +/***************************************************************************//** + * Soft-processor clock definition + * This is the only clock brought over from the Mi-V Libero design. + */ +#ifndef SYS_CLK_FREQ +#define SYS_CLK_FREQ 50000000UL +#endif + +/***************************************************************************//** + * Non-memory Peripheral base addresses + * Format of define is: + * __BASE_ADDR + * The field is optional if there is only one instance of the core + * in the design + */ +#define COREUARTAPB0_BASE_ADDR 0x71000000UL +#define COREGPIO_IN_BASE_ADDR 0x72000000UL +#define CORETIMER0_BASE_ADDR 0x73000000UL +#define CORETIMER1_BASE_ADDR 0x74000000UL +#define COREGPIO_OUT_BASE_ADDR 0x75000000UL +#define FLASH_CORE_SPI_BASE 0x76000000UL +#define MIV_I2C_BASE_ADDR 0x7A000000UL + +/***************************************************************************//** + * Peripheral Interrupts are mapped to the corresponding Mi-V Soft processor + * interrupt from the Libero design. + * + * On the legacy RV32 cores, there can be up to 31 external interrupts (IRQ[30:0] + * pins). The legacy RV32 Soft processor external interrupts are defined in the + riscv_plic.h + * + * These are of the form + * typedef enum +{ + NoInterrupt_IRQn = 0, + External_1_IRQn = 1, + External_2_IRQn = 2, + . + . + . + External_31_IRQn = 31 +} IRQn_Type; + + On the legacy RV32 processors, the PLIC identifies the interrupt and passes it + on to the processor core. The interrupt 0 is not used. The pin IRQ[0] should + map to External_1_IRQn likewise IRQ[30] should map to External_31_IRQn + +e.g + +#define TIMER0_IRQn External_30_IRQn +#define TIMER1_IRQn External_31_IRQn + + The MIV_RV32 have up to six optional system interrupts, MSYS_EI[n] in addition + to one EXT_IRQ. + On the MIV_RV32 does not have an inbuilt PLIC and all the interrupts are directly + delivered to the processor core, hence unlike legacy RV32 core no interrupt + number mapping is necessary on MIV_RV32 core. + */ + +/**************************************************************************** + * Baud value to achieve a 115200 baud rate with system clock defined by + * SYS_CLK_FREQ. + * This value is calculated using the following equation: + * BAUD_VALUE = (CLOCK / (16 * BAUD_RATE)) - 1 + *****************************************************************************/ +#define BAUD_VALUE_115200 ((SYS_CLK_FREQ / (16 * 115200)) - 1) + +/****************************************************************************** + * Baud value to achieve a 57600 baud rate with system clock defined by + * SYS_CLK_FREQ. + * This value is calculated using the following equation: + * BAUD_VALUE = (CLOCK / (16 * BAUD_RATE)) - 1 + *****************************************************************************/ + #define BAUD_VALUE_57600 ((SYS_CLK_FREQ / (16 * 57600)) - 1) + +/***************************************************************************//** + * Define MSCC_STDIO_THRU_CORE_UART_APB in the project settings if you want the + * standard IOs to be redirected to a terminal via UART. + */ +#ifdef MSCC_STDIO_THRU_CORE_UART_APB +/* + * A base address mapping for the STDIO printf/scanf mapping to CortUARTapb + * must be provided if it is being used + * + * e.g. #define MSCC_STDIO_UART_BASE_ADDR COREUARTAPB1_BASE_ADDR + */ +#define MSCC_STDIO_UART_BASE_ADDR COREUARTAPB0_BASE_ADDR + +#ifndef MSCC_STDIO_UART_BASE_ADDR +#error MSCC_STDIO_UART_BASE_ADDR not defined- e.g. #define MSCC_STDIO_UART_BASE_ADDR COREUARTAPB1_BASE_ADDR +#endif + +#ifndef MSCC_STDIO_BAUD_VALUE +/* + * The MSCC_STDIO_BAUD_VALUE define should be set in your project's settings to + * specify the baud value used by the standard output CoreUARTapb instance for + * generating the UART's baud rate if you want a different baud rate from the + * default of 115200 baud + */ +#define MSCC_STDIO_BAUD_VALUE 115200 +#endif /*MSCC_STDIO_BAUD_VALUE*/ + +#endif /* end of MSCC_STDIO_THRU_CORE_UART_APB */ +/******************************************************************************* + * End of user edit section + */ +#endif /* FPGA_DESIGN_CONFIG_H_ */ diff --git a/bootloaders/miv-rv32-bootloader/src/boards/polarfire-eval-kit/platform_config/linker/miv-rv32-tcm.ld b/bootloaders/miv-rv32-bootloader/src/boards/polarfire-eval-kit/platform_config/linker/miv-rv32-tcm.ld new file mode 100644 index 0000000..149fb3a --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/boards/polarfire-eval-kit/platform_config/linker/miv-rv32-tcm.ld @@ -0,0 +1,141 @@ +/******************************************************************************* + * Copyright 2019-2021 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * file name : microsemi-riscv-ram-imc.ld + * The Mi-V soft processor linker script for creating a SoftConsole downloadable + * debug image executing in SRAM. + * + * This linker script assumes that the TCM on the Mi-V soft processor memory space + * starts at the 0x40000000 and has the size of 16k. The start address and size of + * the memory space must be correct as per the Libero design. + * + * SVN $Revision: 9661 $ + * SVN $Date: 2018-01-15 16:13:33 +0530 (Mon, 15 Jan 2018) $ + */ + +OUTPUT_ARCH( "riscv" ) +ENTRY(_start) + +MEMORY +{ + ram (rwx) : ORIGIN = 0x40000000, LENGTH = 32k +} + +RAM_START_ADDRESS = 0x40000000; /* Must be the same value MEMORY region ram ORIGIN above. */ +RAM_SIZE = 32k; /* Must be the same value MEMORY region ram LENGTH above. */ +STACK_SIZE = 2k; /* needs to be calculated for your application */ +HEAP_SIZE = 0k; /* needs to be calculated for your application */ + +SECTIONS +{ + .entry : ALIGN(0x10) + { + KEEP (*(SORT_NONE(.entry))) + } > ram + + .text : ALIGN(0x10) + { + *(.text .text.* .gnu.linkonce.t.*) + *(.plt) + . = ALIGN(0x10); + + KEEP (*crtbegin.o(.ctors)) + KEEP (*(EXCLUDE_FILE (*crtend.o) .ctors)) + KEEP (*(SORT(.ctors.*))) + KEEP (*crtend.o(.ctors)) + KEEP (*crtbegin.o(.dtors)) + KEEP (*(EXCLUDE_FILE (*crtend.o) .dtors)) + KEEP (*(SORT(.dtors.*))) + KEEP (*crtend.o(.dtors)) + + *(.rodata .rodata.* .gnu.linkonce.r.*) + *(.gcc_except_table) + *(.eh_frame_hdr) + *(.eh_frame) + + KEEP (*(.init)) + KEEP (*(.fini)) + + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP (*(.preinit_array)) + PROVIDE_HIDDEN (__preinit_array_end = .); + PROVIDE_HIDDEN (__init_array_start = .); + KEEP (*(SORT(.init_array.*))) + KEEP (*(.init_array)) + PROVIDE_HIDDEN (__init_array_end = .); + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP (*(.fini_array)) + KEEP (*(SORT(.fini_array.*))) + PROVIDE_HIDDEN (__fini_array_end = .); + . = ALIGN(0x10); + + } > ram + + /* short/global data section */ + .sdata : ALIGN(0x10) + { + __sdata_load = LOADADDR(.sdata); + __sdata_start = .; + __global_pointer$ = . + 0x800; + *(.srodata.cst16) *(.srodata.cst8) *(.srodata.cst4) *(.srodata.cst2) + *(.srodata*) + *(.sdata .sdata.* .gnu.linkonce.s.*) + . = ALIGN(0x10); + __sdata_end = .; + } > ram + + /* data section */ + .data : ALIGN(0x10) + { + __data_load = LOADADDR(.data); + __data_start = .; + *(.got.plt) *(.got) + *(.shdata) + *(.data .data.* .gnu.linkonce.d.*) + . = ALIGN(0x10); + __data_end = .; + } > ram + + /* sbss section */ + .sbss : ALIGN(0x10) + { + __sbss_start = .; + *(.sbss .sbss.* .gnu.linkonce.sb.*) + *(.scommon) + . = ALIGN(0x10); + __sbss_end = .; + } > ram + + /* bss section */ + .bss : ALIGN(0x10) + { + __bss_start = .; + *(.shbss) + *(.bss .bss.* .gnu.linkonce.b.*) + *(COMMON) + . = ALIGN(0x10); + __bss_end = .; + } > ram + + /* End of uninitialized data segment */ + _end = .; + + .heap : ALIGN(0x10) + { + __heap_start = .; + . += HEAP_SIZE; + __heap_end = .; + . = ALIGN(0x10); + _heap_end = __heap_end; + } > ram + + .stack : ALIGN(0x10) + { + __stack_bottom = .; + . += STACK_SIZE; + __stack_top = .; + } > ram +} + diff --git a/bootloaders/miv-rv32-bootloader/src/boards/polarfire-eval-kit/platform_config/miv_rv32_hal_config/readme.md b/bootloaders/miv-rv32-bootloader/src/boards/polarfire-eval-kit/platform_config/miv_rv32_hal_config/readme.md new file mode 100644 index 0000000..6724ed6 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/boards/polarfire-eval-kit/platform_config/miv_rv32_hal_config/readme.md @@ -0,0 +1,3 @@ +# readme + +Software configurations that may be required for MIV_RV32 HAL in future will be stored here. \ No newline at end of file diff --git a/bootloaders/miv-rv32-bootloader/src/middleware/readme.md b/bootloaders/miv-rv32-bootloader/src/middleware/readme.md new file mode 100644 index 0000000..89931ee --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/middleware/readme.md @@ -0,0 +1 @@ +# readme diff --git a/bootloaders/miv-rv32-bootloader/src/middleware/ymodem/ymodem.c b/bootloaders/miv-rv32-bootloader/src/middleware/ymodem/ymodem.c new file mode 100644 index 0000000..6cf05dc --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/middleware/ymodem/ymodem.c @@ -0,0 +1,675 @@ +/* + * copyright (c) 2015 Microsemi Inc + * + * based on ymodem.c for rtdsr, copyright (c) 2011 Pete B. + * based on ymodem.c for bootldr, copyright (c) 2001 John G Dorsey + * baded on ymodem.c for reimage, copyright (c) 2009 Rich M Legrand + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of + * the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + * + * + * + */ + +#define RTG4_DEMO + +#include +#include +#ifndef RTG4_DEMO +#include "sf2_bl_options.h" +#include "sf2_bl_defs.h" +#else +#include "drivers/fabric_ip/CoreUARTapb/core_uart_apb.h" +#endif +#include "ymodem.h" + + +extern UART_instance_t g_uart; +extern volatile uint32_t g_10ms_count; + +/***************************************************************************//** + * Calculate CRC for block of data. + */ +uint16_t sf2bl_crc16(const uint8_t *buf, uint32_t count) +{ + uint16_t crc = 0; + int i; + + while(count--) + { + crc = crc ^ *buf++ << 8; + + for (i=0; i<8; i++) + { + if (crc & 0x8000) + { + crc = crc << 1 ^ 0x1021; + } + else + { + crc = crc << 1; + } + } + } + + return crc; +} + + +/***************************************************************************//** + * The rest of this is only needed for YMODEM builds. + */ +#if SF2BL_COMMS_OPTION == SF2BL_COMMS_YMODEM + +#ifndef RTG4_DEMO + +#if SF2BL_YMODEM_PORT == SF2BL_CORE16550 +#include "core_16550.h" +#else +#include "mss_uart.h" +#endif + + +#if SF2BL_YMODEM_PORT == SF2BL_CORE16550 +/* To keep things consistent define an instance and a pointer for the UART data + * so that MSS and CORE code is as similar as possible. + */ +uart_16550_instance_t g_my_uart_instance; +uart_16550_instance_t *g_my_uart; + +#else + +#if (SF2BL_YMODEM_PORT == SF2BL_MSS_UART0) +mss_uart_instance_t *g_my_uart = &g_mss_uart0; +#else +mss_uart_instance_t *g_my_uart = &g_mss_uart1; +#endif + +#endif + +#ifndef RTG4_DEMO +/***************************************************************************//** + * + */ +void sf2bl_ymodem_init(void) +{ +#if SF2BL_YMODEM_PORT == SF2BL_CORE16550 + uint16_t baud_value; + uint32_t temp; + + /* baud_value = (clock /(baud_rate * 16)) + * Use 32 bits to preserve precision before down sizing to 16 bit */ +#if SF2BL_CORE16550_FIC == 0 + temp = (uint32_t)(MSS_SYS_FIC_0_CLK_FREQ) / ((uint32_t)(SF2BL_YMODEM_BAUD) * 16u); +#else + temp = (uint32_t)(MSS_SYS_FIC_1_CLK_FREQ) / ((uint32_t)(SF2BL_YMODEM_BAUD) * 16u); +#endif + baud_rate = temp; + + UART_16550_init(g_my_uart, SF2BL_CORE16550_HW_BASE, baud_value, + UART_16550_DATA_8_BITS | UART_16550_EVEN_PARITY | UART_16550_ONE_STOP_BIT); + + g_driver_init |= SF2BL_DRIVER_CORE_UART; +#else + MSS_UART_init(g_my_uart, SF2BL_MODEM_BAUD, + MSS_UART_DATA_8_BITS | MSS_UART_NO_PARITY | MSS_UART_ONE_STOP_BIT); + + if(g_my_uart == &g_mss_uart0) + { + g_driver_init |= SF2BL_DRIVER_MSS_UART0; + } + else + { + g_driver_init |= SF2BL_DRIVER_MSS_UART1; + } +#endif +} +#endif + +/***************************************************************************//** + * + */ +void sf2bl_ymodem_deinit(void) +{ +#if SF2BL_YMODEM_PORT == SF2BL_CORE16550 + UART_16550_deinit(g_my_uart, SF2BL_CORE16550_HW_BASE); + g_driver_init &= ~SF2BL_DRIVER_CORE_UART; +#else + MSS_UART_deinit(g_my_uart); + if(g_my_uart == &g_mss_uart0) + { + g_driver_init &= ~SF2BL_DRIVER_MSS_UART0; + } + else + { + g_driver_init &= ~SF2BL_DRIVER_MSS_UART1; + } +#endif +} + +#endif //#ifndef RTG4_DEMO + +/* + * These Ymodem calls are aimed at embedded software and tailored to + * work against Microsoft's HyperTerminal. Some of the Ymodem protocol +* operations have been voluntarily left out. + * + * To be able to use these functions, you must provide: + * o int _getchar(int timeout): A serial getchar() call, with a + * timeout expressed in seconds. Negative means infinite timeout. + * should return the read character, as an int, or negative on + * error/timeout. + * o void _putchar(int c): A serial putchar() call + */ + + +/***************************************************************************//** + * + */ +static void _sleep(uint32_t seconds_delay) + +{ + uint32_t start_time; + + start_time = g_10ms_count; /* record starting point */ + seconds_delay *= 1000; /* Convert to ms */ + + while((g_10ms_count - start_time) < seconds_delay) + ; +} + + + +/***************************************************************************//** + * + */ +static int32_t _getchar(int32_t timeout) +{ + uint32_t start_time; + uint8_t rx_byte; + int32_t done; + int32_t received; + int32_t ret_value; + + ret_value = -1; /* Assume failure/timeout to simplify things */ + done = 0; + + if(timeout < 0) /* blocking mode, exit only on rx character or error */ + { + while(!done) + { +#ifndef RTG4_DEMO + received = MSS_UART_get_rx(g_my_uart, &rx_byte, 1); +#else + received = UART_get_rx( &g_uart, &rx_byte, 1 ); +#endif + if(0 != received) + { + done = 1; +#ifndef RTG4_DEMO + if(MSS_UART_NO_ERROR == MSS_UART_get_rx_status(g_my_uart)) +#endif + { + ret_value = (int32_t)rx_byte; + } + } + } + } + else if(timeout > 0) /* time limited mode */ + { + start_time = g_10ms_count; /* record starting point */ + timeout *= 1000; /* Convert timeout to ms */ + while(!done) + { +#ifndef RTG4_DEMO + received = MSS_UART_get_rx(g_my_uart, &rx_byte, 1); +#else + received = UART_get_rx( &g_uart, &rx_byte, 1 ); +#endif + if(0 != received) + { + done = 1; +#ifndef RTG4_DEMO + if(MSS_UART_NO_ERROR == MSS_UART_get_rx_status(g_my_uart)) +#endif + { + ret_value = (int32_t)rx_byte; + } + } + + if((g_10ms_count) >= start_time + timeout) + { + /* Timed out so exit with ret_value == -1 */ + done = 1; + } + } + } + else /* one shot mode */ + { +#ifndef RTG4_DEMO + received = MSS_UART_get_rx(g_my_uart, &rx_byte, 1); +#else + received = UART_get_rx( &g_uart, &rx_byte, 1 ); +#endif +#ifndef RTG4_DEMO + if((0 != received) && (MSS_UART_NO_ERROR == MSS_UART_get_rx_status(g_my_uart))) +#else + if(0 != received) +#endif + { + ret_value = (int32_t)rx_byte; + } + } + + return(ret_value); +} + + +/***************************************************************************//** + * + */ +/* + * Debug data and code to capture last hundred sends to see what sequence took + * place. + */ +#if 0 +static uint8_t __tx_buffer[100]; +static int32_t __tx_index = 0; +#endif + +void _putchar(int32_t data) +{ + uint8_t tx_byte; + +#if 0 + __tx_buffer[__tx_index++] = (uint8_t)data; + if(__tx_index >= 100) + __tx_index = 0; +#endif + + tx_byte = (uint8_t)data; + +#ifndef RTG4_DEMO + MSS_UART_polled_tx(g_my_uart, &tx_byte, 1); +#else + UART_send( &g_uart, &tx_byte, 1 ); +#endif +} + + +/***************************************************************************//** + * + */ +void _putstring(uint8_t *string) +{ + +#ifndef RTG4_DEMO + MSS_UART_polled_tx(g_my_uart, string, strlen((const char *)string)); +#else + UART_send( &g_uart, string, strlen((const char *)string) ); +#endif +} + + +/***************************************************************************//** + * + */ +static uint32_t str_to_u32(uint8_t *str) +{ + const uint8_t *s = str; + uint32_t acc; + uint8_t c; + + /* strip leading spaces if any */ + do + { + c = *s++; + } while (c == ' '); + + for(acc = 0; (c >= '0') && (c <= '9'); c = *s++) + { + c -= '0'; + acc *= 10; + acc += c; + } + + return acc; +} + + +/***************************************************************************//** + * Returns 0 on success, 1 on corrupt packet, -1 on error (timeout): + * *length will be set to the length of + */ +static int32_t receive_packet(uint8_t *data, int32_t *length) +{ + volatile int32_t index; + int32_t rx_char; + volatile int32_t return_val = 0; /* Assume everything is ok */ + uint32_t packet_size = 0U; + + *length = 0; + + rx_char = _getchar(PACKET_TIMEOUT); + + if(rx_char < 0) + { + return_val = -1; + } + else + { + switch(rx_char) + { + case SOH: /* 128 byte packet start */ + packet_size = PACKET_SIZE; + break; + + case STX: /* 1024 byte packet start */ + packet_size = PACKET_1K_SIZE; + break; + + case EOT: /* end of file marker */ + return_val = -2; /* Signifies end of file */ + break; + + case CAN: /* Possible cancellation of transfer */ + rx_char = _getchar(PACKET_TIMEOUT); + if(CAN == rx_char) + { + /* Got CAN CAN so really is cancel */ + *length = -1; + return_val = -3; /* Signifies cancelled */ + break; + } + /* signal an error, CAN followed by not CAN is probably an + * error on the line + */ + *length = -1; + return_val = -4; /* Signifies unexpected start of packet character */ + break; + default: + /* This case could be the result of corruption on the first octet + * of the packet, but it's more likely that it's the user banging + * on the terminal trying to abort a transfer. Technically, the + * former case deserves a NAK, but for now we'll just treat this + * as an abort case. + */ + *length = -1; + return_val = -4; /* Signifies unexpected start of packet character */ + break; + } + + if(0 == return_val) /* Still ok */ + { + *data = (uint8_t)rx_char; /* Store first character of packet */ + + for(index = 1; (index < (int32_t)(packet_size + PACKET_OVERHEAD)) && (0 == return_val); ++index) + { + rx_char = _getchar(PACKET_TIMEOUT); + if (rx_char < 0) + { + return_val = -1; + } + else + { + data[index] = (uint8_t)rx_char; + } + } + + /* Just a sanity check on the sequence number/complement value. + * Caller should check for in-order arrival. + * + */ + int y = (0 == return_val); + uint8_t x = data[PACKET_SEQNO_INDEX]; + uint8_t z = ((uint8_t)((data[PACKET_SEQNO_COMP_INDEX] ^ 0xffU) & 0xffU)); + if(y && (x != z)) + { + return_val = 1; + } + + if((0 == return_val) && (sf2bl_crc16(data + PACKET_HEADER, packet_size + PACKET_TRAILER) != 0)) + { + return_val = 1; + } + + if(0 == return_val) /* All ok ! */ + { + *length = packet_size; + } + } + } + + if(return_val < -1) /* returning 0 but *length == -1 or 0 so fix up return value */ + { + return_val = 0; + } + + return(return_val); +} + + +/***************************************************************************//** + * + */ +/* Returns the length of the file received, or 0 on error: */ +uint32_t ymodem_receive(uint8_t *buf, uint32_t length, uint8_t *file_name) +{ + static uint8_t packet_data[PACKET_1K_SIZE + PACKET_OVERHEAD]; /* Declare as static as 1K is a lot to put on our stack */ + uint8_t file_size[FILE_SIZE_LENGTH + 1]; + uint8_t *file_ptr; + int32_t packet_length; + int32_t index; + int32_t file_done; + int32_t session_done; + + int32_t crc_nak; + uint32_t packets_received; + uint32_t errors; + int32_t first_try = 1; + uint8_t *buf_ptr; + uint32_t size = 0; + uint32_t return_val = 0; /* Default to abnormal exit */ + uint32_t temp; + int32_t rx_status; + + file_name[0] = 0; + session_done = 0; + errors = 0; + + while(0 == session_done) + { + crc_nak = 1; + + if(!first_try) + { + _putchar(CRC); + } + + first_try = 0; + packets_received = 0; + file_done = 0; + buf_ptr = buf; + + while(0 == file_done) + { + rx_status = receive_packet(packet_data, &packet_length); + switch(rx_status) + { + case 0: /* Success */ + errors = 0; + switch(packet_length) + { + case -1: /* abort */ + _putchar(ACK); + + /* Terminate transfer immediately */ + file_done = 1; + session_done = 1; + break; + + case 0: /* end of transmission */ + _putchar(ACK); + /* Should add some sort of sanity check on the number of + * packets received and the advertised file length. + */ + file_done = 1; + return_val = 1; /* Signal normal exit */ + break; + + default: /* normal packet */ + if((packet_data[PACKET_SEQNO_INDEX] & 0xff) != (packets_received & 0xff)) + { + /* + * Hmmm, Tera Term 4.86 doesn't seem to like the ACK+C + * response and resends the header packet. Responding + * with just C seems to work. Only try this if we get a + * repeat of packet 0... + */ + if((1 == packets_received) && (0 == (packet_data[PACKET_SEQNO_INDEX] & 0xff))) + { + _putchar(CRC); /* Repeated packet 0 error */ + } + else + { + _putchar(NAK); /* Normal out of sequence packet error */ + } + } + else + { + if(0 == packets_received) + { + /* The spec suggests that the whole data section should + * be zeroed, but I don't think all senders do this. If + * we have a NULL filename and the first few digits of + * the file length are zero, we'll call it empty. + */ + temp = 0; + for(index = PACKET_HEADER; index < PACKET_HEADER + 4; index++) + { + temp += (uint32_t)packet_data[index]; + } + + if(0 != temp) /* looks like there is something there... */ + { /* filename packet has data */ + file_ptr = packet_data + PACKET_HEADER; + /* Copy file name until nul or too much */ + for(index = 0; *file_ptr && (index < FILE_NAME_LENGTH);) + { + file_name[index++] = *file_ptr++; + } + + file_name[index] = '\0'; + + while(*file_ptr != 0) /* Search for nul terminator if not there already */ + { + ++file_ptr; + } + + ++file_ptr; /* Step over nul */ + + for(index = 0; *file_ptr && (*file_ptr != ' ') && (index < FILE_SIZE_LENGTH);) + { + file_size[index++] = *file_ptr++; + } + + file_size[index] = '\0'; + + size = str_to_u32(file_size); + if(size > length) + { + _putchar(CAN); + _putchar(CAN); + _sleep(1); + + /* Terminate transfer immediately */ + file_done = 1; + session_done = 1; + } + else + { + _putchar(ACK); + _putchar(crc_nak ? CRC : NAK); + crc_nak = 0; + } + } + else + { /* filename packet is empty; end session */ + _putchar(ACK); + file_done = 1; + session_done = 1; + break; + } + } + else + { + /* This shouldn't happen, but we check anyway in case the + * sender lied in its filename packet: + */ + if((buf_ptr + packet_length) - buf > length) + { + _putchar(CAN); + _putchar(CAN); + _sleep(1); + + /* Terminate transfer immediately */ + file_done = 1; + session_done = 1; + } + else + { + for (index=0; index < packet_length; index++) + { + buf_ptr[index] = packet_data[PACKET_HEADER + index]; + } + + buf_ptr += packet_length; + _putchar(ACK); + } + } + + ++packets_received; + } /* sequence number ok */ + break; + } + break; + + default: /* timeout or error */ + if(packets_received != 0) + { + if(++errors >= MAX_ERRORS) + { + _putchar(CAN); + _putchar(CAN); + _sleep(1); + + /* Terminate transfer immediately */ + file_done = 1; + session_done = 1; + } + } + + if(0 == session_done) + { + _putchar(CRC); + } + break; + } + } /* receive packets */ + } /* receive files */ + + return(return_val == 1 ? size : 0 ); +} + +#endif /* SF2BL_COMMS_OPTION == SF2BL_COMMS_YMODEM */ diff --git a/bootloaders/miv-rv32-bootloader/src/middleware/ymodem/ymodem.h b/bootloaders/miv-rv32-bootloader/src/middleware/ymodem/ymodem.h new file mode 100644 index 0000000..d50f50c --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/middleware/ymodem/ymodem.h @@ -0,0 +1,65 @@ +/* ymodem for SmartFusion2 Bootloader + * + * copyright (c) 2015 Microsemi Inc + * + * based on ymodem for RTD Serial Recovery (rtdsr) + * copyright (c) 2011 Pete B. + * + * based on ymodem.h for bootldr, copyright (c) 2001 John G Dorsey + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of + * the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + * + * + */ + +#if !defined(_YMODEM_H) +#define _YMODEM_H + +#define PACKET_SEQNO_INDEX (1) +#define PACKET_SEQNO_COMP_INDEX (2) + +#define PACKET_HEADER (3) /* start, block, block-complement */ +#define PACKET_TRAILER (2) /* CRC bytes */ +#define PACKET_OVERHEAD (PACKET_HEADER + PACKET_TRAILER) +#define PACKET_SIZE (128) +#define PACKET_1K_SIZE (1024) +#define PACKET_TIMEOUT (1) + +#define FILE_NAME_LENGTH (64) +#define FILE_SIZE_LENGTH (16) + +/* ASCII control codes: */ +#define SOH (0x01) /* start of 128-byte data packet */ +#define STX (0x02) /* start of 1024-byte data packet */ +#define EOT (0x04) /* end of transmission */ +#define ACK (0x06) /* receive OK */ +#define NAK (0x15) /* receiver error; retry */ +#define CAN (0x18) /* two of these in succession aborts transfer */ +#define CRC (0x43) /* use in place of first NAK for CRC mode */ + +/* Number of consecutive receive errors before giving up: */ +#define MAX_ERRORS (5) + +void sf2bl_ymodem_init(void); +void sf2bl_ymodem_deinit(void); +uint32_t ymodem_receive(uint8_t *buf, uint32_t length, uint8_t *file_name); +uint16_t sf2bl_crc16(const uint8_t *buf, uint32_t count); +void _putchar(int32_t data); +void _putstring(uint8_t *string); + +#endif /* !define(_YMODEM_H) */ + + + + diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreGPIO/core_gpio.c b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreGPIO/core_gpio.c new file mode 100644 index 0000000..63cd377 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreGPIO/core_gpio.c @@ -0,0 +1,531 @@ +/******************************************************************************* + * (c) Copyright 2008-2021 Microchip FPGA Embedded Systems Solutions. + * + * @file core_gpio.c + * @author Microchip FPGA Embedded Systems Solutions + * @brief CoreGPIO bare metal driver implementation. + * + */ +#include "coregpio_regs.h" +#include "core_gpio.h" + +/*-------------------------------------------------------------------------*//** + * + */ +#define GPIO_INT_ENABLE_MASK (uint32_t)0x00000008UL +#define OUTPUT_BUFFER_ENABLE_MASK 0x00000004UL + + +#define NB_OF_GPIO 32 + +#define CLEAR_ALL_IRQ32 (uint32_t)0xFFFFFFFF +#define CLEAR_ALL_IRQ16 (uint16_t)0xFFFF +#define CLEAR_ALL_IRQ8 (uint8_t)0xFF + +/*-------------------------------------------------------------------------*//** + * GPIO_init() + * See "core_gpio.h" for details of how to use this function. + */ +void GPIO_init +( + gpio_instance_t * this_gpio, + addr_t base_addr, + gpio_apb_width_t bus_width +) +{ + uint8_t i = 0; + addr_t cfg_reg_addr = base_addr; + + this_gpio->base_addr = base_addr; + this_gpio->apb_bus_width = bus_width; + + /* Clear configuration. */ + for( i = 0, cfg_reg_addr = base_addr; i < NB_OF_GPIO; ++i ) + { + HW_set_8bit_reg( cfg_reg_addr, 0 ); + cfg_reg_addr += 4; + } + /* Clear any pending interrupts */ + switch( this_gpio->apb_bus_width ) + { + case GPIO_APB_32_BITS_BUS: + HAL_set_32bit_reg( this_gpio->base_addr, IRQ, CLEAR_ALL_IRQ32 ); + break; + + case GPIO_APB_16_BITS_BUS: + HAL_set_16bit_reg( this_gpio->base_addr, IRQ0, (uint16_t)CLEAR_ALL_IRQ16 ); + HAL_set_16bit_reg( this_gpio->base_addr, IRQ1, (uint16_t)CLEAR_ALL_IRQ16 ); + break; + + case GPIO_APB_8_BITS_BUS: + HAL_set_8bit_reg( this_gpio->base_addr, IRQ0, (uint8_t)CLEAR_ALL_IRQ8 ); + HAL_set_8bit_reg( this_gpio->base_addr, IRQ1, (uint8_t)CLEAR_ALL_IRQ8 ); + HAL_set_8bit_reg( this_gpio->base_addr, IRQ2, (uint8_t)CLEAR_ALL_IRQ8 ); + HAL_set_8bit_reg( this_gpio->base_addr, IRQ3, (uint8_t)CLEAR_ALL_IRQ8 ); + break; + + default: + HAL_ASSERT(0); + break; + } +} + +/*-------------------------------------------------------------------------*//** + * GPIO_config + * See "core_gpio.h" for details of how to use this function. + */ +void GPIO_config +( + gpio_instance_t * this_gpio, + gpio_id_t port_id, + uint32_t config +) +{ + HAL_ASSERT( port_id < NB_OF_GPIO ); + + if ( port_id < NB_OF_GPIO ) + { + uint32_t cfg_reg_addr = this_gpio->base_addr; + cfg_reg_addr += (port_id * 4); + HW_set_32bit_reg( cfg_reg_addr, config ); + + /* + * Verify that the configuration was correctly written. Failure to read + * back the expected value may indicate that the GPIO port was configured + * as part of the hardware flow and cannot be modified through software. + * It may also indicate that the base address passed as parameter to + * GPIO_init() was incorrect. + */ + HAL_ASSERT( HW_get_32bit_reg( cfg_reg_addr ) == config ); + } +} + +/*-------------------------------------------------------------------------*//** + * GPIO_set_outputs + * See "core_gpio.h" for details of how to use this function. + */ +void GPIO_set_outputs +( + gpio_instance_t * this_gpio, + uint32_t value +) +{ + switch( this_gpio->apb_bus_width ) + { + case GPIO_APB_32_BITS_BUS: + HAL_set_32bit_reg( this_gpio->base_addr, GPIO_OUT, value ); + break; + + case GPIO_APB_16_BITS_BUS: + HAL_set_16bit_reg( this_gpio->base_addr, GPIO_OUT0, (uint16_t)value ); + HAL_set_16bit_reg( this_gpio->base_addr, GPIO_OUT1, (uint16_t)(value >> 16) ); + break; + + case GPIO_APB_8_BITS_BUS: + HAL_set_8bit_reg( this_gpio->base_addr, GPIO_OUT0, (uint8_t)value ); + HAL_set_8bit_reg( this_gpio->base_addr, GPIO_OUT1, (uint8_t)(value >> 8) ); + HAL_set_8bit_reg( this_gpio->base_addr, GPIO_OUT2, (uint8_t)(value >> 16) ); + HAL_set_8bit_reg( this_gpio->base_addr, GPIO_OUT3, (uint8_t)(value >> 24) ); + break; + + default: + HAL_ASSERT(0); + break; + } + + /* + * Verify that the output register was correctly written. Failure to read back + * the expected value may indicate that some of the GPIOs may not exist due to + * the number of GPIOs selected in the CoreGPIO hardware flow configuration. + * It may also indicate that the base address or APB bus width passed as + * parameter to the GPIO_init() function do not match the hardware design. + */ + HAL_ASSERT( GPIO_get_outputs( this_gpio ) == value ); +} + +/*-------------------------------------------------------------------------*//** + * GPIO_get_inputs + * See "core_gpio.h" for details of how to use this function. + */ +uint32_t GPIO_get_inputs +( + gpio_instance_t * this_gpio +) +{ + uint32_t gpio_in = 0; + + switch( this_gpio->apb_bus_width ) + { + case GPIO_APB_32_BITS_BUS: + gpio_in = HAL_get_32bit_reg( this_gpio->base_addr, GPIO_IN ); + break; + + case GPIO_APB_16_BITS_BUS: + gpio_in |= HAL_get_16bit_reg( this_gpio->base_addr, GPIO_IN0 ); + gpio_in |= (HAL_get_16bit_reg( this_gpio->base_addr, GPIO_IN1 ) << 16); + break; + + case GPIO_APB_8_BITS_BUS: + gpio_in |= HAL_get_8bit_reg( this_gpio->base_addr, GPIO_IN0 ); + gpio_in |= (HAL_get_8bit_reg( this_gpio->base_addr, GPIO_IN1 ) << 8); + gpio_in |= (HAL_get_8bit_reg( this_gpio->base_addr, GPIO_IN2 ) << 16); + gpio_in |= (HAL_get_8bit_reg( this_gpio->base_addr, GPIO_IN3 ) << 24); + break; + + default: + HAL_ASSERT(0); + break; + } + + return gpio_in; +} + +/*-------------------------------------------------------------------------*//** + * GPIO_get_outputs + * See "core_gpio.h" for details of how to use this function. + */ +uint32_t GPIO_get_outputs +( + gpio_instance_t * this_gpio +) +{ + uint32_t gpio_out = 0; + + switch( this_gpio->apb_bus_width ) + { + case GPIO_APB_32_BITS_BUS: + gpio_out = HAL_get_32bit_reg( this_gpio->base_addr, GPIO_OUT ); + break; + + case GPIO_APB_16_BITS_BUS: + gpio_out |= HAL_get_16bit_reg( this_gpio->base_addr, GPIO_OUT0 ); + gpio_out |= (HAL_get_16bit_reg( this_gpio->base_addr, GPIO_OUT1 ) << 16); + break; + + case GPIO_APB_8_BITS_BUS: + gpio_out |= HAL_get_16bit_reg( this_gpio->base_addr, GPIO_OUT0 ); + gpio_out |= (HAL_get_16bit_reg( this_gpio->base_addr, GPIO_OUT1 ) << 8); + gpio_out |= (HAL_get_16bit_reg( this_gpio->base_addr, GPIO_OUT2 ) << 16); + gpio_out |= (HAL_get_16bit_reg( this_gpio->base_addr, GPIO_OUT3 ) << 24); + break; + + default: + HAL_ASSERT(0); + break; + } + + return gpio_out; +} + +/*-------------------------------------------------------------------------*//** + * GPIO_set_output + * See "core_gpio.h" for details of how to use this function. + */ +void GPIO_set_output +( + gpio_instance_t * this_gpio, + gpio_id_t port_id, + uint8_t value +) +{ + HAL_ASSERT( port_id < NB_OF_GPIO ); + + + switch( this_gpio->apb_bus_width ) + { + case GPIO_APB_32_BITS_BUS: + { + uint32_t outputs_state; + + outputs_state = HAL_get_32bit_reg( this_gpio->base_addr, GPIO_OUT ); + if ( 0 == value ) + { + outputs_state &= ~(1 << port_id); + } + else + { + outputs_state |= 1 << port_id; + } + HAL_set_32bit_reg( this_gpio->base_addr, GPIO_OUT, outputs_state ); + + /* + * Verify that the output register was correctly written. Failure to read back + * the expected value may indicate that some of the GPIOs may not exist due to + * the number of GPIOs selected in the CoreGPIO hardware flow configuration. + * It may also indicate that the base address or APB bus width passed as + * parameter to the GPIO_init() function do not match the hardware design. + */ + HAL_ASSERT( HAL_get_32bit_reg( this_gpio->base_addr, GPIO_OUT ) == outputs_state ); + } + break; + + case GPIO_APB_16_BITS_BUS: + { + uint16_t outputs_state; + uint32_t gpio_out_reg_addr = this_gpio->base_addr + GPIO_OUT_REG_OFFSET + ((port_id >> 4) * 4); + + outputs_state = HW_get_16bit_reg( gpio_out_reg_addr ); + if ( 0 == value ) + { + outputs_state &= ~(1 << (port_id & 0x0F)); + } + else + { + outputs_state |= 1 << (port_id & 0x0F); + } + HW_set_16bit_reg( gpio_out_reg_addr, outputs_state ); + + /* + * Verify that the output register was correctly written. Failure to read back + * the expected value may indicate that some of the GPIOs may not exist due to + * the number of GPIOs selected in the CoreGPIO hardware flow configuration. + * It may also indicate that the base address or APB bus width passed as + * parameter to the GPIO_init() function do not match the hardware design. + */ + HAL_ASSERT( HW_get_16bit_reg( gpio_out_reg_addr ) == outputs_state ); + } + break; + + case GPIO_APB_8_BITS_BUS: + { + uint8_t outputs_state; + uint32_t gpio_out_reg_addr = this_gpio->base_addr + GPIO_OUT_REG_OFFSET + ((port_id >> 3) * 4); + + outputs_state = HW_get_8bit_reg( gpio_out_reg_addr ); + if ( 0 == value ) + { + outputs_state &= ~(1 << (port_id & 0x07)); + } + else + { + outputs_state |= 1 << (port_id & 0x07); + } + HW_set_8bit_reg( gpio_out_reg_addr, outputs_state ); + + /* + * Verify that the output register was correctly written. Failure to read back + * the expected value may indicate that some of the GPIOs may not exist due to + * the number of GPIOs selected in the CoreGPIO hardware flow configuration. + * It may also indicate that the base address or APB bus width passed as + * parameter to the GPIO_init() function do not match the hardware design. + */ + HAL_ASSERT( HW_get_8bit_reg( gpio_out_reg_addr ) == outputs_state ); + } + break; + + default: + HAL_ASSERT(0); + break; + } +} + +/*-------------------------------------------------------------------------*//** + * GPIO_drive_inout + * See "core_gpio.h" for details of how to use this function. + */ +void GPIO_drive_inout +( + gpio_instance_t * this_gpio, + gpio_id_t port_id, + gpio_inout_state_t inout_state +) +{ + uint32_t config; + uint32_t cfg_reg_addr = this_gpio->base_addr; + + HAL_ASSERT( port_id < NB_OF_GPIO ); + + switch( inout_state ) + { + case GPIO_DRIVE_HIGH: + /* Set output high */ + GPIO_set_output( this_gpio, port_id, 1 ); + + /* Enable output buffer */ + cfg_reg_addr = this_gpio->base_addr + (port_id * 4); + config = HW_get_8bit_reg( cfg_reg_addr ); + config |= OUTPUT_BUFFER_ENABLE_MASK; + HW_set_8bit_reg( cfg_reg_addr, config ); + break; + + case GPIO_DRIVE_LOW: + /* Set output low */ + GPIO_set_output( this_gpio, port_id, 0 ); + + /* Enable output buffer */ + cfg_reg_addr = this_gpio->base_addr + (port_id * 4); + config = HW_get_8bit_reg( cfg_reg_addr ); + config |= OUTPUT_BUFFER_ENABLE_MASK; + HW_set_8bit_reg( cfg_reg_addr, config ); + break; + + case GPIO_HIGH_Z: + /* Disable output buffer */ + cfg_reg_addr = this_gpio->base_addr + (port_id * 4); + config = HW_get_8bit_reg( cfg_reg_addr ); + config &= ~OUTPUT_BUFFER_ENABLE_MASK; + HW_set_8bit_reg( cfg_reg_addr, config ); + break; + + default: + HAL_ASSERT(0); + break; + } +} + +/*-------------------------------------------------------------------------*//** + * GPIO_enable_irq + * See "core_gpio.h" for details of how to use this function. + */ +void GPIO_enable_irq +( + gpio_instance_t * this_gpio, + gpio_id_t port_id +) +{ + uint32_t cfg_value; + uint32_t cfg_reg_addr = this_gpio->base_addr; + + HAL_ASSERT( port_id < NB_OF_GPIO ); + + if ( port_id < NB_OF_GPIO ) + { + cfg_reg_addr += (port_id * 4); + cfg_value = HW_get_8bit_reg( cfg_reg_addr ); + cfg_value |= GPIO_INT_ENABLE_MASK; + HW_set_8bit_reg( cfg_reg_addr, cfg_value ); + } +} + +/*-------------------------------------------------------------------------*//** + * GPIO_disable_irq + * See "core_gpio.h" for details of how to use this function. + */ +void GPIO_disable_irq +( + gpio_instance_t * this_gpio, + gpio_id_t port_id +) +{ + uint32_t cfg_value; + uint32_t cfg_reg_addr = this_gpio->base_addr; + + HAL_ASSERT( port_id < NB_OF_GPIO ); + + if ( port_id < NB_OF_GPIO ) + { + cfg_reg_addr += (port_id * 4); + cfg_value = HW_get_8bit_reg( cfg_reg_addr ); + cfg_value &= ~GPIO_INT_ENABLE_MASK; + HW_set_8bit_reg( cfg_reg_addr, cfg_value ); + } +} + +/*-------------------------------------------------------------------------*//** + * GPIO_clear_irq + * See "core_gpio.h" for details of how to use this function. + */ +void GPIO_clear_irq +( + gpio_instance_t * this_gpio, + gpio_id_t port_id +) +{ + uint32_t irq_clr_value = ((uint32_t)1) << ((uint32_t)port_id); + + switch( this_gpio->apb_bus_width ) + { + case GPIO_APB_32_BITS_BUS: + HAL_set_32bit_reg( this_gpio->base_addr, IRQ, irq_clr_value ); + break; + + case GPIO_APB_16_BITS_BUS: + HAL_set_16bit_reg( this_gpio->base_addr, IRQ0, irq_clr_value ); + HAL_set_16bit_reg( this_gpio->base_addr, IRQ1, irq_clr_value >> 16 ); + break; + + case GPIO_APB_8_BITS_BUS: + HAL_set_8bit_reg( this_gpio->base_addr, IRQ0, irq_clr_value ); + HAL_set_8bit_reg( this_gpio->base_addr, IRQ1, irq_clr_value >> 8 ); + HAL_set_8bit_reg( this_gpio->base_addr, IRQ2, irq_clr_value >> 16 ); + HAL_set_8bit_reg( this_gpio->base_addr, IRQ3, irq_clr_value >> 24 ); + break; + + default: + HAL_ASSERT(0); + break; + } +} + +/*-------------------------------------------------------------------------*//** + * GPIO_get_irq_sources + * See "core_gpio.h" for details of how to use this function. + */ +uint32_t GPIO_get_irq_sources +( + gpio_instance_t * this_gpio +) +{ + uint32_t intr_src = 0; + + switch( this_gpio->apb_bus_width ) + { + case GPIO_APB_32_BITS_BUS: + intr_src = HAL_get_32bit_reg( this_gpio->base_addr, IRQ ); + break; + + case GPIO_APB_16_BITS_BUS: + intr_src |= HAL_get_16bit_reg( this_gpio->base_addr, IRQ0 ); + intr_src |= (HAL_get_16bit_reg( this_gpio->base_addr, IRQ1 ) << 16); + break; + + case GPIO_APB_8_BITS_BUS: + intr_src |= HAL_get_16bit_reg( this_gpio->base_addr, IRQ0 ); + intr_src |= (HAL_get_16bit_reg( this_gpio->base_addr, IRQ1 ) << 8); + intr_src |= (HAL_get_16bit_reg( this_gpio->base_addr, IRQ2 ) << 16); + intr_src |= (HAL_get_16bit_reg( this_gpio->base_addr, IRQ3 ) << 24); + break; + + default: + HAL_ASSERT(0); + break; + } + + return intr_src; +} + +/*-------------------------------------------------------------------------*//** + * GPIO_clear_all_irq_sources + * See "core_gpio.h" for details of how to use this function. + */ +void GPIO_clear_all_irq_sources +( + gpio_instance_t * this_gpio, + uint32_t bitmask +) +{ + uint32_t irq_clr_value = bitmask; + + switch( this_gpio->apb_bus_width ) + { + case GPIO_APB_32_BITS_BUS: + HAL_set_32bit_reg( this_gpio->base_addr, IRQ, irq_clr_value ); + break; + + case GPIO_APB_16_BITS_BUS: + HAL_set_16bit_reg( this_gpio->base_addr, IRQ0, irq_clr_value ); + HAL_set_16bit_reg( this_gpio->base_addr, IRQ1, irq_clr_value >> 16 ); + break; + + case GPIO_APB_8_BITS_BUS: + HAL_set_8bit_reg( this_gpio->base_addr, IRQ0, irq_clr_value ); + HAL_set_8bit_reg( this_gpio->base_addr, IRQ1, irq_clr_value >> 8 ); + HAL_set_8bit_reg( this_gpio->base_addr, IRQ2, irq_clr_value >> 16 ); + HAL_set_8bit_reg( this_gpio->base_addr, IRQ3, irq_clr_value >> 24 ); + break; + + default: + HAL_ASSERT(0); + break; + } +} diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreGPIO/core_gpio.h b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreGPIO/core_gpio.h new file mode 100644 index 0000000..3491d68 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreGPIO/core_gpio.h @@ -0,0 +1,654 @@ +/******************************************************************************* + * (c) Copyright 2008-2021 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * @file core_gpio.h + * @author Microchip FPGA Embedded Systems Solutions + * @brief CoreGPIO bare metal driver public API. + * + */ + +/*=========================================================================*//** + @mainpage CoreGPIO Bare Metal Driver. + + @section intro_sec Introduction + The CoreGPIO hardware IP includes up to 32 general purpose input output GPIOs. + This driver provides a set of functions for controlling the GPIOs as part of a + bare metal system where no operating system is available. These drivers + can be adapted for use as part of an operating system but the implementation + of the adaptation layer between this driver and the operating system's driver + model is outside the scope of this driver. + + @section driver_configuration Driver Configuration + The CoreGPIO individual IOs can be configured either in the hardware flow or + as part of the software application through calls to the GPIO_config() function. + GPIOs configured as as part of the hardware is fixed and cannot be modified + using a call to the GPI_config() function. + + @section theory_op Theory of Operation + The CoreGPIO driver uses the Actel Hardware Abstraction Layer (HAL) to access + hardware registers. You must ensure that the Actel HAL is included as part of + your software project. The Actel HAL is available through the Actel Firmware + Catalog. + + The CoreGPIO driver functions are logically grouped into the following groups: + - Initialization + - Configuration + - Reading and writing GPIO state + - Interrupt control + + The CoreGPIO driver is initialized through a call to the GPIO_init() function. + The GPIO_init() function must be called before any other GPIO driver functions + can be called. + + Each GPIO port is individually configured through a call to the + GPIO_config() function. Configuration includes deciding if a GPIO port + will be used as input, output or both. GPIO ports configured as inputs can be + further configured to generate interrupts based on the input's state. + Interrupts can be level or edge sensitive. + Please note that a CoreGPIO hardware instance can be generated, as part of the + hardware flow, with a fixed configuration for some or all of its IOs. Attempting + to modify the configuration of such a hardware configured IO using the + GPIO_config() function has no effect. + + The state of the GPIO ports can be read and written using the following + functions: + - GPIO_get_inputs() + - GPIO_get_outputs() + - GPIO_set_outputs() + - GPIO_drive_inout() + + Interrupts generated by GPIO ports configured as inputs are controlled using + the following functions: + - GPIO_enable_irq() + - GPIO_disable_irq() + - GPIO_clear_irq() + - GPIO_get_irq_sources() + - GPIO_clear_all_irq_sources() + + *//*=========================================================================*/ +#ifndef CORE_GPIO_H_ +#define CORE_GPIO_H_ + +#ifndef LEGACY_DIR_STRUCTURE +#include "hal/hal.h" + +#else +#include "hal.h" +#endif + +/*-------------------------------------------------------------------------*//** + The gpio_id_t enumeration is used to identify GPIOs as part of the + parameter to functions: + - GPIO_config(), + - GPIO_drive_inout(), + - GPIO_enable_int(), + - GPIO_disable_int(), + - GPIO_clear_int() + */ +typedef enum __gpio_id_t +{ + GPIO_0 = 0, + GPIO_1 = 1, + GPIO_2 = 2, + GPIO_3 = 3, + GPIO_4 = 4, + GPIO_5 = 5, + GPIO_6 = 6, + GPIO_7 = 7, + GPIO_8 = 8, + GPIO_9 = 9, + GPIO_10 = 10, + GPIO_11 = 11, + GPIO_12 = 12, + GPIO_13 = 13, + GPIO_14 = 14, + GPIO_15 = 15, + GPIO_16 = 16, + GPIO_17 = 17, + GPIO_18 = 18, + GPIO_19 = 19, + GPIO_20 = 20, + GPIO_21 = 21, + GPIO_22 = 22, + GPIO_23 = 23, + GPIO_24 = 24, + GPIO_25 = 25, + GPIO_26 = 26, + GPIO_27 = 27, + GPIO_28 = 28, + GPIO_29 = 29, + GPIO_30 = 30, + GPIO_31 = 31 +} gpio_id_t; + +typedef enum __gpio_apb_width_t +{ + GPIO_APB_8_BITS_BUS = 0, + GPIO_APB_16_BITS_BUS = 1, + GPIO_APB_32_BITS_BUS = 2, + GPIO_APB_UNKNOWN_BUS_WIDTH = 3 +} gpio_apb_width_t; + +/*-------------------------------------------------------------------------*//** + */ +typedef struct __gpio_instance_t +{ + addr_t base_addr; + gpio_apb_width_t apb_bus_width; +} gpio_instance_t; + +/*-------------------------------------------------------------------------*//** + GPIO ports definitions used to identify GPIOs as part of the parameter to + function GPIO_set_outputs(). + These definitions can also be used to identity GPIO through logical + operations on the return value of function GPIO_get_inputs(). + */ +#define GPIO_0_MASK 0x00000001UL +#define GPIO_1_MASK 0x00000002UL +#define GPIO_2_MASK 0x00000004UL +#define GPIO_3_MASK 0x00000008UL +#define GPIO_4_MASK 0x00000010UL +#define GPIO_5_MASK 0x00000020UL +#define GPIO_6_MASK 0x00000040UL +#define GPIO_7_MASK 0x00000080UL +#define GPIO_8_MASK 0x00000100UL +#define GPIO_9_MASK 0x00000200UL +#define GPIO_10_MASK 0x00000400UL +#define GPIO_11_MASK 0x00000800UL +#define GPIO_12_MASK 0x00001000UL +#define GPIO_13_MASK 0x00002000UL +#define GPIO_14_MASK 0x00004000UL +#define GPIO_15_MASK 0x00008000UL +#define GPIO_16_MASK 0x00010000UL +#define GPIO_17_MASK 0x00020000UL +#define GPIO_18_MASK 0x00040000UL +#define GPIO_19_MASK 0x00080000UL +#define GPIO_20_MASK 0x00100000UL +#define GPIO_21_MASK 0x00200000UL +#define GPIO_22_MASK 0x00400000UL +#define GPIO_23_MASK 0x00800000UL +#define GPIO_24_MASK 0x01000000UL +#define GPIO_25_MASK 0x02000000UL +#define GPIO_26_MASK 0x04000000UL +#define GPIO_27_MASK 0x08000000UL +#define GPIO_28_MASK 0x10000000UL +#define GPIO_29_MASK 0x20000000UL +#define GPIO_30_MASK 0x40000000UL +#define GPIO_31_MASK 0x80000000UL + +/*-------------------------------------------------------------------------*//** + * GPIO modes + */ +#define GPIO_INPUT_MODE 0x0000000002UL +#define GPIO_OUTPUT_MODE 0x0000000005UL +#define GPIO_INOUT_MODE 0x0000000003UL + +/*-------------------------------------------------------------------------*//** + * Possible GPIO inputs interrupt configurations. + */ +#define GPIO_IRQ_LEVEL_HIGH 0x0000000000UL +#define GPIO_IRQ_LEVEL_LOW 0x0000000020UL +#define GPIO_IRQ_EDGE_POSITIVE 0x0000000040UL +#define GPIO_IRQ_EDGE_NEGATIVE 0x0000000060UL +#define GPIO_IRQ_EDGE_BOTH 0x0000000080UL + +/*-------------------------------------------------------------------------*//** + * Possible states for GPIO configured as INOUT. + */ +typedef enum gpio_inout_state +{ + GPIO_DRIVE_LOW = 0, + GPIO_DRIVE_HIGH, + GPIO_HIGH_Z +} gpio_inout_state_t; + +/*-------------------------------------------------------------------------*//** + The GPIO_init() function initialises a CoreGPIO hardware instance and the data + structure associated with the CoreGPIO hardware instance. + Please note that a CoreGPIO hardware instance can be generated with a fixed + configuration for some or all of its IOs as part of the hardware flow. Attempting + to modify the configuration of such a hardware configured IO using the + GPIO_config() function has no effect. + + @param this_gpio + Pointer to the gpio_instance_t data structure instance holding all data + regarding the CoreGPIO hardware instance being initialized. A pointer to the + same data structure will be used in subsequent calls to the CoreGPIO driver + functions in order to identify the CoreGPIO instance that should perform the + operation implemented by the called driver function. + + @param base_addr + The base_addr parameter is the base address in the processor's memory map for + the registers of the GPIO instance being initialized. + + @param bus_width + The bus_width parameter informs the driver of the APB bus width selected during + the hardware flow configuration of the CoreGPIO hardware instance. It indicates + to the driver whether the CoreGPIO hardware registers will be visible as 8, 16 + or 32 bits registers. Allowed value are: + - GPIO_APB_8_BITS_BUS + - GPIO_APB_16_BITS_BUS + - GPIO_APB_32_BITS_BUS + + @return + none. + + Example: + @code + #define COREGPIO_BASE_ADDR 0xC2000000 + + gpio_instance_t g_gpio; + + void system_init( void ) + { + GPIO_init( &g_gpio, COREGPIO_BASE_ADDR, GPIO_APB_32_BITS_BUS ); + } + @endcode + */ +void GPIO_init +( + gpio_instance_t * this_gpio, + addr_t base_addr, + gpio_apb_width_t bus_width +); + +/*-------------------------------------------------------------------------*//** + The GPIO_config() function is used to configure an individual GPIO port. + + @param this_gpio + The this_gpio parameter is a pointer to the gpio_instance_t structure holding + all data regarding the CoreGPIO instance controlled through this function call. + + @param port_id + The port_id parameter identifies the GPIO port to be configured. + An enumeration item of the form GPIO_n where n is the number of the GPIO + port is used to identify the GPIO port. For example GPIO_0 identifies the + first GPIO port and GPIO_31 the last one. + + @param config + The config parameter specifies the configuration to be applied to the GPIO + port identified by the first parameter. It is a logical OR of GPIO mode and + the interrupt mode. The interrupt mode is only relevant if the GPIO is + configured as input. + Possible modes are: + - GPIO_INPUT_MODE, + - GPIO_OUTPUT_MODE, + - GPIO_INOUT_MODE. + Possible interrupt modes are: + - GPIO_IRQ_LEVEL_HIGH, + - GPIO_IRQ_LEVEL_LOW, + - GPIO_IRQ_EDGE_POSITIVE, + - GPIO_IRQ_EDGE_NEGATIVE, + - GPIO_IRQ_EDGE_BOTH + + @return + none. + + For example the following call will configure GPIO 4 as an input generating + interrupts on a low to high transition of the input: + @code + GPIO_config( &g_gpio, GPIO_4, GPIO_INPUT_MODE | GPIO_IRQ_EDGE_POSITIVE ); + @endcode + */ +void GPIO_config +( + gpio_instance_t * this_gpio, + gpio_id_t port_id, + uint32_t config +); + +/*-------------------------------------------------------------------------*//** + The GPIO_set_outputs() function is used to set the state of the GPIO ports + configured as outputs. + + @param this_gpio + The this_gpio parameter is a pointer to the gpio_instance_t structure holding + all data regarding the CoreGPIO instance controlled through this function call. + + @param value + The value parameter specifies the state of the GPIO ports configured as + outputs. It is a bit mask of the form (GPIO_n_MASK | GPIO_m_MASK) where n + and m are numbers identifying GPIOs. + For example (GPIO_0_MASK | GPIO_1_MASK | GPIO_2_MASK ) specifies that the + first, second and third GPIOs' must be set high and all other outputs set + low. + + @return + none. + + Example 1: + Set GPIOs outputs 0 and 8 high and all other GPIO outputs low. + @code + GPIO_set_outputs( &g_gpio, GPIO_0_MASK | GPIO_8_MASK ); + @endcode + + Example 2: + Set GPIOs outputs 2 and 4 low without affecting other GPIO outputs. + @code + uint32_t gpio_outputs; + gpio_outputs = GPIO_get_outputs( &g_gpio ); + gpio_outputs &= ~( GPIO_2_MASK | GPIO_4_MASK ); + GPIO_set_outputs( &g_gpio, gpio_outputs ); + @endcode + + @see GPIO_get_outputs() + */ +void GPIO_set_outputs +( + gpio_instance_t * this_gpio, + uint32_t value +); + +/*-------------------------------------------------------------------------*//** + The GPIO_set_output() function is used to set the state of a single GPIO + port configured as output. + + @param this_gpio + The this_gpio parameter is a pointer to the gpio_instance_t structure holding + all data regarding the CoreGPIO instance controlled through this function call. + + @param port_id + The port_id parameter specifies the GPIO port that will have its output set + by a call to this function. + + @param value + The value parameter specifies the desired state for the GPIO output. A value + of 0 will set the output low and a value of 1 will set the port high. + + @return + none. + */ +void GPIO_set_output +( + gpio_instance_t * this_gpio, + gpio_id_t port_id, + uint8_t value +); + +/*-------------------------------------------------------------------------*//** + The GPIO_get_inputs() function is used to read the state of all GPIOs + configured as inputs. + + @param this_gpio + The this_gpio parameter is a pointer to the gpio_instance_t structure holding + all data regarding the CoreGPIO instance controlled through this function call. + + @return + This function returns a 32 bit unsigned integer where each bit represents + the state of an input. The least significant bit representing the state of + GPIO 0 and the most significant bit the state of GPIO 31. + */ +uint32_t GPIO_get_inputs +( + gpio_instance_t * this_gpio +); + +/*-------------------------------------------------------------------------*//** + The GPIO_get_outputs() function is used to read the current state of all + GPIO outputs. + + @param this_gpio + The this_gpio parameter is a pointer to the gpio_instance_t structure holding + all data regarding the CoreGPIO instance controlled through this function call. + + @return + This function returns a 32 bit unsigned integer where each bit represents + the state of an output. The least significant bit representing the state + of GPIO 0 and the most significant bit the state of GPIO 31. + */ +uint32_t GPIO_get_outputs +( + gpio_instance_t * this_gpio +); + +/*-------------------------------------------------------------------------*//** + The GPIO_drive_inout() function is used to set the output state of a + GPIO configured as INOUT. An INOUT GPIO can be in one of three states: + - high + - low + - high impedance + An INOUT output would typically be used where several devices can drive the + state of a signal. The high and low states are equivalent to the high and low + states of a GPIO configured as output. The high impedance state is used to + prevent the GPIO from driving the state of the output and therefore allow + reading the state of the GPIO as an input. + Please note that the GPIO port you wish to use as INOUT through this function + must be configurable through software. Therefore the GPIO ports used as INOUT + must not have a fixed configuration selected as part of the hardware flow. + + @param this_gpio + The this_gpio parameter is a pointer to the gpio_instance_t structure holding + all data regarding the CoreGPIO instance controlled through this function call. + + @param port_id + The port_id parameter identifies the GPIO for which this function will + change the output state. + An enumeration item of the form GPIO_n where n is the number of the GPIO + port is used to identify the GPIO port. For example GPIO_0 identifies the + first GPIO port and GPIO_31 the last one. + + @param inout_state + The inout_state parameter specifies the state of the I/O identified by the + first parameter. Possible states are: + - GPIO_DRIVE_HIGH, + - GPIO_DRIVE_LOW, + - GPIO_HIGH_Z (high impedance) + + @return + none. + + Example: + The call to GPIO_drive_inout() below will set the GPIO 7 output to + high impedance state. + @code + GPIO_drive_inout( &g_gpio, GPIO_7, GPIO_HIGH_Z ); + @endcode + */ +void GPIO_drive_inout +( + gpio_instance_t * this_gpio, + gpio_id_t port_id, + gpio_inout_state_t inout_state +); + +/*-------------------------------------------------------------------------*//** + The GPIO_enable_irq() function is used to enable an interrupt to be + generated based on the state of the input identified as parameter. + + @param this_gpio + The this_gpio parameter is a pointer to the gpio_instance_t structure holding + all data regarding the CoreGPIO instance controlled through this function call. + + @param port_id + The port_id parameter identifies the GPIO input the call to + GPIO_enable_irq() will enable to generate interrupts. + An enumeration item of the form GPIO_n where n is the number of the GPIO + port is used to identify the GPIO port. For example GPIO_0 identifies the + first GPIO port and GPIO_31 the last one. + + @return + none. + + Example: + The call to GPIO_enable_irq() below will allow GPIO 8 to generate + interrupts. + @code + GPIO_enable_irq( &g_gpio, GPIO_8 ); + @endcode + */ +void GPIO_enable_irq +( + gpio_instance_t * this_gpio, + gpio_id_t port_id +); + +/*-------------------------------------------------------------------------*//** + The GPIO_disable_irq() function is used to disable interrupt from being + generated based on the state of the input specified as parameter. + + @param this_gpio + The this_gpio parameter is a pointer to the gpio_instance_t structure holding + all data regarding the CoreGPIO instance controlled through this function call. + + @param port_id + The port_id parameter identifies the GPIO input the call to + GPIO_disable_irq() will disable from generating interrupts. + An enumeration item of the form GPIO_n where n is the number of the GPIO + port is used to identify the GPIO port. For example GPIO_0 identifies the + first GPIO port and GPIO_31 the last one. + + @return + none. + + Example: + The call to GPIO_disable_irq() below will prevent GPIO 8 from generating + interrupts. + @code + GPIO_disable_irq( &g_gpio, GPIO_8 ); + @endcode + */ +void GPIO_disable_irq +( + gpio_instance_t * this_gpio, + gpio_id_t port_id +); + +/*-------------------------------------------------------------------------*//** + The GPIO_clear_irq() function is used to clear the interrupt generated by + the GPIO specified as parameter. The GPIO_clear_irq() function must be + called as part of a GPIO interrupt service routine (ISR) in order to prevent + the same interrupt event re-triggering a call to the GPIO ISR. + Please note that interrupts may also need to be cleared in the processor's + interrupt controller. + + @param this_gpio + The this_gpio parameter is a pointer to the gpio_instance_t structure holding + all data regarding the CoreGPIO instance controlled through this function call. + + @param port_id + The port_id parameter identifies the GPIO input for which to clear the + interrupt. + An enumeration item of the form GPIO_n where n is the number of the GPIO + port is used to identify the GPIO port. For example GPIO_0 identifies the + first GPIO port and GPIO_31 the last one. + + @return + none. + + Example: + The example below demonstrates the use of the GPIO_clear_irq() function as + part of the GPIO 9 interrupt service routine. + @code + void GPIO9_IRQHandler( void ) + { + do_interrupt_processing(); + + GPIO_clear_irq( &g_gpio, GPIO_9 ); + + NVIC_ClearPendingIRQ( GPIO9_IRQn ); + } + @endcode + */ +void GPIO_clear_irq +( + gpio_instance_t * this_gpio, + gpio_id_t port_id +); + +/*-------------------------------------------------------------------------*//** + The GPIO_get_irq_sources() function is used to identify the source of + interrupt. i.e. the GPIO input line whose state change triggered the interrupt. + The GPIO_get_irq_sources() function must be called as part of a GPIO + interrupt service routine (ISR) in order to determine the interrupt source. + + @param this_gpio + The this_gpio parameter is a pointer to the gpio_instance_t structure holding + all data regarding the CoreGPIO instance controlled through this function call. + + @return + This function returns a 32 bit unsigned integer where each bit represents + the pin number of GPIO. + + Example: + The example below demonstrates the use of the GPIO_get_irq_sources() function + as part of the GPIO 9 interrupt service routine. + @code + void GPIO9_IRQHandler( void ) + { + do_interrupt_processing(); + + GPIO_clear_all_irq_sources(g_p_mygpio, GPIO_get_irq_sources(g_p_mygpio)); + + NVIC_ClearPendingIRQ( GPIO9_IRQn ); + } + @endcode + */ +uint32_t GPIO_get_irq_sources +( + gpio_instance_t * this_gpio +); + +/*-------------------------------------------------------------------------*//** + The GPIO_clear_all_irq_sources() function is used to clear the all the active + interrupt generated by the GPIO specified as parameter. The + GPIO_clear_all_irq_sources() function must be called as part of a GPIO interrupt + service routine (ISR) in order to prevent the same interrupt event + re-triggering a call to the GPIO ISR. + Please note that interrupts may also need to be cleared in the processor's + interrupt controller. + + @param this_gpio + The this_gpio parameter is a pointer to the gpio_instance_t structure holding + all data regarding the CoreGPIO instance controlled through this function call. + + @param bitmask + This bitmask parameter is a 32 bit unsigned integer where each bit represents + the GPIO pin used to clears the interrupt bit register of the corresponding + GPIO bit. The least significant bit representing the status of GPIO 0 and + the most significant bit the status of GPIO 31. + + @return + none. + + Example: + The example below demonstrates the use of the GPIO_clear_all_irq_sources() function as + part of the GPIO 9 interrupt service routine. + @code + void GPIO9_IRQHandler( void ) + { + do_interrupt_processing(); + + do_interrupt_processing(); + + GPIO_clear_all_irq_sources(g_p_mygpio, GPIO_get_irq_sources(g_p_mygpio)); + + NVIC_ClearPendingIRQ( GPIO9_IRQn ); + } + @endcode + */ +void GPIO_clear_all_irq_sources +( + gpio_instance_t * this_gpio, + uint32_t bitmask +); +#endif /* CORE_GPIO_H_ */ diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreGPIO/coregpio_regs.h b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreGPIO/coregpio_regs.h new file mode 100644 index 0000000..0c13e28 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreGPIO/coregpio_regs.h @@ -0,0 +1,43 @@ +/******************************************************************************* + * (c) Copyright 2008-2021 Microchip FPGA Embedded Systems Solutions. + * + * @file coregpio_regs.h + * @author Microchip FPGA Embedded Systems Solutions + * @brief CoreGPIO register definitions + * + */ + +#ifndef __CORE_GPIO_REGISTERS_H +#define __CORE_GPIO_REGISTERS_H 1 + +/*------------------------------------------------------------------------------ + * + */ +#define IRQ_REG_OFFSET 0x80 + +#define IRQ0_REG_OFFSET 0x80 +#define IRQ1_REG_OFFSET 0x84 +#define IRQ2_REG_OFFSET 0x88 +#define IRQ3_REG_OFFSET 0x8C + +/*------------------------------------------------------------------------------ + * + */ +#define GPIO_IN_REG_OFFSET 0x90 + +#define GPIO_IN0_REG_OFFSET 0x90 +#define GPIO_IN1_REG_OFFSET 0x94 +#define GPIO_IN2_REG_OFFSET 0x98 +#define GPIO_IN3_REG_OFFSET 0x9C + +/*------------------------------------------------------------------------------ + * + */ +#define GPIO_OUT_REG_OFFSET 0xA0 + +#define GPIO_OUT0_REG_OFFSET 0xA0 +#define GPIO_OUT1_REG_OFFSET 0xA4 +#define GPIO_OUT2_REG_OFFSET 0xA8 +#define GPIO_OUT3_REG_OFFSET 0xAC + +#endif /* __CORE_GPIO_REGISTERS_H */ diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreSPI/core_spi.c b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreSPI/core_spi.c new file mode 100644 index 0000000..926b758 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreSPI/core_spi.c @@ -0,0 +1,1138 @@ +/******************************************************************************* + * (c) Copyright 2007-2022 Microchip FPGA Embedded Systems Solutions. + * + * @file core_uart_apb.c + * @author Microchip FPGA Embedded Systems Solutions + * @brief CoreSPI driver implementation. See "core_spi.h" for description of + * the functions implemented in this file. + * + */ + +#include "core_spi.h" +#include "corespi_regs.h" +#include + +/******************************************************************************* + * Null parameters with appropriate type definitions + */ +#define NULL_ADDR ( ( addr_t ) 0u ) +#define NULL_INSTANCE ( ( spi_instance_t * ) 0u ) +#define NULL_BUFF ( ( uint8_t * ) 0u ) +#define NULL_FRAME_HANDLER ( ( spi_frame_rx_handler_t ) 0u ) +#define NULL_BLOCK_HANDLER ( ( spi_block_rx_handler_t ) 0u ) +#define NULL_SLAVE_TX_UPDATE_HANDLER ( ( spi_slave_frame_tx_handler_t ) 0u ) +#define NULL_SLAVE_CMD_HANDLER NULL_BLOCK_HANDLER + +#define SPI_ALL_INTS (0xFFu) /* For clearing all active interrupts */ + +/******************************************************************************* + * Possible states for different register bit fields + */ + +#define DISABLE 0u +#define ENABLE 1u + + +/******************************************************************************* + * Function return values + */ +enum { + FAILURE = 0u, + SUCCESS = 1u +}; + +/******************************************************************************* + * Local function declarations + */ +static void fill_slave_tx_fifo( spi_instance_t * this_spi ); +static void read_slave_rx_fifo( spi_instance_t * this_spi ); +static void recover_from_rx_overflow( const spi_instance_t * this_spi ); + +/******************************************************************************* + * SPI_init() + * See "core_spi.h" for details of how to use this function. + */ +void SPI_init +( + spi_instance_t * this_spi, + addr_t base_addr, + uint16_t fifo_depth +) +{ + HAL_ASSERT( NULL_INSTANCE != this_spi ); + HAL_ASSERT( NULL_ADDR != base_addr ); + HAL_ASSERT( SPI_MAX_FIFO_DEPTH >= fifo_depth ); + HAL_ASSERT( SPI_MIN_FIFO_DEPTH <= fifo_depth ); + + if( ( NULL_INSTANCE != this_spi ) && ( base_addr != NULL_ADDR ) ) + { + /* + * Initialize all transmit / receive buffers and handlers + * + * Relies on the fact that byte filling with 0x00 will equate + * to 0 for any non byte sized items too. + */ + + /* First fill struct with 0s */ + memset( this_spi, 0, sizeof(spi_instance_t) ); + + /* Configure CoreSPI instance attributes */ + this_spi->base_addr = (addr_t)base_addr; + + /* Store FIFO depth or fall back to minimum if out of range */ + if( ( SPI_MAX_FIFO_DEPTH >= fifo_depth ) && ( SPI_MIN_FIFO_DEPTH <= fifo_depth ) ) + { + this_spi->fifo_depth = fifo_depth; + } + else + { + this_spi->fifo_depth = SPI_MIN_FIFO_DEPTH; + } + /* Make sure the CoreSPI is disabled while we configure it */ + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL1_ENABLE, DISABLE ); + + /* Ensure all slaves are deselected */ + HAL_set_8bit_reg( this_spi->base_addr, SSEL, 0u ); + + /* Flush the receive and transmit FIFOs*/ + HAL_set_8bit_reg( this_spi->base_addr, CMD, CMD_TXFIFORST_MASK | CMD_RXFIFORST_MASK ); + + /* Clear all interrupts */ + HAL_set_8bit_reg( this_spi->base_addr, INTCLR, SPI_ALL_INTS ); + + /* Ensure RXAVAIL, TXRFM, SSEND and CMDINT are disabled */ + HAL_set_8bit_reg( this_spi->base_addr, CTRL2, 0u ); + /* + * Enable the CoreSPI in the reset default of master mode + * with TXUNDERRUN, RXOVFLOW and TXDONE interrupts disabled. + * The driver does not currently use interrupts in master mode. + */ + HAL_set_8bit_reg( this_spi->base_addr, CTRL1, ENABLE | CTRL1_MASTER_MASK ); + } +} + +/***************************************************************************//** + * SPI_configure_slave_mode() + * See "core_spi.h" for details of how to use this function. + */ +void SPI_configure_slave_mode +( + spi_instance_t * this_spi +) +{ + HAL_ASSERT( NULL_INSTANCE != this_spi ); + + if( NULL_INSTANCE != this_spi ) + { + /* Don't yet know what slave transfer mode will be used */ + this_spi->slave_xfer_mode = SPI_SLAVE_XFER_NONE; + + /* Make sure the CoreSPI is disabled while we configure it */ + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL1_ENABLE, DISABLE ); + + /* Flush the receive and transmit FIFOs*/ + HAL_set_8bit_reg( this_spi->base_addr, CMD, CMD_TXFIFORST_MASK | CMD_RXFIFORST_MASK ); + + /* Clear all interrupts */ + HAL_set_8bit_reg( this_spi->base_addr, INTCLR, SPI_ALL_INTS ); + + /* Ensure RXAVAIL, TXRFM, SSEND and CMDINT are disabled */ + HAL_set_8bit_reg( this_spi->base_addr, CTRL2, 0u ); + /* + * Enable the CoreSPI in slave mode with TXUNDERRUN, RXOVFLOW and TXDONE + * interrupts disabled. The appropriate interrupts will be enabled later + * on when the transfer mode is configured. + */ + HAL_set_8bit_reg( this_spi->base_addr, CTRL1, ENABLE ); + } +} + +/***************************************************************************//** + * SPI_configure_master_mode() + * See "core_spi.h" for details of how to use this function. + */ +void SPI_configure_master_mode +( + spi_instance_t * this_spi +) +{ + HAL_ASSERT( NULL_INSTANCE != this_spi ); + + if( NULL_INSTANCE != this_spi ) + { + /* Disable the CoreSPI for a little while, while we configure the CoreSPI */ + HAL_set_8bit_reg_field(this_spi->base_addr, CTRL1_ENABLE, DISABLE); + + /* Reset slave transfer mode to unknown in case it has been set previously */ + this_spi->slave_xfer_mode = SPI_SLAVE_XFER_NONE; + + /* Flush the receive and transmit FIFOs*/ + HAL_set_8bit_reg( this_spi->base_addr, CMD, CMD_TXFIFORST_MASK | CMD_RXFIFORST_MASK ); + + /* Clear all interrupts */ + HAL_set_8bit_reg( this_spi->base_addr, INTCLR, SPI_ALL_INTS ); + + /* Ensure RXAVAIL, TXRFM, SSEND and CMDINT are disabled */ + HAL_set_8bit_reg( this_spi->base_addr, CTRL2, 0u ); + + /* Enable the CoreSPI in master mode with TXUNDERRUN, RXOVFLOW and TXDONE interrupts disabled */ + HAL_set_8bit_reg( this_spi->base_addr, CTRL1, ENABLE | CTRL1_MASTER_MASK ); + } +} + +/***************************************************************************//** + * SPI_set_slave_select() + * See "core_spi.h" for details of how to use this function. + */ +void SPI_set_slave_select +( + spi_instance_t * this_spi, + spi_slave_t slave +) +{ + spi_slave_t temp = (spi_slave_t)(0x00u) ; + + HAL_ASSERT( NULL_INSTANCE != this_spi ); + HAL_ASSERT( SPI_MAX_NB_OF_SLAVES > slave ); + + if( ( NULL_INSTANCE != this_spi ) && ( SPI_MAX_NB_OF_SLAVES > slave ) ) + { + /* This function is only intended to be used with an SPI master */ + if( DISABLE != HAL_get_8bit_reg_field(this_spi->base_addr, CTRL1_MASTER ) ) + { + /* Recover from receiver overflow because of previous slave */ + if( ENABLE == HAL_get_8bit_reg_field(this_spi->base_addr, STATUS_RXOVFLOW ) ) + { + recover_from_rx_overflow( this_spi ); + } + /* Set the correct slave select bit */ + temp = (spi_slave_t)( HAL_get_8bit_reg( this_spi->base_addr, SSEL ) | ((uint32_t)1u << (uint32_t)slave) ); + HAL_set_8bit_reg( this_spi->base_addr, SSEL, (uint_fast8_t)temp ); + } + } +} + +/***************************************************************************//** + * SPI_clear_slave_select() + * See "core_spi.h" for details of how to use this function. + */ +void SPI_clear_slave_select +( + spi_instance_t * this_spi, + spi_slave_t slave +) +{ + spi_slave_t temp = (spi_slave_t) (0x00u) ; + + HAL_ASSERT( NULL_INSTANCE != this_spi ); + HAL_ASSERT( SPI_MAX_NB_OF_SLAVES > slave ); + + if( ( NULL_INSTANCE != this_spi ) && ( SPI_MAX_NB_OF_SLAVES > slave ) ) + { + /* This function is only intended to be used with an SPI master. */ + if( DISABLE != HAL_get_8bit_reg_field(this_spi->base_addr, CTRL1_MASTER ) ) + { + /* Recover from receiver overflow because of previous slave */ + if( ENABLE == HAL_get_8bit_reg_field(this_spi->base_addr, STATUS_RXOVFLOW) ) + { + recover_from_rx_overflow( this_spi ); + } + /* Clear the correct slave select bit */ + temp = (spi_slave_t)( HAL_get_8bit_reg( this_spi->base_addr, SSEL ) & ~((uint32_t)1u << (uint32_t)slave) ); + HAL_set_8bit_reg( this_spi->base_addr, SSEL, (uint_fast8_t)temp ) ; + } + } +} + +/***************************************************************************//** + * SPI_transfer_frame() + * See "core_spi.h" for details of how to use this function. + */ +uint32_t SPI_transfer_frame +( + spi_instance_t * this_spi, + uint32_t tx_bits +) +{ + volatile uint32_t rx_data = 0u; /* Ensure consistent return value if in slave mode */ + + HAL_ASSERT( NULL_INSTANCE != this_spi ); + + if( NULL_INSTANCE != this_spi ) + { + /* This function is only intended to be used with an SPI master. */ + if( DISABLE != HAL_get_8bit_reg_field(this_spi->base_addr, CTRL1_MASTER ) ) + { + /* Flush the receive and transmit FIFOs by resetting both */ + HAL_set_8bit_reg(this_spi->base_addr, CMD, CMD_TXFIFORST_MASK | CMD_RXFIFORST_MASK); + + /* Send frame. */ + HAL_set_32bit_reg( this_spi->base_addr, TXLAST, tx_bits ); + + /* Wait for frame Tx to complete. */ + while ( ENABLE != HAL_get_8bit_reg_field(this_spi->base_addr, STATUS_DONE ) ) + { + ; + } + + /* Read received frame. */ + rx_data = HAL_get_32bit_reg( this_spi->base_addr, RXDATA ); + } + } + + /* Finally, return the frame we received from the slave or 0 */ + return( rx_data ); +} + + +/***************************************************************************//** + * SPI_transfer_block() + * See "core_spi.h" for details of how to use this function. + */ +void SPI_transfer_block +( + spi_instance_t * this_spi, + const uint8_t * cmd_buffer, + uint16_t cmd_byte_size, + uint8_t * rx_buffer, + uint16_t rx_byte_size +) +{ + uint32_t transfer_size = 0U; /* Total number of bytes to transfer. */ + uint16_t transfer_idx = 0U; /* Number of bytes transferred so far */ + uint16_t tx_idx = 0u; /* Number of valid data bytes sent */ + uint16_t rx_idx = 0u; /* Number of valid response bytes received */ + uint16_t transit = 0U; /* Number of bytes "in flight" to avoid FIFO errors */ + + HAL_ASSERT( NULL_INSTANCE != this_spi ); + + if( NULL_INSTANCE != this_spi ) + { + /* This function is only intended to be used with an SPI master. */ + if( ( DISABLE != HAL_get_8bit_reg_field(this_spi->base_addr, CTRL1_MASTER ) ) && + /* Check for empty transfer as well */ + ( 0u != ( (uint32_t)cmd_byte_size + (uint32_t)rx_byte_size ) ) ) + { + /* + * tansfer_size is one less than the real amount as we have to write + * the last frame separately to trigger the slave deselect in case + * the SPS option is in place. + */ + transfer_size = ( (uint32_t)cmd_byte_size + (uint32_t)rx_byte_size ) - 1u; + /* Flush the receive and transmit FIFOs */ + HAL_set_8bit_reg(this_spi->base_addr, CMD, (uint32_t)(CMD_TXFIFORST_MASK | CMD_RXFIFORST_MASK )); + + /* Recover from receiver overflow because of previous slave */ + if( ENABLE == HAL_get_8bit_reg_field(this_spi->base_addr, STATUS_RXOVFLOW) ) + { + recover_from_rx_overflow( this_spi ); + } + + /* Disable the Core SPI for a little bit, while we load the TX FIFO */ + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL1_ENABLE, DISABLE ); + + while( ( tx_idx < transfer_size ) && ( tx_idx < this_spi->fifo_depth ) ) + { + if( tx_idx < cmd_byte_size ) + { + /* Push out valid data */ + HAL_set_32bit_reg( this_spi->base_addr, TXDATA, (uint32_t)cmd_buffer[tx_idx] ); + } + else + { + /* Push out 0s to get data back from slave */ + HAL_set_32bit_reg( this_spi->base_addr, TXDATA, 0U ); + } + ++transit; + ++tx_idx; + } + + /* If room left to put last frame in before the off, then do it */ + if( ( tx_idx == transfer_size ) && ( tx_idx < this_spi->fifo_depth ) ) + { + if( tx_idx < cmd_byte_size ) + { + /* Push out valid data, not expecting any reply this time */ + HAL_set_32bit_reg( this_spi->base_addr, TXLAST, (uint32_t)cmd_buffer[tx_idx] ); + } + else + { + /* Push out last 0 to get data back from slave */ + HAL_set_32bit_reg( this_spi->base_addr, TXLAST, 0U ); + } + + ++transit; + ++tx_idx; + } + + /* FIFO is all loaded up so enable Core SPI to start transfer */ + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL1_ENABLE, ENABLE ); + + /* Perform the remainder of the transfer by sending a byte every time a byte + * has been received. This should ensure that no Rx overflow can happen in + * case of an interrupt occurring during this function. + * + * We break the transfer down into stages to minimise the processing in + * each loop as the SPI interface is very demanding at higher clock rates. + * This works well with FIFOs but might be less efficient if there is only + * a single frame buffer. + * + * First stage transfers remaining command bytes (if any). + * At this stage anything in the RX FIFO can be discarded as it is + * not part of a valid response. + */ + while( tx_idx < cmd_byte_size ) + { + if( transit < this_spi->fifo_depth ) + { + /* Send another byte. */ + if( tx_idx == transfer_size ) /* Last frame is special... */ + { + HAL_set_32bit_reg( this_spi->base_addr, TXLAST, (uint32_t)cmd_buffer[tx_idx] ); + } + else + { + HAL_set_32bit_reg( this_spi->base_addr, TXDATA, (uint32_t)cmd_buffer[tx_idx] ); + } + ++tx_idx; + ++transit; + } + if( !HAL_get_8bit_reg_field( this_spi->base_addr, STATUS_RXEMPTY ) ) + { + /* Read and discard. */ + HAL_get_32bit_reg( this_spi->base_addr, RXDATA ); + ++transfer_idx; + --transit; + } + } + /* + * Now, we are writing dummy bytes to push through the response from + * the slave but we still have to keep discarding any read data that + * corresponds with one of our command bytes. + */ + while( transfer_idx < cmd_byte_size ) + { + if( transit < this_spi->fifo_depth ) + { + if( tx_idx < transfer_size ) + { + HAL_set_32bit_reg( this_spi->base_addr, TXDATA, 0U ); + ++tx_idx; + ++transit; + } + } + if( !HAL_get_8bit_reg_field(this_spi->base_addr, STATUS_RXEMPTY ) ) + { + /* Read and discard. */ + HAL_get_32bit_reg( this_spi->base_addr, RXDATA ); + ++transfer_idx; + --transit; + } + } + /* + * Now we are now only sending dummy data to push through the + * valid response data which we store in the response buffer. + */ + while( tx_idx < transfer_size ) + { + if( transit < this_spi->fifo_depth ) + { + HAL_set_32bit_reg( this_spi->base_addr, TXDATA, 0U ); + ++tx_idx; + ++transit; + } + if( !HAL_get_8bit_reg_field(this_spi->base_addr, STATUS_RXEMPTY ) ) + { + /* Process received byte. */ + rx_buffer[rx_idx] = (uint8_t)HAL_get_32bit_reg( this_spi->base_addr, RXDATA ); + ++rx_idx; + ++transfer_idx; + --transit; + } + } + /* If we still need to send the last frame */ + while( tx_idx == transfer_size ) + { + if( transit < this_spi->fifo_depth ) + { + HAL_set_32bit_reg( this_spi->base_addr, TXLAST, 0U ); + ++tx_idx; + ++transit; + } + if( !HAL_get_8bit_reg_field( this_spi->base_addr, STATUS_RXEMPTY ) ) + { + /* Process received byte. */ + rx_buffer[rx_idx] = (uint8_t)HAL_get_32bit_reg( this_spi->base_addr, RXDATA ); + ++rx_idx; + ++transfer_idx; + --transit; + } + } + /* + * Finally, we are now finished sending data and are only reading + * valid response data which we store in the response buffer. + */ + while( transfer_idx <= transfer_size ) + { + if( !HAL_get_8bit_reg_field(this_spi->base_addr, STATUS_RXEMPTY ) ) + { + /* Process received byte. */ + rx_buffer[rx_idx] = (uint8_t)HAL_get_32bit_reg( this_spi->base_addr, RXDATA ); + ++rx_idx; + ++transfer_idx; + } + } + } + } +} + +/***************************************************************************//** + * SPI_set_frame_rx_handler() + * See "core_spi.h" for details of how to use this function. + */ +void SPI_set_frame_rx_handler +( + spi_instance_t * this_spi, + spi_frame_rx_handler_t rx_handler +) +{ + HAL_ASSERT( NULL_INSTANCE != this_spi ); + + if(NULL_INSTANCE != this_spi) + { + /* This function is only intended to be used with an SPI slave. */ + if(DISABLE == HAL_get_8bit_reg_field(this_spi->base_addr, CTRL1_MASTER)) + { + /* Disable the Core SPI while we configure */ + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL1_ENABLE, DISABLE ); + + /* Clear all interrupts */ + HAL_set_8bit_reg( this_spi->base_addr, INTCLR, SPI_ALL_INTS ); + + /* Disable SSEND and CMD interrupts as we are not doing block transfers */ + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL2_INTSSEND, DISABLE ); + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL2_INTCMD, DISABLE ); + + /* Disable block Rx handler as they are mutually exclusive. */ + this_spi->block_rx_handler = 0U; + + /* Keep a copy of the pointer to the Rx handler function. */ + this_spi->frame_rx_handler = rx_handler; + + if( SPI_SLAVE_XFER_FRAME != this_spi->slave_xfer_mode ) + { + /* + * Either just coming from init or were previously in block mode + * so no tx frame handler is set at this point in time... + * + * Don't allow TXDONE interrupts. + */ + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL1_INTTXDONE, DISABLE ); + } + + /* Flush the receive and transmit FIFOs*/ + HAL_set_8bit_reg(this_spi->base_addr, CMD, CMD_TXFIFORST_MASK | CMD_RXFIFORST_MASK); + + /* Enable Rx and FIFO error interrupts */ + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL1_INTRXOVFLOW, ENABLE ); + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL1_INTTXURUN, ENABLE ); + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL2_INTRXDATA, ENABLE ); + + /* Make sure correct mode is selected */ + this_spi->slave_xfer_mode = SPI_SLAVE_XFER_FRAME; + + /* Finally re-enable the CoreSPI */ + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL1_ENABLE, ENABLE ); + } + } +} + +/***************************************************************************//** + * SPI_set_slave_tx_frame() + * See "core_spi.h" for details of how to use this function. + */ +void SPI_set_slave_tx_frame +( + spi_instance_t * this_spi, + uint32_t frame_value, + spi_slave_frame_tx_handler_t slave_tx_frame_handler +) +{ + HAL_ASSERT( NULL_INSTANCE != this_spi ); + + if( NULL_INSTANCE != this_spi ) + { + /* This function is only intended to be used with an SPI slave. */ + if( DISABLE == HAL_get_8bit_reg_field(this_spi->base_addr, CTRL1_MASTER ) ) + { + /* Disable the Core SPI while we configure */ + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL1_ENABLE, DISABLE ); + + /* Clear all interrupts */ + HAL_set_8bit_reg( this_spi->base_addr, INTCLR, SPI_ALL_INTS ); + + /* Disable SSEND and CMD interrupts as we are not doing block transfers */ + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL2_INTSSEND, DISABLE ); + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL2_INTCMD, DISABLE ); + + if( SPI_SLAVE_XFER_FRAME != this_spi->slave_xfer_mode ) + { + /* + * Either just coming from init or were previously in block mode + * so no rx frame handler is set at this point in time... + * + * Don't allow RXDATA interrupts. + */ + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL2_INTRXDATA, DISABLE ); + } + + /* Disable slave block tx buffer as it is mutually exclusive with frame + * level handling. */ + this_spi->slave_tx_buffer = NULL_BUFF; + this_spi->slave_tx_size = 0U; + this_spi->slave_tx_idx = 0U; + + /* Flush the receive and transmit FIFOs*/ + HAL_set_8bit_reg(this_spi->base_addr, CMD, CMD_TXFIFORST_MASK | CMD_RXFIFORST_MASK); + + /* Assign the slave frame update handler - NULL_SLAVE_TX_UPDATE_HANDLER for none */ + this_spi->slave_tx_frame_handler = slave_tx_frame_handler; + + /* Keep a copy of the slave Tx frame value. */ + this_spi->slave_tx_frame = frame_value; + + /* Load one frame into Tx data register. */ + HAL_set_32bit_reg( this_spi->base_addr, TXLAST, this_spi->slave_tx_frame ); + + /* Enable Tx Done interrupt in order to reload the slave Tx frame after each + * time it has been sent. */ + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL1_INTTXDONE, ENABLE ); + + /* Make sure correct mode is selected */ + this_spi->slave_xfer_mode = SPI_SLAVE_XFER_FRAME; + + /* Ready to go so enable CoreSPI */ + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL1_ENABLE, ENABLE ); + } + } +} + +/***************************************************************************//** + * SPI_set_slave_block_buffers() + * See "core_spi.h" for details of how to use this function. + */ +void SPI_set_slave_block_buffers +( + spi_instance_t * this_spi, + const uint8_t * tx_buffer, + uint32_t tx_buff_size, + uint8_t * rx_buffer, + uint32_t rx_buff_size, + spi_block_rx_handler_t block_rx_handler +) +{ + HAL_ASSERT( NULL_INSTANCE != this_spi ); + + if( NULL_INSTANCE != this_spi ) + { + /* This function is only intended to be used with an SPI slave. */ + if( DISABLE == HAL_get_8bit_reg_field(this_spi->base_addr, CTRL1_MASTER ) ) + { + /* Disable the Core SPI while we configure */ + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL1_ENABLE, DISABLE ); + + /* Make sure correct mode is selected */ + this_spi->slave_xfer_mode = SPI_SLAVE_XFER_BLOCK; + /* + * No command handler should be setup at this stage so fake this + * to ensure 0 padding works. + */ + this_spi->cmd_done = 1u; + + /* Disable frame handlers as they are mutually exclusive with block Rx handler. */ + this_spi->frame_rx_handler = NULL_FRAME_HANDLER; + this_spi->slave_tx_frame_handler = NULL_SLAVE_TX_UPDATE_HANDLER; + + /* Keep a copy of the pointer to the block Rx handler function. */ + this_spi->block_rx_handler = block_rx_handler; + + /* Assign slave receive buffer */ + this_spi->slave_rx_buffer = rx_buffer; + this_spi->slave_rx_size = rx_buff_size; + this_spi->slave_rx_idx = 0U; + + /* Assign slave transmit buffer*/ + this_spi->slave_tx_buffer = tx_buffer; + this_spi->slave_tx_size = tx_buff_size; + this_spi->slave_tx_idx = 0U; + + /* Flush the receive and transmit FIFOs */ + HAL_set_8bit_reg( this_spi->base_addr, CMD, CMD_TXFIFORST_MASK | CMD_RXFIFORST_MASK ); + + /* Clear all interrupts */ + HAL_set_8bit_reg( this_spi->base_addr, INTCLR, SPI_ALL_INTS ); + + /* Preload the transmit FIFO. */ + while( !(HAL_get_8bit_reg_field(this_spi->base_addr, STATUS_TXFULL)) && + ( this_spi->slave_tx_idx < this_spi->slave_tx_size ) ) + { + HAL_set_32bit_reg( this_spi->base_addr, TXDATA, (uint32_t)this_spi->slave_tx_buffer[this_spi->slave_tx_idx] ); + ++this_spi->slave_tx_idx; + } + /* + * Disable TXDATA interrupt as we will look after transmission in rx handling + * because we know that once we have read a frame it is safe to send another one. + */ + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL2_INTTXDATA, DISABLE ); + + /* Enable Rx, FIFO error and SSEND interrupts */ + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL1_INTRXOVFLOW, ENABLE ); + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL1_INTTXURUN, ENABLE ); + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL2_INTRXDATA, ENABLE ); + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL2_INTSSEND, ENABLE ); + + /* Disable command handler until it is set explicitly */ + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL2_INTCMD, DISABLE ); + + /* Now enable the CoreSPI */ + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL1_ENABLE, ENABLE ); + } + } +} + +/***************************************************************************//** + * SPI_set_cmd_handler() + * See "core_spi.h" for details of how to use this function. + */ +void SPI_set_cmd_handler +( + spi_instance_t * this_spi, + spi_block_rx_handler_t cmd_handler, + uint32_t cmd_size +) +{ + uint32_t ctrl2 = 0u; + + HAL_ASSERT( NULL_INSTANCE != this_spi ); + HAL_ASSERT( NULL_SLAVE_CMD_HANDLER != cmd_handler ); + HAL_ASSERT( 0u < cmd_size ); + + if( ( NULL_INSTANCE != this_spi ) && ( 0u < cmd_size ) && + ( NULL_SLAVE_CMD_HANDLER != cmd_handler ) ) + { + /* Disable the Core SPI while we configure */ + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL1_ENABLE, DISABLE ); + /* + * Note we don't flush the FIFOs as this has been done already when + * block mode was configured. + * + * Clear this flag so zero padding is disabled until command response + * has been taken care of. + */ + this_spi->cmd_done = 0u; + + /* Assign user handler for Command received interrupt */ + this_spi->cmd_handler = cmd_handler; + + /* Configure the command size and Enable Command received interrupt */ + ctrl2 = HAL_get_8bit_reg( this_spi->base_addr, CTRL2 ); + + /* First clear the count field then insert count and int enables */ + ctrl2 &= ~(uint32_t)CTRL2_CMDSIZE_MASK; + ctrl2 |= (uint32_t)((cmd_size & CTRL2_CMDSIZE_MASK) | CTRL2_INTCMD_MASK | CTRL2_INTRXDATA_MASK); + HAL_set_8bit_reg( this_spi->base_addr, CTRL2, ctrl2 ); + + /* Now enable the CoreSPI */ + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL1_ENABLE, ENABLE ); + } +} + +/***************************************************************************//** + * SPI_set_cmd_response() + * See "core_spi.h" for details of how to use this function. + */ +void SPI_set_cmd_response +( + spi_instance_t * this_spi, + const uint8_t * resp_tx_buffer, + uint32_t resp_buff_size +) +{ + HAL_ASSERT( NULL_INSTANCE != this_spi ); + HAL_ASSERT( NULL_BUFF != resp_tx_buffer ); + HAL_ASSERT( 0u < resp_buff_size ); + + if( ( NULL_INSTANCE != this_spi ) && ( 0u < resp_buff_size ) && + ( NULL_BUFF != resp_tx_buffer ) ) + { + this_spi->resp_tx_buffer = resp_tx_buffer; + this_spi->resp_buff_size = resp_buff_size; + this_spi->resp_buff_tx_idx = 0u; + + fill_slave_tx_fifo(this_spi); + } +} + + +/***************************************************************************//** + * SPI_enable() + * See "core_spi.h" for details of how to use this function. + */ +void SPI_enable +( + spi_instance_t * this_spi +) +{ + HAL_ASSERT( NULL_INSTANCE != this_spi ); + + if( NULL_INSTANCE != this_spi ) + { + /* Disable the Core SPI while we configure */ + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL1_ENABLE, ENABLE ); + } +} + + +/***************************************************************************//** + * SPI_disable() + * See "core_spi.h" for details of how to use this function. + */ +void SPI_disable +( + spi_instance_t * this_spi +) +{ + HAL_ASSERT( NULL_INSTANCE != this_spi ); + + if( NULL_INSTANCE != this_spi ) + { + /* Disable the Core SPI while we configure */ + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL1_ENABLE, DISABLE ); + } +} + + +/***************************************************************************//** + * SPI interrupt service routine. + */ +void SPI_isr +( + spi_instance_t * this_spi +) +{ + uint32_t rx_frame; + int32_t guard; + +/* + * The assert and the NULL check here can be commented out to reduce the interrupt + * latency once you are sure the interrupt vector code is correct. + */ + HAL_ASSERT( NULL_INSTANCE != this_spi ); + if( NULL_INSTANCE != this_spi ) + { + /* Handle receive. */ + if( ENABLE == HAL_get_8bit_reg_field( this_spi->base_addr, INTMASK_RXDATA ) ) + { + /* + * Service receive data according to transfer mode in operation. + * + * We check block mode first as this is most likely to have back to back + * transfers with multiple bytes. + * + * Note the order of the checks here will effect interrupt latency and + * for critical timing the mode you are using most often should probably be + * be the first checked. + */ + if( SPI_SLAVE_XFER_BLOCK == this_spi->slave_xfer_mode ) /* Block handling mode. */ + { + while( 0u == HAL_get_8bit_reg_field( this_spi->base_addr, STATUS_RXEMPTY ) ) + { + /* Read irrespective to clear the RX IRQ */ + rx_frame = HAL_get_32bit_reg( this_spi->base_addr, RXDATA ); + if( this_spi->slave_rx_idx < this_spi->slave_rx_size ) + { + this_spi->slave_rx_buffer[this_spi->slave_rx_idx] = (uint8_t)rx_frame; + } + ++this_spi->slave_rx_idx; + } + /* + * Now handle updating of tx FIFO to keep the data flowing. + * First see if there is anything in slave_tx_buffer to send. + */ + while( ( this_spi->slave_tx_idx < this_spi->slave_tx_size ) + && ( 0u == HAL_get_8bit_reg_field( this_spi->base_addr, STATUS_TXFULL ) ) ) + { + HAL_set_32bit_reg( this_spi->base_addr, TXDATA, (uint32_t)this_spi->slave_tx_buffer[this_spi->slave_tx_idx] ); + ++this_spi->slave_tx_idx; + } + /* + * Next see if there is anything in resp_tx_buffer to send. + */ + if( this_spi->slave_tx_idx >= this_spi->slave_tx_size ) + { + while( ( this_spi->resp_buff_tx_idx < this_spi->resp_buff_size ) + && ( 0u == HAL_get_8bit_reg_field( this_spi->base_addr, STATUS_TXFULL ) ) ) + { + HAL_set_32bit_reg( this_spi->base_addr, TXDATA, (uint32_t)this_spi->resp_tx_buffer[this_spi->resp_buff_tx_idx] ); + ++this_spi->resp_buff_tx_idx; + } + } + /* + * Lastly, see if we are ready to pad with 0s . + */ + if( this_spi->cmd_done && ( this_spi->slave_tx_idx >= this_spi->slave_tx_size ) && + ( this_spi->resp_buff_tx_idx >= this_spi->resp_buff_size ) ) + { + guard = 1 + ((int32_t)this_spi->fifo_depth / 4); + while( ( 0u == HAL_get_8bit_reg_field( this_spi->base_addr, STATUS_TXFULL ) ) + && ( 0 != guard ) ) + { + /* + * Pad TX FIFO with 0s for consistent behaviour if the master + * tries to transfer more than we expected. + */ + HAL_set_32bit_reg(this_spi->base_addr, TXDATA, 0x00u); + /* + * We use the guard count to cover the event that we are never + * seeing the TX FIFO full because the data is being pulled + * out as fast as we can stuff it in. In this case we never spend + * more than our allocated time spinning here. + */ + guard--; + } + } + } + else if( SPI_SLAVE_XFER_FRAME == this_spi->slave_xfer_mode ) /* Single frame handling mode. */ + { + while( 0u == HAL_get_8bit_reg_field( this_spi->base_addr, STATUS_RXEMPTY ) ) + { + rx_frame = HAL_get_32bit_reg( this_spi->base_addr, RXDATA ); + if( NULL_FRAME_HANDLER != this_spi->frame_rx_handler ) + { + this_spi->frame_rx_handler( rx_frame ); + } + } + } + else /* Slave transfer mode not set up so discard anything in RX FIFO */ + { + HAL_set_8bit_reg( this_spi->base_addr, CMD, CMD_RXFIFORST_MASK ); + } + + HAL_set_8bit_reg_field( this_spi->base_addr, INTCLR_RXDATA, ENABLE ); + } + + /* Handle transmit. */ + if( ENABLE == HAL_get_8bit_reg_field( this_spi->base_addr, INTMASK_TXDONE ) ) + { + /* + * Note, the driver only currently uses the txdone interrupt when + * in frame transmit mode. In block mode all TX handling is done by the + * receive interrupt handling code as we know that for every frame received + * a frame must be placed in the TX FIFO. + */ + if( SPI_SLAVE_XFER_FRAME == this_spi->slave_xfer_mode ) + { + /* Execute the user callback to update the slave_tx_frame */ + if( NULL_SLAVE_TX_UPDATE_HANDLER != this_spi->slave_tx_frame_handler ) + { + this_spi->slave_tx_frame_handler ( this_spi ); + } + + /* Reload slave tx frame into Tx data register. */ + HAL_set_32bit_reg( this_spi->base_addr, TXLAST, this_spi->slave_tx_frame ); + } + else if( SPI_SLAVE_XFER_BLOCK != this_spi->slave_xfer_mode ) + { + /* Slave transfer mode not set up so discard anything in TX FIFO */ + HAL_set_8bit_reg( this_spi->base_addr, CMD, CMD_TXFIFORST_MASK ); + } + else + { + /* Nothing to do, no slave mode configured */ + } + + HAL_set_8bit_reg_field( this_spi->base_addr, INTCLR_TXDONE, ENABLE ); + } + + + /* Handle receive overflow. */ + if( ENABLE == HAL_get_8bit_reg_field(this_spi->base_addr, INTMASK_RXOVERFLOW)) + { + HAL_set_8bit_reg(this_spi->base_addr, CMD, CMD_RXFIFORST_MASK); + HAL_set_8bit_reg_field(this_spi->base_addr, INTCLR_RXOVERFLOW, ENABLE); + } + + /* Handle transmit under run. */ + if( ENABLE == HAL_get_8bit_reg_field( this_spi->base_addr, INTMASK_TXUNDERRUN ) ) + { + HAL_set_8bit_reg( this_spi->base_addr, CMD, CMD_TXFIFORST_MASK ); + HAL_set_8bit_reg_field( this_spi->base_addr, INTCLR_TXUNDERRUN, ENABLE ); + } + + /* Handle command interrupt. */ + if( ENABLE == HAL_get_8bit_reg_field( this_spi->base_addr, INTMASK_CMDINT ) ) + { + read_slave_rx_fifo( this_spi ); + + /* + * Call the command handler if one exists. + */ + if( NULL_SLAVE_CMD_HANDLER != this_spi->cmd_handler ) + { + this_spi->cmd_handler( this_spi->slave_rx_buffer, this_spi->slave_rx_idx ); + } + this_spi->cmd_done = 1u; + /* Disable command interrupt until slave select becomes de-asserted to avoid retriggering. */ + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL2_INTCMD, DISABLE ); + HAL_set_8bit_reg_field( this_spi->base_addr, INTCLR_CMDINT, ENABLE ); + } + + /* Handle slave select becoming de-asserted. */ + if( ENABLE == HAL_get_8bit_reg_field( this_spi->base_addr, INTMASK_SSEND) ) + { + /* Only supposed to do all this if transferring blocks... */ + if(SPI_SLAVE_XFER_BLOCK == this_spi->slave_xfer_mode) + { + uint32_t rx_size; + + /* Empty any remaining bytes in RX FIFO */ + read_slave_rx_fifo( this_spi ); + rx_size = this_spi->slave_rx_idx; + /* + * Re-enable command interrupt if required. + * Must be done before re loading FIFO to ensure stale response + * data is not pushed into the FIFO. + */ + if(NULL_SLAVE_CMD_HANDLER != this_spi->cmd_handler) + { + this_spi->cmd_done = 0u; + this_spi->resp_tx_buffer = 0u; + this_spi->resp_buff_size = 0u; + this_spi->resp_buff_tx_idx = 0u; + HAL_set_8bit_reg_field( this_spi->base_addr, INTCLR_CMDINT, ENABLE ); + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL2_INTCMD, ENABLE ); + } + /* + * Reset the transmit index to 0 to restart transmit at the start of the + * transmit buffer in the next transaction. This also requires flushing + * the Tx FIFO and refilling it with the start of Tx data buffer. + */ + this_spi->slave_tx_idx = 0u; + HAL_set_8bit_reg( this_spi->base_addr, CMD, CMD_TXFIFORST_MASK | CMD_RXFIFORST_MASK ); + fill_slave_tx_fifo( this_spi ); + + /* Prepare to receive next packet. */ + this_spi->slave_rx_idx = 0u; + /* + * Call the receive handler if one exists. + */ + if( NULL_BLOCK_HANDLER != this_spi->block_rx_handler ) + { + this_spi->block_rx_handler( this_spi->slave_rx_buffer, rx_size ); + } + + HAL_set_8bit_reg_field( this_spi->base_addr, INTCLR_RXDATA, ENABLE ); + } + + HAL_set_8bit_reg_field( this_spi->base_addr, INTCLR_SSEND, ENABLE ); + } + } +} + +/******************************************************************************* + * Local function definitions + */ + +/***************************************************************************//** + * Fill the transmit FIFO (used for slave block transfers). + */ +static void fill_slave_tx_fifo +( + spi_instance_t * this_spi +) +{ + /* First see if slave_tx_buffer needs transmitting */ + while( ( this_spi->slave_tx_idx < this_spi->slave_tx_size ) && + !HAL_get_8bit_reg_field( this_spi->base_addr, STATUS_TXFULL ) ) + { + HAL_set_32bit_reg( this_spi->base_addr, TXDATA, (uint32_t)this_spi->slave_tx_buffer[this_spi->slave_tx_idx] ); + ++this_spi->slave_tx_idx; + } + + /* Then see if it is safe to look at putting resp_tx_buffer in FIFO? */ + if( this_spi->slave_tx_idx >= this_spi->slave_tx_size ) + { + while( ( this_spi->resp_buff_tx_idx < this_spi->resp_buff_size ) && + !HAL_get_8bit_reg_field( this_spi->base_addr, STATUS_TXFULL ) ) + { + HAL_set_32bit_reg( this_spi->base_addr, TXDATA, (uint32_t)this_spi->resp_tx_buffer[this_spi->resp_buff_tx_idx] ); + ++this_spi->resp_buff_tx_idx; + } + } +} + +/***************************************************************************//** + * + */ +static void read_slave_rx_fifo +( + spi_instance_t * this_spi +) +{ + uint32_t rx_frame; + + if( SPI_SLAVE_XFER_BLOCK == this_spi->slave_xfer_mode ) /* Block handling mode. */ + { + while( !HAL_get_8bit_reg_field( this_spi->base_addr, STATUS_RXEMPTY ) ) + { + rx_frame = HAL_get_32bit_reg( this_spi->base_addr, RXDATA ); /* Read irresepective to clear the RX IRQ */ + if( this_spi->slave_rx_idx < this_spi->slave_rx_size ) + { + this_spi->slave_rx_buffer[this_spi->slave_rx_idx] = (uint8_t)rx_frame; + } + ++this_spi->slave_rx_idx; + } + } + else if( SPI_SLAVE_XFER_FRAME == this_spi->slave_xfer_mode ) /* Frame handling mode */ + { + while( !HAL_get_8bit_reg_field( this_spi->base_addr, STATUS_RXEMPTY ) ) + { + /* Single frame handling mode. */ + rx_frame = HAL_get_32bit_reg( this_spi->base_addr, RXDATA ); + if( NULL_FRAME_HANDLER != this_spi->frame_rx_handler ) + { + this_spi->frame_rx_handler( rx_frame ); + } + } + } + else /* Slave transfer mode not set up so discard anything in RX FIFO */ + { + HAL_set_8bit_reg( this_spi->base_addr, CMD, CMD_RXFIFORST_MASK ); + } +} + +/***************************************************************************//** + * This function is to recover the CoreSPI from receiver overflow. + * It temporarily disables the CoreSPI from interacting with external world, flushes + * the transmit and receiver FIFOs, clears all interrupts and then re-enables + * the CoreSPI instance referred by this_spi parameter. + */ +static void recover_from_rx_overflow +( + const spi_instance_t * this_spi +) +{ + /* Disable CoreSPI */ + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL1_ENABLE, DISABLE ); + + /* Reset TX and RX FIFOs */ + HAL_set_8bit_reg( this_spi->base_addr, CMD, CMD_TXFIFORST_MASK | CMD_RXFIFORST_MASK ); + + /* Clear all interrupts */ + HAL_set_8bit_reg( this_spi->base_addr, INTCLR, SPI_ALL_INTS ); + + /* Enable CoreSPI */ + HAL_set_8bit_reg_field( this_spi->base_addr, CTRL1_ENABLE, ENABLE ); +} + + diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreSPI/core_spi.h b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreSPI/core_spi.h new file mode 100644 index 0000000..4ae077e --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreSPI/core_spi.h @@ -0,0 +1,1221 @@ +/******************************************************************************* + * (c) Copyright 2007-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * @file core_spi.h + * @author Microchip FPGA Embedded Systems Solutions + * @brief This file contains the application programming interface for the + * CoreSPI bare metal driver. + * + * This Core SPI driver provides functions for implementing SPI master or + * SPI slave operations with the CoreSPI v4.2. It is not compatible with the + * CoreSPI v3.0. + * + * The Core SPI driver supports two classes of data transfer operation: + * SPI frame operation or SPI block transfer operations. + * + * Frame operations allow transferring individual SPI frames from 4 to 32 bits + * in length. Block operations allow transferring blocks of data organized as + * 8 bit frames. + * + */ +/*=========================================================================*//** + @mainpage Core SPI Bare Metal Driver. + + @section intro_sec Introduction + CoreSPI is an IP component that implements a full-duplex, synchronous, and + configurable serial peripheral interface (SPI) with frame sizes from 4 to 32 + bits and bus interface sizes of 8-, 16-, or 32-bit . Each CoreSPI instance + can communicate with up to 8 slave devices. + + This driver provides a set of functions for controlling CoreSPI as part of + the bare metal system where no operating system is available. These drivers + can be adapted to be used as a part of an operating system, but the + implementation of the adaptation layer between driver and the operating + system's driver model is outside the scope of this User�s Guide. + + @section driver_configuration Driver Configuration + Your application software should configure the CoreSPI driver through calls + to the SPI_init() function for each CoreSPI instance in the hardware design. + This function configures a default set of parameters that include a CoreSPI + hardware instance base address and the depth of the FIFOs for this instance. + + The CoreSPI instance is configured at the time of instantiation in hardware + design for APB width, frame size, FIFO depth, serial clock speed, serial + clock polarity, serial clock phase and slave select state parameters. + + CoreSPI can communicate with up to 8 different slave devices that match + the CoreSPI configuration done at the time of hardware instantiation. + + The functions SPI_configure_slave_mode() and SPI_configure_master_mode() are + used to configure the CoreSPI instance as a master or as a slave as required by + the application. + + When CoreSPI wishes to communicate with a specific slave device, the + function SPI_set_slave_select() is called with the slave number as an + argument. This function selects the slave device. A previously selected + slave can be unselected by calling the function SPI_clear_slave_select(). + + @section theory_op Theory of Operation + The CoreSPI driver functions are grouped into the following categories: + � Initialization + � Configuration for either master or slave operations + � SPI master frame transfer control + � SPI master block transfer control + � SPI slave frame transfer control + � SPI slave block transfer control + Frame transfers allow CoreSPI to write or read up to 32 bits of data in a + single SPI transaction. For example, a frame transfer of 12 bits might be used + to read the result of an ADC conversion from a SPI analog to digital converter. + + Block transfers allow CoreSPI to write and/or read a number of bytes in a single + SPI transaction. With the driver as is, block transfer transactions allow data + transfers in multiples of 8 bits (8, 16, 24, 32, 40�) and the CoreSPI instance + has to be configured for 8 bit frames. For other frame sizes, the + SPI_transfer_block() code can act as a template for developing a frame block + transfer function. + Block transfers are typically used with byte oriented devices like SPI + FLASH devices. + + Note: The CoreSPI instance in the hardware design must be configured for + the frame size required by the application; configuration by driver is + not possible. + + Initialization + The CoreSPI driver is initialized through a call to the SPI_init() function. + The SPI_init() function takes a pointer to the global CoreSPI instance data + structure of type spi_instance_t and the base address of the CoreSPI instance + as defined by the hardware design. The CoreSPI instance global data structure + is used by the driver to store state information for each CoreSPI instance. + A pointer to these data structures is also used as the first parameter to + any of the driver functions to identify which CoreSPI will be used by the + called function. It is the responsibility of the application programmer to + create and maintain these global CoreSPI instance data structures. Any call + to a CoreSPI driver function should be of the form SPI_function_name + ( &g_core_spi0, ... ). + The SPI_init() function resets the transmit and receives FIFOs of CoreSPI + instance being initialized. + The SPI_init() function must be called before any other CoreSPI driver + functions can be called. + + Configuration + A CoreSPI instance can operate either as a master or as a slave SPI device. + There are two distinct functions for configuring a CoreSPI instance for + master or slave operations. + + Master configuration + The SPI_configure_master_mode() function configures the specified CoreSPI + block for operations as a SPI master. This function must be called once + before the CoreSPI block communicates with a SPI slave device. + + Slave configuration + The SPI_configure_slave_mode() function configures the specified CoreSPI + block for operations as a SPI slave. This function must be called after + SPI_init() call to configure the CoreSPI instance referred by this_spi + parameter to operate in slave mode. + + SPI master frame transfer control + The following functions are used as a part of the SPI master frame transfers: + � SPI_set_slave_select() + � SPI_transfer_frame() + � SPI_clear_slave_select() + The master must first select the target slave or slaves to be addressed through + a call to SPI_set_slave_select(). This causes the relevant select line(s) to + become asserted while data is clocked out onto the SPI data line. + + A function call is then made to SPI_transfer_frame() specifying the value + of the data frame to be sent and returning the value read. + + The function SPI_clear_slave_select() can be used after the transfer is + complete to prevent this slave select line from being asserted during + subsequent SPI transactions. A call to this function is required only if + the master is communicating with multiple slave devices. + + SPI master block transfer control + The following functions are used as a part of the SPI master block transfers: + � SPI_set_slave_select() + � SPI_transfer_block() + � SPI_clear_slave_select() + The master must first select the target slave or slaves through a call to + SPI_set_slave_select(). This causes the relevant slave select line(s) to + become asserted while data is clocked out onto the SPI data line. + Alternatively, a general purpose input/output (GPIO) can be used to control + the state of the target slave device�s chip select signal. + + A call is then made to the SPI_transfer_block() function. The parameters of + this function specify the following: + � The number of bytes to be transmitted + � A pointer to the buffer containing the data to be transmitted + � The number of bytes to be received + � A pointer to the buffer where received data will be stored + + The number of bytes to be transmitted can be set to zero to indicate that the + transfer is purely a block read transfer. The number of bytes to be received + can be set to zero to specify that the transfer is purely a block write + transfer. + + Block mode transfers as implemented by the driver are effectively half duplex + as we do not store the values received from the slave device whilst we are + transmitting. If full duplex operation is required the driver + SPI_transfer_block() function can serve as a starting point for implementing + full duplex block transfers. + + The SPI_clear_slave_select() function can be used after the transfer is + complete to prevent this slave select line from being asserted during + subsequent SPI transactions. A call to this function is only required if + the master is communicating with multiple slave devices. + + SPI slave frame transfer control + The following functions are used as a part of the SPI slave frame transfers: + � SPI_set_frame_rx_handler() + � SPI_set_slave_tx_frame() + + The SPI_set_frame_rx_handler() function specifies the receive handler + function that will be called when a frame of data has been received by the + SPI when it is configured as a slave. The receive handler function specified + through this call processes the frame data written over the SPI bus to the + SPI slave by the remote SPI master. The receive handler function must be + implemented as part of the application. It is only required if the SPI slave + is the target of SPI frame write transactions. + + The SPI_set_slave_tx_frame() function specifies the frame data that will be + returned to the SPI master. The frame data specified through this function + is the value that will be read over the SPI bus by the remote SPI master, + when it initiates a transaction. A call to SPI_set_slave_tx_frame() is only + required if the SPI slave is the target of SPI read transactions, i.e., if + data is meant to be read over CoreSPI. + + If both frame handlers are required, the call to SPI_set_frame_rx_handler() + should be made first otherwise the initial TX frame will be discarded when + SPI_set_frame_rx_handler() clears the FIFOs as part of its initialization. + + SPI slave block transfer control + The following functions are used as a part of the SPI slave block transfers: + � SPI_set_slave_block_buffers() + � SPI_set_cmd_handler() + � SPI_set_cmd_response() + + The SPI_set_slave_block_buffers() function is used to configure an SPI slave + for block transfer operations. It specifies the following: + � The buffer containing the data that will be returned to the remote SPI + master + � The buffer where data received from the remote SPI master will be + stored + � The optional handler function that will be called after the receive + buffer is filled. + + The SPI_set_cmd_handler() function specifies a command handler function that + will be called by the driver once a specific number of frames have been + received after the SPI chip select signal becoming active. The number of + bytes making up the command part of the transaction is specified as part of + the parameters to the SPI_set_cmd_handler() function. The command handler + function is implemented as a part of the application making use of the SPI + driver and typically calls the SPI_set_cmd_response() function. + + The SPI_set_cmd_response() function specifies the data that will be returned + to the master. Typically, the SPI_set_slave_block_buffers() function is + called as a part of the system initialisation to specify the data sent to + the master while the command bytes are being received. The transmit buffer + specified though the call to the SPI_set_slave_block_buffers() function + would also typically include one or more bytes allowing the turn around time + for the command handler function to execute and call the + SPI_set_cmd_response() function. + + *//*=========================================================================*/ +#ifndef CORE_SPI_H_ +#define CORE_SPI_H_ + +#ifndef LEGACY_DIR_STRUCTURE +#include "hal/hal.h" + +#else +#include "hal.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/***************************************************************************//** + These constants define the maximum and minimum FIFO depths allowed for the + CoreSPI instance. User need to inform the driver of the FIFO depth for each + CoreSPI instance to ensure that the FIFOs are managed correctly. + */ +#define SPI_MAX_FIFO_DEPTH 32u +#define SPI_MIN_FIFO_DEPTH 1u + +/***************************************************************************//** + Instances of this structure are used to identify specific CoreSPI hardware + instances. A pointer to an instance of the spi_instance_t structure is passed + as the first parameter to the CoreSPI driver functions to identify which SPI + performs the requested operation. + */ +typedef struct spi_instance spi_instance_t; + +/***************************************************************************//** + This function pointer type is to assign a callback function for TX interrupt + when slave wants send the next updated frame. + + Declaring and Implementing Slave Frame Receive Handler Functions: + Slave transmit frame update handler functions should follow the following + prototype: + void slave_txframe_update_handler ( spi_instance_t * this_spi ); + The actual name of the receive handler is unimportant. You can use any name + of your choice for the frame update handler. + + A common handler may be used for more than one slave instance as the particular + slave device currently requiring service is indicated. + */ +typedef void (*spi_slave_frame_tx_handler_t)( spi_instance_t * this_spi ); + +/***************************************************************************//** + This defines the function prototype that must be followed by the SPI slave + frame receive handler functions. These functions are registered with the SPI + driver through the SPI_set_frame_rx_handler() function. + + Declaring and Implementing the Slave Frame Receive Handler Functions: + The Slave frame receive handler functions should follow the following + prototype: + void slave_frame_receive_handler(uint32_t rx_frame); + The actual name of the receive handler is unimportant. You can use any name + of your choice for the receive frame handler. The rx_frame parameter will + contain the value of the received frame. + + Separate handler functions are required for each slave instance as there is + no indication of the slave requiring service passed to the handler. + + */ +typedef void (*spi_frame_rx_handler_t)( uint32_t rx_frame ); + +/***************************************************************************//** + This defines the function prototype that must be followed by SPI slave + block receive handler functions. These functions are registered with the + SPI driver through the SPI_set_slave_block_buffers() function. + + Declaring and Implementing Slave Block Receive Handler Functions + Slave block receive handler functions should follow the following prototype: + void spi_block_rx_handler ( uint8_t * rx_buff, uint16_t rx_size ); + The actual name of the receive handler is unimportant. You can use any name + of your choice for the receive frame handler. The rx_buff parameter will + contain a pointer to the start of the received block. The rx_size parameter + will contain the number of bytes of the received block. + + Separate handler functions are required for each slave instance as there is + no indication of the slave requiring service passed to the handler. + + */ +typedef void (*spi_block_rx_handler_t)( uint8_t * rx_buff, uint32_t rx_size ); + +/***************************************************************************//** + This enumeration is used to select a specific SPI slave device (0 to 7). It is + used as a parameter to the SPI_configure_master_mode(), SPI_set_slave_select(), + and SPI_clear_slave_select() functions. + */ +typedef enum __spi_slave_t +{ + SPI_SLAVE_0 = 0, + SPI_SLAVE_1 = 1, + SPI_SLAVE_2 = 2, + SPI_SLAVE_3 = 3, + SPI_SLAVE_4 = 4, + SPI_SLAVE_5 = 5, + SPI_SLAVE_6 = 6, + SPI_SLAVE_7 = 7, + SPI_MAX_NB_OF_SLAVES = 8 +} spi_slave_t; + +/***************************************************************************//** + This enumeration is used to indicate the current slave mode transfer type so + that we are not relying on buffer comparisons to dictate the logic of the driver. + */ +typedef enum __spi_sxfer_mode_t +{ + SPI_SLAVE_XFER_NONE = 0, /* Not configured yet */ + SPI_SLAVE_XFER_BLOCK = 1, /* Block transfers, with SSEND delimiting end of block */ + SPI_SLAVE_XFER_FRAME = 2 /* Single frame transfers */ +} spi_sxfer_mode_t; + +/***************************************************************************//** + There is one instance of this structure for each of the core SPIs. Instances + of this structure are used to identify a specific SPI. A pointer to an + instance of the spi_instance_t structure is passed as + the first parameter to SPI driver functions to identify which SPI should + perform the requested operation. + */ +struct spi_instance{ + + /** Base address in the processor's memory map for the + * registers of the CoreSPI instance being initialized. */ + addr_t base_addr; /*!< Base address of SPI hardware instance. */ + + uint32_t rx_frame; /*!< received data */ + + /* Internal transmit state: */ + const uint8_t * slave_tx_buffer; /*!< Pointer to slave transmit buffer. */ + uint32_t slave_tx_size; /*!< Size of slave transmit buffer. */ + uint32_t slave_tx_idx; /*!< Current index into slave transmit buffer. */ + + /* Slave command response buffer: */ + const uint8_t * resp_tx_buffer; + uint32_t resp_buff_size; + uint32_t resp_buff_tx_idx; + spi_block_rx_handler_t cmd_handler; + uint32_t cmd_done; /*!< Flag which indicates response has been set up and + it is safe to pad with 0s once the response is sent. */ + + /* Internal receive state: */ + uint8_t * slave_rx_buffer; /*!< Pointer to buffer where data received by a slave will be stored. */ + uint32_t slave_rx_size; /*!< Slave receive buffer size. */ + uint32_t slave_rx_idx; /*!< Current index into slave receive buffer. */ + + /** Slave received frame handler: */ + spi_frame_rx_handler_t frame_rx_handler; /*!< Pointer to function that will be called when a frame + is received when the SPI block is configured as slave. */ + /** Slave transmitted frame handler: */ + uint32_t slave_tx_frame; /*!< Value of the data frame that will be transmitted + when the SPI block is configured as slave. */ + spi_slave_frame_tx_handler_t slave_tx_frame_handler; /*!< Callback function pointer to update slave_tx_frame */ + + /* Slave block rx handler: */ + spi_block_rx_handler_t block_rx_handler; /*!< Pointer to the function that will be called when a data block has been received. */ + + /* Per instance specific hardware information that the driver needs to know */ + uint16_t fifo_depth; /*!< Depth of RX and TX FIFOs in frames. */ + + /* How we are expecting to deal with slave transfers */ + spi_sxfer_mode_t slave_xfer_mode; /*!< Current slave mode transfer configuration. */ +}; + +/*============================================================================== + * Public functions + *============================================================================*/ + +/***************************************************************************//** + The SPI_init() function initializes the hardware and data structures of a + CoreSPI instance referenced by this_spi parameter. This function must be + called for each CoreSPI instance with a unique this_spi and base_addr + parameter combination. The SPI_init() function must be called before any + other CoreSPI driver functions are called. + + After SPI_init() has been called, the CoreSPI will be configured as a master, + all interrupt sources will be masked and all slaves deselected. + + @param this_spi + The this_spi parameter is a pointer to a spi_instance_t structure identifying + the CoreSPI hardware block to be initialized. This parameter must point to + the g_core_spi global data structure defined within the application code. + + @param base_addr + The base_addr parameter is the base address in the processor's memory map for + the registers of the CoreSPI instance being initialized. It is assumed that + any non NULL value passed in here points to a valid instance of a CoreSPI as + the driver has no way of verifying this. Failure to pass in a valid address + can result in system instability. + + @param fifo_depth + The fifo_depth parameter specifies the number of frames in the receive + and transmit FIFOs of the CoreSPI instance being initialized. + + @return + This function does not return any value. + + Example: + @code + #define SPI0_BASE_ADDR 0xC2000000 + + spi_instance_t g_spi0; + SPI_init( &g_spi0, SPI0_BASE_ADDR, 8 ); + @endcode + */ +void SPI_init +( + spi_instance_t * this_spi, + addr_t base_addr, + uint16_t fifo_depth +); + +/***************************************************************************//** + The SPI_configure_slave_mode() function is used when a CoreSPI instance is + to be configured as a SPI slave. + + @param this_spi + The this_spi parameter is a pointer to a spi_instance_t structure identifying + the CoreSPI hardware block to be configured. This parameter must point to + the g_core_spi global data structure defined within the application code. + + @return + This function does not return any value. + + Example: + @code + #define SPI0_BASE_ADDR 0xC2000000 + + spi_instance_t g_spi0; + + int main(void) + { + SPI_init( &g_spi0, SPI0_BASE_ADDR, 8 ); + SPI_configure_slave_mode ( &g _spi0 ); + } + @endcode + */ +void SPI_configure_slave_mode +( + spi_instance_t * this_spi +); + +/***************************************************************************//** + The SPI_configure_master_mode() function is used when a CoreSPI instance is + to be configured as a SPI master. + + @param this_spi + The this_spi parameter is a pointer to a spi_instance_t structure identifying + the CoreSPI hardware block to be configured. This parameter must point to + a g_core_spi global data structure defined within the application code. + + @return + This function does not return any value. + + Example: + @code + #define SPI0_BASE_ADDR 0xC2000000 + + spi_instance_t g_spi0; + + int main(void) + { + SPI_init( &g_spi0, SPI0_BASE_ADDR, 8 ); + SPI_configure_master_mode ( &g _spi0 ); + } + @endcode + */ +void SPI_configure_master_mode +( + spi_instance_t * this_spi +); + +/***************************************************************************//** + The SPI_set_slave_select() function is used by a CoreSPI master to select a + specific slave. This function causes the relevant slave select signal to be + asserted while data is clocked out onto the SPI data line. + + @param this_spi + The this_spi parameter is a pointer to a spi_instance_t structure identifying + the CoreSPI hardware block to operate on. This parameter must point to + a g_core_spi global data structure defined within the application code. + + @param slave + The slave parameter is one of the spi_slave_t enumerated constants + identifying a slave. + + @return + This function does not return any value. + + Example: + @code + #define SPI0_BASE_ADDR 0xC2000000 + + spi_instance_t g_spi0; + const uint32_t master_tx_frame = 0x0100A0E1; + + SPI_init( &g_spi0, SPI0_BASE_ADDR, 1 ); + SPI_configure_master_mode( &g_spi0 ); + + SPI_set_slave_select( &g_spi0, SPI_SLAVE_0 ); + SPI_transfer_frame( &g_spi0, master_tx_frame ); + SPI_clear_slave_select( &g_spi0, SPI_SLAVE_0 ); + + @endcode + */ +void SPI_set_slave_select +( + spi_instance_t * this_spi, + spi_slave_t slave +); + +/***************************************************************************//** + The SPI_clear_slave_select() function is used by a CoreSPI master to + deselect a specific slave. This function causes the relevant slave select + signal to be de-asserted. + + @param this_spi + The this_spi parameter is a pointer to a spi_instance_t structure identifying + the CoreSPI hardware block to operate on. This parameter must point to + a g_core_spi global data structure defined within the application code. + + @param slave + The slave parameter is one of the spi_slave_t enumerated constants + identifying a slave. + + @return + This function does not return any value. + + Example: + @code + #define SPI0_BASE_ADDR 0xC2000000 + + spi_instance_t g_spi0; + const uint32_t master_tx_frame = 0x0100A0E1; + + SPI_init( &g_spi0, SPI0_BASE_ADDR, 1 ); + SPI_configure_master_mode( &g_spi0 ); + + SPI_set_slave_select( &g_spi0, SPI_SLAVE_0 ); + SPI_transfer_frame( &g_spi0, master_tx_frame ); + SPI_clear_slave_select( &g_spi0, SPI_SLAVE_0 ); + @endcode + */ +void SPI_clear_slave_select +( + spi_instance_t * this_spi, + spi_slave_t slave +); + +/***************************************************************************//** + The SPI_transfer_frame() function is used by a SPI master to transmit and + receive a single frame of the size that has been configured at the time of + CoreSPI hardware instantiation. This function is typically used for + transactions with a SPI slave where the number of transmit and receive bits + are not divisible by 8 or where full duplex exchange of frames is required. + + @param this_spi + The this_spi parameter is a pointer to a spi_instance_t structure identifying + the CoreSPI hardware block to operate on. This parameter must point to + a g_core_spi global data structure defined within the application code. + + @param tx_bits + The tx_bits parameter is a 32-bit word containing the value that will be + transmitted. If the frame size configured for the CoreSPI in question is + less that 32 bits, the upper bits will be ignored. + Note: The bit length of the value to be transmitted to the slave is + set when the CoreSPI is instantiated in the hardware design. + + @return + This function returns a 32-bit word containing the value that is received + from the slave. If the frame size configured for the CoreSPI in question is + less that 32 bits, the upper bits will be 0. + + Example: + @code + #define SPI0_BASE_ADDR 0xC2000000 + + spi_instance_t g_spi0 ; + const uint32_t master_tx_frame = 0x0100A0E1; + uint32_t master_rx; + + SPI_init(&g_spi0, SPI0_BASE_ADDR, 1 ); + SPI_configure_master_mode( &g_spi0 ); + SPI_set_slave_select( &g_spi0, SPI_SLAVE_0 ); + master_rx = SPI_transfer_frame( &g_spi0, master_tx_frame ); + SPI_clear_slave_select( &g_spi0, SPI_SLAVE_0 ); + @endcode + */ +uint32_t SPI_transfer_frame +( + spi_instance_t * this_spi, + uint32_t tx_bits +); + +/***************************************************************************//** + The SPI_transfer_block() function is used by the SPI master to transmit and + receive blocks of data organized as a specified number of 8 bit frames. It + can be used for the following: + � Writing a data block to a slave + � Reading a data block from a slave + � Sending a command to a slave followed by reading the outcome of + the command in a single SPI transaction. + + @param this_spi + The this_spi parameter is a pointer to a spi_instance_t structure identifying + the CoreSPI hardware block to operate on. This parameter must point to + a g_core_spi global data structure defined within the application code. + + @param cmd_buffer + The cmd_buffer parameter is a pointer to the buffer containing the data that + will be sent by the master from the beginning of the transfer. This pointer + can be null (0) if the master does not need to send a command before reading + data. + + @param cmd_byte_size + The cmd_byte_size parameter specifies the number of bytes contained in + cmd_buffer that will be sent. A value �0� indicates that no data needs + to be sent to the slave. + + @param rx_buffer + The rx_buffer parameter is a pointer to the buffer where the data received + from the slave after the command has been sent will be stored. This pointer + can be null (0) if the master does not need to receive any data from the + slave. + + @param rx_byte_size + The rx_byte_size parameter specifies the number of bytes to be received from + the slave and stored in the rx_buffer. A value �0� indicates that no data is + to be read from the slave. + + @return + This function does not return any value. + + Example: + @code + Polled write transfer example + #define SPI0_BASE_ADDR 0xC2000000 + + spi_instance_t g_spi0 ; + + uint8_t master_tx_buffer[MASTER_TX_BUFFER] = + { + 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A + }; + SPI_init( &g_spi0, SPI0_BASE_ADDR, 8 ); + + SPI_configure_master_mode( &g_spi0 ); + + SPI_set_slave_select( &g_spi0, SPI_SLAVE_0) ; + SPI_transfer_block + ( + &g_spi0, + master_tx_buffer, + sizeof(master_tx_buffer), + 0, + 0 + ); + SPI_clear_slave_select(&g_spi0, SPI_SLAVE_0 ); + @endcode + */ +void SPI_transfer_block +( + spi_instance_t * this_spi, + const uint8_t * tx_buffer, + uint16_t tx_byte_size, + uint8_t * rx_buffer, + uint16_t rx_byte_size +); + +/***************************************************************************//** + The SPI_set_frame_rx_handler() function is used by the SPI slaves to specify + the receive handler function that will be called by the SPI driver interrupt + handler when a frame of data is received by the SPI slave. + + @param this_spi + The this_spi parameter is a pointer to a spi_instance_t structure identifying + the CoreSPI hardware block to operate on. This parameter must point to + a g_core_spi global data structure defined within the application code. + + @param rx_handler + The rx_handler parameter is a pointer to the frame receive handler that must + be called when a frame is received by the CoreSPI slave. Passing in a NULL + pointer disables the receive handler but does enable the receive interrupt to + ensure the RX FIFO is emptied each time a frame is received. + + @return + This function does not return any value. + + Example: + @code + #define SPI0_BASE_ADDR 0xC2000000 + + uint32_t g_slave_rx_frame = 0; + spi_instance_t g_spi0; + + void slave_frame_handler(uint32_t rx_frame) + { + g_slave_rx_frame = rx_frame; + } + int setup_slave( void ) + { + SPI_init( &g_spi0, SPI0_BASE_ADDR, 1 ); + SPI_configure_slave_mode( &g_spi0 ); + SPI_set_frame_rx_handler( &g_spi0, slave_frame_handler ); + } + @endcode + */ +void SPI_set_frame_rx_handler +( + spi_instance_t * this_spi, + spi_frame_rx_handler_t rx_handler +); + +/***************************************************************************//** + The SPI_set_slave_tx_frame() function is used by the SPI slaves to specify + the frame that will be transmitted, when a transaction is initiated by + the SPI master. This function allows you to assign a slave_tx_frame_handler + function which will be executed upon transmit interrupt when the SPI is + in slave mode. + + @param this_spi + The this_spi parameter is a pointer to a spi_instance_t structure identifying + the CoreSPI hardware block to operate on. This parameter must point to + a g_core_spi global data structure defined within the application code. + + @param frame_value + The frame_value parameter contains the value of the frame to be sent to the + master. + Note: The bit length of the value to be transmitted to the master is + set when the CoreSPI is instantiated in the hardware design. + + @param slave_tx_frame_handler + The slave_tx_frame_handler function pointer will be executed upon occurrence of + transmit interrupt when CoreSPI is operating in slave mode. This parameter + is optional and if set to NULL it is assumed that the frame value is static or + updated asynchronously. + + @return + This function does not return any value. + + Example: + @code + #define SPI0_BASE_ADDR 0xC2000000 + + spi_instance_t g_spi0 ; + const uint32_t slave_tx_frame[2] = { 0x0110F761, 0x0110F671 }; + uint32_t master_rx; + uint32_t slave_frame_idx = 0 ; + + slave_frame_update( spi_instance_t * this_spi ) + { + this_spi->slave_tx_frame = slave_tx_frame[slave_frame_idx++]; + if( slave_frame_idx > 2 ) + slave_frame_idx = 0; + } + main() + { + SPI_init( &g_spi0, SPI0_BASE_ADDR, 1 ); + SPI_configure_master_mode( &g_spi0 ) ; + SPI_set_slave_tx_frame( &g_spi0, slave_tx_frame[slave_frame_idx++], + &slave_frame_update ); + } + @endcode + */ +void SPI_set_slave_tx_frame +( + spi_instance_t * this_spi, + uint32_t frame_value, + spi_slave_frame_tx_handler_t slave_tx_frame_handler +); + +/***************************************************************************//** + The SPI_set_slave_block_buffers() function is used to configure an SPI slave + for block transfer operations. It specifies one or more of the following: + � The data that will be transmitted when accessed by a master. + � The buffer where the data received from a master will be stored. + � The handler function that must be called after the receive buffer has + been filled. + � The number of bytes that must be received from the master before the + receive handler function is called. + These parameters allow the following use cases: + � Slave performing an action after receiving a block of data from a + master containing a command. This action will be performed by the + receive handler based on the content of the receive data buffer. + � Slave returning a block of data to the master. The type of information + is always the same but the actual values change over time. For example, + returning the voltage of a predefined set of analog inputs. + � Slave returning data based on a command contained in the first part of + the SPI transaction. For example, reading the voltage of the analog + input specified by the first data byte by the master. This is achieved + by using the SPI_set_slave_block_buffers() function in conjunction with + functions SPI_set_cmd_handler() and SPI_set_cmd_response(). + + Refer to the SPI_set_cmd_handler() function description for details of + this use case. + + @param this_spi + The this_spi parameter is a pointer to a spi_instance_t structure identifying + the CoreSPI hardware block to operate on. This parameter must point to + a g_core_spi global data structure defined within the application code. + + @param tx_buffer + The tx_buffer parameter is a pointer to a buffer containing the data that + will be sent to the master. This parameter can be set to �0� if the SPI + slave is not intended to be the target of SPI read transactions. + + @param tx_buff_size + The tx_buff_size parameter specifies the number of bytes that will be + transmitted by the SPI slave. It is the number of bytes contained in the + tx_buffer. This parameter can be set to �0� if the SPI slave is not + intended to be the target of SPI read transactions. The driver returns 0s + to the master if there is no buffer specified or the master reads beyond the + end of the buffer. + Note. If SPI_transfer_block() is used to read from this slave and there + is no command handler involved, the buffer size here must be at least the + combined length of the command and response specified by the master and the + bytes at the start corresponding to the command will be discarded by the + master. + + @param rx_buffer + The rx_buffer parameter is a pointer to the buffer where data received + from the master will be stored. This parameter can be set to �0� if the + SPI slave is not intended to be the target of SPI write or write-read + transactions. + + @param rx_buff_size + The rx_buff_size parameter specifies the size of the receive buffer. It is + also the number of bytes that must be received before the receive handler + is called, if a receive handler is specified using the block_rx_handler + parameter. Any bytes received in excess of this are discarded. + This parameter can be set to �0� if the SPI slave is not intended + to be the target of SPI write or write-read transactions. + + @param block_rx_handler + The block_rx_handler parameter is a pointer to a function that will be called + when receive buffer has been filled or the slave select has been de-asserted. + This parameter can be set to �0� if the SPI slave is not intended to be the + target of SPI write or write-read transactions. + + @return + This function does not return any value. + + Example: + @code + Slave Performing Operation Based on Master Command: + In this example the SPI slave is configured to receive 10 bytes of data + or command from the SPI slave, and process the data received from the master. + + #define SPI0_BASE_ADDR 0xC2000000 + + uint32_t nb_of_rx_handler_calls = 0; + spi_instance_t g_spi0; + + void spi1_block_rx_handler_b + ( + uint8_t * rx_buff, + uint16_t rx_size + ) + { + ++nb_of_rx_handler_calls; + } + + void setup_slave( void ) + { + uint8_t slave_rx_buffer[10] = + { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + }; + + SPI_init( &g_spi0, SPI0_BASE_ADDR, 8 ); + SPI_configure_slave_mode( &g_spi0 ); + + SPI_set_slave_block_buffers + ( + &g_spi0, + 0, + 0, + slave_rx_buffer, + sizeof( master_tx_buffer ), + spi1_block_rx_handler_b + ); + } + @endcode + */ +void SPI_set_slave_block_buffers +( + spi_instance_t * this_spi, + const uint8_t * tx_buffer, + uint32_t tx_buff_size, + uint8_t * rx_buffer, + uint32_t rx_buff_size, + spi_block_rx_handler_t block_rx_handler +); + +/***************************************************************************//** + The SPI_isr() function is the top level interrupt handler function for the + CoreSPI driver. You must call SPI_isr() from the system level + (CoreInterrupt and NVIC level) interrupt handler assigned to the interrupt + triggered by the CoreSPI SPIINT signal. Your system level interrupt handler + must also clear the system level interrupt triggered by the CoreSPI SPIINT + signal before returning, to prevent a re-assertion of the same interrupt. + + This function supports all types of interrupt triggered by CoreSPI. It is not + a complete interrupt handler by itself; rather, it is a top level wrapper that + abstracts CoreSPI command interrupt and slave mode transmit interrupt handling + by calling lower level handler functions specific to each type of CoreSPI + interrupt. You must create the lower level handler functions to suit your + application and register them with the driver through calls to the + SPI_set_cmd_handler(), SPI_set_cmd_response() and SPI_set_slave_tx_frame() + functions. + + @param this_spi + The this_spi parameter is a pointer to a spi_instance_t structure identifying + the CoreSPI hardware block to operate on. This parameter must point to + the g_core_spi global data structure defined within the application code. + + @return + This function does not return any value. + + Example: + @code + + Example of configuring a CoreInterrupt connected to the Fabric Interrupt on a + SmartFusion device to handle CoreSPI interrupt. + + #define #define SPI1_INT_IRQ_NB 0 + spi_instance_t g_spi0; + + Void CIC_irq1_handler(void) + { + SPI_isr( &g_spi0 ); + } + + void Fabric_IRQHandler( void ) + { + // Call the CoreInterrupt driver ISR to determine the source of the + // interrupt and call the relevant ISR registered to it. + CIC_irq_handler(); + + // Clear NVIC interrupt status to allow further interrupts + NVIC_ClearPendingIRQ( Fabric_IRQn ); + } + + main() + { + ... + + CIC_init( CIC_BASE_ADDR ); + + // Install handler for SPI IRQ + CIC_set_irq_handler( SPI0_INT_IRQ_NB, CIC_irq1_handler ); + + NVIC_ClearPendingIRQ( Fabric_IRQn ); + NVIC_EnableIRQ( Fabric_IRQn ); + + CIC_enable_irq( SPI1_INT_IRQ_NB ); + + ... + } + @endcode + */ +void SPI_isr +( + spi_instance_t * this_spi +); + +/***************************************************************************//** + The SPI_set_cmd_handler() function specifies a command handler function that + will be called when the number of bytes received reaches the command size + specified as parameter cmd_size. + + This function is used by the SPI slaves performing block transfers. Its + purpose is to allow a SPI slave to decide the data that will be returned to + the master while a SPI transaction is taking place. Typically, one or more + command bytes are sent by the master to request some specific data. The slave + interprets the command byte(s) while one or more turn-around bytes are + transmitted. The slave adjusts its transmit data buffer based on the command + during the turn around time. + + The diagram below provides an example of the use of this function where the + SPI slave returns data bytes D0 to D6 based on the value of a command. The + 3 bytes long command is made up of a command opcode byte followed by an + address byte followed by a size byte. The cmd_handler() function specified + through an earlier call to SPI_set_cmd_handler() is called by the CoreSPI + driver once the third byte is received. The cmd_handler() function + interprets the command bytes and calls SPI_set_cmd_response() to set the SPI + slave's response transmit buffer with the data to be transmitted after the + turnaround bytes (T0 to T3). The number of turnaround bytes must be + sufficient to give enough time for the cmd_handler() to execute. The number + of turnaround bytes is specified by the protocol used on top of the SPI + transport layer so that master and slave agree on the number of turn around + bytes. + + t0 t1 t2 t3 t4 + | | | | | + |------------------------------------------------------------------| + | COMMAND | TURN-AROUND | DATA | + |------------------------------------------------------------------| + | C | A | S | T0 | T1 | T2 | T3 | D0 | D1 | D2 | D3 | D4 | D5 | D6 | + |------------------------------------------------------------------| + | + | + --> cmd_handler() called here. + | + | + --> SPI_set_cmd_response() called here by + implementation of cmd_handler() to set the data + that will be transmitted by the SPI slave. + + @param this_spi + The this_spi parameter is a pointer to a spi_instance_t structure identifying + the CoreSPI hardware block to operate on. This parameter must point to + the g_core_spi global data structure defined within the application code. + + @param cmd_handler + The cmd_handler parameter is a pointer to a function with the prototype: + void cmd_handler(uint8_t * rx_buff, uint32_t rx_size); + It specifies the function that will be called when the number of bytes + specified by the parameter cmd_size has been received. + + @param cmd_size + The cmd_size parameter specifies the number of bytes that must be received + before the command handler function specified by cmd_handler is called. The + CoreSPI supports cmd_size values in the range 1 to 7. + + @return + This function does not return any value. + + Example: + @code + The following example demonstrates how to configure CoreSPI to implement + the protocol given as an example above. The configure_slave() function + configures CoreSPI. It sets receive and transmit buffers. The transmit + buffer specified through the call to SPI_set_slave_block_buffers() function + specifies the data that will be returned to the master in bytes between + t0 and t3. These bytes will be sent to the master while the master transmits + the command and dummy bytes. The spi_slave_cmd_handler() function will be + called by the driver at time t1 after the 3 command bytes have been received. + The spi_block_rx_handler() function will be called by the driver at time t4, + when the transaction completes and the slave select signal becomes + de-asserted. + + #define SPI0_BASE_ADDR 0xC2000000 + #define COMMAND_SIZE 3 + #define NB_OF_DUMMY_BYTES 4 + #define MAX_TRANSACTION_SIZE 16 + + spi_instance_t g_spi0; + uint8_t slave_tx_buffer[COMMAND_SIZE + NB_OF_DUMMY_BYTES]; + uint8_t slave_rx_buffer[MAX_TRANSACTION_SIZE]; + + void configure_slave( void ) + { + SPI_init( &g_spi0, SPI0_BASE_ADDR, 8 ); + SPI_configure_slave_mode( &g_spi0 ); + SPI_set_slave_block_buffers + ( + &g_spi0, + slave_tx_buffer, + COMMAND_SIZE + NB_OF_DUMMY_BYTES, + slave_rx_buffer, + sizeof(slave_rx_buffer), + spi_block_rx_handler + ); + + SPI_set_cmd_handler + ( + &g_spi0, + spi_slave_cmd_handler, + COMMAND_SIZE + ); + } + + void spi_slave_cmd_handler + ( + uint8_t * rx_buff, + uint32_t rx_size + ) + { + uint8_t command; + uint8_t address; + uint8_t size; + uint8_t * p_response; + uint32_t response_size; + + command = rx_buff[0]; + address = rx_buff[1]; + size = rx_buff[2]; + + p_response = get_response_data( command, address, size, &response_size ); + SPI_set_cmd_response( &g_spi0, p_response, response_size ); + } + + void spi_block_rx_handler + ( + uint8_t * rx_buff, + uint32_t rx_size + ) + { + process_rx_data( rx_buff, rx_size ); + } + @endcode + */ +void SPI_set_cmd_handler +( + spi_instance_t * this_spi, + spi_block_rx_handler_t cmd_handler, + uint32_t cmd_size +); + +/***************************************************************************//** + The SPI_set_cmd_response() function specifies the data that will be returned + to the master. See the description of SPI_set_cmd_handler() for details. + + @param this_spi + The this_spi parameter is a pointer to a spi_instance_t structure identifying + the CoreSPI hardware block to operate on. This parameter must point to + a g_core_spi global data structure defined within the application code. + + @param resp_tx_buffer + The resp_tx_buffer parameter is a pointer to the buffer containing the data + that must be returned to the host in the data phase of a SPI transaction. + + @param resp_buff_size + The resp_buff_size parameter specifies the size of the buffer pointed to + by the resp_tx_buffer parameter. + + @return + This function does not return any value. + */ +void SPI_set_cmd_response +( + spi_instance_t * this_spi, + const uint8_t * resp_tx_buffer, + uint32_t resp_buff_size +); + +/***************************************************************************//** + The SPI_enable() function enables the CoreSPI and allows it respond to external + signals. It is usually called to re-enable a CoreSPI instance which has been + disabled previously via a call to SPI_disable() as the normal state of a CoreSPI + after initialization is enabled. + + @param this_spi + The this_spi parameter is a pointer to a spi_instance_t structure identifying + the CoreSPI hardware block to operate on. This parameter must point to + the g_core_spi global data structure defined within the application code. + + @return + This function does not return any value. + */ +void SPI_enable +( + spi_instance_t * this_spi +); + +/***************************************************************************//** + The SPI_disable() function disables the CoreSPI and stops it responding to + external signals. + + @param this_spi + The this_spi parameter is a pointer to a spi_instance_t structure identifying + the CoreSPI hardware block to operate on. This parameter must point to + the g_core_spi global data structure defined within the application code. + + @return + This function does not return any value. + */ +void SPI_disable +( + spi_instance_t * this_spi +); + +#ifdef __cplusplus +} +#endif + +#endif /* CORE_SPI_H_*/ diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreSPI/corespi_regs.h b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreSPI/corespi_regs.h new file mode 100644 index 0000000..d92fb80 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreSPI/corespi_regs.h @@ -0,0 +1,267 @@ +/******************************************************************************* + * (c) Copyright 2008-2022 Microchip FPGA Embedded Systems Solutions. + * + * @file corespi_regs.h + * @author Microchip FPGA Embedded Systems Solutions + * @brief CoreSPI register definitions + * + */ +#ifndef CORESPI_REGS_H_ +#define CORESPI_REGS_H_ + +/******************************************************************************* + * Control register 1: + *------------------------------------------------------------------------------ + */ +#define CTRL1_REG_OFFSET 0x00u + +#define CTRL1_ENABLE_OFFSET 0x00u +#define CTRL1_ENABLE_MASK 0x01u +#define CTRL1_ENABLE_SHIFT 0x00 + +#define CTRL1_MASTER_OFFSET 0x00u +#define CTRL1_MASTER_MASK 0x02u +#define CTRL1_MASTER_SHIFT 0x01 + +#define CTRL1_INTRXDATA_OFFSET 0x00u +#define CTRL1_INTRXDATA_MASK 0x04u +#define CTRL1_INTRXDATA_SHIFT 0x02 + +#define CTRL1_INTTXDONE_OFFSET 0x00u +#define CTRL1_INTTXDONE_MASK 0x08u +#define CTRL1_INTTXDONE_SHIFT 0x03 + +#define CTRL1_INTRXOVFLOW_OFFSET 0x00u +#define CTRL1_INTRXOVFLOW_MASK 0x10u +#define CTRL1_INTRXOVFLOW_SHIFT 0x04 + +#define CTRL1_INTTXURUN_OFFSET 0x00u +#define CTRL1_INTTXURUN_MASK 0x20u +#define CTRL1_INTTXURUN_SHIFT 0x05 + +#define CTRL1_FRAMEURUN_OFFSET 0x00u +#define CTRL1_FRAMEURUN_MASK 0x40u +#define CTRL1_FRAMEURUN_SHIFT 0x06 + +#define CTRL1_OENOFF_OFFSET 0x00u +#define CTRL1_OENOFF_MASK 0x80u +#define CTRL1_OENOFF_SHIFT 0x07 + +/******************************************************************************* + * Interrupt clear register: + *------------------------------------------------------------------------------ + */ +#define INTCLR_REG_OFFSET 0x04u + +#define INTCLR_TXDONE_OFFSET 0x04u +#define INTCLR_TXDONE_MASK 0x01u +#define INTCLR_TXDONE_SHIFT 0x00 + +#define INTCLR_RXDONE_OFFSET 0x04u +#define INTCLR_RXDONE_MASK 0x02u +#define INTCLR_RXDONE_SHIFT 0x01 + +#define INTCLR_RXOVERFLOW_OFFSET 0x04u +#define INTCLR_RXOVERFLOW_MASK 0x04u +#define INTCLR_RXOVERFLOW_SHIFT 0x02 + +#define INTCLR_TXUNDERRUN_OFFSET 0x04u +#define INTCLR_TXUNDERRUN_MASK 0x08u +#define INTCLR_TXUNDERRUN_SHIFT 0x03 + +#define INTCLR_CMDINT_OFFSET 0x04u +#define INTCLR_CMDINT_MASK 0x10u +#define INTCLR_CMDINT_SHIFT 0x04 + +#define INTCLR_SSEND_OFFSET 0x04u +#define INTCLR_SSEND_MASK 0x20u +#define INTCLR_SSEND_SHIFT 0x05 + +#define INTCLR_RXDATA_OFFSET 0x04u +#define INTCLR_RXDATA_MASK 0x40u +#define INTCLR_RXDATA_SHIFT 0x06 + +#define INTCLR_TXDATA_OFFSET 0x04u +#define INTCLR_TXDATA_MASK 0x80u +#define INTCLR_TXDATA_SHIFT 0x07 + +/******************************************************************************* + * Receive data register: + *------------------------------------------------------------------------------ + */ +#define RXDATA_REG_OFFSET 0x08u + +/******************************************************************************* + * Transmit data register: + *------------------------------------------------------------------------------ + */ +#define TXDATA_REG_OFFSET 0x0Cu + +/******************************************************************************* + * Masked interrupt status register: + *------------------------------------------------------------------------------ + */ +#define INTMASK_REG_OFFSET 0x10u + +#define INTMASK_TXDONE_OFFSET 0x10u +#define INTMASK_TXDONE_MASK 0x01u +#define INTMASK_TXDONE_SHIFT 0x00 + +#define INTMASK_RXDONE_OFFSET 0x10u +#define INTMASK_RXDONE_MASK 0x02u +#define INTMASK_RXDONE_SHIFT 0x01 + +#define INTMASK_RXOVERFLOW_OFFSET 0x10u +#define INTMASK_RXOVERFLOW_MASK 0x04u +#define INTMASK_RXOVERFLOW_SHIFT 0x02 + +#define INTMASK_TXUNDERRUN_OFFSET 0x10u +#define INTMASK_TXUNDERRUN_MASK 0x08u +#define INTMASK_TXUNDERRUN_SHIFT 0x03 + +#define INTMASK_CMDINT_OFFSET 0x10u +#define INTMASK_CMDINT_MASK 0x10u +#define INTMASK_CMDINT_SHIFT 0x04 + +#define INTMASK_SSEND_OFFSET 0x10u +#define INTMASK_SSEND_MASK 0x20u +#define INTMASK_SSEND_SHIFT 0x05 + +#define INTMASK_RXDATA_OFFSET 0x10u +#define INTMASK_RXDATA_MASK 0x40u +#define INTMASK_RXDATA_SHIFT 0x06 + +#define INTMASK_TXDATA_OFFSET 0x10u +#define INTMASK_TXDATA_MASK 0x80u +#define INTMASK_TXDATA_SHIFT 0x07 + +/******************************************************************************* + * Raw interrupt status register: + *------------------------------------------------------------------------------ + */ +#define INTRAW_REG_OFFSET 0x14u + +#define INTRAW_TXDONE_OFFSET 0x14u +#define INTRAW_TXDONE_MASK 0x01u +#define INTRAW_TXDONE_SHIFT 0x00 + +#define INTRAW_RXDONE_OFFSET 0x14u +#define INTRAW_RXDONE_MASK 0x02u +#define INTRAW_RXDONE_SHIFT 0x01 + +#define INTRAW_RXOVERFLOW_OFFSET 0x14u +#define INTRAW_RXOVERFLOW_MASK 0x04u +#define INTRAW_RXOVERFLOW_SHIFT 0x02 + +#define INTRAW_TXUNDERRUN_OFFSET 0x14u +#define INTRAW_TXUNDERRUN_MASK 0x08u +#define INTRAW_TXUNDERRUN_SHIFT 0x03 + +#define INTRAW_CMDINT_OFFSET 0x14u +#define INTRAW_CMDINT_MASK 0x10u +#define INTRAW_CMDINT_SHIFT 0x04 + +#define INTRAW_SSEND_OFFSET 0x14u +#define INTRAW_SSEND_MASK 0x20u +#define INTRAW_SSEND_SHIFT 0x05 + +#define INTRAW_RXDATA_OFFSET 0x14u +#define INTRAW_RXDATA_MASK 0x40u +#define INTRAW_RXDATA_SHIFT 0x06 + +#define INTRAW_TXDATA_OFFSET 0x14u +#define INTRAW_TXDATA_MASK 0x80u +#define INTRAW_TXDATA_SHIFT 0x07 + +/******************************************************************************* + * Control register 2: + *------------------------------------------------------------------------------ + */ +#define CTRL2_REG_OFFSET 0x18u + +#define CTRL2_CMDSIZE_OFFSET 0x18u +#define CTRL2_CMDSIZE_MASK 0x07u +#define CTRL2_CMDSIZE_SHIFT 0x00 + +#define CTRL2_INTCMD_OFFSET 0x18u +#define CTRL2_INTCMD_MASK 0x10u +#define CTRL2_INTCMD_SHIFT 0x04 + +#define CTRL2_INTSSEND_OFFSET 0x18u +#define CTRL2_INTSSEND_MASK 0x20u +#define CTRL2_INTSSEND_SHIFT 0x05 + +#define CTRL2_INTRXDATA_OFFSET 0x18u +#define CTRL2_INTRXDATA_MASK 0x40u +#define CTRL2_INTRXDATA_SHIFT 0x06 + +#define CTRL2_INTTXDATA_OFFSET 0x18u +#define CTRL2_INTTXDATA_MASK 0x80u +#define CTRL2_INTTXDATA_SHIFT 0x07 + +/******************************************************************************* + * Command register: + *------------------------------------------------------------------------------ + */ +#define CMD_REG_OFFSET 0x1Cu + +#define CMD_RXFIFORST_OFFSET 0x1Cu +#define CMD_RXFIFORST_MASK 0x01u +#define CMD_RXFIFORST_SHIFT 0x00 + +#define CMD_TXFIFORST_OFFSET 0x1Cu +#define CMD_TXFIFORST_MASK 0x02u +#define CMD_TXFIFORST_SHIFT 0x01 + +/******************************************************************************* + * Status register: + *------------------------------------------------------------------------------ + */ +#define STATUS_REG_OFFSET 0x20u + +#define STATUS_FIRSTFRAME_OFFSET 0x20u +#define STATUS_FIRSTFRAME_MASK 0x01u +#define STATUS_FIRSTFRAME_SHIFT 0x00 + +#define STATUS_DONE_OFFSET 0x20u +#define STATUS_DONE_MASK 0x02u +#define STATUS_DONE_SHIFT 0x01 + +#define STATUS_RXEMPTY_OFFSET 0x20u +#define STATUS_RXEMPTY_MASK 0x04u +#define STATUS_RXEMPTY_SHIFT 0x02 + +#define STATUS_TXFULL_OFFSET 0x20u +#define STATUS_TXFULL_MASK 0x08u +#define STATUS_TXFULL_SHIFT 0x03 + +#define STATUS_RXOVFLOW_OFFSET 0x20u +#define STATUS_RXOVFLOW_MASK 0x10u +#define STATUS_RXOVFLOW_SHIFT 0x04 + +#define STATUS_TXUNDERRUN_OFFSET 0x20u +#define STATUS_TXUNDERRUN_MASK 0x20u +#define STATUS_TXUNDERRUN_SHIFT 0x05 + +#define STATUS_SSEL_OFFSET 0x20u +#define STATUS_SSEL_MASK 0x40u +#define STATUS_SSEL_SHIFT 0x06 + +#define STATUS_ACTIVE_OFFSET 0x20u +#define STATUS_ACTIVE_MASK 0x80u +#define STATUS_ACTIVE_SHIFT 0x07 + +/******************************************************************************* + * Slave select register: + *------------------------------------------------------------------------------ + */ +#define SSEL_REG_OFFSET 0x24u + +/******************************************************************************* + * Transmit data last register: + *------------------------------------------------------------------------------ + */ +#define TXLAST_REG_OFFSET 0x28u + + +#endif /*CORESPI_REGS_H_*/ diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreSysServices_PF/core_sysservices_pf.c b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreSysServices_PF/core_sysservices_pf.c new file mode 100644 index 0000000..82ab53f --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreSysServices_PF/core_sysservices_pf.c @@ -0,0 +1,844 @@ +/******************************************************************************* + * (c) Copyright 2019-2021 Microchip FPGA Embedded Systems Solutions. + * + * PF_System_Services driver implementation. See file "core_syservices_pf.h" for + * description of the functions implemented in this file. + * + */ +#ifndef LEGACY_DIR_STRUCTURE +#include "hal/hal.h" +#include "core_sysservices_pf.h" +#include "coresysservicespf_regs.h" + +#else +#include "hal.h" +#include "core_sysservices_pf.h" +#include "coresysservicespf_regs.h" +#include "hal_assert.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#define NULL_BUFFER (( uint8_t* ) 0) + +static uint8_t execute_ss_command +( + uint8_t cmd_opcode, + const uint8_t* cmd_data, + uint16_t cmd_data_size, + const uint8_t* p_response, + uint16_t response_size, + uint16_t mb_offset, + uint16_t response_offset +); + +uint32_t g_css_pf_base_addr = 0u; + +/***************************************************************************//** + * SYS_init() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +void +SYS_init +( + uint32_t base_addr +) +{ + g_css_pf_base_addr = base_addr; +} + +/***************************************************************************//** + * SYS_get_serial_number() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t +SYS_get_serial_number +( + const uint8_t * p_serial_number, + uint16_t mb_offset +) +{ + uint8_t status = SYS_PARAM_ERR; + + if (p_serial_number == NULL_BUFFER) + { + return status; + } + + status = execute_ss_command(SERIAL_NUMBER_REQUEST_CMD, + NULL_BUFFER, + 0u, + p_serial_number, + SERIAL_NUMBER_RESP_LEN, + mb_offset, + 0u); + + return status; +} + +/***************************************************************************//** + * SYS_get_user_code() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t +SYS_get_user_code +( + const uint8_t * p_user_code, + uint16_t mb_offset +) +{ + uint8_t status = SYS_PARAM_ERR; + + if(p_user_code == NULL_BUFFER) + { + return status; + } + + status = execute_ss_command(USERCODE_REQUEST_CMD, + NULL_BUFFER, + 0u, + p_user_code, + USERCODE_RESP_LEN, + mb_offset, + 0u); + return status; +} + +/***************************************************************************//** + * SYS_get_design_info() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t +SYS_get_design_info +( + const uint8_t * p_design_info, + uint16_t mb_offset +) +{ + uint8_t status = SYS_PARAM_ERR; + + if(p_design_info == NULL_BUFFER) + { + return status; + } + + status = execute_ss_command(DESIGN_INFO_REQUEST_CMD, + NULL_BUFFER, + 0u, + p_design_info, + DESIGN_INFO_RESP_LEN, + mb_offset, + 0u); + return status; +} + +/***************************************************************************//** + * SYS_get_device_certificate() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t +SYS_get_device_certificate +( + const uint8_t * p_device_certificate, + uint16_t mb_offset +) +{ + uint8_t status = SYS_PARAM_ERR; + + if(p_device_certificate == NULL_BUFFER) + { + return status; + } + + status = execute_ss_command(DEVICE_CERTIFICATE_REQUEST_CMD, + NULL_BUFFER, + 0u, + p_device_certificate, + DEVICE_CERTIFICATE_RESP_LEN, + mb_offset, + 0u); + return status; +} + +/***************************************************************************//** + * SYS_read_digest() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t SYS_read_digest +( + const uint8_t * p_digest, + uint16_t mb_offset +) +{ + uint8_t status = SYS_PARAM_ERR; + + if(p_digest == NULL_BUFFER) + { + return status; + } + +#ifndef CORESYSSERVICES_MPFS + status = execute_ss_command(READ_DIGEST_REQUEST_CMD, + NULL_BUFFER, + 0u, + p_digest, + READ_DIGEST_RESP_LEN, + mb_offset, + 0u); +#else + status = execute_ss_command(READ_DIGEST_REQUEST_CMD, + NULL_BUFFER, + 0u, + p_digest, + READ_DIGEST_MPFS_RESP_LEN, + mb_offset, + 0u); +#endif + return status; + +} + +/***************************************************************************//** + * SYS_query_security() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t SYS_query_security +( + uint8_t * p_security_locks, + uint16_t mb_offset +) +{ + uint8_t status = SYS_PARAM_ERR; + uint8_t idx = 0u; + + if(p_security_locks == NULL_BUFFER) + { + return status; + } + +#ifndef CORESYSSERVICES_MPFS + uint8_t buf[12] = {0}; + /* Actual QUERY_SECURITY_RESP_LEN is 9 or 33 but PF_System_Services core + * needs number of words instead of number of bytes to be written to or read + * from MailBox */ + status = execute_ss_command(QUERY_SECURITY_REQUEST_CMD, + NULL_BUFFER, + 0u, + buf, + (QUERY_SECURITY_RESP_LEN + 3u), + mb_offset, + 0u); + + for (idx = 0u; idx < 9u; idx++) + { + *(p_security_locks+idx) = buf[idx]; + } + +#else + uint8_t buf[36] = {0}; + + status = execute_ss_command(QUERY_SECURITY_REQUEST_CMD, + NULL_BUFFER, + 0u, + buf, + (QUERY_SECURITY_MPFS_RESP_LEN + 3u), + mb_offset, + 0u); + + for (idx = 0u; idx < 33u; idx++) + { + *(p_security_locks+idx) = buf[idx]; + } + +#endif + + return status; +} + +/***************************************************************************//** + * SYS_read_debug_info() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t SYS_read_debug_info +( + const uint8_t * p_debug_info, + uint16_t mb_offset +) +{ + uint8_t status = SYS_PARAM_ERR; + + if(p_debug_info == NULL_BUFFER) + { + return status; + } + + status = execute_ss_command(READ_DEBUG_INFO_REQUEST_CMD, + NULL_BUFFER, + 0u, + p_debug_info, + READ_DEBUG_INFO_RESP_LEN, + mb_offset, + 0u); + return status; +} + +#ifdef CORESYSSERVICES_MPFS +/***************************************************************************//** + * SYS_read_envm_parameter() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t SYS_read_envm_parameter +( + uint8_t * p_envm_param, + uint16_t mb_offset +) +{ + uint8_t status = SYS_PARAM_ERR; + + if(p_envm_param == NULL_BUFFER) + { + return status; + } + + status = execute_ss_command(READ_ENVM_PARAM_REQUEST_CMD, + NULL_BUFFER, + 0, + p_envm_param, + READ_ENVM_PARAM_RESP_LEN, + mb_offset, + 0); + return status; +} + +#endif + +/***************************************************************************//** + * SYS_puf_emulation_service() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t SYS_puf_emulation_service +( + const uint8_t * p_challenge, + uint8_t op_type, + uint8_t* p_response, + uint16_t mb_offset +) +{ + uint8_t status = SYS_PARAM_ERR; + uint8_t mb_format[20] = {0x00}; + uint8_t index = 0u; + + if((p_response == NULL_BUFFER) || (p_challenge == NULL_BUFFER)) + { + return status; + } + + /* Frame the data required for mailbox */ + mb_format[index] = op_type; + + for (index = 4u; index < 20u; index++) + { + mb_format[index] = p_challenge[index - 4u]; + } + + status = execute_ss_command(PUF_EMULATION_SERVICE_REQUEST_CMD, + mb_format, + PUF_EMULATION_SERVICE_CMD_LEN, + p_response, + PUF_EMULATION_SERVICE_RESP_LEN, + mb_offset, + 5u); /* mentioning offset to number of words instead of bytes */ + + return status; +} + +/***************************************************************************//** + * SYS_digital_signature_service() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t SYS_digital_signature_service +( + const uint8_t* p_hash, + uint8_t format, + uint8_t* p_response, + uint16_t mb_offset +) +{ + uint8_t status = SYS_PARAM_ERR; + + if((p_hash == NULL_BUFFER) || (p_response == NULL_BUFFER)) + { + return status; + } + + if (format == DIGITAL_SIGNATURE_RAW_FORMAT_REQUEST_CMD) + { + status = execute_ss_command(DIGITAL_SIGNATURE_RAW_FORMAT_REQUEST_CMD, + p_hash, + DIGITAL_SIGNATURE_HASH_LEN, + p_response, + DIGITAL_SIGNATURE_RAW_FORMAT_RESP_SIZE, + mb_offset, + 12u); /* mentioning offset to number of words instead of bytes */ + } + else + { + status = execute_ss_command(DIGITAL_SIGNATURE_DER_FORMAT_REQUEST_CMD, + p_hash, + DIGITAL_SIGNATURE_HASH_LEN, + p_response, + DIGITAL_SIGNATURE_DER_FORMAT_RESP_SIZE, + mb_offset, + 12u); /* mentioning offset to number of words instead of bytes */ + } + + return status; +} + +/***************************************************************************//** + * SYS_secure_nvm_write() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t SYS_secure_nvm_write +( + uint8_t format, + uint8_t snvm_module, + const uint8_t* p_data, + const uint8_t* p_user_key, + uint16_t mb_offset +) +{ + uint8_t frame[256] = {0x00}; + uint8_t* p_frame = &frame[0]; + uint16_t index = 0u; + uint8_t status = SYS_PARAM_ERR; + + HAL_ASSERT(!(NULL_BUFFER == p_data)); + HAL_ASSERT(!(NULL_BUFFER == p_user_key)); + HAL_ASSERT(!(snvm_module >= 221u)); + + if((p_data == NULL_BUFFER) || (p_user_key == NULL_BUFFER) + || (snvm_module >= 221)) + { + return status; + } + + if ((format != SNVM_NON_AUTHEN_TEXT_REQUEST_CMD) + || (format != SNVM_AUTHEN_TEXT_REQUEST_CMD) + || (format != SNVM_AUTHEN_CIPHERTEXT_REQUEST_CMD)) + { + return status; + } + + *p_frame = snvm_module; /* SNVMADDR - SNVM module */ + + p_frame += 4u; /* Next 3 bytes RESERVED - For alignment */ + + /* Copy user key and send the command/data to mailbox. */ + if ((format == SNVM_AUTHEN_TEXT_REQUEST_CMD) || + (format == SNVM_AUTHEN_CIPHERTEXT_REQUEST_CMD)) + { + /* Copy user data */ + for (index = 0u; index < (AUTHENTICATED_TEXT_DATA_LEN - USER_SECRET_KEY_LEN - 4u); index++) + { + *p_frame = p_data[index]; + p_frame++; + } + + /* Copy user key */ + for (index = 0u; index < USER_SECRET_KEY_LEN; index++) + { + *p_frame = p_user_key[index]; + p_frame++; + } + + status = execute_ss_command(format, + &frame[0], + AUTHENTICATED_TEXT_DATA_LEN, + NULL_BUFFER, + 0u, + mb_offset, + 0u); + } + else + { + /* Copy user data */ + for (index = 0u; index < (NON_AUTHENTICATED_TEXT_DATA_LEN - 4u); index++) + { + *(p_frame+index) = p_data[index]; + } + + status = execute_ss_command(format, + &frame[0], + NON_AUTHENTICATED_TEXT_DATA_LEN, + NULL_BUFFER, + 0u, + mb_offset, + 0u); + } + + return status; +} + +/***************************************************************************//** + * SYS_secure_nvm_read() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t SYS_secure_nvm_read +( + uint8_t snvm_module, + const uint8_t* p_user_key, + uint8_t* p_admin, + uint8_t* p_data, + uint16_t data_len, + uint16_t mb_offset +) +{ + /* Frame the message. */ + uint8_t frame[16] = {0x00u}; + uint8_t* p_frame = &frame[0u]; + uint8_t status = SYS_PARAM_ERR; + uint8_t response[256] = {0x00u}; + uint16_t index = 0u; + + HAL_ASSERT(!(NULL_BUFFER == p_data)); + HAL_ASSERT(!(NULL_BUFFER == p_admin)); + HAL_ASSERT(!(snvm_module > 221u)); + + HAL_ASSERT(data_len == 236u || data_len == 252u); + + if((p_data == NULL_BUFFER) || + (snvm_module >= 221) || + (p_admin == NULL_BUFFER)) + { + return status; + } + + *p_frame = snvm_module; /* SNVMADDR - SNVM module */ + + p_frame += 4u; /* RESERVED - For alignment */ + + /* Copy user key */ + if (236u == data_len) + { + HAL_ASSERT(p_user_key != NULL_BUFFER); + + if(p_user_key == NULL_BUFFER) + { + return status; + } + + for (index = 0u; index < 12u; index++) + { + *p_frame = p_user_key[index]; + p_frame++; + } + } + else + { + p_frame += 12u; + } + + status = execute_ss_command(SNVM_READ_REQUEST_CMD, + &frame[0], + 16u, + response, + (data_len + 4u), + mb_offset, + 4u); /* mentioning offset to number of words instead of bytes */ + + if (SYS_SUCCESS == status) + { + for (index = 0u; index < 4u; index++) + { + *(p_admin+index) = (uint32_t)response[index]; + } + + + /* Copy data into user buffer. */ + for (index = 4u; index < (data_len + 4u); index++) + { + *(p_data + (index - 4u)) = response[index]; + } + } + else + { + ; + } + + return status; +} + +/***************************************************************************//** + * SYS_nonce_service() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t SYS_nonce_service +( + const uint8_t * p_nonce, + uint16_t mb_offset +) +{ + uint8_t status = SYS_PARAM_ERR; + + if((p_nonce == NULL_BUFFER)) + { + return status; + } + + status = execute_ss_command(NONCE_SERVICE_REQUEST_CMD, + NULL_BUFFER, + 0u, + p_nonce, + NONCE_SERVICE_RESP_LEN, + mb_offset, + 0u); + + return status; +} + +/***************************************************************************//** + * SYS_bitstream_authenticate_service() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t SYS_bitstream_authenticate_service +( + uint32_t spi_flash_address, + uint16_t mb_offset +) +{ + uint8_t status = SYS_PARAM_ERR; + uint32_t l_spi_flash_address = spi_flash_address; + status = execute_ss_command(BITSTREAM_AUTHENTICATE_CMD, + (uint8_t* )&l_spi_flash_address, + 4u, + NULL_BUFFER, + 0u, + mb_offset, + 0u); + + return status; +} + +/***************************************************************************//** + * SYS_IAP_image_authenticate_service() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t SYS_IAP_image_authenticate_service +( + uint8_t spi_idx +) +{ + uint8_t status = SYS_PARAM_ERR; + + HAL_ASSERT(!(spi_idx == 1u)); + + if (spi_idx == 1u) + { + return status; + } + + status = execute_ss_command(IAP_BITSTREAM_AUTHENTICATE_CMD, + NULL_BUFFER, + 0u, + NULL_BUFFER, + 0u, + spi_idx, + 0u); + + return status; +} + +/***************************************************************************//** + * SYS_digest_check_service() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t SYS_digest_check_service +( + uint32_t options, + uint16_t mb_offset +) +{ + uint8_t status = SYS_PARAM_ERR; + uint32_t l_options = options; + + status = execute_ss_command(DIGEST_CHECK_CMD, + (uint8_t* )&l_options, + 4u, + NULL_BUFFER, + 0u, + mb_offset, + 0u); + return status; +} + +/***************************************************************************//** + * SYS_iap_service() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t SYS_iap_service +( + uint8_t iap_cmd, + uint32_t spiaddr +) +{ + uint8_t status = SYS_PARAM_ERR; + uint32_t l_spiaddr = spiaddr; + + if ((IAP_PROGRAM_BY_SPIIDX_CMD == iap_cmd) || (IAP_VERIFY_BY_SPIIDX_CMD == iap_cmd)) + { + HAL_ASSERT(!(1u == spiaddr)); + } + + status = execute_ss_command(iap_cmd, + (uint8_t*)&l_spiaddr, + 4u, + NULL_BUFFER, + 0u, + spiaddr, + 0u); + + return status; +} + +/***************************************************************************//** + Internal functions. +*/ +/* +This function executes the SS command. If Mailbox input data is required by the +it will first load it from cmd_data into the Mailbox. If the service requires +the response data to be read from mailbox, it will do so and store it in p_response. +*/ +static uint8_t execute_ss_command +( + uint8_t cmd_opcode, + const uint8_t* cmd_data, + uint16_t cmd_data_size, + const uint8_t* p_response, + uint16_t response_size, + uint16_t mb_offset, + uint16_t response_offset +) +{ + /* Pointer used during Writing to Mailbox memory. */ + uint32_t status = 0u; + uint16_t idx = 0u; + uint16_t ss_command = 0u; + uint32_t* word_buf; + uint16_t timeout_count = SS_TIMEOUT_COUNT; + + /* making sure that the system controller is not executing any service i.e. + SS_USER_BUSY is gone 0 */ + + while (1u == HAL_get_32bit_reg_field(g_css_pf_base_addr, SS_USER_BUSY)) + { + --timeout_count; + + if (timeout_count == 0) + { + return SS_USER_BUSY_TIMEOUT; + } + } + + /* Form the SS command: bit 0to6 is the opcode, bit 7to15 is the Mailbox offset + For some services this field has another meaning + (e.g. for IAP bitstream auth. it means spi_idx) */ + ss_command = ((mb_offset << 7u) | (cmd_opcode & 0x7Fu)); + + /* Load the command register with the SS request command code*/ + HAL_set_32bit_reg(g_css_pf_base_addr, SS_CMD, ss_command); + + if (cmd_data_size > 0u) + { + HAL_ASSERT(!(NULL_BUFFER == cmd_data)); + HAL_ASSERT(!(cmd_data_size % 4u)); + + /* Load the MBX_WCNT register with number of words */ + HAL_set_32bit_reg( g_css_pf_base_addr, MBX_WCNT, (cmd_data_size/4u)); + + /* Load the MBX_WADDR register with offset of input data (write to Mailbox) + For all the services this offset remains either 0 or Not applicable + for the services in which no Mailbox write is required.*/ + HAL_set_32bit_reg( g_css_pf_base_addr, MBX_WADDR, (0x00u + mb_offset)); + + } + + if (response_size > 0u) + { + HAL_ASSERT(!(NULL_BUFFER == p_response)); + HAL_ASSERT(!(response_size % 4u)); + + /* + Load the MBX_RWCNT register with number of words to be read from Mailbox + */ + HAL_set_32bit_reg( g_css_pf_base_addr, MBX_RCNT, (response_size/4u)); + + /* + Load the MBX_RADRDESC register with offset address within the mailbox + format for that particular service. + It will be 0 for the services where there is no output data from G5CONTROL + is expected. + This function assumes that this value is pre-calculated by service specific + functions as this value is fixed for each service. + */ + HAL_set_32bit_reg( g_css_pf_base_addr, MBX_RADDR, (response_offset + mb_offset)); + } + + /*Set the request bit in SYS_SERV_REQ register to start the service*/ + HAL_set_32bit_reg_field(g_css_pf_base_addr, SS_REQ_REQ, 0x01u); + + if (cmd_data_size > 0u) + { + word_buf = (uint32_t*)cmd_data; + + /* Write the user data into mail box. */ + for (idx = 0u; idx < (cmd_data_size/4u); idx++) + { + HAL_set_32bit_reg( g_css_pf_base_addr, MBX_WDATA, word_buf[idx]); + } + } + + timeout_count = SS_TIMEOUT_COUNT; + if (response_size > 0u) + { + word_buf = (uint32_t*)p_response; + + for (idx = 0u; idx < (response_size/4u); idx++) + { + while (0u == HAL_get_32bit_reg_field(g_css_pf_base_addr, + SS_USER_RDVLD)) + { + --timeout_count; + + if (timeout_count == 0) + { + return SS_USER_RDVLD_TIMEOUT; + } + } + word_buf[idx] = HAL_get_32bit_reg(g_css_pf_base_addr, MBX_RDATA); + } + } + + timeout_count = SS_TIMEOUT_COUNT; + /* make sure that service is complete i.e. SS_USER_BUSY is gone 0 */ + while (1u == HAL_get_32bit_reg_field(g_css_pf_base_addr, SS_USER_BUSY)) + { + --timeout_count; + + if (timeout_count == 0) + { + return SS_USER_RDVLD_TIMEOUT; + } + } + + /* Read the status returned by System Controller */ + status = HAL_get_32bit_reg(g_css_pf_base_addr, SS_STAT); + + return (uint8_t)status; +} + +#ifdef __cplusplus +} +#endif diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreSysServices_PF/core_sysservices_pf.h b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreSysServices_PF/core_sysservices_pf.h new file mode 100644 index 0000000..aa1c82b --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreSysServices_PF/core_sysservices_pf.h @@ -0,0 +1,1222 @@ +/******************************************************************************* + * Copyright 2019-2021 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * This file contains the application programming interface for the + * CoreSysServices_PF bare metal driver. + */ +/*=========================================================================*//** + @mainpage CoreSysServices_PF Bare Metal Driver. + + @section intro_sec Introduction + The PolarFire System Services (PF_SYSTEM_SERVICES) SgCore enables executing + system services on the PolarFire and PolarFire SoC device. The System services + are System Controller actions initiated via the System Controller’s System + Service Interface (SSI). The PolarFire System Services SgCore provides a + method to initiate these system services. The PF_SYSTEM_SERVICES interacts + with the system controller on SSI and Mailbox interface to initiate system + services, exchange data required for that services and to know the successful + completion or error status. + + The PF_SYSTEM_SERVICES provides an APB interface for controlling the registers + functions for controlling the PF_SYSTEM_SERVICES as part of a bare metal system + implemented within it. This software driver provides a set of where no + part of an operating system but the implementation of the adaptation layer + operating system is available. This driver can be adapted for use as + between this driver and the operating system's driver model is outside the + scope of this driver. + + Features + The CoreSysServices_PF driver provides the following features: + - Executing device and design information services. + - Executing design services. + - Executing data security services + - Executing Fabric services. + + The CoreSysServices_PF driver is provided as C source code. + + @section Driver Configuration + Your application software should configure the CoreSysServices_PF driver, through + call to the SYS_init() function. Only one instance of PF_SYSTEM_SERVICES SgCore is + supported. No additional configuration files are required to use the driver. + + @section theory_op Theory of Operation + The CoreSysServices_PF driver provides access to the PolarFire system services. + These system services are grouped into the following categories: + + Device & Design Information Service + - Serial Number Service + - USERCODE Service + - Design Info Service + - Device Certificate Services + - Read Digests + - Query Security + - Read Debug Info + - Read eNVM param + + Design services + - Bitstream authentication service + - IAP bitstream authentication service + + Data Security services + - Digital Signature Service + - Secure NVM (SNVM) Functions + - PUF Emulation Service + - Nonce Service + + Fabric services + - Digest Check Service + - In Application programming(IAP)/ Auto-Update service + + Initialization and Configuration + The CoreSysServices_PF driver is initialized through a call to the SYS_init() + function. The SYS_init() function must be called before any other + CoreSysServices_PF driver functions is called. + + Device and design information services + The CoreSysServices_PF driver can be used to read information about the device + and the design using the following functions: + - SYS_get_serial_number() + - SYS_get_user_code() + - SYS_get_design_info() + - SYS_get_device_certificate() + - SYS_read_digest() + - SYS_query_security() + - SYS_read_debug_info() + + Design Authentication services + The CoreSysServices_PF driver can be used to execute design services using the + following functions: + - SYS_bitstream_authenticate_service() + - SYS_IAP_image_authenticate_service() + + Data security services + The CoreSysServices_PF driver can be used to execute data security services + using the following functions: + - SYS_digital_signature_service() + - SYS_secure_nvm_write() + - SYS_secure_nvm_read() + - SYS_puf_emulation_service () + - SYS_nonce_service () + + Executing Fabric services + The CoreSysServices_PF driver can be used to execute fabric services using the + following functions: + - SYS_digest_check_service() + - SYS_iap_service() + + All the service execution functions return the 8 bit status returned by + system controller on executing the given service. A '0' value indicates + successful execution of that service. A non-zero value indicates error. + The error codes for each service are different. Please see individual function + description to know the exact meanings of the error codes for each service. + + The function descriptions in this file will mainly focus on details required + by the user to use the APIs provided by this driver to execute the services. + To know the complete details of the system services, please refer to the + PolarFire® FPGA and PolarFire SoC FPGA System Services document. Link below: + https://onlinedocs.microchip.com/pr/GUID-1409CF11-8EF9-4C24-A94E-70979A688632-en-US-3/index.html + + *//*=========================================================================*/ +#ifndef __CORE_SYSSERV_PF_H +#define __CORE_SYSSERV_PF_H 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/***************************************************************************//** + * Service execution success and error status codes: + * The status codes below are the return values from the system service functions. + * For any service, a return value '0' indicates that the service was executed + * successfully. A non-zero return value indicates that the service was not + * executed successfully. For all the services, the return value represents the + * status code returned by the system controller for the respective service, + * except the values SYS_PARAM_ERR, SS_USER_BUSY_TIMEOUT and SS_USER_RDVLD_TIMEOUT. + * These three values indicate the error conditions detected by this driver and + * they do not overlap with the status code returned by the system controller for + * any of the system service. + */ +/* + * SYS_SUCCESS + * System service executed successfully. + * + * SYS_PARAM_ERR + * System service cannot be executed as one or more parameters are not as + * expected by this driver. No read/write access will be performed with the + * IP. + * + * SS_USER_BUSY_TIMEOUT + * The System service request was initiated and the driver timed-out while + * waiting for the system service to complete. The System Service + * completion is indicated by de-assertion of the SS_USER_BUSY bit by the + * IP. + * + * SS_USER_RDVLD_TIMEOUT + * The System service request was initiated and the driver timed-out while + * waiting for SS_USER_RDVLD bit, which indicates availability of data to + * be read from the mailbox, to become active. +*/ +#define SYS_SUCCESS 0u +#define SYS_PARAM_ERR 0xFFu +#define SS_USER_BUSY_TIMEOUT 0xFAu +#define SS_USER_RDVLD_TIMEOUT 0xFBu + +/* + * SS_TIMEOUT_COUNT + * The SS_TIMEOUT_COUNT value will be used by the driver as a timeout count + * while waiting for either the SS_USER_BUSY or SS_USER_RDVLD. This empirical + * value is sufficiently large so that the operations will not falsely + * timeout in the normal circumstance. It is provided as a way to provide + * more debug information to the application in case there are some + * unforeseen issues. You may change this value for your need based on your + * system design. + */ +#define SS_TIMEOUT_COUNT 40000u +/* + * SYS_DCF_DEVICE_MISMATCH + * Public key or FSN do not match device + * + * + * SYS_DCF_INVALID_SIGNATURE + * Certificate signature is invalid + * + * SYS_DCF_SYSTEM_ERROR + * PUF or storage failure + */ +#define SYS_DCF_DEVICE_MISMATCH 1u +#define SYS_DCF_INVALID_SIGNATURE 2u +#define SYS_DCF_SYSTEM_ERROR 3u + +/* + * SYS_NONCE_PUK_FETCH_ERROR + * Error fetching PUK + * + * SYS_NONCE_SEED_GEN_ERROR + * Error generating seed + */ +#define SYS_NONCE_PUK_FETCH_ERROR 1u +#define SYS_NONCE_SEED_GEN_ERROR 2u + +/* Secure NVM write error codes + * + * SNVM_WRITE_INVALID_SNVMADDR + * Illegal page address + * + * SNVM_WRITE_FAILURE + * PNVM program/verify failed + * + * SNVM_WRITE_SYSTEM_ERROR + * PUF or storage failure + * + * SNVM_WRITE_NOT_PERMITTED + * Write is not permitted + */ +#define SNVM_WRITE_INVALID_SNVMADDR 1u +#define SNVM_WRITE_FAILURE 2u +#define SNVM_WRITE_SYSTEM_ERROR 3u +#define SNVM_WRITE_NOT_PERMITTED 4u + +/* Secure NVM read error codes + * + * SNVM_READ_INVALID_SNVMADDR + * Illegal page address + * + * SNVM_READ_AUTHENTICATION_FAILURE + * Storage corrupt or incorrect USK + * + * SNVM_READ_SYSTEM_ERROR + * PUF or storage failure + * + */ +#define SNVM_READ_INVALID_SNVMADDR 1u +#define SNVM_READ_AUTHENTICATION_FAILURE 2u +#define SNVM_READ_SYSTEM_ERROR 3u + +/* Digital Signature Service error code + * + * DIGITAL_SIGNATURE_FEK_FAILURE_ERROR + * Error retrieving FEK + * + * DIGITAL_SIGNATURE_DRBG_ERROR + * Failed to generate nonce + * + * DIGITAL_SIGNATURE_ECDSA_ERROR + * ECDSA failed + */ +#define DIGITAL_SIGNATURE_FEK_FAILURE_ERROR 1u +#define DIGITAL_SIGNATURE_DRBG_ERROR 2u +#define DIGITAL_SIGNATURE_ECDSA_ERROR 3u + +/*Digest Check error code + * + * NOTE: when these error occur, the DIGEST tamper flag is triggered + * + * DIGEST_CHECK_FABRICERR + * Fabric digest check error + * + * DIGEST_CHECK_CCERR + * UFS Fabric Configuration (CC) segment digest check error + * + * DIGEST_CHECK_SNVMERR + * ROM digest in SNVM segment digest check error + * + * DIGEST_CHECK_ULERR + * UFS UL segment digest check error + * + * DIGEST_CHECK_UK0ERR + * UKDIGEST0 in User Key segment digest check error + * + * DIGEST_CHECK_UK1ERR + * UKDIGEST1 in User Key segment digest check error + * + * DIGEST_CHECK_UK2ERR + * UKDIGEST2 in User Key segment (UPK1) digest check error + * + * DIGEST_CHECK_UK3ERR + * UKDIGEST3 in User Key segment (UK1) digest check error + * + * DIGEST_CHECK_UK4ERR + * UKDIGEST4 in User Key segment (DPK) digest check error + * + * DIGEST_CHECK_UK5ERR + * UKDIGEST5 in User Key segment (UPK2) digest check error + * + * DIGEST_CHECK_UK6ERR + * UKDIGEST6 in User Key segment (UK2) digest check error + * + * DIGEST_CHECK_UPERR + * UFS Permanent Lock (UPERM) segment digest check error + * + * DIGEST_CHECK_SYSERR + * M3 ROM, Factory and Factory Key Segments digest check error + * + */ +#define DIGEST_CHECK_FABRICERR 0x00u +#define DIGEST_CHECK_CCERR 0x01u +#define DIGEST_CHECK_SNVMERR 0x02u +#define DIGEST_CHECK_ULERR 0x03u +#define DIGEST_CHECK_UK0ERR 0x04u +#define DIGEST_CHECK_UK1ERR 0x05u +#define DIGEST_CHECK_UK2ERR 0x06u +#define DIGEST_CHECK_UK3ERR 0x07u +#define DIGEST_CHECK_UK4ERR 0x08u +#define DIGEST_CHECK_UK5ERR 0x09u +#define DIGEST_CHECK_UK6ERR 0x10u +#define DIGEST_CHECK_UPERR 0x11u +#define DIGEST_CHECK_SYSERR 0x12u + +/* bitstream authentication and IAP bitstream authentication Return status + * + * BSTREAM_AUTH_CHAINING_MISMATCH_ERR + * Validator or hash chaining mismatch. Incorrectly constructed bitstream or + * wrong key used. + * + * BSTREAM_AUTH_UNEXPECTED_DATA_ERR + * Unexpected data received. + * Additional data received after end of EOB component + * + * BSTREAM_AUTH_INVALID_ENCRY_KEY_ERR + * Invalid/corrupt encryption key. + * The requested key mode is disabled or the key could not be read/reconstructed + * + * BSTREAM_AUTH_INVALID_HEADER_ERR + * Invalid component header + * + * BSTREAM_AUTH_BACK_LEVEL_NOT_SATISFIED_ERR + * Back level not satisfied + * + * BSTREAM_AUTH_ILLEGAL_BITSTREAM_MODE_ERR + * Illegal bitstream mode. + * Requested bitstream mode is disabled by user security + * + * BSTREAM_AUTH_DNS_BINDING_MISMATCH_ERR + * DSN binding mismatch + * + * BSTREAM_AUTH_ILLEGAL_COMPONENT_SEQUENCE_ERR + * Illegal component sequence + * + * BSTREAM_AUTH_INSUFF_DEVICE_CAPAB_ERR + * Insufficient device capabilities + * + * BSTREAM_AUTH_INCORRECT_DEVICEID_ERR + * Incorrect DEVICEID + * + * BSTREAM_AUTH_PROTOCOL_VERSION_ERR + * Unsupported bitstream protocol version (regeneration required) + * + * BSTREAM_AUTH_VERIFY_ERR + * Verify not permitted on this bitstream + * + * BSTREAM_AUTH_INVALID_DEV_CERT_ERR + * Invalid Device Certificate. + * Device SCAC is invalid or not present + * + * BSTREAM_AUTH_INVALID_DIB_ERR + * Invalid DIB + * + * BSTREAM_AUTH_SPI_NOT_MASTER_ERR + * Device not in SPI Master Mode. + * Error may occur only when bitstream is executed through IAP mode + * + * BSTREAM_AUTH_AUTOIAP_NO_VALID_IMAGE_ERR + * No valid images found. + * Error may occur when bitstream is executed through Auto Update mode. + * Occurs when No valid image pointers are found. + * + * BSTREAM_AUTH_INDEXIAP_NO_VALID_IMAGE_ERR + * No valid images found. + * Error may occur when bitstream is executed through IAP mode via Index Mode. + * Occurs when No valid image pointers are found. + * + * BSTREAM_AUTH_NEWER_DESIGN_VERSION_ERR + * Programmed design version is newer than AutoUpdate image found. + * Error may occur when bitstream is executed through Auto Update mode + * + * BSTREAM_AUTH_INVALID_IMAGE_ERR + * Selected image was invalid and no recovery was performed due to valid design + * in device. + * Error may occur only when bitstream is executed through Auto Update or IAP mode + * (This error is here for completeness but only can be observed by running the + * READ_DEBUG_INFO instruction and looking at IAP Error code field) + * + * BSTREAM_AUTH_IMAGE_PROGRAM_FAILED_ERR + * Selected and Recovery image failed to program. + * Error may occur only when bitstream is executed through Auto Update or + * IAP mode + * (This error is here for completeness but only can be observed by running the + * READ_DEBUG_INFO instruction and looking at IAP Error code field) + * + * BSTREAM_AUTH_ABORT_ERR + * Abort. + * Non-bitstream instruction executed during bitstream loading. + * + * BSTREAM_AUTH_NVMVERIFY_ERR + * Fabric/UFS verification failed (min or weak limit) + * + * BSTREAM_AUTH_PROTECTED_ERR + * Device security prevented modification of non-volatile memory + * + * BSTREAM_AUTH_NOTENA + * Programming mode not enabled + * + * BSTREAM_AUTH_PNVMVERIFY + * pNVM verify operation failed + * + * BSTREAM_AUTH_SYSTEM + * System hardware error (PUF or DRBG) + * + * BSTREAM_AUTH_BADCOMPONENT + * An internal error was detected in a component payload + * + * BSTREAM_AUTH_HVPROGERR + * HV programming subsystem failure (pump failure) + * + * BSTREAM_AUTH_HVSTATE + * HV programming subsystem in unexpected state (internal error) + * + */ +#define BSTREAM_AUTH_CHAINING_MISMATCH_ERR 1 +#define BSTREAM_AUTH_UNEXPECTED_DATA_ERR 2 +#define BSTREAM_AUTH_INVALID_ENCRY_KEY_ERR 3 +#define BSTREAM_AUTH_INVALID_HEADER_ERR 4 +#define BSTREAM_AUTH_BACK_LEVEL_NOT_SATISFIED_ERR 5 +#define BSTREAM_AUTH_ILLEGAL_BITSTREAM_MODE_ERR 6 +#define BSTREAM_AUTH_DNS_BINDING_MISMATCH_ERR 7 +#define BSTREAM_AUTH_ILLEGAL_COMPONENT_SEQUENCE_ERR 8 +#define BSTREAM_AUTH_INSUFF_DEVICE_CAPAB_ERR 9 +#define BSTREAM_AUTH_INCORRECT_DEVICEID_ERR 10 +#define BSTREAM_AUTH_PROTOCOL_VERSION_ERR 11 +#define BSTREAM_AUTH_VERIFY_ERR 12 +#define BSTREAM_AUTH_INVALID_DEV_CERT_ERR 13 +#define BSTREAM_AUTH_INVALID_DIB_ERR 14 +#define BSTREAM_AUTH_SPI_NOT_MASTER_ERR 21 +#define BSTREAM_AUTH_AUTOIAP_NO_VALID_IMAGE_ERR 22 +#define BSTREAM_AUTH_INDEXIAP_NO_VALID_IMAGE_ERR 23 +#define BSTREAM_AUTH_NEWER_DESIGN_VERSION_ERR 24 +/* 25 Reserved */ +#define BSTREAM_AUTH_INVALID_IMAGE_ERR 26 +#define BSTREAM_AUTH_IMAGE_PROGRAM_FAILED_ERR 27 +#define BSTREAM_AUTH_ABORT_ERR 127 +#define BSTREAM_AUTH_NVMVERIFY_ERR 128 +#define BSTREAM_AUTH_PROTECTED_ERR 129 +#define BSTREAM_AUTH_NOTENA 130 +#define BSTREAM_AUTH_PNVMVERIFY 131 +#define BSTREAM_AUTH_SYSTEM 132 +#define BSTREAM_AUTH_BADCOMPONENT 133 +#define BSTREAM_AUTH_HVPROGERR 134 +#define BSTREAM_AUTH_HVSTATE 135 + +/***************************************************************************//** + * Mailbox ECC status + * Provides ECC status when the mailbox is read. The values are as follows: + * 00: No ECC errors detected, data is correct. + * 01: Exactly one bit error occurred and has been corrected. + * 10: Exactly two bits error occurred and no correction performed. + * 11: Reserved. + */ +#define SYS_MBOX_ECC_NO_ERROR_MASK 0x00u +#define SYS_MBOX_ONEBIT_ERROR_CORRECTED_MASK 0x40u +#define SYS_MBOX_TWOBIT_ERROR_MASK 0xC0u + +/***************************************************************************//** + * Service request command opcodes: +*/ +#define SERIAL_NUMBER_REQUEST_CMD 0x00u +#define USERCODE_REQUEST_CMD 0x01u +#define DESIGN_INFO_REQUEST_CMD 0x02u +#define DEVICE_CERTIFICATE_REQUEST_CMD 0x03u +#define READ_DIGEST_REQUEST_CMD 0x04u +#define QUERY_SECURITY_REQUEST_CMD 0x05u +#define READ_DEBUG_INFO_REQUEST_CMD 0x06u +#define READ_ENVM_PARAM_REQUEST_CMD 0x07u +#define SNVM_NON_AUTHEN_TEXT_REQUEST_CMD 0x10u +#define SNVM_AUTHEN_TEXT_REQUEST_CMD 0x11u +#define SNVM_AUTHEN_CIPHERTEXT_REQUEST_CMD 0x12u +#define SNVM_READ_REQUEST_CMD 0x18u +#define DIGITAL_SIGNATURE_RAW_FORMAT_REQUEST_CMD 0x19u +#define PUF_EMULATION_SERVICE_REQUEST_CMD 0x20u +#define NONCE_SERVICE_REQUEST_CMD 0x21u +#define DIGITAL_SIGNATURE_DER_FORMAT_REQUEST_CMD 0x1Au + +#define BITSTREAM_AUTHENTICATE_CMD 0x23u +#define IAP_BITSTREAM_AUTHENTICATE_CMD 0x22u + +#define DIGEST_CHECK_CMD 0x47u + +#define IAP_PROGRAM_BY_SPIIDX_CMD 0x42u +#define IAP_VERIFY_BY_SPIIDX_CMD 0x44u +#define IAP_PROGRAM_BY_SPIADDR_CMD 0x43u +#define IAP_VERIFY_BY_SPIADDR_CMD 0x45u +#define IAP_AUTOUPDATE_CMD 0x46u + +/***************************************************************************//** + * Service request Mailbox return data length + */ +#define SERIAL_NUMBER_RESP_LEN 16u +#define USERCODE_RESP_LEN 4u +#define DESIGN_INFO_RESP_LEN 36u +#define DEVICE_CERTIFICATE_RESP_LEN 1024u +#define READ_DIGEST_RESP_LEN 416u +#define QUERY_SECURITY_RESP_LEN 9u +#define READ_DEBUG_INFO_RESP_LEN 76u +#define READ_ENVM_PARAM_RESP_LEN 256u +#define NONCE_SERVICE_RESP_LEN 32u + +#define PUF_EMULATION_SERVICE_CMD_LEN 20u +#define PUF_EMULATION_SERVICE_RESP_LEN 32u + +#define DIGITAL_SIGNATURE_HASH_LEN 48u +#define DIGITAL_SIGNATURE_RAW_FORMAT_RESP_SIZE 96u +#define DIGITAL_SIGNATURE_DER_FORMAT_RESP_SIZE 104u + +#define USER_SECRET_KEY_LEN 12u + +/* Same driver can be used on PolarFire SoC platform and the response length + * is different for PolarFire SoC. Constants defined below are used only when the + * PF System services driver is used with PolarFire SoC Platform. + */ +#define READ_DIGEST_MPFS_RESP_LEN 576u +#define QUERY_SECURITY_MPFS_RESP_LEN 33u + +/* SNVM Input data length from sNVM write. */ + +/* SNVMADDR + RESERVED + PT + USK */ +#define NON_AUTHENTICATED_TEXT_DATA_LEN 256u + +/* SNVMADDR + RESERVED + PT */ +#define AUTHENTICATED_TEXT_DATA_LEN 252u + +/* Digest Check Input options + * + * DIGEST_CHECK_FABRIC + * Carry out digest check on Fabric + * + * DIGEST_CHECK_CC + * Carry out digest check on UFS Fabric Configuration (CC) segment + * + * DIGEST_CHECK_SNVM + * Carry out digest check on ROM digest in SNVM segment + * + * DIGEST_CHECK_UL + * Carry out digest check on UFS UL segment + * + * DIGEST_CHECK_UKDIGEST0 + * Carry out digest check on UKDIGEST0 in User Key segment + * + * DIGEST_CHECK_UKDIGEST1 + * Carry out digest check on UKDIGEST1 in User Key segment + * + * DIGEST_CHECK_UKDIGEST2 + * Carry out digest check on UKDIGEST2 in User Key segment (UPK1) + * + * DIGEST_CHECK_UKDIGEST3 + * Carry out digest check on UKDIGEST3 in User Key segment (UK1) + * + * DIGEST_CHECK_UKDIGEST4 + * Carry out digest check on UKDIGEST4 in User Key segment (DPK) + * + * DIGEST_CHECK_UKDIGEST5 + * Carry out digest check on UKDIGEST5 in User Key segment (UPK2) + * + * DIGEST_CHECK_UKDIGEST6 + * Carry out digest check on UKDIGEST6 in User Key segment (UK2) + * + * DIGEST_CHECK_UPERM + * Carry out digest check on UFS Permanent lock (UPERM) segment + * + * DIGEST_CHECK_SYS + * Carry out digest check on Factory and Factory Key Segments. + * + */ +#define DIGEST_CHECK_FABRIC (0x01<<0x00u) /*Fabric digest*/ +#define DIGEST_CHECK_CC (0x01<<0x01u) /*UFS Fabric Configuration (CC) segment*/ +#define DIGEST_CHECK_SNVM (0x01<<0x02u) /*ROM digest in SNVM segment*/ +#define DIGEST_CHECK_UL (0x01<<0x03u) /*UFS UL segment*/ +#define DIGEST_CHECK_UKDIGEST0 (0x01<<0x04u) /*UKDIGEST0 in User Key segment*/ +#define DIGEST_CHECK_UKDIGEST1 (0x01<<0x05u) /*UKDIGEST1 in User Key segment*/ +#define DIGEST_CHECK_UKDIGEST2 (0x01<<0x06u) /*UKDIGEST2 in User Key segment (UPK1)*/ +#define DIGEST_CHECK_UKDIGEST3 (0x01<<0x07u) /*UKDIGEST3 in User Key segment (UK1)*/ +#define DIGEST_CHECK_UKDIGEST4 (0x01<<0x08u) /*UKDIGEST4 in User Key segment (DPK)*/ +#define DIGEST_CHECK_UKDIGEST5 (0x01<<0x09u) /*UKDIGEST5 in User Key segment (UPK2)*/ +#define DIGEST_CHECK_UKDIGEST6 (0x01<<0x0au) /*UKDIGEST6 in User Key segment (UK2)*/ +#define DIGEST_CHECK_UPERM (0x01<<0x0bu) /*UFS Permanent lock (UPERM) segment*/ +#define DIGEST_CHECK_SYS (0x01<<0x0cu) /*Factory and Factory Key Segments.*/ + +/***************************************************************************//** + * The function SYS_init() is used to initialize the internal data structures of + * this driver. Currently this function is empty. + * + * @param base_addr The base_addr parameter specifies the base address of the + * PF_System_services core. + * + * @return This function does not return a value. + */ +void +SYS_init +( + uint32_t base_addr +); + +/***************************************************************************//** + * The function SYS_get_serial_number() is used to execute "serial number" system + * service. + * + * @param p_serial_number The p_serial_number parameter is a pointer to a buffer + * in which the data returned by system controller will + * be copied. + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return This function returns the status code returned by the + * system controller for this service. A '0' status code + * means that the service was executed successfully. + */ +uint8_t +SYS_get_serial_number +( + const uint8_t * p_serial_number, + uint16_t mb_offset +); + +/***************************************************************************//** + * The function SYS_get_user_code() is used to execute "USERCODE" system + * service. + * @param p_user_code The p_user_code parameter is a pointer to a buffer + * in which the data returned by system controller will be + * copied. + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return This function returns the status code returned by the + * system controller for this service. A '0' status code + * means that the service was executed successfully. + */ +uint8_t +SYS_get_user_code +( + const uint8_t * p_user_code, + uint16_t mb_offset +); + +/***************************************************************************//** + * The function SYS_get_design_info() is used to execute "Get Design Info" system + * service. + * + * @param p_design_info The p_design_info parameter is a pointer to a buffer + * in which the data returned by system controller will be + * copied. Total size of debug information is 36 bytes. + * The data from the system controller includes the 256-bit + * user-defined design ID, 16-bit design version and 16-bit + * design back level. + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return This function returns the status code returned by the + * system controller for this service. A '0' status code + * means that the service was executed successfully. + */ +uint8_t +SYS_get_design_info +( + const uint8_t * p_design_info, + uint16_t mb_offset +); + +/***************************************************************************//** + * The function SYS_get_device_certificate() is used to execute "Get Device + * Certificate" system service. + * + * @param p_device_certificate The p_device_certificate parameter is a pointer + * to a buffer in which the data returned by the + * system controller will be copied. + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return This function returns the status code returned by the + * system controller for this service. A '0' status code means that + * the service was executed successfully. + * + */ +uint8_t +SYS_get_device_certificate +( + const uint8_t * p_device_certificate, + uint16_t mb_offset +); + +/***************************************************************************//** + * The function SYS_read_digest() is used to execute "Read Digest" system service. + * + * @param p_digest The p_digest parameter is a pointer to a buffer + * in which the data returned by system controller will be + * copied. + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return This function returns the status code returned by the + * system controller for this service. A '0' status code + * means that the service was executed successfully. + */ +uint8_t SYS_read_digest +( + const uint8_t * p_digest, + uint16_t mb_offset +); + +/***************************************************************************//** + * The function SYS_query_security() is used to execute "Query Security" system + * service. + * + * @param p_security_locks The p_security_locks parameter is a pointer to a buffer + * in which the data returned by system controller will + * be copied. + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return This function returns the status code returned by the + * system controller for this service. A '0' status code means that + * the service was executed successfully. + */ +uint8_t SYS_query_security +( + uint8_t * p_security_locks, + uint16_t mb_offset +); + +/***************************************************************************//** + * The function SYS_read_debug_info() is used to execute "Read Debug info" system + * service. + * + * @param p_debug_info The p_debug_info parameter is a pointer to a buffer + * in which the data returned by system controller will be + * copied. + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return This function returns the status code returned by the + * system controller for this service. A '0' status code + * means that the service was executed successfully. + */ +uint8_t SYS_read_debug_info +( + const uint8_t * p_debug_info, + uint16_t mb_offset +); + +#ifdef CORESYSSERVICES_PFSOC +/***************************************************************************//** + * The function SYS_read_envm_param() is used to retrieve all parameters needed + * for eNVM operation and programming. + * + * NOTE: This service is available only on PolarFire SoC Platform. + * This service is not yet supported by PF_SYSTEM_SERVICES 3.0.100. + * + * @param p_envm_param The p_envm_param parameter is a pointer to a buffer + * in which the data returned by system controller will be copied. + * This buffer will store all the eNVM parameters. + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return The SYS_read_envm_param service will return zero if the + * service executed successfully otherwise it will return + * one indicating error. + */ +uint8_t SYS_read_envm_parameter +( + uint8_t * p_envm_param, + uint16_t mb_offset +); +#endif +/***************************************************************************//** + * The function SYS_puf_emulation_service() is used to authenticating a device. + * + * The SYS_puf_emulation_service() function accept a challenge comprising a + * 8-bit optype and 128-bit challenge and return a 256-bit response unique to + * the given challenge and the device. + * + * @param p_challenge The p_challenge parameter specifies the 128-bit challenge + * to be used to generate the unique 256-bits unique + * response. + * + * @param op_type The op_type parameter specifies the operational parameter + * to be used to generate the unique 256-bits unique + * response. + * + * @param p_response The p_response parameter is a pointer to a buffer in + * which the data returned i.e. response by system controller will + * be copied. + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return The SYS_puf_emulation_service function will return zero + * if the service executed successfully otherwise it will + * return one indicating error. + */ +uint8_t SYS_puf_emulation_service +( + const uint8_t * p_challenge, + uint8_t op_type, + uint8_t* p_response, + uint16_t mb_offset +); + +/***************************************************************************//** + * The SYS_digital_signature_service() function is used to generate P-384 ECDSA + * signature based on SHA384 hash value. + * + * @param p_hash The p_hash parameter is a pointer to the buffer which + * contain the 48 bytes SHA384 Hash value(input value). + * + * @param format The format parameter specifies the output format of + * generated SIGNATURE field. The different types of output + * signature formats are as follow: + * - DIGITAL_SIGNATURE_RAW_FORMAT + * - DIGITAL_SIGNATURE_DER_FORMAT + * + * @param p_response The p_response parameter is a pointer to a buffer which + * contain the generated ECDSA signature. The field may be + * 96 bytes or 104 bytes depending upon the output format. + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return The SYS_digital_signature_service function will return + * zero if the service executed successfully otherwise + * non-zero values indicating error. + */ +uint8_t SYS_digital_signature_service +( + const uint8_t* p_hash, + uint8_t format, + uint8_t* p_response, + uint16_t mb_offset +); + +/***************************************************************************//** + * The SYS_secure_nvm_write() function is used to provide write access/write the + * data in the sNVM region. Data can be stored in the following format: + * Non-authenticated plaintext, + * Authenticated plaintext + * Authenticated ciphertext + * + * Note: If you are executing this function with Authenticated plaintext + * or Authenticated ciphertext on a device whose sNVM was never previously + * written to, then the service may fail. For it to work, you must first write + * Authenticated data to the sNVM using Libero along with USK client and + * custom security. This flow generates the SMK. Refer UG0753 PolarFire FPGA + * security User Guide for further details. + + * @param format The format parameter specifies the format used to write + * data in sNVM region. The different type of text formats + * are as follow: + * - NON_AUTHENTICATED_PLAINTEXT_FORMAT + * - AUTHENTICATED_PLAINTEXT_FORMAT + * - AUTHENTICATED_CIPHERTEXT_FORMAT + * + * @param snvm_module The snvm_module parameter specifies the the sNVM module + * in which the data need to be written. + * + * @param p_data The p_data parameter is a pointer to a buffer which + * contains the data to be stored in sNVM region. The data + * length to be written is if fixed depending on the format + * parameter. If NON_AUTHENTICATED_PLAINTEXT_FORMAT is + * selected then you can write 252 bytes in the sNVM module. + * For other two formats the data length is 236 bytes. + * + * @param p_user_key The p_user_key parameter is a pointer to a buffer which + * contain the 96-bit key USK (user secret key). This user + * secret key will enhance the security when authentication + * is used.(i.e. When Authenticated plaintext and + * Authenticated ciphertext format is selected). + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return The SYS_secure_nvm_write function will return + * zero if the service executed successfully otherwise + * non-zero values indicating error. + */ +uint8_t SYS_secure_nvm_write +( + uint8_t format, + uint8_t snvm_module, + const uint8_t* p_data, + const uint8_t* p_user_key, + uint16_t mb_offset +); + +/***************************************************************************//** + * The SYS_secure_nvm_read() function is used to read data present in sNVM region. + * User should provide USK key, if the data was programmed using authentication. + * If the data was written in the sNVM using the authenticated plaintext or the + * authenticated ciphertext service option then this service will return the + * valid data only when authentication is successful. Please also refer the + * SYS_secure_nvm_write() function for more details. If the data was written in + * the sNVM using the authenticated plaintext or the authenticated ciphertext + * service option then this service will return the valid data only when + * authentication is successful. Please also refer the SYS_secure_nvm_write() + * function and its parameter description for more details. + * + * @param snvm_module The snvm_module parameter specifies the sNVM module + * from which the data need to be read. + * + * @param p_user_key The p_user_key parameter is a pointer to a buffer which + * contain the 96-bit key USK (user secret key). User should + * provide same secret key which is previously used for + * authentication while writing data in sNVM region. + * + * @param p_admin The p_admin parameter is a pointer to the buffer where + * the output page admin data will be stored. The page admin + * data is 4 bytes long. + * + * @param p_data The p_data parameter is a pointer to a buffer which + * contains the data read from sNVM region. User should + * provide the buffer large enough to store the read data. + * + * @param data_len The data_len parameter specifies the number of bytes to be + * read from sNVM. + * The application should know whether the data written in the + * chose sNVM module was previously stored using Authentication + * or not. + * The data_len should be 236 bytes, for authenticated data. + * For not authenticated data the data_len should be 252 bytes. + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return The SYS_secure_nvm_read function will return + * zero if the service executed successfully otherwise + * non-zero values indicating error. + */ +uint8_t SYS_secure_nvm_read +( + uint8_t snvm_module, + const uint8_t* p_user_key, + uint8_t* p_admin, + uint8_t* p_data, + uint16_t data_len, + uint16_t mb_offset +); + +/***************************************************************************//** + * The function SYS_nonce_service() is used to issue "Nonce Service" system + * service to the system controller. + * + * @param p_nonce The p_nonce parameter is a pointer to a buffer + * in which the data returned by system controller will be copied. + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return This function returns the status code returned by the + * system controller for this service. A '0' status code means + * that the service was executed successfully and a non-zero + * value indicates error. Please refer to the document link + * provided in the theory of operation section to know more + * about the service and service response. + */ +uint8_t SYS_nonce_service +( + const uint8_t * p_nonce, + uint16_t mb_offset +); + +/***************************************************************************//** + * The SYS_bitstream_authenticate_service() function is used to authenticate + * the Bitstream which is located in SPI through a system service routine. Prior + * to using the IAP service, it may be required to first validate the new + * bitstream before committing the device to reprogramming, thus avoiding the + * need to invoke recovery procedures if the bitstream is invalid. + * + * This service is applicable to bitstreams stored in SPI Flash memory only. + * + * @param spi_flash_address + * The spi_flash_address parameter specifies the address within + * SPI Flash memory where the bit-stream is stored. + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return The SYS_bitstream_authenticate_service function will return + * zero if the service executed successfully the non-zero + * response from system controller indicates error. Please + * refer to the document link provided in the theory of + * operation section to know more about the service and service + * response. + */ +uint8_t SYS_bitstream_authenticate_service +( + uint32_t spi_flash_address, + uint16_t mb_offset +); + +/***************************************************************************//** + * The SYS_IAP_image_authenticate_service() function is used to authenticate + * the IAP image which is located in SPI through a system service routine. The + * service checks the image descriptor and the referenced bitstream and optional + * initialization data. If the image is authenticated successfully, then the + * image is guaranteed to be valid when used by an IAP function. + * + * This service is applicable to bitstreams stored in SPI Flash memory only. + * + * @param spi_idx + * The spi_idx parameter specifies the index in the SPI directory to + * be used where the IAP bit-stream is stored. + * + * Note: To support recovery SPI_IDX=1 should be an empty slot and the recovery + * image should be located in SPI_IDX=0. Since SPI_IDX=1 should be an + * empty slot it shouldn’t be passed into the system service. + * + * @return The SYS_IAP_image_authenticate_service function will return + * zero if the service executed successfully the non-zero + * response from system controller indicates error. Please + * refer to the document link provided in the theory of + * operation section to know more about the service and service + * response. + */ +uint8_t SYS_IAP_image_authenticate_service +( + uint8_t spi_idx +); + +/***************************************************************************//** + * The SYS_digest_check_service() function is used to Recalculates and compares + * digests of selected non-volatile memories. If the fabric digest is to be + * checked, then the user design must follow all prerequisite steps for the + * FlashFreeze service before invoking this service. + * + * This service is applicable to bitstreams stored in SPI Flash memory only. + * + * @param options + * The options parameter specifies the digest check options which + * indicate the area on which the digest check should be performed. + * Below is the list of options. You can OR these options to indicate + * to perform digest check on multiple segments. + * + * Note: The options parameter will be of 2 bytes when used with PF + * device and 4 bytes when used with PolarFire SoC device. + * + * Options[i] Description + * 0x01 Fabric digest + * 0x02 Fabric Configuration (CC) segment + * 0x04 ROM digest in SNVM segment + * 0x08 UL segment + * 0x10 UKDIGEST0 in User Key segment + * 0x20 UKDIGEST1 in User Key segment + * 0x40 UKDIGEST2 in User Key segment (UPK1) + * 0x80 UKDIGEST3 in User Key segment (UK1) + * 0x100 UKDIGEST4 in User Key segment (DPK) + * 0x200 UKDIGEST5 in User Key segment (UPK2) + * 0x400 UKDIGEST6 in User Key segment (UK2) + * 0x800 UFS Permanent lock (UPERM) segment + * 0x1000 Factory and Factory Key Segments. + * 0x2000 UKDIGEST7 in User Key segment (HWM) (PFSoC) + * 0x4000 ENVMDIGEST (PFSoC only) + * 0x8000 UKDIGEST8 for MSS Boot Info (PFSoC only) + * 0x10000 SNVM_RW_ACCESS_MAP Digest (PFSoC only) + * 0x20000 SBIC revocation digest (PFSoC only) + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return The SYS_digest_check_service function will return + * zero if the service executed successfully the non-zero + * response from system controller indicates error. Pleaes + * refer to the document link provided in the theory of + * operation section to know more about the service and service + * response. + */ +uint8_t SYS_digest_check_service +( + uint32_t options, + uint16_t mb_offset +); + +/***************************************************************************//** + * The SYS_iap_service() function is used to IAP service. The IAP service allows t + * he user to reprogram the device without the need for an external master. The + * user design writes the bitstream to be programmed into a SPI Flash connected + * to the SPI port. When the service is invoked, the System Controller + * automatically reads the bitstream from the SPI flash and programs the device. + * The service allows the image to be executed in either VERIFY or PROGRAM modes. + * Another option for IAP is to perform the auto-update sequence. In this case + * the newest image of the first two images in the SPI directory is chosen to be + * programmed. + * + * @param iap_cmd + * The iap_cmd parameter specifies the specific IAP command which + * depends upon VERIFY or PROGRAM modes and the SPI address method. + * + * iap_cmd Description + * IAP_PROGRAM_BY_SPIIDX_CMD IAP program. + * IAP_VERIFY_BY_SPIIDX_CMD Fabric Configuration (CC) segment + * IAP_PROGRAM_BY_SPIADDR_CMD ROM digest in SNVM segment + * IAP_VERIFY_BY_SPIADDR_CMD UL segment + * IAP_AUTOUPDATE_CMD UKDIGEST0 in User Key segment + * + * @param spiaddr + * The spiaddr parameter specifies the either the either the index + * in the SPI directory or the SPI address in the SPI Flash memory. + * Below is the list of the possible meaning of spiaddr parameter + * in accordance with the iap_cmd parameter. + * + * iap_cmd spiaddr + * IAP_PROGRAM_BY_SPIIDX_CMD Index in the SPI directory. + * IAP_VERIFY_BY_SPIIDX_CMD Index in the SPI directory. + * IAP_PROGRAM_BY_SPIADDR_CMD SPI address in the SPI Flash memory + * IAP_VERIFY_BY_SPIADDR_CMD SPI address in the SPI Flash memory + * IAP_AUTOUPDATE_CMD spiaddr is ignored as No index/address + * required for this command. + * + * Note: For the IAP services with command IAP_PROGRAM_BY_SPIIDX_CMD and + * IAP_VERIFY_BY_SPIIDX_CMD To support recovery SPI_IDX=1 should be an + * empty slot and the recovery image should be located in SPI_IDX=0. + * Since SPI_IDX=1 should be an empty slot it shouldn’t be passed into + * the system service. + * + * @return The SYS_iap_service function will return zero if the service + * executed successfully and the non-zero response from system + * controller indicates error. Please refer to the document + * link provided in the theory of operation section to know + * more about the service and service response. + */ +uint8_t SYS_iap_service +( + uint8_t iap_cmd, + uint32_t spiaddr +); + +#ifdef __cplusplus +} +#endif + +#endif /* __CORE_SYSSERV_PF_H */ diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreSysServices_PF/coresysservicespf_regs.h b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreSysServices_PF/coresysservicespf_regs.h new file mode 100644 index 0000000..c978968 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreSysServices_PF/coresysservicespf_regs.h @@ -0,0 +1,147 @@ +/******************************************************************************* + * (c) Copyright 2019-2021 Microchip FPGA Embedded Systems Solutions. + * + * Register bit offsets and masks definitions for CoreSysServices_PF driver. + */ + +#ifndef __CORE_SYSSERV_PF_REGISTERS +#define __CORE_SYSSERV_PF_REGISTERS 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/*------------------------------------------------------------------------------ + * SYS_SERV_CMD (offset 0x04) register details + */ +#define SS_CMD_REG_OFFSET 0x04u + +#define SS_CMD_OFFSET 0x04 +#define SS_CMD_MASK 0x0000FFFFu +#define SS_CMD_SHIFT 0u + +/*------------------------------------------------------------------------------ + * SYS_SERV_STAT (offset 0x08) register details + */ +#define SS_STAT_REG_OFFSET 0x08u + +#define SS_STAT_OFFSET 0x08 +#define SS_STAT_MASK 0x0000FFFFu +#define SS_STAT_SHIFT 0u + +/*------------------------------------------------------------------------------ + * SYS_SERV_REQ (offset 0x0C) register details + */ +#define SS_REQ_REG_OFFSET 0x0Cu + + +#define SS_REQ_REQ_OFFSET 0x0Cu +#define SS_REQ_REQ_MASK 0x00000001UL +#define SS_REQ_REQ_SHIFT 0u + +#define SS_REQ_ABUSY_OFFSET 0x0Cu +#define SS_REQ_ABUSY_MASK 0x00000002UL +#define SS_REQ_ABUSY_SHIFT 1u + +#define SS_REQ_NABUSY_OFFSET 0x0Cu +#define SS_REQ_NABUSY_MASK 0x00000004UL +#define SS_REQ_NABUSY_SHIFT 2u + +#define SS_REQ_SSBUSY_OFFSET 0x0Cu +#define SS_REQ_SSBUSY_MASK 0x00000008UL +#define SS_REQ_SSBUSY_SHIFT 3u + +#define SS_REQ_AREQ_OFFSET 0x0Cu +#define SS_REQ_AREQ_MASK 0x00000010UL +#define SS_REQ_AREQ_SHIFT 4u + +#define SS_REQ_NAREQ_OFFSET 0x0Cu +#define SS_REQ_NAREQ_MASK 0x00000020UL +#define SS_REQ_NAREQ_SHIFT 5u +/*------------------------------------------------------------------------------ + * MBX_ECCSTATUS (offset 0x10) register details + */ +#define MBX_ECCSTATUS_REG_OFFSET 0x10u + +#define MBX_ECCSTATUS_OFFSET 0x10 +#define MBX_ECCSTATUS_MASK 0x03u +#define MBX_ECCSTATUS_SHIFT 0u + + +/*------------------------------------------------------------------------------ + * MBX_WCNT (offset 0x14) register details + */ +#define MBX_WCNT_REG_OFFSET 0x14u + +#define MBX_WCNT_OFFSET 0x14 +#define MBX_WCNT_MASK 0x000001FFu +#define MBX_WCNT_SHIFT 0u + +/*------------------------------------------------------------------------------ + * MBX_RWCNT (offset 0x18) register details + */ +#define MBX_RCNT_REG_OFFSET 0x18u + +#define MBX_RCNT_OFFSET 0x18 +#define MBX_RCNT_MASK 0x000001FFu +#define MBX_RCNT_SHIFT 0u + +/*------------------------------------------------------------------------------ + * MBX_WADRDESC (offset 0x1C) register details + */ +#define MBX_WADDR_REG_OFFSET 0x1Cu + +#define MBX_WADDR_OFFSET 0x1C +#define MBX_WADDR_MASK 0x000001FFu +#define MBX_WADDR_SHIFT 0u + +/*------------------------------------------------------------------------------ + * MBX_RADRDESC (offset 0x20) register details + */ +#define MBX_RADDR_REG_OFFSET 0x20u + +#define MBX_RADDR_OFFSET 0x20 +#define MBX_RADDR_MASK 0x000001FFu +#define MBX_RADDR_SHIFT 0u + +/*------------------------------------------------------------------------------ + * MBX_WDATA (offset 0x28) register details + */ +#define MBX_WDATA_REG_OFFSET 0x28u + +#define MBX_WDATA_OFFSET 0x28 +#define MBX_WDATA_MASK 0xFFFFFFFFu +#define MBX_WDATA_SHIFT 0u + + +/*------------------------------------------------------------------------------ + * MBX_RDATA (offset 0x2C) register details + */ +#define MBX_RDATA_REG_OFFSET 0x2Cu + +#define MBX_RDATA_OFFSET 0x2C +#define MBX_RDATA_MASK 0xFFFFFFFFu +#define MBX_RDATA_SHIFT 0u + +/*------------------------------------------------------------------------------ + * SS_USER (offset 0x30) register details + */ +#define SS_USER_REG_OFFSET 0x30u + +#define SS_USER_BUSY_OFFSET 0x30 +#define SS_USER_BUSY_MASK 0x00000001u +#define SS_USER_BUSY_SHIFT 0u + +#define SS_USER_RDVLD_OFFSET 0x30 +#define SS_USER_RDVLD_MASK 0x00000002u +#define SS_USER_RDVLD_SHIFT 1u + +#define SS_USER_CMDERR_OFFSET 0x30 +#define SS_USER_CMDERR_MASK 0x00000004u +#define SS_USER_CMDERR_SHIFT 2u + +#ifdef __cplusplus +} +#endif + +#endif /* __CORE_SYSSERV_PF_REGISTERS */ diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreUARTapb/core_uart_apb.c b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreUARTapb/core_uart_apb.c new file mode 100644 index 0000000..2b2087a --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreUARTapb/core_uart_apb.c @@ -0,0 +1,295 @@ +/******************************************************************************* + * (c) Copyright 2007-2021 Microchip FPGA Embedded Systems Solutions. + * + * @file core_uart_apb.c + * @author Microchip FPGA Embedded Systems Solutions + * @brief CoreUARTapb driver implementation. See file "core_uart_apb.h" for + * description of the functions implemented in this file. + * + */ + +#include "coreuartapb_regs.h" +#include "core_uart_apb.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define NULL_INSTANCE ( ( UART_instance_t* ) 0 ) +#define NULL_BUFFER ( ( uint8_t* ) 0 ) + +#define MAX_LINE_CONFIG ( ( uint8_t )( DATA_8_BITS | ODD_PARITY ) ) +#define MAX_BAUD_VALUE ( ( uint16_t )( 0x1FFF ) ) +#define STATUS_ERROR_MASK ( ( uint8_t )( STATUS_PARITYERR_MASK | \ + STATUS_OVERFLOW_MASK | \ + STATUS_FRAMERR_MASK ) ) +#define BAUDVALUE_LSB ( (uint16_t) (0x00FF) ) +#define BAUDVALUE_MSB ( (uint16_t) (0xFF00) ) +#define BAUDVALUE_SHIFT ( (uint8_t) (5) ) + +#define STATUS_ERROR_OFFSET STATUS_PARITYERR_SHIFT + +/***************************************************************************//** + * UART_init() + * See "core_uart_apb.h" for details of how to use this function. + */ +void +UART_init +( + UART_instance_t * this_uart, + addr_t base_addr, + uint16_t baud_value, + uint8_t line_config +) +{ + uint8_t rx_full; + + HAL_ASSERT( this_uart != NULL_INSTANCE ) + HAL_ASSERT( line_config <= MAX_LINE_CONFIG ) + HAL_ASSERT( baud_value <= MAX_BAUD_VALUE ) + + if( ( this_uart != NULL_INSTANCE ) && + ( line_config <= MAX_LINE_CONFIG ) && + ( baud_value <= MAX_BAUD_VALUE ) ) + { + /* + * Store lower 8-bits of baud value in CTRL1. + */ + HAL_set_8bit_reg( base_addr, CTRL1, (uint_fast8_t)(baud_value & + BAUDVALUE_LSB ) ); + + /* + * Extract higher 5-bits of baud value and store in higher 5-bits + * of CTRL2, along with line configuration in lower 3 three bits. + */ + HAL_set_8bit_reg( base_addr, CTRL2, (uint_fast8_t)line_config | + (uint_fast8_t)((baud_value & + BAUDVALUE_MSB) >> BAUDVALUE_SHIFT ) ); + + this_uart->base_address = base_addr; +#ifndef NDEBUG + { + uint8_t config; + uint8_t temp; + uint16_t baud_val; + baud_val = HAL_get_8bit_reg( this_uart->base_address, CTRL1 ); + config = HAL_get_8bit_reg( this_uart->base_address, CTRL2 ); + /* + * To resolve operator precedence between & and << + */ + temp = ( config & (uint8_t)(CTRL2_BAUDVALUE_MASK ) ); + baud_val |= (uint16_t)( (uint16_t)(temp) << BAUDVALUE_SHIFT ); + config &= (uint8_t)(~CTRL2_BAUDVALUE_MASK); + HAL_ASSERT( baud_val == baud_value ); + HAL_ASSERT( config == line_config ); + } +#endif + + /* + * Flush the receive FIFO of data that may have been received before the + * driver was initialized. + */ + rx_full = HAL_get_8bit_reg( this_uart->base_address, STATUS ) & + STATUS_RXFULL_MASK; + while ( rx_full ) + { + HAL_get_8bit_reg( this_uart->base_address, RXDATA ); + rx_full = HAL_get_8bit_reg( this_uart->base_address, STATUS ) & + STATUS_RXFULL_MASK; + } + + /* + * Clear status of the UART instance. + */ + this_uart->status = (uint8_t)0; + } +} + +/***************************************************************************//** + * UART_send() + * See "core_uart_apb.h" for details of how to use this function. + */ +void +UART_send +( + UART_instance_t * this_uart, + const uint8_t * tx_buffer, + size_t tx_size +) +{ + size_t char_idx; + uint8_t tx_ready; + + HAL_ASSERT( this_uart != NULL_INSTANCE ) + HAL_ASSERT( tx_buffer != NULL_BUFFER ) + HAL_ASSERT( tx_size > 0 ) + + if( (this_uart != NULL_INSTANCE) && + (tx_buffer != NULL_BUFFER) && + (tx_size > (size_t)0) ) + { + for ( char_idx = (size_t)0; char_idx < tx_size; char_idx++ ) + { + /* Wait for UART to become ready to transmit. */ + do { + tx_ready = HAL_get_8bit_reg( this_uart->base_address, STATUS ) & + STATUS_TXRDY_MASK; + } while ( !tx_ready ); + /* Send next character in the buffer. */ + HAL_set_8bit_reg( this_uart->base_address, TXDATA, + (uint_fast8_t)tx_buffer[char_idx] ); + } + } +} + +/***************************************************************************//** + * UART_fill_tx_fifo() + * See "core_uart_apb.h" for details of how to use this function. + */ +size_t +UART_fill_tx_fifo +( + UART_instance_t * this_uart, + const uint8_t * tx_buffer, + size_t tx_size +) +{ + uint8_t tx_ready; + size_t size_sent = 0u; + + HAL_ASSERT( this_uart != NULL_INSTANCE ) + HAL_ASSERT( tx_buffer != NULL_BUFFER ) + HAL_ASSERT( tx_size > 0 ) + + /* Fill the UART's Tx FIFO until the FIFO is full or the complete input + * buffer has been written. */ + if( (this_uart != NULL_INSTANCE) && + (tx_buffer != NULL_BUFFER) && + (tx_size > 0u) ) + { + tx_ready = HAL_get_8bit_reg( this_uart->base_address, STATUS ) & + STATUS_TXRDY_MASK; + if ( tx_ready ) + { + do { + HAL_set_8bit_reg( this_uart->base_address, TXDATA, + (uint_fast8_t)tx_buffer[size_sent] ); + size_sent++; + tx_ready = HAL_get_8bit_reg( this_uart->base_address, STATUS ) & + STATUS_TXRDY_MASK; + } while ( (tx_ready) && ( size_sent < tx_size ) ); + } + } + return size_sent; +} + +/***************************************************************************//** + * UART_get_rx() + * See "core_uart_apb.h" for details of how to use this function. + */ +size_t +UART_get_rx +( + UART_instance_t * this_uart, + uint8_t * rx_buffer, + size_t buff_size +) +{ + uint8_t new_status; + uint8_t rx_full; + size_t rx_idx = 0u; + + HAL_ASSERT( this_uart != NULL_INSTANCE ) + HAL_ASSERT( rx_buffer != NULL_BUFFER ) + HAL_ASSERT( buff_size > 0 ) + + if( (this_uart != NULL_INSTANCE) && + (rx_buffer != NULL_BUFFER) && + (buff_size > 0u) ) + { + rx_idx = 0u; + new_status = HAL_get_8bit_reg( this_uart->base_address, STATUS ); + this_uart->status |= new_status; + rx_full = new_status & STATUS_RXFULL_MASK; + while ( ( rx_full ) && ( rx_idx < buff_size ) ) + { + rx_buffer[rx_idx] = HAL_get_8bit_reg( this_uart->base_address, + RXDATA ); + rx_idx++; + new_status = HAL_get_8bit_reg( this_uart->base_address, STATUS ); + this_uart->status |= new_status; + rx_full = new_status & STATUS_RXFULL_MASK; + } + } + return rx_idx; +} + +/***************************************************************************//** + * UART_polled_tx_string() + * See "core_uart_apb.h" for details of how to use this function. + */ +void +UART_polled_tx_string +( + UART_instance_t * this_uart, + const uint8_t * p_sz_string +) +{ + uint32_t char_idx; + uint8_t tx_ready; + + HAL_ASSERT( this_uart != NULL_INSTANCE ) + HAL_ASSERT( p_sz_string != NULL_BUFFER ) + + if( ( this_uart != NULL_INSTANCE ) && ( p_sz_string != NULL_BUFFER ) ) + { + char_idx = 0U; + while( 0U != p_sz_string[char_idx] ) + { + /* Wait for UART to become ready to transmit. */ + do { + tx_ready = HAL_get_8bit_reg( this_uart->base_address, STATUS ) & + STATUS_TXRDY_MASK; + } while ( !tx_ready ); + /* Send next character in the buffer. */ + HAL_set_8bit_reg( this_uart->base_address, TXDATA, + (uint_fast8_t)p_sz_string[char_idx] ); + char_idx++; + } + } +} + +/***************************************************************************//** + * UART_get_rx_status() + * See "core_uart_apb.h" for details of how to use this function. + */ +uint8_t +UART_get_rx_status +( + UART_instance_t * this_uart +) +{ + uint8_t status = UART_APB_INVALID_PARAM; + + HAL_ASSERT( this_uart != NULL_INSTANCE ) + /* + * Extract UART error status and place in lower bits of "status". + * Bit 0 - Parity error status + * Bit 1 - Overflow error status + * Bit 2 - Frame error status + */ + if( this_uart != NULL_INSTANCE ) + { + status = ( ( this_uart->status & STATUS_ERROR_MASK ) >> + STATUS_ERROR_OFFSET ); + /* + * Clear the sticky status for this instance. + */ + this_uart->status = (uint8_t)0; + } + return status; +} + +#ifdef __cplusplus +} +#endif diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreUARTapb/core_uart_apb.h b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreUARTapb/core_uart_apb.h new file mode 100644 index 0000000..2ce0b88 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreUARTapb/core_uart_apb.h @@ -0,0 +1,432 @@ +/******************************************************************************* + * (c) Copyright 2007-2021 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * @file core_uart_apb.h + * @author Microchip FPGA Embedded Systems Solutions + * @brief This file contains the application programming interface for the + * CoreUARTapb bare metal driver. + * + */ +/*=========================================================================*//** + @mainpage CoreUARTapb Bare Metal Driver. + + @section intro_sec Introduction + CoreUARTapb is an implementation of the Universal Asynchronous + Receiver/Transmitter aimed at a minimal FPGA tile usage within an Microsemi + FPGA. The CoreUARTapb bare metal software driver is designed for use in + systems with no operating system. + + The CoreUARTapb driver provides functions for basic polled transmitting and + receiving operations. It also provides functions allowing use of the + CoreUARTapb in interrupt-driven mode, but leaves the management of interrupts + to the calling application, as interrupt enabling and disabling cannot be + controlled through the CoreUARTapb registers. The CoreUARTapb driver is + provided as C source code. + + @section driver_configuration Driver Configuration + Your application software should configure the CoreUARTapb driver, through + calls to the UART_init() function for each CoreUARTapb instance in the + hardware design. The configuration parameters include the CoreUARTapb + hardware instance base address and other runtime parameters, such as baud + rate, bit width, and parity. No CoreUARTapb hardware configuration parameters + are needed by the driver, apart from the CoreUARTapb hardware instance base + address. Hence, no additional configuration files are required to use the driver. + + A CoreUARTapb hardware instance can be generated with fixed baud value, + character size and parity configuration settings as part of the hardware flow. + The baud_value and line_config parameter values passed to the UART_init() + function will not have any effect if fixed values were selected for the + baud value, character size and parity in the hardware configuration of + CoreUARTapb. When fixed values are selected for these hardware configuration + parameters, the driver cannot overwrite the fixed values in the CoreUARTapb + control registers, CTRL1 and CTRL2. + + @section theory_op Theory of Operation + The CoreUARTapb software driver is designed to allow the control of multiple + instances of CoreUARTapb. Each instance of CoreUARTapb in the hardware design + is associated with a single instance of the UART_instance_t structure in the + software. You need to allocate memory for one unique UART_instance_t + structure instance for each CoreUARTapb hardware instance. The contents of + these data structures are initialized during calls to function UART_init(). + A pointer to the structure is passed to subsequent driver functions in order + to identify the CoreUARTapb hardware instance you wish to perform the + requested operation on. + + Note: Do not attempt to directly manipulate the content of UART_instance_t + structures. This structure is only intended to be modified by the driver + function. + + The driver can be used to transmit and receive data once initialized. + Transmit can be performed using the UART_send() function. This function + is blocking, meaning that it will only return once the data passed to + the function has been sent to the CoreUARTapb hardware. Data received + by the CoreUARTapb hardware can be read by the user application using + the UART_get_rx() function. + + The function UART_fill_tx_fifo() is also provided to be used as part of + interrupt-driven transmit. This function fills the CoreUARTapb hardware + transmit FIFO with the content of a data buffer passed as a parameter before + returning. The control of the interrupts must be implemented outside the + driver as the CoreUARTapb hardware does not provide the ability to enable + or disable its interrupt sources. + + The function UART_polled_tx_string() is provided to transmit a NULL + terminated string in polled mode. This function is blocking, meaning that it + will only return once the data passed to the function has been sent to the + CoreUARTapb hardware. + + The function UART_get_rx_status() returns the error status of the CoreUARTapb + receiver. This can be used by applications to take appropriate action in case + of receiver errors. +*//*=========================================================================*/ +#ifndef __CORE_UART_APB_H +#define __CORE_UART_APB_H 1 + +#ifndef LEGACY_DIR_STRUCTURE +#include "hal/hal.h" + +#else +#include "hal.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/***************************************************************************//** + * Data bits length defines: + */ +#define DATA_7_BITS 0x00u +#define DATA_8_BITS 0x01u + +/***************************************************************************//** + * Parity defines: + */ +#define NO_PARITY 0x00u +#define EVEN_PARITY 0x02u +#define ODD_PARITY 0x06u + +/***************************************************************************//** + * Error Status definitions: + */ +#define UART_APB_PARITY_ERROR 0x01u +#define UART_APB_OVERFLOW_ERROR 0x02u +#define UART_APB_FRAMING_ERROR 0x04u +#define UART_APB_NO_ERROR 0x00u +#define UART_APB_INVALID_PARAM 0xFFu + +/***************************************************************************//** + * UART_instance_t + * + * There should be one instance of this structure for each instance of CoreUARTapb + * in your system. This structure instance is used to identify the various UARTs + * in a system and should be passed as first parameter to UART functions to + * identify which UART should perform the requested operation. The 'status' + * element in the structure is used to provide sticky status information. + */ +typedef struct +{ + addr_t base_address; + uint8_t status; +} UART_instance_t; + +/***************************************************************************//** + * The function UART_init() initializes the UART with the configuration passed + * as parameters. The configuration parameters are the baud_value used to + * generate the baud rate and the line configuration (bit length and parity). + * + * @param this_uart The this_uart parameter is a pointer to a UART_instance_t + * structure which holds all data regarding this instance of + * the CoreUARTapb. This pointer will be used to identify + * the target CoreUARTapb hardware instance in subsequent + * calls to the CoreUARTapb functions. + * @param base_addr The base_address parameter is the base address in the + * processor's memory map for the registers of the + * CoreUARTapb instance being initialized. + * @param baud_value The baud_value parameter is used to select the baud rate + * for the UART. The baud value is calculated from the + * frequency of the system clock in hertz and the desired + * baud rate using the following equation: + * + * baud_value = (clock /(baud_rate * 16)) - 1. + * + * The baud_value parameter must be a value in the range 0 + * to 8191 (or 0x0000 to 0x1FFF). + * @param line_config This parameter is the line configuration specifying the + * bit length and parity settings. This is a logical OR of: + * - DATA_7_BITS + * - DATA_8_BITS + * - NO_PARITY + * - EVEN_PARITY + * - ODD_PARITY + * For example, 8 bits even parity would be specified as + * (DATA_8_BITS | EVEN_PARITY). + * @return This function does not return a value. + * Example: + * @code + * #define BAUD_VALUE_57600 25 + * + * #define COREUARTAPB0_BASE_ADDR 0xC3000000UL + * + * UART_instance_t g_uart; + * int main() + * { + * UART_init(&g_uart, COREUARTAPB0_BASE_ADDR, + BAUD_VALUE_57600, (DATA_8_BITS | EVEN_PARITY)); + * } + * @endcode + */ +void +UART_init +( + UART_instance_t * this_uart, + addr_t base_addr, + uint16_t baud_value, + uint8_t line_config +); + +/***************************************************************************//** + * The function UART_send() is used to transmit data. It transfers the contents + * of the transmitter data buffer, passed as a function parameter, into the + * UART's hardware transmitter FIFO. It returns when the full content of the + * transmitter data buffer has been transferred to the UART's transmitter FIFO. + * + * Note: you cannot assume that the data you are sending using this function has + * been received at the other end by the time this function returns. The actual + * transmit over the serial connection will still be taking place at the time of + * the function return. It is safe to release or reuse the memory used as the + * transmit buffer once this function returns. + * + * @param this_uart The this_uart parameter is a pointer to a + * UART_instance_t structure which holds all data regarding + * this instance of the CoreUARTapbUART. + * @param tx_buffer The tx_buffer parameter is a pointer to a buffer + * containing the data to be transmitted. + * @param tx_size The tx_size parameter is the size, in bytes, of + * the data to be transmitted. + * + * @return This function does not return a value. + * + * Example: + * @code + * uint8_t testmsg1[] = {"\n\r\n\r\n\rUART_send() test message 1"}; + * UART_send(&g_uart,(const uint8_t *)&testmsg1,sizeof(testmsg1)); + * @endcode + */ +void +UART_send +( + UART_instance_t * this_uart, + const uint8_t * tx_buffer, + size_t tx_size +); + +/***************************************************************************//** + * The function UART_fill_tx_fifo() fills the UART's transmitter hardware FIFO + * with the data found in the transmitter buffer that is passed in as a + * function parameter. The function returns either when the FIFO is full or + * when the complete contents of the transmitter buffer have been copied into + * the FIFO. It returns the number of bytes copied into the UART's transmitter + * hardware FIFO. This function is intended to be used as part of + * interrupt-driven transmission. + * + * Note: You cannot assume that the data you transmit using this function has + * been received at the other end by the time this function returns. + * The actual transmission over the serial connection will still be + * taking place at the time of the function return. + * + * @param this_uart The this_uart parameter is a pointer to a UART_instance_t + * structure which holds all data regarding this instance of + * the UART. + * @param tx_buffer The tx_buffer parameter is a pointer to a buffer + * containing the data to be transmitted. + * @param tx_size The tx_size parameter is the size in bytes, of the data + * to be transmitted. + * @return This function returns the number of bytes copied + * into the UART's transmitter hardware FIFO. + * + * Example: + * @code + * void send_using_interrupt + * ( + * uint8_t * pbuff, + * size_t tx_size + * ) + * { + * size_t size_in_fifo; + * size_in_fifo = UART_fill_tx_fifo( &g_uart, pbuff, tx_size ); + * } + * @endcode + */ +size_t +UART_fill_tx_fifo +( + UART_instance_t * this_uart, + const uint8_t * tx_buffer, + size_t tx_size +); + +/***************************************************************************//** + * The function UART_get_rx() reads the content of the UART's receiver hardware + * FIFO and stores it in the receiver buffer that is passed in as a function + * parameter. It copies either the full contents of the FIFO into the receiver + * buffer, or just enough data from the FIFO to fill the receiver buffer, + * dependent upon the size of the receiver buffer. The size of the receiver + * buffer is passed in as a function parameter. UART_get_rx() returns the number + * of bytes copied into the receiver buffer. If no data was received at the time + * the function is called, the function returns 0. + * + * Note: This function reads and accumulates the receiver status of the + * CoreUARTapb instance before reading each byte from the receiver's + * data register/FIFO. This allows the driver to maintain a sticky + * record of any receiver errors that occur as the UART receives each + * data byte; receiver errors would otherwise be lost after each read + * from the receiver's data register. A call to the UART_get_rx_status() + * function returns any receiver errors accumulated during the execution + * of the UART_get_rx() function. + * Note: When FIFO mode is disabled in the CoreUARTapb hardware configuration, + * the driver accumulates a sticky record of any parity errors, framing + * errors or overflow errors. When FIFO mode is enabled, the driver + * accumulates a sticky record of overflow errors only; in this case + * interrupts must be used to handle parity errors or framing errors. + * + * @param this_uart The this_uart parameter is a pointer to a UART_instance_t + * structure which holds all data regarding this instance of + * the UART. + * @param rx_buffer The rx_buffer parameter is a pointer to a buffer where the + * received data will be copied. + * @param buff_size The buff_size parameter is the size of the receive buffer + * in bytes. + * @return This function returns the number of bytes copied into the + * receive buffer. + * + * Example: + * @code + * #define MAX_RX_DATA_SIZE 256 + * + * uint8_t rx_data[MAX_RX_DATA_SIZE]; + * uint8_t rx_size = 0; + * + * rx_size = UART_get_rx( &g_uart, rx_data, sizeof(rx_data) ); + * @endcode + */ +size_t +UART_get_rx +( + UART_instance_t * this_uart, + uint8_t * rx_buffer, + size_t buff_size +); + +/***************************************************************************//** + * The function UART_polled_tx_string() is used to transmit a NULL ('\0') + * terminated string. Internally, it polls for the transmit ready status and + * transfers the text starting at the address pointed to by p_sz_string into + * the UART's hardware transmitter FIFO. It is a blocking function and returns + * only when the complete string has been transferred to the UART's transmit + * FIFO. + * + * Note: You cannot assume that the data you transmit using this function + * has been received at the other end by the time this function + * returns. The actual transmission over the serial connection will + * still be taking place at the time of the function return. + * + * @param this_uart The this_uart parameter is a pointer to a + * UART_instance_t structure which holds + * all data regarding this instance of the UART. + * @param p_sz_string The p_sz_string parameter is a pointer to a buffer + * containing the NULL ('\0') terminated string to be + * transmitted. + * @return This function does not return a value. + * + * Example: + * @code + * uint8_t testmsg1[] = {"\r\n\r\nUART_polled_tx_string() test message 1\0"}; + * UART_polled_tx_string(&g_uart,(const uint8_t *)&testmsg1); + * @endcode + */ +void +UART_polled_tx_string +( + UART_instance_t * this_uart, + const uint8_t * p_sz_string +); + +/***************************************************************************//** + * The UART_get_rx_status() function returns the receiver error status of the + * CoreUARTapb instance. It reads both the current error status of the receiver + * and the accumulated error status from preceding calls to the UART_get_rx() + * function and combines them using a bitwise OR. It returns the cumulative + * parity, framing and overflow error status of the receiver, since the + * previous call to UART_get_rx_status(), as an 8-bit encoded value. + * + * Note: The UART_get_rx() function reads and accumulates the receiver status + * of the CoreUARTapb instance before reading each byte from the + * receiver's data register/FIFO. The driver maintains a sticky record + * of the cumulative error status, which persists after the + * UART_get_rx() function returns. The UART_get_rx_status() function + * clears this accumulated record of receiver errors before returning. + * + * @param this_uart The this_uart parameter is a pointer to a UART_instance_t + * structure which holds all data regarding this instance + * of the UART. + * @return This function returns the UART receiver error status as + * an 8-bit encoded value. The returned value is 0 if no + * receiver errors occurred. The driver provides a set of + * bit mask constants which should be compared with and/or + * used to mask the returned value to determine the + * receiver error status. + * When the return value is compared to the following bit + * masks, a non-zero result indicates that the + * corresponding error occurred: + * UART_APB_PARITY_ERROR (bit mask = 0x01) + * UART_APB_OVERFLOW_ERROR (bit mask = 0x02) + * UART_APB_FRAMING_ERROR (bit mask = 0x04) + * When the return value is compared to the following bit + * mask, a non-zero result indicates that no error occurred: + * UART_APB_NO_ERROR (0x00) + * + * Example: + * @code + * UART_instance_t g_uart; + * uint8_t rx_data[MAX_RX_DATA_SIZE]; + * uint8_t err_status; + * err_status = UART_get_err_status(&g_uart); + * + * if(UART_APB_NO_ERROR == err_status ) + * { + * rx_size = UART_get_rx( &g_uart, rx_data, MAX_RX_DATA_SIZE ); + * } + * @endcode + */ +uint8_t +UART_get_rx_status +( + UART_instance_t * this_uart +); + +#ifdef __cplusplus +} +#endif + +#endif /* __CORE_UART_APB_H */ diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreUARTapb/coreuartapb_regs.h b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreUARTapb/coreuartapb_regs.h new file mode 100644 index 0000000..8651f0c --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/CoreUARTapb/coreuartapb_regs.h @@ -0,0 +1,131 @@ +/******************************************************************************* + * (c) Copyright 2007-2021 Microchip FPGA Embedded Systems Solutions. + * + * @file coreuartapb_regs.h + * @author Microchip FPGA Embedded Systems Solutions + * @brief CoreUARTapb register definitions + */ + +#ifndef __CORE_UART_APB_REGISTERS +#define __CORE_UART_APB_REGISTERS 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/*------------------------------------------------------------------------------ + * TxData register details + */ +#define TXDATA_REG_OFFSET 0x0u + +/* + * TxData bits. + */ +#define TXDATA_OFFSET 0x0u +#define TXDATA_MASK 0xFFu +#define TXDATA_SHIFT 0u + +/*------------------------------------------------------------------------------ + * RxData register details + */ +#define RXDATA_REG_OFFSET 0x4u + +/* + * RxData bits. + */ +#define RXDATA_OFFSET 0x4u +#define RXDATA_MASK 0xFFu +#define RXDATA_SHIFT 0u + +/*------------------------------------------------------------------------------ + * ControReg1 register details + */ +#define CTRL1_REG_OFFSET 0x8u + +/* + * Baud value (Lower 8-bits) + */ +#define CTRL1_BAUDVALUE_OFFSET 0x8u +#define CTRL1_BAUDVALUE_MASK 0xFFu +#define CTRL1_BAUDVALUE_SHIFT 0u + +/*------------------------------------------------------------------------------ + * ControReg2 register details + */ +#define CTRL2_REG_OFFSET 0xCu + +/* + * Bit length + */ +#define CTRL2_BIT_LENGTH_OFFSET 0xCu +#define CTRL2_BIT_LENGTH_MASK 0x01u +#define CTRL2_BIT_LENGTH_SHIFT 0u + +/* + * Parity enable. + */ +#define CTRL2_PARITY_EN_OFFSET 0xCu +#define CTRL2_PARITY_EN_MASK 0x02u +#define CTRL2_PARITY_EN_SHIFT 1u + +/* + * Odd/even parity selection. + */ +#define CTRL2_ODD_EVEN_OFFSET 0xCu +#define CTRL2_ODD_EVEN_MASK 0x04u +#define CTRL2_ODD_EVEN_SHIFT 2u + +/* + * Baud value (Higher 5-bits) + */ +#define CTRL2_BAUDVALUE_OFFSET 0xCu +#define CTRL2_BAUDVALUE_MASK 0xF8u +#define CTRL2_BAUDVALUE_SHIFT 3u + +/*------------------------------------------------------------------------------ + * StatusReg register details + */ +#define StatusReg_REG_OFFSET 0x10u + +#define STATUS_REG_OFFSET 0x10u + +/* + * Transmit ready. + */ +#define STATUS_TXRDY_OFFSET 0x10u +#define STATUS_TXRDY_MASK 0x01u +#define STATUS_TXRDY_SHIFT 0u + +/* + * Receive full. + */ +#define STATUS_RXFULL_OFFSET 0x10u +#define STATUS_RXFULL_MASK 0x02u +#define STATUS_RXFULL_SHIFT 1u + +/* + * Parity error. + */ +#define STATUS_PARITYERR_OFFSET 0x10u +#define STATUS_PARITYERR_MASK 0x04u +#define STATUS_PARITYERR_SHIFT 2u + +/* + * Overflow. + */ +#define STATUS_OVERFLOW_OFFSET 0x10u +#define STATUS_OVERFLOW_MASK 0x08u +#define STATUS_OVERFLOW_SHIFT 3u + +/* + * Frame Error. + */ +#define STATUS_FRAMERR_OFFSET 0x10u +#define STATUS_FRAMERR_MASK 0x10u +#define STATUS_FRAMERR_SHIFT 4u + +#ifdef __cplusplus +} +#endif + +#endif /* __CORE_UART_APB_REGISTERS */ diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_i2c/miv_i2c.c b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_i2c/miv_i2c.c new file mode 100644 index 0000000..a2115c9 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_i2c/miv_i2c.c @@ -0,0 +1,758 @@ +/******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * Mi-V I2C Soft IP bare-metal driver. This module is delivered as part of + * Extended Sub System(ESS) MIV_ESS. + * Please refer to miv_i2c.h file for more information. + */ + +#include "miv_i2c.h" + +#ifdef __cplusplus +extern "C" { +#endif + +void MIV_I2C_enable_irq(void); +void MIV_I2C_disable_irq(void); + +#define MIV_I2C_ERROR 0xFFu + +/*------------------------------------------------------------------------------ + * MIV I2C transaction direction. + */ +#define MIV_I2C_WRITE_DIR 0u +#define MIV_I2C_READ_DIR 1u + +/* -- TRANSACTIONS TYPES -- */ +#define MIV_I2C_NO_TRANSACTION 0u +#define MIV_I2C_MASTER_WRITE_TRANSACTION 1u +#define MIV_I2C_MASTER_READ_TRANSACTION 2u +#define MIV_I2C_MASTER_SEQUENTIAL_READ_TRANSACTION 3u + +/*------------------------------------------------------------------------------ + * MIV I2C HW states + */ +#define MIV_I2C_IDLE 0x00u +#define MIV_I2C_TX_STA_CB 0x01u +#define MIV_I2C_TX_DATA 0x02u +#define MIV_I2C_RX_DATA 0x03u + +/* + * Please refer to miv_i2c.h for more info + */ +void +MIV_I2C_init +( + miv_i2c_instance_t *this_i2c, + addr_t base_addr +) +{ + /* Assign the base address + * Clock Prescale value set + * MIV_I2C interrupt enabled + * I2C core enable + */ + psr_t processor_state; + + /* Disabling the interrupts */ + processor_state = HAL_disable_interrupts(); + + /* + * Initialize all items of the this_miv_i2c data structure to zero. This + * initializes all state variables to their init value. It relies on + * the fact that NO_TRANSACTION, MIV_I2C_SUCCESS and I2C_RELEASE_BUS all + * have an actual value of zero. + */ + memset(this_i2c, 0, sizeof(miv_i2c_instance_t)); + + this_i2c->base_addr = base_addr; + + HAL_restore_interrupts(processor_state); +} + +/* + * Please refer to miv_i2c.h for more info + */ +void +MIV_I2C_config +( + miv_i2c_instance_t *this_i2c, + uint16_t clk_prescale +) +{ + /* Assign the base address + * Clock Prescale value set + * MIV_I2C interrupt enabled + * I2C core enable + */ + psr_t processor_state; + + /* Disabling the interrupts */ + processor_state = HAL_disable_interrupts(); + + /* Before writing to prescale reg, the core enable must be zero */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CTRL_CORE_EN, 0x00u); + + /* Set the prescale value */ + HAL_set_16bit_reg(this_i2c->base_addr, PRESCALE, clk_prescale); + + /* Enable the MIV I2C interrupts */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CTRL_IRQ_EN, 0x01u); + + /* Enable the MIV I2C core */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CTRL_CORE_EN, 0x01u); + + this_i2c->master_state = MIV_I2C_IDLE; + + HAL_restore_interrupts(processor_state); +} + +/* + * Please refer to miv_i2c.h for more info + */ +uint8_t +MIV_I2C_start +( + miv_i2c_instance_t *this_i2c +) +{ + psr_t processor_state; + + processor_state = HAL_disable_interrupts(); + + /* Generate I2C start condition */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_STA, 0x01u); + + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_WR, 0x01); + + HAL_restore_interrupts(processor_state); + + return 0u; +} + +/* + * Please refer to miv_i2c.h for more info + */ +uint8_t +MIV_I2C_stop +( + miv_i2c_instance_t *this_i2c +) +{ + psr_t processor_state; + + processor_state = HAL_disable_interrupts(); + + /* Generate I2C stop condition */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_STO, 0x01u); + + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_WR, 0x01); + + HAL_restore_interrupts(processor_state); + + return 0u; +} + +/* + * Please refer to miv_i2c.h for more info + */ +void +MIV_I2C_write +( + miv_i2c_instance_t *this_i2c, + uint8_t i2c_target_addr, + const uint8_t *write_buffer, + uint16_t write_size, + uint8_t bus_options, + uint8_t ack_polling_options +) +{ + psr_t processor_state; + + processor_state = HAL_disable_interrupts(); + + /* I2C write flow + * + * Check I2C status for ongoing transaction + * Populate the structure with input data + * Generate start condition + * Set the write_direction and target address. + */ + + /* Update the transaction only when there is no ongoing I2C transaction */ + if (this_i2c->transaction == MIV_I2C_NO_TRANSACTION) + { + this_i2c->transaction = MIV_I2C_MASTER_WRITE_TRANSACTION; + } + + /* Update the Pending transaction information so that transaction can restarted */ + this_i2c->pending_transaction = MIV_I2C_MASTER_WRITE_TRANSACTION ; + + /* Populate the i2c instance structure */ + + /* Set the target addr */ + this_i2c->target_addr = i2c_target_addr; + this_i2c->dir = MIV_I2C_WRITE_DIR; + + /* Set up the tx buffer */ + this_i2c->master_tx_buffer = write_buffer; + this_i2c->master_tx_size = write_size; + this_i2c->master_tx_idx = 0u; + + /* Set the I2C status in progress and setup the options */ + this_i2c->bus_options = bus_options; + this_i2c->ack_polling_options = ack_polling_options; + this_i2c->master_status = MIV_I2C_IN_PROGRESS; + + + /* Generate I2C start condition */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_STA, 0x01u); + + /* write target address and write bit */ + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_DIR, MIV_I2C_WRITE_DIR); + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_TARGET_ADDR, i2c_target_addr); + + /* Set WR bit to transmit start condition and control byte */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_WR, 0x01); + + /* Set current master hw state -> transmitted start condition and + * control byte + */ + this_i2c->master_state = MIV_I2C_TX_STA_CB; + + /* + * Clear interrupts if required (depends on repeated starts). + * Since the Bus is on hold, only then prior status needs to + * be cleared. + */ + if ( MIV_I2C_HOLD_BUS == this_i2c->bus_status ) + { + /* Must toggle IACK bit to clear the MIV_I2C IRQ*/ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_IACK, 0x01); + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_IACK, 0x00); + } + + MIV_I2C_enable_irq(); + + HAL_restore_interrupts(processor_state); + +} + +/* + * Please refer to miv_i2c.h for more info + */ +void +MIV_I2C_read +( + miv_i2c_instance_t *this_i2c, + uint8_t i2c_target_addr, + uint8_t *read_buffer, + uint16_t read_size, + uint8_t bus_options, + uint8_t ack_polling_options +) +{ + psr_t processor_state; + uint8_t status = MIV_I2C_SUCCESS; + + processor_state = HAL_disable_interrupts(); + + /* MIV I2C Read operation flow + * + * Check for ongoing transaction + * Populate the i2c instance structure + * Generate the start condition + * Set the READ_direction bit and target addr + */ + + uint8_t read_stat = HAL_get_8bit_reg_field(this_i2c->base_addr, STAT_TIP); + + /* Update the transaction only when there is no ongoing I2C transaction */ + if (this_i2c->transaction == MIV_I2C_NO_TRANSACTION) + { + this_i2c->transaction = MIV_I2C_MASTER_READ_TRANSACTION; + } + + this_i2c->pending_transaction = MIV_I2C_MASTER_READ_TRANSACTION; + + /* Populate the MIV I2C instance structure */ + + this_i2c->target_addr = i2c_target_addr; + this_i2c->dir = MIV_I2C_READ_DIR; + + /* Populate read buffer */ + this_i2c->master_rx_buffer = read_buffer; + this_i2c->master_rx_size = read_size; + this_i2c->master_rx_idx = 0u; + + /* Set the BUS and ACK polling options */ + this_i2c->bus_options = bus_options; + this_i2c->ack_polling_options = ack_polling_options; + + /* Generate the start condition */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_STA, 0x01u); + + /* Set the DIR bit and target addr */ + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_DIR, MIV_I2C_READ_DIR); + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_TARGET_ADDR, i2c_target_addr); + + /* Set the WR bit to transmit the start condition and command byte */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_WR, 0x01u); + + /* Set the i2c master state and status transmitting STA and Command Byte */ + this_i2c->master_state = MIV_I2C_TX_STA_CB; + this_i2c->master_status = MIV_I2C_IN_PROGRESS; + + /* Toggle the IACK bit if required */ + /* + * Clear interrupts if required (depends on repeated starts). + * Since the Bus is on hold, only then prior status needs to + * be cleared. + */ + if ( MIV_I2C_HOLD_BUS == this_i2c->bus_status ) + { + /* Must toggle IACK bit to clear the MIV_I2C IRQ*/ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_IACK, 0x01); + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_IACK, 0x00); + } + /* Enable the I2C interrupt */ + MIV_I2C_enable_irq(); + + HAL_restore_interrupts(processor_state); +} + +/* + * Please refer to miv_i2c.h for more info + */ +void +MIV_I2C_write_read +( + miv_i2c_instance_t *this_i2c, + uint8_t target_addr, + const uint8_t *write_buffer, + uint16_t write_size, + uint8_t *read_buffer, + uint16_t read_size, + uint8_t bus_options, + uint8_t ack_polling_options +) +{ + uint8_t status = MIV_I2C_SUCCESS; + psr_t processor_state; + + processor_state = HAL_disable_interrupts(); + + uint8_t read_stat = HAL_get_8bit_reg_field(this_i2c->base_addr, STAT_TIP); + + /* I2C write read operation flow + * + * Used to read the data from set address offset + * + * Configure the i2c instance structure + * generate the start and configure the dir and target addr + * set wr bit to transmit the start and command byte + * + */ + + /* Update the transaction only when there is no ongoing I2C transaction */ + if (this_i2c->transaction == MIV_I2C_NO_TRANSACTION) + { + this_i2c->transaction = MIV_I2C_MASTER_READ_TRANSACTION; + } + + this_i2c->pending_transaction = MIV_I2C_MASTER_READ_TRANSACTION; + + /* Populate the I2C instance */ + + this_i2c->target_addr = target_addr; + + /* setup the i2c direction */ + this_i2c->dir = MIV_I2C_WRITE_DIR; + + /* set up transmit buffer */ + this_i2c->master_tx_buffer = write_buffer; + this_i2c->master_tx_size = write_size; + this_i2c->master_tx_idx = 0u; + + /* set up receive buffer */ + this_i2c->master_rx_buffer = read_buffer; + this_i2c->master_rx_size = read_size; + this_i2c->master_rx_idx = 0u; + + /* Set the bus and ack polling options */ + this_i2c->bus_options = bus_options; + this_i2c->ack_polling_options = ack_polling_options; + + /* Generate the start command */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_STA, 0x01u); + + /* Set the DIR and target addr */ + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_TARGET_ADDR, target_addr); + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_DIR, this_i2c->dir); + + /* Set the WR bit to transmit the start command and command byte */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_WR, 0x01); + + /* Set the i2c master state and status transmitting STA and Command Byte */ + this_i2c->master_state = MIV_I2C_TX_STA_CB; + this_i2c->master_status = MIV_I2C_IN_PROGRESS; + + /* + * Clear interrupt if required + */ + if ( MIV_I2C_HOLD_BUS == this_i2c->bus_status ) + { + /* Must toggle IACK bit to clear the MIV_I2C IRQ*/ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_IACK, 0x01u); + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_IACK, 0x00u); + } + + /* Enable the I2C interrupt */ + MIV_I2C_enable_irq(); + + HAL_restore_interrupts(processor_state); +} + +/* MIV_I2C_isr() + * Please refer to miv_i2c.h for more info + */ +void +MIV_I2C_isr +( + miv_i2c_instance_t *this_i2c +) +{ + uint8_t i2c_state; + uint8_t i2c_ack_status; + uint8_t i2c_al_status; + uint8_t hold_bus; + + /* Read the I2C master state */ + i2c_state = this_i2c->master_state; + + /* Read the ack and al status */ + i2c_ack_status = HAL_get_8bit_reg_field(this_i2c->base_addr, STAT_RXACK); + i2c_al_status = HAL_get_8bit_reg_field(this_i2c->base_addr, STAT_AL); + + switch (i2c_state) + { + /* I2C ISR State Machine + * + * Cases: + * - Transmit start condition and control byte + * - Received ACK and bus arbitration was not lost (Read or Write) + * - Received NACK + * - Bus arbitration lost + * + * - Transmit data + * - Received ACK and bus arbitration was not lost (Read or Write) + * - Received NACK + * - Bus arbitration lost + * + * - Receive data + * - Received ACK and bus arbitration was not lost (Read or Write) + * - Bus arbitration lost + */ + + case MIV_I2C_TX_STA_CB: + + /* Received ACK from target and I2C bus arbitration is not lost */ + if (i2c_ack_status == 0u && i2c_al_status == 0u) + { + /* If I2C master write operation */ + if (this_i2c->dir == MIV_I2C_WRITE_DIR) + { + /* write first byte of data and set the WR bit to transfer the data */ + HAL_set_8bit_reg(this_i2c->base_addr, TRANSMIT, + this_i2c->master_tx_buffer[this_i2c->master_tx_idx]); + + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_WR, 0x01u); + + /* Increment the index */ + this_i2c->master_tx_idx++; + + /* Set the master state to TX data */ + this_i2c->master_state = MIV_I2C_TX_DATA; + } + /* Master read operation */ + else + { + if (this_i2c->master_rx_size == 1u) + { + /* Send the ACK if the rx size is 1, transmit NACK to slave + * after receiving 1 byte to indicate slave to stop sending + * the data + */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_ACK, 0x01u); + } + + /* Send the RD command to slave */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_RD, 0x01u); + + /* Increment the index */ + this_i2c->master_rx_idx++; + + /* Change state to receive data */ + this_i2c->master_state = MIV_I2C_RX_DATA; + } + } + else if (i2c_ack_status == 1u) + { + if (this_i2c->ack_polling_options == MIV_I2C_ACK_POLLING_ENABLE) + { + /* Target responded with NACK and ACK polling option is enabled + * + * Re-send the start condition and control byte + * + * TO-DO: This might become infinite loop check for timeout + * options. + */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_STA, 0x01u); + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_TARGET_ADDR, this_i2c->target_addr); + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_DIR, this_i2c->dir); + + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_WR, 0x01u); + + this_i2c->master_tx_idx = 0u; + this_i2c->master_state = MIV_I2C_TX_STA_CB; + } + + else + { + /* Target responded with NACK and ACK polling is disabled + * Abort the transaction and move to IDLE state + */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_STO, 0x01u); + + this_i2c->master_status = MIV_I2C_FAILED; + this_i2c->transaction = MIV_I2C_NO_TRANSACTION; + + this_i2c->master_state = MIV_I2C_IDLE; + } + } + + else if (i2c_al_status == 1u) + { + /* Arbitration was lost on the BUS during the transmission of + * previous start condition and control byte. + * Re-send the STA and CB + */ + + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_STA, 0x01u); + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_TARGET_ADDR, this_i2c->target_addr); + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_DIR, this_i2c->dir); + + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_WR, 0x01u); + + this_i2c->master_state = MIV_I2C_TX_STA_CB; + } + + break; + + /* Transmit master data */ + case MIV_I2C_TX_DATA: + + /* ACK received and arbitration was not lost */ + if (i2c_ack_status == 0u && i2c_al_status == 0u) + { + uint8_t tx_buff[this_i2c->master_tx_size]; + if (this_i2c->master_tx_idx < this_i2c->master_tx_size) + { + HAL_set_8bit_reg(this_i2c->base_addr, TRANSMIT, + this_i2c->master_tx_buffer[this_i2c->master_tx_idx]); + + tx_buff[this_i2c->master_tx_idx] = this_i2c->master_tx_buffer[this_i2c->master_tx_idx]; + + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_WR, 0x01u); + + /* Increment the index */ + this_i2c->master_tx_idx++; + + /* Set the master state to TX data */ + this_i2c->master_state = MIV_I2C_TX_DATA; + } + + /* All the bytes are transmitted */ + else if (this_i2c->master_tx_idx == this_i2c->master_tx_size) + { + /* If this is a MASTER_READ_TRANSACTION, hold bus and start a + new transfer in read mode now that the read address has been + written to the slave */ + if(this_i2c->transaction == MIV_I2C_MASTER_READ_TRANSACTION) + + { + //Switch direction to READ + this_i2c->dir = MIV_I2C_READ_DIR; + + // Set the STA bit + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_STA, 0x01u); + + /* Set the DIR bit and target addr */ + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_DIR, MIV_I2C_READ_DIR); + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_TARGET_ADDR, this_i2c->target_addr); + + /* Set the WR bit to transmit the start condition and command byte */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_WR, 0x01u); + + // Reset the buffer index + this_i2c->master_tx_idx = 0u; + this_i2c->master_rx_idx = 0u; + + /* Set the master state to RX data */ + this_i2c->master_state = MIV_I2C_RX_DATA; + } + + else + { + /* If releasing the bus, transmit the stop condition at the end + * of the transfer. + */ + hold_bus = this_i2c->bus_status & MIV_I2C_HOLD_BUS; + + if (hold_bus == 0) + { + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_STO, 0x01u); + } + else + { + MIV_I2C_disable_irq(); + } + this_i2c->master_status = MIV_I2C_SUCCESS; + this_i2c->transaction = MIV_I2C_NO_TRANSACTION; + this_i2c->master_state = MIV_I2C_IDLE; + } + } + } + + else if (i2c_ack_status == 1u) + { + /* Received NACK from target device + * + * Release the bus and end the transfer + */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_STO, 0x01u); + + this_i2c->master_status = MIV_I2C_FAILED; + this_i2c->transaction = MIV_I2C_NO_TRANSACTION; + + this_i2c->master_state = MIV_I2C_IDLE; + } + + else if (i2c_al_status == 1u) + { + /* Arbitration was lost on the BUS during the transmission of + * previous start condition and control byte. + * Re-send the STA and CB + */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_STA, 0x01u); + + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_TARGET_ADDR, + this_i2c->target_addr); + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_DIR, this_i2c->dir); + + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_WR, 0x01); + + this_i2c->master_state = MIV_I2C_TX_STA_CB; + } + + break; + + /* Receive target device data */ + case MIV_I2C_RX_DATA: + + if (i2c_al_status == 0u) + { + if (this_i2c->master_rx_idx < this_i2c->master_rx_size) + { + this_i2c->master_rx_buffer[this_i2c->master_rx_idx - 1u] = + HAL_get_8bit_reg(this_i2c->base_addr, RECEIVE); + + /* If next byte is last one + * Send NACK to target device to stop sending data + */ + if (this_i2c->master_rx_idx == (this_i2c->master_rx_size - 1u)) + { + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_ACK, 0x01u); + } + + else + { + /* Send ACK to receive next bytes */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_ACK, 0x00u); + } + + /* Set RD bit to receive next byte */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_RD, 0x01u); + + this_i2c->master_rx_idx++; + } + + /* Received all bytes */ + else //if (this_i2c->master_rx_idx == this_i2c->master_rx_size) + { + this_i2c->master_rx_buffer[this_i2c->master_rx_idx - 1] = + HAL_get_8bit_reg(this_i2c->base_addr, RECEIVE); + + hold_bus = this_i2c->bus_status & MIV_I2C_HOLD_BUS; + + if (hold_bus == 0) + { + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_STO, 0x01u); + } + else + { + MIV_I2C_disable_irq(); + } + this_i2c->master_status = MIV_I2C_SUCCESS; + this_i2c->transaction = MIV_I2C_NO_TRANSACTION; + + this_i2c->master_state = MIV_I2C_IDLE; + } + } + + else if (i2c_al_status == 1u) + { + /* Arbitration was lost on the BUS during the transmission of + * previous start condition and control byte. + * Re-send the STA and CB + */ + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_TARGET_ADDR, + this_i2c->target_addr); + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_DIR, this_i2c->dir); + + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_STA, 0x01u); + + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_WR, 0x01); + + this_i2c->master_state = MIV_I2C_TX_STA_CB; + } + + break; + } + + /* Toggle the IACK bit to clear interrupt */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_IACK, 0x01u); + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_IACK, 0x00u); +} + +/* + * Please refer to miv_i2c.h for more info + */ +uint8_t +MIV_I2C_get_status +( + miv_i2c_instance_t *this_i2c +) +{ + uint8_t i2c_status; + + i2c_status = HAL_get_8bit_reg(this_i2c->base_addr, STATUS); + + return i2c_status; +} + +#ifdef __cplusplus +} +#endif diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_i2c/miv_i2c.h b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_i2c/miv_i2c.h new file mode 100644 index 0000000..688a16c --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_i2c/miv_i2c.h @@ -0,0 +1,850 @@ +/******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * This file contains the application programming interface for the MI-V Soft IP + * I2C module driver. This module is delivered as a part of Mi-V Extended + * Sub-System(MIV_ESS). + */ + +/*=========================================================================*//** + @mainpage Mi-V I2C Bare Metal Driver + + ============================================================================== + Introduction + ============================================================================== + The Mi-V I2C driver provides a set of functions for controlling the Mi-V I2C + Soft-IP module. This module is delivered as a part of the Mi-V Extended + Sub System(MIV_ESS). The driver provides a minimal APB-driven I2C interface, + supporting initiator read and write access to peripheral I2C devices. + + The major features provided by the Mi-V I2C driver are: + - Support for configuring the I2C instance. + - I2C master operations. + - I2C ISR. + + This driver can be used as part of a bare metal system where no operating + system is available. The driver can be adapted for use as part of an + operating system, but the implementation of the adaptation layer between the + driver and the operating system's driver model is outside the scope of this + driver. + + ============================================================================== + Hardware Flow Dependencies + ============================================================================== + The application software should initialize and configure the Mi-V I2C through + the call to the MIV_I2C_init() and MIV_I2C_config() function for Mi-V I2C + instance in the design. The configuration parameter include base address and + Prescaler value. + + ------------------------------ + Interrupt Control + ------------------------------ + The Mi-V I2C driver has to enable and disable the generation of interrupts by + Mi-V I2C at various times while operating. This enabling and disabling of the + interrupts must be done through the Mi-V RV32 HAL provided interrupt handlers. + For that reason, the method controlling the Mi-V I2C interrupts is system + specific and it is necessary to customize the MIV_I2C_enable_irq() and + MIV_I2C_disable_irq() functions as per requirement. + + The implementation of MIV_I2C_enable_irq() should permit the interrupts + generated by the Mi-V I2C to the processor through a call to respective miv-hal + interrupt handler. The implementation of MIV_I2C_disable_irq() should prevent + the interrupts generated by a Mi-V I2C from interrupting the processor. + Please refer to the miv_i2c_interrupt.c for more information about the + implementation. + + No MIV_I2C hardware configuration parameters are used by the driver, apart + from the MIV_I2C base address. Hence, no additional configuration files + are required to use the driver. + + ============================================================================== + Theory of Operation + ============================================================================== + The Mi-V I2C software driver is designed to allow the control of multiple + instances of Mi-V I2C. Each instance of Mi-V I2C in the hardware design is + associated with a single instance of the miv_i2c_instance_t structure in the + software. User must allocate memory for one unique miv_i2c_instance_t + structure for each instance of Mi-V I2C in the hardware. + A pointer to the structure is passed to the subsequent driver functions in + order to identify the MIV_I2C hardware instance and to perform requested + operation. + + Note: Do not attempt to directly manipulate the contents of the + miv_i2c_instance_t structure. These structures are only intended to be modified + by the driver functions. + + The Mi-V I2C driver functions are grouped into following categories: + - Initialization and configuration + - I2C master operation functions to handle write, read and write_read + operations. + - Interrupt control + + -------------------------------- + Initialization and configuration + -------------------------------- + The Mi-V I2C device is first initialized by the call to MIV_I2C_init(). This + function initializes the instance of Mi-V I2C with the base address. + MIV_I2C_init() function must be called before any other Mi-V I2C driver API. + + The configuration of the Mi-V I2C instance is done via call to the + MIV_I2C_config() function. This function will set the prescale value which is + used to set the frequency of the I2C clock(SCLK) generated by I2C module. + + --------------------------------- + Transaction types + --------------------------------- + The driver is designed to handle three types of transactions: + - Write transactions + - Read transactions + - Write-Read transaction + + ### Write Transaction + The write transaction begins with master sending a start condition, followed + by device address byte with the R/W bit set to logic '0', and then by the + word address bytes. The slave acknowledges the receipt of its address with + acknowledge bit. The master sends one byte at a time to the slave, which must + acknowledge the receipt of each byte for the next byte to be sent. The master + sends STOP condition to complete the transaction. The slave can abort the + transaction by replying with negative acknowledge. + + The application programmer can choose not to send the STOP bit at the end of + the transaction causing repetitive start conditions. + + ### Read Transaction + The master I2C device initiates a read transaction by sending a START bit + as soon as the bus becomes free. The start condition is followed by the + control byte which contains 7-bit slave address followed by R/W bit set to + logic '1'. The slave sends data one byte at a time to the master, which must + acknowledge receipt of each byte for the next byte to be sent. The master + sends a non-acknowledge bit following the last byte it wishes to read + followed by a STOP bit. + + The application programmer can choose not to send a STOP bit at the end of + the transaction causing the next transaction to begin with a repeated + START bit. + + ### Write-Read Transaction + The write read transaction is a combination of a write transaction + immediately followed by a read transaction. There is no STOP condition sent + between the write and read phase of write-read transaction. A repeated START + condition is sent between the write and read phases. + + Whilst the write handler is being executed, the slave holds the clock line + low to stretch the clock until the response is ready. + + The write-read transaction is typically used to send an memory/register + address in the write transaction specifying the start address of the data to + be transferred during the read phase. + + The application programmer can choose not to send a STOP bit at the end of + the transaction causing the next transaction to begin with a repeated + START bit. + + ------------------------------------- + Interrupt Control + ------------------------------------- + The Mi-V I2C driver is interrupt driven and it uses the MIV_I2C_irq() function + to drive the ISR state machine which is at the heart of the driver. The + application is responsible for providing the link between the interrupt + generating hardware and the Mi-V I2C interrupt handler and must ensure that + the MIV_I2C_isr() function is called with the correct miv_i2c_instance_t + structure pointer for the Mi-V I2C instance initiating the interrupt. + +*//*=========================================================================*/ +#ifndef MIV_I2C_H_ +#define MIV_I2C_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "mivi2c_regs.h" +#include + +#ifndef LEGACY_DIR_STRUCTURE +#include "hal/hal.h" +#else +#include "hal.h" +#endif + +/*-------------------------------------------------------------------------*//** + The miv_i2c_status_t type is used to report the status of I2C transactions. + */ +typedef enum miv_i2c_status +{ + MIV_I2C_SUCCESS = 0u, + MIV_I2C_IN_PROGRESS, + MIV_I2C_FAILED, + MIV_I2C_TIMED_OUT +}miv_i2c_status_t; + +/*-------------------------------------------------------------------------*//** + This structure is used to identify the MIV_I2C hardware instances in a system. + Your application software should declare one instance of this structure for + each instance of the MIV_I2C in your system. The function MIV_I2C_init() + Initializes this structure. A pointer to an initialised instance of the structure + should be passed as the first parameter to the MIV_I2C driver functions, to + identify which MIV_I2C hardware instance should perform the requested operation. + + The contents of this data structure should not be modified or used outside of + the MIV_I2C driver. Software using the MIV_I2C driver should only need to + create one single instance of this data structure for each MIV_I2C hardware + instance in the system, then pass a pointer to these data structures with each + call to the MIV_I2C driver in order to identify the MIV_I2C hardware instance + it wishes to use. +*/ + +typedef struct miv_i2c_instance +{ + addr_t base_addr; + + /* Transmit related info:*/ + uint_fast8_t target_addr; + + /* Current transaction type */ + uint8_t transaction; + + uint8_t bus_options; + + uint8_t ack_polling_options; + + /* Current State of the I2C master */ + uint8_t master_state; + + /* Master TX INFO: */ + const uint8_t * master_tx_buffer; + uint_fast16_t master_tx_size; + uint_fast16_t master_tx_idx; + uint_fast8_t dir; + + /* Master RX INFO: */ + uint8_t * master_rx_buffer; + uint_fast16_t master_rx_size; + uint_fast16_t master_rx_idx; + + /* Master Status */ + volatile miv_i2c_status_t master_status; + uint32_t master_timeout_ms; + + /* user specific data */ + void *p_user_data ; + + /* I2C bus status */ + uint8_t bus_status; + + /* Is transaction pending flag */ + uint8_t is_transaction_pending; + + /* I2C Pending transaction */ + uint8_t pending_transaction; + +}miv_i2c_instance_t; + + +/*-------------------------------------------------------------------------*//** + MIV_I2C_RELEASE_BUS + ===================== + The MIV_I2C_RELEASE_BUS constant is used to specify the bus_options parameter + for MIV_I2C_read(), MIV_I2C_write() and MIV_I2C_write_read() to indicate + that a STOP bit must be generated at the end of the I2C transaction to release + the bus. + */ +#define MIV_I2C_RELEASE_BUS 0x00u + + +/*-------------------------------------------------------------------------*//** + MIV_I2C_HOLD_BUS + ===================== + The MIV_I2C_HOLD_BUS constant is used to specify the bus_optionsparameter + for MIV_I2C_read(), MIV_I2C_write() and MIV_I2C_write_read() to indicate + that a STOP bit must not be generated at the end of the I2C transaction in + order to retain the bus ownership. This causes the next transaction to + begin with a repeated START bit and no STOP bit between the transactions. + */ +#define MIV_I2C_HOLD_BUS 0x01u + +/*-------------------------------------------------------------------------*//** + MIV_I2C_ACK_POLLING_DISABLE + ===================== + The MIV_I2C_ACK_POLLING_DISABLE constant is used to specify the + ack_polling_options parameter to functions MIV_I2C_write(), + MIV_I2C_write_read() and MIV_I2C_read(). Acknowledgment polling is used when + working with I2C memory devices such as EEPROM, which feature an internal + write cycle. + + With acknowledgment polling disabled, if the target slave device responds to the + control byte with a NACK, the MIV_I2C will abort the transfer. + */ +#define MIV_I2C_ACK_POLLING_DISABLE 0x00u + +/*-------------------------------------------------------------------------*//** + MIV_I2C_ACK_POLLING_ENABLE + ===================== + The MIV_I2C_ACK_POLLING_ENABLE constant is used to specify the + ack_polling_options parameter to functions MIV_I2C_write(), + MIV_I2C_write_read() and MIV_I2C_read(). acknowledgment polling is used when + working with I2C memory devices such as EEPROM, which feature an internal + write cycle. + + With acknowledgment polling enabled, if the slave device responds to the + control byte with a NACK, the MIV_I2C will repeatedly transmit another control + byte until the slave device accepts the connection with an ACK, or the timeout + specified in the MIV_I2C_wait_complete() function is reached. Acknowledgment + polling allows for the next read/write operation to be started as soon as the + EEPROM has completed its internal write cycle. + */ +#define MIV_I2C_ACK_POLLING_ENABLE 0x01u + +/*--------------------------------Public APIs---------------------------------*/ + +/*-------------------------------------------------------------------------*//** + The MIV_I2C_init() function is used to initialize the Mi-V I2C module instance + with the base address. + + Note: This function should be called before calling any other Mi-V I2C + functions. + + @param this_i2c + A pointer to the miv_i2c_instance_t data structure which + will hold all the data related to the Mi-V I2C module + instance being used. A pointer to this structure is passed to + rest of the Mi-V I2C driver functions for operation. + @param base_addr + Base address of the Mi-V I2C module instance in the MIV_ESS + soft IP. + + @return + This function does not return any value. + + Example: + @code + #define MIV_I2C_BASE_ADDR 0x7A000000u + + miv_i2c_instance_t g_miv_i2c_inst; + + void main( void ) + { + MIV_I2C_init( &g_miv_i2c_inst, MIV_I2C_BASE_ADDR); + } + @endcode + */ +void +MIV_I2C_init +( + miv_i2c_instance_t *this_i2c, + addr_t base_addr +); + +/*-------------------------------------------------------------------------*//** + The MIV_I2C_config() function is used to configure the Mi-V I2C module. This + function will set the prescale value which is used to set the frequency of + the I2C clock(SCLK) generated by I2C module and also enables the I2C core and + interrupts. + + @param this_i2c + A pointer to the miv_i2c_instance_t data structure which + will hold all the data related to the Mi-V I2C module + instance being used. A pointer to this structure is passed to + rest of the Mi-V I2C driver functions for operation. + + @param clk_prescale + The value used to set the frequency of Mi-V I2C serial clock + (SCLK) generated by the Mi-V I2C module instance. The + prescaler value required to set particular frequency of + Mi-V I2C can be calculated using following formula: + + prescaler = (System Clock Frequency) / (5 * (Desired I2C Clock Frequency)) - 1 + + @return + This function does not return any value. + + + Example: + @code + #define MIV_I2C_BASE_ADDR 0x7A000000u + + miv_i2c_instance_t g_miv_i2c_inst; + + void main( void ) + { + MIV_I2C_init( &g_miv_i2c_inst, MIV_I2C_BASE_ADDR); + + Configuring Mi-V I2C core at Normal Speed (100MHz) for 50MHz Sys clock. + MIV_I2C_config(&g_miv_i2c_inst, 0x63); + } + @endcode + */ +void +MIV_I2C_config +( + miv_i2c_instance_t *this_i2c, + uint16_t clk_prescale +); + + +uint8_t +MIV_I2C_start +( + miv_i2c_instance_t *this_i2c +); + + +uint8_t +MIV_I2C_stop +( + miv_i2c_instance_t *this_i2c +); + +/*-------------------------------------------------------------------------*//** + The MIV_I2C_write() is used to set up and start the Mi-V I2C master write + transaction. This function is used for all Mi-V master write operation. + + For more information about the operation, please refer to the 'theory of + operations' section at the start of this document. + + This function returns immediately after initiating the transaction. The content + of the write buffer passed as parameter should not be modified until the write + transaction completes. It also means that the memory allocated for the write + buffer should not be freed or should not go out of scope before the write + completes. + You can check for the write transaction completion by polling the master_status + from miv_i2c_instance_t structure as shown in the sample code. + + @param this_i2c + A pointer to the miv_i2c_instance_t data structure which + will hold all the data related to the Mi-V I2C module + instance being used. A pointer to this structure is passed to + rest of the Mi-V I2C driver functions for operation. + + @param i2c_target_addr + This parameter specifies the serial address for the slave + device. + + @param write_buffer + This parameter is a pointer to the buffer holding data to be + written to target I2C device. + Care must be taken not to release the memory used by this + buffer before the write transaction completes. + + @param write_size + Number of bytes held in the write_buffer to be written to the + I2C device. + @param bus_options: + The bus_options parameter is used to indicate if the I2C bus + should be released on completion of the write transaction. + Using the MIV_I2C_RELEASE_BUS constant for the bus_options + parameter causes a STOP bit to be generated at the end of the + write transaction causing the bus to be released for other I2C + devices to use. Using the MIV_I2C_HOLD_BUS constant as + bus_options parameter prevents a STOP bit from being generated + at the end of the write transaction, preventing other I2C + devices from initiating a bus transaction. + + @param ack_polling_options: + The ack_polling_options parameter is used to indicate how the + MIV_I2C will respond if the slave device transmits a NACK to + the I2C control byte. Using the MIV_I2C_ACK_POLLING_DISABLE + constant for the ack_polling_options parameter causes the + MIV_I2C to abort the transfer if the slave device responds to + the I2C control byte with a NACK. Using the + MIV_I2C_ACK_POLLING_ENABLE constant for the ack_polling_options + parameter causes the MIV_I2C to repeatedly transmit a control + byte to the slave device until the slave device responds with + an ACK. + @return + This function does not return any value. + + + Example: + @code + #define MIV_I2C_BASE_ADDR 0x7A000000u + + miv_i2c_instance_t g_miv_i2c_inst; + + void main( void ) + { + MIV_I2C_init( &g_miv_i2c_inst, MIV_I2C_BASE_ADDR); + + Configuring Mi-V I2C core at Normal Speed (100MHz) for 50MHz Sys clock. + MIV_I2C_config(&g_miv_i2c_inst, 0x63); + + MIV_I2C_write (&g_miv_i2c_inst, + DUALEE_SLAVEADDRESS_1, + i2c_tx_buffer, + transfer_size, + MIV_I2C_RELEASE_BUS, + MIV_I2C_ACK_POLLING_ENABLE + ); + + // Wait till the miv i2c status changes + do { + miv_i2c_status = miv_i2c.master_status; + }while (MIV_I2C_IN_PROGRESS == miv_i2c_status); + } + @endcode + */ +void +MIV_I2C_write +( + miv_i2c_instance_t *this_i2c, + uint8_t i2c_target_addr, + const uint8_t *write_buffer, + uint16_t write_size, + uint8_t bus_options, + uint8_t ack_polling_options +); + +/*-------------------------------------------------------------------------*//** + The MIV_I2C_read() is used to set up and start the Mi-V I2C master read + transaction. This function is used for all MIV_I2C master read operation. + + For more information about the operation, please refer to the 'theory of + operations' section at the start of this document. + + This function returns immediately after initiating the transaction. The content + of the read buffer passed as parameter should not be modified until the write + transaction completes. It also means that the memory allocated for the read + buffer should not be freed or should not go out of scope before the read + completes. + You can check for the write transaction completion by polling the master_status + from miv_i2c_instance_t structure as shown in the sample code. + + @param this_i2c + A pointer to the miv_i2c_instance_t data structure which + will hold all the data related to the Mi-V I2C module + instance being used. A pointer to this structure is passed to + rest of the Mi-V I2C driver functions for operation. + + @param i2c_target_addr + This parameter specifies the serial address for the slave + device. + + @param read_buffer + This parameter is a pointer to the buffer where the data + received from the I2C slave device is stored. + Care must be taken not to release the memory used by this + buffer before the write transaction completes. + + @param read_size + Number of bytes held in the write_buffer to be read from the + I2C device. + + @param bus_options: + The bus_options parameter is used to indicate if the I2C bus + should be released on completion of the write transaction. + Using the MIV_I2C_RELEASE_BUS constant for the bus_options + parameter causes a STOP bit to be generated at the end of the + write transaction causing the bus to be released for other I2C + devices to use. Using the MIV_I2C_HOLD_BUS constant as + bus_options parameter prevents a STOP bit from being generated + at the end of the write transaction, preventing other I2C + devices from initiating a bus transaction. + + @param ack_polling_options: + The ack_polling_options parameter is used to indicate how the + MIV_I2C will respond if the slave device transmits a NACK to + the I2C control byte. Using the MIV_I2C_ACK_POLLING_DISABLE + constant for the ack_polling_options parameter causes the + MIV_I2C to abort the transfer if the slave device responds to + the I2C control byte with a NACK. Using the + MIV_I2C_ACK_POLLING_ENABLE constant for the ack_polling_options + parameter causes the MIV_I2C to repeatedly transmit a control + byte to the slave device until the slave device responds with + an ACK. + @return + This function does not return any value. + + + Example: + @code + #define MIV_I2C_BASE_ADDR 0x7A000000u + + miv_i2c_instance_t g_miv_i2c_inst; + + void main( void ) + { + MIV_I2C_init( &g_miv_i2c_inst, MIV_I2C_BASE_ADDR); + + Configuring Mi-V I2C core at Normal Speed (100MHz) for 50MHz Sys clock. + MIV_I2C_config(&g_miv_i2c_inst, 0x63); + + MIV_I2C_write (&g_miv_i2c_inst, + DUALEE_SLAVEADDRESS_1, + i2c_tx_buffer, + transfer_size, + MIV_I2C_RELEASE_BUS, + MIV_I2C_ACK_POLLING_ENABLE + ); + + // Wait till the miv i2c status changes + do { + miv_i2c_status = miv_i2c.master_status; + }while (MIV_I2C_IN_PROGRESS == miv_i2c_status); + + // reset miv_i2c_status variable + miv_i2c_status = 0u; + + MIV_I2C_read (&g_miv_i2c_inst, + DUALEE_SLAVEADDRESS_1, + i2c_rx_buffer, + transfer_size, + MIV_I2C_RELEASE_BUS, + MIV_I2C_ACK_POLLING_ENABLE + ); + + // Wait till the miv i2c status changes + do { + miv_i2c_status = miv_i2c.master_status; + }while (MIV_I2C_IN_PROGRESS == miv_i2c_status); + } + @endcode + */ +void +MIV_I2C_read +( + miv_i2c_instance_t *this_i2c, + uint8_t i2c_target_addr, + uint8_t *read_buffer, + uint16_t read_size, + uint8_t bus_options, + uint8_t ack_polling_options +); + +/*-------------------------------------------------------------------------*//** + The MIV_I2C_write_read() is used to set up and start the Mi-V I2C master + write_read transaction. This function is used for all MIV_I2C master write_read + operation. + + This function is used in cases where data is being requested from a specific + address offset inside the target I2C slave device. + In this type of I2C operation, the I2C master starts by initiating a write + operation. During this write operation, the specific address offset is written + to the I2C slave. Once the address offset has been written to the I2C slave, + the I2C master transmits a repeated start, and initiates a read operation to + read data from the set address. + + For more information about the operation, please refer to the 'theory of + operations' section at the start of this document. + + This function returns immediately after initiating the transaction. The content + of the write and read buffer passed as parameter should not be modified until + the write transaction completes. It also means that the memory allocated for + the write and read buffer should not be freed or should not go out of scope + before the operation completes. + You can check for the write_read transaction completion by polling the + master_status from miv_i2c_instance_t structure. + + @param this_i2c + A pointer to the miv_i2c_instance_t data structure which + will hold all the data related to the Mi-V I2C module + instance being used. A pointer to this structure is passed to + rest of the Mi-V I2C driver functions for operation. + + @param i2c_target_addr + This parameter specifies the serial address for the slave + device. + + @param write_buffer + This parameter is a pointer to the buffer holding data to be + written to target I2C device. + Care must be taken not to release the memory used by this + buffer before the write transaction completes. + + @param write_size + Number of bytes held in the write_buffer to be written to the + I2C device. + + @param read_buffer + This parameter is a pointer to the buffer where the data + received from the I2C slave device is stored. + Care must be taken not to release the memory used by this + buffer before the write transaction completes. + + @param read_size + Number of bytes held in the write_buffer to be read from the + I2C device. + + @param bus_options: + The bus_options parameter is used to indicate if the I2C bus + should be released on completion of the write transaction. + Using the MIV_I2C_RELEASE_BUS constant for the bus_options + parameter causes a STOP bit to be generated at the end of the + write transaction causing the bus to be released for other I2C + devices to use. Using the MIV_I2C_HOLD_BUS constant as + bus_options parameter prevents a STOP bit from being generated + at the end of the write transaction, preventing other I2C + devices from initiating a bus transaction. + + @param ack_polling_options: + The ack_polling_options parameter is used to indicate how the + MIV_I2C will respond if the slave device transmits a NACK to + the I2C control byte. Using the MIV_I2C_ACK_POLLING_DISABLE + constant for the ack_polling_options parameter causes the + MIV_I2C to abort the transfer if the slave device responds to + the I2C control byte with a NACK. Using the + MIV_I2C_ACK_POLLING_ENABLE constant for the ack_polling_options + parameter causes the MIV_I2C to repeatedly transmit a control + byte to the slave device until the slave device responds with + an ACK or the timeout specified in the MIV_I2C_wait_complete() + function is reached. + @return + This function does not return any value. + + + Example: + @code + #define MIV_I2C_BASE_ADDR 0x7A000000u + + miv_i2c_instance_t g_miv_i2c_inst; + + void main( void ) + { + MIV_I2C_init( &g_miv_i2c_inst, MIV_I2C_BASE_ADDR); + + Configuring Mi-V I2C core at Normal Speed (100MHz) for 50MHz Sys clock. + MIV_I2C_config(&g_miv_i2c_inst, 0x63); + + MIV_I2C_write (&g_miv_i2c_inst, + DUALEE_SLAVEADDRESS_1, + i2c_tx_buffer, + transfer_size, + MIV_I2C_RELEASE_BUS, + MIV_I2C_ACK_POLLING_ENABLE + ); + + // Wait till the miv i2c status changes + do { + miv_i2c_status = miv_i2c.master_status; + }while (MIV_I2C_IN_PROGRESS == miv_i2c_status); + + // reset miv_i2c_status variable + miv_i2c_status = 0u; + + uint8_t addr_offset[2] = {0x00, 0x00}; + MIV_I2C_write_read(&miv_i2c, + DUALEE_SLAVEADDRESS_1, + addr_offset, + sizeof(addr_offset), + i2c_rx_buffer, + transfer_size, + MIV_I2C_RELEASE_BUS, + MIV_I2C_ACK_POLLING_ENABLE + ); + + // Wait till the miv i2c status changes + do { + miv_i2c_status = miv_i2c.master_status; + }while (MIV_I2C_IN_PROGRESS == miv_i2c_status); + } + @endcode + */ +void +MIV_I2C_write_read +( + miv_i2c_instance_t *this_i2c, + uint8_t target_addr, + const uint8_t *write_buffer, + uint16_t write_size, + uint8_t *read_buffer, + uint16_t read_size, + uint8_t bus_options, + uint8_t ack_polling_options +); + +/*-------------------------------------------------------------------------*//** + The MIV_I2C_isr() function contains the MIV_I2C's interrupt service routine. + This ISR is at the heart of the MIV_I2C driver, and is used to control the + interrupt-driven, byte-by-byte I2C read and write operations. + + The ISR operates as a Finite State Machine (FSM), which uses the previously + completed I2C operation and its result to determine which I2C operation will + be performed next. + + The ISR operation is divided into following categories: + - MIV_I2C_IDLE + - MIV_I2C_TX_STA_CB + - MIV_I2C_TX_DATA + - MIV_I2C_RX_DATA + + ##### MIV_I2C_IDLE + The MIV_I2C_IDLE is entered on reset, or when an I2C master operation has been + completed or aborted. + Upon entering, the FSM will remain in this state until a write, read, or + write-read operation is requested + + ##### MIV_I2C_STA_CB + The MIV_I2C_TX_STA_CB operation is performed when the start condition and + control byte(i2c target address(7-bit) and direction of transaction(1-bit)) is + transmitted by the Mi-V I2C master device to the slave. + If the target I2C slave device responded to the previous START Condition + + Control Byte with an ACK, the MIV_I2C will start the requested I2C + read/write operation. + If the target slave I2C slave device responds with NACK, the MIV_I2C will + remain in this state or return to the idle state based on ack_polling + configuration. + + ##### MIV_I2C_TX_DATA + The MIV_I2C_TX_DATA state is entered after the target slave device accepts a + write request with an ACK. + This state is used to handle the byte-by-byte MIV_I2C write operations. + The FSM will remain in this state until either all data bytes have been + written to the target slave device, or an error occurs during the write + operation. + + ##### MIV_I2C_RX_DATA + The MIV_I2C_RX_DATA state is entered after the target slave device accepts a + read request with an ACK. + This state is used to handle the byte-by-byte MIV_I2C read operations. + The FSM will remain in this state until either all data bytes have been + received from the target slave device, or an error occurs. + + @param this_i2c + A pointer to the miv_i2c_instance_t data structure which + will hold all the data related to the Mi-V I2C module + instance being used. A pointer to this structure is passed to + rest of the Mi-V I2C driver functions for operation. + */ +void +MIV_I2C_isr +( + miv_i2c_instance_t *this_i2c +); + +/*-------------------------------------------------------------------------*//** + The MIV_I2C_get_status() returns the 8-bit Mi-V I2C status register value. + + @param this_i2c + A pointer to the miv_i2c_instance_t data structure which + will hold all the data related to the Mi-V I2C module + instance being used. A pointer to this structure is passed to + rest of the Mi-V I2C driver functions for operation. + @return + This function returns 8-bit Mi-V I2C status register value. + */ +uint8_t +MIV_I2C_get_status +( + miv_i2c_instance_t *this_i2c +); + +#endif /* MIV_I2C_H_ */ diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_i2c/miv_i2c_interrupt.c b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_i2c/miv_i2c_interrupt.c new file mode 100644 index 0000000..871eafe --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_i2c/miv_i2c_interrupt.c @@ -0,0 +1,25 @@ +/******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * This file contains functions used for MIV_I2C driver interrupt control. + * User should enable and disable the interrupts according to their design. + * Please refer to miv_i2c.h file for more information. + */ + +#include "miv_rv32_hal/miv_rv32_hal.h" + +void MIV_I2C_disable_irq(void) +{ +/* Disable I2C interrupt */ + MRV_disable_local_irq(MRV32_MSYS_EIE2_IRQn); +} + +void MIV_I2C_enable_irq(void) +{ +/* Enable I2C interrupt */ + MRV_enable_local_irq(MRV32_MSYS_EIE2_IRQn); +} + + diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_i2c/mivi2c_regs.h b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_i2c/mivi2c_regs.h new file mode 100644 index 0000000..ee6770a --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_i2c/mivi2c_regs.h @@ -0,0 +1,154 @@ + /******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * This file contains Register bit offsets and masks definitions for MI-V Soft + * IP I2C module driver. This module is delivered as a part of Mi-V extended + * Sub-System(MIV_ESS). + */ + +#ifndef MIV_I2C_APB_REGISTERS +#define MIV_I2C_APB_REGISTERS 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/*------------------------------------------------------------------------------ + * Prescale register details + */ +#define PRESCALE_REG_OFFSET 0x00u + +/* Prescale register bits */ +#define PRESCALE_OFFSET 0x00u +#define PRESCALE_MASK 0xFFFFu +#define PRESCALE_SHIFT 0u + +/*------------------------------------------------------------------------------ + * Control register details + */ +#define CONTROL_REG_OFFSET 0x04u + +/* Control register bits */ +#define CONTROL_OFFSET 0x04u +#define CONTROL_MASK 0xC0u +#define CONTROL_SHIFT 0u + +/* Control register Core Enable Bit */ +#define CTRL_CORE_EN_OFFSET 0x04u +#define CTRL_CORE_EN_MASK 0x80u +#define CTRL_CORE_EN_SHIFT 7u + +/* Control register IRQ Enable bit */ +#define CTRL_IRQ_EN_OFFSET 0x04u +#define CTRL_IRQ_EN_MASK 0x40u +#define CTRL_IRQ_EN_SHIFT 6u + +/*------------------------------------------------------------------------------ + * Transmit register details + */ +#define TRANSMIT_REG_OFFSET 0x08u + +/* Transmit register bits */ +#define TRANSMIT_OFFSET 0x08u +#define TRANSMIT_MASK 0xFFu +#define TRANSMIT_SHIFT 0u + +/* Transmit register DIR bit */ +#define TX_DIR_OFFSET 0x08u +#define TX_DIR_MASK 0x01u +#define TX_DIR_SHIFT 0u + +/* Transmit register TARGET_ADDR bit */ +#define TX_TARGET_ADDR_OFFSET 0x08u +#define TX_TARGET_ADDR_MASK 0xFEu +#define TX_TARGET_ADDR_SHIFT 1u + +/*------------------------------------------------------------------------------ + * Receive register details + */ +#define RECEIVE_REG_OFFSET 0x0Cu + +/* Receive register bits */ +#define RECEIVE_OFFSET 0x0Cu +#define RECEIVE_MASK 0xFFu +#define RECEIVE_SHIFT 0u + +/*------------------------------------------------------------------------------ + * Command register details + */ +#define COMMAND_REG_OFFSET 0x10u + +/* Command register bits */ +#define COMMAND_OFFSET 0x10u +#define COMMAND_MASK 0xF9u +#define COMMAND_SHIFT 0u + +/* Command register IACK bit */ +#define CMD_IACK_OFFSET 0x10u +#define CMD_IACK_MASK 0x01u +#define CMD_IACK_SHIFT 0u + +/* Command register ACK bit */ +#define CMD_ACK_OFFSET 0x10u +#define CMD_ACK_MASK 0x08u +#define CMD_ACK_SHIFT 3u + +/* Command register WR bit */ +#define CMD_WR_OFFSET 0x10u +#define CMD_WR_MASK 0x10u +#define CMD_WR_SHIFT 4u + +/* Command register RD bit */ +#define CMD_RD_OFFSET 0x10u +#define CMD_RD_MASK 0x20u +#define CMD_RD_SHIFT 5u + +/* Command register STO bit */ +#define CMD_STO_OFFSET 0x10u +#define CMD_STO_MASK 0x40u +#define CMD_STO_SHIFT 6u + +/* Command register STA bit */ +#define CMD_STA_OFFSET 0x10u +#define CMD_STA_MASK 0x80u +#define CMD_STA_SHIFT 7u + +/*------------------------------------------------------------------------------ + * Status register details + */ +#define STATUS_REG_OFFSET 0x14u + +/* Command register bits */ +#define STATUS_OFFSET 0x14u +#define STATUS_MASK 0xFFu +#define STATUS_SHIFT 0u + +/* Status register Interrupt Flag(IF) bit */ +#define STAT_IF_OFFSET 0x14u +#define STAT_IF_MASK 0x01u +#define STAT_IF_SHIFT 0u + +/* Status register Transfer in Progress(TIP) bit */ +#define STAT_TIP_OFFSET 0x14u +#define STAT_TIP_MASK 0x02u +#define STAT_TIP_SHIFT 1u + +/* Status register Arbitration Lost(AL) bit */ +#define STAT_AL_OFFSET 0x14u +#define STAT_AL_MASK 0x20u +#define STAT_AL_SHIFT 5u + +/* Status register Busy(BUSY) bit */ +#define STAT_BUSY_OFFSET 0x14u +#define STAT_BUSY_MASK 0x40u +#define STAT_BUSY_SHIFT 6u + +/* Status register Ack received(RXACK) bit */ +#define STAT_RXACK_OFFSET 0x14u +#define STAT_RXACK_MASK 0x80u +#define STAT_RXACK_SHIFT 7u + + +#endif /* MIV_I2C_APB_REGISTERS */ diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_plic/miv_plic.c b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_plic/miv_plic.c new file mode 100644 index 0000000..7eb9637 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_plic/miv_plic.c @@ -0,0 +1,287 @@ +/******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * MI-V Soft IP fabric bare-metal driver for Mi-V PLIC module. This module is + * delivered as a part of Mi-V Extended Sub System(MIV_ESS). + * Please refer to miv_plic.h file for more information. + */ + +#include "miv_plic.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/***************************************************************************//** + * Mi-V PLIC interrupt handler function declaration. + * These functions are called by the external interrupt handler of the MIV_RV32 + * core base on the PLIC source causing the interrupt. + */ +uint8_t Invalid_IRQHandler(void); +uint8_t MIV_PLIC_EXT0_IRQHandler(void); +uint8_t MIV_PLIC_EXT1_IRQHandler(void); +uint8_t MIV_PLIC_EXT2_IRQHandler(void); +uint8_t MIV_PLIC_EXT3_IRQHandler(void); +uint8_t MIV_PLIC_EXT4_IRQHandler(void); +uint8_t MIV_PLIC_EXT5_IRQHandler(void); +uint8_t MIV_PLIC_EXT6_IRQHandler(void); +uint8_t MIV_PLIC_EXT7_IRQHandler(void); +uint8_t MIV_PLIC_EXT8_IRQHandler(void); +uint8_t MIV_PLIC_EXT9_IRQHandler(void); +uint8_t MIV_PLIC_EXT10_IRQHandler(void); +uint8_t MIV_PLIC_EXT11_IRQHandler(void); +uint8_t MIV_PLIC_EXT12_IRQHandler(void); +uint8_t MIV_PLIC_EXT13_IRQHandler(void); +uint8_t MIV_PLIC_EXT14_IRQHandler(void); +uint8_t MIV_PLIC_EXT15_IRQHandler(void); +uint8_t MIV_PLIC_EXT16_IRQHandler(void); +uint8_t MIV_PLIC_EXT17_IRQHandler(void); +uint8_t MIV_PLIC_EXT18_IRQHandler(void); +uint8_t MIV_PLIC_EXT19_IRQHandler(void); +uint8_t MIV_PLIC_EXT20_IRQHandler(void); +uint8_t MIV_PLIC_EXT21_IRQHandler(void); +uint8_t MIV_PLIC_EXT22_IRQHandler(void); +uint8_t MIV_PLIC_EXT23_IRQHandler(void); +uint8_t MIV_PLIC_EXT24_IRQHandler(void); +uint8_t MIV_PLIC_EXT25_IRQHandler(void); +uint8_t MIV_PLIC_EXT26_IRQHandler(void); +uint8_t MIV_PLIC_EXT27_IRQHandler(void); +uint8_t MIV_PLIC_EXT28_IRQHandler(void); +uint8_t MIV_PLIC_EXT29_IRQHandler(void); +uint8_t MIV_PLIC_EXT30_IRQHandler(void); + +/***************************************************************************//** + * MIV_PLIC interrupt handler for external interrupts. + * The array of the function pointers pointing to the weak handler of the Mi-V + * PLIC interrupt handlers. + * These functions are called by the external interrupt handler of the MIV_RV32 + * core base on the PLIC source causing the interrupt. + */ +uint8_t (* const ext_irq_handler_table[32]) (void) = +{ + Invalid_IRQHandler, + MIV_PLIC_EXT0_IRQHandler, + MIV_PLIC_EXT1_IRQHandler, + MIV_PLIC_EXT2_IRQHandler, + MIV_PLIC_EXT3_IRQHandler, + MIV_PLIC_EXT4_IRQHandler, + MIV_PLIC_EXT5_IRQHandler, + MIV_PLIC_EXT6_IRQHandler, + MIV_PLIC_EXT7_IRQHandler, + MIV_PLIC_EXT8_IRQHandler, + MIV_PLIC_EXT9_IRQHandler, + MIV_PLIC_EXT10_IRQHandler, + MIV_PLIC_EXT11_IRQHandler, + MIV_PLIC_EXT12_IRQHandler, + MIV_PLIC_EXT13_IRQHandler, + MIV_PLIC_EXT14_IRQHandler, + MIV_PLIC_EXT15_IRQHandler, + MIV_PLIC_EXT16_IRQHandler, + MIV_PLIC_EXT17_IRQHandler, + MIV_PLIC_EXT18_IRQHandler, + MIV_PLIC_EXT19_IRQHandler, + MIV_PLIC_EXT20_IRQHandler, + MIV_PLIC_EXT21_IRQHandler, + MIV_PLIC_EXT22_IRQHandler, + MIV_PLIC_EXT23_IRQHandler, + MIV_PLIC_EXT24_IRQHandler, + MIV_PLIC_EXT25_IRQHandler, + MIV_PLIC_EXT26_IRQHandler, + MIV_PLIC_EXT27_IRQHandler, + MIV_PLIC_EXT28_IRQHandler, + MIV_PLIC_EXT29_IRQHandler, + MIV_PLIC_EXT30_IRQHandler +}; + +/* Mi-V PLIC interrupt weak handlers */ +__attribute__((weak)) uint8_t Invalid_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT0_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT1_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT2_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT3_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT4_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT5_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT6_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT7_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT8_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT9_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT10_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT11_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT12_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT13_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT14_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT15_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT16_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT17_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT18_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT19_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT20_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT21_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT22_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT23_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT24_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT25_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT26_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT27_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT28_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT29_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT30_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +/*-------------------------------------------------------------------------*//** + * Please refer to miv_plic.h for more information about this function. +*/ +void +MIV_PLIC_isr +( + miv_plic_instance_t *this_plic +) +{ + unsigned long hart_id = read_csr(mhartid); + + /* claim the interrupt from PLIC controller */ + + uint32_t int_num = HAL_get_32bit_reg(this_plic->base_addr + + (0x1000 * hart_id), INT_CLAIM_COMPLETE); + + uint8_t disable = EXT_IRQ_KEEP_ENABLED; + disable = ext_irq_handler_table[int_num](); + + /* Indicate the PLIC controller that the interrupt is processed and claim is + * complete. */ + HAL_set_32bit_reg(this_plic->base_addr + + (0x1000 * hart_id), INT_CLAIM_COMPLETE, int_num); + + if (EXT_IRQ_DISABLE == disable) + { + MIV_PLIC_disable_irq(this_plic, (miv_plic_irq_num_t)int_num); + } +} diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_plic/miv_plic.h b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_plic/miv_plic.h new file mode 100644 index 0000000..3e893c3 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_plic/miv_plic.h @@ -0,0 +1,411 @@ +/******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * This file contains the application programming interface for the MI-V Soft IP + * PLIC module driver. This module is delivered as a part of Mi-V Extended + * Sub-System(ESS). + */ + /*=========================================================================*//** + @mainpage Mi-V PLIC Bare Metal Driver + + ============================================================================== + Introduction + ============================================================================== + The Mi-V driver provides a set of functions for controlling the Mi-V PLIC + (platform level interrupt controller) soft-IP module. This module is delivered + as a part of the MIV_ESS. The PLIC multiplexes external interrupt signals into + a single interrupt signal that is connected to an external interrupt of the + processor. + + The major features provided by the driver are: + - Support for configuring the PLIC instances. + - Enabling and Disabling interrupts + - Interrupt Handling + + This driver can be used as part of a bare metal system where no operating + system is available. The driver can be adapted for use as part of an + operating system, but the implementation of the adaptation layer between the + driver and the operating system's driver model is outside the scope of this + driver. + + ============================================================================== + Hardware Flow Dependencies + ============================================================================== + The application software should initialize the Mi-V PLIC through the call to + the MIV_PLIC_init() function for Mi-V PLIC instance in the design. + + No Mi-V PLIC hardware configuration parameters are used by the driver, apart + from the Mi-V PLIC base address. Hence, no additional configuration files + are required to use the driver. + + ============================================================================== + Theory of Operation + ============================================================================== + The operation of Mi-V PLIC driver is divided into following steps: + - Initialization + - Enabling and Disabling interrupts + - Interrupt control + + -------------------------------------------- + Initialization + -------------------------------------------- + The Mi-V PLIC module is first initialized by the call to MIV_PLIC_init(). This + function takes a pointer to the Mi-V PLIC instance data structure and the base + address of the Mi-V PLIC instance is defined by the hardware design. The + instance data structure is used to store the base address of the Mi-V PLIC + module and a pointer to the Mi-V PLIC register data structure. The Mi-V PLIC + register data structure maps the address of the Mi-V PLIC registers. + + --------------------------------------------- + Enabling and Disabling interrupts + --------------------------------------------- + The MIV_PLIC_enable_irq() function enables the specific interrupt provided by + user. A call to this function will allow the enabling of each of the global + interrupts corresponding to the bit in the interrupt enable register of Mi-V + PLIC. + The MIV_PLIC_disable_irq() function disables the specific interrupt provided + by the user. This function can be used to disable the interrupts from outside + of the external interrupt handler. + + ---------------------------------------- + Interrupt Control + ---------------------------------------- + When an interrupt occurs on an enabled interrupt, the PLIC gateway captures + the interrupt and asserts the corresponding interrupt pending bit. Once + the enable bit and pending bit are asserted, then the PLIC_IRQ signal asserts + until the interrupt is claimed by the driver interrupt handler MIV_PLIC_irq() + function. + When multiple interrupts assert then the lowest interrupt number will be + serviced first, for example, if interrupt 1 and 6 assert at the same time, + interrupt 1 will be serviced first, followed by interrupt 6. + +*/ +#include +#include "miv_plic_regs.h" + +#ifndef LEGACY_DIR_STRUCTURE +#include "hal/hal.h" +#include "miv_rv32_hal/miv_rv32_hal.h" +#else +#include "hal.h" +#include "miv_rv32_hal.h" +#endif + +/*-------------------------------------------------------------------------*//** + This enumeration is used to select a specific Mi-V PLIC interrupt. It is + used as a parameter to enable or disable the interrupt. +*/ +typedef enum miv_plic_irq_num +{ + NoInterrupt_IRQn = 0, + MIV_PLIC_EXT0_IRQn = 1, + MIV_PLIC_EXT1_IRQn = 2, + MIV_PLIC_EXT2_IRQn = 3, + MIV_PLIC_EXT3_IRQn = 4, + MIV_PLIC_EXT4_IRQn = 5, + MIV_PLIC_EXT5_IRQn = 6, + MIV_PLIC_EXT6_IRQn = 7, + MIV_PLIC_EXT7_IRQn = 8, + MIV_PLIC_EXT8_IRQn = 9, + MIV_PLIC_EXT9_IRQn = 10, + MIV_PLIC_EXT10_IRQn = 11, + MIV_PLIC_EXT11_IRQn = 12, + MIV_PLIC_EXT12_IRQn = 13, + MIV_PLIC_EXT13_IRQn = 14, + MIV_PLIC_EXT14_IRQn = 15, + MIV_PLIC_EXT15_IRQn = 16, + MIV_PLIC_EXT16_IRQn = 17, + MIV_PLIC_EXT17_IRQn = 18, + MIV_PLIC_EXT18_IRQn = 19, + MIV_PLIC_EXT19_IRQn = 20, + MIV_PLIC_EXT20_IRQn = 21, + MIV_PLIC_EXT21_IRQn = 22, + MIV_PLIC_EXT22_IRQn = 23, + MIV_PLIC_EXT23_IRQn = 24, + MIV_PLIC_EXT24_IRQn = 25, + MIV_PLIC_EXT25_IRQn = 26, + MIV_PLIC_EXT26_IRQn = 27, + MIV_PLIC_EXT27_IRQn = 28, + MIV_PLIC_EXT28_IRQn = 29, + MIV_PLIC_EXT29_IRQn = 30, + MIV_PLIC_EXT30_IRQn = 31 +} miv_plic_irq_num_t; + +/*--------------------------------------------------------------------------*//* + * This structure maps the priority threshold and claim complete register in + * the memory. + */ +typedef struct +{ + volatile uint32_t PRIORITY_THRESHOLD; + volatile uint32_t CLAIM_COMPLETE; + volatile uint32_t reserved[1022]; +} IRQ_Target_Type; + +/*--------------------------------------------------------------------------*//* + * This structure maps the Interrupt enable sources from 0 - 1023 for one + * context. + */ +typedef struct +{ + volatile uint32_t ENABLES[32]; +} Target_Enables_Type; + +/*-------------------------------------------------------------------------*//** + This structure holds the base address of the Mi-V PLIC module. This structure + is used by all the functions to access the Mi-V PLIC registers. +*/ +typedef struct miv_plic_instance +{ + addr_t base_addr; +} miv_plic_instance_t; + +/*-------------------------------------------------------------------------*//** + * The MIV_PLIC_isr is the top level interrupt handler function for the Mi-V PLIC + * driver. You must call the MIV_PLIC_isr() from the system level interrupt + * handler(External_IRQHandler). + * This function must be called from the external interrupt handler function + * provided by the processor hardware abstraction layer. In case of MIV_RV32 + * soft processor, it must be called from External_IRQHandler() function + * provided by MIV_RV32 HAL. + * + * The MIV_PLIC_isr() function claims the interrupt number + * that triggered the interrupt and then invokes the appropriate PLIC interrupt + * handler. + * After handling the PLIC interrupt, this function will complete the interrupt + * by clearing the claim complete bit for the particular interrupt source. + * + * @param this_plic + * A pointer to the miv_plic_instance_t data structure which + * will hold all the data related to the Mi-V PLIC instance + * being used. A pointer to this data structure is passed to + * rest of Mi-V PLIC driver functions for operation. + * + * @return + * This function does not return any value. + * + * Example: + * @code + * #define MIV_PLIC_BASE_ADDR 0x70000000 + * #define PLIC_EXT_INTR_SOURCES 31 + * + * miv_plic_instance_t g_plic; + * uint8_t MIV_PLIC_EXT0_IRQHandler(void) + * { + * *** ISR operation *** + * + * return(EXT_IRQ_KEEP_ENABLED); + * } + * + * void External_IRQHandler(void) + * { + * uint32_t reg_val = read_csr(mip); + * MIV_PLIC_isr(&g_plic); + * } + * + * void main(void) + * { + * MIV_PLIC_init(&g_plic, MIV_PLIC_BASE_ADDR, PLIC_EXT_INTR_SOURCES); + * + * MIV_PLIC_enable_irq(&g_plic, MIV_PLIC_EXT0_IRQn); + * MIV_PLIC_enable_irq(&g_plic, MIV_PLIC_EXT1_IRQn); + * MIV_PLIC_enable_irq(&g_plic, MIV_PLIC_EXT2_IRQn); + * MIV_PLIC_enable_irq(&g_plic, MIV_PLIC_EXT3_IRQn); + * } + * @endcode + */ +void MIV_PLIC_isr(miv_plic_instance_t *this_plic); + +/*-------------------------------------------------------------------------*//** + * The MIV_PLIC_init() function initializes the Mi-V PLIC instance with base + * address. This function resets the PLIC controller by disabling all the PLIC + * interrupts. + * + * Note: This function must be called before calling any other Mi-V PLIC driver + * function. + * + * @param this_plic + * A pointer to the miv_plic_instance_t data structure which + * will hold all the data related to the Mi-V PLIC instance + * being used. A pointer to this data structure is passed to + * rest of Mi-V PLIC driver functions for operation. + * + * @param base_addr + * Base address of the Mi-V PLIC instance in the MIV_ESS soft-IP. + * + * @param ext_intr_sources + * Number of interrupts initialized in the design. + * + * @return + * This function does not return any value. + * + * Example + * @code + * #define MIV_PLIC_BASE_ADDR 0x70000000 + * #define PLIC_EXT_INTR_SOURCES 31 + * + * miv_plic_instance_t g_plic; + * + * void main(void) + * { + * MIV_PLIC_init(&g_plic, MIV_PLIC_BASE_ADDR, PLIC_EXT_INTR_SOURCES); + * } + * @endcode + */ +static inline void +MIV_PLIC_init +( + miv_plic_instance_t *this_plic, + addr_t base_addr, + uint8_t ext_intr_sources +) +{ + uint32_t inc; + unsigned long hart_id = read_csr(mhartid); + + this_plic->base_addr = base_addr; + + /* Disable all interrupts for the current hart. + * The PLIC_EXT_INTR_SOURCES should be defined in the hw_platform.h. This + * macro holds the number of PLIC interrupts enabled in the design. + */ + for(inc = 0; inc < ((ext_intr_sources + 32u) / 32u); ++inc) + { + HAL_set_32bit_reg( + (this_plic->base_addr + inc + (hart_id * 128)), INT_ENABLE , 0x0u); + } +} + +/*-------------------------------------------------------------------------*//** + * The MIV_PLIC_enable_irq() function enables the PLIC interrupt provided with + * IRQn parameter. + * + * @param this_plic + * A pointer to the miv_plic_instance_t data structure which + * will hold all the data related to the Mi-V PLIC instance + * being used. A pointer to this data structure is passed to + * rest of Mi-V PLIC driver functions for operation. + * @param IRQn + * Number of PLIC interrupt to enable. + * + * @return + * This function does not return any value. + * + * Example + * @code + * #define MIV_PLIC_BASE_ADDR 0x70000000 + * #define PLIC_EXT_INTR_SOURCES 31 + * + * miv_plic_instance_t g_plic; + * + * void main(void) + * { + * MIV_PLIC_init(&g_plic, MIV_PLIC_BASE_ADDR, PLIC_EXT_INTR_SOURCES); + * + * MIV_PLIC_enable_irq(&g_plic, MIV_PLIC_EXT0_IRQn); + * MIV_PLIC_enable_irq(&g_plic, MIV_PLIC_EXT1_IRQn); + * MIV_PLIC_enable_irq(&g_plic, MIV_PLIC_EXT2_IRQn); + * MIV_PLIC_enable_irq(&g_plic, MIV_PLIC_EXT3_IRQn); + * } + * @endcode + */ +static inline void +MIV_PLIC_enable_irq +( + miv_plic_instance_t *this_plic, + miv_plic_irq_num_t IRQn +) +{ + unsigned long hart_id = read_csr(mhartid); + + uint32_t current = HAL_get_32bit_reg( + (this_plic->base_addr + (IRQn/32) + (hart_id * 128)) , INT_ENABLE); + + current |= (uint32_t)1 << (IRQn % 32); + + HAL_set_32bit_reg( + (this_plic->base_addr + (IRQn/32) + (hart_id * 128)), INT_ENABLE, current); + +} + +/*-------------------------------------------------------------------------*//** + * The MIV_PLIC_disable_irq() function disables the PLIC interrupt provided with + * IRQn parameter. + * + * NOTE: + * This function can be used to disable the PLIC interrupt from outside the + * external interrupt handler functions. + * If you wish to disable the PLIC interrupt from the external interrupt handler, + * you should use the return value of EXT_IRQ_DISABLE. This will disable the + * selected PLIC interrupt from the Mi-V PLIC driver interrupt handler. + * + * @param this_plic + * A pointer to the miv_plic_instance_t data structure which + * will hold all the data related to the Mi-V PLIC instance + * being used. A pointer to this data structure is passed to + * rest of Mi-V PLIC driver functions for operation. + * @param IRQn + * Number of PLIC interrupt to disable. + * + * @return + * This function does not return any value. + * + * Example + * @code + * #define MIV_PLIC_BASE_ADDR 0x70000000 + * #define PLIC_EXT_INTR_SOURCES 31 + * + * miv_plic_instance_t g_plic; + * + * void main(void) + * { + * MIV_PLIC_init(&g_plic, MIV_PLIC_BASE_ADDR, PLIC_EXT_INTR_SOURCES); + * + * MIV_PLIC_enable_irq(&g_plic, MIV_PLIC_EXT0_IRQn); + * MIV_PLIC_enable_irq(&g_plic, MIV_PLIC_EXT1_IRQn); + * MIV_PLIC_enable_irq(&g_plic, MIV_PLIC_EXT2_IRQn); + * MIV_PLIC_enable_irq(&g_plic, MIV_PLIC_EXT3_IRQn); + * + * MIV_PLIC_disable_irq(&g_plic, MIV_PLIC_EXT0_IRQn); + * MIV_PLIC_disable_irq(&g_plic, MIV_PLIC_EXT1_IRQn); + * MIV_PLIC_disable_irq(&g_plic, MIV_PLIC_EXT2_IRQn); + * MIV_PLIC_disable_irq(&g_plic, MIV_PLIC_EXT3_IRQn); + * } + * @endcode + */ +static inline void +MIV_PLIC_disable_irq +( + miv_plic_instance_t *this_plic, + miv_plic_irq_num_t IRQn +) +{ + unsigned long hart_id = read_csr(mhartid); + + uint32_t current = HAL_get_32bit_reg((this_plic->base_addr + (IRQn/32) + (hart_id * 128)) , INT_ENABLE); + + current &= ~((uint32_t)1 << (IRQn % 32)); + + HAL_set_32bit_reg((this_plic->base_addr + (IRQn/32) + (hart_id * 128)), INT_ENABLE, current); + +} diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_plic/miv_plic_regs.h b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_plic/miv_plic_regs.h new file mode 100644 index 0000000..d2fc15f --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_plic/miv_plic_regs.h @@ -0,0 +1,27 @@ + /******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * This file contains Register bit offsets and masks definitions for MI-V Soft + * IP PLIC module driver. This module is delivered as a part of Mi-V extended + * Sub-System(ESS). + */ + +#ifndef ESS_PLIC_REGISTERS +#define ESS_PLIC_REGISTERS 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/* Interrupt pending register offset */ +#define INT_PENDING_REG_OFFSET 0x1000u + +/* Interrupt enable register */ +#define INT_ENABLE_REG_OFFSET 0x2000u + +/* Interrupt claim complete register */ +#define INT_CLAIM_COMPLETE_REG_OFFSET 0x200004u + +#endif /* ESS_PLIC_REGISTERS */ diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_timer/miv_timer.h b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_timer/miv_timer.h new file mode 100644 index 0000000..66e8f24 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_timer/miv_timer.h @@ -0,0 +1,327 @@ +/******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * Mi-V Timer Soft IP bare-metal driver. This module is delivered as part of + * the Mi-V Extended Sub System(ESS) MIV_ESS. + */ + +/*=========================================================================*//** + @mainpage Mi-V Timer Bare Metal Driver. + The Mi-V Timer bare metal software driver supports the timer module which + serves as a system timer for the Mi-V Extended Sub System(ESS). + + @section intro_sec Introduction + The MI-V Timer driver supports set of functions for controlling the Mi-V + Timer module. + The Mi-V Timer can generate a timer interrupt signal for the system based on + special system clock intervals specified by the parameters that can be passed + in by the user. + + The major features provided by Mi-V Timer driver are: + - Support for Mi-V Timer instance for each Mi-V Timer peripheral. + - Read current time + - Write to the machine time compare register + + @section hw_dependencies Hardware Flow dependency + The application should configure the Mi-V Timer driver through calls to + MIV_TIMER_init() functions for each MIV_TIMER instance in the hardware + design. The configuration parameter include the MIV_TIMER hardware instance, + base address and number of ticks to generate timer interrupt. + + MIV_RV32 core offers flexibility in terms of generating the MTIME and MTIMECMP + registers internal to the core or using external time reference. + When MIV_ESS is interfaced with MIV_RV32 core, the timer module in the MIV_ESS + can be configured as follows: + - Internal MTIME External MTIME IRQ + Generate the MTIME internally(MIV_RV32) and have a timer interrupt input + to the core as external pin(from MIV_ESS). + + - External MTIME Internal MTIME IRQ + Generate the time value externally(from MIV_ESS), in this case a 64-bit + port will open in the MIV_RV32 core as input and MIV_ESS will output the + 64-bit TIME_COUNT value. The generation of mtimecmp and interrupt is + done internally(MIV_RV32). + + - External MTIME External MTIME IRQ + Generate both the time and timer interrupt externally. + In this case 64-bit port will be available on the Mi-V RV32 core as input + and a 1 pin port will be available for timer interrupt. + + The design must be configured accordingly to use these combinations in the + firmware. + + No MIV_TIMER hardware configuration parameters are used by the driver, apart + from MIV_TIMER base address. Hence, no additional configuration files are + required to use the driver. + + @section theory_op Theory of Operation + + The MIV_TIMER module is a simple systick timer which can generate a timer + interrupt signal for the system at specific intervals specified by the + parameters that can be passed by the user. + These interrupt signal are then fed to the MIV_RV32 core via timer interrupt. + + The operation of MIV_TIMER is divided into following steps: + - Initialization + - Configuration + - Read/Write TIME + + ## Initialization + The MIV_TIMER is first initialized by a call to MIV_TIMER_init(). This + function initializes the instance of Mi-V TIMER with the base address. + The MIV_TIMER_init() function must be called before any other Mi-V Timer driver + function. + + ## Configuration + The Mi-V TIMER configuration includes writing the mtimecmp register with the + initial time value at which timer interrupt should be generated. + When the mtime register value becomes greater than or equal to mtimecmp value, + a timer interrupt signal(TIMER_IRQ) is generated. + + ## Read/Write TIME + The time value can be read by reading the mtime register via call to the + MIV_TIMER_read_mtime(). This function reads the MTIME register which contains + the 64-bit value of the timer count. The count increments by 1 every time the + prescale ticks. This function returns 64-bit MTIME_COUNT value which is the + current value of timer count. + + The time value read in the MIV_TIMER_read_mtime() function can be written to + the mtimecmp register by calling MIV_TIMER_write_mtimecmp() to generate + periodic interrupts. + The writing of the mtimecmp register should be done in the systick_handler() + function. + */ + +#ifndef MIV_TIMER_H_ +#define MIV_TIMER_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef LEGACY_DIR_STRUCTURE +#include "hal/hal.h" +#include "miv_rv32_hal/miv_rv32_hal.h" + +#else +#include "hal.h" +#include "miv_rv32_hal.h" +#endif +/*-------------------------------------------------------------------------*//** +MIV_TIMER_SUCCESS +===================== + +The MIV_TIMER_SUCCESS constant indicates successful configuration of +Mi-V Timer module. +*/ +#define MIV_TIMER_SUCCESS 0u + +/*-------------------------------------------------------------------------*//** +MIV_TIMER_ERROR +===================== + +The MIV_TIMER_ERROR constant indicates that there is an error with +configuring the Mi-V Timer module. +*/ +#define MIV_TIMER_ERROR 1u + +/*-------------------------------------------------------------------------*//* +MASK_32BIT +===================== + +32-bit mask constant used in calculation of 64-bit register value. +*/ +#define MASK_32BIT 0xFFFFFFFFu + +/*-------------------------------------------------------------------------*//* +Mi-V Timer register offsets +===================== +The MTIMECMP is the 64-bit timer compare register, it pre-sets the threshold +which needs to be reached by the timer count register. +This 64-bit register is accessed with 2 32-bit address offset, lower 32-bits +and higher 32-bits. + - MTIMECMP_L_REG_OFFSET + - MTIMECMP_H_REG_OFFSET + +The MTIME is the 64-bit register that contains the 64-bit timer count. The +count increments by 1 every time the prescaler ticks. +This 64-bit register is accessed with 2 32-bit address offset, lower 32-bits +and higher 32-bits. + - MTIME_L_REG_OFFSET + - MTIME_H_REG_OFFSET + +The PRESCALE register is used to determine the amount of clock cycles the +selected clock needs to go through, for MTIME register to increment count. + - PRESCALAR_REG_OFFSET +*/ + +/// @cond private +#define MTIMECMP_L_REG_OFFSET 0x4000u +#define MTIMECMP_H_REG_OFFSET 0x4004u + +#define MTIME_L_REG_OFFSET 0xBFF8u +#define MTIME_H_REG_OFFSET 0xBFFCu + +#define PRESCALAR_REG_OFFSET 0x5000u +/// @endcond + +/*-------------------------------------------------------------------------*//** + This structure holds the base address of the Mi-V Timer module and instance + of the Mi-V Timer register structure. +*/ +typedef struct miv_timer_instance +{ + addr_t base_addr; +} miv_timer_instance_t; + +/** The MIV_TIMER_init() is used to initialize the Mi-V Timer module. This + function will assign the base addresses of the Mi-V Timer module. + User should call this function before calling any of the Mi-V Timer driver + APIs. + + @param this_timer + Timer structure which holds the base address for the Mi-V Timer hardware + instance. + + @param base_address + Base address of the Mi-V Timer module. + + @return + This function does not return any value. + */ +static inline void +MIV_TIMER_init +( + miv_timer_instance_t* this_timer, + addr_t base_addr +) +{ + this_timer->base_addr = base_addr; +} + +/** MIV_TIMER_read_current_time() is used to read the mtimecmp register values. + + @param this_timer + Timer structure which holds the base address for the Mi-V Timer hardware + instance. + + @return + This function returns 64-bit mtimecmp register value. + */ +static inline uint64_t +MIV_TIMER_read_current_time +( + miv_timer_instance_t* this_timer +) +{ + volatile uint64_t read_data = 0u; + volatile uint32_t mtime_hi = 0u; + volatile uint32_t mtime_lo = 0u; + + /* when mtime lower word is 0xFFFFFFFF, there will be rollover and + * returned value could be wrong. */ + do { + mtime_hi = HAL_get_32bit_reg(this_timer->base_addr, MTIME_H); + mtime_lo = HAL_get_32bit_reg(this_timer->base_addr, MTIME_L); + + } while(mtime_hi != HAL_get_32bit_reg(this_timer->base_addr, MTIME_H)); + + read_data = mtime_hi; + + return(((read_data) << 32u) | mtime_lo); +} + +/** MIV_TIMER_write_compare_time() is used to write to the MTIMECMP register in + the event of interrupt. User must use this function in the interrupt handler + to de-assert the MIV_TIMER interrupt. + + @param this_timer + Timer structure which holds the base address for the Mi-V Timer hardware + instance. + + @param write_value + Value to write into the mtimecmp register. + + @return + This function does not return any value. + */ +static inline void +MIV_TIMER_write_compare_time +( + miv_timer_instance_t* this_timer, + uint64_t compare_reg_value +) +{ + HAL_set_32bit_reg(this_timer->base_addr, MTIMECMP_H, MASK_32BIT); + + HAL_set_32bit_reg(this_timer->base_addr, MTIMECMP_L, + (compare_reg_value & MASK_32BIT)); + + HAL_set_32bit_reg(this_timer->base_addr, MTIMECMP_H, + ((compare_reg_value >> 32u) & MASK_32BIT)); +} + +/** The MIV_TIMER_config() is used to configure the MIV_ESS Timer module. The + prescale value serves to divide the count of clock cycles for the timer and + provides control over what point in time, the timer interrupt gets + asserted. + + @param this_timer + Timer structure which holds the base address for the Mi-V Timer hardware + instance. + + @param ticks + Number of ticks after which interrupt will be generated. + + @return + This function returns Mi-V Timer configuration status. + */ +static inline uint32_t +MIV_TIMER_config +( + miv_timer_instance_t* this_timer, + uint64_t ticks +) +{ + uint32_t ret_val = MIV_TIMER_ERROR; + uint64_t mtime_val = 0u; + uint32_t prescalar = 0u; + uint64_t miv_timer_increment = 0U; + + prescalar = HAL_get_32bit_reg(this_timer->base_addr, PRESCALAR); + + miv_timer_increment = (uint64_t)(ticks) / prescalar; + + if (miv_timer_increment > 0U) + { + mtime_val = MIV_TIMER_read_current_time(this_timer); + + MIV_TIMER_write_compare_time(this_timer ,(mtime_val + miv_timer_increment)); + + ret_val = MIV_TIMER_SUCCESS; + } + + return ret_val; +} + +#endif /* MIV_TIMER_H */ diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_udma/miv_udma.c b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_udma/miv_udma.c new file mode 100644 index 0000000..d57f2ae --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_udma/miv_udma.c @@ -0,0 +1,107 @@ +/******************************************************************************* + * (c) Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * Mi-V uDMA Soft IP bare-metal driver. This module is delivered as part of + * Mi-V Extended Sub System(MIV_ESS) + */ + +#include "miv_udma_regs.h" +#include "miv_udma.h" + +/***************************************************************************//** + * MIV_uDMA_init() + * See "miv_udma.h" for details of how to use this function. + */ +void +MIV_uDMA_init +( + miv_udma_instance_t* this_udma, + addr_t base_addr +) +{ + /* Assign the Mi-V uDMA base address to the uDMA instance structure */ + this_udma->base_address = base_addr; +} + +/***************************************************************************//** + * MIV_uDMA_config() + * See "miv_udma.h" for details of how to use this function. + */ +void +MIV_uDMA_config +( + miv_udma_instance_t* this_udma, + addr_t src_addr, + addr_t dest_addr, + uint32_t transfer_size, + uint32_t irq_config +) +{ + /* Source memory start address */ + HAL_set_32bit_reg(this_udma->base_address, SRC_START_ADDR, src_addr); + + /* Destination memory start address */ + HAL_set_32bit_reg(this_udma->base_address, DEST_START_ADDR, dest_addr); + + /* Data transfer size */ + HAL_set_32bit_reg(this_udma->base_address, BLK_SIZE, transfer_size); + + /* Configure the uDMA IRQ */ + HAL_set_32bit_reg(this_udma->base_address, IRQ_CFG, irq_config); +} + +/***************************************************************************//** + * MIV_uDMA_start() + * See "miv_udma.h" for details of how to use this function. + */ +void +MIV_uDMA_start +( + miv_udma_instance_t* this_udma +) +{ + /* Start the uDMA transfer */ + HAL_set_32bit_reg(this_udma->base_address, CONTROL_SR, CTRL_START_TX_MASK); +} + +/***************************************************************************//** + * MIV_uDMA_reset() + * See "miv_udma.h" for details of how to use this function. + */ +void +MIV_uDMA_reset +( + miv_udma_instance_t* this_udma +) +{ + /* Toggle the uDMA_reset bit to reset the uDMA. + * Resetting the uDMA will clear all the configuration made by + * MIV_uDMA_config(). + * + * This function should be called from the interrupt handler to clear the + * IRQ. + */ + HAL_set_32bit_reg_field(this_udma->base_address, CTRL_RESET_TX, 0x1u); + HAL_set_32bit_reg_field(this_udma->base_address, CTRL_RESET_TX, 0x0u); +} + +/***************************************************************************//** + * MIV_uDMA_read_status() + * See "miv_udma.h" for details of how to use this function. + */ +uint32_t +MIV_uDMA_read_status +( + miv_udma_instance_t* this_udma +) +{ + uint32_t status = 0u; + + /* Read the status of the uDMA transfer. + * The transfer status register can be Error or Busy depending on the + * current uDMA transfer. + */ + status = HAL_get_32bit_reg(this_udma->base_address, TX_STATUS); + + return status; +} diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_udma/miv_udma.h b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_udma/miv_udma.h new file mode 100644 index 0000000..e3ad5da --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_udma/miv_udma.h @@ -0,0 +1,285 @@ +/******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * This file contains the application programming interface for the MI-V Soft IP + * uDMA module driver. This module is delivered as a part of Mi-V Extended + * Sub-System(MIV_ESS). + */ + +/*=========================================================================*//** + @mainpage Mi-V uDMA Bare Metal Driver. + The Mi-V uDMA bare metal software driver. + + @section intro_sec Introduction + The Mi-V uDMA driver provides a set of functions to control the Mi-V uDMA + module in the Mi-V Extended Sub System(MIV_ESS) soft-IP. The Mi-V uDMA module + allows peripherals with AHB interfaces to transfer data independently of the + MIV_RV32 RISC-V processor. + + The major features provided by the Mi-V uDMA driver are: + - Initialization and configuration + - Start and reset the transaction + + This driver can be used as part of a bare metal system where no operating + system is available. The driver can be adapted for use as part of an + operating system, but the implementation of the adaptation layer between the + driver and the operating system's driver model is outside the scope of this + driver. + + @section hw_dependencies Hardware Flow Dependency + The application software should initialize and configure the Mi-V uDMA through + the call to MIV_uDMA_init(), MIV_uDMA_config() function for Mi-V uDMA + instance in the design. + The μDMA can operate in two possible transfer configurations: + + AHBL Read –> AHBL Write: + In this configuration, the μDMA reads data from the source memory over an + AHBL (Mirrored Main/Initiator) read interface and writes data to the + destination memory over an AHBL (Mirrored Main/Initiator) write interface. + + AHBL Read –> TAS Write: + In this configuration, the μDMA reads data from the source memory over an + AHBL (Mirrored Main/Initiator) read interface and writes data to the + destination memory over the TAS (Mirrored Main/Initiator) write interface. + + The AHBL Read -> TAS Write configuration is out of scope for this driver. + + @section theory_op Theory of Operation + The uDMA module in the Mi-V Extended Sub System(MIV_ESS) is a single channel + uDMA module that allows peripherals to perform read write operations between + source and destination memory. The Mi-V uDMA driver is generally used in + interrupt driven mode and uses the Mi-V uDMA IRQ signal to drive the + interrupt service routine(ISR) which signifies a transfer has completed. + The status is checked in the ISR to ensure the transfer is completed + successfully. + The reset operation in the ISR will reset the Mi-V uDMA controller. + Once the Mi-V uDMA transfer completes, Mi-V uDMA retires. To + initiate another transaction, Mi-V uDMA will have to be configured again. + + The operation of the Mi-V uDMA driver can be divided into following + categories: + - Initialization + - Configuration + - Start and reset transfer + + ### Initialization and configuration + Mi-V uDMA is first initialized by a call to MIV_uDMA_init(). This function + initializes the instance of Mi-V uDMA with base address. The MIV_uDMA_init() + function must be called before calling any other Mi-V uDMA driver functions. + + The Mi-V uDMA is configured by a call to MIV_uDMA_config(). This function + will configure the source_addr and dest_addr registers of the Mi-V uDMA with + source and destination addresses for Mi-V uDMA transfers. + This function also configures the transfer size and interrupt preference for + successful transfer of Mi-V uDMA. + + ### Start and Reset transfer + Once the Mi-V uDMA is configured, the transfers can be started with a call to + MIV_uDMA_start(). Once the Mi-V uDMA transfer is started, it can not be + aborted and the status of the transfer should be read from the ISR by a call + to MIV_uDMA_read_status(). + + The Mi-V uDMA can be reset to the default state by calling MIV_uDMA_reset() + function. After performing reset operation, the Mi-V uDMA should be + re-configured to perform transfer since MIV_uDMA_reset() resets the Mi-V uDMA + controller. + */ + +#ifndef MIV_uDMA_H_ +#define MIV_uDMA_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef LEGACY_DIR_STRUCTURE +#include "hal/hal.h" +#include "hal/cpu_types.h" + +#else +#include "hal.h" +#include "cpu_types.h" +#endif + +/*-------------------------------------------------------------------------*//** + MIV_uDMA_CTRL_IRQ_CONFIG + ===================== + + The MIV_uDMA_CTRL_IRQ_CONFIG macro is used to assert the uDMA IRQ when an error + occurs during a uDMA transfer or on the completion of a uDMA transfer. + */ +#define MIV_uDMA_CTRL_IRQ_CONFIG 1u + +/*-------------------------------------------------------------------------*//** + MIV_uDMA_STATUS_BUSY + ===================== + + The MIV_uDMA_STATUS_BUSY macro is used to indicate that the uDMA transfer is + in progress. + */ +#define MIV_uDMA_STATUS_BUSY 1u + +/*-------------------------------------------------------------------------*//** + MIV_uDMA_STATUS_ERROR + ===================== + + The MIV_uDMA_STATUS_ERROR macro is used to indicate that the last uDMA + transfer has caused an error. + */ +#define MIV_uDMA_STATUS_ERROR 2u + +/***************************************************************************//** + * Mi-V uDMA instant structure. + * This structure will hold the base of Mi-V uDMA module which is used in the + * other functions in the driver to access the uDMA registers. + */ +typedef struct miv_udma_instance +{ + addr_t base_address; +} miv_udma_instance_t; + +/***************************************************************************//** + * The MIV_uDMA_init() assigns the base address of Mi-V uDMA module to the + * uDMA instance structure. + * This address is used in later part of the driver to access the uDMA registers. + * + * @param this_udma + * This parameter is a pointer to the miv_udma_instance_t structure. + * + * @param base_addr + * Base address of the Mi-V uDMA module. + * + * @return + * This function does not return a value. + */ +void +MIV_uDMA_init +( + miv_udma_instance_t* this_udma, + addr_t base_addr +); + +/***************************************************************************//** + * The MIV_uDMA_config() is used to configure the Mi-V uDMA controller. + * This function will set the source address, destination address, block size + * and IRQ config register. + * + * @param this_udma + * This parameter is a pointer to the miv_udma_instance_t structure which + * holds the base address of Mi-V uDMA module. + * + * @param base_addr + * Base address of the Mi-V uDMA + * + * @param src_addr + * Source address of memory from which the uDMA will read the data. + * + * @param dest_addr + * Destination address where the data will be written from src_addr. + * + * @param transfer_size + * Number of 32-bit words to transfer + * + * @param irq_config + * uDMA IRQ Configuration. + * + * When set, the IRQ is asserted when and error occurs during a uDMA + * transfer or on the completion of the uDMA transfer. + * + * When clear, the IRQ is only asserted when an error occurs during a uDMA + * transfer. + * + * @return + * This function does not return any value. + */ +void +MIV_uDMA_config +( + miv_udma_instance_t* this_udma, + addr_t src_addr, + addr_t dest_addr, + uint32_t transfer_size, + uint32_t irq_config +); + +/***************************************************************************//** + * The MIV_uDMA_start() is used to start the uDMA transfer. + * + * @param this_udma + * This parameter is a pointer to the miv_udma_instance_t structure which + * holds the base address of Mi-V uDMA module. + * + * @return + * This function does not return any value. + */ +void +MIV_uDMA_start +( + miv_udma_instance_t* this_udma +); + +/***************************************************************************//** + * The MIV_uDMA_reset() is used to clear the uDMA interrupt and reset the uDMA + * transfer. + * + * This function should be called from interrupt handler and it will reset the + * values set during MIV_uDMA_config(). + * + * @param this_udma + * This parameter is a pointer to the miv_udma_instance_t structure which + * holds the base address of Mi-V uDMA module. + * + * @return + * This function does not return any value. + */ +void +MIV_uDMA_reset +( + miv_udma_instance_t* this_udma +); + +/***************************************************************************//** + * The MIV_uDMA_read_status() will be used to status of the uDMA transfer. When + * Interrupt is enabled this function can be called from the interrupt handler + * to know the reason of uDMA interrupt. + * + * @param this_udma + * This parameter is a pointer to the miv_udma_instance_t structure which + * holds the base address of Mi-V uDMA module. + * + * @return + * Return value will indicate error of busy status of the uDMA channel. + * + * |Bit Number| Name | Description | + * |----------|---------|------------------------------------------------------| + * | 0 | Busy | When set indicates that uDMA transfer is in progress| + * | 1 | Error | When set indicates that last uDMA transfer caused an| + * | | | error. | + */ +uint32_t +MIV_uDMA_read_status +( + miv_udma_instance_t* this_pdma +); + +#endif /* MIV_uDMA_H_ */ diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_udma/miv_udma_regs.h b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_udma/miv_udma_regs.h new file mode 100644 index 0000000..359055e --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_udma/miv_udma_regs.h @@ -0,0 +1,91 @@ + /******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * This file contains Register bit offsets and masks definitions for MI-V Soft + * IP uDMA module driver. This module is delivered as a part of Mi-V + * extended Sub-System(ESS) MIV_ESS. + */ + +#ifndef MIV_UDMA_APB_REGISTERS +#define MIV_UDMA_APB_REGISTERS 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/**************************************************************************//** + * Control start/Reset register details + */ + +#define CONTROL_SR_REG_OFFSET 0x0u + +/* Control start/Reset register bits */ +#define CONTROL_SR_OFFSET 0x00u +#define CONTROL_SR_MASK 0x03u +#define CONTROL_SR_SHIFT 0u + +/* uDMA Control Start Transfer */ + +#define CTRL_START_TX_OFFSET 0x00u +#define CTRL_START_TX_MASK 0x01u +#define CTRL_START_TX_SHIFT 0u + +/* uDMA Control Reset Transfer */ +#define CTRL_RESET_TX_OFFSET 0x00u +#define CTRL_RESET_TX_MASK 0x02u +#define CTRL_RESET_TX_SHIFT 1u + +/**************************************************************************//** + * IRQ Configuration register details + */ +#define IRQ_CFG_REG_OFFSET 0x4u + +/* Control start/Reset register bits */ +#define IRQ_CFG_OFFSET 0x04u +#define IRQ_CFG_MASK 0x01u +#define IRQ_CFG_SHIFT 0u + +/***************************************************************************//** + * Transfer Status register details + */ +#define TX_STATUS_REG_OFFSET 0x08u + +/* Transfer status register bits */ +#define TX_STATUS_OFFSET 0x08u +#define TX_STATUS_MASK 0x03u +#define TX_STATUS_SHIFT 0u + +/***************************************************************************//** + * Source Memory Start Address Register + */ +#define SRC_START_ADDR_REG_OFFSET 0x0cu + +/* Source Memory Start Address Register bits */ +#define SRC_START_ADDR_OFFSET 0x0cu +#define SRC_START_ADDR_MASK 0xFFFFFFFFu +#define SRC_START_ADDR_SHIFT 0u + +/***************************************************************************//** + * Destination Memory Start Address register details + */ +#define DEST_START_ADDR_REG_OFFSET 0x10u + +/* Destination Memory Start Address register bits */ +#define DEST_START_ADDR_OFFSET 0x10u +#define DEST_START_ADDR_MASK 0xFFFFFFFFu +#define DEST_START_ADDR_SHIFT 0x0u + +/***************************************************************************//** + * Block Size register details + */ +#define BLK_SIZE_REG_OFFSET 0x14u + +/* Destination Memory Start Address register bits */ +#define BLK_SIZE_OFFSET 0x14u +#define BLK_SIZE_MASK 0xFFFFFFFFu +#define BLK_SIZE_SHIFT 0x0u + + +#endif /* MIV_UDMA_APB_REGISTERS */ diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_watchdog/miv_watchdog.c b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_watchdog/miv_watchdog.c new file mode 100644 index 0000000..2aa8061 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_watchdog/miv_watchdog.c @@ -0,0 +1,101 @@ +/******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * Mi-V Watchdog Soft IP bare-metal driver. This module is delivered as part of + * Extended Sub System(ESS) MIV_ESS. + * Please refer to miv_watchdog.h file for more information. + */ + +#include "miv_watchdog.h" + +#ifdef __cplusplus +extern "C" { +#endif + +addr_t g_this_wdog; + +/***************************************************************************//* + * Please refer to miv_watchdog.h for more info about this function + */ +void +MIV_WDOG_init +( + addr_t base_addr +) +{ + /* Register the Mi-V Watchdog base address to the driver */ + g_this_wdog = base_addr; +} + +/***************************************************************************//* + * Please refer to miv_watchdog.h for more info about this function + */ +uint8_t MIV_WDOG_configure +( + const miv_wdog_config_t *config +) +{ + uint8_t error = 0u; + + /* check load value and trigger max value */ + if (config->timeout_val <= MIV_WDOG_TRIGGER_MAX) + { + HAL_set_32bit_reg(g_this_wdog, WDOGTRIG,(config->timeout_val)); + } + else + { + error = 1u; + } + + if (config->time_val <= MIV_WDOG_TIMER_MAX) + { + HAL_set_32bit_reg(g_this_wdog, WDOGMSVP,(config->mvrp_val)); + } + else + { + error = 1u; + } + + HAL_set_32bit_reg_field(g_this_wdog, WDOGCNTL_NEXT_ENFORBIDDEN, + config->forbidden_en); + + /* Reload watchdog with new load if it is not in forbidden window */ + if (!(WDOGSTAT_FORBIDDEN_MASK & (HAL_get_32bit_reg(g_this_wdog, WDOGSTAT)))) + { + HAL_set_32bit_reg(g_this_wdog, WDOGRFSH, MIV_WDOG_REFRESH_KEY); + } + else + { + error = 1u; + } + + return (error); +} + +/***************************************************************************//* + * Please refer to miv_watchdog.h for more info about this function + */ +void MIV_WDOG_get_config +( + miv_wdog_config_t *config +) +{ + if (0 != g_this_wdog) + { + + config->time_val = HAL_get_32bit_reg(g_this_wdog, WDOGTIME); + + config->timeout_val = HAL_get_32bit_reg(g_this_wdog, WDOGTRIG); + + config->mvrp_val = HAL_get_32bit_reg(g_this_wdog, WDOGMSVP); + + config->forbidden_en = HAL_get_32bit_reg_field(g_this_wdog, + WDOGCNTL_NEXT_ENFORBIDDEN); + } +} + +#ifdef __cplusplus +} +#endif diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_watchdog/miv_watchdog.h b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_watchdog/miv_watchdog.h new file mode 100644 index 0000000..8877e55 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_watchdog/miv_watchdog.h @@ -0,0 +1,553 @@ +/******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * This file contains the application programming interface for the MI-V Soft IP + * Watchdog module driver. This module is delivered as a part of Mi-V Extended + * Sub-System(MIV_ESS). + */ +/*=========================================================================*//** + @mainpage MiV Watchdog Bare Metal Driver + + ============================================================================== + Introduction + ============================================================================== + The Mi-V Watchdog module in the MIV_ESS is used to generate a reset for the + system automatically if the software doesn't periodically update or refresh + the timer countdown register. This software driver provides set of functions + for controlling Mi-V Watchdog module as a part of bare metal system where no + operating system is available. The driver can be adapted for use as a part of + an operating system, but the implementation of the adaptation layer between + the driver and the operating system's driver model is outside the scope of the + driver. + + Mi-V Watchdog provides following features: + - Initializing the Mi-V Watchdog + - Reading current value and status of watchdog timer + - Refreshing the watchdog timer value + - Enabling, disabling and clearing timeout and Maximum Value up to which + Refresh is Permitted (MVRP) interrupts. + + ============================================================================== + Hardware Flow Dependencies + ============================================================================== + The application software should initialize and configure the Mi-V Watchdog + module the the call to the MIV_WDOG_init() and MIV_WDOG_configure() functions. + + No MIV_WDOG hardware configuration parameter are used by the driver, apart + from the MIV_WDOG base address. Hence, no additional configuration files are + required to use the driver. + + ============================================================================== + Theory of Operation + ============================================================================== + The Mi-V Watchdog driver functions are grouped into the following categories: + - Initialization and configuration + - Reading the current value and status of the watchdog timer + - Refreshing the watchdog timer value + - Support for enabling, disabling and clearing time-out and MVRP interrupts. + + -------------------------------- + Initialization and Configuration + -------------------------------- + The MIV_WDOG_init() function stores the base of MIV_WDT module in the MIV_ESS. + This base address is used by rest of the functions to access the Mi-V Watchdog + registers. Please make call this function before calling any other function + from this driver. + Note: The Mi-V Watchdog driver supports only one instance of MIV_WDT in the + hardware. + The Mi-V Watchdog driver provides the MIV_WDOG_configure() function to + configure the MIV_WDOG module with desired configuration values. It also + provides the MIV_WDOG_get_config() to read back the current configuration of + the MIV_WDOG. You can use this function to retrieve the current configurations + and then overwrite them with the application specific values, such as initial + watchdog timer value, Maximum Value (up to which) Refresh (is) Permitted, + watchdog time-out value, enable/disable forbidden region, enable/disable + MVRP interrupt and interrupt type. + + -------------------------------------------- + Reading the Watchdog Timer Value and Status + -------------------------------------------- + Mi-V Watchdog is a down counter. A refresh forbidden window can be created by + configuring the watchdog Maximum Value up to which Refresh is Permitted (MVRP). + When the current value of the watchdog timer is greater than the MVRP value, + refreshing the watchdog is forbidden. Attempting to refresh the watchdog timer + in the forbidden window will assert a timeout interrupt. The + MIV_WDOG_forbidden_status() function can be used to know whether the watchdog + timer is in forbidden window or has crossed it. By default, the forbidden + window is disabled. It can be enabled by providing an appropriate value as + parameter to the MIV_WDOG_configure() function. When the forbidden window is + disabled, any attempt to refresh the watchdog timer is ignored and the counter + keeps on down counting. + + The current value of the watchdog timer can be read using the + MIV_WDOG_current_value() function. This function can be called at any time. + + -------------------------------------------- + Refreshing the Watchdog Timer Value + -------------------------------------------- + The watchdog timer value is refreshed using the MIV_WDOG_reload() function. + The value reloaded into the watchdog timer down-counter is specified at the + configuration time with an appropriate value as parameter to the + MIV_WDOG_get_config() function. + + -------------------------------------------- + Interrupt Control + -------------------------------------------- + The Mi-V Watchdog generates two interrupts, The MVRP interrupt and + the timeout interrupt. + The MVRP interrupt is generated when the watchdog down-counter crosses the + Maximum Value up to which Refresh is Permitted (MVRP). Following functions to + control MVRP interrupt: + - MIV_WDOG_enable_mvrp_irq + - MIV_WDOG_disable_mvrp_irq + - MIV_WDOG_clear_mvrp_irq + + The timeout interrupt is generated when the watchdog down-counter crosses the + watchdog timeout value. The timeout value is a non-zero value and it can be + set to a maximum of MIV_WDOG_TRIGGER_MAX. The non-maskable interrupt is + generated when the watchdog crosses this timeout value, the down counter + keeps on down counting and a reset signal is generated when reaches zero. + Following functions to control timeout interrupt: + - MIV_WDOG_enable_timeout_irq + - MIV_WDOG_disable_timeout_irq + - MIV_WDOG_clear_timeout_irq + +*//*=========================================================================*/ + +#ifndef MIV_WATCHDOG_H_ +#define MIV_WATCHDOG_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include "miv_watchdog_regs.h" + +#ifndef LEGACY_DIR_STRUCTURE +#include "hal/hal.h" +#else +#include "hal.h" +#endif + +/****************************************************************************//* + * The following constants can be used to configure the Mi-V Watchdog where a + * zero or non-zero value such as enable or disable is to be provided as a input + * parameter as shown below: + */ +#define MIV_WDOG_ENABLE 1u +#define MIV_WDOG_DISABLE 0u + +/***************************************************************************//** + The miv_wdog_config_t type for the watchdog Configuration structure. This + type is used as a parameter for the MIV_WDOG_configure() and the + MIV_WDOG_get_config() functions. + + Following are the values as part of this structure +| Parameter | Description | +|------------------|-----------------------------------------------------------| +| time_val | The value from which the watchdog timer counts down | +| mvrp_val | The Watchdog MVRP value | +| timeout_val | The watchdog timeout value | +| forbidden_en | Enable/disable the forbidden window | +| | When set, if a refresh occurs in the forbidden window, | +| | the watchdog timeout interrupt will be generated. | + +Time calculation example: + + time_val = 0xFFFFF0u + mvrp_val = 0x989680u + timeout_val = 0x3e8u + + A prescaler = 256 is used. + Considering clock = 50Mhz + + The MVRP interrupt will happen after + (0xFFFFF0 - 0x989680) * ( 1/(50MHz/256)) + mvrp interrupt will happen after 34 sec. after system reset + + (0xFFFFF0 - 0x3e8) * ( 1/(50MHz/256)) + timeout interrupt will happen after 85 sec. after system reset + */ +typedef struct miv_wdog_config +{ + uint32_t time_val; + uint32_t mvrp_val; + uint32_t timeout_val; + uint32_t forbidden_en; + uint32_t intr_type; +}miv_wdog_config_t; + +extern addr_t g_this_wdog; + +/***************************************************************************//* + Internal constants and types +*******************************************************************************/ + +/// @cond private +#define MIV_WDOG_TRIGGER_MAX 4095u +#define MIV_WDOG_TIMER_MAX 16777200u +/// @endcond + +/*-------------------------------------------------------------------------*//* +MIV_WDOG_REFRESH_KEY +===================== + +The MIV_WDOG_REFRESH_KEY macro holds the magic value which will cause a +reload of the watchdog's down counter when written to the watchdog's +WDOGREFRESH register. +*/ +#define MIV_WDOG_REFRESH_KEY (uint32_t)0xDEADC0DEU + +/*-------------------------------------------------------------------------*//* +MIV_WDOG_FORCE_RESET_KEY +===================== +The MIV_WDOG_FORCE_RESET_KEY macro holds the magic value which will force a +reset if the watchdog is already timeout. Writing any other value or writing +TRIGGER register at other times will trigger the watchdog NMI sequence +(i.e raise a timeout interrupt) + */ +#define MIV_WDOG_FORCE_RESET_KEY (uint32_t)0xDEADU + +/***************************************************************************//** + * The MIV_WDOG_init() is used to register the Mi-V Watchdog module base + * address to the driver. + * + * Note: User should call this function before calling any other Mi-V watchdog + * driver function. + * + * @param base_addr + * The base address of the Mi-V watchdog module. This address is used by + * rest of the watchdog driver functions to access the registers. + * + * @return + * This function does not return any value. + */ +void +MIV_WDOG_init +( + addr_t base_addr +); + +/***************************************************************************//** + * The MIV_WDOG_get_config() function returns the current configurations of the + * Mi-V Watchdog. The Mi-V Watchdog is pre-initialized by the flash + * bits at the design time. When used for the first time before calling the + * MIV_WDOG_configure() function, this function will return the default + * configurations as configured at the design time. + * + * @param config + * The config parameter is used to store the current configuration of the Mi-V + * Watchdog. + * + * Please see the description of miv_wdog_config_t for details. + * + * @return + * This function does not return any value. + * + * Example: + */ +void +MIV_WDOG_get_config +( + miv_wdog_config_t* config +); + +/***************************************************************************//** + * The MIV_WDOG_configure() function configures the watchdog module. The + * Watchdog module is pre-initialized by the flash bits at the design time to the + * default values. You can reconfigure the Watchdog module using + * MIV_WDOG_configure() function. + * + * Note that the MIV_WDOG_configure() function can be used only once, as it + * writes into the TIME register. After a write into the TIME register, the TIME, + * TRIGGER and MSVP register values are frozen and can't be altered again unless + * a system reset happens. + * + * Note also that the Mi-V Watchdog is not enabled at reset, calling this function + * will start the watchdog, it cannot then be disabled and must be refreshed + * periodically. + * + * @param config + * The config parameter is the input parameter in which the configurations to + * be applied to the watchdog module are provided by the application. + * Please see the description of miv_wdog_config_t for details. + * + * @return + * This function returns a zero value when executed successfully. A non-zero + * value is returned when the configuration values are out of bound. + * + * Example: + */ +uint8_t +MIV_WDOG_configure +( + const miv_wdog_config_t * config +); + +/***************************************************************************//** + * The MIV_WDOG_reload() function causes the watchdog to reload its down-counter + * timer with the load value configured through interrupt handler. This function + * must be called regularly to avoid a system reset or a watchdog interrupt. + * + * @param + * Void + * + * @return + * This function does not return a value. + */ +static inline void +MIV_WDOG_reload +( + void +) +{ + if (0 != g_this_wdog) + { + HAL_set_32bit_reg(g_this_wdog, WDOGRFSH, MIV_WDOG_REFRESH_KEY); + } +} + +/***************************************************************************//** + * The MIV_WDOG_current_value() function returns the current value of the + * watchdog's down-counter. + * + * @param + * Void + * + * @return + * This function returns the current value of the watchdog’s down-counter as + * a 32-bit unsigned integer. + */ +static inline uint32_t +MIV_WDOG_current_value +( + void +) +{ + return (HAL_get_32bit_reg(g_this_wdog, WDOGRFSH)); +} + +/***************************************************************************//** + * The MIV_WDOG_forbidden_status() function returns the refresh status of the + * Mi-V Watchdog. + * + * @param + * Void + * + * @return + * This function returns the refresh status of the watchdog. A value of 1 + * indicates that watchdog's down-counter is within the forbidden window and + * that a reload should not be done. A value of 0 indicates that the watchdog's + * down counter is within the permitted window and that a reload is allowed. + */ +static inline uint32_t +MIV_WDOG_forbidden_status +( + void +) +{ + return (HAL_get_32bit_reg_field(g_this_wdog, WDOGSTAT_FORBIDDEN)); +} + +/***************************************************************************//** + * The MIV_WDOG_enable_mvrp_irq() function enables the MVRP interrupt. + * This interrupt is asserted when the timer countdown register leaves the + * maximum value up to which refresh is permitted (MVRP) window. + * + * @param + * Void + * + * @return + * This function does not return a value. + * + * Example: + */ +static inline void +MIV_WDOG_enable_mvrp_irq +( + void +) +{ + + if (0 != g_this_wdog) + { + HAL_set_32bit_reg_field(g_this_wdog, WDOGCNTL_NEXT_INTENT_MSVP, 0x01u); + } +} + +/***************************************************************************//** + * The MIV_WDOG_disable_mvrp_irq() function disables the generation of the + * MVRP interrupt. + * + * @param + * Void + * + * @return + * This function does not return a value. + */ +static inline void +MIV_WDOG_disable_mvrp_irq +( + void +) +{ + if (0 != g_this_wdog) + { + HAL_set_32bit_reg_field(g_this_wdog, WDOGCNTL_NEXT_INTENT_MSVP, 0x0u); + } +} + +/***************************************************************************//** + * The MIV_WDOG_clear_timeout_irq() function clears the watchdog’s timeout + * interrupt which is connected to the MIV-RV32 interrupt. Calling + * MIV_WDOG_clear_timeout_irq() results in clearing the MIV-RV32 interrupt. + * Note: You must call the MIV_WDOG_clear_timeout_irq() function as part of your + * implementation of the interrupt handler in order to prevent the same + * interrupt event re-triggering a call to the timeout ISR. + * + * @param + * Void + * + * @return + * This function does not return any value. + * + */ +static inline void +MIV_WDOG_clear_timeout_irq +( + void +) +{ + if (0 != g_this_wdog) + { + HAL_set_32bit_reg_field(g_this_wdog, WDOGSTAT_WDOG_TRIPPED, 0x01u); + /* + * Perform a second write to ensure that the first write completed before + * returning from this function. This is to account for posted writes across + * the AHB matrix. The second write ensures that the first write has + * completed and that the interrupt line has been de-asserted by the time + * the function returns. Omitting the second write may result in a delay + * in the de-assertion of the interrupt line going to the RISC-V and a + * retriggering of the interrupt. + */ + HAL_set_32bit_reg_field(g_this_wdog, WDOGSTAT_WDOG_TRIPPED, 0x01u); + } +} + +/***************************************************************************//** + * The MIV_WDOG_clear_mvrp_irq() function clears the mvrp interrupt. + * + * Note: You must call the MIV_WDOG_clear_mvrp_irq() function as part of your + * implementation of the interrupt service routine (ISR) in order to + * prevent the same interrupt event re-triggering a call to the mvrp ISR. + * + * @param + * Void + * + * @return + * This function does not return a value. + */ +static inline void +MIV_WDOG_clear_mvrp_irq +( + void +) +{ + if (0 != g_this_wdog) + { + HAL_set_32bit_reg_field(g_this_wdog, WDOGSTAT_MSVP_TRIPPED, 0x01u); + /* + * Perform a second write to ensure that the first write completed before + * returning from this function. This is to account for posted writes across + * the AHB matrix. The second write ensures that the first write has + * completed and that the interrupt line has been de-asserted by the time + * the function returns. Omitting the second write may result in a delay + * in the de-assertion of the interrupt line going to the RISC-V and a + * re-triggering of the interrupt. + */ + HAL_set_32bit_reg_field(g_this_wdog, WDOGSTAT_MSVP_TRIPPED, 0x01u); + } +} + +/***************************************************************************//** + * The MIV_WDOG_timeout_occured() function reports the occurrence of a timeout + * event. + * + * @param + * Void + * + * @return + * A zero value indicates no watchdog timeout event occurred. A value of 1 + * indicates that a timeout event occurred. + */ +static inline uint32_t +MIV_WDOG_timeout_occured +( + void +) +{ + return (HAL_get_32bit_reg_field(g_this_wdog, WDOGSTAT_TRIGGERED)); +} + +/***************************************************************************//** + * The MIV_WDOG_force_reset() function is used to force an immediate reset + * if the watchdog has already triggered. Writing any value in this condition + * will result in watchdog timeout. + * The time out interrupt WDOG_IRQ will be set to high and watchdog timer + * countdown register updated with watchdog trigger timeout register value. + * If the Watchdog has timed out, a special 16-bit value needs to be written + * to the register to force a reset on CPU_RESETN, 0xDEAD + * Then the Watchdog countdown is reset/updated with the top Watchdog Runtime + * register value. + * + * @param + * Void + * + * @return + * This function does not return a value. + */ +static inline void +MIV_WDOG_force_reset +( + void +) +{ + if (WDOGSTAT_TRIGGERED_MASK == + HAL_get_32bit_reg_field(g_this_wdog, WDOGSTAT_TRIGGERED)) + + { + HAL_set_32bit_reg(g_this_wdog, WDOGFORCE, MIV_WDOG_FORCE_RESET_KEY); + } + + else + { + HAL_set_32bit_reg(g_this_wdog, WDOGFORCE, 0x0u); + } +} + +#ifdef __cplusplus +} +#endif + +#endif /* MIV_WATCHDOG_H_ */ diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_watchdog/miv_watchdog_regs.h b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_watchdog/miv_watchdog_regs.h new file mode 100644 index 0000000..2cc9441 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/fabric_ip/miv_watchdog/miv_watchdog_regs.h @@ -0,0 +1,114 @@ + /******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * This file contains Register bit offsets and masks definitions for MI-V Soft + * IP watchdog module driver. This module is delivered as a part of Mi-V + * extended Sub-System(ESS) MIV_ESS. + */ + +#ifndef MIV_WDOG_REGISTERS +#define MIV_WDOG_REGISTERS 1u + +/*------------------------------------------------------------------------------ + * Refresh register details + */ +#define WDOGRFSH_REG_OFFSET 0x00u + +/* Refresh register bits */ +#define WDOGRFSH_OFFSET 0x00u +#define WDOGRFSH_MASK 0xFFFFFFFFu +#define WDOGRFSH_SHIFT 0u + +/*------------------------------------------------------------------------------ + * Control register details + */ +#define WDOGCNTL_REG_OFFSET 0x04u + +/* Control register next intent msvp bit */ +#define WDOGCNTL_NEXT_INTENT_MSVP_OFFSET 0x04u +#define WDOGCNTL_NEXT_INTENT_MSVP_MASK 0x01u +#define WDOGCNTL_NEXT_INTENT_MSVP_SHIFT 0u + +/* Control register next intent wdog bit */ +#define WDOGCNTL_NEXT_INTENT_WDOG_OFFSET 0x04u +#define WDOGCNTL_NEXT_INTENT_WDOG_MASK 0x02u +#define WDOGCNTL_NEXT_INTENT_WDOG_SHIFT 1u + +/* Control register next enforbidden bit */ +#define WDOGCNTL_NEXT_ENFORBIDDEN_OFFSET 0x04u +#define WDOGCNTL_NEXT_ENFORBIDDEN_MASK 0x04u +#define WDOGCNTL_NEXT_ENFORBIDDEN_SHIFT 2u + +/*------------------------------------------------------------------------------ + * Watchdog status register + */ +#define WDOGSTAT_REG_OFFSET 0x08u + +/* msvp_tripped bit */ +#define WDOGSTAT_MSVP_TRIPPED_OFFSET 0x08u +#define WDOGSTAT_MSVP_TRIPPED_MASK 0x01u +#define WDOGSTAT_MSVP_TRIPPED_SHIFT 0u + +/* WDOG Tripped bit */ +#define WDOGSTAT_WDOG_TRIPPED_OFFSET 0x08u +#define WDOGSTAT_WDOG_TRIPPED_MASK 0x02u +#define WDOGSTAT_WDOG_TRIPPED_SHIFT 1u + +/* Forbidden bit */ +#define WDOGSTAT_FORBIDDEN_OFFSET 0x08u +#define WDOGSTAT_FORBIDDEN_MASK 0x04u +#define WDOGSTAT_FORBIDDEN_SHIFT 2u + +/* Triggered bit */ +#define WDOGSTAT_TRIGGERED_OFFSET 0x08u +#define WDOGSTAT_TRIGGERED_MASK 0x08u +#define WDOGSTAT_TRIGGERED_SHIFT 3u + +/* wdoglocked bit */ +#define WDOGSTAT_WDOGLOCKED_OFFSET 0x08u +#define WDOGSTAT_WDOGLOCKED_MASK 0x10u +#define WDOGSTAT_WDOGLOCKED_SHIFT 4u + +/*------------------------------------------------------------------------------ + * Watchdog runtime register + */ +#define WDOGTIME_REG_OFFSET 0x0Cu + +/* wdogmsvp bit */ +#define WDOGTIME_WDOGVALUE_OFFSET 0x0Cu +#define WDOGTIME_WDOGVALUE_MASK 0xFFFFFFu +#define WDOGTIME_WDOGVALUE_SHIFT 0u + +/*------------------------------------------------------------------------------ + * Watchdog MVRP register + */ +#define WDOGMSVP_REG_OFFSET 0x10u + +/* wdogmsvp bit */ +#define WDOGMSVP_OFFSET 0x10u +#define WDOGMSVP_MASK 0xFFFFFFu +#define WDOGMSVP_SHIFT 0u + +/*------------------------------------------------------------------------------ + * Watchdog Trigger Timeout register + */ +#define WDOGTRIG_REG_OFFSET 0x14u + +/* wdogmsvp bit */ +#define WDOGTRIG_WDOGRST_OFFSET 0x14u +#define WDOGTRIG_WDOGRST_MASK 0xFFFFFFu +#define WDOGTRIG_WDOGRST_SHIFT 0u + +/*------------------------------------------------------------------------------ + * Watchdog Force Reset register details + */ +#define WDOGFORCE_REG_OFFSET 0x18u + +/* Refresh register bits */ +#define WDOGFORCE_OFFSET 0x18u +#define WDOGFORCE_MASK 0xFFFFFFFFu +#define WDOGFORCE_SHIFT 0u + +#endif diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/off_chip/readme.md b/bootloaders/miv-rv32-bootloader/src/platform/drivers/off_chip/readme.md new file mode 100644 index 0000000..5581d1b --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/off_chip/readme.md @@ -0,0 +1,2 @@ +# readme + diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/off_chip/spi_flash/spi_flash.c b/bootloaders/miv-rv32-bootloader/src/platform/drivers/off_chip/spi_flash/spi_flash.c new file mode 100644 index 0000000..81f2c93 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/off_chip/spi_flash/spi_flash.c @@ -0,0 +1,572 @@ +/******************************************************************************* +* +* (c) Copyright 2013 Microsemi SoC Products Group. All rights reserved. +* +* Company: Microsemi Corporation +* +* File: spi_flash.c +* +* Description: +* +* Device driver for the on-board SPI flash for SmartFusion KITS Atmel AT25DF641 +* +* SVN $Revision: 8241 $ +* SVN $Date: 2016-02-15 11:21:27 +0000 (Mon, 15 Feb 2016) $ +* +*******************************************************************************/ + +#include + +#ifndef LEGACY_DIR_STRUCTURE +#include "hal/hal.h" + +#else +#include "hal.h" +#endif +#include "drivers/fabric_ip/CoreSPI/core_spi.h" +#include "spi_flash.h" + +#define READ_ARRAY_OPCODE 0x1B +#define DEVICE_ID_READ 0x9F + +#define WRITE_ENABLE_CMD 0x06 +#define WRITE_DISABLE_CMD 0x04 +#define PROGRAM_PAGE_CMD 0x02 +#define WRITE_STATUS1_OPCODE 0x01 +#define CHIP_ERASE_OPCODE 0x60 +#define ERASE_4K_BLOCK_OPCODE 0x20 +#define ERASE_32K_BLOCK_OPCODE 0x52 +#define ERASE_64K_BLOCK_OPCODE 0xD8 +#define READ_STATUS 0x05 +#define PROGRAM_RESUME_CMD 0xD0 +#define READ_SECTOR_PROTECT 0x3C + + +#define READY_BIT_MASK 0x01 +#define PROTECT_SECTOR_OPCODE 0x36 +#define UNPROTECT_SECTOR_OPCODE 0x39 + +#define DONT_CARE 0 + +#define NB_BYTES_PER_PAGE 256 + +#define BLOCK_ALIGN_MASK_4K 0xFFFFF000 +#define BLOCK_ALIGN_MASK_32K 0xFFFF8000 +#define BLOCK_ALIGN_MASK_64K 0xFFFF0000 + +/* + * Maximum bytes required for command including opcode, + * address and any dummy bytes. + */ + +#define ATMEL_MAX_CMD_BYTES 6 +#define ATMEL_MAX_WRITE_BYTES (ATMEL_MAX_CMD_BYTES + NB_BYTES_PER_PAGE) + +spi_instance_t g_flash_core_spi; + + +#define SPI_INSTANCE &g_flash_core_spi +#define SPI_SLAVE 0 + +#define SPI_TRANS_BLOCK SPI_transfer_block + +/* + * Our maximum write to the SPI FLASH device will be a 6 byte command + * and a full 256 byte page of data. We construct this here because the + * SPI block transfer only supports a single write buffer. To avoid the + * overhead of buffer copying you could use the driver SPI_transfer_block() + * as a template for writing a block transfer routine that allowed transfers + * from two separate buffers without deselecting the slave. + */ +static uint8_t flash_write_buffer[ATMEL_MAX_WRITE_BYTES]; + +static uint8_t wait_ready( void ); +static uint8_t wait_ready_erase( void ); + +/****************************************************************************** + *For more details please refer the spi_flash.h file + ******************************************************************************/ +spi_flash_status_t spi_flash_init( uint32_t base_addr ) +{ + /*-------------------------------------------------------------------------- + * Configure MSS_SPI. + */ + + SPI_init(SPI_INSTANCE, base_addr, 32); + SPI_configure_master_mode( SPI_INSTANCE ); + SPI_set_slave_select( SPI_INSTANCE, SPI_SLAVE ); + + return( SPI_FLASH_SUCCESS ); +} + +/****************************************************************************** + *For more details please refer the spi_flash.h file + ******************************************************************************/ +spi_flash_status_t +spi_flash_control_hw +( + spi_flash_control_hw_t operation, + uint32_t param1, + void * ptrParam +) +{ + uint8_t x; + switch(operation){ + case SPI_FLASH_READ_DEVICE_ID: + { + uint8_t read_device_id_cmd = DEVICE_ID_READ; + uint8_t read_buffer[3]; + struct device_Info *ptrDevInfo = (struct device_Info *)ptrParam; +//x=1; + +//while(x<0xff) +{ + //read_device_id_cmd = x; + SPI_TRANS_BLOCK( SPI_INSTANCE, + &read_device_id_cmd, + 1, + read_buffer, + sizeof(read_buffer) ); + x++; +} + + ptrDevInfo->manufacturer_id = read_buffer[0]; + ptrDevInfo->device_id = read_buffer[1]; + ptrDevInfo->mem_cap = read_buffer[2]; + + } + break; + case SPI_FLASH_SECTOR_PROTECT: + { + uint8_t cmd_buffer[4]; + uint32_t address = param1; + + /* Send Write Enable command */ + cmd_buffer[0] = WRITE_ENABLE_CMD; + if(wait_ready()) + return SPI_FLASH_UNSUCCESS; + SPI_TRANS_BLOCK( SPI_INSTANCE, cmd_buffer, 1, 0, 0 ); + /* protect sector */ + cmd_buffer[0] = PROTECT_SECTOR_OPCODE; + cmd_buffer[1] = (address >> 16) & 0xFF; + cmd_buffer[2] = (address >> 8 ) & 0xFF; + cmd_buffer[3] = address & 0xFF; + if(wait_ready()) + return SPI_FLASH_UNSUCCESS; + + SPI_TRANS_BLOCK( SPI_INSTANCE, + cmd_buffer, + sizeof(cmd_buffer), + 0, + 0 ); + } + break; + case SPI_FLASH_SECTOR_UNPROTECT: + { + uint8_t cmd_buffer[4]; + uint32_t address = param1; + + /* Send Write Enable command */ + cmd_buffer[0] = WRITE_ENABLE_CMD; + if(wait_ready()) + return SPI_FLASH_UNSUCCESS; + + SPI_TRANS_BLOCK( SPI_INSTANCE, cmd_buffer, 1, 0, 0 ); + + /* Unprotect sector */ + cmd_buffer[0] = UNPROTECT_SECTOR_OPCODE; + cmd_buffer[1] = (address >> 16) & 0xFF; + cmd_buffer[2] = (address >> 8 ) & 0xFF; + cmd_buffer[3] = address & 0xFF; + if(wait_ready()) + return SPI_FLASH_UNSUCCESS; + + SPI_TRANS_BLOCK( SPI_INSTANCE, + cmd_buffer, + sizeof(cmd_buffer), + 0, + 0 ); + } + break; + + case SPI_FLASH_GLOBAL_PROTECT: + case SPI_FLASH_GLOBAL_UNPROTECT: + { + uint8_t cmd_buffer[2]; + /* Send Write Enable command */ + cmd_buffer[0] = WRITE_ENABLE_CMD; + + if(wait_ready()) + return SPI_FLASH_UNSUCCESS; + + SPI_TRANS_BLOCK( SPI_INSTANCE, cmd_buffer, 1, 0, 0 ); + + /* Send Chip Erase command */ + cmd_buffer[0] = WRITE_STATUS1_OPCODE; + cmd_buffer[1] = 0; + + if(wait_ready()) + return SPI_FLASH_UNSUCCESS; + + SPI_TRANS_BLOCK( SPI_INSTANCE, cmd_buffer, 2, 0, 0 ); + if(wait_ready()) + return SPI_FLASH_UNSUCCESS; + } + break; + case SPI_FLASH_CHIP_ERASE: + { + uint8_t cmd_buffer; + /* Send Write Enable command */ + cmd_buffer = WRITE_ENABLE_CMD; + + if(wait_ready()) + return SPI_FLASH_UNSUCCESS; + + SPI_TRANS_BLOCK( SPI_INSTANCE, &cmd_buffer, 1, 0, 0 ); + + /* Send Chip Erase command */ + cmd_buffer = CHIP_ERASE_OPCODE; + + if(wait_ready()) + return SPI_FLASH_UNSUCCESS; + + SPI_TRANS_BLOCK( SPI_INSTANCE, &cmd_buffer, 1, 0, 0 ); + if(wait_ready()) + return SPI_FLASH_UNSUCCESS; + } + break; + case SPI_FLASH_RESET: + { + uint8_t cmd_buffer; + /* Send Write Enable command */ + cmd_buffer = 0x66; + SPI_TRANS_BLOCK( SPI_INSTANCE, &cmd_buffer, 1, 0, 0 ); + cmd_buffer = 0x99; + SPI_TRANS_BLOCK( SPI_INSTANCE, &cmd_buffer, 1, 0, 0 ); + if(wait_ready()) + return SPI_FLASH_UNSUCCESS; + } + break; + + case SPI_FLASH_4KBLOCK_ERASE: + { + uint32_t address = param1 & BLOCK_ALIGN_MASK_4K; + uint8_t cmd_buffer[4]; + /* Send Write Enable command */ + cmd_buffer[0] = WRITE_ENABLE_CMD; + + if(wait_ready()) + return SPI_FLASH_UNSUCCESS; + + SPI_TRANS_BLOCK( SPI_INSTANCE, cmd_buffer, 1, 0, 0 ); + + if(wait_ready()) + return SPI_FLASH_UNSUCCESS; + + /* Send Chip Erase command */ + cmd_buffer[0] = ERASE_4K_BLOCK_OPCODE; + cmd_buffer[1] = (address >> 16) & 0xFF; + cmd_buffer[2] = (address >> 8 ) & 0xFF; + cmd_buffer[3] = address & 0xFF; + + if(wait_ready()) + return SPI_FLASH_UNSUCCESS; + + wait_ready_erase(); + + SPI_TRANS_BLOCK( SPI_INSTANCE, cmd_buffer, 4, 0, 0 ); + if(wait_ready()) + return SPI_FLASH_UNSUCCESS; + + wait_ready_erase(); + + } + break; + case SPI_FLASH_32KBLOCK_ERASE: + { + uint32_t address = param1 & BLOCK_ALIGN_MASK_32K; + uint8_t cmd_buffer[4]; + /* Send Write Enable command */ + cmd_buffer[0] = WRITE_ENABLE_CMD; + + wait_ready(); + SPI_TRANS_BLOCK( SPI_INSTANCE, cmd_buffer, 1, 0, 0 ); + + /* Send Chip Erase command */ + cmd_buffer[0] = ERASE_32K_BLOCK_OPCODE; + cmd_buffer[1] = (address >> 16) & 0xFF; + cmd_buffer[2] = (address >> 8 ) & 0xFF; + cmd_buffer[3] = address & 0xFF; + + if(wait_ready()) + return SPI_FLASH_UNSUCCESS; + + SPI_TRANS_BLOCK( SPI_INSTANCE, cmd_buffer, 4, 0, 0 ); + if(wait_ready()) + return SPI_FLASH_UNSUCCESS; + } + break; + case SPI_FLASH_64KBLOCK_ERASE: + { + uint32_t address = param1 & BLOCK_ALIGN_MASK_64K; + uint8_t cmd_buffer[4]; + /* Send Write Enable command */ + cmd_buffer[0] = WRITE_ENABLE_CMD; + + if(wait_ready()) + return SPI_FLASH_UNSUCCESS; + + SPI_TRANS_BLOCK( SPI_INSTANCE, cmd_buffer, 1, 0, 0 ); + + /* Send Chip Erase command */ + cmd_buffer[0] = ERASE_64K_BLOCK_OPCODE; + cmd_buffer[1] = (address >> 16) & 0xFF; + cmd_buffer[2] = (address >> 8 ) & 0xFF; + cmd_buffer[3] = address & 0xFF; + + if(wait_ready()) + return SPI_FLASH_UNSUCCESS; + SPI_TRANS_BLOCK( SPI_INSTANCE, + cmd_buffer, + sizeof(cmd_buffer), + 0, + 0 ); + if(wait_ready()) + return SPI_FLASH_UNSUCCESS; + } + break; + case SPI_FLASH_GET_STATUS: + { + uint8_t status[2]; + uint8_t command = READ_STATUS; + + SPI_TRANS_BLOCK( SPI_INSTANCE, + &command, + sizeof(uint8_t), + status, + 2 ); + + *((uint16_t *)ptrParam) = (status[1]) << 8 | status[0]; + } + break; + + case SPI_FLASH_GET_PROTECT: + { + uint8_t cmd_buffer[4]; + + /* Send Read Sector Protection Register command */ + cmd_buffer[0] = READ_SECTOR_PROTECT; + cmd_buffer[1] = (param1 >> 16) & 0xFF; + cmd_buffer[2] = (param1 >> 8 ) & 0xFF; + cmd_buffer[3] = param1 & 0xFF; + + if(wait_ready()) + return SPI_FLASH_UNSUCCESS; + + SPI_TRANS_BLOCK( SPI_INSTANCE, + cmd_buffer, + sizeof(cmd_buffer), + (uint8_t *)ptrParam, + 1 ); + + if(wait_ready()) + { + *((uint8_t *)ptrParam) = 1; // Mark as bad result as real one is 0 or 255 + return SPI_FLASH_UNSUCCESS; + } + } + break; + + default: + return SPI_FLASH_INVALID_ARGUMENTS; + break; + } + return SPI_FLASH_SUCCESS; +} + + +/****************************************************************************** + *For more details please refer the spi_flash.h file + ******************************************************************************/ +spi_flash_status_t +spi_flash_read +( + uint32_t address, + uint8_t * rx_buffer, + size_t size_in_bytes +) +{ + uint8_t cmd_buffer[6]; + + cmd_buffer[0] = 0x03;//READ_ARRAY_OPCODE; + cmd_buffer[1] = (uint8_t)((address >> 16) & 0xFF); + cmd_buffer[2] = (uint8_t)((address >> 8) & 0xFF);; + cmd_buffer[3] = (uint8_t)(address & 0xFF); + cmd_buffer[4] = DONT_CARE; + cmd_buffer[5] = DONT_CARE; + + wait_ready_erase(); + + if(wait_ready()) + return SPI_FLASH_UNSUCCESS; + + wait_ready_erase(); + + SPI_TRANS_BLOCK( SPI_INSTANCE, cmd_buffer, 4/*sizeof(cmd_buffer)*/, rx_buffer, size_in_bytes ); + wait_ready_erase(); + return 0; +} + + +/******************************************************************************* + * This function sends the command and data to the FLASH device via SPI. + */ +static void write_cmd_data +( + spi_instance_t * this_spi, + const uint8_t * cmd_buffer, + uint16_t cmd_byte_size, + uint8_t * data_buffer, + uint16_t data_byte_size +) +{ + /* + * Construct our combined command and data block + */ + if( cmd_byte_size ) + memcpy( flash_write_buffer, cmd_buffer, cmd_byte_size ); + + if( data_byte_size ) + memcpy( &flash_write_buffer[cmd_byte_size], data_buffer, data_byte_size ); + + SPI_TRANS_BLOCK( this_spi, flash_write_buffer, cmd_byte_size + data_byte_size, 0, 0 ); +} + +/****************************************************************************** + *For more details please refer the spi_flash.h file + ******************************************************************************/ +spi_flash_status_t +spi_flash_write +( + uint32_t address, + uint8_t * write_buffer, + size_t size_in_bytes +) +{ + uint8_t cmd_buffer[4]; + + uint32_t in_buffer_idx; + uint32_t nb_bytes_to_write; + uint32_t target_addr; + + /* Send Write Enable command */ + cmd_buffer[0] = WRITE_ENABLE_CMD; + wait_ready(); + SPI_TRANS_BLOCK( SPI_INSTANCE, cmd_buffer, 1, 0, 0 ); + + /* Unprotect sector */ + cmd_buffer[0] = UNPROTECT_SECTOR_OPCODE; + cmd_buffer[1] = (address >> 16) & 0xFF; + cmd_buffer[2] = (address >> 8 ) & 0xFF; + cmd_buffer[3] = address & 0xFF; + wait_ready(); + SPI_TRANS_BLOCK( SPI_INSTANCE, cmd_buffer, sizeof(cmd_buffer), 0, 0 ); + wait_ready_erase(); + + /* Send Write Enable command */ + cmd_buffer[0] = WRITE_ENABLE_CMD; + if(wait_ready()) + return SPI_FLASH_UNSUCCESS; + + SPI_TRANS_BLOCK( SPI_INSTANCE, cmd_buffer, 1, 0, 0 ); + + /**/ + in_buffer_idx = 0; + nb_bytes_to_write = size_in_bytes; + target_addr = address; + + while ( in_buffer_idx < size_in_bytes ) + { + wait_ready_erase(); + uint32_t size_left; + nb_bytes_to_write = 0x100 - (target_addr & 0xFF); + /* adjust max possible size to page boundary. */ + size_left = size_in_bytes - in_buffer_idx; + if ( size_left < nb_bytes_to_write ) + { + nb_bytes_to_write = size_left; + } + + if(wait_ready()) + return SPI_FLASH_UNSUCCESS; + + /* Send Write Enable command */ + cmd_buffer[0] = WRITE_ENABLE_CMD; + SPI_TRANS_BLOCK( SPI_INSTANCE, cmd_buffer, 1, 0, 0 ); + + /* Program page */ + if(wait_ready()) + return SPI_FLASH_UNSUCCESS; + + + cmd_buffer[0] = PROGRAM_PAGE_CMD; + cmd_buffer[1] = (target_addr >> 16) & 0xFF; + cmd_buffer[2] = (target_addr >> 8 ) & 0xFF; + cmd_buffer[3] = target_addr & 0xFF; + + write_cmd_data + ( + SPI_INSTANCE, + cmd_buffer, + sizeof(cmd_buffer), + &write_buffer[in_buffer_idx], + nb_bytes_to_write + ); + + target_addr += nb_bytes_to_write; + in_buffer_idx += nb_bytes_to_write; + wait_ready_erase(); + } + + /* Send Write Disable command. */ + cmd_buffer[0] = WRITE_DISABLE_CMD; + + if(wait_ready()) + return SPI_FLASH_UNSUCCESS; + + SPI_TRANS_BLOCK( SPI_INSTANCE, cmd_buffer, 1, 0, 0 ); + return 0; +} + + +/****************************************************************************** + * This function waits for the SPI operation to complete + ******************************************************************************/ +static uint8_t wait_ready( void ) +{ + uint32_t count = 0; + uint8_t ready_bit; + uint8_t command = READ_STATUS; +#if 1 + do { + SPI_TRANS_BLOCK(SPI_INSTANCE, &command, 1, &ready_bit, 1); + ready_bit = ready_bit & READY_BIT_MASK; + count++; + } while((ready_bit & READY_BIT_MASK) /*&& (count <= 0x7FFFFFFF)*/); +#endif + return (ready_bit); +} + +static uint8_t wait_ready_erase( void ) +{ + uint32_t count = 0; + uint8_t ready_bit; + uint8_t command = 0x70 ; // FLAG_READ_STATUS; +#if 1 + do { + SPI_TRANS_BLOCK(SPI_INSTANCE, &command, 1, &ready_bit, 1); + count++; + } while((ready_bit & 0x80) == 0); +#endif + return (ready_bit); +} diff --git a/bootloaders/miv-rv32-bootloader/src/platform/drivers/off_chip/spi_flash/spi_flash.h b/bootloaders/miv-rv32-bootloader/src/platform/drivers/off_chip/spi_flash/spi_flash.h new file mode 100644 index 0000000..a043e4e --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/drivers/off_chip/spi_flash/spi_flash.h @@ -0,0 +1,270 @@ + /****************************************************************************** + * + * (c) Copyright 2013 Microsemi SoC Products Group. All rights reserved. + * + * Company: Microsemi Corporation + * + * File: spi_flash.h + * + * Note: + * + * This is a non DMA version of the flash driver for the CoreSPI 4.2.xx + * based on the driver for MSS SPI based driver from MPM 6. + * + * The SPI_FLASH_GET_STATUS command now returns the 2 bytes of the status + * via the pointer parameter and the PI_FLASH_GET_PROTECT command has been + * added. + * + * SVN $Revision: 8241 $ + * SVN $Date: 2016-02-15 11:21:27 +0000 (Mon, 15 Feb 2016) $ + * + *******************************************************************************/ + +#ifndef __AT25DF641_SPI_FLASH_H_ +#define __AT25DF641_SPI_FLASH_H_ + +#include +#include + +/******************************************************************************* + * Possible return values from functions on SPI FLASH. + ******************************************************************************/ +typedef enum { + SPI_FLASH_SUCCESS = 0, + SPI_FLASH_PROTECTION_ERROR, + SPI_FLASH_WRITE_ERROR, + SPI_FLASH_INVALID_ARGUMENTS, + SPI_FLASH_INVALID_ADDRESS, + SPI_FLASH_UNSUCCESS +} spi_flash_status_t; + +/******************************************************************************* + * Possible HW Control commands on SPI FLASH. + ******************************************************************************/ +typedef enum { + SPI_FLASH_SECTOR_UNPROTECT = 0, + SPI_FLASH_SECTOR_PROTECT, + SPI_FLASH_GLOBAL_UNPROTECT, + SPI_FLASH_GLOBAL_PROTECT, + SPI_FLASH_GET_STATUS, + SPI_FLASH_4KBLOCK_ERASE, + SPI_FLASH_32KBLOCK_ERASE, + SPI_FLASH_64KBLOCK_ERASE, + SPI_FLASH_CHIP_ERASE, + SPI_FLASH_READ_DEVICE_ID, + SPI_FLASH_RESET, + SPI_FLASH_GET_PROTECT +/* + SPI_FLASH_SECTOR_LOCKDOWN, + SPI_FLASH_FREEZE_SECTOR_LOCKDOWN +*/ +} spi_flash_control_hw_t; + +struct device_Info{ + uint8_t manufacturer_id; + uint8_t device_id; + uint8_t mem_cap; +}; + +/******************************************************************************* + * This function initialzes the SPI peripheral for data transfer + ******************************************************************************/ +spi_flash_status_t +spi_flash_init +( + uint32_t base_addr +); + +/****************************************************************************** + * This function performs the various operations on the serial Flash + * based on the command passed as first parameter. + * The operation of the each command is explained below. + * + * @param operation + * The operations supported are as per the enum spi_flash_control_hw_t + * defined above. The functionality is as follows: + * + * 1. SPI_FLASH_SECTOR_UNPROTECT: Every 64KBytes are represented + * in sectors. There is a corresponding bits set for protection + * of that sector. To do modify operations like write and erase + * we need to call this operation to unprotect the block. + * The second parameter 'param1' for this function is the block + * address to unprotect. + * + * 2. SPI_FLASH_SECTOR_PROTECT : Every 64KBytes are represented + * in sectors. There is a corresponding bits set for protection + * of that sector. To protect from the modify operations like + * write and erase we need to call this operation + * to protect the block. The second parameter 'param1' for this + * function is the block address to protect. + * + * 3. SPI_FLASH_GLOBAL_UNPROTECT: This command is used to unprotect + * the entire flash for modify operations. + * + * 4. SPI_FLASH_GLOBAL_PROTECT: This command is used to protect/lock + * the entire flash from modify operations. + * + * 5. SPI_FLASH_GET_STATUS: This function used to get the SPI Flash + * status register content for more details of the status bits + * refer to the data sheet for the AT25DF641. The second parameter + * is ignored and the third parameter points to an unsigned 16 bit + * value to store the status in. The first status byte is in b0-7 + * and the second status byte in b8-15. + * + * 6. SPI_FLASH_4KBLOCK_ERASE: This command is used to erase the block + * starting at 4KB boundary. The starting address of the 4K Block is + * passed in the second parameter param1 of this API. + * + * 7. SPI_FLASH_32KBLOCK_ERASE: This command is used to erase the block + * starting at 32KB boundary. The starting address of the 32K Block + * is passed in the second parameter param1 of this API. + * + * 8. SPI_FLASH_64KBLOCK_ERASE: This command is used to erase the block + * starting at 64KB boundary. The starting address of the 64K Block + * is passed in the second parameter peram1 of this API. + * + * 9. SPI_FLASH_CHIP_ERASE This command is used to erase the entire flash chip. + * + * 10. SPI_FLASH_READ_DEVICE_ID: This command is used to read the + * device properties. The values are filled in the third parameter + * 'ptrParam' of this API, + * + * 11. SPI_FLASH_RESET: In some cases it may be necessary to prematurely terminate + * a program or erase cycle early rather than wait the hundreds of microseconds or + * milliseconds necessary for the program or erase operation to complete normally. + * The Reset command allows a program or erase operation in progress to be ended + * abruptly and returns the device to an idle state. + * + * 12. SPI_FLASH_GET_PROTECT: Read the sector protection register for the sector in. + * question. Should be 0x00 if unprotected and 0xFF if protected. The second + * parameter is an address within the 64K sector we are examining. The third + * parameter is a pointer to an unsigned 8 bit location to store the protection + * register value in. + * + * @param param1 The param1 usage is explained in the above description according + * to command in use. + * @param ptrParam The ptrParam usage is explained in the above description according + * to command in use. + * @return The return value indicates if the write was successful. + * Possible values are: + * SPI_FLASH_SUCCESS, + * SPI_FLASH_PROTECTION_ERROR, + * SPI_FLASH_INVALID_ARGUMENTS, + * SPI_FLASH_INVALID_ADDRESS, + * SPI_FLASH_UNSUCCESS + * + * SPI_FLASH_SUCCESS: describes the SPI Flash operation is + * correct and complete + * + * SPI_FLASH_PROTECTION_ERROR: The sector is under protected and + * not allowing the operation. + * We need to do the unprotect and do the operation + * + * SPI_FLASH_INVALID_ARGUMENTS: describes that function has received + * Invalid arguments + * + * SPI_FLASH_INVALID_ADDRESS: describes that function has received + * Invalid address + * + * SPI_FLASH_UNSUCCESS: describes the SPI Flash operation is + * incomplete + */ + +spi_flash_status_t +spi_flash_control_hw +( + spi_flash_control_hw_t operation, + uint32_t peram1, + void * ptrPeram +); + +/******************************************************************************* + * This function reads the content from the serial Flash. + * The data is read from the memory location specified by the first parameter. + * This address is ranges from 0 to SPI Flash Size. This address range is not + * the processors absolute range. + * + * @param start_addr This is the address at which data willbe read. + * This address is ranges from 0 to SPI Flash Size. + * This address range is not the processors absolute range. + * @param p_data This is a pointer to the buffer for holding the read data. + * @param nb_bytes This is the number of bytes to be read from SPI Flash. + * @return The return value indicates if the write was successful. + * Possible values are: + * SPI_FLASH_SUCCESS, + * SPI_FLASH_PROTECTION_ERROR, + * SPI_FLASH_INVALID_ARGUMENTS, + * SPI_FLASH_INVALID_ADDRESS, + * SPI_FLASH_UNSUCCESS + * + * SPI_FLASH_SUCCESS: describes the SPI Flash operation is + * correct and complete + * + * SPI_FLASH_INVALID_ARGUMENTS: describes that function has received + * Invalid arguments + * + * SPI_FLASH_INVALID_ADDRESS: describes that function has received + * Invalid address + * + * SPI_FLASH_UNSUCCESS: describes the SPI Flash operation is + * incomplete + */ +spi_flash_status_t +spi_flash_read +( + uint32_t address, + uint8_t * rx_buffer, + size_t size_in_bytes +); + +/******************************************************************************* + * This function writes the content of the buffer passed as parameter to + * Serial Flash through SPI. The data is written from the memory location specified + * by the first parameter. + * This address is ranges from 0 to SPI Flash Size. This address range is not + * the processors absolute range + * + * @param start_addr This is the address at which data will be written. + * This address is ranges from 0 to SPI Flash Size. + * This address range is not the processors absolute range + * @param p_data This is a pointer to the buffer holding the data to be + * written into Serial Flash. + * @param nb_bytes This is the number of bytes to be written into Serial Flash. + * @return The return value indicates if the write was successful. + * Possible values are: + * SPI_FLASH_SUCCESS, + * SPI_FLASH_PROTECTION_ERROR, + * SPI_FLASH_WRITE_ERROR, + * SPI_FLASH_INVALID_ARGUMENTS, + * SPI_FLASH_INVALID_ADDRESS, + * SPI_FLASH_UNSUCCESS + * + * SPI_FLASH_SUCCESS: describes the SPI Flash operation is + * correct and complete + * + * SPI_FLASH_PROTECTION_ERROR: The sector is under protected and + * not allowing the operation. + * We need to do the unprotect and do the operation + * + * SPI_FLASH_WRITE_ERROR: describes the SPI Flash write operation is + * failed + * + * SPI_FLASH_INVALID_ARGUMENTS: describes that function has received + * Invalid arguments + * + * SPI_FLASH_INVALID_ADDRESS: describes that function has received + * Invalid address. Address range should be between 0 to 8 MB + * + * SPI_FLASH_UNSUCCESS: describes the SPI Flash operation is + * incomplete + */ + +spi_flash_status_t +spi_flash_write +( + uint32_t address, + uint8_t * write_buffer, + size_t size_in_bytes +); + +#endif diff --git a/bootloaders/miv-rv32-bootloader/src/platform/hal/cpu_types.h b/bootloaders/miv-rv32-bootloader/src/platform/hal/cpu_types.h new file mode 100644 index 0000000..ef8ab20 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/hal/cpu_types.h @@ -0,0 +1,41 @@ +/******************************************************************************* + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file cpu_types.h + * @author Microchip FPGA Embedded Systems Solutions + * @brief Type definitions which can be commonly used by the fabric-ip drivers. + * + */ +#ifndef __CPU_TYPES_H +#define __CPU_TYPES_H 1 + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef unsigned int size_t; + +/*------------------------------------------------------------------------------ + * addr_t: address type. + * Used to specify the address of peripherals present in the processor's memory + * map. + */ +typedef unsigned int addr_t; + +/*------------------------------------------------------------------------------ + * psr_t: processor state register. + * Used by HAL_disable_interrupts() and HAL_restore_interrupts() to store the + * processor's state between disabling and restoring interrupts. + */ +typedef unsigned int psr_t; + +#ifdef __cplusplus +} +#endif + +#endif /* CPU_TYPES_H */ + diff --git a/bootloaders/miv-rv32-bootloader/src/platform/hal/hal.h b/bootloaders/miv-rv32-bootloader/src/platform/hal/hal.h new file mode 100644 index 0000000..7eec17a --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/hal/hal.h @@ -0,0 +1,235 @@ +/***************************************************************************//** + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * @file hal.h + * @author Microchip FPGA Embedded Systems Solutions + * @brief Hardware abstraction layer functions for peripheral register accesses. + * + */ +#ifndef __HAL_H +#define __HAL_H 1 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "cpu_types.h" +#include "hw_reg_access.h" +#include "hal_assert.h" +/***************************************************************************//** + * Enable all interrupts at the processor level. + */ +void HAL_enable_interrupts( void ); + +/***************************************************************************//** + * Disable all interrupts at the processor core level. + * Return the interrupts enable state before disabling occurred so that it can + * later be restored. + */ +psr_t HAL_disable_interrupts( void ); + +/***************************************************************************//** + * Restore the interrupts enable state at the processor core level. + * This function is normally passed the value returned from a previous call to + * HAL_disable_interrupts(). + */ +void HAL_restore_interrupts( psr_t saved_psr ); + +/***************************************************************************//** + */ +#define FIELD_OFFSET(FIELD_NAME) (FIELD_NAME##_OFFSET) +#define FIELD_SHIFT(FIELD_NAME) (FIELD_NAME##_SHIFT) +#define FIELD_MASK(FIELD_NAME) (FIELD_NAME##_MASK) + +/***************************************************************************//** + * The macro HAL_set_32bit_reg() allows writing a 32 bits wide register. + * + * BASE_ADDR: A variable of type addr_t specifying the base address of the + * peripheral containing the register. + * REG_NAME: A string identifying the register to write. These strings are + * specified in a header file associated with the peripheral. + * VALUE: A variable of type uint32_t containing the value to write. + */ +#define HAL_set_32bit_reg(BASE_ADDR, REG_NAME, VALUE) \ + (HW_set_32bit_reg( ((BASE_ADDR) + (REG_NAME##_REG_OFFSET)), (VALUE) )) + +/***************************************************************************//** + * The macro HAL_get_32bit_reg() is used to read the value of a 32 bits wide + * register. + * + * BASE_ADDR: A variable of type addr_t specifying the base address of the + * peripheral containing the register. + * REG_NAME: A string identifying the register to read. These strings are + * specified in a header file associated with the peripheral. + * RETURN: This function-like macro returns a uint32_t value. + */ +#define HAL_get_32bit_reg(BASE_ADDR, REG_NAME) \ + (HW_get_32bit_reg( ((BASE_ADDR) + (REG_NAME##_REG_OFFSET)) )) + +/***************************************************************************//** + * The macro HAL_set_32bit_reg_field() is used to write a field within a + * 32 bits wide register. The field written can be one or more bits. + * + * BASE_ADDR: A variable of type addr_t specifying the base address of the + * peripheral containing the register. + * FIELD_NAME: A string identifying the register field to write. These strings + * are specified in a header file associated with the peripheral. + * VALUE: A variable of type uint32_t containing the field value to write. + */ +#define HAL_set_32bit_reg_field(BASE_ADDR, FIELD_NAME, VALUE) \ + (HW_set_32bit_reg_field(\ + (BASE_ADDR) + FIELD_OFFSET(FIELD_NAME),\ + FIELD_SHIFT(FIELD_NAME),\ + FIELD_MASK(FIELD_NAME),\ + (VALUE))) + +/***************************************************************************//** + * The macro HAL_get_32bit_reg_field() is used to read a register field from + * within a 32 bit wide peripheral register. The field can be one or more bits. + * + * BASE_ADDR: A variable of type addr_t specifying the base address of the + * peripheral containing the register. + * FIELD_NAME: A string identifying the register field to write. These strings + * are specified in a header file associated with the peripheral. + * RETURN: This function-like macro returns a uint32_t value. + */ +#define HAL_get_32bit_reg_field(BASE_ADDR, FIELD_NAME) \ + (HW_get_32bit_reg_field(\ + (BASE_ADDR) + FIELD_OFFSET(FIELD_NAME),\ + FIELD_SHIFT(FIELD_NAME),\ + FIELD_MASK(FIELD_NAME))) + +/***************************************************************************//** + * The macro HAL_set_16bit_reg() allows writing a 16 bits wide register. + * + * BASE_ADDR: A variable of type addr_t specifying the base address of the + * peripheral containing the register. + * REG_NAME: A string identifying the register to write. These strings are + * specified in a header file associated with the peripheral. + * VALUE: A variable of type uint_fast16_t containing the value to write. + */ +#define HAL_set_16bit_reg(BASE_ADDR, REG_NAME, VALUE) \ + (HW_set_16bit_reg( ((BASE_ADDR) + (REG_NAME##_REG_OFFSET)), (VALUE) )) + +/***************************************************************************//** + * The macro HAL_get_16bit_reg() is used to read the value of a 16 bits wide + * register. + * + * BASE_ADDR: A variable of type addr_t specifying the base address of the + * peripheral containing the register. + * REG_NAME: A string identifying the register to read. These strings are + * specified in a header file associated with the peripheral. + * RETURN: This function-like macro returns a uint16_t value. + */ +#define HAL_get_16bit_reg(BASE_ADDR, REG_NAME) \ + (HW_get_16bit_reg( (BASE_ADDR) + (REG_NAME##_REG_OFFSET) )) + +/***************************************************************************//** + * The macro HAL_set_16bit_reg_field() is used to write a field within a + * 16 bits wide register. The field written can be one or more bits. + * + * BASE_ADDR: A variable of type addr_t specifying the base address of the + * peripheral containing the register. + * FIELD_NAME: A string identifying the register field to write. These strings + * are specified in a header file associated with the peripheral. + * VALUE: A variable of type uint16_t containing the field value to write. + */ +#define HAL_set_16bit_reg_field(BASE_ADDR, FIELD_NAME, VALUE) \ + (HW_set_16bit_reg_field(\ + (BASE_ADDR) + FIELD_OFFSET(FIELD_NAME),\ + FIELD_SHIFT(FIELD_NAME),\ + FIELD_MASK(FIELD_NAME),\ + (VALUE))) + +/***************************************************************************//** + * The macro HAL_get_16bit_reg_field() is used to read a register field from + * within a 8 bit wide peripheral register. The field can be one or more bits. + * + * BASE_ADDR: A variable of type addr_t specifying the base address of the + * peripheral containing the register. + * FIELD_NAME: A string identifying the register field to write. These strings + * are specified in a header file associated with the peripheral. + * RETURN: This function-like macro returns a uint16_t value. + */ +#define HAL_get_16bit_reg_field(BASE_ADDR, FIELD_NAME) \ + (HW_get_16bit_reg_field(\ + (BASE_ADDR) + FIELD_OFFSET(FIELD_NAME),\ + FIELD_SHIFT(FIELD_NAME),\ + FIELD_MASK(FIELD_NAME))) + +/***************************************************************************//** + * The macro HAL_set_8bit_reg() allows writing a 8 bits wide register. + * + * BASE_ADDR: A variable of type addr_t specifying the base address of the + * peripheral containing the register. + * REG_NAME: A string identifying the register to write. These strings are + * specified in a header file associated with the peripheral. + * VALUE: A variable of type uint_fast8_t containing the value to write. + */ +#define HAL_set_8bit_reg(BASE_ADDR, REG_NAME, VALUE) \ + (HW_set_8bit_reg( ((BASE_ADDR) + (REG_NAME##_REG_OFFSET)), (VALUE) )) + +/***************************************************************************//** + * The macro HAL_get_8bit_reg() is used to read the value of a 8 bits wide + * register. + * + * BASE_ADDR: A variable of type addr_t specifying the base address of the + * peripheral containing the register. + * REG_NAME: A string identifying the register to read. These strings are + * specified in a header file associated with the peripheral. + * RETURN: This function-like macro returns a uint8_t value. + */ +#define HAL_get_8bit_reg(BASE_ADDR, REG_NAME) \ + (HW_get_8bit_reg( (BASE_ADDR) + (REG_NAME##_REG_OFFSET) )) + +/***************************************************************************//** + */ +#define HAL_set_8bit_reg_field(BASE_ADDR, FIELD_NAME, VALUE) \ + (HW_set_8bit_reg_field(\ + (BASE_ADDR) + FIELD_OFFSET(FIELD_NAME),\ + FIELD_SHIFT(FIELD_NAME),\ + FIELD_MASK(FIELD_NAME),\ + (VALUE))) + +/***************************************************************************//** + * The macro HAL_get_8bit_reg_field() is used to read a register field from + * within a 8 bit wide peripheral register. The field can be one or more bits. + * + * BASE_ADDR: A variable of type addr_t specifying the base address of the + * peripheral containing the register. + * FIELD_NAME: A string identifying the register field to write. These strings + * are specified in a header file associated with the peripheral. + * RETURN: This function-like macro returns a uint8_t value. + */ +#define HAL_get_8bit_reg_field(BASE_ADDR, FIELD_NAME) \ + (HW_get_8bit_reg_field(\ + (BASE_ADDR) + FIELD_OFFSET(FIELD_NAME),\ + FIELD_SHIFT(FIELD_NAME),\ + FIELD_MASK(FIELD_NAME))) + +#ifdef __cplusplus +} +#endif + +#endif /*HAL_H*/ + diff --git a/bootloaders/miv-rv32-bootloader/src/platform/hal/hal_assert.h b/bootloaders/miv-rv32-bootloader/src/platform/hal/hal_assert.h new file mode 100644 index 0000000..8e0c747 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/hal/hal_assert.h @@ -0,0 +1,48 @@ +/******************************************************************************* + * Copyright 2019-2021 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file hal_assert.h + * @author Microchip FPGA Embedded Systems Solutions + * @brief HAL assert functions + */ +#ifndef __HAL_ASSERT_HEADER +#define __HAL_ASSERT_HEADER 1 +#define NDEBUG 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/* Disable assertions if we do not recognize the compiler. */ +#if defined ( __GNUC__ ) +#if defined(NDEBUG) +/***************************************************************************//** + * HAL_ASSERT() is defined out when the NDEBUG symbol is used. + ******************************************************************************/ +#define HAL_ASSERT(CHECK) + +#else + +/***************************************************************************//** + * Default behavior for HAL_ASSERT() macro: + *------------------------------------------------------------------------------ + The behavior is toolchain specific and project setting specific. + ******************************************************************************/ +#define HAL_ASSERT(CHECK)\ + do { \ + if (!(CHECK)) \ + { \ + __asm__ volatile ("ebreak"); \ + }\ + } while(0); + +#endif /* NDEBUG */ +#endif /*__GNUC__*/ + +#ifdef __cplusplus +} +#endif +#endif /* __HAL_ASSERT_HEADER */ + diff --git a/bootloaders/miv-rv32-bootloader/src/platform/hal/hal_irq.c b/bootloaders/miv-rv32-bootloader/src/platform/hal/hal_irq.c new file mode 100644 index 0000000..6fe7fce --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/hal/hal_irq.c @@ -0,0 +1,45 @@ +/***************************************************************************//** + * Copyright 2019-2021 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file hal_irq.c + * @author Microchip FPGA Embedded Systems Solutions + * @brief Legacy interrupt control functions for the Microchip driver library + * hardware abstraction layer. + * + */ +#include "hal.h" +#include "miv_rv32_hal/miv_rv32_hal.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/*------------------------------------------------------------------------------ + * + */ +void HAL_enable_interrupts(void) { + MRV_enable_interrupts(); +} + +/*------------------------------------------------------------------------------ + * + */ +psr_t HAL_disable_interrupts(void) { + psr_t psr; + psr = read_csr(mstatus); + MRV_disable_interrupts(); + return(psr); +} + +/*------------------------------------------------------------------------------ + * + */ +void HAL_restore_interrupts(psr_t saved_psr) { + write_csr(mstatus, saved_psr); +} + +#ifdef __cplusplus +} +#endif \ No newline at end of file diff --git a/bootloaders/miv-rv32-bootloader/src/platform/hal/hw_macros.h b/bootloaders/miv-rv32-bootloader/src/platform/hal/hw_macros.h new file mode 100644 index 0000000..ed2c681 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/hal/hw_macros.h @@ -0,0 +1,106 @@ +/******************************************************************************* + * Copyright 2019-2021 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file hw_macros.h + * @author Microchip FPGA Embedded Systems Solutions + * @brief Hardware registers access macros. + * + * THE MACROS DEFINED IN THIS FILE ARE DEPRECATED. DO NOT USE FOR NEW + * DEVELOPMENT. + * + * These macros are used to access peripheral registers. They allow access to + * 8, 16 and 32 bit wide registers. All accesses to peripheral registers should + * be done through these macros in order to ease porting across different + * processors/bus architectures. + * + * Some of these macros also allow access to a specific register field. + * + */ +#ifndef __HW_REGISTER_MACROS_H +#define __HW_REGISTER_MACROS_H 1 +#ifdef __cplusplus +extern "C" { +#endif + +/*------------------------------------------------------------------------------ + * 32 bits registers access: + */ +#define HW_get_uint32_reg(BASE_ADDR, REG_OFFSET) (*((uint32_t volatile *)(BASE_ADDR + REG_OFFSET##_REG_OFFSET))) + +#define HW_set_uint32_reg(BASE_ADDR, REG_OFFSET, VALUE) (*((uint32_t volatile *)(BASE_ADDR + REG_OFFSET##_REG_OFFSET)) = (VALUE)) + +#define HW_set_uint32_reg_field(BASE_ADDR, FIELD, VALUE) \ + (*((uint32_t volatile *)(BASE_ADDR + FIELD##_OFFSET)) = \ + ( \ + (uint32_t) \ + ( \ + (*((uint32_t volatile *)(BASE_ADDR + FIELD##_OFFSET))) & ~FIELD##_MASK) | \ + (uint32_t)(((VALUE) << FIELD##_SHIFT) & FIELD##_MASK) \ + ) \ + ) + +#define HW_get_uint32_reg_field( BASE_ADDR, FIELD ) \ + (( (*((uint32_t volatile *)(BASE_ADDR + FIELD##_OFFSET))) & FIELD##_MASK) >> FIELD##_SHIFT) + +/*------------------------------------------------------------------------------ + * 32 bits memory access: + */ +#define HW_get_uint32(BASE_ADDR) (*((uint32_t volatile *)(BASE_ADDR))) + +#define HW_set_uint32(BASE_ADDR, VALUE) (*((uint32_t volatile *)(BASE_ADDR)) = (VALUE)) + +/*------------------------------------------------------------------------------ + * 16 bits registers access: + */ +#define HW_get_uint16_reg(BASE_ADDR, REG_OFFSET) (*((uint16_t volatile *)(BASE_ADDR + REG_OFFSET##_REG_OFFSET))) + +#define HW_set_uint16_reg(BASE_ADDR, REG_OFFSET, VALUE) (*((uint16_t volatile *)(BASE_ADDR + REG_OFFSET##_REG_OFFSET)) = (VALUE)) + +#define HW_set_uint16_reg_field(BASE_ADDR, FIELD, VALUE) \ + (*((uint16_t volatile *)(BASE_ADDR + FIELD##_OFFSET)) = \ + ( \ + (uint16_t) \ + ( \ + (*((uint16_t volatile *)(BASE_ADDR + FIELD##_OFFSET))) & ~FIELD##_MASK) | \ + (uint16_t)(((VALUE) << FIELD##_SHIFT) & FIELD##_MASK) \ + ) \ + ) + +#define HW_get_uint16_reg_field( BASE_ADDR, FIELD ) \ + (( (*((uint16_t volatile *)(BASE_ADDR + FIELD##_OFFSET))) & FIELD##_MASK) >> FIELD##_SHIFT) + +/*------------------------------------------------------------------------------ + * 8 bits registers access: + */ +#define HW_get_uint8_reg(BASE_ADDR, REG_OFFSET) (*((uint8_t volatile *)(BASE_ADDR + REG_OFFSET##_REG_OFFSET))) + +#define HW_set_uint8_reg(BASE_ADDR, REG_OFFSET, VALUE) (*((uint8_t volatile *)(BASE_ADDR + REG_OFFSET##_REG_OFFSET)) = (VALUE)) + +#define HW_set_uint8_reg_field(BASE_ADDR, FIELD, VALUE) \ + (*((uint8_t volatile *)(BASE_ADDR + FIELD##_OFFSET)) = \ + ( \ + (uint8_t) \ + ( \ + (*((uint8_t volatile *)(BASE_ADDR + FIELD##_OFFSET))) & ~FIELD##_MASK) | \ + (uint8_t)(((VALUE) << FIELD##_SHIFT) & FIELD##_MASK) \ + ) \ + ) + +#define HW_get_uint8_reg_field( BASE_ADDR, FIELD ) \ + (( (*((uint8_t volatile *)(BASE_ADDR + FIELD##_OFFSET))) & FIELD##_MASK) >> FIELD##_SHIFT) + +/*------------------------------------------------------------------------------ + * 8 bits memory access: + */ +#define HW_get_uint8(BASE_ADDR) (*((uint8_t volatile *)(BASE_ADDR))) + +#define HW_set_uint8(BASE_ADDR, VALUE) (*((uint8_t volatile *)(BASE_ADDR)) = (VALUE)) + +#ifdef __cplusplus +extern "C" { +#endif + +#endif /* __HW_REGISTER_MACROS_H */ + diff --git a/bootloaders/miv-rv32-bootloader/src/platform/hal/hw_reg_access.S b/bootloaders/miv-rv32-bootloader/src/platform/hal/hw_reg_access.S new file mode 100644 index 0000000..f4aa0a0 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/hal/hw_reg_access.S @@ -0,0 +1,215 @@ +/***************************************************************************//** + * Copyright 2019-2021 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file hw_reg_access.S + * @author Microchip FPGA Embedded Systems Solutions + * @brief Hardware registers access functions. + * The implementation of these function is platform and toolchain specific. + * The functions declared here are implemented using assembler as part of the + * processor/toolchain specific HAL. This implementation is for the combination + * of the 32 bit RISC-V processors and GNU tool chain. + * + */ + +.section .text + .globl HW_set_32bit_reg + .globl HW_get_32bit_reg + .globl HW_set_32bit_reg_field + .globl HW_get_32bit_reg_field + .globl HW_set_16bit_reg + .globl HW_get_16bit_reg + .globl HW_set_16bit_reg_field + .globl HW_get_16bit_reg_field + .globl HW_set_8bit_reg + .globl HW_get_8bit_reg + .globl HW_set_8bit_reg_field + .globl HW_get_8bit_reg_field + + +/***************************************************************************//** + * HW_set_32bit_reg is used to write the content of a 32 bits wide peripheral + * register. + * + * a0: addr_t reg_addr + * a1: uint32_t value + */ +HW_set_32bit_reg: + sw a1, 0(a0) + ret + +/***************************************************************************//** + * HW_get_32bit_reg is used to read the content of a 32 bits wide peripheral + * register. + * + * a0: addr_t reg_addr + + * @return 32 bits value read from the peripheral register. + */ +HW_get_32bit_reg: + lw a0, 0(a0) + ret + +/***************************************************************************//** + * HW_set_32bit_reg_field is used to set the content of a field in a 32 bits + * wide peripheral register. + * + * a0: addr_t reg_addr + * a1: int_fast8_t shift + * a2: uint32_t mask + * a3: uint32_t value + */ +HW_set_32bit_reg_field: + mv t3, a3 + sll t3, t3, a1 + and t3, t3, a2 + lw t1, 0(a0) + mv t2, a2 + not t2, t2 + and t1, t1, t2 + or t1, t1, t3 + sw t1, 0(a0) + ret + +/***************************************************************************//** + * HW_get_32bit_reg_field is used to read the content of a field out of a + * 32 bits wide peripheral register. + * + * a0: addr_t reg_addr + * a1: int_fast8_t shift + * a2: uint32_t mask + * + * @return 32 bits value containing the register field value specified + * as parameter. + */ +HW_get_32bit_reg_field: + lw a0, 0(a0) + and a0, a0, a2 + srl a0, a0, a1 + ret + +/***************************************************************************//** + * HW_set_16bit_reg is used to write the content of a 16 bits wide peripheral + * register. + * + * a0: addr_t reg_addr + * a1: uint_fast16_t value + */ +HW_set_16bit_reg: + sh a1, 0(a0) + ret + +/***************************************************************************//** + * HW_get_16bit_reg is used to read the content of a 16 bits wide peripheral + * register. + * + * a0: addr_t reg_addr + + * @return 16 bits value read from the peripheral register. + */ +HW_get_16bit_reg: + lh a0, (a0) + ret + +/***************************************************************************//** + * HW_set_16bit_reg_field is used to set the content of a field in a 16 bits + * wide peripheral register. + * + * a0: addr_t reg_addr + * a1: int_fast8_t shift + * a2: uint_fast16_t mask + * a3: uint_fast16_t value + * @param value Value to be written in the specified field. + */ +HW_set_16bit_reg_field: + mv t3, a3 + sll t3, t3, a1 + and t3, t3, a2 + lh t1, 0(a0) + mv t2, a2 + not t2, t2 + and t1, t1, t2 + or t1, t1, t3 + sh t1, 0(a0) + ret + +/***************************************************************************//** + * HW_get_16bit_reg_field is used to read the content of a field from a + * 16 bits wide peripheral register. + * + * a0: addr_t reg_addr + * a1: int_fast8_t shift + * a2: uint_fast16_t mask + * + * @return 16 bits value containing the register field value specified + * as parameter. + */ +HW_get_16bit_reg_field: + lh a0, 0(a0) + and a0, a0, a2 + srl a0, a0, a1 + ret + +/***************************************************************************//** + * HW_set_8bit_reg is used to write the content of a 8 bits wide peripheral + * register. + * + * a0: addr_t reg_addr + * a1: uint_fast8_t value + */ +HW_set_8bit_reg: + sb a1, 0(a0) + ret + +/***************************************************************************//** + * HW_get_8bit_reg is used to read the content of a 8 bits wide peripheral + * register. + * + * a0: addr_t reg_addr + + * @return 8 bits value read from the peripheral register. + */ +HW_get_8bit_reg: + lb a0, 0(a0) + ret + +/***************************************************************************//** + * HW_set_8bit_reg_field is used to set the content of a field in a 8 bits + * wide peripheral register. + * + * a0: addr_t reg_addr, + * a1: int_fast8_t shift + * a2: uint_fast8_t mask + * a3: uint_fast8_t value + */ +HW_set_8bit_reg_field: + mv t3, a3 + sll t3, t3, a1 + and t3, t3, a2 + lb t1, 0(a0) + mv t2, a2 + not t2, t2 + and t1, t1, t2 + or t1, t1, t3 + sb t1, 0(a0) + ret + +/***************************************************************************//** + * HW_get_8bit_reg_field is used to read the content of a field from a + * 8 bits wide peripheral register. + * + * a0: addr_t reg_addr + * a1: int_fast8_t shift + * a2: uint_fast8_t mask + * + * @return 8 bits value containing the register field value specified + * as parameter. + */ +HW_get_8bit_reg_field: + lb a0, 0(a0) + and a0, a0, a2 + srl a0, a0, a1 + ret + +.end diff --git a/bootloaders/miv-rv32-bootloader/src/platform/hal/hw_reg_access.h b/bootloaders/miv-rv32-bootloader/src/platform/hal/hw_reg_access.h new file mode 100644 index 0000000..1f6a551 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/hal/hw_reg_access.h @@ -0,0 +1,239 @@ +/***************************************************************************//** + * Copyright 2019-2021 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file hw_reg_access.S + * @author Microchip FPGA Embedded Systems Solutions + * @brief Hardware registers access functions. + * The implementation of these function is platform and tool-chain specific. + * The functions declared here are implemented using assembler as part of the + * processor/tool-chain specific HAL. This implementation is for the combination + * of the 32 bit RISC-V processors and GNU tool chain. + * + */ +#ifndef __HW_REG_ACCESS +#define __HW_REG_ACCESS +#ifdef __cplusplus +extern "C" { +#endif + +#include "cpu_types.h" +/***************************************************************************//** + * HW_set_32bit_reg is used to write the content of a 32 bits wide peripheral + * register. + * + * @param reg_addr Address in the processor's memory map of the register to + * write. + * @param value Value to be written into the peripheral register. + */ +void +HW_set_32bit_reg +( + addr_t reg_addr, + uint32_t value +); + +/***************************************************************************//** + * HW_get_32bit_reg is used to read the content of a 32 bits wide peripheral + * register. + * + * @param reg_addr Address in the processor's memory map of the register to + * read. + * @return 32 bits value read from the peripheral register. + */ +uint32_t +HW_get_32bit_reg +( + addr_t reg_addr +); + +/***************************************************************************//** + * HW_set_32bit_reg_field is used to set the content of a field in a 32 bits + * wide peripheral register. + * + * @param reg_addr Address in the processor's memory map of the register to + * be written. + * @param shift Bit offset of the register field to be read within the + * register. + * @param mask Bit mask to be applied to the raw register value to filter + * out the other register fields values. + * @param value Value to be written in the specified field. + */ +void +HW_set_32bit_reg_field +( + addr_t reg_addr, + int_fast8_t shift, + uint32_t mask, + uint32_t value +); + +/***************************************************************************//** + * HW_get_32bit_reg_field is used to read the content of a field out of a + * 32 bits wide peripheral register. + * + * @param reg_addr Address in the processor's memory map of the register to + * read. + * @param shift Bit offset of the register field to be written within the + * register. + * @param mask Bit mask to be applied to the raw register value to filter + * out the other register fields values. + * + * @return 32 bits value containing the register field value specified + * as parameter. + */ +uint32_t +HW_get_32bit_reg_field +( + addr_t reg_addr, + int_fast8_t shift, + uint32_t mask +); + +/***************************************************************************//** + * HW_set_16bit_reg is used to write the content of a 16 bits wide peripheral + * register. + * + * @param reg_addr Address in the processor's memory map of the register to + * write. + * @param value Value to be written into the peripheral register. + */ +void +HW_set_16bit_reg +( + addr_t reg_addr, + uint_fast16_t value +); + +/***************************************************************************//** + * HW_get_16bit_reg is used to read the content of a 16 bits wide peripheral + * register. + * + * @param reg_addr Address in the processor's memory map of the register to + * read. + * @return 16 bits value read from the peripheral register. + */ +uint16_t +HW_get_16bit_reg +( + addr_t reg_addr +); + +/***************************************************************************//** + * HW_set_16bit_reg_field is used to set the content of a field in a 16 bits + * wide peripheral register. + * + * @param reg_addr Address in the processor's memory map of the register to + * be written. + * @param shift Bit offset of the register field to be read within the + * register. + * @param mask Bit mask to be applied to the raw register value to filter + * out the other register fields values. + * @param value Value to be written in the specified field. + */ +void HW_set_16bit_reg_field +( + addr_t reg_addr, + int_fast8_t shift, + uint_fast16_t mask, + uint_fast16_t value +); + +/***************************************************************************//** + * HW_get_16bit_reg_field is used to read the content of a field from a + * 16 bits wide peripheral register. + * + * @param reg_addr Address in the processor's memory map of the register to + * read. + * @param shift Bit offset of the register field to be written within the + * register. + * @param mask Bit mask to be applied to the raw register value to filter + * out the other register fields values. + * + * @return 16 bits value containing the register field value specified + * as parameter. + */ +uint16_t HW_get_16bit_reg_field +( + addr_t reg_addr, + int_fast8_t shift, + uint_fast16_t mask +); + +/***************************************************************************//** + * HW_set_8bit_reg is used to write the content of a 8 bits wide peripheral + * register. + * + * @param reg_addr Address in the processor's memory map of the register to + * write. + * @param value Value to be written into the peripheral register. + */ +void +HW_set_8bit_reg +( + addr_t reg_addr, + uint_fast8_t value +); + +/***************************************************************************//** + * HW_get_8bit_reg is used to read the content of a 8 bits wide peripheral + * register. + * + * @param reg_addr Address in the processor's memory map of the register to + * read. + * @return 8 bits value read from the peripheral register. + */ +uint8_t +HW_get_8bit_reg +( + addr_t reg_addr +); + +/***************************************************************************//** + * HW_set_8bit_reg_field is used to set the content of a field in a 8 bits + * wide peripheral register. + * + * @param reg_addr Address in the processor's memory map of the register to + * be written. + * @param shift Bit offset of the register field to be read within the + * register. + * @param mask Bit mask to be applied to the raw register value to filter + * out the other register fields values. + * @param value Value to be written in the specified field. + */ +void HW_set_8bit_reg_field +( + addr_t reg_addr, + int_fast8_t shift, + uint_fast8_t mask, + uint_fast8_t value +); + +/***************************************************************************//** + * HW_get_8bit_reg_field is used to read the content of a field from a + * 8 bits wide peripheral register. + * + * @param reg_addr Address in the processor's memory map of the register to + * read. + * @param shift Bit offset of the register field to be written within the + * register. + * @param mask Bit mask to be applied to the raw register value to filter + * out the other register fields values. + * + * @return 8 bits value containing the register field value specified + * as parameter. + */ +uint8_t HW_get_8bit_reg_field +( + addr_t reg_addr, + int_fast8_t shift, + uint_fast8_t mask +); + +#ifdef __cplusplus +} +#endif + +#endif /* __HW_REG_ACCESS */ + diff --git a/bootloaders/miv-rv32-bootloader/src/platform/hal/readme.md b/bootloaders/miv-rv32-bootloader/src/platform/hal/readme.md new file mode 100644 index 0000000..c756b34 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/hal/readme.md @@ -0,0 +1,38 @@ +# hal folder + + +The HAL folder hardware abstraction for the bare metal drivers for the fabric +IP cores. The HAL folder contains files using a combination of C and assembly +source code. This layer allows the fabric ip drivers to be used with any of the +soft processors or the MSS hardened processors. + +The hal folder should be included in a your project under the platform directory. +See location in the drawing below. + +The hal folder contains: + +* register access functions +* assert macros + +### Project directory strucutre, showing where hal folder sits. + + +---------+ +-----------+ + | src +----->|application| + +---------+ | +-----------+ + | + | +-----------+ + +-->|middleware | + | +-----------+ + | + | +-----------+ +---------+ + +-->|platform +---->|drivers | + +-----------+ | +---------+ + | + | +---------+ + +->|hal | + | +---------+ + | + | +---------+ + +->|mpfs_hal | + +---------+ + \ No newline at end of file diff --git a/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv-rv32-execute-in-place.ld b/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv-rv32-execute-in-place.ld new file mode 100644 index 0000000..19df5fb --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv-rv32-execute-in-place.ld @@ -0,0 +1,154 @@ +/******************************************************************************* + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * file name : miv-rv32-execute-in-place.ld + * Mi-V soft processor linker script for creating a SoftConsole downloadable + * image executing from a one address space whereas the data, sdata and stack + * sections are placed in another address space. This could be used in cases such + * as: + * 1) When using MIV_RV32, the reset vector points to the LSRAM at address + * 0x80000000 and the data, sdata, bss and stack sections are placed in the + * TCM region. + * + * 2) Executing from a Non Volatile memory. The actual memory will depend on + * the FPGA platform. For exameple, it could be the eNVM on SmartFusion2, + * Igloo2 or on-board non-volatile memory which supports code execution. + * + * NOTE: Modify the memory section addresses and the sizes according to your + * Libero design. + * + * To know more about the memory map of the MIV_RV32 based Libero design, open + * the MIV_RV32 IP configurator and look for "Reset Vector Address" and the + * "Memory Map" tab. + * + */ + +OUTPUT_ARCH( "riscv" ) +ENTRY(_start) + + +MEMORY +{ + rom (rx) : ORIGIN = 0x80000000, LENGTH = 16k + ram (rwx) : ORIGIN = 0x80004000, LENGTH = 16k +} + +STACK_SIZE = 1k; /* needs to be calculated for your application */ +HEAP_SIZE = 0; /* needs to be calculated for your application */ + +SECTIONS +{ + .entry : ALIGN(0x10) + { + KEEP (*(SORT_NONE(.entry))) + . = ALIGN(0x10); + } > rom + + .text : ALIGN(0x10) + { + KEEP (*(SORT_NONE(.text.entry))) + . = ALIGN(0x10); + *(.text .text.* .gnu.linkonce.t.*) + *(.plt) + . = ALIGN(0x10); + + KEEP (*crtbegin.o(.ctors)) + KEEP (*(EXCLUDE_FILE (*crtend.o) .ctors)) + KEEP (*(SORT(.ctors.*))) + KEEP (*crtend.o(.ctors)) + KEEP (*crtbegin.o(.dtors)) + KEEP (*(EXCLUDE_FILE (*crtend.o) .dtors)) + KEEP (*(SORT(.dtors.*))) + KEEP (*crtend.o(.dtors)) + + *(.rodata .rodata.* .gnu.linkonce.r.*) + *(.gcc_except_table) + *(.eh_frame_hdr) + *(.eh_frame) + + KEEP (*(.init)) + KEEP (*(.fini)) + + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP (*(.preinit_array)) + PROVIDE_HIDDEN (__preinit_array_end = .); + PROVIDE_HIDDEN (__init_array_start = .); + KEEP (*(SORT(.init_array.*))) + KEEP (*(.init_array)) + PROVIDE_HIDDEN (__init_array_end = .); + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP (*(.fini_array)) + KEEP (*(SORT(.fini_array.*))) + PROVIDE_HIDDEN (__fini_array_end = .); + . = ALIGN(0x10); + + } >rom + + /* short/global data section */ + .sdata : ALIGN(0x10) + { + __sdata_load = LOADADDR(.sdata); + __sdata_start = .; + PROVIDE( __global_pointer$ = . + 0x800); + *(.srodata.cst16) *(.srodata.cst8) *(.srodata.cst4) *(.srodata.cst2) + *(.srodata*) + *(.sdata .sdata.* .gnu.linkonce.s.*) + . = ALIGN(0x10); + __sdata_end = .; + } >ram AT>rom + + /* data section */ + .data : ALIGN(0x10) + { + __data_load = LOADADDR(.data); + __data_start = .; + *(.got.plt) *(.got) + *(.shdata) + *(.data .data.* .gnu.linkonce.d.*) + . = ALIGN(0x10); + __data_end = .; + } >ram AT>rom + + /* sbss section */ + .sbss : ALIGN(0x10) + { + __sbss_start = .; + *(.sbss .sbss.* .gnu.linkonce.sb.*) + *(.scommon) + . = ALIGN(0x10); + __sbss_end = .; + } > ram + + /* sbss section */ + .bss : ALIGN(0x10) + { + __bss_start = .; + *(.shbss) + *(.bss .bss.* .gnu.linkonce.b.*) + *(COMMON) + . = ALIGN(0x10); + __bss_end = .; + } > ram + + /* End of uninitialized data segment */ + _end = .; + + .heap : ALIGN(0x10) + { + __heap_start = .; + . += HEAP_SIZE; + __heap_end = .; + . = ALIGN(0x10); + _heap_end = __heap_end; + } > ram + + .stack : ALIGN(0x10) + { + __stack_bottom = .; + . += STACK_SIZE; + __stack_top = .; + } > ram +} + diff --git a/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv-rv32-ram.ld b/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv-rv32-ram.ld new file mode 100644 index 0000000..e0707df --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv-rv32-ram.ld @@ -0,0 +1,150 @@ +/******************************************************************************* + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * file name : miv-rv32-ram.ld + * Mi-V soft processor linker script for creating a SoftConsole downloadable + * debug image executing in SRAM. + * + * This linker script assumes that a RAM is connected at on Mi-V soft processor + * memory space pointed by the reset vector address. + * + * NOTE : Modify the memory section address and the size according to your + * Libero design. + * For example: + * 1) If you want to download and step debug at a different RAM memory address in + * your design (For example TCM base address) than the one provided in this file. + * 2) The MIV_RV32, when used with MIV_ESS IP, provides ways to copy the executable + * HEX file from external Non-Volatile memory into the TCM at reset. In this + * case your executable must be linked to the TCM address. + * + * To know more about the memory map of the MIV_RV32 based Libero design, open + * the MIV_RV32 IP configurator and look for "Reset Vector Address" and the + * "Memory Map" tab. + * + */ + +OUTPUT_ARCH( "riscv" ) +ENTRY(_start) + +MEMORY +{ + ram (rwx) : ORIGIN = 0x80000000, LENGTH = 32k +} + +STACK_SIZE = 2k; /* needs to be calculated for your application */ +HEAP_SIZE = 0k; /* needs to be calculated for your application */ + +SECTIONS +{ + .entry : ALIGN(0x10) + { + KEEP (*(SORT_NONE(.entry))) + . = ALIGN(0x10); + } > ram + + .text : ALIGN(0x10) + { + *(.text .text.* .gnu.linkonce.t.*) + *(.plt) + . = ALIGN(0x10); + + KEEP (*crtbegin.o(.ctors)) + KEEP (*(EXCLUDE_FILE (*crtend.o) .ctors)) + KEEP (*(SORT(.ctors.*))) + KEEP (*crtend.o(.ctors)) + KEEP (*crtbegin.o(.dtors)) + KEEP (*(EXCLUDE_FILE (*crtend.o) .dtors)) + KEEP (*(SORT(.dtors.*))) + KEEP (*crtend.o(.dtors)) + + *(.rodata .rodata.* .gnu.linkonce.r.*) + *(.gcc_except_table) + *(.eh_frame_hdr) + *(.eh_frame) + + KEEP (*(.init)) + KEEP (*(.fini)) + + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP (*(.preinit_array)) + PROVIDE_HIDDEN (__preinit_array_end = .); + PROVIDE_HIDDEN (__init_array_start = .); + KEEP (*(SORT(.init_array.*))) + KEEP (*(.init_array)) + PROVIDE_HIDDEN (__init_array_end = .); + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP (*(.fini_array)) + KEEP (*(SORT(.fini_array.*))) + PROVIDE_HIDDEN (__fini_array_end = .); + . = ALIGN(0x10); + + } > ram + + /* short/global data section */ + .sdata : ALIGN(0x10) + { + __sdata_load = LOADADDR(.sdata); + __sdata_start = .; + PROVIDE( __global_pointer$ = . + 0x800); + *(.srodata.cst16) *(.srodata.cst8) *(.srodata.cst4) *(.srodata.cst2) + *(.srodata*) + *(.sdata .sdata.* .gnu.linkonce.s.*) + . = ALIGN(0x10); + __sdata_end = .; + } > ram + + /* data section */ + .data : ALIGN(0x10) + { + __data_load = LOADADDR(.data); + __data_start = .; + *(.got.plt) *(.got) + *(.shdata) + *(.data .data.* .gnu.linkonce.d.*) + . = ALIGN(0x10); + __data_end = .; + } > ram + + /* sbss section */ + .sbss : ALIGN(0x10) + { + __sbss_start = .; + *(.sbss .sbss.* .gnu.linkonce.sb.*) + *(.scommon) + . = ALIGN(0x10); + __sbss_end = .; + } > ram + + /* sbss section */ + .bss : ALIGN(0x10) + { + __bss_start = .; + *(.shbss) + *(.bss .bss.* .gnu.linkonce.b.*) + *(COMMON) + . = ALIGN(0x10); + __bss_end = .; + } > ram + + /* End of uninitialized data segment */ + _end = .; + + .heap : ALIGN(0x10) + { + __heap_start = .; + . += HEAP_SIZE; + __heap_end = .; + . = ALIGN(0x10); + _heap_end = __heap_end; + } > ram + + .stack : ALIGN(0x10) + { + __stack_bottom = .; + . += STACK_SIZE; + __stack_top = .; + } > ram +} + diff --git a/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv_rv32_entry.S b/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv_rv32_entry.S new file mode 100644 index 0000000..a19a813 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv_rv32_entry.S @@ -0,0 +1,821 @@ +/******************************************************************************* + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file miv_rv32_entry.S + * @author Microchip FPGA Embedded Systems Solutions + * @brief Mi-V soft processor vectors, trap handling and startup code. + * + */ +#ifndef ENTRY_S +#define ENTRY_S + +#define A_EXTENSION_MASK 0x00000001u +#define MTVEC_MODE_BIT_MASK 0x00000003u +#define MTVEC_VECTORED_MODE_VAL 0x00000001u + +#if __riscv_xlen == 64 +# define LREG ld +# define SREG sd +# define REGBYTES 8 +#else +# define LREG lw +# define SREG sw +# define REGBYTES 4 +#endif + + .section .entry, "ax" + .globl _start + +_start: + j handle_reset + +/* Some of the Mi-V soft IP cores support compressed 'C' extension. If the Mi-V + core in your design doesn't support 'C' extension and you enable 'C' extension + in firmware project compiler options, then it would result in a trap. For this + case, we are avoiding compressed instruction here so you can put a breakpoint + at the jump and you can at least look at mcause, mepc and get some hints + about the crash. */ +trap_entry: +.option push +.option norvc +j generic_trap_handler +.option pop + .word 0 + .word 0 + +sw_trap_entry: + j vector_sw_trap_handler +#ifdef __riscv_compressed + .2byte 0 +#endif + .word 0 + .word 0 + .word 0 + +tmr_trap_entry: + j vector_tmr_trap_handler +#ifdef __riscv_compressed + .2byte 0 +#endif + .word 0 + .word 0 + .word 0 + +ext_trap_entry: + j vector_ext_trap_handler +#ifdef __riscv_compressed + .2byte 0 +#endif + .word 0 + .word 0 + .word 0 + .word 0 + +#ifndef MIV_LEGACY_RV32 +MGEUI_trap_entry: + j vector_MGEUI_trap_handler +#ifdef __riscv_compressed + .2byte 0 +#endif + +MGECI_trap_entry: + j vector_MGECI_trap_handler +#ifdef __riscv_compressed + .2byte 0 +#endif + .word 0 + .word 0 + .word 0 + .word 0 + .word 0 + .word 0 + +MSYS_EI0_trap_entry: + j vector_MSYS_EI0_trap_handler +#ifdef __riscv_compressed + .2byte 0 +#endif + +MSYS_EI1_trap_entry: + j vector_MSYS_EI1_trap_handler +#ifdef __riscv_compressed + .2byte 0 +#endif + +MSYS_EI2_trap_entry: + j vector_MSYS_EI2_trap_handler +#ifdef __riscv_compressed + .2byte 0 +#endif + +MSYS_EI3_trap_entry: + j vector_MSYS_EI3_trap_handler +#ifdef __riscv_compressed + .2byte 0 +#endif + +MSYS_EI4_trap_entry: + j vector_MSYS_EI4_trap_handler +#ifdef __riscv_compressed + .2byte 0 +#endif + +MSYS_EI5_trap_entry: + j vector_MSYS_EI5_trap_handler +#ifdef __riscv_compressed + .2byte 0 +#endif + +#ifdef __riscv_compressed + .2byte 0 +#endif + +OPSRV_trap_entry: + j vector_OPSRV_IRQHandler +#endif /* MIV_LEGACY_RV32 */ + +.align 4 +generic_trap_handler: + addi sp, sp, -32*REGBYTES +.align 4 + SREG x1, 0 * REGBYTES(sp) + SREG x2, 1 * REGBYTES(sp) + SREG x3, 2 * REGBYTES(sp) + SREG x4, 3 * REGBYTES(sp) + SREG x5, 4 * REGBYTES(sp) + SREG x6, 5 * REGBYTES(sp) + SREG x7, 6 * REGBYTES(sp) + SREG x8, 7 * REGBYTES(sp) + SREG x9, 8 * REGBYTES(sp) + SREG x10, 9 * REGBYTES(sp) + SREG x11, 10 * REGBYTES(sp) + SREG x12, 11 * REGBYTES(sp) + SREG x13, 12 * REGBYTES(sp) + SREG x14, 13 * REGBYTES(sp) + SREG x15, 14 * REGBYTES(sp) + SREG x16, 15 * REGBYTES(sp) + SREG x17, 16 * REGBYTES(sp) + SREG x18, 17 * REGBYTES(sp) + SREG x19, 18 * REGBYTES(sp) + SREG x20, 19 * REGBYTES(sp) + SREG x21, 20 * REGBYTES(sp) + SREG x22, 21 * REGBYTES(sp) + SREG x23, 22 * REGBYTES(sp) + SREG x24, 23 * REGBYTES(sp) + SREG x25, 24 * REGBYTES(sp) + SREG x26, 25 * REGBYTES(sp) + SREG x27, 26 * REGBYTES(sp) + SREG x28, 27 * REGBYTES(sp) + SREG x29, 28 * REGBYTES(sp) + SREG x30, 29 * REGBYTES(sp) + SREG x31, 30 * REGBYTES(sp) + + csrr a0, mcause + csrr a1, mepc + jal handle_trap + j generic_restore + +vector_sw_trap_handler: + addi sp, sp, -32*REGBYTES + + SREG x1, 0 * REGBYTES(sp) + SREG x2, 1 * REGBYTES(sp) + SREG x3, 2 * REGBYTES(sp) + SREG x4, 3 * REGBYTES(sp) + SREG x5, 4 * REGBYTES(sp) + SREG x6, 5 * REGBYTES(sp) + SREG x7, 6 * REGBYTES(sp) + SREG x8, 7 * REGBYTES(sp) + SREG x9, 8 * REGBYTES(sp) + SREG x10, 9 * REGBYTES(sp) + SREG x11, 10 * REGBYTES(sp) + SREG x12, 11 * REGBYTES(sp) + SREG x13, 12 * REGBYTES(sp) + SREG x14, 13 * REGBYTES(sp) + SREG x15, 14 * REGBYTES(sp) + SREG x16, 15 * REGBYTES(sp) + SREG x17, 16 * REGBYTES(sp) + SREG x18, 17 * REGBYTES(sp) + SREG x19, 18 * REGBYTES(sp) + SREG x20, 19 * REGBYTES(sp) + SREG x21, 20 * REGBYTES(sp) + SREG x22, 21 * REGBYTES(sp) + SREG x23, 22 * REGBYTES(sp) + SREG x24, 23 * REGBYTES(sp) + SREG x25, 24 * REGBYTES(sp) + SREG x26, 25 * REGBYTES(sp) + SREG x27, 26 * REGBYTES(sp) + SREG x28, 27 * REGBYTES(sp) + SREG x29, 28 * REGBYTES(sp) + SREG x30, 29 * REGBYTES(sp) + SREG x31, 30 * REGBYTES(sp) + + jal handle_m_soft_interrupt + j generic_restore + +vector_tmr_trap_handler: + addi sp, sp, -32*REGBYTES + + SREG x1, 0 * REGBYTES(sp) + SREG x2, 1 * REGBYTES(sp) + SREG x3, 2 * REGBYTES(sp) + SREG x4, 3 * REGBYTES(sp) + SREG x5, 4 * REGBYTES(sp) + SREG x6, 5 * REGBYTES(sp) + SREG x7, 6 * REGBYTES(sp) + SREG x8, 7 * REGBYTES(sp) + SREG x9, 8 * REGBYTES(sp) + SREG x10, 9 * REGBYTES(sp) + SREG x11, 10 * REGBYTES(sp) + SREG x12, 11 * REGBYTES(sp) + SREG x13, 12 * REGBYTES(sp) + SREG x14, 13 * REGBYTES(sp) + SREG x15, 14 * REGBYTES(sp) + SREG x16, 15 * REGBYTES(sp) + SREG x17, 16 * REGBYTES(sp) + SREG x18, 17 * REGBYTES(sp) + SREG x19, 18 * REGBYTES(sp) + SREG x20, 19 * REGBYTES(sp) + SREG x21, 20 * REGBYTES(sp) + SREG x22, 21 * REGBYTES(sp) + SREG x23, 22 * REGBYTES(sp) + SREG x24, 23 * REGBYTES(sp) + SREG x25, 24 * REGBYTES(sp) + SREG x26, 25 * REGBYTES(sp) + SREG x27, 26 * REGBYTES(sp) + SREG x28, 27 * REGBYTES(sp) + SREG x29, 28 * REGBYTES(sp) + SREG x30, 29 * REGBYTES(sp) + SREG x31, 30 * REGBYTES(sp) + + jal handle_m_timer_interrupt + j generic_restore + +vector_ext_trap_handler: + addi sp, sp, -32*REGBYTES + + SREG x1, 0 * REGBYTES(sp) + SREG x2, 1 * REGBYTES(sp) + SREG x3, 2 * REGBYTES(sp) + SREG x4, 3 * REGBYTES(sp) + SREG x5, 4 * REGBYTES(sp) + SREG x6, 5 * REGBYTES(sp) + SREG x7, 6 * REGBYTES(sp) + SREG x8, 7 * REGBYTES(sp) + SREG x9, 8 * REGBYTES(sp) + SREG x10, 9 * REGBYTES(sp) + SREG x11, 10 * REGBYTES(sp) + SREG x12, 11 * REGBYTES(sp) + SREG x13, 12 * REGBYTES(sp) + SREG x14, 13 * REGBYTES(sp) + SREG x15, 14 * REGBYTES(sp) + SREG x16, 15 * REGBYTES(sp) + SREG x17, 16 * REGBYTES(sp) + SREG x18, 17 * REGBYTES(sp) + SREG x19, 18 * REGBYTES(sp) + SREG x20, 19 * REGBYTES(sp) + SREG x21, 20 * REGBYTES(sp) + SREG x22, 21 * REGBYTES(sp) + SREG x23, 22 * REGBYTES(sp) + SREG x24, 23 * REGBYTES(sp) + SREG x25, 24 * REGBYTES(sp) + SREG x26, 25 * REGBYTES(sp) + SREG x27, 26 * REGBYTES(sp) + SREG x28, 27 * REGBYTES(sp) + SREG x29, 28 * REGBYTES(sp) + SREG x30, 29 * REGBYTES(sp) + SREG x31, 30 * REGBYTES(sp) + +#ifdef MIV_LEGACY_RV32 + jal handle_m_ext_interrupt +#else + jal External_IRQHandler +#endif /* MIV_LEGACY_RV32 */ + j generic_restore + +#ifndef MIV_LEGACY_RV32 +vector_MGEUI_trap_handler: + addi sp, sp, -32*REGBYTES + + SREG x1, 0 * REGBYTES(sp) + SREG x2, 1 * REGBYTES(sp) + SREG x3, 2 * REGBYTES(sp) + SREG x4, 3 * REGBYTES(sp) + SREG x5, 4 * REGBYTES(sp) + SREG x6, 5 * REGBYTES(sp) + SREG x7, 6 * REGBYTES(sp) + SREG x8, 7 * REGBYTES(sp) + SREG x9, 8 * REGBYTES(sp) + SREG x10, 9 * REGBYTES(sp) + SREG x11, 10 * REGBYTES(sp) + SREG x12, 11 * REGBYTES(sp) + SREG x13, 12 * REGBYTES(sp) + SREG x14, 13 * REGBYTES(sp) + SREG x15, 14 * REGBYTES(sp) + SREG x16, 15 * REGBYTES(sp) + SREG x17, 16 * REGBYTES(sp) + SREG x18, 17 * REGBYTES(sp) + SREG x19, 18 * REGBYTES(sp) + SREG x20, 19 * REGBYTES(sp) + SREG x21, 20 * REGBYTES(sp) + SREG x22, 21 * REGBYTES(sp) + SREG x23, 22 * REGBYTES(sp) + SREG x24, 23 * REGBYTES(sp) + SREG x25, 24 * REGBYTES(sp) + SREG x26, 25 * REGBYTES(sp) + SREG x27, 26 * REGBYTES(sp) + SREG x28, 27 * REGBYTES(sp) + SREG x29, 28 * REGBYTES(sp) + SREG x30, 29 * REGBYTES(sp) + SREG x31, 30 * REGBYTES(sp) + + jal MGEUI_IRQHandler + j generic_restore + +vector_MGECI_trap_handler: + addi sp, sp, -32*REGBYTES + + SREG x1, 0 * REGBYTES(sp) + SREG x2, 1 * REGBYTES(sp) + SREG x3, 2 * REGBYTES(sp) + SREG x4, 3 * REGBYTES(sp) + SREG x5, 4 * REGBYTES(sp) + SREG x6, 5 * REGBYTES(sp) + SREG x7, 6 * REGBYTES(sp) + SREG x8, 7 * REGBYTES(sp) + SREG x9, 8 * REGBYTES(sp) + SREG x10, 9 * REGBYTES(sp) + SREG x11, 10 * REGBYTES(sp) + SREG x12, 11 * REGBYTES(sp) + SREG x13, 12 * REGBYTES(sp) + SREG x14, 13 * REGBYTES(sp) + SREG x15, 14 * REGBYTES(sp) + SREG x16, 15 * REGBYTES(sp) + SREG x17, 16 * REGBYTES(sp) + SREG x18, 17 * REGBYTES(sp) + SREG x19, 18 * REGBYTES(sp) + SREG x20, 19 * REGBYTES(sp) + SREG x21, 20 * REGBYTES(sp) + SREG x22, 21 * REGBYTES(sp) + SREG x23, 22 * REGBYTES(sp) + SREG x24, 23 * REGBYTES(sp) + SREG x25, 24 * REGBYTES(sp) + SREG x26, 25 * REGBYTES(sp) + SREG x27, 26 * REGBYTES(sp) + SREG x28, 27 * REGBYTES(sp) + SREG x29, 28 * REGBYTES(sp) + SREG x30, 29 * REGBYTES(sp) + SREG x31, 30 * REGBYTES(sp) + + jal MGECI_IRQHandler + j generic_restore + +vector_MSYS_EI0_trap_handler: + addi sp, sp, -32*REGBYTES + + SREG x1, 0 * REGBYTES(sp) + SREG x2, 1 * REGBYTES(sp) + SREG x3, 2 * REGBYTES(sp) + SREG x4, 3 * REGBYTES(sp) + SREG x5, 4 * REGBYTES(sp) + SREG x6, 5 * REGBYTES(sp) + SREG x7, 6 * REGBYTES(sp) + SREG x8, 7 * REGBYTES(sp) + SREG x9, 8 * REGBYTES(sp) + SREG x10, 9 * REGBYTES(sp) + SREG x11, 10 * REGBYTES(sp) + SREG x12, 11 * REGBYTES(sp) + SREG x13, 12 * REGBYTES(sp) + SREG x14, 13 * REGBYTES(sp) + SREG x15, 14 * REGBYTES(sp) + SREG x16, 15 * REGBYTES(sp) + SREG x17, 16 * REGBYTES(sp) + SREG x18, 17 * REGBYTES(sp) + SREG x19, 18 * REGBYTES(sp) + SREG x20, 19 * REGBYTES(sp) + SREG x21, 20 * REGBYTES(sp) + SREG x22, 21 * REGBYTES(sp) + SREG x23, 22 * REGBYTES(sp) + SREG x24, 23 * REGBYTES(sp) + SREG x25, 24 * REGBYTES(sp) + SREG x26, 25 * REGBYTES(sp) + SREG x27, 26 * REGBYTES(sp) + SREG x28, 27 * REGBYTES(sp) + SREG x29, 28 * REGBYTES(sp) + SREG x30, 29 * REGBYTES(sp) + SREG x31, 30 * REGBYTES(sp) + + jal MSYS_EI0_IRQHandler + j generic_restore + +vector_MSYS_EI1_trap_handler: + addi sp, sp, -32*REGBYTES + + SREG x1, 0 * REGBYTES(sp) + SREG x2, 1 * REGBYTES(sp) + SREG x3, 2 * REGBYTES(sp) + SREG x4, 3 * REGBYTES(sp) + SREG x5, 4 * REGBYTES(sp) + SREG x6, 5 * REGBYTES(sp) + SREG x7, 6 * REGBYTES(sp) + SREG x8, 7 * REGBYTES(sp) + SREG x9, 8 * REGBYTES(sp) + SREG x10, 9 * REGBYTES(sp) + SREG x11, 10 * REGBYTES(sp) + SREG x12, 11 * REGBYTES(sp) + SREG x13, 12 * REGBYTES(sp) + SREG x14, 13 * REGBYTES(sp) + SREG x15, 14 * REGBYTES(sp) + SREG x16, 15 * REGBYTES(sp) + SREG x17, 16 * REGBYTES(sp) + SREG x18, 17 * REGBYTES(sp) + SREG x19, 18 * REGBYTES(sp) + SREG x20, 19 * REGBYTES(sp) + SREG x21, 20 * REGBYTES(sp) + SREG x22, 21 * REGBYTES(sp) + SREG x23, 22 * REGBYTES(sp) + SREG x24, 23 * REGBYTES(sp) + SREG x25, 24 * REGBYTES(sp) + SREG x26, 25 * REGBYTES(sp) + SREG x27, 26 * REGBYTES(sp) + SREG x28, 27 * REGBYTES(sp) + SREG x29, 28 * REGBYTES(sp) + SREG x30, 29 * REGBYTES(sp) + SREG x31, 30 * REGBYTES(sp) + + jal MSYS_EI1_IRQHandler + j generic_restore + +vector_MSYS_EI2_trap_handler: + addi sp, sp, -32*REGBYTES + + SREG x1, 0 * REGBYTES(sp) + SREG x2, 1 * REGBYTES(sp) + SREG x3, 2 * REGBYTES(sp) + SREG x4, 3 * REGBYTES(sp) + SREG x5, 4 * REGBYTES(sp) + SREG x6, 5 * REGBYTES(sp) + SREG x7, 6 * REGBYTES(sp) + SREG x8, 7 * REGBYTES(sp) + SREG x9, 8 * REGBYTES(sp) + SREG x10, 9 * REGBYTES(sp) + SREG x11, 10 * REGBYTES(sp) + SREG x12, 11 * REGBYTES(sp) + SREG x13, 12 * REGBYTES(sp) + SREG x14, 13 * REGBYTES(sp) + SREG x15, 14 * REGBYTES(sp) + SREG x16, 15 * REGBYTES(sp) + SREG x17, 16 * REGBYTES(sp) + SREG x18, 17 * REGBYTES(sp) + SREG x19, 18 * REGBYTES(sp) + SREG x20, 19 * REGBYTES(sp) + SREG x21, 20 * REGBYTES(sp) + SREG x22, 21 * REGBYTES(sp) + SREG x23, 22 * REGBYTES(sp) + SREG x24, 23 * REGBYTES(sp) + SREG x25, 24 * REGBYTES(sp) + SREG x26, 25 * REGBYTES(sp) + SREG x27, 26 * REGBYTES(sp) + SREG x28, 27 * REGBYTES(sp) + SREG x29, 28 * REGBYTES(sp) + SREG x30, 29 * REGBYTES(sp) + SREG x31, 30 * REGBYTES(sp) + + jal MSYS_EI2_IRQHandler + j generic_restore + +vector_MSYS_EI3_trap_handler: + addi sp, sp, -32*REGBYTES + + SREG x1, 0 * REGBYTES(sp) + SREG x2, 1 * REGBYTES(sp) + SREG x3, 2 * REGBYTES(sp) + SREG x4, 3 * REGBYTES(sp) + SREG x5, 4 * REGBYTES(sp) + SREG x6, 5 * REGBYTES(sp) + SREG x7, 6 * REGBYTES(sp) + SREG x8, 7 * REGBYTES(sp) + SREG x9, 8 * REGBYTES(sp) + SREG x10, 9 * REGBYTES(sp) + SREG x11, 10 * REGBYTES(sp) + SREG x12, 11 * REGBYTES(sp) + SREG x13, 12 * REGBYTES(sp) + SREG x14, 13 * REGBYTES(sp) + SREG x15, 14 * REGBYTES(sp) + SREG x16, 15 * REGBYTES(sp) + SREG x17, 16 * REGBYTES(sp) + SREG x18, 17 * REGBYTES(sp) + SREG x19, 18 * REGBYTES(sp) + SREG x20, 19 * REGBYTES(sp) + SREG x21, 20 * REGBYTES(sp) + SREG x22, 21 * REGBYTES(sp) + SREG x23, 22 * REGBYTES(sp) + SREG x24, 23 * REGBYTES(sp) + SREG x25, 24 * REGBYTES(sp) + SREG x26, 25 * REGBYTES(sp) + SREG x27, 26 * REGBYTES(sp) + SREG x28, 27 * REGBYTES(sp) + SREG x29, 28 * REGBYTES(sp) + SREG x30, 29 * REGBYTES(sp) + SREG x31, 30 * REGBYTES(sp) + + jal MSYS_EI3_IRQHandler + j generic_restore + +vector_MSYS_EI4_trap_handler: + addi sp, sp, -32*REGBYTES + + SREG x1, 0 * REGBYTES(sp) + SREG x2, 1 * REGBYTES(sp) + SREG x3, 2 * REGBYTES(sp) + SREG x4, 3 * REGBYTES(sp) + SREG x5, 4 * REGBYTES(sp) + SREG x6, 5 * REGBYTES(sp) + SREG x7, 6 * REGBYTES(sp) + SREG x8, 7 * REGBYTES(sp) + SREG x9, 8 * REGBYTES(sp) + SREG x10, 9 * REGBYTES(sp) + SREG x11, 10 * REGBYTES(sp) + SREG x12, 11 * REGBYTES(sp) + SREG x13, 12 * REGBYTES(sp) + SREG x14, 13 * REGBYTES(sp) + SREG x15, 14 * REGBYTES(sp) + SREG x16, 15 * REGBYTES(sp) + SREG x17, 16 * REGBYTES(sp) + SREG x18, 17 * REGBYTES(sp) + SREG x19, 18 * REGBYTES(sp) + SREG x20, 19 * REGBYTES(sp) + SREG x21, 20 * REGBYTES(sp) + SREG x22, 21 * REGBYTES(sp) + SREG x23, 22 * REGBYTES(sp) + SREG x24, 23 * REGBYTES(sp) + SREG x25, 24 * REGBYTES(sp) + SREG x26, 25 * REGBYTES(sp) + SREG x27, 26 * REGBYTES(sp) + SREG x28, 27 * REGBYTES(sp) + SREG x29, 28 * REGBYTES(sp) + SREG x30, 29 * REGBYTES(sp) + SREG x31, 30 * REGBYTES(sp) + + jal MSYS_EI4_IRQHandler + j generic_restore + +vector_MSYS_EI5_trap_handler: + addi sp, sp, -32*REGBYTES + + SREG x1, 0 * REGBYTES(sp) + SREG x2, 1 * REGBYTES(sp) + SREG x3, 2 * REGBYTES(sp) + SREG x4, 3 * REGBYTES(sp) + SREG x5, 4 * REGBYTES(sp) + SREG x6, 5 * REGBYTES(sp) + SREG x7, 6 * REGBYTES(sp) + SREG x8, 7 * REGBYTES(sp) + SREG x9, 8 * REGBYTES(sp) + SREG x10, 9 * REGBYTES(sp) + SREG x11, 10 * REGBYTES(sp) + SREG x12, 11 * REGBYTES(sp) + SREG x13, 12 * REGBYTES(sp) + SREG x14, 13 * REGBYTES(sp) + SREG x15, 14 * REGBYTES(sp) + SREG x16, 15 * REGBYTES(sp) + SREG x17, 16 * REGBYTES(sp) + SREG x18, 17 * REGBYTES(sp) + SREG x19, 18 * REGBYTES(sp) + SREG x20, 19 * REGBYTES(sp) + SREG x21, 20 * REGBYTES(sp) + SREG x22, 21 * REGBYTES(sp) + SREG x23, 22 * REGBYTES(sp) + SREG x24, 23 * REGBYTES(sp) + SREG x25, 24 * REGBYTES(sp) + SREG x26, 25 * REGBYTES(sp) + SREG x27, 26 * REGBYTES(sp) + SREG x28, 27 * REGBYTES(sp) + SREG x29, 28 * REGBYTES(sp) + SREG x30, 29 * REGBYTES(sp) + SREG x31, 30 * REGBYTES(sp) + + jal MSYS_EI5_IRQHandler + j generic_restore + +vector_OPSRV_IRQHandler: + addi sp, sp, -32*REGBYTES + + SREG x1, 0 * REGBYTES(sp) + SREG x2, 1 * REGBYTES(sp) + SREG x3, 2 * REGBYTES(sp) + SREG x4, 3 * REGBYTES(sp) + SREG x5, 4 * REGBYTES(sp) + SREG x6, 5 * REGBYTES(sp) + SREG x7, 6 * REGBYTES(sp) + SREG x8, 7 * REGBYTES(sp) + SREG x9, 8 * REGBYTES(sp) + SREG x10, 9 * REGBYTES(sp) + SREG x11, 10 * REGBYTES(sp) + SREG x12, 11 * REGBYTES(sp) + SREG x13, 12 * REGBYTES(sp) + SREG x14, 13 * REGBYTES(sp) + SREG x15, 14 * REGBYTES(sp) + SREG x16, 15 * REGBYTES(sp) + SREG x17, 16 * REGBYTES(sp) + SREG x18, 17 * REGBYTES(sp) + SREG x19, 18 * REGBYTES(sp) + SREG x20, 19 * REGBYTES(sp) + SREG x21, 20 * REGBYTES(sp) + SREG x22, 21 * REGBYTES(sp) + SREG x23, 22 * REGBYTES(sp) + SREG x24, 23 * REGBYTES(sp) + SREG x25, 24 * REGBYTES(sp) + SREG x26, 25 * REGBYTES(sp) + SREG x27, 26 * REGBYTES(sp) + SREG x28, 27 * REGBYTES(sp) + SREG x29, 28 * REGBYTES(sp) + SREG x30, 29 * REGBYTES(sp) + SREG x31, 30 * REGBYTES(sp) + + jal OPSRV_IRQHandler + j generic_restore +#endif /* MIV_LEGACY_RV32 */ + +generic_restore: + LREG x1, 0 * REGBYTES(sp) + LREG x2, 1 * REGBYTES(sp) + LREG x3, 2 * REGBYTES(sp) + LREG x4, 3 * REGBYTES(sp) + LREG x5, 4 * REGBYTES(sp) + LREG x6, 5 * REGBYTES(sp) + LREG x7, 6 * REGBYTES(sp) + LREG x8, 7 * REGBYTES(sp) + LREG x9, 8 * REGBYTES(sp) + LREG x10, 9 * REGBYTES(sp) + LREG x11, 10 * REGBYTES(sp) + LREG x12, 11 * REGBYTES(sp) + LREG x13, 12 * REGBYTES(sp) + LREG x14, 13 * REGBYTES(sp) + LREG x15, 14 * REGBYTES(sp) + LREG x16, 15 * REGBYTES(sp) + LREG x17, 16 * REGBYTES(sp) + LREG x18, 17 * REGBYTES(sp) + LREG x19, 18 * REGBYTES(sp) + LREG x20, 19 * REGBYTES(sp) + LREG x21, 20 * REGBYTES(sp) + LREG x22, 21 * REGBYTES(sp) + LREG x23, 22 * REGBYTES(sp) + LREG x24, 23 * REGBYTES(sp) + LREG x25, 24 * REGBYTES(sp) + LREG x26, 25 * REGBYTES(sp) + LREG x27, 26 * REGBYTES(sp) + LREG x28, 27 * REGBYTES(sp) + LREG x29, 28 * REGBYTES(sp) + LREG x30, 29 * REGBYTES(sp) + LREG x31, 30 * REGBYTES(sp) + + addi sp, sp, 32*REGBYTES + mret + + .section .text, "ax" +handle_reset: +/* Ensure instructions are not relaxed, since gp is not yet set */ +.option push +.option norelax + + csrwi mstatus, 0 + csrwi mie, 0 + la ra, _start + + csrr t0, misa + andi t0, t0, A_EXTENSION_MASK + bnez t0, ima_cores_setup /* Jump to IMA core handling */ + +/* For MIV_RV32 cores the mtvec exception base address is fixed at Reset vector + address + 0x4. Check the mode bits. */ + csrr t0, mtvec + andi t0, t0, MTVEC_MODE_BIT_MASK + li t1, MTVEC_VECTORED_MODE_VAL + bne t0, t1, ima_cores_setup /* Jump to IMA core handling */ + + /* When mode = 1 => this is vectored mode on MIV_RV32 core. + Verify that the trap_handler address matches the configuration in MTVEC */ + csrr t0, mtvec + andi t0, t0, 0xFFFFFFFC + la t1, trap_entry + bne t0, t1, vector_address_not_matching + j generic_reset_handling + +ima_cores_setup: + la t0, trap_entry + +#ifdef MIV_LEGACY_RV32_VECTORED_INTERRUPTS + addi t0, t0, 0x01 /* Set the mode bit for IMA cores. + For MIV_RV32 cores this is done by configurator. */ +#endif + csrw mtvec, t0 + +generic_reset_handling: +/* Copy sdata section first so that the gp is set and linker relaxation can be + used */ + la a4, __sdata_load + la a5, __sdata_start + la a6, __sdata_end + beq a4, a5, 1f /* Exit if source and dest are same */ + beq a5, a6, 1f /* Exit if section start and end addresses are same */ + call block_copy + +1: + /* initialize global pointer */ + la gp, __global_pointer$ + +.option pop + +/* Floating point support configuration */ +#ifdef __riscv_flen + csrr t0, mstatus + lui t1, 0xffffa + addi t1, t1, -1 + and t0, t0, t1 + lui t1, 0x4 + or t1, t0, t1 + csrw mstatus, t1 + + lui t0, 0x0 + fscsr t0 +#endif + call initializations + /* Initialize stack pointer */ + la sp, __stack_top + + /* Jump into C code */ + j _init + +/* Error: trap_entry is not at the expected address of reset_vector+mtvec offset + as configured in the MIV_RV32 core vectored mode */ +vector_address_not_matching: + ebreak + +initializations: +/* Initialize the .bss section */ + mv t0, ra /* Store ra for future use */ + la a5, __bss_start + la a6, __bss_end + beq a5, a6, 1f /* Section start and end address are the same */ + call zeroize_block + +1: +/* Initialize the .sbss section */ + la a5, __sbss_start + la a6, __sbss_end + beq a5, a6, 1f /* Section start and end address are the same */ + call zeroize_block + +/* Clear heap */ + la a5, __heap_start + la a6, __heap_end + beq a5, a6, 1f /* Section start and end address are the same */ + call zeroize_block + +1: +/* Copy data section */ + la a4, __data_load + la a5, __data_start + la a6, __data_end + beq a4, a5, 1f /* Exit early if source and dest are same */ + beq a5, a6, 1f /* Section start and end addresses are the same */ + call block_copy + +1: + mv ra, t0 /* Retrieve ra */ + ret + +zeroize_block: + bltu a6, a5, block_copy_error /* Error. End address is less than start */ + or a7, a6, a5 /* Check if start or end is unalined */ + andi a7, a7, 0x03u + bgtz a7, block_copy_error /* Unaligned addresses error*/ +zeroize_loop: + sw x0, 0(a5) + add a5, a5, __SIZEOF_POINTER__ + blt a5, a6, zeroize_loop + ret + +block_copy: + bltu a6, a5, block_copy_error /* Error. End address is less than start */ + or a7, a6, a5 /* Check if start or end is unalined */ + andi a7, a7, 0x03u + bgtz a7, block_copy_error /* Unaligned addresses error*/ +block_copy_loop: + lw a7, 0(a4) + sw a7, 0(a5) + addi a5, a5, 0x04 + addi a4, a4, 0x04 + blt a5, a6, block_copy_loop + j block_copy_exit + +block_copy_error: + j block_copy_error + +block_copy_exit: + ret + +#endif /*ENTRY_S*/ diff --git a/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv_rv32_hal.c b/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv_rv32_hal.c new file mode 100644 index 0000000..8fa82b1 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv_rv32_hal.c @@ -0,0 +1,327 @@ +/******************************************************************************* + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file miv_rv32_hal.c + * @author Microchip FPGA Embedded Systems Solutions + * @brief Implementation of Hardware Abstraction Layer for Mi-V soft processors + * + */ +#include +#include "miv_rv32_hal.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define SUCCESS 0U +#define ERROR 1U +#define MASK_32BIT 0xFFFFFFFFu + +/*------------------------------------------------------------------------------ + * Write in a sequence recommended by privileged spec to avoid spurious + * interrupts + + # New comparand is in a1:a0. + li t0, -1 + sw t0, mtimecmp # No smaller than old value. + sw a1, mtimecmp+4 # No smaller than new value. + sw a0, mtimecmp # New value. + */ +#define WRITE_MTIMECMP(value) MTIMECMPH = MASK_32BIT; \ + MTIMECMP = value & MASK_32BIT;\ + MTIMECMPH = (value >> 32u) & MASK_32BIT; + +#define WRITE_MTIME(value) MTIME = value & MASK_32BIT;\ + MTIMEH = (value >> 32u) & MASK_32BIT; + +extern void Software_IRQHandler(void); + +#ifdef MIV_LEGACY_RV32 +#define MTIME_PRESCALER 100UL +/*------------------------------------------------------------------------------ + * + */ +uint8_t Invalid_IRQHandler(void); +uint8_t External_1_IRQHandler(void); +uint8_t External_2_IRQHandler(void); +uint8_t External_3_IRQHandler(void); +uint8_t External_4_IRQHandler(void); +uint8_t External_5_IRQHandler(void); +uint8_t External_6_IRQHandler(void); +uint8_t External_7_IRQHandler(void); +uint8_t External_8_IRQHandler(void); +uint8_t External_9_IRQHandler(void); +uint8_t External_10_IRQHandler(void); +uint8_t External_11_IRQHandler(void); +uint8_t External_12_IRQHandler(void); +uint8_t External_13_IRQHandler(void); +uint8_t External_14_IRQHandler(void); +uint8_t External_15_IRQHandler(void); +uint8_t External_16_IRQHandler(void); +uint8_t External_17_IRQHandler(void); +uint8_t External_18_IRQHandler(void); +uint8_t External_19_IRQHandler(void); +uint8_t External_20_IRQHandler(void); +uint8_t External_21_IRQHandler(void); +uint8_t External_22_IRQHandler(void); +uint8_t External_23_IRQHandler(void); +uint8_t External_24_IRQHandler(void); +uint8_t External_25_IRQHandler(void); +uint8_t External_26_IRQHandler(void); +uint8_t External_27_IRQHandler(void); +uint8_t External_28_IRQHandler(void); +uint8_t External_29_IRQHandler(void); +uint8_t External_30_IRQHandler(void); +uint8_t External_31_IRQHandler(void); + + +/*------------------------------------------------------------------------------ + * RISC-V interrupt handler for external interrupts. + */ +uint8_t (* const ext_irq_handler_table[32])(void) = +{ + + Invalid_IRQHandler, + External_1_IRQHandler, + External_2_IRQHandler, + External_3_IRQHandler, + External_4_IRQHandler, + External_5_IRQHandler, + External_6_IRQHandler, + External_7_IRQHandler, + External_8_IRQHandler, + External_9_IRQHandler, + External_10_IRQHandler, + External_11_IRQHandler, + External_12_IRQHandler, + External_13_IRQHandler, + External_14_IRQHandler, + External_15_IRQHandler, + External_16_IRQHandler, + External_17_IRQHandler, + External_18_IRQHandler, + External_19_IRQHandler, + External_20_IRQHandler, + External_21_IRQHandler, + External_22_IRQHandler, + External_23_IRQHandler, + External_24_IRQHandler, + External_25_IRQHandler, + External_26_IRQHandler, + External_27_IRQHandler, + External_28_IRQHandler, + External_29_IRQHandler, + External_30_IRQHandler, + External_31_IRQHandler +}; + +#else +/*------------------------------------------------------------------------------ + * Interrupt handlers as mapped into the MIE register of the MIV_RV32 + */ +extern void External_IRQHandler(void); +extern void MGEUI_IRQHandler(void); +extern void MGECI_IRQHandler(void); +extern void MSYS_EI0_IRQHandler(void); +extern void MSYS_EI1_IRQHandler(void); +extern void MSYS_EI2_IRQHandler(void); +extern void MSYS_EI3_IRQHandler(void); +extern void MSYS_EI4_IRQHandler(void); +extern void MSYS_EI5_IRQHandler(void); +extern void OPSRV_IRQHandler(void); + +#endif + +/*------------------------------------------------------------------------------ + * Increment value for the mtimecmp register in order to achieve a system tick + * interrupt as specified through the MRV_systick_config() function. + */ +static uint64_t g_systick_increment = 0U; + +/*------------------------------------------------------------------------------ + * Configure the machine timer to generate an interrupt. + */ +uint32_t MRV_systick_config(uint64_t ticks) +{ + uint32_t ret_val = ERROR; + + g_systick_increment = (uint64_t)(ticks) / MTIME_PRESCALER; + + if (g_systick_increment > 0U) + { + +#ifndef MIV_RV32_EXT_TIMECMP + WRITE_MTIMECMP(MRV_read_mtime() + g_systick_increment) +#endif + set_csr(mie, MIP_MTIP); + MRV_enable_interrupts(); + + ret_val = SUCCESS; + } + + return ret_val; +} + +/*------------------------------------------------------------------------------ + * RISC-V interrupt handler for machine timer interrupts. + */ +void handle_m_timer_interrupt(void) +{ +#ifndef MIV_RV32_EXT_TIMECMP + WRITE_MTIMECMP(MRV_read_mtime() + g_systick_increment) +#endif + SysTick_Handler(); +} + +/*------------------------------------------------------------------------------ + * RISC-V interrupt handler for software interrupts. + */ +#ifdef MIV_LEGACY_RV32 +void handle_m_ext_interrupt(void) +{ + unsigned long hart_id = read_csr(mhartid); + uint32_t int_num = PLIC->TARGET[hart_id].CLAIM_COMPLETE; + uint8_t disable = EXT_IRQ_KEEP_ENABLED; + + if (0u !=int_num) + { + disable = ext_irq_handler_table[int_num](); + + PLIC->TARGET[hart_id].CLAIM_COMPLETE = int_num; + + if(EXT_IRQ_DISABLE == disable) + { + MRV_PLIC_disable_irq((IRQn_Type)int_num); + } + } +} +#endif + +void handle_m_soft_interrupt(void) +{ + Software_IRQHandler(); + MRV_clear_soft_irq(); +} + +/*------------------------------------------------------------------------------ + * Trap handler. This function is invoked in the non-vectored mode. + */ +void handle_trap(uintptr_t mcause, uintptr_t mepc) +{ + if ((mcause & MCAUSE_INT) && ((mcause & MCAUSE_CAUSE) == IRQ_M_SOFT)) + { + handle_m_soft_interrupt(); + } + else if ((mcause & MCAUSE_INT) && ((mcause & MCAUSE_CAUSE) == IRQ_M_TIMER)) + { + handle_m_timer_interrupt(); + } + else if ((mcause & MCAUSE_INT) && ((mcause & MCAUSE_CAUSE) == IRQ_M_EXT)) + { +#ifdef MIV_LEGACY_RV32 + handle_m_ext_interrupt(); +#else + External_IRQHandler(); +#endif + } +#ifndef MIV_LEGACY_RV32 + else if ((mcause & MCAUSE_INT) && ((mcause & MCAUSE_CAUSE) == MSYS_EI0)) + { + MSYS_EI0_IRQHandler(); + } + else if ((mcause & MCAUSE_INT) && ((mcause & MCAUSE_CAUSE) == MSYS_EI1)) + { + MSYS_EI1_IRQHandler(); + } + else if ((mcause & MCAUSE_INT) && ((mcause & MCAUSE_CAUSE) == MSYS_EI2)) + { + MSYS_EI2_IRQHandler(); + } + else if ((mcause & MCAUSE_INT) && ((mcause & MCAUSE_CAUSE) == MSYS_EI3)) + { + MSYS_EI3_IRQHandler(); + } + else if ((mcause & MCAUSE_INT) && ((mcause & MCAUSE_CAUSE) == MSYS_EI4)) + { + MSYS_EI4_IRQHandler(); + } + else if ((mcause & MCAUSE_INT) && ((mcause & MCAUSE_CAUSE) == MSYS_EI5)) + { + MSYS_EI5_IRQHandler(); + } + else if ((mcause & MCAUSE_INT) && ((mcause & MCAUSE_CAUSE) == OPSRV_REG)) + { + OPSRV_IRQHandler(); + } + else if ((mcause & MCAUSE_INT) && ((mcause & MCAUSE_CAUSE) == MGEUI)) + { + MGEUI_IRQHandler(); + } + else if ((mcause & MCAUSE_INT) && ((mcause & MCAUSE_CAUSE) == MGECI)) + { + MGECI_IRQHandler(); + } +#endif + + else + { +#ifndef NDEBUG + /* + Arguments supplied to this function are mcause, mepc (exception PC) and + stack pointer. + Based on privileged-isa specification mcause values and meanings are: + + 0 Instruction address misaligned (mtval/mtval is the address) + 1 Instruction access fault (mtval/mtval is the address) + 2 Illegal instruction (mtval/mtval contains the + offending instruction opcode) + 3 Breakpoint + 4 Load address misaligned (mtval/mtval is the address) + 5 Load address fault (mtval/mtval is the address) + 6 Store/AMO address fault (mtval/mtval is the address) + 7 Store/AMO access fault (mtval/mtval is the address) + 8 Environment call from U-mode + 9 Environment call from S-mode + A Environment call from M-mode + B Instruction page fault + C Load page fault (mtval/mtval is the address) + E Store page fault (mtval/mtval is the address) + + # Please note: mtval is the newer name for register mbadaddr + # If you get a compile failure here, use the older name. + # At this point, both are supported in latest compiler, older compiler + # versions only support mbadaddr. + # See: https://github.com/riscv/riscv-gcc/issues/133 + */ + + /* interrupt pending */ + uintptr_t mip = read_csr(mip); + + /* additional info and meaning depends on mcause */ + uintptr_t mtval = read_csr(mtval); + + /* trap vector */ + uintptr_t mtvec = read_csr(mtvec); + + /* temporary, sometimes might hold temporary value of a0 */ + uintptr_t mscratch = read_csr(mscratch); + + /* status contains many smaller fields: */ + uintptr_t mstatus = read_csr(mstatus); + + /* PC value when the exception was taken*/ + uintptr_t mmepc = read_csr(mepc); + + /* breakpoint */ + __asm__("ebreak"); +#else + _exit(1 + mcause); +#endif + } +} + +#ifdef __cplusplus +} +#endif diff --git a/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv_rv32_hal.h b/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv_rv32_hal.h new file mode 100644 index 0000000..7231610 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv_rv32_hal.h @@ -0,0 +1,521 @@ +/******************************************************************************* + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * @file miv_rv32_hal.h + * @author Microchip FPGA Embedded Systems Solutions + * @brief Hardware Abstraction Layer functions for Mi-V soft processors + * + */ + +#ifndef RISCV_HAL_H +#define RISCV_HAL_H + +#include "miv_rv32_regs.h" +#include "miv_rv32_plic.h" + +#ifndef LEGACY_DIR_STRUCTURE +#include "fpga_design_config/fpga_design_config.h" +#else +#include "hw_platform.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/***************************************************************************//** + * Return value from External IRQ handler. This will be used to disable the + * External interrupt. + */ +#define EXT_IRQ_KEEP_ENABLED 0U +#define EXT_IRQ_DISABLE 1U + +/***************************************************************************//** + * System tick handler. This handler function gets called when the Machine + * timer interrupt asserts. An implementation of this function should be + * provided by the application to implement the application specific machine + * timer interrupt handling. If application does not provide such implementation + * the weakly linked handler stub function implemented in riscv_hal_stubs.c gets + * linked. + */ +void SysTick_Handler(void); + +/***************************************************************************//** + * System timer tick configuration. + * Configures the machine timer to generate a system tick interrupt at regular + * intervals. + * Takes the number of system clock ticks between interrupts. + * + * Returns 0 if successful. + * Returns 1 if the interrupt interval cannot be achieved. + */ +uint32_t MRV_systick_config(uint64_t ticks); + + +#ifdef MIV_LEGACY_RV32 +#define MSIP (*(uint32_t*)0x44000000UL) +#define MTIMECMP (*(uint32_t*)0x44004000UL) +#define MTIMECMPH (*(uint32_t*)0x44004004UL) +#define MTIME (*(uint32_t*)0x4400BFF8UL) +#define MTIMEH (*(uint32_t*)0x4400BFFCUL) + +/* To maintain backward compatibility with FreeRTOS config code */ +#define PRCI_BASE 0x44000000UL + +#else + +/* To maintain backward compatibility with FreeRTOS config code */ +#define PRCI_BASE 0x02000000UL + +/* OPSRV stands for "Offload Processor Subsystem for RISC-V" (OPSRV) on the + * MIV_RV32 IP core. Please see the handbook for more details. */ + +/* TCM ECC correctable error irq enable mask value */ +#define OPSRV_TCM_ECC_CE_IRQ 0x01u + +/* TCMECC uncorrectable error irq enable */ +#define OPSRV_TCM_ECC_UCE_IRQ 0x02u + +/* AXI write response error irq enable */ +#define OPSRV_AXI_WR_RESP_IRQ 0x10u + +#define OPSRV_BASE_ADDR 0x00006000UL + +typedef struct +{ + volatile uint32_t cfg; /*Parity is not being supported by MIV_RV32 v3.0*/ + volatile uint32_t reserved0[3]; + volatile uint32_t irq_en; /*offset 0x10*/ + volatile uint32_t irq_pend; + volatile uint32_t reserved1[2]; + volatile uint32_t soft_reg; /*offset 0x20*/ +} OPSRV_Type; + +#define OPSRV ((OPSRV_Type *)OPSRV_BASE_ADDR) + +#define EXT_INTR_SOURCES 1 + +#define MTIMECMP (*(volatile uint32_t*)0x02004000UL) +#define MTIMECMPH (*(volatile uint32_t*)0x02004004UL) + +/* On MIV_RV32IMC v2.0 and v2.1 MTIME_PRESCALER is not defined and using this + * definition will result in crash. For those core use the definition as below + * #define MTIME_PRESCALER 100u + */ +#define MTIME_PRESCALER (*(volatile uint32_t*)0x02005000UL) + +#ifndef MIV_RV32_EXT_TIMER +#define MTIME (*(volatile uint32_t*)0x0200BFF8UL) +#define MTIMEH (*(volatile uint32_t*)0x0200BFFCUL) +#else +#define MTIME HAL_ASSERT(0); +#endif + +/* These definitions are provided for convenient identification of the interrupts + * in the MIE/MIP registers. + * Apart from the standard software, timer and external interrupts, the names + * of the additional interrupts correspond to the names as used in the MIV_RV32 + * handbook. Please refer the MIV_RV32 handbook for more details. + * */ +#define MRV32_SOFT_IRQn MIE_3_IRQn +#define MRV32_TIMER_IRQn MIE_7_IRQn +#define MRV32_EXT_IRQn MIE_11_IRQn + +/*============================================================================== + * Interrupt numbers: + * This enum represents the interrupt enable bits in the MIE register. + */ +enum +{ + MIE_0_IRQn = (0x01u), + MIE_1_IRQn = (0x01u<<1u), + MIE_2_IRQn = (0x01u<<2u), + MIE_3_IRQn = (0x01u<<3u), /*MSIE*/ + MIE_4_IRQn = (0x01u<<4u), + MIE_5_IRQn = (0x01u<<5u), + MIE_6_IRQn = (0x01u<<6u), + MIE_7_IRQn = (0x01u<<7u), /*MTIE*/ + MIE_8_IRQn = (0x01u<<8u), + MIE_9_IRQn = (0x01u<<9u), + MIE_10_IRQn = (0x01u<<10u), + MIE_11_IRQn = (0x01u<<11u), /*MEIE*/ + MIE_12_IRQn = (0x01u<<12u), + MIE_13_IRQn = (0x01u<<13u), + MIE_14_IRQn = (0x01u<<14u), + MIE_15_IRQn = (0x01u<<15u), + MIE_16_IRQn = (0x01u<<16u), /*MGEUIE*/ + MIE_17_IRQn = (0x01u<<17u), /*MGECIE*/ + MIE_18_IRQn = (0x01u<<18u), + MIE_19_IRQn = (0x01u<<19u), + MIE_20_IRQn = (0x01u<<20u), + MIE_21_IRQn = (0x01u<<21u), + MIE_22_IRQn = (0x01u<<22u), + MIE_23_IRQn = (0x01u<<23u), + MIE_24_IRQn = (0x01u<<24u), /*MSYS_EIE0*/ + MIE_25_IRQn = (0x01u<<25u), /*MSYS_EIE1*/ + MIE_26_IRQn = (0x01u<<26u), /*MSYS_EIE2*/ + MIE_27_IRQn = (0x01u<<27u), /*MSYS_EIE3*/ + MIE_28_IRQn = (0x01u<<28u), /*MSYS_EIE4*/ + MIE_29_IRQn = (0x01u<<29u), /*MSYS_EIE5*/ + MIE_30_IRQn = (0x01u<<30u) /*OPSRV_IRQ_IE*/ + +} MRV_LOCAL_IRQn_Type; + +#ifndef MIV_LEGACY_RV32 +#define MRV32_MGEUIE_IRQn MIE_16_IRQn +#define MRV32_MGECIE_IRQn MIE_17_IRQn +#define MRV32_MSYS_EIE0_IRQn MIE_24_IRQn +#define MRV32_MSYS_EIE1_IRQn MIE_25_IRQn +#define MRV32_MSYS_EIE2_IRQn MIE_26_IRQn +#define MRV32_MSYS_EIE3_IRQn MIE_27_IRQn +#define MRV32_MSYS_EIE4_IRQn MIE_28_IRQn +#define MRV32_MSYS_EIE5_IRQn MIE_29_IRQn +#define MRV32_MSYS_OPSRV_IRQn MIE_30_IRQn + +/***************************************************************************//** + Enable OPSRV interrupt. Parameter takes logical OR of following values + #define OPSRV_TCM_ECC_CE_IRQ 0x01u + #define OPSRV_TCM_ECC_UCE_IRQ 0x02u + #define OPSRV_AXI_WR_RESP_IRQ 0x10u + */ +static inline void MRV32_opsrv_enable_irq(uint32_t irq_mask) +{ + OPSRV->irq_en = irq_mask; +} + +/***************************************************************************//** + Disable OPSRV interrupt. Parameter takes logical OR of following values + #define OPSRV_TCM_ECC_CE_IRQ 0x01u + #define OPSRV_TCM_ECC_UCE_IRQ 0x02u + #define OPSRV_AXI_WR_RESP_IRQ 0x10u + */ +static inline void MRV32_opsrv_disable_irq(uint32_t irq_mask) +{ + OPSRV->irq_en &= ~irq_mask; +} + +/***************************************************************************//** + Clear OPSRV interrupt. Parameter takes logical OR of following values + #define OPSRV_TCM_ECC_CE_IRQ 0x01u + #define OPSRV_TCM_ECC_UCE_IRQ 0x02u + #define OPSRV_AXI_WR_RESP_IRQ 0x10u + */ +static inline void MRV32_opsrv_clear_irq(uint32_t irq_mask) +{ + OPSRV->irq_pend |= irq_mask; +} + +/***************************************************************************//** + * The function MRV32_is_gpr_ded() returns the core_gpr_ded_reset_reg bit value. + * When ECC is enabled, the core_gpr_ded_reset_reg is set when the core was + * reset due to GPR DED error. + */ +static inline uint32_t MRV32_is_gpr_ded(void) +{ + return((OPSRV->soft_reg & 0x04u) >> 0x02u); +} + +/***************************************************************************//** + * The function MRV32_clear_gpr_ded() can be used to clear the + * core_gpr_ded_reset_reg bit. When ECC is enabled, the core_gpr_ded_reset_reg + * is set when the core was previously reset due to GPR DED error. + */ +static inline void MRV32_clear_gpr_ded(void) +{ + OPSRV->soft_reg &= ~0x04u; +} + +/***************************************************************************//** + * The function MRV32_enable_parity_check() is used to enable parity check on + * the TCM and it's interface transactions. This feature is not available on + * MIV_RV32 v3.0.100 soft processor core. + */ +static inline void MRV32_enable_parity_check(void) +{ + OPSRV->cfg |= 0x01u; +} + +/***************************************************************************//** + * The function MRV32_disable_parity_check() is used to disable parity check on + * the TCM and it's interface transactions. + */ +static inline void MRV32_disable_parity_check(void) +{ + OPSRV->cfg &= ~0x01u; +} + +/***************************************************************************//** + * The function MRV32_cpu_soft_reset() is used to cause a soft cpu reset on + * the MIV_RV32 soft processor core. + */ +static inline void MRV32_cpu_soft_reset(void) +{ + OPSRV->soft_reg &= ~0x01u; +} + +/***************************************************************************//** + Clear GPR ECC Uncorrectable interrupt. MGEUI interrupt is available only when + ECC is enabled in MIV_RV32 IP configurator. + */ +static inline void MRV32_mgeui_clear_irq(uint32_t irq_mask) +{ + clear_csr(mip, MRV32_MGEUIE_IRQn); +} + +/***************************************************************************//** + Clear GPR ECC correctable interrupt. MGECI interrupt is available only when + ECC is enabled in MIV_RV32 IP configurator. + */ +static inline void MRV32_mgeci_clear_irq(uint32_t irq_mask) +{ + clear_csr(mip, MRV32_MGECIE_IRQn); +} + +/***************************************************************************//** + When ECC is enabled for the GPRs and if that data has a single bit error then + the data coming out of the ECC block will be corrected and will not have the + error but the data source will still have the error. + The ECC block does not write back corrected data to memory. + Therefore, if data has a single bit error, then the corrected data should be + written back to prevent the single bit error from becoming a double bit error. + The MRV32_clear_gpr_ecc_errors() can be used for that. + + Clear the pending interrupt bit after this using MRV32_mgeci_clear_irq() + function to complete the ECC error handling. + */ +static inline void MRV32_clear_gpr_ecc_errors(void) +{ + uint32_t temp; + + __asm__ __volatile__ ( + "sw x31, %0" + :"=m" (temp)); + + __asm__ volatile ( + "mv x31, x1;" + "mv x1, x31;" + + "mv x31, x2;" + "mv x2, x31;" + + "mv x31, x3;" + "mv x3, x31;" + + "mv x31, x4;" + "mv x4, x31;" + + "mv x31, x5;" + "mv x5, x31;" + + "mv x31, x6;" + "mv x6, x31;" + + "mv x31, x7;" + "mv x7, x31;" + + "mv x31, x8;" + "mv x8, x31;" + + "mv x31, x9;" + "mv x9, x31;" + + "mv x31, x10;" + "mv x10, x31;" + + "mv x31, x11;" + "mv x11, x31;" + + "mv x31, x12;" + "mv x12, x31;" + + "mv x31, x13;" + "mv x13, x31;" + + "mv x31, x14;" + "mv x14, x31;" + + "mv x31, x15;" + "mv x15, x31;" + + "mv x31, x16;" + "mv x16, x31;" + + "mv x31, x17;" + "mv x17, x31;" + + "mv x31, x18;" + "mv x18, x31;" + + "mv x31, x19;" + "mv x19, x31;" + + "mv x31, x20;" + "mv x20, x31;" + + "mv x31, x21;" + "mv x21, x31;" + + "mv x31, x22;" + "mv x22, x31;" + + "mv x31, x23;" + "mv x23, x31;" + + "mv x31, x24;" + "mv x24, x31;" + + "mv x31, x25;" + "mv x25, x31;" + + "mv x31, x26;" + "mv x26, x31;" + + "mv x31, x27;" + "mv x27, x31;" + + "mv x31, x28;" + "mv x28, x31;" + + "mv x31, x29;" + "mv x29, x31;" + + "mv x31, x30;" + "mv x30, x31;"); + + __asm__ __volatile__ ( + "lw x31, %0;" + : + :"m" (temp)); +} + +#endif + +/***************************************************************************//** + * Enable interrupts. + This function takes a mask value as input. For each set bit in the mask value, + corresponding interrupt bit in the MIE register is enabled. + + MRV_enable_local_irq(MRV32_SOFT_IRQn | + MRV32_TIMER_IRQn | + MRV32_EXT_IRQn | + MRV32_MSYS_EIE0_IRQn | + MRV32_MSYS_OPSRV_IRQn); + */ +static inline void MRV_enable_local_irq(uint32_t mask) +{ + set_csr(mie, mask); +} + +/***************************************************************************//** + * Disable interrupts. + This function takes a mask value as input. For each set bit in the mask value, + corresponding interrupt bit in the MIE register is disabled. + + MRV_disable_local_irq(MRV32_SOFT_IRQn | + MRV32_TIMER_IRQn | + MRV32_EXT_IRQn | + MRV32_MSYS_EIE0_IRQn | + MRV32_MSYS_OPSRV_IRQn); + */ +static inline void MRV_disable_local_irq(uint32_t mask) +{ + clear_csr(mie, mask); +} +#endif + +/***************************************************************************//** + * The function MRV_raise_soft_irq() raises a synchronous software interrupt + * by writing into the MSIP register. + */ +static inline void MRV_raise_soft_irq(void) +{ + set_csr(mie, MIP_MSIP); /* Enable software interrupt bit */ + +#ifdef MIV_LEGACY_RV32 + /* You need to make sure that the global interrupt is enabled */ + MSIP = 0x01; /* raise soft interrupt */ +#else + /* Raise soft IRQ on MIV_RV32 processor */ + OPSRV->soft_reg |= (1u << 1u); +#endif +} + +/***************************************************************************//** + * The function MRV_clear_soft_irq() clears a synchronous software interrupt + * by clearing the MSIP register. + */ +static inline void MRV_clear_soft_irq(void) +{ +#ifdef MIV_LEGACY_RV32 + MSIP = 0x00u; /* clear soft interrupt */ +#else + /* Clear soft IRQ on MIV_RV32 processor */ + OPSRV->soft_reg &= ~(1u << 1u); +#endif +} + +/***************************************************************************//** + * The function MRV_enable_interrupts() enables all interrupts setting the + * machine mode interrupt enable bit in MSTATUS register. + */ +static inline void MRV_enable_interrupts(void) +{ + set_csr(mstatus, MSTATUS_MIE); +} + +/***************************************************************************//** + * The function MRV_disable_interrupts() disables all interrupts clearing the + * machine mode interrupt enable bit in MSTATUS register. + */ +static inline void MRV_disable_interrupts(void) +{ + clear_csr(mstatus, MSTATUS_MPIE); + clear_csr(mstatus, MSTATUS_MIE); +} + +/***************************************************************************//** + * The function MRV_read_mtime() returns the current MTIME register value. + */ +static inline uint64_t MRV_read_mtime(void) +{ + volatile uint32_t hi = 0u; + volatile uint32_t lo = 0u; + +#ifndef MIV_RV32_EXT_TIMER + /* when mtime lower word is 0xFFFFFFFF, there will be rollover and + * returned value could be wrong. */ + do { + hi = MTIMEH; + lo = MTIME; + } while(hi != MTIMEH); + + return((((uint64_t)MTIMEH) << 32u) | lo); +#endif +} + +#ifdef __cplusplus +} +#endif + +#endif /* RISCV_HAL_H */ + diff --git a/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv_rv32_init.c b/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv_rv32_init.c new file mode 100644 index 0000000..e5f811f --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv_rv32_init.c @@ -0,0 +1,39 @@ +/******************************************************************************* + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file miv_rv32_init.c + * @author Microchip FPGA Embedded Systems Solutions + * @brief Mi-V soft processor memory section initializations and start-up code. + * + */ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +extern void main(void); + +void _init(void) +{ + /* This function is a placeholder for the case where some more hardware + * specific initializations are required before jumping into the application + * code. You can implement it here. */ + + /* Jump to the application code after all initializations are completed */ + main(); +} + +/* Function called after main() finishes */ +void +_fini(void) +{ +} + +#ifdef __cplusplus +} +#endif + diff --git a/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv_rv32_plic.h b/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv_rv32_plic.h new file mode 100644 index 0000000..19050cf --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv_rv32_plic.h @@ -0,0 +1,213 @@ +/******************************************************************************* + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file miv_rv32_plic.h + * @author Microchip FPGA Embedded Systems Solutions + * @brief Mi-V legacy RV32 soft processor PLIC access data structures and + * functions. + * Legacy RV32 soft processors are DEPRICATED. + * Migrate to MIV_RV32 v3.0 or later. + * + */ +#ifndef RISCV_PLIC_H +#define RISCV_PLIC_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/*============================================================================== + * Interrupt numbers: + */ +#ifdef MIV_LEGACY_RV32 +typedef enum +{ + NoInterrupt_IRQn = 0, + External_1_IRQn = 1, + External_2_IRQn = 2, + External_3_IRQn = 3, + External_4_IRQn = 4, + External_5_IRQn = 5, + External_6_IRQn = 6, + External_7_IRQn = 7, + External_8_IRQn = 8, + External_9_IRQn = 9, + External_10_IRQn = 10, + External_11_IRQn = 11, + External_12_IRQn = 12, + External_13_IRQn = 13, + External_14_IRQn = 14, + External_15_IRQn = 15, + External_16_IRQn = 16, + External_17_IRQn = 17, + External_18_IRQn = 18, + External_19_IRQn = 19, + External_20_IRQn = 20, + External_21_IRQn = 21, + External_22_IRQn = 22, + External_23_IRQn = 23, + External_24_IRQn = 24, + External_25_IRQn = 25, + External_26_IRQn = 26, + External_27_IRQn = 27, + External_28_IRQn = 28, + External_29_IRQn = 29, + External_30_IRQn = 30, + External_31_IRQn = 31 +} IRQn_Type; + +#define EXT_INTR_SOURCES 31 + +/*============================================================================== + * PLIC: Platform Level Interrupt Controller + */ +#define PLIC_BASE_ADDR 0x40000000UL + +typedef struct +{ + volatile uint32_t PRIORITY_THRESHOLD; + volatile uint32_t CLAIM_COMPLETE; + volatile uint32_t reserved[1022]; +} IRQ_Target_Type; + +typedef struct +{ + volatile uint32_t ENABLES[32]; +} Target_Enables_Type; + +typedef struct +{ + /*-------------------- Source Priority --------------------*/ + volatile uint32_t SOURCE_PRIORITY[1024]; + + /*-------------------- Pending array --------------------*/ + volatile const uint32_t PENDING_ARRAY[32]; + volatile uint32_t RESERVED1[992]; + + /*-------------------- Target enables --------------------*/ + volatile Target_Enables_Type TARGET_ENABLES[15808]; + + volatile uint32_t RESERVED2[16384]; + + /*--- Target Priority threshold and claim/complete---------*/ + IRQ_Target_Type TARGET[15872]; + +} PLIC_Type; + +#define PLIC ((PLIC_Type *)PLIC_BASE_ADDR) + +/*============================================================================== + * The function MRV_PLIC_init() initializes the PLIC controller and enables + * the global external interrupt bit. + */ +static inline void MRV_PLIC_init(void) +{ + uint32_t inc; + unsigned long hart_id = read_csr(mhartid); + + /* Disable all interrupts for the current hart. */ + for(inc = 0; inc < ((EXT_INTR_SOURCES + 32u) / 32u); ++inc) + { + PLIC->TARGET_ENABLES[hart_id].ENABLES[inc] = 0; + } + + /* Set priorities to zero. */ + for(inc = 0; inc < EXT_INTR_SOURCES; ++inc) + { + PLIC->SOURCE_PRIORITY[inc] = 0; + } + + /* Set the threshold to zero. */ + PLIC->TARGET[hart_id].PRIORITY_THRESHOLD = 0; + + /* Enable machine external interrupts. */ + set_csr(mie, MIP_MEIP); +} + +/*============================================================================== + * The function MRV_PLIC_enable_irq() enables the external interrupt for the + * interrupt number indicated by the parameter IRQn. + */ +static inline void MRV_PLIC_enable_irq(IRQn_Type IRQn) +{ + unsigned long hart_id = read_csr(mhartid); + uint32_t current = PLIC->TARGET_ENABLES[hart_id].ENABLES[IRQn / 32]; + current |= (uint32_t)1 << (IRQn % 32); + PLIC->TARGET_ENABLES[hart_id].ENABLES[IRQn / 32] = current; +} + +/*============================================================================== + * The function MRV_PLIC_disable_irq() disables the external interrupt for + * the interrupt number indicated by the parameter IRQn. + + * NOTE: + * This function can be used to disable the external interrupt from outside + * external interrupt handler function. + * This function MUST NOT be used from within the External Interrupt handler. + * If you wish to disable the external interrupt while the interrupt handler + * for that external interrupt is executing then you must use the return value + * EXT_IRQ_DISABLE to return from the extern interrupt handler. + */ +static inline void MRV_PLIC_disable_irq(IRQn_Type IRQn) +{ + unsigned long hart_id = read_csr(mhartid); + uint32_t current = PLIC->TARGET_ENABLES[hart_id].ENABLES[IRQn / 32]; + + current &= ~((uint32_t)1 << (IRQn % 32)); + + PLIC->TARGET_ENABLES[hart_id].ENABLES[IRQn / 32] = current; +} + +/*============================================================================== + * The function MRV_PLIC_set_priority() sets the priority for the external + * interrupt for the interrupt number indicated by the parameter IRQn. + */ +static inline void MRV_PLIC_set_priority(IRQn_Type IRQn, uint32_t priority) +{ + PLIC->SOURCE_PRIORITY[IRQn] = priority; +} + +/*============================================================================== + * The function MRV_PLIC_get_priority() returns the priority for the external + * interrupt for the interrupt number indicated by the parameter IRQn. + */ +static inline uint32_t MRV_PLIC_get_priority(IRQn_Type IRQn) +{ + return PLIC->SOURCE_PRIORITY[IRQn]; +} + +/***************************************************************************//** + * MRV_PLIC_clear_pending_irq(void) + * This is only called by the startup hart and only once + * Clears any pending interrupts as PLIC can be in unknown state on startup + */ +static inline void MRV_PLIC_clear_pending_irq(void) +{ + unsigned long hart_id = read_csr(mhartid); + volatile uint32_t int_num = PLIC->TARGET[hart_id].CLAIM_COMPLETE; + volatile int32_t wait_possible_int; + + while (NoInterrupt_IRQn != int_num) + { + PLIC->TARGET[hart_id].CLAIM_COMPLETE = int_num; + wait_possible_int = 0xFU; + while (wait_possible_int) + { + wait_possible_int--; + } + + int_num = PLIC->TARGET[hart_id].CLAIM_COMPLETE; + } +} + +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* RISCV_PLIC_H */ diff --git a/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv_rv32_regs.h b/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv_rv32_regs.h new file mode 100644 index 0000000..1837f42 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv_rv32_regs.h @@ -0,0 +1,543 @@ +/******************************************************************************* + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file miv_rv32_regs.h + * @author Microchip FPGA Embedded Systems Solutions + * @brief Mi-V soft processor register bit mask and shift constants encodings. + * + */ +#ifndef RISCV_REGS_H +#define RISCV_REGS_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define MSTATUS_UIE 0x00000001UL +#define MSTATUS_SIE 0x00000002UL +#define MSTATUS_HIE 0x00000004UL +#define MSTATUS_MIE 0x00000008UL +#define MSTATUS_UPIE 0x00000010UL +#define MSTATUS_SPIE 0x00000020UL +#define MSTATUS_HPIE 0x00000040UL +#define MSTATUS_MPIE 0x00000080UL +#define MSTATUS_SPP 0x00000100UL +#define MSTATUS_HPP 0x00000600UL +#define MSTATUS_MPP 0x00001800UL +#define MSTATUS_FS 0x00006000UL +#define MSTATUS_XS 0x00018000UL +#define MSTATUS_MPRV 0x00020000UL +#define MSTATUS_SUM 0x00040000UL +#define MSTATUS_MXR 0x00080000UL +#define MSTATUS_TVM 0x00100000UL +#define MSTATUS_TW 0x00200000UL +#define MSTATUS_TSR 0x00400000UL +#define MSTATUS_RES 0x7F800000UL +#define MSTATUS32_SD 0x80000000UL +#define MSTATUS64_SD 0x8000000000000000UL + +#define MCAUSE32_CAUSE 0x7FFFFFFFUL +#define MCAUSE64_CAUSE 0x7FFFFFFFFFFFFFFFUL +#define MCAUSE32_INT 0x80000000UL +#define MCAUSE64_INT 0x8000000000000000UL + +#define MIP_SSIP (1u << IRQ_S_SOFT) +#define MIP_HSIP (1u << IRQ_H_SOFT) +#define MIP_MSIP (1u << IRQ_M_SOFT) +#define MIP_STIP (1u << IRQ_S_TIMER) +#define MIP_HTIP (1u << IRQ_H_TIMER) +#define MIP_MTIP (1u << IRQ_M_TIMER) +#define MIP_SEIP (1u << IRQ_S_EXT) +#define MIP_HEIP (1u << IRQ_H_EXT) +#define MIP_MEIP (1u << IRQ_M_EXT) + +#ifndef MIV_LEGACY_RV32 +#define MGEUI 16U +#define MGECI 17U +#define MSYS_EI0 24U +#define MSYS_EI1 25U +#define MSYS_EI2 26U +#define MSYS_EI3 27U +#define MSYS_EI4 28U +#define MSYS_EI5 29U +#define OPSRV_REG 30U + +#define MGEUI_MEIP (1u << MGEUI) +#define MGECI_MEIP (1u << MGECI) +#define MSYS_EI0IP (1u << MSYS_EI0) +#define MSYS_EI1IP (1u << MSYS_EI1) +#define MSYS_EI2IP (1u << MSYS_EI2) +#define MSYS_EI3IP (1u << MSYS_EI3) +#define MSYS_EI4IP (1u << MSYS_EI4) +#define MSYS_EI5IP (1u << MSYS_EI5) +#define MSYS_EXTERNAL_INT (0x3Fu << MSYS_EI0) +#define MIP_OPSRV_REG (1u << OPSRV_REG) +#endif + +#define PRV_M 3U + +#define VM_MBARE 0U +#define VM_MBB 1U +#define VM_MBBID 2U +#define VM_SV32 8U +#define VM_SV39 9U +#define VM_SV48 10U + +#define IRQ_S_SOFT 1U +#define IRQ_H_SOFT 2U +#define IRQ_M_SOFT 3U +#define IRQ_S_TIMER 5U +#define IRQ_H_TIMER 6U +#define IRQ_M_TIMER 7U +#define IRQ_S_EXT 9U +#define IRQ_H_EXT 10U +#define IRQ_M_EXT 11U + +#define DEFAULT_RSTVEC 0x00001000 +#define DEFAULT_NMIVEC 0x00001004 +#define DEFAULT_MTVEC 0x00001010 +#define CONFIG_STRING_ADDR 0x0000100C +#define EXT_IO_BASE 0x40000000 +#define DRAM_BASE 0x80000000 + +#ifdef __riscv + +#if __riscv_xlen == 64 +# define MSTATUS_SD MSTATUS64_SD +# define SSTATUS_SD SSTATUS64_SD +# define MCAUSE_INT MCAUSE64_INT +# define MCAUSE_CAUSE MCAUSE64_CAUSE +# define RISCV_PGLEVEL_BITS 9 +#else +# define MSTATUS_SD MSTATUS32_SD +# define SSTATUS_SD SSTATUS32_SD +# define RISCV_PGLEVEL_BITS 10 +# define MCAUSE_INT MCAUSE32_INT +# define MCAUSE_CAUSE MCAUSE32_CAUSE +#endif + +#define RISCV_PGSHIFT 12U +#define RISCV_PGSIZE (1U << RISCV_PGSHIFT) + +#ifndef __ASSEMBLER__ + +#ifdef __GNUC__ + +#define read_csr(reg) ({ unsigned long __tmp; \ + __asm__ volatile ("csrr %0, " #reg : "=r"(__tmp)); \ + __tmp; }) + +#define write_csr(reg, val) ({ \ + __asm__ volatile ("csrw " #reg ", %0" :: "rK"(val)); }) + +#define swap_csr(reg, val) ({ unsigned long __tmp; \ + __asm__ volatile ("csrrw %0, " #reg ", %1" : "=r"(__tmp) : "rK"(val)); \ + __tmp; }) + +#define set_csr(reg, bit) ({ unsigned long __tmp; \ + __asm__ volatile ("csrrs %0, " #reg ", %1" : "=r"(__tmp) : "rK"(bit)); \ + __tmp; }) + +#define clear_csr(reg, bit) ({ unsigned long __tmp; \ + __asm__ volatile ("csrrc %0, " #reg ", %1" : "=r"(__tmp) : "rK"(bit)); \ + __tmp; }) + +#ifdef __riscv_atomic + +#define MASK(nr) (1UL << nr) +#define MASK_NOT(nr) (~(1UL << nr)) + +/** + * atomic_read - read atomic variable + * @v: pointer of type int + * + * Atomically reads the value of @v. + */ +static inline int atomic_read(const int *v) +{ + return *((volatile int *)(v)); +} + +/** + * atomic_set - set atomic variable + * @v: pointer of type int + * @i: required value + * + * Atomically sets the value of @v to @i. + */ +static inline void atomic_set(int *v, int i) +{ + *v = i; +} + +/** + * atomic_add - add integer to atomic variable + * @i: integer value to add + * @v: pointer of type int + * + * Atomically adds @i to @v. + */ +static inline void atomic_add(int i, int *v) +{ + __asm__ __volatile__ ( + "amoadd.w zero, %1, %0" + : "+A" (*v) + : "r" (i)); +} + +static inline int atomic_fetch_add(unsigned int mask, int *v) +{ + int out; + + __asm__ __volatile__ ( + "amoadd.w %2, %1, %0" + : "+A" (*v), "=r" (out) + : "r" (mask)); + return out; +} + +/** + * atomic_sub - subtract integer from atomic variable + * @i: integer value to subtract + * @v: pointer of type int + * + * Atomically subtracts @i from @v. + */ +static inline void atomic_sub(int i, int *v) +{ + atomic_add(-i, v); +} + +static inline int atomic_fetch_sub(unsigned int mask, int *v) +{ + int out; + + __asm__ __volatile__ ( + "amosub.w %2, %1, %0" + : "+A" (*v), "=r" (out) + : "r" (mask)); + return out; +} + +/** + * atomic_add_return - add integer to atomic variable + * @i: integer value to add + * @v: pointer of type int + * + * Atomically adds @i to @v and returns the result + */ +static inline int atomic_add_return(int i, int *v) +{ + register int c; + __asm__ __volatile__ ( + "amoadd.w %0, %2, %1" + : "=r" (c), "+A" (*v) + : "r" (i)); + return (c + i); +} + +/** + * atomic_sub_return - subtract integer from atomic variable + * @i: integer value to subtract + * @v: pointer of type int + * + * Atomically subtracts @i from @v and returns the result + */ +static inline int atomic_sub_return(int i, int *v) +{ + return atomic_add_return(-i, v); +} + +/** + * atomic_inc - increment atomic variable + * @v: pointer of type int + * + * Atomically increments @v by 1. + */ +static inline void atomic_inc(int *v) +{ + atomic_add(1, v); +} + +/** + * atomic_dec - decrement atomic variable + * @v: pointer of type int + * + * Atomically decrements @v by 1. + */ +static inline void atomic_dec(int *v) +{ + atomic_add(-1, v); +} + +static inline int atomic_inc_return(int *v) +{ + return atomic_add_return(1, v); +} + +static inline int atomic_dec_return(int *v) +{ + return atomic_sub_return(1, v); +} + +/** + * atomic_sub_and_test - subtract value from variable and test result + * @i: integer value to subtract + * @v: pointer of type int + * + * Atomically subtracts @i from @v and returns + * true if the result is zero, or false for all + * other cases. + */ +static inline int atomic_sub_and_test(int i, int *v) +{ + return (atomic_sub_return(i, v) == 0); +} + +/** + * atomic_inc_and_test - increment and test + * @v: pointer of type int + * + * Atomically increments @v by 1 + * and returns true if the result is zero, or false for all + * other cases. + */ +static inline int atomic_inc_and_test(int *v) +{ + return (atomic_inc_return(v) == 0); +} + +/** + * atomic_dec_and_test - decrement and test + * @v: pointer of type int + * + * Atomically decrements @v by 1 and + * returns true if the result is 0, or false for all other + * cases. + */ +static inline int atomic_dec_and_test(int *v) +{ + return (atomic_dec_return(v) == 0); +} + +/** + * atomic_add_negative - add and test if negative + * @i: integer value to add + * @v: pointer of type int + * + * Atomically adds @i to @v and returns true + * if the result is negative, or false when + * result is greater than or equal to zero. + */ +static inline int atomic_add_negative(int i, int *v) +{ + return (atomic_add_return(i, v) < 0); +} + +static inline int atomic_xchg(int *v, int n) +{ + register int c; + __asm__ __volatile__ ( + "amoswap.w %0, %2, %1" + : "=r" (c), "+A" (*v) + : "r" (n)); + return c; +} + +/** + * atomic_and - Atomically clear bits in atomic variable + * @mask: Mask of the bits to be retained + * @v: pointer of type int + * + * Atomically retains the bits set in @mask from @v + */ +static inline void atomic_and(unsigned int mask, int *v) +{ + __asm__ __volatile__ ( + "amoand.w zero, %1, %0" + : "+A" (*v) + : "r" (mask)); +} + +static inline int atomic_fetch_and(unsigned int mask, int *v) +{ + int out; + __asm__ __volatile__ ( + "amoand.w %2, %1, %0" + : "+A" (*v), "=r" (out) + : "r" (mask)); + return out; +} + +/** + * atomic_or - Atomically set bits in atomic variable + * @mask: Mask of the bits to be set + * @v: pointer of type int + * + * Atomically sets the bits set in @mask in @v + */ +static inline void atomic_or(unsigned int mask, int *v) +{ + __asm__ __volatile__ ( + "amoor.w zero, %1, %0" + : "+A" (*v) + : "r" (mask)); +} + +static inline int atomic_fetch_or(unsigned int mask, int *v) +{ + int out; + __asm__ __volatile__ ( + "amoor.w %2, %1, %0" + : "+A" (*v), "=r" (out) + : "r" (mask)); + return out; +} + +/** + * atomic_xor - Atomically flips bits in atomic variable + * @mask: Mask of the bits to be flipped + * @v: pointer of type int + * + * Atomically flips the bits set in @mask in @v + */ +static inline void atomic_xor(unsigned int mask, int *v) +{ + __asm__ __volatile__ ( + "amoxor.w zero, %1, %0" + : "+A" (*v) + : "r" (mask)); +} + +static inline int atomic_fetch_xor(unsigned int mask, int *v) +{ + int out; + __asm__ __volatile__ ( + "amoxor.w %2, %1, %0" + : "+A" (*v), "=r" (out) + : "r" (mask)); + return out; +} + +/** + * test_and_set_bit - Set a bit and return its old value + * @nr: Bit to set + * @addr: Address to count from + * + * This operation is atomic and cannot be reordered. + * It also implies a memory barrier. + */ +static inline int test_and_set_bit(int nr, volatile unsigned long *addr) +{ + unsigned long __res, __mask; + __mask = MASK(nr); + __asm__ __volatile__ ( \ + "amoor.w %0, %2, %1" \ + : "=r" (__res), "+A" (*addr) \ + : "r" (__mask)); \ + + return ((__res & __mask) != 0); +} + +/** + * test_and_clear_bit - Clear a bit and return its old value + * @nr: Bit to clear + * @addr: Address to count from + * + * This operation is atomic and cannot be reordered. + * It also implies a memory barrier. + */ +static inline int test_and_clear_bit(int nr, volatile unsigned long *addr) +{ + unsigned long __res, __mask; + __mask = MASK_NOT(nr); + __asm__ __volatile__ ( \ + "amoand.w %0, %2, %1" \ + : "=r" (__res), "+A" (*addr) \ + : "r" (__mask)); \ + + return ((__res & __mask) != 0); +} + +/** + * test_and_change_bit - Change a bit and return its old value + * @nr: Bit to change + * @addr: Address to count from + * + * This operation is atomic and cannot be reordered. + * It also implies a memory barrier. + */ +static inline int test_and_change_bit(int nr, volatile unsigned long *addr) +{ + + unsigned long __res, __mask; + __mask = MASK(nr); + __asm__ __volatile__ ( \ + "amoxor.w %0, %2, %1" \ + : "=r" (__res), "+A" (*addr) \ + : "r" (__mask)); \ + + return ((__res & __mask) != 0); +} + +/** + * set_bit - Atomically set a bit in memory + * @nr: the bit to set + * @addr: the address to start counting from + * + * This function is atomic and may not be reordered. + */ + +static inline void set_bit(int nr, volatile unsigned long *addr) +{ + __asm__ __volatile__ ( \ + "AMOOR.w zero, %1, %0" \ + : "+A" (*addr) \ + : "r" (MASK(nr))); +} + +/** + * clear_bit - Clears a bit in memory + * @nr: Bit to clear + * @addr: Address to start counting from + * + * clear_bit() is atomic and may not be reordered. + */ +static inline void clear_bit(int nr, volatile unsigned long *addr) +{ + __asm__ __volatile__ ( \ + "AMOAND.w zero, %1, %0" \ + : "+A" (*addr) \ + : "r" (MASK_NOT(nr))); +} + +/** + * change_bit - Toggle a bit in memory + * @nr: Bit to change + * @addr: Address to start counting from + * + * change_bit() is atomic and may not be reordered. + */ +static inline void change_bit(int nr, volatile unsigned long *addr) +{ + __asm__ __volatile__ ( \ + "AMOXOR.w zero, %1, %0" \ + : "+A" (*addr) \ + : "r" (MASK(nr))); +} + +#endif /* __riscv_atomic */ + +#endif /* __GNUC__ */ + +#endif /* __ASSEMBLER__ */ + +#endif /* __riscv */ + +#ifdef __cplusplus +} +#endif + +#endif /* RISCV_REGS_H */ diff --git a/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv_rv32_stubs.c b/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv_rv32_stubs.c new file mode 100644 index 0000000..7f5042b --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv_rv32_stubs.c @@ -0,0 +1,239 @@ +/******************************************************************************* + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file miv_rv32_stubs.c + * @author Microchip FPGA Embedded Systems Solutions + * @brief Stubs for the Mi-V soft processor Interrupt handler. + * + * The functions below will only be linked with the application code if the user + * does not provide an implementation for these functions. These functions are + * defined with weak linking so that they can be overridden by a function with + * same prototype in the user's application code. + * + */ +#include + +#ifdef __cplusplus +extern "C" { +#endif + +__attribute__((weak)) void Software_IRQHandler(void) +{ + _exit(10); +} + +__attribute__((weak)) void SysTick_Handler(void) +{ + /* Default handler */ +} + +#ifdef MIV_LEGACY_RV32 +__attribute__((weak)) uint8_t Invalid_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_1_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_2_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_3_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_4_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_5_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_6_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_7_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_8_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_9_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_10_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_11_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_12_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_13_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_14_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_15_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_16_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_17_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_18_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_19_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_20_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_21_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_22_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_23_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_24_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_25_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_26_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_27_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_28_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_29_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_30_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_31_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +#else + +__attribute__((weak)) void External_IRQHandler(void) +{ +} + +__attribute__((weak)) void MGECI_IRQHandler(void) +{ +} + +__attribute__((weak)) void MGEUI_IRQHandler(void) +{ +} + +__attribute__((weak)) void OPSRV_IRQHandler(void) +{ +} + +__attribute__((weak)) void MSYS_EI5_IRQHandler(void) +{ +} + +__attribute__((weak)) void MSYS_EI4_IRQHandler(void) +{ +} + +__attribute__((weak)) void MSYS_EI3_IRQHandler(void) +{ +} + +__attribute__((weak)) void MSYS_EI2_IRQHandler(void) +{ +} + +__attribute__((weak)) void MSYS_EI1_IRQHandler(void) +{ +} + +__attribute__((weak)) void MSYS_EI0_IRQHandler(void) +{ +} + +#endif + +#ifdef __cplusplus +} +#endif diff --git a/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv_rv32_syscall.c b/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv_rv32_syscall.c new file mode 100644 index 0000000..b24e729 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/miv_rv32_syscall.c @@ -0,0 +1,349 @@ +/******************************************************************************* + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file miv_rv32_syscall.c + * @author Microchip FPGA Embedded Systems Solutions + * @brief Stubs for system calls. + * + */ +#include +#include +#include +#include +#include "miv_rv32_hal.h" + +#ifdef MSCC_STDIO_THRU_CORE_UART_APB + +#ifndef LEGACY_DIR_STRUCTURE +#include "drivers/fabric_ip/CoreUARTapb/core_uart_apb.h" +#else +#include "core_uart_apb.h" +#endif + +#endif /*MSCC_STDIO_THRU_CORE_UART_APB*/ + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef MSCC_STDIO_THRU_CORE_UART_APB + +/*------------------------------------------------------------------------------ + * CoreUARTapb instance data for the CoreUARTapb instance used for standard + * output. + */ +static UART_instance_t g_stdio_uart; + +/*============================================================================== + * Flag used to indicate if the UART driver needs to be initialized. + */ +static int g_stdio_uart_init_done = 0; + +/* + * Disable semihosting apis + */ +#pragma import(__use_no_semihosting_swi) + +/*============================================================================== + * sendchar() + */ +int sendchar(int ch) +{ + /*-------------------------------------------------------------------------- + * Initialize the UART driver if it is the first time this function is + * called. + */ + if ( !g_stdio_uart_init_done ) + { + /****************************************************************************** + * Baud value: + * This value is calculated using the following equation: + * BAUD_VALUE = (CLOCK / (16 * BAUD_RATE)) - 1 + *****************************************************************************/ + UART_init( &g_stdio_uart, + MSCC_STDIO_UART_BASE_ADDR, + ((SYS_CLK_FREQ/(16 * MSCC_STDIO_BAUD_VALUE))-1), + (DATA_8_BITS | NO_PARITY)); + + g_stdio_uart_init_done = 1; + } + + /*-------------------------------------------------------------------------- + * Output text to the UART. + */ + UART_send( &g_stdio_uart, (uint8_t *)&ch, 1 ); + + return (ch); +} + +/*============================================================================== + * getachar() + */ +int getachar(void) +{ + uint8_t rx_size; + uint8_t rx_byte; + + if ( !g_stdio_uart_init_done ) + { + /****************************************************************************** + * Baud value: + * This value is calculated using the following equation: + * BAUD_VALUE = (CLOCK / (16 * BAUD_RATE)) - 1 + *****************************************************************************/ + UART_init( &g_stdio_uart, + MSCC_STDIO_UART_BASE_ADDR, + ((SYS_CLK_FREQ/(16 * MSCC_STDIO_BAUD_VALUE))-1), + (DATA_8_BITS | NO_PARITY)); + + g_stdio_uart_init_done = 1; + } + + do + { + rx_size = UART_get_rx(&g_stdio_uart, &rx_byte, 1); + } while(0u == rx_size); + + return rx_byte; +} + +#endif /*MSCC_STDIO_THRU_CORE_UART_APB*/ + +#undef errno +static int errno; + +static char *__env[1] = { 0 }; +char **environ = __env; + +void write_hex(int fd, uint32_t hex) +{ + uint8_t ii; + uint8_t jj; + char towrite; + uint8_t digit; + + write( fd , "0x", 2U ); + + for (ii = 8U ; ii > 0U; ii--) + { + jj = ii-1U; + digit = ((hex & (0xFU << (jj*4U))) >> (jj*4U)); + towrite = digit < 0xAU ? (0x48U + digit) : (0x65U + (digit - 0xAU)); + write( fd, &towrite, 1U); + } +} + + +#ifdef GDB_TESTING +void __attribute__((optimize("O0"))) _exit(int code) +#else +void _exit(int code) +#endif +{ +#ifdef MSCC_STDIO_THRU_CORE_UART_APB + const char * message = "\nProgam has exited with code:"; + + write(STDERR_FILENO, message, strlen(message)); + write_hex(STDERR_FILENO, code); +#endif + + while (1){}; +} + +void *_sbrk(ptrdiff_t incr) +{ + extern char _end[]; + extern char _heap_end[]; + static char *curbrk = _end; + void * ret = NULL; + + if (((curbrk + incr) < _end) || ((curbrk + incr) > _heap_end)) + { + ret = ((char *) - 1); + } + else + { + curbrk += incr; + ret = curbrk - incr; + } + + return(ret); +} + +int _isatty(int fd) +{ + int ret = 0; + + if (fd <= 2) /* one of stdin, stdout, stderr */ + { + ret = 1; + } + else + { + errno = EBADF; + ret = 0; + } + + return(ret); +} + +static int stub(int err) +{ + errno = err; + return -1; +} + +int _open(const char* name, int flags, int mode) +{ + return stub(ENOENT); +} + +int _openat(int dirfd, const char* name, int flags, int mode) +{ + return stub(ENOENT); +} + +int _close(int fd) +{ + return stub(EBADF); +} + +int _execve(const char* name, char* const argv[], char* const env[]) +{ + return stub(ENOMEM); +} + +int _fork(void) +{ + return stub(EAGAIN); +} + +int _fstat(int fd, struct stat *st) +{ + int ret = 0; + + if (isatty(fd)) + { + st->st_mode = S_IFCHR; + ret = 0; + } + else + { + ret = stub(EBADF); + } + + return ret; +} + +int _getpid(void) +{ + return 1; +} + +int _kill(int pid, int sig) +{ + return stub(EINVAL); +} + +int _link(const char *old_name, const char *new_name) +{ + return stub(EMLINK); +} + +off_t _lseek(int fd, off_t ptr, int dir) +{ + off_t ret = 0; + if (_isatty(fd)) + { + ret = 0; + } + else + { + ret = stub(EBADF); + } + + return ret; +} + +ssize_t _read(int fd, void* ptr, size_t len) +{ +#ifdef MSCC_STDIO_THRU_CORE_UART_APB + + char* ptr1 = (char*)ptr; + + if (_isatty(fd)) + { + int count; + + for (count = 0; count < len; count++) + { + ptr1[count] = getachar(); + sendchar(ptr1[count]); + + /* Return partial buffer if we get EOL */ + if (('\r' == ptr1[count])||('\n' == ptr1[count])) + { + ptr1[count] = '\n'; + return count; + } + } + + return count; /* Filled the buffer */ + } +#endif + + return stub(EBADF); +} + +int _stat(const char* file, struct stat* st) +{ + return stub(EACCES); +} + +clock_t _times(struct tms* buf) +{ + return stub(EACCES); +} + +int _unlink(const char* name) +{ + return stub(ENOENT); +} + +int _wait(int* status) +{ + return stub(ECHILD); +} + +ssize_t _write(int fd, const void* ptr, size_t len) +{ +#ifdef MSCC_STDIO_THRU_CORE_UART_APB + int count_out; + char* ptr1 = (char*)ptr; + + /*-------------------------------------------------------------------------- + * Output text to the UART. + */ + count_out = 0; + while(len--) + { + sendchar(ptr1[count_out]); + count_out++; + } + + errno = 0; + return count_out; + +#else /* MSCC_STDIO_THRU_CORE_UART_APB */ + + return stub(EBADF); + +#endif /* MSCC_STDIO_THRU_CORE_UART_APB */ + +} + +#ifdef __cplusplus +} +#endif diff --git a/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/sample_fpga_design_config.h b/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/sample_fpga_design_config.h new file mode 100644 index 0000000..a380d96 --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/miv_rv32_hal/sample_fpga_design_config.h @@ -0,0 +1,167 @@ +/******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file sample_fpga_design_config.h + * @author Microchip FPGA Embedded Systems Solutions + * @brief Sample design configuration settings + * + */ + /*========================================================================*//** + @mainpage + Example file detailing how the fpga_design_config.h should be constructed + for the SoftConsole project targeted for Mi-V processors. + + @section intro_sec Introduction + The SoftConsole project targeted for Mi-V processors now have an improved + folder structure. Detailed description of the folder structure is available + at https://github.com/Mi-V-Soft-RISC-V/miv-rv32-documentation. + + The fpga_design_config.h must be stored as shown below + /boards//fpga_design_config.h + + Currently this file must be hand crafted when using the Mi-V Soft Processor. + In future, all the design and soft IP configurations will be automatically + generated from the Libero design description data. + + You can use this sample file as an example. + Rename this file from sample_fpga_design_config.h to fpga_design_config.h + and then customize it per your hardware design. + + @section Project configuration Instructions + 1. Change SYS_CLK_FREQ define to frequency of Mi-V Soft processor clock + 2 Add all the soft IP core BASE addresses + 3. Add the peripheral Core Interrupts to Mi-V Soft processor IRQ number + mappings + 4. Define MSCC_STDIO_UART_BASE_ADDR if you want a CoreUARTapb mapped to + STDIO + + **NOTE** + In the legacy folder structures, the file hw_config.h as was used at the + root of the project folder. This file is now depricated. + +*//*=========================================================================*/ + +#ifndef FPGA_DESIGN_CONFIG_H_ +#define FPGA_DESIGN_CONFIG_H_ + +/***************************************************************************//** + * Soft-processor clock definition + * This is the only clock brought over from the Mi-V Libero design. + */ +#ifndef SYS_CLK_FREQ +#define SYS_CLK_FREQ 50000000UL +#endif + +/***************************************************************************//** + * Peripheral base addresses. + * Format of define is: + * __BASE_ADDR + * The field is optional if there is only one instance of the core + * in the design + * MIV_ESS is an extended peripheral subsystem IP core with peripherals + * connections as defined below. + * The system can be further extended by attaching APB peripherals to the + * empty APB slots. + */ +#define MIV_ESS_PLIC_BASE_ADDR 0x70000000UL +#define COREUARTAPB0_BASE_ADDR 0x71000000UL +#define MIV_MTIMER_BASE_ADDR 0x72000000UL +#define MIV_ESS_APBSLOT3_BASE_ADDR 0x73000000UL +#define MIV_ESS_APBSLOT4_BASE_ADDR 0x74000000UL +#define COREGPIO_OUT_BASE_ADDR 0x75000000UL +#define CORESPI_BASE_ADDR 0x76000000UL +#define MIV_ESS_uDMA_BASE_ADDR 0x78000000UL +#define MIV_ESS_WDOG_BASE_ADDR 0x79000000UL +#define MIV_ESS_I2C_BASE_ADDR 0x7A000000UL +#define MIV_ESS_APBSLOTB_BASE_ADDR 0x7B000000UL +#define MIV_ESS_APBSLOTC_BASE_ADDR 0x7C000000UL +#define MIV_ESS_APBSLOTD_BASE_ADDR 0x7D000000UL +#define MIV_ESS_APBSLOTE_BASE_ADDR 0x7E000000UL +#define MIV_ESS_APBSLOTF_BASE_ADDR 0x7F000000UL + +/***************************************************************************//** + * Peripheral Interrupts are mapped to the corresponding Mi-V Soft processor + * interrupt in the Libero design. + * + * On the legacy RV32 cores, there can be up to 31 external interrupts (IRQ[30:0] + * pins). The legacy RV32 Soft processor external interrupts are defined in the + miv_rv32_plic.h + * + * These are of the form + * typedef enum +{ + NoInterrupt_IRQn = 0, + External_1_IRQn = 1, + External_2_IRQn = 2, + . + . + . + External_31_IRQn = 31 +} IRQn_Type; + + On the legacy RV32 processors, the PLIC identifies the interrupt and passes it + on to the processor core. The interrupt 0 is not used. The pin IRQ[0] should + map to External_1_IRQn likewise IRQ[30] should map to External_31_IRQn + +e.g + +#define TIMER0_IRQn External_30_IRQn +#define TIMER1_IRQn External_31_IRQn + + The MIV_RV32 soft processor has up to six optional system interrupts, MSYS_EI[n] + in addition to one EXT_IRQ. + The MIV_RV32 does not have an inbuilt PLIC and all the interrupts are directly + delivered to the processor core, hence unlike legacy RV32 cores, no interrupt + number mapping is necessary on MIV_RV32 core. + */ + +/**************************************************************************** + * Baud value to achieve a 115200 baud rate with system clock defined by + * SYS_CLK_FREQ. + * This value is calculated using the following equation: + * BAUD_VALUE = (CLOCK / (16 * BAUD_RATE)) - 1 + *****************************************************************************/ +#define BAUD_VALUE_115200 ((SYS_CLK_FREQ / (16 * 115200)) - 1) + +/****************************************************************************** + * Baud value to achieve a 57600 baud rate with system clock defined by + * SYS_CLK_FREQ. + * This value is calculated using the following equation: + * BAUD_VALUE = (CLOCK / (16 * BAUD_RATE)) - 1 + *****************************************************************************/ + #define BAUD_VALUE_57600 ((SYS_CLK_FREQ / (16 * 57600)) - 1) + +/***************************************************************************//** + * Define MSCC_STDIO_THRU_CORE_UART_APB in the project settings if you want the + * standard IOs to be redirected to a terminal via UART. + */ +#ifdef MSCC_STDIO_THRU_CORE_UART_APB +/* + * A base address mapping for the STDIO printf/scanf mapping to CortUARTapb + * must be provided if it is being used + * + * e.g. #define MSCC_STDIO_UART_BASE_ADDR COREUARTAPB1_BASE_ADDR + */ +#define MSCC_STDIO_UART_BASE_ADDR COREUARTAPB0_BASE_ADDR + +#ifndef MSCC_STDIO_UART_BASE_ADDR +#error MSCC_STDIO_UART_BASE_ADDR not defined- e.g. #define MSCC_STDIO_UART_BASE_ADDR COREUARTAPB1_BASE_ADDR +#endif + +#ifndef MSCC_STDIO_BAUD_VALUE +/* + * The MSCC_STDIO_BAUD_VALUE define should be set in your project's settings to + * specify the baud value used by the standard output CoreUARTapb instance for + * generating the UART's baud rate if you want a different baud rate from the + * default of 115200 baud + */ +#define MSCC_STDIO_BAUD_VALUE 115200 +#endif /*MSCC_STDIO_BAUD_VALUE*/ + +#endif /* end of MSCC_STDIO_THRU_CORE_UART_APB */ +/******************************************************************************* + * End of user edit section + */ +#endif /* FPGA_DESIGN_CONFIG_H_ */ diff --git a/bootloaders/miv-rv32-bootloader/src/platform/platform_config_reference/linker/readme.md b/bootloaders/miv-rv32-bootloader/src/platform/platform_config_reference/linker/readme.md new file mode 100644 index 0000000..5581d1b --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/platform_config_reference/linker/readme.md @@ -0,0 +1,2 @@ +# readme + diff --git a/bootloaders/miv-rv32-bootloader/src/platform/platform_config_reference/miv_rv32_hal_config/readme.md b/bootloaders/miv-rv32-bootloader/src/platform/platform_config_reference/miv_rv32_hal_config/readme.md new file mode 100644 index 0000000..5581d1b --- /dev/null +++ b/bootloaders/miv-rv32-bootloader/src/platform/platform_config_reference/miv_rv32_hal_config/readme.md @@ -0,0 +1,2 @@ +# readme + diff --git a/freertos/miv-rv32-freertos-demo/.cproject b/freertos/miv-rv32-freertos-demo/.cproject new file mode 100644 index 0000000..56d4edb --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/.cproject @@ -0,0 +1,799 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/freertos/miv-rv32-freertos-demo/.gitignore b/freertos/miv-rv32-freertos-demo/.gitignore new file mode 100644 index 0000000..fc4dc52 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/.gitignore @@ -0,0 +1,6 @@ +*.html +/.settings*/ +/Debug +/Release +/*-Debug/ +/*-Release/ \ No newline at end of file diff --git a/freertos/miv-rv32-freertos-demo/.project b/freertos/miv-rv32-freertos-demo/.project new file mode 100644 index 0000000..fbd7c4e --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/.project @@ -0,0 +1,36 @@ + + + miv-rv32-freertos-demo + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + + + FREERTOS_ROOT + $%7BPARENT-3-PROJECT_LOC%7D + + + copy_PARENT + $%7BPARENT-4-PROJECT_LOC%7D/FreeRTOS/WorkingCopy/FreeRTOS + + + diff --git a/freertos/miv-rv32-freertos-demo/README.md b/freertos/miv-rv32-freertos-demo/README.md new file mode 100644 index 0000000..f2bf355 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/README.md @@ -0,0 +1,89 @@ +# Mi-V Soft processor FreeRTOS Examples +This repository provides a FreeRTOS demonstration project for the Future Avalanche board built with Microchip's SoftConsole IDE. + +``` + + |-- src + | |- applications + | |-- boards + | | |- avalanche-board + | |- freertos-source + | |- platform + +``` + +The *applications* directory contains applications that are ready for use with the provided design for the Future Avalanche board. + +The *boards* directory contains the files needed to configure the Future Avalanche board to make the FreeRTOS demo run correctly. + +The *freertos-source* directory contains the FreeRTOS kernel, as well as the files defining the tasks used in the full demo. + +The *platform* directory contains the HAL and the drivers. + +## Build configuration +Four default build configurations are provided for this project: + +|Configuration | Description | +|------------------------- | ---------------------------------------------------------------------------------------------------------- | +|miv-rv32-Debug | Targeted for the Mi-V soft processor configured with RV32I base ISA + M and C extensions. Not-optimized (-O0). Can be used with any Mi-V RV32 | +|miv-rv32-Release | Targeted for the Mi-V soft processor configured with RV32I base ISA + M and C extensions. Optimized size (-Os). Can be used with any Mi-V RV32 | +|legacy-rv32imaf-Debug | Targeted for the legacy cores configured with RV32I base ISA + M, A, and F extensions. Not-optimized (-O0)| +|legacy-rv32imaf-Debug | Targeted for the legacy cores configured with RV32I base ISA + M, A, and F extensions. Optimized size (-Os)| + +You can create your own build configuration to match the specific needs for your project by going to the Project Explorer tab in SoftConcole, right clicking on the project's name, choosing Properties and then going to C/C++ build->Settings. + +**Linker scripts:** A build configuration needs a linker script to describe the memory layout of the executable. Each build configuration selects an appropriate linker scripts via the project settings. The linker script for each configuration in \/src/boards/avalanche-board/\/platform_config\linker matches the Libero® design for the Avalanche kit, located in \/src/boards/avalanche-board\libero_design. + +### Settings via header files +Beside the SoftConsole project settings, a project needs few additionnal configurations. These configurations are categorized into hardware and software configurations. + +#### Hardware configurations +The hardware configuration file is the \/src/boards/avalanche-board/\/fpga_design_config/fpga_design_config.h file. This is where you define the hardware configuration such as clock, MTIME prescaler (under the name TICK_COUNT_PRESCALER) and the peripherals memory map. It is also in this file that you must specify if the project is running on Renode or on hardware. You must make sure that the configuration in this example project matches the actual configurations of the Libero® design that you are using to test this example project. + +To choose a particular hardware configuration, include an appropriate \/src/boards/avalanche-board folder path via the SoftConsole project settings. + +#### Software configurations +A different software configuration might be required for your project to run correctly. + +According to your project, you might want to change the FreeRTOS configuration. This is done by modifying the \/src/applications/FreeRTOSConfig.h file. For further information, see [FreeRTOS customisation](https://www.freertos.org/a00110.html). + +## Libero Design + +The FreeRTOS demo targets the 2022.1-v1.0 release of MiV for the Avalanche board. The base design of soft CPU for PolarFire FPGA can be found [here](https://mi-v-ecosystem.github.io/docs/mi-v-soft-cpu/#mi-v-soft-cpus). If you are going to build the 2022.1-v1.0 release of the Libero® project from [that GitHub repository](https://mi-v-ecosystem.github.io/docs/mi-v-soft-cpu/#mi-v-soft-cpus), you are going to need **Libero® 2022.1** or later installed. Nonetheless, the base design needs to be modified to be able to run the FreeRTOS demo. + +The size of the RAM must be increased to *256kB* (i.e. *65536 words*) for MiV-RV32 when the C extension is on, and to *512kB* (i.e. *131072 words*) for legacy MiV of for MiV-RV32 when the C extension is off. + +When using the MiV-RV32 base design, two CoreTimers must be added to the design. +To add them, go to the *Catalogue* tab in Libero, type "CoreTimer" in the IP Catalog search bar, and drag two CoreTimers to the BaseDesign SmartDesign window. +You then need to connect them. To do so: +1. Connect the CoreTimer's *PCLK* input to the *OUT0_FABCLK_0* output of the Clock Conditioning Circuitry (CCC). +2. Connect the CoreTimer's *PRESETn* input to the *FABRIC_RESET_N* output of the CoreReset block. +3. Double-click on the MiV-ESS component, go to the APB tab, and enable the APB slots 3 and 4. You can then connect each CoreTimer's APB input to one of these APB slots from MiV-ESS. +4. Connect the output of the CoreTimer connected to the MiV_ESS's APB slot 3 to the MSYS_EI[0] input of the MiV_RV32. +5. Connect the output of the CoreTimer connected to the MiV_ESS's APB slot 4 to the EXT_IRQ input of the MiV_RV32. +6. Generate the component and follow the usual Libero design flow. + +To avoid adding the previous changes by hand, you can simply execute the tcl script provided under ..\miv-rv32-freertos-applications\miv-rv32-freertos-demo\src\boards\avalanche-board\miv-rv32-design\fpga_design\libero design. To do so, open Libero®, go to Project->Execute Script.., select the PF_Avalanche_MIV_RV32_BaseDesign.tcl file and type "DGC2" in the argument field. If you are going to build the Libero® project from the scripts provided in this repository, you are going to need **Libero® 2022.2** or later installed. + +To use the legacy-IMAF design, you can simply use the tcl script provided under ..\miv-rv32-freertos-applications\miv-rv32-freertos-demo\src\boards\avalanche-board\legacy-rv32imaf-design\fpga_design\libero design. To do so, you must use **Libero® 2022.2** or later, go to Project->Execute Script.., select the PF_Avalanche_MIV_RV32_BaseDesign.tcl file and type "CFG1" in the argument field. + +## How to run FreeRTOS demo on Renode emulation platform +The FreeRTOS demo can be used on board or on Renode emulation platform. To use the provided Renode debug configurations, you will need to use **SoftConsole v2022.2-782** or later. + +### Software configuration +To properly use the demo on Renode, the RENODE_SIMULATION macro must be set to 1 in src/boards/avalanche-board/\/fpga_design_config/fpga_design_config.h. This step is needed because the MiV core has MTIME prescaler, which divides the CPU clock to generate the MTIME. The FreeRTOS kernel generates its own clock by generating tick interrupts and incrementing a tick count at a given frequency. This tick interrupt being based on the MTIME, the prescaler has to be considered when setting the tick frequency (see src/freertos-source/source/portable/GCC/RISC-V/port.c). Nevertheless, there is no such prescaler in the Renode model. So, setting RENODE_SIMULATION to 0 for hardware or to 1 for Renode makes the tick frequency adapted to the platform. You should also check that the definition of the macro TICK_COUNT_PRESCALER matches the MTIME prescaler in the Libero design. + +### Start a Renode session + +1. Compile the project with the ***Release*** configuration of the design you want +2. Righ click on *miv-rv32-freertos renode-rv32i start-platform-and-debug.launch* (respectively *miv-rv32-freertos renode-legacy-rv32 start-platform-and-debug.launch* if you want to emulate the legacy design), select "Debug as" and "miv-rv32-freertos renode-rv32i start-platform-and-debug" (respectively *miv-rv32-freertos renode-legacy-rv32 start-platform-and-debug.launch*) +3. You can then use the usual debug tools, such as breakpoints, steps, etc. +4. You should see either a "blink" message or a dot appearing in the Renode window, depending on if you use the simple blinky demo or the full demo + + +### Further reading +[Mi-V soft CPUs](https://mi-v-ecosystem.github.io/docs/mi-v-soft-cpu/#mi-v-soft-cpus) + +[Future Avalanche board](https://mi-v-soft-risc-v.github.io/Future-Avalanche-Board/) +___ +Libero® and PolarFire® are the property of Microchip Technology Inc. (MCHP). \ No newline at end of file diff --git a/freertos/miv-rv32-freertos-demo/miv-rv32-freertos renode-legacy-rv32 debug.launch b/freertos/miv-rv32-freertos-demo/miv-rv32-freertos renode-legacy-rv32 debug.launch new file mode 100644 index 0000000..109c21e --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/miv-rv32-freertos renode-legacy-rv32 debug.launch @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/freertos/miv-rv32-freertos-demo/miv-rv32-freertos renode-legacy-rv32 start-platform-and-debug.launch b/freertos/miv-rv32-freertos-demo/miv-rv32-freertos renode-legacy-rv32 start-platform-and-debug.launch new file mode 100644 index 0000000..2fdf191 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/miv-rv32-freertos renode-legacy-rv32 start-platform-and-debug.launch @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/freertos/miv-rv32-freertos-demo/miv-rv32-freertos renode-rv32i debug.launch b/freertos/miv-rv32-freertos-demo/miv-rv32-freertos renode-rv32i debug.launch new file mode 100644 index 0000000..4255b11 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/miv-rv32-freertos renode-rv32i debug.launch @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/freertos/miv-rv32-freertos-demo/miv-rv32-freertos renode-rv32i start-platform-and-debug.launch b/freertos/miv-rv32-freertos-demo/miv-rv32-freertos renode-rv32i start-platform-and-debug.launch new file mode 100644 index 0000000..d9a3952 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/miv-rv32-freertos renode-rv32i start-platform-and-debug.launch @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/freertos/miv-rv32-freertos-demo/miv-rv32-freertos-demo hw attach.launch b/freertos/miv-rv32-freertos-demo/miv-rv32-freertos-demo hw attach.launch new file mode 100644 index 0000000..6064269 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/miv-rv32-freertos-demo hw attach.launch @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/freertos/miv-rv32-freertos-demo/miv-rv32-freertos-demo hw debug.launch b/freertos/miv-rv32-freertos-demo/miv-rv32-freertos-demo hw debug.launch new file mode 100644 index 0000000..94ff670 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/miv-rv32-freertos-demo hw debug.launch @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/freertos/miv-rv32-freertos-demo/src/application/FreeRTOSConfig.h b/freertos/miv-rv32-freertos-demo/src/application/FreeRTOSConfig.h new file mode 100644 index 0000000..2db44d3 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/application/FreeRTOSConfig.h @@ -0,0 +1,157 @@ +/* + FreeRTOS V202107.00 + All rights reserved + + VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. + + This file is part of the FreeRTOS distribution. + + FreeRTOS is free software; you can redistribute it and/or modify it under + the terms of the GNU General Public License (version 2) as published by the + Free Software Foundation >>>> AND MODIFIED BY <<<< the FreeRTOS exception. + + *************************************************************************** + >>! NOTE: The modification to the GPL is included to allow you to !<< + >>! distribute a combined work that includes FreeRTOS without being !<< + >>! obliged to provide the source code for proprietary components !<< + >>! outside of the FreeRTOS kernel. !<< + *************************************************************************** + + FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. Full license text is available on the following + link: http://www.freertos.org/a00114.html + + *************************************************************************** + * * + * FreeRTOS provides completely free yet professionally developed, * + * robust, strictly quality controlled, supported, and cross * + * platform software that is more than just the market leader, it * + * is the industry's de facto standard. * + * * + * Help yourself get started quickly while simultaneously helping * + * to support the FreeRTOS project by purchasing a FreeRTOS * + * tutorial book, reference manual, or both: * + * http://www.FreeRTOS.org/Documentation * + * * + *************************************************************************** + + http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading + the FAQ page "My application does not run, what could be wrong?". Have you + defined configASSERT()? + + http://www.FreeRTOS.org/support - In return for receiving this top quality + embedded software for free we request you assist our global community by + participating in the support forum. + + http://www.FreeRTOS.org/training - Investing in training allows your team to + be as productive as possible as early as possible. Now you can receive + FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers + Ltd, and the world's leading authority on the world's leading RTOS. + + http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, + including FreeRTOS+Trace - an indispensable productivity tool, a DOS + compatible FAT file system, and our tiny thread aware UDP/IP stack. + + http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate. + Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS. + + http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High + Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS + licenses offer ticketed support, indemnification and commercial middleware. + + http://www.SafeRTOS.com - High Integrity Systems also provide a safety + engineered and independently SIL3 certified version for use in safety and + mission critical applications that require provable dependability. + + 1 tab == 4 spaces! +*/ + + +#ifndef FREERTOS_CONFIG_H +#define FREERTOS_CONFIG_H + +#ifndef LEGACY_DIR_STRUCTURE +#include "fpga_design_config/fpga_design_config.h" +#else +#include "hw_platform.h" +#endif /*LEGACY_DIR_STRUCTURE*/ + +#include "miv_rv32_hal/miv_rv32_hal.h" + +/* See https://www.freertos.org/Using-FreeRTOS-on-RISC-V.html */ +#define configMTIME_BASE_ADDRESS ( ( PRCI_BASE ) + 0xBFF8UL ) +#define configMTIMECMP_BASE_ADDRESS ( ( PRCI_BASE ) + 0x4000UL ) + +/*----------------------------------------------------------- + * Application specific definitions. + * + * These definitions should be adjusted for your particular hardware and + * application requirements. + * + * THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE + * FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE. + * + * See http://www.freertos.org/a00110.html. + *----------------------------------------------------------*/ + +#define configUSE_PREEMPTION 1 +#define configUSE_IDLE_HOOK 1 +#define configUSE_TICK_HOOK 1 +#define configCPU_CLOCK_HZ ( ( uint32_t ) ( SYS_CLK_FREQ ) ) +#define configTICK_RATE_HZ ( ( TickType_t ) 1000 ) +#define configMAX_PRIORITIES ( 5 ) +#define configMINIMAL_STACK_SIZE ( ( uint32_t ) 500 ) +#define configTOTAL_HEAP_SIZE ( ( size_t ) ( 170 * 1024 ) ) +#define configMAX_TASK_NAME_LEN ( 16 ) +#define configUSE_TRACE_FACILITY 0 +#define configUSE_16_BIT_TICKS 0 +#define configIDLE_SHOULD_YIELD 0 +#define configUSE_MUTEXES 1 +#define configQUEUE_REGISTRY_SIZE 8 +#define configCHECK_FOR_STACK_OVERFLOW 2 +#define configUSE_RECURSIVE_MUTEXES 1 +#define configUSE_MALLOC_FAILED_HOOK 1 +#define configUSE_APPLICATION_TASK_TAG 0 +#define configUSE_COUNTING_SEMAPHORES 1 +#define configGENERATE_RUN_TIME_STATS 0 +#define configUSE_PORT_OPTIMISED_TASK_SELECTION 1 + +/* Co-routine definitions. */ +#define configUSE_CO_ROUTINES 0 +#define configMAX_CO_ROUTINE_PRIORITIES ( 2 ) + +/* Software timer definitions. */ +#define configUSE_TIMERS 1 +#define configTIMER_TASK_PRIORITY ( configMAX_PRIORITIES - 1 ) +#define configTIMER_QUEUE_LENGTH 4 +#define configTIMER_TASK_STACK_DEPTH ( configMINIMAL_STACK_SIZE ) + +/* Task priorities. Allow these to be overridden. */ +#ifndef uartPRIMARY_PRIORITY + #define uartPRIMARY_PRIORITY ( configMAX_PRIORITIES - 3 ) +#endif + +/* Set the following definitions to 1 to include the API function, or zero +to exclude the API function. */ +#define INCLUDE_vTaskPrioritySet 1 +#define INCLUDE_uxTaskPriorityGet 1 +#define INCLUDE_vTaskDelete 1 +#define INCLUDE_vTaskCleanUpResources 1 +#define INCLUDE_vTaskSuspend 1 +#define INCLUDE_vTaskDelayUntil 1 +#define INCLUDE_vTaskDelay 1 +#define INCLUDE_eTaskGetState 1 +#define INCLUDE_xTimerPendFunctionCall 1 +#define INCLUDE_xTaskAbortDelay 1 +#define INCLUDE_xTaskGetHandle 1 +#define INCLUDE_xSemaphoreGetMutexHolder 1 + +/* Normal assert() semantics without relying on the provision of an assert.h +header file. */ +#define configASSERT( x ) if( ( x ) == 0 ) { taskDISABLE_INTERRUPTS(); __asm volatile( "ebreak" ); for( ;; ); } + +/* Defined in main.c and used in main_blinky.c and main_full.c. */ +void vSendString( const char * const pcString ); + +#endif /* FREERTOS_CONFIG_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/application/blinky_demo/main_blinky.c b/freertos/miv-rv32-freertos-demo/src/application/blinky_demo/main_blinky.c new file mode 100644 index 0000000..7ff3e8a --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/application/blinky_demo/main_blinky.c @@ -0,0 +1,206 @@ +/* + * FreeRTOS V202107.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +/****************************************************************************** + * NOTE 1: This project provides two demo applications. A simple blinky + * style project, and a more comprehensive test and demo application. The + * mainCREATE_SIMPLE_BLINKY_DEMO_ONLY setting in main.c is used to select + * between the two. See the notes on using mainCREATE_SIMPLE_BLINKY_DEMO_ONLY + * in main.c. This file implements the simply blinky style version. + * + * NOTE 2: This file only contains the source code that is specific to the + * basic demo. Generic functions, such FreeRTOS hook functions, and functions + * required to configure the hardware are defined in main.c. + ****************************************************************************** + * + * main_blinky() creates one queue, and two tasks. It then starts the + * scheduler. + * + * The Queue Send Task: + * The queue send task is implemented by the prvQueueSendTask() function in + * this file. prvQueueSendTask() sits in a loop that causes it to repeatedly + * block for 1000 milliseconds, before sending the value 100 to the queue that + * was created within main_blinky(). Once the value is sent, the task loops + * back around to block for another 1000 milliseconds...and so on. + * + * The Queue Receive Task: + * The queue receive task is implemented by the prvQueueReceiveTask() function + * in this file. prvQueueReceiveTask() sits in a loop where it repeatedly + * blocks on attempts to read data from the queue that was created within + * main_blinky(). When data is received, the task checks the value of the + * data, and if the value equals the expected 100, writes 'Blink' to the UART + * (the UART is used in place of the LED to allow easy execution in QEMU). The + * 'block time' parameter passed to the queue receive function specifies that + * the task should be held in the Blocked state indefinitely to wait for data to + * be available on the queue. The queue receive task will only leave the + * Blocked state when the queue send task writes to the queue. As the queue + * send task writes to the queue every 1000 milliseconds, the queue receive + * task leaves the Blocked state every 1000 milliseconds, and therefore toggles + * the LED every 200 milliseconds. + */ + +/* Standard includes. */ +#include +#include +#include + +/* Kernel includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" + +/* Priorities used by the tasks. */ +#define mainQUEUE_RECEIVE_TASK_PRIORITY ( tskIDLE_PRIORITY + 2 ) +#define mainQUEUE_SEND_TASK_PRIORITY ( tskIDLE_PRIORITY + 1 ) + +/* The rate at which data is sent to the queue. The 200ms value is converted +to ticks using the pdMS_TO_TICKS() macro. */ +#define mainQUEUE_SEND_FREQUENCY_MS pdMS_TO_TICKS( 1000 ) /* 1000 */ + +/* The maximum number items the queue can hold. The priority of the receiving +task is above the priority of the sending task, so the receiving task will +preempt the sending task and remove the queue items each time the sending task +writes to the queue. Therefore the queue will never have more than one item in +it at any time, and even with a queue length of 1, the sending task will never +find the queue full. */ +#define mainQUEUE_LENGTH ( 1 ) + +/*-----------------------------------------------------------*/ + +/* + * Called by main when mainCREATE_SIMPLE_BLINKY_DEMO_ONLY is set to 1 in + * main.c. + */ +void main_blinky( void ); + +/* + * The tasks as described in the comments at the top of this file. + */ +static void prvQueueReceiveTask( void *pvParameters ); +static void prvQueueSendTask( void *pvParameters ); + +/*-----------------------------------------------------------*/ + +/* The queue used by both tasks. */ +static QueueHandle_t xQueue = NULL; + +/*-----------------------------------------------------------*/ + +void main_blinky( void ) +{ + /* Create the queue. */ + xQueue = xQueueCreate( mainQUEUE_LENGTH, sizeof( uint32_t ) ); + + if( xQueue != NULL ) + { + /* Start the two tasks as described in the comments at the top of this + file. */ + xTaskCreate( prvQueueReceiveTask, /* The function that implements the task. */ + "Rx", /* The text name assigned to the task - for debug only as it is not used by the kernel. */ + configMINIMAL_STACK_SIZE * 2U, /* The size of the stack to allocate to the task. */ + NULL, /* The parameter passed to the task - not used in this case. */ + mainQUEUE_RECEIVE_TASK_PRIORITY, /* The priority assigned to the task. */ + NULL ); /* The task handle is not required, so NULL is passed. */ + + xTaskCreate( prvQueueSendTask, "TX", configMINIMAL_STACK_SIZE * 2U, NULL, mainQUEUE_SEND_TASK_PRIORITY, NULL ); + + /* Start the tasks and timer running. */ + vTaskStartScheduler(); + } + + /* If all is well, the scheduler will now be running, and the following + line will never be reached. If the following line does execute, then + there was insufficient FreeRTOS heap memory available for the Idle and/or + timer tasks to be created. See the memory management section on the + FreeRTOS web site for more details on the FreeRTOS heap + http://www.freertos.org/a00111.html. */ + for( ;; ); +} +/*-----------------------------------------------------------*/ + +static void prvQueueSendTask( void *pvParameters ) +{ +TickType_t xNextWakeTime; +const unsigned long ulValueToSend = 100UL; +BaseType_t xReturned; + + /* Remove compiler warning about unused parameter. */ + ( void ) pvParameters; + + /* Initialise xNextWakeTime - this only needs to be done once. */ + xNextWakeTime = xTaskGetTickCount(); + + for( ;; ) + { + /* Place this task in the blocked state until it is time to run again. */ + vTaskDelayUntil( &xNextWakeTime, mainQUEUE_SEND_FREQUENCY_MS ); + /* vTaskDelay(mainQUEUE_SEND_FREQUENCY_MS); */ + + /* Send to the queue - causing the queue receive task to unblock and + toggle the LED. 0 is used as the block time so the sending operation + will not block - it shouldn't need to block as the queue should always + be empty at this point in the code. */ + xReturned = xQueueSend( xQueue, &ulValueToSend, 0U ); + configASSERT( xReturned == pdPASS ); + } +} +/*-----------------------------------------------------------*/ + +static void prvQueueReceiveTask( void *pvParameters ) +{ +unsigned long ulReceivedValue; +const unsigned long ulExpectedValue = 100UL; +const char * const pcPassMessage = "Blink\r\n"; +const char * const pcFailMessage = "Unexpected value received\r\n"; +extern void vToggleLED( void ); + + /* Remove compiler warning about unused parameter. */ + ( void ) pvParameters; + + for( ;; ) + { + /* Wait until something arrives in the queue - this task will block + indefinitely provided INCLUDE_vTaskSuspend is set to 1 in + FreeRTOSConfig.h. */ + xQueueReceive( xQueue, &ulReceivedValue, portMAX_DELAY ); + + /* To get here something must have been received from the queue, but + is it the expected value? If it is, toggle the LED. */ + if( ulReceivedValue == ulExpectedValue ) + { + vSendString( pcPassMessage ); + vToggleLED(); + ulReceivedValue = 0U; + } + else + { + vSendString( pcFailMessage ); + } + } +} +/*-----------------------------------------------------------*/ + diff --git a/freertos/miv-rv32-freertos-demo/src/application/full_demo/RegTest.S b/freertos/miv-rv32-freertos-demo/src/application/full_demo/RegTest.S new file mode 100644 index 0000000..06a14ec --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/application/full_demo/RegTest.S @@ -0,0 +1,266 @@ +/* + * FreeRTOS V202107.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + + .extern ulRegTest1LoopCounter + .extern ulRegTest2LoopCounter + + .global vRegTest1Implementation + .global vRegTest2Implementation + +/*-----------------------------------------------------------*/ + +/* + * The register check tasks are described in the comments at the top of + * main_full.c. + */ + +.align( 4 ) +vRegTest1Implementation: + + /* Fill the core registers with known values. */ + li x5, 0x5 + li x6, 0x6 + li x7, 0x7 + li x8, 0x8 + li x9, 0x9 + li x10, 0xa + li x11, 0xb + li x12, 0xc + li x13, 0xd + li x14, 0xe + li x15, 0xf + li x16, 0x10 + li x17, 0x11 + li x18, 0x12 + li x19, 0x13 + li x20, 0x14 + li x21, 0x15 + li x22, 0x16 + li x23, 0x17 + li x24, 0x18 + li x25, 0x19 + li x26, 0x1a + li x27, 0x1b + li x28, 0x1c + li x29, 0x1d + li x30, 0x1e + +reg1_loop: + + /* Check each register still contains the expected known value. + vRegTest1Implementation uses x31 as the temporary, vRegTest2Implementation + uses x5 as the temporary. */ + li x31, 0x5 + bne x31, x5, reg1_error_loop + li x31, 0x6 + bne x31, x6, reg1_error_loop + li x31, 0x7 + bne x31, x7, reg1_error_loop + li x31, 0x8 + bne x31, x8, reg1_error_loop + li x31, 0x9 + bne x31, x9, reg1_error_loop + li x31, 0xa + bne x31, x10, reg1_error_loop + li x31, 0xb + bne x31, x11, reg1_error_loop + li x31, 0xc + bne x31, x12, reg1_error_loop + li x31, 0xd + bne x31, x13, reg1_error_loop + li x31, 0xe + bne x31, x14, reg1_error_loop + li x31, 0xf + bne x31, x15, reg1_error_loop + li x31, 0x10 + bne x31, x16, reg1_error_loop + li x31, 0x11 + bne x31, x17, reg1_error_loop + li x31, 0x12 + bne x31, x18, reg1_error_loop + li x31, 0x13 + bne x31, x19, reg1_error_loop + li x31, 0x14 + bne x31, x20, reg1_error_loop + li x31, 0x15 + bne x31, x21, reg1_error_loop + li x31, 0x16 + bne x31, x22, reg1_error_loop + li x31, 0x17 + bne x31, x23, reg1_error_loop + li x31, 0x18 + bne x31, x24, reg1_error_loop + li x31, 0x19 + bne x31, x25, reg1_error_loop + li x31, 0x1a + bne x31, x26, reg1_error_loop + li x31, 0x1b + bne x31, x27, reg1_error_loop + li x31, 0x1c + bne x31, x28, reg1_error_loop + li x31, 0x1d + bne x31, x29, reg1_error_loop + li x31, 0x1e + bne x31, x30, reg1_error_loop + + /* Everything passed, increment the loop counter. */ + lw x31, ulRegTest1LoopCounterConst + lw x30, 0(x31) + addi x30, x30, 1 + sw x30, 0(x31) + + /* Restore clobbered register reading for next loop. */ + li x30, 0x1e + + /* Yield to increase code coverage. */ + ecall + + /* Start again. */ + jal reg1_loop + +reg1_error_loop: + /* Jump here if a register contains an uxpected value. This stops the loop + counter being incremented so the check task knows an error was found. */ + ebreak + jal reg1_error_loop + +.align( 4 ) +ulRegTest1LoopCounterConst: .word ulRegTest1LoopCounter + +/*-----------------------------------------------------------*/ + +.align( 4 ) +vRegTest2Implementation: + + /* Fill the core registers with known values. */ + li x6, 0x61 + li x7, 0x71 + li x8, 0x81 + li x9, 0x91 + li x10, 0xa1 + li x11, 0xb1 + li x12, 0xc1 + li x13, 0xd1 + li x14, 0xe1 + li x15, 0xf1 + li x16, 0x20 + li x17, 0x21 + li x18, 0x22 + li x19, 0x23 + li x20, 0x24 + li x21, 0x25 + li x22, 0x26 + li x23, 0x27 + li x24, 0x28 + li x25, 0x29 + li x26, 0x2a + li x27, 0x2b + li x28, 0x2c + li x29, 0x2d + li x30, 0x2e + li x31, 0x2f + +Reg2_loop: + + /* Check each register still contains the expected known value. + vRegTest2Implementation uses x5 as the temporary, vRegTest1Implementation + uses x31 as the temporary. */ + li x5, 0x61 + bne x5, x6, reg2_error_loop + li x5, 0x71 + bne x5, x7, reg2_error_loop + li x5, 0x81 + bne x5, x8, reg2_error_loop + li x5, 0x91 + bne x5, x9, reg2_error_loop + li x5, 0xa1 + bne x5, x10, reg2_error_loop + li x5, 0xb1 + bne x5, x11, reg2_error_loop + li x5, 0xc1 + bne x5, x12, reg2_error_loop + li x5, 0xd1 + bne x5, x13, reg2_error_loop + li x5, 0xe1 + bne x5, x14, reg2_error_loop + li x5, 0xf1 + bne x5, x15, reg2_error_loop + li x5, 0x20 + bne x5, x16, reg2_error_loop + li x5, 0x21 + bne x5, x17, reg2_error_loop + li x5, 0x22 + bne x5, x18, reg2_error_loop + li x5, 0x23 + bne x5, x19, reg2_error_loop + li x5, 0x24 + bne x5, x20, reg2_error_loop + li x5, 0x25 + bne x5, x21, reg2_error_loop + li x5, 0x26 + bne x5, x22, reg2_error_loop + li x5, 0x27 + bne x5, x23, reg2_error_loop + li x5, 0x28 + bne x5, x24, reg2_error_loop + li x5, 0x29 + bne x5, x25, reg2_error_loop + li x5, 0x2a + bne x5, x26, reg2_error_loop + li x5, 0x2b + bne x5, x27, reg2_error_loop + li x5, 0x2c + bne x5, x28, reg2_error_loop + li x5, 0x2d + bne x5, x29, reg2_error_loop + li x5, 0x2e + bne x5, x30, reg2_error_loop + li x5, 0x2f + bne x5, x31, reg2_error_loop + + /* Everything passed, increment the loop counter. */ + lw x5, ulRegTest2LoopCounterConst + lw x6, 0(x5) + addi x6, x6, 1 + sw x6, 0(x5) + + /* Restore clobbered register reading for next loop. */ + li x6, 0x61 + + /* Start again. */ + jal Reg2_loop + +reg2_error_loop: + /* Jump here if a register contains an uxpected value. This stops the loop + counter being incremented so the check task knows an error was found. */ + ebreak + jal reg2_error_loop + +.align( 4 ) +ulRegTest2LoopCounterConst: .word ulRegTest2LoopCounter + + diff --git a/freertos/miv-rv32-freertos-demo/src/application/full_demo/main_full.c b/freertos/miv-rv32-freertos-demo/src/application/full_demo/main_full.c new file mode 100644 index 0000000..bd1a903 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/application/full_demo/main_full.c @@ -0,0 +1,511 @@ +/* + * FreeRTOS V202107.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/****************************************************************************** + * NOTE 1: This project provides two demo applications. A simple blinky style + * project, and a more comprehensive test and demo application. The + * mainCREATE_SIMPLE_BLINKY_DEMO_ONLY setting in main.c is used to select + * between the two. See the notes on using mainCREATE_SIMPLE_BLINKY_DEMO_ONLY + * in main.c. This file implements the comprehensive test and demo version. + * + * NOTE 2: This file only contains the source code that is specific to the + * full demo. Generic functions, such FreeRTOS hook functions, and functions + * required to configure the hardware, are defined in main.c. + * + ****************************************************************************** + * + * main_full() creates all the demo application tasks and software timers, then + * starts the scheduler. The web documentation provides more details of the + * standard demo application tasks, which provide no particular functionality, + * but do provide a good example of how to use the FreeRTOS API. + * + * In addition to the standard demo tasks, the following tasks and tests are + * defined and/or created within this file: + * + * "Reg test" tasks - These fill both the core registers with known values, then + * check that each register maintains its expected value for the lifetime of the + * task. Each task uses a different set of values. The reg test tasks execute + * with a very low priority, so get preempted very frequently. A register + * containing an unexpected value is indicative of an error in the context + * switching mechanism. + * + * "Check" task - The check executes every three seconds. It checks that all + * the standard demo tasks, and the register check tasks, are not only still + * executing, but are executing without reporting any errors. If the check task + * discovers that a task has either stalled, or reported an error, then it + * prints an error message to the UART, otherwise it prints "Pass.". + */ + +/* Standard includes. */ +#include +#include + +/* Kernel includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "timers.h" +#include "semphr.h" + +/* Microchip includes. */ +#include "drivers/fpga_ip/CoreTimer/core_timer.h" +#include "miv_rv32_hal/miv_rv32_hal.h" +#include "hal/hal.h" + +/* Standard demo application includes. */ +#include "dynamic.h" +#include "blocktim.h" +#include "GenQTest.h" +#include "recmutex.h" +#include "TimerDemo.h" +#include "EventGroupsDemo.h" +#include "TaskNotify.h" +#include "AbortDelay.h" +#include "countsem.h" +#include "death.h" +#include "MessageBufferDemo.h" +#include "StreamBufferDemo.h" +#include "StreamBufferInterrupt.h" + +/* Priorities for the demo application tasks. */ +#define mainCHECK_TASK_PRIORITY ( configMAX_PRIORITIES - 1 ) +#define mainCREATOR_TASK_PRIORITY ( tskIDLE_PRIORITY + 3UL ) + +/* The period of the check task, in ms, converted to ticks using the +pdMS_TO_TICKS() macro. mainNO_ERROR_CHECK_TASK_PERIOD is used if no errors have +been found, mainERROR_CHECK_TASK_PERIOD is used if an error has been found. */ +#define mainNO_ERROR_CHECK_TASK_PERIOD pdMS_TO_TICKS( 3000UL ) +#define mainERROR_CHECK_TASK_PERIOD pdMS_TO_TICKS( 500UL ) + +/* Parameters that are passed into the register check tasks solely for the +purpose of ensuring parameters are passed into tasks correctly. */ +#define mainREG_TEST_TASK_1_PARAMETER ( ( void * ) 0x12345678 ) +#define mainREG_TEST_TASK_2_PARAMETER ( ( void * ) 0x87654321 ) + +/* The base period used by the timer test tasks. */ +#define mainTIMER_TEST_PERIOD ( 50 ) + +/* The size of the stack allocated to the check task (as described in the +comments at the top of this file. */ +#define mainCHECK_TASK_STACK_SIZE_WORDS 100 + +/* Size of the stacks to allocated for the register check tasks. */ +#define mainREG_TEST_STACK_SIZE_WORDS 300 + +/* Maintain compatibility accross all designs */ +#ifndef CORETIMER0_BASE_ADDR +#define CORETIMER0_BASE_ADDR MIV_ESS_APBSLOT3_BASE_ADDR +#endif +#ifndef CORETIMER1_BASE_ADDR +#define CORETIMER1_BASE_ADDR MIV_ESS_APBSLOT4_BASE_ADDR +#endif + + +/*-----------------------------------------------------------*/ + +/* + * Called by main() to run the full demo (as opposed to the blinky demo) when + * mainCREATE_SIMPLE_BLINKY_DEMO_ONLY is set to 0. + */ +void main_full( void ); + +/* + * The check task, as described at the top of this file. + */ +static void prvCheckTask( void *pvParameters ); + +/* + * Initialise and start the peripheral timers that are used to exercise external + * interrupt processing. + */ +static void prvSetupPeripheralTimers( void ); + +/* + * Register check tasks as described at the top of this file. The nature of + * these files necessitates that they are written in an assembly file, but the + * entry points are kept in the C file for the convenience of checking the task + * parameter. + */ +static void prvRegTestTaskEntry1( void *pvParameters ); +extern void vRegTest1Implementation( void ); +static void prvRegTestTaskEntry2( void *pvParameters ); +extern void vRegTest2Implementation( void ); + +/* + * Tick hook used by the full demo, which includes code that interacts with + * some of the tests. + */ +void vFullDemoTickHook( void ); + +/*-----------------------------------------------------------*/ + +/* Timers used to exercise external interrupt processing. */ +static timer_instance_t g_timer0, g_timer1; + +/* Variables incremented by the peripheral timers used to exercise external +interrupts. */ +volatile uint32_t ulTimer0Interrupts = 0, ulTimer1Interrupts = 0; + +/* The following two variables are used to communicate the status of the +register check tasks to the check task. If the variables keep incrementing, +then the register check tasks have not discovered any errors. If a variable +stops incrementing, then an error has been found. */ +volatile uint32_t ulRegTest1LoopCounter = 0UL, ulRegTest2LoopCounter = 0UL; + +/*-----------------------------------------------------------*/ + +void main_full( void ) +{ + /* Start all the other standard demo/test tasks. They have no particular + functionality, but do demonstrate how to use the FreeRTOS API and test the + kernel port. */ + vStartDynamicPriorityTasks(); + vCreateBlockTimeTasks(); + vStartGenericQueueTasks( tskIDLE_PRIORITY ); + vStartRecursiveMutexTasks(); + vStartTimerDemoTask( mainTIMER_TEST_PERIOD ); + vStartEventGroupTasks(); + vStartTaskNotifyTask(); + vCreateAbortDelayTasks(); + vStartCountingSemaphoreTasks(); + vStartMessageBufferTasks( configMINIMAL_STACK_SIZE ); + vStartStreamBufferTasks(); + vStartStreamBufferInterruptDemo(); + + /* Create the register check tasks, as described at the top of this file. + Use xTaskCreateStatic() to create a task using only statically allocated + memory. */ + xTaskCreate( prvRegTestTaskEntry1, /* The function that implements the task. */ + "Reg1", /* The name of the task. */ + mainREG_TEST_STACK_SIZE_WORDS, /* Size of stack to allocate for the task - in words not bytes!. */ + mainREG_TEST_TASK_1_PARAMETER, /* Parameter passed into the task. */ + tskIDLE_PRIORITY, /* Priority of the task. */ + NULL ); /* Can be used to pass out a handle to the created task. */ + xTaskCreate( prvRegTestTaskEntry2, "Reg2", mainREG_TEST_STACK_SIZE_WORDS, mainREG_TEST_TASK_2_PARAMETER, tskIDLE_PRIORITY, NULL ); + + /* Create the task that performs the 'check' functionality, as described at + the top of this file. */ + xTaskCreate( prvCheckTask, "Check", mainCHECK_TASK_STACK_SIZE_WORDS, NULL, mainCHECK_TASK_PRIORITY, NULL ); + + /* The set of tasks created by the following function call have to be + created last as they keep account of the number of tasks they expect to see + running. */ + vCreateSuicidalTasks( mainCREATOR_TASK_PRIORITY ); + + /* Start the timers that are used to exercise external interrupt handling. */ + prvSetupPeripheralTimers(); + + /* Start the scheduler. */ + vSendString( "Starting" ); + vTaskStartScheduler(); + + /* If all is well, the scheduler will now be running, and the following + line will never be reached. If the following line does execute, then + there was insufficient FreeRTOS heap memory available for the Idle and/or + timer tasks to be created. See the memory management section on the + FreeRTOS web site for more details on the FreeRTOS heap + http://www.freertos.org/a00111.html. */ + for( ;; ); +} +/*-----------------------------------------------------------*/ + +static void prvCheckTask( void *pvParameters ) +{ +TickType_t xDelayPeriod = mainNO_ERROR_CHECK_TASK_PERIOD; +TickType_t xLastExecutionTime; +uint32_t ulLastRegTest1Value = 0, ulLastRegTest2Value = 0; +uint32_t ulLastTimer0Interrupts = 0, ulLastTimer1Interrupts = 0; +char * const pcPassMessage = "."; +char * pcStatusMessage = pcPassMessage; +extern void vToggleLED( void ); + + /* Just to stop compiler warnings. */ + ( void ) pvParameters; + + /* Initialise xLastExecutionTime so the first call to vTaskDelayUntil() + works correctly. */ + xLastExecutionTime = xTaskGetTickCount(); + + /* Cycle for ever, delaying then checking all the other tasks are still + operating without error. The onboard LED is toggled on each iteration. + If an error is detected then the delay period is decreased from + mainNO_ERROR_CHECK_TASK_PERIOD to mainERROR_CHECK_TASK_PERIOD. This has the + effect of increasing the rate at which the onboard LED toggles, and in so + doing gives visual feedback of the system status. */ + for( ;; ) + { + /* Delay until it is time to execute again. */ + vTaskDelayUntil( &xLastExecutionTime, xDelayPeriod ); + + /* Check all the demo tasks (other than the flash tasks) to ensure + that they are all still running, and that none have detected an error. */ + if( xAreDynamicPriorityTasksStillRunning() == pdFALSE ) + { + pcStatusMessage = "ERROR: Dynamic priority demo/tests.\r\n"; + } + + if( xAreBlockTimeTestTasksStillRunning() == pdFALSE ) + { + pcStatusMessage = "ERROR: Block time demo/tests.\r\n"; + } + + if( xAreGenericQueueTasksStillRunning() == pdFALSE ) + { + pcStatusMessage = "ERROR: Generic queue demo/tests.\r\n"; + } + + if( xAreRecursiveMutexTasksStillRunning() == pdFALSE ) + { + pcStatusMessage = "ERROR: Recursive mutex demo/tests.\r\n"; + } + + if( xAreTimerDemoTasksStillRunning( ( TickType_t ) xDelayPeriod ) == pdFALSE ) + { + pcStatusMessage = "ERROR: Timer demo/tests.\r\n"; + } + + if( xAreEventGroupTasksStillRunning() == pdFALSE ) + { + pcStatusMessage = "ERROR: Event group demo/tests.\r\n"; + } + + if( xAreTaskNotificationTasksStillRunning() == pdFALSE ) + { + pcStatusMessage = "ERROR: Task notification demo/tests.\r\n"; + } + + if( xAreAbortDelayTestTasksStillRunning() == pdFALSE ) + { + pcStatusMessage = "ERROR: Abort delay.\r\n"; + } + + if( xAreCountingSemaphoreTasksStillRunning() == pdFALSE ) + { + pcStatusMessage = "ERROR: Counting semaphores.\r\n"; + } + + if( xIsCreateTaskStillRunning() == pdFALSE ) + { + pcStatusMessage = "ERROR: Suicide tasks.\r\n"; + } + + if( xAreMessageBufferTasksStillRunning() == pdFALSE ) + { + pcStatusMessage = "ERROR: Message buffer.\r\n"; + } + + if( xAreStreamBufferTasksStillRunning() == pdFALSE ) + { + pcStatusMessage = "ERROR: Stream buffer.\r\n"; + } + + if( xIsInterruptStreamBufferDemoStillRunning() == pdFALSE ) + { + pcStatusMessage = "ERROR: Stream buffer interrupt.\r\n"; + } + + /* Check that the register test 1 task is still running. */ + if( ulLastRegTest1Value == ulRegTest1LoopCounter ) + { + pcStatusMessage = "ERROR: Register test 1.\r\n"; + } + ulLastRegTest1Value = ulRegTest1LoopCounter; + + /* Check that the register test 2 task is still running. */ + if( ulLastRegTest2Value == ulRegTest2LoopCounter ) + { + pcStatusMessage = "ERROR: Register test 2.\r\n"; + } + ulLastRegTest2Value = ulRegTest2LoopCounter; + + /* Check interrupts from the peripheral timers are being handled. */ + if( ulLastTimer0Interrupts == ulTimer0Interrupts ) + { + pcStatusMessage = "ERROR: Peripheral timer 0.\r\n"; + } + ulLastTimer0Interrupts = ulTimer0Interrupts; + + if( ulLastTimer1Interrupts == ulTimer1Interrupts ) + { + pcStatusMessage = "ERROR: Peripheral timer 1.\r\n"; + } + ulLastTimer1Interrupts = ulTimer1Interrupts; + + /* Write the status message to the UART. */ + vSendString( pcStatusMessage ); + vToggleLED(); + + /* If an error has been found then increase the LED toggle rate by + increasing the cycle frequency. */ + if( pcStatusMessage != pcPassMessage ) + { + xDelayPeriod = mainERROR_CHECK_TASK_PERIOD; + } + } +} +/*-----------------------------------------------------------*/ + +static void prvRegTestTaskEntry1( void *pvParameters ) +{ + /* Although the regtest task is written in assembler, its entry point is + written in C for convenience of checking the task parameter is being passed + in correctly. */ + if( pvParameters == mainREG_TEST_TASK_1_PARAMETER ) + { + /* Start the part of the test that is written in assembler. */ + vRegTest1Implementation(); + } + + /* The following line will only execute if the task parameter is found to + be incorrect. The check task will detect that the regtest loop counter is + not being incremented and flag an error. */ + vTaskDelete( NULL ); +} +/*-----------------------------------------------------------*/ + +static void prvRegTestTaskEntry2( void *pvParameters ) +{ + /* Although the regtest task is written in assembler, its entry point is + written in C for convenience of checking the task parameter is being passed + in correctly. */ + if( pvParameters == mainREG_TEST_TASK_2_PARAMETER ) + { + /* Start the part of the test that is written in assembler. */ + vRegTest2Implementation(); + } + + /* The following line will only execute if the task parameter is found to + be incorrect. The check task will detect that the regtest loop counter is + not being incremented and flag an error. */ + vTaskDelete( NULL ); +} +/*-----------------------------------------------------------*/ + +void vFullDemoTickHook( void ) +{ + /* The full demo includes a software timer demo/test that requires + prodding periodically from the tick interrupt. */ + vTimerPeriodicISRTests(); + + /* Call the periodic event group from ISR demo. */ + vPeriodicEventGroupsProcessing(); + + /* Use task notifications from an interrupt. */ + xNotifyTaskFromISR(); + + /* Writes to stream buffer byte by byte to test the stream buffer trigger + level functionality. */ + vPeriodicStreamBufferProcessing(); + + /* Writes a string to a string buffer four bytes at a time to demonstrate + a stream being sent from an interrupt to a task. */ + vBasicStreamBufferSendFromISR(); + + /* Called from vApplicationTickHook() when the project is configured to + build the full test/demo applications. */ +} +/*-----------------------------------------------------------*/ + +static void prvSetupPeripheralTimers( void ) +{ + TMR_init( &g_timer0, + CORETIMER0_BASE_ADDR, + TMR_CONTINUOUS_MODE, + PRESCALER_DIV_1024, + 83000 ); + + TMR_init( &g_timer1, + CORETIMER1_BASE_ADDR, + TMR_CONTINUOUS_MODE, + PRESCALER_DIV_512, + 42000 ); + + #ifdef MIV_LEGACY_RV32 + /* In this version of the PLIC, the priorities are fixed at 1. + Lower numbered devices have higher priorities. But this code is given as + an example. + */ + MRV_PLIC_set_priority( External_30_IRQn, 1 ); + MRV_PLIC_set_priority( External_31_IRQn, 1 ); + + /*Enable Timer 1 & 0 Interrupt*/ + MRV_PLIC_enable_irq( External_30_IRQn ); + MRV_PLIC_enable_irq( External_31_IRQn ); + #else + /*Enable Timer 1 & 0 Interrupt*/ + MRV_enable_local_irq( MRV32_EXT_IRQn ); + MRV_enable_local_irq( MRV32_MSYS_EIE0_IRQn ); + #endif /* MIV_LEGACY_RV32 */ + + /* Enable the timers */ + TMR_enable_int( &g_timer0 ); + TMR_enable_int( &g_timer1 ); + + /* Make sure timers don't interrupt until the scheduler is running. */ + portDISABLE_INTERRUPTS(); + + /*Start the timer*/ + TMR_start( &g_timer0 ); + TMR_start( &g_timer1 ); +} +/*-----------------------------------------------------------*/ + +#ifdef MIV_LEGACY_RV32 +/*Core Timer 0 Interrupt Handler*/ +uint8_t External_30_IRQHandler( void ) +{ + ulTimer0Interrupts++; + TMR_clear_int(&g_timer0); + return( EXT_IRQ_KEEP_ENABLED ); +} +/*-----------------------------------------------------------*/ + +/*Core Timer 1 Interrupt Handler*/ +uint8_t External_31_IRQHandler( void ) +{ + ulTimer1Interrupts++; + TMR_clear_int(&g_timer1); + + return( EXT_IRQ_KEEP_ENABLED ); +} +#else +/*Core Timer 0 Interrupt Handler for MIV_RV32 core*/ +uint8_t MSYS_EI0_IRQHandler( void ) +{ + ulTimer0Interrupts++; + TMR_clear_int(&g_timer0); + + return( EXT_IRQ_KEEP_ENABLED ); +} + +/*Core Timer 1 Interrupt Handler for MIV_RV32 core*/ +uint8_t External_IRQHandler( void ) +{ + ulTimer1Interrupts++; + TMR_clear_int(&g_timer1); + + return( EXT_IRQ_KEEP_ENABLED ); +} +#endif /* MIV_LEGACY_RV32 */ diff --git a/freertos/miv-rv32-freertos-demo/src/application/main.c b/freertos/miv-rv32-freertos-demo/src/application/main.c new file mode 100644 index 0000000..4c8690c --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/application/main.c @@ -0,0 +1,196 @@ +/* + * FreeRTOS V202107.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +/* FreeRTOS kernel includes. */ +#include "FreeRTOS.h" +#include "task.h" + +/* Microchip includes. */ +#include "drivers/fpga_ip/CoreUARTapb/core_uart_apb.h" +#include "drivers/fpga_ip/CoreGPIO/core_gpio.h" + +/****************************************************************************** + * This project provides two demo applications. A simple blinky style project, + * and a more comprehensive test and demo application. The + * mainCREATE_SIMPLE_BLINKY_DEMO_ONLY setting (defined in this file) is used to + * select between the two. The simply blinky demo is implemented and described + * in main_blinky.c. The more comprehensive test and demo application is + * implemented and described in main_full.c. + * + * This file implements the code that is not demo specific, including the + * hardware setup and standard FreeRTOS hook functions. + * + * ENSURE TO READ THE DOCUMENTATION PAGE FOR THIS PORT AND DEMO APPLICATION ON + * THE http://www.FreeRTOS.org WEB SITE FOR FULL INFORMATION ON USING THIS DEMO + * APPLICATION, AND ITS ASSOCIATE FreeRTOS ARCHITECTURE PORT! + * + */ + +/* Set mainCREATE_SIMPLE_BLINKY_DEMO_ONLY to one to run the simple blinky demo, +or 0 to run the more comprehensive test and demo application. */ +#define mainCREATE_SIMPLE_BLINKY_DEMO_ONLY 0 + +/* + * main_blinky() is used when mainCREATE_SIMPLE_BLINKY_DEMO_ONLY is set to 1. + * main_full() is used when mainCREATE_SIMPLE_BLINKY_DEMO_ONLY is set to 0. + */ +#if mainCREATE_SIMPLE_BLINKY_DEMO_ONLY == 1 + extern void main_blinky( void ); +#else + extern void main_full( void ); +#endif /* #if mainCREATE_SIMPLE_BLINKY_DEMO_ONLY == 1 */ + +/* Prototypes for the standard FreeRTOS callback/hook functions implemented +within this file. See https://www.freertos.org/a00016.html */ +void vApplicationMallocFailedHook( void ); +void vApplicationIdleHook( void ); +void vApplicationStackOverflowHook( TaskHandle_t pxTask, char *pcTaskName ); +void vApplicationTickHook( void ); + +/* Prepare hardware to run the demo. */ +static void prvSetupHardware( void ); + +/* Send a message to the UART initialised in prvSetupHardware. */ +void vSendString( const char * const pcString ); + +/*-----------------------------------------------------------*/ + +/* The UART to which strings are output, and the GPIO used to toggle the LED. */ +static UART_instance_t g_uart; +static gpio_instance_t g_gpio_out; + +/*-----------------------------------------------------------*/ + +int main( void ) +{ + prvSetupHardware(); + + /* The mainCREATE_SIMPLE_BLINKY_DEMO_ONLY setting is described at the top + of this file. */ + #if( mainCREATE_SIMPLE_BLINKY_DEMO_ONLY == 1 ) + { + main_blinky(); + } + #else + { + main_full(); + } + #endif +} +/*-----------------------------------------------------------*/ + +static void prvSetupHardware( void ) +{ + #ifdef MIV_LEGACY_RV32 + MRV_PLIC_init(); + #endif /* MIV_LEGACY_RV32 */ + UART_init( &g_uart, COREUARTAPB0_BASE_ADDR, BAUD_VALUE_115200, ( DATA_8_BITS | NO_PARITY ) ); + GPIO_init( &g_gpio_out, COREGPIO_OUT_BASE_ADDR, GPIO_APB_32_BITS_BUS ); /* added to init LED*/ + + /* The CoreGPIO IP instantiated in the reference designs provided on Github + * have is configured to have GPIO_0 to GPIO_3 ports as outputs. + * This configuration can not be changed by the firmware since it is fixed in + * the CoreGPIO instance. In your Libero design if you do not make + * the GPIO configurations 'fixed', then you will need to configure them + * using GPIO_config() function*/ + /* GPIO_config( &g_gpio_out, GPIO_1, GPIO_OUTPUT_MODE ); */ /* added to configure LED*/ +} +/*-----------------------------------------------------------*/ + +void vToggleLED( void ) +{ +static uint32_t ulLEDState = 0; + + GPIO_set_outputs( &g_gpio_out, ulLEDState ); + ulLEDState = !ulLEDState; + +} + +/*-----------------------------------------------------------*/ + +void vSendString( const char * const pcString ) +{ + UART_polled_tx_string( &g_uart, ( const uint8_t * ) pcString ); +} +/*-----------------------------------------------------------*/ + +void vApplicationMallocFailedHook( void ) +{ + /* vApplicationMallocFailedHook() will only be called if + configUSE_MALLOC_FAILED_HOOK is set to 1 in FreeRTOSConfig.h. It is a hook + function that will get called if a call to pvPortMalloc() fails. + pvPortMalloc() is called internally by the kernel whenever a task, queue, + timer or semaphore is created. It is also called by various parts of the + demo application. If heap_1.c or heap_2.c are used, then the size of the + heap available to pvPortMalloc() is defined by configTOTAL_HEAP_SIZE in + FreeRTOSConfig.h, and the xPortGetFreeHeapSize() API function can be used + to query the size of free heap space that remains (although it does not + provide information on how the remaining heap might be fragmented). */ + taskDISABLE_INTERRUPTS(); + __asm volatile( "ebreak" ); + for( ;; ); +} +/*-----------------------------------------------------------*/ + +void vApplicationIdleHook( void ) +{ + /* vApplicationIdleHook() will only be called if configUSE_IDLE_HOOK is set + to 1 in FreeRTOSConfig.h. It will be called on each iteration of the idle + task. It is essential that code added to this hook function never attempts + to block in any way (for example, call xQueueReceive() with a block time + specified, or call vTaskDelay()). If the application makes use of the + vTaskDelete() API function (as this demo application does) then it is also + important that vApplicationIdleHook() is permitted to return to its calling + function, because it is the responsibility of the idle task to clean up + memory allocated by the kernel to any task that has since been deleted. */ +} +/*-----------------------------------------------------------*/ + +void vApplicationStackOverflowHook( TaskHandle_t pxTask, char *pcTaskName ) +{ + ( void ) pcTaskName; + ( void ) pxTask; + + /* Run time stack overflow checking is performed if + configCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2. This hook + function is called if a stack overflow is detected. */ + taskDISABLE_INTERRUPTS(); + __asm volatile( "ebreak" ); + for( ;; ); +} +/*-----------------------------------------------------------*/ + +void vApplicationTickHook( void ) +{ + /* The tests in the full demo expect some interaction with interrupts. */ + #if( mainCREATE_SIMPLE_BLINKY_DEMO_ONLY != 1 ) + { + extern void vFullDemoTickHook( void ); + vFullDemoTickHook(); + } + #endif +} diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/design description/README.md b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/design description/README.md new file mode 100644 index 0000000..e2dca3b --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/design description/README.md @@ -0,0 +1,3 @@ +# Design Description + + The Libero generated design description will be stored here. \ No newline at end of file diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/PF_Avalanche_MIV_RV32IMAF_BaseDesign.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/PF_Avalanche_MIV_RV32IMAF_BaseDesign.tcl new file mode 100644 index 0000000..0720a97 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/PF_Avalanche_MIV_RV32IMAF_BaseDesign.tcl @@ -0,0 +1,248 @@ +set config [string toupper [lindex $argv 0]] +set design_flow_stage [string toupper [lindex $argv 1]] +set die_variant [string toupper [lindex $argv 2]] + +set hw_platform PF_Avalanche +set soft_cpu MIV_RV32IMAF +set sd_reference BaseDesign + +# +# Procedure blocks start +proc create_new_project_label { } { + puts "\n------------------------------------------------------------------------------- \ + \r\nCreating a new project for the 'PF_Avalanche' board. \ + \r\n-------------------------------------------------------------------------------" +} + +proc project_exists { } { + puts "\n------------------------------------------------------------------------------- \ + \r\nError: A project exists for the 'PF_Avalanche' with this configuration. \ + \r\n-------------------------------------------------------------------------------" +} + +proc no_first_argument_entered { } { + puts "\n------------------------------------------------------------------------------- \ + \r\nInfo: No 1st Argument has been entered. \ + \r\nInfo: Enter the 1st Argument responsible for type of design configuration -'CFG1..CFGn' \ + \r\nInfo: Default 'CFG1' design has been selected. \ + \r\n-------------------------------------------------------------------------------" +} + +proc invalid_first_argument { } { + puts "\n------------------------------------------------------------------------------- \ + \r\nError: Wrong 1st Argument has been entered. No valid configuration detected. \ + \r\nInfo: Make sure you enter a valid first argument -'CFG1..CFGn'. \ + \r\n-------------------------------------------------------------------------------" +} + +proc no_second_argument_entered { } { + puts "\n------------------------------------------------------------------------------- \ + \r\nInfo: No 2nd Argument has been entered. \ + \r\nInfo: Enter the 2nd Argument after the 1st to be taken further in the Design Flow. \ + \r\n-------------------------------------------------------------------------------" +} + +proc invalid_second_argument { } { + puts "\n------------------------------------------------------------------------------- \ + \r\nError: Wrong 2nd Argument has been entered. \ + \r\nInfo: Make sure you enter a valid 2nd argument -'Synthesize...Export_Programming_File'.\ + \r\n-------------------------------------------------------------------------------" +} + +proc no_third_argument_entered { } { + puts "\n------------------------------------------------------------------------------- \ + \r\nInfo: No 3rd Argument has been entered. \ + \r\nInfo: Assuming the default 'PS' die type as target \ + \r\n-------------------------------------------------------------------------------" +} + +proc invalid_third_argument { } { + puts "\n------------------------------------------------------------------------------- \ + \r\nError: Wrong 3rd Argument has been entered. \ + \r\nInfo: Make sure you enter 'PS' or 'ES' to specify die target type. \ + \r\n-------------------------------------------------------------------------------" +} + +proc base_design_built { } { + puts "\n------------------------------------------------------------------------------- \ + \r\nInfo: BaseDesign built. \ + \r\n-------------------------------------------------------------------------------" +} + +proc legacy_core_msg { } { + puts "\n------------------------------------------------------------------------------- \ + \r\nWarning: This Libero design uses a legacy Mi-V soft processor core. \ + \r\nWarning: Legacy Mi-V soft processors are not recommended for new designs. \ + \r\nInfo: MIV_RV32 is recommended for new designs. \ + \r\n------------------------------------------------------------------------------- \n" +} + + +proc download_required_direct_cores { } { + download_core -vlnv {Actel:DirectCore:CoreUARTapb:5.7.100} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Actel:DirectCore:CoreTimer:2.0.103} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Actel:DirectCore:CORERESET_PF:2.3.100} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Actel:DirectCore:COREJTAGDEBUG:4.0.100} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Actel:DirectCore:CoreGPIO:3.2.102} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Actel:DirectCore:COREAXITOAHBL:3.6.101} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Actel:DirectCore:CoreAPB3:4.2.100} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Actel:DirectCore:COREAHBTOAPB3:3.2.101} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Actel:DirectCore:CoreAHBLite:5.6.105} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Microsemi:MiV:MIV_RV32:3.0.100} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Microsemi:MiV:MIV_RV32IMA_L1_AHB:2.3.100} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Microsemi:MiV:MIV_RV32IMA_L1_AXI:2.1.100} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Microsemi:MiV:MIV_RV32IMAF_L1_AHB:2.1.100} -location {www.microchip-ip.com/repositories/DirectCore} +} + +proc pre_configure_place_and_route { } { + # Configuring Place_and_Route tool for a timing pass. + configure_tool -name {PLACEROUTE} -params {EFFORT_LEVEL:false} -params {REPAIR_MIN_DELAY:true} -params {TDPR:true} +} + +proc run_verify_timing { } { + run_tool -name {VERIFYTIMING} +} +# Procedure blocks end +# + +#Filter for argument argv0: config +if {$config == ""} then { + set config "CFG1" + no_first_argument_entered +} elseif {$config != "CFG1"} then { + puts "config is: $config" + invalid_first_argument + exit 1 +} else { + puts "Info: Configuration selected: $config" +} + +#Filter for argument argv1: design flow +if {$design_flow_stage == ""} then { + no_second_argument_entered +} elseif {$design_flow_stage == "SYNTHESIZE" + || $design_flow_stage == "PLACE_AND_ROUTE" + || $design_flow_stage == "GENERATE_BITSTREAM" + || $design_flow_stage == "EXPORT_PROGRAMMING_FILE"} then { + puts "Info: Design flow run tool selected: $design_flow_stage" +} elseif {$design_flow_stage == "ES" + || $design_flow_stage == "PS"} then { + set die_variant "$design_flow_stage" +} else { + invalid_second_argument + exit 1 +} + +#Filter for argument argv2: die type +if {$die_variant == ""} { + set die_variant "PS" + no_third_argument_entered +} elseif {$die_variant == "PS" + || $die_variant == "ES"} then { + puts "Info: Die type selected: $die_variant" +} else { + invalid_third_argument + exit 1 +} + +append target_board $hw_platform _ $die_variant +append project_folder_name MIV_ $config _BD +set project_dir "./$project_folder_name" +append project_name $target_board _ $soft_cpu _ $config _ $sd_reference + +if {"$config" == "CFG1"} then { + if {[file exists $project_dir] == 1} then { + project_exists + } else { + no_first_argument_entered + create_new_project_label + if {"$die_variant" == "PS"} then { + new_project -location $project_dir -name $project_name -project_description {} -block_mode 0 -standalone_peripheral_initialization 0 -instantiate_in_smartdesign 1 -ondemand_build_dh 1 -hdl {VERILOG} -family {PolarFire} -die {MPF300TS} -package {FCG484} -speed {STD} -die_voltage {1.0} -part_range {IND} -adv_options {IO_DEFT_STD:LVCMOS 1.8V} -adv_options {RESTRICTPROBEPINS:1} -adv_options {RESTRICTSPIPINS:0} -adv_options {SYSTEM_CONTROLLER_SUSPEND_MODE:0} -adv_options {TEMPR:IND} -adv_options {VCCI_1.2_VOLTR:IND} -adv_options {VCCI_1.5_VOLTR:IND} -adv_options {VCCI_1.8_VOLTR:IND} -adv_options {VCCI_2.5_VOLTR:IND} -adv_options {VCCI_3.3_VOLTR:IND} -adv_options {VOLTR:IND} + } elseif {"$die_variant" == "ES"} then { + new_project -location $project_dir -name $project_name -project_description {} -block_mode 0 -standalone_peripheral_initialization 0 -instantiate_in_smartdesign 1 -ondemand_build_dh 1 -hdl {VERILOG} -family {PolarFire} -die {MPF300TS_ES} -package {FCG484} -speed {STD} -die_voltage {1.0} -part_range {EXT} -adv_options {IO_DEFT_STD:LVCMOS 1.8V} -adv_options {RESTRICTPROBEPINS:1} -adv_options {RESTRICTSPIPINS:0} -adv_options {SYSTEM_CONTROLLER_SUSPEND_MODE:0} -adv_options {TEMPR:EXT} -adv_options {VCCI_1.2_VOLTR:EXT} -adv_options {VCCI_1.5_VOLTR:EXT} -adv_options {VCCI_1.8_VOLTR:EXT} -adv_options {VCCI_2.5_VOLTR:EXT} -adv_options {VCCI_3.3_VOLTR:EXT} -adv_options {VOLTR:EXT} + } else { + invalid_third_argument + exit 1 + } + download_required_direct_cores + source ./import/components/IMAF_CFG1/import_sd_and_constraints_imaf_cfg1.tcl + save_project + base_design_built + } +} else { + invalid_first_argument + exit 1 +} + +pre_configure_place_and_route + +if {"$design_flow_stage" == "SYNTHESIZE"} then { + puts "\n------------------------------------------------------------------------------- \ + \r\nBegin Synthesis... \ + \r\n-------------------------------------------------------------------------------" + + run_tool -name {SYNTHESIZE} + save_project + + puts "\n------------------------------------------------------------------------------- \ + \r\nSynthesis Complete. \ + \r\n-------------------------------------------------------------------------------" + + +} elseif {"$design_flow_stage" == "PLACE_AND_ROUTE"} then { + + puts "\n------------------------------------------------------------------------------- \ + \r\nBegin Place and Route... \ + \r\n-------------------------------------------------------------------------------" + + run_verify_timing + save_project + + puts "\n------------------------------------------------------------------------------- \ + \r\nPlace and Route Complete. \ + \r\n-------------------------------------------------------------------------------" + + +} elseif {"$design_flow_stage" == "GENERATE_BITSTREAM"} then { + + puts "\n------------------------------------------------------------------------------- \ + \r\nGenerating Bitstream... \ + \r\n-------------------------------------------------------------------------------" + + run_verify_timing + run_tool -name {GENERATEPROGRAMMINGDATA} + run_tool -name {GENERATEPROGRAMMINGFILE} + save_project + + puts "\n------------------------------------------------------------------------------- \ + \r\nBitstream Generated. \ + \r\n-------------------------------------------------------------------------------" + + +} elseif {"$design_flow_stage" == "EXPORT_PROGRAMMING_FILE"} then { + + puts "\n------------------------------------------------------------------------------- \ + \r\nExporting Programming Files... \ + \r\n-------------------------------------------------------------------------------" + + run_verify_timing + run_tool -name {GENERATEPROGRAMMINGFILE} + + + export_prog_job \ + -job_file_name $project_name \ + -export_dir $project_dir/designer/BaseDesign/export \ + -bitstream_file_type {TRUSTED_FACILITY} \ + -bitstream_file_components {} + save_project + + + puts "\n------------------------------------------------------------------------------- \ + \r\nProgramming Files Exported. \ + \r\n-------------------------------------------------------------------------------" + +} else { + puts "Info: No design flow tool run." +} + +legacy_core_msg diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/IMAF_CFG1/build_sd_imaf_cfg1.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/IMAF_CFG1/build_sd_imaf_cfg1.tcl new file mode 100644 index 0000000..e213991 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/IMAF_CFG1/build_sd_imaf_cfg1.tcl @@ -0,0 +1,214 @@ +#MIV Cores : MIV_RV32IMAF_L1_AHB +# +#Libero's TCL top level script +# +#This Tcl file sources other Tcl files to build the design(on which recursive export is run) in a bottom-up fashion + +#Sourcing the Tcl files for creating individual components under the top level +source ./import/components/SHARED_COMPONENTS/COREAHBTOAPB3_0.tcl +source ./import/components/SHARED_COMPONENTS/CoreAHBL_0.tcl +source ./import/components/SHARED_COMPONENTS/CoreAPB3_0.tcl +source ./import/components/SHARED_COMPONENTS/CoreGPIO_IN.tcl +source ./import/components/SHARED_COMPONENTS/CoreGPIO_OUT.tcl +source ./import/components/SHARED_COMPONENTS/CoreJTAGDebug_1.tcl +source ./import/components/SHARED_COMPONENTS/CoreRESET_PF_0.tcl +source ./import/components/SHARED_COMPONENTS/CoreTimer_0.tcl +source ./import/components/SHARED_COMPONENTS/CoreTimer_1.tcl +source ./import/components/SHARED_COMPONENTS/CoreUARTapb_0.tcl +source ./import/components/SHARED_COMPONENTS/MIV_RV32IMAF_L1_AHB_0.tcl +source ./import/components/SHARED_COMPONENTS/PF_CCC_0.tcl +source ./import/components/SHARED_COMPONENTS/PF_INIT_MONITOR_0.tcl +source ./import/components/SHARED_COMPONENTS/PF_OSC_0.tcl +source ./import/components/SHARED_COMPONENTS/PF_SRAM_0.tcl + +# Creating SmartDesign BaseDesign +set sd_name {BaseDesign} +create_smartdesign -sd_name ${sd_name} + +# Disable auto promotion of pins of type 'pad' +auto_promote_pad_pins -promote_all 0 + +# Create top level Ports +sd_create_scalar_port -sd_name ${sd_name} -port_name {TDO} -port_direction {OUT} +sd_create_scalar_port -sd_name ${sd_name} -port_name {TRSTB} -port_direction {IN} +sd_create_scalar_port -sd_name ${sd_name} -port_name {TCK} -port_direction {IN} +sd_create_scalar_port -sd_name ${sd_name} -port_name {TDI} -port_direction {IN} +sd_create_scalar_port -sd_name ${sd_name} -port_name {TMS} -port_direction {IN} +sd_create_scalar_port -sd_name ${sd_name} -port_name {RX} -port_direction {IN} +sd_create_scalar_port -sd_name ${sd_name} -port_name {TX} -port_direction {OUT} +sd_create_scalar_port -sd_name ${sd_name} -port_name {USER_RST} -port_direction {IN} + +sd_create_scalar_port -sd_name ${sd_name} -port_name {PUSH_BTN_1} -port_direction {IN} +sd_create_scalar_port -sd_name ${sd_name} -port_name {PUSH_BTN_2} -port_direction {IN} +sd_create_scalar_port -sd_name ${sd_name} -port_name {LED_1} -port_direction {OUT} +sd_create_scalar_port -sd_name ${sd_name} -port_name {LED_2} -port_direction {OUT} +sd_create_scalar_port -sd_name ${sd_name} -port_name {LED_3} -port_direction {OUT} +sd_create_scalar_port -sd_name ${sd_name} -port_name {LED_4} -port_direction {OUT} + +# Add CoreAHBL_0 instance +sd_instantiate_component -sd_name ${sd_name} -component_name {CoreAHBL_0} -instance_name {CoreAHBL_0} +sd_connect_pins_to_constant -sd_name ${sd_name} -pin_names {CoreAHBL_0:REMAP_M0} -value {GND} + + + +# Add COREAHBTOAPB3_0 instance +sd_instantiate_component -sd_name ${sd_name} -component_name {COREAHBTOAPB3_0} -instance_name {COREAHBTOAPB3_0} + + + +# Add CoreAPB3_0 instance +sd_instantiate_component -sd_name ${sd_name} -component_name {CoreAPB3_0} -instance_name {CoreAPB3_0} + + + +# Add CoreGPIO_IN instance +sd_instantiate_component -sd_name ${sd_name} -component_name {CoreGPIO_IN} -instance_name {CoreGPIO_IN} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {CoreGPIO_IN:INT} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {CoreGPIO_IN:GPIO_OUT} +sd_create_pin_slices -sd_name ${sd_name} -pin_name {CoreGPIO_IN:GPIO_IN} -pin_slices {"[0:0]"} +sd_create_pin_slices -sd_name ${sd_name} -pin_name {CoreGPIO_IN:GPIO_IN} -pin_slices {"[1:1]"} + + + +# Add CoreGPIO_OUT instance +sd_instantiate_component -sd_name ${sd_name} -component_name {CoreGPIO_OUT} -instance_name {CoreGPIO_OUT} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {CoreGPIO_OUT:INT} +sd_connect_pins_to_constant -sd_name ${sd_name} -pin_names {CoreGPIO_OUT:GPIO_IN} -value {GND} +sd_create_pin_slices -sd_name ${sd_name} -pin_name {CoreGPIO_OUT:GPIO_OUT} -pin_slices {"[0:0]"} +sd_create_pin_slices -sd_name ${sd_name} -pin_name {CoreGPIO_OUT:GPIO_OUT} -pin_slices {"[1:1]"} +sd_create_pin_slices -sd_name ${sd_name} -pin_name {CoreGPIO_OUT:GPIO_OUT} -pin_slices {"[2:2]"} +sd_create_pin_slices -sd_name ${sd_name} -pin_name {CoreGPIO_OUT:GPIO_OUT} -pin_slices {"[3:3]"} + + + +# Add CoreJTAGDebug_1 instance +sd_instantiate_component -sd_name ${sd_name} -component_name {CoreJTAGDebug_1} -instance_name {CoreJTAGDebug_1} + + + +# Add CoreRESET_PF_0 instance +sd_instantiate_component -sd_name ${sd_name} -component_name {CoreRESET_PF_0} -instance_name {CoreRESET_PF_0} +sd_connect_pins_to_constant -sd_name ${sd_name} -pin_names {CoreRESET_PF_0:BANK_x_VDDI_STATUS} -value {VCC} +sd_connect_pins_to_constant -sd_name ${sd_name} -pin_names {CoreRESET_PF_0:BANK_y_VDDI_STATUS} -value {VCC} +sd_connect_pins_to_constant -sd_name ${sd_name} -pin_names {CoreRESET_PF_0:SS_BUSY} -value {GND} +sd_connect_pins_to_constant -sd_name ${sd_name} -pin_names {CoreRESET_PF_0:FF_US_RESTORE} -value {GND} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {CoreRESET_PF_0:PLL_POWERDOWN_B} + + + +# Add CoreTimer_0 instance +sd_instantiate_component -sd_name ${sd_name} -component_name {CoreTimer_0} -instance_name {CoreTimer_0} + + + +# Add CoreTimer_1 instance +sd_instantiate_component -sd_name ${sd_name} -component_name {CoreTimer_1} -instance_name {CoreTimer_1} + + + +# Add CoreUARTapb_0 instance +sd_instantiate_component -sd_name ${sd_name} -component_name {CoreUARTapb_0} -instance_name {CoreUARTapb_0} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {CoreUARTapb_0:TXRDY} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {CoreUARTapb_0:RXRDY} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {CoreUARTapb_0:PARITY_ERR} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {CoreUARTapb_0:OVERFLOW} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {CoreUARTapb_0:FRAMING_ERR} + + + +# Add MIV_RV32IMAF_L1_AHB_0 instance +sd_instantiate_component -sd_name ${sd_name} -component_name {MIV_RV32IMAF_L1_AHB_0} -instance_name {MIV_RV32IMAF_L1_AHB_0} +sd_create_pin_slices -sd_name ${sd_name} -pin_name {MIV_RV32IMAF_L1_AHB_0:IRQ} -pin_slices {[28:0]} +sd_connect_pins_to_constant -sd_name ${sd_name} -pin_names {MIV_RV32IMAF_L1_AHB_0:IRQ[28:0]} -value {GND} +sd_create_pin_slices -sd_name ${sd_name} -pin_name {MIV_RV32IMAF_L1_AHB_0:IRQ} -pin_slices {[29]} +sd_create_pin_slices -sd_name ${sd_name} -pin_name {MIV_RV32IMAF_L1_AHB_0:IRQ} -pin_slices {[30]} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {MIV_RV32IMAF_L1_AHB_0:AHB_MST_MEM_HSEL} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {MIV_RV32IMAF_L1_AHB_0:AHB_MST_MMIO_HSEL} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {MIV_RV32IMAF_L1_AHB_0:DRV_TDO} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {MIV_RV32IMAF_L1_AHB_0:EXT_RESETN} + + + +# Add PF_CCC_0 instance +sd_instantiate_component -sd_name ${sd_name} -component_name {PF_CCC_0} -instance_name {PF_CCC_0} + + + +# Add PF_INIT_MONITOR_0 instance +sd_instantiate_component -sd_name ${sd_name} -component_name {PF_INIT_MONITOR_0} -instance_name {PF_INIT_MONITOR_0} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {PF_INIT_MONITOR_0:PCIE_INIT_DONE} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {PF_INIT_MONITOR_0:USRAM_INIT_DONE} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {PF_INIT_MONITOR_0:SRAM_INIT_DONE} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {PF_INIT_MONITOR_0:XCVR_INIT_DONE} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {PF_INIT_MONITOR_0:USRAM_INIT_FROM_SNVM_DONE} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {PF_INIT_MONITOR_0:USRAM_INIT_FROM_UPROM_DONE} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {PF_INIT_MONITOR_0:USRAM_INIT_FROM_SPI_DONE} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {PF_INIT_MONITOR_0:SRAM_INIT_FROM_SNVM_DONE} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {PF_INIT_MONITOR_0:SRAM_INIT_FROM_UPROM_DONE} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {PF_INIT_MONITOR_0:SRAM_INIT_FROM_SPI_DONE} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {PF_INIT_MONITOR_0:AUTOCALIB_DONE} + + + +# Add PF_OSC_0 instance +sd_instantiate_component -sd_name ${sd_name} -component_name {PF_OSC_0} -instance_name {PF_OSC_0} + + + +# Add PF_SRAM_0 instance +sd_instantiate_component -sd_name ${sd_name} -component_name {PF_SRAM_0} -instance_name {PF_SRAM_0} + + + +# Add scalar net connections +sd_connect_pins -sd_name ${sd_name} -pin_names {"MIV_RV32IMAF_L1_AHB_0:TCK" "CoreJTAGDebug_1:TGT_TCK_0" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"MIV_RV32IMAF_L1_AHB_0:TDI" "CoreJTAGDebug_1:TGT_TDI_0" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"MIV_RV32IMAF_L1_AHB_0:TMS" "CoreJTAGDebug_1:TGT_TMS_0" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"MIV_RV32IMAF_L1_AHB_0:TRST" "CoreJTAGDebug_1:TGT_TRST_0" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"COREAHBTOAPB3_0:HRESETN" "CoreTimer_1:PRESETn" "MIV_RV32IMAF_L1_AHB_0:RESETN" "PF_SRAM_0:HRESETN" "CoreGPIO_IN:PRESETN" "CoreGPIO_OUT:PRESETN" "CoreAHBL_0:HRESETN" "CoreTimer_0:PRESETn" "CoreUARTapb_0:PRESETN" "CoreRESET_PF_0:FABRIC_RESET_N" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"MIV_RV32IMAF_L1_AHB_0:IRQ[29]" "CoreTimer_0:TIMINT" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CoreTimer_1:TIMINT" "MIV_RV32IMAF_L1_AHB_0:IRQ[30]" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"MIV_RV32IMAF_L1_AHB_0:TDO" "CoreJTAGDebug_1:TGT_TDO_0" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"COREAHBTOAPB3_0:HCLK" "PF_CCC_0:OUT0_FABCLK_0" "CoreTimer_1:PCLK" "MIV_RV32IMAF_L1_AHB_0:CLK" "PF_SRAM_0:HCLK" "CoreUARTapb_0:PCLK" "CoreGPIO_IN:PCLK" "CoreGPIO_OUT:PCLK" "CoreAHBL_0:HCLK" "CoreTimer_0:PCLK" "CoreRESET_PF_0:CLK" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"PF_CCC_0:PLL_LOCK_0" "CoreRESET_PF_0:PLL_LOCK" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"PF_INIT_MONITOR_0:DEVICE_INIT_DONE" "CoreRESET_PF_0:INIT_DONE" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"PF_OSC_0:RCOSC_160MHZ_GL" "PF_CCC_0:REF_CLK_0" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CoreUARTapb_0:RX" "RX" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"TCK" "CoreJTAGDebug_1:TCK" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CoreJTAGDebug_1:TDI" "TDI" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CoreJTAGDebug_1:TDO" "TDO" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CoreJTAGDebug_1:TMS" "TMS" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"TRSTB" "CoreJTAGDebug_1:TRSTB" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CoreUARTapb_0:TX" "TX" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CoreRESET_PF_0:EXT_RST_N" "USER_RST" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"PF_INIT_MONITOR_0:FABRIC_POR_N" "CoreRESET_PF_0:FPGA_POR_N"} + +# Add bus net connections +sd_connect_pins -sd_name ${sd_name} -pin_names {"CoreGPIO_IN:GPIO_IN[0]" "PUSH_BTN_1" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CoreGPIO_IN:GPIO_IN[1]" "PUSH_BTN_2" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CoreGPIO_OUT:GPIO_OUT[0]" "LED_1" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CoreGPIO_OUT:GPIO_OUT[1]" "LED_2" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CoreGPIO_OUT:GPIO_OUT[2]" "LED_3" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CoreGPIO_OUT:GPIO_OUT[3]" "LED_4" } + +# Add bus interface net connections +sd_connect_pins -sd_name ${sd_name} -pin_names {"COREAHBTOAPB3_0:AHBslave" "CoreAHBL_0:AHBmslave7" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"PF_SRAM_0:AHBSlaveInterface" "CoreAHBL_0:AHBmslave8" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CoreAPB3_0:APB3mmaster" "COREAHBTOAPB3_0:APBmaster" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CoreAPB3_0:APBmslave1" "CoreUARTapb_0:APB_bif" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CoreAPB3_0:APBmslave2" "CoreGPIO_IN:APB_bif" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CoreAPB3_0:APBmslave3" "CoreTimer_0:APBslave" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CoreAPB3_0:APBmslave4" "CoreTimer_1:APBslave" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CoreAPB3_0:APBmslave5" "CoreGPIO_OUT:APB_bif" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"MIV_RV32IMAF_L1_AHB_0:AHB_MST_MEM" "CoreAHBL_0:AHBmmaster1" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CoreAHBL_0:AHBmmaster0" "MIV_RV32IMAF_L1_AHB_0:AHB_MST_MMIO" } + +# Re-enable auto promotion of pins of type 'pad' +auto_promote_pad_pins -promote_all 1 +# Re-arrange SmartDesign layout +sd_reset_layout -sd_name ${sd_name} +# Save the smartDesign +save_smartdesign -sd_name ${sd_name} +# Generate SmartDesign BaseDesign +generate_component -component_name ${sd_name} + diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/IMAF_CFG1/import_sd_and_constraints_imaf_cfg1.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/IMAF_CFG1/import_sd_and_constraints_imaf_cfg1.tcl new file mode 100644 index 0000000..2913b64 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/IMAF_CFG1/import_sd_and_constraints_imaf_cfg1.tcl @@ -0,0 +1,46 @@ +puts "\n------------------------------------------------------------------------------- \ + \r\nImporting Components... \ + \r\n------------------------------------------------------------------------------- \n" + +source ./import/components/IMAF_CFG1/build_sd_imaf_cfg1.tcl + +puts "\n------------------------------------------------------------------------------- \ + \r\nComponents Imported. \ + \r\n------------------------------------------------------------------------------- \n" + +build_design_hierarchy +set_root BaseDesign + +puts "\n------------------------------------------------------------------------------- \ + \r\nApplying Design Constraints... \ + \r\n------------------------------------------------------------------------------- \n" + +import_files -io_pdc ./import/constraints/io/io_constraints.pdc +import_files -sdc ./import/constraints/io_jtag_constraints.sdc +import_files -fp_pdc ./import/constraints/fp/ccc_fp.pdc + +# #Associate SDC constraint file to Place and Route tool +organize_tool_files -tool {PLACEROUTE} \ + -file $project_dir/constraint/io/io_constraints.pdc \ + -file $project_dir/constraint/io_jtag_constraints.sdc \ + -file $project_dir/constraint/fp/ccc_fp.pdc \ + -module {BaseDesign::work} -input_type {constraint} + +organize_tool_files -tool {SYNTHESIZE} \ + -file $project_dir/constraint/io_jtag_constraints.sdc \ + -module {BaseDesign::work} -input_type {constraint} + +organize_tool_files -tool {VERIFYTIMING} \ + -file $project_dir/constraint/io_jtag_constraints.sdc \ + -module {BaseDesign::work} -input_type {constraint} + +set_root BaseDesign +run_tool -name {CONSTRAINT_MANAGEMENT} +derive_constraints_sdc + +puts "\n------------------------------------------------------------------------------- \ + \r\nDesign Constraints Applied. \ + \r\n------------------------------------------------------------------------------- \n" + + + diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/COREAHBTOAPB3_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/COREAHBTOAPB3_0.tcl new file mode 100644 index 0000000..16aa3be --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/COREAHBTOAPB3_0.tcl @@ -0,0 +1,4 @@ +# Exporting core COREAHBTOAPB3_0 to TCL +# Exporting Create design command for core COREAHBTOAPB3_0 +create_and_configure_core -core_vlnv {Actel:DirectCore:COREAHBTOAPB3:3.2.101} -component_name {COREAHBTOAPB3_0} -params { } +# Exporting core COREAHBTOAPB3_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreAHBL_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreAHBL_0.tcl new file mode 100644 index 0000000..712d16e --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreAHBL_0.tcl @@ -0,0 +1,111 @@ +# Exporting core CoreAHBL_0 to TCL +# Exporting Create design command for core CoreAHBL_0 +create_and_configure_core -core_vlnv {Actel:DirectCore:CoreAHBLite:5.6.105} -component_name {CoreAHBL_0} -params {\ +"HADDR_SHG_CFG:1" \ +"M0_AHBSLOT0ENABLE:false" \ +"M0_AHBSLOT1ENABLE:false" \ +"M0_AHBSLOT2ENABLE:false" \ +"M0_AHBSLOT3ENABLE:false" \ +"M0_AHBSLOT4ENABLE:false" \ +"M0_AHBSLOT5ENABLE:false" \ +"M0_AHBSLOT6ENABLE:false" \ +"M0_AHBSLOT7ENABLE:true" \ +"M0_AHBSLOT8ENABLE:false" \ +"M0_AHBSLOT9ENABLE:false" \ +"M0_AHBSLOT10ENABLE:false" \ +"M0_AHBSLOT11ENABLE:false" \ +"M0_AHBSLOT12ENABLE:false" \ +"M0_AHBSLOT13ENABLE:false" \ +"M0_AHBSLOT14ENABLE:false" \ +"M0_AHBSLOT15ENABLE:false" \ +"M0_AHBSLOT16ENABLE:false" \ +"M1_AHBSLOT0ENABLE:false" \ +"M1_AHBSLOT1ENABLE:false" \ +"M1_AHBSLOT2ENABLE:false" \ +"M1_AHBSLOT3ENABLE:false" \ +"M1_AHBSLOT4ENABLE:false" \ +"M1_AHBSLOT5ENABLE:false" \ +"M1_AHBSLOT6ENABLE:false" \ +"M1_AHBSLOT7ENABLE:false" \ +"M1_AHBSLOT8ENABLE:true" \ +"M1_AHBSLOT9ENABLE:false" \ +"M1_AHBSLOT10ENABLE:false" \ +"M1_AHBSLOT11ENABLE:false" \ +"M1_AHBSLOT12ENABLE:false" \ +"M1_AHBSLOT13ENABLE:false" \ +"M1_AHBSLOT14ENABLE:false" \ +"M1_AHBSLOT15ENABLE:false" \ +"M1_AHBSLOT16ENABLE:false" \ +"M2_AHBSLOT0ENABLE:false" \ +"M2_AHBSLOT1ENABLE:false" \ +"M2_AHBSLOT2ENABLE:false" \ +"M2_AHBSLOT3ENABLE:false" \ +"M2_AHBSLOT4ENABLE:false" \ +"M2_AHBSLOT5ENABLE:false" \ +"M2_AHBSLOT6ENABLE:false" \ +"M2_AHBSLOT7ENABLE:false" \ +"M2_AHBSLOT8ENABLE:false" \ +"M2_AHBSLOT9ENABLE:false" \ +"M2_AHBSLOT10ENABLE:false" \ +"M2_AHBSLOT11ENABLE:false" \ +"M2_AHBSLOT12ENABLE:false" \ +"M2_AHBSLOT13ENABLE:false" \ +"M2_AHBSLOT14ENABLE:false" \ +"M2_AHBSLOT15ENABLE:false" \ +"M2_AHBSLOT16ENABLE:false" \ +"M3_AHBSLOT0ENABLE:false" \ +"M3_AHBSLOT1ENABLE:false" \ +"M3_AHBSLOT2ENABLE:false" \ +"M3_AHBSLOT3ENABLE:false" \ +"M3_AHBSLOT4ENABLE:false" \ +"M3_AHBSLOT5ENABLE:false" \ +"M3_AHBSLOT6ENABLE:false" \ +"M3_AHBSLOT7ENABLE:false" \ +"M3_AHBSLOT8ENABLE:false" \ +"M3_AHBSLOT9ENABLE:false" \ +"M3_AHBSLOT10ENABLE:false" \ +"M3_AHBSLOT11ENABLE:false" \ +"M3_AHBSLOT12ENABLE:false" \ +"M3_AHBSLOT13ENABLE:false" \ +"M3_AHBSLOT14ENABLE:false" \ +"M3_AHBSLOT15ENABLE:false" \ +"M3_AHBSLOT16ENABLE:false" \ +"MASTER0_INTERFACE:1" \ +"MASTER1_INTERFACE:1" \ +"MASTER2_INTERFACE:1" \ +"MASTER3_INTERFACE:1" \ +"MEMSPACE:1" \ +"SC_0:false" \ +"SC_1:false" \ +"SC_2:false" \ +"SC_3:false" \ +"SC_4:false" \ +"SC_5:false" \ +"SC_6:false" \ +"SC_7:false" \ +"SC_8:false" \ +"SC_9:false" \ +"SC_10:false" \ +"SC_11:false" \ +"SC_12:false" \ +"SC_13:false" \ +"SC_14:false" \ +"SC_15:false" \ +"SLAVE0_INTERFACE:1" \ +"SLAVE1_INTERFACE:1" \ +"SLAVE2_INTERFACE:1" \ +"SLAVE3_INTERFACE:1" \ +"SLAVE4_INTERFACE:1" \ +"SLAVE5_INTERFACE:1" \ +"SLAVE6_INTERFACE:1" \ +"SLAVE7_INTERFACE:1" \ +"SLAVE8_INTERFACE:1" \ +"SLAVE9_INTERFACE:1" \ +"SLAVE10_INTERFACE:1" \ +"SLAVE11_INTERFACE:1" \ +"SLAVE12_INTERFACE:1" \ +"SLAVE13_INTERFACE:1" \ +"SLAVE14_INTERFACE:1" \ +"SLAVE15_INTERFACE:1" \ +"SLAVE16_INTERFACE:1" } +# Exporting core CoreAHBL_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreAPB3_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreAPB3_0.tcl new file mode 100644 index 0000000..58d003b --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreAPB3_0.tcl @@ -0,0 +1,41 @@ +# Exporting core CoreAPB3_0 to TCL +# Exporting Create design command for core CoreAPB3_0 +create_and_configure_core -core_vlnv {Actel:DirectCore:CoreAPB3:4.2.100} -component_name {CoreAPB3_0} -params {\ +"APB_DWIDTH:32" \ +"APBSLOT0ENABLE:false" \ +"APBSLOT1ENABLE:true" \ +"APBSLOT2ENABLE:true" \ +"APBSLOT3ENABLE:true" \ +"APBSLOT4ENABLE:true" \ +"APBSLOT5ENABLE:true" \ +"APBSLOT6ENABLE:false" \ +"APBSLOT7ENABLE:false" \ +"APBSLOT8ENABLE:false" \ +"APBSLOT9ENABLE:false" \ +"APBSLOT10ENABLE:false" \ +"APBSLOT11ENABLE:false" \ +"APBSLOT12ENABLE:false" \ +"APBSLOT13ENABLE:false" \ +"APBSLOT14ENABLE:false" \ +"APBSLOT15ENABLE:false" \ +"IADDR_OPTION:0" \ +"MADDR_BITS:16" \ +"SC_0:false" \ +"SC_1:false" \ +"SC_2:false" \ +"SC_3:false" \ +"SC_4:false" \ +"SC_5:false" \ +"SC_6:false" \ +"SC_7:false" \ +"SC_8:false" \ +"SC_9:false" \ +"SC_10:false" \ +"SC_11:false" \ +"SC_12:false" \ +"SC_13:false" \ +"SC_14:false" \ +"SC_15:false" \ +"UPR_NIBBLE_POSN:6" } +# Exporting core CoreAPB3_0 to TCL done + diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreAXITOAHBL_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreAXITOAHBL_0.tcl new file mode 100644 index 0000000..c4ebe04 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreAXITOAHBL_0.tcl @@ -0,0 +1,11 @@ +# Exporting core CoreAXITOAHBL_0 to TCL +# Exporting Create design command for core CoreAXITOAHBL_0 +create_and_configure_core -core_vlnv {Actel:DirectCore:COREAXITOAHBL:3.6.101} -component_name {CoreAXITOAHBL_0} -params {\ +"ASYNC_CLOCKS:false" \ +"AXI_DWIDTH:64" \ +"AXI_SEL_MM_S:1" \ +"EXPOSE_WID:false" \ +"ID_WIDTH:5" \ +"NO_BURST_TRANS:false" \ +"WRAP_SUPPORT:false" } +# Exporting core CoreAXITOAHBL_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreAXITOAHBL_1.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreAXITOAHBL_1.tcl new file mode 100644 index 0000000..5b315bb --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreAXITOAHBL_1.tcl @@ -0,0 +1,11 @@ +# Exporting core CoreAXITOAHBL_1 to TCL +# Exporting Create design command for core CoreAXITOAHBL_1 +create_and_configure_core -core_vlnv {Actel:DirectCore:COREAXITOAHBL:3.6.101} -component_name {CoreAXITOAHBL_1} -params {\ +"ASYNC_CLOCKS:false" \ +"AXI_DWIDTH:64" \ +"AXI_SEL_MM_S:1" \ +"EXPOSE_WID:false" \ +"ID_WIDTH:5" \ +"NO_BURST_TRANS:false" \ +"WRAP_SUPPORT:false" } +# Exporting core CoreAXITOAHBL_1 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreGPIO_IN.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreGPIO_IN.tcl new file mode 100644 index 0000000..a1c824d --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreGPIO_IN.tcl @@ -0,0 +1,136 @@ +# Exporting core CoreGPIO_IN to TCL +# Exporting Create design command for core CoreGPIO_IN +create_and_configure_core -core_vlnv {Actel:DirectCore:CoreGPIO:3.2.102} -component_name {CoreGPIO_IN} -params {\ +"APB_WIDTH:32" \ +"FIXED_CONFIG_0:true" \ +"FIXED_CONFIG_1:true" \ +"FIXED_CONFIG_2:false" \ +"FIXED_CONFIG_3:false" \ +"FIXED_CONFIG_4:false" \ +"FIXED_CONFIG_5:false" \ +"FIXED_CONFIG_6:false" \ +"FIXED_CONFIG_7:false" \ +"FIXED_CONFIG_8:false" \ +"FIXED_CONFIG_9:false" \ +"FIXED_CONFIG_10:false" \ +"FIXED_CONFIG_11:false" \ +"FIXED_CONFIG_12:false" \ +"FIXED_CONFIG_13:false" \ +"FIXED_CONFIG_14:false" \ +"FIXED_CONFIG_15:false" \ +"FIXED_CONFIG_16:false" \ +"FIXED_CONFIG_17:false" \ +"FIXED_CONFIG_18:false" \ +"FIXED_CONFIG_19:false" \ +"FIXED_CONFIG_20:false" \ +"FIXED_CONFIG_21:false" \ +"FIXED_CONFIG_22:false" \ +"FIXED_CONFIG_23:false" \ +"FIXED_CONFIG_24:false" \ +"FIXED_CONFIG_25:false" \ +"FIXED_CONFIG_26:false" \ +"FIXED_CONFIG_27:false" \ +"FIXED_CONFIG_28:false" \ +"FIXED_CONFIG_29:false" \ +"FIXED_CONFIG_30:false" \ +"FIXED_CONFIG_31:false" \ +"INT_BUS:0" \ +"IO_INT_TYPE_0:7" \ +"IO_INT_TYPE_1:7" \ +"IO_INT_TYPE_2:7" \ +"IO_INT_TYPE_3:7" \ +"IO_INT_TYPE_4:7" \ +"IO_INT_TYPE_5:7" \ +"IO_INT_TYPE_6:7" \ +"IO_INT_TYPE_7:7" \ +"IO_INT_TYPE_8:7" \ +"IO_INT_TYPE_9:7" \ +"IO_INT_TYPE_10:7" \ +"IO_INT_TYPE_11:7" \ +"IO_INT_TYPE_12:7" \ +"IO_INT_TYPE_13:7" \ +"IO_INT_TYPE_14:7" \ +"IO_INT_TYPE_15:7" \ +"IO_INT_TYPE_16:7" \ +"IO_INT_TYPE_17:7" \ +"IO_INT_TYPE_18:7" \ +"IO_INT_TYPE_19:7" \ +"IO_INT_TYPE_20:7" \ +"IO_INT_TYPE_21:7" \ +"IO_INT_TYPE_22:7" \ +"IO_INT_TYPE_23:7" \ +"IO_INT_TYPE_24:7" \ +"IO_INT_TYPE_25:7" \ +"IO_INT_TYPE_26:7" \ +"IO_INT_TYPE_27:7" \ +"IO_INT_TYPE_28:7" \ +"IO_INT_TYPE_29:7" \ +"IO_INT_TYPE_30:7" \ +"IO_INT_TYPE_31:7" \ +"IO_NUM:2" \ +"IO_TYPE_0:0" \ +"IO_TYPE_1:0" \ +"IO_TYPE_2:0" \ +"IO_TYPE_3:0" \ +"IO_TYPE_4:0" \ +"IO_TYPE_5:0" \ +"IO_TYPE_6:0" \ +"IO_TYPE_7:0" \ +"IO_TYPE_8:0" \ +"IO_TYPE_9:0" \ +"IO_TYPE_10:0" \ +"IO_TYPE_11:0" \ +"IO_TYPE_12:0" \ +"IO_TYPE_13:0" \ +"IO_TYPE_14:0" \ +"IO_TYPE_15:0" \ +"IO_TYPE_16:0" \ +"IO_TYPE_17:0" \ +"IO_TYPE_18:0" \ +"IO_TYPE_19:0" \ +"IO_TYPE_20:0" \ +"IO_TYPE_21:0" \ +"IO_TYPE_22:0" \ +"IO_TYPE_23:0" \ +"IO_TYPE_24:0" \ +"IO_TYPE_25:0" \ +"IO_TYPE_26:0" \ +"IO_TYPE_27:0" \ +"IO_TYPE_28:0" \ +"IO_TYPE_29:0" \ +"IO_TYPE_30:0" \ +"IO_TYPE_31:0" \ +"IO_VAL_0:0" \ +"IO_VAL_1:0" \ +"IO_VAL_2:0" \ +"IO_VAL_3:0" \ +"IO_VAL_4:0" \ +"IO_VAL_5:0" \ +"IO_VAL_6:0" \ +"IO_VAL_7:0" \ +"IO_VAL_8:0" \ +"IO_VAL_9:0" \ +"IO_VAL_10:0" \ +"IO_VAL_11:0" \ +"IO_VAL_12:0" \ +"IO_VAL_13:0" \ +"IO_VAL_14:0" \ +"IO_VAL_15:0" \ +"IO_VAL_16:0" \ +"IO_VAL_17:0" \ +"IO_VAL_18:0" \ +"IO_VAL_19:0" \ +"IO_VAL_20:0" \ +"IO_VAL_21:0" \ +"IO_VAL_22:0" \ +"IO_VAL_23:0" \ +"IO_VAL_24:0" \ +"IO_VAL_25:0" \ +"IO_VAL_26:0" \ +"IO_VAL_27:0" \ +"IO_VAL_28:0" \ +"IO_VAL_29:0" \ +"IO_VAL_30:0" \ +"IO_VAL_31:0" \ +"OE_TYPE:1" } +# Exporting core CoreGPIO_IN to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreGPIO_OUT.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreGPIO_OUT.tcl new file mode 100644 index 0000000..cecf205 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreGPIO_OUT.tcl @@ -0,0 +1,136 @@ +# Exporting core CoreGPIO_OUT to TCL +# Exporting Create design command for core CoreGPIO_OUT +create_and_configure_core -core_vlnv {Actel:DirectCore:CoreGPIO:3.2.102} -component_name {CoreGPIO_OUT} -params {\ +"APB_WIDTH:32" \ +"FIXED_CONFIG_0:true" \ +"FIXED_CONFIG_1:true" \ +"FIXED_CONFIG_2:true" \ +"FIXED_CONFIG_3:true" \ +"FIXED_CONFIG_4:false" \ +"FIXED_CONFIG_5:false" \ +"FIXED_CONFIG_6:false" \ +"FIXED_CONFIG_7:false" \ +"FIXED_CONFIG_8:false" \ +"FIXED_CONFIG_9:false" \ +"FIXED_CONFIG_10:false" \ +"FIXED_CONFIG_11:false" \ +"FIXED_CONFIG_12:false" \ +"FIXED_CONFIG_13:false" \ +"FIXED_CONFIG_14:false" \ +"FIXED_CONFIG_15:false" \ +"FIXED_CONFIG_16:false" \ +"FIXED_CONFIG_17:false" \ +"FIXED_CONFIG_18:false" \ +"FIXED_CONFIG_19:false" \ +"FIXED_CONFIG_20:false" \ +"FIXED_CONFIG_21:false" \ +"FIXED_CONFIG_22:false" \ +"FIXED_CONFIG_23:false" \ +"FIXED_CONFIG_24:false" \ +"FIXED_CONFIG_25:false" \ +"FIXED_CONFIG_26:false" \ +"FIXED_CONFIG_27:false" \ +"FIXED_CONFIG_28:false" \ +"FIXED_CONFIG_29:false" \ +"FIXED_CONFIG_30:false" \ +"FIXED_CONFIG_31:false" \ +"INT_BUS:0" \ +"IO_INT_TYPE_0:7" \ +"IO_INT_TYPE_1:7" \ +"IO_INT_TYPE_2:7" \ +"IO_INT_TYPE_3:7" \ +"IO_INT_TYPE_4:7" \ +"IO_INT_TYPE_5:7" \ +"IO_INT_TYPE_6:7" \ +"IO_INT_TYPE_7:7" \ +"IO_INT_TYPE_8:7" \ +"IO_INT_TYPE_9:7" \ +"IO_INT_TYPE_10:7" \ +"IO_INT_TYPE_11:7" \ +"IO_INT_TYPE_12:7" \ +"IO_INT_TYPE_13:7" \ +"IO_INT_TYPE_14:7" \ +"IO_INT_TYPE_15:7" \ +"IO_INT_TYPE_16:7" \ +"IO_INT_TYPE_17:7" \ +"IO_INT_TYPE_18:7" \ +"IO_INT_TYPE_19:7" \ +"IO_INT_TYPE_20:7" \ +"IO_INT_TYPE_21:7" \ +"IO_INT_TYPE_22:7" \ +"IO_INT_TYPE_23:7" \ +"IO_INT_TYPE_24:7" \ +"IO_INT_TYPE_25:7" \ +"IO_INT_TYPE_26:7" \ +"IO_INT_TYPE_27:7" \ +"IO_INT_TYPE_28:7" \ +"IO_INT_TYPE_29:7" \ +"IO_INT_TYPE_30:7" \ +"IO_INT_TYPE_31:7" \ +"IO_NUM:4" \ +"IO_TYPE_0:1" \ +"IO_TYPE_1:1" \ +"IO_TYPE_2:1" \ +"IO_TYPE_3:1" \ +"IO_TYPE_4:0" \ +"IO_TYPE_5:0" \ +"IO_TYPE_6:0" \ +"IO_TYPE_7:0" \ +"IO_TYPE_8:0" \ +"IO_TYPE_9:0" \ +"IO_TYPE_10:0" \ +"IO_TYPE_11:0" \ +"IO_TYPE_12:0" \ +"IO_TYPE_13:0" \ +"IO_TYPE_14:0" \ +"IO_TYPE_15:0" \ +"IO_TYPE_16:0" \ +"IO_TYPE_17:0" \ +"IO_TYPE_18:0" \ +"IO_TYPE_19:0" \ +"IO_TYPE_20:0" \ +"IO_TYPE_21:0" \ +"IO_TYPE_22:0" \ +"IO_TYPE_23:0" \ +"IO_TYPE_24:0" \ +"IO_TYPE_25:0" \ +"IO_TYPE_26:0" \ +"IO_TYPE_27:0" \ +"IO_TYPE_28:0" \ +"IO_TYPE_29:0" \ +"IO_TYPE_30:0" \ +"IO_TYPE_31:0" \ +"IO_VAL_0:0" \ +"IO_VAL_1:0" \ +"IO_VAL_2:0" \ +"IO_VAL_3:0" \ +"IO_VAL_4:0" \ +"IO_VAL_5:0" \ +"IO_VAL_6:0" \ +"IO_VAL_7:0" \ +"IO_VAL_8:0" \ +"IO_VAL_9:0" \ +"IO_VAL_10:0" \ +"IO_VAL_11:0" \ +"IO_VAL_12:0" \ +"IO_VAL_13:0" \ +"IO_VAL_14:0" \ +"IO_VAL_15:0" \ +"IO_VAL_16:0" \ +"IO_VAL_17:0" \ +"IO_VAL_18:0" \ +"IO_VAL_19:0" \ +"IO_VAL_20:0" \ +"IO_VAL_21:0" \ +"IO_VAL_22:0" \ +"IO_VAL_23:0" \ +"IO_VAL_24:0" \ +"IO_VAL_25:0" \ +"IO_VAL_26:0" \ +"IO_VAL_27:0" \ +"IO_VAL_28:0" \ +"IO_VAL_29:0" \ +"IO_VAL_30:0" \ +"IO_VAL_31:0" \ +"OE_TYPE:1" } +# Exporting core CoreGPIO_OUT to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreJTAGDebug_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreJTAGDebug_0.tcl new file mode 100644 index 0000000..4cc67f3 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreJTAGDebug_0.tcl @@ -0,0 +1,39 @@ +# Exporting core CoreJTAGDebug_0 to TCL +# Exporting Create design command for core CoreJTAGDebug_0 +create_and_configure_core -core_vlnv {Actel:DirectCore:COREJTAGDEBUG:4.0.100} -component_name {CoreJTAGDebug_0} -params {\ +"IR_CODE_TGT_0:0x55" \ +"IR_CODE_TGT_1:0x56" \ +"IR_CODE_TGT_2:0x57" \ +"IR_CODE_TGT_3:0x58" \ +"IR_CODE_TGT_4:0x59" \ +"IR_CODE_TGT_5:0x5a" \ +"IR_CODE_TGT_6:0x5b" \ +"IR_CODE_TGT_7:0x5c" \ +"IR_CODE_TGT_8:0x5d" \ +"IR_CODE_TGT_9:0x5e" \ +"IR_CODE_TGT_10:0x5f" \ +"IR_CODE_TGT_11:0x60" \ +"IR_CODE_TGT_12:0x61" \ +"IR_CODE_TGT_13:0x62" \ +"IR_CODE_TGT_14:0x63" \ +"IR_CODE_TGT_15:0x64" \ +"NUM_DEBUG_TGTS:1" \ +"TGT_ACTIVE_HIGH_RESET_0:false" \ +"TGT_ACTIVE_HIGH_RESET_1:false" \ +"TGT_ACTIVE_HIGH_RESET_2:false" \ +"TGT_ACTIVE_HIGH_RESET_3:false" \ +"TGT_ACTIVE_HIGH_RESET_4:false" \ +"TGT_ACTIVE_HIGH_RESET_5:false" \ +"TGT_ACTIVE_HIGH_RESET_6:false" \ +"TGT_ACTIVE_HIGH_RESET_7:false" \ +"TGT_ACTIVE_HIGH_RESET_8:false" \ +"TGT_ACTIVE_HIGH_RESET_9:false" \ +"TGT_ACTIVE_HIGH_RESET_10:false" \ +"TGT_ACTIVE_HIGH_RESET_11:false" \ +"TGT_ACTIVE_HIGH_RESET_12:false" \ +"TGT_ACTIVE_HIGH_RESET_13:false" \ +"TGT_ACTIVE_HIGH_RESET_14:false" \ +"TGT_ACTIVE_HIGH_RESET_15:false" \ +"UJTAG_BYPASS:false" \ +"UJTAG_SEC_EN:false" } +# Exporting core CoreJTAGDebug_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreJTAGDebug_1.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreJTAGDebug_1.tcl new file mode 100644 index 0000000..6543672 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreJTAGDebug_1.tcl @@ -0,0 +1,39 @@ +# Exporting core CoreJTAGDebug_0 to TCL +# Exporting Create design command for core CoreJTAGDebug_0 +create_and_configure_core -core_vlnv {Actel:DirectCore:COREJTAGDEBUG:4.0.100} -component_name {CoreJTAGDebug_1} -params {\ +"IR_CODE_TGT_0:0x55" \ +"IR_CODE_TGT_1:0x56" \ +"IR_CODE_TGT_2:0x57" \ +"IR_CODE_TGT_3:0x58" \ +"IR_CODE_TGT_4:0x59" \ +"IR_CODE_TGT_5:0x5a" \ +"IR_CODE_TGT_6:0x5b" \ +"IR_CODE_TGT_7:0x5c" \ +"IR_CODE_TGT_8:0x5d" \ +"IR_CODE_TGT_9:0x5e" \ +"IR_CODE_TGT_10:0x5f" \ +"IR_CODE_TGT_11:0x60" \ +"IR_CODE_TGT_12:0x61" \ +"IR_CODE_TGT_13:0x62" \ +"IR_CODE_TGT_14:0x63" \ +"IR_CODE_TGT_15:0x64" \ +"NUM_DEBUG_TGTS:1" \ +"TGT_ACTIVE_HIGH_RESET_0:true" \ +"TGT_ACTIVE_HIGH_RESET_1:true" \ +"TGT_ACTIVE_HIGH_RESET_2:true" \ +"TGT_ACTIVE_HIGH_RESET_3:true" \ +"TGT_ACTIVE_HIGH_RESET_4:true" \ +"TGT_ACTIVE_HIGH_RESET_5:true" \ +"TGT_ACTIVE_HIGH_RESET_6:true" \ +"TGT_ACTIVE_HIGH_RESET_7:true" \ +"TGT_ACTIVE_HIGH_RESET_8:true" \ +"TGT_ACTIVE_HIGH_RESET_9:true" \ +"TGT_ACTIVE_HIGH_RESET_10:true" \ +"TGT_ACTIVE_HIGH_RESET_11:true" \ +"TGT_ACTIVE_HIGH_RESET_12:true" \ +"TGT_ACTIVE_HIGH_RESET_13:true" \ +"TGT_ACTIVE_HIGH_RESET_14:true" \ +"TGT_ACTIVE_HIGH_RESET_15:true" \ +"UJTAG_BYPASS:false" \ +"UJTAG_SEC_EN:false" } +# Exporting core CoreJTAGDebug_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreRESET_PF_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreRESET_PF_0.tcl new file mode 100644 index 0000000..877325b --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreRESET_PF_0.tcl @@ -0,0 +1,4 @@ +# Exporting core CoreRESET_PF_0 to TCL +# Exporting Create design command for core CoreRESET_PF_0 +create_and_configure_core -core_vlnv {Actel:DirectCore:CORERESET_PF:2.3.100} -component_name {CoreRESET_PF_0} -params { } +# Exporting core CoreRESET_PF_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreTimer_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreTimer_0.tcl new file mode 100644 index 0000000..fda5b3b --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreTimer_0.tcl @@ -0,0 +1,6 @@ +# Exporting core CoreTimer_0 to TCL +# Exporting Create design command for core CoreTimer_0 +create_and_configure_core -core_vlnv {Actel:DirectCore:CoreTimer:2.0.103} -component_name {CoreTimer_0} -params {\ +"INTACTIVEH:1" \ +"WIDTH:32" } +# Exporting core CoreTimer_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreTimer_1.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreTimer_1.tcl new file mode 100644 index 0000000..6a598ae --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreTimer_1.tcl @@ -0,0 +1,6 @@ +# Exporting core CoreTimer_1 to TCL +# Exporting Create design command for core CoreTimer_1 +create_and_configure_core -core_vlnv {Actel:DirectCore:CoreTimer:2.0.103} -component_name {CoreTimer_1} -params {\ +"INTACTIVEH:1" \ +"WIDTH:32" } +# Exporting core CoreTimer_1 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreUARTapb_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreUARTapb_0.tcl new file mode 100644 index 0000000..efb076f --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/CoreUARTapb_0.tcl @@ -0,0 +1,14 @@ +# Exporting core CoreUARTapb_0 to TCL +# Exporting Create design command for core CoreUARTapb_0 +create_and_configure_core -core_vlnv {Actel:DirectCore:CoreUARTapb:5.7.100} -component_name {CoreUARTapb_0} -params {\ +"BAUD_VAL_FRCTN:0" \ +"BAUD_VAL_FRCTN_EN:false" \ +"BAUD_VALUE:1" \ +"FIXEDMODE:0" \ +"PRG_BIT8:0" \ +"PRG_PARITY:0" \ +"RX_FIFO:0" \ +"RX_LEGACY_MODE:0" \ +"TX_FIFO:0" \ +"USE_SOFT_FIFO:0" } +# Exporting core CoreUARTapb_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/MIV_RV32IMAF_L1_AHB_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/MIV_RV32IMAF_L1_AHB_0.tcl new file mode 100644 index 0000000..378a8ad --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/MIV_RV32IMAF_L1_AHB_0.tcl @@ -0,0 +1,7 @@ +# Exporting core MIV_RV32IMAF_L1_AHB_0 to TCL +# Exporting Create design command for core MIV_RV32IMAF_L1_AHB_0 +create_and_configure_core -core_vlnv {Microsemi:MiV:MIV_RV32IMAF_L1_AHB:2.1.100} -component_name {MIV_RV32IMAF_L1_AHB_0} -params {\ +"ECC_EN:false" \ +"RESET_VECTOR_ADDR_0:0x0" \ +"RESET_VECTOR_ADDR_1:0x8000" } +# Exporting core MIV_RV32IMAF_L1_AHB_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/MIV_RV32IMA_L1_AHB_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/MIV_RV32IMA_L1_AHB_0.tcl new file mode 100644 index 0000000..dbe95c4 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/MIV_RV32IMA_L1_AHB_0.tcl @@ -0,0 +1,8 @@ +# Exporting core MIV_RV32IMA_L1_AHB_0 to TCL +# Exporting Create design command for core MIV_RV32IMA_L1_AHB_0 +create_and_configure_core -core_vlnv {Microsemi:MiV:MIV_RV32IMA_L1_AHB:2.3.100} -component_name {MIV_RV32IMA_L1_AHB_0} -params {\ +"ECC_EN:false" \ +"EXT_HALT:false" \ +"RESET_VECTOR_ADDR_0:0x0" \ +"RESET_VECTOR_ADDR_1:0x8000" } +# Exporting core MIV_RV32IMA_L1_AHB_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/MIV_RV32IMA_L1_AXI_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/MIV_RV32IMA_L1_AXI_0.tcl new file mode 100644 index 0000000..613ae7e --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/MIV_RV32IMA_L1_AXI_0.tcl @@ -0,0 +1,9 @@ +# Exporting core MIV_RV32IMA_L1_AXI_0 to TCL +# Exporting Create design command for core MIV_RV32IMA_L1_AXI_0 +create_and_configure_core -core_vlnv {Microsemi:MiV:MIV_RV32IMA_L1_AXI:2.1.100} -component_name {MIV_RV32IMA_L1_AXI_0} -params {\ +"MASTER_TYPE:0" \ +"MEM_WID:5" \ +"MMIO_WID:5" \ +"RESET_VECTOR_ADDR_0:0x0" \ +"RESET_VECTOR_ADDR_1:0x8000" } +# Exporting core MIV_RV32IMA_L1_AXI_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/MIV_RV32_CFG1_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/MIV_RV32_CFG1_0.tcl new file mode 100644 index 0000000..078553f --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/MIV_RV32_CFG1_0.tcl @@ -0,0 +1,53 @@ +# Exporting core MIV_RV32_CFG1_0 to TCL +# Exporting Create design command for core MIV_RV32_CFG1_0 +create_and_configure_core -core_vlnv {Microsemi:MiV:MIV_RV32:3.0.100} -component_name {MIV_RV32_CFG1_0} -params {\ +"AHB_END_ADDR_0:0x7fff" \ +"AHB_END_ADDR_1:0x8fff" \ +"AHB_MASTER_TYPE:1" \ +"AHB_SLAVE_MIRROR:true" \ +"AHB_START_ADDR_0:0x0" \ +"AHB_START_ADDR_1:0x8000" \ +"APB_END_ADDR_0:0xffff" \ +"APB_END_ADDR_1:0x7fff" \ +"APB_MASTER_TYPE:1" \ +"APB_SLAVE_MIRROR:false" \ +"APB_START_ADDR_0:0x0" \ +"APB_START_ADDR_1:0x7000" \ +"AXI_END_ADDR_0:0xffff" \ +"AXI_END_ADDR_1:0x6fff" \ +"AXI_MASTER_TYPE:0" \ +"AXI_SLAVE_MIRROR:false" \ +"AXI_START_ADDR_0:0x0" \ +"AXI_START_ADDR_1:0x6000" \ +"BOOTROM_DEST_ADDR_LOWER:0x0" \ +"BOOTROM_DEST_ADDR_UPPER:0x4000" \ +"BOOTROM_PRESENT:false" \ +"BOOTROM_SRC_END_ADDR_LOWER:0x3fff" \ +"BOOTROM_SRC_END_ADDR_UPPER:0x8000" \ +"BOOTROM_SRC_START_ADDR_LOWER:0x0" \ +"BOOTROM_SRC_START_ADDR_UPPER:0x8000" \ +"DEBUGGER:true" \ +"ECC_ENABLE:false" \ +"FWD_REGS:false" \ +"GEN_DECODE_RV32:3" \ +"GEN_MUL_TYPE:2" \ +"GPR_REGS:false" \ +"INTERNAL_MTIME:true" \ +"INTERNAL_MTIME_IRQ:true" \ +"MTIME_PRESCALER:100" \ +"NUM_EXT_IRQS:1" \ +"RECONFIG_BOOTROM:false" \ +"RESET_VECTOR_ADDR_0:0x0" \ +"RESET_VECTOR_ADDR_1:0x8000" \ +"TAS_END_ADDR_0:0x3fff" \ +"TAS_END_ADDR_1:0x4000" \ +"TAS_START_ADDR_0:0x0" \ +"TAS_START_ADDR_1:0x4000" \ +"TCM_END_ADDR_0:0x7fff" \ +"TCM_END_ADDR_1:0x4000" \ +"TCM_PRESENT:true" \ +"TCM_START_ADDR_0:0x0" \ +"TCM_START_ADDR_1:0x4000" \ +"TCM_TAS_PRESENT:false" \ +"VECTORED_INTERRUPTS:false" } +# Exporting core MIV_RV32_CFG1_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/MIV_RV32_CFG2_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/MIV_RV32_CFG2_0.tcl new file mode 100644 index 0000000..cb26ab3 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/MIV_RV32_CFG2_0.tcl @@ -0,0 +1,53 @@ +# Exporting core MIV_RV32_CFG2_0 to TCL +# Exporting Create design command for core MIV_RV32_CFG2_0 +create_and_configure_core -core_vlnv {Microsemi:MiV:MIV_RV32:3.0.100} -component_name {MIV_RV32_CFG2_0} -params {\ +"AHB_END_ADDR_0:0xffff" \ +"AHB_END_ADDR_1:0x8fff" \ +"AHB_MASTER_TYPE:0" \ +"AHB_SLAVE_MIRROR:false" \ +"AHB_START_ADDR_0:0x0" \ +"AHB_START_ADDR_1:0x8000" \ +"APB_END_ADDR_0:0xffff" \ +"APB_END_ADDR_1:0x7fff" \ +"APB_MASTER_TYPE:1" \ +"APB_SLAVE_MIRROR:false" \ +"APB_START_ADDR_0:0x0" \ +"APB_START_ADDR_1:0x7000" \ +"AXI_END_ADDR_0:0x7fff" \ +"AXI_END_ADDR_1:0x8fff" \ +"AXI_MASTER_TYPE:2" \ +"AXI_SLAVE_MIRROR:true" \ +"AXI_START_ADDR_0:0x0" \ +"AXI_START_ADDR_1:0x8000" \ +"BOOTROM_DEST_ADDR_LOWER:0x0" \ +"BOOTROM_DEST_ADDR_UPPER:0x4000" \ +"BOOTROM_PRESENT:false" \ +"BOOTROM_SRC_END_ADDR_LOWER:0x3fff" \ +"BOOTROM_SRC_END_ADDR_UPPER:0x8000" \ +"BOOTROM_SRC_START_ADDR_LOWER:0x0" \ +"BOOTROM_SRC_START_ADDR_UPPER:0x8000" \ +"DEBUGGER:true" \ +"ECC_ENABLE:false" \ +"FWD_REGS:false" \ +"GEN_DECODE_RV32:2" \ +"GEN_MUL_TYPE:0" \ +"GPR_REGS:false" \ +"INTERNAL_MTIME:true" \ +"INTERNAL_MTIME_IRQ:true" \ +"MTIME_PRESCALER:100" \ +"NUM_EXT_IRQS:1" \ +"RECONFIG_BOOTROM:false" \ +"RESET_VECTOR_ADDR_0:0x0" \ +"RESET_VECTOR_ADDR_1:0x8000" \ +"TAS_END_ADDR_0:0x3fff" \ +"TAS_END_ADDR_1:0x4000" \ +"TAS_START_ADDR_0:0x0" \ +"TAS_START_ADDR_1:0x4000" \ +"TCM_END_ADDR_0:0x3fff" \ +"TCM_END_ADDR_1:0x4000" \ +"TCM_PRESENT:false" \ +"TCM_START_ADDR_0:0x0" \ +"TCM_START_ADDR_1:0x4000" \ +"TCM_TAS_PRESENT:false" \ +"VECTORED_INTERRUPTS:false" } +# Exporting core MIV_RV32_CFG2_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/MIV_RV32_CFG3_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/MIV_RV32_CFG3_0.tcl new file mode 100644 index 0000000..8cf5cdc --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/MIV_RV32_CFG3_0.tcl @@ -0,0 +1,54 @@ +# Exporting core MIV_RV32_CFG3_0 to TCL +# Exporting Create design command for core MIV_RV32_CFG3_0 +create_and_configure_core -core_vlnv {Microsemi:MiV:MIV_RV32:3.0.100} -component_name {MIV_RV32_CFG3_0} -params {\ +"AHB_END_ADDR_0:0xffff" \ +"AHB_END_ADDR_1:0x8fff" \ +"AHB_MASTER_TYPE:0" \ +"AHB_SLAVE_MIRROR:false" \ +"AHB_START_ADDR_0:0x0" \ +"AHB_START_ADDR_1:0x8000" \ +"APB_END_ADDR_0:0xffff" \ +"APB_END_ADDR_1:0x7fff" \ +"APB_MASTER_TYPE:1" \ +"APB_SLAVE_MIRROR:false" \ +"APB_START_ADDR_0:0x0" \ +"APB_START_ADDR_1:0x7000" \ +"AXI_END_ADDR_0:0xffff" \ +"AXI_END_ADDR_1:0x6fff" \ +"AXI_MASTER_TYPE:0" \ +"AXI_SLAVE_MIRROR:false" \ +"AXI_START_ADDR_0:0x0" \ +"AXI_START_ADDR_1:0x6000" \ +"BOOTROM_DEST_ADDR_LOWER:0x0" \ +"BOOTROM_DEST_ADDR_UPPER:0x4000" \ +"BOOTROM_PRESENT:false" \ +"BOOTROM_SRC_END_ADDR_LOWER:0x3fff" \ +"BOOTROM_SRC_END_ADDR_UPPER:0x8000" \ +"BOOTROM_SRC_START_ADDR_LOWER:0x0" \ +"BOOTROM_SRC_START_ADDR_UPPER:0x8000" \ +"DEBUGGER:true" \ +"ECC_ENABLE:false" \ +"FWD_REGS:false" \ +"GEN_DECODE_RV32:0" \ +"GEN_MUL_TYPE:2" \ +"GPR_REGS:false" \ +"INTERNAL_MTIME:true" \ +"INTERNAL_MTIME_IRQ:true" \ +"MTIME_PRESCALER:100" \ +"NUM_EXT_IRQS:1" \ +"RECONFIG_BOOTROM:false" \ +"RESET_VECTOR_ADDR_0:0x0" \ +"RESET_VECTOR_ADDR_1:0x8000" \ +"TAS_END_ADDR_0:0x3fff" \ +"TAS_END_ADDR_1:0x4000" \ +"TAS_START_ADDR_0:0x0" \ +"TAS_START_ADDR_1:0x4000" \ +"TCM_END_ADDR_0:0x7fff" \ +"TCM_END_ADDR_1:0x8000" \ +"TCM_PRESENT:true" \ +"TCM_START_ADDR_0:0x0" \ +"TCM_START_ADDR_1:0x8000" \ +"TCM_TAS_PRESENT:false" \ +"VECTORED_INTERRUPTS:false" } +# Exporting core MIV_RV32_CFG3_0 to TCL done + diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/PF_CCC_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/PF_CCC_0.tcl new file mode 100644 index 0000000..e05afc1 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/PF_CCC_0.tcl @@ -0,0 +1,246 @@ +# Exporting core PF_CCC_0 to TCL +# Exporting Create design command for core PF_CCC_0 +create_and_configure_core -core_vlnv {Actel:SgCore:PF_CCC:*} -download_core -component_name {PF_CCC_0} -params {\ +"DLL_CLK_0_BANKCLK_EN:false" \ +"DLL_CLK_0_DEDICATED_EN:false" \ +"DLL_CLK_0_FABCLK_EN:false" \ +"DLL_CLK_1_BANKCLK_EN:false" \ +"DLL_CLK_1_DEDICATED_EN:false" \ +"DLL_CLK_1_FABCLK_EN:false" \ +"DLL_CLK_P_EN:false" \ +"DLL_CLK_P_OPTIONS_EN:false" \ +"DLL_CLK_REF_OPTION:DIVIDE_BY_1" \ +"DLL_CLK_REF_OPTIONS_EN:false" \ +"DLL_CLK_S_EN:false" \ +"DLL_CLK_S_OPTION:DIVIDE_BY_1" \ +"DLL_CLK_S_OPTIONS_EN:false" \ +"DLL_DELAY4:0" \ +"DLL_DYNAMIC_CODE_EN:false" \ +"DLL_DYNAMIC_RECONFIG_INTERFACE_EN:false" \ +"DLL_EXPORT_PWRDWN:false" \ +"DLL_FB_CLK:Primary" \ +"DLL_FB_EN:false" \ +"DLL_FINE_PHASE_CODE:0" \ +"DLL_IN:1" \ +"DLL_JITTER:0" \ +"DLL_MODE:PHASE_REF_MODE" \ +"DLL_ONLY_EN:false" \ +"DLL_OUT_0:1" \ +"DLL_OUT_1:1" \ +"DLL_PRIM_PHASE:90" \ +"DLL_PRIM_PHASE_CODE:0" \ +"DLL_SEC_PHASE:90" \ +"DLL_SEC_PHASE_CODE:0" \ +"DLL_SELECTED_IN:Output2" \ +"FF_REQUIRES_LOCK_EN_0:0" \ +"GL0_0_BANKCLK_USED:false" \ +"GL0_0_BYPASS:0" \ +"GL0_0_BYPASS_EN:false" \ +"GL0_0_DEDICATED_USED:false" \ +"GL0_0_DIV:25" \ +"GL0_0_DIVSTART:0" \ +"GL0_0_DYNAMIC_PH:false" \ +"GL0_0_EXPOSE_EN:false" \ +"GL0_0_FABCLK_GATED_USED:false" \ +"GL0_0_FABCLK_USED:true" \ +"GL0_0_FREQ_SEL:false" \ +"GL0_0_IS_USED:true" \ +"GL0_0_OUT_FREQ:50" \ +"GL0_0_PHASE_INDEX:0" \ +"GL0_0_PHASE_SEL:false" \ +"GL0_0_PLL_PHASE:0" \ +"GL0_1_BANKCLK_USED:false" \ +"GL0_1_BYPASS:0" \ +"GL0_1_BYPASS_EN:false" \ +"GL0_1_DEDICATED_USED:false" \ +"GL0_1_DIV:1" \ +"GL0_1_DIVSTART:0" \ +"GL0_1_DYNAMIC_PH:false" \ +"GL0_1_EXPOSE_EN:false" \ +"GL0_1_FABCLK_USED:false" \ +"GL0_1_FREQ_SEL:false" \ +"GL0_1_IS_USED:true" \ +"GL0_1_OUT_FREQ:100" \ +"GL0_1_PHASE_INDEX:0" \ +"GL0_1_PHASE_SEL:false" \ +"GL0_1_PLL_PHASE:0" \ +"GL1_0_BANKCLK_USED:false" \ +"GL1_0_BYPASS:0" \ +"GL1_0_BYPASS_EN:false" \ +"GL1_0_DEDICATED_USED:false" \ +"GL1_0_DIV:1" \ +"GL1_0_DIVSTART:0" \ +"GL1_0_DYNAMIC_PH:false" \ +"GL1_0_EXPOSE_EN:false" \ +"GL1_0_FABCLK_GATED_USED:false" \ +"GL1_0_FABCLK_USED:true" \ +"GL1_0_FREQ_SEL:false" \ +"GL1_0_IS_USED:false" \ +"GL1_0_OUT_FREQ:100" \ +"GL1_0_PHASE_INDEX:0" \ +"GL1_0_PHASE_SEL:false" \ +"GL1_0_PLL_PHASE:0" \ +"GL1_1_BANKCLK_USED:false" \ +"GL1_1_BYPASS:0" \ +"GL1_1_BYPASS_EN:false" \ +"GL1_1_DEDICATED_USED:false" \ +"GL1_1_DIV:1" \ +"GL1_1_DIVSTART:0" \ +"GL1_1_DYNAMIC_PH:false" \ +"GL1_1_EXPOSE_EN:false" \ +"GL1_1_FABCLK_USED:false" \ +"GL1_1_FREQ_SEL:false" \ +"GL1_1_IS_USED:false" \ +"GL1_1_OUT_FREQ:0" \ +"GL1_1_PHASE_INDEX:0" \ +"GL1_1_PHASE_SEL:false" \ +"GL1_1_PLL_PHASE:0" \ +"GL2_0_BANKCLK_USED:false" \ +"GL2_0_BYPASS:0" \ +"GL2_0_BYPASS_EN:false" \ +"GL2_0_DEDICATED_USED:false" \ +"GL2_0_DIV:1" \ +"GL2_0_DIVSTART:0" \ +"GL2_0_DYNAMIC_PH:false" \ +"GL2_0_EXPOSE_EN:false" \ +"GL2_0_FABCLK_GATED_USED:false" \ +"GL2_0_FABCLK_USED:true" \ +"GL2_0_FREQ_SEL:false" \ +"GL2_0_IS_USED:false" \ +"GL2_0_OUT_FREQ:100" \ +"GL2_0_PHASE_INDEX:0" \ +"GL2_0_PHASE_SEL:false" \ +"GL2_0_PLL_PHASE:0" \ +"GL2_1_BANKCLK_USED:false" \ +"GL2_1_BYPASS:0" \ +"GL2_1_BYPASS_EN:false" \ +"GL2_1_DEDICATED_USED:false" \ +"GL2_1_DIV:1" \ +"GL2_1_DIVSTART:0" \ +"GL2_1_DYNAMIC_PH:false" \ +"GL2_1_EXPOSE_EN:false" \ +"GL2_1_FABCLK_USED:false" \ +"GL2_1_FREQ_SEL:false" \ +"GL2_1_IS_USED:false" \ +"GL2_1_OUT_FREQ:0" \ +"GL2_1_PHASE_INDEX:0" \ +"GL2_1_PHASE_SEL:false" \ +"GL2_1_PLL_PHASE:0" \ +"GL3_0_BANKCLK_USED:false" \ +"GL3_0_BYPASS:0" \ +"GL3_0_BYPASS_EN:false" \ +"GL3_0_DEDICATED_USED:false" \ +"GL3_0_DIV:1" \ +"GL3_0_DIVSTART:0" \ +"GL3_0_DYNAMIC_PH:false" \ +"GL3_0_EXPOSE_EN:false" \ +"GL3_0_FABCLK_GATED_USED:false" \ +"GL3_0_FABCLK_USED:true" \ +"GL3_0_FREQ_SEL:false" \ +"GL3_0_IS_USED:false" \ +"GL3_0_OUT_FREQ:100" \ +"GL3_0_PHASE_INDEX:0" \ +"GL3_0_PHASE_SEL:false" \ +"GL3_0_PLL_PHASE:0" \ +"GL3_1_BANKCLK_USED:false" \ +"GL3_1_BYPASS:0" \ +"GL3_1_BYPASS_EN:false" \ +"GL3_1_DEDICATED_USED:false" \ +"GL3_1_DIV:1" \ +"GL3_1_DIVSTART:0" \ +"GL3_1_DYNAMIC_PH:false" \ +"GL3_1_EXPOSE_EN:false" \ +"GL3_1_FABCLK_USED:false" \ +"GL3_1_FREQ_SEL:false" \ +"GL3_1_IS_USED:false" \ +"GL3_1_OUT_FREQ:0" \ +"GL3_1_PHASE_INDEX:0" \ +"GL3_1_PHASE_SEL:false" \ +"GL3_1_PLL_PHASE:0" \ +"PLL_ALLOW_CCC_EXT_FB:false" \ +"PLL_BANDWIDTH_0:2" \ +"PLL_BANDWIDTH_1:1" \ +"PLL_BYPASS_GO_B_0:false" \ +"PLL_BYPASS_GO_B_1:false" \ +"PLL_BYPASS_POST_0:0" \ +"PLL_BYPASS_POST_0_0:false" \ +"PLL_BYPASS_POST_0_1:false" \ +"PLL_BYPASS_POST_0_2:false" \ +"PLL_BYPASS_POST_0_3:false" \ +"PLL_BYPASS_POST_1:0" \ +"PLL_BYPASS_POST_1_0:false" \ +"PLL_BYPASS_POST_1_1:false" \ +"PLL_BYPASS_POST_1_2:false" \ +"PLL_BYPASS_POST_1_3:false" \ +"PLL_BYPASS_PRE_0:0" \ +"PLL_BYPASS_PRE_0_0:false" \ +"PLL_BYPASS_PRE_0_1:false" \ +"PLL_BYPASS_PRE_0_2:false" \ +"PLL_BYPASS_PRE_0_3:false" \ +"PLL_BYPASS_PRE_1:0" \ +"PLL_BYPASS_PRE_1_0:false" \ +"PLL_BYPASS_PRE_1_1:false" \ +"PLL_BYPASS_PRE_1_2:false" \ +"PLL_BYPASS_PRE_1_3:false" \ +"PLL_BYPASS_SEL_0:0" \ +"PLL_BYPASS_SEL_0_0:false" \ +"PLL_BYPASS_SEL_0_1:false" \ +"PLL_BYPASS_SEL_0_2:false" \ +"PLL_BYPASS_SEL_0_3:false" \ +"PLL_BYPASS_SEL_1:0" \ +"PLL_BYPASS_SEL_1_0:false" \ +"PLL_BYPASS_SEL_1_1:false" \ +"PLL_BYPASS_SEL_1_2:false" \ +"PLL_BYPASS_SEL_1_3:false" \ +"PLL_DELAY_LINE_REF_FB_0:false" \ +"PLL_DELAY_LINE_REF_FB_1:false" \ +"PLL_DELAY_LINE_USED_0:false" \ +"PLL_DELAY_LINE_USED_1:false" \ +"PLL_DELAY_STEPS_0:1" \ +"PLL_DELAY_STEPS_1:1" \ +"PLL_DLL_CASCADED_EN:false" \ +"PLL_DYNAMIC_CONTROL_EN_0:true" \ +"PLL_DYNAMIC_CONTROL_EN_1:false" \ +"PLL_DYNAMIC_RECONFIG_INTERFACE_EN_0:false" \ +"PLL_DYNAMIC_RECONFIG_INTERFACE_EN_1:false" \ +"PLL_EXPORT_PWRDWN:false" \ +"PLL_EXT_MAX_ADDR_0:128" \ +"PLL_EXT_MAX_ADDR_1:128" \ +"PLL_EXT_WAVE_SEL_0:0" \ +"PLL_EXT_WAVE_SEL_1:0" \ +"PLL_FB_CLK_0:GL0_0" \ +"PLL_FB_CLK_1:GL0_1" \ +"PLL_FEEDBACK_MODE_0:Post-VCO" \ +"PLL_FEEDBACK_MODE_1:Post-VCO" \ +"PLL_IN_FREQ_0:160" \ +"PLL_IN_FREQ_1:100" \ +"PLL_INT_MODE_EN_0:false" \ +"PLL_INT_MODE_EN_1:false" \ +"PLL_LOCK_COUNT_0:0" \ +"PLL_LOCK_COUNT_1:0" \ +"PLL_LP_REQUIRES_LOCK_EN_0:false" \ +"PLL_LP_REQUIRES_LOCK_EN_1:false" \ +"PLL_PLL_CASCADED_EN:false" \ +"PLL_PLL_CASCADED_SELECTED_CLK:Output2" \ +"PLL_POSTDIVIDERADDSOFTLOGIC_0:true" \ +"PLL_REF_CLK_SEL_0:false" \ +"PLL_REF_CLK_SEL_1:false" \ +"PLL_REFDIV_0:1" \ +"PLL_REFDIV_1:1" \ +"PLL_SPREAD_MODE_0:false" \ +"PLL_SPREAD_MODE_1:false" \ +"PLL_SSM_DEPTH_0:5" \ +"PLL_SSM_DEPTH_1:5" \ +"PLL_SSM_DIVVAL_0:1" \ +"PLL_SSM_DIVVAL_1:1" \ +"PLL_SSM_FREQ_0:32" \ +"PLL_SSM_FREQ_1:32" \ +"PLL_SSM_RAND_PATTERN_0:2" \ +"PLL_SSM_RAND_PATTERN_1:2" \ +"PLL_SSMD_EN_0:false" \ +"PLL_SSMD_EN_1:false" \ +"PLL_SYNC_CORNER_PLL:false" \ +"PLL_SYNC_EN:false" \ +"PLL_VCO_MODE_0:MIN_JITTER" \ +"PLL_VCO_MODE_1:MIN_JITTER" } +# Exporting core PF_CCC_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/PF_INIT_MONITOR_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/PF_INIT_MONITOR_0.tcl new file mode 100644 index 0000000..3d4fc2e --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/PF_INIT_MONITOR_0.tcl @@ -0,0 +1,65 @@ +# Exporting core PF_INIT_MONITOR_0 to TCL +# Exporting Create design command for core PF_INIT_MONITOR_0 +create_and_configure_core -core_vlnv {Actel:SgCore:PF_INIT_MONITOR:*} -download_core -component_name {PF_INIT_MONITOR_0} -params {\ +"BANK_0_CALIB_STATUS_ENABLED:false" \ +"BANK_0_CALIB_STATUS_SIMULATION_DELAY:1" \ +"BANK_0_RECALIBRATION_ENABLED:false" \ +"BANK_0_VDDI_STATUS_ENABLED:false" \ +"BANK_0_VDDI_STATUS_SIMULATION_DELAY:1" \ +"BANK_1_CALIB_STATUS_ENABLED:false" \ +"BANK_1_CALIB_STATUS_SIMULATION_DELAY:1" \ +"BANK_1_RECALIBRATION_ENABLED:false" \ +"BANK_1_VDDI_STATUS_ENABLED:false" \ +"BANK_1_VDDI_STATUS_SIMULATION_DELAY:1" \ +"BANK_2_CALIB_STATUS_ENABLED:false" \ +"BANK_2_CALIB_STATUS_SIMULATION_DELAY:1" \ +"BANK_2_RECALIBRATION_ENABLED:false" \ +"BANK_2_VDDI_STATUS_ENABLED:false" \ +"BANK_2_VDDI_STATUS_SIMULATION_DELAY:1" \ +"BANK_4_CALIB_STATUS_ENABLED:false" \ +"BANK_4_CALIB_STATUS_SIMULATION_DELAY:1" \ +"BANK_4_RECALIBRATION_ENABLED:false" \ +"BANK_4_VDDI_STATUS_ENABLED:false" \ +"BANK_4_VDDI_STATUS_SIMULATION_DELAY:1" \ +"BANK_5_CALIB_STATUS_ENABLED:false" \ +"BANK_5_CALIB_STATUS_SIMULATION_DELAY:1" \ +"BANK_5_RECALIBRATION_ENABLED:false" \ +"BANK_5_VDDI_STATUS_ENABLED:false" \ +"BANK_5_VDDI_STATUS_SIMULATION_DELAY:1" \ +"BANK_6_CALIB_STATUS_ENABLED:false" \ +"BANK_6_CALIB_STATUS_SIMULATION_DELAY:1" \ +"BANK_6_RECALIBRATION_ENABLED:false" \ +"BANK_6_VDDI_STATUS_ENABLED:false" \ +"BANK_6_VDDI_STATUS_SIMULATION_DELAY:1" \ +"BANK_7_CALIB_STATUS_ENABLED:false" \ +"BANK_7_CALIB_STATUS_SIMULATION_DELAY:1" \ +"BANK_7_RECALIBRATION_ENABLED:false" \ +"BANK_7_VDDI_STATUS_ENABLED:false" \ +"BANK_7_VDDI_STATUS_SIMULATION_DELAY:1" \ +"DEVICE_INIT_DONE_SIMULATION_DELAY:7" \ +"FABRIC_POR_N_SIMULATION_DELAY:1" \ +"PCIE_INIT_DONE_SIMULATION_DELAY:4" \ +"SHOW_BANK_0_CALIB_STATUS_ENABLED:true" \ +"SHOW_BANK_0_RECALIBRATION_ENABLED:false" \ +"SHOW_BANK_0_VDDI_STATUS_ENABLED:true" \ +"SHOW_BANK_1_CALIB_STATUS_ENABLED:true" \ +"SHOW_BANK_1_RECALIBRATION_ENABLED:false" \ +"SHOW_BANK_1_VDDI_STATUS_ENABLED:true" \ +"SHOW_BANK_2_CALIB_STATUS_ENABLED:true" \ +"SHOW_BANK_2_RECALIBRATION_ENABLED:false" \ +"SHOW_BANK_2_VDDI_STATUS_ENABLED:true" \ +"SHOW_BANK_4_CALIB_STATUS_ENABLED:true" \ +"SHOW_BANK_4_RECALIBRATION_ENABLED:false" \ +"SHOW_BANK_4_VDDI_STATUS_ENABLED:true" \ +"SHOW_BANK_5_CALIB_STATUS_ENABLED:true" \ +"SHOW_BANK_5_RECALIBRATION_ENABLED:false" \ +"SHOW_BANK_5_VDDI_STATUS_ENABLED:true" \ +"SHOW_BANK_6_CALIB_STATUS_ENABLED:true" \ +"SHOW_BANK_6_RECALIBRATION_ENABLED:false" \ +"SHOW_BANK_6_VDDI_STATUS_ENABLED:true" \ +"SHOW_BANK_7_CALIB_STATUS_ENABLED:true" \ +"SHOW_BANK_7_RECALIBRATION_ENABLED:false" \ +"SHOW_BANK_7_VDDI_STATUS_ENABLED:true" \ +"SRAM_INIT_DONE_SIMULATION_DELAY:6" \ +"USRAM_INIT_DONE_SIMULATION_DELAY:5" } +# Exporting Component Description of PF_INIT_MONITOR_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/PF_OSC_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/PF_OSC_0.tcl new file mode 100644 index 0000000..6cac953 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/PF_OSC_0.tcl @@ -0,0 +1,10 @@ +# Exporting core PF_OSC_0 to TCL +# Exporting Create design command for core PF_OSC_0 +create_and_configure_core -core_vlnv {Actel:SgCore:PF_OSC:*} -download_core -component_name {PF_OSC_0} -params {\ +"RCOSC_2MHZ_CLK_DIV_EN:false" \ +"RCOSC_2MHZ_GL_EN:false" \ +"RCOSC_2MHZ_NGMUX_EN:false" \ +"RCOSC_160MHZ_CLK_DIV_EN:false" \ +"RCOSC_160MHZ_GL_EN:true" \ +"RCOSC_160MHZ_NGMUX_EN:false" } +# Exporting core PF_OSC_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/PF_SRAM_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/PF_SRAM_0.tcl new file mode 100644 index 0000000..a5a0e86 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/PF_SRAM_0.tcl @@ -0,0 +1,27 @@ +# Exporting Component Description of PF_SRAM_0 to TCL +# Family: PolarFire +# Part Number: MPF300T_ES-FCG484I +# Create and Configure the core component PF_SRAM_0 +create_and_configure_core -core_vlnv {Actel:SystemBuilder:PF_SRAM_AHBL_AXI:1.2.108} -component_name {PF_SRAM_0} -params {\ +"AXI4_AWIDTH:32" \ +"AXI4_DWIDTH:32" \ +"AXI4_IDWIDTH:8" \ +"AXI4_IFTYPE_RD:T" \ +"AXI4_IFTYPE_WR:T" \ +"AXI4_WRAP_SUPPORT:F" \ +"BYTEENABLES:1" \ +"BYTE_ENABLE_WIDTH:4" \ +"B_REN_POLARITY:2" \ +"CASCADE:1" \ +"ECC_OPTIONS:0" \ +"FABRIC_INTERFACE_TYPE:0" \ +"IMPORT_FILE:" \ +"INIT_RAM:F" \ +"LPM_HINT:0" \ +"PIPELINE_OPTIONS:1" \ +"RDEPTH:131072" \ +"RWIDTH:40" \ +"USE_NATIVE_INTERFACE:F" \ +"WDEPTH:131072" \ +"WWIDTH:40" } +# Exporting Component Description of PF_SRAM_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/PF_SRAM_AXI4_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/PF_SRAM_AXI4_0.tcl new file mode 100644 index 0000000..5a612bb --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/components/SHARED_COMPONENTS/PF_SRAM_AXI4_0.tcl @@ -0,0 +1,25 @@ +# Exporting core PF_SRAM_AXI4_0 to TCL +# Create design TCL command for core PF_SRAM_AXI4_0 +create_and_configure_core -core_vlnv {Actel:SystemBuilder:PF_SRAM_AHBL_AXI:*} -download_core -component_name {PF_SRAM_AXI4_0} -params {\ +"AXI4_AWIDTH:32" \ +"AXI4_DWIDTH:32" \ +"AXI4_IDWIDTH:8" \ +"AXI4_IFTYPE_RD:T" \ +"AXI4_IFTYPE_WR:T" \ +"AXI4_WRAP_SUPPORT:F" \ +"BYTEENABLES:1" \ +"BYTE_ENABLE_WIDTH:4" \ +"B_REN_POLARITY:2" \ +"CASCADE:1" \ +"ECC_OPTIONS:0" \ +"FABRIC_INTERFACE_TYPE:1" \ +"IMPORT_FILE:" \ +"INIT_RAM:F" \ +"LPM_HINT:0" \ +"PIPELINE_OPTIONS:1" \ +"RDEPTH:32768" \ +"RWIDTH:40" \ +"USE_NATIVE_INTERFACE:F" \ +"WDEPTH:32768" \ +"WWIDTH:40" } +# Exporting core PF_SRAM_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/constraints/fp/ccc_fp.pdc b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/constraints/fp/ccc_fp.pdc new file mode 100644 index 0000000..6332ce7 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/constraints/fp/ccc_fp.pdc @@ -0,0 +1 @@ +set_location -inst_name {PF_CCC_0_inst_0/PF_CCC_0_0/pll_inst_0} -location PLL0_SE \ No newline at end of file diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/constraints/io/io_constraints.pdc b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/constraints/io/io_constraints.pdc new file mode 100644 index 0000000..4226a1b --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/constraints/io/io_constraints.pdc @@ -0,0 +1,505 @@ +# Microsemi I/O Physical Design Constraints file + +# User I/O Constraints file + +# Version: PolarFire v2.3 12.200.35.9 + +# Family: PolarFire , Die: MPF300T(ES) , Package: FCG484 + +# Date generated: Mon Jan 07 16:35:59 2019 + + +# +# User Locked I/O Bank Settings +# + +set_iobank -bank_name Bank5 \ + -vcci 3.30 \ + -fixed true \ + -update_iostd true + + +# +# Unlocked I/O Bank Settings +# The I/O Bank Settings can be locked by directly editing this file +# or by making changes in the I/O Attribute Editor +# + + +# +# User Locked I/O settings +# + +# -- User PushButtons I/O -- # + +set_io -port_name {PUSH_BTN_1} \ + -pin_name E13 \ + -fixed true \ + -DIRECTION INPUT + +set_io -port_name {PUSH_BTN_2} \ + -pin_name E14 \ + -fixed true \ + -DIRECTION INPUT + +set_io -port_name USER_RST \ + -pin_name F5 \ + -fixed true \ + -DIRECTION INPUT + + +# -- LEDs I/O --# + +set_io -port_name {LED_1} \ + -pin_name D7 \ + -fixed true \ + -DIRECTION OUTPUT + +set_io -port_name {LED_2} \ + -pin_name D8 \ + -fixed true \ + -DIRECTION OUTPUT + +set_io -port_name {LED_3} \ + -pin_name D9 \ + -fixed true \ + -DIRECTION OUTPUT + +set_io -port_name {LED_4} \ + -pin_name D6 \ + -fixed true \ + -DIRECTION OUTPUT + + +# -- UART RX/TX -- # + +set_io -port_name RX \ + -pin_name F16 \ + -fixed true \ + -DIRECTION INPUT + + +set_io -port_name TX \ + -pin_name F17 \ + -fixed true \ + -DIRECTION OUTPUT + + +# +# Dedicated Peripheral I/O Settings +# + + +set_io -port_name TCK \ + -pin_name F8 \ + -DIRECTION INPUT + + +set_io -port_name TDI \ + -pin_name G8 \ + -DIRECTION INPUT + + +set_io -port_name TDO \ + -pin_name F6 \ + -DIRECTION OUTPUT + + +set_io -port_name TMS \ + -pin_name F7 \ + -DIRECTION INPUT + + +set_io -port_name TRSTB \ + -pin_name G7 \ + -DIRECTION INPUT + + +# Microsemi I/O Physical Design Constraints file + +# User I/O Constraints file + +# Version: PolarFire v2.3 12.200.35.9 + +# Family: PolarFire , Die: MPF300T_ES , Package: FCG484 + +# Date generated: Sun Jan 13 21:06:20 2019 +# +# Unlocked I/O settings +# The I/Os in this section are unplaced or placed but are not locked +# the other listed attributes have been applied +# + +#set_io -port_name CLK1_50M \ + -pin_name R1 \ + -fixed true \ + -io_std LVCMOS25 \ + -DIRECTION INPUT +#set_io -port_name REF_CLK_0 \ + -io_std LVCMOS18 \ + -DIRECTION INPUT + +# +# User Locked I/O settings +# + +#set_io -port_name AND1_Y \ + -pin_name A3 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[0]} \ + -pin_name U5 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[1]} \ + -pin_name U4 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[2]} \ + -pin_name V4 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[3]} \ + -pin_name W3 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[4]} \ + -pin_name V5 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[5]} \ + -pin_name W4 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[6]} \ + -pin_name Y3 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[7]} \ + -pin_name AA3 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[8]} \ + -pin_name Y4 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[9]} \ + -pin_name Y5 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[10]} \ + -pin_name AA2 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[11]} \ + -pin_name AB2 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[12]} \ + -pin_name V6 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[13]} \ + -pin_name W6 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[14]} \ + -pin_name AB3 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {BA[0]} \ + -pin_name V7 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {BA[1]} \ + -pin_name Y6 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {BA[2]} \ + -pin_name U7 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name CAS_N \ + -pin_name AA5 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name CK0 \ + -pin_name V2 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name CK0_N \ + -pin_name W2 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name CKE \ + -pin_name W8 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name CS_N \ + -pin_name W7 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name CTRLR_READY \ + -pin_name D6 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name DEVICE_INIT_DONE \ + -pin_name A13 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {DM[0]} \ + -pin_name Y9 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {DM[1]} \ + -pin_name R15 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {DQS[0]} \ + -pin_name T10 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQS[1]} \ + -pin_name R13 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQS_N[0]} \ + -pin_name U10 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQS_N[1]} \ + -pin_name T12 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[0]} \ + -pin_name T7 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[1]} \ + -pin_name T8 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[2]} \ + -pin_name U8 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[3]} \ + -pin_name U9 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[4]} \ + -pin_name R10 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[5]} \ + -pin_name V9 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[6]} \ + -pin_name V10 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[7]} \ + -pin_name W9 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[8]} \ + -pin_name V14 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[9]} \ + -pin_name U14 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[10]} \ + -pin_name R12 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[11]} \ + -pin_name T11 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[12]} \ + -pin_name U15 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[13]} \ + -pin_name T13 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[14]} \ + -pin_name U13 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[15]} \ + -pin_name T15 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name ODT \ + -pin_name AA7 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name PLL_LOCK_0 \ + -pin_name A12 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name RAS_N \ + -pin_name AA6 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name RESET_N \ + -pin_name AB7 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name SHIELD0 \ + -pin_name R9 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name SHIELD1 \ + -pin_name V15 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name WE_N \ + -pin_name AB5 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name reset_sync_0 \ + -pin_name A16 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name reset_sync_1 \ + -pin_name A15 \ + -fixed true \ + -DIRECTION OUTPUT + + + +# +# Dedicated Peripheral I/O Settings +# + + +# +# Unlocked I/O settings +# The I/Os in this section are unplaced or placed but are not locked +# the other listed attributes have been applied +# + + +# +#Ports using Dedicated Pins + +# + diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/constraints/io_jtag_constraints.sdc b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/constraints/io_jtag_constraints.sdc new file mode 100644 index 0000000..a5644a4 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design/libero design/import/constraints/io_jtag_constraints.sdc @@ -0,0 +1,7 @@ +create_clock -name { TCK } \ +-period 166.67 \ +-waveform { 0 83.33 } \ +[ get_ports { TCK } ] + +# JTAG and Mi-V clocks are independent - adding asynchronous clock group +set_clock_groups -name {async1} -asynchronous -group [ get_clocks { PF_CCC_0_inst_0/PF_CCC_0_0/pll_inst_0/OUT0 } ] -group [ get_clocks { TCK } ] \ No newline at end of file diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design_config/fpga_design_config.h b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design_config/fpga_design_config.h new file mode 100644 index 0000000..4b7c41a --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/fpga_design_config/fpga_design_config.h @@ -0,0 +1,136 @@ +/******************************************************************************* + * (c) Copyright 2016-2022 Microsemi Corporation. All rights reserved. + * + * Platform definitions + * Version based on requirements of RISCV-HAL + * + * SVN $Revision: 9587 $ + * SVN $Date: 2017-11-16 12:53:31 +0530 (Thu, 16 Nov 2017) $ + */ + /*=========================================================================*//** + @mainpage Sample file detailing how hw_platform.h should be constructed for + the Mi-V processors. + + @section intro_sec Introduction + The hw_platform.h is to be located in the project root directory. + Currently this file must be hand crafted when using the Mi-V Soft Processor. + + You can use this file as sample. + Rename this file from sample_hw_platform.h to hw_platform.h and store it in + the root folder of your project. Then customize it per your HW design. + + @section driver_configuration Project configuration Instructions + 1. Change SYS_CLK_FREQ define to frequency of Mi-V Soft processor clock + 2 Add all other core BASE addresses + 3. Add peripheral Core Interrupt to Mi-V Soft processor interrupt mappings + 4. Define MSCC_STDIO_UART_BASE_ADDR if you want a CoreUARTapb mapped to STDIO +*//*=========================================================================*/ + +#ifndef HW_PLATFORM_H +#define HW_PLATFORM_H + +/***************************************************************************//** + * Soft-processor clock definition + * This is the only clock brought over from the Mi-V Soft processor Libero design. + */ +#ifndef SYS_CLK_FREQ +#define SYS_CLK_FREQ 50000000UL /* 66000000UL originally */ +#endif + +/***************************************************************************//** + * MTIME prescaler definition + * The MiV soft-cores include, by default, a prescaler (100 is the default value) + * on the MTIME on the hardware. To take this prescaler into account and make + * the Renode and the hardware timings match, we set the macro RENODE_SIMULATION + * to 1 if the demo is run on Renode, to 0 otherwise. + */ + +#define RENODE_SIMULATION 0 + +#ifndef TICK_COUNT_PRESCALER + #define TICK_COUNT_PRESCALER 100UL +#endif + +/***************************************************************************//** + * Non-memory Peripheral base addresses + * Format of define is: + * __BASE_ADDR + */ +#define COREUARTAPB0_BASE_ADDR 0x70001000UL +#define COREGPIO_IN_BASE_ADDR 0x70002000UL +#define CORETIMER0_BASE_ADDR 0x70003000UL +#define CORETIMER1_BASE_ADDR 0x70004000UL +#define COREGPIO_OUT_BASE_ADDR 0x70005000UL +#define FLASH_CORE_SPI_BASE 0x70006000UL +#define CORE16550_BASE_ADDR 0x70007000UL + +/***************************************************************************//** + * Peripheral Interrupts are mapped to the corresponding Mi-V Soft processor + * interrupt from the Libero design. + * + * On the legacy RV32 cores, there can be up to 31 external interrupts (IRQ[30:0] + * pins). The legacy RV32 Soft processor external interrupts are defined in the + riscv_plic.h + * + * These are of the form + * typedef enum +{ + NoInterrupt_IRQn = 0, + External_1_IRQn = 1, + External_2_IRQn = 2, + . + . + . + External_31_IRQn = 31 +} IRQn_Type; + + On the legacy RV32 processors, the PLIC identifies the interrupt and passes it + on to the processor core. The interrupt 0 is not used. The pin IRQ[0] should + map to External_1_IRQn likewise IRQ[30] should map to External_31_IRQn + + On the MIV_RV32 core, there is one external interrupts and it can also have + up to six optional external system interrupts. On these cores there is no PLIC + and these interrupts are directly delivered to the processor core, hence unlike + legacy RV32 core no interrupt number mapping is necessary on MIV_RV32 core. + */ + +/**************************************************************************** + * Baud value to achieve a 115200 baud rate with a 83MHz system clock. + * This value is calculated using the following equation: + * BAUD_VALUE = (CLOCK / (16 * BAUD_RATE)) - 1 + *****************************************************************************/ +#define BAUD_VALUE_115200 (SYS_CLK_FREQ / (16 * 115200)) - 1 + +/***************************************************************************//** + * User edit section- Edit sections below if required + */ +#ifdef MSCC_STDIO_THRU_CORE_UART_APB +/* + * A base address mapping for the STDIO printf/scanf mapping to CortUARTapb + * must be provided if it is being used + * + * e.g. #define MSCC_STDIO_UART_BASE_ADDR COREUARTAPB1_BASE_ADDR + */ +#define MSCC_STDIO_UART_BASE_ADDR COREUARTAPB0_BASE_ADDR + +#ifndef MSCC_STDIO_UART_BASE_ADDR +#error MSCC_STDIO_UART_BASE_ADDR not defined- e.g. #define MSCC_STDIO_UART_BASE_ADDR COREUARTAPB1_BASE_ADDR +#endif + +#ifndef MSCC_STDIO_BAUD_VALUE +/* + * The MSCC_STDIO_BAUD_VALUE define should be set in your project's settings to + * specify the baud value used by the standard output CoreUARTapb instance for + * generating the UART's baud rate if you want a different baud rate from the + * default of 115200 baud + */ +#define MSCC_STDIO_BAUD_VALUE 115200 +#endif /*MSCC_STDIO_BAUD_VALUE*/ + +#endif /* end of MSCC_STDIO_THRU_CORE_UART_APB */ +/******************************************************************************* + * End of user edit section + */ +#endif /* HW_PLATFORM_H */ + + diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/platform_config/linker/legacy-rv32imaf-ram.ld b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/platform_config/linker/legacy-rv32imaf-ram.ld new file mode 100644 index 0000000..b5c9b70 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/legacy-rv32imaf-design/platform_config/linker/legacy-rv32imaf-ram.ld @@ -0,0 +1,152 @@ +/******************************************************************************* + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * file name : miv-rv32-ram.ld + * Mi-V soft processor linker script for creating a SoftConsole downloadable + * debug image executing in SRAM. + * + * This linker script assumes that a RAM is connected at on Mi-V soft processor + * memory space pointed by the reset vector address. + * + * NOTE : Modify the memory section address and the size according to your + * Libero design. + * For example: + * 1) If you want to download and step debug at a different RAM memory address in + * your design (For example TCM base address) than the one provided in this file. + * 2) The MIV_RV32, when used with MIV_ESS IP, provides ways to copy the executable + * HEX file from external Non-Volatile memory into the TCM at reset. In this + * case your executable must be linked to the TCM address. + * + * To know more about the memory map of the MIV_RV32 based Libero design, open + * the MIV_RV32 IP configurator and look for "Reset Vector Address" and the + * "Memory Map" tab. + * + */ + +OUTPUT_ARCH( "riscv" ) +ENTRY(_start) + +MEMORY +{ + ram (rwx) : ORIGIN = 0x80000000, LENGTH = 512k +} + +STACK_SIZE = 2k; /* needs to be calculated for your application */ +HEAP_SIZE = 4; /* needs to be calculated for your application */ + +SECTIONS +{ + .entry : ALIGN(0x10) + { + KEEP (*(SORT_NONE(.entry))) + . = ALIGN(0x10); + } > ram + + .text : ALIGN(0x10) + { + *(.text .text.* .gnu.linkonce.t.*) + *(.plt) + . = ALIGN(0x10); + + KEEP (*crtbegin.o(.ctors)) + KEEP (*(EXCLUDE_FILE (*crtend.o) .ctors)) + KEEP (*(SORT(.ctors.*))) + KEEP (*crtend.o(.ctors)) + KEEP (*crtbegin.o(.dtors)) + KEEP (*(EXCLUDE_FILE (*crtend.o) .dtors)) + KEEP (*(SORT(.dtors.*))) + KEEP (*crtend.o(.dtors)) + + *(.rodata .rodata.* .gnu.linkonce.r.*) + *(.gcc_except_table) + *(.eh_frame_hdr) + *(.eh_frame) + + KEEP (*(.init)) + KEEP (*(.fini)) + + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP (*(.preinit_array)) + PROVIDE_HIDDEN (__preinit_array_end = .); + PROVIDE_HIDDEN (__init_array_start = .); + KEEP (*(SORT(.init_array.*))) + KEEP (*(.init_array)) + PROVIDE_HIDDEN (__init_array_end = .); + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP (*(.fini_array)) + KEEP (*(SORT(.fini_array.*))) + PROVIDE_HIDDEN (__fini_array_end = .); + . = ALIGN(0x10); + + } > ram + + /* short/global data section */ + .sdata : ALIGN(0x10) + { + __sdata_load = LOADADDR(.sdata); + __sdata_start = .; + PROVIDE( __global_pointer$ = . + 0x800); + *(.srodata.cst16) *(.srodata.cst8) *(.srodata.cst4) *(.srodata.cst2) + *(.srodata*) + *(.sdata .sdata.* .gnu.linkonce.s.*) + . = ALIGN(0x10); + __sdata_end = .; + } > ram + + /* data section */ + .data : ALIGN(0x10) + { + __data_load = LOADADDR(.data); + __data_start = .; + *(.got.plt) *(.got) + *(.shdata) + *(.data .data.* .gnu.linkonce.d.*) + . = ALIGN(0x10); + __data_end = .; + } > ram + + /* sbss section */ + .sbss : ALIGN(0x10) + { + __sbss_start = .; + *(.sbss .sbss.* .gnu.linkonce.sb.*) + *(.scommon) + . = ALIGN(0x10); + __sbss_end = .; + } > ram + + /* sbss section */ + .bss : ALIGN(0x10) + { + __bss_start = .; + *(.shbss) + *(.bss .bss.* .gnu.linkonce.b.*) + *(COMMON) + . = ALIGN(0x10); + __bss_end = .; + } > ram + + /* End of uninitialized data segment */ + _end = .; + + .heap : ALIGN(0x10) + { + __heap_start = .; + . += HEAP_SIZE; + __heap_end = .; + . = ALIGN(0x10); + _heap_end = __heap_end; + } > ram + + .stack : ALIGN(0x10) + { + __stack_bottom = .; + . += STACK_SIZE; + __stack_top = .; + _sp = .; + __freertos_irq_stack_top = .; + } > ram +} + diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/PF_Avalanche_MIV_RV32_BaseDesign.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/PF_Avalanche_MIV_RV32_BaseDesign.tcl new file mode 100644 index 0000000..c9c7334 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/PF_Avalanche_MIV_RV32_BaseDesign.tcl @@ -0,0 +1,297 @@ +set config [string toupper [lindex $argv 0]] +set design_flow_stage [string toupper [lindex $argv 1]] +set die_variant [string toupper [lindex $argv 2]] + +set hw_platform PF_Avalanche +set soft_cpu MIV_RV32 +set sd_reference BaseDesign + +# +# Procedure blocks start +proc create_new_project_label { } { + puts "\n------------------------------------------------------------------------------- \ + \r\nCreating a new project for the 'PF_Avalanche' board. \ + \r\n-------------------------------------------------------------------------------" +} + +proc project_exists { } { + puts "\n------------------------------------------------------------------------------- \ + \r\nError: A project exists for the 'PF_Avalanche' with this configuration. \ + \r\n-------------------------------------------------------------------------------" +} + +proc no_first_argument_entered { } { + puts "\n------------------------------------------------------------------------------- \ + \r\nInfo: No 1st Argument has been entered. \ + \r\nInfo: Enter the 1st Argument responsible for type of design configuration -'CFG1..CFGn' \ + \r\nInfo: Default 'CFG1' design has been selected. \ + \r\n-------------------------------------------------------------------------------" +} + +proc invalid_first_argument { } { + puts "\n------------------------------------------------------------------------------- \ + \r\nError: Wrong 1st Argument has been entered. No valid configuration detected. \ + \r\nInfo: Make sure you enter a valid first argument -'CFG1..CFGn'. \ + \r\n-------------------------------------------------------------------------------" +} + +proc no_second_argument_entered { } { + puts "\n------------------------------------------------------------------------------- \ + \r\nInfo: No 2nd Argument has been entered. \ + \r\nInfo: Enter the 2nd Argument after the 1st to be taken further in the Design Flow. \ + \r\n-------------------------------------------------------------------------------" +} + +proc invalid_second_argument { } { + puts "\n------------------------------------------------------------------------------- \ + \r\nError: Wrong 2nd Argument has been entered. \ + \r\nInfo: Make sure you enter a valid 2nd argument -'Synthesize...Export_Programming_File'.\ + \r\n-------------------------------------------------------------------------------" +} + +proc no_third_argument_entered { } { + puts "\n------------------------------------------------------------------------------- \ + \r\nInfo: No 3rd Argument has been entered. \ + \r\nInfo: Assuming the default 'PS' die type as target \ + \r\n-------------------------------------------------------------------------------" +} + +proc invalid_third_argument { } { + puts "\n------------------------------------------------------------------------------- \ + \r\nError: Wrong 3rd Argument has been entered. \ + \r\nInfo: Make sure you enter 'PS' or 'ES' to specify die target type. \ + \r\n-------------------------------------------------------------------------------" +} + +proc base_design_built { } { + puts "\n------------------------------------------------------------------------------- \ + \r\nInfo: BaseDesign built. \ + \r\n-------------------------------------------------------------------------------" +} + +proc download_required_direct_cores { } { + download_core -vlnv {Actel:DirectCore:CoreUARTapb:5.7.100} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Actel:DirectCore:CoreTimer:2.0.103} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Actel:DirectCore:CORERESET_PF:2.3.100} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Actel:DirectCore:COREJTAGDEBUG:4.0.100} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Actel:DirectCore:CoreGPIO:3.2.102} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Actel:DirectCore:COREAXITOAHBL:3.6.101} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Actel:DirectCore:CoreAPB3:4.2.100} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Actel:DirectCore:COREAHBTOAPB3:3.2.101} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Actel:DirectCore:CoreAHBLite:5.6.105} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Microsemi:MiV:MIV_RV32:3.0.100} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Microsemi:MiV:MIV_RV32IMA_L1_AHB:2.3.100} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Microsemi:MiV:MIV_RV32IMA_L1_AXI:2.1.100} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Microsemi:MiV:MIV_RV32IMAF_L1_AHB:2.1.100} -location {www.microchip-ip.com/repositories/DirectCore} +} + +proc pre_configure_place_and_route { } { + # Configuring Place_and_Route tool for a timing pass. + configure_tool -name {PLACEROUTE} -params {EFFORT_LEVEL:false} -params {REPAIR_MIN_DELAY:true} -params {TDPR:true} +} + +proc run_verify_timing { } { + run_tool -name {VERIFYTIMING} +} +# Procedure blocks end +# + +#Filter for argument argv0: config +if {$config == ""} then { + set config "CFG1" + no_first_argument_entered +} elseif {$config != "CFG1" + && $config != "CFG2" + && $config != "CFG3" + && $config != "DGC2"} then { + puts "config is: $config" + invalid_first_argument + exit 1 +} else { + puts "Info: Configuration selected: $config" +} + +#Filter for argument argv1: design flow +if {$design_flow_stage == ""} then { + no_second_argument_entered +} elseif {$design_flow_stage == "SYNTHESIZE" + || $design_flow_stage == "PLACE_AND_ROUTE" + || $design_flow_stage == "GENERATE_BITSTREAM" + || $design_flow_stage == "EXPORT_PROGRAMMING_FILE"} then { + puts "Info: Design flow run tool selected: $design_flow_stage" +} elseif {$design_flow_stage == "ES" + || $design_flow_stage == "PS"} then { + set die_variant "$design_flow_stage" +} else { + invalid_second_argument + exit 1 +} + +#Filter for argument argv2: die type +if {$die_variant == ""} { + set die_variant "PS" + no_third_argument_entered +} elseif {$die_variant == "PS" + || $die_variant == "ES"} then { + puts "Info: Die type selected: $die_variant" +} else { + invalid_third_argument + exit 1 +} + +append target_board $hw_platform _ $die_variant +append project_folder_name MIV_ $config _BD +set project_dir "./$project_folder_name" +append project_name $target_board _ $soft_cpu _ $config _ $sd_reference + +if {"$config" == "CFG1"} then { + if {[file exists $project_dir] == 1} then { + project_exists + } else { + create_new_project_label + if {"$die_variant" == "PS"} then { + new_project -location $project_dir -name $project_name -project_description {} -block_mode 0 -standalone_peripheral_initialization 0 -instantiate_in_smartdesign 1 -ondemand_build_dh 1 -hdl {VERILOG} -family {PolarFire} -die {MPF300TS} -package {FCG484} -speed {STD} -die_voltage {1.0} -part_range {IND} -adv_options {IO_DEFT_STD:LVCMOS 1.8V} -adv_options {RESTRICTPROBEPINS:1} -adv_options {RESTRICTSPIPINS:0} -adv_options {SYSTEM_CONTROLLER_SUSPEND_MODE:0} -adv_options {TEMPR:IND} -adv_options {VCCI_1.2_VOLTR:IND} -adv_options {VCCI_1.5_VOLTR:IND} -adv_options {VCCI_1.8_VOLTR:IND} -adv_options {VCCI_2.5_VOLTR:IND} -adv_options {VCCI_3.3_VOLTR:IND} -adv_options {VOLTR:IND} + } elseif {"$die_variant" == "ES"} then { + new_project -location $project_dir -name $project_name -project_description {} -block_mode 0 -standalone_peripheral_initialization 0 -instantiate_in_smartdesign 1 -ondemand_build_dh 1 -hdl {VERILOG} -family {PolarFire} -die {MPF300TS_ES} -package {FCG484} -speed {STD} -die_voltage {1.0} -part_range {EXT} -adv_options {IO_DEFT_STD:LVCMOS 1.8V} -adv_options {RESTRICTPROBEPINS:1} -adv_options {RESTRICTSPIPINS:0} -adv_options {SYSTEM_CONTROLLER_SUSPEND_MODE:0} -adv_options {TEMPR:EXT} -adv_options {VCCI_1.2_VOLTR:EXT} -adv_options {VCCI_1.5_VOLTR:EXT} -adv_options {VCCI_1.8_VOLTR:EXT} -adv_options {VCCI_2.5_VOLTR:EXT} -adv_options {VCCI_3.3_VOLTR:EXT} -adv_options {VOLTR:EXT} + } else { + invalid_third_argument + exit 1 + } + download_required_direct_cores + source ./import/components/IMC_CFG1/import_sd_and_constraints_imc_cfg1.tcl + save_project + base_design_built + } +} elseif {"$config" == "CFG2"} then { + if {[file exists $project_dir] == 1} then { + project_exists + } else { + create_new_project_label + if {"$die_variant" == "PS"} then { + new_project -location $project_dir -name $project_name -project_description {} -block_mode 0 -standalone_peripheral_initialization 0 -instantiate_in_smartdesign 1 -ondemand_build_dh 1 -hdl {VERILOG} -family {PolarFire} -die {MPF300TS} -package {FCG484} -speed {STD} -die_voltage {1.0} -part_range {IND} -adv_options {IO_DEFT_STD:LVCMOS 1.8V} -adv_options {RESTRICTPROBEPINS:1} -adv_options {RESTRICTSPIPINS:0} -adv_options {SYSTEM_CONTROLLER_SUSPEND_MODE:0} -adv_options {TEMPR:IND} -adv_options {VCCI_1.2_VOLTR:IND} -adv_options {VCCI_1.5_VOLTR:IND} -adv_options {VCCI_1.8_VOLTR:IND} -adv_options {VCCI_2.5_VOLTR:IND} -adv_options {VCCI_3.3_VOLTR:IND} -adv_options {VOLTR:IND} + } elseif {"$die_variant" == "ES"} then { + new_project -location $project_dir -name $project_name -project_description {} -block_mode 0 -standalone_peripheral_initialization 0 -instantiate_in_smartdesign 1 -ondemand_build_dh 1 -hdl {VERILOG} -family {PolarFire} -die {MPF300TS_ES} -package {FCG484} -speed {STD} -die_voltage {1.0} -part_range {EXT} -adv_options {IO_DEFT_STD:LVCMOS 1.8V} -adv_options {RESTRICTPROBEPINS:1} -adv_options {RESTRICTSPIPINS:0} -adv_options {SYSTEM_CONTROLLER_SUSPEND_MODE:0} -adv_options {TEMPR:EXT} -adv_options {VCCI_1.2_VOLTR:EXT} -adv_options {VCCI_1.5_VOLTR:EXT} -adv_options {VCCI_1.8_VOLTR:EXT} -adv_options {VCCI_2.5_VOLTR:EXT} -adv_options {VCCI_3.3_VOLTR:EXT} -adv_options {VOLTR:EXT} + } else { + invalid_third_argument + exit 1 + } + download_required_direct_cores + source ./import/components/IMC_CFG2/import_sd_and_constraints_imc_cfg2.tcl + save_project + base_design_built + } +} elseif {"$config" == "CFG3"} then { + if {[file exists $project_dir] == 1} then { + project_exists + } else { + create_new_project_label + if {"$die_variant" == "PS"} then { + new_project -location $project_dir -name $project_name -project_description {} -block_mode 0 -standalone_peripheral_initialization 0 -instantiate_in_smartdesign 1 -ondemand_build_dh 1 -hdl {VERILOG} -family {PolarFire} -die {MPF300TS} -package {FCG484} -speed {STD} -die_voltage {1.0} -part_range {IND} -adv_options {IO_DEFT_STD:LVCMOS 1.8V} -adv_options {RESTRICTPROBEPINS:1} -adv_options {RESTRICTSPIPINS:0} -adv_options {SYSTEM_CONTROLLER_SUSPEND_MODE:0} -adv_options {TEMPR:IND} -adv_options {VCCI_1.2_VOLTR:IND} -adv_options {VCCI_1.5_VOLTR:IND} -adv_options {VCCI_1.8_VOLTR:IND} -adv_options {VCCI_2.5_VOLTR:IND} -adv_options {VCCI_3.3_VOLTR:IND} -adv_options {VOLTR:IND} + } elseif {"$die_variant" == "ES"} then { + new_project -location $project_dir -name $project_name -project_description {} -block_mode 0 -standalone_peripheral_initialization 0 -instantiate_in_smartdesign 1 -ondemand_build_dh 1 -hdl {VERILOG} -family {PolarFire} -die {MPF300TS_ES} -package {FCG484} -speed {STD} -die_voltage {1.0} -part_range {EXT} -adv_options {IO_DEFT_STD:LVCMOS 1.8V} -adv_options {RESTRICTPROBEPINS:1} -adv_options {RESTRICTSPIPINS:0} -adv_options {SYSTEM_CONTROLLER_SUSPEND_MODE:0} -adv_options {TEMPR:EXT} -adv_options {VCCI_1.2_VOLTR:EXT} -adv_options {VCCI_1.5_VOLTR:EXT} -adv_options {VCCI_1.8_VOLTR:EXT} -adv_options {VCCI_2.5_VOLTR:EXT} -adv_options {VCCI_3.3_VOLTR:EXT} -adv_options {VOLTR:EXT} + } else { + invalid_third_argument + exit 1 + } + download_required_direct_cores + source ./import/components/IMC_CFG3/import_sd_and_constraints_imc_cfg3.tcl + save_project + base_design_built + } +} elseif {"$config" == "DGC2"} then { + if {[file exists $project_dir] == 1} then { + project_exists + } else { + create_new_project_label + if {"$die_variant" == "PS"} then { + new_project -location $project_dir -name $project_name -project_description {} -block_mode 0 -standalone_peripheral_initialization 0 -instantiate_in_smartdesign 1 -ondemand_build_dh 1 -hdl {VERILOG} -family {PolarFire} -die {MPF300TS} -package {FCG484} -speed {STD} -die_voltage {1.0} -part_range {IND} -adv_options {IO_DEFT_STD:LVCMOS 1.8V} -adv_options {RESTRICTPROBEPINS:1} -adv_options {RESTRICTSPIPINS:0} -adv_options {SYSTEM_CONTROLLER_SUSPEND_MODE:0} -adv_options {TEMPR:IND} -adv_options {VCCI_1.2_VOLTR:IND} -adv_options {VCCI_1.5_VOLTR:IND} -adv_options {VCCI_1.8_VOLTR:IND} -adv_options {VCCI_2.5_VOLTR:IND} -adv_options {VCCI_3.3_VOLTR:IND} -adv_options {VOLTR:IND} + } elseif {"$die_variant" == "ES"} then { + new_project -location $project_dir -name $project_name -project_description {} -block_mode 0 -standalone_peripheral_initialization 0 -instantiate_in_smartdesign 1 -ondemand_build_dh 1 -hdl {VERILOG} -family {PolarFire} -die {MPF300TS_ES} -package {FCG484} -speed {STD} -die_voltage {1.0} -part_range {EXT} -adv_options {IO_DEFT_STD:LVCMOS 1.8V} -adv_options {RESTRICTPROBEPINS:1} -adv_options {RESTRICTSPIPINS:0} -adv_options {SYSTEM_CONTROLLER_SUSPEND_MODE:0} -adv_options {TEMPR:EXT} -adv_options {VCCI_1.2_VOLTR:EXT} -adv_options {VCCI_1.5_VOLTR:EXT} -adv_options {VCCI_1.8_VOLTR:EXT} -adv_options {VCCI_2.5_VOLTR:EXT} -adv_options {VCCI_3.3_VOLTR:EXT} -adv_options {VOLTR:EXT} + } else { + invalid_third_argument + exit 1 + } + file copy ./import/components/IMC_DGC2/hex/miv-rv32i-systick-blinky.hex $project_dir + download_required_direct_cores + file copy ./import/components/IMC_DGC2/bootloader_elf ./MIV_DGC2_BD + source ./import/components/IMC_DGC2/import_sd_and_constraints_miv_ess_dgc2.tcl + save_project + base_design_built + } +} else { + invalid_first_argument + exit 1 +} + +pre_configure_place_and_route + +if {"$design_flow_stage" == "SYNTHESIZE"} then { + puts "\n------------------------------------------------------------------------------- \ + \r\nBegin Synthesis... \ + \r\n-------------------------------------------------------------------------------" + + run_tool -name {SYNTHESIZE} + save_project + + puts "\n------------------------------------------------------------------------------- \ + \r\nSynthesis Complete. \ + \r\n-------------------------------------------------------------------------------" + + +} elseif {"$design_flow_stage" == "PLACE_AND_ROUTE"} then { + + puts "\n------------------------------------------------------------------------------- \ + \r\nBegin Place and Route... \ + \r\n-------------------------------------------------------------------------------" + + run_verify_timing + save_project + + puts "\n------------------------------------------------------------------------------- \ + \r\nPlace and Route Complete. \ + \r\n-------------------------------------------------------------------------------" + + +} elseif {"$design_flow_stage" == "GENERATE_BITSTREAM"} then { + + puts "\n------------------------------------------------------------------------------- \ + \r\nGenerating Bitstream... \ + \r\n-------------------------------------------------------------------------------" + + run_verify_timing + run_tool -name {GENERATEPROGRAMMINGDATA} + run_tool -name {GENERATEPROGRAMMINGFILE} + save_project + + puts "\n------------------------------------------------------------------------------- \ + \r\nBitstream Generated. \ + \r\n-------------------------------------------------------------------------------" + + +} elseif {"$design_flow_stage" == "EXPORT_PROGRAMMING_FILE"} then { + + puts "\n------------------------------------------------------------------------------- \ + \r\nExporting Programming Files... \ + \r\n-------------------------------------------------------------------------------" + run_verify_timing + run_tool -name {GENERATEPROGRAMMINGFILE} + + + export_prog_job \ + -job_file_name $project_name \ + -export_dir $project_dir/designer/BaseDesign/export \ + -bitstream_file_type {TRUSTED_FACILITY} \ + -bitstream_file_components {} + save_project + + + puts "\n------------------------------------------------------------------------------- \ + \r\nProgramming Files Exported. \ + \r\n-------------------------------------------------------------------------------" + +} else { + puts "Info: No design flow tool run." +} + + + diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/PF_Avalanche_MIV_RV32_BaseDesign.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/PF_Avalanche_MIV_RV32_BaseDesign.tcl new file mode 100644 index 0000000..c9c7334 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/PF_Avalanche_MIV_RV32_BaseDesign.tcl @@ -0,0 +1,297 @@ +set config [string toupper [lindex $argv 0]] +set design_flow_stage [string toupper [lindex $argv 1]] +set die_variant [string toupper [lindex $argv 2]] + +set hw_platform PF_Avalanche +set soft_cpu MIV_RV32 +set sd_reference BaseDesign + +# +# Procedure blocks start +proc create_new_project_label { } { + puts "\n------------------------------------------------------------------------------- \ + \r\nCreating a new project for the 'PF_Avalanche' board. \ + \r\n-------------------------------------------------------------------------------" +} + +proc project_exists { } { + puts "\n------------------------------------------------------------------------------- \ + \r\nError: A project exists for the 'PF_Avalanche' with this configuration. \ + \r\n-------------------------------------------------------------------------------" +} + +proc no_first_argument_entered { } { + puts "\n------------------------------------------------------------------------------- \ + \r\nInfo: No 1st Argument has been entered. \ + \r\nInfo: Enter the 1st Argument responsible for type of design configuration -'CFG1..CFGn' \ + \r\nInfo: Default 'CFG1' design has been selected. \ + \r\n-------------------------------------------------------------------------------" +} + +proc invalid_first_argument { } { + puts "\n------------------------------------------------------------------------------- \ + \r\nError: Wrong 1st Argument has been entered. No valid configuration detected. \ + \r\nInfo: Make sure you enter a valid first argument -'CFG1..CFGn'. \ + \r\n-------------------------------------------------------------------------------" +} + +proc no_second_argument_entered { } { + puts "\n------------------------------------------------------------------------------- \ + \r\nInfo: No 2nd Argument has been entered. \ + \r\nInfo: Enter the 2nd Argument after the 1st to be taken further in the Design Flow. \ + \r\n-------------------------------------------------------------------------------" +} + +proc invalid_second_argument { } { + puts "\n------------------------------------------------------------------------------- \ + \r\nError: Wrong 2nd Argument has been entered. \ + \r\nInfo: Make sure you enter a valid 2nd argument -'Synthesize...Export_Programming_File'.\ + \r\n-------------------------------------------------------------------------------" +} + +proc no_third_argument_entered { } { + puts "\n------------------------------------------------------------------------------- \ + \r\nInfo: No 3rd Argument has been entered. \ + \r\nInfo: Assuming the default 'PS' die type as target \ + \r\n-------------------------------------------------------------------------------" +} + +proc invalid_third_argument { } { + puts "\n------------------------------------------------------------------------------- \ + \r\nError: Wrong 3rd Argument has been entered. \ + \r\nInfo: Make sure you enter 'PS' or 'ES' to specify die target type. \ + \r\n-------------------------------------------------------------------------------" +} + +proc base_design_built { } { + puts "\n------------------------------------------------------------------------------- \ + \r\nInfo: BaseDesign built. \ + \r\n-------------------------------------------------------------------------------" +} + +proc download_required_direct_cores { } { + download_core -vlnv {Actel:DirectCore:CoreUARTapb:5.7.100} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Actel:DirectCore:CoreTimer:2.0.103} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Actel:DirectCore:CORERESET_PF:2.3.100} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Actel:DirectCore:COREJTAGDEBUG:4.0.100} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Actel:DirectCore:CoreGPIO:3.2.102} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Actel:DirectCore:COREAXITOAHBL:3.6.101} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Actel:DirectCore:CoreAPB3:4.2.100} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Actel:DirectCore:COREAHBTOAPB3:3.2.101} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Actel:DirectCore:CoreAHBLite:5.6.105} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Microsemi:MiV:MIV_RV32:3.0.100} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Microsemi:MiV:MIV_RV32IMA_L1_AHB:2.3.100} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Microsemi:MiV:MIV_RV32IMA_L1_AXI:2.1.100} -location {www.microchip-ip.com/repositories/DirectCore} + download_core -vlnv {Microsemi:MiV:MIV_RV32IMAF_L1_AHB:2.1.100} -location {www.microchip-ip.com/repositories/DirectCore} +} + +proc pre_configure_place_and_route { } { + # Configuring Place_and_Route tool for a timing pass. + configure_tool -name {PLACEROUTE} -params {EFFORT_LEVEL:false} -params {REPAIR_MIN_DELAY:true} -params {TDPR:true} +} + +proc run_verify_timing { } { + run_tool -name {VERIFYTIMING} +} +# Procedure blocks end +# + +#Filter for argument argv0: config +if {$config == ""} then { + set config "CFG1" + no_first_argument_entered +} elseif {$config != "CFG1" + && $config != "CFG2" + && $config != "CFG3" + && $config != "DGC2"} then { + puts "config is: $config" + invalid_first_argument + exit 1 +} else { + puts "Info: Configuration selected: $config" +} + +#Filter for argument argv1: design flow +if {$design_flow_stage == ""} then { + no_second_argument_entered +} elseif {$design_flow_stage == "SYNTHESIZE" + || $design_flow_stage == "PLACE_AND_ROUTE" + || $design_flow_stage == "GENERATE_BITSTREAM" + || $design_flow_stage == "EXPORT_PROGRAMMING_FILE"} then { + puts "Info: Design flow run tool selected: $design_flow_stage" +} elseif {$design_flow_stage == "ES" + || $design_flow_stage == "PS"} then { + set die_variant "$design_flow_stage" +} else { + invalid_second_argument + exit 1 +} + +#Filter for argument argv2: die type +if {$die_variant == ""} { + set die_variant "PS" + no_third_argument_entered +} elseif {$die_variant == "PS" + || $die_variant == "ES"} then { + puts "Info: Die type selected: $die_variant" +} else { + invalid_third_argument + exit 1 +} + +append target_board $hw_platform _ $die_variant +append project_folder_name MIV_ $config _BD +set project_dir "./$project_folder_name" +append project_name $target_board _ $soft_cpu _ $config _ $sd_reference + +if {"$config" == "CFG1"} then { + if {[file exists $project_dir] == 1} then { + project_exists + } else { + create_new_project_label + if {"$die_variant" == "PS"} then { + new_project -location $project_dir -name $project_name -project_description {} -block_mode 0 -standalone_peripheral_initialization 0 -instantiate_in_smartdesign 1 -ondemand_build_dh 1 -hdl {VERILOG} -family {PolarFire} -die {MPF300TS} -package {FCG484} -speed {STD} -die_voltage {1.0} -part_range {IND} -adv_options {IO_DEFT_STD:LVCMOS 1.8V} -adv_options {RESTRICTPROBEPINS:1} -adv_options {RESTRICTSPIPINS:0} -adv_options {SYSTEM_CONTROLLER_SUSPEND_MODE:0} -adv_options {TEMPR:IND} -adv_options {VCCI_1.2_VOLTR:IND} -adv_options {VCCI_1.5_VOLTR:IND} -adv_options {VCCI_1.8_VOLTR:IND} -adv_options {VCCI_2.5_VOLTR:IND} -adv_options {VCCI_3.3_VOLTR:IND} -adv_options {VOLTR:IND} + } elseif {"$die_variant" == "ES"} then { + new_project -location $project_dir -name $project_name -project_description {} -block_mode 0 -standalone_peripheral_initialization 0 -instantiate_in_smartdesign 1 -ondemand_build_dh 1 -hdl {VERILOG} -family {PolarFire} -die {MPF300TS_ES} -package {FCG484} -speed {STD} -die_voltage {1.0} -part_range {EXT} -adv_options {IO_DEFT_STD:LVCMOS 1.8V} -adv_options {RESTRICTPROBEPINS:1} -adv_options {RESTRICTSPIPINS:0} -adv_options {SYSTEM_CONTROLLER_SUSPEND_MODE:0} -adv_options {TEMPR:EXT} -adv_options {VCCI_1.2_VOLTR:EXT} -adv_options {VCCI_1.5_VOLTR:EXT} -adv_options {VCCI_1.8_VOLTR:EXT} -adv_options {VCCI_2.5_VOLTR:EXT} -adv_options {VCCI_3.3_VOLTR:EXT} -adv_options {VOLTR:EXT} + } else { + invalid_third_argument + exit 1 + } + download_required_direct_cores + source ./import/components/IMC_CFG1/import_sd_and_constraints_imc_cfg1.tcl + save_project + base_design_built + } +} elseif {"$config" == "CFG2"} then { + if {[file exists $project_dir] == 1} then { + project_exists + } else { + create_new_project_label + if {"$die_variant" == "PS"} then { + new_project -location $project_dir -name $project_name -project_description {} -block_mode 0 -standalone_peripheral_initialization 0 -instantiate_in_smartdesign 1 -ondemand_build_dh 1 -hdl {VERILOG} -family {PolarFire} -die {MPF300TS} -package {FCG484} -speed {STD} -die_voltage {1.0} -part_range {IND} -adv_options {IO_DEFT_STD:LVCMOS 1.8V} -adv_options {RESTRICTPROBEPINS:1} -adv_options {RESTRICTSPIPINS:0} -adv_options {SYSTEM_CONTROLLER_SUSPEND_MODE:0} -adv_options {TEMPR:IND} -adv_options {VCCI_1.2_VOLTR:IND} -adv_options {VCCI_1.5_VOLTR:IND} -adv_options {VCCI_1.8_VOLTR:IND} -adv_options {VCCI_2.5_VOLTR:IND} -adv_options {VCCI_3.3_VOLTR:IND} -adv_options {VOLTR:IND} + } elseif {"$die_variant" == "ES"} then { + new_project -location $project_dir -name $project_name -project_description {} -block_mode 0 -standalone_peripheral_initialization 0 -instantiate_in_smartdesign 1 -ondemand_build_dh 1 -hdl {VERILOG} -family {PolarFire} -die {MPF300TS_ES} -package {FCG484} -speed {STD} -die_voltage {1.0} -part_range {EXT} -adv_options {IO_DEFT_STD:LVCMOS 1.8V} -adv_options {RESTRICTPROBEPINS:1} -adv_options {RESTRICTSPIPINS:0} -adv_options {SYSTEM_CONTROLLER_SUSPEND_MODE:0} -adv_options {TEMPR:EXT} -adv_options {VCCI_1.2_VOLTR:EXT} -adv_options {VCCI_1.5_VOLTR:EXT} -adv_options {VCCI_1.8_VOLTR:EXT} -adv_options {VCCI_2.5_VOLTR:EXT} -adv_options {VCCI_3.3_VOLTR:EXT} -adv_options {VOLTR:EXT} + } else { + invalid_third_argument + exit 1 + } + download_required_direct_cores + source ./import/components/IMC_CFG2/import_sd_and_constraints_imc_cfg2.tcl + save_project + base_design_built + } +} elseif {"$config" == "CFG3"} then { + if {[file exists $project_dir] == 1} then { + project_exists + } else { + create_new_project_label + if {"$die_variant" == "PS"} then { + new_project -location $project_dir -name $project_name -project_description {} -block_mode 0 -standalone_peripheral_initialization 0 -instantiate_in_smartdesign 1 -ondemand_build_dh 1 -hdl {VERILOG} -family {PolarFire} -die {MPF300TS} -package {FCG484} -speed {STD} -die_voltage {1.0} -part_range {IND} -adv_options {IO_DEFT_STD:LVCMOS 1.8V} -adv_options {RESTRICTPROBEPINS:1} -adv_options {RESTRICTSPIPINS:0} -adv_options {SYSTEM_CONTROLLER_SUSPEND_MODE:0} -adv_options {TEMPR:IND} -adv_options {VCCI_1.2_VOLTR:IND} -adv_options {VCCI_1.5_VOLTR:IND} -adv_options {VCCI_1.8_VOLTR:IND} -adv_options {VCCI_2.5_VOLTR:IND} -adv_options {VCCI_3.3_VOLTR:IND} -adv_options {VOLTR:IND} + } elseif {"$die_variant" == "ES"} then { + new_project -location $project_dir -name $project_name -project_description {} -block_mode 0 -standalone_peripheral_initialization 0 -instantiate_in_smartdesign 1 -ondemand_build_dh 1 -hdl {VERILOG} -family {PolarFire} -die {MPF300TS_ES} -package {FCG484} -speed {STD} -die_voltage {1.0} -part_range {EXT} -adv_options {IO_DEFT_STD:LVCMOS 1.8V} -adv_options {RESTRICTPROBEPINS:1} -adv_options {RESTRICTSPIPINS:0} -adv_options {SYSTEM_CONTROLLER_SUSPEND_MODE:0} -adv_options {TEMPR:EXT} -adv_options {VCCI_1.2_VOLTR:EXT} -adv_options {VCCI_1.5_VOLTR:EXT} -adv_options {VCCI_1.8_VOLTR:EXT} -adv_options {VCCI_2.5_VOLTR:EXT} -adv_options {VCCI_3.3_VOLTR:EXT} -adv_options {VOLTR:EXT} + } else { + invalid_third_argument + exit 1 + } + download_required_direct_cores + source ./import/components/IMC_CFG3/import_sd_and_constraints_imc_cfg3.tcl + save_project + base_design_built + } +} elseif {"$config" == "DGC2"} then { + if {[file exists $project_dir] == 1} then { + project_exists + } else { + create_new_project_label + if {"$die_variant" == "PS"} then { + new_project -location $project_dir -name $project_name -project_description {} -block_mode 0 -standalone_peripheral_initialization 0 -instantiate_in_smartdesign 1 -ondemand_build_dh 1 -hdl {VERILOG} -family {PolarFire} -die {MPF300TS} -package {FCG484} -speed {STD} -die_voltage {1.0} -part_range {IND} -adv_options {IO_DEFT_STD:LVCMOS 1.8V} -adv_options {RESTRICTPROBEPINS:1} -adv_options {RESTRICTSPIPINS:0} -adv_options {SYSTEM_CONTROLLER_SUSPEND_MODE:0} -adv_options {TEMPR:IND} -adv_options {VCCI_1.2_VOLTR:IND} -adv_options {VCCI_1.5_VOLTR:IND} -adv_options {VCCI_1.8_VOLTR:IND} -adv_options {VCCI_2.5_VOLTR:IND} -adv_options {VCCI_3.3_VOLTR:IND} -adv_options {VOLTR:IND} + } elseif {"$die_variant" == "ES"} then { + new_project -location $project_dir -name $project_name -project_description {} -block_mode 0 -standalone_peripheral_initialization 0 -instantiate_in_smartdesign 1 -ondemand_build_dh 1 -hdl {VERILOG} -family {PolarFire} -die {MPF300TS_ES} -package {FCG484} -speed {STD} -die_voltage {1.0} -part_range {EXT} -adv_options {IO_DEFT_STD:LVCMOS 1.8V} -adv_options {RESTRICTPROBEPINS:1} -adv_options {RESTRICTSPIPINS:0} -adv_options {SYSTEM_CONTROLLER_SUSPEND_MODE:0} -adv_options {TEMPR:EXT} -adv_options {VCCI_1.2_VOLTR:EXT} -adv_options {VCCI_1.5_VOLTR:EXT} -adv_options {VCCI_1.8_VOLTR:EXT} -adv_options {VCCI_2.5_VOLTR:EXT} -adv_options {VCCI_3.3_VOLTR:EXT} -adv_options {VOLTR:EXT} + } else { + invalid_third_argument + exit 1 + } + file copy ./import/components/IMC_DGC2/hex/miv-rv32i-systick-blinky.hex $project_dir + download_required_direct_cores + file copy ./import/components/IMC_DGC2/bootloader_elf ./MIV_DGC2_BD + source ./import/components/IMC_DGC2/import_sd_and_constraints_miv_ess_dgc2.tcl + save_project + base_design_built + } +} else { + invalid_first_argument + exit 1 +} + +pre_configure_place_and_route + +if {"$design_flow_stage" == "SYNTHESIZE"} then { + puts "\n------------------------------------------------------------------------------- \ + \r\nBegin Synthesis... \ + \r\n-------------------------------------------------------------------------------" + + run_tool -name {SYNTHESIZE} + save_project + + puts "\n------------------------------------------------------------------------------- \ + \r\nSynthesis Complete. \ + \r\n-------------------------------------------------------------------------------" + + +} elseif {"$design_flow_stage" == "PLACE_AND_ROUTE"} then { + + puts "\n------------------------------------------------------------------------------- \ + \r\nBegin Place and Route... \ + \r\n-------------------------------------------------------------------------------" + + run_verify_timing + save_project + + puts "\n------------------------------------------------------------------------------- \ + \r\nPlace and Route Complete. \ + \r\n-------------------------------------------------------------------------------" + + +} elseif {"$design_flow_stage" == "GENERATE_BITSTREAM"} then { + + puts "\n------------------------------------------------------------------------------- \ + \r\nGenerating Bitstream... \ + \r\n-------------------------------------------------------------------------------" + + run_verify_timing + run_tool -name {GENERATEPROGRAMMINGDATA} + run_tool -name {GENERATEPROGRAMMINGFILE} + save_project + + puts "\n------------------------------------------------------------------------------- \ + \r\nBitstream Generated. \ + \r\n-------------------------------------------------------------------------------" + + +} elseif {"$design_flow_stage" == "EXPORT_PROGRAMMING_FILE"} then { + + puts "\n------------------------------------------------------------------------------- \ + \r\nExporting Programming Files... \ + \r\n-------------------------------------------------------------------------------" + run_verify_timing + run_tool -name {GENERATEPROGRAMMINGFILE} + + + export_prog_job \ + -job_file_name $project_name \ + -export_dir $project_dir/designer/BaseDesign/export \ + -bitstream_file_type {TRUSTED_FACILITY} \ + -bitstream_file_components {} + save_project + + + puts "\n------------------------------------------------------------------------------- \ + \r\nProgramming Files Exported. \ + \r\n-------------------------------------------------------------------------------" + +} else { + puts "Info: No design flow tool run." +} + + + diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/README.md b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/README.md new file mode 100644 index 0000000..6a972ae --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/README.md @@ -0,0 +1,132 @@ +## Mi-V Extended Subsystem Design Guide Configuration 2: I2C Write & Boot +This folder contains Tcl scripts that build Libero SoC v2022.1 MIV_ESS DGC2 design project for the Future Avalanche Board. The script is executed in Libero SoC to generate the sample design. +> Design is catered for Libero SoC v2022.1. Using older versions of Libero SoC will result in errors. + +#### PF_Avalanche_MIV_RV32_BaseDesign + +| Config | Description | +| :------:|:----------------------------------------| +| DGC2 | This design uses the **MIV_RV32** core configured as follows:
  • RISC-V Extensions: IMC
  • Multiplier: MACC (Pipelined)
  • Interfaces: AHB Master (mirrored), APB3 Master
  • Reset Vector Address: 0x4000_0000
  • Internal IRQs: 6
  • TCM: Enabled
  • TCM APB Slave (TAS): Enabled
  • System Timer: Internal MTIME enabled, Internal MTIME IRQ enabled
  • Debug: enabled
This design uses the **MIV_ESS** core configured as follows:
  • Bootstrap: Enabled
  • Bootstrap Source: I2C
  • uDMA: Disabled
  • GPIO: Enabled, 2 GPIO_IN and 4 GPIO_OUT (fixed config)
  • I2C: Enabled, Two-Byte I2C Address
  • PLIC: Disabled
  • SPI: Disabled
  • Timer: Disabled
  • UART: Enabled
  • Watchdog: Disabled
| + +> This design configuration is only available for the PolarFire Avalanche Kit (Revision 3 with production silicon devices). + +**Important**: This design requires a Dual EE Click board from mikroBUS inserted into the mikroBUS header on the Avalanche Development Kit board. The Dual EE Click is available at [Mikroe.com](https://www.mikroe.com/dual-ee-click). + + +## Instructions + +#### Running Libero SoC in GUI mode, with Script Arguments + 1. Open Libero SoC + 2. Execute the selected script, Project -> Execute Script + 3. Select the directory that the script is located in, using the "..." + 4. Select the script and select "Open" + 5. In the arguments text box, enter "DGC2 SYNTHESIZE PS" + 6. Select the "Run" button to execute the script + 7. Once complete, a script report will be generated. + +In this example, the arguments "DGC2 SYNTHESIZE PS" are entered to take the production silicon (PS) die project through to Synthesis. + +Libero executes the script and opens the Mi-V sample project targeted for a production silicon (PS) die. The script adds Timing constraints to the project for Synthesis, Place and Route, and Timing Verification. Additionally, I/O Constraints are added to the project for Place and Route. The project can now be taken through the remainder of the Libero SoC design flow. + +## Script Arguments +The complete set of script arguments are documented here. + +#### First argument: +| Argument | Description | +| ------------------------- |:---------------| +| DGC2 | Generate a MIV_ESS example design from the *MIV_ESS v2.0 Design Guide* (accessible from the Libero catalog) | + +#### Second argument: +| Argument | Description | +| ------------------------- |:---------------| +| SYNTHESIZE | Run synthesis on the design | +| PLACE_AND_ROUTE | Run place and route on the design | +| GENERATE_BITSTREAM | Generate the bitstream for the design| +| EXPORT_PROGRAMMING_FILE | Export the programming file (.job) | + + +#### Third argument: +| Argument | Description | +| ------------------------- |:---------------| +| PS | Build a base design targeted for 'PS' die | +| ES | Build a base design targeted for 'ES' die | + + +## Software Provided +There are two programs included with this configuration: +* **miv-rv32i-systick-blinky.hex**: A Hex program configured to run from TCM's address (0x4000_0000). The program is initialized in the LSRAM component at 0x8000_0000 and it is accessible over the AHB interface. + > The example hex program was created using miv-rv32i-systick-blinky in release mode (miv32i-Release). For more information about the project go to bare metal example: [miv-rv32i-systick-blinky](https://github.com/Mi-V-Soft-RISC-V/miv-rv32-bare-metal-examples/tree/main/applications/miv-rv32-hal/miv-rv32i-systick-blinky) + +* **miv-rv32-ess-bootloader.elf**: The supplied Bootloader .elf file is used to copy data from the LSRAM (SRC_MEM) @0x8000_0000 to external I2C Flash memory (Dual EE Click board required) + > The .elf program was compiled using 'miv-rv32-ess-bootloader' in Bootstrap mode. For more information about the project go to bare metal example: [miv-rv32-ess-bootloader](https://github.com/Mi-V-Soft-RISC-V/miv-rv32-bare-metal-examples/tree/main/applications/bootloaders/miv-rv32-bootloader) + +#### Running a Bootloader .elf program for DGC2 +The provided program, *miv-rv32-ess-bootloader.elf* , is available in the Libero project folder after the *create_project* .tcl script has been run for the Design Configuration 2 (DGC2). The program can be used to transfer a program stored in LSRAM to an external I2C EEPROM. The MIV_ESS can then copy the code to the MIV_RV32 Tightly Coupled Memory (TCM), then the MIV_RV32 can boot the copied code. + +The sources are available from the [Mi-V Soft processor Bare Metal examples](https://github.com/Mi-V-Soft-RISC-V/miv-rv32-bare-metal-examples). +To run the Bootloader .elf program, follow the steps below or refer to the *MIV_ESS v2.0 Design Guide* (accessible from the Libero catalog) for more detailed instructions: +> A DGC2 Libero design directory is required to have been created to access the .elf file. The hardware needs to be programmed with DGC2 bitstream. + + 1. Open SoftConsole (v2021.1 or above) + 2. From Run > Debug Configurations, double click GDB OpenOCD Debugging + 3. In the Main window, select C/C++ Applications using the Browse button, then navigate to your Libero's project directory ./MIV_DGC2_BD and select the Bootloader .elf file + 4. Select the Debugger tab to set up OpenOCD and GDB + a. To set up OpenOCD, check the Start OpenOCD locally check box and browse to the OpenOCD path \openocd\bin\openocd.exe + b. To set up GDB, browse to the GDB path \riscv-unknownelf-gcc\bin\riscv64-unknown-elf-gdb.exe. + 5. Click Apply + 6. Click Debug to launch the debug session. + +## Design Guide Configuration - DGC2: I2C Write & Boot + +> This design requires a Dual EE Click board from mikroBUS inserted into the mikroBUS header on the Avalanche Development Kit board. The Dual EE Click is available at [Mikroe.com](https://www.mikroe.com/dual-ee-click). + +### Features +The Libero designs include the following features: +* A soft RISC-V processor. +* A RISC-V debug block allowing on-target debug using SoftConsole +* An Extended subsystem with peripheral cores +* The operating frequency of the design is 50MHz +* Target memory is SRAM/TCM (32kB) +* User peripherals: MIV_ESS (Bootstrap, I2C, GPIO, UART) + +### Boot Sequence Operation +A more detailed description of the boot sequence can be found in this section. + +> Pre-requisites: +> * Ensure the Dual EE Click board is inserted correctly in the mikroBUS header on the Future Avalanche Board. +> * The board needs to be programmed with DGC2 bitstream. Refer to this section, run the [Libero Design](#Running Libero SoC in GUI mode, with Script Arguments) +> * Initiating the Boot Sequence for DGC2, requires data to be previously written to external memory I2C EEPROM. Use the provided Bootloader .elf program *miv-rv32-ess-bootloader.elf* to write the *miv-rv32i-systick-blinky.hex* program in the LSRAM to the external memory I2C Flash. + + 1. Once the board has been powered-on, hold SW1 to enable the Bootstrap functionality in the MIV_ESS. Then press and release SW2 to perform a system reset request. + 2. MIV_ESS copies a program from the I2C Flash device to the MIV_RV32 Tightly-Coupled Memory (TCM) via the TCM APB Slave (TAS) interface. + 3. When the transfer from I2C Flash is complete, MIV_ESS releases MIV_RV32 core from reset and MIV_RV32 is allowed to boot the program from TCM. + 4. The LEDs on the Future Avalanche Board will start blinking, signifying Bootstrap has completed its transfer and SW1 can then be released. + +### Peripherals - MIV_ESS + +| Peripheral | Address Start | Address End | +| ------------------------------: |:-------------:|:--------------:| +| PLIC | 0x7000_0000 | 0x70FF_FFFF | +| CoreUARTapb | 0x7100_0000 | 0x71FF_FFFF | +| Timer | 0x7200_0000 | 0x72FF_FFFF | +| CoreTimer_0 / MIV_ESS_APBSLOT3 | 0x7300_0000 | 0x73FF_FFFF | +| CoreTimer_1 / MIV_ESS_APBSLOT4 | 0x7400_0000 | 0x74FF_FFFF | +| CoreGPIO_OUT | 0x7500_0000 | 0x75FF_FFFF | +| SPI | 0x7600_0000 | 0x76FF_FFFF | +| uDMA | 0x7800_0000 | 0x78FF_FFFF | +| WDOG | 0x7900_0000 | 0x79FF_FFFF | +| I2C | 0x7A00_0000 | 0x7AFF_FFFF | +| MIV_ESS_APBSLOTB_BASE | 0x7B00_0000 | 0x7BFF_FFFF | +| MIV_ESS_APBSLOTC_BASE | 0x7C00_0000 | 0x7CFF_FFFF | +| MIV_ESS_APBSLOTD_BASE | 0x7D00_0000 | 0x7DFF_FFFF | +| MIV_ESS_APBSLOTE_BASE | 0x7E00_0000 | 0x7EFF_FFFF | +| MIV_ESS_APBSLOTF_BASE | 0x7F00_0000 | 0x7FFF_FFFF | + +### Memory Sources + +| Memory Source | Address Start | Address End | Size | +| -------------------------------: |:-------------:|:-----------:|:------:| +| TCM | 0x4000_0000 | 0x4000_7FFF | 32kB | +| LSRAM | 0x8000_0000 | 0x8000_7FFF | 32kB | + + diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/bootloader_elf/miv-rv32-ess-bootloader.elf b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/bootloader_elf/miv-rv32-ess-bootloader.elf new file mode 100644 index 0000000..adc86ca Binary files /dev/null and b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/bootloader_elf/miv-rv32-ess-bootloader.elf differ diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/COREJTAGDEBUG_C0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/COREJTAGDEBUG_C0.tcl new file mode 100644 index 0000000..829202c --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/COREJTAGDEBUG_C0.tcl @@ -0,0 +1,41 @@ +# Exporting Component Description of COREJTAGDEBUG_C0 to TCL +# Family: PolarFire +# Part Number: MPF300T_ES-FCG484E +# Create and Configure the core component COREJTAGDEBUG_C0 +create_and_configure_core -core_vlnv {Actel:DirectCore:COREJTAGDEBUG:4.0.100} -component_name {COREJTAGDEBUG_C0} -params {\ +"IR_CODE_TGT_0:0x55" \ +"IR_CODE_TGT_1:0x56" \ +"IR_CODE_TGT_2:0x57" \ +"IR_CODE_TGT_3:0x58" \ +"IR_CODE_TGT_4:0x59" \ +"IR_CODE_TGT_5:0x5a" \ +"IR_CODE_TGT_6:0x5b" \ +"IR_CODE_TGT_7:0x5c" \ +"IR_CODE_TGT_8:0x5d" \ +"IR_CODE_TGT_9:0x5e" \ +"IR_CODE_TGT_10:0x5f" \ +"IR_CODE_TGT_11:0x60" \ +"IR_CODE_TGT_12:0x61" \ +"IR_CODE_TGT_13:0x62" \ +"IR_CODE_TGT_14:0x63" \ +"IR_CODE_TGT_15:0x64" \ +"NUM_DEBUG_TGTS:1" \ +"TGT_ACTIVE_HIGH_RESET_0:false" \ +"TGT_ACTIVE_HIGH_RESET_1:false" \ +"TGT_ACTIVE_HIGH_RESET_2:false" \ +"TGT_ACTIVE_HIGH_RESET_3:false" \ +"TGT_ACTIVE_HIGH_RESET_4:false" \ +"TGT_ACTIVE_HIGH_RESET_5:false" \ +"TGT_ACTIVE_HIGH_RESET_6:false" \ +"TGT_ACTIVE_HIGH_RESET_7:false" \ +"TGT_ACTIVE_HIGH_RESET_8:false" \ +"TGT_ACTIVE_HIGH_RESET_9:false" \ +"TGT_ACTIVE_HIGH_RESET_10:false" \ +"TGT_ACTIVE_HIGH_RESET_11:false" \ +"TGT_ACTIVE_HIGH_RESET_12:false" \ +"TGT_ACTIVE_HIGH_RESET_13:false" \ +"TGT_ACTIVE_HIGH_RESET_14:false" \ +"TGT_ACTIVE_HIGH_RESET_15:false" \ +"UJTAG_BYPASS:false" \ +"UJTAG_SEC_EN:false" } +# Exporting Component Description of COREJTAGDEBUG_C0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/CORERESET_PF_C0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/CORERESET_PF_C0.tcl new file mode 100644 index 0000000..d324b93 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/CORERESET_PF_C0.tcl @@ -0,0 +1,6 @@ +# Exporting Component Description of CORERESET_PF_C0 to TCL +# Family: PolarFire +# Part Number: MPF300T_ES-FCG484E +# Create and Configure the core component CORERESET_PF_C0 +create_and_configure_core -core_vlnv {Actel:DirectCore:CORERESET_PF:2.3.100} -component_name {CORERESET_PF_C0} -params { } +# Exporting Component Description of CORERESET_PF_C0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/CoreTimer_C0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/CoreTimer_C0.tcl new file mode 100644 index 0000000..77dff03 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/CoreTimer_C0.tcl @@ -0,0 +1,8 @@ +# Exporting Component Description of CoreTimer_C0 to TCL +# Family: PolarFire +# Part Number: MPF300T_ES-FCG484E +# Create and Configure the core component CoreTimer_C0 +create_and_configure_core -core_vlnv {Actel:DirectCore:CoreTimer:2.0.103} -component_name {CoreTimer_C0} -params {\ +"INTACTIVEH:1" \ +"WIDTH:32" } +# Exporting Component Description of CoreTimer_C0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/CoreTimer_C1.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/CoreTimer_C1.tcl new file mode 100644 index 0000000..0e98079 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/CoreTimer_C1.tcl @@ -0,0 +1,8 @@ +# Exporting Component Description of CoreTimer_C1 to TCL +# Family: PolarFire +# Part Number: MPF300T_ES-FCG484E +# Create and Configure the core component CoreTimer_C1 +create_and_configure_core -core_vlnv {Actel:DirectCore:CoreTimer:2.0.103} -component_name {CoreTimer_C1} -params {\ +"INTACTIVEH:1" \ +"WIDTH:32" } +# Exporting Component Description of CoreTimer_C1 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/MIV_ESS_C0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/MIV_ESS_C0.tcl new file mode 100644 index 0000000..0508f6b --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/MIV_ESS_C0.tcl @@ -0,0 +1,208 @@ +# Exporting Component Description of MIV_ESS_C0 to TCL +# Family: PolarFire +# Part Number: MPF300T_ES-FCG484E +# Create and Configure the core component MIV_ESS_C0 +create_and_configure_core -core_vlnv {Actel:SystemBuilder:MIV_ESS:2.0.100} -component_name {MIV_ESS_C0} -params {\ +"APBSLOT11ENABLE:false" \ +"APBSLOT12ENABLE:false" \ +"APBSLOT13ENABLE:false" \ +"APBSLOT14ENABLE:false" \ +"APBSLOT15ENABLE:false" \ +"APBSLOT3ENABLE:true" \ +"APBSLOT4ENABLE:true" \ +"APB_DST_ADDR_LOWER:0x0" \ +"APB_DST_ADDR_UPPER:0x4000" \ +"APB_DWIDTH:32" \ +"APB_INITIATOR_0_MIRROR:false" \ +"APB_WIDTH:32" \ +"BAUD_VALUE:1" \ +"BAUD_VAL_FRCTN:0" \ +"BAUD_VAL_FRCTN_EN:false" \ +"BOOTLOAD_EN:true" \ +"BOOTLOAD_SOURCE:2" \ +"BUSY_SIGNAL:true" \ +"CFG_CLK:33" \ +"CFG_FIFO_DEPTH:32" \ +"CFG_FRAME_SIZE:8" \ +"CFG_MODE:0" \ +"CFG_MOT_MODE:0" \ +"CFG_MOT_SSEL:false" \ +"CFG_NSC_OPERATION:0" \ +"CFG_TI_JMB_FRAMES:false" \ +"CFG_TI_NSC_CUSTOM:0" \ +"CFG_TI_NSC_FRC:false" \ +"DATA_WORD_CNT:8192" \ +"FAMILY_TARGET:26" \ +"FIXEDMODE:0" \ +"FIXED_CONFIG_0:true" \ +"FIXED_CONFIG_1:true" \ +"FIXED_CONFIG_10:false" \ +"FIXED_CONFIG_11:false" \ +"FIXED_CONFIG_12:false" \ +"FIXED_CONFIG_13:false" \ +"FIXED_CONFIG_14:false" \ +"FIXED_CONFIG_15:false" \ +"FIXED_CONFIG_16:false" \ +"FIXED_CONFIG_17:false" \ +"FIXED_CONFIG_18:false" \ +"FIXED_CONFIG_19:false" \ +"FIXED_CONFIG_2:true" \ +"FIXED_CONFIG_20:false" \ +"FIXED_CONFIG_21:false" \ +"FIXED_CONFIG_22:false" \ +"FIXED_CONFIG_23:false" \ +"FIXED_CONFIG_24:false" \ +"FIXED_CONFIG_25:false" \ +"FIXED_CONFIG_26:false" \ +"FIXED_CONFIG_27:false" \ +"FIXED_CONFIG_28:false" \ +"FIXED_CONFIG_29:false" \ +"FIXED_CONFIG_3:true" \ +"FIXED_CONFIG_30:false" \ +"FIXED_CONFIG_31:false" \ +"FIXED_CONFIG_4:false" \ +"FIXED_CONFIG_5:false" \ +"FIXED_CONFIG_6:false" \ +"FIXED_CONFIG_7:false" \ +"FIXED_CONFIG_8:false" \ +"FIXED_CONFIG_9:false" \ +"GPIO_EN:true" \ +"GUI_ALIGN_0:true" \ +"I2C_CLK_DIVISOR:99" \ +"I2C_EN:true" \ +"I2C_MULTI_ADDR_BYTES:1" \ +"I2C_SLV_ADDR:0x50" \ +"I2C_START_ADDR_LOWER:0x0" \ +"I2C_START_ADDR_UPPER:0x0" \ +"INTERNAL_MTIME_IRQ:true" \ +"INT_BUS:0" \ +"IO_INT_TYPE_0:7" \ +"IO_INT_TYPE_1:7" \ +"IO_INT_TYPE_10:7" \ +"IO_INT_TYPE_11:7" \ +"IO_INT_TYPE_12:7" \ +"IO_INT_TYPE_13:7" \ +"IO_INT_TYPE_14:7" \ +"IO_INT_TYPE_15:7" \ +"IO_INT_TYPE_16:7" \ +"IO_INT_TYPE_17:7" \ +"IO_INT_TYPE_18:7" \ +"IO_INT_TYPE_19:7" \ +"IO_INT_TYPE_2:7" \ +"IO_INT_TYPE_20:7" \ +"IO_INT_TYPE_21:7" \ +"IO_INT_TYPE_22:7" \ +"IO_INT_TYPE_23:7" \ +"IO_INT_TYPE_24:7" \ +"IO_INT_TYPE_25:7" \ +"IO_INT_TYPE_26:7" \ +"IO_INT_TYPE_27:7" \ +"IO_INT_TYPE_28:7" \ +"IO_INT_TYPE_29:7" \ +"IO_INT_TYPE_3:7" \ +"IO_INT_TYPE_30:7" \ +"IO_INT_TYPE_31:7" \ +"IO_INT_TYPE_4:7" \ +"IO_INT_TYPE_5:7" \ +"IO_INT_TYPE_6:7" \ +"IO_INT_TYPE_7:7" \ +"IO_INT_TYPE_8:7" \ +"IO_INT_TYPE_9:7" \ +"IO_NUM:4" \ +"IO_TYPE_0:2" \ +"IO_TYPE_1:2" \ +"IO_TYPE_10:0" \ +"IO_TYPE_11:0" \ +"IO_TYPE_12:0" \ +"IO_TYPE_13:0" \ +"IO_TYPE_14:0" \ +"IO_TYPE_15:0" \ +"IO_TYPE_16:0" \ +"IO_TYPE_17:0" \ +"IO_TYPE_18:0" \ +"IO_TYPE_19:0" \ +"IO_TYPE_2:2" \ +"IO_TYPE_20:0" \ +"IO_TYPE_21:0" \ +"IO_TYPE_22:0" \ +"IO_TYPE_23:0" \ +"IO_TYPE_24:0" \ +"IO_TYPE_25:0" \ +"IO_TYPE_26:0" \ +"IO_TYPE_27:0" \ +"IO_TYPE_28:0" \ +"IO_TYPE_29:0" \ +"IO_TYPE_3:2" \ +"IO_TYPE_30:0" \ +"IO_TYPE_31:0" \ +"IO_TYPE_4:0" \ +"IO_TYPE_5:0" \ +"IO_TYPE_6:0" \ +"IO_TYPE_7:0" \ +"IO_TYPE_8:0" \ +"IO_TYPE_9:0" \ +"IO_VAL_0:0" \ +"IO_VAL_1:0" \ +"IO_VAL_10:0" \ +"IO_VAL_11:0" \ +"IO_VAL_12:0" \ +"IO_VAL_13:0" \ +"IO_VAL_14:0" \ +"IO_VAL_15:0" \ +"IO_VAL_16:0" \ +"IO_VAL_17:0" \ +"IO_VAL_18:0" \ +"IO_VAL_19:0" \ +"IO_VAL_2:0" \ +"IO_VAL_20:0" \ +"IO_VAL_21:0" \ +"IO_VAL_22:0" \ +"IO_VAL_23:0" \ +"IO_VAL_24:0" \ +"IO_VAL_25:0" \ +"IO_VAL_26:0" \ +"IO_VAL_27:0" \ +"IO_VAL_28:0" \ +"IO_VAL_29:0" \ +"IO_VAL_3:0" \ +"IO_VAL_30:0" \ +"IO_VAL_31:0" \ +"IO_VAL_4:0" \ +"IO_VAL_5:0" \ +"IO_VAL_6:0" \ +"IO_VAL_7:0" \ +"IO_VAL_8:0" \ +"IO_VAL_9:0" \ +"IRQ_EN_SIGNAL:true" \ +"MTIME_PRESCALER:1000" \ +"MTIME_RTC_CLOCK:false" \ +"OE_TYPE:1" \ +"PLIC_EN:false" \ +"PLIC_IRQS:8" \ +"PRG_BIT8:0" \ +"PRG_PARITY:0" \ +"READ_4BYTE_ADDR:0" \ +"READ_MIRROR:false" \ +"READ_STATUS_TYPE:false" \ +"RST_EXTPROC_DURATION:1000" \ +"RST_RECOVERY_DURATION:8" \ +"RX_FIFO:0" \ +"RX_LEGACY_MODE:0" \ +"SPI_CLK_RATIO:33" \ +"SPI_EN:false" \ +"SPI_SRC_ADDR_LOWER:0x0" \ +"SPI_SRC_ADDR_UPPER:0x0" \ +"SS_DESELECT_DURATION:8" \ +"SW_RESET_TYPE:0" \ +"SYS_TIMER_EN:false" \ +"TX_FIFO:0" \ +"UART_EN:true" \ +"UART_STATUS_FLAGS:false" \ +"UPROM_SRC_ADDR_LOWER:0x0" \ +"UPROM_SRC_ADDR_UPPER:0x0" \ +"USE_SOFT_FIFO:0" \ +"WDT_EN:false" \ +"WRITE_MIRROR:false" \ +"WRITE_PORT:1" \ +"uDMA_EN:false" } +# Exporting Component Description of MIV_ESS_C0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/MIV_RV32_C0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/MIV_RV32_C0.tcl new file mode 100644 index 0000000..cbd62b4 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/MIV_RV32_C0.tcl @@ -0,0 +1,55 @@ +# Exporting Component Description of MIV_RV32_C0 to TCL +# Family: PolarFire +# Part Number: MPF300T_ES-FCG484E +# Create and Configure the core component MIV_RV32_C0 +create_and_configure_core -core_vlnv {Microsemi:MiV:MIV_RV32:3.0.100} -component_name {MIV_RV32_C0} -params {\ +"AHB_END_ADDR_0:0xffff" \ +"AHB_END_ADDR_1:0x8fff" \ +"AHB_MASTER_TYPE:1" \ +"AHB_SLAVE_MIRROR:true" \ +"AHB_START_ADDR_0:0x0" \ +"AHB_START_ADDR_1:0x8000" \ +"APB_END_ADDR_0:0xffff" \ +"APB_END_ADDR_1:0x7fff" \ +"APB_MASTER_TYPE:1" \ +"APB_SLAVE_MIRROR:true" \ +"APB_START_ADDR_0:0x0" \ +"APB_START_ADDR_1:0x7000" \ +"AXI_END_ADDR_0:0xffff" \ +"AXI_END_ADDR_1:0x6fff" \ +"AXI_MASTER_TYPE:0" \ +"AXI_SLAVE_MIRROR:true" \ +"AXI_START_ADDR_0:0x0" \ +"AXI_START_ADDR_1:0x6000" \ +"BOOTROM_DEST_ADDR_LOWER:0x0" \ +"BOOTROM_DEST_ADDR_UPPER:0x4000" \ +"BOOTROM_PRESENT:false" \ +"BOOTROM_SRC_END_ADDR_LOWER:0x3fff" \ +"BOOTROM_SRC_END_ADDR_UPPER:0x8000" \ +"BOOTROM_SRC_START_ADDR_LOWER:0x0" \ +"BOOTROM_SRC_START_ADDR_UPPER:0x8000" \ +"DEBUGGER:true" \ +"ECC_ENABLE:false" \ +"FWD_REGS:false" \ +"GEN_DECODE_RV32:3" \ +"GEN_MUL_TYPE:2" \ +"GPR_REGS:false" \ +"INTERNAL_MTIME:true" \ +"INTERNAL_MTIME_IRQ:true" \ +"MTIME_PRESCALER:100" \ +"NUM_EXT_IRQS:6" \ +"RECONFIG_BOOTROM:false" \ +"RESET_VECTOR_ADDR_0:0x0" \ +"RESET_VECTOR_ADDR_1:0x4000" \ +"TAS_END_ADDR_0:0x7fff" \ +"TAS_END_ADDR_1:0x4000" \ +"TAS_START_ADDR_0:0x0" \ +"TAS_START_ADDR_1:0x4000" \ +"TCM_END_ADDR_0:0x7fff" \ +"TCM_END_ADDR_1:0x4000" \ +"TCM_PRESENT:true" \ +"TCM_START_ADDR_0:0x0" \ +"TCM_START_ADDR_1:0x4000" \ +"TCM_TAS_PRESENT:true" \ +"VECTORED_INTERRUPTS:false" } +# Exporting Component Description of MIV_RV32_C0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/PF_CCC_C0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/PF_CCC_C0.tcl new file mode 100644 index 0000000..4e9b1e1 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/PF_CCC_C0.tcl @@ -0,0 +1,249 @@ +# Exporting Component Description of PF_CCC_C0 to TCL +# Family: PolarFire +# Part Number: MPF300T_ES-FCG484E +# Create and Configure the core component PF_CCC_C0 +create_and_configure_core -core_vlnv {Actel:SgCore:PF_CCC:2.2.214} -component_name {PF_CCC_C0} -params {\ +"DLL_CLK_0_BANKCLK_EN:false" \ +"DLL_CLK_0_DEDICATED_EN:false" \ +"DLL_CLK_0_FABCLK_EN:false" \ +"DLL_CLK_1_BANKCLK_EN:false" \ +"DLL_CLK_1_DEDICATED_EN:false" \ +"DLL_CLK_1_FABCLK_EN:false" \ +"DLL_CLK_P_EN:false" \ +"DLL_CLK_P_OPTIONS_EN:false" \ +"DLL_CLK_REF_OPTION:DIVIDE_BY_1" \ +"DLL_CLK_REF_OPTIONS_EN:false" \ +"DLL_CLK_S_EN:false" \ +"DLL_CLK_S_OPTION:DIVIDE_BY_1" \ +"DLL_CLK_S_OPTIONS_EN:false" \ +"DLL_DELAY4:0" \ +"DLL_DYNAMIC_CODE_EN:false" \ +"DLL_DYNAMIC_RECONFIG_INTERFACE_EN:false" \ +"DLL_EXPORT_PWRDWN:false" \ +"DLL_FB_CLK:Primary" \ +"DLL_FB_EN:false" \ +"DLL_FINE_PHASE_CODE:0" \ +"DLL_IN:133" \ +"DLL_JITTER:0" \ +"DLL_MODE:PHASE_REF_MODE" \ +"DLL_ONLY_EN:false" \ +"DLL_OUT_0:1" \ +"DLL_OUT_1:1" \ +"DLL_PRIM_PHASE:90" \ +"DLL_PRIM_PHASE_CODE:0" \ +"DLL_SEC_PHASE:90" \ +"DLL_SEC_PHASE_CODE:0" \ +"DLL_SELECTED_IN:Output2" \ +"FF_REQUIRES_LOCK_EN_0:0" \ +"GL0_0_BANKCLK_USED:false" \ +"GL0_0_BYPASS:0" \ +"GL0_0_BYPASS_EN:false" \ +"GL0_0_DEDICATED_USED:false" \ +"GL0_0_DIV:12" \ +"GL0_0_DIVSTART:0" \ +"GL0_0_DYNAMIC_PH:false" \ +"GL0_0_EXPOSE_EN:false" \ +"GL0_0_FABCLK_GATED_USED:false" \ +"GL0_0_FABCLK_USED:true" \ +"GL0_0_FREQ_SEL:false" \ +"GL0_0_IS_USED:true" \ +"GL0_0_OUT_FREQ:50" \ +"GL0_0_PHASE_INDEX:0" \ +"GL0_0_PHASE_SEL:false" \ +"GL0_0_PLL_PHASE:0" \ +"GL0_1_BANKCLK_USED:false" \ +"GL0_1_BYPASS:0" \ +"GL0_1_BYPASS_EN:false" \ +"GL0_1_DEDICATED_USED:false" \ +"GL0_1_DIV:1" \ +"GL0_1_DIVSTART:0" \ +"GL0_1_DYNAMIC_PH:false" \ +"GL0_1_EXPOSE_EN:false" \ +"GL0_1_FABCLK_USED:false" \ +"GL0_1_FREQ_SEL:false" \ +"GL0_1_IS_USED:true" \ +"GL0_1_OUT_FREQ:100" \ +"GL0_1_PHASE_INDEX:0" \ +"GL0_1_PHASE_SEL:false" \ +"GL0_1_PLL_PHASE:0" \ +"GL1_0_BANKCLK_USED:false" \ +"GL1_0_BYPASS:0" \ +"GL1_0_BYPASS_EN:false" \ +"GL1_0_DEDICATED_USED:false" \ +"GL1_0_DIV:1" \ +"GL1_0_DIVSTART:0" \ +"GL1_0_DYNAMIC_PH:false" \ +"GL1_0_EXPOSE_EN:false" \ +"GL1_0_FABCLK_GATED_USED:false" \ +"GL1_0_FABCLK_USED:true" \ +"GL1_0_FREQ_SEL:false" \ +"GL1_0_IS_USED:false" \ +"GL1_0_OUT_FREQ:100" \ +"GL1_0_PHASE_INDEX:0" \ +"GL1_0_PHASE_SEL:false" \ +"GL1_0_PLL_PHASE:0" \ +"GL1_1_BANKCLK_USED:false" \ +"GL1_1_BYPASS:0" \ +"GL1_1_BYPASS_EN:false" \ +"GL1_1_DEDICATED_USED:false" \ +"GL1_1_DIV:1" \ +"GL1_1_DIVSTART:0" \ +"GL1_1_DYNAMIC_PH:false" \ +"GL1_1_EXPOSE_EN:false" \ +"GL1_1_FABCLK_USED:false" \ +"GL1_1_FREQ_SEL:false" \ +"GL1_1_IS_USED:false" \ +"GL1_1_OUT_FREQ:0" \ +"GL1_1_PHASE_INDEX:0" \ +"GL1_1_PHASE_SEL:false" \ +"GL1_1_PLL_PHASE:0" \ +"GL2_0_BANKCLK_USED:false" \ +"GL2_0_BYPASS:0" \ +"GL2_0_BYPASS_EN:false" \ +"GL2_0_DEDICATED_USED:false" \ +"GL2_0_DIV:1" \ +"GL2_0_DIVSTART:0" \ +"GL2_0_DYNAMIC_PH:false" \ +"GL2_0_EXPOSE_EN:false" \ +"GL2_0_FABCLK_GATED_USED:false" \ +"GL2_0_FABCLK_USED:true" \ +"GL2_0_FREQ_SEL:false" \ +"GL2_0_IS_USED:false" \ +"GL2_0_OUT_FREQ:100" \ +"GL2_0_PHASE_INDEX:0" \ +"GL2_0_PHASE_SEL:false" \ +"GL2_0_PLL_PHASE:0" \ +"GL2_1_BANKCLK_USED:false" \ +"GL2_1_BYPASS:0" \ +"GL2_1_BYPASS_EN:false" \ +"GL2_1_DEDICATED_USED:false" \ +"GL2_1_DIV:1" \ +"GL2_1_DIVSTART:0" \ +"GL2_1_DYNAMIC_PH:false" \ +"GL2_1_EXPOSE_EN:false" \ +"GL2_1_FABCLK_USED:false" \ +"GL2_1_FREQ_SEL:false" \ +"GL2_1_IS_USED:false" \ +"GL2_1_OUT_FREQ:0" \ +"GL2_1_PHASE_INDEX:0" \ +"GL2_1_PHASE_SEL:false" \ +"GL2_1_PLL_PHASE:0" \ +"GL3_0_BANKCLK_USED:false" \ +"GL3_0_BYPASS:0" \ +"GL3_0_BYPASS_EN:false" \ +"GL3_0_DEDICATED_USED:false" \ +"GL3_0_DIV:1" \ +"GL3_0_DIVSTART:0" \ +"GL3_0_DYNAMIC_PH:false" \ +"GL3_0_EXPOSE_EN:false" \ +"GL3_0_FABCLK_GATED_USED:false" \ +"GL3_0_FABCLK_USED:true" \ +"GL3_0_FREQ_SEL:false" \ +"GL3_0_IS_USED:false" \ +"GL3_0_OUT_FREQ:100" \ +"GL3_0_PHASE_INDEX:0" \ +"GL3_0_PHASE_SEL:false" \ +"GL3_0_PLL_PHASE:0" \ +"GL3_1_BANKCLK_USED:false" \ +"GL3_1_BYPASS:0" \ +"GL3_1_BYPASS_EN:false" \ +"GL3_1_DEDICATED_USED:false" \ +"GL3_1_DIV:1" \ +"GL3_1_DIVSTART:0" \ +"GL3_1_DYNAMIC_PH:false" \ +"GL3_1_EXPOSE_EN:false" \ +"GL3_1_FABCLK_USED:false" \ +"GL3_1_FREQ_SEL:false" \ +"GL3_1_IS_USED:false" \ +"GL3_1_OUT_FREQ:0" \ +"GL3_1_PHASE_INDEX:0" \ +"GL3_1_PHASE_SEL:false" \ +"GL3_1_PLL_PHASE:0" \ +"PLL_ALLOW_CCC_EXT_FB:false" \ +"PLL_BANDWIDTH_0:2" \ +"PLL_BANDWIDTH_1:1" \ +"PLL_BYPASS_GO_B_0:false" \ +"PLL_BYPASS_GO_B_1:false" \ +"PLL_BYPASS_POST_0:0" \ +"PLL_BYPASS_POST_0_0:false" \ +"PLL_BYPASS_POST_0_1:false" \ +"PLL_BYPASS_POST_0_2:false" \ +"PLL_BYPASS_POST_0_3:false" \ +"PLL_BYPASS_POST_1:0" \ +"PLL_BYPASS_POST_1_0:false" \ +"PLL_BYPASS_POST_1_1:false" \ +"PLL_BYPASS_POST_1_2:false" \ +"PLL_BYPASS_POST_1_3:false" \ +"PLL_BYPASS_PRE_0:0" \ +"PLL_BYPASS_PRE_0_0:false" \ +"PLL_BYPASS_PRE_0_1:false" \ +"PLL_BYPASS_PRE_0_2:false" \ +"PLL_BYPASS_PRE_0_3:false" \ +"PLL_BYPASS_PRE_1:0" \ +"PLL_BYPASS_PRE_1_0:false" \ +"PLL_BYPASS_PRE_1_1:false" \ +"PLL_BYPASS_PRE_1_2:false" \ +"PLL_BYPASS_PRE_1_3:false" \ +"PLL_BYPASS_SEL_0:0" \ +"PLL_BYPASS_SEL_0_0:false" \ +"PLL_BYPASS_SEL_0_1:false" \ +"PLL_BYPASS_SEL_0_2:false" \ +"PLL_BYPASS_SEL_0_3:false" \ +"PLL_BYPASS_SEL_1:0" \ +"PLL_BYPASS_SEL_1_0:false" \ +"PLL_BYPASS_SEL_1_1:false" \ +"PLL_BYPASS_SEL_1_2:false" \ +"PLL_BYPASS_SEL_1_3:false" \ +"PLL_DELAY_LINE_REF_FB_0:false" \ +"PLL_DELAY_LINE_REF_FB_1:false" \ +"PLL_DELAY_LINE_USED_0:false" \ +"PLL_DELAY_LINE_USED_1:false" \ +"PLL_DELAY_STEPS_0:1" \ +"PLL_DELAY_STEPS_1:1" \ +"PLL_DLL_CASCADED_EN:false" \ +"PLL_DYNAMIC_CONTROL_EN_0:true" \ +"PLL_DYNAMIC_CONTROL_EN_1:false" \ +"PLL_DYNAMIC_RECONFIG_INTERFACE_EN_0:false" \ +"PLL_DYNAMIC_RECONFIG_INTERFACE_EN_1:false" \ +"PLL_EXPORT_PWRDWN:true" \ +"PLL_EXT_MAX_ADDR_0:128" \ +"PLL_EXT_MAX_ADDR_1:128" \ +"PLL_EXT_WAVE_SEL_0:0" \ +"PLL_EXT_WAVE_SEL_1:0" \ +"PLL_FB_CLK_0:GL0_0" \ +"PLL_FB_CLK_1:GL0_1" \ +"PLL_FEEDBACK_MODE_0:Post-VCO" \ +"PLL_FEEDBACK_MODE_1:Post-VCO" \ +"PLL_IN_FREQ_0:160" \ +"PLL_IN_FREQ_1:100" \ +"PLL_INT_MODE_EN_0:false" \ +"PLL_INT_MODE_EN_1:false" \ +"PLL_LOCK_COUNT_0:0" \ +"PLL_LOCK_COUNT_1:0" \ +"PLL_LP_REQUIRES_LOCK_EN_0:false" \ +"PLL_LP_REQUIRES_LOCK_EN_1:false" \ +"PLL_PLL_CASCADED_EN:false" \ +"PLL_PLL_CASCADED_SELECTED_CLK:Output2" \ +"PLL_POSTDIVIDERADDSOFTLOGIC_0:true" \ +"PLL_REF_CLK_SEL_0:false" \ +"PLL_REF_CLK_SEL_1:false" \ +"PLL_REFDIV_0:1" \ +"PLL_REFDIV_1:1" \ +"PLL_RESET_ON_LOCK_0:true" \ +"PLL_SPREAD_MODE_0:false" \ +"PLL_SPREAD_MODE_1:false" \ +"PLL_SSM_DEPTH_0:5" \ +"PLL_SSM_DEPTH_1:5" \ +"PLL_SSM_DIVVAL_0:1" \ +"PLL_SSM_DIVVAL_1:1" \ +"PLL_SSM_FREQ_0:32" \ +"PLL_SSM_FREQ_1:32" \ +"PLL_SSM_RAND_PATTERN_0:2" \ +"PLL_SSM_RAND_PATTERN_1:2" \ +"PLL_SSMD_EN_0:false" \ +"PLL_SSMD_EN_1:false" \ +"PLL_SYNC_CORNER_PLL:false" \ +"PLL_SYNC_EN:false" \ +"PLL_VCO_MODE_0:MIN_JITTER" \ +"PLL_VCO_MODE_1:MIN_JITTER" } +# Exporting Component Description of PF_CCC_C0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/PF_INIT_MONITOR_C0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/PF_INIT_MONITOR_C0.tcl new file mode 100644 index 0000000..ba7416f --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/PF_INIT_MONITOR_C0.tcl @@ -0,0 +1,68 @@ +# Exporting Component Description of PF_INIT_MONITOR_C0 to TCL +# Family: PolarFire +# Part Number: MPF300T_ES-FCG484E +# Create and Configure the core component PF_INIT_MONITOR_C0 +create_and_configure_core -core_vlnv {Actel:SgCore:PF_INIT_MONITOR:2.0.304} -component_name {PF_INIT_MONITOR_C0} -params {\ +"BANK_0_CALIB_STATUS_ENABLED:false" \ +"BANK_0_CALIB_STATUS_SIMULATION_DELAY:1" \ +"BANK_0_RECALIBRATION_ENABLED:false" \ +"BANK_0_VDDI_STATUS_ENABLED:false" \ +"BANK_0_VDDI_STATUS_SIMULATION_DELAY:1" \ +"BANK_1_CALIB_STATUS_ENABLED:false" \ +"BANK_1_CALIB_STATUS_SIMULATION_DELAY:1" \ +"BANK_1_RECALIBRATION_ENABLED:false" \ +"BANK_1_VDDI_STATUS_ENABLED:false" \ +"BANK_1_VDDI_STATUS_SIMULATION_DELAY:1" \ +"BANK_2_CALIB_STATUS_ENABLED:false" \ +"BANK_2_CALIB_STATUS_SIMULATION_DELAY:1" \ +"BANK_2_RECALIBRATION_ENABLED:false" \ +"BANK_2_VDDI_STATUS_ENABLED:false" \ +"BANK_2_VDDI_STATUS_SIMULATION_DELAY:1" \ +"BANK_4_CALIB_STATUS_ENABLED:false" \ +"BANK_4_CALIB_STATUS_SIMULATION_DELAY:1" \ +"BANK_4_RECALIBRATION_ENABLED:false" \ +"BANK_4_VDDI_STATUS_ENABLED:false" \ +"BANK_4_VDDI_STATUS_SIMULATION_DELAY:1" \ +"BANK_5_CALIB_STATUS_ENABLED:true" \ +"BANK_5_CALIB_STATUS_SIMULATION_DELAY:1" \ +"BANK_5_RECALIBRATION_ENABLED:false" \ +"BANK_5_VDDI_STATUS_ENABLED:false" \ +"BANK_5_VDDI_STATUS_SIMULATION_DELAY:1" \ +"BANK_6_CALIB_STATUS_ENABLED:true" \ +"BANK_6_CALIB_STATUS_SIMULATION_DELAY:1" \ +"BANK_6_RECALIBRATION_ENABLED:false" \ +"BANK_6_VDDI_STATUS_ENABLED:false" \ +"BANK_6_VDDI_STATUS_SIMULATION_DELAY:1" \ +"BANK_7_CALIB_STATUS_ENABLED:true" \ +"BANK_7_CALIB_STATUS_SIMULATION_DELAY:1" \ +"BANK_7_RECALIBRATION_ENABLED:false" \ +"BANK_7_VDDI_STATUS_ENABLED:false" \ +"BANK_7_VDDI_STATUS_SIMULATION_DELAY:1" \ +"DEVICE_INIT_DONE_SIMULATION_DELAY:7" \ +"FABRIC_POR_N_SIMULATION_DELAY:1" \ +"LATCH_SC_OUTPUTS:false" \ +"PCIE_INIT_DONE_SIMULATION_DELAY:4" \ +"SHOW_BANK_0_CALIB_STATUS_ENABLED:true" \ +"SHOW_BANK_0_RECALIBRATION_ENABLED:true" \ +"SHOW_BANK_0_VDDI_STATUS_ENABLED:true" \ +"SHOW_BANK_1_CALIB_STATUS_ENABLED:true" \ +"SHOW_BANK_1_RECALIBRATION_ENABLED:true" \ +"SHOW_BANK_1_VDDI_STATUS_ENABLED:true" \ +"SHOW_BANK_2_CALIB_STATUS_ENABLED:true" \ +"SHOW_BANK_2_RECALIBRATION_ENABLED:true" \ +"SHOW_BANK_2_VDDI_STATUS_ENABLED:true" \ +"SHOW_BANK_4_CALIB_STATUS_ENABLED:true" \ +"SHOW_BANK_4_RECALIBRATION_ENABLED:true" \ +"SHOW_BANK_4_VDDI_STATUS_ENABLED:true" \ +"SHOW_BANK_5_CALIB_STATUS_ENABLED:false" \ +"SHOW_BANK_5_RECALIBRATION_ENABLED:false" \ +"SHOW_BANK_5_VDDI_STATUS_ENABLED:false" \ +"SHOW_BANK_6_CALIB_STATUS_ENABLED:false" \ +"SHOW_BANK_6_RECALIBRATION_ENABLED:false" \ +"SHOW_BANK_6_VDDI_STATUS_ENABLED:false" \ +"SHOW_BANK_7_CALIB_STATUS_ENABLED:false" \ +"SHOW_BANK_7_RECALIBRATION_ENABLED:false" \ +"SHOW_BANK_7_VDDI_STATUS_ENABLED:false" \ +"SRAM_INIT_DONE_SIMULATION_DELAY:6" \ +"USRAM_INIT_DONE_SIMULATION_DELAY:5" } +# Exporting Component Description of PF_INIT_MONITOR_C0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/PF_OSC_C0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/PF_OSC_C0.tcl new file mode 100644 index 0000000..0127560 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/PF_OSC_C0.tcl @@ -0,0 +1,12 @@ +# Exporting Component Description of PF_OSC_C0 to TCL +# Family: PolarFire +# Part Number: MPF300T_ES-FCG484E +# Create and Configure the core component PF_OSC_C0 +create_and_configure_core -core_vlnv {Actel:SgCore:PF_OSC:1.0.102} -component_name {PF_OSC_C0} -params {\ +"RCOSC_2MHZ_CLK_DIV_EN:false" \ +"RCOSC_2MHZ_GL_EN:false" \ +"RCOSC_2MHZ_NGMUX_EN:false" \ +"RCOSC_160MHZ_CLK_DIV_EN:false" \ +"RCOSC_160MHZ_GL_EN:true" \ +"RCOSC_160MHZ_NGMUX_EN:false" } +# Exporting Component Description of PF_OSC_C0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/SRC_MEM.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/SRC_MEM.tcl new file mode 100644 index 0000000..a511f16 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/SRC_MEM.tcl @@ -0,0 +1,27 @@ +# Exporting Component Description of SRC_MEM to TCL +# Family: PolarFire +# Part Number: MPF300T_ES-FCG484E +# Create and Configure the core component SRC_MEM +create_and_configure_core -core_vlnv {Actel:SystemBuilder:PF_SRAM_AHBL_AXI:1.2.108} -component_name {SRC_MEM} -params {\ +"AXI4_AWIDTH:32" \ +"AXI4_DWIDTH:32" \ +"AXI4_IDWIDTH:8" \ +"AXI4_IFTYPE_RD:T" \ +"AXI4_IFTYPE_WR:T" \ +"AXI4_WRAP_SUPPORT:F" \ +"BYTEENABLES:1" \ +"BYTE_ENABLE_WIDTH:4" \ +"B_REN_POLARITY:2" \ +"CASCADE:1" \ +"ECC_OPTIONS:0" \ +"FABRIC_INTERFACE_TYPE:0" \ +"IMPORT_FILE:miv-rv32i-systick-blinky.hex" \ +"INIT_RAM:T" \ +"LPM_HINT:0" \ +"PIPELINE_OPTIONS:1" \ +"RDEPTH:65536" \ +"RWIDTH:40" \ +"USE_NATIVE_INTERFACE:F" \ +"WDEPTH:65536" \ +"WWIDTH:40" } +# Exporting Component Description of SRC_MEM to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/build_sd_miv_ess_dgc2.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/build_sd_miv_ess_dgc2.tcl new file mode 100644 index 0000000..6f2ec03 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/components/build_sd_miv_ess_dgc2.tcl @@ -0,0 +1,175 @@ +# Creating SmartDesign BaseDesign +set sd_name {BaseDesign} +create_smartdesign -sd_name ${sd_name} + +# Disable auto promotion of pins of type 'pad' +auto_promote_pad_pins -promote_all 0 + +# Create top level Scalar Ports +sd_create_scalar_port -sd_name ${sd_name} -port_name {BOOTSTRAP_BYPASS} -port_direction {IN} +sd_create_scalar_port -sd_name ${sd_name} -port_name {RX} -port_direction {IN} +sd_create_scalar_port -sd_name ${sd_name} -port_name {SYS_RESET_REQ} -port_direction {IN} +sd_create_scalar_port -sd_name ${sd_name} -port_name {TCK} -port_direction {IN} +sd_create_scalar_port -sd_name ${sd_name} -port_name {TDI} -port_direction {IN} +sd_create_scalar_port -sd_name ${sd_name} -port_name {TMS} -port_direction {IN} +sd_create_scalar_port -sd_name ${sd_name} -port_name {TRSTB} -port_direction {IN} +sd_create_scalar_port -sd_name ${sd_name} -port_name {USER_RST} -port_direction {IN} + +sd_create_scalar_port -sd_name ${sd_name} -port_name {TDO} -port_direction {OUT} +sd_create_scalar_port -sd_name ${sd_name} -port_name {TX} -port_direction {OUT} + +sd_create_scalar_port -sd_name ${sd_name} -port_name {SCL} -port_direction {INOUT} -port_is_pad {1} +sd_create_scalar_port -sd_name ${sd_name} -port_name {SDA} -port_direction {INOUT} -port_is_pad {1} + +# Create top level Bus Ports +sd_create_bus_port -sd_name ${sd_name} -port_name {GPIO_OUT} -port_direction {OUT} -port_range {[3:0]} + + +# Add BIBUF_0 instance +sd_instantiate_macro -sd_name ${sd_name} -macro_name {BIBUF} -instance_name {BIBUF_0} +sd_invert_pins -sd_name ${sd_name} -pin_names {BIBUF_0:E} + + + +# Add BIBUF_1 instance +sd_instantiate_macro -sd_name ${sd_name} -macro_name {BIBUF} -instance_name {BIBUF_1} +sd_invert_pins -sd_name ${sd_name} -pin_names {BIBUF_1:E} + + + +# Add COREJTAGDEBUG_C0_0 instance +sd_instantiate_component -sd_name ${sd_name} -component_name {COREJTAGDEBUG_C0} -instance_name {COREJTAGDEBUG_C0_0} + + + +# Add CORERESET_PF_C0_0 instance +sd_instantiate_component -sd_name ${sd_name} -component_name {CORERESET_PF_C0} -instance_name {CORERESET_PF_C0_0} +sd_connect_pins_to_constant -sd_name ${sd_name} -pin_names {CORERESET_PF_C0_0:BANK_x_VDDI_STATUS} -value {VCC} +sd_connect_pins_to_constant -sd_name ${sd_name} -pin_names {CORERESET_PF_C0_0:BANK_y_VDDI_STATUS} -value {VCC} +sd_connect_pins_to_constant -sd_name ${sd_name} -pin_names {CORERESET_PF_C0_0:SS_BUSY} -value {GND} +sd_connect_pins_to_constant -sd_name ${sd_name} -pin_names {CORERESET_PF_C0_0:FF_US_RESTORE} -value {GND} + + + +# Add CoreTimer_C0_0 instance +sd_instantiate_component -sd_name ${sd_name} -component_name {CoreTimer_C0} -instance_name {CoreTimer_C0_0} + + + +# Add CoreTimer_C1_0 instance +sd_instantiate_component -sd_name ${sd_name} -component_name {CoreTimer_C1} -instance_name {CoreTimer_C1_0} + + + +# Add MIV_ESS_C0_0 instance +sd_instantiate_component -sd_name ${sd_name} -component_name {MIV_ESS_C0} -instance_name {MIV_ESS_C0_0} +sd_invert_pins -sd_name ${sd_name} -pin_names {MIV_ESS_C0_0:SYS_RESET_REQ} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {MIV_ESS_C0_0:I2C_IRQ} +sd_connect_pins_to_constant -sd_name ${sd_name} -pin_names {MIV_ESS_C0_0:GPIO_IN} -value {GND} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {MIV_ESS_C0_0:GPIO_INT} + + + +# Add MIV_RV32_C0_0 instance +sd_instantiate_component -sd_name ${sd_name} -component_name {MIV_RV32_C0} -instance_name {MIV_RV32_C0_0} +sd_create_pin_slices -sd_name ${sd_name} -pin_name {MIV_RV32_C0_0:MSYS_EI} -pin_slices {[0:0]} +sd_create_pin_slices -sd_name ${sd_name} -pin_name {MIV_RV32_C0_0:MSYS_EI} -pin_slices {[1:1]} +sd_connect_pins_to_constant -sd_name ${sd_name} -pin_names {MIV_RV32_C0_0:MSYS_EI[1:1]} -value {GND} +sd_create_pin_slices -sd_name ${sd_name} -pin_name {MIV_RV32_C0_0:MSYS_EI} -pin_slices {[2:2]} +sd_connect_pins_to_constant -sd_name ${sd_name} -pin_names {MIV_RV32_C0_0:MSYS_EI[2:2]} -value {GND} +sd_create_pin_slices -sd_name ${sd_name} -pin_name {MIV_RV32_C0_0:MSYS_EI} -pin_slices {[3:3]} +sd_connect_pins_to_constant -sd_name ${sd_name} -pin_names {MIV_RV32_C0_0:MSYS_EI[3:3]} -value {GND} +sd_create_pin_slices -sd_name ${sd_name} -pin_name {MIV_RV32_C0_0:MSYS_EI} -pin_slices {[4:4]} +sd_connect_pins_to_constant -sd_name ${sd_name} -pin_names {MIV_RV32_C0_0:MSYS_EI[4:4]} -value {GND} +sd_create_pin_slices -sd_name ${sd_name} -pin_name {MIV_RV32_C0_0:MSYS_EI} -pin_slices {[5:5]} +sd_connect_pins_to_constant -sd_name ${sd_name} -pin_names {MIV_RV32_C0_0:MSYS_EI[5:5]} -value {GND} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {MIV_RV32_C0_0:JTAG_TDO_DR} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {MIV_RV32_C0_0:EXT_RESETN} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {MIV_RV32_C0_0:TIME_COUNT_OUT} + + + +# Add PF_CCC_C0_0 instance +sd_instantiate_component -sd_name ${sd_name} -component_name {PF_CCC_C0} -instance_name {PF_CCC_C0_0} + + + +# Add PF_INIT_MONITOR_C0_0 instance +sd_instantiate_component -sd_name ${sd_name} -component_name {PF_INIT_MONITOR_C0} -instance_name {PF_INIT_MONITOR_C0_0} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {PF_INIT_MONITOR_C0_0:PCIE_INIT_DONE} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {PF_INIT_MONITOR_C0_0:USRAM_INIT_DONE} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {PF_INIT_MONITOR_C0_0:SRAM_INIT_DONE} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {PF_INIT_MONITOR_C0_0:XCVR_INIT_DONE} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {PF_INIT_MONITOR_C0_0:USRAM_INIT_FROM_SNVM_DONE} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {PF_INIT_MONITOR_C0_0:USRAM_INIT_FROM_UPROM_DONE} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {PF_INIT_MONITOR_C0_0:USRAM_INIT_FROM_SPI_DONE} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {PF_INIT_MONITOR_C0_0:SRAM_INIT_FROM_SNVM_DONE} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {PF_INIT_MONITOR_C0_0:SRAM_INIT_FROM_UPROM_DONE} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {PF_INIT_MONITOR_C0_0:SRAM_INIT_FROM_SPI_DONE} +sd_mark_pins_unused -sd_name ${sd_name} -pin_names {PF_INIT_MONITOR_C0_0:AUTOCALIB_DONE} + + + +# Add PF_OSC_C0_0 instance +sd_instantiate_component -sd_name ${sd_name} -component_name {PF_OSC_C0} -instance_name {PF_OSC_C0_0} + + + +# Add SRC_MEM_0 instance +sd_instantiate_component -sd_name ${sd_name} -component_name {SRC_MEM} -instance_name {SRC_MEM_0} + + + +# Add scalar net connections +sd_connect_pins -sd_name ${sd_name} -pin_names {"BIBUF_0:D" "MIV_ESS_C0_0:I2C_SDA_O" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"BIBUF_0:E" "MIV_ESS_C0_0:I2C_SDA_O_EN" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"BIBUF_0:PAD" "SDA" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"BIBUF_0:Y" "MIV_ESS_C0_0:I2C_SDA_I" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"BIBUF_1:D" "MIV_ESS_C0_0:I2C_SCL_O" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"BIBUF_1:E" "MIV_ESS_C0_0:I2C_SCL_O_EN" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"BIBUF_1:PAD" "SCL" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"BIBUF_1:Y" "MIV_ESS_C0_0:I2C_SCL_I" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"BOOTSTRAP_BYPASS" "MIV_ESS_C0_0:BOOTSTRAP_BYPASS" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"COREJTAGDEBUG_C0_0:TCK" "TCK" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"COREJTAGDEBUG_C0_0:TDI" "TDI" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"COREJTAGDEBUG_C0_0:TDO" "TDO" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"COREJTAGDEBUG_C0_0:TGT_TCK_0" "MIV_RV32_C0_0:JTAG_TCK" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"COREJTAGDEBUG_C0_0:TGT_TDI_0" "MIV_RV32_C0_0:JTAG_TDI" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"COREJTAGDEBUG_C0_0:TGT_TDO_0" "MIV_RV32_C0_0:JTAG_TDO" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"COREJTAGDEBUG_C0_0:TGT_TMS_0" "MIV_RV32_C0_0:JTAG_TMS" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"COREJTAGDEBUG_C0_0:TGT_TRSTN_0" "MIV_RV32_C0_0:JTAG_TRSTN" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"COREJTAGDEBUG_C0_0:TMS" "TMS" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"COREJTAGDEBUG_C0_0:TRSTB" "TRSTB" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CORERESET_PF_C0_0:CLK" "CoreTimer_C0_0:PCLK" "CoreTimer_C1_0:PCLK" "MIV_ESS_C0_0:PCLK" "MIV_RV32_C0_0:CLK" "PF_CCC_C0_0:OUT0_FABCLK_0" "SRC_MEM_0:HCLK" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CORERESET_PF_C0_0:EXT_RST_N" "USER_RST" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CORERESET_PF_C0_0:FABRIC_RESET_N" "CoreTimer_C0_0:PRESETn" "CoreTimer_C1_0:PRESETn" "MIV_ESS_C0_0:PRESETN" "SRC_MEM_0:HRESETN" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CORERESET_PF_C0_0:FPGA_POR_N" "PF_INIT_MONITOR_C0_0:FABRIC_POR_N" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CORERESET_PF_C0_0:INIT_DONE" "PF_INIT_MONITOR_C0_0:DEVICE_INIT_DONE" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CORERESET_PF_C0_0:PLL_LOCK" "PF_CCC_C0_0:PLL_LOCK_0" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CORERESET_PF_C0_0:PLL_POWERDOWN_B" "PF_CCC_C0_0:PLL_POWERDOWN_N_0" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CoreTimer_C0_0:TIMINT" "MIV_RV32_C0_0:MSYS_EI[0:0]" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CoreTimer_C1_0:TIMINT" "MIV_RV32_C0_0:EXT_IRQ" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"MIV_ESS_C0_0:CPU_ACCESS_DISABLE" "MIV_RV32_C0_0:TCM_CPU_ACCESS_DISABLE" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"MIV_ESS_C0_0:CPU_RESETN" "MIV_RV32_C0_0:RESETN" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"MIV_ESS_C0_0:SYS_RESET_REQ" "SYS_RESET_REQ" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"MIV_ESS_C0_0:TAS_ACCESS_DISABLE" "MIV_RV32_C0_0:TCM_TAS_ACCESS_DISABLE" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"MIV_ESS_C0_0:UART_RX" "RX" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"MIV_ESS_C0_0:UART_TX" "TX" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"PF_CCC_C0_0:REF_CLK_0" "PF_OSC_C0_0:RCOSC_160MHZ_GL" } + +# Add bus net connections +sd_connect_pins -sd_name ${sd_name} -pin_names {"GPIO_OUT" "MIV_ESS_C0_0:GPIO_OUT" } + +# Add bus interface net connections +sd_connect_pins -sd_name ${sd_name} -pin_names {"CoreTimer_C0_0:APBslave" "MIV_ESS_C0_0:APB_3_mTARGET" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"CoreTimer_C1_0:APBslave" "MIV_ESS_C0_0:APB_4_mTARGET" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"MIV_ESS_C0_0:APB_0_TARGET" "MIV_RV32_C0_0:APB_M_SLV" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"MIV_ESS_C0_0:TAS_APB_mTARGET" "MIV_RV32_C0_0:TCM_APB_SLV" } +sd_connect_pins -sd_name ${sd_name} -pin_names {"MIV_RV32_C0_0:AHBL_M_SLV" "SRC_MEM_0:AHBSlaveInterface" } + +# Re-enable auto promotion of pins of type 'pad' +auto_promote_pad_pins -promote_all 1 +# Save the smartDesign +save_smartdesign -sd_name ${sd_name} +# Generate SmartDesign BaseDesign +generate_component -component_name ${sd_name} diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/constraints/io/io_constraints.pdc b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/constraints/io/io_constraints.pdc new file mode 100644 index 0000000..3470202 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/constraints/io/io_constraints.pdc @@ -0,0 +1,515 @@ +# Microsemi I/O Physical Design Constraints file + +# User I/O Constraints file + +# Version: PolarFire v2.3 12.200.35.9 + +# Family: PolarFire , Die: MPF300T(ES) , Package: FCG484 + +# Date generated: Mon Jan 07 16:35:59 2019 + + +# +# User Locked I/O Bank Settings +# + + +# +# Unlocked I/O Bank Settings +# The I/O Bank Settings can be locked by directly editing this file +# or by making changes in the I/O Attribute Editor +# + + +# +# User Locked I/O settings +# + +# -- User PushButtons I/O -- # + +set_io -port_name {BOOTSTRAP_BYPASS} \ + -pin_name E13 \ + -fixed true \ + -io_std LVCMOS33 \ + -DIRECTION INPUT + +set_io -port_name {SYS_RESET_REQ} \ + -pin_name E14 \ + -io_std LVCMOS33 \ + -DIRECTION INPUT + +set_io -port_name USER_RST \ + -pin_name F5 \ + -fixed true \ + -io_std LVCMOS33 \ + -DIRECTION INPUT + + +# -- LEDs I/O --# + +set_io -port_name {GPIO_OUT[0]} \ + -pin_name D7 \ + -io_std LVCMOS33 + +set_io -port_name {GPIO_OUT[1]} \ + -pin_name D8 \ + -io_std LVCMOS33 + +set_io -port_name {GPIO_OUT[2]} \ + -pin_name D9 \ + -io_std LVCMOS33 + +set_io -port_name {GPIO_OUT[3]} \ + -pin_name D6 \ + -io_std LVCMOS33 + + +# -- UART RX/TX -- # + +set_io -port_name RX \ + -pin_name F16 \ + -fixed true \ + -io_std LVCMOS33 \ + -DIRECTION INPUT + + +set_io -port_name TX \ + -pin_name F17 \ + -fixed true \ + -io_std LVCMOS33 \ + -DIRECTION OUTPUT + + +# ----- I2C -----# +set_io -port_name {SCL} \ + -pin_name C6 \ + -fixed true \ + -RES_PULL Up \ + -io_std LVCMOS33 \ + -DIRECTION Inout + +set_io -port_name {SDA} \ + -pin_name C7 \ + -fixed true \ + -RES_PULL Up \ + -io_std LVCMOS33 \ + -DIRECTION Inout + +# +# Dedicated Peripheral I/O Settings +# + + +set_io -port_name TCK \ + -pin_name F8 \ + -DIRECTION INPUT + + +set_io -port_name TDI \ + -pin_name G8 \ + -DIRECTION INPUT + + +set_io -port_name TDO \ + -pin_name F6 \ + -DIRECTION OUTPUT + + +set_io -port_name TMS \ + -pin_name F7 \ + -DIRECTION INPUT + + +set_io -port_name TRSTB \ + -pin_name G7 \ + -DIRECTION INPUT + + +# Microsemi I/O Physical Design Constraints file + +# User I/O Constraints file + +# Version: PolarFire v2.3 12.200.35.9 + +# Family: PolarFire , Die: MPF300T_ES , Package: FCG484 + +# Date generated: Sun Jan 13 21:06:20 2019 +# +# Unlocked I/O settings +# The I/Os in this section are unplaced or placed but are not locked +# the other listed attributes have been applied +# + +#set_io -port_name CLK1_50M \ + -pin_name R1 \ + -fixed true \ + -io_std LVCMOS25 \ + -DIRECTION INPUT +#set_io -port_name REF_CLK_0 \ + -io_std LVCMOS18 \ + -DIRECTION INPUT + +# +# User Locked I/O settings +# + +#set_io -port_name AND1_Y \ + -pin_name A3 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[0]} \ + -pin_name U5 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[1]} \ + -pin_name U4 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[2]} \ + -pin_name V4 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[3]} \ + -pin_name W3 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[4]} \ + -pin_name V5 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[5]} \ + -pin_name W4 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[6]} \ + -pin_name Y3 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[7]} \ + -pin_name AA3 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[8]} \ + -pin_name Y4 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[9]} \ + -pin_name Y5 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[10]} \ + -pin_name AA2 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[11]} \ + -pin_name AB2 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[12]} \ + -pin_name V6 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[13]} \ + -pin_name W6 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[14]} \ + -pin_name AB3 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {BA[0]} \ + -pin_name V7 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {BA[1]} \ + -pin_name Y6 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {BA[2]} \ + -pin_name U7 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name CAS_N \ + -pin_name AA5 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name CK0 \ + -pin_name V2 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name CK0_N \ + -pin_name W2 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name CKE \ + -pin_name W8 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name CS_N \ + -pin_name W7 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name CTRLR_READY \ + -pin_name D6 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name DEVICE_INIT_DONE \ + -pin_name A13 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {DM[0]} \ + -pin_name Y9 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {DM[1]} \ + -pin_name R15 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {DQS[0]} \ + -pin_name T10 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQS[1]} \ + -pin_name R13 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQS_N[0]} \ + -pin_name U10 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQS_N[1]} \ + -pin_name T12 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[0]} \ + -pin_name T7 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[1]} \ + -pin_name T8 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[2]} \ + -pin_name U8 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[3]} \ + -pin_name U9 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[4]} \ + -pin_name R10 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[5]} \ + -pin_name V9 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[6]} \ + -pin_name V10 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[7]} \ + -pin_name W9 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[8]} \ + -pin_name V14 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[9]} \ + -pin_name U14 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[10]} \ + -pin_name R12 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[11]} \ + -pin_name T11 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[12]} \ + -pin_name U15 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[13]} \ + -pin_name T13 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[14]} \ + -pin_name U13 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[15]} \ + -pin_name T15 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name ODT \ + -pin_name AA7 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name PLL_LOCK_0 \ + -pin_name A12 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name RAS_N \ + -pin_name AA6 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name RESET_N \ + -pin_name AB7 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name SHIELD0 \ + -pin_name R9 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name SHIELD1 \ + -pin_name V15 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name WE_N \ + -pin_name AB5 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name reset_sync_0 \ + -pin_name A16 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name reset_sync_1 \ + -pin_name A15 \ + -fixed true \ + -DIRECTION OUTPUT + + + +# +# Dedicated Peripheral I/O Settings +# + + +# +# Unlocked I/O settings +# The I/Os in this section are unplaced or placed but are not locked +# the other listed attributes have been applied +# + + +# +#Ports using Dedicated Pins + +# + diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/constraints/io_jtag_constraints.sdc b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/constraints/io_jtag_constraints.sdc new file mode 100644 index 0000000..d8e81f0 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/constraints/io_jtag_constraints.sdc @@ -0,0 +1,7 @@ +create_clock -name { TCK } \ +-period 166.67 \ +-waveform { 0 83.33 } \ +[ get_ports { TCK } ] + +# JTAG and Mi-V clocks are independent - adding asynchronous clock group +set_clock_groups -name {async1} -asynchronous -group [ get_clocks { PF_CCC_C0_0/PF_CCC_C0_0/pll_inst_0/OUT0 } ] -group [ get_clocks { TCK } ] \ No newline at end of file diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/hex/miv-ess-blinky-tcm.hex b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/hex/miv-ess-blinky-tcm.hex new file mode 100644 index 0000000..51b15fe --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/hex/miv-ess-blinky-tcm.hex @@ -0,0 +1,482 @@ +:100000006F0010016F00C00700000000000000003A +:100010006F00C010000000000000000000000000A1 +:100020006F00401800000000000000000000000009 +:100030006F00C01F00000000000000000000000072 +:10004000000000006F0000276F00402F000000003C +:1000500000000000000000000000000000000000A0 +:10006000000000006F0000366F00403E6F008046C9 +:100070006F00C04E6F0000576F00405F6F008067D9 +:10008000130101F81300000013000000130000002A +:1000900023201100232221002324310023264100A4 +:1000A00023285100232A6100232C7100232E810074 +:1000B000232091022322A1022324B1022326C1027C +:1000C0002328D102232AE102232CF102232E01034B +:1000D0002320110523222105232431052326410550 +:1000E00023285105232A6105232C7105232E810520 +:1000F000232091072322A1072324B1072326C10728 +:100100002328D107232AE107232CF1077325203464 +:10011000F3251034EF00D0226F004066130101F880 +:100120002320110023222100232431002326410013 +:1001300023285100232A6100232C7100232E8100E3 +:10014000232091022322A1022324B1022326C102EB +:100150002328D102232AE102232CF102232E0103BA +:1001600023201105232221052324310523264105BF +:1001700023285105232A6105232C7105232E81058F +:10018000232091072322A1072324B1072326C10797 +:100190002328D107232AE107232CF107EF0090172A +:1001A0006F00C05D130101F82320110023222100FC +:1001B000232431002326410023285100232A6100F3 +:1001C000232C7100232E8100232091022322A102DF +:1001D0002324B1022326C1022328D102232AE102CB +:1001E000232CF102232E01032320110523222105B4 +:1001F000232431052326410523285105232A61059F +:10020000232C7105232E8105232091072322A1078A +:100210002324B1072326C1072328D107232AE10776 +:10022000232CF107EF0050066F004055130101F831 +:100230002320110023222100232431002326410002 +:1002400023285100232A6100232C7100232E8100D2 +:10025000232091022322A1022324B1022326C102DA +:100260002328D102232AE102232CF102232E0103A9 +:1002700023201105232221052324310523264105AE +:1002800023285105232A6105232C7105232E81057E +:10029000232091072322A1072324B1072326C10786 +:1002A0002328D107232AE107232CF107EF10806AC6 +:1002B0006F00C04C130101F82320110023222100FC +:1002C000232431002326410023285100232A6100E2 +:1002D000232C7100232E8100232091022322A102CE +:1002E0002324B1022326C1022328D102232AE102BA +:1002F000232CF102232E01032320110523222105A3 +:10030000232431052326410523285105232A61058D +:10031000232C7105232E8105232091072322A10779 +:100320002324B1072326C1072328D107232AE10765 +:10033000232CF107EF10C0636F004044130101F854 +:1003400023201100232221002324310023264100F1 +:1003500023285100232A6100232C7100232E8100C1 +:10036000232091022322A1022324B1022326C102C9 +:100370002328D102232AE102232CF102232E010398 +:10038000232011052322210523243105232641059D +:1003900023285105232A6105232C7105232E81056D +:1003A000232091072322A1072324B1072326C10775 +:1003B0002328D107232AE107232CF107EF10005D42 +:1003C0006F00C03B130101F82320110023222100FC +:1003D000232431002326410023285100232A6100D1 +:1003E000232C7100232E8100232091022322A102BD +:1003F0002324B1022326C1022328D102232AE102A9 +:10040000232CF102232E0103232011052322210591 +:10041000232431052326410523285105232A61057C +:10042000232C7105232E8105232091072322A10768 +:100430002324B1072326C1072328D107232AE10754 +:10044000232CF107EF1040566F004033130101F8E1 +:1004500023201100232221002324310023264100E0 +:1004600023285100232A6100232C7100232E8100B0 +:10047000232091022322A1022324B1022326C102B8 +:100480002328D102232AE102232CF102232E010387 +:10049000232011052322210523243105232641058C +:1004A00023285105232A6105232C7105232E81055C +:1004B000232091072322A1072324B1072326C10764 +:1004C0002328D107232AE107232CF107EF10804FBF +:1004D0006F00C02A130101F82320110023222100FC +:1004E000232431002326410023285100232A6100C0 +:1004F000232C7100232E8100232091022322A102AC +:100500002324B1022326C1022328D102232AE10297 +:10051000232CF102232E0103232011052322210580 +:10052000232431052326410523285105232A61056B +:10053000232C7105232E8105232091072322A10757 +:100540002324B1072326C1072328D107232AE10743 +:10055000232CF107EF10C0486F004022130101F86F +:1005600023201100232221002324310023264100CF +:1005700023285100232A6100232C7100232E81009F +:10058000232091022322A1022324B1022326C102A7 +:100590002328D102232AE102232CF102232E010376 +:1005A000232011052322210523243105232641057B +:1005B00023285105232A6105232C7105232E81054B +:1005C000232091072322A1072324B1072326C10753 +:1005D0002328D107232AE107232CF107EF1000423B +:1005E0006F00C019130101F82320110023222100FC +:1005F000232431002326410023285100232A6100AF +:10060000232C7100232E8100232091022322A1029A +:100610002324B1022326C1022328D102232AE10286 +:10062000232CF102232E010323201105232221056F +:10063000232431052326410523285105232A61055A +:10064000232C7105232E8105232091072322A10746 +:100650002324B1072326C1072328D107232AE10732 +:10066000232CF107EF10403B6F004011130101F8FC +:1006700023201100232221002324310023264100BE +:1006800023285100232A6100232C7100232E81008E +:10069000232091022322A1022324B1022326C10296 +:1006A0002328D102232AE102232CF102232E010365 +:1006B000232011052322210523243105232641056A +:1006C00023285105232A6105232C7105232E81053A +:1006D000232091072322A1072324B1072326C10742 +:1006E0002328D107232AE107232CF107EF108034B8 +:1006F0006F00C008130101F82320110023222100FC +:10070000232431002326410023285100232A61009D +:10071000232C7100232E8100232091022322A10289 +:100720002324B1022326C1022328D102232AE10275 +:10073000232CF102232E010323201105232221055E +:10074000232431052326410523285105232A610549 +:10075000232C7105232E8105232091072322A10735 +:100760002324B1072326C1072328D107232AE10721 +:10077000232CF107EF10C02D6F00400083200100F3 +:1007800003214100832181000322C1008322010152 +:1007900003234101832381010324C1018324010236 +:1007A00003254102832581020326C102832601031A +:1007B00003274103832781030328C10383280104FE +:1007C0000329410483298104032AC104832A0105E2 +:1007D000032B4105832B8105032CC105832C0106C6 +:1007E000032D4106832D8106032EC106832E0107AA +:1007F000032F4107832F8107130101087300203065 +:0408000000000000F4 +:10081000735000307350403097F0FFFF9380807E1C +:10082000F322103093F2120063960202F32250304A +:1008300093F2320013031000639E6200F3225030E3 +:1008400093F2C2FF17F3FFFF1303037C6398620464 +:100850006F00000197F2FFFF9382027B739052308A +:100860001717000013070759971700009387875839 +:1008700017180000130808596308F700638607017A +:1008800097000000E780400997210000938181D6FE +:10089000EF000001138101C86F0080517300100048 +:1008A0009382000093870183138801886384070182 +:1008B000EF0040049387018113880183638C070153 +:1008C000EF00400393870188138801886384070140 +:1008D000EF00400213870181938701811388018112 +:1008E0006306F70063840701EF00C00293800200F3 +:1008F000678000006364F804B368F80093F8380078 +:10090000634E100323A0070093874700E3CC07FF43 +:10091000678000006364F802B368F80093F8380059 +:10092000634E10018328070023A017019387470017 +:1009300013074700E3C807FF6F0080006F00000047 +:1009400067800000130101FF2326810013040101C9 +:10095000B767000003A70702B76700001377D7FF48 +:1009600023A0E702130000000324C10013010101CA +:1009700067800000130101FE232E81001304010291 +:10098000F36704302326F4FE130000000324C101A2 +:100990001301010267800000130101FD23261102EB +:1009A0002324810223222103232031031304010382 +:1009B000232EA4FC930710002326F4FEB757000251 +:1009C00083A70700938507000325C4FDEF10C01D12 +:1009D000930705001389070093090000971700008B +:1009E0009387474223A0270123A2370197170000CE +:1009F0009387474183A6070003A747009387060014 +:100A0000B3E7E70063820706B7C70002938787FF53 +:100A100003A8470083A70700171700001307873EA6 +:100A2000832507000326470037450002B386B70039 +:100A300093880600B3B8F8003307C800B387E8000E +:100A40001387070093870600130807002320F5008B +:100A50002322050193070008F3A747302324F4FE5F +:100A6000EFF05FF1232604FE8327C4FE1385070001 +:100A70008320C10203248102032941028329010248 +:100A80001301010367800000130101FE232E1100F2 +:100A9000232C81001304010293070008F3B74730A9 +:100AA0002326F4FEEF00907CB7C70002938787FFF0 +:100AB00003A8470083A70700171700001307873410 +:100AC000832507000326470037450002B386B70099 +:100AD00093880600B3B8F8003307C800B387E8006E +:100AE0001387070093870600130807002320F500EB +:100AF0002322050193070008F3A747302324F4FEBF +:100B0000130000008320C1010324810113010102AD +:100B100067800000130101FF2326110023248100B8 +:100B200013040101EF009060EFF0DFE1130000001B +:100B30008320C100032481001301010167800000AC +:100B4000130101FB2326110423248104130401054E +:100B5000232EA4FA232CB4FA8327C4FB63D2070202 +:100B60000327C4FBB707008093C7F7FF3377F7006D +:100B70009307B0006316F700EF00D05D6F0000220E +:100B80008327C4FB63D207020327C4FBB707008097 +:100B900093C7F7FF3377F700930730006316F7002A +:100BA000EFF05FF76F00801F8327C4FB63D207025B +:100BB0000327C4FBB707008093C7F7FF3377F7001D +:100BC000930770006316F700EFF01FEC6F00001D35 +:100BD0008327C4FB63D207020327C4FBB707008047 +:100BE00093C7F7FF3377F700930780016316F70089 +:100BF000EF00905B6F00801A8327C4FB63D207026B +:100C00000327C4FBB707008093C7F7FF3377F700CC +:100C1000930790016316F700EF00D05A6F00001899 +:100C20008327C4FB63D207020327C4FBB7070080F6 +:100C300093C7F7FF3377F7009307A0016316F70018 +:100C4000EF00105A6F0080158327C4FB63D20702A0 +:100C50000327C4FBB707008093C7F7FF3377F7007C +:100C60009307B0016316F700EF0050596F000013AF +:100C70008327C4FB63D207020327C4FBB7070080A6 +:100C800093C7F7FF3377F7009307C0016316F700A8 +:100C9000EF0090586F0080108327C4FB63D20702D7 +:100CA0000327C4FBB707008093C7F7FF3377F7002C +:100CB0009307D0016316F700EF00D0576F00000EC6 +:100CC0008327C4FB63D207020327C4FBB707008056 +:100CD00093C7F7FF3377F7009307E0016316F70038 +:100CE000EF0010576F00800B8327C4FB63D207020D +:100CF0000327C4FBB707008093C7F7FF3377F700DC +:100D0000930700016316F700EF0090466F0000099B +:100D10008327C4FB63D207020327C4FBB707008005 +:100D200093C7F7FF3377F700930710016316F700B7 +:100D3000EF00D0456F008006F32740342326F4FEF1 +:100D40008327C4FE2324F4FEF32730342322F4FE49 +:100D5000832744FE2320F4FEF3275030232EF4FC97 +:100D60008327C4FD232CF4FCF3270034232AF4FC4E +:100D7000832744FD2328F4FCF32700302326F4FCCA +:100D80008327C4FC2324F4FCF32710342322F4FC2F +:100D9000832744FC2320F4FC7300100013000000A0 +:100DA0008320C1040324810413010105678000002E +:100DB000130101FF232611002324810013040101E4 +:100DC000EF009050130000008320C1000324810035 +:100DD0001301010167800000130101FF2326810038 +:100DE00013040101130000000324C10013010101D9 +:100DF00067800000130101FF2326110023248100D6 +:100E000013040101EFF01FB7130000008320C1009D +:100E10000324810013010101678000002320B50035 +:100E2000678000000325050067800000138E060020 +:100E3000331EBE00337ECE0003230500930306005D +:100E400093C3F3FF337373003363C301232065003F +:100E500067800000032505003375C5003355B500D4 +:100E6000678000002310B5006780000003150500AF +:100E700067800000138E0600331EBE00337ECE0056 +:100E8000031305009303060093C3F3FF337373004A +:100E90003363C3012310650067800000031505005C +:100EA0003375C5003355B500678000002300B500D9 +:100EB000678000000305050067800000138E0600B0 +:100EC000331EBE00337ECE000303050093030600ED +:100ED00093C3F3FF337373003363C30123006500CF +:100EE00067800000030505003375C5003355B50064 +:100EF00067800000130101FD2326110223248102D3 +:100F000013040103232EA4FC232CB4FC9307060036 +:100F100013870600231BF4FC93070700A30AF4FCC5 +:100F20008327C4FD6394070073001000034754FD3A +:100F30009307700063F4E70073001000035764FD2B +:100F4000B72700006364F700730010008327C4FD17 +:100F500063840716034754FD9307700063EEE7149C +:100F6000035764FDB72700006378F714832784FDD7 +:100F700013878700835764FD93F7F70F9385070066 +:100F800013050700EFF09FF2832784FD9386C700C7 +:100F9000034754FD835764FD93D7574093F7877FEA +:100FA000B367F7009385070013850600EFF01FF085 +:100FB0008327C4FD032784FD23A0E7008327C4FD06 +:100FC00083A707009387870013850700EFF09FEE44 +:100FD000930705002316F4FE8327C4FD83A70700AB +:100FE0009387C70013850700EFF0DFEC9307050038 +:100FF000A305F4FE8347B4FE93F787FF2305F4FEB1 +:101000008347A4FE9397070193D70701939757004F +:1010100013970701135707018357C4FEB367F700FF +:101020002316F4FE8347B4FE93F77700A305F4FE7E +:101030000357C4FE835764FD6304F7007300100078 +:101040000347B4FE834754FD6304F70073001000A8 +:101050008327C4FD83A70700938707011385070033 +:10106000EFF05FE59307050093F72700A307F4FE71 +:101070006F0080038327C4FD83A707009387470081 +:1010800013850700EFF01FE38327C4FD83A7070044 +:101090009387070113850700EFF0DFE19307050051 +:1010A00093F72700A307F4FE8347F4FEE39407FCBD +:1010B0008327C4FD23820700130000008320C102A0 +:1010C000032481021301010367800000130101FD65 +:1010D00023261102232481022322910213040103F7 +:1010E000232EA4FC232CB4FC232AC4FC232404FEBA +:1010F0008327C4FD6394070073001000832784FDD9 +:101100006394070073001000832744FD6394070075 +:10111000730010008327C4FD6386070E832784FDB8 +:101120006382070E832744FD638E070C232404FE8D +:101130008327C4FD83A70700938707011385070052 +:10114000EFF05FD793070500A303F4FE8327C4FDE8 +:1011500003C74700834774FEB367F70013F7F70F21 +:101160008327C4FD2382E700834774FE93F727009B +:10117000A307F4FE6F00C0078327C4FD83A7070001 +:1011800093864700032784FD832784FEB304F7007A +:1011900013850600EFF01FD2930705002380F400AB +:1011A000832784FE938717002324F4FE8327C4FD3E +:1011B00083A707009387070113850700EFF09FCFF0 +:1011C00093070500A303F4FE8327C4FD03C747006C +:1011D000834774FEB367F70013F7F70F8327C4FD47 +:1011E0002382E700834774FE93F72700A307F4FEEA +:1011F0008347F4FE63880700032784FE832744FDAA +:10120000E36CF7F6832784FE138507008320C10271 +:10121000032481028324410213010103678000003B +:10122000130101FD2326110223248102130401036B +:10123000232EA4FC232CB4FC8327C4FD6394070055 +:1012400073001000832784FD63940700730010006F +:101250008327C4FD63800708832784FD638C07060A +:10126000232604FE6F00C0058327C4FD83A7070063 +:101270009387070113850700EFF0DFC3930705008D +:1012800093F71700A305F4FE8347B4FEE38E07FC33 +:101290008327C4FD83A60700032784FD8327C4FE9C +:1012A000B307F70083C7070093850700138506007F +:1012B000EFF0DFBF8327C4FE938717002326F4FED9 +:1012C000032784FD8327C4FEB307F70083C7070005 +:1012D000E39C07F8130000008320C102032481026D +:1012E0001301010367800000130101FD2326110291 +:1012F0002324810213040103232EA4FC232CB4FC19 +:10130000232AC4FCA30704FE832784FD2324F4FEC0 +:101310008327C4FD032784FD23A0E7008327C4FDA2 +:10132000032744FD23A2E700A30704FE832784FDCF +:101330002324F4FE6F00800293050000032584FE41 +:10134000EFF0DFB6832784FE938747002324F4FE63 +:101350008347F4FE93871700A307F4FE0347F4FEC8 +:101360009307F001E3FAE7FC8327C4FD83A7470056 +:10137000130710006386E702638207061307200045 +:101380006390E70C8327C4FD83A7070093870708B2 +:101390009305F0FF13850700EFF05FA86F00C00A08 +:1013A0008327C4FD83A7070013870708B707010039 +:1013B0009385F7FF13050700EFF0DFAA8327C4FD2D +:1013C00083A7070013874708B70701009385F7FF36 +:1013D00013050700EFF01FA96F0000078327C4FD66 +:1013E00083A70700938707089305F00F138507006D +:1013F000EFF0DFAB8327C4FD83A70700938747087F +:101400009305F00F13850700EFF05FAA8327C4FD53 +:1014100083A70700938787089305F00F13850700BC +:10142000EFF0DFA88327C4FD83A707009387C708D1 +:101430009305F00F13850700EFF05FA76F00C00062 +:101440007300100013000000130000008320C1028D +:10145000032481021301010367800000130101FED0 +:10146000232E1100232C8100130401022326A4FE45 +:101470002324B4FE8327C4FE83A74700130710006C +:101480006386E702638C0706130720006390E7106A +:101490008327C4FE83A707009387070A832584FE5A +:1014A00013850700EFF09F976F00C00E8327C4FEDF +:1014B00083A707009387070A032784FE13170701F2 +:1014C000135707019305070013850700EFF09F9955 +:1014D0008327C4FE83A707001387470A832784FE58 +:1014E00093D707019397070193D7070193850700C7 +:1014F00013050700EFF01F976F00C0098327C4FE94 +:1015000083A707009387070A032784FE1377F70F43 +:101510009305070013850700EFF05F998327C4FE4A +:1015200083A707001387470A832784FE93D7870082 +:1015300093F7F70F9385070013050700EFF01F9748 +:101540008327C4FE83A707001387870A832784FEA7 +:1015500093D7070193F7F70F93850700130507004B +:10156000EFF0DF948327C4FE83A707001387C70A21 +:10157000832784FE93D7870193F7F70F938507009E +:1015800013050700EFF09F926F00C000730010007A +:10159000130000000325C4FEEF00001A1307050026 +:1015A000832784FE6384E7007300100013000000AB +:1015B0008320C1010324810113010102678000001F +:1015C000130101FD232611022324810213040103C8 +:1015D000232EA4FC232604FE8327C4FD83A74700F3 +:1015E000130710006386E7026380070813072000D3 +:1015F0006394E7128327C4FD83A707009387070935 +:1016000013850700EFF01F822326A4FE6F00401110 +:101610008327C4FD83A70700938707091385070065 +:10162000EFF0DF8493070500138707008327C4FECC +:10163000B3E7E7002326F4FE8327C4FD83A7070052 +:101640009387470913850700EFF05F829307050032 +:1016500093970701138707008327C4FEB3E7E700CA +:101660002326F4FE6F00C00B8327C4FD83A7070069 +:101670009387070913850700EFF0DF8393070500C1 +:10168000138707008327C4FEB3E7E7002326F4FE91 +:101690008327C4FD83A707009387470913850700A5 +:1016A000EFF05F819307050093978700138707008A +:1016B0008327C4FEB3E7E7002326F4FE8327C4FD97 +:1016C00083A707009387870913850700EFF08FFE34 +:1016D0009307050093970701138707008327C4FE2C +:1016E000B3E7E7002326F4FE8327C4FD83A70700A2 +:1016F0009387C70913850700EFF0CFFB9307050019 +:1017000093978701138707008327C4FEB3E7E70099 +:101710002326F4FE6F00C0007300100013000000C9 +:101720008327C4FE138507008320C102032481029E +:101730001301010367800000130101FD232611023C +:101740002324810213040103232EA4FC232604FE78 +:101750008327C4FD83A74700130710006386E702B1 +:1017600063800708130720006394E7128327C4FDF2 +:1017700083A707009387070A13850700EFF08FEA16 +:101780002326A4FE6F0040118327C4FD83A7070012 +:101790009387070A13850700EFF04FED93070500C5 +:1017A000138707008327C4FEB3E7E7002326F4FE70 +:1017B0008327C4FD83A707009387470A1385070083 +:1017C000EFF0CFEA9307050093970701138707000F +:1017D0008327C4FEB3E7E7002326F4FE6F00C00BA7 +:1017E0008327C4FD83A707009387070A1385070093 +:1017F000EFF0CFE793070500138707008327C4FEA8 +:10180000B3E7E7002326F4FE8327C4FD83A7070080 +:101810009387470A13850700EFF04FE5930705000C +:1018200093978700138707008327C4FEB3E7E70079 +:101830002326F4FE8327C4FD83A707009387870A26 +:1018400013850700EFF08FE29307050093970701D8 +:10185000138707008327C4FEB3E7E7002326F4FEBF +:101860008327C4FD83A707009387C70A1385070052 +:10187000EFF0CFDF930705009397870113870700E9 +:101880008327C4FEB3E7E7002326F4FE6F00C00001 +:1018900073001000130000008327C4FE13850700A7 +:1018A0008320C10203248102130101036780000029 +:1018B000130101FD2326810213040103232EA4FC3E +:1018C000F32740302326F4FE8327C4FE2324F4FEAE +:1018D000032784FE8327C4FDB367F7002324F4FEA7 +:1018E000832784FEF3A747302322F4FE1300000071 +:1018F0000324C1021301010367800000130101FFEB +:101900002326810013040101B767000003A7070223 +:10191000B76700001377D7FF23A0E702130000008A +:101920000324C1001301010167800000130101FFBE +:10193000232611002324810013040101EFF01FFC72 +:10194000130000008320C100032481001301010162 +:1019500067800000130101FF2326810013040101A9 +:10196000130000000324C10013010101678000007F +:10197000130101FF2326810013040101130000005D +:101980000324C1001301010167800000130101FF5E +:101990002326810013040101130000000324C10069 +:1019A0001301010167800000130101FF232681005C +:1019B00013040101130000000324C10013010101FD +:1019C00067800000130101FF232681001304010139 +:1019D000130000000324C10013010101678000000F +:1019E000130101FF232681001304010113000000ED +:1019F0000324C1001301010167800000130101FFEE +:101A00002326810013040101130000000324C100F8 +:101A10001301010167800000130101FF23268100EB +:101A200013040101130000000324C100130101018C +:101A300067800000130101FF2326810013040101C8 +:101A4000130000000324C10013010101678000009E +:101A5000130101FF2326810013040101130000007C +:101A60000324C1001301010167800000130101FF7D +:101A70002326110023248100130401019387C181CF +:101A800083A7070013C7F7009387C18123A0E7004E +:101A90009387C18183A707009385070013858187FA +:101AA000EFF0DF9B97050000938585321385018752 +:101AB000EFF00FF7130000008320C1000324810022 +:101AC0001301010167800000130101FF23261100AB +:101AD0002324810013040101930610001306A001C2 +:101AE000B705007113850187EFF0CFC0970700009D +:101AF0009387473083A707009385070013850187E5 +:101B0000EFF00FF213062000B705007513858187EB +:101B1000EFF08FFD9305000013858187EFF01F9490 +:101B2000EFF04FADB717003F13850780EFF05FD898 +:101B3000B7F7FA0213850708EFE01FE61306000463 +:101B4000970500009385052E13850187EFF00FD8C8 +:101B50009307050013F7F70F938781812380E70030 +:101B60009387818183C7070093F7F70FE38807FC0A +:101B7000970500009385052B13850187EFF04FEA49 +:101B8000938781812380070013858187EFF05FA30E +:101B9000130705009387018223A0E7006FF01FFA67 +:101BA0006340050663C60506138605009305050018 +:101BB0001305F0FF630C060293061000637AB6006B +:101BC0006358C0001316160093961600E36AB6FE1B +:101BD0001305000063E6C500B385C5403365D50035 +:101BE00093D6160013561600E39606FE6780000093 +:101BF00093820000EFF05FFB138505006780020011 +:101C00003305A04063D80500B305B0406FF0DFF99D +:101C1000B305B04093820000EFF01FF93305A040F8 +:101C2000678002009382000063CA0500634C0500D0 +:101C3000EFF09FF71385050067800200B305B04001 +:101C4000E35805FE3305A040EFF01FF63305B04022 +:101C5000678002000000000000000000000000009B +:101C60000D0A2A2A2A2A2A2A2A2A2A2A2A2A2A2A11 +:101C70002A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2AC4 +:101C80002A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2AB4 +:101C90002A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2AA4 +:101CA0002A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A94 +:101CB0000D0A0A2A2A2A2A2A2A2A2A2A2A2A2A2AE1 +:101CC0002A2A2A2A2A2A2A202020204D692D562015 +:101CD00053797374656D2054696D657220426C6927 +:101CE0006E6B79204578616D706C65202020202A0C +:101CF0002A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A44 +:101D00002A2A2A2A2A2A0D0A0A2A2A2A2A2A2A2A90 +:101D10002A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A23 +:101D20002A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A13 +:101D30002A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A03 +:101D40002A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2AF3 +:101D50002A2A2A2A2A2A2A0D0A0D0A4F6273657234 +:101D6000766520746865204C45447320626C696E0A +:101D70006B696E67206F6E2074686520626F617298 +:101D8000642E20546865204C45442070617474654D +:101D9000726E206368616E6765732065766572791F +:101DA0002074696D6520612073797374656D20748A +:101DB000696D657220696E74657272757074206FDA +:101DC00063637572732E0D0A000000000D0A496EE0 +:101DD0007465726E616C2053797374656D205469FB +:101DE0006D657220496E74657272757074000000C2 +:101DF000601C004000000000000000000000000027 +:0400000540000000B7 +:00000001FF diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/hex/miv-rv32i-systick-blinky.hex b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/hex/miv-rv32i-systick-blinky.hex new file mode 100644 index 0000000..de7791b --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/hex/miv-rv32i-systick-blinky.hex @@ -0,0 +1,436 @@ +:100000006F0010016F00C00700000000000000003A +:100010006F00C010000000000000000000000000A1 +:100020006F00401800000000000000000000000009 +:100030006F00C01F00000000000000000000000072 +:10004000000000006F0000276F00402F000000003C +:1000500000000000000000000000000000000000A0 +:10006000000000006F0000366F00403E6F008046C9 +:100070006F00C04E6F0000576F00405F6F008067D9 +:10008000130101F81300000013000000130000002A +:1000900023201100232221002324310023264100A4 +:1000A00023285100232A6100232C7100232E810074 +:1000B000232091022322A1022324B1022326C1027C +:1000C0002328D102232AE102232CF102232E01034B +:1000D0002320110523222105232431052326410550 +:1000E00023285105232A6105232C7105232E810520 +:1000F000232091072322A1072324B1072326C10728 +:100100002328D107232AE107232CF1077325203464 +:10011000F3251034EF00D01B6F004066130101F887 +:100120002320110023222100232431002326410013 +:1001300023285100232A6100232C7100232E8100E3 +:10014000232091022322A1022324B1022326C102EB +:100150002328D102232AE102232CF102232E0103BA +:1001600023201105232221052324310523264105BF +:1001700023285105232A6105232C7105232E81058F +:10018000232091072322A1072324B1072326C10797 +:100190002328D107232AE107232CF107EF00D010F1 +:1001A0006F00C05D130101F82320110023222100FC +:1001B000232431002326410023285100232A6100F3 +:1001C000232C7100232E8100232091022322A102DF +:1001D0002324B1022326C1022328D102232AE102CB +:1001E000232CF102232E01032320110523222105B4 +:1001F000232431052326410523285105232A61059F +:10020000232C7105232E8105232091072322A1078A +:100210002324B1072326C1072328D107232AE10776 +:10022000232CF107EF00D0016F004055130101F8B6 +:100230002320110023222100232431002326410002 +:1002400023285100232A6100232C7100232E8100D2 +:10025000232091022322A1022324B1022326C102DA +:100260002328D102232AE102232CF102232E0103A9 +:1002700023201105232221052324310523264105AE +:1002800023285105232A6105232C7105232E81057E +:10029000232091072322A1072324B1072326C10786 +:1002A0002328D107232AE107232CF107EF00900D23 +:1002B0006F00C04C130101F82320110023222100FC +:1002C000232431002326410023285100232A6100E2 +:1002D000232C7100232E8100232091022322A102CE +:1002E0002324B1022326C1022328D102232AE102BA +:1002F000232CF102232E01032320110523222105A3 +:10030000232431052326410523285105232A61058D +:10031000232C7105232E8105232091072322A10779 +:100320002324B1072326C1072328D107232AE10765 +:10033000232CF107EF0090056F004044130101F8F2 +:1003400023201100232221002324310023264100F1 +:1003500023285100232A6100232C7100232E8100C1 +:10036000232091022322A1022324B1022326C102C9 +:100370002328D102232AE102232CF102232E010398 +:10038000232011052322210523243105232641059D +:1003900023285105232A6105232C7105232E81056D +:1003A000232091072322A1072324B1072326C10775 +:1003B0002328D107232AE107232CF107EF00C07C73 +:1003C0006F00C03B130101F82320110023222100FC +:1003D000232431002326410023285100232A6100D1 +:1003E000232C7100232E8100232091022322A102BD +:1003F0002324B1022326C1022328D102232AE102A9 +:10040000232CF102232E0103232011052322210591 +:10041000232431052326410523285105232A61057C +:10042000232C7105232E8105232091072322A10768 +:100430002324B1072326C1072328D107232AE10754 +:10044000232CF107EF0040766F004033130101F8D1 +:1004500023201100232221002324310023264100E0 +:1004600023285100232A6100232C7100232E8100B0 +:10047000232091022322A1022324B1022326C102B8 +:100480002328D102232AE102232CF102232E010387 +:10049000232011052322210523243105232641058C +:1004A00023285105232A6105232C7105232E81055C +:1004B000232091072322A1072324B1072326C10764 +:1004C0002328D107232AE107232CF107EF00806DB1 +:1004D0006F00C02A130101F82320110023222100FC +:1004E000232431002326410023285100232A6100C0 +:1004F000232C7100232E8100232091022322A102AC +:100500002324B1022326C1022328D102232AE10297 +:10051000232CF102232E0103232011052322210580 +:10052000232431052326410523285105232A61056B +:10053000232C7105232E8105232091072322A10757 +:100540002324B1072326C1072328D107232AE10743 +:10055000232CF107EF00C0646F004022130101F863 +:1005600023201100232221002324310023264100CF +:1005700023285100232A6100232C7100232E81009F +:10058000232091022322A1022324B1022326C102A7 +:100590002328D102232AE102232CF102232E010376 +:1005A000232011052322210523243105232641057B +:1005B00023285105232A6105232C7105232E81054B +:1005C000232091072322A1072324B1072326C10753 +:1005D0002328D107232AE107232CF107EF00005C31 +:1005E0006F00C019130101F82320110023222100FC +:1005F000232431002326410023285100232A6100AF +:10060000232C7100232E8100232091022322A1029A +:100610002324B1022326C1022328D102232AE10286 +:10062000232CF102232E010323201105232221056F +:10063000232431052326410523285105232A61055A +:10064000232C7105232E8105232091072322A10746 +:100650002324B1072326C1072328D107232AE10732 +:10066000232CF107EF0040536F004011130101F8F4 +:1006700023201100232221002324310023264100BE +:1006800023285100232A6100232C7100232E81008E +:10069000232091022322A1022324B1022326C10296 +:1006A0002328D102232AE102232CF102232E010365 +:1006B000232011052322210523243105232641056A +:1006C00023285105232A6105232C7105232E81053A +:1006D000232091072322A1072324B1072326C10742 +:1006E0002328D107232AE107232CF107EF00804AB2 +:1006F0006F00C008130101F82320110023222100FC +:10070000232431002326410023285100232A61009D +:10071000232C7100232E8100232091022322A10289 +:100720002324B1022326C1022328D102232AE10275 +:10073000232CF102232E010323201105232221055E +:10074000232431052326410523285105232A610549 +:10075000232C7105232E8105232091072322A10735 +:100760002324B1072326C1072328D107232AE10721 +:10077000232CF107EF00C0416F00400083200100EF +:1007800003214100832181000322C1008322010152 +:1007900003234101832381010324C1018324010236 +:1007A00003254102832581020326C102832601031A +:1007B00003274103832781030328C10383280104FE +:1007C0000329410483298104032AC104832A0105E2 +:1007D000032B4105832B8105032CC105832C0106C6 +:1007E000032D4106832D8106032EC106832E0107AA +:1007F000032F4107832F8107130101087300203065 +:1008000000000000000000000000000000000000E8 +:10081000735000307350403097F0FFFF9380807E1C +:10082000B7C200029382C2FF23A00200F32210305D +:1008300093F2120063960202F322503093F23200D8 +:1008400013031000639E6200F322503093F2C2FF44 +:1008500017F3FFFF1303437B639862046F000001EB +:1008600097F2FFFF9382427A73905230171700007D +:100870001307472A971700009387C7291718000006 +:100880001308482A6308F7006386070197000000F1 +:10089000E7804009972100009381C1A7EF00000184 +:1008A000138101076F00802D7300100093820000F8 +:1008B000938701821388018763840701EF00400456 +:1008C0009387018113880182638C0701EF00400345 +:1008D000938701871388018763840701EF00400233 +:1008E0001387018193870181138801816306F700D3 +:1008F00063840701EF00C00293800200678000005C +:100900006364F804B368F80093F83800634E10038A +:1009100023A0070093874700E3CC07FF6780000010 +:100920006364F802B368F80093F83800634E10016E +:100930008328070023A01701938747001307470068 +:10094000E3C807FF6F0080006F00000067800000B1 +:10095000130101FF2324010023260100B7C7000271 +:1009600083A6C7FF2324D10083A687FF2326D100B7 +:1009700003A6C7FF83268100E314D6FE83A5C7FF25 +:100980000325C1001301010167800000130101FE6E +:10099000B75700022328210103A90700930600008E +:1009A000232C810013060900232A910023263101FC +:1009B00023244101232E110093090500138A050009 +:1009C000EF00007B23A8A18023AAB1809304050037 +:1009D0001384050063160A001305100063E229055D +:1009E000374900029307F0FF2322F900EFF05FF68A +:1009F000330595002320A900EFF09FF533059500FE +:100A000033359500B38585003305B5002322A90051 +:100A100093070008F3A74730F3670430130500007D +:100A20008320C101032481018324410103290101A1 +:100A30008329C100032A810013010102678000009D +:100A4000130101FF2326110023248100232291009A +:100A500023202101374400029307F0FF2322F400F2 +:100A6000EFF01FEF9387018103A9070083A44700DC +:100A7000330525012320A400EFF09FED3305A900E5 +:100A800033352501B385B4003305B5002322A40016 +:100A9000032481008320C100832441000329010035 +:100AA000130101016F00C05D130101FF2326110036 +:100AB000EF00C05B37670000832707028320C10077 +:100AC00093F7D7FF2320F70213010101678000008D +:100AD000635E05089317150093D7170013073000BE +:100AE0006394E7006FF05FFC130770006394E70006 +:100AF0006FF01FF51307B0006394E7006F008008E4 +:100B0000130780016394E7006F00000A1307900148 +:100B10006394E7006F0000091307A0016394E700E6 +:100B20006F0000081307B0016394E7006F0000072F +:100B30001307C0016394E7006F0000061307D0019C +:100B40006394E7006F0000051307E0016394E7007A +:100B50006F000004130700016394E7006F000003B7 +:100B6000130710016394E7006F000002130101FFF7 +:100B70001305150023261100EF0040036F000054F9 +:100B800067800000678000006780000067800000C9 +:100B900067800000678000006780000067800000B9 +:100BA0006780000067800000678000006F00000021 +:100BB000F3670430678000002320B50067800000E1 +:100BC0000325050067800000138E0600331EBE005B +:100BD000337ECE00032305009303060093C3F3FF87 +:100BE000337373003363C301232065006780000003 +:100BF000032505003375C5003355B5006780000037 +:100C00002310B50067800000031505006780000011 +:100C1000138E0600331EBE00337ECE000313050084 +:100C20009303060093C3F3FF337373003363C3016D +:100C30002310650067800000031505003375C500AB +:100C40003355B500678000002300B50067800000C1 +:100C50000305050067800000138E0600331EBE00EA +:100C6000337ECE00030305009303060093C3F3FF16 +:100C7000337373003363C301230065006780000092 +:100C8000030505003375C5003355B50067800000C6 +:100C90006304050A9307700063E0D70AB7270000D2 +:100CA000637CF608130101FE232C81002328210117 +:100CB0001304060013890500232A91009375F60F8B +:100CC000930405001354544013058900232E11008A +:100CD000232631011374847F93890600EFF0DFF639 +:100CE0001305C900B3653401EFF01FF613050901C0 +:100CF00023A02401EFF0DFF5137525006312050230 +:100D0000238204008320C101032481018324410143 +:100D1000032901018329C10013010102678000003A +:100D200003A5040013054500EFF09FF203A504009E +:100D3000130505016FF01FFC67800000130101FE21 +:100D4000232E1100232C8100232A91002328210126 +:100D500023263101630C0508938905006388050883 +:100D6000930406006308060213040500032505002A +:100D70001309000013050501EFF09FED83474400C0 +:100D8000B367F5002302F40013752500630405061C +:100D9000631299028320C101032481011385040099 +:100DA00003290101832441018329C10013010102A8 +:100DB000678000000325040013054500EFF05FE99C +:100DC000B38729012380A700032504001309190014 +:100DD00013050501EFF0DFE783474400B367F50033 +:100DE0002302F400137525006FF05FFA93040000EE +:100DF0006FF05FFA930409006FF0DFF963020506F4 +:100E000063800506130101FF232481002322910042 +:100E10002326110093040500138405008347040072 +:100E2000639C07008320C1000324810083244100C8 +:100E3000130101016780000003A5040013050501EB +:100E4000EFF01FE113751500E30805FE834504006C +:100E500003A5040013041400EFF01FDF6FF01FFC64 +:100E600067800000130101FF2324810013040500A3 +:100E70002322910023202101232611002320B400E6 +:100E8000938405002322C5001389050813850400F7 +:100E90009305000093844400EFF01FDBE39824FFE8 +:100EA0008327440013071000638AE7026384070660 +:100EB00013072000639AE70A032504000324810036 +:100EC0008320C10083244100032901009305F0FF22 +:100ED00013050508130101016FF01FCE032504005F +:100EE000B70401009385F4FF13050508EFF05FD107 +:100EF00003250400032481008320C100032901008D +:100F00009385F4FF83244100130545081301010173 +:100F10006FF01FCF032504009305F00F130505089C +:100F2000EFF09FD2032504009305F00F1305450849 +:100F3000EFF09FD1032504009305F00F13058508FA +:100F4000EFF09FD003250400032481008320C1001B +:100F500083244100032901009305F00F1305C50800 +:100F6000130101016FF05FCE8320C10003248100D3 +:100F7000832441000329010013010101678000005F +:100F800083274500130101FF2324810023229100C0 +:100F90002326110013071000130405009384050095 +:100FA0006386E702638E0704130720006396E70A4F +:100FB00003250500032481008320C1008324410010 +:100FC0001305050A130101016FF01FBF032505007A +:100FD0009395050193D505011305050AEFF05FC24E +:100FE00003250400032481008320C10093D504015C +:100FF000832441001305450A130101016FF05FC00E +:101000000325050093F5F50F1305050AEFF0DFC37F +:101010000325040093D5840093F5F50F1305450AC5 +:10102000EFF09FC20325040093D5040193F5F50F5B +:101030001305850AEFF05FC1032504000324810036 +:101040008320C10093D58401832441001305C50A80 +:10105000130101016FF05FBF8320C10003248100F1 +:1010600083244100130101016780000037670000FD +:101070008327070293F7D7FF2320F702678000003A +:101080009387C18103A70700130101FF23261100E5 +:101090001347F70023A0E70083A507001385018607 +:1010A000EFF01FEE8320C100970500009385857D3A +:1010B00013858186130101016FF05FD4130101FFD5 +:1010C000930610001306A001B705007113858186F1 +:1010D00023261100232481002322910023202101B3 +:1010E000EFF01FBB971700009387C7A283A50700E7 +:1010F00013858186EFF09FD013062000B705007599 +:1011000013850186EFF01FD6930500001385018635 +:10111000EFF01FE7EFF0DFA9B7070007F3A74730AD +:1011200037F5FA021305050893050000EFF01F8656 +:1011300093840182138481861389818113060004BC +:101140009385018213050400EFF05FBF238CA1801B +:101150008347090093F7F70FE38207FE93850400A6 +:1011600013050400EFF09FC9238C01806FF01FFD71 +:10117000130101FD23248102232C410123261102A6 +:101180002322910223202103232E3101232A5101FE +:101190002328610123267101232481012322910147 +:1011A000130A050013840500639E06229389060036 +:1011B000930406001309050063FEC510B70701007C +:1011C000938A0500636EF62CB7070001636AF65632 +:1011D000135786019309800197170000938787832F +:1011E000B387E70083C70700B3893701930700027D +:1011F000B3873741638C07003314F400B3593A01C5 +:10120000B314F600B3EA89003319FA0013DB0401C2 +:1012100093050B0013850A00EF004060130A0500D8 +:1012200093050B0013850A00939A0401EF00805A7E +:1012300093DA0A01930505001304050013850A00DB +:10124000EF008056131A0A0193570901B367FA0099 +:1012500063FCA700B38797001307F4FF63E49700CC +:1012600063E8A75213040700B389A74093050B0056 +:1012700013850900EF00805A130A050093050B003F +:1012800013850900EF0000551319090193050500A6 +:1012900093090500131A0A0113850A00135909015D +:1012A000EF00805033692A01637EA900338924014D +:1012B0009387F9FF636699009389E9FF6364A90046 +:1012C000938907001315040133653501130C0000E1 +:1012D0006F00C016631A0600930500001305100086 +:1012E000EF00404F93040500B707010063EEF418C8 +:1012F000B707000163ECF44413D78401930980011C +:101300009707000093870771B387E70083C707003B +:10131000B389370193070002B3873741639E0718EB +:10132000939B04013304944013DB040193DB0B0112 +:10133000130C100093050B0013050400EF00004E82 +:10134000130A050093050B0013050400EF00804805 +:1013500093850B0013040500EF000045131A0A01E2 +:1013600093570901B367FA0063FCA700B38797009E +:101370001307F4FF63E4970063E2A7421304070036 +:10138000B389A74093050B0013850900EF000049BE +:10139000130A050093050B0013850900EF00804335 +:1013A0001319090193850B00131A0A011359090136 +:1013B0009309050033692A01EF00003F637EA9000D +:1013C000338924019387F9FF636699009389E9FFC4 +:1013D0006364A9009389070013150401336535017F +:1013E0006F00C00563E8D504B707010063E4F608A1 +:1013F000B707000163E0F63493D7860193058001B7 +:1014000017070000130707613307F700834707003A +:10141000130B0002B387B700330BFB4063100B18AC +:1014200063EC86323336CA0013451600130C0000F5 +:101430006F00C000130C00001305000093050C00A2 +:101440008320C10203248102832441020329010273 +:101450008329C101032A8101832A4101032B010150 +:10146000832BC100032C8100832C41001301010355 +:10147000678000009307F00F63F6D72E93D786009E +:10148000930580006FF0DFF79307F00F13870400D8 +:10149000E3F897E613D78400930980006FF05FE6C6 +:1014A0009307F00F13070600E3F8C7D2135786001F +:1014B000930980006FF05FD2B394F400335C340181 +:1014C00013DB040193050B0013050C003314F40027 +:1014D0003319FA00B3593A01EF004034B3EA8900F6 +:1014E00093050B0093090500939B040113050C0061 +:1014F000EF00402E93DB0B0193050500130A050056 +:1015000013850B00EF00402A9399090193D70A0134 +:10151000B3E7F90063FEA700B38797001307FAFF4C +:1015200063E4972663F2A726130AEAFFB3879700BE +:101530003384A74093050B0013050400EF00002E31 +:101540009309050093050B0013050400EF008028A4 +:10155000939A0A0193050500130C050013940901E1 +:1015600013850B0093DA0A01EF0000243364540161 +:10157000637EA400330494009307FCFF636E941E03 +:10158000637CA41E130CECFF33049400131A0A01AD +:101590003304A440336C8A016FF0DFD9B35BF600EB +:1015A000B3966601B3EBDB00B354F40093D90B019F +:1015B000B357FA00938509003314640113850400BE +:1015C00033E48700B31A6601EF00402513090500D4 +:1015D00093850900139C0B0113850400EF00801F05 +:1015E000135C0C0193050500930C050013050C001A +:1015F000EF00801B1319090193570401B367F90029 +:1016000063FEA700B38777011387FCFF63EA7717B0 +:1016100063F8A716938CECFFB3877701B384A740D8 +:101620009385090013850400EF00401F130905008E +:101630009385090013850400EF00C01913140401F9 +:1016400093050500930405001319090113050C0007 +:1016500013540401EF00401533648900637EA40035 +:10166000330474019387F4FF636474116372A410EC +:101670009384E4FF33047401370E0100939C0C0142 +:10168000B3EC9C001307FEFF33F8EC0033F7EA00DD +:101690003304A44093D80C0193DA0A01130508001F +:1016A00093050700EF0040101303050093850A001F +:1016B00013050800EF00400F13080500930507000D +:1016C00013850800EF00400E1307050093850A00FC +:1016D00013850800EF00400D935703013308E8001D +:1016E000B387070163F4E7003305C50113D707018A +:1016F0003305A700636AA4026308A40013850C00E5 +:10170000130C00006FF09FD3370701001307F7FF9A +:10171000B3F7E700939707013373E30033166A01C9 +:10172000B3876700E37CF6FC1385FCFF130C000015 +:101730006FF0DFD093D70601930500016FF05FCC07 +:1017400013570601930900016FF01FA913D7040175 +:10175000930900016FF0DFBA130C000013051000AD +:101760006FF0DFCD93870600930500006FF05FC92F +:10177000938407006FF05FF0138C07006FF01FE198 +:10178000930C07006FF09FE9130A07006FF05FDA10 +:101790001304E4FFB38797006FF01FAD1304E4FF59 +:1017A000B38797006FF0DFBD130605001305000037 +:1017B00093F61500638406003305C50093D5150024 +:1017C00013161600E39605FE6780000063400506C9 +:1017D00063C6050613860500930505001305F0FF93 +:1017E000630C060293061000637AB6006358C000CB +:1017F0001316160093961600E36AB6FE1305000052 +:1018000063E6C500B385C5403365D50093D61600A1 +:1018100013561600E39606FE6780000093820000D0 +:10182000EFF05FFB13850500678002003305A040E1 +:1018300063D80500B305B0406FF0DFF9B305B040E1 +:1018400093820000EFF01FF93305A040678002008B +:101850009382000063CA0500634C0500EFF09FF718 +:101860001385050067800200B305B040E35805FE0C +:101870003305A040EFF01FF63305B040678002004B +:101880000D0A496E7465726E616C205379737465CC +:101890006D2054696D657220496E74657272757041 +:1018A000740000000D0A2A2A2A2A2A2A2A2A2A2A09 +:1018B0002A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A88 +:1018C0002A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A78 +:1018D0002A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A68 +:1018E0002A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A58 +:1018F0002A2A2A2A0D0A0A2A2A2A2A2A2A2A2A2AA5 +:101900002A2A2A2A2A2A2A2A2A2A2A202020204D3C +:10191000692D562053797374656D2054696D657215 +:1019200020426C696E6B79204578616D706C652022 +:101930002020202A2A2A2A2A2A2A2A2A2A2A2A2A25 +:101940002A2A2A2A2A2A2A2A2A2A0D0A0A2A2A2A54 +:101950002A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2AE7 +:101960002A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2AD7 +:101970002A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2AC7 +:101980002A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2AB7 +:101990002A2A2A2A2A2A2A2A2A2A2A0D0A0D0A4FFC +:1019A00062736572766520746865204C45447320C7 +:1019B000626C696E6B696E67206F6E20746865205B +:1019C000626F6172642E20546865204C454420701B +:1019D00061747465726E206368616E6765732065FB +:1019E000766572792074696D6520612073797374EE +:1019F000656D2074696D657220696E7465727275AB +:101A00007074206F63637572732E0D0A00000000FE +:101A10000001020203030303040404040404040495 +:101A20000505050505050505050505050505050566 +:101A30000606060606060606060606060606060646 +:101A40000606060606060606060606060606060636 +:101A50000707070707070707070707070707070716 +:101A60000707070707070707070707070707070706 +:101A700007070707070707070707070707070707F6 +:101A800007070707070707070707070707070707E6 +:101A900008080808080808080808080808080808C6 +:101AA00008080808080808080808080808080808B6 +:101AB00008080808080808080808080808080808A6 +:101AC0000808080808080808080808080808080896 +:101AD0000808080808080808080808080808080886 +:101AE0000808080808080808080808080808080876 +:101AF0000808080808080808080808080808080866 +:101B00000808080808080808080808080808080855 +:101B1000A4180040000000000000000000000000C9 +:0400000540000000B7 +:00000001FF diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/import_comps_miv_ess_dgc2.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/import_comps_miv_ess_dgc2.tcl new file mode 100644 index 0000000..28cbf53 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/import_comps_miv_ess_dgc2.tcl @@ -0,0 +1,14 @@ +#This Tcl file sources other Tcl files to build the design(on which recursive export is run) in a bottom-up fashion + +#Sourcing the Tcl files for creating individual components under the top level +source ./import/components/IMC_DGC2/components/COREJTAGDEBUG_C0.tcl +source ./import/components/IMC_DGC2/components/CORERESET_PF_C0.tcl +source ./import/components/IMC_DGC2/components/CoreTimer_C0.tcl +source ./import/components/IMC_DGC2/components/CoreTimer_C1.tcl +source ./import/components/IMC_DGC2/components/MIV_ESS_C0.tcl +source ./import/components/IMC_DGC2/components/MIV_RV32_C0.tcl +source ./import/components/IMC_DGC2/components/PF_CCC_C0.tcl +source ./import/components/IMC_DGC2/components/PF_INIT_MONITOR_C0.tcl +source ./import/components/IMC_DGC2/components/PF_OSC_C0.tcl +source ./import/components/IMC_DGC2/components/SRC_MEM.tcl +source ./import/components/IMC_DGC2/components/build_sd_miv_ess_dgc2.tcl diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/import_sd_and_constraints_miv_ess_dgc2.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/import_sd_and_constraints_miv_ess_dgc2.tcl new file mode 100644 index 0000000..d80101c --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/IMC_DGC2/import_sd_and_constraints_miv_ess_dgc2.tcl @@ -0,0 +1,42 @@ +puts "\n------------------------------------------------------------------------------- \ + \r\nImporting Components... \ + \r\n------------------------------------------------------------------------------- \n" + +source ./import/components/IMC_DGC2/import_comps_miv_ess_dgc2.tcl + +puts "\n------------------------------------------------------------------------------- \ + \r\nComponents Imported. \ + \r\n------------------------------------------------------------------------------- \n" + +build_design_hierarchy +set_root BaseDesign + +puts "\n------------------------------------------------------------------------------- \ + \r\nApplying Design Constraints... \ + \r\n------------------------------------------------------------------------------- \n" + +import_files -io_pdc ./import/components/IMC_DGC2/constraints/io/io_constraints.pdc +import_files -sdc ./import/components/IMC_DGC2/constraints/io_jtag_constraints.sdc + +# #Associate SDC constraint file to Place and Route tool +organize_tool_files -tool {PLACEROUTE} \ + -file $project_dir/constraint/io/io_constraints.pdc \ + -file $project_dir/constraint/io_jtag_constraints.sdc \ + -module {BaseDesign::work} -input_type {constraint} + +organize_tool_files -tool {SYNTHESIZE} \ + -file $project_dir/constraint/io_jtag_constraints.sdc \ + -module {BaseDesign::work} -input_type {constraint} + +organize_tool_files -tool {VERIFYTIMING} \ + -file $project_dir/constraint/io_jtag_constraints.sdc \ + -module {BaseDesign::work} -input_type {constraint} + +set_root BaseDesign +run_tool -name {CONSTRAINT_MANAGEMENT} +derive_constraints_sdc + +puts "\n------------------------------------------------------------------------------- \ + \r\nDesign Constraints Applied. \ + \r\n------------------------------------------------------------------------------- \n" + diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/COREAHBTOAPB3_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/COREAHBTOAPB3_0.tcl new file mode 100644 index 0000000..16aa3be --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/COREAHBTOAPB3_0.tcl @@ -0,0 +1,4 @@ +# Exporting core COREAHBTOAPB3_0 to TCL +# Exporting Create design command for core COREAHBTOAPB3_0 +create_and_configure_core -core_vlnv {Actel:DirectCore:COREAHBTOAPB3:3.2.101} -component_name {COREAHBTOAPB3_0} -params { } +# Exporting core COREAHBTOAPB3_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreAHBL_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreAHBL_0.tcl new file mode 100644 index 0000000..712d16e --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreAHBL_0.tcl @@ -0,0 +1,111 @@ +# Exporting core CoreAHBL_0 to TCL +# Exporting Create design command for core CoreAHBL_0 +create_and_configure_core -core_vlnv {Actel:DirectCore:CoreAHBLite:5.6.105} -component_name {CoreAHBL_0} -params {\ +"HADDR_SHG_CFG:1" \ +"M0_AHBSLOT0ENABLE:false" \ +"M0_AHBSLOT1ENABLE:false" \ +"M0_AHBSLOT2ENABLE:false" \ +"M0_AHBSLOT3ENABLE:false" \ +"M0_AHBSLOT4ENABLE:false" \ +"M0_AHBSLOT5ENABLE:false" \ +"M0_AHBSLOT6ENABLE:false" \ +"M0_AHBSLOT7ENABLE:true" \ +"M0_AHBSLOT8ENABLE:false" \ +"M0_AHBSLOT9ENABLE:false" \ +"M0_AHBSLOT10ENABLE:false" \ +"M0_AHBSLOT11ENABLE:false" \ +"M0_AHBSLOT12ENABLE:false" \ +"M0_AHBSLOT13ENABLE:false" \ +"M0_AHBSLOT14ENABLE:false" \ +"M0_AHBSLOT15ENABLE:false" \ +"M0_AHBSLOT16ENABLE:false" \ +"M1_AHBSLOT0ENABLE:false" \ +"M1_AHBSLOT1ENABLE:false" \ +"M1_AHBSLOT2ENABLE:false" \ +"M1_AHBSLOT3ENABLE:false" \ +"M1_AHBSLOT4ENABLE:false" \ +"M1_AHBSLOT5ENABLE:false" \ +"M1_AHBSLOT6ENABLE:false" \ +"M1_AHBSLOT7ENABLE:false" \ +"M1_AHBSLOT8ENABLE:true" \ +"M1_AHBSLOT9ENABLE:false" \ +"M1_AHBSLOT10ENABLE:false" \ +"M1_AHBSLOT11ENABLE:false" \ +"M1_AHBSLOT12ENABLE:false" \ +"M1_AHBSLOT13ENABLE:false" \ +"M1_AHBSLOT14ENABLE:false" \ +"M1_AHBSLOT15ENABLE:false" \ +"M1_AHBSLOT16ENABLE:false" \ +"M2_AHBSLOT0ENABLE:false" \ +"M2_AHBSLOT1ENABLE:false" \ +"M2_AHBSLOT2ENABLE:false" \ +"M2_AHBSLOT3ENABLE:false" \ +"M2_AHBSLOT4ENABLE:false" \ +"M2_AHBSLOT5ENABLE:false" \ +"M2_AHBSLOT6ENABLE:false" \ +"M2_AHBSLOT7ENABLE:false" \ +"M2_AHBSLOT8ENABLE:false" \ +"M2_AHBSLOT9ENABLE:false" \ +"M2_AHBSLOT10ENABLE:false" \ +"M2_AHBSLOT11ENABLE:false" \ +"M2_AHBSLOT12ENABLE:false" \ +"M2_AHBSLOT13ENABLE:false" \ +"M2_AHBSLOT14ENABLE:false" \ +"M2_AHBSLOT15ENABLE:false" \ +"M2_AHBSLOT16ENABLE:false" \ +"M3_AHBSLOT0ENABLE:false" \ +"M3_AHBSLOT1ENABLE:false" \ +"M3_AHBSLOT2ENABLE:false" \ +"M3_AHBSLOT3ENABLE:false" \ +"M3_AHBSLOT4ENABLE:false" \ +"M3_AHBSLOT5ENABLE:false" \ +"M3_AHBSLOT6ENABLE:false" \ +"M3_AHBSLOT7ENABLE:false" \ +"M3_AHBSLOT8ENABLE:false" \ +"M3_AHBSLOT9ENABLE:false" \ +"M3_AHBSLOT10ENABLE:false" \ +"M3_AHBSLOT11ENABLE:false" \ +"M3_AHBSLOT12ENABLE:false" \ +"M3_AHBSLOT13ENABLE:false" \ +"M3_AHBSLOT14ENABLE:false" \ +"M3_AHBSLOT15ENABLE:false" \ +"M3_AHBSLOT16ENABLE:false" \ +"MASTER0_INTERFACE:1" \ +"MASTER1_INTERFACE:1" \ +"MASTER2_INTERFACE:1" \ +"MASTER3_INTERFACE:1" \ +"MEMSPACE:1" \ +"SC_0:false" \ +"SC_1:false" \ +"SC_2:false" \ +"SC_3:false" \ +"SC_4:false" \ +"SC_5:false" \ +"SC_6:false" \ +"SC_7:false" \ +"SC_8:false" \ +"SC_9:false" \ +"SC_10:false" \ +"SC_11:false" \ +"SC_12:false" \ +"SC_13:false" \ +"SC_14:false" \ +"SC_15:false" \ +"SLAVE0_INTERFACE:1" \ +"SLAVE1_INTERFACE:1" \ +"SLAVE2_INTERFACE:1" \ +"SLAVE3_INTERFACE:1" \ +"SLAVE4_INTERFACE:1" \ +"SLAVE5_INTERFACE:1" \ +"SLAVE6_INTERFACE:1" \ +"SLAVE7_INTERFACE:1" \ +"SLAVE8_INTERFACE:1" \ +"SLAVE9_INTERFACE:1" \ +"SLAVE10_INTERFACE:1" \ +"SLAVE11_INTERFACE:1" \ +"SLAVE12_INTERFACE:1" \ +"SLAVE13_INTERFACE:1" \ +"SLAVE14_INTERFACE:1" \ +"SLAVE15_INTERFACE:1" \ +"SLAVE16_INTERFACE:1" } +# Exporting core CoreAHBL_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreAPB3_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreAPB3_0.tcl new file mode 100644 index 0000000..58d003b --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreAPB3_0.tcl @@ -0,0 +1,41 @@ +# Exporting core CoreAPB3_0 to TCL +# Exporting Create design command for core CoreAPB3_0 +create_and_configure_core -core_vlnv {Actel:DirectCore:CoreAPB3:4.2.100} -component_name {CoreAPB3_0} -params {\ +"APB_DWIDTH:32" \ +"APBSLOT0ENABLE:false" \ +"APBSLOT1ENABLE:true" \ +"APBSLOT2ENABLE:true" \ +"APBSLOT3ENABLE:true" \ +"APBSLOT4ENABLE:true" \ +"APBSLOT5ENABLE:true" \ +"APBSLOT6ENABLE:false" \ +"APBSLOT7ENABLE:false" \ +"APBSLOT8ENABLE:false" \ +"APBSLOT9ENABLE:false" \ +"APBSLOT10ENABLE:false" \ +"APBSLOT11ENABLE:false" \ +"APBSLOT12ENABLE:false" \ +"APBSLOT13ENABLE:false" \ +"APBSLOT14ENABLE:false" \ +"APBSLOT15ENABLE:false" \ +"IADDR_OPTION:0" \ +"MADDR_BITS:16" \ +"SC_0:false" \ +"SC_1:false" \ +"SC_2:false" \ +"SC_3:false" \ +"SC_4:false" \ +"SC_5:false" \ +"SC_6:false" \ +"SC_7:false" \ +"SC_8:false" \ +"SC_9:false" \ +"SC_10:false" \ +"SC_11:false" \ +"SC_12:false" \ +"SC_13:false" \ +"SC_14:false" \ +"SC_15:false" \ +"UPR_NIBBLE_POSN:6" } +# Exporting core CoreAPB3_0 to TCL done + diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreAXITOAHBL_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreAXITOAHBL_0.tcl new file mode 100644 index 0000000..c4ebe04 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreAXITOAHBL_0.tcl @@ -0,0 +1,11 @@ +# Exporting core CoreAXITOAHBL_0 to TCL +# Exporting Create design command for core CoreAXITOAHBL_0 +create_and_configure_core -core_vlnv {Actel:DirectCore:COREAXITOAHBL:3.6.101} -component_name {CoreAXITOAHBL_0} -params {\ +"ASYNC_CLOCKS:false" \ +"AXI_DWIDTH:64" \ +"AXI_SEL_MM_S:1" \ +"EXPOSE_WID:false" \ +"ID_WIDTH:5" \ +"NO_BURST_TRANS:false" \ +"WRAP_SUPPORT:false" } +# Exporting core CoreAXITOAHBL_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreAXITOAHBL_1.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreAXITOAHBL_1.tcl new file mode 100644 index 0000000..5b315bb --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreAXITOAHBL_1.tcl @@ -0,0 +1,11 @@ +# Exporting core CoreAXITOAHBL_1 to TCL +# Exporting Create design command for core CoreAXITOAHBL_1 +create_and_configure_core -core_vlnv {Actel:DirectCore:COREAXITOAHBL:3.6.101} -component_name {CoreAXITOAHBL_1} -params {\ +"ASYNC_CLOCKS:false" \ +"AXI_DWIDTH:64" \ +"AXI_SEL_MM_S:1" \ +"EXPOSE_WID:false" \ +"ID_WIDTH:5" \ +"NO_BURST_TRANS:false" \ +"WRAP_SUPPORT:false" } +# Exporting core CoreAXITOAHBL_1 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreGPIO_IN.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreGPIO_IN.tcl new file mode 100644 index 0000000..a1c824d --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreGPIO_IN.tcl @@ -0,0 +1,136 @@ +# Exporting core CoreGPIO_IN to TCL +# Exporting Create design command for core CoreGPIO_IN +create_and_configure_core -core_vlnv {Actel:DirectCore:CoreGPIO:3.2.102} -component_name {CoreGPIO_IN} -params {\ +"APB_WIDTH:32" \ +"FIXED_CONFIG_0:true" \ +"FIXED_CONFIG_1:true" \ +"FIXED_CONFIG_2:false" \ +"FIXED_CONFIG_3:false" \ +"FIXED_CONFIG_4:false" \ +"FIXED_CONFIG_5:false" \ +"FIXED_CONFIG_6:false" \ +"FIXED_CONFIG_7:false" \ +"FIXED_CONFIG_8:false" \ +"FIXED_CONFIG_9:false" \ +"FIXED_CONFIG_10:false" \ +"FIXED_CONFIG_11:false" \ +"FIXED_CONFIG_12:false" \ +"FIXED_CONFIG_13:false" \ +"FIXED_CONFIG_14:false" \ +"FIXED_CONFIG_15:false" \ +"FIXED_CONFIG_16:false" \ +"FIXED_CONFIG_17:false" \ +"FIXED_CONFIG_18:false" \ +"FIXED_CONFIG_19:false" \ +"FIXED_CONFIG_20:false" \ +"FIXED_CONFIG_21:false" \ +"FIXED_CONFIG_22:false" \ +"FIXED_CONFIG_23:false" \ +"FIXED_CONFIG_24:false" \ +"FIXED_CONFIG_25:false" \ +"FIXED_CONFIG_26:false" \ +"FIXED_CONFIG_27:false" \ +"FIXED_CONFIG_28:false" \ +"FIXED_CONFIG_29:false" \ +"FIXED_CONFIG_30:false" \ +"FIXED_CONFIG_31:false" \ +"INT_BUS:0" \ +"IO_INT_TYPE_0:7" \ +"IO_INT_TYPE_1:7" \ +"IO_INT_TYPE_2:7" \ +"IO_INT_TYPE_3:7" \ +"IO_INT_TYPE_4:7" \ +"IO_INT_TYPE_5:7" \ +"IO_INT_TYPE_6:7" \ +"IO_INT_TYPE_7:7" \ +"IO_INT_TYPE_8:7" \ +"IO_INT_TYPE_9:7" \ +"IO_INT_TYPE_10:7" \ +"IO_INT_TYPE_11:7" \ +"IO_INT_TYPE_12:7" \ +"IO_INT_TYPE_13:7" \ +"IO_INT_TYPE_14:7" \ +"IO_INT_TYPE_15:7" \ +"IO_INT_TYPE_16:7" \ +"IO_INT_TYPE_17:7" \ +"IO_INT_TYPE_18:7" \ +"IO_INT_TYPE_19:7" \ +"IO_INT_TYPE_20:7" \ +"IO_INT_TYPE_21:7" \ +"IO_INT_TYPE_22:7" \ +"IO_INT_TYPE_23:7" \ +"IO_INT_TYPE_24:7" \ +"IO_INT_TYPE_25:7" \ +"IO_INT_TYPE_26:7" \ +"IO_INT_TYPE_27:7" \ +"IO_INT_TYPE_28:7" \ +"IO_INT_TYPE_29:7" \ +"IO_INT_TYPE_30:7" \ +"IO_INT_TYPE_31:7" \ +"IO_NUM:2" \ +"IO_TYPE_0:0" \ +"IO_TYPE_1:0" \ +"IO_TYPE_2:0" \ +"IO_TYPE_3:0" \ +"IO_TYPE_4:0" \ +"IO_TYPE_5:0" \ +"IO_TYPE_6:0" \ +"IO_TYPE_7:0" \ +"IO_TYPE_8:0" \ +"IO_TYPE_9:0" \ +"IO_TYPE_10:0" \ +"IO_TYPE_11:0" \ +"IO_TYPE_12:0" \ +"IO_TYPE_13:0" \ +"IO_TYPE_14:0" \ +"IO_TYPE_15:0" \ +"IO_TYPE_16:0" \ +"IO_TYPE_17:0" \ +"IO_TYPE_18:0" \ +"IO_TYPE_19:0" \ +"IO_TYPE_20:0" \ +"IO_TYPE_21:0" \ +"IO_TYPE_22:0" \ +"IO_TYPE_23:0" \ +"IO_TYPE_24:0" \ +"IO_TYPE_25:0" \ +"IO_TYPE_26:0" \ +"IO_TYPE_27:0" \ +"IO_TYPE_28:0" \ +"IO_TYPE_29:0" \ +"IO_TYPE_30:0" \ +"IO_TYPE_31:0" \ +"IO_VAL_0:0" \ +"IO_VAL_1:0" \ +"IO_VAL_2:0" \ +"IO_VAL_3:0" \ +"IO_VAL_4:0" \ +"IO_VAL_5:0" \ +"IO_VAL_6:0" \ +"IO_VAL_7:0" \ +"IO_VAL_8:0" \ +"IO_VAL_9:0" \ +"IO_VAL_10:0" \ +"IO_VAL_11:0" \ +"IO_VAL_12:0" \ +"IO_VAL_13:0" \ +"IO_VAL_14:0" \ +"IO_VAL_15:0" \ +"IO_VAL_16:0" \ +"IO_VAL_17:0" \ +"IO_VAL_18:0" \ +"IO_VAL_19:0" \ +"IO_VAL_20:0" \ +"IO_VAL_21:0" \ +"IO_VAL_22:0" \ +"IO_VAL_23:0" \ +"IO_VAL_24:0" \ +"IO_VAL_25:0" \ +"IO_VAL_26:0" \ +"IO_VAL_27:0" \ +"IO_VAL_28:0" \ +"IO_VAL_29:0" \ +"IO_VAL_30:0" \ +"IO_VAL_31:0" \ +"OE_TYPE:1" } +# Exporting core CoreGPIO_IN to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreGPIO_OUT.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreGPIO_OUT.tcl new file mode 100644 index 0000000..cecf205 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreGPIO_OUT.tcl @@ -0,0 +1,136 @@ +# Exporting core CoreGPIO_OUT to TCL +# Exporting Create design command for core CoreGPIO_OUT +create_and_configure_core -core_vlnv {Actel:DirectCore:CoreGPIO:3.2.102} -component_name {CoreGPIO_OUT} -params {\ +"APB_WIDTH:32" \ +"FIXED_CONFIG_0:true" \ +"FIXED_CONFIG_1:true" \ +"FIXED_CONFIG_2:true" \ +"FIXED_CONFIG_3:true" \ +"FIXED_CONFIG_4:false" \ +"FIXED_CONFIG_5:false" \ +"FIXED_CONFIG_6:false" \ +"FIXED_CONFIG_7:false" \ +"FIXED_CONFIG_8:false" \ +"FIXED_CONFIG_9:false" \ +"FIXED_CONFIG_10:false" \ +"FIXED_CONFIG_11:false" \ +"FIXED_CONFIG_12:false" \ +"FIXED_CONFIG_13:false" \ +"FIXED_CONFIG_14:false" \ +"FIXED_CONFIG_15:false" \ +"FIXED_CONFIG_16:false" \ +"FIXED_CONFIG_17:false" \ +"FIXED_CONFIG_18:false" \ +"FIXED_CONFIG_19:false" \ +"FIXED_CONFIG_20:false" \ +"FIXED_CONFIG_21:false" \ +"FIXED_CONFIG_22:false" \ +"FIXED_CONFIG_23:false" \ +"FIXED_CONFIG_24:false" \ +"FIXED_CONFIG_25:false" \ +"FIXED_CONFIG_26:false" \ +"FIXED_CONFIG_27:false" \ +"FIXED_CONFIG_28:false" \ +"FIXED_CONFIG_29:false" \ +"FIXED_CONFIG_30:false" \ +"FIXED_CONFIG_31:false" \ +"INT_BUS:0" \ +"IO_INT_TYPE_0:7" \ +"IO_INT_TYPE_1:7" \ +"IO_INT_TYPE_2:7" \ +"IO_INT_TYPE_3:7" \ +"IO_INT_TYPE_4:7" \ +"IO_INT_TYPE_5:7" \ +"IO_INT_TYPE_6:7" \ +"IO_INT_TYPE_7:7" \ +"IO_INT_TYPE_8:7" \ +"IO_INT_TYPE_9:7" \ +"IO_INT_TYPE_10:7" \ +"IO_INT_TYPE_11:7" \ +"IO_INT_TYPE_12:7" \ +"IO_INT_TYPE_13:7" \ +"IO_INT_TYPE_14:7" \ +"IO_INT_TYPE_15:7" \ +"IO_INT_TYPE_16:7" \ +"IO_INT_TYPE_17:7" \ +"IO_INT_TYPE_18:7" \ +"IO_INT_TYPE_19:7" \ +"IO_INT_TYPE_20:7" \ +"IO_INT_TYPE_21:7" \ +"IO_INT_TYPE_22:7" \ +"IO_INT_TYPE_23:7" \ +"IO_INT_TYPE_24:7" \ +"IO_INT_TYPE_25:7" \ +"IO_INT_TYPE_26:7" \ +"IO_INT_TYPE_27:7" \ +"IO_INT_TYPE_28:7" \ +"IO_INT_TYPE_29:7" \ +"IO_INT_TYPE_30:7" \ +"IO_INT_TYPE_31:7" \ +"IO_NUM:4" \ +"IO_TYPE_0:1" \ +"IO_TYPE_1:1" \ +"IO_TYPE_2:1" \ +"IO_TYPE_3:1" \ +"IO_TYPE_4:0" \ +"IO_TYPE_5:0" \ +"IO_TYPE_6:0" \ +"IO_TYPE_7:0" \ +"IO_TYPE_8:0" \ +"IO_TYPE_9:0" \ +"IO_TYPE_10:0" \ +"IO_TYPE_11:0" \ +"IO_TYPE_12:0" \ +"IO_TYPE_13:0" \ +"IO_TYPE_14:0" \ +"IO_TYPE_15:0" \ +"IO_TYPE_16:0" \ +"IO_TYPE_17:0" \ +"IO_TYPE_18:0" \ +"IO_TYPE_19:0" \ +"IO_TYPE_20:0" \ +"IO_TYPE_21:0" \ +"IO_TYPE_22:0" \ +"IO_TYPE_23:0" \ +"IO_TYPE_24:0" \ +"IO_TYPE_25:0" \ +"IO_TYPE_26:0" \ +"IO_TYPE_27:0" \ +"IO_TYPE_28:0" \ +"IO_TYPE_29:0" \ +"IO_TYPE_30:0" \ +"IO_TYPE_31:0" \ +"IO_VAL_0:0" \ +"IO_VAL_1:0" \ +"IO_VAL_2:0" \ +"IO_VAL_3:0" \ +"IO_VAL_4:0" \ +"IO_VAL_5:0" \ +"IO_VAL_6:0" \ +"IO_VAL_7:0" \ +"IO_VAL_8:0" \ +"IO_VAL_9:0" \ +"IO_VAL_10:0" \ +"IO_VAL_11:0" \ +"IO_VAL_12:0" \ +"IO_VAL_13:0" \ +"IO_VAL_14:0" \ +"IO_VAL_15:0" \ +"IO_VAL_16:0" \ +"IO_VAL_17:0" \ +"IO_VAL_18:0" \ +"IO_VAL_19:0" \ +"IO_VAL_20:0" \ +"IO_VAL_21:0" \ +"IO_VAL_22:0" \ +"IO_VAL_23:0" \ +"IO_VAL_24:0" \ +"IO_VAL_25:0" \ +"IO_VAL_26:0" \ +"IO_VAL_27:0" \ +"IO_VAL_28:0" \ +"IO_VAL_29:0" \ +"IO_VAL_30:0" \ +"IO_VAL_31:0" \ +"OE_TYPE:1" } +# Exporting core CoreGPIO_OUT to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreJTAGDebug_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreJTAGDebug_0.tcl new file mode 100644 index 0000000..4cc67f3 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreJTAGDebug_0.tcl @@ -0,0 +1,39 @@ +# Exporting core CoreJTAGDebug_0 to TCL +# Exporting Create design command for core CoreJTAGDebug_0 +create_and_configure_core -core_vlnv {Actel:DirectCore:COREJTAGDEBUG:4.0.100} -component_name {CoreJTAGDebug_0} -params {\ +"IR_CODE_TGT_0:0x55" \ +"IR_CODE_TGT_1:0x56" \ +"IR_CODE_TGT_2:0x57" \ +"IR_CODE_TGT_3:0x58" \ +"IR_CODE_TGT_4:0x59" \ +"IR_CODE_TGT_5:0x5a" \ +"IR_CODE_TGT_6:0x5b" \ +"IR_CODE_TGT_7:0x5c" \ +"IR_CODE_TGT_8:0x5d" \ +"IR_CODE_TGT_9:0x5e" \ +"IR_CODE_TGT_10:0x5f" \ +"IR_CODE_TGT_11:0x60" \ +"IR_CODE_TGT_12:0x61" \ +"IR_CODE_TGT_13:0x62" \ +"IR_CODE_TGT_14:0x63" \ +"IR_CODE_TGT_15:0x64" \ +"NUM_DEBUG_TGTS:1" \ +"TGT_ACTIVE_HIGH_RESET_0:false" \ +"TGT_ACTIVE_HIGH_RESET_1:false" \ +"TGT_ACTIVE_HIGH_RESET_2:false" \ +"TGT_ACTIVE_HIGH_RESET_3:false" \ +"TGT_ACTIVE_HIGH_RESET_4:false" \ +"TGT_ACTIVE_HIGH_RESET_5:false" \ +"TGT_ACTIVE_HIGH_RESET_6:false" \ +"TGT_ACTIVE_HIGH_RESET_7:false" \ +"TGT_ACTIVE_HIGH_RESET_8:false" \ +"TGT_ACTIVE_HIGH_RESET_9:false" \ +"TGT_ACTIVE_HIGH_RESET_10:false" \ +"TGT_ACTIVE_HIGH_RESET_11:false" \ +"TGT_ACTIVE_HIGH_RESET_12:false" \ +"TGT_ACTIVE_HIGH_RESET_13:false" \ +"TGT_ACTIVE_HIGH_RESET_14:false" \ +"TGT_ACTIVE_HIGH_RESET_15:false" \ +"UJTAG_BYPASS:false" \ +"UJTAG_SEC_EN:false" } +# Exporting core CoreJTAGDebug_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreJTAGDebug_1.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreJTAGDebug_1.tcl new file mode 100644 index 0000000..6543672 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreJTAGDebug_1.tcl @@ -0,0 +1,39 @@ +# Exporting core CoreJTAGDebug_0 to TCL +# Exporting Create design command for core CoreJTAGDebug_0 +create_and_configure_core -core_vlnv {Actel:DirectCore:COREJTAGDEBUG:4.0.100} -component_name {CoreJTAGDebug_1} -params {\ +"IR_CODE_TGT_0:0x55" \ +"IR_CODE_TGT_1:0x56" \ +"IR_CODE_TGT_2:0x57" \ +"IR_CODE_TGT_3:0x58" \ +"IR_CODE_TGT_4:0x59" \ +"IR_CODE_TGT_5:0x5a" \ +"IR_CODE_TGT_6:0x5b" \ +"IR_CODE_TGT_7:0x5c" \ +"IR_CODE_TGT_8:0x5d" \ +"IR_CODE_TGT_9:0x5e" \ +"IR_CODE_TGT_10:0x5f" \ +"IR_CODE_TGT_11:0x60" \ +"IR_CODE_TGT_12:0x61" \ +"IR_CODE_TGT_13:0x62" \ +"IR_CODE_TGT_14:0x63" \ +"IR_CODE_TGT_15:0x64" \ +"NUM_DEBUG_TGTS:1" \ +"TGT_ACTIVE_HIGH_RESET_0:true" \ +"TGT_ACTIVE_HIGH_RESET_1:true" \ +"TGT_ACTIVE_HIGH_RESET_2:true" \ +"TGT_ACTIVE_HIGH_RESET_3:true" \ +"TGT_ACTIVE_HIGH_RESET_4:true" \ +"TGT_ACTIVE_HIGH_RESET_5:true" \ +"TGT_ACTIVE_HIGH_RESET_6:true" \ +"TGT_ACTIVE_HIGH_RESET_7:true" \ +"TGT_ACTIVE_HIGH_RESET_8:true" \ +"TGT_ACTIVE_HIGH_RESET_9:true" \ +"TGT_ACTIVE_HIGH_RESET_10:true" \ +"TGT_ACTIVE_HIGH_RESET_11:true" \ +"TGT_ACTIVE_HIGH_RESET_12:true" \ +"TGT_ACTIVE_HIGH_RESET_13:true" \ +"TGT_ACTIVE_HIGH_RESET_14:true" \ +"TGT_ACTIVE_HIGH_RESET_15:true" \ +"UJTAG_BYPASS:false" \ +"UJTAG_SEC_EN:false" } +# Exporting core CoreJTAGDebug_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreRESET_PF_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreRESET_PF_0.tcl new file mode 100644 index 0000000..877325b --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreRESET_PF_0.tcl @@ -0,0 +1,4 @@ +# Exporting core CoreRESET_PF_0 to TCL +# Exporting Create design command for core CoreRESET_PF_0 +create_and_configure_core -core_vlnv {Actel:DirectCore:CORERESET_PF:2.3.100} -component_name {CoreRESET_PF_0} -params { } +# Exporting core CoreRESET_PF_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreTimer_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreTimer_0.tcl new file mode 100644 index 0000000..fda5b3b --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreTimer_0.tcl @@ -0,0 +1,6 @@ +# Exporting core CoreTimer_0 to TCL +# Exporting Create design command for core CoreTimer_0 +create_and_configure_core -core_vlnv {Actel:DirectCore:CoreTimer:2.0.103} -component_name {CoreTimer_0} -params {\ +"INTACTIVEH:1" \ +"WIDTH:32" } +# Exporting core CoreTimer_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreTimer_1.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreTimer_1.tcl new file mode 100644 index 0000000..6a598ae --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreTimer_1.tcl @@ -0,0 +1,6 @@ +# Exporting core CoreTimer_1 to TCL +# Exporting Create design command for core CoreTimer_1 +create_and_configure_core -core_vlnv {Actel:DirectCore:CoreTimer:2.0.103} -component_name {CoreTimer_1} -params {\ +"INTACTIVEH:1" \ +"WIDTH:32" } +# Exporting core CoreTimer_1 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreUARTapb_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreUARTapb_0.tcl new file mode 100644 index 0000000..efb076f --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/CoreUARTapb_0.tcl @@ -0,0 +1,14 @@ +# Exporting core CoreUARTapb_0 to TCL +# Exporting Create design command for core CoreUARTapb_0 +create_and_configure_core -core_vlnv {Actel:DirectCore:CoreUARTapb:5.7.100} -component_name {CoreUARTapb_0} -params {\ +"BAUD_VAL_FRCTN:0" \ +"BAUD_VAL_FRCTN_EN:false" \ +"BAUD_VALUE:1" \ +"FIXEDMODE:0" \ +"PRG_BIT8:0" \ +"PRG_PARITY:0" \ +"RX_FIFO:0" \ +"RX_LEGACY_MODE:0" \ +"TX_FIFO:0" \ +"USE_SOFT_FIFO:0" } +# Exporting core CoreUARTapb_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/MIV_RV32IMAF_L1_AHB_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/MIV_RV32IMAF_L1_AHB_0.tcl new file mode 100644 index 0000000..378a8ad --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/MIV_RV32IMAF_L1_AHB_0.tcl @@ -0,0 +1,7 @@ +# Exporting core MIV_RV32IMAF_L1_AHB_0 to TCL +# Exporting Create design command for core MIV_RV32IMAF_L1_AHB_0 +create_and_configure_core -core_vlnv {Microsemi:MiV:MIV_RV32IMAF_L1_AHB:2.1.100} -component_name {MIV_RV32IMAF_L1_AHB_0} -params {\ +"ECC_EN:false" \ +"RESET_VECTOR_ADDR_0:0x0" \ +"RESET_VECTOR_ADDR_1:0x8000" } +# Exporting core MIV_RV32IMAF_L1_AHB_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/MIV_RV32IMA_L1_AHB_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/MIV_RV32IMA_L1_AHB_0.tcl new file mode 100644 index 0000000..dbe95c4 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/MIV_RV32IMA_L1_AHB_0.tcl @@ -0,0 +1,8 @@ +# Exporting core MIV_RV32IMA_L1_AHB_0 to TCL +# Exporting Create design command for core MIV_RV32IMA_L1_AHB_0 +create_and_configure_core -core_vlnv {Microsemi:MiV:MIV_RV32IMA_L1_AHB:2.3.100} -component_name {MIV_RV32IMA_L1_AHB_0} -params {\ +"ECC_EN:false" \ +"EXT_HALT:false" \ +"RESET_VECTOR_ADDR_0:0x0" \ +"RESET_VECTOR_ADDR_1:0x8000" } +# Exporting core MIV_RV32IMA_L1_AHB_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/MIV_RV32IMA_L1_AXI_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/MIV_RV32IMA_L1_AXI_0.tcl new file mode 100644 index 0000000..613ae7e --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/MIV_RV32IMA_L1_AXI_0.tcl @@ -0,0 +1,9 @@ +# Exporting core MIV_RV32IMA_L1_AXI_0 to TCL +# Exporting Create design command for core MIV_RV32IMA_L1_AXI_0 +create_and_configure_core -core_vlnv {Microsemi:MiV:MIV_RV32IMA_L1_AXI:2.1.100} -component_name {MIV_RV32IMA_L1_AXI_0} -params {\ +"MASTER_TYPE:0" \ +"MEM_WID:5" \ +"MMIO_WID:5" \ +"RESET_VECTOR_ADDR_0:0x0" \ +"RESET_VECTOR_ADDR_1:0x8000" } +# Exporting core MIV_RV32IMA_L1_AXI_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/MIV_RV32_CFG1_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/MIV_RV32_CFG1_0.tcl new file mode 100644 index 0000000..078553f --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/MIV_RV32_CFG1_0.tcl @@ -0,0 +1,53 @@ +# Exporting core MIV_RV32_CFG1_0 to TCL +# Exporting Create design command for core MIV_RV32_CFG1_0 +create_and_configure_core -core_vlnv {Microsemi:MiV:MIV_RV32:3.0.100} -component_name {MIV_RV32_CFG1_0} -params {\ +"AHB_END_ADDR_0:0x7fff" \ +"AHB_END_ADDR_1:0x8fff" \ +"AHB_MASTER_TYPE:1" \ +"AHB_SLAVE_MIRROR:true" \ +"AHB_START_ADDR_0:0x0" \ +"AHB_START_ADDR_1:0x8000" \ +"APB_END_ADDR_0:0xffff" \ +"APB_END_ADDR_1:0x7fff" \ +"APB_MASTER_TYPE:1" \ +"APB_SLAVE_MIRROR:false" \ +"APB_START_ADDR_0:0x0" \ +"APB_START_ADDR_1:0x7000" \ +"AXI_END_ADDR_0:0xffff" \ +"AXI_END_ADDR_1:0x6fff" \ +"AXI_MASTER_TYPE:0" \ +"AXI_SLAVE_MIRROR:false" \ +"AXI_START_ADDR_0:0x0" \ +"AXI_START_ADDR_1:0x6000" \ +"BOOTROM_DEST_ADDR_LOWER:0x0" \ +"BOOTROM_DEST_ADDR_UPPER:0x4000" \ +"BOOTROM_PRESENT:false" \ +"BOOTROM_SRC_END_ADDR_LOWER:0x3fff" \ +"BOOTROM_SRC_END_ADDR_UPPER:0x8000" \ +"BOOTROM_SRC_START_ADDR_LOWER:0x0" \ +"BOOTROM_SRC_START_ADDR_UPPER:0x8000" \ +"DEBUGGER:true" \ +"ECC_ENABLE:false" \ +"FWD_REGS:false" \ +"GEN_DECODE_RV32:3" \ +"GEN_MUL_TYPE:2" \ +"GPR_REGS:false" \ +"INTERNAL_MTIME:true" \ +"INTERNAL_MTIME_IRQ:true" \ +"MTIME_PRESCALER:100" \ +"NUM_EXT_IRQS:1" \ +"RECONFIG_BOOTROM:false" \ +"RESET_VECTOR_ADDR_0:0x0" \ +"RESET_VECTOR_ADDR_1:0x8000" \ +"TAS_END_ADDR_0:0x3fff" \ +"TAS_END_ADDR_1:0x4000" \ +"TAS_START_ADDR_0:0x0" \ +"TAS_START_ADDR_1:0x4000" \ +"TCM_END_ADDR_0:0x7fff" \ +"TCM_END_ADDR_1:0x4000" \ +"TCM_PRESENT:true" \ +"TCM_START_ADDR_0:0x0" \ +"TCM_START_ADDR_1:0x4000" \ +"TCM_TAS_PRESENT:false" \ +"VECTORED_INTERRUPTS:false" } +# Exporting core MIV_RV32_CFG1_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/MIV_RV32_CFG2_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/MIV_RV32_CFG2_0.tcl new file mode 100644 index 0000000..cb26ab3 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/MIV_RV32_CFG2_0.tcl @@ -0,0 +1,53 @@ +# Exporting core MIV_RV32_CFG2_0 to TCL +# Exporting Create design command for core MIV_RV32_CFG2_0 +create_and_configure_core -core_vlnv {Microsemi:MiV:MIV_RV32:3.0.100} -component_name {MIV_RV32_CFG2_0} -params {\ +"AHB_END_ADDR_0:0xffff" \ +"AHB_END_ADDR_1:0x8fff" \ +"AHB_MASTER_TYPE:0" \ +"AHB_SLAVE_MIRROR:false" \ +"AHB_START_ADDR_0:0x0" \ +"AHB_START_ADDR_1:0x8000" \ +"APB_END_ADDR_0:0xffff" \ +"APB_END_ADDR_1:0x7fff" \ +"APB_MASTER_TYPE:1" \ +"APB_SLAVE_MIRROR:false" \ +"APB_START_ADDR_0:0x0" \ +"APB_START_ADDR_1:0x7000" \ +"AXI_END_ADDR_0:0x7fff" \ +"AXI_END_ADDR_1:0x8fff" \ +"AXI_MASTER_TYPE:2" \ +"AXI_SLAVE_MIRROR:true" \ +"AXI_START_ADDR_0:0x0" \ +"AXI_START_ADDR_1:0x8000" \ +"BOOTROM_DEST_ADDR_LOWER:0x0" \ +"BOOTROM_DEST_ADDR_UPPER:0x4000" \ +"BOOTROM_PRESENT:false" \ +"BOOTROM_SRC_END_ADDR_LOWER:0x3fff" \ +"BOOTROM_SRC_END_ADDR_UPPER:0x8000" \ +"BOOTROM_SRC_START_ADDR_LOWER:0x0" \ +"BOOTROM_SRC_START_ADDR_UPPER:0x8000" \ +"DEBUGGER:true" \ +"ECC_ENABLE:false" \ +"FWD_REGS:false" \ +"GEN_DECODE_RV32:2" \ +"GEN_MUL_TYPE:0" \ +"GPR_REGS:false" \ +"INTERNAL_MTIME:true" \ +"INTERNAL_MTIME_IRQ:true" \ +"MTIME_PRESCALER:100" \ +"NUM_EXT_IRQS:1" \ +"RECONFIG_BOOTROM:false" \ +"RESET_VECTOR_ADDR_0:0x0" \ +"RESET_VECTOR_ADDR_1:0x8000" \ +"TAS_END_ADDR_0:0x3fff" \ +"TAS_END_ADDR_1:0x4000" \ +"TAS_START_ADDR_0:0x0" \ +"TAS_START_ADDR_1:0x4000" \ +"TCM_END_ADDR_0:0x3fff" \ +"TCM_END_ADDR_1:0x4000" \ +"TCM_PRESENT:false" \ +"TCM_START_ADDR_0:0x0" \ +"TCM_START_ADDR_1:0x4000" \ +"TCM_TAS_PRESENT:false" \ +"VECTORED_INTERRUPTS:false" } +# Exporting core MIV_RV32_CFG2_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/MIV_RV32_CFG3_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/MIV_RV32_CFG3_0.tcl new file mode 100644 index 0000000..8cf5cdc --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/MIV_RV32_CFG3_0.tcl @@ -0,0 +1,54 @@ +# Exporting core MIV_RV32_CFG3_0 to TCL +# Exporting Create design command for core MIV_RV32_CFG3_0 +create_and_configure_core -core_vlnv {Microsemi:MiV:MIV_RV32:3.0.100} -component_name {MIV_RV32_CFG3_0} -params {\ +"AHB_END_ADDR_0:0xffff" \ +"AHB_END_ADDR_1:0x8fff" \ +"AHB_MASTER_TYPE:0" \ +"AHB_SLAVE_MIRROR:false" \ +"AHB_START_ADDR_0:0x0" \ +"AHB_START_ADDR_1:0x8000" \ +"APB_END_ADDR_0:0xffff" \ +"APB_END_ADDR_1:0x7fff" \ +"APB_MASTER_TYPE:1" \ +"APB_SLAVE_MIRROR:false" \ +"APB_START_ADDR_0:0x0" \ +"APB_START_ADDR_1:0x7000" \ +"AXI_END_ADDR_0:0xffff" \ +"AXI_END_ADDR_1:0x6fff" \ +"AXI_MASTER_TYPE:0" \ +"AXI_SLAVE_MIRROR:false" \ +"AXI_START_ADDR_0:0x0" \ +"AXI_START_ADDR_1:0x6000" \ +"BOOTROM_DEST_ADDR_LOWER:0x0" \ +"BOOTROM_DEST_ADDR_UPPER:0x4000" \ +"BOOTROM_PRESENT:false" \ +"BOOTROM_SRC_END_ADDR_LOWER:0x3fff" \ +"BOOTROM_SRC_END_ADDR_UPPER:0x8000" \ +"BOOTROM_SRC_START_ADDR_LOWER:0x0" \ +"BOOTROM_SRC_START_ADDR_UPPER:0x8000" \ +"DEBUGGER:true" \ +"ECC_ENABLE:false" \ +"FWD_REGS:false" \ +"GEN_DECODE_RV32:0" \ +"GEN_MUL_TYPE:2" \ +"GPR_REGS:false" \ +"INTERNAL_MTIME:true" \ +"INTERNAL_MTIME_IRQ:true" \ +"MTIME_PRESCALER:100" \ +"NUM_EXT_IRQS:1" \ +"RECONFIG_BOOTROM:false" \ +"RESET_VECTOR_ADDR_0:0x0" \ +"RESET_VECTOR_ADDR_1:0x8000" \ +"TAS_END_ADDR_0:0x3fff" \ +"TAS_END_ADDR_1:0x4000" \ +"TAS_START_ADDR_0:0x0" \ +"TAS_START_ADDR_1:0x4000" \ +"TCM_END_ADDR_0:0x7fff" \ +"TCM_END_ADDR_1:0x8000" \ +"TCM_PRESENT:true" \ +"TCM_START_ADDR_0:0x0" \ +"TCM_START_ADDR_1:0x8000" \ +"TCM_TAS_PRESENT:false" \ +"VECTORED_INTERRUPTS:false" } +# Exporting core MIV_RV32_CFG3_0 to TCL done + diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/PF_CCC_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/PF_CCC_0.tcl new file mode 100644 index 0000000..e05afc1 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/PF_CCC_0.tcl @@ -0,0 +1,246 @@ +# Exporting core PF_CCC_0 to TCL +# Exporting Create design command for core PF_CCC_0 +create_and_configure_core -core_vlnv {Actel:SgCore:PF_CCC:*} -download_core -component_name {PF_CCC_0} -params {\ +"DLL_CLK_0_BANKCLK_EN:false" \ +"DLL_CLK_0_DEDICATED_EN:false" \ +"DLL_CLK_0_FABCLK_EN:false" \ +"DLL_CLK_1_BANKCLK_EN:false" \ +"DLL_CLK_1_DEDICATED_EN:false" \ +"DLL_CLK_1_FABCLK_EN:false" \ +"DLL_CLK_P_EN:false" \ +"DLL_CLK_P_OPTIONS_EN:false" \ +"DLL_CLK_REF_OPTION:DIVIDE_BY_1" \ +"DLL_CLK_REF_OPTIONS_EN:false" \ +"DLL_CLK_S_EN:false" \ +"DLL_CLK_S_OPTION:DIVIDE_BY_1" \ +"DLL_CLK_S_OPTIONS_EN:false" \ +"DLL_DELAY4:0" \ +"DLL_DYNAMIC_CODE_EN:false" \ +"DLL_DYNAMIC_RECONFIG_INTERFACE_EN:false" \ +"DLL_EXPORT_PWRDWN:false" \ +"DLL_FB_CLK:Primary" \ +"DLL_FB_EN:false" \ +"DLL_FINE_PHASE_CODE:0" \ +"DLL_IN:1" \ +"DLL_JITTER:0" \ +"DLL_MODE:PHASE_REF_MODE" \ +"DLL_ONLY_EN:false" \ +"DLL_OUT_0:1" \ +"DLL_OUT_1:1" \ +"DLL_PRIM_PHASE:90" \ +"DLL_PRIM_PHASE_CODE:0" \ +"DLL_SEC_PHASE:90" \ +"DLL_SEC_PHASE_CODE:0" \ +"DLL_SELECTED_IN:Output2" \ +"FF_REQUIRES_LOCK_EN_0:0" \ +"GL0_0_BANKCLK_USED:false" \ +"GL0_0_BYPASS:0" \ +"GL0_0_BYPASS_EN:false" \ +"GL0_0_DEDICATED_USED:false" \ +"GL0_0_DIV:25" \ +"GL0_0_DIVSTART:0" \ +"GL0_0_DYNAMIC_PH:false" \ +"GL0_0_EXPOSE_EN:false" \ +"GL0_0_FABCLK_GATED_USED:false" \ +"GL0_0_FABCLK_USED:true" \ +"GL0_0_FREQ_SEL:false" \ +"GL0_0_IS_USED:true" \ +"GL0_0_OUT_FREQ:50" \ +"GL0_0_PHASE_INDEX:0" \ +"GL0_0_PHASE_SEL:false" \ +"GL0_0_PLL_PHASE:0" \ +"GL0_1_BANKCLK_USED:false" \ +"GL0_1_BYPASS:0" \ +"GL0_1_BYPASS_EN:false" \ +"GL0_1_DEDICATED_USED:false" \ +"GL0_1_DIV:1" \ +"GL0_1_DIVSTART:0" \ +"GL0_1_DYNAMIC_PH:false" \ +"GL0_1_EXPOSE_EN:false" \ +"GL0_1_FABCLK_USED:false" \ +"GL0_1_FREQ_SEL:false" \ +"GL0_1_IS_USED:true" \ +"GL0_1_OUT_FREQ:100" \ +"GL0_1_PHASE_INDEX:0" \ +"GL0_1_PHASE_SEL:false" \ +"GL0_1_PLL_PHASE:0" \ +"GL1_0_BANKCLK_USED:false" \ +"GL1_0_BYPASS:0" \ +"GL1_0_BYPASS_EN:false" \ +"GL1_0_DEDICATED_USED:false" \ +"GL1_0_DIV:1" \ +"GL1_0_DIVSTART:0" \ +"GL1_0_DYNAMIC_PH:false" \ +"GL1_0_EXPOSE_EN:false" \ +"GL1_0_FABCLK_GATED_USED:false" \ +"GL1_0_FABCLK_USED:true" \ +"GL1_0_FREQ_SEL:false" \ +"GL1_0_IS_USED:false" \ +"GL1_0_OUT_FREQ:100" \ +"GL1_0_PHASE_INDEX:0" \ +"GL1_0_PHASE_SEL:false" \ +"GL1_0_PLL_PHASE:0" \ +"GL1_1_BANKCLK_USED:false" \ +"GL1_1_BYPASS:0" \ +"GL1_1_BYPASS_EN:false" \ +"GL1_1_DEDICATED_USED:false" \ +"GL1_1_DIV:1" \ +"GL1_1_DIVSTART:0" \ +"GL1_1_DYNAMIC_PH:false" \ +"GL1_1_EXPOSE_EN:false" \ +"GL1_1_FABCLK_USED:false" \ +"GL1_1_FREQ_SEL:false" \ +"GL1_1_IS_USED:false" \ +"GL1_1_OUT_FREQ:0" \ +"GL1_1_PHASE_INDEX:0" \ +"GL1_1_PHASE_SEL:false" \ +"GL1_1_PLL_PHASE:0" \ +"GL2_0_BANKCLK_USED:false" \ +"GL2_0_BYPASS:0" \ +"GL2_0_BYPASS_EN:false" \ +"GL2_0_DEDICATED_USED:false" \ +"GL2_0_DIV:1" \ +"GL2_0_DIVSTART:0" \ +"GL2_0_DYNAMIC_PH:false" \ +"GL2_0_EXPOSE_EN:false" \ +"GL2_0_FABCLK_GATED_USED:false" \ +"GL2_0_FABCLK_USED:true" \ +"GL2_0_FREQ_SEL:false" \ +"GL2_0_IS_USED:false" \ +"GL2_0_OUT_FREQ:100" \ +"GL2_0_PHASE_INDEX:0" \ +"GL2_0_PHASE_SEL:false" \ +"GL2_0_PLL_PHASE:0" \ +"GL2_1_BANKCLK_USED:false" \ +"GL2_1_BYPASS:0" \ +"GL2_1_BYPASS_EN:false" \ +"GL2_1_DEDICATED_USED:false" \ +"GL2_1_DIV:1" \ +"GL2_1_DIVSTART:0" \ +"GL2_1_DYNAMIC_PH:false" \ +"GL2_1_EXPOSE_EN:false" \ +"GL2_1_FABCLK_USED:false" \ +"GL2_1_FREQ_SEL:false" \ +"GL2_1_IS_USED:false" \ +"GL2_1_OUT_FREQ:0" \ +"GL2_1_PHASE_INDEX:0" \ +"GL2_1_PHASE_SEL:false" \ +"GL2_1_PLL_PHASE:0" \ +"GL3_0_BANKCLK_USED:false" \ +"GL3_0_BYPASS:0" \ +"GL3_0_BYPASS_EN:false" \ +"GL3_0_DEDICATED_USED:false" \ +"GL3_0_DIV:1" \ +"GL3_0_DIVSTART:0" \ +"GL3_0_DYNAMIC_PH:false" \ +"GL3_0_EXPOSE_EN:false" \ +"GL3_0_FABCLK_GATED_USED:false" \ +"GL3_0_FABCLK_USED:true" \ +"GL3_0_FREQ_SEL:false" \ +"GL3_0_IS_USED:false" \ +"GL3_0_OUT_FREQ:100" \ +"GL3_0_PHASE_INDEX:0" \ +"GL3_0_PHASE_SEL:false" \ +"GL3_0_PLL_PHASE:0" \ +"GL3_1_BANKCLK_USED:false" \ +"GL3_1_BYPASS:0" \ +"GL3_1_BYPASS_EN:false" \ +"GL3_1_DEDICATED_USED:false" \ +"GL3_1_DIV:1" \ +"GL3_1_DIVSTART:0" \ +"GL3_1_DYNAMIC_PH:false" \ +"GL3_1_EXPOSE_EN:false" \ +"GL3_1_FABCLK_USED:false" \ +"GL3_1_FREQ_SEL:false" \ +"GL3_1_IS_USED:false" \ +"GL3_1_OUT_FREQ:0" \ +"GL3_1_PHASE_INDEX:0" \ +"GL3_1_PHASE_SEL:false" \ +"GL3_1_PLL_PHASE:0" \ +"PLL_ALLOW_CCC_EXT_FB:false" \ +"PLL_BANDWIDTH_0:2" \ +"PLL_BANDWIDTH_1:1" \ +"PLL_BYPASS_GO_B_0:false" \ +"PLL_BYPASS_GO_B_1:false" \ +"PLL_BYPASS_POST_0:0" \ +"PLL_BYPASS_POST_0_0:false" \ +"PLL_BYPASS_POST_0_1:false" \ +"PLL_BYPASS_POST_0_2:false" \ +"PLL_BYPASS_POST_0_3:false" \ +"PLL_BYPASS_POST_1:0" \ +"PLL_BYPASS_POST_1_0:false" \ +"PLL_BYPASS_POST_1_1:false" \ +"PLL_BYPASS_POST_1_2:false" \ +"PLL_BYPASS_POST_1_3:false" \ +"PLL_BYPASS_PRE_0:0" \ +"PLL_BYPASS_PRE_0_0:false" \ +"PLL_BYPASS_PRE_0_1:false" \ +"PLL_BYPASS_PRE_0_2:false" \ +"PLL_BYPASS_PRE_0_3:false" \ +"PLL_BYPASS_PRE_1:0" \ +"PLL_BYPASS_PRE_1_0:false" \ +"PLL_BYPASS_PRE_1_1:false" \ +"PLL_BYPASS_PRE_1_2:false" \ +"PLL_BYPASS_PRE_1_3:false" \ +"PLL_BYPASS_SEL_0:0" \ +"PLL_BYPASS_SEL_0_0:false" \ +"PLL_BYPASS_SEL_0_1:false" \ +"PLL_BYPASS_SEL_0_2:false" \ +"PLL_BYPASS_SEL_0_3:false" \ +"PLL_BYPASS_SEL_1:0" \ +"PLL_BYPASS_SEL_1_0:false" \ +"PLL_BYPASS_SEL_1_1:false" \ +"PLL_BYPASS_SEL_1_2:false" \ +"PLL_BYPASS_SEL_1_3:false" \ +"PLL_DELAY_LINE_REF_FB_0:false" \ +"PLL_DELAY_LINE_REF_FB_1:false" \ +"PLL_DELAY_LINE_USED_0:false" \ +"PLL_DELAY_LINE_USED_1:false" \ +"PLL_DELAY_STEPS_0:1" \ +"PLL_DELAY_STEPS_1:1" \ +"PLL_DLL_CASCADED_EN:false" \ +"PLL_DYNAMIC_CONTROL_EN_0:true" \ +"PLL_DYNAMIC_CONTROL_EN_1:false" \ +"PLL_DYNAMIC_RECONFIG_INTERFACE_EN_0:false" \ +"PLL_DYNAMIC_RECONFIG_INTERFACE_EN_1:false" \ +"PLL_EXPORT_PWRDWN:false" \ +"PLL_EXT_MAX_ADDR_0:128" \ +"PLL_EXT_MAX_ADDR_1:128" \ +"PLL_EXT_WAVE_SEL_0:0" \ +"PLL_EXT_WAVE_SEL_1:0" \ +"PLL_FB_CLK_0:GL0_0" \ +"PLL_FB_CLK_1:GL0_1" \ +"PLL_FEEDBACK_MODE_0:Post-VCO" \ +"PLL_FEEDBACK_MODE_1:Post-VCO" \ +"PLL_IN_FREQ_0:160" \ +"PLL_IN_FREQ_1:100" \ +"PLL_INT_MODE_EN_0:false" \ +"PLL_INT_MODE_EN_1:false" \ +"PLL_LOCK_COUNT_0:0" \ +"PLL_LOCK_COUNT_1:0" \ +"PLL_LP_REQUIRES_LOCK_EN_0:false" \ +"PLL_LP_REQUIRES_LOCK_EN_1:false" \ +"PLL_PLL_CASCADED_EN:false" \ +"PLL_PLL_CASCADED_SELECTED_CLK:Output2" \ +"PLL_POSTDIVIDERADDSOFTLOGIC_0:true" \ +"PLL_REF_CLK_SEL_0:false" \ +"PLL_REF_CLK_SEL_1:false" \ +"PLL_REFDIV_0:1" \ +"PLL_REFDIV_1:1" \ +"PLL_SPREAD_MODE_0:false" \ +"PLL_SPREAD_MODE_1:false" \ +"PLL_SSM_DEPTH_0:5" \ +"PLL_SSM_DEPTH_1:5" \ +"PLL_SSM_DIVVAL_0:1" \ +"PLL_SSM_DIVVAL_1:1" \ +"PLL_SSM_FREQ_0:32" \ +"PLL_SSM_FREQ_1:32" \ +"PLL_SSM_RAND_PATTERN_0:2" \ +"PLL_SSM_RAND_PATTERN_1:2" \ +"PLL_SSMD_EN_0:false" \ +"PLL_SSMD_EN_1:false" \ +"PLL_SYNC_CORNER_PLL:false" \ +"PLL_SYNC_EN:false" \ +"PLL_VCO_MODE_0:MIN_JITTER" \ +"PLL_VCO_MODE_1:MIN_JITTER" } +# Exporting core PF_CCC_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/PF_INIT_MONITOR_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/PF_INIT_MONITOR_0.tcl new file mode 100644 index 0000000..3d4fc2e --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/PF_INIT_MONITOR_0.tcl @@ -0,0 +1,65 @@ +# Exporting core PF_INIT_MONITOR_0 to TCL +# Exporting Create design command for core PF_INIT_MONITOR_0 +create_and_configure_core -core_vlnv {Actel:SgCore:PF_INIT_MONITOR:*} -download_core -component_name {PF_INIT_MONITOR_0} -params {\ +"BANK_0_CALIB_STATUS_ENABLED:false" \ +"BANK_0_CALIB_STATUS_SIMULATION_DELAY:1" \ +"BANK_0_RECALIBRATION_ENABLED:false" \ +"BANK_0_VDDI_STATUS_ENABLED:false" \ +"BANK_0_VDDI_STATUS_SIMULATION_DELAY:1" \ +"BANK_1_CALIB_STATUS_ENABLED:false" \ +"BANK_1_CALIB_STATUS_SIMULATION_DELAY:1" \ +"BANK_1_RECALIBRATION_ENABLED:false" \ +"BANK_1_VDDI_STATUS_ENABLED:false" \ +"BANK_1_VDDI_STATUS_SIMULATION_DELAY:1" \ +"BANK_2_CALIB_STATUS_ENABLED:false" \ +"BANK_2_CALIB_STATUS_SIMULATION_DELAY:1" \ +"BANK_2_RECALIBRATION_ENABLED:false" \ +"BANK_2_VDDI_STATUS_ENABLED:false" \ +"BANK_2_VDDI_STATUS_SIMULATION_DELAY:1" \ +"BANK_4_CALIB_STATUS_ENABLED:false" \ +"BANK_4_CALIB_STATUS_SIMULATION_DELAY:1" \ +"BANK_4_RECALIBRATION_ENABLED:false" \ +"BANK_4_VDDI_STATUS_ENABLED:false" \ +"BANK_4_VDDI_STATUS_SIMULATION_DELAY:1" \ +"BANK_5_CALIB_STATUS_ENABLED:false" \ +"BANK_5_CALIB_STATUS_SIMULATION_DELAY:1" \ +"BANK_5_RECALIBRATION_ENABLED:false" \ +"BANK_5_VDDI_STATUS_ENABLED:false" \ +"BANK_5_VDDI_STATUS_SIMULATION_DELAY:1" \ +"BANK_6_CALIB_STATUS_ENABLED:false" \ +"BANK_6_CALIB_STATUS_SIMULATION_DELAY:1" \ +"BANK_6_RECALIBRATION_ENABLED:false" \ +"BANK_6_VDDI_STATUS_ENABLED:false" \ +"BANK_6_VDDI_STATUS_SIMULATION_DELAY:1" \ +"BANK_7_CALIB_STATUS_ENABLED:false" \ +"BANK_7_CALIB_STATUS_SIMULATION_DELAY:1" \ +"BANK_7_RECALIBRATION_ENABLED:false" \ +"BANK_7_VDDI_STATUS_ENABLED:false" \ +"BANK_7_VDDI_STATUS_SIMULATION_DELAY:1" \ +"DEVICE_INIT_DONE_SIMULATION_DELAY:7" \ +"FABRIC_POR_N_SIMULATION_DELAY:1" \ +"PCIE_INIT_DONE_SIMULATION_DELAY:4" \ +"SHOW_BANK_0_CALIB_STATUS_ENABLED:true" \ +"SHOW_BANK_0_RECALIBRATION_ENABLED:false" \ +"SHOW_BANK_0_VDDI_STATUS_ENABLED:true" \ +"SHOW_BANK_1_CALIB_STATUS_ENABLED:true" \ +"SHOW_BANK_1_RECALIBRATION_ENABLED:false" \ +"SHOW_BANK_1_VDDI_STATUS_ENABLED:true" \ +"SHOW_BANK_2_CALIB_STATUS_ENABLED:true" \ +"SHOW_BANK_2_RECALIBRATION_ENABLED:false" \ +"SHOW_BANK_2_VDDI_STATUS_ENABLED:true" \ +"SHOW_BANK_4_CALIB_STATUS_ENABLED:true" \ +"SHOW_BANK_4_RECALIBRATION_ENABLED:false" \ +"SHOW_BANK_4_VDDI_STATUS_ENABLED:true" \ +"SHOW_BANK_5_CALIB_STATUS_ENABLED:true" \ +"SHOW_BANK_5_RECALIBRATION_ENABLED:false" \ +"SHOW_BANK_5_VDDI_STATUS_ENABLED:true" \ +"SHOW_BANK_6_CALIB_STATUS_ENABLED:true" \ +"SHOW_BANK_6_RECALIBRATION_ENABLED:false" \ +"SHOW_BANK_6_VDDI_STATUS_ENABLED:true" \ +"SHOW_BANK_7_CALIB_STATUS_ENABLED:true" \ +"SHOW_BANK_7_RECALIBRATION_ENABLED:false" \ +"SHOW_BANK_7_VDDI_STATUS_ENABLED:true" \ +"SRAM_INIT_DONE_SIMULATION_DELAY:6" \ +"USRAM_INIT_DONE_SIMULATION_DELAY:5" } +# Exporting Component Description of PF_INIT_MONITOR_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/PF_OSC_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/PF_OSC_0.tcl new file mode 100644 index 0000000..6cac953 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/PF_OSC_0.tcl @@ -0,0 +1,10 @@ +# Exporting core PF_OSC_0 to TCL +# Exporting Create design command for core PF_OSC_0 +create_and_configure_core -core_vlnv {Actel:SgCore:PF_OSC:*} -download_core -component_name {PF_OSC_0} -params {\ +"RCOSC_2MHZ_CLK_DIV_EN:false" \ +"RCOSC_2MHZ_GL_EN:false" \ +"RCOSC_2MHZ_NGMUX_EN:false" \ +"RCOSC_160MHZ_CLK_DIV_EN:false" \ +"RCOSC_160MHZ_GL_EN:true" \ +"RCOSC_160MHZ_NGMUX_EN:false" } +# Exporting core PF_OSC_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/PF_SRAM_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/PF_SRAM_0.tcl new file mode 100644 index 0000000..e453466 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/PF_SRAM_0.tcl @@ -0,0 +1,25 @@ +# Exporting core PF_SRAM_0 to TCL +# Create design TCL command for core PF_SRAM_0 +create_and_configure_core -core_vlnv {Actel:SystemBuilder:PF_SRAM_AHBL_AXI:*} -download_core -component_name {PF_SRAM_0} -params {\ +"AXI4_AWIDTH:32" \ +"AXI4_DWIDTH:32" \ +"AXI4_IDWIDTH:8" \ +"AXI4_IFTYPE_RD:T" \ +"AXI4_IFTYPE_WR:T" \ +"AXI4_WRAP_SUPPORT:F" \ +"BYTEENABLES:1" \ +"BYTE_ENABLE_WIDTH:4" \ +"B_REN_POLARITY:2" \ +"CASCADE:1" \ +"ECC_OPTIONS:0" \ +"FABRIC_INTERFACE_TYPE:0" \ +"IMPORT_FILE:" \ +"INIT_RAM:F" \ +"LPM_HINT:0" \ +"PIPELINE_OPTIONS:1" \ +"RDEPTH:32768" \ +"RWIDTH:40" \ +"USE_NATIVE_INTERFACE:F" \ +"WDEPTH:32768" \ +"WWIDTH:40" } +# Exporting core PF_SRAM_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/PF_SRAM_AXI4_0.tcl b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/PF_SRAM_AXI4_0.tcl new file mode 100644 index 0000000..5a612bb --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/components/SHARED_COMPONENTS/PF_SRAM_AXI4_0.tcl @@ -0,0 +1,25 @@ +# Exporting core PF_SRAM_AXI4_0 to TCL +# Create design TCL command for core PF_SRAM_AXI4_0 +create_and_configure_core -core_vlnv {Actel:SystemBuilder:PF_SRAM_AHBL_AXI:*} -download_core -component_name {PF_SRAM_AXI4_0} -params {\ +"AXI4_AWIDTH:32" \ +"AXI4_DWIDTH:32" \ +"AXI4_IDWIDTH:8" \ +"AXI4_IFTYPE_RD:T" \ +"AXI4_IFTYPE_WR:T" \ +"AXI4_WRAP_SUPPORT:F" \ +"BYTEENABLES:1" \ +"BYTE_ENABLE_WIDTH:4" \ +"B_REN_POLARITY:2" \ +"CASCADE:1" \ +"ECC_OPTIONS:0" \ +"FABRIC_INTERFACE_TYPE:1" \ +"IMPORT_FILE:" \ +"INIT_RAM:F" \ +"LPM_HINT:0" \ +"PIPELINE_OPTIONS:1" \ +"RDEPTH:32768" \ +"RWIDTH:40" \ +"USE_NATIVE_INTERFACE:F" \ +"WDEPTH:32768" \ +"WWIDTH:40" } +# Exporting core PF_SRAM_0 to TCL done diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/constraints/fp/ccc_fp.pdc b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/constraints/fp/ccc_fp.pdc new file mode 100644 index 0000000..6332ce7 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/constraints/fp/ccc_fp.pdc @@ -0,0 +1 @@ +set_location -inst_name {PF_CCC_0_inst_0/PF_CCC_0_0/pll_inst_0} -location PLL0_SE \ No newline at end of file diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/constraints/io/io_constraints.pdc b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/constraints/io/io_constraints.pdc new file mode 100644 index 0000000..4226a1b --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/constraints/io/io_constraints.pdc @@ -0,0 +1,505 @@ +# Microsemi I/O Physical Design Constraints file + +# User I/O Constraints file + +# Version: PolarFire v2.3 12.200.35.9 + +# Family: PolarFire , Die: MPF300T(ES) , Package: FCG484 + +# Date generated: Mon Jan 07 16:35:59 2019 + + +# +# User Locked I/O Bank Settings +# + +set_iobank -bank_name Bank5 \ + -vcci 3.30 \ + -fixed true \ + -update_iostd true + + +# +# Unlocked I/O Bank Settings +# The I/O Bank Settings can be locked by directly editing this file +# or by making changes in the I/O Attribute Editor +# + + +# +# User Locked I/O settings +# + +# -- User PushButtons I/O -- # + +set_io -port_name {PUSH_BTN_1} \ + -pin_name E13 \ + -fixed true \ + -DIRECTION INPUT + +set_io -port_name {PUSH_BTN_2} \ + -pin_name E14 \ + -fixed true \ + -DIRECTION INPUT + +set_io -port_name USER_RST \ + -pin_name F5 \ + -fixed true \ + -DIRECTION INPUT + + +# -- LEDs I/O --# + +set_io -port_name {LED_1} \ + -pin_name D7 \ + -fixed true \ + -DIRECTION OUTPUT + +set_io -port_name {LED_2} \ + -pin_name D8 \ + -fixed true \ + -DIRECTION OUTPUT + +set_io -port_name {LED_3} \ + -pin_name D9 \ + -fixed true \ + -DIRECTION OUTPUT + +set_io -port_name {LED_4} \ + -pin_name D6 \ + -fixed true \ + -DIRECTION OUTPUT + + +# -- UART RX/TX -- # + +set_io -port_name RX \ + -pin_name F16 \ + -fixed true \ + -DIRECTION INPUT + + +set_io -port_name TX \ + -pin_name F17 \ + -fixed true \ + -DIRECTION OUTPUT + + +# +# Dedicated Peripheral I/O Settings +# + + +set_io -port_name TCK \ + -pin_name F8 \ + -DIRECTION INPUT + + +set_io -port_name TDI \ + -pin_name G8 \ + -DIRECTION INPUT + + +set_io -port_name TDO \ + -pin_name F6 \ + -DIRECTION OUTPUT + + +set_io -port_name TMS \ + -pin_name F7 \ + -DIRECTION INPUT + + +set_io -port_name TRSTB \ + -pin_name G7 \ + -DIRECTION INPUT + + +# Microsemi I/O Physical Design Constraints file + +# User I/O Constraints file + +# Version: PolarFire v2.3 12.200.35.9 + +# Family: PolarFire , Die: MPF300T_ES , Package: FCG484 + +# Date generated: Sun Jan 13 21:06:20 2019 +# +# Unlocked I/O settings +# The I/Os in this section are unplaced or placed but are not locked +# the other listed attributes have been applied +# + +#set_io -port_name CLK1_50M \ + -pin_name R1 \ + -fixed true \ + -io_std LVCMOS25 \ + -DIRECTION INPUT +#set_io -port_name REF_CLK_0 \ + -io_std LVCMOS18 \ + -DIRECTION INPUT + +# +# User Locked I/O settings +# + +#set_io -port_name AND1_Y \ + -pin_name A3 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[0]} \ + -pin_name U5 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[1]} \ + -pin_name U4 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[2]} \ + -pin_name V4 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[3]} \ + -pin_name W3 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[4]} \ + -pin_name V5 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[5]} \ + -pin_name W4 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[6]} \ + -pin_name Y3 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[7]} \ + -pin_name AA3 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[8]} \ + -pin_name Y4 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[9]} \ + -pin_name Y5 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[10]} \ + -pin_name AA2 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[11]} \ + -pin_name AB2 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[12]} \ + -pin_name V6 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[13]} \ + -pin_name W6 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {A[14]} \ + -pin_name AB3 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {BA[0]} \ + -pin_name V7 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {BA[1]} \ + -pin_name Y6 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {BA[2]} \ + -pin_name U7 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name CAS_N \ + -pin_name AA5 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name CK0 \ + -pin_name V2 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name CK0_N \ + -pin_name W2 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name CKE \ + -pin_name W8 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name CS_N \ + -pin_name W7 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name CTRLR_READY \ + -pin_name D6 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name DEVICE_INIT_DONE \ + -pin_name A13 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {DM[0]} \ + -pin_name Y9 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {DM[1]} \ + -pin_name R15 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name {DQS[0]} \ + -pin_name T10 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQS[1]} \ + -pin_name R13 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQS_N[0]} \ + -pin_name U10 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQS_N[1]} \ + -pin_name T12 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[0]} \ + -pin_name T7 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[1]} \ + -pin_name T8 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[2]} \ + -pin_name U8 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[3]} \ + -pin_name U9 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[4]} \ + -pin_name R10 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[5]} \ + -pin_name V9 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[6]} \ + -pin_name V10 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[7]} \ + -pin_name W9 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[8]} \ + -pin_name V14 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[9]} \ + -pin_name U14 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[10]} \ + -pin_name R12 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[11]} \ + -pin_name T11 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[12]} \ + -pin_name U15 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[13]} \ + -pin_name T13 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[14]} \ + -pin_name U13 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name {DQ[15]} \ + -pin_name T15 \ + -fixed true \ + -DIRECTION INOUT + + +#set_io -port_name ODT \ + -pin_name AA7 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name PLL_LOCK_0 \ + -pin_name A12 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name RAS_N \ + -pin_name AA6 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name RESET_N \ + -pin_name AB7 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name SHIELD0 \ + -pin_name R9 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name SHIELD1 \ + -pin_name V15 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name WE_N \ + -pin_name AB5 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name reset_sync_0 \ + -pin_name A16 \ + -fixed true \ + -DIRECTION OUTPUT + + +#set_io -port_name reset_sync_1 \ + -pin_name A15 \ + -fixed true \ + -DIRECTION OUTPUT + + + +# +# Dedicated Peripheral I/O Settings +# + + +# +# Unlocked I/O settings +# The I/Os in this section are unplaced or placed but are not locked +# the other listed attributes have been applied +# + + +# +#Ports using Dedicated Pins + +# + diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/constraints/io_jtag_constraints.sdc b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/constraints/io_jtag_constraints.sdc new file mode 100644 index 0000000..a5644a4 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/Libero design/import/constraints/io_jtag_constraints.sdc @@ -0,0 +1,7 @@ +create_clock -name { TCK } \ +-period 166.67 \ +-waveform { 0 83.33 } \ +[ get_ports { TCK } ] + +# JTAG and Mi-V clocks are independent - adding asynchronous clock group +set_clock_groups -name {async1} -asynchronous -group [ get_clocks { PF_CCC_0_inst_0/PF_CCC_0_0/pll_inst_0/OUT0 } ] -group [ get_clocks { TCK } ] \ No newline at end of file diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/design description/README.md b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/design description/README.md new file mode 100644 index 0000000..e2dca3b --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design/design description/README.md @@ -0,0 +1,3 @@ +# Design Description + + The Libero generated design description will be stored here. \ No newline at end of file diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design_config/fpga_design_config.h b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design_config/fpga_design_config.h new file mode 100644 index 0000000..357942e --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/fpga_design_config/fpga_design_config.h @@ -0,0 +1,181 @@ +/******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file sample_fpga_design_config.h + * @author Microchip FPGA Embedded Systems Solutions + * @brief Sample design configuration settings + * + */ + /*========================================================================*//** + @mainpage + Example file detailing how the fpga_design_config.h should be constructed + for the SoftConsole project targeted for Mi-V processors. + + @section intro_sec Introduction + The SoftConsole project targeted for Mi-V processors now have an improved + folder structure. Detailed description of the folder structure is available + at https://github.com/Mi-V-Soft-RISC-V/miv-rv32-documentation. + + The fpga_design_config.h must be stored as shown below + /boards//fpga_design_config.h + + Currently this file must be hand crafted when using the Mi-V Soft Processor. + In future, all the design and soft IP configurations will be automatically + generated from the Libero design description data. + + You can use this sample file as an example. + Rename this file from sample_fpga_design_config.h to fpga_design_config.h + and then customize it per your hardware design. + + @section Project configuration Instructions + 1. Change SYS_CLK_FREQ define to frequency of Mi-V Soft processor clock + 2 Add all the soft IP core BASE addresses + 3. Add the peripheral Core Interrupts to Mi-V Soft processor IRQ number + mappings + 4. Define MSCC_STDIO_UART_BASE_ADDR if you want a CoreUARTapb mapped to + STDIO + + **NOTE** + In the legacy folder structures, the file hw_config.h as was used at the + root of the project folder. This file is now depricated. + +*//*=========================================================================*/ + +#ifndef FPGA_DESIGN_CONFIG_H_ +#define FPGA_DESIGN_CONFIG_H_ + +/***************************************************************************//** + * Soft-processor clock definition + * This is the only clock brought over from the Mi-V Libero design. + */ +#ifndef SYS_CLK_FREQ +#define SYS_CLK_FREQ 50000000UL +#endif + +/***************************************************************************//** + * MTIME prescaler definition + * The MiV soft-cores include, by default, a prescaler (100 is the default value) + * on the MTIME on the hardware. To take this prescaler into account and make + * the Renode and the hardware timings match, we set the macro RENODE_SIMULATION + * to 1 if the demo is run on Renode, to 0 otherwise. + */ + +#define RENODE_SIMULATION 0 + +#ifndef TICK_COUNT_PRESCALER + #define TICK_COUNT_PRESCALER 100UL +#endif + +/***************************************************************************//** + * Peripheral base addresses. + * Format of define is: + * __BASE_ADDR + * The field is optional if there is only one instance of the core + * in the design + * MIV_ESS is an extended peripheral subsystem IP core with peripherals + * connections as defined below. + * The system can be further extended by attaching APB peripherals to the + * empty APB slots. + */ +#define MIV_ESS_PLIC_BASE_ADDR 0x70000000UL +#define COREUARTAPB0_BASE_ADDR 0x71000000UL +#define MIV_MTIMER_BASE_ADDR 0x72000000UL +#define MIV_ESS_APBSLOT3_BASE_ADDR 0x73000000UL +#define MIV_ESS_APBSLOT4_BASE_ADDR 0x74000000UL +#define COREGPIO_OUT_BASE_ADDR 0x75000000UL +#define CORESPI_BASE_ADDR 0x76000000UL +#define MIV_ESS_uDMA_BASE_ADDR 0x78000000UL +#define MIV_ESS_WDOG_BASE_ADDR 0x79000000UL +#define MIV_ESS_I2C_BASE_ADDR 0x7A000000UL +#define MIV_ESS_APBSLOTB_BASE_ADDR 0x7B000000UL +#define MIV_ESS_APBSLOTC_BASE_ADDR 0x7C000000UL +#define MIV_ESS_APBSLOTD_BASE_ADDR 0x7D000000UL +#define MIV_ESS_APBSLOTE_BASE_ADDR 0x7E000000UL +#define MIV_ESS_APBSLOTF_BASE_ADDR 0x7F000000UL + +/***************************************************************************//** + * Peripheral Interrupts are mapped to the corresponding Mi-V Soft processor + * interrupt in the Libero design. + * + * On the legacy RV32 cores, there can be up to 31 external interrupts (IRQ[30:0] + * pins). The legacy RV32 Soft processor external interrupts are defined in the + miv_rv32_plic.h + * + * These are of the form + * typedef enum +{ + NoInterrupt_IRQn = 0, + External_1_IRQn = 1, + External_2_IRQn = 2, + . + . + . + External_31_IRQn = 31 +} IRQn_Type; + + On the legacy RV32 processors, the PLIC identifies the interrupt and passes it + on to the processor core. The interrupt 0 is not used. The pin IRQ[0] should + map to External_1_IRQn likewise IRQ[30] should map to External_31_IRQn + +e.g + +#define TIMER0_IRQn External_30_IRQn +#define TIMER1_IRQn External_31_IRQn + + The MIV_RV32 soft processor has up to six optional system interrupts, MSYS_EI[n] + in addition to one EXT_IRQ. + The MIV_RV32 does not have an inbuilt PLIC and all the interrupts are directly + delivered to the processor core, hence unlike legacy RV32 cores, no interrupt + number mapping is necessary on MIV_RV32 core. + */ + +/**************************************************************************** + * Baud value to achieve a 115200 baud rate with system clock defined by + * SYS_CLK_FREQ. + * This value is calculated using the following equation: + * BAUD_VALUE = (CLOCK / (16 * BAUD_RATE)) - 1 + *****************************************************************************/ +#define BAUD_VALUE_115200 ((SYS_CLK_FREQ / (16 * 115200)) - 1) + +/****************************************************************************** + * Baud value to achieve a 57600 baud rate with system clock defined by + * SYS_CLK_FREQ. + * This value is calculated using the following equation: + * BAUD_VALUE = (CLOCK / (16 * BAUD_RATE)) - 1 + *****************************************************************************/ + #define BAUD_VALUE_57600 ((SYS_CLK_FREQ / (16 * 57600)) - 1) + +/***************************************************************************//** + * Define MSCC_STDIO_THRU_CORE_UART_APB in the project settings if you want the + * standard IOs to be redirected to a terminal via UART. + */ +#ifdef MSCC_STDIO_THRU_CORE_UART_APB +/* + * A base address mapping for the STDIO printf/scanf mapping to CortUARTapb + * must be provided if it is being used + * + * e.g. #define MSCC_STDIO_UART_BASE_ADDR COREUARTAPB1_BASE_ADDR + */ +#define MSCC_STDIO_UART_BASE_ADDR COREUARTAPB0_BASE_ADDR + +#ifndef MSCC_STDIO_UART_BASE_ADDR +#error MSCC_STDIO_UART_BASE_ADDR not defined- e.g. #define MSCC_STDIO_UART_BASE_ADDR COREUARTAPB1_BASE_ADDR +#endif + +#ifndef MSCC_STDIO_BAUD_VALUE +/* + * The MSCC_STDIO_BAUD_VALUE define should be set in your project's settings to + * specify the baud value used by the standard output CoreUARTapb instance for + * generating the UART's baud rate if you want a different baud rate from the + * default of 115200 baud + */ +#define MSCC_STDIO_BAUD_VALUE 115200 +#endif /*MSCC_STDIO_BAUD_VALUE*/ + +#endif /* end of MSCC_STDIO_THRU_CORE_UART_APB */ +/******************************************************************************* + * End of user edit section + */ +#endif /* FPGA_DESIGN_CONFIG_H_ */ diff --git a/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/platform_config/linker/miv-rv32-ram.ld b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/platform_config/linker/miv-rv32-ram.ld new file mode 100644 index 0000000..ae2f903 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/boards/avalanche-board/miv-rv32-design/platform_config/linker/miv-rv32-ram.ld @@ -0,0 +1,152 @@ +/******************************************************************************* + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * file name : miv-rv32-ram.ld + * Mi-V soft processor linker script for creating a SoftConsole downloadable + * debug image executing in SRAM. + * + * This linker script assumes that a RAM is connected at on Mi-V soft processor + * memory space pointed by the reset vector address. + * + * NOTE : Modify the memory section address and the size according to your + * Libero design. + * For example: + * 1) If you want to download and step debug at a different RAM memory address in + * your design (For example TCM base address) than the one provided in this file. + * 2) The MIV_RV32, when used with MIV_ESS IP, provides ways to copy the executable + * HEX file from external Non-Volatile memory into the TCM at reset. In this + * case your executable must be linked to the TCM address. + * + * To know more about the memory map of the MIV_RV32 based Libero design, open + * the MIV_RV32 IP configurator and look for "Reset Vector Address" and the + * "Memory Map" tab. + * + */ + +OUTPUT_ARCH( "riscv" ) +ENTRY(_start) + +MEMORY +{ + ram (rwx) : ORIGIN = 0x80000000, LENGTH = 256k +} + +STACK_SIZE = 2k; /* needs to be calculated for your application */ +HEAP_SIZE = 4; /* needs to be calculated for your application */ + +SECTIONS +{ + .entry : ALIGN(0x10) + { + KEEP (*(SORT_NONE(.entry))) + . = ALIGN(0x10); + } > ram + + .text : ALIGN(0x10) + { + *(.text .text.* .gnu.linkonce.t.*) + *(.plt) + . = ALIGN(0x10); + + KEEP (*crtbegin.o(.ctors)) + KEEP (*(EXCLUDE_FILE (*crtend.o) .ctors)) + KEEP (*(SORT(.ctors.*))) + KEEP (*crtend.o(.ctors)) + KEEP (*crtbegin.o(.dtors)) + KEEP (*(EXCLUDE_FILE (*crtend.o) .dtors)) + KEEP (*(SORT(.dtors.*))) + KEEP (*crtend.o(.dtors)) + + *(.rodata .rodata.* .gnu.linkonce.r.*) + *(.gcc_except_table) + *(.eh_frame_hdr) + *(.eh_frame) + + KEEP (*(.init)) + KEEP (*(.fini)) + + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP (*(.preinit_array)) + PROVIDE_HIDDEN (__preinit_array_end = .); + PROVIDE_HIDDEN (__init_array_start = .); + KEEP (*(SORT(.init_array.*))) + KEEP (*(.init_array)) + PROVIDE_HIDDEN (__init_array_end = .); + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP (*(.fini_array)) + KEEP (*(SORT(.fini_array.*))) + PROVIDE_HIDDEN (__fini_array_end = .); + . = ALIGN(0x10); + + } > ram + + /* short/global data section */ + .sdata : ALIGN(0x10) + { + __sdata_load = LOADADDR(.sdata); + __sdata_start = .; + PROVIDE( __global_pointer$ = . + 0x800); + *(.srodata.cst16) *(.srodata.cst8) *(.srodata.cst4) *(.srodata.cst2) + *(.srodata*) + *(.sdata .sdata.* .gnu.linkonce.s.*) + . = ALIGN(0x10); + __sdata_end = .; + } > ram + + /* data section */ + .data : ALIGN(0x10) + { + __data_load = LOADADDR(.data); + __data_start = .; + *(.got.plt) *(.got) + *(.shdata) + *(.data .data.* .gnu.linkonce.d.*) + . = ALIGN(0x10); + __data_end = .; + } > ram + + /* sbss section */ + .sbss : ALIGN(0x10) + { + __sbss_start = .; + *(.sbss .sbss.* .gnu.linkonce.sb.*) + *(.scommon) + . = ALIGN(0x10); + __sbss_end = .; + } > ram + + /* sbss section */ + .bss : ALIGN(0x10) + { + __bss_start = .; + *(.shbss) + *(.bss .bss.* .gnu.linkonce.b.*) + *(COMMON) + . = ALIGN(0x10); + __bss_end = .; + } > ram + + /* End of uninitialized data segment */ + _end = .; + + .heap : ALIGN(0x10) + { + __heap_start = .; + . += HEAP_SIZE; + __heap_end = .; + . = ALIGN(0x10); + _heap_end = __heap_end; + } > ram + + .stack : ALIGN(0x10) + { + __stack_bottom = .; + . += STACK_SIZE; + __stack_top = .; + _sp = .; + __freertos_irq_stack_top = .; + } > ram +} + diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/AbortDelay.c b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/AbortDelay.c new file mode 100644 index 0000000..c3098db --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/AbortDelay.c @@ -0,0 +1,800 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +/* + * This file contains some test scenarios that ensure tasks respond correctly + * to xTaskAbortDelay() calls. It also ensures tasks return the correct state + * of eBlocked when blocked indefinitely in both the case where a task is + * blocked on an object and when a task is blocked on a notification. + */ + +/* Standard includes. */ +#include "limits.h" + +/* Kernel includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" +#include "semphr.h" +#include "event_groups.h" +#include "stream_buffer.h" + +/* Demo includes. */ +#include "AbortDelay.h" + +/* This file can only be used if the functionality it tests is included in the + * build. Remove the whole file if this is not the case. */ +#if ( INCLUDE_xTaskAbortDelay == 1 ) + + #if ( INCLUDE_xTaskGetHandle != 1 ) + #error This test file uses the xTaskGetHandle() API function so INCLUDE_xTaskGetHandle must be set to 1 in FreeRTOSConfig.h. + #endif + +/* Task priorities. Allow these to be overridden. */ + #ifndef abtCONTROLLING_PRIORITY + #define abtCONTROLLING_PRIORITY ( configMAX_PRIORITIES - 3 ) + #endif + + #ifndef abtBLOCKING_PRIORITY + #define abtBLOCKING_PRIORITY ( configMAX_PRIORITIES - 2 ) + #endif + +/* The tests that are performed. */ + #define abtNOTIFY_WAIT_ABORTS 0 + #define abtNOTIFY_TAKE_ABORTS 1 + #define abtDELAY_ABORTS 2 + #define abtDELAY_UNTIL_ABORTS 3 + #define abtSEMAPHORE_TAKE_ABORTS 4 + #define abtEVENT_GROUP_ABORTS 5 + #define abtQUEUE_SEND_ABORTS 6 + #define abtSTREAM_BUFFER_RECEIVE 7 + #define abtMAX_TESTS 8 + +/*-----------------------------------------------------------*/ + +/* + * The two test tasks. The controlling task specifies which test to executed. + * More information is provided in the comments within the tasks. + */ + static void prvControllingTask( void * pvParameters ); + static void prvBlockingTask( void * pvParameters ); + +/* + * Test functions called by the blocking task. Each function follows the same + * pattern, but the way the task blocks is different in each case. + * + * In each function three blocking calls are made. The first and third + * blocking call is expected to time out, while the middle blocking call is + * expected to be aborted by the controlling task half way through the block + * time. + */ + static void prvTestAbortingTaskNotifyWait( void ); + static void prvTestAbortingTaskNotifyTake( void ); + static void prvTestAbortingTaskDelay( void ); + static void prvTestAbortingTaskDelayUntil( void ); + static void prvTestAbortingSemaphoreTake( void ); + static void prvTestAbortingEventGroupWait( void ); + static void prvTestAbortingQueueSend( void ); + static void prvTestAbortingStreamBufferReceive( void ); + +/* + * Performs a few tests to cover code paths not otherwise covered by the continuous + * tests. + */ + static void prvPerformSingleTaskTests( void ); + +/* + * Checks the amount of time a task spent in the Blocked state is within the + * expected bounds. + */ + static void prvCheckExpectedTimeIsWithinAnAcceptableMargin( TickType_t xStartTime, + TickType_t xExpectedBlockTime ); + +/*-----------------------------------------------------------*/ + +/* Used to ensure that tasks are still executing without error. */ + static volatile BaseType_t xControllingCycles = 0, xBlockingCycles = 0; + static volatile BaseType_t xErrorOccurred = pdFALSE; + +/* Each task needs to know the other tasks handle so they can send signals to + * each other. The handle is obtained from the task's name. */ + static const char * pcControllingTaskName = "AbtCtrl", * pcBlockingTaskName = "AbtBlk"; + +/* The maximum amount of time a task will block for. */ + const TickType_t xMaxBlockTime = pdMS_TO_TICKS( 100 ); + const TickType_t xHalfMaxBlockTime = pdMS_TO_TICKS( 50 ); + +/* The actual block time is dependent on the priority of other tasks in the + * system so the actual block time might be greater than that expected, but it + * should be within an acceptable upper bound. */ + const TickType_t xAllowableMargin = pdMS_TO_TICKS( 7 ); + +/*-----------------------------------------------------------*/ + + void vCreateAbortDelayTasks( void ) + { + /* Create the two test tasks described above. */ + xTaskCreate( prvControllingTask, pcControllingTaskName, configMINIMAL_STACK_SIZE, NULL, abtCONTROLLING_PRIORITY, NULL ); + xTaskCreate( prvBlockingTask, pcBlockingTaskName, configMINIMAL_STACK_SIZE, NULL, abtBLOCKING_PRIORITY, NULL ); + } +/*-----------------------------------------------------------*/ + + static void prvControllingTask( void * pvParameters ) + { + TaskHandle_t xBlockingTask; + uint32_t ulTestToPerform = abtNOTIFY_WAIT_ABORTS; + TickType_t xTimeAtStart; + const TickType_t xStartMargin = 2UL; + + /* Just to remove compiler warnings. */ + ( void ) pvParameters; + + xBlockingTask = xTaskGetHandle( pcBlockingTaskName ); + configASSERT( xBlockingTask ); + + for( ; ; ) + { + /* Tell the secondary task to perform the next test. */ + xTimeAtStart = xTaskGetTickCount(); + xTaskNotify( xBlockingTask, ulTestToPerform, eSetValueWithOverwrite ); + + /* The secondary task has a higher priority, so will now be in the + * Blocked state to wait for a maximum of xMaxBlockTime. It expects that + * period to complete with a timeout. It will then block for + * xMaxBlockTimeAgain, but this time it expects to the block time to abort + * half way through. Block until it is time to send the abort to the + * secondary task. xStartMargin is used because this task takes timing + * from the beginning of the test, whereas the blocking task takes timing + * from the entry into the Blocked state - and as the tasks run at + * different priorities, there may be some discrepancy. Also, temporarily + * raise the priority of the controlling task to that of the blocking + * task to minimise discrepancies. */ + vTaskPrioritySet( NULL, abtBLOCKING_PRIORITY ); + vTaskDelay( xMaxBlockTime + xHalfMaxBlockTime + xStartMargin ); + + if( xTaskAbortDelay( xBlockingTask ) != pdPASS ) + { + xErrorOccurred = pdTRUE; + } + + /* Reset the priority to the normal controlling priority. */ + vTaskPrioritySet( NULL, abtCONTROLLING_PRIORITY ); + + /* Now wait to be notified that the secondary task has completed its + * test. */ + ulTaskNotifyTake( pdTRUE, portMAX_DELAY ); + + /* Did the entire test run for the expected time, which is two full + * block times plus the half block time caused by calling + * xTaskAbortDelay()? */ + prvCheckExpectedTimeIsWithinAnAcceptableMargin( xTimeAtStart, ( xMaxBlockTime + xMaxBlockTime + xHalfMaxBlockTime ) ); + + /* Move onto the next test. */ + ulTestToPerform++; + + if( ulTestToPerform >= abtMAX_TESTS ) + { + ulTestToPerform = 0; + } + + /* To indicate this task is still executing. */ + xControllingCycles++; + } + } +/*-----------------------------------------------------------*/ + + static void prvBlockingTask( void * pvParameters ) + { + TaskHandle_t xControllingTask; + uint32_t ulNotificationValue; + const uint32_t ulMax = 0xffffffffUL; + + /* Just to remove compiler warnings. */ + ( void ) pvParameters; + + /* Start by performing a few tests to cover code not exercised in the loops + * below. */ + prvPerformSingleTaskTests(); + + xControllingTask = xTaskGetHandle( pcControllingTaskName ); + configASSERT( xControllingTask ); + + for( ; ; ) + { + /* Wait to be notified of the test that is to be performed next. */ + xTaskNotifyWait( 0, ulMax, &ulNotificationValue, portMAX_DELAY ); + + switch( ulNotificationValue ) + { + case abtNOTIFY_WAIT_ABORTS: + prvTestAbortingTaskNotifyWait(); + break; + + case abtNOTIFY_TAKE_ABORTS: + prvTestAbortingTaskNotifyTake(); + break; + + case abtDELAY_ABORTS: + prvTestAbortingTaskDelay(); + break; + + case abtDELAY_UNTIL_ABORTS: + prvTestAbortingTaskDelayUntil(); + break; + + case abtSEMAPHORE_TAKE_ABORTS: + prvTestAbortingSemaphoreTake(); + break; + + case abtEVENT_GROUP_ABORTS: + prvTestAbortingEventGroupWait(); + break; + + case abtQUEUE_SEND_ABORTS: + prvTestAbortingQueueSend(); + break; + + case abtSTREAM_BUFFER_RECEIVE: + prvTestAbortingStreamBufferReceive(); + break; + + default: + /* Should not get here. */ + break; + } + + /* Let the primary task know the test is complete. */ + xTaskNotifyGive( xControllingTask ); + + /* To indicate this task is still executing. */ + xBlockingCycles++; + } + } +/*-----------------------------------------------------------*/ + + static void prvPerformSingleTaskTests( void ) + { + TaskHandle_t xThisTask; + BaseType_t xReturned; + + /* Try unblocking this task using both the task and ISR versions of the API - + * both should return false as this task is not blocked. */ + xThisTask = xTaskGetCurrentTaskHandle(); + + xReturned = xTaskAbortDelay( xThisTask ); + + if( xReturned != pdFALSE ) + { + xErrorOccurred = pdTRUE; + } + } +/*-----------------------------------------------------------*/ + + static void prvTestAbortingTaskDelayUntil( void ) + { + TickType_t xTimeAtStart, xLastBlockTime; + BaseType_t xReturned; + + /* Note the time before the delay so the length of the delay is known. */ + xTimeAtStart = xTaskGetTickCount(); + + /* Take a copy of the time as it is updated in the call to + * xTaskDelayUntil() but its original value is needed to determine the actual + * time spend in the Blocked state. */ + xLastBlockTime = xTimeAtStart; + + /* This first delay should just time out. */ + xReturned = xTaskDelayUntil( &xLastBlockTime, xMaxBlockTime ); + prvCheckExpectedTimeIsWithinAnAcceptableMargin( xTimeAtStart, xMaxBlockTime ); + configASSERT( xReturned == pdTRUE ); + + /* Remove compiler warning about value being set but not used in the case + * configASSERT() is not defined. */ + ( void ) xReturned; + + /* This second delay should be aborted by the primary task half way + * through. Again take a copy of the time as it is updated in the call to + * vTaskDelayUntil() buts its original value is needed to determine the amount + * of time actually spent in the Blocked state. This uses vTaskDelayUntil() + * in place of xTaskDelayUntil() for test coverage. */ + xTimeAtStart = xTaskGetTickCount(); + xLastBlockTime = xTimeAtStart; + vTaskDelayUntil( &xLastBlockTime, xMaxBlockTime ); + prvCheckExpectedTimeIsWithinAnAcceptableMargin( xTimeAtStart, xHalfMaxBlockTime ); + + /* As with the other tests, the third block period should not time out. */ + xTimeAtStart = xTaskGetTickCount(); + xLastBlockTime = xTimeAtStart; + xReturned = xTaskDelayUntil( &xLastBlockTime, xMaxBlockTime ); + prvCheckExpectedTimeIsWithinAnAcceptableMargin( xTimeAtStart, xMaxBlockTime ); + configASSERT( xReturned == pdTRUE ); + + /* Remove compiler warning about value being set but not used in the case + * configASSERT() is not defined. */ + ( void ) xReturned; + } +/*-----------------------------------------------------------*/ + + static void prvTestAbortingTaskDelay( void ) + { + TickType_t xTimeAtStart; + + /* Note the time before the delay so the length of the delay is known. */ + xTimeAtStart = xTaskGetTickCount(); + + /* This first delay should just time out. */ + vTaskDelay( xMaxBlockTime ); + prvCheckExpectedTimeIsWithinAnAcceptableMargin( xTimeAtStart, xMaxBlockTime ); + + /* Note the time before the delay so the length of the delay is known. */ + xTimeAtStart = xTaskGetTickCount(); + + /* This second delay should be aborted by the primary task half way + * through. */ + vTaskDelay( xMaxBlockTime ); + prvCheckExpectedTimeIsWithinAnAcceptableMargin( xTimeAtStart, xHalfMaxBlockTime ); + + /* Note the time before the delay so the length of the delay is known. */ + xTimeAtStart = xTaskGetTickCount(); + + /* This third delay should just time out again. */ + vTaskDelay( xMaxBlockTime ); + prvCheckExpectedTimeIsWithinAnAcceptableMargin( xTimeAtStart, xMaxBlockTime ); + } +/*-----------------------------------------------------------*/ + + static void prvTestAbortingTaskNotifyTake( void ) + { + TickType_t xTimeAtStart; + uint32_t ulReturn; + + /* Note the time before the delay so the length of the delay is known. */ + xTimeAtStart = xTaskGetTickCount(); + + /* This first delay should just time out. */ + ulReturn = ulTaskNotifyTake( pdFALSE, xMaxBlockTime ); + + if( ulReturn != 0 ) + { + xErrorOccurred = pdTRUE; + } + + prvCheckExpectedTimeIsWithinAnAcceptableMargin( xTimeAtStart, xMaxBlockTime ); + + /* Note the time before the delay so the length of the delay is known. */ + xTimeAtStart = xTaskGetTickCount(); + + /* This second delay should be aborted by the primary task half way + * through. */ + ulReturn = ulTaskNotifyTake( pdFALSE, xMaxBlockTime ); + + if( ulReturn != 0 ) + { + xErrorOccurred = pdTRUE; + } + + prvCheckExpectedTimeIsWithinAnAcceptableMargin( xTimeAtStart, xHalfMaxBlockTime ); + + /* Note the time before the delay so the length of the delay is known. */ + xTimeAtStart = xTaskGetTickCount(); + + /* This third delay should just time out again. */ + ulReturn = ulTaskNotifyTake( pdFALSE, xMaxBlockTime ); + + if( ulReturn != 0 ) + { + xErrorOccurred = pdTRUE; + } + + prvCheckExpectedTimeIsWithinAnAcceptableMargin( xTimeAtStart, xMaxBlockTime ); + } +/*-----------------------------------------------------------*/ + + static void prvTestAbortingEventGroupWait( void ) + { + TickType_t xTimeAtStart; + EventGroupHandle_t xEventGroup; + EventBits_t xBitsToWaitFor = ( EventBits_t ) 0x01, xReturn; + + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + static StaticEventGroup_t xEventGroupBuffer; + + /* Create the event group. Statically allocated memory is used so the + * creation cannot fail. */ + xEventGroup = xEventGroupCreateStatic( &xEventGroupBuffer ); + } + #else + { + xEventGroup = xEventGroupCreate(); + configASSERT( xEventGroup ); + } + #endif /* if ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ + + /* Note the time before the delay so the length of the delay is known. */ + xTimeAtStart = xTaskGetTickCount(); + + /* This first delay should just time out. */ + xReturn = xEventGroupWaitBits( xEventGroup, xBitsToWaitFor, pdTRUE, pdTRUE, xMaxBlockTime ); + + if( xReturn != 0x00 ) + { + xErrorOccurred = pdTRUE; + } + + prvCheckExpectedTimeIsWithinAnAcceptableMargin( xTimeAtStart, xMaxBlockTime ); + + /* Note the time before the delay so the length of the delay is known. */ + xTimeAtStart = xTaskGetTickCount(); + + /* This second delay should be aborted by the primary task half way + * through. */ + xReturn = xEventGroupWaitBits( xEventGroup, xBitsToWaitFor, pdTRUE, pdTRUE, xMaxBlockTime ); + + if( xReturn != 0x00 ) + { + xErrorOccurred = pdTRUE; + } + + prvCheckExpectedTimeIsWithinAnAcceptableMargin( xTimeAtStart, xHalfMaxBlockTime ); + + /* Note the time before the delay so the length of the delay is known. */ + xTimeAtStart = xTaskGetTickCount(); + + /* This third delay should just time out again. */ + xReturn = xEventGroupWaitBits( xEventGroup, xBitsToWaitFor, pdTRUE, pdTRUE, xMaxBlockTime ); + + if( xReturn != 0x00 ) + { + xErrorOccurred = pdTRUE; + } + + prvCheckExpectedTimeIsWithinAnAcceptableMargin( xTimeAtStart, xMaxBlockTime ); + + /* Not really necessary in this case, but for completeness. */ + vEventGroupDelete( xEventGroup ); + } +/*-----------------------------------------------------------*/ + + static void prvTestAbortingStreamBufferReceive( void ) + { + TickType_t xTimeAtStart; + StreamBufferHandle_t xStreamBuffer; + size_t xReturn; + const size_t xTriggerLevelBytes = ( size_t ) 1; + uint8_t uxRxData; + + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + /* Defines the memory that will actually hold the streams within the + * stream buffer. */ + static uint8_t ucStorageBuffer[ sizeof( configMESSAGE_BUFFER_LENGTH_TYPE ) + 1 ]; + + /* The variable used to hold the stream buffer structure. */ + StaticStreamBuffer_t xStreamBufferStruct; + + + xStreamBuffer = xStreamBufferCreateStatic( sizeof( ucStorageBuffer ), + xTriggerLevelBytes, + ucStorageBuffer, + &xStreamBufferStruct ); + } + #else /* if ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ + { + xStreamBuffer = xStreamBufferCreate( sizeof( uint8_t ), xTriggerLevelBytes ); + configASSERT( xStreamBuffer ); + } + #endif /* if ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ + + /* Note the time before the delay so the length of the delay is known. */ + xTimeAtStart = xTaskGetTickCount(); + + /* This first delay should just time out. */ + xReturn = xStreamBufferReceive( xStreamBuffer, &uxRxData, sizeof( uxRxData ), xMaxBlockTime ); + + if( xReturn != 0x00 ) + { + xErrorOccurred = pdTRUE; + } + + prvCheckExpectedTimeIsWithinAnAcceptableMargin( xTimeAtStart, xMaxBlockTime ); + + /* Note the time before the delay so the length of the delay is known. */ + xTimeAtStart = xTaskGetTickCount(); + + /* This second delay should be aborted by the primary task half way + * through xMaxBlockTime. */ + xReturn = xStreamBufferReceive( xStreamBuffer, &uxRxData, sizeof( uxRxData ), xMaxBlockTime ); + + if( xReturn != 0x00 ) + { + xErrorOccurred = pdTRUE; + } + + prvCheckExpectedTimeIsWithinAnAcceptableMargin( xTimeAtStart, xHalfMaxBlockTime ); + + /* Note the time before the delay so the length of the delay is known. */ + xTimeAtStart = xTaskGetTickCount(); + + /* This third delay should just time out again. */ + xReturn = xStreamBufferReceive( xStreamBuffer, &uxRxData, sizeof( uxRxData ), xMaxBlockTime ); + + if( xReturn != 0x00 ) + { + xErrorOccurred = pdTRUE; + } + + prvCheckExpectedTimeIsWithinAnAcceptableMargin( xTimeAtStart, xMaxBlockTime ); + + /* Not really necessary in this case, but for completeness. */ + vStreamBufferDelete( xStreamBuffer ); + } +/*-----------------------------------------------------------*/ + + static void prvTestAbortingQueueSend( void ) + { + TickType_t xTimeAtStart; + BaseType_t xReturn; + const UBaseType_t xQueueLength = ( UBaseType_t ) 1; + QueueHandle_t xQueue; + uint8_t ucItemToQueue; + + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + static StaticQueue_t xQueueBuffer; + static uint8_t ucQueueStorage[ sizeof( uint8_t ) ]; + + /* Create the queue. Statically allocated memory is used so the + * creation cannot fail. */ + xQueue = xQueueCreateStatic( xQueueLength, sizeof( uint8_t ), ucQueueStorage, &xQueueBuffer ); + } + #else + { + xQueue = xQueueCreate( xQueueLength, sizeof( uint8_t ) ); + configASSERT( xQueue ); + } + #endif /* if ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ + + /* This function tests aborting when in the blocked state waiting to send, + * so the queue must be full. There is only one space in the queue. */ + xReturn = xQueueSend( xQueue, &ucItemToQueue, xMaxBlockTime ); + + if( xReturn != pdPASS ) + { + xErrorOccurred = pdTRUE; + } + + /* Note the time before the delay so the length of the delay is known. */ + xTimeAtStart = xTaskGetTickCount(); + + /* This first delay should just time out. */ + xReturn = xQueueSend( xQueue, &ucItemToQueue, xMaxBlockTime ); + + if( xReturn != pdFALSE ) + { + xErrorOccurred = pdTRUE; + } + + prvCheckExpectedTimeIsWithinAnAcceptableMargin( xTimeAtStart, xMaxBlockTime ); + + /* Note the time before the delay so the length of the delay is known. */ + xTimeAtStart = xTaskGetTickCount(); + + /* This second delay should be aborted by the primary task half way + * through. */ + xReturn = xQueueSend( xQueue, &ucItemToQueue, xMaxBlockTime ); + + if( xReturn != pdFALSE ) + { + xErrorOccurred = pdTRUE; + } + + prvCheckExpectedTimeIsWithinAnAcceptableMargin( xTimeAtStart, xHalfMaxBlockTime ); + + /* Note the time before the delay so the length of the delay is known. */ + xTimeAtStart = xTaskGetTickCount(); + + /* This third delay should just time out again. */ + xReturn = xQueueSend( xQueue, &ucItemToQueue, xMaxBlockTime ); + + if( xReturn != pdFALSE ) + { + xErrorOccurred = pdTRUE; + } + + prvCheckExpectedTimeIsWithinAnAcceptableMargin( xTimeAtStart, xMaxBlockTime ); + + /* Not really necessary in this case, but for completeness. */ + vQueueDelete( xQueue ); + } +/*-----------------------------------------------------------*/ + + static void prvTestAbortingSemaphoreTake( void ) + { + TickType_t xTimeAtStart; + BaseType_t xReturn; + SemaphoreHandle_t xSemaphore; + + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + static StaticSemaphore_t xSemaphoreBuffer; + + /* Create the semaphore. Statically allocated memory is used so the + * creation cannot fail. */ + xSemaphore = xSemaphoreCreateBinaryStatic( &xSemaphoreBuffer ); + } + #else + { + xSemaphore = xSemaphoreCreateBinary(); + } + #endif + + /* Note the time before the delay so the length of the delay is known. */ + xTimeAtStart = xTaskGetTickCount(); + + /* This first delay should just time out. */ + xReturn = xSemaphoreTake( xSemaphore, xMaxBlockTime ); + + if( xReturn != pdFALSE ) + { + xErrorOccurred = pdTRUE; + } + + prvCheckExpectedTimeIsWithinAnAcceptableMargin( xTimeAtStart, xMaxBlockTime ); + + /* Note the time before the delay so the length of the delay is known. */ + xTimeAtStart = xTaskGetTickCount(); + + /* This second delay should be aborted by the primary task half way + * through xMaxBlockTime. */ + xReturn = xSemaphoreTake( xSemaphore, portMAX_DELAY ); + + if( xReturn != pdFALSE ) + { + xErrorOccurred = pdTRUE; + } + + prvCheckExpectedTimeIsWithinAnAcceptableMargin( xTimeAtStart, xHalfMaxBlockTime ); + + /* Note the time before the delay so the length of the delay is known. */ + xTimeAtStart = xTaskGetTickCount(); + + /* This third delay should just time out again. */ + xReturn = xSemaphoreTake( xSemaphore, xMaxBlockTime ); + + if( xReturn != pdFALSE ) + { + xErrorOccurred = pdTRUE; + } + + prvCheckExpectedTimeIsWithinAnAcceptableMargin( xTimeAtStart, xMaxBlockTime ); + + /* Not really necessary in this case, but for completeness. */ + vSemaphoreDelete( xSemaphore ); + } +/*-----------------------------------------------------------*/ + + static void prvTestAbortingTaskNotifyWait( void ) + { + TickType_t xTimeAtStart; + BaseType_t xReturn; + + /* Note the time before the delay so the length of the delay is known. */ + xTimeAtStart = xTaskGetTickCount(); + + /* This first delay should just time out. */ + xReturn = xTaskNotifyWait( 0, 0, NULL, xMaxBlockTime ); + + if( xReturn != pdFALSE ) + { + xErrorOccurred = pdTRUE; + } + + prvCheckExpectedTimeIsWithinAnAcceptableMargin( xTimeAtStart, xMaxBlockTime ); + + /* Note the time before the delay so the length of the delay is known. */ + xTimeAtStart = xTaskGetTickCount(); + + /* This second delay should be aborted by the primary task half way + * through xMaxBlockTime. */ + xReturn = xTaskNotifyWait( 0, 0, NULL, portMAX_DELAY ); + + if( xReturn != pdFALSE ) + { + xErrorOccurred = pdTRUE; + } + + prvCheckExpectedTimeIsWithinAnAcceptableMargin( xTimeAtStart, xHalfMaxBlockTime ); + + /* Note the time before the delay so the length of the delay is known. */ + xTimeAtStart = xTaskGetTickCount(); + + /* This third delay should just time out again. */ + xReturn = xTaskNotifyWait( 0, 0, NULL, xMaxBlockTime ); + + if( xReturn != pdFALSE ) + { + xErrorOccurred = pdTRUE; + } + + prvCheckExpectedTimeIsWithinAnAcceptableMargin( xTimeAtStart, xMaxBlockTime ); + } +/*-----------------------------------------------------------*/ + + static void prvCheckExpectedTimeIsWithinAnAcceptableMargin( TickType_t xStartTime, + TickType_t xExpectedBlockTime ) + { + TickType_t xTimeNow, xActualBlockTime; + + xTimeNow = xTaskGetTickCount(); + xActualBlockTime = xTimeNow - xStartTime; + + /* The actual block time should not be less than the expected block time. */ + if( xActualBlockTime < xExpectedBlockTime ) + { + xErrorOccurred = pdTRUE; + } + + /* The actual block time can be greater than the expected block time, as it + * depends on the priority of the other tasks, but it should be within an + * acceptable margin. */ + if( xActualBlockTime > ( xExpectedBlockTime + xAllowableMargin ) ) + { + xErrorOccurred = pdTRUE; + } + } +/*-----------------------------------------------------------*/ + + BaseType_t xAreAbortDelayTestTasksStillRunning( void ) + { + static BaseType_t xLastControllingCycleCount = 0, xLastBlockingCycleCount = 0; + BaseType_t xReturn = pdPASS; + + /* Have both tasks performed at least one cycle since this function was + * last called? */ + if( xControllingCycles == xLastControllingCycleCount ) + { + xReturn = pdFAIL; + } + + if( xBlockingCycles == xLastBlockingCycleCount ) + { + xReturn = pdFAIL; + } + + if( xErrorOccurred == pdTRUE ) + { + xReturn = pdFAIL; + } + + xLastBlockingCycleCount = xBlockingCycles; + xLastControllingCycleCount = xControllingCycles; + + return xReturn; + } + +#endif /* INCLUDE_xTaskAbortDelay == 1 */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/EventGroupsDemo.c b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/EventGroupsDemo.c new file mode 100644 index 0000000..8c86b68 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/EventGroupsDemo.c @@ -0,0 +1,1059 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + + + +/* + * This file contains fairly comprehensive checks on the behaviour of event + * groups. It is not intended to be a user friendly demonstration of the + * event groups API. + * + * NOTE: The tests implemented in this file are informal 'sanity' tests + * only and are not part of the module tests that make use of the + * mtCOVERAGE_TEST_MARKER macro within the event groups implementation. + */ + + +/* Scheduler include files. */ +#include "FreeRTOS.h" +#include "task.h" +#include "event_groups.h" + +/* Demo app includes. */ +#include "EventGroupsDemo.h" + +#if ( INCLUDE_eTaskGetState != 1 ) + #error INCLUDE_eTaskGetState must be set to 1 in FreeRTOSConfig.h to use this demo file. +#endif + +/* Priorities used by the tasks. */ +#define ebSET_BIT_TASK_PRIORITY ( tskIDLE_PRIORITY ) +#define ebWAIT_BIT_TASK_PRIORITY ( tskIDLE_PRIORITY + 1 ) + +/* Generic bit definitions. */ +#define ebBIT_0 ( 0x01 ) +#define ebBIT_1 ( 0x02 ) +#define ebBIT_2 ( 0x04 ) +#define ebBIT_3 ( 0x08 ) +#define ebBIT_4 ( 0x10 ) +#define ebBIT_5 ( 0x20 ) +#define ebBIT_6 ( 0x40 ) +#define ebBIT_7 ( 0x80 ) + +/* Combinations of bits used in the demo. */ +#define ebCOMBINED_BITS ( ebBIT_1 | ebBIT_5 | ebBIT_7 ) +#define ebALL_BITS ( ebBIT_0 | ebBIT_1 | ebBIT_2 | ebBIT_3 | ebBIT_4 | ebBIT_5 | ebBIT_6 | ebBIT_7 ) + +/* Associate a bit to each task. These bits are used to identify all the tasks + * that synchronise with the xEventGroupSync() function. */ +#define ebSET_BIT_TASK_SYNC_BIT ebBIT_0 +#define ebWAIT_BIT_TASK_SYNC_BIT ebBIT_1 +#define ebRENDESVOUS_TASK_1_SYNC_BIT ebBIT_2 +#define ebRENDESVOUS_TASK_2_SYNC_BIT ebBIT_3 +#define ebALL_SYNC_BITS ( ebSET_BIT_TASK_SYNC_BIT | ebWAIT_BIT_TASK_SYNC_BIT | ebRENDESVOUS_TASK_1_SYNC_BIT | ebRENDESVOUS_TASK_2_SYNC_BIT ) + +/* A block time of zero simply means "don't block". */ +#define ebDONT_BLOCK ( 0 ) + +/* A 5ms delay. */ +#define ebSHORT_DELAY pdMS_TO_TICKS( ( TickType_t ) 5 ) + +/* Used in the selective bits test which checks no, one or both tasks blocked on + * event bits in a group are unblocked as appropriate as different bits get set. */ +#define ebSELECTIVE_BITS_1 0x03 +#define ebSELECTIVE_BITS_2 0x05 + +#ifndef ebRENDESVOUS_TEST_TASK_STACK_SIZE + #define ebRENDESVOUS_TEST_TASK_STACK_SIZE configMINIMAL_STACK_SIZE +#endif + +#ifndef ebEVENT_GROUP_SET_BITS_TEST_TASK_STACK_SIZE + #define ebEVENT_GROUP_SET_BITS_TEST_TASK_STACK_SIZE configMINIMAL_STACK_SIZE +#endif + +/*-----------------------------------------------------------*/ + +/* + * NOTE: The tests implemented in this function are informal 'sanity' tests + * only and are not part of the module tests that make use of the + * mtCOVERAGE_TEST_MARKER macro within the event groups implementation. + * + * The master test task. This task: + * + * 1) Calls prvSelectiveBitsTestMasterFunction() to test the behaviour when two + * tasks are blocked on different bits in an event group. The counterpart of + * this test is implemented by the prvSelectiveBitsTestSlaveFunction() + * function (which is called by the two tasks that block on the event group). + * + * 2) Calls prvBitCombinationTestMasterFunction() to test the behaviour when + * just one task is blocked on various combinations of bits within an event + * group. The counterpart of this test is implemented within the 'test + * slave' task. + * + * 3) Calls prvPerformTaskSyncTests() to test task synchronisation behaviour. + */ +static void prvTestMasterTask( void * pvParameters ); + +/* + * A helper task that enables the 'test master' task to perform several + * behavioural tests. See the comments above the prvTestMasterTask() prototype + * above. + */ +static void prvTestSlaveTask( void * pvParameters ); + +/* + * The part of the test that is performed between the 'test master' task and the + * 'test slave' task to test the behaviour when the slave blocks on various + * event bit combinations. + */ +static BaseType_t prvBitCombinationTestMasterFunction( BaseType_t xError, + TaskHandle_t xTestSlaveTaskHandle ); + +/* + * The part of the test that uses all the tasks to test the task synchronisation + * behaviour. + */ +static BaseType_t prvPerformTaskSyncTests( BaseType_t xError, + TaskHandle_t xTestSlaveTaskHandle ); + +/* + * Two instances of prvSyncTask() are created. They start by calling + * prvSelectiveBitsTestSlaveFunction() to act as slaves when the test master is + * executing the prvSelectiveBitsTestMasterFunction() function. They then loop + * to test the task synchronisation (rendezvous) behaviour. + */ +static void prvSyncTask( void * pvParameters ); + +/* + * Functions used in a test that blocks two tasks on various different bits + * within an event group - then sets each bit in turn and checks that the + * correct tasks unblock at the correct times. + */ +static BaseType_t prvSelectiveBitsTestMasterFunction( void ); +static void prvSelectiveBitsTestSlaveFunction( void ); + +/*-----------------------------------------------------------*/ + +/* Variables that are incremented by the tasks on each cycle provided no errors + * have been found. Used to detect an error or stall in the test cycling. */ +static volatile uint32_t ulTestMasterCycles = 0, ulTestSlaveCycles = 0, ulISRCycles = 0; + +/* The event group used by all the task based tests. */ +static EventGroupHandle_t xEventGroup = NULL; + +/* The event group used by the interrupt based tests. */ +static EventGroupHandle_t xISREventGroup = NULL; + +/* Handles to the tasks that only take part in the synchronisation calls. */ +static TaskHandle_t xSyncTask1 = NULL, xSyncTask2 = NULL; + +/*-----------------------------------------------------------*/ + +void vStartEventGroupTasks( void ) +{ + TaskHandle_t xTestSlaveTaskHandle; + + /* + * This file contains fairly comprehensive checks on the behaviour of event + * groups. It is not intended to be a user friendly demonstration of the + * event groups API. + * + * NOTE: The tests implemented in this file are informal 'sanity' tests + * only and are not part of the module tests that make use of the + * mtCOVERAGE_TEST_MARKER macro within the event groups implementation. + * + * Create the test tasks as described at the top of this file. + */ + xTaskCreate( prvTestSlaveTask, "WaitO", ebRENDESVOUS_TEST_TASK_STACK_SIZE, NULL, ebWAIT_BIT_TASK_PRIORITY, &xTestSlaveTaskHandle ); + xTaskCreate( prvTestMasterTask, "SetB", ebEVENT_GROUP_SET_BITS_TEST_TASK_STACK_SIZE, ( void * ) xTestSlaveTaskHandle, ebSET_BIT_TASK_PRIORITY, NULL ); + xTaskCreate( prvSyncTask, "Rndv", ebRENDESVOUS_TEST_TASK_STACK_SIZE, ( void * ) ebRENDESVOUS_TASK_1_SYNC_BIT, ebWAIT_BIT_TASK_PRIORITY, &xSyncTask1 ); + xTaskCreate( prvSyncTask, "Rndv", ebRENDESVOUS_TEST_TASK_STACK_SIZE, ( void * ) ebRENDESVOUS_TASK_2_SYNC_BIT, ebWAIT_BIT_TASK_PRIORITY, &xSyncTask2 ); + + /* If the last task was created then the others will have been too. */ + configASSERT( xSyncTask2 ); + + /* Create the event group used by the ISR tests. The event group used by + * the tasks is created by the tasks themselves. */ + xISREventGroup = xEventGroupCreate(); + configASSERT( xISREventGroup ); +} +/*-----------------------------------------------------------*/ + +static void prvTestMasterTask( void * pvParameters ) +{ + BaseType_t xError; + +/* The handle to the slave task is passed in as the task parameter. */ + TaskHandle_t xTestSlaveTaskHandle = ( TaskHandle_t ) pvParameters; + + /* Avoid compiler warnings. */ + ( void ) pvParameters; + + /* Create the event group used by the tasks ready for the initial tests. */ + xEventGroup = xEventGroupCreate(); + configASSERT( xEventGroup ); + + /* Perform the tests that block two tasks on different combinations of bits, + * then set each bit in turn and check the correct tasks unblock at the correct + * times. */ + xError = prvSelectiveBitsTestMasterFunction(); + + for( ; ; ) + { + /* Recreate the event group ready for the next cycle. */ + xEventGroup = xEventGroupCreate(); + configASSERT( xEventGroup ); + + /* Perform the tests that check the behaviour when a single task is + * blocked on various combinations of event bits. */ + xError = prvBitCombinationTestMasterFunction( xError, xTestSlaveTaskHandle ); + + /* Perform the task synchronisation tests. */ + xError = prvPerformTaskSyncTests( xError, xTestSlaveTaskHandle ); + + /* Delete the event group. */ + vEventGroupDelete( xEventGroup ); + + /* Now all the other tasks should have completed and suspended + * themselves ready for the next go around the loop. */ + if( eTaskGetState( xTestSlaveTaskHandle ) != eSuspended ) + { + xError = pdTRUE; + } + + if( eTaskGetState( xSyncTask1 ) != eSuspended ) + { + xError = pdTRUE; + } + + if( eTaskGetState( xSyncTask2 ) != eSuspended ) + { + xError = pdTRUE; + } + + /* Only increment the cycle variable if no errors have been detected. */ + if( xError == pdFALSE ) + { + ulTestMasterCycles++; + } + + configASSERT( xError == pdFALSE ); + } +} +/*-----------------------------------------------------------*/ + +static void prvSyncTask( void * pvParameters ) +{ + EventBits_t uxSynchronisationBit, uxReturned; + + /* A few tests that check the behaviour when two tasks are blocked on + * various different bits within an event group are performed before this task + * enters its infinite loop to carry out its main demo function. */ + prvSelectiveBitsTestSlaveFunction(); + + /* The bit to use to indicate this task is at the synchronisation point is + * passed in as the task parameter. */ + uxSynchronisationBit = ( EventBits_t ) pvParameters; + + for( ; ; ) + { + /* Now this task takes part in a task synchronisation - sometimes known + * as a 'rendezvous'. Its execution pattern is controlled by the 'test + * master' task, which is responsible for taking this task out of the + * Suspended state when it is time to test the synchronisation behaviour. + * See: http://www.freertos.org/xEventGroupSync.html. */ + vTaskSuspend( NULL ); + + /* Set the bit that indicates this task is at the synchronisation + * point. The first time this is done the 'test master' task has a lower + * priority than this task so this task will get to the sync point before + * the set bits task - test this by calling xEventGroupSync() with a zero + * block time before calling again with a max delay - the first call should + * return before the rendezvous completes, the second only after the + * rendezvous is complete. */ + uxReturned = xEventGroupSync( xEventGroup, /* The event group used for the synchronisation. */ + uxSynchronisationBit, /* The bit to set in the event group to indicate this task is at the sync point. */ + ebALL_SYNC_BITS, /* The bits to wait for - these bits are set by the other tasks taking part in the sync. */ + ebDONT_BLOCK ); /* The maximum time to wait for the sync condition to be met before giving up. */ + + /* No block time was specified, so as per the comments above, the + * rendezvous is not expected to have completed yet. */ + configASSERT( ( uxReturned & ebALL_SYNC_BITS ) != ebALL_SYNC_BITS ); + + uxReturned = xEventGroupSync( xEventGroup, /* The event group used for the synchronisation. */ + uxSynchronisationBit, /* The bit to set in the event group to indicate this task is at the sync point. */ + ebALL_SYNC_BITS, /* The bits to wait for - these bits are set by the other tasks taking part in the sync. */ + portMAX_DELAY ); /* The maximum time to wait for the sync condition to be met before giving up. */ + + /* A max delay was used, so this task should only exit the above + * function call when the sync condition is met. Check this is the + * case. */ + configASSERT( ( uxReturned & ebALL_SYNC_BITS ) == ebALL_SYNC_BITS ); + + /* Remove compiler warning if configASSERT() is not defined. */ + ( void ) uxReturned; + + /* Wait until the 'test master' task unsuspends this task again. */ + vTaskSuspend( NULL ); + + /* Set the bit that indicates this task is at the synchronisation + * point again. This time the 'test master' task has a higher priority + * than this task so will get to the sync point before this task. */ + uxReturned = xEventGroupSync( xEventGroup, uxSynchronisationBit, ebALL_SYNC_BITS, portMAX_DELAY ); + + /* Again a max delay was used, so this task should only exit the above + * function call when the sync condition is met. Check this is the + * case. */ + configASSERT( ( uxReturned & ebALL_SYNC_BITS ) == ebALL_SYNC_BITS ); + + /* Block on the event group again. This time the event group is going + * to be deleted while this task is blocked on it so it is expected that 0 + * be returned. */ + uxReturned = xEventGroupWaitBits( xEventGroup, ebALL_SYNC_BITS, pdFALSE, pdTRUE, portMAX_DELAY ); + configASSERT( uxReturned == 0 ); + } +} +/*-----------------------------------------------------------*/ + +static void prvTestSlaveTask( void * pvParameters ) +{ + EventBits_t uxReturned; + BaseType_t xError = pdFALSE; + + /* Avoid compiler warnings. */ + ( void ) pvParameters; + + for( ; ; ) + { + /********************************************************************** + * Part 1: This section is the counterpart to the + * prvBitCombinationTestMasterFunction() function which is called by the + * test master task. + *********************************************************************** + * + * This task is controller by the 'test master' task (which is + * implemented by prvTestMasterTask()). Suspend until resumed by the + * 'test master' task. */ + vTaskSuspend( NULL ); + + /* Wait indefinitely for one of the bits in ebCOMBINED_BITS to get + * set. Clear the bit on exit. */ + uxReturned = xEventGroupWaitBits( xEventGroup, /* The event group that contains the event bits being queried. */ + ebBIT_1, /* The bit to wait for. */ + pdTRUE, /* Clear the bit on exit. */ + pdTRUE, /* Wait for all the bits (only one in this case anyway). */ + portMAX_DELAY ); /* Block indefinitely to wait for the condition to be met. */ + + /* The 'test master' task set all the bits defined by ebCOMBINED_BITS, + * only one of which was being waited for by this task. The return value + * shows the state of the event bits when the task was unblocked, however + * because the task was waiting for ebBIT_1 and 'clear on exit' was set to + * the current state of the event bits will have ebBIT_1 clear. */ + if( uxReturned != ebCOMBINED_BITS ) + { + xError = pdTRUE; + } + + /* Now call xEventGroupWaitBits() again, this time waiting for all the + * bits in ebCOMBINED_BITS to be set. This call should block until the + * 'test master' task sets ebBIT_1 - which was the bit cleared in the call + * to xEventGroupWaitBits() above. */ + uxReturned = xEventGroupWaitBits( xEventGroup, + ebCOMBINED_BITS, /* The bits being waited on. */ + pdFALSE, /* Don't clear the bits on exit. */ + pdTRUE, /* All the bits must be set to unblock. */ + portMAX_DELAY ); + + /* Were all the bits set? */ + if( ( uxReturned & ebCOMBINED_BITS ) != ebCOMBINED_BITS ) + { + xError = pdTRUE; + } + + /* Suspend again to wait for the 'test master' task. */ + vTaskSuspend( NULL ); + + /* Now call xEventGroupWaitBits() again, again waiting for all the bits + * in ebCOMBINED_BITS to be set, but this time clearing the bits when the + * task is unblocked. */ + uxReturned = xEventGroupWaitBits( xEventGroup, + ebCOMBINED_BITS, /* The bits being waited on. */ + pdTRUE, /* Clear the bits on exit. */ + pdTRUE, /* All the bits must be set to unblock. */ + portMAX_DELAY ); + + /* The 'test master' task set all the bits in the event group, so that + * is the value that should have been returned. The bits defined by + * ebCOMBINED_BITS will have been clear again in the current value though + * as 'clear on exit' was set to pdTRUE. */ + if( uxReturned != ebALL_BITS ) + { + xError = pdTRUE; + } + + /********************************************************************** + * Part 2: This section is the counterpart to the + * prvPerformTaskSyncTests() function which is called by the + * test master task. + *********************************************************************** + * + * + * Once again wait for the 'test master' task to unsuspend this task + * when it is time for the next test. */ + vTaskSuspend( NULL ); + + /* Now peform a synchronisation with all the other tasks. At this point + * the 'test master' task has the lowest priority so will get to the sync + * point after all the other synchronising tasks. */ + uxReturned = xEventGroupSync( xEventGroup, /* The event group used for the sync. */ + ebWAIT_BIT_TASK_SYNC_BIT, /* The bit in the event group used to indicate this task is at the sync point. */ + ebALL_SYNC_BITS, /* The bits to wait for. These bits are set by the other tasks taking part in the sync. */ + portMAX_DELAY ); /* The maximum time to wait for the sync condition to be met before giving up. */ + + /* A sync with a max delay should only exit when all the synchronisation + * bits are set... */ + if( ( uxReturned & ebALL_SYNC_BITS ) != ebALL_SYNC_BITS ) + { + xError = pdTRUE; + } + + /* ...but now the synchronisation bits should be clear again. Read back + * the current value of the bits within the event group to check that is + * the case. Setting the bits to zero will return the bits previous value + * then leave all the bits clear. */ + if( xEventGroupSetBits( xEventGroup, 0x00 ) != 0 ) + { + xError = pdTRUE; + } + + /* Check the bits are indeed 0 now by simply reading then. */ + if( xEventGroupGetBits( xEventGroup ) != 0 ) + { + xError = pdTRUE; + } + + if( xError == pdFALSE ) + { + /* This task is still cycling without finding an error. */ + ulTestSlaveCycles++; + } + + vTaskSuspend( NULL ); + + /* This time sync when the 'test master' task has the highest priority + * at the point where it sets its sync bit - so this time the 'test master' + * task will get to the sync point before this task. */ + uxReturned = xEventGroupSync( xEventGroup, ebWAIT_BIT_TASK_SYNC_BIT, ebALL_SYNC_BITS, portMAX_DELAY ); + + /* A sync with a max delay should only exit when all the synchronisation + * bits are set... */ + if( ( uxReturned & ebALL_SYNC_BITS ) != ebALL_SYNC_BITS ) + { + xError = pdTRUE; + } + + /* ...but now the sync bits should be clear again. */ + if( xEventGroupSetBits( xEventGroup, 0x00 ) != 0 ) + { + xError = pdTRUE; + } + + /* Block on the event group again. This time the event group is going + * to be deleted while this task is blocked on it, so it is expected that 0 + * will be returned. */ + uxReturned = xEventGroupWaitBits( xEventGroup, ebALL_SYNC_BITS, pdFALSE, pdTRUE, portMAX_DELAY ); + + if( uxReturned != 0 ) + { + xError = pdTRUE; + } + + if( xError == pdFALSE ) + { + /* This task is still cycling without finding an error. */ + ulTestSlaveCycles++; + } + + configASSERT( xError == pdFALSE ); + } +} +/*-----------------------------------------------------------*/ + +static BaseType_t prvPerformTaskSyncTests( BaseType_t xError, + TaskHandle_t xTestSlaveTaskHandle ) +{ + EventBits_t uxBits; + + /* The three tasks that take part in the synchronisation (rendezvous) are + * expected to be in the suspended state at the start of the test. */ + if( eTaskGetState( xTestSlaveTaskHandle ) != eSuspended ) + { + xError = pdTRUE; + } + + if( eTaskGetState( xSyncTask1 ) != eSuspended ) + { + xError = pdTRUE; + } + + if( eTaskGetState( xSyncTask2 ) != eSuspended ) + { + xError = pdTRUE; + } + + /* Try a synch with no other tasks involved. First set all the bits other + * than this task's bit. */ + xEventGroupSetBits( xEventGroup, ( ebALL_SYNC_BITS & ~ebSET_BIT_TASK_SYNC_BIT ) ); + + /* Then wait on just one bit - the bit that is being set. */ + uxBits = xEventGroupSync( xEventGroup, /* The event group used for the synchronisation. */ + ebSET_BIT_TASK_SYNC_BIT, /* The bit set by this task when it reaches the sync point. */ + ebSET_BIT_TASK_SYNC_BIT, /* The bits to wait for - in this case it is just waiting for itself. */ + portMAX_DELAY ); /* The maximum time to wait for the sync condition to be met. */ + + /* A sync with a max delay should only exit when all the synchronise + * bits are set...check that is the case. In this case there is only one + * sync bit anyway. */ + if( ( uxBits & ebSET_BIT_TASK_SYNC_BIT ) != ebSET_BIT_TASK_SYNC_BIT ) + { + xError = pdTRUE; + } + + /* ...but now the sync bits should be clear again, leaving all the other + * bits set (as only one bit was being waited for). */ + if( xEventGroupGetBits( xEventGroup ) != ( ebALL_SYNC_BITS & ~ebSET_BIT_TASK_SYNC_BIT ) ) + { + xError = pdTRUE; + } + + /* Clear all the bits to zero again. */ + xEventGroupClearBits( xEventGroup, ( ebALL_SYNC_BITS & ~ebSET_BIT_TASK_SYNC_BIT ) ); + + if( xEventGroupGetBits( xEventGroup ) != 0 ) + { + xError = pdTRUE; + } + + /* Unsuspend the other tasks then check they have executed up to the + * synchronisation point. */ + vTaskResume( xTestSlaveTaskHandle ); + vTaskResume( xSyncTask1 ); + vTaskResume( xSyncTask2 ); + + if( eTaskGetState( xTestSlaveTaskHandle ) != eBlocked ) + { + xError = pdTRUE; + } + + if( eTaskGetState( xSyncTask1 ) != eBlocked ) + { + xError = pdTRUE; + } + + if( eTaskGetState( xSyncTask2 ) != eBlocked ) + { + xError = pdTRUE; + } + + /* Set this task's sync bit. */ + uxBits = xEventGroupSync( xEventGroup, /* The event group used for the synchronisation. */ + ebSET_BIT_TASK_SYNC_BIT, /* The bit set by this task when it reaches the sync point. */ + ebALL_SYNC_BITS, /* The bits to wait for - these bits are set by the other tasks that take part in the sync. */ + portMAX_DELAY ); /* The maximum time to wait for the sync condition to be met. */ + + /* A sync with a max delay should only exit when all the synchronise + * bits are set...check that is the case. */ + if( ( uxBits & ebALL_SYNC_BITS ) != ebALL_SYNC_BITS ) + { + xError = pdTRUE; + } + + /* ...but now the sync bits should be clear again. */ + if( xEventGroupGetBits( xEventGroup ) != 0 ) + { + xError = pdTRUE; + } + + /* The other tasks should now all be suspended again, ready for the next + * synchronisation. */ + if( eTaskGetState( xTestSlaveTaskHandle ) != eSuspended ) + { + xError = pdTRUE; + } + + if( eTaskGetState( xSyncTask1 ) != eSuspended ) + { + xError = pdTRUE; + } + + if( eTaskGetState( xSyncTask2 ) != eSuspended ) + { + xError = pdTRUE; + } + + /* Sync again - but this time set the last necessary bit as the + * highest priority task, rather than the lowest priority task. Unsuspend + * the other tasks then check they have executed up to the synchronisation + * point. */ + vTaskResume( xTestSlaveTaskHandle ); + vTaskResume( xSyncTask1 ); + vTaskResume( xSyncTask2 ); + + if( eTaskGetState( xTestSlaveTaskHandle ) != eBlocked ) + { + xError = pdTRUE; + } + + if( eTaskGetState( xSyncTask1 ) != eBlocked ) + { + xError = pdTRUE; + } + + if( eTaskGetState( xSyncTask2 ) != eBlocked ) + { + xError = pdTRUE; + } + + /* Raise the priority of this task above that of the other tasks. */ + vTaskPrioritySet( NULL, ebWAIT_BIT_TASK_PRIORITY + 1 ); + + /* Set this task's sync bit. */ + uxBits = xEventGroupSync( xEventGroup, ebSET_BIT_TASK_SYNC_BIT, ebALL_SYNC_BITS, portMAX_DELAY ); + + /* A sync with a max delay should only exit when all the synchronisation + * bits are set... */ + if( ( uxBits & ebALL_SYNC_BITS ) != ebALL_SYNC_BITS ) + { + xError = pdTRUE; + } + + /* ...but now the sync bits should be clear again. */ + if( xEventGroupGetBits( xEventGroup ) != 0 ) + { + xError = pdTRUE; + } + + /* The other tasks should now all be in the ready state again, but not + * executed yet as this task still has a higher relative priority. */ + if( eTaskGetState( xTestSlaveTaskHandle ) != eReady ) + { + xError = pdTRUE; + } + + if( eTaskGetState( xSyncTask1 ) != eReady ) + { + xError = pdTRUE; + } + + if( eTaskGetState( xSyncTask2 ) != eReady ) + { + xError = pdTRUE; + } + + /* Reset the priority of this task back to its original value. */ + vTaskPrioritySet( NULL, ebSET_BIT_TASK_PRIORITY ); + + /* Now all the other tasks should have reblocked on the event bits + * to test the behaviour when the event bits are deleted. */ + if( eTaskGetState( xTestSlaveTaskHandle ) != eBlocked ) + { + xError = pdTRUE; + } + + if( eTaskGetState( xSyncTask1 ) != eBlocked ) + { + xError = pdTRUE; + } + + if( eTaskGetState( xSyncTask2 ) != eBlocked ) + { + xError = pdTRUE; + } + + return xError; +} +/*-----------------------------------------------------------*/ + +static BaseType_t prvBitCombinationTestMasterFunction( BaseType_t xError, + TaskHandle_t xTestSlaveTaskHandle ) +{ + EventBits_t uxBits; + + /* Resume the other task. It will block, pending a single bit from + * within ebCOMBINED_BITS. */ + vTaskResume( xTestSlaveTaskHandle ); + + /* Ensure the other task is blocked on the task. */ + if( eTaskGetState( xTestSlaveTaskHandle ) != eBlocked ) + { + xError = pdTRUE; + } + + /* Set all the bits in ebCOMBINED_BITS - the 'test slave' task is only + * blocked waiting for one of them. */ + xEventGroupSetBits( xEventGroup, ebCOMBINED_BITS ); + + /* The 'test slave' task should now have executed, clearing ebBIT_1 (the + * bit it was blocked on), then re-entered the Blocked state to wait for + * all the other bits in ebCOMBINED_BITS to be set again. First check + * ebBIT_1 is clear. */ + uxBits = xEventGroupWaitBits( xEventGroup, ebALL_BITS, pdFALSE, pdFALSE, ebDONT_BLOCK ); + + if( uxBits != ( ebCOMBINED_BITS & ~ebBIT_1 ) ) + { + xError = pdTRUE; + } + + /* Ensure the other task is still in the blocked state. */ + if( eTaskGetState( xTestSlaveTaskHandle ) != eBlocked ) + { + xError = pdTRUE; + } + + /* Set all the bits other than ebBIT_1 - which is the bit that must be + * set before the other task unblocks. */ + xEventGroupSetBits( xEventGroup, ebALL_BITS & ~ebBIT_1 ); + + /* Ensure all the expected bits are still set. */ + uxBits = xEventGroupWaitBits( xEventGroup, ebALL_BITS, pdFALSE, pdFALSE, ebDONT_BLOCK ); + + if( uxBits != ( ebALL_BITS & ~ebBIT_1 ) ) + { + xError = pdTRUE; + } + + /* Ensure the other task is still in the blocked state. */ + if( eTaskGetState( xTestSlaveTaskHandle ) != eBlocked ) + { + xError = pdTRUE; + } + + /* Now also set ebBIT_1, which should unblock the other task, which will + * then suspend itself. */ + xEventGroupSetBits( xEventGroup, ebBIT_1 ); + + /* Ensure the other task is suspended. */ + if( eTaskGetState( xTestSlaveTaskHandle ) != eSuspended ) + { + xError = pdTRUE; + } + + /* The other task should not have cleared the bits - so all the bits + * should still be set. */ + if( xEventGroupSetBits( xEventGroup, 0x00 ) != ebALL_BITS ) + { + xError = pdTRUE; + } + + /* Clear ebBIT_1 again. */ + if( xEventGroupClearBits( xEventGroup, ebBIT_1 ) != ebALL_BITS ) + { + xError = pdTRUE; + } + + /* Resume the other task - which will wait on all the ebCOMBINED_BITS + * again - this time clearing the bits when it is unblocked. */ + vTaskResume( xTestSlaveTaskHandle ); + + /* Ensure the other task is blocked once again. */ + if( eTaskGetState( xTestSlaveTaskHandle ) != eBlocked ) + { + xError = pdTRUE; + } + + /* Set the bit the other task is waiting for. */ + xEventGroupSetBits( xEventGroup, ebBIT_1 ); + + /* Ensure the other task is suspended once again. */ + if( eTaskGetState( xTestSlaveTaskHandle ) != eSuspended ) + { + xError = pdTRUE; + } + + /* The other task should have cleared the bits in ebCOMBINED_BITS. + * Clear the remaining bits. */ + uxBits = xEventGroupWaitBits( xEventGroup, ebALL_BITS, pdFALSE, pdFALSE, ebDONT_BLOCK ); + + if( uxBits != ( ebALL_BITS & ~ebCOMBINED_BITS ) ) + { + xError = pdTRUE; + } + + /* Clear all bits ready for the sync with the other three tasks. The + * value returned is the value prior to the bits being cleared. */ + if( xEventGroupClearBits( xEventGroup, ebALL_BITS ) != ( ebALL_BITS & ~ebCOMBINED_BITS ) ) + { + xError = pdTRUE; + } + + /* The bits should be clear now. */ + if( xEventGroupGetBits( xEventGroup ) != 0x00 ) + { + xError = pdTRUE; + } + + return xError; +} +/*-----------------------------------------------------------*/ + +static void prvSelectiveBitsTestSlaveFunction( void ) +{ + EventBits_t uxPendBits, uxReturned; + + /* Used in a test that blocks two tasks on various different bits within an + * event group - then sets each bit in turn and checks that the correct tasks + * unblock at the correct times. + * + * This function is called by two different tasks - each of which will use a + * different bit. Check the task handle to see which task the function was + * called by. */ + if( xTaskGetCurrentTaskHandle() == xSyncTask1 ) + { + uxPendBits = ebSELECTIVE_BITS_1; + } + else + { + uxPendBits = ebSELECTIVE_BITS_2; + } + + for( ; ; ) + { + /* Wait until it is time to perform the next cycle of the test. The + * task is unsuspended by the tests implemented in the + * prvSelectiveBitsTestMasterFunction() function. */ + vTaskSuspend( NULL ); + uxReturned = xEventGroupWaitBits( xEventGroup, uxPendBits, pdTRUE, pdFALSE, portMAX_DELAY ); + + if( uxReturned == ( EventBits_t ) 0 ) + { + break; + } + } +} +/*-----------------------------------------------------------*/ + +static BaseType_t prvSelectiveBitsTestMasterFunction( void ) +{ + BaseType_t xError = pdFALSE; + EventBits_t uxBit; + + /* Used in a test that blocks two tasks on various different bits within an + * event group - then sets each bit in turn and checks that the correct tasks + * unblock at the correct times. The two other tasks (xSyncTask1 and + * xSyncTask2) call prvSelectiveBitsTestSlaveFunction() to perform their parts in + * this test. + * + * Both other tasks should start in the suspended state. */ + if( eTaskGetState( xSyncTask1 ) != eSuspended ) + { + xError = pdTRUE; + } + + if( eTaskGetState( xSyncTask2 ) != eSuspended ) + { + xError = pdTRUE; + } + + /* Test each bit in the byte individually. */ + for( uxBit = 0x01; uxBit < 0x100; uxBit <<= 1 ) + { + /* Resume both tasks. */ + vTaskResume( xSyncTask1 ); + vTaskResume( xSyncTask2 ); + + /* Now both tasks should be blocked on the event group. */ + if( eTaskGetState( xSyncTask1 ) != eBlocked ) + { + xError = pdTRUE; + } + + if( eTaskGetState( xSyncTask2 ) != eBlocked ) + { + xError = pdTRUE; + } + + /* Set one bit. */ + xEventGroupSetBits( xEventGroup, uxBit ); + + /* Is the bit set in the first set of selective bits? If so the first + * sync task should have unblocked and returned to the suspended state. */ + if( ( uxBit & ebSELECTIVE_BITS_1 ) == 0 ) + { + /* Task should not have unblocked. */ + if( eTaskGetState( xSyncTask1 ) != eBlocked ) + { + xError = pdTRUE; + } + } + else + { + /* Task should have unblocked and returned to the suspended state. */ + if( eTaskGetState( xSyncTask1 ) != eSuspended ) + { + xError = pdTRUE; + } + } + + /* Same checks for the second sync task. */ + if( ( uxBit & ebSELECTIVE_BITS_2 ) == 0 ) + { + /* Task should not have unblocked. */ + if( eTaskGetState( xSyncTask2 ) != eBlocked ) + { + xError = pdTRUE; + } + } + else + { + /* Task should have unblocked and returned to the suspended state. */ + if( eTaskGetState( xSyncTask2 ) != eSuspended ) + { + xError = pdTRUE; + } + } + } + + /* Ensure both tasks are blocked on the event group again, then delete the + * event group so the other tasks leave this portion of the test. */ + vTaskResume( xSyncTask1 ); + vTaskResume( xSyncTask2 ); + + /* Deleting the event group is the signal that the two other tasks should + * leave the prvSelectiveBitsTestSlaveFunction() function and continue to the main + * part of their functionality. */ + vEventGroupDelete( xEventGroup ); + + return xError; +} +/*-----------------------------------------------------------*/ + +void vPeriodicEventGroupsProcessing( void ) +{ + static BaseType_t xCallCount = 0, xISRTestError = pdFALSE; + const BaseType_t xSetBitCount = 100, xGetBitsCount = 200, xClearBitsCount = 300; + const EventBits_t uxBitsToSet = 0x12U; + EventBits_t uxReturned; + BaseType_t xMessagePosted; + + /* Called periodically from the tick hook to exercise the "FromISR" + * functions. */ + + /* Check the even group tasks were actually created. */ + configASSERT( xISREventGroup ); + + xCallCount++; + + if( xCallCount == xSetBitCount ) + { + /* All the event bits should start clear. */ + uxReturned = xEventGroupGetBitsFromISR( xISREventGroup ); + + if( uxReturned != 0x00 ) + { + xISRTestError = pdTRUE; + } + else + { + /* Set the bits. This is called from the tick hook so it is not + * necessary to use the last parameter to ensure a context switch + * occurs immediately. */ + xMessagePosted = xEventGroupSetBitsFromISR( xISREventGroup, uxBitsToSet, NULL ); + + if( xMessagePosted != pdPASS ) + { + xISRTestError = pdTRUE; + } + } + } + else if( xCallCount == xGetBitsCount ) + { + /* Check the bits were set as expected. */ + uxReturned = xEventGroupGetBitsFromISR( xISREventGroup ); + + if( uxReturned != uxBitsToSet ) + { + xISRTestError = pdTRUE; + } + } + else if( xCallCount == xClearBitsCount ) + { + /* Clear the bits again. */ + uxReturned = ( EventBits_t ) xEventGroupClearBitsFromISR( xISREventGroup, uxBitsToSet ); + + /* Check the message was posted. */ + if( uxReturned != pdPASS ) + { + xISRTestError = pdTRUE; + } + + /* Go back to the start. */ + xCallCount = 0; + + /* If no errors have been detected then increment the count of test + * cycles. */ + if( xISRTestError == pdFALSE ) + { + ulISRCycles++; + } + } + else + { + /* Nothing else to do. */ + } +} + +/*-----------------------------------------------------------*/ +/* This is called to check that all the created tasks are still running. */ +BaseType_t xAreEventGroupTasksStillRunning( void ) +{ + static uint32_t ulPreviousWaitBitCycles = 0, ulPreviousSetBitCycles = 0, ulPreviousISRCycles = 0; + BaseType_t xStatus = pdPASS; + + /* Check the tasks are still cycling without finding any errors. */ + if( ulPreviousSetBitCycles == ulTestMasterCycles ) + { + xStatus = pdFAIL; + } + + ulPreviousSetBitCycles = ulTestMasterCycles; + + if( ulPreviousWaitBitCycles == ulTestSlaveCycles ) + { + xStatus = pdFAIL; + } + + ulPreviousWaitBitCycles = ulTestSlaveCycles; + + if( ulPreviousISRCycles == ulISRCycles ) + { + xStatus = pdFAIL; + } + + ulPreviousISRCycles = ulISRCycles; + + return xStatus; +} diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/GenQTest.c b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/GenQTest.c new file mode 100644 index 0000000..e278ca6 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/GenQTest.c @@ -0,0 +1,1039 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + + +/* + * Tests the extra queue functionality introduced in FreeRTOS.org V4.5.0 - + * including xQueueSendToFront(), xQueueSendToBack(), xQueuePeek() and + * mutex behaviour. + * + * See the comments above the prvSendFrontAndBackTest() and + * prvLowPriorityMutexTask() prototypes below for more information. + */ + +/* Standard includes. */ +#include + +/* Scheduler include files. */ +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" +#include "semphr.h" + +/* Demo program include files. */ +#include "GenQTest.h" + +#define genqQUEUE_LENGTH ( 5 ) +#define intsemNO_BLOCK ( 0 ) +#define genqSHORT_BLOCK ( pdMS_TO_TICKS( 2 ) ) + +#define genqMUTEX_LOW_PRIORITY ( tskIDLE_PRIORITY ) +#define genqMUTEX_TEST_PRIORITY ( tskIDLE_PRIORITY + 1 ) +#define genqMUTEX_MEDIUM_PRIORITY ( tskIDLE_PRIORITY + 2 ) +#define genqMUTEX_HIGH_PRIORITY ( tskIDLE_PRIORITY + 3 ) + +#ifndef genqMUTEX_TEST_TASK_STACK_SIZE + #define genqMUTEX_TEST_TASK_STACK_SIZE configMINIMAL_STACK_SIZE +#endif + +#ifndef genqGENERIC_QUEUE_TEST_TASK_STACK_SIZE + #define genqGENERIC_QUEUE_TEST_TASK_STACK_SIZE configMINIMAL_STACK_SIZE +#endif +/*-----------------------------------------------------------*/ + +/* + * Tests the behaviour of the xQueueSendToFront() and xQueueSendToBack() + * macros by using both to fill a queue, then reading from the queue to + * check the resultant queue order is as expected. Queue data is also + * peeked. + */ +static void prvSendFrontAndBackTest( void * pvParameters ); + +/* + * The following three tasks are used to demonstrate the mutex behaviour. + * Each task is given a different priority to demonstrate the priority + * inheritance mechanism. + * + * The low priority task obtains a mutex. After this a high priority task + * attempts to obtain the same mutex, causing its priority to be inherited + * by the low priority task. The task with the inherited high priority then + * resumes a medium priority task to ensure it is not blocked by the medium + * priority task while it holds the inherited high priority. Once the mutex + * is returned the task with the inherited priority returns to its original + * low priority, and is therefore immediately preempted by first the high + * priority task and then the medium priority task before it can continue. + */ +static void prvLowPriorityMutexTask( void * pvParameters ); +static void prvMediumPriorityMutexTask( void * pvParameters ); +static void prvHighPriorityMutexTask( void * pvParameters ); + +/* + * Tests the behaviour when a low priority task inherits the priority of a + * higher priority task when taking two mutexes, and returns the mutexes in + * first the same order as the two mutexes were obtained, and second the + * opposite order as the two mutexes were obtained. + */ +static void prvTakeTwoMutexesReturnInSameOrder( SemaphoreHandle_t xMutex, + SemaphoreHandle_t xLocalMutex ); +static void prvTakeTwoMutexesReturnInDifferentOrder( SemaphoreHandle_t xMutex, + SemaphoreHandle_t xLocalMutex ); + +#if ( INCLUDE_xTaskAbortDelay == 1 ) + + #if ( configUSE_PREEMPTION == 0 ) + #error The additional tests included when INCLUDE_xTaskAbortDelay is 1 expect preemption to be used. + #endif + +/* Tests the behaviour when a low priority task inherits the priority of a + * high priority task only for the high priority task to timeout before + * obtaining the mutex. */ + static void prvHighPriorityTimeout( SemaphoreHandle_t xMutex ); +#endif + +/*-----------------------------------------------------------*/ + +/* Flag that will be latched to pdTRUE should any unexpected behaviour be + * detected in any of the tasks. */ +static volatile BaseType_t xErrorDetected = pdFALSE; + +/* Counters that are incremented on each cycle of a test. This is used to + * detect a stalled task - a test that is no longer running. */ +static volatile uint32_t ulLoopCounter = 0; +static volatile uint32_t ulLoopCounter2 = 0; + +/* The variable that is guarded by the mutex in the mutex demo tasks. */ +static volatile uint32_t ulGuardedVariable = 0; + +/* Handles used in the mutex test to suspend and resume the high and medium + * priority mutex test tasks. */ +static TaskHandle_t xHighPriorityMutexTask, xMediumPriorityMutexTask; + +/* If INCLUDE_xTaskAbortDelay is 1 additional tests are performed, requiring an + * additional task. */ +#if ( INCLUDE_xTaskAbortDelay == 1 ) + static TaskHandle_t xSecondMediumPriorityMutexTask; +#endif + +/* Lets the high priority semaphore task know that its wait for the semaphore + * was aborted, in which case not being able to obtain the semaphore is not to be + * considered an error. */ +static volatile BaseType_t xBlockWasAborted = pdFALSE; + +/*-----------------------------------------------------------*/ + +void vStartGenericQueueTasks( UBaseType_t uxPriority ) +{ + QueueHandle_t xQueue; + SemaphoreHandle_t xMutex; + + /* Create the queue that we are going to use for the + * prvSendFrontAndBackTest demo. */ + xQueue = xQueueCreate( genqQUEUE_LENGTH, sizeof( uint32_t ) ); + + if( xQueue != NULL ) + { + /* vQueueAddToRegistry() adds the queue to the queue registry, if one + * is in use. The queue registry is provided as a means for kernel aware + * debuggers to locate queues and has no purpose if a kernel aware debugger + * is not being used. The call to vQueueAddToRegistry() will be removed + * by the pre-processor if configQUEUE_REGISTRY_SIZE is not defined or is + * defined to be less than 1. */ + vQueueAddToRegistry( xQueue, "Gen_Queue_Test" ); + + /* Create the demo task and pass it the queue just created. We are + * passing the queue handle by value so it does not matter that it is + * declared on the stack here. */ + xTaskCreate( prvSendFrontAndBackTest, "GenQ", genqGENERIC_QUEUE_TEST_TASK_STACK_SIZE, ( void * ) xQueue, uxPriority, NULL ); + } + + /* Create the mutex used by the prvMutexTest task. */ + xMutex = xSemaphoreCreateMutex(); + + if( xMutex != NULL ) + { + /* vQueueAddToRegistry() adds the mutex to the registry, if one is + * in use. The registry is provided as a means for kernel aware + * debuggers to locate mutexes and has no purpose if a kernel aware + * debugger is not being used. The call to vQueueAddToRegistry() will be + * removed by the pre-processor if configQUEUE_REGISTRY_SIZE is not + * defined or is defined to be less than 1. */ + vQueueAddToRegistry( ( QueueHandle_t ) xMutex, "Gen_Queue_Mutex" ); + + /* Create the mutex demo tasks and pass it the mutex just created. We + * are passing the mutex handle by value so it does not matter that it is + * declared on the stack here. */ + xTaskCreate( prvLowPriorityMutexTask, "MuLow", genqMUTEX_TEST_TASK_STACK_SIZE, ( void * ) xMutex, genqMUTEX_LOW_PRIORITY, NULL ); + xTaskCreate( prvMediumPriorityMutexTask, "MuMed", configMINIMAL_STACK_SIZE, NULL, genqMUTEX_MEDIUM_PRIORITY, &xMediumPriorityMutexTask ); + xTaskCreate( prvHighPriorityMutexTask, "MuHigh", genqMUTEX_TEST_TASK_STACK_SIZE, ( void * ) xMutex, genqMUTEX_HIGH_PRIORITY, &xHighPriorityMutexTask ); + + /* If INCLUDE_xTaskAbortDelay is set then additional tests are performed, + * requiring two instances of prvHighPriorityMutexTask(). */ + #if ( INCLUDE_xTaskAbortDelay == 1 ) + { + xTaskCreate( prvHighPriorityMutexTask, "MuHigh2", configMINIMAL_STACK_SIZE, ( void * ) xMutex, genqMUTEX_MEDIUM_PRIORITY, &xSecondMediumPriorityMutexTask ); + } + #endif /* INCLUDE_xTaskAbortDelay */ + } +} +/*-----------------------------------------------------------*/ + +static void prvSendFrontAndBackTest( void * pvParameters ) +{ + uint32_t ulData, ulData2, ulLoopCounterSnapshot; + QueueHandle_t xQueue; + + #ifdef USE_STDIO + void vPrintDisplayMessage( const char * const * ppcMessageToSend ); + + const char * const pcTaskStartMsg = "Queue SendToFront/SendToBack/Peek test started.\r\n"; + + /* Queue a message for printing to say the task has started. */ + vPrintDisplayMessage( &pcTaskStartMsg ); + #endif + + xQueue = ( QueueHandle_t ) pvParameters; + + for( ; ; ) + { + /* The queue is empty, so sending an item to the back of the queue + * should have the same effect as sending it to the front of the queue. + * + * First send to the front and check everything is as expected. */ + ulLoopCounterSnapshot = ulLoopCounter; + xQueueSendToFront( xQueue, ( void * ) &ulLoopCounterSnapshot, intsemNO_BLOCK ); + + if( uxQueueMessagesWaiting( xQueue ) != 1 ) + { + xErrorDetected = pdTRUE; + } + + if( xQueueReceive( xQueue, ( void * ) &ulData, intsemNO_BLOCK ) != pdPASS ) + { + xErrorDetected = pdTRUE; + } + + /* The data we sent to the queue should equal the data we just received + * from the queue. */ + if( ulLoopCounter != ulData ) + { + xErrorDetected = pdTRUE; + } + + /* Then do the same, sending the data to the back, checking everything + * is as expected. */ + if( uxQueueMessagesWaiting( xQueue ) != 0 ) + { + xErrorDetected = pdTRUE; + } + + ulLoopCounterSnapshot = ulLoopCounter; + xQueueSendToBack( xQueue, ( void * ) &ulLoopCounterSnapshot, intsemNO_BLOCK ); + + if( uxQueueMessagesWaiting( xQueue ) != 1 ) + { + xErrorDetected = pdTRUE; + } + + if( xQueueReceive( xQueue, ( void * ) &ulData, intsemNO_BLOCK ) != pdPASS ) + { + xErrorDetected = pdTRUE; + } + + if( uxQueueMessagesWaiting( xQueue ) != 0 ) + { + xErrorDetected = pdTRUE; + } + + /* The data sent to the queue should equal the data just received from + * the queue. */ + if( ulLoopCounter != ulData ) + { + xErrorDetected = pdTRUE; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + /* Place 2, 3, 4 into the queue, adding items to the back of the queue. */ + for( ulData = 2; ulData < 5; ulData++ ) + { + xQueueSendToBack( xQueue, ( void * ) &ulData, intsemNO_BLOCK ); + } + + /* Now the order in the queue should be 2, 3, 4, with 2 being the first + * thing to be read out. Now add 1 then 0 to the front of the queue. */ + if( uxQueueMessagesWaiting( xQueue ) != 3 ) + { + xErrorDetected = pdTRUE; + } + + ulData = 1; + xQueueSendToFront( xQueue, ( void * ) &ulData, intsemNO_BLOCK ); + ulData = 0; + xQueueSendToFront( xQueue, ( void * ) &ulData, intsemNO_BLOCK ); + + /* Now the queue should be full, and when we read the data out we + * should receive 0, 1, 2, 3, 4. */ + if( uxQueueMessagesWaiting( xQueue ) != 5 ) + { + xErrorDetected = pdTRUE; + } + + if( xQueueSendToFront( xQueue, ( void * ) &ulData, intsemNO_BLOCK ) != errQUEUE_FULL ) + { + xErrorDetected = pdTRUE; + } + + if( xQueueSendToBack( xQueue, ( void * ) &ulData, intsemNO_BLOCK ) != errQUEUE_FULL ) + { + xErrorDetected = pdTRUE; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + /* Check the data we read out is in the expected order. */ + for( ulData = 0; ulData < genqQUEUE_LENGTH; ulData++ ) + { + /* Try peeking the data first. */ + if( xQueuePeek( xQueue, &ulData2, intsemNO_BLOCK ) != pdPASS ) + { + xErrorDetected = pdTRUE; + } + + if( ulData != ulData2 ) + { + xErrorDetected = pdTRUE; + } + + /* Now try receiving the data for real. The value should be the + * same. Clobber the value first so we know we really received it. */ + ulData2 = ~ulData2; + + if( xQueueReceive( xQueue, &ulData2, intsemNO_BLOCK ) != pdPASS ) + { + xErrorDetected = pdTRUE; + } + + if( ulData != ulData2 ) + { + xErrorDetected = pdTRUE; + } + } + + /* The queue should now be empty again. */ + if( uxQueueMessagesWaiting( xQueue ) != 0 ) + { + xErrorDetected = pdTRUE; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + + /* Our queue is empty once more, add 10, 11 to the back. */ + ulData = 10; + + if( xQueueSend( xQueue, &ulData, intsemNO_BLOCK ) != pdPASS ) + { + xErrorDetected = pdTRUE; + } + + ulData = 11; + + if( xQueueSend( xQueue, &ulData, intsemNO_BLOCK ) != pdPASS ) + { + xErrorDetected = pdTRUE; + } + + if( uxQueueMessagesWaiting( xQueue ) != 2 ) + { + xErrorDetected = pdTRUE; + } + + /* Now we should have 10, 11 in the queue. Add 7, 8, 9 to the + * front. */ + for( ulData = 9; ulData >= 7; ulData-- ) + { + if( xQueueSendToFront( xQueue, ( void * ) &ulData, intsemNO_BLOCK ) != pdPASS ) + { + xErrorDetected = pdTRUE; + } + } + + /* Now check that the queue is full, and that receiving data provides + * the expected sequence of 7, 8, 9, 10, 11. */ + if( uxQueueMessagesWaiting( xQueue ) != 5 ) + { + xErrorDetected = pdTRUE; + } + + if( xQueueSendToFront( xQueue, ( void * ) &ulData, intsemNO_BLOCK ) != errQUEUE_FULL ) + { + xErrorDetected = pdTRUE; + } + + if( xQueueSendToBack( xQueue, ( void * ) &ulData, intsemNO_BLOCK ) != errQUEUE_FULL ) + { + xErrorDetected = pdTRUE; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + /* Check the data we read out is in the expected order. */ + for( ulData = 7; ulData < ( 7 + genqQUEUE_LENGTH ); ulData++ ) + { + if( xQueueReceive( xQueue, &ulData2, intsemNO_BLOCK ) != pdPASS ) + { + xErrorDetected = pdTRUE; + } + + if( ulData != ulData2 ) + { + xErrorDetected = pdTRUE; + } + } + + if( uxQueueMessagesWaiting( xQueue ) != 0 ) + { + xErrorDetected = pdTRUE; + } + + /* Increment the loop counter to indicate these tasks are still + * executing. */ + ulLoopCounter++; + } +} +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_xTaskAbortDelay == 1 ) + + static void prvHighPriorityTimeout( SemaphoreHandle_t xMutex ) + { + static UBaseType_t uxLoopCount = 0; + + /* The tests in this function are very similar, the slight variations + * are for code coverage purposes. */ + + /* Take the mutex. It should be available now. Check before and after + * taking that the holder is reported correctly. */ + if( xSemaphoreGetMutexHolder( xMutex ) != NULL ) + { + xErrorDetected = pdTRUE; + } + + if( xSemaphoreTake( xMutex, intsemNO_BLOCK ) != pdPASS ) + { + xErrorDetected = pdTRUE; + } + + if( xSemaphoreGetMutexHolder( xMutex ) != xTaskGetCurrentTaskHandle() ) + { + xErrorDetected = pdTRUE; + } + + /* This task's priority should be as per that assigned when the task was + * created. */ + if( uxTaskPriorityGet( NULL ) != genqMUTEX_LOW_PRIORITY ) + { + xErrorDetected = pdTRUE; + } + + /* Now unsuspend the high priority task. This will attempt to take the + * mutex, and block when it finds it cannot obtain it. */ + vTaskResume( xHighPriorityMutexTask ); + + /* This task should now have inherited the priority of the high priority + * task as by now the high priority task will have attempted to obtain the + * mutex. */ + if( uxTaskPriorityGet( NULL ) != genqMUTEX_HIGH_PRIORITY ) + { + xErrorDetected = pdTRUE; + } + + /* Unblock a second medium priority task. It too will attempt to take + * the mutex and enter the Blocked state - it won't run yet though as this + * task has inherited a priority above it. */ + vTaskResume( xSecondMediumPriorityMutexTask ); + + /* This task should still have the priority of the high priority task as + * that had already been inherited as is the highest priority of the three + * tasks using the mutex. */ + if( uxTaskPriorityGet( NULL ) != genqMUTEX_HIGH_PRIORITY ) + { + xErrorDetected = pdTRUE; + } + + /* On some loops, block for a short while to provide additional + * code coverage. Blocking here will allow the medium priority task to + * execute and so also block on the mutex so when the high priority task + * causes this task to disinherit the high priority it is inherited down to + * the priority of the medium priority task. When there is no delay the + * medium priority task will not run until after the disinheritance, so + * this task will disinherit back to its base priority, then only up to the + * medium priority after the medium priority has executed. */ + vTaskDelay( uxLoopCount & ( UBaseType_t ) 0x07 ); + + /* Now force the high priority task to unblock. It will fail to obtain + * the mutex and go back to the suspended state - allowing this task to + * execute again. xBlockWasAborted is set to pdTRUE so the higher priority + * task knows that its failure to obtain the semaphore is not an error. */ + xBlockWasAborted = pdTRUE; + + if( xTaskAbortDelay( xHighPriorityMutexTask ) != pdPASS ) + { + xErrorDetected = pdTRUE; + } + + /* This task has inherited the priority of xHighPriorityMutexTask so + * could still be running even though xHighPriorityMutexTask is no longer + * blocked. Delay for a short while to ensure xHighPriorityMutexTask gets + * a chance to run - indicated by this task changing priority. It should + * disinherit the high priority task, but then inherit the priority of the + * medium priority task that is waiting for the same mutex. */ + while( uxTaskPriorityGet( NULL ) != genqMUTEX_MEDIUM_PRIORITY ) + { + /* If this task gets stuck here then the check variables will stop + * incrementing and the check task will detect the error. */ + vTaskDelay( genqSHORT_BLOCK ); + } + + /* Now force the medium priority task to unblock. xBlockWasAborted is + * set to pdTRUE so the medium priority task knows that its failure to + * obtain the semaphore is not an error. */ + xBlockWasAborted = pdTRUE; + + if( xTaskAbortDelay( xSecondMediumPriorityMutexTask ) != pdPASS ) + { + xErrorDetected = pdTRUE; + } + + /* This time no other tasks are waiting for the mutex, so this task + * should return to its base priority. This might not happen straight + * away as it is running at the same priority as the task it just + * unblocked. */ + while( uxTaskPriorityGet( NULL ) != genqMUTEX_LOW_PRIORITY ) + { + /* If this task gets stuck here then the check variables will stop + * incrementing and the check task will detect the error. */ + vTaskDelay( genqSHORT_BLOCK ); + } + + /* Give the semaphore back ready for the next test. Check the mutex + * holder before and after using the "FromISR" version for code coverage. */ + if( xSemaphoreGetMutexHolderFromISR( xMutex ) != xTaskGetCurrentTaskHandle() ) + { + xErrorDetected = pdTRUE; + } + + xSemaphoreGive( xMutex ); + + if( xSemaphoreGetMutexHolderFromISR( xMutex ) != NULL ) + { + xErrorDetected = pdTRUE; + } + + configASSERT( xErrorDetected == pdFALSE ); + + /* Now do the same again, but this time unsuspend the tasks in the + * opposite order. This takes a different path though the code because + * when the high priority task has its block aborted there is already + * another task in the list of tasks waiting for the mutex, and the + * low priority task drops down to that priority, rather than dropping + * down to its base priority before inheriting the priority of the medium + * priority task. */ + if( xSemaphoreTake( xMutex, intsemNO_BLOCK ) != pdPASS ) + { + xErrorDetected = pdTRUE; + } + + if( uxTaskPriorityGet( NULL ) != genqMUTEX_LOW_PRIORITY ) + { + xErrorDetected = pdTRUE; + } + + /* This time unsuspend the medium priority task first. This will + * attempt to take the mutex, and block when it finds it cannot obtain it. */ + vTaskResume( xSecondMediumPriorityMutexTask ); + + /* This time this task should now have inherited the priority of the + * medium task. */ + if( uxTaskPriorityGet( NULL ) != genqMUTEX_MEDIUM_PRIORITY ) + { + xErrorDetected = pdTRUE; + } + + /* This time the high priority task in unsuspended second. */ + vTaskResume( xHighPriorityMutexTask ); + + /* The high priority task should already have run, causing this task to + * inherit a priority for the second time. */ + if( uxTaskPriorityGet( NULL ) != genqMUTEX_HIGH_PRIORITY ) + { + xErrorDetected = pdTRUE; + } + + /* This time, when the high priority task has its delay aborted and it + * fails to obtain the mutex this task will immediately have its priority + * lowered down to that of the highest priority task waiting on the mutex, + * which is the medium priority task. */ + xBlockWasAborted = pdTRUE; + + if( xTaskAbortDelay( xHighPriorityMutexTask ) != pdPASS ) + { + xErrorDetected = pdTRUE; + } + + while( uxTaskPriorityGet( NULL ) != genqMUTEX_MEDIUM_PRIORITY ) + { + /* If this task gets stuck here then the check variables will stop + * incrementing and the check task will detect the error. */ + vTaskDelay( genqSHORT_BLOCK ); + } + + /* And finally, when the medium priority task also have its delay + * aborted there are no other tasks waiting for the mutex so this task + * returns to its base priority. */ + xBlockWasAborted = pdTRUE; + + if( xTaskAbortDelay( xSecondMediumPriorityMutexTask ) != pdPASS ) + { + xErrorDetected = pdTRUE; + } + + while( uxTaskPriorityGet( NULL ) != genqMUTEX_LOW_PRIORITY ) + { + /* If this task gets stuck here then the check variables will stop + * incrementing and the check task will detect the error. */ + vTaskDelay( genqSHORT_BLOCK ); + } + + /* Give the semaphore back ready for the next test. */ + xSemaphoreGive( xMutex ); + + configASSERT( xErrorDetected == pdFALSE ); + + /* uxLoopCount is used to add a variable delay, and in-so-doing provide + * additional code coverage. */ + uxLoopCount++; + } + +#endif /* INCLUDE_xTaskAbortDelay == 1 */ +/*-----------------------------------------------------------*/ + +static void prvTakeTwoMutexesReturnInDifferentOrder( SemaphoreHandle_t xMutex, + SemaphoreHandle_t xLocalMutex ) +{ + /* Take the mutex. It should be available now. */ + if( xSemaphoreTake( xMutex, intsemNO_BLOCK ) != pdPASS ) + { + xErrorDetected = pdTRUE; + } + + /* Set the guarded variable to a known start value. */ + ulGuardedVariable = 0; + + /* This task's priority should be as per that assigned when the task was + * created. */ + if( uxTaskPriorityGet( NULL ) != genqMUTEX_LOW_PRIORITY ) + { + xErrorDetected = pdTRUE; + } + + /* Now unsuspend the high priority task. This will attempt to take the + * mutex, and block when it finds it cannot obtain it. */ + vTaskResume( xHighPriorityMutexTask ); + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + /* Ensure the task is reporting its priority as blocked and not + * suspended (as it would have done in versions up to V7.5.3). */ + #if ( INCLUDE_eTaskGetState == 1 ) + { + configASSERT( eTaskGetState( xHighPriorityMutexTask ) == eBlocked ); + } + #endif /* INCLUDE_eTaskGetState */ + + /* This task should now have inherited the priority of the high priority + * task as by now the high priority task will have attempted to obtain the + * mutex. */ + if( uxTaskPriorityGet( NULL ) != genqMUTEX_HIGH_PRIORITY ) + { + xErrorDetected = pdTRUE; + } + + /* Attempt to set the priority of this task to the test priority - + * between the idle priority and the medium/high test priorities, but the + * actual priority should remain at the high priority. */ + vTaskPrioritySet( NULL, genqMUTEX_TEST_PRIORITY ); + + if( uxTaskPriorityGet( NULL ) != genqMUTEX_HIGH_PRIORITY ) + { + xErrorDetected = pdTRUE; + } + + /* Now unsuspend the medium priority task. This should not run as the + * inherited priority of this task is above that of the medium priority + * task. */ + vTaskResume( xMediumPriorityMutexTask ); + + /* If the medium priority task did run then it will have incremented the + * guarded variable. */ + if( ulGuardedVariable != 0 ) + { + xErrorDetected = pdTRUE; + } + + /* Take the local mutex too, so two mutexes are now held. */ + if( xSemaphoreTake( xLocalMutex, intsemNO_BLOCK ) != pdPASS ) + { + xErrorDetected = pdTRUE; + } + + /* When the semaphore is given back the priority of this task should not + * yet be disinherited because the local mutex is still held. This is a + * simplification to allow FreeRTOS to be integrated with middleware that + * attempts to hold multiple mutexes without bloating the code with complex + * algorithms. It is possible that the high priority mutex task will + * execute as it shares a priority with this task. */ + if( xSemaphoreGive( xMutex ) != pdPASS ) + { + xErrorDetected = pdTRUE; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + /* The guarded variable is only incremented by the medium priority task, + * which still should not have executed as this task should remain at the + * higher priority, ensure this is the case. */ + if( ulGuardedVariable != 0 ) + { + xErrorDetected = pdTRUE; + } + + if( uxTaskPriorityGet( NULL ) != genqMUTEX_HIGH_PRIORITY ) + { + xErrorDetected = pdTRUE; + } + + /* Now also give back the local mutex, taking the held count back to 0. + * This time the priority of this task should be disinherited back to the + * priority to which it was set while the mutex was held. This means + * the medium priority task should execute and increment the guarded + * variable. When this task next runs both the high and medium priority + * tasks will have been suspended again. */ + if( xSemaphoreGive( xLocalMutex ) != pdPASS ) + { + xErrorDetected = pdTRUE; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + /* Check the guarded variable did indeed increment... */ + if( ulGuardedVariable != 1 ) + { + xErrorDetected = pdTRUE; + } + + /* ... and that the priority of this task has been disinherited to + * genqMUTEX_TEST_PRIORITY. */ + if( uxTaskPriorityGet( NULL ) != genqMUTEX_TEST_PRIORITY ) + { + xErrorDetected = pdTRUE; + } + + /* Set the priority of this task back to its original value, ready for + * the next loop around this test. */ + vTaskPrioritySet( NULL, genqMUTEX_LOW_PRIORITY ); +} +/*-----------------------------------------------------------*/ + +static void prvTakeTwoMutexesReturnInSameOrder( SemaphoreHandle_t xMutex, + SemaphoreHandle_t xLocalMutex ) +{ + /* Take the mutex. It should be available now. */ + if( xSemaphoreTake( xMutex, intsemNO_BLOCK ) != pdPASS ) + { + xErrorDetected = pdTRUE; + } + + /* Set the guarded variable to a known start value. */ + ulGuardedVariable = 0; + + /* This task's priority should be as per that assigned when the task was + * created. */ + if( uxTaskPriorityGet( NULL ) != genqMUTEX_LOW_PRIORITY ) + { + xErrorDetected = pdTRUE; + } + + /* Now unsuspend the high priority task. This will attempt to take the + * mutex, and block when it finds it cannot obtain it. */ + vTaskResume( xHighPriorityMutexTask ); + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + /* Ensure the task is reporting its priority as blocked and not + * suspended (as it would have done in versions up to V7.5.3). */ + #if ( INCLUDE_eTaskGetState == 1 ) + { + configASSERT( eTaskGetState( xHighPriorityMutexTask ) == eBlocked ); + } + #endif /* INCLUDE_eTaskGetState */ + + /* This task should now have inherited the priority of the high priority + * task as by now the high priority task will have attempted to obtain the + * mutex. */ + if( uxTaskPriorityGet( NULL ) != genqMUTEX_HIGH_PRIORITY ) + { + xErrorDetected = pdTRUE; + } + + /* Now unsuspend the medium priority task. This should not run as the + * inherited priority of this task is above that of the medium priority + * task. */ + vTaskResume( xMediumPriorityMutexTask ); + + /* If the medium priority task did run then it will have incremented the + * guarded variable. */ + if( ulGuardedVariable != 0 ) + { + xErrorDetected = pdTRUE; + } + + /* Take the local mutex too, so two mutexes are now held. */ + if( xSemaphoreTake( xLocalMutex, intsemNO_BLOCK ) != pdPASS ) + { + xErrorDetected = pdTRUE; + } + + /* When the local semaphore is given back the priority of this task should + * not yet be disinherited because the shared mutex is still held. This is a + * simplification to allow FreeRTOS to be integrated with middleware that + * attempts to hold multiple mutexes without bloating the code with complex + * algorithms. It is possible that the high priority mutex task will + * execute as it shares a priority with this task. */ + if( xSemaphoreGive( xLocalMutex ) != pdPASS ) + { + xErrorDetected = pdTRUE; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + /* The guarded variable is only incremented by the medium priority task, + * which still should not have executed as this task should remain at the + * higher priority, ensure this is the case. */ + if( ulGuardedVariable != 0 ) + { + xErrorDetected = pdTRUE; + } + + if( uxTaskPriorityGet( NULL ) != genqMUTEX_HIGH_PRIORITY ) + { + xErrorDetected = pdTRUE; + } + + /* Now also give back the shared mutex, taking the held count back to 0. + * This time the priority of this task should be disinherited back to the + * priority at which it was created. This means the medium priority task + * should execute and increment the guarded variable. When this task next runs + * both the high and medium priority tasks will have been suspended again. */ + if( xSemaphoreGive( xMutex ) != pdPASS ) + { + xErrorDetected = pdTRUE; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + /* Check the guarded variable did indeed increment... */ + if( ulGuardedVariable != 1 ) + { + xErrorDetected = pdTRUE; + } + + /* ... and that the priority of this task has been disinherited to + * genqMUTEX_LOW_PRIORITY. */ + if( uxTaskPriorityGet( NULL ) != genqMUTEX_LOW_PRIORITY ) + { + xErrorDetected = pdTRUE; + } +} +/*-----------------------------------------------------------*/ + +static void prvLowPriorityMutexTask( void * pvParameters ) +{ + SemaphoreHandle_t xMutex = ( SemaphoreHandle_t ) pvParameters, xLocalMutex; + + #ifdef USE_STDIO + void vPrintDisplayMessage( const char * const * ppcMessageToSend ); + + const char * const pcTaskStartMsg = "Mutex with priority inheritance test started.\r\n"; + + /* Queue a message for printing to say the task has started. */ + vPrintDisplayMessage( &pcTaskStartMsg ); + #endif + + /* The local mutex is used to check the 'mutex held' count. */ + xLocalMutex = xSemaphoreCreateMutex(); + configASSERT( xLocalMutex ); + + for( ; ; ) + { + /* The first tests exercise the priority inheritance when two mutexes + * are taken then returned in a different order to which they were + * taken. */ + prvTakeTwoMutexesReturnInDifferentOrder( xMutex, xLocalMutex ); + + /* Just to show this task is still running. */ + ulLoopCounter2++; + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + /* The second tests exercise the priority inheritance when two mutexes + * are taken then returned in the same order in which they were taken. */ + prvTakeTwoMutexesReturnInSameOrder( xMutex, xLocalMutex ); + + /* Just to show this task is still running. */ + ulLoopCounter2++; + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + #if ( INCLUDE_xTaskAbortDelay == 1 ) + { + /* Tests the behaviour when a low priority task inherits the + * priority of a high priority task only for the high priority task to + * timeout before obtaining the mutex. */ + prvHighPriorityTimeout( xMutex ); + } + #endif + } +} +/*-----------------------------------------------------------*/ + +static void prvMediumPriorityMutexTask( void * pvParameters ) +{ + ( void ) pvParameters; + + for( ; ; ) + { + /* The medium priority task starts by suspending itself. The low + * priority task will unsuspend this task when required. */ + vTaskSuspend( NULL ); + + /* When this task unsuspends all it does is increment the guarded + * variable, this is so the low priority task knows that it has + * executed. */ + ulGuardedVariable++; + } +} +/*-----------------------------------------------------------*/ + +static void prvHighPriorityMutexTask( void * pvParameters ) +{ + SemaphoreHandle_t xMutex = ( SemaphoreHandle_t ) pvParameters; + + for( ; ; ) + { + /* The high priority task starts by suspending itself. The low + * priority task will unsuspend this task when required. */ + vTaskSuspend( NULL ); + + /* When this task unsuspends all it does is attempt to obtain the + * mutex. It should find the mutex is not available so a block time is + * specified. */ + if( xSemaphoreTake( xMutex, portMAX_DELAY ) != pdPASS ) + { + /* This task would expect to obtain the mutex unless its wait for + * the mutex was aborted. */ + if( xBlockWasAborted == pdFALSE ) + { + xErrorDetected = pdTRUE; + } + else + { + xBlockWasAborted = pdFALSE; + } + } + else + { + /* When the mutex is eventually obtained it is just given back before + * returning to suspend ready for the next cycle. */ + if( xSemaphoreGive( xMutex ) != pdPASS ) + { + xErrorDetected = pdTRUE; + } + } + } +} +/*-----------------------------------------------------------*/ + + +/* This is called to check that all the created tasks are still running. */ +BaseType_t xAreGenericQueueTasksStillRunning( void ) +{ + static uint32_t ulLastLoopCounter = 0, ulLastLoopCounter2 = 0; + + /* If the demo task is still running then we expect the loop counters to + * have incremented since this function was last called. */ + if( ulLastLoopCounter == ulLoopCounter ) + { + xErrorDetected = pdTRUE; + } + + if( ulLastLoopCounter2 == ulLoopCounter2 ) + { + xErrorDetected = pdTRUE; + } + + ulLastLoopCounter = ulLoopCounter; + ulLastLoopCounter2 = ulLoopCounter2; + + /* Errors detected in the task itself will have latched xErrorDetected + * to true. */ + + return ( BaseType_t ) !xErrorDetected; +} diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/MessageBufferDemo.c b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/MessageBufferDemo.c new file mode 100644 index 0000000..783a65d --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/MessageBufferDemo.c @@ -0,0 +1,972 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +/* Standard includes. */ +#include "stdio.h" +#include "string.h" + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "message_buffer.h" + +/* Demo app includes. */ +#include "MessageBufferDemo.h" + +/* The number of bytes of storage in the message buffers used in this test. */ +#define mbMESSAGE_BUFFER_LENGTH_BYTES ( ( size_t ) 50 ) + +/* The number of additional bytes used to store the length of each message. */ +#define mbBYTES_TO_STORE_MESSAGE_LENGTH ( sizeof( configMESSAGE_BUFFER_LENGTH_TYPE ) ) + +/* Start and end ASCII characters used in messages sent to the buffers. */ +#define mbASCII_SPACE 32 +#define mbASCII_TILDA 126 + +/* Defines the number of tasks to create in this test and demo. */ +#define mbNUMBER_OF_ECHO_CLIENTS ( 2 ) +#define mbNUMBER_OF_SENDER_TASKS ( 2 ) + +/* Priority of the test tasks. The send and receive go from low to high + * priority tasks, and from high to low priority tasks. */ +#define mbLOWER_PRIORITY ( tskIDLE_PRIORITY ) +#define mbHIGHER_PRIORITY ( tskIDLE_PRIORITY + 1 ) + +/* Block times used when sending and receiving from the message buffers. */ +#define mbRX_TX_BLOCK_TIME pdMS_TO_TICKS( 175UL ) + +/* A block time of 0 means "don't block". */ +#define mbDONT_BLOCK ( 0 ) + +/*-----------------------------------------------------------*/ + +/* + * Performs various tests that do not require multiple tasks to interact. + */ +static void prvSingleTaskTests( MessageBufferHandle_t xMessageBuffer ); + +/* + * Tests sending and receiving various lengths of messages via a message buffer. + * The echo client sends the messages to the echo server, which then sends the + * message back to the echo client which, checks it receives exactly what it + * sent. + */ +static void prvEchoClient( void * pvParameters ); +static void prvEchoServer( void * pvParameters ); + +/* + * Tasks that send and receive to a message buffer at a low priority and without + * blocking, so the send and receive functions interleave in time as the tasks + * are switched in and out. + */ +static void prvNonBlockingReceiverTask( void * pvParameters ); +static void prvNonBlockingSenderTask( void * pvParameters ); + +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + +/* This file tests both statically and dynamically allocated message buffers. + * Allocate the structures and buffers to be used by the statically allocated + * objects, which get used in the echo tests. */ + static void prvReceiverTask( void * pvParameters ); + static void prvSenderTask( void * pvParameters ); + + static StaticMessageBuffer_t xStaticMessageBuffers[ mbNUMBER_OF_ECHO_CLIENTS ]; + static uint8_t ucBufferStorage[ mbNUMBER_OF_SENDER_TASKS ][ mbMESSAGE_BUFFER_LENGTH_BYTES + 1 ]; + static uint32_t ulSenderLoopCounters[ mbNUMBER_OF_SENDER_TASKS ] = { 0 }; +#endif /* configSUPPORT_STATIC_ALLOCATION */ + + +#if ( configRUN_ADDITIONAL_TESTS == 1 ) + #define mbCOHERENCE_TEST_BUFFER_SIZE 20 + #define mbCOHERENCE_TEST_BYTES_WRITTEN 5 + #define mbBYTES_TO_STORE_MESSAGE_LENGTH ( sizeof( configMESSAGE_BUFFER_LENGTH_TYPE ) ) + #define mbEXPECTED_FREE_BYTES_AFTER_WRITING_STRING ( mbCOHERENCE_TEST_BUFFER_SIZE - ( mbCOHERENCE_TEST_BYTES_WRITTEN + mbBYTES_TO_STORE_MESSAGE_LENGTH ) ) + + static void prvSpaceAvailableCoherenceActor( void * pvParameters ); + static void prvSpaceAvailableCoherenceTester( void * pvParameters ); + static MessageBufferHandle_t xCoherenceTestMessageBuffer = NULL; + + static uint32_t ulSizeCoherencyTestCycles = 0UL; +#endif /* if ( configRUN_ADDITIONAL_TESTS == 1 ) */ + +/*-----------------------------------------------------------*/ + +/* The buffers used by the echo client and server tasks. */ +typedef struct ECHO_MESSAGE_BUFFERS +{ + /* Handles to the data structures that describe the message buffers. */ + MessageBufferHandle_t xEchoClientBuffer; + MessageBufferHandle_t xEchoServerBuffer; +} EchoMessageBuffers_t; +static uint32_t ulEchoLoopCounters[ mbNUMBER_OF_ECHO_CLIENTS ] = { 0 }; + +/* The non-blocking tasks monitor their operation, and if no errors have been + * found, increment ulNonBlockingRxCounter. xAreMessageBufferTasksStillRunning() + * then checks ulNonBlockingRxCounter and only returns pdPASS if + * ulNonBlockingRxCounter is still incrementing. */ +static uint32_t ulNonBlockingRxCounter = 0; + +/* A message that is longer than the buffer, parts of which are written to the + * message buffer to test writing different lengths at different offsets. */ +static const char * pc55ByteString = "One two three four five six seven eight nine ten eleve"; + +/* Remember the required stack size so tasks can be created at run time (after + * initialisation time. */ +static configSTACK_DEPTH_TYPE xBlockingStackSize = 0; + +/*-----------------------------------------------------------*/ + +void vStartMessageBufferTasks( configSTACK_DEPTH_TYPE xStackSize ) +{ + MessageBufferHandle_t xMessageBuffer; + + #ifndef configMESSAGE_BUFFER_BLOCK_TASK_STACK_SIZE + xBlockingStackSize = ( xStackSize + ( xStackSize >> 1U ) ); + #else + xBlockingStackSize = configMESSAGE_BUFFER_BLOCK_TASK_STACK_SIZE; + #endif + + /* The echo servers sets up the message buffers before creating the echo + * client tasks. One set of tasks has the server as the higher priority, and + * the other has the client as the higher priority. */ + xTaskCreate( prvEchoServer, "1EchoServer", xBlockingStackSize, NULL, mbHIGHER_PRIORITY, NULL ); + xTaskCreate( prvEchoServer, "2EchoServer", xBlockingStackSize, NULL, mbLOWER_PRIORITY, NULL ); + + /* The non blocking tasks run continuously and will interleave with each + * other, so must be created at the lowest priority. The message buffer they + * use is created and passed in using the task's parameter. */ + xMessageBuffer = xMessageBufferCreate( mbMESSAGE_BUFFER_LENGTH_BYTES ); + xTaskCreate( prvNonBlockingReceiverTask, "NonBlkRx", xStackSize, ( void * ) xMessageBuffer, tskIDLE_PRIORITY, NULL ); + xTaskCreate( prvNonBlockingSenderTask, "NonBlkTx", xStackSize, ( void * ) xMessageBuffer, tskIDLE_PRIORITY, NULL ); + + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + /* The sender tasks set up the message buffers before creating the + * receiver tasks. Priorities must be 0 and 1 as the priority is used to + * index into the xStaticMessageBuffers and ucBufferStorage arrays. */ + xTaskCreate( prvSenderTask, "1Sender", xBlockingStackSize, NULL, mbHIGHER_PRIORITY, NULL ); + xTaskCreate( prvSenderTask, "2Sender", xBlockingStackSize, NULL, mbLOWER_PRIORITY, NULL ); + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ + + #if ( configRUN_ADDITIONAL_TESTS == 1 ) + { + xCoherenceTestMessageBuffer = xMessageBufferCreate( mbCOHERENCE_TEST_BUFFER_SIZE ); + configASSERT( xCoherenceTestMessageBuffer ); + + xTaskCreate( prvSpaceAvailableCoherenceActor, "mbsanity1", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL ); + xTaskCreate( prvSpaceAvailableCoherenceTester, "mbsanity2", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL ); + } + #endif +} +/*-----------------------------------------------------------*/ + +static void prvSingleTaskTests( MessageBufferHandle_t xMessageBuffer ) +{ + size_t xReturned, xItem, xExpectedSpace, xNextLength; + const size_t xMax6ByteMessages = mbMESSAGE_BUFFER_LENGTH_BYTES / ( 6 + mbBYTES_TO_STORE_MESSAGE_LENGTH ); + const size_t x6ByteLength = 6, x17ByteLength = 17; + uint8_t * pucFullBuffer, * pucData, * pucReadData; + TickType_t xTimeBeforeCall, xTimeAfterCall; + const TickType_t xBlockTime = pdMS_TO_TICKS( 25 ), xAllowableMargin = pdMS_TO_TICKS( 3 ); + UBaseType_t uxOriginalPriority; + + /* Remove warning in case configASSERT() is not defined. */ + ( void ) xAllowableMargin; + + /* To minimise stack and heap usage a full size buffer is allocated from + * the heap, then buffers which hold smaller amounts of data are overlayed + * with the larger buffer - just make sure not to use both at once!. */ + pucFullBuffer = pvPortMalloc( mbMESSAGE_BUFFER_LENGTH_BYTES ); + configASSERT( pucFullBuffer ); + + pucData = pucFullBuffer; + pucReadData = pucData + x17ByteLength; + + /* Nothing has been added or removed yet, so expect the free space to be + * exactly as created and the length of the next message to be 0. */ + xExpectedSpace = xMessageBufferSpaceAvailable( xMessageBuffer ); + configASSERT( xExpectedSpace == mbMESSAGE_BUFFER_LENGTH_BYTES ); + configASSERT( xMessageBufferIsEmpty( xMessageBuffer ) == pdTRUE ); + xNextLength = xMessageBufferNextLengthBytes( xMessageBuffer ); + configASSERT( xNextLength == 0 ); + /* In case configASSERT() is not define. */ + ( void ) xExpectedSpace; + ( void ) xNextLength; + + /* Try sending more bytes than possible, first using the FromISR version, then + * with an infinite block time to ensure this task does not lock up. */ + xReturned = xMessageBufferSendFromISR( xMessageBuffer, ( void * ) pucData, mbMESSAGE_BUFFER_LENGTH_BYTES + sizeof( configMESSAGE_BUFFER_LENGTH_TYPE ), NULL ); + configASSERT( xReturned == ( size_t ) 0 ); + /* In case configASSERT() is not defined. */ + ( void ) xReturned; + xReturned = xMessageBufferSend( xMessageBuffer, ( void * ) pucData, mbMESSAGE_BUFFER_LENGTH_BYTES + sizeof( configMESSAGE_BUFFER_LENGTH_TYPE ), portMAX_DELAY ); + configASSERT( xReturned == ( size_t ) 0 ); + /* In case configASSERT() is not defined. */ + ( void ) xReturned; + + /* The buffer is 50 bytes long. When an item is added to the buffer an + * additional 4 bytes are added to hold the item's size. That means adding + * 6 bytes to the buffer will actually add 10 bytes to the buffer. Therefore, + * with a 50 byte buffer, a maximum of 5 6 bytes items can be added before the + * buffer is completely full. NOTE: The numbers in this paragraph assume + * sizeof( configMESSAGE_BUFFER_LENGTH_TYPE ) == 4. */ + for( xItem = 0; xItem < xMax6ByteMessages; xItem++ ) + { + configASSERT( xMessageBufferIsFull( xMessageBuffer ) == pdFALSE ); + + /* Generate recognisable data to write to the buffer. This is just + * ascii characters that shows which loop iteration the data was written + * in. The 'FromISR' version is used to give it some exercise as a block + * time is not used. That requires the call to be in a critical section + * so this code can also run on FreeRTOS ports that do not support + * interrupt nesting (and so don't have interrupt safe critical + * sections).*/ + memset( ( void * ) pucData, ( ( int ) '0' ) + ( int ) xItem, x6ByteLength ); + taskENTER_CRITICAL(); + { + xReturned = xMessageBufferSendFromISR( xMessageBuffer, ( void * ) pucData, x6ByteLength, NULL ); + } + taskEXIT_CRITICAL(); + configASSERT( xReturned == x6ByteLength ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + + /* The space in the buffer will have reduced by the amount of user data + * written into the buffer and the amount of space used to store the length + * of the data written into the buffer. */ + xExpectedSpace -= ( x6ByteLength + mbBYTES_TO_STORE_MESSAGE_LENGTH ); + xReturned = xMessageBufferSpaceAvailable( xMessageBuffer ); + configASSERT( xReturned == xExpectedSpace ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + + /* Only 6 byte messages are written. */ + xNextLength = xMessageBufferNextLengthBytes( xMessageBuffer ); + configASSERT( xNextLength == x6ByteLength ); + ( void ) xNextLength; /* In case configASSERT() is not defined. */ + } + + /* Now the buffer should be full, and attempting to add anything will should + * fail. */ + configASSERT( xMessageBufferIsFull( xMessageBuffer ) == pdTRUE ); + xReturned = xMessageBufferSend( xMessageBuffer, ( void * ) pucData, sizeof( pucData[ 0 ] ), mbDONT_BLOCK ); + configASSERT( xReturned == 0 ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + + /* Adding with a timeout should also fail after the appropriate time. The + * priority is temporarily boosted in this part of the test to keep the + * allowable margin to a minimum. */ + uxOriginalPriority = uxTaskPriorityGet( NULL ); + vTaskPrioritySet( NULL, configMAX_PRIORITIES - 1 ); + xTimeBeforeCall = xTaskGetTickCount(); + xReturned = xMessageBufferSend( xMessageBuffer, ( void * ) pucData, sizeof( pucData[ 0 ] ), xBlockTime ); + xTimeAfterCall = xTaskGetTickCount(); + vTaskPrioritySet( NULL, uxOriginalPriority ); + configASSERT( ( ( TickType_t ) ( xTimeAfterCall - xTimeBeforeCall ) ) >= xBlockTime ); + configASSERT( ( ( TickType_t ) ( xTimeAfterCall - xTimeBeforeCall ) ) < ( xBlockTime + xAllowableMargin ) ); + configASSERT( xReturned == 0 ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + ( void ) xTimeBeforeCall; + ( void ) xTimeAfterCall; + + /* The buffer is now full of data in the form "000000", "111111", etc. Make + * sure the data is read out as expected. */ + for( xItem = 0; xItem < xMax6ByteMessages; xItem++ ) + { + /* Generate the data that is expected to be read out for this loop + * iteration. */ + memset( ( void * ) pucData, ( ( int ) '0' ) + ( int ) xItem, x6ByteLength ); + + /* Try reading the message into a buffer that is too small. The message + * should remain in the buffer. */ + xReturned = xMessageBufferReceive( xMessageBuffer, ( void * ) pucReadData, x6ByteLength - 1, mbDONT_BLOCK ); + configASSERT( xReturned == 0 ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + + /* Should still be at least one 6 byte message still available. */ + xNextLength = xMessageBufferNextLengthBytes( xMessageBuffer ); + configASSERT( xNextLength == x6ByteLength ); + ( void ) xNextLength; /* In case configASSERT() is not defined. */ + + /* Read the next 6 bytes out. The 'FromISR' version is used to give it + * some exercise as a block time is not used. THa requires the code to be + * in a critical section so this test can be run with FreeRTOS ports that + * do not support interrupt nesting (and therefore don't have interrupt + * safe critical sections). */ + taskENTER_CRITICAL(); + { + xReturned = xMessageBufferReceiveFromISR( xMessageBuffer, ( void * ) pucReadData, x6ByteLength, NULL ); + } + taskEXIT_CRITICAL(); + configASSERT( xReturned == x6ByteLength ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + + /* Does the data read out match that expected? */ + configASSERT( memcmp( ( void * ) pucData, ( void * ) pucReadData, x6ByteLength ) == 0 ); + + /* The space in the buffer will have increased by the amount of user + * data read from into the buffer and the amount of space used to store the + * length of the data read into the buffer. */ + xExpectedSpace += ( x6ByteLength + mbBYTES_TO_STORE_MESSAGE_LENGTH ); + xReturned = xMessageBufferSpaceAvailable( xMessageBuffer ); + configASSERT( xReturned == xExpectedSpace ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + } + + /* The buffer should be empty again. */ + configASSERT( xMessageBufferIsEmpty( xMessageBuffer ) == pdTRUE ); + xExpectedSpace = xMessageBufferSpaceAvailable( xMessageBuffer ); + configASSERT( xExpectedSpace == mbMESSAGE_BUFFER_LENGTH_BYTES ); + ( void ) xExpectedSpace; /* In case configASSERT() is not defined. */ + xNextLength = xMessageBufferNextLengthBytes( xMessageBuffer ); + configASSERT( xNextLength == 0 ); + ( void ) xNextLength; /* In case configASSERT() is not defined. */ + + + /* Reading with a timeout should also fail after the appropriate time. The + * priority is temporarily boosted in this part of the test to keep the + * allowable margin to a minimum. */ + vTaskPrioritySet( NULL, configMAX_PRIORITIES - 1 ); + xTimeBeforeCall = xTaskGetTickCount(); + xReturned = xMessageBufferReceive( xMessageBuffer, ( void * ) pucReadData, x6ByteLength, xBlockTime ); + xTimeAfterCall = xTaskGetTickCount(); + vTaskPrioritySet( NULL, uxOriginalPriority ); + configASSERT( ( xTimeAfterCall - xTimeBeforeCall ) >= xBlockTime ); + configASSERT( ( xTimeAfterCall - xTimeBeforeCall ) < ( xBlockTime + xAllowableMargin ) ); + configASSERT( xReturned == 0 ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + ( void ) xTimeBeforeCall; + ( void ) xTimeAfterCall; + + + /* In the next loop 17 bytes are written to then read out on each iteration. + * The expected length variable is always used after 17 bytes have been written + * into the buffer - the length of the message is also written, making a total + * of 21 bytes consumed for each 17 byte message. */ + xExpectedSpace = mbMESSAGE_BUFFER_LENGTH_BYTES - ( x17ByteLength + mbBYTES_TO_STORE_MESSAGE_LENGTH ); + + /* Reading and writing 17 bytes at a time will result in 21 bytes being + * written into the buffer, and as 50 is not divisible by 21, writing multiple + * times will cause the data to wrap in the buffer.*/ + for( xItem = 0; xItem < 100; xItem++ ) + { + /* Generate recognisable data to write to the queue. This is just + * ascii characters that shows which loop iteration the data was written + * in. */ + memset( ( void * ) pucData, ( ( int ) '0' ) + ( int ) xItem, x17ByteLength ); + xReturned = xMessageBufferSend( xMessageBuffer, ( void * ) pucData, x17ByteLength, mbDONT_BLOCK ); + configASSERT( xReturned == x17ByteLength ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + + /* Only 17 byte messages are written. */ + xNextLength = xMessageBufferNextLengthBytes( xMessageBuffer ); + configASSERT( xNextLength == x17ByteLength ); + ( void ) xNextLength; /* In case configASSERT() is not defined. */ + + /* The space in the buffer will have reduced by the amount of user data + * written into the buffer and the amount of space used to store the length + * of the data written into the buffer. */ + xReturned = xMessageBufferSpaceAvailable( xMessageBuffer ); + configASSERT( xReturned == xExpectedSpace ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + + /* Read the 17 bytes out again. */ + xReturned = xMessageBufferReceive( xMessageBuffer, ( void * ) pucReadData, x17ByteLength, mbDONT_BLOCK ); + configASSERT( xReturned == x17ByteLength ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + + /* Does the data read out match that expected? */ + configASSERT( memcmp( ( void * ) pucData, ( void * ) pucReadData, x17ByteLength ) == 0 ); + + /* Don't expect any messages to be available as the data was read out + * again. */ + xNextLength = xMessageBufferNextLengthBytes( xMessageBuffer ); + configASSERT( xNextLength == 0 ); + ( void ) xNextLength; /* In case configASSERT() is not defined. */ + } + + /* The buffer should be empty again. */ + configASSERT( xMessageBufferIsEmpty( xMessageBuffer ) == pdTRUE ); + xExpectedSpace = xMessageBufferSpaceAvailable( xMessageBuffer ); + configASSERT( xExpectedSpace == mbMESSAGE_BUFFER_LENGTH_BYTES ); + + /* Cannot write within sizeof( size_t ) (assumed to be 4 bytes in this test) + * bytes of the full 50 bytes, as that would not leave space for the four bytes + * taken by the data length. */ + xReturned = xMessageBufferSend( xMessageBuffer, ( const void * ) pc55ByteString, mbMESSAGE_BUFFER_LENGTH_BYTES, mbDONT_BLOCK ); + configASSERT( xReturned == 0 ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + #ifndef configMESSAGE_BUFFER_LENGTH_TYPE + { + /* The following will fail if configMESSAGE_BUFFER_LENGTH_TYPE is set + * to a non 32-bit type. */ + xReturned = xMessageBufferSend( xMessageBuffer, ( const void * ) pc55ByteString, mbMESSAGE_BUFFER_LENGTH_BYTES - 1, mbDONT_BLOCK ); + configASSERT( xReturned == 0 ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + xReturned = xMessageBufferSend( xMessageBuffer, ( const void * ) pc55ByteString, mbMESSAGE_BUFFER_LENGTH_BYTES - 2, mbDONT_BLOCK ); + configASSERT( xReturned == 0 ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + xReturned = xMessageBufferSend( xMessageBuffer, ( const void * ) pc55ByteString, mbMESSAGE_BUFFER_LENGTH_BYTES - 3, mbDONT_BLOCK ); + configASSERT( xReturned == 0 ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + } + #endif /* ifndef configMESSAGE_BUFFER_LENGTH_TYPE */ + + /* Don't expect any messages to be available as the above were too large to + * get written. */ + xNextLength = xMessageBufferNextLengthBytes( xMessageBuffer ); + configASSERT( xNextLength == 0 ); + ( void ) xNextLength; /* In case configASSERT() is not defined. */ + + /* Can write mbMESSAGE_BUFFER_LENGTH_BYTES - sizeof( size_t ) bytes though. */ + xReturned = xMessageBufferSend( xMessageBuffer, ( const void * ) pc55ByteString, mbMESSAGE_BUFFER_LENGTH_BYTES - sizeof( size_t ), mbDONT_BLOCK ); + configASSERT( xReturned == mbMESSAGE_BUFFER_LENGTH_BYTES - sizeof( size_t ) ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + xNextLength = xMessageBufferNextLengthBytes( xMessageBuffer ); + configASSERT( xNextLength == ( mbMESSAGE_BUFFER_LENGTH_BYTES - sizeof( size_t ) ) ); + ( void ) xNextLength; /* In case configASSERT() is not defined. */ + xReturned = xMessageBufferReceive( xMessageBuffer, ( void * ) pucFullBuffer, mbMESSAGE_BUFFER_LENGTH_BYTES - sizeof( size_t ), mbDONT_BLOCK ); + configASSERT( xReturned == ( mbMESSAGE_BUFFER_LENGTH_BYTES - sizeof( size_t ) ) ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + configASSERT( memcmp( ( const void * ) pucFullBuffer, pc55ByteString, mbMESSAGE_BUFFER_LENGTH_BYTES - sizeof( size_t ) ) == 0 ); + + /* Clean up. */ + vPortFree( pucFullBuffer ); + xMessageBufferReset( xMessageBuffer ); +} +/*-----------------------------------------------------------*/ + +static void prvNonBlockingSenderTask( void * pvParameters ) +{ + MessageBufferHandle_t xMessageBuffer; + int32_t iDataToSend = 0; + size_t xStringLength; + const int32_t iMaxValue = 1500; + char cTxString[ 12 ]; /* Large enough to hold a 32 number in ASCII. */ + + /* In this case the message buffer has already been created and is passed + * into the task using the task's parameter. */ + + xMessageBuffer = ( MessageBufferHandle_t ) pvParameters; + + /* Create a string from an incrementing number. The length of the + * string will increase and decrease as the value of the number increases + * then overflows. */ + memset( cTxString, 0x00, sizeof( cTxString ) ); + sprintf( cTxString, "%d", ( int ) iDataToSend ); + xStringLength = strlen( cTxString ); + + for( ; ; ) + { + /* Doesn't block so calls can interleave with the non-blocking + * receives performed by prvNonBlockingReceiverTask(). */ + if( xMessageBufferSend( xMessageBuffer, ( void * ) cTxString, strlen( cTxString ), mbDONT_BLOCK ) == xStringLength ) + { + iDataToSend++; + + if( iDataToSend > iMaxValue ) + { + /* The value sent is reset back to 0 to ensure the string being sent + * does not remain at the same length for too long. */ + iDataToSend = 0; + } + + /* Create the next string. */ + memset( cTxString, 0x00, sizeof( cTxString ) ); + sprintf( cTxString, "%d", ( int ) iDataToSend ); + xStringLength = strlen( cTxString ); + } + } +} +/*-----------------------------------------------------------*/ + +static void prvNonBlockingReceiverTask( void * pvParameters ) +{ + MessageBufferHandle_t xMessageBuffer; + BaseType_t xNonBlockingReceiveError = pdFALSE; + int32_t iDataToSend = 0; + size_t xStringLength, xReceiveLength; + const int32_t iMaxValue = 1500; + char cExpectedString[ 12 ]; /* Large enough to hold a 32 number in ASCII. */ + char cRxString[ 12 ]; + + /* In this case the message buffer has already been created and is passed + * into the task using the task's parameter. */ + xMessageBuffer = ( MessageBufferHandle_t ) pvParameters; + + /* Create a string from an incrementing number. The length of the + * string will increase and decrease as the value of the number increases + * then overflows. This should always match the string sent to the buffer by + * the non blocking sender task. */ + memset( cExpectedString, 0x00, sizeof( cExpectedString ) ); + memset( cRxString, 0x00, sizeof( cRxString ) ); + sprintf( cExpectedString, "%d", ( int ) iDataToSend ); + xStringLength = strlen( cExpectedString ); + + for( ; ; ) + { + /* Doesn't block so calls can interleave with the non-blocking + * receives performed by prvNonBlockingReceiverTask(). */ + xReceiveLength = xMessageBufferReceive( xMessageBuffer, ( void * ) cRxString, sizeof( cRxString ), mbDONT_BLOCK ); + + /* Should only ever receive no data is available, or the expected + * length of data is available. */ + if( ( xReceiveLength != 0 ) && ( xReceiveLength != xStringLength ) ) + { + xNonBlockingReceiveError = pdTRUE; + } + + if( xReceiveLength == xStringLength ) + { + /* Ensure the received data was that expected, then generate the + * next expected string. */ + if( strcmp( cRxString, cExpectedString ) != 0 ) + { + xNonBlockingReceiveError = pdTRUE; + } + + iDataToSend++; + + if( iDataToSend > iMaxValue ) + { + /* The value sent is reset back to 0 to ensure the string being sent + * does not remain at the same length for too long. */ + iDataToSend = 0; + } + + memset( cExpectedString, 0x00, sizeof( cExpectedString ) ); + memset( cRxString, 0x00, sizeof( cRxString ) ); + sprintf( cExpectedString, "%d", ( int ) iDataToSend ); + xStringLength = strlen( cExpectedString ); + + if( xNonBlockingReceiveError == pdFALSE ) + { + /* No errors detected so increment the counter that lets the + * check task know this test is still functioning correctly. */ + ulNonBlockingRxCounter++; + } + } + } +} +/*-----------------------------------------------------------*/ + +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + + static void prvSenderTask( void * pvParameters ) + { + MessageBufferHandle_t xMessageBuffer, xTempMessageBuffer; + int32_t iDataToSend = 0; + const int32_t iSendsBetweenIncrements = 100; + char cTxString[ 12 ]; /* Large enough to hold a 32 number in ASCII. */ + const TickType_t xTicksToWait = mbRX_TX_BLOCK_TIME, xShortDelay = pdMS_TO_TICKS( 50 ); + StaticMessageBuffer_t xStaticMessageBuffer; + size_t xBytesSent; + + + /* The task's priority is used as an index into the loop counters used to + * indicate this task is still running. */ + UBaseType_t uxIndex = uxTaskPriorityGet( NULL ); + + /* Make sure a change in priority does not inadvertently result in an + * invalid array index. */ + configASSERT( uxIndex < mbNUMBER_OF_ECHO_CLIENTS ); + + /* Avoid compiler warnings about unused parameters. */ + ( void ) pvParameters; + + xMessageBuffer = xMessageBufferCreateStatic( sizeof( ucBufferStorage ) / mbNUMBER_OF_SENDER_TASKS, /* The number of bytes in each buffer in the array. */ + &( ucBufferStorage[ uxIndex ][ 0 ] ), /* The address of the buffer to use within the array. */ + &( xStaticMessageBuffers[ uxIndex ] ) ); /* The static message buffer structure to use within the array. */ + + /* Now the message buffer has been created the receiver task can be created. + * If this sender task has the higher priority then the receiver task is + * created at the lower priority - if this sender task has the lower priority + * then the receiver task is created at the higher priority. */ + if( uxTaskPriorityGet( NULL ) == mbLOWER_PRIORITY ) + { + /* Here prvSingleTaskTests() performs various tests on a message buffer + * that was created statically. */ + prvSingleTaskTests( xMessageBuffer ); + xTaskCreate( prvReceiverTask, "MsgReceiver", xBlockingStackSize, ( void * ) xMessageBuffer, mbHIGHER_PRIORITY, NULL ); + } + else + { + xTaskCreate( prvReceiverTask, "MsgReceiver", xBlockingStackSize, ( void * ) xMessageBuffer, mbLOWER_PRIORITY, NULL ); + } + + for( ; ; ) + { + /* Create a string from an incrementing number. The length of the + * string will increase and decrease as the value of the number increases + * then overflows. */ + memset( cTxString, 0x00, sizeof( cTxString ) ); + sprintf( cTxString, "%d", ( int ) iDataToSend ); + + do + { + xBytesSent = xMessageBufferSend( xMessageBuffer, ( void * ) cTxString, strlen( cTxString ), xTicksToWait ); + } while( xBytesSent == 0 ); /* Buffer may become full when receiver is running at the idle priority. */ + + iDataToSend++; + + if( ( iDataToSend % iSendsBetweenIncrements ) == 0 ) + { + /* Increment a loop counter so a check task can tell this task is + * still running as expected. */ + ulSenderLoopCounters[ uxIndex ]++; + + if( uxTaskPriorityGet( NULL ) == mbHIGHER_PRIORITY ) + { + /* Allow other tasks to run. */ + vTaskDelay( xShortDelay ); + } + + /* This message buffer is just created and deleted to ensure no + * issues when attempting to delete a message buffer that was + * created using statically allocated memory. To save stack space + * the buffer is set to point to the cTxString array - this is + * ok because nothing is actually written to the memory. */ + xTempMessageBuffer = xMessageBufferCreateStatic( sizeof( cTxString ), ( uint8_t * ) cTxString, &xStaticMessageBuffer ); + vMessageBufferDelete( xTempMessageBuffer ); + } + } + } + +#endif /* configSUPPORT_STATIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + + static void prvReceiverTask( void * pvParameters ) + { + MessageBufferHandle_t * const pxMessageBuffer = ( MessageBufferHandle_t * ) pvParameters; + char cExpectedString[ 12 ]; /* Large enough to hold a 32-bit number in ASCII. */ + char cReceivedString[ 12 ]; /* Large enough to hold a 32-bit number in ASCII. */ + int32_t iExpectedData = 0; + const TickType_t xTicksToWait = pdMS_TO_TICKS( 5UL ); + size_t xReceivedBytes; + + for( ; ; ) + { + /* Generate the next expected string in the cExpectedString buffer. */ + memset( cExpectedString, 0x00, sizeof( cExpectedString ) ); + sprintf( cExpectedString, "%d", ( int ) iExpectedData ); + + /* Receive the next string from the message buffer. */ + memset( cReceivedString, 0x00, sizeof( cReceivedString ) ); + + do + { + xReceivedBytes = xMessageBufferReceive( pxMessageBuffer, ( void * ) cReceivedString, sizeof( cExpectedString ), xTicksToWait ); + } while( xReceivedBytes == 0 ); + + /* Ensure the received string matches the expected string. */ + configASSERT( strcmp( cExpectedString, cReceivedString ) == 0 ); + + iExpectedData++; + } + } + +#endif /* configSUPPORT_STATIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +static void prvEchoClient( void * pvParameters ) +{ + size_t xSendLength = 0, ux; + char * pcStringToSend, * pcStringReceived, cNextChar = mbASCII_SPACE; + const TickType_t xTicksToWait = pdMS_TO_TICKS( 50 ); + +/* The task's priority is used as an index into the loop counters used to + * indicate this task is still running. */ + UBaseType_t uxIndex = uxTaskPriorityGet( NULL ); + +/* Pointers to the client and server message buffers are passed into this task + * using the task's parameter. */ + EchoMessageBuffers_t * pxMessageBuffers = ( EchoMessageBuffers_t * ) pvParameters; + + /* Prevent compiler warnings. */ + ( void ) pvParameters; + + /* Create the buffer into which strings to send to the server will be + * created, and the buffer into which strings echoed back from the server will + * be copied. */ + pcStringToSend = ( char * ) pvPortMalloc( mbMESSAGE_BUFFER_LENGTH_BYTES ); + pcStringReceived = ( char * ) pvPortMalloc( mbMESSAGE_BUFFER_LENGTH_BYTES ); + + configASSERT( pcStringToSend ); + configASSERT( pcStringReceived ); + + for( ; ; ) + { + /* Generate the length of the next string to send. */ + xSendLength++; + + /* The message buffer is being used to hold variable length data, so + * each data item requires sizeof( size_t ) bytes to hold the data's + * length, hence the sizeof() in the if() condition below. */ + if( xSendLength > ( mbMESSAGE_BUFFER_LENGTH_BYTES - sizeof( size_t ) ) ) + { + /* Back to a string length of 1. */ + xSendLength = sizeof( char ); + + /* Maintain a count of the number of times this code executes so a + * check task can determine if this task is still functioning as + * expected or not. As there are two client tasks, and the priorities + * used are 0 and 1, the task's priority is used as an index into the + * loop count array. */ + ulEchoLoopCounters[ uxIndex ]++; + } + + memset( pcStringToSend, 0x00, mbMESSAGE_BUFFER_LENGTH_BYTES ); + + for( ux = 0; ux < xSendLength; ux++ ) + { + pcStringToSend[ ux ] = cNextChar; + + cNextChar++; + + if( cNextChar > mbASCII_TILDA ) + { + cNextChar = mbASCII_SPACE; + } + } + + /* Send the generated string to the buffer. */ + do + { + ux = xMessageBufferSend( pxMessageBuffers->xEchoClientBuffer, ( void * ) pcStringToSend, xSendLength, xTicksToWait ); + + if( ux == 0 ) + { + mtCOVERAGE_TEST_MARKER(); + } + } while( ux == 0 ); + + /* Wait for the string to be echoed back. */ + memset( pcStringReceived, 0x00, mbMESSAGE_BUFFER_LENGTH_BYTES ); + xMessageBufferReceive( pxMessageBuffers->xEchoServerBuffer, ( void * ) pcStringReceived, xSendLength, portMAX_DELAY ); + + configASSERT( strcmp( pcStringToSend, pcStringReceived ) == 0 ); + } +} +/*-----------------------------------------------------------*/ + +static void prvEchoServer( void * pvParameters ) +{ + MessageBufferHandle_t xTempMessageBuffer; + size_t xReceivedLength; + char * pcReceivedString; + EchoMessageBuffers_t xMessageBuffers; + TickType_t xTimeOnEntering; + const TickType_t xTicksToBlock = pdMS_TO_TICKS( 250UL ); + + /* Prevent compiler warnings about unused parameters. */ + ( void ) pvParameters; + + /* Create the message buffer used to send data from the client to the server, + * and the message buffer used to echo the data from the server back to the + * client. */ + xMessageBuffers.xEchoClientBuffer = xMessageBufferCreate( mbMESSAGE_BUFFER_LENGTH_BYTES ); + xMessageBuffers.xEchoServerBuffer = xMessageBufferCreate( mbMESSAGE_BUFFER_LENGTH_BYTES ); + configASSERT( xMessageBuffers.xEchoClientBuffer ); + configASSERT( xMessageBuffers.xEchoServerBuffer ); + + /* Create the buffer into which received strings will be copied. */ + pcReceivedString = ( char * ) pvPortMalloc( mbMESSAGE_BUFFER_LENGTH_BYTES ); + configASSERT( pcReceivedString ); + + /* Don't expect to receive anything yet! */ + xTimeOnEntering = xTaskGetTickCount(); + xReceivedLength = xMessageBufferReceive( xMessageBuffers.xEchoClientBuffer, ( void * ) pcReceivedString, mbMESSAGE_BUFFER_LENGTH_BYTES, xTicksToBlock ); + configASSERT( ( ( TickType_t ) ( xTaskGetTickCount() - xTimeOnEntering ) ) >= xTicksToBlock ); + configASSERT( xReceivedLength == 0 ); + ( void ) xTimeOnEntering; /* In case configASSERT() is not defined. */ + + /* Now the message buffers have been created the echo client task can be + * created. If this server task has the higher priority then the client task + * is created at the lower priority - if this server task has the lower + * priority then the client task is created at the higher priority. */ + if( uxTaskPriorityGet( NULL ) == mbLOWER_PRIORITY ) + { + xTaskCreate( prvEchoClient, "EchoClient", configMINIMAL_STACK_SIZE, ( void * ) &xMessageBuffers, mbHIGHER_PRIORITY, NULL ); + } + else + { + /* Here prvSingleTaskTests() performs various tests on a message buffer + * that was created dynamically. */ + prvSingleTaskTests( xMessageBuffers.xEchoClientBuffer ); + xTaskCreate( prvEchoClient, "EchoClient", configMINIMAL_STACK_SIZE, ( void * ) &xMessageBuffers, mbLOWER_PRIORITY, NULL ); + } + + for( ; ; ) + { + memset( pcReceivedString, 0x00, mbMESSAGE_BUFFER_LENGTH_BYTES ); + + /* Has any data been sent by the client? */ + xReceivedLength = xMessageBufferReceive( xMessageBuffers.xEchoClientBuffer, ( void * ) pcReceivedString, mbMESSAGE_BUFFER_LENGTH_BYTES, portMAX_DELAY ); + + /* Should always receive data as max delay was used. */ + configASSERT( xReceivedLength > 0 ); + + /* Echo the received data back to the client. */ + xMessageBufferSend( xMessageBuffers.xEchoServerBuffer, ( void * ) pcReceivedString, xReceivedLength, portMAX_DELAY ); + + /* This message buffer is just created and deleted to ensure no memory + * leaks. */ + xTempMessageBuffer = xMessageBufferCreate( mbMESSAGE_BUFFER_LENGTH_BYTES ); + vMessageBufferDelete( xTempMessageBuffer ); + } +} +/*-----------------------------------------------------------*/ + +/* Tests within configRUN_ADDITIONAL_TESTS blocks only execute on larger + * platforms or have been added to pre-existing files that are already in use + * by other test projects without ensuring they don't cause those pre-existing + * projects to run out of program or data memory. */ +#if ( configRUN_ADDITIONAL_TESTS == 1 ) + + static void prvSpaceAvailableCoherenceActor( void * pvParameters ) + { + static char * cTxString = "12345"; + char cRxString[ mbCOHERENCE_TEST_BYTES_WRITTEN + 1 ]; /* +1 for NULL terminator. */ + + ( void ) pvParameters; + + for( ; ; ) + { + /* Add bytes to the buffer so the other task should see + * mbEXPECTED_FREE_BYTES_AFTER_WRITING_STRING bytes free. */ + xMessageBufferSend( xCoherenceTestMessageBuffer, ( void * ) cTxString, strlen( cTxString ), 0 ); + configASSERT( xMessageBufferSpacesAvailable( xCoherenceTestMessageBuffer ) == mbEXPECTED_FREE_BYTES_AFTER_WRITING_STRING ); + + /* Read out message again so the other task should read the full + * mbCOHERENCE_TEST_BUFFER_SIZE bytes free again. */ + memset( ( void * ) cRxString, 0x00, sizeof( cRxString ) ); + xMessageBufferReceive( xCoherenceTestMessageBuffer, ( void * ) cRxString, mbCOHERENCE_TEST_BYTES_WRITTEN, 0 ); + configASSERT( strcmp( cTxString, cRxString ) == 0 ); + } + } + /*-----------------------------------------------------------*/ + + static void prvSpaceAvailableCoherenceTester( void * pvParameters ) + { + size_t xSpaceAvailable; + BaseType_t xErrorFound = pdFALSE; + + ( void ) pvParameters; + + for( ; ; ) + { + /* This message buffer is only ever empty or contains 5 bytes. So all + * queries of its free space should result in one of the two values tested + * below. */ + xSpaceAvailable = xMessageBufferSpacesAvailable( xCoherenceTestMessageBuffer ); + + if( ( xSpaceAvailable == mbCOHERENCE_TEST_BUFFER_SIZE ) || + ( xSpaceAvailable == mbEXPECTED_FREE_BYTES_AFTER_WRITING_STRING ) ) + { + /* Only continue to increment the variable that shows this task + * is still executing if no errors have been found. */ + if( xErrorFound == pdFALSE ) + { + ulSizeCoherencyTestCycles++; + } + } + else + { + xErrorFound = pdTRUE; + } + + configASSERT( xErrorFound == pdFALSE ); + } + } + +#endif /* configRUN_ADDITIONAL_TESTS == 1 */ +/*-----------------------------------------------------------*/ + +BaseType_t xAreMessageBufferTasksStillRunning( void ) +{ + static uint32_t ulLastEchoLoopCounters[ mbNUMBER_OF_ECHO_CLIENTS ] = { 0 }; + static uint32_t ulLastNonBlockingRxCounter = 0; + BaseType_t xReturn = pdPASS, x; + + for( x = 0; x < mbNUMBER_OF_ECHO_CLIENTS; x++ ) + { + if( ulLastEchoLoopCounters[ x ] == ulEchoLoopCounters[ x ] ) + { + xReturn = pdFAIL; + } + else + { + ulLastEchoLoopCounters[ x ] = ulEchoLoopCounters[ x ]; + } + } + + if( ulNonBlockingRxCounter == ulLastNonBlockingRxCounter ) + { + xReturn = pdFAIL; + } + else + { + ulLastNonBlockingRxCounter = ulNonBlockingRxCounter; + } + + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + static uint32_t ulLastSenderLoopCounters[ mbNUMBER_OF_ECHO_CLIENTS ] = { 0 }; + + for( x = 0; x < mbNUMBER_OF_SENDER_TASKS; x++ ) + { + if( ulLastSenderLoopCounters[ x ] == ulSenderLoopCounters[ x ] ) + { + xReturn = pdFAIL; + } + else + { + ulLastSenderLoopCounters[ x ] = ulSenderLoopCounters[ x ]; + } + } + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ + + #if ( configRUN_ADDITIONAL_TESTS == 1 ) + { + static uint32_t ullastSizeCoherencyTestCycles = 0UL; + + if( ullastSizeCoherencyTestCycles == ulSizeCoherencyTestCycles ) + { + xReturn = pdFAIL; + } + else + { + ullastSizeCoherencyTestCycles = ulSizeCoherencyTestCycles; + } + } + #endif /* if ( configRUN_ADDITIONAL_TESTS == 1 ) */ + + return xReturn; +} +/*-----------------------------------------------------------*/ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/StreamBufferDemo.c b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/StreamBufferDemo.c new file mode 100644 index 0000000..3ff2371 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/StreamBufferDemo.c @@ -0,0 +1,1247 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* Standard includes. */ +#include "stdio.h" +#include "string.h" + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "stream_buffer.h" + +/* Demo app includes. */ +#include "StreamBufferDemo.h" + +/* The number of bytes of storage in the stream buffers used in this test. */ +#define sbSTREAM_BUFFER_LENGTH_BYTES ( ( size_t ) 30 ) + +/* Stream buffer length one. */ +#define sbSTREAM_BUFFER_LENGTH_ONE ( ( size_t ) 1 ) + +/* Start and end ASCII characters used in data sent to the buffers. */ +#define sbASCII_SPACE 32 +#define sbASCII_TILDA 126 + +/* Defines the number of tasks to create in this test and demo. */ +#define sbNUMBER_OF_ECHO_CLIENTS ( 2 ) +#define sbNUMBER_OF_SENDER_TASKS ( 2 ) + +/* Priority of the test tasks. The send and receive go from low to high + * priority tasks, and from high to low priority tasks. */ +#define sbLOWER_PRIORITY ( tskIDLE_PRIORITY ) +#define sbHIGHER_PRIORITY ( tskIDLE_PRIORITY + 1 ) + +/* Block times used when sending and receiving from the stream buffers. */ +#define sbRX_TX_BLOCK_TIME pdMS_TO_TICKS( 125UL ) + +/* A block time of 0 means "don't block". */ +#define sbDONT_BLOCK ( 0 ) + +/* The trigger level sets the number of bytes that must be present in the + * stream buffer before a task that is blocked on the stream buffer is moved out of + * the Blocked state so it can read the bytes. */ +#define sbTRIGGER_LEVEL_1 ( 1 ) + +/* The size of the stack allocated to the tasks that run as part of this demo/ + * test. The stack size is over generous in most cases. */ +#ifndef configSTREAM_BUFFER_SENDER_TASK_STACK_SIZE + #define sbSTACK_SIZE ( configMINIMAL_STACK_SIZE + ( configMINIMAL_STACK_SIZE >> 1 ) ) +#else + #define sbSTACK_SIZE configSTREAM_BUFFER_SENDER_TASK_STACK_SIZE +#endif + +#ifndef configSTREAM_BUFFER_SMALLER_TASK_STACK_SIZE + #define sbSMALLER_STACK_SIZE sbSTACK_SIZE +#else + #define sbSMALLER_STACK_SIZE configSTREAM_BUFFER_SMALLER_TASK_STACK_SIZE +#endif + +/*-----------------------------------------------------------*/ + +/* + * Performs various tests that do not require multiple tasks to interact. + */ +static void prvSingleTaskTests( StreamBufferHandle_t xStreamBuffer ); + +/* + * Tests sending and receiving various lengths of data via a stream buffer. + * The echo client sends the data to the echo server, which then sends the + * data back to the echo client, which checks it receives exactly what it + * sent. + */ +static void prvEchoClient( void * pvParameters ); +static void prvEchoServer( void * pvParameters ); + +/* + * Tasks that send and receive to a stream buffer at a low priority and without + * blocking, so the send and receive functions interleave in time as the tasks + * are switched in and out. + */ +static void prvNonBlockingReceiverTask( void * pvParameters ); +static void prvNonBlockingSenderTask( void * pvParameters ); + +/* Performs an assert() like check in a way that won't get removed when + * performing a code coverage analysis. */ +static void prvCheckExpectedState( BaseType_t xState ); + +/* + * A task that creates a stream buffer with a specific trigger level, then + * receives a string from an interrupt (the RTOS tick hook) byte by byte to + * check it is only unblocked when the specified trigger level is reached. + */ +static void prvInterruptTriggerLevelTest( void * pvParameters ); + +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + +/* This file tests both statically and dynamically allocated stream buffers. + * Allocate the structures and buffers to be used by the statically allocated + * objects, which get used in the echo tests. */ + static void prvReceiverTask( void * pvParameters ); + static void prvSenderTask( void * pvParameters ); + + static StaticStreamBuffer_t xStaticStreamBuffers[ sbNUMBER_OF_ECHO_CLIENTS ]; + static uint32_t ulSenderLoopCounters[ sbNUMBER_OF_SENDER_TASKS ] = { 0 }; +#endif /* configSUPPORT_STATIC_ALLOCATION */ + +/* The +1 is to make the test logic easier as the function that calculates the + * free space will return one less than the actual free space - adding a 1 to the + * actual length makes it appear to the tests as if the free space is returned as + * it might logically be expected. Returning 1 less than the actual free space is + * fine as it can never result in an overrun. */ +static uint8_t ucBufferStorage[ sbNUMBER_OF_SENDER_TASKS ][ sbSTREAM_BUFFER_LENGTH_BYTES + 1 ]; + +/*-----------------------------------------------------------*/ + +/* The buffers used by the echo client and server tasks. */ +typedef struct ECHO_STREAM_BUFFERS +{ + /* Handles to the data structures that describe the stream buffers. */ + StreamBufferHandle_t xEchoClientBuffer; + StreamBufferHandle_t xEchoServerBuffer; +} EchoStreamBuffers_t; +static volatile uint32_t ulEchoLoopCounters[ sbNUMBER_OF_ECHO_CLIENTS ] = { 0 }; + +/* The non-blocking tasks monitor their operation, and if no errors have been + * found, increment ulNonBlockingRxCounter. xAreStreamBufferTasksStillRunning() + * then checks ulNonBlockingRxCounter and only returns pdPASS if + * ulNonBlockingRxCounter is still incrementing. */ +static volatile uint32_t ulNonBlockingRxCounter = 0; + +/* The task that receives characters from the tick interrupt in order to test + * different trigger levels monitors its own behaviour. If it has not detected any + * error then it increments ulInterruptTriggerCounter to indicate to the check task + * that it is still operating correctly. */ +static volatile uint32_t ulInterruptTriggerCounter = 0UL; + +/* The stream buffer used from the tick interrupt. This sends one byte at a time + * to a test task to test the trigger level operation. The variable is set to NULL + * in between test runs. */ +static volatile StreamBufferHandle_t xInterruptStreamBuffer = NULL; + +/* The data sent from the tick interrupt to the task that tests the trigger + * level functionality. */ +static const char * pcDataSentFromInterrupt = "0123456789"; + +/* Data that is longer than the buffer that is sent to the buffers as a stream + * of bytes. Parts of which are written to the stream buffer to test writing + * different lengths at different offsets, to many bytes, part streams, streams + * that wrap, etc.. Two messages are defined to ensure left over data is not + * accidentally read out of the buffer. */ +static const char * pc55ByteString = "One two three four five six seven eight nine ten eleven"; +static const char * pc54ByteString = "01234567891abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQ"; + +/* Used to log the status of the tests contained within this file for reporting + * to a monitoring task ('check' task). */ +static BaseType_t xErrorStatus = pdPASS; + +/*-----------------------------------------------------------*/ + +void vStartStreamBufferTasks( void ) +{ + StreamBufferHandle_t xStreamBuffer; + + /* The echo servers sets up the stream buffers before creating the echo + * client tasks. One set of tasks has the server as the higher priority, and + * the other has the client as the higher priority. */ + xTaskCreate( prvEchoServer, "1StrEchoServer", sbSMALLER_STACK_SIZE, NULL, sbHIGHER_PRIORITY, NULL ); + xTaskCreate( prvEchoServer, "2StrEchoServer", sbSMALLER_STACK_SIZE, NULL, sbLOWER_PRIORITY, NULL ); + + /* The non blocking tasks run continuously and will interleave with each + * other, so must be created at the lowest priority. The stream buffer they + * use is created and passed in using the task's parameter. */ + xStreamBuffer = xStreamBufferCreate( sbSTREAM_BUFFER_LENGTH_BYTES, sbTRIGGER_LEVEL_1 ); + xTaskCreate( prvNonBlockingReceiverTask, "StrNonBlkRx", configMINIMAL_STACK_SIZE, ( void * ) xStreamBuffer, tskIDLE_PRIORITY, NULL ); + xTaskCreate( prvNonBlockingSenderTask, "StrNonBlkTx", configMINIMAL_STACK_SIZE, ( void * ) xStreamBuffer, tskIDLE_PRIORITY, NULL ); + + /* The task that receives bytes from an interrupt to test that it unblocks + * at a specific trigger level must run at a high priority to minimise the risk + * of it receiving more characters before it can execute again after being + * unblocked. */ + xTaskCreate( prvInterruptTriggerLevelTest, "StrTrig", configMINIMAL_STACK_SIZE, NULL, configMAX_PRIORITIES - 1, NULL ); + + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + /* The sender tasks set up the stream buffers before creating the + * receiver tasks. Priorities must be 0 and 1 as the priority is used to + * index into the xStaticStreamBuffers and ucBufferStorage arrays. */ + xTaskCreate( prvSenderTask, "Str1Sender", sbSMALLER_STACK_SIZE, NULL, sbHIGHER_PRIORITY, NULL ); + xTaskCreate( prvSenderTask, "Str2Sender", sbSMALLER_STACK_SIZE, NULL, sbLOWER_PRIORITY, NULL ); + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ +} +/*-----------------------------------------------------------*/ + +static void prvCheckExpectedState( BaseType_t xState ) +{ + configASSERT( xState ); + + if( xState == pdFAIL ) + { + xErrorStatus = pdFAIL; + } +} +/*-----------------------------------------------------------*/ + +static void prvSingleTaskTests( StreamBufferHandle_t xStreamBuffer ) +{ + size_t xReturned, xItem, xExpected, xExpectedSpaces, xExpectedBytes; + const size_t xMax6ByteMessages = sbSTREAM_BUFFER_LENGTH_BYTES / 6; + const size_t xTrueSize = ( sizeof( ucBufferStorage ) / sbNUMBER_OF_SENDER_TASKS ); + const size_t x6ByteLength = 6, x17ByteLength = 17, xFullBufferSize = sbSTREAM_BUFFER_LENGTH_BYTES * ( size_t ) 2; + uint8_t * pucFullBuffer, * pucData, * pucReadData; + TickType_t xTimeBeforeCall, xTimeAfterCall; + const TickType_t xBlockTime = pdMS_TO_TICKS( 15 ), xAllowableMargin = pdMS_TO_TICKS( 3 ), xMinimalBlockTime = 2; + UBaseType_t uxOriginalPriority; + + /* Remove warning in case configASSERT() is not defined. */ + ( void ) xAllowableMargin; + + /* To minimise stack and heap usage a full size buffer is allocated from the + * heap, then buffers which hold smaller amounts of data are overlayed with the + * larger buffer - just make sure not to use both at once! */ + pucFullBuffer = pvPortMalloc( xFullBufferSize ); + configASSERT( pucFullBuffer ); + + pucData = pucFullBuffer; + pucReadData = pucData + x17ByteLength; + + /* Nothing has been added or removed yet, so expect the free space to be + * exactly as created. Head and tail are both at 0. */ + xExpectedSpaces = sbSTREAM_BUFFER_LENGTH_BYTES; + xExpectedBytes = 0; + xExpected = xStreamBufferSpacesAvailable( xStreamBuffer ); + prvCheckExpectedState( xExpected == xExpectedSpaces ); + xExpected = xStreamBufferBytesAvailable( xStreamBuffer ); + prvCheckExpectedState( xExpected == xExpectedBytes ); + prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdTRUE ); + prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdFALSE ); + + /* Add a single item - number of bytes available should go up by one and spaces + * available down by one. Head is in front of tail. */ + xExpectedSpaces--; + xExpectedBytes++; + xReturned = xStreamBufferSend( xStreamBuffer, ( void * ) pucData, sizeof( *pucData ), ( TickType_t ) 0 ); + prvCheckExpectedState( xReturned == sizeof( *pucData ) ); + xExpected = xStreamBufferSpacesAvailable( xStreamBuffer ); + prvCheckExpectedState( xExpected == xExpectedSpaces ); + xExpected = xStreamBufferBytesAvailable( xStreamBuffer ); + prvCheckExpectedState( xExpected == xExpectedBytes ); + prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdFALSE ); + prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdFALSE ); + + /* Now fill the buffer by adding another 29 bytes. Head is 30 tail is at 0. */ + xExpectedSpaces -= 29; + xExpectedBytes += 29; + xReturned = xStreamBufferSend( xStreamBuffer, ( void * ) pucData, ( sbSTREAM_BUFFER_LENGTH_BYTES - 1 ), ( TickType_t ) 0 ); + prvCheckExpectedState( xReturned == ( sbSTREAM_BUFFER_LENGTH_BYTES - 1 ) ); + xExpected = xStreamBufferSpacesAvailable( xStreamBuffer ); + prvCheckExpectedState( xExpected == xExpectedSpaces ); + xExpected = xStreamBufferBytesAvailable( xStreamBuffer ); + prvCheckExpectedState( xExpected == xExpectedBytes ); + prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdFALSE ); + prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdTRUE ); + + /* Should not be able to add another byte now. */ + xReturned = xStreamBufferSend( xStreamBuffer, ( void * ) pucData, sizeof( *pucData ), ( TickType_t ) 0 ); + prvCheckExpectedState( xReturned == ( size_t ) 0 ); + + /* Remove a byte so the tail pointer moves off 0. Head pointer remains at the + * end of the buffer. */ + xExpectedSpaces += 1; + xExpectedBytes -= 1; + xReturned = xStreamBufferReceive( xStreamBuffer, ( void * ) pucData, sizeof( *pucData ), ( TickType_t ) 0 ); + prvCheckExpectedState( xReturned == sizeof( *pucData ) ); + xExpected = xStreamBufferSpacesAvailable( xStreamBuffer ); + prvCheckExpectedState( xExpected == xExpectedSpaces ); + xExpected = xStreamBufferBytesAvailable( xStreamBuffer ); + prvCheckExpectedState( xExpected == xExpectedBytes ); + prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdFALSE ); + prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdFALSE ); + + /* Should be able to add another byte to fill the buffer again now. */ + xExpectedSpaces -= 1; + xExpectedBytes += 1; + xReturned = xStreamBufferSend( xStreamBuffer, ( void * ) pucData, sizeof( *pucData ), ( TickType_t ) 0 ); + prvCheckExpectedState( xReturned == sizeof( *pucData ) ); + xExpected = xStreamBufferSpacesAvailable( xStreamBuffer ); + prvCheckExpectedState( xExpected == xExpectedSpaces ); + xExpected = xStreamBufferBytesAvailable( xStreamBuffer ); + prvCheckExpectedState( xExpected == xExpectedBytes ); + prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdFALSE ); + prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdTRUE ); + + /* Now the head pointer is behind the tail pointer. Read another 29 bytes so + * the tail pointer moves to the end of the buffer. */ + xExpectedSpaces += 29; + xExpectedBytes -= 29; + xReturned = xStreamBufferReceive( xStreamBuffer, ( void * ) pucData, ( size_t ) 29, ( TickType_t ) 0 ); + prvCheckExpectedState( xReturned == ( size_t ) 29 ); + xExpected = xStreamBufferSpacesAvailable( xStreamBuffer ); + prvCheckExpectedState( xExpected == xExpectedSpaces ); + xExpected = xStreamBufferBytesAvailable( xStreamBuffer ); + prvCheckExpectedState( xExpected == xExpectedBytes ); + prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdFALSE ); + prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdFALSE ); + + /* Read out one more byte to wrap the tail back around to the start, to get back + * to where we started. */ + xExpectedSpaces += 1; + xExpectedBytes -= 1; + xReturned = xStreamBufferReceive( xStreamBuffer, ( void * ) pucData, sizeof( *pucData ), ( TickType_t ) 0 ); + prvCheckExpectedState( xReturned == sizeof( *pucData ) ); + xExpected = xStreamBufferSpacesAvailable( xStreamBuffer ); + prvCheckExpectedState( xExpected == xExpectedSpaces ); + xExpected = xStreamBufferBytesAvailable( xStreamBuffer ); + prvCheckExpectedState( xExpected == xExpectedBytes ); + prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdTRUE ); + prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdFALSE ); + + /* Try filling the message buffer in one write, blocking indefinitely. Expect to + * have written one byte less. */ + xReturned = xStreamBufferSend( xStreamBuffer, ( void * ) pucData, xTrueSize, portMAX_DELAY ); + xExpectedSpaces = ( size_t ) 0; + prvCheckExpectedState( xReturned == ( xTrueSize - ( size_t ) 1 ) ); + xExpected = xStreamBufferSpacesAvailable( xStreamBuffer ); + prvCheckExpectedState( xExpected == xExpectedSpaces ); + prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdFALSE ); + prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdTRUE ); + + /* Empty the buffer again ready for the rest of the tests. Again block + * indefinitely to ensure reading more than there can possible be won't lock this + * task up, so expect to actually receive one byte less than requested. */ + xReturned = xStreamBufferReceive( xStreamBuffer, ( void * ) pucData, xTrueSize, portMAX_DELAY ); + prvCheckExpectedState( xReturned == ( xTrueSize - ( size_t ) 1 ) ); + xExpected = xStreamBufferSpacesAvailable( xStreamBuffer ); + prvCheckExpectedState( xExpected == sbSTREAM_BUFFER_LENGTH_BYTES ); + xExpected = xStreamBufferBytesAvailable( xStreamBuffer ); + prvCheckExpectedState( xExpected == ( size_t ) 0 ); + prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdTRUE ); + prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdFALSE ); + + + /* The buffer is 30 bytes long. 6 5 byte messages should fit before the + * buffer is completely full. */ + xExpected = xStreamBufferSpacesAvailable( xStreamBuffer ); + + for( xItem = 0; xItem < xMax6ByteMessages; xItem++ ) + { + prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdFALSE ); + + /* Generate recognisable data to write to the buffer. This is just + * ascii characters that shows which loop iteration the data was written + * in. The 'FromISR' version is used to give it some exercise as a block + * time is not used, so the call must be inside a critical section so it + * runs with ports that don't support interrupt nesting (and therefore + * don't have interrupt safe critical sections). */ + memset( ( void * ) pucData, ( ( int ) '0' ) + ( int ) xItem, x6ByteLength ); + taskENTER_CRITICAL(); + { + xReturned = xStreamBufferSendFromISR( xStreamBuffer, ( void * ) pucData, x6ByteLength, NULL ); + } + taskEXIT_CRITICAL(); + prvCheckExpectedState( xReturned == x6ByteLength ); + + /* The space in the buffer will have reduced by the amount of user data + * written into the buffer. */ + xExpected -= x6ByteLength; + xReturned = xStreamBufferSpacesAvailable( xStreamBuffer ); + prvCheckExpectedState( xReturned == xExpected ); + xReturned = xStreamBufferBytesAvailable( xStreamBuffer ); + /* +1 as it is zero indexed. */ + prvCheckExpectedState( xReturned == ( ( xItem + 1 ) * x6ByteLength ) ); + } + + /* Now the buffer should be full, and attempting to add anything should fail. */ + prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdTRUE ); + xReturned = xStreamBufferSend( xStreamBuffer, ( void * ) pucData, sizeof( pucData[ 0 ] ), sbDONT_BLOCK ); + prvCheckExpectedState( xReturned == 0 ); + + /* Adding with a timeout should also fail after the appropriate time. The + * priority is temporarily boosted in this part of the test to keep the + * allowable margin to a minimum. */ + uxOriginalPriority = uxTaskPriorityGet( NULL ); + vTaskPrioritySet( NULL, configMAX_PRIORITIES - 1 ); + xTimeBeforeCall = xTaskGetTickCount(); + xReturned = xStreamBufferSend( xStreamBuffer, ( void * ) pucData, sizeof( pucData[ 0 ] ), xBlockTime ); + xTimeAfterCall = xTaskGetTickCount(); + vTaskPrioritySet( NULL, uxOriginalPriority ); + prvCheckExpectedState( ( ( TickType_t ) ( xTimeAfterCall - xTimeBeforeCall ) ) >= xBlockTime ); + prvCheckExpectedState( ( ( TickType_t ) ( xTimeAfterCall - xTimeBeforeCall ) ) < ( xBlockTime + xAllowableMargin ) ); + prvCheckExpectedState( xReturned == 0 ); + + /* The buffer is now full of data in the form "000000", "111111", etc. Make + * sure the data is read out as expected. */ + for( xItem = 0; xItem < xMax6ByteMessages; xItem++ ) + { + /* Generate the data that is expected to be read out for this loop + * iteration. */ + memset( ( void * ) pucData, ( ( int ) '0' ) + ( int ) xItem, x6ByteLength ); + + /* Read the next 6 bytes out. The 'FromISR' version is used to give it + * some exercise as a block time is not used, so a it must be called from + * a critical section so this will work on ports that don't support + * interrupt nesting (so don't have interrupt safe critical sections). */ + taskENTER_CRITICAL(); + { + xReturned = xStreamBufferReceiveFromISR( xStreamBuffer, ( void * ) pucReadData, x6ByteLength, NULL ); + } + taskEXIT_CRITICAL(); + prvCheckExpectedState( xReturned == x6ByteLength ); + + /* Does the data read out match that expected? */ + prvCheckExpectedState( memcmp( ( void * ) pucData, ( void * ) pucReadData, x6ByteLength ) == 0 ); + + /* The space in the buffer will have increased by the amount of user + * data removed from the buffer. */ + xExpected += x6ByteLength; + xReturned = xStreamBufferSpacesAvailable( xStreamBuffer ); + prvCheckExpectedState( xReturned == xExpected ); + xReturned = xStreamBufferBytesAvailable( xStreamBuffer ); + prvCheckExpectedState( xReturned == ( sbSTREAM_BUFFER_LENGTH_BYTES - xExpected ) ); + } + + /* The buffer should be empty again. */ + prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdTRUE ); + xExpected = xStreamBufferSpacesAvailable( xStreamBuffer ); + prvCheckExpectedState( xExpected == sbSTREAM_BUFFER_LENGTH_BYTES ); + + /* Reading with a timeout should also fail after the appropriate time. The + * priority is temporarily boosted in this part of the test to keep the + * allowable margin to a minimum. */ + vTaskPrioritySet( NULL, configMAX_PRIORITIES - 1 ); + xTimeBeforeCall = xTaskGetTickCount(); + xReturned = xStreamBufferReceive( xStreamBuffer, ( void * ) pucReadData, x6ByteLength, xBlockTime ); + xTimeAfterCall = xTaskGetTickCount(); + vTaskPrioritySet( NULL, uxOriginalPriority ); + prvCheckExpectedState( ( ( TickType_t ) ( xTimeAfterCall - xTimeBeforeCall ) ) >= xBlockTime ); + prvCheckExpectedState( ( ( TickType_t ) ( xTimeAfterCall - xTimeBeforeCall ) ) < ( xBlockTime + xAllowableMargin ) ); + prvCheckExpectedState( xReturned == 0 ); + + + /* In the next loop 17 bytes are written to then read out on each + * iteration. As 30 is not divisible by 17 the data will wrap around. */ + xExpected = sbSTREAM_BUFFER_LENGTH_BYTES - x17ByteLength; + + for( xItem = 0; xItem < 100; xItem++ ) + { + /* Generate recognisable data to write to the queue. This is just + * ascii characters that shows which loop iteration the data was written + * in. */ + memset( ( void * ) pucData, ( ( int ) '0' ) + ( int ) xItem, x17ByteLength ); + xReturned = xStreamBufferSend( xStreamBuffer, ( void * ) pucData, x17ByteLength, sbDONT_BLOCK ); + prvCheckExpectedState( xReturned == x17ByteLength ); + + /* The space in the buffer will have reduced by the amount of user data + * written into the buffer. */ + xReturned = xStreamBufferSpacesAvailable( xStreamBuffer ); + prvCheckExpectedState( xReturned == xExpected ); + xReturned = xStreamBufferBytesAvailable( xStreamBuffer ); + prvCheckExpectedState( xReturned == x17ByteLength ); + prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdFALSE ); + prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdFALSE ); + + /* Read the 17 bytes out again. */ + xReturned = xStreamBufferReceive( xStreamBuffer, ( void * ) pucReadData, x17ByteLength, sbDONT_BLOCK ); + prvCheckExpectedState( xReturned == x17ByteLength ); + + /* Does the data read out match that expected? */ + prvCheckExpectedState( memcmp( ( void * ) pucData, ( void * ) pucReadData, x17ByteLength ) == 0 ); + + /* Full buffer space available again. */ + xReturned = xStreamBufferSpacesAvailable( xStreamBuffer ); + prvCheckExpectedState( xReturned == sbSTREAM_BUFFER_LENGTH_BYTES ); + xReturned = xStreamBufferBytesAvailable( xStreamBuffer ); + prvCheckExpectedState( xReturned == 0 ); + prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdFALSE ); + prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdTRUE ); + } + + /* Fill the buffer with one message, check it is full, then read it back + * again and check the correct data is received. */ + xStreamBufferSend( xStreamBuffer, ( const void * ) pc55ByteString, sbSTREAM_BUFFER_LENGTH_BYTES, sbDONT_BLOCK ); + xStreamBufferReceive( xStreamBuffer, ( void * ) pucFullBuffer, sbSTREAM_BUFFER_LENGTH_BYTES, sbDONT_BLOCK ); + prvCheckExpectedState( memcmp( pc55ByteString, pucFullBuffer, sbSTREAM_BUFFER_LENGTH_BYTES ) == 0 ); + + /* Fill the buffer one bytes at a time. */ + for( xItem = 0; xItem < sbSTREAM_BUFFER_LENGTH_BYTES; xItem++ ) + { + /* Block time is only for test coverage, the task should never actually + * block here. */ + xStreamBufferSend( xStreamBuffer, ( const void * ) &( pc54ByteString[ xItem ] ), sizeof( char ), sbRX_TX_BLOCK_TIME ); + } + + /* The buffer should now be full. */ + prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdTRUE ); + + /* Read the message out in one go, even though it was written in individual + * bytes. Try reading much more data than is actually available to ensure only + * the available bytes are returned (otherwise this read will write outside of + * the memory allocated anyway!). */ + xReturned = xStreamBufferReceive( xStreamBuffer, pucFullBuffer, sbSTREAM_BUFFER_LENGTH_BYTES * ( size_t ) 2, sbRX_TX_BLOCK_TIME ); + prvCheckExpectedState( xReturned == sbSTREAM_BUFFER_LENGTH_BYTES ); + prvCheckExpectedState( memcmp( ( const void * ) pc54ByteString, ( const void * ) pucFullBuffer, sbSTREAM_BUFFER_LENGTH_BYTES ) == 0 ); + + /* Now do the opposite, write in one go and read out in single bytes. */ + xReturned = xStreamBufferSend( xStreamBuffer, ( const void * ) pc55ByteString, sbSTREAM_BUFFER_LENGTH_BYTES, sbRX_TX_BLOCK_TIME ); + prvCheckExpectedState( xReturned == sbSTREAM_BUFFER_LENGTH_BYTES ); + prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdTRUE ); + prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdFALSE ); + prvCheckExpectedState( xStreamBufferBytesAvailable( xStreamBuffer ) == sbSTREAM_BUFFER_LENGTH_BYTES ); + prvCheckExpectedState( xStreamBufferSpacesAvailable( xStreamBuffer ) == 0 ); + + /* Read from the buffer one byte at a time. */ + for( xItem = 0; xItem < sbSTREAM_BUFFER_LENGTH_BYTES; xItem++ ) + { + /* Block time is only for test coverage, the task should never actually + * block here. */ + xStreamBufferReceive( xStreamBuffer, ( void * ) pucFullBuffer, sizeof( char ), sbRX_TX_BLOCK_TIME ); + prvCheckExpectedState( pc55ByteString[ xItem ] == pucFullBuffer[ 0 ] ); + } + + prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdTRUE ); + prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdFALSE ); + + /* Try writing more bytes than there is space. */ + vTaskPrioritySet( NULL, configMAX_PRIORITIES - 1 ); + xReturned = xStreamBufferSend( xStreamBuffer, ( const void * ) pc54ByteString, sbSTREAM_BUFFER_LENGTH_BYTES * ( size_t ) 2, xMinimalBlockTime ); + vTaskPrioritySet( NULL, uxOriginalPriority ); + prvCheckExpectedState( xReturned == sbSTREAM_BUFFER_LENGTH_BYTES ); + prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdTRUE ); + prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdFALSE ); + + /* No space now though. */ + xReturned = xStreamBufferSend( xStreamBuffer, ( const void * ) pc54ByteString, sbSTREAM_BUFFER_LENGTH_BYTES * ( size_t ) 2, xMinimalBlockTime ); + prvCheckExpectedState( xReturned == 0 ); + + /* Ensure data was written as expected even when there was an attempt to + * write more than was available. This also tries to read more bytes than are + * available. */ + xReturned = xStreamBufferReceive( xStreamBuffer, ( void * ) pucFullBuffer, xFullBufferSize, xMinimalBlockTime ); + prvCheckExpectedState( memcmp( ( const void * ) pucFullBuffer, ( const void * ) pc54ByteString, sbSTREAM_BUFFER_LENGTH_BYTES ) == 0 ); + prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdFALSE ); + prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdTRUE ); + + /* Clean up with data in the buffer to ensure the tests that follow don't + * see the data (the data should be discarded). */ + ( void ) xStreamBufferSend( xStreamBuffer, ( const void * ) pc55ByteString, sbSTREAM_BUFFER_LENGTH_BYTES / ( size_t ) 2, sbDONT_BLOCK ); + vPortFree( pucFullBuffer ); + xStreamBufferReset( xStreamBuffer ); +} +/*-----------------------------------------------------------*/ + +static void prvNonBlockingSenderTask( void * pvParameters ) +{ + StreamBufferHandle_t xStreamBuffer; + size_t xNextChar = 0, xBytesToSend, xBytesActuallySent; + const size_t xStringLength = strlen( pc54ByteString ); + + /* In this case the stream buffer has already been created and is passed + * into the task using the task's parameter. */ + xStreamBuffer = ( StreamBufferHandle_t ) pvParameters; + + /* Keep sending the string to the stream buffer as many bytes as possible in + * each go. Doesn't block so calls can interleave with the non-blocking + * receives performed by prvNonBlockingReceiverTask(). */ + for( ; ; ) + { + /* The whole string cannot be sent at once, so xNextChar is an index to + * the position within the string that has been sent so far. How many + * bytes are there left to send before the end of the string? */ + xBytesToSend = xStringLength - xNextChar; + + /* Attempt to send right up to the end of the string. */ + xBytesActuallySent = xStreamBufferSend( xStreamBuffer, ( const void * ) &( pc54ByteString[ xNextChar ] ), xBytesToSend, sbDONT_BLOCK ); + prvCheckExpectedState( xBytesActuallySent <= xBytesToSend ); + + /* Move the index up the string to the next character to be sent, + * wrapping if the end of the string has been reached. */ + xNextChar += xBytesActuallySent; + prvCheckExpectedState( xNextChar <= xStringLength ); + + if( xNextChar == xStringLength ) + { + xNextChar = 0; + } + } +} +/*-----------------------------------------------------------*/ + +static void prvNonBlockingReceiverTask( void * pvParameters ) +{ + StreamBufferHandle_t xStreamBuffer; + size_t xNextChar = 0, xReceiveLength, xBytesToTest, xStartIndex; + const size_t xStringLength = strlen( pc54ByteString ); + char cRxString[ 12 ]; /* Holds received characters. */ + BaseType_t xNonBlockingReceiveError = pdFALSE; + + /* In this case the stream buffer has already been created and is passed + * into the task using the task's parameter. */ + xStreamBuffer = ( StreamBufferHandle_t ) pvParameters; + + /* Expects to receive the pc54ByteString over and over again. Sends and + * receives are not blocking so will interleave. */ + for( ; ; ) + { + /* Attempt to receive as many bytes as possible, up to the limit of the + * Rx buffer size. */ + xReceiveLength = xStreamBufferReceive( xStreamBuffer, ( void * ) cRxString, sizeof( cRxString ), sbDONT_BLOCK ); + + if( xReceiveLength > 0 ) + { + /* xNextChar is the index into pc54ByteString that has been received + * already. If xReceiveLength bytes are added to that, will it go off + * the end of the string? If so, then first test up to the end of the + * string, then go back to the start of pc54ByteString to test the + * remains of the received data. */ + xBytesToTest = xReceiveLength; + + if( ( xNextChar + xBytesToTest ) > xStringLength ) + { + /* Cap to test the received data to the end of the string. */ + xBytesToTest = xStringLength - xNextChar; + + if( memcmp( ( const void * ) &( pc54ByteString[ xNextChar ] ), ( const void * ) cRxString, xBytesToTest ) != 0 ) + { + xNonBlockingReceiveError = pdTRUE; + } + + /* Then move back to the start of the string to test the + * remaining received bytes. */ + xNextChar = 0; + xStartIndex = xBytesToTest; + xBytesToTest = xReceiveLength - xBytesToTest; + } + else + { + /* The string didn't wrap in the buffer, so start comparing from + * the start of the received data. */ + xStartIndex = 0; + } + + /* Test the received bytes are as expected, then move the index + * along the string to the next expected char to receive. */ + if( memcmp( ( const void * ) &( pc54ByteString[ xNextChar ] ), ( const void * ) &( cRxString[ xStartIndex ] ), xBytesToTest ) != 0 ) + { + xNonBlockingReceiveError = pdTRUE; + } + + if( xNonBlockingReceiveError == pdFALSE ) + { + /* No errors detected so increment the counter that lets the + * check task know this test is still functioning correctly. */ + ulNonBlockingRxCounter++; + } + + xNextChar += xBytesToTest; + + if( xNextChar >= xStringLength ) + { + xNextChar = 0; + } + } + } +} +/*-----------------------------------------------------------*/ + +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + + static void prvSenderTask( void * pvParameters ) + { + StreamBufferHandle_t xStreamBuffer, xTempStreamBuffer; + static uint8_t ucTempBuffer[ 10 ]; /* Just used to exercise stream buffer creating and deletion. */ + const TickType_t xTicksToWait = sbRX_TX_BLOCK_TIME, xShortDelay = pdMS_TO_TICKS( 50 ); + StaticStreamBuffer_t xStaticStreamBuffer; + size_t xNextChar = 0, xBytesToSend, xBytesActuallySent; + const size_t xStringLength = strlen( pc55ByteString ); + + /* The task's priority is used as an index into the loop counters used to + * indicate this task is still running. */ + UBaseType_t uxIndex = uxTaskPriorityGet( NULL ); + + /* Make sure a change in priority does not inadvertently result in an + * invalid array index. */ + prvCheckExpectedState( uxIndex < sbNUMBER_OF_ECHO_CLIENTS ); + + /* Avoid compiler warnings about unused parameters. */ + ( void ) pvParameters; + + xStreamBuffer = xStreamBufferCreateStatic( sizeof( ucBufferStorage ) / sbNUMBER_OF_SENDER_TASKS, /* The number of bytes in each buffer in the array. */ + sbTRIGGER_LEVEL_1, /* The number of bytes to be in the buffer before a task blocked to wait for data is unblocked. */ + &( ucBufferStorage[ uxIndex ][ 0 ] ), /* The address of the buffer to use within the array. */ + &( xStaticStreamBuffers[ uxIndex ] ) ); /* The static stream buffer structure to use within the array. */ + + /* Now the stream buffer has been created the receiver task can be + * created. If this sender task has the higher priority then the receiver + * task is created at the lower priority - if this sender task has the + * lower priority then the receiver task is created at the higher + * priority. */ + if( uxTaskPriorityGet( NULL ) == sbLOWER_PRIORITY ) + { + /* Here prvSingleTaskTests() performs various tests on a stream buffer + * that was created statically. */ + prvSingleTaskTests( xStreamBuffer ); + xTaskCreate( prvReceiverTask, "StrReceiver", sbSMALLER_STACK_SIZE, ( void * ) xStreamBuffer, sbHIGHER_PRIORITY, NULL ); + } + else + { + xTaskCreate( prvReceiverTask, "StrReceiver", sbSMALLER_STACK_SIZE, ( void * ) xStreamBuffer, sbLOWER_PRIORITY, NULL ); + } + + for( ; ; ) + { + /* The whole string cannot be sent at once, so xNextChar is an index + * to the position within the string that has been sent so far. How + * many bytes are there left to send before the end of the string? */ + xBytesToSend = xStringLength - xNextChar; + + /* Attempt to send right up to the end of the string. */ + xBytesActuallySent = xStreamBufferSend( xStreamBuffer, ( const void * ) &( pc55ByteString[ xNextChar ] ), xBytesToSend, xTicksToWait ); + prvCheckExpectedState( xBytesActuallySent <= xBytesToSend ); + + /* Move the index up the string to the next character to be sent, + * wrapping if the end of the string has been reached. */ + xNextChar += xBytesActuallySent; + prvCheckExpectedState( xNextChar <= xStringLength ); + + if( xNextChar == xStringLength ) + { + xNextChar = 0; + } + + /* Increment a loop counter so a check task can tell this task is + * still running as expected. */ + ulSenderLoopCounters[ uxIndex ]++; + + if( uxTaskPriorityGet( NULL ) == sbHIGHER_PRIORITY ) + { + /* Allow other tasks to run. */ + vTaskDelay( xShortDelay ); + } + + /* This stream buffer is just created and deleted to ensure no + * issues when attempting to delete a stream buffer that was + * created using statically allocated memory. To save stack space + * the buffer is set to point to the pc55ByteString, which is a const + * string, but no data is written into the buffer so any valid address + * will do. */ + xTempStreamBuffer = xStreamBufferCreateStatic( sizeof( ucTempBuffer ), sbTRIGGER_LEVEL_1, ucTempBuffer, &xStaticStreamBuffer ); + xStreamBufferReset( xTempStreamBuffer ); + vStreamBufferDelete( xTempStreamBuffer ); + } + } + +#endif /* configSUPPORT_STATIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + + static void prvReceiverTask( void * pvParameters ) + { + StreamBufferHandle_t const pxStreamBuffer = ( StreamBufferHandle_t ) pvParameters; + char cRxString[ 12 ]; /* Large enough to hold a 32-bit number in ASCII. */ + const TickType_t xTicksToWait = pdMS_TO_TICKS( 5UL ); + const size_t xStringLength = strlen( pc55ByteString ); + size_t xNextChar = 0, xReceivedLength, xBytesToReceive; + + for( ; ; ) + { + /* Attempt to receive the number of bytes to the end of the string, + * or the number of byte that can be placed into the rx buffer, + * whichever is smallest. */ + xBytesToReceive = configMIN( ( xStringLength - xNextChar ), sizeof( cRxString ) ); + + do + { + xReceivedLength = xStreamBufferReceive( pxStreamBuffer, ( void * ) cRxString, xBytesToReceive, xTicksToWait ); + } while( xReceivedLength == 0 ); + + /* Ensure the received string matches the expected string. */ + prvCheckExpectedState( memcmp( ( void * ) cRxString, ( const void * ) &( pc55ByteString[ xNextChar ] ), xReceivedLength ) == 0 ); + + /* Move the index into the string up to the end of the bytes + * received so far - wrapping if the end of the string has been + * reached. */ + xNextChar += xReceivedLength; + + if( xNextChar >= xStringLength ) + { + xNextChar = 0; + } + } + } + +#endif /* configSUPPORT_STATIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +static void prvEchoClient( void * pvParameters ) +{ + size_t xSendLength = 0, ux; + char * pcStringToSend, * pcStringReceived, cNextChar = sbASCII_SPACE; + const TickType_t xTicksToWait = pdMS_TO_TICKS( 50 ); + StreamBufferHandle_t xTempStreamBuffer; + +/* The task's priority is used as an index into the loop counters used to + * indicate this task is still running. */ + UBaseType_t uxIndex = uxTaskPriorityGet( NULL ); + +/* Pointers to the client and server stream buffers are passed into this task + * using the task's parameter. */ + EchoStreamBuffers_t * pxStreamBuffers = ( EchoStreamBuffers_t * ) pvParameters; + + /* Prevent compiler warnings. */ + ( void ) pvParameters; + + /* Create the buffer into which strings to send to the server will be + * created, and the buffer into which strings echoed back from the server will + * be copied. */ + pcStringToSend = ( char * ) pvPortMalloc( sbSTREAM_BUFFER_LENGTH_BYTES ); + pcStringReceived = ( char * ) pvPortMalloc( sbSTREAM_BUFFER_LENGTH_BYTES ); + + configASSERT( pcStringToSend ); + configASSERT( pcStringReceived ); + + for( ; ; ) + { + /* Generate the length of the next string to send. */ + xSendLength++; + + /* The stream buffer is being used to hold variable length data, so + * each data item requires sizeof( size_t ) bytes to hold the data's + * length, hence the sizeof() in the if() condition below. */ + if( xSendLength > ( sbSTREAM_BUFFER_LENGTH_BYTES - sizeof( size_t ) ) ) + { + /* Back to a string length of 1. */ + xSendLength = sizeof( char ); + } + + memset( pcStringToSend, 0x00, sbSTREAM_BUFFER_LENGTH_BYTES ); + + for( ux = 0; ux < xSendLength; ux++ ) + { + pcStringToSend[ ux ] = cNextChar; + + cNextChar++; + + if( cNextChar > sbASCII_TILDA ) + { + cNextChar = sbASCII_SPACE; + } + } + + /* Send the generated string to the buffer. */ + do + { + ux = xStreamBufferSend( pxStreamBuffers->xEchoClientBuffer, ( void * ) pcStringToSend, xSendLength, xTicksToWait ); + } while( ux == 0 ); + + /* Wait for the string to be echoed back. */ + memset( pcStringReceived, 0x00, sbSTREAM_BUFFER_LENGTH_BYTES ); + xStreamBufferReceive( pxStreamBuffers->xEchoServerBuffer, ( void * ) pcStringReceived, xSendLength, portMAX_DELAY ); + + prvCheckExpectedState( strcmp( pcStringToSend, pcStringReceived ) == 0 ); + + /* Maintain a count of the number of times this code executes so a + * check task can determine if this task is still functioning as + * expected or not. As there are two client tasks, and the priorities + * used are 0 and 1, the task's priority is used as an index into the + * loop count array. */ + ulEchoLoopCounters[ uxIndex ]++; + + /* This stream buffer is just created and deleted to ensure no memory + * leaks. */ + xTempStreamBuffer = xStreamBufferCreate( sbSTREAM_BUFFER_LENGTH_BYTES, sbTRIGGER_LEVEL_1 ); + vStreamBufferDelete( xTempStreamBuffer ); + + /* The following are tests for a stream buffer of size one. */ + /* Create a buffer of size one. */ + xTempStreamBuffer = xStreamBufferCreate( sbSTREAM_BUFFER_LENGTH_ONE, sbTRIGGER_LEVEL_1 ); + /* Ensure that the buffer was created successfully. */ + configASSERT( xTempStreamBuffer ); + + /* Send one byte to the buffer. */ + ux = xStreamBufferSend( xTempStreamBuffer, ( void * ) pcStringToSend, ( size_t ) 1, sbDONT_BLOCK ); + /* Ensure that the byte was sent successfully. */ + configASSERT( ux == 1 ); + /* Try sending another byte to the buffer. */ + ux = xStreamBufferSend( xTempStreamBuffer, ( void * ) pcStringToSend, ( size_t ) 1, sbDONT_BLOCK ); + /* Make sure that send failed as the buffer is full. */ + configASSERT( ux == 0 ); + + /* Receive one byte from the buffer. */ + memset( pcStringReceived, 0x00, sbSTREAM_BUFFER_LENGTH_BYTES ); + ux = xStreamBufferReceive( xTempStreamBuffer, ( void * ) pcStringReceived, ( size_t ) 1, sbDONT_BLOCK ); + /* Ensure that the receive was successful. */ + configASSERT( ux == 1 ); + /* Ensure that the correct data was received. */ + configASSERT( pcStringToSend[ 0 ] == pcStringReceived[ 0 ] ); + /* Try receiving another byte from the buffer. */ + ux = xStreamBufferReceive( xTempStreamBuffer, ( void * ) pcStringReceived, ( size_t ) 1, sbDONT_BLOCK ); + /* Ensure that the receive failed as the buffer is empty. */ + configASSERT( ux == 0 ); + + /* Try sending two bytes to the buffer. Since the size of the + * buffer is one, we must not be able to send more than one. */ + ux = xStreamBufferSend( xTempStreamBuffer, ( void * ) pcStringToSend, ( size_t ) 2, sbDONT_BLOCK ); + /* Ensure that only one byte was sent. */ + configASSERT( ux == 1 ); + + /* Try receiving two bytes from the buffer. Since the size of the + * buffer is one, we must not be able to get more than one. */ + memset( pcStringReceived, 0x00, sbSTREAM_BUFFER_LENGTH_BYTES ); + ux = xStreamBufferReceive( xTempStreamBuffer, ( void * ) pcStringReceived, ( size_t ) 2, sbDONT_BLOCK ); + /* Ensure that only one byte was received. */ + configASSERT( ux == 1 ); + /* Ensure that the correct data was received. */ + configASSERT( pcStringToSend[ 0 ] == pcStringReceived[ 0 ] ); + + /* Delete the buffer. */ + vStreamBufferDelete( xTempStreamBuffer ); + } +} +/*-----------------------------------------------------------*/ + +static void prvEchoServer( void * pvParameters ) +{ + size_t xReceivedLength; + char * pcReceivedString; + EchoStreamBuffers_t xStreamBuffers; + TickType_t xTimeOnEntering; + const TickType_t xTicksToBlock = pdMS_TO_TICKS( 350UL ); + + /* Prevent compiler warnings about unused parameters. */ + ( void ) pvParameters; + + /* Create the stream buffer used to send data from the client to the server, + * and the stream buffer used to echo the data from the server back to the + * client. */ + xStreamBuffers.xEchoClientBuffer = xStreamBufferCreate( sbSTREAM_BUFFER_LENGTH_BYTES, sbTRIGGER_LEVEL_1 ); + xStreamBuffers.xEchoServerBuffer = xStreamBufferCreate( sbSTREAM_BUFFER_LENGTH_BYTES, sbTRIGGER_LEVEL_1 ); + configASSERT( xStreamBuffers.xEchoClientBuffer ); + configASSERT( xStreamBuffers.xEchoServerBuffer ); + + /* Create the buffer into which received strings will be copied. */ + pcReceivedString = ( char * ) pvPortMalloc( sbSTREAM_BUFFER_LENGTH_BYTES ); + configASSERT( pcReceivedString ); + + /* Don't expect to receive anything yet! */ + xTimeOnEntering = xTaskGetTickCount(); + xReceivedLength = xStreamBufferReceive( xStreamBuffers.xEchoClientBuffer, ( void * ) pcReceivedString, sbSTREAM_BUFFER_LENGTH_BYTES, xTicksToBlock ); + prvCheckExpectedState( ( ( TickType_t ) ( xTaskGetTickCount() - xTimeOnEntering ) ) >= xTicksToBlock ); + prvCheckExpectedState( xReceivedLength == 0 ); + + /* Now the stream buffers have been created the echo client task can be + * created. If this server task has the higher priority then the client task + * is created at the lower priority - if this server task has the lower + * priority then the client task is created at the higher priority. */ + if( uxTaskPriorityGet( NULL ) == sbLOWER_PRIORITY ) + { + xTaskCreate( prvEchoClient, "EchoClient", sbSMALLER_STACK_SIZE, ( void * ) &xStreamBuffers, sbHIGHER_PRIORITY, NULL ); + } + else + { + /* Here prvSingleTaskTests() performs various tests on a stream buffer + * that was created dynamically. */ + prvSingleTaskTests( xStreamBuffers.xEchoClientBuffer ); + xTaskCreate( prvEchoClient, "EchoClient", sbSMALLER_STACK_SIZE, ( void * ) &xStreamBuffers, sbLOWER_PRIORITY, NULL ); + } + + for( ; ; ) + { + memset( pcReceivedString, 0x00, sbSTREAM_BUFFER_LENGTH_BYTES ); + + /* Has any data been sent by the client? */ + xReceivedLength = xStreamBufferReceive( xStreamBuffers.xEchoClientBuffer, ( void * ) pcReceivedString, sbSTREAM_BUFFER_LENGTH_BYTES, portMAX_DELAY ); + + /* Should always receive data as max delay was used. */ + prvCheckExpectedState( xReceivedLength > 0 ); + + /* Echo the received data back to the client. */ + xStreamBufferSend( xStreamBuffers.xEchoServerBuffer, ( void * ) pcReceivedString, xReceivedLength, portMAX_DELAY ); + } +} +/*-----------------------------------------------------------*/ + +void vPeriodicStreamBufferProcessing( void ) +{ + static size_t xNextChar = 0; + BaseType_t xHigherPriorityTaskWoken = pdFALSE; + + /* Called from the tick interrupt hook. If the global stream buffer + * variable is not NULL then the prvInterruptTriggerTest() task expects a byte + * to be sent to the stream buffer on each tick interrupt. */ + if( xInterruptStreamBuffer != NULL ) + { + /* One character from the pcDataSentFromInterrupt string is sent on each + * interrupt. The task blocked on the stream buffer should not be + * unblocked until the defined trigger level is hit. */ + xStreamBufferSendFromISR( xInterruptStreamBuffer, ( const void * ) &( pcDataSentFromInterrupt[ xNextChar ] ), sizeof( char ), &xHigherPriorityTaskWoken ); + + if( xNextChar < strlen( pcDataSentFromInterrupt ) ) + { + xNextChar++; + } + } + else + { + /* Start at the beginning of the string being sent again. */ + xNextChar = 0; + } +} +/*-----------------------------------------------------------*/ + +static void prvInterruptTriggerLevelTest( void * pvParameters ) +{ + StreamBufferHandle_t xStreamBuffer; + size_t xTriggerLevel = 1, xBytesReceived; + const size_t xStreamBufferSizeBytes = ( size_t ) 9, xMaxTriggerLevel = ( size_t ) 7, xMinTriggerLevel = ( size_t ) 2; + const TickType_t xReadBlockTime = 5, xCycleBlockTime = pdMS_TO_TICKS( 100 ); + uint8_t ucRxData[ 9 ]; + BaseType_t xErrorDetected = pdFALSE; + + #ifndef configSTREAM_BUFFER_TRIGGER_LEVEL_TEST_MARGIN + const size_t xAllowableMargin = ( size_t ) 0; + #else + const size_t xAllowableMargin = ( size_t ) configSTREAM_BUFFER_TRIGGER_LEVEL_TEST_MARGIN; + #endif + + /* Remove compiler warning about unused parameter. */ + ( void ) pvParameters; + + for( ; ; ) + { + for( xTriggerLevel = xMinTriggerLevel; xTriggerLevel < xMaxTriggerLevel; xTriggerLevel++ ) + { + /* This test is very time sensitive so delay at the beginning to ensure + * the rest of the system is up and running before starting. Delay between + * each loop to ensure the interrupt that sends to the stream buffer + * detects it needs to start sending from the start of the strin again.. */ + vTaskDelay( xCycleBlockTime ); + + /* Create the stream buffer that will be used from inside the tick + * interrupt. */ + memset( ucRxData, 0x00, sizeof( ucRxData ) ); + xStreamBuffer = xStreamBufferCreate( xStreamBufferSizeBytes, xTriggerLevel ); + configASSERT( xStreamBuffer ); + + /* Now the stream buffer has been created it can be assigned to the + * file scope variable, which will allow the tick interrupt to start + * using it. */ + taskENTER_CRITICAL(); + { + xInterruptStreamBuffer = xStreamBuffer; + } + taskEXIT_CRITICAL(); + + xBytesReceived = xStreamBufferReceive( xStreamBuffer, ( void * ) ucRxData, sizeof( ucRxData ), xReadBlockTime ); + + /* Set the file scope variable back to NULL so the interrupt doesn't + * try to use it again. */ + taskENTER_CRITICAL(); + { + xInterruptStreamBuffer = NULL; + } + taskEXIT_CRITICAL(); + + /* Now check the number of bytes received equals the trigger level, + * except in the case that the read timed out before the trigger level + * was reached. */ + if( xTriggerLevel > xReadBlockTime ) + { + /* Trigger level was greater than the block time so expect to + * time out having received xReadBlockTime bytes. */ + if( xBytesReceived > xReadBlockTime ) + { + /* Received more bytes than expected. That could happen if + * this task unblocked at the right time, but an interrupt + * added another byte to the stream buffer before this task was + * able to run. */ + if( ( xBytesReceived - xReadBlockTime ) > xAllowableMargin ) + { + xErrorDetected = pdTRUE; + } + } + else if( xReadBlockTime != xBytesReceived ) + { + /* It is possible the interrupt placed an item in the stream + * buffer before this task called xStreamBufferReceive(), but + * if that is the case then xBytesReceived will only every be + * 0 as the interrupt will only have executed once. */ + if( xBytesReceived != 1 ) + { + xErrorDetected = pdTRUE; + } + } + } + else if( xTriggerLevel < xReadBlockTime ) + { + /* Trigger level was less than the block time so we expect to + * have received the trigger level number of bytes - could be more + * though depending on other activity between the task being + * unblocked and the task reading the number of bytes received. It + * could also be less if the interrupt already put something in the + * stream buffer before this task attempted to read it - in which + * case the task would have returned the available bytes immediately + * without ever blocking - in that case the bytes received will + * only ever be 1 as the interrupt would not have executed more + * than one in that time unless this task has too low a priority. */ + if( xBytesReceived < xTriggerLevel ) + { + if( xBytesReceived != 1 ) + { + xErrorDetected = pdTRUE; + } + } + else if( ( xBytesReceived - xTriggerLevel ) > xAllowableMargin ) + { + xErrorDetected = pdTRUE; + } + } + else + { + /* The trigger level equalled the block time, so expect to + * receive no greater than the block time. It could also be less + * if the interrupt already put something in the stream buffer + * before this task attempted to read it - in which case the task + * would have returned the available bytes immediately without ever + * blocking - in that case the bytes received would only ever be 1 + * because the interrupt is not going to execute twice in that time + * unless this task is running a too low a priority. */ + if( xBytesReceived < xReadBlockTime ) + { + if( xBytesReceived != 1 ) + { + xErrorDetected = pdTRUE; + } + } + else if( ( xBytesReceived - xReadBlockTime ) > xAllowableMargin ) + { + xErrorDetected = pdTRUE; + } + } + + if( xBytesReceived > sizeof( ucRxData ) ) + { + xErrorDetected = pdTRUE; + } + else if( memcmp( ( void * ) ucRxData, ( const void * ) pcDataSentFromInterrupt, xBytesReceived ) != 0 ) + { + /* Received data didn't match that expected. */ + xErrorDetected = pdTRUE; + } + + if( xErrorDetected == pdFALSE ) + { + /* Increment the cycle counter so the 'check' task knows this test + * is still running without error. */ + ulInterruptTriggerCounter++; + } + + /* Tidy up ready for the next loop. */ + vStreamBufferDelete( xStreamBuffer ); + } + } +} +/*-----------------------------------------------------------*/ + +BaseType_t xAreStreamBufferTasksStillRunning( void ) +{ + static uint32_t ulLastEchoLoopCounters[ sbNUMBER_OF_ECHO_CLIENTS ] = { 0 }; + static uint32_t ulLastNonBlockingRxCounter = 0; + static uint32_t ulLastInterruptTriggerCounter = 0; + BaseType_t x; + + for( x = 0; x < sbNUMBER_OF_ECHO_CLIENTS; x++ ) + { + if( ulLastEchoLoopCounters[ x ] == ulEchoLoopCounters[ x ] ) + { + xErrorStatus = pdFAIL; + } + else + { + ulLastEchoLoopCounters[ x ] = ulEchoLoopCounters[ x ]; + } + } + + if( ulNonBlockingRxCounter == ulLastNonBlockingRxCounter ) + { + xErrorStatus = pdFAIL; + } + else + { + ulLastNonBlockingRxCounter = ulNonBlockingRxCounter; + } + + if( ulLastInterruptTriggerCounter == ulInterruptTriggerCounter ) + { + xErrorStatus = pdFAIL; + } + else + { + ulLastInterruptTriggerCounter = ulInterruptTriggerCounter; + } + + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + static uint32_t ulLastSenderLoopCounters[ sbNUMBER_OF_ECHO_CLIENTS ] = { 0 }; + + for( x = 0; x < sbNUMBER_OF_SENDER_TASKS; x++ ) + { + if( ulLastSenderLoopCounters[ x ] == ulSenderLoopCounters[ x ] ) + { + xErrorStatus = pdFAIL; + } + else + { + ulLastSenderLoopCounters[ x ] = ulSenderLoopCounters[ x ]; + } + } + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ + + return xErrorStatus; +} +/*-----------------------------------------------------------*/ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/StreamBufferInterrupt.c b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/StreamBufferInterrupt.c new file mode 100644 index 0000000..724d8a4 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/StreamBufferInterrupt.c @@ -0,0 +1,229 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +/* + * A simple example that shows a stream buffer being used to pass data from an + * interrupt to a task. + * + * There are two strings, pcStringToSend and pcStringToReceive, where + * pcStringToReceive is a substring of pcStringToSend. The interrupt sends + * a few bytes of pcStringToSend to a stream buffer ever few times that it + * executes. A task reads the bytes from the stream buffer, looking for the + * substring, and flagging an error if the received data is invalid. + */ + +/* Standard includes. */ +#include "stdio.h" +#include "string.h" + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "stream_buffer.h" + +/* Demo app includes. */ +#include "StreamBufferInterrupt.h" + +#define sbiSTREAM_BUFFER_LENGTH_BYTES ( ( size_t ) 100 ) +#define sbiSTREAM_BUFFER_TRIGGER_LEVEL_10 ( ( BaseType_t ) 10 ) + +/*-----------------------------------------------------------*/ + +/* Implements the task that receives a stream of bytes from the interrupt. */ +static void prvReceivingTask( void * pvParameters ); + +/*-----------------------------------------------------------*/ + +/* The stream buffer that is used to send data from an interrupt to the task. */ +static StreamBufferHandle_t xStreamBuffer = NULL; + +/* The string that is sent from the interrupt to the task four bytes at a + * time. Must be multiple of 4 bytes long as the ISR sends 4 bytes at a time*/ +static const char * pcStringToSend = "_____Hello FreeRTOS_____"; + +/* The string to task is looking for, which must be a substring of + * pcStringToSend. */ +static const char * pcStringToReceive = "Hello FreeRTOS"; + +/* Set to pdFAIL if anything unexpected happens. */ +static BaseType_t xDemoStatus = pdPASS; + +/* Incremented each time pcStringToReceive is correctly received, provided no + * errors have occurred. Used so the check task can check this task is still + * running as expected. */ +static uint32_t ulCycleCount = 0; + +/*-----------------------------------------------------------*/ + +void vStartStreamBufferInterruptDemo( void ) +{ + /* Create the stream buffer that sends data from the interrupt to the + * task, and create the task. */ + xStreamBuffer = xStreamBufferCreate( /* The buffer length in bytes. */ + sbiSTREAM_BUFFER_LENGTH_BYTES, + /* The stream buffer's trigger level. */ + sbiSTREAM_BUFFER_TRIGGER_LEVEL_10 ); + + xTaskCreate( prvReceivingTask, /* The function that implements the task. */ + "StrIntRx", /* Human readable name for the task. */ + configMINIMAL_STACK_SIZE, /* Stack size (in words!). */ + NULL, /* Task parameter is not used. */ + tskIDLE_PRIORITY + 2, /* The priority at which the task is created. */ + NULL ); /* No use for the task handle. */ +} +/*-----------------------------------------------------------*/ + +static void prvReceivingTask( void * pvParameters ) +{ + char cRxBuffer[ 20 ]; + BaseType_t xNextByte = 0; + + /* Remove warning about unused parameters. */ + ( void ) pvParameters; + + /* Make sure the string will fit in the Rx buffer, including the NULL + * terminator. */ + configASSERT( sizeof( cRxBuffer ) > strlen( pcStringToReceive ) ); + + /* Make sure the stream buffer has been created. */ + configASSERT( xStreamBuffer != NULL ); + + /* Start with the Rx buffer in a known state. */ + memset( cRxBuffer, 0x00, sizeof( cRxBuffer ) ); + + for( ; ; ) + { + /* Keep receiving characters until the end of the string is received. + * Note: An infinite block time is used to simplify the example. Infinite + * block times are not recommended in production code as they do not allow + * for error recovery. */ + xStreamBufferReceive( /* The stream buffer data is being received from. */ + xStreamBuffer, + /* Where to place received data. */ + ( void * ) &( cRxBuffer[ xNextByte ] ), + /* The number of bytes to receive. */ + sizeof( char ), + + /* The time to wait for the next data if the buffer + * is empty. */ + portMAX_DELAY ); + + /* If xNextByte is 0 then this task is looking for the start of the + * string, which is 'H'. */ + if( xNextByte == 0 ) + { + if( cRxBuffer[ xNextByte ] == 'H' ) + { + /* The start of the string has been found. Now receive + * characters until the end of the string is found. */ + xNextByte++; + } + } + else + { + /* Receiving characters while looking for the end of the string, + * which is an 'S'. */ + if( cRxBuffer[ xNextByte ] == 'S' ) + { + /* The string has now been received. Check its validity. */ + if( strcmp( cRxBuffer, pcStringToReceive ) != 0 ) + { + xDemoStatus = pdFAIL; + } + + /* Return to start looking for the beginning of the string + * again. */ + memset( cRxBuffer, 0x00, sizeof( cRxBuffer ) ); + xNextByte = 0; + + /* Increment the cycle count as an indication to the check task + * that this demo is still running. */ + if( xDemoStatus == pdPASS ) + { + ulCycleCount++; + } + } + else + { + /* Receive the next character the next time around, while + * continuing to look for the end of the string. */ + xNextByte++; + + configASSERT( ( size_t ) xNextByte < sizeof( cRxBuffer ) ); + } + } + } +} +/*-----------------------------------------------------------*/ + +void vBasicStreamBufferSendFromISR( void ) +{ + static size_t xNextByteToSend = 0; + const BaseType_t xCallsBetweenSends = 100, xBytesToSend = 4; + static BaseType_t xCallCount = 0; + + /* Is it time to write to the stream buffer again? */ + xCallCount++; + + if( xCallCount > xCallsBetweenSends ) + { + xCallCount = 0; + + /* Send the next four bytes to the stream buffer. */ + xStreamBufferSendFromISR( xStreamBuffer, + ( const void * ) ( pcStringToSend + xNextByteToSend ), + xBytesToSend, + NULL ); + + /* Send the next four bytes the next time around, wrapping to the start + * of the string if necessary. */ + xNextByteToSend += xBytesToSend; + + if( xNextByteToSend >= strlen( pcStringToSend ) ) + { + xNextByteToSend = 0; + } + } +} +/*-----------------------------------------------------------*/ + +BaseType_t xIsInterruptStreamBufferDemoStillRunning( void ) +{ + uint32_t ulLastCycleCount = 0; + + /* Check the demo is still running. */ + if( ulLastCycleCount == ulCycleCount ) + { + xDemoStatus = pdFAIL; + } + else + { + ulLastCycleCount = ulCycleCount; + } + + return xDemoStatus; +} diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/TaskNotify.c b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/TaskNotify.c new file mode 100644 index 0000000..ebaf277 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/TaskNotify.c @@ -0,0 +1,721 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + + +/* + * Tests the behaviour of direct task notifications. + */ + +/* Standard includes. */ +#include + +/* Scheduler include files. */ +#include "FreeRTOS.h" +#include "task.h" +#include "timers.h" + +/* Demo program include files. */ +#include "TaskNotify.h" + +/* Allow parameters to be overridden on a demo by demo basis. */ +#ifndef notifyNOTIFIED_TASK_STACK_SIZE + #define notifyNOTIFIED_TASK_STACK_SIZE configMINIMAL_STACK_SIZE +#endif + +#define notifyTASK_PRIORITY ( tskIDLE_PRIORITY ) + +/* Constants used in tests when setting/clearing bits. */ +#define notifyUINT32_MAX ( ( uint32_t ) 0xffffffff ) +#define notifyUINT32_HIGH_BYTE ( ( uint32_t ) 0xff000000 ) +#define notifyUINT32_LOW_BYTE ( ( uint32_t ) 0x000000ff ) + +#define notifySUSPENDED_TEST_TIMER_PERIOD pdMS_TO_TICKS( 50 ) + +/*-----------------------------------------------------------*/ + +/* + * Implementation of the task that gets notified. + */ +static void prvNotifiedTask( void * pvParameters ); + +/* + * Performs a few initial tests that can be done prior to creating the second + * task. + */ +static void prvSingleTaskTests( void ); + +/* + * Software timer callback function from which xTaskNotify() is called. + */ +static void prvNotifyingTimer( TimerHandle_t xTimer ); + +/* + * Utility function to create pseudo random numbers. + */ +static UBaseType_t prvRand( void ); + +/* + * Callback for a timer that is used during preliminary testing. The timer + * tests the behaviour when 1: a task waiting for a notification is suspended + * and then resumed without ever receiving a notification, and 2: when a task + * waiting for a notification receives a notification while it is suspended. + */ +static void prvSuspendedTaskTimerTestCallback( TimerHandle_t xExpiredTimer ); + +/*-----------------------------------------------------------*/ + +/* Used to latch errors during the test's execution. */ +static BaseType_t xErrorStatus = pdPASS; + +/* Used to ensure the task has not stalled. */ +static volatile uint32_t ulNotifyCycleCount = 0; + +/* The handle of the task that receives the notifications. */ +static TaskHandle_t xTaskToNotify = NULL; + +/* Used to count the notifications sent to the task from a software timer and + * the number of notifications received by the task from the software timer. The + * two should stay synchronised. */ +static uint32_t ulTimerNotificationsReceived = 0UL, ulTimerNotificationsSent = 0UL; + +/* The timer used to notify the task. */ +static TimerHandle_t xTimer = NULL; + +/* Used by the pseudo random number generating function. */ +static size_t uxNextRand = 0; + +/*-----------------------------------------------------------*/ + +void vStartTaskNotifyTask( void ) +{ + /* Create the task that performs some tests by itself, then loops around + * being notified by both a software timer and an interrupt. */ + xTaskCreate( prvNotifiedTask, /* Function that implements the task. */ + "Notified", /* Text name for the task - for debugging only - not used by the kernel. */ + notifyNOTIFIED_TASK_STACK_SIZE, /* Task's stack size in words, not bytes!. */ + NULL, /* Task parameter, not used in this case. */ + notifyTASK_PRIORITY, /* Task priority, 0 is the lowest. */ + &xTaskToNotify ); /* Used to pass a handle to the task out is needed, otherwise set to NULL. */ + + /* Pseudo seed the random number generator. */ + uxNextRand = ( size_t ) prvRand; +} +/*-----------------------------------------------------------*/ + +static void prvSingleTaskTests( void ) +{ + const TickType_t xTicksToWait = pdMS_TO_TICKS( 100UL ); + BaseType_t xReturned; + uint32_t ulNotifiedValue, ulLoop, ulNotifyingValue, ulPreviousValue, ulExpectedValue; + TickType_t xTimeOnEntering; + const uint32_t ulFirstNotifiedConst = 100001UL, ulSecondNotifiedValueConst = 5555UL, ulMaxLoops = 5UL; + const uint32_t ulBit0 = 0x01UL, ulBit1 = 0x02UL; + TimerHandle_t xSingleTaskTimer; + + + /* ------------------------------------------------------------------------ + * Check blocking when there are no notifications. */ + xTimeOnEntering = xTaskGetTickCount(); + xReturned = xTaskNotifyWait( notifyUINT32_MAX, 0, &ulNotifiedValue, xTicksToWait ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + + /* Should have blocked for the entire block time. */ + if( ( xTaskGetTickCount() - xTimeOnEntering ) < xTicksToWait ) + { + xErrorStatus = pdFAIL; + } + + configASSERT( xReturned == pdFAIL ); + configASSERT( ulNotifiedValue == 0UL ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + ( void ) ulNotifiedValue; + + + + /* ------------------------------------------------------------------------ + * Check no blocking when notifications are pending. First notify itself - + * this would not be a normal thing to do and is done here for test purposes + * only. */ + xReturned = xTaskNotifyAndQuery( xTaskToNotify, ulFirstNotifiedConst, eSetValueWithoutOverwrite, &ulPreviousValue ); + + /* Even through the 'without overwrite' action was used the update should + * have been successful. */ + configASSERT( xReturned == pdPASS ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + + /* No bits should have been pending previously. */ + configASSERT( ulPreviousValue == 0 ); + ( void ) ulPreviousValue; + + /* The task should now have a notification pending, and so not time out. */ + xTimeOnEntering = xTaskGetTickCount(); + xReturned = xTaskNotifyWait( notifyUINT32_MAX, 0, &ulNotifiedValue, xTicksToWait ); + + if( ( xTaskGetTickCount() - xTimeOnEntering ) >= xTicksToWait ) + { + xErrorStatus = pdFAIL; + } + + /* The task should have been notified, and the notified value should + * be equal to ulFirstNotifiedConst. */ + configASSERT( xReturned == pdPASS ); + configASSERT( ulNotifiedValue == ulFirstNotifiedConst ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + ( void ) ulNotifiedValue; + + /* Incremented to show the task is still running. */ + ulNotifyCycleCount++; + + + + /*------------------------------------------------------------------------- + * Check the non-overwriting functionality. The notification is done twice + * using two different notification values. The action says don't overwrite so + * only the first notification should pass and the value read back should also + * be that used with the first notification. */ + xReturned = xTaskNotify( xTaskToNotify, ulFirstNotifiedConst, eSetValueWithoutOverwrite ); + configASSERT( xReturned == pdPASS ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + + xReturned = xTaskNotify( xTaskToNotify, ulSecondNotifiedValueConst, eSetValueWithoutOverwrite ); + configASSERT( xReturned == pdFAIL ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + + /* Waiting for the notification should now return immediately so a block + * time of zero is used. */ + xReturned = xTaskNotifyWait( notifyUINT32_MAX, 0, &ulNotifiedValue, 0 ); + + configASSERT( xReturned == pdPASS ); + configASSERT( ulNotifiedValue == ulFirstNotifiedConst ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + ( void ) ulNotifiedValue; + + + + /*------------------------------------------------------------------------- + * Do the same again, only this time use the overwriting version. This time + * both notifications should pass, and the value written the second time should + * overwrite the value written the first time, and so be the value that is read + * back. */ + xReturned = xTaskNotify( xTaskToNotify, ulFirstNotifiedConst, eSetValueWithOverwrite ); + configASSERT( xReturned == pdPASS ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + xReturned = xTaskNotify( xTaskToNotify, ulSecondNotifiedValueConst, eSetValueWithOverwrite ); + configASSERT( xReturned == pdPASS ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + xReturned = xTaskNotifyWait( notifyUINT32_MAX, 0, &ulNotifiedValue, 0 ); + configASSERT( xReturned == pdPASS ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + configASSERT( ulNotifiedValue == ulSecondNotifiedValueConst ); + ( void ) ulNotifiedValue; + + + + /*------------------------------------------------------------------------- + * Check notifications with no action pass without updating the value. Even + * though ulFirstNotifiedConst is used as the value the value read back should + * remain at ulSecondNotifiedConst. */ + xReturned = xTaskNotify( xTaskToNotify, ulFirstNotifiedConst, eNoAction ); + configASSERT( xReturned == pdPASS ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + xReturned = xTaskNotifyWait( notifyUINT32_MAX, 0, &ulNotifiedValue, 0 ); + configASSERT( ulNotifiedValue == ulSecondNotifiedValueConst ); + ( void ) ulNotifiedValue; /* In case configASSERT() is not defined. */ + + /*------------------------------------------------------------------------- + * Check incrementing values. Send ulMaxLoop increment notifications, then + * ensure the received value is as expected - which should be + * ulSecondNotificationValueConst plus how ever many times to loop iterated. */ + for( ulLoop = 0; ulLoop < ulMaxLoops; ulLoop++ ) + { + xReturned = xTaskNotify( xTaskToNotify, 0, eIncrement ); + configASSERT( xReturned == pdPASS ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + } + + xReturned = xTaskNotifyWait( notifyUINT32_MAX, 0, &ulNotifiedValue, 0 ); + configASSERT( xReturned == pdPASS ); + configASSERT( ulNotifiedValue == ( ulSecondNotifiedValueConst + ulMaxLoops ) ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + ( void ) ulNotifiedValue; + + /* Should not be any notifications pending now. */ + xReturned = xTaskNotifyWait( 0, 0, &ulNotifiedValue, 0 ); + configASSERT( xReturned == pdFAIL ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + ( void ) ulNotifiedValue; + + + + /*------------------------------------------------------------------------- + * Check all bits can be set by notifying the task with one additional bit set + * on each notification, and exiting the loop when all the bits are found to be + * set. As there are 32-bits the loop should execute 32 times before all the + * bits are found to be set. */ + ulNotifyingValue = 0x01; + ulLoop = 0; + + /* Start with all bits clear. */ + xTaskNotifyWait( notifyUINT32_MAX, 0, &ulNotifiedValue, 0 ); + + do + { + /* Set the next bit in the task's notified value. */ + xTaskNotify( xTaskToNotify, ulNotifyingValue, eSetBits ); + + /* Wait for the notified value - which of course will already be + * available. Don't clear the bits on entry or exit as this loop is exited + * when all the bits are set. */ + xReturned = xTaskNotifyWait( 0, 0, &ulNotifiedValue, 0 ); + configASSERT( xReturned == pdPASS ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + + ulLoop++; + + /* Use the next bit on the next iteration around this loop. */ + ulNotifyingValue <<= 1UL; + } while( ulNotifiedValue != notifyUINT32_MAX ); + + /* As a 32-bit value was used the loop should have executed 32 times before + * all the bits were set. */ + configASSERT( ulLoop == 32 ); + + + + /*------------------------------------------------------------------------- + * Check bits are cleared on entry but not on exit when a notification fails + * to arrive before timing out - both with and without a timeout value. Wait + * for the notification again - but this time it is not given by anything and + * should return pdFAIL. The parameters are set to clear bit zero on entry and + * bit one on exit. As no notification was received only the bit cleared on + * entry should actually get cleared. */ + xReturned = xTaskNotifyWait( ulBit0, ulBit1, &ulNotifiedValue, xTicksToWait ); + configASSERT( xReturned == pdFAIL ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + + /* Notify the task with no action so as not to update the bits even though + * notifyUINT32_MAX is used as the notification value. */ + xTaskNotify( xTaskToNotify, notifyUINT32_MAX, eNoAction ); + + /* Reading back the value should should find bit 0 is clear, as this was + * cleared on entry, but bit 1 is not clear as it will not have been cleared on + * exit as no notification was received. */ + xReturned = xTaskNotifyWait( 0x00UL, 0x00UL, &ulNotifiedValue, 0 ); + configASSERT( xReturned == pdPASS ); + configASSERT( ulNotifiedValue == ( notifyUINT32_MAX & ~ulBit0 ) ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + + + + /*------------------------------------------------------------------------- + * Now try clearing the bit on exit. For that to happen a notification must be + * received, so the task is notified first. */ + xTaskNotify( xTaskToNotify, 0, eNoAction ); + xTaskNotifyWait( 0x00, ulBit1, &ulNotifiedValue, 0 ); + + /* However as the bit is cleared on exit, after the returned notification + * value is set, the returned notification value should not have the bit + * cleared... */ + configASSERT( ulNotifiedValue == ( notifyUINT32_MAX & ~ulBit0 ) ); + + /* ...but reading the value back again should find that the bit was indeed + * cleared internally. The returned value should be pdFAIL however as nothing + * has notified the task in the mean time. */ + xReturned = xTaskNotifyWait( 0x00, 0x00, &ulNotifiedValue, 0 ); + configASSERT( xReturned == pdFAIL ); + configASSERT( ulNotifiedValue == ( notifyUINT32_MAX & ~( ulBit0 | ulBit1 ) ) ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + + + + /*------------------------------------------------------------------------- + * Now try querying the previous value while notifying a task. */ + xTaskNotifyAndQuery( xTaskToNotify, 0x00, eSetBits, &ulPreviousValue ); + configASSERT( ulNotifiedValue == ( notifyUINT32_MAX & ~( ulBit0 | ulBit1 ) ) ); + + /* Clear all bits. */ + xTaskNotifyWait( 0x00, notifyUINT32_MAX, &ulNotifiedValue, 0 ); + xTaskNotifyAndQuery( xTaskToNotify, 0x00, eSetBits, &ulPreviousValue ); + configASSERT( ulPreviousValue == 0 ); + + ulExpectedValue = 0; + + for( ulLoop = 0x01; ulLoop < 0x80UL; ulLoop <<= 1UL ) + { + /* Set the next bit up, and expect to receive the last bits set (so + * the previous value will not yet have the bit being set this time + * around). */ + xTaskNotifyAndQuery( xTaskToNotify, ulLoop, eSetBits, &ulPreviousValue ); + configASSERT( ulExpectedValue == ulPreviousValue ); + ulExpectedValue |= ulLoop; + } + + /* ------------------------------------------------------------------------ + * Clear the previous notifications. */ + xTaskNotifyWait( notifyUINT32_MAX, 0, &ulNotifiedValue, 0 ); + + /* The task should not have any notifications pending, so an attempt to clear + * the notification state should fail. */ + configASSERT( xTaskNotifyStateClear( NULL ) == pdFALSE ); + + /* Get the task to notify itself. This is not a normal thing to do, and is + * only done here for test purposes. */ + xTaskNotifyAndQuery( xTaskToNotify, ulFirstNotifiedConst, eSetValueWithoutOverwrite, &ulPreviousValue ); + + /* Now the notification state should be eNotified, so it should now be + * possible to clear the notification state. */ + configASSERT( xTaskNotifyStateClear( NULL ) == pdTRUE ); + configASSERT( xTaskNotifyStateClear( NULL ) == pdFALSE ); + + + + /* ------------------------------------------------------------------------ + * Clear bits in the notification value. */ + + /* Get the task to set all bits its own notification value. This is not a + * normal thing to do, and is only done here for test purposes. */ + xTaskNotify( xTaskToNotify, notifyUINT32_MAX, eSetBits ); + + /* Now clear the top bytes - the returned value from the first call should + * indicate that previously all bits were set. */ + configASSERT( ulTaskNotifyValueClear( xTaskToNotify, notifyUINT32_HIGH_BYTE ) == notifyUINT32_MAX ); + + /* Next clear the bottom bytes - the returned value this time should indicate + * that the top byte was clear (before the bottom byte was cleared. */ + configASSERT( ulTaskNotifyValueClear( xTaskToNotify, notifyUINT32_LOW_BYTE ) == ( notifyUINT32_MAX & ~notifyUINT32_HIGH_BYTE ) ); + + /* Next clear all bytes - the returned value should indicate that previously the + * high and low bytes were clear. */ + configASSERT( ulTaskNotifyValueClear( xTaskToNotify, notifyUINT32_MAX ) == ( notifyUINT32_MAX & ~notifyUINT32_HIGH_BYTE & ~notifyUINT32_LOW_BYTE ) ); + + /* Now all bits should be clear. */ + configASSERT( ulTaskNotifyValueClear( xTaskToNotify, notifyUINT32_MAX ) == 0 ); + configASSERT( ulTaskNotifyValueClear( xTaskToNotify, 0UL ) == 0 ); + configASSERT( ulTaskNotifyValueClear( xTaskToNotify, notifyUINT32_MAX ) == 0 ); + + /* Now the notification state should be eNotified, so it should now be + * possible to clear the notification state. */ + configASSERT( xTaskNotifyStateClear( NULL ) == pdTRUE ); + configASSERT( xTaskNotifyStateClear( NULL ) == pdFALSE ); + + + + /* ------------------------------------------------------------------------ + * Create a timer that will try notifying this task while it is suspended. */ + xSingleTaskTimer = xTimerCreate( "SingleNotify", notifySUSPENDED_TEST_TIMER_PERIOD, pdFALSE, NULL, prvSuspendedTaskTimerTestCallback ); + configASSERT( xSingleTaskTimer ); + + /* Incremented to show the task is still running. */ + ulNotifyCycleCount++; + + /* Ensure no notifications are pending. */ + xTaskNotifyWait( notifyUINT32_MAX, 0, NULL, 0 ); + + /* Raise the task's priority so it can suspend itself before the timer + * expires. */ + vTaskPrioritySet( NULL, configMAX_PRIORITIES - 1 ); + + /* Start the timer that will try notifying this task while it is + * suspended, then wait for a notification. The first time the callback + * executes the timer will suspend the task, then resume the task, without + * ever sending a notification to the task. */ + ulNotifiedValue = 0; + xTimerStart( xSingleTaskTimer, portMAX_DELAY ); + + /* Check a notification is not received. */ + xReturned = xTaskNotifyWait( 0, 0, &ulNotifiedValue, portMAX_DELAY ); + configASSERT( xReturned == pdFALSE ); + configASSERT( ulNotifiedValue == 0 ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + + /* Incremented to show the task is still running. */ + ulNotifyCycleCount++; + + /* Start the timer that will try notifying this task while it is + * suspended, then wait for a notification. The second time the callback + * executes the timer will suspend the task, notify the task, then resume the + * task (previously it was suspended and resumed without being notified). */ + xTimerStart( xSingleTaskTimer, portMAX_DELAY ); + + /* Check a notification is received. */ + xReturned = xTaskNotifyWait( 0, 0, &ulNotifiedValue, portMAX_DELAY ); + configASSERT( xReturned == pdPASS ); + ( void ) xReturned; /* In case configASSERT() is not defined. */ + configASSERT( ulNotifiedValue != 0 ); + + /* Return the task to its proper priority and delete the timer as it is + * not used again. */ + vTaskPrioritySet( NULL, notifyTASK_PRIORITY ); + xTimerDelete( xSingleTaskTimer, portMAX_DELAY ); + + /* Incremented to show the task is still running. */ + ulNotifyCycleCount++; + + /* Leave all bits cleared. */ + xTaskNotifyWait( notifyUINT32_MAX, 0, NULL, 0 ); +} +/*-----------------------------------------------------------*/ + +static void prvSuspendedTaskTimerTestCallback( TimerHandle_t xExpiredTimer ) +{ + static uint32_t ulCallCount = 0; + + /* Remove compiler warnings about unused parameters. */ + ( void ) xExpiredTimer; + + /* Callback for a timer that is used during preliminary testing. The timer + * tests the behaviour when 1: a task waiting for a notification is suspended + * and then resumed without ever receiving a notification, and 2: when a task + * waiting for a notification receives a notification while it is suspended. */ + + if( ulCallCount == 0 ) + { + vTaskSuspend( xTaskToNotify ); + configASSERT( eTaskGetState( xTaskToNotify ) == eSuspended ); + vTaskResume( xTaskToNotify ); + } + else + { + vTaskSuspend( xTaskToNotify ); + + /* Sending a notification while the task is suspended should pass, but + * not cause the task to resume. ulCallCount is just used as a convenient + * non-zero value. */ + xTaskNotify( xTaskToNotify, ulCallCount, eSetValueWithOverwrite ); + + /* Make sure giving the notification didn't resume the task. */ + configASSERT( eTaskGetState( xTaskToNotify ) == eSuspended ); + + vTaskResume( xTaskToNotify ); + } + + ulCallCount++; +} +/*-----------------------------------------------------------*/ + +static void prvNotifyingTimer( TimerHandle_t xNotUsed ) +{ + ( void ) xNotUsed; + + xTaskNotifyGive( xTaskToNotify ); + + /* This value is also incremented from an interrupt. */ + taskENTER_CRITICAL(); + { + ulTimerNotificationsSent++; + } + taskEXIT_CRITICAL(); +} +/*-----------------------------------------------------------*/ + +static void prvNotifiedTask( void * pvParameters ) +{ + const TickType_t xMaxPeriod = pdMS_TO_TICKS( 90 ), xMinPeriod = pdMS_TO_TICKS( 10 ), xDontBlock = 0; + TickType_t xPeriod; + const uint32_t ulCyclesToRaisePriority = 50UL; + + /* Remove compiler warnings about unused parameters. */ + ( void ) pvParameters; + + /* Run a few tests that can be done from a single task before entering the + * main loop. */ + prvSingleTaskTests(); + + /* Create the software timer that is used to send notifications to this + * task. Notifications are also received from an interrupt. */ + xTimer = xTimerCreate( "Notifier", xMaxPeriod, pdFALSE, NULL, prvNotifyingTimer ); + + for( ; ; ) + { + /* Start the timer again with a different period. Sometimes the period + * will be higher than the task's block time, sometimes it will be lower + * than the task's block time. */ + xPeriod = prvRand() % xMaxPeriod; + + if( xPeriod < xMinPeriod ) + { + xPeriod = xMinPeriod; + } + + /* Change the timer period and start the timer. */ + xTimerChangePeriod( xTimer, xPeriod, portMAX_DELAY ); + + /* Block waiting for the notification again with a different period. + * Sometimes the period will be higher than the task's block time, + * sometimes it will be lower than the task's block time. */ + xPeriod = prvRand() % xMaxPeriod; + + if( xPeriod < xMinPeriod ) + { + xPeriod = xMinPeriod; + } + + /* Block to wait for a notification but without clearing the + * notification count, so only add one to the count of received + * notifications as any other notifications will remain pending. */ + if( ulTaskNotifyTake( pdFALSE, xPeriod ) != 0 ) + { + ulTimerNotificationsReceived++; + } + + /* Take a notification without clearing again, but this time without a + * block time specified. */ + if( ulTaskNotifyTake( pdFALSE, xDontBlock ) != 0 ) + { + ulTimerNotificationsReceived++; + } + + /* Wait for the next notification from the timer, clearing all + * notifications if one is received, so this time adding the total number + * of notifications that were pending as none will be left pending after + * the function call. */ + ulTimerNotificationsReceived += ulTaskNotifyTake( pdTRUE, xPeriod ); + + /* Occasionally raise the priority of the task being notified to test + * the path where the task is notified from an ISR and becomes the highest + * priority ready state task, but the pxHigherPriorityTaskWoken parameter + * is NULL (which it is in the tick hook that sends notifications to this + * task). */ + if( ( ulNotifyCycleCount % ulCyclesToRaisePriority ) == 0 ) + { + vTaskPrioritySet( xTaskToNotify, configMAX_PRIORITIES - 1 ); + + /* Wait for the next notification again, clearing all notifications + * if one is received, but this time blocking indefinitely. */ + ulTimerNotificationsReceived += ulTaskNotifyTake( pdTRUE, portMAX_DELAY ); + + /* Reset the priority. */ + vTaskPrioritySet( xTaskToNotify, notifyTASK_PRIORITY ); + } + else + { + /* Wait for the next notification again, clearing all notifications + * if one is received, but this time blocking indefinitely. */ + ulTimerNotificationsReceived += ulTaskNotifyTake( pdTRUE, portMAX_DELAY ); + } + + /* Incremented to show the task is still running. */ + ulNotifyCycleCount++; + } +} +/*-----------------------------------------------------------*/ + +void xNotifyTaskFromISR( void ) +{ + static BaseType_t xCallCount = 0, xAPIToUse = 0; + const BaseType_t xCallInterval = pdMS_TO_TICKS( 50 ); + uint32_t ulPreviousValue; + const uint32_t ulUnexpectedValue = 0xff; + + /* Check the task notification demo tasks were actually created. */ + configASSERT( xTaskToNotify ); + + /* The task performs some tests before starting the timer that gives the + * notification from this interrupt. If the timer has not been created yet + * then the initial tests have not yet completed and the notification should + * not be sent. */ + if( xTimer != NULL ) + { + xCallCount++; + + if( xCallCount >= xCallInterval ) + { + /* It is time to 'give' the notification again. */ + xCallCount = 0; + + /* Test using both vTaskNotifyGiveFromISR(), xTaskNotifyFromISR() + * and xTaskNotifyAndQueryFromISR(). */ + switch( xAPIToUse ) + { + case 0: + vTaskNotifyGiveFromISR( xTaskToNotify, NULL ); + xAPIToUse++; + break; + + case 1: + xTaskNotifyFromISR( xTaskToNotify, 0, eIncrement, NULL ); + xAPIToUse++; + break; + + case 2: + ulPreviousValue = ulUnexpectedValue; + xTaskNotifyAndQueryFromISR( xTaskToNotify, 0, eIncrement, &ulPreviousValue, NULL ); + configASSERT( ulPreviousValue != ulUnexpectedValue ); + xAPIToUse = 0; + break; + + default: /* Should never get here!. */ + break; + } + + ulTimerNotificationsSent++; + } + } +} +/*-----------------------------------------------------------*/ + +/* This is called to check the created tasks are still running and have not + * detected any errors. */ +BaseType_t xAreTaskNotificationTasksStillRunning( void ) +{ + static uint32_t ulLastNotifyCycleCount = 0; + const uint32_t ulMaxSendReceiveDeviation = 5UL; + + /* Check the cycle count is still incrementing to ensure the task is still + * actually running. */ + if( ulLastNotifyCycleCount == ulNotifyCycleCount ) + { + xErrorStatus = pdFAIL; + } + else + { + ulLastNotifyCycleCount = ulNotifyCycleCount; + } + + /* Check the count of 'takes' from the software timer is keeping track with + * the amount of 'gives'. */ + if( ulTimerNotificationsSent > ulTimerNotificationsReceived ) + { + if( ( ulTimerNotificationsSent - ulTimerNotificationsReceived ) > ulMaxSendReceiveDeviation ) + { + xErrorStatus = pdFAIL; + } + } + + return xErrorStatus; +} +/*-----------------------------------------------------------*/ + +static UBaseType_t prvRand( void ) +{ + const size_t uxMultiplier = ( size_t ) 0x015a4e35, uxIncrement = ( size_t ) 1; + + /* Utility function to generate a pseudo random number. */ + uxNextRand = ( uxMultiplier * uxNextRand ) + uxIncrement; + return( ( uxNextRand >> 16 ) & ( ( size_t ) 0x7fff ) ); +} +/*-----------------------------------------------------------*/ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/TimerDemo.c b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/TimerDemo.c new file mode 100644 index 0000000..cee0ce6 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/TimerDemo.c @@ -0,0 +1,1173 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + + +/* + * Tests the behaviour of timers. Some timers are created before the scheduler + * is started, and some after. + */ + +/* Standard includes. */ +#include + +/* Scheduler include files. */ +#include "FreeRTOS.h" +#include "task.h" +#include "timers.h" + +/* Demo program include files. */ +#include "TimerDemo.h" + +#if ( configTIMER_TASK_PRIORITY < 1 ) + #error configTIMER_TASK_PRIORITY must be set to at least 1 for this test/demo to function correctly. +#endif + +#define tmrdemoDONT_BLOCK ( ( TickType_t ) 0 ) +#define tmrdemoONE_SHOT_TIMER_PERIOD ( xBasePeriod * ( TickType_t ) 3 ) +#define tmrdemoNUM_TIMER_RESETS ( ( uint8_t ) 10 ) + +#ifndef tmrTIMER_TEST_TASK_STACK_SIZE + #define tmrTIMER_TEST_TASK_STACK_SIZE configMINIMAL_STACK_SIZE +#endif + +/*-----------------------------------------------------------*/ + +/* The callback functions used by the timers. These each increment a counter + * to indicate which timer has expired. The auto-reload timers that are used by + * the test task (as opposed to being used from an ISR) all share the same + * prvAutoReloadTimerCallback() callback function, and use the ID of the + * pxExpiredTimer parameter passed into that function to know which counter to + * increment. The other timers all have their own unique callback function and + * simply increment their counters without using the callback function parameter. */ +static void prvAutoReloadTimerCallback( TimerHandle_t pxExpiredTimer ); +static void prvOneShotTimerCallback( TimerHandle_t pxExpiredTimer ); +static void prvTimerTestTask( void * pvParameters ); +static void prvISRAutoReloadTimerCallback( TimerHandle_t pxExpiredTimer ); +static void prvISROneShotTimerCallback( TimerHandle_t pxExpiredTimer ); + +/* The test functions used by the timer test task. These manipulate the auto + * reload and one-shot timers in various ways, then delay, then inspect the timers + * to ensure they have behaved as expected. */ +static void prvTest1_CreateTimersWithoutSchedulerRunning( void ); +static void prvTest2_CheckTaskAndTimersInitialState( void ); +static void prvTest3_CheckAutoReloadExpireRates( void ); +static void prvTest4_CheckAutoReloadTimersCanBeStopped( void ); +static void prvTest5_CheckBasicOneShotTimerBehaviour( void ); +static void prvTest6_CheckAutoReloadResetBehaviour( void ); +static void prvTest7_CheckBacklogBehaviour( void ); +static void prvResetStartConditionsForNextIteration( void ); + +/*-----------------------------------------------------------*/ + +/* Flag that will be latched to pdFAIL should any unexpected behaviour be + * detected in any of the demo tests. */ +static volatile BaseType_t xTestStatus = pdPASS; + +/* Flag indicating whether the testing includes the backlog demo. The backlog + * demo can be disruptive to other demos because the timer backlog is created by + * calling xTaskCatchUpTicks(). */ +static uint8_t ucIsBacklogDemoEnabled = ( uint8_t ) pdFALSE; + +/* Counter that is incremented on each cycle of a test. This is used to + * detect a stalled task - a test that is no longer running. */ +static volatile uint32_t ulLoopCounter = 0; + +/* A set of auto-reload timers - each of which use the same callback function. + * The callback function uses the timer ID to index into, and then increment, a + * counter in the ucAutoReloadTimerCounters[] array. The callback function stops + * xAutoReloadTimers[0] during its callback if ucIsStopNeededInTimerZeroCallback is + * pdTRUE. The auto-reload timers referenced from xAutoReloadTimers[] are used by + * the prvTimerTestTask task. */ +static TimerHandle_t xAutoReloadTimers[ configTIMER_QUEUE_LENGTH + 1 ] = { 0 }; +static uint8_t ucAutoReloadTimerCounters[ configTIMER_QUEUE_LENGTH + 1 ] = { 0 }; +static uint8_t ucIsStopNeededInTimerZeroCallback = ( uint8_t ) pdFALSE; + +/* The one-shot timer is configured to use a callback function that increments + * ucOneShotTimerCounter each time it gets called. */ +static TimerHandle_t xOneShotTimer = NULL; +static uint8_t ucOneShotTimerCounter = ( uint8_t ) 0; + +/* The ISR reload timer is controlled from the tick hook to exercise the timer + * API functions that can be used from an ISR. It is configured to increment + * ucISRReloadTimerCounter each time its callback function is executed. */ +static TimerHandle_t xISRAutoReloadTimer = NULL; +static uint8_t ucISRAutoReloadTimerCounter = ( uint8_t ) 0; + +/* The ISR one-shot timer is controlled from the tick hook to exercise the timer + * API functions that can be used from an ISR. It is configured to increment + * ucISRReloadTimerCounter each time its callback function is executed. */ +static TimerHandle_t xISROneShotTimer = NULL; +static uint8_t ucISROneShotTimerCounter = ( uint8_t ) 0; + +/* The period of all the timers are a multiple of the base period. The base + * period is configured by the parameter to vStartTimerDemoTask(). */ +static TickType_t xBasePeriod = 0; + +/*-----------------------------------------------------------*/ + +void vStartTimerDemoTask( TickType_t xBasePeriodIn ) +{ + /* Start with the timer and counter arrays clear - this is only necessary + * where the compiler does not clear them automatically on start up. */ + memset( ucAutoReloadTimerCounters, 0x00, sizeof( ucAutoReloadTimerCounters ) ); + memset( xAutoReloadTimers, 0x00, sizeof( xAutoReloadTimers ) ); + + /* Store the period from which all the timer periods will be generated from + * (multiples of). */ + xBasePeriod = xBasePeriodIn; + + /* Create a set of timers for use by this demo/test. */ + prvTest1_CreateTimersWithoutSchedulerRunning(); + + /* Create the task that will control and monitor the timers. This is + * created at a lower priority than the timer service task to ensure, as + * far as it is concerned, commands on timers are acted on immediately + * (sending a command to the timer service task will unblock the timer service + * task, which will then preempt this task). */ + if( xTestStatus != pdFAIL ) + { + xTaskCreate( prvTimerTestTask, "Tmr Tst", tmrTIMER_TEST_TASK_STACK_SIZE, NULL, configTIMER_TASK_PRIORITY - 1, NULL ); + } +} +/*-----------------------------------------------------------*/ + +void vTimerDemoIncludeBacklogTests( BaseType_t includeBacklogTests ) +{ + ucIsBacklogDemoEnabled = ( uint8_t ) includeBacklogTests; +} +/*-----------------------------------------------------------*/ + +static void prvTimerTestTask( void * pvParameters ) +{ + ( void ) pvParameters; + + /* Create a one-shot timer for use later on in this test. For test purposes it + * is created as an auto-reload timer then converted to a one-shot timer. */ + xOneShotTimer = xTimerCreate( "Oneshot Timer", /* Text name to facilitate debugging. The kernel does not use this itself. */ + tmrdemoONE_SHOT_TIMER_PERIOD, /* The period for the timer. */ + pdFALSE, /* Autoreload is false, so created as a one-shot timer. */ + ( void * ) 0, /* The timer identifier. Initialise to 0, then increment each time it is called. */ + prvOneShotTimerCallback ); /* The callback to be called when the timer expires. */ + + if( xOneShotTimer == NULL ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + /* Purely for test coverage purposes - change and query the reload mode to + * auto-reload then back to one-shot. */ + + /* Change timer to auto-reload. */ + vTimerSetReloadMode( xOneShotTimer, pdTRUE ); + + /* Timer should now be auto-reload. */ + configASSERT( uxTimerGetReloadMode( xOneShotTimer ) == pdTRUE ); + + /* Change timer to one-shot, which is what is needed for this test. */ + vTimerSetReloadMode( xOneShotTimer, pdFALSE ); + + /* Check change to one-shot was successful. */ + configASSERT( uxTimerGetReloadMode( xOneShotTimer ) == pdFALSE ); + + /* Ensure all the timers are in their expected initial state. This + * depends on the timer service task having a higher priority than this task. */ + prvTest2_CheckTaskAndTimersInitialState(); + + for( ; ; ) + { + /* Check the auto-reload timers expire at the expected/correct rates. */ + prvTest3_CheckAutoReloadExpireRates(); + + /* Check the auto-reload timers can be stopped correctly, and correctly + * report their state. */ + prvTest4_CheckAutoReloadTimersCanBeStopped(); + + /* Check the one-shot timer only calls its callback once after it has been + * started, and that it reports its state correctly. */ + prvTest5_CheckBasicOneShotTimerBehaviour(); + + /* Check timer reset behaviour. */ + prvTest6_CheckAutoReloadResetBehaviour(); + + /* Check timer behaviour when the timer task gets behind in its work. */ + if( ucIsBacklogDemoEnabled == ( uint8_t ) pdTRUE ) + { + prvTest7_CheckBacklogBehaviour(); + } + + /* Start the timers again to restart all the tests over again. */ + prvResetStartConditionsForNextIteration(); + } +} +/*-----------------------------------------------------------*/ + +/* This is called to check that the created task is still running and has not + * detected any errors. */ +BaseType_t xAreTimerDemoTasksStillRunning( TickType_t xCycleFrequency ) +{ + static uint32_t ulLastLoopCounter = 0UL; + TickType_t xMaxBlockTimeUsedByTheseTests, xLoopCounterIncrementTimeMax; + static TickType_t xIterationsWithoutCounterIncrement = ( TickType_t ) 0, xLastCycleFrequency; + + if( xLastCycleFrequency != xCycleFrequency ) + { + /* The cycle frequency has probably become much faster due to an error + * elsewhere. Start counting Iterations again. */ + xIterationsWithoutCounterIncrement = ( TickType_t ) 0; + xLastCycleFrequency = xCycleFrequency; + } + + /* Calculate the maximum number of times that it is permissible for this + * function to be called without ulLoopCounter being incremented. This is + * necessary because the tests in this file block for extended periods, and the + * block period might be longer than the time between calls to this function. */ + xMaxBlockTimeUsedByTheseTests = ( ( TickType_t ) configTIMER_QUEUE_LENGTH ) * xBasePeriod; + xLoopCounterIncrementTimeMax = ( xMaxBlockTimeUsedByTheseTests / xCycleFrequency ) + 1; + + /* If the demo task is still running then the loop counter is expected to + * have incremented every xLoopCounterIncrementTimeMax calls. */ + if( ulLastLoopCounter == ulLoopCounter ) + { + xIterationsWithoutCounterIncrement++; + + if( xIterationsWithoutCounterIncrement > xLoopCounterIncrementTimeMax ) + { + /* The tests appear to be no longer running (stalled). */ + xTestStatus = pdFAIL; + } + } + else + { + /* ulLoopCounter changed, so the count of times this function was called + * without a change can be reset to zero. */ + xIterationsWithoutCounterIncrement = ( TickType_t ) 0; + } + + ulLastLoopCounter = ulLoopCounter; + + /* Errors detected in the task itself will have latched xTestStatus + * to pdFAIL. */ + + return xTestStatus; +} +/*-----------------------------------------------------------*/ + +static void prvTest1_CreateTimersWithoutSchedulerRunning( void ) +{ + TickType_t xTimer; + + for( xTimer = 0; xTimer < configTIMER_QUEUE_LENGTH; xTimer++ ) + { + /* As the timer queue is not yet full, it should be possible to both + * create and start a timer. These timers are being started before the + * scheduler has been started, so their block times should get set to zero + * within the timer API itself. */ + xAutoReloadTimers[ xTimer ] = xTimerCreate( "FR Timer", /* Text name to facilitate debugging. The kernel does not use this itself. */ + ( ( xTimer + ( TickType_t ) 1 ) * xBasePeriod ), /* The period for the timer. The plus 1 ensures a period of zero is not specified. */ + pdTRUE, /* Auto-reload is set to true. */ + ( void * ) xTimer, /* An identifier for the timer as all the auto-reload timers use the same callback. */ + prvAutoReloadTimerCallback ); /* The callback to be called when the timer expires. */ + + if( xAutoReloadTimers[ xTimer ] == NULL ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + else + { + configASSERT( strcmp( pcTimerGetName( xAutoReloadTimers[ xTimer ] ), "FR Timer" ) == 0 ); + + /* The scheduler has not yet started, so the block period of + * portMAX_DELAY should just get set to zero in xTimerStart(). Also, + * the timer queue is not yet full so xTimerStart() should return + * pdPASS. */ + if( xTimerStart( xAutoReloadTimers[ xTimer ], portMAX_DELAY ) != pdPASS ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + } + } + + /* The timers queue should now be full, so it should be possible to create + * another timer, but not possible to start it (the timer queue will not get + * drained until the scheduler has been started. */ + xAutoReloadTimers[ configTIMER_QUEUE_LENGTH ] = xTimerCreate( "FR Timer", /* Text name to facilitate debugging. The kernel does not use this itself. */ + ( configTIMER_QUEUE_LENGTH * xBasePeriod ), /* The period for the timer. */ + pdTRUE, /* Auto-reload is set to true. */ + ( void * ) xTimer, /* An identifier for the timer as all the auto-reload timers use the same callback. */ + prvAutoReloadTimerCallback ); /* The callback executed when the timer expires. */ + + if( xAutoReloadTimers[ configTIMER_QUEUE_LENGTH ] == NULL ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + else + { + if( xTimerStart( xAutoReloadTimers[ xTimer ], portMAX_DELAY ) == pdPASS ) + { + /* This time it would not be expected that the timer could be + * started at this point. */ + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + } + + /* Create the timers that are used from the tick interrupt to test the timer + * API functions that can be called from an ISR. */ + xISRAutoReloadTimer = xTimerCreate( "ISR AR", /* The text name given to the timer. */ + 0xffff, /* The timer is not given a period yet - this will be done from the tick hook, but a period of 0 is invalid. */ + pdTRUE, /* This is an auto-reload timer. */ + ( void * ) NULL, /* The identifier is not required. */ + prvISRAutoReloadTimerCallback ); /* The callback that is executed when the timer expires. */ + + xISROneShotTimer = xTimerCreate( "ISR OS", /* The text name given to the timer. */ + 0xffff, /* The timer is not given a period yet - this will be done from the tick hook, but a period of 0 is invalid. */ + pdFALSE, /* This is a one-shot timer. */ + ( void * ) NULL, /* The identifier is not required. */ + prvISROneShotTimerCallback ); /* The callback that is executed when the timer expires. */ + + if( ( xISRAutoReloadTimer == NULL ) || ( xISROneShotTimer == NULL ) ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } +} +/*-----------------------------------------------------------*/ + +static void prvTest2_CheckTaskAndTimersInitialState( void ) +{ + uint8_t ucTimer; + + /* Ensure all the timers are in their expected initial state. This depends + * on the timer service task having a higher priority than this task. + * + * auto-reload timers 0 to ( configTIMER_QUEUE_LENGTH - 1 ) should now be active, + * and auto-reload timer configTIMER_QUEUE_LENGTH should not yet be active (it + * could not be started prior to the scheduler being started when it was + * created). */ + for( ucTimer = 0; ucTimer < ( uint8_t ) configTIMER_QUEUE_LENGTH; ucTimer++ ) + { + if( xTimerIsTimerActive( xAutoReloadTimers[ ucTimer ] ) == pdFALSE ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + } + + if( xTimerIsTimerActive( xAutoReloadTimers[ configTIMER_QUEUE_LENGTH ] ) != pdFALSE ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } +} +/*-----------------------------------------------------------*/ + +static void prvTest3_CheckAutoReloadExpireRates( void ) +{ + uint8_t ucMaxAllowableValue, ucMinAllowableValue, ucTimer; + TickType_t xBlockPeriod, xTimerPeriod, xExpectedNumber; + UBaseType_t uxOriginalPriority; + + /* Check the auto-reload timers expire at the expected rates. Do this at a + * high priority for maximum accuracy. This is ok as most of the time is spent + * in the Blocked state. */ + uxOriginalPriority = uxTaskPriorityGet( NULL ); + vTaskPrioritySet( NULL, ( configMAX_PRIORITIES - 1 ) ); + + /* Delaying for configTIMER_QUEUE_LENGTH * xBasePeriod ticks should allow + * all the auto-reload timers to expire at least once. */ + xBlockPeriod = ( ( TickType_t ) configTIMER_QUEUE_LENGTH ) * xBasePeriod; + vTaskDelay( xBlockPeriod ); + + /* Check that all the auto-reload timers have called their callback + * function the expected number of times. */ + for( ucTimer = 0; ucTimer < ( uint8_t ) configTIMER_QUEUE_LENGTH; ucTimer++ ) + { + /* The expected number of expires is equal to the block period divided + * by the timer period. */ + xTimerPeriod = ( ( ( TickType_t ) ucTimer + ( TickType_t ) 1 ) * xBasePeriod ); + xExpectedNumber = xBlockPeriod / xTimerPeriod; + + ucMaxAllowableValue = ( ( uint8_t ) xExpectedNumber ); + ucMinAllowableValue = ( uint8_t ) ( ( uint8_t ) xExpectedNumber - ( uint8_t ) 1 ); /* Weird casting to try and please all compilers. */ + + if( ( ucAutoReloadTimerCounters[ ucTimer ] < ucMinAllowableValue ) || + ( ucAutoReloadTimerCounters[ ucTimer ] > ucMaxAllowableValue ) + ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + } + + /* Return to the original priority. */ + vTaskPrioritySet( NULL, uxOriginalPriority ); + + if( xTestStatus == pdPASS ) + { + /* No errors have been reported so increment the loop counter so the + * check task knows this task is still running. */ + ulLoopCounter++; + } +} +/*-----------------------------------------------------------*/ + +static void prvTest4_CheckAutoReloadTimersCanBeStopped( void ) +{ + uint8_t ucTimer; + + /* Check the auto-reload timers can be stopped correctly, and correctly + * report their state. */ + + /* Stop all the active timers. */ + for( ucTimer = 0; ucTimer < ( uint8_t ) configTIMER_QUEUE_LENGTH; ucTimer++ ) + { + /* The timer has not been stopped yet! */ + if( xTimerIsTimerActive( xAutoReloadTimers[ ucTimer ] ) == pdFALSE ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + /* Now stop the timer. This will appear to happen immediately to + * this task because this task is running at a priority below the + * timer service task. */ + xTimerStop( xAutoReloadTimers[ ucTimer ], tmrdemoDONT_BLOCK ); + + /* The timer should now be inactive. */ + if( xTimerIsTimerActive( xAutoReloadTimers[ ucTimer ] ) != pdFALSE ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + } + + taskENTER_CRITICAL(); + { + /* The timer in array position configTIMER_QUEUE_LENGTH should not + * be active. The critical section is used to ensure the timer does + * not call its callback between the next line running and the array + * being cleared back to zero, as that would mask an error condition. */ + if( ucAutoReloadTimerCounters[ configTIMER_QUEUE_LENGTH ] != ( uint8_t ) 0 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + /* Clear the timer callback count. */ + memset( ( void * ) ucAutoReloadTimerCounters, 0, sizeof( ucAutoReloadTimerCounters ) ); + } + taskEXIT_CRITICAL(); + + /* The timers are now all inactive, so this time, after delaying, none + * of the callback counters should have incremented. */ + vTaskDelay( ( ( TickType_t ) configTIMER_QUEUE_LENGTH ) * xBasePeriod ); + + for( ucTimer = 0; ucTimer < ( uint8_t ) configTIMER_QUEUE_LENGTH; ucTimer++ ) + { + if( ucAutoReloadTimerCounters[ ucTimer ] != ( uint8_t ) 0 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + } + + if( xTestStatus == pdPASS ) + { + /* No errors have been reported so increment the loop counter so + * the check task knows this task is still running. */ + ulLoopCounter++; + } +} +/*-----------------------------------------------------------*/ + +static void prvTest5_CheckBasicOneShotTimerBehaviour( void ) +{ + /* Check the one-shot timer only calls its callback once after it has been + * started, and that it reports its state correctly. */ + + /* The one-shot timer should not be active yet. */ + if( xTimerIsTimerActive( xOneShotTimer ) != pdFALSE ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + if( ucOneShotTimerCounter != ( uint8_t ) 0 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + /* Start the one-shot timer and check that it reports its state correctly. */ + xTimerStart( xOneShotTimer, tmrdemoDONT_BLOCK ); + + if( xTimerIsTimerActive( xOneShotTimer ) == pdFALSE ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + /* Delay for three times as long as the one-shot timer period, then check + * to ensure it has only called its callback once, and is now not in the + * active state. */ + vTaskDelay( tmrdemoONE_SHOT_TIMER_PERIOD * ( TickType_t ) 3 ); + + if( xTimerIsTimerActive( xOneShotTimer ) != pdFALSE ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + if( ucOneShotTimerCounter != ( uint8_t ) 1 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + else + { + /* Reset the one-shot timer callback count. */ + ucOneShotTimerCounter = ( uint8_t ) 0; + } + + if( xTestStatus == pdPASS ) + { + /* No errors have been reported so increment the loop counter so the + * check task knows this task is still running. */ + ulLoopCounter++; + } +} +/*-----------------------------------------------------------*/ + +static void prvTest6_CheckAutoReloadResetBehaviour( void ) +{ + uint8_t ucTimer; + + /* Check timer reset behaviour. */ + + /* Restart the one-shot timer and check it reports its status correctly. */ + xTimerStart( xOneShotTimer, tmrdemoDONT_BLOCK ); + + if( xTimerIsTimerActive( xOneShotTimer ) == pdFALSE ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + /* Restart one of the auto-reload timers and check that it reports its + * status correctly. */ + xTimerStart( xAutoReloadTimers[ configTIMER_QUEUE_LENGTH - 1 ], tmrdemoDONT_BLOCK ); + + if( xTimerIsTimerActive( xAutoReloadTimers[ configTIMER_QUEUE_LENGTH - 1 ] ) == pdFALSE ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + for( ucTimer = 0; ucTimer < tmrdemoNUM_TIMER_RESETS; ucTimer++ ) + { + /* Delay for half as long as the one-shot timer period, then reset it. + * It should never expire while this is done, so its callback count should + * never increment. */ + vTaskDelay( tmrdemoONE_SHOT_TIMER_PERIOD / 2 ); + + /* Check both running timers are still active, but have not called their + * callback functions. */ + if( xTimerIsTimerActive( xOneShotTimer ) == pdFALSE ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + if( ucOneShotTimerCounter != ( uint8_t ) 0 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + if( xTimerIsTimerActive( xAutoReloadTimers[ configTIMER_QUEUE_LENGTH - 1 ] ) == pdFALSE ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + if( ucAutoReloadTimerCounters[ configTIMER_QUEUE_LENGTH - 1 ] != ( uint8_t ) 0 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + /* Reset both running timers. */ + xTimerReset( xOneShotTimer, tmrdemoDONT_BLOCK ); + xTimerReset( xAutoReloadTimers[ configTIMER_QUEUE_LENGTH - 1 ], tmrdemoDONT_BLOCK ); + + if( xTestStatus == pdPASS ) + { + /* No errors have been reported so increment the loop counter so + * the check task knows this task is still running. */ + ulLoopCounter++; + } + } + + /* Finally delay long enough for both running timers to expire. */ + vTaskDelay( ( ( TickType_t ) configTIMER_QUEUE_LENGTH ) * xBasePeriod ); + + /* The timers were not reset during the above delay period so should now + * both have called their callback functions. */ + if( ucOneShotTimerCounter != ( uint8_t ) 1 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + if( ucAutoReloadTimerCounters[ configTIMER_QUEUE_LENGTH - 1 ] == 0 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + /* The one-shot timer should no longer be active, while the auto-reload + * timer should still be active. */ + if( xTimerIsTimerActive( xAutoReloadTimers[ configTIMER_QUEUE_LENGTH - 1 ] ) == pdFALSE ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + if( xTimerIsTimerActive( xOneShotTimer ) == pdTRUE ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + /* Stop the auto-reload timer again. */ + xTimerStop( xAutoReloadTimers[ configTIMER_QUEUE_LENGTH - 1 ], tmrdemoDONT_BLOCK ); + + if( xTimerIsTimerActive( xAutoReloadTimers[ configTIMER_QUEUE_LENGTH - 1 ] ) != pdFALSE ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + /* Clear the timer callback counts, ready for another iteration of these + * tests. */ + ucAutoReloadTimerCounters[ configTIMER_QUEUE_LENGTH - 1 ] = ( uint8_t ) 0; + ucOneShotTimerCounter = ( uint8_t ) 0; + + if( xTestStatus == pdPASS ) + { + /* No errors have been reported so increment the loop counter so the check + * task knows this task is still running. */ + ulLoopCounter++; + } +} +/*-----------------------------------------------------------*/ + +static void prvTest7_CheckBacklogBehaviour( void ) +{ + /* Use the first auto-reload timer to test stopping a timer from a + * backlogged callback. */ + + /* The timer has not been started yet! */ + if( xTimerIsTimerActive( xAutoReloadTimers[ 0 ] ) != pdFALSE ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + /* Prompt the callback function to stop the timer. */ + ucIsStopNeededInTimerZeroCallback = ( uint8_t ) pdTRUE; + + /* Now start the timer. This will appear to happen immediately to + * this task because this task is running at a priority below the timer + * service task. Use a timer period of one tick so the call to + * xTaskCatchUpTicks() below has minimal impact on other tests that might + * be running. */ +#define tmrdemoBACKLOG_TIMER_PERIOD ( ( TickType_t ) 1 ) + xTimerChangePeriod( xAutoReloadTimers[ 0 ], tmrdemoBACKLOG_TIMER_PERIOD, tmrdemoDONT_BLOCK ); + + /* The timer should now be active. */ + if( xTimerIsTimerActive( xAutoReloadTimers[ 0 ] ) == pdFALSE ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + /* Arrange for the callback to execute late enough that it will execute + * twice, back-to-back. The timer must handle the stop request properly + * in spite of the backlog of callbacks. */ +#define tmrdemoEXPECTED_BACKLOG_EXPIRES ( ( TickType_t ) 2 ) + xTaskCatchUpTicks( tmrdemoBACKLOG_TIMER_PERIOD * tmrdemoEXPECTED_BACKLOG_EXPIRES ); + + /* The timer should now be inactive. */ + if( xTimerIsTimerActive( xAutoReloadTimers[ 0 ] ) != pdFALSE ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + /* Restore the standard timer period, and leave the timer inactive. */ + xTimerChangePeriod( xAutoReloadTimers[ 0 ], xBasePeriod, tmrdemoDONT_BLOCK ); + xTimerStop( xAutoReloadTimers[ 0 ], tmrdemoDONT_BLOCK ); + + /* Clear the reload count for the timer used in this test. */ + ucAutoReloadTimerCounters[ 0 ] = ( uint8_t ) 0; + + if( xTestStatus == pdPASS ) + { + /* No errors have been reported so increment the loop counter so the check + * task knows this task is still running. */ + ulLoopCounter++; + } +} +/*-----------------------------------------------------------*/ + +static void prvResetStartConditionsForNextIteration( void ) +{ + uint8_t ucTimer; + + /* Start the timers again to start all the tests over again. */ + + /* Start the timers again. */ + for( ucTimer = 0; ucTimer < ( uint8_t ) configTIMER_QUEUE_LENGTH; ucTimer++ ) + { + /* The timer has not been started yet! */ + if( xTimerIsTimerActive( xAutoReloadTimers[ ucTimer ] ) != pdFALSE ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + /* Now start the timer. This will appear to happen immediately to + * this task because this task is running at a priority below the timer + * service task. */ + xTimerStart( xAutoReloadTimers[ ucTimer ], tmrdemoDONT_BLOCK ); + + /* The timer should now be active. */ + if( xTimerIsTimerActive( xAutoReloadTimers[ ucTimer ] ) == pdFALSE ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + } + + if( xTestStatus == pdPASS ) + { + /* No errors have been reported so increment the loop counter so the + * check task knows this task is still running. */ + ulLoopCounter++; + } +} +/*-----------------------------------------------------------*/ + +void vTimerPeriodicISRTests( void ) +{ + static TickType_t uxTick = ( TickType_t ) -1; + + #if ( configTIMER_TASK_PRIORITY != ( configMAX_PRIORITIES - 1 ) ) + + /* The timer service task is not the highest priority task, so it cannot + * be assumed that timings will be exact. Timers should never call their + * callback before their expiry time, but a margin is permissible for calling + * their callback after their expiry time. If exact timing is required then + * configTIMER_TASK_PRIORITY must be set to ensure the timer service task + * is the highest priority task in the system. + * + * This function is called from the tick hook. The tick hook is called + * even when the scheduler is suspended. Therefore it is possible that the + * uxTick count maintained in this function is temporarily ahead of the tick + * count maintained by the kernel. When this is the case a message posted from + * this function will assume a time stamp in advance of the real time stamp, + * which can result in a timer being processed before this function expects it + * to. For example, if the kernel's tick count was 100, and uxTick was 102, + * then this function will not expect the timer to have expired until the + * kernel's tick count is (102 + xBasePeriod), whereas in reality the timer + * will expire when the kernel's tick count is (100 + xBasePeriod). For this + * reason xMargin is used as an allowable margin for premature timer expires + * as well as late timer expires. */ + #ifdef _WINDOWS_ + /* Windows is not real real time. */ + const TickType_t xMargin = 20; + #else + const TickType_t xMargin = 6; + #endif /* _WINDOWS_ */ + #else + #ifdef _WINDOWS_ + /* Windows is not real real time. */ + const TickType_t xMargin = 20; + #else + const TickType_t xMargin = 4; + #endif /* _WINDOWS_ */ + #endif /* if ( configTIMER_TASK_PRIORITY != ( configMAX_PRIORITIES - 1 ) ) */ + + + uxTick++; + + if( uxTick == 0 ) + { + /* The timers will have been created, but not started. Start them now + * by setting their period. */ + ucISRAutoReloadTimerCounter = 0; + ucISROneShotTimerCounter = 0; + + /* It is possible that the timer task has not yet made room in the + * timer queue. If the timers cannot be started then reset uxTick so + * another attempt is made later. */ + uxTick = ( TickType_t ) -1; + + /* Try starting first timer. */ + if( xTimerChangePeriodFromISR( xISRAutoReloadTimer, xBasePeriod, NULL ) == pdPASS ) + { + /* First timer was started, try starting the second timer. */ + if( xTimerChangePeriodFromISR( xISROneShotTimer, xBasePeriod, NULL ) == pdPASS ) + { + /* Both timers were started, so set the uxTick back to its + * proper value. */ + uxTick = 0; + } + else + { + /* Second timer could not be started, so stop the first one + * again. */ + xTimerStopFromISR( xISRAutoReloadTimer, NULL ); + } + } + } + else if( uxTick == ( xBasePeriod - xMargin ) ) + { + /* Neither timer should have expired yet. */ + if( ( ucISRAutoReloadTimerCounter != 0 ) || ( ucISROneShotTimerCounter != 0 ) ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + } + else if( uxTick == ( xBasePeriod + xMargin ) ) + { + /* Both timers should now have expired once. The auto-reload timer will + * still be active, but the one-shot timer should now have stopped. */ + if( ( ucISRAutoReloadTimerCounter != 1 ) || ( ucISROneShotTimerCounter != 1 ) ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + } + else if( uxTick == ( ( 2 * xBasePeriod ) - xMargin ) ) + { + /* The auto-reload timer will still be active, but the one-shot timer + * should now have stopped - however, at this time neither of the timers + * should have expired again since the last test. */ + if( ( ucISRAutoReloadTimerCounter != 1 ) || ( ucISROneShotTimerCounter != 1 ) ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + } + else if( uxTick == ( ( 2 * xBasePeriod ) + xMargin ) ) + { + /* The auto-reload timer will still be active, but the one-shot timer + * should now have stopped. At this time the auto-reload timer should have + * expired again, but the one-shot timer count should not have changed. */ + if( ucISRAutoReloadTimerCounter != 2 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + if( ucISROneShotTimerCounter != 1 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + } + else if( uxTick == ( ( 2 * xBasePeriod ) + ( xBasePeriod >> ( TickType_t ) 2U ) ) ) + { + /* The auto-reload timer will still be active, but the one-shot timer + * should now have stopped. Again though, at this time, neither timer call + * back should have been called since the last test. */ + if( ucISRAutoReloadTimerCounter != 2 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + if( ucISROneShotTimerCounter != 1 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + } + else if( uxTick == ( 3 * xBasePeriod ) ) + { + /* Start the one-shot timer again. */ + xTimerStartFromISR( xISROneShotTimer, NULL ); + } + else if( uxTick == ( ( 3 * xBasePeriod ) + xMargin ) ) + { + /* The auto-reload timer and one-shot timer will be active. At + * this time the auto-reload timer should have expired again, but the one + * shot timer count should not have changed yet. */ + if( ucISRAutoReloadTimerCounter != 3 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + if( ucISROneShotTimerCounter != 1 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + /* Now stop the auto-reload timer. The one-shot timer was started + * a few ticks ago. */ + xTimerStopFromISR( xISRAutoReloadTimer, NULL ); + } + else if( uxTick == ( 4 * ( xBasePeriod - xMargin ) ) ) + { + /* The auto-reload timer is now stopped, and the one-shot timer is + * active, but at this time neither timer should have expired since the + * last test. */ + if( ucISRAutoReloadTimerCounter != 3 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + if( ucISROneShotTimerCounter != 1 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + } + else if( uxTick == ( ( 4 * xBasePeriod ) + xMargin ) ) + { + /* The auto-reload timer is now stopped, and the one-shot timer is + * active. The one-shot timer should have expired again, but the auto + * reload timer should not have executed its callback. */ + if( ucISRAutoReloadTimerCounter != 3 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + if( ucISROneShotTimerCounter != 2 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + } + else if( uxTick == ( 8 * xBasePeriod ) ) + { + /* The auto-reload timer is now stopped, and the one-shot timer has + * already expired and then stopped itself. Both callback counters should + * not have incremented since the last test. */ + if( ucISRAutoReloadTimerCounter != 3 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + if( ucISROneShotTimerCounter != 2 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + /* Now reset the one-shot timer. */ + xTimerResetFromISR( xISROneShotTimer, NULL ); + } + else if( uxTick == ( ( 9 * xBasePeriod ) - xMargin ) ) + { + /* Only the one-shot timer should be running, but it should not have + * expired since the last test. Check the callback counters have not + * incremented, then reset the one-shot timer again. */ + if( ucISRAutoReloadTimerCounter != 3 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + if( ucISROneShotTimerCounter != 2 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + xTimerResetFromISR( xISROneShotTimer, NULL ); + } + else if( uxTick == ( ( 10 * xBasePeriod ) - ( 2 * xMargin ) ) ) + { + /* Only the one-shot timer should be running, but it should not have + * expired since the last test. Check the callback counters have not + * incremented, then reset the one-shot timer again. */ + if( ucISRAutoReloadTimerCounter != 3 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + if( ucISROneShotTimerCounter != 2 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + xTimerResetFromISR( xISROneShotTimer, NULL ); + } + else if( uxTick == ( ( 11 * xBasePeriod ) - ( 3 * xMargin ) ) ) + { + /* Only the one-shot timer should be running, but it should not have + * expired since the last test. Check the callback counters have not + * incremented, then reset the one-shot timer once again. */ + if( ucISRAutoReloadTimerCounter != 3 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + if( ucISROneShotTimerCounter != 2 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + xTimerResetFromISR( xISROneShotTimer, NULL ); + } + else if( uxTick == ( ( 12 * xBasePeriod ) - ( 2 * xMargin ) ) ) + { + /* Only the one-shot timer should have been running and this time it + * should have expired. Check its callback count has been incremented. + * The auto-reload timer is still not running so should still have the same + * count value. This time the one-shot timer is not reset so should not + * restart from its expiry period again. */ + if( ucISRAutoReloadTimerCounter != 3 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + if( ucISROneShotTimerCounter != 3 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + } + else if( uxTick == ( 15 * xBasePeriod ) ) + { + /* Neither timer should be running now. Check neither callback count + * has incremented, then go back to the start to run these tests all + * over again. */ + if( ucISRAutoReloadTimerCounter != 3 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + if( ucISROneShotTimerCounter != 3 ) + { + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } + + uxTick = ( TickType_t ) -1; + } +} +/*-----------------------------------------------------------*/ + +/*** Timer callback functions are defined below here. ***/ + +static void prvAutoReloadTimerCallback( TimerHandle_t pxExpiredTimer ) +{ + size_t uxTimerID; + + uxTimerID = ( size_t ) pvTimerGetTimerID( pxExpiredTimer ); + + if( uxTimerID <= ( configTIMER_QUEUE_LENGTH + 1 ) ) + { + ( ucAutoReloadTimerCounters[ uxTimerID ] )++; + + /* Stop timer ID 0 if requested. */ + if( ( uxTimerID == ( size_t ) 0 ) && ( ucIsStopNeededInTimerZeroCallback == ( uint8_t ) pdTRUE ) ) + { + xTimerStop( pxExpiredTimer, tmrdemoDONT_BLOCK ); + ucIsStopNeededInTimerZeroCallback = ( uint8_t ) pdFALSE; + } + } + else + { + /* The timer ID appears to be unexpected (invalid). */ + xTestStatus = pdFAIL; + configASSERT( xTestStatus ); + } +} +/*-----------------------------------------------------------*/ + +static void prvOneShotTimerCallback( TimerHandle_t pxExpiredTimer ) +{ +/* A count is kept of the number of times this callback function is executed. + * The count is stored as the timer's ID. This is only done to test the + * vTimerSetTimerID() function. */ + static size_t uxCallCount = 0; + size_t uxLastCallCount; + + /* Obtain the timer's ID, which should be a count of the number of times + * this callback function has been executed. */ + uxLastCallCount = ( size_t ) pvTimerGetTimerID( pxExpiredTimer ); + configASSERT( uxLastCallCount == uxCallCount ); + + /* Increment the call count, then save it back as the timer's ID. This is + * only done to test the vTimerSetTimerID() API function. */ + uxLastCallCount++; + vTimerSetTimerID( pxExpiredTimer, ( void * ) uxLastCallCount ); + uxCallCount++; + + ucOneShotTimerCounter++; +} +/*-----------------------------------------------------------*/ + +static void prvISRAutoReloadTimerCallback( TimerHandle_t pxExpiredTimer ) +{ + /* The parameter is not used in this case as only one timer uses this + * callback function. */ + ( void ) pxExpiredTimer; + + ucISRAutoReloadTimerCounter++; +} +/*-----------------------------------------------------------*/ + +static void prvISROneShotTimerCallback( TimerHandle_t pxExpiredTimer ) +{ + /* The parameter is not used in this case as only one timer uses this + * callback function. */ + ( void ) pxExpiredTimer; + + ucISROneShotTimerCounter++; +} +/*-----------------------------------------------------------*/ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/blocktim.c b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/blocktim.c new file mode 100644 index 0000000..be47070 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/blocktim.c @@ -0,0 +1,598 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +/* + * This file contains some test scenarios that ensure tasks do not exit queue + * send or receive functions prematurely. A description of the tests is + * included within the code. + */ + +/* Kernel includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" + +/* Demo includes. */ +#include "blocktim.h" + +/* Task priorities and stack sizes. Allow these to be overridden. */ +#ifndef bktPRIMARY_PRIORITY + #define bktPRIMARY_PRIORITY ( configMAX_PRIORITIES - 3 ) +#endif + +#ifndef bktSECONDARY_PRIORITY + #define bktSECONDARY_PRIORITY ( configMAX_PRIORITIES - 4 ) +#endif + +#ifndef bktBLOCK_TIME_TASK_STACK_SIZE + #define bktBLOCK_TIME_TASK_STACK_SIZE configMINIMAL_STACK_SIZE +#endif + +/* Task behaviour. */ +#define bktQUEUE_LENGTH ( 5 ) +#define bktSHORT_WAIT pdMS_TO_TICKS( ( TickType_t ) 20 ) +#define bktPRIMARY_BLOCK_TIME ( 10 ) +#define bktALLOWABLE_MARGIN ( 15 ) +#define bktTIME_TO_BLOCK ( 175 ) +#define bktDONT_BLOCK ( ( TickType_t ) 0 ) +#define bktRUN_INDICATOR ( ( UBaseType_t ) 0x55 ) + +/* In case the demo does not have software timers enabled, as this file uses + * the configTIMER_TASK_PRIORITY setting. */ +#ifndef configTIMER_TASK_PRIORITY + #define configTIMER_TASK_PRIORITY ( configMAX_PRIORITIES - 1 ) +#endif + +/*-----------------------------------------------------------*/ + +/* + * The two test tasks. Their behaviour is commented within the functions. + */ +static void vPrimaryBlockTimeTestTask( void * pvParameters ); +static void vSecondaryBlockTimeTestTask( void * pvParameters ); + +/* + * Very basic tests to verify the block times are as expected. + */ +static void prvBasicDelayTests( void ); + +/*-----------------------------------------------------------*/ + +/* The queue on which the tasks block. */ +static QueueHandle_t xTestQueue; + +/* Handle to the secondary task is required by the primary task for calls + * to vTaskSuspend/Resume(). */ +static TaskHandle_t xSecondary; + +/* Used to ensure that tasks are still executing without error. */ +static volatile BaseType_t xPrimaryCycles = 0, xSecondaryCycles = 0; +static volatile BaseType_t xErrorOccurred = pdFALSE; + +/* Provides a simple mechanism for the primary task to know when the + * secondary task has executed. */ +static volatile UBaseType_t xRunIndicator; + +/*-----------------------------------------------------------*/ + +void vCreateBlockTimeTasks( void ) +{ + /* Create the queue on which the two tasks block. */ + xTestQueue = xQueueCreate( bktQUEUE_LENGTH, sizeof( BaseType_t ) ); + + if( xTestQueue != NULL ) + { + /* vQueueAddToRegistry() adds the queue to the queue registry, if one + * is in use. The queue registry is provided as a means for kernel aware + * debuggers to locate queues and has no purpose if a kernel aware + * debugger is not being used. The call to vQueueAddToRegistry() will be + * removed by the pre-processor if configQUEUE_REGISTRY_SIZE is not + * defined or is defined to be less than 1. */ + vQueueAddToRegistry( xTestQueue, "Block_Time_Queue" ); + + /* Create the two test tasks. */ + xTaskCreate( vPrimaryBlockTimeTestTask, "BTest1", bktBLOCK_TIME_TASK_STACK_SIZE, NULL, bktPRIMARY_PRIORITY, NULL ); + xTaskCreate( vSecondaryBlockTimeTestTask, "BTest2", bktBLOCK_TIME_TASK_STACK_SIZE, NULL, bktSECONDARY_PRIORITY, &xSecondary ); + } +} +/*-----------------------------------------------------------*/ + +static void vPrimaryBlockTimeTestTask( void * pvParameters ) +{ + BaseType_t xItem, xData; + TickType_t xTimeWhenBlocking; + TickType_t xTimeToBlock, xBlockedTime; + + ( void ) pvParameters; + + for( ; ; ) + { + /********************************************************************* + * Test 0 + * + * Basic vTaskDelay() and vTaskDelayUntil() tests. */ + prvBasicDelayTests(); + + /********************************************************************* + * Test 1 + * + * Simple block time wakeup test on queue receives. */ + for( xItem = 0; xItem < bktQUEUE_LENGTH; xItem++ ) + { + /* The queue is empty. Attempt to read from the queue using a block + * time. When we wake, ensure the delta in time is as expected. */ + xTimeToBlock = ( TickType_t ) ( bktPRIMARY_BLOCK_TIME << xItem ); + + xTimeWhenBlocking = xTaskGetTickCount(); + + /* We should unblock after xTimeToBlock having not received + * anything on the queue. */ + if( xQueueReceive( xTestQueue, &xData, xTimeToBlock ) != errQUEUE_EMPTY ) + { + xErrorOccurred = pdTRUE; + } + + /* How long were we blocked for? */ + xBlockedTime = xTaskGetTickCount() - xTimeWhenBlocking; + + if( xBlockedTime < xTimeToBlock ) + { + /* Should not have blocked for less than we requested. */ + xErrorOccurred = pdTRUE; + } + + if( xBlockedTime > ( xTimeToBlock + bktALLOWABLE_MARGIN ) ) + { + /* Should not have blocked for longer than we requested, + * although we would not necessarily run as soon as we were + * unblocked so a margin is allowed. */ + xErrorOccurred = pdTRUE; + } + } + + /********************************************************************* + * Test 2 + * + * Simple block time wakeup test on queue sends. + * + * First fill the queue. It should be empty so all sends should pass. */ + for( xItem = 0; xItem < bktQUEUE_LENGTH; xItem++ ) + { + if( xQueueSend( xTestQueue, &xItem, bktDONT_BLOCK ) != pdPASS ) + { + xErrorOccurred = pdTRUE; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + } + + for( xItem = 0; xItem < bktQUEUE_LENGTH; xItem++ ) + { + /* The queue is full. Attempt to write to the queue using a block + * time. When we wake, ensure the delta in time is as expected. */ + xTimeToBlock = ( TickType_t ) ( bktPRIMARY_BLOCK_TIME << xItem ); + + xTimeWhenBlocking = xTaskGetTickCount(); + + /* We should unblock after xTimeToBlock having not received + * anything on the queue. */ + if( xQueueSend( xTestQueue, &xItem, xTimeToBlock ) != errQUEUE_FULL ) + { + xErrorOccurred = pdTRUE; + } + + /* How long were we blocked for? */ + xBlockedTime = xTaskGetTickCount() - xTimeWhenBlocking; + + if( xBlockedTime < xTimeToBlock ) + { + /* Should not have blocked for less than we requested. */ + xErrorOccurred = pdTRUE; + } + + if( xBlockedTime > ( xTimeToBlock + bktALLOWABLE_MARGIN ) ) + { + /* Should not have blocked for longer than we requested, + * although we would not necessarily run as soon as we were + * unblocked so a margin is allowed. */ + xErrorOccurred = pdTRUE; + } + } + + /********************************************************************* + * Test 3 + * + * Wake the other task, it will block attempting to post to the queue. + * When we read from the queue the other task will wake, but before it + * can run we will post to the queue again. When the other task runs it + * will find the queue still full, even though it was woken. It should + * recognise that its block time has not expired and return to block for + * the remains of its block time. + * + * Wake the other task so it blocks attempting to post to the already + * full queue. */ + xRunIndicator = 0; + vTaskResume( xSecondary ); + + /* We need to wait a little to ensure the other task executes. */ + while( xRunIndicator != bktRUN_INDICATOR ) + { + /* The other task has not yet executed. */ + vTaskDelay( bktSHORT_WAIT ); + } + + /* Make sure the other task is blocked on the queue. */ + vTaskDelay( bktSHORT_WAIT ); + xRunIndicator = 0; + + for( xItem = 0; xItem < bktQUEUE_LENGTH; xItem++ ) + { + /* Now when we make space on the queue the other task should wake + * but not execute as this task has higher priority. */ + if( xQueueReceive( xTestQueue, &xData, bktDONT_BLOCK ) != pdPASS ) + { + xErrorOccurred = pdTRUE; + } + + /* Now fill the queue again before the other task gets a chance to + * execute. If the other task had executed we would find the queue + * full ourselves, and the other task have set xRunIndicator. */ + if( xQueueSend( xTestQueue, &xItem, bktDONT_BLOCK ) != pdPASS ) + { + xErrorOccurred = pdTRUE; + } + + if( xRunIndicator == bktRUN_INDICATOR ) + { + /* The other task should not have executed. */ + xErrorOccurred = pdTRUE; + } + + /* Raise the priority of the other task so it executes and blocks + * on the queue again. */ + vTaskPrioritySet( xSecondary, bktPRIMARY_PRIORITY + 2 ); + + /* The other task should now have re-blocked without exiting the + * queue function. */ + if( xRunIndicator == bktRUN_INDICATOR ) + { + /* The other task should not have executed outside of the + * queue function. */ + xErrorOccurred = pdTRUE; + } + + /* Set the priority back down. */ + vTaskPrioritySet( xSecondary, bktSECONDARY_PRIORITY ); + } + + /* Let the other task timeout. When it unblockes it will check that it + * unblocked at the correct time, then suspend itself. */ + while( xRunIndicator != bktRUN_INDICATOR ) + { + vTaskDelay( bktSHORT_WAIT ); + } + + vTaskDelay( bktSHORT_WAIT ); + xRunIndicator = 0; + + /********************************************************************* + * Test 4 + * + * As per test 3 - but with the send and receive the other way around. + * The other task blocks attempting to read from the queue. + * + * Empty the queue. We should find that it is full. */ + for( xItem = 0; xItem < bktQUEUE_LENGTH; xItem++ ) + { + if( xQueueReceive( xTestQueue, &xData, bktDONT_BLOCK ) != pdPASS ) + { + xErrorOccurred = pdTRUE; + } + } + + /* Wake the other task so it blocks attempting to read from the + * already empty queue. */ + vTaskResume( xSecondary ); + + /* We need to wait a little to ensure the other task executes. */ + while( xRunIndicator != bktRUN_INDICATOR ) + { + vTaskDelay( bktSHORT_WAIT ); + } + + vTaskDelay( bktSHORT_WAIT ); + xRunIndicator = 0; + + for( xItem = 0; xItem < bktQUEUE_LENGTH; xItem++ ) + { + /* Now when we place an item on the queue the other task should + * wake but not execute as this task has higher priority. */ + if( xQueueSend( xTestQueue, &xItem, bktDONT_BLOCK ) != pdPASS ) + { + xErrorOccurred = pdTRUE; + } + + /* Now empty the queue again before the other task gets a chance to + * execute. If the other task had executed we would find the queue + * empty ourselves, and the other task would be suspended. */ + if( xQueueReceive( xTestQueue, &xData, bktDONT_BLOCK ) != pdPASS ) + { + xErrorOccurred = pdTRUE; + } + + if( xRunIndicator == bktRUN_INDICATOR ) + { + /* The other task should not have executed. */ + xErrorOccurred = pdTRUE; + } + + /* Raise the priority of the other task so it executes and blocks + * on the queue again. */ + vTaskPrioritySet( xSecondary, bktPRIMARY_PRIORITY + 2 ); + + /* The other task should now have re-blocked without exiting the + * queue function. */ + if( xRunIndicator == bktRUN_INDICATOR ) + { + /* The other task should not have executed outside of the + * queue function. */ + xErrorOccurred = pdTRUE; + } + + vTaskPrioritySet( xSecondary, bktSECONDARY_PRIORITY ); + } + + /* Let the other task timeout. When it unblockes it will check that it + * unblocked at the correct time, then suspend itself. */ + while( xRunIndicator != bktRUN_INDICATOR ) + { + vTaskDelay( bktSHORT_WAIT ); + } + + vTaskDelay( bktSHORT_WAIT ); + + xPrimaryCycles++; + } +} +/*-----------------------------------------------------------*/ + +static void vSecondaryBlockTimeTestTask( void * pvParameters ) +{ + TickType_t xTimeWhenBlocking, xBlockedTime; + BaseType_t xData; + + ( void ) pvParameters; + + for( ; ; ) + { + /********************************************************************* + * Test 0, 1 and 2 + * + * This task does not participate in these tests. */ + vTaskSuspend( NULL ); + + /********************************************************************* + * Test 3 + * + * The first thing we do is attempt to read from the queue. It should be + * full so we block. Note the time before we block so we can check the + * wake time is as per that expected. */ + xTimeWhenBlocking = xTaskGetTickCount(); + + /* We should unblock after bktTIME_TO_BLOCK having not sent anything to + * the queue. */ + xData = 0; + xRunIndicator = bktRUN_INDICATOR; + + if( xQueueSend( xTestQueue, &xData, bktTIME_TO_BLOCK ) != errQUEUE_FULL ) + { + xErrorOccurred = pdTRUE; + } + + /* How long were we inside the send function? */ + xBlockedTime = xTaskGetTickCount() - xTimeWhenBlocking; + + /* We should not have blocked for less time than bktTIME_TO_BLOCK. */ + if( xBlockedTime < bktTIME_TO_BLOCK ) + { + xErrorOccurred = pdTRUE; + } + + /* We should of not blocked for much longer than bktALLOWABLE_MARGIN + * either. A margin is permitted as we would not necessarily run as + * soon as we unblocked. */ + if( xBlockedTime > ( bktTIME_TO_BLOCK + bktALLOWABLE_MARGIN ) ) + { + xErrorOccurred = pdTRUE; + } + + /* Suspend ready for test 3. */ + xRunIndicator = bktRUN_INDICATOR; + vTaskSuspend( NULL ); + + /********************************************************************* + * Test 4 + * + * As per test three, but with the send and receive reversed. */ + xTimeWhenBlocking = xTaskGetTickCount(); + + /* We should unblock after bktTIME_TO_BLOCK having not received + * anything on the queue. */ + xRunIndicator = bktRUN_INDICATOR; + + if( xQueueReceive( xTestQueue, &xData, bktTIME_TO_BLOCK ) != errQUEUE_EMPTY ) + { + xErrorOccurred = pdTRUE; + } + + xBlockedTime = xTaskGetTickCount() - xTimeWhenBlocking; + + /* We should not have blocked for less time than bktTIME_TO_BLOCK. */ + if( xBlockedTime < bktTIME_TO_BLOCK ) + { + xErrorOccurred = pdTRUE; + } + + /* We should of not blocked for much longer than bktALLOWABLE_MARGIN + * either. A margin is permitted as we would not necessarily run as soon + * as we unblocked. */ + if( xBlockedTime > ( bktTIME_TO_BLOCK + bktALLOWABLE_MARGIN ) ) + { + xErrorOccurred = pdTRUE; + } + + xRunIndicator = bktRUN_INDICATOR; + + xSecondaryCycles++; + } +} +/*-----------------------------------------------------------*/ + +static void prvBasicDelayTests( void ) +{ + TickType_t xPreTime, xPostTime, x, xLastUnblockTime, xExpectedUnblockTime; + const TickType_t xPeriod = 75, xCycles = 5, xAllowableMargin = ( bktALLOWABLE_MARGIN >> 1 ), xHalfPeriod = xPeriod / ( TickType_t ) 2; + BaseType_t xDidBlock; + + /* Temporarily increase priority so the timing is more accurate, but not so + * high as to disrupt the timer tests. */ + vTaskPrioritySet( NULL, configTIMER_TASK_PRIORITY - 1 ); + + /* Crude check to too see that vTaskDelay() blocks for the expected + * period. */ + xPreTime = xTaskGetTickCount(); + vTaskDelay( bktTIME_TO_BLOCK ); + xPostTime = xTaskGetTickCount(); + + /* The priority is higher, so the allowable margin is halved when compared + * to the other tests in this file. */ + if( ( xPostTime - xPreTime ) > ( bktTIME_TO_BLOCK + xAllowableMargin ) ) + { + xErrorOccurred = pdTRUE; + } + + /* Now crude tests to check the vTaskDelayUntil() functionality. */ + xPostTime = xTaskGetTickCount(); + xLastUnblockTime = xPostTime; + + for( x = 0; x < xCycles; x++ ) + { + /* Calculate the next expected unblock time from the time taken before + * this loop was entered. */ + xExpectedUnblockTime = xPostTime + ( x * xPeriod ); + + vTaskDelayUntil( &xLastUnblockTime, xPeriod ); + + if( ( xTaskGetTickCount() - xExpectedUnblockTime ) > ( bktTIME_TO_BLOCK + xAllowableMargin ) ) + { + xErrorOccurred = pdTRUE; + } + + xPrimaryCycles++; + } + + /* Crude tests for return value of xTaskDelayUntil(). First a standard block + * should return that the task does block. */ + xDidBlock = xTaskDelayUntil( &xLastUnblockTime, xPeriod ); + + if( xDidBlock != pdTRUE ) + { + xErrorOccurred = pdTRUE; + } + + /* Now delay a few ticks so repeating the above block period will not block for + * the full amount of time, but will still block. */ + vTaskDelay( xHalfPeriod ); + xDidBlock = xTaskDelayUntil( &xLastUnblockTime, xPeriod ); + + if( xDidBlock != pdTRUE ) + { + xErrorOccurred = pdTRUE; + } + + /* This time block for longer than xPeriod before calling xTaskDelayUntil() so + * the call to xTaskDelayUntil() should not block. */ + vTaskDelay( xPeriod ); + xDidBlock = xTaskDelayUntil( &xLastUnblockTime, xPeriod ); + + if( xDidBlock != pdFALSE ) + { + xErrorOccurred = pdTRUE; + } + + /* Catch up. */ + xDidBlock = xTaskDelayUntil( &xLastUnblockTime, xPeriod ); + + if( xDidBlock != pdTRUE ) + { + xErrorOccurred = pdTRUE; + } + + /* Again block for slightly longer than a period so ensure the time is in the + * past next time xTaskDelayUntil() gets called. */ + vTaskDelay( xPeriod + xAllowableMargin ); + xDidBlock = xTaskDelayUntil( &xLastUnblockTime, xPeriod ); + + if( xDidBlock != pdFALSE ) + { + xErrorOccurred = pdTRUE; + } + + /* Reset to the original task priority ready for the other tests. */ + vTaskPrioritySet( NULL, bktPRIMARY_PRIORITY ); +} +/*-----------------------------------------------------------*/ + +BaseType_t xAreBlockTimeTestTasksStillRunning( void ) +{ + static BaseType_t xLastPrimaryCycleCount = 0, xLastSecondaryCycleCount = 0; + BaseType_t xReturn = pdPASS; + + /* Have both tasks performed at least one cycle since this function was + * last called? */ + if( xPrimaryCycles == xLastPrimaryCycleCount ) + { + xReturn = pdFAIL; + } + + if( xSecondaryCycles == xLastSecondaryCycleCount ) + { + xReturn = pdFAIL; + } + + if( xErrorOccurred == pdTRUE ) + { + xReturn = pdFAIL; + } + + xLastSecondaryCycleCount = xSecondaryCycles; + xLastPrimaryCycleCount = xPrimaryCycles; + + return xReturn; +} diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/countsem.c b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/countsem.c new file mode 100644 index 0000000..97d0c24 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/countsem.c @@ -0,0 +1,291 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + + +/* + * Simple demonstration of the usage of counting semaphore. + */ + +/* Scheduler include files. */ +#include "FreeRTOS.h" +#include "task.h" +#include "semphr.h" + +/* Demo program include files. */ +#include "countsem.h" + +/* The maximum count value that the semaphore used for the demo can hold. */ +#define countMAX_COUNT_VALUE ( 200 ) + +/* Constants used to indicate whether or not the semaphore should have been + * created with its maximum count value, or its minimum count value. These + * numbers are used to ensure that the pointers passed in as the task parameters + * are valid. */ +#define countSTART_AT_MAX_COUNT ( 0xaa ) +#define countSTART_AT_ZERO ( 0x55 ) + +/* Two tasks are created for the test. One uses a semaphore created with its + * count value set to the maximum, and one with the count value set to zero. */ +#define countNUM_TEST_TASKS ( 2 ) +#define countDONT_BLOCK ( 0 ) + +/*-----------------------------------------------------------*/ + +/* Flag that will be latched to pdTRUE should any unexpected behaviour be + * detected in any of the tasks. */ +static volatile BaseType_t xErrorDetected = pdFALSE; + +/*-----------------------------------------------------------*/ + +/* + * The demo task. This simply counts the semaphore up to its maximum value, + * the counts it back down again. The result of each semaphore 'give' and + * 'take' is inspected, with an error being flagged if it is found not to be + * the expected result. + */ +static void prvCountingSemaphoreTask( void * pvParameters ); + +/* + * Utility function to increment the semaphore count value up from zero to + * countMAX_COUNT_VALUE. + */ +static void prvIncrementSemaphoreCount( SemaphoreHandle_t xSemaphore, + volatile UBaseType_t * puxLoopCounter ); + +/* + * Utility function to decrement the semaphore count value up from + * countMAX_COUNT_VALUE to zero. + */ +static void prvDecrementSemaphoreCount( SemaphoreHandle_t xSemaphore, + volatile UBaseType_t * puxLoopCounter ); + +/*-----------------------------------------------------------*/ + +/* The structure that is passed into the task as the task parameter. */ +typedef struct COUNT_SEM_STRUCT +{ + /* The semaphore to be used for the demo. */ + SemaphoreHandle_t xSemaphore; + + /* Set to countSTART_AT_MAX_COUNT if the semaphore should be created with + * its count value set to its max count value, or countSTART_AT_ZERO if it + * should have been created with its count value set to 0. */ + UBaseType_t uxExpectedStartCount; + + /* Incremented on each cycle of the demo task. Used to detect a stalled + * task. */ + volatile UBaseType_t uxLoopCounter; +} xCountSemStruct; + +/* Two structures are defined, one is passed to each test task. */ +static xCountSemStruct xParameters[ countNUM_TEST_TASKS ]; + +/*-----------------------------------------------------------*/ + +void vStartCountingSemaphoreTasks( void ) +{ + /* Create the semaphores that we are going to use for the test/demo. The + * first should be created such that it starts at its maximum count value, + * the second should be created such that it starts with a count value of zero. */ + xParameters[ 0 ].xSemaphore = xSemaphoreCreateCounting( countMAX_COUNT_VALUE, countMAX_COUNT_VALUE ); + xParameters[ 0 ].uxExpectedStartCount = countSTART_AT_MAX_COUNT; + xParameters[ 0 ].uxLoopCounter = 0; + + xParameters[ 1 ].xSemaphore = xSemaphoreCreateCounting( countMAX_COUNT_VALUE, 0 ); + xParameters[ 1 ].uxExpectedStartCount = 0; + xParameters[ 1 ].uxLoopCounter = 0; + + /* Were the semaphores created? */ + if( ( xParameters[ 0 ].xSemaphore != NULL ) || ( xParameters[ 1 ].xSemaphore != NULL ) ) + { + /* vQueueAddToRegistry() adds the semaphore to the registry, if one is + * in use. The registry is provided as a means for kernel aware + * debuggers to locate semaphores and has no purpose if a kernel aware + * debugger is not being used. The call to vQueueAddToRegistry() will be + * removed by the pre-processor if configQUEUE_REGISTRY_SIZE is not + * defined or is defined to be less than 1. */ + vQueueAddToRegistry( ( QueueHandle_t ) xParameters[ 0 ].xSemaphore, "Counting_Sem_1" ); + vQueueAddToRegistry( ( QueueHandle_t ) xParameters[ 1 ].xSemaphore, "Counting_Sem_2" ); + + /* Create the demo tasks, passing in the semaphore to use as the parameter. */ + xTaskCreate( prvCountingSemaphoreTask, "CNT1", configMINIMAL_STACK_SIZE, ( void * ) &( xParameters[ 0 ] ), tskIDLE_PRIORITY, NULL ); + xTaskCreate( prvCountingSemaphoreTask, "CNT2", configMINIMAL_STACK_SIZE, ( void * ) &( xParameters[ 1 ] ), tskIDLE_PRIORITY, NULL ); + } +} +/*-----------------------------------------------------------*/ + +static void prvDecrementSemaphoreCount( SemaphoreHandle_t xSemaphore, + volatile UBaseType_t * puxLoopCounter ) +{ + UBaseType_t ux; + + /* If the semaphore count is at its maximum then we should not be able to + * 'give' the semaphore. */ + if( xSemaphoreGive( xSemaphore ) == pdPASS ) + { + xErrorDetected = pdTRUE; + } + + /* We should be able to 'take' the semaphore countMAX_COUNT_VALUE times. */ + for( ux = 0; ux < countMAX_COUNT_VALUE; ux++ ) + { + configASSERT( uxSemaphoreGetCount( xSemaphore ) == ( countMAX_COUNT_VALUE - ux ) ); + + if( xSemaphoreTake( xSemaphore, countDONT_BLOCK ) != pdPASS ) + { + /* We expected to be able to take the semaphore. */ + xErrorDetected = pdTRUE; + } + + ( *puxLoopCounter )++; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + /* If the semaphore count is zero then we should not be able to 'take' + * the semaphore. */ + configASSERT( uxSemaphoreGetCount( xSemaphore ) == 0 ); + + if( xSemaphoreTake( xSemaphore, countDONT_BLOCK ) == pdPASS ) + { + xErrorDetected = pdTRUE; + } +} +/*-----------------------------------------------------------*/ + +static void prvIncrementSemaphoreCount( SemaphoreHandle_t xSemaphore, + volatile UBaseType_t * puxLoopCounter ) +{ + UBaseType_t ux; + + /* If the semaphore count is zero then we should not be able to 'take' + * the semaphore. */ + if( xSemaphoreTake( xSemaphore, countDONT_BLOCK ) == pdPASS ) + { + xErrorDetected = pdTRUE; + } + + /* We should be able to 'give' the semaphore countMAX_COUNT_VALUE times. */ + for( ux = 0; ux < countMAX_COUNT_VALUE; ux++ ) + { + configASSERT( uxSemaphoreGetCount( xSemaphore ) == ux ); + + if( xSemaphoreGive( xSemaphore ) != pdPASS ) + { + /* We expected to be able to take the semaphore. */ + xErrorDetected = pdTRUE; + } + + ( *puxLoopCounter )++; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + /* If the semaphore count is at its maximum then we should not be able to + * 'give' the semaphore. */ + if( xSemaphoreGive( xSemaphore ) == pdPASS ) + { + xErrorDetected = pdTRUE; + } +} +/*-----------------------------------------------------------*/ + +static void prvCountingSemaphoreTask( void * pvParameters ) +{ + xCountSemStruct * pxParameter; + + #ifdef USE_STDIO + void vPrintDisplayMessage( const char * const * ppcMessageToSend ); + + const char * const pcTaskStartMsg = "Counting semaphore demo started.\r\n"; + + /* Queue a message for printing to say the task has started. */ + vPrintDisplayMessage( &pcTaskStartMsg ); + #endif + + /* The semaphore to be used was passed as the parameter. */ + pxParameter = ( xCountSemStruct * ) pvParameters; + + /* Did we expect to find the semaphore already at its max count value, or + * at zero? */ + if( pxParameter->uxExpectedStartCount == countSTART_AT_MAX_COUNT ) + { + prvDecrementSemaphoreCount( pxParameter->xSemaphore, &( pxParameter->uxLoopCounter ) ); + } + + /* Now we expect the semaphore count to be 0, so this time there is an + * error if we can take the semaphore. */ + if( xSemaphoreTake( pxParameter->xSemaphore, 0 ) == pdPASS ) + { + xErrorDetected = pdTRUE; + } + + for( ; ; ) + { + prvIncrementSemaphoreCount( pxParameter->xSemaphore, &( pxParameter->uxLoopCounter ) ); + prvDecrementSemaphoreCount( pxParameter->xSemaphore, &( pxParameter->uxLoopCounter ) ); + } +} +/*-----------------------------------------------------------*/ + +BaseType_t xAreCountingSemaphoreTasksStillRunning( void ) +{ + static UBaseType_t uxLastCount0 = 0, uxLastCount1 = 0; + BaseType_t xReturn = pdPASS; + + /* Return fail if any 'give' or 'take' did not result in the expected + * behaviour. */ + if( xErrorDetected != pdFALSE ) + { + xReturn = pdFAIL; + } + + /* Return fail if either task is not still incrementing its loop counter. */ + if( uxLastCount0 == xParameters[ 0 ].uxLoopCounter ) + { + xReturn = pdFAIL; + } + else + { + uxLastCount0 = xParameters[ 0 ].uxLoopCounter; + } + + if( uxLastCount1 == xParameters[ 1 ].uxLoopCounter ) + { + xReturn = pdFAIL; + } + else + { + uxLastCount1 = xParameters[ 1 ].uxLoopCounter; + } + + return xReturn; +} diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/death.c b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/death.c new file mode 100644 index 0000000..04b1f4a --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/death.c @@ -0,0 +1,201 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +/** + * Create a single persistent task which periodically dynamically creates another + * two tasks. The original task is called the creator task, the two tasks it + * creates are called suicidal tasks. + * + * One of the created suicidal tasks kill one other suicidal task before killing + * itself - leaving just the original task remaining. + * + * The creator task must be spawned after all of the other demo application tasks + * as it keeps a check on the number of tasks under the scheduler control. The + * number of tasks it expects to see running should never be greater than the + * number of tasks that were in existence when the creator task was spawned, plus + * one set of four suicidal tasks. If this number is exceeded an error is flagged. + * + * \page DeathC death.c + * \ingroup DemoFiles + *
+ */ + + +#include + +/* Scheduler include files. */ +#include "FreeRTOS.h" +#include "task.h" + +/* Demo program include files. */ +#include "death.h" + +#define deathSTACK_SIZE ( configMINIMAL_STACK_SIZE + 60 ) + +/* The task originally created which is responsible for periodically dynamically + * creating another four tasks. */ +static portTASK_FUNCTION_PROTO( vCreateTasks, pvParameters ); + +/* The task function of the dynamically created tasks. */ +static portTASK_FUNCTION_PROTO( vSuicidalTask, pvParameters ); + +/* A variable which is incremented every time the dynamic tasks are created. This + * is used to check that the task is still running. */ +static volatile uint16_t usCreationCount = 0; + +/* Used to store the number of tasks that were originally running so the creator + * task can tell if any of the suicidal tasks have failed to die. + */ +static volatile UBaseType_t uxTasksRunningAtStart = 0; + +/* When a task deletes itself, it stack and TCB are cleaned up by the Idle task. + * Under heavy load the idle task might not get much processing time, so it would + * be legitimate for several tasks to remain undeleted for a short period. There + * may also be a few other unexpected tasks if, for example, the tasks that test + * static allocation are also being used. */ +static const UBaseType_t uxMaxNumberOfExtraTasksRunning = 3; + +/* Used to store a handle to the task that should be killed by a suicidal task, + * before it kills itself. */ +TaskHandle_t xCreatedTask; + +/*-----------------------------------------------------------*/ + +void vCreateSuicidalTasks( UBaseType_t uxPriority ) +{ + xTaskCreate( vCreateTasks, "CREATOR", deathSTACK_SIZE, ( void * ) NULL, uxPriority, NULL ); +} +/*-----------------------------------------------------------*/ + +static portTASK_FUNCTION( vSuicidalTask, pvParameters ) +{ + volatile long l1, l2; + TaskHandle_t xTaskToKill; + const TickType_t xDelay = pdMS_TO_TICKS( ( TickType_t ) 200 ); + + /* Test deletion of a task's secure context, if any. */ + portALLOCATE_SECURE_CONTEXT( configMINIMAL_SECURE_STACK_SIZE ); + + if( pvParameters != NULL ) + { + /* This task is periodically created four times. Two created tasks are + * passed a handle to the other task so it can kill it before killing itself. + * The other task is passed in null. */ + xTaskToKill = *( TaskHandle_t * ) pvParameters; + } + else + { + xTaskToKill = NULL; + } + + for( ; ; ) + { + /* Do something random just to use some stack and registers. */ + l1 = 2; + l2 = 89; + l2 *= l1; + vTaskDelay( xDelay ); + + if( xTaskToKill != NULL ) + { + /* Make sure the other task has a go before we delete it. */ + vTaskDelay( ( TickType_t ) 0 ); + + /* Kill the other task that was created by vCreateTasks(). */ + vTaskDelete( xTaskToKill ); + + /* Kill ourselves. */ + vTaskDelete( NULL ); + } + } +} /*lint !e818 !e550 Function prototype must be as per standard for task functions. */ +/*-----------------------------------------------------------*/ + +static portTASK_FUNCTION( vCreateTasks, pvParameters ) +{ + const TickType_t xDelay = pdMS_TO_TICKS( ( TickType_t ) 1000 ); + UBaseType_t uxPriority; + + /* Remove compiler warning about unused parameter. */ + ( void ) pvParameters; + + /* Delay at the start to ensure tasks created by other demos have been + * created before storing the current number of tasks. */ + vTaskDelay( xDelay ); + uxTasksRunningAtStart = ( UBaseType_t ) uxTaskGetNumberOfTasks(); + + uxPriority = uxTaskPriorityGet( NULL ); + + for( ; ; ) + { + /* Just loop round, delaying then creating the four suicidal tasks. */ + vTaskDelay( xDelay ); + + xCreatedTask = NULL; + + xTaskCreate( vSuicidalTask, "SUICID1", configMINIMAL_STACK_SIZE, NULL, uxPriority, &xCreatedTask ); + xTaskCreate( vSuicidalTask, "SUICID2", configMINIMAL_STACK_SIZE, &xCreatedTask, uxPriority, NULL ); + + ++usCreationCount; + } +} +/*-----------------------------------------------------------*/ + +/* This is called to check that the creator task is still running and that there + * are not any more than four extra tasks. */ +BaseType_t xIsCreateTaskStillRunning( void ) +{ + static uint16_t usLastCreationCount = 0xfff; + BaseType_t xReturn = pdTRUE; + static UBaseType_t uxTasksRunningNow; + + if( usLastCreationCount == usCreationCount ) + { + xReturn = pdFALSE; + } + else + { + usLastCreationCount = usCreationCount; + } + + uxTasksRunningNow = ( UBaseType_t ) uxTaskGetNumberOfTasks(); + + if( uxTasksRunningNow < uxTasksRunningAtStart ) + { + xReturn = pdFALSE; + } + else if( ( uxTasksRunningNow - uxTasksRunningAtStart ) > uxMaxNumberOfExtraTasksRunning ) + { + xReturn = pdFALSE; + } + else + { + /* Everything is okay. */ + } + + return xReturn; +} diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/dynamic.c b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/dynamic.c new file mode 100644 index 0000000..19171a3 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/dynamic.c @@ -0,0 +1,480 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +/* + * The first test creates three tasks - two counter tasks (one continuous count + * and one limited count) and one controller. A "count" variable is shared + * between all three tasks. The two counter tasks should never be in a "ready" + * state at the same time. The controller task runs at the same priority as + * the continuous count task, and at a lower priority than the limited count + * task. + * + * One counter task loops indefinitely, incrementing the shared count variable + * on each iteration. To ensure it has exclusive access to the variable it + * raises its priority above that of the controller task before each + * increment, lowering it again to its original priority before starting the + * next iteration. + * + * The other counter task increments the shared count variable on each + * iteration of its loop until the count has reached a limit of 0xff - at + * which point it suspends itself. It will not start a new loop until the + * controller task has made it "ready" again by calling vTaskResume(). + * This second counter task operates at a higher priority than controller + * task so does not need to worry about mutual exclusion of the counter + * variable. + * + * The controller task is in two sections. The first section controls and + * monitors the continuous count task. When this section is operational the + * limited count task is suspended. Likewise, the second section controls + * and monitors the limited count task. When this section is operational the + * continuous count task is suspended. + * + * In the first section the controller task first takes a copy of the shared + * count variable. To ensure mutual exclusion on the count variable it + * suspends the continuous count task, resuming it again when the copy has been + * taken. The controller task then sleeps for a fixed period - during which + * the continuous count task will execute and increment the shared variable. + * When the controller task wakes it checks that the continuous count task + * has executed by comparing the copy of the shared variable with its current + * value. This time, to ensure mutual exclusion, the scheduler itself is + * suspended with a call to vTaskSuspendAll (). This is for demonstration + * purposes only and is not a recommended technique due to its inefficiency. + * + * After a fixed number of iterations the controller task suspends the + * continuous count task, and moves on to its second section. + * + * At the start of the second section the shared variable is cleared to zero. + * The limited count task is then woken from its suspension by a call to + * vTaskResume (). As this counter task operates at a higher priority than + * the controller task the controller task should not run again until the + * shared variable has been counted up to the limited value causing the counter + * task to suspend itself. The next line after vTaskResume () is therefore + * a check on the shared variable to ensure everything is as expected. + * + * + * The second test consists of a couple of very simple tasks that post onto a + * queue while the scheduler is suspended. This test was added to test parts + * of the scheduler not exercised by the first test. + * + */ + +#include + +/* Scheduler include files. */ +#include "FreeRTOS.h" +#include "task.h" +#include "semphr.h" + +/* Demo app include files. */ +#include "dynamic.h" + +/* Function that implements the "limited count" task as described above. */ +static portTASK_FUNCTION_PROTO( vLimitedIncrementTask, pvParameters ); + +/* Function that implements the "continuous count" task as described above. */ +static portTASK_FUNCTION_PROTO( vContinuousIncrementTask, pvParameters ); + +/* Function that implements the controller task as described above. */ +static portTASK_FUNCTION_PROTO( vCounterControlTask, pvParameters ); + +static portTASK_FUNCTION_PROTO( vQueueReceiveWhenSuspendedTask, pvParameters ); +static portTASK_FUNCTION_PROTO( vQueueSendWhenSuspendedTask, pvParameters ); + +/* Demo task specific constants. */ +#ifndef priSUSPENDED_RX_TASK_STACK_SIZE + #define priSUSPENDED_RX_TASK_STACK_SIZE ( configMINIMAL_STACK_SIZE ) +#endif +#define priSTACK_SIZE ( configMINIMAL_STACK_SIZE ) +#define priSLEEP_TIME pdMS_TO_TICKS( 128 ) +#define priLOOPS ( 5 ) +#define priMAX_COUNT ( ( uint32_t ) 0xff ) +#define priNO_BLOCK ( ( TickType_t ) 0 ) +#define priSUSPENDED_QUEUE_LENGTH ( 1 ) + +/*-----------------------------------------------------------*/ + +/* Handles to the two counter tasks. These could be passed in as parameters + * to the controller task to prevent them having to be file scope. */ +static TaskHandle_t xContinuousIncrementHandle, xLimitedIncrementHandle; + +/* The shared counter variable. This is passed in as a parameter to the two + * counter variables for demonstration purposes. */ +static uint32_t ulCounter; + +/* Variables used to check that the tasks are still operating without error. + * Each complete iteration of the controller task increments this variable + * provided no errors have been found. The variable maintaining the same value + * is therefore indication of an error. */ +static volatile uint16_t usCheckVariable = ( uint16_t ) 0; +static volatile BaseType_t xSuspendedQueueSendError = pdFALSE; +static volatile BaseType_t xSuspendedQueueReceiveError = pdFALSE; + +/* Queue used by the second test. */ +QueueHandle_t xSuspendedTestQueue; + +/* The value the queue receive task expects to receive next. This is file + * scope so xAreDynamicPriorityTasksStillRunning() can ensure it is still + * incrementing. */ +static uint32_t ulExpectedValue = ( uint32_t ) 0; + +/*-----------------------------------------------------------*/ + +/* + * Start the three tasks as described at the top of the file. + * Note that the limited count task is given a higher priority. + */ +void vStartDynamicPriorityTasks( void ) +{ + xSuspendedTestQueue = xQueueCreate( priSUSPENDED_QUEUE_LENGTH, sizeof( uint32_t ) ); + + if( xSuspendedTestQueue != NULL ) + { + /* vQueueAddToRegistry() adds the queue to the queue registry, if one is + * in use. The queue registry is provided as a means for kernel aware + * debuggers to locate queues and has no purpose if a kernel aware debugger + * is not being used. The call to vQueueAddToRegistry() will be removed + * by the pre-processor if configQUEUE_REGISTRY_SIZE is not defined or is + * defined to be less than 1. */ + vQueueAddToRegistry( xSuspendedTestQueue, "Suspended_Test_Queue" ); + + xTaskCreate( vContinuousIncrementTask, "CNT_INC", priSTACK_SIZE, ( void * ) &ulCounter, tskIDLE_PRIORITY, &xContinuousIncrementHandle ); + xTaskCreate( vLimitedIncrementTask, "LIM_INC", priSTACK_SIZE, ( void * ) &ulCounter, tskIDLE_PRIORITY + 1, &xLimitedIncrementHandle ); + xTaskCreate( vCounterControlTask, "C_CTRL", priSUSPENDED_RX_TASK_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL ); + xTaskCreate( vQueueSendWhenSuspendedTask, "SUSP_TX", priSTACK_SIZE, NULL, tskIDLE_PRIORITY, NULL ); + xTaskCreate( vQueueReceiveWhenSuspendedTask, "SUSP_RX", priSUSPENDED_RX_TASK_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL ); + } +} +/*-----------------------------------------------------------*/ + +/* + * Just loops around incrementing the shared variable until the limit has been + * reached. Once the limit has been reached it suspends itself. + */ +static portTASK_FUNCTION( vLimitedIncrementTask, pvParameters ) +{ + volatile uint32_t * pulCounter; + + /* Take a pointer to the shared variable from the parameters passed into + * the task. */ + pulCounter = ( volatile uint32_t * ) pvParameters; + + /* This will run before the control task, so the first thing it does is + * suspend - the control task will resume it when ready. */ + vTaskSuspend( NULL ); + + for( ; ; ) + { + /* Just count up to a value then suspend. */ + ( *pulCounter )++; + + if( *pulCounter >= priMAX_COUNT ) + { + vTaskSuspend( NULL ); + } + } +} +/*-----------------------------------------------------------*/ + +/* + * Just keep counting the shared variable up. The control task will suspend + * this task when it wants. + */ +static portTASK_FUNCTION( vContinuousIncrementTask, pvParameters ) +{ + volatile uint32_t * pulCounter; + UBaseType_t uxOurPriority; + + /* Take a pointer to the shared variable from the parameters passed into + * the task. */ + pulCounter = ( volatile uint32_t * ) pvParameters; + + /* Query our priority so we can raise it when exclusive access to the + * shared variable is required. */ + uxOurPriority = uxTaskPriorityGet( NULL ); + + for( ; ; ) + { + /* Raise the priority above the controller task to ensure a context + * switch does not occur while the variable is being accessed. */ + vTaskPrioritySet( NULL, uxOurPriority + 1 ); + { + configASSERT( ( uxTaskPriorityGet( NULL ) == ( uxOurPriority + 1 ) ) ); + ( *pulCounter )++; + } + vTaskPrioritySet( NULL, uxOurPriority ); + + #if ( configUSE_PREEMPTION == 0 ) + taskYIELD(); + #endif + + configASSERT( ( uxTaskPriorityGet( NULL ) == uxOurPriority ) ); + } +} +/*-----------------------------------------------------------*/ + +/* + * Controller task as described above. + */ +static portTASK_FUNCTION( vCounterControlTask, pvParameters ) +{ + uint32_t ulLastCounter; + short sLoops; + short sError = pdFALSE; + + /* Just to stop warning messages. */ + ( void ) pvParameters; + + for( ; ; ) + { + /* Start with the counter at zero. */ + ulCounter = ( uint32_t ) 0; + + /* First section : */ + + /* Check the continuous count task is running. */ + for( sLoops = 0; sLoops < priLOOPS; sLoops++ ) + { + /* Suspend the continuous count task so we can take a mirror of the + * shared variable without risk of corruption. This is not really + * needed as the other task raises its priority above this task's + * priority. */ + vTaskSuspend( xContinuousIncrementHandle ); + { + #if ( INCLUDE_eTaskGetState == 1 ) + { + configASSERT( eTaskGetState( xContinuousIncrementHandle ) == eSuspended ); + } + #endif /* INCLUDE_eTaskGetState */ + + ulLastCounter = ulCounter; + } + vTaskResume( xContinuousIncrementHandle ); + + #if ( configUSE_PREEMPTION == 0 ) + taskYIELD(); + #endif + + #if ( INCLUDE_eTaskGetState == 1 ) + { + configASSERT( eTaskGetState( xContinuousIncrementHandle ) == eReady ); + } + #endif /* INCLUDE_eTaskGetState */ + + /* Now delay to ensure the other task has processor time. */ + vTaskDelay( priSLEEP_TIME ); + + /* Check the shared variable again. This time to ensure mutual + * exclusion the whole scheduler will be locked. This is just for + * demo purposes! */ + vTaskSuspendAll(); + { + if( ulLastCounter == ulCounter ) + { + /* The shared variable has not changed. There is a problem + * with the continuous count task so flag an error. */ + sError = pdTRUE; + } + } + xTaskResumeAll(); + } + + /* Second section: */ + + /* Suspend the continuous counter task so it stops accessing the shared + * variable. */ + vTaskSuspend( xContinuousIncrementHandle ); + + /* Reset the variable. */ + ulCounter = ( uint32_t ) 0; + + #if ( INCLUDE_eTaskGetState == 1 ) + { + configASSERT( eTaskGetState( xLimitedIncrementHandle ) == eSuspended ); + } + #endif /* INCLUDE_eTaskGetState */ + + /* Resume the limited count task which has a higher priority than us. + * We should therefore not return from this call until the limited count + * task has suspended itself with a known value in the counter variable. */ + vTaskResume( xLimitedIncrementHandle ); + + #if ( configUSE_PREEMPTION == 0 ) + taskYIELD(); + #endif + + /* This task should not run again until xLimitedIncrementHandle has + * suspended itself. */ + #if ( INCLUDE_eTaskGetState == 1 ) + { + configASSERT( eTaskGetState( xLimitedIncrementHandle ) == eSuspended ); + } + #endif /* INCLUDE_eTaskGetState */ + + /* Does the counter variable have the expected value? */ + if( ulCounter != priMAX_COUNT ) + { + sError = pdTRUE; + } + + if( sError == pdFALSE ) + { + /* If no errors have occurred then increment the check variable. */ + portENTER_CRITICAL(); + usCheckVariable++; + portEXIT_CRITICAL(); + } + + /* Resume the continuous count task and do it all again. */ + vTaskResume( xContinuousIncrementHandle ); + + #if ( configUSE_PREEMPTION == 0 ) + taskYIELD(); + #endif + } +} +/*-----------------------------------------------------------*/ + +static portTASK_FUNCTION( vQueueSendWhenSuspendedTask, pvParameters ) +{ + static uint32_t ulValueToSend = ( uint32_t ) 0; + + /* Just to stop warning messages. */ + ( void ) pvParameters; + + for( ; ; ) + { + vTaskSuspendAll(); + { + /* We must not block while the scheduler is suspended! */ + if( xQueueSend( xSuspendedTestQueue, ( void * ) &ulValueToSend, priNO_BLOCK ) != pdTRUE ) + { + xSuspendedQueueSendError = pdTRUE; + } + } + xTaskResumeAll(); + + vTaskDelay( priSLEEP_TIME ); + + ++ulValueToSend; + } +} +/*-----------------------------------------------------------*/ + +static portTASK_FUNCTION( vQueueReceiveWhenSuspendedTask, pvParameters ) +{ + uint32_t ulReceivedValue; + BaseType_t xGotValue; + + /* Just to stop warning messages. */ + ( void ) pvParameters; + + for( ; ; ) + { + do + { + /* Suspending the scheduler here is fairly pointless and + * undesirable for a normal application. It is done here purely + * to test the scheduler. The inner xTaskResumeAll() should + * never return pdTRUE as the scheduler is still locked by the + * outer call. */ + vTaskSuspendAll(); + { + vTaskSuspendAll(); + { + xGotValue = xQueueReceive( xSuspendedTestQueue, ( void * ) &ulReceivedValue, priNO_BLOCK ); + } + + if( xTaskResumeAll() != pdFALSE ) + { + xSuspendedQueueReceiveError = pdTRUE; + } + } + xTaskResumeAll(); + + #if configUSE_PREEMPTION == 0 + { + taskYIELD(); + } + #endif + } while( xGotValue == pdFALSE ); + + if( ulReceivedValue != ulExpectedValue ) + { + xSuspendedQueueReceiveError = pdTRUE; + } + + if( xSuspendedQueueReceiveError != pdTRUE ) + { + /* Only increment the variable if an error has not occurred. This + * allows xAreDynamicPriorityTasksStillRunning() to check for stalled + * tasks as well as explicit errors. */ + ++ulExpectedValue; + } + } +} +/*-----------------------------------------------------------*/ + +/* Called to check that all the created tasks are still running without error. */ +BaseType_t xAreDynamicPriorityTasksStillRunning( void ) +{ +/* Keep a history of the check variables so we know if it has been incremented + * since the last call. */ + static uint16_t usLastTaskCheck = ( uint16_t ) 0; + static uint32_t ulLastExpectedValue = ( uint32_t ) 0U; + BaseType_t xReturn = pdTRUE; + + /* Check the tasks are still running by ensuring the check variable + * is still incrementing. */ + + if( usCheckVariable == usLastTaskCheck ) + { + /* The check has not incremented so an error exists. */ + xReturn = pdFALSE; + } + + if( ulExpectedValue == ulLastExpectedValue ) + { + /* The value being received by the queue receive task has not + * incremented so an error exists. */ + xReturn = pdFALSE; + } + + if( xSuspendedQueueSendError == pdTRUE ) + { + xReturn = pdFALSE; + } + + if( xSuspendedQueueReceiveError == pdTRUE ) + { + xReturn = pdFALSE; + } + + usLastTaskCheck = usCheckVariable; + ulLastExpectedValue = ulExpectedValue; + + return xReturn; +} diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/recmutex.c b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/recmutex.c new file mode 100644 index 0000000..5315bd3 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/Minimal/recmutex.c @@ -0,0 +1,412 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +/* + * The tasks defined on this page demonstrate the use of recursive mutexes. + * + * For recursive mutex functionality the created mutex should be created using + * xSemaphoreCreateRecursiveMutex(), then be manipulated + * using the xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() API + * functions. + * + * This demo creates three tasks all of which access the same recursive mutex: + * + * prvRecursiveMutexControllingTask() has the highest priority so executes + * first and grabs the mutex. It then performs some recursive accesses - + * between each of which it sleeps for a short period to let the lower + * priority tasks execute. When it has completed its demo functionality + * it gives the mutex back before suspending itself. + * + * prvRecursiveMutexBlockingTask() attempts to access the mutex by performing + * a blocking 'take'. The blocking task has a lower priority than the + * controlling task so by the time it executes the mutex has already been + * taken by the controlling task, causing the blocking task to block. It + * does not unblock until the controlling task has given the mutex back, + * and it does not actually run until the controlling task has suspended + * itself (due to the relative priorities). When it eventually does obtain + * the mutex all it does is give the mutex back prior to also suspending + * itself. At this point both the controlling task and the blocking task are + * suspended. + * + * prvRecursiveMutexPollingTask() runs at the idle priority. It spins round + * a tight loop attempting to obtain the mutex with a non-blocking call. As + * the lowest priority task it will not successfully obtain the mutex until + * both the controlling and blocking tasks are suspended. Once it eventually + * does obtain the mutex it first unsuspends both the controlling task and + * blocking task prior to giving the mutex back - resulting in the polling + * task temporarily inheriting the controlling tasks priority. + */ + +/* Scheduler include files. */ +#include "FreeRTOS.h" +#include "task.h" +#include "semphr.h" + +/* Demo app include files. */ +#include "recmutex.h" + +/* Priorities assigned to the three tasks. recmuCONTROLLING_TASK_PRIORITY can + * be overridden by a definition in FreeRTOSConfig.h. */ +#ifndef recmuCONTROLLING_TASK_PRIORITY + #define recmuCONTROLLING_TASK_PRIORITY ( tskIDLE_PRIORITY + 2 ) +#endif +#define recmuBLOCKING_TASK_PRIORITY ( tskIDLE_PRIORITY + 1 ) +#define recmuPOLLING_TASK_PRIORITY ( tskIDLE_PRIORITY + 0 ) + +/* The recursive call depth. */ +#define recmuMAX_COUNT ( 10 ) + +/* Misc. */ +#define recmuSHORT_DELAY ( pdMS_TO_TICKS( 20 ) ) +#define recmuNO_DELAY ( ( TickType_t ) 0 ) +#define recmu15ms_DELAY ( pdMS_TO_TICKS( 15 ) ) + +#ifndef recmuRECURSIVE_MUTEX_TEST_TASK_STACK_SIZE + #define recmuRECURSIVE_MUTEX_TEST_TASK_STACK_SIZE configMINIMAL_STACK_SIZE +#endif + +/* The three tasks as described at the top of this file. */ +static void prvRecursiveMutexControllingTask( void * pvParameters ); +static void prvRecursiveMutexBlockingTask( void * pvParameters ); +static void prvRecursiveMutexPollingTask( void * pvParameters ); + +/* The mutex used by the demo. */ +static SemaphoreHandle_t xMutex; + +/* Variables used to detect and latch errors. */ +static volatile BaseType_t xErrorOccurred = pdFALSE, xControllingIsSuspended = pdFALSE, xBlockingIsSuspended = pdFALSE; +static volatile UBaseType_t uxControllingCycles = 0, uxBlockingCycles = 0, uxPollingCycles = 0; + +/* Handles of the two higher priority tasks, required so they can be resumed + * (unsuspended). */ +static TaskHandle_t xControllingTaskHandle, xBlockingTaskHandle; + +/*-----------------------------------------------------------*/ + +void vStartRecursiveMutexTasks( void ) +{ + /* Just creates the mutex and the three tasks. */ + + xMutex = xSemaphoreCreateRecursiveMutex(); + + if( xMutex != NULL ) + { + /* vQueueAddToRegistry() adds the mutex to the registry, if one is + * in use. The registry is provided as a means for kernel aware + * debuggers to locate mutex and has no purpose if a kernel aware debugger + * is not being used. The call to vQueueAddToRegistry() will be removed + * by the pre-processor if configQUEUE_REGISTRY_SIZE is not defined or is + * defined to be less than 1. */ + vQueueAddToRegistry( ( QueueHandle_t ) xMutex, "Recursive_Mutex" ); + + xTaskCreate( prvRecursiveMutexControllingTask, "Rec1", recmuRECURSIVE_MUTEX_TEST_TASK_STACK_SIZE, NULL, recmuCONTROLLING_TASK_PRIORITY, &xControllingTaskHandle ); + xTaskCreate( prvRecursiveMutexBlockingTask, "Rec2", recmuRECURSIVE_MUTEX_TEST_TASK_STACK_SIZE, NULL, recmuBLOCKING_TASK_PRIORITY, &xBlockingTaskHandle ); + xTaskCreate( prvRecursiveMutexPollingTask, "Rec3", recmuRECURSIVE_MUTEX_TEST_TASK_STACK_SIZE, NULL, recmuPOLLING_TASK_PRIORITY, NULL ); + } +} +/*-----------------------------------------------------------*/ + +static void prvRecursiveMutexControllingTask( void * pvParameters ) +{ + UBaseType_t ux; + + /* Just to remove compiler warning. */ + ( void ) pvParameters; + + for( ; ; ) + { + /* Should not be able to 'give' the mutex, as we have not yet 'taken' + * it. The first time through, the mutex will not have been used yet, + * subsequent times through, at this point the mutex will be held by the + * polling task. */ + if( xSemaphoreGiveRecursive( xMutex ) == pdPASS ) + { + xErrorOccurred = pdTRUE; + } + + for( ux = 0; ux < recmuMAX_COUNT; ux++ ) + { + /* We should now be able to take the mutex as many times as + * we like. + * + * The first time through the mutex will be immediately available, on + * subsequent times through the mutex will be held by the polling task + * at this point and this Take will cause the polling task to inherit + * the priority of this task. In this case the block time must be + * long enough to ensure the polling task will execute again before the + * block time expires. If the block time does expire then the error + * flag will be set here. */ + if( xSemaphoreTakeRecursive( xMutex, recmu15ms_DELAY ) != pdPASS ) + { + xErrorOccurred = pdTRUE; + } + + /* Ensure the other task attempting to access the mutex (and the + * other demo tasks) are able to execute to ensure they either block + * (where a block time is specified) or return an error (where no + * block time is specified) as the mutex is held by this task. */ + vTaskDelay( recmuSHORT_DELAY ); + } + + /* For each time we took the mutex, give it back. */ + for( ux = 0; ux < recmuMAX_COUNT; ux++ ) + { + /* Ensure the other task attempting to access the mutex (and the + * other demo tasks) are able to execute. */ + vTaskDelay( recmuSHORT_DELAY ); + + /* We should now be able to give the mutex as many times as we + * took it. When the mutex is available again the Blocking task + * should be unblocked but not run because it has a lower priority + * than this task. The polling task should also not run at this point + * as it too has a lower priority than this task. */ + if( xSemaphoreGiveRecursive( xMutex ) != pdPASS ) + { + xErrorOccurred = pdTRUE; + } + + #if ( configUSE_PREEMPTION == 0 ) + taskYIELD(); + #endif + } + + /* Having given it back the same number of times as it was taken, we + * should no longer be the mutex owner, so the next give should fail. */ + if( xSemaphoreGiveRecursive( xMutex ) == pdPASS ) + { + xErrorOccurred = pdTRUE; + } + + /* Keep count of the number of cycles this task has performed so a + * stall can be detected. */ + uxControllingCycles++; + + /* Suspend ourselves so the blocking task can execute. */ + xControllingIsSuspended = pdTRUE; + vTaskSuspend( NULL ); + xControllingIsSuspended = pdFALSE; + } +} +/*-----------------------------------------------------------*/ + +static void prvRecursiveMutexBlockingTask( void * pvParameters ) +{ + /* Just to remove compiler warning. */ + ( void ) pvParameters; + + for( ; ; ) + { + /* This task will run while the controlling task is blocked, and the + * controlling task will block only once it has the mutex - therefore + * this call should block until the controlling task has given up the + * mutex, and not actually execute past this call until the controlling + * task is suspended. portMAX_DELAY - 1 is used instead of portMAX_DELAY + * to ensure the task's state is reported as Blocked and not Suspended in + * a later call to configASSERT() (within the polling task). */ + if( xSemaphoreTakeRecursive( xMutex, ( portMAX_DELAY - 1 ) ) == pdPASS ) + { + if( xControllingIsSuspended != pdTRUE ) + { + /* Did not expect to execute until the controlling task was + * suspended. */ + xErrorOccurred = pdTRUE; + } + else + { + /* Give the mutex back before suspending ourselves to allow + * the polling task to obtain the mutex. */ + if( xSemaphoreGiveRecursive( xMutex ) != pdPASS ) + { + xErrorOccurred = pdTRUE; + } + + xBlockingIsSuspended = pdTRUE; + vTaskSuspend( NULL ); + xBlockingIsSuspended = pdFALSE; + } + } + else + { + /* We should not leave the xSemaphoreTakeRecursive() function + * until the mutex was obtained. */ + xErrorOccurred = pdTRUE; + } + + /* The controlling and blocking tasks should be in lock step. */ + if( uxControllingCycles != ( UBaseType_t ) ( uxBlockingCycles + 1 ) ) + { + xErrorOccurred = pdTRUE; + } + + /* Keep count of the number of cycles this task has performed so a + * stall can be detected. */ + uxBlockingCycles++; + } +} +/*-----------------------------------------------------------*/ + +static void prvRecursiveMutexPollingTask( void * pvParameters ) +{ + /* Just to remove compiler warning. */ + ( void ) pvParameters; + + for( ; ; ) + { + /* Keep attempting to obtain the mutex. It should only be obtained when + * the blocking task has suspended itself, which in turn should only + * happen when the controlling task is also suspended. */ + if( xSemaphoreTakeRecursive( xMutex, recmuNO_DELAY ) == pdPASS ) + { + #if ( INCLUDE_eTaskGetState == 1 ) + { + configASSERT( eTaskGetState( xControllingTaskHandle ) == eSuspended ); + configASSERT( eTaskGetState( xBlockingTaskHandle ) == eSuspended ); + } + #endif /* INCLUDE_eTaskGetState */ + + /* Is the blocking task suspended? */ + if( ( xBlockingIsSuspended != pdTRUE ) || ( xControllingIsSuspended != pdTRUE ) ) + { + xErrorOccurred = pdTRUE; + } + else + { + /* Keep count of the number of cycles this task has performed + * so a stall can be detected. */ + uxPollingCycles++; + + /* We can resume the other tasks here even though they have a + * higher priority than the polling task. When they execute they + * will attempt to obtain the mutex but fail because the polling + * task is still the mutex holder. The polling task (this task) + * will then inherit the higher priority. The Blocking task will + * block indefinitely when it attempts to obtain the mutex, the + * Controlling task will only block for a fixed period and an + * error will be latched if the polling task has not returned the + * mutex by the time this fixed period has expired. */ + vTaskResume( xBlockingTaskHandle ); + #if ( configUSE_PREEMPTION == 0 ) + taskYIELD(); + #endif + + vTaskResume( xControllingTaskHandle ); + #if ( configUSE_PREEMPTION == 0 ) + taskYIELD(); + #endif + + /* The other two tasks should now have executed and no longer + * be suspended. */ + if( ( xBlockingIsSuspended == pdTRUE ) || ( xControllingIsSuspended == pdTRUE ) ) + { + xErrorOccurred = pdTRUE; + } + + #if ( INCLUDE_uxTaskPriorityGet == 1 ) + { + /* Check priority inherited. */ + configASSERT( uxTaskPriorityGet( NULL ) == recmuCONTROLLING_TASK_PRIORITY ); + } + #endif /* INCLUDE_uxTaskPriorityGet */ + + #if ( INCLUDE_eTaskGetState == 1 ) + { + configASSERT( eTaskGetState( xControllingTaskHandle ) == eBlocked ); + configASSERT( eTaskGetState( xBlockingTaskHandle ) == eBlocked ); + } + #endif /* INCLUDE_eTaskGetState */ + + /* Release the mutex, disinheriting the higher priority again. */ + if( xSemaphoreGiveRecursive( xMutex ) != pdPASS ) + { + xErrorOccurred = pdTRUE; + } + + #if ( INCLUDE_uxTaskPriorityGet == 1 ) + { + /* Check priority disinherited. */ + configASSERT( uxTaskPriorityGet( NULL ) == recmuPOLLING_TASK_PRIORITY ); + } + #endif /* INCLUDE_uxTaskPriorityGet */ + } + } + + #if configUSE_PREEMPTION == 0 + { + taskYIELD(); + } + #endif + } +} +/*-----------------------------------------------------------*/ + +/* This is called to check that all the created tasks are still running. */ +BaseType_t xAreRecursiveMutexTasksStillRunning( void ) +{ + BaseType_t xReturn; + static UBaseType_t uxLastControllingCycles = 0, uxLastBlockingCycles = 0, uxLastPollingCycles = 0; + + /* Is the controlling task still cycling? */ + if( uxLastControllingCycles == uxControllingCycles ) + { + xErrorOccurred = pdTRUE; + } + else + { + uxLastControllingCycles = uxControllingCycles; + } + + /* Is the blocking task still cycling? */ + if( uxLastBlockingCycles == uxBlockingCycles ) + { + xErrorOccurred = pdTRUE; + } + else + { + uxLastBlockingCycles = uxBlockingCycles; + } + + /* Is the polling task still cycling? */ + if( uxLastPollingCycles == uxPollingCycles ) + { + xErrorOccurred = pdTRUE; + } + else + { + uxLastPollingCycles = uxPollingCycles; + } + + if( xErrorOccurred == pdTRUE ) + { + xReturn = pdFAIL; + } + else + { + xReturn = pdPASS; + } + + return xReturn; +} diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/AbortDelay.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/AbortDelay.h new file mode 100644 index 0000000..cf279f4 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/AbortDelay.h @@ -0,0 +1,34 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef ABORT_DELAY_H +#define ABORT_DELAY_H + +void vCreateAbortDelayTasks( void ); +BaseType_t xAreAbortDelayTestTasksStillRunning( void ); + +#endif diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/BlockQ.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/BlockQ.h new file mode 100644 index 0000000..c6e92b7 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/BlockQ.h @@ -0,0 +1,34 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef BLOCK_Q_H +#define BLOCK_Q_H + +void vStartBlockingQueueTasks( UBaseType_t uxPriority ); +BaseType_t xAreBlockingQueuesStillRunning( void ); + +#endif diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/EventGroupsDemo.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/EventGroupsDemo.h new file mode 100644 index 0000000..9e00ad1 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/EventGroupsDemo.h @@ -0,0 +1,43 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + + + +/* + * This file contains fairly comprehensive checks on the behaviour of event + * groups. It is not intended to be a user friendly demonstration of the event + * groups API. + */ + +#ifndef EVENT_GROUPS_DEMO_H +#define EVENT_GROUPS_DEMO_H + +void vStartEventGroupTasks( void ); +BaseType_t xAreEventGroupTasksStillRunning( void ); +void vPeriodicEventGroupsProcessing( void ); + +#endif /* EVENT_GROUPS_DEMO_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/GenQTest.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/GenQTest.h new file mode 100644 index 0000000..ed43392 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/GenQTest.h @@ -0,0 +1,35 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef GEN_Q_TEST_H +#define GEN_Q_TEST_H + +void vStartGenericQueueTasks( UBaseType_t uxPriority ); +BaseType_t xAreGenericQueueTasksStillRunning( void ); +void vMutexISRInteractionTest( void ); + +#endif /* GEN_Q_TEST_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/IntQueue.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/IntQueue.h new file mode 100644 index 0000000..5ad5e0b --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/IntQueue.h @@ -0,0 +1,36 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef QUEUE_ACCESS_TEST +#define QUEUE_ACCESS_TEST + +void vStartInterruptQueueTasks( void ); +BaseType_t xAreIntQueueTasksStillRunning( void ); +BaseType_t xFirstTimerHandler( void ); +BaseType_t xSecondTimerHandler( void ); + +#endif /* QUEUE_ACCESS_TEST */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/IntSemTest.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/IntSemTest.h new file mode 100644 index 0000000..9ea8f4d --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/IntSemTest.h @@ -0,0 +1,35 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef INT_SEM_TEST_H +#define INT_SEM_TEST_H + +void vStartInterruptSemaphoreTasks( void ); +BaseType_t xAreInterruptSemaphoreTasksStillRunning( void ); +void vInterruptSemaphorePeriodicTest( void ); + +#endif /* INT_SEM_TEST_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/MessageBufferAMP.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/MessageBufferAMP.h new file mode 100644 index 0000000..6964a8c --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/MessageBufferAMP.h @@ -0,0 +1,35 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef MESSAGE_BUFFER_AMP_H +#define MESSAGE_BUFFER_AMP_H + +void vStartMessageBufferAMPTasks( configSTACK_DEPTH_TYPE xStackSize ); +BaseType_t xAreMessageBufferAMPTasksStillRunning( void ); +void vGenerateCoreBInterrupt( void * xUpdatedMessageBuffer ); + +#endif /* MESSAGE_BUFFER_AMP_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/MessageBufferDemo.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/MessageBufferDemo.h new file mode 100644 index 0000000..c7ee7db --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/MessageBufferDemo.h @@ -0,0 +1,34 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef MESSAGE_BUFFER_TEST_H +#define MESSAGE_BUFFER_TEST_H + +void vStartMessageBufferTasks( configSTACK_DEPTH_TYPE xStackSize ); +BaseType_t xAreMessageBufferTasksStillRunning( void ); + +#endif /* MESSAGE_BUFFER_TEST_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/PollQ.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/PollQ.h new file mode 100644 index 0000000..ac4ab0c --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/PollQ.h @@ -0,0 +1,34 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef POLLED_Q_H +#define POLLED_Q_H + +void vStartPolledQueueTasks( UBaseType_t uxPriority ); +BaseType_t xArePollingQueuesStillRunning( void ); + +#endif diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/QPeek.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/QPeek.h new file mode 100644 index 0000000..b077180 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/QPeek.h @@ -0,0 +1,34 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef Q_PEEK_TEST_H +#define Q_PEEK_TEST_H + +void vStartQueuePeekTasks( void ); +BaseType_t xAreQueuePeekTasksStillRunning( void ); + +#endif /* Q_PEEK_TEST_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/QueueOverwrite.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/QueueOverwrite.h new file mode 100644 index 0000000..e44cd04 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/QueueOverwrite.h @@ -0,0 +1,35 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef QUEUE_OVERWRITE_H +#define QUEUE_OVERWRITE_H + +void vStartQueueOverwriteTask( UBaseType_t uxPriority ); +BaseType_t xIsQueueOverwriteTaskStillRunning( void ); +void vQueueOverwritePeriodicISRDemo( void ); + +#endif /* QUEUE_OVERWRITE_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/QueueSet.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/QueueSet.h new file mode 100644 index 0000000..a2457b5 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/QueueSet.h @@ -0,0 +1,35 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef QUEUE_WAIT_MULTIPLE_H +#define QUEUE_WAIT_MULTIPLE_H + +void vStartQueueSetTasks( void ); +BaseType_t xAreQueueSetTasksStillRunning( void ); +void vQueueSetAccessQueueSetFromISR( void ); + +#endif /* QUEUE_WAIT_MULTIPLE_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/QueueSetPolling.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/QueueSetPolling.h new file mode 100644 index 0000000..cea74e0 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/QueueSetPolling.h @@ -0,0 +1,35 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef QUEUE_SET_POLLING_H +#define QUEUE_SET_POLLING_H + +void vStartQueueSetPollingTask( void ); +BaseType_t xAreQueueSetPollTasksStillRunning( void ); +void vQueueSetPollingInterruptAccess( void ); + +#endif /* QUEUE_SET_POLLING_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/StaticAllocation.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/StaticAllocation.h new file mode 100644 index 0000000..d1438d4 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/StaticAllocation.h @@ -0,0 +1,34 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef STATIC_ALLOCATION_H +#define STATIC_ALLOCATION_H + +void vStartStaticallyAllocatedTasks( void ); +BaseType_t xAreStaticAllocationTasksStillRunning( void ); + +#endif /* STATIC_ALLOCATION_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/StreamBufferDemo.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/StreamBufferDemo.h new file mode 100644 index 0000000..385939d --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/StreamBufferDemo.h @@ -0,0 +1,35 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef STREAM_BUFFER_TEST_H +#define STREAM_BUFFER_TEST_H + +void vStartStreamBufferTasks( void ); +BaseType_t xAreStreamBufferTasksStillRunning( void ); +void vPeriodicStreamBufferProcessing( void ); + +#endif /* STREAM_BUFFER_TEST_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/StreamBufferInterrupt.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/StreamBufferInterrupt.h new file mode 100644 index 0000000..8224c0e --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/StreamBufferInterrupt.h @@ -0,0 +1,35 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef STREAM_BUFFER_INTERRUPT_H +#define STREAM_BUFFER_INTERRUPT_H + +void vStartStreamBufferInterruptDemo( void ); +void vBasicStreamBufferSendFromISR( void ); +BaseType_t xIsInterruptStreamBufferDemoStillRunning( void ); + +#endif /* STREAM_BUFFER_INTERRUPT_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/TaskNotify.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/TaskNotify.h new file mode 100644 index 0000000..c18eeb9 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/TaskNotify.h @@ -0,0 +1,35 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef TASK_NOTIFY_H +#define TASK_NOTIFY_H + +void vStartTaskNotifyTask( void ); +BaseType_t xAreTaskNotificationTasksStillRunning( void ); +void xNotifyTaskFromISR( void ); + +#endif /* TASK_NOTIFY_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/TaskNotifyArray.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/TaskNotifyArray.h new file mode 100644 index 0000000..a00f566 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/TaskNotifyArray.h @@ -0,0 +1,35 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef TASK_NOTIFY_ARRAY_H +#define TASK_NOTIFY_ARRAY_H + +void vStartTaskNotifyArrayTask( void ); +BaseType_t xAreTaskNotificationArrayTasksStillRunning( void ); +void xNotifyArrayTaskFromISR( void ); + +#endif /* TASK_NOTIFY_ARRAY_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/TimerDemo.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/TimerDemo.h new file mode 100644 index 0000000..0aaccdc --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/TimerDemo.h @@ -0,0 +1,35 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#ifndef TIMER_DEMO_H +#define TIMER_DEMO_H + +void vStartTimerDemoTask( TickType_t xBaseFrequencyIn ); +BaseType_t xAreTimerDemoTasksStillRunning( TickType_t xCycleFrequency ); +void vTimerPeriodicISRTests( void ); +void vTimerDemoIncludeBacklogTests( BaseType_t includeBacklogTests ); + +#endif /* TIMER_DEMO_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/blocktim.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/blocktim.h new file mode 100644 index 0000000..3e5b737 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/blocktim.h @@ -0,0 +1,34 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef BLOCK_TIME_TEST_H +#define BLOCK_TIME_TEST_H + +void vCreateBlockTimeTasks( void ); +BaseType_t xAreBlockTimeTestTasksStillRunning( void ); + +#endif diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/comtest.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/comtest.h new file mode 100644 index 0000000..3a04604 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/comtest.h @@ -0,0 +1,40 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef COMTEST_H +#define COMTEST_H + +void vAltStartComTestTasks( UBaseType_t uxPriority, + uint32_t ulBaudRate, + UBaseType_t uxLED ); +void vStartComTestTasks( UBaseType_t uxPriority, + eCOMPort ePort, + eBaud eBaudRate ); +BaseType_t xAreComTestTasksStillRunning( void ); +void vComTestUnsuspendTask( void ); + +#endif /* ifndef COMTEST_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/comtest2.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/comtest2.h new file mode 100644 index 0000000..6caf743 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/comtest2.h @@ -0,0 +1,36 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef COMTEST_H +#define COMTEST_H + +void vAltStartComTestTasks( UBaseType_t uxPriority, + uint32_t ulBaudRate, + UBaseType_t uxLED ); +BaseType_t xAreComTestTasksStillRunning( void ); + +#endif diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/comtest_strings.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/comtest_strings.h new file mode 100644 index 0000000..87bd814 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/comtest_strings.h @@ -0,0 +1,36 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef COMTEST_STRINGS_H +#define COMTEST_STRINGS_H + +void vStartComTestStringsTasks( UBaseType_t uxPriority, + uint32_t ulBaudRate, + UBaseType_t uxLED ); +BaseType_t xAreComTestTasksStillRunning( void ); + +#endif diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/countsem.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/countsem.h new file mode 100644 index 0000000..6f1f03c --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/countsem.h @@ -0,0 +1,34 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef COUNT_SEMAPHORE_TEST_H +#define COUNT_SEMAPHORE_TEST_H + +void vStartCountingSemaphoreTasks( void ); +BaseType_t xAreCountingSemaphoreTasksStillRunning( void ); + +#endif diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/crflash.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/crflash.h new file mode 100644 index 0000000..67bb0a3 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/crflash.h @@ -0,0 +1,46 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef CRFLASH_LED_H +#define CRFLASH_LED_H + +/* + * Create the co-routines used to flash the LED's at different rates. + * + * @param uxPriority The number of 'fixed delay' co-routines to create. This + * also effects the number of LED's that will be utilised. For example, + * passing in 3 will cause LED's 0 to 2 to be utilised. + */ +void vStartFlashCoRoutines( UBaseType_t uxPriority ); + +/* + * Return pdPASS or pdFAIL depending on whether an error has been detected + * or not. + */ +BaseType_t xAreFlashCoRoutinesStillRunning( void ); + +#endif diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/crhook.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/crhook.h new file mode 100644 index 0000000..3e3791f --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/crhook.h @@ -0,0 +1,42 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef CRHOOK_H +#define CRHOOK_H + +/* + * Create the co-routines used to communicate wit the tick hook. + */ +void vStartHookCoRoutines( void ); + +/* + * Return pdPASS or pdFAIL depending on whether an error has been detected + * or not. + */ +BaseType_t xAreHookCoRoutinesStillRunning( void ); + +#endif diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/death.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/death.h new file mode 100644 index 0000000..295914c --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/death.h @@ -0,0 +1,34 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef SUICIDE_TASK_H +#define SUICIDE_TASK_H + +void vCreateSuicidalTasks( UBaseType_t uxPriority ); +BaseType_t xIsCreateTaskStillRunning( void ); + +#endif diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/dynamic.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/dynamic.h new file mode 100644 index 0000000..2185568 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/dynamic.h @@ -0,0 +1,34 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef DYNAMIC_MANIPULATION_H +#define DYNAMIC_MANIPULATION_H + +void vStartDynamicPriorityTasks( void ); +BaseType_t xAreDynamicPriorityTasksStillRunning( void ); + +#endif diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/fileIO.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/fileIO.h new file mode 100644 index 0000000..0d353f0 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/fileIO.h @@ -0,0 +1,36 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef FILE_IO_H +#define FILE_IO_H + +void vDisplayMessage( const char * const pcMessageToPrint ); +void vWriteMessageToDisk( const char * const pcMessage ); +void vWriteBufferToDisk( const char * const pcBuffer, + uint32_t ulBufferLength ); + +#endif diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/flash.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/flash.h new file mode 100644 index 0000000..3fa82b4 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/flash.h @@ -0,0 +1,33 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef FLASH_LED_H +#define FLASH_LED_H + +void vStartLEDFlashTasks( UBaseType_t uxPriority ); + +#endif diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/flash_timer.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/flash_timer.h new file mode 100644 index 0000000..ef3577c --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/flash_timer.h @@ -0,0 +1,41 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef FLASH_TIMER_H +#define FLASH_TIMER_H + +/* + * Creates the LED flashing timers. xNumberOfLEDs specifies how many timers to + * create, with each timer toggling a different LED. The first LED to be + * toggled is LED 0, with subsequent LEDs following on in numerical order. Each + * timer uses the exact same callback function, with the timer ID being used + * within the callback function to determine which timer has actually expired + * (and therefore which LED to toggle). + */ +void vStartLEDFlashTimers( UBaseType_t uxNumberOfLEDs ); + +#endif /* FLASH_TIMER_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/flop.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/flop.h new file mode 100644 index 0000000..7c1c74d --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/flop.h @@ -0,0 +1,34 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef FLOP_TASKS_H +#define FLOP_TASKS_H + +void vStartMathTasks( UBaseType_t uxPriority ); +BaseType_t xAreMathsTaskStillRunning( void ); + +#endif diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/integer.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/integer.h new file mode 100644 index 0000000..7a58a05 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/integer.h @@ -0,0 +1,34 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef INTEGER_TASKS_H +#define INTEGER_TASKS_H + +void vStartIntegerMathTasks( UBaseType_t uxPriority ); +BaseType_t xAreIntegerMathsTaskStillRunning( void ); + +#endif diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/mevents.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/mevents.h new file mode 100644 index 0000000..ee915c9 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/mevents.h @@ -0,0 +1,34 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef EVENTS_TEST_H +#define EVENTS_TEST_H + +void vStartMultiEventTasks( void ); +BaseType_t xAreMultiEventTasksStillRunning( void ); + +#endif diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/partest.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/partest.h new file mode 100644 index 0000000..b97f2ab --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/partest.h @@ -0,0 +1,38 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef PARTEST_H +#define PARTEST_H + +#define partstDEFAULT_PORT_ADDRESS ( ( uint16_t ) 0x378 ) + +void vParTestInitialise( void ); +void vParTestSetLED( UBaseType_t uxLED, + BaseType_t xValue ); +void vParTestToggleLED( UBaseType_t uxLED ); + +#endif diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/print.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/print.h new file mode 100644 index 0000000..f016d93 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/print.h @@ -0,0 +1,35 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef PRINT_H +#define PRINT_H + +void vPrintInitialise( void ); +void vPrintDisplayMessage( const char * const * pcMessageToSend ); +const char * pcPrintGetNextMessage( TickType_t xPrintRate ); + +#endif diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/recmutex.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/recmutex.h new file mode 100644 index 0000000..eaf46a4 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/recmutex.h @@ -0,0 +1,34 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef RECURSIVE_MUTEX_TEST_H +#define RECURSIVE_MUTEX_TEST_H + +void vStartRecursiveMutexTasks( void ); +BaseType_t xAreRecursiveMutexTasksStillRunning( void ); + +#endif diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/semtest.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/semtest.h new file mode 100644 index 0000000..16693a0 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/semtest.h @@ -0,0 +1,34 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef SEMAPHORE_TEST_H +#define SEMAPHORE_TEST_H + +void vStartSemaphoreTasks( UBaseType_t uxPriority ); +BaseType_t xAreSemaphoreTasksStillRunning( void ); + +#endif diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/serial.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/serial.h new file mode 100644 index 0000000..8f2ba74 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/common/include/serial.h @@ -0,0 +1,109 @@ +/* + * FreeRTOS V202112.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef SERIAL_COMMS_H +#define SERIAL_COMMS_H + +typedef void * xComPortHandle; + +typedef enum +{ + serCOM1, + serCOM2, + serCOM3, + serCOM4, + serCOM5, + serCOM6, + serCOM7, + serCOM8 +} eCOMPort; + +typedef enum +{ + serNO_PARITY, + serODD_PARITY, + serEVEN_PARITY, + serMARK_PARITY, + serSPACE_PARITY +} eParity; + +typedef enum +{ + serSTOP_1, + serSTOP_2 +} eStopBits; + +typedef enum +{ + serBITS_5, + serBITS_6, + serBITS_7, + serBITS_8 +} eDataBits; + +typedef enum +{ + ser50, + ser75, + ser110, + ser134, + ser150, + ser200, + ser300, + ser600, + ser1200, + ser1800, + ser2400, + ser4800, + ser9600, + ser19200, + ser38400, + ser57600, + ser115200 +} eBaud; + +xComPortHandle xSerialPortInitMinimal( unsigned long ulWantedBaud, + unsigned portBASE_TYPE uxQueueLength ); +xComPortHandle xSerialPortInit( eCOMPort ePort, + eBaud eWantedBaud, + eParity eWantedParity, + eDataBits eWantedDataBits, + eStopBits eWantedStopBits, + unsigned portBASE_TYPE uxBufferLength ); +void vSerialPutString( xComPortHandle pxPort, + const signed char * const pcString, + unsigned short usStringLength ); +signed portBASE_TYPE xSerialGetChar( xComPortHandle pxPort, + signed char * pcRxedChar, + TickType_t xBlockTime ); +signed portBASE_TYPE xSerialPutChar( xComPortHandle pxPort, + signed char cOutChar, + TickType_t xBlockTime ); +portBASE_TYPE xSerialWaitForSemaphore( xComPortHandle xPort ); +void vSerialClose( xComPortHandle xPort ); + +#endif /* ifndef SERIAL_COMMS_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/.gitmodules b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/.gitmodules new file mode 100644 index 0000000..aaa2390 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/.gitmodules @@ -0,0 +1,6 @@ +[submodule "ThirdParty/FreeRTOS-Kernel-Partner-Supported-Ports"] + path = portable/ThirdParty/Partner-Supported-Ports + url = https://github.com/FreeRTOS/FreeRTOS-Kernel-Partner-Supported-Ports +[submodule "ThirdParty/FreeRTOS-Kernel-Community-Supported-Ports"] + path = portable/ThirdParty/Community-Supported-Ports + url = https://github.com/FreeRTOS/FreeRTOS-Kernel-Community-Supported-Ports diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/croutine.c b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/croutine.c new file mode 100644 index 0000000..d9bce9b --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/croutine.c @@ -0,0 +1,363 @@ +/* + * FreeRTOS Kernel V10.4.6 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#include "FreeRTOS.h" +#include "task.h" +#include "croutine.h" + +/* Remove the whole file is co-routines are not being used. */ +#if ( configUSE_CO_ROUTINES != 0 ) + +/* + * Some kernel aware debuggers require data to be viewed to be global, rather + * than file scope. + */ + #ifdef portREMOVE_STATIC_QUALIFIER + #define static + #endif + + +/* Lists for ready and blocked co-routines. --------------------*/ + static List_t pxReadyCoRoutineLists[ configMAX_CO_ROUTINE_PRIORITIES ]; /*< Prioritised ready co-routines. */ + static List_t xDelayedCoRoutineList1; /*< Delayed co-routines. */ + static List_t xDelayedCoRoutineList2; /*< Delayed co-routines (two lists are used - one for delays that have overflowed the current tick count. */ + static List_t * pxDelayedCoRoutineList = NULL; /*< Points to the delayed co-routine list currently being used. */ + static List_t * pxOverflowDelayedCoRoutineList = NULL; /*< Points to the delayed co-routine list currently being used to hold co-routines that have overflowed the current tick count. */ + static List_t xPendingReadyCoRoutineList; /*< Holds co-routines that have been readied by an external event. They cannot be added directly to the ready lists as the ready lists cannot be accessed by interrupts. */ + +/* Other file private variables. --------------------------------*/ + CRCB_t * pxCurrentCoRoutine = NULL; + static UBaseType_t uxTopCoRoutineReadyPriority = 0; + static TickType_t xCoRoutineTickCount = 0, xLastTickCount = 0, xPassedTicks = 0; + +/* The initial state of the co-routine when it is created. */ + #define corINITIAL_STATE ( 0 ) + +/* + * Place the co-routine represented by pxCRCB into the appropriate ready queue + * for the priority. It is inserted at the end of the list. + * + * This macro accesses the co-routine ready lists and therefore must not be + * used from within an ISR. + */ + #define prvAddCoRoutineToReadyQueue( pxCRCB ) \ + { \ + if( pxCRCB->uxPriority > uxTopCoRoutineReadyPriority ) \ + { \ + uxTopCoRoutineReadyPriority = pxCRCB->uxPriority; \ + } \ + vListInsertEnd( ( List_t * ) &( pxReadyCoRoutineLists[ pxCRCB->uxPriority ] ), &( pxCRCB->xGenericListItem ) ); \ + } + +/* + * Utility to ready all the lists used by the scheduler. This is called + * automatically upon the creation of the first co-routine. + */ + static void prvInitialiseCoRoutineLists( void ); + +/* + * Co-routines that are readied by an interrupt cannot be placed directly into + * the ready lists (there is no mutual exclusion). Instead they are placed in + * in the pending ready list in order that they can later be moved to the ready + * list by the co-routine scheduler. + */ + static void prvCheckPendingReadyList( void ); + +/* + * Macro that looks at the list of co-routines that are currently delayed to + * see if any require waking. + * + * Co-routines are stored in the queue in the order of their wake time - + * meaning once one co-routine has been found whose timer has not expired + * we need not look any further down the list. + */ + static void prvCheckDelayedList( void ); + +/*-----------------------------------------------------------*/ + + BaseType_t xCoRoutineCreate( crCOROUTINE_CODE pxCoRoutineCode, + UBaseType_t uxPriority, + UBaseType_t uxIndex ) + { + BaseType_t xReturn; + CRCB_t * pxCoRoutine; + + /* Allocate the memory that will store the co-routine control block. */ + pxCoRoutine = ( CRCB_t * ) pvPortMalloc( sizeof( CRCB_t ) ); + + if( pxCoRoutine ) + { + /* If pxCurrentCoRoutine is NULL then this is the first co-routine to + * be created and the co-routine data structures need initialising. */ + if( pxCurrentCoRoutine == NULL ) + { + pxCurrentCoRoutine = pxCoRoutine; + prvInitialiseCoRoutineLists(); + } + + /* Check the priority is within limits. */ + if( uxPriority >= configMAX_CO_ROUTINE_PRIORITIES ) + { + uxPriority = configMAX_CO_ROUTINE_PRIORITIES - 1; + } + + /* Fill out the co-routine control block from the function parameters. */ + pxCoRoutine->uxState = corINITIAL_STATE; + pxCoRoutine->uxPriority = uxPriority; + pxCoRoutine->uxIndex = uxIndex; + pxCoRoutine->pxCoRoutineFunction = pxCoRoutineCode; + + /* Initialise all the other co-routine control block parameters. */ + vListInitialiseItem( &( pxCoRoutine->xGenericListItem ) ); + vListInitialiseItem( &( pxCoRoutine->xEventListItem ) ); + + /* Set the co-routine control block as a link back from the ListItem_t. + * This is so we can get back to the containing CRCB from a generic item + * in a list. */ + listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xGenericListItem ), pxCoRoutine ); + listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xEventListItem ), pxCoRoutine ); + + /* Event lists are always in priority order. */ + listSET_LIST_ITEM_VALUE( &( pxCoRoutine->xEventListItem ), ( ( TickType_t ) configMAX_CO_ROUTINE_PRIORITIES - ( TickType_t ) uxPriority ) ); + + /* Now the co-routine has been initialised it can be added to the ready + * list at the correct priority. */ + prvAddCoRoutineToReadyQueue( pxCoRoutine ); + + xReturn = pdPASS; + } + else + { + xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; + } + + return xReturn; + } +/*-----------------------------------------------------------*/ + + void vCoRoutineAddToDelayedList( TickType_t xTicksToDelay, + List_t * pxEventList ) + { + TickType_t xTimeToWake; + + /* Calculate the time to wake - this may overflow but this is + * not a problem. */ + xTimeToWake = xCoRoutineTickCount + xTicksToDelay; + + /* We must remove ourselves from the ready list before adding + * ourselves to the blocked list as the same list item is used for + * both lists. */ + ( void ) uxListRemove( ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) ); + + /* The list item will be inserted in wake time order. */ + listSET_LIST_ITEM_VALUE( &( pxCurrentCoRoutine->xGenericListItem ), xTimeToWake ); + + if( xTimeToWake < xCoRoutineTickCount ) + { + /* Wake time has overflowed. Place this item in the + * overflow list. */ + vListInsert( ( List_t * ) pxOverflowDelayedCoRoutineList, ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) ); + } + else + { + /* The wake time has not overflowed, so we can use the + * current block list. */ + vListInsert( ( List_t * ) pxDelayedCoRoutineList, ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) ); + } + + if( pxEventList ) + { + /* Also add the co-routine to an event list. If this is done then the + * function must be called with interrupts disabled. */ + vListInsert( pxEventList, &( pxCurrentCoRoutine->xEventListItem ) ); + } + } +/*-----------------------------------------------------------*/ + + static void prvCheckPendingReadyList( void ) + { + /* Are there any co-routines waiting to get moved to the ready list? These + * are co-routines that have been readied by an ISR. The ISR cannot access + * the ready lists itself. */ + while( listLIST_IS_EMPTY( &xPendingReadyCoRoutineList ) == pdFALSE ) + { + CRCB_t * pxUnblockedCRCB; + + /* The pending ready list can be accessed by an ISR. */ + portDISABLE_INTERRUPTS(); + { + pxUnblockedCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( ( &xPendingReadyCoRoutineList ) ); + ( void ) uxListRemove( &( pxUnblockedCRCB->xEventListItem ) ); + } + portENABLE_INTERRUPTS(); + + ( void ) uxListRemove( &( pxUnblockedCRCB->xGenericListItem ) ); + prvAddCoRoutineToReadyQueue( pxUnblockedCRCB ); + } + } +/*-----------------------------------------------------------*/ + + static void prvCheckDelayedList( void ) + { + CRCB_t * pxCRCB; + + xPassedTicks = xTaskGetTickCount() - xLastTickCount; + + while( xPassedTicks ) + { + xCoRoutineTickCount++; + xPassedTicks--; + + /* If the tick count has overflowed we need to swap the ready lists. */ + if( xCoRoutineTickCount == 0 ) + { + List_t * pxTemp; + + /* Tick count has overflowed so we need to swap the delay lists. If there are + * any items in pxDelayedCoRoutineList here then there is an error! */ + pxTemp = pxDelayedCoRoutineList; + pxDelayedCoRoutineList = pxOverflowDelayedCoRoutineList; + pxOverflowDelayedCoRoutineList = pxTemp; + } + + /* See if this tick has made a timeout expire. */ + while( listLIST_IS_EMPTY( pxDelayedCoRoutineList ) == pdFALSE ) + { + pxCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxDelayedCoRoutineList ); + + if( xCoRoutineTickCount < listGET_LIST_ITEM_VALUE( &( pxCRCB->xGenericListItem ) ) ) + { + /* Timeout not yet expired. */ + break; + } + + portDISABLE_INTERRUPTS(); + { + /* The event could have occurred just before this critical + * section. If this is the case then the generic list item will + * have been moved to the pending ready list and the following + * line is still valid. Also the pvContainer parameter will have + * been set to NULL so the following lines are also valid. */ + ( void ) uxListRemove( &( pxCRCB->xGenericListItem ) ); + + /* Is the co-routine waiting on an event also? */ + if( pxCRCB->xEventListItem.pxContainer ) + { + ( void ) uxListRemove( &( pxCRCB->xEventListItem ) ); + } + } + portENABLE_INTERRUPTS(); + + prvAddCoRoutineToReadyQueue( pxCRCB ); + } + } + + xLastTickCount = xCoRoutineTickCount; + } +/*-----------------------------------------------------------*/ + + void vCoRoutineSchedule( void ) + { + /* Only run a co-routine after prvInitialiseCoRoutineLists() has been + * called. prvInitialiseCoRoutineLists() is called automatically when a + * co-routine is created. */ + if( pxDelayedCoRoutineList != NULL ) + { + /* See if any co-routines readied by events need moving to the ready lists. */ + prvCheckPendingReadyList(); + + /* See if any delayed co-routines have timed out. */ + prvCheckDelayedList(); + + /* Find the highest priority queue that contains ready co-routines. */ + while( listLIST_IS_EMPTY( &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) ) ) + { + if( uxTopCoRoutineReadyPriority == 0 ) + { + /* No more co-routines to check. */ + return; + } + + --uxTopCoRoutineReadyPriority; + } + + /* listGET_OWNER_OF_NEXT_ENTRY walks through the list, so the co-routines + * of the same priority get an equal share of the processor time. */ + listGET_OWNER_OF_NEXT_ENTRY( pxCurrentCoRoutine, &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) ); + + /* Call the co-routine. */ + ( pxCurrentCoRoutine->pxCoRoutineFunction )( pxCurrentCoRoutine, pxCurrentCoRoutine->uxIndex ); + } + } +/*-----------------------------------------------------------*/ + + static void prvInitialiseCoRoutineLists( void ) + { + UBaseType_t uxPriority; + + for( uxPriority = 0; uxPriority < configMAX_CO_ROUTINE_PRIORITIES; uxPriority++ ) + { + vListInitialise( ( List_t * ) &( pxReadyCoRoutineLists[ uxPriority ] ) ); + } + + vListInitialise( ( List_t * ) &xDelayedCoRoutineList1 ); + vListInitialise( ( List_t * ) &xDelayedCoRoutineList2 ); + vListInitialise( ( List_t * ) &xPendingReadyCoRoutineList ); + + /* Start with pxDelayedCoRoutineList using list1 and the + * pxOverflowDelayedCoRoutineList using list2. */ + pxDelayedCoRoutineList = &xDelayedCoRoutineList1; + pxOverflowDelayedCoRoutineList = &xDelayedCoRoutineList2; + } +/*-----------------------------------------------------------*/ + + BaseType_t xCoRoutineRemoveFromEventList( const List_t * pxEventList ) + { + CRCB_t * pxUnblockedCRCB; + BaseType_t xReturn; + + /* This function is called from within an interrupt. It can only access + * event lists and the pending ready list. This function assumes that a + * check has already been made to ensure pxEventList is not empty. */ + pxUnblockedCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxEventList ); + ( void ) uxListRemove( &( pxUnblockedCRCB->xEventListItem ) ); + vListInsertEnd( ( List_t * ) &( xPendingReadyCoRoutineList ), &( pxUnblockedCRCB->xEventListItem ) ); + + if( pxUnblockedCRCB->uxPriority >= pxCurrentCoRoutine->uxPriority ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + + return xReturn; + } + +#endif /* configUSE_CO_ROUTINES == 0 */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/event_groups.c b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/event_groups.c new file mode 100644 index 0000000..93d9d0d --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/event_groups.c @@ -0,0 +1,777 @@ +/* + * FreeRTOS Kernel V10.4.6 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* Standard includes. */ +#include + +/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining + * all the API functions to use the MPU wrappers. That should only be done when + * task.h is included from an application file. */ +#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "timers.h" +#include "event_groups.h" + +/* Lint e961, e750 and e9021 are suppressed as a MISRA exception justified + * because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined + * for the header files above, but not in this file, in order to generate the + * correct privileged Vs unprivileged linkage and placement. */ +#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750 !e9021 See comment above. */ + +/* The following bit fields convey control information in a task's event list + * item value. It is important they don't clash with the + * taskEVENT_LIST_ITEM_VALUE_IN_USE definition. */ +#if configUSE_16_BIT_TICKS == 1 + #define eventCLEAR_EVENTS_ON_EXIT_BIT 0x0100U + #define eventUNBLOCKED_DUE_TO_BIT_SET 0x0200U + #define eventWAIT_FOR_ALL_BITS 0x0400U + #define eventEVENT_BITS_CONTROL_BYTES 0xff00U +#else + #define eventCLEAR_EVENTS_ON_EXIT_BIT 0x01000000UL + #define eventUNBLOCKED_DUE_TO_BIT_SET 0x02000000UL + #define eventWAIT_FOR_ALL_BITS 0x04000000UL + #define eventEVENT_BITS_CONTROL_BYTES 0xff000000UL +#endif + +typedef struct EventGroupDef_t +{ + EventBits_t uxEventBits; + List_t xTasksWaitingForBits; /*< List of tasks waiting for a bit to be set. */ + + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxEventGroupNumber; + #endif + + #if ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the event group is statically allocated to ensure no attempt is made to free the memory. */ + #endif +} EventGroup_t; + +/*-----------------------------------------------------------*/ + +/* + * Test the bits set in uxCurrentEventBits to see if the wait condition is met. + * The wait condition is defined by xWaitForAllBits. If xWaitForAllBits is + * pdTRUE then the wait condition is met if all the bits set in uxBitsToWaitFor + * are also set in uxCurrentEventBits. If xWaitForAllBits is pdFALSE then the + * wait condition is met if any of the bits set in uxBitsToWait for are also set + * in uxCurrentEventBits. + */ +static BaseType_t prvTestWaitCondition( const EventBits_t uxCurrentEventBits, + const EventBits_t uxBitsToWaitFor, + const BaseType_t xWaitForAllBits ) PRIVILEGED_FUNCTION; + +/*-----------------------------------------------------------*/ + +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + + EventGroupHandle_t xEventGroupCreateStatic( StaticEventGroup_t * pxEventGroupBuffer ) + { + EventGroup_t * pxEventBits; + + /* A StaticEventGroup_t object must be provided. */ + configASSERT( pxEventGroupBuffer ); + + #if ( configASSERT_DEFINED == 1 ) + { + /* Sanity check that the size of the structure used to declare a + * variable of type StaticEventGroup_t equals the size of the real + * event group structure. */ + volatile size_t xSize = sizeof( StaticEventGroup_t ); + configASSERT( xSize == sizeof( EventGroup_t ) ); + } /*lint !e529 xSize is referenced if configASSERT() is defined. */ + #endif /* configASSERT_DEFINED */ + + /* The user has provided a statically allocated event group - use it. */ + pxEventBits = ( EventGroup_t * ) pxEventGroupBuffer; /*lint !e740 !e9087 EventGroup_t and StaticEventGroup_t are deliberately aliased for data hiding purposes and guaranteed to have the same size and alignment requirement - checked by configASSERT(). */ + + if( pxEventBits != NULL ) + { + pxEventBits->uxEventBits = 0; + vListInitialise( &( pxEventBits->xTasksWaitingForBits ) ); + + #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + { + /* Both static and dynamic allocation can be used, so note that + * this event group was created statically in case the event group + * is later deleted. */ + pxEventBits->ucStaticallyAllocated = pdTRUE; + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + + traceEVENT_GROUP_CREATE( pxEventBits ); + } + else + { + /* xEventGroupCreateStatic should only ever be called with + * pxEventGroupBuffer pointing to a pre-allocated (compile time + * allocated) StaticEventGroup_t variable. */ + traceEVENT_GROUP_CREATE_FAILED(); + } + + return pxEventBits; + } + +#endif /* configSUPPORT_STATIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + + EventGroupHandle_t xEventGroupCreate( void ) + { + EventGroup_t * pxEventBits; + + /* Allocate the event group. Justification for MISRA deviation as + * follows: pvPortMalloc() always ensures returned memory blocks are + * aligned per the requirements of the MCU stack. In this case + * pvPortMalloc() must return a pointer that is guaranteed to meet the + * alignment requirements of the EventGroup_t structure - which (if you + * follow it through) is the alignment requirements of the TickType_t type + * (EventBits_t being of TickType_t itself). Therefore, whenever the + * stack alignment requirements are greater than or equal to the + * TickType_t alignment requirements the cast is safe. In other cases, + * where the natural word size of the architecture is less than + * sizeof( TickType_t ), the TickType_t variables will be accessed in two + * or more reads operations, and the alignment requirements is only that + * of each individual read. */ + pxEventBits = ( EventGroup_t * ) pvPortMalloc( sizeof( EventGroup_t ) ); /*lint !e9087 !e9079 see comment above. */ + + if( pxEventBits != NULL ) + { + pxEventBits->uxEventBits = 0; + vListInitialise( &( pxEventBits->xTasksWaitingForBits ) ); + + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + /* Both static and dynamic allocation can be used, so note this + * event group was allocated statically in case the event group is + * later deleted. */ + pxEventBits->ucStaticallyAllocated = pdFALSE; + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ + + traceEVENT_GROUP_CREATE( pxEventBits ); + } + else + { + traceEVENT_GROUP_CREATE_FAILED(); /*lint !e9063 Else branch only exists to allow tracing and does not generate code if trace macros are not defined. */ + } + + return pxEventBits; + } + +#endif /* configSUPPORT_DYNAMIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +EventBits_t xEventGroupSync( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToSet, + const EventBits_t uxBitsToWaitFor, + TickType_t xTicksToWait ) +{ + EventBits_t uxOriginalBitValue, uxReturn; + EventGroup_t * pxEventBits = xEventGroup; + BaseType_t xAlreadyYielded; + BaseType_t xTimeoutOccurred = pdFALSE; + + configASSERT( ( uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); + configASSERT( uxBitsToWaitFor != 0 ); + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif + + vTaskSuspendAll(); + { + uxOriginalBitValue = pxEventBits->uxEventBits; + + ( void ) xEventGroupSetBits( xEventGroup, uxBitsToSet ); + + if( ( ( uxOriginalBitValue | uxBitsToSet ) & uxBitsToWaitFor ) == uxBitsToWaitFor ) + { + /* All the rendezvous bits are now set - no need to block. */ + uxReturn = ( uxOriginalBitValue | uxBitsToSet ); + + /* Rendezvous always clear the bits. They will have been cleared + * already unless this is the only task in the rendezvous. */ + pxEventBits->uxEventBits &= ~uxBitsToWaitFor; + + xTicksToWait = 0; + } + else + { + if( xTicksToWait != ( TickType_t ) 0 ) + { + traceEVENT_GROUP_SYNC_BLOCK( xEventGroup, uxBitsToSet, uxBitsToWaitFor ); + + /* Store the bits that the calling task is waiting for in the + * task's event list item so the kernel knows when a match is + * found. Then enter the blocked state. */ + vTaskPlaceOnUnorderedEventList( &( pxEventBits->xTasksWaitingForBits ), ( uxBitsToWaitFor | eventCLEAR_EVENTS_ON_EXIT_BIT | eventWAIT_FOR_ALL_BITS ), xTicksToWait ); + + /* This assignment is obsolete as uxReturn will get set after + * the task unblocks, but some compilers mistakenly generate a + * warning about uxReturn being returned without being set if the + * assignment is omitted. */ + uxReturn = 0; + } + else + { + /* The rendezvous bits were not set, but no block time was + * specified - just return the current event bit value. */ + uxReturn = pxEventBits->uxEventBits; + xTimeoutOccurred = pdTRUE; + } + } + } + xAlreadyYielded = xTaskResumeAll(); + + if( xTicksToWait != ( TickType_t ) 0 ) + { + if( xAlreadyYielded == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* The task blocked to wait for its required bits to be set - at this + * point either the required bits were set or the block time expired. If + * the required bits were set they will have been stored in the task's + * event list item, and they should now be retrieved then cleared. */ + uxReturn = uxTaskResetEventItemValue(); + + if( ( uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET ) == ( EventBits_t ) 0 ) + { + /* The task timed out, just return the current event bit value. */ + taskENTER_CRITICAL(); + { + uxReturn = pxEventBits->uxEventBits; + + /* Although the task got here because it timed out before the + * bits it was waiting for were set, it is possible that since it + * unblocked another task has set the bits. If this is the case + * then it needs to clear the bits before exiting. */ + if( ( uxReturn & uxBitsToWaitFor ) == uxBitsToWaitFor ) + { + pxEventBits->uxEventBits &= ~uxBitsToWaitFor; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + + xTimeoutOccurred = pdTRUE; + } + else + { + /* The task unblocked because the bits were set. */ + } + + /* Control bits might be set as the task had blocked should not be + * returned. */ + uxReturn &= ~eventEVENT_BITS_CONTROL_BYTES; + } + + traceEVENT_GROUP_SYNC_END( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTimeoutOccurred ); + + /* Prevent compiler warnings when trace macros are not used. */ + ( void ) xTimeoutOccurred; + + return uxReturn; +} +/*-----------------------------------------------------------*/ + +EventBits_t xEventGroupWaitBits( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToWaitFor, + const BaseType_t xClearOnExit, + const BaseType_t xWaitForAllBits, + TickType_t xTicksToWait ) +{ + EventGroup_t * pxEventBits = xEventGroup; + EventBits_t uxReturn, uxControlBits = 0; + BaseType_t xWaitConditionMet, xAlreadyYielded; + BaseType_t xTimeoutOccurred = pdFALSE; + + /* Check the user is not attempting to wait on the bits used by the kernel + * itself, and that at least one bit is being requested. */ + configASSERT( xEventGroup ); + configASSERT( ( uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); + configASSERT( uxBitsToWaitFor != 0 ); + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif + + vTaskSuspendAll(); + { + const EventBits_t uxCurrentEventBits = pxEventBits->uxEventBits; + + /* Check to see if the wait condition is already met or not. */ + xWaitConditionMet = prvTestWaitCondition( uxCurrentEventBits, uxBitsToWaitFor, xWaitForAllBits ); + + if( xWaitConditionMet != pdFALSE ) + { + /* The wait condition has already been met so there is no need to + * block. */ + uxReturn = uxCurrentEventBits; + xTicksToWait = ( TickType_t ) 0; + + /* Clear the wait bits if requested to do so. */ + if( xClearOnExit != pdFALSE ) + { + pxEventBits->uxEventBits &= ~uxBitsToWaitFor; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else if( xTicksToWait == ( TickType_t ) 0 ) + { + /* The wait condition has not been met, but no block time was + * specified, so just return the current value. */ + uxReturn = uxCurrentEventBits; + xTimeoutOccurred = pdTRUE; + } + else + { + /* The task is going to block to wait for its required bits to be + * set. uxControlBits are used to remember the specified behaviour of + * this call to xEventGroupWaitBits() - for use when the event bits + * unblock the task. */ + if( xClearOnExit != pdFALSE ) + { + uxControlBits |= eventCLEAR_EVENTS_ON_EXIT_BIT; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + if( xWaitForAllBits != pdFALSE ) + { + uxControlBits |= eventWAIT_FOR_ALL_BITS; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Store the bits that the calling task is waiting for in the + * task's event list item so the kernel knows when a match is + * found. Then enter the blocked state. */ + vTaskPlaceOnUnorderedEventList( &( pxEventBits->xTasksWaitingForBits ), ( uxBitsToWaitFor | uxControlBits ), xTicksToWait ); + + /* This is obsolete as it will get set after the task unblocks, but + * some compilers mistakenly generate a warning about the variable + * being returned without being set if it is not done. */ + uxReturn = 0; + + traceEVENT_GROUP_WAIT_BITS_BLOCK( xEventGroup, uxBitsToWaitFor ); + } + } + xAlreadyYielded = xTaskResumeAll(); + + if( xTicksToWait != ( TickType_t ) 0 ) + { + if( xAlreadyYielded == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* The task blocked to wait for its required bits to be set - at this + * point either the required bits were set or the block time expired. If + * the required bits were set they will have been stored in the task's + * event list item, and they should now be retrieved then cleared. */ + uxReturn = uxTaskResetEventItemValue(); + + if( ( uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET ) == ( EventBits_t ) 0 ) + { + taskENTER_CRITICAL(); + { + /* The task timed out, just return the current event bit value. */ + uxReturn = pxEventBits->uxEventBits; + + /* It is possible that the event bits were updated between this + * task leaving the Blocked state and running again. */ + if( prvTestWaitCondition( uxReturn, uxBitsToWaitFor, xWaitForAllBits ) != pdFALSE ) + { + if( xClearOnExit != pdFALSE ) + { + pxEventBits->uxEventBits &= ~uxBitsToWaitFor; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + xTimeoutOccurred = pdTRUE; + } + taskEXIT_CRITICAL(); + } + else + { + /* The task unblocked because the bits were set. */ + } + + /* The task blocked so control bits may have been set. */ + uxReturn &= ~eventEVENT_BITS_CONTROL_BYTES; + } + + traceEVENT_GROUP_WAIT_BITS_END( xEventGroup, uxBitsToWaitFor, xTimeoutOccurred ); + + /* Prevent compiler warnings when trace macros are not used. */ + ( void ) xTimeoutOccurred; + + return uxReturn; +} +/*-----------------------------------------------------------*/ + +EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToClear ) +{ + EventGroup_t * pxEventBits = xEventGroup; + EventBits_t uxReturn; + + /* Check the user is not attempting to clear the bits used by the kernel + * itself. */ + configASSERT( xEventGroup ); + configASSERT( ( uxBitsToClear & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); + + taskENTER_CRITICAL(); + { + traceEVENT_GROUP_CLEAR_BITS( xEventGroup, uxBitsToClear ); + + /* The value returned is the event group value prior to the bits being + * cleared. */ + uxReturn = pxEventBits->uxEventBits; + + /* Clear the bits. */ + pxEventBits->uxEventBits &= ~uxBitsToClear; + } + taskEXIT_CRITICAL(); + + return uxReturn; +} +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) ) + + BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToClear ) + { + BaseType_t xReturn; + + traceEVENT_GROUP_CLEAR_BITS_FROM_ISR( xEventGroup, uxBitsToClear ); + xReturn = xTimerPendFunctionCallFromISR( vEventGroupClearBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToClear, NULL ); /*lint !e9087 Can't avoid cast to void* as a generic callback function not specific to this use case. Callback casts back to original type so safe. */ + + return xReturn; + } + +#endif /* if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) ) */ +/*-----------------------------------------------------------*/ + +EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup ) +{ + UBaseType_t uxSavedInterruptStatus; + EventGroup_t const * const pxEventBits = xEventGroup; + EventBits_t uxReturn; + + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + uxReturn = pxEventBits->uxEventBits; + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + + return uxReturn; +} /*lint !e818 EventGroupHandle_t is a typedef used in other functions to so can't be pointer to const. */ +/*-----------------------------------------------------------*/ + +EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToSet ) +{ + ListItem_t * pxListItem, * pxNext; + ListItem_t const * pxListEnd; + List_t const * pxList; + EventBits_t uxBitsToClear = 0, uxBitsWaitedFor, uxControlBits; + EventGroup_t * pxEventBits = xEventGroup; + BaseType_t xMatchFound = pdFALSE; + + /* Check the user is not attempting to set the bits used by the kernel + * itself. */ + configASSERT( xEventGroup ); + configASSERT( ( uxBitsToSet & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); + + pxList = &( pxEventBits->xTasksWaitingForBits ); + pxListEnd = listGET_END_MARKER( pxList ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ + vTaskSuspendAll(); + { + traceEVENT_GROUP_SET_BITS( xEventGroup, uxBitsToSet ); + + pxListItem = listGET_HEAD_ENTRY( pxList ); + + /* Set the bits. */ + pxEventBits->uxEventBits |= uxBitsToSet; + + /* See if the new bit value should unblock any tasks. */ + while( pxListItem != pxListEnd ) + { + pxNext = listGET_NEXT( pxListItem ); + uxBitsWaitedFor = listGET_LIST_ITEM_VALUE( pxListItem ); + xMatchFound = pdFALSE; + + /* Split the bits waited for from the control bits. */ + uxControlBits = uxBitsWaitedFor & eventEVENT_BITS_CONTROL_BYTES; + uxBitsWaitedFor &= ~eventEVENT_BITS_CONTROL_BYTES; + + if( ( uxControlBits & eventWAIT_FOR_ALL_BITS ) == ( EventBits_t ) 0 ) + { + /* Just looking for single bit being set. */ + if( ( uxBitsWaitedFor & pxEventBits->uxEventBits ) != ( EventBits_t ) 0 ) + { + xMatchFound = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else if( ( uxBitsWaitedFor & pxEventBits->uxEventBits ) == uxBitsWaitedFor ) + { + /* All bits are set. */ + xMatchFound = pdTRUE; + } + else + { + /* Need all bits to be set, but not all the bits were set. */ + } + + if( xMatchFound != pdFALSE ) + { + /* The bits match. Should the bits be cleared on exit? */ + if( ( uxControlBits & eventCLEAR_EVENTS_ON_EXIT_BIT ) != ( EventBits_t ) 0 ) + { + uxBitsToClear |= uxBitsWaitedFor; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Store the actual event flag value in the task's event list + * item before removing the task from the event list. The + * eventUNBLOCKED_DUE_TO_BIT_SET bit is set so the task knows + * that is was unblocked due to its required bits matching, rather + * than because it timed out. */ + vTaskRemoveFromUnorderedEventList( pxListItem, pxEventBits->uxEventBits | eventUNBLOCKED_DUE_TO_BIT_SET ); + } + + /* Move onto the next list item. Note pxListItem->pxNext is not + * used here as the list item may have been removed from the event list + * and inserted into the ready/pending reading list. */ + pxListItem = pxNext; + } + + /* Clear any bits that matched when the eventCLEAR_EVENTS_ON_EXIT_BIT + * bit was set in the control word. */ + pxEventBits->uxEventBits &= ~uxBitsToClear; + } + ( void ) xTaskResumeAll(); + + return pxEventBits->uxEventBits; +} +/*-----------------------------------------------------------*/ + +void vEventGroupDelete( EventGroupHandle_t xEventGroup ) +{ + EventGroup_t * pxEventBits = xEventGroup; + const List_t * pxTasksWaitingForBits; + + configASSERT( pxEventBits ); + + pxTasksWaitingForBits = &( pxEventBits->xTasksWaitingForBits ); + + vTaskSuspendAll(); + { + traceEVENT_GROUP_DELETE( xEventGroup ); + + while( listCURRENT_LIST_LENGTH( pxTasksWaitingForBits ) > ( UBaseType_t ) 0 ) + { + /* Unblock the task, returning 0 as the event list is being deleted + * and cannot therefore have any bits set. */ + configASSERT( pxTasksWaitingForBits->xListEnd.pxNext != ( const ListItem_t * ) &( pxTasksWaitingForBits->xListEnd ) ); + vTaskRemoveFromUnorderedEventList( pxTasksWaitingForBits->xListEnd.pxNext, eventUNBLOCKED_DUE_TO_BIT_SET ); + } + + #if ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) ) + { + /* The event group can only have been allocated dynamically - free + * it again. */ + vPortFree( pxEventBits ); + } + #elif ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + { + /* The event group could have been allocated statically or + * dynamically, so check before attempting to free the memory. */ + if( pxEventBits->ucStaticallyAllocated == ( uint8_t ) pdFALSE ) + { + vPortFree( pxEventBits ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + } + ( void ) xTaskResumeAll(); +} +/*-----------------------------------------------------------*/ + +/* For internal use only - execute a 'set bits' command that was pended from + * an interrupt. */ +void vEventGroupSetBitsCallback( void * pvEventGroup, + const uint32_t ulBitsToSet ) +{ + ( void ) xEventGroupSetBits( pvEventGroup, ( EventBits_t ) ulBitsToSet ); /*lint !e9079 Can't avoid cast to void* as a generic timer callback prototype. Callback casts back to original type so safe. */ +} +/*-----------------------------------------------------------*/ + +/* For internal use only - execute a 'clear bits' command that was pended from + * an interrupt. */ +void vEventGroupClearBitsCallback( void * pvEventGroup, + const uint32_t ulBitsToClear ) +{ + ( void ) xEventGroupClearBits( pvEventGroup, ( EventBits_t ) ulBitsToClear ); /*lint !e9079 Can't avoid cast to void* as a generic timer callback prototype. Callback casts back to original type so safe. */ +} +/*-----------------------------------------------------------*/ + +static BaseType_t prvTestWaitCondition( const EventBits_t uxCurrentEventBits, + const EventBits_t uxBitsToWaitFor, + const BaseType_t xWaitForAllBits ) +{ + BaseType_t xWaitConditionMet = pdFALSE; + + if( xWaitForAllBits == pdFALSE ) + { + /* Task only has to wait for one bit within uxBitsToWaitFor to be + * set. Is one already set? */ + if( ( uxCurrentEventBits & uxBitsToWaitFor ) != ( EventBits_t ) 0 ) + { + xWaitConditionMet = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* Task has to wait for all the bits in uxBitsToWaitFor to be set. + * Are they set already? */ + if( ( uxCurrentEventBits & uxBitsToWaitFor ) == uxBitsToWaitFor ) + { + xWaitConditionMet = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + return xWaitConditionMet; +} +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) ) + + BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToSet, + BaseType_t * pxHigherPriorityTaskWoken ) + { + BaseType_t xReturn; + + traceEVENT_GROUP_SET_BITS_FROM_ISR( xEventGroup, uxBitsToSet ); + xReturn = xTimerPendFunctionCallFromISR( vEventGroupSetBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToSet, pxHigherPriorityTaskWoken ); /*lint !e9087 Can't avoid cast to void* as a generic callback function not specific to this use case. Callback casts back to original type so safe. */ + + return xReturn; + } + +#endif /* if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + UBaseType_t uxEventGroupGetNumber( void * xEventGroup ) + { + UBaseType_t xReturn; + EventGroup_t const * pxEventBits = ( EventGroup_t * ) xEventGroup; /*lint !e9087 !e9079 EventGroupHandle_t is a pointer to an EventGroup_t, but EventGroupHandle_t is kept opaque outside of this file for data hiding purposes. */ + + if( xEventGroup == NULL ) + { + xReturn = 0; + } + else + { + xReturn = pxEventBits->uxEventGroupNumber; + } + + return xReturn; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + void vEventGroupSetNumber( void * xEventGroup, + UBaseType_t uxEventGroupNumber ) + { + ( ( EventGroup_t * ) xEventGroup )->uxEventGroupNumber = uxEventGroupNumber; /*lint !e9087 !e9079 EventGroupHandle_t is a pointer to an EventGroup_t, but EventGroupHandle_t is kept opaque outside of this file for data hiding purposes. */ + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/FreeRTOS.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/FreeRTOS.h new file mode 100644 index 0000000..383f04a --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/FreeRTOS.h @@ -0,0 +1,1362 @@ +/* + * FreeRTOS Kernel V10.4.6 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#ifndef INC_FREERTOS_H +#define INC_FREERTOS_H + +/* + * Include the generic headers required for the FreeRTOS port being used. + */ +#include + +/* + * If stdint.h cannot be located then: + * + If using GCC ensure the -nostdint options is *not* being used. + * + Ensure the project's include path includes the directory in which your + * compiler stores stdint.h. + * + Set any compiler options necessary for it to support C99, as technically + * stdint.h is only mandatory with C99 (FreeRTOS does not require C99 in any + * other way). + * + The FreeRTOS download includes a simple stdint.h definition that can be + * used in cases where none is provided by the compiler. The files only + * contains the typedefs required to build FreeRTOS. Read the instructions + * in FreeRTOS/source/stdint.readme for more information. + */ +#include /* READ COMMENT ABOVE. */ + +/* *INDENT-OFF* */ +#ifdef __cplusplus + extern "C" { +#endif +/* *INDENT-ON* */ + +/* Application specific configuration options. */ +#include "FreeRTOSConfig.h" + +/* Basic FreeRTOS definitions. */ +#include "projdefs.h" + +/* Definitions specific to the port being used. */ +#include "portable.h" + +/* Must be defaulted before configUSE_NEWLIB_REENTRANT is used below. */ +#ifndef configUSE_NEWLIB_REENTRANT + #define configUSE_NEWLIB_REENTRANT 0 +#endif + +/* Required if struct _reent is used. */ +#if ( configUSE_NEWLIB_REENTRANT == 1 ) + #include +#endif + +/* + * Check all the required application specific macros have been defined. + * These macros are application specific and (as downloaded) are defined + * within FreeRTOSConfig.h. + */ + +#ifndef configMINIMAL_STACK_SIZE + #error Missing definition: configMINIMAL_STACK_SIZE must be defined in FreeRTOSConfig.h. configMINIMAL_STACK_SIZE defines the size (in words) of the stack allocated to the idle task. Refer to the demo project provided for your port for a suitable value. +#endif + +#ifndef configMAX_PRIORITIES + #error Missing definition: configMAX_PRIORITIES must be defined in FreeRTOSConfig.h. See the Configuration section of the FreeRTOS API documentation for details. +#endif + +#if configMAX_PRIORITIES < 1 + #error configMAX_PRIORITIES must be defined to be greater than or equal to 1. +#endif + +#ifndef configUSE_PREEMPTION + #error Missing definition: configUSE_PREEMPTION must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. +#endif + +#ifndef configUSE_IDLE_HOOK + #error Missing definition: configUSE_IDLE_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. +#endif + +#ifndef configUSE_TICK_HOOK + #error Missing definition: configUSE_TICK_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. +#endif + +#ifndef configUSE_16_BIT_TICKS + #error Missing definition: configUSE_16_BIT_TICKS must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. +#endif + +#ifndef configUSE_CO_ROUTINES + #define configUSE_CO_ROUTINES 0 +#endif + +#ifndef INCLUDE_vTaskPrioritySet + #define INCLUDE_vTaskPrioritySet 0 +#endif + +#ifndef INCLUDE_uxTaskPriorityGet + #define INCLUDE_uxTaskPriorityGet 0 +#endif + +#ifndef INCLUDE_vTaskDelete + #define INCLUDE_vTaskDelete 0 +#endif + +#ifndef INCLUDE_vTaskSuspend + #define INCLUDE_vTaskSuspend 0 +#endif + +#ifdef INCLUDE_xTaskDelayUntil + #ifdef INCLUDE_vTaskDelayUntil + +/* INCLUDE_vTaskDelayUntil was replaced by INCLUDE_xTaskDelayUntil. Backward + * compatibility is maintained if only one or the other is defined, but + * there is a conflict if both are defined. */ + #error INCLUDE_vTaskDelayUntil and INCLUDE_xTaskDelayUntil are both defined. INCLUDE_vTaskDelayUntil is no longer required and should be removed + #endif +#endif + +#ifndef INCLUDE_xTaskDelayUntil + #ifdef INCLUDE_vTaskDelayUntil + +/* If INCLUDE_vTaskDelayUntil is set but INCLUDE_xTaskDelayUntil is not then + * the project's FreeRTOSConfig.h probably pre-dates the introduction of + * xTaskDelayUntil and setting INCLUDE_xTaskDelayUntil to whatever + * INCLUDE_vTaskDelayUntil is set to will ensure backward compatibility. + */ + #define INCLUDE_xTaskDelayUntil INCLUDE_vTaskDelayUntil + #endif +#endif + +#ifndef INCLUDE_xTaskDelayUntil + #define INCLUDE_xTaskDelayUntil 0 +#endif + +#ifndef INCLUDE_vTaskDelay + #define INCLUDE_vTaskDelay 0 +#endif + +#ifndef INCLUDE_xTaskGetIdleTaskHandle + #define INCLUDE_xTaskGetIdleTaskHandle 0 +#endif + +#ifndef INCLUDE_xTaskAbortDelay + #define INCLUDE_xTaskAbortDelay 0 +#endif + +#ifndef INCLUDE_xQueueGetMutexHolder + #define INCLUDE_xQueueGetMutexHolder 0 +#endif + +#ifndef INCLUDE_xSemaphoreGetMutexHolder + #define INCLUDE_xSemaphoreGetMutexHolder INCLUDE_xQueueGetMutexHolder +#endif + +#ifndef INCLUDE_xTaskGetHandle + #define INCLUDE_xTaskGetHandle 0 +#endif + +#ifndef INCLUDE_uxTaskGetStackHighWaterMark + #define INCLUDE_uxTaskGetStackHighWaterMark 0 +#endif + +#ifndef INCLUDE_uxTaskGetStackHighWaterMark2 + #define INCLUDE_uxTaskGetStackHighWaterMark2 0 +#endif + +#ifndef INCLUDE_eTaskGetState + #define INCLUDE_eTaskGetState 0 +#endif + +#ifndef INCLUDE_xTaskResumeFromISR + #define INCLUDE_xTaskResumeFromISR 1 +#endif + +#ifndef INCLUDE_xTimerPendFunctionCall + #define INCLUDE_xTimerPendFunctionCall 0 +#endif + +#ifndef INCLUDE_xTaskGetSchedulerState + #define INCLUDE_xTaskGetSchedulerState 0 +#endif + +#ifndef INCLUDE_xTaskGetCurrentTaskHandle + #define INCLUDE_xTaskGetCurrentTaskHandle 0 +#endif + +#if configUSE_CO_ROUTINES != 0 + #ifndef configMAX_CO_ROUTINE_PRIORITIES + #error configMAX_CO_ROUTINE_PRIORITIES must be greater than or equal to 1. + #endif +#endif + +#ifndef configUSE_DAEMON_TASK_STARTUP_HOOK + #define configUSE_DAEMON_TASK_STARTUP_HOOK 0 +#endif + +#ifndef configUSE_APPLICATION_TASK_TAG + #define configUSE_APPLICATION_TASK_TAG 0 +#endif + +#ifndef configNUM_THREAD_LOCAL_STORAGE_POINTERS + #define configNUM_THREAD_LOCAL_STORAGE_POINTERS 0 +#endif + +#ifndef configUSE_RECURSIVE_MUTEXES + #define configUSE_RECURSIVE_MUTEXES 0 +#endif + +#ifndef configUSE_MUTEXES + #define configUSE_MUTEXES 0 +#endif + +#ifndef configUSE_TIMERS + #define configUSE_TIMERS 0 +#endif + +#ifndef configUSE_COUNTING_SEMAPHORES + #define configUSE_COUNTING_SEMAPHORES 0 +#endif + +#ifndef configUSE_ALTERNATIVE_API + #define configUSE_ALTERNATIVE_API 0 +#endif + +#ifndef portCRITICAL_NESTING_IN_TCB + #define portCRITICAL_NESTING_IN_TCB 0 +#endif + +#ifndef configMAX_TASK_NAME_LEN + #define configMAX_TASK_NAME_LEN 16 +#endif + +#ifndef configIDLE_SHOULD_YIELD + #define configIDLE_SHOULD_YIELD 1 +#endif + +#if configMAX_TASK_NAME_LEN < 1 + #error configMAX_TASK_NAME_LEN must be set to a minimum of 1 in FreeRTOSConfig.h +#endif + +#ifndef configASSERT + #define configASSERT( x ) + #define configASSERT_DEFINED 0 +#else + #define configASSERT_DEFINED 1 +#endif + +/* configPRECONDITION should be defined as configASSERT. + * The CBMC proofs need a way to track assumptions and assertions. + * A configPRECONDITION statement should express an implicit invariant or + * assumption made. A configASSERT statement should express an invariant that must + * hold explicit before calling the code. */ +#ifndef configPRECONDITION + #define configPRECONDITION( X ) configASSERT( X ) + #define configPRECONDITION_DEFINED 0 +#else + #define configPRECONDITION_DEFINED 1 +#endif + +#ifndef portMEMORY_BARRIER + #define portMEMORY_BARRIER() +#endif + +#ifndef portSOFTWARE_BARRIER + #define portSOFTWARE_BARRIER() +#endif + +/* The timers module relies on xTaskGetSchedulerState(). */ +#if configUSE_TIMERS == 1 + + #ifndef configTIMER_TASK_PRIORITY + #error If configUSE_TIMERS is set to 1 then configTIMER_TASK_PRIORITY must also be defined. + #endif /* configTIMER_TASK_PRIORITY */ + + #ifndef configTIMER_QUEUE_LENGTH + #error If configUSE_TIMERS is set to 1 then configTIMER_QUEUE_LENGTH must also be defined. + #endif /* configTIMER_QUEUE_LENGTH */ + + #ifndef configTIMER_TASK_STACK_DEPTH + #error If configUSE_TIMERS is set to 1 then configTIMER_TASK_STACK_DEPTH must also be defined. + #endif /* configTIMER_TASK_STACK_DEPTH */ + +#endif /* configUSE_TIMERS */ + +#ifndef portSET_INTERRUPT_MASK_FROM_ISR + #define portSET_INTERRUPT_MASK_FROM_ISR() 0 +#endif + +#ifndef portCLEAR_INTERRUPT_MASK_FROM_ISR + #define portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedStatusValue ) ( void ) uxSavedStatusValue +#endif + +#ifndef portCLEAN_UP_TCB + #define portCLEAN_UP_TCB( pxTCB ) ( void ) pxTCB +#endif + +#ifndef portPRE_TASK_DELETE_HOOK + #define portPRE_TASK_DELETE_HOOK( pvTaskToDelete, pxYieldPending ) +#endif + +#ifndef portSETUP_TCB + #define portSETUP_TCB( pxTCB ) ( void ) pxTCB +#endif + +#ifndef configQUEUE_REGISTRY_SIZE + #define configQUEUE_REGISTRY_SIZE 0U +#endif + +#if ( configQUEUE_REGISTRY_SIZE < 1 ) + #define vQueueAddToRegistry( xQueue, pcName ) + #define vQueueUnregisterQueue( xQueue ) + #define pcQueueGetName( xQueue ) +#endif + +#ifndef portPOINTER_SIZE_TYPE + #define portPOINTER_SIZE_TYPE uint32_t +#endif + +/* Remove any unused trace macros. */ +#ifndef traceSTART + +/* Used to perform any necessary initialisation - for example, open a file + * into which trace is to be written. */ + #define traceSTART() +#endif + +#ifndef traceEND + +/* Use to close a trace, for example close a file into which trace has been + * written. */ + #define traceEND() +#endif + +#ifndef traceTASK_SWITCHED_IN + +/* Called after a task has been selected to run. pxCurrentTCB holds a pointer + * to the task control block of the selected task. */ + #define traceTASK_SWITCHED_IN() +#endif + +#ifndef traceINCREASE_TICK_COUNT + +/* Called before stepping the tick count after waking from tickless idle + * sleep. */ + #define traceINCREASE_TICK_COUNT( x ) +#endif + +#ifndef traceLOW_POWER_IDLE_BEGIN + /* Called immediately before entering tickless idle. */ + #define traceLOW_POWER_IDLE_BEGIN() +#endif + +#ifndef traceLOW_POWER_IDLE_END + /* Called when returning to the Idle task after a tickless idle. */ + #define traceLOW_POWER_IDLE_END() +#endif + +#ifndef traceTASK_SWITCHED_OUT + +/* Called before a task has been selected to run. pxCurrentTCB holds a pointer + * to the task control block of the task being switched out. */ + #define traceTASK_SWITCHED_OUT() +#endif + +#ifndef traceTASK_PRIORITY_INHERIT + +/* Called when a task attempts to take a mutex that is already held by a + * lower priority task. pxTCBOfMutexHolder is a pointer to the TCB of the task + * that holds the mutex. uxInheritedPriority is the priority the mutex holder + * will inherit (the priority of the task that is attempting to obtain the + * muted. */ + #define traceTASK_PRIORITY_INHERIT( pxTCBOfMutexHolder, uxInheritedPriority ) +#endif + +#ifndef traceTASK_PRIORITY_DISINHERIT + +/* Called when a task releases a mutex, the holding of which had resulted in + * the task inheriting the priority of a higher priority task. + * pxTCBOfMutexHolder is a pointer to the TCB of the task that is releasing the + * mutex. uxOriginalPriority is the task's configured (base) priority. */ + #define traceTASK_PRIORITY_DISINHERIT( pxTCBOfMutexHolder, uxOriginalPriority ) +#endif + +#ifndef traceBLOCKING_ON_QUEUE_RECEIVE + +/* Task is about to block because it cannot read from a + * queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore + * upon which the read was attempted. pxCurrentTCB points to the TCB of the + * task that attempted the read. */ + #define traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ) +#endif + +#ifndef traceBLOCKING_ON_QUEUE_PEEK + +/* Task is about to block because it cannot read from a + * queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore + * upon which the read was attempted. pxCurrentTCB points to the TCB of the + * task that attempted the read. */ + #define traceBLOCKING_ON_QUEUE_PEEK( pxQueue ) +#endif + +#ifndef traceBLOCKING_ON_QUEUE_SEND + +/* Task is about to block because it cannot write to a + * queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore + * upon which the write was attempted. pxCurrentTCB points to the TCB of the + * task that attempted the write. */ + #define traceBLOCKING_ON_QUEUE_SEND( pxQueue ) +#endif + +#ifndef configCHECK_FOR_STACK_OVERFLOW + #define configCHECK_FOR_STACK_OVERFLOW 0 +#endif + +#ifndef configRECORD_STACK_HIGH_ADDRESS + #define configRECORD_STACK_HIGH_ADDRESS 0 +#endif + +#ifndef configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H + #define configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H 0 +#endif + +/* The following event macros are embedded in the kernel API calls. */ + +#ifndef traceMOVED_TASK_TO_READY_STATE + #define traceMOVED_TASK_TO_READY_STATE( pxTCB ) +#endif + +#ifndef tracePOST_MOVED_TASK_TO_READY_STATE + #define tracePOST_MOVED_TASK_TO_READY_STATE( pxTCB ) +#endif + +#ifndef traceQUEUE_CREATE + #define traceQUEUE_CREATE( pxNewQueue ) +#endif + +#ifndef traceQUEUE_CREATE_FAILED + #define traceQUEUE_CREATE_FAILED( ucQueueType ) +#endif + +#ifndef traceCREATE_MUTEX + #define traceCREATE_MUTEX( pxNewQueue ) +#endif + +#ifndef traceCREATE_MUTEX_FAILED + #define traceCREATE_MUTEX_FAILED() +#endif + +#ifndef traceGIVE_MUTEX_RECURSIVE + #define traceGIVE_MUTEX_RECURSIVE( pxMutex ) +#endif + +#ifndef traceGIVE_MUTEX_RECURSIVE_FAILED + #define traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex ) +#endif + +#ifndef traceTAKE_MUTEX_RECURSIVE + #define traceTAKE_MUTEX_RECURSIVE( pxMutex ) +#endif + +#ifndef traceTAKE_MUTEX_RECURSIVE_FAILED + #define traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex ) +#endif + +#ifndef traceCREATE_COUNTING_SEMAPHORE + #define traceCREATE_COUNTING_SEMAPHORE() +#endif + +#ifndef traceCREATE_COUNTING_SEMAPHORE_FAILED + #define traceCREATE_COUNTING_SEMAPHORE_FAILED() +#endif + +#ifndef traceQUEUE_SET_SEND + #define traceQUEUE_SET_SEND traceQUEUE_SEND +#endif + +#ifndef traceQUEUE_SEND + #define traceQUEUE_SEND( pxQueue ) +#endif + +#ifndef traceQUEUE_SEND_FAILED + #define traceQUEUE_SEND_FAILED( pxQueue ) +#endif + +#ifndef traceQUEUE_RECEIVE + #define traceQUEUE_RECEIVE( pxQueue ) +#endif + +#ifndef traceQUEUE_PEEK + #define traceQUEUE_PEEK( pxQueue ) +#endif + +#ifndef traceQUEUE_PEEK_FAILED + #define traceQUEUE_PEEK_FAILED( pxQueue ) +#endif + +#ifndef traceQUEUE_PEEK_FROM_ISR + #define traceQUEUE_PEEK_FROM_ISR( pxQueue ) +#endif + +#ifndef traceQUEUE_RECEIVE_FAILED + #define traceQUEUE_RECEIVE_FAILED( pxQueue ) +#endif + +#ifndef traceQUEUE_SEND_FROM_ISR + #define traceQUEUE_SEND_FROM_ISR( pxQueue ) +#endif + +#ifndef traceQUEUE_SEND_FROM_ISR_FAILED + #define traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ) +#endif + +#ifndef traceQUEUE_RECEIVE_FROM_ISR + #define traceQUEUE_RECEIVE_FROM_ISR( pxQueue ) +#endif + +#ifndef traceQUEUE_RECEIVE_FROM_ISR_FAILED + #define traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue ) +#endif + +#ifndef traceQUEUE_PEEK_FROM_ISR_FAILED + #define traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue ) +#endif + +#ifndef traceQUEUE_DELETE + #define traceQUEUE_DELETE( pxQueue ) +#endif + +#ifndef traceTASK_CREATE + #define traceTASK_CREATE( pxNewTCB ) +#endif + +#ifndef traceTASK_CREATE_FAILED + #define traceTASK_CREATE_FAILED() +#endif + +#ifndef traceTASK_DELETE + #define traceTASK_DELETE( pxTaskToDelete ) +#endif + +#ifndef traceTASK_DELAY_UNTIL + #define traceTASK_DELAY_UNTIL( x ) +#endif + +#ifndef traceTASK_DELAY + #define traceTASK_DELAY() +#endif + +#ifndef traceTASK_PRIORITY_SET + #define traceTASK_PRIORITY_SET( pxTask, uxNewPriority ) +#endif + +#ifndef traceTASK_SUSPEND + #define traceTASK_SUSPEND( pxTaskToSuspend ) +#endif + +#ifndef traceTASK_RESUME + #define traceTASK_RESUME( pxTaskToResume ) +#endif + +#ifndef traceTASK_RESUME_FROM_ISR + #define traceTASK_RESUME_FROM_ISR( pxTaskToResume ) +#endif + +#ifndef traceTASK_INCREMENT_TICK + #define traceTASK_INCREMENT_TICK( xTickCount ) +#endif + +#ifndef traceTIMER_CREATE + #define traceTIMER_CREATE( pxNewTimer ) +#endif + +#ifndef traceTIMER_CREATE_FAILED + #define traceTIMER_CREATE_FAILED() +#endif + +#ifndef traceTIMER_COMMAND_SEND + #define traceTIMER_COMMAND_SEND( xTimer, xMessageID, xMessageValueValue, xReturn ) +#endif + +#ifndef traceTIMER_EXPIRED + #define traceTIMER_EXPIRED( pxTimer ) +#endif + +#ifndef traceTIMER_COMMAND_RECEIVED + #define traceTIMER_COMMAND_RECEIVED( pxTimer, xMessageID, xMessageValue ) +#endif + +#ifndef traceMALLOC + #define traceMALLOC( pvAddress, uiSize ) +#endif + +#ifndef traceFREE + #define traceFREE( pvAddress, uiSize ) +#endif + +#ifndef traceEVENT_GROUP_CREATE + #define traceEVENT_GROUP_CREATE( xEventGroup ) +#endif + +#ifndef traceEVENT_GROUP_CREATE_FAILED + #define traceEVENT_GROUP_CREATE_FAILED() +#endif + +#ifndef traceEVENT_GROUP_SYNC_BLOCK + #define traceEVENT_GROUP_SYNC_BLOCK( xEventGroup, uxBitsToSet, uxBitsToWaitFor ) +#endif + +#ifndef traceEVENT_GROUP_SYNC_END + #define traceEVENT_GROUP_SYNC_END( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTimeoutOccurred ) ( void ) xTimeoutOccurred +#endif + +#ifndef traceEVENT_GROUP_WAIT_BITS_BLOCK + #define traceEVENT_GROUP_WAIT_BITS_BLOCK( xEventGroup, uxBitsToWaitFor ) +#endif + +#ifndef traceEVENT_GROUP_WAIT_BITS_END + #define traceEVENT_GROUP_WAIT_BITS_END( xEventGroup, uxBitsToWaitFor, xTimeoutOccurred ) ( void ) xTimeoutOccurred +#endif + +#ifndef traceEVENT_GROUP_CLEAR_BITS + #define traceEVENT_GROUP_CLEAR_BITS( xEventGroup, uxBitsToClear ) +#endif + +#ifndef traceEVENT_GROUP_CLEAR_BITS_FROM_ISR + #define traceEVENT_GROUP_CLEAR_BITS_FROM_ISR( xEventGroup, uxBitsToClear ) +#endif + +#ifndef traceEVENT_GROUP_SET_BITS + #define traceEVENT_GROUP_SET_BITS( xEventGroup, uxBitsToSet ) +#endif + +#ifndef traceEVENT_GROUP_SET_BITS_FROM_ISR + #define traceEVENT_GROUP_SET_BITS_FROM_ISR( xEventGroup, uxBitsToSet ) +#endif + +#ifndef traceEVENT_GROUP_DELETE + #define traceEVENT_GROUP_DELETE( xEventGroup ) +#endif + +#ifndef tracePEND_FUNC_CALL + #define tracePEND_FUNC_CALL( xFunctionToPend, pvParameter1, ulParameter2, ret ) +#endif + +#ifndef tracePEND_FUNC_CALL_FROM_ISR + #define tracePEND_FUNC_CALL_FROM_ISR( xFunctionToPend, pvParameter1, ulParameter2, ret ) +#endif + +#ifndef traceQUEUE_REGISTRY_ADD + #define traceQUEUE_REGISTRY_ADD( xQueue, pcQueueName ) +#endif + +#ifndef traceTASK_NOTIFY_TAKE_BLOCK + #define traceTASK_NOTIFY_TAKE_BLOCK( uxIndexToWait ) +#endif + +#ifndef traceTASK_NOTIFY_TAKE + #define traceTASK_NOTIFY_TAKE( uxIndexToWait ) +#endif + +#ifndef traceTASK_NOTIFY_WAIT_BLOCK + #define traceTASK_NOTIFY_WAIT_BLOCK( uxIndexToWait ) +#endif + +#ifndef traceTASK_NOTIFY_WAIT + #define traceTASK_NOTIFY_WAIT( uxIndexToWait ) +#endif + +#ifndef traceTASK_NOTIFY + #define traceTASK_NOTIFY( uxIndexToNotify ) +#endif + +#ifndef traceTASK_NOTIFY_FROM_ISR + #define traceTASK_NOTIFY_FROM_ISR( uxIndexToNotify ) +#endif + +#ifndef traceTASK_NOTIFY_GIVE_FROM_ISR + #define traceTASK_NOTIFY_GIVE_FROM_ISR( uxIndexToNotify ) +#endif + +#ifndef traceSTREAM_BUFFER_CREATE_FAILED + #define traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_CREATE_STATIC_FAILED + #define traceSTREAM_BUFFER_CREATE_STATIC_FAILED( xReturn, xIsMessageBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_CREATE + #define traceSTREAM_BUFFER_CREATE( pxStreamBuffer, xIsMessageBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_DELETE + #define traceSTREAM_BUFFER_DELETE( xStreamBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_RESET + #define traceSTREAM_BUFFER_RESET( xStreamBuffer ) +#endif + +#ifndef traceBLOCKING_ON_STREAM_BUFFER_SEND + #define traceBLOCKING_ON_STREAM_BUFFER_SEND( xStreamBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_SEND + #define traceSTREAM_BUFFER_SEND( xStreamBuffer, xBytesSent ) +#endif + +#ifndef traceSTREAM_BUFFER_SEND_FAILED + #define traceSTREAM_BUFFER_SEND_FAILED( xStreamBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_SEND_FROM_ISR + #define traceSTREAM_BUFFER_SEND_FROM_ISR( xStreamBuffer, xBytesSent ) +#endif + +#ifndef traceBLOCKING_ON_STREAM_BUFFER_RECEIVE + #define traceBLOCKING_ON_STREAM_BUFFER_RECEIVE( xStreamBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_RECEIVE + #define traceSTREAM_BUFFER_RECEIVE( xStreamBuffer, xReceivedLength ) +#endif + +#ifndef traceSTREAM_BUFFER_RECEIVE_FAILED + #define traceSTREAM_BUFFER_RECEIVE_FAILED( xStreamBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_RECEIVE_FROM_ISR + #define traceSTREAM_BUFFER_RECEIVE_FROM_ISR( xStreamBuffer, xReceivedLength ) +#endif + +#ifndef configGENERATE_RUN_TIME_STATS + #define configGENERATE_RUN_TIME_STATS 0 +#endif + +#if ( configGENERATE_RUN_TIME_STATS == 1 ) + + #ifndef portCONFIGURE_TIMER_FOR_RUN_TIME_STATS + #error If configGENERATE_RUN_TIME_STATS is defined then portCONFIGURE_TIMER_FOR_RUN_TIME_STATS must also be defined. portCONFIGURE_TIMER_FOR_RUN_TIME_STATS should call a port layer function to setup a peripheral timer/counter that can then be used as the run time counter time base. + #endif /* portCONFIGURE_TIMER_FOR_RUN_TIME_STATS */ + + #ifndef portGET_RUN_TIME_COUNTER_VALUE + #ifndef portALT_GET_RUN_TIME_COUNTER_VALUE + #error If configGENERATE_RUN_TIME_STATS is defined then either portGET_RUN_TIME_COUNTER_VALUE or portALT_GET_RUN_TIME_COUNTER_VALUE must also be defined. See the examples provided and the FreeRTOS web site for more information. + #endif /* portALT_GET_RUN_TIME_COUNTER_VALUE */ + #endif /* portGET_RUN_TIME_COUNTER_VALUE */ + +#endif /* configGENERATE_RUN_TIME_STATS */ + +#ifndef portCONFIGURE_TIMER_FOR_RUN_TIME_STATS + #define portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() +#endif + +#ifndef configUSE_MALLOC_FAILED_HOOK + #define configUSE_MALLOC_FAILED_HOOK 0 +#endif + +#ifndef portPRIVILEGE_BIT + #define portPRIVILEGE_BIT ( ( UBaseType_t ) 0x00 ) +#endif + +#ifndef portYIELD_WITHIN_API + #define portYIELD_WITHIN_API portYIELD +#endif + +#ifndef portSUPPRESS_TICKS_AND_SLEEP + #define portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ) +#endif + +#ifndef configEXPECTED_IDLE_TIME_BEFORE_SLEEP + #define configEXPECTED_IDLE_TIME_BEFORE_SLEEP 2 +#endif + +#if configEXPECTED_IDLE_TIME_BEFORE_SLEEP < 2 + #error configEXPECTED_IDLE_TIME_BEFORE_SLEEP must not be less than 2 +#endif + +#ifndef configUSE_TICKLESS_IDLE + #define configUSE_TICKLESS_IDLE 0 +#endif + +#ifndef configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING + #define configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING( x ) +#endif + +#ifndef configPRE_SLEEP_PROCESSING + #define configPRE_SLEEP_PROCESSING( x ) +#endif + +#ifndef configPOST_SLEEP_PROCESSING + #define configPOST_SLEEP_PROCESSING( x ) +#endif + +#ifndef configUSE_QUEUE_SETS + #define configUSE_QUEUE_SETS 0 +#endif + +#ifndef portTASK_USES_FLOATING_POINT + #define portTASK_USES_FLOATING_POINT() +#endif + +#ifndef portALLOCATE_SECURE_CONTEXT + #define portALLOCATE_SECURE_CONTEXT( ulSecureStackSize ) +#endif + +#ifndef portDONT_DISCARD + #define portDONT_DISCARD +#endif + +#ifndef configUSE_TIME_SLICING + #define configUSE_TIME_SLICING 1 +#endif + +#ifndef configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS + #define configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS 0 +#endif + +#ifndef configUSE_STATS_FORMATTING_FUNCTIONS + #define configUSE_STATS_FORMATTING_FUNCTIONS 0 +#endif + +#ifndef portASSERT_IF_INTERRUPT_PRIORITY_INVALID + #define portASSERT_IF_INTERRUPT_PRIORITY_INVALID() +#endif + +#ifndef configUSE_TRACE_FACILITY + #define configUSE_TRACE_FACILITY 0 +#endif + +#ifndef mtCOVERAGE_TEST_MARKER + #define mtCOVERAGE_TEST_MARKER() +#endif + +#ifndef mtCOVERAGE_TEST_DELAY + #define mtCOVERAGE_TEST_DELAY() +#endif + +#ifndef portASSERT_IF_IN_ISR + #define portASSERT_IF_IN_ISR() +#endif + +#ifndef configUSE_PORT_OPTIMISED_TASK_SELECTION + #define configUSE_PORT_OPTIMISED_TASK_SELECTION 0 +#endif + +#ifndef configAPPLICATION_ALLOCATED_HEAP + #define configAPPLICATION_ALLOCATED_HEAP 0 +#endif + +#ifndef configUSE_TASK_NOTIFICATIONS + #define configUSE_TASK_NOTIFICATIONS 1 +#endif + +#ifndef configTASK_NOTIFICATION_ARRAY_ENTRIES + #define configTASK_NOTIFICATION_ARRAY_ENTRIES 1 +#endif + +#if configTASK_NOTIFICATION_ARRAY_ENTRIES < 1 + #error configTASK_NOTIFICATION_ARRAY_ENTRIES must be at least 1 +#endif + +#ifndef configUSE_POSIX_ERRNO + #define configUSE_POSIX_ERRNO 0 +#endif + +#ifndef portTICK_TYPE_IS_ATOMIC + #define portTICK_TYPE_IS_ATOMIC 0 +#endif + +#ifndef configSUPPORT_STATIC_ALLOCATION + /* Defaults to 0 for backward compatibility. */ + #define configSUPPORT_STATIC_ALLOCATION 0 +#endif + +#ifndef configSUPPORT_DYNAMIC_ALLOCATION + /* Defaults to 1 for backward compatibility. */ + #define configSUPPORT_DYNAMIC_ALLOCATION 1 +#endif + +#ifndef configSTACK_DEPTH_TYPE + +/* Defaults to uint16_t for backward compatibility, but can be overridden + * in FreeRTOSConfig.h if uint16_t is too restrictive. */ + #define configSTACK_DEPTH_TYPE uint16_t +#endif + +#ifndef configRUN_TIME_COUNTER_TYPE + +/* Defaults to uint32_t for backward compatibility, but can be overridden in + * FreeRTOSConfig.h if uint32_t is too restrictive. */ + + #define configRUN_TIME_COUNTER_TYPE uint32_t +#endif + +#ifndef configMESSAGE_BUFFER_LENGTH_TYPE + +/* Defaults to size_t for backward compatibility, but can be overridden + * in FreeRTOSConfig.h if lengths will always be less than the number of bytes + * in a size_t. */ + #define configMESSAGE_BUFFER_LENGTH_TYPE size_t +#endif + +/* Sanity check the configuration. */ +#if ( configUSE_TICKLESS_IDLE != 0 ) + #if ( INCLUDE_vTaskSuspend != 1 ) + #error INCLUDE_vTaskSuspend must be set to 1 if configUSE_TICKLESS_IDLE is not set to 0 + #endif /* INCLUDE_vTaskSuspend */ +#endif /* configUSE_TICKLESS_IDLE */ + +#if ( ( configSUPPORT_STATIC_ALLOCATION == 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) ) + #error configSUPPORT_STATIC_ALLOCATION and configSUPPORT_DYNAMIC_ALLOCATION cannot both be 0, but can both be 1. +#endif + +#if ( ( configUSE_RECURSIVE_MUTEXES == 1 ) && ( configUSE_MUTEXES != 1 ) ) + #error configUSE_MUTEXES must be set to 1 to use recursive mutexes +#endif + +#ifndef configINITIAL_TICK_COUNT + #define configINITIAL_TICK_COUNT 0 +#endif + +#if ( portTICK_TYPE_IS_ATOMIC == 0 ) + +/* Either variables of tick type cannot be read atomically, or + * portTICK_TYPE_IS_ATOMIC was not set - map the critical sections used when + * the tick count is returned to the standard critical section macros. */ + #define portTICK_TYPE_ENTER_CRITICAL() portENTER_CRITICAL() + #define portTICK_TYPE_EXIT_CRITICAL() portEXIT_CRITICAL() + #define portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR() portSET_INTERRUPT_MASK_FROM_ISR() + #define portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( x ) portCLEAR_INTERRUPT_MASK_FROM_ISR( ( x ) ) +#else + +/* The tick type can be read atomically, so critical sections used when the + * tick count is returned can be defined away. */ + #define portTICK_TYPE_ENTER_CRITICAL() + #define portTICK_TYPE_EXIT_CRITICAL() + #define portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR() 0 + #define portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( x ) ( void ) x +#endif /* if ( portTICK_TYPE_IS_ATOMIC == 0 ) */ + +/* Definitions to allow backward compatibility with FreeRTOS versions prior to + * V8 if desired. */ +#ifndef configENABLE_BACKWARD_COMPATIBILITY + #define configENABLE_BACKWARD_COMPATIBILITY 1 +#endif + +#ifndef configPRINTF + +/* configPRINTF() was not defined, so define it away to nothing. To use + * configPRINTF() then define it as follows (where MyPrintFunction() is + * provided by the application writer): + * + * void MyPrintFunction(const char *pcFormat, ... ); + #define configPRINTF( X ) MyPrintFunction X + * + * Then call like a standard printf() function, but placing brackets around + * all parameters so they are passed as a single parameter. For example: + * configPRINTF( ("Value = %d", MyVariable) ); */ + #define configPRINTF( X ) +#endif + +#ifndef configMAX + +/* The application writer has not provided their own MAX macro, so define + * the following generic implementation. */ + #define configMAX( a, b ) ( ( ( a ) > ( b ) ) ? ( a ) : ( b ) ) +#endif + +#ifndef configMIN + +/* The application writer has not provided their own MIN macro, so define + * the following generic implementation. */ + #define configMIN( a, b ) ( ( ( a ) < ( b ) ) ? ( a ) : ( b ) ) +#endif + +#if configENABLE_BACKWARD_COMPATIBILITY == 1 + #define eTaskStateGet eTaskGetState + #define portTickType TickType_t + #define xTaskHandle TaskHandle_t + #define xQueueHandle QueueHandle_t + #define xSemaphoreHandle SemaphoreHandle_t + #define xQueueSetHandle QueueSetHandle_t + #define xQueueSetMemberHandle QueueSetMemberHandle_t + #define xTimeOutType TimeOut_t + #define xMemoryRegion MemoryRegion_t + #define xTaskParameters TaskParameters_t + #define xTaskStatusType TaskStatus_t + #define xTimerHandle TimerHandle_t + #define xCoRoutineHandle CoRoutineHandle_t + #define pdTASK_HOOK_CODE TaskHookFunction_t + #define portTICK_RATE_MS portTICK_PERIOD_MS + #define pcTaskGetTaskName pcTaskGetName + #define pcTimerGetTimerName pcTimerGetName + #define pcQueueGetQueueName pcQueueGetName + #define vTaskGetTaskInfo vTaskGetInfo + #define xTaskGetIdleRunTimeCounter ulTaskGetIdleRunTimeCounter + +/* Backward compatibility within the scheduler code only - these definitions + * are not really required but are included for completeness. */ + #define tmrTIMER_CALLBACK TimerCallbackFunction_t + #define pdTASK_CODE TaskFunction_t + #define xListItem ListItem_t + #define xList List_t + +/* For libraries that break the list data hiding, and access list structure + * members directly (which is not supposed to be done). */ + #define pxContainer pvContainer +#endif /* configENABLE_BACKWARD_COMPATIBILITY */ + +#if ( configUSE_ALTERNATIVE_API != 0 ) + #error The alternative API was deprecated some time ago, and was removed in FreeRTOS V9.0 0 +#endif + +/* Set configUSE_TASK_FPU_SUPPORT to 0 to omit floating point support even + * if floating point hardware is otherwise supported by the FreeRTOS port in use. + * This constant is not supported by all FreeRTOS ports that include floating + * point support. */ +#ifndef configUSE_TASK_FPU_SUPPORT + #define configUSE_TASK_FPU_SUPPORT 1 +#endif + +/* Set configENABLE_MPU to 1 to enable MPU support and 0 to disable it. This is + * currently used in ARMv8M ports. */ +#ifndef configENABLE_MPU + #define configENABLE_MPU 0 +#endif + +/* Set configENABLE_FPU to 1 to enable FPU support and 0 to disable it. This is + * currently used in ARMv8M ports. */ +#ifndef configENABLE_FPU + #define configENABLE_FPU 1 +#endif + +/* Set configENABLE_TRUSTZONE to 1 enable TrustZone support and 0 to disable it. + * This is currently used in ARMv8M ports. */ +#ifndef configENABLE_TRUSTZONE + #define configENABLE_TRUSTZONE 1 +#endif + +/* Set configRUN_FREERTOS_SECURE_ONLY to 1 to run the FreeRTOS ARMv8M port on + * the Secure Side only. */ +#ifndef configRUN_FREERTOS_SECURE_ONLY + #define configRUN_FREERTOS_SECURE_ONLY 0 +#endif + +#ifndef configRUN_ADDITIONAL_TESTS + #define configRUN_ADDITIONAL_TESTS 0 +#endif + + +/* Sometimes the FreeRTOSConfig.h settings only allow a task to be created using + * dynamically allocated RAM, in which case when any task is deleted it is known + * that both the task's stack and TCB need to be freed. Sometimes the + * FreeRTOSConfig.h settings only allow a task to be created using statically + * allocated RAM, in which case when any task is deleted it is known that neither + * the task's stack or TCB should be freed. Sometimes the FreeRTOSConfig.h + * settings allow a task to be created using either statically or dynamically + * allocated RAM, in which case a member of the TCB is used to record whether the + * stack and/or TCB were allocated statically or dynamically, so when a task is + * deleted the RAM that was allocated dynamically is freed again and no attempt is + * made to free the RAM that was allocated statically. + * tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE is only true if it is possible for a + * task to be created using either statically or dynamically allocated RAM. Note + * that if portUSING_MPU_WRAPPERS is 1 then a protected task can be created with + * a statically allocated stack and a dynamically allocated TCB. + * + * The following table lists various combinations of portUSING_MPU_WRAPPERS, + * configSUPPORT_DYNAMIC_ALLOCATION and configSUPPORT_STATIC_ALLOCATION and + * when it is possible to have both static and dynamic allocation: + * +-----+---------+--------+-----------------------------+-----------------------------------+------------------+-----------+ + * | MPU | Dynamic | Static | Available Functions | Possible Allocations | Both Dynamic and | Need Free | + * | | | | | | Static Possible | | + * +-----+---------+--------+-----------------------------+-----------------------------------+------------------+-----------+ + * | 0 | 0 | 1 | xTaskCreateStatic | TCB - Static, Stack - Static | No | No | + * +-----|---------|--------|-----------------------------|-----------------------------------|------------------|-----------| + * | 0 | 1 | 0 | xTaskCreate | TCB - Dynamic, Stack - Dynamic | No | Yes | + * +-----|---------|--------|-----------------------------|-----------------------------------|------------------|-----------| + * | 0 | 1 | 1 | xTaskCreate, | 1. TCB - Dynamic, Stack - Dynamic | Yes | Yes | + * | | | | xTaskCreateStatic | 2. TCB - Static, Stack - Static | | | + * +-----|---------|--------|-----------------------------|-----------------------------------|------------------|-----------| + * | 1 | 0 | 1 | xTaskCreateStatic, | TCB - Static, Stack - Static | No | No | + * | | | | xTaskCreateRestrictedStatic | | | | + * +-----|---------|--------|-----------------------------|-----------------------------------|------------------|-----------| + * | 1 | 1 | 0 | xTaskCreate, | 1. TCB - Dynamic, Stack - Dynamic | Yes | Yes | + * | | | | xTaskCreateRestricted | 2. TCB - Dynamic, Stack - Static | | | + * +-----|---------|--------|-----------------------------|-----------------------------------|------------------|-----------| + * | 1 | 1 | 1 | xTaskCreate, | 1. TCB - Dynamic, Stack - Dynamic | Yes | Yes | + * | | | | xTaskCreateStatic, | 2. TCB - Dynamic, Stack - Static | | | + * | | | | xTaskCreateRestricted, | 3. TCB - Static, Stack - Static | | | + * | | | | xTaskCreateRestrictedStatic | | | | + * +-----+---------+--------+-----------------------------+-----------------------------------+------------------+-----------+ + */ +#define tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE \ + ( ( ( portUSING_MPU_WRAPPERS == 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) || \ + ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) ) + +/* + * In line with software engineering best practice, FreeRTOS implements a strict + * data hiding policy, so the real structures used by FreeRTOS to maintain the + * state of tasks, queues, semaphores, etc. are not accessible to the application + * code. However, if the application writer wants to statically allocate such + * an object then the size of the object needs to be known. Dummy structures + * that are guaranteed to have the same size and alignment requirements of the + * real objects are used for this purpose. The dummy list and list item + * structures below are used for inclusion in such a dummy structure. + */ +struct xSTATIC_LIST_ITEM +{ + #if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy1; + #endif + TickType_t xDummy2; + void * pvDummy3[ 4 ]; + #if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy4; + #endif +}; +typedef struct xSTATIC_LIST_ITEM StaticListItem_t; + +/* See the comments above the struct xSTATIC_LIST_ITEM definition. */ +struct xSTATIC_MINI_LIST_ITEM +{ + #if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy1; + #endif + TickType_t xDummy2; + void * pvDummy3[ 2 ]; +}; +typedef struct xSTATIC_MINI_LIST_ITEM StaticMiniListItem_t; + +/* See the comments above the struct xSTATIC_LIST_ITEM definition. */ +typedef struct xSTATIC_LIST +{ + #if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy1; + #endif + UBaseType_t uxDummy2; + void * pvDummy3; + StaticMiniListItem_t xDummy4; + #if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy5; + #endif +} StaticList_t; + +/* + * In line with software engineering best practice, especially when supplying a + * library that is likely to change in future versions, FreeRTOS implements a + * strict data hiding policy. This means the Task structure used internally by + * FreeRTOS is not accessible to application code. However, if the application + * writer wants to statically allocate the memory required to create a task then + * the size of the task object needs to be known. The StaticTask_t structure + * below is provided for this purpose. Its sizes and alignment requirements are + * guaranteed to match those of the genuine structure, no matter which + * architecture is being used, and no matter how the values in FreeRTOSConfig.h + * are set. Its contents are somewhat obfuscated in the hope users will + * recognise that it would be unwise to make direct use of the structure members. + */ +typedef struct xSTATIC_TCB +{ + void * pxDummy1; + #if ( portUSING_MPU_WRAPPERS == 1 ) + xMPU_SETTINGS xDummy2; + #endif + StaticListItem_t xDummy3[ 2 ]; + UBaseType_t uxDummy5; + void * pxDummy6; + uint8_t ucDummy7[ configMAX_TASK_NAME_LEN ]; + #if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) ) + void * pxDummy8; + #endif + #if ( portCRITICAL_NESTING_IN_TCB == 1 ) + UBaseType_t uxDummy9; + #endif + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy10[ 2 ]; + #endif + #if ( configUSE_MUTEXES == 1 ) + UBaseType_t uxDummy12[ 2 ]; + #endif + #if ( configUSE_APPLICATION_TASK_TAG == 1 ) + void * pxDummy14; + #endif + #if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) + void * pvDummy15[ configNUM_THREAD_LOCAL_STORAGE_POINTERS ]; + #endif + #if ( configGENERATE_RUN_TIME_STATS == 1 ) + configRUN_TIME_COUNTER_TYPE ulDummy16; + #endif + #if ( configUSE_NEWLIB_REENTRANT == 1 ) + struct _reent xDummy17; + #endif + #if ( configUSE_TASK_NOTIFICATIONS == 1 ) + uint32_t ulDummy18[ configTASK_NOTIFICATION_ARRAY_ENTRIES ]; + uint8_t ucDummy19[ configTASK_NOTIFICATION_ARRAY_ENTRIES ]; + #endif + #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) + uint8_t uxDummy20; + #endif + + #if ( INCLUDE_xTaskAbortDelay == 1 ) + uint8_t ucDummy21; + #endif + #if ( configUSE_POSIX_ERRNO == 1 ) + int iDummy22; + #endif +} StaticTask_t; + +/* + * In line with software engineering best practice, especially when supplying a + * library that is likely to change in future versions, FreeRTOS implements a + * strict data hiding policy. This means the Queue structure used internally by + * FreeRTOS is not accessible to application code. However, if the application + * writer wants to statically allocate the memory required to create a queue + * then the size of the queue object needs to be known. The StaticQueue_t + * structure below is provided for this purpose. Its sizes and alignment + * requirements are guaranteed to match those of the genuine structure, no + * matter which architecture is being used, and no matter how the values in + * FreeRTOSConfig.h are set. Its contents are somewhat obfuscated in the hope + * users will recognise that it would be unwise to make direct use of the + * structure members. + */ +typedef struct xSTATIC_QUEUE +{ + void * pvDummy1[ 3 ]; + + union + { + void * pvDummy2; + UBaseType_t uxDummy2; + } u; + + StaticList_t xDummy3[ 2 ]; + UBaseType_t uxDummy4[ 3 ]; + uint8_t ucDummy5[ 2 ]; + + #if ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + uint8_t ucDummy6; + #endif + + #if ( configUSE_QUEUE_SETS == 1 ) + void * pvDummy7; + #endif + + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy8; + uint8_t ucDummy9; + #endif +} StaticQueue_t; +typedef StaticQueue_t StaticSemaphore_t; + +/* + * In line with software engineering best practice, especially when supplying a + * library that is likely to change in future versions, FreeRTOS implements a + * strict data hiding policy. This means the event group structure used + * internally by FreeRTOS is not accessible to application code. However, if + * the application writer wants to statically allocate the memory required to + * create an event group then the size of the event group object needs to be + * know. The StaticEventGroup_t structure below is provided for this purpose. + * Its sizes and alignment requirements are guaranteed to match those of the + * genuine structure, no matter which architecture is being used, and no matter + * how the values in FreeRTOSConfig.h are set. Its contents are somewhat + * obfuscated in the hope users will recognise that it would be unwise to make + * direct use of the structure members. + */ +typedef struct xSTATIC_EVENT_GROUP +{ + TickType_t xDummy1; + StaticList_t xDummy2; + + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy3; + #endif + + #if ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + uint8_t ucDummy4; + #endif +} StaticEventGroup_t; + +/* + * In line with software engineering best practice, especially when supplying a + * library that is likely to change in future versions, FreeRTOS implements a + * strict data hiding policy. This means the software timer structure used + * internally by FreeRTOS is not accessible to application code. However, if + * the application writer wants to statically allocate the memory required to + * create a software timer then the size of the queue object needs to be known. + * The StaticTimer_t structure below is provided for this purpose. Its sizes + * and alignment requirements are guaranteed to match those of the genuine + * structure, no matter which architecture is being used, and no matter how the + * values in FreeRTOSConfig.h are set. Its contents are somewhat obfuscated in + * the hope users will recognise that it would be unwise to make direct use of + * the structure members. + */ +typedef struct xSTATIC_TIMER +{ + void * pvDummy1; + StaticListItem_t xDummy2; + TickType_t xDummy3; + void * pvDummy5; + TaskFunction_t pvDummy6; + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy7; + #endif + uint8_t ucDummy8; +} StaticTimer_t; + +/* + * In line with software engineering best practice, especially when supplying a + * library that is likely to change in future versions, FreeRTOS implements a + * strict data hiding policy. This means the stream buffer structure used + * internally by FreeRTOS is not accessible to application code. However, if + * the application writer wants to statically allocate the memory required to + * create a stream buffer then the size of the stream buffer object needs to be + * known. The StaticStreamBuffer_t structure below is provided for this + * purpose. Its size and alignment requirements are guaranteed to match those + * of the genuine structure, no matter which architecture is being used, and + * no matter how the values in FreeRTOSConfig.h are set. Its contents are + * somewhat obfuscated in the hope users will recognise that it would be unwise + * to make direct use of the structure members. + */ +typedef struct xSTATIC_STREAM_BUFFER +{ + size_t uxDummy1[ 4 ]; + void * pvDummy2[ 3 ]; + uint8_t ucDummy3; + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy4; + #endif +} StaticStreamBuffer_t; + +/* Message buffers are built on stream buffers. */ +typedef StaticStreamBuffer_t StaticMessageBuffer_t; + +/* *INDENT-OFF* */ +#ifdef __cplusplus + } +#endif +/* *INDENT-ON* */ + +#endif /* INC_FREERTOS_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/StackMacros.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/StackMacros.h new file mode 100644 index 0000000..6ddeb3a --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/StackMacros.h @@ -0,0 +1,34 @@ +/* + * FreeRTOS Kernel V10.4.6 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + + +#ifndef _MSC_VER /* Visual Studio doesn't support #warning. */ + #warning The name of this file has changed to stack_macros.h. Please update your code accordingly. This source file (which has the original name) will be removed in future released. +#endif + +#include "stack_macros.h" diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/atomic.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/atomic.h new file mode 100644 index 0000000..8d7c107 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/atomic.h @@ -0,0 +1,419 @@ +/* + * FreeRTOS Kernel V10.4.6 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/** + * @file atomic.h + * @brief FreeRTOS atomic operation support. + * + * This file implements atomic functions by disabling interrupts globally. + * Implementations with architecture specific atomic instructions can be + * provided under each compiler directory. + */ + +#ifndef ATOMIC_H +#define ATOMIC_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h must appear in source files before include atomic.h" +#endif + +/* Standard includes. */ +#include + +/* *INDENT-OFF* */ +#ifdef __cplusplus + extern "C" { +#endif +/* *INDENT-ON* */ + +/* + * Port specific definitions -- entering/exiting critical section. + * Refer template -- ./lib/FreeRTOS/portable/Compiler/Arch/portmacro.h + * + * Every call to ATOMIC_EXIT_CRITICAL() must be closely paired with + * ATOMIC_ENTER_CRITICAL(). + * + */ +#if defined( portSET_INTERRUPT_MASK_FROM_ISR ) + +/* Nested interrupt scheme is supported in this port. */ + #define ATOMIC_ENTER_CRITICAL() \ + UBaseType_t uxCriticalSectionType = portSET_INTERRUPT_MASK_FROM_ISR() + + #define ATOMIC_EXIT_CRITICAL() \ + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxCriticalSectionType ) + +#else + +/* Nested interrupt scheme is NOT supported in this port. */ + #define ATOMIC_ENTER_CRITICAL() portENTER_CRITICAL() + #define ATOMIC_EXIT_CRITICAL() portEXIT_CRITICAL() + +#endif /* portSET_INTERRUPT_MASK_FROM_ISR() */ + +/* + * Port specific definition -- "always inline". + * Inline is compiler specific, and may not always get inlined depending on your + * optimization level. Also, inline is considered as performance optimization + * for atomic. Thus, if portFORCE_INLINE is not provided by portmacro.h, + * instead of resulting error, simply define it away. + */ +#ifndef portFORCE_INLINE + #define portFORCE_INLINE +#endif + +#define ATOMIC_COMPARE_AND_SWAP_SUCCESS 0x1U /**< Compare and swap succeeded, swapped. */ +#define ATOMIC_COMPARE_AND_SWAP_FAILURE 0x0U /**< Compare and swap failed, did not swap. */ + +/*----------------------------- Swap && CAS ------------------------------*/ + +/** + * Atomic compare-and-swap + * + * @brief Performs an atomic compare-and-swap operation on the specified values. + * + * @param[in, out] pulDestination Pointer to memory location from where value is + * to be loaded and checked. + * @param[in] ulExchange If condition meets, write this value to memory. + * @param[in] ulComparand Swap condition. + * + * @return Unsigned integer of value 1 or 0. 1 for swapped, 0 for not swapped. + * + * @note This function only swaps *pulDestination with ulExchange, if previous + * *pulDestination value equals ulComparand. + */ +static portFORCE_INLINE uint32_t Atomic_CompareAndSwap_u32( uint32_t volatile * pulDestination, + uint32_t ulExchange, + uint32_t ulComparand ) +{ + uint32_t ulReturnValue; + + ATOMIC_ENTER_CRITICAL(); + { + if( *pulDestination == ulComparand ) + { + *pulDestination = ulExchange; + ulReturnValue = ATOMIC_COMPARE_AND_SWAP_SUCCESS; + } + else + { + ulReturnValue = ATOMIC_COMPARE_AND_SWAP_FAILURE; + } + } + ATOMIC_EXIT_CRITICAL(); + + return ulReturnValue; +} +/*-----------------------------------------------------------*/ + +/** + * Atomic swap (pointers) + * + * @brief Atomically sets the address pointed to by *ppvDestination to the value + * of *pvExchange. + * + * @param[in, out] ppvDestination Pointer to memory location from where a pointer + * value is to be loaded and written back to. + * @param[in] pvExchange Pointer value to be written to *ppvDestination. + * + * @return The initial value of *ppvDestination. + */ +static portFORCE_INLINE void * Atomic_SwapPointers_p32( void * volatile * ppvDestination, + void * pvExchange ) +{ + void * pReturnValue; + + ATOMIC_ENTER_CRITICAL(); + { + pReturnValue = *ppvDestination; + *ppvDestination = pvExchange; + } + ATOMIC_EXIT_CRITICAL(); + + return pReturnValue; +} +/*-----------------------------------------------------------*/ + +/** + * Atomic compare-and-swap (pointers) + * + * @brief Performs an atomic compare-and-swap operation on the specified pointer + * values. + * + * @param[in, out] ppvDestination Pointer to memory location from where a pointer + * value is to be loaded and checked. + * @param[in] pvExchange If condition meets, write this value to memory. + * @param[in] pvComparand Swap condition. + * + * @return Unsigned integer of value 1 or 0. 1 for swapped, 0 for not swapped. + * + * @note This function only swaps *ppvDestination with pvExchange, if previous + * *ppvDestination value equals pvComparand. + */ +static portFORCE_INLINE uint32_t Atomic_CompareAndSwapPointers_p32( void * volatile * ppvDestination, + void * pvExchange, + void * pvComparand ) +{ + uint32_t ulReturnValue = ATOMIC_COMPARE_AND_SWAP_FAILURE; + + ATOMIC_ENTER_CRITICAL(); + { + if( *ppvDestination == pvComparand ) + { + *ppvDestination = pvExchange; + ulReturnValue = ATOMIC_COMPARE_AND_SWAP_SUCCESS; + } + } + ATOMIC_EXIT_CRITICAL(); + + return ulReturnValue; +} + + +/*----------------------------- Arithmetic ------------------------------*/ + +/** + * Atomic add + * + * @brief Atomically adds count to the value of the specified pointer points to. + * + * @param[in,out] pulAddend Pointer to memory location from where value is to be + * loaded and written back to. + * @param[in] ulCount Value to be added to *pulAddend. + * + * @return previous *pulAddend value. + */ +static portFORCE_INLINE uint32_t Atomic_Add_u32( uint32_t volatile * pulAddend, + uint32_t ulCount ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + { + ulCurrent = *pulAddend; + *pulAddend += ulCount; + } + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} +/*-----------------------------------------------------------*/ + +/** + * Atomic subtract + * + * @brief Atomically subtracts count from the value of the specified pointer + * pointers to. + * + * @param[in,out] pulAddend Pointer to memory location from where value is to be + * loaded and written back to. + * @param[in] ulCount Value to be subtract from *pulAddend. + * + * @return previous *pulAddend value. + */ +static portFORCE_INLINE uint32_t Atomic_Subtract_u32( uint32_t volatile * pulAddend, + uint32_t ulCount ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + { + ulCurrent = *pulAddend; + *pulAddend -= ulCount; + } + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} +/*-----------------------------------------------------------*/ + +/** + * Atomic increment + * + * @brief Atomically increments the value of the specified pointer points to. + * + * @param[in,out] pulAddend Pointer to memory location from where value is to be + * loaded and written back to. + * + * @return *pulAddend value before increment. + */ +static portFORCE_INLINE uint32_t Atomic_Increment_u32( uint32_t volatile * pulAddend ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + { + ulCurrent = *pulAddend; + *pulAddend += 1; + } + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} +/*-----------------------------------------------------------*/ + +/** + * Atomic decrement + * + * @brief Atomically decrements the value of the specified pointer points to + * + * @param[in,out] pulAddend Pointer to memory location from where value is to be + * loaded and written back to. + * + * @return *pulAddend value before decrement. + */ +static portFORCE_INLINE uint32_t Atomic_Decrement_u32( uint32_t volatile * pulAddend ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + { + ulCurrent = *pulAddend; + *pulAddend -= 1; + } + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} + +/*----------------------------- Bitwise Logical ------------------------------*/ + +/** + * Atomic OR + * + * @brief Performs an atomic OR operation on the specified values. + * + * @param [in, out] pulDestination Pointer to memory location from where value is + * to be loaded and written back to. + * @param [in] ulValue Value to be ORed with *pulDestination. + * + * @return The original value of *pulDestination. + */ +static portFORCE_INLINE uint32_t Atomic_OR_u32( uint32_t volatile * pulDestination, + uint32_t ulValue ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + { + ulCurrent = *pulDestination; + *pulDestination |= ulValue; + } + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} +/*-----------------------------------------------------------*/ + +/** + * Atomic AND + * + * @brief Performs an atomic AND operation on the specified values. + * + * @param [in, out] pulDestination Pointer to memory location from where value is + * to be loaded and written back to. + * @param [in] ulValue Value to be ANDed with *pulDestination. + * + * @return The original value of *pulDestination. + */ +static portFORCE_INLINE uint32_t Atomic_AND_u32( uint32_t volatile * pulDestination, + uint32_t ulValue ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + { + ulCurrent = *pulDestination; + *pulDestination &= ulValue; + } + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} +/*-----------------------------------------------------------*/ + +/** + * Atomic NAND + * + * @brief Performs an atomic NAND operation on the specified values. + * + * @param [in, out] pulDestination Pointer to memory location from where value is + * to be loaded and written back to. + * @param [in] ulValue Value to be NANDed with *pulDestination. + * + * @return The original value of *pulDestination. + */ +static portFORCE_INLINE uint32_t Atomic_NAND_u32( uint32_t volatile * pulDestination, + uint32_t ulValue ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + { + ulCurrent = *pulDestination; + *pulDestination = ~( ulCurrent & ulValue ); + } + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} +/*-----------------------------------------------------------*/ + +/** + * Atomic XOR + * + * @brief Performs an atomic XOR operation on the specified values. + * + * @param [in, out] pulDestination Pointer to memory location from where value is + * to be loaded and written back to. + * @param [in] ulValue Value to be XORed with *pulDestination. + * + * @return The original value of *pulDestination. + */ +static portFORCE_INLINE uint32_t Atomic_XOR_u32( uint32_t volatile * pulDestination, + uint32_t ulValue ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + { + ulCurrent = *pulDestination; + *pulDestination ^= ulValue; + } + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} + +/* *INDENT-OFF* */ +#ifdef __cplusplus + } +#endif +/* *INDENT-ON* */ + +#endif /* ATOMIC_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/croutine.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/croutine.h new file mode 100644 index 0000000..51bdd4f --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/croutine.h @@ -0,0 +1,753 @@ +/* + * FreeRTOS Kernel V10.4.6 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#ifndef CO_ROUTINE_H +#define CO_ROUTINE_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h must appear in source files before include croutine.h" +#endif + +#include "list.h" + +/* *INDENT-OFF* */ +#ifdef __cplusplus + extern "C" { +#endif +/* *INDENT-ON* */ + +/* Used to hide the implementation of the co-routine control block. The + * control block structure however has to be included in the header due to + * the macro implementation of the co-routine functionality. */ +typedef void * CoRoutineHandle_t; + +/* Defines the prototype to which co-routine functions must conform. */ +typedef void (* crCOROUTINE_CODE)( CoRoutineHandle_t, + UBaseType_t ); + +typedef struct corCoRoutineControlBlock +{ + crCOROUTINE_CODE pxCoRoutineFunction; + ListItem_t xGenericListItem; /*< List item used to place the CRCB in ready and blocked queues. */ + ListItem_t xEventListItem; /*< List item used to place the CRCB in event lists. */ + UBaseType_t uxPriority; /*< The priority of the co-routine in relation to other co-routines. */ + UBaseType_t uxIndex; /*< Used to distinguish between co-routines when multiple co-routines use the same co-routine function. */ + uint16_t uxState; /*< Used internally by the co-routine implementation. */ +} CRCB_t; /* Co-routine control block. Note must be identical in size down to uxPriority with TCB_t. */ + +/** + * croutine. h + * @code{c} + * BaseType_t xCoRoutineCreate( + * crCOROUTINE_CODE pxCoRoutineCode, + * UBaseType_t uxPriority, + * UBaseType_t uxIndex + * ); + * @endcode + * + * Create a new co-routine and add it to the list of co-routines that are + * ready to run. + * + * @param pxCoRoutineCode Pointer to the co-routine function. Co-routine + * functions require special syntax - see the co-routine section of the WEB + * documentation for more information. + * + * @param uxPriority The priority with respect to other co-routines at which + * the co-routine will run. + * + * @param uxIndex Used to distinguish between different co-routines that + * execute the same function. See the example below and the co-routine section + * of the WEB documentation for further information. + * + * @return pdPASS if the co-routine was successfully created and added to a ready + * list, otherwise an error code defined with ProjDefs.h. + * + * Example usage: + * @code{c} + * // Co-routine to be created. + * void vFlashCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex ) + * { + * // Variables in co-routines must be declared static if they must maintain value across a blocking call. + * // This may not be necessary for const variables. + * static const char cLedToFlash[ 2 ] = { 5, 6 }; + * static const TickType_t uxFlashRates[ 2 ] = { 200, 400 }; + * + * // Must start every co-routine with a call to crSTART(); + * crSTART( xHandle ); + * + * for( ;; ) + * { + * // This co-routine just delays for a fixed period, then toggles + * // an LED. Two co-routines are created using this function, so + * // the uxIndex parameter is used to tell the co-routine which + * // LED to flash and how int32_t to delay. This assumes xQueue has + * // already been created. + * vParTestToggleLED( cLedToFlash[ uxIndex ] ); + * crDELAY( xHandle, uxFlashRates[ uxIndex ] ); + * } + * + * // Must end every co-routine with a call to crEND(); + * crEND(); + * } + * + * // Function that creates two co-routines. + * void vOtherFunction( void ) + * { + * uint8_t ucParameterToPass; + * TaskHandle_t xHandle; + * + * // Create two co-routines at priority 0. The first is given index 0 + * // so (from the code above) toggles LED 5 every 200 ticks. The second + * // is given index 1 so toggles LED 6 every 400 ticks. + * for( uxIndex = 0; uxIndex < 2; uxIndex++ ) + * { + * xCoRoutineCreate( vFlashCoRoutine, 0, uxIndex ); + * } + * } + * @endcode + * \defgroup xCoRoutineCreate xCoRoutineCreate + * \ingroup Tasks + */ +BaseType_t xCoRoutineCreate( crCOROUTINE_CODE pxCoRoutineCode, + UBaseType_t uxPriority, + UBaseType_t uxIndex ); + + +/** + * croutine. h + * @code{c} + * void vCoRoutineSchedule( void ); + * @endcode + * + * Run a co-routine. + * + * vCoRoutineSchedule() executes the highest priority co-routine that is able + * to run. The co-routine will execute until it either blocks, yields or is + * preempted by a task. Co-routines execute cooperatively so one + * co-routine cannot be preempted by another, but can be preempted by a task. + * + * If an application comprises of both tasks and co-routines then + * vCoRoutineSchedule should be called from the idle task (in an idle task + * hook). + * + * Example usage: + * @code{c} + * // This idle task hook will schedule a co-routine each time it is called. + * // The rest of the idle task will execute between co-routine calls. + * void vApplicationIdleHook( void ) + * { + * vCoRoutineSchedule(); + * } + * + * // Alternatively, if you do not require any other part of the idle task to + * // execute, the idle task hook can call vCoRoutineSchedule() within an + * // infinite loop. + * void vApplicationIdleHook( void ) + * { + * for( ;; ) + * { + * vCoRoutineSchedule(); + * } + * } + * @endcode + * \defgroup vCoRoutineSchedule vCoRoutineSchedule + * \ingroup Tasks + */ +void vCoRoutineSchedule( void ); + +/** + * croutine. h + * @code{c} + * crSTART( CoRoutineHandle_t xHandle ); + * @endcode + * + * This macro MUST always be called at the start of a co-routine function. + * + * Example usage: + * @code{c} + * // Co-routine to be created. + * void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex ) + * { + * // Variables in co-routines must be declared static if they must maintain value across a blocking call. + * static int32_t ulAVariable; + * + * // Must start every co-routine with a call to crSTART(); + * crSTART( xHandle ); + * + * for( ;; ) + * { + * // Co-routine functionality goes here. + * } + * + * // Must end every co-routine with a call to crEND(); + * crEND(); + * } + * @endcode + * \defgroup crSTART crSTART + * \ingroup Tasks + */ +#define crSTART( pxCRCB ) \ + switch( ( ( CRCB_t * ) ( pxCRCB ) )->uxState ) { \ + case 0: + +/** + * croutine. h + * @code{c} + * crEND(); + * @endcode + * + * This macro MUST always be called at the end of a co-routine function. + * + * Example usage: + * @code{c} + * // Co-routine to be created. + * void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex ) + * { + * // Variables in co-routines must be declared static if they must maintain value across a blocking call. + * static int32_t ulAVariable; + * + * // Must start every co-routine with a call to crSTART(); + * crSTART( xHandle ); + * + * for( ;; ) + * { + * // Co-routine functionality goes here. + * } + * + * // Must end every co-routine with a call to crEND(); + * crEND(); + * } + * @endcode + * \defgroup crSTART crSTART + * \ingroup Tasks + */ +#define crEND() } + +/* + * These macros are intended for internal use by the co-routine implementation + * only. The macros should not be used directly by application writers. + */ +#define crSET_STATE0( xHandle ) \ + ( ( CRCB_t * ) ( xHandle ) )->uxState = ( __LINE__ * 2 ); return; \ + case ( __LINE__ * 2 ): +#define crSET_STATE1( xHandle ) \ + ( ( CRCB_t * ) ( xHandle ) )->uxState = ( ( __LINE__ * 2 ) + 1 ); return; \ + case ( ( __LINE__ * 2 ) + 1 ): + +/** + * croutine. h + * @code{c} + * crDELAY( CoRoutineHandle_t xHandle, TickType_t xTicksToDelay ); + * @endcode + * + * Delay a co-routine for a fixed period of time. + * + * crDELAY can only be called from the co-routine function itself - not + * from within a function called by the co-routine function. This is because + * co-routines do not maintain their own stack. + * + * @param xHandle The handle of the co-routine to delay. This is the xHandle + * parameter of the co-routine function. + * + * @param xTickToDelay The number of ticks that the co-routine should delay + * for. The actual amount of time this equates to is defined by + * configTICK_RATE_HZ (set in FreeRTOSConfig.h). The constant portTICK_PERIOD_MS + * can be used to convert ticks to milliseconds. + * + * Example usage: + * @code{c} + * // Co-routine to be created. + * void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex ) + * { + * // Variables in co-routines must be declared static if they must maintain value across a blocking call. + * // This may not be necessary for const variables. + * // We are to delay for 200ms. + * static const xTickType xDelayTime = 200 / portTICK_PERIOD_MS; + * + * // Must start every co-routine with a call to crSTART(); + * crSTART( xHandle ); + * + * for( ;; ) + * { + * // Delay for 200ms. + * crDELAY( xHandle, xDelayTime ); + * + * // Do something here. + * } + * + * // Must end every co-routine with a call to crEND(); + * crEND(); + * } + * @endcode + * \defgroup crDELAY crDELAY + * \ingroup Tasks + */ +#define crDELAY( xHandle, xTicksToDelay ) \ + if( ( xTicksToDelay ) > 0 ) \ + { \ + vCoRoutineAddToDelayedList( ( xTicksToDelay ), NULL ); \ + } \ + crSET_STATE0( ( xHandle ) ); + +/** + * @code{c} + * crQUEUE_SEND( + * CoRoutineHandle_t xHandle, + * QueueHandle_t pxQueue, + * void *pvItemToQueue, + * TickType_t xTicksToWait, + * BaseType_t *pxResult + * ) + * @endcode + * + * The macro's crQUEUE_SEND() and crQUEUE_RECEIVE() are the co-routine + * equivalent to the xQueueSend() and xQueueReceive() functions used by tasks. + * + * crQUEUE_SEND and crQUEUE_RECEIVE can only be used from a co-routine whereas + * xQueueSend() and xQueueReceive() can only be used from tasks. + * + * crQUEUE_SEND can only be called from the co-routine function itself - not + * from within a function called by the co-routine function. This is because + * co-routines do not maintain their own stack. + * + * See the co-routine section of the WEB documentation for information on + * passing data between tasks and co-routines and between ISR's and + * co-routines. + * + * @param xHandle The handle of the calling co-routine. This is the xHandle + * parameter of the co-routine function. + * + * @param pxQueue The handle of the queue on which the data will be posted. + * The handle is obtained as the return value when the queue is created using + * the xQueueCreate() API function. + * + * @param pvItemToQueue A pointer to the data being posted onto the queue. + * The number of bytes of each queued item is specified when the queue is + * created. This number of bytes is copied from pvItemToQueue into the queue + * itself. + * + * @param xTickToDelay The number of ticks that the co-routine should block + * to wait for space to become available on the queue, should space not be + * available immediately. The actual amount of time this equates to is defined + * by configTICK_RATE_HZ (set in FreeRTOSConfig.h). The constant + * portTICK_PERIOD_MS can be used to convert ticks to milliseconds (see example + * below). + * + * @param pxResult The variable pointed to by pxResult will be set to pdPASS if + * data was successfully posted onto the queue, otherwise it will be set to an + * error defined within ProjDefs.h. + * + * Example usage: + * @code{c} + * // Co-routine function that blocks for a fixed period then posts a number onto + * // a queue. + * static void prvCoRoutineFlashTask( CoRoutineHandle_t xHandle, UBaseType_t uxIndex ) + * { + * // Variables in co-routines must be declared static if they must maintain value across a blocking call. + * static BaseType_t xNumberToPost = 0; + * static BaseType_t xResult; + * + * // Co-routines must begin with a call to crSTART(). + * crSTART( xHandle ); + * + * for( ;; ) + * { + * // This assumes the queue has already been created. + * crQUEUE_SEND( xHandle, xCoRoutineQueue, &xNumberToPost, NO_DELAY, &xResult ); + * + * if( xResult != pdPASS ) + * { + * // The message was not posted! + * } + * + * // Increment the number to be posted onto the queue. + * xNumberToPost++; + * + * // Delay for 100 ticks. + * crDELAY( xHandle, 100 ); + * } + * + * // Co-routines must end with a call to crEND(). + * crEND(); + * } + * @endcode + * \defgroup crQUEUE_SEND crQUEUE_SEND + * \ingroup Tasks + */ +#define crQUEUE_SEND( xHandle, pxQueue, pvItemToQueue, xTicksToWait, pxResult ) \ + { \ + *( pxResult ) = xQueueCRSend( ( pxQueue ), ( pvItemToQueue ), ( xTicksToWait ) ); \ + if( *( pxResult ) == errQUEUE_BLOCKED ) \ + { \ + crSET_STATE0( ( xHandle ) ); \ + *pxResult = xQueueCRSend( ( pxQueue ), ( pvItemToQueue ), 0 ); \ + } \ + if( *pxResult == errQUEUE_YIELD ) \ + { \ + crSET_STATE1( ( xHandle ) ); \ + *pxResult = pdPASS; \ + } \ + } + +/** + * croutine. h + * @code{c} + * crQUEUE_RECEIVE( + * CoRoutineHandle_t xHandle, + * QueueHandle_t pxQueue, + * void *pvBuffer, + * TickType_t xTicksToWait, + * BaseType_t *pxResult + * ) + * @endcode + * + * The macro's crQUEUE_SEND() and crQUEUE_RECEIVE() are the co-routine + * equivalent to the xQueueSend() and xQueueReceive() functions used by tasks. + * + * crQUEUE_SEND and crQUEUE_RECEIVE can only be used from a co-routine whereas + * xQueueSend() and xQueueReceive() can only be used from tasks. + * + * crQUEUE_RECEIVE can only be called from the co-routine function itself - not + * from within a function called by the co-routine function. This is because + * co-routines do not maintain their own stack. + * + * See the co-routine section of the WEB documentation for information on + * passing data between tasks and co-routines and between ISR's and + * co-routines. + * + * @param xHandle The handle of the calling co-routine. This is the xHandle + * parameter of the co-routine function. + * + * @param pxQueue The handle of the queue from which the data will be received. + * The handle is obtained as the return value when the queue is created using + * the xQueueCreate() API function. + * + * @param pvBuffer The buffer into which the received item is to be copied. + * The number of bytes of each queued item is specified when the queue is + * created. This number of bytes is copied into pvBuffer. + * + * @param xTickToDelay The number of ticks that the co-routine should block + * to wait for data to become available from the queue, should data not be + * available immediately. The actual amount of time this equates to is defined + * by configTICK_RATE_HZ (set in FreeRTOSConfig.h). The constant + * portTICK_PERIOD_MS can be used to convert ticks to milliseconds (see the + * crQUEUE_SEND example). + * + * @param pxResult The variable pointed to by pxResult will be set to pdPASS if + * data was successfully retrieved from the queue, otherwise it will be set to + * an error code as defined within ProjDefs.h. + * + * Example usage: + * @code{c} + * // A co-routine receives the number of an LED to flash from a queue. It + * // blocks on the queue until the number is received. + * static void prvCoRoutineFlashWorkTask( CoRoutineHandle_t xHandle, UBaseType_t uxIndex ) + * { + * // Variables in co-routines must be declared static if they must maintain value across a blocking call. + * static BaseType_t xResult; + * static UBaseType_t uxLEDToFlash; + * + * // All co-routines must start with a call to crSTART(). + * crSTART( xHandle ); + * + * for( ;; ) + * { + * // Wait for data to become available on the queue. + * crQUEUE_RECEIVE( xHandle, xCoRoutineQueue, &uxLEDToFlash, portMAX_DELAY, &xResult ); + * + * if( xResult == pdPASS ) + * { + * // We received the LED to flash - flash it! + * vParTestToggleLED( uxLEDToFlash ); + * } + * } + * + * crEND(); + * } + * @endcode + * \defgroup crQUEUE_RECEIVE crQUEUE_RECEIVE + * \ingroup Tasks + */ +#define crQUEUE_RECEIVE( xHandle, pxQueue, pvBuffer, xTicksToWait, pxResult ) \ + { \ + *( pxResult ) = xQueueCRReceive( ( pxQueue ), ( pvBuffer ), ( xTicksToWait ) ); \ + if( *( pxResult ) == errQUEUE_BLOCKED ) \ + { \ + crSET_STATE0( ( xHandle ) ); \ + *( pxResult ) = xQueueCRReceive( ( pxQueue ), ( pvBuffer ), 0 ); \ + } \ + if( *( pxResult ) == errQUEUE_YIELD ) \ + { \ + crSET_STATE1( ( xHandle ) ); \ + *( pxResult ) = pdPASS; \ + } \ + } + +/** + * croutine. h + * @code{c} + * crQUEUE_SEND_FROM_ISR( + * QueueHandle_t pxQueue, + * void *pvItemToQueue, + * BaseType_t xCoRoutinePreviouslyWoken + * ) + * @endcode + * + * The macro's crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() are the + * co-routine equivalent to the xQueueSendFromISR() and xQueueReceiveFromISR() + * functions used by tasks. + * + * crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() can only be used to + * pass data between a co-routine and and ISR, whereas xQueueSendFromISR() and + * xQueueReceiveFromISR() can only be used to pass data between a task and and + * ISR. + * + * crQUEUE_SEND_FROM_ISR can only be called from an ISR to send data to a queue + * that is being used from within a co-routine. + * + * See the co-routine section of the WEB documentation for information on + * passing data between tasks and co-routines and between ISR's and + * co-routines. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param xCoRoutinePreviouslyWoken This is included so an ISR can post onto + * the same queue multiple times from a single interrupt. The first call + * should always pass in pdFALSE. Subsequent calls should pass in + * the value returned from the previous call. + * + * @return pdTRUE if a co-routine was woken by posting onto the queue. This is + * used by the ISR to determine if a context switch may be required following + * the ISR. + * + * Example usage: + * @code{c} + * // A co-routine that blocks on a queue waiting for characters to be received. + * static void vReceivingCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex ) + * { + * char cRxedChar; + * BaseType_t xResult; + * + * // All co-routines must start with a call to crSTART(). + * crSTART( xHandle ); + * + * for( ;; ) + * { + * // Wait for data to become available on the queue. This assumes the + * // queue xCommsRxQueue has already been created! + * crQUEUE_RECEIVE( xHandle, xCommsRxQueue, &uxLEDToFlash, portMAX_DELAY, &xResult ); + * + * // Was a character received? + * if( xResult == pdPASS ) + * { + * // Process the character here. + * } + * } + * + * // All co-routines must end with a call to crEND(). + * crEND(); + * } + * + * // An ISR that uses a queue to send characters received on a serial port to + * // a co-routine. + * void vUART_ISR( void ) + * { + * char cRxedChar; + * BaseType_t xCRWokenByPost = pdFALSE; + * + * // We loop around reading characters until there are none left in the UART. + * while( UART_RX_REG_NOT_EMPTY() ) + * { + * // Obtain the character from the UART. + * cRxedChar = UART_RX_REG; + * + * // Post the character onto a queue. xCRWokenByPost will be pdFALSE + * // the first time around the loop. If the post causes a co-routine + * // to be woken (unblocked) then xCRWokenByPost will be set to pdTRUE. + * // In this manner we can ensure that if more than one co-routine is + * // blocked on the queue only one is woken by this ISR no matter how + * // many characters are posted to the queue. + * xCRWokenByPost = crQUEUE_SEND_FROM_ISR( xCommsRxQueue, &cRxedChar, xCRWokenByPost ); + * } + * } + * @endcode + * \defgroup crQUEUE_SEND_FROM_ISR crQUEUE_SEND_FROM_ISR + * \ingroup Tasks + */ +#define crQUEUE_SEND_FROM_ISR( pxQueue, pvItemToQueue, xCoRoutinePreviouslyWoken ) \ + xQueueCRSendFromISR( ( pxQueue ), ( pvItemToQueue ), ( xCoRoutinePreviouslyWoken ) ) + + +/** + * croutine. h + * @code{c} + * crQUEUE_SEND_FROM_ISR( + * QueueHandle_t pxQueue, + * void *pvBuffer, + * BaseType_t * pxCoRoutineWoken + * ) + * @endcode + * + * The macro's crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() are the + * co-routine equivalent to the xQueueSendFromISR() and xQueueReceiveFromISR() + * functions used by tasks. + * + * crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() can only be used to + * pass data between a co-routine and and ISR, whereas xQueueSendFromISR() and + * xQueueReceiveFromISR() can only be used to pass data between a task and and + * ISR. + * + * crQUEUE_RECEIVE_FROM_ISR can only be called from an ISR to receive data + * from a queue that is being used from within a co-routine (a co-routine + * posted to the queue). + * + * See the co-routine section of the WEB documentation for information on + * passing data between tasks and co-routines and between ISR's and + * co-routines. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvBuffer A pointer to a buffer into which the received item will be + * placed. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from the queue into + * pvBuffer. + * + * @param pxCoRoutineWoken A co-routine may be blocked waiting for space to become + * available on the queue. If crQUEUE_RECEIVE_FROM_ISR causes such a + * co-routine to unblock *pxCoRoutineWoken will get set to pdTRUE, otherwise + * *pxCoRoutineWoken will remain unchanged. + * + * @return pdTRUE an item was successfully received from the queue, otherwise + * pdFALSE. + * + * Example usage: + * @code{c} + * // A co-routine that posts a character to a queue then blocks for a fixed + * // period. The character is incremented each time. + * static void vSendingCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex ) + * { + * // cChar holds its value while this co-routine is blocked and must therefore + * // be declared static. + * static char cCharToTx = 'a'; + * BaseType_t xResult; + * + * // All co-routines must start with a call to crSTART(). + * crSTART( xHandle ); + * + * for( ;; ) + * { + * // Send the next character to the queue. + * crQUEUE_SEND( xHandle, xCoRoutineQueue, &cCharToTx, NO_DELAY, &xResult ); + * + * if( xResult == pdPASS ) + * { + * // The character was successfully posted to the queue. + * } + * else + * { + * // Could not post the character to the queue. + * } + * + * // Enable the UART Tx interrupt to cause an interrupt in this + * // hypothetical UART. The interrupt will obtain the character + * // from the queue and send it. + * ENABLE_RX_INTERRUPT(); + * + * // Increment to the next character then block for a fixed period. + * // cCharToTx will maintain its value across the delay as it is + * // declared static. + * cCharToTx++; + * if( cCharToTx > 'x' ) + * { + * cCharToTx = 'a'; + * } + * crDELAY( 100 ); + * } + * + * // All co-routines must end with a call to crEND(). + * crEND(); + * } + * + * // An ISR that uses a queue to receive characters to send on a UART. + * void vUART_ISR( void ) + * { + * char cCharToTx; + * BaseType_t xCRWokenByPost = pdFALSE; + * + * while( UART_TX_REG_EMPTY() ) + * { + * // Are there any characters in the queue waiting to be sent? + * // xCRWokenByPost will automatically be set to pdTRUE if a co-routine + * // is woken by the post - ensuring that only a single co-routine is + * // woken no matter how many times we go around this loop. + * if( crQUEUE_RECEIVE_FROM_ISR( pxQueue, &cCharToTx, &xCRWokenByPost ) ) + * { + * SEND_CHARACTER( cCharToTx ); + * } + * } + * } + * @endcode + * \defgroup crQUEUE_RECEIVE_FROM_ISR crQUEUE_RECEIVE_FROM_ISR + * \ingroup Tasks + */ +#define crQUEUE_RECEIVE_FROM_ISR( pxQueue, pvBuffer, pxCoRoutineWoken ) \ + xQueueCRReceiveFromISR( ( pxQueue ), ( pvBuffer ), ( pxCoRoutineWoken ) ) + +/* + * This function is intended for internal use by the co-routine macros only. + * The macro nature of the co-routine implementation requires that the + * prototype appears here. The function should not be used by application + * writers. + * + * Removes the current co-routine from its ready list and places it in the + * appropriate delayed list. + */ +void vCoRoutineAddToDelayedList( TickType_t xTicksToDelay, + List_t * pxEventList ); + +/* + * This function is intended for internal use by the queue implementation only. + * The function should not be used by application writers. + * + * Removes the highest priority co-routine from the event list and places it in + * the pending ready list. + */ +BaseType_t xCoRoutineRemoveFromEventList( const List_t * pxEventList ); + +/* *INDENT-OFF* */ +#ifdef __cplusplus + } +#endif +/* *INDENT-ON* */ + +#endif /* CO_ROUTINE_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/deprecated_definitions.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/deprecated_definitions.h new file mode 100644 index 0000000..a833141 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/deprecated_definitions.h @@ -0,0 +1,281 @@ +/* + * FreeRTOS Kernel V10.4.6 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#ifndef DEPRECATED_DEFINITIONS_H +#define DEPRECATED_DEFINITIONS_H + + +/* Each FreeRTOS port has a unique portmacro.h header file. Originally a + * pre-processor definition was used to ensure the pre-processor found the correct + * portmacro.h file for the port being used. That scheme was deprecated in favour + * of setting the compiler's include path such that it found the correct + * portmacro.h file - removing the need for the constant and allowing the + * portmacro.h file to be located anywhere in relation to the port being used. The + * definitions below remain in the code for backward compatibility only. New + * projects should not use them. */ + +#ifdef OPEN_WATCOM_INDUSTRIAL_PC_PORT + #include "..\..\Source\portable\owatcom\16bitdos\pc\portmacro.h" + typedef void ( __interrupt __far * pxISR )(); +#endif + +#ifdef OPEN_WATCOM_FLASH_LITE_186_PORT + #include "..\..\Source\portable\owatcom\16bitdos\flsh186\portmacro.h" + typedef void ( __interrupt __far * pxISR )(); +#endif + +#ifdef GCC_MEGA_AVR + #include "../portable/GCC/ATMega323/portmacro.h" +#endif + +#ifdef IAR_MEGA_AVR + #include "../portable/IAR/ATMega323/portmacro.h" +#endif + +#ifdef MPLAB_PIC24_PORT + #include "../../Source/portable/MPLAB/PIC24_dsPIC/portmacro.h" +#endif + +#ifdef MPLAB_DSPIC_PORT + #include "../../Source/portable/MPLAB/PIC24_dsPIC/portmacro.h" +#endif + +#ifdef MPLAB_PIC18F_PORT + #include "../../Source/portable/MPLAB/PIC18F/portmacro.h" +#endif + +#ifdef MPLAB_PIC32MX_PORT + #include "../../Source/portable/MPLAB/PIC32MX/portmacro.h" +#endif + +#ifdef _FEDPICC + #include "libFreeRTOS/Include/portmacro.h" +#endif + +#ifdef SDCC_CYGNAL + #include "../../Source/portable/SDCC/Cygnal/portmacro.h" +#endif + +#ifdef GCC_ARM7 + #include "../../Source/portable/GCC/ARM7_LPC2000/portmacro.h" +#endif + +#ifdef GCC_ARM7_ECLIPSE + #include "portmacro.h" +#endif + +#ifdef ROWLEY_LPC23xx + #include "../../Source/portable/GCC/ARM7_LPC23xx/portmacro.h" +#endif + +#ifdef IAR_MSP430 + #include "..\..\Source\portable\IAR\MSP430\portmacro.h" +#endif + +#ifdef GCC_MSP430 + #include "../../Source/portable/GCC/MSP430F449/portmacro.h" +#endif + +#ifdef ROWLEY_MSP430 + #include "../../Source/portable/Rowley/MSP430F449/portmacro.h" +#endif + +#ifdef ARM7_LPC21xx_KEIL_RVDS + #include "..\..\Source\portable\RVDS\ARM7_LPC21xx\portmacro.h" +#endif + +#ifdef SAM7_GCC + #include "../../Source/portable/GCC/ARM7_AT91SAM7S/portmacro.h" +#endif + +#ifdef SAM7_IAR + #include "..\..\Source\portable\IAR\AtmelSAM7S64\portmacro.h" +#endif + +#ifdef SAM9XE_IAR + #include "..\..\Source\portable\IAR\AtmelSAM9XE\portmacro.h" +#endif + +#ifdef LPC2000_IAR + #include "..\..\Source\portable\IAR\LPC2000\portmacro.h" +#endif + +#ifdef STR71X_IAR + #include "..\..\Source\portable\IAR\STR71x\portmacro.h" +#endif + +#ifdef STR75X_IAR + #include "..\..\Source\portable\IAR\STR75x\portmacro.h" +#endif + +#ifdef STR75X_GCC + #include "..\..\Source\portable\GCC\STR75x\portmacro.h" +#endif + +#ifdef STR91X_IAR + #include "..\..\Source\portable\IAR\STR91x\portmacro.h" +#endif + +#ifdef GCC_H8S + #include "../../Source/portable/GCC/H8S2329/portmacro.h" +#endif + +#ifdef GCC_AT91FR40008 + #include "../../Source/portable/GCC/ARM7_AT91FR40008/portmacro.h" +#endif + +#ifdef RVDS_ARMCM3_LM3S102 + #include "../../Source/portable/RVDS/ARM_CM3/portmacro.h" +#endif + +#ifdef GCC_ARMCM3_LM3S102 + #include "../../Source/portable/GCC/ARM_CM3/portmacro.h" +#endif + +#ifdef GCC_ARMCM3 + #include "../../Source/portable/GCC/ARM_CM3/portmacro.h" +#endif + +#ifdef IAR_ARM_CM3 + #include "../../Source/portable/IAR/ARM_CM3/portmacro.h" +#endif + +#ifdef IAR_ARMCM3_LM + #include "../../Source/portable/IAR/ARM_CM3/portmacro.h" +#endif + +#ifdef HCS12_CODE_WARRIOR + #include "../../Source/portable/CodeWarrior/HCS12/portmacro.h" +#endif + +#ifdef MICROBLAZE_GCC + #include "../../Source/portable/GCC/MicroBlaze/portmacro.h" +#endif + +#ifdef TERN_EE + #include "..\..\Source\portable\Paradigm\Tern_EE\small\portmacro.h" +#endif + +#ifdef GCC_HCS12 + #include "../../Source/portable/GCC/HCS12/portmacro.h" +#endif + +#ifdef GCC_MCF5235 + #include "../../Source/portable/GCC/MCF5235/portmacro.h" +#endif + +#ifdef COLDFIRE_V2_GCC + #include "../../../Source/portable/GCC/ColdFire_V2/portmacro.h" +#endif + +#ifdef COLDFIRE_V2_CODEWARRIOR + #include "../../Source/portable/CodeWarrior/ColdFire_V2/portmacro.h" +#endif + +#ifdef GCC_PPC405 + #include "../../Source/portable/GCC/PPC405_Xilinx/portmacro.h" +#endif + +#ifdef GCC_PPC440 + #include "../../Source/portable/GCC/PPC440_Xilinx/portmacro.h" +#endif + +#ifdef _16FX_SOFTUNE + #include "..\..\Source\portable\Softune\MB96340\portmacro.h" +#endif + +#ifdef BCC_INDUSTRIAL_PC_PORT + +/* A short file name has to be used in place of the normal + * FreeRTOSConfig.h when using the Borland compiler. */ + #include "frconfig.h" + #include "..\portable\BCC\16BitDOS\PC\prtmacro.h" + typedef void ( __interrupt __far * pxISR )(); +#endif + +#ifdef BCC_FLASH_LITE_186_PORT + +/* A short file name has to be used in place of the normal + * FreeRTOSConfig.h when using the Borland compiler. */ + #include "frconfig.h" + #include "..\portable\BCC\16BitDOS\flsh186\prtmacro.h" + typedef void ( __interrupt __far * pxISR )(); +#endif + +#ifdef __GNUC__ + #ifdef __AVR32_AVR32A__ + #include "portmacro.h" + #endif +#endif + +#ifdef __ICCAVR32__ + #ifdef __CORE__ + #if __CORE__ == __AVR32A__ + #include "portmacro.h" + #endif + #endif +#endif + +#ifdef __91467D + #include "portmacro.h" +#endif + +#ifdef __96340 + #include "portmacro.h" +#endif + + +#ifdef __IAR_V850ES_Fx3__ + #include "../../Source/portable/IAR/V850ES/portmacro.h" +#endif + +#ifdef __IAR_V850ES_Jx3__ + #include "../../Source/portable/IAR/V850ES/portmacro.h" +#endif + +#ifdef __IAR_V850ES_Jx3_L__ + #include "../../Source/portable/IAR/V850ES/portmacro.h" +#endif + +#ifdef __IAR_V850ES_Jx2__ + #include "../../Source/portable/IAR/V850ES/portmacro.h" +#endif + +#ifdef __IAR_V850ES_Hx2__ + #include "../../Source/portable/IAR/V850ES/portmacro.h" +#endif + +#ifdef __IAR_78K0R_Kx3__ + #include "../../Source/portable/IAR/78K0R/portmacro.h" +#endif + +#ifdef __IAR_78K0R_Kx3L__ + #include "../../Source/portable/IAR/78K0R/portmacro.h" +#endif + +#endif /* DEPRECATED_DEFINITIONS_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/event_groups.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/event_groups.h new file mode 100644 index 0000000..601a29b --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/event_groups.h @@ -0,0 +1,777 @@ +/* + * FreeRTOS Kernel V10.4.6 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#ifndef EVENT_GROUPS_H +#define EVENT_GROUPS_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h" must appear in source files before "include event_groups.h" +#endif + +/* FreeRTOS includes. */ +#include "timers.h" + +/* *INDENT-OFF* */ +#ifdef __cplusplus + extern "C" { +#endif +/* *INDENT-ON* */ + +/** + * An event group is a collection of bits to which an application can assign a + * meaning. For example, an application may create an event group to convey + * the status of various CAN bus related events in which bit 0 might mean "A CAN + * message has been received and is ready for processing", bit 1 might mean "The + * application has queued a message that is ready for sending onto the CAN + * network", and bit 2 might mean "It is time to send a SYNC message onto the + * CAN network" etc. A task can then test the bit values to see which events + * are active, and optionally enter the Blocked state to wait for a specified + * bit or a group of specified bits to be active. To continue the CAN bus + * example, a CAN controlling task can enter the Blocked state (and therefore + * not consume any processing time) until either bit 0, bit 1 or bit 2 are + * active, at which time the bit that was actually active would inform the task + * which action it had to take (process a received message, send a message, or + * send a SYNC). + * + * The event groups implementation contains intelligence to avoid race + * conditions that would otherwise occur were an application to use a simple + * variable for the same purpose. This is particularly important with respect + * to when a bit within an event group is to be cleared, and when bits have to + * be set and then tested atomically - as is the case where event groups are + * used to create a synchronisation point between multiple tasks (a + * 'rendezvous'). + * + * \defgroup EventGroup + */ + + + +/** + * event_groups.h + * + * Type by which event groups are referenced. For example, a call to + * xEventGroupCreate() returns an EventGroupHandle_t variable that can then + * be used as a parameter to other event group functions. + * + * \defgroup EventGroupHandle_t EventGroupHandle_t + * \ingroup EventGroup + */ +struct EventGroupDef_t; +typedef struct EventGroupDef_t * EventGroupHandle_t; + +/* + * The type that holds event bits always matches TickType_t - therefore the + * number of bits it holds is set by configUSE_16_BIT_TICKS (16 bits if set to 1, + * 32 bits if set to 0. + * + * \defgroup EventBits_t EventBits_t + * \ingroup EventGroup + */ +typedef TickType_t EventBits_t; + +/** + * event_groups.h + * @code{c} + * EventGroupHandle_t xEventGroupCreate( void ); + * @endcode + * + * Create a new event group. + * + * Internally, within the FreeRTOS implementation, event groups use a [small] + * block of memory, in which the event group's structure is stored. If an event + * groups is created using xEventGroupCreate() then the required memory is + * automatically dynamically allocated inside the xEventGroupCreate() function. + * (see https://www.FreeRTOS.org/a00111.html). If an event group is created + * using xEventGroupCreateStatic() then the application writer must instead + * provide the memory that will get used by the event group. + * xEventGroupCreateStatic() therefore allows an event group to be created + * without using any dynamic memory allocation. + * + * Although event groups are not related to ticks, for internal implementation + * reasons the number of bits available for use in an event group is dependent + * on the configUSE_16_BIT_TICKS setting in FreeRTOSConfig.h. If + * configUSE_16_BIT_TICKS is 1 then each event group contains 8 usable bits (bit + * 0 to bit 7). If configUSE_16_BIT_TICKS is set to 0 then each event group has + * 24 usable bits (bit 0 to bit 23). The EventBits_t type is used to store + * event bits within an event group. + * + * @return If the event group was created then a handle to the event group is + * returned. If there was insufficient FreeRTOS heap available to create the + * event group then NULL is returned. See https://www.FreeRTOS.org/a00111.html + * + * Example usage: + * @code{c} + * // Declare a variable to hold the created event group. + * EventGroupHandle_t xCreatedEventGroup; + * + * // Attempt to create the event group. + * xCreatedEventGroup = xEventGroupCreate(); + * + * // Was the event group created successfully? + * if( xCreatedEventGroup == NULL ) + * { + * // The event group was not created because there was insufficient + * // FreeRTOS heap available. + * } + * else + * { + * // The event group was created. + * } + * @endcode + * \defgroup xEventGroupCreate xEventGroupCreate + * \ingroup EventGroup + */ +#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + EventGroupHandle_t xEventGroupCreate( void ) PRIVILEGED_FUNCTION; +#endif + +/** + * event_groups.h + * @code{c} + * EventGroupHandle_t xEventGroupCreateStatic( EventGroupHandle_t * pxEventGroupBuffer ); + * @endcode + * + * Create a new event group. + * + * Internally, within the FreeRTOS implementation, event groups use a [small] + * block of memory, in which the event group's structure is stored. If an event + * groups is created using xEventGroupCreate() then the required memory is + * automatically dynamically allocated inside the xEventGroupCreate() function. + * (see https://www.FreeRTOS.org/a00111.html). If an event group is created + * using xEventGroupCreateStatic() then the application writer must instead + * provide the memory that will get used by the event group. + * xEventGroupCreateStatic() therefore allows an event group to be created + * without using any dynamic memory allocation. + * + * Although event groups are not related to ticks, for internal implementation + * reasons the number of bits available for use in an event group is dependent + * on the configUSE_16_BIT_TICKS setting in FreeRTOSConfig.h. If + * configUSE_16_BIT_TICKS is 1 then each event group contains 8 usable bits (bit + * 0 to bit 7). If configUSE_16_BIT_TICKS is set to 0 then each event group has + * 24 usable bits (bit 0 to bit 23). The EventBits_t type is used to store + * event bits within an event group. + * + * @param pxEventGroupBuffer pxEventGroupBuffer must point to a variable of type + * StaticEventGroup_t, which will be then be used to hold the event group's data + * structures, removing the need for the memory to be allocated dynamically. + * + * @return If the event group was created then a handle to the event group is + * returned. If pxEventGroupBuffer was NULL then NULL is returned. + * + * Example usage: + * @code{c} + * // StaticEventGroup_t is a publicly accessible structure that has the same + * // size and alignment requirements as the real event group structure. It is + * // provided as a mechanism for applications to know the size of the event + * // group (which is dependent on the architecture and configuration file + * // settings) without breaking the strict data hiding policy by exposing the + * // real event group internals. This StaticEventGroup_t variable is passed + * // into the xSemaphoreCreateEventGroupStatic() function and is used to store + * // the event group's data structures + * StaticEventGroup_t xEventGroupBuffer; + * + * // Create the event group without dynamically allocating any memory. + * xEventGroup = xEventGroupCreateStatic( &xEventGroupBuffer ); + * @endcode + */ +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + EventGroupHandle_t xEventGroupCreateStatic( StaticEventGroup_t * pxEventGroupBuffer ) PRIVILEGED_FUNCTION; +#endif + +/** + * event_groups.h + * @code{c} + * EventBits_t xEventGroupWaitBits( EventGroupHandle_t xEventGroup, + * const EventBits_t uxBitsToWaitFor, + * const BaseType_t xClearOnExit, + * const BaseType_t xWaitForAllBits, + * const TickType_t xTicksToWait ); + * @endcode + * + * [Potentially] block to wait for one or more bits to be set within a + * previously created event group. + * + * This function cannot be called from an interrupt. + * + * @param xEventGroup The event group in which the bits are being tested. The + * event group must have previously been created using a call to + * xEventGroupCreate(). + * + * @param uxBitsToWaitFor A bitwise value that indicates the bit or bits to test + * inside the event group. For example, to wait for bit 0 and/or bit 2 set + * uxBitsToWaitFor to 0x05. To wait for bits 0 and/or bit 1 and/or bit 2 set + * uxBitsToWaitFor to 0x07. Etc. + * + * @param xClearOnExit If xClearOnExit is set to pdTRUE then any bits within + * uxBitsToWaitFor that are set within the event group will be cleared before + * xEventGroupWaitBits() returns if the wait condition was met (if the function + * returns for a reason other than a timeout). If xClearOnExit is set to + * pdFALSE then the bits set in the event group are not altered when the call to + * xEventGroupWaitBits() returns. + * + * @param xWaitForAllBits If xWaitForAllBits is set to pdTRUE then + * xEventGroupWaitBits() will return when either all the bits in uxBitsToWaitFor + * are set or the specified block time expires. If xWaitForAllBits is set to + * pdFALSE then xEventGroupWaitBits() will return when any one of the bits set + * in uxBitsToWaitFor is set or the specified block time expires. The block + * time is specified by the xTicksToWait parameter. + * + * @param xTicksToWait The maximum amount of time (specified in 'ticks') to wait + * for one/all (depending on the xWaitForAllBits value) of the bits specified by + * uxBitsToWaitFor to become set. + * + * @return The value of the event group at the time either the bits being waited + * for became set, or the block time expired. Test the return value to know + * which bits were set. If xEventGroupWaitBits() returned because its timeout + * expired then not all the bits being waited for will be set. If + * xEventGroupWaitBits() returned because the bits it was waiting for were set + * then the returned value is the event group value before any bits were + * automatically cleared in the case that xClearOnExit parameter was set to + * pdTRUE. + * + * Example usage: + * @code{c} + * #define BIT_0 ( 1 << 0 ) + * #define BIT_4 ( 1 << 4 ) + * + * void aFunction( EventGroupHandle_t xEventGroup ) + * { + * EventBits_t uxBits; + * const TickType_t xTicksToWait = 100 / portTICK_PERIOD_MS; + * + * // Wait a maximum of 100ms for either bit 0 or bit 4 to be set within + * // the event group. Clear the bits before exiting. + * uxBits = xEventGroupWaitBits( + * xEventGroup, // The event group being tested. + * BIT_0 | BIT_4, // The bits within the event group to wait for. + * pdTRUE, // BIT_0 and BIT_4 should be cleared before returning. + * pdFALSE, // Don't wait for both bits, either bit will do. + * xTicksToWait ); // Wait a maximum of 100ms for either bit to be set. + * + * if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) ) + * { + * // xEventGroupWaitBits() returned because both bits were set. + * } + * else if( ( uxBits & BIT_0 ) != 0 ) + * { + * // xEventGroupWaitBits() returned because just BIT_0 was set. + * } + * else if( ( uxBits & BIT_4 ) != 0 ) + * { + * // xEventGroupWaitBits() returned because just BIT_4 was set. + * } + * else + * { + * // xEventGroupWaitBits() returned because xTicksToWait ticks passed + * // without either BIT_0 or BIT_4 becoming set. + * } + * } + * @endcode + * \defgroup xEventGroupWaitBits xEventGroupWaitBits + * \ingroup EventGroup + */ +EventBits_t xEventGroupWaitBits( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToWaitFor, + const BaseType_t xClearOnExit, + const BaseType_t xWaitForAllBits, + TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/** + * event_groups.h + * @code{c} + * EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear ); + * @endcode + * + * Clear bits within an event group. This function cannot be called from an + * interrupt. + * + * @param xEventGroup The event group in which the bits are to be cleared. + * + * @param uxBitsToClear A bitwise value that indicates the bit or bits to clear + * in the event group. For example, to clear bit 3 only, set uxBitsToClear to + * 0x08. To clear bit 3 and bit 0 set uxBitsToClear to 0x09. + * + * @return The value of the event group before the specified bits were cleared. + * + * Example usage: + * @code{c} + * #define BIT_0 ( 1 << 0 ) + * #define BIT_4 ( 1 << 4 ) + * + * void aFunction( EventGroupHandle_t xEventGroup ) + * { + * EventBits_t uxBits; + * + * // Clear bit 0 and bit 4 in xEventGroup. + * uxBits = xEventGroupClearBits( + * xEventGroup, // The event group being updated. + * BIT_0 | BIT_4 );// The bits being cleared. + * + * if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) ) + * { + * // Both bit 0 and bit 4 were set before xEventGroupClearBits() was + * // called. Both will now be clear (not set). + * } + * else if( ( uxBits & BIT_0 ) != 0 ) + * { + * // Bit 0 was set before xEventGroupClearBits() was called. It will + * // now be clear. + * } + * else if( ( uxBits & BIT_4 ) != 0 ) + * { + * // Bit 4 was set before xEventGroupClearBits() was called. It will + * // now be clear. + * } + * else + * { + * // Neither bit 0 nor bit 4 were set in the first place. + * } + * } + * @endcode + * \defgroup xEventGroupClearBits xEventGroupClearBits + * \ingroup EventGroup + */ +EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToClear ) PRIVILEGED_FUNCTION; + +/** + * event_groups.h + * @code{c} + * BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet ); + * @endcode + * + * A version of xEventGroupClearBits() that can be called from an interrupt. + * + * Setting bits in an event group is not a deterministic operation because there + * are an unknown number of tasks that may be waiting for the bit or bits being + * set. FreeRTOS does not allow nondeterministic operations to be performed + * while interrupts are disabled, so protects event groups that are accessed + * from tasks by suspending the scheduler rather than disabling interrupts. As + * a result event groups cannot be accessed directly from an interrupt service + * routine. Therefore xEventGroupClearBitsFromISR() sends a message to the + * timer task to have the clear operation performed in the context of the timer + * task. + * + * @param xEventGroup The event group in which the bits are to be cleared. + * + * @param uxBitsToClear A bitwise value that indicates the bit or bits to clear. + * For example, to clear bit 3 only, set uxBitsToClear to 0x08. To clear bit 3 + * and bit 0 set uxBitsToClear to 0x09. + * + * @return If the request to execute the function was posted successfully then + * pdPASS is returned, otherwise pdFALSE is returned. pdFALSE will be returned + * if the timer service queue was full. + * + * Example usage: + * @code{c} + * #define BIT_0 ( 1 << 0 ) + * #define BIT_4 ( 1 << 4 ) + * + * // An event group which it is assumed has already been created by a call to + * // xEventGroupCreate(). + * EventGroupHandle_t xEventGroup; + * + * void anInterruptHandler( void ) + * { + * // Clear bit 0 and bit 4 in xEventGroup. + * xResult = xEventGroupClearBitsFromISR( + * xEventGroup, // The event group being updated. + * BIT_0 | BIT_4 ); // The bits being set. + * + * if( xResult == pdPASS ) + * { + * // The message was posted successfully. + * } + * } + * @endcode + * \defgroup xEventGroupClearBitsFromISR xEventGroupClearBitsFromISR + * \ingroup EventGroup + */ +#if ( configUSE_TRACE_FACILITY == 1 ) + BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToClear ) PRIVILEGED_FUNCTION; +#else + #define xEventGroupClearBitsFromISR( xEventGroup, uxBitsToClear ) \ + xTimerPendFunctionCallFromISR( vEventGroupClearBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToClear, NULL ) +#endif + +/** + * event_groups.h + * @code{c} + * EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet ); + * @endcode + * + * Set bits within an event group. + * This function cannot be called from an interrupt. xEventGroupSetBitsFromISR() + * is a version that can be called from an interrupt. + * + * Setting bits in an event group will automatically unblock tasks that are + * blocked waiting for the bits. + * + * @param xEventGroup The event group in which the bits are to be set. + * + * @param uxBitsToSet A bitwise value that indicates the bit or bits to set. + * For example, to set bit 3 only, set uxBitsToSet to 0x08. To set bit 3 + * and bit 0 set uxBitsToSet to 0x09. + * + * @return The value of the event group at the time the call to + * xEventGroupSetBits() returns. There are two reasons why the returned value + * might have the bits specified by the uxBitsToSet parameter cleared. First, + * if setting a bit results in a task that was waiting for the bit leaving the + * blocked state then it is possible the bit will be cleared automatically + * (see the xClearBitOnExit parameter of xEventGroupWaitBits()). Second, any + * unblocked (or otherwise Ready state) task that has a priority above that of + * the task that called xEventGroupSetBits() will execute and may change the + * event group value before the call to xEventGroupSetBits() returns. + * + * Example usage: + * @code{c} + * #define BIT_0 ( 1 << 0 ) + * #define BIT_4 ( 1 << 4 ) + * + * void aFunction( EventGroupHandle_t xEventGroup ) + * { + * EventBits_t uxBits; + * + * // Set bit 0 and bit 4 in xEventGroup. + * uxBits = xEventGroupSetBits( + * xEventGroup, // The event group being updated. + * BIT_0 | BIT_4 );// The bits being set. + * + * if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) ) + * { + * // Both bit 0 and bit 4 remained set when the function returned. + * } + * else if( ( uxBits & BIT_0 ) != 0 ) + * { + * // Bit 0 remained set when the function returned, but bit 4 was + * // cleared. It might be that bit 4 was cleared automatically as a + * // task that was waiting for bit 4 was removed from the Blocked + * // state. + * } + * else if( ( uxBits & BIT_4 ) != 0 ) + * { + * // Bit 4 remained set when the function returned, but bit 0 was + * // cleared. It might be that bit 0 was cleared automatically as a + * // task that was waiting for bit 0 was removed from the Blocked + * // state. + * } + * else + * { + * // Neither bit 0 nor bit 4 remained set. It might be that a task + * // was waiting for both of the bits to be set, and the bits were + * // cleared as the task left the Blocked state. + * } + * } + * @endcode + * \defgroup xEventGroupSetBits xEventGroupSetBits + * \ingroup EventGroup + */ +EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToSet ) PRIVILEGED_FUNCTION; + +/** + * event_groups.h + * @code{c} + * BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, BaseType_t *pxHigherPriorityTaskWoken ); + * @endcode + * + * A version of xEventGroupSetBits() that can be called from an interrupt. + * + * Setting bits in an event group is not a deterministic operation because there + * are an unknown number of tasks that may be waiting for the bit or bits being + * set. FreeRTOS does not allow nondeterministic operations to be performed in + * interrupts or from critical sections. Therefore xEventGroupSetBitsFromISR() + * sends a message to the timer task to have the set operation performed in the + * context of the timer task - where a scheduler lock is used in place of a + * critical section. + * + * @param xEventGroup The event group in which the bits are to be set. + * + * @param uxBitsToSet A bitwise value that indicates the bit or bits to set. + * For example, to set bit 3 only, set uxBitsToSet to 0x08. To set bit 3 + * and bit 0 set uxBitsToSet to 0x09. + * + * @param pxHigherPriorityTaskWoken As mentioned above, calling this function + * will result in a message being sent to the timer daemon task. If the + * priority of the timer daemon task is higher than the priority of the + * currently running task (the task the interrupt interrupted) then + * *pxHigherPriorityTaskWoken will be set to pdTRUE by + * xEventGroupSetBitsFromISR(), indicating that a context switch should be + * requested before the interrupt exits. For that reason + * *pxHigherPriorityTaskWoken must be initialised to pdFALSE. See the + * example code below. + * + * @return If the request to execute the function was posted successfully then + * pdPASS is returned, otherwise pdFALSE is returned. pdFALSE will be returned + * if the timer service queue was full. + * + * Example usage: + * @code{c} + * #define BIT_0 ( 1 << 0 ) + * #define BIT_4 ( 1 << 4 ) + * + * // An event group which it is assumed has already been created by a call to + * // xEventGroupCreate(). + * EventGroupHandle_t xEventGroup; + * + * void anInterruptHandler( void ) + * { + * BaseType_t xHigherPriorityTaskWoken, xResult; + * + * // xHigherPriorityTaskWoken must be initialised to pdFALSE. + * xHigherPriorityTaskWoken = pdFALSE; + * + * // Set bit 0 and bit 4 in xEventGroup. + * xResult = xEventGroupSetBitsFromISR( + * xEventGroup, // The event group being updated. + * BIT_0 | BIT_4 // The bits being set. + * &xHigherPriorityTaskWoken ); + * + * // Was the message posted successfully? + * if( xResult == pdPASS ) + * { + * // If xHigherPriorityTaskWoken is now set to pdTRUE then a context + * // switch should be requested. The macro used is port specific and + * // will be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() - + * // refer to the documentation page for the port being used. + * portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); + * } + * } + * @endcode + * \defgroup xEventGroupSetBitsFromISR xEventGroupSetBitsFromISR + * \ingroup EventGroup + */ +#if ( configUSE_TRACE_FACILITY == 1 ) + BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToSet, + BaseType_t * pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; +#else + #define xEventGroupSetBitsFromISR( xEventGroup, uxBitsToSet, pxHigherPriorityTaskWoken ) \ + xTimerPendFunctionCallFromISR( vEventGroupSetBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToSet, pxHigherPriorityTaskWoken ) +#endif + +/** + * event_groups.h + * @code{c} + * EventBits_t xEventGroupSync( EventGroupHandle_t xEventGroup, + * const EventBits_t uxBitsToSet, + * const EventBits_t uxBitsToWaitFor, + * TickType_t xTicksToWait ); + * @endcode + * + * Atomically set bits within an event group, then wait for a combination of + * bits to be set within the same event group. This functionality is typically + * used to synchronise multiple tasks, where each task has to wait for the other + * tasks to reach a synchronisation point before proceeding. + * + * This function cannot be used from an interrupt. + * + * The function will return before its block time expires if the bits specified + * by the uxBitsToWait parameter are set, or become set within that time. In + * this case all the bits specified by uxBitsToWait will be automatically + * cleared before the function returns. + * + * @param xEventGroup The event group in which the bits are being tested. The + * event group must have previously been created using a call to + * xEventGroupCreate(). + * + * @param uxBitsToSet The bits to set in the event group before determining + * if, and possibly waiting for, all the bits specified by the uxBitsToWait + * parameter are set. + * + * @param uxBitsToWaitFor A bitwise value that indicates the bit or bits to test + * inside the event group. For example, to wait for bit 0 and bit 2 set + * uxBitsToWaitFor to 0x05. To wait for bits 0 and bit 1 and bit 2 set + * uxBitsToWaitFor to 0x07. Etc. + * + * @param xTicksToWait The maximum amount of time (specified in 'ticks') to wait + * for all of the bits specified by uxBitsToWaitFor to become set. + * + * @return The value of the event group at the time either the bits being waited + * for became set, or the block time expired. Test the return value to know + * which bits were set. If xEventGroupSync() returned because its timeout + * expired then not all the bits being waited for will be set. If + * xEventGroupSync() returned because all the bits it was waiting for were + * set then the returned value is the event group value before any bits were + * automatically cleared. + * + * Example usage: + * @code{c} + * // Bits used by the three tasks. + * #define TASK_0_BIT ( 1 << 0 ) + * #define TASK_1_BIT ( 1 << 1 ) + * #define TASK_2_BIT ( 1 << 2 ) + * + * #define ALL_SYNC_BITS ( TASK_0_BIT | TASK_1_BIT | TASK_2_BIT ) + * + * // Use an event group to synchronise three tasks. It is assumed this event + * // group has already been created elsewhere. + * EventGroupHandle_t xEventBits; + * + * void vTask0( void *pvParameters ) + * { + * EventBits_t uxReturn; + * TickType_t xTicksToWait = 100 / portTICK_PERIOD_MS; + * + * for( ;; ) + * { + * // Perform task functionality here. + * + * // Set bit 0 in the event flag to note this task has reached the + * // sync point. The other two tasks will set the other two bits defined + * // by ALL_SYNC_BITS. All three tasks have reached the synchronisation + * // point when all the ALL_SYNC_BITS are set. Wait a maximum of 100ms + * // for this to happen. + * uxReturn = xEventGroupSync( xEventBits, TASK_0_BIT, ALL_SYNC_BITS, xTicksToWait ); + * + * if( ( uxReturn & ALL_SYNC_BITS ) == ALL_SYNC_BITS ) + * { + * // All three tasks reached the synchronisation point before the call + * // to xEventGroupSync() timed out. + * } + * } + * } + * + * void vTask1( void *pvParameters ) + * { + * for( ;; ) + * { + * // Perform task functionality here. + * + * // Set bit 1 in the event flag to note this task has reached the + * // synchronisation point. The other two tasks will set the other two + * // bits defined by ALL_SYNC_BITS. All three tasks have reached the + * // synchronisation point when all the ALL_SYNC_BITS are set. Wait + * // indefinitely for this to happen. + * xEventGroupSync( xEventBits, TASK_1_BIT, ALL_SYNC_BITS, portMAX_DELAY ); + * + * // xEventGroupSync() was called with an indefinite block time, so + * // this task will only reach here if the synchronisation was made by all + * // three tasks, so there is no need to test the return value. + * } + * } + * + * void vTask2( void *pvParameters ) + * { + * for( ;; ) + * { + * // Perform task functionality here. + * + * // Set bit 2 in the event flag to note this task has reached the + * // synchronisation point. The other two tasks will set the other two + * // bits defined by ALL_SYNC_BITS. All three tasks have reached the + * // synchronisation point when all the ALL_SYNC_BITS are set. Wait + * // indefinitely for this to happen. + * xEventGroupSync( xEventBits, TASK_2_BIT, ALL_SYNC_BITS, portMAX_DELAY ); + * + * // xEventGroupSync() was called with an indefinite block time, so + * // this task will only reach here if the synchronisation was made by all + * // three tasks, so there is no need to test the return value. + * } + * } + * + * @endcode + * \defgroup xEventGroupSync xEventGroupSync + * \ingroup EventGroup + */ +EventBits_t xEventGroupSync( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToSet, + const EventBits_t uxBitsToWaitFor, + TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + + +/** + * event_groups.h + * @code{c} + * EventBits_t xEventGroupGetBits( EventGroupHandle_t xEventGroup ); + * @endcode + * + * Returns the current value of the bits in an event group. This function + * cannot be used from an interrupt. + * + * @param xEventGroup The event group being queried. + * + * @return The event group bits at the time xEventGroupGetBits() was called. + * + * \defgroup xEventGroupGetBits xEventGroupGetBits + * \ingroup EventGroup + */ +#define xEventGroupGetBits( xEventGroup ) xEventGroupClearBits( xEventGroup, 0 ) + +/** + * event_groups.h + * @code{c} + * EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup ); + * @endcode + * + * A version of xEventGroupGetBits() that can be called from an ISR. + * + * @param xEventGroup The event group being queried. + * + * @return The event group bits at the time xEventGroupGetBitsFromISR() was called. + * + * \defgroup xEventGroupGetBitsFromISR xEventGroupGetBitsFromISR + * \ingroup EventGroup + */ +EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup ) PRIVILEGED_FUNCTION; + +/** + * event_groups.h + * @code{c} + * void xEventGroupDelete( EventGroupHandle_t xEventGroup ); + * @endcode + * + * Delete an event group that was previously created by a call to + * xEventGroupCreate(). Tasks that are blocked on the event group will be + * unblocked and obtain 0 as the event group's value. + * + * @param xEventGroup The event group being deleted. + */ +void vEventGroupDelete( EventGroupHandle_t xEventGroup ) PRIVILEGED_FUNCTION; + +/* For internal use only. */ +void vEventGroupSetBitsCallback( void * pvEventGroup, + const uint32_t ulBitsToSet ) PRIVILEGED_FUNCTION; +void vEventGroupClearBitsCallback( void * pvEventGroup, + const uint32_t ulBitsToClear ) PRIVILEGED_FUNCTION; + + +#if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxEventGroupGetNumber( void * xEventGroup ) PRIVILEGED_FUNCTION; + void vEventGroupSetNumber( void * xEventGroup, + UBaseType_t uxEventGroupNumber ) PRIVILEGED_FUNCTION; +#endif + +/* *INDENT-OFF* */ +#ifdef __cplusplus + } +#endif +/* *INDENT-ON* */ + +#endif /* EVENT_GROUPS_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/list.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/list.h new file mode 100644 index 0000000..f866f9f --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/list.h @@ -0,0 +1,499 @@ +/* + * FreeRTOS Kernel V10.4.6 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* + * This is the list implementation used by the scheduler. While it is tailored + * heavily for the schedulers needs, it is also available for use by + * application code. + * + * list_ts can only store pointers to list_item_ts. Each ListItem_t contains a + * numeric value (xItemValue). Most of the time the lists are sorted in + * ascending item value order. + * + * Lists are created already containing one list item. The value of this + * item is the maximum possible that can be stored, it is therefore always at + * the end of the list and acts as a marker. The list member pxHead always + * points to this marker - even though it is at the tail of the list. This + * is because the tail contains a wrap back pointer to the true head of + * the list. + * + * In addition to it's value, each list item contains a pointer to the next + * item in the list (pxNext), a pointer to the list it is in (pxContainer) + * and a pointer to back to the object that contains it. These later two + * pointers are included for efficiency of list manipulation. There is + * effectively a two way link between the object containing the list item and + * the list item itself. + * + * + * \page ListIntroduction List Implementation + * \ingroup FreeRTOSIntro + */ + + +#ifndef LIST_H +#define LIST_H + +#ifndef INC_FREERTOS_H + #error "FreeRTOS.h must be included before list.h" +#endif + +/* + * The list structure members are modified from within interrupts, and therefore + * by rights should be declared volatile. However, they are only modified in a + * functionally atomic way (within critical sections of with the scheduler + * suspended) and are either passed by reference into a function or indexed via + * a volatile variable. Therefore, in all use cases tested so far, the volatile + * qualifier can be omitted in order to provide a moderate performance + * improvement without adversely affecting functional behaviour. The assembly + * instructions generated by the IAR, ARM and GCC compilers when the respective + * compiler's options were set for maximum optimisation has been inspected and + * deemed to be as intended. That said, as compiler technology advances, and + * especially if aggressive cross module optimisation is used (a use case that + * has not been exercised to any great extend) then it is feasible that the + * volatile qualifier will be needed for correct optimisation. It is expected + * that a compiler removing essential code because, without the volatile + * qualifier on the list structure members and with aggressive cross module + * optimisation, the compiler deemed the code unnecessary will result in + * complete and obvious failure of the scheduler. If this is ever experienced + * then the volatile qualifier can be inserted in the relevant places within the + * list structures by simply defining configLIST_VOLATILE to volatile in + * FreeRTOSConfig.h (as per the example at the bottom of this comment block). + * If configLIST_VOLATILE is not defined then the preprocessor directives below + * will simply #define configLIST_VOLATILE away completely. + * + * To use volatile list structure members then add the following line to + * FreeRTOSConfig.h (without the quotes): + * "#define configLIST_VOLATILE volatile" + */ +#ifndef configLIST_VOLATILE + #define configLIST_VOLATILE +#endif /* configSUPPORT_CROSS_MODULE_OPTIMISATION */ + +/* *INDENT-OFF* */ +#ifdef __cplusplus + extern "C" { +#endif +/* *INDENT-ON* */ + +/* Macros that can be used to place known values within the list structures, + * then check that the known values do not get corrupted during the execution of + * the application. These may catch the list data structures being overwritten in + * memory. They will not catch data errors caused by incorrect configuration or + * use of FreeRTOS.*/ +#if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 0 ) + /* Define the macros to do nothing. */ + #define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE + #define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE + #define listFIRST_LIST_INTEGRITY_CHECK_VALUE + #define listSECOND_LIST_INTEGRITY_CHECK_VALUE + #define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) + #define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) + #define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ) + #define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ) + #define listTEST_LIST_ITEM_INTEGRITY( pxItem ) + #define listTEST_LIST_INTEGRITY( pxList ) +#else /* if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 0 ) */ + /* Define macros that add new members into the list structures. */ + #define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE TickType_t xListItemIntegrityValue1; + #define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE TickType_t xListItemIntegrityValue2; + #define listFIRST_LIST_INTEGRITY_CHECK_VALUE TickType_t xListIntegrityValue1; + #define listSECOND_LIST_INTEGRITY_CHECK_VALUE TickType_t xListIntegrityValue2; + +/* Define macros that set the new structure members to known values. */ + #define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) ( pxItem )->xListItemIntegrityValue1 = pdINTEGRITY_CHECK_VALUE + #define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) ( pxItem )->xListItemIntegrityValue2 = pdINTEGRITY_CHECK_VALUE + #define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ) ( pxList )->xListIntegrityValue1 = pdINTEGRITY_CHECK_VALUE + #define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ) ( pxList )->xListIntegrityValue2 = pdINTEGRITY_CHECK_VALUE + +/* Define macros that will assert if one of the structure members does not + * contain its expected value. */ + #define listTEST_LIST_ITEM_INTEGRITY( pxItem ) configASSERT( ( ( pxItem )->xListItemIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxItem )->xListItemIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) ) + #define listTEST_LIST_INTEGRITY( pxList ) configASSERT( ( ( pxList )->xListIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxList )->xListIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) ) +#endif /* configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES */ + + +/* + * Definition of the only type of object that a list can contain. + */ +struct xLIST; +struct xLIST_ITEM +{ + listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + configLIST_VOLATILE TickType_t xItemValue; /*< The value being listed. In most cases this is used to sort the list in ascending order. */ + struct xLIST_ITEM * configLIST_VOLATILE pxNext; /*< Pointer to the next ListItem_t in the list. */ + struct xLIST_ITEM * configLIST_VOLATILE pxPrevious; /*< Pointer to the previous ListItem_t in the list. */ + void * pvOwner; /*< Pointer to the object (normally a TCB) that contains the list item. There is therefore a two way link between the object containing the list item and the list item itself. */ + struct xLIST * configLIST_VOLATILE pxContainer; /*< Pointer to the list in which this list item is placed (if any). */ + listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ +}; +typedef struct xLIST_ITEM ListItem_t; /* For some reason lint wants this as two separate definitions. */ + +struct xMINI_LIST_ITEM +{ + listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + configLIST_VOLATILE TickType_t xItemValue; + struct xLIST_ITEM * configLIST_VOLATILE pxNext; + struct xLIST_ITEM * configLIST_VOLATILE pxPrevious; +}; +typedef struct xMINI_LIST_ITEM MiniListItem_t; + +/* + * Definition of the type of queue used by the scheduler. + */ +typedef struct xLIST +{ + listFIRST_LIST_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + volatile UBaseType_t uxNumberOfItems; + ListItem_t * configLIST_VOLATILE pxIndex; /*< Used to walk through the list. Points to the last item returned by a call to listGET_OWNER_OF_NEXT_ENTRY (). */ + MiniListItem_t xListEnd; /*< List item that contains the maximum possible item value meaning it is always at the end of the list and is therefore used as a marker. */ + listSECOND_LIST_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ +} List_t; + +/* + * Access macro to set the owner of a list item. The owner of a list item + * is the object (usually a TCB) that contains the list item. + * + * \page listSET_LIST_ITEM_OWNER listSET_LIST_ITEM_OWNER + * \ingroup LinkedList + */ +#define listSET_LIST_ITEM_OWNER( pxListItem, pxOwner ) ( ( pxListItem )->pvOwner = ( void * ) ( pxOwner ) ) + +/* + * Access macro to get the owner of a list item. The owner of a list item + * is the object (usually a TCB) that contains the list item. + * + * \page listGET_LIST_ITEM_OWNER listSET_LIST_ITEM_OWNER + * \ingroup LinkedList + */ +#define listGET_LIST_ITEM_OWNER( pxListItem ) ( ( pxListItem )->pvOwner ) + +/* + * Access macro to set the value of the list item. In most cases the value is + * used to sort the list in ascending order. + * + * \page listSET_LIST_ITEM_VALUE listSET_LIST_ITEM_VALUE + * \ingroup LinkedList + */ +#define listSET_LIST_ITEM_VALUE( pxListItem, xValue ) ( ( pxListItem )->xItemValue = ( xValue ) ) + +/* + * Access macro to retrieve the value of the list item. The value can + * represent anything - for example the priority of a task, or the time at + * which a task should be unblocked. + * + * \page listGET_LIST_ITEM_VALUE listGET_LIST_ITEM_VALUE + * \ingroup LinkedList + */ +#define listGET_LIST_ITEM_VALUE( pxListItem ) ( ( pxListItem )->xItemValue ) + +/* + * Access macro to retrieve the value of the list item at the head of a given + * list. + * + * \page listGET_LIST_ITEM_VALUE listGET_LIST_ITEM_VALUE + * \ingroup LinkedList + */ +#define listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxList ) ( ( ( pxList )->xListEnd ).pxNext->xItemValue ) + +/* + * Return the list item at the head of the list. + * + * \page listGET_HEAD_ENTRY listGET_HEAD_ENTRY + * \ingroup LinkedList + */ +#define listGET_HEAD_ENTRY( pxList ) ( ( ( pxList )->xListEnd ).pxNext ) + +/* + * Return the next list item. + * + * \page listGET_NEXT listGET_NEXT + * \ingroup LinkedList + */ +#define listGET_NEXT( pxListItem ) ( ( pxListItem )->pxNext ) + +/* + * Return the list item that marks the end of the list + * + * \page listGET_END_MARKER listGET_END_MARKER + * \ingroup LinkedList + */ +#define listGET_END_MARKER( pxList ) ( ( ListItem_t const * ) ( &( ( pxList )->xListEnd ) ) ) + +/* + * Access macro to determine if a list contains any items. The macro will + * only have the value true if the list is empty. + * + * \page listLIST_IS_EMPTY listLIST_IS_EMPTY + * \ingroup LinkedList + */ +#define listLIST_IS_EMPTY( pxList ) ( ( ( pxList )->uxNumberOfItems == ( UBaseType_t ) 0 ) ? pdTRUE : pdFALSE ) + +/* + * Access macro to return the number of items in the list. + */ +#define listCURRENT_LIST_LENGTH( pxList ) ( ( pxList )->uxNumberOfItems ) + +/* + * Access function to obtain the owner of the next entry in a list. + * + * The list member pxIndex is used to walk through a list. Calling + * listGET_OWNER_OF_NEXT_ENTRY increments pxIndex to the next item in the list + * and returns that entry's pxOwner parameter. Using multiple calls to this + * function it is therefore possible to move through every item contained in + * a list. + * + * The pxOwner parameter of a list item is a pointer to the object that owns + * the list item. In the scheduler this is normally a task control block. + * The pxOwner parameter effectively creates a two way link between the list + * item and its owner. + * + * @param pxTCB pxTCB is set to the address of the owner of the next list item. + * @param pxList The list from which the next item owner is to be returned. + * + * \page listGET_OWNER_OF_NEXT_ENTRY listGET_OWNER_OF_NEXT_ENTRY + * \ingroup LinkedList + */ +#define listGET_OWNER_OF_NEXT_ENTRY( pxTCB, pxList ) \ + { \ + List_t * const pxConstList = ( pxList ); \ + /* Increment the index to the next item and return the item, ensuring */ \ + /* we don't return the marker used at the end of the list. */ \ + ( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext; \ + if( ( void * ) ( pxConstList )->pxIndex == ( void * ) &( ( pxConstList )->xListEnd ) ) \ + { \ + ( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext; \ + } \ + ( pxTCB ) = ( pxConstList )->pxIndex->pvOwner; \ + } + +/* + * Version of uxListRemove() that does not return a value. Provided as a slight + * optimisation for xTaskIncrementTick() by being inline. + * + * Remove an item from a list. The list item has a pointer to the list that + * it is in, so only the list item need be passed into the function. + * + * @param uxListRemove The item to be removed. The item will remove itself from + * the list pointed to by it's pxContainer parameter. + * + * @return The number of items that remain in the list after the list item has + * been removed. + * + * \page listREMOVE_ITEM listREMOVE_ITEM + * \ingroup LinkedList + */ +#define listREMOVE_ITEM( pxItemToRemove ) \ + { \ + /* The list item knows which list it is in. Obtain the list from the list \ + * item. */ \ + List_t * const pxList = ( pxItemToRemove )->pxContainer; \ + \ + ( pxItemToRemove )->pxNext->pxPrevious = ( pxItemToRemove )->pxPrevious; \ + ( pxItemToRemove )->pxPrevious->pxNext = ( pxItemToRemove )->pxNext; \ + /* Make sure the index is left pointing to a valid item. */ \ + if( pxList->pxIndex == ( pxItemToRemove ) ) \ + { \ + pxList->pxIndex = ( pxItemToRemove )->pxPrevious; \ + } \ + \ + ( pxItemToRemove )->pxContainer = NULL; \ + ( pxList->uxNumberOfItems )--; \ + } + +/* + * Inline version of vListInsertEnd() to provide slight optimisation for + * xTaskIncrementTick(). + * + * Insert a list item into a list. The item will be inserted in a position + * such that it will be the last item within the list returned by multiple + * calls to listGET_OWNER_OF_NEXT_ENTRY. + * + * The list member pxIndex is used to walk through a list. Calling + * listGET_OWNER_OF_NEXT_ENTRY increments pxIndex to the next item in the list. + * Placing an item in a list using vListInsertEnd effectively places the item + * in the list position pointed to by pxIndex. This means that every other + * item within the list will be returned by listGET_OWNER_OF_NEXT_ENTRY before + * the pxIndex parameter again points to the item being inserted. + * + * @param pxList The list into which the item is to be inserted. + * + * @param pxNewListItem The list item to be inserted into the list. + * + * \page listINSERT_END listINSERT_END + * \ingroup LinkedList + */ +#define listINSERT_END( pxList, pxNewListItem ) \ + { \ + ListItem_t * const pxIndex = ( pxList )->pxIndex; \ + \ + /* Only effective when configASSERT() is also defined, these tests may catch \ + * the list data structures being overwritten in memory. They will not catch \ + * data errors caused by incorrect configuration or use of FreeRTOS. */ \ + listTEST_LIST_INTEGRITY( ( pxList ) ); \ + listTEST_LIST_ITEM_INTEGRITY( ( pxNewListItem ) ); \ + \ + /* Insert a new list item into ( pxList ), but rather than sort the list, \ + * makes the new list item the last item to be removed by a call to \ + * listGET_OWNER_OF_NEXT_ENTRY(). */ \ + ( pxNewListItem )->pxNext = pxIndex; \ + ( pxNewListItem )->pxPrevious = pxIndex->pxPrevious; \ + \ + pxIndex->pxPrevious->pxNext = ( pxNewListItem ); \ + pxIndex->pxPrevious = ( pxNewListItem ); \ + \ + /* Remember which list the item is in. */ \ + ( pxNewListItem )->pxContainer = ( pxList ); \ + \ + ( ( pxList )->uxNumberOfItems )++; \ + } + +/* + * Access function to obtain the owner of the first entry in a list. Lists + * are normally sorted in ascending item value order. + * + * This function returns the pxOwner member of the first item in the list. + * The pxOwner parameter of a list item is a pointer to the object that owns + * the list item. In the scheduler this is normally a task control block. + * The pxOwner parameter effectively creates a two way link between the list + * item and its owner. + * + * @param pxList The list from which the owner of the head item is to be + * returned. + * + * \page listGET_OWNER_OF_HEAD_ENTRY listGET_OWNER_OF_HEAD_ENTRY + * \ingroup LinkedList + */ +#define listGET_OWNER_OF_HEAD_ENTRY( pxList ) ( ( &( ( pxList )->xListEnd ) )->pxNext->pvOwner ) + +/* + * Check to see if a list item is within a list. The list item maintains a + * "container" pointer that points to the list it is in. All this macro does + * is check to see if the container and the list match. + * + * @param pxList The list we want to know if the list item is within. + * @param pxListItem The list item we want to know if is in the list. + * @return pdTRUE if the list item is in the list, otherwise pdFALSE. + */ +#define listIS_CONTAINED_WITHIN( pxList, pxListItem ) ( ( ( pxListItem )->pxContainer == ( pxList ) ) ? ( pdTRUE ) : ( pdFALSE ) ) + +/* + * Return the list a list item is contained within (referenced from). + * + * @param pxListItem The list item being queried. + * @return A pointer to the List_t object that references the pxListItem + */ +#define listLIST_ITEM_CONTAINER( pxListItem ) ( ( pxListItem )->pxContainer ) + +/* + * This provides a crude means of knowing if a list has been initialised, as + * pxList->xListEnd.xItemValue is set to portMAX_DELAY by the vListInitialise() + * function. + */ +#define listLIST_IS_INITIALISED( pxList ) ( ( pxList )->xListEnd.xItemValue == portMAX_DELAY ) + +/* + * Must be called before a list is used! This initialises all the members + * of the list structure and inserts the xListEnd item into the list as a + * marker to the back of the list. + * + * @param pxList Pointer to the list being initialised. + * + * \page vListInitialise vListInitialise + * \ingroup LinkedList + */ +void vListInitialise( List_t * const pxList ) PRIVILEGED_FUNCTION; + +/* + * Must be called before a list item is used. This sets the list container to + * null so the item does not think that it is already contained in a list. + * + * @param pxItem Pointer to the list item being initialised. + * + * \page vListInitialiseItem vListInitialiseItem + * \ingroup LinkedList + */ +void vListInitialiseItem( ListItem_t * const pxItem ) PRIVILEGED_FUNCTION; + +/* + * Insert a list item into a list. The item will be inserted into the list in + * a position determined by its item value (ascending item value order). + * + * @param pxList The list into which the item is to be inserted. + * + * @param pxNewListItem The item that is to be placed in the list. + * + * \page vListInsert vListInsert + * \ingroup LinkedList + */ +void vListInsert( List_t * const pxList, + ListItem_t * const pxNewListItem ) PRIVILEGED_FUNCTION; + +/* + * Insert a list item into a list. The item will be inserted in a position + * such that it will be the last item within the list returned by multiple + * calls to listGET_OWNER_OF_NEXT_ENTRY. + * + * The list member pxIndex is used to walk through a list. Calling + * listGET_OWNER_OF_NEXT_ENTRY increments pxIndex to the next item in the list. + * Placing an item in a list using vListInsertEnd effectively places the item + * in the list position pointed to by pxIndex. This means that every other + * item within the list will be returned by listGET_OWNER_OF_NEXT_ENTRY before + * the pxIndex parameter again points to the item being inserted. + * + * @param pxList The list into which the item is to be inserted. + * + * @param pxNewListItem The list item to be inserted into the list. + * + * \page vListInsertEnd vListInsertEnd + * \ingroup LinkedList + */ +void vListInsertEnd( List_t * const pxList, + ListItem_t * const pxNewListItem ) PRIVILEGED_FUNCTION; + +/* + * Remove an item from a list. The list item has a pointer to the list that + * it is in, so only the list item need be passed into the function. + * + * @param uxListRemove The item to be removed. The item will remove itself from + * the list pointed to by it's pxContainer parameter. + * + * @return The number of items that remain in the list after the list item has + * been removed. + * + * \page uxListRemove uxListRemove + * \ingroup LinkedList + */ +UBaseType_t uxListRemove( ListItem_t * const pxItemToRemove ) PRIVILEGED_FUNCTION; + +/* *INDENT-OFF* */ +#ifdef __cplusplus + } +#endif +/* *INDENT-ON* */ + +#endif /* ifndef LIST_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/message_buffer.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/message_buffer.h new file mode 100644 index 0000000..1406267 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/message_buffer.h @@ -0,0 +1,823 @@ +/* + * FreeRTOS Kernel V10.4.6 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + + +/* + * Message buffers build functionality on top of FreeRTOS stream buffers. + * Whereas stream buffers are used to send a continuous stream of data from one + * task or interrupt to another, message buffers are used to send variable + * length discrete messages from one task or interrupt to another. Their + * implementation is light weight, making them particularly suited for interrupt + * to task and core to core communication scenarios. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xMessageBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xMessageBufferRead()) inside a critical section and set the receive + * timeout to 0. + * + * Message buffers hold variable length messages. To enable that, when a + * message is written to the message buffer an additional sizeof( size_t ) bytes + * are also written to store the message's length (that happens internally, with + * the API function). sizeof( size_t ) is typically 4 bytes on a 32-bit + * architecture, so writing a 10 byte message to a message buffer on a 32-bit + * architecture will actually reduce the available space in the message buffer + * by 14 bytes (10 byte are used by the message, and 4 bytes to hold the length + * of the message). + */ + +#ifndef FREERTOS_MESSAGE_BUFFER_H +#define FREERTOS_MESSAGE_BUFFER_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h must appear in source files before include message_buffer.h" +#endif + +/* Message buffers are built onto of stream buffers. */ +#include "stream_buffer.h" + +/* *INDENT-OFF* */ +#if defined( __cplusplus ) + extern "C" { +#endif +/* *INDENT-ON* */ + +/** + * Type by which message buffers are referenced. For example, a call to + * xMessageBufferCreate() returns an MessageBufferHandle_t variable that can + * then be used as a parameter to xMessageBufferSend(), xMessageBufferReceive(), + * etc. + */ +typedef void * MessageBufferHandle_t; + +/*-----------------------------------------------------------*/ + +/** + * message_buffer.h + * + * @code{c} + * MessageBufferHandle_t xMessageBufferCreate( size_t xBufferSizeBytes ); + * @endcode + * + * Creates a new message buffer using dynamically allocated memory. See + * xMessageBufferCreateStatic() for a version that uses statically allocated + * memory (memory that is allocated at compile time). + * + * configSUPPORT_DYNAMIC_ALLOCATION must be set to 1 or left undefined in + * FreeRTOSConfig.h for xMessageBufferCreate() to be available. + * + * @param xBufferSizeBytes The total number of bytes (not messages) the message + * buffer will be able to hold at any one time. When a message is written to + * the message buffer an additional sizeof( size_t ) bytes are also written to + * store the message's length. sizeof( size_t ) is typically 4 bytes on a + * 32-bit architecture, so on most 32-bit architectures a 10 byte message will + * take up 14 bytes of message buffer space. + * + * @return If NULL is returned, then the message buffer cannot be created + * because there is insufficient heap memory available for FreeRTOS to allocate + * the message buffer data structures and storage area. A non-NULL value being + * returned indicates that the message buffer has been created successfully - + * the returned value should be stored as the handle to the created message + * buffer. + * + * Example use: + * @code{c} + * + * void vAFunction( void ) + * { + * MessageBufferHandle_t xMessageBuffer; + * const size_t xMessageBufferSizeBytes = 100; + * + * // Create a message buffer that can hold 100 bytes. The memory used to hold + * // both the message buffer structure and the messages themselves is allocated + * // dynamically. Each message added to the buffer consumes an additional 4 + * // bytes which are used to hold the lengh of the message. + * xMessageBuffer = xMessageBufferCreate( xMessageBufferSizeBytes ); + * + * if( xMessageBuffer == NULL ) + * { + * // There was not enough heap memory space available to create the + * // message buffer. + * } + * else + * { + * // The message buffer was created successfully and can now be used. + * } + * + * @endcode + * \defgroup xMessageBufferCreate xMessageBufferCreate + * \ingroup MessageBufferManagement + */ +#define xMessageBufferCreate( xBufferSizeBytes ) \ + ( MessageBufferHandle_t ) xStreamBufferGenericCreate( xBufferSizeBytes, ( size_t ) 0, pdTRUE ) + +/** + * message_buffer.h + * + * @code{c} + * MessageBufferHandle_t xMessageBufferCreateStatic( size_t xBufferSizeBytes, + * uint8_t *pucMessageBufferStorageArea, + * StaticMessageBuffer_t *pxStaticMessageBuffer ); + * @endcode + * Creates a new message buffer using statically allocated memory. See + * xMessageBufferCreate() for a version that uses dynamically allocated memory. + * + * @param xBufferSizeBytes The size, in bytes, of the buffer pointed to by the + * pucMessageBufferStorageArea parameter. When a message is written to the + * message buffer an additional sizeof( size_t ) bytes are also written to store + * the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit + * architecture, so on most 32-bit architecture a 10 byte message will take up + * 14 bytes of message buffer space. The maximum number of bytes that can be + * stored in the message buffer is actually (xBufferSizeBytes - 1). + * + * @param pucMessageBufferStorageArea Must point to a uint8_t array that is at + * least xBufferSizeBytes big. This is the array to which messages are + * copied when they are written to the message buffer. + * + * @param pxStaticMessageBuffer Must point to a variable of type + * StaticMessageBuffer_t, which will be used to hold the message buffer's data + * structure. + * + * @return If the message buffer is created successfully then a handle to the + * created message buffer is returned. If either pucMessageBufferStorageArea or + * pxStaticmessageBuffer are NULL then NULL is returned. + * + * Example use: + * @code{c} + * + * // Used to dimension the array used to hold the messages. The available space + * // will actually be one less than this, so 999. + #define STORAGE_SIZE_BYTES 1000 + * + * // Defines the memory that will actually hold the messages within the message + * // buffer. + * static uint8_t ucStorageBuffer[ STORAGE_SIZE_BYTES ]; + * + * // The variable used to hold the message buffer structure. + * StaticMessageBuffer_t xMessageBufferStruct; + * + * void MyFunction( void ) + * { + * MessageBufferHandle_t xMessageBuffer; + * + * xMessageBuffer = xMessageBufferCreateStatic( sizeof( ucStorageBuffer ), + * ucStorageBuffer, + * &xMessageBufferStruct ); + * + * // As neither the pucMessageBufferStorageArea or pxStaticMessageBuffer + * // parameters were NULL, xMessageBuffer will not be NULL, and can be used to + * // reference the created message buffer in other message buffer API calls. + * + * // Other code that uses the message buffer can go here. + * } + * + * @endcode + * \defgroup xMessageBufferCreateStatic xMessageBufferCreateStatic + * \ingroup MessageBufferManagement + */ +#define xMessageBufferCreateStatic( xBufferSizeBytes, pucMessageBufferStorageArea, pxStaticMessageBuffer ) \ + ( MessageBufferHandle_t ) xStreamBufferGenericCreateStatic( xBufferSizeBytes, 0, pdTRUE, pucMessageBufferStorageArea, pxStaticMessageBuffer ) + +/** + * message_buffer.h + * + * @code{c} + * size_t xMessageBufferSend( MessageBufferHandle_t xMessageBuffer, + * const void *pvTxData, + * size_t xDataLengthBytes, + * TickType_t xTicksToWait ); + * @endcode + * + * Sends a discrete message to the message buffer. The message can be any + * length that fits within the buffer's free space, and is copied into the + * buffer. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xMessageBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xMessageBufferRead()) inside a critical section and set the receive + * block time to 0. + * + * Use xMessageBufferSend() to write to a message buffer from a task. Use + * xMessageBufferSendFromISR() to write to a message buffer from an interrupt + * service routine (ISR). + * + * @param xMessageBuffer The handle of the message buffer to which a message is + * being sent. + * + * @param pvTxData A pointer to the message that is to be copied into the + * message buffer. + * + * @param xDataLengthBytes The length of the message. That is, the number of + * bytes to copy from pvTxData into the message buffer. When a message is + * written to the message buffer an additional sizeof( size_t ) bytes are also + * written to store the message's length. sizeof( size_t ) is typically 4 bytes + * on a 32-bit architecture, so on most 32-bit architecture setting + * xDataLengthBytes to 20 will reduce the free space in the message buffer by 24 + * bytes (20 bytes of message data and 4 bytes to hold the message length). + * + * @param xTicksToWait The maximum amount of time the calling task should remain + * in the Blocked state to wait for enough space to become available in the + * message buffer, should the message buffer have insufficient space when + * xMessageBufferSend() is called. The calling task will never block if + * xTicksToWait is zero. The block time is specified in tick periods, so the + * absolute time it represents is dependent on the tick frequency. The macro + * pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into + * a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will cause + * the task to wait indefinitely (without timing out), provided + * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. Tasks do not use any + * CPU time when they are in the Blocked state. + * + * @return The number of bytes written to the message buffer. If the call to + * xMessageBufferSend() times out before there was enough space to write the + * message into the message buffer then zero is returned. If the call did not + * time out then xDataLengthBytes is returned. + * + * Example use: + * @code{c} + * void vAFunction( MessageBufferHandle_t xMessageBuffer ) + * { + * size_t xBytesSent; + * uint8_t ucArrayToSend[] = { 0, 1, 2, 3 }; + * char *pcStringToSend = "String to send"; + * const TickType_t x100ms = pdMS_TO_TICKS( 100 ); + * + * // Send an array to the message buffer, blocking for a maximum of 100ms to + * // wait for enough space to be available in the message buffer. + * xBytesSent = xMessageBufferSend( xMessageBuffer, ( void * ) ucArrayToSend, sizeof( ucArrayToSend ), x100ms ); + * + * if( xBytesSent != sizeof( ucArrayToSend ) ) + * { + * // The call to xMessageBufferSend() times out before there was enough + * // space in the buffer for the data to be written. + * } + * + * // Send the string to the message buffer. Return immediately if there is + * // not enough space in the buffer. + * xBytesSent = xMessageBufferSend( xMessageBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), 0 ); + * + * if( xBytesSent != strlen( pcStringToSend ) ) + * { + * // The string could not be added to the message buffer because there was + * // not enough free space in the buffer. + * } + * } + * @endcode + * \defgroup xMessageBufferSend xMessageBufferSend + * \ingroup MessageBufferManagement + */ +#define xMessageBufferSend( xMessageBuffer, pvTxData, xDataLengthBytes, xTicksToWait ) \ + xStreamBufferSend( ( StreamBufferHandle_t ) xMessageBuffer, pvTxData, xDataLengthBytes, xTicksToWait ) + +/** + * message_buffer.h + * + * @code{c} + * size_t xMessageBufferSendFromISR( MessageBufferHandle_t xMessageBuffer, + * const void *pvTxData, + * size_t xDataLengthBytes, + * BaseType_t *pxHigherPriorityTaskWoken ); + * @endcode + * + * Interrupt safe version of the API function that sends a discrete message to + * the message buffer. The message can be any length that fits within the + * buffer's free space, and is copied into the buffer. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xMessageBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xMessageBufferRead()) inside a critical section and set the receive + * block time to 0. + * + * Use xMessageBufferSend() to write to a message buffer from a task. Use + * xMessageBufferSendFromISR() to write to a message buffer from an interrupt + * service routine (ISR). + * + * @param xMessageBuffer The handle of the message buffer to which a message is + * being sent. + * + * @param pvTxData A pointer to the message that is to be copied into the + * message buffer. + * + * @param xDataLengthBytes The length of the message. That is, the number of + * bytes to copy from pvTxData into the message buffer. When a message is + * written to the message buffer an additional sizeof( size_t ) bytes are also + * written to store the message's length. sizeof( size_t ) is typically 4 bytes + * on a 32-bit architecture, so on most 32-bit architecture setting + * xDataLengthBytes to 20 will reduce the free space in the message buffer by 24 + * bytes (20 bytes of message data and 4 bytes to hold the message length). + * + * @param pxHigherPriorityTaskWoken It is possible that a message buffer will + * have a task blocked on it waiting for data. Calling + * xMessageBufferSendFromISR() can make data available, and so cause a task that + * was waiting for data to leave the Blocked state. If calling + * xMessageBufferSendFromISR() causes a task to leave the Blocked state, and the + * unblocked task has a priority higher than the currently executing task (the + * task that was interrupted), then, internally, xMessageBufferSendFromISR() + * will set *pxHigherPriorityTaskWoken to pdTRUE. If + * xMessageBufferSendFromISR() sets this value to pdTRUE, then normally a + * context switch should be performed before the interrupt is exited. This will + * ensure that the interrupt returns directly to the highest priority Ready + * state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it + * is passed into the function. See the code example below for an example. + * + * @return The number of bytes actually written to the message buffer. If the + * message buffer didn't have enough free space for the message to be stored + * then 0 is returned, otherwise xDataLengthBytes is returned. + * + * Example use: + * @code{c} + * // A message buffer that has already been created. + * MessageBufferHandle_t xMessageBuffer; + * + * void vAnInterruptServiceRoutine( void ) + * { + * size_t xBytesSent; + * char *pcStringToSend = "String to send"; + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE. + * + * // Attempt to send the string to the message buffer. + * xBytesSent = xMessageBufferSendFromISR( xMessageBuffer, + * ( void * ) pcStringToSend, + * strlen( pcStringToSend ), + * &xHigherPriorityTaskWoken ); + * + * if( xBytesSent != strlen( pcStringToSend ) ) + * { + * // The string could not be added to the message buffer because there was + * // not enough free space in the buffer. + * } + * + * // If xHigherPriorityTaskWoken was set to pdTRUE inside + * // xMessageBufferSendFromISR() then a task that has a priority above the + * // priority of the currently executing task was unblocked and a context + * // switch should be performed to ensure the ISR returns to the unblocked + * // task. In most FreeRTOS ports this is done by simply passing + * // xHigherPriorityTaskWoken into portYIELD_FROM_ISR(), which will test the + * // variables value, and perform the context switch if necessary. Check the + * // documentation for the port in use for port specific instructions. + * portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); + * } + * @endcode + * \defgroup xMessageBufferSendFromISR xMessageBufferSendFromISR + * \ingroup MessageBufferManagement + */ +#define xMessageBufferSendFromISR( xMessageBuffer, pvTxData, xDataLengthBytes, pxHigherPriorityTaskWoken ) \ + xStreamBufferSendFromISR( ( StreamBufferHandle_t ) xMessageBuffer, pvTxData, xDataLengthBytes, pxHigherPriorityTaskWoken ) + +/** + * message_buffer.h + * + * @code{c} + * size_t xMessageBufferReceive( MessageBufferHandle_t xMessageBuffer, + * void *pvRxData, + * size_t xBufferLengthBytes, + * TickType_t xTicksToWait ); + * @endcode + * + * Receives a discrete message from a message buffer. Messages can be of + * variable length and are copied out of the buffer. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xMessageBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xMessageBufferRead()) inside a critical section and set the receive + * block time to 0. + * + * Use xMessageBufferReceive() to read from a message buffer from a task. Use + * xMessageBufferReceiveFromISR() to read from a message buffer from an + * interrupt service routine (ISR). + * + * @param xMessageBuffer The handle of the message buffer from which a message + * is being received. + * + * @param pvRxData A pointer to the buffer into which the received message is + * to be copied. + * + * @param xBufferLengthBytes The length of the buffer pointed to by the pvRxData + * parameter. This sets the maximum length of the message that can be received. + * If xBufferLengthBytes is too small to hold the next message then the message + * will be left in the message buffer and 0 will be returned. + * + * @param xTicksToWait The maximum amount of time the task should remain in the + * Blocked state to wait for a message, should the message buffer be empty. + * xMessageBufferReceive() will return immediately if xTicksToWait is zero and + * the message buffer is empty. The block time is specified in tick periods, so + * the absolute time it represents is dependent on the tick frequency. The + * macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds + * into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will + * cause the task to wait indefinitely (without timing out), provided + * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. Tasks do not use any + * CPU time when they are in the Blocked state. + * + * @return The length, in bytes, of the message read from the message buffer, if + * any. If xMessageBufferReceive() times out before a message became available + * then zero is returned. If the length of the message is greater than + * xBufferLengthBytes then the message will be left in the message buffer and + * zero is returned. + * + * Example use: + * @code{c} + * void vAFunction( MessageBuffer_t xMessageBuffer ) + * { + * uint8_t ucRxData[ 20 ]; + * size_t xReceivedBytes; + * const TickType_t xBlockTime = pdMS_TO_TICKS( 20 ); + * + * // Receive the next message from the message buffer. Wait in the Blocked + * // state (so not using any CPU processing time) for a maximum of 100ms for + * // a message to become available. + * xReceivedBytes = xMessageBufferReceive( xMessageBuffer, + * ( void * ) ucRxData, + * sizeof( ucRxData ), + * xBlockTime ); + * + * if( xReceivedBytes > 0 ) + * { + * // A ucRxData contains a message that is xReceivedBytes long. Process + * // the message here.... + * } + * } + * @endcode + * \defgroup xMessageBufferReceive xMessageBufferReceive + * \ingroup MessageBufferManagement + */ +#define xMessageBufferReceive( xMessageBuffer, pvRxData, xBufferLengthBytes, xTicksToWait ) \ + xStreamBufferReceive( ( StreamBufferHandle_t ) xMessageBuffer, pvRxData, xBufferLengthBytes, xTicksToWait ) + + +/** + * message_buffer.h + * + * @code{c} + * size_t xMessageBufferReceiveFromISR( MessageBufferHandle_t xMessageBuffer, + * void *pvRxData, + * size_t xBufferLengthBytes, + * BaseType_t *pxHigherPriorityTaskWoken ); + * @endcode + * + * An interrupt safe version of the API function that receives a discrete + * message from a message buffer. Messages can be of variable length and are + * copied out of the buffer. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xMessageBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xMessageBufferRead()) inside a critical section and set the receive + * block time to 0. + * + * Use xMessageBufferReceive() to read from a message buffer from a task. Use + * xMessageBufferReceiveFromISR() to read from a message buffer from an + * interrupt service routine (ISR). + * + * @param xMessageBuffer The handle of the message buffer from which a message + * is being received. + * + * @param pvRxData A pointer to the buffer into which the received message is + * to be copied. + * + * @param xBufferLengthBytes The length of the buffer pointed to by the pvRxData + * parameter. This sets the maximum length of the message that can be received. + * If xBufferLengthBytes is too small to hold the next message then the message + * will be left in the message buffer and 0 will be returned. + * + * @param pxHigherPriorityTaskWoken It is possible that a message buffer will + * have a task blocked on it waiting for space to become available. Calling + * xMessageBufferReceiveFromISR() can make space available, and so cause a task + * that is waiting for space to leave the Blocked state. If calling + * xMessageBufferReceiveFromISR() causes a task to leave the Blocked state, and + * the unblocked task has a priority higher than the currently executing task + * (the task that was interrupted), then, internally, + * xMessageBufferReceiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. + * If xMessageBufferReceiveFromISR() sets this value to pdTRUE, then normally a + * context switch should be performed before the interrupt is exited. That will + * ensure the interrupt returns directly to the highest priority Ready state + * task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is + * passed into the function. See the code example below for an example. + * + * @return The length, in bytes, of the message read from the message buffer, if + * any. + * + * Example use: + * @code{c} + * // A message buffer that has already been created. + * MessageBuffer_t xMessageBuffer; + * + * void vAnInterruptServiceRoutine( void ) + * { + * uint8_t ucRxData[ 20 ]; + * size_t xReceivedBytes; + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE. + * + * // Receive the next message from the message buffer. + * xReceivedBytes = xMessageBufferReceiveFromISR( xMessageBuffer, + * ( void * ) ucRxData, + * sizeof( ucRxData ), + * &xHigherPriorityTaskWoken ); + * + * if( xReceivedBytes > 0 ) + * { + * // A ucRxData contains a message that is xReceivedBytes long. Process + * // the message here.... + * } + * + * // If xHigherPriorityTaskWoken was set to pdTRUE inside + * // xMessageBufferReceiveFromISR() then a task that has a priority above the + * // priority of the currently executing task was unblocked and a context + * // switch should be performed to ensure the ISR returns to the unblocked + * // task. In most FreeRTOS ports this is done by simply passing + * // xHigherPriorityTaskWoken into portYIELD_FROM_ISR(), which will test the + * // variables value, and perform the context switch if necessary. Check the + * // documentation for the port in use for port specific instructions. + * portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); + * } + * @endcode + * \defgroup xMessageBufferReceiveFromISR xMessageBufferReceiveFromISR + * \ingroup MessageBufferManagement + */ +#define xMessageBufferReceiveFromISR( xMessageBuffer, pvRxData, xBufferLengthBytes, pxHigherPriorityTaskWoken ) \ + xStreamBufferReceiveFromISR( ( StreamBufferHandle_t ) xMessageBuffer, pvRxData, xBufferLengthBytes, pxHigherPriorityTaskWoken ) + +/** + * message_buffer.h + * + * @code{c} + * void vMessageBufferDelete( MessageBufferHandle_t xMessageBuffer ); + * @endcode + * + * Deletes a message buffer that was previously created using a call to + * xMessageBufferCreate() or xMessageBufferCreateStatic(). If the message + * buffer was created using dynamic memory (that is, by xMessageBufferCreate()), + * then the allocated memory is freed. + * + * A message buffer handle must not be used after the message buffer has been + * deleted. + * + * @param xMessageBuffer The handle of the message buffer to be deleted. + * + */ +#define vMessageBufferDelete( xMessageBuffer ) \ + vStreamBufferDelete( ( StreamBufferHandle_t ) xMessageBuffer ) + +/** + * message_buffer.h + * @code{c} + * BaseType_t xMessageBufferIsFull( MessageBufferHandle_t xMessageBuffer ); + * @endcode + * + * Tests to see if a message buffer is full. A message buffer is full if it + * cannot accept any more messages, of any size, until space is made available + * by a message being removed from the message buffer. + * + * @param xMessageBuffer The handle of the message buffer being queried. + * + * @return If the message buffer referenced by xMessageBuffer is full then + * pdTRUE is returned. Otherwise pdFALSE is returned. + */ +#define xMessageBufferIsFull( xMessageBuffer ) \ + xStreamBufferIsFull( ( StreamBufferHandle_t ) xMessageBuffer ) + +/** + * message_buffer.h + * @code{c} + * BaseType_t xMessageBufferIsEmpty( MessageBufferHandle_t xMessageBuffer ); + * @endcode + * + * Tests to see if a message buffer is empty (does not contain any messages). + * + * @param xMessageBuffer The handle of the message buffer being queried. + * + * @return If the message buffer referenced by xMessageBuffer is empty then + * pdTRUE is returned. Otherwise pdFALSE is returned. + * + */ +#define xMessageBufferIsEmpty( xMessageBuffer ) \ + xStreamBufferIsEmpty( ( StreamBufferHandle_t ) xMessageBuffer ) + +/** + * message_buffer.h + * @code{c} + * BaseType_t xMessageBufferReset( MessageBufferHandle_t xMessageBuffer ); + * @endcode + * + * Resets a message buffer to its initial empty state, discarding any message it + * contained. + * + * A message buffer can only be reset if there are no tasks blocked on it. + * + * @param xMessageBuffer The handle of the message buffer being reset. + * + * @return If the message buffer was reset then pdPASS is returned. If the + * message buffer could not be reset because either there was a task blocked on + * the message queue to wait for space to become available, or to wait for a + * a message to be available, then pdFAIL is returned. + * + * \defgroup xMessageBufferReset xMessageBufferReset + * \ingroup MessageBufferManagement + */ +#define xMessageBufferReset( xMessageBuffer ) \ + xStreamBufferReset( ( StreamBufferHandle_t ) xMessageBuffer ) + + +/** + * message_buffer.h + * @code{c} + * size_t xMessageBufferSpaceAvailable( MessageBufferHandle_t xMessageBuffer ); + * @endcode + * Returns the number of bytes of free space in the message buffer. + * + * @param xMessageBuffer The handle of the message buffer being queried. + * + * @return The number of bytes that can be written to the message buffer before + * the message buffer would be full. When a message is written to the message + * buffer an additional sizeof( size_t ) bytes are also written to store the + * message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit + * architecture, so if xMessageBufferSpacesAvailable() returns 10, then the size + * of the largest message that can be written to the message buffer is 6 bytes. + * + * \defgroup xMessageBufferSpaceAvailable xMessageBufferSpaceAvailable + * \ingroup MessageBufferManagement + */ +#define xMessageBufferSpaceAvailable( xMessageBuffer ) \ + xStreamBufferSpacesAvailable( ( StreamBufferHandle_t ) xMessageBuffer ) +#define xMessageBufferSpacesAvailable( xMessageBuffer ) \ + xStreamBufferSpacesAvailable( ( StreamBufferHandle_t ) xMessageBuffer ) /* Corrects typo in original macro name. */ + +/** + * message_buffer.h + * @code{c} + * size_t xMessageBufferNextLengthBytes( MessageBufferHandle_t xMessageBuffer ); + * @endcode + * Returns the length (in bytes) of the next message in a message buffer. + * Useful if xMessageBufferReceive() returned 0 because the size of the buffer + * passed into xMessageBufferReceive() was too small to hold the next message. + * + * @param xMessageBuffer The handle of the message buffer being queried. + * + * @return The length (in bytes) of the next message in the message buffer, or 0 + * if the message buffer is empty. + * + * \defgroup xMessageBufferNextLengthBytes xMessageBufferNextLengthBytes + * \ingroup MessageBufferManagement + */ +#define xMessageBufferNextLengthBytes( xMessageBuffer ) \ + xStreamBufferNextMessageLengthBytes( ( StreamBufferHandle_t ) xMessageBuffer ) PRIVILEGED_FUNCTION; + +/** + * message_buffer.h + * + * @code{c} + * BaseType_t xMessageBufferSendCompletedFromISR( MessageBufferHandle_t xMessageBuffer, BaseType_t *pxHigherPriorityTaskWoken ); + * @endcode + * + * For advanced users only. + * + * The sbSEND_COMPLETED() macro is called from within the FreeRTOS APIs when + * data is sent to a message buffer or stream buffer. If there was a task that + * was blocked on the message or stream buffer waiting for data to arrive then + * the sbSEND_COMPLETED() macro sends a notification to the task to remove it + * from the Blocked state. xMessageBufferSendCompletedFromISR() does the same + * thing. It is provided to enable application writers to implement their own + * version of sbSEND_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME. + * + * See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for + * additional information. + * + * @param xMessageBuffer The handle of the stream buffer to which data was + * written. + * + * @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be + * initialised to pdFALSE before it is passed into + * xMessageBufferSendCompletedFromISR(). If calling + * xMessageBufferSendCompletedFromISR() removes a task from the Blocked state, + * and the task has a priority above the priority of the currently running task, + * then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a + * context switch should be performed before exiting the ISR. + * + * @return If a task was removed from the Blocked state then pdTRUE is returned. + * Otherwise pdFALSE is returned. + * + * \defgroup xMessageBufferSendCompletedFromISR xMessageBufferSendCompletedFromISR + * \ingroup StreamBufferManagement + */ +#define xMessageBufferSendCompletedFromISR( xMessageBuffer, pxHigherPriorityTaskWoken ) \ + xStreamBufferSendCompletedFromISR( ( StreamBufferHandle_t ) xMessageBuffer, pxHigherPriorityTaskWoken ) + +/** + * message_buffer.h + * + * @code{c} + * BaseType_t xMessageBufferReceiveCompletedFromISR( MessageBufferHandle_t xMessageBuffer, BaseType_t *pxHigherPriorityTaskWoken ); + * @endcode + * + * For advanced users only. + * + * The sbRECEIVE_COMPLETED() macro is called from within the FreeRTOS APIs when + * data is read out of a message buffer or stream buffer. If there was a task + * that was blocked on the message or stream buffer waiting for data to arrive + * then the sbRECEIVE_COMPLETED() macro sends a notification to the task to + * remove it from the Blocked state. xMessageBufferReceiveCompletedFromISR() + * does the same thing. It is provided to enable application writers to + * implement their own version of sbRECEIVE_COMPLETED(), and MUST NOT BE USED AT + * ANY OTHER TIME. + * + * See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for + * additional information. + * + * @param xMessageBuffer The handle of the stream buffer from which data was + * read. + * + * @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be + * initialised to pdFALSE before it is passed into + * xMessageBufferReceiveCompletedFromISR(). If calling + * xMessageBufferReceiveCompletedFromISR() removes a task from the Blocked state, + * and the task has a priority above the priority of the currently running task, + * then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a + * context switch should be performed before exiting the ISR. + * + * @return If a task was removed from the Blocked state then pdTRUE is returned. + * Otherwise pdFALSE is returned. + * + * \defgroup xMessageBufferReceiveCompletedFromISR xMessageBufferReceiveCompletedFromISR + * \ingroup StreamBufferManagement + */ +#define xMessageBufferReceiveCompletedFromISR( xMessageBuffer, pxHigherPriorityTaskWoken ) \ + xStreamBufferReceiveCompletedFromISR( ( StreamBufferHandle_t ) xMessageBuffer, pxHigherPriorityTaskWoken ) + +/* *INDENT-OFF* */ +#if defined( __cplusplus ) + } /* extern "C" */ +#endif +/* *INDENT-ON* */ + +#endif /* !defined( FREERTOS_MESSAGE_BUFFER_H ) */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/mpu_prototypes.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/mpu_prototypes.h new file mode 100644 index 0000000..cb743be --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/mpu_prototypes.h @@ -0,0 +1,260 @@ +/* + * FreeRTOS Kernel V10.4.6 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* + * When the MPU is used the standard (non MPU) API functions are mapped to + * equivalents that start "MPU_", the prototypes for which are defined in this + * header files. This will cause the application code to call the MPU_ version + * which wraps the non-MPU version with privilege promoting then demoting code, + * so the kernel code always runs will full privileges. + */ + + +#ifndef MPU_PROTOTYPES_H +#define MPU_PROTOTYPES_H + +/* MPU versions of tasks.h API functions. */ +BaseType_t MPU_xTaskCreate( TaskFunction_t pxTaskCode, + const char * const pcName, + const uint16_t usStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask ) FREERTOS_SYSTEM_CALL; +TaskHandle_t MPU_xTaskCreateStatic( TaskFunction_t pxTaskCode, + const char * const pcName, + const uint32_t ulStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + StackType_t * const puxStackBuffer, + StaticTask_t * const pxTaskBuffer ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskDelete( TaskHandle_t xTaskToDelete ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskDelay( const TickType_t xTicksToDelay ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskDelayUntil( TickType_t * const pxPreviousWakeTime, + const TickType_t xTimeIncrement ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskAbortDelay( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxTaskPriorityGet( const TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; +eTaskState MPU_eTaskGetState( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskGetInfo( TaskHandle_t xTask, + TaskStatus_t * pxTaskStatus, + BaseType_t xGetFreeStackSpace, + eTaskState eState ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskPrioritySet( TaskHandle_t xTask, + UBaseType_t uxNewPriority ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskSuspend( TaskHandle_t xTaskToSuspend ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskResume( TaskHandle_t xTaskToResume ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskStartScheduler( void ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskSuspendAll( void ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskResumeAll( void ) FREERTOS_SYSTEM_CALL; +TickType_t MPU_xTaskGetTickCount( void ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxTaskGetNumberOfTasks( void ) FREERTOS_SYSTEM_CALL; +char * MPU_pcTaskGetName( TaskHandle_t xTaskToQuery ) FREERTOS_SYSTEM_CALL; +TaskHandle_t MPU_xTaskGetHandle( const char * pcNameToQuery ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxTaskGetStackHighWaterMark( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; +configSTACK_DEPTH_TYPE MPU_uxTaskGetStackHighWaterMark2( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskSetApplicationTaskTag( TaskHandle_t xTask, + TaskHookFunction_t pxHookFunction ) FREERTOS_SYSTEM_CALL; +TaskHookFunction_t MPU_xTaskGetApplicationTaskTag( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, + BaseType_t xIndex, + void * pvValue ) FREERTOS_SYSTEM_CALL; +void * MPU_pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, + BaseType_t xIndex ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskCallApplicationTaskHook( TaskHandle_t xTask, + void * pvParameter ) FREERTOS_SYSTEM_CALL; +TaskHandle_t MPU_xTaskGetIdleTaskHandle( void ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, + const UBaseType_t uxArraySize, + configRUN_TIME_COUNTER_TYPE * const pulTotalRunTime ) FREERTOS_SYSTEM_CALL; +configRUN_TIME_COUNTER_TYPE MPU_ulTaskGetIdleRunTimeCounter( void ) FREERTOS_SYSTEM_CALL; +configRUN_TIME_COUNTER_TYPE MPU_ulTaskGetIdleRunTimePercent( void ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskList( char * pcWriteBuffer ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskGetRunTimeStats( char * pcWriteBuffer ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskGenericNotify( TaskHandle_t xTaskToNotify, + UBaseType_t uxIndexToNotify, + uint32_t ulValue, + eNotifyAction eAction, + uint32_t * pulPreviousNotificationValue ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskGenericNotifyWait( UBaseType_t uxIndexToWaitOn, + uint32_t ulBitsToClearOnEntry, + uint32_t ulBitsToClearOnExit, + uint32_t * pulNotificationValue, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +uint32_t MPU_ulTaskGenericNotifyTake( UBaseType_t uxIndexToWaitOn, + BaseType_t xClearCountOnExit, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskGenericNotifyStateClear( TaskHandle_t xTask, + UBaseType_t uxIndexToClear ) FREERTOS_SYSTEM_CALL; +uint32_t MPU_ulTaskGenericNotifyValueClear( TaskHandle_t xTask, + UBaseType_t uxIndexToClear, + uint32_t ulBitsToClear ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskIncrementTick( void ) FREERTOS_SYSTEM_CALL; +TaskHandle_t MPU_xTaskGetCurrentTaskHandle( void ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, + TickType_t * const pxTicksToWait ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskMissedYield( void ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskGetSchedulerState( void ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskCatchUpTicks( TickType_t xTicksToCatchUp ) FREERTOS_SYSTEM_CALL; + +/* MPU versions of queue.h API functions. */ +BaseType_t MPU_xQueueGenericSend( QueueHandle_t xQueue, + const void * const pvItemToQueue, + TickType_t xTicksToWait, + const BaseType_t xCopyPosition ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueueReceive( QueueHandle_t xQueue, + void * const pvBuffer, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueuePeek( QueueHandle_t xQueue, + void * const pvBuffer, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueueSemaphoreTake( QueueHandle_t xQueue, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxQueueMessagesWaiting( const QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxQueueSpacesAvailable( const QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; +void MPU_vQueueDelete( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; +QueueHandle_t MPU_xQueueCreateMutex( const uint8_t ucQueueType ) FREERTOS_SYSTEM_CALL; +QueueHandle_t MPU_xQueueCreateMutexStatic( const uint8_t ucQueueType, + StaticQueue_t * pxStaticQueue ) FREERTOS_SYSTEM_CALL; +QueueHandle_t MPU_xQueueCreateCountingSemaphore( const UBaseType_t uxMaxCount, + const UBaseType_t uxInitialCount ) FREERTOS_SYSTEM_CALL; +QueueHandle_t MPU_xQueueCreateCountingSemaphoreStatic( const UBaseType_t uxMaxCount, + const UBaseType_t uxInitialCount, + StaticQueue_t * pxStaticQueue ) FREERTOS_SYSTEM_CALL; +TaskHandle_t MPU_xQueueGetMutexHolder( QueueHandle_t xSemaphore ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueueTakeMutexRecursive( QueueHandle_t xMutex, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueueGiveMutexRecursive( QueueHandle_t pxMutex ) FREERTOS_SYSTEM_CALL; +void MPU_vQueueAddToRegistry( QueueHandle_t xQueue, + const char * pcName ) FREERTOS_SYSTEM_CALL; +void MPU_vQueueUnregisterQueue( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; +const char * MPU_pcQueueGetName( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; +QueueHandle_t MPU_xQueueGenericCreate( const UBaseType_t uxQueueLength, + const UBaseType_t uxItemSize, + const uint8_t ucQueueType ) FREERTOS_SYSTEM_CALL; +QueueHandle_t MPU_xQueueGenericCreateStatic( const UBaseType_t uxQueueLength, + const UBaseType_t uxItemSize, + uint8_t * pucQueueStorage, + StaticQueue_t * pxStaticQueue, + const uint8_t ucQueueType ) FREERTOS_SYSTEM_CALL; +QueueSetHandle_t MPU_xQueueCreateSet( const UBaseType_t uxEventQueueLength ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, + QueueSetHandle_t xQueueSet ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, + QueueSetHandle_t xQueueSet ) FREERTOS_SYSTEM_CALL; +QueueSetMemberHandle_t MPU_xQueueSelectFromSet( QueueSetHandle_t xQueueSet, + const TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueueGenericReset( QueueHandle_t xQueue, + BaseType_t xNewQueue ) FREERTOS_SYSTEM_CALL; +void MPU_vQueueSetQueueNumber( QueueHandle_t xQueue, + UBaseType_t uxQueueNumber ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxQueueGetQueueNumber( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; +uint8_t MPU_ucQueueGetQueueType( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; + +/* MPU versions of timers.h API functions. */ +TimerHandle_t MPU_xTimerCreate( const char * const pcTimerName, + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction ) FREERTOS_SYSTEM_CALL; +TimerHandle_t MPU_xTimerCreateStatic( const char * const pcTimerName, + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction, + StaticTimer_t * pxTimerBuffer ) FREERTOS_SYSTEM_CALL; +void * MPU_pvTimerGetTimerID( const TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; +void MPU_vTimerSetTimerID( TimerHandle_t xTimer, + void * pvNewID ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTimerIsTimerActive( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; +TaskHandle_t MPU_xTimerGetTimerDaemonTaskHandle( void ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, + void * pvParameter1, + uint32_t ulParameter2, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +const char * MPU_pcTimerGetName( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; +void MPU_vTimerSetReloadMode( TimerHandle_t xTimer, + const UBaseType_t uxAutoReload ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxTimerGetReloadMode( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; +TickType_t MPU_xTimerGetPeriod( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; +TickType_t MPU_xTimerGetExpiryTime( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTimerCreateTimerTask( void ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTimerGenericCommand( TimerHandle_t xTimer, + const BaseType_t xCommandID, + const TickType_t xOptionalValue, + BaseType_t * const pxHigherPriorityTaskWoken, + const TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; + +/* MPU versions of event_group.h API functions. */ +EventGroupHandle_t MPU_xEventGroupCreate( void ) FREERTOS_SYSTEM_CALL; +EventGroupHandle_t MPU_xEventGroupCreateStatic( StaticEventGroup_t * pxEventGroupBuffer ) FREERTOS_SYSTEM_CALL; +EventBits_t MPU_xEventGroupWaitBits( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToWaitFor, + const BaseType_t xClearOnExit, + const BaseType_t xWaitForAllBits, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +EventBits_t MPU_xEventGroupClearBits( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToClear ) FREERTOS_SYSTEM_CALL; +EventBits_t MPU_xEventGroupSetBits( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToSet ) FREERTOS_SYSTEM_CALL; +EventBits_t MPU_xEventGroupSync( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToSet, + const EventBits_t uxBitsToWaitFor, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +void MPU_vEventGroupDelete( EventGroupHandle_t xEventGroup ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxEventGroupGetNumber( void * xEventGroup ) FREERTOS_SYSTEM_CALL; + +/* MPU versions of message/stream_buffer.h API functions. */ +size_t MPU_xStreamBufferSend( StreamBufferHandle_t xStreamBuffer, + const void * pvTxData, + size_t xDataLengthBytes, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +size_t MPU_xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer, + void * pvRxData, + size_t xBufferLengthBytes, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +size_t MPU_xStreamBufferNextMessageLengthBytes( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; +void MPU_vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xStreamBufferReset( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; +size_t MPU_xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; +size_t MPU_xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, + size_t xTriggerLevel ) FREERTOS_SYSTEM_CALL; +StreamBufferHandle_t MPU_xStreamBufferGenericCreate( size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + BaseType_t xIsMessageBuffer ) FREERTOS_SYSTEM_CALL; +StreamBufferHandle_t MPU_xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + BaseType_t xIsMessageBuffer, + uint8_t * const pucStreamBufferStorageArea, + StaticStreamBuffer_t * const pxStaticStreamBuffer ) FREERTOS_SYSTEM_CALL; + + + +#endif /* MPU_PROTOTYPES_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/mpu_wrappers.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/mpu_wrappers.h new file mode 100644 index 0000000..9b6cd7c --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/mpu_wrappers.h @@ -0,0 +1,217 @@ +/* + * FreeRTOS Kernel V10.4.6 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#ifndef MPU_WRAPPERS_H +#define MPU_WRAPPERS_H + +/* This file redefines API functions to be called through a wrapper macro, but + * only for ports that are using the MPU. */ +#if ( portUSING_MPU_WRAPPERS == 1 ) + +/* MPU_WRAPPERS_INCLUDED_FROM_API_FILE will be defined when this file is + * included from queue.c or task.c to prevent it from having an effect within + * those files. */ + #ifndef MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +/* + * Map standard (non MPU) API functions to equivalents that start + * "MPU_". This will cause the application code to call the MPU_ + * version, which wraps the non-MPU version with privilege promoting + * then demoting code, so the kernel code always runs will full + * privileges. + */ + +/* Map standard tasks.h API functions to the MPU equivalents. */ + #define xTaskCreate MPU_xTaskCreate + #define xTaskCreateStatic MPU_xTaskCreateStatic + #define vTaskDelete MPU_vTaskDelete + #define vTaskDelay MPU_vTaskDelay + #define xTaskDelayUntil MPU_xTaskDelayUntil + #define xTaskAbortDelay MPU_xTaskAbortDelay + #define uxTaskPriorityGet MPU_uxTaskPriorityGet + #define eTaskGetState MPU_eTaskGetState + #define vTaskGetInfo MPU_vTaskGetInfo + #define vTaskPrioritySet MPU_vTaskPrioritySet + #define vTaskSuspend MPU_vTaskSuspend + #define vTaskResume MPU_vTaskResume + #define vTaskSuspendAll MPU_vTaskSuspendAll + #define xTaskResumeAll MPU_xTaskResumeAll + #define xTaskGetTickCount MPU_xTaskGetTickCount + #define uxTaskGetNumberOfTasks MPU_uxTaskGetNumberOfTasks + #define pcTaskGetName MPU_pcTaskGetName + #define xTaskGetHandle MPU_xTaskGetHandle + #define uxTaskGetStackHighWaterMark MPU_uxTaskGetStackHighWaterMark + #define uxTaskGetStackHighWaterMark2 MPU_uxTaskGetStackHighWaterMark2 + #define vTaskSetApplicationTaskTag MPU_vTaskSetApplicationTaskTag + #define xTaskGetApplicationTaskTag MPU_xTaskGetApplicationTaskTag + #define vTaskSetThreadLocalStoragePointer MPU_vTaskSetThreadLocalStoragePointer + #define pvTaskGetThreadLocalStoragePointer MPU_pvTaskGetThreadLocalStoragePointer + #define xTaskCallApplicationTaskHook MPU_xTaskCallApplicationTaskHook + #define xTaskGetIdleTaskHandle MPU_xTaskGetIdleTaskHandle + #define uxTaskGetSystemState MPU_uxTaskGetSystemState + #define vTaskList MPU_vTaskList + #define vTaskGetRunTimeStats MPU_vTaskGetRunTimeStats + #define ulTaskGetIdleRunTimeCounter MPU_ulTaskGetIdleRunTimeCounter + #define ulTaskGetIdleRunTimePercent MPU_ulTaskGetIdleRunTimePercent + #define xTaskGenericNotify MPU_xTaskGenericNotify + #define xTaskGenericNotifyWait MPU_xTaskGenericNotifyWait + #define ulTaskGenericNotifyTake MPU_ulTaskGenericNotifyTake + #define xTaskGenericNotifyStateClear MPU_xTaskGenericNotifyStateClear + #define ulTaskGenericNotifyValueClear MPU_ulTaskGenericNotifyValueClear + #define xTaskCatchUpTicks MPU_xTaskCatchUpTicks + + #define xTaskGetCurrentTaskHandle MPU_xTaskGetCurrentTaskHandle + #define vTaskSetTimeOutState MPU_vTaskSetTimeOutState + #define xTaskCheckForTimeOut MPU_xTaskCheckForTimeOut + #define xTaskGetSchedulerState MPU_xTaskGetSchedulerState + +/* Map standard queue.h API functions to the MPU equivalents. */ + #define xQueueGenericSend MPU_xQueueGenericSend + #define xQueueReceive MPU_xQueueReceive + #define xQueuePeek MPU_xQueuePeek + #define xQueueSemaphoreTake MPU_xQueueSemaphoreTake + #define uxQueueMessagesWaiting MPU_uxQueueMessagesWaiting + #define uxQueueSpacesAvailable MPU_uxQueueSpacesAvailable + #define vQueueDelete MPU_vQueueDelete + #define xQueueCreateMutex MPU_xQueueCreateMutex + #define xQueueCreateMutexStatic MPU_xQueueCreateMutexStatic + #define xQueueCreateCountingSemaphore MPU_xQueueCreateCountingSemaphore + #define xQueueCreateCountingSemaphoreStatic MPU_xQueueCreateCountingSemaphoreStatic + #define xQueueGetMutexHolder MPU_xQueueGetMutexHolder + #define xQueueTakeMutexRecursive MPU_xQueueTakeMutexRecursive + #define xQueueGiveMutexRecursive MPU_xQueueGiveMutexRecursive + #define xQueueGenericCreate MPU_xQueueGenericCreate + #define xQueueGenericCreateStatic MPU_xQueueGenericCreateStatic + #define xQueueCreateSet MPU_xQueueCreateSet + #define xQueueAddToSet MPU_xQueueAddToSet + #define xQueueRemoveFromSet MPU_xQueueRemoveFromSet + #define xQueueSelectFromSet MPU_xQueueSelectFromSet + #define xQueueGenericReset MPU_xQueueGenericReset + + #if ( configQUEUE_REGISTRY_SIZE > 0 ) + #define vQueueAddToRegistry MPU_vQueueAddToRegistry + #define vQueueUnregisterQueue MPU_vQueueUnregisterQueue + #define pcQueueGetName MPU_pcQueueGetName + #endif + +/* Map standard timer.h API functions to the MPU equivalents. */ + #define xTimerCreate MPU_xTimerCreate + #define xTimerCreateStatic MPU_xTimerCreateStatic + #define pvTimerGetTimerID MPU_pvTimerGetTimerID + #define vTimerSetTimerID MPU_vTimerSetTimerID + #define xTimerIsTimerActive MPU_xTimerIsTimerActive + #define xTimerGetTimerDaemonTaskHandle MPU_xTimerGetTimerDaemonTaskHandle + #define xTimerPendFunctionCall MPU_xTimerPendFunctionCall + #define pcTimerGetName MPU_pcTimerGetName + #define vTimerSetReloadMode MPU_vTimerSetReloadMode + #define uxTimerGetReloadMode MPU_uxTimerGetReloadMode + #define xTimerGetPeriod MPU_xTimerGetPeriod + #define xTimerGetExpiryTime MPU_xTimerGetExpiryTime + #define xTimerGenericCommand MPU_xTimerGenericCommand + +/* Map standard event_group.h API functions to the MPU equivalents. */ + #define xEventGroupCreate MPU_xEventGroupCreate + #define xEventGroupCreateStatic MPU_xEventGroupCreateStatic + #define xEventGroupWaitBits MPU_xEventGroupWaitBits + #define xEventGroupClearBits MPU_xEventGroupClearBits + #define xEventGroupSetBits MPU_xEventGroupSetBits + #define xEventGroupSync MPU_xEventGroupSync + #define vEventGroupDelete MPU_vEventGroupDelete + +/* Map standard message/stream_buffer.h API functions to the MPU + * equivalents. */ + #define xStreamBufferSend MPU_xStreamBufferSend + #define xStreamBufferReceive MPU_xStreamBufferReceive + #define xStreamBufferNextMessageLengthBytes MPU_xStreamBufferNextMessageLengthBytes + #define vStreamBufferDelete MPU_vStreamBufferDelete + #define xStreamBufferIsFull MPU_xStreamBufferIsFull + #define xStreamBufferIsEmpty MPU_xStreamBufferIsEmpty + #define xStreamBufferReset MPU_xStreamBufferReset + #define xStreamBufferSpacesAvailable MPU_xStreamBufferSpacesAvailable + #define xStreamBufferBytesAvailable MPU_xStreamBufferBytesAvailable + #define xStreamBufferSetTriggerLevel MPU_xStreamBufferSetTriggerLevel + #define xStreamBufferGenericCreate MPU_xStreamBufferGenericCreate + #define xStreamBufferGenericCreateStatic MPU_xStreamBufferGenericCreateStatic + + +/* Remove the privileged function macro, but keep the PRIVILEGED_DATA + * macro so applications can place data in privileged access sections + * (useful when using statically allocated objects). */ + #define PRIVILEGED_FUNCTION + #define PRIVILEGED_DATA __attribute__( ( section( "privileged_data" ) ) ) + #define FREERTOS_SYSTEM_CALL + + #else /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE */ + + /* Ensure API functions go in the privileged execution section. */ + #define PRIVILEGED_FUNCTION __attribute__( ( section( "privileged_functions" ) ) ) + #define PRIVILEGED_DATA __attribute__( ( section( "privileged_data" ) ) ) + #define FREERTOS_SYSTEM_CALL __attribute__( ( section( "freertos_system_calls" ) ) ) + + /** + * @brief Calls the port specific code to raise the privilege. + * + * Sets xRunningPrivileged to pdFALSE if privilege was raised, else sets + * it to pdTRUE. + */ + #define xPortRaisePrivilege( xRunningPrivileged ) \ + { \ + /* Check whether the processor is already privileged. */ \ + xRunningPrivileged = portIS_PRIVILEGED(); \ + \ + /* If the processor is not already privileged, raise privilege. */ \ + if( xRunningPrivileged == pdFALSE ) \ + { \ + portRAISE_PRIVILEGE(); \ + } \ + } + + /** + * @brief If xRunningPrivileged is not pdTRUE, calls the port specific + * code to reset the privilege, otherwise does nothing. + */ + #define vPortResetPrivilege( xRunningPrivileged ) \ + { \ + if( xRunningPrivileged == pdFALSE ) \ + { \ + portRESET_PRIVILEGE(); \ + } \ + } + + #endif /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE */ + +#else /* portUSING_MPU_WRAPPERS */ + + #define PRIVILEGED_FUNCTION + #define PRIVILEGED_DATA + #define FREERTOS_SYSTEM_CALL + +#endif /* portUSING_MPU_WRAPPERS */ + + +#endif /* MPU_WRAPPERS_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/portable.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/portable.h new file mode 100644 index 0000000..0ec6416 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/portable.h @@ -0,0 +1,223 @@ +/* + * FreeRTOS Kernel V10.4.6 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/*----------------------------------------------------------- +* Portable layer API. Each function must be defined for each port. +*----------------------------------------------------------*/ + +#ifndef PORTABLE_H +#define PORTABLE_H + +/* Each FreeRTOS port has a unique portmacro.h header file. Originally a + * pre-processor definition was used to ensure the pre-processor found the correct + * portmacro.h file for the port being used. That scheme was deprecated in favour + * of setting the compiler's include path such that it found the correct + * portmacro.h file - removing the need for the constant and allowing the + * portmacro.h file to be located anywhere in relation to the port being used. + * Purely for reasons of backward compatibility the old method is still valid, but + * to make it clear that new projects should not use it, support for the port + * specific constants has been moved into the deprecated_definitions.h header + * file. */ +#include "deprecated_definitions.h" + +/* If portENTER_CRITICAL is not defined then including deprecated_definitions.h + * did not result in a portmacro.h header file being included - and it should be + * included here. In this case the path to the correct portmacro.h header file + * must be set in the compiler's include path. */ +#ifndef portENTER_CRITICAL + #include "portmacro.h" +#endif + +#if portBYTE_ALIGNMENT == 32 + #define portBYTE_ALIGNMENT_MASK ( 0x001f ) +#elif portBYTE_ALIGNMENT == 16 + #define portBYTE_ALIGNMENT_MASK ( 0x000f ) +#elif portBYTE_ALIGNMENT == 8 + #define portBYTE_ALIGNMENT_MASK ( 0x0007 ) +#elif portBYTE_ALIGNMENT == 4 + #define portBYTE_ALIGNMENT_MASK ( 0x0003 ) +#elif portBYTE_ALIGNMENT == 2 + #define portBYTE_ALIGNMENT_MASK ( 0x0001 ) +#elif portBYTE_ALIGNMENT == 1 + #define portBYTE_ALIGNMENT_MASK ( 0x0000 ) +#else /* if portBYTE_ALIGNMENT == 32 */ + #error "Invalid portBYTE_ALIGNMENT definition" +#endif /* if portBYTE_ALIGNMENT == 32 */ + +#ifndef portUSING_MPU_WRAPPERS + #define portUSING_MPU_WRAPPERS 0 +#endif + +#ifndef portNUM_CONFIGURABLE_REGIONS + #define portNUM_CONFIGURABLE_REGIONS 1 +#endif + +#ifndef portHAS_STACK_OVERFLOW_CHECKING + #define portHAS_STACK_OVERFLOW_CHECKING 0 +#endif + +#ifndef portARCH_NAME + #define portARCH_NAME NULL +#endif + +#ifndef configSTACK_ALLOCATION_FROM_SEPARATE_HEAP + /* Defaults to 0 for backward compatibility. */ + #define configSTACK_ALLOCATION_FROM_SEPARATE_HEAP 0 +#endif + +/* *INDENT-OFF* */ +#ifdef __cplusplus + extern "C" { +#endif +/* *INDENT-ON* */ + +#include "mpu_wrappers.h" + +/* + * Setup the stack of a new task so it is ready to be placed under the + * scheduler control. The registers have to be placed on the stack in + * the order that the port expects to find them. + * + */ +#if ( portUSING_MPU_WRAPPERS == 1 ) + #if ( portHAS_STACK_OVERFLOW_CHECKING == 1 ) + StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack, + StackType_t * pxEndOfStack, + TaskFunction_t pxCode, + void * pvParameters, + BaseType_t xRunPrivileged ) PRIVILEGED_FUNCTION; + #else + StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack, + TaskFunction_t pxCode, + void * pvParameters, + BaseType_t xRunPrivileged ) PRIVILEGED_FUNCTION; + #endif +#else /* if ( portUSING_MPU_WRAPPERS == 1 ) */ + #if ( portHAS_STACK_OVERFLOW_CHECKING == 1 ) + StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack, + StackType_t * pxEndOfStack, + TaskFunction_t pxCode, + void * pvParameters ) PRIVILEGED_FUNCTION; + #else + StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack, + TaskFunction_t pxCode, + void * pvParameters ) PRIVILEGED_FUNCTION; + #endif +#endif /* if ( portUSING_MPU_WRAPPERS == 1 ) */ + +/* Used by heap_5.c to define the start address and size of each memory region + * that together comprise the total FreeRTOS heap space. */ +typedef struct HeapRegion +{ + uint8_t * pucStartAddress; + size_t xSizeInBytes; +} HeapRegion_t; + +/* Used to pass information about the heap out of vPortGetHeapStats(). */ +typedef struct xHeapStats +{ + size_t xAvailableHeapSpaceInBytes; /* The total heap size currently available - this is the sum of all the free blocks, not the largest block that can be allocated. */ + size_t xSizeOfLargestFreeBlockInBytes; /* The maximum size, in bytes, of all the free blocks within the heap at the time vPortGetHeapStats() is called. */ + size_t xSizeOfSmallestFreeBlockInBytes; /* The minimum size, in bytes, of all the free blocks within the heap at the time vPortGetHeapStats() is called. */ + size_t xNumberOfFreeBlocks; /* The number of free memory blocks within the heap at the time vPortGetHeapStats() is called. */ + size_t xMinimumEverFreeBytesRemaining; /* The minimum amount of total free memory (sum of all free blocks) there has been in the heap since the system booted. */ + size_t xNumberOfSuccessfulAllocations; /* The number of calls to pvPortMalloc() that have returned a valid memory block. */ + size_t xNumberOfSuccessfulFrees; /* The number of calls to vPortFree() that has successfully freed a block of memory. */ +} HeapStats_t; + +/* + * Used to define multiple heap regions for use by heap_5.c. This function + * must be called before any calls to pvPortMalloc() - not creating a task, + * queue, semaphore, mutex, software timer, event group, etc. will result in + * pvPortMalloc being called. + * + * pxHeapRegions passes in an array of HeapRegion_t structures - each of which + * defines a region of memory that can be used as the heap. The array is + * terminated by a HeapRegions_t structure that has a size of 0. The region + * with the lowest start address must appear first in the array. + */ +void vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions ) PRIVILEGED_FUNCTION; + +/* + * Returns a HeapStats_t structure filled with information about the current + * heap state. + */ +void vPortGetHeapStats( HeapStats_t * pxHeapStats ); + +/* + * Map to the memory management routines required for the port. + */ +void * pvPortMalloc( size_t xSize ) PRIVILEGED_FUNCTION; +void vPortFree( void * pv ) PRIVILEGED_FUNCTION; +void vPortInitialiseBlocks( void ) PRIVILEGED_FUNCTION; +size_t xPortGetFreeHeapSize( void ) PRIVILEGED_FUNCTION; +size_t xPortGetMinimumEverFreeHeapSize( void ) PRIVILEGED_FUNCTION; + +#if ( configSTACK_ALLOCATION_FROM_SEPARATE_HEAP == 1 ) + void * pvPortMallocStack( size_t xSize ) PRIVILEGED_FUNCTION; + void vPortFreeStack( void * pv ) PRIVILEGED_FUNCTION; +#else + #define pvPortMallocStack pvPortMalloc + #define vPortFreeStack vPortFree +#endif + +/* + * Setup the hardware ready for the scheduler to take control. This generally + * sets up a tick interrupt and sets timers for the correct tick frequency. + */ +BaseType_t xPortStartScheduler( void ) PRIVILEGED_FUNCTION; + +/* + * Undo any hardware/ISR setup that was performed by xPortStartScheduler() so + * the hardware is left in its original condition after the scheduler stops + * executing. + */ +void vPortEndScheduler( void ) PRIVILEGED_FUNCTION; + +/* + * The structures and methods of manipulating the MPU are contained within the + * port layer. + * + * Fills the xMPUSettings structure with the memory region information + * contained in xRegions. + */ +#if ( portUSING_MPU_WRAPPERS == 1 ) + struct xMEMORY_REGION; + void vPortStoreTaskMPUSettings( xMPU_SETTINGS * xMPUSettings, + const struct xMEMORY_REGION * const xRegions, + StackType_t * pxBottomOfStack, + uint32_t ulStackDepth ) PRIVILEGED_FUNCTION; +#endif + +/* *INDENT-OFF* */ +#ifdef __cplusplus + } +#endif +/* *INDENT-ON* */ + +#endif /* PORTABLE_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/projdefs.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/projdefs.h new file mode 100644 index 0000000..e623bf7 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/projdefs.h @@ -0,0 +1,122 @@ +/* + * FreeRTOS Kernel V10.4.6 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#ifndef PROJDEFS_H +#define PROJDEFS_H + +/* + * Defines the prototype to which task functions must conform. Defined in this + * file to ensure the type is known before portable.h is included. + */ +typedef void (* TaskFunction_t)( void * ); + +/* Converts a time in milliseconds to a time in ticks. This macro can be + * overridden by a macro of the same name defined in FreeRTOSConfig.h in case the + * definition here is not suitable for your application. */ +#ifndef pdMS_TO_TICKS + #define pdMS_TO_TICKS( xTimeInMs ) ( ( TickType_t ) ( ( ( TickType_t ) ( xTimeInMs ) * ( TickType_t ) configTICK_RATE_HZ ) / ( TickType_t ) 1000U ) ) +#endif + +#define pdFALSE ( ( BaseType_t ) 0 ) +#define pdTRUE ( ( BaseType_t ) 1 ) + +#define pdPASS ( pdTRUE ) +#define pdFAIL ( pdFALSE ) +#define errQUEUE_EMPTY ( ( BaseType_t ) 0 ) +#define errQUEUE_FULL ( ( BaseType_t ) 0 ) + +/* FreeRTOS error definitions. */ +#define errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY ( -1 ) +#define errQUEUE_BLOCKED ( -4 ) +#define errQUEUE_YIELD ( -5 ) + +/* Macros used for basic data corruption checks. */ +#ifndef configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES + #define configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES 0 +#endif + +#if ( configUSE_16_BIT_TICKS == 1 ) + #define pdINTEGRITY_CHECK_VALUE 0x5a5a +#else + #define pdINTEGRITY_CHECK_VALUE 0x5a5a5a5aUL +#endif + +/* The following errno values are used by FreeRTOS+ components, not FreeRTOS + * itself. */ +#define pdFREERTOS_ERRNO_NONE 0 /* No errors */ +#define pdFREERTOS_ERRNO_ENOENT 2 /* No such file or directory */ +#define pdFREERTOS_ERRNO_EINTR 4 /* Interrupted system call */ +#define pdFREERTOS_ERRNO_EIO 5 /* I/O error */ +#define pdFREERTOS_ERRNO_ENXIO 6 /* No such device or address */ +#define pdFREERTOS_ERRNO_EBADF 9 /* Bad file number */ +#define pdFREERTOS_ERRNO_EAGAIN 11 /* No more processes */ +#define pdFREERTOS_ERRNO_EWOULDBLOCK 11 /* Operation would block */ +#define pdFREERTOS_ERRNO_ENOMEM 12 /* Not enough memory */ +#define pdFREERTOS_ERRNO_EACCES 13 /* Permission denied */ +#define pdFREERTOS_ERRNO_EFAULT 14 /* Bad address */ +#define pdFREERTOS_ERRNO_EBUSY 16 /* Mount device busy */ +#define pdFREERTOS_ERRNO_EEXIST 17 /* File exists */ +#define pdFREERTOS_ERRNO_EXDEV 18 /* Cross-device link */ +#define pdFREERTOS_ERRNO_ENODEV 19 /* No such device */ +#define pdFREERTOS_ERRNO_ENOTDIR 20 /* Not a directory */ +#define pdFREERTOS_ERRNO_EISDIR 21 /* Is a directory */ +#define pdFREERTOS_ERRNO_EINVAL 22 /* Invalid argument */ +#define pdFREERTOS_ERRNO_ENOSPC 28 /* No space left on device */ +#define pdFREERTOS_ERRNO_ESPIPE 29 /* Illegal seek */ +#define pdFREERTOS_ERRNO_EROFS 30 /* Read only file system */ +#define pdFREERTOS_ERRNO_EUNATCH 42 /* Protocol driver not attached */ +#define pdFREERTOS_ERRNO_EBADE 50 /* Invalid exchange */ +#define pdFREERTOS_ERRNO_EFTYPE 79 /* Inappropriate file type or format */ +#define pdFREERTOS_ERRNO_ENMFILE 89 /* No more files */ +#define pdFREERTOS_ERRNO_ENOTEMPTY 90 /* Directory not empty */ +#define pdFREERTOS_ERRNO_ENAMETOOLONG 91 /* File or path name too long */ +#define pdFREERTOS_ERRNO_EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ +#define pdFREERTOS_ERRNO_ENOBUFS 105 /* No buffer space available */ +#define pdFREERTOS_ERRNO_ENOPROTOOPT 109 /* Protocol not available */ +#define pdFREERTOS_ERRNO_EADDRINUSE 112 /* Address already in use */ +#define pdFREERTOS_ERRNO_ETIMEDOUT 116 /* Connection timed out */ +#define pdFREERTOS_ERRNO_EINPROGRESS 119 /* Connection already in progress */ +#define pdFREERTOS_ERRNO_EALREADY 120 /* Socket already connected */ +#define pdFREERTOS_ERRNO_EADDRNOTAVAIL 125 /* Address not available */ +#define pdFREERTOS_ERRNO_EISCONN 127 /* Socket is already connected */ +#define pdFREERTOS_ERRNO_ENOTCONN 128 /* Socket is not connected */ +#define pdFREERTOS_ERRNO_ENOMEDIUM 135 /* No medium inserted */ +#define pdFREERTOS_ERRNO_EILSEQ 138 /* An invalid UTF-16 sequence was encountered. */ +#define pdFREERTOS_ERRNO_ECANCELED 140 /* Operation canceled. */ + +/* The following endian values are used by FreeRTOS+ components, not FreeRTOS + * itself. */ +#define pdFREERTOS_LITTLE_ENDIAN 0 +#define pdFREERTOS_BIG_ENDIAN 1 + +/* Re-defining endian values for generic naming. */ +#define pdLITTLE_ENDIAN pdFREERTOS_LITTLE_ENDIAN +#define pdBIG_ENDIAN pdFREERTOS_BIG_ENDIAN + + +#endif /* PROJDEFS_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/queue.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/queue.h new file mode 100644 index 0000000..6a92b6b --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/queue.h @@ -0,0 +1,1722 @@ +/* + * FreeRTOS Kernel V10.4.6 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + + +#ifndef QUEUE_H +#define QUEUE_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h" must appear in source files before "include queue.h" +#endif + +/* *INDENT-OFF* */ +#ifdef __cplusplus + extern "C" { +#endif +/* *INDENT-ON* */ + +#include "task.h" + +/** + * Type by which queues are referenced. For example, a call to xQueueCreate() + * returns an QueueHandle_t variable that can then be used as a parameter to + * xQueueSend(), xQueueReceive(), etc. + */ +struct QueueDefinition; /* Using old naming convention so as not to break kernel aware debuggers. */ +typedef struct QueueDefinition * QueueHandle_t; + +/** + * Type by which queue sets are referenced. For example, a call to + * xQueueCreateSet() returns an xQueueSet variable that can then be used as a + * parameter to xQueueSelectFromSet(), xQueueAddToSet(), etc. + */ +typedef struct QueueDefinition * QueueSetHandle_t; + +/** + * Queue sets can contain both queues and semaphores, so the + * QueueSetMemberHandle_t is defined as a type to be used where a parameter or + * return value can be either an QueueHandle_t or an SemaphoreHandle_t. + */ +typedef struct QueueDefinition * QueueSetMemberHandle_t; + +/* For internal use only. */ +#define queueSEND_TO_BACK ( ( BaseType_t ) 0 ) +#define queueSEND_TO_FRONT ( ( BaseType_t ) 1 ) +#define queueOVERWRITE ( ( BaseType_t ) 2 ) + +/* For internal use only. These definitions *must* match those in queue.c. */ +#define queueQUEUE_TYPE_BASE ( ( uint8_t ) 0U ) +#define queueQUEUE_TYPE_SET ( ( uint8_t ) 0U ) +#define queueQUEUE_TYPE_MUTEX ( ( uint8_t ) 1U ) +#define queueQUEUE_TYPE_COUNTING_SEMAPHORE ( ( uint8_t ) 2U ) +#define queueQUEUE_TYPE_BINARY_SEMAPHORE ( ( uint8_t ) 3U ) +#define queueQUEUE_TYPE_RECURSIVE_MUTEX ( ( uint8_t ) 4U ) + +/** + * queue. h + * @code{c} + * QueueHandle_t xQueueCreate( + * UBaseType_t uxQueueLength, + * UBaseType_t uxItemSize + * ); + * @endcode + * + * Creates a new queue instance, and returns a handle by which the new queue + * can be referenced. + * + * Internally, within the FreeRTOS implementation, queues use two blocks of + * memory. The first block is used to hold the queue's data structures. The + * second block is used to hold items placed into the queue. If a queue is + * created using xQueueCreate() then both blocks of memory are automatically + * dynamically allocated inside the xQueueCreate() function. (see + * https://www.FreeRTOS.org/a00111.html). If a queue is created using + * xQueueCreateStatic() then the application writer must provide the memory that + * will get used by the queue. xQueueCreateStatic() therefore allows a queue to + * be created without using any dynamic memory allocation. + * + * https://www.FreeRTOS.org/Embedded-RTOS-Queues.html + * + * @param uxQueueLength The maximum number of items that the queue can contain. + * + * @param uxItemSize The number of bytes each item in the queue will require. + * Items are queued by copy, not by reference, so this is the number of bytes + * that will be copied for each posted item. Each item on the queue must be + * the same size. + * + * @return If the queue is successfully create then a handle to the newly + * created queue is returned. If the queue cannot be created then 0 is + * returned. + * + * Example usage: + * @code{c} + * struct AMessage + * { + * char ucMessageID; + * char ucData[ 20 ]; + * }; + * + * void vATask( void *pvParameters ) + * { + * QueueHandle_t xQueue1, xQueue2; + * + * // Create a queue capable of containing 10 uint32_t values. + * xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); + * if( xQueue1 == 0 ) + * { + * // Queue was not created and must not be used. + * } + * + * // Create a queue capable of containing 10 pointers to AMessage structures. + * // These should be passed by pointer as they contain a lot of data. + * xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); + * if( xQueue2 == 0 ) + * { + * // Queue was not created and must not be used. + * } + * + * // ... Rest of task code. + * } + * @endcode + * \defgroup xQueueCreate xQueueCreate + * \ingroup QueueManagement + */ +#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + #define xQueueCreate( uxQueueLength, uxItemSize ) xQueueGenericCreate( ( uxQueueLength ), ( uxItemSize ), ( queueQUEUE_TYPE_BASE ) ) +#endif + +/** + * queue. h + * @code{c} + * QueueHandle_t xQueueCreateStatic( + * UBaseType_t uxQueueLength, + * UBaseType_t uxItemSize, + * uint8_t *pucQueueStorage, + * StaticQueue_t *pxQueueBuffer + * ); + * @endcode + * + * Creates a new queue instance, and returns a handle by which the new queue + * can be referenced. + * + * Internally, within the FreeRTOS implementation, queues use two blocks of + * memory. The first block is used to hold the queue's data structures. The + * second block is used to hold items placed into the queue. If a queue is + * created using xQueueCreate() then both blocks of memory are automatically + * dynamically allocated inside the xQueueCreate() function. (see + * https://www.FreeRTOS.org/a00111.html). If a queue is created using + * xQueueCreateStatic() then the application writer must provide the memory that + * will get used by the queue. xQueueCreateStatic() therefore allows a queue to + * be created without using any dynamic memory allocation. + * + * https://www.FreeRTOS.org/Embedded-RTOS-Queues.html + * + * @param uxQueueLength The maximum number of items that the queue can contain. + * + * @param uxItemSize The number of bytes each item in the queue will require. + * Items are queued by copy, not by reference, so this is the number of bytes + * that will be copied for each posted item. Each item on the queue must be + * the same size. + * + * @param pucQueueStorage If uxItemSize is not zero then + * pucQueueStorage must point to a uint8_t array that is at least large + * enough to hold the maximum number of items that can be in the queue at any + * one time - which is ( uxQueueLength * uxItemsSize ) bytes. If uxItemSize is + * zero then pucQueueStorage can be NULL. + * + * @param pxQueueBuffer Must point to a variable of type StaticQueue_t, which + * will be used to hold the queue's data structure. + * + * @return If the queue is created then a handle to the created queue is + * returned. If pxQueueBuffer is NULL then NULL is returned. + * + * Example usage: + * @code{c} + * struct AMessage + * { + * char ucMessageID; + * char ucData[ 20 ]; + * }; + * + #define QUEUE_LENGTH 10 + #define ITEM_SIZE sizeof( uint32_t ) + * + * // xQueueBuffer will hold the queue structure. + * StaticQueue_t xQueueBuffer; + * + * // ucQueueStorage will hold the items posted to the queue. Must be at least + * // [(queue length) * ( queue item size)] bytes long. + * uint8_t ucQueueStorage[ QUEUE_LENGTH * ITEM_SIZE ]; + * + * void vATask( void *pvParameters ) + * { + * QueueHandle_t xQueue1; + * + * // Create a queue capable of containing 10 uint32_t values. + * xQueue1 = xQueueCreate( QUEUE_LENGTH, // The number of items the queue can hold. + * ITEM_SIZE // The size of each item in the queue + * &( ucQueueStorage[ 0 ] ), // The buffer that will hold the items in the queue. + * &xQueueBuffer ); // The buffer that will hold the queue structure. + * + * // The queue is guaranteed to be created successfully as no dynamic memory + * // allocation is used. Therefore xQueue1 is now a handle to a valid queue. + * + * // ... Rest of task code. + * } + * @endcode + * \defgroup xQueueCreateStatic xQueueCreateStatic + * \ingroup QueueManagement + */ +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + #define xQueueCreateStatic( uxQueueLength, uxItemSize, pucQueueStorage, pxQueueBuffer ) xQueueGenericCreateStatic( ( uxQueueLength ), ( uxItemSize ), ( pucQueueStorage ), ( pxQueueBuffer ), ( queueQUEUE_TYPE_BASE ) ) +#endif /* configSUPPORT_STATIC_ALLOCATION */ + +/** + * queue. h + * @code{c} + * BaseType_t xQueueSendToToFront( + * QueueHandle_t xQueue, + * const void *pvItemToQueue, + * TickType_t xTicksToWait + * ); + * @endcode + * + * Post an item to the front of a queue. The item is queued by copy, not by + * reference. This function must not be called from an interrupt service + * routine. See xQueueSendFromISR () for an alternative which may be used + * in an ISR. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param xTicksToWait The maximum amount of time the task should block + * waiting for space to become available on the queue, should it already + * be full. The call will return immediately if this is set to 0 and the + * queue is full. The time is defined in tick periods so the constant + * portTICK_PERIOD_MS should be used to convert to real time if this is required. + * + * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. + * + * Example usage: + * @code{c} + * struct AMessage + * { + * char ucMessageID; + * char ucData[ 20 ]; + * } xMessage; + * + * uint32_t ulVar = 10UL; + * + * void vATask( void *pvParameters ) + * { + * QueueHandle_t xQueue1, xQueue2; + * struct AMessage *pxMessage; + * + * // Create a queue capable of containing 10 uint32_t values. + * xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); + * + * // Create a queue capable of containing 10 pointers to AMessage structures. + * // These should be passed by pointer as they contain a lot of data. + * xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); + * + * // ... + * + * if( xQueue1 != 0 ) + * { + * // Send an uint32_t. Wait for 10 ticks for space to become + * // available if necessary. + * if( xQueueSendToFront( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS ) + * { + * // Failed to post the message, even after 10 ticks. + * } + * } + * + * if( xQueue2 != 0 ) + * { + * // Send a pointer to a struct AMessage object. Don't block if the + * // queue is already full. + * pxMessage = & xMessage; + * xQueueSendToFront( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 ); + * } + * + * // ... Rest of task code. + * } + * @endcode + * \defgroup xQueueSend xQueueSend + * \ingroup QueueManagement + */ +#define xQueueSendToFront( xQueue, pvItemToQueue, xTicksToWait ) \ + xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_FRONT ) + +/** + * queue. h + * @code{c} + * BaseType_t xQueueSendToBack( + * QueueHandle_t xQueue, + * const void *pvItemToQueue, + * TickType_t xTicksToWait + * ); + * @endcode + * + * This is a macro that calls xQueueGenericSend(). + * + * Post an item to the back of a queue. The item is queued by copy, not by + * reference. This function must not be called from an interrupt service + * routine. See xQueueSendFromISR () for an alternative which may be used + * in an ISR. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param xTicksToWait The maximum amount of time the task should block + * waiting for space to become available on the queue, should it already + * be full. The call will return immediately if this is set to 0 and the queue + * is full. The time is defined in tick periods so the constant + * portTICK_PERIOD_MS should be used to convert to real time if this is required. + * + * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. + * + * Example usage: + * @code{c} + * struct AMessage + * { + * char ucMessageID; + * char ucData[ 20 ]; + * } xMessage; + * + * uint32_t ulVar = 10UL; + * + * void vATask( void *pvParameters ) + * { + * QueueHandle_t xQueue1, xQueue2; + * struct AMessage *pxMessage; + * + * // Create a queue capable of containing 10 uint32_t values. + * xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); + * + * // Create a queue capable of containing 10 pointers to AMessage structures. + * // These should be passed by pointer as they contain a lot of data. + * xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); + * + * // ... + * + * if( xQueue1 != 0 ) + * { + * // Send an uint32_t. Wait for 10 ticks for space to become + * // available if necessary. + * if( xQueueSendToBack( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS ) + * { + * // Failed to post the message, even after 10 ticks. + * } + * } + * + * if( xQueue2 != 0 ) + * { + * // Send a pointer to a struct AMessage object. Don't block if the + * // queue is already full. + * pxMessage = & xMessage; + * xQueueSendToBack( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 ); + * } + * + * // ... Rest of task code. + * } + * @endcode + * \defgroup xQueueSend xQueueSend + * \ingroup QueueManagement + */ +#define xQueueSendToBack( xQueue, pvItemToQueue, xTicksToWait ) \ + xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_BACK ) + +/** + * queue. h + * @code{c} + * BaseType_t xQueueSend( + * QueueHandle_t xQueue, + * const void * pvItemToQueue, + * TickType_t xTicksToWait + * ); + * @endcode + * + * This is a macro that calls xQueueGenericSend(). It is included for + * backward compatibility with versions of FreeRTOS.org that did not + * include the xQueueSendToFront() and xQueueSendToBack() macros. It is + * equivalent to xQueueSendToBack(). + * + * Post an item on a queue. The item is queued by copy, not by reference. + * This function must not be called from an interrupt service routine. + * See xQueueSendFromISR () for an alternative which may be used in an ISR. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param xTicksToWait The maximum amount of time the task should block + * waiting for space to become available on the queue, should it already + * be full. The call will return immediately if this is set to 0 and the + * queue is full. The time is defined in tick periods so the constant + * portTICK_PERIOD_MS should be used to convert to real time if this is required. + * + * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. + * + * Example usage: + * @code{c} + * struct AMessage + * { + * char ucMessageID; + * char ucData[ 20 ]; + * } xMessage; + * + * uint32_t ulVar = 10UL; + * + * void vATask( void *pvParameters ) + * { + * QueueHandle_t xQueue1, xQueue2; + * struct AMessage *pxMessage; + * + * // Create a queue capable of containing 10 uint32_t values. + * xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); + * + * // Create a queue capable of containing 10 pointers to AMessage structures. + * // These should be passed by pointer as they contain a lot of data. + * xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); + * + * // ... + * + * if( xQueue1 != 0 ) + * { + * // Send an uint32_t. Wait for 10 ticks for space to become + * // available if necessary. + * if( xQueueSend( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS ) + * { + * // Failed to post the message, even after 10 ticks. + * } + * } + * + * if( xQueue2 != 0 ) + * { + * // Send a pointer to a struct AMessage object. Don't block if the + * // queue is already full. + * pxMessage = & xMessage; + * xQueueSend( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 ); + * } + * + * // ... Rest of task code. + * } + * @endcode + * \defgroup xQueueSend xQueueSend + * \ingroup QueueManagement + */ +#define xQueueSend( xQueue, pvItemToQueue, xTicksToWait ) \ + xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_BACK ) + +/** + * queue. h + * @code{c} + * BaseType_t xQueueOverwrite( + * QueueHandle_t xQueue, + * const void * pvItemToQueue + * ); + * @endcode + * + * Only for use with queues that have a length of one - so the queue is either + * empty or full. + * + * Post an item on a queue. If the queue is already full then overwrite the + * value held in the queue. The item is queued by copy, not by reference. + * + * This function must not be called from an interrupt service routine. + * See xQueueOverwriteFromISR () for an alternative which may be used in an ISR. + * + * @param xQueue The handle of the queue to which the data is being sent. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @return xQueueOverwrite() is a macro that calls xQueueGenericSend(), and + * therefore has the same return values as xQueueSendToFront(). However, pdPASS + * is the only value that can be returned because xQueueOverwrite() will write + * to the queue even when the queue is already full. + * + * Example usage: + * @code{c} + * + * void vFunction( void *pvParameters ) + * { + * QueueHandle_t xQueue; + * uint32_t ulVarToSend, ulValReceived; + * + * // Create a queue to hold one uint32_t value. It is strongly + * // recommended *not* to use xQueueOverwrite() on queues that can + * // contain more than one value, and doing so will trigger an assertion + * // if configASSERT() is defined. + * xQueue = xQueueCreate( 1, sizeof( uint32_t ) ); + * + * // Write the value 10 to the queue using xQueueOverwrite(). + * ulVarToSend = 10; + * xQueueOverwrite( xQueue, &ulVarToSend ); + * + * // Peeking the queue should now return 10, but leave the value 10 in + * // the queue. A block time of zero is used as it is known that the + * // queue holds a value. + * ulValReceived = 0; + * xQueuePeek( xQueue, &ulValReceived, 0 ); + * + * if( ulValReceived != 10 ) + * { + * // Error unless the item was removed by a different task. + * } + * + * // The queue is still full. Use xQueueOverwrite() to overwrite the + * // value held in the queue with 100. + * ulVarToSend = 100; + * xQueueOverwrite( xQueue, &ulVarToSend ); + * + * // This time read from the queue, leaving the queue empty once more. + * // A block time of 0 is used again. + * xQueueReceive( xQueue, &ulValReceived, 0 ); + * + * // The value read should be the last value written, even though the + * // queue was already full when the value was written. + * if( ulValReceived != 100 ) + * { + * // Error! + * } + * + * // ... + * } + * @endcode + * \defgroup xQueueOverwrite xQueueOverwrite + * \ingroup QueueManagement + */ +#define xQueueOverwrite( xQueue, pvItemToQueue ) \ + xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), 0, queueOVERWRITE ) + + +/** + * queue. h + * @code{c} + * BaseType_t xQueueGenericSend( + * QueueHandle_t xQueue, + * const void * pvItemToQueue, + * TickType_t xTicksToWait + * BaseType_t xCopyPosition + * ); + * @endcode + * + * It is preferred that the macros xQueueSend(), xQueueSendToFront() and + * xQueueSendToBack() are used in place of calling this function directly. + * + * Post an item on a queue. The item is queued by copy, not by reference. + * This function must not be called from an interrupt service routine. + * See xQueueSendFromISR () for an alternative which may be used in an ISR. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param xTicksToWait The maximum amount of time the task should block + * waiting for space to become available on the queue, should it already + * be full. The call will return immediately if this is set to 0 and the + * queue is full. The time is defined in tick periods so the constant + * portTICK_PERIOD_MS should be used to convert to real time if this is required. + * + * @param xCopyPosition Can take the value queueSEND_TO_BACK to place the + * item at the back of the queue, or queueSEND_TO_FRONT to place the item + * at the front of the queue (for high priority messages). + * + * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. + * + * Example usage: + * @code{c} + * struct AMessage + * { + * char ucMessageID; + * char ucData[ 20 ]; + * } xMessage; + * + * uint32_t ulVar = 10UL; + * + * void vATask( void *pvParameters ) + * { + * QueueHandle_t xQueue1, xQueue2; + * struct AMessage *pxMessage; + * + * // Create a queue capable of containing 10 uint32_t values. + * xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); + * + * // Create a queue capable of containing 10 pointers to AMessage structures. + * // These should be passed by pointer as they contain a lot of data. + * xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); + * + * // ... + * + * if( xQueue1 != 0 ) + * { + * // Send an uint32_t. Wait for 10 ticks for space to become + * // available if necessary. + * if( xQueueGenericSend( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10, queueSEND_TO_BACK ) != pdPASS ) + * { + * // Failed to post the message, even after 10 ticks. + * } + * } + * + * if( xQueue2 != 0 ) + * { + * // Send a pointer to a struct AMessage object. Don't block if the + * // queue is already full. + * pxMessage = & xMessage; + * xQueueGenericSend( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0, queueSEND_TO_BACK ); + * } + * + * // ... Rest of task code. + * } + * @endcode + * \defgroup xQueueSend xQueueSend + * \ingroup QueueManagement + */ +BaseType_t xQueueGenericSend( QueueHandle_t xQueue, + const void * const pvItemToQueue, + TickType_t xTicksToWait, + const BaseType_t xCopyPosition ) PRIVILEGED_FUNCTION; + +/** + * queue. h + * @code{c} + * BaseType_t xQueuePeek( + * QueueHandle_t xQueue, + * void * const pvBuffer, + * TickType_t xTicksToWait + * ); + * @endcode + * + * Receive an item from a queue without removing the item from the queue. + * The item is received by copy so a buffer of adequate size must be + * provided. The number of bytes copied into the buffer was defined when + * the queue was created. + * + * Successfully received items remain on the queue so will be returned again + * by the next call, or a call to xQueueReceive(). + * + * This macro must not be used in an interrupt service routine. See + * xQueuePeekFromISR() for an alternative that can be called from an interrupt + * service routine. + * + * @param xQueue The handle to the queue from which the item is to be + * received. + * + * @param pvBuffer Pointer to the buffer into which the received item will + * be copied. + * + * @param xTicksToWait The maximum amount of time the task should block + * waiting for an item to receive should the queue be empty at the time + * of the call. The time is defined in tick periods so the constant + * portTICK_PERIOD_MS should be used to convert to real time if this is required. + * xQueuePeek() will return immediately if xTicksToWait is 0 and the queue + * is empty. + * + * @return pdTRUE if an item was successfully received from the queue, + * otherwise pdFALSE. + * + * Example usage: + * @code{c} + * struct AMessage + * { + * char ucMessageID; + * char ucData[ 20 ]; + * } xMessage; + * + * QueueHandle_t xQueue; + * + * // Task to create a queue and post a value. + * void vATask( void *pvParameters ) + * { + * struct AMessage *pxMessage; + * + * // Create a queue capable of containing 10 pointers to AMessage structures. + * // These should be passed by pointer as they contain a lot of data. + * xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) ); + * if( xQueue == 0 ) + * { + * // Failed to create the queue. + * } + * + * // ... + * + * // Send a pointer to a struct AMessage object. Don't block if the + * // queue is already full. + * pxMessage = & xMessage; + * xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 ); + * + * // ... Rest of task code. + * } + * + * // Task to peek the data from the queue. + * void vADifferentTask( void *pvParameters ) + * { + * struct AMessage *pxRxedMessage; + * + * if( xQueue != 0 ) + * { + * // Peek a message on the created queue. Block for 10 ticks if a + * // message is not immediately available. + * if( xQueuePeek( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) ) + * { + * // pcRxedMessage now points to the struct AMessage variable posted + * // by vATask, but the item still remains on the queue. + * } + * } + * + * // ... Rest of task code. + * } + * @endcode + * \defgroup xQueuePeek xQueuePeek + * \ingroup QueueManagement + */ +BaseType_t xQueuePeek( QueueHandle_t xQueue, + void * const pvBuffer, + TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/** + * queue. h + * @code{c} + * BaseType_t xQueuePeekFromISR( + * QueueHandle_t xQueue, + * void *pvBuffer, + * ); + * @endcode + * + * A version of xQueuePeek() that can be called from an interrupt service + * routine (ISR). + * + * Receive an item from a queue without removing the item from the queue. + * The item is received by copy so a buffer of adequate size must be + * provided. The number of bytes copied into the buffer was defined when + * the queue was created. + * + * Successfully received items remain on the queue so will be returned again + * by the next call, or a call to xQueueReceive(). + * + * @param xQueue The handle to the queue from which the item is to be + * received. + * + * @param pvBuffer Pointer to the buffer into which the received item will + * be copied. + * + * @return pdTRUE if an item was successfully received from the queue, + * otherwise pdFALSE. + * + * \defgroup xQueuePeekFromISR xQueuePeekFromISR + * \ingroup QueueManagement + */ +BaseType_t xQueuePeekFromISR( QueueHandle_t xQueue, + void * const pvBuffer ) PRIVILEGED_FUNCTION; + +/** + * queue. h + * @code{c} + * BaseType_t xQueueReceive( + * QueueHandle_t xQueue, + * void *pvBuffer, + * TickType_t xTicksToWait + * ); + * @endcode + * + * Receive an item from a queue. The item is received by copy so a buffer of + * adequate size must be provided. The number of bytes copied into the buffer + * was defined when the queue was created. + * + * Successfully received items are removed from the queue. + * + * This function must not be used in an interrupt service routine. See + * xQueueReceiveFromISR for an alternative that can. + * + * @param xQueue The handle to the queue from which the item is to be + * received. + * + * @param pvBuffer Pointer to the buffer into which the received item will + * be copied. + * + * @param xTicksToWait The maximum amount of time the task should block + * waiting for an item to receive should the queue be empty at the time + * of the call. xQueueReceive() will return immediately if xTicksToWait + * is zero and the queue is empty. The time is defined in tick periods so the + * constant portTICK_PERIOD_MS should be used to convert to real time if this is + * required. + * + * @return pdTRUE if an item was successfully received from the queue, + * otherwise pdFALSE. + * + * Example usage: + * @code{c} + * struct AMessage + * { + * char ucMessageID; + * char ucData[ 20 ]; + * } xMessage; + * + * QueueHandle_t xQueue; + * + * // Task to create a queue and post a value. + * void vATask( void *pvParameters ) + * { + * struct AMessage *pxMessage; + * + * // Create a queue capable of containing 10 pointers to AMessage structures. + * // These should be passed by pointer as they contain a lot of data. + * xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) ); + * if( xQueue == 0 ) + * { + * // Failed to create the queue. + * } + * + * // ... + * + * // Send a pointer to a struct AMessage object. Don't block if the + * // queue is already full. + * pxMessage = & xMessage; + * xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 ); + * + * // ... Rest of task code. + * } + * + * // Task to receive from the queue. + * void vADifferentTask( void *pvParameters ) + * { + * struct AMessage *pxRxedMessage; + * + * if( xQueue != 0 ) + * { + * // Receive a message on the created queue. Block for 10 ticks if a + * // message is not immediately available. + * if( xQueueReceive( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) ) + * { + * // pcRxedMessage now points to the struct AMessage variable posted + * // by vATask. + * } + * } + * + * // ... Rest of task code. + * } + * @endcode + * \defgroup xQueueReceive xQueueReceive + * \ingroup QueueManagement + */ +BaseType_t xQueueReceive( QueueHandle_t xQueue, + void * const pvBuffer, + TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/** + * queue. h + * @code{c} + * UBaseType_t uxQueueMessagesWaiting( const QueueHandle_t xQueue ); + * @endcode + * + * Return the number of messages stored in a queue. + * + * @param xQueue A handle to the queue being queried. + * + * @return The number of messages available in the queue. + * + * \defgroup uxQueueMessagesWaiting uxQueueMessagesWaiting + * \ingroup QueueManagement + */ +UBaseType_t uxQueueMessagesWaiting( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; + +/** + * queue. h + * @code{c} + * UBaseType_t uxQueueSpacesAvailable( const QueueHandle_t xQueue ); + * @endcode + * + * Return the number of free spaces available in a queue. This is equal to the + * number of items that can be sent to the queue before the queue becomes full + * if no items are removed. + * + * @param xQueue A handle to the queue being queried. + * + * @return The number of spaces available in the queue. + * + * \defgroup uxQueueMessagesWaiting uxQueueMessagesWaiting + * \ingroup QueueManagement + */ +UBaseType_t uxQueueSpacesAvailable( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; + +/** + * queue. h + * @code{c} + * void vQueueDelete( QueueHandle_t xQueue ); + * @endcode + * + * Delete a queue - freeing all the memory allocated for storing of items + * placed on the queue. + * + * @param xQueue A handle to the queue to be deleted. + * + * \defgroup vQueueDelete vQueueDelete + * \ingroup QueueManagement + */ +void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; + +/** + * queue. h + * @code{c} + * BaseType_t xQueueSendToFrontFromISR( + * QueueHandle_t xQueue, + * const void *pvItemToQueue, + * BaseType_t *pxHigherPriorityTaskWoken + * ); + * @endcode + * + * This is a macro that calls xQueueGenericSendFromISR(). + * + * Post an item to the front of a queue. It is safe to use this macro from + * within an interrupt service routine. + * + * Items are queued by copy not reference so it is preferable to only + * queue small items, especially when called from an ISR. In most cases + * it would be preferable to store a pointer to the item being queued. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param pxHigherPriorityTaskWoken xQueueSendToFrontFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task + * to unblock, and the unblocked task has a priority higher than the currently + * running task. If xQueueSendToFromFromISR() sets this value to pdTRUE then + * a context switch should be requested before the interrupt is exited. + * + * @return pdTRUE if the data was successfully sent to the queue, otherwise + * errQUEUE_FULL. + * + * Example usage for buffered IO (where the ISR can obtain more than one value + * per call): + * @code{c} + * void vBufferISR( void ) + * { + * char cIn; + * BaseType_t xHigherPrioritTaskWoken; + * + * // We have not woken a task at the start of the ISR. + * xHigherPriorityTaskWoken = pdFALSE; + * + * // Loop until the buffer is empty. + * do + * { + * // Obtain a byte from the buffer. + * cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); + * + * // Post the byte. + * xQueueSendToFrontFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); + * + * } while( portINPUT_BYTE( BUFFER_COUNT ) ); + * + * // Now the buffer is empty we can switch context if necessary. + * if( xHigherPriorityTaskWoken ) + * { + * taskYIELD (); + * } + * } + * @endcode + * + * \defgroup xQueueSendFromISR xQueueSendFromISR + * \ingroup QueueManagement + */ +#define xQueueSendToFrontFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) \ + xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueSEND_TO_FRONT ) + + +/** + * queue. h + * @code{c} + * BaseType_t xQueueSendToBackFromISR( + * QueueHandle_t xQueue, + * const void *pvItemToQueue, + * BaseType_t *pxHigherPriorityTaskWoken + * ); + * @endcode + * + * This is a macro that calls xQueueGenericSendFromISR(). + * + * Post an item to the back of a queue. It is safe to use this macro from + * within an interrupt service routine. + * + * Items are queued by copy not reference so it is preferable to only + * queue small items, especially when called from an ISR. In most cases + * it would be preferable to store a pointer to the item being queued. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param pxHigherPriorityTaskWoken xQueueSendToBackFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task + * to unblock, and the unblocked task has a priority higher than the currently + * running task. If xQueueSendToBackFromISR() sets this value to pdTRUE then + * a context switch should be requested before the interrupt is exited. + * + * @return pdTRUE if the data was successfully sent to the queue, otherwise + * errQUEUE_FULL. + * + * Example usage for buffered IO (where the ISR can obtain more than one value + * per call): + * @code{c} + * void vBufferISR( void ) + * { + * char cIn; + * BaseType_t xHigherPriorityTaskWoken; + * + * // We have not woken a task at the start of the ISR. + * xHigherPriorityTaskWoken = pdFALSE; + * + * // Loop until the buffer is empty. + * do + * { + * // Obtain a byte from the buffer. + * cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); + * + * // Post the byte. + * xQueueSendToBackFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); + * + * } while( portINPUT_BYTE( BUFFER_COUNT ) ); + * + * // Now the buffer is empty we can switch context if necessary. + * if( xHigherPriorityTaskWoken ) + * { + * taskYIELD (); + * } + * } + * @endcode + * + * \defgroup xQueueSendFromISR xQueueSendFromISR + * \ingroup QueueManagement + */ +#define xQueueSendToBackFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) \ + xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueSEND_TO_BACK ) + +/** + * queue. h + * @code{c} + * BaseType_t xQueueOverwriteFromISR( + * QueueHandle_t xQueue, + * const void * pvItemToQueue, + * BaseType_t *pxHigherPriorityTaskWoken + * ); + * @endcode + * + * A version of xQueueOverwrite() that can be used in an interrupt service + * routine (ISR). + * + * Only for use with queues that can hold a single item - so the queue is either + * empty or full. + * + * Post an item on a queue. If the queue is already full then overwrite the + * value held in the queue. The item is queued by copy, not by reference. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param pxHigherPriorityTaskWoken xQueueOverwriteFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task + * to unblock, and the unblocked task has a priority higher than the currently + * running task. If xQueueOverwriteFromISR() sets this value to pdTRUE then + * a context switch should be requested before the interrupt is exited. + * + * @return xQueueOverwriteFromISR() is a macro that calls + * xQueueGenericSendFromISR(), and therefore has the same return values as + * xQueueSendToFrontFromISR(). However, pdPASS is the only value that can be + * returned because xQueueOverwriteFromISR() will write to the queue even when + * the queue is already full. + * + * Example usage: + * @code{c} + * + * QueueHandle_t xQueue; + * + * void vFunction( void *pvParameters ) + * { + * // Create a queue to hold one uint32_t value. It is strongly + * // recommended *not* to use xQueueOverwriteFromISR() on queues that can + * // contain more than one value, and doing so will trigger an assertion + * // if configASSERT() is defined. + * xQueue = xQueueCreate( 1, sizeof( uint32_t ) ); + * } + * + * void vAnInterruptHandler( void ) + * { + * // xHigherPriorityTaskWoken must be set to pdFALSE before it is used. + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; + * uint32_t ulVarToSend, ulValReceived; + * + * // Write the value 10 to the queue using xQueueOverwriteFromISR(). + * ulVarToSend = 10; + * xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken ); + * + * // The queue is full, but calling xQueueOverwriteFromISR() again will still + * // pass because the value held in the queue will be overwritten with the + * // new value. + * ulVarToSend = 100; + * xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken ); + * + * // Reading from the queue will now return 100. + * + * // ... + * + * if( xHigherPrioritytaskWoken == pdTRUE ) + * { + * // Writing to the queue caused a task to unblock and the unblocked task + * // has a priority higher than or equal to the priority of the currently + * // executing task (the task this interrupt interrupted). Perform a context + * // switch so this interrupt returns directly to the unblocked task. + * portYIELD_FROM_ISR(); // or portEND_SWITCHING_ISR() depending on the port. + * } + * } + * @endcode + * \defgroup xQueueOverwriteFromISR xQueueOverwriteFromISR + * \ingroup QueueManagement + */ +#define xQueueOverwriteFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) \ + xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueOVERWRITE ) + +/** + * queue. h + * @code{c} + * BaseType_t xQueueSendFromISR( + * QueueHandle_t xQueue, + * const void *pvItemToQueue, + * BaseType_t *pxHigherPriorityTaskWoken + * ); + * @endcode + * + * This is a macro that calls xQueueGenericSendFromISR(). It is included + * for backward compatibility with versions of FreeRTOS.org that did not + * include the xQueueSendToBackFromISR() and xQueueSendToFrontFromISR() + * macros. + * + * Post an item to the back of a queue. It is safe to use this function from + * within an interrupt service routine. + * + * Items are queued by copy not reference so it is preferable to only + * queue small items, especially when called from an ISR. In most cases + * it would be preferable to store a pointer to the item being queued. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param pxHigherPriorityTaskWoken xQueueSendFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task + * to unblock, and the unblocked task has a priority higher than the currently + * running task. If xQueueSendFromISR() sets this value to pdTRUE then + * a context switch should be requested before the interrupt is exited. + * + * @return pdTRUE if the data was successfully sent to the queue, otherwise + * errQUEUE_FULL. + * + * Example usage for buffered IO (where the ISR can obtain more than one value + * per call): + * @code{c} + * void vBufferISR( void ) + * { + * char cIn; + * BaseType_t xHigherPriorityTaskWoken; + * + * // We have not woken a task at the start of the ISR. + * xHigherPriorityTaskWoken = pdFALSE; + * + * // Loop until the buffer is empty. + * do + * { + * // Obtain a byte from the buffer. + * cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); + * + * // Post the byte. + * xQueueSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); + * + * } while( portINPUT_BYTE( BUFFER_COUNT ) ); + * + * // Now the buffer is empty we can switch context if necessary. + * if( xHigherPriorityTaskWoken ) + * { + * // Actual macro used here is port specific. + * portYIELD_FROM_ISR (); + * } + * } + * @endcode + * + * \defgroup xQueueSendFromISR xQueueSendFromISR + * \ingroup QueueManagement + */ +#define xQueueSendFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) \ + xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueSEND_TO_BACK ) + +/** + * queue. h + * @code{c} + * BaseType_t xQueueGenericSendFromISR( + * QueueHandle_t xQueue, + * const void *pvItemToQueue, + * BaseType_t *pxHigherPriorityTaskWoken, + * BaseType_t xCopyPosition + * ); + * @endcode + * + * It is preferred that the macros xQueueSendFromISR(), + * xQueueSendToFrontFromISR() and xQueueSendToBackFromISR() be used in place + * of calling this function directly. xQueueGiveFromISR() is an + * equivalent for use by semaphores that don't actually copy any data. + * + * Post an item on a queue. It is safe to use this function from within an + * interrupt service routine. + * + * Items are queued by copy not reference so it is preferable to only + * queue small items, especially when called from an ISR. In most cases + * it would be preferable to store a pointer to the item being queued. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param pxHigherPriorityTaskWoken xQueueGenericSendFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task + * to unblock, and the unblocked task has a priority higher than the currently + * running task. If xQueueGenericSendFromISR() sets this value to pdTRUE then + * a context switch should be requested before the interrupt is exited. + * + * @param xCopyPosition Can take the value queueSEND_TO_BACK to place the + * item at the back of the queue, or queueSEND_TO_FRONT to place the item + * at the front of the queue (for high priority messages). + * + * @return pdTRUE if the data was successfully sent to the queue, otherwise + * errQUEUE_FULL. + * + * Example usage for buffered IO (where the ISR can obtain more than one value + * per call): + * @code{c} + * void vBufferISR( void ) + * { + * char cIn; + * BaseType_t xHigherPriorityTaskWokenByPost; + * + * // We have not woken a task at the start of the ISR. + * xHigherPriorityTaskWokenByPost = pdFALSE; + * + * // Loop until the buffer is empty. + * do + * { + * // Obtain a byte from the buffer. + * cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); + * + * // Post each byte. + * xQueueGenericSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWokenByPost, queueSEND_TO_BACK ); + * + * } while( portINPUT_BYTE( BUFFER_COUNT ) ); + * + * // Now the buffer is empty we can switch context if necessary. Note that the + * // name of the yield function required is port specific. + * if( xHigherPriorityTaskWokenByPost ) + * { + * portYIELD_FROM_ISR(); + * } + * } + * @endcode + * + * \defgroup xQueueSendFromISR xQueueSendFromISR + * \ingroup QueueManagement + */ +BaseType_t xQueueGenericSendFromISR( QueueHandle_t xQueue, + const void * const pvItemToQueue, + BaseType_t * const pxHigherPriorityTaskWoken, + const BaseType_t xCopyPosition ) PRIVILEGED_FUNCTION; +BaseType_t xQueueGiveFromISR( QueueHandle_t xQueue, + BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + +/** + * queue. h + * @code{c} + * BaseType_t xQueueReceiveFromISR( + * QueueHandle_t xQueue, + * void *pvBuffer, + * BaseType_t *pxTaskWoken + * ); + * @endcode + * + * Receive an item from a queue. It is safe to use this function from within an + * interrupt service routine. + * + * @param xQueue The handle to the queue from which the item is to be + * received. + * + * @param pvBuffer Pointer to the buffer into which the received item will + * be copied. + * + * @param pxTaskWoken A task may be blocked waiting for space to become + * available on the queue. If xQueueReceiveFromISR causes such a task to + * unblock *pxTaskWoken will get set to pdTRUE, otherwise *pxTaskWoken will + * remain unchanged. + * + * @return pdTRUE if an item was successfully received from the queue, + * otherwise pdFALSE. + * + * Example usage: + * @code{c} + * + * QueueHandle_t xQueue; + * + * // Function to create a queue and post some values. + * void vAFunction( void *pvParameters ) + * { + * char cValueToPost; + * const TickType_t xTicksToWait = ( TickType_t )0xff; + * + * // Create a queue capable of containing 10 characters. + * xQueue = xQueueCreate( 10, sizeof( char ) ); + * if( xQueue == 0 ) + * { + * // Failed to create the queue. + * } + * + * // ... + * + * // Post some characters that will be used within an ISR. If the queue + * // is full then this task will block for xTicksToWait ticks. + * cValueToPost = 'a'; + * xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); + * cValueToPost = 'b'; + * xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); + * + * // ... keep posting characters ... this task may block when the queue + * // becomes full. + * + * cValueToPost = 'c'; + * xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); + * } + * + * // ISR that outputs all the characters received on the queue. + * void vISR_Routine( void ) + * { + * BaseType_t xTaskWokenByReceive = pdFALSE; + * char cRxedChar; + * + * while( xQueueReceiveFromISR( xQueue, ( void * ) &cRxedChar, &xTaskWokenByReceive) ) + * { + * // A character was received. Output the character now. + * vOutputCharacter( cRxedChar ); + * + * // If removing the character from the queue woke the task that was + * // posting onto the queue cTaskWokenByReceive will have been set to + * // pdTRUE. No matter how many times this loop iterates only one + * // task will be woken. + * } + * + * if( cTaskWokenByPost != ( char ) pdFALSE; + * { + * taskYIELD (); + * } + * } + * @endcode + * \defgroup xQueueReceiveFromISR xQueueReceiveFromISR + * \ingroup QueueManagement + */ +BaseType_t xQueueReceiveFromISR( QueueHandle_t xQueue, + void * const pvBuffer, + BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + +/* + * Utilities to query queues that are safe to use from an ISR. These utilities + * should be used only from witin an ISR, or within a critical section. + */ +BaseType_t xQueueIsQueueEmptyFromISR( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; +BaseType_t xQueueIsQueueFullFromISR( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; +UBaseType_t uxQueueMessagesWaitingFromISR( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; + +/* + * The functions defined above are for passing data to and from tasks. The + * functions below are the equivalents for passing data to and from + * co-routines. + * + * These functions are called from the co-routine macro implementation and + * should not be called directly from application code. Instead use the macro + * wrappers defined within croutine.h. + */ +BaseType_t xQueueCRSendFromISR( QueueHandle_t xQueue, + const void * pvItemToQueue, + BaseType_t xCoRoutinePreviouslyWoken ); +BaseType_t xQueueCRReceiveFromISR( QueueHandle_t xQueue, + void * pvBuffer, + BaseType_t * pxTaskWoken ); +BaseType_t xQueueCRSend( QueueHandle_t xQueue, + const void * pvItemToQueue, + TickType_t xTicksToWait ); +BaseType_t xQueueCRReceive( QueueHandle_t xQueue, + void * pvBuffer, + TickType_t xTicksToWait ); + +/* + * For internal use only. Use xSemaphoreCreateMutex(), + * xSemaphoreCreateCounting() or xSemaphoreGetMutexHolder() instead of calling + * these functions directly. + */ +QueueHandle_t xQueueCreateMutex( const uint8_t ucQueueType ) PRIVILEGED_FUNCTION; +QueueHandle_t xQueueCreateMutexStatic( const uint8_t ucQueueType, + StaticQueue_t * pxStaticQueue ) PRIVILEGED_FUNCTION; +QueueHandle_t xQueueCreateCountingSemaphore( const UBaseType_t uxMaxCount, + const UBaseType_t uxInitialCount ) PRIVILEGED_FUNCTION; +QueueHandle_t xQueueCreateCountingSemaphoreStatic( const UBaseType_t uxMaxCount, + const UBaseType_t uxInitialCount, + StaticQueue_t * pxStaticQueue ) PRIVILEGED_FUNCTION; +BaseType_t xQueueSemaphoreTake( QueueHandle_t xQueue, + TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; +TaskHandle_t xQueueGetMutexHolder( QueueHandle_t xSemaphore ) PRIVILEGED_FUNCTION; +TaskHandle_t xQueueGetMutexHolderFromISR( QueueHandle_t xSemaphore ) PRIVILEGED_FUNCTION; + +/* + * For internal use only. Use xSemaphoreTakeMutexRecursive() or + * xSemaphoreGiveMutexRecursive() instead of calling these functions directly. + */ +BaseType_t xQueueTakeMutexRecursive( QueueHandle_t xMutex, + TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; +BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) PRIVILEGED_FUNCTION; + +/* + * Reset a queue back to its original empty state. The return value is now + * obsolete and is always set to pdPASS. + */ +#define xQueueReset( xQueue ) xQueueGenericReset( xQueue, pdFALSE ) + +/* + * The registry is provided as a means for kernel aware debuggers to + * locate queues, semaphores and mutexes. Call vQueueAddToRegistry() add + * a queue, semaphore or mutex handle to the registry if you want the handle + * to be available to a kernel aware debugger. If you are not using a kernel + * aware debugger then this function can be ignored. + * + * configQUEUE_REGISTRY_SIZE defines the maximum number of handles the + * registry can hold. configQUEUE_REGISTRY_SIZE must be greater than 0 + * within FreeRTOSConfig.h for the registry to be available. Its value + * does not effect the number of queues, semaphores and mutexes that can be + * created - just the number that the registry can hold. + * + * If vQueueAddToRegistry is called more than once with the same xQueue + * parameter, the registry will store the pcQueueName parameter from the + * most recent call to vQueueAddToRegistry. + * + * @param xQueue The handle of the queue being added to the registry. This + * is the handle returned by a call to xQueueCreate(). Semaphore and mutex + * handles can also be passed in here. + * + * @param pcQueueName The name to be associated with the handle. This is the + * name that the kernel aware debugger will display. The queue registry only + * stores a pointer to the string - so the string must be persistent (global or + * preferably in ROM/Flash), not on the stack. + */ +#if ( configQUEUE_REGISTRY_SIZE > 0 ) + void vQueueAddToRegistry( QueueHandle_t xQueue, + const char * pcQueueName ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ +#endif + +/* + * The registry is provided as a means for kernel aware debuggers to + * locate queues, semaphores and mutexes. Call vQueueAddToRegistry() add + * a queue, semaphore or mutex handle to the registry if you want the handle + * to be available to a kernel aware debugger, and vQueueUnregisterQueue() to + * remove the queue, semaphore or mutex from the register. If you are not using + * a kernel aware debugger then this function can be ignored. + * + * @param xQueue The handle of the queue being removed from the registry. + */ +#if ( configQUEUE_REGISTRY_SIZE > 0 ) + void vQueueUnregisterQueue( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; +#endif + +/* + * The queue registry is provided as a means for kernel aware debuggers to + * locate queues, semaphores and mutexes. Call pcQueueGetName() to look + * up and return the name of a queue in the queue registry from the queue's + * handle. + * + * @param xQueue The handle of the queue the name of which will be returned. + * @return If the queue is in the registry then a pointer to the name of the + * queue is returned. If the queue is not in the registry then NULL is + * returned. + */ +#if ( configQUEUE_REGISTRY_SIZE > 0 ) + const char * pcQueueGetName( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ +#endif + +/* + * Generic version of the function used to create a queue using dynamic memory + * allocation. This is called by other functions and macros that create other + * RTOS objects that use the queue structure as their base. + */ +#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + QueueHandle_t xQueueGenericCreate( const UBaseType_t uxQueueLength, + const UBaseType_t uxItemSize, + const uint8_t ucQueueType ) PRIVILEGED_FUNCTION; +#endif + +/* + * Generic version of the function used to create a queue using dynamic memory + * allocation. This is called by other functions and macros that create other + * RTOS objects that use the queue structure as their base. + */ +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + QueueHandle_t xQueueGenericCreateStatic( const UBaseType_t uxQueueLength, + const UBaseType_t uxItemSize, + uint8_t * pucQueueStorage, + StaticQueue_t * pxStaticQueue, + const uint8_t ucQueueType ) PRIVILEGED_FUNCTION; +#endif + +/* + * Queue sets provide a mechanism to allow a task to block (pend) on a read + * operation from multiple queues or semaphores simultaneously. + * + * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this + * function. + * + * A queue set must be explicitly created using a call to xQueueCreateSet() + * before it can be used. Once created, standard FreeRTOS queues and semaphores + * can be added to the set using calls to xQueueAddToSet(). + * xQueueSelectFromSet() is then used to determine which, if any, of the queues + * or semaphores contained in the set is in a state where a queue read or + * semaphore take operation would be successful. + * + * Note 1: See the documentation on https://www.FreeRTOS.org/RTOS-queue-sets.html + * for reasons why queue sets are very rarely needed in practice as there are + * simpler methods of blocking on multiple objects. + * + * Note 2: Blocking on a queue set that contains a mutex will not cause the + * mutex holder to inherit the priority of the blocked task. + * + * Note 3: An additional 4 bytes of RAM is required for each space in a every + * queue added to a queue set. Therefore counting semaphores that have a high + * maximum count value should not be added to a queue set. + * + * Note 4: A receive (in the case of a queue) or take (in the case of a + * semaphore) operation must not be performed on a member of a queue set unless + * a call to xQueueSelectFromSet() has first returned a handle to that set member. + * + * @param uxEventQueueLength Queue sets store events that occur on + * the queues and semaphores contained in the set. uxEventQueueLength specifies + * the maximum number of events that can be queued at once. To be absolutely + * certain that events are not lost uxEventQueueLength should be set to the + * total sum of the length of the queues added to the set, where binary + * semaphores and mutexes have a length of 1, and counting semaphores have a + * length set by their maximum count value. Examples: + * + If a queue set is to hold a queue of length 5, another queue of length 12, + * and a binary semaphore, then uxEventQueueLength should be set to + * (5 + 12 + 1), or 18. + * + If a queue set is to hold three binary semaphores then uxEventQueueLength + * should be set to (1 + 1 + 1 ), or 3. + * + If a queue set is to hold a counting semaphore that has a maximum count of + * 5, and a counting semaphore that has a maximum count of 3, then + * uxEventQueueLength should be set to (5 + 3), or 8. + * + * @return If the queue set is created successfully then a handle to the created + * queue set is returned. Otherwise NULL is returned. + */ +QueueSetHandle_t xQueueCreateSet( const UBaseType_t uxEventQueueLength ) PRIVILEGED_FUNCTION; + +/* + * Adds a queue or semaphore to a queue set that was previously created by a + * call to xQueueCreateSet(). + * + * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this + * function. + * + * Note 1: A receive (in the case of a queue) or take (in the case of a + * semaphore) operation must not be performed on a member of a queue set unless + * a call to xQueueSelectFromSet() has first returned a handle to that set member. + * + * @param xQueueOrSemaphore The handle of the queue or semaphore being added to + * the queue set (cast to an QueueSetMemberHandle_t type). + * + * @param xQueueSet The handle of the queue set to which the queue or semaphore + * is being added. + * + * @return If the queue or semaphore was successfully added to the queue set + * then pdPASS is returned. If the queue could not be successfully added to the + * queue set because it is already a member of a different queue set then pdFAIL + * is returned. + */ +BaseType_t xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, + QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION; + +/* + * Removes a queue or semaphore from a queue set. A queue or semaphore can only + * be removed from a set if the queue or semaphore is empty. + * + * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this + * function. + * + * @param xQueueOrSemaphore The handle of the queue or semaphore being removed + * from the queue set (cast to an QueueSetMemberHandle_t type). + * + * @param xQueueSet The handle of the queue set in which the queue or semaphore + * is included. + * + * @return If the queue or semaphore was successfully removed from the queue set + * then pdPASS is returned. If the queue was not in the queue set, or the + * queue (or semaphore) was not empty, then pdFAIL is returned. + */ +BaseType_t xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, + QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION; + +/* + * xQueueSelectFromSet() selects from the members of a queue set a queue or + * semaphore that either contains data (in the case of a queue) or is available + * to take (in the case of a semaphore). xQueueSelectFromSet() effectively + * allows a task to block (pend) on a read operation on all the queues and + * semaphores in a queue set simultaneously. + * + * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this + * function. + * + * Note 1: See the documentation on https://www.FreeRTOS.org/RTOS-queue-sets.html + * for reasons why queue sets are very rarely needed in practice as there are + * simpler methods of blocking on multiple objects. + * + * Note 2: Blocking on a queue set that contains a mutex will not cause the + * mutex holder to inherit the priority of the blocked task. + * + * Note 3: A receive (in the case of a queue) or take (in the case of a + * semaphore) operation must not be performed on a member of a queue set unless + * a call to xQueueSelectFromSet() has first returned a handle to that set member. + * + * @param xQueueSet The queue set on which the task will (potentially) block. + * + * @param xTicksToWait The maximum time, in ticks, that the calling task will + * remain in the Blocked state (with other tasks executing) to wait for a member + * of the queue set to be ready for a successful queue read or semaphore take + * operation. + * + * @return xQueueSelectFromSet() will return the handle of a queue (cast to + * a QueueSetMemberHandle_t type) contained in the queue set that contains data, + * or the handle of a semaphore (cast to a QueueSetMemberHandle_t type) contained + * in the queue set that is available, or NULL if no such queue or semaphore + * exists before before the specified block time expires. + */ +QueueSetMemberHandle_t xQueueSelectFromSet( QueueSetHandle_t xQueueSet, + const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/* + * A version of xQueueSelectFromSet() that can be used from an ISR. + */ +QueueSetMemberHandle_t xQueueSelectFromSetFromISR( QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION; + +/* Not public API functions. */ +void vQueueWaitForMessageRestricted( QueueHandle_t xQueue, + TickType_t xTicksToWait, + const BaseType_t xWaitIndefinitely ) PRIVILEGED_FUNCTION; +BaseType_t xQueueGenericReset( QueueHandle_t xQueue, + BaseType_t xNewQueue ) PRIVILEGED_FUNCTION; +void vQueueSetQueueNumber( QueueHandle_t xQueue, + UBaseType_t uxQueueNumber ) PRIVILEGED_FUNCTION; +UBaseType_t uxQueueGetQueueNumber( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; +uint8_t ucQueueGetQueueType( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; + + +/* *INDENT-OFF* */ +#ifdef __cplusplus + } +#endif +/* *INDENT-ON* */ + +#endif /* QUEUE_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/semphr.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/semphr.h new file mode 100644 index 0000000..d28d4a0 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/semphr.h @@ -0,0 +1,1189 @@ +/* + * FreeRTOS Kernel V10.4.6 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#ifndef SEMAPHORE_H +#define SEMAPHORE_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h" must appear in source files before "include semphr.h" +#endif + +#include "queue.h" + +typedef QueueHandle_t SemaphoreHandle_t; + +#define semBINARY_SEMAPHORE_QUEUE_LENGTH ( ( uint8_t ) 1U ) +#define semSEMAPHORE_QUEUE_ITEM_LENGTH ( ( uint8_t ) 0U ) +#define semGIVE_BLOCK_TIME ( ( TickType_t ) 0U ) + + +/** + * semphr. h + * @code{c} + * vSemaphoreCreateBinary( SemaphoreHandle_t xSemaphore ); + * @endcode + * + * In many usage scenarios it is faster and more memory efficient to use a + * direct to task notification in place of a binary semaphore! + * https://www.FreeRTOS.org/RTOS-task-notifications.html + * + * This old vSemaphoreCreateBinary() macro is now deprecated in favour of the + * xSemaphoreCreateBinary() function. Note that binary semaphores created using + * the vSemaphoreCreateBinary() macro are created in a state such that the + * first call to 'take' the semaphore would pass, whereas binary semaphores + * created using xSemaphoreCreateBinary() are created in a state such that the + * the semaphore must first be 'given' before it can be 'taken'. + * + * Macro that implements a semaphore by using the existing queue mechanism. + * The queue length is 1 as this is a binary semaphore. The data size is 0 + * as we don't want to actually store any data - we just want to know if the + * queue is empty or full. + * + * This type of semaphore can be used for pure synchronisation between tasks or + * between an interrupt and a task. The semaphore need not be given back once + * obtained, so one task/interrupt can continuously 'give' the semaphore while + * another continuously 'takes' the semaphore. For this reason this type of + * semaphore does not use a priority inheritance mechanism. For an alternative + * that does use priority inheritance see xSemaphoreCreateMutex(). + * + * @param xSemaphore Handle to the created semaphore. Should be of type SemaphoreHandle_t. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore = NULL; + * + * void vATask( void * pvParameters ) + * { + * // Semaphore cannot be used before a call to vSemaphoreCreateBinary (). + * // This is a macro so pass the variable in directly. + * vSemaphoreCreateBinary( xSemaphore ); + * + * if( xSemaphore != NULL ) + * { + * // The semaphore was created successfully. + * // The semaphore can now be used. + * } + * } + * @endcode + * \defgroup vSemaphoreCreateBinary vSemaphoreCreateBinary + * \ingroup Semaphores + */ +#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + #define vSemaphoreCreateBinary( xSemaphore ) \ + { \ + ( xSemaphore ) = xQueueGenericCreate( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE ); \ + if( ( xSemaphore ) != NULL ) \ + { \ + ( void ) xSemaphoreGive( ( xSemaphore ) ); \ + } \ + } +#endif + +/** + * semphr. h + * @code{c} + * SemaphoreHandle_t xSemaphoreCreateBinary( void ); + * @endcode + * + * Creates a new binary semaphore instance, and returns a handle by which the + * new semaphore can be referenced. + * + * In many usage scenarios it is faster and more memory efficient to use a + * direct to task notification in place of a binary semaphore! + * https://www.FreeRTOS.org/RTOS-task-notifications.html + * + * Internally, within the FreeRTOS implementation, binary semaphores use a block + * of memory, in which the semaphore structure is stored. If a binary semaphore + * is created using xSemaphoreCreateBinary() then the required memory is + * automatically dynamically allocated inside the xSemaphoreCreateBinary() + * function. (see https://www.FreeRTOS.org/a00111.html). If a binary semaphore + * is created using xSemaphoreCreateBinaryStatic() then the application writer + * must provide the memory. xSemaphoreCreateBinaryStatic() therefore allows a + * binary semaphore to be created without using any dynamic memory allocation. + * + * The old vSemaphoreCreateBinary() macro is now deprecated in favour of this + * xSemaphoreCreateBinary() function. Note that binary semaphores created using + * the vSemaphoreCreateBinary() macro are created in a state such that the + * first call to 'take' the semaphore would pass, whereas binary semaphores + * created using xSemaphoreCreateBinary() are created in a state such that the + * the semaphore must first be 'given' before it can be 'taken'. + * + * This type of semaphore can be used for pure synchronisation between tasks or + * between an interrupt and a task. The semaphore need not be given back once + * obtained, so one task/interrupt can continuously 'give' the semaphore while + * another continuously 'takes' the semaphore. For this reason this type of + * semaphore does not use a priority inheritance mechanism. For an alternative + * that does use priority inheritance see xSemaphoreCreateMutex(). + * + * @return Handle to the created semaphore, or NULL if the memory required to + * hold the semaphore's data structures could not be allocated. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore = NULL; + * + * void vATask( void * pvParameters ) + * { + * // Semaphore cannot be used before a call to xSemaphoreCreateBinary(). + * // This is a macro so pass the variable in directly. + * xSemaphore = xSemaphoreCreateBinary(); + * + * if( xSemaphore != NULL ) + * { + * // The semaphore was created successfully. + * // The semaphore can now be used. + * } + * } + * @endcode + * \defgroup xSemaphoreCreateBinary xSemaphoreCreateBinary + * \ingroup Semaphores + */ +#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + #define xSemaphoreCreateBinary() xQueueGenericCreate( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE ) +#endif + +/** + * semphr. h + * @code{c} + * SemaphoreHandle_t xSemaphoreCreateBinaryStatic( StaticSemaphore_t *pxSemaphoreBuffer ); + * @endcode + * + * Creates a new binary semaphore instance, and returns a handle by which the + * new semaphore can be referenced. + * + * NOTE: In many usage scenarios it is faster and more memory efficient to use a + * direct to task notification in place of a binary semaphore! + * https://www.FreeRTOS.org/RTOS-task-notifications.html + * + * Internally, within the FreeRTOS implementation, binary semaphores use a block + * of memory, in which the semaphore structure is stored. If a binary semaphore + * is created using xSemaphoreCreateBinary() then the required memory is + * automatically dynamically allocated inside the xSemaphoreCreateBinary() + * function. (see https://www.FreeRTOS.org/a00111.html). If a binary semaphore + * is created using xSemaphoreCreateBinaryStatic() then the application writer + * must provide the memory. xSemaphoreCreateBinaryStatic() therefore allows a + * binary semaphore to be created without using any dynamic memory allocation. + * + * This type of semaphore can be used for pure synchronisation between tasks or + * between an interrupt and a task. The semaphore need not be given back once + * obtained, so one task/interrupt can continuously 'give' the semaphore while + * another continuously 'takes' the semaphore. For this reason this type of + * semaphore does not use a priority inheritance mechanism. For an alternative + * that does use priority inheritance see xSemaphoreCreateMutex(). + * + * @param pxSemaphoreBuffer Must point to a variable of type StaticSemaphore_t, + * which will then be used to hold the semaphore's data structure, removing the + * need for the memory to be allocated dynamically. + * + * @return If the semaphore is created then a handle to the created semaphore is + * returned. If pxSemaphoreBuffer is NULL then NULL is returned. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore = NULL; + * StaticSemaphore_t xSemaphoreBuffer; + * + * void vATask( void * pvParameters ) + * { + * // Semaphore cannot be used before a call to xSemaphoreCreateBinary(). + * // The semaphore's data structures will be placed in the xSemaphoreBuffer + * // variable, the address of which is passed into the function. The + * // function's parameter is not NULL, so the function will not attempt any + * // dynamic memory allocation, and therefore the function will not return + * // return NULL. + * xSemaphore = xSemaphoreCreateBinary( &xSemaphoreBuffer ); + * + * // Rest of task code goes here. + * } + * @endcode + * \defgroup xSemaphoreCreateBinaryStatic xSemaphoreCreateBinaryStatic + * \ingroup Semaphores + */ +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + #define xSemaphoreCreateBinaryStatic( pxStaticSemaphore ) xQueueGenericCreateStatic( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, NULL, pxStaticSemaphore, queueQUEUE_TYPE_BINARY_SEMAPHORE ) +#endif /* configSUPPORT_STATIC_ALLOCATION */ + +/** + * semphr. h + * @code{c} + * xSemaphoreTake( + * SemaphoreHandle_t xSemaphore, + * TickType_t xBlockTime + * ); + * @endcode + * + * Macro to obtain a semaphore. The semaphore must have previously been + * created with a call to xSemaphoreCreateBinary(), xSemaphoreCreateMutex() or + * xSemaphoreCreateCounting(). + * + * @param xSemaphore A handle to the semaphore being taken - obtained when + * the semaphore was created. + * + * @param xBlockTime The time in ticks to wait for the semaphore to become + * available. The macro portTICK_PERIOD_MS can be used to convert this to a + * real time. A block time of zero can be used to poll the semaphore. A block + * time of portMAX_DELAY can be used to block indefinitely (provided + * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h). + * + * @return pdTRUE if the semaphore was obtained. pdFALSE + * if xBlockTime expired without the semaphore becoming available. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore = NULL; + * + * // A task that creates a semaphore. + * void vATask( void * pvParameters ) + * { + * // Create the semaphore to guard a shared resource. + * xSemaphore = xSemaphoreCreateBinary(); + * } + * + * // A task that uses the semaphore. + * void vAnotherTask( void * pvParameters ) + * { + * // ... Do other things. + * + * if( xSemaphore != NULL ) + * { + * // See if we can obtain the semaphore. If the semaphore is not available + * // wait 10 ticks to see if it becomes free. + * if( xSemaphoreTake( xSemaphore, ( TickType_t ) 10 ) == pdTRUE ) + * { + * // We were able to obtain the semaphore and can now access the + * // shared resource. + * + * // ... + * + * // We have finished accessing the shared resource. Release the + * // semaphore. + * xSemaphoreGive( xSemaphore ); + * } + * else + * { + * // We could not obtain the semaphore and can therefore not access + * // the shared resource safely. + * } + * } + * } + * @endcode + * \defgroup xSemaphoreTake xSemaphoreTake + * \ingroup Semaphores + */ +#define xSemaphoreTake( xSemaphore, xBlockTime ) xQueueSemaphoreTake( ( xSemaphore ), ( xBlockTime ) ) + +/** + * semphr. h + * @code{c} + * xSemaphoreTakeRecursive( + * SemaphoreHandle_t xMutex, + * TickType_t xBlockTime + * ); + * @endcode + * + * Macro to recursively obtain, or 'take', a mutex type semaphore. + * The mutex must have previously been created using a call to + * xSemaphoreCreateRecursiveMutex(); + * + * configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this + * macro to be available. + * + * This macro must not be used on mutexes created using xSemaphoreCreateMutex(). + * + * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex + * doesn't become available again until the owner has called + * xSemaphoreGiveRecursive() for each successful 'take' request. For example, + * if a task successfully 'takes' the same mutex 5 times then the mutex will + * not be available to any other task until it has also 'given' the mutex back + * exactly five times. + * + * @param xMutex A handle to the mutex being obtained. This is the + * handle returned by xSemaphoreCreateRecursiveMutex(); + * + * @param xBlockTime The time in ticks to wait for the semaphore to become + * available. The macro portTICK_PERIOD_MS can be used to convert this to a + * real time. A block time of zero can be used to poll the semaphore. If + * the task already owns the semaphore then xSemaphoreTakeRecursive() will + * return immediately no matter what the value of xBlockTime. + * + * @return pdTRUE if the semaphore was obtained. pdFALSE if xBlockTime + * expired without the semaphore becoming available. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xMutex = NULL; + * + * // A task that creates a mutex. + * void vATask( void * pvParameters ) + * { + * // Create the mutex to guard a shared resource. + * xMutex = xSemaphoreCreateRecursiveMutex(); + * } + * + * // A task that uses the mutex. + * void vAnotherTask( void * pvParameters ) + * { + * // ... Do other things. + * + * if( xMutex != NULL ) + * { + * // See if we can obtain the mutex. If the mutex is not available + * // wait 10 ticks to see if it becomes free. + * if( xSemaphoreTakeRecursive( xSemaphore, ( TickType_t ) 10 ) == pdTRUE ) + * { + * // We were able to obtain the mutex and can now access the + * // shared resource. + * + * // ... + * // For some reason due to the nature of the code further calls to + * // xSemaphoreTakeRecursive() are made on the same mutex. In real + * // code these would not be just sequential calls as this would make + * // no sense. Instead the calls are likely to be buried inside + * // a more complex call structure. + * xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); + * xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); + * + * // The mutex has now been 'taken' three times, so will not be + * // available to another task until it has also been given back + * // three times. Again it is unlikely that real code would have + * // these calls sequentially, but instead buried in a more complex + * // call structure. This is just for illustrative purposes. + * xSemaphoreGiveRecursive( xMutex ); + * xSemaphoreGiveRecursive( xMutex ); + * xSemaphoreGiveRecursive( xMutex ); + * + * // Now the mutex can be taken by other tasks. + * } + * else + * { + * // We could not obtain the mutex and can therefore not access + * // the shared resource safely. + * } + * } + * } + * @endcode + * \defgroup xSemaphoreTakeRecursive xSemaphoreTakeRecursive + * \ingroup Semaphores + */ +#if ( configUSE_RECURSIVE_MUTEXES == 1 ) + #define xSemaphoreTakeRecursive( xMutex, xBlockTime ) xQueueTakeMutexRecursive( ( xMutex ), ( xBlockTime ) ) +#endif + +/** + * semphr. h + * @code{c} + * xSemaphoreGive( SemaphoreHandle_t xSemaphore ); + * @endcode + * + * Macro to release a semaphore. The semaphore must have previously been + * created with a call to xSemaphoreCreateBinary(), xSemaphoreCreateMutex() or + * xSemaphoreCreateCounting(). and obtained using sSemaphoreTake(). + * + * This macro must not be used from an ISR. See xSemaphoreGiveFromISR () for + * an alternative which can be used from an ISR. + * + * This macro must also not be used on semaphores created using + * xSemaphoreCreateRecursiveMutex(). + * + * @param xSemaphore A handle to the semaphore being released. This is the + * handle returned when the semaphore was created. + * + * @return pdTRUE if the semaphore was released. pdFALSE if an error occurred. + * Semaphores are implemented using queues. An error can occur if there is + * no space on the queue to post a message - indicating that the + * semaphore was not first obtained correctly. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore = NULL; + * + * void vATask( void * pvParameters ) + * { + * // Create the semaphore to guard a shared resource. + * xSemaphore = vSemaphoreCreateBinary(); + * + * if( xSemaphore != NULL ) + * { + * if( xSemaphoreGive( xSemaphore ) != pdTRUE ) + * { + * // We would expect this call to fail because we cannot give + * // a semaphore without first "taking" it! + * } + * + * // Obtain the semaphore - don't block if the semaphore is not + * // immediately available. + * if( xSemaphoreTake( xSemaphore, ( TickType_t ) 0 ) ) + * { + * // We now have the semaphore and can access the shared resource. + * + * // ... + * + * // We have finished accessing the shared resource so can free the + * // semaphore. + * if( xSemaphoreGive( xSemaphore ) != pdTRUE ) + * { + * // We would not expect this call to fail because we must have + * // obtained the semaphore to get here. + * } + * } + * } + * } + * @endcode + * \defgroup xSemaphoreGive xSemaphoreGive + * \ingroup Semaphores + */ +#define xSemaphoreGive( xSemaphore ) xQueueGenericSend( ( QueueHandle_t ) ( xSemaphore ), NULL, semGIVE_BLOCK_TIME, queueSEND_TO_BACK ) + +/** + * semphr. h + * @code{c} + * xSemaphoreGiveRecursive( SemaphoreHandle_t xMutex ); + * @endcode + * + * Macro to recursively release, or 'give', a mutex type semaphore. + * The mutex must have previously been created using a call to + * xSemaphoreCreateRecursiveMutex(); + * + * configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this + * macro to be available. + * + * This macro must not be used on mutexes created using xSemaphoreCreateMutex(). + * + * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex + * doesn't become available again until the owner has called + * xSemaphoreGiveRecursive() for each successful 'take' request. For example, + * if a task successfully 'takes' the same mutex 5 times then the mutex will + * not be available to any other task until it has also 'given' the mutex back + * exactly five times. + * + * @param xMutex A handle to the mutex being released, or 'given'. This is the + * handle returned by xSemaphoreCreateMutex(); + * + * @return pdTRUE if the semaphore was given. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xMutex = NULL; + * + * // A task that creates a mutex. + * void vATask( void * pvParameters ) + * { + * // Create the mutex to guard a shared resource. + * xMutex = xSemaphoreCreateRecursiveMutex(); + * } + * + * // A task that uses the mutex. + * void vAnotherTask( void * pvParameters ) + * { + * // ... Do other things. + * + * if( xMutex != NULL ) + * { + * // See if we can obtain the mutex. If the mutex is not available + * // wait 10 ticks to see if it becomes free. + * if( xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ) == pdTRUE ) + * { + * // We were able to obtain the mutex and can now access the + * // shared resource. + * + * // ... + * // For some reason due to the nature of the code further calls to + * // xSemaphoreTakeRecursive() are made on the same mutex. In real + * // code these would not be just sequential calls as this would make + * // no sense. Instead the calls are likely to be buried inside + * // a more complex call structure. + * xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); + * xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); + * + * // The mutex has now been 'taken' three times, so will not be + * // available to another task until it has also been given back + * // three times. Again it is unlikely that real code would have + * // these calls sequentially, it would be more likely that the calls + * // to xSemaphoreGiveRecursive() would be called as a call stack + * // unwound. This is just for demonstrative purposes. + * xSemaphoreGiveRecursive( xMutex ); + * xSemaphoreGiveRecursive( xMutex ); + * xSemaphoreGiveRecursive( xMutex ); + * + * // Now the mutex can be taken by other tasks. + * } + * else + * { + * // We could not obtain the mutex and can therefore not access + * // the shared resource safely. + * } + * } + * } + * @endcode + * \defgroup xSemaphoreGiveRecursive xSemaphoreGiveRecursive + * \ingroup Semaphores + */ +#if ( configUSE_RECURSIVE_MUTEXES == 1 ) + #define xSemaphoreGiveRecursive( xMutex ) xQueueGiveMutexRecursive( ( xMutex ) ) +#endif + +/** + * semphr. h + * @code{c} + * xSemaphoreGiveFromISR( + * SemaphoreHandle_t xSemaphore, + * BaseType_t *pxHigherPriorityTaskWoken + * ); + * @endcode + * + * Macro to release a semaphore. The semaphore must have previously been + * created with a call to xSemaphoreCreateBinary() or xSemaphoreCreateCounting(). + * + * Mutex type semaphores (those created using a call to xSemaphoreCreateMutex()) + * must not be used with this macro. + * + * This macro can be used from an ISR. + * + * @param xSemaphore A handle to the semaphore being released. This is the + * handle returned when the semaphore was created. + * + * @param pxHigherPriorityTaskWoken xSemaphoreGiveFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if giving the semaphore caused a task + * to unblock, and the unblocked task has a priority higher than the currently + * running task. If xSemaphoreGiveFromISR() sets this value to pdTRUE then + * a context switch should be requested before the interrupt is exited. + * + * @return pdTRUE if the semaphore was successfully given, otherwise errQUEUE_FULL. + * + * Example usage: + * @code{c} + \#define LONG_TIME 0xffff + \#define TICKS_TO_WAIT 10 + * SemaphoreHandle_t xSemaphore = NULL; + * + * // Repetitive task. + * void vATask( void * pvParameters ) + * { + * for( ;; ) + * { + * // We want this task to run every 10 ticks of a timer. The semaphore + * // was created before this task was started. + * + * // Block waiting for the semaphore to become available. + * if( xSemaphoreTake( xSemaphore, LONG_TIME ) == pdTRUE ) + * { + * // It is time to execute. + * + * // ... + * + * // We have finished our task. Return to the top of the loop where + * // we will block on the semaphore until it is time to execute + * // again. Note when using the semaphore for synchronisation with an + * // ISR in this manner there is no need to 'give' the semaphore back. + * } + * } + * } + * + * // Timer ISR + * void vTimerISR( void * pvParameters ) + * { + * static uint8_t ucLocalTickCount = 0; + * static BaseType_t xHigherPriorityTaskWoken; + * + * // A timer tick has occurred. + * + * // ... Do other time functions. + * + * // Is it time for vATask () to run? + * xHigherPriorityTaskWoken = pdFALSE; + * ucLocalTickCount++; + * if( ucLocalTickCount >= TICKS_TO_WAIT ) + * { + * // Unblock the task by releasing the semaphore. + * xSemaphoreGiveFromISR( xSemaphore, &xHigherPriorityTaskWoken ); + * + * // Reset the count so we release the semaphore again in 10 ticks time. + * ucLocalTickCount = 0; + * } + * + * if( xHigherPriorityTaskWoken != pdFALSE ) + * { + * // We can force a context switch here. Context switching from an + * // ISR uses port specific syntax. Check the demo task for your port + * // to find the syntax required. + * } + * } + * @endcode + * \defgroup xSemaphoreGiveFromISR xSemaphoreGiveFromISR + * \ingroup Semaphores + */ +#define xSemaphoreGiveFromISR( xSemaphore, pxHigherPriorityTaskWoken ) xQueueGiveFromISR( ( QueueHandle_t ) ( xSemaphore ), ( pxHigherPriorityTaskWoken ) ) + +/** + * semphr. h + * @code{c} + * xSemaphoreTakeFromISR( + * SemaphoreHandle_t xSemaphore, + * BaseType_t *pxHigherPriorityTaskWoken + * ); + * @endcode + * + * Macro to take a semaphore from an ISR. The semaphore must have + * previously been created with a call to xSemaphoreCreateBinary() or + * xSemaphoreCreateCounting(). + * + * Mutex type semaphores (those created using a call to xSemaphoreCreateMutex()) + * must not be used with this macro. + * + * This macro can be used from an ISR, however taking a semaphore from an ISR + * is not a common operation. It is likely to only be useful when taking a + * counting semaphore when an interrupt is obtaining an object from a resource + * pool (when the semaphore count indicates the number of resources available). + * + * @param xSemaphore A handle to the semaphore being taken. This is the + * handle returned when the semaphore was created. + * + * @param pxHigherPriorityTaskWoken xSemaphoreTakeFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if taking the semaphore caused a task + * to unblock, and the unblocked task has a priority higher than the currently + * running task. If xSemaphoreTakeFromISR() sets this value to pdTRUE then + * a context switch should be requested before the interrupt is exited. + * + * @return pdTRUE if the semaphore was successfully taken, otherwise + * pdFALSE + */ +#define xSemaphoreTakeFromISR( xSemaphore, pxHigherPriorityTaskWoken ) xQueueReceiveFromISR( ( QueueHandle_t ) ( xSemaphore ), NULL, ( pxHigherPriorityTaskWoken ) ) + +/** + * semphr. h + * @code{c} + * SemaphoreHandle_t xSemaphoreCreateMutex( void ); + * @endcode + * + * Creates a new mutex type semaphore instance, and returns a handle by which + * the new mutex can be referenced. + * + * Internally, within the FreeRTOS implementation, mutex semaphores use a block + * of memory, in which the mutex structure is stored. If a mutex is created + * using xSemaphoreCreateMutex() then the required memory is automatically + * dynamically allocated inside the xSemaphoreCreateMutex() function. (see + * https://www.FreeRTOS.org/a00111.html). If a mutex is created using + * xSemaphoreCreateMutexStatic() then the application writer must provided the + * memory. xSemaphoreCreateMutexStatic() therefore allows a mutex to be created + * without using any dynamic memory allocation. + * + * Mutexes created using this function can be accessed using the xSemaphoreTake() + * and xSemaphoreGive() macros. The xSemaphoreTakeRecursive() and + * xSemaphoreGiveRecursive() macros must not be used. + * + * This type of semaphore uses a priority inheritance mechanism so a task + * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the + * semaphore it is no longer required. + * + * Mutex type semaphores cannot be used from within interrupt service routines. + * + * See xSemaphoreCreateBinary() for an alternative implementation that can be + * used for pure synchronisation (where one task or interrupt always 'gives' the + * semaphore and another always 'takes' the semaphore) and from within interrupt + * service routines. + * + * @return If the mutex was successfully created then a handle to the created + * semaphore is returned. If there was not enough heap to allocate the mutex + * data structures then NULL is returned. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore; + * + * void vATask( void * pvParameters ) + * { + * // Semaphore cannot be used before a call to xSemaphoreCreateMutex(). + * // This is a macro so pass the variable in directly. + * xSemaphore = xSemaphoreCreateMutex(); + * + * if( xSemaphore != NULL ) + * { + * // The semaphore was created successfully. + * // The semaphore can now be used. + * } + * } + * @endcode + * \defgroup xSemaphoreCreateMutex xSemaphoreCreateMutex + * \ingroup Semaphores + */ +#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + #define xSemaphoreCreateMutex() xQueueCreateMutex( queueQUEUE_TYPE_MUTEX ) +#endif + +/** + * semphr. h + * @code{c} + * SemaphoreHandle_t xSemaphoreCreateMutexStatic( StaticSemaphore_t *pxMutexBuffer ); + * @endcode + * + * Creates a new mutex type semaphore instance, and returns a handle by which + * the new mutex can be referenced. + * + * Internally, within the FreeRTOS implementation, mutex semaphores use a block + * of memory, in which the mutex structure is stored. If a mutex is created + * using xSemaphoreCreateMutex() then the required memory is automatically + * dynamically allocated inside the xSemaphoreCreateMutex() function. (see + * https://www.FreeRTOS.org/a00111.html). If a mutex is created using + * xSemaphoreCreateMutexStatic() then the application writer must provided the + * memory. xSemaphoreCreateMutexStatic() therefore allows a mutex to be created + * without using any dynamic memory allocation. + * + * Mutexes created using this function can be accessed using the xSemaphoreTake() + * and xSemaphoreGive() macros. The xSemaphoreTakeRecursive() and + * xSemaphoreGiveRecursive() macros must not be used. + * + * This type of semaphore uses a priority inheritance mechanism so a task + * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the + * semaphore it is no longer required. + * + * Mutex type semaphores cannot be used from within interrupt service routines. + * + * See xSemaphoreCreateBinary() for an alternative implementation that can be + * used for pure synchronisation (where one task or interrupt always 'gives' the + * semaphore and another always 'takes' the semaphore) and from within interrupt + * service routines. + * + * @param pxMutexBuffer Must point to a variable of type StaticSemaphore_t, + * which will be used to hold the mutex's data structure, removing the need for + * the memory to be allocated dynamically. + * + * @return If the mutex was successfully created then a handle to the created + * mutex is returned. If pxMutexBuffer was NULL then NULL is returned. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore; + * StaticSemaphore_t xMutexBuffer; + * + * void vATask( void * pvParameters ) + * { + * // A mutex cannot be used before it has been created. xMutexBuffer is + * // into xSemaphoreCreateMutexStatic() so no dynamic memory allocation is + * // attempted. + * xSemaphore = xSemaphoreCreateMutexStatic( &xMutexBuffer ); + * + * // As no dynamic memory allocation was performed, xSemaphore cannot be NULL, + * // so there is no need to check it. + * } + * @endcode + * \defgroup xSemaphoreCreateMutexStatic xSemaphoreCreateMutexStatic + * \ingroup Semaphores + */ +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + #define xSemaphoreCreateMutexStatic( pxMutexBuffer ) xQueueCreateMutexStatic( queueQUEUE_TYPE_MUTEX, ( pxMutexBuffer ) ) +#endif /* configSUPPORT_STATIC_ALLOCATION */ + + +/** + * semphr. h + * @code{c} + * SemaphoreHandle_t xSemaphoreCreateRecursiveMutex( void ); + * @endcode + * + * Creates a new recursive mutex type semaphore instance, and returns a handle + * by which the new recursive mutex can be referenced. + * + * Internally, within the FreeRTOS implementation, recursive mutexs use a block + * of memory, in which the mutex structure is stored. If a recursive mutex is + * created using xSemaphoreCreateRecursiveMutex() then the required memory is + * automatically dynamically allocated inside the + * xSemaphoreCreateRecursiveMutex() function. (see + * https://www.FreeRTOS.org/a00111.html). If a recursive mutex is created using + * xSemaphoreCreateRecursiveMutexStatic() then the application writer must + * provide the memory that will get used by the mutex. + * xSemaphoreCreateRecursiveMutexStatic() therefore allows a recursive mutex to + * be created without using any dynamic memory allocation. + * + * Mutexes created using this macro can be accessed using the + * xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros. The + * xSemaphoreTake() and xSemaphoreGive() macros must not be used. + * + * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex + * doesn't become available again until the owner has called + * xSemaphoreGiveRecursive() for each successful 'take' request. For example, + * if a task successfully 'takes' the same mutex 5 times then the mutex will + * not be available to any other task until it has also 'given' the mutex back + * exactly five times. + * + * This type of semaphore uses a priority inheritance mechanism so a task + * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the + * semaphore it is no longer required. + * + * Mutex type semaphores cannot be used from within interrupt service routines. + * + * See xSemaphoreCreateBinary() for an alternative implementation that can be + * used for pure synchronisation (where one task or interrupt always 'gives' the + * semaphore and another always 'takes' the semaphore) and from within interrupt + * service routines. + * + * @return xSemaphore Handle to the created mutex semaphore. Should be of type + * SemaphoreHandle_t. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore; + * + * void vATask( void * pvParameters ) + * { + * // Semaphore cannot be used before a call to xSemaphoreCreateMutex(). + * // This is a macro so pass the variable in directly. + * xSemaphore = xSemaphoreCreateRecursiveMutex(); + * + * if( xSemaphore != NULL ) + * { + * // The semaphore was created successfully. + * // The semaphore can now be used. + * } + * } + * @endcode + * \defgroup xSemaphoreCreateRecursiveMutex xSemaphoreCreateRecursiveMutex + * \ingroup Semaphores + */ +#if ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configUSE_RECURSIVE_MUTEXES == 1 ) ) + #define xSemaphoreCreateRecursiveMutex() xQueueCreateMutex( queueQUEUE_TYPE_RECURSIVE_MUTEX ) +#endif + +/** + * semphr. h + * @code{c} + * SemaphoreHandle_t xSemaphoreCreateRecursiveMutexStatic( StaticSemaphore_t *pxMutexBuffer ); + * @endcode + * + * Creates a new recursive mutex type semaphore instance, and returns a handle + * by which the new recursive mutex can be referenced. + * + * Internally, within the FreeRTOS implementation, recursive mutexs use a block + * of memory, in which the mutex structure is stored. If a recursive mutex is + * created using xSemaphoreCreateRecursiveMutex() then the required memory is + * automatically dynamically allocated inside the + * xSemaphoreCreateRecursiveMutex() function. (see + * https://www.FreeRTOS.org/a00111.html). If a recursive mutex is created using + * xSemaphoreCreateRecursiveMutexStatic() then the application writer must + * provide the memory that will get used by the mutex. + * xSemaphoreCreateRecursiveMutexStatic() therefore allows a recursive mutex to + * be created without using any dynamic memory allocation. + * + * Mutexes created using this macro can be accessed using the + * xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros. The + * xSemaphoreTake() and xSemaphoreGive() macros must not be used. + * + * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex + * doesn't become available again until the owner has called + * xSemaphoreGiveRecursive() for each successful 'take' request. For example, + * if a task successfully 'takes' the same mutex 5 times then the mutex will + * not be available to any other task until it has also 'given' the mutex back + * exactly five times. + * + * This type of semaphore uses a priority inheritance mechanism so a task + * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the + * semaphore it is no longer required. + * + * Mutex type semaphores cannot be used from within interrupt service routines. + * + * See xSemaphoreCreateBinary() for an alternative implementation that can be + * used for pure synchronisation (where one task or interrupt always 'gives' the + * semaphore and another always 'takes' the semaphore) and from within interrupt + * service routines. + * + * @param pxMutexBuffer Must point to a variable of type StaticSemaphore_t, + * which will then be used to hold the recursive mutex's data structure, + * removing the need for the memory to be allocated dynamically. + * + * @return If the recursive mutex was successfully created then a handle to the + * created recursive mutex is returned. If pxMutexBuffer was NULL then NULL is + * returned. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore; + * StaticSemaphore_t xMutexBuffer; + * + * void vATask( void * pvParameters ) + * { + * // A recursive semaphore cannot be used before it is created. Here a + * // recursive mutex is created using xSemaphoreCreateRecursiveMutexStatic(). + * // The address of xMutexBuffer is passed into the function, and will hold + * // the mutexes data structures - so no dynamic memory allocation will be + * // attempted. + * xSemaphore = xSemaphoreCreateRecursiveMutexStatic( &xMutexBuffer ); + * + * // As no dynamic memory allocation was performed, xSemaphore cannot be NULL, + * // so there is no need to check it. + * } + * @endcode + * \defgroup xSemaphoreCreateRecursiveMutexStatic xSemaphoreCreateRecursiveMutexStatic + * \ingroup Semaphores + */ +#if ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configUSE_RECURSIVE_MUTEXES == 1 ) ) + #define xSemaphoreCreateRecursiveMutexStatic( pxStaticSemaphore ) xQueueCreateMutexStatic( queueQUEUE_TYPE_RECURSIVE_MUTEX, pxStaticSemaphore ) +#endif /* configSUPPORT_STATIC_ALLOCATION */ + +/** + * semphr. h + * @code{c} + * SemaphoreHandle_t xSemaphoreCreateCounting( UBaseType_t uxMaxCount, UBaseType_t uxInitialCount ); + * @endcode + * + * Creates a new counting semaphore instance, and returns a handle by which the + * new counting semaphore can be referenced. + * + * In many usage scenarios it is faster and more memory efficient to use a + * direct to task notification in place of a counting semaphore! + * https://www.FreeRTOS.org/RTOS-task-notifications.html + * + * Internally, within the FreeRTOS implementation, counting semaphores use a + * block of memory, in which the counting semaphore structure is stored. If a + * counting semaphore is created using xSemaphoreCreateCounting() then the + * required memory is automatically dynamically allocated inside the + * xSemaphoreCreateCounting() function. (see + * https://www.FreeRTOS.org/a00111.html). If a counting semaphore is created + * using xSemaphoreCreateCountingStatic() then the application writer can + * instead optionally provide the memory that will get used by the counting + * semaphore. xSemaphoreCreateCountingStatic() therefore allows a counting + * semaphore to be created without using any dynamic memory allocation. + * + * Counting semaphores are typically used for two things: + * + * 1) Counting events. + * + * In this usage scenario an event handler will 'give' a semaphore each time + * an event occurs (incrementing the semaphore count value), and a handler + * task will 'take' a semaphore each time it processes an event + * (decrementing the semaphore count value). The count value is therefore + * the difference between the number of events that have occurred and the + * number that have been processed. In this case it is desirable for the + * initial count value to be zero. + * + * 2) Resource management. + * + * In this usage scenario the count value indicates the number of resources + * available. To obtain control of a resource a task must first obtain a + * semaphore - decrementing the semaphore count value. When the count value + * reaches zero there are no free resources. When a task finishes with the + * resource it 'gives' the semaphore back - incrementing the semaphore count + * value. In this case it is desirable for the initial count value to be + * equal to the maximum count value, indicating that all resources are free. + * + * @param uxMaxCount The maximum count value that can be reached. When the + * semaphore reaches this value it can no longer be 'given'. + * + * @param uxInitialCount The count value assigned to the semaphore when it is + * created. + * + * @return Handle to the created semaphore. Null if the semaphore could not be + * created. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore; + * + * void vATask( void * pvParameters ) + * { + * SemaphoreHandle_t xSemaphore = NULL; + * + * // Semaphore cannot be used before a call to xSemaphoreCreateCounting(). + * // The max value to which the semaphore can count should be 10, and the + * // initial value assigned to the count should be 0. + * xSemaphore = xSemaphoreCreateCounting( 10, 0 ); + * + * if( xSemaphore != NULL ) + * { + * // The semaphore was created successfully. + * // The semaphore can now be used. + * } + * } + * @endcode + * \defgroup xSemaphoreCreateCounting xSemaphoreCreateCounting + * \ingroup Semaphores + */ +#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + #define xSemaphoreCreateCounting( uxMaxCount, uxInitialCount ) xQueueCreateCountingSemaphore( ( uxMaxCount ), ( uxInitialCount ) ) +#endif + +/** + * semphr. h + * @code{c} + * SemaphoreHandle_t xSemaphoreCreateCountingStatic( UBaseType_t uxMaxCount, UBaseType_t uxInitialCount, StaticSemaphore_t *pxSemaphoreBuffer ); + * @endcode + * + * Creates a new counting semaphore instance, and returns a handle by which the + * new counting semaphore can be referenced. + * + * In many usage scenarios it is faster and more memory efficient to use a + * direct to task notification in place of a counting semaphore! + * https://www.FreeRTOS.org/RTOS-task-notifications.html + * + * Internally, within the FreeRTOS implementation, counting semaphores use a + * block of memory, in which the counting semaphore structure is stored. If a + * counting semaphore is created using xSemaphoreCreateCounting() then the + * required memory is automatically dynamically allocated inside the + * xSemaphoreCreateCounting() function. (see + * https://www.FreeRTOS.org/a00111.html). If a counting semaphore is created + * using xSemaphoreCreateCountingStatic() then the application writer must + * provide the memory. xSemaphoreCreateCountingStatic() therefore allows a + * counting semaphore to be created without using any dynamic memory allocation. + * + * Counting semaphores are typically used for two things: + * + * 1) Counting events. + * + * In this usage scenario an event handler will 'give' a semaphore each time + * an event occurs (incrementing the semaphore count value), and a handler + * task will 'take' a semaphore each time it processes an event + * (decrementing the semaphore count value). The count value is therefore + * the difference between the number of events that have occurred and the + * number that have been processed. In this case it is desirable for the + * initial count value to be zero. + * + * 2) Resource management. + * + * In this usage scenario the count value indicates the number of resources + * available. To obtain control of a resource a task must first obtain a + * semaphore - decrementing the semaphore count value. When the count value + * reaches zero there are no free resources. When a task finishes with the + * resource it 'gives' the semaphore back - incrementing the semaphore count + * value. In this case it is desirable for the initial count value to be + * equal to the maximum count value, indicating that all resources are free. + * + * @param uxMaxCount The maximum count value that can be reached. When the + * semaphore reaches this value it can no longer be 'given'. + * + * @param uxInitialCount The count value assigned to the semaphore when it is + * created. + * + * @param pxSemaphoreBuffer Must point to a variable of type StaticSemaphore_t, + * which will then be used to hold the semaphore's data structure, removing the + * need for the memory to be allocated dynamically. + * + * @return If the counting semaphore was successfully created then a handle to + * the created counting semaphore is returned. If pxSemaphoreBuffer was NULL + * then NULL is returned. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore; + * StaticSemaphore_t xSemaphoreBuffer; + * + * void vATask( void * pvParameters ) + * { + * SemaphoreHandle_t xSemaphore = NULL; + * + * // Counting semaphore cannot be used before they have been created. Create + * // a counting semaphore using xSemaphoreCreateCountingStatic(). The max + * // value to which the semaphore can count is 10, and the initial value + * // assigned to the count will be 0. The address of xSemaphoreBuffer is + * // passed in and will be used to hold the semaphore structure, so no dynamic + * // memory allocation will be used. + * xSemaphore = xSemaphoreCreateCounting( 10, 0, &xSemaphoreBuffer ); + * + * // No memory allocation was attempted so xSemaphore cannot be NULL, so there + * // is no need to check its value. + * } + * @endcode + * \defgroup xSemaphoreCreateCountingStatic xSemaphoreCreateCountingStatic + * \ingroup Semaphores + */ +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + #define xSemaphoreCreateCountingStatic( uxMaxCount, uxInitialCount, pxSemaphoreBuffer ) xQueueCreateCountingSemaphoreStatic( ( uxMaxCount ), ( uxInitialCount ), ( pxSemaphoreBuffer ) ) +#endif /* configSUPPORT_STATIC_ALLOCATION */ + +/** + * semphr. h + * @code{c} + * void vSemaphoreDelete( SemaphoreHandle_t xSemaphore ); + * @endcode + * + * Delete a semaphore. This function must be used with care. For example, + * do not delete a mutex type semaphore if the mutex is held by a task. + * + * @param xSemaphore A handle to the semaphore to be deleted. + * + * \defgroup vSemaphoreDelete vSemaphoreDelete + * \ingroup Semaphores + */ +#define vSemaphoreDelete( xSemaphore ) vQueueDelete( ( QueueHandle_t ) ( xSemaphore ) ) + +/** + * semphr.h + * @code{c} + * TaskHandle_t xSemaphoreGetMutexHolder( SemaphoreHandle_t xMutex ); + * @endcode + * + * If xMutex is indeed a mutex type semaphore, return the current mutex holder. + * If xMutex is not a mutex type semaphore, or the mutex is available (not held + * by a task), return NULL. + * + * Note: This is a good way of determining if the calling task is the mutex + * holder, but not a good way of determining the identity of the mutex holder as + * the holder may change between the function exiting and the returned value + * being tested. + */ +#define xSemaphoreGetMutexHolder( xSemaphore ) xQueueGetMutexHolder( ( xSemaphore ) ) + +/** + * semphr.h + * @code{c} + * TaskHandle_t xSemaphoreGetMutexHolderFromISR( SemaphoreHandle_t xMutex ); + * @endcode + * + * If xMutex is indeed a mutex type semaphore, return the current mutex holder. + * If xMutex is not a mutex type semaphore, or the mutex is available (not held + * by a task), return NULL. + * + */ +#define xSemaphoreGetMutexHolderFromISR( xSemaphore ) xQueueGetMutexHolderFromISR( ( xSemaphore ) ) + +/** + * semphr.h + * @code{c} + * UBaseType_t uxSemaphoreGetCount( SemaphoreHandle_t xSemaphore ); + * @endcode + * + * If the semaphore is a counting semaphore then uxSemaphoreGetCount() returns + * its current count value. If the semaphore is a binary semaphore then + * uxSemaphoreGetCount() returns 1 if the semaphore is available, and 0 if the + * semaphore is not available. + * + */ +#define uxSemaphoreGetCount( xSemaphore ) uxQueueMessagesWaiting( ( QueueHandle_t ) ( xSemaphore ) ) + +/** + * semphr.h + * @code{c} + * UBaseType_t uxSemaphoreGetCountFromISR( SemaphoreHandle_t xSemaphore ); + * @endcode + * + * If the semaphore is a counting semaphore then uxSemaphoreGetCountFromISR() returns + * its current count value. If the semaphore is a binary semaphore then + * uxSemaphoreGetCountFromISR() returns 1 if the semaphore is available, and 0 if the + * semaphore is not available. + * + */ +#define uxSemaphoreGetCountFromISR( xSemaphore ) uxQueueMessagesWaitingFromISR( ( QueueHandle_t ) ( xSemaphore ) ) + +#endif /* SEMAPHORE_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/stack_macros.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/stack_macros.h new file mode 100644 index 0000000..cfe5b95 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/stack_macros.h @@ -0,0 +1,137 @@ +/* + * FreeRTOS Kernel V10.4.6 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#ifndef STACK_MACROS_H +#define STACK_MACROS_H + +/* + * Call the stack overflow hook function if the stack of the task being swapped + * out is currently overflowed, or looks like it might have overflowed in the + * past. + * + * Setting configCHECK_FOR_STACK_OVERFLOW to 1 will cause the macro to check + * the current stack state only - comparing the current top of stack value to + * the stack limit. Setting configCHECK_FOR_STACK_OVERFLOW to greater than 1 + * will also cause the last few stack bytes to be checked to ensure the value + * to which the bytes were set when the task was created have not been + * overwritten. Note this second test does not guarantee that an overflowed + * stack will always be recognised. + */ + +/*-----------------------------------------------------------*/ + +/* + * portSTACK_LIMIT_PADDING is a number of extra words to consider to be in + * use on the stack. + */ +#ifndef portSTACK_LIMIT_PADDING + #define portSTACK_LIMIT_PADDING 0 +#endif + +#if ( ( configCHECK_FOR_STACK_OVERFLOW == 1 ) && ( portSTACK_GROWTH < 0 ) ) + +/* Only the current stack state is to be checked. */ + #define taskCHECK_FOR_STACK_OVERFLOW() \ + { \ + /* Is the currently saved stack pointer within the stack limit? */ \ + if( pxCurrentTCB->pxTopOfStack <= pxCurrentTCB->pxStack + portSTACK_LIMIT_PADDING ) \ + { \ + vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ + } \ + } + +#endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */ +/*-----------------------------------------------------------*/ + +#if ( ( configCHECK_FOR_STACK_OVERFLOW == 1 ) && ( portSTACK_GROWTH > 0 ) ) + +/* Only the current stack state is to be checked. */ + #define taskCHECK_FOR_STACK_OVERFLOW() \ + { \ + \ + /* Is the currently saved stack pointer within the stack limit? */ \ + if( pxCurrentTCB->pxTopOfStack >= pxCurrentTCB->pxEndOfStack - portSTACK_LIMIT_PADDING ) \ + { \ + vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ + } \ + } + +#endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */ +/*-----------------------------------------------------------*/ + +#if ( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH < 0 ) ) + + #define taskCHECK_FOR_STACK_OVERFLOW() \ + { \ + const uint32_t * const pulStack = ( uint32_t * ) pxCurrentTCB->pxStack; \ + const uint32_t ulCheckValue = ( uint32_t ) 0xa5a5a5a5; \ + \ + if( ( pulStack[ 0 ] != ulCheckValue ) || \ + ( pulStack[ 1 ] != ulCheckValue ) || \ + ( pulStack[ 2 ] != ulCheckValue ) || \ + ( pulStack[ 3 ] != ulCheckValue ) ) \ + { \ + vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ + } \ + } + +#endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */ +/*-----------------------------------------------------------*/ + +#if ( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH > 0 ) ) + + #define taskCHECK_FOR_STACK_OVERFLOW() \ + { \ + int8_t * pcEndOfStack = ( int8_t * ) pxCurrentTCB->pxEndOfStack; \ + static const uint8_t ucExpectedStackBytes[] = { tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ + tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ + tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ + tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ + tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE }; \ + \ + \ + pcEndOfStack -= sizeof( ucExpectedStackBytes ); \ + \ + /* Has the extremity of the task stack ever been written over? */ \ + if( memcmp( ( void * ) pcEndOfStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) != 0 ) \ + { \ + vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ + } \ + } + +#endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */ +/*-----------------------------------------------------------*/ + +/* Remove stack overflow macro if not being used. */ +#ifndef taskCHECK_FOR_STACK_OVERFLOW + #define taskCHECK_FOR_STACK_OVERFLOW() +#endif + + + +#endif /* STACK_MACROS_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/stdint.readme b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/stdint.readme new file mode 100644 index 0000000..654c62b --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/stdint.readme @@ -0,0 +1,58 @@ +/* + * FreeRTOS Kernel V10.4.6 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#ifndef FREERTOS_STDINT +#define FREERTOS_STDINT + +/******************************************************************************* + * THIS IS NOT A FULL stdint.h IMPLEMENTATION - It only contains the definitions + * necessary to build the FreeRTOS code. It is provided to allow FreeRTOS to be + * built using compilers that do not provide their own stdint.h definition. + * + * To use this file: + * + * 1) Copy this file into the directory that contains your FreeRTOSConfig.h + * header file, as that directory will already be in the compiler's include + * path. + * + * 2) Rename the copied file stdint.h. + * + */ + +typedef signed char int8_t; +typedef unsigned char uint8_t; +typedef short int16_t; +typedef unsigned short uint16_t; +typedef long int32_t; +typedef unsigned long uint32_t; + +#ifndef SIZE_MAX + #define SIZE_MAX ( ( size_t ) -1 ) +#endif + +#endif /* FREERTOS_STDINT */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/stream_buffer.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/stream_buffer.h new file mode 100644 index 0000000..c2812d4 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/stream_buffer.h @@ -0,0 +1,869 @@ +/* + * FreeRTOS Kernel V10.4.6 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* + * Stream buffers are used to send a continuous stream of data from one task or + * interrupt to another. Their implementation is light weight, making them + * particularly suited for interrupt to task and core to core communication + * scenarios. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xStreamBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xStreamBufferReceive()) inside a critical section section and set the + * receive block time to 0. + * + */ + +#ifndef STREAM_BUFFER_H +#define STREAM_BUFFER_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h must appear in source files before include stream_buffer.h" +#endif + +/* *INDENT-OFF* */ +#if defined( __cplusplus ) + extern "C" { +#endif +/* *INDENT-ON* */ + +/** + * Type by which stream buffers are referenced. For example, a call to + * xStreamBufferCreate() returns an StreamBufferHandle_t variable that can + * then be used as a parameter to xStreamBufferSend(), xStreamBufferReceive(), + * etc. + */ +struct StreamBufferDef_t; +typedef struct StreamBufferDef_t * StreamBufferHandle_t; + + +/** + * stream_buffer.h + * + * @code{c} + * StreamBufferHandle_t xStreamBufferCreate( size_t xBufferSizeBytes, size_t xTriggerLevelBytes ); + * @endcode + * + * Creates a new stream buffer using dynamically allocated memory. See + * xStreamBufferCreateStatic() for a version that uses statically allocated + * memory (memory that is allocated at compile time). + * + * configSUPPORT_DYNAMIC_ALLOCATION must be set to 1 or left undefined in + * FreeRTOSConfig.h for xStreamBufferCreate() to be available. + * + * @param xBufferSizeBytes The total number of bytes the stream buffer will be + * able to hold at any one time. + * + * @param xTriggerLevelBytes The number of bytes that must be in the stream + * buffer before a task that is blocked on the stream buffer to wait for data is + * moved out of the blocked state. For example, if a task is blocked on a read + * of an empty stream buffer that has a trigger level of 1 then the task will be + * unblocked when a single byte is written to the buffer or the task's block + * time expires. As another example, if a task is blocked on a read of an empty + * stream buffer that has a trigger level of 10 then the task will not be + * unblocked until the stream buffer contains at least 10 bytes or the task's + * block time expires. If a reading task's block time expires before the + * trigger level is reached then the task will still receive however many bytes + * are actually available. Setting a trigger level of 0 will result in a + * trigger level of 1 being used. It is not valid to specify a trigger level + * that is greater than the buffer size. + * + * @return If NULL is returned, then the stream buffer cannot be created + * because there is insufficient heap memory available for FreeRTOS to allocate + * the stream buffer data structures and storage area. A non-NULL value being + * returned indicates that the stream buffer has been created successfully - + * the returned value should be stored as the handle to the created stream + * buffer. + * + * Example use: + * @code{c} + * + * void vAFunction( void ) + * { + * StreamBufferHandle_t xStreamBuffer; + * const size_t xStreamBufferSizeBytes = 100, xTriggerLevel = 10; + * + * // Create a stream buffer that can hold 100 bytes. The memory used to hold + * // both the stream buffer structure and the data in the stream buffer is + * // allocated dynamically. + * xStreamBuffer = xStreamBufferCreate( xStreamBufferSizeBytes, xTriggerLevel ); + * + * if( xStreamBuffer == NULL ) + * { + * // There was not enough heap memory space available to create the + * // stream buffer. + * } + * else + * { + * // The stream buffer was created successfully and can now be used. + * } + * } + * @endcode + * \defgroup xStreamBufferCreate xStreamBufferCreate + * \ingroup StreamBufferManagement + */ +#define xStreamBufferCreate( xBufferSizeBytes, xTriggerLevelBytes ) xStreamBufferGenericCreate( xBufferSizeBytes, xTriggerLevelBytes, pdFALSE ) + +/** + * stream_buffer.h + * + * @code{c} + * StreamBufferHandle_t xStreamBufferCreateStatic( size_t xBufferSizeBytes, + * size_t xTriggerLevelBytes, + * uint8_t *pucStreamBufferStorageArea, + * StaticStreamBuffer_t *pxStaticStreamBuffer ); + * @endcode + * Creates a new stream buffer using statically allocated memory. See + * xStreamBufferCreate() for a version that uses dynamically allocated memory. + * + * configSUPPORT_STATIC_ALLOCATION must be set to 1 in FreeRTOSConfig.h for + * xStreamBufferCreateStatic() to be available. + * + * @param xBufferSizeBytes The size, in bytes, of the buffer pointed to by the + * pucStreamBufferStorageArea parameter. + * + * @param xTriggerLevelBytes The number of bytes that must be in the stream + * buffer before a task that is blocked on the stream buffer to wait for data is + * moved out of the blocked state. For example, if a task is blocked on a read + * of an empty stream buffer that has a trigger level of 1 then the task will be + * unblocked when a single byte is written to the buffer or the task's block + * time expires. As another example, if a task is blocked on a read of an empty + * stream buffer that has a trigger level of 10 then the task will not be + * unblocked until the stream buffer contains at least 10 bytes or the task's + * block time expires. If a reading task's block time expires before the + * trigger level is reached then the task will still receive however many bytes + * are actually available. Setting a trigger level of 0 will result in a + * trigger level of 1 being used. It is not valid to specify a trigger level + * that is greater than the buffer size. + * + * @param pucStreamBufferStorageArea Must point to a uint8_t array that is at + * least xBufferSizeBytes big. This is the array to which streams are + * copied when they are written to the stream buffer. + * + * @param pxStaticStreamBuffer Must point to a variable of type + * StaticStreamBuffer_t, which will be used to hold the stream buffer's data + * structure. + * + * @return If the stream buffer is created successfully then a handle to the + * created stream buffer is returned. If either pucStreamBufferStorageArea or + * pxStaticstreamBuffer are NULL then NULL is returned. + * + * Example use: + * @code{c} + * + * // Used to dimension the array used to hold the streams. The available space + * // will actually be one less than this, so 999. + #define STORAGE_SIZE_BYTES 1000 + * + * // Defines the memory that will actually hold the streams within the stream + * // buffer. + * static uint8_t ucStorageBuffer[ STORAGE_SIZE_BYTES ]; + * + * // The variable used to hold the stream buffer structure. + * StaticStreamBuffer_t xStreamBufferStruct; + * + * void MyFunction( void ) + * { + * StreamBufferHandle_t xStreamBuffer; + * const size_t xTriggerLevel = 1; + * + * xStreamBuffer = xStreamBufferCreateStatic( sizeof( ucStorageBuffer ), + * xTriggerLevel, + * ucStorageBuffer, + * &xStreamBufferStruct ); + * + * // As neither the pucStreamBufferStorageArea or pxStaticStreamBuffer + * // parameters were NULL, xStreamBuffer will not be NULL, and can be used to + * // reference the created stream buffer in other stream buffer API calls. + * + * // Other code that uses the stream buffer can go here. + * } + * + * @endcode + * \defgroup xStreamBufferCreateStatic xStreamBufferCreateStatic + * \ingroup StreamBufferManagement + */ +#define xStreamBufferCreateStatic( xBufferSizeBytes, xTriggerLevelBytes, pucStreamBufferStorageArea, pxStaticStreamBuffer ) \ + xStreamBufferGenericCreateStatic( xBufferSizeBytes, xTriggerLevelBytes, pdFALSE, pucStreamBufferStorageArea, pxStaticStreamBuffer ) + +/** + * stream_buffer.h + * + * @code{c} + * size_t xStreamBufferSend( StreamBufferHandle_t xStreamBuffer, + * const void *pvTxData, + * size_t xDataLengthBytes, + * TickType_t xTicksToWait ); + * @endcode + * + * Sends bytes to a stream buffer. The bytes are copied into the stream buffer. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xStreamBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xStreamBufferReceive()) inside a critical section and set the receive + * block time to 0. + * + * Use xStreamBufferSend() to write to a stream buffer from a task. Use + * xStreamBufferSendFromISR() to write to a stream buffer from an interrupt + * service routine (ISR). + * + * @param xStreamBuffer The handle of the stream buffer to which a stream is + * being sent. + * + * @param pvTxData A pointer to the buffer that holds the bytes to be copied + * into the stream buffer. + * + * @param xDataLengthBytes The maximum number of bytes to copy from pvTxData + * into the stream buffer. + * + * @param xTicksToWait The maximum amount of time the task should remain in the + * Blocked state to wait for enough space to become available in the stream + * buffer, should the stream buffer contain too little space to hold the + * another xDataLengthBytes bytes. The block time is specified in tick periods, + * so the absolute time it represents is dependent on the tick frequency. The + * macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds + * into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will + * cause the task to wait indefinitely (without timing out), provided + * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. If a task times out + * before it can write all xDataLengthBytes into the buffer it will still write + * as many bytes as possible. A task does not use any CPU time when it is in + * the blocked state. + * + * @return The number of bytes written to the stream buffer. If a task times + * out before it can write all xDataLengthBytes into the buffer it will still + * write as many bytes as possible. + * + * Example use: + * @code{c} + * void vAFunction( StreamBufferHandle_t xStreamBuffer ) + * { + * size_t xBytesSent; + * uint8_t ucArrayToSend[] = { 0, 1, 2, 3 }; + * char *pcStringToSend = "String to send"; + * const TickType_t x100ms = pdMS_TO_TICKS( 100 ); + * + * // Send an array to the stream buffer, blocking for a maximum of 100ms to + * // wait for enough space to be available in the stream buffer. + * xBytesSent = xStreamBufferSend( xStreamBuffer, ( void * ) ucArrayToSend, sizeof( ucArrayToSend ), x100ms ); + * + * if( xBytesSent != sizeof( ucArrayToSend ) ) + * { + * // The call to xStreamBufferSend() times out before there was enough + * // space in the buffer for the data to be written, but it did + * // successfully write xBytesSent bytes. + * } + * + * // Send the string to the stream buffer. Return immediately if there is not + * // enough space in the buffer. + * xBytesSent = xStreamBufferSend( xStreamBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), 0 ); + * + * if( xBytesSent != strlen( pcStringToSend ) ) + * { + * // The entire string could not be added to the stream buffer because + * // there was not enough free space in the buffer, but xBytesSent bytes + * // were sent. Could try again to send the remaining bytes. + * } + * } + * @endcode + * \defgroup xStreamBufferSend xStreamBufferSend + * \ingroup StreamBufferManagement + */ +size_t xStreamBufferSend( StreamBufferHandle_t xStreamBuffer, + const void * pvTxData, + size_t xDataLengthBytes, + TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * + * @code{c} + * size_t xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer, + * const void *pvTxData, + * size_t xDataLengthBytes, + * BaseType_t *pxHigherPriorityTaskWoken ); + * @endcode + * + * Interrupt safe version of the API function that sends a stream of bytes to + * the stream buffer. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xStreamBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xStreamBufferReceive()) inside a critical section and set the receive + * block time to 0. + * + * Use xStreamBufferSend() to write to a stream buffer from a task. Use + * xStreamBufferSendFromISR() to write to a stream buffer from an interrupt + * service routine (ISR). + * + * @param xStreamBuffer The handle of the stream buffer to which a stream is + * being sent. + * + * @param pvTxData A pointer to the data that is to be copied into the stream + * buffer. + * + * @param xDataLengthBytes The maximum number of bytes to copy from pvTxData + * into the stream buffer. + * + * @param pxHigherPriorityTaskWoken It is possible that a stream buffer will + * have a task blocked on it waiting for data. Calling + * xStreamBufferSendFromISR() can make data available, and so cause a task that + * was waiting for data to leave the Blocked state. If calling + * xStreamBufferSendFromISR() causes a task to leave the Blocked state, and the + * unblocked task has a priority higher than the currently executing task (the + * task that was interrupted), then, internally, xStreamBufferSendFromISR() + * will set *pxHigherPriorityTaskWoken to pdTRUE. If + * xStreamBufferSendFromISR() sets this value to pdTRUE, then normally a + * context switch should be performed before the interrupt is exited. This will + * ensure that the interrupt returns directly to the highest priority Ready + * state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it + * is passed into the function. See the example code below for an example. + * + * @return The number of bytes actually written to the stream buffer, which will + * be less than xDataLengthBytes if the stream buffer didn't have enough free + * space for all the bytes to be written. + * + * Example use: + * @code{c} + * // A stream buffer that has already been created. + * StreamBufferHandle_t xStreamBuffer; + * + * void vAnInterruptServiceRoutine( void ) + * { + * size_t xBytesSent; + * char *pcStringToSend = "String to send"; + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE. + * + * // Attempt to send the string to the stream buffer. + * xBytesSent = xStreamBufferSendFromISR( xStreamBuffer, + * ( void * ) pcStringToSend, + * strlen( pcStringToSend ), + * &xHigherPriorityTaskWoken ); + * + * if( xBytesSent != strlen( pcStringToSend ) ) + * { + * // There was not enough free space in the stream buffer for the entire + * // string to be written, ut xBytesSent bytes were written. + * } + * + * // If xHigherPriorityTaskWoken was set to pdTRUE inside + * // xStreamBufferSendFromISR() then a task that has a priority above the + * // priority of the currently executing task was unblocked and a context + * // switch should be performed to ensure the ISR returns to the unblocked + * // task. In most FreeRTOS ports this is done by simply passing + * // xHigherPriorityTaskWoken into taskYIELD_FROM_ISR(), which will test the + * // variables value, and perform the context switch if necessary. Check the + * // documentation for the port in use for port specific instructions. + * taskYIELD_FROM_ISR( xHigherPriorityTaskWoken ); + * } + * @endcode + * \defgroup xStreamBufferSendFromISR xStreamBufferSendFromISR + * \ingroup StreamBufferManagement + */ +size_t xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer, + const void * pvTxData, + size_t xDataLengthBytes, + BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * + * @code{c} + * size_t xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer, + * void *pvRxData, + * size_t xBufferLengthBytes, + * TickType_t xTicksToWait ); + * @endcode + * + * Receives bytes from a stream buffer. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xStreamBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xStreamBufferReceive()) inside a critical section and set the receive + * block time to 0. + * + * Use xStreamBufferReceive() to read from a stream buffer from a task. Use + * xStreamBufferReceiveFromISR() to read from a stream buffer from an + * interrupt service routine (ISR). + * + * @param xStreamBuffer The handle of the stream buffer from which bytes are to + * be received. + * + * @param pvRxData A pointer to the buffer into which the received bytes will be + * copied. + * + * @param xBufferLengthBytes The length of the buffer pointed to by the + * pvRxData parameter. This sets the maximum number of bytes to receive in one + * call. xStreamBufferReceive will return as many bytes as possible up to a + * maximum set by xBufferLengthBytes. + * + * @param xTicksToWait The maximum amount of time the task should remain in the + * Blocked state to wait for data to become available if the stream buffer is + * empty. xStreamBufferReceive() will return immediately if xTicksToWait is + * zero. The block time is specified in tick periods, so the absolute time it + * represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can + * be used to convert a time specified in milliseconds into a time specified in + * ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait + * indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 + * in FreeRTOSConfig.h. A task does not use any CPU time when it is in the + * Blocked state. + * + * @return The number of bytes actually read from the stream buffer, which will + * be less than xBufferLengthBytes if the call to xStreamBufferReceive() timed + * out before xBufferLengthBytes were available. + * + * Example use: + * @code{c} + * void vAFunction( StreamBuffer_t xStreamBuffer ) + * { + * uint8_t ucRxData[ 20 ]; + * size_t xReceivedBytes; + * const TickType_t xBlockTime = pdMS_TO_TICKS( 20 ); + * + * // Receive up to another sizeof( ucRxData ) bytes from the stream buffer. + * // Wait in the Blocked state (so not using any CPU processing time) for a + * // maximum of 100ms for the full sizeof( ucRxData ) number of bytes to be + * // available. + * xReceivedBytes = xStreamBufferReceive( xStreamBuffer, + * ( void * ) ucRxData, + * sizeof( ucRxData ), + * xBlockTime ); + * + * if( xReceivedBytes > 0 ) + * { + * // A ucRxData contains another xRecievedBytes bytes of data, which can + * // be processed here.... + * } + * } + * @endcode + * \defgroup xStreamBufferReceive xStreamBufferReceive + * \ingroup StreamBufferManagement + */ +size_t xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer, + void * pvRxData, + size_t xBufferLengthBytes, + TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * + * @code{c} + * size_t xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer, + * void *pvRxData, + * size_t xBufferLengthBytes, + * BaseType_t *pxHigherPriorityTaskWoken ); + * @endcode + * + * An interrupt safe version of the API function that receives bytes from a + * stream buffer. + * + * Use xStreamBufferReceive() to read bytes from a stream buffer from a task. + * Use xStreamBufferReceiveFromISR() to read bytes from a stream buffer from an + * interrupt service routine (ISR). + * + * @param xStreamBuffer The handle of the stream buffer from which a stream + * is being received. + * + * @param pvRxData A pointer to the buffer into which the received bytes are + * copied. + * + * @param xBufferLengthBytes The length of the buffer pointed to by the + * pvRxData parameter. This sets the maximum number of bytes to receive in one + * call. xStreamBufferReceive will return as many bytes as possible up to a + * maximum set by xBufferLengthBytes. + * + * @param pxHigherPriorityTaskWoken It is possible that a stream buffer will + * have a task blocked on it waiting for space to become available. Calling + * xStreamBufferReceiveFromISR() can make space available, and so cause a task + * that is waiting for space to leave the Blocked state. If calling + * xStreamBufferReceiveFromISR() causes a task to leave the Blocked state, and + * the unblocked task has a priority higher than the currently executing task + * (the task that was interrupted), then, internally, + * xStreamBufferReceiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. + * If xStreamBufferReceiveFromISR() sets this value to pdTRUE, then normally a + * context switch should be performed before the interrupt is exited. That will + * ensure the interrupt returns directly to the highest priority Ready state + * task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is + * passed into the function. See the code example below for an example. + * + * @return The number of bytes read from the stream buffer, if any. + * + * Example use: + * @code{c} + * // A stream buffer that has already been created. + * StreamBuffer_t xStreamBuffer; + * + * void vAnInterruptServiceRoutine( void ) + * { + * uint8_t ucRxData[ 20 ]; + * size_t xReceivedBytes; + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE. + * + * // Receive the next stream from the stream buffer. + * xReceivedBytes = xStreamBufferReceiveFromISR( xStreamBuffer, + * ( void * ) ucRxData, + * sizeof( ucRxData ), + * &xHigherPriorityTaskWoken ); + * + * if( xReceivedBytes > 0 ) + * { + * // ucRxData contains xReceivedBytes read from the stream buffer. + * // Process the stream here.... + * } + * + * // If xHigherPriorityTaskWoken was set to pdTRUE inside + * // xStreamBufferReceiveFromISR() then a task that has a priority above the + * // priority of the currently executing task was unblocked and a context + * // switch should be performed to ensure the ISR returns to the unblocked + * // task. In most FreeRTOS ports this is done by simply passing + * // xHigherPriorityTaskWoken into taskYIELD_FROM_ISR(), which will test the + * // variables value, and perform the context switch if necessary. Check the + * // documentation for the port in use for port specific instructions. + * taskYIELD_FROM_ISR( xHigherPriorityTaskWoken ); + * } + * @endcode + * \defgroup xStreamBufferReceiveFromISR xStreamBufferReceiveFromISR + * \ingroup StreamBufferManagement + */ +size_t xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer, + void * pvRxData, + size_t xBufferLengthBytes, + BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * + * @code{c} + * void vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer ); + * @endcode + * + * Deletes a stream buffer that was previously created using a call to + * xStreamBufferCreate() or xStreamBufferCreateStatic(). If the stream + * buffer was created using dynamic memory (that is, by xStreamBufferCreate()), + * then the allocated memory is freed. + * + * A stream buffer handle must not be used after the stream buffer has been + * deleted. + * + * @param xStreamBuffer The handle of the stream buffer to be deleted. + * + * \defgroup vStreamBufferDelete vStreamBufferDelete + * \ingroup StreamBufferManagement + */ +void vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * + * @code{c} + * BaseType_t xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer ); + * @endcode + * + * Queries a stream buffer to see if it is full. A stream buffer is full if it + * does not have any free space, and therefore cannot accept any more data. + * + * @param xStreamBuffer The handle of the stream buffer being queried. + * + * @return If the stream buffer is full then pdTRUE is returned. Otherwise + * pdFALSE is returned. + * + * \defgroup xStreamBufferIsFull xStreamBufferIsFull + * \ingroup StreamBufferManagement + */ +BaseType_t xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * + * @code{c} + * BaseType_t xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer ); + * @endcode + * + * Queries a stream buffer to see if it is empty. A stream buffer is empty if + * it does not contain any data. + * + * @param xStreamBuffer The handle of the stream buffer being queried. + * + * @return If the stream buffer is empty then pdTRUE is returned. Otherwise + * pdFALSE is returned. + * + * \defgroup xStreamBufferIsEmpty xStreamBufferIsEmpty + * \ingroup StreamBufferManagement + */ +BaseType_t xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * + * @code{c} + * BaseType_t xStreamBufferReset( StreamBufferHandle_t xStreamBuffer ); + * @endcode + * + * Resets a stream buffer to its initial, empty, state. Any data that was in + * the stream buffer is discarded. A stream buffer can only be reset if there + * are no tasks blocked waiting to either send to or receive from the stream + * buffer. + * + * @param xStreamBuffer The handle of the stream buffer being reset. + * + * @return If the stream buffer is reset then pdPASS is returned. If there was + * a task blocked waiting to send to or read from the stream buffer then the + * stream buffer is not reset and pdFAIL is returned. + * + * \defgroup xStreamBufferReset xStreamBufferReset + * \ingroup StreamBufferManagement + */ +BaseType_t xStreamBufferReset( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * + * @code{c} + * size_t xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer ); + * @endcode + * + * Queries a stream buffer to see how much free space it contains, which is + * equal to the amount of data that can be sent to the stream buffer before it + * is full. + * + * @param xStreamBuffer The handle of the stream buffer being queried. + * + * @return The number of bytes that can be written to the stream buffer before + * the stream buffer would be full. + * + * \defgroup xStreamBufferSpacesAvailable xStreamBufferSpacesAvailable + * \ingroup StreamBufferManagement + */ +size_t xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * + * @code{c} + * size_t xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer ); + * @endcode + * + * Queries a stream buffer to see how much data it contains, which is equal to + * the number of bytes that can be read from the stream buffer before the stream + * buffer would be empty. + * + * @param xStreamBuffer The handle of the stream buffer being queried. + * + * @return The number of bytes that can be read from the stream buffer before + * the stream buffer would be empty. + * + * \defgroup xStreamBufferBytesAvailable xStreamBufferBytesAvailable + * \ingroup StreamBufferManagement + */ +size_t xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * + * @code{c} + * BaseType_t xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, size_t xTriggerLevel ); + * @endcode + * + * A stream buffer's trigger level is the number of bytes that must be in the + * stream buffer before a task that is blocked on the stream buffer to + * wait for data is moved out of the blocked state. For example, if a task is + * blocked on a read of an empty stream buffer that has a trigger level of 1 + * then the task will be unblocked when a single byte is written to the buffer + * or the task's block time expires. As another example, if a task is blocked + * on a read of an empty stream buffer that has a trigger level of 10 then the + * task will not be unblocked until the stream buffer contains at least 10 bytes + * or the task's block time expires. If a reading task's block time expires + * before the trigger level is reached then the task will still receive however + * many bytes are actually available. Setting a trigger level of 0 will result + * in a trigger level of 1 being used. It is not valid to specify a trigger + * level that is greater than the buffer size. + * + * A trigger level is set when the stream buffer is created, and can be modified + * using xStreamBufferSetTriggerLevel(). + * + * @param xStreamBuffer The handle of the stream buffer being updated. + * + * @param xTriggerLevel The new trigger level for the stream buffer. + * + * @return If xTriggerLevel was less than or equal to the stream buffer's length + * then the trigger level will be updated and pdTRUE is returned. Otherwise + * pdFALSE is returned. + * + * \defgroup xStreamBufferSetTriggerLevel xStreamBufferSetTriggerLevel + * \ingroup StreamBufferManagement + */ +BaseType_t xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, + size_t xTriggerLevel ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * + * @code{c} + * BaseType_t xStreamBufferSendCompletedFromISR( StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken ); + * @endcode + * + * For advanced users only. + * + * The sbSEND_COMPLETED() macro is called from within the FreeRTOS APIs when + * data is sent to a message buffer or stream buffer. If there was a task that + * was blocked on the message or stream buffer waiting for data to arrive then + * the sbSEND_COMPLETED() macro sends a notification to the task to remove it + * from the Blocked state. xStreamBufferSendCompletedFromISR() does the same + * thing. It is provided to enable application writers to implement their own + * version of sbSEND_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME. + * + * See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for + * additional information. + * + * @param xStreamBuffer The handle of the stream buffer to which data was + * written. + * + * @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be + * initialised to pdFALSE before it is passed into + * xStreamBufferSendCompletedFromISR(). If calling + * xStreamBufferSendCompletedFromISR() removes a task from the Blocked state, + * and the task has a priority above the priority of the currently running task, + * then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a + * context switch should be performed before exiting the ISR. + * + * @return If a task was removed from the Blocked state then pdTRUE is returned. + * Otherwise pdFALSE is returned. + * + * \defgroup xStreamBufferSendCompletedFromISR xStreamBufferSendCompletedFromISR + * \ingroup StreamBufferManagement + */ +BaseType_t xStreamBufferSendCompletedFromISR( StreamBufferHandle_t xStreamBuffer, + BaseType_t * pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * + * @code{c} + * BaseType_t xStreamBufferReceiveCompletedFromISR( StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken ); + * @endcode + * + * For advanced users only. + * + * The sbRECEIVE_COMPLETED() macro is called from within the FreeRTOS APIs when + * data is read out of a message buffer or stream buffer. If there was a task + * that was blocked on the message or stream buffer waiting for data to arrive + * then the sbRECEIVE_COMPLETED() macro sends a notification to the task to + * remove it from the Blocked state. xStreamBufferReceiveCompletedFromISR() + * does the same thing. It is provided to enable application writers to + * implement their own version of sbRECEIVE_COMPLETED(), and MUST NOT BE USED AT + * ANY OTHER TIME. + * + * See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for + * additional information. + * + * @param xStreamBuffer The handle of the stream buffer from which data was + * read. + * + * @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be + * initialised to pdFALSE before it is passed into + * xStreamBufferReceiveCompletedFromISR(). If calling + * xStreamBufferReceiveCompletedFromISR() removes a task from the Blocked state, + * and the task has a priority above the priority of the currently running task, + * then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a + * context switch should be performed before exiting the ISR. + * + * @return If a task was removed from the Blocked state then pdTRUE is returned. + * Otherwise pdFALSE is returned. + * + * \defgroup xStreamBufferReceiveCompletedFromISR xStreamBufferReceiveCompletedFromISR + * \ingroup StreamBufferManagement + */ +BaseType_t xStreamBufferReceiveCompletedFromISR( StreamBufferHandle_t xStreamBuffer, + BaseType_t * pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + +/* Functions below here are not part of the public API. */ +StreamBufferHandle_t xStreamBufferGenericCreate( size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + BaseType_t xIsMessageBuffer ) PRIVILEGED_FUNCTION; + +StreamBufferHandle_t xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + BaseType_t xIsMessageBuffer, + uint8_t * const pucStreamBufferStorageArea, + StaticStreamBuffer_t * const pxStaticStreamBuffer ) PRIVILEGED_FUNCTION; + +size_t xStreamBufferNextMessageLengthBytes( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +#if ( configUSE_TRACE_FACILITY == 1 ) + void vStreamBufferSetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer, + UBaseType_t uxStreamBufferNumber ) PRIVILEGED_FUNCTION; + UBaseType_t uxStreamBufferGetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + uint8_t ucStreamBufferGetStreamBufferType( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; +#endif + +/* *INDENT-OFF* */ +#if defined( __cplusplus ) + } +#endif +/* *INDENT-ON* */ + +#endif /* !defined( STREAM_BUFFER_H ) */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/task.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/task.h new file mode 100644 index 0000000..ec80cd9 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/task.h @@ -0,0 +1,3112 @@ +/* + * FreeRTOS Kernel V10.4.6 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + + +#ifndef INC_TASK_H +#define INC_TASK_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h must appear in source files before include task.h" +#endif + +#include "list.h" + +/* *INDENT-OFF* */ +#ifdef __cplusplus + extern "C" { +#endif +/* *INDENT-ON* */ + +/*----------------------------------------------------------- +* MACROS AND DEFINITIONS +*----------------------------------------------------------*/ + +/* + * If tskKERNEL_VERSION_NUMBER ends with + it represents the version in development + * after the numbered release. + * + * The tskKERNEL_VERSION_MAJOR, tskKERNEL_VERSION_MINOR, tskKERNEL_VERSION_BUILD + * values will reflect the last released version number. + */ +#define tskKERNEL_VERSION_NUMBER "V10.4.6" +#define tskKERNEL_VERSION_MAJOR 10 +#define tskKERNEL_VERSION_MINOR 4 +#define tskKERNEL_VERSION_BUILD 6 + +/* MPU region parameters passed in ulParameters + * of MemoryRegion_t struct. */ +#define tskMPU_REGION_READ_ONLY ( 1UL << 0UL ) +#define tskMPU_REGION_READ_WRITE ( 1UL << 1UL ) +#define tskMPU_REGION_EXECUTE_NEVER ( 1UL << 2UL ) +#define tskMPU_REGION_NORMAL_MEMORY ( 1UL << 3UL ) +#define tskMPU_REGION_DEVICE_MEMORY ( 1UL << 4UL ) + +/* The direct to task notification feature used to have only a single notification + * per task. Now there is an array of notifications per task that is dimensioned by + * configTASK_NOTIFICATION_ARRAY_ENTRIES. For backward compatibility, any use of the + * original direct to task notification defaults to using the first index in the + * array. */ +#define tskDEFAULT_INDEX_TO_NOTIFY ( 0 ) + +/** + * task. h + * + * Type by which tasks are referenced. For example, a call to xTaskCreate + * returns (via a pointer parameter) an TaskHandle_t variable that can then + * be used as a parameter to vTaskDelete to delete the task. + * + * \defgroup TaskHandle_t TaskHandle_t + * \ingroup Tasks + */ +struct tskTaskControlBlock; /* The old naming convention is used to prevent breaking kernel aware debuggers. */ +typedef struct tskTaskControlBlock * TaskHandle_t; + +/* + * Defines the prototype to which the application task hook function must + * conform. + */ +typedef BaseType_t (* TaskHookFunction_t)( void * ); + +/* Task states returned by eTaskGetState. */ +typedef enum +{ + eRunning = 0, /* A task is querying the state of itself, so must be running. */ + eReady, /* The task being queried is in a ready or pending ready list. */ + eBlocked, /* The task being queried is in the Blocked state. */ + eSuspended, /* The task being queried is in the Suspended state, or is in the Blocked state with an infinite time out. */ + eDeleted, /* The task being queried has been deleted, but its TCB has not yet been freed. */ + eInvalid /* Used as an 'invalid state' value. */ +} eTaskState; + +/* Actions that can be performed when vTaskNotify() is called. */ +typedef enum +{ + eNoAction = 0, /* Notify the task without updating its notify value. */ + eSetBits, /* Set bits in the task's notification value. */ + eIncrement, /* Increment the task's notification value. */ + eSetValueWithOverwrite, /* Set the task's notification value to a specific value even if the previous value has not yet been read by the task. */ + eSetValueWithoutOverwrite /* Set the task's notification value if the previous value has been read by the task. */ +} eNotifyAction; + +/* + * Used internally only. + */ +typedef struct xTIME_OUT +{ + BaseType_t xOverflowCount; + TickType_t xTimeOnEntering; +} TimeOut_t; + +/* + * Defines the memory ranges allocated to the task when an MPU is used. + */ +typedef struct xMEMORY_REGION +{ + void * pvBaseAddress; + uint32_t ulLengthInBytes; + uint32_t ulParameters; +} MemoryRegion_t; + +/* + * Parameters required to create an MPU protected task. + */ +typedef struct xTASK_PARAMETERS +{ + TaskFunction_t pvTaskCode; + const char * pcName; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + configSTACK_DEPTH_TYPE usStackDepth; + void * pvParameters; + UBaseType_t uxPriority; + StackType_t * puxStackBuffer; + MemoryRegion_t xRegions[ portNUM_CONFIGURABLE_REGIONS ]; + #if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + StaticTask_t * const pxTaskBuffer; + #endif +} TaskParameters_t; + +/* Used with the uxTaskGetSystemState() function to return the state of each task + * in the system. */ +typedef struct xTASK_STATUS +{ + TaskHandle_t xHandle; /* The handle of the task to which the rest of the information in the structure relates. */ + const char * pcTaskName; /* A pointer to the task's name. This value will be invalid if the task was deleted since the structure was populated! */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + UBaseType_t xTaskNumber; /* A number unique to the task. */ + eTaskState eCurrentState; /* The state in which the task existed when the structure was populated. */ + UBaseType_t uxCurrentPriority; /* The priority at which the task was running (may be inherited) when the structure was populated. */ + UBaseType_t uxBasePriority; /* The priority to which the task will return if the task's current priority has been inherited to avoid unbounded priority inversion when obtaining a mutex. Only valid if configUSE_MUTEXES is defined as 1 in FreeRTOSConfig.h. */ + configRUN_TIME_COUNTER_TYPE ulRunTimeCounter; /* The total run time allocated to the task so far, as defined by the run time stats clock. See https://www.FreeRTOS.org/rtos-run-time-stats.html. Only valid when configGENERATE_RUN_TIME_STATS is defined as 1 in FreeRTOSConfig.h. */ + StackType_t * pxStackBase; /* Points to the lowest address of the task's stack area. */ + configSTACK_DEPTH_TYPE usStackHighWaterMark; /* The minimum amount of stack space that has remained for the task since the task was created. The closer this value is to zero the closer the task has come to overflowing its stack. */ +} TaskStatus_t; + +/* Possible return values for eTaskConfirmSleepModeStatus(). */ +typedef enum +{ + eAbortSleep = 0, /* A task has been made ready or a context switch pended since portSUPPRESS_TICKS_AND_SLEEP() was called - abort entering a sleep mode. */ + eStandardSleep, /* Enter a sleep mode that will not last any longer than the expected idle time. */ + eNoTasksWaitingTimeout /* No tasks are waiting for a timeout so it is safe to enter a sleep mode that can only be exited by an external interrupt. */ +} eSleepModeStatus; + +/** + * Defines the priority used by the idle task. This must not be modified. + * + * \ingroup TaskUtils + */ +#define tskIDLE_PRIORITY ( ( UBaseType_t ) 0U ) + +/** + * task. h + * + * Macro for forcing a context switch. + * + * \defgroup taskYIELD taskYIELD + * \ingroup SchedulerControl + */ +#define taskYIELD() portYIELD() + +/** + * task. h + * + * Macro to mark the start of a critical code region. Preemptive context + * switches cannot occur when in a critical region. + * + * NOTE: This may alter the stack (depending on the portable implementation) + * so must be used with care! + * + * \defgroup taskENTER_CRITICAL taskENTER_CRITICAL + * \ingroup SchedulerControl + */ +#define taskENTER_CRITICAL() portENTER_CRITICAL() +#define taskENTER_CRITICAL_FROM_ISR() portSET_INTERRUPT_MASK_FROM_ISR() + +/** + * task. h + * + * Macro to mark the end of a critical code region. Preemptive context + * switches cannot occur when in a critical region. + * + * NOTE: This may alter the stack (depending on the portable implementation) + * so must be used with care! + * + * \defgroup taskEXIT_CRITICAL taskEXIT_CRITICAL + * \ingroup SchedulerControl + */ +#define taskEXIT_CRITICAL() portEXIT_CRITICAL() +#define taskEXIT_CRITICAL_FROM_ISR( x ) portCLEAR_INTERRUPT_MASK_FROM_ISR( x ) + +/** + * task. h + * + * Macro to disable all maskable interrupts. + * + * \defgroup taskDISABLE_INTERRUPTS taskDISABLE_INTERRUPTS + * \ingroup SchedulerControl + */ +#define taskDISABLE_INTERRUPTS() portDISABLE_INTERRUPTS() + +/** + * task. h + * + * Macro to enable microcontroller interrupts. + * + * \defgroup taskENABLE_INTERRUPTS taskENABLE_INTERRUPTS + * \ingroup SchedulerControl + */ +#define taskENABLE_INTERRUPTS() portENABLE_INTERRUPTS() + +/* Definitions returned by xTaskGetSchedulerState(). taskSCHEDULER_SUSPENDED is + * 0 to generate more optimal code when configASSERT() is defined as the constant + * is used in assert() statements. */ +#define taskSCHEDULER_SUSPENDED ( ( BaseType_t ) 0 ) +#define taskSCHEDULER_NOT_STARTED ( ( BaseType_t ) 1 ) +#define taskSCHEDULER_RUNNING ( ( BaseType_t ) 2 ) + + +/*----------------------------------------------------------- +* TASK CREATION API +*----------------------------------------------------------*/ + +/** + * task. h + * @code{c} + * BaseType_t xTaskCreate( + * TaskFunction_t pxTaskCode, + * const char *pcName, + * configSTACK_DEPTH_TYPE usStackDepth, + * void *pvParameters, + * UBaseType_t uxPriority, + * TaskHandle_t *pxCreatedTask + * ); + * @endcode + * + * Create a new task and add it to the list of tasks that are ready to run. + * + * Internally, within the FreeRTOS implementation, tasks use two blocks of + * memory. The first block is used to hold the task's data structures. The + * second block is used by the task as its stack. If a task is created using + * xTaskCreate() then both blocks of memory are automatically dynamically + * allocated inside the xTaskCreate() function. (see + * https://www.FreeRTOS.org/a00111.html). If a task is created using + * xTaskCreateStatic() then the application writer must provide the required + * memory. xTaskCreateStatic() therefore allows a task to be created without + * using any dynamic memory allocation. + * + * See xTaskCreateStatic() for a version that does not use any dynamic memory + * allocation. + * + * xTaskCreate() can only be used to create a task that has unrestricted + * access to the entire microcontroller memory map. Systems that include MPU + * support can alternatively create an MPU constrained task using + * xTaskCreateRestricted(). + * + * @param pxTaskCode Pointer to the task entry function. Tasks + * must be implemented to never return (i.e. continuous loop). + * + * @param pcName A descriptive name for the task. This is mainly used to + * facilitate debugging. Max length defined by configMAX_TASK_NAME_LEN - default + * is 16. + * + * @param usStackDepth The size of the task stack specified as the number of + * variables the stack can hold - not the number of bytes. For example, if + * the stack is 16 bits wide and usStackDepth is defined as 100, 200 bytes + * will be allocated for stack storage. + * + * @param pvParameters Pointer that will be used as the parameter for the task + * being created. + * + * @param uxPriority The priority at which the task should run. Systems that + * include MPU support can optionally create tasks in a privileged (system) + * mode by setting bit portPRIVILEGE_BIT of the priority parameter. For + * example, to create a privileged task at priority 2 the uxPriority parameter + * should be set to ( 2 | portPRIVILEGE_BIT ). + * + * @param pxCreatedTask Used to pass back a handle by which the created task + * can be referenced. + * + * @return pdPASS if the task was successfully created and added to a ready + * list, otherwise an error code defined in the file projdefs.h + * + * Example usage: + * @code{c} + * // Task to be created. + * void vTaskCode( void * pvParameters ) + * { + * for( ;; ) + * { + * // Task code goes here. + * } + * } + * + * // Function that creates a task. + * void vOtherFunction( void ) + * { + * static uint8_t ucParameterToPass; + * TaskHandle_t xHandle = NULL; + * + * // Create the task, storing the handle. Note that the passed parameter ucParameterToPass + * // must exist for the lifetime of the task, so in this case is declared static. If it was just an + * // an automatic stack variable it might no longer exist, or at least have been corrupted, by the time + * // the new task attempts to access it. + * xTaskCreate( vTaskCode, "NAME", STACK_SIZE, &ucParameterToPass, tskIDLE_PRIORITY, &xHandle ); + * configASSERT( xHandle ); + * + * // Use the handle to delete the task. + * if( xHandle != NULL ) + * { + * vTaskDelete( xHandle ); + * } + * } + * @endcode + * \defgroup xTaskCreate xTaskCreate + * \ingroup Tasks + */ +#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + BaseType_t xTaskCreate( TaskFunction_t pxTaskCode, + const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const configSTACK_DEPTH_TYPE usStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask ) PRIVILEGED_FUNCTION; +#endif + +/** + * task. h + * @code{c} + * TaskHandle_t xTaskCreateStatic( TaskFunction_t pxTaskCode, + * const char *pcName, + * uint32_t ulStackDepth, + * void *pvParameters, + * UBaseType_t uxPriority, + * StackType_t *puxStackBuffer, + * StaticTask_t *pxTaskBuffer ); + * @endcode + * + * Create a new task and add it to the list of tasks that are ready to run. + * + * Internally, within the FreeRTOS implementation, tasks use two blocks of + * memory. The first block is used to hold the task's data structures. The + * second block is used by the task as its stack. If a task is created using + * xTaskCreate() then both blocks of memory are automatically dynamically + * allocated inside the xTaskCreate() function. (see + * https://www.FreeRTOS.org/a00111.html). If a task is created using + * xTaskCreateStatic() then the application writer must provide the required + * memory. xTaskCreateStatic() therefore allows a task to be created without + * using any dynamic memory allocation. + * + * @param pxTaskCode Pointer to the task entry function. Tasks + * must be implemented to never return (i.e. continuous loop). + * + * @param pcName A descriptive name for the task. This is mainly used to + * facilitate debugging. The maximum length of the string is defined by + * configMAX_TASK_NAME_LEN in FreeRTOSConfig.h. + * + * @param ulStackDepth The size of the task stack specified as the number of + * variables the stack can hold - not the number of bytes. For example, if + * the stack is 32-bits wide and ulStackDepth is defined as 100 then 400 bytes + * will be allocated for stack storage. + * + * @param pvParameters Pointer that will be used as the parameter for the task + * being created. + * + * @param uxPriority The priority at which the task will run. + * + * @param puxStackBuffer Must point to a StackType_t array that has at least + * ulStackDepth indexes - the array will then be used as the task's stack, + * removing the need for the stack to be allocated dynamically. + * + * @param pxTaskBuffer Must point to a variable of type StaticTask_t, which will + * then be used to hold the task's data structures, removing the need for the + * memory to be allocated dynamically. + * + * @return If neither puxStackBuffer nor pxTaskBuffer are NULL, then the task + * will be created and a handle to the created task is returned. If either + * puxStackBuffer or pxTaskBuffer are NULL then the task will not be created and + * NULL is returned. + * + * Example usage: + * @code{c} + * + * // Dimensions of the buffer that the task being created will use as its stack. + * // NOTE: This is the number of words the stack will hold, not the number of + * // bytes. For example, if each stack item is 32-bits, and this is set to 100, + * // then 400 bytes (100 * 32-bits) will be allocated. + #define STACK_SIZE 200 + * + * // Structure that will hold the TCB of the task being created. + * StaticTask_t xTaskBuffer; + * + * // Buffer that the task being created will use as its stack. Note this is + * // an array of StackType_t variables. The size of StackType_t is dependent on + * // the RTOS port. + * StackType_t xStack[ STACK_SIZE ]; + * + * // Function that implements the task being created. + * void vTaskCode( void * pvParameters ) + * { + * // The parameter value is expected to be 1 as 1 is passed in the + * // pvParameters value in the call to xTaskCreateStatic(). + * configASSERT( ( uint32_t ) pvParameters == 1UL ); + * + * for( ;; ) + * { + * // Task code goes here. + * } + * } + * + * // Function that creates a task. + * void vOtherFunction( void ) + * { + * TaskHandle_t xHandle = NULL; + * + * // Create the task without using any dynamic memory allocation. + * xHandle = xTaskCreateStatic( + * vTaskCode, // Function that implements the task. + * "NAME", // Text name for the task. + * STACK_SIZE, // Stack size in words, not bytes. + * ( void * ) 1, // Parameter passed into the task. + * tskIDLE_PRIORITY,// Priority at which the task is created. + * xStack, // Array to use as the task's stack. + * &xTaskBuffer ); // Variable to hold the task's data structure. + * + * // puxStackBuffer and pxTaskBuffer were not NULL, so the task will have + * // been created, and xHandle will be the task's handle. Use the handle + * // to suspend the task. + * vTaskSuspend( xHandle ); + * } + * @endcode + * \defgroup xTaskCreateStatic xTaskCreateStatic + * \ingroup Tasks + */ +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + TaskHandle_t xTaskCreateStatic( TaskFunction_t pxTaskCode, + const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const uint32_t ulStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + StackType_t * const puxStackBuffer, + StaticTask_t * const pxTaskBuffer ) PRIVILEGED_FUNCTION; +#endif /* configSUPPORT_STATIC_ALLOCATION */ + +/** + * task. h + * @code{c} + * BaseType_t xTaskCreateRestricted( TaskParameters_t *pxTaskDefinition, TaskHandle_t *pxCreatedTask ); + * @endcode + * + * Only available when configSUPPORT_DYNAMIC_ALLOCATION is set to 1. + * + * xTaskCreateRestricted() should only be used in systems that include an MPU + * implementation. + * + * Create a new task and add it to the list of tasks that are ready to run. + * The function parameters define the memory regions and associated access + * permissions allocated to the task. + * + * See xTaskCreateRestrictedStatic() for a version that does not use any + * dynamic memory allocation. + * + * @param pxTaskDefinition Pointer to a structure that contains a member + * for each of the normal xTaskCreate() parameters (see the xTaskCreate() API + * documentation) plus an optional stack buffer and the memory region + * definitions. + * + * @param pxCreatedTask Used to pass back a handle by which the created task + * can be referenced. + * + * @return pdPASS if the task was successfully created and added to a ready + * list, otherwise an error code defined in the file projdefs.h + * + * Example usage: + * @code{c} + * // Create an TaskParameters_t structure that defines the task to be created. + * static const TaskParameters_t xCheckTaskParameters = + * { + * vATask, // pvTaskCode - the function that implements the task. + * "ATask", // pcName - just a text name for the task to assist debugging. + * 100, // usStackDepth - the stack size DEFINED IN WORDS. + * NULL, // pvParameters - passed into the task function as the function parameters. + * ( 1UL | portPRIVILEGE_BIT ),// uxPriority - task priority, set the portPRIVILEGE_BIT if the task should run in a privileged state. + * cStackBuffer,// puxStackBuffer - the buffer to be used as the task stack. + * + * // xRegions - Allocate up to three separate memory regions for access by + * // the task, with appropriate access permissions. Different processors have + * // different memory alignment requirements - refer to the FreeRTOS documentation + * // for full information. + * { + * // Base address Length Parameters + * { cReadWriteArray, 32, portMPU_REGION_READ_WRITE }, + * { cReadOnlyArray, 32, portMPU_REGION_READ_ONLY }, + * { cPrivilegedOnlyAccessArray, 128, portMPU_REGION_PRIVILEGED_READ_WRITE } + * } + * }; + * + * int main( void ) + * { + * TaskHandle_t xHandle; + * + * // Create a task from the const structure defined above. The task handle + * // is requested (the second parameter is not NULL) but in this case just for + * // demonstration purposes as its not actually used. + * xTaskCreateRestricted( &xRegTest1Parameters, &xHandle ); + * + * // Start the scheduler. + * vTaskStartScheduler(); + * + * // Will only get here if there was insufficient memory to create the idle + * // and/or timer task. + * for( ;; ); + * } + * @endcode + * \defgroup xTaskCreateRestricted xTaskCreateRestricted + * \ingroup Tasks + */ +#if ( portUSING_MPU_WRAPPERS == 1 ) + BaseType_t xTaskCreateRestricted( const TaskParameters_t * const pxTaskDefinition, + TaskHandle_t * pxCreatedTask ) PRIVILEGED_FUNCTION; +#endif + +/** + * task. h + * @code{c} + * BaseType_t xTaskCreateRestrictedStatic( TaskParameters_t *pxTaskDefinition, TaskHandle_t *pxCreatedTask ); + * @endcode + * + * Only available when configSUPPORT_STATIC_ALLOCATION is set to 1. + * + * xTaskCreateRestrictedStatic() should only be used in systems that include an + * MPU implementation. + * + * Internally, within the FreeRTOS implementation, tasks use two blocks of + * memory. The first block is used to hold the task's data structures. The + * second block is used by the task as its stack. If a task is created using + * xTaskCreateRestricted() then the stack is provided by the application writer, + * and the memory used to hold the task's data structure is automatically + * dynamically allocated inside the xTaskCreateRestricted() function. If a task + * is created using xTaskCreateRestrictedStatic() then the application writer + * must provide the memory used to hold the task's data structures too. + * xTaskCreateRestrictedStatic() therefore allows a memory protected task to be + * created without using any dynamic memory allocation. + * + * @param pxTaskDefinition Pointer to a structure that contains a member + * for each of the normal xTaskCreate() parameters (see the xTaskCreate() API + * documentation) plus an optional stack buffer and the memory region + * definitions. If configSUPPORT_STATIC_ALLOCATION is set to 1 the structure + * contains an additional member, which is used to point to a variable of type + * StaticTask_t - which is then used to hold the task's data structure. + * + * @param pxCreatedTask Used to pass back a handle by which the created task + * can be referenced. + * + * @return pdPASS if the task was successfully created and added to a ready + * list, otherwise an error code defined in the file projdefs.h + * + * Example usage: + * @code{c} + * // Create an TaskParameters_t structure that defines the task to be created. + * // The StaticTask_t variable is only included in the structure when + * // configSUPPORT_STATIC_ALLOCATION is set to 1. The PRIVILEGED_DATA macro can + * // be used to force the variable into the RTOS kernel's privileged data area. + * static PRIVILEGED_DATA StaticTask_t xTaskBuffer; + * static const TaskParameters_t xCheckTaskParameters = + * { + * vATask, // pvTaskCode - the function that implements the task. + * "ATask", // pcName - just a text name for the task to assist debugging. + * 100, // usStackDepth - the stack size DEFINED IN WORDS. + * NULL, // pvParameters - passed into the task function as the function parameters. + * ( 1UL | portPRIVILEGE_BIT ),// uxPriority - task priority, set the portPRIVILEGE_BIT if the task should run in a privileged state. + * cStackBuffer,// puxStackBuffer - the buffer to be used as the task stack. + * + * // xRegions - Allocate up to three separate memory regions for access by + * // the task, with appropriate access permissions. Different processors have + * // different memory alignment requirements - refer to the FreeRTOS documentation + * // for full information. + * { + * // Base address Length Parameters + * { cReadWriteArray, 32, portMPU_REGION_READ_WRITE }, + * { cReadOnlyArray, 32, portMPU_REGION_READ_ONLY }, + * { cPrivilegedOnlyAccessArray, 128, portMPU_REGION_PRIVILEGED_READ_WRITE } + * } + * + * &xTaskBuffer; // Holds the task's data structure. + * }; + * + * int main( void ) + * { + * TaskHandle_t xHandle; + * + * // Create a task from the const structure defined above. The task handle + * // is requested (the second parameter is not NULL) but in this case just for + * // demonstration purposes as its not actually used. + * xTaskCreateRestricted( &xRegTest1Parameters, &xHandle ); + * + * // Start the scheduler. + * vTaskStartScheduler(); + * + * // Will only get here if there was insufficient memory to create the idle + * // and/or timer task. + * for( ;; ); + * } + * @endcode + * \defgroup xTaskCreateRestrictedStatic xTaskCreateRestrictedStatic + * \ingroup Tasks + */ +#if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + BaseType_t xTaskCreateRestrictedStatic( const TaskParameters_t * const pxTaskDefinition, + TaskHandle_t * pxCreatedTask ) PRIVILEGED_FUNCTION; +#endif + +/** + * task. h + * @code{c} + * void vTaskAllocateMPURegions( TaskHandle_t xTask, const MemoryRegion_t * const pxRegions ); + * @endcode + * + * Memory regions are assigned to a restricted task when the task is created by + * a call to xTaskCreateRestricted(). These regions can be redefined using + * vTaskAllocateMPURegions(). + * + * @param xTask The handle of the task being updated. + * + * @param xRegions A pointer to a MemoryRegion_t structure that contains the + * new memory region definitions. + * + * Example usage: + * @code{c} + * // Define an array of MemoryRegion_t structures that configures an MPU region + * // allowing read/write access for 1024 bytes starting at the beginning of the + * // ucOneKByte array. The other two of the maximum 3 definable regions are + * // unused so set to zero. + * static const MemoryRegion_t xAltRegions[ portNUM_CONFIGURABLE_REGIONS ] = + * { + * // Base address Length Parameters + * { ucOneKByte, 1024, portMPU_REGION_READ_WRITE }, + * { 0, 0, 0 }, + * { 0, 0, 0 } + * }; + * + * void vATask( void *pvParameters ) + * { + * // This task was created such that it has access to certain regions of + * // memory as defined by the MPU configuration. At some point it is + * // desired that these MPU regions are replaced with that defined in the + * // xAltRegions const struct above. Use a call to vTaskAllocateMPURegions() + * // for this purpose. NULL is used as the task handle to indicate that this + * // function should modify the MPU regions of the calling task. + * vTaskAllocateMPURegions( NULL, xAltRegions ); + * + * // Now the task can continue its function, but from this point on can only + * // access its stack and the ucOneKByte array (unless any other statically + * // defined or shared regions have been declared elsewhere). + * } + * @endcode + * \defgroup xTaskCreateRestricted xTaskCreateRestricted + * \ingroup Tasks + */ +void vTaskAllocateMPURegions( TaskHandle_t xTask, + const MemoryRegion_t * const pxRegions ) PRIVILEGED_FUNCTION; + +/** + * task. h + * @code{c} + * void vTaskDelete( TaskHandle_t xTaskToDelete ); + * @endcode + * + * INCLUDE_vTaskDelete must be defined as 1 for this function to be available. + * See the configuration section for more information. + * + * Remove a task from the RTOS real time kernel's management. The task being + * deleted will be removed from all ready, blocked, suspended and event lists. + * + * NOTE: The idle task is responsible for freeing the kernel allocated + * memory from tasks that have been deleted. It is therefore important that + * the idle task is not starved of microcontroller processing time if your + * application makes any calls to vTaskDelete (). Memory allocated by the + * task code is not automatically freed, and should be freed before the task + * is deleted. + * + * See the demo application file death.c for sample code that utilises + * vTaskDelete (). + * + * @param xTaskToDelete The handle of the task to be deleted. Passing NULL will + * cause the calling task to be deleted. + * + * Example usage: + * @code{c} + * void vOtherFunction( void ) + * { + * TaskHandle_t xHandle; + * + * // Create the task, storing the handle. + * xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); + * + * // Use the handle to delete the task. + * vTaskDelete( xHandle ); + * } + * @endcode + * \defgroup vTaskDelete vTaskDelete + * \ingroup Tasks + */ +void vTaskDelete( TaskHandle_t xTaskToDelete ) PRIVILEGED_FUNCTION; + +/*----------------------------------------------------------- +* TASK CONTROL API +*----------------------------------------------------------*/ + +/** + * task. h + * @code{c} + * void vTaskDelay( const TickType_t xTicksToDelay ); + * @endcode + * + * Delay a task for a given number of ticks. The actual time that the + * task remains blocked depends on the tick rate. The constant + * portTICK_PERIOD_MS can be used to calculate real time from the tick + * rate - with the resolution of one tick period. + * + * INCLUDE_vTaskDelay must be defined as 1 for this function to be available. + * See the configuration section for more information. + * + * + * vTaskDelay() specifies a time at which the task wishes to unblock relative to + * the time at which vTaskDelay() is called. For example, specifying a block + * period of 100 ticks will cause the task to unblock 100 ticks after + * vTaskDelay() is called. vTaskDelay() does not therefore provide a good method + * of controlling the frequency of a periodic task as the path taken through the + * code, as well as other task and interrupt activity, will affect the frequency + * at which vTaskDelay() gets called and therefore the time at which the task + * next executes. See xTaskDelayUntil() for an alternative API function designed + * to facilitate fixed frequency execution. It does this by specifying an + * absolute time (rather than a relative time) at which the calling task should + * unblock. + * + * @param xTicksToDelay The amount of time, in tick periods, that + * the calling task should block. + * + * Example usage: + * + * void vTaskFunction( void * pvParameters ) + * { + * // Block for 500ms. + * const TickType_t xDelay = 500 / portTICK_PERIOD_MS; + * + * for( ;; ) + * { + * // Simply toggle the LED every 500ms, blocking between each toggle. + * vToggleLED(); + * vTaskDelay( xDelay ); + * } + * } + * + * \defgroup vTaskDelay vTaskDelay + * \ingroup TaskCtrl + */ +void vTaskDelay( const TickType_t xTicksToDelay ) PRIVILEGED_FUNCTION; + +/** + * task. h + * @code{c} + * BaseType_t xTaskDelayUntil( TickType_t *pxPreviousWakeTime, const TickType_t xTimeIncrement ); + * @endcode + * + * INCLUDE_xTaskDelayUntil must be defined as 1 for this function to be available. + * See the configuration section for more information. + * + * Delay a task until a specified time. This function can be used by periodic + * tasks to ensure a constant execution frequency. + * + * This function differs from vTaskDelay () in one important aspect: vTaskDelay () will + * cause a task to block for the specified number of ticks from the time vTaskDelay () is + * called. It is therefore difficult to use vTaskDelay () by itself to generate a fixed + * execution frequency as the time between a task starting to execute and that task + * calling vTaskDelay () may not be fixed [the task may take a different path though the + * code between calls, or may get interrupted or preempted a different number of times + * each time it executes]. + * + * Whereas vTaskDelay () specifies a wake time relative to the time at which the function + * is called, xTaskDelayUntil () specifies the absolute (exact) time at which it wishes to + * unblock. + * + * The macro pdMS_TO_TICKS() can be used to calculate the number of ticks from a + * time specified in milliseconds with a resolution of one tick period. + * + * @param pxPreviousWakeTime Pointer to a variable that holds the time at which the + * task was last unblocked. The variable must be initialised with the current time + * prior to its first use (see the example below). Following this the variable is + * automatically updated within xTaskDelayUntil (). + * + * @param xTimeIncrement The cycle time period. The task will be unblocked at + * time *pxPreviousWakeTime + xTimeIncrement. Calling xTaskDelayUntil with the + * same xTimeIncrement parameter value will cause the task to execute with + * a fixed interface period. + * + * @return Value which can be used to check whether the task was actually delayed. + * Will be pdTRUE if the task way delayed and pdFALSE otherwise. A task will not + * be delayed if the next expected wake time is in the past. + * + * Example usage: + * @code{c} + * // Perform an action every 10 ticks. + * void vTaskFunction( void * pvParameters ) + * { + * TickType_t xLastWakeTime; + * const TickType_t xFrequency = 10; + * BaseType_t xWasDelayed; + * + * // Initialise the xLastWakeTime variable with the current time. + * xLastWakeTime = xTaskGetTickCount (); + * for( ;; ) + * { + * // Wait for the next cycle. + * xWasDelayed = xTaskDelayUntil( &xLastWakeTime, xFrequency ); + * + * // Perform action here. xWasDelayed value can be used to determine + * // whether a deadline was missed if the code here took too long. + * } + * } + * @endcode + * \defgroup xTaskDelayUntil xTaskDelayUntil + * \ingroup TaskCtrl + */ +BaseType_t xTaskDelayUntil( TickType_t * const pxPreviousWakeTime, + const TickType_t xTimeIncrement ) PRIVILEGED_FUNCTION; + +/* + * vTaskDelayUntil() is the older version of xTaskDelayUntil() and does not + * return a value. + */ +#define vTaskDelayUntil( pxPreviousWakeTime, xTimeIncrement ) \ + { \ + ( void ) xTaskDelayUntil( pxPreviousWakeTime, xTimeIncrement ); \ + } + + +/** + * task. h + * @code{c} + * BaseType_t xTaskAbortDelay( TaskHandle_t xTask ); + * @endcode + * + * INCLUDE_xTaskAbortDelay must be defined as 1 in FreeRTOSConfig.h for this + * function to be available. + * + * A task will enter the Blocked state when it is waiting for an event. The + * event it is waiting for can be a temporal event (waiting for a time), such + * as when vTaskDelay() is called, or an event on an object, such as when + * xQueueReceive() or ulTaskNotifyTake() is called. If the handle of a task + * that is in the Blocked state is used in a call to xTaskAbortDelay() then the + * task will leave the Blocked state, and return from whichever function call + * placed the task into the Blocked state. + * + * There is no 'FromISR' version of this function as an interrupt would need to + * know which object a task was blocked on in order to know which actions to + * take. For example, if the task was blocked on a queue the interrupt handler + * would then need to know if the queue was locked. + * + * @param xTask The handle of the task to remove from the Blocked state. + * + * @return If the task referenced by xTask was not in the Blocked state then + * pdFAIL is returned. Otherwise pdPASS is returned. + * + * \defgroup xTaskAbortDelay xTaskAbortDelay + * \ingroup TaskCtrl + */ +BaseType_t xTaskAbortDelay( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +/** + * task. h + * @code{c} + * UBaseType_t uxTaskPriorityGet( const TaskHandle_t xTask ); + * @endcode + * + * INCLUDE_uxTaskPriorityGet must be defined as 1 for this function to be available. + * See the configuration section for more information. + * + * Obtain the priority of any task. + * + * @param xTask Handle of the task to be queried. Passing a NULL + * handle results in the priority of the calling task being returned. + * + * @return The priority of xTask. + * + * Example usage: + * @code{c} + * void vAFunction( void ) + * { + * TaskHandle_t xHandle; + * + * // Create a task, storing the handle. + * xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); + * + * // ... + * + * // Use the handle to obtain the priority of the created task. + * // It was created with tskIDLE_PRIORITY, but may have changed + * // it itself. + * if( uxTaskPriorityGet( xHandle ) != tskIDLE_PRIORITY ) + * { + * // The task has changed it's priority. + * } + * + * // ... + * + * // Is our priority higher than the created task? + * if( uxTaskPriorityGet( xHandle ) < uxTaskPriorityGet( NULL ) ) + * { + * // Our priority (obtained using NULL handle) is higher. + * } + * } + * @endcode + * \defgroup uxTaskPriorityGet uxTaskPriorityGet + * \ingroup TaskCtrl + */ +UBaseType_t uxTaskPriorityGet( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +/** + * task. h + * @code{c} + * UBaseType_t uxTaskPriorityGetFromISR( const TaskHandle_t xTask ); + * @endcode + * + * A version of uxTaskPriorityGet() that can be used from an ISR. + */ +UBaseType_t uxTaskPriorityGetFromISR( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +/** + * task. h + * @code{c} + * eTaskState eTaskGetState( TaskHandle_t xTask ); + * @endcode + * + * INCLUDE_eTaskGetState must be defined as 1 for this function to be available. + * See the configuration section for more information. + * + * Obtain the state of any task. States are encoded by the eTaskState + * enumerated type. + * + * @param xTask Handle of the task to be queried. + * + * @return The state of xTask at the time the function was called. Note the + * state of the task might change between the function being called, and the + * functions return value being tested by the calling task. + */ +eTaskState eTaskGetState( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +/** + * task. h + * @code{c} + * void vTaskGetInfo( TaskHandle_t xTask, TaskStatus_t *pxTaskStatus, BaseType_t xGetFreeStackSpace, eTaskState eState ); + * @endcode + * + * configUSE_TRACE_FACILITY must be defined as 1 for this function to be + * available. See the configuration section for more information. + * + * Populates a TaskStatus_t structure with information about a task. + * + * @param xTask Handle of the task being queried. If xTask is NULL then + * information will be returned about the calling task. + * + * @param pxTaskStatus A pointer to the TaskStatus_t structure that will be + * filled with information about the task referenced by the handle passed using + * the xTask parameter. + * + * @xGetFreeStackSpace The TaskStatus_t structure contains a member to report + * the stack high water mark of the task being queried. Calculating the stack + * high water mark takes a relatively long time, and can make the system + * temporarily unresponsive - so the xGetFreeStackSpace parameter is provided to + * allow the high water mark checking to be skipped. The high watermark value + * will only be written to the TaskStatus_t structure if xGetFreeStackSpace is + * not set to pdFALSE; + * + * @param eState The TaskStatus_t structure contains a member to report the + * state of the task being queried. Obtaining the task state is not as fast as + * a simple assignment - so the eState parameter is provided to allow the state + * information to be omitted from the TaskStatus_t structure. To obtain state + * information then set eState to eInvalid - otherwise the value passed in + * eState will be reported as the task state in the TaskStatus_t structure. + * + * Example usage: + * @code{c} + * void vAFunction( void ) + * { + * TaskHandle_t xHandle; + * TaskStatus_t xTaskDetails; + * + * // Obtain the handle of a task from its name. + * xHandle = xTaskGetHandle( "Task_Name" ); + * + * // Check the handle is not NULL. + * configASSERT( xHandle ); + * + * // Use the handle to obtain further information about the task. + * vTaskGetInfo( xHandle, + * &xTaskDetails, + * pdTRUE, // Include the high water mark in xTaskDetails. + * eInvalid ); // Include the task state in xTaskDetails. + * } + * @endcode + * \defgroup vTaskGetInfo vTaskGetInfo + * \ingroup TaskCtrl + */ +void vTaskGetInfo( TaskHandle_t xTask, + TaskStatus_t * pxTaskStatus, + BaseType_t xGetFreeStackSpace, + eTaskState eState ) PRIVILEGED_FUNCTION; + +/** + * task. h + * @code{c} + * void vTaskPrioritySet( TaskHandle_t xTask, UBaseType_t uxNewPriority ); + * @endcode + * + * INCLUDE_vTaskPrioritySet must be defined as 1 for this function to be available. + * See the configuration section for more information. + * + * Set the priority of any task. + * + * A context switch will occur before the function returns if the priority + * being set is higher than the currently executing task. + * + * @param xTask Handle to the task for which the priority is being set. + * Passing a NULL handle results in the priority of the calling task being set. + * + * @param uxNewPriority The priority to which the task will be set. + * + * Example usage: + * @code{c} + * void vAFunction( void ) + * { + * TaskHandle_t xHandle; + * + * // Create a task, storing the handle. + * xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); + * + * // ... + * + * // Use the handle to raise the priority of the created task. + * vTaskPrioritySet( xHandle, tskIDLE_PRIORITY + 1 ); + * + * // ... + * + * // Use a NULL handle to raise our priority to the same value. + * vTaskPrioritySet( NULL, tskIDLE_PRIORITY + 1 ); + * } + * @endcode + * \defgroup vTaskPrioritySet vTaskPrioritySet + * \ingroup TaskCtrl + */ +void vTaskPrioritySet( TaskHandle_t xTask, + UBaseType_t uxNewPriority ) PRIVILEGED_FUNCTION; + +/** + * task. h + * @code{c} + * void vTaskSuspend( TaskHandle_t xTaskToSuspend ); + * @endcode + * + * INCLUDE_vTaskSuspend must be defined as 1 for this function to be available. + * See the configuration section for more information. + * + * Suspend any task. When suspended a task will never get any microcontroller + * processing time, no matter what its priority. + * + * Calls to vTaskSuspend are not accumulative - + * i.e. calling vTaskSuspend () twice on the same task still only requires one + * call to vTaskResume () to ready the suspended task. + * + * @param xTaskToSuspend Handle to the task being suspended. Passing a NULL + * handle will cause the calling task to be suspended. + * + * Example usage: + * @code{c} + * void vAFunction( void ) + * { + * TaskHandle_t xHandle; + * + * // Create a task, storing the handle. + * xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); + * + * // ... + * + * // Use the handle to suspend the created task. + * vTaskSuspend( xHandle ); + * + * // ... + * + * // The created task will not run during this period, unless + * // another task calls vTaskResume( xHandle ). + * + * //... + * + * + * // Suspend ourselves. + * vTaskSuspend( NULL ); + * + * // We cannot get here unless another task calls vTaskResume + * // with our handle as the parameter. + * } + * @endcode + * \defgroup vTaskSuspend vTaskSuspend + * \ingroup TaskCtrl + */ +void vTaskSuspend( TaskHandle_t xTaskToSuspend ) PRIVILEGED_FUNCTION; + +/** + * task. h + * @code{c} + * void vTaskResume( TaskHandle_t xTaskToResume ); + * @endcode + * + * INCLUDE_vTaskSuspend must be defined as 1 for this function to be available. + * See the configuration section for more information. + * + * Resumes a suspended task. + * + * A task that has been suspended by one or more calls to vTaskSuspend () + * will be made available for running again by a single call to + * vTaskResume (). + * + * @param xTaskToResume Handle to the task being readied. + * + * Example usage: + * @code{c} + * void vAFunction( void ) + * { + * TaskHandle_t xHandle; + * + * // Create a task, storing the handle. + * xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); + * + * // ... + * + * // Use the handle to suspend the created task. + * vTaskSuspend( xHandle ); + * + * // ... + * + * // The created task will not run during this period, unless + * // another task calls vTaskResume( xHandle ). + * + * //... + * + * + * // Resume the suspended task ourselves. + * vTaskResume( xHandle ); + * + * // The created task will once again get microcontroller processing + * // time in accordance with its priority within the system. + * } + * @endcode + * \defgroup vTaskResume vTaskResume + * \ingroup TaskCtrl + */ +void vTaskResume( TaskHandle_t xTaskToResume ) PRIVILEGED_FUNCTION; + +/** + * task. h + * @code{c} + * void xTaskResumeFromISR( TaskHandle_t xTaskToResume ); + * @endcode + * + * INCLUDE_xTaskResumeFromISR must be defined as 1 for this function to be + * available. See the configuration section for more information. + * + * An implementation of vTaskResume() that can be called from within an ISR. + * + * A task that has been suspended by one or more calls to vTaskSuspend () + * will be made available for running again by a single call to + * xTaskResumeFromISR (). + * + * xTaskResumeFromISR() should not be used to synchronise a task with an + * interrupt if there is a chance that the interrupt could arrive prior to the + * task being suspended - as this can lead to interrupts being missed. Use of a + * semaphore as a synchronisation mechanism would avoid this eventuality. + * + * @param xTaskToResume Handle to the task being readied. + * + * @return pdTRUE if resuming the task should result in a context switch, + * otherwise pdFALSE. This is used by the ISR to determine if a context switch + * may be required following the ISR. + * + * \defgroup vTaskResumeFromISR vTaskResumeFromISR + * \ingroup TaskCtrl + */ +BaseType_t xTaskResumeFromISR( TaskHandle_t xTaskToResume ) PRIVILEGED_FUNCTION; + +/*----------------------------------------------------------- +* SCHEDULER CONTROL +*----------------------------------------------------------*/ + +/** + * task. h + * @code{c} + * void vTaskStartScheduler( void ); + * @endcode + * + * Starts the real time kernel tick processing. After calling the kernel + * has control over which tasks are executed and when. + * + * See the demo application file main.c for an example of creating + * tasks and starting the kernel. + * + * Example usage: + * @code{c} + * void vAFunction( void ) + * { + * // Create at least one task before starting the kernel. + * xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL ); + * + * // Start the real time kernel with preemption. + * vTaskStartScheduler (); + * + * // Will not get here unless a task calls vTaskEndScheduler () + * } + * @endcode + * + * \defgroup vTaskStartScheduler vTaskStartScheduler + * \ingroup SchedulerControl + */ +void vTaskStartScheduler( void ) PRIVILEGED_FUNCTION; + +/** + * task. h + * @code{c} + * void vTaskEndScheduler( void ); + * @endcode + * + * NOTE: At the time of writing only the x86 real mode port, which runs on a PC + * in place of DOS, implements this function. + * + * Stops the real time kernel tick. All created tasks will be automatically + * deleted and multitasking (either preemptive or cooperative) will + * stop. Execution then resumes from the point where vTaskStartScheduler () + * was called, as if vTaskStartScheduler () had just returned. + * + * See the demo application file main. c in the demo/PC directory for an + * example that uses vTaskEndScheduler (). + * + * vTaskEndScheduler () requires an exit function to be defined within the + * portable layer (see vPortEndScheduler () in port. c for the PC port). This + * performs hardware specific operations such as stopping the kernel tick. + * + * vTaskEndScheduler () will cause all of the resources allocated by the + * kernel to be freed - but will not free resources allocated by application + * tasks. + * + * Example usage: + * @code{c} + * void vTaskCode( void * pvParameters ) + * { + * for( ;; ) + * { + * // Task code goes here. + * + * // At some point we want to end the real time kernel processing + * // so call ... + * vTaskEndScheduler (); + * } + * } + * + * void vAFunction( void ) + * { + * // Create at least one task before starting the kernel. + * xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL ); + * + * // Start the real time kernel with preemption. + * vTaskStartScheduler (); + * + * // Will only get here when the vTaskCode () task has called + * // vTaskEndScheduler (). When we get here we are back to single task + * // execution. + * } + * @endcode + * + * \defgroup vTaskEndScheduler vTaskEndScheduler + * \ingroup SchedulerControl + */ +void vTaskEndScheduler( void ) PRIVILEGED_FUNCTION; + +/** + * task. h + * @code{c} + * void vTaskSuspendAll( void ); + * @endcode + * + * Suspends the scheduler without disabling interrupts. Context switches will + * not occur while the scheduler is suspended. + * + * After calling vTaskSuspendAll () the calling task will continue to execute + * without risk of being swapped out until a call to xTaskResumeAll () has been + * made. + * + * API functions that have the potential to cause a context switch (for example, + * xTaskDelayUntil(), xQueueSend(), etc.) must not be called while the scheduler + * is suspended. + * + * Example usage: + * @code{c} + * void vTask1( void * pvParameters ) + * { + * for( ;; ) + * { + * // Task code goes here. + * + * // ... + * + * // At some point the task wants to perform a long operation during + * // which it does not want to get swapped out. It cannot use + * // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the + * // operation may cause interrupts to be missed - including the + * // ticks. + * + * // Prevent the real time kernel swapping out the task. + * vTaskSuspendAll (); + * + * // Perform the operation here. There is no need to use critical + * // sections as we have all the microcontroller processing time. + * // During this time interrupts will still operate and the kernel + * // tick count will be maintained. + * + * // ... + * + * // The operation is complete. Restart the kernel. + * xTaskResumeAll (); + * } + * } + * @endcode + * \defgroup vTaskSuspendAll vTaskSuspendAll + * \ingroup SchedulerControl + */ +void vTaskSuspendAll( void ) PRIVILEGED_FUNCTION; + +/** + * task. h + * @code{c} + * BaseType_t xTaskResumeAll( void ); + * @endcode + * + * Resumes scheduler activity after it was suspended by a call to + * vTaskSuspendAll(). + * + * xTaskResumeAll() only resumes the scheduler. It does not unsuspend tasks + * that were previously suspended by a call to vTaskSuspend(). + * + * @return If resuming the scheduler caused a context switch then pdTRUE is + * returned, otherwise pdFALSE is returned. + * + * Example usage: + * @code{c} + * void vTask1( void * pvParameters ) + * { + * for( ;; ) + * { + * // Task code goes here. + * + * // ... + * + * // At some point the task wants to perform a long operation during + * // which it does not want to get swapped out. It cannot use + * // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the + * // operation may cause interrupts to be missed - including the + * // ticks. + * + * // Prevent the real time kernel swapping out the task. + * vTaskSuspendAll (); + * + * // Perform the operation here. There is no need to use critical + * // sections as we have all the microcontroller processing time. + * // During this time interrupts will still operate and the real + * // time kernel tick count will be maintained. + * + * // ... + * + * // The operation is complete. Restart the kernel. We want to force + * // a context switch - but there is no point if resuming the scheduler + * // caused a context switch already. + * if( !xTaskResumeAll () ) + * { + * taskYIELD (); + * } + * } + * } + * @endcode + * \defgroup xTaskResumeAll xTaskResumeAll + * \ingroup SchedulerControl + */ +BaseType_t xTaskResumeAll( void ) PRIVILEGED_FUNCTION; + +/*----------------------------------------------------------- +* TASK UTILITIES +*----------------------------------------------------------*/ + +/** + * task. h + * @code{c} + * TickType_t xTaskGetTickCount( void ); + * @endcode + * + * @return The count of ticks since vTaskStartScheduler was called. + * + * \defgroup xTaskGetTickCount xTaskGetTickCount + * \ingroup TaskUtils + */ +TickType_t xTaskGetTickCount( void ) PRIVILEGED_FUNCTION; + +/** + * task. h + * @code{c} + * TickType_t xTaskGetTickCountFromISR( void ); + * @endcode + * + * @return The count of ticks since vTaskStartScheduler was called. + * + * This is a version of xTaskGetTickCount() that is safe to be called from an + * ISR - provided that TickType_t is the natural word size of the + * microcontroller being used or interrupt nesting is either not supported or + * not being used. + * + * \defgroup xTaskGetTickCountFromISR xTaskGetTickCountFromISR + * \ingroup TaskUtils + */ +TickType_t xTaskGetTickCountFromISR( void ) PRIVILEGED_FUNCTION; + +/** + * task. h + * @code{c} + * uint16_t uxTaskGetNumberOfTasks( void ); + * @endcode + * + * @return The number of tasks that the real time kernel is currently managing. + * This includes all ready, blocked and suspended tasks. A task that + * has been deleted but not yet freed by the idle task will also be + * included in the count. + * + * \defgroup uxTaskGetNumberOfTasks uxTaskGetNumberOfTasks + * \ingroup TaskUtils + */ +UBaseType_t uxTaskGetNumberOfTasks( void ) PRIVILEGED_FUNCTION; + +/** + * task. h + * @code{c} + * char *pcTaskGetName( TaskHandle_t xTaskToQuery ); + * @endcode + * + * @return The text (human readable) name of the task referenced by the handle + * xTaskToQuery. A task can query its own name by either passing in its own + * handle, or by setting xTaskToQuery to NULL. + * + * \defgroup pcTaskGetName pcTaskGetName + * \ingroup TaskUtils + */ +char * pcTaskGetName( TaskHandle_t xTaskToQuery ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + +/** + * task. h + * @code{c} + * TaskHandle_t xTaskGetHandle( const char *pcNameToQuery ); + * @endcode + * + * NOTE: This function takes a relatively long time to complete and should be + * used sparingly. + * + * @return The handle of the task that has the human readable name pcNameToQuery. + * NULL is returned if no matching name is found. INCLUDE_xTaskGetHandle + * must be set to 1 in FreeRTOSConfig.h for pcTaskGetHandle() to be available. + * + * \defgroup pcTaskGetHandle pcTaskGetHandle + * \ingroup TaskUtils + */ +TaskHandle_t xTaskGetHandle( const char * pcNameToQuery ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + +/** + * task.h + * @code{c} + * UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask ); + * @endcode + * + * INCLUDE_uxTaskGetStackHighWaterMark must be set to 1 in FreeRTOSConfig.h for + * this function to be available. + * + * Returns the high water mark of the stack associated with xTask. That is, + * the minimum free stack space there has been (in words, so on a 32 bit machine + * a value of 1 means 4 bytes) since the task started. The smaller the returned + * number the closer the task has come to overflowing its stack. + * + * uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the + * same except for their return type. Using configSTACK_DEPTH_TYPE allows the + * user to determine the return type. It gets around the problem of the value + * overflowing on 8-bit types without breaking backward compatibility for + * applications that expect an 8-bit return type. + * + * @param xTask Handle of the task associated with the stack to be checked. + * Set xTask to NULL to check the stack of the calling task. + * + * @return The smallest amount of free stack space there has been (in words, so + * actual spaces on the stack rather than bytes) since the task referenced by + * xTask was created. + */ +UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +/** + * task.h + * @code{c} + * configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2( TaskHandle_t xTask ); + * @endcode + * + * INCLUDE_uxTaskGetStackHighWaterMark2 must be set to 1 in FreeRTOSConfig.h for + * this function to be available. + * + * Returns the high water mark of the stack associated with xTask. That is, + * the minimum free stack space there has been (in words, so on a 32 bit machine + * a value of 1 means 4 bytes) since the task started. The smaller the returned + * number the closer the task has come to overflowing its stack. + * + * uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the + * same except for their return type. Using configSTACK_DEPTH_TYPE allows the + * user to determine the return type. It gets around the problem of the value + * overflowing on 8-bit types without breaking backward compatibility for + * applications that expect an 8-bit return type. + * + * @param xTask Handle of the task associated with the stack to be checked. + * Set xTask to NULL to check the stack of the calling task. + * + * @return The smallest amount of free stack space there has been (in words, so + * actual spaces on the stack rather than bytes) since the task referenced by + * xTask was created. + */ +configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +/* When using trace macros it is sometimes necessary to include task.h before + * FreeRTOS.h. When this is done TaskHookFunction_t will not yet have been defined, + * so the following two prototypes will cause a compilation error. This can be + * fixed by simply guarding against the inclusion of these two prototypes unless + * they are explicitly required by the configUSE_APPLICATION_TASK_TAG configuration + * constant. */ +#ifdef configUSE_APPLICATION_TASK_TAG + #if configUSE_APPLICATION_TASK_TAG == 1 + +/** + * task.h + * @code{c} + * void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction ); + * @endcode + * + * Sets pxHookFunction to be the task hook function used by the task xTask. + * Passing xTask as NULL has the effect of setting the calling tasks hook + * function. + */ + void vTaskSetApplicationTaskTag( TaskHandle_t xTask, + TaskHookFunction_t pxHookFunction ) PRIVILEGED_FUNCTION; + +/** + * task.h + * @code{c} + * void xTaskGetApplicationTaskTag( TaskHandle_t xTask ); + * @endcode + * + * Returns the pxHookFunction value assigned to the task xTask. Do not + * call from an interrupt service routine - call + * xTaskGetApplicationTaskTagFromISR() instead. + */ + TaskHookFunction_t xTaskGetApplicationTaskTag( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +/** + * task.h + * @code{c} + * void xTaskGetApplicationTaskTagFromISR( TaskHandle_t xTask ); + * @endcode + * + * Returns the pxHookFunction value assigned to the task xTask. Can + * be called from an interrupt service routine. + */ + TaskHookFunction_t xTaskGetApplicationTaskTagFromISR( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + #endif /* configUSE_APPLICATION_TASK_TAG ==1 */ +#endif /* ifdef configUSE_APPLICATION_TASK_TAG */ + +#if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) + +/* Each task contains an array of pointers that is dimensioned by the + * configNUM_THREAD_LOCAL_STORAGE_POINTERS setting in FreeRTOSConfig.h. The + * kernel does not use the pointers itself, so the application writer can use + * the pointers for any purpose they wish. The following two functions are + * used to set and query a pointer respectively. */ + void vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, + BaseType_t xIndex, + void * pvValue ) PRIVILEGED_FUNCTION; + void * pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, + BaseType_t xIndex ) PRIVILEGED_FUNCTION; + +#endif + +#if ( configCHECK_FOR_STACK_OVERFLOW > 0 ) + +/** + * task.h + * @code{c} + * void vApplicationStackOverflowHook( TaskHandle_t xTask char *pcTaskName); + * @endcode + * + * The application stack overflow hook is called when a stack overflow is detected for a task. + * + * Details on stack overflow detection can be found here: https://www.FreeRTOS.org/Stacks-and-stack-overflow-checking.html + * + * @param xTask the task that just exceeded its stack boundaries. + * @param pcTaskName A character string containing the name of the offending task. + */ + void vApplicationStackOverflowHook( TaskHandle_t xTask, + char * pcTaskName ); + +#endif + +#if ( configUSE_TICK_HOOK > 0 ) + +/** + * task.h + * @code{c} + * void vApplicationTickHook( void ); + * @endcode + * + * This hook function is called in the system tick handler after any OS work is completed. + */ + void vApplicationTickHook( void ); /*lint !e526 Symbol not defined as it is an application callback. */ + +#endif + +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + +/** + * task.h + * @code{c} + * void vApplicationGetIdleTaskMemory( StaticTask_t ** ppxIdleTaskTCBBuffer, StackType_t ** ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize ) + * @endcode + * + * This function is used to provide a statically allocated block of memory to FreeRTOS to hold the Idle Task TCB. This function is required when + * configSUPPORT_STATIC_ALLOCATION is set. For more information see this URI: https://www.FreeRTOS.org/a00110.html#configSUPPORT_STATIC_ALLOCATION + * + * @param ppxIdleTaskTCBBuffer A handle to a statically allocated TCB buffer + * @param ppxIdleTaskStackBuffer A handle to a statically allocated Stack buffer for the idle task + * @param pulIdleTaskStackSize A pointer to the number of elements that will fit in the allocated stack buffer + */ + void vApplicationGetIdleTaskMemory( StaticTask_t ** ppxIdleTaskTCBBuffer, + StackType_t ** ppxIdleTaskStackBuffer, + uint32_t * pulIdleTaskStackSize ); /*lint !e526 Symbol not defined as it is an application callback. */ +#endif + +/** + * task.h + * @code{c} + * BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask, void *pvParameter ); + * @endcode + * + * Calls the hook function associated with xTask. Passing xTask as NULL has + * the effect of calling the Running tasks (the calling task) hook function. + * + * pvParameter is passed to the hook function for the task to interpret as it + * wants. The return value is the value returned by the task hook function + * registered by the user. + */ +BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask, + void * pvParameter ) PRIVILEGED_FUNCTION; + +/** + * xTaskGetIdleTaskHandle() is only available if + * INCLUDE_xTaskGetIdleTaskHandle is set to 1 in FreeRTOSConfig.h. + * + * Simply returns the handle of the idle task. It is not valid to call + * xTaskGetIdleTaskHandle() before the scheduler has been started. + */ +TaskHandle_t xTaskGetIdleTaskHandle( void ) PRIVILEGED_FUNCTION; + +/** + * configUSE_TRACE_FACILITY must be defined as 1 in FreeRTOSConfig.h for + * uxTaskGetSystemState() to be available. + * + * uxTaskGetSystemState() populates an TaskStatus_t structure for each task in + * the system. TaskStatus_t structures contain, among other things, members + * for the task handle, task name, task priority, task state, and total amount + * of run time consumed by the task. See the TaskStatus_t structure + * definition in this file for the full member list. + * + * NOTE: This function is intended for debugging use only as its use results in + * the scheduler remaining suspended for an extended period. + * + * @param pxTaskStatusArray A pointer to an array of TaskStatus_t structures. + * The array must contain at least one TaskStatus_t structure for each task + * that is under the control of the RTOS. The number of tasks under the control + * of the RTOS can be determined using the uxTaskGetNumberOfTasks() API function. + * + * @param uxArraySize The size of the array pointed to by the pxTaskStatusArray + * parameter. The size is specified as the number of indexes in the array, or + * the number of TaskStatus_t structures contained in the array, not by the + * number of bytes in the array. + * + * @param pulTotalRunTime If configGENERATE_RUN_TIME_STATS is set to 1 in + * FreeRTOSConfig.h then *pulTotalRunTime is set by uxTaskGetSystemState() to the + * total run time (as defined by the run time stats clock, see + * https://www.FreeRTOS.org/rtos-run-time-stats.html) since the target booted. + * pulTotalRunTime can be set to NULL to omit the total run time information. + * + * @return The number of TaskStatus_t structures that were populated by + * uxTaskGetSystemState(). This should equal the number returned by the + * uxTaskGetNumberOfTasks() API function, but will be zero if the value passed + * in the uxArraySize parameter was too small. + * + * Example usage: + * @code{c} + * // This example demonstrates how a human readable table of run time stats + * // information is generated from raw data provided by uxTaskGetSystemState(). + * // The human readable table is written to pcWriteBuffer + * void vTaskGetRunTimeStats( char *pcWriteBuffer ) + * { + * TaskStatus_t *pxTaskStatusArray; + * volatile UBaseType_t uxArraySize, x; + * configRUN_TIME_COUNTER_TYPE ulTotalRunTime, ulStatsAsPercentage; + * + * // Make sure the write buffer does not contain a string. + * pcWriteBuffer = 0x00; + * + * // Take a snapshot of the number of tasks in case it changes while this + * // function is executing. + * uxArraySize = uxTaskGetNumberOfTasks(); + * + * // Allocate a TaskStatus_t structure for each task. An array could be + * // allocated statically at compile time. + * pxTaskStatusArray = pvPortMalloc( uxArraySize * sizeof( TaskStatus_t ) ); + * + * if( pxTaskStatusArray != NULL ) + * { + * // Generate raw status information about each task. + * uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalRunTime ); + * + * // For percentage calculations. + * ulTotalRunTime /= 100UL; + * + * // Avoid divide by zero errors. + * if( ulTotalRunTime > 0 ) + * { + * // For each populated position in the pxTaskStatusArray array, + * // format the raw data as human readable ASCII data + * for( x = 0; x < uxArraySize; x++ ) + * { + * // What percentage of the total run time has the task used? + * // This will always be rounded down to the nearest integer. + * // ulTotalRunTimeDiv100 has already been divided by 100. + * ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalRunTime; + * + * if( ulStatsAsPercentage > 0UL ) + * { + * sprintf( pcWriteBuffer, "%s\t\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage ); + * } + * else + * { + * // If the percentage is zero here then the task has + * // consumed less than 1% of the total run time. + * sprintf( pcWriteBuffer, "%s\t\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter ); + * } + * + * pcWriteBuffer += strlen( ( char * ) pcWriteBuffer ); + * } + * } + * + * // The array is no longer needed, free the memory it consumes. + * vPortFree( pxTaskStatusArray ); + * } + * } + * @endcode + */ +UBaseType_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, + const UBaseType_t uxArraySize, + configRUN_TIME_COUNTER_TYPE * const pulTotalRunTime ) PRIVILEGED_FUNCTION; + +/** + * task. h + * @code{c} + * void vTaskList( char *pcWriteBuffer ); + * @endcode + * + * configUSE_TRACE_FACILITY and configUSE_STATS_FORMATTING_FUNCTIONS must + * both be defined as 1 for this function to be available. See the + * configuration section of the FreeRTOS.org website for more information. + * + * NOTE 1: This function will disable interrupts for its duration. It is + * not intended for normal application runtime use but as a debug aid. + * + * Lists all the current tasks, along with their current state and stack + * usage high water mark. + * + * Tasks are reported as blocked ('B'), ready ('R'), deleted ('D') or + * suspended ('S'). + * + * PLEASE NOTE: + * + * This function is provided for convenience only, and is used by many of the + * demo applications. Do not consider it to be part of the scheduler. + * + * vTaskList() calls uxTaskGetSystemState(), then formats part of the + * uxTaskGetSystemState() output into a human readable table that displays task: + * names, states, priority, stack usage and task number. + * Stack usage specified as the number of unused StackType_t words stack can hold + * on top of stack - not the number of bytes. + * + * vTaskList() has a dependency on the sprintf() C library function that might + * bloat the code size, use a lot of stack, and provide different results on + * different platforms. An alternative, tiny, third party, and limited + * functionality implementation of sprintf() is provided in many of the + * FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note + * printf-stdarg.c does not provide a full snprintf() implementation!). + * + * It is recommended that production systems call uxTaskGetSystemState() + * directly to get access to raw stats data, rather than indirectly through a + * call to vTaskList(). + * + * @param pcWriteBuffer A buffer into which the above mentioned details + * will be written, in ASCII form. This buffer is assumed to be large + * enough to contain the generated report. Approximately 40 bytes per + * task should be sufficient. + * + * \defgroup vTaskList vTaskList + * \ingroup TaskUtils + */ +void vTaskList( char * pcWriteBuffer ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + +/** + * task. h + * @code{c} + * void vTaskGetRunTimeStats( char *pcWriteBuffer ); + * @endcode + * + * configGENERATE_RUN_TIME_STATS and configUSE_STATS_FORMATTING_FUNCTIONS + * must both be defined as 1 for this function to be available. The application + * must also then provide definitions for + * portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and portGET_RUN_TIME_COUNTER_VALUE() + * to configure a peripheral timer/counter and return the timers current count + * value respectively. The counter should be at least 10 times the frequency of + * the tick count. + * + * NOTE 1: This function will disable interrupts for its duration. It is + * not intended for normal application runtime use but as a debug aid. + * + * Setting configGENERATE_RUN_TIME_STATS to 1 will result in a total + * accumulated execution time being stored for each task. The resolution + * of the accumulated time value depends on the frequency of the timer + * configured by the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() macro. + * Calling vTaskGetRunTimeStats() writes the total execution time of each + * task into a buffer, both as an absolute count value and as a percentage + * of the total system execution time. + * + * NOTE 2: + * + * This function is provided for convenience only, and is used by many of the + * demo applications. Do not consider it to be part of the scheduler. + * + * vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part of the + * uxTaskGetSystemState() output into a human readable table that displays the + * amount of time each task has spent in the Running state in both absolute and + * percentage terms. + * + * vTaskGetRunTimeStats() has a dependency on the sprintf() C library function + * that might bloat the code size, use a lot of stack, and provide different + * results on different platforms. An alternative, tiny, third party, and + * limited functionality implementation of sprintf() is provided in many of the + * FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note + * printf-stdarg.c does not provide a full snprintf() implementation!). + * + * It is recommended that production systems call uxTaskGetSystemState() directly + * to get access to raw stats data, rather than indirectly through a call to + * vTaskGetRunTimeStats(). + * + * @param pcWriteBuffer A buffer into which the execution times will be + * written, in ASCII form. This buffer is assumed to be large enough to + * contain the generated report. Approximately 40 bytes per task should + * be sufficient. + * + * \defgroup vTaskGetRunTimeStats vTaskGetRunTimeStats + * \ingroup TaskUtils + */ +void vTaskGetRunTimeStats( char * pcWriteBuffer ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + +/** + * task. h + * @code{c} + * configRUN_TIME_COUNTER_TYPE ulTaskGetIdleRunTimeCounter( void ); + * configRUN_TIME_COUNTER_TYPE ulTaskGetIdleRunTimePercent( void ); + * @endcode + * + * configGENERATE_RUN_TIME_STATS, configUSE_STATS_FORMATTING_FUNCTIONS and + * INCLUDE_xTaskGetIdleTaskHandle must all be defined as 1 for these functions + * to be available. The application must also then provide definitions for + * portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and portGET_RUN_TIME_COUNTER_VALUE() + * to configure a peripheral timer/counter and return the timers current count + * value respectively. The counter should be at least 10 times the frequency of + * the tick count. + * + * Setting configGENERATE_RUN_TIME_STATS to 1 will result in a total + * accumulated execution time being stored for each task. The resolution + * of the accumulated time value depends on the frequency of the timer + * configured by the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() macro. + * While uxTaskGetSystemState() and vTaskGetRunTimeStats() writes the total + * execution time of each task into a buffer, ulTaskGetIdleRunTimeCounter() + * returns the total execution time of just the idle task and + * ulTaskGetIdleRunTimePercent() returns the percentage of the CPU time used by + * just the idle task. + * + * Note the amount of idle time is only a good measure of the slack time in a + * system if there are no other tasks executing at the idle priority, tickless + * idle is not used, and configIDLE_SHOULD_YIELD is set to 0. + * + * @return The total run time of the idle task or the percentage of the total + * run time consumed by the idle task. This is the amount of time the + * idle task has actually been executing. The unit of time is dependent on the + * frequency configured using the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and + * portGET_RUN_TIME_COUNTER_VALUE() macros. + * + * \defgroup ulTaskGetIdleRunTimeCounter ulTaskGetIdleRunTimeCounter + * \ingroup TaskUtils + */ +configRUN_TIME_COUNTER_TYPE ulTaskGetIdleRunTimeCounter( void ) PRIVILEGED_FUNCTION; +configRUN_TIME_COUNTER_TYPE ulTaskGetIdleRunTimePercent( void ) PRIVILEGED_FUNCTION; + +/** + * task. h + * @code{c} + * BaseType_t xTaskNotifyIndexed( TaskHandle_t xTaskToNotify, UBaseType_t uxIndexToNotify, uint32_t ulValue, eNotifyAction eAction ); + * BaseType_t xTaskNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction ); + * @endcode + * + * See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. + * + * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for these + * functions to be available. + * + * Sends a direct to task notification to a task, with an optional value and + * action. + * + * Each task has a private array of "notification values" (or 'notifications'), + * each of which is a 32-bit unsigned integer (uint32_t). The constant + * configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the + * array, and (for backward compatibility) defaults to 1 if left undefined. + * Prior to FreeRTOS V10.4.0 there was only one notification value per task. + * + * Events can be sent to a task using an intermediary object. Examples of such + * objects are queues, semaphores, mutexes and event groups. Task notifications + * are a method of sending an event directly to a task without the need for such + * an intermediary object. + * + * A notification sent to a task can optionally perform an action, such as + * update, overwrite or increment one of the task's notification values. In + * that way task notifications can be used to send data to a task, or be used as + * light weight and fast binary or counting semaphores. + * + * A task can use xTaskNotifyWaitIndexed() or ulTaskNotifyTakeIndexed() to + * [optionally] block to wait for a notification to be pending. The task does + * not consume any CPU time while it is in the Blocked state. + * + * A notification sent to a task will remain pending until it is cleared by the + * task calling xTaskNotifyWaitIndexed() or ulTaskNotifyTakeIndexed() (or their + * un-indexed equivalents). If the task was already in the Blocked state to + * wait for a notification when the notification arrives then the task will + * automatically be removed from the Blocked state (unblocked) and the + * notification cleared. + * + * **NOTE** Each notification within the array operates independently - a task + * can only block on one notification within the array at a time and will not be + * unblocked by a notification sent to any other array index. + * + * Backward compatibility information: + * Prior to FreeRTOS V10.4.0 each task had a single "notification value", and + * all task notification API functions operated on that value. Replacing the + * single notification value with an array of notification values necessitated a + * new set of API functions that could address specific notifications within the + * array. xTaskNotify() is the original API function, and remains backward + * compatible by always operating on the notification value at index 0 in the + * array. Calling xTaskNotify() is equivalent to calling xTaskNotifyIndexed() + * with the uxIndexToNotify parameter set to 0. + * + * @param xTaskToNotify The handle of the task being notified. The handle to a + * task can be returned from the xTaskCreate() API function used to create the + * task, and the handle of the currently running task can be obtained by calling + * xTaskGetCurrentTaskHandle(). + * + * @param uxIndexToNotify The index within the target task's array of + * notification values to which the notification is to be sent. uxIndexToNotify + * must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotify() does + * not have this parameter and always sends notifications to index 0. + * + * @param ulValue Data that can be sent with the notification. How the data is + * used depends on the value of the eAction parameter. + * + * @param eAction Specifies how the notification updates the task's notification + * value, if at all. Valid values for eAction are as follows: + * + * eSetBits - + * The target notification value is bitwise ORed with ulValue. + * xTaskNotifyIndexed() always returns pdPASS in this case. + * + * eIncrement - + * The target notification value is incremented. ulValue is not used and + * xTaskNotifyIndexed() always returns pdPASS in this case. + * + * eSetValueWithOverwrite - + * The target notification value is set to the value of ulValue, even if the + * task being notified had not yet processed the previous notification at the + * same array index (the task already had a notification pending at that index). + * xTaskNotifyIndexed() always returns pdPASS in this case. + * + * eSetValueWithoutOverwrite - + * If the task being notified did not already have a notification pending at the + * same array index then the target notification value is set to ulValue and + * xTaskNotifyIndexed() will return pdPASS. If the task being notified already + * had a notification pending at the same array index then no action is + * performed and pdFAIL is returned. + * + * eNoAction - + * The task receives a notification at the specified array index without the + * notification value at that index being updated. ulValue is not used and + * xTaskNotifyIndexed() always returns pdPASS in this case. + * + * pulPreviousNotificationValue - + * Can be used to pass out the subject task's notification value before any + * bits are modified by the notify function. + * + * @return Dependent on the value of eAction. See the description of the + * eAction parameter. + * + * \defgroup xTaskNotifyIndexed xTaskNotifyIndexed + * \ingroup TaskNotifications + */ +BaseType_t xTaskGenericNotify( TaskHandle_t xTaskToNotify, + UBaseType_t uxIndexToNotify, + uint32_t ulValue, + eNotifyAction eAction, + uint32_t * pulPreviousNotificationValue ) PRIVILEGED_FUNCTION; +#define xTaskNotify( xTaskToNotify, ulValue, eAction ) \ + xTaskGenericNotify( ( xTaskToNotify ), ( tskDEFAULT_INDEX_TO_NOTIFY ), ( ulValue ), ( eAction ), NULL ) +#define xTaskNotifyIndexed( xTaskToNotify, uxIndexToNotify, ulValue, eAction ) \ + xTaskGenericNotify( ( xTaskToNotify ), ( uxIndexToNotify ), ( ulValue ), ( eAction ), NULL ) + +/** + * task. h + * @code{c} + * BaseType_t xTaskNotifyAndQueryIndexed( TaskHandle_t xTaskToNotify, UBaseType_t uxIndexToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotifyValue ); + * BaseType_t xTaskNotifyAndQuery( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotifyValue ); + * @endcode + * + * See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. + * + * xTaskNotifyAndQueryIndexed() performs the same operation as + * xTaskNotifyIndexed() with the addition that it also returns the subject + * task's prior notification value (the notification value at the time the + * function is called rather than when the function returns) in the additional + * pulPreviousNotifyValue parameter. + * + * xTaskNotifyAndQuery() performs the same operation as xTaskNotify() with the + * addition that it also returns the subject task's prior notification value + * (the notification value as it was at the time the function is called, rather + * than when the function returns) in the additional pulPreviousNotifyValue + * parameter. + * + * \defgroup xTaskNotifyAndQueryIndexed xTaskNotifyAndQueryIndexed + * \ingroup TaskNotifications + */ +#define xTaskNotifyAndQuery( xTaskToNotify, ulValue, eAction, pulPreviousNotifyValue ) \ + xTaskGenericNotify( ( xTaskToNotify ), ( tskDEFAULT_INDEX_TO_NOTIFY ), ( ulValue ), ( eAction ), ( pulPreviousNotifyValue ) ) +#define xTaskNotifyAndQueryIndexed( xTaskToNotify, uxIndexToNotify, ulValue, eAction, pulPreviousNotifyValue ) \ + xTaskGenericNotify( ( xTaskToNotify ), ( uxIndexToNotify ), ( ulValue ), ( eAction ), ( pulPreviousNotifyValue ) ) + +/** + * task. h + * @code{c} + * BaseType_t xTaskNotifyIndexedFromISR( TaskHandle_t xTaskToNotify, UBaseType_t uxIndexToNotify, uint32_t ulValue, eNotifyAction eAction, BaseType_t *pxHigherPriorityTaskWoken ); + * BaseType_t xTaskNotifyFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, BaseType_t *pxHigherPriorityTaskWoken ); + * @endcode + * + * See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. + * + * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for these + * functions to be available. + * + * A version of xTaskNotifyIndexed() that can be used from an interrupt service + * routine (ISR). + * + * Each task has a private array of "notification values" (or 'notifications'), + * each of which is a 32-bit unsigned integer (uint32_t). The constant + * configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the + * array, and (for backward compatibility) defaults to 1 if left undefined. + * Prior to FreeRTOS V10.4.0 there was only one notification value per task. + * + * Events can be sent to a task using an intermediary object. Examples of such + * objects are queues, semaphores, mutexes and event groups. Task notifications + * are a method of sending an event directly to a task without the need for such + * an intermediary object. + * + * A notification sent to a task can optionally perform an action, such as + * update, overwrite or increment one of the task's notification values. In + * that way task notifications can be used to send data to a task, or be used as + * light weight and fast binary or counting semaphores. + * + * A task can use xTaskNotifyWaitIndexed() to [optionally] block to wait for a + * notification to be pending, or ulTaskNotifyTakeIndexed() to [optionally] block + * to wait for a notification value to have a non-zero value. The task does + * not consume any CPU time while it is in the Blocked state. + * + * A notification sent to a task will remain pending until it is cleared by the + * task calling xTaskNotifyWaitIndexed() or ulTaskNotifyTakeIndexed() (or their + * un-indexed equivalents). If the task was already in the Blocked state to + * wait for a notification when the notification arrives then the task will + * automatically be removed from the Blocked state (unblocked) and the + * notification cleared. + * + * **NOTE** Each notification within the array operates independently - a task + * can only block on one notification within the array at a time and will not be + * unblocked by a notification sent to any other array index. + * + * Backward compatibility information: + * Prior to FreeRTOS V10.4.0 each task had a single "notification value", and + * all task notification API functions operated on that value. Replacing the + * single notification value with an array of notification values necessitated a + * new set of API functions that could address specific notifications within the + * array. xTaskNotifyFromISR() is the original API function, and remains + * backward compatible by always operating on the notification value at index 0 + * within the array. Calling xTaskNotifyFromISR() is equivalent to calling + * xTaskNotifyIndexedFromISR() with the uxIndexToNotify parameter set to 0. + * + * @param uxIndexToNotify The index within the target task's array of + * notification values to which the notification is to be sent. uxIndexToNotify + * must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyFromISR() + * does not have this parameter and always sends notifications to index 0. + * + * @param xTaskToNotify The handle of the task being notified. The handle to a + * task can be returned from the xTaskCreate() API function used to create the + * task, and the handle of the currently running task can be obtained by calling + * xTaskGetCurrentTaskHandle(). + * + * @param ulValue Data that can be sent with the notification. How the data is + * used depends on the value of the eAction parameter. + * + * @param eAction Specifies how the notification updates the task's notification + * value, if at all. Valid values for eAction are as follows: + * + * eSetBits - + * The task's notification value is bitwise ORed with ulValue. xTaskNotify() + * always returns pdPASS in this case. + * + * eIncrement - + * The task's notification value is incremented. ulValue is not used and + * xTaskNotify() always returns pdPASS in this case. + * + * eSetValueWithOverwrite - + * The task's notification value is set to the value of ulValue, even if the + * task being notified had not yet processed the previous notification (the + * task already had a notification pending). xTaskNotify() always returns + * pdPASS in this case. + * + * eSetValueWithoutOverwrite - + * If the task being notified did not already have a notification pending then + * the task's notification value is set to ulValue and xTaskNotify() will + * return pdPASS. If the task being notified already had a notification + * pending then no action is performed and pdFAIL is returned. + * + * eNoAction - + * The task receives a notification without its notification value being + * updated. ulValue is not used and xTaskNotify() always returns pdPASS in + * this case. + * + * @param pxHigherPriorityTaskWoken xTaskNotifyFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if sending the notification caused the + * task to which the notification was sent to leave the Blocked state, and the + * unblocked task has a priority higher than the currently running task. If + * xTaskNotifyFromISR() sets this value to pdTRUE then a context switch should + * be requested before the interrupt is exited. How a context switch is + * requested from an ISR is dependent on the port - see the documentation page + * for the port in use. + * + * @return Dependent on the value of eAction. See the description of the + * eAction parameter. + * + * \defgroup xTaskNotifyIndexedFromISR xTaskNotifyIndexedFromISR + * \ingroup TaskNotifications + */ +BaseType_t xTaskGenericNotifyFromISR( TaskHandle_t xTaskToNotify, + UBaseType_t uxIndexToNotify, + uint32_t ulValue, + eNotifyAction eAction, + uint32_t * pulPreviousNotificationValue, + BaseType_t * pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; +#define xTaskNotifyFromISR( xTaskToNotify, ulValue, eAction, pxHigherPriorityTaskWoken ) \ + xTaskGenericNotifyFromISR( ( xTaskToNotify ), ( tskDEFAULT_INDEX_TO_NOTIFY ), ( ulValue ), ( eAction ), NULL, ( pxHigherPriorityTaskWoken ) ) +#define xTaskNotifyIndexedFromISR( xTaskToNotify, uxIndexToNotify, ulValue, eAction, pxHigherPriorityTaskWoken ) \ + xTaskGenericNotifyFromISR( ( xTaskToNotify ), ( uxIndexToNotify ), ( ulValue ), ( eAction ), NULL, ( pxHigherPriorityTaskWoken ) ) + +/** + * task. h + * @code{c} + * BaseType_t xTaskNotifyAndQueryIndexedFromISR( TaskHandle_t xTaskToNotify, UBaseType_t uxIndexToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue, BaseType_t *pxHigherPriorityTaskWoken ); + * BaseType_t xTaskNotifyAndQueryFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue, BaseType_t *pxHigherPriorityTaskWoken ); + * @endcode + * + * See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. + * + * xTaskNotifyAndQueryIndexedFromISR() performs the same operation as + * xTaskNotifyIndexedFromISR() with the addition that it also returns the + * subject task's prior notification value (the notification value at the time + * the function is called rather than at the time the function returns) in the + * additional pulPreviousNotifyValue parameter. + * + * xTaskNotifyAndQueryFromISR() performs the same operation as + * xTaskNotifyFromISR() with the addition that it also returns the subject + * task's prior notification value (the notification value at the time the + * function is called rather than at the time the function returns) in the + * additional pulPreviousNotifyValue parameter. + * + * \defgroup xTaskNotifyAndQueryIndexedFromISR xTaskNotifyAndQueryIndexedFromISR + * \ingroup TaskNotifications + */ +#define xTaskNotifyAndQueryIndexedFromISR( xTaskToNotify, uxIndexToNotify, ulValue, eAction, pulPreviousNotificationValue, pxHigherPriorityTaskWoken ) \ + xTaskGenericNotifyFromISR( ( xTaskToNotify ), ( uxIndexToNotify ), ( ulValue ), ( eAction ), ( pulPreviousNotificationValue ), ( pxHigherPriorityTaskWoken ) ) +#define xTaskNotifyAndQueryFromISR( xTaskToNotify, ulValue, eAction, pulPreviousNotificationValue, pxHigherPriorityTaskWoken ) \ + xTaskGenericNotifyFromISR( ( xTaskToNotify ), ( tskDEFAULT_INDEX_TO_NOTIFY ), ( ulValue ), ( eAction ), ( pulPreviousNotificationValue ), ( pxHigherPriorityTaskWoken ) ) + +/** + * task. h + * @code{c} + * BaseType_t xTaskNotifyWaitIndexed( UBaseType_t uxIndexToWaitOn, uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait ); + * + * BaseType_t xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait ); + * @endcode + * + * Waits for a direct to task notification to be pending at a given index within + * an array of direct to task notifications. + * + * See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. + * + * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this + * function to be available. + * + * Each task has a private array of "notification values" (or 'notifications'), + * each of which is a 32-bit unsigned integer (uint32_t). The constant + * configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the + * array, and (for backward compatibility) defaults to 1 if left undefined. + * Prior to FreeRTOS V10.4.0 there was only one notification value per task. + * + * Events can be sent to a task using an intermediary object. Examples of such + * objects are queues, semaphores, mutexes and event groups. Task notifications + * are a method of sending an event directly to a task without the need for such + * an intermediary object. + * + * A notification sent to a task can optionally perform an action, such as + * update, overwrite or increment one of the task's notification values. In + * that way task notifications can be used to send data to a task, or be used as + * light weight and fast binary or counting semaphores. + * + * A notification sent to a task will remain pending until it is cleared by the + * task calling xTaskNotifyWaitIndexed() or ulTaskNotifyTakeIndexed() (or their + * un-indexed equivalents). If the task was already in the Blocked state to + * wait for a notification when the notification arrives then the task will + * automatically be removed from the Blocked state (unblocked) and the + * notification cleared. + * + * A task can use xTaskNotifyWaitIndexed() to [optionally] block to wait for a + * notification to be pending, or ulTaskNotifyTakeIndexed() to [optionally] block + * to wait for a notification value to have a non-zero value. The task does + * not consume any CPU time while it is in the Blocked state. + * + * **NOTE** Each notification within the array operates independently - a task + * can only block on one notification within the array at a time and will not be + * unblocked by a notification sent to any other array index. + * + * Backward compatibility information: + * Prior to FreeRTOS V10.4.0 each task had a single "notification value", and + * all task notification API functions operated on that value. Replacing the + * single notification value with an array of notification values necessitated a + * new set of API functions that could address specific notifications within the + * array. xTaskNotifyWait() is the original API function, and remains backward + * compatible by always operating on the notification value at index 0 in the + * array. Calling xTaskNotifyWait() is equivalent to calling + * xTaskNotifyWaitIndexed() with the uxIndexToWaitOn parameter set to 0. + * + * @param uxIndexToWaitOn The index within the calling task's array of + * notification values on which the calling task will wait for a notification to + * be received. uxIndexToWaitOn must be less than + * configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyWait() does + * not have this parameter and always waits for notifications on index 0. + * + * @param ulBitsToClearOnEntry Bits that are set in ulBitsToClearOnEntry value + * will be cleared in the calling task's notification value before the task + * checks to see if any notifications are pending, and optionally blocks if no + * notifications are pending. Setting ulBitsToClearOnEntry to ULONG_MAX (if + * limits.h is included) or 0xffffffffUL (if limits.h is not included) will have + * the effect of resetting the task's notification value to 0. Setting + * ulBitsToClearOnEntry to 0 will leave the task's notification value unchanged. + * + * @param ulBitsToClearOnExit If a notification is pending or received before + * the calling task exits the xTaskNotifyWait() function then the task's + * notification value (see the xTaskNotify() API function) is passed out using + * the pulNotificationValue parameter. Then any bits that are set in + * ulBitsToClearOnExit will be cleared in the task's notification value (note + * *pulNotificationValue is set before any bits are cleared). Setting + * ulBitsToClearOnExit to ULONG_MAX (if limits.h is included) or 0xffffffffUL + * (if limits.h is not included) will have the effect of resetting the task's + * notification value to 0 before the function exits. Setting + * ulBitsToClearOnExit to 0 will leave the task's notification value unchanged + * when the function exits (in which case the value passed out in + * pulNotificationValue will match the task's notification value). + * + * @param pulNotificationValue Used to pass the task's notification value out + * of the function. Note the value passed out will not be effected by the + * clearing of any bits caused by ulBitsToClearOnExit being non-zero. + * + * @param xTicksToWait The maximum amount of time that the task should wait in + * the Blocked state for a notification to be received, should a notification + * not already be pending when xTaskNotifyWait() was called. The task + * will not consume any processing time while it is in the Blocked state. This + * is specified in kernel ticks, the macro pdMS_TO_TICKS( value_in_ms ) can be + * used to convert a time specified in milliseconds to a time specified in + * ticks. + * + * @return If a notification was received (including notifications that were + * already pending when xTaskNotifyWait was called) then pdPASS is + * returned. Otherwise pdFAIL is returned. + * + * \defgroup xTaskNotifyWaitIndexed xTaskNotifyWaitIndexed + * \ingroup TaskNotifications + */ +BaseType_t xTaskGenericNotifyWait( UBaseType_t uxIndexToWaitOn, + uint32_t ulBitsToClearOnEntry, + uint32_t ulBitsToClearOnExit, + uint32_t * pulNotificationValue, + TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; +#define xTaskNotifyWait( ulBitsToClearOnEntry, ulBitsToClearOnExit, pulNotificationValue, xTicksToWait ) \ + xTaskGenericNotifyWait( tskDEFAULT_INDEX_TO_NOTIFY, ( ulBitsToClearOnEntry ), ( ulBitsToClearOnExit ), ( pulNotificationValue ), ( xTicksToWait ) ) +#define xTaskNotifyWaitIndexed( uxIndexToWaitOn, ulBitsToClearOnEntry, ulBitsToClearOnExit, pulNotificationValue, xTicksToWait ) \ + xTaskGenericNotifyWait( ( uxIndexToWaitOn ), ( ulBitsToClearOnEntry ), ( ulBitsToClearOnExit ), ( pulNotificationValue ), ( xTicksToWait ) ) + +/** + * task. h + * @code{c} + * BaseType_t xTaskNotifyGiveIndexed( TaskHandle_t xTaskToNotify, UBaseType_t uxIndexToNotify ); + * BaseType_t xTaskNotifyGive( TaskHandle_t xTaskToNotify ); + * @endcode + * + * Sends a direct to task notification to a particular index in the target + * task's notification array in a manner similar to giving a counting semaphore. + * + * See https://www.FreeRTOS.org/RTOS-task-notifications.html for more details. + * + * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for these + * macros to be available. + * + * Each task has a private array of "notification values" (or 'notifications'), + * each of which is a 32-bit unsigned integer (uint32_t). The constant + * configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the + * array, and (for backward compatibility) defaults to 1 if left undefined. + * Prior to FreeRTOS V10.4.0 there was only one notification value per task. + * + * Events can be sent to a task using an intermediary object. Examples of such + * objects are queues, semaphores, mutexes and event groups. Task notifications + * are a method of sending an event directly to a task without the need for such + * an intermediary object. + * + * A notification sent to a task can optionally perform an action, such as + * update, overwrite or increment one of the task's notification values. In + * that way task notifications can be used to send data to a task, or be used as + * light weight and fast binary or counting semaphores. + * + * xTaskNotifyGiveIndexed() is a helper macro intended for use when task + * notifications are used as light weight and faster binary or counting + * semaphore equivalents. Actual FreeRTOS semaphores are given using the + * xSemaphoreGive() API function, the equivalent action that instead uses a task + * notification is xTaskNotifyGiveIndexed(). + * + * When task notifications are being used as a binary or counting semaphore + * equivalent then the task being notified should wait for the notification + * using the ulTaskNotificationTakeIndexed() API function rather than the + * xTaskNotifyWaitIndexed() API function. + * + * **NOTE** Each notification within the array operates independently - a task + * can only block on one notification within the array at a time and will not be + * unblocked by a notification sent to any other array index. + * + * Backward compatibility information: + * Prior to FreeRTOS V10.4.0 each task had a single "notification value", and + * all task notification API functions operated on that value. Replacing the + * single notification value with an array of notification values necessitated a + * new set of API functions that could address specific notifications within the + * array. xTaskNotifyGive() is the original API function, and remains backward + * compatible by always operating on the notification value at index 0 in the + * array. Calling xTaskNotifyGive() is equivalent to calling + * xTaskNotifyGiveIndexed() with the uxIndexToNotify parameter set to 0. + * + * @param xTaskToNotify The handle of the task being notified. The handle to a + * task can be returned from the xTaskCreate() API function used to create the + * task, and the handle of the currently running task can be obtained by calling + * xTaskGetCurrentTaskHandle(). + * + * @param uxIndexToNotify The index within the target task's array of + * notification values to which the notification is to be sent. uxIndexToNotify + * must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyGive() + * does not have this parameter and always sends notifications to index 0. + * + * @return xTaskNotifyGive() is a macro that calls xTaskNotify() with the + * eAction parameter set to eIncrement - so pdPASS is always returned. + * + * \defgroup xTaskNotifyGiveIndexed xTaskNotifyGiveIndexed + * \ingroup TaskNotifications + */ +#define xTaskNotifyGive( xTaskToNotify ) \ + xTaskGenericNotify( ( xTaskToNotify ), ( tskDEFAULT_INDEX_TO_NOTIFY ), ( 0 ), eIncrement, NULL ) +#define xTaskNotifyGiveIndexed( xTaskToNotify, uxIndexToNotify ) \ + xTaskGenericNotify( ( xTaskToNotify ), ( uxIndexToNotify ), ( 0 ), eIncrement, NULL ) + +/** + * task. h + * @code{c} + * void vTaskNotifyGiveIndexedFromISR( TaskHandle_t xTaskHandle, UBaseType_t uxIndexToNotify, BaseType_t *pxHigherPriorityTaskWoken ); + * void vTaskNotifyGiveFromISR( TaskHandle_t xTaskHandle, BaseType_t *pxHigherPriorityTaskWoken ); + * @endcode + * + * A version of xTaskNotifyGiveIndexed() that can be called from an interrupt + * service routine (ISR). + * + * See https://www.FreeRTOS.org/RTOS-task-notifications.html for more details. + * + * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this macro + * to be available. + * + * Each task has a private array of "notification values" (or 'notifications'), + * each of which is a 32-bit unsigned integer (uint32_t). The constant + * configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the + * array, and (for backward compatibility) defaults to 1 if left undefined. + * Prior to FreeRTOS V10.4.0 there was only one notification value per task. + * + * Events can be sent to a task using an intermediary object. Examples of such + * objects are queues, semaphores, mutexes and event groups. Task notifications + * are a method of sending an event directly to a task without the need for such + * an intermediary object. + * + * A notification sent to a task can optionally perform an action, such as + * update, overwrite or increment one of the task's notification values. In + * that way task notifications can be used to send data to a task, or be used as + * light weight and fast binary or counting semaphores. + * + * vTaskNotifyGiveIndexedFromISR() is intended for use when task notifications + * are used as light weight and faster binary or counting semaphore equivalents. + * Actual FreeRTOS semaphores are given from an ISR using the + * xSemaphoreGiveFromISR() API function, the equivalent action that instead uses + * a task notification is vTaskNotifyGiveIndexedFromISR(). + * + * When task notifications are being used as a binary or counting semaphore + * equivalent then the task being notified should wait for the notification + * using the ulTaskNotificationTakeIndexed() API function rather than the + * xTaskNotifyWaitIndexed() API function. + * + * **NOTE** Each notification within the array operates independently - a task + * can only block on one notification within the array at a time and will not be + * unblocked by a notification sent to any other array index. + * + * Backward compatibility information: + * Prior to FreeRTOS V10.4.0 each task had a single "notification value", and + * all task notification API functions operated on that value. Replacing the + * single notification value with an array of notification values necessitated a + * new set of API functions that could address specific notifications within the + * array. xTaskNotifyFromISR() is the original API function, and remains + * backward compatible by always operating on the notification value at index 0 + * within the array. Calling xTaskNotifyGiveFromISR() is equivalent to calling + * xTaskNotifyGiveIndexedFromISR() with the uxIndexToNotify parameter set to 0. + * + * @param xTaskToNotify The handle of the task being notified. The handle to a + * task can be returned from the xTaskCreate() API function used to create the + * task, and the handle of the currently running task can be obtained by calling + * xTaskGetCurrentTaskHandle(). + * + * @param uxIndexToNotify The index within the target task's array of + * notification values to which the notification is to be sent. uxIndexToNotify + * must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. + * xTaskNotifyGiveFromISR() does not have this parameter and always sends + * notifications to index 0. + * + * @param pxHigherPriorityTaskWoken vTaskNotifyGiveFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if sending the notification caused the + * task to which the notification was sent to leave the Blocked state, and the + * unblocked task has a priority higher than the currently running task. If + * vTaskNotifyGiveFromISR() sets this value to pdTRUE then a context switch + * should be requested before the interrupt is exited. How a context switch is + * requested from an ISR is dependent on the port - see the documentation page + * for the port in use. + * + * \defgroup vTaskNotifyGiveIndexedFromISR vTaskNotifyGiveIndexedFromISR + * \ingroup TaskNotifications + */ +void vTaskGenericNotifyGiveFromISR( TaskHandle_t xTaskToNotify, + UBaseType_t uxIndexToNotify, + BaseType_t * pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; +#define vTaskNotifyGiveFromISR( xTaskToNotify, pxHigherPriorityTaskWoken ) \ + vTaskGenericNotifyGiveFromISR( ( xTaskToNotify ), ( tskDEFAULT_INDEX_TO_NOTIFY ), ( pxHigherPriorityTaskWoken ) ); +#define vTaskNotifyGiveIndexedFromISR( xTaskToNotify, uxIndexToNotify, pxHigherPriorityTaskWoken ) \ + vTaskGenericNotifyGiveFromISR( ( xTaskToNotify ), ( uxIndexToNotify ), ( pxHigherPriorityTaskWoken ) ); + +/** + * task. h + * @code{c} + * uint32_t ulTaskNotifyTakeIndexed( UBaseType_t uxIndexToWaitOn, BaseType_t xClearCountOnExit, TickType_t xTicksToWait ); + * + * uint32_t ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait ); + * @endcode + * + * Waits for a direct to task notification on a particular index in the calling + * task's notification array in a manner similar to taking a counting semaphore. + * + * See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. + * + * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this + * function to be available. + * + * Each task has a private array of "notification values" (or 'notifications'), + * each of which is a 32-bit unsigned integer (uint32_t). The constant + * configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the + * array, and (for backward compatibility) defaults to 1 if left undefined. + * Prior to FreeRTOS V10.4.0 there was only one notification value per task. + * + * Events can be sent to a task using an intermediary object. Examples of such + * objects are queues, semaphores, mutexes and event groups. Task notifications + * are a method of sending an event directly to a task without the need for such + * an intermediary object. + * + * A notification sent to a task can optionally perform an action, such as + * update, overwrite or increment one of the task's notification values. In + * that way task notifications can be used to send data to a task, or be used as + * light weight and fast binary or counting semaphores. + * + * ulTaskNotifyTakeIndexed() is intended for use when a task notification is + * used as a faster and lighter weight binary or counting semaphore alternative. + * Actual FreeRTOS semaphores are taken using the xSemaphoreTake() API function, + * the equivalent action that instead uses a task notification is + * ulTaskNotifyTakeIndexed(). + * + * When a task is using its notification value as a binary or counting semaphore + * other tasks should send notifications to it using the xTaskNotifyGiveIndexed() + * macro, or xTaskNotifyIndex() function with the eAction parameter set to + * eIncrement. + * + * ulTaskNotifyTakeIndexed() can either clear the task's notification value at + * the array index specified by the uxIndexToWaitOn parameter to zero on exit, + * in which case the notification value acts like a binary semaphore, or + * decrement the notification value on exit, in which case the notification + * value acts like a counting semaphore. + * + * A task can use ulTaskNotifyTakeIndexed() to [optionally] block to wait for + * a notification. The task does not consume any CPU time while it is in the + * Blocked state. + * + * Where as xTaskNotifyWaitIndexed() will return when a notification is pending, + * ulTaskNotifyTakeIndexed() will return when the task's notification value is + * not zero. + * + * **NOTE** Each notification within the array operates independently - a task + * can only block on one notification within the array at a time and will not be + * unblocked by a notification sent to any other array index. + * + * Backward compatibility information: + * Prior to FreeRTOS V10.4.0 each task had a single "notification value", and + * all task notification API functions operated on that value. Replacing the + * single notification value with an array of notification values necessitated a + * new set of API functions that could address specific notifications within the + * array. ulTaskNotifyTake() is the original API function, and remains backward + * compatible by always operating on the notification value at index 0 in the + * array. Calling ulTaskNotifyTake() is equivalent to calling + * ulTaskNotifyTakeIndexed() with the uxIndexToWaitOn parameter set to 0. + * + * @param uxIndexToWaitOn The index within the calling task's array of + * notification values on which the calling task will wait for a notification to + * be non-zero. uxIndexToWaitOn must be less than + * configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyTake() does + * not have this parameter and always waits for notifications on index 0. + * + * @param xClearCountOnExit if xClearCountOnExit is pdFALSE then the task's + * notification value is decremented when the function exits. In this way the + * notification value acts like a counting semaphore. If xClearCountOnExit is + * not pdFALSE then the task's notification value is cleared to zero when the + * function exits. In this way the notification value acts like a binary + * semaphore. + * + * @param xTicksToWait The maximum amount of time that the task should wait in + * the Blocked state for the task's notification value to be greater than zero, + * should the count not already be greater than zero when + * ulTaskNotifyTake() was called. The task will not consume any processing + * time while it is in the Blocked state. This is specified in kernel ticks, + * the macro pdMS_TO_TICKS( value_in_ms ) can be used to convert a time + * specified in milliseconds to a time specified in ticks. + * + * @return The task's notification count before it is either cleared to zero or + * decremented (see the xClearCountOnExit parameter). + * + * \defgroup ulTaskNotifyTakeIndexed ulTaskNotifyTakeIndexed + * \ingroup TaskNotifications + */ +uint32_t ulTaskGenericNotifyTake( UBaseType_t uxIndexToWaitOn, + BaseType_t xClearCountOnExit, + TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; +#define ulTaskNotifyTake( xClearCountOnExit, xTicksToWait ) \ + ulTaskGenericNotifyTake( ( tskDEFAULT_INDEX_TO_NOTIFY ), ( xClearCountOnExit ), ( xTicksToWait ) ) +#define ulTaskNotifyTakeIndexed( uxIndexToWaitOn, xClearCountOnExit, xTicksToWait ) \ + ulTaskGenericNotifyTake( ( uxIndexToWaitOn ), ( xClearCountOnExit ), ( xTicksToWait ) ) + +/** + * task. h + * @code{c} + * BaseType_t xTaskNotifyStateClearIndexed( TaskHandle_t xTask, UBaseType_t uxIndexToCLear ); + * + * BaseType_t xTaskNotifyStateClear( TaskHandle_t xTask ); + * @endcode + * + * See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. + * + * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for these + * functions to be available. + * + * Each task has a private array of "notification values" (or 'notifications'), + * each of which is a 32-bit unsigned integer (uint32_t). The constant + * configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the + * array, and (for backward compatibility) defaults to 1 if left undefined. + * Prior to FreeRTOS V10.4.0 there was only one notification value per task. + * + * If a notification is sent to an index within the array of notifications then + * the notification at that index is said to be 'pending' until it is read or + * explicitly cleared by the receiving task. xTaskNotifyStateClearIndexed() + * is the function that clears a pending notification without reading the + * notification value. The notification value at the same array index is not + * altered. Set xTask to NULL to clear the notification state of the calling + * task. + * + * Backward compatibility information: + * Prior to FreeRTOS V10.4.0 each task had a single "notification value", and + * all task notification API functions operated on that value. Replacing the + * single notification value with an array of notification values necessitated a + * new set of API functions that could address specific notifications within the + * array. xTaskNotifyStateClear() is the original API function, and remains + * backward compatible by always operating on the notification value at index 0 + * within the array. Calling xTaskNotifyStateClear() is equivalent to calling + * xTaskNotifyStateClearIndexed() with the uxIndexToNotify parameter set to 0. + * + * @param xTask The handle of the RTOS task that will have a notification state + * cleared. Set xTask to NULL to clear a notification state in the calling + * task. To obtain a task's handle create the task using xTaskCreate() and + * make use of the pxCreatedTask parameter, or create the task using + * xTaskCreateStatic() and store the returned value, or use the task's name in + * a call to xTaskGetHandle(). + * + * @param uxIndexToClear The index within the target task's array of + * notification values to act upon. For example, setting uxIndexToClear to 1 + * will clear the state of the notification at index 1 within the array. + * uxIndexToClear must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. + * ulTaskNotifyStateClear() does not have this parameter and always acts on the + * notification at index 0. + * + * @return pdTRUE if the task's notification state was set to + * eNotWaitingNotification, otherwise pdFALSE. + * + * \defgroup xTaskNotifyStateClearIndexed xTaskNotifyStateClearIndexed + * \ingroup TaskNotifications + */ +BaseType_t xTaskGenericNotifyStateClear( TaskHandle_t xTask, + UBaseType_t uxIndexToClear ) PRIVILEGED_FUNCTION; +#define xTaskNotifyStateClear( xTask ) \ + xTaskGenericNotifyStateClear( ( xTask ), ( tskDEFAULT_INDEX_TO_NOTIFY ) ) +#define xTaskNotifyStateClearIndexed( xTask, uxIndexToClear ) \ + xTaskGenericNotifyStateClear( ( xTask ), ( uxIndexToClear ) ) + +/** + * task. h + * @code{c} + * uint32_t ulTaskNotifyValueClearIndexed( TaskHandle_t xTask, UBaseType_t uxIndexToClear, uint32_t ulBitsToClear ); + * + * uint32_t ulTaskNotifyValueClear( TaskHandle_t xTask, uint32_t ulBitsToClear ); + * @endcode + * + * See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. + * + * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for these + * functions to be available. + * + * Each task has a private array of "notification values" (or 'notifications'), + * each of which is a 32-bit unsigned integer (uint32_t). The constant + * configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the + * array, and (for backward compatibility) defaults to 1 if left undefined. + * Prior to FreeRTOS V10.4.0 there was only one notification value per task. + * + * ulTaskNotifyValueClearIndexed() clears the bits specified by the + * ulBitsToClear bit mask in the notification value at array index uxIndexToClear + * of the task referenced by xTask. + * + * Backward compatibility information: + * Prior to FreeRTOS V10.4.0 each task had a single "notification value", and + * all task notification API functions operated on that value. Replacing the + * single notification value with an array of notification values necessitated a + * new set of API functions that could address specific notifications within the + * array. ulTaskNotifyValueClear() is the original API function, and remains + * backward compatible by always operating on the notification value at index 0 + * within the array. Calling ulTaskNotifyValueClear() is equivalent to calling + * ulTaskNotifyValueClearIndexed() with the uxIndexToClear parameter set to 0. + * + * @param xTask The handle of the RTOS task that will have bits in one of its + * notification values cleared. Set xTask to NULL to clear bits in a + * notification value of the calling task. To obtain a task's handle create the + * task using xTaskCreate() and make use of the pxCreatedTask parameter, or + * create the task using xTaskCreateStatic() and store the returned value, or + * use the task's name in a call to xTaskGetHandle(). + * + * @param uxIndexToClear The index within the target task's array of + * notification values in which to clear the bits. uxIndexToClear + * must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. + * ulTaskNotifyValueClear() does not have this parameter and always clears bits + * in the notification value at index 0. + * + * @param ulBitsToClear Bit mask of the bits to clear in the notification value of + * xTask. Set a bit to 1 to clear the corresponding bits in the task's notification + * value. Set ulBitsToClear to 0xffffffff (UINT_MAX on 32-bit architectures) to clear + * the notification value to 0. Set ulBitsToClear to 0 to query the task's + * notification value without clearing any bits. + * + * + * @return The value of the target task's notification value before the bits + * specified by ulBitsToClear were cleared. + * \defgroup ulTaskNotifyValueClear ulTaskNotifyValueClear + * \ingroup TaskNotifications + */ +uint32_t ulTaskGenericNotifyValueClear( TaskHandle_t xTask, + UBaseType_t uxIndexToClear, + uint32_t ulBitsToClear ) PRIVILEGED_FUNCTION; +#define ulTaskNotifyValueClear( xTask, ulBitsToClear ) \ + ulTaskGenericNotifyValueClear( ( xTask ), ( tskDEFAULT_INDEX_TO_NOTIFY ), ( ulBitsToClear ) ) +#define ulTaskNotifyValueClearIndexed( xTask, uxIndexToClear, ulBitsToClear ) \ + ulTaskGenericNotifyValueClear( ( xTask ), ( uxIndexToClear ), ( ulBitsToClear ) ) + +/** + * task.h + * @code{c} + * void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ); + * @endcode + * + * Capture the current time for future use with xTaskCheckForTimeOut(). + * + * @param pxTimeOut Pointer to a timeout object into which the current time + * is to be captured. The captured time includes the tick count and the number + * of times the tick count has overflowed since the system first booted. + * \defgroup vTaskSetTimeOutState vTaskSetTimeOutState + * \ingroup TaskCtrl + */ +void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) PRIVILEGED_FUNCTION; + +/** + * task.h + * @code{c} + * BaseType_t xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, TickType_t * const pxTicksToWait ); + * @endcode + * + * Determines if pxTicksToWait ticks has passed since a time was captured + * using a call to vTaskSetTimeOutState(). The captured time includes the tick + * count and the number of times the tick count has overflowed. + * + * @param pxTimeOut The time status as captured previously using + * vTaskSetTimeOutState. If the timeout has not yet occurred, it is updated + * to reflect the current time status. + * @param pxTicksToWait The number of ticks to check for timeout i.e. if + * pxTicksToWait ticks have passed since pxTimeOut was last updated (either by + * vTaskSetTimeOutState() or xTaskCheckForTimeOut()), the timeout has occurred. + * If the timeout has not occurred, pxTicksToWait is updated to reflect the + * number of remaining ticks. + * + * @return If timeout has occurred, pdTRUE is returned. Otherwise pdFALSE is + * returned and pxTicksToWait is updated to reflect the number of remaining + * ticks. + * + * @see https://www.FreeRTOS.org/xTaskCheckForTimeOut.html + * + * Example Usage: + * @code{c} + * // Driver library function used to receive uxWantedBytes from an Rx buffer + * // that is filled by a UART interrupt. If there are not enough bytes in the + * // Rx buffer then the task enters the Blocked state until it is notified that + * // more data has been placed into the buffer. If there is still not enough + * // data then the task re-enters the Blocked state, and xTaskCheckForTimeOut() + * // is used to re-calculate the Block time to ensure the total amount of time + * // spent in the Blocked state does not exceed MAX_TIME_TO_WAIT. This + * // continues until either the buffer contains at least uxWantedBytes bytes, + * // or the total amount of time spent in the Blocked state reaches + * // MAX_TIME_TO_WAIT - at which point the task reads however many bytes are + * // available up to a maximum of uxWantedBytes. + * + * size_t xUART_Receive( uint8_t *pucBuffer, size_t uxWantedBytes ) + * { + * size_t uxReceived = 0; + * TickType_t xTicksToWait = MAX_TIME_TO_WAIT; + * TimeOut_t xTimeOut; + * + * // Initialize xTimeOut. This records the time at which this function + * // was entered. + * vTaskSetTimeOutState( &xTimeOut ); + * + * // Loop until the buffer contains the wanted number of bytes, or a + * // timeout occurs. + * while( UART_bytes_in_rx_buffer( pxUARTInstance ) < uxWantedBytes ) + * { + * // The buffer didn't contain enough data so this task is going to + * // enter the Blocked state. Adjusting xTicksToWait to account for + * // any time that has been spent in the Blocked state within this + * // function so far to ensure the total amount of time spent in the + * // Blocked state does not exceed MAX_TIME_TO_WAIT. + * if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) != pdFALSE ) + * { + * //Timed out before the wanted number of bytes were available, + * // exit the loop. + * break; + * } + * + * // Wait for a maximum of xTicksToWait ticks to be notified that the + * // receive interrupt has placed more data into the buffer. + * ulTaskNotifyTake( pdTRUE, xTicksToWait ); + * } + * + * // Attempt to read uxWantedBytes from the receive buffer into pucBuffer. + * // The actual number of bytes read (which might be less than + * // uxWantedBytes) is returned. + * uxReceived = UART_read_from_receive_buffer( pxUARTInstance, + * pucBuffer, + * uxWantedBytes ); + * + * return uxReceived; + * } + * @endcode + * \defgroup xTaskCheckForTimeOut xTaskCheckForTimeOut + * \ingroup TaskCtrl + */ +BaseType_t xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, + TickType_t * const pxTicksToWait ) PRIVILEGED_FUNCTION; + +/** + * task.h + * @code{c} + * BaseType_t xTaskCatchUpTicks( TickType_t xTicksToCatchUp ); + * @endcode + * + * This function corrects the tick count value after the application code has held + * interrupts disabled for an extended period resulting in tick interrupts having + * been missed. + * + * This function is similar to vTaskStepTick(), however, unlike + * vTaskStepTick(), xTaskCatchUpTicks() may move the tick count forward past a + * time at which a task should be removed from the blocked state. That means + * tasks may have to be removed from the blocked state as the tick count is + * moved. + * + * @param xTicksToCatchUp The number of tick interrupts that have been missed due to + * interrupts being disabled. Its value is not computed automatically, so must be + * computed by the application writer. + * + * @return pdTRUE if moving the tick count forward resulted in a task leaving the + * blocked state and a context switch being performed. Otherwise pdFALSE. + * + * \defgroup xTaskCatchUpTicks xTaskCatchUpTicks + * \ingroup TaskCtrl + */ +BaseType_t xTaskCatchUpTicks( TickType_t xTicksToCatchUp ) PRIVILEGED_FUNCTION; + + +/*----------------------------------------------------------- +* SCHEDULER INTERNALS AVAILABLE FOR PORTING PURPOSES +*----------------------------------------------------------*/ + +/* + * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS ONLY + * INTENDED FOR USE WHEN IMPLEMENTING A PORT OF THE SCHEDULER AND IS + * AN INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER. + * + * Called from the real time kernel tick (either preemptive or cooperative), + * this increments the tick count and checks if any tasks that are blocked + * for a finite period required removing from a blocked list and placing on + * a ready list. If a non-zero value is returned then a context switch is + * required because either: + * + A task was removed from a blocked list because its timeout had expired, + * or + * + Time slicing is in use and there is a task of equal priority to the + * currently running task. + */ +BaseType_t xTaskIncrementTick( void ) PRIVILEGED_FUNCTION; + +/* + * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS AN + * INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER. + * + * THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED. + * + * Removes the calling task from the ready list and places it both + * on the list of tasks waiting for a particular event, and the + * list of delayed tasks. The task will be removed from both lists + * and replaced on the ready list should either the event occur (and + * there be no higher priority tasks waiting on the same event) or + * the delay period expires. + * + * The 'unordered' version replaces the event list item value with the + * xItemValue value, and inserts the list item at the end of the list. + * + * The 'ordered' version uses the existing event list item value (which is the + * owning task's priority) to insert the list item into the event list in task + * priority order. + * + * @param pxEventList The list containing tasks that are blocked waiting + * for the event to occur. + * + * @param xItemValue The item value to use for the event list item when the + * event list is not ordered by task priority. + * + * @param xTicksToWait The maximum amount of time that the task should wait + * for the event to occur. This is specified in kernel ticks, the constant + * portTICK_PERIOD_MS can be used to convert kernel ticks into a real time + * period. + */ +void vTaskPlaceOnEventList( List_t * const pxEventList, + const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; +void vTaskPlaceOnUnorderedEventList( List_t * pxEventList, + const TickType_t xItemValue, + const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/* + * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS AN + * INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER. + * + * THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED. + * + * This function performs nearly the same function as vTaskPlaceOnEventList(). + * The difference being that this function does not permit tasks to block + * indefinitely, whereas vTaskPlaceOnEventList() does. + * + */ +void vTaskPlaceOnEventListRestricted( List_t * const pxEventList, + TickType_t xTicksToWait, + const BaseType_t xWaitIndefinitely ) PRIVILEGED_FUNCTION; + +/* + * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS AN + * INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER. + * + * THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED. + * + * Removes a task from both the specified event list and the list of blocked + * tasks, and places it on a ready queue. + * + * xTaskRemoveFromEventList()/vTaskRemoveFromUnorderedEventList() will be called + * if either an event occurs to unblock a task, or the block timeout period + * expires. + * + * xTaskRemoveFromEventList() is used when the event list is in task priority + * order. It removes the list item from the head of the event list as that will + * have the highest priority owning task of all the tasks on the event list. + * vTaskRemoveFromUnorderedEventList() is used when the event list is not + * ordered and the event list items hold something other than the owning tasks + * priority. In this case the event list item value is updated to the value + * passed in the xItemValue parameter. + * + * @return pdTRUE if the task being removed has a higher priority than the task + * making the call, otherwise pdFALSE. + */ +BaseType_t xTaskRemoveFromEventList( const List_t * const pxEventList ) PRIVILEGED_FUNCTION; +void vTaskRemoveFromUnorderedEventList( ListItem_t * pxEventListItem, + const TickType_t xItemValue ) PRIVILEGED_FUNCTION; + +/* + * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS ONLY + * INTENDED FOR USE WHEN IMPLEMENTING A PORT OF THE SCHEDULER AND IS + * AN INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER. + * + * Sets the pointer to the current TCB to the TCB of the highest priority task + * that is ready to run. + */ +portDONT_DISCARD void vTaskSwitchContext( void ) PRIVILEGED_FUNCTION; + +/* + * THESE FUNCTIONS MUST NOT BE USED FROM APPLICATION CODE. THEY ARE USED BY + * THE EVENT BITS MODULE. + */ +TickType_t uxTaskResetEventItemValue( void ) PRIVILEGED_FUNCTION; + +/* + * Return the handle of the calling task. + */ +TaskHandle_t xTaskGetCurrentTaskHandle( void ) PRIVILEGED_FUNCTION; + +/* + * Shortcut used by the queue implementation to prevent unnecessary call to + * taskYIELD(); + */ +void vTaskMissedYield( void ) PRIVILEGED_FUNCTION; + +/* + * Returns the scheduler state as taskSCHEDULER_RUNNING, + * taskSCHEDULER_NOT_STARTED or taskSCHEDULER_SUSPENDED. + */ +BaseType_t xTaskGetSchedulerState( void ) PRIVILEGED_FUNCTION; + +/* + * Raises the priority of the mutex holder to that of the calling task should + * the mutex holder have a priority less than the calling task. + */ +BaseType_t xTaskPriorityInherit( TaskHandle_t const pxMutexHolder ) PRIVILEGED_FUNCTION; + +/* + * Set the priority of a task back to its proper priority in the case that it + * inherited a higher priority while it was holding a semaphore. + */ +BaseType_t xTaskPriorityDisinherit( TaskHandle_t const pxMutexHolder ) PRIVILEGED_FUNCTION; + +/* + * If a higher priority task attempting to obtain a mutex caused a lower + * priority task to inherit the higher priority task's priority - but the higher + * priority task then timed out without obtaining the mutex, then the lower + * priority task will disinherit the priority again - but only down as far as + * the highest priority task that is still waiting for the mutex (if there were + * more than one task waiting for the mutex). + */ +void vTaskPriorityDisinheritAfterTimeout( TaskHandle_t const pxMutexHolder, + UBaseType_t uxHighestPriorityWaitingTask ) PRIVILEGED_FUNCTION; + +/* + * Get the uxTCBNumber assigned to the task referenced by the xTask parameter. + */ +UBaseType_t uxTaskGetTaskNumber( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +/* + * Set the uxTaskNumber of the task referenced by the xTask parameter to + * uxHandle. + */ +void vTaskSetTaskNumber( TaskHandle_t xTask, + const UBaseType_t uxHandle ) PRIVILEGED_FUNCTION; + +/* + * Only available when configUSE_TICKLESS_IDLE is set to 1. + * If tickless mode is being used, or a low power mode is implemented, then + * the tick interrupt will not execute during idle periods. When this is the + * case, the tick count value maintained by the scheduler needs to be kept up + * to date with the actual execution time by being skipped forward by a time + * equal to the idle period. + */ +void vTaskStepTick( const TickType_t xTicksToJump ) PRIVILEGED_FUNCTION; + +/* + * Only available when configUSE_TICKLESS_IDLE is set to 1. + * Provided for use within portSUPPRESS_TICKS_AND_SLEEP() to allow the port + * specific sleep function to determine if it is ok to proceed with the sleep, + * and if it is ok to proceed, if it is ok to sleep indefinitely. + * + * This function is necessary because portSUPPRESS_TICKS_AND_SLEEP() is only + * called with the scheduler suspended, not from within a critical section. It + * is therefore possible for an interrupt to request a context switch between + * portSUPPRESS_TICKS_AND_SLEEP() and the low power mode actually being + * entered. eTaskConfirmSleepModeStatus() should be called from a short + * critical section between the timer being stopped and the sleep mode being + * entered to ensure it is ok to proceed into the sleep mode. + */ +eSleepModeStatus eTaskConfirmSleepModeStatus( void ) PRIVILEGED_FUNCTION; + +/* + * For internal use only. Increment the mutex held count when a mutex is + * taken and return the handle of the task that has taken the mutex. + */ +TaskHandle_t pvTaskIncrementMutexHeldCount( void ) PRIVILEGED_FUNCTION; + +/* + * For internal use only. Same as vTaskSetTimeOutState(), but without a critical + * section. + */ +void vTaskInternalSetTimeOutState( TimeOut_t * const pxTimeOut ) PRIVILEGED_FUNCTION; + + +/* *INDENT-OFF* */ +#ifdef __cplusplus + } +#endif +/* *INDENT-ON* */ +#endif /* INC_TASK_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/timers.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/timers.h new file mode 100644 index 0000000..2be826c --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/include/timers.h @@ -0,0 +1,1355 @@ +/* + * FreeRTOS Kernel V10.4.6 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + + +#ifndef TIMERS_H +#define TIMERS_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h must appear in source files before include timers.h" +#endif + +/*lint -save -e537 This headers are only multiply included if the application code + * happens to also be including task.h. */ +#include "task.h" +/*lint -restore */ + +/* *INDENT-OFF* */ +#ifdef __cplusplus + extern "C" { +#endif +/* *INDENT-ON* */ + +/*----------------------------------------------------------- +* MACROS AND DEFINITIONS +*----------------------------------------------------------*/ + +/* IDs for commands that can be sent/received on the timer queue. These are to + * be used solely through the macros that make up the public software timer API, + * as defined below. The commands that are sent from interrupts must use the + * highest numbers as tmrFIRST_FROM_ISR_COMMAND is used to determine if the task + * or interrupt version of the queue send function should be used. */ +#define tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR ( ( BaseType_t ) -2 ) +#define tmrCOMMAND_EXECUTE_CALLBACK ( ( BaseType_t ) -1 ) +#define tmrCOMMAND_START_DONT_TRACE ( ( BaseType_t ) 0 ) +#define tmrCOMMAND_START ( ( BaseType_t ) 1 ) +#define tmrCOMMAND_RESET ( ( BaseType_t ) 2 ) +#define tmrCOMMAND_STOP ( ( BaseType_t ) 3 ) +#define tmrCOMMAND_CHANGE_PERIOD ( ( BaseType_t ) 4 ) +#define tmrCOMMAND_DELETE ( ( BaseType_t ) 5 ) + +#define tmrFIRST_FROM_ISR_COMMAND ( ( BaseType_t ) 6 ) +#define tmrCOMMAND_START_FROM_ISR ( ( BaseType_t ) 6 ) +#define tmrCOMMAND_RESET_FROM_ISR ( ( BaseType_t ) 7 ) +#define tmrCOMMAND_STOP_FROM_ISR ( ( BaseType_t ) 8 ) +#define tmrCOMMAND_CHANGE_PERIOD_FROM_ISR ( ( BaseType_t ) 9 ) + + +/** + * Type by which software timers are referenced. For example, a call to + * xTimerCreate() returns an TimerHandle_t variable that can then be used to + * reference the subject timer in calls to other software timer API functions + * (for example, xTimerStart(), xTimerReset(), etc.). + */ +struct tmrTimerControl; /* The old naming convention is used to prevent breaking kernel aware debuggers. */ +typedef struct tmrTimerControl * TimerHandle_t; + +/* + * Defines the prototype to which timer callback functions must conform. + */ +typedef void (* TimerCallbackFunction_t)( TimerHandle_t xTimer ); + +/* + * Defines the prototype to which functions used with the + * xTimerPendFunctionCallFromISR() function must conform. + */ +typedef void (* PendedFunction_t)( void *, + uint32_t ); + +/** + * TimerHandle_t xTimerCreate( const char * const pcTimerName, + * TickType_t xTimerPeriodInTicks, + * UBaseType_t uxAutoReload, + * void * pvTimerID, + * TimerCallbackFunction_t pxCallbackFunction ); + * + * Creates a new software timer instance, and returns a handle by which the + * created software timer can be referenced. + * + * Internally, within the FreeRTOS implementation, software timers use a block + * of memory, in which the timer data structure is stored. If a software timer + * is created using xTimerCreate() then the required memory is automatically + * dynamically allocated inside the xTimerCreate() function. (see + * https://www.FreeRTOS.org/a00111.html). If a software timer is created using + * xTimerCreateStatic() then the application writer must provide the memory that + * will get used by the software timer. xTimerCreateStatic() therefore allows a + * software timer to be created without using any dynamic memory allocation. + * + * Timers are created in the dormant state. The xTimerStart(), xTimerReset(), + * xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and + * xTimerChangePeriodFromISR() API functions can all be used to transition a + * timer into the active state. + * + * @param pcTimerName A text name that is assigned to the timer. This is done + * purely to assist debugging. The kernel itself only ever references a timer + * by its handle, and never by its name. + * + * @param xTimerPeriodInTicks The timer period. The time is defined in tick + * periods so the constant portTICK_PERIOD_MS can be used to convert a time that + * has been specified in milliseconds. For example, if the timer must expire + * after 100 ticks, then xTimerPeriodInTicks should be set to 100. + * Alternatively, if the timer must expire after 500ms, then xPeriod can be set + * to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or + * equal to 1000. Time timer period must be greater than 0. + * + * @param uxAutoReload If uxAutoReload is set to pdTRUE then the timer will + * expire repeatedly with a frequency set by the xTimerPeriodInTicks parameter. + * If uxAutoReload is set to pdFALSE then the timer will be a one-shot timer and + * enter the dormant state after it expires. + * + * @param pvTimerID An identifier that is assigned to the timer being created. + * Typically this would be used in the timer callback function to identify which + * timer expired when the same callback function is assigned to more than one + * timer. + * + * @param pxCallbackFunction The function to call when the timer expires. + * Callback functions must have the prototype defined by TimerCallbackFunction_t, + * which is "void vCallbackFunction( TimerHandle_t xTimer );". + * + * @return If the timer is successfully created then a handle to the newly + * created timer is returned. If the timer cannot be created because there is + * insufficient FreeRTOS heap remaining to allocate the timer + * structures then NULL is returned. + * + * Example usage: + * @verbatim + * #define NUM_TIMERS 5 + * + * // An array to hold handles to the created timers. + * TimerHandle_t xTimers[ NUM_TIMERS ]; + * + * // An array to hold a count of the number of times each timer expires. + * int32_t lExpireCounters[ NUM_TIMERS ] = { 0 }; + * + * // Define a callback function that will be used by multiple timer instances. + * // The callback function does nothing but count the number of times the + * // associated timer expires, and stop the timer once the timer has expired + * // 10 times. + * void vTimerCallback( TimerHandle_t pxTimer ) + * { + * int32_t lArrayIndex; + * const int32_t xMaxExpiryCountBeforeStopping = 10; + * + * // Optionally do something if the pxTimer parameter is NULL. + * configASSERT( pxTimer ); + * + * // Which timer expired? + * lArrayIndex = ( int32_t ) pvTimerGetTimerID( pxTimer ); + * + * // Increment the number of times that pxTimer has expired. + * lExpireCounters[ lArrayIndex ] += 1; + * + * // If the timer has expired 10 times then stop it from running. + * if( lExpireCounters[ lArrayIndex ] == xMaxExpiryCountBeforeStopping ) + * { + * // Do not use a block time if calling a timer API function from a + * // timer callback function, as doing so could cause a deadlock! + * xTimerStop( pxTimer, 0 ); + * } + * } + * + * void main( void ) + * { + * int32_t x; + * + * // Create then start some timers. Starting the timers before the scheduler + * // has been started means the timers will start running immediately that + * // the scheduler starts. + * for( x = 0; x < NUM_TIMERS; x++ ) + * { + * xTimers[ x ] = xTimerCreate( "Timer", // Just a text name, not used by the kernel. + * ( 100 * x ), // The timer period in ticks. + * pdTRUE, // The timers will auto-reload themselves when they expire. + * ( void * ) x, // Assign each timer a unique id equal to its array index. + * vTimerCallback // Each timer calls the same callback when it expires. + * ); + * + * if( xTimers[ x ] == NULL ) + * { + * // The timer was not created. + * } + * else + * { + * // Start the timer. No block time is specified, and even if one was + * // it would be ignored because the scheduler has not yet been + * // started. + * if( xTimerStart( xTimers[ x ], 0 ) != pdPASS ) + * { + * // The timer could not be set into the Active state. + * } + * } + * } + * + * // ... + * // Create tasks here. + * // ... + * + * // Starting the scheduler will start the timers running as they have already + * // been set into the active state. + * vTaskStartScheduler(); + * + * // Should not reach here. + * for( ;; ); + * } + * @endverbatim + */ +#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + TimerHandle_t xTimerCreate( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction ) PRIVILEGED_FUNCTION; +#endif + +/** + * TimerHandle_t xTimerCreateStatic(const char * const pcTimerName, + * TickType_t xTimerPeriodInTicks, + * UBaseType_t uxAutoReload, + * void * pvTimerID, + * TimerCallbackFunction_t pxCallbackFunction, + * StaticTimer_t *pxTimerBuffer ); + * + * Creates a new software timer instance, and returns a handle by which the + * created software timer can be referenced. + * + * Internally, within the FreeRTOS implementation, software timers use a block + * of memory, in which the timer data structure is stored. If a software timer + * is created using xTimerCreate() then the required memory is automatically + * dynamically allocated inside the xTimerCreate() function. (see + * https://www.FreeRTOS.org/a00111.html). If a software timer is created using + * xTimerCreateStatic() then the application writer must provide the memory that + * will get used by the software timer. xTimerCreateStatic() therefore allows a + * software timer to be created without using any dynamic memory allocation. + * + * Timers are created in the dormant state. The xTimerStart(), xTimerReset(), + * xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and + * xTimerChangePeriodFromISR() API functions can all be used to transition a + * timer into the active state. + * + * @param pcTimerName A text name that is assigned to the timer. This is done + * purely to assist debugging. The kernel itself only ever references a timer + * by its handle, and never by its name. + * + * @param xTimerPeriodInTicks The timer period. The time is defined in tick + * periods so the constant portTICK_PERIOD_MS can be used to convert a time that + * has been specified in milliseconds. For example, if the timer must expire + * after 100 ticks, then xTimerPeriodInTicks should be set to 100. + * Alternatively, if the timer must expire after 500ms, then xPeriod can be set + * to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or + * equal to 1000. The timer period must be greater than 0. + * + * @param uxAutoReload If uxAutoReload is set to pdTRUE then the timer will + * expire repeatedly with a frequency set by the xTimerPeriodInTicks parameter. + * If uxAutoReload is set to pdFALSE then the timer will be a one-shot timer and + * enter the dormant state after it expires. + * + * @param pvTimerID An identifier that is assigned to the timer being created. + * Typically this would be used in the timer callback function to identify which + * timer expired when the same callback function is assigned to more than one + * timer. + * + * @param pxCallbackFunction The function to call when the timer expires. + * Callback functions must have the prototype defined by TimerCallbackFunction_t, + * which is "void vCallbackFunction( TimerHandle_t xTimer );". + * + * @param pxTimerBuffer Must point to a variable of type StaticTimer_t, which + * will be then be used to hold the software timer's data structures, removing + * the need for the memory to be allocated dynamically. + * + * @return If the timer is created then a handle to the created timer is + * returned. If pxTimerBuffer was NULL then NULL is returned. + * + * Example usage: + * @verbatim + * + * // The buffer used to hold the software timer's data structure. + * static StaticTimer_t xTimerBuffer; + * + * // A variable that will be incremented by the software timer's callback + * // function. + * UBaseType_t uxVariableToIncrement = 0; + * + * // A software timer callback function that increments a variable passed to + * // it when the software timer was created. After the 5th increment the + * // callback function stops the software timer. + * static void prvTimerCallback( TimerHandle_t xExpiredTimer ) + * { + * UBaseType_t *puxVariableToIncrement; + * BaseType_t xReturned; + * + * // Obtain the address of the variable to increment from the timer ID. + * puxVariableToIncrement = ( UBaseType_t * ) pvTimerGetTimerID( xExpiredTimer ); + * + * // Increment the variable to show the timer callback has executed. + * ( *puxVariableToIncrement )++; + * + * // If this callback has executed the required number of times, stop the + * // timer. + * if( *puxVariableToIncrement == 5 ) + * { + * // This is called from a timer callback so must not block. + * xTimerStop( xExpiredTimer, staticDONT_BLOCK ); + * } + * } + * + * + * void main( void ) + * { + * // Create the software time. xTimerCreateStatic() has an extra parameter + * // than the normal xTimerCreate() API function. The parameter is a pointer + * // to the StaticTimer_t structure that will hold the software timer + * // structure. If the parameter is passed as NULL then the structure will be + * // allocated dynamically, just as if xTimerCreate() had been called. + * xTimer = xTimerCreateStatic( "T1", // Text name for the task. Helps debugging only. Not used by FreeRTOS. + * xTimerPeriod, // The period of the timer in ticks. + * pdTRUE, // This is an auto-reload timer. + * ( void * ) &uxVariableToIncrement, // A variable incremented by the software timer's callback function + * prvTimerCallback, // The function to execute when the timer expires. + * &xTimerBuffer ); // The buffer that will hold the software timer structure. + * + * // The scheduler has not started yet so a block time is not used. + * xReturned = xTimerStart( xTimer, 0 ); + * + * // ... + * // Create tasks here. + * // ... + * + * // Starting the scheduler will start the timers running as they have already + * // been set into the active state. + * vTaskStartScheduler(); + * + * // Should not reach here. + * for( ;; ); + * } + * @endverbatim + */ +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + TimerHandle_t xTimerCreateStatic( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction, + StaticTimer_t * pxTimerBuffer ) PRIVILEGED_FUNCTION; +#endif /* configSUPPORT_STATIC_ALLOCATION */ + +/** + * void *pvTimerGetTimerID( TimerHandle_t xTimer ); + * + * Returns the ID assigned to the timer. + * + * IDs are assigned to timers using the pvTimerID parameter of the call to + * xTimerCreated() that was used to create the timer, and by calling the + * vTimerSetTimerID() API function. + * + * If the same callback function is assigned to multiple timers then the timer + * ID can be used as time specific (timer local) storage. + * + * @param xTimer The timer being queried. + * + * @return The ID assigned to the timer being queried. + * + * Example usage: + * + * See the xTimerCreate() API function example usage scenario. + */ +void * pvTimerGetTimerID( const TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; + +/** + * void vTimerSetTimerID( TimerHandle_t xTimer, void *pvNewID ); + * + * Sets the ID assigned to the timer. + * + * IDs are assigned to timers using the pvTimerID parameter of the call to + * xTimerCreated() that was used to create the timer. + * + * If the same callback function is assigned to multiple timers then the timer + * ID can be used as time specific (timer local) storage. + * + * @param xTimer The timer being updated. + * + * @param pvNewID The ID to assign to the timer. + * + * Example usage: + * + * See the xTimerCreate() API function example usage scenario. + */ +void vTimerSetTimerID( TimerHandle_t xTimer, + void * pvNewID ) PRIVILEGED_FUNCTION; + +/** + * BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer ); + * + * Queries a timer to see if it is active or dormant. + * + * A timer will be dormant if: + * 1) It has been created but not started, or + * 2) It is an expired one-shot timer that has not been restarted. + * + * Timers are created in the dormant state. The xTimerStart(), xTimerReset(), + * xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and + * xTimerChangePeriodFromISR() API functions can all be used to transition a timer into the + * active state. + * + * @param xTimer The timer being queried. + * + * @return pdFALSE will be returned if the timer is dormant. A value other than + * pdFALSE will be returned if the timer is active. + * + * Example usage: + * @verbatim + * // This function assumes xTimer has already been created. + * void vAFunction( TimerHandle_t xTimer ) + * { + * if( xTimerIsTimerActive( xTimer ) != pdFALSE ) // or more simply and equivalently "if( xTimerIsTimerActive( xTimer ) )" + * { + * // xTimer is active, do something. + * } + * else + * { + * // xTimer is not active, do something else. + * } + * } + * @endverbatim + */ +BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; + +/** + * TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ); + * + * Simply returns the handle of the timer service/daemon task. It it not valid + * to call xTimerGetTimerDaemonTaskHandle() before the scheduler has been started. + */ +TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ) PRIVILEGED_FUNCTION; + +/** + * BaseType_t xTimerStart( TimerHandle_t xTimer, TickType_t xTicksToWait ); + * + * Timer functionality is provided by a timer service/daemon task. Many of the + * public FreeRTOS timer API functions send commands to the timer service task + * through a queue called the timer command queue. The timer command queue is + * private to the kernel itself and is not directly accessible to application + * code. The length of the timer command queue is set by the + * configTIMER_QUEUE_LENGTH configuration constant. + * + * xTimerStart() starts a timer that was previously created using the + * xTimerCreate() API function. If the timer had already been started and was + * already in the active state, then xTimerStart() has equivalent functionality + * to the xTimerReset() API function. + * + * Starting a timer ensures the timer is in the active state. If the timer + * is not stopped, deleted, or reset in the mean time, the callback function + * associated with the timer will get called 'n' ticks after xTimerStart() was + * called, where 'n' is the timers defined period. + * + * It is valid to call xTimerStart() before the scheduler has been started, but + * when this is done the timer will not actually start until the scheduler is + * started, and the timers expiry time will be relative to when the scheduler is + * started, not relative to when xTimerStart() was called. + * + * The configUSE_TIMERS configuration constant must be set to 1 for xTimerStart() + * to be available. + * + * @param xTimer The handle of the timer being started/restarted. + * + * @param xTicksToWait Specifies the time, in ticks, that the calling task should + * be held in the Blocked state to wait for the start command to be successfully + * sent to the timer command queue, should the queue already be full when + * xTimerStart() was called. xTicksToWait is ignored if xTimerStart() is called + * before the scheduler is started. + * + * @return pdFAIL will be returned if the start command could not be sent to + * the timer command queue even after xTicksToWait ticks had passed. pdPASS will + * be returned if the command was successfully sent to the timer command queue. + * When the command is actually processed will depend on the priority of the + * timer service/daemon task relative to other tasks in the system, although the + * timers expiry time is relative to when xTimerStart() is actually called. The + * timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY + * configuration constant. + * + * Example usage: + * + * See the xTimerCreate() API function example usage scenario. + * + */ +#define xTimerStart( xTimer, xTicksToWait ) \ + xTimerGenericCommand( ( xTimer ), tmrCOMMAND_START, ( xTaskGetTickCount() ), NULL, ( xTicksToWait ) ) + +/** + * BaseType_t xTimerStop( TimerHandle_t xTimer, TickType_t xTicksToWait ); + * + * Timer functionality is provided by a timer service/daemon task. Many of the + * public FreeRTOS timer API functions send commands to the timer service task + * through a queue called the timer command queue. The timer command queue is + * private to the kernel itself and is not directly accessible to application + * code. The length of the timer command queue is set by the + * configTIMER_QUEUE_LENGTH configuration constant. + * + * xTimerStop() stops a timer that was previously started using either of the + * The xTimerStart(), xTimerReset(), xTimerStartFromISR(), xTimerResetFromISR(), + * xTimerChangePeriod() or xTimerChangePeriodFromISR() API functions. + * + * Stopping a timer ensures the timer is not in the active state. + * + * The configUSE_TIMERS configuration constant must be set to 1 for xTimerStop() + * to be available. + * + * @param xTimer The handle of the timer being stopped. + * + * @param xTicksToWait Specifies the time, in ticks, that the calling task should + * be held in the Blocked state to wait for the stop command to be successfully + * sent to the timer command queue, should the queue already be full when + * xTimerStop() was called. xTicksToWait is ignored if xTimerStop() is called + * before the scheduler is started. + * + * @return pdFAIL will be returned if the stop command could not be sent to + * the timer command queue even after xTicksToWait ticks had passed. pdPASS will + * be returned if the command was successfully sent to the timer command queue. + * When the command is actually processed will depend on the priority of the + * timer service/daemon task relative to other tasks in the system. The timer + * service/daemon task priority is set by the configTIMER_TASK_PRIORITY + * configuration constant. + * + * Example usage: + * + * See the xTimerCreate() API function example usage scenario. + * + */ +#define xTimerStop( xTimer, xTicksToWait ) \ + xTimerGenericCommand( ( xTimer ), tmrCOMMAND_STOP, 0U, NULL, ( xTicksToWait ) ) + +/** + * BaseType_t xTimerChangePeriod( TimerHandle_t xTimer, + * TickType_t xNewPeriod, + * TickType_t xTicksToWait ); + * + * Timer functionality is provided by a timer service/daemon task. Many of the + * public FreeRTOS timer API functions send commands to the timer service task + * through a queue called the timer command queue. The timer command queue is + * private to the kernel itself and is not directly accessible to application + * code. The length of the timer command queue is set by the + * configTIMER_QUEUE_LENGTH configuration constant. + * + * xTimerChangePeriod() changes the period of a timer that was previously + * created using the xTimerCreate() API function. + * + * xTimerChangePeriod() can be called to change the period of an active or + * dormant state timer. + * + * The configUSE_TIMERS configuration constant must be set to 1 for + * xTimerChangePeriod() to be available. + * + * @param xTimer The handle of the timer that is having its period changed. + * + * @param xNewPeriod The new period for xTimer. Timer periods are specified in + * tick periods, so the constant portTICK_PERIOD_MS can be used to convert a time + * that has been specified in milliseconds. For example, if the timer must + * expire after 100 ticks, then xNewPeriod should be set to 100. Alternatively, + * if the timer must expire after 500ms, then xNewPeriod can be set to + * ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than + * or equal to 1000. + * + * @param xTicksToWait Specifies the time, in ticks, that the calling task should + * be held in the Blocked state to wait for the change period command to be + * successfully sent to the timer command queue, should the queue already be + * full when xTimerChangePeriod() was called. xTicksToWait is ignored if + * xTimerChangePeriod() is called before the scheduler is started. + * + * @return pdFAIL will be returned if the change period command could not be + * sent to the timer command queue even after xTicksToWait ticks had passed. + * pdPASS will be returned if the command was successfully sent to the timer + * command queue. When the command is actually processed will depend on the + * priority of the timer service/daemon task relative to other tasks in the + * system. The timer service/daemon task priority is set by the + * configTIMER_TASK_PRIORITY configuration constant. + * + * Example usage: + * @verbatim + * // This function assumes xTimer has already been created. If the timer + * // referenced by xTimer is already active when it is called, then the timer + * // is deleted. If the timer referenced by xTimer is not active when it is + * // called, then the period of the timer is set to 500ms and the timer is + * // started. + * void vAFunction( TimerHandle_t xTimer ) + * { + * if( xTimerIsTimerActive( xTimer ) != pdFALSE ) // or more simply and equivalently "if( xTimerIsTimerActive( xTimer ) )" + * { + * // xTimer is already active - delete it. + * xTimerDelete( xTimer ); + * } + * else + * { + * // xTimer is not active, change its period to 500ms. This will also + * // cause the timer to start. Block for a maximum of 100 ticks if the + * // change period command cannot immediately be sent to the timer + * // command queue. + * if( xTimerChangePeriod( xTimer, 500 / portTICK_PERIOD_MS, 100 ) == pdPASS ) + * { + * // The command was successfully sent. + * } + * else + * { + * // The command could not be sent, even after waiting for 100 ticks + * // to pass. Take appropriate action here. + * } + * } + * } + * @endverbatim + */ +#define xTimerChangePeriod( xTimer, xNewPeriod, xTicksToWait ) \ + xTimerGenericCommand( ( xTimer ), tmrCOMMAND_CHANGE_PERIOD, ( xNewPeriod ), NULL, ( xTicksToWait ) ) + +/** + * BaseType_t xTimerDelete( TimerHandle_t xTimer, TickType_t xTicksToWait ); + * + * Timer functionality is provided by a timer service/daemon task. Many of the + * public FreeRTOS timer API functions send commands to the timer service task + * through a queue called the timer command queue. The timer command queue is + * private to the kernel itself and is not directly accessible to application + * code. The length of the timer command queue is set by the + * configTIMER_QUEUE_LENGTH configuration constant. + * + * xTimerDelete() deletes a timer that was previously created using the + * xTimerCreate() API function. + * + * The configUSE_TIMERS configuration constant must be set to 1 for + * xTimerDelete() to be available. + * + * @param xTimer The handle of the timer being deleted. + * + * @param xTicksToWait Specifies the time, in ticks, that the calling task should + * be held in the Blocked state to wait for the delete command to be + * successfully sent to the timer command queue, should the queue already be + * full when xTimerDelete() was called. xTicksToWait is ignored if xTimerDelete() + * is called before the scheduler is started. + * + * @return pdFAIL will be returned if the delete command could not be sent to + * the timer command queue even after xTicksToWait ticks had passed. pdPASS will + * be returned if the command was successfully sent to the timer command queue. + * When the command is actually processed will depend on the priority of the + * timer service/daemon task relative to other tasks in the system. The timer + * service/daemon task priority is set by the configTIMER_TASK_PRIORITY + * configuration constant. + * + * Example usage: + * + * See the xTimerChangePeriod() API function example usage scenario. + */ +#define xTimerDelete( xTimer, xTicksToWait ) \ + xTimerGenericCommand( ( xTimer ), tmrCOMMAND_DELETE, 0U, NULL, ( xTicksToWait ) ) + +/** + * BaseType_t xTimerReset( TimerHandle_t xTimer, TickType_t xTicksToWait ); + * + * Timer functionality is provided by a timer service/daemon task. Many of the + * public FreeRTOS timer API functions send commands to the timer service task + * through a queue called the timer command queue. The timer command queue is + * private to the kernel itself and is not directly accessible to application + * code. The length of the timer command queue is set by the + * configTIMER_QUEUE_LENGTH configuration constant. + * + * xTimerReset() re-starts a timer that was previously created using the + * xTimerCreate() API function. If the timer had already been started and was + * already in the active state, then xTimerReset() will cause the timer to + * re-evaluate its expiry time so that it is relative to when xTimerReset() was + * called. If the timer was in the dormant state then xTimerReset() has + * equivalent functionality to the xTimerStart() API function. + * + * Resetting a timer ensures the timer is in the active state. If the timer + * is not stopped, deleted, or reset in the mean time, the callback function + * associated with the timer will get called 'n' ticks after xTimerReset() was + * called, where 'n' is the timers defined period. + * + * It is valid to call xTimerReset() before the scheduler has been started, but + * when this is done the timer will not actually start until the scheduler is + * started, and the timers expiry time will be relative to when the scheduler is + * started, not relative to when xTimerReset() was called. + * + * The configUSE_TIMERS configuration constant must be set to 1 for xTimerReset() + * to be available. + * + * @param xTimer The handle of the timer being reset/started/restarted. + * + * @param xTicksToWait Specifies the time, in ticks, that the calling task should + * be held in the Blocked state to wait for the reset command to be successfully + * sent to the timer command queue, should the queue already be full when + * xTimerReset() was called. xTicksToWait is ignored if xTimerReset() is called + * before the scheduler is started. + * + * @return pdFAIL will be returned if the reset command could not be sent to + * the timer command queue even after xTicksToWait ticks had passed. pdPASS will + * be returned if the command was successfully sent to the timer command queue. + * When the command is actually processed will depend on the priority of the + * timer service/daemon task relative to other tasks in the system, although the + * timers expiry time is relative to when xTimerStart() is actually called. The + * timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY + * configuration constant. + * + * Example usage: + * @verbatim + * // When a key is pressed, an LCD back-light is switched on. If 5 seconds pass + * // without a key being pressed, then the LCD back-light is switched off. In + * // this case, the timer is a one-shot timer. + * + * TimerHandle_t xBacklightTimer = NULL; + * + * // The callback function assigned to the one-shot timer. In this case the + * // parameter is not used. + * void vBacklightTimerCallback( TimerHandle_t pxTimer ) + * { + * // The timer expired, therefore 5 seconds must have passed since a key + * // was pressed. Switch off the LCD back-light. + * vSetBacklightState( BACKLIGHT_OFF ); + * } + * + * // The key press event handler. + * void vKeyPressEventHandler( char cKey ) + * { + * // Ensure the LCD back-light is on, then reset the timer that is + * // responsible for turning the back-light off after 5 seconds of + * // key inactivity. Wait 10 ticks for the command to be successfully sent + * // if it cannot be sent immediately. + * vSetBacklightState( BACKLIGHT_ON ); + * if( xTimerReset( xBacklightTimer, 100 ) != pdPASS ) + * { + * // The reset command was not executed successfully. Take appropriate + * // action here. + * } + * + * // Perform the rest of the key processing here. + * } + * + * void main( void ) + * { + * int32_t x; + * + * // Create then start the one-shot timer that is responsible for turning + * // the back-light off if no keys are pressed within a 5 second period. + * xBacklightTimer = xTimerCreate( "BacklightTimer", // Just a text name, not used by the kernel. + * ( 5000 / portTICK_PERIOD_MS), // The timer period in ticks. + * pdFALSE, // The timer is a one-shot timer. + * 0, // The id is not used by the callback so can take any value. + * vBacklightTimerCallback // The callback function that switches the LCD back-light off. + * ); + * + * if( xBacklightTimer == NULL ) + * { + * // The timer was not created. + * } + * else + * { + * // Start the timer. No block time is specified, and even if one was + * // it would be ignored because the scheduler has not yet been + * // started. + * if( xTimerStart( xBacklightTimer, 0 ) != pdPASS ) + * { + * // The timer could not be set into the Active state. + * } + * } + * + * // ... + * // Create tasks here. + * // ... + * + * // Starting the scheduler will start the timer running as it has already + * // been set into the active state. + * vTaskStartScheduler(); + * + * // Should not reach here. + * for( ;; ); + * } + * @endverbatim + */ +#define xTimerReset( xTimer, xTicksToWait ) \ + xTimerGenericCommand( ( xTimer ), tmrCOMMAND_RESET, ( xTaskGetTickCount() ), NULL, ( xTicksToWait ) ) + +/** + * BaseType_t xTimerStartFromISR( TimerHandle_t xTimer, + * BaseType_t *pxHigherPriorityTaskWoken ); + * + * A version of xTimerStart() that can be called from an interrupt service + * routine. + * + * @param xTimer The handle of the timer being started/restarted. + * + * @param pxHigherPriorityTaskWoken The timer service/daemon task spends most + * of its time in the Blocked state, waiting for messages to arrive on the timer + * command queue. Calling xTimerStartFromISR() writes a message to the timer + * command queue, so has the potential to transition the timer service/daemon + * task out of the Blocked state. If calling xTimerStartFromISR() causes the + * timer service/daemon task to leave the Blocked state, and the timer service/ + * daemon task has a priority equal to or greater than the currently executing + * task (the task that was interrupted), then *pxHigherPriorityTaskWoken will + * get set to pdTRUE internally within the xTimerStartFromISR() function. If + * xTimerStartFromISR() sets this value to pdTRUE then a context switch should + * be performed before the interrupt exits. + * + * @return pdFAIL will be returned if the start command could not be sent to + * the timer command queue. pdPASS will be returned if the command was + * successfully sent to the timer command queue. When the command is actually + * processed will depend on the priority of the timer service/daemon task + * relative to other tasks in the system, although the timers expiry time is + * relative to when xTimerStartFromISR() is actually called. The timer + * service/daemon task priority is set by the configTIMER_TASK_PRIORITY + * configuration constant. + * + * Example usage: + * @verbatim + * // This scenario assumes xBacklightTimer has already been created. When a + * // key is pressed, an LCD back-light is switched on. If 5 seconds pass + * // without a key being pressed, then the LCD back-light is switched off. In + * // this case, the timer is a one-shot timer, and unlike the example given for + * // the xTimerReset() function, the key press event handler is an interrupt + * // service routine. + * + * // The callback function assigned to the one-shot timer. In this case the + * // parameter is not used. + * void vBacklightTimerCallback( TimerHandle_t pxTimer ) + * { + * // The timer expired, therefore 5 seconds must have passed since a key + * // was pressed. Switch off the LCD back-light. + * vSetBacklightState( BACKLIGHT_OFF ); + * } + * + * // The key press interrupt service routine. + * void vKeyPressEventInterruptHandler( void ) + * { + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; + * + * // Ensure the LCD back-light is on, then restart the timer that is + * // responsible for turning the back-light off after 5 seconds of + * // key inactivity. This is an interrupt service routine so can only + * // call FreeRTOS API functions that end in "FromISR". + * vSetBacklightState( BACKLIGHT_ON ); + * + * // xTimerStartFromISR() or xTimerResetFromISR() could be called here + * // as both cause the timer to re-calculate its expiry time. + * // xHigherPriorityTaskWoken was initialised to pdFALSE when it was + * // declared (in this function). + * if( xTimerStartFromISR( xBacklightTimer, &xHigherPriorityTaskWoken ) != pdPASS ) + * { + * // The start command was not executed successfully. Take appropriate + * // action here. + * } + * + * // Perform the rest of the key processing here. + * + * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch + * // should be performed. The syntax required to perform a context switch + * // from inside an ISR varies from port to port, and from compiler to + * // compiler. Inspect the demos for the port you are using to find the + * // actual syntax required. + * if( xHigherPriorityTaskWoken != pdFALSE ) + * { + * // Call the interrupt safe yield function here (actual function + * // depends on the FreeRTOS port being used). + * } + * } + * @endverbatim + */ +#define xTimerStartFromISR( xTimer, pxHigherPriorityTaskWoken ) \ + xTimerGenericCommand( ( xTimer ), tmrCOMMAND_START_FROM_ISR, ( xTaskGetTickCountFromISR() ), ( pxHigherPriorityTaskWoken ), 0U ) + +/** + * BaseType_t xTimerStopFromISR( TimerHandle_t xTimer, + * BaseType_t *pxHigherPriorityTaskWoken ); + * + * A version of xTimerStop() that can be called from an interrupt service + * routine. + * + * @param xTimer The handle of the timer being stopped. + * + * @param pxHigherPriorityTaskWoken The timer service/daemon task spends most + * of its time in the Blocked state, waiting for messages to arrive on the timer + * command queue. Calling xTimerStopFromISR() writes a message to the timer + * command queue, so has the potential to transition the timer service/daemon + * task out of the Blocked state. If calling xTimerStopFromISR() causes the + * timer service/daemon task to leave the Blocked state, and the timer service/ + * daemon task has a priority equal to or greater than the currently executing + * task (the task that was interrupted), then *pxHigherPriorityTaskWoken will + * get set to pdTRUE internally within the xTimerStopFromISR() function. If + * xTimerStopFromISR() sets this value to pdTRUE then a context switch should + * be performed before the interrupt exits. + * + * @return pdFAIL will be returned if the stop command could not be sent to + * the timer command queue. pdPASS will be returned if the command was + * successfully sent to the timer command queue. When the command is actually + * processed will depend on the priority of the timer service/daemon task + * relative to other tasks in the system. The timer service/daemon task + * priority is set by the configTIMER_TASK_PRIORITY configuration constant. + * + * Example usage: + * @verbatim + * // This scenario assumes xTimer has already been created and started. When + * // an interrupt occurs, the timer should be simply stopped. + * + * // The interrupt service routine that stops the timer. + * void vAnExampleInterruptServiceRoutine( void ) + * { + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; + * + * // The interrupt has occurred - simply stop the timer. + * // xHigherPriorityTaskWoken was set to pdFALSE where it was defined + * // (within this function). As this is an interrupt service routine, only + * // FreeRTOS API functions that end in "FromISR" can be used. + * if( xTimerStopFromISR( xTimer, &xHigherPriorityTaskWoken ) != pdPASS ) + * { + * // The stop command was not executed successfully. Take appropriate + * // action here. + * } + * + * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch + * // should be performed. The syntax required to perform a context switch + * // from inside an ISR varies from port to port, and from compiler to + * // compiler. Inspect the demos for the port you are using to find the + * // actual syntax required. + * if( xHigherPriorityTaskWoken != pdFALSE ) + * { + * // Call the interrupt safe yield function here (actual function + * // depends on the FreeRTOS port being used). + * } + * } + * @endverbatim + */ +#define xTimerStopFromISR( xTimer, pxHigherPriorityTaskWoken ) \ + xTimerGenericCommand( ( xTimer ), tmrCOMMAND_STOP_FROM_ISR, 0, ( pxHigherPriorityTaskWoken ), 0U ) + +/** + * BaseType_t xTimerChangePeriodFromISR( TimerHandle_t xTimer, + * TickType_t xNewPeriod, + * BaseType_t *pxHigherPriorityTaskWoken ); + * + * A version of xTimerChangePeriod() that can be called from an interrupt + * service routine. + * + * @param xTimer The handle of the timer that is having its period changed. + * + * @param xNewPeriod The new period for xTimer. Timer periods are specified in + * tick periods, so the constant portTICK_PERIOD_MS can be used to convert a time + * that has been specified in milliseconds. For example, if the timer must + * expire after 100 ticks, then xNewPeriod should be set to 100. Alternatively, + * if the timer must expire after 500ms, then xNewPeriod can be set to + * ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than + * or equal to 1000. + * + * @param pxHigherPriorityTaskWoken The timer service/daemon task spends most + * of its time in the Blocked state, waiting for messages to arrive on the timer + * command queue. Calling xTimerChangePeriodFromISR() writes a message to the + * timer command queue, so has the potential to transition the timer service/ + * daemon task out of the Blocked state. If calling xTimerChangePeriodFromISR() + * causes the timer service/daemon task to leave the Blocked state, and the + * timer service/daemon task has a priority equal to or greater than the + * currently executing task (the task that was interrupted), then + * *pxHigherPriorityTaskWoken will get set to pdTRUE internally within the + * xTimerChangePeriodFromISR() function. If xTimerChangePeriodFromISR() sets + * this value to pdTRUE then a context switch should be performed before the + * interrupt exits. + * + * @return pdFAIL will be returned if the command to change the timers period + * could not be sent to the timer command queue. pdPASS will be returned if the + * command was successfully sent to the timer command queue. When the command + * is actually processed will depend on the priority of the timer service/daemon + * task relative to other tasks in the system. The timer service/daemon task + * priority is set by the configTIMER_TASK_PRIORITY configuration constant. + * + * Example usage: + * @verbatim + * // This scenario assumes xTimer has already been created and started. When + * // an interrupt occurs, the period of xTimer should be changed to 500ms. + * + * // The interrupt service routine that changes the period of xTimer. + * void vAnExampleInterruptServiceRoutine( void ) + * { + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; + * + * // The interrupt has occurred - change the period of xTimer to 500ms. + * // xHigherPriorityTaskWoken was set to pdFALSE where it was defined + * // (within this function). As this is an interrupt service routine, only + * // FreeRTOS API functions that end in "FromISR" can be used. + * if( xTimerChangePeriodFromISR( xTimer, &xHigherPriorityTaskWoken ) != pdPASS ) + * { + * // The command to change the timers period was not executed + * // successfully. Take appropriate action here. + * } + * + * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch + * // should be performed. The syntax required to perform a context switch + * // from inside an ISR varies from port to port, and from compiler to + * // compiler. Inspect the demos for the port you are using to find the + * // actual syntax required. + * if( xHigherPriorityTaskWoken != pdFALSE ) + * { + * // Call the interrupt safe yield function here (actual function + * // depends on the FreeRTOS port being used). + * } + * } + * @endverbatim + */ +#define xTimerChangePeriodFromISR( xTimer, xNewPeriod, pxHigherPriorityTaskWoken ) \ + xTimerGenericCommand( ( xTimer ), tmrCOMMAND_CHANGE_PERIOD_FROM_ISR, ( xNewPeriod ), ( pxHigherPriorityTaskWoken ), 0U ) + +/** + * BaseType_t xTimerResetFromISR( TimerHandle_t xTimer, + * BaseType_t *pxHigherPriorityTaskWoken ); + * + * A version of xTimerReset() that can be called from an interrupt service + * routine. + * + * @param xTimer The handle of the timer that is to be started, reset, or + * restarted. + * + * @param pxHigherPriorityTaskWoken The timer service/daemon task spends most + * of its time in the Blocked state, waiting for messages to arrive on the timer + * command queue. Calling xTimerResetFromISR() writes a message to the timer + * command queue, so has the potential to transition the timer service/daemon + * task out of the Blocked state. If calling xTimerResetFromISR() causes the + * timer service/daemon task to leave the Blocked state, and the timer service/ + * daemon task has a priority equal to or greater than the currently executing + * task (the task that was interrupted), then *pxHigherPriorityTaskWoken will + * get set to pdTRUE internally within the xTimerResetFromISR() function. If + * xTimerResetFromISR() sets this value to pdTRUE then a context switch should + * be performed before the interrupt exits. + * + * @return pdFAIL will be returned if the reset command could not be sent to + * the timer command queue. pdPASS will be returned if the command was + * successfully sent to the timer command queue. When the command is actually + * processed will depend on the priority of the timer service/daemon task + * relative to other tasks in the system, although the timers expiry time is + * relative to when xTimerResetFromISR() is actually called. The timer service/daemon + * task priority is set by the configTIMER_TASK_PRIORITY configuration constant. + * + * Example usage: + * @verbatim + * // This scenario assumes xBacklightTimer has already been created. When a + * // key is pressed, an LCD back-light is switched on. If 5 seconds pass + * // without a key being pressed, then the LCD back-light is switched off. In + * // this case, the timer is a one-shot timer, and unlike the example given for + * // the xTimerReset() function, the key press event handler is an interrupt + * // service routine. + * + * // The callback function assigned to the one-shot timer. In this case the + * // parameter is not used. + * void vBacklightTimerCallback( TimerHandle_t pxTimer ) + * { + * // The timer expired, therefore 5 seconds must have passed since a key + * // was pressed. Switch off the LCD back-light. + * vSetBacklightState( BACKLIGHT_OFF ); + * } + * + * // The key press interrupt service routine. + * void vKeyPressEventInterruptHandler( void ) + * { + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; + * + * // Ensure the LCD back-light is on, then reset the timer that is + * // responsible for turning the back-light off after 5 seconds of + * // key inactivity. This is an interrupt service routine so can only + * // call FreeRTOS API functions that end in "FromISR". + * vSetBacklightState( BACKLIGHT_ON ); + * + * // xTimerStartFromISR() or xTimerResetFromISR() could be called here + * // as both cause the timer to re-calculate its expiry time. + * // xHigherPriorityTaskWoken was initialised to pdFALSE when it was + * // declared (in this function). + * if( xTimerResetFromISR( xBacklightTimer, &xHigherPriorityTaskWoken ) != pdPASS ) + * { + * // The reset command was not executed successfully. Take appropriate + * // action here. + * } + * + * // Perform the rest of the key processing here. + * + * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch + * // should be performed. The syntax required to perform a context switch + * // from inside an ISR varies from port to port, and from compiler to + * // compiler. Inspect the demos for the port you are using to find the + * // actual syntax required. + * if( xHigherPriorityTaskWoken != pdFALSE ) + * { + * // Call the interrupt safe yield function here (actual function + * // depends on the FreeRTOS port being used). + * } + * } + * @endverbatim + */ +#define xTimerResetFromISR( xTimer, pxHigherPriorityTaskWoken ) \ + xTimerGenericCommand( ( xTimer ), tmrCOMMAND_RESET_FROM_ISR, ( xTaskGetTickCountFromISR() ), ( pxHigherPriorityTaskWoken ), 0U ) + + +/** + * BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, + * void *pvParameter1, + * uint32_t ulParameter2, + * BaseType_t *pxHigherPriorityTaskWoken ); + * + * + * Used from application interrupt service routines to defer the execution of a + * function to the RTOS daemon task (the timer service task, hence this function + * is implemented in timers.c and is prefixed with 'Timer'). + * + * Ideally an interrupt service routine (ISR) is kept as short as possible, but + * sometimes an ISR either has a lot of processing to do, or needs to perform + * processing that is not deterministic. In these cases + * xTimerPendFunctionCallFromISR() can be used to defer processing of a function + * to the RTOS daemon task. + * + * A mechanism is provided that allows the interrupt to return directly to the + * task that will subsequently execute the pended callback function. This + * allows the callback function to execute contiguously in time with the + * interrupt - just as if the callback had executed in the interrupt itself. + * + * @param xFunctionToPend The function to execute from the timer service/ + * daemon task. The function must conform to the PendedFunction_t + * prototype. + * + * @param pvParameter1 The value of the callback function's first parameter. + * The parameter has a void * type to allow it to be used to pass any type. + * For example, unsigned longs can be cast to a void *, or the void * can be + * used to point to a structure. + * + * @param ulParameter2 The value of the callback function's second parameter. + * + * @param pxHigherPriorityTaskWoken As mentioned above, calling this function + * will result in a message being sent to the timer daemon task. If the + * priority of the timer daemon task (which is set using + * configTIMER_TASK_PRIORITY in FreeRTOSConfig.h) is higher than the priority of + * the currently running task (the task the interrupt interrupted) then + * *pxHigherPriorityTaskWoken will be set to pdTRUE within + * xTimerPendFunctionCallFromISR(), indicating that a context switch should be + * requested before the interrupt exits. For that reason + * *pxHigherPriorityTaskWoken must be initialised to pdFALSE. See the + * example code below. + * + * @return pdPASS is returned if the message was successfully sent to the + * timer daemon task, otherwise pdFALSE is returned. + * + * Example usage: + * @verbatim + * + * // The callback function that will execute in the context of the daemon task. + * // Note callback functions must all use this same prototype. + * void vProcessInterface( void *pvParameter1, uint32_t ulParameter2 ) + * { + * BaseType_t xInterfaceToService; + * + * // The interface that requires servicing is passed in the second + * // parameter. The first parameter is not used in this case. + * xInterfaceToService = ( BaseType_t ) ulParameter2; + * + * // ...Perform the processing here... + * } + * + * // An ISR that receives data packets from multiple interfaces + * void vAnISR( void ) + * { + * BaseType_t xInterfaceToService, xHigherPriorityTaskWoken; + * + * // Query the hardware to determine which interface needs processing. + * xInterfaceToService = prvCheckInterfaces(); + * + * // The actual processing is to be deferred to a task. Request the + * // vProcessInterface() callback function is executed, passing in the + * // number of the interface that needs processing. The interface to + * // service is passed in the second parameter. The first parameter is + * // not used in this case. + * xHigherPriorityTaskWoken = pdFALSE; + * xTimerPendFunctionCallFromISR( vProcessInterface, NULL, ( uint32_t ) xInterfaceToService, &xHigherPriorityTaskWoken ); + * + * // If xHigherPriorityTaskWoken is now set to pdTRUE then a context + * // switch should be requested. The macro used is port specific and will + * // be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() - refer to + * // the documentation page for the port being used. + * portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); + * + * } + * @endverbatim + */ +BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, + void * pvParameter1, + uint32_t ulParameter2, + BaseType_t * pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + +/** + * BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, + * void *pvParameter1, + * uint32_t ulParameter2, + * TickType_t xTicksToWait ); + * + * + * Used to defer the execution of a function to the RTOS daemon task (the timer + * service task, hence this function is implemented in timers.c and is prefixed + * with 'Timer'). + * + * @param xFunctionToPend The function to execute from the timer service/ + * daemon task. The function must conform to the PendedFunction_t + * prototype. + * + * @param pvParameter1 The value of the callback function's first parameter. + * The parameter has a void * type to allow it to be used to pass any type. + * For example, unsigned longs can be cast to a void *, or the void * can be + * used to point to a structure. + * + * @param ulParameter2 The value of the callback function's second parameter. + * + * @param xTicksToWait Calling this function will result in a message being + * sent to the timer daemon task on a queue. xTicksToWait is the amount of + * time the calling task should remain in the Blocked state (so not using any + * processing time) for space to become available on the timer queue if the + * queue is found to be full. + * + * @return pdPASS is returned if the message was successfully sent to the + * timer daemon task, otherwise pdFALSE is returned. + * + */ +BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, + void * pvParameter1, + uint32_t ulParameter2, + TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/** + * const char * const pcTimerGetName( TimerHandle_t xTimer ); + * + * Returns the name that was assigned to a timer when the timer was created. + * + * @param xTimer The handle of the timer being queried. + * + * @return The name assigned to the timer specified by the xTimer parameter. + */ +const char * pcTimerGetName( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + +/** + * void vTimerSetReloadMode( TimerHandle_t xTimer, const UBaseType_t uxAutoReload ); + * + * Updates a timer to be either an auto-reload timer, in which case the timer + * automatically resets itself each time it expires, or a one-shot timer, in + * which case the timer will only expire once unless it is manually restarted. + * + * @param xTimer The handle of the timer being updated. + * + * @param uxAutoReload If uxAutoReload is set to pdTRUE then the timer will + * expire repeatedly with a frequency set by the timer's period (see the + * xTimerPeriodInTicks parameter of the xTimerCreate() API function). If + * uxAutoReload is set to pdFALSE then the timer will be a one-shot timer and + * enter the dormant state after it expires. + */ +void vTimerSetReloadMode( TimerHandle_t xTimer, + const UBaseType_t uxAutoReload ) PRIVILEGED_FUNCTION; + +/** + * UBaseType_t uxTimerGetReloadMode( TimerHandle_t xTimer ); + * + * Queries a timer to determine if it is an auto-reload timer, in which case the timer + * automatically resets itself each time it expires, or a one-shot timer, in + * which case the timer will only expire once unless it is manually restarted. + * + * @param xTimer The handle of the timer being queried. + * + * @return If the timer is an auto-reload timer then pdTRUE is returned, otherwise + * pdFALSE is returned. + */ +UBaseType_t uxTimerGetReloadMode( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; + +/** + * TickType_t xTimerGetPeriod( TimerHandle_t xTimer ); + * + * Returns the period of a timer. + * + * @param xTimer The handle of the timer being queried. + * + * @return The period of the timer in ticks. + */ +TickType_t xTimerGetPeriod( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; + +/** + * TickType_t xTimerGetExpiryTime( TimerHandle_t xTimer ); + * + * Returns the time in ticks at which the timer will expire. If this is less + * than the current tick count then the expiry time has overflowed from the + * current time. + * + * @param xTimer The handle of the timer being queried. + * + * @return If the timer is running then the time in ticks at which the timer + * will next expire is returned. If the timer is not running then the return + * value is undefined. + */ +TickType_t xTimerGetExpiryTime( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; + +/* + * Functions beyond this part are not part of the public API and are intended + * for use by the kernel only. + */ +BaseType_t xTimerCreateTimerTask( void ) PRIVILEGED_FUNCTION; +BaseType_t xTimerGenericCommand( TimerHandle_t xTimer, + const BaseType_t xCommandID, + const TickType_t xOptionalValue, + BaseType_t * const pxHigherPriorityTaskWoken, + const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +#if ( configUSE_TRACE_FACILITY == 1 ) + void vTimerSetTimerNumber( TimerHandle_t xTimer, + UBaseType_t uxTimerNumber ) PRIVILEGED_FUNCTION; + UBaseType_t uxTimerGetTimerNumber( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; +#endif + +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + +/** + * task.h + * @code{c} + * void vApplicationGetTimerTaskMemory( StaticTask_t ** ppxTimerTaskTCBBuffer, StackType_t ** ppxTimerTaskStackBuffer, uint32_t *pulTimerTaskStackSize ) + * @endcode + * + * This function is used to provide a statically allocated block of memory to FreeRTOS to hold the Timer Task TCB. This function is required when + * configSUPPORT_STATIC_ALLOCATION is set. For more information see this URI: https://www.FreeRTOS.org/a00110.html#configSUPPORT_STATIC_ALLOCATION + * + * @param ppxTimerTaskTCBBuffer A handle to a statically allocated TCB buffer + * @param ppxTimerTaskStackBuffer A handle to a statically allocated Stack buffer for thie idle task + * @param pulTimerTaskStackSize A pointer to the number of elements that will fit in the allocated stack buffer + */ + void vApplicationGetTimerTaskMemory( StaticTask_t ** ppxTimerTaskTCBBuffer, + StackType_t ** ppxTimerTaskStackBuffer, + uint32_t * pulTimerTaskStackSize ); + +#endif + +/* *INDENT-OFF* */ +#ifdef __cplusplus + } +#endif +/* *INDENT-ON* */ +#endif /* TIMERS_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/list.c b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/list.c new file mode 100644 index 0000000..42a2e09 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/list.c @@ -0,0 +1,215 @@ +/* + * FreeRTOS Kernel V10.4.6 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + + +#include + +/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining + * all the API functions to use the MPU wrappers. That should only be done when + * task.h is included from an application file. */ +#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +#include "FreeRTOS.h" +#include "list.h" + +/* Lint e9021, e961 and e750 are suppressed as a MISRA exception justified + * because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be + * defined for the header files above, but not in this file, in order to + * generate the correct privileged Vs unprivileged linkage and placement. */ +#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750 !e9021. */ + +/*----------------------------------------------------------- +* PUBLIC LIST API documented in list.h +*----------------------------------------------------------*/ + +void vListInitialise( List_t * const pxList ) +{ + /* The list structure contains a list item which is used to mark the + * end of the list. To initialise the list the list end is inserted + * as the only list entry. */ + pxList->pxIndex = ( ListItem_t * ) &( pxList->xListEnd ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ + + /* The list end value is the highest possible value in the list to + * ensure it remains at the end of the list. */ + pxList->xListEnd.xItemValue = portMAX_DELAY; + + /* The list end next and previous pointers point to itself so we know + * when the list is empty. */ + pxList->xListEnd.pxNext = ( ListItem_t * ) &( pxList->xListEnd ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ + pxList->xListEnd.pxPrevious = ( ListItem_t * ) &( pxList->xListEnd ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ + + pxList->uxNumberOfItems = ( UBaseType_t ) 0U; + + /* Write known values into the list if + * configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ); + listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ); +} +/*-----------------------------------------------------------*/ + +void vListInitialiseItem( ListItem_t * const pxItem ) +{ + /* Make sure the list item is not recorded as being on a list. */ + pxItem->pxContainer = NULL; + + /* Write known values into the list item if + * configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ); + listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ); +} +/*-----------------------------------------------------------*/ + +void vListInsertEnd( List_t * const pxList, + ListItem_t * const pxNewListItem ) +{ + ListItem_t * const pxIndex = pxList->pxIndex; + + /* Only effective when configASSERT() is also defined, these tests may catch + * the list data structures being overwritten in memory. They will not catch + * data errors caused by incorrect configuration or use of FreeRTOS. */ + listTEST_LIST_INTEGRITY( pxList ); + listTEST_LIST_ITEM_INTEGRITY( pxNewListItem ); + + /* Insert a new list item into pxList, but rather than sort the list, + * makes the new list item the last item to be removed by a call to + * listGET_OWNER_OF_NEXT_ENTRY(). */ + pxNewListItem->pxNext = pxIndex; + pxNewListItem->pxPrevious = pxIndex->pxPrevious; + + /* Only used during decision coverage testing. */ + mtCOVERAGE_TEST_DELAY(); + + pxIndex->pxPrevious->pxNext = pxNewListItem; + pxIndex->pxPrevious = pxNewListItem; + + /* Remember which list the item is in. */ + pxNewListItem->pxContainer = pxList; + + ( pxList->uxNumberOfItems )++; +} +/*-----------------------------------------------------------*/ + +void vListInsert( List_t * const pxList, + ListItem_t * const pxNewListItem ) +{ + ListItem_t * pxIterator; + const TickType_t xValueOfInsertion = pxNewListItem->xItemValue; + + /* Only effective when configASSERT() is also defined, these tests may catch + * the list data structures being overwritten in memory. They will not catch + * data errors caused by incorrect configuration or use of FreeRTOS. */ + listTEST_LIST_INTEGRITY( pxList ); + listTEST_LIST_ITEM_INTEGRITY( pxNewListItem ); + + /* Insert the new list item into the list, sorted in xItemValue order. + * + * If the list already contains a list item with the same item value then the + * new list item should be placed after it. This ensures that TCBs which are + * stored in ready lists (all of which have the same xItemValue value) get a + * share of the CPU. However, if the xItemValue is the same as the back marker + * the iteration loop below will not end. Therefore the value is checked + * first, and the algorithm slightly modified if necessary. */ + if( xValueOfInsertion == portMAX_DELAY ) + { + pxIterator = pxList->xListEnd.pxPrevious; + } + else + { + /* *** NOTE *********************************************************** + * If you find your application is crashing here then likely causes are + * listed below. In addition see https://www.FreeRTOS.org/FAQHelp.html for + * more tips, and ensure configASSERT() is defined! + * https://www.FreeRTOS.org/a00110.html#configASSERT + * + * 1) Stack overflow - + * see https://www.FreeRTOS.org/Stacks-and-stack-overflow-checking.html + * 2) Incorrect interrupt priority assignment, especially on Cortex-M + * parts where numerically high priority values denote low actual + * interrupt priorities, which can seem counter intuitive. See + * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html and the definition + * of configMAX_SYSCALL_INTERRUPT_PRIORITY on + * https://www.FreeRTOS.org/a00110.html + * 3) Calling an API function from within a critical section or when + * the scheduler is suspended, or calling an API function that does + * not end in "FromISR" from an interrupt. + * 4) Using a queue or semaphore before it has been initialised or + * before the scheduler has been started (are interrupts firing + * before vTaskStartScheduler() has been called?). + * 5) If the FreeRTOS port supports interrupt nesting then ensure that + * the priority of the tick interrupt is at or below + * configMAX_SYSCALL_INTERRUPT_PRIORITY. + **********************************************************************/ + + for( pxIterator = ( ListItem_t * ) &( pxList->xListEnd ); pxIterator->pxNext->xItemValue <= xValueOfInsertion; pxIterator = pxIterator->pxNext ) /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. *//*lint !e440 The iterator moves to a different value, not xValueOfInsertion. */ + { + /* There is nothing to do here, just iterating to the wanted + * insertion position. */ + } + } + + pxNewListItem->pxNext = pxIterator->pxNext; + pxNewListItem->pxNext->pxPrevious = pxNewListItem; + pxNewListItem->pxPrevious = pxIterator; + pxIterator->pxNext = pxNewListItem; + + /* Remember which list the item is in. This allows fast removal of the + * item later. */ + pxNewListItem->pxContainer = pxList; + + ( pxList->uxNumberOfItems )++; +} +/*-----------------------------------------------------------*/ + +UBaseType_t uxListRemove( ListItem_t * const pxItemToRemove ) +{ +/* The list item knows which list it is in. Obtain the list from the list + * item. */ + List_t * const pxList = pxItemToRemove->pxContainer; + + pxItemToRemove->pxNext->pxPrevious = pxItemToRemove->pxPrevious; + pxItemToRemove->pxPrevious->pxNext = pxItemToRemove->pxNext; + + /* Only used during decision coverage testing. */ + mtCOVERAGE_TEST_DELAY(); + + /* Make sure the index is left pointing to a valid item. */ + if( pxList->pxIndex == pxItemToRemove ) + { + pxList->pxIndex = pxItemToRemove->pxPrevious; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + pxItemToRemove->pxContainer = NULL; + ( pxList->uxNumberOfItems )--; + + return pxList->uxNumberOfItems; +} +/*-----------------------------------------------------------*/ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/GCC/RISC-V/Documentation.url b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/GCC/RISC-V/Documentation.url new file mode 100644 index 0000000..5546f87 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/GCC/RISC-V/Documentation.url @@ -0,0 +1,5 @@ +[{000214A0-0000-0000-C000-000000000046}] +Prop3=19,11 +[InternetShortcut] +IDList= +URL=https://www.FreeRTOS.org/Using-FreeRTOS-on-RISC-V.html diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/GCC/RISC-V/chip_specific_extensions/RV32I_CLINT_no_extensions/freertos_risc_v_chip_specific_extensions.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/GCC/RISC-V/chip_specific_extensions/RV32I_CLINT_no_extensions/freertos_risc_v_chip_specific_extensions.h new file mode 100644 index 0000000..90dbb97 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/GCC/RISC-V/chip_specific_extensions/RV32I_CLINT_no_extensions/freertos_risc_v_chip_specific_extensions.h @@ -0,0 +1,69 @@ +/* + * FreeRTOS Kernel V10.4.4 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* + * The FreeRTOS kernel's RISC-V port is split between the the code that is + * common across all currently supported RISC-V chips (implementations of the + * RISC-V ISA), and code that tailors the port to a specific RISC-V chip: + * + * + FreeRTOS\Source\portable\GCC\RISC-V-RV32\portASM.S contains the code that + * is common to all currently supported RISC-V chips. There is only one + * portASM.S file because the same file is built for all RISC-V target chips. + * + * + Header files called freertos_risc_v_chip_specific_extensions.h contain the + * code that tailors the FreeRTOS kernel's RISC-V port to a specific RISC-V + * chip. There are multiple freertos_risc_v_chip_specific_extensions.h files + * as there are multiple RISC-V chip implementations. + * + * !!!NOTE!!! + * TAKE CARE TO INCLUDE THE CORRECT freertos_risc_v_chip_specific_extensions.h + * HEADER FILE FOR THE CHIP IN USE. This is done using the assembler's (not the + * compiler's!) include path. For example, if the chip in use includes a core + * local interrupter (CLINT) and does not include any chip specific register + * extensions then add the path below to the assembler's include path: + * FreeRTOS\Source\portable\GCC\RISC-V-RV32\chip_specific_extensions\RV32I_CLINT_no_extensions + * + */ + + +#ifndef __FREERTOS_RISC_V_EXTENSIONS_H__ +#define __FREERTOS_RISC_V_EXTENSIONS_H__ + +#define portasmHAS_SIFIVE_CLINT 1 +#define portasmHAS_MTIME 1 +#define portasmADDITIONAL_CONTEXT_SIZE 0 /* Must be even number on 32-bit cores. */ + +.macro portasmSAVE_ADDITIONAL_REGISTERS + /* No additional registers to save, so this macro does nothing. */ + .endm + +.macro portasmRESTORE_ADDITIONAL_REGISTERS + /* No additional registers to restore, so this macro does nothing. */ + .endm + +#endif /* __FREERTOS_RISC_V_EXTENSIONS_H__ */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/GCC/RISC-V/chip_specific_extensions/readme.txt b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/GCC/RISC-V/chip_specific_extensions/readme.txt new file mode 100644 index 0000000..b24c0b9 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/GCC/RISC-V/chip_specific_extensions/readme.txt @@ -0,0 +1,23 @@ +/* + * The FreeRTOS kernel's RISC-V port is split between the the code that is + * common across all currently supported RISC-V chips (implementations of the + * RISC-V ISA), and code that tailors the port to a specific RISC-V chip: + * + * + FreeRTOS\Source\portable\GCC\RISC-V-RV32\portASM.S contains the code that + * is common to all currently supported RISC-V chips. There is only one + * portASM.S file because the same file is built for all RISC-V target chips. + * + * + Header files called freertos_risc_v_chip_specific_extensions.h contain the + * code that tailors the FreeRTOS kernel's RISC-V port to a specific RISC-V + * chip. There are multiple freertos_risc_v_chip_specific_extensions.h files + * as there are multiple RISC-V chip implementations. + * + * !!!NOTE!!! + * TAKE CARE TO INCLUDE THE CORRECT freertos_risc_v_chip_specific_extensions.h + * HEADER FILE FOR THE CHIP IN USE. This is done using the assembler's (not the + * compiler's!) include path. For example, if the chip in use includes a core + * local interrupter (CLINT) and does not include any chip specific register + * extensions then add the path below to the assembler's include path: + * FreeRTOS\Source\portable\GCC\RISC-V-RV32\chip_specific_extensions\RV32I_CLINT_no_extensions + * + */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/GCC/RISC-V/port.c b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/GCC/RISC-V/port.c new file mode 100644 index 0000000..9ac9e63 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/GCC/RISC-V/port.c @@ -0,0 +1,223 @@ +/* + * FreeRTOS Kernel V10.4.4 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/*----------------------------------------------------------- + * Implementation of functions defined in portable.h for the RISC-V RV32 port. + *----------------------------------------------------------*/ + +/* Scheduler includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "portmacro.h" + +/* Standard includes. */ +#include "string.h" + +#ifdef configCLINT_BASE_ADDRESS + #warning The configCLINT_BASE_ADDRESS constant has been deprecated. configMTIME_BASE_ADDRESS and configMTIMECMP_BASE_ADDRESS are currently being derived from the (possibly 0) configCLINT_BASE_ADDRESS setting. Please update to define configMTIME_BASE_ADDRESS and configMTIMECMP_BASE_ADDRESS dirctly in place of configCLINT_BASE_ADDRESS. See https://www.FreeRTOS.org/Using-FreeRTOS-on-RISC-V.html +#endif + +#ifndef configMTIME_BASE_ADDRESS + #warning configMTIME_BASE_ADDRESS must be defined in FreeRTOSConfig.h. If the target chip includes a memory-mapped mtime register then set configMTIME_BASE_ADDRESS to the mapped address. Otherwise set configMTIME_BASE_ADDRESS to 0. See https://www.FreeRTOS.org/Using-FreeRTOS-on-RISC-V.html +#endif + +#ifndef configMTIMECMP_BASE_ADDRESS + #warning configMTIMECMP_BASE_ADDRESS must be defined in FreeRTOSConfig.h. If the target chip includes a memory-mapped mtimecmp register then set configMTIMECMP_BASE_ADDRESS to the mapped address. Otherwise set configMTIMECMP_BASE_ADDRESS to 0. See https://www.FreeRTOS.org/Using-FreeRTOS-on-RISC-V.html +#endif + +/* Let the user override the pre-loading of the initial LR with the address of +prvTaskExitError() in case it messes up unwinding of the stack in the +debugger. */ +#ifdef configTASK_RETURN_ADDRESS + #define portTASK_RETURN_ADDRESS configTASK_RETURN_ADDRESS +#else + #define portTASK_RETURN_ADDRESS prvTaskExitError +#endif + +/* The stack used by interrupt service routines. Set configISR_STACK_SIZE_WORDS +to use a statically allocated array as the interrupt stack. Alternative leave +configISR_STACK_SIZE_WORDS undefined and update the linker script so that a +linker variable names __freertos_irq_stack_top has the same value as the top +of the stack used by main. Using the linker script method will repurpose the +stack that was used by main before the scheduler was started for use as the +interrupt stack after the scheduler has started. */ +#ifdef configISR_STACK_SIZE_WORDS + static __attribute__ ((aligned(16))) StackType_t xISRStack[ configISR_STACK_SIZE_WORDS ] = { 0 }; + const StackType_t xISRStackTop = ( StackType_t ) &( xISRStack[ configISR_STACK_SIZE_WORDS & ~portBYTE_ALIGNMENT_MASK ] ); + + /* Don't use 0xa5 as the stack fill bytes as that is used by the kernerl for + the task stacks, and so will legitimately appear in many positions within + the ISR stack. */ + #define portISR_STACK_FILL_BYTE 0xee +#else + extern const uint32_t __freertos_irq_stack_top[]; + const StackType_t xISRStackTop = ( StackType_t ) __freertos_irq_stack_top; +#endif + +/* + * Setup the timer to generate the tick interrupts. The implementation in this + * file is weak to allow application writers to change the timer used to + * generate the tick interrupt. + */ +void vPortSetupTimerInterrupt( void ) __attribute__(( weak )); + +/*-----------------------------------------------------------*/ + +/* Used to program the machine timer compare register. */ +uint64_t ullNextTime = 0ULL; +const uint64_t *pullNextTime = &ullNextTime; + +#if RENODE_SIMULATION == 1 /* Assumes increment won't go over 32-bits. */ + const size_t uxTimerIncrementsForOneTick = ( size_t ) ( ( configCPU_CLOCK_HZ ) / ( configTICK_RATE_HZ ) ); +#else + const size_t uxTimerIncrementsForOneTick = ( size_t ) ( ( configCPU_CLOCK_HZ / TICK_COUNT_PRESCALER ) / ( configTICK_RATE_HZ ) ); +#endif /* RENODE_SIMULATION == 1 */ + +uint32_t const ullMachineTimerCompareRegisterBase = configMTIMECMP_BASE_ADDRESS; +volatile uint64_t * pullMachineTimerCompareRegister = NULL; + +/* Set configCHECK_FOR_STACK_OVERFLOW to 3 to add ISR stack checking to task +stack checking. A problem in the ISR stack will trigger an assert, not call the +stack overflow hook function (because the stack overflow hook is specific to a +task stack, not the ISR stack). */ +#if defined( configISR_STACK_SIZE_WORDS ) && ( configCHECK_FOR_STACK_OVERFLOW > 2 ) + #warning This path not tested, or even compiled yet. + + static const uint8_t ucExpectedStackBytes[] = { + portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, \ + portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, \ + portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, \ + portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, \ + portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE }; \ + + #define portCHECK_ISR_STACK() configASSERT( ( memcmp( ( void * ) xISRStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) == 0 ) ) +#else + /* Define the function away. */ + #define portCHECK_ISR_STACK() +#endif /* configCHECK_FOR_STACK_OVERFLOW > 2 */ + +/*-----------------------------------------------------------*/ + + +#if( configMTIME_BASE_ADDRESS != 0 ) && ( configMTIMECMP_BASE_ADDRESS != 0 ) + + void vPortSetupTimerInterrupt( void ) + { + uint32_t ulCurrentTimeHigh, ulCurrentTimeLow; + volatile uint32_t * const pulTimeHigh = ( volatile uint32_t * const ) ( ( configMTIME_BASE_ADDRESS ) + 4UL ); /* 8-byte typer so high 32-bit word is 4 bytes up. */ + volatile uint32_t * const pulTimeLow = ( volatile uint32_t * const ) ( configMTIME_BASE_ADDRESS ); + volatile uint32_t ulHartId; + + __asm volatile( "csrr %0, mhartid" : "=r"( ulHartId ) ); + pullMachineTimerCompareRegister = ( volatile uint64_t * ) ( ullMachineTimerCompareRegisterBase + ( ulHartId * sizeof( uint64_t ) ) ); + + do + { + ulCurrentTimeHigh = *pulTimeHigh; + ulCurrentTimeLow = *pulTimeLow; + } while( ulCurrentTimeHigh != *pulTimeHigh ); + + ullNextTime = ( uint64_t ) ulCurrentTimeHigh; + ullNextTime <<= 32ULL; /* High 4-byte word is 32-bits up. */ + ullNextTime |= ( uint64_t ) ulCurrentTimeLow; + ullNextTime += ( uint64_t ) uxTimerIncrementsForOneTick; + *pullMachineTimerCompareRegister = ullNextTime; + + /* Prepare the time to use after the next tick interrupt. */ + ullNextTime += ( uint64_t ) uxTimerIncrementsForOneTick; + + + + } + +#endif /* ( configMTIME_BASE_ADDRESS != 0 ) && ( configMTIME_BASE_ADDRESS != 0 ) */ +/*-----------------------------------------------------------*/ + +BaseType_t xPortStartScheduler( void ) +{ +extern void xPortStartFirstTask( void ); + + #if( configASSERT_DEFINED == 1 ) + { + volatile uint32_t mtvec = 0; + + /* Check the least significant two bits of mtvec are 00 - indicating + single vector mode. */ + __asm volatile( "csrr %0, mtvec" : "=r"( mtvec ) ); + configASSERT( ( mtvec & 0x03UL ) == 0 ); + + /* Check alignment of the interrupt stack - which is the same as the + stack that was being used by main() prior to the scheduler being + started. */ + configASSERT( ( xISRStackTop & portBYTE_ALIGNMENT_MASK ) == 0 ); + + #ifdef configISR_STACK_SIZE_WORDS + { + memset( ( void * ) xISRStack, portISR_STACK_FILL_BYTE, sizeof( xISRStack ) ); + } + #endif /* configISR_STACK_SIZE_WORDS */ + } + #endif /* configASSERT_DEFINED */ + + /* If there is a CLINT then it is ok to use the default implementation + in this file, otherwise vPortSetupTimerInterrupt() must be implemented to + configure whichever clock is to be used to generate the tick interrupt. */ + vPortSetupTimerInterrupt(); + + #if( ( configMTIME_BASE_ADDRESS != 0 ) && ( configMTIMECMP_BASE_ADDRESS != 0 ) ) + { + /* Enable mtime and external interrupts. 1<<7 for timer interrupt, 1<<11 + for external interrupt. _RB_ What happens here when mtime is not present as + with pulpino? */ + __asm volatile( "csrs mie, %0" :: "r"(0x880) ); + } + #else + { + /* Enable external interrupts. */ + __asm volatile( "csrs mie, %0" :: "r"(0x800) ); + } + #endif /* ( configMTIME_BASE_ADDRESS != 0 ) && ( configMTIMECMP_BASE_ADDRESS != 0 ) */ + + xPortStartFirstTask(); + + /* Should not get here as after calling xPortStartFirstTask() only tasks + should be executing. */ + return pdFAIL; +} +/*-----------------------------------------------------------*/ + +void vPortEndScheduler( void ) +{ + /* Not implemented. */ + for( ;; ); +} + + + + + diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/GCC/RISC-V/portASM.S b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/GCC/RISC-V/portASM.S new file mode 100644 index 0000000..c5f3696 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/GCC/RISC-V/portASM.S @@ -0,0 +1,578 @@ +/* + * FreeRTOS Kernel V10.4.4 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* + * The FreeRTOS kernel's RISC-V port is split between the the code that is + * common across all currently supported RISC-V chips (implementations of the + * RISC-V ISA), and code which tailors the port to a specific RISC-V chip: + * + * + The code that is common to all RISC-V chips is implemented in + * FreeRTOS\Source\portable\GCC\RISC-V-RV32\portASM.S. There is only one + * portASM.S file because the same file is used no matter which RISC-V chip is + * in use. + * + * + The code that tailors the kernel's RISC-V port to a specific RISC-V + * chip is implemented in freertos_risc_v_chip_specific_extensions.h. There + * is one freertos_risc_v_chip_specific_extensions.h that can be used with any + * RISC-V chip that both includes a standard CLINT and does not add to the + * base set of RISC-V registers. There are additional + * freertos_risc_v_chip_specific_extensions.h files for RISC-V implementations + * that do not include a standard CLINT or do add to the base set of RISC-V + * registers. + * + * CARE MUST BE TAKEN TO INCLDUE THE CORRECT + * freertos_risc_v_chip_specific_extensions.h HEADER FILE FOR THE CHIP + * IN USE. To include the correct freertos_risc_v_chip_specific_extensions.h + * header file ensure the path to the correct header file is in the assembler's + * include path. + * + * This freertos_risc_v_chip_specific_extensions.h is for use on RISC-V chips + * that include a standard CLINT and do not add to the base set of RISC-V + * registers. + * + */ +#if __riscv_xlen == 64 + #define portWORD_SIZE 8 + #define store_x sd + #define load_x ld +#elif __riscv_xlen == 32 + #define store_x sw + #define load_x lw + #define portWORD_SIZE 4 +#else + #error Assembler did not define __riscv_xlen +#endif + +#if __riscv_flen == 32 +# define fload_x flw +# define fstore_x fsw +#elif __riscv_flen == 64 +# define fload_x fld +# define fstore_x fsd +#endif + +#ifdef __riscv_flen +# define portCONTEXT_SIZE 64 +# define portFLOATING_POINT_SIZE 32 +#else +# define portCONTEXT_SIZE 32 +#endif + + +/* Only the standard core registers are stored by default. Any additional +registers must be saved by the portasmSAVE_ADDITIONAL_REGISTERS and +portasmRESTORE_ADDITIONAL_REGISTERS macros - which can be defined in a chip +specific version of freertos_risc_v_chip_specific_extensions.h. See the notes +at the top of this file. */ + +#include "freertos_risc_v_chip_specific_extensions.h" + +/* Check the freertos_risc_v_chip_specific_extensions.h and/or command line +definitions. */ +#if defined( portasmHAS_CLINT ) && defined( portasmHAS_MTIME ) + #error The portasmHAS_CLINT constant has been deprecated. Please replace it with portasmHAS_MTIME. portasmHAS_CLINT and portasmHAS_MTIME cannot both be defined at once. See https://www.FreeRTOS.org/Using-FreeRTOS-on-RISC-V.html +#endif + +#ifdef portasmHAS_CLINT + #warning The portasmHAS_CLINT constant has been deprecated. Please replace it with portasmHAS_MTIME and portasmHAS_SIFIVE_CLINT. For now portasmHAS_MTIME and portasmHAS_SIFIVE_CLINT are derived from portasmHAS_CLINT. See https://www.FreeRTOS.org/Using-FreeRTOS-on-RISC-V.html + #define portasmHAS_MTIME portasmHAS_CLINT + #define portasmHAS_SIFIVE_CLINT portasmHAS_CLINT +#endif + +#ifndef portasmHAS_MTIME + #error freertos_risc_v_chip_specific_extensions.h must define portasmHAS_MTIME to either 1 (MTIME clock present) or 0 (MTIME clock not present). See https://www.FreeRTOS.org/Using-FreeRTOS-on-RISC-V.html +#endif + +#ifndef portasmHANDLE_INTERRUPT + #error portasmHANDLE_INTERRUPT must be defined to the function to be called to handle external/peripheral interrupts. portasmHANDLE_INTERRUPT can be defined on the assembler command line or in the appropriate freertos_risc_v_chip_specific_extensions.h header file. https://www.FreeRTOS.org/Using-FreeRTOS-on-RISC-V.html +#endif + +#ifndef portasmHAS_SIFIVE_CLINT + #define portasmHAS_SIFIVE_CLINT 0 +#endif + +.global xPortStartFirstTask +.global freertos_risc_v_trap_handler +.global pxPortInitialiseStack +.extern pxCurrentTCB +.extern ulPortTrapHandler +.extern vTaskSwitchContext +.extern xTaskIncrementTick +.extern Timer_IRQHandler +.extern pullMachineTimerCompareRegister +.extern pullNextTime +.extern uxTimerIncrementsForOneTick /* size_t type so 32-bit on 32-bit core and 64-bits on 64-bit core. */ +.extern xISRStackTop +.extern portasmHANDLE_INTERRUPT + +/*-----------------------------------------------------------*/ + +.align 8 +.func +freertos_risc_v_trap_handler: + + addi sp, sp, -portWORD_SIZE*portCONTEXT_SIZE + store_x x1, 1 * portWORD_SIZE( sp ) + store_x x5, 2 * portWORD_SIZE( sp ) + store_x x6, 3 * portWORD_SIZE( sp ) + store_x x7, 4 * portWORD_SIZE( sp ) + store_x x8, 5 * portWORD_SIZE( sp ) + store_x x9, 6 * portWORD_SIZE( sp ) + store_x x10, 7 * portWORD_SIZE( sp ) + store_x x11, 8 * portWORD_SIZE( sp ) + store_x x12, 9 * portWORD_SIZE( sp ) + store_x x13, 10 * portWORD_SIZE( sp ) + store_x x14, 11 * portWORD_SIZE( sp ) + store_x x15, 12 * portWORD_SIZE( sp ) + store_x x16, 13 * portWORD_SIZE( sp ) + store_x x17, 14 * portWORD_SIZE( sp ) + store_x x18, 15 * portWORD_SIZE( sp ) + store_x x19, 16 * portWORD_SIZE( sp ) + store_x x20, 17 * portWORD_SIZE( sp ) + store_x x21, 18 * portWORD_SIZE( sp ) + store_x x22, 19 * portWORD_SIZE( sp ) + store_x x23, 20 * portWORD_SIZE( sp ) + store_x x24, 21 * portWORD_SIZE( sp ) + store_x x25, 22 * portWORD_SIZE( sp ) + store_x x26, 23 * portWORD_SIZE( sp ) + store_x x27, 24 * portWORD_SIZE( sp ) + store_x x28, 25 * portWORD_SIZE( sp ) + store_x x29, 26 * portWORD_SIZE( sp ) + store_x x30, 27 * portWORD_SIZE( sp ) + store_x x31, 28 * portWORD_SIZE( sp ) + #if __riscv_flen > 0 + fstore_x f0, 32 * portWORD_SIZE( sp ) + fstore_x f1, 33 * portWORD_SIZE( sp ) + fstore_x f2, 34 * portWORD_SIZE( sp ) + fstore_x f3, 35 * portWORD_SIZE( sp ) + fstore_x f4, 36 * portWORD_SIZE( sp ) + fstore_x f5, 37 * portWORD_SIZE( sp ) + fstore_x f6, 38 * portWORD_SIZE( sp ) + fstore_x f7, 39 * portWORD_SIZE( sp ) + fstore_x f8, 40 * portWORD_SIZE( sp ) + fstore_x f9, 41 * portWORD_SIZE( sp ) + fstore_x f10, 42 * portWORD_SIZE( sp ) + fstore_x f11, 43 * portWORD_SIZE( sp ) + fstore_x f12, 44 * portWORD_SIZE( sp ) + fstore_x f13, 45 * portWORD_SIZE( sp ) + fstore_x f14, 46 * portWORD_SIZE( sp ) + fstore_x f15, 47 * portWORD_SIZE( sp ) + fstore_x f16, 48 * portWORD_SIZE( sp ) + fstore_x f17, 49 * portWORD_SIZE( sp ) + fstore_x f18, 50 * portWORD_SIZE( sp ) + fstore_x f19, 51 * portWORD_SIZE( sp ) + fstore_x f20, 52 * portWORD_SIZE( sp ) + fstore_x f21, 53 * portWORD_SIZE( sp ) + fstore_x f22, 54 * portWORD_SIZE( sp ) + fstore_x f23, 55 * portWORD_SIZE( sp ) + fstore_x f24, 56 * portWORD_SIZE( sp ) + fstore_x f25, 57 * portWORD_SIZE( sp ) + fstore_x f26, 58 * portWORD_SIZE( sp ) + fstore_x f27, 59 * portWORD_SIZE( sp ) + fstore_x f28, 60 * portWORD_SIZE( sp ) + fstore_x f29, 61 * portWORD_SIZE( sp ) + fstore_x f30, 62 * portWORD_SIZE( sp ) + fstore_x f31, 63 * portWORD_SIZE( sp ) + #endif /* __riscv_flen > 0 */ + + csrr t0, mstatus /* Required for MPIE bit. */ + store_x t0, 29 * portWORD_SIZE( sp ) + + + portasmSAVE_ADDITIONAL_REGISTERS /* Defined in freertos_risc_v_chip_specific_extensions.h to save any registers unique to the RISC-V implementation. */ + + load_x t0, pxCurrentTCB /* Load pxCurrentTCB. */ + store_x sp, 0( t0 ) /* Write sp to first TCB member. */ + + csrr a0, mcause + csrr a1, mepc + +test_if_asynchronous: + srli a2, a0, __riscv_xlen - 1 /* MSB of mcause is 1 if handing an asynchronous interrupt - shift to LSB to clear other bits. */ + beq a2, x0, handle_synchronous /* Branch past interrupt handing if not asynchronous. */ + store_x a1, 0( sp ) /* Asynch so save unmodified exception return address. */ + +handle_asynchronous: + +#if( portasmHAS_MTIME != 0 ) + + test_if_mtimer: /* If there is a CLINT then the mtimer is used to generate the tick interrupt. */ + + addi t0, x0, 1 + + slli t0, t0, __riscv_xlen - 1 /* LSB is already set, shift into MSB. Shift 31 on 32-bit or 63 on 64-bit cores. */ + addi t1, t0, 7 /* 0x8000[]0007 == machine timer interrupt. */ + bne a0, t1, test_if_external_interrupt + + load_x t0, pullMachineTimerCompareRegister /* Load address of compare register into t0. */ + load_x t1, pullNextTime /* Load the address of ullNextTime into t1. */ + + #if( __riscv_xlen == 32 ) + + + /* Update the 64-bit mtimer compare match value in two 32-bit writes. */ + li t4, -1 + lw t2, 0(t1) /* Load the low word of ullNextTime into t2. */ + lw t3, 4(t1) /* Load the high word of ullNextTime into t3. */ + sw t4, 0(t0) /* Low word no smaller than old value to start with - will be overwritten below. */ + sw t3, 4(t0) /* Store high word of ullNextTime into compare register. No smaller than new value. */ + sw t2, 0(t0) /* Store low word of ullNextTime into compare register. */ + lw t0, uxTimerIncrementsForOneTick /* Load the value of ullTimerIncrementForOneTick into t0 (could this be optimized by storing in an array next to pullNextTime?). */ + add t4, t0, t2 /* Add the low word of ullNextTime to the timer increments for one tick (assumes timer increment for one tick fits in 32-bits). */ + sltu t5, t4, t2 /* See if the sum of low words overflowed (what about the zero case?). */ + add t6, t3, t5 /* Add overflow to high word of ullNextTime. */ + sw t4, 0(t1) /* Store new low word of ullNextTime. */ + sw t6, 4(t1) /* Store new high word of ullNextTime. */ + + + + #endif /* __riscv_xlen == 32 */ + + #if( __riscv_xlen == 64 ) + + /* Update the 64-bit mtimer compare match value. */ + ld t2, 0(t1) /* Load ullNextTime into t2. */ + sd t2, 0(t0) /* Store ullNextTime into compare register. */ + ld t0, uxTimerIncrementsForOneTick /* Load the value of ullTimerIncrementForOneTick into t0 (could this be optimized by storing in an array next to pullNextTime?). */ + add t4, t0, t2 /* Add ullNextTime to the timer increments for one tick. */ + sd t4, 0(t1) /* Store ullNextTime. */ + + #endif /* __riscv_xlen == 64 */ + + load_x sp, xISRStackTop /* Switch to ISR stack before function call. */ + jal xTaskIncrementTick + beqz a0, processed_source /* Don't switch context if incrementing tick didn't unblock a task. */ + jal vTaskSwitchContext + j processed_source + + test_if_external_interrupt: + addi t1, t1, 4 /* 0x80000007 + 4 = 0x8000000b == Machine external interrupt. */ + beq a0, t1, handle_external_interrupt /* Something as yet unhandled. */ + + test_if_optional_external_interrupt: + #if( __riscv_xlen == 32 ) + andi t1, a0, 0x10 /* Allows to handle the optionnal external, correctable, uncorretable and OPSRV interrupts */ + #endif + #if( __riscv_xlen == 64 ) + andi t1, a0, 0x30 + #endif + beqz t1, as_yet_unhandled /* If t1 is equal to 0, it is an unhandled trap. */ + + handle_external_interrupt: + #endif /* portasmHAS_MTIME */ + + load_x sp, xISRStackTop /* Switch to ISR stack before function call. */ + jal portasmHANDLE_INTERRUPT /* Jump to the interrupt handler if there is no CLINT or if there is a CLINT and it has been determined that an external interrupt is pending. */ + j processed_source + +handle_synchronous: + addi a1, a1, 4 /* Synchronous so updated exception return address to the instruction after the instruction that generated the exeption. */ + store_x a1, 0( sp ) /* Save updated exception return address. */ + +test_if_environment_call: + li t0, 11 /* 11 == environment call. */ + bne a0, t0, is_exception /* Not an M environment call, so some other exception. */ + load_x sp, xISRStackTop /* Switch to ISR stack before function call. */ + jal vTaskSwitchContext + j processed_source + +is_exception: + csrr t0, mcause /* For viewing in the debugger only. */ + csrr t1, mepc /* For viewing in the debugger only */ + csrr t2, mstatus + j is_exception /* No other exceptions handled yet. */ + +as_yet_unhandled: + csrr t0, mcause /* For viewing in the debugger only. */ + j as_yet_unhandled + +processed_source: + load_x t1, pxCurrentTCB /* Load pxCurrentTCB. */ + load_x sp, 0( t1 ) /* Read sp from first TCB member. */ + + /* Load mret with the address of the next instruction in the task to run next. */ + load_x t0, 0( sp ) + csrw mepc, t0 + + portasmRESTORE_ADDITIONAL_REGISTERS /* Defined in freertos_risc_v_chip_specific_extensions.h to restore any registers unique to the RISC-V implementation. */ + + /* Load mstatus with the interrupt enable bits used by the task. */ + load_x t0, 29 * portWORD_SIZE( sp ) + csrw mstatus, t0 /* Required for MPIE bit. */ + + load_x x1, 1 * portWORD_SIZE( sp ) + load_x x5, 2 * portWORD_SIZE( sp ) /* t0 */ + load_x x6, 3 * portWORD_SIZE( sp ) /* t1 */ + load_x x7, 4 * portWORD_SIZE( sp ) /* t2 */ + load_x x8, 5 * portWORD_SIZE( sp ) /* s0/fp */ + load_x x9, 6 * portWORD_SIZE( sp ) /* s1 */ + load_x x10, 7 * portWORD_SIZE( sp ) /* a0 */ + load_x x11, 8 * portWORD_SIZE( sp ) /* a1 */ + load_x x12, 9 * portWORD_SIZE( sp ) /* a2 */ + load_x x13, 10 * portWORD_SIZE( sp ) /* a3 */ + load_x x14, 11 * portWORD_SIZE( sp ) /* a4 */ + load_x x15, 12 * portWORD_SIZE( sp ) /* a5 */ + load_x x16, 13 * portWORD_SIZE( sp ) /* a6 */ + load_x x17, 14 * portWORD_SIZE( sp ) /* a7 */ + load_x x18, 15 * portWORD_SIZE( sp ) /* s2 */ + load_x x19, 16 * portWORD_SIZE( sp ) /* s3 */ + load_x x20, 17 * portWORD_SIZE( sp ) /* s4 */ + load_x x21, 18 * portWORD_SIZE( sp ) /* s5 */ + load_x x22, 19 * portWORD_SIZE( sp ) /* s6 */ + load_x x23, 20 * portWORD_SIZE( sp ) /* s7 */ + load_x x24, 21 * portWORD_SIZE( sp ) /* s8 */ + load_x x25, 22 * portWORD_SIZE( sp ) /* s9 */ + load_x x26, 23 * portWORD_SIZE( sp ) /* s10 */ + load_x x27, 24 * portWORD_SIZE( sp ) /* s11 */ + load_x x28, 25 * portWORD_SIZE( sp ) /* t3 */ + load_x x29, 26 * portWORD_SIZE( sp ) /* t4 */ + load_x x30, 27 * portWORD_SIZE( sp ) /* t5 */ + load_x x31, 28 * portWORD_SIZE( sp ) /* t6 */ + #if __riscv_flen > 0 + fload_x f0, 32 * portWORD_SIZE( sp ) + fload_x f1, 33 * portWORD_SIZE( sp ) + fload_x f2, 34 * portWORD_SIZE( sp ) + fload_x f3, 35 * portWORD_SIZE( sp ) + fload_x f4, 36 * portWORD_SIZE( sp ) + fload_x f5, 37 * portWORD_SIZE( sp ) + fload_x f6, 38 * portWORD_SIZE( sp ) + fload_x f7, 39 * portWORD_SIZE( sp ) + fload_x f8, 40 * portWORD_SIZE( sp ) + fload_x f9, 41 * portWORD_SIZE( sp ) + fload_x f10, 42 * portWORD_SIZE( sp ) + fload_x f11, 43 * portWORD_SIZE( sp ) + fload_x f12, 44 * portWORD_SIZE( sp ) + fload_x f13, 45 * portWORD_SIZE( sp ) + fload_x f14, 46 * portWORD_SIZE( sp ) + fload_x f15, 47 * portWORD_SIZE( sp ) + fload_x f16, 48 * portWORD_SIZE( sp ) + fload_x f17, 49 * portWORD_SIZE( sp ) + fload_x f18, 50 * portWORD_SIZE( sp ) + fload_x f19, 51 * portWORD_SIZE( sp ) + fload_x f20, 52 * portWORD_SIZE( sp ) + fload_x f21, 53 * portWORD_SIZE( sp ) + fload_x f22, 54 * portWORD_SIZE( sp ) + fload_x f23, 55 * portWORD_SIZE( sp ) + fload_x f24, 56 * portWORD_SIZE( sp ) + fload_x f25, 57 * portWORD_SIZE( sp ) + fload_x f26, 58 * portWORD_SIZE( sp ) + fload_x f27, 59 * portWORD_SIZE( sp ) + fload_x f28, 60 * portWORD_SIZE( sp ) + fload_x f29, 61 * portWORD_SIZE( sp ) + fload_x f30, 62 * portWORD_SIZE( sp ) + fload_x f31, 63 * portWORD_SIZE( sp ) + #endif /* __riscv_flen > 0 */ + addi sp, sp, portWORD_SIZE*portCONTEXT_SIZE + + mret + .endfunc +/*-----------------------------------------------------------*/ + +.align 8 +.func +xPortStartFirstTask: + +#if( portasmHAS_SIFIVE_CLINT != 0 ) + /* If there is a clint then interrupts can branch directly to the FreeRTOS + trap handler. Otherwise the interrupt controller will need to be configured + outside of this file. */ + la t0, freertos_risc_v_trap_handler + csrw mtvec, t0 +#endif /* portasmHAS_CLILNT */ + + load_x sp, pxCurrentTCB /* Load pxCurrentTCB. */ + load_x sp, 0( sp ) /* Read sp from first TCB member. */ + + load_x x1, 0( sp ) /* Note for starting the scheduler the exception return address is used as the function return address. */ + + portasmRESTORE_ADDITIONAL_REGISTERS /* Defined in freertos_risc_v_chip_specific_extensions.h to restore any registers unique to the RISC-V implementation. */ + + load_x x6, 3 * portWORD_SIZE( sp ) /* t1 */ + load_x x7, 4 * portWORD_SIZE( sp ) /* t2 */ + load_x x8, 5 * portWORD_SIZE( sp ) /* s0/fp */ + load_x x9, 6 * portWORD_SIZE( sp ) /* s1 */ + load_x x10, 7 * portWORD_SIZE( sp ) /* a0 */ + load_x x11, 8 * portWORD_SIZE( sp ) /* a1 */ + load_x x12, 9 * portWORD_SIZE( sp ) /* a2 */ + load_x x13, 10 * portWORD_SIZE( sp ) /* a3 */ + load_x x14, 11 * portWORD_SIZE( sp ) /* a4 */ + load_x x15, 12 * portWORD_SIZE( sp ) /* a5 */ + load_x x16, 13 * portWORD_SIZE( sp ) /* a6 */ + load_x x17, 14 * portWORD_SIZE( sp ) /* a7 */ + load_x x18, 15 * portWORD_SIZE( sp ) /* s2 */ + load_x x19, 16 * portWORD_SIZE( sp ) /* s3 */ + load_x x20, 17 * portWORD_SIZE( sp ) /* s4 */ + load_x x21, 18 * portWORD_SIZE( sp ) /* s5 */ + load_x x22, 19 * portWORD_SIZE( sp ) /* s6 */ + load_x x23, 20 * portWORD_SIZE( sp ) /* s7 */ + load_x x24, 21 * portWORD_SIZE( sp ) /* s8 */ + load_x x25, 22 * portWORD_SIZE( sp ) /* s9 */ + load_x x26, 23 * portWORD_SIZE( sp ) /* s10 */ + load_x x27, 24 * portWORD_SIZE( sp ) /* s11 */ + load_x x28, 25 * portWORD_SIZE( sp ) /* t3 */ + load_x x29, 26 * portWORD_SIZE( sp ) /* t4 */ + load_x x30, 27 * portWORD_SIZE( sp ) /* t5 */ + load_x x31, 28 * portWORD_SIZE( sp ) /* t6 */ + #if __riscv_flen > 0 + fload_x f0, 32 * portWORD_SIZE( sp ) + fload_x f1, 33 * portWORD_SIZE( sp ) + fload_x f2, 34 * portWORD_SIZE( sp ) + fload_x f3, 35 * portWORD_SIZE( sp ) + fload_x f4, 36 * portWORD_SIZE( sp ) + fload_x f5, 37 * portWORD_SIZE( sp ) + fload_x f6, 38 * portWORD_SIZE( sp ) + fload_x f7, 39 * portWORD_SIZE( sp ) + fload_x f8, 40 * portWORD_SIZE( sp ) + fload_x f9, 41 * portWORD_SIZE( sp ) + fload_x f10, 42 * portWORD_SIZE( sp ) + fload_x f11, 43 * portWORD_SIZE( sp ) + fload_x f12, 44 * portWORD_SIZE( sp ) + fload_x f13, 45 * portWORD_SIZE( sp ) + fload_x f14, 46 * portWORD_SIZE( sp ) + fload_x f15, 47 * portWORD_SIZE( sp ) + fload_x f16, 48 * portWORD_SIZE( sp ) + fload_x f17, 49 * portWORD_SIZE( sp ) + fload_x f18, 50 * portWORD_SIZE( sp ) + fload_x f19, 51 * portWORD_SIZE( sp ) + fload_x f20, 52 * portWORD_SIZE( sp ) + fload_x f21, 53 * portWORD_SIZE( sp ) + fload_x f22, 54 * portWORD_SIZE( sp ) + fload_x f23, 55 * portWORD_SIZE( sp ) + fload_x f24, 56 * portWORD_SIZE( sp ) + fload_x f25, 57 * portWORD_SIZE( sp ) + fload_x f26, 58 * portWORD_SIZE( sp ) + fload_x f27, 59 * portWORD_SIZE( sp ) + fload_x f28, 60 * portWORD_SIZE( sp ) + fload_x f29, 61 * portWORD_SIZE( sp ) + fload_x f30, 62 * portWORD_SIZE( sp ) + fload_x f31, 63 * portWORD_SIZE( sp ) + #endif /* __riscv_flen > 0 */ + + load_x x5, 29 * portWORD_SIZE( sp ) /* Initial mstatus into x5 (t0) */ + addi x5, x5, 0x08 /* Set MIE bit so the first task starts with interrupts enabled - required as returns with ret not eret. */ + csrrw x0, mstatus, x5 /* Interrupts enabled from here! */ + load_x x5, 2 * portWORD_SIZE( sp ) /* Initial x5 (t0) value. */ + addi sp, sp, portWORD_SIZE*portCONTEXT_SIZE + ret + .endfunc +/*-----------------------------------------------------------*/ + +/* + * Unlike other ports pxPortInitialiseStack() is written in assembly code as it + * needs access to the portasmADDITIONAL_CONTEXT_SIZE constant. The prototype + * for the function is as per the other ports: + * StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters ); + * + * As per the standard RISC-V ABI pxTopcOfStack is passed in in a0, pxCode in + * a1, and pvParameters in a2. The new top of stack is passed out in a0. + * + * RISC-V maps registers to ABI names as follows (X1 to X31 integer registers + * for the 'I' profile, X1 to X15 for the 'E' profile, currently I assumed). + * + * Register ABI Name Description Saver + * x0 zero Hard-wired zero - + * x1 ra Return address Caller + * x2 sp Stack pointer Callee + * x3 gp Global pointer - + * x4 tp Thread pointer - + * x5-7 t0-2 Temporaries Caller + * x8 s0/fp Saved register/Frame pointer Callee + * x9 s1 Saved register Callee + * x10-11 a0-1 Function Arguments/return values Caller + * x12-17 a2-7 Function arguments Caller + * x18-27 s2-11 Saved registers Callee + * x28-31 t3-6 Temporaries Caller + * + * The RISC-V context is saved t FreeRTOS tasks in the following stack frame, + * where the global and thread pointers are currently assumed to be constant so + * are not saved: + * + * mstatus + * x31 + * x30 + * x29 + * x28 + * x27 + * x26 + * x25 + * x24 + * x23 + * x22 + * x21 + * x20 + * x19 + * x18 + * x17 + * x16 + * x15 + * x14 + * x13 + * x12 + * x11 + * pvParameters + * x9 + * x8 + * x7 + * x6 + * x5 + * portTASK_RETURN_ADDRESS + * [chip specific registers go here] + * pxCode + */ +.align 8 +.func +pxPortInitialiseStack: + + csrr t0, mstatus /* Obtain current mstatus value. */ + andi t0, t0, ~0x8 /* Ensure interrupts are disabled when the stack is restored within an ISR. Required when a task is created after the schedulre has been started, otherwise interrupts would be disabled anyway. */ + addi t1, x0, 0x188 /* Generate the value 0x1880, which are the MPIE and MPP bits to set in mstatus. */ + slli t1, t1, 4 + or t0, t0, t1 /* Set MPIE and MPP bits in mstatus value. */ + + #if __riscv_flen > 0 + addi a0, a0, -(portFLOATING_POINT_SIZE * portWORD_SIZE) /* space for floating point registers */ + #endif + addi a0, a0, -portWORD_SIZE + store_x t0, 0(a0) /* mstatus onto the stack. */ + addi a0, a0, -(22 * portWORD_SIZE) /* Space for registers x11-x31. */ + store_x a2, 0(a0) /* Task parameters (pvParameters parameter) goes into register X10/a0 on the stack. */ + addi a0, a0, -(6 * portWORD_SIZE) /* Space for registers x5-x9. */ + store_x x0, 0(a0) /* Return address onto the stack, could be portTASK_RETURN_ADDRESS */ + addi t0, x0, portasmADDITIONAL_CONTEXT_SIZE /* The number of chip specific additional registers. */ +chip_specific_stack_frame: /* First add any chip specific registers to the stack frame being created. */ + beq t0, x0, 1f /* No more chip specific registers to save. */ + addi a0, a0, -portWORD_SIZE /* Make space for chip specific register. */ + store_x x0, 0(a0) /* Give the chip specific register an initial value of zero. */ + addi t0, t0, -1 /* Decrement the count of chip specific registers remaining. */ + j chip_specific_stack_frame /* Until no more chip specific registers. */ +1: + addi a0, a0, -portWORD_SIZE + store_x a1, 0(a0) /* mret value (pxCode parameter) onto the stack. */ + ret + .endfunc +/*-----------------------------------------------------------*/ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/GCC/RISC-V/portmacro.h b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/GCC/RISC-V/portmacro.h new file mode 100644 index 0000000..4e1277a --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/GCC/RISC-V/portmacro.h @@ -0,0 +1,187 @@ +/* + * FreeRTOS Kernel V10.4.4 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + + +#ifndef PORTMACRO_H +#define PORTMACRO_H + +#ifdef __cplusplus +extern "C" { +#endif + +/*----------------------------------------------------------- + * Port specific definitions. + * + * The settings in this file configure FreeRTOS correctly for the + * given hardware and compiler. + * + * These settings should not be altered. + *----------------------------------------------------------- + */ + +/* Type definitions. */ +#if __riscv_xlen == 64 + #define portSTACK_TYPE uint64_t + #define portBASE_TYPE int64_t + #define portUBASE_TYPE uint64_t + #define portMAX_DELAY ( TickType_t ) 0xffffffffffffffffUL + #define portPOINTER_SIZE_TYPE uint64_t +#elif __riscv_xlen == 32 + #define portSTACK_TYPE uint32_t + #define portBASE_TYPE int32_t + #define portUBASE_TYPE uint32_t + #define portMAX_DELAY ( TickType_t ) 0xffffffffUL +#else + #error Assembler did not define __riscv_xlen +#endif + + +typedef portSTACK_TYPE StackType_t; +typedef portBASE_TYPE BaseType_t; +typedef portUBASE_TYPE UBaseType_t; +typedef portUBASE_TYPE TickType_t; + +/* Legacy type definitions. */ +#define portCHAR char +#define portFLOAT float +#define portDOUBLE double +#define portLONG long +#define portSHORT short + +/* 32-bit tick type on a 32-bit architecture, so reads of the tick count do +not need to be guarded with a critical section. */ +#define portTICK_TYPE_IS_ATOMIC 1 +/*-----------------------------------------------------------*/ + +/* Architecture specifics. */ +#define portSTACK_GROWTH ( -1 ) +#define portTICK_PERIOD_MS ( ( TickType_t ) 1000 / configTICK_RATE_HZ ) +#ifdef __riscv64 + #error This is the RV32 port that has not yet been adapted for 64. + #define portBYTE_ALIGNMENT 16 +#else + #define portBYTE_ALIGNMENT 16 +#endif +/*-----------------------------------------------------------*/ + + +/* Scheduler utilities. */ +extern void vTaskSwitchContext( void ); +#define portYIELD() __asm volatile( "ecall" ); +#define portEND_SWITCHING_ISR( xSwitchRequired ) do { if( xSwitchRequired ) vTaskSwitchContext(); } while( 0 ) +#define portYIELD_FROM_ISR( x ) portEND_SWITCHING_ISR( x ) +/*-----------------------------------------------------------*/ + + +/* Critical section management. */ +#define portCRITICAL_NESTING_IN_TCB 1 +extern void vTaskEnterCritical( void ); +extern void vTaskExitCritical( void ); + +#define portSET_INTERRUPT_MASK_FROM_ISR() 0 +#define portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedStatusValue ) ( void ) uxSavedStatusValue +#define portDISABLE_INTERRUPTS() __asm volatile( "csrc mstatus, 8" ) +#define portENABLE_INTERRUPTS() __asm volatile( "csrs mstatus, 8" ) +#define portENTER_CRITICAL() vTaskEnterCritical() +#define portEXIT_CRITICAL() vTaskExitCritical() + +/*-----------------------------------------------------------*/ + +/* Architecture specific optimisations. */ +#ifndef configUSE_PORT_OPTIMISED_TASK_SELECTION + #define configUSE_PORT_OPTIMISED_TASK_SELECTION 1 +#endif + +#if( configUSE_PORT_OPTIMISED_TASK_SELECTION == 1 ) + + /* Check the configuration. */ + #if( configMAX_PRIORITIES > 32 ) + #error configUSE_PORT_OPTIMISED_TASK_SELECTION can only be set to 1 when configMAX_PRIORITIES is less than or equal to 32. It is very rare that a system requires more than 10 to 15 difference priorities as tasks that share a priority will time slice. + #endif + + /* Store/clear the ready priorities in a bit map. */ + #define portRECORD_READY_PRIORITY( uxPriority, uxReadyPriorities ) ( uxReadyPriorities ) |= ( 1UL << ( uxPriority ) ) + #define portRESET_READY_PRIORITY( uxPriority, uxReadyPriorities ) ( uxReadyPriorities ) &= ~( 1UL << ( uxPriority ) ) + + /*-----------------------------------------------------------*/ + + #define portGET_HIGHEST_PRIORITY( uxTopPriority, uxReadyPriorities ) uxTopPriority = ( 31UL - __builtin_clz( uxReadyPriorities ) ) + +#endif /* configUSE_PORT_OPTIMISED_TASK_SELECTION */ + + +/*-----------------------------------------------------------*/ + +/* Task function macros as described on the FreeRTOS.org WEB site. These are +not necessary for to use this port. They are defined so the common demo files +(which build with all the ports) will build. */ +#define portTASK_FUNCTION_PROTO( vFunction, pvParameters ) void vFunction( void *pvParameters ) +#define portTASK_FUNCTION( vFunction, pvParameters ) void vFunction( void *pvParameters ) + +/*-----------------------------------------------------------*/ + +#define portNOP() __asm volatile ( " nop " ) + +#define portINLINE __inline + +#ifndef portFORCE_INLINE + #define portFORCE_INLINE inline __attribute__(( always_inline)) +#endif + +#define portMEMORY_BARRIER() __asm volatile( "" ::: "memory" ) +/*-----------------------------------------------------------*/ + + +/* configCLINT_BASE_ADDRESS is a legacy definition that was replaced by the +configMTIME_BASE_ADDRESS and configMTIMECMP_BASE_ADDRESS definitions. For +backward compatibility derive the newer definitions from the old if the old +definition is found. */ +#if defined( configCLINT_BASE_ADDRESS ) && !defined( configMTIME_BASE_ADDRESS ) && ( configCLINT_BASE_ADDRESS == 0 ) + /* Legacy case where configCLINT_BASE_ADDRESS was defined as 0 to indicate + there was no CLINT. Equivalent now is to set the MTIME and MTIMECMP + addresses to 0. */ + #define configMTIME_BASE_ADDRESS ( 0 ) + #define configMTIMECMP_BASE_ADDRESS ( 0 ) +#elif defined( configCLINT_BASE_ADDRESS ) && !defined( configMTIME_BASE_ADDRESS ) + /* Legacy case where configCLINT_BASE_ADDRESS was set to the base address of + the CLINT. Equivalent now is to derive the MTIME and MTIMECMP addresses + from the CLINT address. */ + #define configMTIME_BASE_ADDRESS ( ( configCLINT_BASE_ADDRESS ) + 0xBFF8UL ) + #define configMTIMECMP_BASE_ADDRESS ( ( configCLINT_BASE_ADDRESS ) + 0x4000UL ) +#elif !defined( configMTIME_BASE_ADDRESS ) || !defined( configMTIMECMP_BASE_ADDRESS ) + #error configMTIME_BASE_ADDRESS and configMTIMECMP_BASE_ADDRESS must be defined in FreeRTOSConfig.h. Set them to zero if there is no MTIME (machine time) clock. See https://www.FreeRTOS.org/Using-FreeRTOS-on-RISC-V.html +#endif + + + +#ifdef __cplusplus +} +#endif + +#endif /* PORTMACRO_H */ + diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/GCC/RISC-V/readme.txt b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/GCC/RISC-V/readme.txt new file mode 100644 index 0000000..b24c0b9 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/GCC/RISC-V/readme.txt @@ -0,0 +1,23 @@ +/* + * The FreeRTOS kernel's RISC-V port is split between the the code that is + * common across all currently supported RISC-V chips (implementations of the + * RISC-V ISA), and code that tailors the port to a specific RISC-V chip: + * + * + FreeRTOS\Source\portable\GCC\RISC-V-RV32\portASM.S contains the code that + * is common to all currently supported RISC-V chips. There is only one + * portASM.S file because the same file is built for all RISC-V target chips. + * + * + Header files called freertos_risc_v_chip_specific_extensions.h contain the + * code that tailors the FreeRTOS kernel's RISC-V port to a specific RISC-V + * chip. There are multiple freertos_risc_v_chip_specific_extensions.h files + * as there are multiple RISC-V chip implementations. + * + * !!!NOTE!!! + * TAKE CARE TO INCLUDE THE CORRECT freertos_risc_v_chip_specific_extensions.h + * HEADER FILE FOR THE CHIP IN USE. This is done using the assembler's (not the + * compiler's!) include path. For example, if the chip in use includes a core + * local interrupter (CLINT) and does not include any chip specific register + * extensions then add the path below to the assembler's include path: + * FreeRTOS\Source\portable\GCC\RISC-V-RV32\chip_specific_extensions\RV32I_CLINT_no_extensions + * + */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/MemMang/ReadMe.url b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/MemMang/ReadMe.url new file mode 100644 index 0000000..28c9937 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/MemMang/ReadMe.url @@ -0,0 +1,5 @@ +[{000214A0-0000-0000-C000-000000000046}] +Prop3=19,2 +[InternetShortcut] +URL=https://www.FreeRTOS.org/a00111.html +IDList= diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/MemMang/heap_4.c b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/MemMang/heap_4.c new file mode 100644 index 0000000..cf26cc0 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/MemMang/heap_4.c @@ -0,0 +1,504 @@ +/* + * FreeRTOS Kernel V10.4.4 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* + * A sample implementation of pvPortMalloc() and vPortFree() that combines + * (coalescences) adjacent memory blocks as they are freed, and in so doing + * limits memory fragmentation. + * + * See heap_1.c, heap_2.c and heap_3.c for alternative implementations, and the + * memory management pages of https://www.FreeRTOS.org for more information. + */ +#include + +/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining + * all the API functions to use the MPU wrappers. That should only be done when + * task.h is included from an application file. */ +#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +#include "FreeRTOS.h" +#include "task.h" + +#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +#if ( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) + #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 +#endif + +/* Block sizes must not get too small. */ +#define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( xHeapStructSize << 1 ) ) + +/* Assumes 8bit bytes! */ +#define heapBITS_PER_BYTE ( ( size_t ) 8 ) + +/* Allocate the memory for the heap. */ +#if ( configAPPLICATION_ALLOCATED_HEAP == 1 ) + +/* The application writer has already defined the array used for the RTOS +* heap - probably so it can be placed in a special segment or address. */ + extern uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; +#else + PRIVILEGED_DATA static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; +#endif /* configAPPLICATION_ALLOCATED_HEAP */ + +/* Define the linked list structure. This is used to link free blocks in order + * of their memory address. */ +typedef struct A_BLOCK_LINK +{ + struct A_BLOCK_LINK * pxNextFreeBlock; /*<< The next free block in the list. */ + size_t xBlockSize; /*<< The size of the free block. */ +} BlockLink_t; + +/*-----------------------------------------------------------*/ + +/* + * Inserts a block of memory that is being freed into the correct position in + * the list of free memory blocks. The block being freed will be merged with + * the block in front it and/or the block behind it if the memory blocks are + * adjacent to each other. + */ +static void prvInsertBlockIntoFreeList( BlockLink_t * pxBlockToInsert ) PRIVILEGED_FUNCTION; + +/* + * Called automatically to setup the required heap structures the first time + * pvPortMalloc() is called. + */ +static void prvHeapInit( void ) PRIVILEGED_FUNCTION; + +/*-----------------------------------------------------------*/ + +/* The size of the structure placed at the beginning of each allocated memory + * block must by correctly byte aligned. */ +static const size_t xHeapStructSize = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); + +/* Create a couple of list links to mark the start and end of the list. */ +PRIVILEGED_DATA static BlockLink_t xStart, * pxEnd = NULL; + +/* Keeps track of the number of calls to allocate and free memory as well as the + * number of free bytes remaining, but says nothing about fragmentation. */ +PRIVILEGED_DATA static size_t xFreeBytesRemaining = 0U; +PRIVILEGED_DATA static size_t xMinimumEverFreeBytesRemaining = 0U; +PRIVILEGED_DATA static size_t xNumberOfSuccessfulAllocations = 0; +PRIVILEGED_DATA static size_t xNumberOfSuccessfulFrees = 0; + +/* Gets set to the top bit of an size_t type. When this bit in the xBlockSize + * member of an BlockLink_t structure is set then the block belongs to the + * application. When the bit is free the block is still part of the free heap + * space. */ +PRIVILEGED_DATA static size_t xBlockAllocatedBit = 0; + +/*-----------------------------------------------------------*/ + +void * pvPortMalloc( size_t xWantedSize ) +{ + BlockLink_t * pxBlock, * pxPreviousBlock, * pxNewBlockLink; + void * pvReturn = NULL; + + vTaskSuspendAll(); + { + /* If this is the first call to malloc then the heap will require + * initialisation to setup the list of free blocks. */ + if( pxEnd == NULL ) + { + prvHeapInit(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Check the requested block size is not so large that the top bit is + * set. The top bit of the block size member of the BlockLink_t structure + * is used to determine who owns the block - the application or the + * kernel, so it must be free. */ + if( ( xWantedSize & xBlockAllocatedBit ) == 0 ) + { + /* The wanted size must be increased so it can contain a BlockLink_t + * structure in addition to the requested amount of bytes. */ + if( ( xWantedSize > 0 ) && + ( ( xWantedSize + xHeapStructSize ) > xWantedSize ) ) /* Overflow check */ + { + xWantedSize += xHeapStructSize; + + /* Ensure that blocks are always aligned. */ + if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 ) + { + /* Byte alignment required. Check for overflow. */ + if( ( xWantedSize + ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ) ) + > xWantedSize ) + { + xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); + configASSERT( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) == 0 ); + } + else + { + xWantedSize = 0; + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + xWantedSize = 0; + } + + if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) ) + { + /* Traverse the list from the start (lowest address) block until + * one of adequate size is found. */ + pxPreviousBlock = &xStart; + pxBlock = xStart.pxNextFreeBlock; + + while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) ) + { + pxPreviousBlock = pxBlock; + pxBlock = pxBlock->pxNextFreeBlock; + } + + /* If the end marker was reached then a block of adequate size + * was not found. */ + if( pxBlock != pxEnd ) + { + /* Return the memory space pointed to - jumping over the + * BlockLink_t structure at its start. */ + pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize ); + + /* This block is being returned for use so must be taken out + * of the list of free blocks. */ + pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock; + + /* If the block is larger than required it can be split into + * two. */ + if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE ) + { + /* This block is to be split into two. Create a new + * block following the number of bytes requested. The void + * cast is used to prevent byte alignment warnings from the + * compiler. */ + pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize ); + configASSERT( ( ( ( size_t ) pxNewBlockLink ) & portBYTE_ALIGNMENT_MASK ) == 0 ); + + /* Calculate the sizes of two blocks split from the + * single block. */ + pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize; + pxBlock->xBlockSize = xWantedSize; + + /* Insert the new block into the list of free blocks. */ + prvInsertBlockIntoFreeList( pxNewBlockLink ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + xFreeBytesRemaining -= pxBlock->xBlockSize; + + if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining ) + { + xMinimumEverFreeBytesRemaining = xFreeBytesRemaining; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* The block is being returned - it is allocated and owned + * by the application and has no "next" block. */ + pxBlock->xBlockSize |= xBlockAllocatedBit; + pxBlock->pxNextFreeBlock = NULL; + xNumberOfSuccessfulAllocations++; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceMALLOC( pvReturn, xWantedSize ); + } + ( void ) xTaskResumeAll(); + + #if ( configUSE_MALLOC_FAILED_HOOK == 1 ) + { + if( pvReturn == NULL ) + { + extern void vApplicationMallocFailedHook( void ); + vApplicationMallocFailedHook(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* if ( configUSE_MALLOC_FAILED_HOOK == 1 ) */ + + configASSERT( ( ( ( size_t ) pvReturn ) & ( size_t ) portBYTE_ALIGNMENT_MASK ) == 0 ); + return pvReturn; +} +/*-----------------------------------------------------------*/ + +void vPortFree( void * pv ) +{ + uint8_t * puc = ( uint8_t * ) pv; + BlockLink_t * pxLink; + + if( pv != NULL ) + { + /* The memory being freed will have an BlockLink_t structure immediately + * before it. */ + puc -= xHeapStructSize; + + /* This casting is to keep the compiler from issuing warnings. */ + pxLink = ( void * ) puc; + + /* Check the block is actually allocated. */ + configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ); + configASSERT( pxLink->pxNextFreeBlock == NULL ); + + if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ) + { + if( pxLink->pxNextFreeBlock == NULL ) + { + /* The block is being returned to the heap - it is no longer + * allocated. */ + pxLink->xBlockSize &= ~xBlockAllocatedBit; + + vTaskSuspendAll(); + { + /* Add this block to the list of free blocks. */ + xFreeBytesRemaining += pxLink->xBlockSize; + traceFREE( pv, pxLink->xBlockSize ); + prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) ); + xNumberOfSuccessfulFrees++; + } + ( void ) xTaskResumeAll(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } +} +/*-----------------------------------------------------------*/ + +size_t xPortGetFreeHeapSize( void ) +{ + return xFreeBytesRemaining; +} +/*-----------------------------------------------------------*/ + +size_t xPortGetMinimumEverFreeHeapSize( void ) +{ + return xMinimumEverFreeBytesRemaining; +} +/*-----------------------------------------------------------*/ + +void vPortInitialiseBlocks( void ) +{ + /* This just exists to keep the linker quiet. */ +} +/*-----------------------------------------------------------*/ + +static void prvHeapInit( void ) /* PRIVILEGED_FUNCTION */ +{ + BlockLink_t * pxFirstFreeBlock; + uint8_t * pucAlignedHeap; + size_t uxAddress; + size_t xTotalHeapSize = configTOTAL_HEAP_SIZE; + + /* Ensure the heap starts on a correctly aligned boundary. */ + uxAddress = ( size_t ) ucHeap; + + if( ( uxAddress & portBYTE_ALIGNMENT_MASK ) != 0 ) + { + uxAddress += ( portBYTE_ALIGNMENT - 1 ); + uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); + xTotalHeapSize -= uxAddress - ( size_t ) ucHeap; + } + + pucAlignedHeap = ( uint8_t * ) uxAddress; + + /* xStart is used to hold a pointer to the first item in the list of free + * blocks. The void cast is used to prevent compiler warnings. */ + xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap; + xStart.xBlockSize = ( size_t ) 0; + + /* pxEnd is used to mark the end of the list of free blocks and is inserted + * at the end of the heap space. */ + uxAddress = ( ( size_t ) pucAlignedHeap ) + xTotalHeapSize; + uxAddress -= xHeapStructSize; + uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); + pxEnd = ( void * ) uxAddress; + pxEnd->xBlockSize = 0; + pxEnd->pxNextFreeBlock = NULL; + + /* To start with there is a single free block that is sized to take up the + * entire heap space, minus the space taken by pxEnd. */ + pxFirstFreeBlock = ( void * ) pucAlignedHeap; + pxFirstFreeBlock->xBlockSize = uxAddress - ( size_t ) pxFirstFreeBlock; + pxFirstFreeBlock->pxNextFreeBlock = pxEnd; + + /* Only one block exists - and it covers the entire usable heap space. */ + xMinimumEverFreeBytesRemaining = pxFirstFreeBlock->xBlockSize; + xFreeBytesRemaining = pxFirstFreeBlock->xBlockSize; + + /* Work out the position of the top bit in a size_t variable. */ + xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 ); +} +/*-----------------------------------------------------------*/ + +static void prvInsertBlockIntoFreeList( BlockLink_t * pxBlockToInsert ) /* PRIVILEGED_FUNCTION */ +{ + BlockLink_t * pxIterator; + uint8_t * puc; + + /* Iterate through the list until a block is found that has a higher address + * than the block being inserted. */ + for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock ) + { + /* Nothing to do here, just iterate to the right position. */ + } + + /* Do the block being inserted, and the block it is being inserted after + * make a contiguous block of memory? */ + puc = ( uint8_t * ) pxIterator; + + if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert ) + { + pxIterator->xBlockSize += pxBlockToInsert->xBlockSize; + pxBlockToInsert = pxIterator; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Do the block being inserted, and the block it is being inserted before + * make a contiguous block of memory? */ + puc = ( uint8_t * ) pxBlockToInsert; + + if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock ) + { + if( pxIterator->pxNextFreeBlock != pxEnd ) + { + /* Form one big block from the two blocks. */ + pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize; + pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock; + } + else + { + pxBlockToInsert->pxNextFreeBlock = pxEnd; + } + } + else + { + pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock; + } + + /* If the block being inserted plugged a gab, so was merged with the block + * before and the block after, then it's pxNextFreeBlock pointer will have + * already been set, and should not be set here as that would make it point + * to itself. */ + if( pxIterator != pxBlockToInsert ) + { + pxIterator->pxNextFreeBlock = pxBlockToInsert; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } +} +/*-----------------------------------------------------------*/ + +void vPortGetHeapStats( HeapStats_t * pxHeapStats ) +{ + BlockLink_t * pxBlock; + size_t xBlocks = 0, xMaxSize = 0, xMinSize = portMAX_DELAY; /* portMAX_DELAY used as a portable way of getting the maximum value. */ + + vTaskSuspendAll(); + { + pxBlock = xStart.pxNextFreeBlock; + + /* pxBlock will be NULL if the heap has not been initialised. The heap + * is initialised automatically when the first allocation is made. */ + if( pxBlock != NULL ) + { + do + { + /* Increment the number of blocks and record the largest block seen + * so far. */ + xBlocks++; + + if( pxBlock->xBlockSize > xMaxSize ) + { + xMaxSize = pxBlock->xBlockSize; + } + + if( pxBlock->xBlockSize < xMinSize ) + { + xMinSize = pxBlock->xBlockSize; + } + + /* Move to the next block in the chain until the last block is + * reached. */ + pxBlock = pxBlock->pxNextFreeBlock; + } while( pxBlock != pxEnd ); + } + } + ( void ) xTaskResumeAll(); + + pxHeapStats->xSizeOfLargestFreeBlockInBytes = xMaxSize; + pxHeapStats->xSizeOfSmallestFreeBlockInBytes = xMinSize; + pxHeapStats->xNumberOfFreeBlocks = xBlocks; + + taskENTER_CRITICAL(); + { + pxHeapStats->xAvailableHeapSpaceInBytes = xFreeBytesRemaining; + pxHeapStats->xNumberOfSuccessfulAllocations = xNumberOfSuccessfulAllocations; + pxHeapStats->xNumberOfSuccessfulFrees = xNumberOfSuccessfulFrees; + pxHeapStats->xMinimumEverFreeBytesRemaining = xMinimumEverFreeBytesRemaining; + } + taskEXIT_CRITICAL(); +} diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/readme.txt b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/readme.txt new file mode 100644 index 0000000..89f6b09 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/portable/readme.txt @@ -0,0 +1,20 @@ +Each real time kernel port consists of three files that contain the core kernel +components and are common to every port, and one or more files that are +specific to a particular microcontroller and/or compiler. + + ++ The FreeRTOS/Source/Portable/MemMang directory contains the five sample +memory allocators as described on the https://www.FreeRTOS.org WEB site. + ++ The other directories each contain files specific to a particular +microcontroller or compiler, where the directory name denotes the compiler +specific files the directory contains. + + + +For example, if you are interested in the [compiler] port for the [architecture] +microcontroller, then the port specific files are contained in +FreeRTOS/Source/Portable/[compiler]/[architecture] directory. If this is the +only port you are interested in then all the other directories can be +ignored. + diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/queue.c b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/queue.c new file mode 100644 index 0000000..46ed9a4 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/queue.c @@ -0,0 +1,3075 @@ +/* + * FreeRTOS Kernel V10.4.6 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#include +#include + +/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining + * all the API functions to use the MPU wrappers. That should only be done when + * task.h is included from an application file. */ +#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" + +#if ( configUSE_CO_ROUTINES == 1 ) + #include "croutine.h" +#endif + +/* Lint e9021, e961 and e750 are suppressed as a MISRA exception justified + * because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined + * for the header files above, but not in this file, in order to generate the + * correct privileged Vs unprivileged linkage and placement. */ +#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750 !e9021. */ + + +/* Constants used with the cRxLock and cTxLock structure members. */ +#define queueUNLOCKED ( ( int8_t ) -1 ) +#define queueLOCKED_UNMODIFIED ( ( int8_t ) 0 ) +#define queueINT8_MAX ( ( int8_t ) 127 ) + +/* When the Queue_t structure is used to represent a base queue its pcHead and + * pcTail members are used as pointers into the queue storage area. When the + * Queue_t structure is used to represent a mutex pcHead and pcTail pointers are + * not necessary, and the pcHead pointer is set to NULL to indicate that the + * structure instead holds a pointer to the mutex holder (if any). Map alternative + * names to the pcHead and structure member to ensure the readability of the code + * is maintained. The QueuePointers_t and SemaphoreData_t types are used to form + * a union as their usage is mutually exclusive dependent on what the queue is + * being used for. */ +#define uxQueueType pcHead +#define queueQUEUE_IS_MUTEX NULL + +typedef struct QueuePointers +{ + int8_t * pcTail; /*< Points to the byte at the end of the queue storage area. Once more byte is allocated than necessary to store the queue items, this is used as a marker. */ + int8_t * pcReadFrom; /*< Points to the last place that a queued item was read from when the structure is used as a queue. */ +} QueuePointers_t; + +typedef struct SemaphoreData +{ + TaskHandle_t xMutexHolder; /*< The handle of the task that holds the mutex. */ + UBaseType_t uxRecursiveCallCount; /*< Maintains a count of the number of times a recursive mutex has been recursively 'taken' when the structure is used as a mutex. */ +} SemaphoreData_t; + +/* Semaphores do not actually store or copy data, so have an item size of + * zero. */ +#define queueSEMAPHORE_QUEUE_ITEM_LENGTH ( ( UBaseType_t ) 0 ) +#define queueMUTEX_GIVE_BLOCK_TIME ( ( TickType_t ) 0U ) + +#if ( configUSE_PREEMPTION == 0 ) + +/* If the cooperative scheduler is being used then a yield should not be + * performed just because a higher priority task has been woken. */ + #define queueYIELD_IF_USING_PREEMPTION() +#else + #define queueYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API() +#endif + +/* + * Definition of the queue used by the scheduler. + * Items are queued by copy, not reference. See the following link for the + * rationale: https://www.FreeRTOS.org/Embedded-RTOS-Queues.html + */ +typedef struct QueueDefinition /* The old naming convention is used to prevent breaking kernel aware debuggers. */ +{ + int8_t * pcHead; /*< Points to the beginning of the queue storage area. */ + int8_t * pcWriteTo; /*< Points to the free next place in the storage area. */ + + union + { + QueuePointers_t xQueue; /*< Data required exclusively when this structure is used as a queue. */ + SemaphoreData_t xSemaphore; /*< Data required exclusively when this structure is used as a semaphore. */ + } u; + + List_t xTasksWaitingToSend; /*< List of tasks that are blocked waiting to post onto this queue. Stored in priority order. */ + List_t xTasksWaitingToReceive; /*< List of tasks that are blocked waiting to read from this queue. Stored in priority order. */ + + volatile UBaseType_t uxMessagesWaiting; /*< The number of items currently in the queue. */ + UBaseType_t uxLength; /*< The length of the queue defined as the number of items it will hold, not the number of bytes. */ + UBaseType_t uxItemSize; /*< The size of each items that the queue will hold. */ + + volatile int8_t cRxLock; /*< Stores the number of items received from the queue (removed from the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */ + volatile int8_t cTxLock; /*< Stores the number of items transmitted to the queue (added to the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */ + + #if ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the memory used by the queue was statically allocated to ensure no attempt is made to free the memory. */ + #endif + + #if ( configUSE_QUEUE_SETS == 1 ) + struct QueueDefinition * pxQueueSetContainer; + #endif + + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxQueueNumber; + uint8_t ucQueueType; + #endif +} xQUEUE; + +/* The old xQUEUE name is maintained above then typedefed to the new Queue_t + * name below to enable the use of older kernel aware debuggers. */ +typedef xQUEUE Queue_t; + +/*-----------------------------------------------------------*/ + +/* + * The queue registry is just a means for kernel aware debuggers to locate + * queue structures. It has no other purpose so is an optional component. + */ +#if ( configQUEUE_REGISTRY_SIZE > 0 ) + +/* The type stored within the queue registry array. This allows a name + * to be assigned to each queue making kernel aware debugging a little + * more user friendly. */ + typedef struct QUEUE_REGISTRY_ITEM + { + const char * pcQueueName; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + QueueHandle_t xHandle; + } xQueueRegistryItem; + +/* The old xQueueRegistryItem name is maintained above then typedefed to the + * new xQueueRegistryItem name below to enable the use of older kernel aware + * debuggers. */ + typedef xQueueRegistryItem QueueRegistryItem_t; + +/* The queue registry is simply an array of QueueRegistryItem_t structures. + * The pcQueueName member of a structure being NULL is indicative of the + * array position being vacant. */ + PRIVILEGED_DATA QueueRegistryItem_t xQueueRegistry[ configQUEUE_REGISTRY_SIZE ]; + +#endif /* configQUEUE_REGISTRY_SIZE */ + +/* + * Unlocks a queue locked by a call to prvLockQueue. Locking a queue does not + * prevent an ISR from adding or removing items to the queue, but does prevent + * an ISR from removing tasks from the queue event lists. If an ISR finds a + * queue is locked it will instead increment the appropriate queue lock count + * to indicate that a task may require unblocking. When the queue in unlocked + * these lock counts are inspected, and the appropriate action taken. + */ +static void prvUnlockQueue( Queue_t * const pxQueue ) PRIVILEGED_FUNCTION; + +/* + * Uses a critical section to determine if there is any data in a queue. + * + * @return pdTRUE if the queue contains no items, otherwise pdFALSE. + */ +static BaseType_t prvIsQueueEmpty( const Queue_t * pxQueue ) PRIVILEGED_FUNCTION; + +/* + * Uses a critical section to determine if there is any space in a queue. + * + * @return pdTRUE if there is no space, otherwise pdFALSE; + */ +static BaseType_t prvIsQueueFull( const Queue_t * pxQueue ) PRIVILEGED_FUNCTION; + +/* + * Copies an item into the queue, either at the front of the queue or the + * back of the queue. + */ +static BaseType_t prvCopyDataToQueue( Queue_t * const pxQueue, + const void * pvItemToQueue, + const BaseType_t xPosition ) PRIVILEGED_FUNCTION; + +/* + * Copies an item out of a queue. + */ +static void prvCopyDataFromQueue( Queue_t * const pxQueue, + void * const pvBuffer ) PRIVILEGED_FUNCTION; + +#if ( configUSE_QUEUE_SETS == 1 ) + +/* + * Checks to see if a queue is a member of a queue set, and if so, notifies + * the queue set that the queue contains data. + */ + static BaseType_t prvNotifyQueueSetContainer( const Queue_t * const pxQueue ) PRIVILEGED_FUNCTION; +#endif + +/* + * Called after a Queue_t structure has been allocated either statically or + * dynamically to fill in the structure's members. + */ +static void prvInitialiseNewQueue( const UBaseType_t uxQueueLength, + const UBaseType_t uxItemSize, + uint8_t * pucQueueStorage, + const uint8_t ucQueueType, + Queue_t * pxNewQueue ) PRIVILEGED_FUNCTION; + +/* + * Mutexes are a special type of queue. When a mutex is created, first the + * queue is created, then prvInitialiseMutex() is called to configure the queue + * as a mutex. + */ +#if ( configUSE_MUTEXES == 1 ) + static void prvInitialiseMutex( Queue_t * pxNewQueue ) PRIVILEGED_FUNCTION; +#endif + +#if ( configUSE_MUTEXES == 1 ) + +/* + * If a task waiting for a mutex causes the mutex holder to inherit a + * priority, but the waiting task times out, then the holder should + * disinherit the priority - but only down to the highest priority of any + * other tasks that are waiting for the same mutex. This function returns + * that priority. + */ + static UBaseType_t prvGetDisinheritPriorityAfterTimeout( const Queue_t * const pxQueue ) PRIVILEGED_FUNCTION; +#endif +/*-----------------------------------------------------------*/ + +/* + * Macro to mark a queue as locked. Locking a queue prevents an ISR from + * accessing the queue event lists. + */ +#define prvLockQueue( pxQueue ) \ + taskENTER_CRITICAL(); \ + { \ + if( ( pxQueue )->cRxLock == queueUNLOCKED ) \ + { \ + ( pxQueue )->cRxLock = queueLOCKED_UNMODIFIED; \ + } \ + if( ( pxQueue )->cTxLock == queueUNLOCKED ) \ + { \ + ( pxQueue )->cTxLock = queueLOCKED_UNMODIFIED; \ + } \ + } \ + taskEXIT_CRITICAL() +/*-----------------------------------------------------------*/ + +BaseType_t xQueueGenericReset( QueueHandle_t xQueue, + BaseType_t xNewQueue ) +{ + BaseType_t xReturn = pdPASS; + Queue_t * const pxQueue = xQueue; + + configASSERT( pxQueue ); + + if( ( pxQueue != NULL ) && + ( pxQueue->uxLength >= 1U ) && + /* Check for multiplication overflow. */ + ( ( SIZE_MAX / pxQueue->uxLength ) >= pxQueue->uxItemSize ) ) + { + taskENTER_CRITICAL(); + { + pxQueue->u.xQueue.pcTail = pxQueue->pcHead + ( pxQueue->uxLength * pxQueue->uxItemSize ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */ + pxQueue->uxMessagesWaiting = ( UBaseType_t ) 0U; + pxQueue->pcWriteTo = pxQueue->pcHead; + pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead + ( ( pxQueue->uxLength - 1U ) * pxQueue->uxItemSize ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */ + pxQueue->cRxLock = queueUNLOCKED; + pxQueue->cTxLock = queueUNLOCKED; + + if( xNewQueue == pdFALSE ) + { + /* If there are tasks blocked waiting to read from the queue, then + * the tasks will remain blocked as after this function exits the queue + * will still be empty. If there are tasks blocked waiting to write to + * the queue, then one should be unblocked as after this function exits + * it will be possible to write to it. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* Ensure the event queues start in the correct state. */ + vListInitialise( &( pxQueue->xTasksWaitingToSend ) ); + vListInitialise( &( pxQueue->xTasksWaitingToReceive ) ); + } + } + taskEXIT_CRITICAL(); + } + else + { + xReturn = pdFAIL; + } + + configASSERT( xReturn != pdFAIL ); + + /* A value is returned for calling semantic consistency with previous + * versions. */ + return xReturn; +} +/*-----------------------------------------------------------*/ + +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + + QueueHandle_t xQueueGenericCreateStatic( const UBaseType_t uxQueueLength, + const UBaseType_t uxItemSize, + uint8_t * pucQueueStorage, + StaticQueue_t * pxStaticQueue, + const uint8_t ucQueueType ) + { + Queue_t * pxNewQueue = NULL; + + /* The StaticQueue_t structure and the queue storage area must be + * supplied. */ + configASSERT( pxStaticQueue ); + + if( ( uxQueueLength > ( UBaseType_t ) 0 ) && + ( pxStaticQueue != NULL ) && + + /* A queue storage area should be provided if the item size is not 0, and + * should not be provided if the item size is 0. */ + ( !( ( pucQueueStorage != NULL ) && ( uxItemSize == 0 ) ) ) && + ( !( ( pucQueueStorage == NULL ) && ( uxItemSize != 0 ) ) ) ) + { + #if ( configASSERT_DEFINED == 1 ) + { + /* Sanity check that the size of the structure used to declare a + * variable of type StaticQueue_t or StaticSemaphore_t equals the size of + * the real queue and semaphore structures. */ + volatile size_t xSize = sizeof( StaticQueue_t ); + + /* This assertion cannot be branch covered in unit tests */ + configASSERT( xSize == sizeof( Queue_t ) ); /* LCOV_EXCL_BR_LINE */ + ( void ) xSize; /* Keeps lint quiet when configASSERT() is not defined. */ + } + #endif /* configASSERT_DEFINED */ + + /* The address of a statically allocated queue was passed in, use it. + * The address of a statically allocated storage area was also passed in + * but is already set. */ + pxNewQueue = ( Queue_t * ) pxStaticQueue; /*lint !e740 !e9087 Unusual cast is ok as the structures are designed to have the same alignment, and the size is checked by an assert. */ + + #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + { + /* Queues can be allocated wither statically or dynamically, so + * note this queue was allocated statically in case the queue is + * later deleted. */ + pxNewQueue->ucStaticallyAllocated = pdTRUE; + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + + prvInitialiseNewQueue( uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue ); + } + else + { + configASSERT( pxNewQueue ); + mtCOVERAGE_TEST_MARKER(); + } + + return pxNewQueue; + } + +#endif /* configSUPPORT_STATIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + + QueueHandle_t xQueueGenericCreate( const UBaseType_t uxQueueLength, + const UBaseType_t uxItemSize, + const uint8_t ucQueueType ) + { + Queue_t * pxNewQueue = NULL; + size_t xQueueSizeInBytes; + uint8_t * pucQueueStorage; + + if( ( uxQueueLength > ( UBaseType_t ) 0 ) && + /* Check for multiplication overflow. */ + ( ( SIZE_MAX / uxQueueLength ) >= uxItemSize ) && + /* Check for addition overflow. */ + ( ( SIZE_MAX - sizeof( Queue_t ) ) >= ( uxQueueLength * uxItemSize ) ) ) + { + /* Allocate enough space to hold the maximum number of items that + * can be in the queue at any time. It is valid for uxItemSize to be + * zero in the case the queue is used as a semaphore. */ + xQueueSizeInBytes = ( size_t ) ( uxQueueLength * uxItemSize ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + + /* Allocate the queue and storage area. Justification for MISRA + * deviation as follows: pvPortMalloc() always ensures returned memory + * blocks are aligned per the requirements of the MCU stack. In this case + * pvPortMalloc() must return a pointer that is guaranteed to meet the + * alignment requirements of the Queue_t structure - which in this case + * is an int8_t *. Therefore, whenever the stack alignment requirements + * are greater than or equal to the pointer to char requirements the cast + * is safe. In other cases alignment requirements are not strict (one or + * two bytes). */ + pxNewQueue = ( Queue_t * ) pvPortMalloc( sizeof( Queue_t ) + xQueueSizeInBytes ); /*lint !e9087 !e9079 see comment above. */ + + if( pxNewQueue != NULL ) + { + /* Jump past the queue structure to find the location of the queue + * storage area. */ + pucQueueStorage = ( uint8_t * ) pxNewQueue; + pucQueueStorage += sizeof( Queue_t ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */ + + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + /* Queues can be created either statically or dynamically, so + * note this task was created dynamically in case it is later + * deleted. */ + pxNewQueue->ucStaticallyAllocated = pdFALSE; + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ + + prvInitialiseNewQueue( uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue ); + } + else + { + traceQUEUE_CREATE_FAILED( ucQueueType ); + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + configASSERT( pxNewQueue ); + mtCOVERAGE_TEST_MARKER(); + } + + return pxNewQueue; + } + +#endif /* configSUPPORT_STATIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +static void prvInitialiseNewQueue( const UBaseType_t uxQueueLength, + const UBaseType_t uxItemSize, + uint8_t * pucQueueStorage, + const uint8_t ucQueueType, + Queue_t * pxNewQueue ) +{ + /* Remove compiler warnings about unused parameters should + * configUSE_TRACE_FACILITY not be set to 1. */ + ( void ) ucQueueType; + + if( uxItemSize == ( UBaseType_t ) 0 ) + { + /* No RAM was allocated for the queue storage area, but PC head cannot + * be set to NULL because NULL is used as a key to say the queue is used as + * a mutex. Therefore just set pcHead to point to the queue as a benign + * value that is known to be within the memory map. */ + pxNewQueue->pcHead = ( int8_t * ) pxNewQueue; + } + else + { + /* Set the head to the start of the queue storage area. */ + pxNewQueue->pcHead = ( int8_t * ) pucQueueStorage; + } + + /* Initialise the queue members as described where the queue type is + * defined. */ + pxNewQueue->uxLength = uxQueueLength; + pxNewQueue->uxItemSize = uxItemSize; + ( void ) xQueueGenericReset( pxNewQueue, pdTRUE ); + + #if ( configUSE_TRACE_FACILITY == 1 ) + { + pxNewQueue->ucQueueType = ucQueueType; + } + #endif /* configUSE_TRACE_FACILITY */ + + #if ( configUSE_QUEUE_SETS == 1 ) + { + pxNewQueue->pxQueueSetContainer = NULL; + } + #endif /* configUSE_QUEUE_SETS */ + + traceQUEUE_CREATE( pxNewQueue ); +} +/*-----------------------------------------------------------*/ + +#if ( configUSE_MUTEXES == 1 ) + + static void prvInitialiseMutex( Queue_t * pxNewQueue ) + { + if( pxNewQueue != NULL ) + { + /* The queue create function will set all the queue structure members + * correctly for a generic queue, but this function is creating a + * mutex. Overwrite those members that need to be set differently - + * in particular the information required for priority inheritance. */ + pxNewQueue->u.xSemaphore.xMutexHolder = NULL; + pxNewQueue->uxQueueType = queueQUEUE_IS_MUTEX; + + /* In case this is a recursive mutex. */ + pxNewQueue->u.xSemaphore.uxRecursiveCallCount = 0; + + traceCREATE_MUTEX( pxNewQueue ); + + /* Start with the semaphore in the expected state. */ + ( void ) xQueueGenericSend( pxNewQueue, NULL, ( TickType_t ) 0U, queueSEND_TO_BACK ); + } + else + { + traceCREATE_MUTEX_FAILED(); + } + } + +#endif /* configUSE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_MUTEXES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + + QueueHandle_t xQueueCreateMutex( const uint8_t ucQueueType ) + { + QueueHandle_t xNewQueue; + const UBaseType_t uxMutexLength = ( UBaseType_t ) 1, uxMutexSize = ( UBaseType_t ) 0; + + xNewQueue = xQueueGenericCreate( uxMutexLength, uxMutexSize, ucQueueType ); + prvInitialiseMutex( ( Queue_t * ) xNewQueue ); + + return xNewQueue; + } + +#endif /* configUSE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_MUTEXES == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + + QueueHandle_t xQueueCreateMutexStatic( const uint8_t ucQueueType, + StaticQueue_t * pxStaticQueue ) + { + QueueHandle_t xNewQueue; + const UBaseType_t uxMutexLength = ( UBaseType_t ) 1, uxMutexSize = ( UBaseType_t ) 0; + + /* Prevent compiler warnings about unused parameters if + * configUSE_TRACE_FACILITY does not equal 1. */ + ( void ) ucQueueType; + + xNewQueue = xQueueGenericCreateStatic( uxMutexLength, uxMutexSize, NULL, pxStaticQueue, ucQueueType ); + prvInitialiseMutex( ( Queue_t * ) xNewQueue ); + + return xNewQueue; + } + +#endif /* configUSE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) ) + + TaskHandle_t xQueueGetMutexHolder( QueueHandle_t xSemaphore ) + { + TaskHandle_t pxReturn; + Queue_t * const pxSemaphore = ( Queue_t * ) xSemaphore; + + configASSERT( xSemaphore ); + + /* This function is called by xSemaphoreGetMutexHolder(), and should not + * be called directly. Note: This is a good way of determining if the + * calling task is the mutex holder, but not a good way of determining the + * identity of the mutex holder, as the holder may change between the + * following critical section exiting and the function returning. */ + taskENTER_CRITICAL(); + { + if( pxSemaphore->uxQueueType == queueQUEUE_IS_MUTEX ) + { + pxReturn = pxSemaphore->u.xSemaphore.xMutexHolder; + } + else + { + pxReturn = NULL; + } + } + taskEXIT_CRITICAL(); + + return pxReturn; + } /*lint !e818 xSemaphore cannot be a pointer to const because it is a typedef. */ + +#endif /* if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) ) + + TaskHandle_t xQueueGetMutexHolderFromISR( QueueHandle_t xSemaphore ) + { + TaskHandle_t pxReturn; + + configASSERT( xSemaphore ); + + /* Mutexes cannot be used in interrupt service routines, so the mutex + * holder should not change in an ISR, and therefore a critical section is + * not required here. */ + if( ( ( Queue_t * ) xSemaphore )->uxQueueType == queueQUEUE_IS_MUTEX ) + { + pxReturn = ( ( Queue_t * ) xSemaphore )->u.xSemaphore.xMutexHolder; + } + else + { + pxReturn = NULL; + } + + return pxReturn; + } /*lint !e818 xSemaphore cannot be a pointer to const because it is a typedef. */ + +#endif /* if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_RECURSIVE_MUTEXES == 1 ) + + BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) + { + BaseType_t xReturn; + Queue_t * const pxMutex = ( Queue_t * ) xMutex; + + configASSERT( pxMutex ); + + /* If this is the task that holds the mutex then xMutexHolder will not + * change outside of this task. If this task does not hold the mutex then + * pxMutexHolder can never coincidentally equal the tasks handle, and as + * this is the only condition we are interested in it does not matter if + * pxMutexHolder is accessed simultaneously by another task. Therefore no + * mutual exclusion is required to test the pxMutexHolder variable. */ + if( pxMutex->u.xSemaphore.xMutexHolder == xTaskGetCurrentTaskHandle() ) + { + traceGIVE_MUTEX_RECURSIVE( pxMutex ); + + /* uxRecursiveCallCount cannot be zero if xMutexHolder is equal to + * the task handle, therefore no underflow check is required. Also, + * uxRecursiveCallCount is only modified by the mutex holder, and as + * there can only be one, no mutual exclusion is required to modify the + * uxRecursiveCallCount member. */ + ( pxMutex->u.xSemaphore.uxRecursiveCallCount )--; + + /* Has the recursive call count unwound to 0? */ + if( pxMutex->u.xSemaphore.uxRecursiveCallCount == ( UBaseType_t ) 0 ) + { + /* Return the mutex. This will automatically unblock any other + * task that might be waiting to access the mutex. */ + ( void ) xQueueGenericSend( pxMutex, NULL, queueMUTEX_GIVE_BLOCK_TIME, queueSEND_TO_BACK ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + xReturn = pdPASS; + } + else + { + /* The mutex cannot be given because the calling task is not the + * holder. */ + xReturn = pdFAIL; + + traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex ); + } + + return xReturn; + } + +#endif /* configUSE_RECURSIVE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_RECURSIVE_MUTEXES == 1 ) + + BaseType_t xQueueTakeMutexRecursive( QueueHandle_t xMutex, + TickType_t xTicksToWait ) + { + BaseType_t xReturn; + Queue_t * const pxMutex = ( Queue_t * ) xMutex; + + configASSERT( pxMutex ); + + /* Comments regarding mutual exclusion as per those within + * xQueueGiveMutexRecursive(). */ + + traceTAKE_MUTEX_RECURSIVE( pxMutex ); + + if( pxMutex->u.xSemaphore.xMutexHolder == xTaskGetCurrentTaskHandle() ) + { + ( pxMutex->u.xSemaphore.uxRecursiveCallCount )++; + xReturn = pdPASS; + } + else + { + xReturn = xQueueSemaphoreTake( pxMutex, xTicksToWait ); + + /* pdPASS will only be returned if the mutex was successfully + * obtained. The calling task may have entered the Blocked state + * before reaching here. */ + if( xReturn != pdFAIL ) + { + ( pxMutex->u.xSemaphore.uxRecursiveCallCount )++; + } + else + { + traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex ); + } + } + + return xReturn; + } + +#endif /* configUSE_RECURSIVE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + + QueueHandle_t xQueueCreateCountingSemaphoreStatic( const UBaseType_t uxMaxCount, + const UBaseType_t uxInitialCount, + StaticQueue_t * pxStaticQueue ) + { + QueueHandle_t xHandle = NULL; + + if( ( uxMaxCount != 0 ) && + ( uxInitialCount <= uxMaxCount ) ) + { + xHandle = xQueueGenericCreateStatic( uxMaxCount, queueSEMAPHORE_QUEUE_ITEM_LENGTH, NULL, pxStaticQueue, queueQUEUE_TYPE_COUNTING_SEMAPHORE ); + + if( xHandle != NULL ) + { + ( ( Queue_t * ) xHandle )->uxMessagesWaiting = uxInitialCount; + + traceCREATE_COUNTING_SEMAPHORE(); + } + else + { + traceCREATE_COUNTING_SEMAPHORE_FAILED(); + } + } + else + { + configASSERT( xHandle ); + mtCOVERAGE_TEST_MARKER(); + } + + return xHandle; + } + +#endif /* ( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + + QueueHandle_t xQueueCreateCountingSemaphore( const UBaseType_t uxMaxCount, + const UBaseType_t uxInitialCount ) + { + QueueHandle_t xHandle = NULL; + + if( ( uxMaxCount != 0 ) && + ( uxInitialCount <= uxMaxCount ) ) + { + xHandle = xQueueGenericCreate( uxMaxCount, queueSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_COUNTING_SEMAPHORE ); + + if( xHandle != NULL ) + { + ( ( Queue_t * ) xHandle )->uxMessagesWaiting = uxInitialCount; + + traceCREATE_COUNTING_SEMAPHORE(); + } + else + { + traceCREATE_COUNTING_SEMAPHORE_FAILED(); + } + } + else + { + configASSERT( xHandle ); + mtCOVERAGE_TEST_MARKER(); + } + + return xHandle; + } + +#endif /* ( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) */ +/*-----------------------------------------------------------*/ + +BaseType_t xQueueGenericSend( QueueHandle_t xQueue, + const void * const pvItemToQueue, + TickType_t xTicksToWait, + const BaseType_t xCopyPosition ) +{ + BaseType_t xEntryTimeSet = pdFALSE, xYieldRequired; + TimeOut_t xTimeOut; + Queue_t * const pxQueue = xQueue; + + configASSERT( pxQueue ); + configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); + configASSERT( !( ( xCopyPosition == queueOVERWRITE ) && ( pxQueue->uxLength != 1 ) ) ); + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif + + /*lint -save -e904 This function relaxes the coding standard somewhat to + * allow return statements within the function itself. This is done in the + * interest of execution time efficiency. */ + for( ; ; ) + { + taskENTER_CRITICAL(); + { + /* Is there room on the queue now? The running task must be the + * highest priority task wanting to access the queue. If the head item + * in the queue is to be overwritten then it does not matter if the + * queue is full. */ + if( ( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) || ( xCopyPosition == queueOVERWRITE ) ) + { + traceQUEUE_SEND( pxQueue ); + + #if ( configUSE_QUEUE_SETS == 1 ) + { + const UBaseType_t uxPreviousMessagesWaiting = pxQueue->uxMessagesWaiting; + + xYieldRequired = prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); + + if( pxQueue->pxQueueSetContainer != NULL ) + { + if( ( xCopyPosition == queueOVERWRITE ) && ( uxPreviousMessagesWaiting != ( UBaseType_t ) 0 ) ) + { + /* Do not notify the queue set as an existing item + * was overwritten in the queue so the number of items + * in the queue has not changed. */ + mtCOVERAGE_TEST_MARKER(); + } + else if( prvNotifyQueueSetContainer( pxQueue ) != pdFALSE ) + { + /* The queue is a member of a queue set, and posting + * to the queue set caused a higher priority task to + * unblock. A context switch is required. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* If there was a task waiting for data to arrive on the + * queue then unblock it now. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The unblocked task has a priority higher than + * our own so yield immediately. Yes it is ok to + * do this from within the critical section - the + * kernel takes care of that. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else if( xYieldRequired != pdFALSE ) + { + /* This path is a special case that will only get + * executed if the task was holding multiple mutexes + * and the mutexes were given back in an order that is + * different to that in which they were taken. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + #else /* configUSE_QUEUE_SETS */ + { + xYieldRequired = prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); + + /* If there was a task waiting for data to arrive on the + * queue then unblock it now. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The unblocked task has a priority higher than + * our own so yield immediately. Yes it is ok to do + * this from within the critical section - the kernel + * takes care of that. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else if( xYieldRequired != pdFALSE ) + { + /* This path is a special case that will only get + * executed if the task was holding multiple mutexes and + * the mutexes were given back in an order that is + * different to that in which they were taken. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_QUEUE_SETS */ + + taskEXIT_CRITICAL(); + return pdPASS; + } + else + { + if( xTicksToWait == ( TickType_t ) 0 ) + { + /* The queue was full and no block time is specified (or + * the block time has expired) so leave now. */ + taskEXIT_CRITICAL(); + + /* Return to the original privilege level before exiting + * the function. */ + traceQUEUE_SEND_FAILED( pxQueue ); + return errQUEUE_FULL; + } + else if( xEntryTimeSet == pdFALSE ) + { + /* The queue was full and a block time was specified so + * configure the timeout structure. */ + vTaskInternalSetTimeOutState( &xTimeOut ); + xEntryTimeSet = pdTRUE; + } + else + { + /* Entry time was already set. */ + mtCOVERAGE_TEST_MARKER(); + } + } + } + taskEXIT_CRITICAL(); + + /* Interrupts and other tasks can send to and receive from the queue + * now the critical section has been exited. */ + + vTaskSuspendAll(); + prvLockQueue( pxQueue ); + + /* Update the timeout state to see if it has expired yet. */ + if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) + { + if( prvIsQueueFull( pxQueue ) != pdFALSE ) + { + traceBLOCKING_ON_QUEUE_SEND( pxQueue ); + vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToSend ), xTicksToWait ); + + /* Unlocking the queue means queue events can effect the + * event list. It is possible that interrupts occurring now + * remove this task from the event list again - but as the + * scheduler is suspended the task will go onto the pending + * ready list instead of the actual ready list. */ + prvUnlockQueue( pxQueue ); + + /* Resuming the scheduler will move tasks from the pending + * ready list into the ready list - so it is feasible that this + * task is already in the ready list before it yields - in which + * case the yield will not cause a context switch unless there + * is also a higher priority task in the pending ready list. */ + if( xTaskResumeAll() == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + } + else + { + /* Try again. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + } + } + else + { + /* The timeout has expired. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + + traceQUEUE_SEND_FAILED( pxQueue ); + return errQUEUE_FULL; + } + } /*lint -restore */ +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueueGenericSendFromISR( QueueHandle_t xQueue, + const void * const pvItemToQueue, + BaseType_t * const pxHigherPriorityTaskWoken, + const BaseType_t xCopyPosition ) +{ + BaseType_t xReturn; + UBaseType_t uxSavedInterruptStatus; + Queue_t * const pxQueue = xQueue; + + configASSERT( pxQueue ); + configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); + configASSERT( !( ( xCopyPosition == queueOVERWRITE ) && ( pxQueue->uxLength != 1 ) ) ); + + /* RTOS ports that support interrupt nesting have the concept of a maximum + * system call (or maximum API call) interrupt priority. Interrupts that are + * above the maximum system call priority are kept permanently enabled, even + * when the RTOS kernel is in a critical section, but cannot make any calls to + * FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h + * then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + * failure if a FreeRTOS API function is called from an interrupt that has been + * assigned a priority above the configured maximum system call priority. + * Only FreeRTOS functions that end in FromISR can be called from interrupts + * that have been assigned a priority at or (logically) below the maximum + * system call interrupt priority. FreeRTOS maintains a separate interrupt + * safe API to ensure interrupt entry is as fast and as simple as possible. + * More information (albeit Cortex-M specific) is provided on the following + * link: https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + /* Similar to xQueueGenericSend, except without blocking if there is no room + * in the queue. Also don't directly wake a task that was blocked on a queue + * read, instead return a flag to say whether a context switch is required or + * not (i.e. has a task with a higher priority than us been woken by this + * post). */ + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + if( ( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) || ( xCopyPosition == queueOVERWRITE ) ) + { + const int8_t cTxLock = pxQueue->cTxLock; + const UBaseType_t uxPreviousMessagesWaiting = pxQueue->uxMessagesWaiting; + + traceQUEUE_SEND_FROM_ISR( pxQueue ); + + /* Semaphores use xQueueGiveFromISR(), so pxQueue will not be a + * semaphore or mutex. That means prvCopyDataToQueue() cannot result + * in a task disinheriting a priority and prvCopyDataToQueue() can be + * called here even though the disinherit function does not check if + * the scheduler is suspended before accessing the ready lists. */ + ( void ) prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); + + /* The event list is not altered if the queue is locked. This will + * be done when the queue is unlocked later. */ + if( cTxLock == queueUNLOCKED ) + { + #if ( configUSE_QUEUE_SETS == 1 ) + { + if( pxQueue->pxQueueSetContainer != NULL ) + { + if( ( xCopyPosition == queueOVERWRITE ) && ( uxPreviousMessagesWaiting != ( UBaseType_t ) 0 ) ) + { + /* Do not notify the queue set as an existing item + * was overwritten in the queue so the number of items + * in the queue has not changed. */ + mtCOVERAGE_TEST_MARKER(); + } + else if( prvNotifyQueueSetContainer( pxQueue ) != pdFALSE ) + { + /* The queue is a member of a queue set, and posting + * to the queue set caused a higher priority task to + * unblock. A context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so + * record that a context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + #else /* configUSE_QUEUE_SETS */ + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so record that a + * context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Not used in this path. */ + ( void ) uxPreviousMessagesWaiting; + } + #endif /* configUSE_QUEUE_SETS */ + } + else + { + /* Increment the lock count so the task that unlocks the queue + * knows that data was posted while it was locked. */ + configASSERT( cTxLock != queueINT8_MAX ); + + pxQueue->cTxLock = ( int8_t ) ( cTxLock + 1 ); + } + + xReturn = pdPASS; + } + else + { + traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ); + xReturn = errQUEUE_FULL; + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueueGiveFromISR( QueueHandle_t xQueue, + BaseType_t * const pxHigherPriorityTaskWoken ) +{ + BaseType_t xReturn; + UBaseType_t uxSavedInterruptStatus; + Queue_t * const pxQueue = xQueue; + + /* Similar to xQueueGenericSendFromISR() but used with semaphores where the + * item size is 0. Don't directly wake a task that was blocked on a queue + * read, instead return a flag to say whether a context switch is required or + * not (i.e. has a task with a higher priority than us been woken by this + * post). */ + + configASSERT( pxQueue ); + + /* xQueueGenericSendFromISR() should be used instead of xQueueGiveFromISR() + * if the item size is not 0. */ + configASSERT( pxQueue->uxItemSize == 0 ); + + /* Normally a mutex would not be given from an interrupt, especially if + * there is a mutex holder, as priority inheritance makes no sense for an + * interrupts, only tasks. */ + configASSERT( !( ( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) && ( pxQueue->u.xSemaphore.xMutexHolder != NULL ) ) ); + + /* RTOS ports that support interrupt nesting have the concept of a maximum + * system call (or maximum API call) interrupt priority. Interrupts that are + * above the maximum system call priority are kept permanently enabled, even + * when the RTOS kernel is in a critical section, but cannot make any calls to + * FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h + * then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + * failure if a FreeRTOS API function is called from an interrupt that has been + * assigned a priority above the configured maximum system call priority. + * Only FreeRTOS functions that end in FromISR can be called from interrupts + * that have been assigned a priority at or (logically) below the maximum + * system call interrupt priority. FreeRTOS maintains a separate interrupt + * safe API to ensure interrupt entry is as fast and as simple as possible. + * More information (albeit Cortex-M specific) is provided on the following + * link: https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; + + /* When the queue is used to implement a semaphore no data is ever + * moved through the queue but it is still valid to see if the queue 'has + * space'. */ + if( uxMessagesWaiting < pxQueue->uxLength ) + { + const int8_t cTxLock = pxQueue->cTxLock; + + traceQUEUE_SEND_FROM_ISR( pxQueue ); + + /* A task can only have an inherited priority if it is a mutex + * holder - and if there is a mutex holder then the mutex cannot be + * given from an ISR. As this is the ISR version of the function it + * can be assumed there is no mutex holder and no need to determine if + * priority disinheritance is needed. Simply increase the count of + * messages (semaphores) available. */ + pxQueue->uxMessagesWaiting = uxMessagesWaiting + ( UBaseType_t ) 1; + + /* The event list is not altered if the queue is locked. This will + * be done when the queue is unlocked later. */ + if( cTxLock == queueUNLOCKED ) + { + #if ( configUSE_QUEUE_SETS == 1 ) + { + if( pxQueue->pxQueueSetContainer != NULL ) + { + if( prvNotifyQueueSetContainer( pxQueue ) != pdFALSE ) + { + /* The semaphore is a member of a queue set, and + * posting to the queue set caused a higher priority + * task to unblock. A context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so + * record that a context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + #else /* configUSE_QUEUE_SETS */ + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so record that a + * context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_QUEUE_SETS */ + } + else + { + /* Increment the lock count so the task that unlocks the queue + * knows that data was posted while it was locked. */ + configASSERT( cTxLock != queueINT8_MAX ); + + pxQueue->cTxLock = ( int8_t ) ( cTxLock + 1 ); + } + + xReturn = pdPASS; + } + else + { + traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ); + xReturn = errQUEUE_FULL; + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueueReceive( QueueHandle_t xQueue, + void * const pvBuffer, + TickType_t xTicksToWait ) +{ + BaseType_t xEntryTimeSet = pdFALSE; + TimeOut_t xTimeOut; + Queue_t * const pxQueue = xQueue; + + /* Check the pointer is not NULL. */ + configASSERT( ( pxQueue ) ); + + /* The buffer into which data is received can only be NULL if the data size + * is zero (so no data is copied into the buffer). */ + configASSERT( !( ( ( pvBuffer ) == NULL ) && ( ( pxQueue )->uxItemSize != ( UBaseType_t ) 0U ) ) ); + + /* Cannot block if the scheduler is suspended. */ + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif + + /*lint -save -e904 This function relaxes the coding standard somewhat to + * allow return statements within the function itself. This is done in the + * interest of execution time efficiency. */ + for( ; ; ) + { + taskENTER_CRITICAL(); + { + const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; + + /* Is there data in the queue now? To be running the calling task + * must be the highest priority task wanting to access the queue. */ + if( uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* Data available, remove one item. */ + prvCopyDataFromQueue( pxQueue, pvBuffer ); + traceQUEUE_RECEIVE( pxQueue ); + pxQueue->uxMessagesWaiting = uxMessagesWaiting - ( UBaseType_t ) 1; + + /* There is now space in the queue, were any tasks waiting to + * post to the queue? If so, unblock the highest priority waiting + * task. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + taskEXIT_CRITICAL(); + return pdPASS; + } + else + { + if( xTicksToWait == ( TickType_t ) 0 ) + { + /* The queue was empty and no block time is specified (or + * the block time has expired) so leave now. */ + taskEXIT_CRITICAL(); + traceQUEUE_RECEIVE_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else if( xEntryTimeSet == pdFALSE ) + { + /* The queue was empty and a block time was specified so + * configure the timeout structure. */ + vTaskInternalSetTimeOutState( &xTimeOut ); + xEntryTimeSet = pdTRUE; + } + else + { + /* Entry time was already set. */ + mtCOVERAGE_TEST_MARKER(); + } + } + } + taskEXIT_CRITICAL(); + + /* Interrupts and other tasks can send to and receive from the queue + * now the critical section has been exited. */ + + vTaskSuspendAll(); + prvLockQueue( pxQueue ); + + /* Update the timeout state to see if it has expired yet. */ + if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) + { + /* The timeout has not expired. If the queue is still empty place + * the task on the list of tasks waiting to receive from the queue. */ + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ); + vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); + prvUnlockQueue( pxQueue ); + + if( xTaskResumeAll() == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* The queue contains data again. Loop back to try and read the + * data. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + } + } + else + { + /* Timed out. If there is no data in the queue exit, otherwise loop + * back and attempt to read the data. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceQUEUE_RECEIVE_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } /*lint -restore */ +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueueSemaphoreTake( QueueHandle_t xQueue, + TickType_t xTicksToWait ) +{ + BaseType_t xEntryTimeSet = pdFALSE; + TimeOut_t xTimeOut; + Queue_t * const pxQueue = xQueue; + + #if ( configUSE_MUTEXES == 1 ) + BaseType_t xInheritanceOccurred = pdFALSE; + #endif + + /* Check the queue pointer is not NULL. */ + configASSERT( ( pxQueue ) ); + + /* Check this really is a semaphore, in which case the item size will be + * 0. */ + configASSERT( pxQueue->uxItemSize == 0 ); + + /* Cannot block if the scheduler is suspended. */ + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif + + /*lint -save -e904 This function relaxes the coding standard somewhat to allow return + * statements within the function itself. This is done in the interest + * of execution time efficiency. */ + for( ; ; ) + { + taskENTER_CRITICAL(); + { + /* Semaphores are queues with an item size of 0, and where the + * number of messages in the queue is the semaphore's count value. */ + const UBaseType_t uxSemaphoreCount = pxQueue->uxMessagesWaiting; + + /* Is there data in the queue now? To be running the calling task + * must be the highest priority task wanting to access the queue. */ + if( uxSemaphoreCount > ( UBaseType_t ) 0 ) + { + traceQUEUE_RECEIVE( pxQueue ); + + /* Semaphores are queues with a data size of zero and where the + * messages waiting is the semaphore's count. Reduce the count. */ + pxQueue->uxMessagesWaiting = uxSemaphoreCount - ( UBaseType_t ) 1; + + #if ( configUSE_MUTEXES == 1 ) + { + if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) + { + /* Record the information required to implement + * priority inheritance should it become necessary. */ + pxQueue->u.xSemaphore.xMutexHolder = pvTaskIncrementMutexHeldCount(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_MUTEXES */ + + /* Check to see if other tasks are blocked waiting to give the + * semaphore, and if so, unblock the highest priority such task. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + taskEXIT_CRITICAL(); + return pdPASS; + } + else + { + if( xTicksToWait == ( TickType_t ) 0 ) + { + /* For inheritance to have occurred there must have been an + * initial timeout, and an adjusted timeout cannot become 0, as + * if it were 0 the function would have exited. */ + #if ( configUSE_MUTEXES == 1 ) + { + configASSERT( xInheritanceOccurred == pdFALSE ); + } + #endif /* configUSE_MUTEXES */ + + /* The semaphore count was 0 and no block time is specified + * (or the block time has expired) so exit now. */ + taskEXIT_CRITICAL(); + traceQUEUE_RECEIVE_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else if( xEntryTimeSet == pdFALSE ) + { + /* The semaphore count was 0 and a block time was specified + * so configure the timeout structure ready to block. */ + vTaskInternalSetTimeOutState( &xTimeOut ); + xEntryTimeSet = pdTRUE; + } + else + { + /* Entry time was already set. */ + mtCOVERAGE_TEST_MARKER(); + } + } + } + taskEXIT_CRITICAL(); + + /* Interrupts and other tasks can give to and take from the semaphore + * now the critical section has been exited. */ + + vTaskSuspendAll(); + prvLockQueue( pxQueue ); + + /* Update the timeout state to see if it has expired yet. */ + if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) + { + /* A block time is specified and not expired. If the semaphore + * count is 0 then enter the Blocked state to wait for a semaphore to + * become available. As semaphores are implemented with queues the + * queue being empty is equivalent to the semaphore count being 0. */ + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ); + + #if ( configUSE_MUTEXES == 1 ) + { + if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) + { + taskENTER_CRITICAL(); + { + xInheritanceOccurred = xTaskPriorityInherit( pxQueue->u.xSemaphore.xMutexHolder ); + } + taskEXIT_CRITICAL(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* if ( configUSE_MUTEXES == 1 ) */ + + vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); + prvUnlockQueue( pxQueue ); + + if( xTaskResumeAll() == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* There was no timeout and the semaphore count was not 0, so + * attempt to take the semaphore again. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + } + } + else + { + /* Timed out. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + + /* If the semaphore count is 0 exit now as the timeout has + * expired. Otherwise return to attempt to take the semaphore that is + * known to be available. As semaphores are implemented by queues the + * queue being empty is equivalent to the semaphore count being 0. */ + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + #if ( configUSE_MUTEXES == 1 ) + { + /* xInheritanceOccurred could only have be set if + * pxQueue->uxQueueType == queueQUEUE_IS_MUTEX so no need to + * test the mutex type again to check it is actually a mutex. */ + if( xInheritanceOccurred != pdFALSE ) + { + taskENTER_CRITICAL(); + { + UBaseType_t uxHighestWaitingPriority; + + /* This task blocking on the mutex caused another + * task to inherit this task's priority. Now this task + * has timed out the priority should be disinherited + * again, but only as low as the next highest priority + * task that is waiting for the same mutex. */ + uxHighestWaitingPriority = prvGetDisinheritPriorityAfterTimeout( pxQueue ); + vTaskPriorityDisinheritAfterTimeout( pxQueue->u.xSemaphore.xMutexHolder, uxHighestWaitingPriority ); + } + taskEXIT_CRITICAL(); + } + } + #endif /* configUSE_MUTEXES */ + + traceQUEUE_RECEIVE_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } /*lint -restore */ +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueuePeek( QueueHandle_t xQueue, + void * const pvBuffer, + TickType_t xTicksToWait ) +{ + BaseType_t xEntryTimeSet = pdFALSE; + TimeOut_t xTimeOut; + int8_t * pcOriginalReadPosition; + Queue_t * const pxQueue = xQueue; + + /* Check the pointer is not NULL. */ + configASSERT( ( pxQueue ) ); + + /* The buffer into which data is received can only be NULL if the data size + * is zero (so no data is copied into the buffer. */ + configASSERT( !( ( ( pvBuffer ) == NULL ) && ( ( pxQueue )->uxItemSize != ( UBaseType_t ) 0U ) ) ); + + /* Cannot block if the scheduler is suspended. */ + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif + + /*lint -save -e904 This function relaxes the coding standard somewhat to + * allow return statements within the function itself. This is done in the + * interest of execution time efficiency. */ + for( ; ; ) + { + taskENTER_CRITICAL(); + { + const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; + + /* Is there data in the queue now? To be running the calling task + * must be the highest priority task wanting to access the queue. */ + if( uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* Remember the read position so it can be reset after the data + * is read from the queue as this function is only peeking the + * data, not removing it. */ + pcOriginalReadPosition = pxQueue->u.xQueue.pcReadFrom; + + prvCopyDataFromQueue( pxQueue, pvBuffer ); + traceQUEUE_PEEK( pxQueue ); + + /* The data is not being removed, so reset the read pointer. */ + pxQueue->u.xQueue.pcReadFrom = pcOriginalReadPosition; + + /* The data is being left in the queue, so see if there are + * any other tasks waiting for the data. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority than this task. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + taskEXIT_CRITICAL(); + return pdPASS; + } + else + { + if( xTicksToWait == ( TickType_t ) 0 ) + { + /* The queue was empty and no block time is specified (or + * the block time has expired) so leave now. */ + taskEXIT_CRITICAL(); + traceQUEUE_PEEK_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else if( xEntryTimeSet == pdFALSE ) + { + /* The queue was empty and a block time was specified so + * configure the timeout structure ready to enter the blocked + * state. */ + vTaskInternalSetTimeOutState( &xTimeOut ); + xEntryTimeSet = pdTRUE; + } + else + { + /* Entry time was already set. */ + mtCOVERAGE_TEST_MARKER(); + } + } + } + taskEXIT_CRITICAL(); + + /* Interrupts and other tasks can send to and receive from the queue + * now that the critical section has been exited. */ + + vTaskSuspendAll(); + prvLockQueue( pxQueue ); + + /* Update the timeout state to see if it has expired yet. */ + if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) + { + /* Timeout has not expired yet, check to see if there is data in the + * queue now, and if not enter the Blocked state to wait for data. */ + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceBLOCKING_ON_QUEUE_PEEK( pxQueue ); + vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); + prvUnlockQueue( pxQueue ); + + if( xTaskResumeAll() == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* There is data in the queue now, so don't enter the blocked + * state, instead return to try and obtain the data. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + } + } + else + { + /* The timeout has expired. If there is still no data in the queue + * exit, otherwise go back and try to read the data again. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceQUEUE_PEEK_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } /*lint -restore */ +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueueReceiveFromISR( QueueHandle_t xQueue, + void * const pvBuffer, + BaseType_t * const pxHigherPriorityTaskWoken ) +{ + BaseType_t xReturn; + UBaseType_t uxSavedInterruptStatus; + Queue_t * const pxQueue = xQueue; + + configASSERT( pxQueue ); + configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); + + /* RTOS ports that support interrupt nesting have the concept of a maximum + * system call (or maximum API call) interrupt priority. Interrupts that are + * above the maximum system call priority are kept permanently enabled, even + * when the RTOS kernel is in a critical section, but cannot make any calls to + * FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h + * then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + * failure if a FreeRTOS API function is called from an interrupt that has been + * assigned a priority above the configured maximum system call priority. + * Only FreeRTOS functions that end in FromISR can be called from interrupts + * that have been assigned a priority at or (logically) below the maximum + * system call interrupt priority. FreeRTOS maintains a separate interrupt + * safe API to ensure interrupt entry is as fast and as simple as possible. + * More information (albeit Cortex-M specific) is provided on the following + * link: https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; + + /* Cannot block in an ISR, so check there is data available. */ + if( uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + const int8_t cRxLock = pxQueue->cRxLock; + + traceQUEUE_RECEIVE_FROM_ISR( pxQueue ); + + prvCopyDataFromQueue( pxQueue, pvBuffer ); + pxQueue->uxMessagesWaiting = uxMessagesWaiting - ( UBaseType_t ) 1; + + /* If the queue is locked the event list will not be modified. + * Instead update the lock count so the task that unlocks the queue + * will know that an ISR has removed data while the queue was + * locked. */ + if( cRxLock == queueUNLOCKED ) + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + /* The task waiting has a higher priority than us so + * force a context switch. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* Increment the lock count so the task that unlocks the queue + * knows that data was removed while it was locked. */ + configASSERT( cRxLock != queueINT8_MAX ); + + pxQueue->cRxLock = ( int8_t ) ( cRxLock + 1 ); + } + + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue ); + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueuePeekFromISR( QueueHandle_t xQueue, + void * const pvBuffer ) +{ + BaseType_t xReturn; + UBaseType_t uxSavedInterruptStatus; + int8_t * pcOriginalReadPosition; + Queue_t * const pxQueue = xQueue; + + configASSERT( pxQueue ); + configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); + configASSERT( pxQueue->uxItemSize != 0 ); /* Can't peek a semaphore. */ + + /* RTOS ports that support interrupt nesting have the concept of a maximum + * system call (or maximum API call) interrupt priority. Interrupts that are + * above the maximum system call priority are kept permanently enabled, even + * when the RTOS kernel is in a critical section, but cannot make any calls to + * FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h + * then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + * failure if a FreeRTOS API function is called from an interrupt that has been + * assigned a priority above the configured maximum system call priority. + * Only FreeRTOS functions that end in FromISR can be called from interrupts + * that have been assigned a priority at or (logically) below the maximum + * system call interrupt priority. FreeRTOS maintains a separate interrupt + * safe API to ensure interrupt entry is as fast and as simple as possible. + * More information (albeit Cortex-M specific) is provided on the following + * link: https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + /* Cannot block in an ISR, so check there is data available. */ + if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + traceQUEUE_PEEK_FROM_ISR( pxQueue ); + + /* Remember the read position so it can be reset as nothing is + * actually being removed from the queue. */ + pcOriginalReadPosition = pxQueue->u.xQueue.pcReadFrom; + prvCopyDataFromQueue( pxQueue, pvBuffer ); + pxQueue->u.xQueue.pcReadFrom = pcOriginalReadPosition; + + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue ); + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +UBaseType_t uxQueueMessagesWaiting( const QueueHandle_t xQueue ) +{ + UBaseType_t uxReturn; + + configASSERT( xQueue ); + + taskENTER_CRITICAL(); + { + uxReturn = ( ( Queue_t * ) xQueue )->uxMessagesWaiting; + } + taskEXIT_CRITICAL(); + + return uxReturn; +} /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */ +/*-----------------------------------------------------------*/ + +UBaseType_t uxQueueSpacesAvailable( const QueueHandle_t xQueue ) +{ + UBaseType_t uxReturn; + Queue_t * const pxQueue = xQueue; + + configASSERT( pxQueue ); + + taskENTER_CRITICAL(); + { + uxReturn = pxQueue->uxLength - pxQueue->uxMessagesWaiting; + } + taskEXIT_CRITICAL(); + + return uxReturn; +} /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */ +/*-----------------------------------------------------------*/ + +UBaseType_t uxQueueMessagesWaitingFromISR( const QueueHandle_t xQueue ) +{ + UBaseType_t uxReturn; + Queue_t * const pxQueue = xQueue; + + configASSERT( pxQueue ); + uxReturn = pxQueue->uxMessagesWaiting; + + return uxReturn; +} /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */ +/*-----------------------------------------------------------*/ + +void vQueueDelete( QueueHandle_t xQueue ) +{ + Queue_t * const pxQueue = xQueue; + + configASSERT( pxQueue ); + traceQUEUE_DELETE( pxQueue ); + + #if ( configQUEUE_REGISTRY_SIZE > 0 ) + { + vQueueUnregisterQueue( pxQueue ); + } + #endif + + #if ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) ) + { + /* The queue can only have been allocated dynamically - free it + * again. */ + vPortFree( pxQueue ); + } + #elif ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + { + /* The queue could have been allocated statically or dynamically, so + * check before attempting to free the memory. */ + if( pxQueue->ucStaticallyAllocated == ( uint8_t ) pdFALSE ) + { + vPortFree( pxQueue ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #else /* if ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) ) */ + { + /* The queue must have been statically allocated, so is not going to be + * deleted. Avoid compiler warnings about the unused parameter. */ + ( void ) pxQueue; + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ +} +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + UBaseType_t uxQueueGetQueueNumber( QueueHandle_t xQueue ) + { + return ( ( Queue_t * ) xQueue )->uxQueueNumber; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + void vQueueSetQueueNumber( QueueHandle_t xQueue, + UBaseType_t uxQueueNumber ) + { + ( ( Queue_t * ) xQueue )->uxQueueNumber = uxQueueNumber; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + uint8_t ucQueueGetQueueType( QueueHandle_t xQueue ) + { + return ( ( Queue_t * ) xQueue )->ucQueueType; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_MUTEXES == 1 ) + + static UBaseType_t prvGetDisinheritPriorityAfterTimeout( const Queue_t * const pxQueue ) + { + UBaseType_t uxHighestPriorityOfWaitingTasks; + + /* If a task waiting for a mutex causes the mutex holder to inherit a + * priority, but the waiting task times out, then the holder should + * disinherit the priority - but only down to the highest priority of any + * other tasks that are waiting for the same mutex. For this purpose, + * return the priority of the highest priority task that is waiting for the + * mutex. */ + if( listCURRENT_LIST_LENGTH( &( pxQueue->xTasksWaitingToReceive ) ) > 0U ) + { + uxHighestPriorityOfWaitingTasks = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) listGET_ITEM_VALUE_OF_HEAD_ENTRY( &( pxQueue->xTasksWaitingToReceive ) ); + } + else + { + uxHighestPriorityOfWaitingTasks = tskIDLE_PRIORITY; + } + + return uxHighestPriorityOfWaitingTasks; + } + +#endif /* configUSE_MUTEXES */ +/*-----------------------------------------------------------*/ + +static BaseType_t prvCopyDataToQueue( Queue_t * const pxQueue, + const void * pvItemToQueue, + const BaseType_t xPosition ) +{ + BaseType_t xReturn = pdFALSE; + UBaseType_t uxMessagesWaiting; + + /* This function is called from a critical section. */ + + uxMessagesWaiting = pxQueue->uxMessagesWaiting; + + if( pxQueue->uxItemSize == ( UBaseType_t ) 0 ) + { + #if ( configUSE_MUTEXES == 1 ) + { + if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) + { + /* The mutex is no longer being held. */ + xReturn = xTaskPriorityDisinherit( pxQueue->u.xSemaphore.xMutexHolder ); + pxQueue->u.xSemaphore.xMutexHolder = NULL; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_MUTEXES */ + } + else if( xPosition == queueSEND_TO_BACK ) + { + ( void ) memcpy( ( void * ) pxQueue->pcWriteTo, pvItemToQueue, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e418 !e9087 MISRA exception as the casts are only redundant for some ports, plus previous logic ensures a null pointer can only be passed to memcpy() if the copy size is 0. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. */ + pxQueue->pcWriteTo += pxQueue->uxItemSize; /*lint !e9016 Pointer arithmetic on char types ok, especially in this use case where it is the clearest way of conveying intent. */ + + if( pxQueue->pcWriteTo >= pxQueue->u.xQueue.pcTail ) /*lint !e946 MISRA exception justified as comparison of pointers is the cleanest solution. */ + { + pxQueue->pcWriteTo = pxQueue->pcHead; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + ( void ) memcpy( ( void * ) pxQueue->u.xQueue.pcReadFrom, pvItemToQueue, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e9087 !e418 MISRA exception as the casts are only redundant for some ports. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. Assert checks null pointer only used when length is 0. */ + pxQueue->u.xQueue.pcReadFrom -= pxQueue->uxItemSize; + + if( pxQueue->u.xQueue.pcReadFrom < pxQueue->pcHead ) /*lint !e946 MISRA exception justified as comparison of pointers is the cleanest solution. */ + { + pxQueue->u.xQueue.pcReadFrom = ( pxQueue->u.xQueue.pcTail - pxQueue->uxItemSize ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + if( xPosition == queueOVERWRITE ) + { + if( uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* An item is not being added but overwritten, so subtract + * one from the recorded number of items in the queue so when + * one is added again below the number of recorded items remains + * correct. */ + --uxMessagesWaiting; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + pxQueue->uxMessagesWaiting = uxMessagesWaiting + ( UBaseType_t ) 1; + + return xReturn; +} +/*-----------------------------------------------------------*/ + +static void prvCopyDataFromQueue( Queue_t * const pxQueue, + void * const pvBuffer ) +{ + if( pxQueue->uxItemSize != ( UBaseType_t ) 0 ) + { + pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; /*lint !e9016 Pointer arithmetic on char types ok, especially in this use case where it is the clearest way of conveying intent. */ + + if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) /*lint !e946 MISRA exception justified as use of the relational operator is the cleanest solutions. */ + { + pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + ( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e418 !e9087 MISRA exception as the casts are only redundant for some ports. Also previous logic ensures a null pointer can only be passed to memcpy() when the count is 0. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. */ + } +} +/*-----------------------------------------------------------*/ + +static void prvUnlockQueue( Queue_t * const pxQueue ) +{ + /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. */ + + /* The lock counts contains the number of extra data items placed or + * removed from the queue while the queue was locked. When a queue is + * locked items can be added or removed, but the event lists cannot be + * updated. */ + taskENTER_CRITICAL(); + { + int8_t cTxLock = pxQueue->cTxLock; + + /* See if data was added to the queue while it was locked. */ + while( cTxLock > queueLOCKED_UNMODIFIED ) + { + /* Data was posted while the queue was locked. Are any tasks + * blocked waiting for data to become available? */ + #if ( configUSE_QUEUE_SETS == 1 ) + { + if( pxQueue->pxQueueSetContainer != NULL ) + { + if( prvNotifyQueueSetContainer( pxQueue ) != pdFALSE ) + { + /* The queue is a member of a queue set, and posting to + * the queue set caused a higher priority task to unblock. + * A context switch is required. */ + vTaskMissedYield(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* Tasks that are removed from the event list will get + * added to the pending ready list as the scheduler is still + * suspended. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so record that a + * context switch is required. */ + vTaskMissedYield(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + break; + } + } + } + #else /* configUSE_QUEUE_SETS */ + { + /* Tasks that are removed from the event list will get added to + * the pending ready list as the scheduler is still suspended. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so record that + * a context switch is required. */ + vTaskMissedYield(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + break; + } + } + #endif /* configUSE_QUEUE_SETS */ + + --cTxLock; + } + + pxQueue->cTxLock = queueUNLOCKED; + } + taskEXIT_CRITICAL(); + + /* Do the same for the Rx lock. */ + taskENTER_CRITICAL(); + { + int8_t cRxLock = pxQueue->cRxLock; + + while( cRxLock > queueLOCKED_UNMODIFIED ) + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + vTaskMissedYield(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + --cRxLock; + } + else + { + break; + } + } + + pxQueue->cRxLock = queueUNLOCKED; + } + taskEXIT_CRITICAL(); +} +/*-----------------------------------------------------------*/ + +static BaseType_t prvIsQueueEmpty( const Queue_t * pxQueue ) +{ + BaseType_t xReturn; + + taskENTER_CRITICAL(); + { + if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + taskEXIT_CRITICAL(); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueueIsQueueEmptyFromISR( const QueueHandle_t xQueue ) +{ + BaseType_t xReturn; + Queue_t * const pxQueue = xQueue; + + configASSERT( pxQueue ); + + if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + + return xReturn; +} /*lint !e818 xQueue could not be pointer to const because it is a typedef. */ +/*-----------------------------------------------------------*/ + +static BaseType_t prvIsQueueFull( const Queue_t * pxQueue ) +{ + BaseType_t xReturn; + + taskENTER_CRITICAL(); + { + if( pxQueue->uxMessagesWaiting == pxQueue->uxLength ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + taskEXIT_CRITICAL(); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueueIsQueueFullFromISR( const QueueHandle_t xQueue ) +{ + BaseType_t xReturn; + Queue_t * const pxQueue = xQueue; + + configASSERT( pxQueue ); + + if( pxQueue->uxMessagesWaiting == pxQueue->uxLength ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + + return xReturn; +} /*lint !e818 xQueue could not be pointer to const because it is a typedef. */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_CO_ROUTINES == 1 ) + + BaseType_t xQueueCRSend( QueueHandle_t xQueue, + const void * pvItemToQueue, + TickType_t xTicksToWait ) + { + BaseType_t xReturn; + Queue_t * const pxQueue = xQueue; + + /* If the queue is already full we may have to block. A critical section + * is required to prevent an interrupt removing something from the queue + * between the check to see if the queue is full and blocking on the queue. */ + portDISABLE_INTERRUPTS(); + { + if( prvIsQueueFull( pxQueue ) != pdFALSE ) + { + /* The queue is full - do we want to block or just leave without + * posting? */ + if( xTicksToWait > ( TickType_t ) 0 ) + { + /* As this is called from a coroutine we cannot block directly, but + * return indicating that we need to block. */ + vCoRoutineAddToDelayedList( xTicksToWait, &( pxQueue->xTasksWaitingToSend ) ); + portENABLE_INTERRUPTS(); + return errQUEUE_BLOCKED; + } + else + { + portENABLE_INTERRUPTS(); + return errQUEUE_FULL; + } + } + } + portENABLE_INTERRUPTS(); + + portDISABLE_INTERRUPTS(); + { + if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) + { + /* There is room in the queue, copy the data into the queue. */ + prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK ); + xReturn = pdPASS; + + /* Were any co-routines waiting for data to become available? */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + /* In this instance the co-routine could be placed directly + * into the ready list as we are within a critical section. + * Instead the same pending ready list mechanism is used as if + * the event were caused from within an interrupt. */ + if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The co-routine waiting has a higher priority so record + * that a yield might be appropriate. */ + xReturn = errQUEUE_YIELD; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + xReturn = errQUEUE_FULL; + } + } + portENABLE_INTERRUPTS(); + + return xReturn; + } + +#endif /* configUSE_CO_ROUTINES */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_CO_ROUTINES == 1 ) + + BaseType_t xQueueCRReceive( QueueHandle_t xQueue, + void * pvBuffer, + TickType_t xTicksToWait ) + { + BaseType_t xReturn; + Queue_t * const pxQueue = xQueue; + + /* If the queue is already empty we may have to block. A critical section + * is required to prevent an interrupt adding something to the queue + * between the check to see if the queue is empty and blocking on the queue. */ + portDISABLE_INTERRUPTS(); + { + if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) + { + /* There are no messages in the queue, do we want to block or just + * leave with nothing? */ + if( xTicksToWait > ( TickType_t ) 0 ) + { + /* As this is a co-routine we cannot block directly, but return + * indicating that we need to block. */ + vCoRoutineAddToDelayedList( xTicksToWait, &( pxQueue->xTasksWaitingToReceive ) ); + portENABLE_INTERRUPTS(); + return errQUEUE_BLOCKED; + } + else + { + portENABLE_INTERRUPTS(); + return errQUEUE_FULL; + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + portENABLE_INTERRUPTS(); + + portDISABLE_INTERRUPTS(); + { + if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* Data is available from the queue. */ + pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; + + if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) + { + pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + --( pxQueue->uxMessagesWaiting ); + ( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( unsigned ) pxQueue->uxItemSize ); + + xReturn = pdPASS; + + /* Were any co-routines waiting for space to become available? */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + /* In this instance the co-routine could be placed directly + * into the ready list as we are within a critical section. + * Instead the same pending ready list mechanism is used as if + * the event were caused from within an interrupt. */ + if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + xReturn = errQUEUE_YIELD; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + xReturn = pdFAIL; + } + } + portENABLE_INTERRUPTS(); + + return xReturn; + } + +#endif /* configUSE_CO_ROUTINES */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_CO_ROUTINES == 1 ) + + BaseType_t xQueueCRSendFromISR( QueueHandle_t xQueue, + const void * pvItemToQueue, + BaseType_t xCoRoutinePreviouslyWoken ) + { + Queue_t * const pxQueue = xQueue; + + /* Cannot block within an ISR so if there is no space on the queue then + * exit without doing anything. */ + if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) + { + prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK ); + + /* We only want to wake one co-routine per ISR, so check that a + * co-routine has not already been woken. */ + if( xCoRoutinePreviouslyWoken == pdFALSE ) + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + return pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xCoRoutinePreviouslyWoken; + } + +#endif /* configUSE_CO_ROUTINES */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_CO_ROUTINES == 1 ) + + BaseType_t xQueueCRReceiveFromISR( QueueHandle_t xQueue, + void * pvBuffer, + BaseType_t * pxCoRoutineWoken ) + { + BaseType_t xReturn; + Queue_t * const pxQueue = xQueue; + + /* We cannot block from an ISR, so check there is data available. If + * not then just leave without doing anything. */ + if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* Copy the data from the queue. */ + pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; + + if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) + { + pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + --( pxQueue->uxMessagesWaiting ); + ( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( unsigned ) pxQueue->uxItemSize ); + + if( ( *pxCoRoutineWoken ) == pdFALSE ) + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + *pxCoRoutineWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + } + + return xReturn; + } + +#endif /* configUSE_CO_ROUTINES */ +/*-----------------------------------------------------------*/ + +#if ( configQUEUE_REGISTRY_SIZE > 0 ) + + void vQueueAddToRegistry( QueueHandle_t xQueue, + const char * pcQueueName ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + { + UBaseType_t ux; + + configASSERT( xQueue ); + + QueueRegistryItem_t * pxEntryToWrite = NULL; + + if( pcQueueName != NULL ) + { + /* See if there is an empty space in the registry. A NULL name denotes + * a free slot. */ + for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ ) + { + /* Replace an existing entry if the queue is already in the registry. */ + if( xQueue == xQueueRegistry[ ux ].xHandle ) + { + pxEntryToWrite = &( xQueueRegistry[ ux ] ); + break; + } + /* Otherwise, store in the next empty location */ + else if( ( pxEntryToWrite == NULL ) && ( xQueueRegistry[ ux ].pcQueueName == NULL ) ) + { + pxEntryToWrite = &( xQueueRegistry[ ux ] ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + + if( pxEntryToWrite != NULL ) + { + /* Store the information on this queue. */ + pxEntryToWrite->pcQueueName = pcQueueName; + pxEntryToWrite->xHandle = xQueue; + + traceQUEUE_REGISTRY_ADD( xQueue, pcQueueName ); + } + } + +#endif /* configQUEUE_REGISTRY_SIZE */ +/*-----------------------------------------------------------*/ + +#if ( configQUEUE_REGISTRY_SIZE > 0 ) + + const char * pcQueueGetName( QueueHandle_t xQueue ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + { + UBaseType_t ux; + const char * pcReturn = NULL; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + + configASSERT( xQueue ); + + /* Note there is nothing here to protect against another task adding or + * removing entries from the registry while it is being searched. */ + + for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ ) + { + if( xQueueRegistry[ ux ].xHandle == xQueue ) + { + pcReturn = xQueueRegistry[ ux ].pcQueueName; + break; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + return pcReturn; + } /*lint !e818 xQueue cannot be a pointer to const because it is a typedef. */ + +#endif /* configQUEUE_REGISTRY_SIZE */ +/*-----------------------------------------------------------*/ + +#if ( configQUEUE_REGISTRY_SIZE > 0 ) + + void vQueueUnregisterQueue( QueueHandle_t xQueue ) + { + UBaseType_t ux; + + configASSERT( xQueue ); + + /* See if the handle of the queue being unregistered in actually in the + * registry. */ + for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ ) + { + if( xQueueRegistry[ ux ].xHandle == xQueue ) + { + /* Set the name to NULL to show that this slot if free again. */ + xQueueRegistry[ ux ].pcQueueName = NULL; + + /* Set the handle to NULL to ensure the same queue handle cannot + * appear in the registry twice if it is added, removed, then + * added again. */ + xQueueRegistry[ ux ].xHandle = ( QueueHandle_t ) 0; + break; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } /*lint !e818 xQueue could not be pointer to const because it is a typedef. */ + +#endif /* configQUEUE_REGISTRY_SIZE */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TIMERS == 1 ) + + void vQueueWaitForMessageRestricted( QueueHandle_t xQueue, + TickType_t xTicksToWait, + const BaseType_t xWaitIndefinitely ) + { + Queue_t * const pxQueue = xQueue; + + /* This function should not be called by application code hence the + * 'Restricted' in its name. It is not part of the public API. It is + * designed for use by kernel code, and has special calling requirements. + * It can result in vListInsert() being called on a list that can only + * possibly ever have one item in it, so the list will be fast, but even + * so it should be called with the scheduler locked and not from a critical + * section. */ + + /* Only do anything if there are no messages in the queue. This function + * will not actually cause the task to block, just place it on a blocked + * list. It will not block until the scheduler is unlocked - at which + * time a yield will be performed. If an item is added to the queue while + * the queue is locked, and the calling task blocks on the queue, then the + * calling task will be immediately unblocked when the queue is unlocked. */ + prvLockQueue( pxQueue ); + + if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0U ) + { + /* There is nothing in the queue, block for the specified period. */ + vTaskPlaceOnEventListRestricted( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait, xWaitIndefinitely ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + prvUnlockQueue( pxQueue ); + } + +#endif /* configUSE_TIMERS */ +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_QUEUE_SETS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + + QueueSetHandle_t xQueueCreateSet( const UBaseType_t uxEventQueueLength ) + { + QueueSetHandle_t pxQueue; + + pxQueue = xQueueGenericCreate( uxEventQueueLength, ( UBaseType_t ) sizeof( Queue_t * ), queueQUEUE_TYPE_SET ); + + return pxQueue; + } + +#endif /* configUSE_QUEUE_SETS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_QUEUE_SETS == 1 ) + + BaseType_t xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, + QueueSetHandle_t xQueueSet ) + { + BaseType_t xReturn; + + taskENTER_CRITICAL(); + { + if( ( ( Queue_t * ) xQueueOrSemaphore )->pxQueueSetContainer != NULL ) + { + /* Cannot add a queue/semaphore to more than one queue set. */ + xReturn = pdFAIL; + } + else if( ( ( Queue_t * ) xQueueOrSemaphore )->uxMessagesWaiting != ( UBaseType_t ) 0 ) + { + /* Cannot add a queue/semaphore to a queue set if there are already + * items in the queue/semaphore. */ + xReturn = pdFAIL; + } + else + { + ( ( Queue_t * ) xQueueOrSemaphore )->pxQueueSetContainer = xQueueSet; + xReturn = pdPASS; + } + } + taskEXIT_CRITICAL(); + + return xReturn; + } + +#endif /* configUSE_QUEUE_SETS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_QUEUE_SETS == 1 ) + + BaseType_t xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, + QueueSetHandle_t xQueueSet ) + { + BaseType_t xReturn; + Queue_t * const pxQueueOrSemaphore = ( Queue_t * ) xQueueOrSemaphore; + + if( pxQueueOrSemaphore->pxQueueSetContainer != xQueueSet ) + { + /* The queue was not a member of the set. */ + xReturn = pdFAIL; + } + else if( pxQueueOrSemaphore->uxMessagesWaiting != ( UBaseType_t ) 0 ) + { + /* It is dangerous to remove a queue from a set when the queue is + * not empty because the queue set will still hold pending events for + * the queue. */ + xReturn = pdFAIL; + } + else + { + taskENTER_CRITICAL(); + { + /* The queue is no longer contained in the set. */ + pxQueueOrSemaphore->pxQueueSetContainer = NULL; + } + taskEXIT_CRITICAL(); + xReturn = pdPASS; + } + + return xReturn; + } /*lint !e818 xQueueSet could not be declared as pointing to const as it is a typedef. */ + +#endif /* configUSE_QUEUE_SETS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_QUEUE_SETS == 1 ) + + QueueSetMemberHandle_t xQueueSelectFromSet( QueueSetHandle_t xQueueSet, + TickType_t const xTicksToWait ) + { + QueueSetMemberHandle_t xReturn = NULL; + + ( void ) xQueueReceive( ( QueueHandle_t ) xQueueSet, &xReturn, xTicksToWait ); /*lint !e961 Casting from one typedef to another is not redundant. */ + return xReturn; + } + +#endif /* configUSE_QUEUE_SETS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_QUEUE_SETS == 1 ) + + QueueSetMemberHandle_t xQueueSelectFromSetFromISR( QueueSetHandle_t xQueueSet ) + { + QueueSetMemberHandle_t xReturn = NULL; + + ( void ) xQueueReceiveFromISR( ( QueueHandle_t ) xQueueSet, &xReturn, NULL ); /*lint !e961 Casting from one typedef to another is not redundant. */ + return xReturn; + } + +#endif /* configUSE_QUEUE_SETS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_QUEUE_SETS == 1 ) + + static BaseType_t prvNotifyQueueSetContainer( const Queue_t * const pxQueue ) + { + Queue_t * pxQueueSetContainer = pxQueue->pxQueueSetContainer; + BaseType_t xReturn = pdFALSE; + + /* This function must be called form a critical section. */ + + /* The following line is not reachable in unit tests because every call + * to prvNotifyQueueSetContainer is preceded by a check that + * pxQueueSetContainer != NULL */ + configASSERT( pxQueueSetContainer ); /* LCOV_EXCL_BR_LINE */ + configASSERT( pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength ); + + if( pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength ) + { + const int8_t cTxLock = pxQueueSetContainer->cTxLock; + + traceQUEUE_SET_SEND( pxQueueSetContainer ); + + /* The data copied is the handle of the queue that contains data. */ + xReturn = prvCopyDataToQueue( pxQueueSetContainer, &pxQueue, queueSEND_TO_BACK ); + + if( cTxLock == queueUNLOCKED ) + { + if( listLIST_IS_EMPTY( &( pxQueueSetContainer->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueueSetContainer->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority. */ + xReturn = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + configASSERT( cTxLock != queueINT8_MAX ); + + pxQueueSetContainer->cTxLock = ( int8_t ) ( cTxLock + 1 ); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xReturn; + } + +#endif /* configUSE_QUEUE_SETS */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/stream_buffer.c b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/stream_buffer.c new file mode 100644 index 0000000..cf6300f --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/stream_buffer.c @@ -0,0 +1,1307 @@ +/* + * FreeRTOS Kernel V10.4.6 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* Standard includes. */ +#include +#include + +/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining + * all the API functions to use the MPU wrappers. That should only be done when + * task.h is included from an application file. */ +#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "stream_buffer.h" + +#if ( configUSE_TASK_NOTIFICATIONS != 1 ) + #error configUSE_TASK_NOTIFICATIONS must be set to 1 to build stream_buffer.c +#endif + +/* Lint e961, e9021 and e750 are suppressed as a MISRA exception justified + * because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined + * for the header files above, but not in this file, in order to generate the + * correct privileged Vs unprivileged linkage and placement. */ +#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750 !e9021. */ + +/* If the user has not provided application specific Rx notification macros, + * or #defined the notification macros away, then provide default implementations + * that uses task notifications. */ +/*lint -save -e9026 Function like macros allowed and needed here so they can be overridden. */ +#ifndef sbRECEIVE_COMPLETED + #define sbRECEIVE_COMPLETED( pxStreamBuffer ) \ + vTaskSuspendAll(); \ + { \ + if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) \ + { \ + ( void ) xTaskNotify( ( pxStreamBuffer )->xTaskWaitingToSend, \ + ( uint32_t ) 0, \ + eNoAction ); \ + ( pxStreamBuffer )->xTaskWaitingToSend = NULL; \ + } \ + } \ + ( void ) xTaskResumeAll(); +#endif /* sbRECEIVE_COMPLETED */ + +#ifndef sbRECEIVE_COMPLETED_FROM_ISR + #define sbRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, \ + pxHigherPriorityTaskWoken ) \ + { \ + UBaseType_t uxSavedInterruptStatus; \ + \ + uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); \ + { \ + if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) \ + { \ + ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToSend, \ + ( uint32_t ) 0, \ + eNoAction, \ + pxHigherPriorityTaskWoken ); \ + ( pxStreamBuffer )->xTaskWaitingToSend = NULL; \ + } \ + } \ + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); \ + } +#endif /* sbRECEIVE_COMPLETED_FROM_ISR */ + +/* If the user has not provided an application specific Tx notification macro, + * or #defined the notification macro away, them provide a default implementation + * that uses task notifications. */ +#ifndef sbSEND_COMPLETED + #define sbSEND_COMPLETED( pxStreamBuffer ) \ + vTaskSuspendAll(); \ + { \ + if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) \ + { \ + ( void ) xTaskNotify( ( pxStreamBuffer )->xTaskWaitingToReceive, \ + ( uint32_t ) 0, \ + eNoAction ); \ + ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; \ + } \ + } \ + ( void ) xTaskResumeAll(); +#endif /* sbSEND_COMPLETED */ + +#ifndef sbSEND_COMPLETE_FROM_ISR + #define sbSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ) \ + { \ + UBaseType_t uxSavedInterruptStatus; \ + \ + uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); \ + { \ + if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) \ + { \ + ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToReceive, \ + ( uint32_t ) 0, \ + eNoAction, \ + pxHigherPriorityTaskWoken ); \ + ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; \ + } \ + } \ + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); \ + } +#endif /* sbSEND_COMPLETE_FROM_ISR */ +/*lint -restore (9026) */ + +/* The number of bytes used to hold the length of a message in the buffer. */ +#define sbBYTES_TO_STORE_MESSAGE_LENGTH ( sizeof( configMESSAGE_BUFFER_LENGTH_TYPE ) ) + +/* Bits stored in the ucFlags field of the stream buffer. */ +#define sbFLAGS_IS_MESSAGE_BUFFER ( ( uint8_t ) 1 ) /* Set if the stream buffer was created as a message buffer, in which case it holds discrete messages rather than a stream. */ +#define sbFLAGS_IS_STATICALLY_ALLOCATED ( ( uint8_t ) 2 ) /* Set if the stream buffer was created using statically allocated memory. */ + +/*-----------------------------------------------------------*/ + +/* Structure that hold state information on the buffer. */ +typedef struct StreamBufferDef_t /*lint !e9058 Style convention uses tag. */ +{ + volatile size_t xTail; /* Index to the next item to read within the buffer. */ + volatile size_t xHead; /* Index to the next item to write within the buffer. */ + size_t xLength; /* The length of the buffer pointed to by pucBuffer. */ + size_t xTriggerLevelBytes; /* The number of bytes that must be in the stream buffer before a task that is waiting for data is unblocked. */ + volatile TaskHandle_t xTaskWaitingToReceive; /* Holds the handle of a task waiting for data, or NULL if no tasks are waiting. */ + volatile TaskHandle_t xTaskWaitingToSend; /* Holds the handle of a task waiting to send data to a message buffer that is full. */ + uint8_t * pucBuffer; /* Points to the buffer itself - that is - the RAM that stores the data passed through the buffer. */ + uint8_t ucFlags; + + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxStreamBufferNumber; /* Used for tracing purposes. */ + #endif +} StreamBuffer_t; + +/* + * The number of bytes available to be read from the buffer. + */ +static size_t prvBytesInBuffer( const StreamBuffer_t * const pxStreamBuffer ) PRIVILEGED_FUNCTION; + +/* + * Add xCount bytes from pucData into the pxStreamBuffer's data storage area. + * This function does not update the buffer's xHead pointer, so multiple writes + * may be chained together "atomically". This is useful for Message Buffers where + * the length and data bytes are written in two separate chunks, and we don't want + * the reader to see the buffer as having grown until after all data is copied over. + * This function takes a custom xHead value to indicate where to write to (necessary + * for chaining) and returns the the resulting xHead position. + * To mark the write as complete, manually set the buffer's xHead field with the + * returned xHead from this function. + */ +static size_t prvWriteBytesToBuffer( StreamBuffer_t * const pxStreamBuffer, + const uint8_t * pucData, + size_t xCount, + size_t xHead ) PRIVILEGED_FUNCTION; + +/* + * If the stream buffer is being used as a message buffer, then reads an entire + * message out of the buffer. If the stream buffer is being used as a stream + * buffer then read as many bytes as possible from the buffer. + * prvReadBytesFromBuffer() is called to actually extract the bytes from the + * buffer's data storage area. + */ +static size_t prvReadMessageFromBuffer( StreamBuffer_t * pxStreamBuffer, + void * pvRxData, + size_t xBufferLengthBytes, + size_t xBytesAvailable ) PRIVILEGED_FUNCTION; + +/* + * If the stream buffer is being used as a message buffer, then writes an entire + * message to the buffer. If the stream buffer is being used as a stream + * buffer then write as many bytes as possible to the buffer. + * prvWriteBytestoBuffer() is called to actually send the bytes to the buffer's + * data storage area. + */ +static size_t prvWriteMessageToBuffer( StreamBuffer_t * const pxStreamBuffer, + const void * pvTxData, + size_t xDataLengthBytes, + size_t xSpace, + size_t xRequiredSpace ) PRIVILEGED_FUNCTION; + +/* + * Copies xCount bytes from the pxStreamBuffer's data storage area to pucData. + * This function does not update the buffer's xTail pointer, so multiple reads + * may be chained together "atomically". This is useful for Message Buffers where + * the length and data bytes are read in two separate chunks, and we don't want + * the writer to see the buffer as having more free space until after all data is + * copied over, especially if we have to abort the read due to insufficient receiving space. + * This function takes a custom xTail value to indicate where to read from (necessary + * for chaining) and returns the the resulting xTail position. + * To mark the read as complete, manually set the buffer's xTail field with the + * returned xTail from this function. + */ +static size_t prvReadBytesFromBuffer( StreamBuffer_t * pxStreamBuffer, + uint8_t * pucData, + size_t xCount, + size_t xTail ) PRIVILEGED_FUNCTION; + +/* + * Called by both pxStreamBufferCreate() and pxStreamBufferCreateStatic() to + * initialise the members of the newly created stream buffer structure. + */ +static void prvInitialiseNewStreamBuffer( StreamBuffer_t * const pxStreamBuffer, + uint8_t * const pucBuffer, + size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + uint8_t ucFlags ) PRIVILEGED_FUNCTION; + +/*-----------------------------------------------------------*/ + +#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + + StreamBufferHandle_t xStreamBufferGenericCreate( size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + BaseType_t xIsMessageBuffer ) + { + uint8_t * pucAllocatedMemory; + uint8_t ucFlags; + + /* In case the stream buffer is going to be used as a message buffer + * (that is, it will hold discrete messages with a little meta data that + * says how big the next message is) check the buffer will be large enough + * to hold at least one message. */ + if( xIsMessageBuffer == pdTRUE ) + { + /* Is a message buffer but not statically allocated. */ + ucFlags = sbFLAGS_IS_MESSAGE_BUFFER; + configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH ); + } + else + { + /* Not a message buffer and not statically allocated. */ + ucFlags = 0; + configASSERT( xBufferSizeBytes > 0 ); + } + + configASSERT( xTriggerLevelBytes <= xBufferSizeBytes ); + + /* A trigger level of 0 would cause a waiting task to unblock even when + * the buffer was empty. */ + if( xTriggerLevelBytes == ( size_t ) 0 ) + { + xTriggerLevelBytes = ( size_t ) 1; + } + + /* A stream buffer requires a StreamBuffer_t structure and a buffer. + * Both are allocated in a single call to pvPortMalloc(). The + * StreamBuffer_t structure is placed at the start of the allocated memory + * and the buffer follows immediately after. The requested size is + * incremented so the free space is returned as the user would expect - + * this is a quirk of the implementation that means otherwise the free + * space would be reported as one byte smaller than would be logically + * expected. */ + if( xBufferSizeBytes < ( xBufferSizeBytes + 1 + sizeof( StreamBuffer_t ) ) ) + { + xBufferSizeBytes++; + pucAllocatedMemory = ( uint8_t * ) pvPortMalloc( xBufferSizeBytes + sizeof( StreamBuffer_t ) ); /*lint !e9079 malloc() only returns void*. */ + } + else + { + pucAllocatedMemory = NULL; + } + + if( pucAllocatedMemory != NULL ) + { + prvInitialiseNewStreamBuffer( ( StreamBuffer_t * ) pucAllocatedMemory, /* Structure at the start of the allocated memory. */ /*lint !e9087 Safe cast as allocated memory is aligned. */ /*lint !e826 Area is not too small and alignment is guaranteed provided malloc() behaves as expected and returns aligned buffer. */ + pucAllocatedMemory + sizeof( StreamBuffer_t ), /* Storage area follows. */ /*lint !e9016 Indexing past structure valid for uint8_t pointer, also storage area has no alignment requirement. */ + xBufferSizeBytes, + xTriggerLevelBytes, + ucFlags ); + + traceSTREAM_BUFFER_CREATE( ( ( StreamBuffer_t * ) pucAllocatedMemory ), xIsMessageBuffer ); + } + else + { + traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer ); + } + + return ( StreamBufferHandle_t ) pucAllocatedMemory; /*lint !e9087 !e826 Safe cast as allocated memory is aligned. */ + } + +#endif /* configSUPPORT_DYNAMIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + + StreamBufferHandle_t xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + BaseType_t xIsMessageBuffer, + uint8_t * const pucStreamBufferStorageArea, + StaticStreamBuffer_t * const pxStaticStreamBuffer ) + { + StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) pxStaticStreamBuffer; /*lint !e740 !e9087 Safe cast as StaticStreamBuffer_t is opaque Streambuffer_t. */ + StreamBufferHandle_t xReturn; + uint8_t ucFlags; + + configASSERT( pucStreamBufferStorageArea ); + configASSERT( pxStaticStreamBuffer ); + configASSERT( xTriggerLevelBytes <= xBufferSizeBytes ); + + /* A trigger level of 0 would cause a waiting task to unblock even when + * the buffer was empty. */ + if( xTriggerLevelBytes == ( size_t ) 0 ) + { + xTriggerLevelBytes = ( size_t ) 1; + } + + if( xIsMessageBuffer != pdFALSE ) + { + /* Statically allocated message buffer. */ + ucFlags = sbFLAGS_IS_MESSAGE_BUFFER | sbFLAGS_IS_STATICALLY_ALLOCATED; + } + else + { + /* Statically allocated stream buffer. */ + ucFlags = sbFLAGS_IS_STATICALLY_ALLOCATED; + } + + /* In case the stream buffer is going to be used as a message buffer + * (that is, it will hold discrete messages with a little meta data that + * says how big the next message is) check the buffer will be large enough + * to hold at least one message. */ + configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH ); + + #if ( configASSERT_DEFINED == 1 ) + { + /* Sanity check that the size of the structure used to declare a + * variable of type StaticStreamBuffer_t equals the size of the real + * message buffer structure. */ + volatile size_t xSize = sizeof( StaticStreamBuffer_t ); + configASSERT( xSize == sizeof( StreamBuffer_t ) ); + } /*lint !e529 xSize is referenced is configASSERT() is defined. */ + #endif /* configASSERT_DEFINED */ + + if( ( pucStreamBufferStorageArea != NULL ) && ( pxStaticStreamBuffer != NULL ) ) + { + prvInitialiseNewStreamBuffer( pxStreamBuffer, + pucStreamBufferStorageArea, + xBufferSizeBytes, + xTriggerLevelBytes, + ucFlags ); + + /* Remember this was statically allocated in case it is ever deleted + * again. */ + pxStreamBuffer->ucFlags |= sbFLAGS_IS_STATICALLY_ALLOCATED; + + traceSTREAM_BUFFER_CREATE( pxStreamBuffer, xIsMessageBuffer ); + + xReturn = ( StreamBufferHandle_t ) pxStaticStreamBuffer; /*lint !e9087 Data hiding requires cast to opaque type. */ + } + else + { + xReturn = NULL; + traceSTREAM_BUFFER_CREATE_STATIC_FAILED( xReturn, xIsMessageBuffer ); + } + + return xReturn; + } + +#endif /* ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ +/*-----------------------------------------------------------*/ + +void vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer ) +{ + StreamBuffer_t * pxStreamBuffer = xStreamBuffer; + + configASSERT( pxStreamBuffer ); + + traceSTREAM_BUFFER_DELETE( xStreamBuffer ); + + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_STATICALLY_ALLOCATED ) == ( uint8_t ) pdFALSE ) + { + #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + { + /* Both the structure and the buffer were allocated using a single call + * to pvPortMalloc(), hence only one call to vPortFree() is required. */ + vPortFree( ( void * ) pxStreamBuffer ); /*lint !e9087 Standard free() semantics require void *, plus pxStreamBuffer was allocated by pvPortMalloc(). */ + } + #else + { + /* Should not be possible to get here, ucFlags must be corrupt. + * Force an assert. */ + configASSERT( xStreamBuffer == ( StreamBufferHandle_t ) ~0 ); + } + #endif + } + else + { + /* The structure and buffer were not allocated dynamically and cannot be + * freed - just scrub the structure so future use will assert. */ + ( void ) memset( pxStreamBuffer, 0x00, sizeof( StreamBuffer_t ) ); + } +} +/*-----------------------------------------------------------*/ + +BaseType_t xStreamBufferReset( StreamBufferHandle_t xStreamBuffer ) +{ + StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + BaseType_t xReturn = pdFAIL; + + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxStreamBufferNumber; + #endif + + configASSERT( pxStreamBuffer ); + + #if ( configUSE_TRACE_FACILITY == 1 ) + { + /* Store the stream buffer number so it can be restored after the + * reset. */ + uxStreamBufferNumber = pxStreamBuffer->uxStreamBufferNumber; + } + #endif + + /* Can only reset a message buffer if there are no tasks blocked on it. */ + taskENTER_CRITICAL(); + { + if( pxStreamBuffer->xTaskWaitingToReceive == NULL ) + { + if( pxStreamBuffer->xTaskWaitingToSend == NULL ) + { + prvInitialiseNewStreamBuffer( pxStreamBuffer, + pxStreamBuffer->pucBuffer, + pxStreamBuffer->xLength, + pxStreamBuffer->xTriggerLevelBytes, + pxStreamBuffer->ucFlags ); + xReturn = pdPASS; + + #if ( configUSE_TRACE_FACILITY == 1 ) + { + pxStreamBuffer->uxStreamBufferNumber = uxStreamBufferNumber; + } + #endif + + traceSTREAM_BUFFER_RESET( xStreamBuffer ); + } + } + } + taskEXIT_CRITICAL(); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, + size_t xTriggerLevel ) +{ + StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + BaseType_t xReturn; + + configASSERT( pxStreamBuffer ); + + /* It is not valid for the trigger level to be 0. */ + if( xTriggerLevel == ( size_t ) 0 ) + { + xTriggerLevel = ( size_t ) 1; + } + + /* The trigger level is the number of bytes that must be in the stream + * buffer before a task that is waiting for data is unblocked. */ + if( xTriggerLevel < pxStreamBuffer->xLength ) + { + pxStreamBuffer->xTriggerLevelBytes = xTriggerLevel; + xReturn = pdPASS; + } + else + { + xReturn = pdFALSE; + } + + return xReturn; +} +/*-----------------------------------------------------------*/ + +size_t xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer ) +{ + const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + size_t xSpace; + size_t xOriginalTail; + + configASSERT( pxStreamBuffer ); + + /* The code below reads xTail and then xHead. This is safe if the stream + * buffer is updated once between the two reads - but not if the stream buffer + * is updated more than once between the two reads - hence the loop. */ + do + { + xOriginalTail = pxStreamBuffer->xTail; + xSpace = pxStreamBuffer->xLength + pxStreamBuffer->xTail; + xSpace -= pxStreamBuffer->xHead; + } while( xOriginalTail != pxStreamBuffer->xTail ); + + xSpace -= ( size_t ) 1; + + if( xSpace >= pxStreamBuffer->xLength ) + { + xSpace -= pxStreamBuffer->xLength; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xSpace; +} +/*-----------------------------------------------------------*/ + +size_t xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer ) +{ + const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + size_t xReturn; + + configASSERT( pxStreamBuffer ); + + xReturn = prvBytesInBuffer( pxStreamBuffer ); + return xReturn; +} +/*-----------------------------------------------------------*/ + +size_t xStreamBufferSend( StreamBufferHandle_t xStreamBuffer, + const void * pvTxData, + size_t xDataLengthBytes, + TickType_t xTicksToWait ) +{ + StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + size_t xReturn, xSpace = 0; + size_t xRequiredSpace = xDataLengthBytes; + TimeOut_t xTimeOut; + size_t xMaxReportedSpace = 0; + + configASSERT( pvTxData ); + configASSERT( pxStreamBuffer ); + + /* The maximum amount of space a stream buffer will ever report is its length + * minus 1. */ + xMaxReportedSpace = pxStreamBuffer->xLength - ( size_t ) 1; + + /* This send function is used to write to both message buffers and stream + * buffers. If this is a message buffer then the space needed must be + * increased by the amount of bytes needed to store the length of the + * message. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xRequiredSpace += sbBYTES_TO_STORE_MESSAGE_LENGTH; + + /* Overflow? */ + configASSERT( xRequiredSpace > xDataLengthBytes ); + + /* If this is a message buffer then it must be possible to write the + * whole message. */ + if( xRequiredSpace > xMaxReportedSpace ) + { + /* The message would not fit even if the entire buffer was empty, + * so don't wait for space. */ + xTicksToWait = ( TickType_t ) 0; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* If this is a stream buffer then it is acceptable to write only part + * of the message to the buffer. Cap the length to the total length of + * the buffer. */ + if( xRequiredSpace > xMaxReportedSpace ) + { + xRequiredSpace = xMaxReportedSpace; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + if( xTicksToWait != ( TickType_t ) 0 ) + { + vTaskSetTimeOutState( &xTimeOut ); + + do + { + /* Wait until the required number of bytes are free in the message + * buffer. */ + taskENTER_CRITICAL(); + { + xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); + + if( xSpace < xRequiredSpace ) + { + /* Clear notification state as going to wait for space. */ + ( void ) xTaskNotifyStateClear( NULL ); + + /* Should only be one writer. */ + configASSERT( pxStreamBuffer->xTaskWaitingToSend == NULL ); + pxStreamBuffer->xTaskWaitingToSend = xTaskGetCurrentTaskHandle(); + } + else + { + taskEXIT_CRITICAL(); + break; + } + } + taskEXIT_CRITICAL(); + + traceBLOCKING_ON_STREAM_BUFFER_SEND( xStreamBuffer ); + ( void ) xTaskNotifyWait( ( uint32_t ) 0, ( uint32_t ) 0, NULL, xTicksToWait ); + pxStreamBuffer->xTaskWaitingToSend = NULL; + } while( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + if( xSpace == ( size_t ) 0 ) + { + xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + xReturn = prvWriteMessageToBuffer( pxStreamBuffer, pvTxData, xDataLengthBytes, xSpace, xRequiredSpace ); + + if( xReturn > ( size_t ) 0 ) + { + traceSTREAM_BUFFER_SEND( xStreamBuffer, xReturn ); + + /* Was a task waiting for the data? */ + if( prvBytesInBuffer( pxStreamBuffer ) >= pxStreamBuffer->xTriggerLevelBytes ) + { + sbSEND_COMPLETED( pxStreamBuffer ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + traceSTREAM_BUFFER_SEND_FAILED( xStreamBuffer ); + } + + return xReturn; +} +/*-----------------------------------------------------------*/ + +size_t xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer, + const void * pvTxData, + size_t xDataLengthBytes, + BaseType_t * const pxHigherPriorityTaskWoken ) +{ + StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + size_t xReturn, xSpace; + size_t xRequiredSpace = xDataLengthBytes; + + configASSERT( pvTxData ); + configASSERT( pxStreamBuffer ); + + /* This send function is used to write to both message buffers and stream + * buffers. If this is a message buffer then the space needed must be + * increased by the amount of bytes needed to store the length of the + * message. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xRequiredSpace += sbBYTES_TO_STORE_MESSAGE_LENGTH; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); + xReturn = prvWriteMessageToBuffer( pxStreamBuffer, pvTxData, xDataLengthBytes, xSpace, xRequiredSpace ); + + if( xReturn > ( size_t ) 0 ) + { + /* Was a task waiting for the data? */ + if( prvBytesInBuffer( pxStreamBuffer ) >= pxStreamBuffer->xTriggerLevelBytes ) + { + sbSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceSTREAM_BUFFER_SEND_FROM_ISR( xStreamBuffer, xReturn ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +static size_t prvWriteMessageToBuffer( StreamBuffer_t * const pxStreamBuffer, + const void * pvTxData, + size_t xDataLengthBytes, + size_t xSpace, + size_t xRequiredSpace ) +{ + size_t xNextHead = pxStreamBuffer->xHead; + + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + /* This is a message buffer, as opposed to a stream buffer. */ + + if( xSpace >= xRequiredSpace ) + { + /* There is enough space to write both the message length and the message + * itself into the buffer. Start by writing the length of the data, the data + * itself will be written later in this function. */ + xNextHead = prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) &( xDataLengthBytes ), sbBYTES_TO_STORE_MESSAGE_LENGTH, xNextHead ); + } + else + { + /* Not enough space, so do not write data to the buffer. */ + xDataLengthBytes = 0; + } + } + else + { + /* This is a stream buffer, as opposed to a message buffer, so writing a + * stream of bytes rather than discrete messages. Plan to write as many + * bytes as possible. */ + xDataLengthBytes = configMIN( xDataLengthBytes, xSpace ); + } + + if( xDataLengthBytes != ( size_t ) 0 ) + { + /* Write the data to the buffer. */ + pxStreamBuffer->xHead = prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) pvTxData, xDataLengthBytes, xNextHead ); /*lint !e9079 Storage buffer is implemented as uint8_t for ease of sizing, alignment and access. */ + } + + return xDataLengthBytes; +} +/*-----------------------------------------------------------*/ + +size_t xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer, + void * pvRxData, + size_t xBufferLengthBytes, + TickType_t xTicksToWait ) +{ + StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + size_t xReceivedLength = 0, xBytesAvailable, xBytesToStoreMessageLength; + + configASSERT( pvRxData ); + configASSERT( pxStreamBuffer ); + + /* This receive function is used by both message buffers, which store + * discrete messages, and stream buffers, which store a continuous stream of + * bytes. Discrete messages include an additional + * sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the + * message. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; + } + else + { + xBytesToStoreMessageLength = 0; + } + + if( xTicksToWait != ( TickType_t ) 0 ) + { + /* Checking if there is data and clearing the notification state must be + * performed atomically. */ + taskENTER_CRITICAL(); + { + xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); + + /* If this function was invoked by a message buffer read then + * xBytesToStoreMessageLength holds the number of bytes used to hold + * the length of the next discrete message. If this function was + * invoked by a stream buffer read then xBytesToStoreMessageLength will + * be 0. */ + if( xBytesAvailable <= xBytesToStoreMessageLength ) + { + /* Clear notification state as going to wait for data. */ + ( void ) xTaskNotifyStateClear( NULL ); + + /* Should only be one reader. */ + configASSERT( pxStreamBuffer->xTaskWaitingToReceive == NULL ); + pxStreamBuffer->xTaskWaitingToReceive = xTaskGetCurrentTaskHandle(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + + if( xBytesAvailable <= xBytesToStoreMessageLength ) + { + /* Wait for data to be available. */ + traceBLOCKING_ON_STREAM_BUFFER_RECEIVE( xStreamBuffer ); + ( void ) xTaskNotifyWait( ( uint32_t ) 0, ( uint32_t ) 0, NULL, xTicksToWait ); + pxStreamBuffer->xTaskWaitingToReceive = NULL; + + /* Recheck the data available after blocking. */ + xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); + } + + /* Whether receiving a discrete message (where xBytesToStoreMessageLength + * holds the number of bytes used to store the message length) or a stream of + * bytes (where xBytesToStoreMessageLength is zero), the number of bytes + * available must be greater than xBytesToStoreMessageLength to be able to + * read bytes from the buffer. */ + if( xBytesAvailable > xBytesToStoreMessageLength ) + { + xReceivedLength = prvReadMessageFromBuffer( pxStreamBuffer, pvRxData, xBufferLengthBytes, xBytesAvailable ); + + /* Was a task waiting for space in the buffer? */ + if( xReceivedLength != ( size_t ) 0 ) + { + traceSTREAM_BUFFER_RECEIVE( xStreamBuffer, xReceivedLength ); + sbRECEIVE_COMPLETED( pxStreamBuffer ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + traceSTREAM_BUFFER_RECEIVE_FAILED( xStreamBuffer ); + mtCOVERAGE_TEST_MARKER(); + } + + return xReceivedLength; +} +/*-----------------------------------------------------------*/ + +size_t xStreamBufferNextMessageLengthBytes( StreamBufferHandle_t xStreamBuffer ) +{ + StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + size_t xReturn, xBytesAvailable; + configMESSAGE_BUFFER_LENGTH_TYPE xTempReturn; + + configASSERT( pxStreamBuffer ); + + /* Ensure the stream buffer is being used as a message buffer. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); + + if( xBytesAvailable > sbBYTES_TO_STORE_MESSAGE_LENGTH ) + { + /* The number of bytes available is greater than the number of bytes + * required to hold the length of the next message, so another message + * is available. */ + ( void ) prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) &xTempReturn, sbBYTES_TO_STORE_MESSAGE_LENGTH, pxStreamBuffer->xTail ); + xReturn = ( size_t ) xTempReturn; + } + else + { + /* The minimum amount of bytes in a message buffer is + * ( sbBYTES_TO_STORE_MESSAGE_LENGTH + 1 ), so if xBytesAvailable is + * less than sbBYTES_TO_STORE_MESSAGE_LENGTH the only other valid + * value is 0. */ + configASSERT( xBytesAvailable == 0 ); + xReturn = 0; + } + } + else + { + xReturn = 0; + } + + return xReturn; +} +/*-----------------------------------------------------------*/ + +size_t xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer, + void * pvRxData, + size_t xBufferLengthBytes, + BaseType_t * const pxHigherPriorityTaskWoken ) +{ + StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + size_t xReceivedLength = 0, xBytesAvailable, xBytesToStoreMessageLength; + + configASSERT( pvRxData ); + configASSERT( pxStreamBuffer ); + + /* This receive function is used by both message buffers, which store + * discrete messages, and stream buffers, which store a continuous stream of + * bytes. Discrete messages include an additional + * sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the + * message. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; + } + else + { + xBytesToStoreMessageLength = 0; + } + + xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); + + /* Whether receiving a discrete message (where xBytesToStoreMessageLength + * holds the number of bytes used to store the message length) or a stream of + * bytes (where xBytesToStoreMessageLength is zero), the number of bytes + * available must be greater than xBytesToStoreMessageLength to be able to + * read bytes from the buffer. */ + if( xBytesAvailable > xBytesToStoreMessageLength ) + { + xReceivedLength = prvReadMessageFromBuffer( pxStreamBuffer, pvRxData, xBufferLengthBytes, xBytesAvailable ); + + /* Was a task waiting for space in the buffer? */ + if( xReceivedLength != ( size_t ) 0 ) + { + sbRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceSTREAM_BUFFER_RECEIVE_FROM_ISR( xStreamBuffer, xReceivedLength ); + + return xReceivedLength; +} +/*-----------------------------------------------------------*/ + +static size_t prvReadMessageFromBuffer( StreamBuffer_t * pxStreamBuffer, + void * pvRxData, + size_t xBufferLengthBytes, + size_t xBytesAvailable ) +{ + size_t xCount, xNextMessageLength; + configMESSAGE_BUFFER_LENGTH_TYPE xTempNextMessageLength; + size_t xNextTail = pxStreamBuffer->xTail; + + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + /* A discrete message is being received. First receive the length + * of the message. */ + xNextTail = prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) &xTempNextMessageLength, sbBYTES_TO_STORE_MESSAGE_LENGTH, xNextTail ); + xNextMessageLength = ( size_t ) xTempNextMessageLength; + + /* Reduce the number of bytes available by the number of bytes just + * read out. */ + xBytesAvailable -= sbBYTES_TO_STORE_MESSAGE_LENGTH; + + /* Check there is enough space in the buffer provided by the + * user. */ + if( xNextMessageLength > xBufferLengthBytes ) + { + /* The user has provided insufficient space to read the message. */ + xNextMessageLength = 0; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* A stream of bytes is being received (as opposed to a discrete + * message), so read as many bytes as possible. */ + xNextMessageLength = xBufferLengthBytes; + } + + /* Use the minimum of the wanted bytes and the available bytes. */ + xCount = configMIN( xNextMessageLength, xBytesAvailable ); + + if( xCount != ( size_t ) 0 ) + { + /* Read the actual data and update the tail to mark the data as officially consumed. */ + pxStreamBuffer->xTail = prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) pvRxData, xCount, xNextTail ); /*lint !e9079 Data storage area is implemented as uint8_t array for ease of sizing, indexing and alignment. */ + } + + return xCount; +} +/*-----------------------------------------------------------*/ + +BaseType_t xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer ) +{ + const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + BaseType_t xReturn; + size_t xTail; + + configASSERT( pxStreamBuffer ); + + /* True if no bytes are available. */ + xTail = pxStreamBuffer->xTail; + + if( pxStreamBuffer->xHead == xTail ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer ) +{ + BaseType_t xReturn; + size_t xBytesToStoreMessageLength; + const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + + configASSERT( pxStreamBuffer ); + + /* This generic version of the receive function is used by both message + * buffers, which store discrete messages, and stream buffers, which store a + * continuous stream of bytes. Discrete messages include an additional + * sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the message. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; + } + else + { + xBytesToStoreMessageLength = 0; + } + + /* True if the available space equals zero. */ + if( xStreamBufferSpacesAvailable( xStreamBuffer ) <= xBytesToStoreMessageLength ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xStreamBufferSendCompletedFromISR( StreamBufferHandle_t xStreamBuffer, + BaseType_t * pxHigherPriorityTaskWoken ) +{ + StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + BaseType_t xReturn; + UBaseType_t uxSavedInterruptStatus; + + configASSERT( pxStreamBuffer ); + + uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); + { + if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) + { + ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToReceive, + ( uint32_t ) 0, + eNoAction, + pxHigherPriorityTaskWoken ); + ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xStreamBufferReceiveCompletedFromISR( StreamBufferHandle_t xStreamBuffer, + BaseType_t * pxHigherPriorityTaskWoken ) +{ + StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + BaseType_t xReturn; + UBaseType_t uxSavedInterruptStatus; + + configASSERT( pxStreamBuffer ); + + uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); + { + if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) + { + ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToSend, + ( uint32_t ) 0, + eNoAction, + pxHigherPriorityTaskWoken ); + ( pxStreamBuffer )->xTaskWaitingToSend = NULL; + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +static size_t prvWriteBytesToBuffer( StreamBuffer_t * const pxStreamBuffer, + const uint8_t * pucData, + size_t xCount, + size_t xHead ) +{ + size_t xFirstLength; + + configASSERT( xCount > ( size_t ) 0 ); + + /* Calculate the number of bytes that can be added in the first write - + * which may be less than the total number of bytes that need to be added if + * the buffer will wrap back to the beginning. */ + xFirstLength = configMIN( pxStreamBuffer->xLength - xHead, xCount ); + + /* Write as many bytes as can be written in the first write. */ + configASSERT( ( xHead + xFirstLength ) <= pxStreamBuffer->xLength ); + ( void ) memcpy( ( void * ) ( &( pxStreamBuffer->pucBuffer[ xHead ] ) ), ( const void * ) pucData, xFirstLength ); /*lint !e9087 memcpy() requires void *. */ + + /* If the number of bytes written was less than the number that could be + * written in the first write... */ + if( xCount > xFirstLength ) + { + /* ...then write the remaining bytes to the start of the buffer. */ + configASSERT( ( xCount - xFirstLength ) <= pxStreamBuffer->xLength ); + ( void ) memcpy( ( void * ) pxStreamBuffer->pucBuffer, ( const void * ) &( pucData[ xFirstLength ] ), xCount - xFirstLength ); /*lint !e9087 memcpy() requires void *. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + xHead += xCount; + + if( xHead >= pxStreamBuffer->xLength ) + { + xHead -= pxStreamBuffer->xLength; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xHead; +} +/*-----------------------------------------------------------*/ + +static size_t prvReadBytesFromBuffer( StreamBuffer_t * pxStreamBuffer, + uint8_t * pucData, + size_t xCount, + size_t xTail ) +{ + size_t xFirstLength; + + configASSERT( xCount != ( size_t ) 0 ); + + /* Calculate the number of bytes that can be read - which may be + * less than the number wanted if the data wraps around to the start of + * the buffer. */ + xFirstLength = configMIN( pxStreamBuffer->xLength - xTail, xCount ); + + /* Obtain the number of bytes it is possible to obtain in the first + * read. Asserts check bounds of read and write. */ + configASSERT( xFirstLength <= xCount ); + configASSERT( ( xTail + xFirstLength ) <= pxStreamBuffer->xLength ); + ( void ) memcpy( ( void * ) pucData, ( const void * ) &( pxStreamBuffer->pucBuffer[ xTail ] ), xFirstLength ); /*lint !e9087 memcpy() requires void *. */ + + /* If the total number of wanted bytes is greater than the number + * that could be read in the first read... */ + if( xCount > xFirstLength ) + { + /* ...then read the remaining bytes from the start of the buffer. */ + ( void ) memcpy( ( void * ) &( pucData[ xFirstLength ] ), ( void * ) ( pxStreamBuffer->pucBuffer ), xCount - xFirstLength ); /*lint !e9087 memcpy() requires void *. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Move the tail pointer to effectively remove the data read from the buffer. */ + xTail += xCount; + + if( xTail >= pxStreamBuffer->xLength ) + { + xTail -= pxStreamBuffer->xLength; + } + + return xTail; +} +/*-----------------------------------------------------------*/ + +static size_t prvBytesInBuffer( const StreamBuffer_t * const pxStreamBuffer ) +{ +/* Returns the distance between xTail and xHead. */ + size_t xCount; + + xCount = pxStreamBuffer->xLength + pxStreamBuffer->xHead; + xCount -= pxStreamBuffer->xTail; + + if( xCount >= pxStreamBuffer->xLength ) + { + xCount -= pxStreamBuffer->xLength; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xCount; +} +/*-----------------------------------------------------------*/ + +static void prvInitialiseNewStreamBuffer( StreamBuffer_t * const pxStreamBuffer, + uint8_t * const pucBuffer, + size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + uint8_t ucFlags ) +{ + /* Assert here is deliberately writing to the entire buffer to ensure it can + * be written to without generating exceptions, and is setting the buffer to a + * known value to assist in development/debugging. */ + #if ( configASSERT_DEFINED == 1 ) + { + /* The value written just has to be identifiable when looking at the + * memory. Don't use 0xA5 as that is the stack fill value and could + * result in confusion as to what is actually being observed. */ + const BaseType_t xWriteValue = 0x55; + configASSERT( memset( pucBuffer, ( int ) xWriteValue, xBufferSizeBytes ) == pucBuffer ); + } /*lint !e529 !e438 xWriteValue is only used if configASSERT() is defined. */ + #endif + + ( void ) memset( ( void * ) pxStreamBuffer, 0x00, sizeof( StreamBuffer_t ) ); /*lint !e9087 memset() requires void *. */ + pxStreamBuffer->pucBuffer = pucBuffer; + pxStreamBuffer->xLength = xBufferSizeBytes; + pxStreamBuffer->xTriggerLevelBytes = xTriggerLevelBytes; + pxStreamBuffer->ucFlags = ucFlags; +} + +#if ( configUSE_TRACE_FACILITY == 1 ) + + UBaseType_t uxStreamBufferGetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer ) + { + return xStreamBuffer->uxStreamBufferNumber; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + void vStreamBufferSetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer, + UBaseType_t uxStreamBufferNumber ) + { + xStreamBuffer->uxStreamBufferNumber = uxStreamBufferNumber; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + uint8_t ucStreamBufferGetStreamBufferType( StreamBufferHandle_t xStreamBuffer ) + { + return( xStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ); + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/tasks.c b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/tasks.c new file mode 100644 index 0000000..6bd84ce --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/tasks.c @@ -0,0 +1,5442 @@ +/* + * FreeRTOS Kernel V10.4.6 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* Standard includes. */ +#include +#include + +/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining + * all the API functions to use the MPU wrappers. That should only be done when + * task.h is included from an application file. */ +#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "timers.h" +#include "stack_macros.h" + +/* Lint e9021, e961 and e750 are suppressed as a MISRA exception justified + * because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined + * for the header files above, but not in this file, in order to generate the + * correct privileged Vs unprivileged linkage and placement. */ +#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750 !e9021. */ + +/* Set configUSE_STATS_FORMATTING_FUNCTIONS to 2 to include the stats formatting + * functions but without including stdio.h here. */ +#if ( configUSE_STATS_FORMATTING_FUNCTIONS == 1 ) + +/* At the bottom of this file are two optional functions that can be used + * to generate human readable text from the raw data generated by the + * uxTaskGetSystemState() function. Note the formatting functions are provided + * for convenience only, and are NOT considered part of the kernel. */ + #include +#endif /* configUSE_STATS_FORMATTING_FUNCTIONS == 1 ) */ + +#if ( configUSE_PREEMPTION == 0 ) + +/* If the cooperative scheduler is being used then a yield should not be + * performed just because a higher priority task has been woken. */ + #define taskYIELD_IF_USING_PREEMPTION() +#else + #define taskYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API() +#endif + +/* Values that can be assigned to the ucNotifyState member of the TCB. */ +#define taskNOT_WAITING_NOTIFICATION ( ( uint8_t ) 0 ) /* Must be zero as it is the initialised value. */ +#define taskWAITING_NOTIFICATION ( ( uint8_t ) 1 ) +#define taskNOTIFICATION_RECEIVED ( ( uint8_t ) 2 ) + +/* + * The value used to fill the stack of a task when the task is created. This + * is used purely for checking the high water mark for tasks. + */ +#define tskSTACK_FILL_BYTE ( 0xa5U ) + +/* Bits used to record how a task's stack and TCB were allocated. */ +#define tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB ( ( uint8_t ) 0 ) +#define tskSTATICALLY_ALLOCATED_STACK_ONLY ( ( uint8_t ) 1 ) +#define tskSTATICALLY_ALLOCATED_STACK_AND_TCB ( ( uint8_t ) 2 ) + +/* If any of the following are set then task stacks are filled with a known + * value so the high water mark can be determined. If none of the following are + * set then don't fill the stack so there is no unnecessary dependency on memset. */ +#if ( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) || ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) ) + #define tskSET_NEW_STACKS_TO_KNOWN_VALUE 1 +#else + #define tskSET_NEW_STACKS_TO_KNOWN_VALUE 0 +#endif + +/* + * Macros used by vListTask to indicate which state a task is in. + */ +#define tskRUNNING_CHAR ( 'X' ) +#define tskBLOCKED_CHAR ( 'B' ) +#define tskREADY_CHAR ( 'R' ) +#define tskDELETED_CHAR ( 'D' ) +#define tskSUSPENDED_CHAR ( 'S' ) + +/* + * Some kernel aware debuggers require the data the debugger needs access to to + * be global, rather than file scope. + */ +#ifdef portREMOVE_STATIC_QUALIFIER + #define static +#endif + +/* The name allocated to the Idle task. This can be overridden by defining + * configIDLE_TASK_NAME in FreeRTOSConfig.h. */ +#ifndef configIDLE_TASK_NAME + #define configIDLE_TASK_NAME "IDLE" +#endif + +#if ( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 ) + +/* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 0 then task selection is + * performed in a generic way that is not optimised to any particular + * microcontroller architecture. */ + +/* uxTopReadyPriority holds the priority of the highest priority ready + * state task. */ + #define taskRECORD_READY_PRIORITY( uxPriority ) \ + { \ + if( ( uxPriority ) > uxTopReadyPriority ) \ + { \ + uxTopReadyPriority = ( uxPriority ); \ + } \ + } /* taskRECORD_READY_PRIORITY */ + +/*-----------------------------------------------------------*/ + + #define taskSELECT_HIGHEST_PRIORITY_TASK() \ + { \ + UBaseType_t uxTopPriority = uxTopReadyPriority; \ + \ + /* Find the highest priority queue that contains ready tasks. */ \ + while( listLIST_IS_EMPTY( &( pxReadyTasksLists[ uxTopPriority ] ) ) ) \ + { \ + configASSERT( uxTopPriority ); \ + --uxTopPriority; \ + } \ + \ + /* listGET_OWNER_OF_NEXT_ENTRY indexes through the list, so the tasks of \ + * the same priority get an equal share of the processor time. */ \ + listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) ); \ + uxTopReadyPriority = uxTopPriority; \ + } /* taskSELECT_HIGHEST_PRIORITY_TASK */ + +/*-----------------------------------------------------------*/ + +/* Define away taskRESET_READY_PRIORITY() and portRESET_READY_PRIORITY() as + * they are only required when a port optimised method of task selection is + * being used. */ + #define taskRESET_READY_PRIORITY( uxPriority ) + #define portRESET_READY_PRIORITY( uxPriority, uxTopReadyPriority ) + +#else /* configUSE_PORT_OPTIMISED_TASK_SELECTION */ + +/* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 1 then task selection is + * performed in a way that is tailored to the particular microcontroller + * architecture being used. */ + +/* A port optimised version is provided. Call the port defined macros. */ + #define taskRECORD_READY_PRIORITY( uxPriority ) portRECORD_READY_PRIORITY( uxPriority, uxTopReadyPriority ) + +/*-----------------------------------------------------------*/ + + #define taskSELECT_HIGHEST_PRIORITY_TASK() \ + { \ + UBaseType_t uxTopPriority; \ + \ + /* Find the highest priority list that contains ready tasks. */ \ + portGET_HIGHEST_PRIORITY( uxTopPriority, uxTopReadyPriority ); \ + configASSERT( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ uxTopPriority ] ) ) > 0 ); \ + listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) ); \ + } /* taskSELECT_HIGHEST_PRIORITY_TASK() */ + +/*-----------------------------------------------------------*/ + +/* A port optimised version is provided, call it only if the TCB being reset + * is being referenced from a ready list. If it is referenced from a delayed + * or suspended list then it won't be in a ready list. */ + #define taskRESET_READY_PRIORITY( uxPriority ) \ + { \ + if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ ( uxPriority ) ] ) ) == ( UBaseType_t ) 0 ) \ + { \ + portRESET_READY_PRIORITY( ( uxPriority ), ( uxTopReadyPriority ) ); \ + } \ + } + +#endif /* configUSE_PORT_OPTIMISED_TASK_SELECTION */ + +/*-----------------------------------------------------------*/ + +/* pxDelayedTaskList and pxOverflowDelayedTaskList are switched when the tick + * count overflows. */ +#define taskSWITCH_DELAYED_LISTS() \ + { \ + List_t * pxTemp; \ + \ + /* The delayed tasks list should be empty when the lists are switched. */ \ + configASSERT( ( listLIST_IS_EMPTY( pxDelayedTaskList ) ) ); \ + \ + pxTemp = pxDelayedTaskList; \ + pxDelayedTaskList = pxOverflowDelayedTaskList; \ + pxOverflowDelayedTaskList = pxTemp; \ + xNumOfOverflows++; \ + prvResetNextTaskUnblockTime(); \ + } + +/*-----------------------------------------------------------*/ + +/* + * Place the task represented by pxTCB into the appropriate ready list for + * the task. It is inserted at the end of the list. + */ +#define prvAddTaskToReadyList( pxTCB ) \ + traceMOVED_TASK_TO_READY_STATE( pxTCB ); \ + taskRECORD_READY_PRIORITY( ( pxTCB )->uxPriority ); \ + listINSERT_END( &( pxReadyTasksLists[ ( pxTCB )->uxPriority ] ), &( ( pxTCB )->xStateListItem ) ); \ + tracePOST_MOVED_TASK_TO_READY_STATE( pxTCB ) +/*-----------------------------------------------------------*/ + +/* + * Several functions take a TaskHandle_t parameter that can optionally be NULL, + * where NULL is used to indicate that the handle of the currently executing + * task should be used in place of the parameter. This macro simply checks to + * see if the parameter is NULL and returns a pointer to the appropriate TCB. + */ +#define prvGetTCBFromHandle( pxHandle ) ( ( ( pxHandle ) == NULL ) ? pxCurrentTCB : ( pxHandle ) ) + +/* The item value of the event list item is normally used to hold the priority + * of the task to which it belongs (coded to allow it to be held in reverse + * priority order). However, it is occasionally borrowed for other purposes. It + * is important its value is not updated due to a task priority change while it is + * being used for another purpose. The following bit definition is used to inform + * the scheduler that the value should not be changed - in which case it is the + * responsibility of whichever module is using the value to ensure it gets set back + * to its original value when it is released. */ +#if ( configUSE_16_BIT_TICKS == 1 ) + #define taskEVENT_LIST_ITEM_VALUE_IN_USE 0x8000U +#else + #define taskEVENT_LIST_ITEM_VALUE_IN_USE 0x80000000UL +#endif + +/* + * Task control block. A task control block (TCB) is allocated for each task, + * and stores task state information, including a pointer to the task's context + * (the task's run time environment, including register values) + */ +typedef struct tskTaskControlBlock /* The old naming convention is used to prevent breaking kernel aware debuggers. */ +{ + volatile StackType_t * pxTopOfStack; /*< Points to the location of the last item placed on the tasks stack. THIS MUST BE THE FIRST MEMBER OF THE TCB STRUCT. */ + + #if ( portUSING_MPU_WRAPPERS == 1 ) + xMPU_SETTINGS xMPUSettings; /*< The MPU settings are defined as part of the port layer. THIS MUST BE THE SECOND MEMBER OF THE TCB STRUCT. */ + #endif + + ListItem_t xStateListItem; /*< The list that the state list item of a task is reference from denotes the state of that task (Ready, Blocked, Suspended ). */ + ListItem_t xEventListItem; /*< Used to reference a task from an event list. */ + UBaseType_t uxPriority; /*< The priority of the task. 0 is the lowest priority. */ + StackType_t * pxStack; /*< Points to the start of the stack. */ + char pcTaskName[ configMAX_TASK_NAME_LEN ]; /*< Descriptive name given to the task when created. Facilitates debugging only. */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + + #if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) ) + StackType_t * pxEndOfStack; /*< Points to the highest valid address for the stack. */ + #endif + + #if ( portCRITICAL_NESTING_IN_TCB == 1 ) + UBaseType_t uxCriticalNesting; /*< Holds the critical section nesting depth for ports that do not maintain their own count in the port layer. */ + #endif + + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxTCBNumber; /*< Stores a number that increments each time a TCB is created. It allows debuggers to determine when a task has been deleted and then recreated. */ + UBaseType_t uxTaskNumber; /*< Stores a number specifically for use by third party trace code. */ + #endif + + #if ( configUSE_MUTEXES == 1 ) + UBaseType_t uxBasePriority; /*< The priority last assigned to the task - used by the priority inheritance mechanism. */ + UBaseType_t uxMutexesHeld; + #endif + + #if ( configUSE_APPLICATION_TASK_TAG == 1 ) + TaskHookFunction_t pxTaskTag; + #endif + + #if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) + void * pvThreadLocalStoragePointers[ configNUM_THREAD_LOCAL_STORAGE_POINTERS ]; + #endif + + #if ( configGENERATE_RUN_TIME_STATS == 1 ) + configRUN_TIME_COUNTER_TYPE ulRunTimeCounter; /*< Stores the amount of time the task has spent in the Running state. */ + #endif + + #if ( configUSE_NEWLIB_REENTRANT == 1 ) + + /* Allocate a Newlib reent structure that is specific to this task. + * Note Newlib support has been included by popular demand, but is not + * used by the FreeRTOS maintainers themselves. FreeRTOS is not + * responsible for resulting newlib operation. User must be familiar with + * newlib and must provide system-wide implementations of the necessary + * stubs. Be warned that (at the time of writing) the current newlib design + * implements a system-wide malloc() that must be provided with locks. + * + * See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html + * for additional information. */ + struct _reent xNewLib_reent; + #endif + + #if ( configUSE_TASK_NOTIFICATIONS == 1 ) + volatile uint32_t ulNotifiedValue[ configTASK_NOTIFICATION_ARRAY_ENTRIES ]; + volatile uint8_t ucNotifyState[ configTASK_NOTIFICATION_ARRAY_ENTRIES ]; + #endif + + /* See the comments in FreeRTOS.h with the definition of + * tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE. */ + #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */ + uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the task is a statically allocated to ensure no attempt is made to free the memory. */ + #endif + + #if ( INCLUDE_xTaskAbortDelay == 1 ) + uint8_t ucDelayAborted; + #endif + + #if ( configUSE_POSIX_ERRNO == 1 ) + int iTaskErrno; + #endif +} tskTCB; + +/* The old tskTCB name is maintained above then typedefed to the new TCB_t name + * below to enable the use of older kernel aware debuggers. */ +typedef tskTCB TCB_t; + +/*lint -save -e956 A manual analysis and inspection has been used to determine + * which static variables must be declared volatile. */ +PRIVILEGED_DATA TCB_t * volatile pxCurrentTCB = NULL; + +/* Lists for ready and blocked tasks. -------------------- + * xDelayedTaskList1 and xDelayedTaskList2 could be moved to function scope but + * doing so breaks some kernel aware debuggers and debuggers that rely on removing + * the static qualifier. */ +PRIVILEGED_DATA static List_t pxReadyTasksLists[ configMAX_PRIORITIES ]; /*< Prioritised ready tasks. */ +PRIVILEGED_DATA static List_t xDelayedTaskList1; /*< Delayed tasks. */ +PRIVILEGED_DATA static List_t xDelayedTaskList2; /*< Delayed tasks (two lists are used - one for delays that have overflowed the current tick count. */ +PRIVILEGED_DATA static List_t * volatile pxDelayedTaskList; /*< Points to the delayed task list currently being used. */ +PRIVILEGED_DATA static List_t * volatile pxOverflowDelayedTaskList; /*< Points to the delayed task list currently being used to hold tasks that have overflowed the current tick count. */ +PRIVILEGED_DATA static List_t xPendingReadyList; /*< Tasks that have been readied while the scheduler was suspended. They will be moved to the ready list when the scheduler is resumed. */ + +#if ( INCLUDE_vTaskDelete == 1 ) + + PRIVILEGED_DATA static List_t xTasksWaitingTermination; /*< Tasks that have been deleted - but their memory not yet freed. */ + PRIVILEGED_DATA static volatile UBaseType_t uxDeletedTasksWaitingCleanUp = ( UBaseType_t ) 0U; + +#endif + +#if ( INCLUDE_vTaskSuspend == 1 ) + + PRIVILEGED_DATA static List_t xSuspendedTaskList; /*< Tasks that are currently suspended. */ + +#endif + +/* Global POSIX errno. Its value is changed upon context switching to match + * the errno of the currently running task. */ +#if ( configUSE_POSIX_ERRNO == 1 ) + int FreeRTOS_errno = 0; +#endif + +/* Other file private variables. --------------------------------*/ +PRIVILEGED_DATA static volatile UBaseType_t uxCurrentNumberOfTasks = ( UBaseType_t ) 0U; +PRIVILEGED_DATA static volatile TickType_t xTickCount = ( TickType_t ) configINITIAL_TICK_COUNT; +PRIVILEGED_DATA static volatile UBaseType_t uxTopReadyPriority = tskIDLE_PRIORITY; +PRIVILEGED_DATA static volatile BaseType_t xSchedulerRunning = pdFALSE; +PRIVILEGED_DATA static volatile TickType_t xPendedTicks = ( TickType_t ) 0U; +PRIVILEGED_DATA static volatile BaseType_t xYieldPending = pdFALSE; +PRIVILEGED_DATA static volatile BaseType_t xNumOfOverflows = ( BaseType_t ) 0; +PRIVILEGED_DATA static UBaseType_t uxTaskNumber = ( UBaseType_t ) 0U; +PRIVILEGED_DATA static volatile TickType_t xNextTaskUnblockTime = ( TickType_t ) 0U; /* Initialised to portMAX_DELAY before the scheduler starts. */ +PRIVILEGED_DATA static TaskHandle_t xIdleTaskHandle = NULL; /*< Holds the handle of the idle task. The idle task is created automatically when the scheduler is started. */ + +/* Improve support for OpenOCD. The kernel tracks Ready tasks via priority lists. + * For tracking the state of remote threads, OpenOCD uses uxTopUsedPriority + * to determine the number of priority lists to read back from the remote target. */ +const volatile UBaseType_t uxTopUsedPriority = configMAX_PRIORITIES - 1U; + +/* Context switches are held pending while the scheduler is suspended. Also, + * interrupts must not manipulate the xStateListItem of a TCB, or any of the + * lists the xStateListItem can be referenced from, if the scheduler is suspended. + * If an interrupt needs to unblock a task while the scheduler is suspended then it + * moves the task's event list item into the xPendingReadyList, ready for the + * kernel to move the task from the pending ready list into the real ready list + * when the scheduler is unsuspended. The pending ready list itself can only be + * accessed from a critical section. */ +PRIVILEGED_DATA static volatile UBaseType_t uxSchedulerSuspended = ( UBaseType_t ) pdFALSE; + +#if ( configGENERATE_RUN_TIME_STATS == 1 ) + +/* Do not move these variables to function scope as doing so prevents the + * code working with debuggers that need to remove the static qualifier. */ + PRIVILEGED_DATA static configRUN_TIME_COUNTER_TYPE ulTaskSwitchedInTime = 0UL; /*< Holds the value of a timer/counter the last time a task was switched in. */ + PRIVILEGED_DATA static volatile configRUN_TIME_COUNTER_TYPE ulTotalRunTime = 0UL; /*< Holds the total amount of execution time as defined by the run time counter clock. */ + +#endif + +/*lint -restore */ + +/*-----------------------------------------------------------*/ + +/* File private functions. --------------------------------*/ + +/** + * Utility task that simply returns pdTRUE if the task referenced by xTask is + * currently in the Suspended state, or pdFALSE if the task referenced by xTask + * is in any other state. + */ +#if ( INCLUDE_vTaskSuspend == 1 ) + + static BaseType_t prvTaskIsTaskSuspended( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +#endif /* INCLUDE_vTaskSuspend */ + +/* + * Utility to ready all the lists used by the scheduler. This is called + * automatically upon the creation of the first task. + */ +static void prvInitialiseTaskLists( void ) PRIVILEGED_FUNCTION; + +/* + * The idle task, which as all tasks is implemented as a never ending loop. + * The idle task is automatically created and added to the ready lists upon + * creation of the first user task. + * + * The portTASK_FUNCTION_PROTO() macro is used to allow port/compiler specific + * language extensions. The equivalent prototype for this function is: + * + * void prvIdleTask( void *pvParameters ); + * + */ +static portTASK_FUNCTION_PROTO( prvIdleTask, pvParameters ) PRIVILEGED_FUNCTION; + +/* + * Utility to free all memory allocated by the scheduler to hold a TCB, + * including the stack pointed to by the TCB. + * + * This does not free memory allocated by the task itself (i.e. memory + * allocated by calls to pvPortMalloc from within the tasks application code). + */ +#if ( INCLUDE_vTaskDelete == 1 ) + + static void prvDeleteTCB( TCB_t * pxTCB ) PRIVILEGED_FUNCTION; + +#endif + +/* + * Used only by the idle task. This checks to see if anything has been placed + * in the list of tasks waiting to be deleted. If so the task is cleaned up + * and its TCB deleted. + */ +static void prvCheckTasksWaitingTermination( void ) PRIVILEGED_FUNCTION; + +/* + * The currently executing task is entering the Blocked state. Add the task to + * either the current or the overflow delayed task list. + */ +static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait, + const BaseType_t xCanBlockIndefinitely ) PRIVILEGED_FUNCTION; + +/* + * Fills an TaskStatus_t structure with information on each task that is + * referenced from the pxList list (which may be a ready list, a delayed list, + * a suspended list, etc.). + * + * THIS FUNCTION IS INTENDED FOR DEBUGGING ONLY, AND SHOULD NOT BE CALLED FROM + * NORMAL APPLICATION CODE. + */ +#if ( configUSE_TRACE_FACILITY == 1 ) + + static UBaseType_t prvListTasksWithinSingleList( TaskStatus_t * pxTaskStatusArray, + List_t * pxList, + eTaskState eState ) PRIVILEGED_FUNCTION; + +#endif + +/* + * Searches pxList for a task with name pcNameToQuery - returning a handle to + * the task if it is found, or NULL if the task is not found. + */ +#if ( INCLUDE_xTaskGetHandle == 1 ) + + static TCB_t * prvSearchForNameWithinSingleList( List_t * pxList, + const char pcNameToQuery[] ) PRIVILEGED_FUNCTION; + +#endif + +/* + * When a task is created, the stack of the task is filled with a known value. + * This function determines the 'high water mark' of the task stack by + * determining how much of the stack remains at the original preset value. + */ +#if ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) ) + + static configSTACK_DEPTH_TYPE prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte ) PRIVILEGED_FUNCTION; + +#endif + +/* + * Return the amount of time, in ticks, that will pass before the kernel will + * next move a task from the Blocked state to the Running state. + * + * This conditional compilation should use inequality to 0, not equality to 1. + * This is to ensure portSUPPRESS_TICKS_AND_SLEEP() can be called when user + * defined low power mode implementations require configUSE_TICKLESS_IDLE to be + * set to a value other than 1. + */ +#if ( configUSE_TICKLESS_IDLE != 0 ) + + static TickType_t prvGetExpectedIdleTime( void ) PRIVILEGED_FUNCTION; + +#endif + +/* + * Set xNextTaskUnblockTime to the time at which the next Blocked state task + * will exit the Blocked state. + */ +static void prvResetNextTaskUnblockTime( void ) PRIVILEGED_FUNCTION; + +#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) ) + +/* + * Helper function used to pad task names with spaces when printing out + * human readable tables of task information. + */ + static char * prvWriteNameToBuffer( char * pcBuffer, + const char * pcTaskName ) PRIVILEGED_FUNCTION; + +#endif + +/* + * Called after a Task_t structure has been allocated either statically or + * dynamically to fill in the structure's members. + */ +static void prvInitialiseNewTask( TaskFunction_t pxTaskCode, + const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const uint32_t ulStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask, + TCB_t * pxNewTCB, + const MemoryRegion_t * const xRegions ) PRIVILEGED_FUNCTION; + +/* + * Called after a new task has been created and initialised to place the task + * under the control of the scheduler. + */ +static void prvAddNewTaskToReadyList( TCB_t * pxNewTCB ) PRIVILEGED_FUNCTION; + +/* + * freertos_tasks_c_additions_init() should only be called if the user definable + * macro FREERTOS_TASKS_C_ADDITIONS_INIT() is defined, as that is the only macro + * called by the function. + */ +#ifdef FREERTOS_TASKS_C_ADDITIONS_INIT + + static void freertos_tasks_c_additions_init( void ) PRIVILEGED_FUNCTION; + +#endif + +/*-----------------------------------------------------------*/ + +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + + TaskHandle_t xTaskCreateStatic( TaskFunction_t pxTaskCode, + const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const uint32_t ulStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + StackType_t * const puxStackBuffer, + StaticTask_t * const pxTaskBuffer ) + { + TCB_t * pxNewTCB; + TaskHandle_t xReturn; + + configASSERT( puxStackBuffer != NULL ); + configASSERT( pxTaskBuffer != NULL ); + + #if ( configASSERT_DEFINED == 1 ) + { + /* Sanity check that the size of the structure used to declare a + * variable of type StaticTask_t equals the size of the real task + * structure. */ + volatile size_t xSize = sizeof( StaticTask_t ); + configASSERT( xSize == sizeof( TCB_t ) ); + ( void ) xSize; /* Prevent lint warning when configASSERT() is not used. */ + } + #endif /* configASSERT_DEFINED */ + + if( ( pxTaskBuffer != NULL ) && ( puxStackBuffer != NULL ) ) + { + /* The memory used for the task's TCB and stack are passed into this + * function - use them. */ + pxNewTCB = ( TCB_t * ) pxTaskBuffer; /*lint !e740 !e9087 Unusual cast is ok as the structures are designed to have the same alignment, and the size is checked by an assert. */ + pxNewTCB->pxStack = ( StackType_t * ) puxStackBuffer; + + #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */ + { + /* Tasks can be created statically or dynamically, so note this + * task was created statically in case the task is later deleted. */ + pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB; + } + #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ + + prvInitialiseNewTask( pxTaskCode, pcName, ulStackDepth, pvParameters, uxPriority, &xReturn, pxNewTCB, NULL ); + prvAddNewTaskToReadyList( pxNewTCB ); + } + else + { + xReturn = NULL; + } + + return xReturn; + } + +#endif /* SUPPORT_STATIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +#if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + + BaseType_t xTaskCreateRestrictedStatic( const TaskParameters_t * const pxTaskDefinition, + TaskHandle_t * pxCreatedTask ) + { + TCB_t * pxNewTCB; + BaseType_t xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; + + configASSERT( pxTaskDefinition->puxStackBuffer != NULL ); + configASSERT( pxTaskDefinition->pxTaskBuffer != NULL ); + + if( ( pxTaskDefinition->puxStackBuffer != NULL ) && ( pxTaskDefinition->pxTaskBuffer != NULL ) ) + { + /* Allocate space for the TCB. Where the memory comes from depends + * on the implementation of the port malloc function and whether or + * not static allocation is being used. */ + pxNewTCB = ( TCB_t * ) pxTaskDefinition->pxTaskBuffer; + + /* Store the stack location in the TCB. */ + pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer; + + #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) + { + /* Tasks can be created statically or dynamically, so note this + * task was created statically in case the task is later deleted. */ + pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB; + } + #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ + + prvInitialiseNewTask( pxTaskDefinition->pvTaskCode, + pxTaskDefinition->pcName, + ( uint32_t ) pxTaskDefinition->usStackDepth, + pxTaskDefinition->pvParameters, + pxTaskDefinition->uxPriority, + pxCreatedTask, pxNewTCB, + pxTaskDefinition->xRegions ); + + prvAddNewTaskToReadyList( pxNewTCB ); + xReturn = pdPASS; + } + + return xReturn; + } + +#endif /* ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ +/*-----------------------------------------------------------*/ + +#if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + + BaseType_t xTaskCreateRestricted( const TaskParameters_t * const pxTaskDefinition, + TaskHandle_t * pxCreatedTask ) + { + TCB_t * pxNewTCB; + BaseType_t xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; + + configASSERT( pxTaskDefinition->puxStackBuffer ); + + if( pxTaskDefinition->puxStackBuffer != NULL ) + { + /* Allocate space for the TCB. Where the memory comes from depends + * on the implementation of the port malloc function and whether or + * not static allocation is being used. */ + pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); + + if( pxNewTCB != NULL ) + { + /* Store the stack location in the TCB. */ + pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer; + + #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) + { + /* Tasks can be created statically or dynamically, so note + * this task had a statically allocated stack in case it is + * later deleted. The TCB was allocated dynamically. */ + pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_ONLY; + } + #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ + + prvInitialiseNewTask( pxTaskDefinition->pvTaskCode, + pxTaskDefinition->pcName, + ( uint32_t ) pxTaskDefinition->usStackDepth, + pxTaskDefinition->pvParameters, + pxTaskDefinition->uxPriority, + pxCreatedTask, pxNewTCB, + pxTaskDefinition->xRegions ); + + prvAddNewTaskToReadyList( pxNewTCB ); + xReturn = pdPASS; + } + } + + return xReturn; + } + +#endif /* portUSING_MPU_WRAPPERS */ +/*-----------------------------------------------------------*/ + +#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + + BaseType_t xTaskCreate( TaskFunction_t pxTaskCode, + const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const configSTACK_DEPTH_TYPE usStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask ) + { + TCB_t * pxNewTCB; + BaseType_t xReturn; + + /* If the stack grows down then allocate the stack then the TCB so the stack + * does not grow into the TCB. Likewise if the stack grows up then allocate + * the TCB then the stack. */ + #if ( portSTACK_GROWTH > 0 ) + { + /* Allocate space for the TCB. Where the memory comes from depends on + * the implementation of the port malloc function and whether or not static + * allocation is being used. */ + pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); + + if( pxNewTCB != NULL ) + { + /* Allocate space for the stack used by the task being created. + * The base of the stack memory stored in the TCB so the task can + * be deleted later if required. */ + pxNewTCB->pxStack = ( StackType_t * ) pvPortMallocStack( ( ( ( size_t ) usStackDepth ) * sizeof( StackType_t ) ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + + if( pxNewTCB->pxStack == NULL ) + { + /* Could not allocate the stack. Delete the allocated TCB. */ + vPortFree( pxNewTCB ); + pxNewTCB = NULL; + } + } + } + #else /* portSTACK_GROWTH */ + { + StackType_t * pxStack; + + /* Allocate space for the stack used by the task being created. */ + pxStack = pvPortMallocStack( ( ( ( size_t ) usStackDepth ) * sizeof( StackType_t ) ) ); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and this allocation is the stack. */ + + if( pxStack != NULL ) + { + /* Allocate space for the TCB. */ + pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); /*lint !e9087 !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack, and the first member of TCB_t is always a pointer to the task's stack. */ + + if( pxNewTCB != NULL ) + { + /* Store the stack location in the TCB. */ + pxNewTCB->pxStack = pxStack; + } + else + { + /* The stack cannot be used as the TCB was not created. Free + * it again. */ + vPortFreeStack( pxStack ); + } + } + else + { + pxNewTCB = NULL; + } + } + #endif /* portSTACK_GROWTH */ + + if( pxNewTCB != NULL ) + { + #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e9029 !e731 Macro has been consolidated for readability reasons. */ + { + /* Tasks can be created statically or dynamically, so note this + * task was created dynamically in case it is later deleted. */ + pxNewTCB->ucStaticallyAllocated = tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB; + } + #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ + + prvInitialiseNewTask( pxTaskCode, pcName, ( uint32_t ) usStackDepth, pvParameters, uxPriority, pxCreatedTask, pxNewTCB, NULL ); + prvAddNewTaskToReadyList( pxNewTCB ); + xReturn = pdPASS; + } + else + { + xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; + } + + return xReturn; + } + +#endif /* configSUPPORT_DYNAMIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +static void prvInitialiseNewTask( TaskFunction_t pxTaskCode, + const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const uint32_t ulStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask, + TCB_t * pxNewTCB, + const MemoryRegion_t * const xRegions ) +{ + StackType_t * pxTopOfStack; + UBaseType_t x; + + #if ( portUSING_MPU_WRAPPERS == 1 ) + /* Should the task be created in privileged mode? */ + BaseType_t xRunPrivileged; + + if( ( uxPriority & portPRIVILEGE_BIT ) != 0U ) + { + xRunPrivileged = pdTRUE; + } + else + { + xRunPrivileged = pdFALSE; + } + uxPriority &= ~portPRIVILEGE_BIT; + #endif /* portUSING_MPU_WRAPPERS == 1 */ + + /* Avoid dependency on memset() if it is not required. */ + #if ( tskSET_NEW_STACKS_TO_KNOWN_VALUE == 1 ) + { + /* Fill the stack with a known value to assist debugging. */ + ( void ) memset( pxNewTCB->pxStack, ( int ) tskSTACK_FILL_BYTE, ( size_t ) ulStackDepth * sizeof( StackType_t ) ); + } + #endif /* tskSET_NEW_STACKS_TO_KNOWN_VALUE */ + + /* Calculate the top of stack address. This depends on whether the stack + * grows from high memory to low (as per the 80x86) or vice versa. + * portSTACK_GROWTH is used to make the result positive or negative as required + * by the port. */ + #if ( portSTACK_GROWTH < 0 ) + { + pxTopOfStack = &( pxNewTCB->pxStack[ ulStackDepth - ( uint32_t ) 1 ] ); + pxTopOfStack = ( StackType_t * ) ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); /*lint !e923 !e9033 !e9078 MISRA exception. Avoiding casts between pointers and integers is not practical. Size differences accounted for using portPOINTER_SIZE_TYPE type. Checked by assert(). */ + + /* Check the alignment of the calculated top of stack is correct. */ + configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0UL ) ); + + #if ( configRECORD_STACK_HIGH_ADDRESS == 1 ) + { + /* Also record the stack's high address, which may assist + * debugging. */ + pxNewTCB->pxEndOfStack = pxTopOfStack; + } + #endif /* configRECORD_STACK_HIGH_ADDRESS */ + } + #else /* portSTACK_GROWTH */ + { + pxTopOfStack = pxNewTCB->pxStack; + + /* Check the alignment of the stack buffer is correct. */ + configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxNewTCB->pxStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0UL ) ); + + /* The other extreme of the stack space is required if stack checking is + * performed. */ + pxNewTCB->pxEndOfStack = pxNewTCB->pxStack + ( ulStackDepth - ( uint32_t ) 1 ); + } + #endif /* portSTACK_GROWTH */ + + /* Store the task name in the TCB. */ + if( pcName != NULL ) + { + for( x = ( UBaseType_t ) 0; x < ( UBaseType_t ) configMAX_TASK_NAME_LEN; x++ ) + { + pxNewTCB->pcTaskName[ x ] = pcName[ x ]; + + /* Don't copy all configMAX_TASK_NAME_LEN if the string is shorter than + * configMAX_TASK_NAME_LEN characters just in case the memory after the + * string is not accessible (extremely unlikely). */ + if( pcName[ x ] == ( char ) 0x00 ) + { + break; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + /* Ensure the name string is terminated in the case that the string length + * was greater or equal to configMAX_TASK_NAME_LEN. */ + pxNewTCB->pcTaskName[ configMAX_TASK_NAME_LEN - 1 ] = '\0'; + } + else + { + /* The task has not been given a name, so just ensure there is a NULL + * terminator when it is read out. */ + pxNewTCB->pcTaskName[ 0 ] = 0x00; + } + + /* This is used as an array index so must ensure it's not too large. */ + configASSERT( uxPriority < configMAX_PRIORITIES ); + + if( uxPriority >= ( UBaseType_t ) configMAX_PRIORITIES ) + { + uxPriority = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) 1U; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + pxNewTCB->uxPriority = uxPriority; + #if ( configUSE_MUTEXES == 1 ) + { + pxNewTCB->uxBasePriority = uxPriority; + pxNewTCB->uxMutexesHeld = 0; + } + #endif /* configUSE_MUTEXES */ + + vListInitialiseItem( &( pxNewTCB->xStateListItem ) ); + vListInitialiseItem( &( pxNewTCB->xEventListItem ) ); + + /* Set the pxNewTCB as a link back from the ListItem_t. This is so we can get + * back to the containing TCB from a generic item in a list. */ + listSET_LIST_ITEM_OWNER( &( pxNewTCB->xStateListItem ), pxNewTCB ); + + /* Event lists are always in priority order. */ + listSET_LIST_ITEM_VALUE( &( pxNewTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + listSET_LIST_ITEM_OWNER( &( pxNewTCB->xEventListItem ), pxNewTCB ); + + #if ( portCRITICAL_NESTING_IN_TCB == 1 ) + { + pxNewTCB->uxCriticalNesting = ( UBaseType_t ) 0U; + } + #endif /* portCRITICAL_NESTING_IN_TCB */ + + #if ( configUSE_APPLICATION_TASK_TAG == 1 ) + { + pxNewTCB->pxTaskTag = NULL; + } + #endif /* configUSE_APPLICATION_TASK_TAG */ + + #if ( configGENERATE_RUN_TIME_STATS == 1 ) + { + pxNewTCB->ulRunTimeCounter = ( configRUN_TIME_COUNTER_TYPE ) 0; + } + #endif /* configGENERATE_RUN_TIME_STATS */ + + #if ( portUSING_MPU_WRAPPERS == 1 ) + { + vPortStoreTaskMPUSettings( &( pxNewTCB->xMPUSettings ), xRegions, pxNewTCB->pxStack, ulStackDepth ); + } + #else + { + /* Avoid compiler warning about unreferenced parameter. */ + ( void ) xRegions; + } + #endif + + #if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) + { + memset( ( void * ) &( pxNewTCB->pvThreadLocalStoragePointers[ 0 ] ), 0x00, sizeof( pxNewTCB->pvThreadLocalStoragePointers ) ); + } + #endif + + #if ( configUSE_TASK_NOTIFICATIONS == 1 ) + { + memset( ( void * ) &( pxNewTCB->ulNotifiedValue[ 0 ] ), 0x00, sizeof( pxNewTCB->ulNotifiedValue ) ); + memset( ( void * ) &( pxNewTCB->ucNotifyState[ 0 ] ), 0x00, sizeof( pxNewTCB->ucNotifyState ) ); + } + #endif + + #if ( configUSE_NEWLIB_REENTRANT == 1 ) + { + /* Initialise this task's Newlib reent structure. + * See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html + * for additional information. */ + _REENT_INIT_PTR( ( &( pxNewTCB->xNewLib_reent ) ) ); + } + #endif + + #if ( INCLUDE_xTaskAbortDelay == 1 ) + { + pxNewTCB->ucDelayAborted = pdFALSE; + } + #endif + + /* Initialize the TCB stack to look as if the task was already running, + * but had been interrupted by the scheduler. The return address is set + * to the start of the task function. Once the stack has been initialised + * the top of stack variable is updated. */ + #if ( portUSING_MPU_WRAPPERS == 1 ) + { + /* If the port has capability to detect stack overflow, + * pass the stack end address to the stack initialization + * function as well. */ + #if ( portHAS_STACK_OVERFLOW_CHECKING == 1 ) + { + #if ( portSTACK_GROWTH < 0 ) + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxStack, pxTaskCode, pvParameters, xRunPrivileged ); + } + #else /* portSTACK_GROWTH */ + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxEndOfStack, pxTaskCode, pvParameters, xRunPrivileged ); + } + #endif /* portSTACK_GROWTH */ + } + #else /* portHAS_STACK_OVERFLOW_CHECKING */ + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters, xRunPrivileged ); + } + #endif /* portHAS_STACK_OVERFLOW_CHECKING */ + } + #else /* portUSING_MPU_WRAPPERS */ + { + /* If the port has capability to detect stack overflow, + * pass the stack end address to the stack initialization + * function as well. */ + #if ( portHAS_STACK_OVERFLOW_CHECKING == 1 ) + { + #if ( portSTACK_GROWTH < 0 ) + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxStack, pxTaskCode, pvParameters ); + } + #else /* portSTACK_GROWTH */ + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxEndOfStack, pxTaskCode, pvParameters ); + } + #endif /* portSTACK_GROWTH */ + } + #else /* portHAS_STACK_OVERFLOW_CHECKING */ + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters ); + } + #endif /* portHAS_STACK_OVERFLOW_CHECKING */ + } + #endif /* portUSING_MPU_WRAPPERS */ + + if( pxCreatedTask != NULL ) + { + /* Pass the handle out in an anonymous way. The handle can be used to + * change the created task's priority, delete the created task, etc.*/ + *pxCreatedTask = ( TaskHandle_t ) pxNewTCB; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } +} +/*-----------------------------------------------------------*/ + +static void prvAddNewTaskToReadyList( TCB_t * pxNewTCB ) +{ + /* Ensure interrupts don't access the task lists while the lists are being + * updated. */ + taskENTER_CRITICAL(); + { + uxCurrentNumberOfTasks++; + + if( pxCurrentTCB == NULL ) + { + /* There are no other tasks, or all the other tasks are in + * the suspended state - make this the current task. */ + pxCurrentTCB = pxNewTCB; + + if( uxCurrentNumberOfTasks == ( UBaseType_t ) 1 ) + { + /* This is the first task to be created so do the preliminary + * initialisation required. We will not recover if this call + * fails, but we will report the failure. */ + prvInitialiseTaskLists(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* If the scheduler is not already running, make this task the + * current task if it is the highest priority task to be created + * so far. */ + if( xSchedulerRunning == pdFALSE ) + { + if( pxCurrentTCB->uxPriority <= pxNewTCB->uxPriority ) + { + pxCurrentTCB = pxNewTCB; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + uxTaskNumber++; + + #if ( configUSE_TRACE_FACILITY == 1 ) + { + /* Add a counter into the TCB for tracing only. */ + pxNewTCB->uxTCBNumber = uxTaskNumber; + } + #endif /* configUSE_TRACE_FACILITY */ + traceTASK_CREATE( pxNewTCB ); + + prvAddTaskToReadyList( pxNewTCB ); + + portSETUP_TCB( pxNewTCB ); + } + taskEXIT_CRITICAL(); + + if( xSchedulerRunning != pdFALSE ) + { + /* If the created task is of a higher priority than the current task + * then it should run now. */ + if( pxCurrentTCB->uxPriority < pxNewTCB->uxPriority ) + { + taskYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } +} +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_vTaskDelete == 1 ) + + void vTaskDelete( TaskHandle_t xTaskToDelete ) + { + TCB_t * pxTCB; + + taskENTER_CRITICAL(); + { + /* If null is passed in here then it is the calling task that is + * being deleted. */ + pxTCB = prvGetTCBFromHandle( xTaskToDelete ); + + /* Remove task from the ready/delayed list. */ + if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + taskRESET_READY_PRIORITY( pxTCB->uxPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Is the task waiting on an event also? */ + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) + { + ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Increment the uxTaskNumber also so kernel aware debuggers can + * detect that the task lists need re-generating. This is done before + * portPRE_TASK_DELETE_HOOK() as in the Windows port that macro will + * not return. */ + uxTaskNumber++; + + if( pxTCB == pxCurrentTCB ) + { + /* A task is deleting itself. This cannot complete within the + * task itself, as a context switch to another task is required. + * Place the task in the termination list. The idle task will + * check the termination list and free up any memory allocated by + * the scheduler for the TCB and stack of the deleted task. */ + vListInsertEnd( &xTasksWaitingTermination, &( pxTCB->xStateListItem ) ); + + /* Increment the ucTasksDeleted variable so the idle task knows + * there is a task that has been deleted and that it should therefore + * check the xTasksWaitingTermination list. */ + ++uxDeletedTasksWaitingCleanUp; + + /* Call the delete hook before portPRE_TASK_DELETE_HOOK() as + * portPRE_TASK_DELETE_HOOK() does not return in the Win32 port. */ + traceTASK_DELETE( pxTCB ); + + /* The pre-delete hook is primarily for the Windows simulator, + * in which Windows specific clean up operations are performed, + * after which it is not possible to yield away from this task - + * hence xYieldPending is used to latch that a context switch is + * required. */ + portPRE_TASK_DELETE_HOOK( pxTCB, &xYieldPending ); + } + else + { + --uxCurrentNumberOfTasks; + traceTASK_DELETE( pxTCB ); + + /* Reset the next expected unblock time in case it referred to + * the task that has just been deleted. */ + prvResetNextTaskUnblockTime(); + } + } + taskEXIT_CRITICAL(); + + /* If the task is not deleting itself, call prvDeleteTCB from outside of + * critical section. If a task deletes itself, prvDeleteTCB is called + * from prvCheckTasksWaitingTermination which is called from Idle task. */ + if( pxTCB != pxCurrentTCB ) + { + prvDeleteTCB( pxTCB ); + } + + /* Force a reschedule if it is the currently running task that has just + * been deleted. */ + if( xSchedulerRunning != pdFALSE ) + { + if( pxTCB == pxCurrentTCB ) + { + configASSERT( uxSchedulerSuspended == 0 ); + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + +#endif /* INCLUDE_vTaskDelete */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_xTaskDelayUntil == 1 ) + + BaseType_t xTaskDelayUntil( TickType_t * const pxPreviousWakeTime, + const TickType_t xTimeIncrement ) + { + TickType_t xTimeToWake; + BaseType_t xAlreadyYielded, xShouldDelay = pdFALSE; + + configASSERT( pxPreviousWakeTime ); + configASSERT( ( xTimeIncrement > 0U ) ); + configASSERT( uxSchedulerSuspended == 0 ); + + vTaskSuspendAll(); + { + /* Minor optimisation. The tick count cannot change in this + * block. */ + const TickType_t xConstTickCount = xTickCount; + + /* Generate the tick time at which the task wants to wake. */ + xTimeToWake = *pxPreviousWakeTime + xTimeIncrement; + + if( xConstTickCount < *pxPreviousWakeTime ) + { + /* The tick count has overflowed since this function was + * lasted called. In this case the only time we should ever + * actually delay is if the wake time has also overflowed, + * and the wake time is greater than the tick time. When this + * is the case it is as if neither time had overflowed. */ + if( ( xTimeToWake < *pxPreviousWakeTime ) && ( xTimeToWake > xConstTickCount ) ) + { + xShouldDelay = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* The tick time has not overflowed. In this case we will + * delay if either the wake time has overflowed, and/or the + * tick time is less than the wake time. */ + if( ( xTimeToWake < *pxPreviousWakeTime ) || ( xTimeToWake > xConstTickCount ) ) + { + xShouldDelay = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + /* Update the wake time ready for the next call. */ + *pxPreviousWakeTime = xTimeToWake; + + if( xShouldDelay != pdFALSE ) + { + traceTASK_DELAY_UNTIL( xTimeToWake ); + + /* prvAddCurrentTaskToDelayedList() needs the block time, not + * the time to wake, so subtract the current tick count. */ + prvAddCurrentTaskToDelayedList( xTimeToWake - xConstTickCount, pdFALSE ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + xAlreadyYielded = xTaskResumeAll(); + + /* Force a reschedule if xTaskResumeAll has not already done so, we may + * have put ourselves to sleep. */ + if( xAlreadyYielded == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xShouldDelay; + } + +#endif /* INCLUDE_xTaskDelayUntil */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_vTaskDelay == 1 ) + + void vTaskDelay( const TickType_t xTicksToDelay ) + { + BaseType_t xAlreadyYielded = pdFALSE; + + /* A delay time of zero just forces a reschedule. */ + if( xTicksToDelay > ( TickType_t ) 0U ) + { + configASSERT( uxSchedulerSuspended == 0 ); + vTaskSuspendAll(); + { + traceTASK_DELAY(); + + /* A task that is removed from the event list while the + * scheduler is suspended will not get placed in the ready + * list or removed from the blocked list until the scheduler + * is resumed. + * + * This task cannot be in an event list as it is the currently + * executing task. */ + prvAddCurrentTaskToDelayedList( xTicksToDelay, pdFALSE ); + } + xAlreadyYielded = xTaskResumeAll(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Force a reschedule if xTaskResumeAll has not already done so, we may + * have put ourselves to sleep. */ + if( xAlreadyYielded == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + +#endif /* INCLUDE_vTaskDelay */ +/*-----------------------------------------------------------*/ + +#if ( ( INCLUDE_eTaskGetState == 1 ) || ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_xTaskAbortDelay == 1 ) ) + + eTaskState eTaskGetState( TaskHandle_t xTask ) + { + eTaskState eReturn; + List_t const * pxStateList, * pxDelayedList, * pxOverflowedDelayedList; + const TCB_t * const pxTCB = xTask; + + configASSERT( pxTCB ); + + if( pxTCB == pxCurrentTCB ) + { + /* The task calling this function is querying its own state. */ + eReturn = eRunning; + } + else + { + taskENTER_CRITICAL(); + { + pxStateList = listLIST_ITEM_CONTAINER( &( pxTCB->xStateListItem ) ); + pxDelayedList = pxDelayedTaskList; + pxOverflowedDelayedList = pxOverflowDelayedTaskList; + } + taskEXIT_CRITICAL(); + + if( ( pxStateList == pxDelayedList ) || ( pxStateList == pxOverflowedDelayedList ) ) + { + /* The task being queried is referenced from one of the Blocked + * lists. */ + eReturn = eBlocked; + } + + #if ( INCLUDE_vTaskSuspend == 1 ) + else if( pxStateList == &xSuspendedTaskList ) + { + /* The task being queried is referenced from the suspended + * list. Is it genuinely suspended or is it blocked + * indefinitely? */ + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ) + { + #if ( configUSE_TASK_NOTIFICATIONS == 1 ) + { + BaseType_t x; + + /* The task does not appear on the event list item of + * and of the RTOS objects, but could still be in the + * blocked state if it is waiting on its notification + * rather than waiting on an object. If not, is + * suspended. */ + eReturn = eSuspended; + + for( x = 0; x < configTASK_NOTIFICATION_ARRAY_ENTRIES; x++ ) + { + if( pxTCB->ucNotifyState[ x ] == taskWAITING_NOTIFICATION ) + { + eReturn = eBlocked; + break; + } + } + } + #else /* if ( configUSE_TASK_NOTIFICATIONS == 1 ) */ + { + eReturn = eSuspended; + } + #endif /* if ( configUSE_TASK_NOTIFICATIONS == 1 ) */ + } + else + { + eReturn = eBlocked; + } + } + #endif /* if ( INCLUDE_vTaskSuspend == 1 ) */ + + #if ( INCLUDE_vTaskDelete == 1 ) + else if( ( pxStateList == &xTasksWaitingTermination ) || ( pxStateList == NULL ) ) + { + /* The task being queried is referenced from the deleted + * tasks list, or it is not referenced from any lists at + * all. */ + eReturn = eDeleted; + } + #endif + + else /*lint !e525 Negative indentation is intended to make use of pre-processor clearer. */ + { + /* If the task is not in any other state, it must be in the + * Ready (including pending ready) state. */ + eReturn = eReady; + } + } + + return eReturn; + } /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */ + +#endif /* INCLUDE_eTaskGetState */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_uxTaskPriorityGet == 1 ) + + UBaseType_t uxTaskPriorityGet( const TaskHandle_t xTask ) + { + TCB_t const * pxTCB; + UBaseType_t uxReturn; + + taskENTER_CRITICAL(); + { + /* If null is passed in here then it is the priority of the task + * that called uxTaskPriorityGet() that is being queried. */ + pxTCB = prvGetTCBFromHandle( xTask ); + uxReturn = pxTCB->uxPriority; + } + taskEXIT_CRITICAL(); + + return uxReturn; + } + +#endif /* INCLUDE_uxTaskPriorityGet */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_uxTaskPriorityGet == 1 ) + + UBaseType_t uxTaskPriorityGetFromISR( const TaskHandle_t xTask ) + { + TCB_t const * pxTCB; + UBaseType_t uxReturn, uxSavedInterruptState; + + /* RTOS ports that support interrupt nesting have the concept of a + * maximum system call (or maximum API call) interrupt priority. + * Interrupts that are above the maximum system call priority are keep + * permanently enabled, even when the RTOS kernel is in a critical section, + * but cannot make any calls to FreeRTOS API functions. If configASSERT() + * is defined in FreeRTOSConfig.h then + * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + * failure if a FreeRTOS API function is called from an interrupt that has + * been assigned a priority above the configured maximum system call + * priority. Only FreeRTOS functions that end in FromISR can be called + * from interrupts that have been assigned a priority at or (logically) + * below the maximum system call interrupt priority. FreeRTOS maintains a + * separate interrupt safe API to ensure interrupt entry is as fast and as + * simple as possible. More information (albeit Cortex-M specific) is + * provided on the following link: + * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + uxSavedInterruptState = portSET_INTERRUPT_MASK_FROM_ISR(); + { + /* If null is passed in here then it is the priority of the calling + * task that is being queried. */ + pxTCB = prvGetTCBFromHandle( xTask ); + uxReturn = pxTCB->uxPriority; + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptState ); + + return uxReturn; + } + +#endif /* INCLUDE_uxTaskPriorityGet */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_vTaskPrioritySet == 1 ) + + void vTaskPrioritySet( TaskHandle_t xTask, + UBaseType_t uxNewPriority ) + { + TCB_t * pxTCB; + UBaseType_t uxCurrentBasePriority, uxPriorityUsedOnEntry; + BaseType_t xYieldRequired = pdFALSE; + + configASSERT( uxNewPriority < configMAX_PRIORITIES ); + + /* Ensure the new priority is valid. */ + if( uxNewPriority >= ( UBaseType_t ) configMAX_PRIORITIES ) + { + uxNewPriority = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) 1U; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + taskENTER_CRITICAL(); + { + /* If null is passed in here then it is the priority of the calling + * task that is being changed. */ + pxTCB = prvGetTCBFromHandle( xTask ); + + traceTASK_PRIORITY_SET( pxTCB, uxNewPriority ); + + #if ( configUSE_MUTEXES == 1 ) + { + uxCurrentBasePriority = pxTCB->uxBasePriority; + } + #else + { + uxCurrentBasePriority = pxTCB->uxPriority; + } + #endif + + if( uxCurrentBasePriority != uxNewPriority ) + { + /* The priority change may have readied a task of higher + * priority than the calling task. */ + if( uxNewPriority > uxCurrentBasePriority ) + { + if( pxTCB != pxCurrentTCB ) + { + /* The priority of a task other than the currently + * running task is being raised. Is the priority being + * raised above that of the running task? */ + if( uxNewPriority >= pxCurrentTCB->uxPriority ) + { + xYieldRequired = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* The priority of the running task is being raised, + * but the running task must already be the highest + * priority task able to run so no yield is required. */ + } + } + else if( pxTCB == pxCurrentTCB ) + { + /* Setting the priority of the running task down means + * there may now be another task of higher priority that + * is ready to execute. */ + xYieldRequired = pdTRUE; + } + else + { + /* Setting the priority of any other task down does not + * require a yield as the running task must be above the + * new priority of the task being modified. */ + } + + /* Remember the ready list the task might be referenced from + * before its uxPriority member is changed so the + * taskRESET_READY_PRIORITY() macro can function correctly. */ + uxPriorityUsedOnEntry = pxTCB->uxPriority; + + #if ( configUSE_MUTEXES == 1 ) + { + /* Only change the priority being used if the task is not + * currently using an inherited priority. */ + if( pxTCB->uxBasePriority == pxTCB->uxPriority ) + { + pxTCB->uxPriority = uxNewPriority; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* The base priority gets set whatever. */ + pxTCB->uxBasePriority = uxNewPriority; + } + #else /* if ( configUSE_MUTEXES == 1 ) */ + { + pxTCB->uxPriority = uxNewPriority; + } + #endif /* if ( configUSE_MUTEXES == 1 ) */ + + /* Only reset the event list item value if the value is not + * being used for anything else. */ + if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) + { + listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxNewPriority ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* If the task is in the blocked or suspended list we need do + * nothing more than change its priority variable. However, if + * the task is in a ready list it needs to be removed and placed + * in the list appropriate to its new priority. */ + if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE ) + { + /* The task is currently in its ready list - remove before + * adding it to its new ready list. As we are in a critical + * section we can do this even if the scheduler is suspended. */ + if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + /* It is known that the task is in its ready list so + * there is no need to check again and the port level + * reset macro can be called directly. */ + portRESET_READY_PRIORITY( uxPriorityUsedOnEntry, uxTopReadyPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + prvAddTaskToReadyList( pxTCB ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + if( xYieldRequired != pdFALSE ) + { + taskYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Remove compiler warning about unused variables when the port + * optimised task selection is not being used. */ + ( void ) uxPriorityUsedOnEntry; + } + } + taskEXIT_CRITICAL(); + } + +#endif /* INCLUDE_vTaskPrioritySet */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_vTaskSuspend == 1 ) + + void vTaskSuspend( TaskHandle_t xTaskToSuspend ) + { + TCB_t * pxTCB; + + taskENTER_CRITICAL(); + { + /* If null is passed in here then it is the running task that is + * being suspended. */ + pxTCB = prvGetTCBFromHandle( xTaskToSuspend ); + + traceTASK_SUSPEND( pxTCB ); + + /* Remove task from the ready/delayed list and place in the + * suspended list. */ + if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + taskRESET_READY_PRIORITY( pxTCB->uxPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Is the task waiting on an event also? */ + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) + { + ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + vListInsertEnd( &xSuspendedTaskList, &( pxTCB->xStateListItem ) ); + + #if ( configUSE_TASK_NOTIFICATIONS == 1 ) + { + BaseType_t x; + + for( x = 0; x < configTASK_NOTIFICATION_ARRAY_ENTRIES; x++ ) + { + if( pxTCB->ucNotifyState[ x ] == taskWAITING_NOTIFICATION ) + { + /* The task was blocked to wait for a notification, but is + * now suspended, so no notification was received. */ + pxTCB->ucNotifyState[ x ] = taskNOT_WAITING_NOTIFICATION; + } + } + } + #endif /* if ( configUSE_TASK_NOTIFICATIONS == 1 ) */ + } + taskEXIT_CRITICAL(); + + if( xSchedulerRunning != pdFALSE ) + { + /* Reset the next expected unblock time in case it referred to the + * task that is now in the Suspended state. */ + taskENTER_CRITICAL(); + { + prvResetNextTaskUnblockTime(); + } + taskEXIT_CRITICAL(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + if( pxTCB == pxCurrentTCB ) + { + if( xSchedulerRunning != pdFALSE ) + { + /* The current task has just been suspended. */ + configASSERT( uxSchedulerSuspended == 0 ); + portYIELD_WITHIN_API(); + } + else + { + /* The scheduler is not running, but the task that was pointed + * to by pxCurrentTCB has just been suspended and pxCurrentTCB + * must be adjusted to point to a different task. */ + if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == uxCurrentNumberOfTasks ) /*lint !e931 Right has no side effect, just volatile. */ + { + /* No other tasks are ready, so set pxCurrentTCB back to + * NULL so when the next task is created pxCurrentTCB will + * be set to point to it no matter what its relative priority + * is. */ + pxCurrentTCB = NULL; + } + else + { + vTaskSwitchContext(); + } + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + +#endif /* INCLUDE_vTaskSuspend */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_vTaskSuspend == 1 ) + + static BaseType_t prvTaskIsTaskSuspended( const TaskHandle_t xTask ) + { + BaseType_t xReturn = pdFALSE; + const TCB_t * const pxTCB = xTask; + + /* Accesses xPendingReadyList so must be called from a critical + * section. */ + + /* It does not make sense to check if the calling task is suspended. */ + configASSERT( xTask ); + + /* Is the task being resumed actually in the suspended list? */ + if( listIS_CONTAINED_WITHIN( &xSuspendedTaskList, &( pxTCB->xStateListItem ) ) != pdFALSE ) + { + /* Has the task already been resumed from within an ISR? */ + if( listIS_CONTAINED_WITHIN( &xPendingReadyList, &( pxTCB->xEventListItem ) ) == pdFALSE ) + { + /* Is it in the suspended list because it is in the Suspended + * state, or because is is blocked with no timeout? */ + if( listIS_CONTAINED_WITHIN( NULL, &( pxTCB->xEventListItem ) ) != pdFALSE ) /*lint !e961. The cast is only redundant when NULL is used. */ + { + xReturn = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xReturn; + } /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */ + +#endif /* INCLUDE_vTaskSuspend */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_vTaskSuspend == 1 ) + + void vTaskResume( TaskHandle_t xTaskToResume ) + { + TCB_t * const pxTCB = xTaskToResume; + + /* It does not make sense to resume the calling task. */ + configASSERT( xTaskToResume ); + + /* The parameter cannot be NULL as it is impossible to resume the + * currently executing task. */ + if( ( pxTCB != pxCurrentTCB ) && ( pxTCB != NULL ) ) + { + taskENTER_CRITICAL(); + { + if( prvTaskIsTaskSuspended( pxTCB ) != pdFALSE ) + { + traceTASK_RESUME( pxTCB ); + + /* The ready list can be accessed even if the scheduler is + * suspended because this is inside a critical section. */ + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); + + /* A higher priority task may have just been resumed. */ + if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) + { + /* This yield may not cause the task just resumed to run, + * but will leave the lists in the correct state for the + * next yield. */ + taskYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + +#endif /* INCLUDE_vTaskSuspend */ + +/*-----------------------------------------------------------*/ + +#if ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) ) + + BaseType_t xTaskResumeFromISR( TaskHandle_t xTaskToResume ) + { + BaseType_t xYieldRequired = pdFALSE; + TCB_t * const pxTCB = xTaskToResume; + UBaseType_t uxSavedInterruptStatus; + + configASSERT( xTaskToResume ); + + /* RTOS ports that support interrupt nesting have the concept of a + * maximum system call (or maximum API call) interrupt priority. + * Interrupts that are above the maximum system call priority are keep + * permanently enabled, even when the RTOS kernel is in a critical section, + * but cannot make any calls to FreeRTOS API functions. If configASSERT() + * is defined in FreeRTOSConfig.h then + * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + * failure if a FreeRTOS API function is called from an interrupt that has + * been assigned a priority above the configured maximum system call + * priority. Only FreeRTOS functions that end in FromISR can be called + * from interrupts that have been assigned a priority at or (logically) + * below the maximum system call interrupt priority. FreeRTOS maintains a + * separate interrupt safe API to ensure interrupt entry is as fast and as + * simple as possible. More information (albeit Cortex-M specific) is + * provided on the following link: + * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + if( prvTaskIsTaskSuspended( pxTCB ) != pdFALSE ) + { + traceTASK_RESUME_FROM_ISR( pxTCB ); + + /* Check the ready lists can be accessed. */ + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + /* Ready lists can be accessed so move the task from the + * suspended list to the ready list directly. */ + if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) + { + xYieldRequired = pdTRUE; + + /* Mark that a yield is pending in case the user is not + * using the return value to initiate a context switch + * from the ISR using portYIELD_FROM_ISR. */ + xYieldPending = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); + } + else + { + /* The delayed or ready lists cannot be accessed so the task + * is held in the pending ready list until the scheduler is + * unsuspended. */ + vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + + return xYieldRequired; + } + +#endif /* ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) ) */ +/*-----------------------------------------------------------*/ + +void vTaskStartScheduler( void ) +{ + BaseType_t xReturn; + + /* Add the idle task at the lowest priority. */ + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + StaticTask_t * pxIdleTaskTCBBuffer = NULL; + StackType_t * pxIdleTaskStackBuffer = NULL; + uint32_t ulIdleTaskStackSize; + + /* The Idle task is created using user provided RAM - obtain the + * address of the RAM then create the idle task. */ + vApplicationGetIdleTaskMemory( &pxIdleTaskTCBBuffer, &pxIdleTaskStackBuffer, &ulIdleTaskStackSize ); + xIdleTaskHandle = xTaskCreateStatic( prvIdleTask, + configIDLE_TASK_NAME, + ulIdleTaskStackSize, + ( void * ) NULL, /*lint !e961. The cast is not redundant for all compilers. */ + portPRIVILEGE_BIT, /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */ + pxIdleTaskStackBuffer, + pxIdleTaskTCBBuffer ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */ + + if( xIdleTaskHandle != NULL ) + { + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + } + } + #else /* if ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ + { + /* The Idle task is being created using dynamically allocated RAM. */ + xReturn = xTaskCreate( prvIdleTask, + configIDLE_TASK_NAME, + configMINIMAL_STACK_SIZE, + ( void * ) NULL, + portPRIVILEGE_BIT, /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */ + &xIdleTaskHandle ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */ + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ + + #if ( configUSE_TIMERS == 1 ) + { + if( xReturn == pdPASS ) + { + xReturn = xTimerCreateTimerTask(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_TIMERS */ + + if( xReturn == pdPASS ) + { + /* freertos_tasks_c_additions_init() should only be called if the user + * definable macro FREERTOS_TASKS_C_ADDITIONS_INIT() is defined, as that is + * the only macro called by the function. */ + #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT + { + freertos_tasks_c_additions_init(); + } + #endif + + /* Interrupts are turned off here, to ensure a tick does not occur + * before or during the call to xPortStartScheduler(). The stacks of + * the created tasks contain a status word with interrupts switched on + * so interrupts will automatically get re-enabled when the first task + * starts to run. */ + portDISABLE_INTERRUPTS(); + + #if ( configUSE_NEWLIB_REENTRANT == 1 ) + { + /* Switch Newlib's _impure_ptr variable to point to the _reent + * structure specific to the task that will run first. + * See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html + * for additional information. */ + _impure_ptr = &( pxCurrentTCB->xNewLib_reent ); + } + #endif /* configUSE_NEWLIB_REENTRANT */ + + xNextTaskUnblockTime = portMAX_DELAY; + xSchedulerRunning = pdTRUE; + xTickCount = ( TickType_t ) configINITIAL_TICK_COUNT; + + /* If configGENERATE_RUN_TIME_STATS is defined then the following + * macro must be defined to configure the timer/counter used to generate + * the run time counter time base. NOTE: If configGENERATE_RUN_TIME_STATS + * is set to 0 and the following line fails to build then ensure you do not + * have portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() defined in your + * FreeRTOSConfig.h file. */ + portCONFIGURE_TIMER_FOR_RUN_TIME_STATS(); + + traceTASK_SWITCHED_IN(); + + /* Setting up the timer tick is hardware specific and thus in the + * portable interface. */ + if( xPortStartScheduler() != pdFALSE ) + { + /* Should not reach here as if the scheduler is running the + * function will not return. */ + } + else + { + /* Should only reach here if a task calls xTaskEndScheduler(). */ + } + } + else + { + /* This line will only be reached if the kernel could not be started, + * because there was not enough FreeRTOS heap to create the idle task + * or the timer task. */ + configASSERT( xReturn != errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY ); + } + + /* Prevent compiler warnings if INCLUDE_xTaskGetIdleTaskHandle is set to 0, + * meaning xIdleTaskHandle is not used anywhere else. */ + ( void ) xIdleTaskHandle; + + /* OpenOCD makes use of uxTopUsedPriority for thread debugging. Prevent uxTopUsedPriority + * from getting optimized out as it is no longer used by the kernel. */ + ( void ) uxTopUsedPriority; +} +/*-----------------------------------------------------------*/ + +void vTaskEndScheduler( void ) +{ + /* Stop the scheduler interrupts and call the portable scheduler end + * routine so the original ISRs can be restored if necessary. The port + * layer must ensure interrupts enable bit is left in the correct state. */ + portDISABLE_INTERRUPTS(); + xSchedulerRunning = pdFALSE; + vPortEndScheduler(); +} +/*----------------------------------------------------------*/ + +void vTaskSuspendAll( void ) +{ + /* A critical section is not required as the variable is of type + * BaseType_t. Please read Richard Barry's reply in the following link to a + * post in the FreeRTOS support forum before reporting this as a bug! - + * https://goo.gl/wu4acr */ + + /* portSOFTWARE_BARRIER() is only implemented for emulated/simulated ports that + * do not otherwise exhibit real time behaviour. */ + portSOFTWARE_BARRIER(); + + /* The scheduler is suspended if uxSchedulerSuspended is non-zero. An increment + * is used to allow calls to vTaskSuspendAll() to nest. */ + ++uxSchedulerSuspended; + + /* Enforces ordering for ports and optimised compilers that may otherwise place + * the above increment elsewhere. */ + portMEMORY_BARRIER(); +} +/*----------------------------------------------------------*/ + +#if ( configUSE_TICKLESS_IDLE != 0 ) + + static TickType_t prvGetExpectedIdleTime( void ) + { + TickType_t xReturn; + UBaseType_t uxHigherPriorityReadyTasks = pdFALSE; + + /* uxHigherPriorityReadyTasks takes care of the case where + * configUSE_PREEMPTION is 0, so there may be tasks above the idle priority + * task that are in the Ready state, even though the idle task is + * running. */ + #if ( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 ) + { + if( uxTopReadyPriority > tskIDLE_PRIORITY ) + { + uxHigherPriorityReadyTasks = pdTRUE; + } + } + #else + { + const UBaseType_t uxLeastSignificantBit = ( UBaseType_t ) 0x01; + + /* When port optimised task selection is used the uxTopReadyPriority + * variable is used as a bit map. If bits other than the least + * significant bit are set then there are tasks that have a priority + * above the idle priority that are in the Ready state. This takes + * care of the case where the co-operative scheduler is in use. */ + if( uxTopReadyPriority > uxLeastSignificantBit ) + { + uxHigherPriorityReadyTasks = pdTRUE; + } + } + #endif /* if ( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 ) */ + + if( pxCurrentTCB->uxPriority > tskIDLE_PRIORITY ) + { + xReturn = 0; + } + else if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > 1 ) + { + /* There are other idle priority tasks in the ready state. If + * time slicing is used then the very next tick interrupt must be + * processed. */ + xReturn = 0; + } + else if( uxHigherPriorityReadyTasks != pdFALSE ) + { + /* There are tasks in the Ready state that have a priority above the + * idle priority. This path can only be reached if + * configUSE_PREEMPTION is 0. */ + xReturn = 0; + } + else + { + xReturn = xNextTaskUnblockTime - xTickCount; + } + + return xReturn; + } + +#endif /* configUSE_TICKLESS_IDLE */ +/*----------------------------------------------------------*/ + +BaseType_t xTaskResumeAll( void ) +{ + TCB_t * pxTCB = NULL; + BaseType_t xAlreadyYielded = pdFALSE; + + /* If uxSchedulerSuspended is zero then this function does not match a + * previous call to vTaskSuspendAll(). */ + configASSERT( uxSchedulerSuspended ); + + /* It is possible that an ISR caused a task to be removed from an event + * list while the scheduler was suspended. If this was the case then the + * removed task will have been added to the xPendingReadyList. Once the + * scheduler has been resumed it is safe to move all the pending ready + * tasks from this list into their appropriate ready list. */ + taskENTER_CRITICAL(); + { + --uxSchedulerSuspended; + + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + if( uxCurrentNumberOfTasks > ( UBaseType_t ) 0U ) + { + /* Move any readied tasks from the pending list into the + * appropriate ready list. */ + while( listLIST_IS_EMPTY( &xPendingReadyList ) == pdFALSE ) + { + pxTCB = listGET_OWNER_OF_HEAD_ENTRY( ( &xPendingReadyList ) ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + listREMOVE_ITEM( &( pxTCB->xEventListItem ) ); + portMEMORY_BARRIER(); + listREMOVE_ITEM( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); + + /* If the moved task has a priority higher than or equal to + * the current task then a yield must be performed. */ + if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) + { + xYieldPending = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + if( pxTCB != NULL ) + { + /* A task was unblocked while the scheduler was suspended, + * which may have prevented the next unblock time from being + * re-calculated, in which case re-calculate it now. Mainly + * important for low power tickless implementations, where + * this can prevent an unnecessary exit from low power + * state. */ + prvResetNextTaskUnblockTime(); + } + + /* If any ticks occurred while the scheduler was suspended then + * they should be processed now. This ensures the tick count does + * not slip, and that any delayed tasks are resumed at the correct + * time. */ + { + TickType_t xPendedCounts = xPendedTicks; /* Non-volatile copy. */ + + if( xPendedCounts > ( TickType_t ) 0U ) + { + do + { + if( xTaskIncrementTick() != pdFALSE ) + { + xYieldPending = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + --xPendedCounts; + } while( xPendedCounts > ( TickType_t ) 0U ); + + xPendedTicks = 0; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + if( xYieldPending != pdFALSE ) + { + #if ( configUSE_PREEMPTION != 0 ) + { + xAlreadyYielded = pdTRUE; + } + #endif + taskYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + + return xAlreadyYielded; +} +/*-----------------------------------------------------------*/ + +TickType_t xTaskGetTickCount( void ) +{ + TickType_t xTicks; + + /* Critical section required if running on a 16 bit processor. */ + portTICK_TYPE_ENTER_CRITICAL(); + { + xTicks = xTickCount; + } + portTICK_TYPE_EXIT_CRITICAL(); + + return xTicks; +} +/*-----------------------------------------------------------*/ + +TickType_t xTaskGetTickCountFromISR( void ) +{ + TickType_t xReturn; + UBaseType_t uxSavedInterruptStatus; + + /* RTOS ports that support interrupt nesting have the concept of a maximum + * system call (or maximum API call) interrupt priority. Interrupts that are + * above the maximum system call priority are kept permanently enabled, even + * when the RTOS kernel is in a critical section, but cannot make any calls to + * FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h + * then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + * failure if a FreeRTOS API function is called from an interrupt that has been + * assigned a priority above the configured maximum system call priority. + * Only FreeRTOS functions that end in FromISR can be called from interrupts + * that have been assigned a priority at or (logically) below the maximum + * system call interrupt priority. FreeRTOS maintains a separate interrupt + * safe API to ensure interrupt entry is as fast and as simple as possible. + * More information (albeit Cortex-M specific) is provided on the following + * link: https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + uxSavedInterruptStatus = portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR(); + { + xReturn = xTickCount; + } + portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +UBaseType_t uxTaskGetNumberOfTasks( void ) +{ + /* A critical section is not required because the variables are of type + * BaseType_t. */ + return uxCurrentNumberOfTasks; +} +/*-----------------------------------------------------------*/ + +char * pcTaskGetName( TaskHandle_t xTaskToQuery ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ +{ + TCB_t * pxTCB; + + /* If null is passed in here then the name of the calling task is being + * queried. */ + pxTCB = prvGetTCBFromHandle( xTaskToQuery ); + configASSERT( pxTCB ); + return &( pxTCB->pcTaskName[ 0 ] ); +} +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_xTaskGetHandle == 1 ) + + static TCB_t * prvSearchForNameWithinSingleList( List_t * pxList, + const char pcNameToQuery[] ) + { + TCB_t * pxNextTCB, * pxFirstTCB, * pxReturn = NULL; + UBaseType_t x; + char cNextChar; + BaseType_t xBreakLoop; + + /* This function is called with the scheduler suspended. */ + + if( listCURRENT_LIST_LENGTH( pxList ) > ( UBaseType_t ) 0 ) + { + listGET_OWNER_OF_NEXT_ENTRY( pxFirstTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + + do + { + listGET_OWNER_OF_NEXT_ENTRY( pxNextTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + + /* Check each character in the name looking for a match or + * mismatch. */ + xBreakLoop = pdFALSE; + + for( x = ( UBaseType_t ) 0; x < ( UBaseType_t ) configMAX_TASK_NAME_LEN; x++ ) + { + cNextChar = pxNextTCB->pcTaskName[ x ]; + + if( cNextChar != pcNameToQuery[ x ] ) + { + /* Characters didn't match. */ + xBreakLoop = pdTRUE; + } + else if( cNextChar == ( char ) 0x00 ) + { + /* Both strings terminated, a match must have been + * found. */ + pxReturn = pxNextTCB; + xBreakLoop = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + if( xBreakLoop != pdFALSE ) + { + break; + } + } + + if( pxReturn != NULL ) + { + /* The handle has been found. */ + break; + } + } while( pxNextTCB != pxFirstTCB ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return pxReturn; + } + +#endif /* INCLUDE_xTaskGetHandle */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_xTaskGetHandle == 1 ) + + TaskHandle_t xTaskGetHandle( const char * pcNameToQuery ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + { + UBaseType_t uxQueue = configMAX_PRIORITIES; + TCB_t * pxTCB; + + /* Task names will be truncated to configMAX_TASK_NAME_LEN - 1 bytes. */ + configASSERT( strlen( pcNameToQuery ) < configMAX_TASK_NAME_LEN ); + + vTaskSuspendAll(); + { + /* Search the ready lists. */ + do + { + uxQueue--; + pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) &( pxReadyTasksLists[ uxQueue ] ), pcNameToQuery ); + + if( pxTCB != NULL ) + { + /* Found the handle. */ + break; + } + } while( uxQueue > ( UBaseType_t ) tskIDLE_PRIORITY ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + + /* Search the delayed lists. */ + if( pxTCB == NULL ) + { + pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) pxDelayedTaskList, pcNameToQuery ); + } + + if( pxTCB == NULL ) + { + pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) pxOverflowDelayedTaskList, pcNameToQuery ); + } + + #if ( INCLUDE_vTaskSuspend == 1 ) + { + if( pxTCB == NULL ) + { + /* Search the suspended list. */ + pxTCB = prvSearchForNameWithinSingleList( &xSuspendedTaskList, pcNameToQuery ); + } + } + #endif + + #if ( INCLUDE_vTaskDelete == 1 ) + { + if( pxTCB == NULL ) + { + /* Search the deleted list. */ + pxTCB = prvSearchForNameWithinSingleList( &xTasksWaitingTermination, pcNameToQuery ); + } + } + #endif + } + ( void ) xTaskResumeAll(); + + return pxTCB; + } + +#endif /* INCLUDE_xTaskGetHandle */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + UBaseType_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, + const UBaseType_t uxArraySize, + configRUN_TIME_COUNTER_TYPE * const pulTotalRunTime ) + { + UBaseType_t uxTask = 0, uxQueue = configMAX_PRIORITIES; + + vTaskSuspendAll(); + { + /* Is there a space in the array for each task in the system? */ + if( uxArraySize >= uxCurrentNumberOfTasks ) + { + /* Fill in an TaskStatus_t structure with information on each + * task in the Ready state. */ + do + { + uxQueue--; + uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &( pxReadyTasksLists[ uxQueue ] ), eReady ); + } while( uxQueue > ( UBaseType_t ) tskIDLE_PRIORITY ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + + /* Fill in an TaskStatus_t structure with information on each + * task in the Blocked state. */ + uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), ( List_t * ) pxDelayedTaskList, eBlocked ); + uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), ( List_t * ) pxOverflowDelayedTaskList, eBlocked ); + + #if ( INCLUDE_vTaskDelete == 1 ) + { + /* Fill in an TaskStatus_t structure with information on + * each task that has been deleted but not yet cleaned up. */ + uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &xTasksWaitingTermination, eDeleted ); + } + #endif + + #if ( INCLUDE_vTaskSuspend == 1 ) + { + /* Fill in an TaskStatus_t structure with information on + * each task in the Suspended state. */ + uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &xSuspendedTaskList, eSuspended ); + } + #endif + + #if ( configGENERATE_RUN_TIME_STATS == 1 ) + { + if( pulTotalRunTime != NULL ) + { + #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE + portALT_GET_RUN_TIME_COUNTER_VALUE( ( *pulTotalRunTime ) ); + #else + *pulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE(); + #endif + } + } + #else /* if ( configGENERATE_RUN_TIME_STATS == 1 ) */ + { + if( pulTotalRunTime != NULL ) + { + *pulTotalRunTime = 0; + } + } + #endif /* if ( configGENERATE_RUN_TIME_STATS == 1 ) */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + ( void ) xTaskResumeAll(); + + return uxTask; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*----------------------------------------------------------*/ + +#if ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) + + TaskHandle_t xTaskGetIdleTaskHandle( void ) + { + /* If xTaskGetIdleTaskHandle() is called before the scheduler has been + * started, then xIdleTaskHandle will be NULL. */ + configASSERT( ( xIdleTaskHandle != NULL ) ); + return xIdleTaskHandle; + } + +#endif /* INCLUDE_xTaskGetIdleTaskHandle */ +/*----------------------------------------------------------*/ + +/* This conditional compilation should use inequality to 0, not equality to 1. + * This is to ensure vTaskStepTick() is available when user defined low power mode + * implementations require configUSE_TICKLESS_IDLE to be set to a value other than + * 1. */ +#if ( configUSE_TICKLESS_IDLE != 0 ) + + void vTaskStepTick( const TickType_t xTicksToJump ) + { + /* Correct the tick count value after a period during which the tick + * was suppressed. Note this does *not* call the tick hook function for + * each stepped tick. */ + configASSERT( ( xTickCount + xTicksToJump ) <= xNextTaskUnblockTime ); + xTickCount += xTicksToJump; + traceINCREASE_TICK_COUNT( xTicksToJump ); + } + +#endif /* configUSE_TICKLESS_IDLE */ +/*----------------------------------------------------------*/ + +BaseType_t xTaskCatchUpTicks( TickType_t xTicksToCatchUp ) +{ + BaseType_t xYieldOccurred; + + /* Must not be called with the scheduler suspended as the implementation + * relies on xPendedTicks being wound down to 0 in xTaskResumeAll(). */ + configASSERT( uxSchedulerSuspended == 0 ); + + /* Use xPendedTicks to mimic xTicksToCatchUp number of ticks occurring when + * the scheduler is suspended so the ticks are executed in xTaskResumeAll(). */ + vTaskSuspendAll(); + xPendedTicks += xTicksToCatchUp; + xYieldOccurred = xTaskResumeAll(); + + return xYieldOccurred; +} +/*----------------------------------------------------------*/ + +#if ( INCLUDE_xTaskAbortDelay == 1 ) + + BaseType_t xTaskAbortDelay( TaskHandle_t xTask ) + { + TCB_t * pxTCB = xTask; + BaseType_t xReturn; + + configASSERT( pxTCB ); + + vTaskSuspendAll(); + { + /* A task can only be prematurely removed from the Blocked state if + * it is actually in the Blocked state. */ + if( eTaskGetState( xTask ) == eBlocked ) + { + xReturn = pdPASS; + + /* Remove the reference to the task from the blocked list. An + * interrupt won't touch the xStateListItem because the + * scheduler is suspended. */ + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + + /* Is the task waiting on an event also? If so remove it from + * the event list too. Interrupts can touch the event list item, + * even though the scheduler is suspended, so a critical section + * is used. */ + taskENTER_CRITICAL(); + { + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) + { + ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); + + /* This lets the task know it was forcibly removed from the + * blocked state so it should not re-evaluate its block time and + * then block again. */ + pxTCB->ucDelayAborted = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + + /* Place the unblocked task into the appropriate ready list. */ + prvAddTaskToReadyList( pxTCB ); + + /* A task being unblocked cannot cause an immediate context + * switch if preemption is turned off. */ + #if ( configUSE_PREEMPTION == 1 ) + { + /* Preemption is on, but a context switch should only be + * performed if the unblocked task has a priority that is + * higher than the currently executing task. */ + if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* Pend the yield to be performed when the scheduler + * is unsuspended. */ + xYieldPending = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_PREEMPTION */ + } + else + { + xReturn = pdFAIL; + } + } + ( void ) xTaskResumeAll(); + + return xReturn; + } + +#endif /* INCLUDE_xTaskAbortDelay */ +/*----------------------------------------------------------*/ + +BaseType_t xTaskIncrementTick( void ) +{ + TCB_t * pxTCB; + TickType_t xItemValue; + BaseType_t xSwitchRequired = pdFALSE; + + /* Called by the portable layer each time a tick interrupt occurs. + * Increments the tick then checks to see if the new tick value will cause any + * tasks to be unblocked. */ + traceTASK_INCREMENT_TICK( xTickCount ); + + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + /* Minor optimisation. The tick count cannot change in this + * block. */ + const TickType_t xConstTickCount = xTickCount + ( TickType_t ) 1; + + /* Increment the RTOS tick, switching the delayed and overflowed + * delayed lists if it wraps to 0. */ + xTickCount = xConstTickCount; + + if( xConstTickCount == ( TickType_t ) 0U ) /*lint !e774 'if' does not always evaluate to false as it is looking for an overflow. */ + { + taskSWITCH_DELAYED_LISTS(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* See if this tick has made a timeout expire. Tasks are stored in + * the queue in the order of their wake time - meaning once one task + * has been found whose block time has not expired there is no need to + * look any further down the list. */ + if( xConstTickCount >= xNextTaskUnblockTime ) + { + for( ; ; ) + { + if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE ) + { + /* The delayed list is empty. Set xNextTaskUnblockTime + * to the maximum possible value so it is extremely + * unlikely that the + * if( xTickCount >= xNextTaskUnblockTime ) test will pass + * next time through. */ + xNextTaskUnblockTime = portMAX_DELAY; /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + break; + } + else + { + /* The delayed list is not empty, get the value of the + * item at the head of the delayed list. This is the time + * at which the task at the head of the delayed list must + * be removed from the Blocked state. */ + pxTCB = listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + xItemValue = listGET_LIST_ITEM_VALUE( &( pxTCB->xStateListItem ) ); + + if( xConstTickCount < xItemValue ) + { + /* It is not time to unblock this item yet, but the + * item value is the time at which the task at the head + * of the blocked list must be removed from the Blocked + * state - so record the item value in + * xNextTaskUnblockTime. */ + xNextTaskUnblockTime = xItemValue; + break; /*lint !e9011 Code structure here is deemed easier to understand with multiple breaks. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* It is time to remove the item from the Blocked state. */ + listREMOVE_ITEM( &( pxTCB->xStateListItem ) ); + + /* Is the task waiting on an event also? If so remove + * it from the event list. */ + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) + { + listREMOVE_ITEM( &( pxTCB->xEventListItem ) ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Place the unblocked task into the appropriate ready + * list. */ + prvAddTaskToReadyList( pxTCB ); + + /* A task being unblocked cannot cause an immediate + * context switch if preemption is turned off. */ + #if ( configUSE_PREEMPTION == 1 ) + { + /* Preemption is on, but a context switch should + * only be performed if the unblocked task has a + * priority that is equal to or higher than the + * currently executing task. */ + if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) + { + xSwitchRequired = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_PREEMPTION */ + } + } + } + + /* Tasks of equal priority to the currently running task will share + * processing time (time slice) if preemption is on, and the application + * writer has not explicitly turned time slicing off. */ + #if ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) ) + { + if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ pxCurrentTCB->uxPriority ] ) ) > ( UBaseType_t ) 1 ) + { + xSwitchRequired = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) ) */ + + #if ( configUSE_TICK_HOOK == 1 ) + { + /* Guard against the tick hook being called when the pended tick + * count is being unwound (when the scheduler is being unlocked). */ + if( xPendedTicks == ( TickType_t ) 0 ) + { + vApplicationTickHook(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_TICK_HOOK */ + + #if ( configUSE_PREEMPTION == 1 ) + { + if( xYieldPending != pdFALSE ) + { + xSwitchRequired = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_PREEMPTION */ + } + else + { + ++xPendedTicks; + + /* The tick hook gets called at regular intervals, even if the + * scheduler is locked. */ + #if ( configUSE_TICK_HOOK == 1 ) + { + vApplicationTickHook(); + } + #endif + } + + return xSwitchRequired; +} +/*-----------------------------------------------------------*/ + +#if ( configUSE_APPLICATION_TASK_TAG == 1 ) + + void vTaskSetApplicationTaskTag( TaskHandle_t xTask, + TaskHookFunction_t pxHookFunction ) + { + TCB_t * xTCB; + + /* If xTask is NULL then it is the task hook of the calling task that is + * getting set. */ + if( xTask == NULL ) + { + xTCB = ( TCB_t * ) pxCurrentTCB; + } + else + { + xTCB = xTask; + } + + /* Save the hook function in the TCB. A critical section is required as + * the value can be accessed from an interrupt. */ + taskENTER_CRITICAL(); + { + xTCB->pxTaskTag = pxHookFunction; + } + taskEXIT_CRITICAL(); + } + +#endif /* configUSE_APPLICATION_TASK_TAG */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_APPLICATION_TASK_TAG == 1 ) + + TaskHookFunction_t xTaskGetApplicationTaskTag( TaskHandle_t xTask ) + { + TCB_t * pxTCB; + TaskHookFunction_t xReturn; + + /* If xTask is NULL then set the calling task's hook. */ + pxTCB = prvGetTCBFromHandle( xTask ); + + /* Save the hook function in the TCB. A critical section is required as + * the value can be accessed from an interrupt. */ + taskENTER_CRITICAL(); + { + xReturn = pxTCB->pxTaskTag; + } + taskEXIT_CRITICAL(); + + return xReturn; + } + +#endif /* configUSE_APPLICATION_TASK_TAG */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_APPLICATION_TASK_TAG == 1 ) + + TaskHookFunction_t xTaskGetApplicationTaskTagFromISR( TaskHandle_t xTask ) + { + TCB_t * pxTCB; + TaskHookFunction_t xReturn; + UBaseType_t uxSavedInterruptStatus; + + /* If xTask is NULL then set the calling task's hook. */ + pxTCB = prvGetTCBFromHandle( xTask ); + + /* Save the hook function in the TCB. A critical section is required as + * the value can be accessed from an interrupt. */ + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + xReturn = pxTCB->pxTaskTag; + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + + return xReturn; + } + +#endif /* configUSE_APPLICATION_TASK_TAG */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_APPLICATION_TASK_TAG == 1 ) + + BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask, + void * pvParameter ) + { + TCB_t * xTCB; + BaseType_t xReturn; + + /* If xTask is NULL then we are calling our own task hook. */ + if( xTask == NULL ) + { + xTCB = pxCurrentTCB; + } + else + { + xTCB = xTask; + } + + if( xTCB->pxTaskTag != NULL ) + { + xReturn = xTCB->pxTaskTag( pvParameter ); + } + else + { + xReturn = pdFAIL; + } + + return xReturn; + } + +#endif /* configUSE_APPLICATION_TASK_TAG */ +/*-----------------------------------------------------------*/ + +void vTaskSwitchContext( void ) +{ + if( uxSchedulerSuspended != ( UBaseType_t ) pdFALSE ) + { + /* The scheduler is currently suspended - do not allow a context + * switch. */ + xYieldPending = pdTRUE; + } + else + { + xYieldPending = pdFALSE; + traceTASK_SWITCHED_OUT(); + + #if ( configGENERATE_RUN_TIME_STATS == 1 ) + { + #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE + portALT_GET_RUN_TIME_COUNTER_VALUE( ulTotalRunTime ); + #else + ulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE(); + #endif + + /* Add the amount of time the task has been running to the + * accumulated time so far. The time the task started running was + * stored in ulTaskSwitchedInTime. Note that there is no overflow + * protection here so count values are only valid until the timer + * overflows. The guard against negative values is to protect + * against suspect run time stat counter implementations - which + * are provided by the application, not the kernel. */ + if( ulTotalRunTime > ulTaskSwitchedInTime ) + { + pxCurrentTCB->ulRunTimeCounter += ( ulTotalRunTime - ulTaskSwitchedInTime ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + ulTaskSwitchedInTime = ulTotalRunTime; + } + #endif /* configGENERATE_RUN_TIME_STATS */ + + /* Check for stack overflow, if configured. */ + taskCHECK_FOR_STACK_OVERFLOW(); + + /* Before the currently running task is switched out, save its errno. */ + #if ( configUSE_POSIX_ERRNO == 1 ) + { + pxCurrentTCB->iTaskErrno = FreeRTOS_errno; + } + #endif + + /* Select a new task to run using either the generic C or port + * optimised asm code. */ + taskSELECT_HIGHEST_PRIORITY_TASK(); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + traceTASK_SWITCHED_IN(); + + /* After the new task is switched in, update the global errno. */ + #if ( configUSE_POSIX_ERRNO == 1 ) + { + FreeRTOS_errno = pxCurrentTCB->iTaskErrno; + } + #endif + + #if ( configUSE_NEWLIB_REENTRANT == 1 ) + { + /* Switch Newlib's _impure_ptr variable to point to the _reent + * structure specific to this task. + * See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html + * for additional information. */ + _impure_ptr = &( pxCurrentTCB->xNewLib_reent ); + } + #endif /* configUSE_NEWLIB_REENTRANT */ + } +} +/*-----------------------------------------------------------*/ + +void vTaskPlaceOnEventList( List_t * const pxEventList, + const TickType_t xTicksToWait ) +{ + configASSERT( pxEventList ); + + /* THIS FUNCTION MUST BE CALLED WITH EITHER INTERRUPTS DISABLED OR THE + * SCHEDULER SUSPENDED AND THE QUEUE BEING ACCESSED LOCKED. */ + + /* Place the event list item of the TCB in the appropriate event list. + * This is placed in the list in priority order so the highest priority task + * is the first to be woken by the event. + * + * Note: Lists are sorted in ascending order by ListItem_t.xItemValue. + * Normally, the xItemValue of a TCB's ListItem_t members is: + * xItemValue = ( configMAX_PRIORITIES - uxPriority ) + * Therefore, the event list is sorted in descending priority order. + * + * The queue that contains the event list is locked, preventing + * simultaneous access from interrupts. */ + vListInsert( pxEventList, &( pxCurrentTCB->xEventListItem ) ); + + prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); +} +/*-----------------------------------------------------------*/ + +void vTaskPlaceOnUnorderedEventList( List_t * pxEventList, + const TickType_t xItemValue, + const TickType_t xTicksToWait ) +{ + configASSERT( pxEventList ); + + /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by + * the event groups implementation. */ + configASSERT( uxSchedulerSuspended != 0 ); + + /* Store the item value in the event list item. It is safe to access the + * event list item here as interrupts won't access the event list item of a + * task that is not in the Blocked state. */ + listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE ); + + /* Place the event list item of the TCB at the end of the appropriate event + * list. It is safe to access the event list here because it is part of an + * event group implementation - and interrupts don't access event groups + * directly (instead they access them indirectly by pending function calls to + * the task level). */ + listINSERT_END( pxEventList, &( pxCurrentTCB->xEventListItem ) ); + + prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); +} +/*-----------------------------------------------------------*/ + +#if ( configUSE_TIMERS == 1 ) + + void vTaskPlaceOnEventListRestricted( List_t * const pxEventList, + TickType_t xTicksToWait, + const BaseType_t xWaitIndefinitely ) + { + configASSERT( pxEventList ); + + /* This function should not be called by application code hence the + * 'Restricted' in its name. It is not part of the public API. It is + * designed for use by kernel code, and has special calling requirements - + * it should be called with the scheduler suspended. */ + + + /* Place the event list item of the TCB in the appropriate event list. + * In this case it is assume that this is the only task that is going to + * be waiting on this event list, so the faster vListInsertEnd() function + * can be used in place of vListInsert. */ + listINSERT_END( pxEventList, &( pxCurrentTCB->xEventListItem ) ); + + /* If the task should block indefinitely then set the block time to a + * value that will be recognised as an indefinite delay inside the + * prvAddCurrentTaskToDelayedList() function. */ + if( xWaitIndefinitely != pdFALSE ) + { + xTicksToWait = portMAX_DELAY; + } + + traceTASK_DELAY_UNTIL( ( xTickCount + xTicksToWait ) ); + prvAddCurrentTaskToDelayedList( xTicksToWait, xWaitIndefinitely ); + } + +#endif /* configUSE_TIMERS */ +/*-----------------------------------------------------------*/ + +BaseType_t xTaskRemoveFromEventList( const List_t * const pxEventList ) +{ + TCB_t * pxUnblockedTCB; + BaseType_t xReturn; + + /* THIS FUNCTION MUST BE CALLED FROM A CRITICAL SECTION. It can also be + * called from a critical section within an ISR. */ + + /* The event list is sorted in priority order, so the first in the list can + * be removed as it is known to be the highest priority. Remove the TCB from + * the delayed list, and add it to the ready list. + * + * If an event is for a queue that is locked then this function will never + * get called - the lock count on the queue will get modified instead. This + * means exclusive access to the event list is guaranteed here. + * + * This function assumes that a check has already been made to ensure that + * pxEventList is not empty. */ + pxUnblockedTCB = listGET_OWNER_OF_HEAD_ENTRY( pxEventList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + configASSERT( pxUnblockedTCB ); + listREMOVE_ITEM( &( pxUnblockedTCB->xEventListItem ) ); + + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + listREMOVE_ITEM( &( pxUnblockedTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxUnblockedTCB ); + + #if ( configUSE_TICKLESS_IDLE != 0 ) + { + /* If a task is blocked on a kernel object then xNextTaskUnblockTime + * might be set to the blocked task's time out time. If the task is + * unblocked for a reason other than a timeout xNextTaskUnblockTime is + * normally left unchanged, because it is automatically reset to a new + * value when the tick count equals xNextTaskUnblockTime. However if + * tickless idling is used it might be more important to enter sleep mode + * at the earliest possible time - so reset xNextTaskUnblockTime here to + * ensure it is updated at the earliest possible time. */ + prvResetNextTaskUnblockTime(); + } + #endif + } + else + { + /* The delayed and ready lists cannot be accessed, so hold this task + * pending until the scheduler is resumed. */ + listINSERT_END( &( xPendingReadyList ), &( pxUnblockedTCB->xEventListItem ) ); + } + + if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* Return true if the task removed from the event list has a higher + * priority than the calling task. This allows the calling task to know if + * it should force a context switch now. */ + xReturn = pdTRUE; + + /* Mark that a yield is pending in case the user is not using the + * "xHigherPriorityTaskWoken" parameter to an ISR safe FreeRTOS function. */ + xYieldPending = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + + return xReturn; +} +/*-----------------------------------------------------------*/ + +void vTaskRemoveFromUnorderedEventList( ListItem_t * pxEventListItem, + const TickType_t xItemValue ) +{ + TCB_t * pxUnblockedTCB; + + /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by + * the event flags implementation. */ + configASSERT( uxSchedulerSuspended != pdFALSE ); + + /* Store the new item value in the event list. */ + listSET_LIST_ITEM_VALUE( pxEventListItem, xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE ); + + /* Remove the event list form the event flag. Interrupts do not access + * event flags. */ + pxUnblockedTCB = listGET_LIST_ITEM_OWNER( pxEventListItem ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + configASSERT( pxUnblockedTCB ); + listREMOVE_ITEM( pxEventListItem ); + + #if ( configUSE_TICKLESS_IDLE != 0 ) + { + /* If a task is blocked on a kernel object then xNextTaskUnblockTime + * might be set to the blocked task's time out time. If the task is + * unblocked for a reason other than a timeout xNextTaskUnblockTime is + * normally left unchanged, because it is automatically reset to a new + * value when the tick count equals xNextTaskUnblockTime. However if + * tickless idling is used it might be more important to enter sleep mode + * at the earliest possible time - so reset xNextTaskUnblockTime here to + * ensure it is updated at the earliest possible time. */ + prvResetNextTaskUnblockTime(); + } + #endif + + /* Remove the task from the delayed list and add it to the ready list. The + * scheduler is suspended so interrupts will not be accessing the ready + * lists. */ + listREMOVE_ITEM( &( pxUnblockedTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxUnblockedTCB ); + + if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* The unblocked task has a priority above that of the calling task, so + * a context switch is required. This function is called with the + * scheduler suspended so xYieldPending is set so the context switch + * occurs immediately that the scheduler is resumed (unsuspended). */ + xYieldPending = pdTRUE; + } +} +/*-----------------------------------------------------------*/ + +void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) +{ + configASSERT( pxTimeOut ); + taskENTER_CRITICAL(); + { + pxTimeOut->xOverflowCount = xNumOfOverflows; + pxTimeOut->xTimeOnEntering = xTickCount; + } + taskEXIT_CRITICAL(); +} +/*-----------------------------------------------------------*/ + +void vTaskInternalSetTimeOutState( TimeOut_t * const pxTimeOut ) +{ + /* For internal use only as it does not use a critical section. */ + pxTimeOut->xOverflowCount = xNumOfOverflows; + pxTimeOut->xTimeOnEntering = xTickCount; +} +/*-----------------------------------------------------------*/ + +BaseType_t xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, + TickType_t * const pxTicksToWait ) +{ + BaseType_t xReturn; + + configASSERT( pxTimeOut ); + configASSERT( pxTicksToWait ); + + taskENTER_CRITICAL(); + { + /* Minor optimisation. The tick count cannot change in this block. */ + const TickType_t xConstTickCount = xTickCount; + const TickType_t xElapsedTime = xConstTickCount - pxTimeOut->xTimeOnEntering; + + #if ( INCLUDE_xTaskAbortDelay == 1 ) + if( pxCurrentTCB->ucDelayAborted != ( uint8_t ) pdFALSE ) + { + /* The delay was aborted, which is not the same as a time out, + * but has the same result. */ + pxCurrentTCB->ucDelayAborted = pdFALSE; + xReturn = pdTRUE; + } + else + #endif + + #if ( INCLUDE_vTaskSuspend == 1 ) + if( *pxTicksToWait == portMAX_DELAY ) + { + /* If INCLUDE_vTaskSuspend is set to 1 and the block time + * specified is the maximum block time then the task should block + * indefinitely, and therefore never time out. */ + xReturn = pdFALSE; + } + else + #endif + + if( ( xNumOfOverflows != pxTimeOut->xOverflowCount ) && ( xConstTickCount >= pxTimeOut->xTimeOnEntering ) ) /*lint !e525 Indentation preferred as is to make code within pre-processor directives clearer. */ + { + /* The tick count is greater than the time at which + * vTaskSetTimeout() was called, but has also overflowed since + * vTaskSetTimeOut() was called. It must have wrapped all the way + * around and gone past again. This passed since vTaskSetTimeout() + * was called. */ + xReturn = pdTRUE; + *pxTicksToWait = ( TickType_t ) 0; + } + else if( xElapsedTime < *pxTicksToWait ) /*lint !e961 Explicit casting is only redundant with some compilers, whereas others require it to prevent integer conversion errors. */ + { + /* Not a genuine timeout. Adjust parameters for time remaining. */ + *pxTicksToWait -= xElapsedTime; + vTaskInternalSetTimeOutState( pxTimeOut ); + xReturn = pdFALSE; + } + else + { + *pxTicksToWait = ( TickType_t ) 0; + xReturn = pdTRUE; + } + } + taskEXIT_CRITICAL(); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +void vTaskMissedYield( void ) +{ + xYieldPending = pdTRUE; +} +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + UBaseType_t uxTaskGetTaskNumber( TaskHandle_t xTask ) + { + UBaseType_t uxReturn; + TCB_t const * pxTCB; + + if( xTask != NULL ) + { + pxTCB = xTask; + uxReturn = pxTCB->uxTaskNumber; + } + else + { + uxReturn = 0U; + } + + return uxReturn; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + void vTaskSetTaskNumber( TaskHandle_t xTask, + const UBaseType_t uxHandle ) + { + TCB_t * pxTCB; + + if( xTask != NULL ) + { + pxTCB = xTask; + pxTCB->uxTaskNumber = uxHandle; + } + } + +#endif /* configUSE_TRACE_FACILITY */ + +/* + * ----------------------------------------------------------- + * The Idle task. + * ---------------------------------------------------------- + * + * The portTASK_FUNCTION() macro is used to allow port/compiler specific + * language extensions. The equivalent prototype for this function is: + * + * void prvIdleTask( void *pvParameters ); + * + */ +static portTASK_FUNCTION( prvIdleTask, pvParameters ) +{ + /* Stop warnings. */ + ( void ) pvParameters; + + /** THIS IS THE RTOS IDLE TASK - WHICH IS CREATED AUTOMATICALLY WHEN THE + * SCHEDULER IS STARTED. **/ + + /* In case a task that has a secure context deletes itself, in which case + * the idle task is responsible for deleting the task's secure context, if + * any. */ + portALLOCATE_SECURE_CONTEXT( configMINIMAL_SECURE_STACK_SIZE ); + + for( ; ; ) + { + /* See if any tasks have deleted themselves - if so then the idle task + * is responsible for freeing the deleted task's TCB and stack. */ + prvCheckTasksWaitingTermination(); + + #if ( configUSE_PREEMPTION == 0 ) + { + /* If we are not using preemption we keep forcing a task switch to + * see if any other task has become available. If we are using + * preemption we don't need to do this as any task becoming available + * will automatically get the processor anyway. */ + taskYIELD(); + } + #endif /* configUSE_PREEMPTION */ + + #if ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) + { + /* When using preemption tasks of equal priority will be + * timesliced. If a task that is sharing the idle priority is ready + * to run then the idle task should yield before the end of the + * timeslice. + * + * A critical region is not required here as we are just reading from + * the list, and an occasional incorrect value will not matter. If + * the ready list at the idle priority contains more than one task + * then a task other than the idle task is ready to execute. */ + if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > ( UBaseType_t ) 1 ) + { + taskYIELD(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) */ + + #if ( configUSE_IDLE_HOOK == 1 ) + { + extern void vApplicationIdleHook( void ); + + /* Call the user defined function from within the idle task. This + * allows the application designer to add background functionality + * without the overhead of a separate task. + * NOTE: vApplicationIdleHook() MUST NOT, UNDER ANY CIRCUMSTANCES, + * CALL A FUNCTION THAT MIGHT BLOCK. */ + vApplicationIdleHook(); + } + #endif /* configUSE_IDLE_HOOK */ + + /* This conditional compilation should use inequality to 0, not equality + * to 1. This is to ensure portSUPPRESS_TICKS_AND_SLEEP() is called when + * user defined low power mode implementations require + * configUSE_TICKLESS_IDLE to be set to a value other than 1. */ + #if ( configUSE_TICKLESS_IDLE != 0 ) + { + TickType_t xExpectedIdleTime; + + /* It is not desirable to suspend then resume the scheduler on + * each iteration of the idle task. Therefore, a preliminary + * test of the expected idle time is performed without the + * scheduler suspended. The result here is not necessarily + * valid. */ + xExpectedIdleTime = prvGetExpectedIdleTime(); + + if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP ) + { + vTaskSuspendAll(); + { + /* Now the scheduler is suspended, the expected idle + * time can be sampled again, and this time its value can + * be used. */ + configASSERT( xNextTaskUnblockTime >= xTickCount ); + xExpectedIdleTime = prvGetExpectedIdleTime(); + + /* Define the following macro to set xExpectedIdleTime to 0 + * if the application does not want + * portSUPPRESS_TICKS_AND_SLEEP() to be called. */ + configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING( xExpectedIdleTime ); + + if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP ) + { + traceLOW_POWER_IDLE_BEGIN(); + portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ); + traceLOW_POWER_IDLE_END(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + ( void ) xTaskResumeAll(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_TICKLESS_IDLE */ + } +} +/*-----------------------------------------------------------*/ + +#if ( configUSE_TICKLESS_IDLE != 0 ) + + eSleepModeStatus eTaskConfirmSleepModeStatus( void ) + { + /* The idle task exists in addition to the application tasks. */ + const UBaseType_t uxNonApplicationTasks = 1; + eSleepModeStatus eReturn = eStandardSleep; + + /* This function must be called from a critical section. */ + + if( listCURRENT_LIST_LENGTH( &xPendingReadyList ) != 0 ) + { + /* A task was made ready while the scheduler was suspended. */ + eReturn = eAbortSleep; + } + else if( xYieldPending != pdFALSE ) + { + /* A yield was pended while the scheduler was suspended. */ + eReturn = eAbortSleep; + } + else if( xPendedTicks != 0 ) + { + /* A tick interrupt has already occurred but was held pending + * because the scheduler is suspended. */ + eReturn = eAbortSleep; + } + else + { + /* If all the tasks are in the suspended list (which might mean they + * have an infinite block time rather than actually being suspended) + * then it is safe to turn all clocks off and just wait for external + * interrupts. */ + if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == ( uxCurrentNumberOfTasks - uxNonApplicationTasks ) ) + { + eReturn = eNoTasksWaitingTimeout; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + return eReturn; + } + +#endif /* configUSE_TICKLESS_IDLE */ +/*-----------------------------------------------------------*/ + +#if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) + + void vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, + BaseType_t xIndex, + void * pvValue ) + { + TCB_t * pxTCB; + + if( xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS ) + { + pxTCB = prvGetTCBFromHandle( xTaskToSet ); + configASSERT( pxTCB != NULL ); + pxTCB->pvThreadLocalStoragePointers[ xIndex ] = pvValue; + } + } + +#endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS */ +/*-----------------------------------------------------------*/ + +#if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) + + void * pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, + BaseType_t xIndex ) + { + void * pvReturn = NULL; + TCB_t * pxTCB; + + if( xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS ) + { + pxTCB = prvGetTCBFromHandle( xTaskToQuery ); + pvReturn = pxTCB->pvThreadLocalStoragePointers[ xIndex ]; + } + else + { + pvReturn = NULL; + } + + return pvReturn; + } + +#endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS */ +/*-----------------------------------------------------------*/ + +#if ( portUSING_MPU_WRAPPERS == 1 ) + + void vTaskAllocateMPURegions( TaskHandle_t xTaskToModify, + const MemoryRegion_t * const xRegions ) + { + TCB_t * pxTCB; + + /* If null is passed in here then we are modifying the MPU settings of + * the calling task. */ + pxTCB = prvGetTCBFromHandle( xTaskToModify ); + + vPortStoreTaskMPUSettings( &( pxTCB->xMPUSettings ), xRegions, NULL, 0 ); + } + +#endif /* portUSING_MPU_WRAPPERS */ +/*-----------------------------------------------------------*/ + +static void prvInitialiseTaskLists( void ) +{ + UBaseType_t uxPriority; + + for( uxPriority = ( UBaseType_t ) 0U; uxPriority < ( UBaseType_t ) configMAX_PRIORITIES; uxPriority++ ) + { + vListInitialise( &( pxReadyTasksLists[ uxPriority ] ) ); + } + + vListInitialise( &xDelayedTaskList1 ); + vListInitialise( &xDelayedTaskList2 ); + vListInitialise( &xPendingReadyList ); + + #if ( INCLUDE_vTaskDelete == 1 ) + { + vListInitialise( &xTasksWaitingTermination ); + } + #endif /* INCLUDE_vTaskDelete */ + + #if ( INCLUDE_vTaskSuspend == 1 ) + { + vListInitialise( &xSuspendedTaskList ); + } + #endif /* INCLUDE_vTaskSuspend */ + + /* Start with pxDelayedTaskList using list1 and the pxOverflowDelayedTaskList + * using list2. */ + pxDelayedTaskList = &xDelayedTaskList1; + pxOverflowDelayedTaskList = &xDelayedTaskList2; +} +/*-----------------------------------------------------------*/ + +static void prvCheckTasksWaitingTermination( void ) +{ + /** THIS FUNCTION IS CALLED FROM THE RTOS IDLE TASK **/ + + #if ( INCLUDE_vTaskDelete == 1 ) + { + TCB_t * pxTCB; + + /* uxDeletedTasksWaitingCleanUp is used to prevent taskENTER_CRITICAL() + * being called too often in the idle task. */ + while( uxDeletedTasksWaitingCleanUp > ( UBaseType_t ) 0U ) + { + taskENTER_CRITICAL(); + { + pxTCB = listGET_OWNER_OF_HEAD_ENTRY( ( &xTasksWaitingTermination ) ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + --uxCurrentNumberOfTasks; + --uxDeletedTasksWaitingCleanUp; + } + taskEXIT_CRITICAL(); + + prvDeleteTCB( pxTCB ); + } + } + #endif /* INCLUDE_vTaskDelete */ +} +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + void vTaskGetInfo( TaskHandle_t xTask, + TaskStatus_t * pxTaskStatus, + BaseType_t xGetFreeStackSpace, + eTaskState eState ) + { + TCB_t * pxTCB; + + /* xTask is NULL then get the state of the calling task. */ + pxTCB = prvGetTCBFromHandle( xTask ); + + pxTaskStatus->xHandle = ( TaskHandle_t ) pxTCB; + pxTaskStatus->pcTaskName = ( const char * ) &( pxTCB->pcTaskName[ 0 ] ); + pxTaskStatus->uxCurrentPriority = pxTCB->uxPriority; + pxTaskStatus->pxStackBase = pxTCB->pxStack; + pxTaskStatus->xTaskNumber = pxTCB->uxTCBNumber; + + #if ( configUSE_MUTEXES == 1 ) + { + pxTaskStatus->uxBasePriority = pxTCB->uxBasePriority; + } + #else + { + pxTaskStatus->uxBasePriority = 0; + } + #endif + + #if ( configGENERATE_RUN_TIME_STATS == 1 ) + { + pxTaskStatus->ulRunTimeCounter = pxTCB->ulRunTimeCounter; + } + #else + { + pxTaskStatus->ulRunTimeCounter = ( configRUN_TIME_COUNTER_TYPE ) 0; + } + #endif + + /* Obtaining the task state is a little fiddly, so is only done if the + * value of eState passed into this function is eInvalid - otherwise the + * state is just set to whatever is passed in. */ + if( eState != eInvalid ) + { + if( pxTCB == pxCurrentTCB ) + { + pxTaskStatus->eCurrentState = eRunning; + } + else + { + pxTaskStatus->eCurrentState = eState; + + #if ( INCLUDE_vTaskSuspend == 1 ) + { + /* If the task is in the suspended list then there is a + * chance it is actually just blocked indefinitely - so really + * it should be reported as being in the Blocked state. */ + if( eState == eSuspended ) + { + vTaskSuspendAll(); + { + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) + { + pxTaskStatus->eCurrentState = eBlocked; + } + } + ( void ) xTaskResumeAll(); + } + } + #endif /* INCLUDE_vTaskSuspend */ + } + } + else + { + pxTaskStatus->eCurrentState = eTaskGetState( pxTCB ); + } + + /* Obtaining the stack space takes some time, so the xGetFreeStackSpace + * parameter is provided to allow it to be skipped. */ + if( xGetFreeStackSpace != pdFALSE ) + { + #if ( portSTACK_GROWTH > 0 ) + { + pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace( ( uint8_t * ) pxTCB->pxEndOfStack ); + } + #else + { + pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace( ( uint8_t * ) pxTCB->pxStack ); + } + #endif + } + else + { + pxTaskStatus->usStackHighWaterMark = 0; + } + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + static UBaseType_t prvListTasksWithinSingleList( TaskStatus_t * pxTaskStatusArray, + List_t * pxList, + eTaskState eState ) + { + configLIST_VOLATILE TCB_t * pxNextTCB, * pxFirstTCB; + UBaseType_t uxTask = 0; + + if( listCURRENT_LIST_LENGTH( pxList ) > ( UBaseType_t ) 0 ) + { + listGET_OWNER_OF_NEXT_ENTRY( pxFirstTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + + /* Populate an TaskStatus_t structure within the + * pxTaskStatusArray array for each task that is referenced from + * pxList. See the definition of TaskStatus_t in task.h for the + * meaning of each TaskStatus_t structure member. */ + do + { + listGET_OWNER_OF_NEXT_ENTRY( pxNextTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + vTaskGetInfo( ( TaskHandle_t ) pxNextTCB, &( pxTaskStatusArray[ uxTask ] ), pdTRUE, eState ); + uxTask++; + } while( pxNextTCB != pxFirstTCB ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return uxTask; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) ) + + static configSTACK_DEPTH_TYPE prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte ) + { + uint32_t ulCount = 0U; + + while( *pucStackByte == ( uint8_t ) tskSTACK_FILL_BYTE ) + { + pucStackByte -= portSTACK_GROWTH; + ulCount++; + } + + ulCount /= ( uint32_t ) sizeof( StackType_t ); /*lint !e961 Casting is not redundant on smaller architectures. */ + + return ( configSTACK_DEPTH_TYPE ) ulCount; + } + +#endif /* ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) + +/* uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the + * same except for their return type. Using configSTACK_DEPTH_TYPE allows the + * user to determine the return type. It gets around the problem of the value + * overflowing on 8-bit types without breaking backward compatibility for + * applications that expect an 8-bit return type. */ + configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2( TaskHandle_t xTask ) + { + TCB_t * pxTCB; + uint8_t * pucEndOfStack; + configSTACK_DEPTH_TYPE uxReturn; + + /* uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are + * the same except for their return type. Using configSTACK_DEPTH_TYPE + * allows the user to determine the return type. It gets around the + * problem of the value overflowing on 8-bit types without breaking + * backward compatibility for applications that expect an 8-bit return + * type. */ + + pxTCB = prvGetTCBFromHandle( xTask ); + + #if portSTACK_GROWTH < 0 + { + pucEndOfStack = ( uint8_t * ) pxTCB->pxStack; + } + #else + { + pucEndOfStack = ( uint8_t * ) pxTCB->pxEndOfStack; + } + #endif + + uxReturn = prvTaskCheckFreeStackSpace( pucEndOfStack ); + + return uxReturn; + } + +#endif /* INCLUDE_uxTaskGetStackHighWaterMark2 */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) + + UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask ) + { + TCB_t * pxTCB; + uint8_t * pucEndOfStack; + UBaseType_t uxReturn; + + pxTCB = prvGetTCBFromHandle( xTask ); + + #if portSTACK_GROWTH < 0 + { + pucEndOfStack = ( uint8_t * ) pxTCB->pxStack; + } + #else + { + pucEndOfStack = ( uint8_t * ) pxTCB->pxEndOfStack; + } + #endif + + uxReturn = ( UBaseType_t ) prvTaskCheckFreeStackSpace( pucEndOfStack ); + + return uxReturn; + } + +#endif /* INCLUDE_uxTaskGetStackHighWaterMark */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_vTaskDelete == 1 ) + + static void prvDeleteTCB( TCB_t * pxTCB ) + { + /* This call is required specifically for the TriCore port. It must be + * above the vPortFree() calls. The call is also used by ports/demos that + * want to allocate and clean RAM statically. */ + portCLEAN_UP_TCB( pxTCB ); + + /* Free up the memory allocated by the scheduler for the task. It is up + * to the task to free any memory allocated at the application level. + * See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html + * for additional information. */ + #if ( configUSE_NEWLIB_REENTRANT == 1 ) + { + _reclaim_reent( &( pxTCB->xNewLib_reent ) ); + } + #endif /* configUSE_NEWLIB_REENTRANT */ + + #if ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) && ( portUSING_MPU_WRAPPERS == 0 ) ) + { + /* The task can only have been allocated dynamically - free both + * the stack and TCB. */ + vPortFreeStack( pxTCB->pxStack ); + vPortFree( pxTCB ); + } + #elif ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */ + { + /* The task could have been allocated statically or dynamically, so + * check what was statically allocated before trying to free the + * memory. */ + if( pxTCB->ucStaticallyAllocated == tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB ) + { + /* Both the stack and TCB were allocated dynamically, so both + * must be freed. */ + vPortFreeStack( pxTCB->pxStack ); + vPortFree( pxTCB ); + } + else if( pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_ONLY ) + { + /* Only the stack was statically allocated, so the TCB is the + * only memory that must be freed. */ + vPortFree( pxTCB ); + } + else + { + /* Neither the stack nor the TCB were allocated dynamically, so + * nothing needs to be freed. */ + configASSERT( pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_AND_TCB ); + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + } + +#endif /* INCLUDE_vTaskDelete */ +/*-----------------------------------------------------------*/ + +static void prvResetNextTaskUnblockTime( void ) +{ + if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE ) + { + /* The new current delayed list is empty. Set xNextTaskUnblockTime to + * the maximum possible value so it is extremely unlikely that the + * if( xTickCount >= xNextTaskUnblockTime ) test will pass until + * there is an item in the delayed list. */ + xNextTaskUnblockTime = portMAX_DELAY; + } + else + { + /* The new current delayed list is not empty, get the value of + * the item at the head of the delayed list. This is the time at + * which the task at the head of the delayed list should be removed + * from the Blocked state. */ + xNextTaskUnblockTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxDelayedTaskList ); + } +} +/*-----------------------------------------------------------*/ + +#if ( ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) || ( configUSE_MUTEXES == 1 ) ) + + TaskHandle_t xTaskGetCurrentTaskHandle( void ) + { + TaskHandle_t xReturn; + + /* A critical section is not required as this is not called from + * an interrupt and the current TCB will always be the same for any + * individual execution thread. */ + xReturn = pxCurrentTCB; + + return xReturn; + } + +#endif /* ( ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) || ( configUSE_MUTEXES == 1 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + + BaseType_t xTaskGetSchedulerState( void ) + { + BaseType_t xReturn; + + if( xSchedulerRunning == pdFALSE ) + { + xReturn = taskSCHEDULER_NOT_STARTED; + } + else + { + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + xReturn = taskSCHEDULER_RUNNING; + } + else + { + xReturn = taskSCHEDULER_SUSPENDED; + } + } + + return xReturn; + } + +#endif /* ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_MUTEXES == 1 ) + + BaseType_t xTaskPriorityInherit( TaskHandle_t const pxMutexHolder ) + { + TCB_t * const pxMutexHolderTCB = pxMutexHolder; + BaseType_t xReturn = pdFALSE; + + /* If the mutex was given back by an interrupt while the queue was + * locked then the mutex holder might now be NULL. _RB_ Is this still + * needed as interrupts can no longer use mutexes? */ + if( pxMutexHolder != NULL ) + { + /* If the holder of the mutex has a priority below the priority of + * the task attempting to obtain the mutex then it will temporarily + * inherit the priority of the task attempting to obtain the mutex. */ + if( pxMutexHolderTCB->uxPriority < pxCurrentTCB->uxPriority ) + { + /* Adjust the mutex holder state to account for its new + * priority. Only reset the event list item value if the value is + * not being used for anything else. */ + if( ( listGET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) + { + listSET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxCurrentTCB->uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* If the task being modified is in the ready state it will need + * to be moved into a new list. */ + if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ pxMutexHolderTCB->uxPriority ] ), &( pxMutexHolderTCB->xStateListItem ) ) != pdFALSE ) + { + if( uxListRemove( &( pxMutexHolderTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + /* It is known that the task is in its ready list so + * there is no need to check again and the port level + * reset macro can be called directly. */ + portRESET_READY_PRIORITY( pxMutexHolderTCB->uxPriority, uxTopReadyPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Inherit the priority before being moved into the new list. */ + pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority; + prvAddTaskToReadyList( pxMutexHolderTCB ); + } + else + { + /* Just inherit the priority. */ + pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority; + } + + traceTASK_PRIORITY_INHERIT( pxMutexHolderTCB, pxCurrentTCB->uxPriority ); + + /* Inheritance occurred. */ + xReturn = pdTRUE; + } + else + { + if( pxMutexHolderTCB->uxBasePriority < pxCurrentTCB->uxPriority ) + { + /* The base priority of the mutex holder is lower than the + * priority of the task attempting to take the mutex, but the + * current priority of the mutex holder is not lower than the + * priority of the task attempting to take the mutex. + * Therefore the mutex holder must have already inherited a + * priority, but inheritance would have occurred if that had + * not been the case. */ + xReturn = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xReturn; + } + +#endif /* configUSE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_MUTEXES == 1 ) + + BaseType_t xTaskPriorityDisinherit( TaskHandle_t const pxMutexHolder ) + { + TCB_t * const pxTCB = pxMutexHolder; + BaseType_t xReturn = pdFALSE; + + if( pxMutexHolder != NULL ) + { + /* A task can only have an inherited priority if it holds the mutex. + * If the mutex is held by a task then it cannot be given from an + * interrupt, and if a mutex is given by the holding task then it must + * be the running state task. */ + configASSERT( pxTCB == pxCurrentTCB ); + configASSERT( pxTCB->uxMutexesHeld ); + ( pxTCB->uxMutexesHeld )--; + + /* Has the holder of the mutex inherited the priority of another + * task? */ + if( pxTCB->uxPriority != pxTCB->uxBasePriority ) + { + /* Only disinherit if no other mutexes are held. */ + if( pxTCB->uxMutexesHeld == ( UBaseType_t ) 0 ) + { + /* A task can only have an inherited priority if it holds + * the mutex. If the mutex is held by a task then it cannot be + * given from an interrupt, and if a mutex is given by the + * holding task then it must be the running state task. Remove + * the holding task from the ready list. */ + if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + portRESET_READY_PRIORITY( pxTCB->uxPriority, uxTopReadyPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Disinherit the priority before adding the task into the + * new ready list. */ + traceTASK_PRIORITY_DISINHERIT( pxTCB, pxTCB->uxBasePriority ); + pxTCB->uxPriority = pxTCB->uxBasePriority; + + /* Reset the event list item value. It cannot be in use for + * any other purpose if this task is running, and it must be + * running to give back the mutex. */ + listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxTCB->uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + prvAddTaskToReadyList( pxTCB ); + + /* Return true to indicate that a context switch is required. + * This is only actually required in the corner case whereby + * multiple mutexes were held and the mutexes were given back + * in an order different to that in which they were taken. + * If a context switch did not occur when the first mutex was + * returned, even if a task was waiting on it, then a context + * switch should occur when the last mutex is returned whether + * a task is waiting on it or not. */ + xReturn = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xReturn; + } + +#endif /* configUSE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_MUTEXES == 1 ) + + void vTaskPriorityDisinheritAfterTimeout( TaskHandle_t const pxMutexHolder, + UBaseType_t uxHighestPriorityWaitingTask ) + { + TCB_t * const pxTCB = pxMutexHolder; + UBaseType_t uxPriorityUsedOnEntry, uxPriorityToUse; + const UBaseType_t uxOnlyOneMutexHeld = ( UBaseType_t ) 1; + + if( pxMutexHolder != NULL ) + { + /* If pxMutexHolder is not NULL then the holder must hold at least + * one mutex. */ + configASSERT( pxTCB->uxMutexesHeld ); + + /* Determine the priority to which the priority of the task that + * holds the mutex should be set. This will be the greater of the + * holding task's base priority and the priority of the highest + * priority task that is waiting to obtain the mutex. */ + if( pxTCB->uxBasePriority < uxHighestPriorityWaitingTask ) + { + uxPriorityToUse = uxHighestPriorityWaitingTask; + } + else + { + uxPriorityToUse = pxTCB->uxBasePriority; + } + + /* Does the priority need to change? */ + if( pxTCB->uxPriority != uxPriorityToUse ) + { + /* Only disinherit if no other mutexes are held. This is a + * simplification in the priority inheritance implementation. If + * the task that holds the mutex is also holding other mutexes then + * the other mutexes may have caused the priority inheritance. */ + if( pxTCB->uxMutexesHeld == uxOnlyOneMutexHeld ) + { + /* If a task has timed out because it already holds the + * mutex it was trying to obtain then it cannot of inherited + * its own priority. */ + configASSERT( pxTCB != pxCurrentTCB ); + + /* Disinherit the priority, remembering the previous + * priority to facilitate determining the subject task's + * state. */ + traceTASK_PRIORITY_DISINHERIT( pxTCB, uxPriorityToUse ); + uxPriorityUsedOnEntry = pxTCB->uxPriority; + pxTCB->uxPriority = uxPriorityToUse; + + /* Only reset the event list item value if the value is not + * being used for anything else. */ + if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) + { + listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxPriorityToUse ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* If the running task is not the task that holds the mutex + * then the task that holds the mutex could be in either the + * Ready, Blocked or Suspended states. Only remove the task + * from its current state list if it is in the Ready state as + * the task's priority is going to change and there is one + * Ready list per priority. */ + if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE ) + { + if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + /* It is known that the task is in its ready list so + * there is no need to check again and the port level + * reset macro can be called directly. */ + portRESET_READY_PRIORITY( pxTCB->uxPriority, uxTopReadyPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + prvAddTaskToReadyList( pxTCB ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + +#endif /* configUSE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if ( portCRITICAL_NESTING_IN_TCB == 1 ) + + void vTaskEnterCritical( void ) + { + portDISABLE_INTERRUPTS(); + + if( xSchedulerRunning != pdFALSE ) + { + ( pxCurrentTCB->uxCriticalNesting )++; + + /* This is not the interrupt safe version of the enter critical + * function so assert() if it is being called from an interrupt + * context. Only API functions that end in "FromISR" can be used in an + * interrupt. Only assert if the critical nesting count is 1 to + * protect against recursive calls if the assert function also uses a + * critical section. */ + if( pxCurrentTCB->uxCriticalNesting == 1 ) + { + portASSERT_IF_IN_ISR(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + +#endif /* portCRITICAL_NESTING_IN_TCB */ +/*-----------------------------------------------------------*/ + +#if ( portCRITICAL_NESTING_IN_TCB == 1 ) + + void vTaskExitCritical( void ) + { + if( xSchedulerRunning != pdFALSE ) + { + if( pxCurrentTCB->uxCriticalNesting > 0U ) + { + ( pxCurrentTCB->uxCriticalNesting )--; + + if( pxCurrentTCB->uxCriticalNesting == 0U ) + { + portENABLE_INTERRUPTS(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + +#endif /* portCRITICAL_NESTING_IN_TCB */ +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) ) + + static char * prvWriteNameToBuffer( char * pcBuffer, + const char * pcTaskName ) + { + size_t x; + + /* Start by copying the entire string. */ + strcpy( pcBuffer, pcTaskName ); + + /* Pad the end of the string with spaces to ensure columns line up when + * printed out. */ + for( x = strlen( pcBuffer ); x < ( size_t ) ( configMAX_TASK_NAME_LEN - 1 ); x++ ) + { + pcBuffer[ x ] = ' '; + } + + /* Terminate. */ + pcBuffer[ x ] = ( char ) 0x00; + + /* Return the new end of string. */ + return &( pcBuffer[ x ] ); + } + +#endif /* ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) */ +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + + void vTaskList( char * pcWriteBuffer ) + { + TaskStatus_t * pxTaskStatusArray; + UBaseType_t uxArraySize, x; + char cStatus; + + /* + * PLEASE NOTE: + * + * This function is provided for convenience only, and is used by many + * of the demo applications. Do not consider it to be part of the + * scheduler. + * + * vTaskList() calls uxTaskGetSystemState(), then formats part of the + * uxTaskGetSystemState() output into a human readable table that + * displays task: names, states, priority, stack usage and task number. + * Stack usage specified as the number of unused StackType_t words stack can hold + * on top of stack - not the number of bytes. + * + * vTaskList() has a dependency on the sprintf() C library function that + * might bloat the code size, use a lot of stack, and provide different + * results on different platforms. An alternative, tiny, third party, + * and limited functionality implementation of sprintf() is provided in + * many of the FreeRTOS/Demo sub-directories in a file called + * printf-stdarg.c (note printf-stdarg.c does not provide a full + * snprintf() implementation!). + * + * It is recommended that production systems call uxTaskGetSystemState() + * directly to get access to raw stats data, rather than indirectly + * through a call to vTaskList(). + */ + + + /* Make sure the write buffer does not contain a string. */ + *pcWriteBuffer = ( char ) 0x00; + + /* Take a snapshot of the number of tasks in case it changes while this + * function is executing. */ + uxArraySize = uxCurrentNumberOfTasks; + + /* Allocate an array index for each task. NOTE! if + * configSUPPORT_DYNAMIC_ALLOCATION is set to 0 then pvPortMalloc() will + * equate to NULL. */ + pxTaskStatusArray = pvPortMalloc( uxCurrentNumberOfTasks * sizeof( TaskStatus_t ) ); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and this allocation allocates a struct that has the alignment requirements of a pointer. */ + + if( pxTaskStatusArray != NULL ) + { + /* Generate the (binary) data. */ + uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, NULL ); + + /* Create a human readable table from the binary data. */ + for( x = 0; x < uxArraySize; x++ ) + { + switch( pxTaskStatusArray[ x ].eCurrentState ) + { + case eRunning: + cStatus = tskRUNNING_CHAR; + break; + + case eReady: + cStatus = tskREADY_CHAR; + break; + + case eBlocked: + cStatus = tskBLOCKED_CHAR; + break; + + case eSuspended: + cStatus = tskSUSPENDED_CHAR; + break; + + case eDeleted: + cStatus = tskDELETED_CHAR; + break; + + case eInvalid: /* Fall through. */ + default: /* Should not get here, but it is included + * to prevent static checking errors. */ + cStatus = ( char ) 0x00; + break; + } + + /* Write the task name to the string, padding with spaces so it + * can be printed in tabular form more easily. */ + pcWriteBuffer = prvWriteNameToBuffer( pcWriteBuffer, pxTaskStatusArray[ x ].pcTaskName ); + + /* Write the rest of the string. */ + sprintf( pcWriteBuffer, "\t%c\t%u\t%u\t%u\r\n", cStatus, ( unsigned int ) pxTaskStatusArray[ x ].uxCurrentPriority, ( unsigned int ) pxTaskStatusArray[ x ].usStackHighWaterMark, ( unsigned int ) pxTaskStatusArray[ x ].xTaskNumber ); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this is a utility function only - not part of the core kernel implementation. */ + pcWriteBuffer += strlen( pcWriteBuffer ); /*lint !e9016 Pointer arithmetic ok on char pointers especially as in this case where it best denotes the intent of the code. */ + } + + /* Free the array again. NOTE! If configSUPPORT_DYNAMIC_ALLOCATION + * is 0 then vPortFree() will be #defined to nothing. */ + vPortFree( pxTaskStatusArray ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + +#endif /* ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) */ +/*----------------------------------------------------------*/ + +#if ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + + void vTaskGetRunTimeStats( char * pcWriteBuffer ) + { + TaskStatus_t * pxTaskStatusArray; + UBaseType_t uxArraySize, x; + configRUN_TIME_COUNTER_TYPE ulTotalTime, ulStatsAsPercentage; + + #if ( configUSE_TRACE_FACILITY != 1 ) + { + #error configUSE_TRACE_FACILITY must also be set to 1 in FreeRTOSConfig.h to use vTaskGetRunTimeStats(). + } + #endif + + /* + * PLEASE NOTE: + * + * This function is provided for convenience only, and is used by many + * of the demo applications. Do not consider it to be part of the + * scheduler. + * + * vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part + * of the uxTaskGetSystemState() output into a human readable table that + * displays the amount of time each task has spent in the Running state + * in both absolute and percentage terms. + * + * vTaskGetRunTimeStats() has a dependency on the sprintf() C library + * function that might bloat the code size, use a lot of stack, and + * provide different results on different platforms. An alternative, + * tiny, third party, and limited functionality implementation of + * sprintf() is provided in many of the FreeRTOS/Demo sub-directories in + * a file called printf-stdarg.c (note printf-stdarg.c does not provide + * a full snprintf() implementation!). + * + * It is recommended that production systems call uxTaskGetSystemState() + * directly to get access to raw stats data, rather than indirectly + * through a call to vTaskGetRunTimeStats(). + */ + + /* Make sure the write buffer does not contain a string. */ + *pcWriteBuffer = ( char ) 0x00; + + /* Take a snapshot of the number of tasks in case it changes while this + * function is executing. */ + uxArraySize = uxCurrentNumberOfTasks; + + /* Allocate an array index for each task. NOTE! If + * configSUPPORT_DYNAMIC_ALLOCATION is set to 0 then pvPortMalloc() will + * equate to NULL. */ + pxTaskStatusArray = pvPortMalloc( uxCurrentNumberOfTasks * sizeof( TaskStatus_t ) ); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and this allocation allocates a struct that has the alignment requirements of a pointer. */ + + if( pxTaskStatusArray != NULL ) + { + /* Generate the (binary) data. */ + uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalTime ); + + /* For percentage calculations. */ + ulTotalTime /= 100UL; + + /* Avoid divide by zero errors. */ + if( ulTotalTime > 0UL ) + { + /* Create a human readable table from the binary data. */ + for( x = 0; x < uxArraySize; x++ ) + { + /* What percentage of the total run time has the task used? + * This will always be rounded down to the nearest integer. + * ulTotalRunTime has already been divided by 100. */ + ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalTime; + + /* Write the task name to the string, padding with + * spaces so it can be printed in tabular form more + * easily. */ + pcWriteBuffer = prvWriteNameToBuffer( pcWriteBuffer, pxTaskStatusArray[ x ].pcTaskName ); + + if( ulStatsAsPercentage > 0UL ) + { + #ifdef portLU_PRINTF_SPECIFIER_REQUIRED + { + sprintf( pcWriteBuffer, "\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage ); + } + #else + { + /* sizeof( int ) == sizeof( long ) so a smaller + * printf() library can be used. */ + sprintf( pcWriteBuffer, "\t%u\t\t%u%%\r\n", ( unsigned int ) pxTaskStatusArray[ x ].ulRunTimeCounter, ( unsigned int ) ulStatsAsPercentage ); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this is a utility function only - not part of the core kernel implementation. */ + } + #endif + } + else + { + /* If the percentage is zero here then the task has + * consumed less than 1% of the total run time. */ + #ifdef portLU_PRINTF_SPECIFIER_REQUIRED + { + sprintf( pcWriteBuffer, "\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].ulRunTimeCounter ); + } + #else + { + /* sizeof( int ) == sizeof( long ) so a smaller + * printf() library can be used. */ + sprintf( pcWriteBuffer, "\t%u\t\t<1%%\r\n", ( unsigned int ) pxTaskStatusArray[ x ].ulRunTimeCounter ); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this is a utility function only - not part of the core kernel implementation. */ + } + #endif + } + + pcWriteBuffer += strlen( pcWriteBuffer ); /*lint !e9016 Pointer arithmetic ok on char pointers especially as in this case where it best denotes the intent of the code. */ + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Free the array again. NOTE! If configSUPPORT_DYNAMIC_ALLOCATION + * is 0 then vPortFree() will be #defined to nothing. */ + vPortFree( pxTaskStatusArray ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + +#endif /* ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) */ +/*-----------------------------------------------------------*/ + +TickType_t uxTaskResetEventItemValue( void ) +{ + TickType_t uxReturn; + + uxReturn = listGET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ) ); + + /* Reset the event list item to its normal value - so it can be used with + * queues and semaphores. */ + listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), ( ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxCurrentTCB->uxPriority ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + + return uxReturn; +} +/*-----------------------------------------------------------*/ + +#if ( configUSE_MUTEXES == 1 ) + + TaskHandle_t pvTaskIncrementMutexHeldCount( void ) + { + /* If xSemaphoreCreateMutex() is called before any tasks have been created + * then pxCurrentTCB will be NULL. */ + if( pxCurrentTCB != NULL ) + { + ( pxCurrentTCB->uxMutexesHeld )++; + } + + return pxCurrentTCB; + } + +#endif /* configUSE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TASK_NOTIFICATIONS == 1 ) + + uint32_t ulTaskGenericNotifyTake( UBaseType_t uxIndexToWait, + BaseType_t xClearCountOnExit, + TickType_t xTicksToWait ) + { + uint32_t ulReturn; + + configASSERT( uxIndexToWait < configTASK_NOTIFICATION_ARRAY_ENTRIES ); + + taskENTER_CRITICAL(); + { + /* Only block if the notification count is not already non-zero. */ + if( pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ] == 0UL ) + { + /* Mark this task as waiting for a notification. */ + pxCurrentTCB->ucNotifyState[ uxIndexToWait ] = taskWAITING_NOTIFICATION; + + if( xTicksToWait > ( TickType_t ) 0 ) + { + prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); + traceTASK_NOTIFY_TAKE_BLOCK( uxIndexToWait ); + + /* All ports are written to allow a yield in a critical + * section (some will yield immediately, others wait until the + * critical section exits) - but it is not something that + * application code should ever do. */ + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + + taskENTER_CRITICAL(); + { + traceTASK_NOTIFY_TAKE( uxIndexToWait ); + ulReturn = pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ]; + + if( ulReturn != 0UL ) + { + if( xClearCountOnExit != pdFALSE ) + { + pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ] = 0UL; + } + else + { + pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ] = ulReturn - ( uint32_t ) 1; + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + pxCurrentTCB->ucNotifyState[ uxIndexToWait ] = taskNOT_WAITING_NOTIFICATION; + } + taskEXIT_CRITICAL(); + + return ulReturn; + } + +#endif /* configUSE_TASK_NOTIFICATIONS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TASK_NOTIFICATIONS == 1 ) + + BaseType_t xTaskGenericNotifyWait( UBaseType_t uxIndexToWait, + uint32_t ulBitsToClearOnEntry, + uint32_t ulBitsToClearOnExit, + uint32_t * pulNotificationValue, + TickType_t xTicksToWait ) + { + BaseType_t xReturn; + + configASSERT( uxIndexToWait < configTASK_NOTIFICATION_ARRAY_ENTRIES ); + + taskENTER_CRITICAL(); + { + /* Only block if a notification is not already pending. */ + if( pxCurrentTCB->ucNotifyState[ uxIndexToWait ] != taskNOTIFICATION_RECEIVED ) + { + /* Clear bits in the task's notification value as bits may get + * set by the notifying task or interrupt. This can be used to + * clear the value to zero. */ + pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ] &= ~ulBitsToClearOnEntry; + + /* Mark this task as waiting for a notification. */ + pxCurrentTCB->ucNotifyState[ uxIndexToWait ] = taskWAITING_NOTIFICATION; + + if( xTicksToWait > ( TickType_t ) 0 ) + { + prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); + traceTASK_NOTIFY_WAIT_BLOCK( uxIndexToWait ); + + /* All ports are written to allow a yield in a critical + * section (some will yield immediately, others wait until the + * critical section exits) - but it is not something that + * application code should ever do. */ + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + + taskENTER_CRITICAL(); + { + traceTASK_NOTIFY_WAIT( uxIndexToWait ); + + if( pulNotificationValue != NULL ) + { + /* Output the current notification value, which may or may not + * have changed. */ + *pulNotificationValue = pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ]; + } + + /* If ucNotifyValue is set then either the task never entered the + * blocked state (because a notification was already pending) or the + * task unblocked because of a notification. Otherwise the task + * unblocked because of a timeout. */ + if( pxCurrentTCB->ucNotifyState[ uxIndexToWait ] != taskNOTIFICATION_RECEIVED ) + { + /* A notification was not received. */ + xReturn = pdFALSE; + } + else + { + /* A notification was already pending or a notification was + * received while the task was waiting. */ + pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ] &= ~ulBitsToClearOnExit; + xReturn = pdTRUE; + } + + pxCurrentTCB->ucNotifyState[ uxIndexToWait ] = taskNOT_WAITING_NOTIFICATION; + } + taskEXIT_CRITICAL(); + + return xReturn; + } + +#endif /* configUSE_TASK_NOTIFICATIONS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TASK_NOTIFICATIONS == 1 ) + + BaseType_t xTaskGenericNotify( TaskHandle_t xTaskToNotify, + UBaseType_t uxIndexToNotify, + uint32_t ulValue, + eNotifyAction eAction, + uint32_t * pulPreviousNotificationValue ) + { + TCB_t * pxTCB; + BaseType_t xReturn = pdPASS; + uint8_t ucOriginalNotifyState; + + configASSERT( uxIndexToNotify < configTASK_NOTIFICATION_ARRAY_ENTRIES ); + configASSERT( xTaskToNotify ); + pxTCB = xTaskToNotify; + + taskENTER_CRITICAL(); + { + if( pulPreviousNotificationValue != NULL ) + { + *pulPreviousNotificationValue = pxTCB->ulNotifiedValue[ uxIndexToNotify ]; + } + + ucOriginalNotifyState = pxTCB->ucNotifyState[ uxIndexToNotify ]; + + pxTCB->ucNotifyState[ uxIndexToNotify ] = taskNOTIFICATION_RECEIVED; + + switch( eAction ) + { + case eSetBits: + pxTCB->ulNotifiedValue[ uxIndexToNotify ] |= ulValue; + break; + + case eIncrement: + ( pxTCB->ulNotifiedValue[ uxIndexToNotify ] )++; + break; + + case eSetValueWithOverwrite: + pxTCB->ulNotifiedValue[ uxIndexToNotify ] = ulValue; + break; + + case eSetValueWithoutOverwrite: + + if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED ) + { + pxTCB->ulNotifiedValue[ uxIndexToNotify ] = ulValue; + } + else + { + /* The value could not be written to the task. */ + xReturn = pdFAIL; + } + + break; + + case eNoAction: + + /* The task is being notified without its notify value being + * updated. */ + break; + + default: + + /* Should not get here if all enums are handled. + * Artificially force an assert by testing a value the + * compiler can't assume is const. */ + configASSERT( xTickCount == ( TickType_t ) 0 ); + + break; + } + + traceTASK_NOTIFY( uxIndexToNotify ); + + /* If the task is in the blocked state specifically to wait for a + * notification then unblock it now. */ + if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) + { + listREMOVE_ITEM( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); + + /* The task should not have been on an event list. */ + configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); + + #if ( configUSE_TICKLESS_IDLE != 0 ) + { + /* If a task is blocked waiting for a notification then + * xNextTaskUnblockTime might be set to the blocked task's time + * out time. If the task is unblocked for a reason other than + * a timeout xNextTaskUnblockTime is normally left unchanged, + * because it will automatically get reset to a new value when + * the tick count equals xNextTaskUnblockTime. However if + * tickless idling is used it might be more important to enter + * sleep mode at the earliest possible time - so reset + * xNextTaskUnblockTime here to ensure it is updated at the + * earliest possible time. */ + prvResetNextTaskUnblockTime(); + } + #endif + + if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* The notified task has a priority above the currently + * executing task so a yield is required. */ + taskYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + + return xReturn; + } + +#endif /* configUSE_TASK_NOTIFICATIONS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TASK_NOTIFICATIONS == 1 ) + + BaseType_t xTaskGenericNotifyFromISR( TaskHandle_t xTaskToNotify, + UBaseType_t uxIndexToNotify, + uint32_t ulValue, + eNotifyAction eAction, + uint32_t * pulPreviousNotificationValue, + BaseType_t * pxHigherPriorityTaskWoken ) + { + TCB_t * pxTCB; + uint8_t ucOriginalNotifyState; + BaseType_t xReturn = pdPASS; + UBaseType_t uxSavedInterruptStatus; + + configASSERT( xTaskToNotify ); + configASSERT( uxIndexToNotify < configTASK_NOTIFICATION_ARRAY_ENTRIES ); + + /* RTOS ports that support interrupt nesting have the concept of a + * maximum system call (or maximum API call) interrupt priority. + * Interrupts that are above the maximum system call priority are keep + * permanently enabled, even when the RTOS kernel is in a critical section, + * but cannot make any calls to FreeRTOS API functions. If configASSERT() + * is defined in FreeRTOSConfig.h then + * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + * failure if a FreeRTOS API function is called from an interrupt that has + * been assigned a priority above the configured maximum system call + * priority. Only FreeRTOS functions that end in FromISR can be called + * from interrupts that have been assigned a priority at or (logically) + * below the maximum system call interrupt priority. FreeRTOS maintains a + * separate interrupt safe API to ensure interrupt entry is as fast and as + * simple as possible. More information (albeit Cortex-M specific) is + * provided on the following link: + * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + pxTCB = xTaskToNotify; + + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + if( pulPreviousNotificationValue != NULL ) + { + *pulPreviousNotificationValue = pxTCB->ulNotifiedValue[ uxIndexToNotify ]; + } + + ucOriginalNotifyState = pxTCB->ucNotifyState[ uxIndexToNotify ]; + pxTCB->ucNotifyState[ uxIndexToNotify ] = taskNOTIFICATION_RECEIVED; + + switch( eAction ) + { + case eSetBits: + pxTCB->ulNotifiedValue[ uxIndexToNotify ] |= ulValue; + break; + + case eIncrement: + ( pxTCB->ulNotifiedValue[ uxIndexToNotify ] )++; + break; + + case eSetValueWithOverwrite: + pxTCB->ulNotifiedValue[ uxIndexToNotify ] = ulValue; + break; + + case eSetValueWithoutOverwrite: + + if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED ) + { + pxTCB->ulNotifiedValue[ uxIndexToNotify ] = ulValue; + } + else + { + /* The value could not be written to the task. */ + xReturn = pdFAIL; + } + + break; + + case eNoAction: + + /* The task is being notified without its notify value being + * updated. */ + break; + + default: + + /* Should not get here if all enums are handled. + * Artificially force an assert by testing a value the + * compiler can't assume is const. */ + configASSERT( xTickCount == ( TickType_t ) 0 ); + break; + } + + traceTASK_NOTIFY_FROM_ISR( uxIndexToNotify ); + + /* If the task is in the blocked state specifically to wait for a + * notification then unblock it now. */ + if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) + { + /* The task should not have been on an event list. */ + configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); + + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + listREMOVE_ITEM( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); + } + else + { + /* The delayed and ready lists cannot be accessed, so hold + * this task pending until the scheduler is resumed. */ + listINSERT_END( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); + } + + if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* The notified task has a priority above the currently + * executing task so a yield is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + + /* Mark that a yield is pending in case the user is not + * using the "xHigherPriorityTaskWoken" parameter to an ISR + * safe FreeRTOS function. */ + xYieldPending = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + + return xReturn; + } + +#endif /* configUSE_TASK_NOTIFICATIONS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TASK_NOTIFICATIONS == 1 ) + + void vTaskGenericNotifyGiveFromISR( TaskHandle_t xTaskToNotify, + UBaseType_t uxIndexToNotify, + BaseType_t * pxHigherPriorityTaskWoken ) + { + TCB_t * pxTCB; + uint8_t ucOriginalNotifyState; + UBaseType_t uxSavedInterruptStatus; + + configASSERT( xTaskToNotify ); + configASSERT( uxIndexToNotify < configTASK_NOTIFICATION_ARRAY_ENTRIES ); + + /* RTOS ports that support interrupt nesting have the concept of a + * maximum system call (or maximum API call) interrupt priority. + * Interrupts that are above the maximum system call priority are keep + * permanently enabled, even when the RTOS kernel is in a critical section, + * but cannot make any calls to FreeRTOS API functions. If configASSERT() + * is defined in FreeRTOSConfig.h then + * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + * failure if a FreeRTOS API function is called from an interrupt that has + * been assigned a priority above the configured maximum system call + * priority. Only FreeRTOS functions that end in FromISR can be called + * from interrupts that have been assigned a priority at or (logically) + * below the maximum system call interrupt priority. FreeRTOS maintains a + * separate interrupt safe API to ensure interrupt entry is as fast and as + * simple as possible. More information (albeit Cortex-M specific) is + * provided on the following link: + * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + pxTCB = xTaskToNotify; + + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + ucOriginalNotifyState = pxTCB->ucNotifyState[ uxIndexToNotify ]; + pxTCB->ucNotifyState[ uxIndexToNotify ] = taskNOTIFICATION_RECEIVED; + + /* 'Giving' is equivalent to incrementing a count in a counting + * semaphore. */ + ( pxTCB->ulNotifiedValue[ uxIndexToNotify ] )++; + + traceTASK_NOTIFY_GIVE_FROM_ISR( uxIndexToNotify ); + + /* If the task is in the blocked state specifically to wait for a + * notification then unblock it now. */ + if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) + { + /* The task should not have been on an event list. */ + configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); + + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + listREMOVE_ITEM( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); + } + else + { + /* The delayed and ready lists cannot be accessed, so hold + * this task pending until the scheduler is resumed. */ + listINSERT_END( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); + } + + if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* The notified task has a priority above the currently + * executing task so a yield is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + + /* Mark that a yield is pending in case the user is not + * using the "xHigherPriorityTaskWoken" parameter in an ISR + * safe FreeRTOS function. */ + xYieldPending = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + } + +#endif /* configUSE_TASK_NOTIFICATIONS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TASK_NOTIFICATIONS == 1 ) + + BaseType_t xTaskGenericNotifyStateClear( TaskHandle_t xTask, + UBaseType_t uxIndexToClear ) + { + TCB_t * pxTCB; + BaseType_t xReturn; + + configASSERT( uxIndexToClear < configTASK_NOTIFICATION_ARRAY_ENTRIES ); + + /* If null is passed in here then it is the calling task that is having + * its notification state cleared. */ + pxTCB = prvGetTCBFromHandle( xTask ); + + taskENTER_CRITICAL(); + { + if( pxTCB->ucNotifyState[ uxIndexToClear ] == taskNOTIFICATION_RECEIVED ) + { + pxTCB->ucNotifyState[ uxIndexToClear ] = taskNOT_WAITING_NOTIFICATION; + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + } + } + taskEXIT_CRITICAL(); + + return xReturn; + } + +#endif /* configUSE_TASK_NOTIFICATIONS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TASK_NOTIFICATIONS == 1 ) + + uint32_t ulTaskGenericNotifyValueClear( TaskHandle_t xTask, + UBaseType_t uxIndexToClear, + uint32_t ulBitsToClear ) + { + TCB_t * pxTCB; + uint32_t ulReturn; + + /* If null is passed in here then it is the calling task that is having + * its notification state cleared. */ + pxTCB = prvGetTCBFromHandle( xTask ); + + taskENTER_CRITICAL(); + { + /* Return the notification as it was before the bits were cleared, + * then clear the bit mask. */ + ulReturn = pxTCB->ulNotifiedValue[ uxIndexToClear ]; + pxTCB->ulNotifiedValue[ uxIndexToClear ] &= ~ulBitsToClear; + } + taskEXIT_CRITICAL(); + + return ulReturn; + } + +#endif /* configUSE_TASK_NOTIFICATIONS */ +/*-----------------------------------------------------------*/ + +#if ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) ) + + configRUN_TIME_COUNTER_TYPE ulTaskGetIdleRunTimeCounter( void ) + { + return xIdleTaskHandle->ulRunTimeCounter; + } + +#endif +/*-----------------------------------------------------------*/ + +#if ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) ) + + configRUN_TIME_COUNTER_TYPE ulTaskGetIdleRunTimePercent( void ) + { + configRUN_TIME_COUNTER_TYPE ulTotalTime, ulReturn; + + ulTotalTime = portGET_RUN_TIME_COUNTER_VALUE(); + + /* For percentage calculations. */ + ulTotalTime /= ( configRUN_TIME_COUNTER_TYPE ) 100; + + /* Avoid divide by zero errors. */ + if( ulTotalTime > ( configRUN_TIME_COUNTER_TYPE ) 0 ) + { + ulReturn = xIdleTaskHandle->ulRunTimeCounter / ulTotalTime; + } + else + { + ulReturn = 0; + } + + return ulReturn; + } + +#endif /* if ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) ) */ +/*-----------------------------------------------------------*/ + +static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait, + const BaseType_t xCanBlockIndefinitely ) +{ + TickType_t xTimeToWake; + const TickType_t xConstTickCount = xTickCount; + + #if ( INCLUDE_xTaskAbortDelay == 1 ) + { + /* About to enter a delayed list, so ensure the ucDelayAborted flag is + * reset to pdFALSE so it can be detected as having been set to pdTRUE + * when the task leaves the Blocked state. */ + pxCurrentTCB->ucDelayAborted = pdFALSE; + } + #endif + + /* Remove the task from the ready list before adding it to the blocked list + * as the same list item is used for both lists. */ + if( uxListRemove( &( pxCurrentTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + /* The current task must be in a ready list, so there is no need to + * check, and the port reset macro can be called directly. */ + portRESET_READY_PRIORITY( pxCurrentTCB->uxPriority, uxTopReadyPriority ); /*lint !e931 pxCurrentTCB cannot change as it is the calling task. pxCurrentTCB->uxPriority and uxTopReadyPriority cannot change as called with scheduler suspended or in a critical section. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + #if ( INCLUDE_vTaskSuspend == 1 ) + { + if( ( xTicksToWait == portMAX_DELAY ) && ( xCanBlockIndefinitely != pdFALSE ) ) + { + /* Add the task to the suspended task list instead of a delayed task + * list to ensure it is not woken by a timing event. It will block + * indefinitely. */ + listINSERT_END( &xSuspendedTaskList, &( pxCurrentTCB->xStateListItem ) ); + } + else + { + /* Calculate the time at which the task should be woken if the event + * does not occur. This may overflow but this doesn't matter, the + * kernel will manage it correctly. */ + xTimeToWake = xConstTickCount + xTicksToWait; + + /* The list item will be inserted in wake time order. */ + listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xStateListItem ), xTimeToWake ); + + if( xTimeToWake < xConstTickCount ) + { + /* Wake time has overflowed. Place this item in the overflow + * list. */ + vListInsert( pxOverflowDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); + } + else + { + /* The wake time has not overflowed, so the current block list + * is used. */ + vListInsert( pxDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); + + /* If the task entering the blocked state was placed at the + * head of the list of blocked tasks then xNextTaskUnblockTime + * needs to be updated too. */ + if( xTimeToWake < xNextTaskUnblockTime ) + { + xNextTaskUnblockTime = xTimeToWake; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + } + #else /* INCLUDE_vTaskSuspend */ + { + /* Calculate the time at which the task should be woken if the event + * does not occur. This may overflow but this doesn't matter, the kernel + * will manage it correctly. */ + xTimeToWake = xConstTickCount + xTicksToWait; + + /* The list item will be inserted in wake time order. */ + listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xStateListItem ), xTimeToWake ); + + if( xTimeToWake < xConstTickCount ) + { + /* Wake time has overflowed. Place this item in the overflow list. */ + vListInsert( pxOverflowDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); + } + else + { + /* The wake time has not overflowed, so the current block list is used. */ + vListInsert( pxDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); + + /* If the task entering the blocked state was placed at the head of the + * list of blocked tasks then xNextTaskUnblockTime needs to be updated + * too. */ + if( xTimeToWake < xNextTaskUnblockTime ) + { + xNextTaskUnblockTime = xTimeToWake; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + /* Avoid compiler warning when INCLUDE_vTaskSuspend is not 1. */ + ( void ) xCanBlockIndefinitely; + } + #endif /* INCLUDE_vTaskSuspend */ +} + +/* Code below here allows additional code to be inserted into this source file, + * especially where access to file scope functions and data is needed (for example + * when performing module tests). */ + +#ifdef FREERTOS_MODULE_TEST + #include "tasks_test_access_functions.h" +#endif + + +#if ( configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H == 1 ) + + #include "freertos_tasks_c_additions.h" + + #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT + static void freertos_tasks_c_additions_init( void ) + { + FREERTOS_TASKS_C_ADDITIONS_INIT(); + } + #endif + +#endif /* if ( configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H == 1 ) */ diff --git a/freertos/miv-rv32-freertos-demo/src/freertos-source/source/timers.c b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/timers.c new file mode 100644 index 0000000..88d834b --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/freertos-source/source/timers.c @@ -0,0 +1,1119 @@ +/* + * FreeRTOS Kernel V10.4.6 + * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* Standard includes. */ +#include + +/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining + * all the API functions to use the MPU wrappers. That should only be done when + * task.h is included from an application file. */ +#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" +#include "timers.h" + +#if ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 0 ) + #error configUSE_TIMERS must be set to 1 to make the xTimerPendFunctionCall() function available. +#endif + +/* Lint e9021, e961 and e750 are suppressed as a MISRA exception justified + * because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined + * for the header files above, but not in this file, in order to generate the + * correct privileged Vs unprivileged linkage and placement. */ +#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e9021 !e961 !e750. */ + + +/* This entire source file will be skipped if the application is not configured + * to include software timer functionality. This #if is closed at the very bottom + * of this file. If you want to include software timer functionality then ensure + * configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */ +#if ( configUSE_TIMERS == 1 ) + +/* Misc definitions. */ + #define tmrNO_DELAY ( ( TickType_t ) 0U ) + #define tmrMAX_TIME_BEFORE_OVERFLOW ( ( TickType_t ) -1 ) + +/* The name assigned to the timer service task. This can be overridden by + * defining trmTIMER_SERVICE_TASK_NAME in FreeRTOSConfig.h. */ + #ifndef configTIMER_SERVICE_TASK_NAME + #define configTIMER_SERVICE_TASK_NAME "Tmr Svc" + #endif + +/* Bit definitions used in the ucStatus member of a timer structure. */ + #define tmrSTATUS_IS_ACTIVE ( ( uint8_t ) 0x01 ) + #define tmrSTATUS_IS_STATICALLY_ALLOCATED ( ( uint8_t ) 0x02 ) + #define tmrSTATUS_IS_AUTORELOAD ( ( uint8_t ) 0x04 ) + +/* The definition of the timers themselves. */ + typedef struct tmrTimerControl /* The old naming convention is used to prevent breaking kernel aware debuggers. */ + { + const char * pcTimerName; /*<< Text name. This is not used by the kernel, it is included simply to make debugging easier. */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + ListItem_t xTimerListItem; /*<< Standard linked list item as used by all kernel features for event management. */ + TickType_t xTimerPeriodInTicks; /*<< How quickly and often the timer expires. */ + void * pvTimerID; /*<< An ID to identify the timer. This allows the timer to be identified when the same callback is used for multiple timers. */ + TimerCallbackFunction_t pxCallbackFunction; /*<< The function that will be called when the timer expires. */ + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxTimerNumber; /*<< An ID assigned by trace tools such as FreeRTOS+Trace */ + #endif + uint8_t ucStatus; /*<< Holds bits to say if the timer was statically allocated or not, and if it is active or not. */ + } xTIMER; + +/* The old xTIMER name is maintained above then typedefed to the new Timer_t + * name below to enable the use of older kernel aware debuggers. */ + typedef xTIMER Timer_t; + +/* The definition of messages that can be sent and received on the timer queue. + * Two types of message can be queued - messages that manipulate a software timer, + * and messages that request the execution of a non-timer related callback. The + * two message types are defined in two separate structures, xTimerParametersType + * and xCallbackParametersType respectively. */ + typedef struct tmrTimerParameters + { + TickType_t xMessageValue; /*<< An optional value used by a subset of commands, for example, when changing the period of a timer. */ + Timer_t * pxTimer; /*<< The timer to which the command will be applied. */ + } TimerParameter_t; + + + typedef struct tmrCallbackParameters + { + PendedFunction_t pxCallbackFunction; /* << The callback function to execute. */ + void * pvParameter1; /* << The value that will be used as the callback functions first parameter. */ + uint32_t ulParameter2; /* << The value that will be used as the callback functions second parameter. */ + } CallbackParameters_t; + +/* The structure that contains the two message types, along with an identifier + * that is used to determine which message type is valid. */ + typedef struct tmrTimerQueueMessage + { + BaseType_t xMessageID; /*<< The command being sent to the timer service task. */ + union + { + TimerParameter_t xTimerParameters; + + /* Don't include xCallbackParameters if it is not going to be used as + * it makes the structure (and therefore the timer queue) larger. */ + #if ( INCLUDE_xTimerPendFunctionCall == 1 ) + CallbackParameters_t xCallbackParameters; + #endif /* INCLUDE_xTimerPendFunctionCall */ + } u; + } DaemonTaskMessage_t; + +/*lint -save -e956 A manual analysis and inspection has been used to determine + * which static variables must be declared volatile. */ + +/* The list in which active timers are stored. Timers are referenced in expire + * time order, with the nearest expiry time at the front of the list. Only the + * timer service task is allowed to access these lists. + * xActiveTimerList1 and xActiveTimerList2 could be at function scope but that + * breaks some kernel aware debuggers, and debuggers that reply on removing the + * static qualifier. */ + PRIVILEGED_DATA static List_t xActiveTimerList1; + PRIVILEGED_DATA static List_t xActiveTimerList2; + PRIVILEGED_DATA static List_t * pxCurrentTimerList; + PRIVILEGED_DATA static List_t * pxOverflowTimerList; + +/* A queue that is used to send commands to the timer service task. */ + PRIVILEGED_DATA static QueueHandle_t xTimerQueue = NULL; + PRIVILEGED_DATA static TaskHandle_t xTimerTaskHandle = NULL; + +/*lint -restore */ + +/*-----------------------------------------------------------*/ + +/* + * Initialise the infrastructure used by the timer service task if it has not + * been initialised already. + */ + static void prvCheckForValidListAndQueue( void ) PRIVILEGED_FUNCTION; + +/* + * The timer service task (daemon). Timer functionality is controlled by this + * task. Other tasks communicate with the timer service task using the + * xTimerQueue queue. + */ + static portTASK_FUNCTION_PROTO( prvTimerTask, pvParameters ) PRIVILEGED_FUNCTION; + +/* + * Called by the timer service task to interpret and process a command it + * received on the timer queue. + */ + static void prvProcessReceivedCommands( void ) PRIVILEGED_FUNCTION; + +/* + * Insert the timer into either xActiveTimerList1, or xActiveTimerList2, + * depending on if the expire time causes a timer counter overflow. + */ + static BaseType_t prvInsertTimerInActiveList( Timer_t * const pxTimer, + const TickType_t xNextExpiryTime, + const TickType_t xTimeNow, + const TickType_t xCommandTime ) PRIVILEGED_FUNCTION; + +/* + * Reload the specified auto-reload timer. If the reloading is backlogged, + * clear the backlog, calling the callback for each additional reload. When + * this function returns, the next expiry time is after xTimeNow. + */ + static void prvReloadTimer( Timer_t * const pxTimer, + TickType_t xExpiredTime, + const TickType_t xTimeNow ) PRIVILEGED_FUNCTION; + +/* + * An active timer has reached its expire time. Reload the timer if it is an + * auto-reload timer, then call its callback. + */ + static void prvProcessExpiredTimer( const TickType_t xNextExpireTime, + const TickType_t xTimeNow ) PRIVILEGED_FUNCTION; + +/* + * The tick count has overflowed. Switch the timer lists after ensuring the + * current timer list does not still reference some timers. + */ + static void prvSwitchTimerLists( void ) PRIVILEGED_FUNCTION; + +/* + * Obtain the current tick count, setting *pxTimerListsWereSwitched to pdTRUE + * if a tick count overflow occurred since prvSampleTimeNow() was last called. + */ + static TickType_t prvSampleTimeNow( BaseType_t * const pxTimerListsWereSwitched ) PRIVILEGED_FUNCTION; + +/* + * If the timer list contains any active timers then return the expire time of + * the timer that will expire first and set *pxListWasEmpty to false. If the + * timer list does not contain any timers then return 0 and set *pxListWasEmpty + * to pdTRUE. + */ + static TickType_t prvGetNextExpireTime( BaseType_t * const pxListWasEmpty ) PRIVILEGED_FUNCTION; + +/* + * If a timer has expired, process it. Otherwise, block the timer service task + * until either a timer does expire or a command is received. + */ + static void prvProcessTimerOrBlockTask( const TickType_t xNextExpireTime, + BaseType_t xListWasEmpty ) PRIVILEGED_FUNCTION; + +/* + * Called after a Timer_t structure has been allocated either statically or + * dynamically to fill in the structure's members. + */ + static void prvInitialiseNewTimer( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction, + Timer_t * pxNewTimer ) PRIVILEGED_FUNCTION; +/*-----------------------------------------------------------*/ + + BaseType_t xTimerCreateTimerTask( void ) + { + BaseType_t xReturn = pdFAIL; + + /* This function is called when the scheduler is started if + * configUSE_TIMERS is set to 1. Check that the infrastructure used by the + * timer service task has been created/initialised. If timers have already + * been created then the initialisation will already have been performed. */ + prvCheckForValidListAndQueue(); + + if( xTimerQueue != NULL ) + { + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + StaticTask_t * pxTimerTaskTCBBuffer = NULL; + StackType_t * pxTimerTaskStackBuffer = NULL; + uint32_t ulTimerTaskStackSize; + + vApplicationGetTimerTaskMemory( &pxTimerTaskTCBBuffer, &pxTimerTaskStackBuffer, &ulTimerTaskStackSize ); + xTimerTaskHandle = xTaskCreateStatic( prvTimerTask, + configTIMER_SERVICE_TASK_NAME, + ulTimerTaskStackSize, + NULL, + ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, + pxTimerTaskStackBuffer, + pxTimerTaskTCBBuffer ); + + if( xTimerTaskHandle != NULL ) + { + xReturn = pdPASS; + } + } + #else /* if ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ + { + xReturn = xTaskCreate( prvTimerTask, + configTIMER_SERVICE_TASK_NAME, + configTIMER_TASK_STACK_DEPTH, + NULL, + ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, + &xTimerTaskHandle ); + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + configASSERT( xReturn ); + return xReturn; + } +/*-----------------------------------------------------------*/ + + #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + + TimerHandle_t xTimerCreate( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction ) + { + Timer_t * pxNewTimer; + + pxNewTimer = ( Timer_t * ) pvPortMalloc( sizeof( Timer_t ) ); /*lint !e9087 !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack, and the first member of Timer_t is always a pointer to the timer's mame. */ + + if( pxNewTimer != NULL ) + { + /* Status is thus far zero as the timer is not created statically + * and has not been started. The auto-reload bit may get set in + * prvInitialiseNewTimer. */ + pxNewTimer->ucStatus = 0x00; + prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer ); + } + + return pxNewTimer; + } + + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + + TimerHandle_t xTimerCreateStatic( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction, + StaticTimer_t * pxTimerBuffer ) + { + Timer_t * pxNewTimer; + + #if ( configASSERT_DEFINED == 1 ) + { + /* Sanity check that the size of the structure used to declare a + * variable of type StaticTimer_t equals the size of the real timer + * structure. */ + volatile size_t xSize = sizeof( StaticTimer_t ); + configASSERT( xSize == sizeof( Timer_t ) ); + ( void ) xSize; /* Keeps lint quiet when configASSERT() is not defined. */ + } + #endif /* configASSERT_DEFINED */ + + /* A pointer to a StaticTimer_t structure MUST be provided, use it. */ + configASSERT( pxTimerBuffer ); + pxNewTimer = ( Timer_t * ) pxTimerBuffer; /*lint !e740 !e9087 StaticTimer_t is a pointer to a Timer_t, so guaranteed to be aligned and sized correctly (checked by an assert()), so this is safe. */ + + if( pxNewTimer != NULL ) + { + /* Timers can be created statically or dynamically so note this + * timer was created statically in case it is later deleted. The + * auto-reload bit may get set in prvInitialiseNewTimer(). */ + pxNewTimer->ucStatus = tmrSTATUS_IS_STATICALLY_ALLOCATED; + + prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer ); + } + + return pxNewTimer; + } + + #endif /* configSUPPORT_STATIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + + static void prvInitialiseNewTimer( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction, + Timer_t * pxNewTimer ) + { + /* 0 is not a valid value for xTimerPeriodInTicks. */ + configASSERT( ( xTimerPeriodInTicks > 0 ) ); + + /* Ensure the infrastructure used by the timer service task has been + * created/initialised. */ + prvCheckForValidListAndQueue(); + + /* Initialise the timer structure members using the function + * parameters. */ + pxNewTimer->pcTimerName = pcTimerName; + pxNewTimer->xTimerPeriodInTicks = xTimerPeriodInTicks; + pxNewTimer->pvTimerID = pvTimerID; + pxNewTimer->pxCallbackFunction = pxCallbackFunction; + vListInitialiseItem( &( pxNewTimer->xTimerListItem ) ); + + if( uxAutoReload != pdFALSE ) + { + pxNewTimer->ucStatus |= tmrSTATUS_IS_AUTORELOAD; + } + + traceTIMER_CREATE( pxNewTimer ); + } +/*-----------------------------------------------------------*/ + + BaseType_t xTimerGenericCommand( TimerHandle_t xTimer, + const BaseType_t xCommandID, + const TickType_t xOptionalValue, + BaseType_t * const pxHigherPriorityTaskWoken, + const TickType_t xTicksToWait ) + { + BaseType_t xReturn = pdFAIL; + DaemonTaskMessage_t xMessage; + + configASSERT( xTimer ); + + /* Send a message to the timer service task to perform a particular action + * on a particular timer definition. */ + if( xTimerQueue != NULL ) + { + /* Send a command to the timer service task to start the xTimer timer. */ + xMessage.xMessageID = xCommandID; + xMessage.u.xTimerParameters.xMessageValue = xOptionalValue; + xMessage.u.xTimerParameters.pxTimer = xTimer; + + if( xCommandID < tmrFIRST_FROM_ISR_COMMAND ) + { + if( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING ) + { + xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait ); + } + else + { + xReturn = xQueueSendToBack( xTimerQueue, &xMessage, tmrNO_DELAY ); + } + } + else + { + xReturn = xQueueSendToBackFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken ); + } + + traceTIMER_COMMAND_SEND( xTimer, xCommandID, xOptionalValue, xReturn ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xReturn; + } +/*-----------------------------------------------------------*/ + + TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ) + { + /* If xTimerGetTimerDaemonTaskHandle() is called before the scheduler has been + * started, then xTimerTaskHandle will be NULL. */ + configASSERT( ( xTimerTaskHandle != NULL ) ); + return xTimerTaskHandle; + } +/*-----------------------------------------------------------*/ + + TickType_t xTimerGetPeriod( TimerHandle_t xTimer ) + { + Timer_t * pxTimer = xTimer; + + configASSERT( xTimer ); + return pxTimer->xTimerPeriodInTicks; + } +/*-----------------------------------------------------------*/ + + void vTimerSetReloadMode( TimerHandle_t xTimer, + const UBaseType_t uxAutoReload ) + { + Timer_t * pxTimer = xTimer; + + configASSERT( xTimer ); + taskENTER_CRITICAL(); + { + if( uxAutoReload != pdFALSE ) + { + pxTimer->ucStatus |= tmrSTATUS_IS_AUTORELOAD; + } + else + { + pxTimer->ucStatus &= ( ( uint8_t ) ~tmrSTATUS_IS_AUTORELOAD ); + } + } + taskEXIT_CRITICAL(); + } +/*-----------------------------------------------------------*/ + + UBaseType_t uxTimerGetReloadMode( TimerHandle_t xTimer ) + { + Timer_t * pxTimer = xTimer; + UBaseType_t uxReturn; + + configASSERT( xTimer ); + taskENTER_CRITICAL(); + { + if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) == 0 ) + { + /* Not an auto-reload timer. */ + uxReturn = ( UBaseType_t ) pdFALSE; + } + else + { + /* Is an auto-reload timer. */ + uxReturn = ( UBaseType_t ) pdTRUE; + } + } + taskEXIT_CRITICAL(); + + return uxReturn; + } +/*-----------------------------------------------------------*/ + + TickType_t xTimerGetExpiryTime( TimerHandle_t xTimer ) + { + Timer_t * pxTimer = xTimer; + TickType_t xReturn; + + configASSERT( xTimer ); + xReturn = listGET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ) ); + return xReturn; + } +/*-----------------------------------------------------------*/ + + const char * pcTimerGetName( TimerHandle_t xTimer ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + { + Timer_t * pxTimer = xTimer; + + configASSERT( xTimer ); + return pxTimer->pcTimerName; + } +/*-----------------------------------------------------------*/ + + static void prvReloadTimer( Timer_t * const pxTimer, + TickType_t xExpiredTime, + const TickType_t xTimeNow ) + { + /* Insert the timer into the appropriate list for the next expiry time. + * If the next expiry time has already passed, advance the expiry time, + * call the callback function, and try again. */ + while( prvInsertTimerInActiveList( pxTimer, ( xExpiredTime + pxTimer->xTimerPeriodInTicks ), xTimeNow, xExpiredTime ) != pdFALSE ) + { + /* Advance the expiry time. */ + xExpiredTime += pxTimer->xTimerPeriodInTicks; + + /* Call the timer callback. */ + traceTIMER_EXPIRED( pxTimer ); + pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); + } + } +/*-----------------------------------------------------------*/ + + static void prvProcessExpiredTimer( const TickType_t xNextExpireTime, + const TickType_t xTimeNow ) + { + Timer_t * const pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList ); /*lint !e9087 !e9079 void * is used as this macro is used with tasks and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + + /* Remove the timer from the list of active timers. A check has already + * been performed to ensure the list is not empty. */ + + ( void ) uxListRemove( &( pxTimer->xTimerListItem ) ); + + /* If the timer is an auto-reload timer then calculate the next + * expiry time and re-insert the timer in the list of active timers. */ + if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0 ) + { + prvReloadTimer( pxTimer, xNextExpireTime, xTimeNow ); + } + else + { + pxTimer->ucStatus &= ( ( uint8_t ) ~tmrSTATUS_IS_ACTIVE ); + } + + /* Call the timer callback. */ + traceTIMER_EXPIRED( pxTimer ); + pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); + } +/*-----------------------------------------------------------*/ + + static portTASK_FUNCTION( prvTimerTask, pvParameters ) + { + TickType_t xNextExpireTime; + BaseType_t xListWasEmpty; + + /* Just to avoid compiler warnings. */ + ( void ) pvParameters; + + #if ( configUSE_DAEMON_TASK_STARTUP_HOOK == 1 ) + { + extern void vApplicationDaemonTaskStartupHook( void ); + + /* Allow the application writer to execute some code in the context of + * this task at the point the task starts executing. This is useful if the + * application includes initialisation code that would benefit from + * executing after the scheduler has been started. */ + vApplicationDaemonTaskStartupHook(); + } + #endif /* configUSE_DAEMON_TASK_STARTUP_HOOK */ + + for( ; ; ) + { + /* Query the timers list to see if it contains any timers, and if so, + * obtain the time at which the next timer will expire. */ + xNextExpireTime = prvGetNextExpireTime( &xListWasEmpty ); + + /* If a timer has expired, process it. Otherwise, block this task + * until either a timer does expire, or a command is received. */ + prvProcessTimerOrBlockTask( xNextExpireTime, xListWasEmpty ); + + /* Empty the command queue. */ + prvProcessReceivedCommands(); + } + } +/*-----------------------------------------------------------*/ + + static void prvProcessTimerOrBlockTask( const TickType_t xNextExpireTime, + BaseType_t xListWasEmpty ) + { + TickType_t xTimeNow; + BaseType_t xTimerListsWereSwitched; + + vTaskSuspendAll(); + { + /* Obtain the time now to make an assessment as to whether the timer + * has expired or not. If obtaining the time causes the lists to switch + * then don't process this timer as any timers that remained in the list + * when the lists were switched will have been processed within the + * prvSampleTimeNow() function. */ + xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched ); + + if( xTimerListsWereSwitched == pdFALSE ) + { + /* The tick count has not overflowed, has the timer expired? */ + if( ( xListWasEmpty == pdFALSE ) && ( xNextExpireTime <= xTimeNow ) ) + { + ( void ) xTaskResumeAll(); + prvProcessExpiredTimer( xNextExpireTime, xTimeNow ); + } + else + { + /* The tick count has not overflowed, and the next expire + * time has not been reached yet. This task should therefore + * block to wait for the next expire time or a command to be + * received - whichever comes first. The following line cannot + * be reached unless xNextExpireTime > xTimeNow, except in the + * case when the current timer list is empty. */ + if( xListWasEmpty != pdFALSE ) + { + /* The current timer list is empty - is the overflow list + * also empty? */ + xListWasEmpty = listLIST_IS_EMPTY( pxOverflowTimerList ); + } + + vQueueWaitForMessageRestricted( xTimerQueue, ( xNextExpireTime - xTimeNow ), xListWasEmpty ); + + if( xTaskResumeAll() == pdFALSE ) + { + /* Yield to wait for either a command to arrive, or the + * block time to expire. If a command arrived between the + * critical section being exited and this yield then the yield + * will not cause the task to block. */ + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + else + { + ( void ) xTaskResumeAll(); + } + } + } +/*-----------------------------------------------------------*/ + + static TickType_t prvGetNextExpireTime( BaseType_t * const pxListWasEmpty ) + { + TickType_t xNextExpireTime; + + /* Timers are listed in expiry time order, with the head of the list + * referencing the task that will expire first. Obtain the time at which + * the timer with the nearest expiry time will expire. If there are no + * active timers then just set the next expire time to 0. That will cause + * this task to unblock when the tick count overflows, at which point the + * timer lists will be switched and the next expiry time can be + * re-assessed. */ + *pxListWasEmpty = listLIST_IS_EMPTY( pxCurrentTimerList ); + + if( *pxListWasEmpty == pdFALSE ) + { + xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList ); + } + else + { + /* Ensure the task unblocks when the tick count rolls over. */ + xNextExpireTime = ( TickType_t ) 0U; + } + + return xNextExpireTime; + } +/*-----------------------------------------------------------*/ + + static TickType_t prvSampleTimeNow( BaseType_t * const pxTimerListsWereSwitched ) + { + TickType_t xTimeNow; + PRIVILEGED_DATA static TickType_t xLastTime = ( TickType_t ) 0U; /*lint !e956 Variable is only accessible to one task. */ + + xTimeNow = xTaskGetTickCount(); + + if( xTimeNow < xLastTime ) + { + prvSwitchTimerLists(); + *pxTimerListsWereSwitched = pdTRUE; + } + else + { + *pxTimerListsWereSwitched = pdFALSE; + } + + xLastTime = xTimeNow; + + return xTimeNow; + } +/*-----------------------------------------------------------*/ + + static BaseType_t prvInsertTimerInActiveList( Timer_t * const pxTimer, + const TickType_t xNextExpiryTime, + const TickType_t xTimeNow, + const TickType_t xCommandTime ) + { + BaseType_t xProcessTimerNow = pdFALSE; + + listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xNextExpiryTime ); + listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer ); + + if( xNextExpiryTime <= xTimeNow ) + { + /* Has the expiry time elapsed between the command to start/reset a + * timer was issued, and the time the command was processed? */ + if( ( ( TickType_t ) ( xTimeNow - xCommandTime ) ) >= pxTimer->xTimerPeriodInTicks ) /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + { + /* The time between a command being issued and the command being + * processed actually exceeds the timers period. */ + xProcessTimerNow = pdTRUE; + } + else + { + vListInsert( pxOverflowTimerList, &( pxTimer->xTimerListItem ) ); + } + } + else + { + if( ( xTimeNow < xCommandTime ) && ( xNextExpiryTime >= xCommandTime ) ) + { + /* If, since the command was issued, the tick count has overflowed + * but the expiry time has not, then the timer must have already passed + * its expiry time and should be processed immediately. */ + xProcessTimerNow = pdTRUE; + } + else + { + vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) ); + } + } + + return xProcessTimerNow; + } +/*-----------------------------------------------------------*/ + + static void prvProcessReceivedCommands( void ) + { + DaemonTaskMessage_t xMessage; + Timer_t * pxTimer; + BaseType_t xTimerListsWereSwitched; + TickType_t xTimeNow; + + while( xQueueReceive( xTimerQueue, &xMessage, tmrNO_DELAY ) != pdFAIL ) /*lint !e603 xMessage does not have to be initialised as it is passed out, not in, and it is not used unless xQueueReceive() returns pdTRUE. */ + { + #if ( INCLUDE_xTimerPendFunctionCall == 1 ) + { + /* Negative commands are pended function calls rather than timer + * commands. */ + if( xMessage.xMessageID < ( BaseType_t ) 0 ) + { + const CallbackParameters_t * const pxCallback = &( xMessage.u.xCallbackParameters ); + + /* The timer uses the xCallbackParameters member to request a + * callback be executed. Check the callback is not NULL. */ + configASSERT( pxCallback ); + + /* Call the function. */ + pxCallback->pxCallbackFunction( pxCallback->pvParameter1, pxCallback->ulParameter2 ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* INCLUDE_xTimerPendFunctionCall */ + + /* Commands that are positive are timer commands rather than pended + * function calls. */ + if( xMessage.xMessageID >= ( BaseType_t ) 0 ) + { + /* The messages uses the xTimerParameters member to work on a + * software timer. */ + pxTimer = xMessage.u.xTimerParameters.pxTimer; + + if( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) == pdFALSE ) /*lint !e961. The cast is only redundant when NULL is passed into the macro. */ + { + /* The timer is in a list, remove it. */ + ( void ) uxListRemove( &( pxTimer->xTimerListItem ) ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceTIMER_COMMAND_RECEIVED( pxTimer, xMessage.xMessageID, xMessage.u.xTimerParameters.xMessageValue ); + + /* In this case the xTimerListsWereSwitched parameter is not used, but + * it must be present in the function call. prvSampleTimeNow() must be + * called after the message is received from xTimerQueue so there is no + * possibility of a higher priority task adding a message to the message + * queue with a time that is ahead of the timer daemon task (because it + * pre-empted the timer daemon task after the xTimeNow value was set). */ + xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched ); + + switch( xMessage.xMessageID ) + { + case tmrCOMMAND_START: + case tmrCOMMAND_START_FROM_ISR: + case tmrCOMMAND_RESET: + case tmrCOMMAND_RESET_FROM_ISR: + /* Start or restart a timer. */ + pxTimer->ucStatus |= tmrSTATUS_IS_ACTIVE; + + if( prvInsertTimerInActiveList( pxTimer, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, xTimeNow, xMessage.u.xTimerParameters.xMessageValue ) != pdFALSE ) + { + /* The timer expired before it was added to the active + * timer list. Process it now. */ + if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0 ) + { + prvReloadTimer( pxTimer, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, xTimeNow ); + } + else + { + pxTimer->ucStatus &= ( ( uint8_t ) ~tmrSTATUS_IS_ACTIVE ); + } + + /* Call the timer callback. */ + traceTIMER_EXPIRED( pxTimer ); + pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + break; + + case tmrCOMMAND_STOP: + case tmrCOMMAND_STOP_FROM_ISR: + /* The timer has already been removed from the active list. */ + pxTimer->ucStatus &= ( ( uint8_t ) ~tmrSTATUS_IS_ACTIVE ); + break; + + case tmrCOMMAND_CHANGE_PERIOD: + case tmrCOMMAND_CHANGE_PERIOD_FROM_ISR: + pxTimer->ucStatus |= tmrSTATUS_IS_ACTIVE; + pxTimer->xTimerPeriodInTicks = xMessage.u.xTimerParameters.xMessageValue; + configASSERT( ( pxTimer->xTimerPeriodInTicks > 0 ) ); + + /* The new period does not really have a reference, and can + * be longer or shorter than the old one. The command time is + * therefore set to the current time, and as the period cannot + * be zero the next expiry time can only be in the future, + * meaning (unlike for the xTimerStart() case above) there is + * no fail case that needs to be handled here. */ + ( void ) prvInsertTimerInActiveList( pxTimer, ( xTimeNow + pxTimer->xTimerPeriodInTicks ), xTimeNow, xTimeNow ); + break; + + case tmrCOMMAND_DELETE: + #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + { + /* The timer has already been removed from the active list, + * just free up the memory if the memory was dynamically + * allocated. */ + if( ( pxTimer->ucStatus & tmrSTATUS_IS_STATICALLY_ALLOCATED ) == ( uint8_t ) 0 ) + { + vPortFree( pxTimer ); + } + else + { + pxTimer->ucStatus &= ( ( uint8_t ) ~tmrSTATUS_IS_ACTIVE ); + } + } + #else /* if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) */ + { + /* If dynamic allocation is not enabled, the memory + * could not have been dynamically allocated. So there is + * no need to free the memory - just mark the timer as + * "not active". */ + pxTimer->ucStatus &= ( ( uint8_t ) ~tmrSTATUS_IS_ACTIVE ); + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + break; + + default: + /* Don't expect to get here. */ + break; + } + } + } + } +/*-----------------------------------------------------------*/ + + static void prvSwitchTimerLists( void ) + { + TickType_t xNextExpireTime; + List_t * pxTemp; + + /* The tick count has overflowed. The timer lists must be switched. + * If there are any timers still referenced from the current timer list + * then they must have expired and should be processed before the lists + * are switched. */ + while( listLIST_IS_EMPTY( pxCurrentTimerList ) == pdFALSE ) + { + xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList ); + + /* Process the expired timer. For auto-reload timers, be careful to + * process only expirations that occur on the current list. Further + * expirations must wait until after the lists are switched. */ + prvProcessExpiredTimer( xNextExpireTime, tmrMAX_TIME_BEFORE_OVERFLOW ); + } + + pxTemp = pxCurrentTimerList; + pxCurrentTimerList = pxOverflowTimerList; + pxOverflowTimerList = pxTemp; + } +/*-----------------------------------------------------------*/ + + static void prvCheckForValidListAndQueue( void ) + { + /* Check that the list from which active timers are referenced, and the + * queue used to communicate with the timer service, have been + * initialised. */ + taskENTER_CRITICAL(); + { + if( xTimerQueue == NULL ) + { + vListInitialise( &xActiveTimerList1 ); + vListInitialise( &xActiveTimerList2 ); + pxCurrentTimerList = &xActiveTimerList1; + pxOverflowTimerList = &xActiveTimerList2; + + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + /* The timer queue is allocated statically in case + * configSUPPORT_DYNAMIC_ALLOCATION is 0. */ + PRIVILEGED_DATA static StaticQueue_t xStaticTimerQueue; /*lint !e956 Ok to declare in this manner to prevent additional conditional compilation guards in other locations. */ + PRIVILEGED_DATA static uint8_t ucStaticTimerQueueStorage[ ( size_t ) configTIMER_QUEUE_LENGTH * sizeof( DaemonTaskMessage_t ) ]; /*lint !e956 Ok to declare in this manner to prevent additional conditional compilation guards in other locations. */ + + xTimerQueue = xQueueCreateStatic( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, ( UBaseType_t ) sizeof( DaemonTaskMessage_t ), &( ucStaticTimerQueueStorage[ 0 ] ), &xStaticTimerQueue ); + } + #else + { + xTimerQueue = xQueueCreate( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, sizeof( DaemonTaskMessage_t ) ); + } + #endif /* if ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ + + #if ( configQUEUE_REGISTRY_SIZE > 0 ) + { + if( xTimerQueue != NULL ) + { + vQueueAddToRegistry( xTimerQueue, "TmrQ" ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configQUEUE_REGISTRY_SIZE */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + } +/*-----------------------------------------------------------*/ + + BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer ) + { + BaseType_t xReturn; + Timer_t * pxTimer = xTimer; + + configASSERT( xTimer ); + + /* Is the timer in the list of active timers? */ + taskENTER_CRITICAL(); + { + if( ( pxTimer->ucStatus & tmrSTATUS_IS_ACTIVE ) == 0 ) + { + xReturn = pdFALSE; + } + else + { + xReturn = pdTRUE; + } + } + taskEXIT_CRITICAL(); + + return xReturn; + } /*lint !e818 Can't be pointer to const due to the typedef. */ +/*-----------------------------------------------------------*/ + + void * pvTimerGetTimerID( const TimerHandle_t xTimer ) + { + Timer_t * const pxTimer = xTimer; + void * pvReturn; + + configASSERT( xTimer ); + + taskENTER_CRITICAL(); + { + pvReturn = pxTimer->pvTimerID; + } + taskEXIT_CRITICAL(); + + return pvReturn; + } +/*-----------------------------------------------------------*/ + + void vTimerSetTimerID( TimerHandle_t xTimer, + void * pvNewID ) + { + Timer_t * const pxTimer = xTimer; + + configASSERT( xTimer ); + + taskENTER_CRITICAL(); + { + pxTimer->pvTimerID = pvNewID; + } + taskEXIT_CRITICAL(); + } +/*-----------------------------------------------------------*/ + + #if ( INCLUDE_xTimerPendFunctionCall == 1 ) + + BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, + void * pvParameter1, + uint32_t ulParameter2, + BaseType_t * pxHigherPriorityTaskWoken ) + { + DaemonTaskMessage_t xMessage; + BaseType_t xReturn; + + /* Complete the message with the function parameters and post it to the + * daemon task. */ + xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR; + xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend; + xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1; + xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2; + + xReturn = xQueueSendFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken ); + + tracePEND_FUNC_CALL_FROM_ISR( xFunctionToPend, pvParameter1, ulParameter2, xReturn ); + + return xReturn; + } + + #endif /* INCLUDE_xTimerPendFunctionCall */ +/*-----------------------------------------------------------*/ + + #if ( INCLUDE_xTimerPendFunctionCall == 1 ) + + BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, + void * pvParameter1, + uint32_t ulParameter2, + TickType_t xTicksToWait ) + { + DaemonTaskMessage_t xMessage; + BaseType_t xReturn; + + /* This function can only be called after a timer has been created or + * after the scheduler has been started because, until then, the timer + * queue does not exist. */ + configASSERT( xTimerQueue ); + + /* Complete the message with the function parameters and post it to the + * daemon task. */ + xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK; + xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend; + xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1; + xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2; + + xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait ); + + tracePEND_FUNC_CALL( xFunctionToPend, pvParameter1, ulParameter2, xReturn ); + + return xReturn; + } + + #endif /* INCLUDE_xTimerPendFunctionCall */ +/*-----------------------------------------------------------*/ + + #if ( configUSE_TRACE_FACILITY == 1 ) + + UBaseType_t uxTimerGetTimerNumber( TimerHandle_t xTimer ) + { + return ( ( Timer_t * ) xTimer )->uxTimerNumber; + } + + #endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + + #if ( configUSE_TRACE_FACILITY == 1 ) + + void vTimerSetTimerNumber( TimerHandle_t xTimer, + UBaseType_t uxTimerNumber ) + { + ( ( Timer_t * ) xTimer )->uxTimerNumber = uxTimerNumber; + } + + #endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +/* This entire source file will be skipped if the application is not configured + * to include software timer functionality. If you want to include software timer + * functionality then ensure configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */ +#endif /* configUSE_TIMERS == 1 */ diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/Core16550/core16550_regs.h b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/Core16550/core16550_regs.h new file mode 100644 index 0000000..44926d4 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/Core16550/core16550_regs.h @@ -0,0 +1,582 @@ +/******************************************************************************* + * (c) Copyright 2007-2015 Microsemi SoC Products Group. All rights reserved. + * + * IP core registers definitions. This file contains the definitions required + * for accessing the IP core through the hardware abstraction layer (HAL). + * This file was automatically generated, using "get_header.exe" version 0.4.0, + * from the IP-XACT description for: + * + * Core16550 version: 2.0.0 + * + * SVN $Revision: 7963 $ + * SVN $Date: 2015-10-09 17:58:21 +0530 (Fri, 09 Oct 2015) $ + * + *******************************************************************************/ +#ifndef CORE_16550_REGISTERS_H_ +#define CORE_16550_REGISTERS_H_ 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/******************************************************************************* + * RBR register: + *------------------------------------------------------------------------------ + * Receive Buffer Register + */ +#define RBR_REG_OFFSET 0x00U + +/******************************************************************************* + * THR register: + *------------------------------------------------------------------------------ + * Transmit Holding Register + */ +#define THR_REG_OFFSET 0x00U + +/******************************************************************************* + * DLR register: + *------------------------------------------------------------------------------ + * Divisor Latch(LSB) Register + */ +#define DLR_REG_OFFSET 0x00U + +/******************************************************************************* + * DMR register: + *------------------------------------------------------------------------------ + * Divisor Latch(MSB) Register + */ +#define DMR_REG_OFFSET 0x04U + +/******************************************************************************* + * IER register: + *------------------------------------------------------------------------------ + * Interrupt Enable Register + */ +#define IER_REG_OFFSET 0x04U + +/*------------------------------------------------------------------------------ + * IER_ERBFI: + * ERBFI field of register IER. + *------------------------------------------------------------------------------ + * Enables Received Data Available Interrupt. 0 - Disabled; 1 - Enabled + */ +#define IER_ERBFI_OFFSET 0x04U +#define IER_ERBFI_MASK 0x01U +#define IER_ERBFI_SHIFT 0U + +/*------------------------------------------------------------------------------ + * IER_ETBEI: + * ETBEI field of register IER. + *------------------------------------------------------------------------------ + * Enables the Transmitter Holding Register Empty Interrupt. 0 - Disabled; 1 - + * Enabled + */ +#define IER_ETBEI_OFFSET 0x04U +#define IER_ETBEI_MASK 0x02U +#define IER_ETBEI_SHIFT 1U + +/*------------------------------------------------------------------------------ + * IER_ELSI: + * ELSI field of register IER. + *------------------------------------------------------------------------------ + * Enables the Receiver Line Status Interrupt. 0 - Disabled; 1 - Enabled + */ +#define IER_ELSI_OFFSET 0x04U +#define IER_ELSI_MASK 0x04U +#define IER_ELSI_SHIFT 2U + +/*------------------------------------------------------------------------------ + * IER_EDSSI: + * EDSSI field of register IER. + *------------------------------------------------------------------------------ + * Enables the Modem Status Interrupt 0 - Disabled; 1 - Enabled + */ +#define IER_EDSSI_OFFSET 0x04U +#define IER_EDSSI_MASK 0x08U +#define IER_EDSSI_SHIFT 3U + +/******************************************************************************* + * IIR register: + *------------------------------------------------------------------------------ + * Interrupt Identification + */ +#define IIR_REG_OFFSET 0x08U + +/*------------------------------------------------------------------------------ + * IIR_IIR: + * IIR field of register IIR. + *------------------------------------------------------------------------------ + * Interrupt Identification bits. + */ +#define IIR_IIR_OFFSET 0x08U +#define IIR_IIR_MASK 0x0FU +#define IIR_IIR_SHIFT 0U + +/*------------------------------------------------------------------------------ + * IIR_IIR: + * IIR field of register IIR. + *------------------------------------------------------------------------------ + * Interrupt Identification bits. + */ + +/*------------------------------------------------------------------------------ + * IIR_Mode: + * Mode field of register IIR. + *------------------------------------------------------------------------------ + * 11 - FIFO mode + */ +#define IIR_MODE_OFFSET 0x08U +#define IIR_MODE_MASK 0xC0U +#define IIR_MODE_SHIFT 6U + +/******************************************************************************* + * FCR register: + *------------------------------------------------------------------------------ + * FIFO Control Register + */ +#define FCR_REG_OFFSET 0x08 + +/*------------------------------------------------------------------------------ + * FCR_Bit0: + * Bit0 field of register FCR. + *------------------------------------------------------------------------------ + * This bit enables both the TX and RX FIFOs. + */ +#define FCR_BIT0_OFFSET 0x08U +#define FCR_BIT0_MASK 0x01U +#define FCR_BIT0_SHIFT 0U + +#define FCR_ENABLE_OFFSET 0x08U +#define FCR_ENABLE_MASK 0x01U +#define FCR_ENABLE_SHIFT 0U + +/*------------------------------------------------------------------------------ + * FCR_Bit1: + * Bit1 field of register FCR. + *------------------------------------------------------------------------------ + * Clears all bytes in the RX FIFO and resets its counter logic. The shift + * register is not cleared. 0 - Disabled; 1 - Enabled + */ +#define FCR_BIT1_OFFSET 0x08U +#define FCR_BIT1_MASK 0x02U +#define FCR_BIT1_SHIFT 1U + +#define FCR_CLEAR_RX_OFFSET 0x08U +#define FCR_CLEAR_RX_MASK 0x02U +#define FCR_CLEAR_RX_SHIFT 1U + +/*------------------------------------------------------------------------------ + * FCR_Bit2: + * Bit2 field of register FCR. + *------------------------------------------------------------------------------ + * Clears all bytes in the TX FIFO and resets its counter logic. The shift + * register is not cleared. 0 - Disabled; 1 - Enabled + */ +#define FCR_BIT2_OFFSET 0x08U +#define FCR_BIT2_MASK 0x04U +#define FCR_BIT2_SHIFT 2U + +#define FCR_CLEAR_TX_OFFSET 0x08U +#define FCR_CLEAR_TX_MASK 0x04U +#define FCR_CLEAR_TX_SHIFT 2U + +/*------------------------------------------------------------------------------ + * FCR_Bit3: + * Bit3 field of register FCR. + *------------------------------------------------------------------------------ + * Enables RXRDYN and TXRDYN pins when set to 1. Otherwise, they are disabled. + */ +#define FCR_BIT3_OFFSET 0x08U +#define FCR_BIT3_MASK 0x08U +#define FCR_BIT3_SHIFT 3U + +#define FCR_RDYN_EN_OFFSET 0x08U +#define FCR_RDYN_EN_MASK 0x08U +#define FCR_RDYN_EN_SHIFT 3U + +/*------------------------------------------------------------------------------ + * FCR_Bit6: + * Bit6 field of register FCR. + *------------------------------------------------------------------------------ + * These bits are used to set the trigger level for the RX FIFO interrupt. RX + * FIFO Trigger Level: 0 - 1; 1 - 4; 2 - 8; 3 - 14 + */ +#define FCR_BIT6_OFFSET 0x08U +#define FCR_BIT6_MASK 0xC0U +#define FCR_BIT6_SHIFT 6U + +#define FCR_TRIG_LEVEL_OFFSET 0x08U +#define FCR_TRIG_LEVEL_MASK 0xC0U +#define FCR_TRIG_LEVEL_SHIFT 6U + +/******************************************************************************* + * LCR register: + *------------------------------------------------------------------------------ + * Line Control Register + */ +#define LCR_REG_OFFSET 0x0CU + +/*------------------------------------------------------------------------------ + * LCR_WLS: + * WLS field of register LCR. + *------------------------------------------------------------------------------ + * Word Length Select: 00 - 5 bits; 01 - 6 bits; 10 - 7 bits; 11 - 8 bits + */ +#define LCR_WLS_OFFSET 0x0CU +#define LCR_WLS_MASK 0x03U +#define LCR_WLS_SHIFT 0U + +/*------------------------------------------------------------------------------ + * LCR_STB: + * STB field of register LCR. + *------------------------------------------------------------------------------ + * Number of Stop Bits: 0 - 1 stop bit; 1 - 1½ stop bits when WLS = 00, 2 stop + * bits in other cases + */ +#define LCR_STB_OFFSET 0x0CU +#define LCR_STB_MASK 0x04U +#define LCR_STB_SHIFT 2U + +/*------------------------------------------------------------------------------ + * LCR_PEN: + * PEN field of register LCR. + *------------------------------------------------------------------------------ + * Parity Enable 0 - Disabled; 1 - Enabled. Parity is added in transmission and + * checked in receiving. + */ +#define LCR_PEN_OFFSET 0x0CU +#define LCR_PEN_MASK 0x08U +#define LCR_PEN_SHIFT 3U + +/*------------------------------------------------------------------------------ + * LCR_EPS: + * EPS field of register LCR. + *------------------------------------------------------------------------------ + * Even Parity Select 0 - Odd parity; 1 - Even parity + */ +#define LCR_EPS_OFFSET 0x0CU +#define LCR_EPS_MASK 0x10U +#define LCR_EPS_SHIFT 4U + +/*------------------------------------------------------------------------------ + * LCR_SP: + * SP field of register LCR. + *------------------------------------------------------------------------------ + * Stick Parity 0 - Disabled; 1 - Enabled When stick parity is enabled, it + * works as follows: Bits 4..3, 11 - 0 will be sent as a parity bit, and + * checked in receiving. 01 - 1 will be sent as a parity bit, and checked in + * receiving. + */ +#define LCR_SP_OFFSET 0x0CU +#define LCR_SP_MASK 0x20U +#define LCR_SP_SHIFT 5U + +/*------------------------------------------------------------------------------ + * LCR_SB: + * SB field of register LCR. + *------------------------------------------------------------------------------ + * Set Break 0 - Disabled 1 - Set break. SOUT is forced to 0. This does not + * have any effect on transmitter logic. The break is disabled by setting the + * bit to 0. + */ +#define LCR_SB_OFFSET 0x0CU +#define LCR_SB_MASK 0x40U +#define LCR_SB_SHIFT 6U + +/*------------------------------------------------------------------------------ + * LCR_DLAB: + * DLAB field of register LCR. + *------------------------------------------------------------------------------ + * Divisor Latch Access Bit 0 - Disabled. Normal addressing mode in use 1 - + * Enabled. Enables access to the Divisor Latch registers during read or write + * operation to addresses 0 and 1. + */ +#define LCR_DLAB_OFFSET 0x0CU +#define LCR_DLAB_MASK 0x80U +#define LCR_DLAB_SHIFT 7U + +/******************************************************************************* + * MCR register: + *------------------------------------------------------------------------------ + * Modem Control Register + */ +#define MCR_REG_OFFSET 0x10U + +/*------------------------------------------------------------------------------ + * MCR_DTR: + * DTR field of register MCR. + *------------------------------------------------------------------------------ + * Controls the Data Terminal Ready (DTRn) output. 0 - DTRn <= 1; 1 - DTRn <= 0 + */ +#define MCR_DTR_OFFSET 0x10U +#define MCR_DTR_MASK 0x01U +#define MCR_DTR_SHIFT 0U + +/*------------------------------------------------------------------------------ + * MCR_RTS: + * RTS field of register MCR. + *------------------------------------------------------------------------------ + * Controls the Request to Send (RTSn) output. 0 - RTSn <= 1; 1 - RTSn <= 0 + */ +#define MCR_RTS_OFFSET 0x10U +#define MCR_RTS_MASK 0x02U +#define MCR_RTS_SHIFT 1U + +/*------------------------------------------------------------------------------ + * MCR_Out1: + * Out1 field of register MCR. + *------------------------------------------------------------------------------ + * Controls the Output1 (OUT1n) signal. 0 - OUT1n <= 1; 1 - OUT1n <= 0 + */ +#define MCR_OUT1_OFFSET 0x10U +#define MCR_OUT1_MASK 0x04U +#define MCR_OUT1_SHIFT 2U + +/*------------------------------------------------------------------------------ + * MCR_Out2: + * Out2 field of register MCR. + *------------------------------------------------------------------------------ + * Controls the Output2 (OUT2n) signal. 0 - OUT2n <=1; 1 - OUT2n <=0 + */ +#define MCR_OUT2_OFFSET 0x10U +#define MCR_OUT2_MASK 0x08U +#define MCR_OUT2_SHIFT 3U + +/*------------------------------------------------------------------------------ + * MCR_Loop: + * Loop field of register MCR. + *------------------------------------------------------------------------------ + * Loop enable bit 0 - Disabled; 1 - Enabled. The following happens in loop + * mode: SOUT is set to 1. The SIN, DSRn, CTSn, RIn, and DCDn inputs are + * disconnected. The output of the Transmitter Shift Register is looped back + * into the Receiver Shift Register. The modem control outputs (DTRn, RTSn, + * OUT1n, and OUT2n) are connected internally to the modem control inputs, and + * the modem control output pins are set at 1. In loopback mode, the + * transmitted data is immediately received, allowing the CPU to check the + * operation of the UART. The interrupts are operating in loop mode. + */ +#define MCR_LOOP_OFFSET 0x10U +#define MCR_LOOP_MASK 0x10U +#define MCR_LOOP_SHIFT 4U + +/******************************************************************************* + * LSR register: + *------------------------------------------------------------------------------ + * Line Status Register + */ +#define LSR_REG_OFFSET 0x14U + +/*------------------------------------------------------------------------------ + * LSR_DR: + * DR field of register LSR. + *------------------------------------------------------------------------------ + * Data Ready indicator 1 when a data byte has been received and stored in the + * FIFO. DR is cleared to 0 when the CPU reads the data from the FIFO. + */ +#define LSR_DR_OFFSET 0x14U +#define LSR_DR_MASK 0x01U +#define LSR_DR_SHIFT 0U + +/*------------------------------------------------------------------------------ + * LSR_OE: + * OE field of register LSR. + *------------------------------------------------------------------------------ + * Overrun Error indicator Indicates that the new byte was received before the + * CPU read the byte from the receive buffer, and that the earlier data byte + * was destroyed. OE is cleared when the CPU reads the Line Status Register. If + * the data continues to fill the FIFO beyond the trigger level, an overrun + * error will occur once the FIFO is full and the next character has been + * completely received in the shift register. The character in the shift + * register is overwritten, but it is not transferred to the FIFO. + */ +#define LSR_OE_OFFSET 0x14U +#define LSR_OE_MASK 0x02U +#define LSR_OE_SHIFT 1U + +/*------------------------------------------------------------------------------ + * LSR_PE: + * PE field of register LSR. + *------------------------------------------------------------------------------ + * Parity Error indicator Indicates that the received byte had a parity error. + * PE is cleared when the CPU reads the Line Status Register. This error is + * revealed to the CPU when its associated character is at the top of the FIFO. + */ +#define LSR_PE_OFFSET 0x14U +#define LSR_PE_MASK 0x04U +#define LSR_PE_SHIFT 2U + +/*------------------------------------------------------------------------------ + * LSR_FE: + * FE field of register LSR. + *------------------------------------------------------------------------------ + * Framing Error indicator Indicates that the received byte did not have a + * valid Stop bit. FE is cleared when the CPU reads the Line Status Register. + * The UART will try to re-synchronize after a framing error. To do this, it + * assumes that the framing error was due to the next start bit, so it samples + * this start bit twice, and then starts receiving the data. This error is + * revealed to the CPU when its associated character is at the top of the FIFO. + */ +#define LSR_FE_OFFSET 0x14U +#define LSR_FE_MASK 0x08U +#define LSR_FE_SHIFT 3U + +/*------------------------------------------------------------------------------ + * LSR_BI: + * BI field of register LSR. + *------------------------------------------------------------------------------ + * Break Interrupt indicator Indicates that the received data is at 0 longer + * than a full word transmission time (start bit + data bits + parity + stop + * bits). BI is cleared when the CPU reads the Line Status Register. This error + * is revealed to the CPU when its associated character is at the top of the + * FIFO. When break occurs, only one zero character is loaded into the FIFO. + */ +#define LSR_BI_OFFSET 0x14U +#define LSR_BI_MASK 0x10U +#define LSR_BI_SHIFT 4U + +/*------------------------------------------------------------------------------ + * LSR_THRE: + * THRE field of register LSR. + *------------------------------------------------------------------------------ + * Transmitter Holding Register Empty indicator Indicates that the UART is + * ready to transmit a new data byte. THRE causes an interrupt to the CPU when + * bit 1 (ETBEI) in the Interrupt Enable Register is 1. This bit is set when + * the TX FIFO is empty. It is cleared when at least one byte is written to the + * TX FIFO. + */ +#define LSR_THRE_OFFSET 0x14U +#define LSR_THRE_MASK 0x20U +#define LSR_THRE_SHIFT 5U + +/*------------------------------------------------------------------------------ + * LSR_TEMT: + * TEMT field of register LSR. + *------------------------------------------------------------------------------ + * Transmitter Empty indicator This bit is set to 1 when both the transmitter + * FIFO and shift registers are empty. + */ +#define LSR_TEMT_OFFSET 0x14U +#define LSR_TEMT_MASK 0x40U +#define LSR_TEMT_SHIFT 6U + +/*------------------------------------------------------------------------------ + * LSR_FIER: + * FIER field of register LSR. + *------------------------------------------------------------------------------ + * This bit is set when there is at least one parity error, framing error, or + * break indication in the FIFO. FIER is cleared when the CPU reads the LSR if + * there are no subsequent errors in the FIFO. + */ +#define LSR_FIER_OFFSET 0x14U +#define LSR_FIER_MASK 0x80U +#define LSR_FIER_SHIFT 7U + +/******************************************************************************* + * MSR register: + *------------------------------------------------------------------------------ + * Modem Status Register + */ +#define MSR_REG_OFFSET 0x18U + +/*------------------------------------------------------------------------------ + * MSR_DCTS: + * DCTS field of register MSR. + *------------------------------------------------------------------------------ + * Delta Clear to Send indicator. Indicates that the CTSn input has changed + * state since the last time it was read by the CPU. + */ +#define MSR_DCTS_OFFSET 0x18U +#define MSR_DCTS_MASK 0x01U +#define MSR_DCTS_SHIFT 0U + +/*------------------------------------------------------------------------------ + * MSR_DDSR: + * DDSR field of register MSR. + *------------------------------------------------------------------------------ + * Delta Data Set Ready indicator Indicates that the DSRn input has changed + * state since the last time it was read by the CPU. + */ +#define MSR_DDSR_OFFSET 0x18U +#define MSR_DDSR_MASK 0x02U +#define MSR_DDSR_SHIFT 1U + +/*------------------------------------------------------------------------------ + * MSR_TERI: + * TERI field of register MSR. + *------------------------------------------------------------------------------ + * Trailing Edge of Ring Indicator detector. Indicates that RI input has + * changed from 0 to 1. + */ +#define MSR_TERI_OFFSET 0x18U +#define MSR_TERI_MASK 0x04U +#define MSR_TERI_SHIFT 2U + +/*------------------------------------------------------------------------------ + * MSR_DDCD: + * DDCD field of register MSR. + *------------------------------------------------------------------------------ + * Delta Data Carrier Detect indicator Indicates that DCD input has changed + * state. NOTE: Whenever bit 0, 1, 2, or 3 is set to 1, a Modem Status + * Interrupt is generated. + */ +#define MSR_DDCD_OFFSET 0x18U +#define MSR_DDCD_MASK 0x08U +#define MSR_DDCD_SHIFT 3U + +/*------------------------------------------------------------------------------ + * MSR_CTS: + * CTS field of register MSR. + *------------------------------------------------------------------------------ + * Clear to Send The complement of the CTSn input. When bit 4 of the Modem + * Control Register (MCR) is set to 1 (loop), this bit is equivalent to DTR in + * the MCR. + */ +#define MSR_CTS_OFFSET 0x18U +#define MSR_CTS_MASK 0x10U +#define MSR_CTS_SHIFT 4U + +/*------------------------------------------------------------------------------ + * MSR_DSR: + * DSR field of register MSR. + *------------------------------------------------------------------------------ + * Data Set Ready The complement of the DSR input. When bit 4 of the MCR is set + * to 1 (loop), this bit is equivalent to RTSn in the MCR. + */ +#define MSR_DSR_OFFSET 0x18U +#define MSR_DSR_MASK 0x20U +#define MSR_DSR_SHIFT 5U + +/*------------------------------------------------------------------------------ + * MSR_RI: + * RI field of register MSR. + *------------------------------------------------------------------------------ + * Ring Indicator The complement of the RIn input. When bit 4 of the MCR is set + * to 1 (loop), this bit is equivalent to OUT1 in the MCR. + */ +#define MSR_RI_OFFSET 0x18U +#define MSR_RI_MASK 0x40U +#define MSR_RI_SHIFT 6U + +/*------------------------------------------------------------------------------ + * MSR_DCD: + * DCD field of register MSR. + *------------------------------------------------------------------------------ + * Data Carrier Detect The complement of DCDn input. When bit 4 of the MCR is + * set to 1 (loop), this bit is equivalent to OUT2 in the MCR. + */ +#define MSR_DCD_OFFSET 0x18U +#define MSR_DCD_MASK 0x80U +#define MSR_DCD_SHIFT 7U + +/******************************************************************************* + * SR register: + *------------------------------------------------------------------------------ + * Scratch Register + */ +#define SR_REG_OFFSET 0x1CU + +#ifdef __cplusplus +} +#endif + +#endif /* CORE_16550_REGISTERS_H_*/ diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/Core16550/core_16550.c b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/Core16550/core_16550.c new file mode 100644 index 0000000..c87ac00 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/Core16550/core_16550.c @@ -0,0 +1,865 @@ +/******************************************************************************* + * (c) Copyright 2007-2015 Microsemi SoC Products Group. All rights reserved. + * + * Core16550 driver implementation. See file "core_16550.h" for a + * description of the functions implemented in this file. + * + * SVN $Revision: 7963 $ + * SVN $Date: 2015-10-09 17:58:21 +0530 (Fri, 09 Oct 2015) $ + */ +#include "hal/hal.h" +#include "drivers/fpga_ip/Core16550/core_16550.h" +#include "drivers/fpga_ip/Core16550/core16550_regs.h" +#include "hal/hal_assert.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/******************************************************************************* + * Definitions for transmitter states + */ +#define TX_COMPLETE 0x00U + +/******************************************************************************* + * Definition for transmitter FIFO size + */ +#define TX_FIFO_SIZE 16U + +/******************************************************************************* + * Default receive interrupt trigger level + */ +#define DEFAULT_RX_TRIG_LEVEL ((uint8_t)UART_16550_FIFO_SINGLE_BYTE) + +/******************************************************************************* + * Receiver error status mask and shift offset + */ +#define STATUS_ERROR_MASK ( LSR_OE_MASK | LSR_PE_MASK | \ + LSR_FE_MASK | LSR_BI_MASK | LSR_FIER_MASK) + +/******************************************************************************* + * Definitions for invalid parameters with proper type + */ +#define INVALID_INTERRUPT 0U +#define INVALID_IRQ_HANDLER ( (uart_16550_irq_handler_t) 0 ) + +/******************************************************************************* + * Possible values for Interrupt Identification Register Field. + */ +#define IIRF_MODEM_STATUS 0x00U +#define IIRF_THRE 0x02U +#define IIRF_RX_DATA 0x04U +#define IIRF_RX_LINE_STATUS 0x06U +#define IIRF_DATA_TIMEOUT 0x0CU + +/******************************************************************************* + * Null parameters with appropriate type definitions + */ +#define NULL_ADDR ( ( addr_t ) 0 ) +#define NULL_INSTANCE ( ( uart_16550_instance_t * ) 0 ) +#define NULL_BUFF ( ( uint8_t * ) 0 ) + +/******************************************************************************* + * Possible states for different register bit fields + */ +enum { + DISABLE = 0U, + ENABLE = 1U +}; + +/******************************************************************************* + * Static function declarations + */ +static void default_tx_handler(uart_16550_instance_t * this_uart); + +/******************************************************************************* + * Public function definitions + */ + +/***************************************************************************//** + * UART_16550_init. + * See core_16550.h for details of how to use this function. + */ +void +UART_16550_init +( + uart_16550_instance_t* this_uart, + addr_t base_addr, + uint16_t baud_value, + uint8_t line_config +) +{ +#ifndef NDEBUG + uint8_t dbg1; + uint8_t dbg2; +#endif + uint8_t fifo_config; + uint8_t temp; + + HAL_ASSERT( base_addr != NULL_ADDR ); + HAL_ASSERT( this_uart != NULL_INSTANCE ); + + if( ( base_addr != NULL_ADDR ) && ( this_uart != NULL_INSTANCE ) ) + { + /* disable interrupts */ + HAL_set_8bit_reg(base_addr, IER, DISABLE); + + /* reset divisor latch */ + HAL_set_8bit_reg_field(base_addr, LCR_DLAB, ENABLE); +#ifndef NDEBUG + dbg1 = HAL_get_8bit_reg_field(base_addr, LCR_DLAB ); + HAL_ASSERT( dbg1 == ENABLE ); +#endif + /* MSB of baud value */ + temp = (uint8_t)(baud_value >> 8); + HAL_set_8bit_reg(base_addr, DMR, temp ); + /* LSB of baud value */ + HAL_set_8bit_reg(base_addr, DLR, ( (uint8_t)baud_value ) ); +#ifndef NDEBUG + dbg1 = HAL_get_8bit_reg(base_addr, DMR ); + dbg2 = HAL_get_8bit_reg(base_addr, DLR ); + HAL_ASSERT( ( ( ( (uint16_t) dbg1 ) << 8 ) | dbg2 ) == baud_value ); +#endif + /* reset divisor latch */ + HAL_set_8bit_reg_field(base_addr, LCR_DLAB, DISABLE); +#ifndef NDEBUG + dbg1 = HAL_get_8bit_reg_field(base_addr, LCR_DLAB ); + HAL_ASSERT( dbg1 == DISABLE ); +#endif + /* set the line control register (bit length, stop bits, parity) */ + HAL_set_8bit_reg( base_addr, LCR, line_config ); +#ifndef NDEBUG + dbg1 = HAL_get_8bit_reg(base_addr, LCR ); + HAL_ASSERT( dbg1 == line_config) +#endif + /* Enable and configure the RX and TX FIFOs. */ + fifo_config = ((uint8_t)(DEFAULT_RX_TRIG_LEVEL << FCR_TRIG_LEVEL_SHIFT) | + FCR_RDYN_EN_MASK | FCR_CLEAR_RX_MASK | + FCR_CLEAR_TX_MASK | FCR_ENABLE_MASK ); + HAL_set_8bit_reg( base_addr, FCR, fifo_config ); + + /* disable loopback */ + HAL_set_8bit_reg_field( base_addr, MCR_LOOP, DISABLE ); +#ifndef NDEBUG + dbg1 = HAL_get_8bit_reg_field(base_addr, MCR_LOOP); + HAL_ASSERT( dbg1 == DISABLE ); +#endif + + /* Instance setup */ + this_uart->base_address = base_addr; + this_uart->tx_buffer = NULL_BUFF; + this_uart->tx_buff_size = TX_COMPLETE; + this_uart->tx_idx = 0U; + this_uart->tx_handler = default_tx_handler; + + this_uart->rx_handler = ( (uart_16550_irq_handler_t) 0 ); + this_uart->linests_handler = ( (uart_16550_irq_handler_t) 0 ); + this_uart->modemsts_handler = ( (uart_16550_irq_handler_t) 0 ); + this_uart->status = 0U; + } +} + +/***************************************************************************//** + * UART_16550_polled_tx. + * See core_16550.h for details of how to use this function. + */ +void +UART_16550_polled_tx +( + uart_16550_instance_t * this_uart, + const uint8_t * pbuff, + uint32_t tx_size +) +{ + uint32_t char_idx = 0U; + uint32_t size_sent; + uint8_t status; + + HAL_ASSERT( this_uart != NULL_INSTANCE ); + HAL_ASSERT( pbuff != NULL_BUFF ); + HAL_ASSERT( tx_size > 0U ); + + if( ( this_uart != NULL_INSTANCE ) && + ( pbuff != NULL_BUFF ) && + ( tx_size > 0U ) ) + { + /* Remain in this loop until the entire input buffer + * has been transferred to the UART. + */ + do { + /* Read the Line Status Register and update the sticky record */ + status = HAL_get_8bit_reg( this_uart->base_address, LSR ); + this_uart->status |= status; + + /* Check if TX FIFO is empty. */ + if( status & LSR_THRE_MASK ) + { + uint32_t fill_size = TX_FIFO_SIZE; + + /* Calculate the number of bytes to transmit. */ + if ( tx_size < TX_FIFO_SIZE ) + { + fill_size = tx_size; + } + + /* Fill the TX FIFO with the calculated the number of bytes. */ + for ( size_sent = 0U; size_sent < fill_size; ++size_sent ) + { + /* Send next character in the buffer. */ + HAL_set_8bit_reg( this_uart->base_address, THR, + (uint_fast8_t)pbuff[char_idx++]); + } + + /* Calculate the number of untransmitted bytes remaining. */ + tx_size -= size_sent; + } + } while ( tx_size ); + } +} + +/***************************************************************************//** + * UART_16550_polled_tx_string. + * See core_16550.h for details of how to use this function. + */ +void +UART_16550_polled_tx_string +( + uart_16550_instance_t * this_uart, + const uint8_t * p_sz_string +) +{ + uint32_t char_idx = 0U; + uint32_t fill_size; + uint_fast8_t data_byte; + uint8_t status; + + HAL_ASSERT( this_uart != NULL_INSTANCE ); + HAL_ASSERT( p_sz_string != NULL_BUFF ); + + if( ( this_uart != NULL_INSTANCE ) && ( p_sz_string != NULL_BUFF ) ) + { + char_idx = 0U; + + /* Get the first data byte from the input buffer */ + data_byte = (uint_fast8_t)p_sz_string[char_idx]; + + /* First check for the NULL terminator byte. + * Then remain in this loop until the entire string in the input buffer + * has been transferred to the UART. + */ + while ( 0U != data_byte ) + { + /* Wait until TX FIFO is empty. */ + do { + status = HAL_get_8bit_reg( this_uart->base_address,LSR); + this_uart->status |= status; + } while ( !( status & LSR_THRE_MASK ) ); + + /* Send bytes from the input buffer until the TX FIFO is full + * or we reach the NULL terminator byte. + */ + fill_size = 0U; + while ( (0U != data_byte) && (fill_size < TX_FIFO_SIZE) ) + { + /* Send the data byte */ + HAL_set_8bit_reg( this_uart->base_address, THR, data_byte ); + ++fill_size; + char_idx++; + /* Get the next data byte from the input buffer */ + data_byte = (uint_fast8_t)p_sz_string[char_idx]; + } + } + } +} + + +/***************************************************************************//** + * UART_16550_irq_tx. + * See core_16550.h for details of how to use this function. + */ +void +UART_16550_irq_tx +( + uart_16550_instance_t * this_uart, + const uint8_t * pbuff, + uint32_t tx_size +) +{ + HAL_ASSERT( this_uart != NULL_INSTANCE ) + HAL_ASSERT( pbuff != NULL_BUFF ) + HAL_ASSERT( tx_size > 0U ) + + if( ( this_uart != NULL_INSTANCE ) && + ( pbuff != NULL_BUFF ) && + ( tx_size > 0U ) ) + { + /*Initialize the UART instance with + parameters required for transmission.*/ + this_uart->tx_buffer = pbuff; + this_uart->tx_buff_size = tx_size; + /* char_idx; */ + this_uart->tx_idx = 0U; + /* assign handler for default data transmission */ + this_uart->tx_handler = default_tx_handler; + + /* enables TX interrupt */ + HAL_set_8bit_reg_field(this_uart->base_address, IER_ETBEI, ENABLE); + } +} + +/***************************************************************************//** + * UART_16550_tx_complete. + * See core_16550.h for details of how to use this function. + */ +int8_t +UART_16550_tx_complete +( + uart_16550_instance_t * this_uart +) +{ + int8_t returnvalue = 0; + uint8_t status = 0U; + + HAL_ASSERT( this_uart != NULL_INSTANCE ) + + if( this_uart != NULL_INSTANCE ) + { + status = HAL_get_8bit_reg(this_uart->base_address,LSR); + this_uart->status |= status; + + if( ( this_uart->tx_buff_size == TX_COMPLETE ) && + ( status & LSR_TEMT_MASK ) ) + { + returnvalue = (int8_t)1; + } + } + return returnvalue; +} + + +/***************************************************************************//** + * UART_16550_get_rx. + * See core_16550.h for details of how to use this function. + */ +size_t +UART_16550_get_rx +( + uart_16550_instance_t * this_uart, + uint8_t * rx_buff, + size_t buff_size +) +{ + uint8_t status; + size_t rx_size = 0U; + + HAL_ASSERT( this_uart != NULL_INSTANCE ) + HAL_ASSERT( rx_buff != (uint8_t *)0 ) + HAL_ASSERT( buff_size > 0U ) + + if( ( this_uart != NULL_INSTANCE ) && + ( rx_buff != (uint8_t *)0 ) && + ( buff_size > 0U ) ) + { + status = HAL_get_8bit_reg( this_uart->base_address, LSR ); + this_uart->status |= status; + while ( ((status & LSR_DR_MASK) != 0U) && ( rx_size < buff_size ) ) + { + rx_buff[rx_size] = HAL_get_8bit_reg( this_uart->base_address, RBR ); + rx_size++; + status = HAL_get_8bit_reg( this_uart->base_address, LSR ); + this_uart->status |= status; + } + } + return rx_size; +} + +/***************************************************************************//** + * UART_16550_isr. + * See core_16550.h for details of how to use this function. + */ +void +UART_16550_isr +( + uart_16550_instance_t * this_uart +) +{ + uint8_t iirf; + + HAL_ASSERT( this_uart != NULL_INSTANCE ) + + if(this_uart != NULL_INSTANCE ) + { + iirf = HAL_get_8bit_reg_field( this_uart->base_address, IIR_IIR ); + + switch ( iirf ) + { + /* Modem status interrupt */ + case IIRF_MODEM_STATUS: + { + if( INVALID_IRQ_HANDLER != this_uart->modemsts_handler ) + { + HAL_ASSERT( INVALID_IRQ_HANDLER != this_uart->modemsts_handler ); + if( INVALID_IRQ_HANDLER != this_uart->modemsts_handler ) + { + (*(this_uart->modemsts_handler))(this_uart); + } + } + } + break; + /* Transmitter Holding Register Empty interrupt */ + case IIRF_THRE: + { + HAL_ASSERT( INVALID_IRQ_HANDLER != this_uart->tx_handler ); + if ( INVALID_IRQ_HANDLER != this_uart->tx_handler ) + { + (*(this_uart->tx_handler))(this_uart); + } + } + break; + /* Received Data Available interrupt */ + case IIRF_RX_DATA: + case IIRF_DATA_TIMEOUT: + { + HAL_ASSERT( INVALID_IRQ_HANDLER != this_uart->rx_handler ); + if ( INVALID_IRQ_HANDLER != this_uart->rx_handler ) + { + (*(this_uart->rx_handler))(this_uart); + } + } + break; + /* Line status interrupt */ + case IIRF_RX_LINE_STATUS: + { + HAL_ASSERT( INVALID_IRQ_HANDLER != this_uart->linests_handler ); + if ( INVALID_IRQ_HANDLER != this_uart->linests_handler ) + { + (*(this_uart->linests_handler))(this_uart); + } + } + break; + /* Unidentified interrupt */ + default: + { + HAL_ASSERT( INVALID_INTERRUPT ) + } + } + } +} + +/***************************************************************************//** + * UART_16550_set_rx_handler. + * See core_16550.h for details of how to use this function. + */ +void +UART_16550_set_rx_handler +( + uart_16550_instance_t * this_uart, + uart_16550_irq_handler_t handler, + uart_16550_rx_trig_level_t trigger_level +) +{ + HAL_ASSERT( this_uart != NULL_INSTANCE ) + HAL_ASSERT( handler != INVALID_IRQ_HANDLER) + HAL_ASSERT( trigger_level < UART_16550_FIFO_INVALID_TRIG_LEVEL) + + if( ( this_uart != NULL_INSTANCE ) && + ( handler != INVALID_IRQ_HANDLER) && + ( trigger_level < UART_16550_FIFO_INVALID_TRIG_LEVEL) ) + { + this_uart->rx_handler = handler; + + /* Set the receive interrupt trigger level. */ + HAL_set_8bit_reg_field( this_uart->base_address, + FCR_TRIG_LEVEL, trigger_level ); + + /* Enable receive interrupt. */ + HAL_set_8bit_reg_field( this_uart->base_address, IER_ERBFI, ENABLE ); + } +} + +/***************************************************************************//** + * UART_16550_set_loopback. + * See core_16550.h for details of how to use this function. + */ +void +UART_16550_set_loopback +( + uart_16550_instance_t * this_uart, + uart_16550_loopback_t loopback +) +{ + HAL_ASSERT( this_uart != NULL_INSTANCE ); + HAL_ASSERT( loopback < UART_16550_INVALID_LOOPBACK ); + + if( ( this_uart != NULL_INSTANCE ) && + ( loopback < UART_16550_INVALID_LOOPBACK ) ) + { + if ( loopback == UART_16550_LOOPBACK_OFF ) + { + HAL_set_8bit_reg_field( this_uart->base_address, + MCR_LOOP, + DISABLE ); + } + else + { + HAL_set_8bit_reg_field( this_uart->base_address, + MCR_LOOP, + ENABLE ); + } + } +} + +/***************************************************************************//** + * UART_16550_get_rx_status. + * See core_16550.h for details of how to use this function. + */ +uint8_t +UART_16550_get_rx_status +( + uart_16550_instance_t * this_uart +) +{ + uint8_t status = UART_16550_INVALID_PARAM; + HAL_ASSERT( this_uart != NULL_INSTANCE ); + + if( ( this_uart != NULL_INSTANCE ) ) + { + /* + * Bit 1 - Overflow error status + * Bit 2 - Parity error status + * Bit 3 - Frame error status + * Bit 4 - Break interrupt indicator + * Bit 7 - FIFO data error status + */ + this_uart->status |= HAL_get_8bit_reg( this_uart->base_address, LSR ); + status = ( this_uart->status & STATUS_ERROR_MASK ); + /* + * Clear the sticky status for this instance. + */ + this_uart->status = (uint8_t)0; + } + return status; +} + +/***************************************************************************//** + * UART_16550_get_modem_status. + * See core_16550.h for details of how to use this function. + */ +uint8_t +UART_16550_get_modem_status +( + uart_16550_instance_t * this_uart +) +{ + uint8_t status = UART_16550_NO_ERROR; + HAL_ASSERT( this_uart != NULL_INSTANCE ) + + if( ( this_uart != NULL_INSTANCE ) ) + { + /* + * Extract UART error status and place in lower bits of "status". + * Bit 0 - Delta Clear to Send Indicator + * Bit 1 - Delta Clear to Receive Indicator + * Bit 2 - Trailing edge of Ring Indicator detector + * Bit 3 - Delta Data Carrier Detect indicator + * Bit 4 - Clear To Send + * Bit 5 - Data Set Ready + * Bit 6 - Ring Indicator + * Bit 7 - Data Carrier Detect + */ + status = HAL_get_8bit_reg( this_uart->base_address, MSR ); + } + return status; +} + +/***************************************************************************//** + * Default TX interrupt handler to automatically transmit data from + * user assgined TX buffer. + */ +static void +default_tx_handler +( + uart_16550_instance_t * this_uart +) +{ + uint8_t status; + + HAL_ASSERT( NULL_INSTANCE != this_uart ) + + if ( this_uart != NULL_INSTANCE ) + { + HAL_ASSERT( NULL_BUFF != this_uart->tx_buffer ) + HAL_ASSERT( 0U != this_uart->tx_buff_size ) + + if ( ( this_uart->tx_buffer != NULL_BUFF ) && + ( 0U != this_uart->tx_buff_size ) ) + { + /* Read the Line Status Register and update the sticky record. */ + status = HAL_get_8bit_reg( this_uart->base_address,LSR); + this_uart->status |= status; + + /* + * This function should only be called as a result of a THRE interrupt. + * Verify that this is true before proceeding to transmit data. + */ + if ( status & LSR_THRE_MASK ) + { + uint32_t size_sent = 0U; + uint32_t fill_size = TX_FIFO_SIZE; + uint32_t tx_remain = this_uart->tx_buff_size - this_uart->tx_idx; + + /* Calculate the number of bytes to transmit. */ + if ( tx_remain < TX_FIFO_SIZE ) + { + fill_size = tx_remain; + } + + /* Fill the TX FIFO with the calculated the number of bytes. */ + for ( size_sent = 0U; size_sent < fill_size; ++size_sent ) + { + /* Send next character in the buffer. */ + HAL_set_8bit_reg( this_uart->base_address, THR, + (uint_fast8_t)this_uart->tx_buffer[this_uart->tx_idx]); + ++this_uart->tx_idx; + } + } + + /* Flag Tx as complete if all data has been pushed into the Tx FIFO. */ + if ( this_uart->tx_idx == this_uart->tx_buff_size ) + { + this_uart->tx_buff_size = TX_COMPLETE; + /* disables TX interrupt */ + HAL_set_8bit_reg_field( this_uart->base_address, + IER_ETBEI, DISABLE); + } + } + } +} + +/***************************************************************************//** + * UART_16550_enable_irq. + * See core_16550.h for details of how to use this function. + */ +void +UART_16550_enable_irq +( + uart_16550_instance_t * this_uart, + uint8_t irq_mask +) +{ + HAL_ASSERT( this_uart != NULL_INSTANCE ) + + if( this_uart != NULL_INSTANCE ) + { + /* irq_mask encoding: 1- enable + * bit 0 - Receive Data Available Interrupt + * bit 1 - Transmitter Holding Register Empty Interrupt + * bit 2 - Receiver Line Status Interrupt + * bit 3 - Modem Status Interrupt + */ + /* read present interrupts for enabled ones*/ + irq_mask |= HAL_get_8bit_reg( this_uart->base_address, IER ); + /* Enable interrupts */ + HAL_set_8bit_reg( this_uart->base_address, IER, irq_mask ); + } +} + +/***************************************************************************//** + * UART_16550_disable_irq. + * See core_16550.h for details of how to use this function. + */ +void +UART_16550_disable_irq +( + uart_16550_instance_t * this_uart, + uint8_t irq_mask +) +{ + HAL_ASSERT( this_uart != NULL_INSTANCE ) + + if( this_uart != NULL_INSTANCE ) + { + /* irq_mask encoding: 1 - disable + * bit 0 - Receive Data Available Interrupt + * bit 1 - Transmitter Holding Register Empty Interrupt + * bit 2 - Receiver Line Status Interrupt + * bit 3 - Modem Status Interrupt + */ + /* read present interrupts for enabled ones */ + irq_mask = (( (uint8_t)~irq_mask ) & + HAL_get_8bit_reg( this_uart->base_address, IER )); + /* Disable interrupts */ + HAL_set_8bit_reg( this_uart->base_address, IER, irq_mask ); + } +} + +/***************************************************************************//** + * UART_16550_set_rxstatus_handler. + * See core_16550.h for details of how to use this function. + */ +void +UART_16550_set_rxstatus_handler +( + uart_16550_instance_t * this_uart, + uart_16550_irq_handler_t handler +) +{ + HAL_ASSERT( this_uart != NULL_INSTANCE ) + HAL_ASSERT( handler != INVALID_IRQ_HANDLER) + + if( ( this_uart != NULL_INSTANCE ) && + ( handler != INVALID_IRQ_HANDLER) ) + { + this_uart->linests_handler = handler; + /* Enable receiver line status interrupt. */ + HAL_set_8bit_reg_field( this_uart->base_address, IER_ELSI, ENABLE ); + } +} + +/***************************************************************************//** + * UART_16550_set_tx_handler. + * See core_16550.h for details of how to use this function. + */ +void +UART_16550_set_tx_handler +( + uart_16550_instance_t * this_uart, + uart_16550_irq_handler_t handler +) +{ + HAL_ASSERT( this_uart != NULL_INSTANCE ) + HAL_ASSERT( handler != INVALID_IRQ_HANDLER) + + if( ( this_uart != NULL_INSTANCE ) && + ( handler != INVALID_IRQ_HANDLER) ) + { + this_uart->tx_handler = handler; + + /* Make TX buffer info invalid */ + this_uart->tx_buffer = NULL_BUFF; + this_uart->tx_buff_size = 0U; + + /* Enable transmitter holding register Empty interrupt. */ + HAL_set_8bit_reg_field( this_uart->base_address, IER_ETBEI, ENABLE ); + } +} + +/***************************************************************************//** + * UART_16550_set_modemstatus_handler. + * See core_16550.h for details of how to use this function. + */ +void +UART_16550_set_modemstatus_handler +( + uart_16550_instance_t * this_uart, + uart_16550_irq_handler_t handler +) +{ + HAL_ASSERT( this_uart != NULL_INSTANCE ) + HAL_ASSERT( handler != INVALID_IRQ_HANDLER) + + if( ( this_uart != NULL_INSTANCE ) && + ( handler != INVALID_IRQ_HANDLER) ) + { + this_uart->modemsts_handler = handler; + /* Enable modem status interrupt. */ + HAL_set_8bit_reg_field( this_uart->base_address, IER_EDSSI, ENABLE ); + } +} + +/***************************************************************************//** + * UART_16550_fill_tx_fifo. + * See core_16550.h for details of how to use this function. + */ +size_t +UART_16550_fill_tx_fifo +( + uart_16550_instance_t * this_uart, + const uint8_t * tx_buffer, + size_t tx_size +) +{ + uint8_t status; + size_t size_sent = 0U; + + HAL_ASSERT( this_uart != NULL_INSTANCE ) + HAL_ASSERT( tx_buffer != NULL_BUFF ) + HAL_ASSERT( tx_size > 0U ) + + /* Fill the UART's Tx FIFO until the FIFO is full or the complete input + * buffer has been written. */ + if( (this_uart != NULL_INSTANCE) && + (tx_buffer != NULL_BUFF) && + (tx_size > 0U) ) + { + /* Read the Line Status Register and update the sticky record. */ + status = HAL_get_8bit_reg( this_uart->base_address, LSR ); + this_uart->status |= status; + + /* Check if TX FIFO is empty. */ + if( status & LSR_THRE_MASK ) + { + uint32_t fill_size = TX_FIFO_SIZE; + + /* Calculate the number of bytes to transmit. */ + if ( tx_size < TX_FIFO_SIZE ) + { + fill_size = tx_size; + } + + /* Fill the TX FIFO with the calculated the number of bytes. */ + for ( size_sent = 0U; size_sent < fill_size; ++size_sent ) + { + /* Send next character in the buffer. */ + HAL_set_8bit_reg( this_uart->base_address, THR, + (uint_fast8_t)tx_buffer[size_sent]); + } + } + } + return size_sent; +} + +/***************************************************************************//** + * UART_16550_get_tx_status. + * See core_16550.h for details of how to use this function. + */ +uint8_t +UART_16550_get_tx_status +( + uart_16550_instance_t * this_uart +) +{ + uint8_t status = UART_16550_TX_BUSY; + HAL_ASSERT( this_uart != NULL_INSTANCE ); + + if( ( this_uart != NULL_INSTANCE ) ) + { + /* Read the Line Status Register and update the sticky record. */ + status = HAL_get_8bit_reg( this_uart->base_address, LSR ); + this_uart->status |= status; + /* + * Extract the transmit status bits from the UART's Line Status Register. + * Bit 5 - Transmitter Holding Register/FIFO Empty (THRE) status. (If = 1, TX FIFO is empty) + * Bit 6 - Transmitter Empty (TEMT) status. (If = 1, both TX FIFO and shift register are empty) + */ + status &= ( LSR_THRE_MASK | LSR_TEMT_MASK ); + } + return status; +} + + +#ifdef __cplusplus +} +#endif + + + + + + + + + + + + diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/Core16550/core_16550.h b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/Core16550/core_16550.h new file mode 100644 index 0000000..afce7ed --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/Core16550/core_16550.h @@ -0,0 +1,1264 @@ +/******************************************************************************* + * (c) Copyright 2007-2015 Microsemi SoC Products Group. All rights reserved. + * + * This file contains the application programming interface for the Core16550 + * bare metal driver. + * + * SVN $Revision: 7963 $ + * SVN $Date: 2015-10-09 17:58:21 +0530 (Fri, 09 Oct 2015) $ + */ +/*=========================================================================*//** + @mainpage Core16550 Bare Metal Driver. + + @section intro_sec Introduction + The Core16550 is an implementation of the Universal Asynchronous + Receiver/Transmitter aimed at complete compliance to standard 16550 UART. + The Core16550 bare metal software driver is designed for use in systems + with no operating system. + + The Core16550 driver provides functions for polled and interrupt driven + transmitting and receiving. It also provides functions for reading the + values from different status registers, enabling and disabling interrupts + at Core16550 level. The Core16550 driver is provided as C source code. + + @section driver_configuration Driver Configuration + Your application software should configure the Core16550 driver through + calls to the UART_16550_init() function for each Core16550 instance in + the hardware design. The configuration parameters include the Core16550 + hardware instance base address and other runtime parameters, such as baud + value, bit width, and parity. + + No Core16550 hardware configuration parameters are needed by the driver, + apart from the Core16550 hardware instance base address. Hence, no + additional configuration files are required to use the driver. + + @section theory_op Theory of Operation + The Core16550 software driver is designed to allow the control of multiple + instances of Core16550. Each instance of Core16550 in the hardware design + is associated with a single instance of the uart_16550_instance_t structure + in the software. You need to allocate memory for one unique + uart_16550_instance_t structure instance for each Core16550 hardware instance. + The contents of these data structures are initialized during calls to + function UART_16550_init(). A pointer to the structure is passed to + subsequent driver functions in order to identify the Core16550 hardware + instance you wish to perform the requested operation on. + + Note: Do not attempt to directly manipulate the content of + uart_16550_instance_t structures. This structure is only intended to be + modified by the driver function. + + Initialization + The Core16550 driver is initialized through a call to the UART_16550_init() + function. This function takes the UART�s configuration as parameters. + The UART_16550_init() function must be called before any other Core16550 + driver functions can be called. + + Polled Transmission and Reception + The driver can be used to transmit and receive data once initialized. Polled + operations where the driver constantly polls the state of the UART registers + in order to control data transmit or data receive are performed using these + functions: + � UART_16550_polled_tx() + � UART_16550_polled_tx_string + � UART_16550_fill_tx_fifo() + � UART_16550_get_rx() + + Data is transmitted using the UART_16550_polled_tx() function. This function + is blocking, meaning that it will only return once the data passed to the + function has been sent to the Core16550 hardware. Data received by the + Core16550 hardware can be read by the UART_16550_get_rx() function. + + The UART_16550_polled_tx_string() function is provided to transmit a NULL (�\0�) + terminated string in polled mode. This function is blocking, meaning that it + will only return once the data passed to the function has been sent to the + Core16550 hardware. + + The UART_16550_fill_tx_fifo() function fills the Core16550 hardware transmit + FIFO with data from a buffer passed as a parameter and returns the number of + bytes transferred to the FIFO. If the transmit FIFO is not empty when the + UART_16550_fill_tx_fifo() function is called it returns immediately without + transferring any data to the FIFO. + + Interrupt Driven Operations + The driver can also transmit or receive data under interrupt control, freeing + your application to perform other tasks until an interrupt occurs indicating + that the driver�s attention is required. Interrupt controlled UART operations + are performed using these functions: + � UART_16550_isr() + � UART_16550_irq_tx() + � UART_16550_tx_complete() + � UART_16550_set_tx_handler() + � UART_16550_set_rx_handler() + � UART_16550_set_rxstatus_handler() + � UART_16550_set_modemstatus_handler() + � UART_16550_enable_irq() + � UART_16550_disable_irq() + + Interrupt Handlers + The UART_16550_isr() function is the top level interrupt handler function for + the Core16550 driver. You must call it from the system level + (CoreInterrupt and NVIC level) interrupt service routine (ISR) assigned to the + interrupt triggered by the Core16550 INTR signal. The UART_16550_isr() function + identifies the source of the Core16550 interrupt and calls the corresponding + handler function previously registered with the driver through calls to the + UART_16550_set_rx_handler(), UART_16550_set_tx_handler(), + UART_16550_set_rxstatus_handler(), and UART_16550_set_modemstatus_handler() + functions. You are responsible for creating these lower level interrupt handlers + as part of your application program and registering them with the driver. + The UART_16550_enable_irq() and UART_16550_disable_irq() functions are used to + enable or disable the received line status, received data available/character + timeout, transmit holding register empty and modem status interrupts at the + Core16550 level. + + Transmitting Data + Interrupt-driven transmit is initiated by a call to UART_16550_irq_tx(), + specifying the block of data to transmit. Your application is then free to + perform other tasks and inquire later whether transmit has completed by calling + the UART_16550_tx_complete() function. The UART_16550_irq_tx() function enables + the UART�s transmit holding register empty (THRE) interrupt and then, when the + interrupt goes active, the driver�s default THRE interrupt handler transfers + the data block to the UART until the entire block is transmitted. + + Note: You can use the UART_16550_set_tx_handler() function to assign an + alternative handler to the THRE interrupt. In this case, you must not use the + UART_16550_irq_tx() function to initiate the transmit, as this will re-assign + the driver�s default THRE interrupt handler to the THRE interrupt. Instead, + your alternative THRE interrupt handler must include a call to the + UART_16550_fill_tx_fifo() function to transfer the data to the UART. + + Receiving Data + Interrupt-driven receive is performed by first calling UART_16550_set_rx_handler() + to register a receive handler function that will be called by the driver whenever + receive data is available. You must provide this receive handler function which + must include a call to the UART_16550_get_rx() function to actually read the + received data. + + UART Status + The function UART_16550_get_rx_status() is used to read the receiver error status. + This function returns the overrun, parity, framing, break, and FIFO error status + of the receiver. + The function UART_16550_get_tx_status() is used to read the transmitter status. + This function returns the transmit empty (TEMT) and transmit holding register + empty (THRE) status of the transmitter. + The function UART_16550_get_modem_status() is used to read the modem status flags. + This function returns the current value of the modem status register. + + Loopback + The function UART_16550_set_loopback() is used to enable or disable loopback + between Tx and Rx lines internal to Core16550. +*//*=========================================================================*/ +#ifndef __CORE_16550_H +#define __CORE_16550_H 1 + +#include "hal/cpu_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/***************************************************************************//** + * Receiver Error Status + * The following defines are used to determine the UART receiver error type. + * These bit mask constants are used with the return value of the + * UART_16550_get_rx_status() function to find out if any errors occurred + * while receiving data. + */ +#define UART_16550_NO_ERROR ( (uint8_t) 0x00 ) +#define UART_16550_OVERRUN_ERROR ( (uint8_t) 0x02 ) +#define UART_16550_PARITY_ERROR ( (uint8_t) 0x04 ) +#define UART_16550_FRAMING_ERROR ( (uint8_t) 0x08 ) +#define UART_16550_BREAK_ERROR ( (uint8_t) 0x10 ) +#define UART_16550_FIFO_ERROR ( (uint8_t) 0x80 ) +#define UART_16550_INVALID_PARAM ( (uint8_t) 0xFF ) + +/***************************************************************************//** + * Modem Status + * The following defines are used to determine the modem status. These bit + * mask constants are used with the return value of the + * UART_16550_get_modem_status() function to find out the modem status of + * the UART. + */ +#define UART_16550_DCTS ( (uint8_t) 0x01 ) +#define UART_16550_DDSR ( (uint8_t) 0x02 ) +#define UART_16550_TERI ( (uint8_t) 0x04 ) +#define UART_16550_DDCD ( (uint8_t) 0x08 ) +#define UART_16550_CTS ( (uint8_t) 0x10 ) +#define UART_16550_DSR ( (uint8_t) 0x20 ) +#define UART_16550_RI ( (uint8_t) 0x40 ) +#define UART_16550_DCD ( (uint8_t) 0x80 ) + +/***************************************************************************//** + * Transmitter Status + * The following definitions are used to determine the UART transmitter status. + * These bit mask constants are used with the return value of the + * UART_16550_get_tx_status() function to find out the status of the + * transmitter. + */ +#define UART_16550_TX_BUSY ( (uint8_t) 0x00 ) +#define UART_16550_THRE ( (uint8_t) 0x20 ) +#define UART_16550_TEMT ( (uint8_t) 0x40 ) + +/***************************************************************************//** + * Core16550 Interrupts + * The following defines are used to enable and disable Core16550 interrupts. + * They are used to build the value of the irq_mask parameter for the + * UART_16550_enable_irq() and UART_16550_disable_irq() functions. A bitwise + * OR of these constants is used to enable or disable multiple interrupts. + */ +#define UART_16550_RBF_IRQ ( (uint8_t) 0x01 ) +#define UART_16550_TBE_IRQ ( (uint8_t) 0x02 ) +#define UART_16550_LS_IRQ ( (uint8_t) 0x04 ) +#define UART_16550_MS_IRQ ( (uint8_t) 0x08 ) + +/***************************************************************************//** + * Data Width + * The following defines are used to build the value of the UART_16550_init() + * function line_config parameter. + */ +#define UART_16550_DATA_5_BITS ( (uint8_t) 0x00 ) +#define UART_16550_DATA_6_BITS ( (uint8_t) 0x01 ) +#define UART_16550_DATA_7_BITS ( (uint8_t) 0x02 ) +#define UART_16550_DATA_8_BITS ( (uint8_t) 0x03 ) + +/***************************************************************************//** + * Parity Control + * The following defines are used to build the value of the UART_16550_init() + * function line_config parameter. + */ +#define UART_16550_NO_PARITY ( (uint8_t) 0x00 ) +#define UART_16550_ODD_PARITY ( (uint8_t) 0x08 ) +#define UART_16550_EVEN_PARITY ( (uint8_t) 0x18 ) +#define UART_16550_STICK_PARITY_1 ( (uint8_t) 0x28 ) +#define UART_16550_STICK_PARITY_0 ( (uint8_t) 0x38 ) + +/***************************************************************************//** + * Number of Stop Bits + * The following defines are used to build the value of the UART_16550_init() + * function line_config parameter. + */ +#define UART_16550_ONE_STOP_BIT ( (uint8_t) 0x00 ) +/*only when data bits is 5*/ +#define UART_16550_ONEHALF_STOP_BIT ( (uint8_t) 0x04 ) +/*only when data bits is not 5*/ +#define UART_16550_TWO_STOP_BITS ( (uint8_t) 0x04 ) + +/***************************************************************************//** + This enumeration specifies the receiver FIFO trigger level. This is the number + of bytes that must be received before the UART generates a receive data + available interrupt. It provides the allowed values for the + UART_16550_set_rx_handler() function�s trigger_level parameter. + */ +typedef enum { + UART_16550_FIFO_SINGLE_BYTE = 0, + UART_16550_FIFO_FOUR_BYTES = 1, + UART_16550_FIFO_EIGHT_BYTES = 2, + UART_16550_FIFO_FOURTEEN_BYTES = 3, + UART_16550_FIFO_INVALID_TRIG_LEVEL +} uart_16550_rx_trig_level_t; + +/***************************************************************************//** + This enumeration specifies the Loopback configuration of the UART. It provides + the allowed values for the UART_16550_set_loopback() function�s loopback + parameter. + */ +typedef enum { + UART_16550_LOOPBACK_OFF = 0, + UART_16550_LOOPBACK_ON = 1, + UART_16550_INVALID_LOOPBACK +} uart_16550_loopback_t; + +/***************************************************************************//** + This is type definition for Core16550 instance. You need to create and + maintain a record of this type. This holds all data regarding the Core16550 + instance. + */ +typedef struct uart_16550_instance uart_16550_instance_t; + +/***************************************************************************//** + This typedef specifies the function prototype for Core16550 interrupt handlers. + All interrupt handlers registered with the Core16550 driver must be of this + type. The interrupt handlers are registered with the driver through the + UART_16550_set_rx_handler(), UART_16550_set_tx_handler(), + UART_16550_set_rxstatus_handler(), and UART_16550_set_modemstatus_handler() + functions. + + The this_uart parameter is a pointer to a uart_16550_instance_t structure that + holds all data regarding this instance of the Core16550. + */ +typedef void (*uart_16550_irq_handler_t)(uart_16550_instance_t * this_uart); + +/***************************************************************************//** + uart_16550_instance. + This structure is used to identify the various Core16550 hardware instances + in your system. Your application software should declare one instance of this + structure for each instance of Core16550 in your system. The function + UART_16550_init() initializes this structure. A pointer to an initialized + instance of the structure should be passed as the first parameter to the + Core16550 driver functions, to identify which Core16550 hardware instance + should perform the requested operation. + */ +struct uart_16550_instance{ + /* Core16550 instance base address: */ + addr_t base_address; + /* Accumulated status: */ + uint8_t status; + + /* transmit related info: */ + const uint8_t* tx_buffer; + uint32_t tx_buff_size; + uint32_t tx_idx; + + /* line status (OE, PE, FE & BI) interrupt handler:*/ + uart_16550_irq_handler_t linests_handler; + /* receive interrupt handler:*/ + uart_16550_irq_handler_t rx_handler; + /* transmitter holding register interrupt handler:*/ + uart_16550_irq_handler_t tx_handler; + /* modem status interrupt handler:*/ + uart_16550_irq_handler_t modemsts_handler; +}; + +/***************************************************************************//** + * The UART_16550_init() function initializes the driver�s data structures and + * the Core16550 hardware with the configuration passed as parameters.. The + * configuration parameters are the baud_value used to generate the baud rate, + * and the line_config used to specify the line configuration (bit length, + * stop bits and parity). + * + * @param this_uart The this_uart parameter is a pointer to a + * uart_16550_instance_t structure that holds all data + * regarding this instance of the Core16550. This pointer + * is used to identify the target Core16550 hardware + * instance in subsequent calls to the Core16550 driver + * functions. + * @param base_addr The base_address parameter is the base address in the + * processor's memory map for the registers of the + * Core16550 instance being initialized. + * @param baud_value The baud_value parameter is used to select the baud rate + * for the UART. The baud value is calculated from the + * frequency of the system clock in Hertz and the desired + * baud rate using the following equation: + * + * baud_value = (clock /(baud_rate * 16)) + * + * The baud_value parameter must be a value in the range 0 + * to 65535 (or 0x0000 to 0xFFFF). + * @param line_config This parameter is the line configuration specifying the + * bit length, number of stop bits and parity settings. This + * is a bitwise OR of one value from each of the following + * groups of allowed values: + * � Data lengths: + * UART_16550_DATA_5_BITS + * UART_16550_DATA_6_BITS + * UART_16550_DATA_7_BITS + * UART_16550_DATA_8_BITS + * � Parity types: + * UART_16550_NO_PARITY + * UART_16550_EVEN_PARITY + * UART_16550_ODD_PARITY + * UART_16550_STICK_PARITY_0 + * UART_16550_STICK_PARITY_1 + * � Number of stop bits: + * UART_16550_ONE_STOP_BIT + * UART_16550_ONEHALF_STOP_BIT + * UART_16550_TWO_STOP_BITS + * @return This function does not return a value. + * + * Example: + * @code + * #define UART_16550_BASE_ADDR 0x2A000000 + * #define BAUD_VALUE_57600 26 + * + * uart_16550_instance_t g_uart; + * + * UART_16550_init( &g_uart, UART_16550_BASE_ADDR, BAUD_VALUE_57600, + * (UART_16550_DATA_8_BITS | + * UART_16550_EVEN_PARITY | + * UART_16550_ONE_STOP_BIT) ); + * @endcode + */ +void +UART_16550_init +( + uart_16550_instance_t* this_uart, + addr_t base_addr, + uint16_t baud_value, + uint8_t line_config +); + +/***************************************************************************//** + * The UART_16550_polled_tx() function is used to transmit data. It transfers + * the contents of the transmitter data buffer, passed as a function parameter, + * into the UART's hardware transmitter FIFO. It returns when the full content + * of the transmitter data buffer has been transferred to the UART's transmitter + * FIFO. It is safe to release or reuse the memory used as the transmitter data + * buffer once this function returns. + * + * Note: This function reads the UART�s line status register (LSR) to poll + * for the active state of the transmitter holding register empty (THRE) bit + * before transferring data from the data buffer to the transmitter FIFO. It + * transfers data to the transmitter FIFO in blocks of 16 bytes or less and + * allows the FIFO to empty before transferring the next block of data. + * + * Note: The actual transmission over the serial connection will still be in + * progress when this function returns. Use the UART_16550_get_tx_status() + * function if you need to know when the transmitter is empty. + * + * @param this_uart The this_uart parameter is a pointer to a + * uart_16550_instance_t structure that holds all + * data regarding this instance of the Core16550. + * @param pbuff The pbuff parameter is a pointer to a buffer containing + * the data to be transmitted. + * @param tx_size The tx_size parameter is the size, in bytes, of the + * data to be transmitted. + * @return This function does not return a value. + * + * Example: + * @code + * uint8_t testmsg1[] = {"\n\r\n\r\n\rUART_16550_polled_tx() test message 1"}; + * UART_16550_polled_tx(&g_uart,(const uint8_t *)testmsg1,sizeof(testmsg1)); + * @endcode + */ +void +UART_16550_polled_tx +( + uart_16550_instance_t * this_uart, + const uint8_t * pbuff, + uint32_t tx_size +); +/***************************************************************************//** + * The UART_16550_polled_tx_string() function is used to transmit a NULL ('\0') + * terminated string. It transfers the text string, from the buffer starting at + * the address pointed to by p_sz_string, into the UART�s hardware transmitter + * FIFO. It returns when the complete string has been transferred to the UART's + * transmit FIFO. It is safe to release or reuse the memory used as the string + * buffer once this function returns. + * + * Note: This function reads the UART�s line status register (LSR) to poll + * for the active state of the transmitter holding register empty (THRE) bit + * before transferring data from the data buffer to the transmitter FIFO. It + * transfers data to the transmitter FIFO in blocks of 16 bytes or less and + * allows the FIFO to empty before transferring the next block of data. + * + * Note: The actual transmission over the serial connection will still be + * in progress when this function returns. Use the UART_16550_get_tx_status() + * function if you need to know when the transmitter is empty. + * + * @param this_uart The this_uart parameter is a pointer to a + * uart_16550_instance_t structure that holds all data + * regarding this instance of the Core16550. + * @param p_sz_string The p_sz_string parameter is a pointer to a buffer + * containing the NULL ('\0') terminated string to be + * transmitted. + * @return This function does not return a value. + * + * Example: + * @code + * uint8_t testmsg1[] = {"\r\n\r\nUART_16550_polled_tx_string() test message 1\0"}; + * UART_16550_polled_tx_string(&g_uart,(const uint8_t *)testmsg1); + * @endcode + */ +void +UART_16550_polled_tx_string +( + uart_16550_instance_t * this_uart, + const uint8_t * p_sz_string +); + +/***************************************************************************//** + * The UART_16550_irq_tx() function is used to initiate an interrupt driven + * transmit. It returns immediately after making a note of the transmit buffer + * location and enabling the transmitter holding register empty (THRE) interrupt + * at the Core16550 level. This function takes a pointer via the pbuff parameter + * to a memory buffer containing the data to transmit. The memory buffer + * specified through this pointer must remain allocated and contain the data to + * transmit until the transmit completion has been detected through calls to + * function UART_16550_tx_complete().The actual transmission over the serial + * connection is still in progress until calls to the UART_16550_tx_complete() + * function indicate transmit completion. + * + * Note: It is your responsibility to call UART_16550_isr(), the driver�s + * top level interrupt handler function, from the system level (CoreInterrupt + * and NVIC level) interrupt handler assigned to the interrupt triggered by the + * Core16550 INTR signal. You must do this before using the UART_16550_irq_tx() + * function. + * + * Note: It is also your responsibility to enable the system level + * (CoreInterrupt and NVIC level) interrupt connected to the Core16550 INTR + * interrupt signal. + * + * Note: The UART_16550_irq_tx() function assigns an internal default transmit + * interrupt handler function to the UART�s THRE interrupt. This interrupt handler + * overrides any custom interrupt handler that you may have previously registered + * using the UART_16550_set_tx_handler() function. + * + * Note: The UART_16550_irq_tx() function�s default transmit interrupt handler + * disables the UART�s THRE interrupt when all of the data has been transferred + * to the UART's transmit FIFO. + * + * @param this_uart The this_uart parameter is a pointer to a + * uart_16550_instance_t structure that holds all data + * regarding this instance of the Core16550. + * @param pbuff The pbuff parameter is a pointer to a buffer containing + * the data to be transmitted. + * @param tx_size The tx_size parameter specifies the size, in bytes, of + * the data to be transmitted. + * @return This function does not return a value. + * + * Example: + * @code + * uint8_t tx_buff[10] = "abcdefghi"; + * + * UART_16550_irq_tx( &g_uart, tx_buff, sizeof(tx_buff)); + * while ( 0 == UART_16550_tx_complete( &g_uart ) ) + * { ; } + * @endcode + */ +void +UART_16550_irq_tx +( + uart_16550_instance_t * this_uart, + const uint8_t * pbuff, + uint32_t tx_size +); + +/***************************************************************************//** + * The UART_16550_tx_complete() function is used to find out if the interrupt + * driven transmit previously initiated through a call to UART_16550_irq_tx() + * is complete. This function is typically used to find out when it is safe + * to reuse or release the memory buffer holding the transmit data. + * + * Note: The transfer of all of the data from the memory buffer to the UART�s + * transmit FIFO and the actual transmission over the serial connection are both + * complete when a call to the UART_16550_tx_complete() function indicate + * transmit completion. + * + * @param this_uart The this_uart parameter is a pointer to a + * uart_16550_instance_t structure that holds all data + * regarding this instance of the Core16550. + * @return This function returns a non-zero value if transmit has + * completed, otherwise it returns zero. + * Example: + * See the UART_16550_irq_tx() function for an example that uses the + * UART_16550_tx_complete() function. + */ +int8_t +UART_16550_tx_complete +( + uart_16550_instance_t * this_uart +); + +/***************************************************************************//** + * The UART_16550_get_rx() function reads the content of the Core16550 + * receiver�s FIFO and stores it in the receive buffer that is passed via the + * rx_buff function parameter. It copies either the full contents of the FIFO + * into the receive buffer, or just enough data from the FIFO to fill the receive + * buffer, dependent upon the size of the receive buffer passed by the buff_size + * parameter. The UART_16550_get_rx() function returns the number of bytes copied + * into the receive buffer .This function is non-blocking and will return 0 + * immediately if no data has been received. + * + * Note: The UART_16550_get_rx() function reads and accumulates the receiver + * status of the Core16550 instance before reading each byte from the receiver's + * data register/FIFO. This allows the driver to maintain a sticky record of any + * receiver errors that occur as the UART receives each data byte; receiver errors + * would otherwise be lost after each read from the receiver's data register. A call + * to the UART_16550_get_rx_status() function returns any receiver errors accumulated + * during the execution of the UART_16550_get_rx() function. + * + * Note: If you need to read the error status for each byte received, set the + * buff_size to 1 and read the receive line error status for each byte using the + * UART_16550_get_rx_status() function. + * The UART_16550_get_rx() function can be used in polled mode, where it is called + * at regular intervals to find out if any data has been received, or in interrupt + * driven-mode, where it is called as part of a receive handler that is called by + * the driver as a result of data being received. + * + * Note: In interrupt driven mode you should call the UART_16550_get_rx() + * function as part of the receive handler function that you register with the + * Core16550 driver through a call to UART_16550_set_rx_handler(). + * + * @param this_uart The this_uart parameter is a pointer to a + * uart_16550_instance_t structure that holds all data + * regarding this instance of the Core16550. + * @param rx_buff The rx_buff parameter is a pointer to a memory buffer + * where the received data is copied. + * @param buff_size The buff_size parameter is the size of the receive + * buffer in bytes. + * @return This function returns the number of bytes copied into + * the receive buffer. + * Example: + * @code + * #define MAX_RX_DATA_SIZE 256 + * + * uint8_t rx_data[MAX_RX_DATA_SIZE]; + * uint8_t rx_size = 0; + * + * rx_size = UART_16550_get_rx( &g_uart, rx_data, sizeof(rx_data) ); + * @endcode + */ +size_t +UART_16550_get_rx +( + uart_16550_instance_t * this_uart, + uint8_t * rx_buff, + size_t buff_size +); + +/***************************************************************************//** + * The UART_16550_isr() function is the top level interrupt handler function for + * the Core16550 driver. You must call UART_16550_isr() from the system level + * (CoreInterrupt and NVIC level) interrupt handler assigned to the interrupt + * triggered by the Core16550 INTR signal. Your system level interrupt handler + * must also clear the system level interrupt triggered by the Core16550 INTR + * signal before returning, to prevent a re-assertion of the same interrupt. + * + * Note: This function supports all types of interrupt triggered by Core16550. + * It is not a complete interrupt handler by itself; rather, it is a top level + * wrapper that abstracts Core16550 interrupt handling by calling lower level + * handler functions specific to each type of Core16550 interrupt. You must + * create the lower level handler functions to suit your application and + * register them with the driver through calls to the UART_16550_set_rx_handler(), + * UART_16550_set_tx_handler(), UART_16550_set_rxstatus_handler() and + * UART_16550_set_modemstatus_handler() functions. + * + * @param this_uart The this_uart parameter is a pointer to a + * uart_16550_instance_t structure that holds all data + * regarding this instance of the Core16550. + * + * @return This function does not return a value. + * + * Example: + * @code + * void CIC_irq1_handler(void) + * { + * UART_16550_isr( &g_uart ); + * } + * @endcode + */ +void +UART_16550_isr +( + uart_16550_instance_t * this_uart +); + +/***************************************************************************//** + * The UART_16550_set_rx_handler() function is used to register a receive handler + * function that is called by the driver when a UART receive data available (RDA) + * interrupt occurs. The UART_16550_set_rx_handler() function also enables the + * RDA interrupt at the Core16550 level. You must create and register the receive + * handler function to suit your application and it must include a call to the + * UART_16550_get_rx() function to actually read the received data. + * + * Note: The driver�s top level interrupt handler function UART_16550_isr() + * will call your receive handler function in response to an RDA interrupt from + * the Core16550. + * + * Note: You can disable the RDA interrupt once the data is received by calling + * the UART_16550_disable_irq() function. This is your choice and is dependent + * upon your application. + * + * @param this_uart The this_uart parameter is a pointer to a + * uart_16550_instance_t structure that holds all data + * regarding this instance of the Core16550. + * @param handler The handler parameter is a pointer to a receive interrupt + * handler function provided by your application that will be + * called as a result of a UART RDA interrupt. This handler + * function must be of type uart_16550_irq_handler_t. + * @param trigger_level The trigger_level parameter is the receive FIFO + * trigger level. This specifies the number of bytes that + * must be received before the UART triggers an RDA + * interrupt. + * @return This function does not return a value. + * + * Example: + * @code + * #include "core_16550.h" + * + * #define RX_BUFF_SIZE 64 + * #define UART_57600_BAUD 26 + * + * uint8_t g_rx_buff[RX_BUFF_SIZE]; + * uart_16550_instance_t g_uart; + * void uart_rx_handler( uart_16550_instance_t * this_uart ) + * { + * UART_16550_get_rx( this_uart, g_rx_buff, RX_BUFF_SIZE ); + * } + * + * int main(void) + * { + * UART_16550_init( &g_uart, UART_57600_BAUD, + * ( UART_16550_DATA_8_BITS | UART_16550_NO_PARITY ) ); + * UART_16550_set_rx_handler( &g_uart, uart_rx_handler, + * UART_16550_FIFO_SINGLE_BYTE); + * while ( 1 ) + * { + * ; + * } + * return(0); + * } + * @endcode + */ +void +UART_16550_set_rx_handler +( + uart_16550_instance_t * this_uart, + uart_16550_irq_handler_t handler, + uart_16550_rx_trig_level_t trigger_level +); + +/***************************************************************************//** + * The UART_16550_set_loopback() function is used to locally loopback the Tx + * and Rx lines of a Core16550 UART. + * + * @param this_uart The this_uart parameter is a pointer to a + * uart_16550_instance_t structure that holds all data + * regarding this instance of the Core16550. + * @param loopback The loopback parameter indicates whether or not the + * UART's transmit and receive lines should be looped back. + * Allowed values are as follows: + * � UART_16550_LOOPBACK_ON + * � UART_16550_LOOPBACK_OFF + * @return This function does not return a value. + * + * Example: + * @code + * #include "core_16550.h" + * + * #define UART_57600_BAUD 26 + * #define DATA_SIZE 4 + * + * uart_16550_instance_t g_uart; + * + * int main(void) + * { + * uint8_t txbuf[DATA_SIZE] = "abc"; + * uint8_t rxbuf[DATA_SIZE]; + * UART_16550_init( &g_uart, UART_57600_BAUD, + * ( UART_16550_DATA_8_BITS | UART_16550_NO_PARITY | + * UART_16550_ONE_STOP_BIT) ); + * UART_16550_set_loopback( &g_uart, UART_16550_LOOPBACK_ON ); + * + * while(1) + * { + * UART_16550_polled_tx( &g_uart, txbuf, DATA_SIZE); + * delay(100); + * UART_16550_get_rx( &g_uart, rxbuf, DATA_SIZE); + * } + * } + * @endcode + */ +void +UART_16550_set_loopback +( + uart_16550_instance_t * this_uart, + uart_16550_loopback_t loopback +); + +/***************************************************************************//** + * The UART_16550_get_rx_status() function returns the receiver error status of + * the Core16550 instance. It reads both the current error status of the receiver + * from the UART�s line status register (LSR) and the accumulated error status + * from preceding calls to the UART_16550_get_rx() function, and it combines + * them using a bitwise OR. It returns the cumulative overrun, parity, framing, + * break and FIFO error status of the receiver, since the previous call to + * UART_16550_get_rx_status(), as an 8-bit encoded value. + * + * Note: The UART_16550_get_rx() function reads and accumulates the receiver + * status of the Core16550 instance before reading each byte from the receiver�s + * data register/FIFO. The driver maintains a sticky record of the cumulative + * receiver error status, which persists after the UART_16550_get_rx() function + * returns. The UART_16550_get_rx_status() function clears the driver�s sticky + * receiver error record before returning. + * + * Note: The driver�s transmit functions also read the line status register + * (LSR) as part of their implementation. When the driver reads the LSR, the + * UART clears any active receiver error bits in the LSR. This could result in + * the driver losing receiver errors. To avoid any loss of receiver errors, the + * transmit functions also update the driver�s sticky record of the cumulative + * receiver error status whenever they read the LSR. + * + * @param this_uart The this_uart parameter is a pointer to a + * uart_16550_instance_t structure that holds all data + * regarding this instance of the Core16550. + * @return This function returns the UART�s receiver error status + * as an 8-bit unsigned integer. The returned value is 0 + * if no receiver errors occurred. The driver provides a + * set of bit mask constants that should be compared with + * and/or used to mask the returned value to determine the + * receiver error status. + * When the return value is compared to the following bit + * masks, a non-zero result indicates that the + * corresponding error occurred: + * � UART_16550_OVERRUN_ERROR (bit mask = 0x02) + * � UART_16550_PARITY_ERROR (bit mask = 0x04) + * � UART_16550_FRAMING_ERROR (bit mask = 0x08) + * � UART_16550_BREAK_ERROR (bit mask = 0x10) + * � UART_16550_FIFO_ERROR (bit mask = 0x80) + * When the return value is compared to the following bit + * mask, a non-zero result indicates that no error occurred: + * � UART_16550_NO_ERROR (bit mask = 0x00) + * Upon unsuccessful execution, this function returns: + * � UART_16550_INVALID_PARAM (bit mask = 0xFF) + * + * Example: + * @code + * uart_16550_instance_t g_uart; + * uint8_t rx_data[MAX_RX_DATA_SIZE]; + * uint8_t err_status; + * + * err_status = UART_16550_get_rx_status(&g_uart); + * if(UART_16550_NO_ERROR == err_status ) + * { + * rx_size = UART_16550_get_rx( &g_uart, rx_data, MAX_RX_DATA_SIZE ); + * } + * @endcode + */ +uint8_t +UART_16550_get_rx_status +( + uart_16550_instance_t * this_uart +); +/***************************************************************************//** + * The UART_16550_enable_irq() function enables the Core16550 interrupts + * specified by the irq_mask parameter. The irq_mask parameter identifies the + * Core16550 interrupts by bit position, as defined in the interrupt enable + * register (IER) of Core16550. The Core16550 interrupts and their identifying + * irq_mask bit positions are as follows: + * � Receive data available interrupt (RDA) (irq_mask bit 0) + * � Transmit holding register empty interrupt (THRE) (irq_mask bit 1) + * � Receiver line status interrupt (LS) (irq_mask bit 2) + * � Modem status interrupt (MS) (irq_mask bit 3) + * When an irq_mask bit position is set to 1, this function enables the + * corresponding Core16550 interrupt in the IER register. When an irq_mask + * bit position is set to 0, the corresponding interrupt�s state remains + * unchanged in the IER register. + * + * @param this_uart The this_uart parameter is a pointer to a + * uart_16550_instance_t structure that holds all data + * regarding this instance of the Core16550. + * @param irq_mask The irq_mask parameter is used to select which of the + * Core16550�s interrupts you want to enable. The allowed + * value for the irq_mask parameter is one of the + * following constants or a bitwise OR of more than one: + * � UART_16550_RBF_IRQ (bit mask = 0x01) + * � UART_16550_TBE_IRQ (bit mask = 0x02) + * � UART_16550_LS_IRQ (bit mask = 0x04) + * � UART_16550_MS_IRQ (bit mask = 0x08) + * @return This function does not return a value. + * + * Example: + * @code + * UART_16550_enable_irq( &g_uart,( UART_16550_RBF_IRQ | UART_16550_TBE_IRQ ) ); + * @endcode + */ +void +UART_16550_enable_irq +( + uart_16550_instance_t * this_uart, + uint8_t irq_mask +); + +/***************************************************************************//** + * The UART_16550_disable_irq() function disables the Core16550 interrupts + * specified by the irq_mask parameter. The irq_mask parameter identifies the + * Core16550 interrupts by bit position, as defined in the interrupt enable + * register (IER) of Core16550. The Core16550 interrupts and their identifying + * bit positions are as follows: + * � Receive data available interrupt (RDA) (irq_mask bit 0) + * � Transmit holding register empty interrupt (THRE) (irq_mask bit 1) + * � Receiver line status interrupt (LS) (irq_mask bit 2) + * � Modem status interrupt (MS) (irq_mask bit 3) + * When an irq_mask bit position is set to 1, this function disables the + * corresponding Core16550 interrupt in the IER register. When an irq_mask bit + * position is set to 0, the corresponding interrupt�s state remains unchanged + * in the IER register. + * + * @param this_uart The this_uart parameter is a pointer to a + * uart_16550_instance_t structure that holds all data + * regarding this instance of the Core16550. + * @param irq_mask The irq_mask parameter is used to select which of the + * Core16550�s interrupts you want to disable. The allowed + * value for the irq_mask parameter is one of the + * following constants or a bitwise OR of more than one: + * � UART_16550_RBF_IRQ (bit mask = 0x01) + * � UART_16550_TBE_IRQ (bit mask = 0x02) + * � UART_16550_LS_IRQ (bit mask = 0x04) + * � UART_16550_MS_IRQ (bit mask = 0x08) + * @return This function does not return a value. + * + * Example: + * @code + * UART_16550_disable_irq( &g_uart, ( UART_16550_RBF_IRQ | UART_16550_TBE_IRQ ) ); + * @endcode + */ +void +UART_16550_disable_irq +( + uart_16550_instance_t * this_uart, + uint8_t irq_mask +); + +/***************************************************************************//** + * The UART_16550_get_modem_status() function returns the modem status of the + * Core16550 instance. It reads the modem status register (MSR) and returns the + * 8 bit value. The bit encoding of the returned value is exactly the same as + * the definition of the bits in the MSR. + * + * @param this_uart The this_uart parameter is a pointer to a + * uart_16550_instance_t structure that holds all data + * regarding this instance of the Core16550. + * @return This function returns current state of the UART's MSR + * as an 8 bit unsigned integer. The driver provides the + * following set of bit mask constants that should be + * compared with and/or used to mask the returned value + * to determine the modem status: + * � UART_16550_DCTS (bit mask = 0x01) + * � UART_16550_DDSR (bit mask = 0x02) + * � UART_16550_TERI (bit mask = 0x04) + * � UART_16550_DDCD (bit mask = 0x08) + * � UART_16550_CTS (bit mask = 0x10) + * � UART_16550_DSR (bit mask = 0x20) + * � UART_16550_RI (bit mask = 0x40) + * � UART_16550_DCD (bit mask = 0x80) + * Example: + * @code + * void uart_modem_status_isr(uart_16550_instance_t * this_uart) + * { + * uint8_t status; + * status = UART_16550_get_modem_status( this_uart ); + * if( status & UART_16550_DCTS ) + * { + * uart_dcts_handler(); + * } + * if( status & UART_16550_CTS ) + * { + * uart_cts_handler(); + * } + * } + * @endcode + */ +uint8_t +UART_16550_get_modem_status +( + uart_16550_instance_t * this_uart +); + +/***************************************************************************//** + * The UART_16550_set_rxstatus_handler() function is used to register a receiver + * status handler function that is called by the driver when a UART receiver + * line status (RLS) interrupt occurs. The UART_16550_set_rxstatus_handler() + * function also enables the RLS interrupt at the Core16550 level. You must + * create and register the receiver status handler function to suit your + * application. + * + * Note: The driver�s top level interrupt handler function UART_16550_isr() + * will call your receive status handler function in response to an RLS + * interrupt from the Core16550. + * + * Note: You can disable the RLS interrupt when required by calling the + * UART_16550_disable_irq() function. This is your choice and is dependent + * upon your application. + * + * @param this_uart The this_uart parameter is a pointer to a + * uart_16550_instance_t structure that holds all data + * regarding this instance of the Core16550. + * @param handler The handler parameter is a pointer to a receiver line + * status interrupt handler function provided by your + * application that will be called as a result of a + * UART RLS interrupt. This handler function must be + * of type uart_16550_irq_handler_t. + * Example: + * @code + * #include "core_16550.h" + * + * #define UART_57600_BAUD 26 + * + * uart_16550_instance_t g_uart; + * + * void uart_rxsts_handler( uart_16550_instance_t * this_uart ) + * { + * uint8_t status; + * status = UART_16550_get_rx_status( this_uart ); + * if( status & UART_16550_OVERUN_ERROR ) + * { + * discard_rx_data(); + * } + * } + * + * int main(void) + * { + * UART_16550_init( &g_uart, UART_57600_BAUD, + * UART_16550_DATA_8_BITS | UART_16550_NO_PARITY | + * UART_16550_ONE_STOP_BIT ); + * UART_16550_set_rxstatus_handler( &g_uart, uart_rxsts_handler ); + * + * while ( 1 ) + * { + * ; + * } + * return(0); + * } + * @endcode + */ +void +UART_16550_set_rxstatus_handler +( + uart_16550_instance_t * this_uart, + uart_16550_irq_handler_t handler +); + +/***************************************************************************//** + * The UART_16550_set_tx_handler() function is used to register a transmit + * handler function that is called by the driver when a UART transmit holding + * register empty (THRE) interrupt occurs. The UART_16550_set_tx_handler() + * function also enables the THRE interrupt at the Core16550 level. You must + * create and register the transmit handler function to suit your application. + * You can use the UART_16550_fill_tx_fifo() function in your transmit handler + * function to write data to the transmitter. + * + * Note: The driver�s top level interrupt handler function UART_16550_isr() + * will call your transmit handler function in response to an THRE interrupt + * from the Core16550. + * + * Note: You can disable the THRE interrupt when required by calling the + * UART_16550_disable_irq() function. This is your choice and is dependent + * upon your application. + * + * Note: The UART_16550_irq_tx() function does not use the transmit handler + * function that you register with the UART_16550_set_tx_handler() function. + * It uses its own internal THRE interrupt handler function that overrides any + * custom interrupt handler that you register using the + * UART_16550_set_tx_handler() function. + * + * @param this_uart The this_uart parameter is a pointer to a + * uart_16550_instance_t structure that holds all data + * regarding this instance of the Core16550. + * @param handler The handler parameter is a pointer to a transmitter + * interrupt handler function provided by your application, + * which will be called as a result of a UART THRE interrupt. + * This handler is of uart_16550_irq_handler_t type. + * @return This function does not return a value. + * + * Example: + * @code + * #include "core_16550.h" + * + * #define UART_57600_BAUD 26 + * + * uart_16550_instance_t g_uart; + * + * uint8_t * g_tx_buffer; + * size_t g_tx_size = 0; + * + * void uart_tx_handler( uart_16550_instance_t * this_uart ) + * { + * size_t size_in_fifo; + * + * size_in_fifo = UART_16550_fill_tx_fifo( this_uart, + * (const uint8_t *)g_tx_buffer, + * g_tx_size ); + * + * if(size_in_fifo == g_tx_size) + * { + * g_tx_size = 0; + * UART_16550_disable_irq( this_uart, UART_16550_TBE_IRQ ); + * } + * else + * { + * g_tx_buffer = &g_tx_buffer[size_in_fifo]; + * g_tx_size = g_tx_size - size_in_fifo; + * } + * } + * + * int main(void) + * { + * uint8_t message[12] = "Hello world"; + * + * UART_16550_init( &g_uart, UART_57600_BAUD, + * UART_16550_DATA_8_BITS | UART_16550_NO_PARITY | + * UART_16550_ONE_STOP_BIT ); + * + * g_tx_buffer = message; + * g_tx_size = sizeof(message); + * + * UART_16550_set_tx_handler( &g_uart, uart_tx_handler); + * + * while ( 1 ) + * { + * ; + * } + * return(0); + * } + * + * @endcode + */ +void +UART_16550_set_tx_handler +( + uart_16550_instance_t * this_uart, + uart_16550_irq_handler_t handler +); + +/***************************************************************************//** + * The UART_16550_set_modemstatus_handler() function is used to register a + * modem status handler function that is called by the driver when a UART modem + * status (MS) interrupt occurs. The UART_16550_set_modemstatus_handler() + * function also enables the MS interrupt at the Core16550 level. You must + * create and register the modem status handler function to suit your + * application. + * + * Note: The driver�s top level interrupt handler function UART_16550_isr() + * will call your receive status handler function in response to an MS interrupt + * from the Core16550. + * + * Note: You can disable the MS interrupt when required by calling the + * UART_16550_disable_irq() function. This is your choice and is dependent + * upon your application. + * + * @param this_uart The this_uart parameter is a pointer to a + * uart_16550_instance_t structure that holds all data + * regarding this instance of the Core16550. + * @param handler The handler parameter is a pointer to a modem status + * interrupt handler function provided by your application + * that will be called as a result of a UART MS interrupt. + * This handler function must be of type + * uart_16550_irq_handler_t. + * @return This function does not return a value. + * + * Example: + * @code + * #include "core_16550.h" + * + * #define UART_57600_BAUD 26 + * + * uart_16550_instance_t g_uart; + * + * void uart_modem_handler( uart_16550_instance_t * this_uart ) + * { + * uint8_t status; + * status = UART_16550_get_modem_status( this_uart ); + * if( status & UART_16550_CTS ) + * { + * uart_cts_handler(); + * } + * } + * + * int main(void) + * { + * UART_16550_init( &g_uart, UART_57600_BAUD, + * UART_16550_DATA_8_BITS | UART_16550_NO_PARITY | + UART_16550_ONE_STOP_BIT); + * UART_16550_set_modemstatus_handler( &g_uart, uart_modem_handler); + * + * while ( 1 ) + * { + * ; + * } + * return(0); + * } + * @endcode + */ +void +UART_16550_set_modemstatus_handler +( + uart_16550_instance_t * this_uart, + uart_16550_irq_handler_t handler +); + +/***************************************************************************//** + * The UART_16550_fill_tx_fifo() function fills the UART's hardware transmitter + * FIFO with the data found in the transmitter buffer that is passed via the + * tx_buffer function parameter. If the transmitter FIFO is not empty when the + * function is called, the function returns immediately without transferring + * any data to the FIFO; otherwise, the function transfers data from the + * transmitter buffer to the FIFO until it is full or until the complete + * contents of the transmitter buffer have been copied into the FIFO. The + * function returns the number of bytes copied into the UART's transmitter FIFO. + * + * Note: This function reads the UART�s line status register (LSR) to check + * for the active state of the transmitter holding register empty (THRE) bit + * before transferring data from the data buffer to the transmitter FIFO. If + * THRE is 0, the function returns immediately, without transferring any data + * to the FIFO. If THRE is 1, the function transfers up to 16 bytes of data to + * the FIFO and then returns. + * + * Note: The actual transmission over the serial connection will still be in + * progress when this function returns. Use the UART_16550_get_tx_status() + * function if you need to know when the transmitter is empty. + * + * @param this_uart The this_uart parameter is a pointer to a + * uart_16550_instance_t structure that holds all data + * regarding this instance of the Core16550. + * @param tx_buffer The tx_buffer parameter is a pointer to a buffer + * containing the data to be transmitted. + * @param tx_size The tx_size parameter is the size in bytes, of the data + * to be transmitted. + * @return This function returns the number of bytes copied + * into the UART's transmitter FIFO. + * + * Example: + * @code + * void send_using_interrupt(uint8_t * pbuff, size_t tx_size) + * { + * size_t size_in_fifo; + * size_in_fifo = UART_16550_fill_tx_fifo( &g_uart, pbuff, tx_size ); + * } + * @endcode + */ +size_t +UART_16550_fill_tx_fifo +( + uart_16550_instance_t * this_uart, + const uint8_t * tx_buffer, + size_t tx_size +); + +/***************************************************************************//** + * The UART_16550_get_tx_status() function returns the transmitter status of + * the Core16550 instance. It reads both the UART�s line status register (LSR) + * and returns the status of the transmit holding register empty (THRE) and + * transmitter empty (TEMT) bits. + * + * @param this_uart The this_uart parameter is a pointer to a + * uart_16550_instance_t structure that holds all data + * regarding this instance of the Core16550. + * @return This function returns the UART�s transmitter status + * as an 8-bit unsigned integer. The returned value is 0 + * if the transmitter status bits are not set or the + * function execution failed. The driver provides a set + * of bit mask constants that should be compared with + * and/or used to mask the returned value to determine + * the transmitter status. + * When the return value is compared to the following + * bitmasks, a non-zero result indicates that the + * corresponding transmitter status bit is set: + * � UART_16550_THRE (bit mask = 0x20) + * � UART_16550_TEMT (bit mask = 0x40) + * When the return value is compared to the following + * bit mask, a non-zero result indicates that the + * transmitter is busy or the function execution failed. + * � UART_16550_TX_BUSY (bit mask = 0x00) + * Example: + * @code + * uint8_t tx_buff[10] = "abcdefghi"; + * + * UART_16550_polled_tx( &g_uart, tx_buff, sizeof(tx_buff)); + * + * while ( ! (UART_16550_TEMT & UART_16550_get_tx_status( &g_uart ) ) ) + * { + * ; + * } + * @endcode + */ +uint8_t +UART_16550_get_tx_status +( + uart_16550_instance_t * this_uart +); + +#ifdef __cplusplus +} +#endif + +#endif /* __CORE_16550_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreGPIO/core_gpio.c b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreGPIO/core_gpio.c new file mode 100644 index 0000000..63cd377 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreGPIO/core_gpio.c @@ -0,0 +1,531 @@ +/******************************************************************************* + * (c) Copyright 2008-2021 Microchip FPGA Embedded Systems Solutions. + * + * @file core_gpio.c + * @author Microchip FPGA Embedded Systems Solutions + * @brief CoreGPIO bare metal driver implementation. + * + */ +#include "coregpio_regs.h" +#include "core_gpio.h" + +/*-------------------------------------------------------------------------*//** + * + */ +#define GPIO_INT_ENABLE_MASK (uint32_t)0x00000008UL +#define OUTPUT_BUFFER_ENABLE_MASK 0x00000004UL + + +#define NB_OF_GPIO 32 + +#define CLEAR_ALL_IRQ32 (uint32_t)0xFFFFFFFF +#define CLEAR_ALL_IRQ16 (uint16_t)0xFFFF +#define CLEAR_ALL_IRQ8 (uint8_t)0xFF + +/*-------------------------------------------------------------------------*//** + * GPIO_init() + * See "core_gpio.h" for details of how to use this function. + */ +void GPIO_init +( + gpio_instance_t * this_gpio, + addr_t base_addr, + gpio_apb_width_t bus_width +) +{ + uint8_t i = 0; + addr_t cfg_reg_addr = base_addr; + + this_gpio->base_addr = base_addr; + this_gpio->apb_bus_width = bus_width; + + /* Clear configuration. */ + for( i = 0, cfg_reg_addr = base_addr; i < NB_OF_GPIO; ++i ) + { + HW_set_8bit_reg( cfg_reg_addr, 0 ); + cfg_reg_addr += 4; + } + /* Clear any pending interrupts */ + switch( this_gpio->apb_bus_width ) + { + case GPIO_APB_32_BITS_BUS: + HAL_set_32bit_reg( this_gpio->base_addr, IRQ, CLEAR_ALL_IRQ32 ); + break; + + case GPIO_APB_16_BITS_BUS: + HAL_set_16bit_reg( this_gpio->base_addr, IRQ0, (uint16_t)CLEAR_ALL_IRQ16 ); + HAL_set_16bit_reg( this_gpio->base_addr, IRQ1, (uint16_t)CLEAR_ALL_IRQ16 ); + break; + + case GPIO_APB_8_BITS_BUS: + HAL_set_8bit_reg( this_gpio->base_addr, IRQ0, (uint8_t)CLEAR_ALL_IRQ8 ); + HAL_set_8bit_reg( this_gpio->base_addr, IRQ1, (uint8_t)CLEAR_ALL_IRQ8 ); + HAL_set_8bit_reg( this_gpio->base_addr, IRQ2, (uint8_t)CLEAR_ALL_IRQ8 ); + HAL_set_8bit_reg( this_gpio->base_addr, IRQ3, (uint8_t)CLEAR_ALL_IRQ8 ); + break; + + default: + HAL_ASSERT(0); + break; + } +} + +/*-------------------------------------------------------------------------*//** + * GPIO_config + * See "core_gpio.h" for details of how to use this function. + */ +void GPIO_config +( + gpio_instance_t * this_gpio, + gpio_id_t port_id, + uint32_t config +) +{ + HAL_ASSERT( port_id < NB_OF_GPIO ); + + if ( port_id < NB_OF_GPIO ) + { + uint32_t cfg_reg_addr = this_gpio->base_addr; + cfg_reg_addr += (port_id * 4); + HW_set_32bit_reg( cfg_reg_addr, config ); + + /* + * Verify that the configuration was correctly written. Failure to read + * back the expected value may indicate that the GPIO port was configured + * as part of the hardware flow and cannot be modified through software. + * It may also indicate that the base address passed as parameter to + * GPIO_init() was incorrect. + */ + HAL_ASSERT( HW_get_32bit_reg( cfg_reg_addr ) == config ); + } +} + +/*-------------------------------------------------------------------------*//** + * GPIO_set_outputs + * See "core_gpio.h" for details of how to use this function. + */ +void GPIO_set_outputs +( + gpio_instance_t * this_gpio, + uint32_t value +) +{ + switch( this_gpio->apb_bus_width ) + { + case GPIO_APB_32_BITS_BUS: + HAL_set_32bit_reg( this_gpio->base_addr, GPIO_OUT, value ); + break; + + case GPIO_APB_16_BITS_BUS: + HAL_set_16bit_reg( this_gpio->base_addr, GPIO_OUT0, (uint16_t)value ); + HAL_set_16bit_reg( this_gpio->base_addr, GPIO_OUT1, (uint16_t)(value >> 16) ); + break; + + case GPIO_APB_8_BITS_BUS: + HAL_set_8bit_reg( this_gpio->base_addr, GPIO_OUT0, (uint8_t)value ); + HAL_set_8bit_reg( this_gpio->base_addr, GPIO_OUT1, (uint8_t)(value >> 8) ); + HAL_set_8bit_reg( this_gpio->base_addr, GPIO_OUT2, (uint8_t)(value >> 16) ); + HAL_set_8bit_reg( this_gpio->base_addr, GPIO_OUT3, (uint8_t)(value >> 24) ); + break; + + default: + HAL_ASSERT(0); + break; + } + + /* + * Verify that the output register was correctly written. Failure to read back + * the expected value may indicate that some of the GPIOs may not exist due to + * the number of GPIOs selected in the CoreGPIO hardware flow configuration. + * It may also indicate that the base address or APB bus width passed as + * parameter to the GPIO_init() function do not match the hardware design. + */ + HAL_ASSERT( GPIO_get_outputs( this_gpio ) == value ); +} + +/*-------------------------------------------------------------------------*//** + * GPIO_get_inputs + * See "core_gpio.h" for details of how to use this function. + */ +uint32_t GPIO_get_inputs +( + gpio_instance_t * this_gpio +) +{ + uint32_t gpio_in = 0; + + switch( this_gpio->apb_bus_width ) + { + case GPIO_APB_32_BITS_BUS: + gpio_in = HAL_get_32bit_reg( this_gpio->base_addr, GPIO_IN ); + break; + + case GPIO_APB_16_BITS_BUS: + gpio_in |= HAL_get_16bit_reg( this_gpio->base_addr, GPIO_IN0 ); + gpio_in |= (HAL_get_16bit_reg( this_gpio->base_addr, GPIO_IN1 ) << 16); + break; + + case GPIO_APB_8_BITS_BUS: + gpio_in |= HAL_get_8bit_reg( this_gpio->base_addr, GPIO_IN0 ); + gpio_in |= (HAL_get_8bit_reg( this_gpio->base_addr, GPIO_IN1 ) << 8); + gpio_in |= (HAL_get_8bit_reg( this_gpio->base_addr, GPIO_IN2 ) << 16); + gpio_in |= (HAL_get_8bit_reg( this_gpio->base_addr, GPIO_IN3 ) << 24); + break; + + default: + HAL_ASSERT(0); + break; + } + + return gpio_in; +} + +/*-------------------------------------------------------------------------*//** + * GPIO_get_outputs + * See "core_gpio.h" for details of how to use this function. + */ +uint32_t GPIO_get_outputs +( + gpio_instance_t * this_gpio +) +{ + uint32_t gpio_out = 0; + + switch( this_gpio->apb_bus_width ) + { + case GPIO_APB_32_BITS_BUS: + gpio_out = HAL_get_32bit_reg( this_gpio->base_addr, GPIO_OUT ); + break; + + case GPIO_APB_16_BITS_BUS: + gpio_out |= HAL_get_16bit_reg( this_gpio->base_addr, GPIO_OUT0 ); + gpio_out |= (HAL_get_16bit_reg( this_gpio->base_addr, GPIO_OUT1 ) << 16); + break; + + case GPIO_APB_8_BITS_BUS: + gpio_out |= HAL_get_16bit_reg( this_gpio->base_addr, GPIO_OUT0 ); + gpio_out |= (HAL_get_16bit_reg( this_gpio->base_addr, GPIO_OUT1 ) << 8); + gpio_out |= (HAL_get_16bit_reg( this_gpio->base_addr, GPIO_OUT2 ) << 16); + gpio_out |= (HAL_get_16bit_reg( this_gpio->base_addr, GPIO_OUT3 ) << 24); + break; + + default: + HAL_ASSERT(0); + break; + } + + return gpio_out; +} + +/*-------------------------------------------------------------------------*//** + * GPIO_set_output + * See "core_gpio.h" for details of how to use this function. + */ +void GPIO_set_output +( + gpio_instance_t * this_gpio, + gpio_id_t port_id, + uint8_t value +) +{ + HAL_ASSERT( port_id < NB_OF_GPIO ); + + + switch( this_gpio->apb_bus_width ) + { + case GPIO_APB_32_BITS_BUS: + { + uint32_t outputs_state; + + outputs_state = HAL_get_32bit_reg( this_gpio->base_addr, GPIO_OUT ); + if ( 0 == value ) + { + outputs_state &= ~(1 << port_id); + } + else + { + outputs_state |= 1 << port_id; + } + HAL_set_32bit_reg( this_gpio->base_addr, GPIO_OUT, outputs_state ); + + /* + * Verify that the output register was correctly written. Failure to read back + * the expected value may indicate that some of the GPIOs may not exist due to + * the number of GPIOs selected in the CoreGPIO hardware flow configuration. + * It may also indicate that the base address or APB bus width passed as + * parameter to the GPIO_init() function do not match the hardware design. + */ + HAL_ASSERT( HAL_get_32bit_reg( this_gpio->base_addr, GPIO_OUT ) == outputs_state ); + } + break; + + case GPIO_APB_16_BITS_BUS: + { + uint16_t outputs_state; + uint32_t gpio_out_reg_addr = this_gpio->base_addr + GPIO_OUT_REG_OFFSET + ((port_id >> 4) * 4); + + outputs_state = HW_get_16bit_reg( gpio_out_reg_addr ); + if ( 0 == value ) + { + outputs_state &= ~(1 << (port_id & 0x0F)); + } + else + { + outputs_state |= 1 << (port_id & 0x0F); + } + HW_set_16bit_reg( gpio_out_reg_addr, outputs_state ); + + /* + * Verify that the output register was correctly written. Failure to read back + * the expected value may indicate that some of the GPIOs may not exist due to + * the number of GPIOs selected in the CoreGPIO hardware flow configuration. + * It may also indicate that the base address or APB bus width passed as + * parameter to the GPIO_init() function do not match the hardware design. + */ + HAL_ASSERT( HW_get_16bit_reg( gpio_out_reg_addr ) == outputs_state ); + } + break; + + case GPIO_APB_8_BITS_BUS: + { + uint8_t outputs_state; + uint32_t gpio_out_reg_addr = this_gpio->base_addr + GPIO_OUT_REG_OFFSET + ((port_id >> 3) * 4); + + outputs_state = HW_get_8bit_reg( gpio_out_reg_addr ); + if ( 0 == value ) + { + outputs_state &= ~(1 << (port_id & 0x07)); + } + else + { + outputs_state |= 1 << (port_id & 0x07); + } + HW_set_8bit_reg( gpio_out_reg_addr, outputs_state ); + + /* + * Verify that the output register was correctly written. Failure to read back + * the expected value may indicate that some of the GPIOs may not exist due to + * the number of GPIOs selected in the CoreGPIO hardware flow configuration. + * It may also indicate that the base address or APB bus width passed as + * parameter to the GPIO_init() function do not match the hardware design. + */ + HAL_ASSERT( HW_get_8bit_reg( gpio_out_reg_addr ) == outputs_state ); + } + break; + + default: + HAL_ASSERT(0); + break; + } +} + +/*-------------------------------------------------------------------------*//** + * GPIO_drive_inout + * See "core_gpio.h" for details of how to use this function. + */ +void GPIO_drive_inout +( + gpio_instance_t * this_gpio, + gpio_id_t port_id, + gpio_inout_state_t inout_state +) +{ + uint32_t config; + uint32_t cfg_reg_addr = this_gpio->base_addr; + + HAL_ASSERT( port_id < NB_OF_GPIO ); + + switch( inout_state ) + { + case GPIO_DRIVE_HIGH: + /* Set output high */ + GPIO_set_output( this_gpio, port_id, 1 ); + + /* Enable output buffer */ + cfg_reg_addr = this_gpio->base_addr + (port_id * 4); + config = HW_get_8bit_reg( cfg_reg_addr ); + config |= OUTPUT_BUFFER_ENABLE_MASK; + HW_set_8bit_reg( cfg_reg_addr, config ); + break; + + case GPIO_DRIVE_LOW: + /* Set output low */ + GPIO_set_output( this_gpio, port_id, 0 ); + + /* Enable output buffer */ + cfg_reg_addr = this_gpio->base_addr + (port_id * 4); + config = HW_get_8bit_reg( cfg_reg_addr ); + config |= OUTPUT_BUFFER_ENABLE_MASK; + HW_set_8bit_reg( cfg_reg_addr, config ); + break; + + case GPIO_HIGH_Z: + /* Disable output buffer */ + cfg_reg_addr = this_gpio->base_addr + (port_id * 4); + config = HW_get_8bit_reg( cfg_reg_addr ); + config &= ~OUTPUT_BUFFER_ENABLE_MASK; + HW_set_8bit_reg( cfg_reg_addr, config ); + break; + + default: + HAL_ASSERT(0); + break; + } +} + +/*-------------------------------------------------------------------------*//** + * GPIO_enable_irq + * See "core_gpio.h" for details of how to use this function. + */ +void GPIO_enable_irq +( + gpio_instance_t * this_gpio, + gpio_id_t port_id +) +{ + uint32_t cfg_value; + uint32_t cfg_reg_addr = this_gpio->base_addr; + + HAL_ASSERT( port_id < NB_OF_GPIO ); + + if ( port_id < NB_OF_GPIO ) + { + cfg_reg_addr += (port_id * 4); + cfg_value = HW_get_8bit_reg( cfg_reg_addr ); + cfg_value |= GPIO_INT_ENABLE_MASK; + HW_set_8bit_reg( cfg_reg_addr, cfg_value ); + } +} + +/*-------------------------------------------------------------------------*//** + * GPIO_disable_irq + * See "core_gpio.h" for details of how to use this function. + */ +void GPIO_disable_irq +( + gpio_instance_t * this_gpio, + gpio_id_t port_id +) +{ + uint32_t cfg_value; + uint32_t cfg_reg_addr = this_gpio->base_addr; + + HAL_ASSERT( port_id < NB_OF_GPIO ); + + if ( port_id < NB_OF_GPIO ) + { + cfg_reg_addr += (port_id * 4); + cfg_value = HW_get_8bit_reg( cfg_reg_addr ); + cfg_value &= ~GPIO_INT_ENABLE_MASK; + HW_set_8bit_reg( cfg_reg_addr, cfg_value ); + } +} + +/*-------------------------------------------------------------------------*//** + * GPIO_clear_irq + * See "core_gpio.h" for details of how to use this function. + */ +void GPIO_clear_irq +( + gpio_instance_t * this_gpio, + gpio_id_t port_id +) +{ + uint32_t irq_clr_value = ((uint32_t)1) << ((uint32_t)port_id); + + switch( this_gpio->apb_bus_width ) + { + case GPIO_APB_32_BITS_BUS: + HAL_set_32bit_reg( this_gpio->base_addr, IRQ, irq_clr_value ); + break; + + case GPIO_APB_16_BITS_BUS: + HAL_set_16bit_reg( this_gpio->base_addr, IRQ0, irq_clr_value ); + HAL_set_16bit_reg( this_gpio->base_addr, IRQ1, irq_clr_value >> 16 ); + break; + + case GPIO_APB_8_BITS_BUS: + HAL_set_8bit_reg( this_gpio->base_addr, IRQ0, irq_clr_value ); + HAL_set_8bit_reg( this_gpio->base_addr, IRQ1, irq_clr_value >> 8 ); + HAL_set_8bit_reg( this_gpio->base_addr, IRQ2, irq_clr_value >> 16 ); + HAL_set_8bit_reg( this_gpio->base_addr, IRQ3, irq_clr_value >> 24 ); + break; + + default: + HAL_ASSERT(0); + break; + } +} + +/*-------------------------------------------------------------------------*//** + * GPIO_get_irq_sources + * See "core_gpio.h" for details of how to use this function. + */ +uint32_t GPIO_get_irq_sources +( + gpio_instance_t * this_gpio +) +{ + uint32_t intr_src = 0; + + switch( this_gpio->apb_bus_width ) + { + case GPIO_APB_32_BITS_BUS: + intr_src = HAL_get_32bit_reg( this_gpio->base_addr, IRQ ); + break; + + case GPIO_APB_16_BITS_BUS: + intr_src |= HAL_get_16bit_reg( this_gpio->base_addr, IRQ0 ); + intr_src |= (HAL_get_16bit_reg( this_gpio->base_addr, IRQ1 ) << 16); + break; + + case GPIO_APB_8_BITS_BUS: + intr_src |= HAL_get_16bit_reg( this_gpio->base_addr, IRQ0 ); + intr_src |= (HAL_get_16bit_reg( this_gpio->base_addr, IRQ1 ) << 8); + intr_src |= (HAL_get_16bit_reg( this_gpio->base_addr, IRQ2 ) << 16); + intr_src |= (HAL_get_16bit_reg( this_gpio->base_addr, IRQ3 ) << 24); + break; + + default: + HAL_ASSERT(0); + break; + } + + return intr_src; +} + +/*-------------------------------------------------------------------------*//** + * GPIO_clear_all_irq_sources + * See "core_gpio.h" for details of how to use this function. + */ +void GPIO_clear_all_irq_sources +( + gpio_instance_t * this_gpio, + uint32_t bitmask +) +{ + uint32_t irq_clr_value = bitmask; + + switch( this_gpio->apb_bus_width ) + { + case GPIO_APB_32_BITS_BUS: + HAL_set_32bit_reg( this_gpio->base_addr, IRQ, irq_clr_value ); + break; + + case GPIO_APB_16_BITS_BUS: + HAL_set_16bit_reg( this_gpio->base_addr, IRQ0, irq_clr_value ); + HAL_set_16bit_reg( this_gpio->base_addr, IRQ1, irq_clr_value >> 16 ); + break; + + case GPIO_APB_8_BITS_BUS: + HAL_set_8bit_reg( this_gpio->base_addr, IRQ0, irq_clr_value ); + HAL_set_8bit_reg( this_gpio->base_addr, IRQ1, irq_clr_value >> 8 ); + HAL_set_8bit_reg( this_gpio->base_addr, IRQ2, irq_clr_value >> 16 ); + HAL_set_8bit_reg( this_gpio->base_addr, IRQ3, irq_clr_value >> 24 ); + break; + + default: + HAL_ASSERT(0); + break; + } +} diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreGPIO/core_gpio.h b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreGPIO/core_gpio.h new file mode 100644 index 0000000..3491d68 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreGPIO/core_gpio.h @@ -0,0 +1,654 @@ +/******************************************************************************* + * (c) Copyright 2008-2021 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * @file core_gpio.h + * @author Microchip FPGA Embedded Systems Solutions + * @brief CoreGPIO bare metal driver public API. + * + */ + +/*=========================================================================*//** + @mainpage CoreGPIO Bare Metal Driver. + + @section intro_sec Introduction + The CoreGPIO hardware IP includes up to 32 general purpose input output GPIOs. + This driver provides a set of functions for controlling the GPIOs as part of a + bare metal system where no operating system is available. These drivers + can be adapted for use as part of an operating system but the implementation + of the adaptation layer between this driver and the operating system's driver + model is outside the scope of this driver. + + @section driver_configuration Driver Configuration + The CoreGPIO individual IOs can be configured either in the hardware flow or + as part of the software application through calls to the GPIO_config() function. + GPIOs configured as as part of the hardware is fixed and cannot be modified + using a call to the GPI_config() function. + + @section theory_op Theory of Operation + The CoreGPIO driver uses the Actel Hardware Abstraction Layer (HAL) to access + hardware registers. You must ensure that the Actel HAL is included as part of + your software project. The Actel HAL is available through the Actel Firmware + Catalog. + + The CoreGPIO driver functions are logically grouped into the following groups: + - Initialization + - Configuration + - Reading and writing GPIO state + - Interrupt control + + The CoreGPIO driver is initialized through a call to the GPIO_init() function. + The GPIO_init() function must be called before any other GPIO driver functions + can be called. + + Each GPIO port is individually configured through a call to the + GPIO_config() function. Configuration includes deciding if a GPIO port + will be used as input, output or both. GPIO ports configured as inputs can be + further configured to generate interrupts based on the input's state. + Interrupts can be level or edge sensitive. + Please note that a CoreGPIO hardware instance can be generated, as part of the + hardware flow, with a fixed configuration for some or all of its IOs. Attempting + to modify the configuration of such a hardware configured IO using the + GPIO_config() function has no effect. + + The state of the GPIO ports can be read and written using the following + functions: + - GPIO_get_inputs() + - GPIO_get_outputs() + - GPIO_set_outputs() + - GPIO_drive_inout() + + Interrupts generated by GPIO ports configured as inputs are controlled using + the following functions: + - GPIO_enable_irq() + - GPIO_disable_irq() + - GPIO_clear_irq() + - GPIO_get_irq_sources() + - GPIO_clear_all_irq_sources() + + *//*=========================================================================*/ +#ifndef CORE_GPIO_H_ +#define CORE_GPIO_H_ + +#ifndef LEGACY_DIR_STRUCTURE +#include "hal/hal.h" + +#else +#include "hal.h" +#endif + +/*-------------------------------------------------------------------------*//** + The gpio_id_t enumeration is used to identify GPIOs as part of the + parameter to functions: + - GPIO_config(), + - GPIO_drive_inout(), + - GPIO_enable_int(), + - GPIO_disable_int(), + - GPIO_clear_int() + */ +typedef enum __gpio_id_t +{ + GPIO_0 = 0, + GPIO_1 = 1, + GPIO_2 = 2, + GPIO_3 = 3, + GPIO_4 = 4, + GPIO_5 = 5, + GPIO_6 = 6, + GPIO_7 = 7, + GPIO_8 = 8, + GPIO_9 = 9, + GPIO_10 = 10, + GPIO_11 = 11, + GPIO_12 = 12, + GPIO_13 = 13, + GPIO_14 = 14, + GPIO_15 = 15, + GPIO_16 = 16, + GPIO_17 = 17, + GPIO_18 = 18, + GPIO_19 = 19, + GPIO_20 = 20, + GPIO_21 = 21, + GPIO_22 = 22, + GPIO_23 = 23, + GPIO_24 = 24, + GPIO_25 = 25, + GPIO_26 = 26, + GPIO_27 = 27, + GPIO_28 = 28, + GPIO_29 = 29, + GPIO_30 = 30, + GPIO_31 = 31 +} gpio_id_t; + +typedef enum __gpio_apb_width_t +{ + GPIO_APB_8_BITS_BUS = 0, + GPIO_APB_16_BITS_BUS = 1, + GPIO_APB_32_BITS_BUS = 2, + GPIO_APB_UNKNOWN_BUS_WIDTH = 3 +} gpio_apb_width_t; + +/*-------------------------------------------------------------------------*//** + */ +typedef struct __gpio_instance_t +{ + addr_t base_addr; + gpio_apb_width_t apb_bus_width; +} gpio_instance_t; + +/*-------------------------------------------------------------------------*//** + GPIO ports definitions used to identify GPIOs as part of the parameter to + function GPIO_set_outputs(). + These definitions can also be used to identity GPIO through logical + operations on the return value of function GPIO_get_inputs(). + */ +#define GPIO_0_MASK 0x00000001UL +#define GPIO_1_MASK 0x00000002UL +#define GPIO_2_MASK 0x00000004UL +#define GPIO_3_MASK 0x00000008UL +#define GPIO_4_MASK 0x00000010UL +#define GPIO_5_MASK 0x00000020UL +#define GPIO_6_MASK 0x00000040UL +#define GPIO_7_MASK 0x00000080UL +#define GPIO_8_MASK 0x00000100UL +#define GPIO_9_MASK 0x00000200UL +#define GPIO_10_MASK 0x00000400UL +#define GPIO_11_MASK 0x00000800UL +#define GPIO_12_MASK 0x00001000UL +#define GPIO_13_MASK 0x00002000UL +#define GPIO_14_MASK 0x00004000UL +#define GPIO_15_MASK 0x00008000UL +#define GPIO_16_MASK 0x00010000UL +#define GPIO_17_MASK 0x00020000UL +#define GPIO_18_MASK 0x00040000UL +#define GPIO_19_MASK 0x00080000UL +#define GPIO_20_MASK 0x00100000UL +#define GPIO_21_MASK 0x00200000UL +#define GPIO_22_MASK 0x00400000UL +#define GPIO_23_MASK 0x00800000UL +#define GPIO_24_MASK 0x01000000UL +#define GPIO_25_MASK 0x02000000UL +#define GPIO_26_MASK 0x04000000UL +#define GPIO_27_MASK 0x08000000UL +#define GPIO_28_MASK 0x10000000UL +#define GPIO_29_MASK 0x20000000UL +#define GPIO_30_MASK 0x40000000UL +#define GPIO_31_MASK 0x80000000UL + +/*-------------------------------------------------------------------------*//** + * GPIO modes + */ +#define GPIO_INPUT_MODE 0x0000000002UL +#define GPIO_OUTPUT_MODE 0x0000000005UL +#define GPIO_INOUT_MODE 0x0000000003UL + +/*-------------------------------------------------------------------------*//** + * Possible GPIO inputs interrupt configurations. + */ +#define GPIO_IRQ_LEVEL_HIGH 0x0000000000UL +#define GPIO_IRQ_LEVEL_LOW 0x0000000020UL +#define GPIO_IRQ_EDGE_POSITIVE 0x0000000040UL +#define GPIO_IRQ_EDGE_NEGATIVE 0x0000000060UL +#define GPIO_IRQ_EDGE_BOTH 0x0000000080UL + +/*-------------------------------------------------------------------------*//** + * Possible states for GPIO configured as INOUT. + */ +typedef enum gpio_inout_state +{ + GPIO_DRIVE_LOW = 0, + GPIO_DRIVE_HIGH, + GPIO_HIGH_Z +} gpio_inout_state_t; + +/*-------------------------------------------------------------------------*//** + The GPIO_init() function initialises a CoreGPIO hardware instance and the data + structure associated with the CoreGPIO hardware instance. + Please note that a CoreGPIO hardware instance can be generated with a fixed + configuration for some or all of its IOs as part of the hardware flow. Attempting + to modify the configuration of such a hardware configured IO using the + GPIO_config() function has no effect. + + @param this_gpio + Pointer to the gpio_instance_t data structure instance holding all data + regarding the CoreGPIO hardware instance being initialized. A pointer to the + same data structure will be used in subsequent calls to the CoreGPIO driver + functions in order to identify the CoreGPIO instance that should perform the + operation implemented by the called driver function. + + @param base_addr + The base_addr parameter is the base address in the processor's memory map for + the registers of the GPIO instance being initialized. + + @param bus_width + The bus_width parameter informs the driver of the APB bus width selected during + the hardware flow configuration of the CoreGPIO hardware instance. It indicates + to the driver whether the CoreGPIO hardware registers will be visible as 8, 16 + or 32 bits registers. Allowed value are: + - GPIO_APB_8_BITS_BUS + - GPIO_APB_16_BITS_BUS + - GPIO_APB_32_BITS_BUS + + @return + none. + + Example: + @code + #define COREGPIO_BASE_ADDR 0xC2000000 + + gpio_instance_t g_gpio; + + void system_init( void ) + { + GPIO_init( &g_gpio, COREGPIO_BASE_ADDR, GPIO_APB_32_BITS_BUS ); + } + @endcode + */ +void GPIO_init +( + gpio_instance_t * this_gpio, + addr_t base_addr, + gpio_apb_width_t bus_width +); + +/*-------------------------------------------------------------------------*//** + The GPIO_config() function is used to configure an individual GPIO port. + + @param this_gpio + The this_gpio parameter is a pointer to the gpio_instance_t structure holding + all data regarding the CoreGPIO instance controlled through this function call. + + @param port_id + The port_id parameter identifies the GPIO port to be configured. + An enumeration item of the form GPIO_n where n is the number of the GPIO + port is used to identify the GPIO port. For example GPIO_0 identifies the + first GPIO port and GPIO_31 the last one. + + @param config + The config parameter specifies the configuration to be applied to the GPIO + port identified by the first parameter. It is a logical OR of GPIO mode and + the interrupt mode. The interrupt mode is only relevant if the GPIO is + configured as input. + Possible modes are: + - GPIO_INPUT_MODE, + - GPIO_OUTPUT_MODE, + - GPIO_INOUT_MODE. + Possible interrupt modes are: + - GPIO_IRQ_LEVEL_HIGH, + - GPIO_IRQ_LEVEL_LOW, + - GPIO_IRQ_EDGE_POSITIVE, + - GPIO_IRQ_EDGE_NEGATIVE, + - GPIO_IRQ_EDGE_BOTH + + @return + none. + + For example the following call will configure GPIO 4 as an input generating + interrupts on a low to high transition of the input: + @code + GPIO_config( &g_gpio, GPIO_4, GPIO_INPUT_MODE | GPIO_IRQ_EDGE_POSITIVE ); + @endcode + */ +void GPIO_config +( + gpio_instance_t * this_gpio, + gpio_id_t port_id, + uint32_t config +); + +/*-------------------------------------------------------------------------*//** + The GPIO_set_outputs() function is used to set the state of the GPIO ports + configured as outputs. + + @param this_gpio + The this_gpio parameter is a pointer to the gpio_instance_t structure holding + all data regarding the CoreGPIO instance controlled through this function call. + + @param value + The value parameter specifies the state of the GPIO ports configured as + outputs. It is a bit mask of the form (GPIO_n_MASK | GPIO_m_MASK) where n + and m are numbers identifying GPIOs. + For example (GPIO_0_MASK | GPIO_1_MASK | GPIO_2_MASK ) specifies that the + first, second and third GPIOs' must be set high and all other outputs set + low. + + @return + none. + + Example 1: + Set GPIOs outputs 0 and 8 high and all other GPIO outputs low. + @code + GPIO_set_outputs( &g_gpio, GPIO_0_MASK | GPIO_8_MASK ); + @endcode + + Example 2: + Set GPIOs outputs 2 and 4 low without affecting other GPIO outputs. + @code + uint32_t gpio_outputs; + gpio_outputs = GPIO_get_outputs( &g_gpio ); + gpio_outputs &= ~( GPIO_2_MASK | GPIO_4_MASK ); + GPIO_set_outputs( &g_gpio, gpio_outputs ); + @endcode + + @see GPIO_get_outputs() + */ +void GPIO_set_outputs +( + gpio_instance_t * this_gpio, + uint32_t value +); + +/*-------------------------------------------------------------------------*//** + The GPIO_set_output() function is used to set the state of a single GPIO + port configured as output. + + @param this_gpio + The this_gpio parameter is a pointer to the gpio_instance_t structure holding + all data regarding the CoreGPIO instance controlled through this function call. + + @param port_id + The port_id parameter specifies the GPIO port that will have its output set + by a call to this function. + + @param value + The value parameter specifies the desired state for the GPIO output. A value + of 0 will set the output low and a value of 1 will set the port high. + + @return + none. + */ +void GPIO_set_output +( + gpio_instance_t * this_gpio, + gpio_id_t port_id, + uint8_t value +); + +/*-------------------------------------------------------------------------*//** + The GPIO_get_inputs() function is used to read the state of all GPIOs + configured as inputs. + + @param this_gpio + The this_gpio parameter is a pointer to the gpio_instance_t structure holding + all data regarding the CoreGPIO instance controlled through this function call. + + @return + This function returns a 32 bit unsigned integer where each bit represents + the state of an input. The least significant bit representing the state of + GPIO 0 and the most significant bit the state of GPIO 31. + */ +uint32_t GPIO_get_inputs +( + gpio_instance_t * this_gpio +); + +/*-------------------------------------------------------------------------*//** + The GPIO_get_outputs() function is used to read the current state of all + GPIO outputs. + + @param this_gpio + The this_gpio parameter is a pointer to the gpio_instance_t structure holding + all data regarding the CoreGPIO instance controlled through this function call. + + @return + This function returns a 32 bit unsigned integer where each bit represents + the state of an output. The least significant bit representing the state + of GPIO 0 and the most significant bit the state of GPIO 31. + */ +uint32_t GPIO_get_outputs +( + gpio_instance_t * this_gpio +); + +/*-------------------------------------------------------------------------*//** + The GPIO_drive_inout() function is used to set the output state of a + GPIO configured as INOUT. An INOUT GPIO can be in one of three states: + - high + - low + - high impedance + An INOUT output would typically be used where several devices can drive the + state of a signal. The high and low states are equivalent to the high and low + states of a GPIO configured as output. The high impedance state is used to + prevent the GPIO from driving the state of the output and therefore allow + reading the state of the GPIO as an input. + Please note that the GPIO port you wish to use as INOUT through this function + must be configurable through software. Therefore the GPIO ports used as INOUT + must not have a fixed configuration selected as part of the hardware flow. + + @param this_gpio + The this_gpio parameter is a pointer to the gpio_instance_t structure holding + all data regarding the CoreGPIO instance controlled through this function call. + + @param port_id + The port_id parameter identifies the GPIO for which this function will + change the output state. + An enumeration item of the form GPIO_n where n is the number of the GPIO + port is used to identify the GPIO port. For example GPIO_0 identifies the + first GPIO port and GPIO_31 the last one. + + @param inout_state + The inout_state parameter specifies the state of the I/O identified by the + first parameter. Possible states are: + - GPIO_DRIVE_HIGH, + - GPIO_DRIVE_LOW, + - GPIO_HIGH_Z (high impedance) + + @return + none. + + Example: + The call to GPIO_drive_inout() below will set the GPIO 7 output to + high impedance state. + @code + GPIO_drive_inout( &g_gpio, GPIO_7, GPIO_HIGH_Z ); + @endcode + */ +void GPIO_drive_inout +( + gpio_instance_t * this_gpio, + gpio_id_t port_id, + gpio_inout_state_t inout_state +); + +/*-------------------------------------------------------------------------*//** + The GPIO_enable_irq() function is used to enable an interrupt to be + generated based on the state of the input identified as parameter. + + @param this_gpio + The this_gpio parameter is a pointer to the gpio_instance_t structure holding + all data regarding the CoreGPIO instance controlled through this function call. + + @param port_id + The port_id parameter identifies the GPIO input the call to + GPIO_enable_irq() will enable to generate interrupts. + An enumeration item of the form GPIO_n where n is the number of the GPIO + port is used to identify the GPIO port. For example GPIO_0 identifies the + first GPIO port and GPIO_31 the last one. + + @return + none. + + Example: + The call to GPIO_enable_irq() below will allow GPIO 8 to generate + interrupts. + @code + GPIO_enable_irq( &g_gpio, GPIO_8 ); + @endcode + */ +void GPIO_enable_irq +( + gpio_instance_t * this_gpio, + gpio_id_t port_id +); + +/*-------------------------------------------------------------------------*//** + The GPIO_disable_irq() function is used to disable interrupt from being + generated based on the state of the input specified as parameter. + + @param this_gpio + The this_gpio parameter is a pointer to the gpio_instance_t structure holding + all data regarding the CoreGPIO instance controlled through this function call. + + @param port_id + The port_id parameter identifies the GPIO input the call to + GPIO_disable_irq() will disable from generating interrupts. + An enumeration item of the form GPIO_n where n is the number of the GPIO + port is used to identify the GPIO port. For example GPIO_0 identifies the + first GPIO port and GPIO_31 the last one. + + @return + none. + + Example: + The call to GPIO_disable_irq() below will prevent GPIO 8 from generating + interrupts. + @code + GPIO_disable_irq( &g_gpio, GPIO_8 ); + @endcode + */ +void GPIO_disable_irq +( + gpio_instance_t * this_gpio, + gpio_id_t port_id +); + +/*-------------------------------------------------------------------------*//** + The GPIO_clear_irq() function is used to clear the interrupt generated by + the GPIO specified as parameter. The GPIO_clear_irq() function must be + called as part of a GPIO interrupt service routine (ISR) in order to prevent + the same interrupt event re-triggering a call to the GPIO ISR. + Please note that interrupts may also need to be cleared in the processor's + interrupt controller. + + @param this_gpio + The this_gpio parameter is a pointer to the gpio_instance_t structure holding + all data regarding the CoreGPIO instance controlled through this function call. + + @param port_id + The port_id parameter identifies the GPIO input for which to clear the + interrupt. + An enumeration item of the form GPIO_n where n is the number of the GPIO + port is used to identify the GPIO port. For example GPIO_0 identifies the + first GPIO port and GPIO_31 the last one. + + @return + none. + + Example: + The example below demonstrates the use of the GPIO_clear_irq() function as + part of the GPIO 9 interrupt service routine. + @code + void GPIO9_IRQHandler( void ) + { + do_interrupt_processing(); + + GPIO_clear_irq( &g_gpio, GPIO_9 ); + + NVIC_ClearPendingIRQ( GPIO9_IRQn ); + } + @endcode + */ +void GPIO_clear_irq +( + gpio_instance_t * this_gpio, + gpio_id_t port_id +); + +/*-------------------------------------------------------------------------*//** + The GPIO_get_irq_sources() function is used to identify the source of + interrupt. i.e. the GPIO input line whose state change triggered the interrupt. + The GPIO_get_irq_sources() function must be called as part of a GPIO + interrupt service routine (ISR) in order to determine the interrupt source. + + @param this_gpio + The this_gpio parameter is a pointer to the gpio_instance_t structure holding + all data regarding the CoreGPIO instance controlled through this function call. + + @return + This function returns a 32 bit unsigned integer where each bit represents + the pin number of GPIO. + + Example: + The example below demonstrates the use of the GPIO_get_irq_sources() function + as part of the GPIO 9 interrupt service routine. + @code + void GPIO9_IRQHandler( void ) + { + do_interrupt_processing(); + + GPIO_clear_all_irq_sources(g_p_mygpio, GPIO_get_irq_sources(g_p_mygpio)); + + NVIC_ClearPendingIRQ( GPIO9_IRQn ); + } + @endcode + */ +uint32_t GPIO_get_irq_sources +( + gpio_instance_t * this_gpio +); + +/*-------------------------------------------------------------------------*//** + The GPIO_clear_all_irq_sources() function is used to clear the all the active + interrupt generated by the GPIO specified as parameter. The + GPIO_clear_all_irq_sources() function must be called as part of a GPIO interrupt + service routine (ISR) in order to prevent the same interrupt event + re-triggering a call to the GPIO ISR. + Please note that interrupts may also need to be cleared in the processor's + interrupt controller. + + @param this_gpio + The this_gpio parameter is a pointer to the gpio_instance_t structure holding + all data regarding the CoreGPIO instance controlled through this function call. + + @param bitmask + This bitmask parameter is a 32 bit unsigned integer where each bit represents + the GPIO pin used to clears the interrupt bit register of the corresponding + GPIO bit. The least significant bit representing the status of GPIO 0 and + the most significant bit the status of GPIO 31. + + @return + none. + + Example: + The example below demonstrates the use of the GPIO_clear_all_irq_sources() function as + part of the GPIO 9 interrupt service routine. + @code + void GPIO9_IRQHandler( void ) + { + do_interrupt_processing(); + + do_interrupt_processing(); + + GPIO_clear_all_irq_sources(g_p_mygpio, GPIO_get_irq_sources(g_p_mygpio)); + + NVIC_ClearPendingIRQ( GPIO9_IRQn ); + } + @endcode + */ +void GPIO_clear_all_irq_sources +( + gpio_instance_t * this_gpio, + uint32_t bitmask +); +#endif /* CORE_GPIO_H_ */ diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreGPIO/coregpio_regs.h b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreGPIO/coregpio_regs.h new file mode 100644 index 0000000..0c13e28 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreGPIO/coregpio_regs.h @@ -0,0 +1,43 @@ +/******************************************************************************* + * (c) Copyright 2008-2021 Microchip FPGA Embedded Systems Solutions. + * + * @file coregpio_regs.h + * @author Microchip FPGA Embedded Systems Solutions + * @brief CoreGPIO register definitions + * + */ + +#ifndef __CORE_GPIO_REGISTERS_H +#define __CORE_GPIO_REGISTERS_H 1 + +/*------------------------------------------------------------------------------ + * + */ +#define IRQ_REG_OFFSET 0x80 + +#define IRQ0_REG_OFFSET 0x80 +#define IRQ1_REG_OFFSET 0x84 +#define IRQ2_REG_OFFSET 0x88 +#define IRQ3_REG_OFFSET 0x8C + +/*------------------------------------------------------------------------------ + * + */ +#define GPIO_IN_REG_OFFSET 0x90 + +#define GPIO_IN0_REG_OFFSET 0x90 +#define GPIO_IN1_REG_OFFSET 0x94 +#define GPIO_IN2_REG_OFFSET 0x98 +#define GPIO_IN3_REG_OFFSET 0x9C + +/*------------------------------------------------------------------------------ + * + */ +#define GPIO_OUT_REG_OFFSET 0xA0 + +#define GPIO_OUT0_REG_OFFSET 0xA0 +#define GPIO_OUT1_REG_OFFSET 0xA4 +#define GPIO_OUT2_REG_OFFSET 0xA8 +#define GPIO_OUT3_REG_OFFSET 0xAC + +#endif /* __CORE_GPIO_REGISTERS_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreSysServices_PF/core_sysservices_pf.c b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreSysServices_PF/core_sysservices_pf.c new file mode 100644 index 0000000..82ab53f --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreSysServices_PF/core_sysservices_pf.c @@ -0,0 +1,844 @@ +/******************************************************************************* + * (c) Copyright 2019-2021 Microchip FPGA Embedded Systems Solutions. + * + * PF_System_Services driver implementation. See file "core_syservices_pf.h" for + * description of the functions implemented in this file. + * + */ +#ifndef LEGACY_DIR_STRUCTURE +#include "hal/hal.h" +#include "core_sysservices_pf.h" +#include "coresysservicespf_regs.h" + +#else +#include "hal.h" +#include "core_sysservices_pf.h" +#include "coresysservicespf_regs.h" +#include "hal_assert.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#define NULL_BUFFER (( uint8_t* ) 0) + +static uint8_t execute_ss_command +( + uint8_t cmd_opcode, + const uint8_t* cmd_data, + uint16_t cmd_data_size, + const uint8_t* p_response, + uint16_t response_size, + uint16_t mb_offset, + uint16_t response_offset +); + +uint32_t g_css_pf_base_addr = 0u; + +/***************************************************************************//** + * SYS_init() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +void +SYS_init +( + uint32_t base_addr +) +{ + g_css_pf_base_addr = base_addr; +} + +/***************************************************************************//** + * SYS_get_serial_number() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t +SYS_get_serial_number +( + const uint8_t * p_serial_number, + uint16_t mb_offset +) +{ + uint8_t status = SYS_PARAM_ERR; + + if (p_serial_number == NULL_BUFFER) + { + return status; + } + + status = execute_ss_command(SERIAL_NUMBER_REQUEST_CMD, + NULL_BUFFER, + 0u, + p_serial_number, + SERIAL_NUMBER_RESP_LEN, + mb_offset, + 0u); + + return status; +} + +/***************************************************************************//** + * SYS_get_user_code() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t +SYS_get_user_code +( + const uint8_t * p_user_code, + uint16_t mb_offset +) +{ + uint8_t status = SYS_PARAM_ERR; + + if(p_user_code == NULL_BUFFER) + { + return status; + } + + status = execute_ss_command(USERCODE_REQUEST_CMD, + NULL_BUFFER, + 0u, + p_user_code, + USERCODE_RESP_LEN, + mb_offset, + 0u); + return status; +} + +/***************************************************************************//** + * SYS_get_design_info() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t +SYS_get_design_info +( + const uint8_t * p_design_info, + uint16_t mb_offset +) +{ + uint8_t status = SYS_PARAM_ERR; + + if(p_design_info == NULL_BUFFER) + { + return status; + } + + status = execute_ss_command(DESIGN_INFO_REQUEST_CMD, + NULL_BUFFER, + 0u, + p_design_info, + DESIGN_INFO_RESP_LEN, + mb_offset, + 0u); + return status; +} + +/***************************************************************************//** + * SYS_get_device_certificate() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t +SYS_get_device_certificate +( + const uint8_t * p_device_certificate, + uint16_t mb_offset +) +{ + uint8_t status = SYS_PARAM_ERR; + + if(p_device_certificate == NULL_BUFFER) + { + return status; + } + + status = execute_ss_command(DEVICE_CERTIFICATE_REQUEST_CMD, + NULL_BUFFER, + 0u, + p_device_certificate, + DEVICE_CERTIFICATE_RESP_LEN, + mb_offset, + 0u); + return status; +} + +/***************************************************************************//** + * SYS_read_digest() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t SYS_read_digest +( + const uint8_t * p_digest, + uint16_t mb_offset +) +{ + uint8_t status = SYS_PARAM_ERR; + + if(p_digest == NULL_BUFFER) + { + return status; + } + +#ifndef CORESYSSERVICES_MPFS + status = execute_ss_command(READ_DIGEST_REQUEST_CMD, + NULL_BUFFER, + 0u, + p_digest, + READ_DIGEST_RESP_LEN, + mb_offset, + 0u); +#else + status = execute_ss_command(READ_DIGEST_REQUEST_CMD, + NULL_BUFFER, + 0u, + p_digest, + READ_DIGEST_MPFS_RESP_LEN, + mb_offset, + 0u); +#endif + return status; + +} + +/***************************************************************************//** + * SYS_query_security() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t SYS_query_security +( + uint8_t * p_security_locks, + uint16_t mb_offset +) +{ + uint8_t status = SYS_PARAM_ERR; + uint8_t idx = 0u; + + if(p_security_locks == NULL_BUFFER) + { + return status; + } + +#ifndef CORESYSSERVICES_MPFS + uint8_t buf[12] = {0}; + /* Actual QUERY_SECURITY_RESP_LEN is 9 or 33 but PF_System_Services core + * needs number of words instead of number of bytes to be written to or read + * from MailBox */ + status = execute_ss_command(QUERY_SECURITY_REQUEST_CMD, + NULL_BUFFER, + 0u, + buf, + (QUERY_SECURITY_RESP_LEN + 3u), + mb_offset, + 0u); + + for (idx = 0u; idx < 9u; idx++) + { + *(p_security_locks+idx) = buf[idx]; + } + +#else + uint8_t buf[36] = {0}; + + status = execute_ss_command(QUERY_SECURITY_REQUEST_CMD, + NULL_BUFFER, + 0u, + buf, + (QUERY_SECURITY_MPFS_RESP_LEN + 3u), + mb_offset, + 0u); + + for (idx = 0u; idx < 33u; idx++) + { + *(p_security_locks+idx) = buf[idx]; + } + +#endif + + return status; +} + +/***************************************************************************//** + * SYS_read_debug_info() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t SYS_read_debug_info +( + const uint8_t * p_debug_info, + uint16_t mb_offset +) +{ + uint8_t status = SYS_PARAM_ERR; + + if(p_debug_info == NULL_BUFFER) + { + return status; + } + + status = execute_ss_command(READ_DEBUG_INFO_REQUEST_CMD, + NULL_BUFFER, + 0u, + p_debug_info, + READ_DEBUG_INFO_RESP_LEN, + mb_offset, + 0u); + return status; +} + +#ifdef CORESYSSERVICES_MPFS +/***************************************************************************//** + * SYS_read_envm_parameter() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t SYS_read_envm_parameter +( + uint8_t * p_envm_param, + uint16_t mb_offset +) +{ + uint8_t status = SYS_PARAM_ERR; + + if(p_envm_param == NULL_BUFFER) + { + return status; + } + + status = execute_ss_command(READ_ENVM_PARAM_REQUEST_CMD, + NULL_BUFFER, + 0, + p_envm_param, + READ_ENVM_PARAM_RESP_LEN, + mb_offset, + 0); + return status; +} + +#endif + +/***************************************************************************//** + * SYS_puf_emulation_service() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t SYS_puf_emulation_service +( + const uint8_t * p_challenge, + uint8_t op_type, + uint8_t* p_response, + uint16_t mb_offset +) +{ + uint8_t status = SYS_PARAM_ERR; + uint8_t mb_format[20] = {0x00}; + uint8_t index = 0u; + + if((p_response == NULL_BUFFER) || (p_challenge == NULL_BUFFER)) + { + return status; + } + + /* Frame the data required for mailbox */ + mb_format[index] = op_type; + + for (index = 4u; index < 20u; index++) + { + mb_format[index] = p_challenge[index - 4u]; + } + + status = execute_ss_command(PUF_EMULATION_SERVICE_REQUEST_CMD, + mb_format, + PUF_EMULATION_SERVICE_CMD_LEN, + p_response, + PUF_EMULATION_SERVICE_RESP_LEN, + mb_offset, + 5u); /* mentioning offset to number of words instead of bytes */ + + return status; +} + +/***************************************************************************//** + * SYS_digital_signature_service() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t SYS_digital_signature_service +( + const uint8_t* p_hash, + uint8_t format, + uint8_t* p_response, + uint16_t mb_offset +) +{ + uint8_t status = SYS_PARAM_ERR; + + if((p_hash == NULL_BUFFER) || (p_response == NULL_BUFFER)) + { + return status; + } + + if (format == DIGITAL_SIGNATURE_RAW_FORMAT_REQUEST_CMD) + { + status = execute_ss_command(DIGITAL_SIGNATURE_RAW_FORMAT_REQUEST_CMD, + p_hash, + DIGITAL_SIGNATURE_HASH_LEN, + p_response, + DIGITAL_SIGNATURE_RAW_FORMAT_RESP_SIZE, + mb_offset, + 12u); /* mentioning offset to number of words instead of bytes */ + } + else + { + status = execute_ss_command(DIGITAL_SIGNATURE_DER_FORMAT_REQUEST_CMD, + p_hash, + DIGITAL_SIGNATURE_HASH_LEN, + p_response, + DIGITAL_SIGNATURE_DER_FORMAT_RESP_SIZE, + mb_offset, + 12u); /* mentioning offset to number of words instead of bytes */ + } + + return status; +} + +/***************************************************************************//** + * SYS_secure_nvm_write() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t SYS_secure_nvm_write +( + uint8_t format, + uint8_t snvm_module, + const uint8_t* p_data, + const uint8_t* p_user_key, + uint16_t mb_offset +) +{ + uint8_t frame[256] = {0x00}; + uint8_t* p_frame = &frame[0]; + uint16_t index = 0u; + uint8_t status = SYS_PARAM_ERR; + + HAL_ASSERT(!(NULL_BUFFER == p_data)); + HAL_ASSERT(!(NULL_BUFFER == p_user_key)); + HAL_ASSERT(!(snvm_module >= 221u)); + + if((p_data == NULL_BUFFER) || (p_user_key == NULL_BUFFER) + || (snvm_module >= 221)) + { + return status; + } + + if ((format != SNVM_NON_AUTHEN_TEXT_REQUEST_CMD) + || (format != SNVM_AUTHEN_TEXT_REQUEST_CMD) + || (format != SNVM_AUTHEN_CIPHERTEXT_REQUEST_CMD)) + { + return status; + } + + *p_frame = snvm_module; /* SNVMADDR - SNVM module */ + + p_frame += 4u; /* Next 3 bytes RESERVED - For alignment */ + + /* Copy user key and send the command/data to mailbox. */ + if ((format == SNVM_AUTHEN_TEXT_REQUEST_CMD) || + (format == SNVM_AUTHEN_CIPHERTEXT_REQUEST_CMD)) + { + /* Copy user data */ + for (index = 0u; index < (AUTHENTICATED_TEXT_DATA_LEN - USER_SECRET_KEY_LEN - 4u); index++) + { + *p_frame = p_data[index]; + p_frame++; + } + + /* Copy user key */ + for (index = 0u; index < USER_SECRET_KEY_LEN; index++) + { + *p_frame = p_user_key[index]; + p_frame++; + } + + status = execute_ss_command(format, + &frame[0], + AUTHENTICATED_TEXT_DATA_LEN, + NULL_BUFFER, + 0u, + mb_offset, + 0u); + } + else + { + /* Copy user data */ + for (index = 0u; index < (NON_AUTHENTICATED_TEXT_DATA_LEN - 4u); index++) + { + *(p_frame+index) = p_data[index]; + } + + status = execute_ss_command(format, + &frame[0], + NON_AUTHENTICATED_TEXT_DATA_LEN, + NULL_BUFFER, + 0u, + mb_offset, + 0u); + } + + return status; +} + +/***************************************************************************//** + * SYS_secure_nvm_read() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t SYS_secure_nvm_read +( + uint8_t snvm_module, + const uint8_t* p_user_key, + uint8_t* p_admin, + uint8_t* p_data, + uint16_t data_len, + uint16_t mb_offset +) +{ + /* Frame the message. */ + uint8_t frame[16] = {0x00u}; + uint8_t* p_frame = &frame[0u]; + uint8_t status = SYS_PARAM_ERR; + uint8_t response[256] = {0x00u}; + uint16_t index = 0u; + + HAL_ASSERT(!(NULL_BUFFER == p_data)); + HAL_ASSERT(!(NULL_BUFFER == p_admin)); + HAL_ASSERT(!(snvm_module > 221u)); + + HAL_ASSERT(data_len == 236u || data_len == 252u); + + if((p_data == NULL_BUFFER) || + (snvm_module >= 221) || + (p_admin == NULL_BUFFER)) + { + return status; + } + + *p_frame = snvm_module; /* SNVMADDR - SNVM module */ + + p_frame += 4u; /* RESERVED - For alignment */ + + /* Copy user key */ + if (236u == data_len) + { + HAL_ASSERT(p_user_key != NULL_BUFFER); + + if(p_user_key == NULL_BUFFER) + { + return status; + } + + for (index = 0u; index < 12u; index++) + { + *p_frame = p_user_key[index]; + p_frame++; + } + } + else + { + p_frame += 12u; + } + + status = execute_ss_command(SNVM_READ_REQUEST_CMD, + &frame[0], + 16u, + response, + (data_len + 4u), + mb_offset, + 4u); /* mentioning offset to number of words instead of bytes */ + + if (SYS_SUCCESS == status) + { + for (index = 0u; index < 4u; index++) + { + *(p_admin+index) = (uint32_t)response[index]; + } + + + /* Copy data into user buffer. */ + for (index = 4u; index < (data_len + 4u); index++) + { + *(p_data + (index - 4u)) = response[index]; + } + } + else + { + ; + } + + return status; +} + +/***************************************************************************//** + * SYS_nonce_service() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t SYS_nonce_service +( + const uint8_t * p_nonce, + uint16_t mb_offset +) +{ + uint8_t status = SYS_PARAM_ERR; + + if((p_nonce == NULL_BUFFER)) + { + return status; + } + + status = execute_ss_command(NONCE_SERVICE_REQUEST_CMD, + NULL_BUFFER, + 0u, + p_nonce, + NONCE_SERVICE_RESP_LEN, + mb_offset, + 0u); + + return status; +} + +/***************************************************************************//** + * SYS_bitstream_authenticate_service() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t SYS_bitstream_authenticate_service +( + uint32_t spi_flash_address, + uint16_t mb_offset +) +{ + uint8_t status = SYS_PARAM_ERR; + uint32_t l_spi_flash_address = spi_flash_address; + status = execute_ss_command(BITSTREAM_AUTHENTICATE_CMD, + (uint8_t* )&l_spi_flash_address, + 4u, + NULL_BUFFER, + 0u, + mb_offset, + 0u); + + return status; +} + +/***************************************************************************//** + * SYS_IAP_image_authenticate_service() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t SYS_IAP_image_authenticate_service +( + uint8_t spi_idx +) +{ + uint8_t status = SYS_PARAM_ERR; + + HAL_ASSERT(!(spi_idx == 1u)); + + if (spi_idx == 1u) + { + return status; + } + + status = execute_ss_command(IAP_BITSTREAM_AUTHENTICATE_CMD, + NULL_BUFFER, + 0u, + NULL_BUFFER, + 0u, + spi_idx, + 0u); + + return status; +} + +/***************************************************************************//** + * SYS_digest_check_service() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t SYS_digest_check_service +( + uint32_t options, + uint16_t mb_offset +) +{ + uint8_t status = SYS_PARAM_ERR; + uint32_t l_options = options; + + status = execute_ss_command(DIGEST_CHECK_CMD, + (uint8_t* )&l_options, + 4u, + NULL_BUFFER, + 0u, + mb_offset, + 0u); + return status; +} + +/***************************************************************************//** + * SYS_iap_service() + * See "core_sysservices_pf.h" for details of how to use this function. + */ +uint8_t SYS_iap_service +( + uint8_t iap_cmd, + uint32_t spiaddr +) +{ + uint8_t status = SYS_PARAM_ERR; + uint32_t l_spiaddr = spiaddr; + + if ((IAP_PROGRAM_BY_SPIIDX_CMD == iap_cmd) || (IAP_VERIFY_BY_SPIIDX_CMD == iap_cmd)) + { + HAL_ASSERT(!(1u == spiaddr)); + } + + status = execute_ss_command(iap_cmd, + (uint8_t*)&l_spiaddr, + 4u, + NULL_BUFFER, + 0u, + spiaddr, + 0u); + + return status; +} + +/***************************************************************************//** + Internal functions. +*/ +/* +This function executes the SS command. If Mailbox input data is required by the +it will first load it from cmd_data into the Mailbox. If the service requires +the response data to be read from mailbox, it will do so and store it in p_response. +*/ +static uint8_t execute_ss_command +( + uint8_t cmd_opcode, + const uint8_t* cmd_data, + uint16_t cmd_data_size, + const uint8_t* p_response, + uint16_t response_size, + uint16_t mb_offset, + uint16_t response_offset +) +{ + /* Pointer used during Writing to Mailbox memory. */ + uint32_t status = 0u; + uint16_t idx = 0u; + uint16_t ss_command = 0u; + uint32_t* word_buf; + uint16_t timeout_count = SS_TIMEOUT_COUNT; + + /* making sure that the system controller is not executing any service i.e. + SS_USER_BUSY is gone 0 */ + + while (1u == HAL_get_32bit_reg_field(g_css_pf_base_addr, SS_USER_BUSY)) + { + --timeout_count; + + if (timeout_count == 0) + { + return SS_USER_BUSY_TIMEOUT; + } + } + + /* Form the SS command: bit 0to6 is the opcode, bit 7to15 is the Mailbox offset + For some services this field has another meaning + (e.g. for IAP bitstream auth. it means spi_idx) */ + ss_command = ((mb_offset << 7u) | (cmd_opcode & 0x7Fu)); + + /* Load the command register with the SS request command code*/ + HAL_set_32bit_reg(g_css_pf_base_addr, SS_CMD, ss_command); + + if (cmd_data_size > 0u) + { + HAL_ASSERT(!(NULL_BUFFER == cmd_data)); + HAL_ASSERT(!(cmd_data_size % 4u)); + + /* Load the MBX_WCNT register with number of words */ + HAL_set_32bit_reg( g_css_pf_base_addr, MBX_WCNT, (cmd_data_size/4u)); + + /* Load the MBX_WADDR register with offset of input data (write to Mailbox) + For all the services this offset remains either 0 or Not applicable + for the services in which no Mailbox write is required.*/ + HAL_set_32bit_reg( g_css_pf_base_addr, MBX_WADDR, (0x00u + mb_offset)); + + } + + if (response_size > 0u) + { + HAL_ASSERT(!(NULL_BUFFER == p_response)); + HAL_ASSERT(!(response_size % 4u)); + + /* + Load the MBX_RWCNT register with number of words to be read from Mailbox + */ + HAL_set_32bit_reg( g_css_pf_base_addr, MBX_RCNT, (response_size/4u)); + + /* + Load the MBX_RADRDESC register with offset address within the mailbox + format for that particular service. + It will be 0 for the services where there is no output data from G5CONTROL + is expected. + This function assumes that this value is pre-calculated by service specific + functions as this value is fixed for each service. + */ + HAL_set_32bit_reg( g_css_pf_base_addr, MBX_RADDR, (response_offset + mb_offset)); + } + + /*Set the request bit in SYS_SERV_REQ register to start the service*/ + HAL_set_32bit_reg_field(g_css_pf_base_addr, SS_REQ_REQ, 0x01u); + + if (cmd_data_size > 0u) + { + word_buf = (uint32_t*)cmd_data; + + /* Write the user data into mail box. */ + for (idx = 0u; idx < (cmd_data_size/4u); idx++) + { + HAL_set_32bit_reg( g_css_pf_base_addr, MBX_WDATA, word_buf[idx]); + } + } + + timeout_count = SS_TIMEOUT_COUNT; + if (response_size > 0u) + { + word_buf = (uint32_t*)p_response; + + for (idx = 0u; idx < (response_size/4u); idx++) + { + while (0u == HAL_get_32bit_reg_field(g_css_pf_base_addr, + SS_USER_RDVLD)) + { + --timeout_count; + + if (timeout_count == 0) + { + return SS_USER_RDVLD_TIMEOUT; + } + } + word_buf[idx] = HAL_get_32bit_reg(g_css_pf_base_addr, MBX_RDATA); + } + } + + timeout_count = SS_TIMEOUT_COUNT; + /* make sure that service is complete i.e. SS_USER_BUSY is gone 0 */ + while (1u == HAL_get_32bit_reg_field(g_css_pf_base_addr, SS_USER_BUSY)) + { + --timeout_count; + + if (timeout_count == 0) + { + return SS_USER_RDVLD_TIMEOUT; + } + } + + /* Read the status returned by System Controller */ + status = HAL_get_32bit_reg(g_css_pf_base_addr, SS_STAT); + + return (uint8_t)status; +} + +#ifdef __cplusplus +} +#endif diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreSysServices_PF/core_sysservices_pf.h b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreSysServices_PF/core_sysservices_pf.h new file mode 100644 index 0000000..aa1c82b --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreSysServices_PF/core_sysservices_pf.h @@ -0,0 +1,1222 @@ +/******************************************************************************* + * Copyright 2019-2021 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * This file contains the application programming interface for the + * CoreSysServices_PF bare metal driver. + */ +/*=========================================================================*//** + @mainpage CoreSysServices_PF Bare Metal Driver. + + @section intro_sec Introduction + The PolarFire System Services (PF_SYSTEM_SERVICES) SgCore enables executing + system services on the PolarFire and PolarFire SoC device. The System services + are System Controller actions initiated via the System Controller’s System + Service Interface (SSI). The PolarFire System Services SgCore provides a + method to initiate these system services. The PF_SYSTEM_SERVICES interacts + with the system controller on SSI and Mailbox interface to initiate system + services, exchange data required for that services and to know the successful + completion or error status. + + The PF_SYSTEM_SERVICES provides an APB interface for controlling the registers + functions for controlling the PF_SYSTEM_SERVICES as part of a bare metal system + implemented within it. This software driver provides a set of where no + part of an operating system but the implementation of the adaptation layer + operating system is available. This driver can be adapted for use as + between this driver and the operating system's driver model is outside the + scope of this driver. + + Features + The CoreSysServices_PF driver provides the following features: + - Executing device and design information services. + - Executing design services. + - Executing data security services + - Executing Fabric services. + + The CoreSysServices_PF driver is provided as C source code. + + @section Driver Configuration + Your application software should configure the CoreSysServices_PF driver, through + call to the SYS_init() function. Only one instance of PF_SYSTEM_SERVICES SgCore is + supported. No additional configuration files are required to use the driver. + + @section theory_op Theory of Operation + The CoreSysServices_PF driver provides access to the PolarFire system services. + These system services are grouped into the following categories: + + Device & Design Information Service + - Serial Number Service + - USERCODE Service + - Design Info Service + - Device Certificate Services + - Read Digests + - Query Security + - Read Debug Info + - Read eNVM param + + Design services + - Bitstream authentication service + - IAP bitstream authentication service + + Data Security services + - Digital Signature Service + - Secure NVM (SNVM) Functions + - PUF Emulation Service + - Nonce Service + + Fabric services + - Digest Check Service + - In Application programming(IAP)/ Auto-Update service + + Initialization and Configuration + The CoreSysServices_PF driver is initialized through a call to the SYS_init() + function. The SYS_init() function must be called before any other + CoreSysServices_PF driver functions is called. + + Device and design information services + The CoreSysServices_PF driver can be used to read information about the device + and the design using the following functions: + - SYS_get_serial_number() + - SYS_get_user_code() + - SYS_get_design_info() + - SYS_get_device_certificate() + - SYS_read_digest() + - SYS_query_security() + - SYS_read_debug_info() + + Design Authentication services + The CoreSysServices_PF driver can be used to execute design services using the + following functions: + - SYS_bitstream_authenticate_service() + - SYS_IAP_image_authenticate_service() + + Data security services + The CoreSysServices_PF driver can be used to execute data security services + using the following functions: + - SYS_digital_signature_service() + - SYS_secure_nvm_write() + - SYS_secure_nvm_read() + - SYS_puf_emulation_service () + - SYS_nonce_service () + + Executing Fabric services + The CoreSysServices_PF driver can be used to execute fabric services using the + following functions: + - SYS_digest_check_service() + - SYS_iap_service() + + All the service execution functions return the 8 bit status returned by + system controller on executing the given service. A '0' value indicates + successful execution of that service. A non-zero value indicates error. + The error codes for each service are different. Please see individual function + description to know the exact meanings of the error codes for each service. + + The function descriptions in this file will mainly focus on details required + by the user to use the APIs provided by this driver to execute the services. + To know the complete details of the system services, please refer to the + PolarFire® FPGA and PolarFire SoC FPGA System Services document. Link below: + https://onlinedocs.microchip.com/pr/GUID-1409CF11-8EF9-4C24-A94E-70979A688632-en-US-3/index.html + + *//*=========================================================================*/ +#ifndef __CORE_SYSSERV_PF_H +#define __CORE_SYSSERV_PF_H 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/***************************************************************************//** + * Service execution success and error status codes: + * The status codes below are the return values from the system service functions. + * For any service, a return value '0' indicates that the service was executed + * successfully. A non-zero return value indicates that the service was not + * executed successfully. For all the services, the return value represents the + * status code returned by the system controller for the respective service, + * except the values SYS_PARAM_ERR, SS_USER_BUSY_TIMEOUT and SS_USER_RDVLD_TIMEOUT. + * These three values indicate the error conditions detected by this driver and + * they do not overlap with the status code returned by the system controller for + * any of the system service. + */ +/* + * SYS_SUCCESS + * System service executed successfully. + * + * SYS_PARAM_ERR + * System service cannot be executed as one or more parameters are not as + * expected by this driver. No read/write access will be performed with the + * IP. + * + * SS_USER_BUSY_TIMEOUT + * The System service request was initiated and the driver timed-out while + * waiting for the system service to complete. The System Service + * completion is indicated by de-assertion of the SS_USER_BUSY bit by the + * IP. + * + * SS_USER_RDVLD_TIMEOUT + * The System service request was initiated and the driver timed-out while + * waiting for SS_USER_RDVLD bit, which indicates availability of data to + * be read from the mailbox, to become active. +*/ +#define SYS_SUCCESS 0u +#define SYS_PARAM_ERR 0xFFu +#define SS_USER_BUSY_TIMEOUT 0xFAu +#define SS_USER_RDVLD_TIMEOUT 0xFBu + +/* + * SS_TIMEOUT_COUNT + * The SS_TIMEOUT_COUNT value will be used by the driver as a timeout count + * while waiting for either the SS_USER_BUSY or SS_USER_RDVLD. This empirical + * value is sufficiently large so that the operations will not falsely + * timeout in the normal circumstance. It is provided as a way to provide + * more debug information to the application in case there are some + * unforeseen issues. You may change this value for your need based on your + * system design. + */ +#define SS_TIMEOUT_COUNT 40000u +/* + * SYS_DCF_DEVICE_MISMATCH + * Public key or FSN do not match device + * + * + * SYS_DCF_INVALID_SIGNATURE + * Certificate signature is invalid + * + * SYS_DCF_SYSTEM_ERROR + * PUF or storage failure + */ +#define SYS_DCF_DEVICE_MISMATCH 1u +#define SYS_DCF_INVALID_SIGNATURE 2u +#define SYS_DCF_SYSTEM_ERROR 3u + +/* + * SYS_NONCE_PUK_FETCH_ERROR + * Error fetching PUK + * + * SYS_NONCE_SEED_GEN_ERROR + * Error generating seed + */ +#define SYS_NONCE_PUK_FETCH_ERROR 1u +#define SYS_NONCE_SEED_GEN_ERROR 2u + +/* Secure NVM write error codes + * + * SNVM_WRITE_INVALID_SNVMADDR + * Illegal page address + * + * SNVM_WRITE_FAILURE + * PNVM program/verify failed + * + * SNVM_WRITE_SYSTEM_ERROR + * PUF or storage failure + * + * SNVM_WRITE_NOT_PERMITTED + * Write is not permitted + */ +#define SNVM_WRITE_INVALID_SNVMADDR 1u +#define SNVM_WRITE_FAILURE 2u +#define SNVM_WRITE_SYSTEM_ERROR 3u +#define SNVM_WRITE_NOT_PERMITTED 4u + +/* Secure NVM read error codes + * + * SNVM_READ_INVALID_SNVMADDR + * Illegal page address + * + * SNVM_READ_AUTHENTICATION_FAILURE + * Storage corrupt or incorrect USK + * + * SNVM_READ_SYSTEM_ERROR + * PUF or storage failure + * + */ +#define SNVM_READ_INVALID_SNVMADDR 1u +#define SNVM_READ_AUTHENTICATION_FAILURE 2u +#define SNVM_READ_SYSTEM_ERROR 3u + +/* Digital Signature Service error code + * + * DIGITAL_SIGNATURE_FEK_FAILURE_ERROR + * Error retrieving FEK + * + * DIGITAL_SIGNATURE_DRBG_ERROR + * Failed to generate nonce + * + * DIGITAL_SIGNATURE_ECDSA_ERROR + * ECDSA failed + */ +#define DIGITAL_SIGNATURE_FEK_FAILURE_ERROR 1u +#define DIGITAL_SIGNATURE_DRBG_ERROR 2u +#define DIGITAL_SIGNATURE_ECDSA_ERROR 3u + +/*Digest Check error code + * + * NOTE: when these error occur, the DIGEST tamper flag is triggered + * + * DIGEST_CHECK_FABRICERR + * Fabric digest check error + * + * DIGEST_CHECK_CCERR + * UFS Fabric Configuration (CC) segment digest check error + * + * DIGEST_CHECK_SNVMERR + * ROM digest in SNVM segment digest check error + * + * DIGEST_CHECK_ULERR + * UFS UL segment digest check error + * + * DIGEST_CHECK_UK0ERR + * UKDIGEST0 in User Key segment digest check error + * + * DIGEST_CHECK_UK1ERR + * UKDIGEST1 in User Key segment digest check error + * + * DIGEST_CHECK_UK2ERR + * UKDIGEST2 in User Key segment (UPK1) digest check error + * + * DIGEST_CHECK_UK3ERR + * UKDIGEST3 in User Key segment (UK1) digest check error + * + * DIGEST_CHECK_UK4ERR + * UKDIGEST4 in User Key segment (DPK) digest check error + * + * DIGEST_CHECK_UK5ERR + * UKDIGEST5 in User Key segment (UPK2) digest check error + * + * DIGEST_CHECK_UK6ERR + * UKDIGEST6 in User Key segment (UK2) digest check error + * + * DIGEST_CHECK_UPERR + * UFS Permanent Lock (UPERM) segment digest check error + * + * DIGEST_CHECK_SYSERR + * M3 ROM, Factory and Factory Key Segments digest check error + * + */ +#define DIGEST_CHECK_FABRICERR 0x00u +#define DIGEST_CHECK_CCERR 0x01u +#define DIGEST_CHECK_SNVMERR 0x02u +#define DIGEST_CHECK_ULERR 0x03u +#define DIGEST_CHECK_UK0ERR 0x04u +#define DIGEST_CHECK_UK1ERR 0x05u +#define DIGEST_CHECK_UK2ERR 0x06u +#define DIGEST_CHECK_UK3ERR 0x07u +#define DIGEST_CHECK_UK4ERR 0x08u +#define DIGEST_CHECK_UK5ERR 0x09u +#define DIGEST_CHECK_UK6ERR 0x10u +#define DIGEST_CHECK_UPERR 0x11u +#define DIGEST_CHECK_SYSERR 0x12u + +/* bitstream authentication and IAP bitstream authentication Return status + * + * BSTREAM_AUTH_CHAINING_MISMATCH_ERR + * Validator or hash chaining mismatch. Incorrectly constructed bitstream or + * wrong key used. + * + * BSTREAM_AUTH_UNEXPECTED_DATA_ERR + * Unexpected data received. + * Additional data received after end of EOB component + * + * BSTREAM_AUTH_INVALID_ENCRY_KEY_ERR + * Invalid/corrupt encryption key. + * The requested key mode is disabled or the key could not be read/reconstructed + * + * BSTREAM_AUTH_INVALID_HEADER_ERR + * Invalid component header + * + * BSTREAM_AUTH_BACK_LEVEL_NOT_SATISFIED_ERR + * Back level not satisfied + * + * BSTREAM_AUTH_ILLEGAL_BITSTREAM_MODE_ERR + * Illegal bitstream mode. + * Requested bitstream mode is disabled by user security + * + * BSTREAM_AUTH_DNS_BINDING_MISMATCH_ERR + * DSN binding mismatch + * + * BSTREAM_AUTH_ILLEGAL_COMPONENT_SEQUENCE_ERR + * Illegal component sequence + * + * BSTREAM_AUTH_INSUFF_DEVICE_CAPAB_ERR + * Insufficient device capabilities + * + * BSTREAM_AUTH_INCORRECT_DEVICEID_ERR + * Incorrect DEVICEID + * + * BSTREAM_AUTH_PROTOCOL_VERSION_ERR + * Unsupported bitstream protocol version (regeneration required) + * + * BSTREAM_AUTH_VERIFY_ERR + * Verify not permitted on this bitstream + * + * BSTREAM_AUTH_INVALID_DEV_CERT_ERR + * Invalid Device Certificate. + * Device SCAC is invalid or not present + * + * BSTREAM_AUTH_INVALID_DIB_ERR + * Invalid DIB + * + * BSTREAM_AUTH_SPI_NOT_MASTER_ERR + * Device not in SPI Master Mode. + * Error may occur only when bitstream is executed through IAP mode + * + * BSTREAM_AUTH_AUTOIAP_NO_VALID_IMAGE_ERR + * No valid images found. + * Error may occur when bitstream is executed through Auto Update mode. + * Occurs when No valid image pointers are found. + * + * BSTREAM_AUTH_INDEXIAP_NO_VALID_IMAGE_ERR + * No valid images found. + * Error may occur when bitstream is executed through IAP mode via Index Mode. + * Occurs when No valid image pointers are found. + * + * BSTREAM_AUTH_NEWER_DESIGN_VERSION_ERR + * Programmed design version is newer than AutoUpdate image found. + * Error may occur when bitstream is executed through Auto Update mode + * + * BSTREAM_AUTH_INVALID_IMAGE_ERR + * Selected image was invalid and no recovery was performed due to valid design + * in device. + * Error may occur only when bitstream is executed through Auto Update or IAP mode + * (This error is here for completeness but only can be observed by running the + * READ_DEBUG_INFO instruction and looking at IAP Error code field) + * + * BSTREAM_AUTH_IMAGE_PROGRAM_FAILED_ERR + * Selected and Recovery image failed to program. + * Error may occur only when bitstream is executed through Auto Update or + * IAP mode + * (This error is here for completeness but only can be observed by running the + * READ_DEBUG_INFO instruction and looking at IAP Error code field) + * + * BSTREAM_AUTH_ABORT_ERR + * Abort. + * Non-bitstream instruction executed during bitstream loading. + * + * BSTREAM_AUTH_NVMVERIFY_ERR + * Fabric/UFS verification failed (min or weak limit) + * + * BSTREAM_AUTH_PROTECTED_ERR + * Device security prevented modification of non-volatile memory + * + * BSTREAM_AUTH_NOTENA + * Programming mode not enabled + * + * BSTREAM_AUTH_PNVMVERIFY + * pNVM verify operation failed + * + * BSTREAM_AUTH_SYSTEM + * System hardware error (PUF or DRBG) + * + * BSTREAM_AUTH_BADCOMPONENT + * An internal error was detected in a component payload + * + * BSTREAM_AUTH_HVPROGERR + * HV programming subsystem failure (pump failure) + * + * BSTREAM_AUTH_HVSTATE + * HV programming subsystem in unexpected state (internal error) + * + */ +#define BSTREAM_AUTH_CHAINING_MISMATCH_ERR 1 +#define BSTREAM_AUTH_UNEXPECTED_DATA_ERR 2 +#define BSTREAM_AUTH_INVALID_ENCRY_KEY_ERR 3 +#define BSTREAM_AUTH_INVALID_HEADER_ERR 4 +#define BSTREAM_AUTH_BACK_LEVEL_NOT_SATISFIED_ERR 5 +#define BSTREAM_AUTH_ILLEGAL_BITSTREAM_MODE_ERR 6 +#define BSTREAM_AUTH_DNS_BINDING_MISMATCH_ERR 7 +#define BSTREAM_AUTH_ILLEGAL_COMPONENT_SEQUENCE_ERR 8 +#define BSTREAM_AUTH_INSUFF_DEVICE_CAPAB_ERR 9 +#define BSTREAM_AUTH_INCORRECT_DEVICEID_ERR 10 +#define BSTREAM_AUTH_PROTOCOL_VERSION_ERR 11 +#define BSTREAM_AUTH_VERIFY_ERR 12 +#define BSTREAM_AUTH_INVALID_DEV_CERT_ERR 13 +#define BSTREAM_AUTH_INVALID_DIB_ERR 14 +#define BSTREAM_AUTH_SPI_NOT_MASTER_ERR 21 +#define BSTREAM_AUTH_AUTOIAP_NO_VALID_IMAGE_ERR 22 +#define BSTREAM_AUTH_INDEXIAP_NO_VALID_IMAGE_ERR 23 +#define BSTREAM_AUTH_NEWER_DESIGN_VERSION_ERR 24 +/* 25 Reserved */ +#define BSTREAM_AUTH_INVALID_IMAGE_ERR 26 +#define BSTREAM_AUTH_IMAGE_PROGRAM_FAILED_ERR 27 +#define BSTREAM_AUTH_ABORT_ERR 127 +#define BSTREAM_AUTH_NVMVERIFY_ERR 128 +#define BSTREAM_AUTH_PROTECTED_ERR 129 +#define BSTREAM_AUTH_NOTENA 130 +#define BSTREAM_AUTH_PNVMVERIFY 131 +#define BSTREAM_AUTH_SYSTEM 132 +#define BSTREAM_AUTH_BADCOMPONENT 133 +#define BSTREAM_AUTH_HVPROGERR 134 +#define BSTREAM_AUTH_HVSTATE 135 + +/***************************************************************************//** + * Mailbox ECC status + * Provides ECC status when the mailbox is read. The values are as follows: + * 00: No ECC errors detected, data is correct. + * 01: Exactly one bit error occurred and has been corrected. + * 10: Exactly two bits error occurred and no correction performed. + * 11: Reserved. + */ +#define SYS_MBOX_ECC_NO_ERROR_MASK 0x00u +#define SYS_MBOX_ONEBIT_ERROR_CORRECTED_MASK 0x40u +#define SYS_MBOX_TWOBIT_ERROR_MASK 0xC0u + +/***************************************************************************//** + * Service request command opcodes: +*/ +#define SERIAL_NUMBER_REQUEST_CMD 0x00u +#define USERCODE_REQUEST_CMD 0x01u +#define DESIGN_INFO_REQUEST_CMD 0x02u +#define DEVICE_CERTIFICATE_REQUEST_CMD 0x03u +#define READ_DIGEST_REQUEST_CMD 0x04u +#define QUERY_SECURITY_REQUEST_CMD 0x05u +#define READ_DEBUG_INFO_REQUEST_CMD 0x06u +#define READ_ENVM_PARAM_REQUEST_CMD 0x07u +#define SNVM_NON_AUTHEN_TEXT_REQUEST_CMD 0x10u +#define SNVM_AUTHEN_TEXT_REQUEST_CMD 0x11u +#define SNVM_AUTHEN_CIPHERTEXT_REQUEST_CMD 0x12u +#define SNVM_READ_REQUEST_CMD 0x18u +#define DIGITAL_SIGNATURE_RAW_FORMAT_REQUEST_CMD 0x19u +#define PUF_EMULATION_SERVICE_REQUEST_CMD 0x20u +#define NONCE_SERVICE_REQUEST_CMD 0x21u +#define DIGITAL_SIGNATURE_DER_FORMAT_REQUEST_CMD 0x1Au + +#define BITSTREAM_AUTHENTICATE_CMD 0x23u +#define IAP_BITSTREAM_AUTHENTICATE_CMD 0x22u + +#define DIGEST_CHECK_CMD 0x47u + +#define IAP_PROGRAM_BY_SPIIDX_CMD 0x42u +#define IAP_VERIFY_BY_SPIIDX_CMD 0x44u +#define IAP_PROGRAM_BY_SPIADDR_CMD 0x43u +#define IAP_VERIFY_BY_SPIADDR_CMD 0x45u +#define IAP_AUTOUPDATE_CMD 0x46u + +/***************************************************************************//** + * Service request Mailbox return data length + */ +#define SERIAL_NUMBER_RESP_LEN 16u +#define USERCODE_RESP_LEN 4u +#define DESIGN_INFO_RESP_LEN 36u +#define DEVICE_CERTIFICATE_RESP_LEN 1024u +#define READ_DIGEST_RESP_LEN 416u +#define QUERY_SECURITY_RESP_LEN 9u +#define READ_DEBUG_INFO_RESP_LEN 76u +#define READ_ENVM_PARAM_RESP_LEN 256u +#define NONCE_SERVICE_RESP_LEN 32u + +#define PUF_EMULATION_SERVICE_CMD_LEN 20u +#define PUF_EMULATION_SERVICE_RESP_LEN 32u + +#define DIGITAL_SIGNATURE_HASH_LEN 48u +#define DIGITAL_SIGNATURE_RAW_FORMAT_RESP_SIZE 96u +#define DIGITAL_SIGNATURE_DER_FORMAT_RESP_SIZE 104u + +#define USER_SECRET_KEY_LEN 12u + +/* Same driver can be used on PolarFire SoC platform and the response length + * is different for PolarFire SoC. Constants defined below are used only when the + * PF System services driver is used with PolarFire SoC Platform. + */ +#define READ_DIGEST_MPFS_RESP_LEN 576u +#define QUERY_SECURITY_MPFS_RESP_LEN 33u + +/* SNVM Input data length from sNVM write. */ + +/* SNVMADDR + RESERVED + PT + USK */ +#define NON_AUTHENTICATED_TEXT_DATA_LEN 256u + +/* SNVMADDR + RESERVED + PT */ +#define AUTHENTICATED_TEXT_DATA_LEN 252u + +/* Digest Check Input options + * + * DIGEST_CHECK_FABRIC + * Carry out digest check on Fabric + * + * DIGEST_CHECK_CC + * Carry out digest check on UFS Fabric Configuration (CC) segment + * + * DIGEST_CHECK_SNVM + * Carry out digest check on ROM digest in SNVM segment + * + * DIGEST_CHECK_UL + * Carry out digest check on UFS UL segment + * + * DIGEST_CHECK_UKDIGEST0 + * Carry out digest check on UKDIGEST0 in User Key segment + * + * DIGEST_CHECK_UKDIGEST1 + * Carry out digest check on UKDIGEST1 in User Key segment + * + * DIGEST_CHECK_UKDIGEST2 + * Carry out digest check on UKDIGEST2 in User Key segment (UPK1) + * + * DIGEST_CHECK_UKDIGEST3 + * Carry out digest check on UKDIGEST3 in User Key segment (UK1) + * + * DIGEST_CHECK_UKDIGEST4 + * Carry out digest check on UKDIGEST4 in User Key segment (DPK) + * + * DIGEST_CHECK_UKDIGEST5 + * Carry out digest check on UKDIGEST5 in User Key segment (UPK2) + * + * DIGEST_CHECK_UKDIGEST6 + * Carry out digest check on UKDIGEST6 in User Key segment (UK2) + * + * DIGEST_CHECK_UPERM + * Carry out digest check on UFS Permanent lock (UPERM) segment + * + * DIGEST_CHECK_SYS + * Carry out digest check on Factory and Factory Key Segments. + * + */ +#define DIGEST_CHECK_FABRIC (0x01<<0x00u) /*Fabric digest*/ +#define DIGEST_CHECK_CC (0x01<<0x01u) /*UFS Fabric Configuration (CC) segment*/ +#define DIGEST_CHECK_SNVM (0x01<<0x02u) /*ROM digest in SNVM segment*/ +#define DIGEST_CHECK_UL (0x01<<0x03u) /*UFS UL segment*/ +#define DIGEST_CHECK_UKDIGEST0 (0x01<<0x04u) /*UKDIGEST0 in User Key segment*/ +#define DIGEST_CHECK_UKDIGEST1 (0x01<<0x05u) /*UKDIGEST1 in User Key segment*/ +#define DIGEST_CHECK_UKDIGEST2 (0x01<<0x06u) /*UKDIGEST2 in User Key segment (UPK1)*/ +#define DIGEST_CHECK_UKDIGEST3 (0x01<<0x07u) /*UKDIGEST3 in User Key segment (UK1)*/ +#define DIGEST_CHECK_UKDIGEST4 (0x01<<0x08u) /*UKDIGEST4 in User Key segment (DPK)*/ +#define DIGEST_CHECK_UKDIGEST5 (0x01<<0x09u) /*UKDIGEST5 in User Key segment (UPK2)*/ +#define DIGEST_CHECK_UKDIGEST6 (0x01<<0x0au) /*UKDIGEST6 in User Key segment (UK2)*/ +#define DIGEST_CHECK_UPERM (0x01<<0x0bu) /*UFS Permanent lock (UPERM) segment*/ +#define DIGEST_CHECK_SYS (0x01<<0x0cu) /*Factory and Factory Key Segments.*/ + +/***************************************************************************//** + * The function SYS_init() is used to initialize the internal data structures of + * this driver. Currently this function is empty. + * + * @param base_addr The base_addr parameter specifies the base address of the + * PF_System_services core. + * + * @return This function does not return a value. + */ +void +SYS_init +( + uint32_t base_addr +); + +/***************************************************************************//** + * The function SYS_get_serial_number() is used to execute "serial number" system + * service. + * + * @param p_serial_number The p_serial_number parameter is a pointer to a buffer + * in which the data returned by system controller will + * be copied. + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return This function returns the status code returned by the + * system controller for this service. A '0' status code + * means that the service was executed successfully. + */ +uint8_t +SYS_get_serial_number +( + const uint8_t * p_serial_number, + uint16_t mb_offset +); + +/***************************************************************************//** + * The function SYS_get_user_code() is used to execute "USERCODE" system + * service. + * @param p_user_code The p_user_code parameter is a pointer to a buffer + * in which the data returned by system controller will be + * copied. + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return This function returns the status code returned by the + * system controller for this service. A '0' status code + * means that the service was executed successfully. + */ +uint8_t +SYS_get_user_code +( + const uint8_t * p_user_code, + uint16_t mb_offset +); + +/***************************************************************************//** + * The function SYS_get_design_info() is used to execute "Get Design Info" system + * service. + * + * @param p_design_info The p_design_info parameter is a pointer to a buffer + * in which the data returned by system controller will be + * copied. Total size of debug information is 36 bytes. + * The data from the system controller includes the 256-bit + * user-defined design ID, 16-bit design version and 16-bit + * design back level. + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return This function returns the status code returned by the + * system controller for this service. A '0' status code + * means that the service was executed successfully. + */ +uint8_t +SYS_get_design_info +( + const uint8_t * p_design_info, + uint16_t mb_offset +); + +/***************************************************************************//** + * The function SYS_get_device_certificate() is used to execute "Get Device + * Certificate" system service. + * + * @param p_device_certificate The p_device_certificate parameter is a pointer + * to a buffer in which the data returned by the + * system controller will be copied. + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return This function returns the status code returned by the + * system controller for this service. A '0' status code means that + * the service was executed successfully. + * + */ +uint8_t +SYS_get_device_certificate +( + const uint8_t * p_device_certificate, + uint16_t mb_offset +); + +/***************************************************************************//** + * The function SYS_read_digest() is used to execute "Read Digest" system service. + * + * @param p_digest The p_digest parameter is a pointer to a buffer + * in which the data returned by system controller will be + * copied. + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return This function returns the status code returned by the + * system controller for this service. A '0' status code + * means that the service was executed successfully. + */ +uint8_t SYS_read_digest +( + const uint8_t * p_digest, + uint16_t mb_offset +); + +/***************************************************************************//** + * The function SYS_query_security() is used to execute "Query Security" system + * service. + * + * @param p_security_locks The p_security_locks parameter is a pointer to a buffer + * in which the data returned by system controller will + * be copied. + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return This function returns the status code returned by the + * system controller for this service. A '0' status code means that + * the service was executed successfully. + */ +uint8_t SYS_query_security +( + uint8_t * p_security_locks, + uint16_t mb_offset +); + +/***************************************************************************//** + * The function SYS_read_debug_info() is used to execute "Read Debug info" system + * service. + * + * @param p_debug_info The p_debug_info parameter is a pointer to a buffer + * in which the data returned by system controller will be + * copied. + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return This function returns the status code returned by the + * system controller for this service. A '0' status code + * means that the service was executed successfully. + */ +uint8_t SYS_read_debug_info +( + const uint8_t * p_debug_info, + uint16_t mb_offset +); + +#ifdef CORESYSSERVICES_PFSOC +/***************************************************************************//** + * The function SYS_read_envm_param() is used to retrieve all parameters needed + * for eNVM operation and programming. + * + * NOTE: This service is available only on PolarFire SoC Platform. + * This service is not yet supported by PF_SYSTEM_SERVICES 3.0.100. + * + * @param p_envm_param The p_envm_param parameter is a pointer to a buffer + * in which the data returned by system controller will be copied. + * This buffer will store all the eNVM parameters. + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return The SYS_read_envm_param service will return zero if the + * service executed successfully otherwise it will return + * one indicating error. + */ +uint8_t SYS_read_envm_parameter +( + uint8_t * p_envm_param, + uint16_t mb_offset +); +#endif +/***************************************************************************//** + * The function SYS_puf_emulation_service() is used to authenticating a device. + * + * The SYS_puf_emulation_service() function accept a challenge comprising a + * 8-bit optype and 128-bit challenge and return a 256-bit response unique to + * the given challenge and the device. + * + * @param p_challenge The p_challenge parameter specifies the 128-bit challenge + * to be used to generate the unique 256-bits unique + * response. + * + * @param op_type The op_type parameter specifies the operational parameter + * to be used to generate the unique 256-bits unique + * response. + * + * @param p_response The p_response parameter is a pointer to a buffer in + * which the data returned i.e. response by system controller will + * be copied. + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return The SYS_puf_emulation_service function will return zero + * if the service executed successfully otherwise it will + * return one indicating error. + */ +uint8_t SYS_puf_emulation_service +( + const uint8_t * p_challenge, + uint8_t op_type, + uint8_t* p_response, + uint16_t mb_offset +); + +/***************************************************************************//** + * The SYS_digital_signature_service() function is used to generate P-384 ECDSA + * signature based on SHA384 hash value. + * + * @param p_hash The p_hash parameter is a pointer to the buffer which + * contain the 48 bytes SHA384 Hash value(input value). + * + * @param format The format parameter specifies the output format of + * generated SIGNATURE field. The different types of output + * signature formats are as follow: + * - DIGITAL_SIGNATURE_RAW_FORMAT + * - DIGITAL_SIGNATURE_DER_FORMAT + * + * @param p_response The p_response parameter is a pointer to a buffer which + * contain the generated ECDSA signature. The field may be + * 96 bytes or 104 bytes depending upon the output format. + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return The SYS_digital_signature_service function will return + * zero if the service executed successfully otherwise + * non-zero values indicating error. + */ +uint8_t SYS_digital_signature_service +( + const uint8_t* p_hash, + uint8_t format, + uint8_t* p_response, + uint16_t mb_offset +); + +/***************************************************************************//** + * The SYS_secure_nvm_write() function is used to provide write access/write the + * data in the sNVM region. Data can be stored in the following format: + * Non-authenticated plaintext, + * Authenticated plaintext + * Authenticated ciphertext + * + * Note: If you are executing this function with Authenticated plaintext + * or Authenticated ciphertext on a device whose sNVM was never previously + * written to, then the service may fail. For it to work, you must first write + * Authenticated data to the sNVM using Libero along with USK client and + * custom security. This flow generates the SMK. Refer UG0753 PolarFire FPGA + * security User Guide for further details. + + * @param format The format parameter specifies the format used to write + * data in sNVM region. The different type of text formats + * are as follow: + * - NON_AUTHENTICATED_PLAINTEXT_FORMAT + * - AUTHENTICATED_PLAINTEXT_FORMAT + * - AUTHENTICATED_CIPHERTEXT_FORMAT + * + * @param snvm_module The snvm_module parameter specifies the the sNVM module + * in which the data need to be written. + * + * @param p_data The p_data parameter is a pointer to a buffer which + * contains the data to be stored in sNVM region. The data + * length to be written is if fixed depending on the format + * parameter. If NON_AUTHENTICATED_PLAINTEXT_FORMAT is + * selected then you can write 252 bytes in the sNVM module. + * For other two formats the data length is 236 bytes. + * + * @param p_user_key The p_user_key parameter is a pointer to a buffer which + * contain the 96-bit key USK (user secret key). This user + * secret key will enhance the security when authentication + * is used.(i.e. When Authenticated plaintext and + * Authenticated ciphertext format is selected). + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return The SYS_secure_nvm_write function will return + * zero if the service executed successfully otherwise + * non-zero values indicating error. + */ +uint8_t SYS_secure_nvm_write +( + uint8_t format, + uint8_t snvm_module, + const uint8_t* p_data, + const uint8_t* p_user_key, + uint16_t mb_offset +); + +/***************************************************************************//** + * The SYS_secure_nvm_read() function is used to read data present in sNVM region. + * User should provide USK key, if the data was programmed using authentication. + * If the data was written in the sNVM using the authenticated plaintext or the + * authenticated ciphertext service option then this service will return the + * valid data only when authentication is successful. Please also refer the + * SYS_secure_nvm_write() function for more details. If the data was written in + * the sNVM using the authenticated plaintext or the authenticated ciphertext + * service option then this service will return the valid data only when + * authentication is successful. Please also refer the SYS_secure_nvm_write() + * function and its parameter description for more details. + * + * @param snvm_module The snvm_module parameter specifies the sNVM module + * from which the data need to be read. + * + * @param p_user_key The p_user_key parameter is a pointer to a buffer which + * contain the 96-bit key USK (user secret key). User should + * provide same secret key which is previously used for + * authentication while writing data in sNVM region. + * + * @param p_admin The p_admin parameter is a pointer to the buffer where + * the output page admin data will be stored. The page admin + * data is 4 bytes long. + * + * @param p_data The p_data parameter is a pointer to a buffer which + * contains the data read from sNVM region. User should + * provide the buffer large enough to store the read data. + * + * @param data_len The data_len parameter specifies the number of bytes to be + * read from sNVM. + * The application should know whether the data written in the + * chose sNVM module was previously stored using Authentication + * or not. + * The data_len should be 236 bytes, for authenticated data. + * For not authenticated data the data_len should be 252 bytes. + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return The SYS_secure_nvm_read function will return + * zero if the service executed successfully otherwise + * non-zero values indicating error. + */ +uint8_t SYS_secure_nvm_read +( + uint8_t snvm_module, + const uint8_t* p_user_key, + uint8_t* p_admin, + uint8_t* p_data, + uint16_t data_len, + uint16_t mb_offset +); + +/***************************************************************************//** + * The function SYS_nonce_service() is used to issue "Nonce Service" system + * service to the system controller. + * + * @param p_nonce The p_nonce parameter is a pointer to a buffer + * in which the data returned by system controller will be copied. + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return This function returns the status code returned by the + * system controller for this service. A '0' status code means + * that the service was executed successfully and a non-zero + * value indicates error. Please refer to the document link + * provided in the theory of operation section to know more + * about the service and service response. + */ +uint8_t SYS_nonce_service +( + const uint8_t * p_nonce, + uint16_t mb_offset +); + +/***************************************************************************//** + * The SYS_bitstream_authenticate_service() function is used to authenticate + * the Bitstream which is located in SPI through a system service routine. Prior + * to using the IAP service, it may be required to first validate the new + * bitstream before committing the device to reprogramming, thus avoiding the + * need to invoke recovery procedures if the bitstream is invalid. + * + * This service is applicable to bitstreams stored in SPI Flash memory only. + * + * @param spi_flash_address + * The spi_flash_address parameter specifies the address within + * SPI Flash memory where the bit-stream is stored. + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return The SYS_bitstream_authenticate_service function will return + * zero if the service executed successfully the non-zero + * response from system controller indicates error. Please + * refer to the document link provided in the theory of + * operation section to know more about the service and service + * response. + */ +uint8_t SYS_bitstream_authenticate_service +( + uint32_t spi_flash_address, + uint16_t mb_offset +); + +/***************************************************************************//** + * The SYS_IAP_image_authenticate_service() function is used to authenticate + * the IAP image which is located in SPI through a system service routine. The + * service checks the image descriptor and the referenced bitstream and optional + * initialization data. If the image is authenticated successfully, then the + * image is guaranteed to be valid when used by an IAP function. + * + * This service is applicable to bitstreams stored in SPI Flash memory only. + * + * @param spi_idx + * The spi_idx parameter specifies the index in the SPI directory to + * be used where the IAP bit-stream is stored. + * + * Note: To support recovery SPI_IDX=1 should be an empty slot and the recovery + * image should be located in SPI_IDX=0. Since SPI_IDX=1 should be an + * empty slot it shouldn’t be passed into the system service. + * + * @return The SYS_IAP_image_authenticate_service function will return + * zero if the service executed successfully the non-zero + * response from system controller indicates error. Please + * refer to the document link provided in the theory of + * operation section to know more about the service and service + * response. + */ +uint8_t SYS_IAP_image_authenticate_service +( + uint8_t spi_idx +); + +/***************************************************************************//** + * The SYS_digest_check_service() function is used to Recalculates and compares + * digests of selected non-volatile memories. If the fabric digest is to be + * checked, then the user design must follow all prerequisite steps for the + * FlashFreeze service before invoking this service. + * + * This service is applicable to bitstreams stored in SPI Flash memory only. + * + * @param options + * The options parameter specifies the digest check options which + * indicate the area on which the digest check should be performed. + * Below is the list of options. You can OR these options to indicate + * to perform digest check on multiple segments. + * + * Note: The options parameter will be of 2 bytes when used with PF + * device and 4 bytes when used with PolarFire SoC device. + * + * Options[i] Description + * 0x01 Fabric digest + * 0x02 Fabric Configuration (CC) segment + * 0x04 ROM digest in SNVM segment + * 0x08 UL segment + * 0x10 UKDIGEST0 in User Key segment + * 0x20 UKDIGEST1 in User Key segment + * 0x40 UKDIGEST2 in User Key segment (UPK1) + * 0x80 UKDIGEST3 in User Key segment (UK1) + * 0x100 UKDIGEST4 in User Key segment (DPK) + * 0x200 UKDIGEST5 in User Key segment (UPK2) + * 0x400 UKDIGEST6 in User Key segment (UK2) + * 0x800 UFS Permanent lock (UPERM) segment + * 0x1000 Factory and Factory Key Segments. + * 0x2000 UKDIGEST7 in User Key segment (HWM) (PFSoC) + * 0x4000 ENVMDIGEST (PFSoC only) + * 0x8000 UKDIGEST8 for MSS Boot Info (PFSoC only) + * 0x10000 SNVM_RW_ACCESS_MAP Digest (PFSoC only) + * 0x20000 SBIC revocation digest (PFSoC only) + * + * @param mb_offset The mb_offset parameter specifies the offset from + * the start of Mailbox where the data related to this service + * will be available. Note that all accesses to the mailbox + * are of word length(4 bytes). A Value '10' of this parameter + * would mean that the data access area for this service + * starts from 11th word (offset 10) in the Mailbox. + * + * @return The SYS_digest_check_service function will return + * zero if the service executed successfully the non-zero + * response from system controller indicates error. Pleaes + * refer to the document link provided in the theory of + * operation section to know more about the service and service + * response. + */ +uint8_t SYS_digest_check_service +( + uint32_t options, + uint16_t mb_offset +); + +/***************************************************************************//** + * The SYS_iap_service() function is used to IAP service. The IAP service allows t + * he user to reprogram the device without the need for an external master. The + * user design writes the bitstream to be programmed into a SPI Flash connected + * to the SPI port. When the service is invoked, the System Controller + * automatically reads the bitstream from the SPI flash and programs the device. + * The service allows the image to be executed in either VERIFY or PROGRAM modes. + * Another option for IAP is to perform the auto-update sequence. In this case + * the newest image of the first two images in the SPI directory is chosen to be + * programmed. + * + * @param iap_cmd + * The iap_cmd parameter specifies the specific IAP command which + * depends upon VERIFY or PROGRAM modes and the SPI address method. + * + * iap_cmd Description + * IAP_PROGRAM_BY_SPIIDX_CMD IAP program. + * IAP_VERIFY_BY_SPIIDX_CMD Fabric Configuration (CC) segment + * IAP_PROGRAM_BY_SPIADDR_CMD ROM digest in SNVM segment + * IAP_VERIFY_BY_SPIADDR_CMD UL segment + * IAP_AUTOUPDATE_CMD UKDIGEST0 in User Key segment + * + * @param spiaddr + * The spiaddr parameter specifies the either the either the index + * in the SPI directory or the SPI address in the SPI Flash memory. + * Below is the list of the possible meaning of spiaddr parameter + * in accordance with the iap_cmd parameter. + * + * iap_cmd spiaddr + * IAP_PROGRAM_BY_SPIIDX_CMD Index in the SPI directory. + * IAP_VERIFY_BY_SPIIDX_CMD Index in the SPI directory. + * IAP_PROGRAM_BY_SPIADDR_CMD SPI address in the SPI Flash memory + * IAP_VERIFY_BY_SPIADDR_CMD SPI address in the SPI Flash memory + * IAP_AUTOUPDATE_CMD spiaddr is ignored as No index/address + * required for this command. + * + * Note: For the IAP services with command IAP_PROGRAM_BY_SPIIDX_CMD and + * IAP_VERIFY_BY_SPIIDX_CMD To support recovery SPI_IDX=1 should be an + * empty slot and the recovery image should be located in SPI_IDX=0. + * Since SPI_IDX=1 should be an empty slot it shouldn’t be passed into + * the system service. + * + * @return The SYS_iap_service function will return zero if the service + * executed successfully and the non-zero response from system + * controller indicates error. Please refer to the document + * link provided in the theory of operation section to know + * more about the service and service response. + */ +uint8_t SYS_iap_service +( + uint8_t iap_cmd, + uint32_t spiaddr +); + +#ifdef __cplusplus +} +#endif + +#endif /* __CORE_SYSSERV_PF_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreSysServices_PF/coresysservicespf_regs.h b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreSysServices_PF/coresysservicespf_regs.h new file mode 100644 index 0000000..c978968 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreSysServices_PF/coresysservicespf_regs.h @@ -0,0 +1,147 @@ +/******************************************************************************* + * (c) Copyright 2019-2021 Microchip FPGA Embedded Systems Solutions. + * + * Register bit offsets and masks definitions for CoreSysServices_PF driver. + */ + +#ifndef __CORE_SYSSERV_PF_REGISTERS +#define __CORE_SYSSERV_PF_REGISTERS 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/*------------------------------------------------------------------------------ + * SYS_SERV_CMD (offset 0x04) register details + */ +#define SS_CMD_REG_OFFSET 0x04u + +#define SS_CMD_OFFSET 0x04 +#define SS_CMD_MASK 0x0000FFFFu +#define SS_CMD_SHIFT 0u + +/*------------------------------------------------------------------------------ + * SYS_SERV_STAT (offset 0x08) register details + */ +#define SS_STAT_REG_OFFSET 0x08u + +#define SS_STAT_OFFSET 0x08 +#define SS_STAT_MASK 0x0000FFFFu +#define SS_STAT_SHIFT 0u + +/*------------------------------------------------------------------------------ + * SYS_SERV_REQ (offset 0x0C) register details + */ +#define SS_REQ_REG_OFFSET 0x0Cu + + +#define SS_REQ_REQ_OFFSET 0x0Cu +#define SS_REQ_REQ_MASK 0x00000001UL +#define SS_REQ_REQ_SHIFT 0u + +#define SS_REQ_ABUSY_OFFSET 0x0Cu +#define SS_REQ_ABUSY_MASK 0x00000002UL +#define SS_REQ_ABUSY_SHIFT 1u + +#define SS_REQ_NABUSY_OFFSET 0x0Cu +#define SS_REQ_NABUSY_MASK 0x00000004UL +#define SS_REQ_NABUSY_SHIFT 2u + +#define SS_REQ_SSBUSY_OFFSET 0x0Cu +#define SS_REQ_SSBUSY_MASK 0x00000008UL +#define SS_REQ_SSBUSY_SHIFT 3u + +#define SS_REQ_AREQ_OFFSET 0x0Cu +#define SS_REQ_AREQ_MASK 0x00000010UL +#define SS_REQ_AREQ_SHIFT 4u + +#define SS_REQ_NAREQ_OFFSET 0x0Cu +#define SS_REQ_NAREQ_MASK 0x00000020UL +#define SS_REQ_NAREQ_SHIFT 5u +/*------------------------------------------------------------------------------ + * MBX_ECCSTATUS (offset 0x10) register details + */ +#define MBX_ECCSTATUS_REG_OFFSET 0x10u + +#define MBX_ECCSTATUS_OFFSET 0x10 +#define MBX_ECCSTATUS_MASK 0x03u +#define MBX_ECCSTATUS_SHIFT 0u + + +/*------------------------------------------------------------------------------ + * MBX_WCNT (offset 0x14) register details + */ +#define MBX_WCNT_REG_OFFSET 0x14u + +#define MBX_WCNT_OFFSET 0x14 +#define MBX_WCNT_MASK 0x000001FFu +#define MBX_WCNT_SHIFT 0u + +/*------------------------------------------------------------------------------ + * MBX_RWCNT (offset 0x18) register details + */ +#define MBX_RCNT_REG_OFFSET 0x18u + +#define MBX_RCNT_OFFSET 0x18 +#define MBX_RCNT_MASK 0x000001FFu +#define MBX_RCNT_SHIFT 0u + +/*------------------------------------------------------------------------------ + * MBX_WADRDESC (offset 0x1C) register details + */ +#define MBX_WADDR_REG_OFFSET 0x1Cu + +#define MBX_WADDR_OFFSET 0x1C +#define MBX_WADDR_MASK 0x000001FFu +#define MBX_WADDR_SHIFT 0u + +/*------------------------------------------------------------------------------ + * MBX_RADRDESC (offset 0x20) register details + */ +#define MBX_RADDR_REG_OFFSET 0x20u + +#define MBX_RADDR_OFFSET 0x20 +#define MBX_RADDR_MASK 0x000001FFu +#define MBX_RADDR_SHIFT 0u + +/*------------------------------------------------------------------------------ + * MBX_WDATA (offset 0x28) register details + */ +#define MBX_WDATA_REG_OFFSET 0x28u + +#define MBX_WDATA_OFFSET 0x28 +#define MBX_WDATA_MASK 0xFFFFFFFFu +#define MBX_WDATA_SHIFT 0u + + +/*------------------------------------------------------------------------------ + * MBX_RDATA (offset 0x2C) register details + */ +#define MBX_RDATA_REG_OFFSET 0x2Cu + +#define MBX_RDATA_OFFSET 0x2C +#define MBX_RDATA_MASK 0xFFFFFFFFu +#define MBX_RDATA_SHIFT 0u + +/*------------------------------------------------------------------------------ + * SS_USER (offset 0x30) register details + */ +#define SS_USER_REG_OFFSET 0x30u + +#define SS_USER_BUSY_OFFSET 0x30 +#define SS_USER_BUSY_MASK 0x00000001u +#define SS_USER_BUSY_SHIFT 0u + +#define SS_USER_RDVLD_OFFSET 0x30 +#define SS_USER_RDVLD_MASK 0x00000002u +#define SS_USER_RDVLD_SHIFT 1u + +#define SS_USER_CMDERR_OFFSET 0x30 +#define SS_USER_CMDERR_MASK 0x00000004u +#define SS_USER_CMDERR_SHIFT 2u + +#ifdef __cplusplus +} +#endif + +#endif /* __CORE_SYSSERV_PF_REGISTERS */ diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreTimer/core_timer.c b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreTimer/core_timer.c new file mode 100644 index 0000000..f89c5b3 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreTimer/core_timer.c @@ -0,0 +1,158 @@ +/******************************************************************************* + * (c) Copyright 2007-2015 Microsemi SoC Products Group. All rights reserved. + * + * CoreTimer driver implementation. + * + * SVN $Revision: 7967 $ + * SVN $Date: 2015-10-09 18:48:26 +0530 (Fri, 09 Oct 2015) $ + */ + +#include "core_timer.h" +#include "coretimer_regs.h" +#include "hal/hal.h" +#include "hal/hal_assert.h" + +#ifndef NDEBUG +static timer_instance_t* NULL_timer_instance; +#endif + +/***************************************************************************//** + * TMR_init() + * See "core_timer.h" for details of how to use this function. + */ +void +TMR_init +( + timer_instance_t * this_timer, + addr_t address, + uint8_t mode, + uint32_t prescale, + uint32_t load_value +) +{ + HAL_ASSERT( this_timer != NULL_timer_instance ) + HAL_ASSERT( prescale <= PRESCALER_DIV_1024 ) + HAL_ASSERT( load_value != 0 ) + + this_timer->base_address = address; + + /* Disable interrupts. */ + HAL_set_32bit_reg_field( address, InterruptEnable,0 ); + + /* Disable timer. */ + HAL_set_32bit_reg_field( address, TimerEnable, 0 ); + + /* Clear pending interrupt. */ + HAL_set_32bit_reg( address, TimerIntClr, 1 ); + + /* Configure prescaler and load value. */ + HAL_set_32bit_reg( address, TimerPrescale, prescale ); + HAL_set_32bit_reg( address, TimerLoad, load_value ); + + /* Set the interrupt mode. */ + if ( mode == TMR_CONTINUOUS_MODE ) + { + HAL_set_32bit_reg_field( address, TimerMode, 0 ); + } + else + { + /* TMR_ONE_SHOT_MODE */ + HAL_set_32bit_reg_field( address, TimerMode, 1 ); + } +} + +/***************************************************************************//** + * TMR_start() + * See "core_timer.h" for details of how to use this function. + */ +void +TMR_start +( + timer_instance_t * this_timer +) +{ + HAL_ASSERT( this_timer != NULL_timer_instance ) + + HAL_set_32bit_reg_field( this_timer->base_address, TimerEnable, 1 ); +} + +/***************************************************************************//** + * TMR_stop() + * See "core_timer.h" for details of how to use this function. + */ +void +TMR_stop +( + timer_instance_t * this_timer +) +{ + HAL_ASSERT( this_timer != NULL_timer_instance ) + + HAL_set_32bit_reg_field( this_timer->base_address, TimerEnable, 0 ); +} + + +/***************************************************************************//** + * TMR_enable_int() + * See "core_timer.h" for details of how to use this function. + */ +void +TMR_enable_int +( + timer_instance_t * this_timer +) +{ + HAL_ASSERT( this_timer != NULL_timer_instance ) + + HAL_set_32bit_reg_field( this_timer->base_address, InterruptEnable, 1 ); +} + +/***************************************************************************//** + * TMR_clear_int() + * See "core_timer.h" for details of how to use this function. + */ +void +TMR_clear_int +( + timer_instance_t * this_timer +) +{ + HAL_ASSERT( this_timer != NULL_timer_instance ) + + HAL_set_32bit_reg( this_timer->base_address, TimerIntClr, 0x01 ); +} + +/***************************************************************************//** + * TMR_current_value() + * See "core_timer.h" for details of how to use this function. + */ +uint32_t +TMR_current_value +( + timer_instance_t * this_timer +) +{ + uint32_t value = 0; + HAL_ASSERT( this_timer != NULL_timer_instance ) + + value = HAL_get_32bit_reg( this_timer->base_address, TimerValue ); + + return value; +} + +/***************************************************************************//** + * TMR_reload() + * See "core_timer.h" for details of how to use this function. + */ +void TMR_reload +( + timer_instance_t * this_timer, + uint32_t load_value +) +{ + HAL_ASSERT( this_timer != NULL_timer_instance ) + HAL_ASSERT( load_value != 0 ) + + HAL_set_32bit_reg(this_timer->base_address, TimerLoad, load_value ); +} + diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreTimer/core_timer.h b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreTimer/core_timer.h new file mode 100644 index 0000000..b5d9984 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreTimer/core_timer.h @@ -0,0 +1,206 @@ +/******************************************************************************* + * (c) Copyright 2007-2015 Microsemi SoC Products Group. All rights reserved. + * + * CoreTimer public API. + * + * SVN $Revision: 7967 $ + * SVN $Date: 2015-10-09 18:48:26 +0530 (Fri, 09 Oct 2015) $ + */ +#ifndef CORE_TIMER_H_ +#define CORE_TIMER_H_ + +#include "hal/cpu_types.h" + +/***************************************************************************//** + * The following definitions are used to select the CoreTimer driver operating + * mode. They allow selecting continuous or one-shot mode. + * 1. Continuous Mode + * In continuous mode the timer's counter is decremented from the load value + * until it reaches zero. The timer counter is automatically reloaded, with the + * load value, upon reaching zero. An interrupt is generated every time the + * counter reaches zero if interrupt is enabled. + * This mode is typically used to generate an interrupt at constant time + * intervals. + * 2. One-shot mode: + * In one-shot mode, the counter decrements from the load value and until it + * reaches zero. An interrupt can be generated, if enabled, when the counter + * reaches zero. The timer's counter must be reloaded to begin counting down + * again. + */ +#define TMR_CONTINUOUS_MODE 0 +#define TMR_ONE_SHOT_MODE 1 + +/***************************************************************************//** + * The following definitions are used to configure the CoreTimer prescaler. + * The prescaler is used to divide down the clock used to decrement the + * CoreTimer counter. It can be configure to divide the clock by 2, 4, 8, + * 16, 32, 64, 128, 256, 512, or 1024. + */ +#define PRESCALER_DIV_2 0 +#define PRESCALER_DIV_4 1 +#define PRESCALER_DIV_8 2 +#define PRESCALER_DIV_16 3 +#define PRESCALER_DIV_32 4 +#define PRESCALER_DIV_64 5 +#define PRESCALER_DIV_128 6 +#define PRESCALER_DIV_256 7 +#define PRESCALER_DIV_512 8 +#define PRESCALER_DIV_1024 9 + +/***************************************************************************//** + * There should be one instance of this structure for each instance of CoreTimer + * in your system. The function TMR_init() initializes this structure. It is + * used to identify the various CoreTimer hardware instances in your system. + * An initialized timer instance structure should be passed as first parameter to + * CoreTimer driver functions to identify which CoreTimer instance should perform + * the requested operation. + * Software using this driver should only need to create one single instance of + * this data structure for each hardware timer instance in the system. + */ +typedef struct __timer_instance_t +{ + addr_t base_address; +} timer_instance_t; + +/***************************************************************************//** + * The function TMR_init() initializes the data structures and sets relevant + * CoreTimer registers. This function will prepare the Timer for use in a given + * hardware/software configuration. It should be called before any other Timer + * API functions. + * The timer will not start counting down immediately after this function is + * called. It is necessary to call TMR_start() to start the timer decrementing. + * The CoreTimer interrupt is disabled as part of this function. + * + * @param this_timer Pointer to a timer_instance_t structure holding all + * relevant data associated with the target timer hardware + * instance. This pointer will be used to identify the + * target CoreTimer hardware instance in subsequent calls + * to the CoreTimer functions. + * @param address Base address in the processor's memory map of the + * registers of the CoreTimer instance being initialized. + * @param mode This parameter is used to select the operating mode of + * the timer driver. This can be either TMR_CONTINUOUS_MODE + * or TMR_ONE_SHOT_MODE. + * @param prescale This parameter is used to select the prescaler divider + * used to divide down the clock used to decrement the + * timer�s counter. This can be set using one of the + * PRESCALER_DIV_ definitions, where is the + * divider�s value. + * @param load_value This parameter is used to set the timer�s load value + * from which the CoreTimer counter will decrement. + * In Continuous mode, this value will be used to reload + * the timer�s counter whenever it reaches zero. + */ +void +TMR_init +( + timer_instance_t * this_timer, + addr_t address, + uint8_t mode, + uint32_t prescale, + uint32_t load_value +); + +/***************************************************************************//** + * The function TMR_start() enables the timer to start counting down. + * This function only needs to be called once after the timer has been + * initialized through a call to TMR_init(). It does not need to be called after + * each call to TMR_reload() when the timer is used in one-shot mode. + * + * @param this_timer Pointer to a timer_instance_t structure holding all + * relevant data associated with the target timer hardware + * instance. This pointer is used to identify the target + * CoreTimer hardware instance. + */ +void +TMR_start +( + timer_instance_t * this_timer +); + +/***************************************************************************//** + * The function TMR_stop() stops the timer counting down. It can be used to + * stop interrupts from being generated when continuous mode is used and + * interrupts must be paused from being generated. + * + * @param this_timer Pointer to a timer_instance_t structure holding all + * relevant data associated with the target timer hardware + * instance. This pointer is used to identify the target + * CoreTimer hardware instance. + */ +void +TMR_stop +( + timer_instance_t * this_timer +); + +/***************************************************************************//** + * The function TMR_enable_int() enables the timer interrupt. A call to this + * function will allow the interrupt signal coming out of CoreTimer to be + * asserted. + * + * @param this_timer Pointer to a timer_instance_t structure holding all + * relevant data associated with the target timer hardware + * instance. This pointer is used to identify the target + * CoreTimer hardware instance. + */ +void +TMR_enable_int +( + timer_instance_t * this_timer +); + +/***************************************************************************//** + * The function TMR_clear_int() clears the timer interrupt. This function should + * be called within the interrupt handler servicing interrupts from the timer. + * Failure to clear the timer interrupt will result in the interrupt signal + * generating from CoreTimer to remain asserted. This assertion may cause the + * interrupt service routine to be continuously called, causing the system to + * lock up. + * + * @param this_timer Pointer to a timer_instance_t structure holding all + * relevant data associated with the target timer hardware + * instance. This pointer is used to identify the target + * CoreTimer hardware instance. + */ +void +TMR_clear_int +( + timer_instance_t * this_timer +); + +/***************************************************************************//** + * The TMR_current_value() function returns the current value of the counter. + * + * @param this_timer Pointer to a timer_instance_t structure holding all + * relevant data associated with the target timer hardware + * instance. This pointer is used to identify the target + * CoreTimer hardware instance. + * + * @return Returns the current value of the timer counter value. + */ +uint32_t +TMR_current_value +( + timer_instance_t * this_timer +); + +/***************************************************************************//** + * The TMR_reload() function is used in one-shot mode. It reloads the timer + * counter with the values passed as parameter. This will result in an interrupt + * being generated when the timer counter reaches 0 if interrupt is enabled. + * + * @param this_timer Pointer to a timer_instance_t structure holding all + * relevant data associated with the target timer hardware + * instance. This pointer is used to identify the target + * CoreTimer hardware instance. + * @param load_value This parameter sets the value from which the CoreTimer + * counter will decrement. + */ +void TMR_reload +( + timer_instance_t * this_timer, + uint32_t load_value +); + +#endif /* CORE_TIMER_H_ */ diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreTimer/coretimer_regs.h b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreTimer/coretimer_regs.h new file mode 100644 index 0000000..8ce8872 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreTimer/coretimer_regs.h @@ -0,0 +1,109 @@ +/******************************************************************************* + * (c) Copyright 2007-2015 Microsemi SoC Products Group. All rights reserved. + * + * SVN $Revision: 7967 $ + * SVN $Date: 2015-10-09 18:48:26 +0530 (Fri, 09 Oct 2015) $ + */ + +#ifndef __CORE_TIMER_REGISTERS +#define __CORE_TIMER_REGISTERS 1 + +/*------------------------------------------------------------------------------ + * TimerLoad register details + */ +#define TimerLoad_REG_OFFSET 0x00 + +/* + * LoadValue bits. + */ +#define LoadValue_OFFSET 0x00 +#define LoadValue_MASK 0xFFFFFFFF +#define LoadValue_SHIFT 0 + +/*------------------------------------------------------------------------------ + * TimerValue register details + */ +#define TimerValue_REG_OFFSET 0x04 + +/* + * CurrentValue bits. + */ +#define CurrentValue_OFFSET 0x04 +#define CurrentValue_MASK 0xFFFFFFFF +#define CurrentValue_SHIFT 0 + +/*------------------------------------------------------------------------------ + * TimerControl register details + */ +#define TimerControl_REG_OFFSET 0x08 + +/* + * TimerEnable bits. + */ +#define TimerEnable_OFFSET 0x08 +#define TimerEnable_MASK 0x00000001 +#define TimerEnable_SHIFT 0 + +/* + * InterruptEnable bits. + */ +#define InterruptEnable_OFFSET 0x08 +#define InterruptEnable_MASK 0x00000002 +#define InterruptEnable_SHIFT 1 + +/* + * TimerMode bits. + */ +#define TimerMode_OFFSET 0x08 +#define TimerMode_MASK 0x00000004 +#define TimerMode_SHIFT 2 + +/*------------------------------------------------------------------------------ + * TimerPrescale register details + */ +#define TimerPrescale_REG_OFFSET 0x0C + +/* + * Prescale bits. + */ +#define Prescale_OFFSET 0x0C +#define Prescale_MASK 0x0000000F +#define Prescale_SHIFT 0 + +/*------------------------------------------------------------------------------ + * TimerIntClr register details + */ +#define TimerIntClr_REG_OFFSET 0x10 + +/* + * TimerIntClr bits. + */ +#define TimerIntClr_OFFSET 0x10 +#define TimerIntClr_MASK 0xFFFFFFFF +#define TimerIntClr_SHIFT 0 + +/*------------------------------------------------------------------------------ + * TimerRIS register details + */ +#define TimerRIS_REG_OFFSET 0x14 + +/* + * RawTimerInterrupt bits. + */ +#define RawTimerInterrupt_OFFSET 0x14 +#define RawTimerInterrupt_MASK 0x00000001 +#define RawTimerInterrupt_SHIFT 0 + +/*------------------------------------------------------------------------------ + * TimerMIS register details + */ +#define TimerMIS_REG_OFFSET 0x18 + +/* + * TimerInterrupt bits. + */ +#define TimerInterrupt_OFFSET 0x18 +#define TimerInterrupt_MASK 0x00000001 +#define TimerInterrupt_SHIFT 0 + +#endif /* __CORE_TIMER_REGISTERS */ diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreUARTapb/core_uart_apb.c b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreUARTapb/core_uart_apb.c new file mode 100644 index 0000000..2b2087a --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreUARTapb/core_uart_apb.c @@ -0,0 +1,295 @@ +/******************************************************************************* + * (c) Copyright 2007-2021 Microchip FPGA Embedded Systems Solutions. + * + * @file core_uart_apb.c + * @author Microchip FPGA Embedded Systems Solutions + * @brief CoreUARTapb driver implementation. See file "core_uart_apb.h" for + * description of the functions implemented in this file. + * + */ + +#include "coreuartapb_regs.h" +#include "core_uart_apb.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define NULL_INSTANCE ( ( UART_instance_t* ) 0 ) +#define NULL_BUFFER ( ( uint8_t* ) 0 ) + +#define MAX_LINE_CONFIG ( ( uint8_t )( DATA_8_BITS | ODD_PARITY ) ) +#define MAX_BAUD_VALUE ( ( uint16_t )( 0x1FFF ) ) +#define STATUS_ERROR_MASK ( ( uint8_t )( STATUS_PARITYERR_MASK | \ + STATUS_OVERFLOW_MASK | \ + STATUS_FRAMERR_MASK ) ) +#define BAUDVALUE_LSB ( (uint16_t) (0x00FF) ) +#define BAUDVALUE_MSB ( (uint16_t) (0xFF00) ) +#define BAUDVALUE_SHIFT ( (uint8_t) (5) ) + +#define STATUS_ERROR_OFFSET STATUS_PARITYERR_SHIFT + +/***************************************************************************//** + * UART_init() + * See "core_uart_apb.h" for details of how to use this function. + */ +void +UART_init +( + UART_instance_t * this_uart, + addr_t base_addr, + uint16_t baud_value, + uint8_t line_config +) +{ + uint8_t rx_full; + + HAL_ASSERT( this_uart != NULL_INSTANCE ) + HAL_ASSERT( line_config <= MAX_LINE_CONFIG ) + HAL_ASSERT( baud_value <= MAX_BAUD_VALUE ) + + if( ( this_uart != NULL_INSTANCE ) && + ( line_config <= MAX_LINE_CONFIG ) && + ( baud_value <= MAX_BAUD_VALUE ) ) + { + /* + * Store lower 8-bits of baud value in CTRL1. + */ + HAL_set_8bit_reg( base_addr, CTRL1, (uint_fast8_t)(baud_value & + BAUDVALUE_LSB ) ); + + /* + * Extract higher 5-bits of baud value and store in higher 5-bits + * of CTRL2, along with line configuration in lower 3 three bits. + */ + HAL_set_8bit_reg( base_addr, CTRL2, (uint_fast8_t)line_config | + (uint_fast8_t)((baud_value & + BAUDVALUE_MSB) >> BAUDVALUE_SHIFT ) ); + + this_uart->base_address = base_addr; +#ifndef NDEBUG + { + uint8_t config; + uint8_t temp; + uint16_t baud_val; + baud_val = HAL_get_8bit_reg( this_uart->base_address, CTRL1 ); + config = HAL_get_8bit_reg( this_uart->base_address, CTRL2 ); + /* + * To resolve operator precedence between & and << + */ + temp = ( config & (uint8_t)(CTRL2_BAUDVALUE_MASK ) ); + baud_val |= (uint16_t)( (uint16_t)(temp) << BAUDVALUE_SHIFT ); + config &= (uint8_t)(~CTRL2_BAUDVALUE_MASK); + HAL_ASSERT( baud_val == baud_value ); + HAL_ASSERT( config == line_config ); + } +#endif + + /* + * Flush the receive FIFO of data that may have been received before the + * driver was initialized. + */ + rx_full = HAL_get_8bit_reg( this_uart->base_address, STATUS ) & + STATUS_RXFULL_MASK; + while ( rx_full ) + { + HAL_get_8bit_reg( this_uart->base_address, RXDATA ); + rx_full = HAL_get_8bit_reg( this_uart->base_address, STATUS ) & + STATUS_RXFULL_MASK; + } + + /* + * Clear status of the UART instance. + */ + this_uart->status = (uint8_t)0; + } +} + +/***************************************************************************//** + * UART_send() + * See "core_uart_apb.h" for details of how to use this function. + */ +void +UART_send +( + UART_instance_t * this_uart, + const uint8_t * tx_buffer, + size_t tx_size +) +{ + size_t char_idx; + uint8_t tx_ready; + + HAL_ASSERT( this_uart != NULL_INSTANCE ) + HAL_ASSERT( tx_buffer != NULL_BUFFER ) + HAL_ASSERT( tx_size > 0 ) + + if( (this_uart != NULL_INSTANCE) && + (tx_buffer != NULL_BUFFER) && + (tx_size > (size_t)0) ) + { + for ( char_idx = (size_t)0; char_idx < tx_size; char_idx++ ) + { + /* Wait for UART to become ready to transmit. */ + do { + tx_ready = HAL_get_8bit_reg( this_uart->base_address, STATUS ) & + STATUS_TXRDY_MASK; + } while ( !tx_ready ); + /* Send next character in the buffer. */ + HAL_set_8bit_reg( this_uart->base_address, TXDATA, + (uint_fast8_t)tx_buffer[char_idx] ); + } + } +} + +/***************************************************************************//** + * UART_fill_tx_fifo() + * See "core_uart_apb.h" for details of how to use this function. + */ +size_t +UART_fill_tx_fifo +( + UART_instance_t * this_uart, + const uint8_t * tx_buffer, + size_t tx_size +) +{ + uint8_t tx_ready; + size_t size_sent = 0u; + + HAL_ASSERT( this_uart != NULL_INSTANCE ) + HAL_ASSERT( tx_buffer != NULL_BUFFER ) + HAL_ASSERT( tx_size > 0 ) + + /* Fill the UART's Tx FIFO until the FIFO is full or the complete input + * buffer has been written. */ + if( (this_uart != NULL_INSTANCE) && + (tx_buffer != NULL_BUFFER) && + (tx_size > 0u) ) + { + tx_ready = HAL_get_8bit_reg( this_uart->base_address, STATUS ) & + STATUS_TXRDY_MASK; + if ( tx_ready ) + { + do { + HAL_set_8bit_reg( this_uart->base_address, TXDATA, + (uint_fast8_t)tx_buffer[size_sent] ); + size_sent++; + tx_ready = HAL_get_8bit_reg( this_uart->base_address, STATUS ) & + STATUS_TXRDY_MASK; + } while ( (tx_ready) && ( size_sent < tx_size ) ); + } + } + return size_sent; +} + +/***************************************************************************//** + * UART_get_rx() + * See "core_uart_apb.h" for details of how to use this function. + */ +size_t +UART_get_rx +( + UART_instance_t * this_uart, + uint8_t * rx_buffer, + size_t buff_size +) +{ + uint8_t new_status; + uint8_t rx_full; + size_t rx_idx = 0u; + + HAL_ASSERT( this_uart != NULL_INSTANCE ) + HAL_ASSERT( rx_buffer != NULL_BUFFER ) + HAL_ASSERT( buff_size > 0 ) + + if( (this_uart != NULL_INSTANCE) && + (rx_buffer != NULL_BUFFER) && + (buff_size > 0u) ) + { + rx_idx = 0u; + new_status = HAL_get_8bit_reg( this_uart->base_address, STATUS ); + this_uart->status |= new_status; + rx_full = new_status & STATUS_RXFULL_MASK; + while ( ( rx_full ) && ( rx_idx < buff_size ) ) + { + rx_buffer[rx_idx] = HAL_get_8bit_reg( this_uart->base_address, + RXDATA ); + rx_idx++; + new_status = HAL_get_8bit_reg( this_uart->base_address, STATUS ); + this_uart->status |= new_status; + rx_full = new_status & STATUS_RXFULL_MASK; + } + } + return rx_idx; +} + +/***************************************************************************//** + * UART_polled_tx_string() + * See "core_uart_apb.h" for details of how to use this function. + */ +void +UART_polled_tx_string +( + UART_instance_t * this_uart, + const uint8_t * p_sz_string +) +{ + uint32_t char_idx; + uint8_t tx_ready; + + HAL_ASSERT( this_uart != NULL_INSTANCE ) + HAL_ASSERT( p_sz_string != NULL_BUFFER ) + + if( ( this_uart != NULL_INSTANCE ) && ( p_sz_string != NULL_BUFFER ) ) + { + char_idx = 0U; + while( 0U != p_sz_string[char_idx] ) + { + /* Wait for UART to become ready to transmit. */ + do { + tx_ready = HAL_get_8bit_reg( this_uart->base_address, STATUS ) & + STATUS_TXRDY_MASK; + } while ( !tx_ready ); + /* Send next character in the buffer. */ + HAL_set_8bit_reg( this_uart->base_address, TXDATA, + (uint_fast8_t)p_sz_string[char_idx] ); + char_idx++; + } + } +} + +/***************************************************************************//** + * UART_get_rx_status() + * See "core_uart_apb.h" for details of how to use this function. + */ +uint8_t +UART_get_rx_status +( + UART_instance_t * this_uart +) +{ + uint8_t status = UART_APB_INVALID_PARAM; + + HAL_ASSERT( this_uart != NULL_INSTANCE ) + /* + * Extract UART error status and place in lower bits of "status". + * Bit 0 - Parity error status + * Bit 1 - Overflow error status + * Bit 2 - Frame error status + */ + if( this_uart != NULL_INSTANCE ) + { + status = ( ( this_uart->status & STATUS_ERROR_MASK ) >> + STATUS_ERROR_OFFSET ); + /* + * Clear the sticky status for this instance. + */ + this_uart->status = (uint8_t)0; + } + return status; +} + +#ifdef __cplusplus +} +#endif diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreUARTapb/core_uart_apb.h b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreUARTapb/core_uart_apb.h new file mode 100644 index 0000000..2ce0b88 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreUARTapb/core_uart_apb.h @@ -0,0 +1,432 @@ +/******************************************************************************* + * (c) Copyright 2007-2021 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * @file core_uart_apb.h + * @author Microchip FPGA Embedded Systems Solutions + * @brief This file contains the application programming interface for the + * CoreUARTapb bare metal driver. + * + */ +/*=========================================================================*//** + @mainpage CoreUARTapb Bare Metal Driver. + + @section intro_sec Introduction + CoreUARTapb is an implementation of the Universal Asynchronous + Receiver/Transmitter aimed at a minimal FPGA tile usage within an Microsemi + FPGA. The CoreUARTapb bare metal software driver is designed for use in + systems with no operating system. + + The CoreUARTapb driver provides functions for basic polled transmitting and + receiving operations. It also provides functions allowing use of the + CoreUARTapb in interrupt-driven mode, but leaves the management of interrupts + to the calling application, as interrupt enabling and disabling cannot be + controlled through the CoreUARTapb registers. The CoreUARTapb driver is + provided as C source code. + + @section driver_configuration Driver Configuration + Your application software should configure the CoreUARTapb driver, through + calls to the UART_init() function for each CoreUARTapb instance in the + hardware design. The configuration parameters include the CoreUARTapb + hardware instance base address and other runtime parameters, such as baud + rate, bit width, and parity. No CoreUARTapb hardware configuration parameters + are needed by the driver, apart from the CoreUARTapb hardware instance base + address. Hence, no additional configuration files are required to use the driver. + + A CoreUARTapb hardware instance can be generated with fixed baud value, + character size and parity configuration settings as part of the hardware flow. + The baud_value and line_config parameter values passed to the UART_init() + function will not have any effect if fixed values were selected for the + baud value, character size and parity in the hardware configuration of + CoreUARTapb. When fixed values are selected for these hardware configuration + parameters, the driver cannot overwrite the fixed values in the CoreUARTapb + control registers, CTRL1 and CTRL2. + + @section theory_op Theory of Operation + The CoreUARTapb software driver is designed to allow the control of multiple + instances of CoreUARTapb. Each instance of CoreUARTapb in the hardware design + is associated with a single instance of the UART_instance_t structure in the + software. You need to allocate memory for one unique UART_instance_t + structure instance for each CoreUARTapb hardware instance. The contents of + these data structures are initialized during calls to function UART_init(). + A pointer to the structure is passed to subsequent driver functions in order + to identify the CoreUARTapb hardware instance you wish to perform the + requested operation on. + + Note: Do not attempt to directly manipulate the content of UART_instance_t + structures. This structure is only intended to be modified by the driver + function. + + The driver can be used to transmit and receive data once initialized. + Transmit can be performed using the UART_send() function. This function + is blocking, meaning that it will only return once the data passed to + the function has been sent to the CoreUARTapb hardware. Data received + by the CoreUARTapb hardware can be read by the user application using + the UART_get_rx() function. + + The function UART_fill_tx_fifo() is also provided to be used as part of + interrupt-driven transmit. This function fills the CoreUARTapb hardware + transmit FIFO with the content of a data buffer passed as a parameter before + returning. The control of the interrupts must be implemented outside the + driver as the CoreUARTapb hardware does not provide the ability to enable + or disable its interrupt sources. + + The function UART_polled_tx_string() is provided to transmit a NULL + terminated string in polled mode. This function is blocking, meaning that it + will only return once the data passed to the function has been sent to the + CoreUARTapb hardware. + + The function UART_get_rx_status() returns the error status of the CoreUARTapb + receiver. This can be used by applications to take appropriate action in case + of receiver errors. +*//*=========================================================================*/ +#ifndef __CORE_UART_APB_H +#define __CORE_UART_APB_H 1 + +#ifndef LEGACY_DIR_STRUCTURE +#include "hal/hal.h" + +#else +#include "hal.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/***************************************************************************//** + * Data bits length defines: + */ +#define DATA_7_BITS 0x00u +#define DATA_8_BITS 0x01u + +/***************************************************************************//** + * Parity defines: + */ +#define NO_PARITY 0x00u +#define EVEN_PARITY 0x02u +#define ODD_PARITY 0x06u + +/***************************************************************************//** + * Error Status definitions: + */ +#define UART_APB_PARITY_ERROR 0x01u +#define UART_APB_OVERFLOW_ERROR 0x02u +#define UART_APB_FRAMING_ERROR 0x04u +#define UART_APB_NO_ERROR 0x00u +#define UART_APB_INVALID_PARAM 0xFFu + +/***************************************************************************//** + * UART_instance_t + * + * There should be one instance of this structure for each instance of CoreUARTapb + * in your system. This structure instance is used to identify the various UARTs + * in a system and should be passed as first parameter to UART functions to + * identify which UART should perform the requested operation. The 'status' + * element in the structure is used to provide sticky status information. + */ +typedef struct +{ + addr_t base_address; + uint8_t status; +} UART_instance_t; + +/***************************************************************************//** + * The function UART_init() initializes the UART with the configuration passed + * as parameters. The configuration parameters are the baud_value used to + * generate the baud rate and the line configuration (bit length and parity). + * + * @param this_uart The this_uart parameter is a pointer to a UART_instance_t + * structure which holds all data regarding this instance of + * the CoreUARTapb. This pointer will be used to identify + * the target CoreUARTapb hardware instance in subsequent + * calls to the CoreUARTapb functions. + * @param base_addr The base_address parameter is the base address in the + * processor's memory map for the registers of the + * CoreUARTapb instance being initialized. + * @param baud_value The baud_value parameter is used to select the baud rate + * for the UART. The baud value is calculated from the + * frequency of the system clock in hertz and the desired + * baud rate using the following equation: + * + * baud_value = (clock /(baud_rate * 16)) - 1. + * + * The baud_value parameter must be a value in the range 0 + * to 8191 (or 0x0000 to 0x1FFF). + * @param line_config This parameter is the line configuration specifying the + * bit length and parity settings. This is a logical OR of: + * - DATA_7_BITS + * - DATA_8_BITS + * - NO_PARITY + * - EVEN_PARITY + * - ODD_PARITY + * For example, 8 bits even parity would be specified as + * (DATA_8_BITS | EVEN_PARITY). + * @return This function does not return a value. + * Example: + * @code + * #define BAUD_VALUE_57600 25 + * + * #define COREUARTAPB0_BASE_ADDR 0xC3000000UL + * + * UART_instance_t g_uart; + * int main() + * { + * UART_init(&g_uart, COREUARTAPB0_BASE_ADDR, + BAUD_VALUE_57600, (DATA_8_BITS | EVEN_PARITY)); + * } + * @endcode + */ +void +UART_init +( + UART_instance_t * this_uart, + addr_t base_addr, + uint16_t baud_value, + uint8_t line_config +); + +/***************************************************************************//** + * The function UART_send() is used to transmit data. It transfers the contents + * of the transmitter data buffer, passed as a function parameter, into the + * UART's hardware transmitter FIFO. It returns when the full content of the + * transmitter data buffer has been transferred to the UART's transmitter FIFO. + * + * Note: you cannot assume that the data you are sending using this function has + * been received at the other end by the time this function returns. The actual + * transmit over the serial connection will still be taking place at the time of + * the function return. It is safe to release or reuse the memory used as the + * transmit buffer once this function returns. + * + * @param this_uart The this_uart parameter is a pointer to a + * UART_instance_t structure which holds all data regarding + * this instance of the CoreUARTapbUART. + * @param tx_buffer The tx_buffer parameter is a pointer to a buffer + * containing the data to be transmitted. + * @param tx_size The tx_size parameter is the size, in bytes, of + * the data to be transmitted. + * + * @return This function does not return a value. + * + * Example: + * @code + * uint8_t testmsg1[] = {"\n\r\n\r\n\rUART_send() test message 1"}; + * UART_send(&g_uart,(const uint8_t *)&testmsg1,sizeof(testmsg1)); + * @endcode + */ +void +UART_send +( + UART_instance_t * this_uart, + const uint8_t * tx_buffer, + size_t tx_size +); + +/***************************************************************************//** + * The function UART_fill_tx_fifo() fills the UART's transmitter hardware FIFO + * with the data found in the transmitter buffer that is passed in as a + * function parameter. The function returns either when the FIFO is full or + * when the complete contents of the transmitter buffer have been copied into + * the FIFO. It returns the number of bytes copied into the UART's transmitter + * hardware FIFO. This function is intended to be used as part of + * interrupt-driven transmission. + * + * Note: You cannot assume that the data you transmit using this function has + * been received at the other end by the time this function returns. + * The actual transmission over the serial connection will still be + * taking place at the time of the function return. + * + * @param this_uart The this_uart parameter is a pointer to a UART_instance_t + * structure which holds all data regarding this instance of + * the UART. + * @param tx_buffer The tx_buffer parameter is a pointer to a buffer + * containing the data to be transmitted. + * @param tx_size The tx_size parameter is the size in bytes, of the data + * to be transmitted. + * @return This function returns the number of bytes copied + * into the UART's transmitter hardware FIFO. + * + * Example: + * @code + * void send_using_interrupt + * ( + * uint8_t * pbuff, + * size_t tx_size + * ) + * { + * size_t size_in_fifo; + * size_in_fifo = UART_fill_tx_fifo( &g_uart, pbuff, tx_size ); + * } + * @endcode + */ +size_t +UART_fill_tx_fifo +( + UART_instance_t * this_uart, + const uint8_t * tx_buffer, + size_t tx_size +); + +/***************************************************************************//** + * The function UART_get_rx() reads the content of the UART's receiver hardware + * FIFO and stores it in the receiver buffer that is passed in as a function + * parameter. It copies either the full contents of the FIFO into the receiver + * buffer, or just enough data from the FIFO to fill the receiver buffer, + * dependent upon the size of the receiver buffer. The size of the receiver + * buffer is passed in as a function parameter. UART_get_rx() returns the number + * of bytes copied into the receiver buffer. If no data was received at the time + * the function is called, the function returns 0. + * + * Note: This function reads and accumulates the receiver status of the + * CoreUARTapb instance before reading each byte from the receiver's + * data register/FIFO. This allows the driver to maintain a sticky + * record of any receiver errors that occur as the UART receives each + * data byte; receiver errors would otherwise be lost after each read + * from the receiver's data register. A call to the UART_get_rx_status() + * function returns any receiver errors accumulated during the execution + * of the UART_get_rx() function. + * Note: When FIFO mode is disabled in the CoreUARTapb hardware configuration, + * the driver accumulates a sticky record of any parity errors, framing + * errors or overflow errors. When FIFO mode is enabled, the driver + * accumulates a sticky record of overflow errors only; in this case + * interrupts must be used to handle parity errors or framing errors. + * + * @param this_uart The this_uart parameter is a pointer to a UART_instance_t + * structure which holds all data regarding this instance of + * the UART. + * @param rx_buffer The rx_buffer parameter is a pointer to a buffer where the + * received data will be copied. + * @param buff_size The buff_size parameter is the size of the receive buffer + * in bytes. + * @return This function returns the number of bytes copied into the + * receive buffer. + * + * Example: + * @code + * #define MAX_RX_DATA_SIZE 256 + * + * uint8_t rx_data[MAX_RX_DATA_SIZE]; + * uint8_t rx_size = 0; + * + * rx_size = UART_get_rx( &g_uart, rx_data, sizeof(rx_data) ); + * @endcode + */ +size_t +UART_get_rx +( + UART_instance_t * this_uart, + uint8_t * rx_buffer, + size_t buff_size +); + +/***************************************************************************//** + * The function UART_polled_tx_string() is used to transmit a NULL ('\0') + * terminated string. Internally, it polls for the transmit ready status and + * transfers the text starting at the address pointed to by p_sz_string into + * the UART's hardware transmitter FIFO. It is a blocking function and returns + * only when the complete string has been transferred to the UART's transmit + * FIFO. + * + * Note: You cannot assume that the data you transmit using this function + * has been received at the other end by the time this function + * returns. The actual transmission over the serial connection will + * still be taking place at the time of the function return. + * + * @param this_uart The this_uart parameter is a pointer to a + * UART_instance_t structure which holds + * all data regarding this instance of the UART. + * @param p_sz_string The p_sz_string parameter is a pointer to a buffer + * containing the NULL ('\0') terminated string to be + * transmitted. + * @return This function does not return a value. + * + * Example: + * @code + * uint8_t testmsg1[] = {"\r\n\r\nUART_polled_tx_string() test message 1\0"}; + * UART_polled_tx_string(&g_uart,(const uint8_t *)&testmsg1); + * @endcode + */ +void +UART_polled_tx_string +( + UART_instance_t * this_uart, + const uint8_t * p_sz_string +); + +/***************************************************************************//** + * The UART_get_rx_status() function returns the receiver error status of the + * CoreUARTapb instance. It reads both the current error status of the receiver + * and the accumulated error status from preceding calls to the UART_get_rx() + * function and combines them using a bitwise OR. It returns the cumulative + * parity, framing and overflow error status of the receiver, since the + * previous call to UART_get_rx_status(), as an 8-bit encoded value. + * + * Note: The UART_get_rx() function reads and accumulates the receiver status + * of the CoreUARTapb instance before reading each byte from the + * receiver's data register/FIFO. The driver maintains a sticky record + * of the cumulative error status, which persists after the + * UART_get_rx() function returns. The UART_get_rx_status() function + * clears this accumulated record of receiver errors before returning. + * + * @param this_uart The this_uart parameter is a pointer to a UART_instance_t + * structure which holds all data regarding this instance + * of the UART. + * @return This function returns the UART receiver error status as + * an 8-bit encoded value. The returned value is 0 if no + * receiver errors occurred. The driver provides a set of + * bit mask constants which should be compared with and/or + * used to mask the returned value to determine the + * receiver error status. + * When the return value is compared to the following bit + * masks, a non-zero result indicates that the + * corresponding error occurred: + * UART_APB_PARITY_ERROR (bit mask = 0x01) + * UART_APB_OVERFLOW_ERROR (bit mask = 0x02) + * UART_APB_FRAMING_ERROR (bit mask = 0x04) + * When the return value is compared to the following bit + * mask, a non-zero result indicates that no error occurred: + * UART_APB_NO_ERROR (0x00) + * + * Example: + * @code + * UART_instance_t g_uart; + * uint8_t rx_data[MAX_RX_DATA_SIZE]; + * uint8_t err_status; + * err_status = UART_get_err_status(&g_uart); + * + * if(UART_APB_NO_ERROR == err_status ) + * { + * rx_size = UART_get_rx( &g_uart, rx_data, MAX_RX_DATA_SIZE ); + * } + * @endcode + */ +uint8_t +UART_get_rx_status +( + UART_instance_t * this_uart +); + +#ifdef __cplusplus +} +#endif + +#endif /* __CORE_UART_APB_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreUARTapb/coreuartapb_regs.h b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreUARTapb/coreuartapb_regs.h new file mode 100644 index 0000000..8651f0c --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/CoreUARTapb/coreuartapb_regs.h @@ -0,0 +1,131 @@ +/******************************************************************************* + * (c) Copyright 2007-2021 Microchip FPGA Embedded Systems Solutions. + * + * @file coreuartapb_regs.h + * @author Microchip FPGA Embedded Systems Solutions + * @brief CoreUARTapb register definitions + */ + +#ifndef __CORE_UART_APB_REGISTERS +#define __CORE_UART_APB_REGISTERS 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/*------------------------------------------------------------------------------ + * TxData register details + */ +#define TXDATA_REG_OFFSET 0x0u + +/* + * TxData bits. + */ +#define TXDATA_OFFSET 0x0u +#define TXDATA_MASK 0xFFu +#define TXDATA_SHIFT 0u + +/*------------------------------------------------------------------------------ + * RxData register details + */ +#define RXDATA_REG_OFFSET 0x4u + +/* + * RxData bits. + */ +#define RXDATA_OFFSET 0x4u +#define RXDATA_MASK 0xFFu +#define RXDATA_SHIFT 0u + +/*------------------------------------------------------------------------------ + * ControReg1 register details + */ +#define CTRL1_REG_OFFSET 0x8u + +/* + * Baud value (Lower 8-bits) + */ +#define CTRL1_BAUDVALUE_OFFSET 0x8u +#define CTRL1_BAUDVALUE_MASK 0xFFu +#define CTRL1_BAUDVALUE_SHIFT 0u + +/*------------------------------------------------------------------------------ + * ControReg2 register details + */ +#define CTRL2_REG_OFFSET 0xCu + +/* + * Bit length + */ +#define CTRL2_BIT_LENGTH_OFFSET 0xCu +#define CTRL2_BIT_LENGTH_MASK 0x01u +#define CTRL2_BIT_LENGTH_SHIFT 0u + +/* + * Parity enable. + */ +#define CTRL2_PARITY_EN_OFFSET 0xCu +#define CTRL2_PARITY_EN_MASK 0x02u +#define CTRL2_PARITY_EN_SHIFT 1u + +/* + * Odd/even parity selection. + */ +#define CTRL2_ODD_EVEN_OFFSET 0xCu +#define CTRL2_ODD_EVEN_MASK 0x04u +#define CTRL2_ODD_EVEN_SHIFT 2u + +/* + * Baud value (Higher 5-bits) + */ +#define CTRL2_BAUDVALUE_OFFSET 0xCu +#define CTRL2_BAUDVALUE_MASK 0xF8u +#define CTRL2_BAUDVALUE_SHIFT 3u + +/*------------------------------------------------------------------------------ + * StatusReg register details + */ +#define StatusReg_REG_OFFSET 0x10u + +#define STATUS_REG_OFFSET 0x10u + +/* + * Transmit ready. + */ +#define STATUS_TXRDY_OFFSET 0x10u +#define STATUS_TXRDY_MASK 0x01u +#define STATUS_TXRDY_SHIFT 0u + +/* + * Receive full. + */ +#define STATUS_RXFULL_OFFSET 0x10u +#define STATUS_RXFULL_MASK 0x02u +#define STATUS_RXFULL_SHIFT 1u + +/* + * Parity error. + */ +#define STATUS_PARITYERR_OFFSET 0x10u +#define STATUS_PARITYERR_MASK 0x04u +#define STATUS_PARITYERR_SHIFT 2u + +/* + * Overflow. + */ +#define STATUS_OVERFLOW_OFFSET 0x10u +#define STATUS_OVERFLOW_MASK 0x08u +#define STATUS_OVERFLOW_SHIFT 3u + +/* + * Frame Error. + */ +#define STATUS_FRAMERR_OFFSET 0x10u +#define STATUS_FRAMERR_MASK 0x10u +#define STATUS_FRAMERR_SHIFT 4u + +#ifdef __cplusplus +} +#endif + +#endif /* __CORE_UART_APB_REGISTERS */ diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_i2c/miv_i2c.c b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_i2c/miv_i2c.c new file mode 100644 index 0000000..a2f4911 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_i2c/miv_i2c.c @@ -0,0 +1,765 @@ +/******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * Mi-V I2C Soft IP bare-metal driver. This module is delivered as part of + * Extended Sub System(ESS) MIV_ESS. + * Please refer to miv_i2c.h file for more information. + */ + +#include "miv_i2c.h" + +#define MIV_I2C_ERROR 0xFFu + +/*------------------------------------------------------------------------------ + * MIV I2C transaction direction. + */ +#define MIV_I2C_WRITE_DIR 0u +#define MIV_I2C_READ_DIR 1u + +/* -- TRANSACTIONS TYPES -- */ +#define MIV_I2C_NO_TRANSACTION 0u +#define MIV_I2C_MASTER_WRITE_TRANSACTION 1u +#define MIV_I2C_MASTER_READ_TRANSACTION 2u +#define MIV_I2C_MASTER_SEQUENTIAL_READ_TRANSACTION 3u + +/*------------------------------------------------------------------------------ + * MIV I2C HW states + */ +#define MIV_I2C_IDLE 0x00u +#define MIV_I2C_TX_STA_CB 0x01u +#define MIV_I2C_TX_DATA 0x02u +#define MIV_I2C_RX_DATA 0x03u + +/*-------------------------------------------------------------------------*//** + The MIV_I2C_disable_irq() disables the Mi-V I2C interrupt. + */ +void +MIV_I2C_disable_irq +( + void +); + +/*-------------------------------------------------------------------------*//** + The MIV_I2C_enable_irq() enables the Mi-V I2C interrupt. + */ +void +MIV_I2C_enable_irq +( + void +); + +/* + * Please refer to miv_i2c.h for more info + */ +void +MIV_I2C_init +( + miv_i2c_instance_t *this_i2c, + addr_t base_addr +) +{ + /* Assign the base address + * Clock Prescale value set + * MIV_I2C interrupt enabled + * I2C core enable + */ + psr_t processor_state; + + /* Disabling the interrupts */ + processor_state = HAL_disable_interrupts(); + + /* + * Initialize all items of the this_miv_i2c data structure to zero. This + * initializes all state variables to their init value. It relies on + * the fact that NO_TRANSACTION, MIV_I2C_SUCCESS and I2C_RELEASE_BUS all + * have an actual value of zero. + */ + memset(this_i2c, 0, sizeof(miv_i2c_instance_t)); + + this_i2c->base_addr = base_addr; + + HAL_restore_interrupts(processor_state); +} + +/* + * Please refer to miv_i2c.h for more info + */ +void +MIV_I2C_config +( + miv_i2c_instance_t *this_i2c, + uint16_t clk_prescale +) +{ + /* Assign the base address + * Clock Prescale value set + * MIV_I2C interrupt enabled + * I2C core enable + */ + psr_t processor_state; + + /* Disabling the interrupts */ + processor_state = HAL_disable_interrupts(); + + /* Before writing to prescale reg, the core enable must be zero */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CTRL_CORE_EN, 0x00u); + + /* Set the prescale value */ + HAL_set_16bit_reg(this_i2c->base_addr, PRESCALE, clk_prescale); + + /* Enable the MIV I2C interrupts */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CTRL_IRQ_EN, 0x01u); + + /* Enable the MIV I2C core */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CTRL_CORE_EN, 0x01u); + + this_i2c->master_state = MIV_I2C_IDLE; + + HAL_restore_interrupts(processor_state); +} + +/* + * Please refer to miv_i2c.h for more info + */ +uint8_t +MIV_I2C_start +( + miv_i2c_instance_t *this_i2c +) +{ + psr_t processor_state; + + processor_state = HAL_disable_interrupts(); + + /* Generate I2C start condition */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_STA, 0x01u); + + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_WR, 0x01); + + HAL_restore_interrupts(processor_state); + + return 0u; +} + +/* + * Please refer to miv_i2c.h for more info + */ +uint8_t +MIV_I2C_stop +( + miv_i2c_instance_t *this_i2c +) +{ + psr_t processor_state; + + processor_state = HAL_disable_interrupts(); + + /* Generate I2C stop condition */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_STO, 0x01u); + + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_WR, 0x01); + + HAL_restore_interrupts(processor_state); + + return 0u; +} + +/* + * Please refer to miv_i2c.h for more info + */ +void +MIV_I2C_write +( + miv_i2c_instance_t *this_i2c, + uint8_t i2c_target_addr, + const uint8_t *write_buffer, + uint16_t write_size, + uint8_t bus_options, + uint8_t ack_polling_options +) +{ + psr_t processor_state; + + processor_state = HAL_disable_interrupts(); + + /* I2C write flow + * + * Check I2C status for ongoing transaction + * Populate the structure with input data + * Generate start condition + * Set the write_direction and target address. + */ + + /* Update the transaction only when there is no ongoing I2C transaction */ + if (this_i2c->transaction == MIV_I2C_NO_TRANSACTION) + { + this_i2c->transaction = MIV_I2C_MASTER_WRITE_TRANSACTION; + } + + /* Update the Pending transaction information so that transaction can restarted */ + this_i2c->pending_transaction = MIV_I2C_MASTER_WRITE_TRANSACTION ; + + /* Populate the i2c instance structure */ + + /* Set the target addr */ + this_i2c->target_addr = i2c_target_addr; + this_i2c->dir = MIV_I2C_WRITE_DIR; + + /* Set up the tx buffer */ + this_i2c->master_tx_buffer = write_buffer; + this_i2c->master_tx_size = write_size; + this_i2c->master_tx_idx = 0u; + + /* Set the I2C status in progress and setup the options */ + this_i2c->bus_options = bus_options; + this_i2c->ack_polling_options = ack_polling_options; + this_i2c->master_status = MIV_I2C_IN_PROGRESS; + + + /* Generate I2C start condition */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_STA, 0x01u); + + /* write target address and write bit */ + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_DIR, MIV_I2C_WRITE_DIR); + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_TARGET_ADDR, i2c_target_addr); + + /* Set WR bit to transmit start condition and control byte */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_WR, 0x01); + + /* Set current master hw state -> transmitted start condition and + * control byte + */ + this_i2c->master_state = MIV_I2C_TX_STA_CB; + + /* + * Clear interrupts if required (depends on repeated starts). + * Since the Bus is on hold, only then prior status needs to + * be cleared. + */ + if ( MIV_I2C_HOLD_BUS == this_i2c->bus_status ) + { + /* Must toggle IACK bit to clear the MIV_I2C IRQ*/ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_IACK, 0x01); + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_IACK, 0x00); + } + + MIV_I2C_enable_irq(); + + HAL_restore_interrupts(processor_state); + +} + +/* + * Please refer to miv_i2c.h for more info + */ +void +MIV_I2C_read +( + miv_i2c_instance_t *this_i2c, + uint8_t i2c_target_addr, + uint8_t *read_buffer, + uint16_t read_size, + uint8_t bus_options, + uint8_t ack_polling_options +) +{ + psr_t processor_state; + uint8_t status = MIV_I2C_SUCCESS; + + processor_state = HAL_disable_interrupts(); + + /* MIV I2C Read operation flow + * + * Check for ongoing transaction + * Populate the i2c instance structure + * Generate the start condition + * Set the READ_direction bit and target addr + */ + + uint8_t read_stat = HAL_get_8bit_reg_field(this_i2c->base_addr, STAT_TIP); + + /* Update the transaction only when there is no ongoing I2C transaction */ + if (this_i2c->transaction == MIV_I2C_NO_TRANSACTION) + { + this_i2c->transaction = MIV_I2C_MASTER_READ_TRANSACTION; + } + + this_i2c->pending_transaction = MIV_I2C_MASTER_READ_TRANSACTION; + + /* Populate the MIV I2C instance structure */ + + this_i2c->target_addr = i2c_target_addr; + this_i2c->dir = MIV_I2C_READ_DIR; + + /* Populate read buffer */ + this_i2c->master_rx_buffer = read_buffer; + this_i2c->master_rx_size = read_size; + this_i2c->master_rx_idx = 0u; + + /* Set the BUS and ACK polling options */ + this_i2c->bus_options = bus_options; + this_i2c->ack_polling_options = ack_polling_options; + + /* Generate the start condition */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_STA, 0x01u); + + /* Set the DIR bit and target addr */ + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_DIR, MIV_I2C_READ_DIR); + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_TARGET_ADDR, i2c_target_addr); + + /* Set the WR bit to transmit the start condition and command byte */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_WR, 0x01u); + + /* Set the i2c master state and status transmitting STA and Command Byte */ + this_i2c->master_state = MIV_I2C_TX_STA_CB; + this_i2c->master_status = MIV_I2C_IN_PROGRESS; + + /* Toggle the IACK bit if required */ + /* + * Clear interrupts if required (depends on repeated starts). + * Since the Bus is on hold, only then prior status needs to + * be cleared. + */ + if ( MIV_I2C_HOLD_BUS == this_i2c->bus_status ) + { + /* Must toggle IACK bit to clear the MIV_I2C IRQ*/ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_IACK, 0x01); + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_IACK, 0x00); + } + /* Enable the I2C interrupt */ + MIV_I2C_enable_irq(); + + HAL_restore_interrupts(processor_state); +} + +/* + * Please refer to miv_i2c.h for more info + */ +void +MIV_I2C_write_read +( + miv_i2c_instance_t *this_i2c, + uint8_t target_addr, + const uint8_t *write_buffer, + uint16_t write_size, + uint8_t *read_buffer, + uint16_t read_size, + uint8_t bus_options, + uint8_t ack_polling_options +) +{ + uint8_t status = MIV_I2C_SUCCESS; + psr_t processor_state; + + processor_state = HAL_disable_interrupts(); + + uint8_t read_stat = HAL_get_8bit_reg_field(this_i2c->base_addr, STAT_TIP); + + /* I2C write read operation flow + * + * Used to read the data from set address offset + * + * Configure the i2c instance structure + * generate the start and configure the dir and target addr + * set wr bit to transmit the start and command byte + * + */ + + /* Update the transaction only when there is no ongoing I2C transaction */ + if (this_i2c->transaction == MIV_I2C_NO_TRANSACTION) + { + this_i2c->transaction = MIV_I2C_MASTER_READ_TRANSACTION; + } + + this_i2c->pending_transaction = MIV_I2C_MASTER_READ_TRANSACTION; + + /* Populate the I2C instance */ + + this_i2c->target_addr = target_addr; + + /* setup the i2c direction */ + this_i2c->dir = MIV_I2C_WRITE_DIR; + + /* set up transmit buffer */ + this_i2c->master_tx_buffer = write_buffer; + this_i2c->master_tx_size = write_size; + this_i2c->master_tx_idx = 0u; + + /* set up receive buffer */ + this_i2c->master_rx_buffer = read_buffer; + this_i2c->master_rx_size = read_size; + this_i2c->master_rx_idx = 0u; + + /* Set the bus and ack polling options */ + this_i2c->bus_options = bus_options; + this_i2c->ack_polling_options = ack_polling_options; + + /* Generate the start command */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_STA, 0x01u); + + /* Set the DIR and target addr */ + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_TARGET_ADDR, target_addr); + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_DIR, this_i2c->dir); + + /* Set the WR bit to transmit the start command and command byte */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_WR, 0x01); + + /* Set the i2c master state and status transmitting STA and Command Byte */ + this_i2c->master_state = MIV_I2C_TX_STA_CB; + this_i2c->master_status = MIV_I2C_IN_PROGRESS; + + /* + * Clear interrupt if required + */ + if ( MIV_I2C_HOLD_BUS == this_i2c->bus_status ) + { + /* Must toggle IACK bit to clear the MIV_I2C IRQ*/ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_IACK, 0x01u); + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_IACK, 0x00u); + } + + /* Enable the I2C interrupt */ + MIV_I2C_enable_irq(); + + HAL_restore_interrupts(processor_state); +} + +/* MIV_I2C_isr() + * Please refer to miv_i2c.h for more info + */ +void +MIV_I2C_isr +( + miv_i2c_instance_t *this_i2c +) +{ + uint8_t i2c_state; + uint8_t i2c_ack_status; + uint8_t i2c_al_status; + uint8_t hold_bus; + + /* Read the I2C master state */ + i2c_state = this_i2c->master_state; + + /* Read the ack and al status */ + i2c_ack_status = HAL_get_8bit_reg_field(this_i2c->base_addr, STAT_RXACK); + i2c_al_status = HAL_get_8bit_reg_field(this_i2c->base_addr, STAT_AL); + + switch (i2c_state) + { + /* I2C ISR State Machine + * + * Cases: + * - Transmit start condition and control byte + * - Received ACK and bus arbitration was not lost (Read or Write) + * - Received NACK + * - Bus arbitration lost + * + * - Transmit data + * - Received ACK and bus arbitration was not lost (Read or Write) + * - Received NACK + * - Bus arbitration lost + * + * - Receive data + * - Received ACK and bus arbitration was not lost (Read or Write) + * - Bus arbitration lost + */ + + case MIV_I2C_TX_STA_CB: + + /* Received ACK from target and I2C bus arbitration is not lost */ + if (i2c_ack_status == 0u && i2c_al_status == 0u) + { + /* If I2C master write operation */ + if (this_i2c->dir == MIV_I2C_WRITE_DIR) + { + /* write first byte of data and set the WR bit to transfer the data */ + HAL_set_8bit_reg(this_i2c->base_addr, TRANSMIT, + this_i2c->master_tx_buffer[this_i2c->master_tx_idx]); + + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_WR, 0x01u); + + /* Increment the index */ + this_i2c->master_tx_idx++; + + /* Set the master state to TX data */ + this_i2c->master_state = MIV_I2C_TX_DATA; + } + /* Master read operation */ + else + { + if (this_i2c->master_rx_size == 1u) + { + /* Send the ACK if the rx size is 1, transmit NACK to slave + * after receiving 1 byte to indicate slave to stop sending + * the data + */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_ACK, 0x01u); + } + + /* Send the RD command to slave */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_RD, 0x01u); + + /* Increment the index */ + this_i2c->master_rx_idx++; + + /* Change state to receive data */ + this_i2c->master_state = MIV_I2C_RX_DATA; + } + } + else if (i2c_ack_status == 1u) + { + if (this_i2c->ack_polling_options == MIV_I2C_ACK_POLLING_ENABLE) + { + /* Target responded with NACK and ACK polling option is enabled + * + * Re-send the start condition and control byte + * + * TO-DO: This might become infinite loop check for timeout + * options. + */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_STA, 0x01u); + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_TARGET_ADDR, this_i2c->target_addr); + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_DIR, this_i2c->dir); + + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_WR, 0x01u); + + this_i2c->master_tx_idx = 0u; + this_i2c->master_state = MIV_I2C_TX_STA_CB; + } + + else + { + /* Target responded with NACK and ACK polling is disabled + * Abort the transaction and move to IDLE state + */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_STO, 0x01u); + + this_i2c->master_status = MIV_I2C_FAILED; + this_i2c->transaction = MIV_I2C_NO_TRANSACTION; + + this_i2c->master_state = MIV_I2C_IDLE; + } + } + + else if (i2c_al_status == 1u) + { + /* Arbitration was lost on the BUS during the transmission of + * previous start condition and control byte. + * Re-send the STA and CB + */ + + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_STA, 0x01u); + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_TARGET_ADDR, this_i2c->target_addr); + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_DIR, this_i2c->dir); + + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_WR, 0x01u); + + this_i2c->master_state = MIV_I2C_TX_STA_CB; + } + + break; + + /* Transmit master data */ + case MIV_I2C_TX_DATA: + + /* ACK received and arbitration was not lost */ + if (i2c_ack_status == 0u && i2c_al_status == 0u) + { + uint8_t tx_buff[this_i2c->master_tx_size]; + if (this_i2c->master_tx_idx < this_i2c->master_tx_size) + { + HAL_set_8bit_reg(this_i2c->base_addr, TRANSMIT, + this_i2c->master_tx_buffer[this_i2c->master_tx_idx]); + + tx_buff[this_i2c->master_tx_idx] = this_i2c->master_tx_buffer[this_i2c->master_tx_idx]; + + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_WR, 0x01u); + + /* Increment the index */ + this_i2c->master_tx_idx++; + + /* Set the master state to TX data */ + this_i2c->master_state = MIV_I2C_TX_DATA; + } + + /* All the bytes are transmitted */ + else if (this_i2c->master_tx_idx == this_i2c->master_tx_size) + { + /* If this is a MASTER_READ_TRANSACTION, hold bus and start a + new transfer in read mode now that the read address has been + written to the slave */ + if(this_i2c->transaction == MIV_I2C_MASTER_READ_TRANSACTION) + + { + //Switch direction to READ + this_i2c->dir = MIV_I2C_READ_DIR; + + // Set the STA bit + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_STA, 0x01u); + + /* Set the DIR bit and target addr */ + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_DIR, MIV_I2C_READ_DIR); + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_TARGET_ADDR, this_i2c->target_addr); + + /* Set the WR bit to transmit the start condition and command byte */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_WR, 0x01u); + + // Reset the buffer index + this_i2c->master_tx_idx = 0u; + this_i2c->master_rx_idx = 0u; + + /* Set the master state to RX data */ + this_i2c->master_state = MIV_I2C_RX_DATA; + } + + else + { + /* If releasing the bus, transmit the stop condition at the end + * of the transfer. + */ + hold_bus = this_i2c->bus_status & MIV_I2C_HOLD_BUS; + + if (hold_bus == 0) + { + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_STO, 0x01u); + } + else + { + MIV_I2C_disable_irq(); + } + this_i2c->master_status = MIV_I2C_SUCCESS; + this_i2c->transaction = MIV_I2C_NO_TRANSACTION; + this_i2c->master_state = MIV_I2C_IDLE; + } + } + } + + else if (i2c_ack_status == 1u) + { + /* Received NACK from target device + * + * Release the bus and end the transfer + */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_STO, 0x01u); + + this_i2c->master_status = MIV_I2C_FAILED; + this_i2c->transaction = MIV_I2C_NO_TRANSACTION; + + this_i2c->master_state = MIV_I2C_IDLE; + } + + else if (i2c_al_status == 1u) + { + /* Arbitration was lost on the BUS during the transmission of + * previous start condition and control byte. + * Re-send the STA and CB + */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_STA, 0x01u); + + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_TARGET_ADDR, + this_i2c->target_addr); + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_DIR, this_i2c->dir); + + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_WR, 0x01); + + this_i2c->master_state = MIV_I2C_TX_STA_CB; + } + + break; + + /* Receive target device data */ + case MIV_I2C_RX_DATA: + + if (i2c_al_status == 0u) + { + if (this_i2c->master_rx_idx < this_i2c->master_rx_size) + { + this_i2c->master_rx_buffer[this_i2c->master_rx_idx - 1u] = + HAL_get_8bit_reg(this_i2c->base_addr, RECEIVE); + + /* If next byte is last one + * Send NACK to target device to stop sending data + */ + if (this_i2c->master_rx_idx == (this_i2c->master_rx_size - 1u)) + { + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_ACK, 0x01u); + } + + else + { + /* Send ACK to receive next bytes */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_ACK, 0x00u); + } + + /* Set RD bit to receive next byte */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_RD, 0x01u); + + this_i2c->master_rx_idx++; + } + + /* Received all bytes */ + else //if (this_i2c->master_rx_idx == this_i2c->master_rx_size) + { + this_i2c->master_rx_buffer[this_i2c->master_rx_idx - 1] = + HAL_get_8bit_reg(this_i2c->base_addr, RECEIVE); + + hold_bus = this_i2c->bus_status & MIV_I2C_HOLD_BUS; + + if (hold_bus == 0) + { + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_STO, 0x01u); + } + else + { + MIV_I2C_disable_irq(); + } + this_i2c->master_status = MIV_I2C_SUCCESS; + this_i2c->transaction = MIV_I2C_NO_TRANSACTION; + + this_i2c->master_state = MIV_I2C_IDLE; + } + } + + else if (i2c_al_status == 1u) + { + /* Arbitration was lost on the BUS during the transmission of + * previous start condition and control byte. + * Re-send the STA and CB + */ + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_TARGET_ADDR, + this_i2c->target_addr); + HAL_set_8bit_reg_field(this_i2c->base_addr, TX_DIR, this_i2c->dir); + + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_STA, 0x01u); + + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_WR, 0x01); + + this_i2c->master_state = MIV_I2C_TX_STA_CB; + } + + break; + } + + /* Toggle the IACK bit to clear interrupt */ + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_IACK, 0x01u); + HAL_set_8bit_reg_field(this_i2c->base_addr, CMD_IACK, 0x00u); +} + +/* + * Please refer to miv_i2c.h for more info + */ +uint8_t +MIV_I2C_get_status +( + miv_i2c_instance_t *this_i2c +) +{ + uint8_t i2c_status; + + i2c_status = HAL_get_8bit_reg(this_i2c->base_addr, STATUS); + + return i2c_status; +} diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_i2c/miv_i2c.h b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_i2c/miv_i2c.h new file mode 100644 index 0000000..c5e704d --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_i2c/miv_i2c.h @@ -0,0 +1,854 @@ +/******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * This file contains the application programming interface for the MI-V Soft IP + * I2C module driver. This module is delivered as a part of Mi-V Extended + * Sub-System(MIV_ESS). + */ + +/*=========================================================================*//** + @mainpage Mi-V I2C Bare Metal Driver + + ============================================================================== + Introduction + ============================================================================== + The Mi-V I2C driver provides a set of functions for controlling the Mi-V I2C + Soft-IP module. This module is delivered as a part of the Mi-V Extended + Sub System(MIV_ESS). The driver provides a minimal APB-driven I2C interface, + supporting initiator read and write access to peripheral I2C devices. + + The major features provided by the Mi-V I2C driver are: + - Support for configuring the I2C instance. + - I2C master operations. + - I2C ISR. + + This driver can be used as part of a bare metal system where no operating + system is available. The driver can be adapted for use as part of an + operating system, but the implementation of the adaptation layer between the + driver and the operating system's driver model is outside the scope of this + driver. + + ============================================================================== + Hardware Flow Dependencies + ============================================================================== + The application software should initialize and configure the Mi-V I2C through + the call to the MIV_I2C_init() and MIV_I2C_config() function for Mi-V I2C + instance in the design. The configuration parameter include base address and + Prescaler value. + + ------------------------------ + Interrupt Control + ------------------------------ + The Mi-V I2C driver has to enable and disable the generation of interrupts by + Mi-V I2C at various times while operating. This enabling and disabling of the + interrupts must be done through the Mi-V RV32 HAL provided interrupt handlers. + For that reason, the method controlling the Mi-V I2C interrupts is system + specific and it is necessary to customize the MIV_I2C_enable_irq() and + MIV_I2C_disable_irq() functions as per requirement. + + The implementation of MIV_I2C_enable_irq() should permit the interrupts + generated by the Mi-V I2C to the processor through a call to respective miv-hal + interrupt handler. The implementation of MIV_I2C_disable_irq() should prevent + the interrupts generated by a Mi-V I2C from interrupting the processor. + Please refer to the miv_i2c_interrupt.c for more information about the + implementation. + + No MIV_I2C hardware configuration parameters are used by the driver, apart + from the MIV_I2C base address. Hence, no additional configuration files + are required to use the driver. + + ============================================================================== + Theory of Operation + ============================================================================== + The Mi-V I2C software driver is designed to allow the control of multiple + instances of Mi-V I2C. Each instance of Mi-V I2C in the hardware design is + associated with a single instance of the miv_i2c_instance_t structure in the + software. User must allocate memory for one unique miv_i2c_instance_t + structure for each instance of Mi-V I2C in the hardware. + A pointer to the structure is passed to the subsequent driver functions in + order to identify the MIV_I2C hardware instance and to perform requested + operation. + + Note: Do not attempt to directly manipulate the contents of the + miv_i2c_instance_t structure. These structures are only intended to be modified + by the driver functions. + + The Mi-V I2C driver functions are grouped into following categories: + - Initialization and configuration + - I2C master operation functions to handle write, read and write_read + operations. + - Interrupt control + + -------------------------------- + Initialization and configuration + -------------------------------- + The Mi-V I2C device is first initialized by the call to MIV_I2C_init(). This + function initializes the instance of Mi-V I2C with the base address. + MIV_I2C_init() function must be called before any other Mi-V I2C driver API. + + The configuration of the Mi-V I2C instance is done via call to the + MIV_I2C_config() function. This function will set the prescale value which is + used to set the frequency of the I2C clock(SCLK) generated by I2C module. + + --------------------------------- + Transaction types + --------------------------------- + The driver is designed to handle three types of transactions: + - Write transactions + - Read transactions + - Write-Read transaction + + ### Write Transaction + The write transaction begins with master sending a start condition, followed + by device address byte with the R/W bit set to logic '0', and then by the + word address bytes. The slave acknowledges the receipt of its address with + acknowledge bit. The master sends one byte at a time to the slave, which must + acknowledge the receipt of each byte for the next byte to be sent. The master + sends STOP condition to complete the transaction. The slave can abort the + transaction by replying with negative acknowledge. + + The application programmer can choose not to send the STOP bit at the end of + the transaction causing repetitive start conditions. + + ### Read Transaction + The master I2C device initiates a read transaction by sending a START bit + as soon as the bus becomes free. The start condition is followed by the + control byte which contains 7-bit slave address followed by R/W bit set to + logic '1'. The slave sends data one byte at a time to the master, which must + acknowledge receipt of each byte for the next byte to be sent. The master + sends a non-acknowledge bit following the last byte it wishes to read + followed by a STOP bit. + + The application programmer can choose not to send a STOP bit at the end of + the transaction causing the next transaction to begin with a repeated + START bit. + + ### Write-Read Transaction + The write read transaction is a combination of a write transaction + immediately followed by a read transaction. There is no STOP condition sent + between the write and read phase of write-read transaction. A repeated START + condition is sent between the write and read phases. + + Whilst the write handler is being executed, the slave holds the clock line + low to stretch the clock until the response is ready. + + The write-read transaction is typically used to send an memory/register + address in the write transaction specifying the start address of the data to + be transferred during the read phase. + + The application programmer can choose not to send a STOP bit at the end of + the transaction causing the next transaction to begin with a repeated + START bit. + + ------------------------------------- + Interrupt Control + ------------------------------------- + The Mi-V I2C driver is interrupt driven and it uses the MIV_I2C_irq() function + to drive the ISR state machine which is at the heart of the driver. The + application is responsible for providing the link between the interrupt + generating hardware and the Mi-V I2C interrupt handler and must ensure that + the MIV_I2C_isr() function is called with the correct miv_i2c_instance_t + structure pointer for the Mi-V I2C instance initiating the interrupt. + +*//*=========================================================================*/ +#ifndef MIV_I2C_H_ +#define MIV_I2C_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "miv_i2c_regs.h" +#include + +#ifndef LEGACY_DIR_STRUCTURE +#include "hal/hal.h" +#else +#include "hal.h" +#endif + +/*-------------------------------------------------------------------------*//** + The miv_i2c_status_t type is used to report the status of I2C transactions. + */ +typedef enum miv_i2c_status +{ + MIV_I2C_SUCCESS = 0u, + MIV_I2C_IN_PROGRESS, + MIV_I2C_FAILED, + MIV_I2C_TIMED_OUT +}miv_i2c_status_t; + +/*-------------------------------------------------------------------------*//** + This structure is used to identify the MIV_I2C hardware instances in a system. + Your application software should declare one instance of this structure for + each instance of the MIV_I2C in your system. The function MIV_I2C_init() + Initializes this structure. A pointer to an initialised instance of the structure + should be passed as the first parameter to the MIV_I2C driver functions, to + identify which MIV_I2C hardware instance should perform the requested operation. + + The contents of this data structure should not be modified or used outside of + the MIV_I2C driver. Software using the MIV_I2C driver should only need to + create one single instance of this data structure for each MIV_I2C hardware + instance in the system, then pass a pointer to these data structures with each + call to the MIV_I2C driver in order to identify the MIV_I2C hardware instance + it wishes to use. +*/ + +typedef struct miv_i2c_instance +{ + addr_t base_addr; + + /* Transmit related info:*/ + uint_fast8_t target_addr; + + /* Current transaction type */ + uint8_t transaction; + + uint8_t bus_options; + + uint8_t ack_polling_options; + + /* Current State of the I2C master */ + uint8_t master_state; + + /* Master TX INFO: */ + const uint8_t * master_tx_buffer; + uint_fast16_t master_tx_size; + uint_fast16_t master_tx_idx; + uint_fast8_t dir; + + /* Master RX INFO: */ + uint8_t * master_rx_buffer; + uint_fast16_t master_rx_size; + uint_fast16_t master_rx_idx; + + /* Master Status */ + volatile miv_i2c_status_t master_status; + uint32_t master_timeout_ms; + + /* user specific data */ + void *p_user_data ; + + /* I2C bus status */ + uint8_t bus_status; + + /* Is transaction pending flag */ + uint8_t is_transaction_pending; + + /* I2C Pending transaction */ + uint8_t pending_transaction; + +}miv_i2c_instance_t; + + +/*-------------------------------------------------------------------------*//** + MIV_I2C_RELEASE_BUS + ===================== + The MIV_I2C_RELEASE_BUS constant is used to specify the bus_options parameter + for MIV_I2C_read(), MIV_I2C_write() and MIV_I2C_write_read() to indicate + that a STOP bit must be generated at the end of the I2C transaction to release + the bus. + */ +#define MIV_I2C_RELEASE_BUS 0x00u + + +/*-------------------------------------------------------------------------*//** + MIV_I2C_HOLD_BUS + ===================== + The MIV_I2C_HOLD_BUS constant is used to specify the bus_optionsparameter + for MIV_I2C_read(), MIV_I2C_write() and MIV_I2C_write_read() to indicate + that a STOP bit must not be generated at the end of the I2C transaction in + order to retain the bus ownership. This causes the next transaction to + begin with a repeated START bit and no STOP bit between the transactions. + */ +#define MIV_I2C_HOLD_BUS 0x01u + +/*-------------------------------------------------------------------------*//** + MIV_I2C_ACK_POLLING_DISABLE + ===================== + The MIV_I2C_ACK_POLLING_DISABLE constant is used to specify the + ack_polling_options parameter to functions MIV_I2C_write(), + MIV_I2C_write_read() and MIV_I2C_read(). Acknowledgment polling is used when + working with I2C memory devices such as EEPROM, which feature an internal + write cycle. + + With acknowledgment polling disabled, if the target slave device responds to the + control byte with a NACK, the MIV_I2C will abort the transfer. + */ +#define MIV_I2C_ACK_POLLING_DISABLE 0x00u + +/*-------------------------------------------------------------------------*//** + MIV_I2C_ACK_POLLING_ENABLE + ===================== + The MIV_I2C_ACK_POLLING_ENABLE constant is used to specify the + ack_polling_options parameter to functions MIV_I2C_write(), + MIV_I2C_write_read() and MIV_I2C_read(). acknowledgment polling is used when + working with I2C memory devices such as EEPROM, which feature an internal + write cycle. + + With acknowledgment polling enabled, if the slave device responds to the + control byte with a NACK, the MIV_I2C will repeatedly transmit another control + byte until the slave device accepts the connection with an ACK, or the timeout + specified in the MIV_I2C_wait_complete() function is reached. Acknowledgment + polling allows for the next read/write operation to be started as soon as the + EEPROM has completed its internal write cycle. + */ +#define MIV_I2C_ACK_POLLING_ENABLE 0x01u + +/*--------------------------------Public APIs---------------------------------*/ + +/*-------------------------------------------------------------------------*//** + The MIV_I2C_init() function is used to initialize the Mi-V I2C module instance + with the base address. + + Note: This function should be called before calling any other Mi-V I2C + functions. + + @param this_i2c + A pointer to the miv_i2c_instance_t data structure which + will hold all the data related to the Mi-V I2C module + instance being used. A pointer to this structure is passed to + rest of the Mi-V I2C driver functions for operation. + @param base_addr + Base address of the Mi-V I2C module instance in the MIV_ESS + soft IP. + + @return + This function does not return any value. + + Example: + @code + #define MIV_I2C_BASE_ADDR 0x7A000000u + + miv_i2c_instance_t g_miv_i2c_inst; + + void main( void ) + { + MIV_I2C_init( &g_miv_i2c_inst, MIV_I2C_BASE_ADDR); + } + @endcode + */ +void +MIV_I2C_init +( + miv_i2c_instance_t *this_i2c, + addr_t base_addr +); + +/*-------------------------------------------------------------------------*//** + The MIV_I2C_config() function is used to configure the Mi-V I2C module. This + function will set the prescale value which is used to set the frequency of + the I2C clock(SCLK) generated by I2C module and also enables the I2C core and + interrupts. + + @param this_i2c + A pointer to the miv_i2c_instance_t data structure which + will hold all the data related to the Mi-V I2C module + instance being used. A pointer to this structure is passed to + rest of the Mi-V I2C driver functions for operation. + + @param clk_prescale + The value used to set the frequency of Mi-V I2C serial clock + (SCLK) generated by the Mi-V I2C module instance. The + prescaler value required to set particular frequency of + Mi-V I2C can be calculated using following formula: + + prescaler = (System Clock Frequency) / (5 * (Desired I2C Clock Frequency)) - 1 + + @return + This function does not return any value. + + + Example: + @code + #define MIV_I2C_BASE_ADDR 0x7A000000u + + miv_i2c_instance_t g_miv_i2c_inst; + + void main( void ) + { + MIV_I2C_init( &g_miv_i2c_inst, MIV_I2C_BASE_ADDR); + + Configuring Mi-V I2C core at Normal Speed (100MHz) for 50MHz Sys clock. + MIV_I2C_config(&g_miv_i2c_inst, 0x63); + } + @endcode + */ +void +MIV_I2C_config +( + miv_i2c_instance_t *this_i2c, + uint16_t clk_prescale +); + + +uint8_t +MIV_I2C_start +( + miv_i2c_instance_t *this_i2c +); + + +uint8_t +MIV_I2C_stop +( + miv_i2c_instance_t *this_i2c +); + +/*-------------------------------------------------------------------------*//** + The MIV_I2C_write() is used to set up and start the Mi-V I2C master write + transaction. This function is used for all Mi-V master write operation. + + For more information about the operation, please refer to the 'theory of + operations' section at the start of this document. + + This function returns immediately after initiating the transaction. The content + of the write buffer passed as parameter should not be modified until the write + transaction completes. It also means that the memory allocated for the write + buffer should not be freed or should not go out of scope before the write + completes. + You can check for the write transaction completion by polling the master_status + from miv_i2c_instance_t structure as shown in the sample code. + + @param this_i2c + A pointer to the miv_i2c_instance_t data structure which + will hold all the data related to the Mi-V I2C module + instance being used. A pointer to this structure is passed to + rest of the Mi-V I2C driver functions for operation. + + @param i2c_target_addr + This parameter specifies the serial address for the slave + device. + + @param write_buffer + This parameter is a pointer to the buffer holding data to be + written to target I2C device. + Care must be taken not to release the memory used by this + buffer before the write transaction completes. + + @param write_size + Number of bytes held in the write_buffer to be written to the + I2C device. + @param bus_options: + The bus_options parameter is used to indicate if the I2C bus + should be released on completion of the write transaction. + Using the MIV_I2C_RELEASE_BUS constant for the bus_options + parameter causes a STOP bit to be generated at the end of the + write transaction causing the bus to be released for other I2C + devices to use. Using the MIV_I2C_HOLD_BUS constant as + bus_options parameter prevents a STOP bit from being generated + at the end of the write transaction, preventing other I2C + devices from initiating a bus transaction. + + @param ack_polling_options: + The ack_polling_options parameter is used to indicate how the + MIV_I2C will respond if the slave device transmits a NACK to + the I2C control byte. Using the MIV_I2C_ACK_POLLING_DISABLE + constant for the ack_polling_options parameter causes the + MIV_I2C to abort the transfer if the slave device responds to + the I2C control byte with a NACK. Using the + MIV_I2C_ACK_POLLING_ENABLE constant for the ack_polling_options + parameter causes the MIV_I2C to repeatedly transmit a control + byte to the slave device until the slave device responds with + an ACK. + @return + This function does not return any value. + + + Example: + @code + #define MIV_I2C_BASE_ADDR 0x7A000000u + + miv_i2c_instance_t g_miv_i2c_inst; + + void main( void ) + { + MIV_I2C_init( &g_miv_i2c_inst, MIV_I2C_BASE_ADDR); + + Configuring Mi-V I2C core at Normal Speed (100MHz) for 50MHz Sys clock. + MIV_I2C_config(&g_miv_i2c_inst, 0x63); + + MIV_I2C_write (&g_miv_i2c_inst, + DUALEE_SLAVEADDRESS_1, + i2c_tx_buffer, + transfer_size, + MIV_I2C_RELEASE_BUS, + MIV_I2C_ACK_POLLING_ENABLE + ); + + // Wait till the miv i2c status changes + do { + miv_i2c_status = miv_i2c.master_status; + }while (MIV_I2C_IN_PROGRESS == miv_i2c_status); + } + @endcode + */ +void +MIV_I2C_write +( + miv_i2c_instance_t *this_i2c, + uint8_t i2c_target_addr, + const uint8_t *write_buffer, + uint16_t write_size, + uint8_t bus_options, + uint8_t ack_polling_options +); + +/*-------------------------------------------------------------------------*//** + The MIV_I2C_read() is used to set up and start the Mi-V I2C master read + transaction. This function is used for all MIV_I2C master read operation. + + For more information about the operation, please refer to the 'theory of + operations' section at the start of this document. + + This function returns immediately after initiating the transaction. The content + of the read buffer passed as parameter should not be modified until the write + transaction completes. It also means that the memory allocated for the read + buffer should not be freed or should not go out of scope before the read + completes. + You can check for the write transaction completion by polling the master_status + from miv_i2c_instance_t structure as shown in the sample code. + + @param this_i2c + A pointer to the miv_i2c_instance_t data structure which + will hold all the data related to the Mi-V I2C module + instance being used. A pointer to this structure is passed to + rest of the Mi-V I2C driver functions for operation. + + @param i2c_target_addr + This parameter specifies the serial address for the slave + device. + + @param read_buffer + This parameter is a pointer to the buffer where the data + received from the I2C slave device is stored. + Care must be taken not to release the memory used by this + buffer before the write transaction completes. + + @param read_size + Number of bytes held in the write_buffer to be read from the + I2C device. + + @param bus_options: + The bus_options parameter is used to indicate if the I2C bus + should be released on completion of the write transaction. + Using the MIV_I2C_RELEASE_BUS constant for the bus_options + parameter causes a STOP bit to be generated at the end of the + write transaction causing the bus to be released for other I2C + devices to use. Using the MIV_I2C_HOLD_BUS constant as + bus_options parameter prevents a STOP bit from being generated + at the end of the write transaction, preventing other I2C + devices from initiating a bus transaction. + + @param ack_polling_options: + The ack_polling_options parameter is used to indicate how the + MIV_I2C will respond if the slave device transmits a NACK to + the I2C control byte. Using the MIV_I2C_ACK_POLLING_DISABLE + constant for the ack_polling_options parameter causes the + MIV_I2C to abort the transfer if the slave device responds to + the I2C control byte with a NACK. Using the + MIV_I2C_ACK_POLLING_ENABLE constant for the ack_polling_options + parameter causes the MIV_I2C to repeatedly transmit a control + byte to the slave device until the slave device responds with + an ACK. + @return + This function does not return any value. + + + Example: + @code + #define MIV_I2C_BASE_ADDR 0x7A000000u + + miv_i2c_instance_t g_miv_i2c_inst; + + void main( void ) + { + MIV_I2C_init( &g_miv_i2c_inst, MIV_I2C_BASE_ADDR); + + Configuring Mi-V I2C core at Normal Speed (100MHz) for 50MHz Sys clock. + MIV_I2C_config(&g_miv_i2c_inst, 0x63); + + MIV_I2C_write (&g_miv_i2c_inst, + DUALEE_SLAVEADDRESS_1, + i2c_tx_buffer, + transfer_size, + MIV_I2C_RELEASE_BUS, + MIV_I2C_ACK_POLLING_ENABLE + ); + + // Wait till the miv i2c status changes + do { + miv_i2c_status = miv_i2c.master_status; + }while (MIV_I2C_IN_PROGRESS == miv_i2c_status); + + // reset miv_i2c_status variable + miv_i2c_status = 0u; + + MIV_I2C_read (&g_miv_i2c_inst, + DUALEE_SLAVEADDRESS_1, + i2c_rx_buffer, + transfer_size, + MIV_I2C_RELEASE_BUS, + MIV_I2C_ACK_POLLING_ENABLE + ); + + // Wait till the miv i2c status changes + do { + miv_i2c_status = miv_i2c.master_status; + }while (MIV_I2C_IN_PROGRESS == miv_i2c_status); + } + @endcode + */ +void +MIV_I2C_read +( + miv_i2c_instance_t *this_i2c, + uint8_t i2c_target_addr, + uint8_t *read_buffer, + uint16_t read_size, + uint8_t bus_options, + uint8_t ack_polling_options +); + +/*-------------------------------------------------------------------------*//** + The MIV_I2C_write_read() is used to set up and start the Mi-V I2C master + write_read transaction. This function is used for all MIV_I2C master write_read + operation. + + This function is used in cases where data is being requested from a specific + address offset inside the target I2C slave device. + In this type of I2C operation, the I2C master starts by initiating a write + operation. During this write operation, the specific address offset is written + to the I2C slave. Once the address offset has been written to the I2C slave, + the I2C master transmits a repeated start, and initiates a read operation to + read data from the set address. + + For more information about the operation, please refer to the 'theory of + operations' section at the start of this document. + + This function returns immediately after initiating the transaction. The content + of the write and read buffer passed as parameter should not be modified until + the write transaction completes. It also means that the memory allocated for + the write and read buffer should not be freed or should not go out of scope + before the operation completes. + You can check for the write_read transaction completion by polling the + master_status from miv_i2c_instance_t structure. + + @param this_i2c + A pointer to the miv_i2c_instance_t data structure which + will hold all the data related to the Mi-V I2C module + instance being used. A pointer to this structure is passed to + rest of the Mi-V I2C driver functions for operation. + + @param i2c_target_addr + This parameter specifies the serial address for the slave + device. + + @param write_buffer + This parameter is a pointer to the buffer holding data to be + written to target I2C device. + Care must be taken not to release the memory used by this + buffer before the write transaction completes. + + @param write_size + Number of bytes held in the write_buffer to be written to the + I2C device. + + @param read_buffer + This parameter is a pointer to the buffer where the data + received from the I2C slave device is stored. + Care must be taken not to release the memory used by this + buffer before the write transaction completes. + + @param read_size + Number of bytes held in the write_buffer to be read from the + I2C device. + + @param bus_options: + The bus_options parameter is used to indicate if the I2C bus + should be released on completion of the write transaction. + Using the MIV_I2C_RELEASE_BUS constant for the bus_options + parameter causes a STOP bit to be generated at the end of the + write transaction causing the bus to be released for other I2C + devices to use. Using the MIV_I2C_HOLD_BUS constant as + bus_options parameter prevents a STOP bit from being generated + at the end of the write transaction, preventing other I2C + devices from initiating a bus transaction. + + @param ack_polling_options: + The ack_polling_options parameter is used to indicate how the + MIV_I2C will respond if the slave device transmits a NACK to + the I2C control byte. Using the MIV_I2C_ACK_POLLING_DISABLE + constant for the ack_polling_options parameter causes the + MIV_I2C to abort the transfer if the slave device responds to + the I2C control byte with a NACK. Using the + MIV_I2C_ACK_POLLING_ENABLE constant for the ack_polling_options + parameter causes the MIV_I2C to repeatedly transmit a control + byte to the slave device until the slave device responds with + an ACK or the timeout specified in the MIV_I2C_wait_complete() + function is reached. + @return + This function does not return any value. + + + Example: + @code + #define MIV_I2C_BASE_ADDR 0x7A000000u + + miv_i2c_instance_t g_miv_i2c_inst; + + void main( void ) + { + MIV_I2C_init( &g_miv_i2c_inst, MIV_I2C_BASE_ADDR); + + Configuring Mi-V I2C core at Normal Speed (100MHz) for 50MHz Sys clock. + MIV_I2C_config(&g_miv_i2c_inst, 0x63); + + MIV_I2C_write (&g_miv_i2c_inst, + DUALEE_SLAVEADDRESS_1, + i2c_tx_buffer, + transfer_size, + MIV_I2C_RELEASE_BUS, + MIV_I2C_ACK_POLLING_ENABLE + ); + + // Wait till the miv i2c status changes + do { + miv_i2c_status = miv_i2c.master_status; + }while (MIV_I2C_IN_PROGRESS == miv_i2c_status); + + // reset miv_i2c_status variable + miv_i2c_status = 0u; + + uint8_t addr_offset[2] = {0x00, 0x00}; + MIV_I2C_write_read(&miv_i2c, + DUALEE_SLAVEADDRESS_1, + addr_offset, + sizeof(addr_offset), + i2c_rx_buffer, + transfer_size, + MIV_I2C_RELEASE_BUS, + MIV_I2C_ACK_POLLING_ENABLE + ); + + // Wait till the miv i2c status changes + do { + miv_i2c_status = miv_i2c.master_status; + }while (MIV_I2C_IN_PROGRESS == miv_i2c_status); + } + @endcode + */ +void +MIV_I2C_write_read +( + miv_i2c_instance_t *this_i2c, + uint8_t target_addr, + const uint8_t *write_buffer, + uint16_t write_size, + uint8_t *read_buffer, + uint16_t read_size, + uint8_t bus_options, + uint8_t ack_polling_options +); + +/*-------------------------------------------------------------------------*//** + The MIV_I2C_isr() function contains the MIV_I2C's interrupt service routine. + This ISR is at the heart of the MIV_I2C driver, and is used to control the + interrupt-driven, byte-by-byte I2C read and write operations. + + The ISR operates as a Finite State Machine (FSM), which uses the previously + completed I2C operation and its result to determine which I2C operation will + be performed next. + + The ISR operation is divided into following categories: + - MIV_I2C_IDLE + - MIV_I2C_TX_STA_CB + - MIV_I2C_TX_DATA + - MIV_I2C_RX_DATA + + ##### MIV_I2C_IDLE + The MIV_I2C_IDLE is entered on reset, or when an I2C master operation has been + completed or aborted. + Upon entering, the FSM will remain in this state until a write, read, or + write-read operation is requested + + ##### MIV_I2C_STA_CB + The MIV_I2C_TX_STA_CB operation is performed when the start condition and + control byte(i2c target address(7-bit) and direction of transaction(1-bit)) is + transmitted by the Mi-V I2C master device to the slave. + If the target I2C slave device responded to the previous START Condition + + Control Byte with an ACK, the MIV_I2C will start the requested I2C + read/write operation. + If the target slave I2C slave device responds with NACK, the MIV_I2C will + remain in this state or return to the idle state based on ack_polling + configuration. + + ##### MIV_I2C_TX_DATA + The MIV_I2C_TX_DATA state is entered after the target slave device accepts a + write request with an ACK. + This state is used to handle the byte-by-byte MIV_I2C write operations. + The FSM will remain in this state until either all data bytes have been + written to the target slave device, or an error occurs during the write + operation. + + ##### MIV_I2C_RX_DATA + The MIV_I2C_RX_DATA state is entered after the target slave device accepts a + read request with an ACK. + This state is used to handle the byte-by-byte MIV_I2C read operations. + The FSM will remain in this state until either all data bytes have been + received from the target slave device, or an error occurs. + + @param this_i2c + A pointer to the miv_i2c_instance_t data structure which + will hold all the data related to the Mi-V I2C module + instance being used. A pointer to this structure is passed to + rest of the Mi-V I2C driver functions for operation. + */ +void +MIV_I2C_isr +( + miv_i2c_instance_t *this_i2c +); + +/*-------------------------------------------------------------------------*//** + The MIV_I2C_get_status() returns the 8-bit Mi-V I2C status register value. + + @param this_i2c + A pointer to the miv_i2c_instance_t data structure which + will hold all the data related to the Mi-V I2C module + instance being used. A pointer to this structure is passed to + rest of the Mi-V I2C driver functions for operation. + @return + This function returns 8-bit Mi-V I2C status register value. + */ +uint8_t +MIV_I2C_get_status +( + miv_i2c_instance_t *this_i2c +); + +#ifdef __cplusplus +} +#endif + +#endif /* MIV_I2C_H_ */ diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_i2c/miv_i2c_interrupt.c b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_i2c/miv_i2c_interrupt.c new file mode 100644 index 0000000..871eafe --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_i2c/miv_i2c_interrupt.c @@ -0,0 +1,25 @@ +/******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * This file contains functions used for MIV_I2C driver interrupt control. + * User should enable and disable the interrupts according to their design. + * Please refer to miv_i2c.h file for more information. + */ + +#include "miv_rv32_hal/miv_rv32_hal.h" + +void MIV_I2C_disable_irq(void) +{ +/* Disable I2C interrupt */ + MRV_disable_local_irq(MRV32_MSYS_EIE2_IRQn); +} + +void MIV_I2C_enable_irq(void) +{ +/* Enable I2C interrupt */ + MRV_enable_local_irq(MRV32_MSYS_EIE2_IRQn); +} + + diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_i2c/miv_i2c_regs.h b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_i2c/miv_i2c_regs.h new file mode 100644 index 0000000..9a4bfbf --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_i2c/miv_i2c_regs.h @@ -0,0 +1,158 @@ + /******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * This file contains Register bit offsets and masks definitions for MI-V Soft + * IP I2C module driver. This module is delivered as a part of Mi-V extended + * Sub-System(MIV_ESS). + */ + +#ifndef MIV_I2C_APB_REGISTERS +#define MIV_I2C_APB_REGISTERS 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/*------------------------------------------------------------------------------ + * Prescale register details + */ +#define PRESCALE_REG_OFFSET 0x00u + +/* Prescale register bits */ +#define PRESCALE_OFFSET 0x00u +#define PRESCALE_MASK 0xFFFFu +#define PRESCALE_SHIFT 0u + +/*------------------------------------------------------------------------------ + * Control register details + */ +#define CONTROL_REG_OFFSET 0x04u + +/* Control register bits */ +#define CONTROL_OFFSET 0x04u +#define CONTROL_MASK 0xC0u +#define CONTROL_SHIFT 0u + +/* Control register Core Enable Bit */ +#define CTRL_CORE_EN_OFFSET 0x04u +#define CTRL_CORE_EN_MASK 0x80u +#define CTRL_CORE_EN_SHIFT 7u + +/* Control register IRQ Enable bit */ +#define CTRL_IRQ_EN_OFFSET 0x04u +#define CTRL_IRQ_EN_MASK 0x40u +#define CTRL_IRQ_EN_SHIFT 6u + +/*------------------------------------------------------------------------------ + * Transmit register details + */ +#define TRANSMIT_REG_OFFSET 0x08u + +/* Transmit register bits */ +#define TRANSMIT_OFFSET 0x08u +#define TRANSMIT_MASK 0xFFu +#define TRANSMIT_SHIFT 0u + +/* Transmit register DIR bit */ +#define TX_DIR_OFFSET 0x08u +#define TX_DIR_MASK 0x01u +#define TX_DIR_SHIFT 0u + +/* Transmit register TARGET_ADDR bit */ +#define TX_TARGET_ADDR_OFFSET 0x08u +#define TX_TARGET_ADDR_MASK 0xFEu +#define TX_TARGET_ADDR_SHIFT 1u + +/*------------------------------------------------------------------------------ + * Receive register details + */ +#define RECEIVE_REG_OFFSET 0x0Cu + +/* Receive register bits */ +#define RECEIVE_OFFSET 0x0Cu +#define RECEIVE_MASK 0xFFu +#define RECEIVE_SHIFT 0u + +/*------------------------------------------------------------------------------ + * Command register details + */ +#define COMMAND_REG_OFFSET 0x10u + +/* Command register bits */ +#define COMMAND_OFFSET 0x10u +#define COMMAND_MASK 0xF9u +#define COMMAND_SHIFT 0u + +/* Command register IACK bit */ +#define CMD_IACK_OFFSET 0x10u +#define CMD_IACK_MASK 0x01u +#define CMD_IACK_SHIFT 0u + +/* Command register ACK bit */ +#define CMD_ACK_OFFSET 0x10u +#define CMD_ACK_MASK 0x08u +#define CMD_ACK_SHIFT 3u + +/* Command register WR bit */ +#define CMD_WR_OFFSET 0x10u +#define CMD_WR_MASK 0x10u +#define CMD_WR_SHIFT 4u + +/* Command register RD bit */ +#define CMD_RD_OFFSET 0x10u +#define CMD_RD_MASK 0x20u +#define CMD_RD_SHIFT 5u + +/* Command register STO bit */ +#define CMD_STO_OFFSET 0x10u +#define CMD_STO_MASK 0x40u +#define CMD_STO_SHIFT 6u + +/* Command register STA bit */ +#define CMD_STA_OFFSET 0x10u +#define CMD_STA_MASK 0x80u +#define CMD_STA_SHIFT 7u + +/*------------------------------------------------------------------------------ + * Status register details + */ +#define STATUS_REG_OFFSET 0x14u + +/* Command register bits */ +#define STATUS_OFFSET 0x14u +#define STATUS_MASK 0xFFu +#define STATUS_SHIFT 0u + +/* Status register Interrupt Flag(IF) bit */ +#define STAT_IF_OFFSET 0x14u +#define STAT_IF_MASK 0x01u +#define STAT_IF_SHIFT 0u + +/* Status register Transfer in Progress(TIP) bit */ +#define STAT_TIP_OFFSET 0x14u +#define STAT_TIP_MASK 0x02u +#define STAT_TIP_SHIFT 1u + +/* Status register Arbitration Lost(AL) bit */ +#define STAT_AL_OFFSET 0x14u +#define STAT_AL_MASK 0x20u +#define STAT_AL_SHIFT 5u + +/* Status register Busy(BUSY) bit */ +#define STAT_BUSY_OFFSET 0x14u +#define STAT_BUSY_MASK 0x40u +#define STAT_BUSY_SHIFT 6u + +/* Status register Ack received(RXACK) bit */ +#define STAT_RXACK_OFFSET 0x14u +#define STAT_RXACK_MASK 0x80u +#define STAT_RXACK_SHIFT 7u + + +#ifdef __cplusplus +} +#endif + +#endif /* MIV_I2C_APB_REGISTERS */ diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_plic/miv_plic.c b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_plic/miv_plic.c new file mode 100644 index 0000000..903f029 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_plic/miv_plic.c @@ -0,0 +1,283 @@ +/******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * MI-V Soft IP fabric bare-metal driver for Mi-V PLIC module. This module is + * delivered as a part of Mi-V Extended Sub System(MIV_ESS). + * Please refer to miv_plic.h file for more information. + */ + +#include "miv_plic.h" + +/***************************************************************************//** + * Mi-V PLIC interrupt handler function declaration. + * These functions are called by the external interrupt handler of the MIV_RV32 + * core base on the PLIC source causing the interrupt. + */ +uint8_t Invalid_IRQHandler(void); +uint8_t MIV_PLIC_EXT0_IRQHandler(void); +uint8_t MIV_PLIC_EXT1_IRQHandler(void); +uint8_t MIV_PLIC_EXT2_IRQHandler(void); +uint8_t MIV_PLIC_EXT3_IRQHandler(void); +uint8_t MIV_PLIC_EXT4_IRQHandler(void); +uint8_t MIV_PLIC_EXT5_IRQHandler(void); +uint8_t MIV_PLIC_EXT6_IRQHandler(void); +uint8_t MIV_PLIC_EXT7_IRQHandler(void); +uint8_t MIV_PLIC_EXT8_IRQHandler(void); +uint8_t MIV_PLIC_EXT9_IRQHandler(void); +uint8_t MIV_PLIC_EXT10_IRQHandler(void); +uint8_t MIV_PLIC_EXT11_IRQHandler(void); +uint8_t MIV_PLIC_EXT12_IRQHandler(void); +uint8_t MIV_PLIC_EXT13_IRQHandler(void); +uint8_t MIV_PLIC_EXT14_IRQHandler(void); +uint8_t MIV_PLIC_EXT15_IRQHandler(void); +uint8_t MIV_PLIC_EXT16_IRQHandler(void); +uint8_t MIV_PLIC_EXT17_IRQHandler(void); +uint8_t MIV_PLIC_EXT18_IRQHandler(void); +uint8_t MIV_PLIC_EXT19_IRQHandler(void); +uint8_t MIV_PLIC_EXT20_IRQHandler(void); +uint8_t MIV_PLIC_EXT21_IRQHandler(void); +uint8_t MIV_PLIC_EXT22_IRQHandler(void); +uint8_t MIV_PLIC_EXT23_IRQHandler(void); +uint8_t MIV_PLIC_EXT24_IRQHandler(void); +uint8_t MIV_PLIC_EXT25_IRQHandler(void); +uint8_t MIV_PLIC_EXT26_IRQHandler(void); +uint8_t MIV_PLIC_EXT27_IRQHandler(void); +uint8_t MIV_PLIC_EXT28_IRQHandler(void); +uint8_t MIV_PLIC_EXT29_IRQHandler(void); +uint8_t MIV_PLIC_EXT30_IRQHandler(void); + +/***************************************************************************//** + * MIV_PLIC interrupt handler for external interrupts. + * The array of the function pointers pointing to the weak handler of the Mi-V + * PLIC interrupt handlers. + * These functions are called by the external interrupt handler of the MIV_RV32 + * core base on the PLIC source causing the interrupt. + */ +uint8_t (* const ext_irq_handler_table[32]) (void) = +{ + Invalid_IRQHandler, + MIV_PLIC_EXT0_IRQHandler, + MIV_PLIC_EXT1_IRQHandler, + MIV_PLIC_EXT2_IRQHandler, + MIV_PLIC_EXT3_IRQHandler, + MIV_PLIC_EXT4_IRQHandler, + MIV_PLIC_EXT5_IRQHandler, + MIV_PLIC_EXT6_IRQHandler, + MIV_PLIC_EXT7_IRQHandler, + MIV_PLIC_EXT8_IRQHandler, + MIV_PLIC_EXT9_IRQHandler, + MIV_PLIC_EXT10_IRQHandler, + MIV_PLIC_EXT11_IRQHandler, + MIV_PLIC_EXT12_IRQHandler, + MIV_PLIC_EXT13_IRQHandler, + MIV_PLIC_EXT14_IRQHandler, + MIV_PLIC_EXT15_IRQHandler, + MIV_PLIC_EXT16_IRQHandler, + MIV_PLIC_EXT17_IRQHandler, + MIV_PLIC_EXT18_IRQHandler, + MIV_PLIC_EXT19_IRQHandler, + MIV_PLIC_EXT20_IRQHandler, + MIV_PLIC_EXT21_IRQHandler, + MIV_PLIC_EXT22_IRQHandler, + MIV_PLIC_EXT23_IRQHandler, + MIV_PLIC_EXT24_IRQHandler, + MIV_PLIC_EXT25_IRQHandler, + MIV_PLIC_EXT26_IRQHandler, + MIV_PLIC_EXT27_IRQHandler, + MIV_PLIC_EXT28_IRQHandler, + MIV_PLIC_EXT29_IRQHandler, + MIV_PLIC_EXT30_IRQHandler +}; + +/* Mi-V PLIC interrupt weak handlers */ +__attribute__((weak)) uint8_t Invalid_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT0_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT1_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT2_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT3_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT4_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT5_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT6_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT7_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT8_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT9_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT10_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT11_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT12_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT13_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT14_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT15_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT16_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT17_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT18_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT19_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT20_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT21_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT22_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT23_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT24_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT25_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT26_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT27_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT28_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT29_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t MIV_PLIC_EXT30_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +/*-------------------------------------------------------------------------*//** + * Please refer to miv_plic.h for more information about this function. +*/ +void +MIV_PLIC_isr +( + miv_plic_instance_t *this_plic +) +{ + unsigned long hart_id = read_csr(mhartid); + + /* claim the interrupt from PLIC controller */ + + uint32_t int_num = HAL_get_32bit_reg(this_plic->base_addr + + (0x1000 * hart_id), INT_CLAIM_COMPLETE); + + uint8_t disable = EXT_IRQ_KEEP_ENABLED; + disable = ext_irq_handler_table[int_num](); + + /* Indicate the PLIC controller that the interrupt is processed and claim is + * complete. */ + HAL_set_32bit_reg(this_plic->base_addr + + (0x1000 * hart_id), INT_CLAIM_COMPLETE, int_num); + + if (EXT_IRQ_DISABLE == disable) + { + MIV_PLIC_disable_irq(this_plic, (miv_plic_irq_num_t)int_num); + } +} diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_plic/miv_plic.h b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_plic/miv_plic.h new file mode 100644 index 0000000..f5d64cd --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_plic/miv_plic.h @@ -0,0 +1,425 @@ +/******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * This file contains the application programming interface for the MI-V Soft IP + * PLIC module driver. This module is delivered as a part of Mi-V Extended + * Sub-System(ESS). + */ + /*=========================================================================*//** + @mainpage Mi-V PLIC Bare Metal Driver + + ============================================================================== + Introduction + ============================================================================== + The Mi-V driver provides a set of functions for controlling the Mi-V PLIC + (platform level interrupt controller) soft-IP module. This module is delivered + as a part of the MIV_ESS. The PLIC multiplexes external interrupt signals into + a single interrupt signal that is connected to an external interrupt of the + processor. + + The major features provided by the driver are: + - Support for configuring the PLIC instances. + - Enabling and Disabling interrupts + - Interrupt Handling + + This driver can be used as part of a bare metal system where no operating + system is available. The driver can be adapted for use as part of an + operating system, but the implementation of the adaptation layer between the + driver and the operating system's driver model is outside the scope of this + driver. + + ============================================================================== + Hardware Flow Dependencies + ============================================================================== + The application software should initialize the Mi-V PLIC through the call to + the MIV_PLIC_init() function for Mi-V PLIC instance in the design. + + No Mi-V PLIC hardware configuration parameters are used by the driver, apart + from the Mi-V PLIC base address. Hence, no additional configuration files + are required to use the driver. + + ============================================================================== + Theory of Operation + ============================================================================== + The operation of Mi-V PLIC driver is divided into following steps: + - Initialization + - Enabling and Disabling interrupts + - Interrupt control + + -------------------------------------------- + Initialization + -------------------------------------------- + The Mi-V PLIC module is first initialized by the call to MIV_PLIC_init(). This + function takes a pointer to the Mi-V PLIC instance data structure and the base + address of the Mi-V PLIC instance is defined by the hardware design. The + instance data structure is used to store the base address of the Mi-V PLIC + module and a pointer to the Mi-V PLIC register data structure. The Mi-V PLIC + register data structure maps the address of the Mi-V PLIC registers. + + --------------------------------------------- + Enabling and Disabling interrupts + --------------------------------------------- + The MIV_PLIC_enable_irq() function enables the specific interrupt provided by + user. A call to this function will allow the enabling of each of the global + interrupts corresponding to the bit in the interrupt enable register of Mi-V + PLIC. + The MIV_PLIC_disable_irq() function disables the specific interrupt provided + by the user. This function can be used to disable the interrupts from outside + of the external interrupt handler. + + ---------------------------------------- + Interrupt Control + ---------------------------------------- + When an interrupt occurs on an enabled interrupt, the PLIC gateway captures + the interrupt and asserts the corresponding interrupt pending bit. Once + the enable bit and pending bit are asserted, then the PLIC_IRQ signal asserts + until the interrupt is claimed by the driver interrupt handler MIV_PLIC_irq() + function. + When multiple interrupts assert then the lowest interrupt number will be + serviced first, for example, if interrupt 1 and 6 assert at the same time, + interrupt 1 will be serviced first, followed by interrupt 6. + +*/ + +#ifndef MIV_PLIC_H_ +#define MIV_PLIC_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include "miv_plic_regs.h" + +#ifndef LEGACY_DIR_STRUCTURE +#include "hal/hal.h" +#include "miv_rv32_hal/miv_rv32_hal.h" +#else +#include "hal.h" +#include "miv_rv32_hal.h" +#endif + +/*-------------------------------------------------------------------------*//** + This enumeration is used to select a specific Mi-V PLIC interrupt. It is + used as a parameter to enable or disable the interrupt. +*/ +typedef enum miv_plic_irq_num +{ + NoInterrupt_IRQn = 0, + MIV_PLIC_EXT0_IRQn = 1, + MIV_PLIC_EXT1_IRQn = 2, + MIV_PLIC_EXT2_IRQn = 3, + MIV_PLIC_EXT3_IRQn = 4, + MIV_PLIC_EXT4_IRQn = 5, + MIV_PLIC_EXT5_IRQn = 6, + MIV_PLIC_EXT6_IRQn = 7, + MIV_PLIC_EXT7_IRQn = 8, + MIV_PLIC_EXT8_IRQn = 9, + MIV_PLIC_EXT9_IRQn = 10, + MIV_PLIC_EXT10_IRQn = 11, + MIV_PLIC_EXT11_IRQn = 12, + MIV_PLIC_EXT12_IRQn = 13, + MIV_PLIC_EXT13_IRQn = 14, + MIV_PLIC_EXT14_IRQn = 15, + MIV_PLIC_EXT15_IRQn = 16, + MIV_PLIC_EXT16_IRQn = 17, + MIV_PLIC_EXT17_IRQn = 18, + MIV_PLIC_EXT18_IRQn = 19, + MIV_PLIC_EXT19_IRQn = 20, + MIV_PLIC_EXT20_IRQn = 21, + MIV_PLIC_EXT21_IRQn = 22, + MIV_PLIC_EXT22_IRQn = 23, + MIV_PLIC_EXT23_IRQn = 24, + MIV_PLIC_EXT24_IRQn = 25, + MIV_PLIC_EXT25_IRQn = 26, + MIV_PLIC_EXT26_IRQn = 27, + MIV_PLIC_EXT27_IRQn = 28, + MIV_PLIC_EXT28_IRQn = 29, + MIV_PLIC_EXT29_IRQn = 30, + MIV_PLIC_EXT30_IRQn = 31 +} miv_plic_irq_num_t; + +/*--------------------------------------------------------------------------*//* + * This structure maps the priority threshold and claim complete register in + * the memory. + */ +typedef struct +{ + volatile uint32_t PRIORITY_THRESHOLD; + volatile uint32_t CLAIM_COMPLETE; + volatile uint32_t reserved[1022]; +} IRQ_Target_Type; + +/*--------------------------------------------------------------------------*//* + * This structure maps the Interrupt enable sources from 0 - 1023 for one + * context. + */ +typedef struct +{ + volatile uint32_t ENABLES[32]; +} Target_Enables_Type; + +/*-------------------------------------------------------------------------*//** + This structure holds the base address of the Mi-V PLIC module. This structure + is used by all the functions to access the Mi-V PLIC registers. +*/ +typedef struct miv_plic_instance +{ + addr_t base_addr; +} miv_plic_instance_t; + +/*-------------------------------------------------------------------------*//** + * The MIV_PLIC_isr is the top level interrupt handler function for the Mi-V PLIC + * driver. You must call the MIV_PLIC_isr() from the system level interrupt + * handler(External_IRQHandler). + * This function must be called from the external interrupt handler function + * provided by the processor hardware abstraction layer. In case of MIV_RV32 + * soft processor, it must be called from External_IRQHandler() function + * provided by MIV_RV32 HAL. + * + * The MIV_PLIC_isr() function claims the interrupt number + * that triggered the interrupt and then invokes the appropriate PLIC interrupt + * handler. + * After handling the PLIC interrupt, this function will complete the interrupt + * by clearing the claim complete bit for the particular interrupt source. + * + * @param this_plic + * A pointer to the miv_plic_instance_t data structure which + * will hold all the data related to the Mi-V PLIC instance + * being used. A pointer to this data structure is passed to + * rest of Mi-V PLIC driver functions for operation. + * + * @return + * This function does not return any value. + * + * Example: + * @code + * #define MIV_PLIC_BASE_ADDR 0x70000000 + * #define PLIC_EXT_INTR_SOURCES 31 + * + * miv_plic_instance_t g_plic; + * uint8_t MIV_PLIC_EXT0_IRQHandler(void) + * { + * *** ISR operation *** + * + * return(EXT_IRQ_KEEP_ENABLED); + * } + * + * void External_IRQHandler(void) + * { + * uint32_t reg_val = read_csr(mip); + * MIV_PLIC_isr(&g_plic); + * } + * + * void main(void) + * { + * MIV_PLIC_init(&g_plic, MIV_PLIC_BASE_ADDR, PLIC_EXT_INTR_SOURCES); + * + * MIV_PLIC_enable_irq(&g_plic, MIV_PLIC_EXT0_IRQn); + * MIV_PLIC_enable_irq(&g_plic, MIV_PLIC_EXT1_IRQn); + * MIV_PLIC_enable_irq(&g_plic, MIV_PLIC_EXT2_IRQn); + * MIV_PLIC_enable_irq(&g_plic, MIV_PLIC_EXT3_IRQn); + * } + * @endcode + */ +void MIV_PLIC_isr(miv_plic_instance_t *this_plic); + +/*-------------------------------------------------------------------------*//** + * The MIV_PLIC_init() function initializes the Mi-V PLIC instance with base + * address. This function resets the PLIC controller by disabling all the PLIC + * interrupts. + * + * Note: This function must be called before calling any other Mi-V PLIC driver + * function. + * + * @param this_plic + * A pointer to the miv_plic_instance_t data structure which + * will hold all the data related to the Mi-V PLIC instance + * being used. A pointer to this data structure is passed to + * rest of Mi-V PLIC driver functions for operation. + * + * @param base_addr + * Base address of the Mi-V PLIC instance in the MIV_ESS soft-IP. + * + * @param ext_intr_sources + * Number of interrupts initialized in the design. + * + * @return + * This function does not return any value. + * + * Example + * @code + * #define MIV_PLIC_BASE_ADDR 0x70000000 + * #define PLIC_EXT_INTR_SOURCES 31 + * + * miv_plic_instance_t g_plic; + * + * void main(void) + * { + * MIV_PLIC_init(&g_plic, MIV_PLIC_BASE_ADDR, PLIC_EXT_INTR_SOURCES); + * } + * @endcode + */ +static inline void +MIV_PLIC_init +( + miv_plic_instance_t *this_plic, + addr_t base_addr, + uint8_t ext_intr_sources +) +{ + uint32_t inc; + unsigned long hart_id = read_csr(mhartid); + + this_plic->base_addr = base_addr; + + /* Disable all interrupts for the current hart. + * The PLIC_EXT_INTR_SOURCES should be defined in the hw_platform.h. This + * macro holds the number of PLIC interrupts enabled in the design. + */ + for(inc = 0; inc < ((ext_intr_sources + 32u) / 32u); ++inc) + { + HAL_set_32bit_reg( + (this_plic->base_addr + inc + (hart_id * 128)), INT_ENABLE , 0x0u); + } +} + +/*-------------------------------------------------------------------------*//** + * The MIV_PLIC_enable_irq() function enables the PLIC interrupt provided with + * IRQn parameter. + * + * @param this_plic + * A pointer to the miv_plic_instance_t data structure which + * will hold all the data related to the Mi-V PLIC instance + * being used. A pointer to this data structure is passed to + * rest of Mi-V PLIC driver functions for operation. + * @param IRQn + * Number of PLIC interrupt to enable. + * + * @return + * This function does not return any value. + * + * Example + * @code + * #define MIV_PLIC_BASE_ADDR 0x70000000 + * #define PLIC_EXT_INTR_SOURCES 31 + * + * miv_plic_instance_t g_plic; + * + * void main(void) + * { + * MIV_PLIC_init(&g_plic, MIV_PLIC_BASE_ADDR, PLIC_EXT_INTR_SOURCES); + * + * MIV_PLIC_enable_irq(&g_plic, MIV_PLIC_EXT0_IRQn); + * MIV_PLIC_enable_irq(&g_plic, MIV_PLIC_EXT1_IRQn); + * MIV_PLIC_enable_irq(&g_plic, MIV_PLIC_EXT2_IRQn); + * MIV_PLIC_enable_irq(&g_plic, MIV_PLIC_EXT3_IRQn); + * } + * @endcode + */ +static inline void +MIV_PLIC_enable_irq +( + miv_plic_instance_t *this_plic, + miv_plic_irq_num_t IRQn +) +{ + unsigned long hart_id = read_csr(mhartid); + + uint32_t current = HAL_get_32bit_reg( + (this_plic->base_addr + (IRQn/32) + (hart_id * 128)) , INT_ENABLE); + + current |= (uint32_t)1 << (IRQn % 32); + + HAL_set_32bit_reg( + (this_plic->base_addr + (IRQn/32) + (hart_id * 128)), INT_ENABLE, current); + +} + +/*-------------------------------------------------------------------------*//** + * The MIV_PLIC_disable_irq() function disables the PLIC interrupt provided with + * IRQn parameter. + * + * NOTE: + * This function can be used to disable the PLIC interrupt from outside the + * external interrupt handler functions. + * If you wish to disable the PLIC interrupt from the external interrupt handler, + * you should use the return value of EXT_IRQ_DISABLE. This will disable the + * selected PLIC interrupt from the Mi-V PLIC driver interrupt handler. + * + * @param this_plic + * A pointer to the miv_plic_instance_t data structure which + * will hold all the data related to the Mi-V PLIC instance + * being used. A pointer to this data structure is passed to + * rest of Mi-V PLIC driver functions for operation. + * @param IRQn + * Number of PLIC interrupt to disable. + * + * @return + * This function does not return any value. + * + * Example + * @code + * #define MIV_PLIC_BASE_ADDR 0x70000000 + * #define PLIC_EXT_INTR_SOURCES 31 + * + * miv_plic_instance_t g_plic; + * + * void main(void) + * { + * MIV_PLIC_init(&g_plic, MIV_PLIC_BASE_ADDR, PLIC_EXT_INTR_SOURCES); + * + * MIV_PLIC_enable_irq(&g_plic, MIV_PLIC_EXT0_IRQn); + * MIV_PLIC_enable_irq(&g_plic, MIV_PLIC_EXT1_IRQn); + * MIV_PLIC_enable_irq(&g_plic, MIV_PLIC_EXT2_IRQn); + * MIV_PLIC_enable_irq(&g_plic, MIV_PLIC_EXT3_IRQn); + * + * MIV_PLIC_disable_irq(&g_plic, MIV_PLIC_EXT0_IRQn); + * MIV_PLIC_disable_irq(&g_plic, MIV_PLIC_EXT1_IRQn); + * MIV_PLIC_disable_irq(&g_plic, MIV_PLIC_EXT2_IRQn); + * MIV_PLIC_disable_irq(&g_plic, MIV_PLIC_EXT3_IRQn); + * } + * @endcode + */ +static inline void +MIV_PLIC_disable_irq +( + miv_plic_instance_t *this_plic, + miv_plic_irq_num_t IRQn +) +{ + unsigned long hart_id = read_csr(mhartid); + + uint32_t current = HAL_get_32bit_reg((this_plic->base_addr + (IRQn/32) + (hart_id * 128)) , INT_ENABLE); + + current &= ~((uint32_t)1 << (IRQn % 32)); + + HAL_set_32bit_reg((this_plic->base_addr + (IRQn/32) + (hart_id * 128)), INT_ENABLE, current); + +} + +#ifdef __cplusplus +} +#endif + +#endif /* MIV_PLIC_H_ */ diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_plic/miv_plic_regs.h b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_plic/miv_plic_regs.h new file mode 100644 index 0000000..76cbc0b --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_plic/miv_plic_regs.h @@ -0,0 +1,31 @@ + /******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * This file contains Register bit offsets and masks definitions for MI-V Soft + * IP PLIC module driver. This module is delivered as a part of Mi-V extended + * Sub-System(MIV_ESS). + */ + +#ifndef MIV_PLIC_REGISTERS +#define MIV_PLIC_REGISTERS 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/* Interrupt pending register offset */ +#define INT_PENDING_REG_OFFSET 0x1000u + +/* Interrupt enable register */ +#define INT_ENABLE_REG_OFFSET 0x2000u + +/* Interrupt claim complete register */ +#define INT_CLAIM_COMPLETE_REG_OFFSET 0x200004u + +#ifdef __cplusplus +} +#endif + +#endif /* MIV_PLIC_REGISTERS */ diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_timer/miv_timer.h b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_timer/miv_timer.h new file mode 100644 index 0000000..5f00889 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_timer/miv_timer.h @@ -0,0 +1,329 @@ +/******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * Mi-V Timer Soft IP bare-metal driver. This module is delivered as part of + * the Mi-V Extended Sub System(ESS) MIV_ESS. + */ + +/*=========================================================================*//** + @mainpage Mi-V Timer Bare Metal Driver. + The Mi-V Timer bare metal software driver supports the timer module which + serves as a system timer for the Mi-V Extended Sub System(ESS). + + @section intro_sec Introduction + The MI-V Timer driver supports set of functions for controlling the Mi-V + Timer module. + The Mi-V Timer can generate a timer interrupt signal for the system based on + special system clock intervals specified by the parameters that can be passed + in by the user. + + The major features provided by Mi-V Timer driver are: + - Support for Mi-V Timer instance for each Mi-V Timer peripheral. + - Read current time + - Write to the machine time compare register + + @section hw_dependencies Hardware Flow dependency + The application should configure the Mi-V Timer driver through calls to + MIV_TIMER_init() functions for each MIV_TIMER instance in the hardware + design. The configuration parameter include the MIV_TIMER hardware instance, + base address and number of ticks to generate timer interrupt. + + MIV_RV32 core offers flexibility in terms of generating the MTIME and MTIMECMP + registers internal to the core or using external time reference. + When MIV_ESS is interfaced with MIV_RV32 core, the timer module in the MIV_ESS + can be configured as follows: + - Internal MTIME External MTIME IRQ + Generate the MTIME internally(MIV_RV32) and have a timer interrupt input + to the core as external pin(from MIV_ESS). + + - External MTIME Internal MTIME IRQ + Generate the time value externally(from MIV_ESS), in this case a 64-bit + port will open in the MIV_RV32 core as input and MIV_ESS will output the + 64-bit TIME_COUNT value. The generation of mtimecmp and interrupt is + done internally(MIV_RV32). + + - External MTIME External MTIME IRQ + Generate both the time and timer interrupt externally. + In this case 64-bit port will be available on the Mi-V RV32 core as input + and a 1 pin port will be available for timer interrupt. + + The design must be configured accordingly to use these combinations in the + firmware. + + No MIV_TIMER hardware configuration parameters are used by the driver, apart + from MIV_TIMER base address. Hence, no additional configuration files are + required to use the driver. + + @section theory_op Theory of Operation + + The MIV_TIMER module is a simple systick timer which can generate a timer + interrupt signal for the system at specific intervals specified by the + parameters that can be passed by the user. + These interrupt signal are then fed to the MIV_RV32 core via timer interrupt. + + The operation of MIV_TIMER is divided into following steps: + - Initialization + - Configuration + - Read/Write TIME + + ## Initialization + The MIV_TIMER is first initialized by a call to MIV_TIMER_init(). This + function initializes the instance of Mi-V TIMER with the base address. + The MIV_TIMER_init() function must be called before any other Mi-V Timer driver + function. + + ## Configuration + The Mi-V TIMER configuration includes writing the mtimecmp register with the + initial time value at which timer interrupt should be generated. + When the mtime register value becomes greater than or equal to mtimecmp value, + a timer interrupt signal(TIMER_IRQ) is generated. + + ## Read/Write TIME + The time value can be read by reading the mtime register via call to the + MIV_TIMER_read_mtime(). This function reads the MTIME register which contains + the 64-bit value of the timer count. The count increments by 1 every time the + prescale ticks. This function returns 64-bit MTIME_COUNT value which is the + current value of timer count. + + The time value read in the MIV_TIMER_read_mtime() function can be written to + the mtimecmp register by calling MIV_TIMER_write_mtimecmp() to generate + periodic interrupts. + The writing of the mtimecmp register should be done in the systick_handler() + function. + */ + +#ifndef MIV_TIMER_H_ +#define MIV_TIMER_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef LEGACY_DIR_STRUCTURE +#include "hal/hal.h" + +#else +#include "hal.h" +#endif +/*-------------------------------------------------------------------------*//** +MIV_TIMER_SUCCESS +===================== + +The MIV_TIMER_SUCCESS constant indicates successful configuration of +Mi-V Timer module. +*/ +#define MIV_TIMER_SUCCESS 0u + +/*-------------------------------------------------------------------------*//** +MIV_TIMER_ERROR +===================== + +The MIV_TIMER_ERROR constant indicates that there is an error with +configuring the Mi-V Timer module. +*/ +#define MIV_TIMER_ERROR 1u + +/*-------------------------------------------------------------------------*//* +MIV_TIMER_MASK_32BIT +===================== + +32-bit mask constant used in calculation of 64-bit register value. +*/ +#define MIV_TIMER_MASK_32BIT 0xFFFFFFFFu + +/*-------------------------------------------------------------------------*//* +Mi-V Timer register offsets +===================== +The MTIMECMP is the 64-bit timer compare register, it pre-sets the threshold +which needs to be reached by the timer count register. +This 64-bit register is accessed with 2 32-bit address offset, lower 32-bits +and higher 32-bits. + - MIV_TIMER_MTIMECMP_L_REG_OFFSET + - MIV_TIMER_MTIMECMP_H_REG_OFFSET + +The MTIME is the 64-bit register that contains the 64-bit timer count. The +count increments by 1 every time the prescaler ticks. +This 64-bit register is accessed with 2 32-bit address offset, lower 32-bits +and higher 32-bits. + - MIV_TIMER_MTIME_L_REG_OFFSET + - MIV_TIMER_MTIME_H_REG_OFFSET + +The PRESCALE register is used to determine the amount of clock cycles the +selected clock needs to go through, for MTIME register to increment count. + - MIV_TIMER_PRESCALAR_REG_OFFSET +*/ + +/// @cond private +#define MIV_TIMER_MTIMECMP_L_REG_OFFSET 0x4000u +#define MIV_TIMER_MTIMECMP_H_REG_OFFSET 0x4004u + +#define MIV_TIMER_MTIME_L_REG_OFFSET 0xBFF8u +#define MIV_TIMER_MTIME_H_REG_OFFSET 0xBFFCu + +#define MIV_TIMER_PRESCALAR_REG_OFFSET 0x5000u +/// @endcond + +/*-------------------------------------------------------------------------*//** + This structure holds the base address of the Mi-V Timer module and instance + of the Mi-V Timer register structure. +*/ +typedef struct miv_timer_instance +{ + addr_t base_addr; +} miv_timer_instance_t; + +/** The MIV_TIMER_init() is used to initialize the Mi-V Timer module. This + function will assign the base addresses of the Mi-V Timer module. + User should call this function before calling any of the Mi-V Timer driver + APIs. + + @param this_timer + Timer structure which holds the base address for the Mi-V Timer hardware + instance. + + @param base_address + Base address of the Mi-V Timer module. + + @return + This function does not return any value. + */ +static inline void +MIV_TIMER_init +( + miv_timer_instance_t* this_timer, + addr_t base_addr +) +{ + this_timer->base_addr = base_addr; +} + +/** MIV_TIMER_read_current_time() is used to read the mtimecmp register values. + + @param this_timer + Timer structure which holds the base address for the Mi-V Timer hardware + instance. + + @return + This function returns 64-bit mtimecmp register value. + */ +static inline uint64_t +MIV_TIMER_read_current_time +( + miv_timer_instance_t* this_timer +) +{ + volatile uint64_t read_data = 0u; + volatile uint32_t mtime_hi = 0u; + volatile uint32_t mtime_lo = 0u; + + /* when mtime lower word is 0xFFFFFFFF, there will be rollover and + * returned value could be wrong. */ + do { + mtime_hi = HAL_get_32bit_reg(this_timer->base_addr, MIV_TIMER_MTIME_H); + mtime_lo = HAL_get_32bit_reg(this_timer->base_addr, MIV_TIMER_MTIME_L); + + } while(mtime_hi != HAL_get_32bit_reg(this_timer->base_addr, MIV_TIMER_MTIME_H)); + + read_data = mtime_hi; + + return(((read_data) << 32u) | mtime_lo); +} + +/** MIV_TIMER_write_compare_time() is used to write to the MTIMECMP register in + the event of interrupt. User must use this function in the interrupt handler + to de-assert the MIV_TIMER interrupt. + + @param this_timer + Timer structure which holds the base address for the Mi-V Timer hardware + instance. + + @param write_value + Value to write into the mtimecmp register. + + @return + This function does not return any value. + */ +static inline void +MIV_TIMER_write_compare_time +( + miv_timer_instance_t* this_timer, + uint64_t compare_reg_value +) +{ + HAL_set_32bit_reg(this_timer->base_addr, MIV_TIMER_MTIMECMP_H, MIV_TIMER_MASK_32BIT); + + HAL_set_32bit_reg(this_timer->base_addr, MIV_TIMER_MTIMECMP_L, + (compare_reg_value & MIV_TIMER_MASK_32BIT)); + + HAL_set_32bit_reg(this_timer->base_addr, MIV_TIMER_MTIMECMP_H, + ((compare_reg_value >> 32u) & MIV_TIMER_MASK_32BIT)); +} + +/** The MIV_TIMER_config() is used to configure the MIV_ESS Timer module. The + prescale value serves to divide the count of clock cycles for the timer and + provides control over what point in time, the timer interrupt gets + asserted. + + @param this_timer + Timer structure which holds the base address for the Mi-V Timer hardware + instance. + + @param ticks + Number of ticks after which interrupt will be generated. + + @return + This function returns Mi-V Timer configuration status. + */ +static inline uint32_t +MIV_TIMER_config +( + miv_timer_instance_t* this_timer, + uint64_t ticks +) +{ + uint32_t ret_val = MIV_TIMER_ERROR; + uint64_t mtime_val = 0u; + uint32_t prescalar = 0u; + uint64_t miv_timer_increment = 0U; + + prescalar = HAL_get_32bit_reg(this_timer->base_addr, MIV_TIMER_PRESCALAR); + + miv_timer_increment = (uint64_t)(ticks) / prescalar; + + if (miv_timer_increment > 0U) + { + mtime_val = MIV_TIMER_read_current_time(this_timer); + + MIV_TIMER_write_compare_time(this_timer ,(mtime_val + miv_timer_increment)); + + ret_val = MIV_TIMER_SUCCESS; + } + + return ret_val; +} + +#ifdef __cplusplus +} +#endif + +#endif /* MIV_TIMER_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_udma/miv_udma.c b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_udma/miv_udma.c new file mode 100644 index 0000000..d57f2ae --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_udma/miv_udma.c @@ -0,0 +1,107 @@ +/******************************************************************************* + * (c) Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * Mi-V uDMA Soft IP bare-metal driver. This module is delivered as part of + * Mi-V Extended Sub System(MIV_ESS) + */ + +#include "miv_udma_regs.h" +#include "miv_udma.h" + +/***************************************************************************//** + * MIV_uDMA_init() + * See "miv_udma.h" for details of how to use this function. + */ +void +MIV_uDMA_init +( + miv_udma_instance_t* this_udma, + addr_t base_addr +) +{ + /* Assign the Mi-V uDMA base address to the uDMA instance structure */ + this_udma->base_address = base_addr; +} + +/***************************************************************************//** + * MIV_uDMA_config() + * See "miv_udma.h" for details of how to use this function. + */ +void +MIV_uDMA_config +( + miv_udma_instance_t* this_udma, + addr_t src_addr, + addr_t dest_addr, + uint32_t transfer_size, + uint32_t irq_config +) +{ + /* Source memory start address */ + HAL_set_32bit_reg(this_udma->base_address, SRC_START_ADDR, src_addr); + + /* Destination memory start address */ + HAL_set_32bit_reg(this_udma->base_address, DEST_START_ADDR, dest_addr); + + /* Data transfer size */ + HAL_set_32bit_reg(this_udma->base_address, BLK_SIZE, transfer_size); + + /* Configure the uDMA IRQ */ + HAL_set_32bit_reg(this_udma->base_address, IRQ_CFG, irq_config); +} + +/***************************************************************************//** + * MIV_uDMA_start() + * See "miv_udma.h" for details of how to use this function. + */ +void +MIV_uDMA_start +( + miv_udma_instance_t* this_udma +) +{ + /* Start the uDMA transfer */ + HAL_set_32bit_reg(this_udma->base_address, CONTROL_SR, CTRL_START_TX_MASK); +} + +/***************************************************************************//** + * MIV_uDMA_reset() + * See "miv_udma.h" for details of how to use this function. + */ +void +MIV_uDMA_reset +( + miv_udma_instance_t* this_udma +) +{ + /* Toggle the uDMA_reset bit to reset the uDMA. + * Resetting the uDMA will clear all the configuration made by + * MIV_uDMA_config(). + * + * This function should be called from the interrupt handler to clear the + * IRQ. + */ + HAL_set_32bit_reg_field(this_udma->base_address, CTRL_RESET_TX, 0x1u); + HAL_set_32bit_reg_field(this_udma->base_address, CTRL_RESET_TX, 0x0u); +} + +/***************************************************************************//** + * MIV_uDMA_read_status() + * See "miv_udma.h" for details of how to use this function. + */ +uint32_t +MIV_uDMA_read_status +( + miv_udma_instance_t* this_udma +) +{ + uint32_t status = 0u; + + /* Read the status of the uDMA transfer. + * The transfer status register can be Error or Busy depending on the + * current uDMA transfer. + */ + status = HAL_get_32bit_reg(this_udma->base_address, TX_STATUS); + + return status; +} diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_udma/miv_udma.h b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_udma/miv_udma.h new file mode 100644 index 0000000..c4e7f3c --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_udma/miv_udma.h @@ -0,0 +1,289 @@ +/******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * This file contains the application programming interface for the MI-V Soft IP + * uDMA module driver. This module is delivered as a part of Mi-V Extended + * Sub-System(MIV_ESS). + */ + +/*=========================================================================*//** + @mainpage Mi-V uDMA Bare Metal Driver. + The Mi-V uDMA bare metal software driver. + + @section intro_sec Introduction + The Mi-V uDMA driver provides a set of functions to control the Mi-V uDMA + module in the Mi-V Extended Sub System(MIV_ESS) soft-IP. The Mi-V uDMA module + allows peripherals with AHB interfaces to transfer data independently of the + MIV_RV32 RISC-V processor. + + The major features provided by the Mi-V uDMA driver are: + - Initialization and configuration + - Start and reset the transaction + + This driver can be used as part of a bare metal system where no operating + system is available. The driver can be adapted for use as part of an + operating system, but the implementation of the adaptation layer between the + driver and the operating system's driver model is outside the scope of this + driver. + + @section hw_dependencies Hardware Flow Dependency + The application software should initialize and configure the Mi-V uDMA through + the call to MIV_uDMA_init(), MIV_uDMA_config() function for Mi-V uDMA + instance in the design. + The μDMA can operate in two possible transfer configurations: + + AHBL Read –> AHBL Write: + In this configuration, the μDMA reads data from the source memory over an + AHBL (Mirrored Main/Initiator) read interface and writes data to the + destination memory over an AHBL (Mirrored Main/Initiator) write interface. + + AHBL Read –> TAS Write: + In this configuration, the μDMA reads data from the source memory over an + AHBL (Mirrored Main/Initiator) read interface and writes data to the + destination memory over the TAS (Mirrored Main/Initiator) write interface. + + The AHBL Read -> TAS Write configuration is out of scope for this driver. + + @section theory_op Theory of Operation + The uDMA module in the Mi-V Extended Sub System(MIV_ESS) is a single channel + uDMA module that allows peripherals to perform read write operations between + source and destination memory. The Mi-V uDMA driver is generally used in + interrupt driven mode and uses the Mi-V uDMA IRQ signal to drive the + interrupt service routine(ISR) which signifies a transfer has completed. + The status is checked in the ISR to ensure the transfer is completed + successfully. + The reset operation in the ISR will reset the Mi-V uDMA controller. + Once the Mi-V uDMA transfer completes, Mi-V uDMA retires. To + initiate another transaction, Mi-V uDMA will have to be configured again. + + The operation of the Mi-V uDMA driver can be divided into following + categories: + - Initialization + - Configuration + - Start and reset transfer + + ### Initialization and configuration + Mi-V uDMA is first initialized by a call to MIV_uDMA_init(). This function + initializes the instance of Mi-V uDMA with base address. The MIV_uDMA_init() + function must be called before calling any other Mi-V uDMA driver functions. + + The Mi-V uDMA is configured by a call to MIV_uDMA_config(). This function + will configure the source_addr and dest_addr registers of the Mi-V uDMA with + source and destination addresses for Mi-V uDMA transfers. + This function also configures the transfer size and interrupt preference for + successful transfer of Mi-V uDMA. + + ### Start and Reset transfer + Once the Mi-V uDMA is configured, the transfers can be started with a call to + MIV_uDMA_start(). Once the Mi-V uDMA transfer is started, it can not be + aborted and the status of the transfer should be read from the ISR by a call + to MIV_uDMA_read_status(). + + The Mi-V uDMA can be reset to the default state by calling MIV_uDMA_reset() + function. After performing reset operation, the Mi-V uDMA should be + re-configured to perform transfer since MIV_uDMA_reset() resets the Mi-V uDMA + controller. + */ + +#ifndef MIV_uDMA_H_ +#define MIV_uDMA_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef LEGACY_DIR_STRUCTURE +#include "hal/hal.h" +#include "hal/cpu_types.h" + +#else +#include "hal.h" +#include "cpu_types.h" +#endif + +/*-------------------------------------------------------------------------*//** + MIV_uDMA_CTRL_IRQ_CONFIG + ===================== + + The MIV_uDMA_CTRL_IRQ_CONFIG macro is used to assert the uDMA IRQ when an error + occurs during a uDMA transfer or on the completion of a uDMA transfer. + */ +#define MIV_uDMA_CTRL_IRQ_CONFIG 1u + +/*-------------------------------------------------------------------------*//** + MIV_uDMA_STATUS_BUSY + ===================== + + The MIV_uDMA_STATUS_BUSY macro is used to indicate that the uDMA transfer is + in progress. + */ +#define MIV_uDMA_STATUS_BUSY 1u + +/*-------------------------------------------------------------------------*//** + MIV_uDMA_STATUS_ERROR + ===================== + + The MIV_uDMA_STATUS_ERROR macro is used to indicate that the last uDMA + transfer has caused an error. + */ +#define MIV_uDMA_STATUS_ERROR 2u + +/***************************************************************************//** + * Mi-V uDMA instant structure. + * This structure will hold the base of Mi-V uDMA module which is used in the + * other functions in the driver to access the uDMA registers. + */ +typedef struct miv_udma_instance +{ + addr_t base_address; +} miv_udma_instance_t; + +/***************************************************************************//** + * The MIV_uDMA_init() assigns the base address of Mi-V uDMA module to the + * uDMA instance structure. + * This address is used in later part of the driver to access the uDMA registers. + * + * @param this_udma + * This parameter is a pointer to the miv_udma_instance_t structure. + * + * @param base_addr + * Base address of the Mi-V uDMA module. + * + * @return + * This function does not return a value. + */ +void +MIV_uDMA_init +( + miv_udma_instance_t* this_udma, + addr_t base_addr +); + +/***************************************************************************//** + * The MIV_uDMA_config() is used to configure the Mi-V uDMA controller. + * This function will set the source address, destination address, block size + * and IRQ config register. + * + * @param this_udma + * This parameter is a pointer to the miv_udma_instance_t structure which + * holds the base address of Mi-V uDMA module. + * + * @param base_addr + * Base address of the Mi-V uDMA + * + * @param src_addr + * Source address of memory from which the uDMA will read the data. + * + * @param dest_addr + * Destination address where the data will be written from src_addr. + * + * @param transfer_size + * Number of 32-bit words to transfer + * + * @param irq_config + * uDMA IRQ Configuration. + * + * When set, the IRQ is asserted when and error occurs during a uDMA + * transfer or on the completion of the uDMA transfer. + * + * When clear, the IRQ is only asserted when an error occurs during a uDMA + * transfer. + * + * @return + * This function does not return any value. + */ +void +MIV_uDMA_config +( + miv_udma_instance_t* this_udma, + addr_t src_addr, + addr_t dest_addr, + uint32_t transfer_size, + uint32_t irq_config +); + +/***************************************************************************//** + * The MIV_uDMA_start() is used to start the uDMA transfer. + * + * @param this_udma + * This parameter is a pointer to the miv_udma_instance_t structure which + * holds the base address of Mi-V uDMA module. + * + * @return + * This function does not return any value. + */ +void +MIV_uDMA_start +( + miv_udma_instance_t* this_udma +); + +/***************************************************************************//** + * The MIV_uDMA_reset() is used to clear the uDMA interrupt and reset the uDMA + * transfer. + * + * This function should be called from interrupt handler and it will reset the + * values set during MIV_uDMA_config(). + * + * @param this_udma + * This parameter is a pointer to the miv_udma_instance_t structure which + * holds the base address of Mi-V uDMA module. + * + * @return + * This function does not return any value. + */ +void +MIV_uDMA_reset +( + miv_udma_instance_t* this_udma +); + +/***************************************************************************//** + * The MIV_uDMA_read_status() will be used to status of the uDMA transfer. When + * Interrupt is enabled this function can be called from the interrupt handler + * to know the reason of uDMA interrupt. + * + * @param this_udma + * This parameter is a pointer to the miv_udma_instance_t structure which + * holds the base address of Mi-V uDMA module. + * + * @return + * Return value will indicate error of busy status of the uDMA channel. + * + * |Bit Number| Name | Description | + * |----------|---------|------------------------------------------------------| + * | 0 | Busy | When set indicates that uDMA transfer is in progress| + * | 1 | Error | When set indicates that last uDMA transfer caused an| + * | | | error. | + */ +uint32_t +MIV_uDMA_read_status +( + miv_udma_instance_t* this_pdma +); + +#ifdef __cplusplus +} +#endif + +#endif /* MIV_uDMA_H_ */ diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_udma/miv_udma_regs.h b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_udma/miv_udma_regs.h new file mode 100644 index 0000000..14d0759 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_udma/miv_udma_regs.h @@ -0,0 +1,94 @@ + /******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * This file contains Register bit offsets and masks definitions for MI-V Soft + * IP uDMA module driver. This module is delivered as a part of Mi-V + * extended Sub-System(ESS) MIV_ESS. + */ + +#ifndef MIV_UDMA_APB_REGISTERS +#define MIV_UDMA_APB_REGISTERS 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/**************************************************************************//** + * Control start/Reset register details + */ + +#define CONTROL_SR_REG_OFFSET 0x0u + +/* Control start/Reset register bits */ +#define CONTROL_SR_OFFSET 0x00u +#define CONTROL_SR_MASK 0x03u +#define CONTROL_SR_SHIFT 0u + +/* uDMA Control Start Transfer */ + +#define CTRL_START_TX_OFFSET 0x00u +#define CTRL_START_TX_MASK 0x01u +#define CTRL_START_TX_SHIFT 0u + +/* uDMA Control Reset Transfer */ +#define CTRL_RESET_TX_OFFSET 0x00u +#define CTRL_RESET_TX_MASK 0x02u +#define CTRL_RESET_TX_SHIFT 1u + +/**************************************************************************//** + * IRQ Configuration register details + */ +#define IRQ_CFG_REG_OFFSET 0x4u + +/* Control start/Reset register bits */ +#define IRQ_CFG_OFFSET 0x04u +#define IRQ_CFG_MASK 0x01u +#define IRQ_CFG_SHIFT 0u + +/***************************************************************************//** + * Transfer Status register details + */ +#define TX_STATUS_REG_OFFSET 0x08u + +/* Transfer status register bits */ +#define TX_STATUS_OFFSET 0x08u +#define TX_STATUS_MASK 0x03u +#define TX_STATUS_SHIFT 0u + +/***************************************************************************//** + * Source Memory Start Address Register + */ +#define SRC_START_ADDR_REG_OFFSET 0x0cu + +/* Source Memory Start Address Register bits */ +#define SRC_START_ADDR_OFFSET 0x0cu +#define SRC_START_ADDR_MASK 0xFFFFFFFFu +#define SRC_START_ADDR_SHIFT 0u + +/***************************************************************************//** + * Destination Memory Start Address register details + */ +#define DEST_START_ADDR_REG_OFFSET 0x10u + +/* Destination Memory Start Address register bits */ +#define DEST_START_ADDR_OFFSET 0x10u +#define DEST_START_ADDR_MASK 0xFFFFFFFFu +#define DEST_START_ADDR_SHIFT 0x0u + +/***************************************************************************//** + * Block Size register details + */ +#define BLK_SIZE_REG_OFFSET 0x14u + +/* Destination Memory Start Address register bits */ +#define BLK_SIZE_OFFSET 0x14u +#define BLK_SIZE_MASK 0xFFFFFFFFu +#define BLK_SIZE_SHIFT 0x0u + +#ifdef __cplusplus +} +#endif + +#endif /* MIV_UDMA_APB_REGISTERS */ diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_watchdog/miv_watchdog.c b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_watchdog/miv_watchdog.c new file mode 100644 index 0000000..525928a --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_watchdog/miv_watchdog.c @@ -0,0 +1,94 @@ +/******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * Mi-V Watchdog Soft IP bare-metal driver. This module is delivered as part of + * Extended Sub System(ESS) MIV_ESS. + * Please refer to miv_watchdog.h file for more information. + */ + +#include "miv_watchdog.h" + +addr_t g_this_wdog; + +/***************************************************************************//* + * Please refer to miv_watchdog.h for more info about this function + */ +void +MIV_WDOG_init +( + addr_t base_addr +) +{ + /* Register the Mi-V Watchdog base address to the driver */ + g_this_wdog = base_addr; +} + +/***************************************************************************//* + * Please refer to miv_watchdog.h for more info about this function + */ +uint8_t MIV_WDOG_configure +( + const miv_wdog_config_t *config +) +{ + uint8_t error = 0u; + + /* check load value and trigger max value */ + if (config->timeout_val <= MIV_WDOG_TRIGGER_MAX) + { + HAL_set_32bit_reg(g_this_wdog, WDOGTRIG,(config->timeout_val)); + } + else + { + error = 1u; + } + + if (config->time_val <= MIV_WDOG_TIMER_MAX) + { + HAL_set_32bit_reg(g_this_wdog, WDOGMSVP,(config->mvrp_val)); + } + else + { + error = 1u; + } + + HAL_set_32bit_reg_field(g_this_wdog, WDOGCNTL_NEXT_ENFORBIDDEN, + config->forbidden_en); + + /* Reload watchdog with new load if it is not in forbidden window */ + if (!(WDOGSTAT_FORBIDDEN_MASK & (HAL_get_32bit_reg(g_this_wdog, WDOGSTAT)))) + { + HAL_set_32bit_reg(g_this_wdog, WDOGRFSH, MIV_WDOG_REFRESH_KEY); + } + else + { + error = 1u; + } + + return (error); +} + +/***************************************************************************//* + * Please refer to miv_watchdog.h for more info about this function + */ +void MIV_WDOG_get_config +( + miv_wdog_config_t *config +) +{ + if (0 != g_this_wdog) + { + + config->time_val = HAL_get_32bit_reg(g_this_wdog, WDOGTIME); + + config->timeout_val = HAL_get_32bit_reg(g_this_wdog, WDOGTRIG); + + config->mvrp_val = HAL_get_32bit_reg(g_this_wdog, WDOGMSVP); + + config->forbidden_en = HAL_get_32bit_reg_field(g_this_wdog, + WDOGCNTL_NEXT_ENFORBIDDEN); + } +} + diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_watchdog/miv_watchdog.h b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_watchdog/miv_watchdog.h new file mode 100644 index 0000000..8877e55 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_watchdog/miv_watchdog.h @@ -0,0 +1,553 @@ +/******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * This file contains the application programming interface for the MI-V Soft IP + * Watchdog module driver. This module is delivered as a part of Mi-V Extended + * Sub-System(MIV_ESS). + */ +/*=========================================================================*//** + @mainpage MiV Watchdog Bare Metal Driver + + ============================================================================== + Introduction + ============================================================================== + The Mi-V Watchdog module in the MIV_ESS is used to generate a reset for the + system automatically if the software doesn't periodically update or refresh + the timer countdown register. This software driver provides set of functions + for controlling Mi-V Watchdog module as a part of bare metal system where no + operating system is available. The driver can be adapted for use as a part of + an operating system, but the implementation of the adaptation layer between + the driver and the operating system's driver model is outside the scope of the + driver. + + Mi-V Watchdog provides following features: + - Initializing the Mi-V Watchdog + - Reading current value and status of watchdog timer + - Refreshing the watchdog timer value + - Enabling, disabling and clearing timeout and Maximum Value up to which + Refresh is Permitted (MVRP) interrupts. + + ============================================================================== + Hardware Flow Dependencies + ============================================================================== + The application software should initialize and configure the Mi-V Watchdog + module the the call to the MIV_WDOG_init() and MIV_WDOG_configure() functions. + + No MIV_WDOG hardware configuration parameter are used by the driver, apart + from the MIV_WDOG base address. Hence, no additional configuration files are + required to use the driver. + + ============================================================================== + Theory of Operation + ============================================================================== + The Mi-V Watchdog driver functions are grouped into the following categories: + - Initialization and configuration + - Reading the current value and status of the watchdog timer + - Refreshing the watchdog timer value + - Support for enabling, disabling and clearing time-out and MVRP interrupts. + + -------------------------------- + Initialization and Configuration + -------------------------------- + The MIV_WDOG_init() function stores the base of MIV_WDT module in the MIV_ESS. + This base address is used by rest of the functions to access the Mi-V Watchdog + registers. Please make call this function before calling any other function + from this driver. + Note: The Mi-V Watchdog driver supports only one instance of MIV_WDT in the + hardware. + The Mi-V Watchdog driver provides the MIV_WDOG_configure() function to + configure the MIV_WDOG module with desired configuration values. It also + provides the MIV_WDOG_get_config() to read back the current configuration of + the MIV_WDOG. You can use this function to retrieve the current configurations + and then overwrite them with the application specific values, such as initial + watchdog timer value, Maximum Value (up to which) Refresh (is) Permitted, + watchdog time-out value, enable/disable forbidden region, enable/disable + MVRP interrupt and interrupt type. + + -------------------------------------------- + Reading the Watchdog Timer Value and Status + -------------------------------------------- + Mi-V Watchdog is a down counter. A refresh forbidden window can be created by + configuring the watchdog Maximum Value up to which Refresh is Permitted (MVRP). + When the current value of the watchdog timer is greater than the MVRP value, + refreshing the watchdog is forbidden. Attempting to refresh the watchdog timer + in the forbidden window will assert a timeout interrupt. The + MIV_WDOG_forbidden_status() function can be used to know whether the watchdog + timer is in forbidden window or has crossed it. By default, the forbidden + window is disabled. It can be enabled by providing an appropriate value as + parameter to the MIV_WDOG_configure() function. When the forbidden window is + disabled, any attempt to refresh the watchdog timer is ignored and the counter + keeps on down counting. + + The current value of the watchdog timer can be read using the + MIV_WDOG_current_value() function. This function can be called at any time. + + -------------------------------------------- + Refreshing the Watchdog Timer Value + -------------------------------------------- + The watchdog timer value is refreshed using the MIV_WDOG_reload() function. + The value reloaded into the watchdog timer down-counter is specified at the + configuration time with an appropriate value as parameter to the + MIV_WDOG_get_config() function. + + -------------------------------------------- + Interrupt Control + -------------------------------------------- + The Mi-V Watchdog generates two interrupts, The MVRP interrupt and + the timeout interrupt. + The MVRP interrupt is generated when the watchdog down-counter crosses the + Maximum Value up to which Refresh is Permitted (MVRP). Following functions to + control MVRP interrupt: + - MIV_WDOG_enable_mvrp_irq + - MIV_WDOG_disable_mvrp_irq + - MIV_WDOG_clear_mvrp_irq + + The timeout interrupt is generated when the watchdog down-counter crosses the + watchdog timeout value. The timeout value is a non-zero value and it can be + set to a maximum of MIV_WDOG_TRIGGER_MAX. The non-maskable interrupt is + generated when the watchdog crosses this timeout value, the down counter + keeps on down counting and a reset signal is generated when reaches zero. + Following functions to control timeout interrupt: + - MIV_WDOG_enable_timeout_irq + - MIV_WDOG_disable_timeout_irq + - MIV_WDOG_clear_timeout_irq + +*//*=========================================================================*/ + +#ifndef MIV_WATCHDOG_H_ +#define MIV_WATCHDOG_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include "miv_watchdog_regs.h" + +#ifndef LEGACY_DIR_STRUCTURE +#include "hal/hal.h" +#else +#include "hal.h" +#endif + +/****************************************************************************//* + * The following constants can be used to configure the Mi-V Watchdog where a + * zero or non-zero value such as enable or disable is to be provided as a input + * parameter as shown below: + */ +#define MIV_WDOG_ENABLE 1u +#define MIV_WDOG_DISABLE 0u + +/***************************************************************************//** + The miv_wdog_config_t type for the watchdog Configuration structure. This + type is used as a parameter for the MIV_WDOG_configure() and the + MIV_WDOG_get_config() functions. + + Following are the values as part of this structure +| Parameter | Description | +|------------------|-----------------------------------------------------------| +| time_val | The value from which the watchdog timer counts down | +| mvrp_val | The Watchdog MVRP value | +| timeout_val | The watchdog timeout value | +| forbidden_en | Enable/disable the forbidden window | +| | When set, if a refresh occurs in the forbidden window, | +| | the watchdog timeout interrupt will be generated. | + +Time calculation example: + + time_val = 0xFFFFF0u + mvrp_val = 0x989680u + timeout_val = 0x3e8u + + A prescaler = 256 is used. + Considering clock = 50Mhz + + The MVRP interrupt will happen after + (0xFFFFF0 - 0x989680) * ( 1/(50MHz/256)) + mvrp interrupt will happen after 34 sec. after system reset + + (0xFFFFF0 - 0x3e8) * ( 1/(50MHz/256)) + timeout interrupt will happen after 85 sec. after system reset + */ +typedef struct miv_wdog_config +{ + uint32_t time_val; + uint32_t mvrp_val; + uint32_t timeout_val; + uint32_t forbidden_en; + uint32_t intr_type; +}miv_wdog_config_t; + +extern addr_t g_this_wdog; + +/***************************************************************************//* + Internal constants and types +*******************************************************************************/ + +/// @cond private +#define MIV_WDOG_TRIGGER_MAX 4095u +#define MIV_WDOG_TIMER_MAX 16777200u +/// @endcond + +/*-------------------------------------------------------------------------*//* +MIV_WDOG_REFRESH_KEY +===================== + +The MIV_WDOG_REFRESH_KEY macro holds the magic value which will cause a +reload of the watchdog's down counter when written to the watchdog's +WDOGREFRESH register. +*/ +#define MIV_WDOG_REFRESH_KEY (uint32_t)0xDEADC0DEU + +/*-------------------------------------------------------------------------*//* +MIV_WDOG_FORCE_RESET_KEY +===================== +The MIV_WDOG_FORCE_RESET_KEY macro holds the magic value which will force a +reset if the watchdog is already timeout. Writing any other value or writing +TRIGGER register at other times will trigger the watchdog NMI sequence +(i.e raise a timeout interrupt) + */ +#define MIV_WDOG_FORCE_RESET_KEY (uint32_t)0xDEADU + +/***************************************************************************//** + * The MIV_WDOG_init() is used to register the Mi-V Watchdog module base + * address to the driver. + * + * Note: User should call this function before calling any other Mi-V watchdog + * driver function. + * + * @param base_addr + * The base address of the Mi-V watchdog module. This address is used by + * rest of the watchdog driver functions to access the registers. + * + * @return + * This function does not return any value. + */ +void +MIV_WDOG_init +( + addr_t base_addr +); + +/***************************************************************************//** + * The MIV_WDOG_get_config() function returns the current configurations of the + * Mi-V Watchdog. The Mi-V Watchdog is pre-initialized by the flash + * bits at the design time. When used for the first time before calling the + * MIV_WDOG_configure() function, this function will return the default + * configurations as configured at the design time. + * + * @param config + * The config parameter is used to store the current configuration of the Mi-V + * Watchdog. + * + * Please see the description of miv_wdog_config_t for details. + * + * @return + * This function does not return any value. + * + * Example: + */ +void +MIV_WDOG_get_config +( + miv_wdog_config_t* config +); + +/***************************************************************************//** + * The MIV_WDOG_configure() function configures the watchdog module. The + * Watchdog module is pre-initialized by the flash bits at the design time to the + * default values. You can reconfigure the Watchdog module using + * MIV_WDOG_configure() function. + * + * Note that the MIV_WDOG_configure() function can be used only once, as it + * writes into the TIME register. After a write into the TIME register, the TIME, + * TRIGGER and MSVP register values are frozen and can't be altered again unless + * a system reset happens. + * + * Note also that the Mi-V Watchdog is not enabled at reset, calling this function + * will start the watchdog, it cannot then be disabled and must be refreshed + * periodically. + * + * @param config + * The config parameter is the input parameter in which the configurations to + * be applied to the watchdog module are provided by the application. + * Please see the description of miv_wdog_config_t for details. + * + * @return + * This function returns a zero value when executed successfully. A non-zero + * value is returned when the configuration values are out of bound. + * + * Example: + */ +uint8_t +MIV_WDOG_configure +( + const miv_wdog_config_t * config +); + +/***************************************************************************//** + * The MIV_WDOG_reload() function causes the watchdog to reload its down-counter + * timer with the load value configured through interrupt handler. This function + * must be called regularly to avoid a system reset or a watchdog interrupt. + * + * @param + * Void + * + * @return + * This function does not return a value. + */ +static inline void +MIV_WDOG_reload +( + void +) +{ + if (0 != g_this_wdog) + { + HAL_set_32bit_reg(g_this_wdog, WDOGRFSH, MIV_WDOG_REFRESH_KEY); + } +} + +/***************************************************************************//** + * The MIV_WDOG_current_value() function returns the current value of the + * watchdog's down-counter. + * + * @param + * Void + * + * @return + * This function returns the current value of the watchdog’s down-counter as + * a 32-bit unsigned integer. + */ +static inline uint32_t +MIV_WDOG_current_value +( + void +) +{ + return (HAL_get_32bit_reg(g_this_wdog, WDOGRFSH)); +} + +/***************************************************************************//** + * The MIV_WDOG_forbidden_status() function returns the refresh status of the + * Mi-V Watchdog. + * + * @param + * Void + * + * @return + * This function returns the refresh status of the watchdog. A value of 1 + * indicates that watchdog's down-counter is within the forbidden window and + * that a reload should not be done. A value of 0 indicates that the watchdog's + * down counter is within the permitted window and that a reload is allowed. + */ +static inline uint32_t +MIV_WDOG_forbidden_status +( + void +) +{ + return (HAL_get_32bit_reg_field(g_this_wdog, WDOGSTAT_FORBIDDEN)); +} + +/***************************************************************************//** + * The MIV_WDOG_enable_mvrp_irq() function enables the MVRP interrupt. + * This interrupt is asserted when the timer countdown register leaves the + * maximum value up to which refresh is permitted (MVRP) window. + * + * @param + * Void + * + * @return + * This function does not return a value. + * + * Example: + */ +static inline void +MIV_WDOG_enable_mvrp_irq +( + void +) +{ + + if (0 != g_this_wdog) + { + HAL_set_32bit_reg_field(g_this_wdog, WDOGCNTL_NEXT_INTENT_MSVP, 0x01u); + } +} + +/***************************************************************************//** + * The MIV_WDOG_disable_mvrp_irq() function disables the generation of the + * MVRP interrupt. + * + * @param + * Void + * + * @return + * This function does not return a value. + */ +static inline void +MIV_WDOG_disable_mvrp_irq +( + void +) +{ + if (0 != g_this_wdog) + { + HAL_set_32bit_reg_field(g_this_wdog, WDOGCNTL_NEXT_INTENT_MSVP, 0x0u); + } +} + +/***************************************************************************//** + * The MIV_WDOG_clear_timeout_irq() function clears the watchdog’s timeout + * interrupt which is connected to the MIV-RV32 interrupt. Calling + * MIV_WDOG_clear_timeout_irq() results in clearing the MIV-RV32 interrupt. + * Note: You must call the MIV_WDOG_clear_timeout_irq() function as part of your + * implementation of the interrupt handler in order to prevent the same + * interrupt event re-triggering a call to the timeout ISR. + * + * @param + * Void + * + * @return + * This function does not return any value. + * + */ +static inline void +MIV_WDOG_clear_timeout_irq +( + void +) +{ + if (0 != g_this_wdog) + { + HAL_set_32bit_reg_field(g_this_wdog, WDOGSTAT_WDOG_TRIPPED, 0x01u); + /* + * Perform a second write to ensure that the first write completed before + * returning from this function. This is to account for posted writes across + * the AHB matrix. The second write ensures that the first write has + * completed and that the interrupt line has been de-asserted by the time + * the function returns. Omitting the second write may result in a delay + * in the de-assertion of the interrupt line going to the RISC-V and a + * retriggering of the interrupt. + */ + HAL_set_32bit_reg_field(g_this_wdog, WDOGSTAT_WDOG_TRIPPED, 0x01u); + } +} + +/***************************************************************************//** + * The MIV_WDOG_clear_mvrp_irq() function clears the mvrp interrupt. + * + * Note: You must call the MIV_WDOG_clear_mvrp_irq() function as part of your + * implementation of the interrupt service routine (ISR) in order to + * prevent the same interrupt event re-triggering a call to the mvrp ISR. + * + * @param + * Void + * + * @return + * This function does not return a value. + */ +static inline void +MIV_WDOG_clear_mvrp_irq +( + void +) +{ + if (0 != g_this_wdog) + { + HAL_set_32bit_reg_field(g_this_wdog, WDOGSTAT_MSVP_TRIPPED, 0x01u); + /* + * Perform a second write to ensure that the first write completed before + * returning from this function. This is to account for posted writes across + * the AHB matrix. The second write ensures that the first write has + * completed and that the interrupt line has been de-asserted by the time + * the function returns. Omitting the second write may result in a delay + * in the de-assertion of the interrupt line going to the RISC-V and a + * re-triggering of the interrupt. + */ + HAL_set_32bit_reg_field(g_this_wdog, WDOGSTAT_MSVP_TRIPPED, 0x01u); + } +} + +/***************************************************************************//** + * The MIV_WDOG_timeout_occured() function reports the occurrence of a timeout + * event. + * + * @param + * Void + * + * @return + * A zero value indicates no watchdog timeout event occurred. A value of 1 + * indicates that a timeout event occurred. + */ +static inline uint32_t +MIV_WDOG_timeout_occured +( + void +) +{ + return (HAL_get_32bit_reg_field(g_this_wdog, WDOGSTAT_TRIGGERED)); +} + +/***************************************************************************//** + * The MIV_WDOG_force_reset() function is used to force an immediate reset + * if the watchdog has already triggered. Writing any value in this condition + * will result in watchdog timeout. + * The time out interrupt WDOG_IRQ will be set to high and watchdog timer + * countdown register updated with watchdog trigger timeout register value. + * If the Watchdog has timed out, a special 16-bit value needs to be written + * to the register to force a reset on CPU_RESETN, 0xDEAD + * Then the Watchdog countdown is reset/updated with the top Watchdog Runtime + * register value. + * + * @param + * Void + * + * @return + * This function does not return a value. + */ +static inline void +MIV_WDOG_force_reset +( + void +) +{ + if (WDOGSTAT_TRIGGERED_MASK == + HAL_get_32bit_reg_field(g_this_wdog, WDOGSTAT_TRIGGERED)) + + { + HAL_set_32bit_reg(g_this_wdog, WDOGFORCE, MIV_WDOG_FORCE_RESET_KEY); + } + + else + { + HAL_set_32bit_reg(g_this_wdog, WDOGFORCE, 0x0u); + } +} + +#ifdef __cplusplus +} +#endif + +#endif /* MIV_WATCHDOG_H_ */ diff --git a/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_watchdog/miv_watchdog_regs.h b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_watchdog/miv_watchdog_regs.h new file mode 100644 index 0000000..2fca983 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/drivers/fpga_ip/miv_watchdog/miv_watchdog_regs.h @@ -0,0 +1,122 @@ + /******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * This file contains Register bit offsets and masks definitions for MI-V Soft + * IP watchdog module driver. This module is delivered as a part of Mi-V + * extended Sub-System(ESS) MIV_ESS. + */ + +#ifndef MIV_WDOG_REGISTERS +#define MIV_WDOG_REGISTERS 1u + +#ifdef __cplusplus +extern "C" { +#endif + +/*------------------------------------------------------------------------------ + * Refresh register details + */ +#define WDOGRFSH_REG_OFFSET 0x00u + +/* Refresh register bits */ +#define WDOGRFSH_OFFSET 0x00u +#define WDOGRFSH_MASK 0xFFFFFFFFu +#define WDOGRFSH_SHIFT 0u + +/*------------------------------------------------------------------------------ + * Control register details + */ +#define WDOGCNTL_REG_OFFSET 0x04u + +/* Control register next intent msvp bit */ +#define WDOGCNTL_NEXT_INTENT_MSVP_OFFSET 0x04u +#define WDOGCNTL_NEXT_INTENT_MSVP_MASK 0x01u +#define WDOGCNTL_NEXT_INTENT_MSVP_SHIFT 0u + +/* Control register next intent wdog bit */ +#define WDOGCNTL_NEXT_INTENT_WDOG_OFFSET 0x04u +#define WDOGCNTL_NEXT_INTENT_WDOG_MASK 0x02u +#define WDOGCNTL_NEXT_INTENT_WDOG_SHIFT 1u + +/* Control register next enforbidden bit */ +#define WDOGCNTL_NEXT_ENFORBIDDEN_OFFSET 0x04u +#define WDOGCNTL_NEXT_ENFORBIDDEN_MASK 0x10u +#define WDOGCNTL_NEXT_ENFORBIDDEN_SHIFT 4u + +/*------------------------------------------------------------------------------ + * Watchdog status register + */ +#define WDOGSTAT_REG_OFFSET 0x08u + +/* msvp_tripped bit */ +#define WDOGSTAT_MSVP_TRIPPED_OFFSET 0x08u +#define WDOGSTAT_MSVP_TRIPPED_MASK 0x01u +#define WDOGSTAT_MSVP_TRIPPED_SHIFT 0u + +/* WDOG Tripped bit */ +#define WDOGSTAT_WDOG_TRIPPED_OFFSET 0x08u +#define WDOGSTAT_WDOG_TRIPPED_MASK 0x02u +#define WDOGSTAT_WDOG_TRIPPED_SHIFT 1u + +/* Forbidden bit */ +#define WDOGSTAT_FORBIDDEN_OFFSET 0x08u +#define WDOGSTAT_FORBIDDEN_MASK 0x04u +#define WDOGSTAT_FORBIDDEN_SHIFT 2u + +/* Triggered bit */ +#define WDOGSTAT_TRIGGERED_OFFSET 0x08u +#define WDOGSTAT_TRIGGERED_MASK 0x08u +#define WDOGSTAT_TRIGGERED_SHIFT 3u + +/* wdoglocked bit */ +#define WDOGSTAT_WDOGLOCKED_OFFSET 0x08u +#define WDOGSTAT_WDOGLOCKED_MASK 0x10u +#define WDOGSTAT_WDOGLOCKED_SHIFT 4u + +/*------------------------------------------------------------------------------ + * Watchdog runtime register + */ +#define WDOGTIME_REG_OFFSET 0x0Cu + +/* wdogmsvp bit */ +#define WDOGTIME_WDOGVALUE_OFFSET 0x0Cu +#define WDOGTIME_WDOGVALUE_MASK 0xFFFFFFu +#define WDOGTIME_WDOGVALUE_SHIFT 0u + +/*------------------------------------------------------------------------------ + * Watchdog MVRP register + */ +#define WDOGMSVP_REG_OFFSET 0x10u + +/* wdogmsvp bit */ +#define WDOGMSVP_OFFSET 0x10u +#define WDOGMSVP_MASK 0xFFFFFFu +#define WDOGMSVP_SHIFT 0u + +/*------------------------------------------------------------------------------ + * Watchdog Trigger Timeout register + */ +#define WDOGTRIG_REG_OFFSET 0x14u + +/* wdogmsvp bit */ +#define WDOGTRIG_WDOGRST_OFFSET 0x14u +#define WDOGTRIG_WDOGRST_MASK 0xFFFFFFu +#define WDOGTRIG_WDOGRST_SHIFT 0u + +/*------------------------------------------------------------------------------ + * Watchdog Force Reset register details + */ +#define WDOGFORCE_REG_OFFSET 0x18u + +/* Refresh register bits */ +#define WDOGFORCE_OFFSET 0x18u +#define WDOGFORCE_MASK 0xFFFFFFFFu +#define WDOGFORCE_SHIFT 0u + +#ifdef __cplusplus +} +#endif + +#endif /* MIV_WATCHDOG_REGS_H_ */ diff --git a/freertos/miv-rv32-freertos-demo/src/platform/hal/cpu_types.h b/freertos/miv-rv32-freertos-demo/src/platform/hal/cpu_types.h new file mode 100644 index 0000000..ef8ab20 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/hal/cpu_types.h @@ -0,0 +1,41 @@ +/******************************************************************************* + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file cpu_types.h + * @author Microchip FPGA Embedded Systems Solutions + * @brief Type definitions which can be commonly used by the fabric-ip drivers. + * + */ +#ifndef __CPU_TYPES_H +#define __CPU_TYPES_H 1 + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef unsigned int size_t; + +/*------------------------------------------------------------------------------ + * addr_t: address type. + * Used to specify the address of peripherals present in the processor's memory + * map. + */ +typedef unsigned int addr_t; + +/*------------------------------------------------------------------------------ + * psr_t: processor state register. + * Used by HAL_disable_interrupts() and HAL_restore_interrupts() to store the + * processor's state between disabling and restoring interrupts. + */ +typedef unsigned int psr_t; + +#ifdef __cplusplus +} +#endif + +#endif /* CPU_TYPES_H */ + diff --git a/freertos/miv-rv32-freertos-demo/src/platform/hal/hal.h b/freertos/miv-rv32-freertos-demo/src/platform/hal/hal.h new file mode 100644 index 0000000..7eec17a --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/hal/hal.h @@ -0,0 +1,235 @@ +/***************************************************************************//** + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * @file hal.h + * @author Microchip FPGA Embedded Systems Solutions + * @brief Hardware abstraction layer functions for peripheral register accesses. + * + */ +#ifndef __HAL_H +#define __HAL_H 1 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "cpu_types.h" +#include "hw_reg_access.h" +#include "hal_assert.h" +/***************************************************************************//** + * Enable all interrupts at the processor level. + */ +void HAL_enable_interrupts( void ); + +/***************************************************************************//** + * Disable all interrupts at the processor core level. + * Return the interrupts enable state before disabling occurred so that it can + * later be restored. + */ +psr_t HAL_disable_interrupts( void ); + +/***************************************************************************//** + * Restore the interrupts enable state at the processor core level. + * This function is normally passed the value returned from a previous call to + * HAL_disable_interrupts(). + */ +void HAL_restore_interrupts( psr_t saved_psr ); + +/***************************************************************************//** + */ +#define FIELD_OFFSET(FIELD_NAME) (FIELD_NAME##_OFFSET) +#define FIELD_SHIFT(FIELD_NAME) (FIELD_NAME##_SHIFT) +#define FIELD_MASK(FIELD_NAME) (FIELD_NAME##_MASK) + +/***************************************************************************//** + * The macro HAL_set_32bit_reg() allows writing a 32 bits wide register. + * + * BASE_ADDR: A variable of type addr_t specifying the base address of the + * peripheral containing the register. + * REG_NAME: A string identifying the register to write. These strings are + * specified in a header file associated with the peripheral. + * VALUE: A variable of type uint32_t containing the value to write. + */ +#define HAL_set_32bit_reg(BASE_ADDR, REG_NAME, VALUE) \ + (HW_set_32bit_reg( ((BASE_ADDR) + (REG_NAME##_REG_OFFSET)), (VALUE) )) + +/***************************************************************************//** + * The macro HAL_get_32bit_reg() is used to read the value of a 32 bits wide + * register. + * + * BASE_ADDR: A variable of type addr_t specifying the base address of the + * peripheral containing the register. + * REG_NAME: A string identifying the register to read. These strings are + * specified in a header file associated with the peripheral. + * RETURN: This function-like macro returns a uint32_t value. + */ +#define HAL_get_32bit_reg(BASE_ADDR, REG_NAME) \ + (HW_get_32bit_reg( ((BASE_ADDR) + (REG_NAME##_REG_OFFSET)) )) + +/***************************************************************************//** + * The macro HAL_set_32bit_reg_field() is used to write a field within a + * 32 bits wide register. The field written can be one or more bits. + * + * BASE_ADDR: A variable of type addr_t specifying the base address of the + * peripheral containing the register. + * FIELD_NAME: A string identifying the register field to write. These strings + * are specified in a header file associated with the peripheral. + * VALUE: A variable of type uint32_t containing the field value to write. + */ +#define HAL_set_32bit_reg_field(BASE_ADDR, FIELD_NAME, VALUE) \ + (HW_set_32bit_reg_field(\ + (BASE_ADDR) + FIELD_OFFSET(FIELD_NAME),\ + FIELD_SHIFT(FIELD_NAME),\ + FIELD_MASK(FIELD_NAME),\ + (VALUE))) + +/***************************************************************************//** + * The macro HAL_get_32bit_reg_field() is used to read a register field from + * within a 32 bit wide peripheral register. The field can be one or more bits. + * + * BASE_ADDR: A variable of type addr_t specifying the base address of the + * peripheral containing the register. + * FIELD_NAME: A string identifying the register field to write. These strings + * are specified in a header file associated with the peripheral. + * RETURN: This function-like macro returns a uint32_t value. + */ +#define HAL_get_32bit_reg_field(BASE_ADDR, FIELD_NAME) \ + (HW_get_32bit_reg_field(\ + (BASE_ADDR) + FIELD_OFFSET(FIELD_NAME),\ + FIELD_SHIFT(FIELD_NAME),\ + FIELD_MASK(FIELD_NAME))) + +/***************************************************************************//** + * The macro HAL_set_16bit_reg() allows writing a 16 bits wide register. + * + * BASE_ADDR: A variable of type addr_t specifying the base address of the + * peripheral containing the register. + * REG_NAME: A string identifying the register to write. These strings are + * specified in a header file associated with the peripheral. + * VALUE: A variable of type uint_fast16_t containing the value to write. + */ +#define HAL_set_16bit_reg(BASE_ADDR, REG_NAME, VALUE) \ + (HW_set_16bit_reg( ((BASE_ADDR) + (REG_NAME##_REG_OFFSET)), (VALUE) )) + +/***************************************************************************//** + * The macro HAL_get_16bit_reg() is used to read the value of a 16 bits wide + * register. + * + * BASE_ADDR: A variable of type addr_t specifying the base address of the + * peripheral containing the register. + * REG_NAME: A string identifying the register to read. These strings are + * specified in a header file associated with the peripheral. + * RETURN: This function-like macro returns a uint16_t value. + */ +#define HAL_get_16bit_reg(BASE_ADDR, REG_NAME) \ + (HW_get_16bit_reg( (BASE_ADDR) + (REG_NAME##_REG_OFFSET) )) + +/***************************************************************************//** + * The macro HAL_set_16bit_reg_field() is used to write a field within a + * 16 bits wide register. The field written can be one or more bits. + * + * BASE_ADDR: A variable of type addr_t specifying the base address of the + * peripheral containing the register. + * FIELD_NAME: A string identifying the register field to write. These strings + * are specified in a header file associated with the peripheral. + * VALUE: A variable of type uint16_t containing the field value to write. + */ +#define HAL_set_16bit_reg_field(BASE_ADDR, FIELD_NAME, VALUE) \ + (HW_set_16bit_reg_field(\ + (BASE_ADDR) + FIELD_OFFSET(FIELD_NAME),\ + FIELD_SHIFT(FIELD_NAME),\ + FIELD_MASK(FIELD_NAME),\ + (VALUE))) + +/***************************************************************************//** + * The macro HAL_get_16bit_reg_field() is used to read a register field from + * within a 8 bit wide peripheral register. The field can be one or more bits. + * + * BASE_ADDR: A variable of type addr_t specifying the base address of the + * peripheral containing the register. + * FIELD_NAME: A string identifying the register field to write. These strings + * are specified in a header file associated with the peripheral. + * RETURN: This function-like macro returns a uint16_t value. + */ +#define HAL_get_16bit_reg_field(BASE_ADDR, FIELD_NAME) \ + (HW_get_16bit_reg_field(\ + (BASE_ADDR) + FIELD_OFFSET(FIELD_NAME),\ + FIELD_SHIFT(FIELD_NAME),\ + FIELD_MASK(FIELD_NAME))) + +/***************************************************************************//** + * The macro HAL_set_8bit_reg() allows writing a 8 bits wide register. + * + * BASE_ADDR: A variable of type addr_t specifying the base address of the + * peripheral containing the register. + * REG_NAME: A string identifying the register to write. These strings are + * specified in a header file associated with the peripheral. + * VALUE: A variable of type uint_fast8_t containing the value to write. + */ +#define HAL_set_8bit_reg(BASE_ADDR, REG_NAME, VALUE) \ + (HW_set_8bit_reg( ((BASE_ADDR) + (REG_NAME##_REG_OFFSET)), (VALUE) )) + +/***************************************************************************//** + * The macro HAL_get_8bit_reg() is used to read the value of a 8 bits wide + * register. + * + * BASE_ADDR: A variable of type addr_t specifying the base address of the + * peripheral containing the register. + * REG_NAME: A string identifying the register to read. These strings are + * specified in a header file associated with the peripheral. + * RETURN: This function-like macro returns a uint8_t value. + */ +#define HAL_get_8bit_reg(BASE_ADDR, REG_NAME) \ + (HW_get_8bit_reg( (BASE_ADDR) + (REG_NAME##_REG_OFFSET) )) + +/***************************************************************************//** + */ +#define HAL_set_8bit_reg_field(BASE_ADDR, FIELD_NAME, VALUE) \ + (HW_set_8bit_reg_field(\ + (BASE_ADDR) + FIELD_OFFSET(FIELD_NAME),\ + FIELD_SHIFT(FIELD_NAME),\ + FIELD_MASK(FIELD_NAME),\ + (VALUE))) + +/***************************************************************************//** + * The macro HAL_get_8bit_reg_field() is used to read a register field from + * within a 8 bit wide peripheral register. The field can be one or more bits. + * + * BASE_ADDR: A variable of type addr_t specifying the base address of the + * peripheral containing the register. + * FIELD_NAME: A string identifying the register field to write. These strings + * are specified in a header file associated with the peripheral. + * RETURN: This function-like macro returns a uint8_t value. + */ +#define HAL_get_8bit_reg_field(BASE_ADDR, FIELD_NAME) \ + (HW_get_8bit_reg_field(\ + (BASE_ADDR) + FIELD_OFFSET(FIELD_NAME),\ + FIELD_SHIFT(FIELD_NAME),\ + FIELD_MASK(FIELD_NAME))) + +#ifdef __cplusplus +} +#endif + +#endif /*HAL_H*/ + diff --git a/freertos/miv-rv32-freertos-demo/src/platform/hal/hal_assert.h b/freertos/miv-rv32-freertos-demo/src/platform/hal/hal_assert.h new file mode 100644 index 0000000..1e18b54 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/hal/hal_assert.h @@ -0,0 +1,47 @@ +/******************************************************************************* + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file hal_assert.h + * @author Microchip FPGA Embedded Systems Solutions + * @brief HAL assert functions + */ +#ifndef __HAL_ASSERT_HEADER +#define __HAL_ASSERT_HEADER 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/* Disable assertions if we do not recognize the compiler. */ +#if defined ( __GNUC__ ) +#if defined(NDEBUG) +/***************************************************************************//** + * HAL_ASSERT() is defined out when the NDEBUG symbol is used. + ******************************************************************************/ +#define HAL_ASSERT(CHECK) + +#else + +/***************************************************************************//** + * Default behavior for HAL_ASSERT() macro: + *------------------------------------------------------------------------------ + The behavior is toolchain specific and project setting specific. + ******************************************************************************/ +#define HAL_ASSERT(CHECK)\ + do { \ + if (!(CHECK)) \ + { \ + __asm__ volatile ("ebreak"); \ + }\ + } while(0); + +#endif /* NDEBUG */ +#endif /*__GNUC__*/ + +#ifdef __cplusplus +} +#endif +#endif /* __HAL_ASSERT_HEADER */ + diff --git a/freertos/miv-rv32-freertos-demo/src/platform/hal/hal_irq.c b/freertos/miv-rv32-freertos-demo/src/platform/hal/hal_irq.c new file mode 100644 index 0000000..95a0775 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/hal/hal_irq.c @@ -0,0 +1,45 @@ +/***************************************************************************//** + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file hal_irq.c + * @author Microchip FPGA Embedded Systems Solutions + * @brief Legacy interrupt control functions for the Microchip driver library + * hardware abstraction layer. + * + */ +#include "hal.h" +#include "miv_rv32_hal/miv_rv32_hal.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/*------------------------------------------------------------------------------ + * + */ +void HAL_enable_interrupts(void) { + MRV_enable_interrupts(); +} + +/*------------------------------------------------------------------------------ + * + */ +psr_t HAL_disable_interrupts(void) { + psr_t psr; + psr = read_csr(mstatus); + MRV_disable_interrupts(); + return(psr); +} + +/*------------------------------------------------------------------------------ + * + */ +void HAL_restore_interrupts(psr_t saved_psr) { + write_csr(mstatus, saved_psr); +} + +#ifdef __cplusplus +} +#endif \ No newline at end of file diff --git a/freertos/miv-rv32-freertos-demo/src/platform/hal/hw_macros.h b/freertos/miv-rv32-freertos-demo/src/platform/hal/hw_macros.h new file mode 100644 index 0000000..189609c --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/hal/hw_macros.h @@ -0,0 +1,106 @@ +/******************************************************************************* + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file hw_macros.h + * @author Microchip FPGA Embedded Systems Solutions + * @brief Hardware registers access macros. + * + * THE MACROS DEFINED IN THIS FILE ARE DEPRECATED. DO NOT USE FOR NEW + * DEVELOPMENT. + * + * These macros are used to access peripheral registers. They allow access to + * 8, 16 and 32 bit wide registers. All accesses to peripheral registers should + * be done through these macros in order to ease porting across different + * processors/bus architectures. + * + * Some of these macros also allow access to a specific register field. + * + */ +#ifndef __HW_REGISTER_MACROS_H +#define __HW_REGISTER_MACROS_H 1 +#ifdef __cplusplus +extern "C" { +#endif + +/*------------------------------------------------------------------------------ + * 32 bits registers access: + */ +#define HW_get_uint32_reg(BASE_ADDR, REG_OFFSET) (*((uint32_t volatile *)(BASE_ADDR + REG_OFFSET##_REG_OFFSET))) + +#define HW_set_uint32_reg(BASE_ADDR, REG_OFFSET, VALUE) (*((uint32_t volatile *)(BASE_ADDR + REG_OFFSET##_REG_OFFSET)) = (VALUE)) + +#define HW_set_uint32_reg_field(BASE_ADDR, FIELD, VALUE) \ + (*((uint32_t volatile *)(BASE_ADDR + FIELD##_OFFSET)) = \ + ( \ + (uint32_t) \ + ( \ + (*((uint32_t volatile *)(BASE_ADDR + FIELD##_OFFSET))) & ~FIELD##_MASK) | \ + (uint32_t)(((VALUE) << FIELD##_SHIFT) & FIELD##_MASK) \ + ) \ + ) + +#define HW_get_uint32_reg_field( BASE_ADDR, FIELD ) \ + (( (*((uint32_t volatile *)(BASE_ADDR + FIELD##_OFFSET))) & FIELD##_MASK) >> FIELD##_SHIFT) + +/*------------------------------------------------------------------------------ + * 32 bits memory access: + */ +#define HW_get_uint32(BASE_ADDR) (*((uint32_t volatile *)(BASE_ADDR))) + +#define HW_set_uint32(BASE_ADDR, VALUE) (*((uint32_t volatile *)(BASE_ADDR)) = (VALUE)) + +/*------------------------------------------------------------------------------ + * 16 bits registers access: + */ +#define HW_get_uint16_reg(BASE_ADDR, REG_OFFSET) (*((uint16_t volatile *)(BASE_ADDR + REG_OFFSET##_REG_OFFSET))) + +#define HW_set_uint16_reg(BASE_ADDR, REG_OFFSET, VALUE) (*((uint16_t volatile *)(BASE_ADDR + REG_OFFSET##_REG_OFFSET)) = (VALUE)) + +#define HW_set_uint16_reg_field(BASE_ADDR, FIELD, VALUE) \ + (*((uint16_t volatile *)(BASE_ADDR + FIELD##_OFFSET)) = \ + ( \ + (uint16_t) \ + ( \ + (*((uint16_t volatile *)(BASE_ADDR + FIELD##_OFFSET))) & ~FIELD##_MASK) | \ + (uint16_t)(((VALUE) << FIELD##_SHIFT) & FIELD##_MASK) \ + ) \ + ) + +#define HW_get_uint16_reg_field( BASE_ADDR, FIELD ) \ + (( (*((uint16_t volatile *)(BASE_ADDR + FIELD##_OFFSET))) & FIELD##_MASK) >> FIELD##_SHIFT) + +/*------------------------------------------------------------------------------ + * 8 bits registers access: + */ +#define HW_get_uint8_reg(BASE_ADDR, REG_OFFSET) (*((uint8_t volatile *)(BASE_ADDR + REG_OFFSET##_REG_OFFSET))) + +#define HW_set_uint8_reg(BASE_ADDR, REG_OFFSET, VALUE) (*((uint8_t volatile *)(BASE_ADDR + REG_OFFSET##_REG_OFFSET)) = (VALUE)) + +#define HW_set_uint8_reg_field(BASE_ADDR, FIELD, VALUE) \ + (*((uint8_t volatile *)(BASE_ADDR + FIELD##_OFFSET)) = \ + ( \ + (uint8_t) \ + ( \ + (*((uint8_t volatile *)(BASE_ADDR + FIELD##_OFFSET))) & ~FIELD##_MASK) | \ + (uint8_t)(((VALUE) << FIELD##_SHIFT) & FIELD##_MASK) \ + ) \ + ) + +#define HW_get_uint8_reg_field( BASE_ADDR, FIELD ) \ + (( (*((uint8_t volatile *)(BASE_ADDR + FIELD##_OFFSET))) & FIELD##_MASK) >> FIELD##_SHIFT) + +/*------------------------------------------------------------------------------ + * 8 bits memory access: + */ +#define HW_get_uint8(BASE_ADDR) (*((uint8_t volatile *)(BASE_ADDR))) + +#define HW_set_uint8(BASE_ADDR, VALUE) (*((uint8_t volatile *)(BASE_ADDR)) = (VALUE)) + +#ifdef __cplusplus +extern "C" { +#endif + +#endif /* __HW_REGISTER_MACROS_H */ + diff --git a/freertos/miv-rv32-freertos-demo/src/platform/hal/hw_reg_access.S b/freertos/miv-rv32-freertos-demo/src/platform/hal/hw_reg_access.S new file mode 100644 index 0000000..dd29223 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/hal/hw_reg_access.S @@ -0,0 +1,215 @@ +/***************************************************************************//** + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file hw_reg_access.S + * @author Microchip FPGA Embedded Systems Solutions + * @brief Hardware registers access functions. + * The implementation of these function is platform and toolchain specific. + * The functions declared here are implemented using assembler as part of the + * processor/toolchain specific HAL. This implementation is for the combination + * of the 32 bit RISC-V processors and GNU tool chain. + * + */ + +.section .text + .globl HW_set_32bit_reg + .globl HW_get_32bit_reg + .globl HW_set_32bit_reg_field + .globl HW_get_32bit_reg_field + .globl HW_set_16bit_reg + .globl HW_get_16bit_reg + .globl HW_set_16bit_reg_field + .globl HW_get_16bit_reg_field + .globl HW_set_8bit_reg + .globl HW_get_8bit_reg + .globl HW_set_8bit_reg_field + .globl HW_get_8bit_reg_field + + +/***************************************************************************//** + * HW_set_32bit_reg is used to write the content of a 32 bits wide peripheral + * register. + * + * a0: addr_t reg_addr + * a1: uint32_t value + */ +HW_set_32bit_reg: + sw a1, 0(a0) + ret + +/***************************************************************************//** + * HW_get_32bit_reg is used to read the content of a 32 bits wide peripheral + * register. + * + * a0: addr_t reg_addr + + * @return 32 bits value read from the peripheral register. + */ +HW_get_32bit_reg: + lw a0, 0(a0) + ret + +/***************************************************************************//** + * HW_set_32bit_reg_field is used to set the content of a field in a 32 bits + * wide peripheral register. + * + * a0: addr_t reg_addr + * a1: int_fast8_t shift + * a2: uint32_t mask + * a3: uint32_t value + */ +HW_set_32bit_reg_field: + mv t3, a3 + sll t3, t3, a1 + and t3, t3, a2 + lw t1, 0(a0) + mv t2, a2 + not t2, t2 + and t1, t1, t2 + or t1, t1, t3 + sw t1, 0(a0) + ret + +/***************************************************************************//** + * HW_get_32bit_reg_field is used to read the content of a field out of a + * 32 bits wide peripheral register. + * + * a0: addr_t reg_addr + * a1: int_fast8_t shift + * a2: uint32_t mask + * + * @return 32 bits value containing the register field value specified + * as parameter. + */ +HW_get_32bit_reg_field: + lw a0, 0(a0) + and a0, a0, a2 + srl a0, a0, a1 + ret + +/***************************************************************************//** + * HW_set_16bit_reg is used to write the content of a 16 bits wide peripheral + * register. + * + * a0: addr_t reg_addr + * a1: uint_fast16_t value + */ +HW_set_16bit_reg: + sh a1, 0(a0) + ret + +/***************************************************************************//** + * HW_get_16bit_reg is used to read the content of a 16 bits wide peripheral + * register. + * + * a0: addr_t reg_addr + + * @return 16 bits value read from the peripheral register. + */ +HW_get_16bit_reg: + lh a0, (a0) + ret + +/***************************************************************************//** + * HW_set_16bit_reg_field is used to set the content of a field in a 16 bits + * wide peripheral register. + * + * a0: addr_t reg_addr + * a1: int_fast8_t shift + * a2: uint_fast16_t mask + * a3: uint_fast16_t value + * @param value Value to be written in the specified field. + */ +HW_set_16bit_reg_field: + mv t3, a3 + sll t3, t3, a1 + and t3, t3, a2 + lh t1, 0(a0) + mv t2, a2 + not t2, t2 + and t1, t1, t2 + or t1, t1, t3 + sh t1, 0(a0) + ret + +/***************************************************************************//** + * HW_get_16bit_reg_field is used to read the content of a field from a + * 16 bits wide peripheral register. + * + * a0: addr_t reg_addr + * a1: int_fast8_t shift + * a2: uint_fast16_t mask + * + * @return 16 bits value containing the register field value specified + * as parameter. + */ +HW_get_16bit_reg_field: + lh a0, 0(a0) + and a0, a0, a2 + srl a0, a0, a1 + ret + +/***************************************************************************//** + * HW_set_8bit_reg is used to write the content of a 8 bits wide peripheral + * register. + * + * a0: addr_t reg_addr + * a1: uint_fast8_t value + */ +HW_set_8bit_reg: + sb a1, 0(a0) + ret + +/***************************************************************************//** + * HW_get_8bit_reg is used to read the content of a 8 bits wide peripheral + * register. + * + * a0: addr_t reg_addr + + * @return 8 bits value read from the peripheral register. + */ +HW_get_8bit_reg: + lb a0, 0(a0) + ret + +/***************************************************************************//** + * HW_set_8bit_reg_field is used to set the content of a field in a 8 bits + * wide peripheral register. + * + * a0: addr_t reg_addr, + * a1: int_fast8_t shift + * a2: uint_fast8_t mask + * a3: uint_fast8_t value + */ +HW_set_8bit_reg_field: + mv t3, a3 + sll t3, t3, a1 + and t3, t3, a2 + lb t1, 0(a0) + mv t2, a2 + not t2, t2 + and t1, t1, t2 + or t1, t1, t3 + sb t1, 0(a0) + ret + +/***************************************************************************//** + * HW_get_8bit_reg_field is used to read the content of a field from a + * 8 bits wide peripheral register. + * + * a0: addr_t reg_addr + * a1: int_fast8_t shift + * a2: uint_fast8_t mask + * + * @return 8 bits value containing the register field value specified + * as parameter. + */ +HW_get_8bit_reg_field: + lb a0, 0(a0) + and a0, a0, a2 + srl a0, a0, a1 + ret + +.end diff --git a/freertos/miv-rv32-freertos-demo/src/platform/hal/hw_reg_access.h b/freertos/miv-rv32-freertos-demo/src/platform/hal/hw_reg_access.h new file mode 100644 index 0000000..1a24309 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/hal/hw_reg_access.h @@ -0,0 +1,239 @@ +/***************************************************************************//** + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file hw_reg_access.S + * @author Microchip FPGA Embedded Systems Solutions + * @brief Hardware registers access functions. + * The implementation of these function is platform and tool-chain specific. + * The functions declared here are implemented using assembler as part of the + * processor/tool-chain specific HAL. This implementation is for the combination + * of the 32 bit RISC-V processors and GNU tool chain. + * + */ +#ifndef __HW_REG_ACCESS +#define __HW_REG_ACCESS +#ifdef __cplusplus +extern "C" { +#endif + +#include "cpu_types.h" +/***************************************************************************//** + * HW_set_32bit_reg is used to write the content of a 32 bits wide peripheral + * register. + * + * @param reg_addr Address in the processor's memory map of the register to + * write. + * @param value Value to be written into the peripheral register. + */ +void +HW_set_32bit_reg +( + addr_t reg_addr, + uint32_t value +); + +/***************************************************************************//** + * HW_get_32bit_reg is used to read the content of a 32 bits wide peripheral + * register. + * + * @param reg_addr Address in the processor's memory map of the register to + * read. + * @return 32 bits value read from the peripheral register. + */ +uint32_t +HW_get_32bit_reg +( + addr_t reg_addr +); + +/***************************************************************************//** + * HW_set_32bit_reg_field is used to set the content of a field in a 32 bits + * wide peripheral register. + * + * @param reg_addr Address in the processor's memory map of the register to + * be written. + * @param shift Bit offset of the register field to be read within the + * register. + * @param mask Bit mask to be applied to the raw register value to filter + * out the other register fields values. + * @param value Value to be written in the specified field. + */ +void +HW_set_32bit_reg_field +( + addr_t reg_addr, + int_fast8_t shift, + uint32_t mask, + uint32_t value +); + +/***************************************************************************//** + * HW_get_32bit_reg_field is used to read the content of a field out of a + * 32 bits wide peripheral register. + * + * @param reg_addr Address in the processor's memory map of the register to + * read. + * @param shift Bit offset of the register field to be written within the + * register. + * @param mask Bit mask to be applied to the raw register value to filter + * out the other register fields values. + * + * @return 32 bits value containing the register field value specified + * as parameter. + */ +uint32_t +HW_get_32bit_reg_field +( + addr_t reg_addr, + int_fast8_t shift, + uint32_t mask +); + +/***************************************************************************//** + * HW_set_16bit_reg is used to write the content of a 16 bits wide peripheral + * register. + * + * @param reg_addr Address in the processor's memory map of the register to + * write. + * @param value Value to be written into the peripheral register. + */ +void +HW_set_16bit_reg +( + addr_t reg_addr, + uint_fast16_t value +); + +/***************************************************************************//** + * HW_get_16bit_reg is used to read the content of a 16 bits wide peripheral + * register. + * + * @param reg_addr Address in the processor's memory map of the register to + * read. + * @return 16 bits value read from the peripheral register. + */ +uint16_t +HW_get_16bit_reg +( + addr_t reg_addr +); + +/***************************************************************************//** + * HW_set_16bit_reg_field is used to set the content of a field in a 16 bits + * wide peripheral register. + * + * @param reg_addr Address in the processor's memory map of the register to + * be written. + * @param shift Bit offset of the register field to be read within the + * register. + * @param mask Bit mask to be applied to the raw register value to filter + * out the other register fields values. + * @param value Value to be written in the specified field. + */ +void HW_set_16bit_reg_field +( + addr_t reg_addr, + int_fast8_t shift, + uint_fast16_t mask, + uint_fast16_t value +); + +/***************************************************************************//** + * HW_get_16bit_reg_field is used to read the content of a field from a + * 16 bits wide peripheral register. + * + * @param reg_addr Address in the processor's memory map of the register to + * read. + * @param shift Bit offset of the register field to be written within the + * register. + * @param mask Bit mask to be applied to the raw register value to filter + * out the other register fields values. + * + * @return 16 bits value containing the register field value specified + * as parameter. + */ +uint16_t HW_get_16bit_reg_field +( + addr_t reg_addr, + int_fast8_t shift, + uint_fast16_t mask +); + +/***************************************************************************//** + * HW_set_8bit_reg is used to write the content of a 8 bits wide peripheral + * register. + * + * @param reg_addr Address in the processor's memory map of the register to + * write. + * @param value Value to be written into the peripheral register. + */ +void +HW_set_8bit_reg +( + addr_t reg_addr, + uint_fast8_t value +); + +/***************************************************************************//** + * HW_get_8bit_reg is used to read the content of a 8 bits wide peripheral + * register. + * + * @param reg_addr Address in the processor's memory map of the register to + * read. + * @return 8 bits value read from the peripheral register. + */ +uint8_t +HW_get_8bit_reg +( + addr_t reg_addr +); + +/***************************************************************************//** + * HW_set_8bit_reg_field is used to set the content of a field in a 8 bits + * wide peripheral register. + * + * @param reg_addr Address in the processor's memory map of the register to + * be written. + * @param shift Bit offset of the register field to be read within the + * register. + * @param mask Bit mask to be applied to the raw register value to filter + * out the other register fields values. + * @param value Value to be written in the specified field. + */ +void HW_set_8bit_reg_field +( + addr_t reg_addr, + int_fast8_t shift, + uint_fast8_t mask, + uint_fast8_t value +); + +/***************************************************************************//** + * HW_get_8bit_reg_field is used to read the content of a field from a + * 8 bits wide peripheral register. + * + * @param reg_addr Address in the processor's memory map of the register to + * read. + * @param shift Bit offset of the register field to be written within the + * register. + * @param mask Bit mask to be applied to the raw register value to filter + * out the other register fields values. + * + * @return 8 bits value containing the register field value specified + * as parameter. + */ +uint8_t HW_get_8bit_reg_field +( + addr_t reg_addr, + int_fast8_t shift, + uint_fast8_t mask +); + +#ifdef __cplusplus +} +#endif + +#endif /* __HW_REG_ACCESS */ + diff --git a/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv-rv32-execute-in-place.ld b/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv-rv32-execute-in-place.ld new file mode 100644 index 0000000..bfb4698 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv-rv32-execute-in-place.ld @@ -0,0 +1,154 @@ +/******************************************************************************* + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * file name : miv-rv32-execute-in-place.ld + * Mi-V soft processor linker script for creating a SoftConsole downloadable + * image executing from a one address space whereas the data, sdata and stack + * sections are placed in another address space. This could be used in cases such + * as: + * 1) When using MIV_RV32, the reset vector points to the LSRAM at address + * 0x80000000 and the data, sdata, bss and stack sections are placed in the + * TCM region. + * + * 2) Executing from a Non Volatile memory. The actual memory will depend on + * the FPGA platform. For exameple, it could be the eNVM on SmartFusion2, + * Igloo2 or on-board non-volatile memory which supports code execution. + * + * NOTE: Modify the memory section addresses and the sizes according to your + * Libero design. + * + * To know more about the memory map of the MIV_RV32 based Libero design, open + * the MIV_RV32 IP configurator and look for "Reset Vector Address" and the + * "Memory Map" tab. + * + */ + +OUTPUT_ARCH( "riscv" ) +ENTRY(_start) + + +MEMORY +{ + rom (rx) : ORIGIN = 0x80000000, LENGTH = 16k + ram (rwx) : ORIGIN = 0x80004000, LENGTH = 16k +} + +STACK_SIZE = 1k; /* needs to be calculated for your application */ +HEAP_SIZE = 1k; /* needs to be calculated for your application */ + +SECTIONS +{ + .entry : ALIGN(0x10) + { + KEEP (*(SORT_NONE(.entry))) + . = ALIGN(0x10); + } > rom + + .text : ALIGN(0x10) + { + KEEP (*(SORT_NONE(.text.entry))) + . = ALIGN(0x10); + *(.text .text.* .gnu.linkonce.t.*) + *(.plt) + . = ALIGN(0x10); + + KEEP (*crtbegin.o(.ctors)) + KEEP (*(EXCLUDE_FILE (*crtend.o) .ctors)) + KEEP (*(SORT(.ctors.*))) + KEEP (*crtend.o(.ctors)) + KEEP (*crtbegin.o(.dtors)) + KEEP (*(EXCLUDE_FILE (*crtend.o) .dtors)) + KEEP (*(SORT(.dtors.*))) + KEEP (*crtend.o(.dtors)) + + *(.rodata .rodata.* .gnu.linkonce.r.*) + *(.gcc_except_table) + *(.eh_frame_hdr) + *(.eh_frame) + + KEEP (*(.init)) + KEEP (*(.fini)) + + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP (*(.preinit_array)) + PROVIDE_HIDDEN (__preinit_array_end = .); + PROVIDE_HIDDEN (__init_array_start = .); + KEEP (*(SORT(.init_array.*))) + KEEP (*(.init_array)) + PROVIDE_HIDDEN (__init_array_end = .); + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP (*(.fini_array)) + KEEP (*(SORT(.fini_array.*))) + PROVIDE_HIDDEN (__fini_array_end = .); + . = ALIGN(0x10); + + } >rom + + /* short/global data section */ + .sdata : ALIGN(0x10) + { + __sdata_load = LOADADDR(.sdata); + __sdata_start = .; + PROVIDE( __global_pointer$ = . + 0x800); + *(.srodata.cst16) *(.srodata.cst8) *(.srodata.cst4) *(.srodata.cst2) + *(.srodata*) + *(.sdata .sdata.* .gnu.linkonce.s.*) + . = ALIGN(0x10); + __sdata_end = .; + } >ram AT>rom + + /* data section */ + .data : ALIGN(0x10) + { + __data_load = LOADADDR(.data); + __data_start = .; + *(.got.plt) *(.got) + *(.shdata) + *(.data .data.* .gnu.linkonce.d.*) + . = ALIGN(0x10); + __data_end = .; + } >ram AT>rom + + /* sbss section */ + .sbss : ALIGN(0x10) + { + __sbss_start = .; + *(.sbss .sbss.* .gnu.linkonce.sb.*) + *(.scommon) + . = ALIGN(0x10); + __sbss_end = .; + } > ram + + /* sbss section */ + .bss : ALIGN(0x10) + { + __bss_start = .; + *(.shbss) + *(.bss .bss.* .gnu.linkonce.b.*) + *(COMMON) + . = ALIGN(0x10); + __bss_end = .; + } > ram + + /* End of uninitialized data segment */ + _end = .; + + .heap : ALIGN(0x10) + { + __heap_start = .; + . += HEAP_SIZE; + __heap_end = .; + . = ALIGN(0x10); + _heap_end = __heap_end; + } > ram + + .stack : ALIGN(0x10) + { + __stack_bottom = .; + . += STACK_SIZE; + __stack_top = .; + } > ram +} + diff --git a/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv-rv32-ram.ld b/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv-rv32-ram.ld new file mode 100644 index 0000000..1aa2a82 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv-rv32-ram.ld @@ -0,0 +1,150 @@ +/******************************************************************************* + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * file name : miv-rv32-ram.ld + * Mi-V soft processor linker script for creating a SoftConsole downloadable + * debug image executing in SRAM. + * + * This linker script assumes that a RAM is connected at on Mi-V soft processor + * memory space pointed by the reset vector address. + * + * NOTE : Modify the memory section address and the size according to your + * Libero design. + * For example: + * 1) If you want to download and step debug at a different RAM memory address in + * your design (For example TCM base address) than the one provided in this file. + * 2) The MIV_RV32, when used with MIV_ESS IP, provides ways to copy the executable + * HEX file from external Non-Volatile memory into the TCM at reset. In this + * case your executable must be linked to the TCM address. + * + * To know more about the memory map of the MIV_RV32 based Libero design, open + * the MIV_RV32 IP configurator and look for "Reset Vector Address" and the + * "Memory Map" tab. + * + */ + +OUTPUT_ARCH( "riscv" ) +ENTRY(_start) + +MEMORY +{ + ram (rwx) : ORIGIN = 0x80000000, LENGTH = 32k +} + +STACK_SIZE = 2k; /* needs to be calculated for your application */ +HEAP_SIZE = 1k; /* needs to be calculated for your application */ + +SECTIONS +{ + .entry : ALIGN(0x10) + { + KEEP (*(SORT_NONE(.entry))) + . = ALIGN(0x10); + } > ram + + .text : ALIGN(0x10) + { + *(.text .text.* .gnu.linkonce.t.*) + *(.plt) + . = ALIGN(0x10); + + KEEP (*crtbegin.o(.ctors)) + KEEP (*(EXCLUDE_FILE (*crtend.o) .ctors)) + KEEP (*(SORT(.ctors.*))) + KEEP (*crtend.o(.ctors)) + KEEP (*crtbegin.o(.dtors)) + KEEP (*(EXCLUDE_FILE (*crtend.o) .dtors)) + KEEP (*(SORT(.dtors.*))) + KEEP (*crtend.o(.dtors)) + + *(.rodata .rodata.* .gnu.linkonce.r.*) + *(.gcc_except_table) + *(.eh_frame_hdr) + *(.eh_frame) + + KEEP (*(.init)) + KEEP (*(.fini)) + + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP (*(.preinit_array)) + PROVIDE_HIDDEN (__preinit_array_end = .); + PROVIDE_HIDDEN (__init_array_start = .); + KEEP (*(SORT(.init_array.*))) + KEEP (*(.init_array)) + PROVIDE_HIDDEN (__init_array_end = .); + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP (*(.fini_array)) + KEEP (*(SORT(.fini_array.*))) + PROVIDE_HIDDEN (__fini_array_end = .); + . = ALIGN(0x10); + + } > ram + + /* short/global data section */ + .sdata : ALIGN(0x10) + { + __sdata_load = LOADADDR(.sdata); + __sdata_start = .; + PROVIDE( __global_pointer$ = . + 0x800); + *(.srodata.cst16) *(.srodata.cst8) *(.srodata.cst4) *(.srodata.cst2) + *(.srodata*) + *(.sdata .sdata.* .gnu.linkonce.s.*) + . = ALIGN(0x10); + __sdata_end = .; + } > ram + + /* data section */ + .data : ALIGN(0x10) + { + __data_load = LOADADDR(.data); + __data_start = .; + *(.got.plt) *(.got) + *(.shdata) + *(.data .data.* .gnu.linkonce.d.*) + . = ALIGN(0x10); + __data_end = .; + } > ram + + /* sbss section */ + .sbss : ALIGN(0x10) + { + __sbss_start = .; + *(.sbss .sbss.* .gnu.linkonce.sb.*) + *(.scommon) + . = ALIGN(0x10); + __sbss_end = .; + } > ram + + /* sbss section */ + .bss : ALIGN(0x10) + { + __bss_start = .; + *(.shbss) + *(.bss .bss.* .gnu.linkonce.b.*) + *(COMMON) + . = ALIGN(0x10); + __bss_end = .; + } > ram + + /* End of uninitialized data segment */ + _end = .; + + .heap : ALIGN(0x10) + { + __heap_start = .; + . += HEAP_SIZE; + __heap_end = .; + . = ALIGN(0x10); + _heap_end = __heap_end; + } > ram + + .stack : ALIGN(0x10) + { + __stack_bottom = .; + . += STACK_SIZE; + __stack_top = .; + } > ram +} + diff --git a/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv_rv32_assert.h b/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv_rv32_assert.h new file mode 100644 index 0000000..b3912ed --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv_rv32_assert.h @@ -0,0 +1,40 @@ +/******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * MIV_RV32 HAL Embedded Software + * + */ +#ifndef MIV_RV32_ASSERT_HEADER +#define MIV_RV32_ASSERT_HEADER + +#ifdef __cplusplus +extern "C" { +#endif + +/***************************************************************************//** + * ASSERT() implementation. + ******************************************************************************/ +/* Disable assertions if we do not recognize the compiler. */ +#if defined ( __GNUC__ ) +#if defined(NDEBUG) +#define ASSERT(CHECK) +#else +#define ASSERT(CHECK)\ + do { \ + if (!(CHECK)) \ + { \ + __asm__ volatile ("ebreak"); \ + }\ + } while(0); + +#endif /* NDEBUG check */ +#endif /* compiler check */ + +#ifdef __cplusplus +} +#endif + +#endif /* MIV_RV32_ASSERT_HEADER */ + diff --git a/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv_rv32_entry.S b/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv_rv32_entry.S new file mode 100644 index 0000000..26b382e --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv_rv32_entry.S @@ -0,0 +1,1319 @@ +/******************************************************************************* + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file miv_rv32_entry.S + * @author Microchip FPGA Embedded Systems Solutions + * @brief Mi-V soft processor vectors, trap handling and startup code. + * + */ +#ifndef ENTRY_S +#define ENTRY_S + +#define A_EXTENSION_MASK 0x00000001u +#define MTVEC_MODE_BIT_MASK 0x00000003u +#define MTVEC_VECTORED_MODE_VAL 0x00000001u + +#define MTIMEH_ADDR 0x200BFFCu + +#if __riscv_xlen == 64 +# define LREG ld +# define SREG sd +# define REGBYTES 8 +#else +# define LREG lw +# define SREG sw +# define REGBYTES 4 +#endif + +#if __riscv_flen == 32 +# define F_LREG flw +# define F_SREG fsw +#elif __riscv_flen == 64 +# define F_LREG fld +# define F_SREG fsd +#endif + +#ifdef __riscv_flen +# define portCONTEXT_SIZE 64 +#else +# define portCONTEXT_SIZE 32 +#endif + + .section .entry, "ax" + .globl _start + +_start: + j handle_reset + +/* Some of the Mi-V soft IP cores support compressed 'C' extension. If the Mi-V + core in your design doesn't support 'C' extension and you enable 'C' extension + in firmware project compiler options, then it would result in a trap. For this + case, we are avoiding compressed instruction here so you can put a breakpoint + at the jump and you can at least look at mcause, mepc and get some hints + about the crash. */ +trap_entry: +.option push +.option norvc +j generic_trap_handler +.option pop + .word 0 + .word 0 + +sw_trap_entry: + j vector_sw_trap_handler +#ifdef __riscv_compressed + .2byte 0 +#endif + .word 0 + .word 0 + .word 0 + +tmr_trap_entry: + j vector_tmr_trap_handler +#ifdef __riscv_compressed + .2byte 0 +#endif + .word 0 + .word 0 + .word 0 + +ext_trap_entry: + j vector_ext_trap_handler +#ifdef __riscv_compressed + .2byte 0 +#endif + .word 0 + .word 0 + .word 0 + .word 0 + +#ifndef MIV_LEGACY_RV32 +MGEUI_trap_entry: + j vector_MGEUI_trap_handler +#ifdef __riscv_compressed + .2byte 0 +#endif + +MGECI_trap_entry: + j vector_MGECI_trap_handler +#ifdef __riscv_compressed + .2byte 0 +#endif + .word 0 + .word 0 + .word 0 + .word 0 + .word 0 + .word 0 + +MSYS_EI0_trap_entry: + j vector_MSYS_EI0_trap_handler +#ifdef __riscv_compressed + .2byte 0 +#endif + +MSYS_EI1_trap_entry: + j vector_MSYS_EI1_trap_handler +#ifdef __riscv_compressed + .2byte 0 +#endif + +MSYS_EI2_trap_entry: + j vector_MSYS_EI2_trap_handler +#ifdef __riscv_compressed + .2byte 0 +#endif + +MSYS_EI3_trap_entry: + j vector_MSYS_EI3_trap_handler +#ifdef __riscv_compressed + .2byte 0 +#endif + +MSYS_EI4_trap_entry: + j vector_MSYS_EI4_trap_handler +#ifdef __riscv_compressed + .2byte 0 +#endif + +MSYS_EI5_trap_entry: + j vector_MSYS_EI5_trap_handler +#ifdef __riscv_compressed + .2byte 0 +#endif + +#ifdef __riscv_compressed + .2byte 0 +#endif + +OPSRV_trap_entry: + j vector_OPSRV_IRQHandler +#endif /* MIV_LEGACY_RV32 */ + +.align 4 +generic_trap_handler: + addi sp, sp, -portCONTEXT_SIZE*REGBYTES +.align 4 + SREG x1, 0 * REGBYTES(sp) + SREG x2, 1 * REGBYTES(sp) + SREG x3, 2 * REGBYTES(sp) + SREG x4, 3 * REGBYTES(sp) + SREG x5, 4 * REGBYTES(sp) + SREG x6, 5 * REGBYTES(sp) + SREG x7, 6 * REGBYTES(sp) + SREG x8, 7 * REGBYTES(sp) + SREG x9, 8 * REGBYTES(sp) + SREG x10, 9 * REGBYTES(sp) + SREG x11, 10 * REGBYTES(sp) + SREG x12, 11 * REGBYTES(sp) + SREG x13, 12 * REGBYTES(sp) + SREG x14, 13 * REGBYTES(sp) + SREG x15, 14 * REGBYTES(sp) + SREG x16, 15 * REGBYTES(sp) + SREG x17, 16 * REGBYTES(sp) + SREG x18, 17 * REGBYTES(sp) + SREG x19, 18 * REGBYTES(sp) + SREG x20, 19 * REGBYTES(sp) + SREG x21, 20 * REGBYTES(sp) + SREG x22, 21 * REGBYTES(sp) + SREG x23, 22 * REGBYTES(sp) + SREG x24, 23 * REGBYTES(sp) + SREG x25, 24 * REGBYTES(sp) + SREG x26, 25 * REGBYTES(sp) + SREG x27, 26 * REGBYTES(sp) + SREG x28, 27 * REGBYTES(sp) + SREG x29, 28 * REGBYTES(sp) + SREG x30, 29 * REGBYTES(sp) + SREG x31, 30 * REGBYTES(sp) + #if __riscv_flen > 0 + F_SREG f0, 32 * REGBYTES(sp) + F_SREG f1, 33 * REGBYTES(sp) + F_SREG f2, 34 * REGBYTES(sp) + F_SREG f3, 35 * REGBYTES(sp) + F_SREG f4, 36 * REGBYTES(sp) + F_SREG f5, 37 * REGBYTES(sp) + F_SREG f6, 38 * REGBYTES(sp) + F_SREG f7, 39 * REGBYTES(sp) + F_SREG f8, 40 * REGBYTES(sp) + F_SREG f9, 41 * REGBYTES(sp) + F_SREG f10, 42 * REGBYTES(sp) + F_SREG f11, 43 * REGBYTES(sp) + F_SREG f12, 44 * REGBYTES(sp) + F_SREG f13, 45 * REGBYTES(sp) + F_SREG f14, 46 * REGBYTES(sp) + F_SREG f15, 47 * REGBYTES(sp) + F_SREG f16, 48 * REGBYTES(sp) + F_SREG f17, 49 * REGBYTES(sp) + F_SREG f18, 50 * REGBYTES(sp) + F_SREG f19, 51 * REGBYTES(sp) + F_SREG f20, 52 * REGBYTES(sp) + F_SREG f21, 53 * REGBYTES(sp) + F_SREG f22, 54 * REGBYTES(sp) + F_SREG f23, 55 * REGBYTES(sp) + F_SREG f24, 56 * REGBYTES(sp) + F_SREG f25, 57 * REGBYTES(sp) + F_SREG f26, 58 * REGBYTES(sp) + F_SREG f27, 59 * REGBYTES(sp) + F_SREG f28, 60 * REGBYTES(sp) + F_SREG f29, 61 * REGBYTES(sp) + F_SREG f30, 62 * REGBYTES(sp) + F_SREG f31, 63 * REGBYTES(sp) + #endif + + csrr a0, mcause + csrr a1, mepc + jal handle_trap + j generic_restore + +vector_sw_trap_handler: + addi sp, sp, -portCONTEXT_SIZE*REGBYTES + + SREG x1, 0 * REGBYTES(sp) + SREG x2, 1 * REGBYTES(sp) + SREG x3, 2 * REGBYTES(sp) + SREG x4, 3 * REGBYTES(sp) + SREG x5, 4 * REGBYTES(sp) + SREG x6, 5 * REGBYTES(sp) + SREG x7, 6 * REGBYTES(sp) + SREG x8, 7 * REGBYTES(sp) + SREG x9, 8 * REGBYTES(sp) + SREG x10, 9 * REGBYTES(sp) + SREG x11, 10 * REGBYTES(sp) + SREG x12, 11 * REGBYTES(sp) + SREG x13, 12 * REGBYTES(sp) + SREG x14, 13 * REGBYTES(sp) + SREG x15, 14 * REGBYTES(sp) + SREG x16, 15 * REGBYTES(sp) + SREG x17, 16 * REGBYTES(sp) + SREG x18, 17 * REGBYTES(sp) + SREG x19, 18 * REGBYTES(sp) + SREG x20, 19 * REGBYTES(sp) + SREG x21, 20 * REGBYTES(sp) + SREG x22, 21 * REGBYTES(sp) + SREG x23, 22 * REGBYTES(sp) + SREG x24, 23 * REGBYTES(sp) + SREG x25, 24 * REGBYTES(sp) + SREG x26, 25 * REGBYTES(sp) + SREG x27, 26 * REGBYTES(sp) + SREG x28, 27 * REGBYTES(sp) + SREG x29, 28 * REGBYTES(sp) + SREG x30, 29 * REGBYTES(sp) + SREG x31, 30 * REGBYTES(sp) + #if __riscv_flen > 0 + F_SREG f0, 32 * REGBYTES(sp) + F_SREG f1, 33 * REGBYTES(sp) + F_SREG f2, 34 * REGBYTES(sp) + F_SREG f3, 35 * REGBYTES(sp) + F_SREG f4, 36 * REGBYTES(sp) + F_SREG f5, 37 * REGBYTES(sp) + F_SREG f6, 38 * REGBYTES(sp) + F_SREG f7, 39 * REGBYTES(sp) + F_SREG f8, 40 * REGBYTES(sp) + F_SREG f9, 41 * REGBYTES(sp) + F_SREG f10, 42 * REGBYTES(sp) + F_SREG f11, 43 * REGBYTES(sp) + F_SREG f12, 44 * REGBYTES(sp) + F_SREG f13, 45 * REGBYTES(sp) + F_SREG f14, 46 * REGBYTES(sp) + F_SREG f15, 47 * REGBYTES(sp) + F_SREG f16, 48 * REGBYTES(sp) + F_SREG f17, 49 * REGBYTES(sp) + F_SREG f18, 50 * REGBYTES(sp) + F_SREG f19, 51 * REGBYTES(sp) + F_SREG f20, 52 * REGBYTES(sp) + F_SREG f21, 53 * REGBYTES(sp) + F_SREG f22, 54 * REGBYTES(sp) + F_SREG f23, 55 * REGBYTES(sp) + F_SREG f24, 56 * REGBYTES(sp) + F_SREG f25, 57 * REGBYTES(sp) + F_SREG f26, 58 * REGBYTES(sp) + F_SREG f27, 59 * REGBYTES(sp) + F_SREG f28, 60 * REGBYTES(sp) + F_SREG f29, 61 * REGBYTES(sp) + F_SREG f30, 62 * REGBYTES(sp) + F_SREG f31, 63 * REGBYTES(sp) + #endif + + jal handle_m_soft_interrupt + j generic_restore + +vector_tmr_trap_handler: + addi sp, sp, -portCONTEXT_SIZE*REGBYTES + + SREG x1, 0 * REGBYTES(sp) + SREG x2, 1 * REGBYTES(sp) + SREG x3, 2 * REGBYTES(sp) + SREG x4, 3 * REGBYTES(sp) + SREG x5, 4 * REGBYTES(sp) + SREG x6, 5 * REGBYTES(sp) + SREG x7, 6 * REGBYTES(sp) + SREG x8, 7 * REGBYTES(sp) + SREG x9, 8 * REGBYTES(sp) + SREG x10, 9 * REGBYTES(sp) + SREG x11, 10 * REGBYTES(sp) + SREG x12, 11 * REGBYTES(sp) + SREG x13, 12 * REGBYTES(sp) + SREG x14, 13 * REGBYTES(sp) + SREG x15, 14 * REGBYTES(sp) + SREG x16, 15 * REGBYTES(sp) + SREG x17, 16 * REGBYTES(sp) + SREG x18, 17 * REGBYTES(sp) + SREG x19, 18 * REGBYTES(sp) + SREG x20, 19 * REGBYTES(sp) + SREG x21, 20 * REGBYTES(sp) + SREG x22, 21 * REGBYTES(sp) + SREG x23, 22 * REGBYTES(sp) + SREG x24, 23 * REGBYTES(sp) + SREG x25, 24 * REGBYTES(sp) + SREG x26, 25 * REGBYTES(sp) + SREG x27, 26 * REGBYTES(sp) + SREG x28, 27 * REGBYTES(sp) + SREG x29, 28 * REGBYTES(sp) + SREG x30, 29 * REGBYTES(sp) + SREG x31, 30 * REGBYTES(sp) + #if __riscv_flen > 0 + F_SREG f0, 32 * REGBYTES(sp) + F_SREG f1, 33 * REGBYTES(sp) + F_SREG f2, 34 * REGBYTES(sp) + F_SREG f3, 35 * REGBYTES(sp) + F_SREG f4, 36 * REGBYTES(sp) + F_SREG f5, 37 * REGBYTES(sp) + F_SREG f6, 38 * REGBYTES(sp) + F_SREG f7, 39 * REGBYTES(sp) + F_SREG f8, 40 * REGBYTES(sp) + F_SREG f9, 41 * REGBYTES(sp) + F_SREG f10, 42 * REGBYTES(sp) + F_SREG f11, 43 * REGBYTES(sp) + F_SREG f12, 44 * REGBYTES(sp) + F_SREG f13, 45 * REGBYTES(sp) + F_SREG f14, 46 * REGBYTES(sp) + F_SREG f15, 47 * REGBYTES(sp) + F_SREG f16, 48 * REGBYTES(sp) + F_SREG f17, 49 * REGBYTES(sp) + F_SREG f18, 50 * REGBYTES(sp) + F_SREG f19, 51 * REGBYTES(sp) + F_SREG f20, 52 * REGBYTES(sp) + F_SREG f21, 53 * REGBYTES(sp) + F_SREG f22, 54 * REGBYTES(sp) + F_SREG f23, 55 * REGBYTES(sp) + F_SREG f24, 56 * REGBYTES(sp) + F_SREG f25, 57 * REGBYTES(sp) + F_SREG f26, 58 * REGBYTES(sp) + F_SREG f27, 59 * REGBYTES(sp) + F_SREG f28, 60 * REGBYTES(sp) + F_SREG f29, 61 * REGBYTES(sp) + F_SREG f30, 62 * REGBYTES(sp) + F_SREG f31, 63 * REGBYTES(sp) + #endif + + jal handle_m_timer_interrupt + j generic_restore + +vector_ext_trap_handler: + addi sp, sp, -portCONTEXT_SIZE*REGBYTES + + SREG x1, 0 * REGBYTES(sp) + SREG x2, 1 * REGBYTES(sp) + SREG x3, 2 * REGBYTES(sp) + SREG x4, 3 * REGBYTES(sp) + SREG x5, 4 * REGBYTES(sp) + SREG x6, 5 * REGBYTES(sp) + SREG x7, 6 * REGBYTES(sp) + SREG x8, 7 * REGBYTES(sp) + SREG x9, 8 * REGBYTES(sp) + SREG x10, 9 * REGBYTES(sp) + SREG x11, 10 * REGBYTES(sp) + SREG x12, 11 * REGBYTES(sp) + SREG x13, 12 * REGBYTES(sp) + SREG x14, 13 * REGBYTES(sp) + SREG x15, 14 * REGBYTES(sp) + SREG x16, 15 * REGBYTES(sp) + SREG x17, 16 * REGBYTES(sp) + SREG x18, 17 * REGBYTES(sp) + SREG x19, 18 * REGBYTES(sp) + SREG x20, 19 * REGBYTES(sp) + SREG x21, 20 * REGBYTES(sp) + SREG x22, 21 * REGBYTES(sp) + SREG x23, 22 * REGBYTES(sp) + SREG x24, 23 * REGBYTES(sp) + SREG x25, 24 * REGBYTES(sp) + SREG x26, 25 * REGBYTES(sp) + SREG x27, 26 * REGBYTES(sp) + SREG x28, 27 * REGBYTES(sp) + SREG x29, 28 * REGBYTES(sp) + SREG x30, 29 * REGBYTES(sp) + SREG x31, 30 * REGBYTES(sp) + #if __riscv_flen > 0 + F_SREG f0, 32 * REGBYTES(sp) + F_SREG f1, 33 * REGBYTES(sp) + F_SREG f2, 34 * REGBYTES(sp) + F_SREG f3, 35 * REGBYTES(sp) + F_SREG f4, 36 * REGBYTES(sp) + F_SREG f5, 37 * REGBYTES(sp) + F_SREG f6, 38 * REGBYTES(sp) + F_SREG f7, 39 * REGBYTES(sp) + F_SREG f8, 40 * REGBYTES(sp) + F_SREG f9, 41 * REGBYTES(sp) + F_SREG f10, 42 * REGBYTES(sp) + F_SREG f11, 43 * REGBYTES(sp) + F_SREG f12, 44 * REGBYTES(sp) + F_SREG f13, 45 * REGBYTES(sp) + F_SREG f14, 46 * REGBYTES(sp) + F_SREG f15, 47 * REGBYTES(sp) + F_SREG f16, 48 * REGBYTES(sp) + F_SREG f17, 49 * REGBYTES(sp) + F_SREG f18, 50 * REGBYTES(sp) + F_SREG f19, 51 * REGBYTES(sp) + F_SREG f20, 52 * REGBYTES(sp) + F_SREG f21, 53 * REGBYTES(sp) + F_SREG f22, 54 * REGBYTES(sp) + F_SREG f23, 55 * REGBYTES(sp) + F_SREG f24, 56 * REGBYTES(sp) + F_SREG f25, 57 * REGBYTES(sp) + F_SREG f26, 58 * REGBYTES(sp) + F_SREG f27, 59 * REGBYTES(sp) + F_SREG f28, 60 * REGBYTES(sp) + F_SREG f29, 61 * REGBYTES(sp) + F_SREG f30, 62 * REGBYTES(sp) + F_SREG f31, 63 * REGBYTES(sp) + #endif + +#ifdef MIV_LEGACY_RV32 + jal handle_m_ext_interrupt +#else + jal External_IRQHandler +#endif /* MIV_LEGACY_RV32 */ + j generic_restore + +#ifndef MIV_LEGACY_RV32 +vector_MGEUI_trap_handler: + addi sp, sp, -portCONTEXT_SIZE*REGBYTES + + SREG x1, 0 * REGBYTES(sp) + SREG x2, 1 * REGBYTES(sp) + SREG x3, 2 * REGBYTES(sp) + SREG x4, 3 * REGBYTES(sp) + SREG x5, 4 * REGBYTES(sp) + SREG x6, 5 * REGBYTES(sp) + SREG x7, 6 * REGBYTES(sp) + SREG x8, 7 * REGBYTES(sp) + SREG x9, 8 * REGBYTES(sp) + SREG x10, 9 * REGBYTES(sp) + SREG x11, 10 * REGBYTES(sp) + SREG x12, 11 * REGBYTES(sp) + SREG x13, 12 * REGBYTES(sp) + SREG x14, 13 * REGBYTES(sp) + SREG x15, 14 * REGBYTES(sp) + SREG x16, 15 * REGBYTES(sp) + SREG x17, 16 * REGBYTES(sp) + SREG x18, 17 * REGBYTES(sp) + SREG x19, 18 * REGBYTES(sp) + SREG x20, 19 * REGBYTES(sp) + SREG x21, 20 * REGBYTES(sp) + SREG x22, 21 * REGBYTES(sp) + SREG x23, 22 * REGBYTES(sp) + SREG x24, 23 * REGBYTES(sp) + SREG x25, 24 * REGBYTES(sp) + SREG x26, 25 * REGBYTES(sp) + SREG x27, 26 * REGBYTES(sp) + SREG x28, 27 * REGBYTES(sp) + SREG x29, 28 * REGBYTES(sp) + SREG x30, 29 * REGBYTES(sp) + SREG x31, 30 * REGBYTES(sp) + #if __riscv_flen > 0 + F_SREG f0, 32 * REGBYTES(sp) + F_SREG f1, 33 * REGBYTES(sp) + F_SREG f2, 34 * REGBYTES(sp) + F_SREG f3, 35 * REGBYTES(sp) + F_SREG f4, 36 * REGBYTES(sp) + F_SREG f5, 37 * REGBYTES(sp) + F_SREG f6, 38 * REGBYTES(sp) + F_SREG f7, 39 * REGBYTES(sp) + F_SREG f8, 40 * REGBYTES(sp) + F_SREG f9, 41 * REGBYTES(sp) + F_SREG f10, 42 * REGBYTES(sp) + F_SREG f11, 43 * REGBYTES(sp) + F_SREG f12, 44 * REGBYTES(sp) + F_SREG f13, 45 * REGBYTES(sp) + F_SREG f14, 46 * REGBYTES(sp) + F_SREG f15, 47 * REGBYTES(sp) + F_SREG f16, 48 * REGBYTES(sp) + F_SREG f17, 49 * REGBYTES(sp) + F_SREG f18, 50 * REGBYTES(sp) + F_SREG f19, 51 * REGBYTES(sp) + F_SREG f20, 52 * REGBYTES(sp) + F_SREG f21, 53 * REGBYTES(sp) + F_SREG f22, 54 * REGBYTES(sp) + F_SREG f23, 55 * REGBYTES(sp) + F_SREG f24, 56 * REGBYTES(sp) + F_SREG f25, 57 * REGBYTES(sp) + F_SREG f26, 58 * REGBYTES(sp) + F_SREG f27, 59 * REGBYTES(sp) + F_SREG f28, 60 * REGBYTES(sp) + F_SREG f29, 61 * REGBYTES(sp) + F_SREG f30, 62 * REGBYTES(sp) + F_SREG f31, 63 * REGBYTES(sp) + #endif + + jal MGEUI_IRQHandler + j generic_restore + +vector_MGECI_trap_handler: + addi sp, sp, -portCONTEXT_SIZE*REGBYTES + + SREG x1, 0 * REGBYTES(sp) + SREG x2, 1 * REGBYTES(sp) + SREG x3, 2 * REGBYTES(sp) + SREG x4, 3 * REGBYTES(sp) + SREG x5, 4 * REGBYTES(sp) + SREG x6, 5 * REGBYTES(sp) + SREG x7, 6 * REGBYTES(sp) + SREG x8, 7 * REGBYTES(sp) + SREG x9, 8 * REGBYTES(sp) + SREG x10, 9 * REGBYTES(sp) + SREG x11, 10 * REGBYTES(sp) + SREG x12, 11 * REGBYTES(sp) + SREG x13, 12 * REGBYTES(sp) + SREG x14, 13 * REGBYTES(sp) + SREG x15, 14 * REGBYTES(sp) + SREG x16, 15 * REGBYTES(sp) + SREG x17, 16 * REGBYTES(sp) + SREG x18, 17 * REGBYTES(sp) + SREG x19, 18 * REGBYTES(sp) + SREG x20, 19 * REGBYTES(sp) + SREG x21, 20 * REGBYTES(sp) + SREG x22, 21 * REGBYTES(sp) + SREG x23, 22 * REGBYTES(sp) + SREG x24, 23 * REGBYTES(sp) + SREG x25, 24 * REGBYTES(sp) + SREG x26, 25 * REGBYTES(sp) + SREG x27, 26 * REGBYTES(sp) + SREG x28, 27 * REGBYTES(sp) + SREG x29, 28 * REGBYTES(sp) + SREG x30, 29 * REGBYTES(sp) + SREG x31, 30 * REGBYTES(sp) + #if __riscv_flen > 0 + F_SREG f0, 32 * REGBYTES(sp) + F_SREG f1, 33 * REGBYTES(sp) + F_SREG f2, 34 * REGBYTES(sp) + F_SREG f3, 35 * REGBYTES(sp) + F_SREG f4, 36 * REGBYTES(sp) + F_SREG f5, 37 * REGBYTES(sp) + F_SREG f6, 38 * REGBYTES(sp) + F_SREG f7, 39 * REGBYTES(sp) + F_SREG f8, 40 * REGBYTES(sp) + F_SREG f9, 41 * REGBYTES(sp) + F_SREG f10, 42 * REGBYTES(sp) + F_SREG f11, 43 * REGBYTES(sp) + F_SREG f12, 44 * REGBYTES(sp) + F_SREG f13, 45 * REGBYTES(sp) + F_SREG f14, 46 * REGBYTES(sp) + F_SREG f15, 47 * REGBYTES(sp) + F_SREG f16, 48 * REGBYTES(sp) + F_SREG f17, 49 * REGBYTES(sp) + F_SREG f18, 50 * REGBYTES(sp) + F_SREG f19, 51 * REGBYTES(sp) + F_SREG f20, 52 * REGBYTES(sp) + F_SREG f21, 53 * REGBYTES(sp) + F_SREG f22, 54 * REGBYTES(sp) + F_SREG f23, 55 * REGBYTES(sp) + F_SREG f24, 56 * REGBYTES(sp) + F_SREG f25, 57 * REGBYTES(sp) + F_SREG f26, 58 * REGBYTES(sp) + F_SREG f27, 59 * REGBYTES(sp) + F_SREG f28, 60 * REGBYTES(sp) + F_SREG f29, 61 * REGBYTES(sp) + F_SREG f30, 62 * REGBYTES(sp) + F_SREG f31, 63 * REGBYTES(sp) + #endif + + jal MGECI_IRQHandler + j generic_restore + +vector_MSYS_EI0_trap_handler: + addi sp, sp, -portCONTEXT_SIZE*REGBYTES + + SREG x1, 0 * REGBYTES(sp) + SREG x2, 1 * REGBYTES(sp) + SREG x3, 2 * REGBYTES(sp) + SREG x4, 3 * REGBYTES(sp) + SREG x5, 4 * REGBYTES(sp) + SREG x6, 5 * REGBYTES(sp) + SREG x7, 6 * REGBYTES(sp) + SREG x8, 7 * REGBYTES(sp) + SREG x9, 8 * REGBYTES(sp) + SREG x10, 9 * REGBYTES(sp) + SREG x11, 10 * REGBYTES(sp) + SREG x12, 11 * REGBYTES(sp) + SREG x13, 12 * REGBYTES(sp) + SREG x14, 13 * REGBYTES(sp) + SREG x15, 14 * REGBYTES(sp) + SREG x16, 15 * REGBYTES(sp) + SREG x17, 16 * REGBYTES(sp) + SREG x18, 17 * REGBYTES(sp) + SREG x19, 18 * REGBYTES(sp) + SREG x20, 19 * REGBYTES(sp) + SREG x21, 20 * REGBYTES(sp) + SREG x22, 21 * REGBYTES(sp) + SREG x23, 22 * REGBYTES(sp) + SREG x24, 23 * REGBYTES(sp) + SREG x25, 24 * REGBYTES(sp) + SREG x26, 25 * REGBYTES(sp) + SREG x27, 26 * REGBYTES(sp) + SREG x28, 27 * REGBYTES(sp) + SREG x29, 28 * REGBYTES(sp) + SREG x30, 29 * REGBYTES(sp) + SREG x31, 30 * REGBYTES(sp) + #if __riscv_flen > 0 + F_SREG f0, 32 * REGBYTES(sp) + F_SREG f1, 33 * REGBYTES(sp) + F_SREG f2, 34 * REGBYTES(sp) + F_SREG f3, 35 * REGBYTES(sp) + F_SREG f4, 36 * REGBYTES(sp) + F_SREG f5, 37 * REGBYTES(sp) + F_SREG f6, 38 * REGBYTES(sp) + F_SREG f7, 39 * REGBYTES(sp) + F_SREG f8, 40 * REGBYTES(sp) + F_SREG f9, 41 * REGBYTES(sp) + F_SREG f10, 42 * REGBYTES(sp) + F_SREG f11, 43 * REGBYTES(sp) + F_SREG f12, 44 * REGBYTES(sp) + F_SREG f13, 45 * REGBYTES(sp) + F_SREG f14, 46 * REGBYTES(sp) + F_SREG f15, 47 * REGBYTES(sp) + F_SREG f16, 48 * REGBYTES(sp) + F_SREG f17, 49 * REGBYTES(sp) + F_SREG f18, 50 * REGBYTES(sp) + F_SREG f19, 51 * REGBYTES(sp) + F_SREG f20, 52 * REGBYTES(sp) + F_SREG f21, 53 * REGBYTES(sp) + F_SREG f22, 54 * REGBYTES(sp) + F_SREG f23, 55 * REGBYTES(sp) + F_SREG f24, 56 * REGBYTES(sp) + F_SREG f25, 57 * REGBYTES(sp) + F_SREG f26, 58 * REGBYTES(sp) + F_SREG f27, 59 * REGBYTES(sp) + F_SREG f28, 60 * REGBYTES(sp) + F_SREG f29, 61 * REGBYTES(sp) + F_SREG f30, 62 * REGBYTES(sp) + F_SREG f31, 63 * REGBYTES(sp) + #endif + + jal MSYS_EI0_IRQHandler + j generic_restore + +vector_MSYS_EI1_trap_handler: + addi sp, sp, -portCONTEXT_SIZE*REGBYTES + + SREG x1, 0 * REGBYTES(sp) + SREG x2, 1 * REGBYTES(sp) + SREG x3, 2 * REGBYTES(sp) + SREG x4, 3 * REGBYTES(sp) + SREG x5, 4 * REGBYTES(sp) + SREG x6, 5 * REGBYTES(sp) + SREG x7, 6 * REGBYTES(sp) + SREG x8, 7 * REGBYTES(sp) + SREG x9, 8 * REGBYTES(sp) + SREG x10, 9 * REGBYTES(sp) + SREG x11, 10 * REGBYTES(sp) + SREG x12, 11 * REGBYTES(sp) + SREG x13, 12 * REGBYTES(sp) + SREG x14, 13 * REGBYTES(sp) + SREG x15, 14 * REGBYTES(sp) + SREG x16, 15 * REGBYTES(sp) + SREG x17, 16 * REGBYTES(sp) + SREG x18, 17 * REGBYTES(sp) + SREG x19, 18 * REGBYTES(sp) + SREG x20, 19 * REGBYTES(sp) + SREG x21, 20 * REGBYTES(sp) + SREG x22, 21 * REGBYTES(sp) + SREG x23, 22 * REGBYTES(sp) + SREG x24, 23 * REGBYTES(sp) + SREG x25, 24 * REGBYTES(sp) + SREG x26, 25 * REGBYTES(sp) + SREG x27, 26 * REGBYTES(sp) + SREG x28, 27 * REGBYTES(sp) + SREG x29, 28 * REGBYTES(sp) + SREG x30, 29 * REGBYTES(sp) + SREG x31, 30 * REGBYTES(sp) + #if __riscv_flen > 0 + F_SREG f0, 32 * REGBYTES(sp) + F_SREG f1, 33 * REGBYTES(sp) + F_SREG f2, 34 * REGBYTES(sp) + F_SREG f3, 35 * REGBYTES(sp) + F_SREG f4, 36 * REGBYTES(sp) + F_SREG f5, 37 * REGBYTES(sp) + F_SREG f6, 38 * REGBYTES(sp) + F_SREG f7, 39 * REGBYTES(sp) + F_SREG f8, 40 * REGBYTES(sp) + F_SREG f9, 41 * REGBYTES(sp) + F_SREG f10, 42 * REGBYTES(sp) + F_SREG f11, 43 * REGBYTES(sp) + F_SREG f12, 44 * REGBYTES(sp) + F_SREG f13, 45 * REGBYTES(sp) + F_SREG f14, 46 * REGBYTES(sp) + F_SREG f15, 47 * REGBYTES(sp) + F_SREG f16, 48 * REGBYTES(sp) + F_SREG f17, 49 * REGBYTES(sp) + F_SREG f18, 50 * REGBYTES(sp) + F_SREG f19, 51 * REGBYTES(sp) + F_SREG f20, 52 * REGBYTES(sp) + F_SREG f21, 53 * REGBYTES(sp) + F_SREG f22, 54 * REGBYTES(sp) + F_SREG f23, 55 * REGBYTES(sp) + F_SREG f24, 56 * REGBYTES(sp) + F_SREG f25, 57 * REGBYTES(sp) + F_SREG f26, 58 * REGBYTES(sp) + F_SREG f27, 59 * REGBYTES(sp) + F_SREG f28, 60 * REGBYTES(sp) + F_SREG f29, 61 * REGBYTES(sp) + F_SREG f30, 62 * REGBYTES(sp) + F_SREG f31, 63 * REGBYTES(sp) + #endif + + jal MSYS_EI1_IRQHandler + j generic_restore + +vector_MSYS_EI2_trap_handler: + addi sp, sp, -portCONTEXT_SIZE*REGBYTES + + SREG x1, 0 * REGBYTES(sp) + SREG x2, 1 * REGBYTES(sp) + SREG x3, 2 * REGBYTES(sp) + SREG x4, 3 * REGBYTES(sp) + SREG x5, 4 * REGBYTES(sp) + SREG x6, 5 * REGBYTES(sp) + SREG x7, 6 * REGBYTES(sp) + SREG x8, 7 * REGBYTES(sp) + SREG x9, 8 * REGBYTES(sp) + SREG x10, 9 * REGBYTES(sp) + SREG x11, 10 * REGBYTES(sp) + SREG x12, 11 * REGBYTES(sp) + SREG x13, 12 * REGBYTES(sp) + SREG x14, 13 * REGBYTES(sp) + SREG x15, 14 * REGBYTES(sp) + SREG x16, 15 * REGBYTES(sp) + SREG x17, 16 * REGBYTES(sp) + SREG x18, 17 * REGBYTES(sp) + SREG x19, 18 * REGBYTES(sp) + SREG x20, 19 * REGBYTES(sp) + SREG x21, 20 * REGBYTES(sp) + SREG x22, 21 * REGBYTES(sp) + SREG x23, 22 * REGBYTES(sp) + SREG x24, 23 * REGBYTES(sp) + SREG x25, 24 * REGBYTES(sp) + SREG x26, 25 * REGBYTES(sp) + SREG x27, 26 * REGBYTES(sp) + SREG x28, 27 * REGBYTES(sp) + SREG x29, 28 * REGBYTES(sp) + SREG x30, 29 * REGBYTES(sp) + SREG x31, 30 * REGBYTES(sp) + #if __riscv_flen > 0 + F_SREG f0, 32 * REGBYTES(sp) + F_SREG f1, 33 * REGBYTES(sp) + F_SREG f2, 34 * REGBYTES(sp) + F_SREG f3, 35 * REGBYTES(sp) + F_SREG f4, 36 * REGBYTES(sp) + F_SREG f5, 37 * REGBYTES(sp) + F_SREG f6, 38 * REGBYTES(sp) + F_SREG f7, 39 * REGBYTES(sp) + F_SREG f8, 40 * REGBYTES(sp) + F_SREG f9, 41 * REGBYTES(sp) + F_SREG f10, 42 * REGBYTES(sp) + F_SREG f11, 43 * REGBYTES(sp) + F_SREG f12, 44 * REGBYTES(sp) + F_SREG f13, 45 * REGBYTES(sp) + F_SREG f14, 46 * REGBYTES(sp) + F_SREG f15, 47 * REGBYTES(sp) + F_SREG f16, 48 * REGBYTES(sp) + F_SREG f17, 49 * REGBYTES(sp) + F_SREG f18, 50 * REGBYTES(sp) + F_SREG f19, 51 * REGBYTES(sp) + F_SREG f20, 52 * REGBYTES(sp) + F_SREG f21, 53 * REGBYTES(sp) + F_SREG f22, 54 * REGBYTES(sp) + F_SREG f23, 55 * REGBYTES(sp) + F_SREG f24, 56 * REGBYTES(sp) + F_SREG f25, 57 * REGBYTES(sp) + F_SREG f26, 58 * REGBYTES(sp) + F_SREG f27, 59 * REGBYTES(sp) + F_SREG f28, 60 * REGBYTES(sp) + F_SREG f29, 61 * REGBYTES(sp) + F_SREG f30, 62 * REGBYTES(sp) + F_SREG f31, 63 * REGBYTES(sp) + #endif + + jal MSYS_EI2_IRQHandler + j generic_restore + +vector_MSYS_EI3_trap_handler: + addi sp, sp, -portCONTEXT_SIZE*REGBYTES + + SREG x1, 0 * REGBYTES(sp) + SREG x2, 1 * REGBYTES(sp) + SREG x3, 2 * REGBYTES(sp) + SREG x4, 3 * REGBYTES(sp) + SREG x5, 4 * REGBYTES(sp) + SREG x6, 5 * REGBYTES(sp) + SREG x7, 6 * REGBYTES(sp) + SREG x8, 7 * REGBYTES(sp) + SREG x9, 8 * REGBYTES(sp) + SREG x10, 9 * REGBYTES(sp) + SREG x11, 10 * REGBYTES(sp) + SREG x12, 11 * REGBYTES(sp) + SREG x13, 12 * REGBYTES(sp) + SREG x14, 13 * REGBYTES(sp) + SREG x15, 14 * REGBYTES(sp) + SREG x16, 15 * REGBYTES(sp) + SREG x17, 16 * REGBYTES(sp) + SREG x18, 17 * REGBYTES(sp) + SREG x19, 18 * REGBYTES(sp) + SREG x20, 19 * REGBYTES(sp) + SREG x21, 20 * REGBYTES(sp) + SREG x22, 21 * REGBYTES(sp) + SREG x23, 22 * REGBYTES(sp) + SREG x24, 23 * REGBYTES(sp) + SREG x25, 24 * REGBYTES(sp) + SREG x26, 25 * REGBYTES(sp) + SREG x27, 26 * REGBYTES(sp) + SREG x28, 27 * REGBYTES(sp) + SREG x29, 28 * REGBYTES(sp) + SREG x30, 29 * REGBYTES(sp) + SREG x31, 30 * REGBYTES(sp) + #if __riscv_flen > 0 + F_SREG f0, 32 * REGBYTES(sp) + F_SREG f1, 33 * REGBYTES(sp) + F_SREG f2, 34 * REGBYTES(sp) + F_SREG f3, 35 * REGBYTES(sp) + F_SREG f4, 36 * REGBYTES(sp) + F_SREG f5, 37 * REGBYTES(sp) + F_SREG f6, 38 * REGBYTES(sp) + F_SREG f7, 39 * REGBYTES(sp) + F_SREG f8, 40 * REGBYTES(sp) + F_SREG f9, 41 * REGBYTES(sp) + F_SREG f10, 42 * REGBYTES(sp) + F_SREG f11, 43 * REGBYTES(sp) + F_SREG f12, 44 * REGBYTES(sp) + F_SREG f13, 45 * REGBYTES(sp) + F_SREG f14, 46 * REGBYTES(sp) + F_SREG f15, 47 * REGBYTES(sp) + F_SREG f16, 48 * REGBYTES(sp) + F_SREG f17, 49 * REGBYTES(sp) + F_SREG f18, 50 * REGBYTES(sp) + F_SREG f19, 51 * REGBYTES(sp) + F_SREG f20, 52 * REGBYTES(sp) + F_SREG f21, 53 * REGBYTES(sp) + F_SREG f22, 54 * REGBYTES(sp) + F_SREG f23, 55 * REGBYTES(sp) + F_SREG f24, 56 * REGBYTES(sp) + F_SREG f25, 57 * REGBYTES(sp) + F_SREG f26, 58 * REGBYTES(sp) + F_SREG f27, 59 * REGBYTES(sp) + F_SREG f28, 60 * REGBYTES(sp) + F_SREG f29, 61 * REGBYTES(sp) + F_SREG f30, 62 * REGBYTES(sp) + F_SREG f31, 63 * REGBYTES(sp) + #endif + + jal MSYS_EI3_IRQHandler + j generic_restore + +vector_MSYS_EI4_trap_handler: + addi sp, sp, -portCONTEXT_SIZE*REGBYTES + + SREG x1, 0 * REGBYTES(sp) + SREG x2, 1 * REGBYTES(sp) + SREG x3, 2 * REGBYTES(sp) + SREG x4, 3 * REGBYTES(sp) + SREG x5, 4 * REGBYTES(sp) + SREG x6, 5 * REGBYTES(sp) + SREG x7, 6 * REGBYTES(sp) + SREG x8, 7 * REGBYTES(sp) + SREG x9, 8 * REGBYTES(sp) + SREG x10, 9 * REGBYTES(sp) + SREG x11, 10 * REGBYTES(sp) + SREG x12, 11 * REGBYTES(sp) + SREG x13, 12 * REGBYTES(sp) + SREG x14, 13 * REGBYTES(sp) + SREG x15, 14 * REGBYTES(sp) + SREG x16, 15 * REGBYTES(sp) + SREG x17, 16 * REGBYTES(sp) + SREG x18, 17 * REGBYTES(sp) + SREG x19, 18 * REGBYTES(sp) + SREG x20, 19 * REGBYTES(sp) + SREG x21, 20 * REGBYTES(sp) + SREG x22, 21 * REGBYTES(sp) + SREG x23, 22 * REGBYTES(sp) + SREG x24, 23 * REGBYTES(sp) + SREG x25, 24 * REGBYTES(sp) + SREG x26, 25 * REGBYTES(sp) + SREG x27, 26 * REGBYTES(sp) + SREG x28, 27 * REGBYTES(sp) + SREG x29, 28 * REGBYTES(sp) + SREG x30, 29 * REGBYTES(sp) + SREG x31, 30 * REGBYTES(sp) + #if __riscv_flen > 0 + F_SREG f0, 32 * REGBYTES(sp) + F_SREG f1, 33 * REGBYTES(sp) + F_SREG f2, 34 * REGBYTES(sp) + F_SREG f3, 35 * REGBYTES(sp) + F_SREG f4, 36 * REGBYTES(sp) + F_SREG f5, 37 * REGBYTES(sp) + F_SREG f6, 38 * REGBYTES(sp) + F_SREG f7, 39 * REGBYTES(sp) + F_SREG f8, 40 * REGBYTES(sp) + F_SREG f9, 41 * REGBYTES(sp) + F_SREG f10, 42 * REGBYTES(sp) + F_SREG f11, 43 * REGBYTES(sp) + F_SREG f12, 44 * REGBYTES(sp) + F_SREG f13, 45 * REGBYTES(sp) + F_SREG f14, 46 * REGBYTES(sp) + F_SREG f15, 47 * REGBYTES(sp) + F_SREG f16, 48 * REGBYTES(sp) + F_SREG f17, 49 * REGBYTES(sp) + F_SREG f18, 50 * REGBYTES(sp) + F_SREG f19, 51 * REGBYTES(sp) + F_SREG f20, 52 * REGBYTES(sp) + F_SREG f21, 53 * REGBYTES(sp) + F_SREG f22, 54 * REGBYTES(sp) + F_SREG f23, 55 * REGBYTES(sp) + F_SREG f24, 56 * REGBYTES(sp) + F_SREG f25, 57 * REGBYTES(sp) + F_SREG f26, 58 * REGBYTES(sp) + F_SREG f27, 59 * REGBYTES(sp) + F_SREG f28, 60 * REGBYTES(sp) + F_SREG f29, 61 * REGBYTES(sp) + F_SREG f30, 62 * REGBYTES(sp) + F_SREG f31, 63 * REGBYTES(sp) + #endif + + jal MSYS_EI4_IRQHandler + j generic_restore + +vector_MSYS_EI5_trap_handler: + addi sp, sp, -portCONTEXT_SIZE*REGBYTES + + SREG x1, 0 * REGBYTES(sp) + SREG x2, 1 * REGBYTES(sp) + SREG x3, 2 * REGBYTES(sp) + SREG x4, 3 * REGBYTES(sp) + SREG x5, 4 * REGBYTES(sp) + SREG x6, 5 * REGBYTES(sp) + SREG x7, 6 * REGBYTES(sp) + SREG x8, 7 * REGBYTES(sp) + SREG x9, 8 * REGBYTES(sp) + SREG x10, 9 * REGBYTES(sp) + SREG x11, 10 * REGBYTES(sp) + SREG x12, 11 * REGBYTES(sp) + SREG x13, 12 * REGBYTES(sp) + SREG x14, 13 * REGBYTES(sp) + SREG x15, 14 * REGBYTES(sp) + SREG x16, 15 * REGBYTES(sp) + SREG x17, 16 * REGBYTES(sp) + SREG x18, 17 * REGBYTES(sp) + SREG x19, 18 * REGBYTES(sp) + SREG x20, 19 * REGBYTES(sp) + SREG x21, 20 * REGBYTES(sp) + SREG x22, 21 * REGBYTES(sp) + SREG x23, 22 * REGBYTES(sp) + SREG x24, 23 * REGBYTES(sp) + SREG x25, 24 * REGBYTES(sp) + SREG x26, 25 * REGBYTES(sp) + SREG x27, 26 * REGBYTES(sp) + SREG x28, 27 * REGBYTES(sp) + SREG x29, 28 * REGBYTES(sp) + SREG x30, 29 * REGBYTES(sp) + SREG x31, 30 * REGBYTES(sp) + #if __riscv_flen > 0 + F_SREG f0, 32 * REGBYTES(sp) + F_SREG f1, 33 * REGBYTES(sp) + F_SREG f2, 34 * REGBYTES(sp) + F_SREG f3, 35 * REGBYTES(sp) + F_SREG f4, 36 * REGBYTES(sp) + F_SREG f5, 37 * REGBYTES(sp) + F_SREG f6, 38 * REGBYTES(sp) + F_SREG f7, 39 * REGBYTES(sp) + F_SREG f8, 40 * REGBYTES(sp) + F_SREG f9, 41 * REGBYTES(sp) + F_SREG f10, 42 * REGBYTES(sp) + F_SREG f11, 43 * REGBYTES(sp) + F_SREG f12, 44 * REGBYTES(sp) + F_SREG f13, 45 * REGBYTES(sp) + F_SREG f14, 46 * REGBYTES(sp) + F_SREG f15, 47 * REGBYTES(sp) + F_SREG f16, 48 * REGBYTES(sp) + F_SREG f17, 49 * REGBYTES(sp) + F_SREG f18, 50 * REGBYTES(sp) + F_SREG f19, 51 * REGBYTES(sp) + F_SREG f20, 52 * REGBYTES(sp) + F_SREG f21, 53 * REGBYTES(sp) + F_SREG f22, 54 * REGBYTES(sp) + F_SREG f23, 55 * REGBYTES(sp) + F_SREG f24, 56 * REGBYTES(sp) + F_SREG f25, 57 * REGBYTES(sp) + F_SREG f26, 58 * REGBYTES(sp) + F_SREG f27, 59 * REGBYTES(sp) + F_SREG f28, 60 * REGBYTES(sp) + F_SREG f29, 61 * REGBYTES(sp) + F_SREG f30, 62 * REGBYTES(sp) + F_SREG f31, 63 * REGBYTES(sp) + #endif + + jal MSYS_EI5_IRQHandler + j generic_restore + +vector_OPSRV_IRQHandler: + addi sp, sp, -portCONTEXT_SIZE*REGBYTES + + SREG x1, 0 * REGBYTES(sp) + SREG x2, 1 * REGBYTES(sp) + SREG x3, 2 * REGBYTES(sp) + SREG x4, 3 * REGBYTES(sp) + SREG x5, 4 * REGBYTES(sp) + SREG x6, 5 * REGBYTES(sp) + SREG x7, 6 * REGBYTES(sp) + SREG x8, 7 * REGBYTES(sp) + SREG x9, 8 * REGBYTES(sp) + SREG x10, 9 * REGBYTES(sp) + SREG x11, 10 * REGBYTES(sp) + SREG x12, 11 * REGBYTES(sp) + SREG x13, 12 * REGBYTES(sp) + SREG x14, 13 * REGBYTES(sp) + SREG x15, 14 * REGBYTES(sp) + SREG x16, 15 * REGBYTES(sp) + SREG x17, 16 * REGBYTES(sp) + SREG x18, 17 * REGBYTES(sp) + SREG x19, 18 * REGBYTES(sp) + SREG x20, 19 * REGBYTES(sp) + SREG x21, 20 * REGBYTES(sp) + SREG x22, 21 * REGBYTES(sp) + SREG x23, 22 * REGBYTES(sp) + SREG x24, 23 * REGBYTES(sp) + SREG x25, 24 * REGBYTES(sp) + SREG x26, 25 * REGBYTES(sp) + SREG x27, 26 * REGBYTES(sp) + SREG x28, 27 * REGBYTES(sp) + SREG x29, 28 * REGBYTES(sp) + SREG x30, 29 * REGBYTES(sp) + SREG x31, 30 * REGBYTES(sp) + #if __riscv_flen > 0 + F_SREG f0, 32 * REGBYTES(sp) + F_SREG f1, 33 * REGBYTES(sp) + F_SREG f2, 34 * REGBYTES(sp) + F_SREG f3, 35 * REGBYTES(sp) + F_SREG f4, 36 * REGBYTES(sp) + F_SREG f5, 37 * REGBYTES(sp) + F_SREG f6, 38 * REGBYTES(sp) + F_SREG f7, 39 * REGBYTES(sp) + F_SREG f8, 40 * REGBYTES(sp) + F_SREG f9, 41 * REGBYTES(sp) + F_SREG f10, 42 * REGBYTES(sp) + F_SREG f11, 43 * REGBYTES(sp) + F_SREG f12, 44 * REGBYTES(sp) + F_SREG f13, 45 * REGBYTES(sp) + F_SREG f14, 46 * REGBYTES(sp) + F_SREG f15, 47 * REGBYTES(sp) + F_SREG f16, 48 * REGBYTES(sp) + F_SREG f17, 49 * REGBYTES(sp) + F_SREG f18, 50 * REGBYTES(sp) + F_SREG f19, 51 * REGBYTES(sp) + F_SREG f20, 52 * REGBYTES(sp) + F_SREG f21, 53 * REGBYTES(sp) + F_SREG f22, 54 * REGBYTES(sp) + F_SREG f23, 55 * REGBYTES(sp) + F_SREG f24, 56 * REGBYTES(sp) + F_SREG f25, 57 * REGBYTES(sp) + F_SREG f26, 58 * REGBYTES(sp) + F_SREG f27, 59 * REGBYTES(sp) + F_SREG f28, 60 * REGBYTES(sp) + F_SREG f29, 61 * REGBYTES(sp) + F_SREG f30, 62 * REGBYTES(sp) + F_SREG f31, 63 * REGBYTES(sp) + #endif + + jal OPSRV_IRQHandler + j generic_restore +#endif /* MIV_LEGACY_RV32 */ + +generic_restore: + LREG x1, 0 * REGBYTES(sp) + LREG x2, 1 * REGBYTES(sp) + LREG x3, 2 * REGBYTES(sp) + LREG x4, 3 * REGBYTES(sp) + LREG x5, 4 * REGBYTES(sp) + LREG x6, 5 * REGBYTES(sp) + LREG x7, 6 * REGBYTES(sp) + LREG x8, 7 * REGBYTES(sp) + LREG x9, 8 * REGBYTES(sp) + LREG x10, 9 * REGBYTES(sp) + LREG x11, 10 * REGBYTES(sp) + LREG x12, 11 * REGBYTES(sp) + LREG x13, 12 * REGBYTES(sp) + LREG x14, 13 * REGBYTES(sp) + LREG x15, 14 * REGBYTES(sp) + LREG x16, 15 * REGBYTES(sp) + LREG x17, 16 * REGBYTES(sp) + LREG x18, 17 * REGBYTES(sp) + LREG x19, 18 * REGBYTES(sp) + LREG x20, 19 * REGBYTES(sp) + LREG x21, 20 * REGBYTES(sp) + LREG x22, 21 * REGBYTES(sp) + LREG x23, 22 * REGBYTES(sp) + LREG x24, 23 * REGBYTES(sp) + LREG x25, 24 * REGBYTES(sp) + LREG x26, 25 * REGBYTES(sp) + LREG x27, 26 * REGBYTES(sp) + LREG x28, 27 * REGBYTES(sp) + LREG x29, 28 * REGBYTES(sp) + LREG x30, 29 * REGBYTES(sp) + LREG x31, 30 * REGBYTES(sp) + #if __riscv_flen > 0 + F_LREG f0, 32 * REGBYTES(sp) + F_LREG f1, 33 * REGBYTES(sp) + F_LREG f2, 34 * REGBYTES(sp) + F_LREG f3, 35 * REGBYTES(sp) + F_LREG f4, 36 * REGBYTES(sp) + F_LREG f5, 37 * REGBYTES(sp) + F_LREG f6, 38 * REGBYTES(sp) + F_LREG f7, 39 * REGBYTES(sp) + F_LREG f8, 40 * REGBYTES(sp) + F_LREG f9, 41 * REGBYTES(sp) + F_LREG f10, 42 * REGBYTES(sp) + F_LREG f11, 43 * REGBYTES(sp) + F_LREG f12, 44 * REGBYTES(sp) + F_LREG f13, 45 * REGBYTES(sp) + F_LREG f14, 46 * REGBYTES(sp) + F_LREG f15, 47 * REGBYTES(sp) + F_LREG f16, 48 * REGBYTES(sp) + F_LREG f17, 49 * REGBYTES(sp) + F_LREG f18, 50 * REGBYTES(sp) + F_LREG f19, 51 * REGBYTES(sp) + F_LREG f20, 52 * REGBYTES(sp) + F_LREG f21, 53 * REGBYTES(sp) + F_LREG f22, 54 * REGBYTES(sp) + F_LREG f23, 55 * REGBYTES(sp) + F_LREG f24, 56 * REGBYTES(sp) + F_LREG f25, 57 * REGBYTES(sp) + F_LREG f26, 58 * REGBYTES(sp) + F_LREG f27, 59 * REGBYTES(sp) + F_LREG f28, 60 * REGBYTES(sp) + F_LREG f29, 61 * REGBYTES(sp) + F_LREG f30, 62 * REGBYTES(sp) + F_LREG f31, 63 * REGBYTES(sp) + #endif + + addi sp, sp, portCONTEXT_SIZE*REGBYTES + mret + + .section .text, "ax" +handle_reset: +/* Ensure instructions are not relaxed, since gp is not yet set */ +.option push +.option norelax + + csrwi mstatus, 0 + csrwi mie, 0 + la ra, _start + +/* Clearnig this to be on safer side as RTL doesnt seem to clear it on reset. */ +#ifndef MIV_LEGACY_RV32 + li t0, MTIMEH_ADDR + sw x0, 0(t0) +#endif + + csrr t0, misa + andi t0, t0, A_EXTENSION_MASK + bnez t0, ima_cores_setup /* Jump to IMA core handling */ + +/* For MIV_RV32 cores the mtvec exception base address is fixed at Reset vector + address + 0x4. Check the mode bits. */ + csrr t0, mtvec + andi t0, t0, MTVEC_MODE_BIT_MASK + li t1, MTVEC_VECTORED_MODE_VAL + bne t0, t1, ima_cores_setup /* Jump to IMA core handling */ + + /* When mode = 1 => this is vectored mode on MIV_RV32 core. + Verify that the trap_handler address matches the configuration in MTVEC */ + csrr t0, mtvec + andi t0, t0, 0xFFFFFFFC + la t1, trap_entry + bne t0, t1, vector_address_not_matching + j generic_reset_handling + +ima_cores_setup: + la t0, trap_entry + +#ifdef MIV_LEGACY_RV32_VECTORED_INTERRUPTS + addi t0, t0, 0x01 /* Set the mode bit for IMA cores. + For MIV_RV32 cores this is done by configurator. */ +#endif + csrw mtvec, t0 + +generic_reset_handling: +/* Copy sdata section first so that the gp is set and linker relaxation can be + used */ + la a4, __sdata_load + la a5, __sdata_start + la a6, __sdata_end + beq a4, a5, 1f /* Exit if source and dest are same */ + beq a5, a6, 1f /* Exit if section start and end addresses are same */ + call block_copy + +1: + /* initialize global pointer */ + la gp, __global_pointer$ + +.option pop + +/* Floating point support configuration */ +#ifdef __riscv_flen + csrr t0, mstatus + lui t1, 0xffffa + addi t1, t1, -1 + and t0, t0, t1 + lui t1, 0x4 + or t1, t0, t1 + csrw mstatus, t1 + + lui t0, 0x0 + fscsr t0 +#endif + call initializations + /* Initialize stack pointer */ + la sp, __stack_top + + /* Jump into C code */ + j _init + +/* Error: trap_entry is not at the expected address of reset_vector+mtvec offset + as configured in the MIV_RV32 core vectored mode */ +vector_address_not_matching: + ebreak + +initializations: +/* Initialize the .bss section */ + mv t0, ra /* Store ra for future use */ + la a5, __bss_start + la a6, __bss_end + beq a5, a6, 1f /* Section start and end address are the same */ + call zeroize_block + +1: +/* Initialize the .sbss section */ + la a5, __sbss_start + la a6, __sbss_end + beq a5, a6, 1f /* Section start and end address are the same */ + call zeroize_block + +/* Clear heap */ + la a5, __heap_start + la a6, __heap_end + beq a5, a6, 1f /* Section start and end address are the same */ + call zeroize_block + +1: +/* Copy data section */ + la a4, __data_load + la a5, __data_start + la a6, __data_end + beq a4, a5, 1f /* Exit early if source and dest are same */ + beq a5, a6, 1f /* Section start and end addresses are the same */ + call block_copy + +1: + mv ra, t0 /* Retrieve ra */ + ret + +zeroize_block: + bltu a6, a5, block_copy_error /* Error. End address is less than start */ + or a7, a6, a5 /* Check if start or end is unalined */ + andi a7, a7, 0x03u + bgtz a7, block_copy_error /* Unaligned addresses error*/ +zeroize_loop: + sw x0, 0(a5) + add a5, a5, __SIZEOF_POINTER__ + blt a5, a6, zeroize_loop + ret + +block_copy: + bltu a6, a5, block_copy_error /* Error. End address is less than start */ + or a7, a6, a5 /* Check if start or end is unalined */ + andi a7, a7, 0x03u + bgtz a7, block_copy_error /* Unaligned addresses error*/ +block_copy_loop: + lw a7, 0(a4) + sw a7, 0(a5) + addi a5, a5, 0x04 + addi a4, a4, 0x04 + blt a5, a6, block_copy_loop + j block_copy_exit + +block_copy_error: + j block_copy_error + +block_copy_exit: + ret + +#endif /*ENTRY_S*/ diff --git a/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv_rv32_hal.c b/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv_rv32_hal.c new file mode 100644 index 0000000..4c19f2c --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv_rv32_hal.c @@ -0,0 +1,372 @@ +/******************************************************************************* + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file miv_rv32_hal.c + * @author Microchip FPGA Embedded Systems Solutions + * @brief Implementation of Hardware Abstraction Layer for Mi-V soft processors + * + */ +#include +#include "miv_rv32_hal.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define SUCCESS 0U +#define ERROR 1U +#define MASK_32BIT 0xFFFFFFFFu + +/*------------------------------------------------------------------------------ + * Write in a sequence recommended by privileged spec to avoid spurious + * interrupts + + # New comparand is in a1:a0. + li t0, -1 + sw t0, mtimecmp # No smaller than old value. + sw a1, mtimecmp+4 # No smaller than new value. + sw a0, mtimecmp # New value. + */ +#ifndef MIV_RV32_EXT_TIMECMP +#define WRITE_MTIMECMP(value) MTIMECMPH = MASK_32BIT; \ + MTIMECMP = value & MASK_32BIT;\ + MTIMECMPH = (value >> 32u) & MASK_32BIT; +#else +#define WRITE_MTIMECMP(value) +#endif + +#ifndef MIV_RV32_EXT_TIMER +#define WRITE_MTIME(value) MTIME = value & MASK_32BIT;\ + MTIMEH = (value >> 32u) & MASK_32BIT; +#else +#define WRITE_MTIME(value) +#endif + +extern void Software_IRQHandler(void); + +#ifdef MIV_LEGACY_RV32 +#define MTIME_PRESCALER 100UL +/*------------------------------------------------------------------------------ + * + */ +uint8_t Invalid_IRQHandler(void); +uint8_t External_1_IRQHandler(void); +uint8_t External_2_IRQHandler(void); +uint8_t External_3_IRQHandler(void); +uint8_t External_4_IRQHandler(void); +uint8_t External_5_IRQHandler(void); +uint8_t External_6_IRQHandler(void); +uint8_t External_7_IRQHandler(void); +uint8_t External_8_IRQHandler(void); +uint8_t External_9_IRQHandler(void); +uint8_t External_10_IRQHandler(void); +uint8_t External_11_IRQHandler(void); +uint8_t External_12_IRQHandler(void); +uint8_t External_13_IRQHandler(void); +uint8_t External_14_IRQHandler(void); +uint8_t External_15_IRQHandler(void); +uint8_t External_16_IRQHandler(void); +uint8_t External_17_IRQHandler(void); +uint8_t External_18_IRQHandler(void); +uint8_t External_19_IRQHandler(void); +uint8_t External_20_IRQHandler(void); +uint8_t External_21_IRQHandler(void); +uint8_t External_22_IRQHandler(void); +uint8_t External_23_IRQHandler(void); +uint8_t External_24_IRQHandler(void); +uint8_t External_25_IRQHandler(void); +uint8_t External_26_IRQHandler(void); +uint8_t External_27_IRQHandler(void); +uint8_t External_28_IRQHandler(void); +uint8_t External_29_IRQHandler(void); +uint8_t External_30_IRQHandler(void); +uint8_t External_31_IRQHandler(void); + + +/*------------------------------------------------------------------------------ + * RISC-V interrupt handler for external interrupts. + */ +uint8_t (* const ext_irq_handler_table[32])(void) = +{ + + Invalid_IRQHandler, + External_1_IRQHandler, + External_2_IRQHandler, + External_3_IRQHandler, + External_4_IRQHandler, + External_5_IRQHandler, + External_6_IRQHandler, + External_7_IRQHandler, + External_8_IRQHandler, + External_9_IRQHandler, + External_10_IRQHandler, + External_11_IRQHandler, + External_12_IRQHandler, + External_13_IRQHandler, + External_14_IRQHandler, + External_15_IRQHandler, + External_16_IRQHandler, + External_17_IRQHandler, + External_18_IRQHandler, + External_19_IRQHandler, + External_20_IRQHandler, + External_21_IRQHandler, + External_22_IRQHandler, + External_23_IRQHandler, + External_24_IRQHandler, + External_25_IRQHandler, + External_26_IRQHandler, + External_27_IRQHandler, + External_28_IRQHandler, + External_29_IRQHandler, + External_30_IRQHandler, + External_31_IRQHandler +}; + +#else +/*------------------------------------------------------------------------------ + * Interrupt handlers as mapped into the MIE register of the MIV_RV32 + */ +extern void External_IRQHandler(void); +extern void MGEUI_IRQHandler(void); +extern void MGECI_IRQHandler(void); +extern void MSYS_EI0_IRQHandler(void); +extern void MSYS_EI1_IRQHandler(void); +extern void MSYS_EI2_IRQHandler(void); +extern void MSYS_EI3_IRQHandler(void); +extern void MSYS_EI4_IRQHandler(void); +extern void MSYS_EI5_IRQHandler(void); +extern void OPSRV_IRQHandler(void); + +#endif /* MIV_LEGACY_RV32 */ + +/*------------------------------------------------------------------------------ + * Increment value for the mtimecmp register in order to achieve a system tick + * interrupt as specified through the MRV_systick_config() function. + */ +static uint64_t g_systick_increment = 0U; +static uint64_t g_systick_cmp_value = 0U; + +/*------------------------------------------------------------------------------ + * Configure the machine timer to generate an interrupt. + */ +uint32_t MRV_systick_config(uint64_t ticks) +{ + uint32_t ret_val = ERROR; + uint64_t remainder = ticks; + + while (remainder >= MTIME_PRESCALER) + { + remainder -= MTIME_PRESCALER; + g_systick_increment++; + } + + g_systick_cmp_value = g_systick_increment + MTIME; + + if (g_systick_increment > 0U) + { + WRITE_MTIMECMP(g_systick_cmp_value); + set_csr(mie, MIP_MTIP); + MRV_enable_interrupts(); + ret_val = SUCCESS; + } + + return ret_val; +} + +/*------------------------------------------------------------------------------ + * RISC-V interrupt handler for machine timer interrupts. + */ +void handle_m_timer_interrupt(void) +{ + clear_csr(mie, MIP_MTIP); + + uint64_t mtime_at_irq = MTIME; + +#ifndef NDEBUG + static volatile uint32_t d_tick = 0u; +#endif + + while(g_systick_cmp_value < (mtime_at_irq + MTIME_DELTA)) { + g_systick_cmp_value = g_systick_cmp_value + g_systick_increment; + +#ifndef NDEBUG + d_tick += 1; +#endif + } + + /* + * Note: If d_tick > 1 it means, that a system timer interrupt has been missed. + * + * Please ensure that interrupt handlers are as short as possible to prevent + * them stopping other interrupts from being handled. For example, if a + * system timer interrupt occurs during a software interrupt, the system + * timer interrupt will not be handled until the software interrupt handling + * is complete. If the software interrupt handling time is more than one systick + * interval, it will result in d_tick > 1. + * + * If you are running the program using the debugger and halt the CPU at a breakpoint, + * MTIME will continue to increment and interrupts will be missed; resulting + * in d_tick > 1. + */ + + WRITE_MTIMECMP(g_systick_cmp_value); + + SysTick_Handler(); + + set_csr(mie, MIP_MTIP); +} + +/*------------------------------------------------------------------------------ + * RISC-V interrupt handler for software interrupts. + */ +#ifdef MIV_LEGACY_RV32 +void handle_m_ext_interrupt(void) +{ + unsigned long hart_id = read_csr(mhartid); + uint32_t int_num = PLIC->TARGET[hart_id].CLAIM_COMPLETE; + uint8_t disable = EXT_IRQ_KEEP_ENABLED; + + if (0u !=int_num) + { + disable = ext_irq_handler_table[int_num](); + + PLIC->TARGET[hart_id].CLAIM_COMPLETE = int_num; + + if(EXT_IRQ_DISABLE == disable) + { + MRV_PLIC_disable_irq((IRQn_Type)int_num); + } + } +} +#endif /* MIV_LEGACY_RV32 */ + +void handle_m_soft_interrupt(void) +{ + Software_IRQHandler(); + MRV_clear_soft_irq(); +} + +/*------------------------------------------------------------------------------ + * Trap handler. This function is invoked in the non-vectored mode. + */ +void handle_trap(uintptr_t mcause, uintptr_t mepc) +{ + if ((mcause & MCAUSE_INT) && ((mcause & MCAUSE_CAUSE) == IRQ_M_SOFT)) + { + handle_m_soft_interrupt(); + } + else if ((mcause & MCAUSE_INT) && ((mcause & MCAUSE_CAUSE) == IRQ_M_TIMER)) + { + handle_m_timer_interrupt(); + } + else if ((mcause & MCAUSE_INT) && ((mcause & MCAUSE_CAUSE) == IRQ_M_EXT)) + { +#ifdef MIV_LEGACY_RV32 + handle_m_ext_interrupt(); +#else + External_IRQHandler(); +#endif + } +#ifndef MIV_LEGACY_RV32 + else if ((mcause & MCAUSE_INT) && ((mcause & MCAUSE_CAUSE) == MSYS_EI0)) + { + MSYS_EI0_IRQHandler(); + } + else if ((mcause & MCAUSE_INT) && ((mcause & MCAUSE_CAUSE) == MSYS_EI1)) + { + MSYS_EI1_IRQHandler(); + } + else if ((mcause & MCAUSE_INT) && ((mcause & MCAUSE_CAUSE) == MSYS_EI2)) + { + MSYS_EI2_IRQHandler(); + } + else if ((mcause & MCAUSE_INT) && ((mcause & MCAUSE_CAUSE) == MSYS_EI3)) + { + MSYS_EI3_IRQHandler(); + } + else if ((mcause & MCAUSE_INT) && ((mcause & MCAUSE_CAUSE) == MSYS_EI4)) + { + MSYS_EI4_IRQHandler(); + } + else if ((mcause & MCAUSE_INT) && ((mcause & MCAUSE_CAUSE) == MSYS_EI5)) + { + MSYS_EI5_IRQHandler(); + } + else if ((mcause & MCAUSE_INT) && ((mcause & MCAUSE_CAUSE) == OPSRV_REG)) + { + OPSRV_IRQHandler(); + } + else if ((mcause & MCAUSE_INT) && ((mcause & MCAUSE_CAUSE) == MGEUI)) + { + MGEUI_IRQHandler(); + } + else if ((mcause & MCAUSE_INT) && ((mcause & MCAUSE_CAUSE) == MGECI)) + { + MGECI_IRQHandler(); + } +#endif /* MIV_LEGACY_RV32 */ + + else + { +#ifndef NDEBUG + /* + Arguments supplied to this function are mcause, mepc (exception PC) and + stack pointer. + Based on privileged-isa specification mcause values and meanings are: + + 0 Instruction address misaligned (mtval/mtval is the address) + 1 Instruction access fault (mtval/mtval is the address) + 2 Illegal instruction (mtval/mtval contains the + offending instruction opcode) + 3 Breakpoint + 4 Load address misaligned (mtval/mtval is the address) + 5 Load address fault (mtval/mtval is the address) + 6 Store/AMO address fault (mtval/mtval is the address) + 7 Store/AMO access fault (mtval/mtval is the address) + 8 Environment call from U-mode + 9 Environment call from S-mode + A Environment call from M-mode + B Instruction page fault + C Load page fault (mtval/mtval is the address) + E Store page fault (mtval/mtval is the address) + + # Please note: mtval is the newer name for register mbadaddr + # If you get a compile failure here, use the older name. + # At this point, both are supported in latest compiler, older compiler + # versions only support mbadaddr. + # See: https://github.com/riscv/riscv-gcc/issues/133 + */ + + /* interrupt pending */ + uintptr_t mip = read_csr(mip); + + /* additional info and meaning depends on mcause */ + uintptr_t mtval = read_csr(mtval); + + /* trap vector */ + uintptr_t mtvec = read_csr(mtvec); + + /* temporary, sometimes might hold temporary value of a0 */ + uintptr_t mscratch = read_csr(mscratch); + + /* status contains many smaller fields: */ + uintptr_t mstatus = read_csr(mstatus); + + /* PC value when the exception was taken*/ + uintptr_t mmepc = read_csr(mepc); + + /* breakpoint */ + __asm__("ebreak"); +#else + _exit(1 + mcause); +#endif /* NDEBUG */ + } +} + +#ifdef __cplusplus +} +#endif + diff --git a/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv_rv32_hal.h b/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv_rv32_hal.h new file mode 100644 index 0000000..45f1d5b --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv_rv32_hal.h @@ -0,0 +1,531 @@ +/******************************************************************************* + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * @file miv_rv32_hal.h + * @author Microchip FPGA Embedded Systems Solutions + * @brief Hardware Abstraction Layer functions for Mi-V soft processors + * + */ + +#ifndef RISCV_HAL_H +#define RISCV_HAL_H + +#include "miv_rv32_regs.h" +#include "miv_rv32_plic.h" +#include "miv_rv32_assert.h" + +#ifndef LEGACY_DIR_STRUCTURE +#include "fpga_design_config/fpga_design_config.h" +#else +#include "hw_platform.h" +#endif /*LEGACY_DIR_STRUCTURE*/ + +#ifdef __cplusplus +extern "C" { +#endif + +/***************************************************************************//** + * Return value from External IRQ handler. This will be used to disable the + * External interrupt. + */ +#define EXT_IRQ_KEEP_ENABLED 0U +#define EXT_IRQ_DISABLE 1U + +/***************************************************************************//** + * System tick handler. This handler function gets called when the Machine + * timer interrupt asserts. An implementation of this function should be + * provided by the application to implement the application specific machine + * timer interrupt handling. If application does not provide such implementation + * the weakly linked handler stub function implemented in riscv_hal_stubs.c gets + * linked. + */ +void SysTick_Handler(void); + +/***************************************************************************//** + * System timer tick configuration. + * Configures the machine timer to generate a system tick interrupt at regular + * intervals. + * Takes the number of system clock ticks between interrupts. + * + * Though this function can take any valid ticks value as parameter, we expect + * that, for all practical purposes, a small tick value (to generate periodic + * interrupts every few miliseconds) will be passed. If you need to generate + * periodic events in the range of seconds or more, you may use the SysTick_Handler() + * to further count the number of interrupts and hence the larger time intervals. + * + * Returns 0 if successful. + * Returns 1 if the interrupt interval cannot be achieved. + */ +uint32_t MRV_systick_config(uint64_t ticks); + +#define MTIME_DELTA 5 + +#ifdef MIV_LEGACY_RV32 +#define MSIP (*(uint32_t*)0x44000000UL) +#define MTIMECMP (*(uint32_t*)0x44004000UL) +#define MTIMECMPH (*(uint32_t*)0x44004004UL) +#define MTIME (*(uint32_t*)0x4400BFF8UL) +#define MTIMEH (*(uint32_t*)0x4400BFFCUL) + +/* To maintain backward compatibility with FreeRTOS config code */ +#define PRCI_BASE 0x44000000UL + +#else + +/* To maintain backward compatibility with FreeRTOS config code */ +#define PRCI_BASE 0x02000000UL + +/* OPSRV stands for "Offload Processor Subsystem for RISC-V" (OPSRV) on the + * MIV_RV32 IP core. Please see the handbook for more details. */ + +/* TCM ECC correctable error irq enable mask value */ +#define OPSRV_TCM_ECC_CE_IRQ 0x01u + +/* TCMECC uncorrectable error irq enable */ +#define OPSRV_TCM_ECC_UCE_IRQ 0x02u + +/* AXI write response error irq enable */ +#define OPSRV_AXI_WR_RESP_IRQ 0x10u + +#define OPSRV_BASE_ADDR 0x00006000UL + +typedef struct +{ + volatile uint32_t cfg; /*Parity is not being supported by MIV_RV32 v3.0*/ + volatile uint32_t reserved0[3]; + volatile uint32_t irq_en; /*offset 0x10*/ + volatile uint32_t irq_pend; + volatile uint32_t reserved1[2]; + volatile uint32_t soft_reg; /*offset 0x20*/ +} OPSRV_Type; + +#define OPSRV ((OPSRV_Type *)OPSRV_BASE_ADDR) + +#ifndef MIV_RV32_EXT_TIMECMP +#define MTIMECMP (*(volatile uint32_t*)0x02004000UL) +#define MTIMECMPH (*(volatile uint32_t*)0x02004004UL) +#else +#define MTIMECMP (0u) +#define MTIMECMPH (0u) +#endif + +/* On MIV_RV32IMC v2.0 and v2.1 MTIME_PRESCALER is not defined and using this + * definition will result in crash. For those core use the definition as below + * #define MTIME_PRESCALER 100u + */ +#define MTIME_PRESCALER (*(volatile uint32_t*)0x02005000UL) + +#ifndef MIV_RV32_EXT_TIMER +#define MTIME (*(volatile uint32_t*)0x0200BFF8UL) +#define MTIMEH (*(volatile uint32_t*)0x0200BFFCUL) +#else +#define MTIME (0u) +#define MTIMEH (0u) +#endif /*MIV_RV32_EXT_TIMER*/ + +/* These definitions are provided for convenient identification of the interrupts + * in the MIE/MIP registers. + * Apart from the standard software, timer and external interrupts, the names + * of the additional interrupts correspond to the names as used in the MIV_RV32 + * handbook. Please refer the MIV_RV32 handbook for more details. + * */ +#define MRV32_SOFT_IRQn MIE_3_IRQn +#define MRV32_TIMER_IRQn MIE_7_IRQn +#define MRV32_EXT_IRQn MIE_11_IRQn + +/*============================================================================== + * Interrupt numbers: + * This enum represents the interrupt enable bits in the MIE register. + */ +enum +{ + MIE_0_IRQn = (0x01u), + MIE_1_IRQn = (0x01u<<1u), + MIE_2_IRQn = (0x01u<<2u), + MIE_3_IRQn = (0x01u<<3u), /*MSIE*/ + MIE_4_IRQn = (0x01u<<4u), + MIE_5_IRQn = (0x01u<<5u), + MIE_6_IRQn = (0x01u<<6u), + MIE_7_IRQn = (0x01u<<7u), /*MTIE*/ + MIE_8_IRQn = (0x01u<<8u), + MIE_9_IRQn = (0x01u<<9u), + MIE_10_IRQn = (0x01u<<10u), + MIE_11_IRQn = (0x01u<<11u), /*MEIE*/ + MIE_12_IRQn = (0x01u<<12u), + MIE_13_IRQn = (0x01u<<13u), + MIE_14_IRQn = (0x01u<<14u), + MIE_15_IRQn = (0x01u<<15u), + MIE_16_IRQn = (0x01u<<16u), /*MGEUIE*/ + MIE_17_IRQn = (0x01u<<17u), /*MGECIE*/ + MIE_18_IRQn = (0x01u<<18u), + MIE_19_IRQn = (0x01u<<19u), + MIE_20_IRQn = (0x01u<<20u), + MIE_21_IRQn = (0x01u<<21u), + MIE_22_IRQn = (0x01u<<22u), + MIE_23_IRQn = (0x01u<<23u), + MIE_24_IRQn = (0x01u<<24u), /*MSYS_EIE0*/ + MIE_25_IRQn = (0x01u<<25u), /*MSYS_EIE1*/ + MIE_26_IRQn = (0x01u<<26u), /*MSYS_EIE2*/ + MIE_27_IRQn = (0x01u<<27u), /*MSYS_EIE3*/ + MIE_28_IRQn = (0x01u<<28u), /*MSYS_EIE4*/ + MIE_29_IRQn = (0x01u<<29u), /*MSYS_EIE5*/ + MIE_30_IRQn = (0x01u<<30u) /*OPSRV_IRQ_IE*/ + +} MRV_LOCAL_IRQn_Type; + + +#define MRV32_MGEUIE_IRQn MIE_16_IRQn +#define MRV32_MGECIE_IRQn MIE_17_IRQn +#define MRV32_MSYS_EIE0_IRQn MIE_24_IRQn +#define MRV32_MSYS_EIE1_IRQn MIE_25_IRQn +#define MRV32_MSYS_EIE2_IRQn MIE_26_IRQn +#define MRV32_MSYS_EIE3_IRQn MIE_27_IRQn +#define MRV32_MSYS_EIE4_IRQn MIE_28_IRQn +#define MRV32_MSYS_EIE5_IRQn MIE_29_IRQn +#define MRV32_MSYS_OPSRV_IRQn MIE_30_IRQn + +/***************************************************************************//** + Enable OPSRV interrupt. Parameter takes logical OR of following values + #define OPSRV_TCM_ECC_CE_IRQ 0x01u + #define OPSRV_TCM_ECC_UCE_IRQ 0x02u + #define OPSRV_AXI_WR_RESP_IRQ 0x10u + */ +static inline void MRV32_opsrv_enable_irq(uint32_t irq_mask) +{ + OPSRV->irq_en = irq_mask; +} + +/***************************************************************************//** + Disable OPSRV interrupt. Parameter takes logical OR of following values + #define OPSRV_TCM_ECC_CE_IRQ 0x01u + #define OPSRV_TCM_ECC_UCE_IRQ 0x02u + #define OPSRV_AXI_WR_RESP_IRQ 0x10u + */ +static inline void MRV32_opsrv_disable_irq(uint32_t irq_mask) +{ + OPSRV->irq_en &= ~irq_mask; +} + +/***************************************************************************//** + Clear OPSRV interrupt. Parameter takes logical OR of following values + #define OPSRV_TCM_ECC_CE_IRQ 0x01u + #define OPSRV_TCM_ECC_UCE_IRQ 0x02u + #define OPSRV_AXI_WR_RESP_IRQ 0x10u + */ +static inline void MRV32_opsrv_clear_irq(uint32_t irq_mask) +{ + OPSRV->irq_pend |= irq_mask; +} + +/***************************************************************************//** + * The function MRV32_is_gpr_ded() returns the core_gpr_ded_reset_reg bit value. + * When ECC is enabled, the core_gpr_ded_reset_reg is set when the core was + * reset due to GPR DED error. + */ +static inline uint32_t MRV32_is_gpr_ded(void) +{ + return((OPSRV->soft_reg & 0x04u) >> 0x02u); +} + +/***************************************************************************//** + * The function MRV32_clear_gpr_ded() can be used to clear the + * core_gpr_ded_reset_reg bit. When ECC is enabled, the core_gpr_ded_reset_reg + * is set when the core was previously reset due to GPR DED error. + */ +static inline void MRV32_clear_gpr_ded(void) +{ + OPSRV->soft_reg &= ~0x04u; +} + +/***************************************************************************//** + When ECC is enabled for the GPRs and if that data has a single bit error then + the data coming out of the ECC block will be corrected and will not have the + error but the data source will still have the error. + The ECC block does not write back corrected data to memory. + Therefore, if data has a single bit error, then the corrected data should be + written back to prevent the single bit error from becoming a double bit error. + The MRV32_clear_gpr_ecc_errors() can be used for that. + + Clear the pending interrupt bit after this using MRV32_mgeci_clear_irq() + function to complete the ECC error handling. + */ +static inline void MRV32_clear_gpr_ecc_errors(void) +{ + uint32_t temp; + + __asm__ __volatile__ ( + "sw x31, %0" + :"=m" (temp)); + + __asm__ volatile ( + "mv x31, x1;" + "mv x1, x31;" + + "mv x31, x2;" + "mv x2, x31;" + + "mv x31, x3;" + "mv x3, x31;" + + "mv x31, x4;" + "mv x4, x31;" + + "mv x31, x5;" + "mv x5, x31;" + + "mv x31, x6;" + "mv x6, x31;" + + "mv x31, x7;" + "mv x7, x31;" + + "mv x31, x8;" + "mv x8, x31;" + + "mv x31, x9;" + "mv x9, x31;" + + "mv x31, x10;" + "mv x10, x31;" + + "mv x31, x11;" + "mv x11, x31;" + + "mv x31, x12;" + "mv x12, x31;" + + "mv x31, x13;" + "mv x13, x31;" + + "mv x31, x14;" + "mv x14, x31;" + + "mv x31, x15;" + "mv x15, x31;" + + "mv x31, x16;" + "mv x16, x31;" + + "mv x31, x17;" + "mv x17, x31;" + + "mv x31, x18;" + "mv x18, x31;" + + "mv x31, x19;" + "mv x19, x31;" + + "mv x31, x20;" + "mv x20, x31;" + + "mv x31, x21;" + "mv x21, x31;" + + "mv x31, x22;" + "mv x22, x31;" + + "mv x31, x23;" + "mv x23, x31;" + + "mv x31, x24;" + "mv x24, x31;" + + "mv x31, x25;" + "mv x25, x31;" + + "mv x31, x26;" + "mv x26, x31;" + + "mv x31, x27;" + "mv x27, x31;" + + "mv x31, x28;" + "mv x28, x31;" + + "mv x31, x29;" + "mv x29, x31;" + + "mv x31, x30;" + "mv x30, x31;"); + + __asm__ __volatile__ ( + "lw x31, %0;" + : + :"m" (temp)); +} + +/***************************************************************************//** + * The function MRV32_enable_parity_check() is used to enable parity check on + * the TCM and it's interface transactions. This feature is not available on + * MIV_RV32 v3.0.100 soft processor core. + */ +static inline void MRV32_enable_parity_check(void) +{ + OPSRV->cfg |= 0x01u; +} + +/***************************************************************************//** + * The function MRV32_disable_parity_check() is used to disable parity check on + * the TCM and it's interface transactions. + */ +static inline void MRV32_disable_parity_check(void) +{ + OPSRV->cfg &= ~0x01u; +} + +/***************************************************************************//** + * The function MRV32_cpu_soft_reset() is used to cause a soft cpu reset on + * the MIV_RV32 soft processor core. + */ +static inline void MRV32_cpu_soft_reset(void) +{ + OPSRV->soft_reg &= ~0x01u; +} + +/***************************************************************************//** + Clear GPR ECC Uncorrectable interrupt. MGEUI interrupt is available only when + ECC is enabled in MIV_RV32 IP configurator. + */ +static inline void MRV32_mgeui_clear_irq(uint32_t irq_mask) +{ + clear_csr(mip, MRV32_MGEUIE_IRQn); +} + +/***************************************************************************//** + Clear GPR ECC correctable interrupt. MGECI interrupt is available only when + ECC is enabled in MIV_RV32 IP configurator. + */ +static inline void MRV32_mgeci_clear_irq(uint32_t irq_mask) +{ + clear_csr(mip, MRV32_MGECIE_IRQn); +} + +/***************************************************************************//** + * Enable interrupts. + This function takes a mask value as input. For each set bit in the mask value, + corresponding interrupt bit in the MIE register is enabled. + + MRV_enable_local_irq(MRV32_SOFT_IRQn | + MRV32_TIMER_IRQn | + MRV32_EXT_IRQn | + MRV32_MSYS_EIE0_IRQn | + MRV32_MSYS_OPSRV_IRQn); + */ +static inline void MRV_enable_local_irq(uint32_t mask) +{ + set_csr(mie, mask); +} + +/***************************************************************************//** + * Disable interrupts. + This function takes a mask value as input. For each set bit in the mask value, + corresponding interrupt bit in the MIE register is disabled. + + MRV_disable_local_irq(MRV32_SOFT_IRQn | + MRV32_TIMER_IRQn | + MRV32_EXT_IRQn | + MRV32_MSYS_EIE0_IRQn | + MRV32_MSYS_OPSRV_IRQn); + */ +static inline void MRV_disable_local_irq(uint32_t mask) +{ + clear_csr(mie, mask); +} + +#endif /* MIV_LEGACY_RV32 */ + +/***************************************************************************//** + * The function MRV_raise_soft_irq() raises a synchronous software interrupt + * by writing into the MSIP register. + */ +static inline void MRV_raise_soft_irq(void) +{ + set_csr(mie, MIP_MSIP); /* Enable software interrupt bit */ + +#ifdef MIV_LEGACY_RV32 + /* You need to make sure that the global interrupt is enabled */ + MSIP = 0x01; /* raise soft interrupt */ +#else + /* Raise soft IRQ on MIV_RV32 processor */ + OPSRV->soft_reg |= (1u << 1u); +#endif +} + +/***************************************************************************//** + * The function MRV_clear_soft_irq() clears a synchronous software interrupt + * by clearing the MSIP register. + */ +static inline void MRV_clear_soft_irq(void) +{ +#ifdef MIV_LEGACY_RV32 + MSIP = 0x00u; /* clear soft interrupt */ +#else + /* Clear soft IRQ on MIV_RV32 processor */ + OPSRV->soft_reg &= ~(1u << 1u); +#endif +} + +/***************************************************************************//** + * The function MRV_enable_interrupts() enables all interrupts setting the + * machine mode interrupt enable bit in MSTATUS register. + */ +static inline void MRV_enable_interrupts(void) +{ + set_csr(mstatus, MSTATUS_MIE); +} + +/***************************************************************************//** + * The function MRV_disable_interrupts() disables all interrupts clearing the + * machine mode interrupt enable bit in MSTATUS register. + */ +static inline void MRV_disable_interrupts(void) +{ + clear_csr(mstatus, MSTATUS_MPIE); + clear_csr(mstatus, MSTATUS_MIE); +} + +/***************************************************************************//** + * The function MRV_read_mtime() returns the current MTIME register value. + */ +static inline uint64_t MRV_read_mtime(void) +{ + volatile uint32_t hi = 0u; + volatile uint32_t lo = 0u; + + /* when mtime lower word is 0xFFFFFFFF, there will be rollover and + * returned value could be wrong. */ + do { + hi = MTIMEH; + lo = MTIME; + } while(hi != MTIMEH); + + return((((uint64_t)MTIMEH) << 32u) | lo); +} + +#ifdef __cplusplus +} +#endif + +#endif /* RISCV_HAL_H */ + + diff --git a/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv_rv32_init.c b/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv_rv32_init.c new file mode 100644 index 0000000..e5f811f --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv_rv32_init.c @@ -0,0 +1,39 @@ +/******************************************************************************* + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file miv_rv32_init.c + * @author Microchip FPGA Embedded Systems Solutions + * @brief Mi-V soft processor memory section initializations and start-up code. + * + */ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +extern void main(void); + +void _init(void) +{ + /* This function is a placeholder for the case where some more hardware + * specific initializations are required before jumping into the application + * code. You can implement it here. */ + + /* Jump to the application code after all initializations are completed */ + main(); +} + +/* Function called after main() finishes */ +void +_fini(void) +{ +} + +#ifdef __cplusplus +} +#endif + diff --git a/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv_rv32_plic.h b/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv_rv32_plic.h new file mode 100644 index 0000000..e3b1401 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv_rv32_plic.h @@ -0,0 +1,214 @@ +/******************************************************************************* + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file miv_rv32_plic.h + * @author Microchip FPGA Embedded Systems Solutions + * @brief Mi-V legacy RV32 soft processor PLIC access data structures and + * functions. + * Legacy RV32 soft processors are DEPRICATED. + * Migrate to MIV_RV32 v3.0 or later. + * + */ +#ifndef RISCV_PLIC_H +#define RISCV_PLIC_H + +#include +#include "miv_rv32_regs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/*============================================================================== + * Interrupt numbers: + */ +#ifdef MIV_LEGACY_RV32 +typedef enum +{ + NoInterrupt_IRQn = 0, + External_1_IRQn = 1, + External_2_IRQn = 2, + External_3_IRQn = 3, + External_4_IRQn = 4, + External_5_IRQn = 5, + External_6_IRQn = 6, + External_7_IRQn = 7, + External_8_IRQn = 8, + External_9_IRQn = 9, + External_10_IRQn = 10, + External_11_IRQn = 11, + External_12_IRQn = 12, + External_13_IRQn = 13, + External_14_IRQn = 14, + External_15_IRQn = 15, + External_16_IRQn = 16, + External_17_IRQn = 17, + External_18_IRQn = 18, + External_19_IRQn = 19, + External_20_IRQn = 20, + External_21_IRQn = 21, + External_22_IRQn = 22, + External_23_IRQn = 23, + External_24_IRQn = 24, + External_25_IRQn = 25, + External_26_IRQn = 26, + External_27_IRQn = 27, + External_28_IRQn = 28, + External_29_IRQn = 29, + External_30_IRQn = 30, + External_31_IRQn = 31 +} IRQn_Type; + +#define EXT_INTR_SOURCES 31 + +/*============================================================================== + * PLIC: Platform Level Interrupt Controller + */ +#define PLIC_BASE_ADDR 0x40000000UL + +typedef struct +{ + volatile uint32_t PRIORITY_THRESHOLD; + volatile uint32_t CLAIM_COMPLETE; + volatile uint32_t reserved[1022]; +} IRQ_Target_Type; + +typedef struct +{ + volatile uint32_t ENABLES[32]; +} Target_Enables_Type; + +typedef struct +{ + /*-------------------- Source Priority --------------------*/ + volatile uint32_t SOURCE_PRIORITY[1024]; + + /*-------------------- Pending array --------------------*/ + volatile const uint32_t PENDING_ARRAY[32]; + volatile uint32_t RESERVED1[992]; + + /*-------------------- Target enables --------------------*/ + volatile Target_Enables_Type TARGET_ENABLES[15808]; + + volatile uint32_t RESERVED2[16384]; + + /*--- Target Priority threshold and claim/complete---------*/ + IRQ_Target_Type TARGET[15872]; + +} PLIC_Type; + +#define PLIC ((PLIC_Type *)PLIC_BASE_ADDR) + +/*============================================================================== + * The function MRV_PLIC_init() initializes the PLIC controller and enables + * the global external interrupt bit. + */ +static inline void MRV_PLIC_init(void) +{ + uint32_t inc; + unsigned long hart_id = read_csr(mhartid); + + /* Disable all interrupts for the current hart. */ + for(inc = 0; inc < ((EXT_INTR_SOURCES + 32u) / 32u); ++inc) + { + PLIC->TARGET_ENABLES[hart_id].ENABLES[inc] = 0; + } + + /* Set priorities to zero. */ + for(inc = 0; inc < EXT_INTR_SOURCES; ++inc) + { + PLIC->SOURCE_PRIORITY[inc] = 0; + } + + /* Set the threshold to zero. */ + PLIC->TARGET[hart_id].PRIORITY_THRESHOLD = 0; + + /* Enable machine external interrupts. */ + set_csr(mie, MIP_MEIP); +} + +/*============================================================================== + * The function MRV_PLIC_enable_irq() enables the external interrupt for the + * interrupt number indicated by the parameter IRQn. + */ +static inline void MRV_PLIC_enable_irq(IRQn_Type IRQn) +{ + unsigned long hart_id = read_csr(mhartid); + uint32_t current = PLIC->TARGET_ENABLES[hart_id].ENABLES[IRQn / 32]; + current |= (uint32_t)1 << (IRQn % 32); + PLIC->TARGET_ENABLES[hart_id].ENABLES[IRQn / 32] = current; +} + +/*============================================================================== + * The function MRV_PLIC_disable_irq() disables the external interrupt for + * the interrupt number indicated by the parameter IRQn. + + * NOTE: + * This function can be used to disable the external interrupt from outside + * external interrupt handler function. + * This function MUST NOT be used from within the External Interrupt handler. + * If you wish to disable the external interrupt while the interrupt handler + * for that external interrupt is executing then you must use the return value + * EXT_IRQ_DISABLE to return from the extern interrupt handler. + */ +static inline void MRV_PLIC_disable_irq(IRQn_Type IRQn) +{ + unsigned long hart_id = read_csr(mhartid); + uint32_t current = PLIC->TARGET_ENABLES[hart_id].ENABLES[IRQn / 32]; + + current &= ~((uint32_t)1 << (IRQn % 32)); + + PLIC->TARGET_ENABLES[hart_id].ENABLES[IRQn / 32] = current; +} + +/*============================================================================== + * The function MRV_PLIC_set_priority() sets the priority for the external + * interrupt for the interrupt number indicated by the parameter IRQn. + */ +static inline void MRV_PLIC_set_priority(IRQn_Type IRQn, uint32_t priority) +{ + PLIC->SOURCE_PRIORITY[IRQn] = priority; +} + +/*============================================================================== + * The function MRV_PLIC_get_priority() returns the priority for the external + * interrupt for the interrupt number indicated by the parameter IRQn. + */ +static inline uint32_t MRV_PLIC_get_priority(IRQn_Type IRQn) +{ + return PLIC->SOURCE_PRIORITY[IRQn]; +} + +/***************************************************************************//** + * MRV_PLIC_clear_pending_irq(void) + * This is only called by the startup hart and only once + * Clears any pending interrupts as PLIC can be in unknown state on startup + */ +static inline void MRV_PLIC_clear_pending_irq(void) +{ + unsigned long hart_id = read_csr(mhartid); + volatile uint32_t int_num = PLIC->TARGET[hart_id].CLAIM_COMPLETE; + volatile int32_t wait_possible_int; + + while (NoInterrupt_IRQn != int_num) + { + PLIC->TARGET[hart_id].CLAIM_COMPLETE = int_num; + wait_possible_int = 0xFU; + while (wait_possible_int) + { + wait_possible_int--; + } + + int_num = PLIC->TARGET[hart_id].CLAIM_COMPLETE; + } +} + +#endif /* MIV_LEGACY_RV32 */ + +#ifdef __cplusplus +} +#endif + +#endif /* RISCV_PLIC_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv_rv32_regs.h b/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv_rv32_regs.h new file mode 100644 index 0000000..9e21bd7 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv_rv32_regs.h @@ -0,0 +1,544 @@ +/******************************************************************************* + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file miv_rv32_regs.h + * @author Microchip FPGA Embedded Systems Solutions + * @brief Mi-V soft processor register bit mask and shift constants encodings. + * + */ +#ifndef RISCV_REGS_H +#define RISCV_REGS_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define MSTATUS_UIE 0x00000001UL +#define MSTATUS_SIE 0x00000002UL +#define MSTATUS_HIE 0x00000004UL +#define MSTATUS_MIE 0x00000008UL +#define MSTATUS_UPIE 0x00000010UL +#define MSTATUS_SPIE 0x00000020UL +#define MSTATUS_HPIE 0x00000040UL +#define MSTATUS_MPIE 0x00000080UL +#define MSTATUS_SPP 0x00000100UL +#define MSTATUS_HPP 0x00000600UL +#define MSTATUS_MPP 0x00001800UL +#define MSTATUS_FS 0x00006000UL +#define MSTATUS_XS 0x00018000UL +#define MSTATUS_MPRV 0x00020000UL +#define MSTATUS_SUM 0x00040000UL +#define MSTATUS_MXR 0x00080000UL +#define MSTATUS_TVM 0x00100000UL +#define MSTATUS_TW 0x00200000UL +#define MSTATUS_TSR 0x00400000UL +#define MSTATUS_RES 0x7F800000UL +#define MSTATUS32_SD 0x80000000UL +#define MSTATUS64_SD 0x8000000000000000UL + +#define MCAUSE32_CAUSE 0x7FFFFFFFUL +#define MCAUSE64_CAUSE 0x7FFFFFFFFFFFFFFFUL +#define MCAUSE32_INT 0x80000000UL +#define MCAUSE64_INT 0x8000000000000000UL + +#define MIP_SSIP (1u << IRQ_S_SOFT) +#define MIP_HSIP (1u << IRQ_H_SOFT) +#define MIP_MSIP (1u << IRQ_M_SOFT) +#define MIP_STIP (1u << IRQ_S_TIMER) +#define MIP_HTIP (1u << IRQ_H_TIMER) +#define MIP_MTIP (1u << IRQ_M_TIMER) +#define MIP_SEIP (1u << IRQ_S_EXT) +#define MIP_HEIP (1u << IRQ_H_EXT) +#define MIP_MEIP (1u << IRQ_M_EXT) + +#ifndef MIV_LEGACY_RV32 +#define MGEUI 16U +#define MGECI 17U +#define MSYS_EI0 24U +#define MSYS_EI1 25U +#define MSYS_EI2 26U +#define MSYS_EI3 27U +#define MSYS_EI4 28U +#define MSYS_EI5 29U +#define OPSRV_REG 30U + +#define MGEUI_MEIP (1u << MGEUI) +#define MGECI_MEIP (1u << MGECI) +#define MSYS_EI0IP (1u << MSYS_EI0) +#define MSYS_EI1IP (1u << MSYS_EI1) +#define MSYS_EI2IP (1u << MSYS_EI2) +#define MSYS_EI3IP (1u << MSYS_EI3) +#define MSYS_EI4IP (1u << MSYS_EI4) +#define MSYS_EI5IP (1u << MSYS_EI5) +#define MSYS_EXTERNAL_INT (0x3Fu << MSYS_EI0) +#define MIP_OPSRV_REG (1u << OPSRV_REG) + +#endif /* MIV_LEGACY_RV32 */ + +#define PRV_M 3U + +#define VM_MBARE 0U +#define VM_MBB 1U +#define VM_MBBID 2U +#define VM_SV32 8U +#define VM_SV39 9U +#define VM_SV48 10U + +#define IRQ_S_SOFT 1U +#define IRQ_H_SOFT 2U +#define IRQ_M_SOFT 3U +#define IRQ_S_TIMER 5U +#define IRQ_H_TIMER 6U +#define IRQ_M_TIMER 7U +#define IRQ_S_EXT 9U +#define IRQ_H_EXT 10U +#define IRQ_M_EXT 11U + +#define DEFAULT_RSTVEC 0x00001000 +#define DEFAULT_NMIVEC 0x00001004 +#define DEFAULT_MTVEC 0x00001010 +#define CONFIG_STRING_ADDR 0x0000100C +#define EXT_IO_BASE 0x40000000 +#define DRAM_BASE 0x80000000 + +#ifdef __riscv + +#if __riscv_xlen == 64 +# define MSTATUS_SD MSTATUS64_SD +# define SSTATUS_SD SSTATUS64_SD +# define MCAUSE_INT MCAUSE64_INT +# define MCAUSE_CAUSE MCAUSE64_CAUSE +# define RISCV_PGLEVEL_BITS 9 +#else +# define MSTATUS_SD MSTATUS32_SD +# define SSTATUS_SD SSTATUS32_SD +# define RISCV_PGLEVEL_BITS 10 +# define MCAUSE_INT MCAUSE32_INT +# define MCAUSE_CAUSE MCAUSE32_CAUSE +#endif + +#define RISCV_PGSHIFT 12U +#define RISCV_PGSIZE (1U << RISCV_PGSHIFT) + +#ifndef __ASSEMBLER__ + +#ifdef __GNUC__ + +#define read_csr(reg) ({ unsigned long __tmp; \ + __asm__ volatile ("csrr %0, " #reg : "=r"(__tmp)); \ + __tmp; }) + +#define write_csr(reg, val) ({ \ + __asm__ volatile ("csrw " #reg ", %0" :: "rK"(val)); }) + +#define swap_csr(reg, val) ({ unsigned long __tmp; \ + __asm__ volatile ("csrrw %0, " #reg ", %1" : "=r"(__tmp) : "rK"(val)); \ + __tmp; }) + +#define set_csr(reg, bit) ({ unsigned long __tmp; \ + __asm__ volatile ("csrrs %0, " #reg ", %1" : "=r"(__tmp) : "rK"(bit)); \ + __tmp; }) + +#define clear_csr(reg, bit) ({ unsigned long __tmp; \ + __asm__ volatile ("csrrc %0, " #reg ", %1" : "=r"(__tmp) : "rK"(bit)); \ + __tmp; }) + +#ifdef __riscv_atomic + +#define MASK(nr) (1UL << nr) +#define MASK_NOT(nr) (~(1UL << nr)) + +/** + * atomic_read - read atomic variable + * @v: pointer of type int + * + * Atomically reads the value of @v. + */ +static inline int atomic_read(const int *v) +{ + return *((volatile int *)(v)); +} + +/** + * atomic_set - set atomic variable + * @v: pointer of type int + * @i: required value + * + * Atomically sets the value of @v to @i. + */ +static inline void atomic_set(int *v, int i) +{ + *v = i; +} + +/** + * atomic_add - add integer to atomic variable + * @i: integer value to add + * @v: pointer of type int + * + * Atomically adds @i to @v. + */ +static inline void atomic_add(int i, int *v) +{ + __asm__ __volatile__ ( + "amoadd.w zero, %1, %0" + : "+A" (*v) + : "r" (i)); +} + +static inline int atomic_fetch_add(unsigned int mask, int *v) +{ + int out; + + __asm__ __volatile__ ( + "amoadd.w %2, %1, %0" + : "+A" (*v), "=r" (out) + : "r" (mask)); + return out; +} + +/** + * atomic_sub - subtract integer from atomic variable + * @i: integer value to subtract + * @v: pointer of type int + * + * Atomically subtracts @i from @v. + */ +static inline void atomic_sub(int i, int *v) +{ + atomic_add(-i, v); +} + +static inline int atomic_fetch_sub(unsigned int mask, int *v) +{ + int out; + + __asm__ __volatile__ ( + "amosub.w %2, %1, %0" + : "+A" (*v), "=r" (out) + : "r" (mask)); + return out; +} + +/** + * atomic_add_return - add integer to atomic variable + * @i: integer value to add + * @v: pointer of type int + * + * Atomically adds @i to @v and returns the result + */ +static inline int atomic_add_return(int i, int *v) +{ + register int c; + __asm__ __volatile__ ( + "amoadd.w %0, %2, %1" + : "=r" (c), "+A" (*v) + : "r" (i)); + return (c + i); +} + +/** + * atomic_sub_return - subtract integer from atomic variable + * @i: integer value to subtract + * @v: pointer of type int + * + * Atomically subtracts @i from @v and returns the result + */ +static inline int atomic_sub_return(int i, int *v) +{ + return atomic_add_return(-i, v); +} + +/** + * atomic_inc - increment atomic variable + * @v: pointer of type int + * + * Atomically increments @v by 1. + */ +static inline void atomic_inc(int *v) +{ + atomic_add(1, v); +} + +/** + * atomic_dec - decrement atomic variable + * @v: pointer of type int + * + * Atomically decrements @v by 1. + */ +static inline void atomic_dec(int *v) +{ + atomic_add(-1, v); +} + +static inline int atomic_inc_return(int *v) +{ + return atomic_add_return(1, v); +} + +static inline int atomic_dec_return(int *v) +{ + return atomic_sub_return(1, v); +} + +/** + * atomic_sub_and_test - subtract value from variable and test result + * @i: integer value to subtract + * @v: pointer of type int + * + * Atomically subtracts @i from @v and returns + * true if the result is zero, or false for all + * other cases. + */ +static inline int atomic_sub_and_test(int i, int *v) +{ + return (atomic_sub_return(i, v) == 0); +} + +/** + * atomic_inc_and_test - increment and test + * @v: pointer of type int + * + * Atomically increments @v by 1 + * and returns true if the result is zero, or false for all + * other cases. + */ +static inline int atomic_inc_and_test(int *v) +{ + return (atomic_inc_return(v) == 0); +} + +/** + * atomic_dec_and_test - decrement and test + * @v: pointer of type int + * + * Atomically decrements @v by 1 and + * returns true if the result is 0, or false for all other + * cases. + */ +static inline int atomic_dec_and_test(int *v) +{ + return (atomic_dec_return(v) == 0); +} + +/** + * atomic_add_negative - add and test if negative + * @i: integer value to add + * @v: pointer of type int + * + * Atomically adds @i to @v and returns true + * if the result is negative, or false when + * result is greater than or equal to zero. + */ +static inline int atomic_add_negative(int i, int *v) +{ + return (atomic_add_return(i, v) < 0); +} + +static inline int atomic_xchg(int *v, int n) +{ + register int c; + __asm__ __volatile__ ( + "amoswap.w %0, %2, %1" + : "=r" (c), "+A" (*v) + : "r" (n)); + return c; +} + +/** + * atomic_and - Atomically clear bits in atomic variable + * @mask: Mask of the bits to be retained + * @v: pointer of type int + * + * Atomically retains the bits set in @mask from @v + */ +static inline void atomic_and(unsigned int mask, int *v) +{ + __asm__ __volatile__ ( + "amoand.w zero, %1, %0" + : "+A" (*v) + : "r" (mask)); +} + +static inline int atomic_fetch_and(unsigned int mask, int *v) +{ + int out; + __asm__ __volatile__ ( + "amoand.w %2, %1, %0" + : "+A" (*v), "=r" (out) + : "r" (mask)); + return out; +} + +/** + * atomic_or - Atomically set bits in atomic variable + * @mask: Mask of the bits to be set + * @v: pointer of type int + * + * Atomically sets the bits set in @mask in @v + */ +static inline void atomic_or(unsigned int mask, int *v) +{ + __asm__ __volatile__ ( + "amoor.w zero, %1, %0" + : "+A" (*v) + : "r" (mask)); +} + +static inline int atomic_fetch_or(unsigned int mask, int *v) +{ + int out; + __asm__ __volatile__ ( + "amoor.w %2, %1, %0" + : "+A" (*v), "=r" (out) + : "r" (mask)); + return out; +} + +/** + * atomic_xor - Atomically flips bits in atomic variable + * @mask: Mask of the bits to be flipped + * @v: pointer of type int + * + * Atomically flips the bits set in @mask in @v + */ +static inline void atomic_xor(unsigned int mask, int *v) +{ + __asm__ __volatile__ ( + "amoxor.w zero, %1, %0" + : "+A" (*v) + : "r" (mask)); +} + +static inline int atomic_fetch_xor(unsigned int mask, int *v) +{ + int out; + __asm__ __volatile__ ( + "amoxor.w %2, %1, %0" + : "+A" (*v), "=r" (out) + : "r" (mask)); + return out; +} + +/** + * test_and_set_bit - Set a bit and return its old value + * @nr: Bit to set + * @addr: Address to count from + * + * This operation is atomic and cannot be reordered. + * It also implies a memory barrier. + */ +static inline int test_and_set_bit(int nr, volatile unsigned long *addr) +{ + unsigned long __res, __mask; + __mask = MASK(nr); + __asm__ __volatile__ ( \ + "amoor.w %0, %2, %1" \ + : "=r" (__res), "+A" (*addr) \ + : "r" (__mask)); \ + + return ((__res & __mask) != 0); +} + +/** + * test_and_clear_bit - Clear a bit and return its old value + * @nr: Bit to clear + * @addr: Address to count from + * + * This operation is atomic and cannot be reordered. + * It also implies a memory barrier. + */ +static inline int test_and_clear_bit(int nr, volatile unsigned long *addr) +{ + unsigned long __res, __mask; + __mask = MASK_NOT(nr); + __asm__ __volatile__ ( \ + "amoand.w %0, %2, %1" \ + : "=r" (__res), "+A" (*addr) \ + : "r" (__mask)); \ + + return ((__res & __mask) != 0); +} + +/** + * test_and_change_bit - Change a bit and return its old value + * @nr: Bit to change + * @addr: Address to count from + * + * This operation is atomic and cannot be reordered. + * It also implies a memory barrier. + */ +static inline int test_and_change_bit(int nr, volatile unsigned long *addr) +{ + + unsigned long __res, __mask; + __mask = MASK(nr); + __asm__ __volatile__ ( \ + "amoxor.w %0, %2, %1" \ + : "=r" (__res), "+A" (*addr) \ + : "r" (__mask)); \ + + return ((__res & __mask) != 0); +} + +/** + * set_bit - Atomically set a bit in memory + * @nr: the bit to set + * @addr: the address to start counting from + * + * This function is atomic and may not be reordered. + */ + +static inline void set_bit(int nr, volatile unsigned long *addr) +{ + __asm__ __volatile__ ( \ + "AMOOR.w zero, %1, %0" \ + : "+A" (*addr) \ + : "r" (MASK(nr))); +} + +/** + * clear_bit - Clears a bit in memory + * @nr: Bit to clear + * @addr: Address to start counting from + * + * clear_bit() is atomic and may not be reordered. + */ +static inline void clear_bit(int nr, volatile unsigned long *addr) +{ + __asm__ __volatile__ ( \ + "AMOAND.w zero, %1, %0" \ + : "+A" (*addr) \ + : "r" (MASK_NOT(nr))); +} + +/** + * change_bit - Toggle a bit in memory + * @nr: Bit to change + * @addr: Address to start counting from + * + * change_bit() is atomic and may not be reordered. + */ +static inline void change_bit(int nr, volatile unsigned long *addr) +{ + __asm__ __volatile__ ( \ + "AMOXOR.w zero, %1, %0" \ + : "+A" (*addr) \ + : "r" (MASK(nr))); +} + +#endif /* __riscv_atomic */ + +#endif /* __GNUC__ */ + +#endif /* __ASSEMBLER__ */ + +#endif /* __riscv */ + +#ifdef __cplusplus +} +#endif + +#endif /* RISCV_REGS_H */ diff --git a/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv_rv32_stubs.c b/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv_rv32_stubs.c new file mode 100644 index 0000000..a7a02d0 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv_rv32_stubs.c @@ -0,0 +1,239 @@ +/******************************************************************************* + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file miv_rv32_stubs.c + * @author Microchip FPGA Embedded Systems Solutions + * @brief Stubs for the Mi-V soft processor Interrupt handler. + * + * The functions below will only be linked with the application code if the user + * does not provide an implementation for these functions. These functions are + * defined with weak linking so that they can be overridden by a function with + * same prototype in the user's application code. + * + */ +#include + +#ifdef __cplusplus +extern "C" { +#endif + +__attribute__((weak)) void Software_IRQHandler(void) +{ + _exit(10); +} + +__attribute__((weak)) void SysTick_Handler(void) +{ + /* Default handler */ +} + +#ifdef MIV_LEGACY_RV32 +__attribute__((weak)) uint8_t Invalid_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_1_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_2_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_3_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_4_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_5_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_6_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_7_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_8_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_9_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_10_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_11_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_12_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_13_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_14_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_15_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_16_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_17_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_18_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_19_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_20_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_21_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_22_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_23_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_24_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_25_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_26_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_27_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_28_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_29_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_30_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +__attribute__((weak)) uint8_t External_31_IRQHandler(void) +{ + return(0U); /* Default handler */ +} + +#else + +__attribute__((weak)) void External_IRQHandler(void) +{ +} + +__attribute__((weak)) void MGECI_IRQHandler(void) +{ +} + +__attribute__((weak)) void MGEUI_IRQHandler(void) +{ +} + +__attribute__((weak)) void OPSRV_IRQHandler(void) +{ +} + +__attribute__((weak)) void MSYS_EI5_IRQHandler(void) +{ +} + +__attribute__((weak)) void MSYS_EI4_IRQHandler(void) +{ +} + +__attribute__((weak)) void MSYS_EI3_IRQHandler(void) +{ +} + +__attribute__((weak)) void MSYS_EI2_IRQHandler(void) +{ +} + +__attribute__((weak)) void MSYS_EI1_IRQHandler(void) +{ +} + +__attribute__((weak)) void MSYS_EI0_IRQHandler(void) +{ +} + +#endif /* MIV_LEGACY_RV32 */ + +#ifdef __cplusplus +} +#endif diff --git a/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv_rv32_syscall.c b/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv_rv32_syscall.c new file mode 100644 index 0000000..98e0036 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/miv_rv32_syscall.c @@ -0,0 +1,364 @@ +/******************************************************************************* + * Copyright 2019-2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file miv_rv32_syscall.c + * @author Microchip FPGA Embedded Systems Solutions + * @brief Stubs for system calls. + * + */ +#include +#include +#include +#include +#include "miv_rv32_hal.h" + +#ifdef MSCC_STDIO_THRU_CORE_UART_APB +#include + +#ifndef LEGACY_DIR_STRUCTURE +#include "drivers/fabric_ip/CoreUARTapb/core_uart_apb.h" +#else +#include "core_uart_apb.h" +#endif + +#endif /*MSCC_STDIO_THRU_CORE_UART_APB*/ + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef MSCC_STDIO_THRU_CORE_UART_APB + +/*------------------------------------------------------------------------------ + * CoreUARTapb instance data for the CoreUARTapb instance used for standard + * output. + */ +static UART_instance_t g_stdio_uart; + +/*============================================================================== + * Flag used to indicate if the UART driver needs to be initialized. + */ +static int g_stdio_uart_init_done = 0; + +/* + * Disable semihosting apis + */ +#pragma import(__use_no_semihosting_swi) + +/*============================================================================== + * sendchar() + */ +int sendchar(int ch) +{ + /*-------------------------------------------------------------------------- + * Initialize the UART driver if it is the first time this function is + * called. + */ + if ( !g_stdio_uart_init_done ) + { + /****************************************************************************** + * Baud value: + * This value is calculated using the following equation: + * BAUD_VALUE = (CLOCK / (16 * BAUD_RATE)) - 1 + *****************************************************************************/ + UART_init( &g_stdio_uart, + MSCC_STDIO_UART_BASE_ADDR, + ((SYS_CLK_FREQ/(16 * MSCC_STDIO_BAUD_VALUE))-1), + (DATA_8_BITS | NO_PARITY)); + + g_stdio_uart_init_done = 1; + } + + /*-------------------------------------------------------------------------- + * Output text to the UART. + */ + UART_send( &g_stdio_uart, (uint8_t *)&ch, 1 ); + + return (ch); +} + +/*============================================================================== + * getachar() + */ +int getachar(void) +{ + uint8_t rx_size; + uint8_t rx_byte; + + if ( !g_stdio_uart_init_done ) + { + /****************************************************************************** + * Baud value: + * This value is calculated using the following equation: + * BAUD_VALUE = (CLOCK / (16 * BAUD_RATE)) - 1 + *****************************************************************************/ + UART_init( &g_stdio_uart, + MSCC_STDIO_UART_BASE_ADDR, + ((SYS_CLK_FREQ/(16 * MSCC_STDIO_BAUD_VALUE))-1), + (DATA_8_BITS | NO_PARITY)); + + g_stdio_uart_init_done = 1; + } + + do + { + rx_size = UART_get_rx(&g_stdio_uart, &rx_byte, 1); + } while(0u == rx_size); + + return rx_byte; +} + +#endif /*MSCC_STDIO_THRU_CORE_UART_APB*/ + +#undef errno +static int errno; + +static char *__env[1] = { 0 }; +char **environ = __env; + +void write_hex(int fd, uint32_t hex) +{ + char towrite; + + write( fd , "0x", 2U ); + + for (uint32_t ii = 8U ; ii > 0U; ii--) + { + uint32_t jj = ii-1U; + uint8_t digit = ((hex & (0xFU << (jj*4U))) >> (jj*4U)); + towrite = digit < 0xAU ? (0x48U + digit) : (0x65U + (digit - 0xAU)); + write( fd, &towrite, 1U); + } +} + + +#ifdef GDB_TESTING +void __attribute__((optimize("O0"))) _exit(int code) +#else +void _exit(int code) +#endif +{ +#ifdef MSCC_STDIO_THRU_CORE_UART_APB + const char * message = "\nProgam has exited with code:"; + + write(STDERR_FILENO, message, strlen(message)); + write_hex(STDERR_FILENO, code); +#endif + + while (1){}; +} + +void *_sbrk(ptrdiff_t incr) +{ + extern char _end; + extern char _heap_end; + extern char __heap_start; + extern char __heap_end; + static char *curbrk = &_end; + void * ret = NULL; + + /* + * Did we allocated memory for the heap in the linker script? + * You need to set HEAP_SIZE to a non-zero value in your linker script if + * the following assertion fires. + */ + ASSERT(&__heap_end > &__heap_start); + + if (((curbrk + incr) < &_end) || ((curbrk + incr) > &_heap_end)) + { + errno = ENOMEM; + ret = ((char *) - 1); + } + else + { + curbrk += incr; + ret = curbrk - incr; + } + + /* + * Did we run out of heap? + * You need to increase the heap size in the linker script if the following + * assertion fires. + * */ + ASSERT(curbrk <= &__heap_end); + + return(ret); +} + +int _isatty(int fd) +{ + int ret = 0; + + if (fd <= 2) /* one of stdin, stdout, stderr */ + { + ret = 1; + } + else + { + errno = EBADF; + ret = 0; + } + + return(ret); +} + +static int stub(int err) +{ + errno = err; + return -1; +} + +int _open(const char* name, int flags, int mode) +{ + return stub(ENOENT); +} + +int _openat(int dirfd, const char* name, int flags, int mode) +{ + return stub(ENOENT); +} + +int _close(int fd) +{ + return stub(EBADF); +} + +int _execve(const char* name, char* const argv[], char* const env[]) +{ + return stub(ENOMEM); +} + +int _fork(void) +{ + return stub(EAGAIN); +} + +int _fstat(int fd, struct stat *st) +{ + int ret = 0; + + if (isatty(fd)) + { + st->st_mode = S_IFCHR; + ret = 0; + } + else + { + ret = stub(EBADF); + } + + return ret; +} + +int _getpid(void) +{ + return 1; +} + +int _kill(int pid, int sig) +{ + return stub(EINVAL); +} + +int _link(const char *old_name, const char *new_name) +{ + return stub(EMLINK); +} + +off_t _lseek(int fd, off_t ptr, int dir) +{ + off_t ret = 0; + if (_isatty(fd)) + { + ret = 0; + } + else + { + ret = stub(EBADF); + } + + return ret; +} + +ssize_t _read(int fd, void* ptr, size_t len) +{ +#ifdef MSCC_STDIO_THRU_CORE_UART_APB + + char* ptr1 = (char*)ptr; + + if (_isatty(fd)) + { + int count; + + for (count = 0; count < len; count++) + { + ptr1[count] = getachar(); + sendchar(ptr1[count]); + + /* Return partial buffer if we get EOL */ + if (('\r' == ptr1[count])||('\n' == ptr1[count])) + { + ptr1[count] = '\n'; + return count; + } + } + + return count; /* Filled the buffer */ + } +#endif + + return stub(EBADF); +} + +int _stat(const char* file, struct stat* st) +{ + return stub(EACCES); +} + +clock_t _times(struct tms* buf) +{ + return stub(EACCES); +} + +int _unlink(const char* name) +{ + return stub(ENOENT); +} + +int _wait(int* status) +{ + return stub(ECHILD); +} + +ssize_t _write(int fd, const void* ptr, size_t len) +{ +#ifdef MSCC_STDIO_THRU_CORE_UART_APB + int count_out; + char* ptr1 = (char*)ptr; + + /*-------------------------------------------------------------------------- + * Output text to the UART. + */ + count_out = 0; + while(len--) + { + sendchar(ptr1[count_out]); + count_out++; + } + + errno = 0; + return count_out; + +#else /* MSCC_STDIO_THRU_CORE_UART_APB */ + + return stub(EBADF); + +#endif /* MSCC_STDIO_THRU_CORE_UART_APB */ + +} + +#ifdef __cplusplus +} +#endif diff --git a/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/sample_fpga_design_config.h b/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/sample_fpga_design_config.h new file mode 100644 index 0000000..a380d96 --- /dev/null +++ b/freertos/miv-rv32-freertos-demo/src/platform/miv_rv32_hal/sample_fpga_design_config.h @@ -0,0 +1,167 @@ +/******************************************************************************* + * Copyright 2022 Microchip FPGA Embedded Systems Solutions. + * + * SPDX-License-Identifier: MIT + * + * @file sample_fpga_design_config.h + * @author Microchip FPGA Embedded Systems Solutions + * @brief Sample design configuration settings + * + */ + /*========================================================================*//** + @mainpage + Example file detailing how the fpga_design_config.h should be constructed + for the SoftConsole project targeted for Mi-V processors. + + @section intro_sec Introduction + The SoftConsole project targeted for Mi-V processors now have an improved + folder structure. Detailed description of the folder structure is available + at https://github.com/Mi-V-Soft-RISC-V/miv-rv32-documentation. + + The fpga_design_config.h must be stored as shown below + /boards//fpga_design_config.h + + Currently this file must be hand crafted when using the Mi-V Soft Processor. + In future, all the design and soft IP configurations will be automatically + generated from the Libero design description data. + + You can use this sample file as an example. + Rename this file from sample_fpga_design_config.h to fpga_design_config.h + and then customize it per your hardware design. + + @section Project configuration Instructions + 1. Change SYS_CLK_FREQ define to frequency of Mi-V Soft processor clock + 2 Add all the soft IP core BASE addresses + 3. Add the peripheral Core Interrupts to Mi-V Soft processor IRQ number + mappings + 4. Define MSCC_STDIO_UART_BASE_ADDR if you want a CoreUARTapb mapped to + STDIO + + **NOTE** + In the legacy folder structures, the file hw_config.h as was used at the + root of the project folder. This file is now depricated. + +*//*=========================================================================*/ + +#ifndef FPGA_DESIGN_CONFIG_H_ +#define FPGA_DESIGN_CONFIG_H_ + +/***************************************************************************//** + * Soft-processor clock definition + * This is the only clock brought over from the Mi-V Libero design. + */ +#ifndef SYS_CLK_FREQ +#define SYS_CLK_FREQ 50000000UL +#endif + +/***************************************************************************//** + * Peripheral base addresses. + * Format of define is: + * __BASE_ADDR + * The field is optional if there is only one instance of the core + * in the design + * MIV_ESS is an extended peripheral subsystem IP core with peripherals + * connections as defined below. + * The system can be further extended by attaching APB peripherals to the + * empty APB slots. + */ +#define MIV_ESS_PLIC_BASE_ADDR 0x70000000UL +#define COREUARTAPB0_BASE_ADDR 0x71000000UL +#define MIV_MTIMER_BASE_ADDR 0x72000000UL +#define MIV_ESS_APBSLOT3_BASE_ADDR 0x73000000UL +#define MIV_ESS_APBSLOT4_BASE_ADDR 0x74000000UL +#define COREGPIO_OUT_BASE_ADDR 0x75000000UL +#define CORESPI_BASE_ADDR 0x76000000UL +#define MIV_ESS_uDMA_BASE_ADDR 0x78000000UL +#define MIV_ESS_WDOG_BASE_ADDR 0x79000000UL +#define MIV_ESS_I2C_BASE_ADDR 0x7A000000UL +#define MIV_ESS_APBSLOTB_BASE_ADDR 0x7B000000UL +#define MIV_ESS_APBSLOTC_BASE_ADDR 0x7C000000UL +#define MIV_ESS_APBSLOTD_BASE_ADDR 0x7D000000UL +#define MIV_ESS_APBSLOTE_BASE_ADDR 0x7E000000UL +#define MIV_ESS_APBSLOTF_BASE_ADDR 0x7F000000UL + +/***************************************************************************//** + * Peripheral Interrupts are mapped to the corresponding Mi-V Soft processor + * interrupt in the Libero design. + * + * On the legacy RV32 cores, there can be up to 31 external interrupts (IRQ[30:0] + * pins). The legacy RV32 Soft processor external interrupts are defined in the + miv_rv32_plic.h + * + * These are of the form + * typedef enum +{ + NoInterrupt_IRQn = 0, + External_1_IRQn = 1, + External_2_IRQn = 2, + . + . + . + External_31_IRQn = 31 +} IRQn_Type; + + On the legacy RV32 processors, the PLIC identifies the interrupt and passes it + on to the processor core. The interrupt 0 is not used. The pin IRQ[0] should + map to External_1_IRQn likewise IRQ[30] should map to External_31_IRQn + +e.g + +#define TIMER0_IRQn External_30_IRQn +#define TIMER1_IRQn External_31_IRQn + + The MIV_RV32 soft processor has up to six optional system interrupts, MSYS_EI[n] + in addition to one EXT_IRQ. + The MIV_RV32 does not have an inbuilt PLIC and all the interrupts are directly + delivered to the processor core, hence unlike legacy RV32 cores, no interrupt + number mapping is necessary on MIV_RV32 core. + */ + +/**************************************************************************** + * Baud value to achieve a 115200 baud rate with system clock defined by + * SYS_CLK_FREQ. + * This value is calculated using the following equation: + * BAUD_VALUE = (CLOCK / (16 * BAUD_RATE)) - 1 + *****************************************************************************/ +#define BAUD_VALUE_115200 ((SYS_CLK_FREQ / (16 * 115200)) - 1) + +/****************************************************************************** + * Baud value to achieve a 57600 baud rate with system clock defined by + * SYS_CLK_FREQ. + * This value is calculated using the following equation: + * BAUD_VALUE = (CLOCK / (16 * BAUD_RATE)) - 1 + *****************************************************************************/ + #define BAUD_VALUE_57600 ((SYS_CLK_FREQ / (16 * 57600)) - 1) + +/***************************************************************************//** + * Define MSCC_STDIO_THRU_CORE_UART_APB in the project settings if you want the + * standard IOs to be redirected to a terminal via UART. + */ +#ifdef MSCC_STDIO_THRU_CORE_UART_APB +/* + * A base address mapping for the STDIO printf/scanf mapping to CortUARTapb + * must be provided if it is being used + * + * e.g. #define MSCC_STDIO_UART_BASE_ADDR COREUARTAPB1_BASE_ADDR + */ +#define MSCC_STDIO_UART_BASE_ADDR COREUARTAPB0_BASE_ADDR + +#ifndef MSCC_STDIO_UART_BASE_ADDR +#error MSCC_STDIO_UART_BASE_ADDR not defined- e.g. #define MSCC_STDIO_UART_BASE_ADDR COREUARTAPB1_BASE_ADDR +#endif + +#ifndef MSCC_STDIO_BAUD_VALUE +/* + * The MSCC_STDIO_BAUD_VALUE define should be set in your project's settings to + * specify the baud value used by the standard output CoreUARTapb instance for + * generating the UART's baud rate if you want a different baud rate from the + * default of 115200 baud + */ +#define MSCC_STDIO_BAUD_VALUE 115200 +#endif /*MSCC_STDIO_BAUD_VALUE*/ + +#endif /* end of MSCC_STDIO_THRU_CORE_UART_APB */ +/******************************************************************************* + * End of user edit section + */ +#endif /* FPGA_DESIGN_CONFIG_H_ */