+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * 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;
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ATOMIC_H */
diff --git a/fw/Middlewares/Third_Party/FreeRTOS/Source/include/croutine.h b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/croutine.h
new file mode 100644
index 0000000..8d7069c
--- /dev/null
+++ b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/croutine.h
@@ -0,0 +1,720 @@
+/*
+ * FreeRTOS Kernel V10.3.1
+ * 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 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"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* 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
+ *
+ BaseType_t xCoRoutineCreate(
+ crCOROUTINE_CODE pxCoRoutineCode,
+ UBaseType_t uxPriority,
+ UBaseType_t uxIndex
+ );
+ *
+ * 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:
+
+ // 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 );
+ }
+ }
+
+ * \defgroup xCoRoutineCreate xCoRoutineCreate
+ * \ingroup Tasks
+ */
+BaseType_t xCoRoutineCreate( crCOROUTINE_CODE pxCoRoutineCode, UBaseType_t uxPriority, UBaseType_t uxIndex );
+
+
+/**
+ * croutine. h
+ *
+ void vCoRoutineSchedule( void );
+ *
+ * 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:
+
+ // 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();
+ }
+ }
+
+ * \defgroup vCoRoutineSchedule vCoRoutineSchedule
+ * \ingroup Tasks
+ */
+void vCoRoutineSchedule( void );
+
+/**
+ * croutine. h
+ *
+ crSTART( CoRoutineHandle_t xHandle );
+ *
+ * This macro MUST always be called at the start of a co-routine function.
+ *
+ * Example usage:
+
+ // 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();
+ }
+ * \defgroup crSTART crSTART
+ * \ingroup Tasks
+ */
+#define crSTART( pxCRCB ) switch( ( ( CRCB_t * )( pxCRCB ) )->uxState ) { case 0:
+
+/**
+ * croutine. h
+ *
+ crEND();
+ *
+ * This macro MUST always be called at the end of a co-routine function.
+ *
+ * Example usage:
+
+ // 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();
+ }
+ * \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
+ *
+ crDELAY( CoRoutineHandle_t xHandle, TickType_t xTicksToDelay );
+ *
+ * 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:
+
+ // 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();
+ }
+ * \defgroup crDELAY crDELAY
+ * \ingroup Tasks
+ */
+#define crDELAY( xHandle, xTicksToDelay ) \
+ if( ( xTicksToDelay ) > 0 ) \
+ { \
+ vCoRoutineAddToDelayedList( ( xTicksToDelay ), NULL ); \
+ } \
+ crSET_STATE0( ( xHandle ) );
+
+/**
+ *
+ crQUEUE_SEND(
+ CoRoutineHandle_t xHandle,
+ QueueHandle_t pxQueue,
+ void *pvItemToQueue,
+ TickType_t xTicksToWait,
+ BaseType_t *pxResult
+ )
+ *
+ * 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:
+
+ // 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();
+ }
+ * \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
+ *
+ crQUEUE_RECEIVE(
+ CoRoutineHandle_t xHandle,
+ QueueHandle_t pxQueue,
+ void *pvBuffer,
+ TickType_t xTicksToWait,
+ BaseType_t *pxResult
+ )
+ *
+ * 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:
+
+ // 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();
+ }
+ * \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
+ *
+ crQUEUE_SEND_FROM_ISR(
+ QueueHandle_t pxQueue,
+ void *pvItemToQueue,
+ BaseType_t xCoRoutinePreviouslyWoken
+ )
+ *
+ * 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:
+
+ // 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 );
+ }
+ }
+ * \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
+ *
+ crQUEUE_SEND_FROM_ISR(
+ QueueHandle_t pxQueue,
+ void *pvBuffer,
+ BaseType_t * pxCoRoutineWoken
+ )
+ *
+ * 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:
+
+ // 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 );
+ }
+ }
+ }
+ * \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 );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CO_ROUTINE_H */
diff --git a/fw/Middlewares/Third_Party/FreeRTOS/Source/include/deprecated_definitions.h b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/deprecated_definitions.h
new file mode 100644
index 0000000..21657b9
--- /dev/null
+++ b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/deprecated_definitions.h
@@ -0,0 +1,279 @@
+/*
+ * FreeRTOS Kernel V10.3.1
+ * 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 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/fw/Middlewares/Third_Party/FreeRTOS/Source/include/event_groups.h b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/event_groups.h
new file mode 100644
index 0000000..a87fdf3
--- /dev/null
+++ b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/event_groups.h
@@ -0,0 +1,757 @@
+/*
+ * FreeRTOS Kernel V10.3.1
+ * 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 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"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * 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
+ *
+ EventGroupHandle_t xEventGroupCreate( void );
+
+ *
+ * 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 xEventGropuCreate() then the required memory is
+ * automatically dynamically allocated inside the xEventGroupCreate() function.
+ * (see http://www.freertos.org/a00111.html). If an event group is created
+ * using xEventGropuCreateStatic() 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 http://www.freertos.org/a00111.html
+ *
+ * Example usage:
+
+ // 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.
+ }
+
+ * \defgroup xEventGroupCreate xEventGroupCreate
+ * \ingroup EventGroup
+ */
+#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
+ EventGroupHandle_t xEventGroupCreate( void ) PRIVILEGED_FUNCTION;
+#endif
+
+/**
+ * event_groups.h
+ *
+ EventGroupHandle_t xEventGroupCreateStatic( EventGroupHandle_t * pxEventGroupBuffer );
+
+ *
+ * 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 xEventGropuCreate() then the required memory is
+ * automatically dynamically allocated inside the xEventGroupCreate() function.
+ * (see http://www.freertos.org/a00111.html). If an event group is created
+ * using xEventGropuCreateStatic() 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:
+
+ // 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 );
+
+ */
+#if( configSUPPORT_STATIC_ALLOCATION == 1 )
+ EventGroupHandle_t xEventGroupCreateStatic( StaticEventGroup_t *pxEventGroupBuffer ) PRIVILEGED_FUNCTION;
+#endif
+
+/**
+ * event_groups.h
+ *
+ EventBits_t xEventGroupWaitBits( EventGroupHandle_t xEventGroup,
+ const EventBits_t uxBitsToWaitFor,
+ const BaseType_t xClearOnExit,
+ const BaseType_t xWaitForAllBits,
+ const TickType_t xTicksToWait );
+
+ *
+ * [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:
+
+ #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.
+ }
+ }
+
+ * \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
+ *
+ EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear );
+
+ *
+ * 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:
+
+ #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.
+ }
+ }
+
+ * \defgroup xEventGroupClearBits xEventGroupClearBits
+ * \ingroup EventGroup
+ */
+EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear ) PRIVILEGED_FUNCTION;
+
+/**
+ * event_groups.h
+ *
+ BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet );
+
+ *
+ * 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:
+
+ #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.
+ }
+ }
+
+ * \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
+ *
+ EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet );
+
+ *
+ * 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:
+
+ #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.
+ }
+ }
+
+ * \defgroup xEventGroupSetBits xEventGroupSetBits
+ * \ingroup EventGroup
+ */
+EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet ) PRIVILEGED_FUNCTION;
+
+/**
+ * event_groups.h
+ *
+ BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, BaseType_t *pxHigherPriorityTaskWoken );
+
+ *
+ * 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:
+
+ #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 );
+ }
+ }
+
+ * \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
+ *
+ EventBits_t xEventGroupSync( EventGroupHandle_t xEventGroup,
+ const EventBits_t uxBitsToSet,
+ const EventBits_t uxBitsToWaitFor,
+ TickType_t xTicksToWait );
+
+ *
+ * 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:
+
+ // 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 syncrhonisation 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 syncrhonisation was made by all
+ // three tasks, so there is no need to test the return value.
+ }
+ }
+
+
+ * \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
+ *
+ EventBits_t xEventGroupGetBits( EventGroupHandle_t xEventGroup );
+
+ *
+ * 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
+ *
+ EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup );
+
+ *
+ * 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
+ *
+ void xEventGroupDelete( EventGroupHandle_t xEventGroup );
+
+ *
+ * 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
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EVENT_GROUPS_H */
+
+
diff --git a/fw/Middlewares/Third_Party/FreeRTOS/Source/include/list.h b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/list.h
new file mode 100644
index 0000000..a3e3024
--- /dev/null
+++ b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/list.h
@@ -0,0 +1,412 @@
+/*
+ * FreeRTOS Kernel V10.3.1
+ * 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 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
+ * descending 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 INC_FREERTOS_H
+ #error FreeRTOS.h must be included before list.h
+#endif
+
+#ifndef LIST_H
+#define LIST_H
+
+/*
+ * 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 */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* 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
+ /* 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 descending 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 descending 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; \
+}
+
+
+/*
+ * 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 (descending 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;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/fw/Middlewares/Third_Party/FreeRTOS/Source/include/message_buffer.h b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/message_buffer.h
new file mode 100644
index 0000000..0c3edb9
--- /dev/null
+++ b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/message_buffer.h
@@ -0,0 +1,803 @@
+/*
+ * FreeRTOS Kernel V10.3.1
+ * 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!
+ */
+
+
+/*
+ * 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"
+
+#if defined( __cplusplus )
+extern "C" {
+#endif
+
+/**
+ * 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
+ *
+
+MessageBufferHandle_t xMessageBufferCreate( size_t xBufferSizeBytes );
+
+ *
+ * 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:
+
+
+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.
+ }
+
+
+ * \defgroup xMessageBufferCreate xMessageBufferCreate
+ * \ingroup MessageBufferManagement
+ */
+#define xMessageBufferCreate( xBufferSizeBytes ) ( MessageBufferHandle_t ) xStreamBufferGenericCreate( xBufferSizeBytes, ( size_t ) 0, pdTRUE )
+
+/**
+ * message_buffer.h
+ *
+
+MessageBufferHandle_t xMessageBufferCreateStatic( size_t xBufferSizeBytes,
+ uint8_t *pucMessageBufferStorageArea,
+ StaticMessageBuffer_t *pxStaticMessageBuffer );
+
+ * 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 + 1 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:
+
+
+// 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( ucBufferStorage ),
+ ucBufferStorage,
+ &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.
+}
+
+
+ * \defgroup xMessageBufferCreateStatic xMessageBufferCreateStatic
+ * \ingroup MessageBufferManagement
+ */
+#define xMessageBufferCreateStatic( xBufferSizeBytes, pucMessageBufferStorageArea, pxStaticMessageBuffer ) ( MessageBufferHandle_t ) xStreamBufferGenericCreateStatic( xBufferSizeBytes, 0, pdTRUE, pucMessageBufferStorageArea, pxStaticMessageBuffer )
+
+/**
+ * message_buffer.h
+ *
+
+size_t xMessageBufferSend( MessageBufferHandle_t xMessageBuffer,
+ const void *pvTxData,
+ size_t xDataLengthBytes,
+ TickType_t xTicksToWait );
+
+ *
+ * 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:
+
+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.
+ }
+}
+
+ * \defgroup xMessageBufferSend xMessageBufferSend
+ * \ingroup MessageBufferManagement
+ */
+#define xMessageBufferSend( xMessageBuffer, pvTxData, xDataLengthBytes, xTicksToWait ) xStreamBufferSend( ( StreamBufferHandle_t ) xMessageBuffer, pvTxData, xDataLengthBytes, xTicksToWait )
+
+/**
+ * message_buffer.h
+ *
+
+size_t xMessageBufferSendFromISR( MessageBufferHandle_t xMessageBuffer,
+ const void *pvTxData,
+ size_t xDataLengthBytes,
+ BaseType_t *pxHigherPriorityTaskWoken );
+
+ *
+ * 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:
+
+// 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 );
+}
+
+ * \defgroup xMessageBufferSendFromISR xMessageBufferSendFromISR
+ * \ingroup MessageBufferManagement
+ */
+#define xMessageBufferSendFromISR( xMessageBuffer, pvTxData, xDataLengthBytes, pxHigherPriorityTaskWoken ) xStreamBufferSendFromISR( ( StreamBufferHandle_t ) xMessageBuffer, pvTxData, xDataLengthBytes, pxHigherPriorityTaskWoken )
+
+/**
+ * message_buffer.h
+ *
+
+size_t xMessageBufferReceive( MessageBufferHandle_t xMessageBuffer,
+ void *pvRxData,
+ size_t xBufferLengthBytes,
+ TickType_t xTicksToWait );
+
+ *
+ * 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:
+
+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....
+ }
+}
+
+ * \defgroup xMessageBufferReceive xMessageBufferReceive
+ * \ingroup MessageBufferManagement
+ */
+#define xMessageBufferReceive( xMessageBuffer, pvRxData, xBufferLengthBytes, xTicksToWait ) xStreamBufferReceive( ( StreamBufferHandle_t ) xMessageBuffer, pvRxData, xBufferLengthBytes, xTicksToWait )
+
+
+/**
+ * message_buffer.h
+ *
+
+size_t xMessageBufferReceiveFromISR( MessageBufferHandle_t xMessageBuffer,
+ void *pvRxData,
+ size_t xBufferLengthBytes,
+ BaseType_t *pxHigherPriorityTaskWoken );
+
+ *
+ * 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:
+
+// 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 );
+}
+
+ * \defgroup xMessageBufferReceiveFromISR xMessageBufferReceiveFromISR
+ * \ingroup MessageBufferManagement
+ */
+#define xMessageBufferReceiveFromISR( xMessageBuffer, pvRxData, xBufferLengthBytes, pxHigherPriorityTaskWoken ) xStreamBufferReceiveFromISR( ( StreamBufferHandle_t ) xMessageBuffer, pvRxData, xBufferLengthBytes, pxHigherPriorityTaskWoken )
+
+/**
+ * message_buffer.h
+ *
+
+void vMessageBufferDelete( MessageBufferHandle_t xMessageBuffer );
+
+ *
+ * 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
+
+BaseType_t xMessageBufferIsFull( MessageBufferHandle_t xMessageBuffer ) );
+
+ *
+ * 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
+
+BaseType_t xMessageBufferIsEmpty( MessageBufferHandle_t xMessageBuffer ) );
+
+ *
+ * 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
+
+BaseType_t xMessageBufferReset( MessageBufferHandle_t xMessageBuffer );
+
+ *
+ * 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
+
+size_t xMessageBufferSpaceAvailable( MessageBufferHandle_t xMessageBuffer ) );
+
+ * 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
+
+ size_t xMessageBufferNextLengthBytes( MessageBufferHandle_t xMessageBuffer ) );
+
+ * 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
+ *
+
+BaseType_t xMessageBufferSendCompletedFromISR( MessageBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken );
+
+ *
+ * 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 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
+ * 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
+ *
+
+BaseType_t xMessageBufferReceiveCompletedFromISR( MessageBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken );
+
+ *
+ * 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 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
+ * 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 )
+
+#if defined( __cplusplus )
+} /* extern "C" */
+#endif
+
+#endif /* !defined( FREERTOS_MESSAGE_BUFFER_H ) */
diff --git a/fw/Middlewares/Third_Party/FreeRTOS/Source/include/mpu_prototypes.h b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/mpu_prototypes.h
new file mode 100644
index 0000000..a21b7a6
--- /dev/null
+++ b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/mpu_prototypes.h
@@ -0,0 +1,160 @@
+/*
+ * FreeRTOS Kernel V10.3.1
+ * 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!
+ */
+
+/*
+ * 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;
+BaseType_t MPU_xTaskCreateRestricted( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) FREERTOS_SYSTEM_CALL;
+BaseType_t MPU_xTaskCreateRestrictedStatic( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) FREERTOS_SYSTEM_CALL;
+void MPU_vTaskAllocateMPURegions( TaskHandle_t xTask, const MemoryRegion_t * const pxRegions ) FREERTOS_SYSTEM_CALL;
+void MPU_vTaskDelete( TaskHandle_t xTaskToDelete ) FREERTOS_SYSTEM_CALL;
+void MPU_vTaskDelay( const TickType_t xTicksToDelay ) FREERTOS_SYSTEM_CALL;
+void MPU_vTaskDelayUntil( 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, uint32_t * const pulTotalRunTime ) FREERTOS_SYSTEM_CALL;
+uint32_t MPU_ulTaskGetIdleRunTimeCounter( 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, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue ) FREERTOS_SYSTEM_CALL;
+BaseType_t MPU_xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL;
+uint32_t MPU_ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL;
+BaseType_t MPU_xTaskNotifyStateClear( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL;
+uint32_t MPU_ulTaskNotifyValueClear( TaskHandle_t xTask, 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/fw/Middlewares/Third_Party/FreeRTOS/Source/include/mpu_wrappers.h b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/mpu_wrappers.h
new file mode 100644
index 0000000..5f63d4f
--- /dev/null
+++ b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/mpu_wrappers.h
@@ -0,0 +1,189 @@
+/*
+ * FreeRTOS Kernel V10.3.1
+ * 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 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. */
+#ifdef portUSING_MPU_WRAPPERS
+
+ /* 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 xTaskCreateRestricted MPU_xTaskCreateRestricted
+ #define vTaskAllocateMPURegions MPU_vTaskAllocateMPURegions
+ #define vTaskDelete MPU_vTaskDelete
+ #define vTaskDelay MPU_vTaskDelay
+ #define vTaskDelayUntil MPU_vTaskDelayUntil
+ #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 xTaskGenericNotify MPU_xTaskGenericNotify
+ #define xTaskNotifyWait MPU_xTaskNotifyWait
+ #define ulTaskNotifyTake MPU_ulTaskNotifyTake
+ #define xTaskNotifyStateClear MPU_xTaskNotifyStateClear
+ #define ulTaskNotifyValueClear MPU_ulTaskNotifyValueClear
+ #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")))
+
+ #endif /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE */
+
+#else /* portUSING_MPU_WRAPPERS */
+
+ #define PRIVILEGED_FUNCTION
+ #define PRIVILEGED_DATA
+ #define FREERTOS_SYSTEM_CALL
+ #define portUSING_MPU_WRAPPERS 0
+
+#endif /* portUSING_MPU_WRAPPERS */
+
+
+#endif /* MPU_WRAPPERS_H */
+
diff --git a/fw/Middlewares/Third_Party/FreeRTOS/Source/include/portable.h b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/portable.h
new file mode 100644
index 0000000..a2099c3
--- /dev/null
+++ b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/portable.h
@@ -0,0 +1,199 @@
+/*
+ * FreeRTOS Kernel V10.3.1
+ * 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!
+ */
+
+/*-----------------------------------------------------------
+ * 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 )
+#endif
+
+#if portBYTE_ALIGNMENT == 16
+ #define portBYTE_ALIGNMENT_MASK ( 0x000f )
+#endif
+
+#if portBYTE_ALIGNMENT == 8
+ #define portBYTE_ALIGNMENT_MASK ( 0x0007 )
+#endif
+
+#if portBYTE_ALIGNMENT == 4
+ #define portBYTE_ALIGNMENT_MASK ( 0x0003 )
+#endif
+
+#if portBYTE_ALIGNMENT == 2
+ #define portBYTE_ALIGNMENT_MASK ( 0x0001 )
+#endif
+
+#if portBYTE_ALIGNMENT == 1
+ #define portBYTE_ALIGNMENT_MASK ( 0x0000 )
+#endif
+
+#ifndef portBYTE_ALIGNMENT_MASK
+ #error "Invalid portBYTE_ALIGNMENT definition"
+#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
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#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( 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
+
+/* 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;
+
+/*
+ * 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
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* PORTABLE_H */
+
diff --git a/fw/Middlewares/Third_Party/FreeRTOS/Source/include/projdefs.h b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/projdefs.h
new file mode 100644
index 0000000..0d95130
--- /dev/null
+++ b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/projdefs.h
@@ -0,0 +1,124 @@
+/*
+ * FreeRTOS Kernel V10.3.1
+ * 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 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 ) 1000 ) )
+#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/fw/Middlewares/Third_Party/FreeRTOS/Source/include/queue.h b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/queue.h
new file mode 100644
index 0000000..52ccca5
--- /dev/null
+++ b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/queue.h
@@ -0,0 +1,1655 @@
+/*
+ * FreeRTOS Kernel V10.3.1
+ * 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_H
+#define QUEUE_H
+
+#ifndef INC_FREERTOS_H
+ #error "include FreeRTOS.h" must appear in source files before "include queue.h"
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#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
+ *
+ QueueHandle_t xQueueCreate(
+ UBaseType_t uxQueueLength,
+ UBaseType_t uxItemSize
+ );
+ *
+ *
+ * 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
+ * http://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.
+ *
+ * http://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:
+
+ 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.
+ }
+
+ * \defgroup xQueueCreate xQueueCreate
+ * \ingroup QueueManagement
+ */
+#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
+ #define xQueueCreate( uxQueueLength, uxItemSize ) xQueueGenericCreate( ( uxQueueLength ), ( uxItemSize ), ( queueQUEUE_TYPE_BASE ) )
+#endif
+
+/**
+ * queue. h
+ *
+ QueueHandle_t xQueueCreateStatic(
+ UBaseType_t uxQueueLength,
+ UBaseType_t uxItemSize,
+ uint8_t *pucQueueStorageBuffer,
+ StaticQueue_t *pxQueueBuffer
+ );
+ *
+ *
+ * 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
+ * http://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.
+ *
+ * http://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 pucQueueStorageBuffer If uxItemSize is not zero then
+ * pucQueueStorageBuffer 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 pucQueueStorageBuffer 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:
+
+ 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.
+ }
+
+ * \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
+ *
+ BaseType_t xQueueSendToToFront(
+ QueueHandle_t xQueue,
+ const void *pvItemToQueue,
+ TickType_t xTicksToWait
+ );
+ *
+ *
+ * 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:
+
+ 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.
+ }
+
+ * \defgroup xQueueSend xQueueSend
+ * \ingroup QueueManagement
+ */
+#define xQueueSendToFront( xQueue, pvItemToQueue, xTicksToWait ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_FRONT )
+
+/**
+ * queue. h
+ *
+ BaseType_t xQueueSendToBack(
+ QueueHandle_t xQueue,
+ const void *pvItemToQueue,
+ TickType_t xTicksToWait
+ );
+ *
+ *
+ * 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:
+
+ 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.
+ }
+
+ * \defgroup xQueueSend xQueueSend
+ * \ingroup QueueManagement
+ */
+#define xQueueSendToBack( xQueue, pvItemToQueue, xTicksToWait ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_BACK )
+
+/**
+ * queue. h
+ *
+ BaseType_t xQueueSend(
+ QueueHandle_t xQueue,
+ const void * pvItemToQueue,
+ TickType_t xTicksToWait
+ );
+ *
+ *
+ * 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:
+
+ 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.
+ }
+
+ * \defgroup xQueueSend xQueueSend
+ * \ingroup QueueManagement
+ */
+#define xQueueSend( xQueue, pvItemToQueue, xTicksToWait ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_BACK )
+
+/**
+ * queue. h
+ *
+ BaseType_t xQueueOverwrite(
+ QueueHandle_t xQueue,
+ const void * pvItemToQueue
+ );
+ *
+ *
+ * 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:
+
+
+ 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!
+ }
+
+ // ...
+}
+
+ * \defgroup xQueueOverwrite xQueueOverwrite
+ * \ingroup QueueManagement
+ */
+#define xQueueOverwrite( xQueue, pvItemToQueue ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), 0, queueOVERWRITE )
+
+
+/**
+ * queue. h
+ *
+ BaseType_t xQueueGenericSend(
+ QueueHandle_t xQueue,
+ const void * pvItemToQueue,
+ TickType_t xTicksToWait
+ BaseType_t xCopyPosition
+ );
+ *
+ *
+ * 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:
+
+ 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.
+ }
+
+ * \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
+ *
+ BaseType_t xQueuePeek(
+ QueueHandle_t xQueue,
+ void * const pvBuffer,
+ TickType_t xTicksToWait
+ );
+ *
+ * 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:
+
+ 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.
+ }
+
+ * \defgroup xQueuePeek xQueuePeek
+ * \ingroup QueueManagement
+ */
+BaseType_t xQueuePeek( QueueHandle_t xQueue, void * const pvBuffer, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
+
+/**
+ * queue. h
+ *
+ BaseType_t xQueuePeekFromISR(
+ QueueHandle_t xQueue,
+ void *pvBuffer,
+ );
+ *
+ * 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
+ *
+ BaseType_t xQueueReceive(
+ QueueHandle_t xQueue,
+ void *pvBuffer,
+ TickType_t xTicksToWait
+ );
+ *
+ * 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:
+
+ 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.
+ }
+
+ * \defgroup xQueueReceive xQueueReceive
+ * \ingroup QueueManagement
+ */
+BaseType_t xQueueReceive( QueueHandle_t xQueue, void * const pvBuffer, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
+
+/**
+ * queue. h
+ * UBaseType_t uxQueueMessagesWaiting( const QueueHandle_t xQueue );
+ *
+ * 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
+ * UBaseType_t uxQueueSpacesAvailable( const QueueHandle_t xQueue );
+ *
+ * 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
+ * void vQueueDelete( QueueHandle_t xQueue );
+ *
+ * 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
+ *
+ BaseType_t xQueueSendToFrontFromISR(
+ QueueHandle_t xQueue,
+ const void *pvItemToQueue,
+ BaseType_t *pxHigherPriorityTaskWoken
+ );
+
+ *
+ * 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):
+
+ 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 ();
+ }
+ }
+
+ *
+ * \defgroup xQueueSendFromISR xQueueSendFromISR
+ * \ingroup QueueManagement
+ */
+#define xQueueSendToFrontFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueSEND_TO_FRONT )
+
+
+/**
+ * queue. h
+ *
+ BaseType_t xQueueSendToBackFromISR(
+ QueueHandle_t xQueue,
+ const void *pvItemToQueue,
+ BaseType_t *pxHigherPriorityTaskWoken
+ );
+
+ *
+ * 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):
+
+ 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 ();
+ }
+ }
+
+ *
+ * \defgroup xQueueSendFromISR xQueueSendFromISR
+ * \ingroup QueueManagement
+ */
+#define xQueueSendToBackFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueSEND_TO_BACK )
+
+/**
+ * queue. h
+ *
+ BaseType_t xQueueOverwriteFromISR(
+ QueueHandle_t xQueue,
+ const void * pvItemToQueue,
+ BaseType_t *pxHigherPriorityTaskWoken
+ );
+ *
+ *
+ * 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:
+
+
+ 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.
+ }
+}
+
+ * \defgroup xQueueOverwriteFromISR xQueueOverwriteFromISR
+ * \ingroup QueueManagement
+ */
+#define xQueueOverwriteFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueOVERWRITE )
+
+/**
+ * queue. h
+ *
+ BaseType_t xQueueSendFromISR(
+ QueueHandle_t xQueue,
+ const void *pvItemToQueue,
+ BaseType_t *pxHigherPriorityTaskWoken
+ );
+
+ *
+ * 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):
+
+ 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 ();
+ }
+ }
+
+ *
+ * \defgroup xQueueSendFromISR xQueueSendFromISR
+ * \ingroup QueueManagement
+ */
+#define xQueueSendFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueSEND_TO_BACK )
+
+/**
+ * queue. h
+ *
+ BaseType_t xQueueGenericSendFromISR(
+ QueueHandle_t xQueue,
+ const void *pvItemToQueue,
+ BaseType_t *pxHigherPriorityTaskWoken,
+ BaseType_t xCopyPosition
+ );
+
+ *
+ * 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):
+
+ 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();
+ }
+ }
+
+ *
+ * \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
+ *
+ BaseType_t xQueueReceiveFromISR(
+ QueueHandle_t xQueue,
+ void *pvBuffer,
+ BaseType_t *pxTaskWoken
+ );
+ *
+ *
+ * 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:
+
+
+ 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 ();
+ }
+ }
+
+ * \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.
+ *
+ * @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 pcName 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 creaet 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 creaet 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 http://wwwFreeRTOS.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 http://wwwFreeRTOS.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;
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* QUEUE_H */
+
diff --git a/fw/Middlewares/Third_Party/FreeRTOS/Source/include/semphr.h b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/semphr.h
new file mode 100644
index 0000000..787c791
--- /dev/null
+++ b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/semphr.h
@@ -0,0 +1,1140 @@
+/*
+ * FreeRTOS Kernel V10.3.1
+ * 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_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
+ * vSemaphoreCreateBinary( SemaphoreHandle_t xSemaphore )
+ *
+ * In many usage scenarios it is faster and more memory efficient to use a
+ * direct to task notification in place of a binary semaphore!
+ * http://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:
+
+ 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.
+ }
+ }
+
+ * \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
+ * SemaphoreHandle_t xSemaphoreCreateBinary( void )
+ *
+ * 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!
+ * http://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 http://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:
+
+ 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.
+ }
+ }
+
+ * \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
+ * SemaphoreHandle_t xSemaphoreCreateBinaryStatic( StaticSemaphore_t *pxSemaphoreBuffer )
+ *
+ * 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!
+ * http://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 http://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:
+
+ 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.
+ }
+
+ * \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
+ * xSemaphoreTake(
+ * SemaphoreHandle_t xSemaphore,
+ * TickType_t xBlockTime
+ * )
+ *
+ * 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:
+
+ 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.
+ }
+ }
+ }
+
+ * \defgroup xSemaphoreTake xSemaphoreTake
+ * \ingroup Semaphores
+ */
+#define xSemaphoreTake( xSemaphore, xBlockTime ) xQueueSemaphoreTake( ( xSemaphore ), ( xBlockTime ) )
+
+/**
+ * semphr. h
+ * xSemaphoreTakeRecursive(
+ * SemaphoreHandle_t xMutex,
+ * TickType_t xBlockTime
+ * )
+ *
+ * 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:
+
+ 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.
+ }
+ }
+ }
+
+ * \defgroup xSemaphoreTakeRecursive xSemaphoreTakeRecursive
+ * \ingroup Semaphores
+ */
+#if( configUSE_RECURSIVE_MUTEXES == 1 )
+ #define xSemaphoreTakeRecursive( xMutex, xBlockTime ) xQueueTakeMutexRecursive( ( xMutex ), ( xBlockTime ) )
+#endif
+
+/**
+ * semphr. h
+ * xSemaphoreGive( SemaphoreHandle_t xSemaphore )
+ *
+ * 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:
+
+ 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.
+ }
+ }
+ }
+ }
+
+ * \defgroup xSemaphoreGive xSemaphoreGive
+ * \ingroup Semaphores
+ */
+#define xSemaphoreGive( xSemaphore ) xQueueGenericSend( ( QueueHandle_t ) ( xSemaphore ), NULL, semGIVE_BLOCK_TIME, queueSEND_TO_BACK )
+
+/**
+ * semphr. h
+ * xSemaphoreGiveRecursive( SemaphoreHandle_t xMutex )
+ *
+ * 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:
+
+ 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.
+ }
+ }
+ }
+
+ * \defgroup xSemaphoreGiveRecursive xSemaphoreGiveRecursive
+ * \ingroup Semaphores
+ */
+#if( configUSE_RECURSIVE_MUTEXES == 1 )
+ #define xSemaphoreGiveRecursive( xMutex ) xQueueGiveMutexRecursive( ( xMutex ) )
+#endif
+
+/**
+ * semphr. h
+ *
+ xSemaphoreGiveFromISR(
+ SemaphoreHandle_t xSemaphore,
+ BaseType_t *pxHigherPriorityTaskWoken
+ )
+ *
+ * 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:
+
+ \#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.
+ }
+ }
+
+ * \defgroup xSemaphoreGiveFromISR xSemaphoreGiveFromISR
+ * \ingroup Semaphores
+ */
+#define xSemaphoreGiveFromISR( xSemaphore, pxHigherPriorityTaskWoken ) xQueueGiveFromISR( ( QueueHandle_t ) ( xSemaphore ), ( pxHigherPriorityTaskWoken ) )
+
+/**
+ * semphr. h
+ *
+ xSemaphoreTakeFromISR(
+ SemaphoreHandle_t xSemaphore,
+ BaseType_t *pxHigherPriorityTaskWoken
+ )
+ *
+ * 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
+ * SemaphoreHandle_t xSemaphoreCreateMutex( void )
+ *
+ * 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
+ * http://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:
+
+ 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.
+ }
+ }
+
+ * \defgroup xSemaphoreCreateMutex xSemaphoreCreateMutex
+ * \ingroup Semaphores
+ */
+#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
+ #define xSemaphoreCreateMutex() xQueueCreateMutex( queueQUEUE_TYPE_MUTEX )
+#endif
+
+/**
+ * semphr. h
+ * SemaphoreHandle_t xSemaphoreCreateMutexStatic( StaticSemaphore_t *pxMutexBuffer )
+ *
+ * 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
+ * http://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:
+
+ 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.
+ }
+
+ * \defgroup xSemaphoreCreateMutexStatic xSemaphoreCreateMutexStatic
+ * \ingroup Semaphores
+ */
+ #if( configSUPPORT_STATIC_ALLOCATION == 1 )
+ #define xSemaphoreCreateMutexStatic( pxMutexBuffer ) xQueueCreateMutexStatic( queueQUEUE_TYPE_MUTEX, ( pxMutexBuffer ) )
+#endif /* configSUPPORT_STATIC_ALLOCATION */
+
+
+/**
+ * semphr. h
+ * SemaphoreHandle_t xSemaphoreCreateRecursiveMutex( void )
+ *
+ * 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
+ * http://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:
+
+ 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.
+ }
+ }
+
+ * \defgroup xSemaphoreCreateRecursiveMutex xSemaphoreCreateRecursiveMutex
+ * \ingroup Semaphores
+ */
+#if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configUSE_RECURSIVE_MUTEXES == 1 ) )
+ #define xSemaphoreCreateRecursiveMutex() xQueueCreateMutex( queueQUEUE_TYPE_RECURSIVE_MUTEX )
+#endif
+
+/**
+ * semphr. h
+ * SemaphoreHandle_t xSemaphoreCreateRecursiveMutexStatic( StaticSemaphore_t *pxMutexBuffer )
+ *
+ * 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
+ * http://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:
+
+ 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.
+ }
+
+ * \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
+ * SemaphoreHandle_t xSemaphoreCreateCounting( UBaseType_t uxMaxCount, UBaseType_t uxInitialCount )
+ *
+ * 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!
+ * http://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
+ * http://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:
+
+ 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.
+ }
+ }
+
+ * \defgroup xSemaphoreCreateCounting xSemaphoreCreateCounting
+ * \ingroup Semaphores
+ */
+#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
+ #define xSemaphoreCreateCounting( uxMaxCount, uxInitialCount ) xQueueCreateCountingSemaphore( ( uxMaxCount ), ( uxInitialCount ) )
+#endif
+
+/**
+ * semphr. h
+ * SemaphoreHandle_t xSemaphoreCreateCountingStatic( UBaseType_t uxMaxCount, UBaseType_t uxInitialCount, StaticSemaphore_t *pxSemaphoreBuffer )
+ *
+ * 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!
+ * http://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
+ * http://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:
+
+ 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.
+ }
+
+ * \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
+ * void vSemaphoreDelete( SemaphoreHandle_t xSemaphore );
+ *
+ * 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
+ * TaskHandle_t xSemaphoreGetMutexHolder( SemaphoreHandle_t xMutex );
+ *
+ * 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
+ * TaskHandle_t xSemaphoreGetMutexHolderFromISR( SemaphoreHandle_t xMutex );
+ *
+ * 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
+ * UBaseType_t uxSemaphoreGetCount( SemaphoreHandle_t xSemaphore );
+ *
+ * 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 ) )
+
+#endif /* SEMAPHORE_H */
+
+
diff --git a/fw/Middlewares/Third_Party/FreeRTOS/Source/include/stack_macros.h b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/stack_macros.h
new file mode 100644
index 0000000..b5bac08
--- /dev/null
+++ b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/stack_macros.h
@@ -0,0 +1,129 @@
+/*
+ * FreeRTOS Kernel V10.3.1
+ * 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 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.
+ */
+
+/*-----------------------------------------------------------*/
+
+#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 ) \
+ { \
+ 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 ) \
+ { \
+ 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/fw/Middlewares/Third_Party/FreeRTOS/Source/include/stream_buffer.h b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/stream_buffer.h
new file mode 100644
index 0000000..a8b68ad
--- /dev/null
+++ b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/stream_buffer.h
@@ -0,0 +1,859 @@
+/*
+ * FreeRTOS Kernel V10.3.1
+ * 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!
+ */
+
+/*
+ * 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
+
+#if defined( __cplusplus )
+extern "C" {
+#endif
+
+/**
+ * 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;
+
+
+/**
+ * message_buffer.h
+ *
+
+StreamBufferHandle_t xStreamBufferCreate( size_t xBufferSizeBytes, size_t xTriggerLevelBytes );
+
+ *
+ * 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:
+
+
+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.
+ }
+}
+
+ * \defgroup xStreamBufferCreate xStreamBufferCreate
+ * \ingroup StreamBufferManagement
+ */
+#define xStreamBufferCreate( xBufferSizeBytes, xTriggerLevelBytes ) xStreamBufferGenericCreate( xBufferSizeBytes, xTriggerLevelBytes, pdFALSE )
+
+/**
+ * stream_buffer.h
+ *
+
+StreamBufferHandle_t xStreamBufferCreateStatic( size_t xBufferSizeBytes,
+ size_t xTriggerLevelBytes,
+ uint8_t *pucStreamBufferStorageArea,
+ StaticStreamBuffer_t *pxStaticStreamBuffer );
+
+ * 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 + 1 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:
+
+
+// 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( ucBufferStorage ),
+ xTriggerLevel,
+ ucBufferStorage,
+ &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.
+}
+
+
+ * \defgroup xStreamBufferCreateStatic xStreamBufferCreateStatic
+ * \ingroup StreamBufferManagement
+ */
+#define xStreamBufferCreateStatic( xBufferSizeBytes, xTriggerLevelBytes, pucStreamBufferStorageArea, pxStaticStreamBuffer ) xStreamBufferGenericCreateStatic( xBufferSizeBytes, xTriggerLevelBytes, pdFALSE, pucStreamBufferStorageArea, pxStaticStreamBuffer )
+
+/**
+ * stream_buffer.h
+ *
+
+size_t xStreamBufferSend( StreamBufferHandle_t xStreamBuffer,
+ const void *pvTxData,
+ size_t xDataLengthBytes,
+ TickType_t xTicksToWait );
+
+ *
+ * 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:
+
+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.
+ }
+}
+
+ * \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
+ *
+
+size_t xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer,
+ const void *pvTxData,
+ size_t xDataLengthBytes,
+ BaseType_t *pxHigherPriorityTaskWoken );
+
+ *
+ * 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:
+
+// 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 );
+}
+
+ * \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
+ *
+
+size_t xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer,
+ void *pvRxData,
+ size_t xBufferLengthBytes,
+ TickType_t xTicksToWait );
+
+ *
+ * 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:
+
+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....
+ }
+}
+
+ * \defgroup xStreamBufferReceive xStreamBufferReceive
+ * \ingroup StreamBufferManagement
+ */
+size_t xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer,
+ void *pvRxData,
+ size_t xBufferLengthBytes,
+ TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
+
+/**
+ * stream_buffer.h
+ *
+
+size_t xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer,
+ void *pvRxData,
+ size_t xBufferLengthBytes,
+ BaseType_t *pxHigherPriorityTaskWoken );
+
+ *
+ * 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:
+
+// 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 );
+}
+
+ * \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
+ *
+
+void vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer );
+
+ *
+ * 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
+ *
+
+BaseType_t xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer );
+
+ *
+ * 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
+ *
+
+BaseType_t xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer );
+
+ *
+ * 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
+ *
+
+BaseType_t xStreamBufferReset( StreamBufferHandle_t xStreamBuffer );
+
+ *
+ * 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
+ *
+
+size_t xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer );
+
+ *
+ * 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
+ *
+
+size_t xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer );
+
+ *
+ * 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
+ *
+
+BaseType_t xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, size_t xTriggerLevel );
+
+ *
+ * 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
+ *
+
+BaseType_t xStreamBufferSendCompletedFromISR( StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken );
+
+ *
+ * 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
+ *
+
+BaseType_t xStreamBufferReceiveCompletedFromISR( StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken );
+
+ *
+ * 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
+
+#if defined( __cplusplus )
+}
+#endif
+
+#endif /* !defined( STREAM_BUFFER_H ) */
diff --git a/fw/Middlewares/Third_Party/FreeRTOS/Source/include/task.h b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/task.h
new file mode 100644
index 0000000..b0cc60b
--- /dev/null
+++ b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/task.h
@@ -0,0 +1,2543 @@
+/*
+ * FreeRTOS Kernel V10.3.1
+ * 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 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"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*-----------------------------------------------------------
+ * MACROS AND DEFINITIONS
+ *----------------------------------------------------------*/
+
+#define tskKERNEL_VERSION_NUMBER "V10.3.1"
+#define tskKERNEL_VERSION_MAJOR 10
+#define tskKERNEL_VERSION_MINOR 3
+#define tskKERNEL_VERSION_BUILD 1
+
+/* 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 )
+
+/**
+ * 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 read 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 * const 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. */
+ uint32_t ulRunTimeCounter; /* The total run time allocated to the task so far, as defined by the run time stats clock. See http://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 portSUPPORESS_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
+ *
+ BaseType_t xTaskCreate(
+ TaskFunction_t pvTaskCode,
+ const char * const pcName,
+ configSTACK_DEPTH_TYPE usStackDepth,
+ void *pvParameters,
+ UBaseType_t uxPriority,
+ TaskHandle_t *pvCreatedTask
+ );
+ *
+ * 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
+ * http://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 pvTaskCode 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 pvCreatedTask 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:
+
+ // 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 );
+ }
+ }
+
+ * \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
+ *
+ TaskHandle_t xTaskCreateStatic( TaskFunction_t pvTaskCode,
+ const char * const pcName,
+ uint32_t ulStackDepth,
+ void *pvParameters,
+ UBaseType_t uxPriority,
+ StackType_t *pxStackBuffer,
+ StaticTask_t *pxTaskBuffer );
+ *
+ * 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
+ * http://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 pvTaskCode 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 pxStackBuffer 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 pxStackBuffer or pxTaskBuffer are NULL, then the task will
+ * be created and a handle to the created task is returned. If either
+ * pxStackBuffer or pxTaskBuffer are NULL then the task will not be created and
+ * NULL is returned.
+ *
+ * Example usage:
+
+
+ // Dimensions 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 );
+ }
+
+ * \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
+ *
+ BaseType_t xTaskCreateRestricted( TaskParameters_t *pxTaskDefinition, TaskHandle_t *pxCreatedTask );
+ *
+ * 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:
+
+// 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( ;; );
+}
+
+ * \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
+ *
+ BaseType_t xTaskCreateRestrictedStatic( TaskParameters_t *pxTaskDefinition, TaskHandle_t *pxCreatedTask );
+ *
+ * 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:
+
+// 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( ;; );
+}
+
+ * \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
+ *
+ void vTaskAllocateMPURegions( TaskHandle_t xTask, const MemoryRegion_t * const pxRegions );
+ *
+ * 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 an MemoryRegion_t structure that contains the
+ * new memory region definitions.
+ *
+ * Example usage:
+
+// 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).
+}
+
+ * \defgroup xTaskCreateRestricted xTaskCreateRestricted
+ * \ingroup Tasks
+ */
+void vTaskAllocateMPURegions( TaskHandle_t xTask, const MemoryRegion_t * const pxRegions ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * void vTaskDelete( TaskHandle_t xTask );
+ *
+ * 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 xTask The handle of the task to be deleted. Passing NULL will
+ * cause the calling task to be deleted.
+ *
+ * Example usage:
+
+ 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 );
+ }
+
+ * \defgroup vTaskDelete vTaskDelete
+ * \ingroup Tasks
+ */
+void vTaskDelete( TaskHandle_t xTaskToDelete ) PRIVILEGED_FUNCTION;
+
+/*-----------------------------------------------------------
+ * TASK CONTROL API
+ *----------------------------------------------------------*/
+
+/**
+ * task. h
+ * void vTaskDelay( const TickType_t xTicksToDelay );
+ *
+ * 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 effect the frequency
+ * at which vTaskDelay() gets called and therefore the time at which the task
+ * next executes. See vTaskDelayUntil() 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
+ * void vTaskDelayUntil( TickType_t *pxPreviousWakeTime, const TickType_t xTimeIncrement );
+ *
+ * INCLUDE_vTaskDelayUntil 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, vTaskDelayUntil () specifies the absolute (exact) time at which it wishes to
+ * unblock.
+ *
+ * The constant portTICK_PERIOD_MS can be used to calculate real time from the tick
+ * rate - with the 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 vTaskDelayUntil ().
+ *
+ * @param xTimeIncrement The cycle time period. The task will be unblocked at
+ * time *pxPreviousWakeTime + xTimeIncrement. Calling vTaskDelayUntil with the
+ * same xTimeIncrement parameter value will cause the task to execute with
+ * a fixed interface period.
+ *
+ * Example usage:
+
+ // Perform an action every 10 ticks.
+ void vTaskFunction( void * pvParameters )
+ {
+ TickType_t xLastWakeTime;
+ const TickType_t xFrequency = 10;
+
+ // Initialise the xLastWakeTime variable with the current time.
+ xLastWakeTime = xTaskGetTickCount ();
+ for( ;; )
+ {
+ // Wait for the next cycle.
+ vTaskDelayUntil( &xLastWakeTime, xFrequency );
+
+ // Perform action here.
+ }
+ }
+
+ * \defgroup vTaskDelayUntil vTaskDelayUntil
+ * \ingroup TaskCtrl
+ */
+void vTaskDelayUntil( TickType_t * const pxPreviousWakeTime, const TickType_t xTimeIncrement ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * BaseType_t xTaskAbortDelay( TaskHandle_t xTask );
+ *
+ * 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
+ * UBaseType_t uxTaskPriorityGet( const TaskHandle_t xTask );
+ *
+ * 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:
+
+ 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.
+ }
+ }
+
+ * \defgroup uxTaskPriorityGet uxTaskPriorityGet
+ * \ingroup TaskCtrl
+ */
+UBaseType_t uxTaskPriorityGet( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * UBaseType_t uxTaskPriorityGetFromISR( const TaskHandle_t xTask );
+ *
+ * A version of uxTaskPriorityGet() that can be used from an ISR.
+ */
+UBaseType_t uxTaskPriorityGetFromISR( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * eTaskState eTaskGetState( TaskHandle_t xTask );
+ *
+ * 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
+ * void vTaskGetInfo( TaskHandle_t xTask, TaskStatus_t *pxTaskStatus, BaseType_t xGetFreeStackSpace, eTaskState eState );
+ *
+ * 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:
+
+ 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.
+ }
+
+ * \defgroup vTaskGetInfo vTaskGetInfo
+ * \ingroup TaskCtrl
+ */
+void vTaskGetInfo( TaskHandle_t xTask, TaskStatus_t *pxTaskStatus, BaseType_t xGetFreeStackSpace, eTaskState eState ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * void vTaskPrioritySet( TaskHandle_t xTask, UBaseType_t uxNewPriority );
+ *
+ * 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:
+
+ 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 );
+ }
+
+ * \defgroup vTaskPrioritySet vTaskPrioritySet
+ * \ingroup TaskCtrl
+ */
+void vTaskPrioritySet( TaskHandle_t xTask, UBaseType_t uxNewPriority ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * void vTaskSuspend( TaskHandle_t xTaskToSuspend );
+ *
+ * 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:
+
+ 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.
+ }
+
+ * \defgroup vTaskSuspend vTaskSuspend
+ * \ingroup TaskCtrl
+ */
+void vTaskSuspend( TaskHandle_t xTaskToSuspend ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * void vTaskResume( TaskHandle_t xTaskToResume );
+ *
+ * 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:
+
+ 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.
+ }
+
+ * \defgroup vTaskResume vTaskResume
+ * \ingroup TaskCtrl
+ */
+void vTaskResume( TaskHandle_t xTaskToResume ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * void xTaskResumeFromISR( TaskHandle_t xTaskToResume );
+ *
+ * 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
+ * void vTaskStartScheduler( void );
+ *
+ * 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:
+
+ 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 ()
+ }
+
+ *
+ * \defgroup vTaskStartScheduler vTaskStartScheduler
+ * \ingroup SchedulerControl
+ */
+void vTaskStartScheduler( void ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * void vTaskEndScheduler( void );
+ *
+ * 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:
+
+ 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.
+ }
+
+ *
+ * \defgroup vTaskEndScheduler vTaskEndScheduler
+ * \ingroup SchedulerControl
+ */
+void vTaskEndScheduler( void ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * void vTaskSuspendAll( void );
+ *
+ * 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,
+ * vTaskDelayUntil(), xQueueSend(), etc.) must not be called while the scheduler
+ * is suspended.
+ *
+ * Example usage:
+
+ 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 ();
+ }
+ }
+
+ * \defgroup vTaskSuspendAll vTaskSuspendAll
+ * \ingroup SchedulerControl
+ */
+void vTaskSuspendAll( void ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * BaseType_t xTaskResumeAll( void );
+ *
+ * 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:
+
+ 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 ();
+ }
+ }
+ }
+
+ * \defgroup xTaskResumeAll xTaskResumeAll
+ * \ingroup SchedulerControl
+ */
+BaseType_t xTaskResumeAll( void ) PRIVILEGED_FUNCTION;
+
+/*-----------------------------------------------------------
+ * TASK UTILITIES
+ *----------------------------------------------------------*/
+
+/**
+ * task. h
+ * TickType_t xTaskGetTickCount( void );
+ *
+ * @return The count of ticks since vTaskStartScheduler was called.
+ *
+ * \defgroup xTaskGetTickCount xTaskGetTickCount
+ * \ingroup TaskUtils
+ */
+TickType_t xTaskGetTickCount( void ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * TickType_t xTaskGetTickCountFromISR( void );
+ *
+ * @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
+ * uint16_t uxTaskGetNumberOfTasks( void );
+ *
+ * @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
+ * char *pcTaskGetName( TaskHandle_t xTaskToQuery );
+ *
+ * @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
+ * TaskHandle_t xTaskGetHandle( const char *pcNameToQuery );
+ *
+ * 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
+ * UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask );
+ *
+ * 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
+ * configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2( TaskHandle_t xTask );
+ *
+ * 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
+ * void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction );
+ *
+ * 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
+ * void xTaskGetApplicationTaskTag( TaskHandle_t xTask );
+ *
+ * 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
+ * void xTaskGetApplicationTaskTagFromISR( TaskHandle_t xTask );
+ *
+ * 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
+
+/**
+ * task.h
+ * BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask, void *pvParameter );
+ *
+ * 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
+ * http://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:
+
+ // 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;
+ uint32_t 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 );
+ }
+ }
+
+ */
+UBaseType_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, const UBaseType_t uxArraySize, uint32_t * const pulTotalRunTime ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * void vTaskList( char *pcWriteBuffer );
+ *
+ * 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 and stack usage.
+ *
+ * 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
+ * void vTaskGetRunTimeStats( char *pcWriteBuffer );
+ *
+ * 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
+* uint32_t ulTaskGetIdleRunTimeCounter( void );
+*
+* 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.
+*
+* 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.
+*
+* @return The total run time of 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
+*/
+uint32_t ulTaskGetIdleRunTimeCounter( void ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * BaseType_t xTaskNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction );
+ *
+ * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this
+ * function to be available.
+ *
+ * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private
+ * "notification value", which is a 32-bit unsigned integer (uint32_t).
+ *
+ * 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 the task's notification value. 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 xTaskNotifyWait() or ulTaskNotifyTake(). 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 xTaskNotifyWait() to [optionally] block to wait for a
+ * notification to be pending, or ulTaskNotifyTake() to [optionally] block
+ * to wait for its notification value to have a non-zero value. The task does
+ * not consume any CPU time while it is in the Blocked state.
+ *
+ * See http://www.FreeRTOS.org/RTOS-task-notifications.html for details.
+ *
+ * @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. xTaskNofify()
+ * 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.
+ *
+ * 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 xTaskNotify xTaskNotify
+ * \ingroup TaskNotifications
+ */
+BaseType_t xTaskGenericNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue ) PRIVILEGED_FUNCTION;
+#define xTaskNotify( xTaskToNotify, ulValue, eAction ) xTaskGenericNotify( ( xTaskToNotify ), ( ulValue ), ( eAction ), NULL )
+#define xTaskNotifyAndQuery( xTaskToNotify, ulValue, eAction, pulPreviousNotifyValue ) xTaskGenericNotify( ( xTaskToNotify ), ( ulValue ), ( eAction ), ( pulPreviousNotifyValue ) )
+
+/**
+ * task. h
+ * BaseType_t xTaskNotifyFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, BaseType_t *pxHigherPriorityTaskWoken );
+ *
+ * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this
+ * function to be available.
+ *
+ * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private
+ * "notification value", which is a 32-bit unsigned integer (uint32_t).
+ *
+ * A version of xTaskNotify() that can be used from an interrupt service routine
+ * (ISR).
+ *
+ * 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 the task's notification value. 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 xTaskNotifyWait() or ulTaskNotifyTake(). 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 xTaskNotifyWait() to [optionally] block to wait for a
+ * notification to be pending, or ulTaskNotifyTake() to [optionally] block
+ * to wait for its notification value to have a non-zero value. The task does
+ * not consume any CPU time while it is in the Blocked state.
+ *
+ * See http://www.FreeRTOS.org/RTOS-task-notifications.html for details.
+ *
+ * @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. xTaskNofify()
+ * 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 xTaskNotify xTaskNotify
+ * \ingroup TaskNotifications
+ */
+BaseType_t xTaskGenericNotifyFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue, BaseType_t *pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION;
+#define xTaskNotifyFromISR( xTaskToNotify, ulValue, eAction, pxHigherPriorityTaskWoken ) xTaskGenericNotifyFromISR( ( xTaskToNotify ), ( ulValue ), ( eAction ), NULL, ( pxHigherPriorityTaskWoken ) )
+#define xTaskNotifyAndQueryFromISR( xTaskToNotify, ulValue, eAction, pulPreviousNotificationValue, pxHigherPriorityTaskWoken ) xTaskGenericNotifyFromISR( ( xTaskToNotify ), ( ulValue ), ( eAction ), ( pulPreviousNotificationValue ), ( pxHigherPriorityTaskWoken ) )
+
+/**
+ * task. h
+ * BaseType_t xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait );
+ *
+ * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this
+ * function to be available.
+ *
+ * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private
+ * "notification value", which is a 32-bit unsigned integer (uint32_t).
+ *
+ * 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 the task's notification value. 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 xTaskNotifyWait() or ulTaskNotifyTake(). 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 xTaskNotifyWait() to [optionally] block to wait for a
+ * notification to be pending, or ulTaskNotifyTake() to [optionally] block
+ * to wait for its notification value to have a non-zero value. The task does
+ * not consume any CPU time while it is in the Blocked state.
+ *
+ * See http://www.FreeRTOS.org/RTOS-task-notifications.html for details.
+ *
+ * @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_TICSK( 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 xTaskNotifyWait xTaskNotifyWait
+ * \ingroup TaskNotifications
+ */
+BaseType_t xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * BaseType_t xTaskNotifyGive( TaskHandle_t xTaskToNotify );
+ *
+ * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this macro
+ * to be available.
+ *
+ * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private
+ * "notification value", which is a 32-bit unsigned integer (uint32_t).
+ *
+ * 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 the task's notification value. 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.
+ *
+ * xTaskNotifyGive() 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
+ * xTaskNotifyGive().
+ *
+ * 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 ulTaskNotificationTake() API function rather than the
+ * xTaskNotifyWait() API function.
+ *
+ * See http://www.FreeRTOS.org/RTOS-task-notifications.html for more details.
+ *
+ * @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().
+ *
+ * @return xTaskNotifyGive() is a macro that calls xTaskNotify() with the
+ * eAction parameter set to eIncrement - so pdPASS is always returned.
+ *
+ * \defgroup xTaskNotifyGive xTaskNotifyGive
+ * \ingroup TaskNotifications
+ */
+#define xTaskNotifyGive( xTaskToNotify ) xTaskGenericNotify( ( xTaskToNotify ), ( 0 ), eIncrement, NULL )
+
+/**
+ * task. h
+ * void vTaskNotifyGiveFromISR( TaskHandle_t xTaskHandle, BaseType_t *pxHigherPriorityTaskWoken );
+ *
+ * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this macro
+ * to be available.
+ *
+ * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private
+ * "notification value", which is a 32-bit unsigned integer (uint32_t).
+ *
+ * A version of xTaskNotifyGive() that can be called from an interrupt service
+ * routine (ISR).
+ *
+ * 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 the task's notification value. 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.
+ *
+ * vTaskNotifyGiveFromISR() 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 vTaskNotifyGiveFromISR().
+ *
+ * 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 ulTaskNotificationTake() API function rather than the
+ * xTaskNotifyWait() API function.
+ *
+ * See http://www.FreeRTOS.org/RTOS-task-notifications.html for more details.
+ *
+ * @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 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 xTaskNotifyWait xTaskNotifyWait
+ * \ingroup TaskNotifications
+ */
+void vTaskNotifyGiveFromISR( TaskHandle_t xTaskToNotify, BaseType_t *pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * uint32_t ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait );
+ *
+ * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this
+ * function to be available.
+ *
+ * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private
+ * "notification value", which is a 32-bit unsigned integer (uint32_t).
+ *
+ * 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 the task's notification value. 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.
+ *
+ * ulTaskNotifyTake() 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
+ * ulTaskNotifyTake().
+ *
+ * When a task is using its notification value as a binary or counting semaphore
+ * other tasks should send notifications to it using the xTaskNotifyGive()
+ * macro, or xTaskNotify() function with the eAction parameter set to
+ * eIncrement.
+ *
+ * ulTaskNotifyTake() can either clear the task's notification value to
+ * zero on exit, in which case the notification value acts like a binary
+ * semaphore, or decrement the task's notification value on exit, in which case
+ * the notification value acts like a counting semaphore.
+ *
+ * A task can use ulTaskNotifyTake() to [optionally] block to wait for a
+ * the task's notification value to be non-zero. The task does not consume any
+ * CPU time while it is in the Blocked state.
+ *
+ * Where as xTaskNotifyWait() will return when a notification is pending,
+ * ulTaskNotifyTake() will return when the task's notification value is
+ * not zero.
+ *
+ * See http://www.FreeRTOS.org/RTOS-task-notifications.html for details.
+ *
+ * @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_TICSK( 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 ulTaskNotifyTake ulTaskNotifyTake
+ * \ingroup TaskNotifications
+ */
+uint32_t ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * BaseType_t xTaskNotifyStateClear( TaskHandle_t xTask );
+ *
+ * If the notification state of the task referenced by the handle xTask is
+ * eNotified, then set the task's notification state to eNotWaitingNotification.
+ * The task's notification value is not altered. Set xTask to NULL to clear the
+ * notification state of the calling task.
+ *
+ * @return pdTRUE if the task's notification state was set to
+ * eNotWaitingNotification, otherwise pdFALSE.
+ * \defgroup xTaskNotifyStateClear xTaskNotifyStateClear
+ * \ingroup TaskNotifications
+ */
+BaseType_t xTaskNotifyStateClear( TaskHandle_t xTask );
+
+/**
+* task. h
+* uint32_t ulTaskNotifyValueClear( TaskHandle_t xTask, uint32_t ulBitsToClear );
+*
+* Clears the bits specified by the ulBitsToClear bit mask in the notification
+* value of the task referenced by xTask.
+*
+* 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 ulTaskNotifyValueClear( TaskHandle_t xTask, uint32_t ulBitsToClear ) PRIVILEGED_FUNCTION;
+
+/**
+ * task.h
+ * void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut )
+ *
+ * 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
+ * BaseType_t xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, TickType_t * const pxTicksToWait );
+ *
+ * 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:
+ *
+ // 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;
+ }
+
+ * \defgroup xTaskCheckForTimeOut xTaskCheckForTimeOut
+ * \ingroup TaskCtrl
+ */
+BaseType_t xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, TickType_t * const pxTicksToWait ) 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 tasks priority) to insert the list item into the event list is 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;
+
+/* Correct the tick count value after the application code has held
+interrupts disabled for an extended period. xTicksToCatchUp is 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.
+
+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. */
+BaseType_t xTaskCatchUpTicks( TickType_t xTicksToCatchUp ) 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 critial
+ * section.
+ */
+void vTaskInternalSetTimeOutState( TimeOut_t * const pxTimeOut ) PRIVILEGED_FUNCTION;
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* INC_TASK_H */
+
+
+
diff --git a/fw/Middlewares/Third_Party/FreeRTOS/Source/include/timers.h b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/timers.h
new file mode 100644
index 0000000..307ea1f
--- /dev/null
+++ b/fw/Middlewares/Third_Party/FreeRTOS/Source/include/timers.h
@@ -0,0 +1,1309 @@
+/*
+ * FreeRTOS Kernel V10.3.1
+ * 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 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 */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*-----------------------------------------------------------
+ * 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
+ * http://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
+ * http://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
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* TIMERS_H */
+
+
+
diff --git a/fw/Middlewares/Third_Party/FreeRTOS/Source/list.c b/fw/Middlewares/Third_Party/FreeRTOS/Source/list.c
new file mode 100644
index 0000000..7618ee8
--- /dev/null
+++ b/fw/Middlewares/Third_Party/FreeRTOS/Source/list.c
@@ -0,0 +1,198 @@
+/*
+ * FreeRTOS Kernel V10.3.1
+ * 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!
+ */
+
+
+#include
+#include "FreeRTOS.h"
+#include "list.h"
+
+/*-----------------------------------------------------------
+ * 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?).
+ **********************************************************************/
+
+ 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/fw/Middlewares/Third_Party/FreeRTOS/Source/portable/GCC/ARM_CM4F/port.c b/fw/Middlewares/Third_Party/FreeRTOS/Source/portable/GCC/ARM_CM4F/port.c
new file mode 100644
index 0000000..89a912c
--- /dev/null
+++ b/fw/Middlewares/Third_Party/FreeRTOS/Source/portable/GCC/ARM_CM4F/port.c
@@ -0,0 +1,775 @@
+/*
+ * FreeRTOS Kernel V10.3.1
+ * 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!
+ */
+
+/*-----------------------------------------------------------
+ * Implementation of functions defined in portable.h for the ARM CM4F port.
+ *----------------------------------------------------------*/
+
+/* Scheduler includes. */
+#include "FreeRTOS.h"
+#include "task.h"
+
+#ifndef __VFP_FP__
+ #error This port can only be used when the project options are configured to enable hardware floating point support.
+#endif
+
+#ifndef configSYSTICK_CLOCK_HZ
+ #define configSYSTICK_CLOCK_HZ configCPU_CLOCK_HZ
+ /* Ensure the SysTick is clocked at the same frequency as the core. */
+ #define portNVIC_SYSTICK_CLK_BIT ( 1UL << 2UL )
+#else
+ /* The way the SysTick is clocked is not modified in case it is not the same
+ as the core. */
+ #define portNVIC_SYSTICK_CLK_BIT ( 0 )
+#endif
+
+/* Constants required to manipulate the core. Registers first... */
+#define portNVIC_SYSTICK_CTRL_REG ( * ( ( volatile uint32_t * ) 0xe000e010 ) )
+#define portNVIC_SYSTICK_LOAD_REG ( * ( ( volatile uint32_t * ) 0xe000e014 ) )
+#define portNVIC_SYSTICK_CURRENT_VALUE_REG ( * ( ( volatile uint32_t * ) 0xe000e018 ) )
+#define portNVIC_SYSPRI2_REG ( * ( ( volatile uint32_t * ) 0xe000ed20 ) )
+/* ...then bits in the registers. */
+#define portNVIC_SYSTICK_INT_BIT ( 1UL << 1UL )
+#define portNVIC_SYSTICK_ENABLE_BIT ( 1UL << 0UL )
+#define portNVIC_SYSTICK_COUNT_FLAG_BIT ( 1UL << 16UL )
+#define portNVIC_PENDSVCLEAR_BIT ( 1UL << 27UL )
+#define portNVIC_PEND_SYSTICK_CLEAR_BIT ( 1UL << 25UL )
+
+/* Constants used to detect a Cortex-M7 r0p1 core, which should use the ARM_CM7
+r0p1 port. */
+#define portCPUID ( * ( ( volatile uint32_t * ) 0xE000ed00 ) )
+#define portCORTEX_M7_r0p1_ID ( 0x410FC271UL )
+#define portCORTEX_M7_r0p0_ID ( 0x410FC270UL )
+
+#define portNVIC_PENDSV_PRI ( ( ( uint32_t ) configKERNEL_INTERRUPT_PRIORITY ) << 16UL )
+#define portNVIC_SYSTICK_PRI ( ( ( uint32_t ) configKERNEL_INTERRUPT_PRIORITY ) << 24UL )
+
+/* Constants required to check the validity of an interrupt priority. */
+#define portFIRST_USER_INTERRUPT_NUMBER ( 16 )
+#define portNVIC_IP_REGISTERS_OFFSET_16 ( 0xE000E3F0 )
+#define portAIRCR_REG ( * ( ( volatile uint32_t * ) 0xE000ED0C ) )
+#define portMAX_8_BIT_VALUE ( ( uint8_t ) 0xff )
+#define portTOP_BIT_OF_BYTE ( ( uint8_t ) 0x80 )
+#define portMAX_PRIGROUP_BITS ( ( uint8_t ) 7 )
+#define portPRIORITY_GROUP_MASK ( 0x07UL << 8UL )
+#define portPRIGROUP_SHIFT ( 8UL )
+
+/* Masks off all bits but the VECTACTIVE bits in the ICSR register. */
+#define portVECTACTIVE_MASK ( 0xFFUL )
+
+/* Constants required to manipulate the VFP. */
+#define portFPCCR ( ( volatile uint32_t * ) 0xe000ef34 ) /* Floating point context control register. */
+#define portASPEN_AND_LSPEN_BITS ( 0x3UL << 30UL )
+
+/* Constants required to set up the initial stack. */
+#define portINITIAL_XPSR ( 0x01000000 )
+#define portINITIAL_EXC_RETURN ( 0xfffffffd )
+
+/* The systick is a 24-bit counter. */
+#define portMAX_24_BIT_NUMBER ( 0xffffffUL )
+
+/* For strict compliance with the Cortex-M spec the task start address should
+have bit-0 clear, as it is loaded into the PC on exit from an ISR. */
+#define portSTART_ADDRESS_MASK ( ( StackType_t ) 0xfffffffeUL )
+
+/* A fiddle factor to estimate the number of SysTick counts that would have
+occurred while the SysTick counter is stopped during tickless idle
+calculations. */
+#define portMISSED_COUNTS_FACTOR ( 45UL )
+
+/* 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
+
+/*
+ * 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 );
+
+/*
+ * Exception handlers.
+ */
+void xPortPendSVHandler( void ) __attribute__ (( naked ));
+void xPortSysTickHandler( void );
+void vPortSVCHandler( void ) __attribute__ (( naked ));
+
+/*
+ * Start first task is a separate function so it can be tested in isolation.
+ */
+static void prvPortStartFirstTask( void ) __attribute__ (( naked ));
+
+/*
+ * Function to enable the VFP.
+ */
+static void vPortEnableVFP( void ) __attribute__ (( naked ));
+
+/*
+ * Used to catch tasks that attempt to return from their implementing function.
+ */
+static void prvTaskExitError( void );
+
+/*-----------------------------------------------------------*/
+
+/* Each task maintains its own interrupt status in the critical nesting
+variable. */
+static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;
+
+/*
+ * The number of SysTick increments that make up one tick period.
+ */
+#if( configUSE_TICKLESS_IDLE == 1 )
+ static uint32_t ulTimerCountsForOneTick = 0;
+#endif /* configUSE_TICKLESS_IDLE */
+
+/*
+ * The maximum number of tick periods that can be suppressed is limited by the
+ * 24 bit resolution of the SysTick timer.
+ */
+#if( configUSE_TICKLESS_IDLE == 1 )
+ static uint32_t xMaximumPossibleSuppressedTicks = 0;
+#endif /* configUSE_TICKLESS_IDLE */
+
+/*
+ * Compensate for the CPU cycles that pass while the SysTick is stopped (low
+ * power functionality only.
+ */
+#if( configUSE_TICKLESS_IDLE == 1 )
+ static uint32_t ulStoppedTimerCompensation = 0;
+#endif /* configUSE_TICKLESS_IDLE */
+
+/*
+ * Used by the portASSERT_IF_INTERRUPT_PRIORITY_INVALID() macro to ensure
+ * FreeRTOS API functions are not called from interrupts that have been assigned
+ * a priority above configMAX_SYSCALL_INTERRUPT_PRIORITY.
+ */
+#if( configASSERT_DEFINED == 1 )
+ static uint8_t ucMaxSysCallPriority = 0;
+ static uint32_t ulMaxPRIGROUPValue = 0;
+ static const volatile uint8_t * const pcInterruptPriorityRegisters = ( const volatile uint8_t * const ) portNVIC_IP_REGISTERS_OFFSET_16;
+#endif /* configASSERT_DEFINED */
+
+/*-----------------------------------------------------------*/
+
+/*
+ * See header file for description.
+ */
+StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters )
+{
+ /* Simulate the stack frame as it would be created by a context switch
+ interrupt. */
+
+ /* Offset added to account for the way the MCU uses the stack on entry/exit
+ of interrupts, and to ensure alignment. */
+ pxTopOfStack--;
+
+ *pxTopOfStack = portINITIAL_XPSR; /* xPSR */
+ pxTopOfStack--;
+ *pxTopOfStack = ( ( StackType_t ) pxCode ) & portSTART_ADDRESS_MASK; /* PC */
+ pxTopOfStack--;
+ *pxTopOfStack = ( StackType_t ) portTASK_RETURN_ADDRESS; /* LR */
+
+ /* Save code space by skipping register initialisation. */
+ pxTopOfStack -= 5; /* R12, R3, R2 and R1. */
+ *pxTopOfStack = ( StackType_t ) pvParameters; /* R0 */
+
+ /* A save method is being used that requires each task to maintain its
+ own exec return value. */
+ pxTopOfStack--;
+ *pxTopOfStack = portINITIAL_EXC_RETURN;
+
+ pxTopOfStack -= 8; /* R11, R10, R9, R8, R7, R6, R5 and R4. */
+
+ return pxTopOfStack;
+}
+/*-----------------------------------------------------------*/
+
+static void prvTaskExitError( void )
+{
+volatile uint32_t ulDummy = 0;
+
+ /* A function that implements a task must not exit or attempt to return to
+ its caller as there is nothing to return to. If a task wants to exit it
+ should instead call vTaskDelete( NULL ).
+
+ Artificially force an assert() to be triggered if configASSERT() is
+ defined, then stop here so application writers can catch the error. */
+ configASSERT( uxCriticalNesting == ~0UL );
+ portDISABLE_INTERRUPTS();
+ while( ulDummy == 0 )
+ {
+ /* This file calls prvTaskExitError() after the scheduler has been
+ started to remove a compiler warning about the function being defined
+ but never called. ulDummy is used purely to quieten other warnings
+ about code appearing after this function is called - making ulDummy
+ volatile makes the compiler think the function could return and
+ therefore not output an 'unreachable code' warning for code that appears
+ after it. */
+ }
+}
+/*-----------------------------------------------------------*/
+
+void vPortSVCHandler( void )
+{
+ __asm volatile (
+ " ldr r3, pxCurrentTCBConst2 \n" /* Restore the context. */
+ " ldr r1, [r3] \n" /* Use pxCurrentTCBConst to get the pxCurrentTCB address. */
+ " ldr r0, [r1] \n" /* The first item in pxCurrentTCB is the task top of stack. */
+ " ldmia r0!, {r4-r11, r14} \n" /* Pop the registers that are not automatically saved on exception entry and the critical nesting count. */
+ " msr psp, r0 \n" /* Restore the task stack pointer. */
+ " isb \n"
+ " mov r0, #0 \n"
+ " msr basepri, r0 \n"
+ " bx r14 \n"
+ " \n"
+ " .align 4 \n"
+ "pxCurrentTCBConst2: .word pxCurrentTCB \n"
+ );
+}
+/*-----------------------------------------------------------*/
+
+static void prvPortStartFirstTask( void )
+{
+ /* Start the first task. This also clears the bit that indicates the FPU is
+ in use in case the FPU was used before the scheduler was started - which
+ would otherwise result in the unnecessary leaving of space in the SVC stack
+ for lazy saving of FPU registers. */
+ __asm volatile(
+ " ldr r0, =0xE000ED08 \n" /* Use the NVIC offset register to locate the stack. */
+ " ldr r0, [r0] \n"
+ " ldr r0, [r0] \n"
+ " msr msp, r0 \n" /* Set the msp back to the start of the stack. */
+ " mov r0, #0 \n" /* Clear the bit that indicates the FPU is in use, see comment above. */
+ " msr control, r0 \n"
+ " cpsie i \n" /* Globally enable interrupts. */
+ " cpsie f \n"
+ " dsb \n"
+ " isb \n"
+ " svc 0 \n" /* System call to start first task. */
+ " nop \n"
+ );
+}
+/*-----------------------------------------------------------*/
+
+/*
+ * See header file for description.
+ */
+BaseType_t xPortStartScheduler( void )
+{
+ /* configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to 0.
+ See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
+ configASSERT( configMAX_SYSCALL_INTERRUPT_PRIORITY );
+
+ /* This port can be used on all revisions of the Cortex-M7 core other than
+ the r0p1 parts. r0p1 parts should use the port from the
+ /source/portable/GCC/ARM_CM7/r0p1 directory. */
+ configASSERT( portCPUID != portCORTEX_M7_r0p1_ID );
+ configASSERT( portCPUID != portCORTEX_M7_r0p0_ID );
+
+ #if( configASSERT_DEFINED == 1 )
+ {
+ volatile uint32_t ulOriginalPriority;
+ volatile uint8_t * const pucFirstUserPriorityRegister = ( volatile uint8_t * const ) ( portNVIC_IP_REGISTERS_OFFSET_16 + portFIRST_USER_INTERRUPT_NUMBER );
+ volatile uint8_t ucMaxPriorityValue;
+
+ /* Determine the maximum priority from which ISR safe FreeRTOS API
+ functions can be called. ISR safe functions are those that end in
+ "FromISR". FreeRTOS maintains separate thread and ISR API functions to
+ ensure interrupt entry is as fast and simple as possible.
+
+ Save the interrupt priority value that is about to be clobbered. */
+ ulOriginalPriority = *pucFirstUserPriorityRegister;
+
+ /* Determine the number of priority bits available. First write to all
+ possible bits. */
+ *pucFirstUserPriorityRegister = portMAX_8_BIT_VALUE;
+
+ /* Read the value back to see how many bits stuck. */
+ ucMaxPriorityValue = *pucFirstUserPriorityRegister;
+
+ /* Use the same mask on the maximum system call priority. */
+ ucMaxSysCallPriority = configMAX_SYSCALL_INTERRUPT_PRIORITY & ucMaxPriorityValue;
+
+ /* Calculate the maximum acceptable priority group value for the number
+ of bits read back. */
+ ulMaxPRIGROUPValue = portMAX_PRIGROUP_BITS;
+ while( ( ucMaxPriorityValue & portTOP_BIT_OF_BYTE ) == portTOP_BIT_OF_BYTE )
+ {
+ ulMaxPRIGROUPValue--;
+ ucMaxPriorityValue <<= ( uint8_t ) 0x01;
+ }
+
+ #ifdef __NVIC_PRIO_BITS
+ {
+ /* Check the CMSIS configuration that defines the number of
+ priority bits matches the number of priority bits actually queried
+ from the hardware. */
+ configASSERT( ( portMAX_PRIGROUP_BITS - ulMaxPRIGROUPValue ) == __NVIC_PRIO_BITS );
+ }
+ #endif
+
+ #ifdef configPRIO_BITS
+ {
+ /* Check the FreeRTOS configuration that defines the number of
+ priority bits matches the number of priority bits actually queried
+ from the hardware. */
+ configASSERT( ( portMAX_PRIGROUP_BITS - ulMaxPRIGROUPValue ) == configPRIO_BITS );
+ }
+ #endif
+
+ /* Shift the priority group value back to its position within the AIRCR
+ register. */
+ ulMaxPRIGROUPValue <<= portPRIGROUP_SHIFT;
+ ulMaxPRIGROUPValue &= portPRIORITY_GROUP_MASK;
+
+ /* Restore the clobbered interrupt priority register to its original
+ value. */
+ *pucFirstUserPriorityRegister = ulOriginalPriority;
+ }
+ #endif /* conifgASSERT_DEFINED */
+
+ /* Make PendSV and SysTick the lowest priority interrupts. */
+ portNVIC_SYSPRI2_REG |= portNVIC_PENDSV_PRI;
+ portNVIC_SYSPRI2_REG |= portNVIC_SYSTICK_PRI;
+
+ /* Start the timer that generates the tick ISR. Interrupts are disabled
+ here already. */
+ vPortSetupTimerInterrupt();
+
+ /* Initialise the critical nesting count ready for the first task. */
+ uxCriticalNesting = 0;
+
+ /* Ensure the VFP is enabled - it should be anyway. */
+ vPortEnableVFP();
+
+ /* Lazy save always. */
+ *( portFPCCR ) |= portASPEN_AND_LSPEN_BITS;
+
+ /* Start the first task. */
+ prvPortStartFirstTask();
+
+ /* Should never get here as the tasks will now be executing! Call the task
+ exit error function to prevent compiler warnings about a static function
+ not being called in the case that the application writer overrides this
+ functionality by defining configTASK_RETURN_ADDRESS. Call
+ vTaskSwitchContext() so link time optimisation does not remove the
+ symbol. */
+ vTaskSwitchContext();
+ prvTaskExitError();
+
+ /* Should not get here! */
+ return 0;
+}
+/*-----------------------------------------------------------*/
+
+void vPortEndScheduler( void )
+{
+ /* Not implemented in ports where there is nothing to return to.
+ Artificially force an assert. */
+ configASSERT( uxCriticalNesting == 1000UL );
+}
+/*-----------------------------------------------------------*/
+
+void vPortEnterCritical( void )
+{
+ portDISABLE_INTERRUPTS();
+ 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( uxCriticalNesting == 1 )
+ {
+ configASSERT( ( portNVIC_INT_CTRL_REG & portVECTACTIVE_MASK ) == 0 );
+ }
+}
+/*-----------------------------------------------------------*/
+
+void vPortExitCritical( void )
+{
+ configASSERT( uxCriticalNesting );
+ uxCriticalNesting--;
+ if( uxCriticalNesting == 0 )
+ {
+ portENABLE_INTERRUPTS();
+ }
+}
+/*-----------------------------------------------------------*/
+
+void xPortPendSVHandler( void )
+{
+ /* This is a naked function. */
+
+ __asm volatile
+ (
+ " mrs r0, psp \n"
+ " isb \n"
+ " \n"
+ " ldr r3, pxCurrentTCBConst \n" /* Get the location of the current TCB. */
+ " ldr r2, [r3] \n"
+ " \n"
+ " tst r14, #0x10 \n" /* Is the task using the FPU context? If so, push high vfp registers. */
+ " it eq \n"
+ " vstmdbeq r0!, {s16-s31} \n"
+ " \n"
+ " stmdb r0!, {r4-r11, r14} \n" /* Save the core registers. */
+ " str r0, [r2] \n" /* Save the new top of stack into the first member of the TCB. */
+ " \n"
+ " stmdb sp!, {r0, r3} \n"
+ " mov r0, %0 \n"
+ " msr basepri, r0 \n"
+ " dsb \n"
+ " isb \n"
+ " bl vTaskSwitchContext \n"
+ " mov r0, #0 \n"
+ " msr basepri, r0 \n"
+ " ldmia sp!, {r0, r3} \n"
+ " \n"
+ " ldr r1, [r3] \n" /* The first item in pxCurrentTCB is the task top of stack. */
+ " ldr r0, [r1] \n"
+ " \n"
+ " ldmia r0!, {r4-r11, r14} \n" /* Pop the core registers. */
+ " \n"
+ " tst r14, #0x10 \n" /* Is the task using the FPU context? If so, pop the high vfp registers too. */
+ " it eq \n"
+ " vldmiaeq r0!, {s16-s31} \n"
+ " \n"
+ " msr psp, r0 \n"
+ " isb \n"
+ " \n"
+ #ifdef WORKAROUND_PMU_CM001 /* XMC4000 specific errata workaround. */
+ #if WORKAROUND_PMU_CM001 == 1
+ " push { r14 } \n"
+ " pop { pc } \n"
+ #endif
+ #endif
+ " \n"
+ " bx r14 \n"
+ " \n"
+ " .align 4 \n"
+ "pxCurrentTCBConst: .word pxCurrentTCB \n"
+ ::"i"(configMAX_SYSCALL_INTERRUPT_PRIORITY)
+ );
+}
+/*-----------------------------------------------------------*/
+
+void xPortSysTickHandler( void )
+{
+ /* The SysTick runs at the lowest interrupt priority, so when this interrupt
+ executes all interrupts must be unmasked. There is therefore no need to
+ save and then restore the interrupt mask value as its value is already
+ known. */
+ portDISABLE_INTERRUPTS();
+ {
+ /* Increment the RTOS tick. */
+ if( xTaskIncrementTick() != pdFALSE )
+ {
+ /* A context switch is required. Context switching is performed in
+ the PendSV interrupt. Pend the PendSV interrupt. */
+ portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
+ }
+ }
+ portENABLE_INTERRUPTS();
+}
+/*-----------------------------------------------------------*/
+
+#if( configUSE_TICKLESS_IDLE == 1 )
+
+ __attribute__((weak)) void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )
+ {
+ uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements;
+ TickType_t xModifiableIdleTime;
+
+ /* Make sure the SysTick reload value does not overflow the counter. */
+ if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )
+ {
+ xExpectedIdleTime = xMaximumPossibleSuppressedTicks;
+ }
+
+ /* Stop the SysTick momentarily. The time the SysTick is stopped for
+ is accounted for as best it can be, but using the tickless mode will
+ inevitably result in some tiny drift of the time maintained by the
+ kernel with respect to calendar time. */
+ portNVIC_SYSTICK_CTRL_REG &= ~portNVIC_SYSTICK_ENABLE_BIT;
+
+ /* Calculate the reload value required to wait xExpectedIdleTime
+ tick periods. -1 is used because this code will execute part way
+ through one of the tick periods. */
+ ulReloadValue = portNVIC_SYSTICK_CURRENT_VALUE_REG + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) );
+ if( ulReloadValue > ulStoppedTimerCompensation )
+ {
+ ulReloadValue -= ulStoppedTimerCompensation;
+ }
+
+ /* Enter a critical section but don't use the taskENTER_CRITICAL()
+ method as that will mask interrupts that should exit sleep mode. */
+ __asm volatile( "cpsid i" ::: "memory" );
+ __asm volatile( "dsb" );
+ __asm volatile( "isb" );
+
+ /* If a context switch is pending or a task is waiting for the scheduler
+ to be unsuspended then abandon the low power entry. */
+ if( eTaskConfirmSleepModeStatus() == eAbortSleep )
+ {
+ /* Restart from whatever is left in the count register to complete
+ this tick period. */
+ portNVIC_SYSTICK_LOAD_REG = portNVIC_SYSTICK_CURRENT_VALUE_REG;
+
+ /* Restart SysTick. */
+ portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
+
+ /* Reset the reload register to the value required for normal tick
+ periods. */
+ portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
+
+ /* Re-enable interrupts - see comments above the cpsid instruction()
+ above. */
+ __asm volatile( "cpsie i" ::: "memory" );
+ }
+ else
+ {
+ /* Set the new reload value. */
+ portNVIC_SYSTICK_LOAD_REG = ulReloadValue;
+
+ /* Clear the SysTick count flag and set the count value back to
+ zero. */
+ portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
+
+ /* Restart SysTick. */
+ portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
+
+ /* Sleep until something happens. configPRE_SLEEP_PROCESSING() can
+ set its parameter to 0 to indicate that its implementation contains
+ its own wait for interrupt or wait for event instruction, and so wfi
+ should not be executed again. However, the original expected idle
+ time variable must remain unmodified, so a copy is taken. */
+ xModifiableIdleTime = xExpectedIdleTime;
+ configPRE_SLEEP_PROCESSING( xModifiableIdleTime );
+ if( xModifiableIdleTime > 0 )
+ {
+ __asm volatile( "dsb" ::: "memory" );
+ __asm volatile( "wfi" );
+ __asm volatile( "isb" );
+ }
+ configPOST_SLEEP_PROCESSING( xExpectedIdleTime );
+
+ /* Re-enable interrupts to allow the interrupt that brought the MCU
+ out of sleep mode to execute immediately. see comments above
+ __disable_interrupt() call above. */
+ __asm volatile( "cpsie i" ::: "memory" );
+ __asm volatile( "dsb" );
+ __asm volatile( "isb" );
+
+ /* Disable interrupts again because the clock is about to be stopped
+ and interrupts that execute while the clock is stopped will increase
+ any slippage between the time maintained by the RTOS and calendar
+ time. */
+ __asm volatile( "cpsid i" ::: "memory" );
+ __asm volatile( "dsb" );
+ __asm volatile( "isb" );
+
+ /* Disable the SysTick clock without reading the
+ portNVIC_SYSTICK_CTRL_REG register to ensure the
+ portNVIC_SYSTICK_COUNT_FLAG_BIT is not cleared if it is set. Again,
+ the time the SysTick is stopped for is accounted for as best it can
+ be, but using the tickless mode will inevitably result in some tiny
+ drift of the time maintained by the kernel with respect to calendar
+ time*/
+ portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT );
+
+ /* Determine if the SysTick clock has already counted to zero and
+ been set back to the current reload value (the reload back being
+ correct for the entire expected idle time) or if the SysTick is yet
+ to count to zero (in which case an interrupt other than the SysTick
+ must have brought the system out of sleep mode). */
+ if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
+ {
+ uint32_t ulCalculatedLoadValue;
+
+ /* The tick interrupt is already pending, and the SysTick count
+ reloaded with ulReloadValue. Reset the
+ portNVIC_SYSTICK_LOAD_REG with whatever remains of this tick
+ period. */
+ ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG );
+
+ /* Don't allow a tiny value, or values that have somehow
+ underflowed because the post sleep hook did something
+ that took too long. */
+ if( ( ulCalculatedLoadValue < ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) )
+ {
+ ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL );
+ }
+
+ portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;
+
+ /* As the pending tick will be processed as soon as this
+ function exits, the tick value maintained by the tick is stepped
+ forward by one less than the time spent waiting. */
+ ulCompleteTickPeriods = xExpectedIdleTime - 1UL;
+ }
+ else
+ {
+ /* Something other than the tick interrupt ended the sleep.
+ Work out how long the sleep lasted rounded to complete tick
+ periods (not the ulReload value which accounted for part
+ ticks). */
+ ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - portNVIC_SYSTICK_CURRENT_VALUE_REG;
+
+ /* How many complete tick periods passed while the processor
+ was waiting? */
+ ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;
+
+ /* The reload value is set to whatever fraction of a single tick
+ period remains. */
+ portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements;
+ }
+
+ /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG
+ again, then set portNVIC_SYSTICK_LOAD_REG back to its standard
+ value. */
+ portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
+ portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
+ vTaskStepTick( ulCompleteTickPeriods );
+ portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
+
+ /* Exit with interrupts enabled. */
+ __asm volatile( "cpsie i" ::: "memory" );
+ }
+ }
+
+#endif /* #if configUSE_TICKLESS_IDLE */
+/*-----------------------------------------------------------*/
+
+/*
+ * Setup the systick timer to generate the tick interrupts at the required
+ * frequency.
+ */
+__attribute__(( weak )) void vPortSetupTimerInterrupt( void )
+{
+ /* Calculate the constants required to configure the tick interrupt. */
+ #if( configUSE_TICKLESS_IDLE == 1 )
+ {
+ ulTimerCountsForOneTick = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ );
+ xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;
+ ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ );
+ }
+ #endif /* configUSE_TICKLESS_IDLE */
+
+ /* Stop and clear the SysTick. */
+ portNVIC_SYSTICK_CTRL_REG = 0UL;
+ portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
+
+ /* Configure SysTick to interrupt at the requested rate. */
+ portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;
+ portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT );
+}
+/*-----------------------------------------------------------*/
+
+/* This is a naked function. */
+static void vPortEnableVFP( void )
+{
+ __asm volatile
+ (
+ " ldr.w r0, =0xE000ED88 \n" /* The FPU enable bits are in the CPACR. */
+ " ldr r1, [r0] \n"
+ " \n"
+ " orr r1, r1, #( 0xf << 20 ) \n" /* Enable CP10 and CP11 coprocessors, then save back. */
+ " str r1, [r0] \n"
+ " bx r14 "
+ );
+}
+/*-----------------------------------------------------------*/
+
+#if( configASSERT_DEFINED == 1 )
+
+ void vPortValidateInterruptPriority( void )
+ {
+ uint32_t ulCurrentInterrupt;
+ uint8_t ucCurrentPriority;
+
+ /* Obtain the number of the currently executing interrupt. */
+ __asm volatile( "mrs %0, ipsr" : "=r"( ulCurrentInterrupt ) :: "memory" );
+
+ /* Is the interrupt number a user defined interrupt? */
+ if( ulCurrentInterrupt >= portFIRST_USER_INTERRUPT_NUMBER )
+ {
+ /* Look up the interrupt's priority. */
+ ucCurrentPriority = pcInterruptPriorityRegisters[ ulCurrentInterrupt ];
+
+ /* The following assertion will fail if a service routine (ISR) for
+ an interrupt that has been assigned a priority above
+ configMAX_SYSCALL_INTERRUPT_PRIORITY calls an ISR safe FreeRTOS API
+ function. ISR safe FreeRTOS API functions must *only* be called
+ from interrupts that have been assigned a priority at or below
+ configMAX_SYSCALL_INTERRUPT_PRIORITY.
+
+ Numerically low interrupt priority numbers represent logically high
+ interrupt priorities, therefore the priority of the interrupt must
+ be set to a value equal to or numerically *higher* than
+ configMAX_SYSCALL_INTERRUPT_PRIORITY.
+
+ Interrupts that use the FreeRTOS API must not be left at their
+ default priority of zero as that is the highest possible priority,
+ which is guaranteed to be above configMAX_SYSCALL_INTERRUPT_PRIORITY,
+ and therefore also guaranteed to be invalid.
+
+ FreeRTOS maintains separate thread and ISR API functions to ensure
+ interrupt entry is as fast and simple as possible.
+
+ The following links provide detailed information:
+ http://www.freertos.org/RTOS-Cortex-M3-M4.html
+ http://www.freertos.org/FAQHelp.html */
+ configASSERT( ucCurrentPriority >= ucMaxSysCallPriority );
+ }
+
+ /* Priority grouping: The interrupt controller (NVIC) allows the bits
+ that define each interrupt's priority to be split between bits that
+ define the interrupt's pre-emption priority bits and bits that define
+ the interrupt's sub-priority. For simplicity all bits must be defined
+ to be pre-emption priority bits. The following assertion will fail if
+ this is not the case (if some bits represent a sub-priority).
+
+ If the application only uses CMSIS libraries for interrupt
+ configuration then the correct setting can be achieved on all Cortex-M
+ devices by calling NVIC_SetPriorityGrouping( 0 ); before starting the
+ scheduler. Note however that some vendor specific peripheral libraries
+ assume a non-zero priority group setting, in which cases using a value
+ of zero will result in unpredictable behaviour. */
+ configASSERT( ( portAIRCR_REG & portPRIORITY_GROUP_MASK ) <= ulMaxPRIGROUPValue );
+ }
+
+#endif /* configASSERT_DEFINED */
+
+
diff --git a/fw/Middlewares/Third_Party/FreeRTOS/Source/portable/GCC/ARM_CM4F/portmacro.h b/fw/Middlewares/Third_Party/FreeRTOS/Source/portable/GCC/ARM_CM4F/portmacro.h
new file mode 100644
index 0000000..d0a566a
--- /dev/null
+++ b/fw/Middlewares/Third_Party/FreeRTOS/Source/portable/GCC/ARM_CM4F/portmacro.h
@@ -0,0 +1,243 @@
+/*
+ * FreeRTOS Kernel V10.3.1
+ * 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 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. */
+#define portCHAR char
+#define portFLOAT float
+#define portDOUBLE double
+#define portLONG long
+#define portSHORT short
+#define portSTACK_TYPE uint32_t
+#define portBASE_TYPE long
+
+typedef portSTACK_TYPE StackType_t;
+typedef long BaseType_t;
+typedef unsigned long UBaseType_t;
+
+#if( configUSE_16_BIT_TICKS == 1 )
+ typedef uint16_t TickType_t;
+ #define portMAX_DELAY ( TickType_t ) 0xffff
+#else
+ typedef uint32_t TickType_t;
+ #define portMAX_DELAY ( TickType_t ) 0xffffffffUL
+
+ /* 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
+#endif
+/*-----------------------------------------------------------*/
+
+/* Architecture specifics. */
+#define portSTACK_GROWTH ( -1 )
+#define portTICK_PERIOD_MS ( ( TickType_t ) 1000 / configTICK_RATE_HZ )
+#define portBYTE_ALIGNMENT 8
+/*-----------------------------------------------------------*/
+
+/* Scheduler utilities. */
+#define portYIELD() \
+{ \
+ /* Set a PendSV to request a context switch. */ \
+ portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT; \
+ \
+ /* Barriers are normally not required but do ensure the code is completely \
+ within the specified behaviour for the architecture. */ \
+ __asm volatile( "dsb" ::: "memory" ); \
+ __asm volatile( "isb" ); \
+}
+
+#define portNVIC_INT_CTRL_REG ( * ( ( volatile uint32_t * ) 0xe000ed04 ) )
+#define portNVIC_PENDSVSET_BIT ( 1UL << 28UL )
+#define portEND_SWITCHING_ISR( xSwitchRequired ) if( xSwitchRequired != pdFALSE ) portYIELD()
+#define portYIELD_FROM_ISR( x ) portEND_SWITCHING_ISR( x )
+/*-----------------------------------------------------------*/
+
+/* Critical section management. */
+extern void vPortEnterCritical( void );
+extern void vPortExitCritical( void );
+#define portSET_INTERRUPT_MASK_FROM_ISR() ulPortRaiseBASEPRI()
+#define portCLEAR_INTERRUPT_MASK_FROM_ISR(x) vPortSetBASEPRI(x)
+#define portDISABLE_INTERRUPTS() vPortRaiseBASEPRI()
+#define portENABLE_INTERRUPTS() vPortSetBASEPRI(0)
+#define portENTER_CRITICAL() vPortEnterCritical()
+#define portEXIT_CRITICAL() vPortExitCritical()
+
+/*-----------------------------------------------------------*/
+
+/* 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 )
+/*-----------------------------------------------------------*/
+
+/* Tickless idle/low power functionality. */
+#ifndef portSUPPRESS_TICKS_AND_SLEEP
+ extern void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime );
+ #define portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ) vPortSuppressTicksAndSleep( xExpectedIdleTime )
+#endif
+/*-----------------------------------------------------------*/
+
+/* Architecture specific optimisations. */
+#ifndef configUSE_PORT_OPTIMISED_TASK_SELECTION
+ #define configUSE_PORT_OPTIMISED_TASK_SELECTION 1
+#endif
+
+#if configUSE_PORT_OPTIMISED_TASK_SELECTION == 1
+
+ /* Generic helper function. */
+ __attribute__( ( always_inline ) ) static inline uint8_t ucPortCountLeadingZeros( uint32_t ulBitmap )
+ {
+ uint8_t ucReturn;
+
+ __asm volatile ( "clz %0, %1" : "=r" ( ucReturn ) : "r" ( ulBitmap ) : "memory" );
+ return ucReturn;
+ }
+
+ /* 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 - ( uint32_t ) ucPortCountLeadingZeros( ( uxReadyPriorities ) ) )
+
+#endif /* configUSE_PORT_OPTIMISED_TASK_SELECTION */
+
+/*-----------------------------------------------------------*/
+
+#ifdef configASSERT
+ void vPortValidateInterruptPriority( void );
+ #define portASSERT_IF_INTERRUPT_PRIORITY_INVALID() vPortValidateInterruptPriority()
+#endif
+
+/* portNOP() is not required by this port. */
+#define portNOP()
+
+#define portINLINE __inline
+
+#ifndef portFORCE_INLINE
+ #define portFORCE_INLINE inline __attribute__(( always_inline))
+#endif
+
+portFORCE_INLINE static BaseType_t xPortIsInsideInterrupt( void )
+{
+uint32_t ulCurrentInterrupt;
+BaseType_t xReturn;
+
+ /* Obtain the number of the currently executing interrupt. */
+ __asm volatile( "mrs %0, ipsr" : "=r"( ulCurrentInterrupt ) :: "memory" );
+
+ if( ulCurrentInterrupt == 0 )
+ {
+ xReturn = pdFALSE;
+ }
+ else
+ {
+ xReturn = pdTRUE;
+ }
+
+ return xReturn;
+}
+
+/*-----------------------------------------------------------*/
+
+portFORCE_INLINE static void vPortRaiseBASEPRI( void )
+{
+uint32_t ulNewBASEPRI;
+
+ __asm volatile
+ (
+ " mov %0, %1 \n" \
+ " msr basepri, %0 \n" \
+ " isb \n" \
+ " dsb \n" \
+ :"=r" (ulNewBASEPRI) : "i" ( configMAX_SYSCALL_INTERRUPT_PRIORITY ) : "memory"
+ );
+}
+
+/*-----------------------------------------------------------*/
+
+portFORCE_INLINE static uint32_t ulPortRaiseBASEPRI( void )
+{
+uint32_t ulOriginalBASEPRI, ulNewBASEPRI;
+
+ __asm volatile
+ (
+ " mrs %0, basepri \n" \
+ " mov %1, %2 \n" \
+ " msr basepri, %1 \n" \
+ " isb \n" \
+ " dsb \n" \
+ :"=r" (ulOriginalBASEPRI), "=r" (ulNewBASEPRI) : "i" ( configMAX_SYSCALL_INTERRUPT_PRIORITY ) : "memory"
+ );
+
+ /* This return will not be reached but is necessary to prevent compiler
+ warnings. */
+ return ulOriginalBASEPRI;
+}
+/*-----------------------------------------------------------*/
+
+portFORCE_INLINE static void vPortSetBASEPRI( uint32_t ulNewMaskValue )
+{
+ __asm volatile
+ (
+ " msr basepri, %0 " :: "r" ( ulNewMaskValue ) : "memory"
+ );
+}
+/*-----------------------------------------------------------*/
+
+#define portMEMORY_BARRIER() __asm volatile( "" ::: "memory" )
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* PORTMACRO_H */
+
diff --git a/fw/Middlewares/Third_Party/FreeRTOS/Source/portable/MemMang/heap_4.c b/fw/Middlewares/Third_Party/FreeRTOS/Source/portable/MemMang/heap_4.c
new file mode 100644
index 0000000..eaf443f
--- /dev/null
+++ b/fw/Middlewares/Third_Party/FreeRTOS/Source/portable/MemMang/heap_4.c
@@ -0,0 +1,492 @@
+/*
+ * FreeRTOS Kernel V10.3.1
+ * 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 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 http://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
+ 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 );
+
+/*
+ * Called automatically to setup the required heap structures the first time
+ * pvPortMalloc() is called.
+ */
+static void prvHeapInit( void );
+
+/*-----------------------------------------------------------*/
+
+/* 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. */
+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. */
+static size_t xFreeBytesRemaining = 0U;
+static size_t xMinimumEverFreeBytesRemaining = 0U;
+static size_t xNumberOfSuccessfulAllocations = 0;
+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. */
+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 is increased so it can contain a BlockLink_t
+ structure in addition to the requested amount of bytes. */
+ if( xWantedSize > 0 )
+ {
+ xWantedSize += xHeapStructSize;
+
+ /* Ensure that blocks are always aligned to the required number
+ of bytes. */
+ if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 )
+ {
+ /* Byte alignment required. */
+ xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) );
+ configASSERT( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) == 0 );
+ }
+ else
+ {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ else
+ {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ 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
+
+ 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 )
+{
+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 )
+{
+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 );
+ }
+ }
+ 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/fw/Middlewares/Third_Party/FreeRTOS/Source/queue.c b/fw/Middlewares/Third_Party/FreeRTOS/Source/queue.c
new file mode 100644
index 0000000..b3203b8
--- /dev/null
+++ b/fw/Middlewares/Third_Party/FreeRTOS/Source/queue.c
@@ -0,0 +1,2945 @@
+/*
+ * FreeRTOS Kernel V10.3.1
+ * 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!
+ */
+
+#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 )
+
+/* 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 )
+{
+Queue_t * const pxQueue = xQueue;
+
+ configASSERT( pxQueue );
+
+ 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();
+
+ /* A value is returned for calling semantic consistency with previous
+ versions. */
+ return pdPASS;
+}
+/*-----------------------------------------------------------*/
+
+#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;
+
+ configASSERT( uxQueueLength > ( UBaseType_t ) 0 );
+
+ /* The StaticQueue_t structure and the queue storage area must be
+ supplied. */
+ configASSERT( 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. */
+ configASSERT( !( ( pucQueueStorage != NULL ) && ( uxItemSize == 0 ) ) );
+ configASSERT( !( ( 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 );
+ configASSERT( xSize == sizeof( Queue_t ) );
+ ( 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( pxNewQueue != NULL )
+ {
+ #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
+ {
+ traceQUEUE_CREATE_FAILED( ucQueueType );
+ 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;
+ size_t xQueueSizeInBytes;
+ uint8_t *pucQueueStorage;
+
+ configASSERT( uxQueueLength > ( UBaseType_t ) 0 );
+
+ /* 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();
+ }
+
+ 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;
+
+ /* 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 ) )
+
+ 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_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;
+
+ configASSERT( uxMaxCount != 0 );
+ configASSERT( 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();
+ }
+
+ 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;
+
+ configASSERT( uxMaxCount != 0 );
+ configASSERT( 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();
+ }
+
+ 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 last 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 a 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: http://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. */
+ 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: http://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. */
+ 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
+
+ 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 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: http://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. */
+ 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: http://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
+ {
+ /* 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;
+
+ /* 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++ )
+ {
+ if( xQueueRegistry[ ux ].pcQueueName == NULL )
+ {
+ /* Store the information on this queue. */
+ xQueueRegistry[ ux ].pcQueueName = pcQueueName;
+ xQueueRegistry[ ux ].xHandle = xQueue;
+
+ traceQUEUE_REGISTRY_ADD( xQueue, pcQueueName );
+ break;
+ }
+ else
+ {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ }
+
+#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. */
+
+ /* 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;
+
+ /* 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. */
+
+ configASSERT( pxQueueSetContainer );
+ configASSERT( pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength );
+
+ if( pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength )
+ {
+ const int8_t cTxLock = pxQueueSetContainer->cTxLock;
+
+ traceQUEUE_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
+ {
+ pxQueueSetContainer->cTxLock = ( int8_t ) ( cTxLock + 1 );
+ }
+ }
+ else
+ {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ return xReturn;
+ }
+
+#endif /* configUSE_QUEUE_SETS */
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/fw/Middlewares/Third_Party/FreeRTOS/Source/stream_buffer.c b/fw/Middlewares/Third_Party/FreeRTOS/Source/stream_buffer.c
new file mode 100644
index 0000000..7ad5d54
--- /dev/null
+++ b/fw/Middlewares/Third_Party/FreeRTOS/Source/stream_buffer.c
@@ -0,0 +1,1263 @@
+/*
+ * FreeRTOS Kernel V10.3.1
+ * 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
+#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, them provide default implementations
+that uses task notifications. */
+/*lint -save -e9026 Function like macros allowed and needed here so they can be overidden. */
+#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 message buffer.
+ * Returns the number of bytes written, which will either equal xCount in the
+ * success case, or 0 if there was not enough space in the buffer (in which case
+ * no data is written into the buffer).
+ */
+static size_t prvWriteBytesToBuffer( StreamBuffer_t * const pxStreamBuffer, const uint8_t *pucData, size_t xCount ) 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,
+ size_t xBytesToStoreMessageLength ) 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;
+
+/*
+ * Read xMaxCount bytes from the pxStreamBuffer message buffer and write them
+ * to pucData.
+ */
+static size_t prvReadBytesFromBuffer( StreamBuffer_t *pxStreamBuffer,
+ uint8_t *pucData,
+ size_t xMaxCount,
+ size_t xBytesAvailable ) 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. */
+ xBufferSizeBytes++;
+ pucAllocatedMemory = ( uint8_t * ) pvPortMalloc( xBufferSizeBytes + sizeof( StreamBuffer_t ) ); /*lint !e9079 malloc() only returns void*. */
+
+ 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;
+
+ configASSERT( pxStreamBuffer );
+
+ xSpace = pxStreamBuffer->xLength + pxStreamBuffer->xTail;
+ xSpace -= pxStreamBuffer->xHead;
+ 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;
+
+ 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;
+
+ /* Overflow? */
+ configASSERT( xRequiredSpace > xDataLengthBytes );
+ }
+ 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 )
+{
+ BaseType_t xShouldWrite;
+ size_t xReturn;
+
+ if( xSpace == ( size_t ) 0 )
+ {
+ /* Doesn't matter if this is a stream buffer or a message buffer, there
+ is no space to write. */
+ xShouldWrite = pdFALSE;
+ }
+ else if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) == ( uint8_t ) 0 )
+ {
+ /* This is a stream buffer, as opposed to a message buffer, so writing a
+ stream of bytes rather than discrete messages. Write as many bytes as
+ possible. */
+ xShouldWrite = pdTRUE;
+ xDataLengthBytes = configMIN( xDataLengthBytes, xSpace );
+ }
+ else if( xSpace >= xRequiredSpace )
+ {
+ /* This is a message buffer, as opposed to a stream buffer, and 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. */
+ xShouldWrite = pdTRUE;
+ ( void ) prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) &( xDataLengthBytes ), sbBYTES_TO_STORE_MESSAGE_LENGTH );
+ }
+ else
+ {
+ /* There is space available, but not enough space. */
+ xShouldWrite = pdFALSE;
+ }
+
+ if( xShouldWrite != pdFALSE )
+ {
+ /* Writes the data itself. */
+ xReturn = prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) pvTxData, xDataLengthBytes ); /*lint !e9079 Storage buffer is implemented as uint8_t for ease of sizing, alighment and access. */
+ }
+ else
+ {
+ xReturn = 0;
+ }
+
+ return xReturn;
+}
+/*-----------------------------------------------------------*/
+
+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, xBytesToStoreMessageLength );
+
+ /* 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, xOriginalTail;
+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. Return its length without removing the length bytes
+ from the buffer. A copy of the tail is stored so the buffer can be
+ returned to its prior state as the message is not actually being
+ removed from the buffer. */
+ xOriginalTail = pxStreamBuffer->xTail;
+ ( void ) prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) &xTempReturn, sbBYTES_TO_STORE_MESSAGE_LENGTH, xBytesAvailable );
+ xReturn = ( size_t ) xTempReturn;
+ pxStreamBuffer->xTail = xOriginalTail;
+ }
+ 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, xBytesToStoreMessageLength );
+
+ /* 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 xBytesToStoreMessageLength )
+{
+size_t xOriginalTail, xReceivedLength, xNextMessageLength;
+configMESSAGE_BUFFER_LENGTH_TYPE xTempNextMessageLength;
+
+ if( xBytesToStoreMessageLength != ( size_t ) 0 )
+ {
+ /* A discrete message is being received. First receive the length
+ of the message. A copy of the tail is stored so the buffer can be
+ returned to its prior state if the length of the message is too
+ large for the provided buffer. */
+ xOriginalTail = pxStreamBuffer->xTail;
+ ( void ) prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) &xTempNextMessageLength, xBytesToStoreMessageLength, xBytesAvailable );
+ xNextMessageLength = ( size_t ) xTempNextMessageLength;
+
+ /* Reduce the number of bytes available by the number of bytes just
+ read out. */
+ xBytesAvailable -= xBytesToStoreMessageLength;
+
+ /* 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
+ so return the buffer to its previous state (so the length of
+ the message is in the buffer again). */
+ pxStreamBuffer->xTail = xOriginalTail;
+ 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;
+ }
+
+ /* Read the actual data. */
+ xReceivedLength = prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) pvRxData, xNextMessageLength, xBytesAvailable ); /*lint !e9079 Data storage area is implemented as uint8_t array for ease of sizing, indexing and alignment. */
+
+ return xReceivedLength;
+}
+/*-----------------------------------------------------------*/
+
+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 xNextHead, xFirstLength;
+
+ configASSERT( xCount > ( size_t ) 0 );
+
+ xNextHead = pxStreamBuffer->xHead;
+
+ /* 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 - xNextHead, xCount );
+
+ /* Write as many bytes as can be written in the first write. */
+ configASSERT( ( xNextHead + xFirstLength ) <= pxStreamBuffer->xLength );
+ ( void ) memcpy( ( void* ) ( &( pxStreamBuffer->pucBuffer[ xNextHead ] ) ), ( 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();
+ }
+
+ xNextHead += xCount;
+ if( xNextHead >= pxStreamBuffer->xLength )
+ {
+ xNextHead -= pxStreamBuffer->xLength;
+ }
+ else
+ {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ pxStreamBuffer->xHead = xNextHead;
+
+ return xCount;
+}
+/*-----------------------------------------------------------*/
+
+static size_t prvReadBytesFromBuffer( StreamBuffer_t *pxStreamBuffer, uint8_t *pucData, size_t xMaxCount, size_t xBytesAvailable )
+{
+size_t xCount, xFirstLength, xNextTail;
+
+ /* Use the minimum of the wanted bytes and the available bytes. */
+ xCount = configMIN( xBytesAvailable, xMaxCount );
+
+ if( xCount > ( size_t ) 0 )
+ {
+ xNextTail = pxStreamBuffer->xTail;
+
+ /* 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 - xNextTail, xCount );
+
+ /* Obtain the number of bytes it is possible to obtain in the first
+ read. Asserts check bounds of read and write. */
+ configASSERT( xFirstLength <= xMaxCount );
+ configASSERT( ( xNextTail + xFirstLength ) <= pxStreamBuffer->xLength );
+ ( void ) memcpy( ( void * ) pucData, ( const void * ) &( pxStreamBuffer->pucBuffer[ xNextTail ] ), 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. */
+ configASSERT( xCount <= xMaxCount );
+ ( 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. */
+ xNextTail += xCount;
+
+ if( xNextTail >= pxStreamBuffer->xLength )
+ {
+ xNextTail -= pxStreamBuffer->xLength;
+ }
+
+ pxStreamBuffer->xTail = xNextTail;
+ }
+ else
+ {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ return xCount;
+}
+/*-----------------------------------------------------------*/
+
+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/fw/Middlewares/Third_Party/FreeRTOS/Source/tasks.c b/fw/Middlewares/Third_Party/FreeRTOS/Source/tasks.c
new file mode 100644
index 0000000..f6a6a9b
--- /dev/null
+++ b/fw/Middlewares/Third_Party/FreeRTOS/Source/tasks.c
@@ -0,0 +1,5310 @@
+/*
+ * FreeRTOS Kernel V10.3.1
+ * 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
+#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 )
+#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 recored 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 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 ); \
+ vListInsertEnd( &( pxReadyTasksLists[ ( pxTCB )->uxPriority ] ), &( ( pxTCB )->xStateListItem ) ); \
+ tracePOST_MOVED_TASK_TO_READY_STATE( pxTCB )
+/*-----------------------------------------------------------*/
+
+/*
+ * Several functions take an 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 )
+ uint32_t 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;
+ volatile uint8_t ucNotifyState;
+ #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 move to function scople 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. */
+
+/* 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 uint32_t ulTaskSwitchedInTime = 0UL; /*< Holds the value of a timer/counter the last time a task was switched in. */
+ PRIVILEGED_DATA static uint32_t ulTotalRunTime = 0UL; /*< Holds the total amount of execution time as defined by the run time counter clock. */
+
+#endif
+
+/*lint -restore */
+
+/*-----------------------------------------------------------*/
+
+/* Callback function prototypes. --------------------------*/
+#if( configCHECK_FOR_STACK_OVERFLOW > 0 )
+
+ extern void vApplicationStackOverflowHook( TaskHandle_t xTask, char *pcTaskName );
+
+#endif
+
+#if( configUSE_TICK_HOOK > 0 )
+
+ extern void vApplicationTickHook( void ); /*lint !e526 Symbol not defined as it is an application callback. */
+
+#endif
+
+#if( configSUPPORT_STATIC_ALLOCATION == 1 )
+
+ extern void vApplicationGetIdleTaskMemory( StaticTask_t **ppxIdleTaskTCBBuffer, StackType_t **ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize ); /*lint !e526 Symbol not defined as it is an application callback. */
+
+#endif
+
+/* 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 );
+
+/*
+ * 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 );
+
+#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 * ) pvPortMalloc( ( ( ( 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 = pvPortMalloc( ( ( ( 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. */
+ vPortFree( 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. First
+ remove the privilege bit if one is present. */
+ 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 = 0UL;
+ }
+ #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 )
+ {
+ for( x = 0; x < ( UBaseType_t ) configNUM_THREAD_LOCAL_STORAGE_POINTERS; x++ )
+ {
+ pxNewTCB->pvThreadLocalStoragePointers[ x ] = NULL;
+ }
+ }
+ #endif
+
+ #if ( configUSE_TASK_NOTIFICATIONS == 1 )
+ {
+ pxNewTCB->ulNotifiedValue = 0;
+ pxNewTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION;
+ }
+ #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 );
+ prvDeleteTCB( pxTCB );
+
+ /* Reset the next expected unblock time in case it referred to
+ the task that has just been deleted. */
+ prvResetNextTaskUnblockTime();
+ }
+ }
+ taskEXIT_CRITICAL();
+
+ /* 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_vTaskDelayUntil == 1 )
+
+ void vTaskDelayUntil( 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();
+ }
+ }
+
+#endif /* INCLUDE_vTaskDelayUntil */
+/*-----------------------------------------------------------*/
+
+#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 )
+ {
+ /* 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( pxTCB->ucNotifyState == taskWAITING_NOTIFICATION )
+ {
+ eReturn = eBlocked;
+ }
+ else
+ {
+ eReturn = eSuspended;
+ }
+ }
+ #else
+ {
+ eReturn = eSuspended;
+ }
+ #endif
+ }
+ else
+ {
+ eReturn = eBlocked;
+ }
+ }
+ #endif
+
+ #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
+ {
+ pxTCB->uxPriority = uxNewPriority;
+ }
+ #endif
+
+ /* 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 it's 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 )
+ {
+ if( pxTCB->ucNotifyState == taskWAITING_NOTIFICATION )
+ {
+ /* The task was blocked to wait for a notification, but is
+ now suspended, so no notification was received. */
+ pxTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION;
+ }
+ }
+ #endif
+ }
+ 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;
+ }
+ 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
+ {
+ /* 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;
+}
+/*-----------------------------------------------------------*/
+
+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! -
+ http://goo.gl/wu4acr */
+
+ /* portSOFRWARE_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( 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. */
+ ( void ) uxListRemove( &( pxTCB->xEventListItem ) );
+ ( void ) uxListRemove( &( pxTCB->xStateListItem ) );
+ prvAddTaskToReadyList( pxTCB );
+
+ /* If the moved task has a priority higher than 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, uint32_t * 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( pulTotalRunTime != NULL )
+ {
+ *pulTotalRunTime = 0;
+ }
+ }
+ #endif
+ }
+ 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 xYieldRequired = pdFALSE;
+
+ /* 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;
+ xYieldRequired = xTaskResumeAll();
+
+ return xYieldRequired;
+}
+/*----------------------------------------------------------*/
+
+#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
+ equal to or 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 deedmed easier to understand with multiple breaks. */
+ }
+ else
+ {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ /* It is time to remove the item from the Blocked state. */
+ ( void ) uxListRemove( &( 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 )
+ {
+ ( void ) uxListRemove( &( 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. 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). */
+ vListInsertEnd( 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. */
+ vListInsertEnd( 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 );
+ ( void ) uxListRemove( &( pxUnblockedTCB->xEventListItem ) );
+
+ if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
+ {
+ ( void ) uxListRemove( &( 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. */
+ vListInsertEnd( &( 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 );
+ ( void ) uxListRemove( 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. */
+ ( void ) uxListRemove( &( 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;
+ }
+ 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 = 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 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 = 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. */
+ vPortFree( 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. */
+ vPortFree( 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 )
+{
+TCB_t *pxTCB;
+
+ 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. */
+ ( 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. */
+ xNextTaskUnblockTime = listGET_LIST_ITEM_VALUE( &( ( pxTCB )->xStateListItem ) );
+ }
+}
+/*-----------------------------------------------------------*/
+
+#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/delayed list. */
+ if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 )
+ {
+ taskRESET_READY_PRIORITY( pxTCB->uxPriority );
+ }
+ 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, pxTCB->uxBasePriority );
+ 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 and stack usage.
+ *
+ * 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;
+ uint32_t 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.
+ ulTotalRunTimeDiv100 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 ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait )
+ {
+ uint32_t ulReturn;
+
+ taskENTER_CRITICAL();
+ {
+ /* Only block if the notification count is not already non-zero. */
+ if( pxCurrentTCB->ulNotifiedValue == 0UL )
+ {
+ /* Mark this task as waiting for a notification. */
+ pxCurrentTCB->ucNotifyState = taskWAITING_NOTIFICATION;
+
+ if( xTicksToWait > ( TickType_t ) 0 )
+ {
+ prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE );
+ traceTASK_NOTIFY_TAKE_BLOCK();
+
+ /* 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();
+ ulReturn = pxCurrentTCB->ulNotifiedValue;
+
+ if( ulReturn != 0UL )
+ {
+ if( xClearCountOnExit != pdFALSE )
+ {
+ pxCurrentTCB->ulNotifiedValue = 0UL;
+ }
+ else
+ {
+ pxCurrentTCB->ulNotifiedValue = ulReturn - ( uint32_t ) 1;
+ }
+ }
+ else
+ {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ pxCurrentTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION;
+ }
+ taskEXIT_CRITICAL();
+
+ return ulReturn;
+ }
+
+#endif /* configUSE_TASK_NOTIFICATIONS */
+/*-----------------------------------------------------------*/
+
+#if( configUSE_TASK_NOTIFICATIONS == 1 )
+
+ BaseType_t xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait )
+ {
+ BaseType_t xReturn;
+
+ taskENTER_CRITICAL();
+ {
+ /* Only block if a notification is not already pending. */
+ if( pxCurrentTCB->ucNotifyState != 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 &= ~ulBitsToClearOnEntry;
+
+ /* Mark this task as waiting for a notification. */
+ pxCurrentTCB->ucNotifyState = taskWAITING_NOTIFICATION;
+
+ if( xTicksToWait > ( TickType_t ) 0 )
+ {
+ prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE );
+ traceTASK_NOTIFY_WAIT_BLOCK();
+
+ /* 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();
+
+ if( pulNotificationValue != NULL )
+ {
+ /* Output the current notification value, which may or may not
+ have changed. */
+ *pulNotificationValue = pxCurrentTCB->ulNotifiedValue;
+ }
+
+ /* 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 != 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 &= ~ulBitsToClearOnExit;
+ xReturn = pdTRUE;
+ }
+
+ pxCurrentTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION;
+ }
+ taskEXIT_CRITICAL();
+
+ return xReturn;
+ }
+
+#endif /* configUSE_TASK_NOTIFICATIONS */
+/*-----------------------------------------------------------*/
+
+#if( configUSE_TASK_NOTIFICATIONS == 1 )
+
+ BaseType_t xTaskGenericNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue )
+ {
+ TCB_t * pxTCB;
+ BaseType_t xReturn = pdPASS;
+ uint8_t ucOriginalNotifyState;
+
+ configASSERT( xTaskToNotify );
+ pxTCB = xTaskToNotify;
+
+ taskENTER_CRITICAL();
+ {
+ if( pulPreviousNotificationValue != NULL )
+ {
+ *pulPreviousNotificationValue = pxTCB->ulNotifiedValue;
+ }
+
+ ucOriginalNotifyState = pxTCB->ucNotifyState;
+
+ pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED;
+
+ switch( eAction )
+ {
+ case eSetBits :
+ pxTCB->ulNotifiedValue |= ulValue;
+ break;
+
+ case eIncrement :
+ ( pxTCB->ulNotifiedValue )++;
+ break;
+
+ case eSetValueWithOverwrite :
+ pxTCB->ulNotifiedValue = ulValue;
+ break;
+
+ case eSetValueWithoutOverwrite :
+ if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED )
+ {
+ pxTCB->ulNotifiedValue = 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( pxTCB->ulNotifiedValue == ~0UL );
+
+ break;
+ }
+
+ traceTASK_NOTIFY();
+
+ /* If the task is in the blocked state specifically to wait for a
+ notification then unblock it now. */
+ if( ucOriginalNotifyState == taskWAITING_NOTIFICATION )
+ {
+ ( void ) uxListRemove( &( 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, 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 );
+
+ /* 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:
+ http://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;
+ }
+
+ ucOriginalNotifyState = pxTCB->ucNotifyState;
+ pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED;
+
+ switch( eAction )
+ {
+ case eSetBits :
+ pxTCB->ulNotifiedValue |= ulValue;
+ break;
+
+ case eIncrement :
+ ( pxTCB->ulNotifiedValue )++;
+ break;
+
+ case eSetValueWithOverwrite :
+ pxTCB->ulNotifiedValue = ulValue;
+ break;
+
+ case eSetValueWithoutOverwrite :
+ if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED )
+ {
+ pxTCB->ulNotifiedValue = 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( pxTCB->ulNotifiedValue == ~0UL );
+ break;
+ }
+
+ traceTASK_NOTIFY_FROM_ISR();
+
+ /* 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 )
+ {
+ ( void ) uxListRemove( &( pxTCB->xStateListItem ) );
+ prvAddTaskToReadyList( pxTCB );
+ }
+ else
+ {
+ /* The delayed and ready lists cannot be accessed, so hold
+ this task pending until the scheduler is resumed. */
+ vListInsertEnd( &( 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 vTaskNotifyGiveFromISR( TaskHandle_t xTaskToNotify, BaseType_t *pxHigherPriorityTaskWoken )
+ {
+ TCB_t * pxTCB;
+ uint8_t ucOriginalNotifyState;
+ UBaseType_t uxSavedInterruptStatus;
+
+ configASSERT( xTaskToNotify );
+
+ /* 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:
+ http://www.freertos.org/RTOS-Cortex-M3-M4.html */
+ portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
+
+ pxTCB = xTaskToNotify;
+
+ uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
+ {
+ ucOriginalNotifyState = pxTCB->ucNotifyState;
+ pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED;
+
+ /* 'Giving' is equivalent to incrementing a count in a counting
+ semaphore. */
+ ( pxTCB->ulNotifiedValue )++;
+
+ traceTASK_NOTIFY_GIVE_FROM_ISR();
+
+ /* 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 )
+ {
+ ( void ) uxListRemove( &( pxTCB->xStateListItem ) );
+ prvAddTaskToReadyList( pxTCB );
+ }
+ else
+ {
+ /* The delayed and ready lists cannot be accessed, so hold
+ this task pending until the scheduler is resumed. */
+ vListInsertEnd( &( 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 xTaskNotifyStateClear( TaskHandle_t xTask )
+ {
+ TCB_t *pxTCB;
+ BaseType_t xReturn;
+
+ /* 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 == taskNOTIFICATION_RECEIVED )
+ {
+ pxTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION;
+ xReturn = pdPASS;
+ }
+ else
+ {
+ xReturn = pdFAIL;
+ }
+ }
+ taskEXIT_CRITICAL();
+
+ return xReturn;
+ }
+
+#endif /* configUSE_TASK_NOTIFICATIONS */
+/*-----------------------------------------------------------*/
+
+#if( configUSE_TASK_NOTIFICATIONS == 1 )
+
+ uint32_t ulTaskNotifyValueClear( TaskHandle_t xTask, 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 = pxCurrentTCB->ulNotifiedValue;
+ pxTCB->ulNotifiedValue &= ~ulBitsToClear;
+ }
+ taskEXIT_CRITICAL();
+
+ return ulReturn;
+ }
+
+#endif /* configUSE_TASK_NOTIFICATIONS */
+/*-----------------------------------------------------------*/
+
+#if( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) )
+
+ uint32_t ulTaskGetIdleRunTimeCounter( void )
+ {
+ return xIdleTaskHandle->ulRunTimeCounter;
+ }
+
+#endif
+/*-----------------------------------------------------------*/
+
+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. */
+ vListInsertEnd( &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
+
+
diff --git a/fw/Middlewares/Third_Party/FreeRTOS/Source/timers.c b/fw/Middlewares/Third_Party/FreeRTOS/Source/timers.c
new file mode 100644
index 0000000..00200b8
--- /dev/null
+++ b/fw/Middlewares/Third_Party/FreeRTOS/Source/timers.c
@@ -0,0 +1,1127 @@
+/*
+ * FreeRTOS Kernel V10.3.1
+ * 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
+
+/* 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
+
+/* 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 */
+
+/*-----------------------------------------------------------*/
+
+#if( configSUPPORT_STATIC_ALLOCATION == 1 )
+
+ /* If static allocation is supported then the application must provide the
+ following callback function - which enables the application to optionally
+ provide the memory that will be used by the timer task as the task's stack
+ and TCB. */
+ extern void vApplicationGetTimerTaskMemory( StaticTask_t **ppxTimerTaskTCBBuffer, StackType_t **ppxTimerTaskStackBuffer, uint32_t *pulTimerTaskStackSize );
+
+#endif
+
+/*
+ * 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;
+
+/*
+ * 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
+ {
+ 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 ) );
+
+ if( pxNewTimer != NULL )
+ {
+ /* 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 &= ~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 prvProcessExpiredTimer( const TickType_t xNextExpireTime, const TickType_t xTimeNow )
+{
+BaseType_t xResult;
+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 ) );
+ traceTIMER_EXPIRED( pxTimer );
+
+ /* 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 )
+ {
+ /* The timer is inserted into a list using a time relative to anything
+ other than the current time. It will therefore be inserted into the
+ correct list relative to the time this task thinks it is now. */
+ if( prvInsertTimerInActiveList( pxTimer, ( xNextExpireTime + pxTimer->xTimerPeriodInTicks ), xTimeNow, xNextExpireTime ) != pdFALSE )
+ {
+ /* The timer expired before it was added to the active timer
+ list. Reload it now. */
+ xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY );
+ configASSERT( xResult );
+ ( void ) xResult;
+ }
+ else
+ {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ else
+ {
+ pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE;
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ /* Call the timer callback. */
+ 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, xResult;
+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 :
+ case tmrCOMMAND_START_DONT_TRACE :
+ /* 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. */
+ pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer );
+ traceTIMER_EXPIRED( pxTimer );
+
+ if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0 )
+ {
+ xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, NULL, tmrNO_DELAY );
+ configASSERT( xResult );
+ ( void ) xResult;
+ }
+ else
+ {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ 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 &= ~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 &= ~tmrSTATUS_IS_ACTIVE;
+ }
+ }
+ #else
+ {
+ /* 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 &= ~tmrSTATUS_IS_ACTIVE;
+ }
+ #endif /* configSUPPORT_DYNAMIC_ALLOCATION */
+ break;
+
+ default :
+ /* Don't expect to get here. */
+ break;
+ }
+ }
+ }
+}
+/*-----------------------------------------------------------*/
+
+static void prvSwitchTimerLists( void )
+{
+TickType_t xNextExpireTime, xReloadTime;
+List_t *pxTemp;
+Timer_t *pxTimer;
+BaseType_t xResult;
+
+ /* 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 );
+
+ /* Remove the timer from the list. */
+ 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. */
+ ( void ) uxListRemove( &( pxTimer->xTimerListItem ) );
+ traceTIMER_EXPIRED( pxTimer );
+
+ /* Execute its callback, then send a command to restart the timer if
+ it is an auto-reload timer. It cannot be restarted here as the lists
+ have not yet been switched. */
+ pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer );
+
+ if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0 )
+ {
+ /* Calculate the reload value, and if the reload value results in
+ the timer going into the same timer list then it has already expired
+ and the timer should be re-inserted into the current list so it is
+ processed again within this loop. Otherwise a command should be sent
+ to restart the timer to ensure it is only inserted into a list after
+ the lists have been swapped. */
+ xReloadTime = ( xNextExpireTime + pxTimer->xTimerPeriodInTicks );
+ if( xReloadTime > xNextExpireTime )
+ {
+ listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xReloadTime );
+ listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer );
+ vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) );
+ }
+ else
+ {
+ xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY );
+ configASSERT( xResult );
+ ( void ) xResult;
+ }
+ }
+ else
+ {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+
+ 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. */
+ static StaticQueue_t xStaticTimerQueue; /*lint !e956 Ok to declare in this manner to prevent additional conditional compilation guards in other locations. */
+ 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 ( 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/fw/STM32H750VBTX_FLASH.ld b/fw/STM32H750VBTX_FLASH.ld
new file mode 100644
index 0000000..e09bf9d
--- /dev/null
+++ b/fw/STM32H750VBTX_FLASH.ld
@@ -0,0 +1,187 @@
+/*
+******************************************************************************
+**
+** File : LinkerScript.ld
+**
+** Author : STM32CubeIDE
+**
+** Abstract : Linker script for STM32H7 series
+** 128Kbytes FLASH and 1056Kbytes RAM
+**
+** Set heap size, stack size and stack location according
+** to application requirements.
+**
+** Set memory bank area and size if external memory is used.
+**
+** Target : STMicroelectronics STM32
+**
+** Distribution: The file is distributed as is, without any warranty
+** of any kind.
+**
+*****************************************************************************
+** @attention
+**
+** Copyright (c) 2024 STMicroelectronics.
+** All rights reserved.
+**
+** This software is licensed under terms that can be found in the LICENSE file
+** in the root directory of this software component.
+** If no LICENSE file comes with this software, it is provided AS-IS.
+**
+****************************************************************************
+*/
+
+/* Entry Point */
+ENTRY(Reset_Handler)
+
+/* Highest address of the user mode stack */
+_estack = ORIGIN(RAM_D1) + LENGTH(RAM_D1); /* end of RAM */
+/* Generate a link error if heap and stack don't fit into RAM */
+_Min_Heap_Size = 0x200; /* required amount of heap */
+_Min_Stack_Size = 0x400; /* required amount of stack */
+
+/* Specify the memory areas */
+MEMORY
+{
+ FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 128K
+ DTCMRAM (xrw) : ORIGIN = 0x20000000, LENGTH = 128K
+ RAM_D1 (xrw) : ORIGIN = 0x24000000, LENGTH = 512K
+ RAM_D2 (xrw) : ORIGIN = 0x30000000, LENGTH = 288K
+ RAM_D3 (xrw) : ORIGIN = 0x38000000, LENGTH = 64K
+ ITCMRAM (xrw) : ORIGIN = 0x00000000, LENGTH = 64K
+}
+
+/* Define output sections */
+SECTIONS
+{
+ /* The startup code goes first into FLASH */
+ .isr_vector :
+ {
+ . = ALIGN(4);
+ KEEP(*(.isr_vector)) /* Startup code */
+ . = ALIGN(4);
+ } >FLASH
+
+ /* The program code and other data goes into FLASH */
+ .text :
+ {
+ . = ALIGN(4);
+ *(.text) /* .text sections (code) */
+ *(.text*) /* .text* sections (code) */
+ *(.glue_7) /* glue arm to thumb code */
+ *(.glue_7t) /* glue thumb to arm code */
+ *(.eh_frame)
+
+ KEEP (*(.init))
+ KEEP (*(.fini))
+
+ . = ALIGN(4);
+ _etext = .; /* define a global symbols at end of code */
+ } >FLASH
+
+ /* Constant data goes into FLASH */
+ .rodata :
+ {
+ . = ALIGN(4);
+ *(.rodata) /* .rodata sections (constants, strings, etc.) */
+ *(.rodata*) /* .rodata* sections (constants, strings, etc.) */
+ . = ALIGN(4);
+ } >FLASH
+
+ .ARM.extab (READONLY) : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */
+ {
+ *(.ARM.extab* .gnu.linkonce.armextab.*)
+ } >FLASH
+ .ARM (READONLY) : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */
+ {
+ __exidx_start = .;
+ *(.ARM.exidx*)
+ __exidx_end = .;
+ } >FLASH
+
+ .preinit_array (READONLY) : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */
+ {
+ PROVIDE_HIDDEN (__preinit_array_start = .);
+ KEEP (*(.preinit_array*))
+ PROVIDE_HIDDEN (__preinit_array_end = .);
+ } >FLASH
+
+ .init_array (READONLY) : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */
+ {
+ PROVIDE_HIDDEN (__init_array_start = .);
+ KEEP (*(SORT(.init_array.*)))
+ KEEP (*(.init_array*))
+ PROVIDE_HIDDEN (__init_array_end = .);
+ } >FLASH
+
+ .fini_array (READONLY) : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */
+ {
+ PROVIDE_HIDDEN (__fini_array_start = .);
+ KEEP (*(SORT(.fini_array.*)))
+ KEEP (*(.fini_array*))
+ PROVIDE_HIDDEN (__fini_array_end = .);
+ } >FLASH
+
+ /* used by the startup to initialize data */
+ _sidata = LOADADDR(.data);
+
+ /* Initialized data sections goes into RAM, load LMA copy after code */
+ .data :
+ {
+ . = ALIGN(4);
+ _sdata = .; /* create a global symbol at data start */
+ *(.data) /* .data sections */
+ *(.data*) /* .data* sections */
+ *(.RamFunc) /* .RamFunc sections */
+ *(.RamFunc*) /* .RamFunc* sections */
+
+ . = ALIGN(4);
+ _edata = .; /* define a global symbol at data end */
+ } >RAM_D1 AT> FLASH
+
+ /* Uninitialized data section */
+ . = ALIGN(4);
+ .bss :
+ {
+ /* This is used by the startup in order to initialize the .bss section */
+ _sbss = .; /* define a global symbol at bss start */
+ __bss_start__ = _sbss;
+ *(.bss)
+ *(.bss*)
+ *(COMMON)
+
+ . = ALIGN(4);
+ _ebss = .; /* define a global symbol at bss end */
+ __bss_end__ = _ebss;
+ } >RAM_D1
+
+ /* User_heap_stack section, used to check that there is enough RAM left */
+ ._user_heap_stack :
+ {
+ . = ALIGN(8);
+ PROVIDE ( end = . );
+ PROVIDE ( _end = . );
+ . = . + _Min_Heap_Size;
+ . = . + _Min_Stack_Size;
+ . = ALIGN(8);
+ } >RAM_D1
+
+ /*.ucheap_section :
+ {
+ . = ALIGN(4);
+ KEEP(*(.mysection));
+ . = ALIGN(4);
+ } >RAM_D2*/
+
+ /* Remove information from the standard libraries */
+ /DISCARD/ :
+ {
+ libc.a ( * )
+ libm.a ( * )
+ libgcc.a ( * )
+ }
+
+ .ARM.attributes 0 : { *(.ARM.attributes) }
+}
+
+
diff --git a/fw/STM32H750VBTX_RAM.ld b/fw/STM32H750VBTX_RAM.ld
new file mode 100644
index 0000000..7cd3677
--- /dev/null
+++ b/fw/STM32H750VBTX_RAM.ld
@@ -0,0 +1,177 @@
+/*
+******************************************************************************
+**
+** File : LinkerScript.ld (debug in RAM dedicated)
+**
+** Author : STM32CubeIDE
+**
+** Abstract : Linker script for STM32H7 series
+** 1024Kbytes RAM_EXEC and 544Kbytes RAM
+**
+** Set heap size, stack size and stack location according
+** to application requirements.
+**
+** Set memory bank area and size if external memory is used.
+**
+** Target : STMicroelectronics STM32
+**
+** Distribution: The file is distributed as is, without any warranty
+** of any kind.
+**
+*****************************************************************************
+** @attention
+**
+** Copyright (c) 2024 STMicroelectronics.
+** All rights reserved.
+**
+** This software is licensed under terms that can be found in the LICENSE file
+** in the root directory of this software component.
+** If no LICENSE file comes with this software, it is provided AS-IS.
+**
+****************************************************************************
+*/
+
+/* Entry Point */
+ENTRY(Reset_Handler)
+
+/* Highest address of the user mode stack */
+_estack = ORIGIN(DTCMRAM) + LENGTH(DTCMRAM); /* end of RAM */
+/* Generate a link error if heap and stack don't fit into RAM */
+_Min_Heap_Size = 0x200; /* required amount of heap */
+_Min_Stack_Size = 0x400; /* required amount of stack */
+
+/* Specify the memory areas */
+MEMORY
+{
+ RAM_EXEC (xrw) : ORIGIN = 0x24000000, LENGTH = 1024K
+ DTCMRAM (xrw) : ORIGIN = 0x20000000, LENGTH = 128K
+ RAM_D2 (xrw) : ORIGIN = 0x30000000, LENGTH = 288K
+ RAM_D3 (xrw) : ORIGIN = 0x38000000, LENGTH = 64K
+ ITCMRAM (xrw) : ORIGIN = 0x00000000, LENGTH = 64K
+}
+
+/* Define output sections */
+SECTIONS
+{
+ /* The startup code goes first into RAM_EXEC */
+ .isr_vector :
+ {
+ . = ALIGN(4);
+ KEEP(*(.isr_vector)) /* Startup code */
+ . = ALIGN(4);
+ } >RAM_EXEC
+
+ /* The program code and other data goes into RAM_EXEC */
+ .text :
+ {
+ . = ALIGN(4);
+ *(.text) /* .text sections (code) */
+ *(.text*) /* .text* sections (code) */
+ *(.glue_7) /* glue arm to thumb code */
+ *(.glue_7t) /* glue thumb to arm code */
+ *(.eh_frame)
+ *(.RamFunc) /* .RamFunc sections */
+ *(.RamFunc*) /* .RamFunc* sections */
+
+ KEEP (*(.init))
+ KEEP (*(.fini))
+
+ . = ALIGN(4);
+ _etext = .; /* define a global symbols at end of code */
+ } >RAM_EXEC
+
+ /* Constant data goes into RAM_EXEC */
+ .rodata :
+ {
+ . = ALIGN(4);
+ *(.rodata) /* .rodata sections (constants, strings, etc.) */
+ *(.rodata*) /* .rodata* sections (constants, strings, etc.) */
+ . = ALIGN(4);
+ } >RAM_EXEC
+
+ .ARM.extab (READONLY) : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */
+ {
+ *(.ARM.extab* .gnu.linkonce.armextab.*)
+ } >RAM_EXEC
+ .ARM (READONLY) : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */
+ {
+ __exidx_start = .;
+ *(.ARM.exidx*)
+ __exidx_end = .;
+ } >RAM_EXEC
+
+ .preinit_array (READONLY) : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */
+ {
+ PROVIDE_HIDDEN (__preinit_array_start = .);
+ KEEP (*(.preinit_array*))
+ PROVIDE_HIDDEN (__preinit_array_end = .);
+ } >RAM_EXEC
+
+ .init_array (READONLY) : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */
+ {
+ PROVIDE_HIDDEN (__init_array_start = .);
+ KEEP (*(SORT(.init_array.*)))
+ KEEP (*(.init_array*))
+ PROVIDE_HIDDEN (__init_array_end = .);
+ } >RAM_EXEC
+
+ .fini_array (READONLY) : /* The READONLY keyword is only supported in GCC11 and later, remove it if using GCC10 or earlier. */
+ {
+ PROVIDE_HIDDEN (__fini_array_start = .);
+ KEEP (*(SORT(.fini_array.*)))
+ KEEP (*(.fini_array*))
+ PROVIDE_HIDDEN (__fini_array_end = .);
+ } >RAM_EXEC
+
+ /* used by the startup to initialize data */
+ _sidata = LOADADDR(.data);
+
+ /* Initialized data sections goes into RAM, load LMA copy after code */
+ .data :
+ {
+ . = ALIGN(4);
+ _sdata = .; /* create a global symbol at data start */
+ *(.data) /* .data sections */
+ *(.data*) /* .data* sections */
+
+ . = ALIGN(4);
+ _edata = .; /* define a global symbol at data end */
+ } >DTCMRAM AT> RAM_EXEC
+
+ /* Uninitialized data section */
+ . = ALIGN(4);
+ .bss :
+ {
+ /* This is used by the startup in order to initialize the .bss section */
+ _sbss = .; /* define a global symbol at bss start */
+ __bss_start__ = _sbss;
+ *(.bss)
+ *(.bss*)
+ *(COMMON)
+
+ . = ALIGN(4);
+ _ebss = .; /* define a global symbol at bss end */
+ __bss_end__ = _ebss;
+ } >DTCMRAM
+
+ /* User_heap_stack section, used to check that there is enough RAM left */
+ ._user_heap_stack :
+ {
+ . = ALIGN(8);
+ PROVIDE ( end = . );
+ PROVIDE ( _end = . );
+ . = . + _Min_Heap_Size;
+ . = . + _Min_Stack_Size;
+ . = ALIGN(8);
+ } >DTCMRAM
+
+ /* Remove information from the standard libraries */
+ /DISCARD/ :
+ {
+ libc.a ( * )
+ libm.a ( * )
+ libgcc.a ( * )
+ }
+
+ .ARM.attributes 0 : { *(.ARM.attributes) }
+}
diff --git a/fw/adv7611.c b/fw/User/adv7611.c
similarity index 52%
rename from fw/adv7611.c
rename to fw/User/adv7611.c
index 5912a0e..4460380 100644
--- a/fw/adv7611.c
+++ b/fw/User/adv7611.c
@@ -1,5 +1,6 @@
//
-// Copyright 2024 Wenting Zhang
+// Grimoire
+// Copyright 2025 Wenting Zhang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -19,30 +20,9 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
-#include
-#include "pico/stdlib.h"
-#include "hardware/i2c.h"
-#include "config.h"
-#include "adv7611.h"
-#include "edid.h"
-
-#ifdef INPUT_ADV7611
-
-#define ADV7611_INT_PIN (1)
-#define ADV7611_RST_PIN (25)
-
-#define ADV7611_I2C (i2c1)
-
-#define ADV7611_I2C_ADDR (0x4C)
-
-// Sub addresses, make sure they don't conflict with anything else!
-#define CEC_I2C_ADDR (0x40) // Default 0x80(0x40)
-#define INFOFRAME_I2C_ADDR (0x3E) // Default 0x7C(0x3E)
-#define DPLL_I2C_ADDR (0x26) // Default 0x26(0x4C)
-#define KSV_I2C_ADDR (0x32) // Default 0x32(0x64)
-#define EDID_I2C_ADDR (0x36) // Default 0x36(0x6C)
-#define HDMI_I2C_ADDR (0x34) // Default 0x34(0x68)
-#define CP_I2C_ADDR (0x23) // Default 0x22(0x44)
+#include "platform.h"
+#include "board.h"
+#include "app.h"
static const uint8_t adv7611_init_0[] = {
ADV7611_I2C_ADDR, 0xf4, (CEC_I2C_ADDR << 1),
@@ -64,55 +44,54 @@ static const uint8_t adv7611_init_1[] = {
ADV7611_I2C_ADDR, 0xfd, (CP_I2C_ADDR << 1),
ADV7611_I2C_ADDR, 0x01, 0x06, // Prim_mode = 110b HDMI-GR
- ADV7611_I2C_ADDR, 0x00, 0x17, // VID-STD: UXGA-R
- ADV7611_I2C_ADDR, 0x02, 0xf8, // F8 = YUV, F2 = RGB
+ ADV7611_I2C_ADDR, 0x00, 0x16, // VID-STD: UXGA (for default clock)
+ ADV7611_I2C_ADDR, 0x02, 0xf2, // F8 = YUV, F2 = RGB
ADV7611_I2C_ADDR, 0x03, 0x40, // 40 = 24bit 444 SDR
- ADV7611_I2C_ADDR, 0x04, 0x42, // P[23:16] V/R, P[15:8] Y/G, P[7:0] U/CrCb/B CLK=28.63636MHz
+ ADV7611_I2C_ADDR, 0x04, 0x46, // P[23:16] V/R, P[15:8] Y/G, P[7:0] U/CrCb/B CLK=24MHz
ADV7611_I2C_ADDR, 0x05, 0x28, // Do not insert AV codes
ADV7611_I2C_ADDR, 0x06, 0xa6, // VS OUT SEL, F/VS/HS/LLC POL
ADV7611_I2C_ADDR, 0x0b, 0x44,
ADV7611_I2C_ADDR, 0x0C, 0x42,
ADV7611_I2C_ADDR, 0x15, 0x80,
- ADV7611_I2C_ADDR, 0x19, 0x8a,
+ ADV7611_I2C_ADDR, 0x19, 0x8a, // Enable LLC DLL
ADV7611_I2C_ADDR, 0x33, 0x40,
ADV7611_I2C_ADDR, 0x14, 0x7f,
- CP_I2C_ADDR, 0xba, 0x01,
- //CP_I2C_ADDR, 0x7c, 0x01,
+ CP_I2C_ADDR, 0xba, 0x00, // Disable free run
+ //HDMI_I2C_ADDR, 0xbf, 0x01, // Bypass CP
+ CP_I2C_ADDR, 0x6c, 0x00, // ADI required setting
KSV_I2C_ADDR, 0x40, 0x81, // DSP_Ctrl4 :00/01 : YUV or RGB; 10 : RAW8; 11 : RAW10
- HDMI_I2C_ADDR, 0x9b, 0x03, // ADI recommanded setting
- HDMI_I2C_ADDR, 0xc1, 0x01, // ADI recommanded setting
- HDMI_I2C_ADDR, 0xc2, 0x01, // ADI recommanded setting
- HDMI_I2C_ADDR, 0xc3, 0x01, // ADI recommanded setting
- HDMI_I2C_ADDR, 0xc4, 0x01, // ADI recommanded setting
- HDMI_I2C_ADDR, 0xc5, 0x01, // ADI recommanded setting
- HDMI_I2C_ADDR, 0xc6, 0x01, // ADI recommanded setting
- HDMI_I2C_ADDR, 0xc7, 0x01, // ADI recommanded setting
- HDMI_I2C_ADDR, 0xc8, 0x01, // ADI recommanded setting
- HDMI_I2C_ADDR, 0xc9, 0x01, // ADI recommanded setting
- HDMI_I2C_ADDR, 0xca, 0x01, // ADI recommanded setting
- HDMI_I2C_ADDR, 0xcb, 0x01, // ADI recommanded setting
- HDMI_I2C_ADDR, 0xcc, 0x01, // ADI recommanded setting
+ HDMI_I2C_ADDR, 0x9b, 0x03, // ADI required setting
+ HDMI_I2C_ADDR, 0xc1, 0x01, // ADI required setting
+ HDMI_I2C_ADDR, 0xc2, 0x01, // ADI required setting
+ HDMI_I2C_ADDR, 0xc3, 0x01, // ADI required setting
+ HDMI_I2C_ADDR, 0xc4, 0x01, // ADI required setting
+ HDMI_I2C_ADDR, 0xc5, 0x01, // ADI required setting
+ HDMI_I2C_ADDR, 0xc6, 0x01, // ADI required setting
+ HDMI_I2C_ADDR, 0xc7, 0x01, // ADI required setting
+ HDMI_I2C_ADDR, 0xc8, 0x01, // ADI required setting
+ HDMI_I2C_ADDR, 0xc9, 0x01, // ADI required setting
+ HDMI_I2C_ADDR, 0xca, 0x01, // ADI required setting
+ HDMI_I2C_ADDR, 0xcb, 0x01, // ADI required setting
+ HDMI_I2C_ADDR, 0xcc, 0x01, // ADI required setting
HDMI_I2C_ADDR, 0x00, 0x00, // Set HDMI input Port A
- HDMI_I2C_ADDR, 0x83, 0xfe, // terminator for Port A
- HDMI_I2C_ADDR, 0x6f, 0x0c, // ADI recommended setting
- HDMI_I2C_ADDR, 0x85, 0x1f, // ADI recommended setting
- HDMI_I2C_ADDR, 0x87, 0x70, // ADI recommended setting
+ HDMI_I2C_ADDR, 0x83, 0xfe, // Termination for Port A
+ HDMI_I2C_ADDR, 0x6f, 0x08, // ADI required setting
+ HDMI_I2C_ADDR, 0x85, 0x1f, // ADI required setting
+ HDMI_I2C_ADDR, 0x87, 0x70, // ADI required setting
HDMI_I2C_ADDR, 0x8d, 0x04, // LFG
HDMI_I2C_ADDR, 0x8e, 0x1e, // HFG
HDMI_I2C_ADDR, 0x1a, 0x8a, // unmute audio
- HDMI_I2C_ADDR, 0x57, 0xda, // ADI recommended setting
- HDMI_I2C_ADDR, 0x58, 0x01,
+ HDMI_I2C_ADDR, 0x57, 0xda, // ADI required setting
+ HDMI_I2C_ADDR, 0x58, 0x01, // ADI required setting
+ HDMI_I2C_ADDR, 0x03, 0x98, // Set DIS_I2C_ZERO_COMPR 0x03[7]=1
+ HDMI_I2C_ADDR, 0x4c, 0x44, // Set NEW_VS_PARAM 0x44[2]=1
HDMI_I2C_ADDR, 0x75, 0x10,
- HDMI_I2C_ADDR, 0x6c, 0xa3, // enable manual HPA
- ADV7611_I2C_ADDR, 0x20, 0x70, // HPD low
- KSV_I2C_ADDR, 0x74, 0x00, // disable internal EDID
};
static const uint8_t adv7611_init_2[] = {
KSV_I2C_ADDR, 0x74, 0x01, // Enable the Internal EDID for Ports
ADV7611_I2C_ADDR, 0x20, 0xf0, // HPD high
- HDMI_I2C_ADDR, 0x6c, 0xa2, // disable manual HPA
- ADV7611_I2C_ADDR, 0xf4, 0x00
+ HDMI_I2C_ADDR, 0x6c, 0xa2 // disable manual HPA
};
static void adv7611_send_init_seq(const uint8_t *seq, int entries) {
@@ -123,9 +102,9 @@ static void adv7611_send_init_seq(const uint8_t *seq, int entries) {
addr = seq[i*3];
buf[0] = seq[i*3 + 1];
buf[1] = seq[i*3 + 2];
- result = i2c_write_blocking(ADV7611_I2C, addr, buf, 2, false);
- if (result != 2) {
- fatal("Failed writing data to ADV7611\n");
+ result = pal_i2c_write_payload(ADV7611_I2C, addr, buf, 2);
+ if (result != 0) {
+ syslog_printf("Failed writing data to ADV7611\n");
}
}
}
@@ -136,28 +115,30 @@ static void adv7611_load_edid(uint8_t *edid) {
for (int i = 0; i < 128; i++) {
buf[0] = i;
buf[1] = edid[i];
- result = i2c_write_blocking(ADV7611_I2C, EDID_I2C_ADDR, buf, 2, false);
- if (result != 2) {
- fatal("Failed writing data to ADV7611\n");
+ result = pal_i2c_write_payload(ADV7611_I2C, EDID_I2C_ADDR, buf, 2);
+ if (result != 0) {
+ syslog_printf("Failed writing data to ADV7611\n");
}
}
}
+uint8_t adv7611_read_reg(uint8_t addr, uint8_t reg) {
+ uint8_t val;
+ int result = pal_i2c_read_reg(ADV7611_I2C, addr, reg, &val);
+ if (result != 0) {
+ syslog_printf("Failed reading data from ADV7611\n");
+ }
+ return val;
+}
+
void adv7611_early_init() {
// Initialize IO, reset ADV7611 and allocate I2C addresses
// So it won't conflict with other ICs
-
- gpio_init(ADV7611_RST_PIN);
- gpio_set_dir(ADV7611_RST_PIN, GPIO_OUT);
- gpio_init(ADV7611_INT_PIN);
- gpio_set_dir(ADV7611_INT_PIN, GPIO_IN);
-
- gpio_put(ADV7611_RST_PIN, 1);
- sleep_ms(100);
- gpio_put(ADV7611_RST_PIN, 0);
- sleep_ms(100);
- gpio_put(ADV7611_RST_PIN, 1);
- sleep_ms(100);
+ gpio_put(DEC_RST, 1);
+ sleep_ms(10);
+ gpio_put(DEC_RST, 0);
+ sleep_ms(10);
+ gpio_put(DEC_RST, 1);
}
void adv7611_init() {
@@ -165,15 +146,9 @@ void adv7611_init() {
adv7611_send_init_seq(adv7611_init_1, sizeof(adv7611_init_1) / 3);
uint8_t *edid = edid_get_raw();
- adv7611_load_edid(edid + 1);
+ adv7611_load_edid(edid);
adv7611_send_init_seq(adv7611_init_2, sizeof(adv7611_init_2) / 3);
- printf("ADV7611 initialization done\n");
+ syslog_printf("ADV7611 initialization done\n");
}
-
-bool adv7611_is_valid(void) {
- return false; // TODO
-}
-
-#endif
diff --git a/fw/adv7611.h b/fw/User/adv7611.h
similarity index 91%
rename from fw/adv7611.h
rename to fw/User/adv7611.h
index 225f58a..a57b76d 100644
--- a/fw/adv7611.h
+++ b/fw/User/adv7611.h
@@ -1,5 +1,6 @@
//
-// Copyright 2024 Wenting Zhang
+// Grimoire
+// Copyright 2025 Wenting Zhang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -21,8 +22,6 @@
//
#pragma once
-#ifdef INPUT_ADV7611
void adv7611_early_init(void);
void adv7611_init(void);
-bool adv7611_is_valid(void);
-#endif
+uint8_t adv7611_read_reg(uint8_t addr, uint8_t reg);
diff --git a/fw/User/app.h b/fw/User/app.h
new file mode 100644
index 0000000..7e03e10
--- /dev/null
+++ b/fw/User/app.h
@@ -0,0 +1,62 @@
+//
+// Grimoire
+// Copyright 2025 Wenting Zhang
+//
+// 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.
+//
+#pragma once
+
+#include "shell.h"
+#include "syslog.h"
+#include "usbapp.h"
+#include "crc16.h"
+#include "ptn3460.h"
+#include "config.h"
+#include "edid.h"
+#include "fpga.h"
+#include "adv7611.h"
+#include "usb_pd.h"
+#include "usbpd.h"
+#include "spiffs.h"
+#include "spiffs_config.h"
+#include "spiffs_nucleus.h"
+#include "spiflash.h"
+#include "power.h"
+#include "caster.h"
+#include "button.h"
+#include "ui.h"
+
+//#define UNUSED(expr) do { (void)(expr); } while (0)
+
+#define HOUSEKEEPING_TASK_PRIORITY (tskIDLE_PRIORITY + 1)
+#define STARTUP_TASK_LOW_PRIORITY (tskIDLE_PRIORITY + 1)
+#define UI_TASK_PRIORITY (tskIDLE_PRIORITY + 3)
+#define USB_DEVICE_TASK_PRIORITY (tskIDLE_PRIORITY + 4)
+#define USB_PD_TASK_PRIORITY (tskIDLE_PRIORITY + 4)
+#define STARTUP_TASK_HIGH_PRIORITY (tskIDLE_PRIORITY + 5)
+#define KEY_SCAN_TASK_PRIORITY (tskIDLE_PRIORITY + 5)
+#define POWER_MON_TASK_PRIORITY (tskIDLE_PRIORITY + 5)
+
+#define STARTUP_TASK_STACK_SIZE (configMINIMAL_STACK_SIZE + 2048)
+#define USB_DEVICE_TASK_STACK_SIZE (configMINIMAL_STACK_SIZE + 128)
+#define USB_PD_TASK_STACK_SIZE (configMINIMAL_STACK_SIZE + 128)
+#define HOUSEKEEPING_TASK_STACK_SIZE (configMINIMAL_STACK_SIZE)
+#define UI_TASK_STACK_SIZE (configMINIMAL_STACK_SIZE)
+#define KEY_SCAN_TASK_STACK_SIZE (configMINIMAL_STACK_SIZE)
+#define POWER_MON_TASK_STACK_SIZE (configMINIMAL_STACK_SIZE)
diff --git a/fw/User/app_main.c b/fw/User/app_main.c
new file mode 100644
index 0000000..8d2d2cf
--- /dev/null
+++ b/fw/User/app_main.c
@@ -0,0 +1,123 @@
+//
+// Grimoire
+// Copyright 2025 Wenting Zhang
+//
+// 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.
+//
+#include "platform.h"
+#include "board.h"
+#include "app.h"
+
+// Memory for FreeRTOS
+//__attribute__((section(".mysection"))) uint8_t ucHeap[configTOTAL_HEAP_SIZE];
+uint8_t ucHeap[configTOTAL_HEAP_SIZE];
+
+// Contexts
+static shell_context_t shell;
+
+// Task handles
+TaskHandle_t housekeeping_task_handle;
+TaskHandle_t startup_task_handle;
+TaskHandle_t idle_task_handle;
+TaskHandle_t usb_device_task_handle;
+TaskHandle_t usb_pd_task_handle;
+TaskHandle_t ui_task_handle;
+TaskHandle_t key_scan_task_handle;
+TaskHandle_t power_mon_task_handle;
+
+static portTASK_FUNCTION(housekeeping_task, pvParameters) {
+ int led = 0;
+ TickType_t last_flash_time, flash_rate;
+
+ flash_rate = pdMS_TO_TICKS(500);
+ last_flash_time = xTaskGetTickCount();
+
+ while (1) {
+ gpio_put(LED_GRN, led);
+ led = !led;
+ vTaskDelayUntil(&last_flash_time, flash_rate);
+ }
+}
+
+static portTASK_FUNCTION(startup_task, pvParameters) {
+ // Power up sequence continues here
+ syslog_printf("System starting");
+ syslog_printf("Serial number: %08x", board_get_uid());
+
+ board_late_init();
+ pal_i2c_init();
+ spif_init();
+ spif_id_t id;
+ spif_read_jedec_id(&id);
+ syslog_printf("SPI Flash Mfg ID: %02x\n", id.manufacturer);
+ syslog_printf("SPI Flash Type: %02x\n", id.type);
+ syslog_printf("SPI Flash Capacity: %02x\n", id.capacity);
+ spiffs_init();
+// spif_erase_sector(0);
+// uint8_t buf[8] = {0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80};
+// spif_write(0, 8, buf);
+// memset(buf, 0, 8);
+// spif_read(0, 8, buf);
+// syslog_printf("RD: %02x %02x %02x %02x %02x %02x %02x %02x", buf[0], buf[1],
+// buf[2], buf[3], buf[4], buf[5], buf[6], buf[7]);
+ config_init();
+ config_load();
+ edid_init();
+ adv7611_early_init(); // Must be before PTN3460 to release RST and I2C bus
+ ptn3460_early_init(); // Let PTN3460 starts internal bootup process
+ fpga_init();
+ adv7611_init();
+ ptn3460_init();
+ caster_init(); // must be after adv7611 as it's the clock source for CSR interface
+ power_set_vcom(config.vcom); // Move out from here
+ power_set_vgh(config.vgh);
+ ui_init();
+
+ idle_task_handle = xTaskGetIdleTaskHandle();
+
+ xTaskCreate(housekeeping_task, "HousekeepingTask", HOUSEKEEPING_TASK_STACK_SIZE,
+ NULL, HOUSEKEEPING_TASK_PRIORITY, &housekeeping_task_handle);
+ xTaskCreate(usb_device_task, "USBDeviceTask", USB_DEVICE_TASK_STACK_SIZE,
+ NULL, USB_DEVICE_TASK_PRIORITY, &usb_device_task_handle);
+ xTaskCreate(usb_pd_task, "USBPDTask", USB_PD_TASK_STACK_SIZE,
+ NULL, USB_PD_TASK_PRIORITY, &usb_pd_task_handle);
+ xTaskCreate(ui_task, "UITask", UI_TASK_STACK_SIZE,
+ NULL, UI_TASK_PRIORITY, &ui_task_handle);
+ xTaskCreate(key_scan_task, "KeyScanTask", KEY_SCAN_TASK_STACK_SIZE,
+ NULL, KEY_SCAN_TASK_PRIORITY, &key_scan_task_handle);
+ xTaskCreate(power_monitor_task, "PowerMonitorTask", POWER_MON_TASK_STACK_SIZE,
+ NULL, POWER_MON_TASK_PRIORITY, &power_mon_task_handle);
+
+ vTaskPrioritySet(NULL, STARTUP_TASK_LOW_PRIORITY);
+
+ shell_init(&shell, usbapp_term_out, usbapp_term_in, SHELL_MODE_BLOCKING, NULL);
+
+ while (1) {
+ shell_start(&shell);
+ }
+}
+
+void app_init(void) {
+ syslog_init();
+
+ xTaskCreate(startup_task, "StartupTask", STARTUP_TASK_STACK_SIZE,
+ NULL, STARTUP_TASK_HIGH_PRIORITY, &startup_task_handle);
+
+ // Up to CubeMX to generate RTOS start
+}
diff --git a/fw/power.h b/fw/User/app_main.h
similarity index 67%
rename from fw/power.h
rename to fw/User/app_main.h
index d1cc59b..e74b895 100644
--- a/fw/power.h
+++ b/fw/User/app_main.h
@@ -1,5 +1,6 @@
//
-// Copyright 2023 Wenting Zhang
+// Grimoire
+// Copyright 2025 Wenting Zhang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -21,24 +22,13 @@
//
#pragma once
-#if defined(POWER_TPS65185)
-#include "tps65185.h"
+extern TaskHandle_t housekeeping_task_handle;
+extern TaskHandle_t startup_task_handle;
+extern TaskHandle_t idle_task_handle;
+extern TaskHandle_t usb_device_task_handle;
+extern TaskHandle_t usb_pd_task_handle;
+extern TaskHandle_t ui_task_handle;
+extern TaskHandle_t key_scan_task_handle;
+extern TaskHandle_t power_mon_task_handle;
-#define power_init() tps_init()
-#define power_enable(x) tps_enable(x)
-#define power_set_vcom(x) tps_set_vcom(x)
-
-#elif defined(POWER_MAX17135)
-#include "max17135.h"
-
-#define power_init() max_init()
-#define power_enable(x) max_enable(x)
-#define power_set_vcom(x) max_set_vcom(x)
-
-#elif defined(POWER_GPIO)
-
-void power_init(void);
-void power_enable(bool en);
-void power_set_vcom(uint16_t vcom);
-
-#endif
+void app_init(void);
diff --git a/fw/User/board.c b/fw/User/board.c
new file mode 100644
index 0000000..19cbcb3
--- /dev/null
+++ b/fw/User/board.c
@@ -0,0 +1,113 @@
+//
+// Grimoire
+// Copyright 2025 Wenting Zhang
+//
+// 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.
+//
+#include "platform.h"
+#include "board.h"
+#include "app.h"
+
+static loop_per_us = 0;
+
+size_t board_usb_get_serial(uint16_t desc_str1[], size_t max_chars) {
+ uint8_t uid[16] __attribute__ ((aligned(4)));
+ size_t uid_len;
+
+ uint32_t* uid32 = (uint32_t*) (uintptr_t) uid;
+ *uid32 = board_get_uid();
+ uid_len = 4;
+
+ if ( uid_len > max_chars / 2 ) uid_len = max_chars / 2;
+
+ for ( size_t i = 0; i < uid_len; i++ ) {
+ for ( size_t j = 0; j < 2; j++ ) {
+ const char nibble_to_hex[16] = {
+ '0', '1', '2', '3', '4', '5', '6', '7',
+ '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
+ };
+ uint8_t const nibble = (uid[i] >> (j * 4)) & 0xf;
+ desc_str1[i * 2 + (1 - j)] = nibble_to_hex[nibble]; // UTF-16-LE
+ }
+ }
+
+ return 2 * uid_len;
+}
+
+void board_late_init(void) {
+ uint32_t iter_count = 100;
+ uint32_t elapsed_ms;
+ do {
+ volatile uint32_t x = iter_count;
+ uint32_t start = xTaskGetTickCount() / portTICK_PERIOD_MS;
+ while (x--);
+ uint32_t end = xTaskGetTickCount() / portTICK_PERIOD_MS;
+ elapsed_ms = end - start;
+ if (elapsed_ms > 10)
+ break; // At least 10ms elapsed
+ iter_count *= 10;
+ } while (1);
+ loop_per_us = iter_count / (elapsed_ms * 1000);
+ syslog_printf("Delay loop calibrated, iterations per us: %d", loop_per_us);
+}
+
+void sleep_us(uint32_t us) {
+ volatile uint32_t x = us * loop_per_us;
+ while (x--);
+}
+
+void board_switch_spi_freq(SPI_HandleTypeDef *spi, uint32_t target) {
+ HAL_SPI_DeInit(spi);
+ if (target >= 24000000)
+ spi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2;
+ else if (target > 12000000)
+ spi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_4;
+ else if (target > 6000000)
+ spi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8;
+ else if (target > 3000000)
+ spi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16;
+ else if (target > 1500000)
+ spi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32;
+ else if (target > 750000)
+ spi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_64;
+ else if (target > 375000)
+ spi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_128;
+ else
+ spi->Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_256;
+ HAL_SPI_Init(spi);
+}
+
+void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) {
+ if (GPIO_Pin == GPIO_PIN_15) {
+ usbpd_isr();
+ }
+}
+
+// TODO: Use semaphore?
+// TODO: Handle more than 1 SPI instance
+static volatile bool tx_complete = false;
+
+void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef *hspi) {
+ tx_complete = true;
+}
+
+void spi_wait_dma_complete(SPI_HandleTypeDef *spi) {
+ while (!tx_complete);
+ tx_complete = false;
+}
diff --git a/fw/User/board.h b/fw/User/board.h
new file mode 100644
index 0000000..a95e9a7
--- /dev/null
+++ b/fw/User/board.h
@@ -0,0 +1,107 @@
+//
+// Grimoire
+// Copyright 2025 Wenting Zhang
+//
+// 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.
+//
+#pragma once
+
+#include "pal_i2c.h"
+
+#define LED_GRN GPIOE, GPIO_PIN_0
+#define LED_RED GPIOE, GPIO_PIN_1
+
+#define BTNCNT 2
+#define BTN1 GPIOB, GPIO_PIN_8
+#define BTN2 GPIOB, GPIO_PIN_5
+
+#define BTN_PRESSED_LEVEL 1 // Active high
+
+#define FPGA_CS GPIOB, GPIO_PIN_12
+#define FPGA_PROG GPIOC, GPIO_PIN_10
+#define FPGA_DONE GPIOC, GPIO_PIN_11
+#define FPGA_SUSP GPIOC, GPIO_PIN_12
+
+#define DP_PDN GPIOD, GPIO_PIN_3
+#define DP_HPD GPIOD, GPIO_PIN_7
+#define DEC_RST GPIOD, GPIO_PIN_6
+
+#define TYPEC_ORI GPIOA, GPIO_PIN_10
+#define TCPC_INT GPIOA, GPIO_PIN_15
+
+#define EPD_PWREN GPIOE, GPIO_PIN_11
+#define EPD_POSEN GPIOE, GPIO_PIN_12
+#define EPD_THROT GPIOD, GPIO_PIN_2
+
+#define FL_EN GPIOE, GPIO_PIN_15
+
+#define VCOM_MEN GPIOA, GPIO_PIN_2
+#define VCOM_EN GPIOA, GPIO_PIN_3
+
+#define FPGA_SPI &hspi2
+
+#define PTN3460_I2C &pi2c1
+#define ADV7611_I2C &pi2c1
+#define FUSB302_I2C &pi2c1
+#define INA3221_I2C &pi2c1
+
+#define TYPEC_MB_ORI_INV 0
+#define TYPEC_AUX_ORI_INV 0
+
+#define PTN3460_I2C_ADDR (0x60)
+#define ADV7611_I2C_ADDR (0x4C)
+#define FUSB302_I2C_ADDR (0x22)
+#define INA3221_0_I2C_ADDR (0x40)
+#define INA3221_1_I2C_ADDR (0x41)
+
+// ADV7611 Sub addresses, make sure they don't conflict with anything else!
+#define CEC_I2C_ADDR (0x3F) // Default 0x40(0x80)
+#define INFOFRAME_I2C_ADDR (0x3E) // Default 0x3E(0x7C)
+#define DPLL_I2C_ADDR (0x26) // Default 0x26(0x4C)
+#define KSV_I2C_ADDR (0x32) // Default 0x32(0x64)
+#define EDID_I2C_ADDR (0x36) // Default 0x36(0x6C)
+#define HDMI_I2C_ADDR (0x34) // Default 0x34(0x68)
+#define CP_I2C_ADDR (0x23) // Default 0x22(0x44)
+
+// For now, these resources are not shared among multiple threads, do not protect them
+extern SPI_HandleTypeDef hspi2;
+extern ADC_HandleTypeDef hadc1;
+extern DAC_HandleTypeDef hdac1;
+extern QSPI_HandleTypeDef hqspi;
+extern TIM_HandleTypeDef htim1;
+
+// GPIO operations are atomic, no need to protect
+#define gpio_put HAL_GPIO_WritePin
+#define gpio_get HAL_GPIO_ReadPin
+#define sleep_ms(x) vTaskDelay(pdMS_TO_TICKS(x))
+
+#define spi_send(spi, buf, size) \
+ HAL_SPI_Transmit(spi, buf, size, HAL_MAX_DELAY)
+#define spi_send_dma(spi, buf, size) \
+ HAL_SPI_Transmit_DMA(spi, buf, size)
+#define spi_send_recv(spi, txbuf, rxbuf, size) \
+ HAL_SPI_TransmitReceive(spi, txbuf, rxbuf, size, HAL_MAX_DELAY)
+
+#define board_get_uid HAL_GetUIDw0
+
+size_t board_usb_get_serial(uint16_t desc_str1[], size_t max_chars);
+void board_switch_spi_freq(SPI_HandleTypeDef *spi, uint32_t target);
+void board_late_init(void); // Initialization only after RTOS has started
+void sleep_us(uint32_t x);
+void spi_wait_dma_complete(SPI_HandleTypeDef *spi);
diff --git a/fw/User/button.c b/fw/User/button.c
new file mode 100644
index 0000000..e9343d3
--- /dev/null
+++ b/fw/User/button.c
@@ -0,0 +1,120 @@
+//
+// Grimoire
+// Copyright 2025 Wenting Zhang
+//
+// 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.
+//
+#include "platform.h"
+#include "board.h"
+#include "app.h"
+#include "button.h"
+
+// Unit: 10ms
+#define SHORT_PRESS_THRESHOLD 2
+#define LONG_PRESS_THRESHOLD 50
+#define RELEASE_THRESHOLD 2
+
+static int timecntr[BTNCNT] = {0};
+static enum {
+ STATE_IDLE,
+ STATE_FIRST_PRESSED,
+ STATE_HOLDING,
+ STATE_RELEASED
+} state[BTNCNT] = {0};
+
+void button_init() {
+ memset(timecntr, 0, sizeof(timecntr));
+ memset(state, 0, sizeof(state));
+}
+
+// Scan a single key, ID is the key number from 0, gpio is pin number
+// Should be called at ~10ms interval
+// Return value:
+// 0 when nothing pressed
+// 1 when short pressed
+// 2 when long pressed
+static uint32_t button_scan_single(int id, bool pressed) {
+ uint32_t retval = 0;
+
+ switch (state[id]) {
+ case STATE_IDLE:
+ if (pressed) {
+ state[id] = STATE_FIRST_PRESSED;
+ timecntr[id] = 0;
+ }
+ break;
+ case STATE_FIRST_PRESSED:
+ timecntr[id]++;
+ if (pressed) {
+ // Still pressing
+ if (timecntr[id] >= SHORT_PRESS_THRESHOLD) {
+ state[id] = STATE_HOLDING;
+ timecntr[id] = 0;
+ }
+ }
+ else {
+ // No longer pressed
+ state[id] = STATE_IDLE;
+ }
+ break;
+ case STATE_HOLDING:
+ timecntr[id]++;
+ if (pressed) {
+ // Still holding
+ if (timecntr[id] == LONG_PRESS_THRESHOLD) {
+ // Exactly when reaching the threshold, return the key press
+ // User gets feedback as soon as the threshold is reached
+ retval = BTN_LONG_PRESSED;
+ }
+ }
+ else {
+ // No longer holding
+ if (timecntr[id] < LONG_PRESS_THRESHOLD) {
+ // Is a short press, signal
+ retval = BTN_SHORT_PRESSED;
+ }
+ timecntr[id] = 0;
+ state[id] = STATE_RELEASED;
+ }
+ break;
+ case STATE_RELEASED:
+ if (pressed) {
+ // Pressed, reset time counter
+ timecntr[id] = 0;
+ }
+ else {
+ // Keep counting time
+ // Only treat key as released when reaching threshold
+ timecntr[id]++;
+ if (timecntr[id] >= RELEASE_THRESHOLD) {
+ state[id] = STATE_IDLE;
+ }
+ }
+ break;
+ }
+
+ return retval;
+}
+
+uint32_t button_scan() {
+ uint32_t btn1 = button_scan_single(0, gpio_get(BTN1) == BTN_PRESSED_LEVEL);
+ uint32_t btn2 = button_scan_single(1, gpio_get(BTN2) == BTN_PRESSED_LEVEL);
+ uint32_t retval = (btn1 & 0x3) | ((btn2 & 0x3) << 2);
+ return retval;
+}
diff --git a/fw/button.h b/fw/User/button.h
similarity index 87%
rename from fw/button.h
rename to fw/User/button.h
index 1a470da..ceb46bd 100644
--- a/fw/button.h
+++ b/fw/User/button.h
@@ -1,5 +1,6 @@
//
-// Copyright 2024 Wenting Zhang
+// Grimoire
+// Copyright 2025 Wenting Zhang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -21,5 +22,10 @@
//
#pragma once
+#define BTN_SHIFT 2
+#define BTN_MASK 0x3
+#define BTN_SHORT_PRESSED 1
+#define BTN_LONG_PRESSED 2
+
void button_init();
uint32_t button_scan();
diff --git a/fw/caster.c b/fw/User/caster.c
similarity index 75%
rename from fw/caster.c
rename to fw/User/caster.c
index 29ffa98..eec2c1c 100644
--- a/fw/caster.c
+++ b/fw/User/caster.c
@@ -1,6 +1,6 @@
//
-// Glider
-// Copyright 2024 Wenting Zhang
+// Grimoire
+// Copyright 2025 Wenting Zhang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -20,13 +20,9 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
-#include
-#include
-#include
-#include
-#include "config.h"
-#include "caster.h"
-#include "fpga.h"
+#include "platform.h"
+#include "board.h"
+#include "app.h"
static size_t last_update;
static size_t last_update_duration;
@@ -45,15 +41,19 @@ static void wait(void) {
void caster_init(void) {
waveform_frames = 38; // Need to sync with the RTL code
- // fpga_write_reg8(CSR_CFG_V_FP, TCON_VFP);
- // fpga_write_reg8(CSR_CFG_V_SYNC, TCON_VSYNC);
- // fpga_write_reg8(CSR_CFG_V_BP, TCON_VBP);
- // fpga_write_reg16(CSR_CFG_V_ACT, TCON_VACT);
- // fpga_write_reg8(CSR_CFG_H_FP, TCON_HFP);
- // fpga_write_reg8(CSR_CFG_H_SYNC, TCON_HSYNC);
- // fpga_write_reg8(CSR_CFG_H_BP, TCON_HBP);
- // fpga_write_reg16(CSR_CFG_H_ACT, TCON_HACT);
- // fpga_write_reg8(CSR_CONTROL, 1); // Enable refresh
+ fpga_write_reg8(CSR_CFG_V_FP, config.tcon_vfp);
+ fpga_write_reg8(CSR_CFG_V_SYNC, config.tcon_vsync);
+ fpga_write_reg8(CSR_CFG_V_BP, config.tcon_vbp);
+ fpga_write_reg16(CSR_CFG_V_ACT, config.tcon_vact);
+ fpga_write_reg8(CSR_CFG_H_FP, config.tcon_hfp);
+ fpga_write_reg8(CSR_CFG_H_SYNC, config.tcon_hsync);
+ fpga_write_reg8(CSR_CFG_H_BP, config.tcon_hbp);
+ fpga_write_reg16(CSR_CFG_H_ACT, config.tcon_hact);
+ uint32_t frame_bytes = config.tcon_hact * 4 * config.tcon_vact * 2;
+ fpga_write_reg8(CSR_CFG_FBYTES_B0, frame_bytes & 0xff);
+ fpga_write_reg8(CSR_CFG_FBYTES_B1, (frame_bytes >> 8) & 0xff);
+ fpga_write_reg8(CSR_CFG_FBYTES_B2, (frame_bytes >> 16) & 0xff);
+ fpga_write_reg8(CSR_CONTROL, 1); // Enable refresh
//fpga_write_reg8(CSR_CFG_MINDRV, 0);
fpga_write_reg8(CSR_LUT_FRAME, 38);
}
@@ -83,7 +83,7 @@ uint8_t caster_redraw(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1) {
}
uint8_t caster_setmode(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1,
- UPDATE_MODE mode) {
+ update_mode_t mode) {
if (is_busy()) return 1;
fpga_write_reg16(CSR_OP_LEFT, x0);
fpga_write_reg16(CSR_OP_TOP, y0);
@@ -96,7 +96,7 @@ uint8_t caster_setmode(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1,
}
uint8_t caster_setinput(uint8_t input_src) {
- if (is_busy()) return 1;
- fpga_write_reg8(CSR_CFG_IN_SRC, input_src);
+// if (is_busy()) return 1;
+// fpga_write_reg8(CSR_CFG_IN_SRC, input_src);
return 0;
}
diff --git a/fw/caster.h b/fw/User/caster.h
similarity index 97%
rename from fw/caster.h
rename to fw/User/caster.h
index 80318bd..8daadc2 100644
--- a/fw/caster.h
+++ b/fw/User/caster.h
@@ -1,6 +1,6 @@
//
-// Caster simulator
-// Copyright 2023 Wenting Zhang
+// Grimoire
+// Copyright 2025 Wenting Zhang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -88,10 +88,10 @@ typedef enum {
UM_FAST_GREY = 5,
UM_AUTO_LUT_NO_DITHER = 6,
UM_AUTO_LUT_ERROR_DIFFUSION = 7
-} UPDATE_MODE;
+} update_mode_t;
void caster_init(void);
uint8_t caster_load_waveform(uint8_t *waveform, uint8_t frames);
uint8_t caster_redraw(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1);
uint8_t caster_setmode(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1,
- UPDATE_MODE mode);
+ update_mode_t mode);
diff --git a/fw/User/config.c b/fw/User/config.c
new file mode 100644
index 0000000..58dfa07
--- /dev/null
+++ b/fw/User/config.c
@@ -0,0 +1,81 @@
+//
+// Grimoire
+// Copyright 2025 Wenting Zhang
+//
+// 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.
+//
+#include "platform.h"
+#include "board.h"
+#include "app.h"
+
+config_t config;
+
+void config_init(void) {
+ // Set default values
+ config.pclk_hz = 162000000;
+ config.hact = 1600;
+ config.vact = 1200;
+ config.hblk = 560;
+ config.hfp = 64;
+ config.hsync = 192;
+ config.vblk = 50;
+ config.vfp = 1;
+ config.vsync = 3;
+ config.size_x_mm = 270;
+ config.size_y_mm = 203;
+ config.mfg_week = 1;
+ config.mfg_year = 0x20;
+ config.tcon_vfp = 45;
+ config.tcon_vsync = 1;
+ config.tcon_vbp = 2;
+ config.tcon_vact = 1200;
+ config.tcon_hfp = 120;
+ config.tcon_hsync = 10;
+ config.tcon_hbp = 10;
+ config.tcon_hact = 400;
+ config.vcom = -2.45f;
+ config.vgh = 22.0f;
+}
+
+void config_load(void) {
+ SPIFFS_clearerr(&spiffs_fs);
+ spiffs_file f = SPIFFS_open(&spiffs_fs, "config.bin", SPIFFS_O_RDONLY, 0);
+ if (SPIFFS_errno(&spiffs_fs) != 0)
+ return;
+
+ spiffs_stat s;
+ SPIFFS_fstat(&spiffs_fs, f, &s);
+ uint32_t size = s.size;
+ if (size != sizeof(config)) {
+ SPIFFS_close(&spiffs_fs, f);
+ return;
+ }
+
+ SPIFFS_read(&spiffs_fs, f, &config, sizeof(config));
+ SPIFFS_close(&spiffs_fs, f);
+}
+
+void config_save(void) {
+ SPIFFS_clearerr(&spiffs_fs);
+ spiffs_file f = SPIFFS_open(&spiffs_fs, "config.bin", SPIFFS_O_CREAT | SPIFFS_O_TRUNC | SPIFFS_O_WRONLY, 0);
+ if (SPIFFS_errno(&spiffs_fs) != 0)
+ return;
+
+ SPIFFS_write(&spiffs_fs, f, &config, sizeof(config));
+}
\ No newline at end of file
diff --git a/fw/User/config.h b/fw/User/config.h
new file mode 100644
index 0000000..8ec371f
--- /dev/null
+++ b/fw/User/config.h
@@ -0,0 +1,56 @@
+//
+// Grimoire
+// Copyright 2025 Wenting Zhang
+//
+// 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.
+//
+#pragma once
+
+typedef struct {
+ uint32_t pclk_hz; // pixel clock
+ uint8_t hfp;
+ uint8_t vfp;
+ uint8_t hsync;
+ uint8_t vsync;
+ uint16_t hact;
+ uint16_t hblk;
+ uint16_t vact;
+ uint16_t vblk;
+ uint16_t size_x_mm; // horizontal screen size
+ uint16_t size_y_mm; // vertical screen size
+ uint8_t mfg_week;
+ uint8_t mfg_year;
+ float vcom;
+ float vgh;
+ // TCON configurations
+ uint8_t tcon_vfp;
+ uint8_t tcon_vsync;
+ uint8_t tcon_vbp;
+ uint16_t tcon_vact;
+ uint8_t tcon_hfp;
+ uint8_t tcon_hsync;
+ uint8_t tcon_hbp;
+ uint16_t tcon_hact;
+} config_t;
+
+extern config_t config;
+
+void config_init(void);
+void config_load(void);
+void config_save(void);
diff --git a/fw/crc16.c b/fw/User/crc16.c
similarity index 100%
rename from fw/crc16.c
rename to fw/User/crc16.c
diff --git a/fw/crc16.h b/fw/User/crc16.h
similarity index 100%
rename from fw/crc16.h
rename to fw/User/crc16.h
diff --git a/fw/User/edid.c b/fw/User/edid.c
new file mode 100644
index 0000000..0d3f16c
--- /dev/null
+++ b/fw/User/edid.c
@@ -0,0 +1,123 @@
+//
+// Glider
+// Copyright 2024 Wenting Zhang
+//
+// 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.
+//
+#include "platform.h"
+#include "board.h"
+#include "app.h"
+
+// 0x81 for DVI, 0x85 for DP
+// Always use 0x85 for now, doesn't really matter
+#define EDID_VID_IN_PARAM (0x85)
+
+static uint8_t edid[128] = {
+ 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, // fixed header (0-7)
+ 0x6a, 0x12, // manufacturer ID (8-9)
+ 0x01, 0x00, // product code (10-11)
+ 0x42, 0x4b, 0x1d, 0x00, // serial number (12-15)
+ 0x01, // week of manufacture (16)
+ 0x20, // year of manufacture (17)
+ 0x01, // EDID version (18)
+ 0x03, // EDID revision (19)
+ EDID_VID_IN_PARAM, // video input parameter (20)
+ 0x00, // horizontal screen size in cm (21)
+ 0x00, // vertical screen size in cm (22)
+ 0x78, // display gamma (23)
+ 0x06, // supported feature (24)
+ 0xee, 0x95, 0xa3, 0x54, 0x4c, 0x99, 0x26, 0x0f, 0x50, 0x54, // chromatic (25-34)
+ 0x00, 0x00, 0x00, // established timing (35-37)
+ 0x01, // X resolution (38)
+ 0x00, // aspect ratio and vertical frequency (39)
+ 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, // standard timing
+ 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, // standard timing continued
+ // descriptor 1 (54-71)
+ 0x00, 0x00, // pixel clock in 10kHz
+ 0x00, // HACT LSB
+ 0x00, // VBLK LSB
+ 0x00, // HACT MSB | HBLK MSB
+ 0x00, // VACT LSB
+ 0x00, // VBLK LSB
+ 0x00, // VACT MSB | VBLK MSB
+ 0x00, // HFP LSB
+ 0x00, // HSYNC LSB
+ 0x00, // VFP LSB | VSYNC LSB
+ 0x00, // HFP MSB | HSYNC MSB | VFP MSB | VSYNC MSB
+ 0x00, // Horizontal size in mm LSB
+ 0x00, // Vertical size in mm LSB
+ 0x00, // HSIZE MSB | VSIZE LSB
+ 0x00, // Horizontal border pixels
+ 0x00, // Vertical border lines
+ 0x1e, // Features bitmap
+ // descriptor 2 (72-89) display name
+ 0x00, 0x00, 0x00, 0xfc, 0x00, 0x50, 0x61, 0x70, 0x65, 0x72, 0x20,
+ 0x4d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72,
+ // descriptor 3 (90-107) display name
+ 0x00, 0x00, 0x00, 0xfc, 0x00, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
+ 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
+ // descriptor 4 (108-125) dummy
+ 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, // number of extensions (126)
+ 0x00 // checksum (127)
+};
+
+void edid_init(void) {
+ // Fill in runtime info
+ edid[16] = config.mfg_week;
+ edid[17] = config.mfg_year;
+ edid[21] = config.size_x_mm / 10;
+ edid[22] = config.size_y_mm / 10;
+ edid[54] = (config.pclk_hz / 10000) & 0xff;
+ edid[55] = ((config.pclk_hz / 10000) >> 8) & 0xff;
+ edid[56] = config.hact & 0xff;
+ edid[57] = config.hblk & 0xff;
+ edid[58] = ((config.hact >> 8) << 4) | (config.hblk >> 8);
+ edid[59] = config.vact & 0xff;
+ edid[60] = config.vblk & 0xff;
+ edid[61] = ((config.vact >> 8) << 4) | (config.vblk >> 8);
+ edid[62] = config.hfp & 0xff;
+ edid[63] = config.hsync & 0xff;
+ edid[64] = ((config.vfp & 0xf) << 4) | (config.vsync & 0xf);
+ edid[65] = ((config.hfp >> 8) << 6) | ((config.hsync >> 8) << 4) |
+ ((config.vfp >> 4) << 2) | (config.vsync >> 4);
+ edid[66] = config.size_x_mm & 0xff;
+ edid[67] = config.size_y_mm & 0xff;
+ edid[68] = ((config.size_x_mm >> 8) << 4) | ((config.size_y_mm >> 8));
+
+ uint32_t devid = board_get_uid();
+ // Populate serial number with this ID
+ edid[12] = (devid >> 24) & 0xff;
+ edid[13] = (devid >> 16) & 0xff;
+ edid[14] = (devid >> 8) & 0xff;
+ edid[15] = (devid) & 0xff;
+
+ // Fix checksum in EDID
+ uint8_t checksum = 0;
+ for (int i = 0; i < 127; i++) {
+ checksum += edid[i];
+ }
+ checksum = ~checksum + 1;
+ edid[127] = checksum;
+}
+
+uint8_t *edid_get_raw() {
+ return edid;
+}
diff --git a/fw/edid.c b/fw/User/edid.c.hardcoded
similarity index 56%
rename from fw/edid.c
rename to fw/User/edid.c.hardcoded
index 56d67fd..7ab3ba9 100644
--- a/fw/edid.c
+++ b/fw/User/edid.c.hardcoded
@@ -1,5 +1,6 @@
//
-// Copyright 2022 Wenting Zhang
+// Grimoire
+// Copyright 2025 Wenting Zhang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -19,27 +20,52 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
-#include
-#include
-#include
-#include
-#include
-#include "edid.h"
-#include "config.h"
-
-#ifdef BOARD_USE_EDID_EMU
-#define EDID_I2C_ADDRESS (0x50)
-#define EDID_I2C (i2c0)
-#define EDID_I2C_SDA (0)
-#define EDID_I2C_SCL (1)
-#endif
+#include "platform.h"
+#include "board.h"
+#include "app.h"
// 0x81 for DVI, 0x85 for DP
// Always use 0x85 for now, doesn't really matter
-#define EDID_VID_IN_PARAM (0x85)
+#define EDID_VID_IN_PARAM (0x81)
-static char edid[129] = {
- 0x00, // register number, not part of EDID
+#define SCREEN_SIZE_X 270
+#define SCREEN_SIZE_Y 203
+#define SCREEN_ASPECT SCREEN_ASPECT_4_3
+
+// 800x600 @ 60, 40MHz DMT
+//#define SCREEN_CLK 40000
+//#define SCREEN_HACT 800
+//#define SCREEN_VACT 600
+//#define SCREEN_HBLK 256
+//#define SCREEN_HFP 40
+//#define SCREEN_HSYNC 128
+//#define SCREEN_VBLK 28
+//#define SCREEN_VFP 1
+//#define SCREEN_VSYNC 4
+
+// DMT
+#define SCREEN_CLK 162000
+#define SCREEN_HACT 1600
+#define SCREEN_VACT 1200
+#define SCREEN_HBLK 560
+#define SCREEN_HFP 64
+#define SCREEN_HSYNC 192
+#define SCREEN_VBLK 50
+#define SCREEN_VFP 1
+#define SCREEN_VSYNC 3
+
+// CVT RBv2
+//#define SCREEN_CLK 124488
+//#define SCREEN_HACT 1600
+//#define SCREEN_VACT 1200
+//#define SCREEN_HBLK 80
+//#define SCREEN_HFP 8
+//#define SCREEN_HSYNC 32
+//#define SCREEN_VBLK 35
+//#define SCREEN_VFP 21
+//#define SCREEN_VSYNC 8
+
+static uint8_t edid[128] = {
0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, // fixed header (0-7)
0x6a, 0x12, // manufacturer ID (8-9)
0x01, 0x00, // product code (10-11)
@@ -60,24 +86,24 @@ static char edid[129] = {
0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, // standard timing
0x01, 0x00, 0x01, 0x00, 0x01, 0x00, // standard timing continued
// descriptor 1 (54-71)
- ((SCREEN_CLK / 10) & 0xff), ((SCREEN_CLK / 10) >> 8), // pixel clock in 10kHz
- (SCREEN_HACT & 0xff), // HACT LSB
- (SCREEN_HBLK & 0xff), // VBLK LSB
- (((SCREEN_HACT >> 8) << 4) | (SCREEN_HBLK >> 8)), // HACT MSB | HBLK MSB
- (SCREEN_VACT & 0xff), // VACT LSB
- (SCREEN_VBLK & 0xff), // VBLK LSB
- (((SCREEN_VACT >> 8) << 4) | (SCREEN_VBLK >> 8)), // VACT MSB | VBLK MSB
- (SCREEN_HFP & 0xff), // HFP LSB
- (SCREEN_HSYNC & 0xff), // HSYNC LSB
- (((SCREEN_VFP & 0xf) << 4) | (SCREEN_VSYNC & 0xf)), // VFP LSB | VSYNC LSB
+ ((SCREEN_CLK / 10) & 0xff), ((SCREEN_CLK / 10) >> 8), // pixel clock in 10kHz 54, 55
+ (SCREEN_HACT & 0xff), // HACT LSB 56
+ (SCREEN_HBLK & 0xff), // HBLK LSB 57
+ (((SCREEN_HACT >> 8) << 4) | (SCREEN_HBLK >> 8)), // HACT MSB | HBLK MSB 58
+ (SCREEN_VACT & 0xff), // VACT LSB 59
+ (SCREEN_VBLK & 0xff), // VBLK LSB 60
+ (((SCREEN_VACT >> 8) << 4) | (SCREEN_VBLK >> 8)), // VACT MSB | VBLK MSB 61
+ (SCREEN_HFP & 0xff), // HFP LSB 62
+ (SCREEN_HSYNC & 0xff), // HSYNC LSB 63
+ (((SCREEN_VFP & 0xf) << 4) | (SCREEN_VSYNC & 0xf)), // VFP LSB | VSYNC LSB 64
(((SCREEN_HFP >> 8) << 6) | ((SCREEN_HSYNC >> 8) << 4) |
- ((SCREEN_VFP >> 4) << 2) | (SCREEN_VSYNC >> 4)), // HFP MSB | HSYNC MSB | VFP MSB | VSYNC MSB
- (SCREEN_SIZE_X & 0xff), // Horizontal size in mm LSB
- (SCREEN_SIZE_Y & 0xff), // Vertical size in mm LSB
- (((SCREEN_SIZE_X >> 8) << 4) | (SCREEN_SIZE_Y >> 8)), // HSIZE MSB | VSIZE LSB
- 0x00, // Horizontal border pixels
- 0x00, // Vertical border lines
- 0x1e, // Features bitmap
+ ((SCREEN_VFP >> 4) << 2) | (SCREEN_VSYNC >> 4)), // HFP MSB | HSYNC MSB | VFP MSB | VSYNC MSB 65
+ (SCREEN_SIZE_X & 0xff), // Horizontal size in mm LSB 66
+ (SCREEN_SIZE_Y & 0xff), // Vertical size in mm LSB 67
+ (((SCREEN_SIZE_X >> 8) << 4) | (SCREEN_SIZE_Y >> 8)), // HSIZE MSB | VSIZE LSB 68
+ 0x00, // Horizontal border pixels 69
+ 0x00, // Vertical border lines 70
+ 0x1e, // Features bitmap 71
// descriptor 2 (72-89) display name
0x00, 0x00, 0x00, 0xfc, 0x00, 0x50, 0x61, 0x70, 0x65, 0x72, 0x20,
0x4d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72,
@@ -91,64 +117,22 @@ static char edid[129] = {
0x00 // checksum (127)
};
-#ifdef BOARD_USE_EDID_EMU
-static void edid_i2c_slave_handler(i2c_inst_t *i2c, i2c_slave_event_t event) {
- static uint8_t addr = 0;
-
- switch (event) {
- case I2C_SLAVE_RECEIVE:
- // I2C master has written some data
- // EDID is read only, all write are treated as address
- addr = i2c_read_byte_raw(i2c);
- break;
- case I2C_SLAVE_REQUEST:
- // I2C master is requesting data
- i2c_write_byte_raw(i2c, edid[addr + 1]);
- addr++;
- if (addr == 128)
- addr = 0; // wrap around
- break;
- case I2C_SLAVE_FINISH:
- // I2C master sent stop
- // Reset transaction if needed
- break;
- }
-}
-#endif
-
-void edid_init() {
+void edid_init(void) {
// Fill in runtime info
- pico_unique_board_id_t board_id;
- pico_get_unique_board_id(&board_id);
- // Populate serial number with this ID (XORed down to 4 bytes)
- edid[13] = board_id.id[0] ^ board_id.id[4];
- edid[14] = board_id.id[1] ^ board_id.id[5];
- edid[15] = board_id.id[2] ^ board_id.id[6];
- edid[16] = board_id.id[3] ^ board_id.id[7];
+ uint32_t devid = board_get_uid();
+ // Populate serial number with this ID
+ edid[12] = (devid >> 24) & 0xff;
+ edid[13] = (devid >> 16) & 0xff;
+ edid[14] = (devid >> 8) & 0xff;
+ edid[15] = (devid) & 0xff;
// Fix checksum in EDID
uint8_t checksum = 0;
- for (int i = 1; i < 128; i++) {
+ for (int i = 0; i < 127; i++) {
checksum += edid[i];
}
checksum = ~checksum + 1;
- edid[128] = checksum;
-
-#ifdef BOARD_USE_EDID_EMU
- // DVI models has DDC I2C connected directly to the RP2040
- // EDID ROM emulation is needed
-
- gpio_init(EDID_I2C_SDA);
- gpio_init(EDID_I2C_SCL);
-
- gpio_set_function(EDID_I2C_SDA, GPIO_FUNC_I2C);
- gpio_set_function(EDID_I2C_SCL, GPIO_FUNC_I2C);
-
- i2c_slave_init(EDID_I2C, EDID_I2C_ADDRESS, &edid_i2c_slave_handler);
-
- // Pull HPD high so host can read the EDID
-
-#endif
+ edid[127] = checksum;
}
uint8_t *edid_get_raw() {
diff --git a/fw/edid.h b/fw/User/edid.h
similarity index 95%
rename from fw/edid.h
rename to fw/User/edid.h
index 880f1b1..6749380 100644
--- a/fw/edid.h
+++ b/fw/User/edid.h
@@ -1,5 +1,6 @@
//
-// Copyright 2022 Wenting Zhang
+// Grimoire
+// Copyright 2025 Wenting Zhang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
diff --git a/fw/User/fpga.c b/fw/User/fpga.c
new file mode 100644
index 0000000..e0849d1
--- /dev/null
+++ b/fw/User/fpga.c
@@ -0,0 +1,170 @@
+//
+// Grimoire
+// Copyright 2025 Wenting Zhang
+//
+// 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.
+//
+#include "platform.h"
+#include "board.h"
+#include "app.h"
+//#include "bitstream.h"
+
+static int fpga_done = 0;
+
+static void delay_loop(uint32_t t) {
+ volatile uint32_t x = t;
+ while (x--);
+}
+
+uint8_t fpga_write_reg8(uint8_t addr, uint8_t val) {
+ uint8_t txbuf[2] = {addr, val};
+ uint8_t rxbuf[2];
+ gpio_put(FPGA_CS, 0);
+ spi_send_recv(FPGA_SPI, txbuf, rxbuf, 2);
+ gpio_put(FPGA_CS, 1);
+ return rxbuf[1];
+}
+
+void fpga_write_reg16(uint8_t addr, uint16_t val) {
+ uint8_t txbuf[3] = {addr, val >> 8, val & 0xff};
+ gpio_put(FPGA_CS, 0);
+ spi_send(FPGA_SPI, txbuf, 3);
+ gpio_put(FPGA_CS, 1);
+}
+
+void fpga_write_bulk(uint8_t addr, uint8_t *buf, int length) {
+ uint8_t txbuf[1] = {addr};
+ gpio_put(FPGA_CS, 0);
+ spi_send(FPGA_SPI, txbuf, 1);
+ spi_send(FPGA_SPI, buf, length);
+ gpio_put(FPGA_CS, 1);
+}
+
+static void fpga_load_bitstream(const char *fn) {
+
+ TickType_t start = xTaskGetTickCount();
+
+ SPIFFS_clearerr(&spiffs_fs);
+ spiffs_file f = SPIFFS_open(&spiffs_fs, fn, SPIFFS_O_RDONLY, 0);
+ if (SPIFFS_errno(&spiffs_fs) != 0)
+ return;
+
+ spiffs_stat s;
+ SPIFFS_fstat(&spiffs_fs, f, &s);
+ uint32_t size = s.size;
+
+ const int block_size = 4096;
+ uint8_t *buf0 = pvPortMalloc(block_size);
+ uint8_t *buf1 = pvPortMalloc(block_size);
+ uint8_t *rdbuf = buf0;
+ uint8_t *wrbuf = buf1;
+ int readbuf = 0;
+
+ gpio_put(FPGA_CS, 0);
+ for (int i = 0; i < size / block_size; i++) {
+ // Start writing if available
+ if (i != 0)
+ spi_send_dma(FPGA_SPI, wrbuf, block_size);
+ SPIFFS_read(&spiffs_fs, f, rdbuf, block_size);
+ // Check DMA finish
+ if (i != 0)
+ spi_wait_dma_complete(FPGA_SPI);
+ // Swap buffer
+ readbuf = !readbuf;
+ rdbuf = readbuf ? buf1 : buf0;
+ wrbuf = readbuf ? buf0 : buf1;
+ }
+
+ // Writing last read block
+ spi_send_dma(FPGA_SPI, wrbuf, block_size);
+
+ int remaining = size % block_size;
+ if (remaining != 0) {
+ SPIFFS_read(&spiffs_fs, f, rdbuf, remaining);
+
+ // Check DMA finish
+ spi_wait_dma_complete(FPGA_SPI);
+ // No need to swap buffer, just send out the last block
+ spi_send_dma(FPGA_SPI, rdbuf, block_size);
+ }
+ gpio_put(FPGA_CS, 1);
+ SPIFFS_close(&spiffs_fs, f);
+
+ // Check DMA finish
+ spi_wait_dma_complete(FPGA_SPI);
+
+ vPortFree(buf0);
+ vPortFree(buf1);
+
+ TickType_t end = xTaskGetTickCount();
+
+ syslog_printf("Bitstream loading took %d ms", (end - start) * (1000 / configTICK_RATE_HZ));
+}
+
+
+static void fpga_wait_done(bool timeout) {
+ if (timeout) {
+ int i;
+ for (i = 0; i < 10; i++) {
+ if (gpio_get(FPGA_DONE) == 1)
+ break;
+ sleep_ms(100);
+ }
+ if (gpio_get(FPGA_DONE) == 0) {
+ syslog_printf("FPGA done does not go high after 1s");
+ }
+ syslog_printf("FPGA is up after %d ms.\n", i);
+ }
+ else {
+ while (gpio_get(FPGA_DONE) != 1) {
+ sleep_ms(100);
+ }
+ syslog_printf("FPGA is up.\n");
+ }
+}
+
+void fpga_init(void) {
+ // Initialize FPGA pins
+ gpio_put(FPGA_CS, 1);
+
+ // FPGA Reset
+ gpio_put(FPGA_PROG, 0);
+ sleep_ms(2);
+ gpio_put(FPGA_PROG, 1);
+ sleep_ms(10);
+
+ // Load bitstream
+#if 1
+ fpga_load_bitstream("fpga.bit");
+ fpga_wait_done(true);
+#else
+ //fpga_wait_done(false);
+#endif
+
+ // Switch to lower frequency
+ board_switch_spi_freq(FPGA_SPI, 6000000);
+}
+
+void fpga_suspend(void) {
+
+}
+
+void fpga_resume(void) {
+
+}
diff --git a/fw/fpga.h b/fw/User/fpga.h
similarity index 96%
rename from fw/fpga.h
rename to fw/User/fpga.h
index 8acc106..44cc71d 100644
--- a/fw/fpga.h
+++ b/fw/User/fpga.h
@@ -1,5 +1,6 @@
//
-// Copyright 2022 Wenting Zhang
+// Grimoire
+// Copyright 2025 Wenting Zhang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
diff --git a/fw/User/pal_i2c.c b/fw/User/pal_i2c.c
new file mode 100644
index 0000000..aaa6b6b
--- /dev/null
+++ b/fw/User/pal_i2c.c
@@ -0,0 +1,306 @@
+//
+// Grimoire
+// Copyright 2025 Wenting Zhang
+//
+// 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.
+//
+#include "platform.h"
+#include "pal_i2c.h"
+
+// Ugly
+#define I2C1_SCL GPIOB, GPIO_PIN_6
+#define I2C1_SDA GPIOB, GPIO_PIN_7
+
+struct pal_i2c_t {
+ SemaphoreHandle_t lock;
+ I2C_TypeDef *port;
+};
+
+struct pal_i2c_t pi2c1;
+
+extern I2C_HandleTypeDef hi2c1;
+
+void pal_i2c_init(void) {
+ pi2c1.port = I2C1;
+ pi2c1.lock = xSemaphoreCreateMutex();
+}
+
+bool pal_i2c_ll_start(pal_i2c_t *i2c, uint32_t request, uint8_t slave_addr, uint8_t transfer_size) {
+ I2C_TypeDef* port = i2c->port;
+ int timeout = 500;
+
+ LL_I2C_HandleTransfer(port, slave_addr, LL_I2C_ADDRSLAVE_7BIT,
+ transfer_size, LL_I2C_MODE_SOFTEND, request);
+
+ while (!LL_I2C_IsActiveFlag_TXIS(port) && !LL_I2C_IsActiveFlag_RXNE(port)) {
+ if (LL_I2C_IsActiveFlag_NACK(port)) {
+ syslog_printf("Addr NACK");
+ LL_I2C_ClearFlag_NACK(port);
+ return false;
+ }
+ if (timeout-- == 0) {
+ syslog_printf("Addr timeout");
+ return false;
+ }
+ sleep_us(1);
+ }
+
+ return true;
+}
+
+
+bool pal_i2c_ll_send(pal_i2c_t *i2c, uint8_t val) {
+ I2C_TypeDef* port = i2c->port;
+ int timeout = 500;
+
+ LL_I2C_TransmitData8(port, val);
+ while (!LL_I2C_IsActiveFlag_TXIS(port) && !LL_I2C_IsActiveFlag_TC(port)) {
+ /* Break if ACK failed */
+ if (LL_I2C_IsActiveFlag_NACK(port)) {
+ LL_I2C_ClearFlag_NACK(port);
+ syslog_printf("Data NACK");
+ return false;
+ }
+ if (timeout-- == 0) {
+ syslog_printf("Data timeout");
+ return false;
+ }
+ sleep_us(1);
+ }
+
+ return true;
+}
+
+
+bool pal_i2c_ll_recv(pal_i2c_t *i2c, uint8_t *val) {
+ I2C_TypeDef* port = i2c->port;
+ int timeout = 500;
+
+ if (!val)
+ return false;
+
+ while (!LL_I2C_IsActiveFlag_RXNE(port) && !LL_I2C_IsActiveFlag_TC(port)) {
+ if (timeout-- == 0) {
+ return false;
+ }
+ sleep_us(1);
+ }
+
+ *val = LL_I2C_ReceiveData8(port);
+
+ return true;
+}
+
+
+void pal_i2c_ll_stop(pal_i2c_t *i2c) {
+ I2C_TypeDef* port = i2c->port;
+ /* Send STOP bit */
+ LL_I2C_GenerateStopCondition(port);
+ while(LL_I2C_IsActiveFlag_BUSY(port));
+}
+
+void pal_i2c_ll_lock(pal_i2c_t *i2c) {
+ xSemaphoreTake(i2c->lock, portMAX_DELAY);
+}
+
+void pal_i2c_ll_unlock(pal_i2c_t *i2c) {
+ xSemaphoreGive(i2c->lock);
+}
+
+int pal_i2c_write_byte(pal_i2c_t *i2c, uint8_t addr, uint8_t val) {
+ int result = -1;
+ xSemaphoreTake(i2c->lock, portMAX_DELAY);
+ if (!pal_i2c_ll_start(i2c, REQ_WRITE, addr << 1, 1))
+ goto i2c_stop_point;
+ if (!pal_i2c_ll_send(i2c, val))
+ goto i2c_stop_point;
+ result = 0;
+i2c_stop_point:
+ pal_i2c_ll_stop(i2c);
+ xSemaphoreGive(i2c->lock);
+ return result;
+}
+
+int pal_i2c_write_reg(pal_i2c_t *i2c, uint8_t addr, uint8_t reg, uint8_t val) {
+ int result = -1;
+ xSemaphoreTake(i2c->lock, portMAX_DELAY);
+ if (!pal_i2c_ll_start(i2c, REQ_WRITE, addr << 1, 2))
+ goto i2c_stop_point;
+ if (!pal_i2c_ll_send(i2c, reg))
+ goto i2c_stop_point;
+ if (!pal_i2c_ll_send(i2c, val))
+ goto i2c_stop_point;
+ result = 0;
+i2c_stop_point:
+ pal_i2c_ll_stop(i2c);
+ xSemaphoreGive(i2c->lock);
+ return result;
+}
+
+int pal_i2c_write_longreg(pal_i2c_t *i2c, uint8_t addr, uint8_t reg, uint8_t *payload, size_t len) {
+ int result = -1;
+ xSemaphoreTake(i2c->lock, portMAX_DELAY);
+ if (!pal_i2c_ll_start(i2c, REQ_WRITE, addr << 1, 1 + len))
+ goto i2c_stop_point;
+ if (!pal_i2c_ll_send(i2c, reg))
+ goto i2c_stop_point;
+ for (int i = 0; i < len; i++) {
+ if (!pal_i2c_ll_send(i2c, payload[i]))
+ goto i2c_stop_point;
+ }
+ result = 0;
+i2c_stop_point:
+ pal_i2c_ll_stop(i2c);
+ xSemaphoreGive(i2c->lock);
+ return result;
+}
+
+int pal_i2c_write_payload(pal_i2c_t *i2c, uint8_t addr, uint8_t *payload, size_t len) {
+ int result = -1;
+ xSemaphoreTake(i2c->lock, portMAX_DELAY);
+ if (!pal_i2c_ll_start(i2c, REQ_WRITE, addr << 1, len))
+ goto i2c_stop_point;
+ for (int i = 0; i < len; i++) {
+ if (!pal_i2c_ll_send(i2c, payload[i]))
+ goto i2c_stop_point;
+ }
+ result = 0;
+i2c_stop_point:
+ pal_i2c_ll_stop(i2c);
+ xSemaphoreGive(i2c->lock);
+ return result;
+}
+
+int pal_i2c_read_reg(pal_i2c_t *i2c, uint8_t addr, uint8_t reg, uint8_t *val) {
+ int result = -1;
+ xSemaphoreTake(i2c->lock, portMAX_DELAY);
+ if (!pal_i2c_ll_start(i2c, REQ_WRITE, addr << 1, 1))
+ goto i2c_stop_point;
+ if (!pal_i2c_ll_send(i2c, reg))
+ goto i2c_stop_point;
+ if (!pal_i2c_ll_start(i2c, REQ_RESTART_READ, addr << 1, 1))
+ goto i2c_stop_point;
+ if (!pal_i2c_ll_recv(i2c, val))
+ goto i2c_stop_point;
+ result = 0;
+i2c_stop_point:
+ pal_i2c_ll_stop(i2c);
+ xSemaphoreGive(i2c->lock);
+ return result;
+}
+
+int pal_i2c_read_payload(pal_i2c_t *i2c, uint8_t addr, uint8_t *tx_payload, size_t tx_len, uint8_t *rx_payload, size_t rx_len) {
+ int result = -1;
+ xSemaphoreTake(i2c->lock, portMAX_DELAY);
+ if (!pal_i2c_ll_start(i2c, REQ_WRITE, addr << 1, tx_len))
+ goto i2c_stop_point;
+ for (int i = 0; i < tx_len; i++) {
+ if (!pal_i2c_ll_send(i2c, tx_payload[i]))
+ goto i2c_stop_point;
+ }
+ if (!pal_i2c_ll_start(i2c, REQ_RESTART_READ, addr << 1, rx_len))
+ goto i2c_stop_point;
+ for (int i = 0; i < rx_len; i++) {
+ if (!pal_i2c_ll_recv(i2c, &rx_payload[i]))
+ goto i2c_stop_point;
+ }
+ result = 0;
+i2c_stop_point:
+ pal_i2c_ll_stop(i2c);
+ xSemaphoreGive(i2c->lock);
+ return result;
+}
+
+int pal_i2c_read_byte(pal_i2c_t *i2c, uint8_t addr, uint8_t *val) {
+ int result = -1;
+ xSemaphoreTake(i2c->lock, portMAX_DELAY);
+ if (!pal_i2c_ll_start(i2c, REQ_READ, addr << 1, 1))
+ goto i2c_stop_point;
+ if (!pal_i2c_ll_recv(i2c, val))
+ goto i2c_stop_point;
+ result = 0;
+i2c_stop_point:
+ pal_i2c_ll_stop(i2c);
+ xSemaphoreGive(i2c->lock);
+ return result;
+}
+
+bool pal_i2c_ping(pal_i2c_t *i2c, uint8_t addr) {
+ bool result = true;
+ I2C_TypeDef* port = i2c->port;
+ xSemaphoreTake(i2c->lock, portMAX_DELAY);
+
+ // Switch to GPIO emulated I2C
+ HAL_GPIO_WritePin(I2C1_SDA, 1);
+ HAL_GPIO_WritePin(I2C1_SCL, 1);
+
+ LL_GPIO_InitTypeDef GPIO_InitStruct = {0};
+ GPIO_InitStruct.Pin = LL_GPIO_PIN_6|LL_GPIO_PIN_7;
+ GPIO_InitStruct.Mode = LL_GPIO_MODE_OUTPUT;
+ GPIO_InitStruct.Speed = LL_GPIO_SPEED_FREQ_LOW;
+ GPIO_InitStruct.OutputType = LL_GPIO_OUTPUT_OPENDRAIN;
+ GPIO_InitStruct.Pull = LL_GPIO_PULL_NO;
+ GPIO_InitStruct.Alternate = LL_GPIO_AF_4;
+ LL_GPIO_Init(GPIOB, &GPIO_InitStruct);
+
+ // Start Condition
+ sleep_us(10);
+ HAL_GPIO_WritePin(I2C1_SDA, 0);
+ sleep_us(5);
+ HAL_GPIO_WritePin(I2C1_SCL, 0);
+ sleep_us(10);
+
+ // Send 7-bit address
+ uint8_t dat = addr << 1;
+ for (int i = 0; i < 8; i++) {
+ HAL_GPIO_WritePin(I2C1_SDA, !!(dat & 0x80));
+ dat <<= 1;
+ sleep_us(5);
+ HAL_GPIO_WritePin(I2C1_SCL, 1);
+ sleep_us(10);
+ HAL_GPIO_WritePin(I2C1_SCL, 0);
+ sleep_us(5);
+ }
+ HAL_GPIO_WritePin(I2C1_SDA, 1);
+ sleep_us(5);
+ HAL_GPIO_WritePin(I2C1_SCL, 1);
+ sleep_us(10);
+ int ack = HAL_GPIO_ReadPin(I2C1_SDA); // 0 - ack, 1 - nack
+ HAL_GPIO_WritePin(I2C1_SCL, 0);
+
+ // Stop condition
+ sleep_us(10);
+ HAL_GPIO_WritePin(I2C1_SDA, 0);
+ sleep_us(5);
+ HAL_GPIO_WritePin(I2C1_SCL, 1);
+ sleep_us(5);
+ HAL_GPIO_WritePin(I2C1_SDA, 1);
+
+ // Back to hardware I2C
+ GPIO_InitStruct.Pin = LL_GPIO_PIN_6|LL_GPIO_PIN_7;
+ GPIO_InitStruct.Mode = LL_GPIO_MODE_ALTERNATE;
+ GPIO_InitStruct.Speed = LL_GPIO_SPEED_FREQ_LOW;
+ GPIO_InitStruct.OutputType = LL_GPIO_OUTPUT_OPENDRAIN;
+ GPIO_InitStruct.Pull = LL_GPIO_PULL_NO;
+ GPIO_InitStruct.Alternate = LL_GPIO_AF_4;
+ LL_GPIO_Init(GPIOB, &GPIO_InitStruct);
+
+ xSemaphoreGive(i2c->lock);
+ return !ack;
+}
diff --git a/fw/User/pal_i2c.h b/fw/User/pal_i2c.h
new file mode 100644
index 0000000..7e84b45
--- /dev/null
+++ b/fw/User/pal_i2c.h
@@ -0,0 +1,52 @@
+//
+// Grimoire
+// Copyright 2025 Wenting Zhang
+//
+// 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.
+//
+#pragma once
+
+// Opaque I2C handler
+typedef struct pal_i2c_t pal_i2c_t;
+
+extern pal_i2c_t pi2c1;
+
+void pal_i2c_init(void);
+int pal_i2c_write_byte(pal_i2c_t *i2c, uint8_t addr, uint8_t val);
+int pal_i2c_write_reg(pal_i2c_t *i2c, uint8_t addr, uint8_t reg, uint8_t val);
+int pal_i2c_write_longreg(pal_i2c_t *i2c, uint8_t addr, uint8_t reg, uint8_t *payload, size_t len);
+int pal_i2c_write_payload(pal_i2c_t *i2c, uint8_t addr, uint8_t *payload, size_t len);
+int pal_i2c_read_reg(pal_i2c_t *i2c, uint8_t addr, uint8_t reg, uint8_t *val);
+int pal_i2c_read_payload(pal_i2c_t *i2c, uint8_t addr, uint8_t *tx_payload, size_t tx_len, uint8_t *rx_payload, size_t rx_len);
+int pal_i2c_read_byte(pal_i2c_t *i2c, uint8_t addr, uint8_t *val);
+bool pal_i2c_ping(pal_i2c_t *i2c, uint8_t addr);
+
+// LL functions:
+#define REQ_NONE LL_I2C_GENERATE_NOSTARTSTOP
+#define REQ_WRITE LL_I2C_GENERATE_START_WRITE
+#define REQ_READ LL_I2C_GENERATE_START_READ
+#define REQ_RESTART_READ LL_I2C_GENERATE_RESTART_7BIT_READ
+#define REQ_RELOAD LL_I2C_MODE_RELOAD
+
+bool pal_i2c_ll_start(pal_i2c_t *i2c, uint32_t request, uint8_t slave_addr, uint8_t transfer_size);
+bool pal_i2c_ll_send(pal_i2c_t *i2c, uint8_t val);
+bool pal_i2c_ll_recv(pal_i2c_t *i2c, uint8_t *val);
+void pal_i2c_ll_stop(pal_i2c_t *i2c);
+void pal_i2c_ll_lock(pal_i2c_t *i2c);
+void pal_i2c_ll_unlock(pal_i2c_t *i2c);
diff --git a/fw/User/platform.h b/fw/User/platform.h
new file mode 100644
index 0000000..6e5794f
--- /dev/null
+++ b/fw/User/platform.h
@@ -0,0 +1,41 @@
+//
+// Grimoire
+// Copyright 2025 Wenting Zhang
+//
+// 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.
+//
+#pragma once
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include "stm32h7xx_hal.h"
+#include "stm32h7xx_ll_cortex.h"
+#include "stm32h7xx_ll_i2c.h"
+#include "stm32h7xx_ll_gpio.h"
+#include "FreeRTOS.h"
+#include "semphr.h"
+#include "task.h"
+#include "queue.h"
+#include "stream_buffer.h"
diff --git a/fw/User/power.c b/fw/User/power.c
new file mode 100644
index 0000000..818f138
--- /dev/null
+++ b/fw/User/power.c
@@ -0,0 +1,108 @@
+//
+// Grimoire
+// Copyright 2025 Wenting Zhang
+//
+// 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.
+//
+#include "platform.h"
+#include "board.h"
+#include "app.h"
+
+void power_on(void) {
+
+}
+
+void power_off(void) {
+
+}
+
+void power_on_epd(void) {
+ gpio_put(VCOM_MEN, 1); // Disable
+ gpio_put(VCOM_EN, 1); // Disable
+ HAL_DAC_Start(&hdac1, DAC_CHANNEL_1);
+ gpio_put(EPD_PWREN, 1);
+ sleep_ms(100);
+ gpio_put(EPD_POSEN, 1);
+ HAL_DAC_Start(&hdac1, DAC_CHANNEL_2);
+ sleep_ms(10);
+ gpio_put(VCOM_EN, 0); // Enable
+}
+
+void power_off_epd(void) {
+ gpio_put(VCOM_EN, 1); // Disable
+ sleep_ms(10);
+ gpio_put(EPD_POSEN, 0);
+ HAL_DAC_Stop(&hdac1, DAC_CHANNEL_2);
+ sleep_ms(10);
+ gpio_put(EPD_PWREN, 0);
+ HAL_DAC_Stop(&hdac1, DAC_CHANNEL_1);
+}
+
+void power_set_vcom(float vcom) {
+ // DAC 000 = -2.667V
+ // DAC 19A = -2.404V
+ // DAC E80 = -0.226V
+ // DAC FF0 = -0.011V
+ // V = 0.000651 * set - 2.667
+ // set = (V + 2.676) / 0.000651
+ float setpt = (vcom + 2.676f) / 0.00066f;
+ int setpt_i = (int)roundf(setpt);
+ if (setpt_i < 0)
+ setpt_i = 0;
+ if (setpt_i > 4095)
+ setpt_i = 4095;
+
+ HAL_DAC_SetValue(&hdac1, DAC_CHANNEL_1, DAC_ALIGN_12B_R, setpt_i);
+}
+
+void power_set_vgh(float vgh) {
+ // DAC 000 26.87V
+ // DAC 0F2 26.19V
+ // DAC 77E 20.95V
+ // DAC FF0 12.26V
+ // Valid range: 22V - 27V
+ // set = (26.945 - V) / 0.03126
+ float setpt = (26.945f - vgh) / 0.003126f;
+ int setpt_i = (int)roundf(setpt);
+ if (setpt_i < 0)
+ setpt_i = 0;
+ if (setpt_i > 4095)
+ setpt_i = 4095;
+
+ HAL_DAC_SetValue(&hdac1, DAC_CHANNEL_2, DAC_ALIGN_12B_R, setpt_i);
+}
+
+void power_on_fl(void) {
+ HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_3);
+}
+
+void power_off_fl(void) {
+ HAL_TIM_PWM_Stop(&htim1, TIM_CHANNEL_3);
+}
+
+void power_set_fl_brightness(uint8_t val) {
+ TIM1->CCR3 = 255 - val;
+}
+
+portTASK_FUNCTION(power_monitor_task, pvParameters) {
+ power_on_epd();
+ while (1) {
+ vTaskDelay(pdMS_TO_TICKS(100)); // Nothing for now
+ }
+}
diff --git a/fw/User/power.h b/fw/User/power.h
new file mode 100644
index 0000000..e4b9b7a
--- /dev/null
+++ b/fw/User/power.h
@@ -0,0 +1,34 @@
+//
+// Grimoire
+// Copyright 2025 Wenting Zhang
+//
+// 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.
+//
+#pragma once
+
+void power_off(void);
+void power_on(void);
+void power_on_epd(void);
+void power_off_epd(void);
+void power_set_vcom(float vcom);
+void power_set_vgh(float vgh);
+void power_on_fl(void);
+void power_off_fl(void);
+void power_set_fl_brightness(uint8_t val);
+portTASK_FUNCTION(power_monitor_task, pvParameters);
diff --git a/fw/ptn3460.c b/fw/User/ptn3460.c
similarity index 50%
rename from fw/ptn3460.c
rename to fw/User/ptn3460.c
index c1070db..74f497c 100644
--- a/fw/ptn3460.c
+++ b/fw/User/ptn3460.c
@@ -1,5 +1,6 @@
//
-// Copyright 2022 Wenting Zhang
+// Grimoire
+// Copyright 2025 Wenting Zhang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -19,79 +20,60 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
-#include
-#include
-#include "pico/stdlib.h"
-#include "hardware/i2c.h"
-#include "config.h"
-#include "ptn3460.h"
-#include "utils.h"
-#include "edid.h"
+#include "platform.h"
+#include "board.h"
+#include "app.h"
-#ifdef INPUT_PTN3460
-
-#define PTN3460_I2C_ADDRESS (0x60)
-
-void ptn3460_select_edid_emulation(uint8_t id) {
- uint8_t buf[2];
- int result;
- buf[0] = (uint8_t)0x84;
- buf[1] = (uint8_t)0x01 | (id << 1);
- result = i2c_write_blocking(PTN3460_I2C, PTN3460_I2C_ADDRESS,
- buf, 2, false);
- if (result != 2) {
- fatal("Failed writing data to PTN3460\n");
+static void ptn3460_write(uint8_t reg, uint8_t val) {
+ int result = pal_i2c_write_reg(PTN3460_I2C, PTN3460_I2C_ADDR, reg, val);
+ if (result != 0) {
+ syslog_printf("Failed writing data to PTN3460\n");
}
}
+static uint8_t ptn3460_read(uint8_t reg) {
+ uint8_t val;
+ int result = pal_i2c_read_reg(PTN3460_I2C, PTN3460_I2C_ADDR, reg, &val);
+ if (result != 0) {
+ syslog_printf("Failed reading data from PTN3460\n");
+ }
+ return val;
+}
+
+static void ptn3460_select_edid_emulation(uint8_t id) {
+ ptn3460_write(0x84, 0x01 | (id << 1));
+}
+
void ptn3460_load_edid(uint8_t *edid) {
- int result;
-
- result = i2c_write_blocking(PTN3460_I2C, PTN3460_I2C_ADDRESS,
- edid, 129, false);
- if (result != 129) {
- fatal("Failed writing data to PTN3460\n");
+ int result = pal_i2c_write_longreg(PTN3460_I2C, PTN3460_I2C_ADDR,
+ 0x00, edid, 128);
+ if (result != 0) {
+ syslog_printf("Failed writing data to PTN3460\n");
}
}
-void ptn3460_write(uint8_t reg, uint8_t val) {
- uint8_t buf[2];
- int result;
- buf[0] = reg;
- buf[1] = val;
- result = i2c_write_blocking(PTN3460_I2C, PTN3460_I2C_ADDRESS,
- buf, 2, false);
- if (result != 2) {
- fatal("Failed writing data to PTN3460\n");
- }
+void ptn3460_early_init(void) {
+ gpio_put(DP_PDN, 1);
}
void ptn3460_init(void) {
- gpio_init(PTN3460_HPD_PIN);
- gpio_set_dir(PTN3460_HPD_PIN, GPIO_IN);
- gpio_pull_down(PTN3460_HPD_PIN);
- gpio_init(PTN3460_PDN_PIN);
- gpio_put(PTN3460_PDN_PIN, 1);
- gpio_set_dir(PTN3460_PDN_PIN, GPIO_OUT);
- gpio_init(PTN3460_VALID_PIN);
- gpio_set_dir(PTN3460_VALID_PIN, GPIO_IN);
- gpio_pull_down(PTN3460_VALID_PIN);
- sleep_ms(50);
// wait for HPD to become high
int ticks = 0;
- while (gpio_get(PTN3460_HPD_PIN) != true) {
+ while (gpio_get(DP_HPD) != true) {
ticks ++;
if (ticks > 500) {
- fatal("PTN3460 boot timeout\n");
+ syslog_printf("PTN3460 boot timeout\n");
}
sleep_ms(1);
}
- printf("PTN3460 up after %d ms\n", ticks);
+ syslog_printf("PTN3460 up after %d ms\n", ticks);
// Enable EDID emulation
ptn3460_select_edid_emulation(0);
ptn3460_load_edid(edid_get_raw());
ptn3460_write(0x81, 0x29); // 18bpp, clock on odd bus, dual channel
+ uint8_t rdval = ptn3460_read(0x81);
+ syslog_printf("PTN3460 readback value %02x (expected %02x)\n", rdval, 0x29);
}
void ptn3460_set_aux_polarity(int reverse) {
@@ -100,9 +82,3 @@ void ptn3460_set_aux_polarity(int reverse) {
else
ptn3460_write(0x80, 0x00); // Disable AUX reverse
}
-
-bool ptn3460_is_valid(void) {
- return gpio_get(PTN3460_VALID_PIN);
-}
-
-#endif
diff --git a/fw/ptn3460.h b/fw/User/ptn3460.h
similarity index 91%
rename from fw/ptn3460.h
rename to fw/User/ptn3460.h
index c7229dd..7cc7eb4 100644
--- a/fw/ptn3460.h
+++ b/fw/User/ptn3460.h
@@ -1,5 +1,6 @@
//
-// Copyright 2022 Wenting Zhang
+// Grimoire
+// Copyright 2025 Wenting Zhang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -21,8 +22,6 @@
//
#pragma once
-#ifdef INPUT_PTN3460
+void ptn3460_early_init(void);
void ptn3460_init(void);
void ptn3460_set_aux_polarity(int reverse);
-bool ptn3460_is_valid(void);
-#endif
\ No newline at end of file
diff --git a/fw/User/shell/linenoise.c b/fw/User/shell/linenoise.c
new file mode 100644
index 0000000..547051b
--- /dev/null
+++ b/fw/User/shell/linenoise.c
@@ -0,0 +1,471 @@
+/* linenoise.c -- guerrilla line editing library against the idea that a
+ * line editing lib needs to be 20,000 lines of C code.
+ *
+ * You can find the latest source code at:
+ *
+ * http://github.com/antirez/linenoise
+ *
+ * Does a number of crazy assumptions that happen to be true in 99.9999% of
+ * the 2010 UNIX computers around.
+ *
+ * Copyright (c) 2010, Salvatore Sanfilippo
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * * Neither the name of Redis nor the names of its contributors may be used
+ * to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * References:
+ * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
+ * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
+ *
+ * Todo list:
+ * - Switch to gets() if $TERM is something we can't support.
+ * - Filter bogus Ctrl+ combinations.
+ * - Win32 support
+ *
+ * Bloat:
+ * - Completion?
+ * - History search like Ctrl+r in readline?
+ *
+ * List of escape sequences used by this program, we do everything just
+ * with three sequences. In order to be so cheap we may have some
+ * flickering effect with some slow terminal, but the lesser sequences
+ * the more compatible.
+ *
+ * CHA (Cursor Horizontal Absolute)
+ * Sequence: ESC [ n G
+ * Effect: moves cursor to column n
+ *
+ * EL (Erase Line)
+ * Sequence: ESC [ n K
+ * Effect: if n is 0 or missing, clear from cursor to end of line
+ * Effect: if n is 1, clear from beginning of line to cursor
+ * Effect: if n is 2, clear entire line
+ *
+ * CUF (CUrsor Forward)
+ * Sequence: ESC [ n C
+ * Effect: moves cursor forward of n chars
+ *
+ * [eLua] code adapted to eLua by bogdanm
+ *
+ */
+
+/*
+ * This code has been modified by Analog Devices, Inc.
+ */
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "shell.h"
+#include "shell_string.h"
+#include "term.h"
+#include "linenoise.h"
+
+#define LINENOISE_NON_BLOCK_RETURN ( -3 )
+#define LINENOISE_CTRL_C ( -2 )
+#define LINENOISE_CTRL_Z ( -1 )
+#define LINENOISE_DONT_PUSH_EMPTY 0
+#define LINENOISE_PUSH_EMPTY 1
+
+/* Make sure a default context always exists */
+shell_context_t *defaultCxt = NULL;
+
+static int linenoise_internal_addhistory( shell_context_t *ctx, const char *line, int force_empty );
+
+void linenoise_cleanup( shell_context_t *ctx )
+{
+ int j;
+
+ if( ctx->histories )
+ {
+ for( j = 0; j < ctx->num_histories; j++ )
+ SHELL_FREE( ctx->histories[ j ] );
+ SHELL_FREE( ctx->histories );
+ ctx->histories = NULL;
+ }
+
+ ctx->num_histories = 0;
+}
+
+#define MAX_SEQ_LEN 32
+static void refreshLine(shell_context_t *ctx, const char *prompt, char *buf, size_t len, size_t pos, size_t cols) {
+ char seq[MAX_SEQ_LEN];
+ size_t plen = strlen(prompt);
+
+ while((plen+pos) >= cols) {
+ buf++;
+ len--;
+ pos--;
+ }
+ while (plen+len > cols) {
+ len--;
+ }
+
+ /* Hide the text if required */
+ if (ctx->hidden) {
+ buf = SHELL_MALLOC(len + 1);
+ memset(buf, '*', len);
+ buf[len] = '\0';
+ }
+
+ /* Cursor to left edge */
+ snprintf(seq,MAX_SEQ_LEN,"\r");
+ term_putstr( &ctx->t, seq, strlen( seq ) );
+ /* Write the prompt and the current buffer content */
+ term_putstr( &ctx->t, prompt, strlen( prompt ) );
+ term_putstr( &ctx->t, buf, len );
+ /* Erase to right */
+ snprintf(seq,MAX_SEQ_LEN,"\x1b[0K");
+ term_putstr( &ctx->t, seq, strlen( seq ) );
+ /* Move cursor to original position. */
+ snprintf(seq,MAX_SEQ_LEN,"\r\x1b[%dC", (int)(pos+plen));
+ term_putstr( &ctx->t, seq, strlen( seq ) );
+
+ if (ctx->hidden) {
+ SHELL_FREE(buf);
+ }
+}
+
+static int linenoisePrompt(shell_context_t *ctx, char *buf, size_t buflen, const char *prompt) {
+
+ /* Blocking mode always starts a new line */
+ if (ctx->blocking == SHELL_MODE_BLOCKING) {
+ ctx->new_line = 1;
+ }
+
+ /* Start a new line if necessary */
+ if (ctx->new_line) {
+
+ ctx->plen = strlen(prompt);
+ ctx->pos = 0;
+ ctx->len = 0;
+ ctx->cols = SHELL_COLUMNS;
+ ctx->history_index = 0;
+
+ buf[0] = '\0';
+ buflen--; /* Make sure there is always space for the nulterm */
+
+ /* The latest history entry is always our current buffer, that
+ * initially is just an empty string. */
+ linenoise_internal_addhistory( ctx, "", LINENOISE_PUSH_EMPTY );
+
+ term_putstr( &ctx->t, prompt, ctx->plen );
+
+ ctx->new_line = false;
+ }
+
+ while(1) {
+
+ int c;
+
+ if (ctx->blocking == SHELL_MODE_BLOCKING) {
+ c = term_getch( &ctx->t, TERM_INPUT_WAIT );
+ } else {
+ c = term_getch( &ctx->t, TERM_INPUT_DONT_WAIT );
+ if (c == -1) {
+ return(LINENOISE_NON_BLOCK_RETURN);
+ }
+ }
+
+ switch(c)
+ {
+ case KC_ENTER:
+ case KC_CTRL_C:
+ case KC_CTRL_Z:
+ if (ctx->num_histories > 0)
+ {
+ ctx->num_histories--;
+ SHELL_FREE( ctx->histories[ctx->num_histories] );
+ }
+ ctx->new_line = true;
+ if( c == KC_CTRL_C )
+ return LINENOISE_CTRL_C;
+ else if( c == KC_CTRL_Z )
+ return LINENOISE_CTRL_Z;
+ return ctx->len;
+
+ case KC_BACKSPACE:
+ if (ctx->pos > 0 && ctx->len > 0)
+ {
+ memmove(buf+ctx->pos-1,buf+ctx->pos,ctx->len-ctx->pos);
+ ctx->pos--;
+ ctx->len--;
+ buf[ctx->len] = '\0';
+ refreshLine(ctx, prompt,buf,ctx->len,ctx->pos,ctx->cols);
+ }
+ break;
+
+ case KC_CTRL_T:
+ /* ctrl-t */
+ if (ctx->len > 1 && ctx->pos > 0 && ctx->pos <= ctx->len)
+ {
+ if (ctx->pos == ctx->len)
+ {
+ ctx->pos--;
+ }
+ int aux = buf[ctx->pos-1];
+ buf[ctx->pos-1] = buf[ctx->pos];
+ buf[ctx->pos] = aux;
+ ctx->pos++;
+ refreshLine(ctx, prompt,buf,ctx->len,ctx->pos,ctx->cols);
+ }
+ break;
+
+ case KC_LEFT:
+ /* left arrow */
+ if (ctx->pos > 0)
+ {
+ ctx->pos--;
+ refreshLine(ctx, prompt,buf,ctx->len,ctx->pos,ctx->cols);
+ }
+ break;
+
+ case KC_RIGHT:
+ /* right arrow */
+ if (ctx->pos != ctx->len)
+ {
+ ctx->pos++;
+ refreshLine(ctx, prompt,buf,ctx->len,ctx->pos,ctx->cols);
+ }
+ break;
+
+ case KC_UP:
+ case KC_DOWN:
+ /* up and down arrow: history */
+ if (ctx->num_histories > 1)
+ {
+ /* Update the current history entry before to
+ * overwrite it with tne next one. */
+ SHELL_FREE(ctx->histories[ctx->num_histories-1-ctx->history_index]);
+ ctx->histories[ctx->num_histories-1-ctx->history_index] = SHELL_STRDUP(buf);
+ /* Show the new entry */
+ ctx->history_index += (c == KC_UP) ? 1 : -1;
+ if (ctx->history_index < 0)
+ {
+ ctx->history_index = 0;
+ break;
+ } else if (ctx->history_index >= ctx->num_histories)
+ {
+ ctx->history_index = ctx->num_histories-1;
+ break;
+ }
+ strncpy(buf,ctx->histories[ctx->num_histories-1-ctx->history_index],buflen);
+ buf[buflen] = '\0';
+ ctx->len = ctx->pos = strlen(buf);
+ refreshLine(ctx, prompt,buf,ctx->len,ctx->pos,ctx->cols);
+ }
+ break;
+
+ case KC_DEL:
+ /* delete */
+ if (ctx->len > 0 && ctx->pos < ctx->len)
+ {
+ memmove(buf+ctx->pos,buf+ctx->pos+1,ctx->len-ctx->pos-1);
+ ctx->len--;
+ buf[ctx->len] = '\0';
+ refreshLine(ctx, prompt,buf,ctx->len,ctx->pos,ctx->cols);
+ }
+ break;
+
+ case KC_HOME: /* Ctrl+a, go to the start of the line */
+ ctx->pos = 0;
+ refreshLine(ctx, prompt,buf,ctx->len,ctx->pos,ctx->cols);
+ break;
+
+ case KC_END: /* ctrl+e, go to the end of the line */
+ ctx->pos = ctx->len;
+ refreshLine(ctx, prompt,buf,ctx->len,ctx->pos,ctx->cols);
+ break;
+
+ case KC_CTRL_U: /* Ctrl+u, delete the whole line. */
+ buf[0] = '\0';
+ ctx->pos = ctx->len = 0;
+ refreshLine(ctx, prompt,buf,ctx->len,ctx->pos,ctx->cols);
+ break;
+
+ case KC_CTRL_K: /* Ctrl+k, delete from current to end of line. */
+ buf[ctx->pos] = '\0';
+ ctx->len = ctx->pos;
+ refreshLine(ctx, prompt,buf,ctx->len,ctx->pos,ctx->cols);
+ break;
+
+ case KC_UNKNOWN:
+ break;
+
+ default:
+ if( isprint( c ) && ctx->len < buflen )
+ {
+ if(ctx->len == ctx->pos)
+ {
+ buf[ctx->pos] = c;
+ ctx->pos++;
+ ctx->len++;
+ buf[ctx->len] = '\0';
+ if (ctx->plen+ctx->len < ctx->cols)
+ {
+ /* Avoid a full update of the line in the
+ * trivial case. */
+ if (ctx->hidden) {
+ term_putch( &ctx->t, '*' );
+ } else {
+ term_putch( &ctx->t, c );
+ }
+ }
+ else
+ {
+ refreshLine(ctx, prompt,buf,ctx->len,ctx->pos,ctx->cols);
+ }
+ }
+ else
+ {
+ memmove(buf+ctx->pos+1,buf+ctx->pos,ctx->len-ctx->pos);
+ buf[ctx->pos] = c;
+ ctx->len++;
+ ctx->pos++;
+ buf[ctx->len] = '\0';
+ refreshLine(ctx, prompt,buf,ctx->len,ctx->pos,ctx->cols);
+ }
+ }
+ break;
+ }
+ }
+
+ //return ctx->len;
+}
+
+int linenoise_getline( shell_context_t *ctx, char* buffer, int maxinput, const char* prompt )
+{
+ int count;
+
+ if (ctx == NULL) {
+ ctx = defaultCxt;
+ }
+
+ while( 1 )
+ {
+ count = linenoisePrompt( ctx, buffer, maxinput, prompt );
+ if (count == LINENOISE_NON_BLOCK_RETURN) {
+ return(LINENOISE_CONTINUE);
+ }
+ if( count == LINENOISE_CTRL_Z )
+ {
+ return LINENOISE_EOF;
+ }
+ else if (count == LINENOISE_CTRL_C)
+ {
+ term_putch(&ctx->t, '\n');
+ }
+ else
+ {
+ term_putch(&ctx->t, '\n');
+ if( count > 0 && buffer[ count ] != '\0' )
+ buffer[ count ] = '\0';
+ return count;
+ }
+ }
+}
+
+static int linenoise_internal_addhistory( shell_context_t *ctx, const char *line, int force_empty )
+{
+ char *linecopy;
+ const char *p;
+
+ if( ctx->max_histories == 0 )
+ return 0;
+
+ if( ctx->histories == NULL )
+ {
+ if( ( ctx->histories = SHELL_MALLOC( sizeof( char* ) * ctx->max_histories ) ) == NULL )
+ {
+ fprintf( stderr, "out of memory in linenoise while trying to allocate history buffer.\n" );
+ return 0;
+ }
+ memset( ctx->histories, 0, ( sizeof( char* ) * ctx->max_histories ) );
+ }
+
+ while( 1 )
+ {
+ if( ( p = strchr( line, '\n' ) ) == NULL )
+ p = line + strlen( line );
+ if( p > line || force_empty == LINENOISE_PUSH_EMPTY )
+ {
+ if( ( linecopy = SHELL_STRNDUP( line, p - line ) ) == NULL )
+ {
+ fprintf( stderr, "out of memory in linenoise while trying to add a line to history.\n" );
+ return 0;
+ }
+ if( ctx->num_histories == ctx->max_histories )
+ {
+ SHELL_FREE( ctx->histories[ 0 ] );
+ memmove( ctx->histories, ctx->histories + 1, sizeof( char* ) * ( ctx->max_histories - 1 ) );
+ ctx->num_histories--;
+ }
+ ctx->histories[ctx->num_histories] = linecopy;
+ ctx->num_histories++;
+ }
+ if( *p == 0 )
+ break;
+ line = p + 1;
+ if( *line == 0 )
+ break;
+ }
+
+ return 1;
+}
+
+int linenoise_addhistory( shell_context_t *ctx, const char *line )
+{
+ if (ctx == NULL) {
+ ctx = defaultCxt;
+ }
+
+ return linenoise_internal_addhistory( ctx, line, LINENOISE_DONT_PUSH_EMPTY );
+}
+
+int linenoise_init(shell_context_t *ctx)
+{
+ /* Initialize the default context */
+ if (defaultCxt == NULL) {
+ defaultCxt = SHELL_MALLOC(sizeof(*defaultCxt));
+ memset(defaultCxt, 0, sizeof(*defaultCxt));
+ defaultCxt->max_histories = SHELL_MAX_HISTORIES;
+ defaultCxt->new_line = 1;
+ if (ctx) {
+ defaultCxt->blocking = ctx->blocking;
+ }
+ }
+
+ /* Initialize the given context */
+ if (ctx) {
+ ctx->max_histories = SHELL_MAX_HISTORIES;
+ ctx->new_line = 1;
+ }
+
+ return 1;
+}
diff --git a/fw/User/shell/linenoise.h b/fw/User/shell/linenoise.h
new file mode 100644
index 0000000..d6022be
--- /dev/null
+++ b/fw/User/shell/linenoise.h
@@ -0,0 +1,52 @@
+/* linenoise.h -- guerrilla line editing library against the idea that a
+ * line editing lib needs to be 20,000 lines of C code.
+ *
+ * See linenoise.c for more information.
+ *
+ * Copyright (c) 2010, Salvatore Sanfilippo
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * * Neither the name of Redis nor the names of its contributors may be used
+ * to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __LINENOISE_H
+#define __LINENOISE_H
+
+#include "shell.h"
+
+// linenoise_getline() non-length return codes
+#define LINENOISE_CONTINUE ( -2 )
+#define LINENOISE_EOF ( -1 )
+
+// linenoise_addhistory() Error codes
+#define LINENOISE_HISTORY_NOT_ENABLED ( -2 )
+#define LINENOISE_HISTORY_EMPTY ( -3 )
+
+int linenoise_getline( shell_context_t *ctx, char* buffer, int maxinput, const char* prompt );
+int linenoise_addhistory( shell_context_t *ctx, const char *line );
+void linenoise_cleanup( shell_context_t *ctx );
+int linenoise_init(shell_context_t *ctx);
+
+#endif /* __LINENOISE_H */
diff --git a/fw/User/shell/shell.c b/fw/User/shell/shell.c
new file mode 100644
index 0000000..de8b87c
--- /dev/null
+++ b/fw/User/shell/shell.c
@@ -0,0 +1,511 @@
+//
+// Grimoire
+// Copyright 2025 Wenting Zhang
+//
+// Original copyright information:
+// Copyright (c) 2022 - Analog Devices Inc. All Rights Reserved.
+//
+// This file is licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License. You may
+// obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations
+// under the License.
+//
+
+#include
+#include
+#include
+#include
+#include
+
+#include "shell.h"
+#include "shell_string.h"
+#include "shell_platform.h"
+#include "shell_printf.h"
+#include "linenoise.h"
+#include "term.h"
+#include "version.h"
+
+#ifdef printf
+#undef printf
+#endif
+
+#define printf(...) shell_printf(ctx, __VA_ARGS__)
+
+// Shell alternate ' ' char
+#define SHELL_ALT_SPACE '\x07'
+
+// Helper macros
+#define SHELL_FUNC( func ) extern void func( shell_context_t *ctx, int argc, char **argv )
+#define SHELL_HELP( cmd ) \
+ extern const char shell_help_##cmd[]; \
+ extern const char shell_help_summary_##cmd[]
+#define SHELL_INFO( cmd ) { #cmd, shell_help_summary_##cmd, shell_help_##cmd }
+
+// Command / handler pair structure
+typedef struct
+{
+ const char* cmd;
+ p_shell_handler handler_func;
+} SHELL_COMMAND;
+
+// Help data
+typedef struct
+{
+ const char *cmd;
+ const char *help_summary;
+ const char *help_full;
+} SHELL_HELP_DATA;
+
+// Add additional shell commands here
+SHELL_FUNC( shell_help );
+SHELL_FUNC( shell_ver );
+SHELL_FUNC( shell_syslog );
+SHELL_FUNC( shell_test );
+SHELL_FUNC( shell_i2c_probe );
+SHELL_FUNC( shell_fl );
+SHELL_FUNC( shell_recv );
+SHELL_FUNC( shell_send );
+SHELL_FUNC( shell_df );
+SHELL_FUNC( shell_dump );
+SHELL_FUNC( shell_fdump );
+SHELL_FUNC( shell_setvolt );
+SHELL_FUNC( shell_setcfg );
+
+SHELL_HELP( help );
+SHELL_HELP( ver );
+SHELL_HELP( syslog );
+SHELL_HELP( test );
+SHELL_HELP( i2c_probe );
+SHELL_HELP( fl );
+SHELL_HELP( recv );
+SHELL_HELP( send );
+SHELL_HELP( df );
+SHELL_HELP( dump );
+SHELL_HELP( fdump );
+SHELL_HELP( setvolt );
+SHELL_HELP( setcfg );
+
+//static const SHELL_COMMAND shell_commands[] =
+const SHELL_COMMAND shell_commands[] =
+{
+ { "help", shell_help },
+ { "ver", shell_ver },
+ { "syslog", shell_syslog },
+ { "test", shell_test },
+ { "i2c_probe", shell_i2c_probe },
+ { "fl", shell_fl },
+ { "recv", shell_recv },
+ { "send", shell_send },
+ { "df", shell_df },
+ { "dump", shell_dump },
+ { "fdump", shell_fdump },
+ { "setvolt", shell_setvolt },
+ { "setcfg", shell_setcfg },
+ { "exit", NULL },
+ { NULL, NULL }
+};
+
+static const SHELL_HELP_DATA shell_help_data[] =
+{
+ SHELL_INFO( help ),
+ SHELL_INFO( ver ),
+ SHELL_INFO( syslog ),
+ SHELL_INFO( test ),
+ SHELL_INFO( i2c_probe ),
+ SHELL_INFO( fl ),
+ SHELL_INFO( recv ),
+ SHELL_INFO( send ),
+ SHELL_INFO( df ),
+ SHELL_INFO( dump ),
+ SHELL_INFO( fdump ),
+ SHELL_INFO( setvolt ),
+ SHELL_INFO( setcfg ),
+ { NULL, NULL, NULL }
+};
+
+// ****************************************************************************
+// Built-in help functions
+// ****************************************************************************
+
+static void shell_alphabetize(shell_context_t *ctx)
+{
+ bool bSwaped;
+ bool bSorted;
+ uint16_t u16HelpTableIdx;
+ uint16_t u16HelpTableSize;
+ uint16_t u16HelpTableCurIdx;
+ uint16_t u16IndicesTableIdx;
+ uint16_t u16HelpTablePrevIdx;
+
+ /* Local Inits */
+ u16HelpTableIdx = 1U;
+ bSwaped = false;
+ bSorted = false;
+ u16HelpTableSize = sizeof(shell_help_data)/sizeof(SHELL_HELP_DATA);
+
+ /* Allocate array based on the size of the help table */
+ ctx->uHelpIndicies = SHELL_MALLOC(u16HelpTableSize * sizeof(*ctx->uHelpIndicies));
+
+ if(ctx->uHelpIndicies != NULL)
+ {
+ /* Initialize array */
+ for(u16IndicesTableIdx = 0U; u16IndicesTableIdx < u16HelpTableSize; u16IndicesTableIdx++)
+ {
+ ctx->uHelpIndicies[u16IndicesTableIdx] = u16IndicesTableIdx;
+ }
+
+ /* The last element in the table is intentionally NULL so exclude from alphabetization */
+ u16HelpTableSize--;
+
+ /* Perform alphabetization, sorting the indices in the array */
+ do
+ {
+ /* Find our starting point */
+ u16HelpTableCurIdx = ctx->uHelpIndicies[u16HelpTableIdx];
+ u16HelpTablePrevIdx = ctx->uHelpIndicies[u16HelpTableIdx - 1U];
+
+ if(strcmp(shell_help_data[u16HelpTableCurIdx].cmd, shell_help_data[u16HelpTablePrevIdx].cmd) < 0)
+ {
+ ctx->uHelpIndicies[u16HelpTableIdx] = u16HelpTablePrevIdx;
+ ctx->uHelpIndicies[u16HelpTableIdx - 1U] = u16HelpTableCurIdx;
+ bSwaped = true;
+ }
+
+ u16HelpTableIdx++;
+
+ /* Exit if we are done sorting - otherwise loop back around again */
+ if(u16HelpTableIdx == u16HelpTableSize)
+ {
+ if(bSwaped == false)
+ {
+ bSorted = true;
+ }
+ else
+ {
+ /* Reset parameters */
+ bSwaped = false;
+ u16HelpTableIdx = 1U;
+ }
+ }
+ }while(bSorted == false);
+ }
+}
+
+// 'Help' help data
+const char shell_help_help[] = "[]\n"
+ " [] - the command to get help on.\n"
+ "Without arguments it shows a summary of all the shell commands.\n";
+const char shell_help_summary_help[] = "shell help";
+
+void shell_help( shell_context_t *ctx, int argc, char **argv )
+{
+ const SHELL_HELP_DATA *ph;
+ uint16_t u16CmdIdx;
+ uint16_t u16TableIdx;
+
+ if( argc > 2 )
+ {
+ printf( "Invalid arguments. Type help [] for usage.\n" );
+ return;
+ }
+ ph = shell_help_data;
+ if( argc == 1 )
+ {
+ // List commands and their summary
+ // It is assumed that a command with an empty summary does not
+ // actually exist (helpful for conditional compilation)
+ // Noting that if we could not alphabetize due to constrained memory,
+ // just print the table as-is.
+ u16CmdIdx = 0U;
+ u16TableIdx = (ctx->uHelpIndicies == NULL) ? u16CmdIdx : ctx->uHelpIndicies[u16CmdIdx];
+ printf( "Shell commands:\n" );
+ while( 1 )
+ {
+ if( ph[u16TableIdx].cmd == NULL )
+ break;
+ if( strlen( ph[u16TableIdx].help_summary ) > 0 )
+ printf( " %-10s - %s\n", ph[u16TableIdx].cmd, ph[u16TableIdx].help_summary );
+ u16CmdIdx++;
+ u16TableIdx = (ctx->uHelpIndicies == NULL) ? u16CmdIdx : ctx->uHelpIndicies[u16CmdIdx];
+ }
+ printf( "For more information use 'help '.\n" );
+ }
+ else
+ {
+ while( 1 )
+ {
+ if( ph->cmd == NULL )
+ break;
+ if( !strcmp( ph->cmd, argv[ 1 ] ) && strlen( ph->help_summary ) > 0 )
+ {
+ printf( "%s - %s", ph->cmd, ph->help_summary );
+ printf( "\n");
+ printf( "Usage: %s %s", ph->cmd, ph->help_full );
+ return;
+ }
+ ph ++;
+ }
+ printf( "Unknown command '%s'.\n", argv[ 1 ] );
+ }
+}
+
+// ****************************************************************************
+// Built-in version function
+// ****************************************************************************
+const char shell_help_ver[] = "\n";
+const char shell_help_summary_ver[] = "show version information";
+
+void shell_ver( shell_context_t *ctx, int argc, char **argv )
+{
+ if( argc != 1 )
+ {
+ printf( "Invalid arguments. Type help [] for usage.\n" );
+ return;
+ }
+ printf( SHELL_WELCOMEMSG, STR_VERSION, __DATE__, __TIME__);
+}
+
+// ****************************************************************************
+// Shell functions
+// ****************************************************************************
+
+// 'Not implemented' handler for shell comands
+void shellh_not_implemented_handler( shell_context_t *ctx, int argc, char **argv )
+{
+ printf( SHELL_ERRMSG );
+}
+
+// Executes the given shell command
+// 'interactive_mode' is 1 if invoked directly from the interactive shell,
+// 0 otherwise
+// Returns a pointer to the shell_command that was executed, NULL for error
+const SHELL_COMMAND* shellh_execute_command( shell_context_t *ctx, char* cmd, int interactive_mode )
+{
+ char *p, *temp;
+ const SHELL_COMMAND* pcmd;
+ int i, inside_quotes;
+ char quote_char;
+ int argc;
+ char *argv[ SHELL_MAX_ARGS ];
+
+ if( strlen( cmd ) == 0 )
+ return NULL;
+
+ // Change '\r', '\n' and '\t' chars to ' ' to ease processing
+ p = cmd;
+ while( *p )
+ {
+ if( *p == '\r' || *p == '\n' || *p == '\t' )
+ *p = ' ';
+ p ++;
+ }
+
+ // Transform ' ' characters inside a '' or "" quoted string in
+ // a 'special' char.
+ for( i = 0, inside_quotes = 0, quote_char = '\0'; i < strlen( cmd ); i ++ )
+ if( ( cmd[ i ] == '\'' ) || ( cmd[ i ] == '"' ) )
+ {
+ if( !inside_quotes )
+ {
+ inside_quotes = 1;
+ quote_char = cmd[ i ];
+ }
+ else
+ {
+ if( cmd[ i ] == quote_char )
+ {
+ inside_quotes = 0;
+ quote_char = '\0';
+ }
+ }
+ }
+ else if( ( cmd[ i ] == ' ' ) && inside_quotes )
+ cmd[ i ] = SHELL_ALT_SPACE;
+ if( inside_quotes )
+ {
+ printf( "Invalid quoted string\n" );
+ return NULL;
+ }
+
+ // Transform consecutive sequences of spaces into a single space
+ p = strchr( cmd, ' ' );
+ while( p )
+ {
+ temp = p + 1;
+ while( *temp && *temp == ' ' )
+ memmove( temp, temp + 1, strlen( temp ) );
+ p = strchr( p + 1, ' ' );
+ }
+ if( !strcmp( cmd, " " ) )
+ return NULL;
+
+ // Skip over the trailing space char if it exists
+ p = cmd + strlen(cmd) - 1;
+ if( *p == ' ' )
+ *p = 0;
+
+ // Skip over the initial space char if it exists
+ p = cmd;
+ if( *p == ' ' )
+ p ++;
+
+ // Compute argc/argv
+ for( argc = 0; argc < SHELL_MAX_ARGS; argc ++ )
+ argv[ argc ] = NULL;
+ argc = 0;
+
+ while( ( temp = strchr( p, ' ' ) ) != NULL )
+ {
+ if( argc < SHELL_MAX_ARGS)
+ {
+ *temp = 0;
+ argv[ argc ++ ] = p;
+ p = temp + 1;
+ }
+ else
+ {
+ break;
+ }
+ }
+ if (argc < SHELL_MAX_ARGS)
+ {
+ argv[ argc ++ ] = p;
+ }
+ else
+ {
+ printf( "Error: too many arguments\n" );
+ return NULL;
+ }
+
+ // Additional argument processing happens here
+ for( i = 0; i < argc; i ++ )
+ {
+ p = argv[ i ];
+ // Put back spaces if needed
+ for( inside_quotes = 0; inside_quotes < strlen( argv[ i ] ); inside_quotes ++ )
+ {
+ if( p[ inside_quotes ] == SHELL_ALT_SPACE )
+ argv[ i ][ inside_quotes ] = ' ';
+ }
+ // Remove quotes
+ if( ( p[ 0 ] == '\'' || p [ 0 ] == '"' ) && ( p[ 0 ] == p[ strlen( p ) - 1 ] ) )
+ {
+ argv[ i ] = p + 1;
+ p[ strlen( p ) - 1 ] = '\0';
+ }
+ }
+
+ // Match user command with shell's commands
+ i = 0;
+ while( 1 )
+ {
+ pcmd = shell_commands + i;
+ if( pcmd->cmd == NULL )
+ {
+ printf( SHELL_ERRMSG );
+ break;
+ }
+ if( !strcmp( pcmd->cmd, argv[ 0 ] ) )
+ {
+ if( pcmd->handler_func )
+ pcmd->handler_func( ctx, argc, argv );
+ break;
+ }
+ i ++;
+ }
+
+ return pcmd;
+}
+
+void shell_exec( shell_context_t *ctx, const char *command )
+{
+ char *cmd;
+ unsigned len;
+ int interactive;
+
+ // Make a copy of the command since it gets overwritten
+ len = strlen(command) + 1;
+ cmd = SHELL_MALLOC(len);
+ memcpy(cmd, command, len);
+
+ // Save interactive status; set non-interactive
+ interactive = ctx->interactive;
+ ctx->interactive = 0;
+
+ // Execute the command
+ shellh_execute_command(ctx, cmd, 0);
+
+ // Restore interactive status
+ ctx->interactive = interactive;
+
+ // Free the copy memory
+ SHELL_FREE(cmd);
+}
+
+void shell_start( shell_context_t *ctx )
+{
+ term_reset_mode(&ctx->t);
+ term_sync_size(&ctx->t);
+ printf("\n");
+ shellh_execute_command(ctx, "ver", 0);
+ shell_poll(ctx);
+}
+
+void shell_poll( shell_context_t *ctx )
+{
+ const SHELL_COMMAND *pcmd;
+ int result;
+
+ while( 1 )
+ {
+ do {
+ result = linenoise_getline( ctx, ctx->cmd, SHELL_MAX_LINE_LEN - 1, SHELL_PROMPT );
+ if (result == LINENOISE_CONTINUE) {
+ return;
+ }
+ if (result == LINENOISE_EOF) {
+ printf( "\n" );
+ clearerr( stdin );
+ break;
+ }
+ } while (result == LINENOISE_EOF);
+
+ if( strlen( ctx->cmd ) == 0 )
+ continue;
+ linenoise_addhistory( ctx, ctx->cmd );
+ pcmd = shellh_execute_command( ctx, ctx->cmd, 1 );
+ // Check for 'exit' command
+ if( pcmd && pcmd->cmd && !pcmd->handler_func )
+ break;
+ }
+}
+
+// Initialize the shell, returning 1 for OK and 0 for error
+int shell_init( shell_context_t *ctx, p_term_out term_out, p_term_in term_in, int blocking, void *usr )
+{
+ memset(ctx, 0, sizeof(*ctx));
+ ctx->blocking = blocking;
+ ctx->usr = usr;
+ ctx->interactive = 1;
+ shell_platform_init(ctx, term_out, term_in);
+ linenoise_init(ctx);
+ shell_alphabetize(ctx);
+ return 1;
+}
+
+void shell_deinit( shell_context_t *ctx )
+{
+ if (ctx->uHelpIndicies) {
+ SHELL_FREE(ctx->uHelpIndicies);
+ ctx->uHelpIndicies = NULL;
+ }
+ linenoise_cleanup(ctx);
+ shell_platform_deinit(ctx);
+}
diff --git a/fw/User/shell/shell.h b/fw/User/shell/shell.h
new file mode 100644
index 0000000..4fbe104
--- /dev/null
+++ b/fw/User/shell/shell.h
@@ -0,0 +1,258 @@
+/*!
+ * @mainpage Shell Index Page
+ * @brief Small command-line shell for embedded systems
+ *
+ * This shell supports:
+ * - Command-line history
+ * - Command-line editing
+ * - Blocking and non-blocking operation
+ * - FreeRTOS and main-loop friendly
+ *
+ * @file shell.h
+ * @version 1.0.0
+ * @sa shell_cfg.h
+ *
+*/
+
+#ifndef __SHELL_H__
+#define __SHELL_H__
+
+#include "shell_cfg.h"
+#include "term.h"
+
+/*!****************************************************************
+ * @brief The number of rows/lines in the display.
+ ******************************************************************/
+#ifndef SHELL_LINES
+#define SHELL_LINES (25)
+#endif
+
+/*!****************************************************************
+ * @brief The number of columns in the display.
+ ******************************************************************/
+#ifndef SHELL_COLUMNS
+#define SHELL_COLUMNS (80)
+#endif
+
+/*!****************************************************************
+ * @brief The function used to allocate memory for the shell.
+ *
+ * This defaults to the standard C library malloc if not defined
+ * otherwise.
+ ******************************************************************/
+#ifndef SHELL_MALLOC
+#define SHELL_MALLOC malloc
+#endif
+
+/*!****************************************************************
+ * @brief The function used to allocate memory for the shell.
+ *
+ * This defaults to the standard C library malloc if not defined
+ * otherwise.
+ ******************************************************************/
+#ifndef SHELL_CALLOC
+#define SHELL_CALLOC calloc
+#endif
+
+/*!****************************************************************
+ * @brief The function used to allocate memory for the shell.
+ *
+ * This defaults to the standard C library malloc if not defined
+ * otherwise.
+ ******************************************************************/
+#ifndef SHELL_REALLOC
+#define SHELL_REALLOC realloc
+#endif
+
+/*!****************************************************************
+ * @brief The function used to free memory.
+ *
+ * This defaults to the standard C library free if not defined
+ * otherwise.
+ ******************************************************************/
+#ifndef SHELL_FREE
+#define SHELL_FREE free
+#endif
+
+/*!****************************************************************
+ * @brief The depth of the command line history buffer.
+ *
+ * The heap allocate/free routines are not called when this is set
+ * to zero.
+ ******************************************************************/
+#ifndef SHELL_MAX_HISTORIES
+#define SHELL_MAX_HISTORIES (25)
+#endif
+
+/*!****************************************************************
+ * @brief The function used for strdup.
+ *
+ * This defaults to a built-in function that allocates memory using
+ * the SHELL_MALLOC allocation routine.
+ ******************************************************************/
+#ifndef SHELL_STRDUP
+#define SHELL_STRDUP shell_strdup
+#endif
+
+/*!****************************************************************
+ * @brief The function used for strndup.
+ *
+ * This defaults to a built-in function that allocates memory using
+ * the SHELL_MALLOC allocation routine.
+ ******************************************************************/
+#ifndef SHELL_STRNDUP
+#define SHELL_STRNDUP shell_strndup
+#endif
+
+/*!****************************************************************
+ * @brief Maximum number of command line arguments
+ ******************************************************************/
+#ifndef SHELL_MAX_ARGS
+#define SHELL_MAX_ARGS 10
+#endif
+
+/*!****************************************************************
+ * @brief Shell welcome message string.
+ *
+ * The %s will be substituted with a version string and the line
+ * must end with a \n terminator.
+ ******************************************************************/
+#ifndef SHELL_WELCOMEMSG
+#define SHELL_WELCOMEMSG "Shell %s\n"
+#endif
+
+/*!****************************************************************
+ * @brief Shell command line prompt string.
+ ******************************************************************/
+#ifndef SHELL_PROMPT
+#define SHELL_PROMPT "# "
+#endif
+
+/*!****************************************************************
+ * @brief Shell error message string string.
+ *
+ * The string must terminate with a newline
+ ******************************************************************/
+#ifndef SHELL_ERRMSG
+#define SHELL_ERRMSG "Invalid command, type 'help' for help\n"
+#endif
+
+/*!****************************************************************
+ * @brief The maximum length of a command line string with all
+ * options.
+ ******************************************************************/
+#ifndef SHELL_MAX_LINE_LEN
+#define SHELL_MAX_LINE_LEN (SHELL_COLUMNS - 1)
+#endif
+
+#ifdef __cplusplus
+extern "C"{
+#endif
+
+/*!****************************************************************
+ * @brief Blocking modes.
+ ******************************************************************/
+enum BLOCKING_MODES {
+ SHELL_MODE_BLOCKING = 0, /**< Blocking mode */
+ SHELL_MODE_NON_BLOCKING /**< Non-blocking mode */
+};
+
+/*!****************************************************************
+ * @brief Shell context block
+ *
+ * This structure holds the shell context between calls to
+ * shell_poll(). The application should not set any of these members.
+ * The documentation for this structure is to aid in debugging.
+ ******************************************************************/
+typedef struct {
+ char cmd[SHELL_MAX_LINE_LEN + 1]; /**< Buffer to hold the the current command line */
+ int blocking; /**< Blocking mode. This is set in shell_init() */
+ int history_index; /**< Index into the array of history pointers */
+ int max_histories; /**< Maximum number of history entries.
+ This is set to SHELL_MAX_HISTORIES */
+ int num_histories; /**< Number of entries in the history pointer array */
+ char **histories; /**< The array of history pointers */
+ int new_line; /**< Indicates a new line must be initialized */
+ size_t plen; /**< Linenoise line plen */
+ size_t pos; /**< Linenoise line position */
+ size_t len; /**< Linenoise current line length */
+ size_t cols; /**< Linenoise terminal line length */
+ int hidden; /**< Hide text */
+ term_state_t t; /**< Terminal state */
+ void *usr; /**< User data pointer */
+ int interactive; /**< Interactive shell */
+ unsigned *uHelpIndicies; /**< Alphabetized help indicies */
+} shell_context_t;
+
+/*!****************************************************************
+ * @brief Typedef of a shell command handler
+ *
+ * Use this when adding new commands to the shell
+ ******************************************************************/
+typedef void( *p_shell_handler )( shell_context_t *ctx, int argc, char **argv );
+
+/*!****************************************************************
+ * @brief Shell initialization routine.
+ *
+ * This function initializes the shell context and sets the
+ * working mode to blocking or non-blocking.
+
+ * @param [in] ctx Pointer to an application allocated context
+ * @param [in] term_out Pointer to function to output characters
+ * @param [in] term_in Pointer to function to input characters
+ * @param [in] mode Blocking or non-blocking mode.
+ * @sa BLOCKING_MODES
+ * @param [in] usr User pointer for term character callback
+ * functions.
+ *
+ * @return Returns 1 if successful, otherwise an error.
+ ******************************************************************/
+int shell_init( shell_context_t *ctx, p_term_out term_out, p_term_in term_in,
+ int mode, void *usr );
+
+/*!****************************************************************
+ * @brief Shell de-initialization routine.
+ *
+ * This function de-initializes and releases all shell resources.
+
+ * @param [in] ctx Pointer to an application allocated context
+ ******************************************************************/
+void shell_deinit( shell_context_t *ctx );
+
+/*!****************************************************************
+ * @brief Shell start routine.
+ *
+ * This function starts the shell. It calls shell_poll() once.
+ * In blocking mode, this call never returns.
+ *
+ * @param [in] ctx Pointer to an application allocated context
+ ******************************************************************/
+void shell_start( shell_context_t *ctx );
+
+/*!****************************************************************
+ * @brief Shell poll routine.
+ *
+ * This function polls for new characters and process completed
+ * command lines. This function should not be called directly in
+ * blocking mode.
+ *
+ * @param [in] ctx Pointer to an application allocated context
+ ******************************************************************/
+void shell_poll( shell_context_t *ctx );
+
+/*!****************************************************************
+ * @brief Shell execute routine.
+ *
+ * This function executes the given command and argument string as
+ * if it were typed on the console.
+ *
+ * @param [in] ctx Pointer to an application allocated context
+ * @param [in] command Command (and arguments) to execute
+ ******************************************************************/
+void shell_exec( shell_context_t *ctx, const char *command );
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif
diff --git a/fw/User/shell/shell_cfg.h b/fw/User/shell/shell_cfg.h
new file mode 100644
index 0000000..4db9317
--- /dev/null
+++ b/fw/User/shell/shell_cfg.h
@@ -0,0 +1,39 @@
+//
+// Grimoire
+// Copyright 2025 Wenting Zhang
+//
+// Original copyright information:
+// Copyright (c) 2022 - Analog Devices Inc. All Rights Reserved.
+//
+// This file is licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License. You may
+// obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations
+// under the License.
+//
+#pragma once
+
+#include "platform.h"
+
+#define SHELL_MAX_ARGS 10
+#define SHELL_WELCOMEMSG "Modos Grimoire\n" \
+ "Version: %s (%s %s)\n"
+#define SHELL_PROMPT "# "
+#define SHELL_ERRMSG "Invalid command, type 'help' for help\n"
+#define SHELL_MAX_LINE_LEN 79
+#define SHELL_COLUMNS 80
+#define SHELL_LINES 24
+#define SHELL_MAX_HISTORIES 50
+#define SHELL_MALLOC pvPortMalloc
+#define SHELL_FREE vPortFree
+// Does not provide calloc/ realloc
+#define SHELL_CALLOC
+#define SHELL_REALLOC
+#define SHELL_STRDUP shell_strdup
+#define SHELL_STRNDUP shell_strndup
diff --git a/fw/User/shell/shell_cmds.c b/fw/User/shell/shell_cmds.c
new file mode 100644
index 0000000..cc5df90
--- /dev/null
+++ b/fw/User/shell/shell_cmds.c
@@ -0,0 +1,713 @@
+//
+// Grimoire
+// Copyright 2025 Wenting Zhang
+//
+// Original copyright information:
+// Copyright (c) 2022 - Analog Devices Inc. All Rights Reserved.
+//
+// This file is licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License. You may
+// obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations
+// under the License.
+//
+
+#include "platform.h"
+#include "board.h"
+#include "shell.h"
+#include "shell_printf.h"
+#include "term.h"
+#include "app_main.h"
+#include "app.h"
+#include "xmodem.h"
+
+#ifdef printf
+#undef printf
+#endif
+
+#ifdef vprintf
+#undef vprintf
+#endif
+
+#define printf(...) shell_printf(ctx, __VA_ARGS__)
+#define vprintf(x,y) shell_vprintf(ctx, x, y)
+
+/***********************************************************************
+ * Misc helper functions
+ **********************************************************************/
+static void dump_bytes(shell_context_t *ctx, unsigned char *rdata, unsigned addr, unsigned rlen) {
+ unsigned i;
+ for (i = 0; i < rlen; i++) {
+ if ((i % 16) == 0) {
+ if (i) {
+ printf("\n");
+ }
+ printf("%08x: ", addr + i);
+ }
+ printf("%02x ", rdata[i]);
+ }
+ printf("\n");
+}
+
+int confirm_danger(shell_context_t *ctx, char *warnStr) {
+ char c;
+
+ printf( "%s\n", warnStr );
+ printf( "Are you sure you want to continue? [y/n]" );
+
+ c = term_getch( &ctx->t, TERM_INPUT_WAIT );
+ printf( "%c\n", isprint( c ) ? c : ' ' );
+
+ if( tolower(c) == 'y' ) {
+ return(1);
+ }
+
+ return(0);
+}
+
+/***********************************************************************
+ * CMD: syslog
+ **********************************************************************/
+const char shell_help_syslog[] = "\n";
+const char shell_help_summary_syslog[] = "Show the live system log";
+
+#define MAX_TS_LINE 32
+#define MAX_LOG_LINE 256
+
+void shell_syslog(shell_context_t *ctx, int argc, char **argv) {
+ char *line;
+ char *lbuf;
+ char *ts;
+ int c;
+
+ ts = SHELL_MALLOC(MAX_TS_LINE);
+ lbuf = SHELL_MALLOC(MAX_LOG_LINE);
+
+ c = 0;
+ do {
+ line = syslog_next(ts, MAX_TS_LINE, lbuf, MAX_LOG_LINE);
+ if (line) {
+ printf("%s %s\n", ts, line);
+ }
+ c = term_getch(&ctx->t, TERM_INPUT_DONT_WAIT);
+#ifdef FREE_RTOS
+ if ((line == NULL) && (c < 0)) {
+ vTaskDelay(pdMS_TO_TICKS(50));
+ }
+#endif
+ } while (c < 0);
+
+ if (ts) {
+ SHELL_FREE(ts);
+ }
+ if (lbuf) {
+ SHELL_FREE(lbuf);
+ }
+}
+
+/***********************************************************************
+ * CMD: stacks
+ **********************************************************************/
+const char shell_help_stacks[] = "\n";
+const char shell_help_summary_stacks[] = "Report task stack usage";
+
+static void shell_print_task_stack(shell_context_t *ctx, TaskHandle_t task) {
+ if (task) {
+ printf(" %s: %u\n",
+ pcTaskGetName(task), (unsigned)uxTaskGetStackHighWaterMark(task)
+ );
+ }
+}
+
+void shell_stacks(shell_context_t *ctx, int argc, char **argv ) {
+ printf("High Water Marks are in 32-bit words (zero is bad).\n");
+ printf("Task Stask High Water Marks:\n");
+
+ shell_print_task_stack(ctx, startup_task_handle);
+ shell_print_task_stack(ctx, housekeeping_task_handle);
+ shell_print_task_stack(ctx, usb_device_task_handle);
+ shell_print_task_stack(ctx, usb_pd_task_handle);
+ shell_print_task_stack(ctx, ui_task_handle);
+ shell_print_task_stack(ctx, key_scan_task_handle);
+ shell_print_task_stack(ctx, power_mon_task_handle);
+}
+
+/***********************************************************************
+ * CMD: test
+ **********************************************************************/
+const char shell_help_test[] = "\n";
+const char shell_help_summary_test[] = "Test command";
+
+void shell_test(shell_context_t *ctx, int argc, char **argv ) {
+
+ uint8_t val;
+
+ val = adv7611_read_reg(ADV7611_I2C_ADDR, 0x6a);
+ if (val & 0x10)
+ printf("TMDS clock detected\n");
+ else
+ printf("No TMDS clock detected\n");
+
+ uint16_t val16;
+ val = adv7611_read_reg(HDMI_I2C_ADDR, 0x51); // D8-D1
+ val16 = (uint16_t)val << 1;
+ val = adv7611_read_reg(HDMI_I2C_ADDR, 0x52);
+ val16 |= val >> 7;
+
+ printf("TMDS frequency %d MHz\n", val16);
+
+ val = adv7611_read_reg(HDMI_I2C_ADDR, 0x04);
+ if (val & 0x2)
+ printf("TMDS PLL locked\n");
+ else
+ printf("TMDS PLL not locked\n");
+
+ val = adv7611_read_reg(HDMI_I2C_ADDR, 0x05);
+ if (val & 0x80)
+ printf("HDMI mode detected\n");
+ else
+ printf("DVI mode detected\n");
+
+ val = adv7611_read_reg(HDMI_I2C_ADDR, 0x07);
+ if (val & 0x20)
+ printf("DE regeneration locked\n");
+ else
+ printf("DE regeneration not locked\n");
+
+ if (val & 0x80)
+ printf("Vertical filter locked\n");
+ else
+ printf("Vertical filter not locked\n");
+
+ val16 = (uint16_t)adv7611_read_reg(HDMI_I2C_ADDR, 0x1e) << 8;
+ val16 |= adv7611_read_reg(HDMI_I2C_ADDR, 0x1f);
+ printf("Total line width: %d\n", val16);
+
+ val16 = (uint16_t)(adv7611_read_reg(HDMI_I2C_ADDR, 0x07) & 0x1f) << 8;
+ val16 |= adv7611_read_reg(HDMI_I2C_ADDR, 0x08);
+ printf("Active line width: %d\n", val16);
+
+ val16 = (uint16_t)(adv7611_read_reg(HDMI_I2C_ADDR, 0x09) & 0x1f) << 8;
+ val16 |= adv7611_read_reg(HDMI_I2C_ADDR, 0x0a);
+ printf("Active field height: %d\n", val16);
+}
+
+/***********************************************************************
+ * CMD: i2c_probe
+ **********************************************************************/
+const char shell_help_i2c_probe[] = "\n"
+ " i2c_port - I2C port to probe\n";
+const char shell_help_summary_i2c_probe[] = "Probe an I2C port for active devices";
+
+void shell_i2c_probe(shell_context_t *ctx, int argc, char **argv)
+{
+ pal_i2c_t *i2c;
+ int i;
+
+ if (argc != 2) {
+ printf("Invalid arguments. Type help [] for usage.\n");
+ return;
+ }
+
+ int i2c_port = strtol(argv[1], NULL, 0);
+ i2c = NULL;
+
+ if (i2c_port == 1) {
+ i2c = &pi2c1;
+ }
+ else {
+ printf("Invalid I2C port!\n");
+ return;
+ }
+
+ printf("Probing I2C port %d:\n", i2c_port);
+ for (i = 0x08; i < 0x78; i++) {
+ bool result = pal_i2c_ping(i2c, i);
+ if (result == true) {
+ printf(" Found device 0x%02x\n", i);
+ }
+ }
+}
+
+
+const char shell_help_fl[] = " [brightness]\n"
+ " operation - on | off | set\n"
+ " brightness - 0-255\n";
+const char shell_help_summary_fl[] = "Control front light";
+
+void shell_fl(shell_context_t *ctx, int argc, char **argv)
+{
+ if ((argc < 2) || (argc > 3)) {
+ printf("Invalid arguments. Type help [] for usage.\n");
+ return;
+ }
+
+ if (strcmp(argv[1], "on") == 0) {
+ power_on_fl();
+ }
+ else if (strcmp(argv[1], "off") == 0) {
+ power_off_fl();
+ }
+
+ if (argc == 3) {
+ int brightness = strtol(argv[2], NULL, 0);
+ power_set_fl_brightness(brightness);
+ }
+}
+
+
+/***********************************************************************
+ * XMODEM helper functions
+ **********************************************************************/
+typedef struct {
+ shell_context_t *ctx;
+} xmodem_state_t;
+
+static void shell_xmodem_putchar(int c, void *usr) {
+ xmodem_state_t *x = (xmodem_state_t *)usr;
+ shell_context_t *ctx = x->ctx;
+ term_state_t *t = &ctx->t;
+
+ term_putch(t, c);
+}
+
+static int shell_xmodem_getchar(int timeout, void *usr) {
+ xmodem_state_t *x = (xmodem_state_t *)usr;
+ shell_context_t *ctx = x->ctx;
+ term_state_t *t = &ctx->t;
+ int c;
+
+ c = term_getch(t, timeout);
+
+ return(c);
+}
+
+typedef struct {
+ xmodem_state_t xmodem;
+ spiffs_file f;
+ void *data;
+ int size;
+} file_xfer_state_t;
+
+static void file_data_write(void *usr, void *data, int size) {
+ file_xfer_state_t *state = (file_xfer_state_t *)usr;
+
+ /*
+ * Need to double-buffer the data in order to strip off the
+ * trailing packet bytes at the end of an xmodem transfer.
+ */
+ if (state->data == NULL) {
+ state->data = SHELL_MALLOC(1024);
+ memcpy(state->data, data, size);
+ state->size = size;
+ } else {
+ if (data) {
+ SPIFFS_write(&spiffs_fs, state->f, state->data, state->size);
+ memcpy(state->data, data, size);
+ state->size = size;
+ } else {
+ uint8_t *buf = (uint8_t *)state->data;
+ while (state->size && buf[state->size-1] == '\x1A') {
+ state->size--;
+ }
+ SPIFFS_write(&spiffs_fs, state->f, state->data, state->size);
+ if (state->data) {
+ SHELL_FREE(state->data);
+ state->data = NULL;
+ }
+ }
+ }
+}
+
+static void file_data_read(void *usr, void *data, int size) {
+ file_xfer_state_t *state = (file_xfer_state_t *)usr;
+
+ if (size > 0) {
+ SPIFFS_read(&spiffs_fs, state->f, data, size);
+ }
+}
+
+/***********************************************************************
+ * CMD: dump
+ **********************************************************************/
+const char shell_help_dump[] = "[addr] \n"
+ " addr - Starting address to dump\n"
+ " len - Number of bytes to dump (default 1)\n";
+const char shell_help_summary_dump[] = "Hex dump of flash contents";
+
+void shell_dump(shell_context_t *ctx, int argc, char **argv)
+{
+ uintptr_t addr = 0;
+ unsigned len = 1;
+ uint8_t *buf;
+ int ok;
+
+ if (argc < 2) {
+ printf("Invalid arguments\n");
+ return;
+ }
+
+ addr = strtoul(argv[1], NULL, 0);
+ if (argc > 2) {
+ len = strtoul(argv[2], NULL, 0);
+ }
+
+ buf = SHELL_MALLOC(len);
+ if (buf) {
+ ok = spif_read(addr, len, buf);
+ if (ok == 0) {
+ dump_bytes(ctx, buf, addr, len);
+ }
+ SHELL_FREE(buf);
+ }
+}
+
+/***********************************************************************
+ * CMD: fdump
+ **********************************************************************/
+const char shell_help_fdump[] =
+ "[file] \n"
+ " file - File to dump\n"
+ " start - Start offset in bytes (default: 0)\n"
+ " size - Size in bytes (default: full file)\n";
+const char shell_help_summary_fdump[] = "Dumps the contents of a file in hex";
+
+#define DUMP_SIZE 512
+
+void shell_fdump(shell_context_t *ctx, int argc, char **argv) {
+ spiffs_file f;
+ size_t start = 0;
+ size_t size = SIZE_MAX;
+ uint8_t *buf = NULL;
+ size_t rlen;
+ int c;
+
+ if( argc < 2 ) {
+ printf("No file given\n");
+ return;
+ }
+
+ if (argc > 2) {
+ start = (size_t)strtoul(argv[2], NULL, 0);
+ }
+
+ if (argc > 3) {
+ size = (size_t)strtoul(argv[3], NULL, 0);
+ }
+
+ f = SPIFFS_open(&spiffs_fs, argv[1], SPIFFS_O_RDONLY, 0);
+ if (f) {
+ buf = SHELL_MALLOC(DUMP_SIZE);
+ SPIFFS_lseek(&spiffs_fs, f, start, SPIFFS_SEEK_SET);
+ do {
+ rlen = (size < DUMP_SIZE) ? size : DUMP_SIZE;
+ rlen = SPIFFS_read(&spiffs_fs, f, buf, rlen);
+ if (rlen) {
+ dump_bytes(ctx, buf, start, rlen);
+ size -= rlen;
+ start += rlen;
+ c = term_getch(&ctx->t, TERM_INPUT_DONT_WAIT);
+ }
+ } while (size && rlen && (c < 0));
+ if (buf) {
+ SHELL_FREE(buf);
+ }
+ SPIFFS_close(&spiffs_fs, f);
+ }
+ else {
+ printf("Unable to open '%s'\n", argv[1]);
+ }
+}
+
+/***********************************************************************
+ * CMD: recv
+ **********************************************************************/
+const char shell_help_recv[] = "\n"
+ " Transfer and save to file\n";
+const char shell_help_summary_recv[] = "Receive a file via XMODEM";
+
+void shell_recv( shell_context_t *ctx, int argc, char **argv )
+{
+ file_xfer_state_t file_state = { 0 };
+ long size;
+
+ if( argc != 2 ) {
+ printf( "Usage: recv \n" );
+ return;
+ }
+
+ file_state.xmodem.ctx = ctx;
+
+ file_state.f = SPIFFS_open(&spiffs_fs, argv[1], SPIFFS_O_CREAT | SPIFFS_O_TRUNC | SPIFFS_O_WRONLY, 0);
+ if( file_state.f == 0) {
+ printf( "unable to open file %s\n", argv[ 1 ] );
+ return;
+ }
+ printf( "Prepare your terminal for XMODEM send ... " );
+ term_set_mode(&ctx->t, TERM_MODE_COOKED, 0);
+ size = XmodemReceiveCrc(file_data_write, &file_state, 4*1024*1024,
+ shell_xmodem_getchar, shell_xmodem_putchar);
+ term_set_mode(&ctx->t, TERM_MODE_COOKED, 1);
+ if (size < 0) {
+ printf( "XMODEM Error: %ld\n", size);
+ } else {
+ printf( "received and saved as %s\n", argv[ 1 ] );
+ }
+ SPIFFS_close(&spiffs_fs, file_state.f);
+}
+
+/***********************************************************************
+ * CMD: send
+ **********************************************************************/
+const char shell_help_send[] = " [ ...]\n";
+const char shell_help_summary_send[] = "Send files via YMODEM.";
+
+typedef struct {
+ file_xfer_state_t state;
+ const char *fname;
+ size_t fsize;
+} ymodem_state_t;
+
+static void ymodem_hdr(void *usr, void *xmodemBuffer, int xmodemSize) {
+ ymodem_state_t *y = (ymodem_state_t *)usr;
+ snprintf(xmodemBuffer, xmodemSize, "%s%c%u", y->fname, 0, (unsigned)y->fsize);
+}
+
+static void ymodem_end(void *xs, void *xmodemBuffer, int xmodemSize) {
+}
+
+void shell_send(shell_context_t *ctx, int argc, char **argv)
+{
+ size_t size;
+ spiffs_file fp = 0;
+ int ret = -1;
+ int i;
+
+ ymodem_state_t y = {
+ .state.xmodem.ctx = ctx,
+ };
+
+ if (argc < 2) {
+ printf("Usage: %s [ ...]\n", argv[0]);
+ return;
+ }
+
+ printf ("Prepare your terminal for YMODEM receive...\n");
+ term_set_mode(&ctx->t, TERM_MODE_COOKED, 0);
+ for (i = 1; i < argc; i++) {
+ fp = SPIFFS_open(&spiffs_fs, argv[i], SPIFFS_O_RDONLY, 0);
+ if (fp) {
+ spiffs_stat s;
+ SPIFFS_fstat(&spiffs_fs, fp, &s);
+ size = s.size;
+ y.fname = argv[i]; y.fsize = size; y.state.f = fp;
+ ret = XmodemTransmit(ymodem_hdr, &y, 128, 0, 1,
+ shell_xmodem_getchar, shell_xmodem_putchar);
+ if (ret >= 0) {
+ ret = XmodemTransmit(file_data_read, &y, y.fsize, 1, 0,
+ shell_xmodem_getchar, shell_xmodem_putchar);
+ }
+ SPIFFS_close(&spiffs_fs, fp);
+ if (ret < 0) {
+ break;
+ }
+ }
+ }
+ if (ret >= 0) {
+ ret = XmodemTransmit(ymodem_end, &y, 128, 0, 1,
+ shell_xmodem_getchar, shell_xmodem_putchar);
+ }
+ term_set_mode(&ctx->t, TERM_MODE_COOKED, 1);
+ if (ret < 0) {
+ printf( "YMODEM Error: %ld\n", ret);
+ }
+}
+
+
+/***********************************************************************
+ * CMD: df
+ **********************************************************************/
+const char shell_help_df[] = "\n";
+const char shell_help_summary_df[] = "Shows internal filesystem disk full status";
+
+void shell_df(shell_context_t *ctx, int argc, char **argv) {
+ printf("%10s %10s %10s %5s\n", "Size", "Used", "Available", "Use %");
+
+ int32_t serr; uint32_t ssize; uint32_t sused;
+ serr = SPIFFS_info(&spiffs_fs, &ssize, &sused);
+ if (serr == SPIFFS_OK) {
+ printf("%10u %10u %10u %5u\n",
+ (unsigned)ssize, (unsigned)sused, (unsigned)(ssize - sused),
+ (unsigned)((100 * sused) / ssize));
+ }
+}
+
+
+const char shell_help_setvolt[] = " \n";
+const char shell_help_summary_setvolt[] = "Set voltage";
+
+void shell_setvolt(shell_context_t *ctx, int argc, char **argv) {
+ if (argc < 3) {
+ printf("Usage: \n", argv[0]);
+ return;
+ }
+
+ float volt = strtof(argv[2], NULL);
+ if (strcmp(argv[1], "vcom") == 0) {
+ power_set_vcom(volt);
+ }
+ else if (strcmp(argv[1], "vgh") == 0) {
+ power_set_vgh(volt);
+ }
+}
+
+
+const char shell_help_setcfg[] = " [key] [value]\n";
+const char shell_help_summary_setcfg[] = "Sets configuration. Remember to use save to save it to the flash.";
+
+void shell_setcfg(shell_context_t *ctx, int argc, char **argv) {
+ if (argc < 2) {
+ printf("Usage: %s\n", shell_help_setcfg);
+ return;
+ }
+
+ enum {UINT8, UINT16, UINT32, FLOAT32} var_type;
+ void * var_pointer;
+ if (argc >= 3) {
+ // has key specifier
+ if (strcmp(argv[2], "pclk_hz") == 0) {
+ var_pointer = &(config.pclk_hz);
+ var_type = UINT32;
+ }
+ else if (strcmp(argv[2], "hfp") == 0) {
+ var_pointer = &(config.hfp);
+ var_type = UINT8;
+ }
+ else if (strcmp(argv[2], "vfp") == 0) {
+ var_pointer = &(config.vfp);
+ var_type = UINT8;
+ }
+ else if (strcmp(argv[2], "hsync") == 0) {
+ var_pointer = &(config.hsync);
+ var_type = UINT8;
+ }
+ else if (strcmp(argv[2], "vsync") == 0) {
+ var_pointer = &(config.vsync);
+ var_type = UINT8;
+ }
+ else if (strcmp(argv[2], "hact") == 0) {
+ var_pointer = &(config.hact);
+ var_type = UINT16;
+ }
+ else if (strcmp(argv[2], "hblk") == 0) {
+ var_pointer = &(config.hblk);
+ var_type = UINT16;
+ }
+ else if (strcmp(argv[2], "vact") == 0) {
+ var_pointer = &(config.vact);
+ var_type = UINT16;
+ }
+ else if (strcmp(argv[2], "vblk") == 0) {
+ var_pointer = &(config.vblk);
+ var_type = UINT16;
+ }
+ else if (strcmp(argv[2], "size_x_mm") == 0) {
+ var_pointer = &(config.size_x_mm);
+ var_type = UINT16;
+ }
+ else if (strcmp(argv[2], "size_y_mm") == 0) {
+ var_pointer = &(config.size_y_mm);
+ var_type = UINT16;
+ }
+ else if (strcmp(argv[2], "mfg_week") == 0) {
+ var_pointer = &(config.mfg_week);
+ var_type = UINT8;
+ }
+ else if (strcmp(argv[2], "mfg_year") == 0) {
+ var_pointer = &(config.mfg_year);
+ var_type = UINT8;
+ }
+ else if (strcmp(argv[2], "vcom") == 0) {
+ var_pointer = &(config.vcom);
+ var_type = FLOAT32;
+ }
+ else if (strcmp(argv[2], "vgh") == 0) {
+ var_pointer = &(config.vgh);
+ var_type = FLOAT32;
+ }
+ else if (strcmp(argv[2], "tcon_vfp") == 0) {
+ var_pointer = &(config.tcon_vfp);
+ var_type = UINT8;
+ }
+ else if (strcmp(argv[2], "tcon_vsync") == 0) {
+ var_pointer = &(config.tcon_vsync);
+ var_type = UINT8;
+ }
+ else if (strcmp(argv[2], "tcon_vbp") == 0) {
+ var_pointer = &(config.tcon_vbp);
+ var_type = UINT8;
+ }
+ else if (strcmp(argv[2], "tcon_vact") == 0) {
+ var_pointer = &(config.tcon_vact);
+ var_type = UINT16;
+ }
+ else if (strcmp(argv[2], "tcon_hfp") == 0) {
+ var_pointer = &(config.tcon_hfp);
+ var_type = UINT8;
+ }
+ else if (strcmp(argv[2], "tcon_hsync") == 0) {
+ var_pointer = &(config.tcon_hsync);
+ var_type = UINT8;
+ }
+ else if (strcmp(argv[2], "tcon_hbp") == 0) {
+ var_pointer = &(config.tcon_hbp);
+ var_type = UINT8;
+ }
+ else if (strcmp(argv[2], "tcon_hact") == 0) {
+ var_pointer = &(config.tcon_hact);
+ var_type = UINT16;
+ }
+ }
+
+ if (strcmp(argv[1], "set") == 0) {
+ if (argc < 4) {
+ printf("Key and value required for set\n");
+ return;
+ }
+ if (var_type == UINT8) {
+ *(uint8_t *)var_pointer = strtol(argv[3], NULL, 10);
+ }
+ else if (var_type == UINT16) {
+ *(uint16_t *)var_pointer = strtol(argv[3], NULL, 10);
+ }
+ else if (var_type == UINT32) {
+ *(uint32_t *)var_pointer = strtol(argv[3], NULL, 10);
+ }
+ else if (var_type == FLOAT32) {
+ *(float *)var_pointer = strtof(argv[3], NULL);
+ }
+ }
+ else if (strcmp(argv[1], "get") == 0) {
+ if (var_type == UINT8) {
+ printf("%d\n", *(uint8_t *)var_pointer);
+ }
+ else if (var_type == UINT16) {
+ printf("%d\n", *(uint16_t *)var_pointer);
+ }
+ else if (var_type == UINT32) {
+ printf("%d\n", *(uint32_t *)var_pointer);
+ }
+ else if (var_type == FLOAT32) {
+ printf("%f\n", *(float *)var_pointer);
+ }
+ }
+ else if (strcmp(argv[1], "save") == 0) {
+ config_save();
+ }
+}
diff --git a/fw/User/shell/shell_platform.c b/fw/User/shell/shell_platform.c
new file mode 100644
index 0000000..ed50ca8
--- /dev/null
+++ b/fw/User/shell/shell_platform.c
@@ -0,0 +1,168 @@
+/*
+ * This code has been modified by Analog Devices, Inc.
+ * ANSI Mode Control processing:
+ * https://vt100.net/docs/vt100-ug/chapter3.html
+ */
+
+#include
+#include
+#include
+#include
+#include
+
+#include "shell.h"
+#include "shell_platform.h"
+#include "term.h"
+
+#define ANSI_CTRL_PARAM_SIZE 16
+#define ANSI_CTRL_MAX_PARAMS 4
+
+static int term_translate( term_state_t *t, int data, void *usr )
+{
+ static int escape = 0;
+
+ static char param[ANSI_CTRL_MAX_PARAMS][ANSI_CTRL_PARAM_SIZE];
+ static int param_num;
+ static int param_idx;
+
+ int i;
+
+ if (escape)
+ {
+ switch (escape)
+ {
+ case 1:
+ if (data == '[')
+ escape = 2;
+ else if (data == 0x1B) {
+ escape = 0;
+ return(KC_ESC);
+ }
+ else
+ escape = 0;
+ break;
+ case 2:
+ if( data >= 'A' && data <= 'D' )
+ {
+ escape = 0;
+ switch( data )
+ {
+ case 'A':
+ return KC_UP;
+ case 'B':
+ return KC_DOWN;
+ case 'C':
+ return KC_RIGHT;
+ case 'D':
+ return KC_LEFT;
+ }
+ }
+ else if( data >= '0' && data <= '9' )
+ {
+ memset(param, 0, sizeof(param));
+ param_num = 0; param_idx = 0;
+ param[param_num][param_idx++] = (char)data;
+ escape = 3;
+ }
+ break;
+ case 3:
+ if( data >= '0' && data <= '9' )
+ {
+ if( param_idx < (ANSI_CTRL_PARAM_SIZE - 1))
+ {
+ param[param_num][param_idx++] = (char)data;
+ }
+ } else {
+ switch( data )
+ {
+ case '~':
+ escape = 0;
+ for ( i = 0; i <= param_num; i++ )
+ {
+ data = atoi(param[i]);
+ switch( data )
+ {
+ case '1':
+ return KC_HOME;
+ case '4':
+ return KC_END;
+ case '5':
+ return KC_PAGEUP;
+ case '6':
+ return KC_PAGEDOWN;
+ default:
+ break;
+ }
+ }
+ break;
+ case ';':
+ if( param_num < ANSI_CTRL_MAX_PARAMS )
+ {
+ param_num++; param_idx = 0;
+ }
+ break;
+ case 'R':
+ escape = 0;
+ if( param_num >= 1 )
+ {
+ t->term_num_lines = atoi(param[0]);
+ t->term_num_cols = atoi(param[1]);
+ }
+ break;
+ }
+ }
+ break;
+ default:
+ break;
+ }
+ return KC_UNKNOWN;
+ }
+ else if( isprint( data ) )
+ return data;
+ else if( data == 0x1B ) // escape sequence
+ {
+ escape = 1;
+ }
+ else if( data == 0x0D )
+ {
+ return KC_ENTER;
+ }
+ else
+ {
+ switch( data )
+ {
+ case 0x09:
+ return KC_TAB;
+ case 0x7F:
+ //return KC_DEL;
+ return KC_BACKSPACE;
+ case 0x08:
+ return KC_BACKSPACE;
+ case 26:
+ return KC_CTRL_Z;
+ case 1:
+ return KC_CTRL_A;
+ case 5:
+ return KC_CTRL_E;
+ case 3:
+ return KC_CTRL_C;
+ case 20:
+ return KC_CTRL_T;
+ case 21:
+ return KC_CTRL_U;
+ case 11:
+ return KC_CTRL_K;
+ }
+ }
+ return KC_UNKNOWN;
+}
+
+void shell_platform_init(shell_context_t *ctx, p_term_out term_out, p_term_in term_in)
+{
+ term_init(&ctx->t, SHELL_LINES, SHELL_COLUMNS, term_out, term_in, term_translate, ctx->usr);
+}
+
+void shell_platform_deinit(shell_context_t *ctx)
+{
+ term_deinit(&ctx->t);
+}
diff --git a/fw/User/shell/shell_platform.h b/fw/User/shell/shell_platform.h
new file mode 100644
index 0000000..757dfcb
--- /dev/null
+++ b/fw/User/shell/shell_platform.h
@@ -0,0 +1,9 @@
+#ifndef _SHELL_PLATFORM_H
+#define _SHELL_PLATFORM_H
+
+#include "shell.h"
+
+void shell_platform_init(shell_context_t *ctx, p_term_out term_out, p_term_in term_in);
+void shell_platform_deinit(shell_context_t *ctx);
+
+#endif
diff --git a/fw/User/shell/shell_printf.c b/fw/User/shell/shell_printf.c
new file mode 100644
index 0000000..7b63c20
--- /dev/null
+++ b/fw/User/shell/shell_printf.c
@@ -0,0 +1,59 @@
+//
+// Grimoire
+// Copyright 2025 Wenting Zhang
+//
+// Original copyright information:
+// Copyright (c) 2022 - Analog Devices Inc. All Rights Reserved.
+//
+// This file is licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License. You may
+// obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations
+// under the License.
+//
+#include
+#include
+#include
+
+#include "shell_printf.h"
+#include "term.h"
+#include "shell.h"
+
+/* Use lightweight printf */
+//#include "printf.h"
+
+int shell_vprintf(shell_context_t *ctx, const char *fmt, va_list ap)
+{
+ va_list va;
+ char *str;
+ va = ap;
+ int len = vsnprintf(NULL, 0, fmt, va);
+ va = ap;
+ str = SHELL_MALLOC(len + 1);
+ vsnprintf(str, len + 1, fmt, va);
+ term_putstr(&ctx->t, str, len);
+ SHELL_FREE(str);
+ return(len);
+}
+
+int shell_printf(shell_context_t *ctx, const char* fmt, ...)
+{
+ va_list va;
+ char *str;
+ va_start(va, fmt);
+ int len = vsnprintf(NULL, 0, fmt, va);
+ va_end(va);
+ va_start(va, fmt);
+ str = SHELL_MALLOC(len + 1);
+ vsnprintf(str, len + 1, fmt, va);
+ va_end(va);
+ term_putstr(&ctx->t, str, len);
+ SHELL_FREE(str);
+ return(len);
+}
diff --git a/fw/User/shell/shell_printf.h b/fw/User/shell/shell_printf.h
new file mode 100644
index 0000000..b715d2a
--- /dev/null
+++ b/fw/User/shell/shell_printf.h
@@ -0,0 +1,31 @@
+//
+// Grimoire
+// Copyright 2025 Wenting Zhang
+//
+// Original copyright information:
+// Copyright (c) 2022 - Analog Devices Inc. All Rights Reserved.
+//
+// This file is licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License. You may
+// obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations
+// under the License.
+//
+
+#ifndef _shell_printf_h
+#define _shell_printf_h
+
+#include
+
+#include "shell.h"
+
+int shell_printf(shell_context_t *ctx, const char* fmt, ...);
+int shell_vprintf(shell_context_t *ctx, const char *format, va_list ap);
+
+#endif
diff --git a/fw/User/shell/shell_string.c b/fw/User/shell/shell_string.c
new file mode 100644
index 0000000..0dbebc5
--- /dev/null
+++ b/fw/User/shell/shell_string.c
@@ -0,0 +1,53 @@
+//
+// Grimoire
+// Copyright 2025 Wenting Zhang
+//
+// Original copyright information:
+// Copyright (c) 2022 - Analog Devices Inc. All Rights Reserved.
+//
+// This file is licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License. You may
+// obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations
+// under the License.
+//
+
+#include
+#include
+
+#include "shell.h"
+
+char *shell_strdup(const char *str)
+{
+ size_t size;
+ char *copy;
+
+ size = strlen(str) + 1;
+ if ((copy = SHELL_MALLOC(size)) == NULL)
+ return(NULL);
+
+ (void)memcpy(copy, str, size);
+ return(copy);
+}
+
+char *shell_strndup(const char *s, size_t n)
+{
+ char *result;
+ size_t size = strlen(s);
+
+ if (n < size)
+ size = n;
+
+ result = (char *)SHELL_MALLOC(size + 1);
+ if (!result)
+ return 0;
+
+ result[size] = '\0';
+ return ((char *)memcpy(result, s, size));
+}
diff --git a/fw/User/shell/shell_string.h b/fw/User/shell/shell_string.h
new file mode 100644
index 0000000..19b2e6d
--- /dev/null
+++ b/fw/User/shell/shell_string.h
@@ -0,0 +1,23 @@
+//
+// Grimoire
+// Copyright 2025 Wenting Zhang
+//
+// Original copyright information:
+// Copyright (c) 2022 - Analog Devices Inc. All Rights Reserved.
+//
+// This file is licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License. You may
+// obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations
+// under the License.
+//
+#pragma once
+
+char *shell_strdup(const char *str);
+char *shell_strndup(const char *s, size_t n);
diff --git a/fw/User/shell/term.c b/fw/User/shell/term.c
new file mode 100644
index 0000000..d61c73c
--- /dev/null
+++ b/fw/User/shell/term.c
@@ -0,0 +1,197 @@
+/*
+ * This code has been modified by Analog Devices, Inc.
+ */
+
+// Terminal function
+#include
+#include
+#include
+
+#include "shell.h"
+#include "shell_platform.h"
+#include "term.h"
+
+// Maximum size on an ANSI sequence
+#define TERM_MAX_ANSI_SIZE 14
+
+// *****************************************************************************
+// Terminal functions
+
+static void term_ansi( term_state_t *t, const char* fmt, ... )
+{
+ char seq[ TERM_MAX_ANSI_SIZE + 1 ];
+ va_list ap;
+
+ seq[ TERM_MAX_ANSI_SIZE ] = '\0';
+ seq[ 0 ] = '\x1B';
+ seq[ 1 ] = '[';
+ va_start( ap, fmt );
+ vsnprintf( seq + 2, TERM_MAX_ANSI_SIZE - 2, fmt, ap );
+ va_end( ap );
+ term_putstr( t, seq, strlen( seq ) );
+}
+
+// Clear the screen
+void term_clrscr(term_state_t *t)
+{
+ term_ansi( t, "2J" );
+ t->term_cx = t->term_cy = 0;
+}
+
+// Clear to end of line
+void term_clreol(term_state_t *t)
+{
+ term_ansi( t, "K" );
+}
+
+// Move cursor to (x, y)
+void term_gotoxy( term_state_t *t, unsigned x, unsigned y )
+{
+ term_ansi( t, "%u;%uH", y, x );
+ t->term_cx = x;
+ t->term_cy = y;
+}
+
+// Move cursor up "delta" lines
+void term_up( term_state_t *t, unsigned delta )
+{
+ term_ansi( t, "%uA", delta );
+ t->term_cy -= delta;
+}
+
+// Move cursor down "delta" lines
+void term_down( term_state_t *t, unsigned delta )
+{
+ term_ansi( t, "%uB", delta );
+ t->term_cy += delta;
+}
+
+// Move cursor right "delta" chars
+void term_right( term_state_t *t, unsigned delta )
+{
+ term_ansi( t, "%uC", delta );
+ t->term_cx -= delta;
+}
+
+// Move cursor left "delta" chars
+void term_left( term_state_t *t, unsigned delta )
+{
+ term_ansi( t, "%uD", delta );
+ t->term_cx += delta;
+}
+
+// Reset the character mode
+void term_reset_mode( term_state_t *t )
+{
+ term_ansi( t, "0m" );
+}
+
+// Request current size from the terminal
+void term_sync_size( term_state_t *t )
+{
+ term_putstr( t, "\x1B" "7", 2 ); // Store cursor position
+ term_ansi( t, "999;999H" ); // Move far away
+ term_ansi( t, "6n" ); // Request position
+ term_putstr( t, "\x1B" "8", 2 ); // Restore cursor position
+}
+
+// Set the terminal size
+void term_set_size( term_state_t *t, unsigned num_cols, unsigned num_lines )
+{
+ t->term_num_lines = num_lines;
+ t->term_num_cols = num_cols;
+ term_ansi(t, "8;%u;%ut", num_lines, num_cols);
+}
+
+void term_set_mode( term_state_t *t, int mode, int set )
+{
+ if ( set ) {
+ t->term_mode |= mode;
+ } else {
+ t->term_mode &= ~mode;
+ }
+}
+
+// Return the number of terminal lines
+unsigned term_get_lines(term_state_t *t)
+{
+ return t->term_num_lines;
+}
+
+// Return the number of terminal columns
+unsigned term_get_cols(term_state_t *t)
+{
+ return t->term_num_cols;
+}
+
+// Write a character to the terminal
+void term_putch( term_state_t *t, char ch )
+{
+ if( ( ch == '\n' ) && ( t->term_mode & TERM_MODE_COOKED ) )
+ {
+ if( t->term_cy < t->term_num_lines )
+ t->term_cy ++;
+ t->term_cx = 0;
+ t->term_out( '\r', t->usr );
+ }
+ t->term_out( ch, t->usr );
+}
+
+// Write a string to the terminal
+void term_putstr( term_state_t *t, const char* str, unsigned size )
+{
+ while( size )
+ {
+ term_putch( t, *str ++ );
+ size --;
+ }
+}
+
+// Write a string of
+
+// Return the cursor "x" position
+unsigned term_get_cx(term_state_t *t)
+{
+ return t->term_cx;
+}
+
+// Return the cursor "y" position
+unsigned term_get_cy(term_state_t *t)
+{
+ return t->term_cy;
+}
+
+// Return a char read from the terminal
+// If "mode" is TERM_INPUT_DONT_WAIT, return the char only if it is available,
+// otherwise return -1
+// Calls the translate function to translate the terminal's physical key codes
+// to logical key codes (defined in the term.h header)
+int term_getch( term_state_t *t, int mode )
+{
+ int ch;
+
+ ch = t->term_in( mode, t->usr );
+
+ if( ( ch != -1 ) && ( t->term_mode & TERM_MODE_COOKED ) )
+ return t->term_translate( t, ch, t->usr );
+ else
+ return ch;
+}
+
+void term_init( term_state_t *t, unsigned lines, unsigned cols, p_term_out term_out_func,
+ p_term_in term_in_func, p_term_translate term_translate_func,
+ void *usr )
+{
+ t->term_num_lines = lines;
+ t->term_num_cols = cols;
+ t->term_out = term_out_func;
+ t->term_in = term_in_func;
+ t->term_translate = term_translate_func;
+ t->usr = usr;
+ t->term_cx = t->term_cy = 0;
+ t->term_mode = TERM_MODE_COOKED;
+}
+
+void term_deinit( term_state_t *t )
+{
+}
diff --git a/fw/User/shell/term.h b/fw/User/shell/term.h
new file mode 100644
index 0000000..ddd4506
--- /dev/null
+++ b/fw/User/shell/term.h
@@ -0,0 +1,102 @@
+// Terminal functions
+
+#ifndef __TERM_H__
+#define __TERM_H__
+
+// ****************************************************************************
+// Data types
+
+typedef struct term_state_t term_state_t; // Break recursive definition
+
+// Terminal output function
+typedef void ( *p_term_out )( char, void * );
+// Terminal input function
+typedef int ( *p_term_in )( int, void * );
+// Terminal translate input function
+typedef int ( *p_term_translate )( term_state_t *, int, void * );
+
+// Terminal input mode (parameter of p_term_in and term_getch())
+#define TERM_INPUT_DONT_WAIT 0
+#define TERM_INPUT_WAIT 1
+
+// Terminal mode flags
+#define TERM_MODE_NONE 0
+#define TERM_MODE_COOKED 1
+
+struct term_state_t {
+ p_term_out term_out; /**< Terminal output function pointer */
+ p_term_in term_in; /**< Terminal input function pointer */
+ p_term_translate term_translate; /**< Terminal translate function pointer */
+ unsigned term_num_lines; /**< Terminal lines */
+ unsigned term_num_cols; /**< Terminal column */
+ unsigned term_cx; /**< Terminal current x */
+ unsigned term_cy; /**< Terminal current y */
+ unsigned term_mode; /**< Terminal character mode */
+ void *usr; /**< User defined pointer */
+};
+
+// ****************************************************************************
+// Exported functions
+
+// Terminal initialization
+void term_init( term_state_t *t, unsigned lines, unsigned cols, p_term_out term_out_func,
+ p_term_in term_in_func, p_term_translate term_translate_func,
+ void *usr );
+void term_deinit( term_state_t *t );
+
+// Terminal output functions
+void term_clrscr(term_state_t *t);
+void term_clreol(term_state_t *t);
+void term_gotoxy( term_state_t *t, unsigned x, unsigned y );
+void term_up( term_state_t *t, unsigned delta );
+void term_down( term_state_t *t, unsigned delta );
+void term_left( term_state_t *t, unsigned delta );
+void term_right( term_state_t *t, unsigned delta );
+unsigned term_get_lines(term_state_t *t);
+unsigned term_get_cols(term_state_t *t);
+void term_putch( term_state_t *t, char ch );
+void term_putstr( term_state_t *t, const char* str, unsigned size );
+unsigned term_get_cx(term_state_t *t);
+unsigned term_get_cy(term_state_t *t);
+int term_getch( term_state_t *t, int mode );
+void term_reset_mode( term_state_t *t );
+void term_sync_size( term_state_t *t );
+void term_set_size( term_state_t *t, unsigned num_cols, unsigned num_lines );
+void term_set_mode( term_state_t *t, int mode, int set );
+
+#define TERM_KEYCODES\
+ _D( KC_UP ),\
+ _D( KC_DOWN ),\
+ _D( KC_LEFT ),\
+ _D( KC_RIGHT ),\
+ _D( KC_HOME ),\
+ _D( KC_END ),\
+ _D( KC_PAGEUP ),\
+ _D( KC_PAGEDOWN ),\
+ _D( KC_ENTER ),\
+ _D( KC_TAB ),\
+ _D( KC_BACKSPACE ),\
+ _D( KC_ESC ),\
+ _D( KC_CTRL_Z ),\
+ _D( KC_CTRL_A ),\
+ _D( KC_CTRL_E ),\
+ _D( KC_CTRL_C ),\
+ _D( KC_CTRL_T ),\
+ _D( KC_CTRL_U ),\
+ _D( KC_CTRL_K ),\
+ _D( KC_DEL ),\
+ _D( KC_UNKNOWN )
+
+// Terminal input functions
+// Keyboard codes
+#define _D( x ) x
+
+enum
+{
+ term_dummy = 255,
+ TERM_KEYCODES,
+ TERM_FIRST_KEY = KC_UP,
+ TERM_LAST_KEY = KC_UNKNOWN
+};
+
+#endif // #ifndef __TERM_H__
diff --git a/fw/User/shell/type.h b/fw/User/shell/type.h
new file mode 100644
index 0000000..4d7410b
--- /dev/null
+++ b/fw/User/shell/type.h
@@ -0,0 +1,5 @@
+// Type definitions for desktop platform
+#ifndef __TYPE_H__
+#define __TYPE_H__
+
+#endif
diff --git a/fw/User/spiffs/.travis.yml b/fw/User/spiffs/.travis.yml
new file mode 100644
index 0000000..fe7cb23
--- /dev/null
+++ b/fw/User/spiffs/.travis.yml
@@ -0,0 +1,8 @@
+language: c
+
+compiler:
+ - gcc
+
+before_script:
+
+script: make all && make clean && make test && make build-all
diff --git a/fw/User/spiffs/LICENSE b/fw/User/spiffs/LICENSE
new file mode 100644
index 0000000..c32f3f0
--- /dev/null
+++ b/fw/User/spiffs/LICENSE
@@ -0,0 +1,20 @@
+The MIT License (MIT)
+
+Copyright (c) 2013-2016 Peter Andersson (pelleplutt1976gmail.com)
+
+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.
diff --git a/fw/User/spiffs/README.md b/fw/User/spiffs/README.md
new file mode 100644
index 0000000..63ab3f6
--- /dev/null
+++ b/fw/User/spiffs/README.md
@@ -0,0 +1,186 @@
+# SPIFFS (SPI Flash File System)
+**V0.3.6**
+
+[](https://travis-ci.org/pellepl/spiffs)
+
+Copyright (c) 2013-2016 Peter Andersson (pelleplutt1976 at gmail.com)
+
+For legal stuff, see [LICENSE](https://github.com/pellepl/spiffs/blob/master/LICENSE). Basically, you may do whatever you want with the source. Use, modify, sell, print it out, roll it and smoke it - as long as I won't be held responsible.
+
+Love to hear feedback though!
+
+
+## INTRODUCTION
+
+Spiffs is a file system intended for SPI NOR flash devices on embedded targets.
+
+Spiffs is designed with following characteristics in mind:
+ - Small (embedded) targets, sparse RAM without heap
+ - Only big areas of data (blocks) can be erased
+ - An erase will reset all bits in block to ones
+ - Writing pulls one to zeroes
+ - Zeroes can only be pulled to ones by erase
+ - Wear leveling
+
+
+## FEATURES
+
+What spiffs does:
+ - Specifically designed for low ram usage
+ - Uses statically sized ram buffers, independent of number of files
+ - Posix-like api: open, close, read, write, seek, stat, etc
+ - It can run on any NOR flash, not only SPI flash - theoretically also on embedded flash of a microprocessor
+ - Multiple spiffs configurations can run on same target - and even on same SPI flash device
+ - Implements static wear leveling
+ - Built in file system consistency checks
+ - Highly configurable
+
+What spiffs does not:
+ - Presently, spiffs does not support directories. It produces a flat structure. Creating a file with path *tmp/myfile.txt* will create a file called *tmp/myfile.txt* instead of a *myfile.txt* under directory *tmp*.
+ - It is not a realtime stack. One write operation might last much longer than another.
+ - Poor scalability. Spiffs is intended for small memory devices - the normal sizes for SPI flashes. Going beyond ~128Mbyte is probably a bad idea. This is a side effect of the design goal to use as little ram as possible.
+ - Presently, it does not detect or handle bad blocks.
+ - One configuration, one binary. There's no generic spiffs binary that handles all types of configurations.
+
+
+## MORE INFO
+
+See the [wiki](https://github.com/pellepl/spiffs/wiki) for [configuring](https://github.com/pellepl/spiffs/wiki/Configure-spiffs), [integrating](https://github.com/pellepl/spiffs/wiki/Integrate-spiffs), [using](https://github.com/pellepl/spiffs/wiki/Using-spiffs), and [optimizing](https://github.com/pellepl/spiffs/wiki/Performance-and-Optimizing) spiffs.
+
+For design, see [docs/TECH_SPEC](https://github.com/pellepl/spiffs/blob/master/docs/TECH_SPEC).
+
+For a generic spi flash driver, see [this](https://github.com/pellepl/spiflash_driver).
+
+## HISTORY
+
+### 0.3.6
+- Fix range bug in index memory mapping #98
+- Add index memory mapping #97
+- Optimize SPIFFS_read for large files #96
+- Add temporal cache for opening files #95
+- More robust gc #93 (thanks @dismirlian)
+- Fixed a double write of same data in certain cache situations
+- Fixed an open bug in READ_ONLY builds
+- File not visible in SPIFFS_readdir #90 (thanks @benpicco-tmp)
+- Cache load code cleanup #92 (thanks @niclash)
+- Fixed lock/unlock asymmetry #88 #87 (thanks @JackJefferson, @dpruessner)
+- Testframe updates
+
+New API functions:
+- `SPIFFS_ix_map` - map index meta data to memory for a file
+- `SPIFFS_ix_unmap` - unmaps index meta data for a file
+- `SPIFFS_ix_remap` - changes file offset for index metadata map
+- `SPIFFS_bytes_to_ix_map_entries` - utility, get length of needed vector for given amount of bytes
+- `SPIFFS_ix_map_entries_to_bytes` - utility, get number of bytes a vector can represent given length
+
+New config defines:
+- `SPIFFS_IX_MAP` - enable possibility to map index meta data to memory for reading faster
+- `SPIFFS_TEMPORAL_FD_CACHE` - enable temporal cache for opening files faster
+- `SPIFFS_TEMPORAL_CACHE_HIT_SCORE` - for tuning the temporal cache
+
+### 0.3.5
+- Fixed a bug in fs check
+- API returns actual error codes #84) (thanks @Nails)
+- Fix compiler warnings for non-gcc #83 #81 (thanks @Nails)
+- Unable to recover from full fs #82 (thanks @rojer)
+- Define SPIFFS_O_* flags #80
+- Problem with long filenames #79 (thanks @psjg)
+- Duplicate file name bug fix #74 (thanks @igrr)
+- SPIFFS_eof and SPIFFS_tell return wrong value #72 (thanks @ArtemPisarenko)
+- Bunch of testframe updates #77 #78 #86 (thanks @dpreussner, @psjg a.o)
+
+### 0.3.4
+- Added user callback file func.
+- Fixed a stat bug with obj id.
+- SPIFFS_probe_fs added
+- Add possibility to compile a read-only version of spiffs
+- Make magic dependent on fs length, if needed (see #59 & #66) (thanks @hreintke)
+- Exposed SPIFFS_open_by_page_function
+- Zero-size file cannot be seek #57 (thanks @lishen2)
+- Add tell and eof functions #54 (thanks @raburton)
+- Make api string params const #53 (thanks @raburton)
+- Preserve user_data during mount() #51 (thanks @rojer)
+
+New API functions:
+- `SPIFFS_set_file_callback_func` - register a callback informing about file events
+- `SPIFFS_probe_fs` - probe a spi flash trying to figure out size of fs
+- `SPIFFS_open_by_page` - open a file by page index
+- `SPIFFS_eof` - checks if end of file is reached
+- `SPIFFS_tell` - returns current file offset
+
+New config defines:
+- `SPIFFS_READ_ONLY`
+- `SPIFFS_USE_MAGIC_LENGTH`
+
+### 0.3.3
+**Might not be compatible with 0.3.2 structures. See issue #40**
+- Possibility to add integer offset to file handles
+- Truncate function presumes too few free pages #49
+- Bug in truncate function #48 (thanks @PawelDefee)
+- Update spiffs_gc.c - remove unnecessary parameter (thanks @PawelDefee)
+- Update INTEGRATION docs (thanks @PawelDefee)
+- Fix pointer truncation in 64-bit platforms (thanks @igrr)
+- Zero-sized files cannot be read #44 (thanks @rojer)
+- (More) correct calculation of max_id in obj_lu_find #42 #41 (thanks @lishen2)
+- Check correct error code in obj_lu_find_free #41 (thanks @lishen2)
+- Moar comments for SPIFFS_lseek (thanks @igrr)
+- Fixed padding in spiffs_page_object_ix #40 (thanks @jmattsson @lishen2)
+- Fixed gc_quick test (thanks @jmattsson)
+- Add SPIFFS_EXCL flag #36
+- SPIFFS_close may fail silently if cache is enabled #37
+- User data in callbacks #34
+- Ignoring SINGLETON build in cache setup (thanks Luca)
+- Compilation error fixed #32 (thanks @chotasanjiv)
+- Align cand_scores (thanks @hefloryd)
+- Fix build warnings when SPIFFS_CACHE is 0 (thanks @ajaybhargav)
+
+New config defines:
+- `SPIFFS_FILEHDL_OFFSET`
+
+### 0.3.2
+- Limit cache size if too much cache is given (thanks pgeiem)
+- New feature - Controlled erase. #23
+- SPIFFS_rename leaks file descriptors #28 (thanks benpicco)
+- moved dbg print defines in test framework to params_test.h
+- lseek should return the resulting offset (thanks hefloryd)
+- fixed type on dbg ifdefs
+- silence warning about signed/unsigned comparison when spiffs_obj_id is 32 bit (thanks benpicco)
+- Possible error in test_spiffs.c #21 (thanks yihcdaso-yeskela)
+- Cache might writethrough too often #16
+- even moar testrunner updates
+- Test framework update and some added tests
+- Some thoughts for next gen
+- Test sigsevs when having too many sectors #13 (thanks alonewolfx2)
+- GC might be suboptimal #11
+- Fix eternal readdir when objheader at last block, last entry
+
+New API functions:
+- `SPIFFS_gc_quick` - call a nonintrusive gc
+- `SPIFFS_gc` - call a full-scale intrusive gc
+
+### 0.3.1
+- Removed two return warnings, was too triggerhappy on release
+
+### 0.3.0
+- Added existing namecheck when creating files
+- Lots of static analysis bugs #6
+- Added rename func
+- Fix SPIFFS_read length when reading beyond file size
+- Added reading beyond file length testcase
+- Made build a bit more configurable
+- Changed name in spiffs from "errno" to "err_code" due to conflicts compiling in mingw
+- Improved GC checks, fixed an append bug, more robust truncate for very special case
+- GC checks preempts GC, truncate even less picky
+- Struct alignment needed for some targets, define in spiffs config #10
+- Spiffs filesystem magic, definable in config
+
+New config defines:
+- `SPIFFS_USE_MAGIC` - enable or disable magic check upon mount
+- `SPIFFS_ALIGNED_OBJECT_INDEX_TABLES` - alignment for certain targets
+
+New API functions:
+- `SPIFFS_rename` - rename files
+- `SPIFFS_clearerr` - clears last errno
+- `SPIFFS_info` - returns info on used and total bytes in fs
+- `SPIFFS_format` - formats the filesystem
+- `SPIFFS_mounted` - checks if filesystem is mounted
diff --git a/fw/User/spiffs/docs/TECH_SPEC b/fw/User/spiffs/docs/TECH_SPEC
new file mode 100644
index 0000000..b4755a6
--- /dev/null
+++ b/fw/User/spiffs/docs/TECH_SPEC
@@ -0,0 +1,239 @@
+* USING SPIFFS
+
+TODO
+
+
+* SPIFFS DESIGN
+
+Spiffs is inspired by YAFFS. However, YAFFS is designed for NAND flashes, and
+for bigger targets with much more ram. Nevertheless, many wise thoughts have
+been borrowed from YAFFS when writing spiffs. Kudos!
+
+The main complication writing spiffs was that it cannot be assumed the target
+has a heap. Spiffs must go along only with the work ram buffer given to it.
+This forces extra implementation on many areas of spiffs.
+
+
+** SPI flash devices using NOR technology
+
+Below is a small description of how SPI flashes work internally. This is to
+give an understanding of the design choices made in spiffs.
+
+SPI flash devices are physically divided in blocks. On some SPI flash devices,
+blocks are further divided into sectors. Datasheets sometimes name blocks as
+sectors and vice versa.
+
+Common memory capacaties for SPI flashes are 512kB up to 8MB of data, where
+blocks may be 64kB. Sectors can be e.g. 4kB, if supported. Many SPI flashes
+have uniform block sizes, whereas others have non-uniform - the latter meaning
+that e.g. the first 16 blocks are 4kB big, and the rest are 64kB.
+
+The entire memory is linear and can be read and written in random access.
+Erasing can only be done block- or sectorwise; or by mass erase.
+
+SPI flashes can normally be erased from 100.000 up to 1.000.000 cycles before
+they fail.
+
+A clean SPI flash from factory have all bits in entire memory set to one. A
+mass erase will reset the device to this state. Block or sector erasing will
+put the all bits in the area given by the sector or block to ones. Writing to a
+NOR flash pulls ones to zeroes. Writing 0xFF to an address is simply a no-op.
+
+Writing 0b10101010 to a flash address holding 0b00001111 will yield 0b00001010.
+
+This way of "write by nand" is used considerably in spiffs.
+
+Common characteristics of NOR flashes are quick reads, but slow writes.
+
+And finally, unlike NAND flashes, NOR flashes seem to not need any error
+correction. They always write correctly I gather.
+
+
+** Spiffs logical structure
+
+Some terminology before proceeding. Physical blocks/sectors means sizes stated
+in the datasheet. Logical blocks and pages is something the integrator choose.
+
+
+** Blocks and pages
+
+Spiffs is allocated to a part or all of the memory of the SPI flash device.
+This area is divided into logical blocks, which in turn are divided into
+logical pages. The boundary of a logical block must coincide with one or more
+physical blocks. The sizes for logical blocks and logical pages always remain
+the same, they are uniform.
+
+Example: non-uniform flash mapped to spiffs with 128kB logical blocks
+
+PHYSICAL FLASH BLOCKS SPIFFS LOGICAL BLOCKS: 128kB
+
++-----------------------+ - - - +-----------------------+
+| Block 1 : 16kB | | Block 1 : 128kB |
++-----------------------+ | |
+| Block 2 : 16kB | | |
++-----------------------+ | |
+| Block 3 : 16kB | | |
++-----------------------+ | |
+| Block 4 : 16kB | | |
++-----------------------+ | |
+| Block 5 : 64kB | | |
++-----------------------+ - - - +-----------------------+
+| Block 6 : 64kB | | Block 2 : 128kB |
++-----------------------+ | |
+| Block 7 : 64kB | | |
++-----------------------+ - - - +-----------------------+
+| Block 8 : 64kB | | Block 3 : 128kB |
++-----------------------+ | |
+| Block 9 : 64kB | | |
++-----------------------+ - - - +-----------------------+
+| ... | | ... |
+
+A logical block is divided further into a number of logical pages. A page
+defines the smallest data holding element known to spiffs. Hence, if a file
+is created being one byte big, it will occupy one page for index and one page
+for data - it will occupy 2 x size of a logical page on flash.
+So it seems it is good to select a small page size.
+
+Each page has a metadata header being normally 5 to 9 bytes. This said, a very
+small page size will make metadata occupy a lot of the memory on the flash. A
+page size of 64 bytes will waste 8-14% on metadata, while 256 bytes 2-4%.
+So it seems it is good to select a big page size.
+
+Also, spiffs uses a ram buffer being two times the page size. This ram buffer
+is used for loading and manipulating pages, but it is also used for algorithms
+to find free file ids, scanning the file system, etc. Having too small a page
+size means less work buffer for spiffs, ending up in more reads operations and
+eventually gives a slower file system.
+
+Choosing the page size for the system involves many factors:
+ - How big is the logical block size
+ - What is the normal size of most files
+ - How much ram can be spent
+ - How much data (vs metadata) must be crammed into the file system
+ - How fast must spiffs be
+ - Other things impossible to find out
+
+So, chosing the Optimal Page Size (tm) seems tricky, to say the least. Don't
+fret - there is no optimal page size. This varies from how the target will use
+spiffs. Use the golden rule:
+
+ ~~~ Logical Page Size = Logical Block Size / 256 ~~~
+
+This is a good starting point. The final page size can then be derived through
+heuristical experimenting for us non-analytical minds.
+
+
+** Objects, indices and look-ups
+
+A file, or an object as called in spiffs, is identified by an object id.
+Another YAFFS rip-off. This object id is a part of the page header. So, all
+pages know to which object/file they belong - not counting the free pages.
+
+An object is made up of two types of pages: object index pages and data pages.
+Data pages contain the data written by user. Index pages contain metadata about
+the object, more specifically what data pages are part of the object.
+
+The page header also includes something called a span index. Let's say a file
+is written covering three data pages. The first data page will then have span
+index 0, the second span index 1, and the last data page will have span index
+2. Simple as that.
+
+Finally, each page header contain flags, telling if the page is used,
+deleted, finalized, holds index or data, and more.
+
+Object indices also have span indices, where an object index with span index 0
+is referred to as the object index header. This page does not only contain
+references to data pages, but also extra info such as object name, object size
+in bytes, flags for file or directory, etc.
+
+If one were to create a file covering three data pages, named e.g.
+"spandex-joke.txt", given object id 12, it could look like this:
+
+PAGE 0
+
+PAGE 1 page header: [obj_id:12 span_ix:0 flags:USED|DATA]
+
+
+PAGE 2 page header: [obj_id:12 span_ix:1 flags:USED|DATA]
+
+
+PAGE 3 page header: [obj_id:545 span_ix:13 flags:USED|DATA]
+
+
+PAGE 4 page header: [obj_id:12 span_ix:2 flags:USED|DATA]
+
+
+PAGE 5 page header: [obj_id:12 span_ix:0 flags:USED|INDEX]
+ obj ix header: [name:spandex-joke.txt size:600 bytes flags:FILE]
+ obj ix: [1 2 4]
+
+Looking in detail at page 5, the object index header page, the object index
+array refers to each data page in order, as mentioned before. The index of the
+object index array correlates with the data page span index.
+
+ entry ix: 0 1 2
+ obj ix: [1 2 4]
+ | | |
+ PAGE 1, DATA, SPAN_IX 0 --------/ | |
+ PAGE 2, DATA, SPAN_IX 1 --------/ |
+ PAGE 4, DATA, SPAN_IX 2 --------/
+
+Things to be unveiled in page 0 - well.. Spiffs is designed for systems low on
+ram. We cannot keep a dynamic list on the whereabouts of each object index
+header so we can find a file fast. There might not even be a heap! But, we do
+not want to scan all page headers on the flash to find the object index header.
+
+The first page(s) of each block contains the so called object look-up. These
+are not normal pages, they do not have a header. Instead, they are arrays
+pointing out what object-id the rest of all pages in the block belongs to.
+
+By this look-up, only the first page(s) in each block must to scanned to find
+the actual page which contains the object index header of the desired object.
+
+The object lookup is redundant metadata. The assumption is that it presents
+less overhead reading a full page of data to memory from each block and search
+that, instead of reading a small amount of data from each page (i.e. the page
+header) in all blocks. Each read operation from SPI flash normally contains
+extra data as the read command itself and the flash address. Also, depending on
+the underlying implementation, other criterions may need to be passed for each
+read transaction, like mutexes and such.
+
+The veiled example unveiled would look like this, with some extra pages:
+
+PAGE 0 [ 12 12 545 12 12 34 34 4 0 0 0 0 ...]
+PAGE 1 page header: [obj_id:12 span_ix:0 flags:USED|DATA] ...
+PAGE 2 page header: [obj_id:12 span_ix:1 flags:USED|DATA] ...
+PAGE 3 page header: [obj_id:545 span_ix:13 flags:USED|DATA] ...
+PAGE 4 page header: [obj_id:12 span_ix:2 flags:USED|DATA] ...
+PAGE 5 page header: [obj_id:12 span_ix:0 flags:USED|INDEX] ...
+PAGE 6 page header: [obj_id:34 span_ix:0 flags:USED|DATA] ...
+PAGE 7 page header: [obj_id:34 span_ix:1 flags:USED|DATA] ...
+PAGE 8 page header: [obj_id:4 span_ix:1 flags:USED|INDEX] ...
+PAGE 9 page header: [obj_id:23 span_ix:0 flags:DELETED|INDEX] ...
+PAGE 10 page header: [obj_id:23 span_ix:0 flags:DELETED|DATA] ...
+PAGE 11 page header: [obj_id:23 span_ix:1 flags:DELETED|DATA] ...
+PAGE 12 page header: [obj_id:23 span_ix:2 flags:DELETED|DATA] ...
+...
+
+Ok, so why are page 9 to 12 marked as 0 when they belong to object id 23? These
+pages are deleted, so this is marked both in page header flags and in the look
+up. This is an example where spiffs uses NOR flashes "nand-way" of writing.
+
+As a matter of fact, there are two object id's which are special:
+
+obj id 0 (all bits zeroes) - indicates a deleted page in object look up
+obj id 0xff.. (all bits ones) - indicates a free page in object look up
+
+Actually, the object id's have another quirk: if the most significant bit is
+set, this indicates an object index page. If the most significant bit is zero,
+this indicates a data page. So to be fully correct, page 0 in above example
+would look like this:
+
+PAGE 0 [ 12 12 545 12 *12 34 34 *4 0 0 0 0 ...]
+
+where the asterisk means the msb of the object id is set.
+
+This is another way to speed up the searches when looking for object indices.
+By looking on the object id's msb in the object lookup, it is also possible
+to find out whether the page is an object index page or a data page.
+
diff --git a/fw/User/spiffs/docs/TODO b/fw/User/spiffs/docs/TODO
new file mode 100644
index 0000000..c947316
--- /dev/null
+++ b/fw/User/spiffs/docs/TODO
@@ -0,0 +1,15 @@
+* When mending lost pages, also see if they fit into length specified in object index header
+
+SPIFFS2 thoughts
+
+* Instead of exact object id:s in the object lookup tables, use a hash of span index and object id.
+ Eg. object id xor:ed with bit-reversed span index.
+ This should decrease number of actual pages that needs to be visited when looking thru the obj lut.
+
+* Logical number of each block. When moving stuff in a garbage collected page, the free
+ page is assigned the same number as the garbage collected. Thus, object index pages do not have to
+ be rewritten.
+
+* Steal one page, use as a bit parity page. When starting an fs modification operation, write one bit
+ as zero. When ending, write another bit as zero. On mount, if number of zeroes in page is uneven, a
+ check is automatically run.
\ No newline at end of file
diff --git a/fw/User/spiffs/files.mk b/fw/User/spiffs/files.mk
new file mode 100644
index 0000000..631ec7e
--- /dev/null
+++ b/fw/User/spiffs/files.mk
@@ -0,0 +1,12 @@
+ifndef spiffs
+$(warn defaulting path to generic spiffs module, spiffs variable not set)
+spiffs = ../generic/spiffs
+endif
+FLAGS += -DCONFIG_BUILD_SPIFFS
+INC += -I${spiffs}/src
+CPATH += ${spiffs}/src
+CFILES += spiffs_nucleus.c
+CFILES += spiffs_gc.c
+CFILES += spiffs_hydrogen.c
+CFILES += spiffs_cache.c
+CFILES += spiffs_check.c
diff --git a/fw/User/spiffs/makefile b/fw/User/spiffs/makefile
new file mode 100644
index 0000000..13ebd96
--- /dev/null
+++ b/fw/User/spiffs/makefile
@@ -0,0 +1,162 @@
+BINARY = linux_spiffs_test
+
+############
+#
+# Paths
+#
+############
+
+sourcedir = src
+builddir = build
+
+
+#############
+#
+# Build tools
+#
+#############
+
+CC = gcc $(COMPILEROPTIONS)
+LD = ld
+GDB = gdb
+OBJCOPY = objcopy
+OBJDUMP = objdump
+MKDIR = mkdir -p
+
+###############
+#
+# Files and libs
+#
+###############
+
+NO_TEST ?= 0
+CFLAGS = $(FLAGS)
+ifeq (1, $(strip $(NO_TEST)))
+CFILES_TEST = main.c
+CFLAGS += -DNO_TEST -Werror
+else
+CFILES_TEST = main.c \
+ test_spiffs.c \
+ test_dev.c \
+ test_check.c \
+ test_hydrogen.c \
+ test_bugreports.c \
+ testsuites.c \
+ testrunner.c
+endif
+include files.mk
+INCLUDE_DIRECTIVES = -I./${sourcedir} -I./${sourcedir}/default -I./${sourcedir}/test
+COMPILEROPTIONS = $(INCLUDE_DIRECTIVES)
+
+COMPILEROPTIONS_APP = \
+-Wall -Wno-format-y2k -W -Wstrict-prototypes -Wmissing-prototypes \
+-Wpointer-arith -Wreturn-type -Wcast-qual -Wwrite-strings -Wswitch \
+-Wshadow -Wcast-align -Wchar-subscripts -Winline -Wnested-externs\
+-Wredundant-decls
+
+############
+#
+# Tasks
+#
+############
+
+vpath %.c ${sourcedir} ${sourcedir}/default ${sourcedir}/test
+
+OBJFILES = $(CFILES:%.c=${builddir}/%.o)
+OBJFILES_TEST = $(CFILES_TEST:%.c=${builddir}/%.o)
+
+DEPFILES = $(CFILES:%.c=${builddir}/%.d) $(CFILES_TEST:%.c=${builddir}/%.d)
+
+ALLOBJFILES += $(OBJFILES) $(OBJFILES_TEST)
+
+DEPENDENCIES = $(DEPFILES)
+
+# link object files, create binary
+$(BINARY): $(ALLOBJFILES)
+ @echo "... linking"
+ @${CC} $(LINKEROPTIONS) -o ${builddir}/$(BINARY) $(ALLOBJFILES) $(LIBS)
+ifeq (1, $(strip $(NO_TEST)))
+ @echo "size: `du -b ${builddir}/${BINARY} | sed 's/\([0-9]*\).*/\1/g '` bytes"
+endif
+
+
+-include $(DEPENDENCIES)
+
+# compile c files
+$(OBJFILES) : ${builddir}/%.o:%.c
+ @echo "... compile $@"
+ @${CC} $(COMPILEROPTIONS_APP) $(CFLAGS) -g -c -o $@ $<
+
+$(OBJFILES_TEST) : ${builddir}/%.o:%.c
+ @echo "... compile $@"
+ @${CC} $(CFLAGS) -g -c -o $@ $<
+
+# make dependencies
+# @echo "... depend $@";
+$(DEPFILES) : ${builddir}/%.d:%.c
+ @rm -f $@; \
+ ${CC} $(COMPILEROPTIONS) -M $< > $@.$$$$; \
+ sed 's,\($*\)\.o[ :]*, ${builddir}/\1.o $@ : ,g' < $@.$$$$ > $@; \
+ rm -f $@.$$$$
+
+all: mkdirs $(BINARY)
+
+mkdirs:
+ -@${MKDIR} ${builddir}
+ -@${MKDIR} test_data
+
+FILTER ?=
+
+test: $(BINARY)
+ifdef $(FILTER)
+ ./build/$(BINARY)
+else
+ ./build/$(BINARY) -f $(FILTER)
+endif
+
+test_failed: $(BINARY)
+ ./build/$(BINARY) _tests_fail
+
+clean:
+ @echo ... removing build files in ${builddir}
+ @rm -f ${builddir}/*.o
+ @rm -f ${builddir}/*.d
+ @rm -f ${builddir}/*.elf
+
+ONOFF = 1 0
+OFFON = 0 1
+build-all:
+ @for rdonly in $(ONOFF); do \
+ for singleton in $(ONOFF); do \
+ for hal_cb_xtra in $(OFFON); do \
+ for cache in $(OFFON); do \
+ for magic in $(OFFON); do \
+ for temporal_cache in $(OFFON); do \
+ for ix_map in $(OFFON); do \
+ echo; \
+ echo ============================================================; \
+ echo SPIFFS_READ_ONLY=$$rdonly; \
+ echo SPIFFS_SINGLETON=$$singleton; \
+ echo SPIFFS_HAL_CALLBACK_EXTRA=$$hal_cb_xtra; \
+ echo SPIFFS_CACHE, SPIFFS_CACHE_WR=$$cache; \
+ echo SPIFFS_USE_MAGIC, SPIFFS_USE_MAGIC_LENGTH=$$magic; \
+ echo SPIFFS_TEMPORAL_FD_CACHE=$$temporal_cache; \
+ echo SPIFFS_IX_MAP=$$ix_map; \
+ $(MAKE) clean && $(MAKE) FLAGS="\
+ -DSPIFFS_HAL_CALLBACK_EXTRA=$$hal_cb_xtra \
+ -DSPIFFS_SINGLETON=$$singleton \
+ -DSPIFFS_CACHE=$$cache \
+ -DSPIFFS_CACHE_WR=$$cache \
+ -DSPIFFS_READ_ONLY=$$rdonly \
+ -DSPIFFS_USE_MAGIC=$$magic \
+ -DSPIFFS_USE_MAGIC_LENGTH=$$magic \
+ -DSPIFFS_TEMPORAL_FD_CACHE=$$temporal_cache \
+ -DSPIFFS_IX_MAP=$$ix_map \
+ " NO_TEST=1; \
+ done || exit 1; \
+ done \
+ done \
+ done \
+ done \
+ done \
+ done
diff --git a/fw/User/spiffs/src/default/spiffs_config.h b/fw/User/spiffs/src/default/spiffs_config.h
new file mode 100644
index 0000000..a6c901b
--- /dev/null
+++ b/fw/User/spiffs/src/default/spiffs_config.h
@@ -0,0 +1,213 @@
+
+#ifndef SPIFFS_CONFIG_H_
+#define SPIFFS_CONFIG_H_
+
+// Following includes are for the linux test build of spiffs
+// These may/should/must be removed/altered/replaced in your target
+#include
+#include
+#include
+#include
+#include
+
+#include "SEGGER_RTT.h"
+
+// Set generic spiffs debug output call.
+#ifndef SPIFFS_DBG
+#define SPIFFS_DBG(...) SEGGER_RTT_printf(__VA_ARGS__)
+#endif
+// Set spiffs debug output call for garbage collecting.
+#ifndef SPIFFS_GC_DBG
+#define SPIFFS_GC_DBG(...) SEGGER_RTT_printf(__VA_ARGS__)
+#endif
+// Set spiffs debug output call for caching.
+#ifndef SPIFFS_CACHE_DBG
+#define SPIFFS_CACHE_DBG(...) SEGGER_RTT_printf(__VA_ARGS__)
+#endif
+// Set spiffs debug output call for system consistency checks.
+#ifndef SPIFFS_CHECK_DBG
+#define SPIFFS_CHECK_DBG(...) SEGGER_RTT_printf(__VA_ARGS__)
+#endif
+
+// Enable/disable API functions to determine exact number of bytes
+// for filedescriptor and cache buffers. Once decided for a configuration,
+// this can be disabled to reduce flash.
+#ifndef SPIFFS_BUFFER_HELP
+#define SPIFFS_BUFFER_HELP 0
+#endif
+
+// Enables/disable memory read caching of nucleus file system operations.
+// If enabled, memory area must be provided for cache in SPIFFS_mount.
+#ifndef SPIFFS_CACHE
+#define SPIFFS_CACHE 1
+#endif
+#if SPIFFS_CACHE
+// Enables memory write caching for file descriptors in hydrogen
+#ifndef SPIFFS_CACHE_WR
+#define SPIFFS_CACHE_WR 0
+#endif
+
+// Enable/disable statistics on caching. Debug/test purpose only.
+#ifndef SPIFFS_CACHE_STATS
+#define SPIFFS_CACHE_STATS 0
+#endif
+#endif
+
+// Always check header of each accessed page to ensure consistent state.
+// If enabled it will increase number of reads, will increase flash.
+#ifndef SPIFFS_PAGE_CHECK
+#define SPIFFS_PAGE_CHECK 3
+#endif
+
+// Define maximum number of gc runs to perform to reach desired free pages.
+#ifndef SPIFFS_GC_MAX_RUNS
+#define SPIFFS_GC_MAX_RUNS 3
+#endif
+
+// Enable/disable statistics on gc. Debug/test purpose only.
+#ifndef SPIFFS_GC_STATS
+#define SPIFFS_GC_STATS 0
+#endif
+
+// Garbage collecting examines all pages in a block which and sums up
+// to a block score. Deleted pages normally gives positive score and
+// used pages normally gives a negative score (as these must be moved).
+// To have a fair wear-leveling, the erase age is also included in score,
+// whose factor normally is the most positive.
+// The larger the score, the more likely it is that the block will
+// picked for garbage collection.
+
+// Garbage collecting heuristics - weight used for deleted pages.
+#ifndef SPIFFS_GC_HEUR_W_DELET
+#define SPIFFS_GC_HEUR_W_DELET (5)
+#endif
+// Garbage collecting heuristics - weight used for used pages.
+#ifndef SPIFFS_GC_HEUR_W_USED
+#define SPIFFS_GC_HEUR_W_USED (-1)
+#endif
+// Garbage collecting heuristics - weight used for time between
+// last erased and erase of this block.
+#ifndef SPIFFS_GC_HEUR_W_ERASE_AGE
+#define SPIFFS_GC_HEUR_W_ERASE_AGE (50)
+#endif
+
+// Object name maximum length.
+#ifndef SPIFFS_OBJ_NAME_LEN
+#define SPIFFS_OBJ_NAME_LEN (32)
+#endif
+
+// Size of buffer allocated on stack used when copying data.
+// Lower value generates more read/writes. No meaning having it bigger
+// than logical page size.
+#ifndef SPIFFS_COPY_BUFFER_STACK
+#define SPIFFS_COPY_BUFFER_STACK (64)
+#endif
+
+// Enable this to have an identifiable spiffs filesystem. This will look for
+// a magic in all sectors to determine if this is a valid spiffs system or
+// not on mount point. If not, SPIFFS_format must be called prior to mounting
+// again.
+#ifndef SPIFFS_USE_MAGIC
+#define SPIFFS_USE_MAGIC (1)
+#endif
+
+#if SPIFFS_USE_MAGIC
+// Only valid when SPIFFS_USE_MAGIC is enabled. If SPIFFS_USE_MAGIC_LENGTH is
+// enabled, the magic will also be dependent on the length of the filesystem.
+// For example, a filesystem configured and formatted for 4 megabytes will not
+// be accepted for mounting with a configuration defining the filesystem as 2
+// megabytes.
+#ifndef SPIFFS_USE_MAGIC_LENGTH
+#define SPIFFS_USE_MAGIC_LENGTH (1)
+#endif
+#endif
+
+// SPIFFS_LOCK and SPIFFS_UNLOCK protects spiffs from reentrancy on api level
+// These should be defined on a multithreaded system
+
+// define this to entering a mutex if you're running on a multithreaded system
+#ifndef SPIFFS_LOCK
+#define SPIFFS_LOCK(fs)
+#endif
+// define this to exiting a mutex if you're running on a multithreaded system
+#ifndef SPIFFS_UNLOCK
+#define SPIFFS_UNLOCK(fs)
+#endif
+
+
+// Enable if only one spiffs instance with constant configuration will exist
+// on the target. This will reduce calculations, flash and memory accesses.
+// Parts of configuration must be defined below instead of at time of mount.
+#ifndef SPIFFS_SINGLETON
+#define SPIFFS_SINGLETON 1
+#endif
+
+#if SPIFFS_SINGLETON
+//// Instead of giving parameters in config struct, singleton build must
+//// give parameters in defines below.
+#ifndef SPIFFS_CFG_PHYS_SZ
+#define SPIFFS_CFG_PHYS_SZ(ignore) (1024*1024*16)
+#endif
+#ifndef SPIFFS_CFG_PHYS_ERASE_SZ
+#define SPIFFS_CFG_PHYS_ERASE_SZ(ignore) (4096)
+#endif
+#ifndef SPIFFS_CFG_PHYS_ADDR
+#define SPIFFS_CFG_PHYS_ADDR(ignore) (0)
+#endif
+#ifndef SPIFFS_CFG_LOG_PAGE_SZ
+#define SPIFFS_CFG_LOG_PAGE_SZ(ignore) (256)
+#endif
+#ifndef SPIFFS_CFG_LOG_BLOCK_SZ
+#define SPIFFS_CFG_LOG_BLOCK_SZ(ignore) (65536)
+#endif
+#endif
+
+//// Set SPFIFS_TEST_VISUALISATION to non-zero to enable SPIFFS_vis function
+//// in the api. This function will visualize all filesystem using given printf
+//// function.
+#ifndef SPIFFS_TEST_VISUALISATION
+#define SPIFFS_TEST_VISUALISATION 0
+#endif
+#if SPIFFS_TEST_VISUALISATION
+#ifndef spiffs_printf
+#define spiffs_printf(...) printf(__VA_ARGS__)
+#endif
+// spiffs_printf argument for a free page
+#ifndef SPIFFS_TEST_VIS_FREE_STR
+#define SPIFFS_TEST_VIS_FREE_STR "_"
+#endif
+// spiffs_printf argument for a deleted page
+#ifndef SPIFFS_TEST_VIS_DELE_STR
+#define SPIFFS_TEST_VIS_DELE_STR "/"
+#endif
+// spiffs_printf argument for an index page for given object id
+#ifndef SPIFFS_TEST_VIS_INDX_STR
+#define SPIFFS_TEST_VIS_INDX_STR(id) "i"
+#endif
+// spiffs_printf argument for a data page for given object id
+#ifndef SPIFFS_TEST_VIS_DATA_STR
+#define SPIFFS_TEST_VIS_DATA_STR(id) "d"
+#endif
+#endif
+
+// Types depending on configuration such as the amount of flash bytes
+// given to spiffs file system in total (spiffs_file_system_size),
+// the logical block size (log_block_size), and the logical page size
+// (log_page_size)
+
+// Block index type. Make sure the size of this type can hold
+// the highest number of all blocks - i.e. spiffs_file_system_size / log_block_size
+typedef uint16_t spiffs_block_ix;
+// Page index type. Make sure the size of this type can hold
+// the highest page number of all pages - i.e. spiffs_file_system_size / log_page_size
+typedef uint16_t spiffs_page_ix;
+// Object id type - most significant bit is reserved for index flag. Make sure the
+// size of this type can hold the highest object id on a full system,
+// i.e. 2 + (spiffs_file_system_size / (2*log_page_size))*2
+typedef uint16_t spiffs_obj_id;
+// Object span index type. Make sure the size of this type can
+// hold the largest possible span index on the system -
+// i.e. (spiffs_file_system_size / log_page_size) - 1
+typedef uint16_t spiffs_span_ix;
+
+#endif /* SPIFFS_CONFIG_H_ */
diff --git a/fw/User/spiffs/src/spiffs.h b/fw/User/spiffs/src/spiffs.h
new file mode 100644
index 0000000..f7a8020
--- /dev/null
+++ b/fw/User/spiffs/src/spiffs.h
@@ -0,0 +1,789 @@
+/*
+ * spiffs.h
+ *
+ * Created on: May 26, 2013
+ * Author: petera
+ */
+
+#ifndef SPIFFS_H_
+#define SPIFFS_H_
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
+#include "spiffs_config.h"
+
+#define SPIFFS_OK 0
+#define SPIFFS_ERR_NOT_MOUNTED -10000
+#define SPIFFS_ERR_FULL -10001
+#define SPIFFS_ERR_NOT_FOUND -10002
+#define SPIFFS_ERR_END_OF_OBJECT -10003
+#define SPIFFS_ERR_DELETED -10004
+#define SPIFFS_ERR_NOT_FINALIZED -10005
+#define SPIFFS_ERR_NOT_INDEX -10006
+#define SPIFFS_ERR_OUT_OF_FILE_DESCS -10007
+#define SPIFFS_ERR_FILE_CLOSED -10008
+#define SPIFFS_ERR_FILE_DELETED -10009
+#define SPIFFS_ERR_BAD_DESCRIPTOR -10010
+#define SPIFFS_ERR_IS_INDEX -10011
+#define SPIFFS_ERR_IS_FREE -10012
+#define SPIFFS_ERR_INDEX_SPAN_MISMATCH -10013
+#define SPIFFS_ERR_DATA_SPAN_MISMATCH -10014
+#define SPIFFS_ERR_INDEX_REF_FREE -10015
+#define SPIFFS_ERR_INDEX_REF_LU -10016
+#define SPIFFS_ERR_INDEX_REF_INVALID -10017
+#define SPIFFS_ERR_INDEX_FREE -10018
+#define SPIFFS_ERR_INDEX_LU -10019
+#define SPIFFS_ERR_INDEX_INVALID -10020
+#define SPIFFS_ERR_NOT_WRITABLE -10021
+#define SPIFFS_ERR_NOT_READABLE -10022
+#define SPIFFS_ERR_CONFLICTING_NAME -10023
+#define SPIFFS_ERR_NOT_CONFIGURED -10024
+
+#define SPIFFS_ERR_NOT_A_FS -10025
+#define SPIFFS_ERR_MOUNTED -10026
+#define SPIFFS_ERR_ERASE_FAIL -10027
+#define SPIFFS_ERR_MAGIC_NOT_POSSIBLE -10028
+
+#define SPIFFS_ERR_NO_DELETED_BLOCKS -10029
+
+#define SPIFFS_ERR_FILE_EXISTS -10030
+
+#define SPIFFS_ERR_NOT_A_FILE -10031
+#define SPIFFS_ERR_RO_NOT_IMPL -10032
+#define SPIFFS_ERR_RO_ABORTED_OPERATION -10033
+#define SPIFFS_ERR_PROBE_TOO_FEW_BLOCKS -10034
+#define SPIFFS_ERR_PROBE_NOT_A_FS -10035
+#define SPIFFS_ERR_NAME_TOO_LONG -10036
+
+#define SPIFFS_ERR_IX_MAP_UNMAPPED -10037
+#define SPIFFS_ERR_IX_MAP_MAPPED -10038
+#define SPIFFS_ERR_IX_MAP_BAD_RANGE -10039
+
+#define SPIFFS_ERR_INTERNAL -10050
+
+#define SPIFFS_ERR_TEST -10100
+
+
+// spiffs file descriptor index type. must be signed
+typedef int16_t spiffs_file;
+// spiffs file descriptor flags
+typedef uint16_t spiffs_flags;
+// spiffs file mode
+typedef uint16_t spiffs_mode;
+// object type
+typedef uint8_t spiffs_obj_type;
+
+struct spiffs_t;
+
+#if SPIFFS_HAL_CALLBACK_EXTRA
+
+/* spi read call function type */
+typedef int32_t (*spiffs_read)(struct spiffs_t *fs, uint32_t addr, uint32_t size, uint8_t *dst);
+/* spi write call function type */
+typedef int32_t (*spiffs_write)(struct spiffs_t *fs, uint32_t addr, uint32_t size, uint8_t *src);
+/* spi erase call function type */
+typedef int32_t (*spiffs_erase)(struct spiffs_t *fs, uint32_t addr, uint32_t size);
+
+#else // SPIFFS_HAL_CALLBACK_EXTRA
+
+/* spi read call function type */
+typedef int32_t (*spiffs_read)(uint32_t addr, uint32_t size, uint8_t *dst);
+/* spi write call function type */
+typedef int32_t (*spiffs_write)(uint32_t addr, uint32_t size, uint8_t *src);
+/* spi erase call function type */
+typedef int32_t (*spiffs_erase)(uint32_t addr, uint32_t size);
+#endif // SPIFFS_HAL_CALLBACK_EXTRA
+
+/* file system check callback report operation */
+typedef enum {
+ SPIFFS_CHECK_LOOKUP = 0,
+ SPIFFS_CHECK_INDEX,
+ SPIFFS_CHECK_PAGE
+} spiffs_check_type;
+
+/* file system check callback report type */
+typedef enum {
+ SPIFFS_CHECK_PROGRESS = 0,
+ SPIFFS_CHECK_ERROR,
+ SPIFFS_CHECK_FIX_INDEX,
+ SPIFFS_CHECK_FIX_LOOKUP,
+ SPIFFS_CHECK_DELETE_ORPHANED_INDEX,
+ SPIFFS_CHECK_DELETE_PAGE,
+ SPIFFS_CHECK_DELETE_BAD_FILE
+} spiffs_check_report;
+
+/* file system check callback function */
+#if SPIFFS_HAL_CALLBACK_EXTRA
+typedef void (*spiffs_check_callback)(struct spiffs_t *fs, spiffs_check_type type, spiffs_check_report report,
+ uint32_t arg1, uint32_t arg2);
+#else // SPIFFS_HAL_CALLBACK_EXTRA
+typedef void (*spiffs_check_callback)(spiffs_check_type type, spiffs_check_report report,
+ uint32_t arg1, uint32_t arg2);
+#endif // SPIFFS_HAL_CALLBACK_EXTRA
+
+/* file system listener callback operation */
+typedef enum {
+ /* the file has been created */
+ SPIFFS_CB_CREATED = 0,
+ /* the file has been updated or moved to another page */
+ SPIFFS_CB_UPDATED,
+ /* the file has been deleted */
+ SPIFFS_CB_DELETED
+} spiffs_fileop_type;
+
+/* file system listener callback function */
+typedef void (*spiffs_file_callback)(struct spiffs_t *fs, spiffs_fileop_type op, spiffs_obj_id obj_id, spiffs_page_ix pix);
+
+#ifndef SPIFFS_DBG
+#define SPIFFS_DBG(...) \
+ print(__VA_ARGS__)
+#endif
+#ifndef SPIFFS_GC_DBG
+#define SPIFFS_GC_DBG(...) printf(__VA_ARGS__)
+#endif
+#ifndef SPIFFS_CACHE_DBG
+#define SPIFFS_CACHE_DBG(...) printf(__VA_ARGS__)
+#endif
+#ifndef SPIFFS_CHECK_DBG
+#define SPIFFS_CHECK_DBG(...) printf(__VA_ARGS__)
+#endif
+
+/* Any write to the filehandle is appended to end of the file */
+#define SPIFFS_APPEND (1<<0)
+#define SPIFFS_O_APPEND SPIFFS_APPEND
+/* If the opened file exists, it will be truncated to zero length before opened */
+#define SPIFFS_TRUNC (1<<1)
+#define SPIFFS_O_TRUNC SPIFFS_TRUNC
+/* If the opened file does not exist, it will be created before opened */
+#define SPIFFS_CREAT (1<<2)
+#define SPIFFS_O_CREAT SPIFFS_CREAT
+/* The opened file may only be read */
+#define SPIFFS_RDONLY (1<<3)
+#define SPIFFS_O_RDONLY SPIFFS_RDONLY
+/* The opened file may only be written */
+#define SPIFFS_WRONLY (1<<4)
+#define SPIFFS_O_WRONLY SPIFFS_WRONLY
+/* The opened file may be both read and written */
+#define SPIFFS_RDWR (SPIFFS_RDONLY | SPIFFS_WRONLY)
+#define SPIFFS_O_RDWR SPIFFS_RDWR
+/* Any writes to the filehandle will never be cached but flushed directly */
+#define SPIFFS_DIRECT (1<<5)
+#define SPIFFS_O_DIRECT SPIFFS_DIRECT
+/* If SPIFFS_O_CREAT and SPIFFS_O_EXCL are set, SPIFFS_open() shall fail if the file exists */
+#define SPIFFS_EXCL (1<<6)
+#define SPIFFS_O_EXCL SPIFFS_EXCL
+
+#define SPIFFS_SEEK_SET (0)
+#define SPIFFS_SEEK_CUR (1)
+#define SPIFFS_SEEK_END (2)
+
+#define SPIFFS_TYPE_FILE (1)
+#define SPIFFS_TYPE_DIR (2)
+#define SPIFFS_TYPE_HARD_LINK (3)
+#define SPIFFS_TYPE_SOFT_LINK (4)
+
+#ifndef SPIFFS_LOCK
+#define SPIFFS_LOCK(fs)
+#endif
+
+#ifndef SPIFFS_UNLOCK
+#define SPIFFS_UNLOCK(fs)
+#endif
+
+// phys structs
+
+// spiffs spi configuration struct
+typedef struct {
+ // physical read function
+ spiffs_read hal_read_f;
+ // physical write function
+ spiffs_write hal_write_f;
+ // physical erase function
+ spiffs_erase hal_erase_f;
+#if SPIFFS_SINGLETON == 0
+ // physical size of the spi flash
+ uint32_t phys_size;
+ // physical offset in spi flash used for spiffs,
+ // must be on block boundary
+ uint32_t phys_addr;
+ // physical size when erasing a block
+ uint32_t phys_erase_block;
+
+ // logical size of a block, must be on physical
+ // block size boundary and must never be less than
+ // a physical block
+ uint32_t log_block_size;
+ // logical size of a page, must be at least
+ // log_block_size / 8
+ uint32_t log_page_size;
+
+#endif
+#if SPIFFS_FILEHDL_OFFSET
+ // an integer offset added to each file handle
+ uint16_t fh_ix_offset;
+#endif
+} spiffs_config;
+
+typedef struct spiffs_t {
+ // file system configuration
+ spiffs_config cfg;
+ // number of logical blocks
+ uint32_t block_count;
+
+ // cursor for free blocks, block index
+ spiffs_block_ix free_cursor_block_ix;
+ // cursor for free blocks, entry index
+ int free_cursor_obj_lu_entry;
+ // cursor when searching, block index
+ spiffs_block_ix cursor_block_ix;
+ // cursor when searching, entry index
+ int cursor_obj_lu_entry;
+
+ // primary work buffer, size of a logical page
+ uint8_t *lu_work;
+ // secondary work buffer, size of a logical page
+ uint8_t *work;
+ // file descriptor memory area
+ uint8_t *fd_space;
+ // available file descriptors
+ uint32_t fd_count;
+
+ // last error
+ int32_t err_code;
+
+ // current number of free blocks
+ uint32_t free_blocks;
+ // current number of busy pages
+ uint32_t stats_p_allocated;
+ // current number of deleted pages
+ uint32_t stats_p_deleted;
+ // flag indicating that garbage collector is cleaning
+ uint8_t cleaning;
+ // max erase count amongst all blocks
+ spiffs_obj_id max_erase_count;
+
+#if SPIFFS_GC_STATS
+ uint32_t stats_gc_runs;
+#endif
+
+#if SPIFFS_CACHE
+ // cache memory
+ void *cache;
+ // cache size
+ uint32_t cache_size;
+#if SPIFFS_CACHE_STATS
+ uint32_t cache_hits;
+ uint32_t cache_misses;
+#endif
+#endif
+
+ // check callback function
+ spiffs_check_callback check_cb_f;
+ // file callback function
+ spiffs_file_callback file_cb_f;
+ // mounted flag
+ uint8_t mounted;
+ // user data
+ void *user_data;
+ // config magic
+ uint32_t config_magic;
+} spiffs;
+
+/* spiffs file status struct */
+typedef struct {
+ spiffs_obj_id obj_id;
+ uint32_t size;
+ spiffs_obj_type type;
+ spiffs_page_ix pix;
+ uint8_t name[SPIFFS_OBJ_NAME_LEN];
+} spiffs_stat;
+
+struct spiffs_dirent {
+ spiffs_obj_id obj_id;
+ uint8_t name[SPIFFS_OBJ_NAME_LEN];
+ spiffs_obj_type type;
+ uint32_t size;
+ spiffs_page_ix pix;
+};
+
+typedef struct {
+ spiffs *fs;
+ spiffs_block_ix block;
+ int entry;
+} spiffs_DIR;
+
+#if SPIFFS_IX_MAP
+
+typedef struct {
+ // buffer with looked up data pixes
+ spiffs_page_ix *map_buf;
+ // precise file byte offset
+ uint32_t offset;
+ // start data span index of lookup buffer
+ spiffs_span_ix start_spix;
+ // end data span index of lookup buffer
+ spiffs_span_ix end_spix;
+} spiffs_ix_map;
+
+#endif
+
+// functions
+
+#if SPIFFS_USE_MAGIC && SPIFFS_USE_MAGIC_LENGTH && SPIFFS_SINGLETON==0
+/**
+ * Special function. This takes a spiffs config struct and returns the number
+ * of blocks this file system was formatted with. This function relies on
+ * that following info is set correctly in given config struct:
+ *
+ * phys_addr, log_page_size, and log_block_size.
+ *
+ * Also, hal_read_f must be set in the config struct.
+ *
+ * One must be sure of the correct page size and that the physical address is
+ * correct in the probed file system when calling this function. It is not
+ * checked if the phys_addr actually points to the start of the file system,
+ * so one might get a false positive if entering a phys_addr somewhere in the
+ * middle of the file system at block boundary. In addition, it is not checked
+ * if the page size is actually correct. If it is not, weird file system sizes
+ * will be returned.
+ *
+ * If this function detects a file system it returns the assumed file system
+ * size, which can be used to set the phys_size.
+ *
+ * Otherwise, it returns an error indicating why it is not regarded as a file
+ * system.
+ *
+ * Note: this function is not protected with SPIFFS_LOCK and SPIFFS_UNLOCK
+ * macros. It returns the error code directly, instead of as read by
+ * SPIFFS_errno.
+ *
+ * @param config essential parts of the physical and logical
+ * configuration of the file system.
+ */
+int32_t SPIFFS_probe_fs(spiffs_config *config);
+#endif // SPIFFS_USE_MAGIC && SPIFFS_USE_MAGIC_LENGTH && SPIFFS_SINGLETON==0
+
+/**
+ * Initializes the file system dynamic parameters and mounts the filesystem.
+ * If SPIFFS_USE_MAGIC is enabled the mounting may fail with SPIFFS_ERR_NOT_A_FS
+ * if the flash does not contain a recognizable file system.
+ * In this case, SPIFFS_format must be called prior to remounting.
+ * @param fs the file system struct
+ * @param config the physical and logical configuration of the file system
+ * @param work a memory work buffer comprising 2*config->log_page_size
+ * bytes used throughout all file system operations
+ * @param fd_space memory for file descriptors
+ * @param fd_space_size memory size of file descriptors
+ * @param cache memory for cache, may be null
+ * @param cache_size memory size of cache
+ * @param check_cb_f callback function for reporting during consistency checks
+ */
+int32_t SPIFFS_mount(spiffs *fs, spiffs_config *config, uint8_t *work,
+ uint8_t *fd_space, uint32_t fd_space_size,
+ void *cache, uint32_t cache_size,
+ spiffs_check_callback check_cb_f);
+
+/**
+ * Unmounts the file system. All file handles will be flushed of any
+ * cached writes and closed.
+ * @param fs the file system struct
+ */
+void SPIFFS_unmount(spiffs *fs);
+
+/**
+ * Creates a new file.
+ * @param fs the file system struct
+ * @param path the path of the new file
+ * @param mode ignored, for posix compliance
+ */
+int32_t SPIFFS_creat(spiffs *fs, const char *path, spiffs_mode mode);
+
+/**
+ * Opens/creates a file.
+ * @param fs the file system struct
+ * @param path the path of the new file
+ * @param flags the flags for the open command, can be combinations of
+ * SPIFFS_O_APPEND, SPIFFS_O_TRUNC, SPIFFS_O_CREAT, SPIFFS_O_RDONLY,
+ * SPIFFS_O_WRONLY, SPIFFS_O_RDWR, SPIFFS_O_DIRECT, SPIFFS_O_EXCL
+ * @param mode ignored, for posix compliance
+ */
+spiffs_file SPIFFS_open(spiffs *fs, const char *path, spiffs_flags flags, spiffs_mode mode);
+
+/**
+ * Opens a file by given dir entry.
+ * Optimization purposes, when traversing a file system with SPIFFS_readdir
+ * a normal SPIFFS_open would need to traverse the filesystem again to find
+ * the file, whilst SPIFFS_open_by_dirent already knows where the file resides.
+ * @param fs the file system struct
+ * @param e the dir entry to the file
+ * @param flags the flags for the open command, can be combinations of
+ * SPIFFS_APPEND, SPIFFS_TRUNC, SPIFFS_CREAT, SPIFFS_RD_ONLY,
+ * SPIFFS_WR_ONLY, SPIFFS_RDWR, SPIFFS_DIRECT.
+ * SPIFFS_CREAT will have no effect in this case.
+ * @param mode ignored, for posix compliance
+ */
+spiffs_file SPIFFS_open_by_dirent(spiffs *fs, struct spiffs_dirent *e, spiffs_flags flags, spiffs_mode mode);
+
+/**
+ * Opens a file by given page index.
+ * Optimization purposes, opens a file by directly pointing to the page
+ * index in the spi flash.
+ * If the page index does not point to a file header SPIFFS_ERR_NOT_A_FILE
+ * is returned.
+ * @param fs the file system struct
+ * @param page_ix the page index
+ * @param flags the flags for the open command, can be combinations of
+ * SPIFFS_APPEND, SPIFFS_TRUNC, SPIFFS_CREAT, SPIFFS_RD_ONLY,
+ * SPIFFS_WR_ONLY, SPIFFS_RDWR, SPIFFS_DIRECT.
+ * SPIFFS_CREAT will have no effect in this case.
+ * @param mode ignored, for posix compliance
+ */
+spiffs_file SPIFFS_open_by_page(spiffs *fs, spiffs_page_ix page_ix, spiffs_flags flags, spiffs_mode mode);
+
+/**
+ * Reads from given filehandle.
+ * @param fs the file system struct
+ * @param fh the filehandle
+ * @param buf where to put read data
+ * @param len how much to read
+ * @returns number of bytes read, or -1 if error
+ */
+int32_t SPIFFS_read(spiffs *fs, spiffs_file fh, void *buf, int32_t len);
+
+/**
+ * Writes to given filehandle.
+ * @param fs the file system struct
+ * @param fh the filehandle
+ * @param buf the data to write
+ * @param len how much to write
+ * @returns number of bytes written, or -1 if error
+ */
+int32_t SPIFFS_write(spiffs *fs, spiffs_file fh, void *buf, int32_t len);
+
+/**
+ * Moves the read/write file offset. Resulting offset is returned or negative if error.
+ * lseek(fs, fd, 0, SPIFFS_SEEK_CUR) will thus return current offset.
+ * @param fs the file system struct
+ * @param fh the filehandle
+ * @param offs how much/where to move the offset
+ * @param whence if SPIFFS_SEEK_SET, the file offset shall be set to offset bytes
+ * if SPIFFS_SEEK_CUR, the file offset shall be set to its current location plus offset
+ * if SPIFFS_SEEK_END, the file offset shall be set to the size of the file plus offse, which should be negative
+ */
+int32_t SPIFFS_lseek(spiffs *fs, spiffs_file fh, int32_t offs, int whence);
+
+/**
+ * Removes a file by path
+ * @param fs the file system struct
+ * @param path the path of the file to remove
+ */
+int32_t SPIFFS_remove(spiffs *fs, const char *path);
+
+/**
+ * Removes a file by filehandle
+ * @param fs the file system struct
+ * @param fh the filehandle of the file to remove
+ */
+int32_t SPIFFS_fremove(spiffs *fs, spiffs_file fh);
+
+/**
+ * Gets file status by path
+ * @param fs the file system struct
+ * @param path the path of the file to stat
+ * @param s the stat struct to populate
+ */
+int32_t SPIFFS_stat(spiffs *fs, const char *path, spiffs_stat *s);
+
+/**
+ * Gets file status by filehandle
+ * @param fs the file system struct
+ * @param fh the filehandle of the file to stat
+ * @param s the stat struct to populate
+ */
+int32_t SPIFFS_fstat(spiffs *fs, spiffs_file fh, spiffs_stat *s);
+
+/**
+ * Flushes all pending write operations from cache for given file
+ * @param fs the file system struct
+ * @param fh the filehandle of the file to flush
+ */
+int32_t SPIFFS_fflush(spiffs *fs, spiffs_file fh);
+
+/**
+ * Closes a filehandle. If there are pending write operations, these are finalized before closing.
+ * @param fs the file system struct
+ * @param fh the filehandle of the file to close
+ */
+int32_t SPIFFS_close(spiffs *fs, spiffs_file fh);
+
+/**
+ * Renames a file
+ * @param fs the file system struct
+ * @param old path of file to rename
+ * @param newPath new path of file
+ */
+int32_t SPIFFS_rename(spiffs *fs, const char *old, const char *newPath);
+
+/**
+ * Returns last error of last file operation.
+ * @param fs the file system struct
+ */
+int32_t SPIFFS_errno(spiffs *fs);
+
+/**
+ * Clears last error.
+ * @param fs the file system struct
+ */
+void SPIFFS_clearerr(spiffs *fs);
+
+/**
+ * Opens a directory stream corresponding to the given name.
+ * The stream is positioned at the first entry in the directory.
+ * On hydrogen builds the name argument is ignored as hydrogen builds always correspond
+ * to a flat file structure - no directories.
+ * @param fs the file system struct
+ * @param name the name of the directory
+ * @param d pointer the directory stream to be populated
+ */
+spiffs_DIR *SPIFFS_opendir(spiffs *fs, const char *name, spiffs_DIR *d);
+
+/**
+ * Closes a directory stream
+ * @param d the directory stream to close
+ */
+int32_t SPIFFS_closedir(spiffs_DIR *d);
+
+/**
+ * Reads a directory into given spifs_dirent struct.
+ * @param d pointer to the directory stream
+ * @param e the dirent struct to be populated
+ * @returns null if error or end of stream, else given dirent is returned
+ */
+struct spiffs_dirent *SPIFFS_readdir(spiffs_DIR *d, struct spiffs_dirent *e);
+
+/**
+ * Runs a consistency check on given filesystem.
+ * @param fs the file system struct
+ */
+int32_t SPIFFS_check(spiffs *fs);
+
+/**
+ * Returns number of total bytes available and number of used bytes.
+ * This is an estimation, and depends on if there a many files with little
+ * data or few files with much data.
+ * NB: If used number of bytes exceeds total bytes, a SPIFFS_check should
+ * run. This indicates a power loss in midst of things. In worst case
+ * (repeated powerlosses in mending or gc) you might have to delete some files.
+ *
+ * @param fs the file system struct
+ * @param total total number of bytes in filesystem
+ * @param used used number of bytes in filesystem
+ */
+int32_t SPIFFS_info(spiffs *fs, uint32_t *total, uint32_t *used);
+
+/**
+ * Formats the entire file system. All data will be lost.
+ * The filesystem must not be mounted when calling this.
+ *
+ * NB: formatting is awkward. Due to backwards compatibility, SPIFFS_mount
+ * MUST be called prior to formatting in order to configure the filesystem.
+ * If SPIFFS_mount succeeds, SPIFFS_unmount must be called before calling
+ * SPIFFS_format.
+ * If SPIFFS_mount fails, SPIFFS_format can be called directly without calling
+ * SPIFFS_unmount first.
+ *
+ * @param fs the file system struct
+ */
+int32_t SPIFFS_format(spiffs *fs);
+
+/**
+ * Returns nonzero if spiffs is mounted, or zero if unmounted.
+ * @param fs the file system struct
+ */
+uint8_t SPIFFS_mounted(spiffs *fs);
+
+/**
+ * Tries to find a block where most or all pages are deleted, and erase that
+ * block if found. Does not care for wear levelling. Will not move pages
+ * around.
+ * If parameter max_free_pages are set to 0, only blocks with only deleted
+ * pages will be selected.
+ *
+ * NB: the garbage collector is automatically called when spiffs needs free
+ * pages. The reason for this function is to give possibility to do background
+ * tidying when user knows the system is idle.
+ *
+ * Use with care.
+ *
+ * Setting max_free_pages to anything larger than zero will eventually wear
+ * flash more as a block containing free pages can be erased.
+ *
+ * Will set err_no to SPIFFS_OK if a block was found and erased,
+ * SPIFFS_ERR_NO_DELETED_BLOCK if no matching block was found,
+ * or other error.
+ *
+ * @param fs the file system struct
+ * @param max_free_pages maximum number allowed free pages in block
+ */
+int32_t SPIFFS_gc_quick(spiffs *fs, uint16_t max_free_pages);
+
+/**
+ * Will try to make room for given amount of bytes in the filesystem by moving
+ * pages and erasing blocks.
+ * If it is physically impossible, err_no will be set to SPIFFS_ERR_FULL. If
+ * there already is this amount (or more) of free space, SPIFFS_gc will
+ * silently return. It is recommended to call SPIFFS_info before invoking
+ * this method in order to determine what amount of bytes to give.
+ *
+ * NB: the garbage collector is automatically called when spiffs needs free
+ * pages. The reason for this function is to give possibility to do background
+ * tidying when user knows the system is idle.
+ *
+ * Use with care.
+ *
+ * @param fs the file system struct
+ * @param size amount of bytes that should be freed
+ */
+int32_t SPIFFS_gc(spiffs *fs, uint32_t size);
+
+/**
+ * Check if EOF reached.
+ * @param fs the file system struct
+ * @param fh the filehandle of the file to check
+ */
+int32_t SPIFFS_eof(spiffs *fs, spiffs_file fh);
+
+/**
+ * Get position in file.
+ * @param fs the file system struct
+ * @param fh the filehandle of the file to check
+ */
+int32_t SPIFFS_tell(spiffs *fs, spiffs_file fh);
+
+/**
+ * Registers a callback function that keeps track on operations on file
+ * headers. Do note, that this callback is called from within internal spiffs
+ * mechanisms. Any operations on the actual file system being callbacked from
+ * in this callback will mess things up for sure - do not do this.
+ * This can be used to track where files are and move around during garbage
+ * collection, which in turn can be used to build location tables in ram.
+ * Used in conjuction with SPIFFS_open_by_page this may improve performance
+ * when opening a lot of files.
+ * Must be invoked after mount.
+ *
+ * @param fs the file system struct
+ * @param cb_func the callback on file operations
+ */
+int32_t SPIFFS_set_file_callback_func(spiffs *fs, spiffs_file_callback cb_func);
+
+#if SPIFFS_IX_MAP
+
+/**
+ * Maps the first level index lookup to a given memory map.
+ * This will make reading big files faster, as the memory map will be used for
+ * looking up data pages instead of searching for the indices on the physical
+ * medium. When mapping, all affected indicies are found and the information is
+ * copied to the array.
+ * Whole file or only parts of it may be mapped. The index map will cover file
+ * contents from argument offset until and including arguments (offset+len).
+ * It is valid to map a longer range than the current file size. The map will
+ * then be populated when the file grows.
+ * On garbage collections and file data page movements, the map array will be
+ * automatically updated. Do not tamper with the map array, as this contains
+ * the references to the data pages. Modifying it from outside will corrupt any
+ * future readings using this file descriptor.
+ * The map will no longer be used when the file descriptor closed or the file
+ * is unmapped.
+ * This can be useful to get faster and more deterministic timing when reading
+ * large files, or when seeking and reading a lot within a file.
+ * @param fs the file system struct
+ * @param fh the file handle of the file to map
+ * @param map a spiffs_ix_map struct, describing the index map
+ * @param offset absolute file offset where to start the index map
+ * @param len length of the mapping in actual file bytes
+ * @param map_buf the array buffer for the look up data - number of required
+ * elements in the array can be derived from function
+ * SPIFFS_bytes_to_ix_map_entries given the length
+ */
+int32_t SPIFFS_ix_map(spiffs *fs, spiffs_file fh, spiffs_ix_map *map,
+ uint32_t offset, uint32_t len, spiffs_page_ix *map_buf);
+
+/**
+ * Unmaps the index lookup from this filehandle. All future readings will
+ * proceed as normal, requiring reading of the first level indices from
+ * physical media.
+ * The map and map buffer given in function SPIFFS_ix_map will no longer be
+ * referenced by spiffs.
+ * It is not strictly necessary to unmap a file before closing it, as closing
+ * a file will automatically unmap it.
+ * @param fs the file system struct
+ * @param fh the file handle of the file to unmap
+ */
+int32_t SPIFFS_ix_unmap(spiffs *fs, spiffs_file fh);
+
+/**
+ * Moves the offset for the index map given in function SPIFFS_ix_map. Parts or
+ * all of the map buffer will repopulated.
+ * @param fs the file system struct
+ * @param fh the mapped file handle of the file to remap
+ * @param offset new absolute file offset where to start the index map
+ */
+int32_t SPIFFS_ix_remap(spiffs *fs, spiffs_file fh, uint32_t offs);
+
+/**
+ * Utility function to get number of spiffs_page_ix entries a map buffer must
+ * contain on order to map given amount of file data in bytes.
+ * See function SPIFFS_ix_map and SPIFFS_ix_map_entries_to_bytes.
+ * @param fs the file system struct
+ * @param bytes number of file data bytes to map
+ * @return needed number of elements in a spiffs_page_ix array needed to
+ * map given amount of bytes in a file
+ */
+int32_t SPIFFS_bytes_to_ix_map_entries(spiffs *fs, uint32_t bytes);
+
+/**
+ * Utility function to amount of file data bytes that can be mapped when
+ * mapping a file with buffer having given number of spiffs_page_ix entries.
+ * See function SPIFFS_ix_map and SPIFFS_bytes_to_ix_map_entries.
+ * @param fs the file system struct
+ * @param map_page_ix_entries number of entries in a spiffs_page_ix array
+ * @return amount of file data in bytes that can be mapped given a map
+ * buffer having given amount of spiffs_page_ix entries
+ */
+int32_t SPIFFS_ix_map_entries_to_bytes(spiffs *fs, uint32_t map_page_ix_entries);
+
+#endif // SPIFFS_IX_MAP
+
+
+#if SPIFFS_TEST_VISUALISATION
+/**
+ * Prints out a visualization of the filesystem.
+ * @param fs the file system struct
+ */
+int32_t SPIFFS_vis(spiffs *fs);
+#endif
+
+#if SPIFFS_BUFFER_HELP
+/**
+ * Returns number of bytes needed for the filedescriptor buffer given
+ * amount of file descriptors.
+ */
+uint32_t SPIFFS_buffer_bytes_for_filedescs(spiffs *fs, uint32_t num_descs);
+
+#if SPIFFS_CACHE
+/**
+ * Returns number of bytes needed for the cache buffer given
+ * amount of cache pages.
+ */
+uint32_t SPIFFS_buffer_bytes_for_cache(spiffs *fs, uint32_t num_pages);
+#endif
+#endif
+
+#if SPIFFS_CACHE
+#endif
+#if defined(__cplusplus)
+}
+#endif
+
+#endif /* SPIFFS_H_ */
diff --git a/fw/User/spiffs/src/spiffs_cache.c b/fw/User/spiffs/src/spiffs_cache.c
new file mode 100644
index 0000000..c784c3f
--- /dev/null
+++ b/fw/User/spiffs/src/spiffs_cache.c
@@ -0,0 +1,316 @@
+/*
+ * spiffs_cache.c
+ *
+ * Created on: Jun 23, 2013
+ * Author: petera
+ */
+
+#include "spiffs.h"
+#include "spiffs_nucleus.h"
+
+#if SPIFFS_CACHE
+
+// returns cached page for give page index, or null if no such cached page
+static spiffs_cache_page *spiffs_cache_page_get(spiffs *fs, spiffs_page_ix pix) {
+ spiffs_cache *cache = spiffs_get_cache(fs);
+ if ((cache->cpage_use_map & cache->cpage_use_mask) == 0) return 0;
+ int i;
+ for (i = 0; i < cache->cpage_count; i++) {
+ spiffs_cache_page *cp = spiffs_get_cache_page_hdr(fs, cache, i);
+ if ((cache->cpage_use_map & (1<flags & SPIFFS_CACHE_FLAG_TYPE_WR) == 0 &&
+ cp->pix == pix ) {
+ SPIFFS_CACHE_DBG("CACHE_GET: have cache page %i for %04x\n", i, pix);
+ cp->last_access = cache->last_access;
+ return cp;
+ }
+ }
+ //SPIFFS_CACHE_DBG("CACHE_GET: no cache for %04x\n", pix);
+ return 0;
+}
+
+// frees cached page
+static int32_t spiffs_cache_page_free(spiffs *fs, int ix, uint8_t write_back) {
+ int32_t res = SPIFFS_OK;
+ spiffs_cache *cache = spiffs_get_cache(fs);
+ spiffs_cache_page *cp = spiffs_get_cache_page_hdr(fs, cache, ix);
+ if (cache->cpage_use_map & (1<flags & SPIFFS_CACHE_FLAG_TYPE_WR) == 0 &&
+ (cp->flags & SPIFFS_CACHE_FLAG_DIRTY)) {
+ uint8_t *mem = spiffs_get_cache_page(fs, cache, ix);
+ res = SPIFFS_HAL_WRITE(fs, SPIFFS_PAGE_TO_PADDR(fs, cp->pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), mem);
+ }
+
+ cp->flags = 0;
+ cache->cpage_use_map &= ~(1 << ix);
+
+ if (cp->flags & SPIFFS_CACHE_FLAG_TYPE_WR) {
+ #if SPIFFS_CACHE_WR
+ SPIFFS_CACHE_DBG("CACHE_FREE: free cache page %i objid %04x\n", ix, cp->obj_id);
+ #endif
+ } else {
+ SPIFFS_CACHE_DBG("CACHE_FREE: free cache page %i pix %04x\n", ix, cp->pix);
+ }
+ }
+
+ return res;
+}
+
+// removes the oldest accessed cached page
+static int32_t spiffs_cache_page_remove_oldest(spiffs *fs, uint8_t flag_mask, uint8_t flags) {
+ int32_t res = SPIFFS_OK;
+ spiffs_cache *cache = spiffs_get_cache(fs);
+
+ if ((cache->cpage_use_map & cache->cpage_use_mask) != cache->cpage_use_mask) {
+ // at least one free cpage
+ return SPIFFS_OK;
+ }
+
+ // all busy, scan thru all to find the cpage which has oldest access
+ int i;
+ int cand_ix = -1;
+ uint32_t oldest_val = 0;
+ for (i = 0; i < cache->cpage_count; i++) {
+ spiffs_cache_page *cp = spiffs_get_cache_page_hdr(fs, cache, i);
+ if ((cache->last_access - cp->last_access) > oldest_val &&
+ (cp->flags & flag_mask) == flags) {
+ oldest_val = cache->last_access - cp->last_access;
+ cand_ix = i;
+ }
+ }
+
+ if (cand_ix >= 0) {
+ res = spiffs_cache_page_free(fs, cand_ix, 1);
+ }
+
+ return res;
+}
+
+// allocates a new cached page and returns it, or null if all cache pages are busy
+static spiffs_cache_page *spiffs_cache_page_allocate(spiffs *fs) {
+ spiffs_cache *cache = spiffs_get_cache(fs);
+ if (cache->cpage_use_map == 0xffffffff) {
+ // out of cache memory
+ return 0;
+ }
+ int i;
+ for (i = 0; i < cache->cpage_count; i++) {
+ if ((cache->cpage_use_map & (1<cpage_use_map |= (1<last_access = cache->last_access;
+ SPIFFS_CACHE_DBG("CACHE_ALLO: allocated cache page %i\n", i);
+ return cp;
+ }
+ }
+ // out of cache entries
+ return 0;
+}
+
+// drops the cache page for give page index
+void spiffs_cache_drop_page(spiffs *fs, spiffs_page_ix pix) {
+ spiffs_cache_page *cp = spiffs_cache_page_get(fs, pix);
+ if (cp) {
+ spiffs_cache_page_free(fs, cp->ix, 0);
+ }
+}
+
+// ------------------------------
+
+// reads from spi flash or the cache
+int32_t spiffs_phys_rd(
+ spiffs *fs,
+ uint8_t op,
+ spiffs_file fh,
+ uint32_t addr,
+ uint32_t len,
+ uint8_t *dst) {
+ (void)fh;
+ int32_t res = SPIFFS_OK;
+ spiffs_cache *cache = spiffs_get_cache(fs);
+ spiffs_cache_page *cp = spiffs_cache_page_get(fs, SPIFFS_PADDR_TO_PAGE(fs, addr));
+ cache->last_access++;
+ if (cp) {
+ // we've already got one, you see
+#if SPIFFS_CACHE_STATS
+ fs->cache_hits++;
+#endif
+ cp->last_access = cache->last_access;
+ uint8_t *mem = spiffs_get_cache_page(fs, cache, cp->ix);
+ memcpy(dst, &mem[SPIFFS_PADDR_TO_PAGE_OFFSET(fs, addr)], len);
+ } else {
+ if ((op & SPIFFS_OP_TYPE_MASK) == SPIFFS_OP_T_OBJ_LU2) {
+ // for second layer lookup functions, we do not cache in order to prevent shredding
+ return SPIFFS_HAL_READ(fs, addr, len, dst);
+ }
+#if SPIFFS_CACHE_STATS
+ fs->cache_misses++;
+#endif
+ // this operation will always free one cache page (unless all already free),
+ // the result code stems from the write operation of the possibly freed cache page
+ res = spiffs_cache_page_remove_oldest(fs, SPIFFS_CACHE_FLAG_TYPE_WR, 0);
+
+ cp = spiffs_cache_page_allocate(fs);
+ if (cp) {
+ cp->flags = SPIFFS_CACHE_FLAG_WRTHRU;
+ cp->pix = SPIFFS_PADDR_TO_PAGE(fs, addr);
+
+ int32_t res2 = SPIFFS_HAL_READ(fs,
+ addr - SPIFFS_PADDR_TO_PAGE_OFFSET(fs, addr),
+ SPIFFS_CFG_LOG_PAGE_SZ(fs),
+ spiffs_get_cache_page(fs, cache, cp->ix));
+ if (res2 != SPIFFS_OK) {
+ // honor read failure before possible write failure (bad idea?)
+ res = res2;
+ }
+ uint8_t *mem = spiffs_get_cache_page(fs, cache, cp->ix);
+ memcpy(dst, &mem[SPIFFS_PADDR_TO_PAGE_OFFSET(fs, addr)], len);
+ } else {
+ // this will never happen, last resort for sake of symmetry
+ int32_t res2 = SPIFFS_HAL_READ(fs, addr, len, dst);
+ if (res2 != SPIFFS_OK) {
+ // honor read failure before possible write failure (bad idea?)
+ res = res2;
+ }
+ }
+ }
+ return res;
+}
+
+// writes to spi flash and/or the cache
+int32_t spiffs_phys_wr(
+ spiffs *fs,
+ uint8_t op,
+ spiffs_file fh,
+ uint32_t addr,
+ uint32_t len,
+ uint8_t *src) {
+ (void)fh;
+ spiffs_page_ix pix = SPIFFS_PADDR_TO_PAGE(fs, addr);
+ spiffs_cache *cache = spiffs_get_cache(fs);
+ spiffs_cache_page *cp = spiffs_cache_page_get(fs, pix);
+
+ if (cp && (op & SPIFFS_OP_COM_MASK) != SPIFFS_OP_C_WRTHRU) {
+ // have a cache page
+ // copy in data to cache page
+
+ if ((op & SPIFFS_OP_COM_MASK) == SPIFFS_OP_C_DELE &&
+ (op & SPIFFS_OP_TYPE_MASK) != SPIFFS_OP_T_OBJ_LU) {
+ // page is being deleted, wipe from cache - unless it is a lookup page
+ spiffs_cache_page_free(fs, cp->ix, 0);
+ return SPIFFS_HAL_WRITE(fs, addr, len, src);
+ }
+
+ uint8_t *mem = spiffs_get_cache_page(fs, cache, cp->ix);
+ memcpy(&mem[SPIFFS_PADDR_TO_PAGE_OFFSET(fs, addr)], src, len);
+
+ cache->last_access++;
+ cp->last_access = cache->last_access;
+
+ if (cp->flags & SPIFFS_CACHE_FLAG_WRTHRU) {
+ // page is being updated, no write-cache, just pass thru
+ return SPIFFS_HAL_WRITE(fs, addr, len, src);
+ } else {
+ return SPIFFS_OK;
+ }
+ } else {
+ // no cache page, no write cache - just write thru
+ return SPIFFS_HAL_WRITE(fs, addr, len, src);
+ }
+}
+
+#if SPIFFS_CACHE_WR
+// returns the cache page that this fd refers, or null if no cache page
+spiffs_cache_page *spiffs_cache_page_get_by_fd(spiffs *fs, spiffs_fd *fd) {
+ spiffs_cache *cache = spiffs_get_cache(fs);
+
+ if ((cache->cpage_use_map & cache->cpage_use_mask) == 0) {
+ // all cpages free, no cpage cannot be assigned to obj_id
+ return 0;
+ }
+
+ int i;
+ for (i = 0; i < cache->cpage_count; i++) {
+ spiffs_cache_page *cp = spiffs_get_cache_page_hdr(fs, cache, i);
+ if ((cache->cpage_use_map & (1<flags & SPIFFS_CACHE_FLAG_TYPE_WR) &&
+ cp->obj_id == fd->obj_id) {
+ return cp;
+ }
+ }
+
+ return 0;
+}
+
+// allocates a new cache page and refers this to given fd - flushes an old cache
+// page if all cache is busy
+spiffs_cache_page *spiffs_cache_page_allocate_by_fd(spiffs *fs, spiffs_fd *fd) {
+ // before this function is called, it is ensured that there is no already existing
+ // cache page with same object id
+ spiffs_cache_page_remove_oldest(fs, SPIFFS_CACHE_FLAG_TYPE_WR, 0);
+ spiffs_cache_page *cp = spiffs_cache_page_allocate(fs);
+ if (cp == 0) {
+ // could not get cache page
+ return 0;
+ }
+
+ cp->flags = SPIFFS_CACHE_FLAG_TYPE_WR;
+ cp->obj_id = fd->obj_id;
+ fd->cache_page = cp;
+ return cp;
+}
+
+// unrefers all fds that this cache page refers to and releases the cache page
+void spiffs_cache_fd_release(spiffs *fs, spiffs_cache_page *cp) {
+ if (cp == 0) return;
+ uint32_t i;
+ spiffs_fd *fds = (spiffs_fd *)fs->fd_space;
+ for (i = 0; i < fs->fd_count; i++) {
+ spiffs_fd *cur_fd = &fds[i];
+ if (cur_fd->file_nbr != 0 && cur_fd->cache_page == cp) {
+ cur_fd->cache_page = 0;
+ }
+ }
+ spiffs_cache_page_free(fs, cp->ix, 0);
+
+ cp->obj_id = 0;
+}
+
+#endif
+
+// initializes the cache
+void spiffs_cache_init(spiffs *fs) {
+ if (fs->cache == 0) return;
+ uint32_t sz = fs->cache_size;
+ uint32_t cache_mask = 0;
+ int i;
+ int cache_entries =
+ (sz - sizeof(spiffs_cache)) / (SPIFFS_CACHE_PAGE_SIZE(fs));
+ if (cache_entries <= 0) return;
+
+ for (i = 0; i < cache_entries; i++) {
+ cache_mask <<= 1;
+ cache_mask |= 1;
+ }
+
+ spiffs_cache cache;
+ memset(&cache, 0, sizeof(spiffs_cache));
+ cache.cpage_count = cache_entries;
+ cache.cpages = (uint8_t *)((uint8_t *)fs->cache + sizeof(spiffs_cache));
+
+ cache.cpage_use_map = 0xffffffff;
+ cache.cpage_use_mask = cache_mask;
+ memcpy(fs->cache, &cache, sizeof(spiffs_cache));
+
+ spiffs_cache *c = spiffs_get_cache(fs);
+
+ memset(c->cpages, 0, c->cpage_count * SPIFFS_CACHE_PAGE_SIZE(fs));
+
+ c->cpage_use_map &= ~(c->cpage_use_mask);
+ for (i = 0; i < cache.cpage_count; i++) {
+ spiffs_get_cache_page_hdr(fs, c, i)->ix = i;
+ }
+}
+
+#endif // SPIFFS_CACHE
diff --git a/fw/User/spiffs/src/spiffs_check.c b/fw/User/spiffs/src/spiffs_check.c
new file mode 100644
index 0000000..a5d3e78
--- /dev/null
+++ b/fw/User/spiffs/src/spiffs_check.c
@@ -0,0 +1,995 @@
+/*
+ * spiffs_check.c
+ *
+ * Contains functionality for checking file system consistency
+ * and mending problems.
+ * Three levels of consistency checks are implemented:
+ *
+ * Look up consistency
+ * Checks if indices in lookup pages are coherent with page headers
+ * Object index consistency
+ * Checks if there are any orphaned object indices (missing object index headers).
+ * If an object index is found but not its header, the object index is deleted.
+ * This is critical for the following page consistency check.
+ * Page consistency
+ * Checks for pages that ought to be indexed, ought not to be indexed, are multiple indexed
+ *
+ *
+ * Created on: Jul 7, 2013
+ * Author: petera
+ */
+
+
+#include "spiffs.h"
+#include "spiffs_nucleus.h"
+
+#if !SPIFFS_READ_ONLY
+
+#if SPIFFS_HAL_CALLBACK_EXTRA
+#define CHECK_CB(_fs, _type, _rep, _arg1, _arg2) \
+ do { \
+ if ((_fs)->check_cb_f) (_fs)->check_cb_f((_fs), (_type), (_rep), (_arg1), (_arg2)); \
+ } while (0)
+#else
+#define CHECK_CB(_fs, _type, _rep, _arg1, _arg2) \
+ do { \
+ if ((_fs)->check_cb_f) (_fs)->check_cb_f((_type), (_rep), (_arg1), (_arg2)); \
+ } while (0)
+#endif
+
+//---------------------------------------
+// Look up consistency
+
+// searches in the object indices and returns the referenced page index given
+// the object id and the data span index
+// destroys fs->lu_work
+static int32_t spiffs_object_get_data_page_index_reference(
+ spiffs *fs,
+ spiffs_obj_id obj_id,
+ spiffs_span_ix data_spix,
+ spiffs_page_ix *pix,
+ spiffs_page_ix *objix_pix) {
+ int32_t res;
+
+ // calculate object index span index for given data page span index
+ spiffs_span_ix objix_spix = SPIFFS_OBJ_IX_ENTRY_SPAN_IX(fs, data_spix);
+
+ // find obj index for obj id and span index
+ res = spiffs_obj_lu_find_id_and_span(fs, obj_id | SPIFFS_OBJ_ID_IX_FLAG, objix_spix, 0, objix_pix);
+ SPIFFS_CHECK_RES(res);
+
+ // load obj index entry
+ uint32_t addr = SPIFFS_PAGE_TO_PADDR(fs, *objix_pix);
+ if (objix_spix == 0) {
+ // get referenced page from object index header
+ addr += sizeof(spiffs_page_object_ix_header) + data_spix * sizeof(spiffs_page_ix);
+ } else {
+ // get referenced page from object index
+ addr += sizeof(spiffs_page_object_ix) + SPIFFS_OBJ_IX_ENTRY(fs, data_spix) * sizeof(spiffs_page_ix);
+ }
+
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ, 0, addr, sizeof(spiffs_page_ix), (uint8_t *)pix);
+
+ return res;
+}
+
+// copies page contents to a new page
+static int32_t spiffs_rewrite_page(spiffs *fs, spiffs_page_ix cur_pix, spiffs_page_header *p_hdr, spiffs_page_ix *new_pix) {
+ int32_t res;
+ res = spiffs_page_allocate_data(fs, p_hdr->obj_id, p_hdr, 0,0,0,0, new_pix);
+ SPIFFS_CHECK_RES(res);
+ res = spiffs_phys_cpy(fs, 0,
+ SPIFFS_PAGE_TO_PADDR(fs, *new_pix) + sizeof(spiffs_page_header),
+ SPIFFS_PAGE_TO_PADDR(fs, cur_pix) + sizeof(spiffs_page_header),
+ SPIFFS_DATA_PAGE_SIZE(fs));
+ SPIFFS_CHECK_RES(res);
+ return res;
+}
+
+// rewrites the object index for given object id and replaces the
+// data page index to a new page index
+static int32_t spiffs_rewrite_index(spiffs *fs, spiffs_obj_id obj_id, spiffs_span_ix data_spix, spiffs_page_ix new_data_pix, spiffs_page_ix objix_pix) {
+ int32_t res;
+ spiffs_block_ix bix;
+ int entry;
+ spiffs_page_ix free_pix;
+ obj_id |= SPIFFS_OBJ_ID_IX_FLAG;
+
+ // find free entry
+ res = spiffs_obj_lu_find_free(fs, fs->free_cursor_block_ix, fs->free_cursor_obj_lu_entry, &bix, &entry);
+ SPIFFS_CHECK_RES(res);
+ free_pix = SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, bix, entry);
+
+ // calculate object index span index for given data page span index
+ spiffs_span_ix objix_spix = SPIFFS_OBJ_IX_ENTRY_SPAN_IX(fs, data_spix);
+ if (objix_spix == 0) {
+ // calc index in index header
+ entry = data_spix;
+ } else {
+ // calc entry in index
+ entry = SPIFFS_OBJ_IX_ENTRY(fs, data_spix);
+
+ }
+ // load index
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ,
+ 0, SPIFFS_PAGE_TO_PADDR(fs, objix_pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->lu_work);
+ SPIFFS_CHECK_RES(res);
+ spiffs_page_header *objix_p_hdr = (spiffs_page_header *)fs->lu_work;
+
+ // be ultra safe, double check header against provided data
+ if (objix_p_hdr->obj_id != obj_id) {
+ spiffs_page_delete(fs, free_pix);
+ return SPIFFS_ERR_CHECK_OBJ_ID_MISM;
+ }
+ if (objix_p_hdr->span_ix != objix_spix) {
+ spiffs_page_delete(fs, free_pix);
+ return SPIFFS_ERR_CHECK_SPIX_MISM;
+ }
+ if ((objix_p_hdr->flags & (SPIFFS_PH_FLAG_USED | SPIFFS_PH_FLAG_IXDELE | SPIFFS_PH_FLAG_INDEX |
+ SPIFFS_PH_FLAG_FINAL | SPIFFS_PH_FLAG_DELET)) !=
+ (SPIFFS_PH_FLAG_IXDELE | SPIFFS_PH_FLAG_DELET)) {
+ spiffs_page_delete(fs, free_pix);
+ return SPIFFS_ERR_CHECK_FLAGS_BAD;
+ }
+
+ // rewrite in mem
+ if (objix_spix == 0) {
+ ((spiffs_page_ix*)((uint8_t *)fs->lu_work + sizeof(spiffs_page_object_ix_header)))[data_spix] = new_data_pix;
+ } else {
+ ((spiffs_page_ix*)((uint8_t *)fs->lu_work + sizeof(spiffs_page_object_ix)))[SPIFFS_OBJ_IX_ENTRY(fs, data_spix)] = new_data_pix;
+ }
+
+ res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_UPDT,
+ 0, SPIFFS_PAGE_TO_PADDR(fs, free_pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->lu_work);
+ SPIFFS_CHECK_RES(res);
+ res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_LU | SPIFFS_OP_C_UPDT,
+ 0, SPIFFS_BLOCK_TO_PADDR(fs, SPIFFS_BLOCK_FOR_PAGE(fs, free_pix)) + SPIFFS_OBJ_LOOKUP_ENTRY_FOR_PAGE(fs, free_pix) * sizeof(spiffs_page_ix),
+ sizeof(spiffs_obj_id),
+ (uint8_t *)&obj_id);
+ SPIFFS_CHECK_RES(res);
+ res = spiffs_page_delete(fs, objix_pix);
+
+ return res;
+}
+
+// deletes an object just by marking object index header as deleted
+static int32_t spiffs_delete_obj_lazy(spiffs *fs, spiffs_obj_id obj_id) {
+ spiffs_page_ix objix_hdr_pix;
+ int32_t res;
+ res = spiffs_obj_lu_find_id_and_span(fs, obj_id, 0, 0, &objix_hdr_pix);
+ if (res == SPIFFS_ERR_NOT_FOUND) {
+ return SPIFFS_OK;
+ }
+ SPIFFS_CHECK_RES(res);
+ uint8_t flags = 0xff & ~SPIFFS_PH_FLAG_IXDELE;
+ res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_LU | SPIFFS_OP_C_UPDT,
+ 0, SPIFFS_PAGE_TO_PADDR(fs, objix_hdr_pix) + offsetof(spiffs_page_header, flags),
+ sizeof(uint8_t),
+ (uint8_t *)&flags);
+ return res;
+}
+
+// validates the given look up entry
+static int32_t spiffs_lookup_check_validate(spiffs *fs, spiffs_obj_id lu_obj_id, spiffs_page_header *p_hdr,
+ spiffs_page_ix cur_pix, spiffs_block_ix cur_block, int cur_entry, int *reload_lu) {
+ (void)cur_block;
+ (void)cur_entry;
+ uint8_t delete_page = 0;
+ int32_t res = SPIFFS_OK;
+ spiffs_page_ix objix_pix;
+ spiffs_page_ix ref_pix;
+ // check validity, take actions
+ if (((lu_obj_id == SPIFFS_OBJ_ID_DELETED) && (p_hdr->flags & SPIFFS_PH_FLAG_DELET)) ||
+ ((lu_obj_id == SPIFFS_OBJ_ID_FREE) && (p_hdr->flags & SPIFFS_PH_FLAG_USED) == 0)) {
+ // look up entry deleted / free but used in page header
+ SPIFFS_CHECK_DBG("LU: pix %04x deleted/free in lu but not on page\n", cur_pix);
+ *reload_lu = 1;
+ delete_page = 1;
+ if (p_hdr->flags & SPIFFS_PH_FLAG_INDEX) {
+ // header says data page
+ // data page can be removed if not referenced by some object index
+ res = spiffs_object_get_data_page_index_reference(fs, p_hdr->obj_id, p_hdr->span_ix, &ref_pix, &objix_pix);
+ if (res == SPIFFS_ERR_NOT_FOUND) {
+ // no object with this id, so remove page safely
+ res = SPIFFS_OK;
+ } else {
+ SPIFFS_CHECK_RES(res);
+ if (ref_pix == cur_pix) {
+ // data page referenced by object index but deleted in lu
+ // copy page to new place and re-write the object index to new place
+ spiffs_page_ix new_pix;
+ res = spiffs_rewrite_page(fs, cur_pix, p_hdr, &new_pix);
+ SPIFFS_CHECK_DBG("LU: FIXUP: data page not found elsewhere, rewriting %04x to new page %04x\n", cur_pix, new_pix);
+ SPIFFS_CHECK_RES(res);
+ *reload_lu = 1;
+ SPIFFS_CHECK_DBG("LU: FIXUP: %04x rewritten to %04x, affected objix_pix %04x\n", cur_pix, new_pix, objix_pix);
+ res = spiffs_rewrite_index(fs, p_hdr->obj_id, p_hdr->span_ix, new_pix, objix_pix);
+ if (res <= _SPIFFS_ERR_CHECK_FIRST && res > _SPIFFS_ERR_CHECK_LAST) {
+ // index bad also, cannot mend this file
+ SPIFFS_CHECK_DBG("LU: FIXUP: index bad %i, cannot mend!\n", res);
+ res = spiffs_page_delete(fs, new_pix);
+ SPIFFS_CHECK_RES(res);
+ res = spiffs_delete_obj_lazy(fs, p_hdr->obj_id);
+ CHECK_CB(fs, SPIFFS_CHECK_LOOKUP, SPIFFS_CHECK_DELETE_BAD_FILE, p_hdr->obj_id, 0);
+ } else {
+ CHECK_CB(fs, SPIFFS_CHECK_LOOKUP, SPIFFS_CHECK_FIX_INDEX, p_hdr->obj_id, p_hdr->span_ix);
+ }
+ SPIFFS_CHECK_RES(res);
+ }
+ }
+ } else {
+ // header says index page
+ // index page can be removed if other index with same obj_id and spanix is found
+ res = spiffs_obj_lu_find_id_and_span(fs, p_hdr->obj_id | SPIFFS_OBJ_ID_IX_FLAG, p_hdr->span_ix, cur_pix, 0);
+ if (res == SPIFFS_ERR_NOT_FOUND) {
+ // no such index page found, check for a data page amongst page headers
+ // lu cannot be trusted
+ res = spiffs_obj_lu_find_id_and_span_by_phdr(fs, p_hdr->obj_id | SPIFFS_OBJ_ID_IX_FLAG, 0, 0, 0);
+ if (res == SPIFFS_OK) { // ignore other errors
+ // got a data page also, assume lu corruption only, rewrite to new page
+ spiffs_page_ix new_pix;
+ res = spiffs_rewrite_page(fs, cur_pix, p_hdr, &new_pix);
+ SPIFFS_CHECK_DBG("LU: FIXUP: ix page with data not found elsewhere, rewriting %04x to new page %04x\n", cur_pix, new_pix);
+ SPIFFS_CHECK_RES(res);
+ *reload_lu = 1;
+ CHECK_CB(fs, SPIFFS_CHECK_LOOKUP, SPIFFS_CHECK_FIX_LOOKUP, p_hdr->obj_id, p_hdr->span_ix);
+ }
+ } else {
+ SPIFFS_CHECK_RES(res);
+ }
+ }
+ }
+ if (lu_obj_id != SPIFFS_OBJ_ID_FREE && lu_obj_id != SPIFFS_OBJ_ID_DELETED) {
+ // look up entry used
+ if ((p_hdr->obj_id | SPIFFS_OBJ_ID_IX_FLAG) != (lu_obj_id | SPIFFS_OBJ_ID_IX_FLAG)) {
+ SPIFFS_CHECK_DBG("LU: pix %04x differ in obj_id lu:%04x ph:%04x\n", cur_pix, lu_obj_id, p_hdr->obj_id);
+ delete_page = 1;
+ if ((p_hdr->flags & SPIFFS_PH_FLAG_DELET) == 0 ||
+ (p_hdr->flags & SPIFFS_PH_FLAG_FINAL) ||
+ (p_hdr->flags & (SPIFFS_PH_FLAG_INDEX | SPIFFS_PH_FLAG_IXDELE)) == 0) {
+ // page deleted or not finalized, just remove it
+ } else {
+ if (p_hdr->flags & SPIFFS_PH_FLAG_INDEX) {
+ // if data page, check for reference to this page
+ res = spiffs_object_get_data_page_index_reference(fs, p_hdr->obj_id, p_hdr->span_ix, &ref_pix, &objix_pix);
+ if (res == SPIFFS_ERR_NOT_FOUND) {
+ // no object with this id, so remove page safely
+ res = SPIFFS_OK;
+ } else {
+ SPIFFS_CHECK_RES(res);
+ // if found, rewrite page with object id, update index, and delete current
+ if (ref_pix == cur_pix) {
+ spiffs_page_ix new_pix;
+ res = spiffs_rewrite_page(fs, cur_pix, p_hdr, &new_pix);
+ SPIFFS_CHECK_RES(res);
+ res = spiffs_rewrite_index(fs, p_hdr->obj_id, p_hdr->span_ix, new_pix, objix_pix);
+ if (res <= _SPIFFS_ERR_CHECK_FIRST && res > _SPIFFS_ERR_CHECK_LAST) {
+ // index bad also, cannot mend this file
+ SPIFFS_CHECK_DBG("LU: FIXUP: index bad %i, cannot mend!\n", res);
+ res = spiffs_page_delete(fs, new_pix);
+ SPIFFS_CHECK_RES(res);
+ res = spiffs_delete_obj_lazy(fs, p_hdr->obj_id);
+ *reload_lu = 1;
+ CHECK_CB(fs, SPIFFS_CHECK_LOOKUP, SPIFFS_CHECK_DELETE_BAD_FILE, p_hdr->obj_id, 0);
+ }
+ SPIFFS_CHECK_RES(res);
+ }
+ }
+ } else {
+ // else if index, check for other pages with both obj_id's and spanix
+ spiffs_page_ix objix_pix_lu, objix_pix_ph;
+ // see if other object index page exists for lookup obj id and span index
+ res = spiffs_obj_lu_find_id_and_span(fs, lu_obj_id | SPIFFS_OBJ_ID_IX_FLAG, p_hdr->span_ix, 0, &objix_pix_lu);
+ if (res == SPIFFS_ERR_NOT_FOUND) {
+ res = SPIFFS_OK;
+ objix_pix_lu = 0;
+ }
+ SPIFFS_CHECK_RES(res);
+ // see if other object index exists for page header obj id and span index
+ res = spiffs_obj_lu_find_id_and_span(fs, p_hdr->obj_id | SPIFFS_OBJ_ID_IX_FLAG, p_hdr->span_ix, 0, &objix_pix_ph);
+ if (res == SPIFFS_ERR_NOT_FOUND) {
+ res = SPIFFS_OK;
+ objix_pix_ph = 0;
+ }
+ SPIFFS_CHECK_RES(res);
+ // if both obj_id's found, just delete current
+ if (objix_pix_ph == 0 || objix_pix_lu == 0) {
+ // otherwise try finding first corresponding data pages
+ spiffs_page_ix data_pix_lu, data_pix_ph;
+ // see if other data page exists for look up obj id and span index
+ res = spiffs_obj_lu_find_id_and_span(fs, lu_obj_id & ~SPIFFS_OBJ_ID_IX_FLAG, 0, 0, &data_pix_lu);
+ if (res == SPIFFS_ERR_NOT_FOUND) {
+ res = SPIFFS_OK;
+ objix_pix_lu = 0;
+ }
+ SPIFFS_CHECK_RES(res);
+ // see if other data page exists for page header obj id and span index
+ res = spiffs_obj_lu_find_id_and_span(fs, p_hdr->obj_id & ~SPIFFS_OBJ_ID_IX_FLAG, 0, 0, &data_pix_ph);
+ if (res == SPIFFS_ERR_NOT_FOUND) {
+ res = SPIFFS_OK;
+ objix_pix_ph = 0;
+ }
+ SPIFFS_CHECK_RES(res);
+
+ spiffs_page_header new_ph;
+ new_ph.flags = 0xff & ~(SPIFFS_PH_FLAG_USED | SPIFFS_PH_FLAG_INDEX | SPIFFS_PH_FLAG_FINAL);
+ new_ph.span_ix = p_hdr->span_ix;
+ spiffs_page_ix new_pix;
+ if ((objix_pix_lu && data_pix_lu && data_pix_ph && objix_pix_ph == 0) ||
+ (objix_pix_lu == 0 && data_pix_ph && objix_pix_ph == 0)) {
+ // got a data page for page header obj id
+ // rewrite as obj_id_ph
+ new_ph.obj_id = p_hdr->obj_id | SPIFFS_OBJ_ID_IX_FLAG;
+ res = spiffs_rewrite_page(fs, cur_pix, &new_ph, &new_pix);
+ SPIFFS_CHECK_DBG("LU: FIXUP: rewrite page %04x as %04x to pix %04x\n", cur_pix, new_ph.obj_id, new_pix);
+ CHECK_CB(fs, SPIFFS_CHECK_LOOKUP, SPIFFS_CHECK_FIX_LOOKUP, p_hdr->obj_id, p_hdr->span_ix);
+ SPIFFS_CHECK_RES(res);
+ *reload_lu = 1;
+ } else if ((objix_pix_ph && data_pix_ph && data_pix_lu && objix_pix_lu == 0) ||
+ (objix_pix_ph == 0 && data_pix_lu && objix_pix_lu == 0)) {
+ // got a data page for look up obj id
+ // rewrite as obj_id_lu
+ new_ph.obj_id = lu_obj_id | SPIFFS_OBJ_ID_IX_FLAG;
+ SPIFFS_CHECK_DBG("LU: FIXUP: rewrite page %04x as %04x\n", cur_pix, new_ph.obj_id);
+ CHECK_CB(fs, SPIFFS_CHECK_LOOKUP, SPIFFS_CHECK_FIX_LOOKUP, p_hdr->obj_id, p_hdr->span_ix);
+ res = spiffs_rewrite_page(fs, cur_pix, &new_ph, &new_pix);
+ SPIFFS_CHECK_RES(res);
+ *reload_lu = 1;
+ } else {
+ // cannot safely do anything
+ SPIFFS_CHECK_DBG("LU: FIXUP: nothing to do, just delete\n");
+ }
+ }
+ }
+ }
+ } else if (((lu_obj_id & SPIFFS_OBJ_ID_IX_FLAG) && (p_hdr->flags & SPIFFS_PH_FLAG_INDEX)) ||
+ ((lu_obj_id & SPIFFS_OBJ_ID_IX_FLAG) == 0 && (p_hdr->flags & SPIFFS_PH_FLAG_INDEX) == 0)) {
+ SPIFFS_CHECK_DBG("LU: %04x lu/page index marking differ\n", cur_pix);
+ spiffs_page_ix data_pix, objix_pix_d;
+ // see if other data page exists for given obj id and span index
+ res = spiffs_obj_lu_find_id_and_span(fs, lu_obj_id & ~SPIFFS_OBJ_ID_IX_FLAG, p_hdr->span_ix, cur_pix, &data_pix);
+ if (res == SPIFFS_ERR_NOT_FOUND) {
+ res = SPIFFS_OK;
+ data_pix = 0;
+ }
+ SPIFFS_CHECK_RES(res);
+ // see if other object index exists for given obj id and span index
+ res = spiffs_obj_lu_find_id_and_span(fs, lu_obj_id | SPIFFS_OBJ_ID_IX_FLAG, p_hdr->span_ix, cur_pix, &objix_pix_d);
+ if (res == SPIFFS_ERR_NOT_FOUND) {
+ res = SPIFFS_OK;
+ objix_pix_d = 0;
+ }
+ SPIFFS_CHECK_RES(res);
+
+ delete_page = 1;
+ // if other data page exists and object index exists, just delete page
+ if (data_pix && objix_pix_d) {
+ SPIFFS_CHECK_DBG("LU: FIXUP: other index and data page exists, simply remove\n");
+ } else
+ // if only data page exists, make this page index
+ if (data_pix && objix_pix_d == 0) {
+ SPIFFS_CHECK_DBG("LU: FIXUP: other data page exists, make this index\n");
+ CHECK_CB(fs, SPIFFS_CHECK_LOOKUP, SPIFFS_CHECK_FIX_INDEX, lu_obj_id, p_hdr->span_ix);
+ spiffs_page_header new_ph;
+ spiffs_page_ix new_pix;
+ new_ph.flags = 0xff & ~(SPIFFS_PH_FLAG_USED | SPIFFS_PH_FLAG_FINAL | SPIFFS_PH_FLAG_INDEX);
+ new_ph.obj_id = lu_obj_id | SPIFFS_OBJ_ID_IX_FLAG;
+ new_ph.span_ix = p_hdr->span_ix;
+ res = spiffs_page_allocate_data(fs, new_ph.obj_id, &new_ph, 0, 0, 0, 1, &new_pix);
+ SPIFFS_CHECK_RES(res);
+ res = spiffs_phys_cpy(fs, 0, SPIFFS_PAGE_TO_PADDR(fs, new_pix) + sizeof(spiffs_page_header),
+ SPIFFS_PAGE_TO_PADDR(fs, cur_pix) + sizeof(spiffs_page_header),
+ SPIFFS_CFG_LOG_PAGE_SZ(fs) - sizeof(spiffs_page_header));
+ SPIFFS_CHECK_RES(res);
+ } else
+ // if only index exists, make data page
+ if (data_pix == 0 && objix_pix_d) {
+ SPIFFS_CHECK_DBG("LU: FIXUP: other index page exists, make this data\n");
+ CHECK_CB(fs, SPIFFS_CHECK_LOOKUP, SPIFFS_CHECK_FIX_LOOKUP, lu_obj_id, p_hdr->span_ix);
+ spiffs_page_header new_ph;
+ spiffs_page_ix new_pix;
+ new_ph.flags = 0xff & ~(SPIFFS_PH_FLAG_USED | SPIFFS_PH_FLAG_FINAL);
+ new_ph.obj_id = lu_obj_id & ~SPIFFS_OBJ_ID_IX_FLAG;
+ new_ph.span_ix = p_hdr->span_ix;
+ res = spiffs_page_allocate_data(fs, new_ph.obj_id, &new_ph, 0, 0, 0, 1, &new_pix);
+ SPIFFS_CHECK_RES(res);
+ res = spiffs_phys_cpy(fs, 0, SPIFFS_PAGE_TO_PADDR(fs, new_pix) + sizeof(spiffs_page_header),
+ SPIFFS_PAGE_TO_PADDR(fs, cur_pix) + sizeof(spiffs_page_header),
+ SPIFFS_CFG_LOG_PAGE_SZ(fs) - sizeof(spiffs_page_header));
+ SPIFFS_CHECK_RES(res);
+ } else {
+ // if nothing exists, we cannot safely make a decision - delete
+ }
+ }
+ else if ((p_hdr->flags & SPIFFS_PH_FLAG_DELET) == 0) {
+ SPIFFS_CHECK_DBG("LU: pix %04x busy in lu but deleted on page\n", cur_pix);
+ delete_page = 1;
+ } else if ((p_hdr->flags & SPIFFS_PH_FLAG_FINAL)) {
+ SPIFFS_CHECK_DBG("LU: pix %04x busy but not final\n", cur_pix);
+ // page can be removed if not referenced by object index
+ *reload_lu = 1;
+ res = spiffs_object_get_data_page_index_reference(fs, lu_obj_id, p_hdr->span_ix, &ref_pix, &objix_pix);
+ if (res == SPIFFS_ERR_NOT_FOUND) {
+ // no object with this id, so remove page safely
+ res = SPIFFS_OK;
+ delete_page = 1;
+ } else {
+ SPIFFS_CHECK_RES(res);
+ if (ref_pix != cur_pix) {
+ SPIFFS_CHECK_DBG("LU: FIXUP: other finalized page is referred, just delete\n");
+ delete_page = 1;
+ } else {
+ // page referenced by object index but not final
+ // just finalize
+ SPIFFS_CHECK_DBG("LU: FIXUP: unfinalized page is referred, finalizing\n");
+ CHECK_CB(fs, SPIFFS_CHECK_LOOKUP, SPIFFS_CHECK_FIX_LOOKUP, p_hdr->obj_id, p_hdr->span_ix);
+ uint8_t flags = 0xff & ~SPIFFS_PH_FLAG_FINAL;
+ res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_UPDT,
+ 0, SPIFFS_PAGE_TO_PADDR(fs, cur_pix) + offsetof(spiffs_page_header, flags),
+ sizeof(uint8_t), (uint8_t*)&flags);
+ }
+ }
+ }
+ }
+
+ if (delete_page) {
+ SPIFFS_CHECK_DBG("LU: FIXUP: deleting page %04x\n", cur_pix);
+ CHECK_CB(fs, SPIFFS_CHECK_LOOKUP, SPIFFS_CHECK_DELETE_PAGE, cur_pix, 0);
+ res = spiffs_page_delete(fs, cur_pix);
+ SPIFFS_CHECK_RES(res);
+ }
+
+ return res;
+}
+
+static int32_t spiffs_lookup_check_v(spiffs *fs, spiffs_obj_id obj_id, spiffs_block_ix cur_block, int cur_entry,
+ const void *user_const_p, void *user_var_p) {
+ (void)user_const_p;
+ (void)user_var_p;
+ int32_t res = SPIFFS_OK;
+ spiffs_page_header p_hdr;
+ spiffs_page_ix cur_pix = SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, cur_block, cur_entry);
+
+ CHECK_CB(fs, SPIFFS_CHECK_LOOKUP, SPIFFS_CHECK_PROGRESS,
+ (cur_block * 256)/fs->block_count, 0);
+
+ // load header
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ,
+ 0, SPIFFS_PAGE_TO_PADDR(fs, cur_pix), sizeof(spiffs_page_header), (uint8_t*)&p_hdr);
+ SPIFFS_CHECK_RES(res);
+
+ int reload_lu = 0;
+
+ res = spiffs_lookup_check_validate(fs, obj_id, &p_hdr, cur_pix, cur_block, cur_entry, &reload_lu);
+ SPIFFS_CHECK_RES(res);
+
+ if (res == SPIFFS_OK) {
+ return reload_lu ? SPIFFS_VIS_COUNTINUE_RELOAD : SPIFFS_VIS_COUNTINUE;
+ }
+ return res;
+}
+
+
+// Scans all object look up. For each entry, corresponding page header is checked for validity.
+// If an object index header page is found, this is also checked
+int32_t spiffs_lookup_consistency_check(spiffs *fs, uint8_t check_all_objects) {
+ (void)check_all_objects;
+ int32_t res = SPIFFS_OK;
+
+ CHECK_CB(fs, SPIFFS_CHECK_LOOKUP, SPIFFS_CHECK_PROGRESS, 0, 0);
+
+ res = spiffs_obj_lu_find_entry_visitor(fs, 0, 0, 0, 0, spiffs_lookup_check_v, 0, 0, 0, 0);
+
+ if (res == SPIFFS_VIS_END) {
+ res = SPIFFS_OK;
+ }
+
+ if (res != SPIFFS_OK) {
+ CHECK_CB(fs, SPIFFS_CHECK_LOOKUP, SPIFFS_CHECK_ERROR, res, 0);
+ }
+
+ CHECK_CB(fs, SPIFFS_CHECK_LOOKUP, SPIFFS_CHECK_PROGRESS, 256, 0);
+
+ return res;
+}
+
+//---------------------------------------
+// Page consistency
+
+// Scans all pages (except lu pages), reserves 4 bits in working memory for each page
+// bit 0: 0 == FREE|DELETED, 1 == USED
+// bit 1: 0 == UNREFERENCED, 1 == REFERENCED
+// bit 2: 0 == NOT_INDEX, 1 == INDEX
+// bit 3: unused
+// A consistent file system will have only pages being
+// * x000 free, unreferenced, not index
+// * x011 used, referenced only once, not index
+// * x101 used, unreferenced, index
+// The working memory might not fit all pages so several scans might be needed
+static int32_t spiffs_page_consistency_check_i(spiffs *fs) {
+ const uint32_t bits = 4;
+ const spiffs_page_ix pages_per_scan = SPIFFS_CFG_LOG_PAGE_SZ(fs) * 8 / bits;
+
+ int32_t res = SPIFFS_OK;
+ spiffs_page_ix pix_offset = 0;
+
+ // for each range of pages fitting into work memory
+ while (pix_offset < SPIFFS_PAGES_PER_BLOCK(fs) * fs->block_count) {
+ // set this flag to abort all checks and rescan the page range
+ uint8_t restart = 0;
+ memset(fs->work, 0, SPIFFS_CFG_LOG_PAGE_SZ(fs));
+
+ spiffs_block_ix cur_block = 0;
+ // build consistency bitmap for id range traversing all blocks
+ while (!restart && cur_block < fs->block_count) {
+ CHECK_CB(fs, SPIFFS_CHECK_PAGE, SPIFFS_CHECK_PROGRESS,
+ (pix_offset*256)/(SPIFFS_PAGES_PER_BLOCK(fs) * fs->block_count) +
+ ((((cur_block * pages_per_scan * 256)/ (SPIFFS_PAGES_PER_BLOCK(fs) * fs->block_count))) / fs->block_count),
+ 0);
+ // traverse each page except for lookup pages
+ spiffs_page_ix cur_pix = SPIFFS_OBJ_LOOKUP_PAGES(fs) + SPIFFS_PAGES_PER_BLOCK(fs) * cur_block;
+ while (!restart && cur_pix < SPIFFS_PAGES_PER_BLOCK(fs) * (cur_block+1)) {
+ //if ((cur_pix & 0xff) == 0)
+ // SPIFFS_CHECK_DBG("PA: processing pix %08x, block %08x of pix %08x, block %08x\n",
+ // cur_pix, cur_block, SPIFFS_PAGES_PER_BLOCK(fs) * fs->block_count, fs->block_count);
+
+ // read header
+ spiffs_page_header p_hdr;
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ,
+ 0, SPIFFS_PAGE_TO_PADDR(fs, cur_pix), sizeof(spiffs_page_header), (uint8_t*)&p_hdr);
+ SPIFFS_CHECK_RES(res);
+
+ uint8_t within_range = (cur_pix >= pix_offset && cur_pix < pix_offset + pages_per_scan);
+ const uint32_t pix_byte_ix = (cur_pix - pix_offset) / (8/bits);
+ const uint8_t pix_bit_ix = (cur_pix & ((8/bits)-1)) * bits;
+
+ if (within_range &&
+ (p_hdr.flags & SPIFFS_PH_FLAG_DELET) && (p_hdr.flags & SPIFFS_PH_FLAG_USED) == 0) {
+ // used
+ fs->work[pix_byte_ix] |= (1<<(pix_bit_ix + 0));
+ }
+ if ((p_hdr.flags & SPIFFS_PH_FLAG_DELET) &&
+ (p_hdr.flags & SPIFFS_PH_FLAG_IXDELE) &&
+ (p_hdr.flags & (SPIFFS_PH_FLAG_INDEX | SPIFFS_PH_FLAG_USED)) == 0) {
+ // found non-deleted index
+ if (within_range) {
+ fs->work[pix_byte_ix] |= (1<<(pix_bit_ix + 2));
+ }
+
+ // load non-deleted index
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ,
+ 0, SPIFFS_PAGE_TO_PADDR(fs, cur_pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->lu_work);
+ SPIFFS_CHECK_RES(res);
+
+ // traverse index for referenced pages
+ spiffs_page_ix *object_page_index;
+ spiffs_page_header *objix_p_hdr = (spiffs_page_header *)fs->lu_work;
+
+ int entries;
+ int i;
+ spiffs_span_ix data_spix_offset;
+ if (p_hdr.span_ix == 0) {
+ // object header page index
+ entries = SPIFFS_OBJ_HDR_IX_LEN(fs);
+ data_spix_offset = 0;
+ object_page_index = (spiffs_page_ix *)((uint8_t *)fs->lu_work + sizeof(spiffs_page_object_ix_header));
+ } else {
+ // object page index
+ entries = SPIFFS_OBJ_IX_LEN(fs);
+ data_spix_offset = SPIFFS_OBJ_HDR_IX_LEN(fs) + SPIFFS_OBJ_IX_LEN(fs) * (p_hdr.span_ix - 1);
+ object_page_index = (spiffs_page_ix *)((uint8_t *)fs->lu_work + sizeof(spiffs_page_object_ix));
+ }
+
+ // for all entries in index
+ for (i = 0; !restart && i < entries; i++) {
+ spiffs_page_ix rpix = object_page_index[i];
+ uint8_t rpix_within_range = rpix >= pix_offset && rpix < pix_offset + pages_per_scan;
+
+ if ((rpix != (spiffs_page_ix)-1 && rpix > SPIFFS_MAX_PAGES(fs))
+ || (rpix_within_range && SPIFFS_IS_LOOKUP_PAGE(fs, rpix))) {
+
+ // bad reference
+ SPIFFS_CHECK_DBG("PA: pix %04x bad pix / LU referenced from page %04x\n",
+ rpix, cur_pix);
+ // check for data page elsewhere
+ spiffs_page_ix data_pix;
+ res = spiffs_obj_lu_find_id_and_span(fs, objix_p_hdr->obj_id & ~SPIFFS_OBJ_ID_IX_FLAG,
+ data_spix_offset + i, 0, &data_pix);
+ if (res == SPIFFS_ERR_NOT_FOUND) {
+ res = SPIFFS_OK;
+ data_pix = 0;
+ }
+ SPIFFS_CHECK_RES(res);
+ if (data_pix == 0) {
+ // if not, allocate free page
+ spiffs_page_header new_ph;
+ new_ph.flags = 0xff & ~(SPIFFS_PH_FLAG_USED | SPIFFS_PH_FLAG_FINAL);
+ new_ph.obj_id = objix_p_hdr->obj_id & ~SPIFFS_OBJ_ID_IX_FLAG;
+ new_ph.span_ix = data_spix_offset + i;
+ res = spiffs_page_allocate_data(fs, new_ph.obj_id, &new_ph, 0, 0, 0, 1, &data_pix);
+ SPIFFS_CHECK_RES(res);
+ SPIFFS_CHECK_DBG("PA: FIXUP: found no existing data page, created new @ %04x\n", data_pix);
+ }
+ // remap index
+ SPIFFS_CHECK_DBG("PA: FIXUP: rewriting index pix %04x\n", cur_pix);
+ res = spiffs_rewrite_index(fs, objix_p_hdr->obj_id | SPIFFS_OBJ_ID_IX_FLAG,
+ data_spix_offset + i, data_pix, cur_pix);
+ if (res <= _SPIFFS_ERR_CHECK_FIRST && res > _SPIFFS_ERR_CHECK_LAST) {
+ // index bad also, cannot mend this file
+ SPIFFS_CHECK_DBG("PA: FIXUP: index bad %i, cannot mend - delete object\n", res);
+ CHECK_CB(fs, SPIFFS_CHECK_PAGE, SPIFFS_CHECK_DELETE_BAD_FILE, objix_p_hdr->obj_id, 0);
+ // delete file
+ res = spiffs_page_delete(fs, cur_pix);
+ } else {
+ CHECK_CB(fs, SPIFFS_CHECK_PAGE, SPIFFS_CHECK_FIX_INDEX, objix_p_hdr->obj_id, objix_p_hdr->span_ix);
+ }
+ SPIFFS_CHECK_RES(res);
+ restart = 1;
+
+ } else if (rpix_within_range) {
+
+ // valid reference
+ // read referenced page header
+ spiffs_page_header rp_hdr;
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ,
+ 0, SPIFFS_PAGE_TO_PADDR(fs, rpix), sizeof(spiffs_page_header), (uint8_t*)&rp_hdr);
+ SPIFFS_CHECK_RES(res);
+
+ // cross reference page header check
+ if (rp_hdr.obj_id != (p_hdr.obj_id & ~SPIFFS_OBJ_ID_IX_FLAG) ||
+ rp_hdr.span_ix != data_spix_offset + i ||
+ (rp_hdr.flags & (SPIFFS_PH_FLAG_DELET | SPIFFS_PH_FLAG_INDEX | SPIFFS_PH_FLAG_USED)) !=
+ (SPIFFS_PH_FLAG_DELET | SPIFFS_PH_FLAG_INDEX)) {
+ SPIFFS_CHECK_DBG("PA: pix %04x has inconsistent page header ix id/span:%04x/%04x, ref id/span:%04x/%04x flags:%02x\n",
+ rpix, p_hdr.obj_id & ~SPIFFS_OBJ_ID_IX_FLAG, data_spix_offset + i,
+ rp_hdr.obj_id, rp_hdr.span_ix, rp_hdr.flags);
+ // try finding correct page
+ spiffs_page_ix data_pix;
+ res = spiffs_obj_lu_find_id_and_span(fs, p_hdr.obj_id & ~SPIFFS_OBJ_ID_IX_FLAG,
+ data_spix_offset + i, rpix, &data_pix);
+ if (res == SPIFFS_ERR_NOT_FOUND) {
+ res = SPIFFS_OK;
+ data_pix = 0;
+ }
+ SPIFFS_CHECK_RES(res);
+ if (data_pix == 0) {
+ // not found, this index is badly borked
+ SPIFFS_CHECK_DBG("PA: FIXUP: index bad, delete object id %04x\n", p_hdr.obj_id);
+ CHECK_CB(fs, SPIFFS_CHECK_PAGE, SPIFFS_CHECK_DELETE_BAD_FILE, p_hdr.obj_id, 0);
+ res = spiffs_delete_obj_lazy(fs, p_hdr.obj_id);
+ SPIFFS_CHECK_RES(res);
+ break;
+ } else {
+ // found it, so rewrite index
+ SPIFFS_CHECK_DBG("PA: FIXUP: found correct data pix %04x, rewrite ix pix %04x id %04x\n",
+ data_pix, cur_pix, p_hdr.obj_id);
+ res = spiffs_rewrite_index(fs, p_hdr.obj_id, data_spix_offset + i, data_pix, cur_pix);
+ if (res <= _SPIFFS_ERR_CHECK_FIRST && res > _SPIFFS_ERR_CHECK_LAST) {
+ // index bad also, cannot mend this file
+ SPIFFS_CHECK_DBG("PA: FIXUP: index bad %i, cannot mend!\n", res);
+ CHECK_CB(fs, SPIFFS_CHECK_PAGE, SPIFFS_CHECK_DELETE_BAD_FILE, p_hdr.obj_id, 0);
+ res = spiffs_delete_obj_lazy(fs, p_hdr.obj_id);
+ } else {
+ CHECK_CB(fs, SPIFFS_CHECK_PAGE, SPIFFS_CHECK_FIX_INDEX, p_hdr.obj_id, p_hdr.span_ix);
+ }
+ SPIFFS_CHECK_RES(res);
+ restart = 1;
+ }
+ }
+ else {
+ // mark rpix as referenced
+ const uint32_t rpix_byte_ix = (rpix - pix_offset) / (8/bits);
+ const uint8_t rpix_bit_ix = (rpix & ((8/bits)-1)) * bits;
+ if (fs->work[rpix_byte_ix] & (1<<(rpix_bit_ix + 1))) {
+ SPIFFS_CHECK_DBG("PA: pix %04x multiple referenced from page %04x\n",
+ rpix, cur_pix);
+ // Here, we should have fixed all broken references - getting this means there
+ // must be multiple files with same object id. Only solution is to delete
+ // the object which is referring to this page
+ SPIFFS_CHECK_DBG("PA: FIXUP: removing object %04x and page %04x\n",
+ p_hdr.obj_id, cur_pix);
+ CHECK_CB(fs, SPIFFS_CHECK_PAGE, SPIFFS_CHECK_DELETE_BAD_FILE, p_hdr.obj_id, 0);
+ res = spiffs_delete_obj_lazy(fs, p_hdr.obj_id);
+ SPIFFS_CHECK_RES(res);
+ // extra precaution, delete this page also
+ res = spiffs_page_delete(fs, cur_pix);
+ SPIFFS_CHECK_RES(res);
+ restart = 1;
+ }
+ fs->work[rpix_byte_ix] |= (1<<(rpix_bit_ix + 1));
+ }
+ }
+ } // for all index entries
+ } // found index
+
+ // next page
+ cur_pix++;
+ }
+ // next block
+ cur_block++;
+ }
+ // check consistency bitmap
+ if (!restart) {
+ spiffs_page_ix objix_pix;
+ spiffs_page_ix rpix;
+
+ uint32_t byte_ix;
+ uint8_t bit_ix;
+ for (byte_ix = 0; !restart && byte_ix < SPIFFS_CFG_LOG_PAGE_SZ(fs); byte_ix++) {
+ for (bit_ix = 0; !restart && bit_ix < 8/bits; bit_ix ++) {
+ uint8_t bitmask = (fs->work[byte_ix] >> (bit_ix * bits)) & 0x7;
+ spiffs_page_ix cur_pix = pix_offset + byte_ix * (8/bits) + bit_ix;
+
+ // 000 ok - free, unreferenced, not index
+
+ if (bitmask == 0x1) {
+
+ // 001
+ SPIFFS_CHECK_DBG("PA: pix %04x USED, UNREFERENCED, not index\n", cur_pix);
+
+ uint8_t rewrite_ix_to_this = 0;
+ uint8_t delete_page = 0;
+ // check corresponding object index entry
+ spiffs_page_header p_hdr;
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ,
+ 0, SPIFFS_PAGE_TO_PADDR(fs, cur_pix), sizeof(spiffs_page_header), (uint8_t*)&p_hdr);
+ SPIFFS_CHECK_RES(res);
+
+ res = spiffs_object_get_data_page_index_reference(fs, p_hdr.obj_id, p_hdr.span_ix,
+ &rpix, &objix_pix);
+ if (res == SPIFFS_OK) {
+ if (((rpix == (spiffs_page_ix)-1 || rpix > SPIFFS_MAX_PAGES(fs)) || (SPIFFS_IS_LOOKUP_PAGE(fs, rpix)))) {
+ // pointing to a bad page altogether, rewrite index to this
+ rewrite_ix_to_this = 1;
+ SPIFFS_CHECK_DBG("PA: corresponding ref is bad: %04x, rewrite to this %04x\n", rpix, cur_pix);
+ } else {
+ // pointing to something else, check what
+ spiffs_page_header rp_hdr;
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ,
+ 0, SPIFFS_PAGE_TO_PADDR(fs, rpix), sizeof(spiffs_page_header), (uint8_t*)&rp_hdr);
+ SPIFFS_CHECK_RES(res);
+ if (((p_hdr.obj_id & ~SPIFFS_OBJ_ID_IX_FLAG) == rp_hdr.obj_id) &&
+ ((rp_hdr.flags & (SPIFFS_PH_FLAG_INDEX | SPIFFS_PH_FLAG_DELET | SPIFFS_PH_FLAG_USED | SPIFFS_PH_FLAG_FINAL)) ==
+ (SPIFFS_PH_FLAG_INDEX | SPIFFS_PH_FLAG_DELET))) {
+ // pointing to something else valid, just delete this page then
+ SPIFFS_CHECK_DBG("PA: corresponding ref is good but different: %04x, delete this %04x\n", rpix, cur_pix);
+ delete_page = 1;
+ } else {
+ // pointing to something weird, update index to point to this page instead
+ if (rpix != cur_pix) {
+ SPIFFS_CHECK_DBG("PA: corresponding ref is weird: %04x %s%s%s%s, rewrite this %04x\n", rpix,
+ (rp_hdr.flags & SPIFFS_PH_FLAG_INDEX) ? "" : "INDEX ",
+ (rp_hdr.flags & SPIFFS_PH_FLAG_DELET) ? "" : "DELETED ",
+ (rp_hdr.flags & SPIFFS_PH_FLAG_USED) ? "NOTUSED " : "",
+ (rp_hdr.flags & SPIFFS_PH_FLAG_FINAL) ? "NOTFINAL " : "",
+ cur_pix);
+ rewrite_ix_to_this = 1;
+ } else {
+ // should not happen, destined for fubar
+ }
+ }
+ }
+ } else if (res == SPIFFS_ERR_NOT_FOUND) {
+ SPIFFS_CHECK_DBG("PA: corresponding ref not found, delete %04x\n", cur_pix);
+ delete_page = 1;
+ res = SPIFFS_OK;
+ }
+
+ if (rewrite_ix_to_this) {
+ // if pointing to invalid page, redirect index to this page
+ SPIFFS_CHECK_DBG("PA: FIXUP: rewrite index id %04x data spix %04x to point to this pix: %04x\n",
+ p_hdr.obj_id, p_hdr.span_ix, cur_pix);
+ res = spiffs_rewrite_index(fs, p_hdr.obj_id, p_hdr.span_ix, cur_pix, objix_pix);
+ if (res <= _SPIFFS_ERR_CHECK_FIRST && res > _SPIFFS_ERR_CHECK_LAST) {
+ // index bad also, cannot mend this file
+ SPIFFS_CHECK_DBG("PA: FIXUP: index bad %i, cannot mend!\n", res);
+ CHECK_CB(fs, SPIFFS_CHECK_PAGE, SPIFFS_CHECK_DELETE_BAD_FILE, p_hdr.obj_id, 0);
+ res = spiffs_page_delete(fs, cur_pix);
+ SPIFFS_CHECK_RES(res);
+ res = spiffs_delete_obj_lazy(fs, p_hdr.obj_id);
+ } else {
+ CHECK_CB(fs, SPIFFS_CHECK_PAGE, SPIFFS_CHECK_FIX_INDEX, p_hdr.obj_id, p_hdr.span_ix);
+ }
+ SPIFFS_CHECK_RES(res);
+ restart = 1;
+ continue;
+ } else if (delete_page) {
+ SPIFFS_CHECK_DBG("PA: FIXUP: deleting page %04x\n", cur_pix);
+ CHECK_CB(fs, SPIFFS_CHECK_PAGE, SPIFFS_CHECK_DELETE_PAGE, cur_pix, 0);
+ res = spiffs_page_delete(fs, cur_pix);
+ }
+ SPIFFS_CHECK_RES(res);
+ }
+ if (bitmask == 0x2) {
+
+ // 010
+ SPIFFS_CHECK_DBG("PA: pix %04x FREE, REFERENCED, not index\n", cur_pix);
+
+ // no op, this should be taken care of when checking valid references
+ }
+
+ // 011 ok - busy, referenced, not index
+
+ if (bitmask == 0x4) {
+
+ // 100
+ SPIFFS_CHECK_DBG("PA: pix %04x FREE, unreferenced, INDEX\n", cur_pix);
+
+ // this should never happen, major fubar
+ }
+
+ // 101 ok - busy, unreferenced, index
+
+ if (bitmask == 0x6) {
+
+ // 110
+ SPIFFS_CHECK_DBG("PA: pix %04x FREE, REFERENCED, INDEX\n", cur_pix);
+
+ // no op, this should be taken care of when checking valid references
+ }
+ if (bitmask == 0x7) {
+
+ // 111
+ SPIFFS_CHECK_DBG("PA: pix %04x USED, REFERENCED, INDEX\n", cur_pix);
+
+ // no op, this should be taken care of when checking valid references
+ }
+ }
+ }
+ }
+
+ SPIFFS_CHECK_DBG("PA: processed %04x, restart %i\n", pix_offset, restart);
+ // next page range
+ if (!restart) {
+ pix_offset += pages_per_scan;
+ }
+ } // while page range not reached end
+ return res;
+}
+
+// Checks consistency amongst all pages and fixes irregularities
+int32_t spiffs_page_consistency_check(spiffs *fs) {
+ CHECK_CB(fs, SPIFFS_CHECK_PAGE, SPIFFS_CHECK_PROGRESS, 0, 0);
+ int32_t res = spiffs_page_consistency_check_i(fs);
+ if (res != SPIFFS_OK) {
+ CHECK_CB(fs, SPIFFS_CHECK_PAGE, SPIFFS_CHECK_ERROR, res, 0);
+ }
+ CHECK_CB(fs, SPIFFS_CHECK_PAGE, SPIFFS_CHECK_PROGRESS, 256, 0);
+ return res;
+}
+
+//---------------------------------------
+// Object index consistency
+
+// searches for given object id in temporary object id index,
+// returns the index or -1
+static int spiffs_object_index_search(spiffs *fs, spiffs_obj_id obj_id) {
+ uint32_t i;
+ spiffs_obj_id *obj_table = (spiffs_obj_id *)fs->work;
+ obj_id &= ~SPIFFS_OBJ_ID_IX_FLAG;
+ for (i = 0; i < SPIFFS_CFG_LOG_PAGE_SZ(fs) / sizeof(spiffs_obj_id); i++) {
+ if ((obj_table[i] & ~SPIFFS_OBJ_ID_IX_FLAG) == obj_id) {
+ return i;
+ }
+ }
+ return -1;
+}
+
+static int32_t spiffs_object_index_consistency_check_v(spiffs *fs, spiffs_obj_id obj_id, spiffs_block_ix cur_block,
+ int cur_entry, const void *user_const_p, void *user_var_p) {
+ (void)user_const_p;
+ int32_t res_c = SPIFFS_VIS_COUNTINUE;
+ int32_t res = SPIFFS_OK;
+ uint32_t *log_ix = (uint32_t*)user_var_p;
+ spiffs_obj_id *obj_table = (spiffs_obj_id *)fs->work;
+
+ CHECK_CB(fs, SPIFFS_CHECK_INDEX, SPIFFS_CHECK_PROGRESS,
+ (cur_block * 256)/fs->block_count, 0);
+
+ if (obj_id != SPIFFS_OBJ_ID_FREE && obj_id != SPIFFS_OBJ_ID_DELETED && (obj_id & SPIFFS_OBJ_ID_IX_FLAG)) {
+ spiffs_page_header p_hdr;
+ spiffs_page_ix cur_pix = SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, cur_block, cur_entry);
+
+ // load header
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ,
+ 0, SPIFFS_PAGE_TO_PADDR(fs, cur_pix), sizeof(spiffs_page_header), (uint8_t*)&p_hdr);
+ SPIFFS_CHECK_RES(res);
+
+ if (p_hdr.span_ix == 0 &&
+ (p_hdr.flags & (SPIFFS_PH_FLAG_INDEX | SPIFFS_PH_FLAG_FINAL | SPIFFS_PH_FLAG_DELET | SPIFFS_PH_FLAG_IXDELE)) ==
+ (SPIFFS_PH_FLAG_DELET)) {
+ SPIFFS_CHECK_DBG("IX: pix %04x, obj id:%04x spix:%04x header not fully deleted - deleting\n",
+ cur_pix, obj_id, p_hdr.span_ix);
+ CHECK_CB(fs, SPIFFS_CHECK_INDEX, SPIFFS_CHECK_DELETE_PAGE, cur_pix, obj_id);
+ res = spiffs_page_delete(fs, cur_pix);
+ SPIFFS_CHECK_RES(res);
+ return res_c;
+ }
+
+ if ((p_hdr.flags & (SPIFFS_PH_FLAG_INDEX | SPIFFS_PH_FLAG_FINAL | SPIFFS_PH_FLAG_DELET | SPIFFS_PH_FLAG_IXDELE)) ==
+ (SPIFFS_PH_FLAG_DELET | SPIFFS_PH_FLAG_IXDELE)) {
+ return res_c;
+ }
+
+ if (p_hdr.span_ix == 0) {
+ // objix header page, register objid as reachable
+ int r = spiffs_object_index_search(fs, obj_id);
+ if (r == -1) {
+ // not registered, do it
+ obj_table[*log_ix] = obj_id & ~SPIFFS_OBJ_ID_IX_FLAG;
+ (*log_ix)++;
+ if (*log_ix >= SPIFFS_CFG_LOG_PAGE_SZ(fs) / sizeof(spiffs_obj_id)) {
+ *log_ix = 0;
+ }
+ }
+ } else { // span index
+ // objix page, see if header can be found
+ int r = spiffs_object_index_search(fs, obj_id);
+ uint8_t delete = 0;
+ if (r == -1) {
+ // not in temporary index, try finding it
+ spiffs_page_ix objix_hdr_pix;
+ res = spiffs_obj_lu_find_id_and_span(fs, obj_id | SPIFFS_OBJ_ID_IX_FLAG, 0, 0, &objix_hdr_pix);
+ res_c = SPIFFS_VIS_COUNTINUE_RELOAD;
+ if (res == SPIFFS_OK) {
+ // found, register as reachable
+ obj_table[*log_ix] = obj_id & ~SPIFFS_OBJ_ID_IX_FLAG;
+ } else if (res == SPIFFS_ERR_NOT_FOUND) {
+ // not found, register as unreachable
+ delete = 1;
+ obj_table[*log_ix] = obj_id | SPIFFS_OBJ_ID_IX_FLAG;
+ } else {
+ SPIFFS_CHECK_RES(res);
+ }
+ (*log_ix)++;
+ if (*log_ix >= SPIFFS_CFG_LOG_PAGE_SZ(fs) / sizeof(spiffs_obj_id)) {
+ *log_ix = 0;
+ }
+ } else {
+ // in temporary index, check reachable flag
+ if ((obj_table[r] & SPIFFS_OBJ_ID_IX_FLAG)) {
+ // registered as unreachable
+ delete = 1;
+ }
+ }
+
+ if (delete) {
+ SPIFFS_CHECK_DBG("IX: FIXUP: pix %04x, obj id:%04x spix:%04x is orphan index - deleting\n",
+ cur_pix, obj_id, p_hdr.span_ix);
+ CHECK_CB(fs, SPIFFS_CHECK_INDEX, SPIFFS_CHECK_DELETE_ORPHANED_INDEX, cur_pix, obj_id);
+ res = spiffs_page_delete(fs, cur_pix);
+ SPIFFS_CHECK_RES(res);
+ }
+ } // span index
+ } // valid object index id
+
+ return res_c;
+}
+
+// Removes orphaned and partially deleted index pages.
+// Scans for index pages. When an index page is found, corresponding index header is searched for.
+// If no such page exists, the index page cannot be reached as no index header exists and must be
+// deleted.
+int32_t spiffs_object_index_consistency_check(spiffs *fs) {
+ int32_t res = SPIFFS_OK;
+ // impl note:
+ // fs->work is used for a temporary object index memory, listing found object ids and
+ // indicating whether they can be reached or not. Acting as a fifo if object ids cannot fit.
+ // In the temporary object index memory, SPIFFS_OBJ_ID_IX_FLAG bit is used to indicate
+ // a reachable/unreachable object id.
+ memset(fs->work, 0, SPIFFS_CFG_LOG_PAGE_SZ(fs));
+ uint32_t obj_id_log_ix = 0;
+ CHECK_CB(fs, SPIFFS_CHECK_INDEX, SPIFFS_CHECK_PROGRESS, 0, 0);
+ res = spiffs_obj_lu_find_entry_visitor(fs, 0, 0, 0, 0, spiffs_object_index_consistency_check_v, 0, &obj_id_log_ix,
+ 0, 0);
+ if (res == SPIFFS_VIS_END) {
+ res = SPIFFS_OK;
+ }
+ if (res != SPIFFS_OK) {
+ CHECK_CB(fs, SPIFFS_CHECK_INDEX, SPIFFS_CHECK_ERROR, res, 0);
+ }
+ CHECK_CB(fs, SPIFFS_CHECK_INDEX, SPIFFS_CHECK_PROGRESS, 256, 0);
+ return res;
+}
+
+#endif // !SPIFFS_READ_ONLY
diff --git a/fw/User/spiffs/src/spiffs_gc.c b/fw/User/spiffs/src/spiffs_gc.c
new file mode 100644
index 0000000..51194ff
--- /dev/null
+++ b/fw/User/spiffs/src/spiffs_gc.c
@@ -0,0 +1,606 @@
+#include "spiffs.h"
+#include "spiffs_nucleus.h"
+
+#if !SPIFFS_READ_ONLY
+
+// Erases a logical block and updates the erase counter.
+// If cache is enabled, all pages that might be cached in this block
+// is dropped.
+static int32_t spiffs_gc_erase_block(
+ spiffs *fs,
+ spiffs_block_ix bix) {
+ int32_t res;
+
+ SPIFFS_GC_DBG("gc: erase block %i\n", bix);
+ res = spiffs_erase_block(fs, bix);
+ SPIFFS_CHECK_RES(res);
+
+#if SPIFFS_CACHE
+ {
+ uint32_t i;
+ for (i = 0; i < SPIFFS_PAGES_PER_BLOCK(fs); i++) {
+ spiffs_cache_drop_page(fs, SPIFFS_PAGE_FOR_BLOCK(fs, bix) + i);
+ }
+ }
+#endif
+ return res;
+}
+
+// Searches for blocks where all entries are deleted - if one is found,
+// the block is erased. Compared to the non-quick gc, the quick one ensures
+// that no updates are needed on existing objects on pages that are erased.
+int32_t spiffs_gc_quick(
+ spiffs *fs, uint16_t max_free_pages) {
+ int32_t res = SPIFFS_OK;
+ uint32_t blocks = fs->block_count;
+ spiffs_block_ix cur_block = 0;
+ uint32_t cur_block_addr = 0;
+ int cur_entry = 0;
+ spiffs_obj_id *obj_lu_buf = (spiffs_obj_id *)fs->lu_work;
+
+ SPIFFS_GC_DBG("gc_quick: running\n");
+#if SPIFFS_GC_STATS
+ fs->stats_gc_runs++;
+#endif
+
+ int entries_per_page = (SPIFFS_CFG_LOG_PAGE_SZ(fs) / sizeof(spiffs_obj_id));
+
+ // find fully deleted blocks
+ // check each block
+ while (res == SPIFFS_OK && blocks--) {
+ uint16_t deleted_pages_in_block = 0;
+ uint16_t free_pages_in_block = 0;
+
+ int obj_lookup_page = 0;
+ // check each object lookup page
+ while (res == SPIFFS_OK && obj_lookup_page < (int)SPIFFS_OBJ_LOOKUP_PAGES(fs)) {
+ int entry_offset = obj_lookup_page * entries_per_page;
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU | SPIFFS_OP_C_READ,
+ 0, cur_block_addr + SPIFFS_PAGE_TO_PADDR(fs, obj_lookup_page), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->lu_work);
+ // check each entry
+ while (res == SPIFFS_OK &&
+ cur_entry - entry_offset < entries_per_page &&
+ cur_entry < (int)(SPIFFS_PAGES_PER_BLOCK(fs)-SPIFFS_OBJ_LOOKUP_PAGES(fs))) {
+ spiffs_obj_id obj_id = obj_lu_buf[cur_entry-entry_offset];
+ if (obj_id == SPIFFS_OBJ_ID_DELETED) {
+ deleted_pages_in_block++;
+ } else if (obj_id == SPIFFS_OBJ_ID_FREE) {
+ // kill scan, go for next block
+ free_pages_in_block++;
+ if (free_pages_in_block > max_free_pages) {
+ obj_lookup_page = SPIFFS_OBJ_LOOKUP_PAGES(fs);
+ res = 1; // kill object lu loop
+ break;
+ }
+ } else {
+ // kill scan, go for next block
+ obj_lookup_page = SPIFFS_OBJ_LOOKUP_PAGES(fs);
+ res = 1; // kill object lu loop
+ break;
+ }
+ cur_entry++;
+ } // per entry
+ obj_lookup_page++;
+ } // per object lookup page
+ if (res == 1) res = SPIFFS_OK;
+
+ if (res == SPIFFS_OK &&
+ deleted_pages_in_block + free_pages_in_block == SPIFFS_PAGES_PER_BLOCK(fs)-SPIFFS_OBJ_LOOKUP_PAGES(fs) &&
+ free_pages_in_block <= max_free_pages) {
+ // found a fully deleted block
+ fs->stats_p_deleted -= deleted_pages_in_block;
+ res = spiffs_gc_erase_block(fs, cur_block);
+ return res;
+ }
+
+ cur_entry = 0;
+ cur_block++;
+ cur_block_addr += SPIFFS_CFG_LOG_BLOCK_SZ(fs);
+ } // per block
+
+ if (res == SPIFFS_OK) {
+ res = SPIFFS_ERR_NO_DELETED_BLOCKS;
+ }
+ return res;
+}
+
+// Checks if garbage collecting is necessary. If so a candidate block is found,
+// cleansed and erased
+int32_t spiffs_gc_check(
+ spiffs *fs,
+ uint32_t len) {
+ int32_t res;
+ int32_t free_pages =
+ (SPIFFS_PAGES_PER_BLOCK(fs) - SPIFFS_OBJ_LOOKUP_PAGES(fs)) * (fs->block_count-2)
+ - fs->stats_p_allocated - fs->stats_p_deleted;
+ int tries = 0;
+
+ if (fs->free_blocks > 3 &&
+ (int32_t)len < free_pages * (int32_t)SPIFFS_DATA_PAGE_SIZE(fs)) {
+ return SPIFFS_OK;
+ }
+
+ uint32_t needed_pages = (len + SPIFFS_DATA_PAGE_SIZE(fs) - 1) / SPIFFS_DATA_PAGE_SIZE(fs);
+// if (fs->free_blocks <= 2 && (int32_t)needed_pages > free_pages) {
+// SPIFFS_GC_DBG("gc: full freeblk:%i needed:%i free:%i dele:%i\n", fs->free_blocks, needed_pages, free_pages, fs->stats_p_deleted);
+// return SPIFFS_ERR_FULL;
+// }
+ if ((int32_t)needed_pages > (int32_t)(free_pages + fs->stats_p_deleted)) {
+ SPIFFS_GC_DBG("gc_check: full freeblk:%i needed:%i free:%i dele:%i\n", fs->free_blocks, needed_pages, free_pages, fs->stats_p_deleted);
+ return SPIFFS_ERR_FULL;
+ }
+
+ do {
+ SPIFFS_GC_DBG("\ngc_check #%i: run gc free_blocks:%i pfree:%i pallo:%i pdele:%i [%i] len:%i of %i\n",
+ tries,
+ fs->free_blocks, free_pages, fs->stats_p_allocated, fs->stats_p_deleted, (free_pages+fs->stats_p_allocated+fs->stats_p_deleted),
+ len, free_pages*SPIFFS_DATA_PAGE_SIZE(fs));
+
+ spiffs_block_ix *cands;
+ int count;
+ spiffs_block_ix cand;
+ int32_t prev_free_pages = free_pages;
+ // if the fs is crammed, ignore block age when selecting candidate - kind of a bad state
+ res = spiffs_gc_find_candidate(fs, &cands, &count, free_pages <= 0);
+ SPIFFS_CHECK_RES(res);
+ if (count == 0) {
+ SPIFFS_GC_DBG("gc_check: no candidates, return\n");
+ return (int32_t)needed_pages < free_pages ? SPIFFS_OK : SPIFFS_ERR_FULL;
+ }
+#if SPIFFS_GC_STATS
+ fs->stats_gc_runs++;
+#endif
+ cand = cands[0];
+ fs->cleaning = 1;
+ //printf("gcing: cleaning block %i\n", cand);
+ res = spiffs_gc_clean(fs, cand);
+ fs->cleaning = 0;
+ if (res < 0) {
+ SPIFFS_GC_DBG("gc_check: cleaning block %i, result %i\n", cand, res);
+ } else {
+ SPIFFS_GC_DBG("gc_check: cleaning block %i, result %i\n", cand, res);
+ }
+ SPIFFS_CHECK_RES(res);
+
+ res = spiffs_gc_erase_page_stats(fs, cand);
+ SPIFFS_CHECK_RES(res);
+
+ res = spiffs_gc_erase_block(fs, cand);
+ SPIFFS_CHECK_RES(res);
+
+ free_pages =
+ (SPIFFS_PAGES_PER_BLOCK(fs) - SPIFFS_OBJ_LOOKUP_PAGES(fs)) * (fs->block_count - 2)
+ - fs->stats_p_allocated - fs->stats_p_deleted;
+
+ if (prev_free_pages <= 0 && prev_free_pages == free_pages) {
+ // abort early to reduce wear, at least tried once
+ SPIFFS_GC_DBG("gc_check: early abort, no result on gc when fs crammed\n");
+ break;
+ }
+
+ } while (++tries < SPIFFS_GC_MAX_RUNS && (fs->free_blocks <= 2 ||
+ (int32_t)len > free_pages*(int32_t)SPIFFS_DATA_PAGE_SIZE(fs)));
+
+ free_pages =
+ (SPIFFS_PAGES_PER_BLOCK(fs) - SPIFFS_OBJ_LOOKUP_PAGES(fs)) * (fs->block_count - 2)
+ - fs->stats_p_allocated - fs->stats_p_deleted;
+ if ((int32_t)len > free_pages*(int32_t)SPIFFS_DATA_PAGE_SIZE(fs)) {
+ res = SPIFFS_ERR_FULL;
+ }
+
+ SPIFFS_GC_DBG("gc_check: finished, %i dirty, blocks %i free, %i pages free, %i tries, res %i\n",
+ fs->stats_p_allocated + fs->stats_p_deleted,
+ fs->free_blocks, free_pages, tries, res);
+
+ return res;
+}
+
+// Updates page statistics for a block that is about to be erased
+int32_t spiffs_gc_erase_page_stats(
+ spiffs *fs,
+ spiffs_block_ix bix) {
+ int32_t res = SPIFFS_OK;
+ int obj_lookup_page = 0;
+ int entries_per_page = (SPIFFS_CFG_LOG_PAGE_SZ(fs) / sizeof(spiffs_obj_id));
+ spiffs_obj_id *obj_lu_buf = (spiffs_obj_id *)fs->lu_work;
+ int cur_entry = 0;
+ uint32_t dele = 0;
+ uint32_t allo = 0;
+
+ // check each object lookup page
+ while (res == SPIFFS_OK && obj_lookup_page < (int)SPIFFS_OBJ_LOOKUP_PAGES(fs)) {
+ int entry_offset = obj_lookup_page * entries_per_page;
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU | SPIFFS_OP_C_READ,
+ 0, bix * SPIFFS_CFG_LOG_BLOCK_SZ(fs) + SPIFFS_PAGE_TO_PADDR(fs, obj_lookup_page), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->lu_work);
+ // check each entry
+ while (res == SPIFFS_OK &&
+ cur_entry - entry_offset < entries_per_page && cur_entry < (int)(SPIFFS_PAGES_PER_BLOCK(fs)-SPIFFS_OBJ_LOOKUP_PAGES(fs))) {
+ spiffs_obj_id obj_id = obj_lu_buf[cur_entry-entry_offset];
+ if (obj_id == SPIFFS_OBJ_ID_FREE) {
+ } else if (obj_id == SPIFFS_OBJ_ID_DELETED) {
+ dele++;
+ } else {
+ allo++;
+ }
+ cur_entry++;
+ } // per entry
+ obj_lookup_page++;
+ } // per object lookup page
+ SPIFFS_GC_DBG("gc_check: wipe pallo:%i pdele:%i\n", allo, dele);
+ fs->stats_p_allocated -= allo;
+ fs->stats_p_deleted -= dele;
+ return res;
+}
+
+// Finds block candidates to erase
+int32_t spiffs_gc_find_candidate(
+ spiffs *fs,
+ spiffs_block_ix **block_candidates,
+ int *candidate_count,
+ char fs_crammed) {
+ int32_t res = SPIFFS_OK;
+ uint32_t blocks = fs->block_count;
+ spiffs_block_ix cur_block = 0;
+ uint32_t cur_block_addr = 0;
+ spiffs_obj_id *obj_lu_buf = (spiffs_obj_id *)fs->lu_work;
+ int cur_entry = 0;
+
+ // using fs->work area as sorted candidate memory, (spiffs_block_ix)cand_bix/(int32_t)score
+ int max_candidates = MIN(fs->block_count, (SPIFFS_CFG_LOG_PAGE_SZ(fs)-8)/(sizeof(spiffs_block_ix) + sizeof(int32_t)));
+ *candidate_count = 0;
+ memset(fs->work, 0xff, SPIFFS_CFG_LOG_PAGE_SZ(fs));
+
+ // divide up work area into block indices and scores
+ spiffs_block_ix *cand_blocks = (spiffs_block_ix *)fs->work;
+ int32_t *cand_scores = (int32_t *)(fs->work + max_candidates * sizeof(spiffs_block_ix));
+
+ // align cand_scores on int32_t boundary
+ cand_scores = (int32_t*)(((ptrdiff_t)cand_scores + sizeof(ptrdiff_t) - 1) & ~(sizeof(ptrdiff_t) - 1));
+
+ *block_candidates = cand_blocks;
+
+ int entries_per_page = (SPIFFS_CFG_LOG_PAGE_SZ(fs) / sizeof(spiffs_obj_id));
+
+ // check each block
+ while (res == SPIFFS_OK && blocks--) {
+ uint16_t deleted_pages_in_block = 0;
+ uint16_t used_pages_in_block = 0;
+
+ int obj_lookup_page = 0;
+ // check each object lookup page
+ while (res == SPIFFS_OK && obj_lookup_page < (int)SPIFFS_OBJ_LOOKUP_PAGES(fs)) {
+ int entry_offset = obj_lookup_page * entries_per_page;
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU | SPIFFS_OP_C_READ,
+ 0, cur_block_addr + SPIFFS_PAGE_TO_PADDR(fs, obj_lookup_page), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->lu_work);
+ // check each entry
+ while (res == SPIFFS_OK &&
+ cur_entry - entry_offset < entries_per_page &&
+ cur_entry < (int)(SPIFFS_PAGES_PER_BLOCK(fs)-SPIFFS_OBJ_LOOKUP_PAGES(fs))) {
+ spiffs_obj_id obj_id = obj_lu_buf[cur_entry-entry_offset];
+ if (obj_id == SPIFFS_OBJ_ID_FREE) {
+ // when a free entry is encountered, scan logic ensures that all following entries are free also
+ res = 1; // kill object lu loop
+ break;
+ } else if (obj_id == SPIFFS_OBJ_ID_DELETED) {
+ deleted_pages_in_block++;
+ } else {
+ used_pages_in_block++;
+ }
+ cur_entry++;
+ } // per entry
+ obj_lookup_page++;
+ } // per object lookup page
+ if (res == 1) res = SPIFFS_OK;
+
+ // calculate score and insert into candidate table
+ // stoneage sort, but probably not so many blocks
+ if (res == SPIFFS_OK && deleted_pages_in_block > 0) {
+ // read erase count
+ spiffs_obj_id erase_count;
+ res = _spiffs_rd(fs, SPIFFS_OP_C_READ | SPIFFS_OP_T_OBJ_LU2, 0,
+ SPIFFS_ERASE_COUNT_PADDR(fs, cur_block),
+ sizeof(spiffs_obj_id), (uint8_t *)&erase_count);
+ SPIFFS_CHECK_RES(res);
+
+ spiffs_obj_id erase_age;
+ if (fs->max_erase_count > erase_count) {
+ erase_age = fs->max_erase_count - erase_count;
+ } else {
+ erase_age = SPIFFS_OBJ_ID_FREE - (erase_count - fs->max_erase_count);
+ }
+
+ int32_t score =
+ deleted_pages_in_block * SPIFFS_GC_HEUR_W_DELET +
+ used_pages_in_block * SPIFFS_GC_HEUR_W_USED +
+ erase_age * (fs_crammed ? 0 : SPIFFS_GC_HEUR_W_ERASE_AGE);
+ int cand_ix = 0;
+ SPIFFS_GC_DBG("gc_check: bix:%i del:%i use:%i score:%i\n", cur_block, deleted_pages_in_block, used_pages_in_block, score);
+ while (cand_ix < max_candidates) {
+ if (cand_blocks[cand_ix] == (spiffs_block_ix)-1) {
+ cand_blocks[cand_ix] = cur_block;
+ cand_scores[cand_ix] = score;
+ break;
+ } else if (cand_scores[cand_ix] < score) {
+ int reorder_cand_ix = max_candidates - 2;
+ while (reorder_cand_ix >= cand_ix) {
+ cand_blocks[reorder_cand_ix + 1] = cand_blocks[reorder_cand_ix];
+ cand_scores[reorder_cand_ix + 1] = cand_scores[reorder_cand_ix];
+ reorder_cand_ix--;
+ }
+ cand_blocks[cand_ix] = cur_block;
+ cand_scores[cand_ix] = score;
+ break;
+ }
+ cand_ix++;
+ }
+ (*candidate_count)++;
+ }
+
+ cur_entry = 0;
+ cur_block++;
+ cur_block_addr += SPIFFS_CFG_LOG_BLOCK_SZ(fs);
+ } // per block
+
+ return res;
+}
+
+typedef enum {
+ FIND_OBJ_DATA,
+ MOVE_OBJ_DATA,
+ MOVE_OBJ_IX,
+ FINISHED
+} spiffs_gc_clean_state;
+
+typedef struct {
+ spiffs_gc_clean_state state;
+ spiffs_obj_id cur_obj_id;
+ spiffs_span_ix cur_objix_spix;
+ spiffs_page_ix cur_objix_pix;
+ spiffs_page_ix cur_data_pix;
+ int stored_scan_entry_index;
+ uint8_t obj_id_found;
+} spiffs_gc;
+
+// Empties given block by moving all data into free pages of another block
+// Strategy:
+// loop:
+// scan object lookup for object data pages
+// for first found id, check spix and load corresponding object index page to memory
+// push object scan lookup entry index
+// rescan object lookup, find data pages with same id and referenced by same object index
+// move data page, update object index in memory
+// when reached end of lookup, store updated object index
+// pop object scan lookup entry index
+// repeat loop until end of object lookup
+// scan object lookup again for remaining object index pages, move to new page in other block
+//
+int32_t spiffs_gc_clean(spiffs *fs, spiffs_block_ix bix) {
+ int32_t res = SPIFFS_OK;
+ const int entries_per_page = (SPIFFS_CFG_LOG_PAGE_SZ(fs) / sizeof(spiffs_obj_id));
+ // this is the global localizer being pushed and popped
+ int cur_entry = 0;
+ spiffs_obj_id *obj_lu_buf = (spiffs_obj_id *)fs->lu_work;
+ spiffs_gc gc; // our stack frame/state
+ spiffs_page_ix cur_pix = 0;
+ spiffs_page_object_ix_header *objix_hdr = (spiffs_page_object_ix_header *)fs->work;
+ spiffs_page_object_ix *objix = (spiffs_page_object_ix *)fs->work;
+
+ SPIFFS_GC_DBG("gc_clean: cleaning block %i\n", bix);
+
+ memset(&gc, 0, sizeof(spiffs_gc));
+ gc.state = FIND_OBJ_DATA;
+
+ if (fs->free_cursor_block_ix == bix) {
+ // move free cursor to next block, cannot use free pages from the block we want to clean
+ fs->free_cursor_block_ix = (bix+1)%fs->block_count;
+ fs->free_cursor_obj_lu_entry = 0;
+ SPIFFS_GC_DBG("gc_clean: move free cursor to block %i\n", fs->free_cursor_block_ix);
+ }
+
+ while (res == SPIFFS_OK && gc.state != FINISHED) {
+ SPIFFS_GC_DBG("gc_clean: state = %i entry:%i\n", gc.state, cur_entry);
+ gc.obj_id_found = 0; // reset (to no found data page)
+
+ // scan through lookup pages
+ int obj_lookup_page = cur_entry / entries_per_page;
+ uint8_t scan = 1;
+ // check each object lookup page
+ while (scan && res == SPIFFS_OK && obj_lookup_page < (int)SPIFFS_OBJ_LOOKUP_PAGES(fs)) {
+ int entry_offset = obj_lookup_page * entries_per_page;
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU | SPIFFS_OP_C_READ,
+ 0, bix * SPIFFS_CFG_LOG_BLOCK_SZ(fs) + SPIFFS_PAGE_TO_PADDR(fs, obj_lookup_page),
+ SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->lu_work);
+ // check each object lookup entry
+ while (scan && res == SPIFFS_OK &&
+ cur_entry - entry_offset < entries_per_page && cur_entry < (int)(SPIFFS_PAGES_PER_BLOCK(fs)-SPIFFS_OBJ_LOOKUP_PAGES(fs))) {
+ spiffs_obj_id obj_id = obj_lu_buf[cur_entry-entry_offset];
+ cur_pix = SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, bix, cur_entry);
+
+ // act upon object id depending on gc state
+ switch (gc.state) {
+ case FIND_OBJ_DATA:
+ // find a data page
+ if (obj_id != SPIFFS_OBJ_ID_DELETED && obj_id != SPIFFS_OBJ_ID_FREE &&
+ ((obj_id & SPIFFS_OBJ_ID_IX_FLAG) == 0)) {
+ // found a data page, stop scanning and handle in switch case below
+ SPIFFS_GC_DBG("gc_clean: FIND_DATA state:%i - found obj id %04x\n", gc.state, obj_id);
+ gc.obj_id_found = 1;
+ gc.cur_obj_id = obj_id;
+ gc.cur_data_pix = cur_pix;
+ scan = 0;
+ }
+ break;
+ case MOVE_OBJ_DATA:
+ // evacuate found data pages for corresponding object index we have in memory,
+ // update memory representation
+ if (obj_id == gc.cur_obj_id) {
+ spiffs_page_header p_hdr;
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ,
+ 0, SPIFFS_PAGE_TO_PADDR(fs, cur_pix), sizeof(spiffs_page_header), (uint8_t*)&p_hdr);
+ SPIFFS_CHECK_RES(res);
+ SPIFFS_GC_DBG("gc_clean: MOVE_DATA found data page %04x:%04x @ %04x\n", gc.cur_obj_id, p_hdr.span_ix, cur_pix);
+ if (SPIFFS_OBJ_IX_ENTRY_SPAN_IX(fs, p_hdr.span_ix) != gc.cur_objix_spix) {
+ SPIFFS_GC_DBG("gc_clean: MOVE_DATA no objix spix match, take in another run\n");
+ } else {
+ spiffs_page_ix new_data_pix;
+ if (p_hdr.flags & SPIFFS_PH_FLAG_DELET) {
+ // move page
+ res = spiffs_page_move(fs, 0, 0, obj_id, &p_hdr, cur_pix, &new_data_pix);
+ SPIFFS_GC_DBG("gc_clean: MOVE_DATA move objix %04x:%04x page %04x to %04x\n", gc.cur_obj_id, p_hdr.span_ix, cur_pix, new_data_pix);
+ SPIFFS_CHECK_RES(res);
+ // move wipes obj_lu, reload it
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU | SPIFFS_OP_C_READ,
+ 0, bix * SPIFFS_CFG_LOG_BLOCK_SZ(fs) + SPIFFS_PAGE_TO_PADDR(fs, obj_lookup_page),
+ SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->lu_work);
+ SPIFFS_CHECK_RES(res);
+ } else {
+ // page is deleted but not deleted in lookup, scrap it -
+ // might seem unnecessary as we will erase this block, but
+ // we might get aborted
+ SPIFFS_GC_DBG("gc_clean: MOVE_DATA wipe objix %04x:%04x page %04x\n", obj_id, p_hdr.span_ix, cur_pix);
+ res = spiffs_page_delete(fs, cur_pix);
+ SPIFFS_CHECK_RES(res);
+ new_data_pix = SPIFFS_OBJ_ID_FREE;
+ }
+ // update memory representation of object index page with new data page
+ if (gc.cur_objix_spix == 0) {
+ // update object index header page
+ ((spiffs_page_ix*)((uint8_t *)objix_hdr + sizeof(spiffs_page_object_ix_header)))[p_hdr.span_ix] = new_data_pix;
+ SPIFFS_GC_DBG("gc_clean: MOVE_DATA wrote page %04x to objix_hdr entry %02x in mem\n", new_data_pix, SPIFFS_OBJ_IX_ENTRY(fs, p_hdr.span_ix));
+ } else {
+ // update object index page
+ ((spiffs_page_ix*)((uint8_t *)objix + sizeof(spiffs_page_object_ix)))[SPIFFS_OBJ_IX_ENTRY(fs, p_hdr.span_ix)] = new_data_pix;
+ SPIFFS_GC_DBG("gc_clean: MOVE_DATA wrote page %04x to objix entry %02x in mem\n", new_data_pix, SPIFFS_OBJ_IX_ENTRY(fs, p_hdr.span_ix));
+ }
+ }
+ }
+ break;
+ case MOVE_OBJ_IX:
+ // find and evacuate object index pages
+ if (obj_id != SPIFFS_OBJ_ID_DELETED && obj_id != SPIFFS_OBJ_ID_FREE &&
+ (obj_id & SPIFFS_OBJ_ID_IX_FLAG)) {
+ // found an index object id
+ spiffs_page_header p_hdr;
+ spiffs_page_ix new_pix;
+ // load header
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ,
+ 0, SPIFFS_PAGE_TO_PADDR(fs, cur_pix), sizeof(spiffs_page_header), (uint8_t*)&p_hdr);
+ SPIFFS_CHECK_RES(res);
+ if (p_hdr.flags & SPIFFS_PH_FLAG_DELET) {
+ // move page
+ res = spiffs_page_move(fs, 0, 0, obj_id, &p_hdr, cur_pix, &new_pix);
+ SPIFFS_GC_DBG("gc_clean: MOVE_OBJIX move objix %04x:%04x page %04x to %04x\n", obj_id, p_hdr.span_ix, cur_pix, new_pix);
+ SPIFFS_CHECK_RES(res);
+ spiffs_cb_object_event(fs, (spiffs_page_object_ix *)&p_hdr,
+ SPIFFS_EV_IX_MOV, obj_id, p_hdr.span_ix, new_pix, 0);
+ // move wipes obj_lu, reload it
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU | SPIFFS_OP_C_READ,
+ 0, bix * SPIFFS_CFG_LOG_BLOCK_SZ(fs) + SPIFFS_PAGE_TO_PADDR(fs, obj_lookup_page),
+ SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->lu_work);
+ SPIFFS_CHECK_RES(res);
+ } else {
+ // page is deleted but not deleted in lookup, scrap it -
+ // might seem unnecessary as we will erase this block, but
+ // we might get aborted
+ SPIFFS_GC_DBG("gc_clean: MOVE_OBJIX wipe objix %04x:%04x page %04x\n", obj_id, p_hdr.span_ix, cur_pix);
+ res = spiffs_page_delete(fs, cur_pix);
+ if (res == SPIFFS_OK) {
+ spiffs_cb_object_event(fs, (spiffs_page_object_ix *)0,
+ SPIFFS_EV_IX_DEL, obj_id, p_hdr.span_ix, cur_pix, 0);
+ }
+ }
+ SPIFFS_CHECK_RES(res);
+ }
+ break;
+ default:
+ scan = 0;
+ break;
+ } // switch gc state
+ cur_entry++;
+ } // per entry
+ obj_lookup_page++; // no need to check scan variable here, obj_lookup_page is set in start of loop
+ } // per object lookup page
+ if (res != SPIFFS_OK) break;
+
+ // state finalization and switch
+ switch (gc.state) {
+ case FIND_OBJ_DATA:
+ if (gc.obj_id_found) {
+ // handle found data page -
+ // find out corresponding obj ix page and load it to memory
+ spiffs_page_header p_hdr;
+ spiffs_page_ix objix_pix;
+ gc.stored_scan_entry_index = cur_entry; // push cursor
+ cur_entry = 0; // restart scan from start
+ gc.state = MOVE_OBJ_DATA;
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ,
+ 0, SPIFFS_PAGE_TO_PADDR(fs, cur_pix), sizeof(spiffs_page_header), (uint8_t*)&p_hdr);
+ SPIFFS_CHECK_RES(res);
+ gc.cur_objix_spix = SPIFFS_OBJ_IX_ENTRY_SPAN_IX(fs, p_hdr.span_ix);
+ SPIFFS_GC_DBG("gc_clean: FIND_DATA find objix span_ix:%04x\n", gc.cur_objix_spix);
+ res = spiffs_obj_lu_find_id_and_span(fs, gc.cur_obj_id | SPIFFS_OBJ_ID_IX_FLAG, gc.cur_objix_spix, 0, &objix_pix);
+ if (res == SPIFFS_ERR_NOT_FOUND) {
+ // on borked systems we might get an ERR_NOT_FOUND here -
+ // this is handled by simply deleting the page as it is not referenced
+ // from anywhere
+ SPIFFS_GC_DBG("gc_clean: FIND_OBJ_DATA objix not found! Wipe page %04x\n", gc.cur_data_pix);
+ res = spiffs_page_delete(fs, gc.cur_data_pix);
+ SPIFFS_CHECK_RES(res);
+ // then we restore states and continue scanning for data pages
+ cur_entry = gc.stored_scan_entry_index; // pop cursor
+ gc.state = FIND_OBJ_DATA;
+ break; // done
+ }
+ SPIFFS_CHECK_RES(res);
+ SPIFFS_GC_DBG("gc_clean: FIND_DATA found object index at page %04x\n", objix_pix);
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ,
+ 0, SPIFFS_PAGE_TO_PADDR(fs, objix_pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->work);
+ SPIFFS_CHECK_RES(res);
+ // cannot allow a gc if the presumed index in fact is no index, a
+ // check must run or lot of data may be lost
+ SPIFFS_VALIDATE_OBJIX(objix->p_hdr, gc.cur_obj_id | SPIFFS_OBJ_ID_IX_FLAG, gc.cur_objix_spix);
+ gc.cur_objix_pix = objix_pix;
+ } else {
+ // no more data pages found, passed thru all block, start evacuating object indices
+ gc.state = MOVE_OBJ_IX;
+ cur_entry = 0; // restart entry scan index
+ }
+ break;
+ case MOVE_OBJ_DATA: {
+ // store modified objix (hdr) page residing in memory now that all
+ // data pages belonging to this object index and residing in the block
+ // we want to evacuate
+ spiffs_page_ix new_objix_pix;
+ gc.state = FIND_OBJ_DATA;
+ cur_entry = gc.stored_scan_entry_index; // pop cursor
+ if (gc.cur_objix_spix == 0) {
+ // store object index header page
+ res = spiffs_object_update_index_hdr(fs, 0, gc.cur_obj_id | SPIFFS_OBJ_ID_IX_FLAG, gc.cur_objix_pix, fs->work, 0, 0, &new_objix_pix);
+ SPIFFS_GC_DBG("gc_clean: MOVE_DATA store modified objix_hdr page, %04x:%04x\n", new_objix_pix, 0);
+ SPIFFS_CHECK_RES(res);
+ } else {
+ // store object index page
+ res = spiffs_page_move(fs, 0, fs->work, gc.cur_obj_id | SPIFFS_OBJ_ID_IX_FLAG, 0, gc.cur_objix_pix, &new_objix_pix);
+ SPIFFS_GC_DBG("gc_clean: MOVE_DATA store modified objix page, %04x:%04x\n", new_objix_pix, objix->p_hdr.span_ix);
+ SPIFFS_CHECK_RES(res);
+ spiffs_cb_object_event(fs, (spiffs_page_object_ix *)fs->work,
+ SPIFFS_EV_IX_UPD, gc.cur_obj_id, objix->p_hdr.span_ix, new_objix_pix, 0);
+ }
+ }
+ break;
+ case MOVE_OBJ_IX:
+ // scanned thru all block, no more object indices found - our work here is done
+ gc.state = FINISHED;
+ break;
+ default:
+ cur_entry = 0;
+ break;
+ } // switch gc.state
+ SPIFFS_GC_DBG("gc_clean: state-> %i\n", gc.state);
+ } // while state != FINISHED
+
+
+ return res;
+}
+
+#endif // !SPIFFS_READ_ONLY
diff --git a/fw/User/spiffs/src/spiffs_hydrogen.c b/fw/User/spiffs/src/spiffs_hydrogen.c
new file mode 100644
index 0000000..3dab579
--- /dev/null
+++ b/fw/User/spiffs/src/spiffs_hydrogen.c
@@ -0,0 +1,1314 @@
+/*
+ * spiffs_hydrogen.c
+ *
+ * Created on: Jun 16, 2013
+ * Author: petera
+ */
+
+#include "spiffs.h"
+#include "spiffs_nucleus.h"
+
+#if SPIFFS_FILEHDL_OFFSET
+#define SPIFFS_FH_OFFS(fs, fh) ((fh) != 0 ? ((fh) + (fs)->cfg.fh_ix_offset) : 0)
+#define SPIFFS_FH_UNOFFS(fs, fh) ((fh) != 0 ? ((fh) - (fs)->cfg.fh_ix_offset) : 0)
+#else
+#define SPIFFS_FH_OFFS(fs, fh) (fh)
+#define SPIFFS_FH_UNOFFS(fs, fh) (fh)
+#endif
+
+#if SPIFFS_CACHE == 1
+static int32_t spiffs_fflush_cache(spiffs *fs, spiffs_file fh);
+#endif
+
+#if SPIFFS_BUFFER_HELP
+uint32_t SPIFFS_buffer_bytes_for_filedescs(spiffs *fs, uint32_t num_descs) {
+ return num_descs * sizeof(spiffs_fd);
+}
+#if SPIFFS_CACHE
+uint32_t SPIFFS_buffer_bytes_for_cache(spiffs *fs, uint32_t num_pages) {
+ return sizeof(spiffs_cache) + num_pages * (sizeof(spiffs_cache_page) + SPIFFS_CFG_LOG_PAGE_SZ(fs));
+}
+#endif
+#endif
+
+uint8_t SPIFFS_mounted(spiffs *fs) {
+ return SPIFFS_CHECK_MOUNT(fs);
+}
+
+int32_t SPIFFS_format(spiffs *fs) {
+#if SPIFFS_READ_ONLY
+ (void)fs;
+ return SPIFFS_ERR_RO_NOT_IMPL;
+#else
+ SPIFFS_API_CHECK_CFG(fs);
+ if (SPIFFS_CHECK_MOUNT(fs)) {
+ fs->err_code = SPIFFS_ERR_MOUNTED;
+ return -1;
+ }
+
+ int32_t res;
+ SPIFFS_LOCK(fs);
+
+ spiffs_block_ix bix = 0;
+ while (bix < fs->block_count) {
+ fs->max_erase_count = 0;
+ res = spiffs_erase_block(fs, bix);
+ if (res != SPIFFS_OK) {
+ res = SPIFFS_ERR_ERASE_FAIL;
+ }
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+ bix++;
+ }
+
+ SPIFFS_UNLOCK(fs);
+
+ return 0;
+#endif // SPIFFS_READ_ONLY
+}
+
+#if SPIFFS_USE_MAGIC && SPIFFS_USE_MAGIC_LENGTH && SPIFFS_SINGLETON==0
+
+int32_t SPIFFS_probe_fs(spiffs_config *config) {
+ int32_t res = spiffs_probe(config);
+ return res;
+}
+
+#endif // SPIFFS_USE_MAGIC && SPIFFS_USE_MAGIC_LENGTH && SPIFFS_SINGLETON==0
+
+int32_t SPIFFS_mount(spiffs *fs, spiffs_config *config, uint8_t *work,
+ uint8_t *fd_space, uint32_t fd_space_size,
+ void *cache, uint32_t cache_size,
+ spiffs_check_callback check_cb_f) {
+ void *user_data;
+ SPIFFS_LOCK(fs);
+ user_data = fs->user_data;
+ memset(fs, 0, sizeof(spiffs));
+ memcpy(&fs->cfg, config, sizeof(spiffs_config));
+ fs->user_data = user_data;
+ fs->block_count = SPIFFS_CFG_PHYS_SZ(fs) / SPIFFS_CFG_LOG_BLOCK_SZ(fs);
+ fs->work = &work[0];
+ fs->lu_work = &work[SPIFFS_CFG_LOG_PAGE_SZ(fs)];
+ memset(fd_space, 0, fd_space_size);
+ // align fd_space pointer to pointer size byte boundary
+ uint8_t ptr_size = sizeof(void*);
+ uint8_t addr_lsb = ((uint8_t)(intptr_t)fd_space) & (ptr_size-1);
+ if (addr_lsb) {
+ fd_space += (ptr_size-addr_lsb);
+ fd_space_size -= (ptr_size-addr_lsb);
+ }
+ fs->fd_space = fd_space;
+ fs->fd_count = (fd_space_size/sizeof(spiffs_fd));
+
+ // align cache pointer to 4 byte boundary
+ addr_lsb = ((uint8_t)(intptr_t)cache) & (ptr_size-1);
+ if (addr_lsb) {
+ uint8_t *cache_8 = (uint8_t *)cache;
+ cache_8 += (ptr_size-addr_lsb);
+ cache = cache_8;
+ cache_size -= (ptr_size-addr_lsb);
+ }
+ if (cache_size & (ptr_size-1)) {
+ cache_size -= (cache_size & (ptr_size-1));
+ }
+
+#if SPIFFS_CACHE
+ fs->cache = cache;
+ fs->cache_size = (cache_size > (SPIFFS_CFG_LOG_PAGE_SZ(fs)*32)) ? SPIFFS_CFG_LOG_PAGE_SZ(fs)*32 : cache_size;
+ spiffs_cache_init(fs);
+#endif
+
+ int32_t res;
+
+#if SPIFFS_USE_MAGIC
+ res = SPIFFS_CHECK_MAGIC_POSSIBLE(fs) ? SPIFFS_OK : SPIFFS_ERR_MAGIC_NOT_POSSIBLE;
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+#endif
+
+ fs->config_magic = SPIFFS_CONFIG_MAGIC;
+
+ res = spiffs_obj_lu_scan(fs);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+ SPIFFS_DBG("page index byte len: %d\n", SPIFFS_CFG_LOG_PAGE_SZ(fs));
+ SPIFFS_DBG("object lookup pages: %d\n", SPIFFS_OBJ_LOOKUP_PAGES(fs));
+ SPIFFS_DBG("page pages per block: %d\n", SPIFFS_PAGES_PER_BLOCK(fs));
+ SPIFFS_DBG("page header length: %d\n", sizeof(spiffs_page_header));
+ SPIFFS_DBG("object header index entries: %d\n", SPIFFS_OBJ_HDR_IX_LEN(fs));
+ SPIFFS_DBG("object index entries: %d\n", SPIFFS_OBJ_IX_LEN(fs));
+ SPIFFS_DBG("available file descriptors: %d\n", fs->fd_count);
+ SPIFFS_DBG("free blocks: %d\n", fs->free_blocks);
+
+ fs->check_cb_f = check_cb_f;
+
+ fs->mounted = 1;
+
+ SPIFFS_UNLOCK(fs);
+
+ return 0;
+}
+
+void SPIFFS_unmount(spiffs *fs) {
+ if (!SPIFFS_CHECK_CFG(fs) || !SPIFFS_CHECK_MOUNT(fs)) return;
+ SPIFFS_LOCK(fs);
+ uint32_t i;
+ spiffs_fd *fds = (spiffs_fd *)fs->fd_space;
+ for (i = 0; i < fs->fd_count; i++) {
+ spiffs_fd *cur_fd = &fds[i];
+ if (cur_fd->file_nbr != 0) {
+#if SPIFFS_CACHE
+ (void)spiffs_fflush_cache(fs, cur_fd->file_nbr);
+#endif
+ spiffs_fd_return(fs, cur_fd->file_nbr);
+ }
+ }
+ fs->mounted = 0;
+
+ SPIFFS_UNLOCK(fs);
+}
+
+int32_t SPIFFS_errno(spiffs *fs) {
+ return fs->err_code;
+}
+
+void SPIFFS_clearerr(spiffs *fs) {
+ fs->err_code = SPIFFS_OK;
+}
+
+int32_t SPIFFS_creat(spiffs *fs, const char *path, spiffs_mode mode) {
+#if SPIFFS_READ_ONLY
+ (void)fs; (void)path; (void)mode;
+ return SPIFFS_ERR_RO_NOT_IMPL;
+#else
+ (void)mode;
+ SPIFFS_API_CHECK_CFG(fs);
+ SPIFFS_API_CHECK_MOUNT(fs);
+ if (strlen(path) > SPIFFS_OBJ_NAME_LEN - 1) {
+ SPIFFS_API_CHECK_RES(fs, SPIFFS_ERR_NAME_TOO_LONG);
+ }
+ SPIFFS_LOCK(fs);
+ spiffs_obj_id obj_id;
+ int32_t res;
+
+ res = spiffs_obj_lu_find_free_obj_id(fs, &obj_id, (const uint8_t*)path);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+ res = spiffs_object_create(fs, obj_id, (const uint8_t*)path, SPIFFS_TYPE_FILE, 0);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+ SPIFFS_UNLOCK(fs);
+ return 0;
+#endif // SPIFFS_READ_ONLY
+}
+
+spiffs_file SPIFFS_open(spiffs *fs, const char *path, spiffs_flags flags, spiffs_mode mode) {
+ (void)mode;
+ SPIFFS_API_CHECK_CFG(fs);
+ SPIFFS_API_CHECK_MOUNT(fs);
+ if (strlen(path) > SPIFFS_OBJ_NAME_LEN - 1) {
+ SPIFFS_API_CHECK_RES(fs, SPIFFS_ERR_NAME_TOO_LONG);
+ }
+ SPIFFS_LOCK(fs);
+
+ spiffs_fd *fd;
+ spiffs_page_ix pix;
+
+#if SPIFFS_READ_ONLY
+ // not valid flags in read only mode
+ flags &= ~(SPIFFS_WRONLY | SPIFFS_CREAT | SPIFFS_TRUNC);
+#endif // SPIFFS_READ_ONLY
+
+ int32_t res = spiffs_fd_find_new(fs, &fd, path);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+ res = spiffs_object_find_object_index_header_by_name(fs, (const uint8_t*)path, &pix);
+ if ((flags & SPIFFS_O_CREAT) == 0) {
+ if (res < SPIFFS_OK) {
+ spiffs_fd_return(fs, fd->file_nbr);
+ }
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+ }
+
+ if (res == SPIFFS_OK &&
+ (flags & (SPIFFS_O_CREAT | SPIFFS_O_EXCL)) == (SPIFFS_O_CREAT | SPIFFS_O_EXCL)) {
+ // creat and excl and file exists - fail
+ res = SPIFFS_ERR_FILE_EXISTS;
+ spiffs_fd_return(fs, fd->file_nbr);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+ }
+
+ if ((flags & SPIFFS_O_CREAT) && res == SPIFFS_ERR_NOT_FOUND) {
+#if !SPIFFS_READ_ONLY
+ spiffs_obj_id obj_id;
+ // no need to enter conflicting name here, already looked for it above
+ res = spiffs_obj_lu_find_free_obj_id(fs, &obj_id, 0);
+ if (res < SPIFFS_OK) {
+ spiffs_fd_return(fs, fd->file_nbr);
+ }
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+ res = spiffs_object_create(fs, obj_id, (const uint8_t*)path, SPIFFS_TYPE_FILE, &pix);
+ if (res < SPIFFS_OK) {
+ spiffs_fd_return(fs, fd->file_nbr);
+ }
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+ flags &= ~SPIFFS_O_TRUNC;
+#endif // !SPIFFS_READ_ONLY
+ } else {
+ if (res < SPIFFS_OK) {
+ spiffs_fd_return(fs, fd->file_nbr);
+ }
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+ }
+ res = spiffs_object_open_by_page(fs, pix, fd, flags, mode);
+ if (res < SPIFFS_OK) {
+ spiffs_fd_return(fs, fd->file_nbr);
+ }
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+#if !SPIFFS_READ_ONLY
+ if (flags & SPIFFS_O_TRUNC) {
+ res = spiffs_object_truncate(fd, 0, 0);
+ if (res < SPIFFS_OK) {
+ spiffs_fd_return(fs, fd->file_nbr);
+ }
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+ }
+#endif // !SPIFFS_READ_ONLY
+
+ fd->fdoffset = 0;
+
+ SPIFFS_UNLOCK(fs);
+
+ return SPIFFS_FH_OFFS(fs, fd->file_nbr);
+}
+
+spiffs_file SPIFFS_open_by_dirent(spiffs *fs, struct spiffs_dirent *e, spiffs_flags flags, spiffs_mode mode) {
+ SPIFFS_API_CHECK_CFG(fs);
+ SPIFFS_API_CHECK_MOUNT(fs);
+ SPIFFS_LOCK(fs);
+
+ spiffs_fd *fd;
+
+ int32_t res = spiffs_fd_find_new(fs, &fd, 0);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+ res = spiffs_object_open_by_page(fs, e->pix, fd, flags, mode);
+ if (res < SPIFFS_OK) {
+ spiffs_fd_return(fs, fd->file_nbr);
+ }
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+#if !SPIFFS_READ_ONLY
+ if (flags & SPIFFS_O_TRUNC) {
+ res = spiffs_object_truncate(fd, 0, 0);
+ if (res < SPIFFS_OK) {
+ spiffs_fd_return(fs, fd->file_nbr);
+ }
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+ }
+#endif // !SPIFFS_READ_ONLY
+
+ fd->fdoffset = 0;
+
+ SPIFFS_UNLOCK(fs);
+
+ return SPIFFS_FH_OFFS(fs, fd->file_nbr);
+}
+
+spiffs_file SPIFFS_open_by_page(spiffs *fs, spiffs_page_ix page_ix, spiffs_flags flags, spiffs_mode mode) {
+ SPIFFS_API_CHECK_CFG(fs);
+ SPIFFS_API_CHECK_MOUNT(fs);
+ SPIFFS_LOCK(fs);
+
+ spiffs_fd *fd;
+
+ int32_t res = spiffs_fd_find_new(fs, &fd, 0);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+ if (SPIFFS_IS_LOOKUP_PAGE(fs, page_ix)) {
+ res = SPIFFS_ERR_NOT_A_FILE;
+ spiffs_fd_return(fs, fd->file_nbr);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+ }
+
+ res = spiffs_object_open_by_page(fs, page_ix, fd, flags, mode);
+ if (res == SPIFFS_ERR_IS_FREE ||
+ res == SPIFFS_ERR_DELETED ||
+ res == SPIFFS_ERR_NOT_FINALIZED ||
+ res == SPIFFS_ERR_NOT_INDEX ||
+ res == SPIFFS_ERR_INDEX_SPAN_MISMATCH) {
+ res = SPIFFS_ERR_NOT_A_FILE;
+ }
+ if (res < SPIFFS_OK) {
+ spiffs_fd_return(fs, fd->file_nbr);
+ }
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+#if !SPIFFS_READ_ONLY
+ if (flags & SPIFFS_O_TRUNC) {
+ res = spiffs_object_truncate(fd, 0, 0);
+ if (res < SPIFFS_OK) {
+ spiffs_fd_return(fs, fd->file_nbr);
+ }
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+ }
+#endif // !SPIFFS_READ_ONLY
+
+ fd->fdoffset = 0;
+
+ SPIFFS_UNLOCK(fs);
+
+ return SPIFFS_FH_OFFS(fs, fd->file_nbr);
+}
+
+int32_t SPIFFS_read(spiffs *fs, spiffs_file fh, void *buf, int32_t len) {
+ SPIFFS_API_CHECK_CFG(fs);
+ SPIFFS_API_CHECK_MOUNT(fs);
+ SPIFFS_LOCK(fs);
+
+ spiffs_fd *fd;
+ int32_t res;
+
+ fh = SPIFFS_FH_UNOFFS(fs, fh);
+ res = spiffs_fd_get(fs, fh, &fd);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+ if ((fd->flags & SPIFFS_O_RDONLY) == 0) {
+ res = SPIFFS_ERR_NOT_READABLE;
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+ }
+
+ if (fd->size == SPIFFS_UNDEFINED_LEN && len > 0) {
+ // special case for zero sized files
+ res = SPIFFS_ERR_END_OF_OBJECT;
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+ }
+
+#if SPIFFS_CACHE_WR
+ spiffs_fflush_cache(fs, fh);
+#endif
+
+ if (fd->fdoffset + len >= fd->size) {
+ // reading beyond file size
+ int32_t avail = fd->size - fd->fdoffset;
+ if (avail <= 0) {
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, SPIFFS_ERR_END_OF_OBJECT);
+ }
+ res = spiffs_object_read(fd, fd->fdoffset, avail, (uint8_t*)buf);
+ if (res == SPIFFS_ERR_END_OF_OBJECT) {
+ fd->fdoffset += avail;
+ SPIFFS_UNLOCK(fs);
+ return avail;
+ } else {
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+ len = avail;
+ }
+ } else {
+ // reading within file size
+ res = spiffs_object_read(fd, fd->fdoffset, len, (uint8_t*)buf);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+ }
+ fd->fdoffset += len;
+
+ SPIFFS_UNLOCK(fs);
+
+ return len;
+}
+
+#if !SPIFFS_READ_ONLY
+static int32_t spiffs_hydro_write(spiffs *fs, spiffs_fd *fd, void *buf, uint32_t offset, int32_t len) {
+ (void)fs;
+ int32_t res = SPIFFS_OK;
+ int32_t remaining = len;
+ if (fd->size != SPIFFS_UNDEFINED_LEN && offset < fd->size) {
+ int32_t m_len = MIN((int32_t)(fd->size - offset), len);
+ res = spiffs_object_modify(fd, offset, (uint8_t *)buf, m_len);
+ SPIFFS_CHECK_RES(res);
+ remaining -= m_len;
+ uint8_t *buf_8 = (uint8_t *)buf;
+ buf_8 += m_len;
+ buf = buf_8;
+ offset += m_len;
+ }
+ if (remaining > 0) {
+ res = spiffs_object_append(fd, offset, (uint8_t *)buf, remaining);
+ SPIFFS_CHECK_RES(res);
+ }
+ return len;
+
+}
+#endif // !SPIFFS_READ_ONLY
+
+int32_t SPIFFS_write(spiffs *fs, spiffs_file fh, void *buf, int32_t len) {
+#if SPIFFS_READ_ONLY
+ (void)fs; (void)fh; (void)buf; (void)len;
+ return SPIFFS_ERR_RO_NOT_IMPL;
+#else
+ SPIFFS_API_CHECK_CFG(fs);
+ SPIFFS_API_CHECK_MOUNT(fs);
+ SPIFFS_LOCK(fs);
+
+ spiffs_fd *fd;
+ int32_t res;
+ uint32_t offset;
+
+ fh = SPIFFS_FH_UNOFFS(fs, fh);
+ res = spiffs_fd_get(fs, fh, &fd);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+ if ((fd->flags & SPIFFS_O_WRONLY) == 0) {
+ res = SPIFFS_ERR_NOT_WRITABLE;
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+ }
+
+ if ((fd->flags & SPIFFS_O_APPEND)) {
+ fd->fdoffset = fd->size == SPIFFS_UNDEFINED_LEN ? 0 : fd->size;
+ }
+
+ offset = fd->fdoffset;
+
+#if SPIFFS_CACHE_WR
+ if (fd->cache_page == 0) {
+ // see if object id is associated with cache already
+ fd->cache_page = spiffs_cache_page_get_by_fd(fs, fd);
+ }
+#endif
+ if (fd->flags & SPIFFS_O_APPEND) {
+ if (fd->size == SPIFFS_UNDEFINED_LEN) {
+ offset = 0;
+ } else {
+ offset = fd->size;
+ }
+#if SPIFFS_CACHE_WR
+ if (fd->cache_page) {
+ offset = MAX(offset, fd->cache_page->offset + fd->cache_page->size);
+ }
+#endif
+ }
+
+#if SPIFFS_CACHE_WR
+ if ((fd->flags & SPIFFS_O_DIRECT) == 0) {
+ if (len < (int32_t)SPIFFS_CFG_LOG_PAGE_SZ(fs)) {
+ // small write, try to cache it
+ uint8_t alloc_cpage = 1;
+ if (fd->cache_page) {
+ // have a cached page for this fd already, check cache page boundaries
+ if (offset < fd->cache_page->offset || // writing before cache
+ offset > fd->cache_page->offset + fd->cache_page->size || // writing after cache
+ offset + len > fd->cache_page->offset + SPIFFS_CFG_LOG_PAGE_SZ(fs)) // writing beyond cache page
+ {
+ // boundary violation, write back cache first and allocate new
+ SPIFFS_CACHE_DBG("CACHE_WR_DUMP: dumping cache page %i for fd %i:%04x, boundary viol, offs:%i size:%i\n",
+ fd->cache_page->ix, fd->file_nbr, fd->obj_id, fd->cache_page->offset, fd->cache_page->size);
+ res = spiffs_hydro_write(fs, fd,
+ spiffs_get_cache_page(fs, spiffs_get_cache(fs), fd->cache_page->ix),
+ fd->cache_page->offset, fd->cache_page->size);
+ spiffs_cache_fd_release(fs, fd->cache_page);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+ } else {
+ // writing within cache
+ alloc_cpage = 0;
+ }
+ }
+
+ if (alloc_cpage) {
+ fd->cache_page = spiffs_cache_page_allocate_by_fd(fs, fd);
+ if (fd->cache_page) {
+ fd->cache_page->offset = offset;
+ fd->cache_page->size = 0;
+ SPIFFS_CACHE_DBG("CACHE_WR_ALLO: allocating cache page %i for fd %i:%04x\n",
+ fd->cache_page->ix, fd->file_nbr, fd->obj_id);
+ }
+ }
+
+ if (fd->cache_page) {
+ uint32_t offset_in_cpage = offset - fd->cache_page->offset;
+ SPIFFS_CACHE_DBG("CACHE_WR_WRITE: storing to cache page %i for fd %i:%04x, offs %i:%i len %i\n",
+ fd->cache_page->ix, fd->file_nbr, fd->obj_id,
+ offset, offset_in_cpage, len);
+ spiffs_cache *cache = spiffs_get_cache(fs);
+ uint8_t *cpage_data = spiffs_get_cache_page(fs, cache, fd->cache_page->ix);
+ memcpy(&cpage_data[offset_in_cpage], buf, len);
+ fd->cache_page->size = MAX(fd->cache_page->size, offset_in_cpage + len);
+ fd->fdoffset += len;
+ SPIFFS_UNLOCK(fs);
+ return len;
+ } else {
+ res = spiffs_hydro_write(fs, fd, buf, offset, len);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+ fd->fdoffset += len;
+ SPIFFS_UNLOCK(fs);
+ return res;
+ }
+ } else {
+ // big write, no need to cache it - but first check if there is a cached write already
+ if (fd->cache_page) {
+ // write back cache first
+ SPIFFS_CACHE_DBG("CACHE_WR_DUMP: dumping cache page %i for fd %i:%04x, big write, offs:%i size:%i\n",
+ fd->cache_page->ix, fd->file_nbr, fd->obj_id, fd->cache_page->offset, fd->cache_page->size);
+ res = spiffs_hydro_write(fs, fd,
+ spiffs_get_cache_page(fs, spiffs_get_cache(fs), fd->cache_page->ix),
+ fd->cache_page->offset, fd->cache_page->size);
+ spiffs_cache_fd_release(fs, fd->cache_page);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+ // data written below
+ }
+ }
+ }
+#endif
+
+ res = spiffs_hydro_write(fs, fd, buf, offset, len);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+ fd->fdoffset += len;
+
+ SPIFFS_UNLOCK(fs);
+
+ return res;
+#endif // SPIFFS_READ_ONLY
+}
+
+int32_t SPIFFS_lseek(spiffs *fs, spiffs_file fh, int32_t offs, int whence) {
+ SPIFFS_API_CHECK_CFG(fs);
+ SPIFFS_API_CHECK_MOUNT(fs);
+ SPIFFS_LOCK(fs);
+
+ spiffs_fd *fd;
+ int32_t res;
+ fh = SPIFFS_FH_UNOFFS(fs, fh);
+ res = spiffs_fd_get(fs, fh, &fd);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+#if SPIFFS_CACHE_WR
+ spiffs_fflush_cache(fs, fh);
+#endif
+
+ switch (whence) {
+ case SPIFFS_SEEK_CUR:
+ offs = fd->fdoffset+offs;
+ break;
+ case SPIFFS_SEEK_END:
+ offs = (fd->size == SPIFFS_UNDEFINED_LEN ? 0 : fd->size) + offs;
+ break;
+ }
+
+ if ((offs > (int32_t)fd->size) && (SPIFFS_UNDEFINED_LEN != fd->size)) {
+ res = SPIFFS_ERR_END_OF_OBJECT;
+ }
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+ spiffs_span_ix data_spix = offs / SPIFFS_DATA_PAGE_SIZE(fs);
+ spiffs_span_ix objix_spix = SPIFFS_OBJ_IX_ENTRY_SPAN_IX(fs, data_spix);
+ if (fd->cursor_objix_spix != objix_spix) {
+ spiffs_page_ix pix;
+ res = spiffs_obj_lu_find_id_and_span(
+ fs, fd->obj_id | SPIFFS_OBJ_ID_IX_FLAG, objix_spix, 0, &pix);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+ fd->cursor_objix_spix = objix_spix;
+ fd->cursor_objix_pix = pix;
+ }
+ fd->fdoffset = offs;
+
+ SPIFFS_UNLOCK(fs);
+
+ return offs;
+}
+
+int32_t SPIFFS_remove(spiffs *fs, const char *path) {
+#if SPIFFS_READ_ONLY
+ (void)fs; (void)path;
+ return SPIFFS_ERR_RO_NOT_IMPL;
+#else
+ SPIFFS_API_CHECK_CFG(fs);
+ SPIFFS_API_CHECK_MOUNT(fs);
+ if (strlen(path) > SPIFFS_OBJ_NAME_LEN - 1) {
+ SPIFFS_API_CHECK_RES(fs, SPIFFS_ERR_NAME_TOO_LONG);
+ }
+ SPIFFS_LOCK(fs);
+
+ spiffs_fd *fd;
+ spiffs_page_ix pix;
+ int32_t res;
+
+ res = spiffs_fd_find_new(fs, &fd, 0);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+ res = spiffs_object_find_object_index_header_by_name(fs, (const uint8_t*)path, &pix);
+ if (res != SPIFFS_OK) {
+ spiffs_fd_return(fs, fd->file_nbr);
+ }
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+ res = spiffs_object_open_by_page(fs, pix, fd, 0,0);
+ if (res != SPIFFS_OK) {
+ spiffs_fd_return(fs, fd->file_nbr);
+ }
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+ res = spiffs_object_truncate(fd, 0, 1);
+ if (res != SPIFFS_OK) {
+ spiffs_fd_return(fs, fd->file_nbr);
+ }
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+ SPIFFS_UNLOCK(fs);
+ return 0;
+#endif // SPIFFS_READ_ONLY
+}
+
+int32_t SPIFFS_fremove(spiffs *fs, spiffs_file fh) {
+#if SPIFFS_READ_ONLY
+ (void)fs; (void)fh;
+ return SPIFFS_ERR_RO_NOT_IMPL;
+#else
+ SPIFFS_API_CHECK_CFG(fs);
+ SPIFFS_API_CHECK_MOUNT(fs);
+ SPIFFS_LOCK(fs);
+
+ spiffs_fd *fd;
+ int32_t res;
+ fh = SPIFFS_FH_UNOFFS(fs, fh);
+ res = spiffs_fd_get(fs, fh, &fd);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+ if ((fd->flags & SPIFFS_O_WRONLY) == 0) {
+ res = SPIFFS_ERR_NOT_WRITABLE;
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+ }
+
+#if SPIFFS_CACHE_WR
+ spiffs_cache_fd_release(fs, fd->cache_page);
+#endif
+
+ res = spiffs_object_truncate(fd, 0, 1);
+
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+ SPIFFS_UNLOCK(fs);
+
+ return 0;
+#endif // SPIFFS_READ_ONLY
+}
+
+static int32_t spiffs_stat_pix(spiffs *fs, spiffs_page_ix pix, spiffs_file fh, spiffs_stat *s) {
+ (void)fh;
+ spiffs_page_object_ix_header objix_hdr;
+ spiffs_obj_id obj_id;
+ int32_t res =_spiffs_rd(fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_READ, fh,
+ SPIFFS_PAGE_TO_PADDR(fs, pix), sizeof(spiffs_page_object_ix_header), (uint8_t *)&objix_hdr);
+ SPIFFS_API_CHECK_RES(fs, res);
+
+ uint32_t obj_id_addr = SPIFFS_BLOCK_TO_PADDR(fs, SPIFFS_BLOCK_FOR_PAGE(fs , pix)) +
+ SPIFFS_OBJ_LOOKUP_ENTRY_FOR_PAGE(fs, pix) * sizeof(spiffs_obj_id);
+ res =_spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU | SPIFFS_OP_C_READ, fh,
+ obj_id_addr, sizeof(spiffs_obj_id), (uint8_t *)&obj_id);
+ SPIFFS_API_CHECK_RES(fs, res);
+
+ s->obj_id = obj_id & ~SPIFFS_OBJ_ID_IX_FLAG;
+ s->type = objix_hdr.type;
+ s->size = objix_hdr.size == SPIFFS_UNDEFINED_LEN ? 0 : objix_hdr.size;
+ s->pix = pix;
+ strncpy((char *)s->name, (char *)objix_hdr.name, SPIFFS_OBJ_NAME_LEN);
+
+ return res;
+}
+
+int32_t SPIFFS_stat(spiffs *fs, const char *path, spiffs_stat *s) {
+ SPIFFS_API_CHECK_CFG(fs);
+ SPIFFS_API_CHECK_MOUNT(fs);
+ if (strlen(path) > SPIFFS_OBJ_NAME_LEN - 1) {
+ SPIFFS_API_CHECK_RES(fs, SPIFFS_ERR_NAME_TOO_LONG);
+ }
+ SPIFFS_LOCK(fs);
+
+ int32_t res;
+ spiffs_page_ix pix;
+
+ res = spiffs_object_find_object_index_header_by_name(fs, (const uint8_t*)path, &pix);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+ res = spiffs_stat_pix(fs, pix, 0, s);
+
+ SPIFFS_UNLOCK(fs);
+
+ return res;
+}
+
+int32_t SPIFFS_fstat(spiffs *fs, spiffs_file fh, spiffs_stat *s) {
+ SPIFFS_API_CHECK_CFG(fs);
+ SPIFFS_API_CHECK_MOUNT(fs);
+ SPIFFS_LOCK(fs);
+
+ spiffs_fd *fd;
+ int32_t res;
+
+ fh = SPIFFS_FH_UNOFFS(fs, fh);
+ res = spiffs_fd_get(fs, fh, &fd);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+#if SPIFFS_CACHE_WR
+ spiffs_fflush_cache(fs, fh);
+#endif
+
+ res = spiffs_stat_pix(fs, fd->objix_hdr_pix, fh, s);
+
+ SPIFFS_UNLOCK(fs);
+
+ return res;
+}
+
+// Checks if there are any cached writes for the object id associated with
+// given filehandle. If so, these writes are flushed.
+#if SPIFFS_CACHE == 1
+static int32_t spiffs_fflush_cache(spiffs *fs, spiffs_file fh) {
+ (void)fs;
+ (void)fh;
+ int32_t res = SPIFFS_OK;
+#if !SPIFFS_READ_ONLY && SPIFFS_CACHE_WR
+
+ spiffs_fd *fd;
+ res = spiffs_fd_get(fs, fh, &fd);
+ SPIFFS_API_CHECK_RES(fs, res);
+
+ if ((fd->flags & SPIFFS_O_DIRECT) == 0) {
+ if (fd->cache_page == 0) {
+ // see if object id is associated with cache already
+ fd->cache_page = spiffs_cache_page_get_by_fd(fs, fd);
+ }
+ if (fd->cache_page) {
+ SPIFFS_CACHE_DBG("CACHE_WR_DUMP: dumping cache page %i for fd %i:%04x, flush, offs:%i size:%i\n",
+ fd->cache_page->ix, fd->file_nbr, fd->obj_id, fd->cache_page->offset, fd->cache_page->size);
+ res = spiffs_hydro_write(fs, fd,
+ spiffs_get_cache_page(fs, spiffs_get_cache(fs), fd->cache_page->ix),
+ fd->cache_page->offset, fd->cache_page->size);
+ if (res < SPIFFS_OK) {
+ fs->err_code = res;
+ }
+ spiffs_cache_fd_release(fs, fd->cache_page);
+ }
+ }
+#endif
+
+ return res;
+}
+#endif
+
+int32_t SPIFFS_fflush(spiffs *fs, spiffs_file fh) {
+ (void)fh;
+ SPIFFS_API_CHECK_CFG(fs);
+ SPIFFS_API_CHECK_MOUNT(fs);
+ int32_t res = SPIFFS_OK;
+#if !SPIFFS_READ_ONLY && SPIFFS_CACHE_WR
+ SPIFFS_LOCK(fs);
+ fh = SPIFFS_FH_UNOFFS(fs, fh);
+ res = spiffs_fflush_cache(fs, fh);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs,res);
+ SPIFFS_UNLOCK(fs);
+#endif
+
+ return res;
+}
+
+int32_t SPIFFS_close(spiffs *fs, spiffs_file fh) {
+ SPIFFS_API_CHECK_CFG(fs);
+ SPIFFS_API_CHECK_MOUNT(fs);
+
+ int32_t res = SPIFFS_OK;
+ SPIFFS_LOCK(fs);
+
+ fh = SPIFFS_FH_UNOFFS(fs, fh);
+#if SPIFFS_CACHE
+ res = spiffs_fflush_cache(fs, fh);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+#endif
+ res = spiffs_fd_return(fs, fh);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+ SPIFFS_UNLOCK(fs);
+
+ return res;
+}
+
+int32_t SPIFFS_rename(spiffs *fs, const char *old_path, const char *new_path) {
+#if SPIFFS_READ_ONLY
+ (void)fs; (void)old_path; (void)new_path;
+ return SPIFFS_ERR_RO_NOT_IMPL;
+#else
+ SPIFFS_API_CHECK_CFG(fs);
+ SPIFFS_API_CHECK_MOUNT(fs);
+ if (strlen(new_path) > SPIFFS_OBJ_NAME_LEN - 1 ||
+ strlen(old_path) > SPIFFS_OBJ_NAME_LEN - 1) {
+ SPIFFS_API_CHECK_RES(fs, SPIFFS_ERR_NAME_TOO_LONG);
+ }
+ SPIFFS_LOCK(fs);
+
+ spiffs_page_ix pix_old, pix_dummy;
+ spiffs_fd *fd;
+
+ int32_t res = spiffs_object_find_object_index_header_by_name(fs, (const uint8_t*)old_path, &pix_old);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+ res = spiffs_object_find_object_index_header_by_name(fs, (const uint8_t*)new_path, &pix_dummy);
+ if (res == SPIFFS_ERR_NOT_FOUND) {
+ res = SPIFFS_OK;
+ } else if (res == SPIFFS_OK) {
+ res = SPIFFS_ERR_CONFLICTING_NAME;
+ }
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+ res = spiffs_fd_find_new(fs, &fd, 0);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+ res = spiffs_object_open_by_page(fs, pix_old, fd, 0, 0);
+ if (res != SPIFFS_OK) {
+ spiffs_fd_return(fs, fd->file_nbr);
+ }
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+ res = spiffs_object_update_index_hdr(fs, fd, fd->obj_id, fd->objix_hdr_pix, 0, (const uint8_t*)new_path,
+ 0, &pix_dummy);
+#if SPIFFS_TEMPORAL_FD_CACHE
+ if (res == SPIFFS_OK) {
+ spiffs_fd_temporal_cache_rehash(fs, old_path, new_path);
+ }
+#endif
+
+ spiffs_fd_return(fs, fd->file_nbr);
+
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+ SPIFFS_UNLOCK(fs);
+
+ return res;
+#endif // SPIFFS_READ_ONLY
+}
+
+spiffs_DIR *SPIFFS_opendir(spiffs *fs, const char *name, spiffs_DIR *d) {
+ (void)name;
+
+ if (!SPIFFS_CHECK_CFG((fs))) {
+ (fs)->err_code = SPIFFS_ERR_NOT_CONFIGURED;
+ return 0;
+ }
+
+ if (!SPIFFS_CHECK_MOUNT(fs)) {
+ fs->err_code = SPIFFS_ERR_NOT_MOUNTED;
+ return 0;
+ }
+
+ d->fs = fs;
+ d->block = 0;
+ d->entry = 0;
+ return d;
+}
+
+static int32_t spiffs_read_dir_v(
+ spiffs *fs,
+ spiffs_obj_id obj_id,
+ spiffs_block_ix bix,
+ int ix_entry,
+ const void *user_const_p,
+ void *user_var_p) {
+ (void)user_const_p;
+ int32_t res;
+ spiffs_page_object_ix_header objix_hdr;
+ if (obj_id == SPIFFS_OBJ_ID_FREE || obj_id == SPIFFS_OBJ_ID_DELETED ||
+ (obj_id & SPIFFS_OBJ_ID_IX_FLAG) == 0) {
+ return SPIFFS_VIS_COUNTINUE;
+ }
+
+ spiffs_page_ix pix = SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, bix, ix_entry);
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ,
+ 0, SPIFFS_PAGE_TO_PADDR(fs, pix), sizeof(spiffs_page_object_ix_header), (uint8_t *)&objix_hdr);
+ if (res != SPIFFS_OK) return res;
+ if ((obj_id & SPIFFS_OBJ_ID_IX_FLAG) &&
+ objix_hdr.p_hdr.span_ix == 0 &&
+ (objix_hdr.p_hdr.flags & (SPIFFS_PH_FLAG_DELET | SPIFFS_PH_FLAG_FINAL | SPIFFS_PH_FLAG_IXDELE)) ==
+ (SPIFFS_PH_FLAG_DELET | SPIFFS_PH_FLAG_IXDELE)) {
+ struct spiffs_dirent *e = (struct spiffs_dirent*)user_var_p;
+ e->obj_id = obj_id;
+ strcpy((char *)e->name, (char *)objix_hdr.name);
+ e->type = objix_hdr.type;
+ e->size = objix_hdr.size == SPIFFS_UNDEFINED_LEN ? 0 : objix_hdr.size;
+ e->pix = pix;
+ return SPIFFS_OK;
+ }
+ return SPIFFS_VIS_COUNTINUE;
+}
+
+struct spiffs_dirent *SPIFFS_readdir(spiffs_DIR *d, struct spiffs_dirent *e) {
+ if (!SPIFFS_CHECK_MOUNT(d->fs)) {
+ d->fs->err_code = SPIFFS_ERR_NOT_MOUNTED;
+ return 0;
+ }
+ SPIFFS_LOCK(d->fs);
+
+ spiffs_block_ix bix;
+ int entry;
+ int32_t res;
+ struct spiffs_dirent *ret = 0;
+
+ res = spiffs_obj_lu_find_entry_visitor(d->fs,
+ d->block,
+ d->entry,
+ SPIFFS_VIS_NO_WRAP,
+ 0,
+ spiffs_read_dir_v,
+ 0,
+ e,
+ &bix,
+ &entry);
+ if (res == SPIFFS_OK) {
+ d->block = bix;
+ d->entry = entry + 1;
+ ret = e;
+ } else {
+ d->fs->err_code = res;
+ }
+ SPIFFS_UNLOCK(d->fs);
+ return ret;
+}
+
+int32_t SPIFFS_closedir(spiffs_DIR *d) {
+ SPIFFS_API_CHECK_CFG(d->fs);
+ SPIFFS_API_CHECK_MOUNT(d->fs);
+ return 0;
+}
+
+int32_t SPIFFS_check(spiffs *fs) {
+#if SPIFFS_READ_ONLY
+ (void)fs;
+ return SPIFFS_ERR_RO_NOT_IMPL;
+#else
+ int32_t res;
+ SPIFFS_API_CHECK_CFG(fs);
+ SPIFFS_API_CHECK_MOUNT(fs);
+ SPIFFS_LOCK(fs);
+
+ res = spiffs_lookup_consistency_check(fs, 0);
+
+ res = spiffs_object_index_consistency_check(fs);
+
+ res = spiffs_page_consistency_check(fs);
+
+ res = spiffs_obj_lu_scan(fs);
+
+ SPIFFS_UNLOCK(fs);
+ return res;
+#endif // SPIFFS_READ_ONLY
+}
+
+int32_t SPIFFS_info(spiffs *fs, uint32_t *total, uint32_t *used) {
+ int32_t res = SPIFFS_OK;
+ SPIFFS_API_CHECK_CFG(fs);
+ SPIFFS_API_CHECK_MOUNT(fs);
+ SPIFFS_LOCK(fs);
+
+ uint32_t pages_per_block = SPIFFS_PAGES_PER_BLOCK(fs);
+ uint32_t blocks = fs->block_count;
+ uint32_t obj_lu_pages = SPIFFS_OBJ_LOOKUP_PAGES(fs);
+ uint32_t data_page_size = SPIFFS_DATA_PAGE_SIZE(fs);
+ uint32_t total_data_pages = (blocks - 2) * (pages_per_block - obj_lu_pages) + 1; // -2 for spare blocks, +1 for emergency page
+
+ if (total) {
+ *total = total_data_pages * data_page_size;
+ }
+
+ if (used) {
+ *used = fs->stats_p_allocated * data_page_size;
+ }
+
+ SPIFFS_UNLOCK(fs);
+ return res;
+}
+
+int32_t SPIFFS_gc_quick(spiffs *fs, uint16_t max_free_pages) {
+#if SPIFFS_READ_ONLY
+ (void)fs; (void)max_free_pages;
+ return SPIFFS_ERR_RO_NOT_IMPL;
+#else
+ int32_t res;
+ SPIFFS_API_CHECK_CFG(fs);
+ SPIFFS_API_CHECK_MOUNT(fs);
+ SPIFFS_LOCK(fs);
+
+ res = spiffs_gc_quick(fs, max_free_pages);
+
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+ SPIFFS_UNLOCK(fs);
+ return 0;
+#endif // SPIFFS_READ_ONLY
+}
+
+
+int32_t SPIFFS_gc(spiffs *fs, uint32_t size) {
+#if SPIFFS_READ_ONLY
+ (void)fs; (void)size;
+ return SPIFFS_ERR_RO_NOT_IMPL;
+#else
+ int32_t res;
+ SPIFFS_API_CHECK_CFG(fs);
+ SPIFFS_API_CHECK_MOUNT(fs);
+ SPIFFS_LOCK(fs);
+
+ res = spiffs_gc_check(fs, size);
+
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+ SPIFFS_UNLOCK(fs);
+ return 0;
+#endif // SPIFFS_READ_ONLY
+}
+
+int32_t SPIFFS_eof(spiffs *fs, spiffs_file fh) {
+ int32_t res;
+ SPIFFS_API_CHECK_CFG(fs);
+ SPIFFS_API_CHECK_MOUNT(fs);
+ SPIFFS_LOCK(fs);
+
+ fh = SPIFFS_FH_UNOFFS(fs, fh);
+
+ spiffs_fd *fd;
+ res = spiffs_fd_get(fs, fh, &fd);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+#if SPIFFS_CACHE_WR
+ res = spiffs_fflush_cache(fs, fh);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+#endif
+
+ res = (fd->fdoffset >= (fd->size == SPIFFS_UNDEFINED_LEN ? 0 : fd->size));
+
+ SPIFFS_UNLOCK(fs);
+ return res;
+}
+
+int32_t SPIFFS_tell(spiffs *fs, spiffs_file fh) {
+ int32_t res;
+ SPIFFS_API_CHECK_CFG(fs);
+ SPIFFS_API_CHECK_MOUNT(fs);
+ SPIFFS_LOCK(fs);
+
+ fh = SPIFFS_FH_UNOFFS(fs, fh);
+
+ spiffs_fd *fd;
+ res = spiffs_fd_get(fs, fh, &fd);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+#if SPIFFS_CACHE_WR
+ res = spiffs_fflush_cache(fs, fh);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+#endif
+
+ res = fd->fdoffset;
+
+ SPIFFS_UNLOCK(fs);
+ return res;
+}
+
+int32_t SPIFFS_set_file_callback_func(spiffs *fs, spiffs_file_callback cb_func) {
+ SPIFFS_LOCK(fs);
+ fs->file_cb_f = cb_func;
+ SPIFFS_UNLOCK(fs);
+ return 0;
+}
+
+#if SPIFFS_IX_MAP
+
+int32_t SPIFFS_ix_map(spiffs *fs, spiffs_file fh, spiffs_ix_map *map,
+ uint32_t offset, uint32_t len, spiffs_page_ix *map_buf) {
+ int32_t res;
+ SPIFFS_API_CHECK_CFG(fs);
+ SPIFFS_API_CHECK_MOUNT(fs);
+ SPIFFS_LOCK(fs);
+
+ fh = SPIFFS_FH_UNOFFS(fs, fh);
+
+ spiffs_fd *fd;
+ res = spiffs_fd_get(fs, fh, &fd);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+ if (fd->ix_map) {
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, SPIFFS_ERR_IX_MAP_MAPPED);
+ }
+
+ map->map_buf = map_buf;
+ map->offset = offset;
+ // nb: spix range includes last
+ map->start_spix = offset / SPIFFS_DATA_PAGE_SIZE(fs);
+ map->end_spix = (offset + len) / SPIFFS_DATA_PAGE_SIZE(fs);
+ memset(map_buf, 0, sizeof(spiffs_page_ix) * (map->end_spix - map->start_spix + 1));
+ fd->ix_map = map;
+
+ // scan for pixes
+ res = spiffs_populate_ix_map(fs, fd, 0, map->end_spix - map->start_spix + 1);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+ SPIFFS_UNLOCK(fs);
+ return res;
+}
+
+int32_t SPIFFS_ix_unmap(spiffs *fs, spiffs_file fh) {
+ int32_t res;
+ SPIFFS_API_CHECK_CFG(fs);
+ SPIFFS_API_CHECK_MOUNT(fs);
+ SPIFFS_LOCK(fs);
+
+ fh = SPIFFS_FH_UNOFFS(fs, fh);
+
+ spiffs_fd *fd;
+ res = spiffs_fd_get(fs, fh, &fd);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+ if (fd->ix_map == 0) {
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, SPIFFS_ERR_IX_MAP_UNMAPPED);
+ }
+
+ fd->ix_map = 0;
+
+ SPIFFS_UNLOCK(fs);
+ return res;
+}
+
+int32_t SPIFFS_ix_remap(spiffs *fs, spiffs_file fh, uint32_t offset) {
+ int32_t res = SPIFFS_OK;
+ SPIFFS_API_CHECK_CFG(fs);
+ SPIFFS_API_CHECK_MOUNT(fs);
+ SPIFFS_LOCK(fs);
+
+ fh = SPIFFS_FH_UNOFFS(fs, fh);
+
+ spiffs_fd *fd;
+ res = spiffs_fd_get(fs, fh, &fd);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+
+ if (fd->ix_map == 0) {
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, SPIFFS_ERR_IX_MAP_UNMAPPED);
+ }
+
+ spiffs_ix_map *map = fd->ix_map;
+
+ int32_t spix_diff = offset / SPIFFS_DATA_PAGE_SIZE(fs) - map->start_spix;
+ map->offset = offset;
+
+ // move existing pixes if within map offs
+ if (spix_diff != 0) {
+ // move vector
+ int i;
+ const int32_t vec_len = map->end_spix - map->start_spix + 1; // spix range includes last
+ map->start_spix += spix_diff;
+ map->end_spix += spix_diff;
+ if (spix_diff >= vec_len) {
+ // moving beyond range
+ memset(&map->map_buf, 0, vec_len * sizeof(spiffs_page_ix));
+ // populate_ix_map is inclusive
+ res = spiffs_populate_ix_map(fs, fd, 0, vec_len-1);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+ } else if (spix_diff > 0) {
+ // diff positive
+ for (i = 0; i < vec_len - spix_diff; i++) {
+ map->map_buf[i] = map->map_buf[i + spix_diff];
+ }
+ // memset is non-inclusive
+ memset(&map->map_buf[vec_len - spix_diff], 0, spix_diff * sizeof(spiffs_page_ix));
+ // populate_ix_map is inclusive
+ res = spiffs_populate_ix_map(fs, fd, vec_len - spix_diff, vec_len-1);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+ } else {
+ // diff negative
+ for (i = vec_len - 1; i >= -spix_diff; i--) {
+ map->map_buf[i] = map->map_buf[i + spix_diff];
+ }
+ // memset is non-inclusive
+ memset(&map->map_buf[0], 0, -spix_diff * sizeof(spiffs_page_ix));
+ // populate_ix_map is inclusive
+ res = spiffs_populate_ix_map(fs, fd, 0, -spix_diff - 1);
+ SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
+ }
+
+ }
+
+ SPIFFS_UNLOCK(fs);
+ return res;
+}
+
+int32_t SPIFFS_bytes_to_ix_map_entries(spiffs *fs, uint32_t bytes) {
+ SPIFFS_API_CHECK_CFG(fs);
+ // always add one extra page, the offset might change to the middle of a page
+ return (bytes + SPIFFS_DATA_PAGE_SIZE(fs) ) / SPIFFS_DATA_PAGE_SIZE(fs);
+}
+
+int32_t SPIFFS_ix_map_entries_to_bytes(spiffs *fs, uint32_t map_page_ix_entries) {
+ SPIFFS_API_CHECK_CFG(fs);
+ return map_page_ix_entries * SPIFFS_DATA_PAGE_SIZE(fs);
+}
+
+#endif // SPIFFS_IX_MAP
+
+#if SPIFFS_TEST_VISUALISATION
+int32_t SPIFFS_vis(spiffs *fs) {
+ int32_t res = SPIFFS_OK;
+ SPIFFS_API_CHECK_CFG(fs);
+ SPIFFS_API_CHECK_MOUNT(fs);
+ SPIFFS_LOCK(fs);
+
+ int entries_per_page = (SPIFFS_CFG_LOG_PAGE_SZ(fs) / sizeof(spiffs_obj_id));
+ spiffs_obj_id *obj_lu_buf = (spiffs_obj_id *)fs->lu_work;
+ spiffs_block_ix bix = 0;
+
+ while (bix < fs->block_count) {
+ // check each object lookup page
+ int obj_lookup_page = 0;
+ int cur_entry = 0;
+
+ while (res == SPIFFS_OK && obj_lookup_page < (int)SPIFFS_OBJ_LOOKUP_PAGES(fs)) {
+ int entry_offset = obj_lookup_page * entries_per_page;
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU | SPIFFS_OP_C_READ,
+ 0, bix * SPIFFS_CFG_LOG_BLOCK_SZ(fs) + SPIFFS_PAGE_TO_PADDR(fs, obj_lookup_page), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->lu_work);
+ // check each entry
+ while (res == SPIFFS_OK &&
+ cur_entry - entry_offset < entries_per_page && cur_entry < (int)(SPIFFS_PAGES_PER_BLOCK(fs)-SPIFFS_OBJ_LOOKUP_PAGES(fs))) {
+ spiffs_obj_id obj_id = obj_lu_buf[cur_entry-entry_offset];
+ if (cur_entry == 0) {
+ spiffs_printf("%4i ", bix);
+ } else if ((cur_entry & 0x3f) == 0) {
+ spiffs_printf(" ");
+ }
+ if (obj_id == SPIFFS_OBJ_ID_FREE) {
+ spiffs_printf(SPIFFS_TEST_VIS_FREE_STR);
+ } else if (obj_id == SPIFFS_OBJ_ID_DELETED) {
+ spiffs_printf(SPIFFS_TEST_VIS_DELE_STR);
+ } else if (obj_id & SPIFFS_OBJ_ID_IX_FLAG){
+ spiffs_printf(SPIFFS_TEST_VIS_INDX_STR(obj_id));
+ } else {
+ spiffs_printf(SPIFFS_TEST_VIS_DATA_STR(obj_id));
+ }
+ cur_entry++;
+ if ((cur_entry & 0x3f) == 0) {
+ spiffs_printf("\n");
+ }
+ } // per entry
+ obj_lookup_page++;
+ } // per object lookup page
+
+ spiffs_obj_id erase_count;
+ res = _spiffs_rd(fs, SPIFFS_OP_C_READ | SPIFFS_OP_T_OBJ_LU2, 0,
+ SPIFFS_ERASE_COUNT_PADDR(fs, bix),
+ sizeof(spiffs_obj_id), (uint8_t *)&erase_count);
+ SPIFFS_CHECK_RES(res);
+
+ if (erase_count != (spiffs_obj_id)-1) {
+ spiffs_printf("\tera_cnt: %i\n", erase_count);
+ } else {
+ spiffs_printf("\tera_cnt: N/A\n");
+ }
+
+ bix++;
+ } // per block
+
+ spiffs_printf("era_cnt_max: %i\n", fs->max_erase_count);
+ spiffs_printf("last_errno: %i\n", fs->err_code);
+ spiffs_printf("blocks: %i\n", fs->block_count);
+ spiffs_printf("free_blocks: %i\n", fs->free_blocks);
+ spiffs_printf("page_alloc: %i\n", fs->stats_p_allocated);
+ spiffs_printf("page_delet: %i\n", fs->stats_p_deleted);
+ SPIFFS_UNLOCK(fs);
+ uint32_t total, used;
+ SPIFFS_info(fs, &total, &used);
+ spiffs_printf("used: %i of %i\n", used, total);
+ return res;
+}
+#endif
diff --git a/fw/User/spiffs/src/spiffs_nucleus.c b/fw/User/spiffs/src/spiffs_nucleus.c
new file mode 100644
index 0000000..3528823
--- /dev/null
+++ b/fw/User/spiffs/src/spiffs_nucleus.c
@@ -0,0 +1,2310 @@
+#include "spiffs.h"
+#include "spiffs_nucleus.h"
+
+static int32_t spiffs_page_data_check(spiffs *fs, spiffs_fd *fd, spiffs_page_ix pix, spiffs_span_ix spix) {
+ int32_t res = SPIFFS_OK;
+ if (pix == (spiffs_page_ix)-1) {
+ // referring to page 0xffff...., bad object index
+ return SPIFFS_ERR_INDEX_REF_FREE;
+ }
+ if (pix % SPIFFS_PAGES_PER_BLOCK(fs) < SPIFFS_OBJ_LOOKUP_PAGES(fs)) {
+ // referring to an object lookup page, bad object index
+ return SPIFFS_ERR_INDEX_REF_LU;
+ }
+ if (pix > SPIFFS_MAX_PAGES(fs)) {
+ // referring to a bad page
+ return SPIFFS_ERR_INDEX_REF_INVALID;
+ }
+#if SPIFFS_PAGE_CHECK
+ spiffs_page_header ph;
+ res = _spiffs_rd(
+ fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_READ,
+ fd->file_nbr,
+ SPIFFS_PAGE_TO_PADDR(fs, pix),
+ sizeof(spiffs_page_header),
+ (uint8_t *)&ph);
+ SPIFFS_CHECK_RES(res);
+ SPIFFS_VALIDATE_DATA(ph, fd->obj_id & ~SPIFFS_OBJ_ID_IX_FLAG, spix);
+#endif
+ return res;
+}
+
+#if !SPIFFS_READ_ONLY
+static int32_t spiffs_page_index_check(spiffs *fs, spiffs_fd *fd, spiffs_page_ix pix, spiffs_span_ix spix) {
+ int32_t res = SPIFFS_OK;
+ if (pix == (spiffs_page_ix)-1) {
+ // referring to page 0xffff...., bad object index
+ return SPIFFS_ERR_INDEX_FREE;
+ }
+ if (pix % SPIFFS_PAGES_PER_BLOCK(fs) < SPIFFS_OBJ_LOOKUP_PAGES(fs)) {
+ // referring to an object lookup page, bad object index
+ return SPIFFS_ERR_INDEX_LU;
+ }
+ if (pix > SPIFFS_MAX_PAGES(fs)) {
+ // referring to a bad page
+ return SPIFFS_ERR_INDEX_INVALID;
+ }
+#if SPIFFS_PAGE_CHECK
+ spiffs_page_header ph;
+ res = _spiffs_rd(
+ fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_READ,
+ fd->file_nbr,
+ SPIFFS_PAGE_TO_PADDR(fs, pix),
+ sizeof(spiffs_page_header),
+ (uint8_t *)&ph);
+ SPIFFS_CHECK_RES(res);
+ SPIFFS_VALIDATE_OBJIX(ph, fd->obj_id, spix);
+#endif
+ return res;
+}
+#endif // !SPIFFS_READ_ONLY
+
+#if !SPIFFS_CACHE
+
+int32_t spiffs_phys_rd(
+ spiffs *fs,
+ uint32_t addr,
+ uint32_t len,
+ uint8_t *dst) {
+ return SPIFFS_HAL_READ(fs, addr, len, dst);
+}
+
+int32_t spiffs_phys_wr(
+ spiffs *fs,
+ uint32_t addr,
+ uint32_t len,
+ uint8_t *src) {
+ return SPIFFS_HAL_WRITE(fs, addr, len, src);
+}
+
+#endif
+
+#if !SPIFFS_READ_ONLY
+int32_t spiffs_phys_cpy(
+ spiffs *fs,
+ spiffs_file fh,
+ uint32_t dst,
+ uint32_t src,
+ uint32_t len) {
+ (void)fh;
+ int32_t res;
+ uint8_t b[SPIFFS_COPY_BUFFER_STACK];
+ while (len > 0) {
+ uint32_t chunk_size = MIN(SPIFFS_COPY_BUFFER_STACK, len);
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_MOVS, fh, src, chunk_size, b);
+ SPIFFS_CHECK_RES(res);
+ res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_MOVD, fh, dst, chunk_size, b);
+ SPIFFS_CHECK_RES(res);
+ len -= chunk_size;
+ src += chunk_size;
+ dst += chunk_size;
+ }
+ return SPIFFS_OK;
+}
+#endif // !SPIFFS_READ_ONLY
+
+// Find object lookup entry containing given id with visitor.
+// Iterate over object lookup pages in each block until a given object id entry is found.
+// When found, the visitor function is called with block index, entry index and user data.
+// If visitor returns SPIFFS_VIS_CONTINUE, the search goes on. Otherwise, the search will be
+// ended and visitor's return code is returned to caller.
+// If no visitor is given (0) the search returns on first entry with matching object id.
+// If no match is found in all look up, SPIFFS_VIS_END is returned.
+// @param fs the file system
+// @param starting_block the starting block to start search in
+// @param starting_lu_entry the look up index entry to start search in
+// @param flags ored combination of SPIFFS_VIS_CHECK_ID, SPIFFS_VIS_CHECK_PH,
+// SPIFFS_VIS_NO_WRAP
+// @param obj_id argument object id
+// @param v visitor callback function
+// @param user_const_p any const pointer, passed to the callback visitor function
+// @param user_var_p any pointer, passed to the callback visitor function
+// @param block_ix reported block index where match was found
+// @param lu_entry reported look up index where match was found
+int32_t spiffs_obj_lu_find_entry_visitor(
+ spiffs *fs,
+ spiffs_block_ix starting_block,
+ int starting_lu_entry,
+ uint8_t flags,
+ spiffs_obj_id obj_id,
+ spiffs_visitor_f v,
+ const void *user_const_p,
+ void *user_var_p,
+ spiffs_block_ix *block_ix,
+ int *lu_entry) {
+ int32_t res = SPIFFS_OK;
+ int32_t entry_count = fs->block_count * SPIFFS_OBJ_LOOKUP_MAX_ENTRIES(fs);
+ spiffs_block_ix cur_block = starting_block;
+ uint32_t cur_block_addr = starting_block * SPIFFS_CFG_LOG_BLOCK_SZ(fs);
+
+ spiffs_obj_id *obj_lu_buf = (spiffs_obj_id *)fs->lu_work;
+ int cur_entry = starting_lu_entry;
+ int entries_per_page = (SPIFFS_CFG_LOG_PAGE_SZ(fs) / sizeof(spiffs_obj_id));
+
+ // wrap initial
+ if (cur_entry > (int)SPIFFS_OBJ_LOOKUP_MAX_ENTRIES(fs) - 1) {
+ cur_entry = 0;
+ cur_block++;
+ cur_block_addr = cur_block * SPIFFS_CFG_LOG_BLOCK_SZ(fs);
+ if (cur_block >= fs->block_count) {
+ if (flags & SPIFFS_VIS_NO_WRAP) {
+ return SPIFFS_VIS_END;
+ } else {
+ // block wrap
+ cur_block = 0;
+ cur_block_addr = 0;
+ }
+ }
+ }
+
+ // check each block
+ while (res == SPIFFS_OK && entry_count > 0) {
+ int obj_lookup_page = cur_entry / entries_per_page;
+ // check each object lookup page
+ while (res == SPIFFS_OK && obj_lookup_page < (int)SPIFFS_OBJ_LOOKUP_PAGES(fs)) {
+ int entry_offset = obj_lookup_page * entries_per_page;
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU | SPIFFS_OP_C_READ,
+ 0, cur_block_addr + SPIFFS_PAGE_TO_PADDR(fs, obj_lookup_page), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->lu_work);
+ // check each entry
+ while (res == SPIFFS_OK &&
+ cur_entry - entry_offset < entries_per_page && // for non-last obj lookup pages
+ cur_entry < (int)SPIFFS_OBJ_LOOKUP_MAX_ENTRIES(fs)) // for last obj lookup page
+ {
+ if ((flags & SPIFFS_VIS_CHECK_ID) == 0 || obj_lu_buf[cur_entry-entry_offset] == obj_id) {
+ if (block_ix) *block_ix = cur_block;
+ if (lu_entry) *lu_entry = cur_entry;
+ if (v) {
+ res = v(
+ fs,
+ (flags & SPIFFS_VIS_CHECK_PH) ? obj_id : obj_lu_buf[cur_entry-entry_offset],
+ cur_block,
+ cur_entry,
+ user_const_p,
+ user_var_p);
+ if (res == SPIFFS_VIS_COUNTINUE || res == SPIFFS_VIS_COUNTINUE_RELOAD) {
+ if (res == SPIFFS_VIS_COUNTINUE_RELOAD) {
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU | SPIFFS_OP_C_READ,
+ 0, cur_block_addr + SPIFFS_PAGE_TO_PADDR(fs, obj_lookup_page), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->lu_work);
+ SPIFFS_CHECK_RES(res);
+ }
+ res = SPIFFS_OK;
+ cur_entry++;
+ entry_count--;
+ continue;
+ } else {
+ return res;
+ }
+ } else {
+ return SPIFFS_OK;
+ }
+ }
+ entry_count--;
+ cur_entry++;
+ } // per entry
+ obj_lookup_page++;
+ } // per object lookup page
+ cur_entry = 0;
+ cur_block++;
+ cur_block_addr += SPIFFS_CFG_LOG_BLOCK_SZ(fs);
+ if (cur_block >= fs->block_count) {
+ if (flags & SPIFFS_VIS_NO_WRAP) {
+ return SPIFFS_VIS_END;
+ } else {
+ // block wrap
+ cur_block = 0;
+ cur_block_addr = 0;
+ }
+ }
+ } // per block
+
+ SPIFFS_CHECK_RES(res);
+
+ return SPIFFS_VIS_END;
+}
+
+#if !SPIFFS_READ_ONLY
+int32_t spiffs_erase_block(
+ spiffs *fs,
+ spiffs_block_ix bix) {
+ int32_t res;
+ uint32_t addr = SPIFFS_BLOCK_TO_PADDR(fs, bix);
+ int32_t size = SPIFFS_CFG_LOG_BLOCK_SZ(fs);
+
+ // here we ignore res, just try erasing the block
+ while (size > 0) {
+ SPIFFS_DBG("erase %08x:%08x\n", addr, SPIFFS_CFG_PHYS_ERASE_SZ(fs));
+ SPIFFS_HAL_ERASE(fs, addr, SPIFFS_CFG_PHYS_ERASE_SZ(fs));
+
+ addr += SPIFFS_CFG_PHYS_ERASE_SZ(fs);
+ size -= SPIFFS_CFG_PHYS_ERASE_SZ(fs);
+ }
+ fs->free_blocks++;
+
+ // register erase count for this block
+ res = _spiffs_wr(fs, SPIFFS_OP_C_WRTHRU | SPIFFS_OP_T_OBJ_LU2, 0,
+ SPIFFS_ERASE_COUNT_PADDR(fs, bix),
+ sizeof(spiffs_obj_id), (uint8_t *)&fs->max_erase_count);
+ SPIFFS_CHECK_RES(res);
+
+#if SPIFFS_USE_MAGIC
+ // finally, write magic
+ spiffs_obj_id magic = SPIFFS_MAGIC(fs, bix);
+ res = _spiffs_wr(fs, SPIFFS_OP_C_WRTHRU | SPIFFS_OP_T_OBJ_LU2, 0,
+ SPIFFS_MAGIC_PADDR(fs, bix),
+ sizeof(spiffs_obj_id), (uint8_t *)&magic);
+ SPIFFS_CHECK_RES(res);
+#endif
+
+ fs->max_erase_count++;
+ if (fs->max_erase_count == SPIFFS_OBJ_ID_IX_FLAG) {
+ fs->max_erase_count = 0;
+ }
+
+ return res;
+}
+#endif // !SPIFFS_READ_ONLY
+
+#if SPIFFS_USE_MAGIC && SPIFFS_USE_MAGIC_LENGTH && SPIFFS_SINGLETON==0
+int32_t spiffs_probe(
+ spiffs_config *cfg) {
+ int32_t res;
+ uint32_t paddr;
+ spiffs dummy_fs; // create a dummy fs struct just to be able to use macros
+ memcpy(&dummy_fs.cfg, cfg, sizeof(spiffs_config));
+ dummy_fs.block_count = 0;
+
+ // Read three magics, as one block may be in an aborted erase state.
+ // At least two of these must contain magic and be in decreasing order.
+ spiffs_obj_id magic[3];
+ spiffs_obj_id bix_count[3];
+
+ spiffs_block_ix bix;
+ for (bix = 0; bix < 3; bix++) {
+ paddr = SPIFFS_MAGIC_PADDR(&dummy_fs, bix);
+#if SPIFFS_HAL_CALLBACK_EXTRA
+ // not any proper fs to report here, so callback with null
+ // (cross fingers that no-one gets angry)
+ res = cfg->hal_read_f((void *)0, paddr, sizeof(spiffs_obj_id), (uint8_t *)&magic[bix]);
+#else
+ res = cfg->hal_read_f(paddr, sizeof(spiffs_obj_id), (uint8_t *)&magic[bix]);
+#endif
+ bix_count[bix] = magic[bix] ^ SPIFFS_MAGIC(&dummy_fs, 0);
+ SPIFFS_CHECK_RES(res);
+ }
+
+ // check that we have sane number of blocks
+ if (bix_count[0] < 3) return SPIFFS_ERR_PROBE_TOO_FEW_BLOCKS;
+ // check that the order is correct, take aborted erases in calculation
+ // first block aborted erase
+ if (magic[0] == (spiffs_obj_id)(-1) && bix_count[1] - bix_count[2] == 1) {
+ return (bix_count[1]+1) * cfg->log_block_size;
+ }
+ // second block aborted erase
+ if (magic[1] == (spiffs_obj_id)(-1) && bix_count[0] - bix_count[2] == 2) {
+ return bix_count[0] * cfg->log_block_size;
+ }
+ // third block aborted erase
+ if (magic[2] == (spiffs_obj_id)(-1) && bix_count[0] - bix_count[1] == 1) {
+ return bix_count[0] * cfg->log_block_size;
+ }
+ // no block has aborted erase
+ if (bix_count[0] - bix_count[1] == 1 && bix_count[1] - bix_count[2] == 1) {
+ return bix_count[0] * cfg->log_block_size;
+ }
+
+ return SPIFFS_ERR_PROBE_NOT_A_FS;
+}
+#endif // SPIFFS_USE_MAGIC && SPIFFS_USE_MAGIC_LENGTH && SPIFFS_SINGLETON==0
+
+
+static int32_t spiffs_obj_lu_scan_v(
+ spiffs *fs,
+ spiffs_obj_id obj_id,
+ spiffs_block_ix bix,
+ int ix_entry,
+ const void *user_const_p,
+ void *user_var_p) {
+ (void)bix;
+ (void)user_const_p;
+ (void)user_var_p;
+ if (obj_id == SPIFFS_OBJ_ID_FREE) {
+ if (ix_entry == 0) {
+ fs->free_blocks++;
+ // todo optimize further, return SPIFFS_NEXT_BLOCK
+ }
+ } else if (obj_id == SPIFFS_OBJ_ID_DELETED) {
+ fs->stats_p_deleted++;
+ } else {
+ fs->stats_p_allocated++;
+ }
+
+ return SPIFFS_VIS_COUNTINUE;
+}
+
+
+// Scans thru all obj lu and counts free, deleted and used pages
+// Find the maximum block erase count
+// Checks magic if enabled
+int32_t spiffs_obj_lu_scan(
+ spiffs *fs) {
+ int32_t res;
+ spiffs_block_ix bix;
+ int entry;
+#if SPIFFS_USE_MAGIC
+ spiffs_block_ix unerased_bix = (spiffs_block_ix)-1;
+#endif
+
+ // find out erase count
+ // if enabled, check magic
+ bix = 0;
+ spiffs_obj_id erase_count_final;
+ spiffs_obj_id erase_count_min = SPIFFS_OBJ_ID_FREE;
+ spiffs_obj_id erase_count_max = 0;
+ while (bix < fs->block_count) {
+#if SPIFFS_USE_MAGIC
+ spiffs_obj_id magic;
+ res = _spiffs_rd(fs,
+ SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ,
+ 0, SPIFFS_MAGIC_PADDR(fs, bix) ,
+ sizeof(spiffs_obj_id), (uint8_t *)&magic);
+
+ SPIFFS_CHECK_RES(res);
+ if (magic != SPIFFS_MAGIC(fs, bix)) {
+ if (unerased_bix == (spiffs_block_ix)-1) {
+ // allow one unerased block as it might be powered down during an erase
+ unerased_bix = bix;
+ } else {
+ // more than one unerased block, bail out
+ SPIFFS_CHECK_RES(SPIFFS_ERR_NOT_A_FS);
+ }
+ }
+#endif
+ spiffs_obj_id erase_count;
+ res = _spiffs_rd(fs,
+ SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ,
+ 0, SPIFFS_ERASE_COUNT_PADDR(fs, bix) ,
+ sizeof(spiffs_obj_id), (uint8_t *)&erase_count);
+ SPIFFS_CHECK_RES(res);
+ if (erase_count != SPIFFS_OBJ_ID_FREE) {
+ erase_count_min = MIN(erase_count_min, erase_count);
+ erase_count_max = MAX(erase_count_max, erase_count);
+ }
+ bix++;
+ }
+
+ if (erase_count_min == 0 && erase_count_max == SPIFFS_OBJ_ID_FREE) {
+ // clean system, set counter to zero
+ erase_count_final = 0;
+ } else if (erase_count_max - erase_count_min > (SPIFFS_OBJ_ID_FREE)/2) {
+ // wrap, take min
+ erase_count_final = erase_count_min+1;
+ } else {
+ erase_count_final = erase_count_max+1;
+ }
+
+ fs->max_erase_count = erase_count_final;
+
+#if SPIFFS_USE_MAGIC
+ if (unerased_bix != (spiffs_block_ix)-1) {
+ // found one unerased block, remedy
+ SPIFFS_DBG("mount: erase block %i\n", bix);
+#if SPIFFS_READ_ONLY
+ res = SPIFFS_ERR_RO_ABORTED_OPERATION;
+#else
+ res = spiffs_erase_block(fs, unerased_bix);
+#endif // SPIFFS_READ_ONLY
+ SPIFFS_CHECK_RES(res);
+ }
+#endif
+
+ // count blocks
+
+ fs->free_blocks = 0;
+ fs->stats_p_allocated = 0;
+ fs->stats_p_deleted = 0;
+
+ res = spiffs_obj_lu_find_entry_visitor(fs,
+ 0,
+ 0,
+ 0,
+ 0,
+ spiffs_obj_lu_scan_v,
+ 0,
+ 0,
+ &bix,
+ &entry);
+
+ if (res == SPIFFS_VIS_END) {
+ res = SPIFFS_OK;
+ }
+
+ SPIFFS_CHECK_RES(res);
+
+ return res;
+}
+
+#if !SPIFFS_READ_ONLY
+// Find free object lookup entry
+// Iterate over object lookup pages in each block until a free object id entry is found
+int32_t spiffs_obj_lu_find_free(
+ spiffs *fs,
+ spiffs_block_ix starting_block,
+ int starting_lu_entry,
+ spiffs_block_ix *block_ix,
+ int *lu_entry) {
+ int32_t res;
+ if (!fs->cleaning && fs->free_blocks < 2) {
+ res = spiffs_gc_quick(fs, 0);
+ if (res == SPIFFS_ERR_NO_DELETED_BLOCKS) {
+ res = SPIFFS_OK;
+ }
+ SPIFFS_CHECK_RES(res);
+ if (fs->free_blocks < 2) {
+ return SPIFFS_ERR_FULL;
+ }
+ }
+ res = spiffs_obj_lu_find_id(fs, starting_block, starting_lu_entry,
+ SPIFFS_OBJ_ID_FREE, block_ix, lu_entry);
+ if (res == SPIFFS_OK) {
+ fs->free_cursor_block_ix = *block_ix;
+ fs->free_cursor_obj_lu_entry = (*lu_entry) + 1;
+ if (*lu_entry == 0) {
+ fs->free_blocks--;
+ }
+ }
+ if (res == SPIFFS_ERR_FULL) {
+ SPIFFS_DBG("fs full\n");
+ }
+
+ return res;
+}
+#endif // !SPIFFS_READ_ONLY
+
+// Find object lookup entry containing given id
+// Iterate over object lookup pages in each block until a given object id entry is found
+int32_t spiffs_obj_lu_find_id(
+ spiffs *fs,
+ spiffs_block_ix starting_block,
+ int starting_lu_entry,
+ spiffs_obj_id obj_id,
+ spiffs_block_ix *block_ix,
+ int *lu_entry) {
+ int32_t res = spiffs_obj_lu_find_entry_visitor(
+ fs, starting_block, starting_lu_entry, SPIFFS_VIS_CHECK_ID, obj_id, 0, 0, 0, block_ix, lu_entry);
+ if (res == SPIFFS_VIS_END) {
+ res = SPIFFS_ERR_NOT_FOUND;
+ }
+ return res;
+}
+
+
+static int32_t spiffs_obj_lu_find_id_and_span_v(
+ spiffs *fs,
+ spiffs_obj_id obj_id,
+ spiffs_block_ix bix,
+ int ix_entry,
+ const void *user_const_p,
+ void *user_var_p) {
+ int32_t res;
+ spiffs_page_header ph;
+ spiffs_page_ix pix = SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, bix, ix_entry);
+ res = _spiffs_rd(fs, 0, SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ,
+ SPIFFS_PAGE_TO_PADDR(fs, pix), sizeof(spiffs_page_header), (uint8_t *)&ph);
+ SPIFFS_CHECK_RES(res);
+ if (ph.obj_id == obj_id &&
+ ph.span_ix == *((spiffs_span_ix*)user_var_p) &&
+ (ph.flags & (SPIFFS_PH_FLAG_FINAL | SPIFFS_PH_FLAG_DELET | SPIFFS_PH_FLAG_USED)) == SPIFFS_PH_FLAG_DELET &&
+ !((obj_id & SPIFFS_OBJ_ID_IX_FLAG) && (ph.flags & SPIFFS_PH_FLAG_IXDELE) == 0 && ph.span_ix == 0) &&
+ (user_const_p == 0 || *((const spiffs_page_ix*)user_const_p) != pix)) {
+ return SPIFFS_OK;
+ } else {
+ return SPIFFS_VIS_COUNTINUE;
+ }
+}
+
+// Find object lookup entry containing given id and span index
+// Iterate over object lookup pages in each block until a given object id entry is found
+int32_t spiffs_obj_lu_find_id_and_span(
+ spiffs *fs,
+ spiffs_obj_id obj_id,
+ spiffs_span_ix spix,
+ spiffs_page_ix exclusion_pix,
+ spiffs_page_ix *pix) {
+ int32_t res;
+ spiffs_block_ix bix;
+ int entry;
+
+ res = spiffs_obj_lu_find_entry_visitor(fs,
+ fs->cursor_block_ix,
+ fs->cursor_obj_lu_entry,
+ SPIFFS_VIS_CHECK_ID,
+ obj_id,
+ spiffs_obj_lu_find_id_and_span_v,
+ exclusion_pix ? &exclusion_pix : 0,
+ &spix,
+ &bix,
+ &entry);
+
+ if (res == SPIFFS_VIS_END) {
+ res = SPIFFS_ERR_NOT_FOUND;
+ }
+
+ SPIFFS_CHECK_RES(res);
+
+ if (pix) {
+ *pix = SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, bix, entry);
+ }
+
+ fs->cursor_block_ix = bix;
+ fs->cursor_obj_lu_entry = entry;
+
+ return res;
+}
+
+// Find object lookup entry containing given id and span index in page headers only
+// Iterate over object lookup pages in each block until a given object id entry is found
+int32_t spiffs_obj_lu_find_id_and_span_by_phdr(
+ spiffs *fs,
+ spiffs_obj_id obj_id,
+ spiffs_span_ix spix,
+ spiffs_page_ix exclusion_pix,
+ spiffs_page_ix *pix) {
+ int32_t res;
+ spiffs_block_ix bix;
+ int entry;
+
+ res = spiffs_obj_lu_find_entry_visitor(fs,
+ fs->cursor_block_ix,
+ fs->cursor_obj_lu_entry,
+ SPIFFS_VIS_CHECK_PH,
+ obj_id,
+ spiffs_obj_lu_find_id_and_span_v,
+ exclusion_pix ? &exclusion_pix : 0,
+ &spix,
+ &bix,
+ &entry);
+
+ if (res == SPIFFS_VIS_END) {
+ res = SPIFFS_ERR_NOT_FOUND;
+ }
+
+ SPIFFS_CHECK_RES(res);
+
+ if (pix) {
+ *pix = SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, bix, entry);
+ }
+
+ fs->cursor_block_ix = bix;
+ fs->cursor_obj_lu_entry = entry;
+
+ return res;
+}
+
+#if SPIFFS_IX_MAP
+
+// update index map of given fd with given object index data
+static void spiffs_update_ix_map(spiffs *fs,
+ spiffs_fd *fd, spiffs_span_ix objix_spix, spiffs_page_object_ix *objix) {
+#if SPIFFS_SINGLETON
+ (void)fs;
+#endif
+ spiffs_ix_map *map = fd->ix_map;
+ spiffs_span_ix map_objix_start_spix = SPIFFS_OBJ_IX_ENTRY_SPAN_IX(fs, map->start_spix);
+ spiffs_span_ix map_objix_end_spix = SPIFFS_OBJ_IX_ENTRY_SPAN_IX(fs, map->end_spix);
+
+ // check if updated ix is within map range
+ if (objix_spix < map_objix_start_spix || objix_spix > map_objix_end_spix) {
+ return;
+ }
+
+ // update memory mapped page index buffer to new pages
+
+ // get range of updated object index map data span indices
+ spiffs_span_ix objix_data_spix_start =
+ SPIFFS_DATA_SPAN_IX_FOR_OBJ_IX_SPAN_IX(fs, objix_spix);
+ spiffs_span_ix objix_data_spix_end = objix_data_spix_start +
+ (objix_spix == 0 ? SPIFFS_OBJ_HDR_IX_LEN(fs) : SPIFFS_OBJ_IX_LEN(fs));
+
+ // calc union of object index range and index map range array
+ spiffs_span_ix map_spix = MAX(map->start_spix, objix_data_spix_start);
+ spiffs_span_ix map_spix_end = MIN(map->end_spix + 1, objix_data_spix_end);
+
+ while (map_spix < map_spix_end) {
+ spiffs_page_ix objix_data_pix;
+ if (objix_spix == 0) {
+ // get data page from object index header page
+ objix_data_pix = ((spiffs_page_ix*)((uint8_t *)objix + sizeof(spiffs_page_object_ix_header)))[map_spix];
+ } else {
+ // get data page from object index page
+ objix_data_pix = ((spiffs_page_ix*)((uint8_t *)objix + sizeof(spiffs_page_object_ix)))[SPIFFS_OBJ_IX_ENTRY(fs, map_spix)];
+ }
+
+ if (objix_data_pix == (spiffs_page_ix)-1) {
+ // reached end of object, abort
+ break;
+ }
+
+ map->map_buf[map_spix - map->start_spix] = objix_data_pix;
+ SPIFFS_DBG("map %04x:%04x (%04x--%04x) objix.spix:%04x to pix %04x\n",
+ fd->obj_id, map_spix - map->start_spix,
+ map->start_spix, map->end_spix,
+ objix->p_hdr.span_ix,
+ objix_data_pix);
+
+ map_spix++;
+ }
+}
+
+typedef struct {
+ spiffs_fd *fd;
+ uint32_t remaining_objix_pages_to_visit;
+ spiffs_span_ix map_objix_start_spix;
+ spiffs_span_ix map_objix_end_spix;
+} spiffs_ix_map_populate_state;
+
+static int32_t spiffs_populate_ix_map_v(
+ spiffs *fs,
+ spiffs_obj_id obj_id,
+ spiffs_block_ix bix,
+ int ix_entry,
+ const void *user_const_p,
+ void *user_var_p) {
+ (void)user_const_p;
+ int32_t res;
+ spiffs_ix_map_populate_state *state = (spiffs_ix_map_populate_state *)user_var_p;
+ spiffs_page_ix pix = SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, bix, ix_entry);
+
+ // load header to check it
+ spiffs_page_object_ix *objix = (spiffs_page_object_ix *)fs->work;
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ,
+ 0, SPIFFS_PAGE_TO_PADDR(fs, pix), sizeof(spiffs_page_object_ix), (uint8_t *)objix);
+ SPIFFS_CHECK_RES(res);
+ SPIFFS_VALIDATE_OBJIX(objix->p_hdr, obj_id, objix->p_hdr.span_ix);
+
+ // check if hdr is ok, and if objix range overlap with ix map range
+ if ((objix->p_hdr.flags & (SPIFFS_PH_FLAG_DELET | SPIFFS_PH_FLAG_FINAL | SPIFFS_PH_FLAG_IXDELE)) ==
+ (SPIFFS_PH_FLAG_DELET | SPIFFS_PH_FLAG_IXDELE) &&
+ objix->p_hdr.span_ix >= state->map_objix_start_spix &&
+ objix->p_hdr.span_ix <= state->map_objix_end_spix) {
+ // ok, load rest of object index
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ,
+ 0, SPIFFS_PAGE_TO_PADDR(fs, pix) + sizeof(spiffs_page_object_ix),
+ SPIFFS_CFG_LOG_PAGE_SZ(fs) - sizeof(spiffs_page_object_ix),
+ (uint8_t *)objix + sizeof(spiffs_page_object_ix));
+ SPIFFS_CHECK_RES(res);
+
+ spiffs_update_ix_map(fs, state->fd, objix->p_hdr.span_ix, objix);
+
+ state->remaining_objix_pages_to_visit--;
+ SPIFFS_DBG("map %04x (%04x--%04x) remaining objix pages %i\n",
+ state->fd->obj_id,
+ state->fd->ix_map->start_spix, state->fd->ix_map->end_spix,
+ state->remaining_objix_pages_to_visit);
+ }
+
+ if (res == SPIFFS_OK) {
+ res = state->remaining_objix_pages_to_visit ? SPIFFS_VIS_COUNTINUE : SPIFFS_VIS_END;
+ }
+ return res;
+}
+
+// populates index map, from vector entry start to vector entry end, inclusive
+int32_t spiffs_populate_ix_map(spiffs *fs, spiffs_fd *fd, uint32_t vec_entry_start, uint32_t vec_entry_end) {
+ int32_t res;
+ spiffs_ix_map *map = fd->ix_map;
+ spiffs_ix_map_populate_state state;
+ vec_entry_start = MIN((map->end_spix - map->start_spix + 1) - 1, (int32_t)vec_entry_start);
+ vec_entry_end = MAX((map->end_spix - map->start_spix + 1) - 1, (int32_t)vec_entry_end);
+ if (vec_entry_start > vec_entry_end) {
+ return SPIFFS_ERR_IX_MAP_BAD_RANGE;
+ }
+ state.map_objix_start_spix = SPIFFS_OBJ_IX_ENTRY_SPAN_IX(fs, map->start_spix + vec_entry_start);
+ state.map_objix_end_spix = SPIFFS_OBJ_IX_ENTRY_SPAN_IX(fs, map->start_spix + vec_entry_end);
+ state.remaining_objix_pages_to_visit =
+ state.map_objix_end_spix - state.map_objix_start_spix + 1;
+ state.fd = fd;
+
+ res = spiffs_obj_lu_find_entry_visitor(
+ fs,
+ SPIFFS_BLOCK_FOR_PAGE(fs, fd->objix_hdr_pix),
+ SPIFFS_OBJ_LOOKUP_ENTRY_FOR_PAGE(fs, fd->objix_hdr_pix),
+ SPIFFS_VIS_CHECK_ID,
+ fd->obj_id | SPIFFS_OBJ_ID_IX_FLAG,
+ spiffs_populate_ix_map_v,
+ 0,
+ &state,
+ 0,
+ 0);
+
+ if (res == SPIFFS_VIS_END) {
+ res = SPIFFS_OK;
+ }
+
+ return res;
+}
+
+#endif
+
+
+#if !SPIFFS_READ_ONLY
+// Allocates a free defined page with given obj_id
+// Occupies object lookup entry and page
+// data may be NULL; where only page header is stored, len and page_offs is ignored
+int32_t spiffs_page_allocate_data(
+ spiffs *fs,
+ spiffs_obj_id obj_id,
+ spiffs_page_header *ph,
+ uint8_t *data,
+ uint32_t len,
+ uint32_t page_offs,
+ uint8_t finalize,
+ spiffs_page_ix *pix) {
+ int32_t res = SPIFFS_OK;
+ spiffs_block_ix bix;
+ int entry;
+
+ // find free entry
+ res = spiffs_obj_lu_find_free(fs, fs->free_cursor_block_ix, fs->free_cursor_obj_lu_entry, &bix, &entry);
+ SPIFFS_CHECK_RES(res);
+
+ // occupy page in object lookup
+ res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_LU | SPIFFS_OP_C_UPDT,
+ 0, SPIFFS_BLOCK_TO_PADDR(fs, bix) + entry * sizeof(spiffs_obj_id), sizeof(spiffs_obj_id), (uint8_t*)&obj_id);
+ SPIFFS_CHECK_RES(res);
+
+ fs->stats_p_allocated++;
+
+ // write page header
+ ph->flags &= ~SPIFFS_PH_FLAG_USED;
+ res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_UPDT,
+ 0, SPIFFS_OBJ_LOOKUP_ENTRY_TO_PADDR(fs, bix, entry), sizeof(spiffs_page_header), (uint8_t*)ph);
+ SPIFFS_CHECK_RES(res);
+
+ // write page data
+ if (data) {
+ res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_UPDT,
+ 0,SPIFFS_OBJ_LOOKUP_ENTRY_TO_PADDR(fs, bix, entry) + sizeof(spiffs_page_header) + page_offs, len, data);
+ SPIFFS_CHECK_RES(res);
+ }
+
+ // finalize header if necessary
+ if (finalize && (ph->flags & SPIFFS_PH_FLAG_FINAL)) {
+ ph->flags &= ~SPIFFS_PH_FLAG_FINAL;
+ res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_UPDT,
+ 0, SPIFFS_OBJ_LOOKUP_ENTRY_TO_PADDR(fs, bix, entry) + offsetof(spiffs_page_header, flags),
+ sizeof(uint8_t),
+ (uint8_t *)&ph->flags);
+ SPIFFS_CHECK_RES(res);
+ }
+
+ // return written page
+ if (pix) {
+ *pix = SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, bix, entry);
+ }
+
+ return res;
+}
+#endif // !SPIFFS_READ_ONLY
+
+#if !SPIFFS_READ_ONLY
+// Moves a page from src to a free page and finalizes it. Updates page index. Page data is given in param page.
+// If page data is null, provided header is used for metainfo and page data is physically copied.
+int32_t spiffs_page_move(
+ spiffs *fs,
+ spiffs_file fh,
+ uint8_t *page_data,
+ spiffs_obj_id obj_id,
+ spiffs_page_header *page_hdr,
+ spiffs_page_ix src_pix,
+ spiffs_page_ix *dst_pix) {
+ int32_t res;
+ uint8_t was_final = 0;
+ spiffs_page_header *p_hdr;
+ spiffs_block_ix bix;
+ int entry;
+ spiffs_page_ix free_pix;
+
+ // find free entry
+ res = spiffs_obj_lu_find_free(fs, fs->free_cursor_block_ix, fs->free_cursor_obj_lu_entry, &bix, &entry);
+ SPIFFS_CHECK_RES(res);
+ free_pix = SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, bix, entry);
+
+ if (dst_pix) *dst_pix = free_pix;
+
+ p_hdr = page_data ? (spiffs_page_header *)page_data : page_hdr;
+ if (page_data) {
+ // got page data
+ was_final = (p_hdr->flags & SPIFFS_PH_FLAG_FINAL) == 0;
+ // write unfinalized page
+ p_hdr->flags |= SPIFFS_PH_FLAG_FINAL;
+ p_hdr->flags &= ~SPIFFS_PH_FLAG_USED;
+ res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_UPDT,
+ 0, SPIFFS_PAGE_TO_PADDR(fs, free_pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), page_data);
+ } else {
+ // copy page data
+ res = spiffs_phys_cpy(fs, fh, SPIFFS_PAGE_TO_PADDR(fs, free_pix), SPIFFS_PAGE_TO_PADDR(fs, src_pix), SPIFFS_CFG_LOG_PAGE_SZ(fs));
+ }
+ SPIFFS_CHECK_RES(res);
+
+ // mark entry in destination object lookup
+ res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_LU | SPIFFS_OP_C_UPDT,
+ 0, SPIFFS_BLOCK_TO_PADDR(fs, SPIFFS_BLOCK_FOR_PAGE(fs, free_pix)) + SPIFFS_OBJ_LOOKUP_ENTRY_FOR_PAGE(fs, free_pix) * sizeof(spiffs_page_ix),
+ sizeof(spiffs_obj_id),
+ (uint8_t *)&obj_id);
+ SPIFFS_CHECK_RES(res);
+
+ fs->stats_p_allocated++;
+
+ if (was_final) {
+ // mark finalized in destination page
+ p_hdr->flags &= ~(SPIFFS_PH_FLAG_FINAL | SPIFFS_PH_FLAG_USED);
+ res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_UPDT,
+ fh,
+ SPIFFS_PAGE_TO_PADDR(fs, free_pix) + offsetof(spiffs_page_header, flags),
+ sizeof(uint8_t),
+ (uint8_t *)&p_hdr->flags);
+ SPIFFS_CHECK_RES(res);
+ }
+ // mark source deleted
+ res = spiffs_page_delete(fs, src_pix);
+ return res;
+}
+#endif // !SPIFFS_READ_ONLY
+
+#if !SPIFFS_READ_ONLY
+// Deletes a page and removes it from object lookup.
+int32_t spiffs_page_delete(
+ spiffs *fs,
+ spiffs_page_ix pix) {
+ int32_t res;
+ spiffs_page_header hdr;
+ hdr.flags = 0xff & ~(SPIFFS_PH_FLAG_DELET | SPIFFS_PH_FLAG_USED);
+ // mark deleted entry in source object lookup
+ spiffs_obj_id d_obj_id = SPIFFS_OBJ_ID_DELETED;
+ res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_LU | SPIFFS_OP_C_DELE,
+ 0,
+ SPIFFS_BLOCK_TO_PADDR(fs, SPIFFS_BLOCK_FOR_PAGE(fs, pix)) + SPIFFS_OBJ_LOOKUP_ENTRY_FOR_PAGE(fs, pix) * sizeof(spiffs_page_ix),
+ sizeof(spiffs_obj_id),
+ (uint8_t *)&d_obj_id);
+ SPIFFS_CHECK_RES(res);
+
+ fs->stats_p_deleted++;
+ fs->stats_p_allocated--;
+
+ // mark deleted in source page
+ res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_DELE,
+ 0,
+ SPIFFS_PAGE_TO_PADDR(fs, pix) + offsetof(spiffs_page_header, flags),
+ sizeof(uint8_t),
+ (uint8_t *)&hdr.flags);
+
+ return res;
+}
+#endif // !SPIFFS_READ_ONLY
+
+#if !SPIFFS_READ_ONLY
+// Create an object index header page with empty index and undefined length
+int32_t spiffs_object_create(
+ spiffs *fs,
+ spiffs_obj_id obj_id,
+ const uint8_t name[SPIFFS_OBJ_NAME_LEN],
+ spiffs_obj_type type,
+ spiffs_page_ix *objix_hdr_pix) {
+ int32_t res = SPIFFS_OK;
+ spiffs_block_ix bix;
+ spiffs_page_object_ix_header oix_hdr;
+ int entry;
+
+ res = spiffs_gc_check(fs, SPIFFS_DATA_PAGE_SIZE(fs));
+ SPIFFS_CHECK_RES(res);
+
+ obj_id |= SPIFFS_OBJ_ID_IX_FLAG;
+
+ // find free entry
+ res = spiffs_obj_lu_find_free(fs, fs->free_cursor_block_ix, fs->free_cursor_obj_lu_entry, &bix, &entry);
+ SPIFFS_CHECK_RES(res);
+ SPIFFS_DBG("create: found free page @ %04x bix:%i entry:%i\n", SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, bix, entry), bix, entry);
+
+ // occupy page in object lookup
+ res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_LU | SPIFFS_OP_C_UPDT,
+ 0, SPIFFS_BLOCK_TO_PADDR(fs, bix) + entry * sizeof(spiffs_obj_id), sizeof(spiffs_obj_id), (uint8_t*)&obj_id);
+ SPIFFS_CHECK_RES(res);
+
+ fs->stats_p_allocated++;
+
+ // write empty object index page
+ oix_hdr.p_hdr.obj_id = obj_id;
+ oix_hdr.p_hdr.span_ix = 0;
+ oix_hdr.p_hdr.flags = 0xff & ~(SPIFFS_PH_FLAG_FINAL | SPIFFS_PH_FLAG_INDEX | SPIFFS_PH_FLAG_USED);
+ oix_hdr.type = type;
+ oix_hdr.size = SPIFFS_UNDEFINED_LEN; // keep ones so we can update later without wasting this page
+ strncpy((char*)&oix_hdr.name, (const char*)name, SPIFFS_OBJ_NAME_LEN);
+
+
+ // update page
+ res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_UPDT,
+ 0, SPIFFS_OBJ_LOOKUP_ENTRY_TO_PADDR(fs, bix, entry), sizeof(spiffs_page_object_ix_header), (uint8_t*)&oix_hdr);
+
+ SPIFFS_CHECK_RES(res);
+ spiffs_cb_object_event(fs, (spiffs_page_object_ix *)&oix_hdr,
+ SPIFFS_EV_IX_NEW, obj_id, 0, SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, bix, entry), SPIFFS_UNDEFINED_LEN);
+
+ if (objix_hdr_pix) {
+ *objix_hdr_pix = SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, bix, entry);
+ }
+
+ return res;
+}
+#endif // !SPIFFS_READ_ONLY
+
+#if !SPIFFS_READ_ONLY
+// update object index header with any combination of name/size/index
+// new_objix_hdr_data may be null, if so the object index header page is loaded
+// name may be null, if so name is not changed
+// size may be null, if so size is not changed
+int32_t spiffs_object_update_index_hdr(
+ spiffs *fs,
+ spiffs_fd *fd,
+ spiffs_obj_id obj_id,
+ spiffs_page_ix objix_hdr_pix,
+ uint8_t *new_objix_hdr_data,
+ const uint8_t name[SPIFFS_OBJ_NAME_LEN],
+ uint32_t size,
+ spiffs_page_ix *new_pix) {
+ int32_t res = SPIFFS_OK;
+ spiffs_page_object_ix_header *objix_hdr;
+ spiffs_page_ix new_objix_hdr_pix;
+
+ obj_id |= SPIFFS_OBJ_ID_IX_FLAG;
+
+ if (new_objix_hdr_data) {
+ // object index header page already given to us, no need to load it
+ objix_hdr = (spiffs_page_object_ix_header *)new_objix_hdr_data;
+ } else {
+ // read object index header page
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_READ,
+ fd->file_nbr, SPIFFS_PAGE_TO_PADDR(fs, objix_hdr_pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->work);
+ SPIFFS_CHECK_RES(res);
+ objix_hdr = (spiffs_page_object_ix_header *)fs->work;
+ }
+
+ SPIFFS_VALIDATE_OBJIX(objix_hdr->p_hdr, obj_id, 0);
+
+ // change name
+ if (name) {
+ strncpy((char*)objix_hdr->name, (const char*)name, SPIFFS_OBJ_NAME_LEN);
+ }
+ if (size) {
+ objix_hdr->size = size;
+ }
+
+ // move and update page
+ res = spiffs_page_move(fs, fd == 0 ? 0 : fd->file_nbr, (uint8_t*)objix_hdr, obj_id, 0, objix_hdr_pix, &new_objix_hdr_pix);
+
+ if (res == SPIFFS_OK) {
+ if (new_pix) {
+ *new_pix = new_objix_hdr_pix;
+ }
+ // callback on object index update
+ spiffs_cb_object_event(fs, (spiffs_page_object_ix *)objix_hdr,
+ new_objix_hdr_data ? SPIFFS_EV_IX_UPD : SPIFFS_EV_IX_UPD_HDR,
+ obj_id, objix_hdr->p_hdr.span_ix, new_objix_hdr_pix, objix_hdr->size);
+ if (fd) fd->objix_hdr_pix = new_objix_hdr_pix; // if this is not in the registered cluster
+ }
+
+ return res;
+}
+#endif // !SPIFFS_READ_ONLY
+
+void spiffs_cb_object_event(
+ spiffs *fs,
+ spiffs_page_object_ix *objix,
+ int ev,
+ spiffs_obj_id obj_id_raw,
+ spiffs_span_ix spix,
+ spiffs_page_ix new_pix,
+ uint32_t new_size) {
+#if SPIFFS_IX_MAP == 0
+ (void)objix;
+#endif
+ // update index caches in all file descriptors
+ spiffs_obj_id obj_id = obj_id_raw & ~SPIFFS_OBJ_ID_IX_FLAG;
+ uint32_t i;
+ spiffs_fd *fds = (spiffs_fd *)fs->fd_space;
+ for (i = 0; i < fs->fd_count; i++) {
+ spiffs_fd *cur_fd = &fds[i];
+#if SPIFFS_TEMPORAL_FD_CACHE
+ if (cur_fd->score == 0 || (cur_fd->obj_id & ~SPIFFS_OBJ_ID_IX_FLAG) != obj_id) continue;
+#else
+ if (cur_fd->file_nbr == 0 || (cur_fd->obj_id & ~SPIFFS_OBJ_ID_IX_FLAG) != obj_id) continue;
+#endif
+ if (spix == 0) {
+ if (ev != SPIFFS_EV_IX_DEL) {
+ SPIFFS_DBG(" callback: setting fd %i:%04x objix_hdr_pix to %04x, size:%i\n", cur_fd->file_nbr, cur_fd->obj_id, new_pix, new_size);
+ cur_fd->objix_hdr_pix = new_pix;
+ if (new_size != 0) {
+ cur_fd->size = new_size;
+ }
+ } else {
+ cur_fd->file_nbr = 0;
+ cur_fd->obj_id = SPIFFS_OBJ_ID_DELETED;
+ }
+ }
+ if (cur_fd->cursor_objix_spix == spix) {
+ if (ev != SPIFFS_EV_IX_DEL) {
+ SPIFFS_DBG(" callback: setting fd %i:%04x span:%04x objix_pix to %04x\n", cur_fd->file_nbr, cur_fd->obj_id, spix, new_pix);
+ cur_fd->cursor_objix_pix = new_pix;
+ } else {
+ cur_fd->cursor_objix_pix = 0;
+ }
+ }
+ }
+
+#if SPIFFS_IX_MAP
+
+ // update index maps
+ if (ev == SPIFFS_EV_IX_UPD || ev == SPIFFS_EV_IX_NEW) {
+ for (i = 0; i < fs->fd_count; i++) {
+ spiffs_fd *cur_fd = &fds[i];
+ // check fd opened, having ix map, match obj id
+ if (cur_fd->file_nbr == 0 ||
+ cur_fd->ix_map == 0 ||
+ (cur_fd->obj_id & ~SPIFFS_OBJ_ID_IX_FLAG) != obj_id) continue;
+ SPIFFS_DBG(" callback: map ix update fd %i:%04x span:%04x\n", cur_fd->file_nbr, cur_fd->obj_id, spix, new_pix);
+ spiffs_update_ix_map(fs, cur_fd, spix, objix);
+ }
+ }
+
+#endif
+
+ // callback to user if object index header
+ if (fs->file_cb_f && spix == 0 && (obj_id_raw & SPIFFS_OBJ_ID_IX_FLAG)) {
+ spiffs_fileop_type op;
+ if (ev == SPIFFS_EV_IX_NEW) {
+ op = SPIFFS_CB_CREATED;
+ } else if (ev == SPIFFS_EV_IX_UPD ||
+ ev == SPIFFS_EV_IX_MOV ||
+ ev == SPIFFS_EV_IX_UPD_HDR) {
+ op = SPIFFS_CB_UPDATED;
+ } else if (ev == SPIFFS_EV_IX_DEL) {
+ op = SPIFFS_CB_DELETED;
+ } else {
+ SPIFFS_DBG(" callback: WARNING unknown callback event %02x\n", ev);
+ return; // bail out
+ }
+ fs->file_cb_f(fs, op, obj_id, new_pix);
+ }
+}
+
+// Open object by id
+int32_t spiffs_object_open_by_id(
+ spiffs *fs,
+ spiffs_obj_id obj_id,
+ spiffs_fd *fd,
+ spiffs_flags flags,
+ spiffs_mode mode) {
+ int32_t res = SPIFFS_OK;
+ spiffs_page_ix pix;
+
+ res = spiffs_obj_lu_find_id_and_span(fs, obj_id | SPIFFS_OBJ_ID_IX_FLAG, 0, 0, &pix);
+ SPIFFS_CHECK_RES(res);
+
+ res = spiffs_object_open_by_page(fs, pix, fd, flags, mode);
+
+ return res;
+}
+
+// Open object by page index
+int32_t spiffs_object_open_by_page(
+ spiffs *fs,
+ spiffs_page_ix pix,
+ spiffs_fd *fd,
+ spiffs_flags flags,
+ spiffs_mode mode) {
+ (void)mode;
+ int32_t res = SPIFFS_OK;
+ spiffs_page_object_ix_header oix_hdr;
+ spiffs_obj_id obj_id;
+
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_READ,
+ fd->file_nbr, SPIFFS_PAGE_TO_PADDR(fs, pix), sizeof(spiffs_page_object_ix_header), (uint8_t *)&oix_hdr);
+ SPIFFS_CHECK_RES(res);
+
+ spiffs_block_ix bix = SPIFFS_BLOCK_FOR_PAGE(fs, pix);
+ int entry = SPIFFS_OBJ_LOOKUP_ENTRY_FOR_PAGE(fs, pix);
+
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU | SPIFFS_OP_C_READ,
+ 0, SPIFFS_BLOCK_TO_PADDR(fs, bix) + entry * sizeof(spiffs_obj_id), sizeof(spiffs_obj_id), (uint8_t *)&obj_id);
+
+ fd->fs = fs;
+ fd->objix_hdr_pix = pix;
+ fd->size = oix_hdr.size;
+ fd->offset = 0;
+ fd->cursor_objix_pix = pix;
+ fd->cursor_objix_spix = 0;
+ fd->obj_id = obj_id;
+ fd->flags = flags;
+
+ SPIFFS_VALIDATE_OBJIX(oix_hdr.p_hdr, fd->obj_id, 0);
+
+ SPIFFS_DBG("open: fd %i is obj id %04x\n", fd->file_nbr, fd->obj_id);
+
+ return res;
+}
+
+#if !SPIFFS_READ_ONLY
+// Append to object
+// keep current object index (header) page in fs->work buffer
+int32_t spiffs_object_append(spiffs_fd *fd, uint32_t offset, uint8_t *data, uint32_t len) {
+ spiffs *fs = fd->fs;
+ int32_t res = SPIFFS_OK;
+ uint32_t written = 0;
+
+ SPIFFS_DBG("append: %i bytes @ offs %i of size %i\n", len, offset, fd->size);
+
+ if (offset > fd->size) {
+ SPIFFS_DBG("append: offset reversed to size\n");
+ offset = fd->size;
+ }
+
+ res = spiffs_gc_check(fs, len + SPIFFS_DATA_PAGE_SIZE(fs)); // add an extra page of data worth for meta
+ if (res != SPIFFS_OK) {
+ SPIFFS_DBG("append: gc check fail %i\n", res);
+ }
+ SPIFFS_CHECK_RES(res);
+
+ spiffs_page_object_ix_header *objix_hdr = (spiffs_page_object_ix_header *)fs->work;
+ spiffs_page_object_ix *objix = (spiffs_page_object_ix *)fs->work;
+ spiffs_page_header p_hdr;
+
+ spiffs_span_ix cur_objix_spix = 0;
+ spiffs_span_ix prev_objix_spix = (spiffs_span_ix)-1;
+ spiffs_page_ix cur_objix_pix = fd->objix_hdr_pix;
+ spiffs_page_ix new_objix_hdr_page;
+
+ spiffs_span_ix data_spix = offset / SPIFFS_DATA_PAGE_SIZE(fs);
+ spiffs_page_ix data_page;
+ uint32_t page_offs = offset % SPIFFS_DATA_PAGE_SIZE(fs);
+
+ // write all data
+ while (res == SPIFFS_OK && written < len) {
+ // calculate object index page span index
+ cur_objix_spix = SPIFFS_OBJ_IX_ENTRY_SPAN_IX(fs, data_spix);
+
+ // handle storing and loading of object indices
+ if (cur_objix_spix != prev_objix_spix) {
+ // new object index page
+ // within this clause we return directly if something fails, object index mess-up
+ if (written > 0) {
+ // store previous object index page, unless first pass
+ SPIFFS_DBG("append: %04x store objix %04x:%04x, written %i\n", fd->obj_id,
+ cur_objix_pix, prev_objix_spix, written);
+ if (prev_objix_spix == 0) {
+ // this is an update to object index header page
+ objix_hdr->size = offset+written;
+ if (offset == 0) {
+ // was an empty object, update same page (size was 0xffffffff)
+ res = spiffs_page_index_check(fs, fd, cur_objix_pix, 0);
+ SPIFFS_CHECK_RES(res);
+ res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_UPDT,
+ fd->file_nbr, SPIFFS_PAGE_TO_PADDR(fs, cur_objix_pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->work);
+ SPIFFS_CHECK_RES(res);
+ } else {
+ // was a nonempty object, update to new page
+ res = spiffs_object_update_index_hdr(fs, fd, fd->obj_id,
+ fd->objix_hdr_pix, fs->work, 0, offset+written, &new_objix_hdr_page);
+ SPIFFS_CHECK_RES(res);
+ SPIFFS_DBG("append: %04x store new objix_hdr, %04x:%04x, written %i\n", fd->obj_id,
+ new_objix_hdr_page, 0, written);
+ }
+ } else {
+ // this is an update to an object index page
+ res = spiffs_page_index_check(fs, fd, cur_objix_pix, prev_objix_spix);
+ SPIFFS_CHECK_RES(res);
+
+ res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_UPDT,
+ fd->file_nbr, SPIFFS_PAGE_TO_PADDR(fs, cur_objix_pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->work);
+ SPIFFS_CHECK_RES(res);
+ spiffs_cb_object_event(fs, (spiffs_page_object_ix *)fs->work,
+ SPIFFS_EV_IX_UPD,fd->obj_id, objix->p_hdr.span_ix, cur_objix_pix, 0);
+ // update length in object index header page
+ res = spiffs_object_update_index_hdr(fs, fd, fd->obj_id,
+ fd->objix_hdr_pix, 0, 0, offset+written, &new_objix_hdr_page);
+ SPIFFS_CHECK_RES(res);
+ SPIFFS_DBG("append: %04x store new size I %i in objix_hdr, %04x:%04x, written %i\n", fd->obj_id,
+ offset+written, new_objix_hdr_page, 0, written);
+ }
+ fd->size = offset+written;
+ fd->offset = offset+written;
+ }
+
+ // create or load new object index page
+ if (cur_objix_spix == 0) {
+ // load object index header page, must always exist
+ SPIFFS_DBG("append: %04x load objixhdr page %04x:%04x\n", fd->obj_id, cur_objix_pix, cur_objix_spix);
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_READ,
+ fd->file_nbr, SPIFFS_PAGE_TO_PADDR(fs, cur_objix_pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->work);
+ SPIFFS_CHECK_RES(res);
+ SPIFFS_VALIDATE_OBJIX(objix_hdr->p_hdr, fd->obj_id, cur_objix_spix);
+ } else {
+ spiffs_span_ix len_objix_spix = SPIFFS_OBJ_IX_ENTRY_SPAN_IX(fs, (fd->size-1)/SPIFFS_DATA_PAGE_SIZE(fs));
+ // on subsequent passes, create a new object index page
+ if (written > 0 || cur_objix_spix > len_objix_spix) {
+ p_hdr.obj_id = fd->obj_id | SPIFFS_OBJ_ID_IX_FLAG;
+ p_hdr.span_ix = cur_objix_spix;
+ p_hdr.flags = 0xff & ~(SPIFFS_PH_FLAG_FINAL | SPIFFS_PH_FLAG_INDEX);
+ res = spiffs_page_allocate_data(fs, fd->obj_id | SPIFFS_OBJ_ID_IX_FLAG,
+ &p_hdr, 0, 0, 0, 1, &cur_objix_pix);
+ SPIFFS_CHECK_RES(res);
+ // quick "load" of new object index page
+ memset(fs->work, 0xff, SPIFFS_CFG_LOG_PAGE_SZ(fs));
+ memcpy(fs->work, &p_hdr, sizeof(spiffs_page_header));
+ spiffs_cb_object_event(fs, (spiffs_page_object_ix *)fs->work,
+ SPIFFS_EV_IX_NEW, fd->obj_id, cur_objix_spix, cur_objix_pix, 0);
+ SPIFFS_DBG("append: %04x create objix page, %04x:%04x, written %i\n", fd->obj_id
+ , cur_objix_pix, cur_objix_spix, written);
+ } else {
+ // on first pass, we load existing object index page
+ spiffs_page_ix pix;
+ SPIFFS_DBG("append: %04x find objix span_ix:%04x\n", fd->obj_id, cur_objix_spix);
+ if (fd->cursor_objix_spix == cur_objix_spix) {
+ pix = fd->cursor_objix_pix;
+ } else {
+ res = spiffs_obj_lu_find_id_and_span(fs, fd->obj_id | SPIFFS_OBJ_ID_IX_FLAG, cur_objix_spix, 0, &pix);
+ SPIFFS_CHECK_RES(res);
+ }
+ SPIFFS_DBG("append: %04x found object index at page %04x [fd size %i]\n", fd->obj_id, pix, fd->size);
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_READ,
+ fd->file_nbr, SPIFFS_PAGE_TO_PADDR(fs, pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->work);
+ SPIFFS_CHECK_RES(res);
+ SPIFFS_VALIDATE_OBJIX(objix_hdr->p_hdr, fd->obj_id, cur_objix_spix);
+ cur_objix_pix = pix;
+ }
+ fd->cursor_objix_pix = cur_objix_pix;
+ fd->cursor_objix_spix = cur_objix_spix;
+ fd->offset = offset+written;
+ fd->size = offset+written;
+ }
+ prev_objix_spix = cur_objix_spix;
+ }
+
+ // write data
+ uint32_t to_write = MIN(len-written, SPIFFS_DATA_PAGE_SIZE(fs) - page_offs);
+ if (page_offs == 0) {
+ // at beginning of a page, allocate and write a new page of data
+ p_hdr.obj_id = fd->obj_id & ~SPIFFS_OBJ_ID_IX_FLAG;
+ p_hdr.span_ix = data_spix;
+ p_hdr.flags = 0xff & ~(SPIFFS_PH_FLAG_FINAL); // finalize immediately
+ res = spiffs_page_allocate_data(fs, fd->obj_id & ~SPIFFS_OBJ_ID_IX_FLAG,
+ &p_hdr, &data[written], to_write, page_offs, 1, &data_page);
+ SPIFFS_DBG("append: %04x store new data page, %04x:%04x offset:%i, len %i, written %i\n", fd->obj_id,
+ data_page, data_spix, page_offs, to_write, written);
+ } else {
+ // append to existing page, fill out free data in existing page
+ if (cur_objix_spix == 0) {
+ // get data page from object index header page
+ data_page = ((spiffs_page_ix*)((uint8_t *)objix_hdr + sizeof(spiffs_page_object_ix_header)))[data_spix];
+ } else {
+ // get data page from object index page
+ data_page = ((spiffs_page_ix*)((uint8_t *)objix + sizeof(spiffs_page_object_ix)))[SPIFFS_OBJ_IX_ENTRY(fs, data_spix)];
+ }
+
+ res = spiffs_page_data_check(fs, fd, data_page, data_spix);
+ SPIFFS_CHECK_RES(res);
+
+ res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_UPDT,
+ fd->file_nbr, SPIFFS_PAGE_TO_PADDR(fs, data_page) + sizeof(spiffs_page_header) + page_offs, to_write, &data[written]);
+ SPIFFS_DBG("append: %04x store to existing data page, %04x:%04x offset:%i, len %i, written %i\n", fd->obj_id
+ , data_page, data_spix, page_offs, to_write, written);
+ }
+
+ if (res != SPIFFS_OK) break;
+
+ // update memory representation of object index page with new data page
+ if (cur_objix_spix == 0) {
+ // update object index header page
+ ((spiffs_page_ix*)((uint8_t *)objix_hdr + sizeof(spiffs_page_object_ix_header)))[data_spix] = data_page;
+ SPIFFS_DBG("append: %04x wrote page %04x to objix_hdr entry %02x in mem\n", fd->obj_id
+ , data_page, data_spix);
+ objix_hdr->size = offset+written;
+ } else {
+ // update object index page
+ ((spiffs_page_ix*)((uint8_t *)objix + sizeof(spiffs_page_object_ix)))[SPIFFS_OBJ_IX_ENTRY(fs, data_spix)] = data_page;
+ SPIFFS_DBG("append: %04x wrote page %04x to objix entry %02x in mem\n", fd->obj_id
+ , data_page, SPIFFS_OBJ_IX_ENTRY(fs, data_spix));
+ }
+
+ // update internals
+ page_offs = 0;
+ data_spix++;
+ written += to_write;
+ } // while all data
+
+ fd->size = offset+written;
+ fd->offset = offset+written;
+ fd->cursor_objix_pix = cur_objix_pix;
+ fd->cursor_objix_spix = cur_objix_spix;
+
+ // finalize updated object indices
+ int32_t res2 = SPIFFS_OK;
+ if (cur_objix_spix != 0) {
+ // wrote beyond object index header page
+ // write last modified object index page, unless object header index page
+ SPIFFS_DBG("append: %04x store objix page, %04x:%04x, written %i\n", fd->obj_id,
+ cur_objix_pix, cur_objix_spix, written);
+
+ res2 = spiffs_page_index_check(fs, fd, cur_objix_pix, cur_objix_spix);
+ SPIFFS_CHECK_RES(res2);
+
+ res2 = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_UPDT,
+ fd->file_nbr, SPIFFS_PAGE_TO_PADDR(fs, cur_objix_pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->work);
+ SPIFFS_CHECK_RES(res2);
+ spiffs_cb_object_event(fs, (spiffs_page_object_ix *)fs->work,
+ SPIFFS_EV_IX_UPD, fd->obj_id, objix->p_hdr.span_ix, cur_objix_pix, 0);
+
+ // update size in object header index page
+ res2 = spiffs_object_update_index_hdr(fs, fd, fd->obj_id,
+ fd->objix_hdr_pix, 0, 0, offset+written, &new_objix_hdr_page);
+ SPIFFS_DBG("append: %04x store new size II %i in objix_hdr, %04x:%04x, written %i, res %i\n", fd->obj_id
+ , offset+written, new_objix_hdr_page, 0, written, res2);
+ SPIFFS_CHECK_RES(res2);
+ } else {
+ // wrote within object index header page
+ if (offset == 0) {
+ // wrote to empty object - simply update size and write whole page
+ objix_hdr->size = offset+written;
+ SPIFFS_DBG("append: %04x store fresh objix_hdr page, %04x:%04x, written %i\n", fd->obj_id
+ , cur_objix_pix, cur_objix_spix, written);
+
+ res2 = spiffs_page_index_check(fs, fd, cur_objix_pix, cur_objix_spix);
+ SPIFFS_CHECK_RES(res2);
+
+ res2 = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_UPDT,
+ fd->file_nbr, SPIFFS_PAGE_TO_PADDR(fs, cur_objix_pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->work);
+ SPIFFS_CHECK_RES(res2);
+ // callback on object index update
+ spiffs_cb_object_event(fs, (spiffs_page_object_ix *)fs->work,
+ SPIFFS_EV_IX_UPD_HDR, fd->obj_id, objix_hdr->p_hdr.span_ix, cur_objix_pix, objix_hdr->size);
+ } else {
+ // modifying object index header page, update size and make new copy
+ res2 = spiffs_object_update_index_hdr(fs, fd, fd->obj_id,
+ fd->objix_hdr_pix, fs->work, 0, offset+written, &new_objix_hdr_page);
+ SPIFFS_DBG("append: %04x store modified objix_hdr page, %04x:%04x, written %i\n", fd->obj_id
+ , new_objix_hdr_page, 0, written);
+ SPIFFS_CHECK_RES(res2);
+ }
+ }
+
+ return res;
+} // spiffs_object_append
+#endif // !SPIFFS_READ_ONLY
+
+#if !SPIFFS_READ_ONLY
+// Modify object
+// keep current object index (header) page in fs->work buffer
+int32_t spiffs_object_modify(spiffs_fd *fd, uint32_t offset, uint8_t *data, uint32_t len) {
+ spiffs *fs = fd->fs;
+ int32_t res = SPIFFS_OK;
+ uint32_t written = 0;
+
+ res = spiffs_gc_check(fs, len + SPIFFS_DATA_PAGE_SIZE(fs));
+ SPIFFS_CHECK_RES(res);
+
+ spiffs_page_object_ix_header *objix_hdr = (spiffs_page_object_ix_header *)fs->work;
+ spiffs_page_object_ix *objix = (spiffs_page_object_ix *)fs->work;
+ spiffs_page_header p_hdr;
+
+ spiffs_span_ix cur_objix_spix = 0;
+ spiffs_span_ix prev_objix_spix = (spiffs_span_ix)-1;
+ spiffs_page_ix cur_objix_pix = fd->objix_hdr_pix;
+ spiffs_page_ix new_objix_hdr_pix;
+
+ spiffs_span_ix data_spix = offset / SPIFFS_DATA_PAGE_SIZE(fs);
+ spiffs_page_ix data_pix;
+ uint32_t page_offs = offset % SPIFFS_DATA_PAGE_SIZE(fs);
+
+
+ // write all data
+ while (res == SPIFFS_OK && written < len) {
+ // calculate object index page span index
+ cur_objix_spix = SPIFFS_OBJ_IX_ENTRY_SPAN_IX(fs, data_spix);
+
+ // handle storing and loading of object indices
+ if (cur_objix_spix != prev_objix_spix) {
+ // new object index page
+ // within this clause we return directly if something fails, object index mess-up
+ if (written > 0) {
+ // store previous object index (header) page, unless first pass
+ if (prev_objix_spix == 0) {
+ // store previous object index header page
+ res = spiffs_object_update_index_hdr(fs, fd, fd->obj_id,
+ fd->objix_hdr_pix, fs->work, 0, 0, &new_objix_hdr_pix);
+ SPIFFS_DBG("modify: store modified objix_hdr page, %04x:%04x, written %i\n", new_objix_hdr_pix, 0, written);
+ SPIFFS_CHECK_RES(res);
+ } else {
+ // store new version of previous object index page
+ spiffs_page_ix new_objix_pix;
+
+ res = spiffs_page_index_check(fs, fd, cur_objix_pix, prev_objix_spix);
+ SPIFFS_CHECK_RES(res);
+
+ res = spiffs_page_move(fs, fd->file_nbr, (uint8_t*)objix, fd->obj_id, 0, cur_objix_pix, &new_objix_pix);
+ SPIFFS_DBG("modify: store previous modified objix page, %04x:%04x, written %i\n", new_objix_pix, objix->p_hdr.span_ix, written);
+ SPIFFS_CHECK_RES(res);
+ spiffs_cb_object_event(fs, (spiffs_page_object_ix *)objix,
+ SPIFFS_EV_IX_UPD, fd->obj_id, objix->p_hdr.span_ix, new_objix_pix, 0);
+ }
+ }
+
+ // load next object index page
+ if (cur_objix_spix == 0) {
+ // load object index header page, must exist
+ SPIFFS_DBG("modify: load objixhdr page %04x:%04x\n", cur_objix_pix, cur_objix_spix);
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_READ,
+ fd->file_nbr, SPIFFS_PAGE_TO_PADDR(fs, cur_objix_pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->work);
+ SPIFFS_CHECK_RES(res);
+ SPIFFS_VALIDATE_OBJIX(objix_hdr->p_hdr, fd->obj_id, cur_objix_spix);
+ } else {
+ // load existing object index page on first pass
+ spiffs_page_ix pix;
+ SPIFFS_DBG("modify: find objix span_ix:%04x\n", cur_objix_spix);
+ if (fd->cursor_objix_spix == cur_objix_spix) {
+ pix = fd->cursor_objix_pix;
+ } else {
+ res = spiffs_obj_lu_find_id_and_span(fs, fd->obj_id | SPIFFS_OBJ_ID_IX_FLAG, cur_objix_spix, 0, &pix);
+ SPIFFS_CHECK_RES(res);
+ }
+ SPIFFS_DBG("modify: found object index at page %04x\n", pix);
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_READ,
+ fd->file_nbr, SPIFFS_PAGE_TO_PADDR(fs, pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->work);
+ SPIFFS_CHECK_RES(res);
+ SPIFFS_VALIDATE_OBJIX(objix_hdr->p_hdr, fd->obj_id, cur_objix_spix);
+ cur_objix_pix = pix;
+ }
+ fd->cursor_objix_pix = cur_objix_pix;
+ fd->cursor_objix_spix = cur_objix_spix;
+ fd->offset = offset+written;
+ prev_objix_spix = cur_objix_spix;
+ }
+
+ // write partial data
+ uint32_t to_write = MIN(len-written, SPIFFS_DATA_PAGE_SIZE(fs) - page_offs);
+ spiffs_page_ix orig_data_pix;
+ if (cur_objix_spix == 0) {
+ // get data page from object index header page
+ orig_data_pix = ((spiffs_page_ix*)((uint8_t *)objix_hdr + sizeof(spiffs_page_object_ix_header)))[data_spix];
+ } else {
+ // get data page from object index page
+ orig_data_pix = ((spiffs_page_ix*)((uint8_t *)objix + sizeof(spiffs_page_object_ix)))[SPIFFS_OBJ_IX_ENTRY(fs, data_spix)];
+ }
+
+ p_hdr.obj_id = fd->obj_id & ~SPIFFS_OBJ_ID_IX_FLAG;
+ p_hdr.span_ix = data_spix;
+ p_hdr.flags = 0xff;
+ if (page_offs == 0 && to_write == SPIFFS_DATA_PAGE_SIZE(fs)) {
+ // a full page, allocate and write a new page of data
+ res = spiffs_page_allocate_data(fs, fd->obj_id & ~SPIFFS_OBJ_ID_IX_FLAG,
+ &p_hdr, &data[written], to_write, page_offs, 1, &data_pix);
+ SPIFFS_DBG("modify: store new data page, %04x:%04x offset:%i, len %i, written %i\n", data_pix, data_spix, page_offs, to_write, written);
+ } else {
+ // write to existing page, allocate new and copy unmodified data
+
+ res = spiffs_page_data_check(fs, fd, orig_data_pix, data_spix);
+ SPIFFS_CHECK_RES(res);
+
+ res = spiffs_page_allocate_data(fs, fd->obj_id & ~SPIFFS_OBJ_ID_IX_FLAG,
+ &p_hdr, 0, 0, 0, 0, &data_pix);
+ if (res != SPIFFS_OK) break;
+
+ // copy unmodified data
+ if (page_offs > 0) {
+ // before modification
+ res = spiffs_phys_cpy(fs, fd->file_nbr,
+ SPIFFS_PAGE_TO_PADDR(fs, data_pix) + sizeof(spiffs_page_header),
+ SPIFFS_PAGE_TO_PADDR(fs, orig_data_pix) + sizeof(spiffs_page_header),
+ page_offs);
+ if (res != SPIFFS_OK) break;
+ }
+ if (page_offs + to_write < SPIFFS_DATA_PAGE_SIZE(fs)) {
+ // after modification
+ res = spiffs_phys_cpy(fs, fd->file_nbr,
+ SPIFFS_PAGE_TO_PADDR(fs, data_pix) + sizeof(spiffs_page_header) + page_offs + to_write,
+ SPIFFS_PAGE_TO_PADDR(fs, orig_data_pix) + sizeof(spiffs_page_header) + page_offs + to_write,
+ SPIFFS_DATA_PAGE_SIZE(fs) - (page_offs + to_write));
+ if (res != SPIFFS_OK) break;
+ }
+
+ res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_UPDT,
+ fd->file_nbr,
+ SPIFFS_PAGE_TO_PADDR(fs, data_pix) + sizeof(spiffs_page_header) + page_offs, to_write, &data[written]);
+ if (res != SPIFFS_OK) break;
+ p_hdr.flags &= ~SPIFFS_PH_FLAG_FINAL;
+ res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_UPDT,
+ fd->file_nbr,
+ SPIFFS_PAGE_TO_PADDR(fs, data_pix) + offsetof(spiffs_page_header, flags),
+ sizeof(uint8_t),
+ (uint8_t *)&p_hdr.flags);
+ if (res != SPIFFS_OK) break;
+
+ SPIFFS_DBG("modify: store to existing data page, src:%04x, dst:%04x:%04x offset:%i, len %i, written %i\n", orig_data_pix, data_pix, data_spix, page_offs, to_write, written);
+ }
+
+ // delete original data page
+ res = spiffs_page_delete(fs, orig_data_pix);
+ if (res != SPIFFS_OK) break;
+ // update memory representation of object index page with new data page
+ if (cur_objix_spix == 0) {
+ // update object index header page
+ ((spiffs_page_ix*)((uint8_t *)objix_hdr + sizeof(spiffs_page_object_ix_header)))[data_spix] = data_pix;
+ SPIFFS_DBG("modify: wrote page %04x to objix_hdr entry %02x in mem\n", data_pix, data_spix);
+ } else {
+ // update object index page
+ ((spiffs_page_ix*)((uint8_t *)objix + sizeof(spiffs_page_object_ix)))[SPIFFS_OBJ_IX_ENTRY(fs, data_spix)] = data_pix;
+ SPIFFS_DBG("modify: wrote page %04x to objix entry %02x in mem\n", data_pix, SPIFFS_OBJ_IX_ENTRY(fs, data_spix));
+ }
+
+ // update internals
+ page_offs = 0;
+ data_spix++;
+ written += to_write;
+ } // while all data
+
+ fd->offset = offset+written;
+ fd->cursor_objix_pix = cur_objix_pix;
+ fd->cursor_objix_spix = cur_objix_spix;
+
+ // finalize updated object indices
+ int32_t res2 = SPIFFS_OK;
+ if (cur_objix_spix != 0) {
+ // wrote beyond object index header page
+ // write last modified object index page
+ // move and update page
+ spiffs_page_ix new_objix_pix;
+
+ res2 = spiffs_page_index_check(fs, fd, cur_objix_pix, cur_objix_spix);
+ SPIFFS_CHECK_RES(res2);
+
+ res2 = spiffs_page_move(fs, fd->file_nbr, (uint8_t*)objix, fd->obj_id, 0, cur_objix_pix, &new_objix_pix);
+ SPIFFS_DBG("modify: store modified objix page, %04x:%04x, written %i\n", new_objix_pix, cur_objix_spix, written);
+ fd->cursor_objix_pix = new_objix_pix;
+ fd->cursor_objix_spix = cur_objix_spix;
+ SPIFFS_CHECK_RES(res2);
+ spiffs_cb_object_event(fs, (spiffs_page_object_ix *)objix,
+ SPIFFS_EV_IX_UPD, fd->obj_id, objix->p_hdr.span_ix, new_objix_pix, 0);
+
+ } else {
+ // wrote within object index header page
+ res2 = spiffs_object_update_index_hdr(fs, fd, fd->obj_id,
+ fd->objix_hdr_pix, fs->work, 0, 0, &new_objix_hdr_pix);
+ SPIFFS_DBG("modify: store modified objix_hdr page, %04x:%04x, written %i\n", new_objix_hdr_pix, 0, written);
+ SPIFFS_CHECK_RES(res2);
+ }
+
+ return res;
+} // spiffs_object_modify
+#endif // !SPIFFS_READ_ONLY
+
+static int32_t spiffs_object_find_object_index_header_by_name_v(
+ spiffs *fs,
+ spiffs_obj_id obj_id,
+ spiffs_block_ix bix,
+ int ix_entry,
+ const void *user_const_p,
+ void *user_var_p) {
+ (void)user_var_p;
+ int32_t res;
+ spiffs_page_object_ix_header objix_hdr;
+ spiffs_page_ix pix = SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, bix, ix_entry);
+ if (obj_id == SPIFFS_OBJ_ID_FREE || obj_id == SPIFFS_OBJ_ID_DELETED ||
+ (obj_id & SPIFFS_OBJ_ID_IX_FLAG) == 0) {
+ return SPIFFS_VIS_COUNTINUE;
+ }
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ,
+ 0, SPIFFS_PAGE_TO_PADDR(fs, pix), sizeof(spiffs_page_object_ix_header), (uint8_t *)&objix_hdr);
+ SPIFFS_CHECK_RES(res);
+ if (objix_hdr.p_hdr.span_ix == 0 &&
+ (objix_hdr.p_hdr.flags & (SPIFFS_PH_FLAG_DELET | SPIFFS_PH_FLAG_FINAL | SPIFFS_PH_FLAG_IXDELE)) ==
+ (SPIFFS_PH_FLAG_DELET | SPIFFS_PH_FLAG_IXDELE)) {
+ if (strcmp((const char*)user_const_p, (char*)objix_hdr.name) == 0) {
+ return SPIFFS_OK;
+ }
+ }
+
+ return SPIFFS_VIS_COUNTINUE;
+}
+
+// Finds object index header page by name
+int32_t spiffs_object_find_object_index_header_by_name(
+ spiffs *fs,
+ const uint8_t name[SPIFFS_OBJ_NAME_LEN],
+ spiffs_page_ix *pix) {
+ int32_t res;
+ spiffs_block_ix bix;
+ int entry;
+
+ res = spiffs_obj_lu_find_entry_visitor(fs,
+ fs->cursor_block_ix,
+ fs->cursor_obj_lu_entry,
+ 0,
+ 0,
+ spiffs_object_find_object_index_header_by_name_v,
+ name,
+ 0,
+ &bix,
+ &entry);
+
+ if (res == SPIFFS_VIS_END) {
+ res = SPIFFS_ERR_NOT_FOUND;
+ }
+ SPIFFS_CHECK_RES(res);
+
+ if (pix) {
+ *pix = SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, bix, entry);
+ }
+
+ fs->cursor_block_ix = bix;
+ fs->cursor_obj_lu_entry = entry;
+
+ return res;
+}
+
+#if !SPIFFS_READ_ONLY
+// Truncates object to new size. If new size is null, object may be removed totally
+int32_t spiffs_object_truncate(
+ spiffs_fd *fd,
+ uint32_t new_size,
+ uint8_t remove_full) {
+ int32_t res = SPIFFS_OK;
+ spiffs *fs = fd->fs;
+
+ if ((fd->size == SPIFFS_UNDEFINED_LEN || fd->size == 0) && !remove_full) {
+ // no op
+ return res;
+ }
+
+ // need 2 pages if not removing: object index page + possibly chopped data page
+ if (remove_full == 0) {
+ res = spiffs_gc_check(fs, SPIFFS_DATA_PAGE_SIZE(fs) * 2);
+ SPIFFS_CHECK_RES(res);
+ }
+
+ spiffs_page_ix objix_pix = fd->objix_hdr_pix;
+ spiffs_span_ix data_spix = (fd->size > 0 ? fd->size-1 : 0) / SPIFFS_DATA_PAGE_SIZE(fs);
+ uint32_t cur_size = fd->size == (uint32_t)SPIFFS_UNDEFINED_LEN ? 0 : fd->size ;
+ spiffs_span_ix cur_objix_spix = 0;
+ spiffs_span_ix prev_objix_spix = (spiffs_span_ix)-1;
+ spiffs_page_object_ix_header *objix_hdr = (spiffs_page_object_ix_header *)fs->work;
+ spiffs_page_object_ix *objix = (spiffs_page_object_ix *)fs->work;
+ spiffs_page_ix data_pix;
+ spiffs_page_ix new_objix_hdr_pix;
+
+ // before truncating, check if object is to be fully removed and mark this
+ if (remove_full && new_size == 0) {
+ uint8_t flags = ~( SPIFFS_PH_FLAG_USED | SPIFFS_PH_FLAG_INDEX | SPIFFS_PH_FLAG_FINAL | SPIFFS_PH_FLAG_IXDELE);
+ res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_UPDT,
+ fd->file_nbr, SPIFFS_PAGE_TO_PADDR(fs, fd->objix_hdr_pix) + offsetof(spiffs_page_header, flags),
+ sizeof(uint8_t),
+ (uint8_t *)&flags);
+ SPIFFS_CHECK_RES(res);
+ }
+
+ // delete from end of object until desired len is reached
+ while (cur_size > new_size) {
+ cur_objix_spix = SPIFFS_OBJ_IX_ENTRY_SPAN_IX(fs, data_spix);
+
+ // put object index for current data span index in work buffer
+ if (prev_objix_spix != cur_objix_spix) {
+ if (prev_objix_spix != (spiffs_span_ix)-1) {
+ // remove previous object index page
+ SPIFFS_DBG("truncate: delete objix page %04x:%04x\n", objix_pix, prev_objix_spix);
+
+ res = spiffs_page_index_check(fs, fd, objix_pix, prev_objix_spix);
+ SPIFFS_CHECK_RES(res);
+
+ res = spiffs_page_delete(fs, objix_pix);
+ SPIFFS_CHECK_RES(res);
+ spiffs_cb_object_event(fs, (spiffs_page_object_ix *)0,
+ SPIFFS_EV_IX_DEL, fd->obj_id, objix->p_hdr.span_ix, objix_pix, 0);
+ if (prev_objix_spix > 0) {
+ // Update object index header page, unless we totally want to remove the file.
+ // If fully removing, we're not keeping consistency as good as when storing the header between chunks,
+ // would we be aborted. But when removing full files, a crammed system may otherwise
+ // report ERR_FULL a la windows. We cannot have that.
+ // Hence, take the risk - if aborted, a file check would free the lost pages and mend things
+ // as the file is marked as fully deleted in the beginning.
+ if (remove_full == 0) {
+ SPIFFS_DBG("truncate: update objix hdr page %04x:%04x to size %i\n", fd->objix_hdr_pix, prev_objix_spix, cur_size);
+ res = spiffs_object_update_index_hdr(fs, fd, fd->obj_id,
+ fd->objix_hdr_pix, 0, 0, cur_size, &new_objix_hdr_pix);
+ SPIFFS_CHECK_RES(res);
+ }
+ fd->size = cur_size;
+ }
+ }
+ // load current object index (header) page
+ if (cur_objix_spix == 0) {
+ objix_pix = fd->objix_hdr_pix;
+ } else {
+ res = spiffs_obj_lu_find_id_and_span(fs, fd->obj_id | SPIFFS_OBJ_ID_IX_FLAG, cur_objix_spix, 0, &objix_pix);
+ SPIFFS_CHECK_RES(res);
+ }
+
+ SPIFFS_DBG("truncate: load objix page %04x:%04x for data spix:%04x\n", objix_pix, cur_objix_spix, data_spix);
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_READ,
+ fd->file_nbr, SPIFFS_PAGE_TO_PADDR(fs, objix_pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->work);
+ SPIFFS_CHECK_RES(res);
+ SPIFFS_VALIDATE_OBJIX(objix_hdr->p_hdr, fd->obj_id, cur_objix_spix);
+ fd->cursor_objix_pix = objix_pix;
+ fd->cursor_objix_spix = cur_objix_spix;
+ fd->offset = cur_size;
+
+ prev_objix_spix = cur_objix_spix;
+ }
+
+ if (cur_objix_spix == 0) {
+ // get data page from object index header page
+ data_pix = ((spiffs_page_ix*)((uint8_t *)objix_hdr + sizeof(spiffs_page_object_ix_header)))[data_spix];
+ ((spiffs_page_ix*)((uint8_t *)objix_hdr + sizeof(spiffs_page_object_ix_header)))[data_spix] = SPIFFS_OBJ_ID_FREE;
+ } else {
+ // get data page from object index page
+ data_pix = ((spiffs_page_ix*)((uint8_t *)objix + sizeof(spiffs_page_object_ix)))[SPIFFS_OBJ_IX_ENTRY(fs, data_spix)];
+ ((spiffs_page_ix*)((uint8_t *)objix + sizeof(spiffs_page_object_ix)))[SPIFFS_OBJ_IX_ENTRY(fs, data_spix)] = SPIFFS_OBJ_ID_FREE;
+ }
+
+ SPIFFS_DBG("truncate: got data pix %04x\n", data_pix);
+
+ if (new_size == 0 || remove_full || cur_size - new_size >= SPIFFS_DATA_PAGE_SIZE(fs)) {
+ // delete full data page
+ res = spiffs_page_data_check(fs, fd, data_pix, data_spix);
+ if (res != SPIFFS_ERR_DELETED && res != SPIFFS_OK && res != SPIFFS_ERR_INDEX_REF_FREE) {
+ SPIFFS_DBG("truncate: err validating data pix %i\n", res);
+ break;
+ }
+
+ if (res == SPIFFS_OK) {
+ res = spiffs_page_delete(fs, data_pix);
+ if (res != SPIFFS_OK) {
+ SPIFFS_DBG("truncate: err deleting data pix %i\n", res);
+ break;
+ }
+ } else if (res == SPIFFS_ERR_DELETED || res == SPIFFS_ERR_INDEX_REF_FREE) {
+ res = SPIFFS_OK;
+ }
+
+ // update current size
+ if (cur_size % SPIFFS_DATA_PAGE_SIZE(fs) == 0) {
+ cur_size -= SPIFFS_DATA_PAGE_SIZE(fs);
+ } else {
+ cur_size -= cur_size % SPIFFS_DATA_PAGE_SIZE(fs);
+ }
+ fd->size = cur_size;
+ fd->offset = cur_size;
+ SPIFFS_DBG("truncate: delete data page %04x for data spix:%04x, cur_size:%i\n", data_pix, data_spix, cur_size);
+ } else {
+ // delete last page, partially
+ spiffs_page_header p_hdr;
+ spiffs_page_ix new_data_pix;
+ uint32_t bytes_to_remove = SPIFFS_DATA_PAGE_SIZE(fs) - (new_size % SPIFFS_DATA_PAGE_SIZE(fs));
+ SPIFFS_DBG("truncate: delete %i bytes from data page %04x for data spix:%04x, cur_size:%i\n", bytes_to_remove, data_pix, data_spix, cur_size);
+
+ res = spiffs_page_data_check(fs, fd, data_pix, data_spix);
+ if (res != SPIFFS_OK) break;
+
+ p_hdr.obj_id = fd->obj_id & ~SPIFFS_OBJ_ID_IX_FLAG;
+ p_hdr.span_ix = data_spix;
+ p_hdr.flags = 0xff;
+ // allocate new page and copy unmodified data
+ res = spiffs_page_allocate_data(fs, fd->obj_id & ~SPIFFS_OBJ_ID_IX_FLAG,
+ &p_hdr, 0, 0, 0, 0, &new_data_pix);
+ if (res != SPIFFS_OK) break;
+ res = spiffs_phys_cpy(fs, 0,
+ SPIFFS_PAGE_TO_PADDR(fs, new_data_pix) + sizeof(spiffs_page_header),
+ SPIFFS_PAGE_TO_PADDR(fs, data_pix) + sizeof(spiffs_page_header),
+ SPIFFS_DATA_PAGE_SIZE(fs) - bytes_to_remove);
+ if (res != SPIFFS_OK) break;
+ // delete original data page
+ res = spiffs_page_delete(fs, data_pix);
+ if (res != SPIFFS_OK) break;
+ p_hdr.flags &= ~SPIFFS_PH_FLAG_FINAL;
+ res = _spiffs_wr(fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_UPDT,
+ fd->file_nbr,
+ SPIFFS_PAGE_TO_PADDR(fs, new_data_pix) + offsetof(spiffs_page_header, flags),
+ sizeof(uint8_t),
+ (uint8_t *)&p_hdr.flags);
+ if (res != SPIFFS_OK) break;
+
+ // update memory representation of object index page with new data page
+ if (cur_objix_spix == 0) {
+ // update object index header page
+ ((spiffs_page_ix*)((uint8_t *)objix_hdr + sizeof(spiffs_page_object_ix_header)))[data_spix] = new_data_pix;
+ SPIFFS_DBG("truncate: wrote page %04x to objix_hdr entry %02x in mem\n", new_data_pix, SPIFFS_OBJ_IX_ENTRY(fs, data_spix));
+ } else {
+ // update object index page
+ ((spiffs_page_ix*)((uint8_t *)objix + sizeof(spiffs_page_object_ix)))[SPIFFS_OBJ_IX_ENTRY(fs, data_spix)] = new_data_pix;
+ SPIFFS_DBG("truncate: wrote page %04x to objix entry %02x in mem\n", new_data_pix, SPIFFS_OBJ_IX_ENTRY(fs, data_spix));
+ }
+ cur_size = new_size;
+ fd->size = new_size;
+ fd->offset = cur_size;
+ break;
+ }
+ data_spix--;
+ } // while all data
+
+ // update object indices
+ if (cur_objix_spix == 0) {
+ // update object index header page
+ if (cur_size == 0) {
+ if (remove_full) {
+ // remove object altogether
+ SPIFFS_DBG("truncate: remove object index header page %04x\n", objix_pix);
+
+ res = spiffs_page_index_check(fs, fd, objix_pix, 0);
+ SPIFFS_CHECK_RES(res);
+
+ res = spiffs_page_delete(fs, objix_pix);
+ SPIFFS_CHECK_RES(res);
+ spiffs_cb_object_event(fs, (spiffs_page_object_ix *)0,
+ SPIFFS_EV_IX_DEL, fd->obj_id, 0, objix_pix, 0);
+ } else {
+ // make uninitialized object
+ SPIFFS_DBG("truncate: reset objix_hdr page %04x\n", objix_pix);
+ memset(fs->work + sizeof(spiffs_page_object_ix_header), 0xff,
+ SPIFFS_CFG_LOG_PAGE_SZ(fs) - sizeof(spiffs_page_object_ix_header));
+ res = spiffs_object_update_index_hdr(fs, fd, fd->obj_id,
+ objix_pix, fs->work, 0, SPIFFS_UNDEFINED_LEN, &new_objix_hdr_pix);
+ SPIFFS_CHECK_RES(res);
+ }
+ } else {
+ // update object index header page
+ SPIFFS_DBG("truncate: update object index header page with indices and size\n");
+ res = spiffs_object_update_index_hdr(fs, fd, fd->obj_id,
+ objix_pix, fs->work, 0, cur_size, &new_objix_hdr_pix);
+ SPIFFS_CHECK_RES(res);
+ }
+ } else {
+ // update both current object index page and object index header page
+ spiffs_page_ix new_objix_pix;
+
+ res = spiffs_page_index_check(fs, fd, objix_pix, cur_objix_spix);
+ SPIFFS_CHECK_RES(res);
+
+ // move and update object index page
+ res = spiffs_page_move(fs, fd->file_nbr, (uint8_t*)objix_hdr, fd->obj_id, 0, objix_pix, &new_objix_pix);
+ SPIFFS_CHECK_RES(res);
+ spiffs_cb_object_event(fs, (spiffs_page_object_ix *)objix_hdr,
+ SPIFFS_EV_IX_UPD, fd->obj_id, objix->p_hdr.span_ix, new_objix_pix, 0);
+ SPIFFS_DBG("truncate: store modified objix page, %04x:%04x\n", new_objix_pix, cur_objix_spix);
+ fd->cursor_objix_pix = new_objix_pix;
+ fd->cursor_objix_spix = cur_objix_spix;
+ fd->offset = cur_size;
+ // update object index header page with new size
+ res = spiffs_object_update_index_hdr(fs, fd, fd->obj_id,
+ fd->objix_hdr_pix, 0, 0, cur_size, &new_objix_hdr_pix);
+ SPIFFS_CHECK_RES(res);
+ }
+ fd->size = cur_size;
+
+ return res;
+} // spiffs_object_truncate
+#endif // !SPIFFS_READ_ONLY
+
+int32_t spiffs_object_read(
+ spiffs_fd *fd,
+ uint32_t offset,
+ uint32_t len,
+ uint8_t *dst) {
+ int32_t res = SPIFFS_OK;
+ spiffs *fs = fd->fs;
+ spiffs_page_ix objix_pix;
+ spiffs_page_ix data_pix;
+ spiffs_span_ix data_spix = offset / SPIFFS_DATA_PAGE_SIZE(fs);
+ uint32_t cur_offset = offset;
+ spiffs_span_ix cur_objix_spix;
+ spiffs_span_ix prev_objix_spix = (spiffs_span_ix)-1;
+ spiffs_page_object_ix_header *objix_hdr = (spiffs_page_object_ix_header *)fs->work;
+ spiffs_page_object_ix *objix = (spiffs_page_object_ix *)fs->work;
+
+ while (cur_offset < offset + len) {
+#if SPIFFS_IX_MAP
+ // check if we have a memory, index map and if so, if we're within index map's range
+ // and if so, if the entry is populated
+ if (fd->ix_map && data_spix >= fd->ix_map->start_spix && data_spix <= fd->ix_map->end_spix
+ && fd->ix_map->map_buf[data_spix - fd->ix_map->start_spix]) {
+ data_pix = fd->ix_map->map_buf[data_spix - fd->ix_map->start_spix];
+ } else {
+#endif
+ cur_objix_spix = SPIFFS_OBJ_IX_ENTRY_SPAN_IX(fs, data_spix);
+ if (prev_objix_spix != cur_objix_spix) {
+ // load current object index (header) page
+ if (cur_objix_spix == 0) {
+ objix_pix = fd->objix_hdr_pix;
+ } else {
+ SPIFFS_DBG("read: find objix %04x:%04x\n", fd->obj_id, cur_objix_spix);
+ if (fd->cursor_objix_spix == cur_objix_spix) {
+ objix_pix = fd->cursor_objix_pix;
+ } else {
+ res = spiffs_obj_lu_find_id_and_span(fs, fd->obj_id | SPIFFS_OBJ_ID_IX_FLAG, cur_objix_spix, 0, &objix_pix);
+ SPIFFS_CHECK_RES(res);
+ }
+ }
+ SPIFFS_DBG("read: load objix page %04x:%04x for data spix:%04x\n", objix_pix, cur_objix_spix, data_spix);
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_IX | SPIFFS_OP_C_READ,
+ fd->file_nbr, SPIFFS_PAGE_TO_PADDR(fs, objix_pix), SPIFFS_CFG_LOG_PAGE_SZ(fs), fs->work);
+ SPIFFS_CHECK_RES(res);
+ SPIFFS_VALIDATE_OBJIX(objix->p_hdr, fd->obj_id, cur_objix_spix);
+
+ fd->offset = cur_offset;
+ fd->cursor_objix_pix = objix_pix;
+ fd->cursor_objix_spix = cur_objix_spix;
+
+ prev_objix_spix = cur_objix_spix;
+ }
+
+ if (cur_objix_spix == 0) {
+ // get data page from object index header page
+ data_pix = ((spiffs_page_ix*)((uint8_t *)objix_hdr + sizeof(spiffs_page_object_ix_header)))[data_spix];
+ } else {
+ // get data page from object index page
+ data_pix = ((spiffs_page_ix*)((uint8_t *)objix + sizeof(spiffs_page_object_ix)))[SPIFFS_OBJ_IX_ENTRY(fs, data_spix)];
+ }
+#if SPIFFS_IX_MAP
+ }
+#endif
+ // all remaining data
+ uint32_t len_to_read = offset + len - cur_offset;
+ // remaining data in page
+ len_to_read = MIN(len_to_read, SPIFFS_DATA_PAGE_SIZE(fs) - (cur_offset % SPIFFS_DATA_PAGE_SIZE(fs)));
+ // remaining data in file
+ len_to_read = MIN(len_to_read, fd->size);
+ SPIFFS_DBG("read: offset:%i rd:%i data spix:%04x is data_pix:%04x addr:%08x\n", cur_offset, len_to_read, data_spix, data_pix,
+ SPIFFS_PAGE_TO_PADDR(fs, data_pix) + sizeof(spiffs_page_header) + (cur_offset % SPIFFS_DATA_PAGE_SIZE(fs)));
+ if (len_to_read <= 0) {
+ res = SPIFFS_ERR_END_OF_OBJECT;
+ break;
+ }
+ res = spiffs_page_data_check(fs, fd, data_pix, data_spix);
+ SPIFFS_CHECK_RES(res);
+ res = _spiffs_rd(
+ fs, SPIFFS_OP_T_OBJ_DA | SPIFFS_OP_C_READ,
+ fd->file_nbr,
+ SPIFFS_PAGE_TO_PADDR(fs, data_pix) + sizeof(spiffs_page_header) + (cur_offset % SPIFFS_DATA_PAGE_SIZE(fs)),
+ len_to_read,
+ dst);
+ SPIFFS_CHECK_RES(res);
+ dst += len_to_read;
+ cur_offset += len_to_read;
+ fd->offset = cur_offset;
+ data_spix++;
+ }
+
+ return res;
+}
+
+#if !SPIFFS_READ_ONLY
+typedef struct {
+ spiffs_obj_id min_obj_id;
+ spiffs_obj_id max_obj_id;
+ uint32_t compaction;
+ const uint8_t *conflicting_name;
+} spiffs_free_obj_id_state;
+
+static int32_t spiffs_obj_lu_find_free_obj_id_bitmap_v(spiffs *fs, spiffs_obj_id id, spiffs_block_ix bix, int ix_entry,
+ const void *user_const_p, void *user_var_p) {
+ if (id != SPIFFS_OBJ_ID_FREE && id != SPIFFS_OBJ_ID_DELETED) {
+ spiffs_obj_id min_obj_id = *((spiffs_obj_id*)user_var_p);
+ const uint8_t *conflicting_name = (const uint8_t*)user_const_p;
+
+ // if conflicting name parameter is given, also check if this name is found in object index hdrs
+ if (conflicting_name && (id & SPIFFS_OBJ_ID_IX_FLAG)) {
+ spiffs_page_ix pix = SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, bix, ix_entry);
+ int res;
+ spiffs_page_object_ix_header objix_hdr;
+ res = _spiffs_rd(fs, SPIFFS_OP_T_OBJ_LU2 | SPIFFS_OP_C_READ,
+ 0, SPIFFS_PAGE_TO_PADDR(fs, pix), sizeof(spiffs_page_object_ix_header), (uint8_t *)&objix_hdr);
+ SPIFFS_CHECK_RES(res);
+ if (objix_hdr.p_hdr.span_ix == 0 &&
+ (objix_hdr.p_hdr.flags & (SPIFFS_PH_FLAG_DELET | SPIFFS_PH_FLAG_FINAL | SPIFFS_PH_FLAG_IXDELE)) ==
+ (SPIFFS_PH_FLAG_DELET | SPIFFS_PH_FLAG_IXDELE)) {
+ if (strcmp((const char*)user_const_p, (char*)objix_hdr.name) == 0) {
+ return SPIFFS_ERR_CONFLICTING_NAME;
+ }
+ }
+ }
+
+ id &= ~SPIFFS_OBJ_ID_IX_FLAG;
+ uint32_t bit_ix = (id-min_obj_id) & 7;
+ int byte_ix = (id-min_obj_id) >> 3;
+ if (byte_ix >= 0 && (uint32_t)byte_ix < SPIFFS_CFG_LOG_PAGE_SZ(fs)) {
+ fs->work[byte_ix] |= (1<conflicting_name && strcmp((const char *)state->conflicting_name, (char *)objix_hdr.name) == 0) {
+ return SPIFFS_ERR_CONFLICTING_NAME;
+ }
+
+ id &= ~SPIFFS_OBJ_ID_IX_FLAG;
+ if (id >= state->min_obj_id && id <= state->max_obj_id) {
+ uint8_t *map = (uint8_t *)fs->work;
+ int ix = (id - state->min_obj_id) / state->compaction;
+ //SPIFFS_DBG("free_obj_id: add ix %i for id %04x min:%04x max%04x comp:%i\n", ix, id, state->min_obj_id, state->max_obj_id, state->compaction);
+ map[ix]++;
+ }
+ }
+ }
+ return SPIFFS_VIS_COUNTINUE;
+}
+
+// Scans thru all object lookup for object index header pages. If total possible number of
+// object ids cannot fit into a work buffer, these are grouped. When a group containing free
+// object ids is found, the object lu is again scanned for object ids within group and bitmasked.
+// Finally, the bitmask is searched for a free id
+int32_t spiffs_obj_lu_find_free_obj_id(spiffs *fs, spiffs_obj_id *obj_id, const uint8_t *conflicting_name) {
+ int32_t res = SPIFFS_OK;
+ uint32_t max_objects = (fs->block_count * SPIFFS_OBJ_LOOKUP_MAX_ENTRIES(fs)) / 2;
+ spiffs_free_obj_id_state state;
+ spiffs_obj_id free_obj_id = SPIFFS_OBJ_ID_FREE;
+ state.min_obj_id = 1;
+ state.max_obj_id = max_objects + 1;
+ if (state.max_obj_id & SPIFFS_OBJ_ID_IX_FLAG) {
+ state.max_obj_id = ((spiffs_obj_id)-1) & ~SPIFFS_OBJ_ID_IX_FLAG;
+ }
+ state.compaction = 0;
+ state.conflicting_name = conflicting_name;
+ while (res == SPIFFS_OK && free_obj_id == SPIFFS_OBJ_ID_FREE) {
+ if (state.max_obj_id - state.min_obj_id <= (spiffs_obj_id)SPIFFS_CFG_LOG_PAGE_SZ(fs)*8) {
+ // possible to represent in bitmap
+ uint32_t i, j;
+ SPIFFS_DBG("free_obj_id: BITM min:%04x max:%04x\n", state.min_obj_id, state.max_obj_id);
+
+ memset(fs->work, 0, SPIFFS_CFG_LOG_PAGE_SZ(fs));
+ res = spiffs_obj_lu_find_entry_visitor(fs, 0, 0, 0, 0, spiffs_obj_lu_find_free_obj_id_bitmap_v,
+ conflicting_name, &state.min_obj_id, 0, 0);
+ if (res == SPIFFS_VIS_END) res = SPIFFS_OK;
+ SPIFFS_CHECK_RES(res);
+ // traverse bitmask until found free obj_id
+ for (i = 0; i < SPIFFS_CFG_LOG_PAGE_SZ(fs); i++) {
+ uint8_t mask = fs->work[i];
+ if (mask == 0xff) {
+ continue;
+ }
+ for (j = 0; j < 8; j++) {
+ if ((mask & (1<work;
+ uint8_t min_count = 0xff;
+
+ for (i = 0; i < SPIFFS_CFG_LOG_PAGE_SZ(fs)/sizeof(uint8_t); i++) {
+ if (map[i] < min_count) {
+ min_count = map[i];
+ min_i = i;
+ if (min_count == 0) {
+ break;
+ }
+ }
+ }
+
+ if (min_count == state.compaction) {
+ // there are no free objids!
+ SPIFFS_DBG("free_obj_id: compacted table is full\n");
+ return SPIFFS_ERR_FULL;
+ }
+
+ SPIFFS_DBG("free_obj_id: COMP select index:%i min_count:%i min:%04x max:%04x compact:%i\n", min_i, min_count, state.min_obj_id, state.max_obj_id, state.compaction);
+
+ if (min_count == 0) {
+ // no id in this range, skip compacting and use directly
+ *obj_id = min_i * state.compaction + state.min_obj_id;
+ return SPIFFS_OK;
+ } else {
+ SPIFFS_DBG("free_obj_id: COMP SEL chunk:%04x min:%04x -> %04x\n", state.compaction, state.min_obj_id, state.min_obj_id + min_i * state.compaction);
+ state.min_obj_id += min_i * state.compaction;
+ state.max_obj_id = state.min_obj_id + state.compaction;
+ // decrease compaction
+ }
+ if ((state.max_obj_id - state.min_obj_id <= (spiffs_obj_id)SPIFFS_CFG_LOG_PAGE_SZ(fs)*8)) {
+ // no need for compacting, use bitmap
+ continue;
+ }
+ }
+ // in a work memory of log_page_size bytes, we may fit in log_page_size ids
+ // todo what if compaction is > 255 - then we cannot fit it in a byte
+ state.compaction = (state.max_obj_id-state.min_obj_id) / ((SPIFFS_CFG_LOG_PAGE_SZ(fs) / sizeof(uint8_t)));
+ SPIFFS_DBG("free_obj_id: COMP min:%04x max:%04x compact:%i\n", state.min_obj_id, state.max_obj_id, state.compaction);
+
+ memset(fs->work, 0, SPIFFS_CFG_LOG_PAGE_SZ(fs));
+ res = spiffs_obj_lu_find_entry_visitor(fs, 0, 0, 0, 0, spiffs_obj_lu_find_free_obj_id_compact_v, &state, 0, 0, 0);
+ if (res == SPIFFS_VIS_END) res = SPIFFS_OK;
+ SPIFFS_CHECK_RES(res);
+ state.conflicting_name = 0; // searched for conflicting name once, no need to do it again
+ }
+ }
+
+ return res;
+}
+#endif // !SPIFFS_READ_ONLY
+
+#if SPIFFS_TEMPORAL_FD_CACHE
+// djb2 hash
+static uint32_t spiffs_hash(spiffs *fs, const uint8_t *name) {
+ (void)fs;
+ uint32_t hash = 5381;
+ uint8_t c;
+ int i = 0;
+ while ((c = name[i++]) && i < SPIFFS_OBJ_NAME_LEN) {
+ hash = (hash * 33) ^ c;
+ }
+ return hash;
+}
+#endif
+
+int32_t spiffs_fd_find_new(spiffs *fs, spiffs_fd **fd, const char *name) {
+#if SPIFFS_TEMPORAL_FD_CACHE
+ uint32_t i;
+ uint16_t min_score = 0xffff;
+ uint32_t cand_ix = (uint32_t)-1;
+ uint32_t name_hash = name ? spiffs_hash(fs, (const uint8_t *)name) : 0;
+ spiffs_fd *fds = (spiffs_fd *)fs->fd_space;
+
+ if (name) {
+ // first, decrease score of all closed descriptors
+ for (i = 0; i < fs->fd_count; i++) {
+ spiffs_fd *cur_fd = &fds[i];
+ if (cur_fd->file_nbr == 0) {
+ if (cur_fd->score > 1) { // score == 0 indicates never used fd
+ cur_fd->score--;
+ }
+ }
+ }
+ }
+
+ // find the free fd with least score
+ for (i = 0; i < fs->fd_count; i++) {
+ spiffs_fd *cur_fd = &fds[i];
+ if (cur_fd->file_nbr == 0) {
+ if (name && cur_fd->name_hash == name_hash) {
+ cand_ix = i;
+ break;
+ }
+ if (cur_fd->score < min_score) {
+ min_score = cur_fd->score;
+ cand_ix = i;
+ }
+ }
+ }
+
+ if (cand_ix != (uint32_t)-1) {
+ spiffs_fd *cur_fd = &fds[cand_ix];
+ if (name) {
+ if (cur_fd->name_hash == name_hash && cur_fd->score > 0) {
+ // opened an fd with same name hash, assume same file
+ // set search point to saved obj index page and hope we have a correct match directly
+ // when start searching - if not, we will just keep searching until it is found
+ fs->cursor_block_ix = SPIFFS_BLOCK_FOR_PAGE(fs, cur_fd->objix_hdr_pix);
+ fs->cursor_obj_lu_entry = SPIFFS_OBJ_LOOKUP_ENTRY_FOR_PAGE(fs, cur_fd->objix_hdr_pix);
+ // update score
+ if (cur_fd->score < 0xffff-SPIFFS_TEMPORAL_CACHE_HIT_SCORE) {
+ cur_fd->score += SPIFFS_TEMPORAL_CACHE_HIT_SCORE;
+ } else {
+ cur_fd->score = 0xffff;
+ }
+ } else {
+ // no hash hit, restore this fd to initial state
+ cur_fd->score = SPIFFS_TEMPORAL_CACHE_HIT_SCORE;
+ cur_fd->name_hash = name_hash;
+ }
+ }
+ cur_fd->file_nbr = cand_ix+1;
+ *fd = cur_fd;
+ return SPIFFS_OK;
+ } else {
+ return SPIFFS_ERR_OUT_OF_FILE_DESCS;
+ }
+#else
+ (void)name;
+ uint32_t i;
+ spiffs_fd *fds = (spiffs_fd *)fs->fd_space;
+ for (i = 0; i < fs->fd_count; i++) {
+ spiffs_fd *cur_fd = &fds[i];
+ if (cur_fd->file_nbr == 0) {
+ cur_fd->file_nbr = i+1;
+ *fd = cur_fd;
+ return SPIFFS_OK;
+ }
+ }
+ return SPIFFS_ERR_OUT_OF_FILE_DESCS;
+#endif
+}
+
+int32_t spiffs_fd_return(spiffs *fs, spiffs_file f) {
+ if (f <= 0 || f > (int16_t )fs->fd_count) {
+ return SPIFFS_ERR_BAD_DESCRIPTOR;
+ }
+ spiffs_fd *fds = (spiffs_fd *)fs->fd_space;
+ spiffs_fd *fd = &fds[f-1];
+ if (fd->file_nbr == 0) {
+ return SPIFFS_ERR_FILE_CLOSED;
+ }
+ fd->file_nbr = 0;
+#if SPIFFS_IX_MAP
+ fd->ix_map = 0;
+#endif
+ return SPIFFS_OK;
+}
+
+int32_t spiffs_fd_get(spiffs *fs, spiffs_file f, spiffs_fd **fd) {
+ if (f <= 0 || f > (int16_t )fs->fd_count) {
+ return SPIFFS_ERR_BAD_DESCRIPTOR;
+ }
+ spiffs_fd *fds = (spiffs_fd *)fs->fd_space;
+ *fd = &fds[f-1];
+ if ((*fd)->file_nbr == 0) {
+ return SPIFFS_ERR_FILE_CLOSED;
+ }
+ return SPIFFS_OK;
+}
+
+#if SPIFFS_TEMPORAL_FD_CACHE
+void spiffs_fd_temporal_cache_rehash(
+ spiffs *fs,
+ const char *old_path,
+ const char *new_path) {
+ uint32_t i;
+ uint32_t old_hash = spiffs_hash(fs, (const uint8_t *)old_path);
+ uint32_t new_hash = spiffs_hash(fs, (const uint8_t *)new_path);
+ spiffs_fd *fds = (spiffs_fd *)fs->fd_space;
+ for (i = 0; i < fs->fd_count; i++) {
+ spiffs_fd *cur_fd = &fds[i];
+ if (cur_fd->score > 0 && cur_fd->name_hash == old_hash) {
+ cur_fd->name_hash = new_hash;
+ }
+ }
+}
+#endif
diff --git a/fw/User/spiffs/src/spiffs_nucleus.h b/fw/User/spiffs/src/spiffs_nucleus.h
new file mode 100644
index 0000000..e53300c
--- /dev/null
+++ b/fw/User/spiffs/src/spiffs_nucleus.h
@@ -0,0 +1,791 @@
+/*
+ * spiffs_nucleus.h
+ *
+ * Created on: Jun 15, 2013
+ * Author: petera
+ */
+
+/* SPIFFS layout
+ *
+ * spiffs is designed for following spi flash characteristics:
+ * - only big areas of data (blocks) can be erased
+ * - erasing resets all bits in a block to ones
+ * - writing pulls ones to zeroes
+ * - zeroes cannot be pulled to ones, without erase
+ * - wear leveling
+ *
+ * spiffs is also meant to be run on embedded, memory constraint devices.
+ *
+ * Entire area is divided in blocks. Entire area is also divided in pages.
+ * Each block contains same number of pages. A page cannot be erased, but a
+ * block can be erased.
+ *
+ * Entire area must be block_size * x
+ * page_size must be block_size / (2^y) where y > 2
+ *
+ * ex: area = 1024*1024 bytes, block size = 65536 bytes, page size = 256 bytes
+ *
+ * BLOCK 0 PAGE 0 object lookup 1
+ * PAGE 1 object lookup 2
+ * ...
+ * PAGE n-1 object lookup n
+ * PAGE n object data 1
+ * PAGE n+1 object data 2
+ * ...
+ * PAGE n+m-1 object data m
+ *
+ * BLOCK 1 PAGE n+m object lookup 1
+ * PAGE n+m+1 object lookup 2
+ * ...
+ * PAGE 2n+m-1 object lookup n
+ * PAGE 2n+m object data 1
+ * PAGE 2n+m object data 2
+ * ...
+ * PAGE 2n+2m-1 object data m
+ * ...
+ *
+ * n is number of object lookup pages, which is number of pages needed to index all pages
+ * in a block by object id
+ * : block_size / page_size * sizeof(obj_id) / page_size
+ * m is number data pages, which is number of pages in block minus number of lookup pages
+ * : block_size / page_size - block_size / page_size * sizeof(obj_id) / page_size
+ * thus, n+m is total number of pages in a block
+ * : block_size / page_size
+ *
+ * ex: n = 65536/256*2/256 = 2, m = 65536/256 - 2 = 254 => n+m = 65536/256 = 256
+ *
+ * Object lookup pages contain object id entries. Each entry represent the corresponding
+ * data page.
+ * Assuming a 16 bit object id, an object id being 0xffff represents a free page.
+ * An object id being 0x0000 represents a deleted page.
+ *
+ * ex: page 0 : lookup : 0008 0001 0aaa ffff ffff ffff ffff ffff ..
+ * page 1 : lookup : ffff ffff ffff ffff ffff ffff ffff ffff ..
+ * page 2 : data : data for object id 0008
+ * page 3 : data : data for object id 0001
+ * page 4 : data : data for object id 0aaa
+ * ...
+ *
+ *
+ * Object data pages can be either object index pages or object content.
+ * All object data pages contains a data page header, containing object id and span index.
+ * The span index denotes the object page ordering amongst data pages with same object id.
+ * This applies to both object index pages (when index spans more than one page of entries),
+ * and object data pages.
+ * An object index page contains page entries pointing to object content page. The entry index
+ * in a object index page correlates to the span index in the actual object data page.
+ * The first object index page (span index 0) is called object index header page, and also
+ * contains object flags (directory/file), size, object name etc.
+ *
+ * ex:
+ * BLOCK 1
+ * PAGE 256: objectl lookup page 1
+ * [*123] [ 123] [ 123] [ 123]
+ * [ 123] [*123] [ 123] [ 123]
+ * [free] [free] [free] [free] ...
+ * PAGE 257: objectl lookup page 2
+ * [free] [free] [free] [free] ...
+ * PAGE 258: object index page (header)
+ * obj.id:0123 span.ix:0000 flags:INDEX
+ * size:1600 name:ex.txt type:file
+ * [259] [260] [261] [262]
+ * PAGE 259: object data page
+ * obj.id:0123 span.ix:0000 flags:DATA
+ * PAGE 260: object data page
+ * obj.id:0123 span.ix:0001 flags:DATA
+ * PAGE 261: object data page
+ * obj.id:0123 span.ix:0002 flags:DATA
+ * PAGE 262: object data page
+ * obj.id:0123 span.ix:0003 flags:DATA
+ * PAGE 263: object index page
+ * obj.id:0123 span.ix:0001 flags:INDEX
+ * [264] [265] [fre] [fre]
+ * [fre] [fre] [fre] [fre]
+ * PAGE 264: object data page
+ * obj.id:0123 span.ix:0004 flags:DATA
+ * PAGE 265: object data page
+ * obj.id:0123 span.ix:0005 flags:DATA
+ *
+ */
+#ifndef SPIFFS_NUCLEUS_H_
+#define SPIFFS_NUCLEUS_H_
+
+#define _SPIFFS_ERR_CHECK_FIRST (SPIFFS_ERR_INTERNAL - 1)
+#define SPIFFS_ERR_CHECK_OBJ_ID_MISM (SPIFFS_ERR_INTERNAL - 1)
+#define SPIFFS_ERR_CHECK_SPIX_MISM (SPIFFS_ERR_INTERNAL - 2)
+#define SPIFFS_ERR_CHECK_FLAGS_BAD (SPIFFS_ERR_INTERNAL - 3)
+#define _SPIFFS_ERR_CHECK_LAST (SPIFFS_ERR_INTERNAL - 4)
+
+// visitor result, continue searching
+#define SPIFFS_VIS_COUNTINUE (SPIFFS_ERR_INTERNAL - 20)
+// visitor result, continue searching after reloading lu buffer
+#define SPIFFS_VIS_COUNTINUE_RELOAD (SPIFFS_ERR_INTERNAL - 21)
+// visitor result, stop searching
+#define SPIFFS_VIS_END (SPIFFS_ERR_INTERNAL - 22)
+
+// updating an object index contents
+#define SPIFFS_EV_IX_UPD (0)
+// creating a new object index
+#define SPIFFS_EV_IX_NEW (1)
+// deleting an object index
+#define SPIFFS_EV_IX_DEL (2)
+// moving an object index without updating contents
+#define SPIFFS_EV_IX_MOV (3)
+// updating an object index header data only, not the table itself
+#define SPIFFS_EV_IX_UPD_HDR (4)
+
+#define SPIFFS_OBJ_ID_IX_FLAG ((spiffs_obj_id)(1<<(8*sizeof(spiffs_obj_id)-1)))
+
+#define SPIFFS_UNDEFINED_LEN (uint32_t)(-1)
+
+#define SPIFFS_OBJ_ID_DELETED ((spiffs_obj_id)0)
+#define SPIFFS_OBJ_ID_FREE ((spiffs_obj_id)-1)
+
+#if SPIFFS_USE_MAGIC
+#if !SPIFFS_USE_MAGIC_LENGTH
+#define SPIFFS_MAGIC(fs, bix) \
+ ((spiffs_obj_id)(0x20140529 ^ SPIFFS_CFG_LOG_PAGE_SZ(fs)))
+#else // SPIFFS_USE_MAGIC_LENGTH
+#define SPIFFS_MAGIC(fs, bix) \
+ ((spiffs_obj_id)(0x20140529 ^ SPIFFS_CFG_LOG_PAGE_SZ(fs) ^ ((fs)->block_count - (bix))))
+#endif // SPIFFS_USE_MAGIC_LENGTH
+#endif // SPIFFS_USE_MAGIC
+
+#define SPIFFS_CONFIG_MAGIC (0x20090315)
+
+#if SPIFFS_SINGLETON == 0
+#define SPIFFS_CFG_LOG_PAGE_SZ(fs) \
+ ((fs)->cfg.log_page_size)
+#define SPIFFS_CFG_LOG_BLOCK_SZ(fs) \
+ ((fs)->cfg.log_block_size)
+#define SPIFFS_CFG_PHYS_SZ(fs) \
+ ((fs)->cfg.phys_size)
+#define SPIFFS_CFG_PHYS_ERASE_SZ(fs) \
+ ((fs)->cfg.phys_erase_block)
+#define SPIFFS_CFG_PHYS_ADDR(fs) \
+ ((fs)->cfg.phys_addr)
+#endif
+
+// total number of pages
+#define SPIFFS_MAX_PAGES(fs) \
+ ( SPIFFS_CFG_PHYS_SZ(fs)/SPIFFS_CFG_LOG_PAGE_SZ(fs) )
+// total number of pages per block, including object lookup pages
+#define SPIFFS_PAGES_PER_BLOCK(fs) \
+ ( SPIFFS_CFG_LOG_BLOCK_SZ(fs)/SPIFFS_CFG_LOG_PAGE_SZ(fs) )
+// number of object lookup pages per block
+#define SPIFFS_OBJ_LOOKUP_PAGES(fs) \
+ (MAX(1, (SPIFFS_PAGES_PER_BLOCK(fs) * sizeof(spiffs_obj_id)) / SPIFFS_CFG_LOG_PAGE_SZ(fs)) )
+// checks if page index belongs to object lookup
+#define SPIFFS_IS_LOOKUP_PAGE(fs,pix) \
+ (((pix) % SPIFFS_PAGES_PER_BLOCK(fs)) < SPIFFS_OBJ_LOOKUP_PAGES(fs))
+// number of object lookup entries in all object lookup pages
+#define SPIFFS_OBJ_LOOKUP_MAX_ENTRIES(fs) \
+ (SPIFFS_PAGES_PER_BLOCK(fs)-SPIFFS_OBJ_LOOKUP_PAGES(fs))
+// converts a block to physical address
+#define SPIFFS_BLOCK_TO_PADDR(fs, block) \
+ ( SPIFFS_CFG_PHYS_ADDR(fs) + (block)* SPIFFS_CFG_LOG_BLOCK_SZ(fs) )
+// converts a object lookup entry to page index
+#define SPIFFS_OBJ_LOOKUP_ENTRY_TO_PIX(fs, block, entry) \
+ ((block)*SPIFFS_PAGES_PER_BLOCK(fs) + (SPIFFS_OBJ_LOOKUP_PAGES(fs) + entry))
+// converts a object lookup entry to physical address of corresponding page
+#define SPIFFS_OBJ_LOOKUP_ENTRY_TO_PADDR(fs, block, entry) \
+ (SPIFFS_BLOCK_TO_PADDR(fs, block) + (SPIFFS_OBJ_LOOKUP_PAGES(fs) + entry) * SPIFFS_CFG_LOG_PAGE_SZ(fs) )
+// converts a page to physical address
+#define SPIFFS_PAGE_TO_PADDR(fs, page) \
+ ( SPIFFS_CFG_PHYS_ADDR(fs) + (page) * SPIFFS_CFG_LOG_PAGE_SZ(fs) )
+// converts a physical address to page
+#define SPIFFS_PADDR_TO_PAGE(fs, addr) \
+ ( ((addr) - SPIFFS_CFG_PHYS_ADDR(fs)) / SPIFFS_CFG_LOG_PAGE_SZ(fs) )
+// gives index in page for a physical address
+#define SPIFFS_PADDR_TO_PAGE_OFFSET(fs, addr) \
+ ( ((addr) - SPIFFS_CFG_PHYS_ADDR(fs)) % SPIFFS_CFG_LOG_PAGE_SZ(fs) )
+// returns containing block for given page
+#define SPIFFS_BLOCK_FOR_PAGE(fs, page) \
+ ( (page) / SPIFFS_PAGES_PER_BLOCK(fs) )
+// returns starting page for block
+#define SPIFFS_PAGE_FOR_BLOCK(fs, block) \
+ ( (block) * SPIFFS_PAGES_PER_BLOCK(fs) )
+// converts page to entry in object lookup page
+#define SPIFFS_OBJ_LOOKUP_ENTRY_FOR_PAGE(fs, page) \
+ ( (page) % SPIFFS_PAGES_PER_BLOCK(fs) - SPIFFS_OBJ_LOOKUP_PAGES(fs) )
+// returns data size in a data page
+#define SPIFFS_DATA_PAGE_SIZE(fs) \
+ ( SPIFFS_CFG_LOG_PAGE_SZ(fs) - sizeof(spiffs_page_header) )
+// returns physical address for block's erase count,
+// always in the physical last entry of the last object lookup page
+#define SPIFFS_ERASE_COUNT_PADDR(fs, bix) \
+ ( SPIFFS_BLOCK_TO_PADDR(fs, bix) + SPIFFS_OBJ_LOOKUP_PAGES(fs) * SPIFFS_CFG_LOG_PAGE_SZ(fs) - sizeof(spiffs_obj_id) )
+// returns physical address for block's magic,
+// always in the physical second last entry of the last object lookup page
+#define SPIFFS_MAGIC_PADDR(fs, bix) \
+ ( SPIFFS_BLOCK_TO_PADDR(fs, bix) + SPIFFS_OBJ_LOOKUP_PAGES(fs) * SPIFFS_CFG_LOG_PAGE_SZ(fs) - sizeof(spiffs_obj_id)*2 )
+// checks if there is any room for magic in the object luts
+#define SPIFFS_CHECK_MAGIC_POSSIBLE(fs) \
+ ( (SPIFFS_OBJ_LOOKUP_MAX_ENTRIES(fs) % (SPIFFS_CFG_LOG_PAGE_SZ(fs)/sizeof(spiffs_obj_id))) * sizeof(spiffs_obj_id) \
+ <= (SPIFFS_CFG_LOG_PAGE_SZ(fs)-sizeof(spiffs_obj_id)*2) )
+
+// define helpers object
+
+// entries in an object header page index
+#define SPIFFS_OBJ_HDR_IX_LEN(fs) \
+ ((SPIFFS_CFG_LOG_PAGE_SZ(fs) - sizeof(spiffs_page_object_ix_header))/sizeof(spiffs_page_ix))
+// entries in an object page index
+#define SPIFFS_OBJ_IX_LEN(fs) \
+ ((SPIFFS_CFG_LOG_PAGE_SZ(fs) - sizeof(spiffs_page_object_ix))/sizeof(spiffs_page_ix))
+// object index entry for given data span index
+#define SPIFFS_OBJ_IX_ENTRY(fs, spix) \
+ ((spix) < SPIFFS_OBJ_HDR_IX_LEN(fs) ? (spix) : (((spix)-SPIFFS_OBJ_HDR_IX_LEN(fs))%SPIFFS_OBJ_IX_LEN(fs)))
+// object index span index number for given data span index or entry
+#define SPIFFS_OBJ_IX_ENTRY_SPAN_IX(fs, spix) \
+ ((spix) < SPIFFS_OBJ_HDR_IX_LEN(fs) ? 0 : (1+((spix)-SPIFFS_OBJ_HDR_IX_LEN(fs))/SPIFFS_OBJ_IX_LEN(fs)))
+// get data span index for object index span index
+#define SPIFFS_DATA_SPAN_IX_FOR_OBJ_IX_SPAN_IX(fs, spix) \
+ ( (spix) == 0 ? 0 : (SPIFFS_OBJ_HDR_IX_LEN(fs) + (((spix)-1) * SPIFFS_OBJ_IX_LEN(fs))) )
+
+#define SPIFFS_OP_T_OBJ_LU (0<<0)
+#define SPIFFS_OP_T_OBJ_LU2 (1<<0)
+#define SPIFFS_OP_T_OBJ_IX (2<<0)
+#define SPIFFS_OP_T_OBJ_DA (3<<0)
+#define SPIFFS_OP_C_DELE (0<<2)
+#define SPIFFS_OP_C_UPDT (1<<2)
+#define SPIFFS_OP_C_MOVS (2<<2)
+#define SPIFFS_OP_C_MOVD (3<<2)
+#define SPIFFS_OP_C_FLSH (4<<2)
+#define SPIFFS_OP_C_READ (5<<2)
+#define SPIFFS_OP_C_WRTHRU (6<<2)
+
+#define SPIFFS_OP_TYPE_MASK (3<<0)
+#define SPIFFS_OP_COM_MASK (7<<2)
+
+
+// if 0, this page is written to, else clean
+#define SPIFFS_PH_FLAG_USED (1<<0)
+// if 0, writing is finalized, else under modification
+#define SPIFFS_PH_FLAG_FINAL (1<<1)
+// if 0, this is an index page, else a data page
+#define SPIFFS_PH_FLAG_INDEX (1<<2)
+// if 0, page is deleted, else valid
+#define SPIFFS_PH_FLAG_DELET (1<<7)
+// if 0, this index header is being deleted
+#define SPIFFS_PH_FLAG_IXDELE (1<<6)
+
+
+#define SPIFFS_CHECK_MOUNT(fs) \
+ ((fs)->mounted != 0)
+
+#define SPIFFS_CHECK_CFG(fs) \
+ ((fs)->config_magic == SPIFFS_CONFIG_MAGIC)
+
+#define SPIFFS_CHECK_RES(res) \
+ do { \
+ if ((res) < SPIFFS_OK) return (res); \
+ } while (0);
+
+#define SPIFFS_API_CHECK_MOUNT(fs) \
+ if (!SPIFFS_CHECK_MOUNT((fs))) { \
+ (fs)->err_code = SPIFFS_ERR_NOT_MOUNTED; \
+ return SPIFFS_ERR_NOT_MOUNTED; \
+ }
+
+#define SPIFFS_API_CHECK_CFG(fs) \
+ if (!SPIFFS_CHECK_CFG((fs))) { \
+ (fs)->err_code = SPIFFS_ERR_NOT_CONFIGURED; \
+ return SPIFFS_ERR_NOT_CONFIGURED; \
+ }
+
+#define SPIFFS_API_CHECK_RES(fs, res) \
+ if ((res) < SPIFFS_OK) { \
+ (fs)->err_code = (res); \
+ return (res); \
+ }
+
+#define SPIFFS_API_CHECK_RES_UNLOCK(fs, res) \
+ if ((res) < SPIFFS_OK) { \
+ (fs)->err_code = (res); \
+ SPIFFS_UNLOCK(fs); \
+ return (res); \
+ }
+
+#define SPIFFS_VALIDATE_OBJIX(ph, objid, spix) \
+ if (((ph).flags & SPIFFS_PH_FLAG_USED) != 0) return SPIFFS_ERR_IS_FREE; \
+ if (((ph).flags & SPIFFS_PH_FLAG_DELET) == 0) return SPIFFS_ERR_DELETED; \
+ if (((ph).flags & SPIFFS_PH_FLAG_FINAL) != 0) return SPIFFS_ERR_NOT_FINALIZED; \
+ if (((ph).flags & SPIFFS_PH_FLAG_INDEX) != 0) return SPIFFS_ERR_NOT_INDEX; \
+ if (((objid) & SPIFFS_OBJ_ID_IX_FLAG) == 0) return SPIFFS_ERR_NOT_INDEX; \
+ if ((ph).span_ix != (spix)) return SPIFFS_ERR_INDEX_SPAN_MISMATCH;
+ //if ((spix) == 0 && ((ph).flags & SPIFFS_PH_FLAG_IXDELE) == 0) return SPIFFS_ERR_DELETED;
+
+#define SPIFFS_VALIDATE_DATA(ph, objid, spix) \
+ if (((ph).flags & SPIFFS_PH_FLAG_USED) != 0) return SPIFFS_ERR_IS_FREE; \
+ if (((ph).flags & SPIFFS_PH_FLAG_DELET) == 0) return SPIFFS_ERR_DELETED; \
+ if (((ph).flags & SPIFFS_PH_FLAG_FINAL) != 0) return SPIFFS_ERR_NOT_FINALIZED; \
+ if (((ph).flags & SPIFFS_PH_FLAG_INDEX) == 0) return SPIFFS_ERR_IS_INDEX; \
+ if ((objid) & SPIFFS_OBJ_ID_IX_FLAG) return SPIFFS_ERR_IS_INDEX; \
+ if ((ph).span_ix != (spix)) return SPIFFS_ERR_DATA_SPAN_MISMATCH;
+
+
+// check id, only visit matching objec ids
+#define SPIFFS_VIS_CHECK_ID (1<<0)
+// report argument object id to visitor - else object lookup id is reported
+#define SPIFFS_VIS_CHECK_PH (1<<1)
+// stop searching at end of all look up pages
+#define SPIFFS_VIS_NO_WRAP (1<<2)
+
+#if SPIFFS_HAL_CALLBACK_EXTRA
+
+#define SPIFFS_HAL_WRITE(_fs, _paddr, _len, _src) \
+ (_fs)->cfg.hal_write_f((_fs), (_paddr), (_len), (_src))
+#define SPIFFS_HAL_READ(_fs, _paddr, _len, _dst) \
+ (_fs)->cfg.hal_read_f((_fs), (_paddr), (_len), (_dst))
+#define SPIFFS_HAL_ERASE(_fs, _paddr, _len) \
+ (_fs)->cfg.hal_erase_f((_fs), (_paddr), (_len))
+
+#else // SPIFFS_HAL_CALLBACK_EXTRA
+
+#define SPIFFS_HAL_WRITE(_fs, _paddr, _len, _src) \
+ (_fs)->cfg.hal_write_f((_paddr), (_len), (_src))
+#define SPIFFS_HAL_READ(_fs, _paddr, _len, _dst) \
+ (_fs)->cfg.hal_read_f((_paddr), (_len), (_dst))
+#define SPIFFS_HAL_ERASE(_fs, _paddr, _len) \
+ (_fs)->cfg.hal_erase_f((_paddr), (_len))
+
+#endif // SPIFFS_HAL_CALLBACK_EXTRA
+
+#if SPIFFS_CACHE
+
+#define SPIFFS_CACHE_FLAG_DIRTY (1<<0)
+#define SPIFFS_CACHE_FLAG_WRTHRU (1<<1)
+#define SPIFFS_CACHE_FLAG_OBJLU (1<<2)
+#define SPIFFS_CACHE_FLAG_OBJIX (1<<3)
+#define SPIFFS_CACHE_FLAG_DATA (1<<4)
+#define SPIFFS_CACHE_FLAG_TYPE_WR (1<<7)
+
+#define SPIFFS_CACHE_PAGE_SIZE(fs) \
+ (sizeof(spiffs_cache_page) + SPIFFS_CFG_LOG_PAGE_SZ(fs))
+
+#define spiffs_get_cache(fs) \
+ ((spiffs_cache *)((fs)->cache))
+
+#define spiffs_get_cache_page_hdr(fs, c, ix) \
+ ((spiffs_cache_page *)(&((c)->cpages[(ix) * SPIFFS_CACHE_PAGE_SIZE(fs)])))
+
+#define spiffs_get_cache_page(fs, c, ix) \
+ ((uint8_t *)(&((c)->cpages[(ix) * SPIFFS_CACHE_PAGE_SIZE(fs)])) + sizeof(spiffs_cache_page))
+
+// cache page struct
+typedef struct {
+ // cache flags
+ uint8_t flags;
+ // cache page index
+ uint8_t ix;
+ // last access of this cache page
+ uint32_t last_access;
+ union {
+ // type read cache
+ struct {
+ // read cache page index
+ spiffs_page_ix pix;
+ };
+#if SPIFFS_CACHE_WR
+ // type write cache
+ struct {
+ // write cache
+ spiffs_obj_id obj_id;
+ // offset in cache page
+ uint32_t offset;
+ // size of cache page
+ uint16_t size;
+ };
+#endif
+ };
+} spiffs_cache_page;
+
+// cache struct
+typedef struct {
+ uint8_t cpage_count;
+ uint32_t last_access;
+ uint32_t cpage_use_map;
+ uint32_t cpage_use_mask;
+ uint8_t *cpages;
+} spiffs_cache;
+
+#endif
+
+
+// spiffs nucleus file descriptor
+typedef struct {
+ // the filesystem of this descriptor
+ spiffs *fs;
+ // number of file descriptor - if 0, the file descriptor is closed
+ spiffs_file file_nbr;
+ // object id - if SPIFFS_OBJ_ID_ERASED, the file was deleted
+ spiffs_obj_id obj_id;
+ // size of the file
+ uint32_t size;
+ // cached object index header page index
+ spiffs_page_ix objix_hdr_pix;
+ // cached offset object index page index
+ spiffs_page_ix cursor_objix_pix;
+ // cached offset object index span index
+ spiffs_span_ix cursor_objix_spix;
+ // current absolute offset
+ uint32_t offset;
+ // current file descriptor offset
+ uint32_t fdoffset;
+ // fd flags
+ spiffs_flags flags;
+#if SPIFFS_CACHE_WR
+ spiffs_cache_page *cache_page;
+#endif
+#if SPIFFS_TEMPORAL_FD_CACHE
+ // djb2 hash of filename
+ uint32_t name_hash;
+ // hit score (score == 0 indicates never used fd)
+ uint16_t score;
+#endif
+#if SPIFFS_IX_MAP
+ // spiffs index map, if 0 it means unmapped
+ spiffs_ix_map *ix_map;
+#endif
+} spiffs_fd;
+
+
+// object structs
+
+// page header, part of each page except object lookup pages
+// NB: this is always aligned when the data page is an object index,
+// as in this case struct spiffs_page_object_ix is used
+typedef struct __attribute(( packed )) {
+ // object id
+ spiffs_obj_id obj_id;
+ // object span index
+ spiffs_span_ix span_ix;
+ // flags
+ uint8_t flags;
+} spiffs_page_header;
+
+// object index header page header
+typedef struct __attribute(( packed ))
+#if SPIFFS_ALIGNED_OBJECT_INDEX_TABLES
+ __attribute(( aligned(sizeof(spiffs_page_ix)) ))
+#endif
+{
+ // common page header
+ spiffs_page_header p_hdr;
+ // alignment
+ uint8_t _align[4 - ((sizeof(spiffs_page_header)&3)==0 ? 4 : (sizeof(spiffs_page_header)&3))];
+ // size of object
+ uint32_t size;
+ // type of object
+ spiffs_obj_type type;
+ // name of object
+ uint8_t name[SPIFFS_OBJ_NAME_LEN];
+} spiffs_page_object_ix_header;
+
+// object index page header
+typedef struct __attribute(( packed )) {
+ spiffs_page_header p_hdr;
+ uint8_t _align[4 - ((sizeof(spiffs_page_header)&3)==0 ? 4 : (sizeof(spiffs_page_header)&3))];
+} spiffs_page_object_ix;
+
+// callback func for object lookup visitor
+typedef int32_t (*spiffs_visitor_f)(spiffs *fs, spiffs_obj_id id, spiffs_block_ix bix, int ix_entry,
+ const void *user_const_p, void *user_var_p);
+
+
+#if SPIFFS_CACHE
+#define _spiffs_rd(fs, op, fh, addr, len, dst) \
+ spiffs_phys_rd((fs), (op), (fh), (addr), (len), (dst))
+#define _spiffs_wr(fs, op, fh, addr, len, src) \
+ spiffs_phys_wr((fs), (op), (fh), (addr), (len), (src))
+#else
+#define _spiffs_rd(fs, op, fh, addr, len, dst) \
+ spiffs_phys_rd((fs), (addr), (len), (dst))
+#define _spiffs_wr(fs, op, fh, addr, len, src) \
+ spiffs_phys_wr((fs), (addr), (len), (src))
+#endif
+
+#ifndef MIN
+#define MIN(a,b) ((a) < (b) ? (a) : (b))
+#endif
+#ifndef MAX
+#define MAX(a,b) ((a) > (b) ? (a) : (b))
+#endif
+
+// ---------------
+
+int32_t spiffs_phys_rd(
+ spiffs *fs,
+#if SPIFFS_CACHE
+ uint8_t op,
+ spiffs_file fh,
+#endif
+ uint32_t addr,
+ uint32_t len,
+ uint8_t *dst);
+
+int32_t spiffs_phys_wr(
+ spiffs *fs,
+#if SPIFFS_CACHE
+ uint8_t op,
+ spiffs_file fh,
+#endif
+ uint32_t addr,
+ uint32_t len,
+ uint8_t *src);
+
+int32_t spiffs_phys_cpy(
+ spiffs *fs,
+ spiffs_file fh,
+ uint32_t dst,
+ uint32_t src,
+ uint32_t len);
+
+int32_t spiffs_phys_count_free_blocks(
+ spiffs *fs);
+
+int32_t spiffs_obj_lu_find_entry_visitor(
+ spiffs *fs,
+ spiffs_block_ix starting_block,
+ int starting_lu_entry,
+ uint8_t flags,
+ spiffs_obj_id obj_id,
+ spiffs_visitor_f v,
+ const void *user_const_p,
+ void *user_var_p,
+ spiffs_block_ix *block_ix,
+ int *lu_entry);
+
+int32_t spiffs_erase_block(
+ spiffs *fs,
+ spiffs_block_ix bix);
+
+#if SPIFFS_USE_MAGIC && SPIFFS_USE_MAGIC_LENGTH
+int32_t spiffs_probe(
+ spiffs_config *cfg);
+#endif // SPIFFS_USE_MAGIC && SPIFFS_USE_MAGIC_LENGTH
+
+// ---------------
+
+int32_t spiffs_obj_lu_scan(
+ spiffs *fs);
+
+int32_t spiffs_obj_lu_find_free_obj_id(
+ spiffs *fs,
+ spiffs_obj_id *obj_id,
+ const uint8_t *conflicting_name);
+
+int32_t spiffs_obj_lu_find_free(
+ spiffs *fs,
+ spiffs_block_ix starting_block,
+ int starting_lu_entry,
+ spiffs_block_ix *block_ix,
+ int *lu_entry);
+
+int32_t spiffs_obj_lu_find_id(
+ spiffs *fs,
+ spiffs_block_ix starting_block,
+ int starting_lu_entry,
+ spiffs_obj_id obj_id,
+ spiffs_block_ix *block_ix,
+ int *lu_entry);
+
+int32_t spiffs_obj_lu_find_id_and_span(
+ spiffs *fs,
+ spiffs_obj_id obj_id,
+ spiffs_span_ix spix,
+ spiffs_page_ix exclusion_pix,
+ spiffs_page_ix *pix);
+
+int32_t spiffs_obj_lu_find_id_and_span_by_phdr(
+ spiffs *fs,
+ spiffs_obj_id obj_id,
+ spiffs_span_ix spix,
+ spiffs_page_ix exclusion_pix,
+ spiffs_page_ix *pix);
+
+// ---------------
+
+int32_t spiffs_page_allocate_data(
+ spiffs *fs,
+ spiffs_obj_id obj_id,
+ spiffs_page_header *ph,
+ uint8_t *data,
+ uint32_t len,
+ uint32_t page_offs,
+ uint8_t finalize,
+ spiffs_page_ix *pix);
+
+int32_t spiffs_page_move(
+ spiffs *fs,
+ spiffs_file fh,
+ uint8_t *page_data,
+ spiffs_obj_id obj_id,
+ spiffs_page_header *page_hdr,
+ spiffs_page_ix src_pix,
+ spiffs_page_ix *dst_pix);
+
+int32_t spiffs_page_delete(
+ spiffs *fs,
+ spiffs_page_ix pix);
+
+// ---------------
+
+int32_t spiffs_object_create(
+ spiffs *fs,
+ spiffs_obj_id obj_id,
+ const uint8_t name[SPIFFS_OBJ_NAME_LEN],
+ spiffs_obj_type type,
+ spiffs_page_ix *objix_hdr_pix);
+
+int32_t spiffs_object_update_index_hdr(
+ spiffs *fs,
+ spiffs_fd *fd,
+ spiffs_obj_id obj_id,
+ spiffs_page_ix objix_hdr_pix,
+ uint8_t *new_objix_hdr_data,
+ const uint8_t name[SPIFFS_OBJ_NAME_LEN],
+ uint32_t size,
+ spiffs_page_ix *new_pix);
+
+#if SPIFFS_IX_MAP
+
+int32_t spiffs_populate_ix_map(
+ spiffs *fs,
+ spiffs_fd *fd,
+ uint32_t vec_entry_start,
+ uint32_t vec_entry_end);
+
+#endif
+
+void spiffs_cb_object_event(
+ spiffs *fs,
+ spiffs_page_object_ix *objix,
+ int ev,
+ spiffs_obj_id obj_id,
+ spiffs_span_ix spix,
+ spiffs_page_ix new_pix,
+ uint32_t new_size);
+
+int32_t spiffs_object_open_by_id(
+ spiffs *fs,
+ spiffs_obj_id obj_id,
+ spiffs_fd *f,
+ spiffs_flags flags,
+ spiffs_mode mode);
+
+int32_t spiffs_object_open_by_page(
+ spiffs *fs,
+ spiffs_page_ix pix,
+ spiffs_fd *f,
+ spiffs_flags flags,
+ spiffs_mode mode);
+
+int32_t spiffs_object_append(
+ spiffs_fd *fd,
+ uint32_t offset,
+ uint8_t *data,
+ uint32_t len);
+
+int32_t spiffs_object_modify(
+ spiffs_fd *fd,
+ uint32_t offset,
+ uint8_t *data,
+ uint32_t len);
+
+int32_t spiffs_object_read(
+ spiffs_fd *fd,
+ uint32_t offset,
+ uint32_t len,
+ uint8_t *dst);
+
+int32_t spiffs_object_truncate(
+ spiffs_fd *fd,
+ uint32_t new_len,
+ uint8_t remove_object);
+
+int32_t spiffs_object_find_object_index_header_by_name(
+ spiffs *fs,
+ const uint8_t name[SPIFFS_OBJ_NAME_LEN],
+ spiffs_page_ix *pix);
+
+// ---------------
+
+int32_t spiffs_gc_check(
+ spiffs *fs,
+ uint32_t len);
+
+int32_t spiffs_gc_erase_page_stats(
+ spiffs *fs,
+ spiffs_block_ix bix);
+
+int32_t spiffs_gc_find_candidate(
+ spiffs *fs,
+ spiffs_block_ix **block_candidate,
+ int *candidate_count,
+ char fs_crammed);
+
+int32_t spiffs_gc_clean(
+ spiffs *fs,
+ spiffs_block_ix bix);
+
+int32_t spiffs_gc_quick(
+ spiffs *fs, uint16_t max_free_pages);
+
+// ---------------
+
+int32_t spiffs_fd_find_new(
+ spiffs *fs,
+ spiffs_fd **fd,
+ const char *name);
+
+int32_t spiffs_fd_return(
+ spiffs *fs,
+ spiffs_file f);
+
+int32_t spiffs_fd_get(
+ spiffs *fs,
+ spiffs_file f,
+ spiffs_fd **fd);
+
+#if SPIFFS_TEMPORAL_FD_CACHE
+void spiffs_fd_temporal_cache_rehash(
+ spiffs *fs,
+ const char *old_path,
+ const char *new_path);
+#endif
+
+#if SPIFFS_CACHE
+void spiffs_cache_init(
+ spiffs *fs);
+
+void spiffs_cache_drop_page(
+ spiffs *fs,
+ spiffs_page_ix pix);
+
+#if SPIFFS_CACHE_WR
+spiffs_cache_page *spiffs_cache_page_allocate_by_fd(
+ spiffs *fs,
+ spiffs_fd *fd);
+
+void spiffs_cache_fd_release(
+ spiffs *fs,
+ spiffs_cache_page *cp);
+
+spiffs_cache_page *spiffs_cache_page_get_by_fd(
+ spiffs *fs,
+ spiffs_fd *fd);
+#endif
+#endif
+
+int32_t spiffs_lookup_consistency_check(
+ spiffs *fs,
+ uint8_t check_all_objects);
+
+int32_t spiffs_page_consistency_check(
+ spiffs *fs);
+
+int32_t spiffs_object_index_consistency_check(
+ spiffs *fs);
+
+#endif /* SPIFFS_NUCLEUS_H_ */
diff --git a/fw/User/spiffs/src/test/main.c b/fw/User/spiffs/src/test/main.c
new file mode 100644
index 0000000..4d363d5
--- /dev/null
+++ b/fw/User/spiffs/src/test/main.c
@@ -0,0 +1,12 @@
+#include
+
+#ifndef NO_TEST
+#include "testrunner.h"
+#endif
+
+int main(int argc, char **args) {
+#ifndef NO_TEST
+ run_tests(argc, args);
+#endif
+ exit(EXIT_SUCCESS);
+}
diff --git a/fw/User/spiffs/src/test/params_test.h b/fw/User/spiffs/src/test/params_test.h
new file mode 100644
index 0000000..0e7710d
--- /dev/null
+++ b/fw/User/spiffs/src/test/params_test.h
@@ -0,0 +1,83 @@
+/*
+ * params_test.h
+ *
+ * Created on: May 26, 2013
+ * Author: petera
+ */
+
+#ifndef PARAMS_TEST_H_
+#define PARAMS_TEST_H_
+
+//////////////// TEST PARAMS ////////////////
+
+// default test total emulated spi flash size
+#define PHYS_FLASH_SIZE (16*1024*1024)
+// default test spiffs file system size
+#define SPIFFS_FLASH_SIZE (2*1024*1024)
+// default test spiffs file system offset in emulated spi flash
+#define SPIFFS_PHYS_ADDR (4*1024*1024)
+// default test sector size
+#define SECTOR_SIZE 65536
+// default test logical block size
+#define LOG_BLOCK (SECTOR_SIZE*2)
+// default test logical page size
+#define LOG_PAGE (SECTOR_SIZE/256)
+// default test number of filedescs
+#define DEFAULT_NUM_FD 16
+// default test number of cache pages
+#define DEFAULT_NUM_CACHE_PAGES 8
+
+// When testing, test bench create reference files for comparison on
+// the actual hard drive. By default, put these on ram drive for speed.
+#define TEST_PATH "/dev/shm/spiffs/test-data/"
+
+#define ASSERT(c, m) real_assert((c),(m), __FILE__, __LINE__);
+void real_assert(int c, const char *n, const char *file, int l);
+
+/////////// SPIFFS BUILD CONFIG ////////////
+
+// test using filesystem magic
+#ifndef SPIFFS_USE_MAGIC
+#define SPIFFS_USE_MAGIC 1
+#endif
+// test using filesystem magic length
+#ifndef SPIFFS_USE_MAGIC_LENGTH
+#define SPIFFS_USE_MAGIC_LENGTH 1
+#endif
+// test using extra param in callback
+#ifndef SPIFFS_HAL_CALLBACK_EXTRA
+#define SPIFFS_HAL_CALLBACK_EXTRA 1
+#endif
+// test using filehandle offset
+#ifndef SPIFFS_FILEHDL_OFFSET
+#define SPIFFS_FILEHDL_OFFSET 1
+// use this offset
+#define TEST_SPIFFS_FILEHDL_OFFSET 0x1000
+#endif
+
+#ifdef NO_TEST
+#define SPIFFS_LOCK(fs)
+#define SPIFFS_UNLOCK(fs)
+#else
+struct spiffs_t;
+extern void test_lock(struct spiffs_t *fs);
+extern void test_unlock(struct spiffs_t *fs);
+#define SPIFFS_LOCK(fs) test_lock(fs)
+#define SPIFFS_UNLOCK(fs) test_unlock(fs)
+#endif
+
+// dbg output
+#define SPIFFS_DBG(...) //printf(__VA_ARGS__)
+#define SPIFFS_GC_DBG(...) //printf(__VA_ARGS__)
+#define SPIFFS_CACHE_DBG(...) //printf(__VA_ARGS__)
+#define SPIFFS_CHECK_DBG(...) //printf(__VA_ARGS__)
+
+// needed types
+typedef signed int s32_t;
+typedef unsigned int u32_t;
+typedef signed short s16_t;
+typedef unsigned short u16_t;
+typedef signed char s8_t;
+typedef unsigned char u8_t;
+
+#endif /* PARAMS_TEST_H_ */
diff --git a/fw/User/spiffs/src/test/test_bugreports.c b/fw/User/spiffs/src/test/test_bugreports.c
new file mode 100644
index 0000000..8ea5f74
--- /dev/null
+++ b/fw/User/spiffs/src/test/test_bugreports.c
@@ -0,0 +1,680 @@
+/*
+ * test_bugreports.c
+ *
+ * Created on: Mar 8, 2015
+ * Author: petera
+ */
+
+
+
+#include "testrunner.h"
+#include "test_spiffs.h"
+#include "spiffs_nucleus.h"
+#include "spiffs.h"
+#include
+#include
+#include
+#include
+#include
+
+SUITE(bug_tests)
+static void setup() {
+ _setup_test_only();
+}
+static void teardown() {
+ _teardown();
+}
+
+TEST(nodemcu_full_fs_1) {
+ fs_reset_specific(0, 0, 4096*20, 4096, 4096, 256);
+
+ int res;
+ spiffs_file fd;
+
+ printf(" fill up system by writing one byte a lot\n");
+ fd = SPIFFS_open(FS, "test1.txt", SPIFFS_RDWR | SPIFFS_CREAT | SPIFFS_TRUNC, 0);
+ TEST_CHECK(fd > 0);
+ int i;
+ spiffs_stat s;
+ res = SPIFFS_OK;
+ for (i = 0; i < 100*1000; i++) {
+ u8_t buf = 'x';
+ res = SPIFFS_write(FS, fd, &buf, 1);
+ }
+
+ int errno = SPIFFS_errno(FS);
+ int res2 = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK(res2 == SPIFFS_OK);
+ printf(" >>> file %s size: %i\n", s.name, s.size);
+
+ TEST_CHECK(errno == SPIFFS_ERR_FULL);
+ SPIFFS_close(FS, fd);
+
+ printf(" remove big file\n");
+ res = SPIFFS_remove(FS, "test1.txt");
+
+ printf("res:%i errno:%i\n",res, SPIFFS_errno(FS));
+
+ TEST_CHECK(res == SPIFFS_OK);
+ res2 = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK(res2 < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_FILE_CLOSED);
+ res2 = SPIFFS_stat(FS, "test1.txt", &s);
+ TEST_CHECK(res2 < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_NOT_FOUND);
+
+ printf(" create small file\n");
+ fd = SPIFFS_open(FS, "test2.txt", SPIFFS_RDWR | SPIFFS_CREAT | SPIFFS_TRUNC, 0);
+ TEST_CHECK(fd > 0);
+ res = SPIFFS_OK;
+ for (i = 0; res >= 0 && i < 1000; i++) {
+ u8_t buf = 'x';
+ res = SPIFFS_write(FS, fd, &buf, 1);
+ }
+ TEST_CHECK(res >= SPIFFS_OK);
+
+ res2 = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK(res2 == SPIFFS_OK);
+ printf(" >>> file %s size: %i\n", s.name, s.size);
+
+ TEST_CHECK(s.size == 1000);
+ SPIFFS_close(FS, fd);
+
+ return TEST_RES_OK;
+
+} TEST_END
+
+TEST(nodemcu_full_fs_2) {
+ fs_reset_specific(0, 0, 4096*22, 4096, 4096, 256);
+
+ int res;
+ spiffs_file fd;
+
+ printf(" fill up system by writing one byte a lot\n");
+ fd = SPIFFS_open(FS, "test1.txt", SPIFFS_RDWR | SPIFFS_CREAT | SPIFFS_TRUNC, 0);
+ TEST_CHECK(fd > 0);
+ int i;
+ spiffs_stat s;
+ res = SPIFFS_OK;
+ for (i = 0; i < 100*1000; i++) {
+ u8_t buf = 'x';
+ res = SPIFFS_write(FS, fd, &buf, 1);
+ }
+
+ int errno = SPIFFS_errno(FS);
+ int res2 = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK(res2 == SPIFFS_OK);
+ printf(" >>> file %s size: %i\n", s.name, s.size);
+
+ TEST_CHECK(errno == SPIFFS_ERR_FULL);
+ SPIFFS_close(FS, fd);
+
+ res2 = SPIFFS_stat(FS, "test1.txt", &s);
+ TEST_CHECK(res2 == SPIFFS_OK);
+
+ SPIFFS_clearerr(FS);
+ printf(" create small file\n");
+ fd = SPIFFS_open(FS, "test2.txt", SPIFFS_RDWR | SPIFFS_CREAT | SPIFFS_TRUNC, 0);
+#if 0
+ // before gc in v3.1
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_OK);
+ TEST_CHECK(fd > 0);
+
+ for (i = 0; i < 1000; i++) {
+ u8_t buf = 'x';
+ res = SPIFFS_write(FS, fd, &buf, 1);
+ }
+
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_FULL);
+ res2 = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK(res2 == SPIFFS_OK);
+ printf(" >>> file %s size: %i\n", s.name, s.size);
+ TEST_CHECK(s.size == 0);
+ SPIFFS_clearerr(FS);
+#else
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_FULL);
+ SPIFFS_clearerr(FS);
+#endif
+ printf(" remove files\n");
+ res = SPIFFS_remove(FS, "test1.txt");
+ TEST_CHECK(res == SPIFFS_OK);
+#if 0
+ res = SPIFFS_remove(FS, "test2.txt");
+ TEST_CHECK(res == SPIFFS_OK);
+#endif
+
+ printf(" create medium file\n");
+ fd = SPIFFS_open(FS, "test3.txt", SPIFFS_RDWR | SPIFFS_CREAT | SPIFFS_TRUNC, 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_OK);
+ TEST_CHECK(fd > 0);
+
+ for (i = 0; i < 20*1000; i++) {
+ u8_t buf = 'x';
+ res = SPIFFS_write(FS, fd, &buf, 1);
+ }
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_OK);
+
+ res2 = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK(res2 == SPIFFS_OK);
+ printf(" >>> file %s size: %i\n", s.name, s.size);
+ TEST_CHECK(s.size == 20*1000);
+
+ return TEST_RES_OK;
+
+} TEST_END
+
+TEST(magic_test) {
+ // this test only works on default sizes
+ TEST_ASSERT(sizeof(spiffs_obj_id) == sizeof(u16_t));
+
+ // one obj lu page, not full
+ fs_reset_specific(0, 0, 4096*16, 4096, 4096*1, 128);
+ TEST_CHECK(SPIFFS_CHECK_MAGIC_POSSIBLE(FS));
+ // one obj lu page, full
+ fs_reset_specific(0, 0, 4096*16, 4096, 4096*2, 128);
+ TEST_CHECK(!SPIFFS_CHECK_MAGIC_POSSIBLE(FS));
+ // two obj lu pages, not full
+ fs_reset_specific(0, 0, 4096*16, 4096, 4096*4, 128);
+ TEST_CHECK(SPIFFS_CHECK_MAGIC_POSSIBLE(FS));
+
+ return TEST_RES_OK;
+
+} TEST_END
+
+TEST(nodemcu_309) {
+ fs_reset_specific(0, 0, 4096*20, 4096, 4096, 256);
+
+ int res;
+ spiffs_file fd;
+ int j;
+
+ for (j = 1; j <= 3; j++) {
+ char fname[32];
+ sprintf(fname, "20K%i.txt", j);
+ fd = SPIFFS_open(FS, fname, SPIFFS_RDWR | SPIFFS_CREAT | SPIFFS_TRUNC | SPIFFS_DIRECT, 0);
+ TEST_CHECK(fd > 0);
+ int i;
+ spiffs_stat s;
+ res = SPIFFS_OK;
+ u8_t err = 0;
+ for (i = 1; i <= 1280; i++) {
+ char *buf = "0123456789ABCDE\n";
+ res = SPIFFS_write(FS, fd, buf, strlen(buf));
+ if (!err && res < 0) {
+ printf("err @ %i,%i\n", i, j);
+ err = 1;
+ }
+ }
+ }
+
+ int errno = SPIFFS_errno(FS);
+ TEST_CHECK(errno == SPIFFS_ERR_FULL);
+
+ u32_t total;
+ u32_t used;
+
+ SPIFFS_info(FS, &total, &used);
+ printf("total:%i\nused:%i\nremain:%i\nerrno:%i\n", total, used, total-used, errno);
+ //TEST_CHECK(total-used < 11000); // disabled, depends on too many variables
+
+ spiffs_DIR d;
+ struct spiffs_dirent e;
+ struct spiffs_dirent *pe = &e;
+
+ SPIFFS_opendir(FS, "/", &d);
+ int spoon_guard = 0;
+ while ((pe = SPIFFS_readdir(&d, pe))) {
+ printf("%s [%04x] size:%i\n", pe->name, pe->obj_id, pe->size);
+ TEST_CHECK(spoon_guard++ < 3);
+ }
+ TEST_CHECK(spoon_guard == 3);
+ SPIFFS_closedir(&d);
+
+ return TEST_RES_OK;
+
+} TEST_END
+
+
+TEST(robert) {
+ // create a clean file system starting at address 0, 2 megabytes big,
+ // sector size 65536, block size 65536, page size 256
+ fs_reset_specific(0, 0, 1024*1024*2, 65536, 65536, 256);
+
+ int res;
+ spiffs_file fd;
+ char fname[32];
+
+ sprintf(fname, "test.txt");
+ fd = SPIFFS_open(FS, fname, SPIFFS_RDWR | SPIFFS_CREAT | SPIFFS_TRUNC, 0);
+ TEST_CHECK(fd > 0);
+ int i;
+ res = SPIFFS_OK;
+ char buf[500];
+ memset(buf, 0xaa, 500);
+ res = SPIFFS_write(FS, fd, buf, 500);
+ TEST_CHECK(res >= SPIFFS_OK);
+ SPIFFS_close(FS, fd);
+
+ int errno = SPIFFS_errno(FS);
+ TEST_CHECK(errno == SPIFFS_OK);
+
+ //SPIFFS_vis(FS);
+ // unmount
+ SPIFFS_unmount(FS);
+
+ // remount
+ res = fs_mount_specific(0, 1024*1024*2, 65536, 65536, 256);
+ TEST_CHECK(res== SPIFFS_OK);
+
+ //SPIFFS_vis(FS);
+
+ spiffs_stat s;
+ TEST_CHECK(SPIFFS_stat(FS, fname, &s) == SPIFFS_OK);
+ printf("file %s stat size %i\n", s.name, s.size);
+ TEST_CHECK(s.size == 500);
+
+ return TEST_RES_OK;
+
+} TEST_END
+
+
+TEST(spiffs_12) {
+ fs_reset_specific(0x4024c000, 0x4024c000 + 0, 192*1024, 4096, 4096*2, 256);
+
+ int res;
+ spiffs_file fd;
+ int j = 1;
+
+ while (1) {
+ char fname[32];
+ sprintf(fname, "file%i.txt", j);
+ fd = SPIFFS_open(FS, fname, SPIFFS_RDWR | SPIFFS_CREAT | SPIFFS_TRUNC | SPIFFS_DIRECT, 0);
+ if (fd <=0) break;
+
+ int i;
+ res = SPIFFS_OK;
+ for (i = 1; i <= 100; i++) {
+ char *buf = "0123456789ABCDE\n";
+ res = SPIFFS_write(FS, fd, buf, strlen(buf));
+ if (res < 0) break;
+ }
+ SPIFFS_close(FS, fd);
+ j++;
+ }
+
+ int errno = SPIFFS_errno(FS);
+ TEST_CHECK(errno == SPIFFS_ERR_FULL);
+
+ u32_t total;
+ u32_t used;
+
+ SPIFFS_info(FS, &total, &used);
+ printf("total:%i (%iK)\nused:%i (%iK)\nremain:%i (%iK)\nerrno:%i\n", total, total/1024, used, used/1024, total-used, (total-used)/1024, errno);
+
+ spiffs_DIR d;
+ struct spiffs_dirent e;
+ struct spiffs_dirent *pe = &e;
+
+ SPIFFS_opendir(FS, "/", &d);
+ while ((pe = SPIFFS_readdir(&d, pe))) {
+ printf("%s [%04x] size:%i\n", pe->name, pe->obj_id, pe->size);
+ }
+ SPIFFS_closedir(&d);
+
+ //SPIFFS_vis(FS);
+
+ //dump_page(FS, 0);
+ //dump_page(FS, 1);
+
+ return TEST_RES_OK;
+
+} TEST_END
+
+
+TEST(zero_sized_file_44) {
+ fs_reset();
+
+ spiffs_file fd = SPIFFS_open(FS, "zero", SPIFFS_RDWR | SPIFFS_CREAT, 0);
+ TEST_CHECK_GE(fd, 0);
+
+ int res = SPIFFS_close(FS, fd);
+ TEST_CHECK_GE(res, 0);
+
+ fd = SPIFFS_open(FS, "zero", SPIFFS_RDWR, 0);
+ TEST_CHECK_GE(fd, 0);
+
+ u8_t buf[8];
+ res = SPIFFS_read(FS, fd, buf, 8);
+ TEST_CHECK_LT(res, 0);
+ TEST_CHECK_EQ(SPIFFS_errno(FS), SPIFFS_ERR_END_OF_OBJECT);
+
+ res = SPIFFS_read(FS, fd, buf, 0);
+ TEST_CHECK_GE(res, 0);
+
+ res = SPIFFS_read(FS, fd, buf, 0);
+ TEST_CHECK_GE(res, 0);
+
+ buf[0] = 1;
+ buf[1] = 2;
+
+ res = SPIFFS_write(FS, fd, buf, 2);
+ TEST_CHECK_EQ(res, 2);
+
+ res = SPIFFS_lseek(FS, fd, 0, SPIFFS_SEEK_SET);
+ TEST_CHECK_GE(res, 0);
+
+ u8_t b;
+ res = SPIFFS_read(FS, fd, &b, 1);
+ TEST_CHECK_EQ(res, 1);
+ TEST_CHECK_EQ(b, 1);
+
+ res = SPIFFS_read(FS, fd, &b, 1);
+ TEST_CHECK_EQ(res, 1);
+ TEST_CHECK_EQ(b, 2);
+
+ res = SPIFFS_read(FS, fd, buf, 8);
+ TEST_CHECK_LT(res, 0);
+ TEST_CHECK_EQ(SPIFFS_errno(FS), SPIFFS_ERR_END_OF_OBJECT);
+
+ return TEST_RES_OK;
+} TEST_END
+
+#if !SPIFFS_READ_ONLY
+TEST(truncate_48) {
+ fs_reset();
+
+ u32_t len = SPIFFS_DATA_PAGE_SIZE(FS)/2;
+
+ s32_t res = test_create_and_write_file("small", len, len);
+ TEST_CHECK_GE(res, 0);
+
+ spiffs_file fd = SPIFFS_open(FS, "small", SPIFFS_RDWR, 0);
+ TEST_CHECK_GE(fd, 0);
+
+ spiffs_fd *desc;
+#if SPIFFS_FILEHDL_OFFSET
+ res = spiffs_fd_get(FS, fd - TEST_SPIFFS_FILEHDL_OFFSET, &desc);
+#else
+ res = spiffs_fd_get(FS, fd, &desc);
+#endif
+
+ TEST_CHECK_GE(res, 0);
+
+ TEST_CHECK_EQ(desc->size, len);
+
+ u32_t new_len = len/2;
+ res = spiffs_object_truncate(desc, new_len, 0);
+ TEST_CHECK_GE(res, 0);
+
+ TEST_CHECK_EQ(desc->size, new_len);
+
+ res = SPIFFS_close(FS, fd);
+ TEST_CHECK_GE(res, 0);
+
+ spiffs_stat s;
+ res = SPIFFS_stat(FS, "small", &s);
+ TEST_CHECK_GE(res, 0);
+ TEST_CHECK_EQ(s.size, new_len);
+
+ res = SPIFFS_remove(FS, "small");
+ TEST_CHECK_GE(res, 0);
+
+ fd = SPIFFS_open(FS, "small", SPIFFS_RDWR, 0);
+ TEST_CHECK_LT(fd, 0);
+ TEST_CHECK_EQ(SPIFFS_errno(FS), SPIFFS_ERR_NOT_FOUND);
+
+ return TEST_RES_OK;
+} TEST_END
+#endif
+
+TEST(eof_tell_72) {
+ fs_reset();
+
+ s32_t res;
+
+ spiffs_file fd = SPIFFS_open(FS, "file", SPIFFS_CREAT | SPIFFS_RDWR | SPIFFS_APPEND, 0);
+ TEST_CHECK_GT(fd, 0);
+ TEST_CHECK_EQ(SPIFFS_eof(FS, fd), 1);
+ TEST_CHECK_EQ(SPIFFS_tell(FS, fd), 0);
+
+ res = SPIFFS_write(FS, fd, "test", 4);
+ TEST_CHECK_EQ(res, 4);
+ TEST_CHECK_EQ(SPIFFS_eof(FS, fd), 1);
+ TEST_CHECK_EQ(SPIFFS_tell(FS, fd), 4);
+
+ res = SPIFFS_fflush(FS, fd);
+ TEST_CHECK_EQ(res, SPIFFS_OK);
+ TEST_CHECK_EQ(SPIFFS_eof(FS, fd), 1);
+ TEST_CHECK_EQ(SPIFFS_tell(FS, fd), 4);
+
+ res = SPIFFS_lseek(FS, fd, 2, SPIFFS_SEEK_SET);
+ TEST_CHECK_EQ(res, 2);
+ TEST_CHECK_EQ(SPIFFS_eof(FS, fd), 0);
+ TEST_CHECK_EQ(SPIFFS_tell(FS, fd), 2);
+
+ res = SPIFFS_write(FS, fd, "test", 4);
+ TEST_CHECK_EQ(res, 4);
+ TEST_CHECK_EQ(SPIFFS_eof(FS, fd), 1);
+ TEST_CHECK_EQ(SPIFFS_tell(FS, fd), 8);
+
+ res = SPIFFS_fflush(FS, fd);
+ TEST_CHECK_EQ(res, SPIFFS_OK);
+ TEST_CHECK_EQ(SPIFFS_eof(FS, fd), 1);
+ TEST_CHECK_EQ(SPIFFS_tell(FS, fd), 8);
+
+ res = SPIFFS_close(FS, fd);
+ TEST_CHECK_EQ(res, SPIFFS_OK);
+ TEST_CHECK_LT(SPIFFS_eof(FS, fd), SPIFFS_OK);
+ TEST_CHECK_LT(SPIFFS_tell(FS, fd), SPIFFS_OK);
+
+ fd = SPIFFS_open(FS, "file", SPIFFS_RDWR, 0);
+ TEST_CHECK_GT(fd, 0);
+ TEST_CHECK_EQ(SPIFFS_eof(FS, fd), 0);
+ TEST_CHECK_EQ(SPIFFS_tell(FS, fd), 0);
+
+ res = SPIFFS_lseek(FS, fd, 2, SPIFFS_SEEK_SET);
+ TEST_CHECK_EQ(res, 2);
+ TEST_CHECK_EQ(SPIFFS_eof(FS, fd), 0);
+ TEST_CHECK_EQ(SPIFFS_tell(FS, fd), 2);
+
+ res = SPIFFS_write(FS, fd, "test", 4);
+ TEST_CHECK_EQ(res, 4);
+ TEST_CHECK_EQ(SPIFFS_eof(FS, fd), 0);
+ TEST_CHECK_EQ(SPIFFS_tell(FS, fd), 6);
+
+ res = SPIFFS_fflush(FS, fd);
+ TEST_CHECK_EQ(res, SPIFFS_OK);
+ TEST_CHECK_EQ(SPIFFS_eof(FS, fd), 0);
+ TEST_CHECK_EQ(SPIFFS_tell(FS, fd), 6);
+
+ res = SPIFFS_lseek(FS, fd, 0, SPIFFS_SEEK_END);
+ TEST_CHECK_EQ(res, 8);
+ TEST_CHECK_EQ(SPIFFS_eof(FS, fd), 1);
+ TEST_CHECK_EQ(SPIFFS_tell(FS, fd), 8);
+
+ return TEST_RES_OK;
+} TEST_END
+
+TEST(spiffs_dup_file_74) {
+ fs_reset_specific(0, 0, 64*1024, 4096, 4096*2, 256);
+ {
+ spiffs_file fd = SPIFFS_open(FS, "/config", SPIFFS_CREAT | SPIFFS_TRUNC | SPIFFS_WRONLY, 0);
+ TEST_CHECK(fd >= 0);
+ char buf[5];
+ strncpy(buf, "test", sizeof(buf));
+ SPIFFS_write(FS, fd, buf, 4);
+ SPIFFS_close(FS, fd);
+ }
+ {
+ spiffs_file fd = SPIFFS_open(FS, "/data", SPIFFS_CREAT | SPIFFS_TRUNC | SPIFFS_WRONLY, 0);
+ TEST_CHECK(fd >= 0);
+ SPIFFS_close(FS, fd);
+ }
+ {
+ spiffs_file fd = SPIFFS_open(FS, "/config", SPIFFS_RDONLY, 0);
+ TEST_CHECK(fd >= 0);
+ char buf[5];
+ int cb = SPIFFS_read(FS, fd, buf, sizeof(buf));
+ TEST_CHECK(cb > 0 && cb < sizeof(buf));
+ TEST_CHECK(strncmp("test", buf, cb) == 0);
+ SPIFFS_close(FS, fd);
+ }
+ {
+ spiffs_file fd = SPIFFS_open(FS, "/data", SPIFFS_CREAT | SPIFFS_TRUNC | SPIFFS_WRONLY, 0);
+ TEST_CHECK(fd >= 0);
+ spiffs_stat stat;
+ SPIFFS_fstat(FS, fd, &stat);
+ if (strcmp((const char*) stat.name, "/data") != 0) {
+ // oops! lets check the list of files...
+ spiffs_DIR dir;
+ SPIFFS_opendir(FS, "/", &dir);
+ struct spiffs_dirent dirent;
+ while (SPIFFS_readdir(&dir, &dirent)) {
+ printf("%s\n", dirent.name);
+ }
+ // this will print "/config" two times
+ TEST_CHECK(0);
+ }
+ SPIFFS_close(FS, fd);
+ }
+ return TEST_RES_OK;
+} TEST_END
+
+TEST(temporal_fd_cache) {
+ fs_reset_specific(0, 0, 1024*1024, 4096, 2*4096, 256);
+ spiffs_file fd;
+ int res;
+ (FS)->fd_count = 4;
+
+ char *fcss = "blaha.css";
+
+ char *fhtml[] = {
+ "index.html", "cykel.html", "bloja.html", "drivmedel.html", "smorgasbord.html",
+ "ombudsman.html", "fubbick.html", "paragrod.html"
+ };
+
+ const int hit_probabilities[] = {
+ 25, 20, 16, 12, 10, 8, 5, 4
+ };
+
+ const int runs = 10000;
+
+ // create our webserver files
+ TEST_CHECK_EQ(test_create_and_write_file(fcss, 2000, 256), SPIFFS_OK);
+ TEST_CHECK_EQ(test_create_and_write_file(fhtml[0], 4000, 256), SPIFFS_OK);
+ TEST_CHECK_EQ(test_create_and_write_file(fhtml[1], 3000, 256), SPIFFS_OK);
+ TEST_CHECK_EQ(test_create_and_write_file(fhtml[2], 2000, 256), SPIFFS_OK);
+ TEST_CHECK_EQ(test_create_and_write_file(fhtml[3], 1000, 256), SPIFFS_OK);
+ TEST_CHECK_EQ(test_create_and_write_file(fhtml[4], 1500, 256), SPIFFS_OK);
+ TEST_CHECK_EQ(test_create_and_write_file(fhtml[5], 3000, 256), SPIFFS_OK);
+ TEST_CHECK_EQ(test_create_and_write_file(fhtml[6], 2000, 256), SPIFFS_OK);
+ TEST_CHECK_EQ(test_create_and_write_file(fhtml[7], 3500, 256), SPIFFS_OK);
+
+ clear_flash_ops_log();
+
+ int run = 0;
+ do {
+ u8_t buf[256];
+
+ // open & read an html
+ int dice = rand() % 100;
+ int probability = 0;
+ int html_ix = 0;
+ do {
+ probability += hit_probabilities[html_ix];
+ if (dice <= probability) {
+ break;
+ }
+ html_ix++;
+ } while(probability < 100);
+
+ TEST_CHECK_EQ(read_and_verify(fhtml[html_ix]), SPIFFS_OK);
+
+ // open & read css
+ TEST_CHECK_EQ(read_and_verify(fcss), SPIFFS_OK);
+ } while (run ++ < runs);
+
+ return TEST_RES_OK;
+} TEST_END
+
+#if 0
+TEST(spiffs_hidden_file_90) {
+ fs_mount_dump("imgs/90.hidden_file.spiffs", 0, 0, 1*1024*1024, 4096, 4096, 128);
+
+ SPIFFS_vis(FS);
+
+ dump_page(FS, 1);
+ dump_page(FS, 0x8fe);
+ dump_page(FS, 0x8ff);
+
+ {
+ spiffs_DIR dir;
+ SPIFFS_opendir(FS, "/", &dir);
+ struct spiffs_dirent dirent;
+ while (SPIFFS_readdir(&dir, &dirent)) {
+ printf("%-32s sz:%-7i obj_id:%08x pix:%08x\n", dirent.name, dirent.size, dirent.obj_id, dirent.pix);
+ }
+ }
+
+ printf("remove cli.bin res %i\n", SPIFFS_remove(FS, "cli.bin"));
+
+ {
+ spiffs_DIR dir;
+ SPIFFS_opendir(FS, "/", &dir);
+ struct spiffs_dirent dirent;
+ while (SPIFFS_readdir(&dir, &dirent)) {
+ printf("%-32s sz:%-7i obj_id:%08x pix:%08x\n", dirent.name, dirent.size, dirent.obj_id, dirent.pix);
+ }
+ }
+ return TEST_RES_OK;
+
+} TEST_END
+#endif
+#if 0
+TEST(null_deref_check_93) {
+ fs_mount_dump("imgs/93.dump.bin", 0, 0, 2*1024*1024, 4096, 4096, 256);
+
+ //int res = SPIFFS_open(FS, "d43.fw", SPIFFS_TRUNC | SPIFFS_CREAT | SPIFFS_WRONLY, 0);
+ //TEST_CHECK_GE(res, SPIFFS_OK);
+
+ SPIFFS_vis(FS);
+
+ printf("\n\n-------------------------------------------------\n\n");
+
+ SPIFFS_check(FS);
+ //fs_store_dump("imgs/93.dump.checked.bin");
+
+ SPIFFS_vis(FS);
+
+ printf("\n\n-------------------------------------------------\n\n");
+
+ SPIFFS_check(FS);
+
+ SPIFFS_vis(FS);
+ printf("\n\n-------------------------------------------------\n\n");
+
+
+
+ return TEST_RES_OK;
+} TEST_END
+#endif
+
+SUITE_TESTS(bug_tests)
+ ADD_TEST(nodemcu_full_fs_1)
+ ADD_TEST(nodemcu_full_fs_2)
+ ADD_TEST(magic_test)
+ ADD_TEST(nodemcu_309)
+ ADD_TEST(robert)
+ ADD_TEST(spiffs_12)
+ ADD_TEST(zero_sized_file_44)
+ ADD_TEST(truncate_48)
+ ADD_TEST(eof_tell_72)
+ ADD_TEST(spiffs_dup_file_74)
+ ADD_TEST(temporal_fd_cache)
+#if 0
+ ADD_TEST(spiffs_hidden_file_90)
+#endif
+#if 0
+ ADD_TEST(null_deref_check_93)
+#endif
+SUITE_END(bug_tests)
diff --git a/fw/User/spiffs/src/test/test_check.c b/fw/User/spiffs/src/test/test_check.c
new file mode 100644
index 0000000..15865c4
--- /dev/null
+++ b/fw/User/spiffs/src/test/test_check.c
@@ -0,0 +1,427 @@
+/*
+ * test_dev.c
+ *
+ * Created on: Jul 14, 2013
+ * Author: petera
+ */
+
+
+#include "testrunner.h"
+#include "test_spiffs.h"
+#include "spiffs_nucleus.h"
+#include "spiffs.h"
+#include
+#include
+#include
+#include
+#include
+
+
+SUITE(check_tests)
+static void setup() {
+ _setup();
+}
+static void teardown() {
+ _teardown();
+}
+
+TEST(evil_write) {
+ fs_set_validate_flashing(0);
+ printf("writing corruption to block 1 data range (leaving lu intact)\n");
+ u32_t data_range = SPIFFS_CFG_LOG_BLOCK_SZ(FS) -
+ SPIFFS_CFG_LOG_PAGE_SZ(FS) * (SPIFFS_OBJ_LOOKUP_PAGES(FS));
+ u8_t *corruption = malloc(data_range);
+ memrand(corruption, data_range);
+ u32_t addr = 0 * SPIFFS_CFG_LOG_PAGE_SZ(FS) * SPIFFS_OBJ_LOOKUP_PAGES(FS);
+ area_write(addr, corruption, data_range);
+ free(corruption);
+
+ int size = SPIFFS_DATA_PAGE_SIZE(FS)*3;
+ int res = test_create_and_write_file("file", size, size);
+
+ printf("CHECK1-----------------\n");
+ SPIFFS_check(FS);
+ printf("CHECK2-----------------\n");
+ SPIFFS_check(FS);
+ printf("CHECK3-----------------\n");
+ SPIFFS_check(FS);
+
+ res = test_create_and_write_file("file2", size, size);
+ TEST_CHECK(res >= 0);
+
+ return TEST_RES_OK;
+} TEST_END
+
+
+TEST(lu_check1) {
+ int size = SPIFFS_DATA_PAGE_SIZE(FS)*3;
+ int res = test_create_and_write_file("file", size, size);
+ TEST_CHECK(res >= 0);
+ res = read_and_verify("file");
+ TEST_CHECK(res >= 0);
+
+ spiffs_file fd = SPIFFS_open(FS, "file", SPIFFS_RDONLY, 0);
+ TEST_CHECK(fd > 0);
+ spiffs_stat s;
+ res = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK(res >= 0);
+ SPIFFS_close(FS, fd);
+
+ // modify lu entry data page index 1
+ spiffs_page_ix pix;
+ res = spiffs_obj_lu_find_id_and_span(FS, s.obj_id & ~SPIFFS_OBJ_ID_IX_FLAG, 1, 0, &pix);
+ TEST_CHECK(res >= 0);
+
+ // reset lu entry to being erased, but keep page data
+ spiffs_obj_id obj_id = SPIFFS_OBJ_ID_DELETED;
+ spiffs_block_ix bix = SPIFFS_BLOCK_FOR_PAGE(FS, pix);
+ int entry = SPIFFS_OBJ_LOOKUP_ENTRY_FOR_PAGE(FS, pix);
+ u32_t addr = SPIFFS_BLOCK_TO_PADDR(FS, bix) + entry*sizeof(spiffs_obj_id);
+
+ area_write(addr, (u8_t*)&obj_id, sizeof(spiffs_obj_id));
+
+#if SPIFFS_CACHE
+ spiffs_cache *cache = spiffs_get_cache(FS);
+ cache->cpage_use_map = 0;
+#endif
+ SPIFFS_check(FS);
+
+ return TEST_RES_OK;
+} TEST_END
+
+
+TEST(page_cons1) {
+ int size = SPIFFS_DATA_PAGE_SIZE(FS)*3;
+ int res = test_create_and_write_file("file", size, size);
+ TEST_CHECK(res >= 0);
+ res = read_and_verify("file");
+ TEST_CHECK(res >= 0);
+
+ spiffs_file fd = SPIFFS_open(FS, "file", SPIFFS_RDONLY, 0);
+ TEST_CHECK(fd > 0);
+ spiffs_stat s;
+ res = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK(res >= 0);
+ SPIFFS_close(FS, fd);
+
+ // modify object index, find object index header
+ spiffs_page_ix pix;
+ res = spiffs_obj_lu_find_id_and_span(FS, s.obj_id | SPIFFS_OBJ_ID_IX_FLAG, 0, 0, &pix);
+ TEST_CHECK(res >= 0);
+
+ // set object index entry 2 to a bad page
+ u32_t addr = SPIFFS_PAGE_TO_PADDR(FS, pix) + sizeof(spiffs_page_object_ix_header) + 0 * sizeof(spiffs_page_ix);
+ spiffs_page_ix bad_pix_ref = 0x55;
+ area_write(addr, (u8_t*)&bad_pix_ref, sizeof(spiffs_page_ix));
+ area_write(addr + sizeof(spiffs_page_ix), (u8_t*)&bad_pix_ref, sizeof(spiffs_page_ix));
+
+ // delete all cache
+#if SPIFFS_CACHE
+ spiffs_cache *cache = spiffs_get_cache(FS);
+ cache->cpage_use_map = 0;
+#endif
+
+ SPIFFS_check(FS);
+
+ res = read_and_verify("file");
+ TEST_CHECK(res >= 0);
+
+ return TEST_RES_OK;
+} TEST_END
+
+
+TEST(page_cons2) {
+ int size = SPIFFS_DATA_PAGE_SIZE(FS)*3;
+ int res = test_create_and_write_file("file", size, size);
+ TEST_CHECK(res >= 0);
+ res = read_and_verify("file");
+ TEST_CHECK(res >= 0);
+
+ spiffs_file fd = SPIFFS_open(FS, "file", SPIFFS_RDONLY, 0);
+ TEST_CHECK(fd > 0);
+ spiffs_stat s;
+ res = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK(res >= 0);
+ SPIFFS_close(FS, fd);
+
+ // modify object index, find object index header
+ spiffs_page_ix pix;
+ res = spiffs_obj_lu_find_id_and_span(FS, s.obj_id | SPIFFS_OBJ_ID_IX_FLAG, 0, 0, &pix);
+ TEST_CHECK(res >= 0);
+
+ // find data page span index 0
+ spiffs_page_ix dpix;
+ res = spiffs_obj_lu_find_id_and_span(FS, s.obj_id & ~SPIFFS_OBJ_ID_IX_FLAG, 0, 0, &dpix);
+ TEST_CHECK(res >= 0);
+
+ // set object index entry 1+2 to a data page 0
+ u32_t addr = SPIFFS_PAGE_TO_PADDR(FS, pix) + sizeof(spiffs_page_object_ix_header) + 1 * sizeof(spiffs_page_ix);
+ spiffs_page_ix bad_pix_ref = dpix;
+ area_write(addr, (u8_t*)&bad_pix_ref, sizeof(spiffs_page_ix));
+ area_write(addr+sizeof(spiffs_page_ix), (u8_t*)&bad_pix_ref, sizeof(spiffs_page_ix));
+
+ // delete all cache
+#if SPIFFS_CACHE
+ spiffs_cache *cache = spiffs_get_cache(FS);
+ cache->cpage_use_map = 0;
+#endif
+
+ SPIFFS_check(FS);
+
+ res = read_and_verify("file");
+ TEST_CHECK(res >= 0);
+
+ return TEST_RES_OK;
+} TEST_END
+
+
+
+TEST(page_cons3) {
+ int size = SPIFFS_DATA_PAGE_SIZE(FS)*3;
+ int res = test_create_and_write_file("file", size, size);
+ TEST_CHECK(res >= 0);
+ res = read_and_verify("file");
+ TEST_CHECK(res >= 0);
+
+ spiffs_file fd = SPIFFS_open(FS, "file", SPIFFS_RDONLY, 0);
+ TEST_CHECK(fd > 0);
+ spiffs_stat s;
+ res = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK(res >= 0);
+ SPIFFS_close(FS, fd);
+
+ // modify object index, find object index header
+ spiffs_page_ix pix;
+ res = spiffs_obj_lu_find_id_and_span(FS, s.obj_id | SPIFFS_OBJ_ID_IX_FLAG, 0, 0, &pix);
+ TEST_CHECK(res >= 0);
+
+ // set object index entry 1+2 lookup page
+ u32_t addr = SPIFFS_PAGE_TO_PADDR(FS, pix) + sizeof(spiffs_page_object_ix_header) + 1 * sizeof(spiffs_page_ix);
+ spiffs_page_ix bad_pix_ref = SPIFFS_PAGES_PER_BLOCK(FS) * (*FS.block_count - 2);
+ area_write(addr, (u8_t*)&bad_pix_ref, sizeof(spiffs_page_ix));
+ area_write(addr+sizeof(spiffs_page_ix), (u8_t*)&bad_pix_ref, sizeof(spiffs_page_ix));
+
+ // delete all cache
+#if SPIFFS_CACHE
+ spiffs_cache *cache = spiffs_get_cache(FS);
+ cache->cpage_use_map = 0;
+#endif
+
+ SPIFFS_check(FS);
+
+ res = read_and_verify("file");
+ TEST_CHECK(res >= 0);
+
+ return TEST_RES_OK;
+} TEST_END
+
+
+TEST(page_cons_final) {
+ int size = SPIFFS_DATA_PAGE_SIZE(FS)*3;
+ int res = test_create_and_write_file("file", size, size);
+ TEST_CHECK(res >= 0);
+ res = read_and_verify("file");
+ TEST_CHECK(res >= 0);
+
+ spiffs_file fd = SPIFFS_open(FS, "file", SPIFFS_RDONLY, 0);
+ TEST_CHECK(fd > 0);
+ spiffs_stat s;
+ res = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK(res >= 0);
+ SPIFFS_close(FS, fd);
+
+ // modify page header, make unfinalized
+ spiffs_page_ix pix;
+ res = spiffs_obj_lu_find_id_and_span(FS, s.obj_id & ~SPIFFS_OBJ_ID_IX_FLAG, 1, 0, &pix);
+ TEST_CHECK(res >= 0);
+
+ // set page span ix 1 as unfinalized
+ u32_t addr = SPIFFS_PAGE_TO_PADDR(FS, pix) + offsetof(spiffs_page_header, flags);
+ u8_t flags;
+ area_read(addr, (u8_t*)&flags, 1);
+ flags |= SPIFFS_PH_FLAG_FINAL;
+ area_write(addr, (u8_t*)&flags, 1);
+
+ // delete all cache
+#if SPIFFS_CACHE
+ spiffs_cache *cache = spiffs_get_cache(FS);
+ cache->cpage_use_map = 0;
+#endif
+
+ SPIFFS_check(FS);
+
+ res = read_and_verify("file");
+ TEST_CHECK(res >= 0);
+
+ return TEST_RES_OK;
+} TEST_END
+
+
+TEST(index_cons1) {
+ int size = SPIFFS_DATA_PAGE_SIZE(FS)*SPIFFS_PAGES_PER_BLOCK(FS);
+ int res = test_create_and_write_file("file", size, size);
+ TEST_CHECK(res >= 0);
+ res = read_and_verify("file");
+ TEST_CHECK(res >= 0);
+
+ spiffs_file fd = SPIFFS_open(FS, "file", SPIFFS_RDONLY, 0);
+ TEST_CHECK(fd > 0);
+ spiffs_stat s;
+ res = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK(res >= 0);
+ SPIFFS_close(FS, fd);
+
+ // modify lu entry data page index header
+ spiffs_page_ix pix;
+ res = spiffs_obj_lu_find_id_and_span(FS, s.obj_id | SPIFFS_OBJ_ID_IX_FLAG, 0, 0, &pix);
+ TEST_CHECK(res >= 0);
+
+ printf(" deleting lu entry pix %04x\n", pix);
+ // reset lu entry to being erased, but keep page data
+ spiffs_obj_id obj_id = SPIFFS_OBJ_ID_DELETED;
+ spiffs_block_ix bix = SPIFFS_BLOCK_FOR_PAGE(FS, pix);
+ int entry = SPIFFS_OBJ_LOOKUP_ENTRY_FOR_PAGE(FS, pix);
+ u32_t addr = SPIFFS_BLOCK_TO_PADDR(FS, bix) + entry * sizeof(spiffs_obj_id);
+
+ area_write(addr, (u8_t*)&obj_id, sizeof(spiffs_obj_id));
+
+#if SPIFFS_CACHE
+ spiffs_cache *cache = spiffs_get_cache(FS);
+ cache->cpage_use_map = 0;
+#endif
+ SPIFFS_check(FS);
+
+ res = read_and_verify("file");
+ TEST_CHECK(res >= 0);
+
+ return TEST_RES_OK;
+} TEST_END
+
+
+TEST(index_cons2) {
+ int size = SPIFFS_DATA_PAGE_SIZE(FS)*SPIFFS_PAGES_PER_BLOCK(FS);
+ int res = test_create_and_write_file("file", size, size);
+ TEST_CHECK(res >= 0);
+ res = read_and_verify("file");
+ TEST_CHECK(res >= 0);
+
+ spiffs_file fd = SPIFFS_open(FS, "file", SPIFFS_RDONLY, 0);
+ TEST_CHECK(fd > 0);
+ spiffs_stat s;
+ res = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK(res >= 0);
+ SPIFFS_close(FS, fd);
+
+ // modify lu entry data page index header
+ spiffs_page_ix pix;
+ res = spiffs_obj_lu_find_id_and_span(FS, s.obj_id | SPIFFS_OBJ_ID_IX_FLAG, 0, 0, &pix);
+ TEST_CHECK(res >= 0);
+
+ printf(" writing lu entry for index page, ix %04x, as data page\n", pix);
+ spiffs_obj_id obj_id = 0x1234;
+ spiffs_block_ix bix = SPIFFS_BLOCK_FOR_PAGE(FS, pix);
+ int entry = SPIFFS_OBJ_LOOKUP_ENTRY_FOR_PAGE(FS, pix);
+ u32_t addr = SPIFFS_BLOCK_TO_PADDR(FS, bix) + entry * sizeof(spiffs_obj_id);
+
+ area_write(addr, (u8_t*)&obj_id, sizeof(spiffs_obj_id));
+
+#if SPIFFS_CACHE
+ spiffs_cache *cache = spiffs_get_cache(FS);
+ cache->cpage_use_map = 0;
+#endif
+ SPIFFS_check(FS);
+
+ res = read_and_verify("file");
+ TEST_CHECK(res >= 0);
+
+ return TEST_RES_OK;
+} TEST_END
+
+
+TEST(index_cons3) {
+ int size = SPIFFS_DATA_PAGE_SIZE(FS)*SPIFFS_PAGES_PER_BLOCK(FS);
+ int res = test_create_and_write_file("file", size, size);
+ TEST_CHECK(res >= 0);
+ res = read_and_verify("file");
+ TEST_CHECK(res >= 0);
+
+ spiffs_file fd = SPIFFS_open(FS, "file", SPIFFS_RDONLY, 0);
+ TEST_CHECK(fd > 0);
+ spiffs_stat s;
+ res = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK(res >= 0);
+ SPIFFS_close(FS, fd);
+
+ // modify lu entry data page index header
+ spiffs_page_ix pix;
+ res = spiffs_obj_lu_find_id_and_span(FS, s.obj_id | SPIFFS_OBJ_ID_IX_FLAG, 0, 0, &pix);
+ TEST_CHECK(res >= 0);
+
+ printf(" setting lu entry pix %04x to another index page\n", pix);
+ // reset lu entry to being erased, but keep page data
+ spiffs_obj_id obj_id = 1234 | SPIFFS_OBJ_ID_IX_FLAG;
+ spiffs_block_ix bix = SPIFFS_BLOCK_FOR_PAGE(FS, pix);
+ int entry = SPIFFS_OBJ_LOOKUP_ENTRY_FOR_PAGE(FS, pix);
+ u32_t addr = SPIFFS_BLOCK_TO_PADDR(FS, bix) + entry * sizeof(spiffs_obj_id);
+
+ area_write(addr, (u8_t*)&obj_id, sizeof(spiffs_obj_id));
+
+#if SPIFFS_CACHE
+ spiffs_cache *cache = spiffs_get_cache(FS);
+ cache->cpage_use_map = 0;
+#endif
+ SPIFFS_check(FS);
+
+ res = read_and_verify("file");
+ TEST_CHECK(res >= 0);
+
+ return TEST_RES_OK;
+} TEST_END
+
+TEST(index_cons4) {
+ int size = SPIFFS_DATA_PAGE_SIZE(FS)*SPIFFS_PAGES_PER_BLOCK(FS);
+ int res = test_create_and_write_file("file", size, size);
+ TEST_CHECK(res >= 0);
+ res = read_and_verify("file");
+ TEST_CHECK(res >= 0);
+
+ spiffs_file fd = SPIFFS_open(FS, "file", SPIFFS_RDONLY, 0);
+ TEST_CHECK(fd > 0);
+ spiffs_stat s;
+ res = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK(res >= 0);
+ SPIFFS_close(FS, fd);
+
+ // modify lu entry data page index header, flags
+ spiffs_page_ix pix;
+ res = spiffs_obj_lu_find_id_and_span(FS, s.obj_id | SPIFFS_OBJ_ID_IX_FLAG, 0, 0, &pix);
+ TEST_CHECK(res >= 0);
+
+ printf(" cue objix hdr deletion in page %04x\n", pix);
+ // set flags as deleting ix header
+ u32_t addr = SPIFFS_PAGE_TO_PADDR(FS, pix) + offsetof(spiffs_page_header, flags);
+ u8_t flags = 0xff & ~(SPIFFS_PH_FLAG_FINAL | SPIFFS_PH_FLAG_USED | SPIFFS_PH_FLAG_INDEX | SPIFFS_PH_FLAG_IXDELE);
+
+ area_write(addr, (u8_t*)&flags, 1);
+
+#if SPIFFS_CACHE
+ spiffs_cache *cache = spiffs_get_cache(FS);
+ cache->cpage_use_map = 0;
+#endif
+ SPIFFS_check(FS);
+
+ return TEST_RES_OK;
+} TEST_END
+
+SUITE_TESTS(check_tests)
+ ADD_TEST(evil_write)
+ ADD_TEST(lu_check1)
+ ADD_TEST(page_cons1)
+ ADD_TEST(page_cons2)
+ ADD_TEST(page_cons3)
+ ADD_TEST(page_cons_final)
+ ADD_TEST(index_cons1)
+ ADD_TEST(index_cons2)
+ ADD_TEST(index_cons3)
+ ADD_TEST(index_cons4)
+SUITE_END(check_tests)
diff --git a/fw/User/spiffs/src/test/test_dev.c b/fw/User/spiffs/src/test/test_dev.c
new file mode 100644
index 0000000..552e9d4
--- /dev/null
+++ b/fw/User/spiffs/src/test/test_dev.c
@@ -0,0 +1,122 @@
+/*
+ * test_dev.c
+ *
+ * Created on: Jul 14, 2013
+ * Author: petera
+ */
+
+
+#include "testrunner.h"
+#include "test_spiffs.h"
+#include "spiffs_nucleus.h"
+#include "spiffs.h"
+#include
+#include
+#include
+#include
+#include
+
+
+SUITE(dev_tests)
+static void setup() {
+ _setup();
+}
+static void teardown() {
+ _teardown();
+}
+
+TEST(interrupted_write) {
+ char *name = "interrupt";
+ char *name2 = "interrupt2";
+ int res;
+ spiffs_file fd;
+
+ const u32_t sz = SPIFFS_CFG_LOG_PAGE_SZ(FS)*8;
+ u8_t *buf = malloc(sz);
+ memrand(buf, sz);
+
+ printf(" create reference file\n");
+ fd = SPIFFS_open(FS, name, SPIFFS_RDWR | SPIFFS_CREAT | SPIFFS_TRUNC, 0);
+ TEST_CHECK(fd > 0);
+ clear_flash_ops_log();
+ res = SPIFFS_write(FS, fd, buf, sz);
+ TEST_CHECK(res >= 0);
+ SPIFFS_close(FS, fd);
+
+ u32_t written = get_flash_ops_log_write_bytes();
+ printf(" written bytes: %i\n", written);
+
+
+ printf(" create error file\n");
+ fd = SPIFFS_open(FS, name2, SPIFFS_RDWR | SPIFFS_CREAT | SPIFFS_TRUNC, 0);
+ TEST_CHECK(fd > 0);
+ clear_flash_ops_log();
+ invoke_error_after_write_bytes(written/2, 0);
+ res = SPIFFS_write(FS, fd, buf, sz);
+ SPIFFS_close(FS, fd);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_TEST);
+
+ clear_flash_ops_log();
+
+#if SPIFFS_CACHE
+ // delete all cache
+ spiffs_cache *cache = spiffs_get_cache(FS);
+ cache->cpage_use_map = 0;
+#endif
+
+
+ printf(" read error file\n");
+ fd = SPIFFS_open(FS, name2, SPIFFS_RDONLY, 0);
+ TEST_CHECK(fd > 0);
+
+ spiffs_stat s;
+ res = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK(res >= 0);
+ printf(" file size: %i\n", s.size);
+
+ if (s.size > 0) {
+ u8_t *buf2 = malloc(s.size);
+ res = SPIFFS_read(FS, fd, buf2, s.size);
+ TEST_CHECK(res >= 0);
+
+ u32_t ix = 0;
+ for (ix = 0; ix < s.size; ix += 16) {
+ int i;
+ printf(" ");
+ for (i = 0; i < 16; i++) {
+ printf("%02x", buf[ix+i]);
+ }
+ printf(" ");
+ for (i = 0; i < 16; i++) {
+ printf("%02x", buf2[ix+i]);
+ }
+ printf("\n");
+ }
+ free(buf2);
+ }
+ SPIFFS_close(FS, fd);
+
+
+ printf(" FS check\n");
+ SPIFFS_check(FS);
+
+ printf(" read error file again\n");
+ fd = SPIFFS_open(FS, name2, SPIFFS_APPEND | SPIFFS_RDWR, 0);
+ TEST_CHECK(fd > 0);
+ res = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK(res >= 0);
+ printf(" file size: %i\n", s.size);
+ printf(" write file\n");
+ res = SPIFFS_write(FS, fd, buf, sz);
+ TEST_CHECK(res >= 0);
+ SPIFFS_close(FS, fd);
+
+ free(buf);
+
+ return TEST_RES_OK;
+
+} TEST_END
+
+SUITE_TESTS(dev_tests)
+ ADD_TEST(interrupted_write)
+SUITE_END(dev_tests)
diff --git a/fw/User/spiffs/src/test/test_hydrogen.c b/fw/User/spiffs/src/test/test_hydrogen.c
new file mode 100644
index 0000000..8244db4
--- /dev/null
+++ b/fw/User/spiffs/src/test/test_hydrogen.c
@@ -0,0 +1,2368 @@
+/*
+ * test_suites.c
+ *
+ * Created on: Jun 19, 2013
+ * Author: petera
+ */
+
+
+#include "testrunner.h"
+#include "test_spiffs.h"
+#include "spiffs_nucleus.h"
+#include "spiffs.h"
+#include
+#include
+#include
+#include
+#include
+
+SUITE(hydrogen_tests)
+static void setup() {
+ _setup();
+}
+static void teardown() {
+ _teardown();
+}
+
+TEST(info)
+{
+ u32_t used, total;
+ int res = SPIFFS_info(FS, &total, &used);
+ TEST_CHECK(res == SPIFFS_OK);
+ TEST_CHECK(used == 0);
+ TEST_CHECK(total < __fs.cfg.phys_size);
+ return TEST_RES_OK;
+}
+TEST_END
+
+#if SPIFFS_USE_MAGIC
+TEST(magic)
+{
+ fs_reset_specific(0, 0, 65536*16, 65536, 65536, 256);
+ SPIFFS_unmount(FS);
+
+ TEST_CHECK_EQ(fs_mount_specific(0, 65536*16, 65536, 65536, 256), SPIFFS_OK);
+ SPIFFS_unmount(FS);
+
+ TEST_CHECK_NEQ(fs_mount_specific(0, 65536*16, 65536, 65536, 128), SPIFFS_OK);
+ TEST_CHECK_EQ(SPIFFS_errno(FS), SPIFFS_ERR_NOT_A_FS);
+
+ TEST_CHECK_NEQ(fs_mount_specific(4, 65536*16, 65536, 65536, 256), SPIFFS_OK);
+ TEST_CHECK_EQ(SPIFFS_errno(FS), SPIFFS_ERR_NOT_A_FS);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+#if SPIFFS_USE_MAGIC_LENGTH
+TEST(magic_length)
+{
+ fs_reset_specific(0, 0, 65536*16, 65536, 65536, 256);
+ SPIFFS_unmount(FS);
+
+ TEST_CHECK_EQ(fs_mount_specific(0, 65536*16, 65536, 65536, 256), SPIFFS_OK);
+ SPIFFS_unmount(FS);
+
+ TEST_CHECK_NEQ(fs_mount_specific(0, 65536*8, 65536, 65536, 256), SPIFFS_OK);
+ TEST_CHECK_EQ(SPIFFS_errno(FS), SPIFFS_ERR_NOT_A_FS);
+
+ TEST_CHECK_NEQ(fs_mount_specific(0, 65536*15, 65536, 65536, 256), SPIFFS_OK);
+ TEST_CHECK_EQ(SPIFFS_errno(FS), SPIFFS_ERR_NOT_A_FS);
+
+ TEST_CHECK_NEQ(fs_mount_specific(0, 65536*17, 65536, 65536, 256), SPIFFS_OK);
+ TEST_CHECK_EQ(SPIFFS_errno(FS), SPIFFS_ERR_NOT_A_FS);
+
+ TEST_CHECK_NEQ(fs_mount_specific(0, 65536*256, 65536, 65536, 256), SPIFFS_OK);
+ TEST_CHECK_EQ(SPIFFS_errno(FS), SPIFFS_ERR_NOT_A_FS);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+#if SPIFFS_SINGLETON==0
+TEST(magic_length_probe)
+{
+ fs_reset_specific(0, 0, 65536*16, 65536, 65536, 256);
+ TEST_CHECK_EQ(SPIFFS_probe_fs(&__fs.cfg), 65536*16);
+
+ fs_reset_specific(0, 0, 65536*24, 65536, 65536, 256);
+ TEST_CHECK_EQ(SPIFFS_probe_fs(&__fs.cfg), 65536*24);
+
+ fs_reset_specific(0, 0, 32768*16, 32768, 32768, 128);
+ TEST_CHECK_EQ(SPIFFS_probe_fs(&__fs.cfg), 32768*16);
+
+ fs_reset_specific(0, 0, 16384*37, 16384, 16384, 128);
+ TEST_CHECK_EQ(SPIFFS_probe_fs(&__fs.cfg), 16384*37);
+
+ fs_reset_specific(0, 0, 4096*11, 4096, 4096, 256);
+ TEST_CHECK_EQ(SPIFFS_probe_fs(&__fs.cfg), 4096*11);
+
+ fs_reset_specific(0, 0, 4096*8, 4096, 4096, 256);
+ __fs.cfg.log_page_size = 128;
+ TEST_CHECK_EQ(SPIFFS_probe_fs(&__fs.cfg), SPIFFS_ERR_PROBE_NOT_A_FS);
+ __fs.cfg.log_page_size = 512;
+ TEST_CHECK_EQ(SPIFFS_probe_fs(&__fs.cfg), SPIFFS_ERR_PROBE_NOT_A_FS);
+ __fs.cfg.log_page_size = 256;
+ __fs.cfg.log_block_size = 8192;
+ TEST_CHECK_EQ(SPIFFS_probe_fs(&__fs.cfg), SPIFFS_ERR_PROBE_NOT_A_FS);
+ __fs.cfg.log_block_size = 2048;
+ TEST_CHECK_EQ(SPIFFS_probe_fs(&__fs.cfg), SPIFFS_ERR_PROBE_NOT_A_FS);
+ __fs.cfg.log_block_size = 4096;
+ __fs.cfg.phys_addr += 2;
+ TEST_CHECK_EQ(SPIFFS_probe_fs(&__fs.cfg), SPIFFS_ERR_PROBE_NOT_A_FS);
+
+ fs_reset_specific(0, 0, 4096*8, 4096, 4096, 256);
+ __fs.cfg.phys_addr += 4096*6;
+ TEST_CHECK_EQ(SPIFFS_probe_fs(&__fs.cfg), SPIFFS_ERR_PROBE_TOO_FEW_BLOCKS);
+
+ fs_reset_specific(0, 0, 4096*8, 4096, 4096, 256);
+ area_set(4096*0, 0xff, 4096); // "erase" block 0
+ TEST_CHECK_EQ(SPIFFS_probe_fs(&__fs.cfg), 4096*8);
+
+ fs_reset_specific(0, 0, 4096*8, 4096, 4096, 256);
+ area_set(4096*0, 0xff, 4096); // "erase" block 1
+ TEST_CHECK_EQ(SPIFFS_probe_fs(&__fs.cfg), 4096*8);
+
+ fs_reset_specific(0, 0, 4096*8, 4096, 4096, 256);
+ area_set(4096*0, 0xff, 4096); // "erase" block 2
+ TEST_CHECK_EQ(SPIFFS_probe_fs(&__fs.cfg), 4096*8);
+
+ fs_reset_specific(0, 0, 4096*8, 4096, 4096, 256);
+ area_set(4096*0, 0xff, 4096*2); // "erase" block 0 & 1
+ TEST_CHECK_EQ(SPIFFS_probe_fs(&__fs.cfg), SPIFFS_ERR_PROBE_NOT_A_FS);
+
+ fs_reset_specific(0, 0, 4096*8, 4096, 4096, 256);
+ area_set(4096*0, 0xff, 4096*2); // "erase" block 0
+ area_set(4096*0, 0xff, 4096); // "erase" block 2
+ TEST_CHECK_EQ(SPIFFS_probe_fs(&__fs.cfg), SPIFFS_ERR_PROBE_NOT_A_FS);
+
+ fs_reset_specific(0, 0, 4096*8, 4096, 4096, 256);
+ area_set(4096*1, 0xff, 4096*2); // "erase" block 1 & 2
+ TEST_CHECK_EQ(SPIFFS_probe_fs(&__fs.cfg), SPIFFS_ERR_PROBE_NOT_A_FS);
+
+ fs_reset_specific(0, 0, 4096*8, 4096, 4096, 256);
+ area_set(4096*0, 0xff, 4096*8); // "erase" all
+ TEST_CHECK_EQ(SPIFFS_probe_fs(&__fs.cfg), SPIFFS_ERR_PROBE_NOT_A_FS);
+
+ fs_reset_specific(0, 0, 4096*8, 4096, 4096, 256);
+ area_set(4096*0, 0xdd, 4096*8); // garble all
+ TEST_CHECK_EQ(SPIFFS_probe_fs(&__fs.cfg), SPIFFS_ERR_PROBE_NOT_A_FS);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+#endif // SPIFFS_SINGLETON==0
+
+#endif // SPIFFS_USE_MAGIC_LENGTH
+
+#endif // SPIFFS_USE_MAGIC
+
+TEST(missing_file)
+{
+ spiffs_file fd = SPIFFS_open(FS, "this_wont_exist", SPIFFS_RDONLY, 0);
+ TEST_CHECK(fd < 0);
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(bad_fd)
+{
+ int res;
+ spiffs_stat s;
+ spiffs_file fd = SPIFFS_open(FS, "this_wont_exist", SPIFFS_RDONLY, 0);
+ TEST_CHECK(fd < 0);
+ res = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK(res < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_BAD_DESCRIPTOR);
+ res = SPIFFS_fremove(FS, fd);
+ TEST_CHECK(res < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_BAD_DESCRIPTOR);
+ res = SPIFFS_lseek(FS, fd, 0, SPIFFS_SEEK_CUR);
+ TEST_CHECK(res < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_BAD_DESCRIPTOR);
+ res = SPIFFS_read(FS, fd, 0, 0);
+ TEST_CHECK(res < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_BAD_DESCRIPTOR);
+ res = SPIFFS_write(FS, fd, 0, 0);
+ TEST_CHECK(res < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_BAD_DESCRIPTOR);
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(closed_fd)
+{
+ int res;
+ spiffs_stat s;
+ res = test_create_file("file");
+ spiffs_file fd = SPIFFS_open(FS, "file", SPIFFS_RDONLY, 0);
+ TEST_CHECK(fd >= 0);
+ SPIFFS_close(FS, fd);
+
+ res = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK(res < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_FILE_CLOSED);
+ res = SPIFFS_fremove(FS, fd);
+ TEST_CHECK(res < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_FILE_CLOSED);
+ res = SPIFFS_lseek(FS, fd, 0, SPIFFS_SEEK_CUR);
+ TEST_CHECK(res < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_FILE_CLOSED);
+ res = SPIFFS_read(FS, fd, 0, 0);
+ TEST_CHECK(res < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_FILE_CLOSED);
+ res = SPIFFS_write(FS, fd, 0, 0);
+ TEST_CHECK(res < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_FILE_CLOSED);
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(deleted_same_fd)
+{
+ int res;
+ spiffs_stat s;
+ spiffs_file fd;
+ res = test_create_file("remove");
+ fd = SPIFFS_open(FS, "remove", SPIFFS_RDWR, 0);
+ TEST_CHECK(fd >= 0);
+ fd = SPIFFS_open(FS, "remove", SPIFFS_RDWR, 0);
+ TEST_CHECK(fd >= 0);
+ res = SPIFFS_fremove(FS, fd);
+ TEST_CHECK(res >= 0);
+
+ res = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK(res < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_FILE_CLOSED);
+ res = SPIFFS_fremove(FS, fd);
+ TEST_CHECK(res < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_FILE_CLOSED);
+ res = SPIFFS_lseek(FS, fd, 0, SPIFFS_SEEK_CUR);
+ TEST_CHECK(res < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_FILE_CLOSED);
+ res = SPIFFS_read(FS, fd, 0, 0);
+ TEST_CHECK(res < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_FILE_CLOSED);
+ res = SPIFFS_write(FS, fd, 0, 0);
+ TEST_CHECK(res < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_FILE_CLOSED);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(deleted_other_fd)
+{
+ int res;
+ spiffs_stat s;
+ spiffs_file fd, fd_orig;
+ res = test_create_file("remove");
+ fd_orig = SPIFFS_open(FS, "remove", SPIFFS_RDWR, 0);
+ TEST_CHECK(fd_orig >= 0);
+ fd = SPIFFS_open(FS, "remove", SPIFFS_RDWR, 0);
+ TEST_CHECK(fd >= 0);
+ res = SPIFFS_fremove(FS, fd_orig);
+ TEST_CHECK(res >= 0);
+ SPIFFS_close(FS, fd_orig);
+
+ res = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK(res < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_FILE_CLOSED);
+ res = SPIFFS_fremove(FS, fd);
+ TEST_CHECK(res < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_FILE_CLOSED);
+ res = SPIFFS_lseek(FS, fd, 0, SPIFFS_SEEK_CUR);
+ TEST_CHECK(res < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_FILE_CLOSED);
+ res = SPIFFS_read(FS, fd, 0, 0);
+ TEST_CHECK(res < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_FILE_CLOSED);
+ res = SPIFFS_write(FS, fd, 0, 0);
+ TEST_CHECK(res < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_FILE_CLOSED);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(file_by_open)
+{
+ int res;
+ spiffs_stat s;
+ spiffs_file fd = SPIFFS_open(FS, "filebopen", SPIFFS_CREAT, 0);
+ TEST_CHECK(fd >= 0);
+ res = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK(res >= 0);
+ TEST_CHECK(strcmp((char*)s.name, "filebopen") == 0);
+ TEST_CHECK(s.size == 0);
+ SPIFFS_close(FS, fd);
+
+ fd = SPIFFS_open(FS, "filebopen", SPIFFS_RDONLY, 0);
+ TEST_CHECK(fd >= 0);
+ res = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK(res >= 0);
+ TEST_CHECK(strcmp((char*)s.name, "filebopen") == 0);
+ TEST_CHECK(s.size == 0);
+ SPIFFS_close(FS, fd);
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(file_by_creat)
+{
+ int res;
+ res = test_create_file("filebcreat");
+ TEST_CHECK(res >= 0);
+ res = SPIFFS_creat(FS, "filebcreat", 0);
+ TEST_CHECK(res < 0);
+ TEST_CHECK(SPIFFS_errno(FS)==SPIFFS_ERR_CONFLICTING_NAME);
+ return TEST_RES_OK;
+}
+TEST_END
+
+TEST(file_by_open_excl)
+{
+ int res;
+ spiffs_stat s;
+ spiffs_file fd = SPIFFS_open(FS, "filebexcl", SPIFFS_CREAT | SPIFFS_EXCL, 0);
+ TEST_CHECK(fd >= 0);
+ res = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK(res >= 0);
+ TEST_CHECK(strcmp((char*)s.name, "filebexcl") == 0);
+ TEST_CHECK(s.size == 0);
+ SPIFFS_close(FS, fd);
+
+ fd = SPIFFS_open(FS, "filebexcl", SPIFFS_CREAT | SPIFFS_EXCL, 0);
+ TEST_CHECK(fd < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_FILE_EXISTS);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+#if SPIFFS_FILEHDL_OFFSET
+TEST(open_fh_offs)
+{
+ int res;
+ spiffs_stat s;
+ spiffs_file fd1, fd2, fd3;
+ fd1 = SPIFFS_open(FS, "1", SPIFFS_CREAT | SPIFFS_EXCL, 0);
+ fd2 = SPIFFS_open(FS, "2", SPIFFS_CREAT | SPIFFS_EXCL, 0);
+ fd3 = SPIFFS_open(FS, "3", SPIFFS_CREAT | SPIFFS_EXCL, 0);
+ TEST_CHECK(fd1 >= TEST_SPIFFS_FILEHDL_OFFSET);
+ TEST_CHECK(fd2 >= TEST_SPIFFS_FILEHDL_OFFSET);
+ TEST_CHECK(fd3 >= TEST_SPIFFS_FILEHDL_OFFSET);
+ SPIFFS_close(FS, fd1);
+ fd1 = SPIFFS_open(FS, "2", SPIFFS_RDONLY, 0);
+ TEST_CHECK(fd1 >= TEST_SPIFFS_FILEHDL_OFFSET);
+ SPIFFS_close(FS, fd2);
+ fd2 = SPIFFS_open(FS, "3", SPIFFS_RDONLY, 0);
+ TEST_CHECK(fd2 >= TEST_SPIFFS_FILEHDL_OFFSET);
+ SPIFFS_close(FS, fd3);
+ fd3 = SPIFFS_open(FS, "1", SPIFFS_RDONLY, 0);
+ TEST_CHECK(fd3 >= TEST_SPIFFS_FILEHDL_OFFSET);
+ SPIFFS_close(FS, fd1);
+ SPIFFS_close(FS, fd2);
+ SPIFFS_close(FS, fd3);
+ fd1 = SPIFFS_open(FS, "3", SPIFFS_RDONLY, 0);
+ TEST_CHECK(fd1 >= TEST_SPIFFS_FILEHDL_OFFSET);
+ SPIFFS_close(FS, fd1);
+ fd1 = SPIFFS_open(FS, "foo", SPIFFS_RDONLY, 0);
+ TEST_CHECK(fd1 < TEST_SPIFFS_FILEHDL_OFFSET);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+#endif //SPIFFS_FILEHDL_OFFSET
+
+TEST(list_dir)
+{
+ int res;
+
+ char *files[4] = {
+ "file1",
+ "file2",
+ "file3",
+ "file4"
+ };
+ int file_cnt = sizeof(files)/sizeof(char *);
+
+ int i;
+
+ for (i = 0; i < file_cnt; i++) {
+ res = test_create_file(files[i]);
+ TEST_CHECK(res >= 0);
+ }
+
+ spiffs_DIR d;
+ struct spiffs_dirent e;
+ struct spiffs_dirent *pe = &e;
+
+ SPIFFS_opendir(FS, "/", &d);
+ int found = 0;
+ while ((pe = SPIFFS_readdir(&d, pe))) {
+ printf(" %s [%04x] size:%i\n", pe->name, pe->obj_id, pe->size);
+ for (i = 0; i < file_cnt; i++) {
+ if (strcmp(files[i], (char *)pe->name) == 0) {
+ found++;
+ break;
+ }
+ }
+ }
+ SPIFFS_closedir(&d);
+
+ TEST_CHECK(found == file_cnt);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(open_by_dirent) {
+ int res;
+
+ char *files[4] = {
+ "file1",
+ "file2",
+ "file3",
+ "file4"
+ };
+ int file_cnt = sizeof(files)/sizeof(char *);
+
+ int i;
+ int size = SPIFFS_DATA_PAGE_SIZE(FS);
+
+ for (i = 0; i < file_cnt; i++) {
+ res = test_create_and_write_file(files[i], size, size);
+ TEST_CHECK(res >= 0);
+ }
+
+ spiffs_DIR d;
+ struct spiffs_dirent e;
+ struct spiffs_dirent *pe = &e;
+
+ int found = 0;
+ SPIFFS_opendir(FS, "/", &d);
+ while ((pe = SPIFFS_readdir(&d, pe))) {
+ spiffs_file fd = SPIFFS_open_by_dirent(FS, pe, SPIFFS_RDWR, 0);
+ TEST_CHECK(fd >= 0);
+ res = read_and_verify_fd(fd, (char *)pe->name);
+ TEST_CHECK(res == SPIFFS_OK);
+ fd = SPIFFS_open_by_dirent(FS, pe, SPIFFS_RDWR, 0);
+ TEST_CHECK(fd >= 0);
+ res = SPIFFS_fremove(FS, fd);
+ TEST_CHECK(res == SPIFFS_OK);
+ SPIFFS_close(FS, fd);
+ found++;
+ }
+ SPIFFS_closedir(&d);
+
+ TEST_CHECK(found == file_cnt);
+
+ found = 0;
+ SPIFFS_opendir(FS, "/", &d);
+ while ((pe = SPIFFS_readdir(&d, pe))) {
+ found++;
+ }
+ SPIFFS_closedir(&d);
+
+ TEST_CHECK(found == 0);
+
+ return TEST_RES_OK;
+
+} TEST_END
+
+
+TEST(open_by_page) {
+ int res;
+
+ char *files[4] = {
+ "file1",
+ "file2",
+ "file3",
+ "file4"
+ };
+ int file_cnt = sizeof(files)/sizeof(char *);
+
+ int i;
+ int size = SPIFFS_DATA_PAGE_SIZE(FS);
+
+ for (i = 0; i < file_cnt; i++) {
+ res = test_create_and_write_file(files[i], size, size);
+ TEST_CHECK(res >= 0);
+ }
+
+ spiffs_DIR d;
+ struct spiffs_dirent e;
+ struct spiffs_dirent *pe = &e;
+
+ int found = 0;
+ SPIFFS_opendir(FS, "/", &d);
+ while ((pe = SPIFFS_readdir(&d, pe))) {
+ spiffs_file fd = SPIFFS_open_by_dirent(FS, pe, SPIFFS_RDWR, 0);
+ TEST_CHECK(fd >= 0);
+ res = read_and_verify_fd(fd, (char *)pe->name);
+ TEST_CHECK(res == SPIFFS_OK);
+ fd = SPIFFS_open_by_page(FS, pe->pix, SPIFFS_RDWR, 0);
+ TEST_CHECK(fd >= 0);
+ res = SPIFFS_fremove(FS, fd);
+ TEST_CHECK(res == SPIFFS_OK);
+ SPIFFS_close(FS, fd);
+ found++;
+ }
+ SPIFFS_closedir(&d);
+
+ TEST_CHECK(found == file_cnt);
+
+ found = 0;
+ SPIFFS_opendir(FS, "/", &d);
+ while ((pe = SPIFFS_readdir(&d, pe))) {
+ found++;
+ }
+ SPIFFS_closedir(&d);
+
+ TEST_CHECK(found == 0);
+
+ spiffs_file fd;
+ // test opening a lookup page
+ fd = SPIFFS_open_by_page(FS, 0, SPIFFS_RDWR, 0);
+ TEST_CHECK_LT(fd, 0);
+ TEST_CHECK_EQ(SPIFFS_errno(FS), SPIFFS_ERR_NOT_A_FILE);
+ // test opening a proper page but not being object index
+ fd = SPIFFS_open_by_page(FS, SPIFFS_OBJ_LOOKUP_PAGES(FS)+1, SPIFFS_RDWR, 0);
+ TEST_CHECK_LT(fd, 0);
+ TEST_CHECK_EQ(SPIFFS_errno(FS), SPIFFS_ERR_NOT_A_FILE);
+
+ return TEST_RES_OK;
+} TEST_END
+
+
+static struct {
+ u32_t calls;
+ spiffs_fileop_type op;
+ spiffs_obj_id obj_id;
+ spiffs_page_ix pix;
+} ucb;
+
+void test_cb(spiffs *fs, spiffs_fileop_type op, spiffs_obj_id obj_id, spiffs_page_ix pix) {
+ ucb.calls++;
+ ucb.op = op;
+ ucb.obj_id = obj_id;
+ ucb.pix = pix;
+ //printf("%4i op:%i objid:%04x pix:%04x\n", ucb.calls, ucb.op, ucb.obj_id, ucb.pix);
+}
+
+TEST(user_callback_basic) {
+ SPIFFS_set_file_callback_func(FS, test_cb);
+ int res;
+ memset(&ucb, 0, sizeof(ucb));
+ spiffs_file fd = SPIFFS_open(FS, "foo", SPIFFS_CREAT | SPIFFS_APPEND | SPIFFS_RDWR, 0);
+ TEST_CHECK_GE(fd, 0);
+ TEST_CHECK_EQ(ucb.calls, 1);
+ TEST_CHECK_EQ(ucb.op, SPIFFS_CB_CREATED);
+ spiffs_stat s;
+ res = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK_GE(res, 0);
+ TEST_CHECK_EQ(ucb.obj_id, s.obj_id);
+ TEST_CHECK_EQ(ucb.pix, s.pix);
+
+ res = SPIFFS_write(FS, fd, "howdy partner", 14);
+ TEST_CHECK_GE(res, 0);
+ res = SPIFFS_fflush(FS, fd);
+ TEST_CHECK_GE(res, 0);
+ TEST_CHECK_EQ(ucb.calls, 2);
+ TEST_CHECK_EQ(ucb.op, SPIFFS_CB_UPDATED);
+ TEST_CHECK_EQ(ucb.obj_id, s.obj_id);
+ TEST_CHECK_EQ(ucb.pix, s.pix);
+
+ res = SPIFFS_fremove(FS, fd);
+ TEST_CHECK_GE(res, 0);
+ TEST_CHECK_EQ(ucb.calls, 3);
+ TEST_CHECK_EQ(ucb.op, SPIFFS_CB_DELETED);
+ TEST_CHECK_EQ(ucb.obj_id, s.obj_id);
+ TEST_CHECK_EQ(ucb.pix, s.pix);
+
+ return TEST_RES_OK;
+} TEST_END
+
+
+TEST(user_callback_gc) {
+ SPIFFS_set_file_callback_func(FS, test_cb);
+
+ char name[32];
+ int f;
+ int size = SPIFFS_DATA_PAGE_SIZE(FS);
+ int pages_per_block = SPIFFS_PAGES_PER_BLOCK(FS) - SPIFFS_OBJ_LOOKUP_PAGES(FS);
+ int files = (pages_per_block-1)/2;
+ int res;
+
+ // fill block with files
+ for (f = 0; f < files; f++) {
+ sprintf(name, "file%i", f);
+ res = test_create_and_write_file(name, size, 1);
+ TEST_CHECK(res >= 0);
+ }
+ for (f = 0; f < files; f++) {
+ sprintf(name, "file%i", f);
+ res = read_and_verify(name);
+ TEST_CHECK(res >= 0);
+ }
+ // remove all files in block
+ for (f = 0; f < files; f++) {
+ sprintf(name, "file%i", f);
+ res = SPIFFS_remove(FS, name);
+ TEST_CHECK(res >= 0);
+ }
+
+ memset(&ucb, 0, sizeof(ucb));
+ spiffs_file fd = SPIFFS_open(FS, "foo", SPIFFS_CREAT | SPIFFS_APPEND | SPIFFS_RDWR, 0);
+ TEST_CHECK_GE(fd, 0);
+ TEST_CHECK_EQ(ucb.calls, 1);
+ TEST_CHECK_EQ(ucb.op, SPIFFS_CB_CREATED);
+ spiffs_stat s;
+ res = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK_GE(res, 0);
+ TEST_CHECK_EQ(ucb.obj_id, s.obj_id);
+ TEST_CHECK_EQ(ucb.pix, s.pix);
+
+ res = SPIFFS_write(FS, fd, "howdy partner", 14);
+ TEST_CHECK_GE(res, 0);
+ res = SPIFFS_fflush(FS, fd);
+ TEST_CHECK_GE(res, 0);
+ TEST_CHECK_EQ(ucb.calls, 2);
+ TEST_CHECK_EQ(ucb.op, SPIFFS_CB_UPDATED);
+ TEST_CHECK_EQ(ucb.obj_id, s.obj_id);
+ TEST_CHECK_EQ(ucb.pix, s.pix);
+
+ u32_t tot, us;
+ SPIFFS_info(FS, &tot, &us);
+
+ // do a hard gc, should move our file
+ res = SPIFFS_gc(FS, tot-us*2);
+ TEST_CHECK_GE(res, 0);
+
+ TEST_CHECK_GE(res, 0);
+ TEST_CHECK_EQ(ucb.calls, 3);
+ TEST_CHECK_EQ(ucb.op, SPIFFS_CB_UPDATED);
+ TEST_CHECK_EQ(ucb.obj_id, s.obj_id);
+ TEST_CHECK_NEQ(ucb.pix, s.pix);
+
+ res = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK_GE(res, 0);
+ TEST_CHECK_EQ(ucb.pix, s.pix);
+
+ res = SPIFFS_fremove(FS, fd);
+ TEST_CHECK_GE(res, 0);
+ TEST_CHECK_EQ(ucb.calls, 4);
+ TEST_CHECK_EQ(ucb.op, SPIFFS_CB_DELETED);
+ TEST_CHECK_EQ(ucb.obj_id, s.obj_id);
+ TEST_CHECK_EQ(ucb.pix, s.pix);
+
+ return TEST_RES_OK;
+} TEST_END
+
+
+TEST(name_too_long) {
+ char name[SPIFFS_OBJ_NAME_LEN*2];
+ memset(name, 0, sizeof(name));
+ int i;
+ for (i = 0; i < SPIFFS_OBJ_NAME_LEN; i++) {
+ name[i] = 'A';
+ }
+
+ TEST_CHECK_LT(SPIFFS_creat(FS, name, 0), SPIFFS_OK);
+ TEST_CHECK_EQ(SPIFFS_errno(FS), SPIFFS_ERR_NAME_TOO_LONG);
+
+ TEST_CHECK_LT(SPIFFS_open(FS, name, SPIFFS_CREAT | SPIFFS_TRUNC, 0), SPIFFS_OK);
+ TEST_CHECK_EQ(SPIFFS_errno(FS), SPIFFS_ERR_NAME_TOO_LONG);
+
+ TEST_CHECK_LT(SPIFFS_remove(FS, name), SPIFFS_OK);
+ TEST_CHECK_EQ(SPIFFS_errno(FS), SPIFFS_ERR_NAME_TOO_LONG);
+
+ spiffs_stat s;
+ TEST_CHECK_LT(SPIFFS_stat(FS, name, &s), SPIFFS_OK);
+ TEST_CHECK_EQ(SPIFFS_errno(FS), SPIFFS_ERR_NAME_TOO_LONG);
+
+ TEST_CHECK_LT(SPIFFS_rename(FS, name, "a"), SPIFFS_OK);
+ TEST_CHECK_EQ(SPIFFS_errno(FS), SPIFFS_ERR_NAME_TOO_LONG);
+
+ TEST_CHECK_LT(SPIFFS_rename(FS, "a", name), SPIFFS_OK);
+ TEST_CHECK_EQ(SPIFFS_errno(FS), SPIFFS_ERR_NAME_TOO_LONG);
+
+ return TEST_RES_OK;
+} TEST_END
+
+
+TEST(rename) {
+ int res;
+
+ char *src_name = "baah";
+ char *dst_name = "booh";
+ char *dst_name2 = "beeh";
+ int size = SPIFFS_DATA_PAGE_SIZE(FS);
+
+ res = test_create_and_write_file(src_name, size, size);
+ TEST_CHECK(res >= 0);
+
+ res = SPIFFS_rename(FS, src_name, dst_name);
+ TEST_CHECK(res >= 0);
+
+ res = SPIFFS_rename(FS, dst_name, dst_name);
+ TEST_CHECK(res < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_CONFLICTING_NAME);
+
+ res = SPIFFS_rename(FS, src_name, dst_name2);
+ TEST_CHECK(res < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_NOT_FOUND);
+
+ return TEST_RES_OK;
+} TEST_END
+
+
+TEST(remove_single_by_path)
+{
+ int res;
+ spiffs_file fd;
+ res = test_create_file("remove");
+ TEST_CHECK(res >= 0);
+ res = SPIFFS_remove(FS, "remove");
+ TEST_CHECK(res >= 0);
+ fd = SPIFFS_open(FS, "remove", SPIFFS_RDONLY, 0);
+ TEST_CHECK(fd < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_NOT_FOUND);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(remove_single_by_fd)
+{
+ int res;
+ spiffs_file fd;
+ res = test_create_file("remove");
+ TEST_CHECK(res >= 0);
+ fd = SPIFFS_open(FS, "remove", SPIFFS_RDWR, 0);
+ TEST_CHECK(fd >= 0);
+ res = SPIFFS_fremove(FS, fd);
+ TEST_CHECK(res >= 0);
+ SPIFFS_close(FS, fd);
+ fd = SPIFFS_open(FS, "remove", SPIFFS_RDONLY, 0);
+ TEST_CHECK(fd < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_NOT_FOUND);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(write_cache)
+{
+ int res;
+ spiffs_file fd;
+ u8_t buf[1024*8];
+ u8_t fbuf[1024*8];
+ res = test_create_file("f");
+ TEST_CHECK(res >= 0);
+ fd = SPIFFS_open(FS, "f", SPIFFS_RDWR, 0);
+ TEST_CHECK(fd >= 0);
+ memrand(buf, sizeof(buf));
+ res = SPIFFS_write(FS, fd, buf, SPIFFS_CFG_LOG_PAGE_SZ(FS)/2);
+ TEST_CHECK(res >= 0);
+ res = SPIFFS_write(FS, fd, buf, SPIFFS_CFG_LOG_PAGE_SZ(FS)*2);
+ TEST_CHECK(res >= 0);
+ res = SPIFFS_close(FS, fd);
+ TEST_CHECK(res >= 0);
+
+ fd = SPIFFS_open(FS, "f", SPIFFS_RDWR, 0);
+ TEST_CHECK(fd >= 0);
+ res = SPIFFS_read(FS, fd, fbuf, SPIFFS_CFG_LOG_PAGE_SZ(FS)/2 + SPIFFS_CFG_LOG_PAGE_SZ(FS)*2);
+ TEST_CHECK(res >= 0);
+ TEST_CHECK(0 == memcmp(&buf[0], &fbuf[0], SPIFFS_CFG_LOG_PAGE_SZ(FS)/2));
+ TEST_CHECK(0 == memcmp(&buf[0], &fbuf[SPIFFS_CFG_LOG_PAGE_SZ(FS)/2], SPIFFS_CFG_LOG_PAGE_SZ(FS)*2));
+ res = SPIFFS_close(FS, fd);
+ TEST_CHECK(res >= 0);
+
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_OK);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(write_big_file_chunks_page)
+{
+ int size = ((50*(FS)->cfg.phys_size)/100);
+ printf(" filesize %i\n", size);
+ int res = test_create_and_write_file("bigfile", size, SPIFFS_DATA_PAGE_SIZE(FS));
+ TEST_CHECK(res >= 0);
+ res = read_and_verify("bigfile");
+ TEST_CHECK(res >= 0);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(write_big_files_chunks_page)
+{
+ char name[32];
+ int f;
+ int files = 10;
+ int res;
+ int size = ((50*(FS)->cfg.phys_size)/100)/files;
+ printf(" filesize %i\n", size);
+ for (f = 0; f < files; f++) {
+ sprintf(name, "bigfile%i", f);
+ res = test_create_and_write_file(name, size, SPIFFS_DATA_PAGE_SIZE(FS));
+ TEST_CHECK(res >= 0);
+ }
+ for (f = 0; f < files; f++) {
+ sprintf(name, "bigfile%i", f);
+ res = read_and_verify(name);
+ TEST_CHECK(res >= 0);
+ }
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(write_big_file_chunks_index)
+{
+ int size = ((50*(FS)->cfg.phys_size)/100);
+ printf(" filesize %i\n", size);
+ int res = test_create_and_write_file("bigfile", size, SPIFFS_DATA_PAGE_SIZE(FS) * SPIFFS_OBJ_HDR_IX_LEN(FS));
+ TEST_CHECK(res >= 0);
+ res = read_and_verify("bigfile");
+ TEST_CHECK(res >= 0);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(write_big_files_chunks_index)
+{
+ char name[32];
+ int f;
+ int files = 10;
+ int res;
+ int size = ((50*(FS)->cfg.phys_size)/100)/files;
+ printf(" filesize %i\n", size);
+ for (f = 0; f < files; f++) {
+ sprintf(name, "bigfile%i", f);
+ res = test_create_and_write_file(name, size, SPIFFS_DATA_PAGE_SIZE(FS) * SPIFFS_OBJ_HDR_IX_LEN(FS));
+ TEST_CHECK(res >= 0);
+ }
+ for (f = 0; f < files; f++) {
+ sprintf(name, "bigfile%i", f);
+ res = read_and_verify(name);
+ TEST_CHECK(res >= 0);
+ }
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(write_big_file_chunks_huge)
+{
+ int size = (FS_PURE_DATA_PAGES(FS) / 2) * SPIFFS_DATA_PAGE_SIZE(FS);
+ printf(" filesize %i\n", size);
+ int res = test_create_and_write_file("bigfile", size, size);
+ TEST_CHECK(res >= 0);
+ res = read_and_verify("bigfile");
+ TEST_CHECK(res >= 0);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(write_big_files_chunks_huge)
+{
+ char name[32];
+ int f;
+ int files = 10;
+ int res;
+ int size = ((50*(FS)->cfg.phys_size)/100)/files;
+ printf(" filesize %i\n", size);
+ for (f = 0; f < files; f++) {
+ sprintf(name, "bigfile%i", f);
+ res = test_create_and_write_file(name, size, size);
+ TEST_CHECK(res >= 0);
+ }
+ for (f = 0; f < files; f++) {
+ sprintf(name, "bigfile%i", f);
+ res = read_and_verify(name);
+ TEST_CHECK(res >= 0);
+ }
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(truncate_big_file)
+{
+ int size = (FS_PURE_DATA_PAGES(FS) / 2) * SPIFFS_DATA_PAGE_SIZE(FS);
+ printf(" filesize %i\n", size);
+ int res = test_create_and_write_file("bigfile", size, size);
+ TEST_CHECK(res >= 0);
+ res = read_and_verify("bigfile");
+ TEST_CHECK(res >= 0);
+ spiffs_file fd = SPIFFS_open(FS, "bigfile", SPIFFS_RDWR, 0);
+ TEST_CHECK(fd > 0);
+ res = SPIFFS_fremove(FS, fd);
+ TEST_CHECK(res >= 0);
+ SPIFFS_close(FS, fd);
+
+ fd = SPIFFS_open(FS, "bigfile", SPIFFS_RDWR, 0);
+ TEST_CHECK(fd < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_NOT_FOUND);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(simultaneous_write) {
+ int res = SPIFFS_creat(FS, "simul1", 0);
+ TEST_CHECK(res >= 0);
+
+ spiffs_file fd1 = SPIFFS_open(FS, "simul1", SPIFFS_RDWR, 0);
+ TEST_CHECK(fd1 > 0);
+ spiffs_file fd2 = SPIFFS_open(FS, "simul1", SPIFFS_RDWR, 0);
+ TEST_CHECK(fd2 > 0);
+ spiffs_file fd3 = SPIFFS_open(FS, "simul1", SPIFFS_RDWR, 0);
+ TEST_CHECK(fd3 > 0);
+
+ u8_t data1 = 1;
+ u8_t data2 = 2;
+ u8_t data3 = 3;
+
+ res = SPIFFS_write(FS, fd1, &data1, 1);
+ TEST_CHECK(res >= 0);
+ SPIFFS_close(FS, fd1);
+ res = SPIFFS_write(FS, fd2, &data2, 1);
+ TEST_CHECK(res >= 0);
+ SPIFFS_close(FS, fd2);
+ res = SPIFFS_write(FS, fd3, &data3, 1);
+ TEST_CHECK(res >= 0);
+ SPIFFS_close(FS, fd3);
+
+ spiffs_stat s;
+ res = SPIFFS_stat(FS, "simul1", &s);
+ TEST_CHECK(res >= 0);
+
+ TEST_CHECK(s.size == 1);
+
+ u8_t rdata;
+ spiffs_file fd = SPIFFS_open(FS, "simul1", SPIFFS_RDONLY, 0);
+ TEST_CHECK(fd > 0);
+ res = SPIFFS_read(FS, fd, &rdata, 1);
+ TEST_CHECK(res >= 0);
+
+ TEST_CHECK(rdata == data3);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(simultaneous_write_append) {
+ int res = SPIFFS_creat(FS, "simul2", 0);
+ TEST_CHECK(res >= 0);
+
+ spiffs_file fd1 = SPIFFS_open(FS, "simul2", SPIFFS_RDWR | SPIFFS_APPEND, 0);
+ TEST_CHECK(fd1 > 0);
+ spiffs_file fd2 = SPIFFS_open(FS, "simul2", SPIFFS_RDWR | SPIFFS_APPEND, 0);
+ TEST_CHECK(fd2 > 0);
+ spiffs_file fd3 = SPIFFS_open(FS, "simul2", SPIFFS_RDWR | SPIFFS_APPEND, 0);
+ TEST_CHECK(fd3 > 0);
+
+ u8_t data1 = 1;
+ u8_t data2 = 2;
+ u8_t data3 = 3;
+
+ res = SPIFFS_write(FS, fd1, &data1, 1);
+ TEST_CHECK(res >= 0);
+ SPIFFS_close(FS, fd1);
+ res = SPIFFS_write(FS, fd2, &data2, 1);
+ TEST_CHECK(res >= 0);
+ SPIFFS_close(FS, fd2);
+ res = SPIFFS_write(FS, fd3, &data3, 1);
+ TEST_CHECK(res >= 0);
+ SPIFFS_close(FS, fd3);
+
+ spiffs_stat s;
+ res = SPIFFS_stat(FS, "simul2", &s);
+ TEST_CHECK(res >= 0);
+
+ TEST_CHECK(s.size == 3);
+
+ u8_t rdata[3];
+ spiffs_file fd = SPIFFS_open(FS, "simul2", SPIFFS_RDONLY, 0);
+ TEST_CHECK(fd > 0);
+ res = SPIFFS_read(FS, fd, &rdata, 3);
+ TEST_CHECK(res >= 0);
+
+ TEST_CHECK(rdata[0] == data1);
+ TEST_CHECK(rdata[1] == data2);
+ TEST_CHECK(rdata[2] == data3);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+TEST(file_uniqueness)
+{
+ int res;
+ spiffs_file fd;
+ char fname[32];
+ int files = ((SPIFFS_CFG_PHYS_SZ(FS) * 75) / 100) / 2 / SPIFFS_CFG_LOG_PAGE_SZ(FS);
+ //(FS_PURE_DATA_PAGES(FS) / 2) - SPIFFS_PAGES_PER_BLOCK(FS)*8;
+ int i;
+ printf(" creating %i files\n", files);
+ for (i = 0; i < files; i++) {
+ char content[20];
+ sprintf(fname, "file%i", i);
+ sprintf(content, "%i", i);
+ res = test_create_file(fname);
+ TEST_CHECK(res >= 0);
+ fd = SPIFFS_open(FS, fname, SPIFFS_APPEND | SPIFFS_RDWR, 0);
+ TEST_CHECK(fd >= 0);
+ res = SPIFFS_write(FS, fd, content, strlen(content)+1);
+ TEST_CHECK(res >= 0);
+ SPIFFS_close(FS, fd);
+ }
+ printf(" checking %i files\n", files);
+ for (i = 0; i < files; i++) {
+ char content[20];
+ char ref_content[20];
+ sprintf(fname, "file%i", i);
+ sprintf(content, "%i", i);
+ fd = SPIFFS_open(FS, fname, SPIFFS_RDONLY, 0);
+ TEST_CHECK(fd >= 0);
+ res = SPIFFS_read(FS, fd, ref_content, strlen(content)+1);
+ TEST_CHECK(res >= 0);
+ TEST_CHECK(strcmp(ref_content, content) == 0);
+ SPIFFS_close(FS, fd);
+ }
+ printf(" removing %i files\n", files/2);
+ for (i = 0; i < files; i += 2) {
+ sprintf(fname, "file%i", i);
+ res = SPIFFS_remove(FS, fname);
+ TEST_CHECK(res >= 0);
+ }
+ printf(" creating %i files\n", files/2);
+ for (i = 0; i < files; i += 2) {
+ char content[20];
+ sprintf(fname, "file%i", i);
+ sprintf(content, "new%i", i);
+ res = test_create_file(fname);
+ TEST_CHECK(res >= 0);
+ fd = SPIFFS_open(FS, fname, SPIFFS_APPEND | SPIFFS_RDWR, 0);
+ TEST_CHECK(fd >= 0);
+ res = SPIFFS_write(FS, fd, content, strlen(content)+1);
+ TEST_CHECK(res >= 0);
+ SPIFFS_close(FS, fd);
+ }
+ printf(" checking %i files\n", files);
+ for (i = 0; i < files; i++) {
+ char content[20];
+ char ref_content[20];
+ sprintf(fname, "file%i", i);
+ if ((i & 1) == 0) {
+ sprintf(content, "new%i", i);
+ } else {
+ sprintf(content, "%i", i);
+ }
+ fd = SPIFFS_open(FS, fname, SPIFFS_RDONLY, 0);
+ TEST_CHECK(fd >= 0);
+ res = SPIFFS_read(FS, fd, ref_content, strlen(content)+1);
+ TEST_CHECK(res >= 0);
+ TEST_CHECK(strcmp(ref_content, content) == 0);
+ SPIFFS_close(FS, fd);
+ }
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+int create_and_read_back(int size, int chunk) {
+ char *name = "file";
+ spiffs_file fd;
+ s32_t res;
+
+ u8_t *buf = malloc(size);
+ memrand(buf, size);
+
+ res = test_create_file(name);
+ CHECK(res >= 0);
+ fd = SPIFFS_open(FS, name, SPIFFS_APPEND | SPIFFS_RDWR, 0);
+ CHECK(fd >= 0);
+ res = SPIFFS_write(FS, fd, buf, size);
+ CHECK(res >= 0);
+
+ spiffs_stat stat;
+ res = SPIFFS_fstat(FS, fd, &stat);
+ CHECK(res >= 0);
+ CHECK(stat.size == size);
+
+ SPIFFS_close(FS, fd);
+
+ fd = SPIFFS_open(FS, name, SPIFFS_RDONLY, 0);
+ CHECK(fd >= 0);
+
+ u8_t *rbuf = malloc(size);
+ int offs = 0;
+ while (offs < size) {
+ int len = MIN(size - offs, chunk);
+ res = SPIFFS_read(FS, fd, &rbuf[offs], len);
+ CHECK(res >= 0);
+ CHECK(memcmp(&rbuf[offs], &buf[offs], len) == 0);
+
+ offs += chunk;
+ }
+
+ CHECK(memcmp(&rbuf[0], &buf[0], size) == 0);
+
+ SPIFFS_close(FS, fd);
+
+ free(rbuf);
+ free(buf);
+
+ return 0;
+}
+
+TEST(read_chunk_1)
+{
+ TEST_CHECK(create_and_read_back(SPIFFS_DATA_PAGE_SIZE(FS)*8, 1) == 0);
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(read_chunk_page)
+{
+ TEST_CHECK(create_and_read_back(SPIFFS_DATA_PAGE_SIZE(FS)*(SPIFFS_PAGES_PER_BLOCK(FS) - SPIFFS_OBJ_LOOKUP_PAGES(FS))*2,
+ SPIFFS_DATA_PAGE_SIZE(FS)) == 0);
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(read_chunk_index)
+{
+ TEST_CHECK(create_and_read_back(SPIFFS_DATA_PAGE_SIZE(FS)*(SPIFFS_PAGES_PER_BLOCK(FS) - SPIFFS_OBJ_LOOKUP_PAGES(FS))*4,
+ SPIFFS_DATA_PAGE_SIZE(FS)*(SPIFFS_PAGES_PER_BLOCK(FS) - SPIFFS_OBJ_LOOKUP_PAGES(FS))) == 0);
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(read_chunk_huge)
+{
+ int sz = (2*(FS)->cfg.phys_size)/3;
+ TEST_CHECK(create_and_read_back(sz, sz) == 0);
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(read_beyond)
+{
+ char *name = "file";
+ spiffs_file fd;
+ s32_t res;
+ u32_t size = SPIFFS_DATA_PAGE_SIZE(FS)*2;
+
+ u8_t *buf = malloc(size);
+ memrand(buf, size);
+
+ res = test_create_file(name);
+ CHECK(res >= 0);
+ fd = SPIFFS_open(FS, name, SPIFFS_APPEND | SPIFFS_RDWR, 0);
+ CHECK(fd >= 0);
+ res = SPIFFS_write(FS, fd, buf, size);
+ CHECK(res >= 0);
+
+ spiffs_stat stat;
+ res = SPIFFS_fstat(FS, fd, &stat);
+ CHECK(res >= 0);
+ CHECK(stat.size == size);
+
+ SPIFFS_close(FS, fd);
+
+ fd = SPIFFS_open(FS, name, SPIFFS_RDONLY, 0);
+ CHECK(fd >= 0);
+
+ u8_t *rbuf = malloc(size+10);
+ res = SPIFFS_read(FS, fd, rbuf, size+10);
+
+ SPIFFS_close(FS, fd);
+
+ free(rbuf);
+ free(buf);
+
+ TEST_CHECK(res == size);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(bad_index_1) {
+ int size = SPIFFS_DATA_PAGE_SIZE(FS)*3;
+ int res = test_create_and_write_file("file", size, size);
+ TEST_CHECK(res >= 0);
+ res = read_and_verify("file");
+ TEST_CHECK(res >= 0);
+
+ spiffs_file fd = SPIFFS_open(FS, "file", SPIFFS_RDONLY, 0);
+ TEST_CHECK(fd > 0);
+ spiffs_stat s;
+ res = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK(res >= 0);
+ SPIFFS_close(FS, fd);
+
+ // modify object index, find object index header
+ spiffs_page_ix pix;
+ res = spiffs_obj_lu_find_id_and_span(FS, s.obj_id | SPIFFS_OBJ_ID_IX_FLAG, 0, 0, &pix);
+ TEST_CHECK(res >= 0);
+
+ // set object index entry 2 to a bad page, free
+ u32_t addr = SPIFFS_PAGE_TO_PADDR(FS, pix) + sizeof(spiffs_page_object_ix_header) + 2 * sizeof(spiffs_page_ix);
+ spiffs_page_ix bad_pix_ref = (spiffs_page_ix)-1;
+ area_write(addr, (u8_t*)&bad_pix_ref, sizeof(spiffs_page_ix));
+
+#if SPIFFS_CACHE
+ // delete all cache
+ spiffs_cache *cache = spiffs_get_cache(FS);
+ cache->cpage_use_map = 0;
+#endif
+
+ res = read_and_verify("file");
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_INDEX_REF_FREE);
+
+ return TEST_RES_OK;
+} TEST_END
+
+
+TEST(bad_index_2) {
+ int size = SPIFFS_DATA_PAGE_SIZE(FS)*3;
+ int res = test_create_and_write_file("file", size, size);
+ TEST_CHECK(res >= 0);
+ res = read_and_verify("file");
+ TEST_CHECK(res >= 0);
+
+ spiffs_file fd = SPIFFS_open(FS, "file", SPIFFS_RDONLY, 0);
+ TEST_CHECK(fd > 0);
+ spiffs_stat s;
+ res = SPIFFS_fstat(FS, fd, &s);
+ TEST_CHECK(res >= 0);
+ SPIFFS_close(FS, fd);
+
+ // modify object index, find object index header
+ spiffs_page_ix pix;
+ res = spiffs_obj_lu_find_id_and_span(FS, s.obj_id | SPIFFS_OBJ_ID_IX_FLAG, 0, 0, &pix);
+ TEST_CHECK(res >= 0);
+
+ // set object index entry 2 to a bad page, lu
+ u32_t addr = SPIFFS_PAGE_TO_PADDR(FS, pix) + sizeof(spiffs_page_object_ix_header) + 2 * sizeof(spiffs_page_ix);
+ spiffs_page_ix bad_pix_ref = SPIFFS_OBJ_LOOKUP_PAGES(FS)-1;
+ area_write(addr, (u8_t*)&bad_pix_ref, sizeof(spiffs_page_ix));
+
+#if SPIFFS_CACHE
+ // delete all cache
+ spiffs_cache *cache = spiffs_get_cache(FS);
+ cache->cpage_use_map = 0;
+#endif
+
+ res = read_and_verify("file");
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_INDEX_REF_LU);
+
+ return TEST_RES_OK;
+} TEST_END
+
+
+TEST(lseek_simple_modification) {
+ int res;
+ spiffs_file fd;
+ char *fname = "seekfile";
+ int i;
+ int len = 4096;
+ fd = SPIFFS_open(FS, fname, SPIFFS_TRUNC | SPIFFS_CREAT | SPIFFS_RDWR, 0);
+ TEST_CHECK(fd > 0);
+ int pfd = open(make_test_fname(fname), O_TRUNC | O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
+ u8_t *buf = malloc(len);
+ memrand(buf, len);
+ res = SPIFFS_write(FS, fd, buf, len);
+ TEST_CHECK(res >= 0);
+ write(pfd, buf, len);
+ free(buf);
+ res = read_and_verify(fname);
+ TEST_CHECK(res >= 0);
+
+ res = SPIFFS_lseek(FS, fd, len/2, SPIFFS_SEEK_SET);
+ TEST_CHECK(res >= 0);
+ lseek(pfd, len/2, SEEK_SET);
+ len = len/4;
+ buf = malloc(len);
+ memrand(buf, len);
+ res = SPIFFS_write(FS, fd, buf, len);
+ TEST_CHECK(res >= 0);
+ write(pfd, buf, len);
+ free(buf);
+
+ res = read_and_verify(fname);
+ TEST_CHECK(res >= 0);
+
+ SPIFFS_close(FS, fd);
+ close(pfd);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(lseek_modification_append) {
+ int res;
+ spiffs_file fd;
+ char *fname = "seekfile";
+ int i;
+ int len = 4096;
+ fd = SPIFFS_open(FS, fname, SPIFFS_TRUNC | SPIFFS_CREAT | SPIFFS_RDWR, 0);
+ TEST_CHECK(fd > 0);
+ int pfd = open(make_test_fname(fname), O_TRUNC | O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
+ u8_t *buf = malloc(len);
+ memrand(buf, len);
+ res = SPIFFS_write(FS, fd, buf, len);
+ TEST_CHECK(res >= 0);
+ write(pfd, buf, len);
+ free(buf);
+ res = read_and_verify(fname);
+ TEST_CHECK(res >= 0);
+
+ res = SPIFFS_lseek(FS, fd, len/2, SPIFFS_SEEK_SET);
+ TEST_CHECK(res >= 0);
+ lseek(pfd, len/2, SEEK_SET);
+
+ buf = malloc(len);
+ memrand(buf, len);
+ res = SPIFFS_write(FS, fd, buf, len);
+ TEST_CHECK(res >= 0);
+ write(pfd, buf, len);
+ free(buf);
+
+ res = read_and_verify(fname);
+ TEST_CHECK(res >= 0);
+
+ SPIFFS_close(FS, fd);
+ close(pfd);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(lseek_modification_append_multi) {
+ int res;
+ spiffs_file fd;
+ char *fname = "seekfile";
+ int len = 1024;
+ int runs = (FS_PURE_DATA_PAGES(FS) / 2) * SPIFFS_DATA_PAGE_SIZE(FS) / (len/2);
+
+ fd = SPIFFS_open(FS, fname, SPIFFS_TRUNC | SPIFFS_CREAT | SPIFFS_RDWR, 0);
+ TEST_CHECK(fd > 0);
+ int pfd = open(make_test_fname(fname), O_TRUNC | O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
+ u8_t *buf = malloc(len);
+ memrand(buf, len);
+ res = SPIFFS_write(FS, fd, buf, len);
+ TEST_CHECK(res >= 0);
+ write(pfd, buf, len);
+ free(buf);
+ res = read_and_verify(fname);
+ TEST_CHECK(res >= 0);
+
+ while (runs--) {
+ res = SPIFFS_lseek(FS, fd, -len/2, SPIFFS_SEEK_END);
+ TEST_CHECK(res >= 0);
+ lseek(pfd, -len/2, SEEK_END);
+
+ buf = malloc(len);
+ memrand(buf, len);
+ res = SPIFFS_write(FS, fd, buf, len);
+ TEST_CHECK(res >= 0);
+ write(pfd, buf, len);
+ free(buf);
+
+ res = read_and_verify(fname);
+ TEST_CHECK(res >= 0);
+ }
+
+ SPIFFS_close(FS, fd);
+ close(pfd);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(lseek_read) {
+ int res;
+ spiffs_file fd;
+ char *fname = "seekfile";
+ int len = (FS_PURE_DATA_PAGES(FS) / 2) * SPIFFS_DATA_PAGE_SIZE(FS);
+ int runs = 100000;
+
+ fd = SPIFFS_open(FS, fname, SPIFFS_TRUNC | SPIFFS_CREAT | SPIFFS_RDWR, 0);
+ TEST_CHECK(fd > 0);
+ u8_t *refbuf = malloc(len);
+ memrand(refbuf, len);
+ res = SPIFFS_write(FS, fd, refbuf, len);
+ TEST_CHECK(res >= 0);
+
+ int offs = 0;
+ res = SPIFFS_lseek(FS, fd, 0, SPIFFS_SEEK_SET);
+ TEST_CHECK(res >= 0);
+
+ while (runs--) {
+ int i;
+ u8_t buf[64];
+ if (offs + 41 + sizeof(buf) >= len) {
+ offs = (offs + 41 + sizeof(buf)) % len;
+ res = SPIFFS_lseek(FS, fd, offs, SPIFFS_SEEK_SET);
+ TEST_CHECK(res >= 0);
+ }
+ res = SPIFFS_lseek(FS, fd, 41, SPIFFS_SEEK_CUR);
+ TEST_CHECK(res >= 0);
+ offs += 41;
+ res = SPIFFS_read(FS, fd, buf, sizeof(buf));
+ TEST_CHECK(res >= 0);
+ for (i = 0; i < sizeof(buf); i++) {
+ if (buf[i] != refbuf[offs+i]) {
+ printf(" mismatch at offs %i\n", offs);
+ }
+ TEST_CHECK(buf[i] == refbuf[offs+i]);
+ }
+ offs += sizeof(buf);
+
+ res = SPIFFS_lseek(FS, fd, -((u32_t)sizeof(buf)+11), SPIFFS_SEEK_CUR);
+ TEST_CHECK(res >= 0);
+ offs -= (sizeof(buf)+11);
+ res = SPIFFS_read(FS, fd, buf, sizeof(buf));
+ TEST_CHECK(res >= 0);
+ for (i = 0; i < sizeof(buf); i++) {
+ if (buf[i] != refbuf[offs+i]) {
+ printf(" mismatch at offs %i\n", offs);
+ }
+ TEST_CHECK(buf[i] == refbuf[offs+i]);
+ }
+ offs += sizeof(buf);
+ }
+
+ free(refbuf);
+ SPIFFS_close(FS, fd);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(gc_quick)
+{
+ char name[32];
+ int f;
+ int size = SPIFFS_DATA_PAGE_SIZE(FS);
+ int pages_per_block=SPIFFS_PAGES_PER_BLOCK(FS) - SPIFFS_OBJ_LOOKUP_PAGES(FS);
+ int files = (pages_per_block+1)/2;
+ int res;
+
+ // negative, try quick gc on clean sys
+ res = SPIFFS_gc_quick(FS, 0);
+ TEST_CHECK(res < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_NO_DELETED_BLOCKS);
+
+ // fill block with files
+ for (f = 0; f < files; f++) {
+ sprintf(name, "file%i", f);
+ res = test_create_and_write_file(name, size, 1);
+ TEST_CHECK(res >= 0);
+ }
+ for (f = 0; f < files; f++) {
+ sprintf(name, "file%i", f);
+ res = read_and_verify(name);
+ TEST_CHECK(res >= 0);
+ }
+ // remove all files in block
+ for (f = 0; f < files; f++) {
+ sprintf(name, "file%i", f);
+ res = SPIFFS_remove(FS, name);
+ TEST_CHECK(res >= 0);
+ }
+
+ // do a quick gc
+ res = SPIFFS_gc_quick(FS, 0);
+ TEST_CHECK(res >= 0);
+
+ // fill another block with files but two pages
+ // We might have one deleted page left over from the previous gc, in case pages_per_block is odd.
+ int pages_already=2*files-pages_per_block;
+ int files2=(pages_per_block-pages_already+1)/2;
+
+ for (f = 0; f < files2 - 1; f++) {
+ sprintf(name, "file%i", f);
+ res = test_create_and_write_file(name, size, 1);
+ TEST_CHECK(res >= 0);
+ }
+ for (f = 0; f < files2 - 1; f++) {
+ sprintf(name, "file%i", f);
+ res = read_and_verify(name);
+ TEST_CHECK(res >= 0);
+ }
+ // remove all files in block leaving two free pages in block
+ for (f = 0; f < files2 - 1; f++) {
+ sprintf(name, "file%i", f);
+ res = SPIFFS_remove(FS, name);
+ TEST_CHECK(res >= 0);
+ }
+
+ // negative, try quick gc where no fully deleted blocks exist
+ res = SPIFFS_gc_quick(FS, 0);
+ TEST_CHECK(res < 0);
+ TEST_CHECK(SPIFFS_errno(FS) == SPIFFS_ERR_NO_DELETED_BLOCKS);
+
+ // positive, try quick gc where allowing two free pages
+ res = SPIFFS_gc_quick(FS, 2);
+ TEST_CHECK(res >= 0);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(write_small_file_chunks_1)
+{
+ int res = test_create_and_write_file("smallfile", 256, 1);
+ TEST_CHECK(res >= 0);
+ res = read_and_verify("smallfile");
+ TEST_CHECK(res >= 0);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(write_small_files_chunks_1)
+{
+ char name[32];
+ int f;
+ int size = 512;
+ int files = ((20*(FS)->cfg.phys_size)/100)/size;
+ int res;
+ for (f = 0; f < files; f++) {
+ sprintf(name, "smallfile%i", f);
+ res = test_create_and_write_file(name, size, 1);
+ TEST_CHECK(res >= 0);
+ }
+ for (f = 0; f < files; f++) {
+ sprintf(name, "smallfile%i", f);
+ res = read_and_verify(name);
+ TEST_CHECK(res >= 0);
+ }
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+TEST(write_big_file_chunks_1)
+{
+ int size = ((50*(FS)->cfg.phys_size)/100);
+ printf(" filesize %i\n", size);
+ int res = test_create_and_write_file("bigfile", size, 1);
+ TEST_CHECK(res >= 0);
+ res = read_and_verify("bigfile");
+ TEST_CHECK(res >= 0);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+TEST(write_big_files_chunks_1)
+{
+ char name[32];
+ int f;
+ int files = 10;
+ int res;
+ int size = ((50*(FS)->cfg.phys_size)/100)/files;
+ printf(" filesize %i\n", size);
+ for (f = 0; f < files; f++) {
+ sprintf(name, "bigfile%i", f);
+ res = test_create_and_write_file(name, size, 1);
+ TEST_CHECK(res >= 0);
+ }
+ for (f = 0; f < files; f++) {
+ sprintf(name, "bigfile%i", f);
+ res = read_and_verify(name);
+ TEST_CHECK(res >= 0);
+ }
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(long_run_config_many_small_one_long)
+{
+ tfile_conf cfgs[] = {
+ { .tsize = LARGE, .ttype = MODIFIED, .tlife = LONG
+ },
+ { .tsize = SMALL, .ttype = UNTAMPERED, .tlife = SHORT
+ },
+ { .tsize = EMPTY, .ttype = APPENDED, .tlife = SHORT
+ },
+ { .tsize = SMALL, .ttype = UNTAMPERED, .tlife = SHORT
+ },
+ { .tsize = SMALL, .ttype = MODIFIED, .tlife = NORMAL
+ },
+ { .tsize = SMALL, .ttype = REWRITTEN, .tlife = LONG
+ },
+ { .tsize = SMALL, .ttype = MODIFIED, .tlife = NORMAL
+ },
+ { .tsize = SMALL, .ttype = MODIFIED, .tlife = NORMAL
+ },
+ { .tsize = SMALL, .ttype = REWRITTEN, .tlife = LONG
+ },
+ { .tsize = SMALL, .ttype = REWRITTEN, .tlife = NORMAL
+ },
+ { .tsize = SMALL, .ttype = MODIFIED, .tlife = LONG
+ },
+ { .tsize = SMALL, .ttype = MODIFIED, .tlife = NORMAL
+ },
+ { .tsize = SMALL, .ttype = REWRITTEN, .tlife = LONG
+ },
+ { .tsize = SMALL, .ttype = REWRITTEN, .tlife = NORMAL
+ },
+ { .tsize = SMALL, .ttype = MODIFIED, .tlife = LONG
+ },
+ };
+
+ int res = run_file_config(sizeof(cfgs)/sizeof(cfgs[0]), &cfgs[0], 206, 5, 0);
+ TEST_CHECK(res >= 0);
+ return TEST_RES_OK;
+}
+TEST_END
+
+TEST(long_run_config_many_medium)
+{
+ tfile_conf cfgs[] = {
+ { .tsize = MEDIUM, .ttype = MODIFIED, .tlife = LONG
+ },
+ { .tsize = MEDIUM, .ttype = APPENDED, .tlife = LONG
+ },
+ { .tsize = LARGE, .ttype = MODIFIED, .tlife = LONG
+ },
+ { .tsize = MEDIUM, .ttype = APPENDED, .tlife = LONG
+ },
+ { .tsize = MEDIUM, .ttype = MODIFIED, .tlife = LONG
+ },
+ { .tsize = MEDIUM, .ttype = MODIFIED, .tlife = LONG
+ },
+ { .tsize = MEDIUM, .ttype = APPENDED, .tlife = LONG
+ },
+ { .tsize = LARGE, .ttype = MODIFIED, .tlife = LONG
+ },
+ { .tsize = MEDIUM, .ttype = APPENDED, .tlife = LONG
+ },
+ { .tsize = MEDIUM, .ttype = MODIFIED, .tlife = LONG
+ },
+ { .tsize = MEDIUM, .ttype = MODIFIED, .tlife = LONG
+ },
+ { .tsize = MEDIUM, .ttype = APPENDED, .tlife = LONG
+ },
+ { .tsize = LARGE, .ttype = MODIFIED, .tlife = LONG
+ },
+ { .tsize = MEDIUM, .ttype = APPENDED, .tlife = LONG
+ },
+ { .tsize = MEDIUM, .ttype = MODIFIED, .tlife = LONG
+ },
+ };
+
+ int res = run_file_config(sizeof(cfgs)/sizeof(cfgs[0]), &cfgs[0], 305, 5, 0);
+ TEST_CHECK(res >= 0);
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(long_run_config_many_small)
+{
+ tfile_conf cfgs[] = {
+ { .tsize = SMALL, .ttype = APPENDED, .tlife = LONG
+ },
+ { .tsize = SMALL, .ttype = MODIFIED, .tlife = NORMAL
+ },
+ { .tsize = SMALL, .ttype = MODIFIED, .tlife = SHORT
+ },
+ { .tsize = SMALL, .ttype = APPENDED, .tlife = NORMAL
+ },
+ { .tsize = SMALL, .ttype = APPENDED, .tlife = SHORT
+ },
+ { .tsize = EMPTY, .ttype = APPENDED, .tlife = NORMAL
+ },
+ { .tsize = EMPTY, .ttype = APPENDED, .tlife = SHORT
+ },
+ { .tsize = EMPTY, .ttype = UNTAMPERED, .tlife = NORMAL
+ },
+ { .tsize = EMPTY, .ttype = UNTAMPERED, .tlife = SHORT
+ },
+ { .tsize = SMALL, .ttype = REWRITTEN, .tlife = NORMAL
+ },
+ { .tsize = SMALL, .ttype = REWRITTEN, .tlife = SHORT
+ },
+ { .tsize = SMALL, .ttype = UNTAMPERED, .tlife = NORMAL
+ },
+ { .tsize = SMALL, .ttype = UNTAMPERED, .tlife = SHORT
+ },
+ { .tsize = EMPTY, .ttype = APPENDED, .tlife = NORMAL
+ },
+ { .tsize = EMPTY, .ttype = APPENDED, .tlife = SHORT
+ },
+ { .tsize = EMPTY, .ttype = UNTAMPERED, .tlife = NORMAL
+ },
+ { .tsize = EMPTY, .ttype = UNTAMPERED, .tlife = SHORT
+ },
+ { .tsize = SMALL, .ttype = MODIFIED, .tlife = NORMAL
+ },
+ { .tsize = SMALL, .ttype = MODIFIED, .tlife = SHORT
+ },
+ { .tsize = SMALL, .ttype = APPENDED, .tlife = NORMAL
+ },
+ { .tsize = SMALL, .ttype = APPENDED, .tlife = SHORT
+ },
+ { .tsize = SMALL, .ttype = APPENDED, .tlife = LONG
+ },
+ { .tsize = EMPTY, .ttype = APPENDED, .tlife = NORMAL
+ },
+ { .tsize = EMPTY, .ttype = APPENDED, .tlife = SHORT
+ },
+ { .tsize = EMPTY, .ttype = UNTAMPERED, .tlife = NORMAL
+ },
+ { .tsize = EMPTY, .ttype = UNTAMPERED, .tlife = SHORT
+ },
+ { .tsize = SMALL, .ttype = REWRITTEN, .tlife = NORMAL
+ },
+ { .tsize = SMALL, .ttype = REWRITTEN, .tlife = SHORT
+ },
+ { .tsize = SMALL, .ttype = UNTAMPERED, .tlife = NORMAL
+ },
+ { .tsize = SMALL, .ttype = UNTAMPERED, .tlife = SHORT
+ },
+ { .tsize = EMPTY, .ttype = APPENDED, .tlife = NORMAL
+ },
+ { .tsize = EMPTY, .ttype = APPENDED, .tlife = SHORT
+ },
+ { .tsize = EMPTY, .ttype = UNTAMPERED, .tlife = NORMAL
+ },
+ { .tsize = EMPTY, .ttype = UNTAMPERED, .tlife = SHORT
+ },
+ { .tsize = SMALL, .ttype = MODIFIED, .tlife = NORMAL
+ },
+ { .tsize = SMALL, .ttype = MODIFIED, .tlife = SHORT
+ },
+ { .tsize = SMALL, .ttype = APPENDED, .tlife = NORMAL
+ },
+ { .tsize = SMALL, .ttype = APPENDED, .tlife = SHORT
+ },
+ { .tsize = EMPTY, .ttype = APPENDED, .tlife = NORMAL
+ },
+ { .tsize = EMPTY, .ttype = APPENDED, .tlife = SHORT
+ },
+ { .tsize = EMPTY, .ttype = UNTAMPERED, .tlife = NORMAL
+ },
+ { .tsize = EMPTY, .ttype = UNTAMPERED, .tlife = SHORT
+ },
+ { .tsize = SMALL, .ttype = REWRITTEN, .tlife = NORMAL
+ },
+ { .tsize = SMALL, .ttype = REWRITTEN, .tlife = SHORT
+ },
+ { .tsize = SMALL, .ttype = UNTAMPERED, .tlife = NORMAL
+ },
+ { .tsize = SMALL, .ttype = UNTAMPERED, .tlife = SHORT
+ },
+ { .tsize = EMPTY, .ttype = APPENDED, .tlife = NORMAL
+ },
+ { .tsize = EMPTY, .ttype = APPENDED, .tlife = SHORT
+ },
+ { .tsize = EMPTY, .ttype = UNTAMPERED, .tlife = NORMAL
+ },
+ { .tsize = EMPTY, .ttype = UNTAMPERED, .tlife = SHORT
+ },
+ { .tsize = SMALL, .ttype = MODIFIED, .tlife = NORMAL
+ },
+ { .tsize = SMALL, .ttype = MODIFIED, .tlife = SHORT
+ },
+ { .tsize = SMALL, .ttype = APPENDED, .tlife = NORMAL
+ },
+ { .tsize = SMALL, .ttype = APPENDED, .tlife = SHORT
+ },
+ { .tsize = EMPTY, .ttype = APPENDED, .tlife = NORMAL
+ },
+ { .tsize = EMPTY, .ttype = APPENDED, .tlife = SHORT
+ },
+ { .tsize = EMPTY, .ttype = UNTAMPERED, .tlife = NORMAL
+ },
+ { .tsize = EMPTY, .ttype = UNTAMPERED, .tlife = SHORT
+ },
+ { .tsize = SMALL, .ttype = REWRITTEN, .tlife = NORMAL
+ },
+ { .tsize = SMALL, .ttype = REWRITTEN, .tlife = SHORT
+ },
+ { .tsize = SMALL, .ttype = UNTAMPERED, .tlife = NORMAL
+ },
+ { .tsize = SMALL, .ttype = UNTAMPERED, .tlife = SHORT
+ },
+ { .tsize = EMPTY, .ttype = APPENDED, .tlife = NORMAL
+ },
+ { .tsize = EMPTY, .ttype = APPENDED, .tlife = SHORT
+ },
+ { .tsize = EMPTY, .ttype = UNTAMPERED, .tlife = NORMAL
+ },
+ { .tsize = EMPTY, .ttype = UNTAMPERED, .tlife = SHORT
+ },
+ };
+
+ int res = run_file_config(sizeof(cfgs)/sizeof(cfgs[0]), &cfgs[0], 115, 6, 0);
+ TEST_CHECK(res >= 0);
+ return TEST_RES_OK;
+}
+TEST_END
+
+
+TEST(long_run)
+{
+ tfile_conf cfgs[] = {
+ { .tsize = EMPTY, .ttype = APPENDED, .tlife = NORMAL
+ },
+ { .tsize = SMALL, .ttype = REWRITTEN, .tlife = SHORT
+ },
+ { .tsize = MEDIUM, .ttype = MODIFIED, .tlife = SHORT
+ },
+ { .tsize = MEDIUM, .ttype = APPENDED, .tlife = SHORT
+ },
+ };
+
+ int macro_runs = 500;
+ printf(" ");
+ u32_t clob_size = SPIFFS_CFG_PHYS_SZ(FS)/4;
+ int res = test_create_and_write_file("long_clobber", clob_size, clob_size);
+ TEST_CHECK(res >= 0);
+
+ res = read_and_verify("long_clobber");
+ TEST_CHECK(res >= 0);
+
+ while (macro_runs--) {
+ //printf(" ---- run %i ----\n", macro_runs);
+ if ((macro_runs % 20) == 0) {
+ printf(".");
+ fflush(stdout);
+ }
+ res = run_file_config(sizeof(cfgs)/sizeof(cfgs[0]), &cfgs[0], 20, 2, 0);
+ TEST_CHECK(res >= 0);
+ }
+ printf("\n");
+
+ res = read_and_verify("long_clobber");
+ TEST_CHECK(res >= 0);
+
+ res = SPIFFS_check(FS);
+ TEST_CHECK(res >= 0);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+#if SPIFFS_IX_MAP
+TEST(ix_map_basic)
+{
+ // create a scattered file
+ s32_t res;
+ spiffs_file fd1, fd2;
+ fd1 = SPIFFS_open(FS, "1", SPIFFS_O_CREAT | SPIFFS_O_WRONLY, 0);
+ TEST_CHECK_GT(fd1, 0);
+ fd2 = SPIFFS_open(FS, "2", SPIFFS_O_CREAT | SPIFFS_O_WRONLY, 0);
+ TEST_CHECK_GT(fd2, 0);
+
+ u8_t buf[SPIFFS_DATA_PAGE_SIZE(FS)];
+ int i;
+ for (i = 0; i < SPIFFS_CFG_PHYS_SZ(FS) / 4 / SPIFFS_DATA_PAGE_SIZE(FS); i++) {
+ memrand(buf, sizeof(buf));
+ res = SPIFFS_write(FS, fd1, buf, sizeof(buf));
+ TEST_CHECK_GE(res, SPIFFS_OK);
+ memrand(buf, sizeof(buf));
+ res = SPIFFS_write(FS, fd2, buf, sizeof(buf));
+ TEST_CHECK_GE(res, SPIFFS_OK);
+ }
+ res = SPIFFS_close(FS, fd1);
+ TEST_CHECK_GE(res, SPIFFS_OK);
+ res = SPIFFS_close(FS, fd2);
+ TEST_CHECK_GE(res, SPIFFS_OK);
+
+ res = SPIFFS_remove(FS, "2");
+ TEST_CHECK_GE(res, SPIFFS_OK);
+
+ spiffs_stat s;
+ res = SPIFFS_stat(FS, "1", &s);
+ TEST_CHECK_GE(res, SPIFFS_OK);
+ u32_t size = s.size;
+
+ printf("file created, size: %i..\n", size);
+
+ fd1 = SPIFFS_open(FS, "1", SPIFFS_O_RDONLY, 0);
+ TEST_CHECK_GT(fd1, 0);
+ printf(".. corresponding pix entries: %i\n", SPIFFS_bytes_to_ix_map_entries(FS, size));
+
+ u8_t rd_buf[SPIFFS_CFG_LOG_PAGE_SZ(FS)];
+
+ fd1 = SPIFFS_open(FS, "1", SPIFFS_O_RDONLY, 0);
+ TEST_CHECK_GT(fd1, 0);
+
+ clear_flash_ops_log();
+
+ printf("reading file without memory mapped index\n");
+ while ((res = SPIFFS_read(FS, fd1, rd_buf, sizeof(rd_buf))) == sizeof(rd_buf));
+ TEST_CHECK_GT(res, SPIFFS_OK);
+
+ res = SPIFFS_OK;
+
+ u32_t reads_without_ixmap = get_flash_ops_log_read_bytes();
+ dump_flash_access_stats();
+
+ u32_t crc_non_map_ix = get_spiffs_file_crc_by_fd(fd1);
+
+ TEST_CHECK_EQ(SPIFFS_close(FS, fd1), SPIFFS_OK);
+
+
+ printf("reading file with memory mapped index\n");
+ spiffs_ix_map map;
+ spiffs_page_ix ixbuf[SPIFFS_bytes_to_ix_map_entries(FS, size)];
+
+ fd1 = SPIFFS_open(FS, "1", SPIFFS_O_RDONLY, 0);
+ TEST_CHECK_GT(fd1, 0);
+
+ // map index to memory
+ res = SPIFFS_ix_map(FS, fd1, &map, 0, size, ixbuf);
+ TEST_CHECK_GE(res, SPIFFS_OK);
+
+ clear_flash_ops_log();
+
+ while ((res = SPIFFS_read(FS, fd1, rd_buf, sizeof(rd_buf))) == sizeof(rd_buf));
+ TEST_CHECK_GT(res, SPIFFS_OK);
+ u32_t reads_with_ixmap_pass1 = get_flash_ops_log_read_bytes();
+
+ dump_flash_access_stats();
+
+ u32_t crc_map_ix_pass1 = get_spiffs_file_crc_by_fd(fd1);
+
+ TEST_CHECK_LT(reads_with_ixmap_pass1, reads_without_ixmap);
+
+ TEST_CHECK_EQ(crc_non_map_ix, crc_map_ix_pass1);
+
+ spiffs_page_ix ref_ixbuf[SPIFFS_bytes_to_ix_map_entries(FS, size)];
+ memcpy(ref_ixbuf, ixbuf, sizeof(ixbuf));
+
+ // force a gc by creating small files until full, reordering the index
+ printf("forcing gc, error ERR_FULL %i expected\n", SPIFFS_ERR_FULL);
+ res = SPIFFS_OK;
+ u32_t ix = 10;
+ while (res == SPIFFS_OK) {
+ char name[32];
+ sprintf(name, "%i", ix);
+ res = test_create_and_write_file(name, SPIFFS_CFG_LOG_BLOCK_SZ(FS), SPIFFS_CFG_LOG_BLOCK_SZ(FS));
+ ix++;
+ }
+
+ TEST_CHECK_EQ(SPIFFS_errno(FS), SPIFFS_ERR_FULL);
+
+ // make sure the map array was altered
+ TEST_CHECK_NEQ(0, memcmp(ref_ixbuf, ixbuf, sizeof(ixbuf)));
+
+ TEST_CHECK_GE(SPIFFS_lseek(FS, fd1, 0, SPIFFS_SEEK_SET), SPIFFS_OK);
+
+ clear_flash_ops_log();
+ while ((res = SPIFFS_read(FS, fd1, rd_buf, sizeof(rd_buf))) == sizeof(rd_buf));
+ TEST_CHECK_GT(res, SPIFFS_OK);
+ u32_t reads_with_ixmap_pass2 = get_flash_ops_log_read_bytes();
+
+ TEST_CHECK_EQ(reads_with_ixmap_pass1, reads_with_ixmap_pass2);
+
+ u32_t crc_map_ix_pass2 = get_spiffs_file_crc_by_fd(fd1);
+
+ TEST_CHECK_EQ(crc_map_ix_pass1, crc_map_ix_pass2);
+
+ TEST_CHECK_EQ(SPIFFS_close(FS, fd1), SPIFFS_OK);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+TEST(ix_map_remap)
+{
+ // create a file, 10 data pages long
+ s32_t res;
+ spiffs_file fd1, fd2;
+ fd1 = SPIFFS_open(FS, "1", SPIFFS_O_CREAT | SPIFFS_O_WRONLY, 0);
+ TEST_CHECK_GT(fd1, 0);
+
+ const int size_pages = 10;
+
+ u8_t buf[SPIFFS_DATA_PAGE_SIZE(FS)];
+ int i;
+ for (i = 0; i < size_pages; i++) {
+ memrand(buf, sizeof(buf));
+ res = SPIFFS_write(FS, fd1, buf, sizeof(buf));
+ TEST_CHECK_GE(res, SPIFFS_OK);
+ }
+ res = SPIFFS_close(FS, fd1);
+ TEST_CHECK_GE(res, SPIFFS_OK);
+
+ spiffs_stat s;
+ res = SPIFFS_stat(FS, "1", &s);
+ TEST_CHECK_GE(res, SPIFFS_OK);
+ u32_t size = s.size;
+
+ printf("file created, size: %i..\n", size);
+
+ fd1 = SPIFFS_open(FS, "1", SPIFFS_O_RDONLY, 0);
+ TEST_CHECK_GT(fd1, 0);
+ printf(".. corresponding pix entries: %i\n", SPIFFS_bytes_to_ix_map_entries(FS, size) + 1);
+ TEST_CHECK_EQ(SPIFFS_bytes_to_ix_map_entries(FS, size), size_pages + 1);
+
+ // map index to memory
+ // move around, check validity
+ const int entries = SPIFFS_bytes_to_ix_map_entries(FS, size/2);
+ spiffs_ix_map map;
+ // add one extra for stack safeguarding
+ spiffs_page_ix ixbuf[entries+1];
+ spiffs_page_ix ixbuf_ref[entries+1];
+ const spiffs_page_ix canary = (spiffs_page_ix)0x87654321;
+ memset(ixbuf, 0xee, sizeof(ixbuf));
+ ixbuf[entries] = canary;
+
+ res = SPIFFS_ix_map(FS, fd1, &map, 0, size/2, ixbuf);
+ TEST_CHECK_GE(res, SPIFFS_OK);
+
+ for (i = 0; i < entries; i++) {
+ printf("%04x ", ixbuf[i]);
+ }
+ printf("\n");
+
+ memcpy(ixbuf_ref, ixbuf, sizeof(spiffs_page_ix) * entries);
+
+ TEST_CHECK_EQ(SPIFFS_ix_remap(FS, fd1, 0), SPIFFS_OK);
+ TEST_CHECK_EQ(canary, ixbuf[entries]);
+ for (i = 0; i < entries; i++) {
+ printf("%04x ", ixbuf[i]);
+ }
+ printf("\n");
+ TEST_CHECK_EQ(0, memcmp(ixbuf_ref, ixbuf, sizeof(spiffs_page_ix) * entries));
+
+ TEST_CHECK_EQ(SPIFFS_ix_remap(FS, fd1, SPIFFS_DATA_PAGE_SIZE(FS)), SPIFFS_OK);
+ for (i = 0; i < entries; i++) {
+ printf("%04x ", ixbuf[i]);
+ }
+ printf("\n");
+ TEST_CHECK_EQ(canary, ixbuf[entries]);
+ TEST_CHECK_EQ(0, memcmp(&ixbuf_ref[1], ixbuf, sizeof(spiffs_page_ix) * (entries-1)));
+
+
+ TEST_CHECK_EQ(SPIFFS_ix_remap(FS, fd1, 0), SPIFFS_OK);
+ for (i = 0; i < entries; i++) {
+ printf("%04x ", ixbuf[i]);
+ }
+ printf("\n");
+ TEST_CHECK_EQ(canary, ixbuf[entries]);
+ TEST_CHECK_EQ(0, memcmp(ixbuf_ref, ixbuf, sizeof(spiffs_page_ix) * entries));
+
+ TEST_CHECK_EQ(SPIFFS_ix_remap(FS, fd1, size/2), SPIFFS_OK);
+ TEST_CHECK_EQ(canary, ixbuf[entries]);
+
+ for (i = 0; i < entries; i++) {
+ printf("%04x ", ixbuf_ref[i]);
+ }
+ printf("\n");
+
+ for (i = 0; i < entries; i++) {
+ printf("%04x ", ixbuf[i]);
+ }
+ printf("\n");
+
+ int matches = 0;
+ for (i = 0; i < entries; i++) {
+ int j;
+ for (j = 0; j < entries; j++) {
+ if (ixbuf_ref[i] == ixbuf[i]) {
+ matches++;
+ }
+ }
+ }
+ TEST_CHECK_LE(matches, 1);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+TEST(ix_map_partial)
+{
+ // create a file, 10 data pages long
+ s32_t res;
+ spiffs_file fd, fd2;
+ fd = SPIFFS_open(FS, "1", SPIFFS_O_CREAT | SPIFFS_O_WRONLY, 0);
+ TEST_CHECK_GT(fd, 0);
+
+ const int size_pages = 10;
+
+ u8_t buf[SPIFFS_DATA_PAGE_SIZE(FS)];
+ int i;
+ for (i = 0; i < size_pages; i++) {
+ memrand(buf, sizeof(buf));
+ res = SPIFFS_write(FS, fd, buf, sizeof(buf));
+ TEST_CHECK_GE(res, SPIFFS_OK);
+ }
+ res = SPIFFS_close(FS, fd);
+ TEST_CHECK_GE(res, SPIFFS_OK);
+
+ spiffs_stat s;
+ res = SPIFFS_stat(FS, "1", &s);
+ TEST_CHECK_GE(res, SPIFFS_OK);
+ u32_t size = s.size;
+
+ printf("file created, size: %i..\n", size);
+
+ const u32_t crc_unmapped = get_spiffs_file_crc("1");
+
+ fd = SPIFFS_open(FS, "1", SPIFFS_O_RDONLY, 0);
+ TEST_CHECK_GT(fd, 0);
+
+ // map index to memory
+ const int entries = SPIFFS_bytes_to_ix_map_entries(FS, size/2);
+ spiffs_ix_map map;
+ spiffs_page_ix ixbuf[entries];
+ spiffs_page_ix ixbuf_ref[entries];
+
+ printf("map 0-50%%\n");
+ res = SPIFFS_ix_map(FS, fd, &map, 0, size/2, ixbuf);
+ TEST_CHECK_GE(res, SPIFFS_OK);
+
+ const u32_t crc_mapped_beginning = get_spiffs_file_crc_by_fd(fd);
+ TEST_CHECK_EQ(crc_mapped_beginning, crc_unmapped);
+
+ printf("map 25-75%%\n");
+ res = SPIFFS_ix_remap(FS, fd, size/4);
+ TEST_CHECK_GE(res, SPIFFS_OK);
+
+ const u32_t crc_mapped_middle = get_spiffs_file_crc_by_fd(fd);
+ TEST_CHECK_EQ(crc_mapped_middle, crc_unmapped);
+
+ printf("map 50-100%%\n");
+ res = SPIFFS_ix_remap(FS, fd, size/2);
+ TEST_CHECK_GE(res, SPIFFS_OK);
+
+ const u32_t crc_mapped_end = get_spiffs_file_crc_by_fd(fd);
+ TEST_CHECK_EQ(crc_mapped_end, crc_unmapped);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+TEST(ix_map_beyond)
+{
+ // create a file, 10 data pages long
+ s32_t res;
+ spiffs_file fd;
+ fd = SPIFFS_open(FS, "1", SPIFFS_O_CREAT | SPIFFS_O_WRONLY, 0);
+ TEST_CHECK_GT(fd, 0);
+
+ const int size_pages = 10;
+
+ u8_t buf[SPIFFS_DATA_PAGE_SIZE(FS)];
+ int i;
+ for (i = 0; i < size_pages; i++) {
+ memrand(buf, sizeof(buf));
+ res = SPIFFS_write(FS, fd, buf, sizeof(buf));
+ TEST_CHECK_GE(res, SPIFFS_OK);
+ }
+ res = SPIFFS_close(FS, fd);
+ TEST_CHECK_GE(res, SPIFFS_OK);
+
+ spiffs_stat s;
+ res = SPIFFS_stat(FS, "1", &s);
+ TEST_CHECK_GE(res, SPIFFS_OK);
+ u32_t size = s.size;
+
+ printf("file created, size: %i..\n", size);
+
+ // map index to memory
+ fd = SPIFFS_open(FS, "1", SPIFFS_O_RDWR | SPIFFS_O_APPEND, 0);
+ TEST_CHECK_GT(fd, 0);
+
+ const int entries = SPIFFS_bytes_to_ix_map_entries(FS, size);
+ spiffs_ix_map map;
+ spiffs_page_ix ixbuf[entries];
+ printf("map has %i entries\n", entries);
+
+ printf("map 100-200%%\n");
+ res = SPIFFS_ix_map(FS, fd, &map, size, size, ixbuf);
+ TEST_CHECK_GE(res, SPIFFS_OK);
+
+ printf("make sure map is empty\n");
+ for (i = 0; i < entries; i++) {
+ printf("%04x ", ixbuf[i]);
+ TEST_CHECK_EQ(ixbuf[i], 0);
+ }
+ printf("\n");
+
+ printf("elongate by 100%%\n");
+ for (i = 0; i < size_pages; i++) {
+ memrand(buf, sizeof(buf));
+ res = SPIFFS_write(FS, fd, buf, sizeof(buf));
+ TEST_CHECK_GE(res, SPIFFS_OK);
+ }
+ TEST_CHECK_GE(SPIFFS_fflush(FS, fd), SPIFFS_OK);
+
+ res = SPIFFS_stat(FS, "1", &s);
+ TEST_CHECK_GE(res, SPIFFS_OK);
+ size = s.size;
+ printf("file elongated, size: %i..\n", size);
+
+ printf("make sure map is full but for one element\n");
+ int zeroed = 0;
+ for (i = 0; i < entries; i++) {
+ printf("%04x ", ixbuf[i]);
+ if (ixbuf[i] == 0) zeroed++;
+ }
+ printf("\n");
+ TEST_CHECK_LE(zeroed, 1);
+
+ printf("remap till end\n");
+ TEST_CHECK_EQ(SPIFFS_ix_remap(FS, fd, size), SPIFFS_OK);
+
+ printf("make sure map is empty but for one element\n");
+ int nonzero = 0;
+ for (i = 0; i < entries; i++) {
+ printf("%04x ", ixbuf[i]);
+ if (ixbuf[i]) nonzero++;
+ }
+ printf("\n");
+ TEST_CHECK_LE(nonzero, 1);
+
+ printf("elongate again, by other fd\n");
+
+ spiffs_file fd2 = SPIFFS_open(FS, "1", SPIFFS_O_WRONLY | SPIFFS_O_APPEND, 0);
+ TEST_CHECK_GT(fd2, 0);
+
+ for (i = 0; i < size_pages; i++) {
+ memrand(buf, sizeof(buf));
+ res = SPIFFS_write(FS, fd2, buf, sizeof(buf));
+ TEST_CHECK_GE(res, SPIFFS_OK);
+ }
+ TEST_CHECK_GE(SPIFFS_close(FS, fd2), SPIFFS_OK);
+
+ printf("make sure map is full but for one element\n");
+ zeroed = 0;
+ for (i = 0; i < entries; i++) {
+ printf("%04x ", ixbuf[i]);
+ if (ixbuf[i] == 0) zeroed++;
+ }
+ printf("\n");
+ TEST_CHECK_LE(zeroed, 1);
+
+ return TEST_RES_OK;
+}
+TEST_END
+
+#endif // SPIFFS_IX_MAP
+
+SUITE_TESTS(hydrogen_tests)
+ ADD_TEST(info)
+#if SPIFFS_USE_MAGIC
+ ADD_TEST(magic)
+#if SPIFFS_USE_MAGIC_LENGTH
+ ADD_TEST(magic_length)
+#if SPIFFS_SINGLETON==0
+ ADD_TEST(magic_length_probe)
+#endif
+#endif
+#endif
+ ADD_TEST(missing_file)
+ ADD_TEST(bad_fd)
+ ADD_TEST(closed_fd)
+ ADD_TEST(deleted_same_fd)
+ ADD_TEST(deleted_other_fd)
+ ADD_TEST(file_by_open)
+ ADD_TEST(file_by_creat)
+ ADD_TEST(file_by_open_excl)
+#if SPIFFS_FILEHDL_OFFSET
+ ADD_TEST(open_fh_offs)
+#endif
+ ADD_TEST(list_dir)
+ ADD_TEST(open_by_dirent)
+ ADD_TEST(open_by_page)
+ ADD_TEST(user_callback_basic)
+ ADD_TEST(user_callback_gc)
+ ADD_TEST(name_too_long)
+ ADD_TEST(rename)
+ ADD_TEST(remove_single_by_path)
+ ADD_TEST(remove_single_by_fd)
+ ADD_TEST(write_cache)
+ ADD_TEST(write_big_file_chunks_page)
+ ADD_TEST(write_big_files_chunks_page)
+ ADD_TEST(write_big_file_chunks_index)
+ ADD_TEST(write_big_files_chunks_index)
+ ADD_TEST(write_big_file_chunks_huge)
+ ADD_TEST(write_big_files_chunks_huge)
+ ADD_TEST(truncate_big_file)
+ ADD_TEST(simultaneous_write)
+ ADD_TEST(simultaneous_write_append)
+ ADD_TEST(file_uniqueness)
+ ADD_TEST(read_chunk_1)
+ ADD_TEST(read_chunk_page)
+ ADD_TEST(read_chunk_index)
+ ADD_TEST(read_chunk_huge)
+ ADD_TEST(read_beyond)
+ ADD_TEST(bad_index_1)
+ ADD_TEST(bad_index_2)
+ ADD_TEST(lseek_simple_modification)
+ ADD_TEST(lseek_modification_append)
+ ADD_TEST(lseek_modification_append_multi)
+ ADD_TEST(lseek_read)
+ ADD_TEST(gc_quick)
+ ADD_TEST(write_small_file_chunks_1)
+ ADD_TEST(write_small_files_chunks_1)
+ ADD_TEST(write_big_file_chunks_1)
+ ADD_TEST(write_big_files_chunks_1)
+ ADD_TEST(long_run_config_many_small_one_long)
+ ADD_TEST(long_run_config_many_medium)
+ ADD_TEST(long_run_config_many_small)
+ ADD_TEST(long_run)
+#if SPIFFS_IX_MAP
+ ADD_TEST(ix_map_basic)
+ ADD_TEST(ix_map_remap)
+ ADD_TEST(ix_map_partial)
+ ADD_TEST(ix_map_beyond)
+#endif
+
+SUITE_END(hydrogen_tests)
+
diff --git a/fw/User/spiffs/src/test/test_spiffs.c b/fw/User/spiffs/src/test/test_spiffs.c
new file mode 100644
index 0000000..2f138a2
--- /dev/null
+++ b/fw/User/spiffs/src/test/test_spiffs.c
@@ -0,0 +1,1048 @@
+/*
+ * test_spiffs.c
+ *
+ * Created on: Jun 19, 2013
+ * Author: petera
+ */
+
+
+#include
+#include
+#include
+
+#include "params_test.h"
+#include "spiffs.h"
+#include "spiffs_nucleus.h"
+
+#include "testrunner.h"
+
+#include "test_spiffs.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+#define AREA(x) _area[(x) - addr_offset]
+
+static u32_t _area_sz;
+static unsigned char *_area = NULL;
+static u32_t addr_offset = 0;
+
+static int *_erases;
+static char _path[256];
+static u32_t bytes_rd = 0;
+static u32_t bytes_wr = 0;
+static u32_t reads = 0;
+static u32_t writes = 0;
+static u32_t error_after_bytes_written = 0;
+static u32_t error_after_bytes_read = 0;
+static char error_after_bytes_written_once_only = 0;
+static char error_after_bytes_read_once_only = 0;
+static char log_flash_ops = 1;
+static u32_t fs_check_fixes = 0;
+static u32_t _fs_locks;
+
+spiffs __fs;
+static u8_t *_work = NULL;
+static u8_t *_fds = NULL;
+static u32_t _fds_sz;
+static u8_t *_cache = NULL;
+static u32_t _cache_sz;
+
+static int check_valid_flash = 1;
+
+#ifndef TEST_PATH
+#define TEST_PATH "/dev/shm/spiffs/test-data/"
+#endif
+
+// taken from http://stackoverflow.com/questions/675039/how-can-i-create-directory-tree-in-c-linux
+// thanks Jonathan Leffler
+
+static int do_mkdir(const char *path, mode_t mode)
+{
+ struct stat st;
+ int status = 0;
+
+ if (stat(path, &st) != 0) {
+ /* Directory does not exist. EEXIST for race condition */
+ if (mkdir(path, mode) != 0 && errno != EEXIST) {
+ status = -1;
+ }
+ } else if (!S_ISDIR(st.st_mode)) {
+ errno = ENOTDIR;
+ status = -1;
+ }
+
+ return status;
+}
+
+/**
+** mkpath - ensure all directories in path exist
+** Algorithm takes the pessimistic view and works top-down to ensure
+** each directory in path exists, rather than optimistically creating
+** the last element and working backwards.
+*/
+static int mkpath(const char *path, mode_t mode) {
+ char *pp;
+ char *sp;
+ int status;
+ char *copypath = strdup(path);
+
+ status = 0;
+ pp = copypath;
+ while (status == 0 && (sp = strchr(pp, '/')) != 0) {
+ if (sp != pp) {
+ /* Neither root nor double slash in path */
+ *sp = '\0';
+ status = do_mkdir(copypath, mode);
+ *sp = '/';
+ }
+ pp = sp + 1;
+ }
+ if (status == 0) {
+ status = do_mkdir(path, mode);
+ }
+ free(copypath);
+ return status;
+}
+
+// end take
+
+char *make_test_fname(const char *name) {
+ sprintf(_path, "%s/%s", TEST_PATH, name);
+ return _path;
+}
+
+void create_test_path(void) {
+ if (mkpath(TEST_PATH, 0755)) {
+ printf("could not create path %s\n", TEST_PATH);
+ exit(1);
+ }
+}
+
+void clear_test_path() {
+ DIR *dp;
+ struct dirent *ep;
+ dp = opendir(TEST_PATH);
+
+ if (dp != NULL) {
+ while ((ep = readdir(dp))) {
+ if (ep->d_name[0] != '.') {
+ sprintf(_path, "%s/%s", TEST_PATH, ep->d_name);
+ remove(_path);
+ }
+ }
+ closedir(dp);
+ }
+}
+
+static s32_t _read(spiffs *fs, u32_t addr, u32_t size, u8_t *dst) {
+ //printf("rd @ addr %08x => %p\n", addr, &AREA(addr));
+ if (log_flash_ops) {
+ bytes_rd += size;
+ reads++;
+ if (error_after_bytes_read > 0 && bytes_rd >= error_after_bytes_read) {
+ if (error_after_bytes_read_once_only) {
+ error_after_bytes_read = 0;
+ }
+ return SPIFFS_ERR_TEST;
+ }
+ }
+ if (addr < __fs.cfg.phys_addr) {
+ printf("FATAL read addr too low %08x < %08x\n", addr, SPIFFS_PHYS_ADDR);
+ exit(0);
+ }
+ if (addr + size > __fs.cfg.phys_addr + __fs.cfg.phys_size) {
+ printf("FATAL read addr too high %08x + %08x > %08x\n", addr, size, SPIFFS_PHYS_ADDR + SPIFFS_FLASH_SIZE);
+ exit(0);
+ }
+ memcpy(dst, &AREA(addr), size);
+ return 0;
+}
+
+static s32_t _write(spiffs *fs, u32_t addr, u32_t size, u8_t *src) {
+ int i;
+ //printf("wr %08x %i\n", addr, size);
+ if (log_flash_ops) {
+ bytes_wr += size;
+ writes++;
+ if (error_after_bytes_written > 0 && bytes_wr >= error_after_bytes_written) {
+ if (error_after_bytes_written_once_only) {
+ error_after_bytes_written = 0;
+ }
+ return SPIFFS_ERR_TEST;
+ }
+ }
+
+ if (addr < __fs.cfg.phys_addr) {
+ printf("FATAL write addr too low %08x < %08x\n", addr, SPIFFS_PHYS_ADDR);
+ exit(0);
+ }
+ if (addr + size > __fs.cfg.phys_addr + __fs.cfg.phys_size) {
+ printf("FATAL write addr too high %08x + %08x > %08x\n", addr, size, SPIFFS_PHYS_ADDR + SPIFFS_FLASH_SIZE);
+ exit(0);
+ }
+
+ for (i = 0; i < size; i++) {
+ if (((addr + i) & (__fs.cfg.log_page_size-1)) != offsetof(spiffs_page_header, flags)) {
+ if (check_valid_flash && ((AREA(addr + i) ^ src[i]) & src[i])) {
+ printf("trying to write %02x to %02x at addr %08x\n", src[i], AREA(addr + i), addr+i);
+ spiffs_page_ix pix = (addr + i) / LOG_PAGE;
+ dump_page(&__fs, pix);
+ return -1;
+ }
+ }
+ AREA(addr + i) &= src[i];
+ }
+ return 0;
+}
+static s32_t _erase(spiffs *fs, u32_t addr, u32_t size) {
+ if (addr & (__fs.cfg.phys_erase_block-1)) {
+ printf("trying to erase at addr %08x, out of boundary\n", addr);
+ return -1;
+ }
+ if (size & (__fs.cfg.phys_erase_block-1)) {
+ printf("trying to erase at with size %08x, out of boundary\n", size);
+ return -1;
+ }
+ _erases[(addr-__fs.cfg.phys_addr)/__fs.cfg.phys_erase_block]++;
+ memset(&AREA(addr), 0xff, size);
+ return 0;
+}
+
+void hexdump_mem(u8_t *b, u32_t len) {
+ while (len--) {
+ if ((((intptr_t)b)&0x1f) == 0) {
+ printf("\n");
+ }
+ printf("%02x", *b++);
+ }
+ printf("\n");
+}
+
+void hexdump(u32_t addr, u32_t len) {
+ int remainder = (addr % 32) == 0 ? 0 : 32 - (addr % 32);
+ u32_t a;
+ for (a = addr - remainder; a < addr+len; a++) {
+ if ((a & 0x1f) == 0) {
+ if (a != addr) {
+ printf(" ");
+ int j;
+ for (j = 0; j < 32; j++) {
+ if (a-32+j < addr)
+ printf(" ");
+ else {
+ printf("%c", (AREA(a-32+j) < 32 || AREA(a-32+j) >= 0x7f) ? '.' : AREA(a-32+j));
+ }
+ }
+ }
+ printf("%s %08x: ", a<=addr ? "":"\n", a);
+ }
+ if (a < addr) {
+ printf(" ");
+ } else {
+ printf("%02x", AREA(a));
+ }
+ }
+ int j;
+ printf(" ");
+ for (j = 0; j < 32; j++) {
+ if (a-32+j < addr)
+ printf(" ");
+ else {
+ printf("%c", (AREA(a-32+j) < 32 || AREA(a-32+j) >= 0x7f) ? '.' : AREA(a-32+j));
+ }
+ }
+ printf("\n");
+}
+
+void dump_page(spiffs *fs, spiffs_page_ix p) {
+ printf("page %04x ", p);
+ u32_t addr = SPIFFS_PAGE_TO_PADDR(fs, p);
+ if (p % SPIFFS_PAGES_PER_BLOCK(fs) < SPIFFS_OBJ_LOOKUP_PAGES(fs)) {
+ // obj lu page
+ printf("OBJ_LU");
+ } else {
+ u32_t obj_id_addr = SPIFFS_BLOCK_TO_PADDR(fs, SPIFFS_BLOCK_FOR_PAGE(fs , p)) +
+ SPIFFS_OBJ_LOOKUP_ENTRY_FOR_PAGE(fs, p) * sizeof(spiffs_obj_id);
+ spiffs_obj_id obj_id = *((spiffs_obj_id *)&AREA(obj_id_addr));
+ // data page
+ spiffs_page_header *ph = (spiffs_page_header *)&AREA(addr);
+ printf("DATA %04x:%04x ", obj_id, ph->span_ix);
+ printf("%s", ((ph->flags & SPIFFS_PH_FLAG_FINAL) == 0) ? "FIN " : "fin ");
+ printf("%s", ((ph->flags & SPIFFS_PH_FLAG_DELET) == 0) ? "DEL " : "del ");
+ printf("%s", ((ph->flags & SPIFFS_PH_FLAG_INDEX) == 0) ? "IDX " : "idx ");
+ printf("%s", ((ph->flags & SPIFFS_PH_FLAG_USED) == 0) ? "USD " : "usd ");
+ printf("%s ", ((ph->flags & SPIFFS_PH_FLAG_IXDELE) == 0) ? "IDL " : "idl ");
+ if (obj_id & SPIFFS_OBJ_ID_IX_FLAG) {
+ // object index
+ printf("OBJ_IX");
+ if (ph->span_ix == 0) {
+ printf("_HDR ");
+ spiffs_page_object_ix_header *oix_hdr = (spiffs_page_object_ix_header *)&AREA(addr);
+ printf("'%s' %i bytes type:%02x", oix_hdr->name, oix_hdr->size, oix_hdr->type);
+ }
+ } else {
+ // data page
+ printf("CONTENT");
+ }
+ }
+ printf("\n");
+ u32_t len = fs->cfg.log_page_size;
+ hexdump(addr, len);
+}
+
+void area_write(u32_t addr, u8_t *buf, u32_t size) {
+ int i;
+ for (i = 0; i < size; i++) {
+ AREA(addr + i) = *buf++;
+ }
+}
+
+void area_set(u32_t addr, u8_t d, u32_t size) {
+ int i;
+ for (i = 0; i < size; i++) {
+ AREA(addr + i) = d;
+ }
+}
+
+void area_read(u32_t addr, u8_t *buf, u32_t size) {
+ int i;
+ for (i = 0; i < size; i++) {
+ *buf++ = AREA(addr + i);
+ }
+}
+
+void dump_erase_counts(spiffs *fs) {
+ spiffs_block_ix bix;
+ printf(" BLOCK |\n");
+ printf(" AGE COUNT|\n");
+ for (bix = 0; bix < fs->block_count; bix++) {
+ printf("----%3i ----|", bix);
+ }
+ printf("\n");
+ for (bix = 0; bix < fs->block_count; bix++) {
+ spiffs_obj_id erase_mark;
+ _spiffs_rd(fs, 0, 0, SPIFFS_ERASE_COUNT_PADDR(fs, bix), sizeof(spiffs_obj_id), (u8_t *)&erase_mark);
+ if (_erases[bix] == 0) {
+ printf(" |");
+ } else {
+ printf("%7i %4i|", (fs->max_erase_count - erase_mark), _erases[bix]);
+ }
+ }
+ printf("\n");
+}
+
+void dump_flash_access_stats() {
+ printf(" RD: %10i reads %10i bytes %10i avg bytes/read\n", reads, bytes_rd, reads == 0 ? 0 : (bytes_rd / reads));
+ printf(" WR: %10i writes %10i bytes %10i avg bytes/write\n", writes, bytes_wr, writes == 0 ? 0 : (bytes_wr / writes));
+}
+
+
+static u32_t old_perc = 999;
+static void spiffs_check_cb_f(spiffs *fs, spiffs_check_type type, spiffs_check_report report,
+ u32_t arg1, u32_t arg2) {
+/* if (report == SPIFFS_CHECK_PROGRESS && old_perc != arg1) {
+ old_perc = arg1;
+ printf("CHECK REPORT: ");
+ switch(type) {
+ case SPIFFS_CHECK_LOOKUP:
+ printf("LU "); break;
+ case SPIFFS_CHECK_INDEX:
+ printf("IX "); break;
+ case SPIFFS_CHECK_PAGE:
+ printf("PA "); break;
+ }
+ printf("%i%%\n", arg1 * 100 / 256);
+ }*/
+ if (report != SPIFFS_CHECK_PROGRESS) {
+ if (report != SPIFFS_CHECK_ERROR) fs_check_fixes++;
+ printf(" check: ");
+ switch (type) {
+ case SPIFFS_CHECK_INDEX:
+ printf("INDEX "); break;
+ case SPIFFS_CHECK_LOOKUP:
+ printf("LOOKUP "); break;
+ case SPIFFS_CHECK_PAGE:
+ printf("PAGE "); break;
+ default:
+ printf("???? "); break;
+ }
+ if (report == SPIFFS_CHECK_ERROR) {
+ printf("ERROR %i", arg1);
+ } else if (report == SPIFFS_CHECK_DELETE_BAD_FILE) {
+ printf("DELETE BAD FILE %04x", arg1);
+ } else if (report == SPIFFS_CHECK_DELETE_ORPHANED_INDEX) {
+ printf("DELETE ORPHANED INDEX %04x", arg1);
+ } else if (report == SPIFFS_CHECK_DELETE_PAGE) {
+ printf("DELETE PAGE %04x", arg1);
+ } else if (report == SPIFFS_CHECK_FIX_INDEX) {
+ printf("FIX INDEX %04x:%04x", arg1, arg2);
+ } else if (report == SPIFFS_CHECK_FIX_LOOKUP) {
+ printf("FIX INDEX %04x:%04x", arg1, arg2);
+ } else {
+ printf("??");
+ }
+ printf("\n");
+ }
+}
+
+void fs_set_addr_offset(u32_t offset) {
+ addr_offset = offset;
+}
+
+void test_lock(spiffs *fs) {
+ if (_fs_locks != 0) {
+ printf("FATAL: reentrant locks. Abort.\n");
+ exit(-1);
+ }
+ _fs_locks++;
+}
+
+void test_unlock(spiffs *fs) {
+ if (_fs_locks != 1) {
+ printf("FATAL: unlocking unlocked. Abort.\n");
+ exit(-1);
+ }
+ _fs_locks--;
+}
+
+s32_t fs_mount_specific(u32_t phys_addr, u32_t phys_size,
+ u32_t phys_sector_size,
+ u32_t log_block_size, u32_t log_page_size) {
+ spiffs_config c;
+ c.hal_erase_f = _erase;
+ c.hal_read_f = _read;
+ c.hal_write_f = _write;
+ c.log_block_size = log_block_size;
+ c.log_page_size = log_page_size;
+ c.phys_addr = phys_addr;
+ c.phys_erase_block = phys_sector_size;
+ c.phys_size = phys_size;
+#if SPIFFS_FILEHDL_OFFSET
+ c.fh_ix_offset = TEST_SPIFFS_FILEHDL_OFFSET;
+#endif
+ return SPIFFS_mount(&__fs, &c, _work, _fds, _fds_sz, _cache, _cache_sz, spiffs_check_cb_f);
+}
+
+static void fs_create(u32_t spiflash_size,
+ u32_t phys_sector_size,
+ u32_t log_page_size,
+ u32_t descriptors, u32_t cache_pages) {
+ _area_sz = spiflash_size;
+ _area = malloc(spiflash_size);
+ ASSERT(_area != NULL, "testbench area could not be malloced");
+
+ const u32_t erase_sz = sizeof(int) * (spiflash_size / phys_sector_size);
+ _erases = malloc(erase_sz);
+ ASSERT(_erases != NULL, "testbench erase log could not be malloced");
+ memset(_erases, 0, erase_sz);
+
+ _fds_sz = descriptors * sizeof(spiffs_fd);
+ _fds = malloc(_fds_sz);
+ ASSERT(_fds != NULL, "testbench fd buffer could not be malloced");
+ memset(_fds, 0, _fds_sz);
+
+ _cache_sz = sizeof(spiffs_cache) + cache_pages * (sizeof(spiffs_cache_page) + log_page_size);
+ _cache = malloc(_cache_sz);
+ ASSERT(_cache != NULL, "testbench cache could not be malloced");
+ memset(_cache, 0, _cache_sz);
+
+ const u32_t work_sz = log_page_size * 2;
+ _work = malloc(work_sz);
+ ASSERT(_work != NULL, "testbench work buffer could not be malloced");
+ memset(_work, 0, work_sz);
+}
+
+static void fs_free(void) {
+ if (_area) free(_area);
+ _area = NULL;
+ if (_erases) free(_erases);
+ _erases = NULL;
+ if (_fds) free(_fds);
+ _fds = NULL;
+ if (_cache) free(_cache);
+ _cache = NULL;
+ if (_work) free(_work);
+ _work = NULL;
+}
+
+/**
+ * addr_offset
+ */
+void fs_reset_specific(u32_t addr_offset, u32_t phys_addr, u32_t phys_size,
+ u32_t phys_sector_size,
+ u32_t log_block_size, u32_t log_page_size) {
+ fs_create(phys_size + phys_addr - addr_offset,
+ phys_sector_size,
+ log_page_size,
+ DEFAULT_NUM_FD,
+ DEFAULT_NUM_CACHE_PAGES);
+ fs_set_addr_offset(addr_offset);
+ memset(&AREA(addr_offset), 0xcc, _area_sz);
+ memset(&AREA(phys_addr), 0xff, phys_size);
+ memset(&__fs, 0, sizeof(__fs));
+
+ s32_t res = fs_mount_specific(phys_addr, phys_size, phys_sector_size, log_block_size, log_page_size);
+
+#if SPIFFS_USE_MAGIC
+ if (res == SPIFFS_OK) {
+ SPIFFS_unmount(&__fs);
+ }
+ res = SPIFFS_format(&__fs);
+ if (res != SPIFFS_OK) {
+ printf("format failed, %i\n", SPIFFS_errno(&__fs));
+ }
+ res = fs_mount_specific(phys_addr, phys_size, phys_sector_size, log_block_size, log_page_size);
+ if (res != SPIFFS_OK) {
+ printf("mount failed, %i\n", SPIFFS_errno(&__fs));
+ }
+#endif
+
+ clear_flash_ops_log();
+ log_flash_ops = 1;
+ fs_check_fixes = 0;
+}
+
+void fs_reset() {
+ fs_reset_specific(0, SPIFFS_PHYS_ADDR, SPIFFS_FLASH_SIZE, SECTOR_SIZE, LOG_BLOCK, LOG_PAGE);
+}
+
+void fs_store_dump(char *fname) {
+ int pfd = open(fname, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
+ ASSERT(pfd > 0, "could not open dump file");
+ write(pfd, _area, _area_sz);
+ close(pfd);
+}
+
+void fs_load_dump(char *fname) {
+ int pfd = open(fname, O_RDONLY, S_IRUSR | S_IWUSR);
+ ASSERT(pfd > 0, "could not load dump");
+ read(pfd, _area, _area_sz);
+ close(pfd);
+}
+
+void fs_mount_dump(char *fname,
+ u32_t addr_offset, u32_t phys_addr, u32_t phys_size,
+ u32_t phys_sector_size,
+ u32_t log_block_size, u32_t log_page_size) {
+ fs_create(phys_size + phys_addr - addr_offset,
+ phys_sector_size,
+ log_page_size,
+ DEFAULT_NUM_FD,
+ DEFAULT_NUM_CACHE_PAGES);
+ fs_set_addr_offset(addr_offset);
+ memset(&AREA(addr_offset), 0xcc, _area_sz);
+ memset(&AREA(phys_addr), 0xff, phys_size);
+ memset(&__fs, 0, sizeof(__fs));
+
+ fs_load_dump(fname);
+
+ s32_t res = fs_mount_specific(phys_addr, phys_size, phys_sector_size, log_block_size, log_page_size);
+
+ ASSERT(res == SPIFFS_OK, "failed mounting dump, check settings");
+
+ clear_flash_ops_log();
+ log_flash_ops = 1;
+ fs_check_fixes = 0;
+}
+
+void set_flash_ops_log(int enable) {
+ log_flash_ops = enable;
+}
+
+void clear_flash_ops_log() {
+ bytes_rd = 0;
+ bytes_wr = 0;
+ reads = 0;
+ writes = 0;
+ error_after_bytes_read = 0;
+ error_after_bytes_written = 0;
+}
+
+u32_t get_flash_ops_log_read_bytes() {
+ return bytes_rd;
+}
+
+u32_t get_flash_ops_log_write_bytes() {
+ return bytes_wr;
+}
+
+void invoke_error_after_read_bytes(u32_t b, char once_only) {
+ error_after_bytes_read = b;
+ error_after_bytes_read_once_only = once_only;
+}
+void invoke_error_after_write_bytes(u32_t b, char once_only) {
+ error_after_bytes_written = b;
+ error_after_bytes_written_once_only = once_only;
+}
+
+void fs_set_validate_flashing(int i) {
+ check_valid_flash = i;
+}
+
+void real_assert(int c, const char *n, const char *file, int l) {
+ if (c == 0) {
+ printf("ASSERT: %s %s @ %i\n", (n ? n : ""), file, l);
+ printf("fs errno:%i\n", __fs.err_code);
+ exit(0);
+ }
+}
+
+int read_and_verify(char *name) {
+ s32_t res;
+ int fd = SPIFFS_open(&__fs, name, SPIFFS_RDONLY, 0);
+ if (fd < 0) {
+ printf(" read_and_verify: could not open file %s\n", name);
+ return fd;
+ }
+ return read_and_verify_fd(fd, name);
+}
+
+int read_and_verify_fd(spiffs_file fd, char *name) {
+ s32_t res;
+ int pfd = open(make_test_fname(name), O_RDONLY);
+ spiffs_stat s;
+ res = SPIFFS_fstat(&__fs, fd, &s);
+ if (res < 0) {
+ printf(" read_and_verify: could not stat file %s\n", name);
+ return res;
+ }
+ if (s.size == 0) {
+ SPIFFS_close(&__fs, fd);
+ close(pfd);
+ return 0;
+ }
+
+ //printf("verifying %s, len %i\n", name, s.size);
+ int offs = 0;
+ u8_t buf_d[256];
+ u8_t buf_v[256];
+ while (offs < s.size) {
+ int read_len = MIN(s.size - offs, sizeof(buf_d));
+ res = SPIFFS_read(&__fs, fd, buf_d, read_len);
+ if (res < 0) {
+ printf(" read_and_verify: could not read file %s offs:%i len:%i filelen:%i\n", name, offs, read_len, s.size);
+ return res;
+ }
+ int pres = read(pfd, buf_v, read_len);
+ (void)pres;
+ //printf("reading offs:%i len:%i spiffs_res:%i posix_res:%i\n", offs, read_len, res, pres);
+ int i;
+ int veri_ok = 1;
+ for (i = 0; veri_ok && i < read_len; i++) {
+ if (buf_d[i] != buf_v[i]) {
+ printf("file verification mismatch @ %i, %02x %c != %02x %c\n", offs+i, buf_d[i], buf_d[i], buf_v[i], buf_v[i]);
+ int j = MAX(0, i-16);
+ int k = MIN(sizeof(buf_d), i+16);
+ k = MIN(s.size-offs, k);
+ int l;
+ for (l = j; l < k; l++) {
+ printf("%c", buf_d[l] > 31 ? buf_d[l] : '.');
+ }
+ printf("\n");
+ for (l = j; l < k; l++) {
+ printf("%c", buf_v[l] > 31 ? buf_v[l] : '.');
+ }
+ printf("\n");
+ veri_ok = 0;
+ }
+ }
+ if (!veri_ok) {
+ SPIFFS_close(&__fs, fd);
+ close(pfd);
+ printf("data mismatch\n");
+ return -1;
+ }
+
+ offs += read_len;
+ }
+
+ SPIFFS_close(&__fs, fd);
+ close(pfd);
+
+ return 0;
+}
+
+static void test_on_stop(test *t) {
+ printf(" spiffs errno:%i\n", SPIFFS_errno(&__fs));
+#if SPIFFS_TEST_VISUALISATION
+ if (_area) SPIFFS_vis(FS);
+#endif
+
+}
+
+void memrand(u8_t *b, int len) {
+ int i;
+ for (i = 0; i < len; i++) {
+ b[i] = rand();
+ }
+}
+
+int test_create_file(char *name) {
+ spiffs_stat s;
+ spiffs_file fd;
+ int res = SPIFFS_creat(FS, name, 0);
+ CHECK_RES(res);
+ fd = SPIFFS_open(FS, name, SPIFFS_RDONLY, 0);
+ CHECK(fd >= 0);
+ res = SPIFFS_fstat(FS, fd, &s);
+ CHECK_RES(res);
+ CHECK(strcmp((char*)s.name, name) == 0);
+ CHECK(s.size == 0);
+ SPIFFS_close(FS, fd);
+ return 0;
+}
+
+int test_create_and_write_file(char *name, int size, int chunk_size) {
+ int res;
+ spiffs_file fd;
+ printf(" create and write %s", name);
+ res = test_create_file(name);
+ if (res < 0) {
+ printf(" failed creation, %i\n",res);
+ }
+ CHECK(res >= 0);
+ fd = SPIFFS_open(FS, name, SPIFFS_APPEND | SPIFFS_RDWR, 0);
+ if (res < 0) {
+ printf(" failed open, %i\n",res);
+ }
+ CHECK(fd >= 0);
+ int pfd = open(make_test_fname(name), O_APPEND | O_TRUNC | O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
+ int offset = 0;
+ int mark = 0;
+ while (offset < size) {
+ int len = MIN(size-offset, chunk_size);
+ if (offset > mark) {
+ mark += size/16;
+ printf(".");
+ fflush(stdout);
+ }
+ u8_t *buf = malloc(len);
+ memrand(buf, len);
+ res = SPIFFS_write(FS, fd, buf, len);
+ write(pfd, buf, len);
+ free(buf);
+ if (res < 0) {
+ printf("\n error @ offset %i, res %i\n", offset, res);
+ }
+ offset += len;
+ CHECK(res >= 0);
+ }
+ printf("\n");
+ close(pfd);
+
+ spiffs_stat stat;
+ res = SPIFFS_fstat(FS, fd, &stat);
+ if (res < 0) {
+ printf(" failed fstat, %i\n",res);
+ }
+ CHECK(res >= 0);
+ if (stat.size != size) {
+ printf(" failed size, %i != %i\n", stat.size, size);
+ }
+ CHECK(stat.size == size);
+
+ SPIFFS_close(FS, fd);
+ return 0;
+}
+
+static u32_t crc32_tab[] = {
+ 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
+ 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
+ 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
+ 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
+ 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
+ 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
+ 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
+ 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
+ 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
+ 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
+ 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
+ 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
+ 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
+ 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
+ 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
+ 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
+ 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
+ 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
+ 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
+ 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
+ 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
+ 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
+ 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
+ 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
+ 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
+ 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
+ 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
+ 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
+ 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
+ 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
+ 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
+ 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
+ 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
+ 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
+ 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
+ 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
+ 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
+ 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
+ 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
+ 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
+ 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
+ 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
+ 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
+};
+
+static u32_t crc32(u32_t crc, const void *buf, size_t size)
+{
+ const u8_t *p;
+
+ p = buf;
+ crc = crc ^ ~0U;
+
+ while (size--)
+ crc = crc32_tab[(crc ^ *p++) & 0xFF] ^ (crc >> 8);
+
+ return crc ^ ~0U;
+}
+
+u32_t get_spiffs_file_crc_by_fd(spiffs_file fd) {
+ s32_t res;
+ u32_t crc = 0;
+ u8_t buf[256];
+
+ ASSERT(SPIFFS_lseek(FS, fd, 0, SPIFFS_SEEK_SET) >= 0, "could not seek to start of file");
+
+ while ((res = SPIFFS_read(FS, fd, buf, sizeof(buf))) >= SPIFFS_OK) {
+ crc = crc32(crc, buf, res);
+ }
+ ASSERT(res == SPIFFS_ERR_END_OF_OBJECT || res == SPIFFS_OK, "failed reading file");
+
+ return crc;
+}
+
+u32_t get_spiffs_file_crc(char *name) {
+ s32_t res;
+ spiffs_file fd;
+ fd = SPIFFS_open(FS, name, SPIFFS_O_RDONLY, 0);
+ ASSERT(fd >= 0, "Could not open file");
+ u32_t crc = get_spiffs_file_crc_by_fd(fd);
+ res = SPIFFS_close(FS, fd);
+ ASSERT(res >= SPIFFS_OK, "failing closing file");
+ return crc;
+}
+
+#if SPIFFS_CACHE
+#if SPIFFS_CACHE_STATS
+static u32_t chits_tot = 0;
+static u32_t cmiss_tot = 0;
+#endif
+#endif
+
+void _setup_test_only() {
+ create_test_path();
+ fs_set_validate_flashing(1);
+ test_init(test_on_stop);
+}
+
+void _setup() {
+ _fs_locks = 0;
+ fs_reset();
+ _setup_test_only();
+}
+
+void _teardown() {
+ printf(" free blocks : %i of %i\n", (FS)->free_blocks, (FS)->block_count);
+ printf(" pages allocated : %i\n", (FS)->stats_p_allocated);
+ printf(" pages deleted : %i\n", (FS)->stats_p_deleted);
+#if SPIFFS_GC_STATS
+ printf(" gc runs : %i\n", (FS)->stats_gc_runs);
+#endif
+#if SPIFFS_CACHE
+#if SPIFFS_CACHE_STATS
+ chits_tot += (FS)->cache_hits;
+ cmiss_tot += (FS)->cache_misses;
+ printf(" cache hits : %i (sum %i)\n", (FS)->cache_hits, chits_tot);
+ printf(" cache misses : %i (sum %i)\n", (FS)->cache_misses, cmiss_tot);
+ printf(" cache utiliz : %f\n", ((float)chits_tot/(float)(chits_tot + cmiss_tot)));
+ chits_tot = 0;
+ cmiss_tot = 0;
+#endif
+#endif
+ if (_area) {
+ dump_flash_access_stats();
+ clear_flash_ops_log();
+#if SPIFFS_GC_STATS
+ if ((FS)->stats_gc_runs > 0)
+#endif
+ dump_erase_counts(FS);
+ printf(" fs consistency check output begin\n");
+ SPIFFS_check(FS);
+ printf(" fs consistency check output end\n");
+ }
+ clear_test_path();
+ fs_free();
+ printf(" locks : %i\n", _fs_locks);
+ if (_fs_locks != 0) {
+ printf("FATAL: lock asymmetry. Abort.\n");
+ exit(-1);
+ }
+}
+
+u32_t tfile_get_size(tfile_size s) {
+ switch (s) {
+ case EMPTY:
+ return 0;
+ case SMALL: // half a data page
+ return SPIFFS_DATA_PAGE_SIZE(FS)/2;
+ case MEDIUM: // one block
+ return SPIFFS_DATA_PAGE_SIZE(FS) * (SPIFFS_PAGES_PER_BLOCK(FS) - SPIFFS_OBJ_LOOKUP_PAGES(FS));
+ case LARGE: // third of fs
+ return SPIFFS_DATA_PAGE_SIZE(FS) * (SPIFFS_PAGES_PER_BLOCK(FS) - SPIFFS_OBJ_LOOKUP_PAGES(FS)) * (FS)->block_count/3;
+ }
+ return 0;
+}
+
+int run_file_config(int cfg_count, tfile_conf* cfgs, int max_runs, int max_concurrent_files, int dbg) {
+ int res;
+ tfile *tfiles = malloc(sizeof(tfile) * max_concurrent_files);
+ memset(tfiles, 0, sizeof(tfile) * max_concurrent_files);
+ int run = 0;
+ int cur_config_ix = 0;
+ char name[32];
+ while (run < max_runs) {
+ if (dbg) printf(" run %i/%i\n", run, max_runs);
+ int i;
+ for (i = 0; i < max_concurrent_files; i++) {
+ sprintf(name, "file%i_%i", (1+run), i);
+ tfile *tf = &tfiles[i];
+ if (tf->state == 0 && cur_config_ix < cfg_count) {
+// create a new file
+ strcpy(tf->name, name);
+ tf->state = 1;
+ tf->cfg = cfgs[cur_config_ix];
+ int size = tfile_get_size(tf->cfg.tsize);
+ if (dbg) printf(" create new %s with cfg %i/%i, size %i\n", name, (1+cur_config_ix), cfg_count, size);
+
+ if (tf->cfg.tsize == EMPTY) {
+ res = SPIFFS_creat(FS, name, 0);
+ CHECK_RES(res);
+ int pfd = open(make_test_fname(name), O_TRUNC | O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
+ close(pfd);
+ int extra_flags = tf->cfg.ttype == APPENDED ? SPIFFS_APPEND : 0;
+ spiffs_file fd = SPIFFS_open(FS, name, extra_flags | SPIFFS_RDWR, 0);
+ CHECK(fd > 0);
+ tf->fd = fd;
+ } else {
+ int extra_flags = tf->cfg.ttype == APPENDED ? SPIFFS_APPEND : 0;
+ spiffs_file fd = SPIFFS_open(FS, name, extra_flags | SPIFFS_TRUNC | SPIFFS_CREAT | SPIFFS_RDWR, 0);
+ CHECK(fd > 0);
+ extra_flags = tf->cfg.ttype == APPENDED ? O_APPEND : 0;
+ int pfd = open(make_test_fname(name), extra_flags | O_TRUNC | O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
+ tf->fd = fd;
+ u8_t *buf = malloc(size);
+ memrand(buf, size);
+ res = SPIFFS_write(FS, fd, buf, size);
+ CHECK_RES(res);
+ write(pfd, buf, size);
+ close(pfd);
+ free(buf);
+ res = read_and_verify(name);
+ CHECK_RES(res);
+ }
+
+ cur_config_ix++;
+ } else if (tf->state > 0) {
+// hande file lifecycle
+ switch (tf->cfg.ttype) {
+ case UNTAMPERED: {
+ break;
+ }
+ case APPENDED: {
+ if (dbg) printf(" appending %s\n", tf->name);
+ int size = SPIFFS_DATA_PAGE_SIZE(FS)*3;
+ u8_t *buf = malloc(size);
+ memrand(buf, size);
+ res = SPIFFS_write(FS, tf->fd, buf, size);
+ CHECK_RES(res);
+ int pfd = open(make_test_fname(tf->name), O_APPEND | O_RDWR);
+ write(pfd, buf, size);
+ close(pfd);
+ free(buf);
+ res = read_and_verify(tf->name);
+ CHECK_RES(res);
+ break;
+ }
+ case MODIFIED: {
+ if (dbg) printf(" modify %s\n", tf->name);
+ spiffs_stat stat;
+ res = SPIFFS_fstat(FS, tf->fd, &stat);
+ CHECK_RES(res);
+ int size = stat.size / tf->cfg.tlife + SPIFFS_DATA_PAGE_SIZE(FS)/3;
+ int offs = (stat.size / tf->cfg.tlife) * tf->state;
+ res = SPIFFS_lseek(FS, tf->fd, offs, SPIFFS_SEEK_SET);
+ CHECK_RES(res);
+ u8_t *buf = malloc(size);
+ memrand(buf, size);
+ res = SPIFFS_write(FS, tf->fd, buf, size);
+ CHECK_RES(res);
+ int pfd = open(make_test_fname(tf->name), O_RDWR);
+ lseek(pfd, offs, SEEK_SET);
+ write(pfd, buf, size);
+ close(pfd);
+ free(buf);
+ res = read_and_verify(tf->name);
+ CHECK_RES(res);
+ break;
+ }
+ case REWRITTEN: {
+ if (tf->fd > 0) {
+ SPIFFS_close(FS, tf->fd);
+ }
+ if (dbg) printf(" rewriting %s\n", tf->name);
+ spiffs_file fd = SPIFFS_open(FS, tf->name, SPIFFS_TRUNC | SPIFFS_CREAT | SPIFFS_RDWR, 0);
+ CHECK(fd > 0);
+ int pfd = open(make_test_fname(tf->name), O_TRUNC | O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
+ tf->fd = fd;
+ int size = tfile_get_size(tf->cfg.tsize);
+ u8_t *buf = malloc(size);
+ memrand(buf, size);
+ res = SPIFFS_write(FS, fd, buf, size);
+ CHECK_RES(res);
+ write(pfd, buf, size);
+ close(pfd);
+ free(buf);
+ res = read_and_verify(tf->name);
+ CHECK_RES(res);
+ break;
+ }
+ }
+ tf->state++;
+ if (tf->state > tf->cfg.tlife) {
+// file outlived its time, kill it
+ if (tf->fd > 0) {
+ SPIFFS_close(FS, tf->fd);
+ }
+ if (dbg) printf(" removing %s\n", tf->name);
+ res = read_and_verify(tf->name);
+ CHECK_RES(res);
+ res = SPIFFS_remove(FS, tf->name);
+ CHECK_RES(res);
+ remove(make_test_fname(tf->name));
+ memset(tf, 0, sizeof(tfile));
+ }
+
+ }
+ }
+
+ run++;
+ }
+ free(tfiles);
+ return 0;
+}
+
+
+
diff --git a/fw/User/spiffs/src/test/test_spiffs.h b/fw/User/spiffs/src/test/test_spiffs.h
new file mode 100644
index 0000000..b0a7353
--- /dev/null
+++ b/fw/User/spiffs/src/test/test_spiffs.h
@@ -0,0 +1,107 @@
+/*
+ * test_spiffs.h
+ *
+ * Created on: Jun 19, 2013
+ * Author: petera
+ */
+
+#ifndef TEST_SPIFFS_H_
+#define TEST_SPIFFS_H_
+
+#include "spiffs.h"
+
+#define FS &__fs
+
+extern spiffs __fs;
+
+
+#define CHECK(r) if (!(r)) return -1;
+#define CHECK_RES(r) if (r < 0) return -1;
+#define FS_PURE_DATA_PAGES(fs) \
+ ((fs)->cfg.phys_size / (fs)->cfg.log_page_size - (fs)->block_count * SPIFFS_OBJ_LOOKUP_PAGES(fs))
+#define FS_PURE_DATA_SIZE(fs) \
+ FS_PURE_DATA_PAGES(fs) * SPIFFS_DATA_PAGE_SIZE(fs)
+
+typedef enum {
+ EMPTY,
+ SMALL,
+ MEDIUM,
+ LARGE,
+} tfile_size;
+
+typedef enum {
+ UNTAMPERED,
+ APPENDED,
+ MODIFIED,
+ REWRITTEN,
+} tfile_type;
+
+typedef enum {
+ SHORT = 3,
+ NORMAL = 15,
+ LONG = 100,
+} tfile_life;
+
+typedef struct {
+ tfile_size tsize;
+ tfile_type ttype;
+ tfile_life tlife;
+} tfile_conf;
+
+typedef struct {
+ int state;
+ spiffs_file fd;
+ tfile_conf cfg;
+ char name[32];
+} tfile;
+
+void fs_reset();
+void fs_reset_specific(u32_t addr_offset, u32_t phys_addr, u32_t phys_size,
+ u32_t phys_sector_size,
+ u32_t log_block_size, u32_t log_page_size);
+s32_t fs_mount_specific(u32_t phys_addr, u32_t phys_size,
+ u32_t phys_sector_size,
+ u32_t log_block_size, u32_t log_page_size);
+void fs_mount_dump(char *fname,
+ u32_t addr_offset, u32_t phys_addr, u32_t phys_size,
+ u32_t phys_sector_size,
+ u32_t log_block_size, u32_t log_page_size);
+
+void fs_store_dump(char *fname);
+void fs_load_dump(char *fname);
+
+void fs_set_addr_offset(u32_t offset);
+int read_and_verify(char *name);
+int read_and_verify_fd(spiffs_file fd, char *name);
+void dump_page(spiffs *fs, spiffs_page_ix p);
+void hexdump(u32_t addr, u32_t len);
+char *make_test_fname(const char *name);
+void clear_test_path();
+void area_write(u32_t addr, u8_t *buf, u32_t size);
+void area_set(u32_t addr, u8_t d, u32_t size);
+void area_read(u32_t addr, u8_t *buf, u32_t size);
+void dump_erase_counts(spiffs *fs);
+void dump_flash_access_stats();
+void set_flash_ops_log(int enable);
+void clear_flash_ops_log();
+u32_t get_flash_ops_log_read_bytes();
+u32_t get_flash_ops_log_write_bytes();
+void invoke_error_after_read_bytes(u32_t b, char once_only);
+void invoke_error_after_write_bytes(u32_t b, char once_only);
+void fs_set_validate_flashing(int i);
+
+void memrand(u8_t *b, int len);
+int test_create_file(char *name);
+int test_create_and_write_file(char *name, int size, int chunk_size);
+u32_t get_spiffs_file_crc_by_fd(spiffs_file fd);
+u32_t get_spiffs_file_crc(char *name);
+void _setup();
+void _setup_test_only();
+void _teardown();
+u32_t tfile_get_size(tfile_size s);
+int run_file_config(int cfg_count, tfile_conf* cfgs, int max_runs, int max_concurrent_files, int dbg);
+
+void test_lock(spiffs *fs);
+void test_unlock(spiffs *fs);
+
+#endif /* TEST_SPIFFS_H_ */
diff --git a/fw/User/spiffs/src/test/testrunner.c b/fw/User/spiffs/src/test/testrunner.c
new file mode 100644
index 0000000..96fa1a3
--- /dev/null
+++ b/fw/User/spiffs/src/test/testrunner.c
@@ -0,0 +1,212 @@
+/*
+ * testrunner.c
+ *
+ * Created on: Jun 18, 2013
+ * Author: petera
+ */
+
+
+#include
+#include
+#include
+
+#include
+#include
+#include
+#include
+#include
+
+#include "testrunner.h"
+
+static struct {
+ test *tests;
+ test *_last_test;
+ int test_count;
+ void (*on_stop)(test *t);
+ test_res *failed;
+ test_res *failed_last;
+ test_res *stopped;
+ test_res *stopped_last;
+ FILE *spec;
+ char incl_filter[256];
+ char excl_filter[256];
+} test_main;
+
+void test_init(void (*on_stop)(test *t)) {
+ test_main.on_stop = on_stop;
+}
+
+static char check_spec(char *name) {
+ if (test_main.spec) {
+ fseek(test_main.spec, 0, SEEK_SET);
+ char *line = NULL;
+ size_t sz;
+ ssize_t read;
+ while ((read = getline(&line, &sz, test_main.spec)) != -1) {
+ if (strncmp(line, name, strlen(line)-1) == 0) {
+ free(line);
+ return 1;
+ }
+ }
+ free(line);
+ return 0;
+ } else {
+ return 1;
+ }
+}
+
+static char check_incl_filter(char *name) {
+ if (strlen(test_main.incl_filter)== 0) return 1;
+ return strstr(name, test_main.incl_filter) == 0 ? 0 : 1;
+}
+
+static char check_excl_filter(char *name) {
+ if (strlen(test_main.excl_filter)== 0) return 1;
+ return strstr(name, test_main.excl_filter) == 0 ? 1 : 0;
+}
+
+void _add_test(test_f f, char *name, void (*setup)(test *t), void (*teardown)(test *t)) {
+ if (f == 0) return;
+ if (!check_spec(name)) return;
+ if (!check_incl_filter(name)) return;
+ if (!check_excl_filter(name)) return;
+ DBGT("adding test %s\n", name);
+ test *t = malloc(sizeof(test));
+ memset(t, 0, sizeof(test));
+ t->f = f;
+ strcpy(t->name, name);
+ t->setup = setup;
+ t->teardown = teardown;
+ if (test_main.tests == 0) {
+ test_main.tests = t;
+ } else {
+ test_main._last_test->_next = t;
+ }
+ test_main._last_test = t;
+ test_main.test_count++;
+}
+
+static void add_res(test *t, test_res **head, test_res **last) {
+ test_res *tr = malloc(sizeof(test_res));
+ memset(tr,0,sizeof(test_res));
+ strcpy(tr->name, t->name);
+ if (*head == 0) {
+ *head = tr;
+ } else {
+ (*last)->_next = tr;
+ }
+ *last = tr;
+}
+
+static void dump_res(test_res **head) {
+ test_res *tr = (*head);
+ while (tr) {
+ test_res *next_tr = tr->_next;
+ printf(" %s\n", tr->name);
+ free(tr);
+ tr = next_tr;
+ }
+}
+
+int run_tests(int argc, char **args) {
+ memset(&test_main, 0, sizeof(test_main));
+ int arg;
+ int incl_filter = 0;
+ int excl_filter = 0;
+ for (arg = 1; arg < argc; arg++) {
+ if (strlen(args[arg]) == 0) continue;
+ if (0 == strcmp("-f", args[arg])) {
+ incl_filter = 1;
+ continue;
+ }
+ if (0 == strcmp("-e", args[arg])) {
+ excl_filter = 1;
+ continue;
+ }
+ if (incl_filter) {
+ strcpy(test_main.incl_filter, args[arg]);
+ incl_filter = 0;
+ } else if (excl_filter) {
+ strcpy(test_main.excl_filter, args[arg]);
+ excl_filter = 0;
+ } else {
+ printf("running tests from %s\n", args[arg]);
+ FILE *fd = fopen(args[1], "r");
+ if (fd == NULL) {
+ printf("%s not found\n", args[arg]);
+ return -2;
+ }
+ test_main.spec = fd;
+ }
+ }
+
+ DBGT("adding suites...\n");
+ add_suites();
+ DBGT("%i tests added\n", test_main.test_count);
+ if (test_main.spec) {
+ fclose(test_main.spec);
+ }
+
+ if (test_main.test_count == 0) {
+ printf("No tests to run\n");
+ return 0;
+ }
+
+ int fd_success = open("_tests_ok", O_APPEND | O_TRUNC | O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
+ int fd_bad = open("_tests_fail", O_APPEND | O_TRUNC | O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
+
+ DBGT("running tests...\n");
+ int ok = 0;
+ int failed = 0;
+ int stopped = 0;
+ test *cur_t = test_main.tests;
+ int i = 1;
+ while (cur_t) {
+ cur_t->setup(cur_t);
+ test *next_test = cur_t->_next;
+ DBGT("TEST %i/%i : running test %s\n", i, test_main.test_count, cur_t->name);
+ i++;
+ int res = cur_t->f(cur_t);
+ cur_t->test_result = res;
+ int fd = res == TEST_RES_OK ? fd_success : fd_bad;
+ write(fd, cur_t->name, strlen(cur_t->name));
+ write(fd, "\n", 1);
+ switch (res) {
+ case TEST_RES_OK:
+ ok++;
+ printf(" .. ok\n");
+ break;
+ case TEST_RES_FAIL:
+ failed++;
+ printf(" .. FAILED\n");
+ if (test_main.on_stop) test_main.on_stop(cur_t);
+ add_res(cur_t, &test_main.failed, &test_main.failed_last);
+ break;
+ case TEST_RES_ASSERT:
+ stopped++;
+ printf(" .. ABORTED\n");
+ if (test_main.on_stop) test_main.on_stop(cur_t);
+ add_res(cur_t, &test_main.stopped, &test_main.stopped_last);
+ break;
+ }
+ cur_t->teardown(cur_t);
+ free(cur_t);
+ cur_t = next_test;
+ }
+ close(fd_success);
+ close(fd_bad);
+ DBGT("ran %i tests\n", test_main.test_count);
+ printf("Test report, %i tests\n", test_main.test_count);
+ printf("%i succeeded\n", ok);
+ printf("%i failed\n", failed);
+ dump_res(&test_main.failed);
+ printf("%i stopped\n", stopped);
+ dump_res(&test_main.stopped);
+ if (ok < test_main.test_count) {
+ printf("\nFAILED\n");
+ return -1;
+ } else {
+ printf("\nALL TESTS OK\n");
+ return 0;
+ }
+}
diff --git a/fw/User/spiffs/src/test/testrunner.h b/fw/User/spiffs/src/test/testrunner.h
new file mode 100644
index 0000000..c64c920
--- /dev/null
+++ b/fw/User/spiffs/src/test/testrunner.h
@@ -0,0 +1,155 @@
+/*
+ * testrunner.h
+ *
+ * Created on: Jun 19, 2013
+ * Author: petera
+ */
+
+/*
+
+file mysuite.c:
+
+SUITE(mysuite)
+
+static void setup(test *t) {}
+
+static void teardown(test *t) {}
+
+TEST(mytest) {
+ printf("mytest runs now..\n");
+ return 0;
+} TEST_END
+
+SUITE_TESTS(mysuite)
+ ADD_TEST(mytest)
+SUITE_END(mysuite)
+
+
+
+file mysuite2.c:
+
+SUITE(mysuite2)
+
+static void setup(test *t) {}
+
+static void teardown(test *t) {}
+
+TEST(mytest2a) {
+ printf("mytest2a runs now..\n");
+ return 0;
+} TEST_END
+
+TEST(mytest2b) {
+ printf("mytest2b runs now..\n");
+ return 0;
+} TEST_END
+
+SUITE_TESTS(mysuite2)
+ ADD_TEST(mytest2a)
+ ADD_TEST(mytest2b)
+SUITE_END(mysuite2)
+
+
+some other file.c:
+
+void add_suites() {
+ ADD_SUITE(mysuite);
+ ADD_SUITE(mysuite2);
+}
+ */
+
+#ifndef TESTRUNNER_H_
+#define TESTRUNNER_H_
+
+#define TEST_RES_OK 0
+#define TEST_RES_FAIL -1
+#define TEST_RES_ASSERT -2
+
+struct test_s;
+
+typedef int (*test_f)(struct test_s *t);
+
+typedef struct test_s {
+ test_f f;
+ char name[256];
+ void *data;
+ void (*setup)(struct test_s *t);
+ void (*teardown)(struct test_s *t);
+ struct test_s *_next;
+ unsigned char test_result;
+} test;
+
+typedef struct test_res_s {
+ char name[256];
+ struct test_res_s *_next;
+} test_res;
+
+#define TEST_CHECK(x) if (!(x)) { \
+ printf(" TEST FAIL %s:%i\n", __FILE__, __LINE__); \
+ goto __fail_stop; \
+}
+#define TEST_CHECK_EQ(x, y) if ((x) != (y)) { \
+ printf(" TEST FAIL %s:%i, %i != %i\n", __FILE__, __LINE__, (x), (y)); \
+ goto __fail_stop; \
+}
+#define TEST_CHECK_NEQ(x, y) if ((x) == (y)) { \
+ printf(" TEST FAIL %s:%i, %i == %i\n", __FILE__, __LINE__, (x), (y)); \
+ goto __fail_stop; \
+}
+#define TEST_CHECK_GT(x, y) if ((x) <= (y)) { \
+ printf(" TEST FAIL %s:%i, %i <= %i\n", __FILE__, __LINE__, (x), (y)); \
+ goto __fail_stop; \
+}
+#define TEST_CHECK_LT(x, y) if ((x) >= (y)) { \
+ printf(" TEST FAIL %s:%i, %i >= %i\n", __FILE__, __LINE__, (x), (y)); \
+ goto __fail_stop; \
+}
+#define TEST_CHECK_GE(x, y) if ((x) < (y)) { \
+ printf(" TEST FAIL %s:%i, %i < %i\n", __FILE__, __LINE__, (x), (y)); \
+ goto __fail_stop; \
+}
+#define TEST_CHECK_LE(x, y) if ((x) > (y)) { \
+ printf(" TEST FAIL %s:%i, %i > %i\n", __FILE__, __LINE__, (x), (y)); \
+ goto __fail_stop; \
+}
+#define TEST_ASSERT(x) if (!(x)) { \
+ printf(" TEST ASSERT %s:%i\n", __FILE__, __LINE__); \
+ goto __fail_assert; \
+}
+
+#define DBGT(...) printf(__VA_ARGS__)
+
+#define str(s) #s
+
+#define SUITE(sui)
+
+#define SUITE_TESTS(sui) \
+ void _add_suite_tests_##sui(void) {
+
+#define SUITE_END(sui) \
+ }
+
+#define ADD_TEST(tf) \
+ _add_test(__test_##tf, str(tf), setup, teardown);
+
+#define ADD_SUITE(sui) \
+ extern void _add_suite_tests_##sui(void); \
+ _add_suite_tests_##sui();
+
+#define TEST(tf) \
+ static int __test_##tf(struct test_s *t) { do
+
+#define TEST_END \
+ while(0); \
+ __fail_stop: return TEST_RES_FAIL; \
+ __fail_assert: return TEST_RES_ASSERT; \
+ }
+
+void add_suites();
+void test_init(void (*on_stop)(test *t));
+// returns 0 if all tests ok, -1 if any test failed, -2 on badness
+int run_tests(int argc, char **args);
+void _add_suite(const char *suite_name);
+void _add_test(test_f f, char *name, void (*setup)(test *t), void (*teardown)(test *t));
+
+#endif /* TESTRUNNER_H_ */
diff --git a/fw/User/spiffs/src/test/testsuites.c b/fw/User/spiffs/src/test/testsuites.c
new file mode 100644
index 0000000..f572287
--- /dev/null
+++ b/fw/User/spiffs/src/test/testsuites.c
@@ -0,0 +1,15 @@
+/*
+ * testsuites.c
+ *
+ * Created on: Jun 19, 2013
+ * Author: petera
+ */
+
+#include "testrunner.h"
+
+void add_suites() {
+ //ADD_SUITE(dev_tests);
+ ADD_SUITE(check_tests);
+ ADD_SUITE(hydrogen_tests);
+ ADD_SUITE(bug_tests);
+}
diff --git a/fw/User/spiffs_config.h b/fw/User/spiffs_config.h
new file mode 100644
index 0000000..da7a424
--- /dev/null
+++ b/fw/User/spiffs_config.h
@@ -0,0 +1,219 @@
+
+#ifndef SPIFFS_CONFIG_H_
+#define SPIFFS_CONFIG_H_
+
+// Following includes are for the linux test build of spiffs
+// These may/should/must be removed/altered/replaced in your target
+#include
+#include
+#include
+#include
+#include
+
+#include "platform.h"
+#include "syslog.h"
+extern SemaphoreHandle_t spiffs_lock;
+
+// Set generic spiffs debug output call.
+#ifndef SPIFFS_DBG
+//#define SPIFFS_DBG(...) syslog_printf(__VA_ARGS__)
+#define SPIFFS_DBG(...)
+#endif
+// Set spiffs debug output call for garbage collecting.
+#ifndef SPIFFS_GC_DBG
+//#define SPIFFS_GC_DBG(...) syslog_printf(__VA_ARGS__)
+#define SPIFFS_GC_DBG(...)
+#endif
+// Set spiffs debug output call for caching.
+#ifndef SPIFFS_CACHE_DBG
+//#define SPIFFS_CACHE_DBG(...) syslog_printf(__VA_ARGS__)
+#define SPIFFS_CACHE_DBG(...)
+#endif
+// Set spiffs debug output call for system consistency checks.
+#ifndef SPIFFS_CHECK_DBG
+//#define SPIFFS_CHECK_DBG(...) syslog_printf(__VA_ARGS__)
+#define SPIFFS_CHECK_DBG(...)
+#endif
+
+// Enable/disable API functions to determine exact number of bytes
+// for filedescriptor and cache buffers. Once decided for a configuration,
+// this can be disabled to reduce flash.
+#ifndef SPIFFS_BUFFER_HELP
+#define SPIFFS_BUFFER_HELP 0
+#endif
+
+// Enables/disable memory read caching of nucleus file system operations.
+// If enabled, memory area must be provided for cache in SPIFFS_mount.
+#ifndef SPIFFS_CACHE
+#define SPIFFS_CACHE 1
+#endif
+#if SPIFFS_CACHE
+// Enables memory write caching for file descriptors in hydrogen
+#ifndef SPIFFS_CACHE_WR
+#define SPIFFS_CACHE_WR 0
+#endif
+
+// Enable/disable statistics on caching. Debug/test purpose only.
+#ifndef SPIFFS_CACHE_STATS
+#define SPIFFS_CACHE_STATS 0
+#endif
+#endif
+
+// Always check header of each accessed page to ensure consistent state.
+// If enabled it will increase number of reads, will increase flash.
+#ifndef SPIFFS_PAGE_CHECK
+#define SPIFFS_PAGE_CHECK 3
+#endif
+
+// Define maximum number of gc runs to perform to reach desired free pages.
+#ifndef SPIFFS_GC_MAX_RUNS
+#define SPIFFS_GC_MAX_RUNS 3
+#endif
+
+// Enable/disable statistics on gc. Debug/test purpose only.
+#ifndef SPIFFS_GC_STATS
+#define SPIFFS_GC_STATS 0
+#endif
+
+// Garbage collecting examines all pages in a block which and sums up
+// to a block score. Deleted pages normally gives positive score and
+// used pages normally gives a negative score (as these must be moved).
+// To have a fair wear-leveling, the erase age is also included in score,
+// whose factor normally is the most positive.
+// The larger the score, the more likely it is that the block will
+// picked for garbage collection.
+
+// Garbage collecting heuristics - weight used for deleted pages.
+#ifndef SPIFFS_GC_HEUR_W_DELET
+#define SPIFFS_GC_HEUR_W_DELET (5)
+#endif
+// Garbage collecting heuristics - weight used for used pages.
+#ifndef SPIFFS_GC_HEUR_W_USED
+#define SPIFFS_GC_HEUR_W_USED (-1)
+#endif
+// Garbage collecting heuristics - weight used for time between
+// last erased and erase of this block.
+#ifndef SPIFFS_GC_HEUR_W_ERASE_AGE
+#define SPIFFS_GC_HEUR_W_ERASE_AGE (50)
+#endif
+
+// Object name maximum length.
+#ifndef SPIFFS_OBJ_NAME_LEN
+#define SPIFFS_OBJ_NAME_LEN (32)
+#endif
+
+// Size of buffer allocated on stack used when copying data.
+// Lower value generates more read/writes. No meaning having it bigger
+// than logical page size.
+#ifndef SPIFFS_COPY_BUFFER_STACK
+#define SPIFFS_COPY_BUFFER_STACK (64)
+#endif
+
+// Enable this to have an identifiable spiffs filesystem. This will look for
+// a magic in all sectors to determine if this is a valid spiffs system or
+// not on mount point. If not, SPIFFS_format must be called prior to mounting
+// again.
+#ifndef SPIFFS_USE_MAGIC
+#define SPIFFS_USE_MAGIC (1)
+#endif
+
+#if SPIFFS_USE_MAGIC
+// Only valid when SPIFFS_USE_MAGIC is enabled. If SPIFFS_USE_MAGIC_LENGTH is
+// enabled, the magic will also be dependent on the length of the filesystem.
+// For example, a filesystem configured and formatted for 4 megabytes will not
+// be accepted for mounting with a configuration defining the filesystem as 2
+// megabytes.
+#ifndef SPIFFS_USE_MAGIC_LENGTH
+#define SPIFFS_USE_MAGIC_LENGTH (1)
+#endif
+#endif
+
+// SPIFFS_LOCK and SPIFFS_UNLOCK protects spiffs from reentrancy on api level
+// These should be defined on a multithreaded system
+
+// define this to entering a mutex if you're running on a multithreaded system
+#ifndef SPIFFS_LOCK
+#define SPIFFS_LOCK(fs) xSemaphoreTake(spiffs_lock, portMAX_DELAY);
+#endif
+// define this to exiting a mutex if you're running on a multithreaded system
+#ifndef SPIFFS_UNLOCK
+#define SPIFFS_UNLOCK(fs) xSemaphoreGive(spiffs_lock);
+#endif
+
+
+// Enable if only one spiffs instance with constant configuration will exist
+// on the target. This will reduce calculations, flash and memory accesses.
+// Parts of configuration must be defined below instead of at time of mount.
+#ifndef SPIFFS_SINGLETON
+#define SPIFFS_SINGLETON 1
+#endif
+
+#if SPIFFS_SINGLETON
+//// Instead of giving parameters in config struct, singleton build must
+//// give parameters in defines below.
+#ifndef SPIFFS_CFG_PHYS_SZ
+#define SPIFFS_CFG_PHYS_SZ(ignore) (4*1024*1024)
+#endif
+#ifndef SPIFFS_CFG_PHYS_ERASE_SZ
+#define SPIFFS_CFG_PHYS_ERASE_SZ(ignore) (4096)
+#endif
+#ifndef SPIFFS_CFG_PHYS_ADDR
+#define SPIFFS_CFG_PHYS_ADDR(ignore) (0)
+#endif
+#ifndef SPIFFS_CFG_LOG_PAGE_SZ
+#define SPIFFS_CFG_LOG_PAGE_SZ(ignore) (256)
+#endif
+#ifndef SPIFFS_CFG_LOG_BLOCK_SZ
+#define SPIFFS_CFG_LOG_BLOCK_SZ(ignore) (65536)
+#endif
+#endif
+
+//// Set SPFIFS_TEST_VISUALISATION to non-zero to enable SPIFFS_vis function
+//// in the api. This function will visualize all filesystem using given printf
+//// function.
+#ifndef SPIFFS_TEST_VISUALISATION
+#define SPIFFS_TEST_VISUALISATION 0
+#endif
+#if SPIFFS_TEST_VISUALISATION
+#ifndef spiffs_printf
+#define spiffs_printf(...) printf(__VA_ARGS__)
+#endif
+// spiffs_printf argument for a free page
+#ifndef SPIFFS_TEST_VIS_FREE_STR
+#define SPIFFS_TEST_VIS_FREE_STR "_"
+#endif
+// spiffs_printf argument for a deleted page
+#ifndef SPIFFS_TEST_VIS_DELE_STR
+#define SPIFFS_TEST_VIS_DELE_STR "/"
+#endif
+// spiffs_printf argument for an index page for given object id
+#ifndef SPIFFS_TEST_VIS_INDX_STR
+#define SPIFFS_TEST_VIS_INDX_STR(id) "i"
+#endif
+// spiffs_printf argument for a data page for given object id
+#ifndef SPIFFS_TEST_VIS_DATA_STR
+#define SPIFFS_TEST_VIS_DATA_STR(id) "d"
+#endif
+#endif
+
+// Types depending on configuration such as the amount of flash bytes
+// given to spiffs file system in total (spiffs_file_system_size),
+// the logical block size (log_block_size), and the logical page size
+// (log_page_size)
+
+// Block index type. Make sure the size of this type can hold
+// the highest number of all blocks - i.e. spiffs_file_system_size / log_block_size
+typedef uint16_t spiffs_block_ix;
+// Page index type. Make sure the size of this type can hold
+// the highest page number of all pages - i.e. spiffs_file_system_size / log_page_size
+typedef uint16_t spiffs_page_ix;
+// Object id type - most significant bit is reserved for index flag. Make sure the
+// size of this type can hold the highest object id on a full system,
+// i.e. 2 + (spiffs_file_system_size / (2*log_page_size))*2
+typedef uint16_t spiffs_obj_id;
+// Object span index type. Make sure the size of this type can
+// hold the largest possible span index on the system -
+// i.e. (spiffs_file_system_size / log_page_size) - 1
+typedef uint16_t spiffs_span_ix;
+
+#endif /* SPIFFS_CONFIG_H_ */
diff --git a/fw/User/spiflash.c b/fw/User/spiflash.c
new file mode 100644
index 0000000..8af001c
--- /dev/null
+++ b/fw/User/spiflash.c
@@ -0,0 +1,536 @@
+//
+// Grimoire
+// Copyright 2025 Wenting Zhang
+//
+// 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.
+//
+#include "platform.h"
+#include "board.h"
+#include "app.h"
+
+/* Reset Operations */
+#define RESET_ENABLE_CMD 0x66
+#define RESET_MEMORY_CMD 0x99
+
+/* Identification Operations */
+#define READ_ID_CMD 0x9E
+#define READ_ID_CMD2 0x9F
+#define MULTIPLE_IO_READ_ID_CMD 0xAF
+#define READ_SERIAL_FLASH_DISCO_PARAM_CMD 0x5A
+
+/* Read Operations */
+#define READ_CMD 0x03
+#define FAST_READ_CMD 0x0B
+#define DUAL_OUT_FAST_READ_CMD 0x3B
+#define DUAL_INOUT_FAST_READ_CMD 0xBB
+#define QUAD_OUT_FAST_READ_CMD 0x6B
+#define QUAD_INOUT_FAST_READ_CMD 0xEB
+
+/* Write Operations */
+#define WRITE_ENABLE_CMD 0x06
+#define WRITE_DISABLE_CMD 0x04
+
+/* Register Operations */
+#define READ_STATUS_REG_CMD 0x05
+#define WRITE_STATUS_REG_CMD 0x01
+
+#define READ_LOCK_REG_CMD 0xE8
+#define WRITE_LOCK_REG_CMD 0xE5
+
+#define READ_FLAG_STATUS_REG_CMD 0x70
+#define CLEAR_FLAG_STATUS_REG_CMD 0x50
+
+#define READ_NONVOL_CFG_REG_CMD 0xB5
+#define WRITE_NONVOL_CFG_REG_CMD 0xB1
+
+#define READ_VOL_CFG_REG_CMD 0x85
+#define WRITE_VOL_CFG_REG_CMD 0x81
+
+#define READ_ENHANCED_VOL_CFG_REG_CMD 0x65
+#define WRITE_ENHANCED_VOL_CFG_REG_CMD 0x61
+
+/* Program Operations */
+#define PAGE_PROG_CMD 0x02
+#define DUAL_IN_FAST_PROG_CMD 0xA2
+#define EXT_DUAL_IN_FAST_PROG_CMD 0xD2
+#define QUAD_IN_FAST_PROG_CMD 0x32
+#define EXT_QUAD_IN_FAST_PROG_CMD 0x12
+
+/* Erase Operations */
+#define SUBSECTOR_ERASE_CMD 0x20
+#define SECTOR_ERASE_CMD 0xD8
+#define BULK_ERASE_CMD 0xC7
+
+#define PROG_ERASE_RESUME_CMD 0x7A
+#define PROG_ERASE_SUSPEND_CMD 0x75
+
+/* One-Time Programmable Operations */
+#define READ_OTP_ARRAY_CMD 0x4B
+#define PROG_OTP_ARRAY_CMD 0x42
+
+static int spif_auto_polling_mem_ready(uint32_t timeout) {
+ QSPI_CommandTypeDef s_command;
+ QSPI_AutoPollingTypeDef s_config;
+
+ /* Configure automatic polling mode to wait for memory ready */
+ s_command.InstructionMode = QSPI_INSTRUCTION_1_LINE;
+ s_command.Instruction = READ_STATUS_REG_CMD;
+ s_command.AddressMode = QSPI_ADDRESS_NONE;
+ s_command.AlternateByteMode = QSPI_ALTERNATE_BYTES_NONE;
+ s_command.DataMode = QSPI_DATA_1_LINE;
+ s_command.DummyCycles = 0;
+ s_command.DdrMode = QSPI_DDR_MODE_DISABLE;
+ s_command.DdrHoldHalfCycle = QSPI_DDR_HHC_ANALOG_DELAY;
+ s_command.SIOOMode = QSPI_SIOO_INST_EVERY_CMD;
+
+ s_config.Match = 0;
+ s_config.MatchMode = QSPI_MATCH_MODE_AND;
+ s_config.Interval = 0x10;
+ s_config.AutomaticStop = QSPI_AUTOMATIC_STOP_ENABLE;
+ s_config.Mask = SPIF_SR_WIP;
+ s_config.StatusBytesSize = 2;
+
+ if (HAL_QSPI_AutoPolling(&hqspi, &s_command, &s_config, timeout) != HAL_OK)
+ return -1;
+
+ return 0;
+}
+
+static int spif_reset_memory(void) {
+ QSPI_CommandTypeDef s_command;
+
+ s_command.InstructionMode = QSPI_INSTRUCTION_1_LINE;
+ s_command.Instruction = RESET_ENABLE_CMD;
+ s_command.AddressMode = QSPI_ADDRESS_NONE;
+ s_command.AlternateByteMode = QSPI_ALTERNATE_BYTES_NONE;
+ s_command.DataMode = QSPI_DATA_NONE;
+ s_command.DummyCycles = 0;
+ s_command.DdrMode = QSPI_DDR_MODE_DISABLE;
+ s_command.DdrHoldHalfCycle = QSPI_DDR_HHC_ANALOG_DELAY;
+ s_command.SIOOMode = QSPI_SIOO_INST_EVERY_CMD;
+
+ if (HAL_QSPI_Command(&hqspi, &s_command, HAL_QSPI_TIMEOUT_DEFAULT_VALUE) != HAL_OK)
+ return -1;
+
+ s_command.Instruction = RESET_MEMORY_CMD;
+
+ if (HAL_QSPI_Command(&hqspi, &s_command, HAL_QSPI_TIMEOUT_DEFAULT_VALUE) != HAL_OK)
+ return -1;
+
+ return spif_auto_polling_mem_ready(HAL_QSPI_TIMEOUT_DEFAULT_VALUE);
+}
+
+static int spif_write_enable(void) {
+ QSPI_CommandTypeDef s_command;
+ QSPI_AutoPollingTypeDef s_config;
+
+ /* Enable write operations */
+ s_command.InstructionMode = QSPI_INSTRUCTION_1_LINE;
+ s_command.Instruction = WRITE_ENABLE_CMD;
+ s_command.AddressMode = QSPI_ADDRESS_NONE;
+ s_command.AlternateByteMode = QSPI_ALTERNATE_BYTES_NONE;
+ s_command.DataMode = QSPI_DATA_NONE;
+ s_command.DummyCycles = 0;
+ s_command.DdrMode = QSPI_DDR_MODE_DISABLE;
+ s_command.DdrHoldHalfCycle = QSPI_DDR_HHC_ANALOG_DELAY;
+ s_command.SIOOMode = QSPI_SIOO_INST_EVERY_CMD;
+
+ if (HAL_QSPI_Command(&hqspi, &s_command, HAL_QSPI_TIMEOUT_DEFAULT_VALUE) != HAL_OK)
+ return -1;
+
+ /* Configure automatic polling mode to wait for write enabling */
+ s_config.Match = SPIF_SR_WREN;
+ s_config.Mask = SPIF_SR_WREN;
+ s_config.MatchMode = QSPI_MATCH_MODE_AND;
+ s_config.StatusBytesSize = 1;
+ s_config.Interval = 0x10;
+ s_config.AutomaticStop = QSPI_AUTOMATIC_STOP_ENABLE;
+
+ s_command.Instruction = READ_STATUS_REG_CMD;
+ s_command.DataMode = QSPI_DATA_1_LINE;
+
+ if (HAL_QSPI_AutoPolling(&hqspi, &s_command, &s_config, HAL_QSPI_TIMEOUT_DEFAULT_VALUE) != HAL_OK)
+ return -1;
+}
+
+static int spif_dummy_cycles_cfg(void) {
+ QSPI_CommandTypeDef s_command;
+ uint8_t reg = 0;
+
+ /* Initialize the read volatile configuration register command */
+ s_command.InstructionMode = QSPI_INSTRUCTION_1_LINE;
+ s_command.Instruction = READ_VOL_CFG_REG_CMD;
+ s_command.AddressMode = QSPI_ADDRESS_NONE;
+ s_command.AlternateByteMode = QSPI_ALTERNATE_BYTES_NONE;
+ s_command.DataMode = QSPI_DATA_1_LINE;
+ s_command.DummyCycles = 0;
+ s_command.NbData = 1;
+ s_command.DdrMode = QSPI_DDR_MODE_DISABLE;
+ s_command.DdrHoldHalfCycle = QSPI_DDR_HHC_ANALOG_DELAY;
+ s_command.SIOOMode = QSPI_SIOO_INST_EVERY_CMD;
+
+ /* Configure the command */
+ if (HAL_QSPI_Command(&hqspi, &s_command, HAL_QSPI_TIMEOUT_DEFAULT_VALUE) != HAL_OK)
+ return -1;
+
+ /* Reception of the data */
+ if (HAL_QSPI_Receive(&hqspi, (uint8_t *)(®), HAL_QSPI_TIMEOUT_DEFAULT_VALUE) != HAL_OK)
+ return -1;
+
+ /* Enable write operations */
+ if (spif_write_enable() != 0)
+ return -1;
+
+ /* Update volatile configuration register (with new dummy cycles) */
+ s_command.Instruction = WRITE_VOL_CFG_REG_CMD;
+ MODIFY_REG(reg, 0xF0F0, (SPIF_DUMMY_CYCLES_READ_QUAD << 4));
+
+ /* Configure the write volatile configuration register command */
+ if (HAL_QSPI_Command(&hqspi, &s_command, HAL_QSPI_TIMEOUT_DEFAULT_VALUE) != HAL_OK)
+ return -1;
+
+ /* Transmission of the data */
+ if (HAL_QSPI_Transmit(&hqspi, (uint8_t *)(®), HAL_QSPI_TIMEOUT_DEFAULT_VALUE) != HAL_OK)
+ return -1;
+
+ return 0;
+}
+
+int spif_init(void) {
+ int result;
+ result = spif_reset_memory();
+ //result += spif_dummy_cycles_cfg();
+ if (result != 0) {
+ syslog_printf("SPI flash initialization failed");
+ }
+ return result;
+}
+
+// TODO: Should have been a semaphore
+static volatile bool tx_complete = false;
+static volatile bool rx_complete = false;
+
+void HAL_QSPI_TxCpltCallback(QSPI_HandleTypeDef *hqspi) {
+ tx_complete = true;
+}
+
+void HAL_QSPI_RxCpltCallback(QSPI_HandleTypeDef *hqspi) {
+ rx_complete = true;
+}
+
+int spif_read(uint32_t addr, uint32_t size, uint8_t *dat) {
+ static QSPI_CommandTypeDef s_command = {
+ .InstructionMode = QSPI_INSTRUCTION_1_LINE,
+ .Instruction = QUAD_INOUT_FAST_READ_CMD,
+ .AddressMode = QSPI_ADDRESS_4_LINES,
+ .AddressSize = QSPI_ADDRESS_24_BITS,
+ .AlternateByteMode = QSPI_ALTERNATE_BYTES_NONE,
+ .DataMode = QSPI_DATA_4_LINES,
+ .DummyCycles = SPIF_DUMMY_CYCLES_READ_QUAD,
+ .DdrMode = QSPI_DDR_MODE_DISABLE,
+ .DdrHoldHalfCycle = QSPI_DDR_HHC_ANALOG_DELAY,
+ .SIOOMode = QSPI_SIOO_INST_EVERY_CMD,
+ };
+
+ /* Initialize the read command */
+ s_command.Address = addr;
+ s_command.NbData = size;
+
+ /* Configure the command */
+ if (HAL_QSPI_Command(&hqspi, &s_command, HAL_QSPI_TIMEOUT_DEFAULT_VALUE) != HAL_OK)
+ return -1;
+
+ rx_complete = false;
+
+ /* Reception of the data */
+ if (HAL_QSPI_Receive_DMA(&hqspi, dat) != HAL_OK)
+ return -1;
+
+ while (!rx_complete);
+
+ return 0;
+}
+
+int spif_write(uint32_t addr, uint32_t size, uint8_t *dat) {
+ QSPI_CommandTypeDef s_command;
+ uint32_t end_addr, current_size, current_addr;
+
+ /* Calculation of the size between the write address and the end of the page */
+ current_size = SPIF_PAGE_SIZE - (addr % SPIF_PAGE_SIZE);
+
+ /* Check if the size of the data is less than the remaining place in the page */
+ if (current_size > size) {
+ current_size = size;
+ }
+
+ /* Initialize the adress variables */
+ current_addr = addr;
+ end_addr = addr + size;
+
+ /* Initialize the program command */
+ s_command.InstructionMode = QSPI_INSTRUCTION_1_LINE;
+ s_command.Instruction = QUAD_IN_FAST_PROG_CMD;
+ s_command.AddressMode = QSPI_ADDRESS_1_LINE;
+ s_command.AddressSize = QSPI_ADDRESS_24_BITS;
+ s_command.AlternateByteMode = QSPI_ALTERNATE_BYTES_NONE;
+ s_command.DataMode = QSPI_DATA_4_LINES;
+ s_command.DummyCycles = 0;
+ s_command.DdrMode = QSPI_DDR_MODE_DISABLE;
+ s_command.DdrHoldHalfCycle = QSPI_DDR_HHC_ANALOG_DELAY;
+ s_command.SIOOMode = QSPI_SIOO_INST_EVERY_CMD;
+
+ /* Perform the write page by page */
+ do {
+ s_command.Address = current_addr;
+ s_command.NbData = current_size;
+
+ if (spif_write_enable() != 0)
+ return -1;
+
+ if (HAL_QSPI_Command(&hqspi, &s_command, HAL_QSPI_TIMEOUT_DEFAULT_VALUE) != HAL_OK)
+ return -1;
+
+ tx_complete = false;
+
+ if (HAL_QSPI_Transmit_DMA(&hqspi, dat) != HAL_OK)
+ return -1;
+
+ while (!tx_complete);
+
+ if (spif_auto_polling_mem_ready(HAL_QSPI_TIMEOUT_DEFAULT_VALUE) != 0)
+ return -1;
+
+ current_addr += current_size;
+ dat += current_size;
+ current_size = ((current_addr + SPIF_PAGE_SIZE) > end_addr) ? (end_addr - current_addr) : SPIF_PAGE_SIZE;
+ } while (current_addr < end_addr);
+
+ return 0;
+}
+
+int spif_erase_block(uint32_t block) {
+ QSPI_CommandTypeDef s_command;
+
+ /* Initialize the erase command */
+ s_command.InstructionMode = QSPI_INSTRUCTION_1_LINE;
+ s_command.Instruction = SUBSECTOR_ERASE_CMD;
+ s_command.AddressMode = QSPI_ADDRESS_1_LINE;
+ s_command.AddressSize = QSPI_ADDRESS_24_BITS;
+ s_command.Address = block;
+ s_command.AlternateByteMode = QSPI_ALTERNATE_BYTES_NONE;
+ s_command.DataMode = QSPI_DATA_NONE;
+ s_command.DummyCycles = 0;
+ s_command.DdrMode = QSPI_DDR_MODE_DISABLE;
+ s_command.DdrHoldHalfCycle = QSPI_DDR_HHC_ANALOG_DELAY;
+ s_command.SIOOMode = QSPI_SIOO_INST_EVERY_CMD;
+
+ if (spif_write_enable() != 0)
+ return -1;
+
+ if (HAL_QSPI_Command(&hqspi, &s_command, HAL_QSPI_TIMEOUT_DEFAULT_VALUE) != HAL_OK)
+ return -1;
+
+ if (spif_auto_polling_mem_ready(SPIF_SUBSECTOR_ERASE_TIMEOUT) != 0)
+ return -1;
+}
+
+int spif_erase_sector(uint32_t sector) {
+ QSPI_CommandTypeDef s_command;
+
+ /* Initialize the erase command */
+ s_command.InstructionMode = QSPI_INSTRUCTION_1_LINE;
+ s_command.Instruction = SECTOR_ERASE_CMD;
+ s_command.AddressMode = QSPI_ADDRESS_1_LINE;
+ s_command.AddressSize = QSPI_ADDRESS_24_BITS;
+ s_command.Address = (sector * SPIF_SECTOR_SIZE);
+ s_command.AlternateByteMode = QSPI_ALTERNATE_BYTES_NONE;
+ s_command.DataMode = QSPI_DATA_NONE;
+ s_command.DummyCycles = 0;
+ s_command.DdrMode = QSPI_DDR_MODE_DISABLE;
+ s_command.DdrHoldHalfCycle = QSPI_DDR_HHC_ANALOG_DELAY;
+ s_command.SIOOMode = QSPI_SIOO_INST_EVERY_CMD;
+
+ if (spif_write_enable() != 0)
+ return -1;
+
+ if (HAL_QSPI_Command(&hqspi, &s_command, HAL_QSPI_TIMEOUT_DEFAULT_VALUE) != HAL_OK)
+ return -1;
+
+ if (spif_auto_polling_mem_ready(SPIF_SECTOR_ERASE_TIMEOUT) != 0)
+ return -1;
+}
+
+int spif_erase_chip(void) {
+ QSPI_CommandTypeDef s_command;
+
+ /* Initialize the erase command */
+ s_command.InstructionMode = QSPI_INSTRUCTION_1_LINE;
+ s_command.Instruction = BULK_ERASE_CMD;
+ s_command.AddressMode = QSPI_ADDRESS_NONE;
+ s_command.AlternateByteMode = QSPI_ALTERNATE_BYTES_NONE;
+ s_command.DataMode = QSPI_DATA_NONE;
+ s_command.DummyCycles = 0;
+ s_command.DdrMode = QSPI_DDR_MODE_DISABLE;
+ s_command.DdrHoldHalfCycle = QSPI_DDR_HHC_ANALOG_DELAY;
+ s_command.SIOOMode = QSPI_SIOO_INST_EVERY_CMD;
+
+ if (spif_write_enable() != 0)
+ return -1;
+
+ if (HAL_QSPI_Command(&hqspi, &s_command, HAL_QSPI_TIMEOUT_DEFAULT_VALUE) != HAL_OK)
+ return -1;
+
+ if (spif_auto_polling_mem_ready(SPIF_BULK_ERASE_TIMEOUT) != 0)
+ return -1;
+}
+
+uint8_t spif_get_status(void) {
+ QSPI_CommandTypeDef s_command;
+ uint8_t reg;
+
+ /* Initialize the read flag status register command */
+ s_command.InstructionMode = QSPI_INSTRUCTION_1_LINE;
+ s_command.Instruction = READ_FLAG_STATUS_REG_CMD;
+ s_command.AddressMode = QSPI_ADDRESS_NONE;
+ s_command.AlternateByteMode = QSPI_ALTERNATE_BYTES_NONE;
+ s_command.DataMode = QSPI_DATA_1_LINE;
+ s_command.DummyCycles = 0;
+ s_command.NbData = 1;
+ s_command.DdrMode = QSPI_DDR_MODE_DISABLE;
+ s_command.DdrHoldHalfCycle = QSPI_DDR_HHC_ANALOG_DELAY;
+ s_command.SIOOMode = QSPI_SIOO_INST_EVERY_CMD;
+
+ if (HAL_QSPI_Command(&hqspi, &s_command, HAL_QSPI_TIMEOUT_DEFAULT_VALUE) != HAL_OK)
+ return -1;
+
+ if (HAL_QSPI_Receive(&hqspi, ®, HAL_QSPI_TIMEOUT_DEFAULT_VALUE) != HAL_OK)
+ return -1;
+
+ if (reg & (SPIF_FSR_PRERR | SPIF_FSR_VPPERR | SPIF_FSR_PGERR | SPIF_FSR_ERERR))
+ return SPIF_ERROR;
+ else if (reg & (SPIF_FSR_PGSUS | SPIF_FSR_ERSUS))
+ return SPIF_SUSPENDED;
+ else if (reg & SPIF_FSR_READY)
+ return SPIF_READY;
+ else
+ return SPIF_BUSY;
+}
+
+int spif_read_id(spif_id_t *id) {
+ uint8_t *rxbuf = (uint8_t *)id;
+ QSPI_CommandTypeDef s_command;
+
+ memset(id, 0, sizeof(*id));
+
+ /* Initialize the erase command */
+ s_command.InstructionMode = QSPI_INSTRUCTION_1_LINE;
+ s_command.Instruction = READ_ID_CMD;
+ s_command.AddressMode = QSPI_ADDRESS_NONE;
+ s_command.AlternateByteMode = QSPI_ALTERNATE_BYTES_NONE;
+ s_command.DataMode = QSPI_DATA_1_LINE;
+ s_command.DummyCycles = 0;
+ s_command.NbData = 20;
+ s_command.DdrMode = QSPI_DDR_MODE_DISABLE;
+ s_command.DdrHoldHalfCycle = QSPI_DDR_HHC_ANALOG_DELAY;
+ s_command.SIOOMode = QSPI_SIOO_INST_EVERY_CMD;
+
+ if (HAL_QSPI_Command(&hqspi, &s_command, HAL_QSPI_TIMEOUT_DEFAULT_VALUE) != HAL_OK)
+ return -1;
+
+ if (HAL_QSPI_Receive(&hqspi, rxbuf, HAL_QSPI_TIMEOUT_DEFAULT_VALUE) != HAL_OK)
+ return -1;
+
+ return 0;
+}
+
+int spif_read_jedec_id(spif_id_t *id) {
+ uint8_t *rxbuf = (uint8_t *)id;
+ QSPI_CommandTypeDef s_command;
+
+ memset(id, 0, sizeof(*id));
+
+ /* Initialize the erase command */
+ s_command.InstructionMode = QSPI_INSTRUCTION_1_LINE;
+ s_command.Instruction = READ_ID_CMD2;
+ s_command.AddressMode = QSPI_ADDRESS_NONE;
+ s_command.AlternateByteMode = QSPI_ALTERNATE_BYTES_NONE;
+ s_command.DataMode = QSPI_DATA_1_LINE;
+ s_command.DummyCycles = 0;
+ s_command.NbData = 3;
+ s_command.DdrMode = QSPI_DDR_MODE_DISABLE;
+ s_command.DdrHoldHalfCycle = QSPI_DDR_HHC_ANALOG_DELAY;
+ s_command.SIOOMode = QSPI_SIOO_INST_EVERY_CMD;
+
+ if (HAL_QSPI_Command(&hqspi, &s_command, HAL_QSPI_TIMEOUT_DEFAULT_VALUE) != HAL_OK)
+ return -1;
+
+ if (HAL_QSPI_Receive(&hqspi, rxbuf, HAL_QSPI_TIMEOUT_DEFAULT_VALUE) != HAL_OK)
+ return -1;
+
+ return 0;
+}
+
+// spiffs abstraction layer
+static spiffs_config spiffs_cfg;
+spiffs spiffs_fs;
+SemaphoreHandle_t spiffs_lock;
+static uint8_t fs_work_buf[256 * 2];
+static uint8_t fs_fds[32 * 4];
+static uint8_t fs_cache_buf[(256 + 32) * 4];
+
+static int32_t _spiffs_erase(uint32_t addr, uint32_t len) {
+ uint32_t i = 0;
+ uint32_t erase_count = (len + 4096 - 1) / 4096;
+ int res = 0;
+ for (i = 0; i < erase_count; i++) {
+ res += spif_erase_block(addr + i * 4096);
+ }
+ return 0;
+}
+
+static int32_t _spiffs_read(uint32_t addr, uint32_t size, uint8_t *dst) {
+ return spif_read(addr, size, dst);
+}
+
+static int32_t _spiffs_write(uint32_t addr, uint32_t size, uint8_t *dst) {
+ return spif_write(addr, size, dst);
+}
+
+void spiffs_init(void) {
+ spiffs_lock = xSemaphoreCreateMutex();
+ spiffs_cfg.hal_erase_f = _spiffs_erase;
+ spiffs_cfg.hal_read_f = _spiffs_read;
+ spiffs_cfg.hal_write_f = _spiffs_write;
+ int res = SPIFFS_mount(&spiffs_fs, &spiffs_cfg, fs_work_buf, fs_fds,
+ sizeof(fs_fds), fs_cache_buf, sizeof(fs_cache_buf), NULL);
+ if ((res != SPIFFS_OK) && (SPIFFS_errno(&spiffs_fs) == SPIFFS_ERR_NOT_A_FS)) {
+ syslog_printf("Formatting SPIFFS...");
+ if (SPIFFS_format(&spiffs_fs) != SPIFFS_OK) {
+ syslog_printf("SPIFFS format failed: %d\n", SPIFFS_errno(&spiffs_fs));
+ }
+ res = SPIFFS_mount(&spiffs_fs, &spiffs_cfg, fs_work_buf, fs_fds,
+ sizeof(fs_fds), fs_cache_buf, sizeof(fs_cache_buf), NULL);
+ }
+ if (res != SPIFFS_OK) {
+ syslog_printf("SPIFFS mount failed: %d\n", SPIFFS_errno(&spiffs_fs));
+ }
+ else {
+ syslog_printf("SPIFFS mounted\n");
+ }
+}
diff --git a/fw/User/spiflash.h b/fw/User/spiflash.h
new file mode 100644
index 0000000..81c799e
--- /dev/null
+++ b/fw/User/spiflash.h
@@ -0,0 +1,75 @@
+//
+// Grimoire
+// Copyright 2025 Wenting Zhang
+//
+// 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.
+//
+#pragma once
+
+#define SPIF_FLASH_SIZE 0x400000 // 4MB
+#define SPIF_SECTOR_SIZE 0x10000 // 64KB
+#define SPIF_SUBSECTOR_SIZE 0x1000 // 4KB
+#define SPIF_PAGE_SIZE 0x100 // 256B
+
+#define SPIF_DUMMY_CYCLES_READ 0
+#define SPIF_DUMMY_CYCLES_READ_QUAD 6
+
+#define SPIF_BULK_ERASE_TIMEOUT 25000
+#define SPIF_SECTOR_ERASE_TIMEOUT 3000
+#define SPIF_SUBSECTOR_ERASE_TIMEOUT 800
+
+// Registers
+#define SPIF_SR_WIP ((uint8_t)0x01)
+#define SPIF_SR_WREN ((uint8_t)0x02)
+
+#define SPIF_FSR_PRERR ((uint8_t)0x02) /*!< Protection error */
+#define SPIF_FSR_PGSUS ((uint8_t)0x04) /*!< Program operation suspended */
+#define SPIF_FSR_VPPERR ((uint8_t)0x08) /*!< Invalid voltage during program or erase */
+#define SPIF_FSR_PGERR ((uint8_t)0x10) /*!< Program error */
+#define SPIF_FSR_ERERR ((uint8_t)0x20) /*!< Erase error */
+#define SPIF_FSR_ERSUS ((uint8_t)0x40) /*!< Erase operation suspended */
+#define SPIF_FSR_READY ((uint8_t)0x80) /*!< Ready or command in progress */
+
+typedef struct {
+ uint8_t manufacturer;
+ uint8_t type;
+ uint8_t capacity;
+ uint8_t id_len;
+ uint32_t uid[4];
+} spif_id_t;
+
+typedef enum {
+ SPIF_READY,
+ SPIF_BUSY,
+ SPIF_SUSPENDED,
+ SPIF_ERROR
+} spif_status_t;
+
+extern spiffs spiffs_fs;
+
+int spif_init(void);
+int spif_read(uint32_t addr, uint32_t size, uint8_t *dat);
+int spif_write(uint32_t addr, uint32_t size, uint8_t *dat);
+int spif_erase_block(uint32_t block);
+int spif_erase_sector(uint32_t sector);
+int spif_erase_chip(void);
+spif_status_t spif_get_status(void);
+int spif_read_id(spif_id_t *id);
+int spif_read_jedec_id(spif_id_t *id);
+void spiffs_init(void);
diff --git a/fw/User/syslog.c b/fw/User/syslog.c
new file mode 100644
index 0000000..c16e5d1
--- /dev/null
+++ b/fw/User/syslog.c
@@ -0,0 +1,199 @@
+//
+// Grimoire
+// Copyright 2025 Wenting Zhang
+//
+// Original copyright information:
+// Copyright (c) 2022 - Analog Devices Inc. All Rights Reserved.
+//
+// This file is licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License. You may
+// obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations
+// under the License.
+//
+#include "platform.h"
+#include "syslog.h"
+
+// The maximum number of entries in the syslog FIFO
+#define SYSLOG_MAX_LINES (100)
+// The maximum line length of a syslog entry
+#define SYSLOG_LINE_MAX (128)
+// The function used to allocate memory for the syslog buffer.
+#define SYSLOG_MALLOC(x) pvPortMalloc(x)
+// The function used to free memory.
+#define SYSLOG_FREE(x) vPortFree(x)
+// The name of the syslog instance.
+#define SYSLOG_NAME "Console Log"
+
+#define SYSLOG_CRITICAL_ENTRY(x) xSemaphoreTake(x, portMAX_DELAY);
+#define SYSLOG_CRITICAL_EXIT(x) xSemaphoreGive(x)
+
+/* TODO: abstract out mutex create/destroy/type */
+
+typedef struct {
+ SemaphoreHandle_t lock;
+ char *name;
+ uint32_t head_idx;
+ uint32_t tail_idx;
+ uint32_t seq;
+ int32_t log_dropped;
+ uint64_t *ts_data;
+ char *log_data;
+} syslog_context_t;
+
+syslog_context_t consoleLog = {
+ .name = SYSLOG_NAME
+};
+
+void syslog_init(void) {
+ syslog_context_t *log = &consoleLog;
+
+ log->lock = xSemaphoreCreateMutex();
+ log->head_idx = 0;
+ log->tail_idx = 0;
+ log->log_dropped = 0;
+ log->seq = 0;
+ log->log_data = SYSLOG_MALLOC(SYSLOG_MAX_LINES * SYSLOG_LINE_MAX);
+ log->ts_data = SYSLOG_MALLOC(SYSLOG_MAX_LINES * sizeof(*(log->ts_data)));
+}
+
+void syslog_print(char *msg)
+{
+ syslog_context_t *log = &consoleLog;
+ char *start, *end;
+
+ SYSLOG_CRITICAL_ENTRY(log->lock);
+
+ log->head_idx++;
+ if (log->head_idx == SYSLOG_MAX_LINES) {
+ log->head_idx = 0;
+ }
+
+ if (log->head_idx == log->tail_idx) {
+ log->tail_idx++;
+ if (log->tail_idx == SYSLOG_MAX_LINES) {
+ log->tail_idx = 0;
+ }
+ log->log_dropped++;
+ }
+
+ start = &log->log_data[log->head_idx * SYSLOG_LINE_MAX];
+ end = start + SYSLOG_LINE_MAX - 1;
+ strncpy(start, msg, SYSLOG_LINE_MAX); *end = 0;
+ log->ts_data[log->head_idx] = xTaskGetTickCount() / portTICK_PERIOD_MS;
+
+ log->seq++;
+
+// char *rdptr = msg;
+// while (*rdptr) {
+// usbapp_term_out(*rdptr++);
+// }
+// usbapp_term_out('\n');
+// usbapp_term_out('\r');
+
+ SYSLOG_CRITICAL_EXIT(log->lock);
+}
+
+void syslog_printf(char *fmt, ...)
+{
+ char line[SYSLOG_LINE_MAX];
+ va_list args;
+
+ va_start(args, fmt);
+ vsnprintf(line, SYSLOG_LINE_MAX, fmt, args);
+ va_end(args);
+
+ syslog_print(line);
+}
+
+void syslog_vprintf(char *fmt, va_list args)
+{
+ char line[SYSLOG_LINE_MAX];
+ vsnprintf(line, SYSLOG_LINE_MAX, fmt, args);
+ syslog_print(line);
+}
+
+void syslog_dump(unsigned max)
+{
+ syslog_context_t *log = &consoleLog;
+ uint64_t ts;
+ char *start;
+ char *end;
+ char *line;
+ unsigned count = 0;
+
+ line = SYSLOG_MALLOC(SYSLOG_LINE_MAX);
+ SYSLOG_CRITICAL_ENTRY(log->lock);
+ while ((log->tail_idx != log->head_idx) && (count < max)) {
+ log->tail_idx++;
+ if (log->tail_idx == SYSLOG_MAX_LINES) {
+ log->tail_idx = 0;
+ }
+ ts = log->ts_data[log->tail_idx];
+ start = &log->log_data[log->tail_idx * SYSLOG_LINE_MAX];
+ strncpy(line, start, SYSLOG_LINE_MAX);
+ SYSLOG_CRITICAL_EXIT(log->lock);
+ end = line + strlen(line) - 1;
+ while (isspace((int)(*end))) {
+ *end = 0;
+ end--;
+ }
+ uint64_t ts_sec, ts_ms;
+ ts_sec = ts / 1000;
+ ts_ms = ts - ts_sec * 1000;
+ printf("[%6lu.%03lu] ", (unsigned long)ts_sec,
+ (unsigned long)ts_ms);
+ puts(line);
+ count++;
+ SYSLOG_CRITICAL_ENTRY(log->lock);
+ }
+ SYSLOG_CRITICAL_EXIT(log->lock);
+ SYSLOG_FREE(line);
+}
+
+char *syslog_next(char *ts, size_t tsMax, char *line, size_t lineMax)
+{
+ syslog_context_t *log = &consoleLog;
+ char *logLine;
+ uint64_t u64ts;
+ char *end;
+
+ SYSLOG_CRITICAL_ENTRY(log->lock);
+ if (log->tail_idx != log->head_idx) {
+ log->tail_idx++;
+ if (log->tail_idx == SYSLOG_MAX_LINES) {
+ log->tail_idx = 0;
+ }
+ logLine = &log->log_data[log->tail_idx * SYSLOG_LINE_MAX];
+ strncpy(line, logLine, lineMax); line[lineMax-1] = '\0';
+ u64ts = log->ts_data[log->tail_idx];
+ } else {
+ line = NULL; ts = NULL;
+ }
+ SYSLOG_CRITICAL_EXIT(log->lock);
+
+ if (line) {
+ end = line + strlen(line) - 1;
+ while (isspace((int)(*end))) {
+ *end = 0;
+ end--;
+ }
+ }
+
+ if (ts) {
+ uint64_t ts_sec, ts_ms;
+ ts_sec = u64ts / 1000;
+ ts_ms = u64ts - ts_sec * 1000;
+ snprintf(ts, tsMax, "[%6lu.%03lu] ", (unsigned long)ts_sec,
+ (unsigned long)ts_ms);
+ ts[tsMax-1] = '\0';
+ }
+
+ return(line);
+}
diff --git a/fw/User/syslog.h b/fw/User/syslog.h
new file mode 100644
index 0000000..92dc11a
--- /dev/null
+++ b/fw/User/syslog.h
@@ -0,0 +1,111 @@
+//
+// Grimoire
+// Copyright 2025 Wenting Zhang
+//
+// Original copyright information:
+// Copyright (c) 2022 - Analog Devices Inc. All Rights Reserved.
+//
+// This file is licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License. You may
+// obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations
+// under the License.
+//
+/*!
+ * @brief Simple system logger
+ *
+ * This logger supports FreeRTOS and bare-metal projects.
+ *
+ * @file syslog.h
+ * @version 1.0.1
+ * @copyright 2023 Analog Devices, Inc. All rights reserved.
+ *
+*/
+#include
+
+#ifndef SYSLOG_H_
+#define SYSLOG_H_
+
+/*!****************************************************************
+ * @brief System log init
+ *
+ * This function initializes the system logger.
+ *
+ * This function can be called before or after the FreeRTOS is
+ * started. The logger will allocate the log buffer using
+ * the function defined by SYSLOG_MALLOC
+ *
+ ******************************************************************/
+void syslog_init(void);
+
+/*!****************************************************************
+ * @brief System log print
+ *
+ * This function prints a fixed string to the system log. Strings
+ * which do not fit within the log line length will be truncated.
+ *
+ * This function is thread safe.
+ *
+ * @param [in] msg Null-terminated string to save in the log
+ *
+ ******************************************************************/
+void syslog_print(char *msg);
+
+/*!****************************************************************
+ * @brief System log printf
+ *
+ * This function prints a variable argument string to the system
+ * log. Strings which do not fit within the log line length
+ * will be truncated.
+ *
+ * This function is thread safe.
+ *
+ * @param [in] fmt Null-terminated format string
+ * @param [in] ... Remaining arguments
+ *
+ ******************************************************************/
+void syslog_printf(char *fmt, ...);
+
+/*!****************************************************************
+ * @brief System log vprintf
+ *
+ * This function prints a variable argument list to the system
+ * log. Strings which do not fit within the log line length
+ * will be truncated.
+ *
+ * This function is thread safe.
+ *
+ * @param [in] fmt Null-terminated format string
+ * @param [in] args Variable argument list
+ *
+ ******************************************************************/
+void syslog_vprintf(char *fmt, va_list args);
+
+/*!****************************************************************
+ * @brief System log next line
+ *
+ * This function returns the next line in the system log or NULL
+ * if the log is empty.
+ *
+ * This function is thread safe.
+ *
+ ******************************************************************/
+char *syslog_next(char *ts, size_t tsMax, char *line, size_t lineMax);
+
+/*!****************************************************************
+ * @brief System log dump
+ *
+ * This function dumps the contents of the system log to stdout.
+ *
+ * This function is thread safe.
+ *
+ ******************************************************************/
+void syslog_dump(unsigned max);
+
+#endif
diff --git a/fw/User/tinyusb b/fw/User/tinyusb
new file mode 160000
index 0000000..bfe0817
--- /dev/null
+++ b/fw/User/tinyusb
@@ -0,0 +1 @@
+Subproject commit bfe08176e516fede93dcd0bb3d43b4044fea25e4
diff --git a/fw/User/tusb_config.h b/fw/User/tusb_config.h
new file mode 100644
index 0000000..e04105d
--- /dev/null
+++ b/fw/User/tusb_config.h
@@ -0,0 +1,115 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2019 Ha Thach (tinyusb.org)
+ *
+ * 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.
+ *
+ */
+
+ #ifndef _TUSB_CONFIG_H_
+ #define _TUSB_CONFIG_H_
+
+ #ifdef __cplusplus
+ extern "C" {
+ #endif
+
+ //--------------------------------------------------------------------+
+ // Board Specific Configuration
+ //--------------------------------------------------------------------+
+
+ // RHPort number used for device can be defined by board.mk, default to port 0
+ #ifndef BOARD_TUD_RHPORT
+ #define BOARD_TUD_RHPORT 0
+ #endif
+
+ // RHPort max operational speed can defined by board.mk
+ #ifndef BOARD_TUD_MAX_SPEED
+ #define BOARD_TUD_MAX_SPEED OPT_MODE_DEFAULT_SPEED
+ #endif
+
+ //--------------------------------------------------------------------
+ // COMMON CONFIGURATION
+ //--------------------------------------------------------------------
+
+ // defined by board.mk
+ #define CFG_TUSB_MCU OPT_MCU_STM32H7
+ #ifndef CFG_TUSB_MCU
+ #error CFG_TUSB_MCU must be defined
+ #endif
+
+ #ifndef CFG_TUSB_OS
+ #define CFG_TUSB_OS OPT_OS_FREERTOS
+ #endif
+
+ #ifndef CFG_TUSB_DEBUG
+ #define CFG_TUSB_DEBUG 0
+ #endif
+
+ // Enable Device stack
+ #define CFG_TUD_ENABLED 1
+
+ // Default is max speed that hardware controller could support with on-chip PHY
+ #define CFG_TUD_MAX_SPEED BOARD_TUD_MAX_SPEED
+
+ /* USB DMA on some MCUs can only access a specific SRAM region with restriction on alignment.
+ * Tinyusb use follows macros to declare transferring memory so that they can be put
+ * into those specific section.
+ * e.g
+ * - CFG_TUSB_MEM SECTION : __attribute__ (( section(".usb_ram") ))
+ * - CFG_TUSB_MEM_ALIGN : __attribute__ ((aligned(4)))
+ */
+ #ifndef CFG_TUSB_MEM_SECTION
+ #define CFG_TUSB_MEM_SECTION
+ #endif
+
+ #ifndef CFG_TUSB_MEM_ALIGN
+ #define CFG_TUSB_MEM_ALIGN __attribute__ ((aligned(4)))
+ #endif
+
+ //--------------------------------------------------------------------
+ // DEVICE CONFIGURATION
+ //--------------------------------------------------------------------
+
+ #ifndef CFG_TUD_ENDPOINT0_SIZE
+ #define CFG_TUD_ENDPOINT0_SIZE 64
+ #endif
+
+ //------------- CLASS -------------//
+ #define CFG_TUD_CDC 1
+ #define CFG_TUD_MSC 0
+ #define CFG_TUD_HID 1
+ #define CFG_TUD_MIDI 0
+ #define CFG_TUD_VENDOR 0
+
+ // CDC FIFO size of TX and RX
+ #define CFG_TUD_CDC_RX_BUFSIZE (TUD_OPT_HIGH_SPEED ? 512 : 64)
+ #define CFG_TUD_CDC_TX_BUFSIZE (TUD_OPT_HIGH_SPEED ? 512 : 64)
+
+ // CDC Endpoint transfer buffer size, more is faster
+ #define CFG_TUD_CDC_EP_BUFSIZE (TUD_OPT_HIGH_SPEED ? 512 : 64)
+
+ // HID buffer size Should be sufficient to hold ID (if any) + Data
+ #define CFG_TUD_HID_EP_BUFSIZE 16
+
+ #ifdef __cplusplus
+ }
+ #endif
+
+ #endif /* _TUSB_CONFIG_H_ */
diff --git a/fw/User/ui.c b/fw/User/ui.c
new file mode 100644
index 0000000..3facabc
--- /dev/null
+++ b/fw/User/ui.c
@@ -0,0 +1,103 @@
+//
+// Grimoire
+// Copyright 2025 Wenting Zhang
+//
+// 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.
+//
+#include "platform.h"
+#include "board.h"
+#include "app.h"
+#include "ui.h"
+
+static QueueHandle_t btn_queue;
+
+typedef enum {
+ BTN1_SHORT_PRESSED,
+ BTN1_LONG_PRESSED,
+ BTN2_SHORT_PRESSED,
+ BTN2_LONG_PRESSED
+} btn_event_t;
+
+static int mode = 1;
+
+const update_mode_t modes[] = {
+ UM_FAST_MONO_NO_DITHER,
+ UM_FAST_MONO_BAYER,
+ UM_FAST_MONO_BLUE_NOISE,
+ UM_FAST_GREY,
+ UM_AUTO_LUT_NO_DITHER,
+ UM_AUTO_LUT_ERROR_DIFFUSION,
+};
+
+static int mode_max = sizeof(modes) / sizeof(modes[0]);
+
+void ui_init(void) {
+ btn_queue = xQueueCreate(8, sizeof(btn_event_t));
+}
+
+portTASK_FUNCTION(ui_task, pvParameters) {
+ while (1) {
+ // Key press logic
+ btn_event_t btn_event;
+ BaseType_t result = xQueueReceive(btn_queue, &btn_event, portMAX_DELAY);
+ if (result != pdTRUE)
+ continue;
+ if (btn_event == BTN1_SHORT_PRESSED) {
+ // First key short press
+ mode--;
+ if (mode < 0) mode = mode_max - 1;
+ caster_setmode(0, 0, config.hact, config.vact, modes[mode]);
+ }
+ else if (btn_event == BTN2_SHORT_PRESSED) {
+ mode++;
+ if (mode >= mode_max) mode = 0;
+ caster_setmode(0, 0, config.hact, config.vact, modes[mode]);
+ }
+ else if ((btn_event == BTN1_LONG_PRESSED) || (btn_event == BTN2_LONG_PRESSED)) {
+ // First key long press
+ // Clear screen
+ caster_redraw(0,0,2400,1800);
+ }
+ }
+}
+
+portTASK_FUNCTION(key_scan_task, pvParameters) {
+ while (1) {
+ uint32_t scan = button_scan();
+ btn_event_t event;
+ // No wait, if the ui task doesn't take it, the key press is lost
+ if ((scan & BTN_MASK) == BTN_SHORT_PRESSED) {
+ event = BTN1_SHORT_PRESSED;
+ xQueueSend(btn_queue, &event, 0);
+ }
+ else if ((scan & BTN_MASK) == BTN_LONG_PRESSED) {
+ event = BTN1_LONG_PRESSED;
+ xQueueSend(btn_queue, &event, 0);
+ }
+ if (((scan >> BTN_SHIFT) & BTN_MASK) == BTN_SHORT_PRESSED) {
+ event = BTN2_SHORT_PRESSED;
+ xQueueSend(btn_queue, &event, 0);
+ }
+ else if (((scan >> BTN_SHIFT) & BTN_MASK) == BTN_LONG_PRESSED) {
+ event = BTN2_LONG_PRESSED;
+ xQueueSend(btn_queue, &event, 0);
+ }
+ vTaskDelay(pdMS_TO_TICKS(10));
+ }
+}
diff --git a/fw/utils.c b/fw/User/ui.h
similarity index 75%
rename from fw/utils.c
rename to fw/User/ui.h
index ad0a740..4771ee4 100644
--- a/fw/utils.c
+++ b/fw/User/ui.h
@@ -1,5 +1,6 @@
//
-// Copyright 2022 Wenting Zhang
+// Grimoire
+// Copyright 2025 Wenting Zhang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -19,22 +20,8 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
-#include
-#include
-#include
-#include
-#include "utils.h"
+#pragma once
-void fatal(const char *msg, ...) {
- va_list params;
-
- va_start(params, msg);
-
- printf("[FATAL] ");
- vprintf(msg, params);
- printf("\n");
-
- va_end(params);
-
- while(1);
-}
\ No newline at end of file
+void ui_init(void);
+portTASK_FUNCTION(ui_task, pvParameters);
+portTASK_FUNCTION(key_scan_task, pvParameters);
diff --git a/fw/User/usb_descriptors.c b/fw/User/usb_descriptors.c
new file mode 100644
index 0000000..c021257
--- /dev/null
+++ b/fw/User/usb_descriptors.c
@@ -0,0 +1,191 @@
+/*
+* The MIT License (MIT)
+*
+* Copyright (c) 2019 Ha Thach (tinyusb.org)
+*
+* 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.
+*
+*/
+
+#include "tusb.h"
+#include "platform.h"
+#include "board.h"
+
+#define USB_VID 0x0483
+#define USB_PID 0x5750 // Composite HID CDC
+#define USB_BCD 0x0200
+
+//--------------------------------------------------------------------+
+// Device Descriptors
+//--------------------------------------------------------------------+
+tusb_desc_device_t const desc_device =
+{
+ .bLength = sizeof(tusb_desc_device_t),
+ .bDescriptorType = TUSB_DESC_DEVICE,
+ .bcdUSB = USB_BCD,
+
+ // Use Interface Association Descriptor (IAD) for CDC
+ // As required by USB Specs IAD's subclass must be common class (2) and protocol must be IAD (1)
+ .bDeviceClass = 0x00,
+ .bDeviceSubClass = 0x00,
+ .bDeviceProtocol = 0x00,
+ .bMaxPacketSize0 = CFG_TUD_ENDPOINT0_SIZE,
+
+ .idVendor = USB_VID,
+ .idProduct = USB_PID,
+ .bcdDevice = 0x0100,
+
+ .iManufacturer = 0x01,
+ .iProduct = 0x02,
+ .iSerialNumber = 0x03,
+
+ .bNumConfigurations = 0x01
+};
+
+// Invoked when received GET DEVICE DESCRIPTOR
+// Application return pointer to descriptor
+uint8_t const * tud_descriptor_device_cb(void)
+{
+ return (uint8_t const *) &desc_device;
+}
+
+//--------------------------------------------------------------------+
+// HID Report Descriptor
+//--------------------------------------------------------------------+
+
+uint8_t const desc_hid_report[] =
+{
+ TUD_HID_REPORT_DESC_GENERIC_INOUT(CFG_TUD_HID_EP_BUFSIZE)
+};
+
+// Invoked when received GET HID REPORT DESCRIPTOR
+// Application return pointer to descriptor
+// Descriptor contents must exist long enough for transfer to complete
+uint8_t const * tud_hid_descriptor_report_cb(uint8_t itf)
+{
+ (void) itf;
+ return desc_hid_report;
+}
+
+//--------------------------------------------------------------------+
+// Configuration Descriptor
+//--------------------------------------------------------------------+
+enum
+{
+ ITF_NUM_HID = 0,
+ ITF_NUM_CDC,
+ ITF_NUM_CDC_DATA,
+ ITF_NUM_TOTAL
+};
+
+#define CONFIG_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_HID_INOUT_DESC_LEN + TUD_CDC_DESC_LEN)
+
+#define EPNUM_HID 0x01
+#define EPNUM_CDC_NOTIF 0x83
+#define EPNUM_CDC_OUT 0x02
+#define EPNUM_CDC_IN 0x82
+
+uint8_t const desc_fs_configuration[] =
+{
+ // Config number, interface count, string index, total length, attribute, power in mA
+ TUD_CONFIG_DESCRIPTOR(1, ITF_NUM_TOTAL, 0, CONFIG_TOTAL_LEN, 0x00, 100),
+
+ // Interface number, string index, protocol, report descriptor len, EP Out & In address, size & polling interval
+ TUD_HID_INOUT_DESCRIPTOR(ITF_NUM_HID, 4, HID_ITF_PROTOCOL_NONE, sizeof(desc_hid_report), EPNUM_HID, 0x80 | EPNUM_HID, CFG_TUD_HID_EP_BUFSIZE, 10),
+
+ // Interface number, string index, EP notification address and size, EP data address (out, in) and size.
+ TUD_CDC_DESCRIPTOR(ITF_NUM_CDC, 5, EPNUM_CDC_NOTIF, 8, EPNUM_CDC_OUT, EPNUM_CDC_IN, 64),
+};
+
+// Invoked when received GET CONFIGURATION DESCRIPTOR
+// Application return pointer to descriptor
+// Descriptor contents must exist long enough for transfer to complete
+uint8_t const * tud_descriptor_configuration_cb(uint8_t index)
+{
+ (void) index; // for multiple configurations
+
+ return desc_fs_configuration;
+}
+
+//--------------------------------------------------------------------+
+// String Descriptors
+//--------------------------------------------------------------------+
+
+// String Descriptor Index
+enum {
+ STRID_LANGID = 0,
+ STRID_MANUFACTURER,
+ STRID_PRODUCT,
+ STRID_SERIAL,
+};
+
+// array of pointer to string descriptors
+char const *string_desc_arr[] =
+{
+ (const char[]) { 0x09, 0x04 }, // 0: is supported language is English (0x0409)
+ "Modos", // 1: Manufacturer
+ "Glider", // 2: Product
+ NULL, // 3: Serials will use unique ID if possible
+ "Control", // 4: HID Interface
+ "Debug", // 5: CDC Interface
+};
+
+static uint16_t _desc_str[32 + 1];
+
+// Invoked when received GET STRING DESCRIPTOR request
+// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete
+uint16_t const *tud_descriptor_string_cb(uint8_t index, uint16_t langid) {
+ (void) langid;
+ size_t chr_count;
+
+ switch ( index ) {
+ case STRID_LANGID:
+ memcpy(&_desc_str[1], string_desc_arr[0], 2);
+ chr_count = 1;
+ break;
+
+ case STRID_SERIAL:
+ chr_count = board_usb_get_serial(_desc_str + 1, 32);
+ break;
+
+ default:
+ // Note: the 0xEE index string is a Microsoft OS 1.0 Descriptors.
+ // https://docs.microsoft.com/en-us/windows-hardware/drivers/usbcon/microsoft-defined-usb-descriptors
+
+ if ( !(index < sizeof(string_desc_arr) / sizeof(string_desc_arr[0])) ) return NULL;
+
+ const char *str = string_desc_arr[index];
+
+ // Cap at max char
+ chr_count = strlen(str);
+ size_t const max_count = sizeof(_desc_str) / sizeof(_desc_str[0]) - 1; // -1 for string type
+ if ( chr_count > max_count ) chr_count = max_count;
+
+ // Convert ASCII string into UTF-16
+ for ( size_t i = 0; i < chr_count; i++ ) {
+ _desc_str[1 + i] = str[i];
+ }
+ break;
+ }
+
+ // first byte is length (including header), second byte is string type
+ _desc_str[0] = (uint16_t) ((TUSB_DESC_STRING << 8) | (2 * chr_count + 2));
+
+ return _desc_str;
+}
diff --git a/fw/usbapp.c b/fw/User/usbapp.c
similarity index 68%
rename from fw/usbapp.c
rename to fw/User/usbapp.c
index ad45042..5e1cdac 100644
--- a/fw/usbapp.c
+++ b/fw/User/usbapp.c
@@ -1,5 +1,6 @@
//
-// Copyright 2024 Wenting Zhang
+// Grimoire
+// Copyright 2025 Wenting Zhang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -19,35 +20,39 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
-#include
-#include "pico/stdlib.h"
-#include "fpga.h"
-#include "caster.h"
+#include "platform.h"
+#include "app.h"
#include "tusb.h"
-#include "usb_descriptors.h"
-#include "usbapp.h"
-#include "crc16.h"
-#include "iap.h"
-void usbapp_init(void) {
- tusb_init();
+void usbapp_term_out(char data, void *usr) {
+ tud_cdc_write_char(data);
+ tud_cdc_write_flush();
}
-// Device callbacks
-void tud_mount_cb(void) {
+QueueHandle_t rxqueue;
+// TODO: Implement proper RTOS wakeup instead of this wait 10ms thing
+void tud_cdc_rx_cb(uint8_t itf) {
+ // There is a risk where the queue is full, not all bytes would be moved
+ // to the RTOS queue. The remaining bytes won't be moved until there is new
+ // stuff coming in from the CDC.
+ while ((uxQueueSpacesAvailable(rxqueue) > 0) && (tud_cdc_available())) {
+ uint8_t c = tud_cdc_read_char();
+ xQueueSend(rxqueue, &c, 0);
+ }
}
-void tud_umount_cb(void) {
+int usbapp_term_in(int mode, void *usr) {
+ uint8_t c;
-}
-
-void tud_suspend_cb(bool remote_wakeup_en) {
- // TODO: Force Suspend
-}
-
-void tud_resume_cb(void) {
-
+ int timeout = 0;
+ if (mode != TERM_INPUT_DONT_WAIT)
+ timeout = pdMS_TO_TICKS(mode + 1);
+ BaseType_t result = xQueueReceive(rxqueue, &c, timeout);
+ if (result == pdTRUE)
+ return c;
+ else
+ return -1;
}
// Invoked when received GET_REPORT control request
@@ -107,10 +112,10 @@ void tud_hid_set_report_cb(uint8_t instance, uint8_t report_id, hid_report_type_
// TODO
break;
case USBCMD_REDRAW:
- retval = caster_redraw(x0, y0, x1, y1);
+ //retval = caster_redraw(x0, y0, x1, y1);
break;
case USBCMD_SETMODE:
- retval = caster_setmode(x0, y0, x1, y1, (UPDATE_MODE)param);
+ //retval = caster_setmode(x0, y0, x1, y1, (UPDATE_MODE)param);
break;
case USBCMD_USBBOOT:
//iap_usbboot();
@@ -135,6 +140,21 @@ returnval:
tud_hid_report(0, txbuf, 16);
}
-void usbapp_task(void) {
- tud_task();
+portTASK_FUNCTION(usb_device_task, pvParameters) {
+ tusb_rhport_init_t dev_init = {
+ .role = TUSB_ROLE_DEVICE,
+ .speed = TUSB_SPEED_AUTO
+ };
+
+ rxqueue = xQueueCreate(1024, sizeof(char));
+ tusb_init(BOARD_TUD_RHPORT, &dev_init);
+
+ // RTOS forever loop
+ while (1) {
+ // put this thread to waiting state until there is new events
+ tud_task();
+
+ // following code only run if tud_task() process at least 1 event
+ }
}
+
diff --git a/fw/usbapp.h b/fw/User/usbapp.h
similarity index 89%
rename from fw/usbapp.h
rename to fw/User/usbapp.h
index 929b081..2b1b1e7 100644
--- a/fw/usbapp.h
+++ b/fw/User/usbapp.h
@@ -1,5 +1,6 @@
//
-// Copyright 2024 Wenting Zhang
+// Grimoire
+// Copyright 2025 Wenting Zhang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -34,5 +35,6 @@
#define USBRET_CHKSUMFAIL 0x01
#define USBRET_SUCCESS 0x55
-void usbapp_init(void);
-void usbapp_task(void);
+void usbapp_term_out(char data, void *usr);
+int usbapp_term_in(int mode, void *usr);
+portTASK_FUNCTION(usb_device_task, pvParameters);
diff --git a/fw/User/usbpd.c b/fw/User/usbpd.c
new file mode 100644
index 0000000..a6e4081
--- /dev/null
+++ b/fw/User/usbpd.c
@@ -0,0 +1,72 @@
+//
+// Grimoire
+// Copyright 2025 Wenting Zhang
+//
+// 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.
+//
+#include "platform.h"
+#include "board.h"
+#include "app.h"
+
+static SemaphoreHandle_t isr_sem = NULL;
+
+void usbpd_isr(void) {
+ BaseType_t context_switch = pdFALSE;
+
+ if (isr_sem) {
+ xSemaphoreGiveFromISR(isr_sem, &context_switch);
+ portYIELD_FROM_ISR(context_switch);
+ }
+}
+
+portTASK_FUNCTION(usb_pd_task, pvParameters) {
+ isr_sem = xSemaphoreCreateCounting(1, 0);
+ extern int dp_enabled;
+ static bool hpd_sent = false;
+
+ int result = tcpm_init(0);
+ if (result)
+ syslog_printf("Failed to initialize TCPC\n");
+
+ int cc1, cc2;
+ tcpc_config[0].drv->get_cc(0, &cc1, &cc2);
+ syslog_printf("CC status %d %d\n", cc1, cc2);
+ pd_init(0);
+ sleep_ms(50);
+ while (1) {
+ BaseType_t rtos_result = xSemaphoreTake(isr_sem, pdMS_TO_TICKS(50));
+// if (rtos_result) {
+// syslog_printf("FUSB302 interrupt");
+// //fusb302_tcpc_alert(0);
+// }
+ fusb302_tcpc_alert(0);
+ pd_run_state_machine(0);
+ if (dp_enabled && !hpd_sent && !pd_is_vdm_busy(0)) {
+ syslog_printf("DP enabled\n");
+ pd_send_hpd(0, hpd_high);
+ hpd_sent = true;
+ }
+ }
+
+ while (1) {
+ sleep_ms(100);
+ }
+
+ vSemaphoreDelete(isr_sem);
+}
diff --git a/fw/bitstream.h b/fw/User/usbpd.h
similarity index 89%
rename from fw/bitstream.h
rename to fw/User/usbpd.h
index cbff8af..d827e55 100644
--- a/fw/bitstream.h
+++ b/fw/User/usbpd.h
@@ -1,5 +1,6 @@
//
-// Copyright 2022 Wenting Zhang
+// Grimoire
+// Copyright 2025 Wenting Zhang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -21,5 +22,5 @@
//
#pragma once
-extern const char fpga_bitstream[];
-extern const int fpga_bitstream_length;
\ No newline at end of file
+void usbpd_isr(void);
+portTASK_FUNCTION(usb_pd_task, pvParameters);
diff --git a/fw/fusb302.c b/fw/User/usbpd/fusb302.c
similarity index 99%
rename from fw/fusb302.c
rename to fw/User/usbpd/fusb302.c
index d10aee0..86d2fc8 100644
--- a/fw/fusb302.c
+++ b/fw/User/usbpd/fusb302.c
@@ -6,8 +6,8 @@
Released under an MIT license. See LICENSE file.
*/
-#include
-#include "pico/stdlib.h"
+#include "platform.h"
+#include "board.h"
#include "fusb302.h"
#include "usb_pd_tcpm.h"
#include "tcpm.h"
@@ -799,7 +799,7 @@ static int fusb302_tcpm_transmit(int port, enum tcpm_transmit_type type,
fusb302_send_message(port, header, data, buf, buf_pos);
// wait for the GoodCRC to come back before we let the rest
// of the code do stuff like change polarity and miss it
- sleep_us(1200);
+ sleep_ms(2);
return 0;
case TCPC_TX_HARD_RESET:
/* Simply hit the SEND_HARD_RESET bit */
diff --git a/fw/fusb302.h b/fw/User/usbpd/fusb302.h
similarity index 100%
rename from fw/fusb302.h
rename to fw/User/usbpd/fusb302.h
diff --git a/fw/tcpm.h b/fw/User/usbpd/tcpm.h
similarity index 100%
rename from fw/tcpm.h
rename to fw/User/usbpd/tcpm.h
diff --git a/fw/User/usbpd/tcpm_driver.c b/fw/User/usbpd/tcpm_driver.c
new file mode 100644
index 0000000..c741013
--- /dev/null
+++ b/fw/User/usbpd/tcpm_driver.c
@@ -0,0 +1,158 @@
+//
+// Copyright 2022 Wenting Zhang
+// Copyright 2017 Jason Cerundolo
+//
+// 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.
+//
+#include "platform.h"
+#include "board.h"
+#include "app.h"
+#include "fusb302.h"
+
+const struct tcpc_config_t tcpc_config[CONFIG_USB_PD_PORT_COUNT] = {
+ {0, FUSB302_I2C_SLAVE_ADDR, &fusb302_tcpm_drv},
+};
+
+void tcpc_i2c_init(void) {
+ // Should be initialized at board level init to avoid dependencies between
+ // drivers that need I2C
+}
+
+/* I2C wrapper functions - get I2C port / slave addr from config struct. */
+int tcpc_write(int port, int reg, int val) {
+ int result = pal_i2c_write_reg(FUSB302_I2C, FUSB302_I2C_SLAVE_ADDR, reg, val);
+ if (result != 0) {
+ syslog_print("Failed writing 8b reg to TCPC");
+ while (1) {
+ sleep_ms(500);
+ }
+ }
+ return 0;
+}
+
+int tcpc_write16(int port, int reg, int val) {
+ uint8_t buf[2];
+ int result;
+ buf[0] = (uint8_t)(val & 0xff);
+ buf[1] = (uint8_t)((val >> 8) & 0xff);
+ result = pal_i2c_write_longreg(FUSB302_I2C, FUSB302_I2C_SLAVE_ADDR, reg, buf, 2);
+ if (result != 0) {
+ syslog_print("Failed writing 16b reg to TCPC");
+ while (1) {
+ sleep_ms(500);
+ }
+ }
+ return 0;
+}
+
+int tcpc_read(int port, int reg, int *val) {
+ uint8_t rd;
+ int result = pal_i2c_read_reg(FUSB302_I2C, FUSB302_I2C_SLAVE_ADDR, reg, &rd);
+ *val = rd;
+ if (result != 0) {
+ syslog_print("Failed reading register from TCPC");
+ while (1) {
+ sleep_ms(500);
+ }
+ }
+ return 0;
+}
+
+int tcpc_read16(int port, int reg, int *val) {
+ uint8_t buf[2];
+ int result;
+
+ uint8_t wr = reg;
+ result = pal_i2c_read_payload(FUSB302_I2C, FUSB302_I2C_SLAVE_ADDR, &wr, 1, buf, 2);
+ if (result != 0) {
+ syslog_print("Failed writing data to TCPC");
+ while (1) {
+ sleep_ms(500);
+ }
+ }
+ *val = (int)buf[1] << 8 | buf[0];
+
+ return 0;
+}
+
+int tcpc_xfer(int port,
+ const uint8_t *out, int out_size,
+ uint8_t *in, int in_size,
+ int flags) {
+ static bool xfer_in_progress = false;
+
+ if (!xfer_in_progress) {
+ // Start from idle
+ pal_i2c_ll_lock(FUSB302_I2C);
+ }
+
+ // Write
+ // Write mode:
+ // if start requested: use REQ_WRITE
+ // otherwise: use REQ_NONE
+ // Read
+ // Read mode:
+ // if start requested: if already in transaction, issue repeated start, otherwise issue start
+ // otherwise: use REQ_NONE
+
+ if (out_size != 0) {
+ uint32_t request = (flags & I2C_XFER_START) ? REQ_WRITE : REQ_NONE;
+ xfer_in_progress = true;
+ if (!pal_i2c_ll_start(FUSB302_I2C, request, FUSB302_I2C_SLAVE_ADDR << 1, out_size))
+ goto fail;
+ for (int i = 0; i < out_size; i++) {
+ if (!pal_i2c_ll_send(FUSB302_I2C, out[i])) {
+ //0x0046syslog_printf("Byte %d", i);
+ goto fail;
+ }
+ }
+ }
+
+ if (in_size != 0) {
+ uint32_t request = (flags & I2C_XFER_START) ?
+ (xfer_in_progress ? REQ_RESTART_READ : REQ_READ) : REQ_NONE;
+ if (!(flags & I2C_XFER_STOP)) {
+ // Would followed by another read
+ request |= REQ_RELOAD;
+ }
+ xfer_in_progress = true;
+ if (!pal_i2c_ll_start(FUSB302_I2C, request, FUSB302_I2C_SLAVE_ADDR << 1, in_size))
+ goto fail;
+ for (int i = 0; i < in_size; i++) {
+ if (!pal_i2c_ll_recv(FUSB302_I2C, &in[i]))
+ goto fail;
+ }
+ }
+
+ if (flags & I2C_XFER_STOP) {
+ goto done;
+ }
+
+ return 0;
+
+fail:
+ syslog_print("Failed transfer data from/ to TCPC");
+ syslog_printf("OUT %d IN %d FLAGS %s%s", out_size, in_size, flags & I2C_XFER_START ? "START " : " ", flags & I2C_XFER_STOP ? "STOP" : "");
+done:
+ xfer_in_progress = false;
+ pal_i2c_ll_stop(FUSB302_I2C);
+ pal_i2c_ll_unlock(FUSB302_I2C);
+ return 0;
+}
+
diff --git a/fw/tcpm_driver.h b/fw/User/usbpd/tcpm_driver.h
similarity index 100%
rename from fw/tcpm_driver.h
rename to fw/User/usbpd/tcpm_driver.h
diff --git a/fw/usb_mux.c b/fw/User/usbpd/usb_mux.c
similarity index 76%
rename from fw/usb_mux.c
rename to fw/User/usbpd/usb_mux.c
index 264b5a5..8d79a9c 100644
--- a/fw/usb_mux.c
+++ b/fw/User/usbpd/usb_mux.c
@@ -19,43 +19,35 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
-#include
-#include
-#include "pico/stdlib.h"
-#include "hardware/i2c.h"
-#include "config.h"
-#include "ptn3460.h"
-#include "utils.h"
+#include "platform.h"
+#include "board.h"
+#include "app.h"
#include "usb_mux.h"
-#ifdef HAS_TYPEC
-
-#define USBC_ORI_PIN 10
-
void usb_mux_init(int port) {
- gpio_init(USBC_ORI_PIN);
- gpio_set_dir(USBC_ORI_PIN, GPIO_OUT);
- gpio_put(USBC_ORI_PIN, 0);
+ //
}
void usb_mux_set(int port, enum typec_mux mux_mode,
enum usb_switch usb_config, int polarity) {
- printf("USB MUX set %s, %d\n",
+ syslog_printf("USB MUX set %s, %s, %d",
+ (mux_mode == TYPEC_MUX_NONE) ? "NONE" :
+ (mux_mode == TYPEC_MUX_USB) ? "USB" :
+ (mux_mode == TYPEC_MUX_DP) ? "DP" : "DOCK",
(usb_config == USB_SWITCH_CONNECT) ? "CONNECT" :
(usb_config == USB_SWITCH_DISCONNECT) ? "DISCONNECT" : "RESTORE",
polarity);
+
if (usb_config == USB_SWITCH_CONNECT) {
if (polarity == 0) {
// Not flipped
- printf("Setting orientation to not flipped\n");
+ syslog_printf("Setting orientation to not flipped");
}
else {
// Flipped
- printf("Setting orientation to flipped\n");
+ syslog_printf("Setting orientation to flipped");
}
- gpio_put(USBC_ORI_PIN, polarity ^ TYPEC_MB_ORI_INV);
+ gpio_put(TYPEC_ORI, polarity ^ TYPEC_MB_ORI_INV);
ptn3460_set_aux_polarity(polarity ^ TYPEC_AUX_ORI_INV);
}
}
-
-#endif
diff --git a/fw/usb_mux.h b/fw/User/usbpd/usb_mux.h
similarity index 100%
rename from fw/usb_mux.h
rename to fw/User/usbpd/usb_mux.h
diff --git a/fw/usb_pd.h b/fw/User/usbpd/usb_pd.h
similarity index 100%
rename from fw/usb_pd.h
rename to fw/User/usbpd/usb_pd.h
diff --git a/fw/usb_pd_driver.c b/fw/User/usbpd/usb_pd_driver.c
similarity index 94%
rename from fw/usb_pd_driver.c
rename to fw/User/usbpd/usb_pd_driver.c
index c9ed657..a1f9a10 100644
--- a/fw/usb_pd_driver.c
+++ b/fw/User/usbpd/usb_pd_driver.c
@@ -20,8 +20,8 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
-#include "pico/stdlib.h"
-#include
+#include "platform.h"
+#include "app.h"
#include "usb_pd_driver.h"
#include "usb_pd.h"
@@ -57,12 +57,12 @@ const int pd_snk_pdo_cnt = ARRAY_SIZE(pd_snk_pdo);
void pd_set_input_current_limit(int port, uint32_t max_ma,
uint32_t supply_voltage)
{
- printf("Setting input current limit to %d V %d mA\n", supply_voltage, max_ma);
+ syslog_printf("Setting input current limit to %d V %d mA", supply_voltage, max_ma);
}
int pd_is_valid_input_voltage(int mv)
{
- printf("Checking valid input voltage %d mV\n", mv);
+ syslog_printf("Checking valid input voltage %d mV", mv);
return (mv < 5500);
}
@@ -73,16 +73,14 @@ int pd_snk_is_vbus_provided(int port)
timestamp_t get_time(void)
{
- absolute_time_t t = get_absolute_time();
-#ifdef NDEBUG
- return (timestamp_t)t;
-#else
- return (timestamp_t)t._private_us_since_boot;
-#endif
+ timestamp_t result;
+ result.val = (uint64_t)xTaskGetTickCount() * 1000 / portTICK_PERIOD_MS;
+ return result;
}
void pd_power_supply_reset(int port)
{
+ syslog_printf("PD power supply reset");
return;
}
diff --git a/fw/usb_pd_driver.h b/fw/User/usbpd/usb_pd_driver.h
similarity index 96%
rename from fw/usb_pd_driver.h
rename to fw/User/usbpd/usb_pd_driver.h
index 656df03..fc451b1 100644
--- a/fw/usb_pd_driver.h
+++ b/fw/User/usbpd/usb_pd_driver.h
@@ -57,7 +57,7 @@ extern "C" {
/* Don't automatically change roles */
#undef CONFIG_USB_PD_INITIAL_DRP_STATE
-#define CONFIG_USB_PD_INITIAL_DRP_STATE PD_DRP_FREEZE
+#define CONFIG_USB_PD_INITIAL_DRP_STATE PD_DRP_FORCE_SINK
/* Board has mux */
#define CONFIG_USBC_SS_MUX
@@ -72,8 +72,8 @@ extern "C" {
/* Define typical operating power and max power */
#define PD_OPERATING_POWER_MW (2250ull)
-#define PD_MAX_POWER_MW (15000ull)
-#define PD_MAX_CURRENT_MA (3000ull)
+#define PD_MAX_POWER_MW (7500ull)
+#define PD_MAX_CURRENT_MA (1500ull)
#define PD_MAX_VOLTAGE_MV (5000ull)
#define PDO_FIXED_FLAGS (PDO_FIXED_COMM_CAP)
diff --git a/fw/usb_pd_policy.c b/fw/User/usbpd/usb_pd_policy.c
similarity index 96%
rename from fw/usb_pd_policy.c
rename to fw/User/usbpd/usb_pd_policy.c
index ee3f848..103cf9c 100644
--- a/fw/usb_pd_policy.c
+++ b/fw/User/usbpd/usb_pd_policy.c
@@ -3,6 +3,8 @@
* found in the LICENSE file.
*/
+#include "platform.h"
+#include "app.h"
#include
#include
#include
@@ -15,8 +17,8 @@
#define CPRINTS(format, args...) cprints(CC_USBPD, format, ## args)
#define CPRINTF(format, args...) cprintf(CC_USBPD, format, ## args)
#else
-#define CPRINTS(format, args...) printf(format, ## args)
-#define CPRINTF(format, args...) printf(format, ## args)
+#define CPRINTS(format, args...) syslog_printf(format, ## args)
+#define CPRINTF(format, args...) syslog_printf(format, ## args)
#endif
static int rw_flash_changed = 1;
@@ -49,7 +51,7 @@ int pd_check_requested_voltage(uint32_t rdo, const int port)
if (max_ma > pdo_ma && !(rdo & RDO_CAP_MISMATCH))
return EC_ERROR_INVAL; /* too much max current */
- CPRINTF("Requested %d V %d mA (for %d/%d mA)\n",
+ CPRINTF("Requested %d V %d mA (for %d/%d mA)",
((pdo >> 10) & 0x3ff) * 50, (pdo & 0x3ff) * 10,
op_ma * 10, max_ma * 10);
@@ -144,7 +146,7 @@ void pd_extract_pdo_power(uint32_t pdo, uint32_t *ma, uint32_t *mv)
*mv = ((pdo >> 10) & 0x3FF) * 50;
if (*mv == 0) {
- CPRINTF("ERR:PDO mv=0\n");
+ CPRINTF("ERR:PDO mv=0");
*ma = 0;
return;
}
@@ -315,7 +317,7 @@ static void dfp_consume_svids(int port, uint32_t *payload)
for (i = pe[port].svid_cnt; i < pe[port].svid_cnt + 12; i += 2) {
if (i == SVID_DISCOVERY_MAX) {
- CPRINTF("ERR:SVIDCNT\n");
+ CPRINTF("ERR:SVIDCNT");
break;
}
@@ -334,7 +336,7 @@ static void dfp_consume_svids(int port, uint32_t *payload)
}
/* TODO(tbroch) need to re-issue discover svids if > 12 */
if (i && ((i % 12) == 0))
- CPRINTF("ERR:SVID+12\n");
+ CPRINTF("ERR:SVID+12");
}
static int dfp_discover_modes(int port, uint32_t *payload)
@@ -351,7 +353,7 @@ static void dfp_consume_modes(int port, int cnt, uint32_t *payload)
int idx = pe[port].svid_idx;
pe[port].svids[idx].mode_cnt = cnt - 1;
if (pe[port].svids[idx].mode_cnt < 0) {
- CPRINTF("ERR:NOMODE\n");
+ CPRINTF("ERR:NOMODE");
} else {
memcpy(pe[port].svids[pe[port].svid_idx].mode_vdo, &payload[1],
sizeof(uint32_t) * pe[port].svids[idx].mode_cnt);
@@ -396,7 +398,7 @@ int allocate_mode(int port, uint16_t svid)
/* There's no space to enter another mode */
if (pe[port].amode_idx == PD_AMODE_COUNT) {
- CPRINTF("ERR:NO AMODE SPACE\n");
+ CPRINTF("ERR:NO AMODE SPACE");
return -1;
}
@@ -441,7 +443,7 @@ uint32_t pd_dfp_enter_mode(int port, uint16_t svid, int opos)
} else if (opos <= modep->data->mode_cnt) {
modep->opos = opos;
} else {
- CPRINTF("opos error\n");
+ CPRINTF("opos error");
return 0;
}
@@ -460,13 +462,13 @@ static int validate_mode_request(struct svdm_amode_data *modep,
return 0;
if (svid != modep->fx->svid) {
- CPRINTF("ERR:svid r:0x%04x != c:0x%04x\n",
+ CPRINTF("ERR:svid r:0x%04x != c:0x%04x",
svid, modep->fx->svid);
return 0;
}
if (opos != modep->opos) {
- CPRINTF("ERR:opos r:%d != c:%d\n",
+ CPRINTF("ERR:opos r:%d != c:%d",
opos, modep->opos);
return 0;
}
@@ -595,23 +597,23 @@ static void dump_pe(int port)
uint32_t mode_caps;
if (pe[port].identity[0] == 0) {
- ccprintf("No identity discovered yet.\n");
+ ccprintf("No identity discovered yet.");
return;
}
idh_ptype = PD_IDH_PTYPE(pe[port].identity[0]);
- ccprintf("IDENT:\n");
- ccprintf("\t[ID Header] %08x :: %s, VID:%04x\n", pe[port].identity[0],
+ ccprintf("IDENT:");
+ ccprintf("\t[ID Header] %08x :: %s, VID:%04x", pe[port].identity[0],
idh_ptype_names[idh_ptype], pd_get_identity_vid(port));
- ccprintf("\t[Cert Stat] %08x\n", pe[port].identity[1]);
+ ccprintf("\t[Cert Stat] %08x", pe[port].identity[1]);
for (i = 2; i < ARRAY_SIZE(pe[port].identity); i++) {
ccprintf("\t");
if (pe[port].identity[i])
ccprintf("[%d] %08x ", i, pe[port].identity[i]);
}
- ccprintf("\n");
+ ccprintf("");
if (pe[port].svid_cnt < 1) {
- ccprintf("No SVIDS discovered yet.\n");
+ ccprintf("No SVIDS discovered yet.");
return;
}
@@ -620,11 +622,11 @@ static void dump_pe(int port)
for (j = 0; j < pe[port].svids[j].mode_cnt; j++)
ccprintf(" [%d] %08x", j + 1,
pe[port].svids[i].mode_vdo[j]);
- ccprintf("\n");
+ ccprintf("");
modep = get_modep(port, pe[port].svids[i].svid);
if (modep) {
mode_caps = modep->data->mode_vdo[modep->opos - 1];
- ccprintf("MODE[%d]: svid:%04x caps:%08x\n", modep->opos,
+ ccprintf("MODE[%d]: svid:%04x caps:%08x", modep->opos,
modep->fx->svid, mode_caps);
}
}
@@ -697,7 +699,7 @@ int pd_svdm(int port, int cnt, uint32_t *payload, uint32_t **rpayload)
return 0;
#endif
default:
- CPRINTF("ERR:CMD:%d\n", cmd);
+ CPRINTF("ERR:CMD:%d", cmd);
rsize = 0;
}
if (func)
@@ -785,7 +787,7 @@ int pd_svdm(int port, int cnt, uint32_t *payload, uint32_t **rpayload)
rsize = 0;
break;
default:
- CPRINTF("ERR:CMD:%d\n", cmd);
+ CPRINTF("ERR:CMD:%d", cmd);
rsize = 0;
}
@@ -802,7 +804,7 @@ int pd_svdm(int port, int cnt, uint32_t *payload, uint32_t **rpayload)
break;
case CMD_ENTER_MODE:
/* Error */
- CPRINTF("ERR:ENTBUSY\n");
+ CPRINTF("ERR:ENTBUSY");
rsize = 0;
break;
case CMD_EXIT_MODE:
@@ -816,7 +818,7 @@ int pd_svdm(int port, int cnt, uint32_t *payload, uint32_t **rpayload)
rsize = 0;
#endif /* CONFIG_USB_PD_ALT_MODE_DFP */
} else {
- CPRINTF("ERR:CMDT:%d\n", cmd);
+ CPRINTF("ERR:CMDT:%d", cmd);
/* do not answer */
rsize = 0;
}
@@ -1076,7 +1078,7 @@ static int svdm_response_svids(int port, uint32_t *payload)
static int dp_status(int port, uint32_t *payload)
{
- CPRINTF("DP status %08x\n", payload[0]);
+ CPRINTF("DP status %08x", payload[0]);
int opos = PD_VDO_OPOS(payload[0]);
int hpd = dp_enabled; //?
if (opos != OPOS)
@@ -1096,7 +1098,7 @@ static int dp_status(int port, uint32_t *payload)
static int dp_config(int port, uint32_t *payload)
{
- CPRINTF("DP config %08x\n", payload[1]);
+ CPRINTF("DP config %08x", payload[1]);
if (PD_DP_CFG_DPON(payload[1])) {
dp_enabled = 1;
}
@@ -1126,7 +1128,7 @@ static int svdm_response_modes(int port, uint32_t *payload)
int svdm_enter_mode(int port, uint32_t *payload)
{
- CPRINTF("SVDM enter mode\n");
+ CPRINTF("SVDM enter mode: VID %08x, OPOS %01x\n", PD_VDO_VID(payload[0]), PD_VDO_OPOS(payload[0]));
/* SID & mode request is valid */
if ((PD_VDO_VID(payload[0]) != USB_SID_DISPLAYPORT) ||
(PD_VDO_OPOS(payload[0]) != OPOS))
@@ -1143,7 +1145,7 @@ int pd_alt_mode(int port, uint16_t svid)
static int svdm_exit_mode(int port, uint32_t *payload)
{
- CPRINTF("SVDM exit mode\n");
+ CPRINTF("SVDM exit mode");
alt_mode = 0;
dp_enabled = 0;
return 1; /* Must return ACK */
@@ -1161,4 +1163,4 @@ const struct svdm_response svdm_rsp = {
.enter_mode = &svdm_enter_mode,
.amode = &dp_fx,
.exit_mode = &svdm_exit_mode,
-};
\ No newline at end of file
+};
diff --git a/fw/usb_pd_protocol.c b/fw/User/usbpd/usb_pd_protocol.c
similarity index 95%
rename from fw/usb_pd_protocol.c
rename to fw/User/usbpd/usb_pd_protocol.c
index 7a3eec3..f3e4a9d 100644
--- a/fw/usb_pd_protocol.c
+++ b/fw/User/usbpd/usb_pd_protocol.c
@@ -7,10 +7,8 @@
* found in the LICENSE file.
*/
-#include
-#include
-#include
-#include "pico/stdlib.h"
+#include "platform.h"
+#include "app.h"
#include "usb_pd.h"
#include "usb_pd_tcpm.h"
#include "usb_mux.h"
@@ -48,8 +46,8 @@ static int debug_level;
*/
static uint8_t pd_comm_enabled[CONFIG_USB_PD_PORT_COUNT];
#else /* CONFIG_COMMON_RUNTIME */
-#define CPRINTF(format, args...) printf(format, ## args)
-#define CPRINTS(format, args...) printf(format, ## args)
+#define CPRINTF(format, args...) syslog_printf(format, ## args)
+#define CPRINTS(format, args...) syslog_printf(format, ## args)
static const int debug_level = 1;
#endif
@@ -424,7 +422,60 @@ static inline void set_state(int port, enum pd_states next_state)
disable_sleep(SLEEP_MASK_USB_PD);
#endif
- CPRINTF("C%d st%d\n", port, next_state);
+ const char *state_name;
+ switch (next_state) {
+ case PD_STATE_DISABLED: state_name = "PD_STATE_DISABLED"; break;
+ case PD_STATE_SUSPENDED: state_name = "PD_STATE_SUSPENDED"; break;
+ #ifdef CONFIG_USB_PD_DUAL_ROLE
+ case PD_STATE_SNK_DISCONNECTED: state_name = "PD_STATE_SNK_DISCONNECTED"; break;
+ case PD_STATE_SNK_DISCONNECTED_DEBOUNCE: state_name = "PD_STATE_SNK_DISCONNECTED_DEBOUNCE"; break;
+ case PD_STATE_SNK_HARD_RESET_RECOVER: state_name = "PD_STATE_SNK_HARD_RESET_RECOVER"; break;
+ case PD_STATE_SNK_DISCOVERY: state_name = "PD_STATE_SNK_DISCOVERY"; break;
+ case PD_STATE_SNK_REQUESTED: state_name = "PD_STATE_SNK_REQUESTED"; break;
+ case PD_STATE_SNK_TRANSITION: state_name = "PD_STATE_SNK_TRANSITION"; break;
+ case PD_STATE_SNK_READY: state_name = "PD_STATE_SNK_READY"; break;
+ case PD_STATE_SNK_SWAP_INIT: state_name = "PD_STATE_SNK_SWAP_INIT"; break;
+ case PD_STATE_SNK_SWAP_SNK_DISABLE: state_name = "PD_STATE_SNK_SWAP_SNK_DISABLE"; break;
+ case PD_STATE_SNK_SWAP_SRC_DISABLE: state_name = "PD_STATE_SNK_SWAP_SRC_DISABLE"; break;
+ case PD_STATE_SNK_SWAP_STANDBY: state_name = "PD_STATE_SNK_SWAP_STANDBY"; break;
+ case PD_STATE_SNK_SWAP_COMPLETE: state_name = "PD_STATE_SNK_SWAP_COMPLETE"; break;
+ #endif
+ case PD_STATE_SRC_DISCONNECTED: state_name = "PD_STATE_SRC_DISCONNECTED"; break;
+ case PD_STATE_SRC_DISCONNECTED_DEBOUNCE: state_name = "PD_STATE_SRC_DISCONNECTED_DEBOUNCE"; break;
+ case PD_STATE_SRC_HARD_RESET_RECOVER: state_name = "PD_STATE_SRC_HARD_RESET_RECOVER"; break;
+ case PD_STATE_SRC_STARTUP: state_name = "PD_STATE_SRC_STARTUP"; break;
+ case PD_STATE_SRC_DISCOVERY: state_name = "PD_STATE_SRC_DISCOVERY"; break;
+ case PD_STATE_SRC_NEGOCIATE: state_name = "PD_STATE_SRC_NEGOCIATE"; break;
+ case PD_STATE_SRC_ACCEPTED: state_name = "PD_STATE_SRC_ACCEPTED"; break;
+ case PD_STATE_SRC_POWERED: state_name = "PD_STATE_SRC_POWERED"; break;
+ case PD_STATE_SRC_TRANSITION: state_name = "PD_STATE_SRC_TRANSITION"; break;
+ case PD_STATE_SRC_READY: state_name = "PD_STATE_SRC_READY"; break;
+ case PD_STATE_SRC_GET_SINK_CAP: state_name = "PD_STATE_SRC_GET_SINK_CAP"; break;
+ case PD_STATE_DR_SWAP: state_name = "PD_STATE_DR_SWAP"; break;
+ #ifdef CONFIG_USB_PD_DUAL_ROLE
+ case PD_STATE_SRC_SWAP_INIT: state_name = "PD_STATE_SRC_SWAP_INIT"; break;
+ case PD_STATE_SRC_SWAP_SNK_DISABLE: state_name = "PD_STATE_SRC_SWAP_SNK_DISABLE"; break;
+ case PD_STATE_SRC_SWAP_SRC_DISABLE: state_name = "PD_STATE_SRC_SWAP_SRC_DISABLE"; break;
+ case PD_STATE_SRC_SWAP_STANDBY: state_name = "PD_STATE_SRC_SWAP_STANDBY"; break;
+ #ifdef CONFIG_USBC_VCONN_SWAP
+ case PD_STATE_VCONN_SWAP_SEND: state_name = "PD_STATE_VCONN_SWAP_SEND"; break;
+ case PD_STATE_VCONN_SWAP_INIT: state_name = "PD_STATE_VCONN_SWAP_INIT"; break;
+ case PD_STATE_VCONN_SWAP_READY: state_name = "PD_STATE_VCONN_SWAP_READY"; break;
+ #endif
+ #endif
+ case PD_STATE_SOFT_RESET: state_name = "PD_STATE_SOFT_RESET"; break;
+ case PD_STATE_HARD_RESET_SEND: state_name = "PD_STATE_HARD_RESET_SEND"; break;
+ case PD_STATE_HARD_RESET_EXECUTE: state_name = "PD_STATE_HARD_RESET_EXECUTE"; break;
+ #ifdef CONFIG_COMMON_RUNTIME
+ case PD_STATE_BIST_RX: state_name = "PD_STATE_BIST_RX"; break;
+ case PD_STATE_BIST_TX: state_name = "PD_STATE_BIST_TX"; break;
+ #endif
+ #ifdef CONFIG_USB_PD_DUAL_ROLE_AUTO_TOGGLE
+ case PD_STATE_DRP_AUTO_TOGGLE: state_name = "PD_STATE_DRP_AUTO_TOGGLE"; break;
+ #endif
+ default: state_name = "Unknown"; break;
+ }
+ CPRINTF("C%d entering state %s", port, state_name);
}
/* increment message ID counter */
@@ -581,7 +632,7 @@ static int send_control(int port, int type)
bit_len = pd_transmit(port, TCPC_TX_SOP, header, NULL);
if (debug_level >= 2)
- CPRINTF("CTRL[%d]>%d\n", type, bit_len);
+ CPRINTF("CTRL[%d]>%d", type, bit_len);
return bit_len;
}
@@ -611,7 +662,7 @@ static int send_source_cap(int port)
bit_len = pd_transmit(port, TCPC_TX_SOP, header, src_pdo);
if (debug_level >= 2)
- CPRINTF("srcCAP>%d\n", bit_len);
+ CPRINTF("srcCAP>%d", bit_len);
return bit_len;
}
@@ -698,7 +749,7 @@ static int send_battery_cap(int port, uint32_t *payload)
bit_len = pd_transmit(port, TCPC_TX_SOP, header, (uint32_t *)msg);
if (debug_level >= 2)
- CPRINTF("batCap>%d\n", bit_len);
+ CPRINTF("batCap>%d", bit_len);
return bit_len;
}
@@ -765,7 +816,7 @@ static int send_battery_status(int port, uint32_t *payload)
bit_len = pd_transmit(port, TCPC_TX_SOP, header, &msg);
if (debug_level >= 2)
- CPRINTF("batStat>%d\n", bit_len);
+ CPRINTF("batStat>%d", bit_len);
return bit_len;
}
@@ -781,7 +832,7 @@ static void send_sink_cap(int port)
bit_len = pd_transmit(port, TCPC_TX_SOP, header, pd_snk_pdo);
if (debug_level >= 2)
- CPRINTF("snkCAP>%d\n", bit_len);
+ CPRINTF("snkCAP>%d", bit_len);
}
static int send_request(int port, uint32_t rdo)
@@ -793,7 +844,7 @@ static int send_request(int port, uint32_t rdo)
bit_len = pd_transmit(port, TCPC_TX_SOP, header, &rdo);
if (debug_level >= 2)
- CPRINTF("REQ%d>\n", bit_len);
+ CPRINTF("REQ%d>", bit_len);
return bit_len;
}
@@ -830,7 +881,7 @@ static int send_bist_cmd(int port)
pd_get_rev(port), 0);
bit_len = pd_transmit(port, TCPC_TX_SOP, header, &bdo);
- CPRINTF("BIST>%d\n", bit_len);
+ CPRINTF("BIST>%d", bit_len);
return bit_len;
}
@@ -851,7 +902,7 @@ static void handle_vdm_request(int port, int cnt, uint32_t *payload)
int rlen = 0;
uint32_t *rdata;
- CPRINTF("VDM request\n");
+ CPRINTF("VDM request");
if (pd[port].vdm_state == VDM_STATE_BUSY) {
/* If UFP responded busy retry after timeout */
if (PD_VDO_CMDT(payload[0]) == CMDT_RSP_BUSY) {
@@ -876,16 +927,16 @@ static void handle_vdm_request(int port, int cnt, uint32_t *payload)
return;
}
if (debug_level >= 2)
- CPRINTF("Unhandled VDM VID %04x CMD %04x\n",
+ CPRINTF("Unhandled VDM VID %04x CMD %04x",
PD_VDO_VID(payload[0]), payload[0] & 0xFFFF);
}
void pd_execute_hard_reset(int port)
{
if (pd[port].last_state == PD_STATE_HARD_RESET_SEND)
- CPRINTF("C%d HARD RST TX\n", port);
+ CPRINTF("C%d HARD RST TX", port);
else
- CPRINTF("C%d HARD RST RX\n", port);
+ CPRINTF("C%d HARD RST RX", port);
pd[port].msg_id = 0;
#ifdef CONFIG_USB_PD_ALT_MODE_DFP
@@ -938,7 +989,7 @@ static void execute_soft_reset(int port)
pd[port].msg_id = 0;
set_state(port, DUAL_ROLE_IF_ELSE(port, PD_STATE_SNK_DISCOVERY,
PD_STATE_SRC_DISCOVERY));
- CPRINTF("C%d Soft Rst\n", port);
+ CPRINTF("C%d Soft Rst", port);
}
void pd_soft_reset(void)
@@ -1010,7 +1061,7 @@ static int pd_send_request_msg(int port, int always_send_request)
supply_voltage, curr_limit);
if (rdo & RDO_CAP_MISMATCH)
CPRINTF(" Mismatch");
- CPRINTF("\n");
+ //CPRINTF("");
pd[port].curr_limit = curr_limit;
pd[port].supply_voltage = supply_voltage;
@@ -1197,7 +1248,7 @@ static void handle_data_request(int port, uint16_t head,
handle_vdm_request(port, cnt, payload);
break;
default:
- CPRINTF("Unhandled data message type %d\n", type);
+ CPRINTF("Unhandled data message type %d", type);
}
}
@@ -1515,7 +1566,7 @@ static void handle_ctrl_request(int port, uint16_t head,
#ifdef CONFIG_USB_PD_REV30
send_control(port, PD_CTRL_NOT_SUPPORTED);
#endif
- CPRINTF("Unhandled ctrl message type %d\n", type);
+ CPRINTF("Unhandled ctrl message type %d", type);
}
}
@@ -1551,7 +1602,6 @@ static void handle_request(int port, uint16_t head,
CPRINTF("RECV %04x/%d ", head, cnt);
for (p = 0; p < cnt; p++)
CPRINTF("[%d]%08x ", p, payload[p]);
- CPRINTF("\n");
}
/*
@@ -1578,7 +1628,7 @@ void pd_send_vdm(int port, uint32_t vid, int cmd, const uint32_t *data,
int count)
{
if (count > VDO_MAX_SIZE - 1) {
- CPRINTF("VDM over max size\n");
+ CPRINTF("VDM over max size");
return;
}
@@ -1641,7 +1691,7 @@ static void pd_vdm_send_state_machine(int port)
/*static int old_vdm_state = 0;
if (pd[port].vdm_state != old_vdm_state) {
- CPRINTF("VDM state: %d\n", pd[port].vdm_state);
+ CPRINTF("VDM state: %d", pd[port].vdm_state);
old_vdm_state = pd[port].vdm_state;
}*/
@@ -1705,7 +1755,6 @@ static inline void pd_dev_dump_info(uint16_t dev_id, uint8_t *hash)
ccprintf(" 0x%02x%02x%02x%02x", hash[j + 3], hash[j + 2],
hash[j + 1], hash[j]);
}
- ccprintf("\n");
}
#endif /* CONFIG_CMD_PD_DEV_DUMP_INFO */
@@ -2527,7 +2576,7 @@ void pd_run_state_machine(int port)
break;
} else if (debug_level >= 2 &&
snk_cap_count == PD_SNK_CAP_RETRIES+1) {
- CPRINTF("ERR SNK_CAP\n");
+ CPRINTF("ERR SNK_CAP");
}
}
@@ -3581,7 +3630,7 @@ static int remote_flashing(int argc, char **argv)
while (pd[port].vdm_state > 0)
task_wait_event(100*MSEC_US);
- ccprintf("DONE %d\n", pd[port].vdm_state);
+ ccprintf("DONE %d", pd[port].vdm_state);
return EC_SUCCESS;
}
#endif /* defined(CONFIG_CMD_PD) && defined(CONFIG_CMD_PD_FLASH) */
@@ -3670,19 +3719,19 @@ static int command_pd(int argc, char **argv)
ccprintf("dual-role toggling: ");
switch (drp_state) {
case PD_DRP_TOGGLE_ON:
- ccprintf("on\n");
+ ccprintf("on");
break;
case PD_DRP_TOGGLE_OFF:
- ccprintf("off\n");
+ ccprintf("off");
break;
case PD_DRP_FREEZE:
- ccprintf("freeze\n");
+ ccprintf("freeze");
break;
case PD_DRP_FORCE_SINK:
- ccprintf("force sink\n");
+ ccprintf("force sink");
break;
case PD_DRP_FORCE_SOURCE:
- ccprintf("force source\n");
+ ccprintf("force source");
break;
}
} else {
@@ -3713,7 +3762,7 @@ static int command_pd(int argc, char **argv)
debug_level = level;
} else
#endif
- ccprintf("dump level: %d\n", debug_level);
+ ccprintf("dump level: %d", debug_level);
return EC_SUCCESS;
}
@@ -3742,7 +3791,7 @@ static int command_pd(int argc, char **argv)
pd_try_src_enable = enable ? 1 : 0;
}
- ccprintf("Try.SRC %s\n", pd_try_src_enable ? "on" : "off");
+ ccprintf("Try.SRC %s", pd_try_src_enable ? "on" : "off");
return EC_SUCCESS;
}
#endif
@@ -3783,14 +3832,14 @@ static int command_pd(int argc, char **argv)
max_volt = pd_get_max_voltage();
pd_request_source_voltage(port, max_volt);
- ccprintf("max req: %dmV\n", max_volt);
+ ccprintf("max req: %dmV", max_volt);
} else if (!strcasecmp(argv[2], "disable")) {
pd_comm_enable(port, 0);
- ccprintf("Port C%d disable\n", port);
+ ccprintf("Port C%d disable", port);
return EC_SUCCESS;
} else if (!strcasecmp(argv[2], "enable")) {
pd_comm_enable(port, 1);
- ccprintf("Port C%d enabled\n", port);
+ ccprintf("Port C%d enabled", port);
return EC_SUCCESS;
} else if (!strncasecmp(argv[2], "hard", 4)) {
set_state(port, PD_STATE_HARD_RESET_SEND);
@@ -3801,7 +3850,7 @@ static int command_pd(int argc, char **argv)
ccprintf("Hash ");
for (i = 0; i < PD_RW_HASH_SIZE / 4; i++)
ccprintf("%08x ", pd[port].dev_rw_hash[i]);
- ccprintf("\nImage %s\n", system_image_copy_t_to_string(
+ ccprintf("Image %s", system_image_copy_t_to_string(
pd[port].current_image));
} else if (!strncasecmp(argv[2], "soft", 4)) {
set_state(port, PD_STATE_SOFT_RESET);
@@ -3831,7 +3880,7 @@ static int command_pd(int argc, char **argv)
pd_ping_enable(port, enable);
}
- ccprintf("Pings %s\n",
+ ccprintf("Pings %s",
(pd[port].flags & PD_FLAGS_PING_ENABLED) ?
"on" : "off");
} else if (!strncasecmp(argv[2], "vdm", 3)) {
@@ -3864,7 +3913,7 @@ static int command_pd(int argc, char **argv)
#endif
if (!strncasecmp(argv[2], "state", 5)) {
ccprintf("Port C%d CC%d, %s - Role: %s-%s%s "
- "State: %s, Flags: 0x%04x\n",
+ "State: %s, Flags: 0x%04x",
port, pd[port].polarity + 1,
pd_comm_is_enabled(port) ? "Ena" : "Dis",
pd[port].power_role == PD_ROLE_SOURCE ? "SRC" : "SNK",
@@ -3880,7 +3929,7 @@ static int command_pd(int argc, char **argv)
}
DECLARE_CONSOLE_COMMAND(pd, command_pd,
"dualrole|dump|rwhashtable"
- "|trysrc [0|1]\n\t "
+ "|trysrc [0|1]\t "
"[tx|bist_rx|bist_tx|charger|clock|dev|disable|enable"
"|soft|hash|hard|ping|state|swap [power|data]|"
"vdm [ping | curr | vers]]",
@@ -4184,7 +4233,7 @@ static int hc_remote_pd_set_amode(struct host_cmd_handler_args *args)
pd_send_vdm(p->port, p->svid,
CMD_EXIT_MODE | VDO_OPOS(p->opos), NULL, 0);
else {
- CPRINTF("Failed exit mode\n");
+ CPRINTF("Failed exit mode");
return EC_RES_ERROR;
}
break;
diff --git a/fw/usb_pd_tcpm.h b/fw/User/usbpd/usb_pd_tcpm.h
similarity index 100%
rename from fw/usb_pd_tcpm.h
rename to fw/User/usbpd/usb_pd_tcpm.h
diff --git a/fw/utils.h b/fw/User/version.h
similarity index 92%
rename from fw/utils.h
rename to fw/User/version.h
index 9a86f9e..e2e7098 100644
--- a/fw/utils.h
+++ b/fw/User/version.h
@@ -1,5 +1,6 @@
//
-// Copyright 2022 Wenting Zhang
+// Grimoire
+// Copyright 2025 Wenting Zhang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -21,4 +22,4 @@
//
#pragma once
-void fatal(const char *msg, ...);
+#define STR_VERSION "0.1"
diff --git a/fw/User/xmodem/xmodem.c b/fw/User/xmodem/xmodem.c
new file mode 100644
index 0000000..8bbfaa4
--- /dev/null
+++ b/fw/User/xmodem/xmodem.c
@@ -0,0 +1,349 @@
+/***********************************************************************************************************************
+ * XMODEM implementation with YMODEM support
+ ***********************************************************************************************************************
+ * Copyright 2001-2019 Georges Menie (www.menie.org)
+ * Modified by Thuffir in 2019
+ * Modified by Analog Devices in 2024
+ * All rights reserved.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * * Neither the name of the University of California, Berkeley nor the
+ * names of its contributors may be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ **********************************************************************************************************************/
+
+/*
+ * This code has been modified by Analog Devices, Inc.
+ */
+
+
+/* this code needs standard functions memcpy() and memset()
+ and input/output functions _inbyte() and _outbyte().
+
+ the prototypes of the input/output functions are:
+ int _inbyte(unsigned short timeout, void *); // timeout
+ void _outbyte(int c, void *);
+
+ */
+
+/* Needed for memcpy() and memeset() */
+#include
+#include "xmodem.h"
+
+/***********************************************************************************************************************
+ * Character constants
+ **********************************************************************************************************************/
+#define SOH 0x01
+#define STX 0x02
+#define EOT 0x04
+#define ACK 0x06
+#define NAK 0x15
+#define CAN 0x18
+#define CTRLZ 0x1A
+
+#ifdef XMODEM_1K
+/* 1024 for XModem 1k + 3 head chars + 2 crc */
+#define XBUF_SIZE (1024 + 3 + 2)
+#else
+/* 128 for XModem + 3 head chars + 2 crc */
+#define XBUF_SIZE (128 + 3 + 2)
+#endif
+
+#ifndef HAVE_CRC16
+/***********************************************************************************************************************
+ * Calculate the CCITT-CRC-16 value of a given buffer
+ **********************************************************************************************************************/
+static unsigned short crc16_ccitt(
+ /* Pointer to the byte buffer */
+ const unsigned char *buffer,
+ /* length of the byte buffer */
+ int length)
+{
+ unsigned short crc16 = 0;
+ while(length != 0) {
+ crc16 = (unsigned char)(crc16 >> 8) | (crc16 << 8);
+ crc16 ^= *buffer;
+ crc16 ^= (unsigned char)(crc16 & 0xff) >> 4;
+ crc16 ^= (crc16 << 8) << 4;
+ crc16 ^= ((crc16 & 0xff) << 4) << 1;
+ buffer++;
+ length--;
+ }
+
+ return crc16;
+}
+#endif
+
+/***********************************************************************************************************************
+ * Check block
+ **********************************************************************************************************************/
+static int check(int crc, const unsigned char *buf, int sz)
+{
+ if (crc) {
+ unsigned short crc = crc16_ccitt(buf, sz);
+ unsigned short tcrc = (buf[sz]<<8)+buf[sz+1];
+ if (crc == tcrc)
+ return 1;
+ }
+ else {
+ int i;
+ unsigned char cks = 0;
+ for (i = 0; i < sz; ++i) {
+ cks += buf[i];
+ }
+ if (cks == buf[sz])
+ return 1;
+ }
+
+ return 0;
+}
+
+/***********************************************************************************************************************
+ * Flush input
+ **********************************************************************************************************************/
+static void flushinput(XmodemInByte _inbyte, void *ctx)
+{
+ while (_inbyte(((DLY_1S)*3)>>1, ctx) >= 0)
+ ;
+}
+
+/***********************************************************************************************************************
+ * XMODEM Receive
+ **********************************************************************************************************************/
+int XmodemReceive(StoreChunkType storeChunk, void *ctx, int destsz, int crc, int mode, XmodemInByte _inbyte, XmodemOutByte _outbyte)
+{
+ unsigned char xbuff[XBUF_SIZE];
+ unsigned char *p;
+ int bufsz;
+ unsigned char trychar = (crc == 2) ? 'G' : (crc ? 'C' : NAK);
+ unsigned char packetno = mode ? 0 : 1;
+ int i, c, len = 0;
+ int retry, retrans = MAXRETRANS;
+ int sync_retry = MAXSYNCTRETRY;
+
+ for(;;) {
+ for( retry = 0; retry < sync_retry; ++retry) {
+ if (trychar) _outbyte(trychar, ctx);
+ if ((c = _inbyte((DLY_1S)<<1, ctx)) >= 0) {
+ switch (c) {
+ case SOH:
+ bufsz = 128;
+ goto start_recv;
+#ifdef XMODEM_1K
+ case STX:
+ bufsz = 1024;
+ goto start_recv;
+#endif
+ case EOT:
+ if(storeChunk) {
+ storeChunk(ctx, NULL, 0);
+ }
+ _outbyte(ACK, ctx);
+ return len; /* normal end */
+ case CAN:
+ if ((c = _inbyte(DLY_1S, ctx)) == CAN) {
+ flushinput(_inbyte, ctx);
+ _outbyte(ACK, ctx);
+ return -1; /* canceled by remote */
+ }
+ break;
+ default:
+ break;
+ }
+ }
+ }
+ if (trychar == 'G') { trychar = 'C'; crc = 1; continue; }
+ //else if (trychar == 'C') { trychar = NAK; crc = 0; sync_retry = 2; continue; }
+ flushinput(_inbyte, ctx);
+ _outbyte(CAN, ctx);
+ _outbyte(CAN, ctx);
+ _outbyte(CAN, ctx);
+ return -2; /* sync error */
+
+ start_recv:
+ trychar = 0;
+ p = xbuff;
+ *p++ = c;
+ for (i = 0; i < (bufsz+(crc?1:0)+3); ++i) {
+ if ((c = _inbyte(DLY_1S, ctx)) < 0) goto reject;
+ *p++ = c;
+ }
+
+ if (xbuff[1] == (unsigned char)(~xbuff[2]) &&
+ (xbuff[1] == packetno || xbuff[1] == (unsigned char)packetno-1) &&
+ check(crc, &xbuff[3], bufsz)) {
+ if (xbuff[1] == packetno) {
+ register int count = destsz - len;
+ if (count > bufsz) count = bufsz;
+ if (count > 0) {
+ if(storeChunk) {
+ storeChunk(ctx, &xbuff[3], count);
+ }
+ else {
+ memcpy (&((unsigned char *)ctx)[len], &xbuff[3], count);
+ }
+ len += count;
+ }
+ ++packetno;
+ retrans = MAXRETRANS+1;
+ }
+ if (--retrans <= 0) {
+ flushinput(_inbyte, ctx);
+ _outbyte(CAN, ctx);
+ _outbyte(CAN, ctx);
+ _outbyte(CAN, ctx);
+ return -3; /* too many retry error */
+ }
+ if(crc != 2) _outbyte(ACK, ctx);
+ if(mode) return len; /* YMODEM control block received */
+ continue;
+ }
+ reject:
+ flushinput(_inbyte, ctx);
+ _outbyte(NAK, ctx);
+ }
+}
+
+/***********************************************************************************************************************
+ * XMODEM Transmit
+ **********************************************************************************************************************/
+int XmodemTransmit(FetchChunkType fetchChunk, void *ctx, int srcsz, int onek, int mode, XmodemInByte _inbyte, XmodemOutByte _outbyte)
+{
+ unsigned char xbuff[XBUF_SIZE];
+ int bufsz, crc = -1;
+ unsigned char packetno = mode ? 0 : 1;
+ int i, c, len = 0;
+ int retry;
+
+ for(;;) {
+ for( retry = 0; retry < MAXSYNCTRETRY; ++retry) {
+ if ((c = _inbyte((DLY_1S)<<1, ctx)) >= 0) {
+ switch (c) {
+ case 'G':
+ crc = 2;
+ goto start_trans;
+ case 'C':
+ crc = 1;
+ goto start_trans;
+ case NAK:
+ crc = 0;
+ goto start_trans;
+ case CAN:
+ if ((c = _inbyte(DLY_1S, ctx)) == CAN) {
+ _outbyte(ACK, ctx);
+ flushinput(_inbyte, ctx);
+ return -1; /* canceled by remote */
+ }
+ break;
+ default:
+ break;
+ }
+ }
+ }
+ _outbyte(CAN, ctx);
+ _outbyte(CAN, ctx);
+ _outbyte(CAN, ctx);
+ flushinput(_inbyte, ctx);
+ return -2; /* no sync */
+
+ for(;;) {
+ start_trans:
+ c = srcsz - len;
+#ifdef XMODEM_1K
+ if(onek && (c > 128)) {
+ xbuff[0] = STX; bufsz = 1024;
+ }
+ else
+#endif
+ {
+ xbuff[0] = SOH; bufsz = 128;
+ }
+ xbuff[1] = packetno;
+ xbuff[2] = ~packetno;
+ if (c > bufsz) c = bufsz;
+ if (c > 0) {
+ memset (&xbuff[3], mode ? 0 : CTRLZ, bufsz);
+ if(fetchChunk) {
+ fetchChunk(ctx, &xbuff[3], c);
+ }
+ else {
+ memcpy (&xbuff[3], &((unsigned char *)ctx)[len], c);
+ }
+ if (crc) {
+ unsigned short ccrc = crc16_ccitt(&xbuff[3], bufsz);
+ xbuff[bufsz+3] = (ccrc>>8) & 0xFF;
+ xbuff[bufsz+4] = ccrc & 0xFF;
+ }
+ else {
+ unsigned char ccks = 0;
+ for (i = 3; i < bufsz+3; ++i) {
+ ccks += xbuff[i];
+ }
+ xbuff[bufsz+3] = ccks;
+ }
+ for (retry = 0; retry < MAXRETRANS; ++retry) {
+ for (i = 0; i < bufsz+4+(crc?1:0); ++i) {
+ _outbyte(xbuff[i], ctx);
+ }
+ c = (crc == 2) ? ACK : _inbyte(DLY_1S, ctx);
+ if (c >= 0 ) {
+ switch (c) {
+ case ACK:
+ ++packetno;
+ len += bufsz;
+ goto start_trans;
+ case CAN:
+ if ((c = _inbyte(DLY_1S, ctx)) == CAN) {
+ _outbyte(ACK, ctx);
+ flushinput(_inbyte, ctx);
+ return -1; /* canceled by remote */
+ }
+ break;
+ case NAK:
+ default:
+ break;
+ }
+ }
+ }
+ _outbyte(CAN, ctx);
+ _outbyte(CAN, ctx);
+ _outbyte(CAN, ctx);
+ flushinput(_inbyte, ctx);
+ return -4; /* xmit error */
+ }
+ else if(mode) {
+ return len; /* YMODEM control block sent */
+ }
+ else {
+ for (retry = 0; retry < 10; ++retry) {
+ _outbyte(EOT, ctx);
+ if ((c = _inbyte((DLY_1S)<<1, ctx)) == ACK) break;
+ }
+ if(c == ACK) {
+ return len; /* Normal exit */
+ }
+ else {
+ flushinput(_inbyte, ctx);
+ return -5; /* No ACK after EOT */
+ }
+ }
+ }
+ }
+}
diff --git a/fw/User/xmodem/xmodem.h b/fw/User/xmodem/xmodem.h
new file mode 100644
index 0000000..ccf67aa
--- /dev/null
+++ b/fw/User/xmodem/xmodem.h
@@ -0,0 +1,146 @@
+/***********************************************************************************************************************
+ * XMODEM implementation with YMODEM support
+ ***********************************************************************************************************************
+ * Copyright 2001-2019 Georges Menie (www.menie.org)
+ * Modified by Thuffir in 2019
+ * Modified by Analog Devices in 2024
+ * All rights reserved.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * * Neither the name of the University of California, Berkeley nor the
+ * names of its contributors may be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ **********************************************************************************************************************/
+
+/*
+ * This code has been modified by Analog Devices, Inc.
+ */
+
+#ifndef XMODEM_H_
+#define XMODEM_H_
+
+/***********************************************************************************************************************
+ * Config Section
+ **********************************************************************************************************************/
+/* Define this if you have your own CCITT-CRC-16 implementation */
+/* #define HAVE_CRC16 */
+
+/* Define this if you want XMODEM-1K support, it will increase stack usage by 896 bytes */
+#define XMODEM_1K
+
+#ifndef DLY_1S
+#define DLY_1S 1000
+#endif
+
+#ifndef MAXRETRANS
+#define MAXRETRANS 25
+#endif
+
+#ifndef MAXSYNCTRETRY
+#define MAXSYNCTRETRY 16
+#endif
+
+/** End Config Section ************************************************************************************************/
+
+typedef int ( *XmodemInByte )(int t, void *ctx);
+typedef void ( *XmodemOutByte )(int c, void *ctx);
+
+/***********************************************************************************************************************
+ * Function prototype for storing the received chunks
+ **********************************************************************************************************************/
+typedef void (*StoreChunkType)(
+ /* Pointer to the function context (can be used for anything) */
+ void *funcCtx,
+ /* Pointer to the XMODEM receive buffer (store data from here) */
+ void *xmodemBuffer,
+ /* Number of bytes received in the XMODEM buffer (and to be stored) */
+ int xmodemSize);
+
+/***********************************************************************************************************************
+ * XMODEM Receive
+ **********************************************************************************************************************/
+int XmodemReceive(
+ /* Function pointer for storing the received chunks or NULL*/
+ StoreChunkType storeChunk,
+ /* If storeChunk is NULL, pointer to the buffer to store the received data, else function context pointer to pass to
+ storeChunk() */
+ void *ctx,
+ /* Number of bytes to receive */
+ int destsz,
+ /* Checksum mode to request: 0 - arithmetic, 1 - CRC16, 2 - YMODEM-G (CRC16 and no ACK) */
+ int crc,
+ /* Receive mode: 0 - normal, nonzero - receive YMODEM control packet */
+ int mode,
+ /* Function pointer for receiving a byte with timeout */
+ XmodemInByte _inbyte,
+ /* Function pointer for sending a byte */
+ XmodemOutByte _outbyte);
+
+/***********************************************************************************************************************
+ * Function shortcut - XMODEM Receive with checksum
+ **********************************************************************************************************************/
+#define XmodemReceiveCsum(storeChunk, ctx, destsz, _inbyte, _outbyte) XmodemReceive(storeChunk, ctx, destsz, 0, 0, _inbyte, _outbyte)
+
+/***********************************************************************************************************************
+ * Function shortcut - XMODEM Receive with CRC-16
+ **********************************************************************************************************************/
+#define XmodemReceiveCrc(storeChunk, ctx, destsz, _inbyte, _outbyte) XmodemReceive(storeChunk, ctx, destsz, 1, 0, _inbyte, _outbyte)
+
+/***********************************************************************************************************************
+ * Function prototype for fetching the data chunks
+ **********************************************************************************************************************/
+typedef void (*FetchChunkType)(
+ /* Pointer to the function context (can be used for anything) */
+ void *funcCtx,
+ /* Pointer to the XMODEM send buffer (fetch data into here) */
+ void *xmodemBuffer,
+ /* Number of bytes that should be fetched (and stored into the XMODEM send buffer) */
+ int xmodemSize);
+
+/***********************************************************************************************************************
+ * XMODEM Transmit
+ **********************************************************************************************************************/
+int XmodemTransmit(
+ /* Function pointer for fetching the data chunks to be sent or NULL*/
+ FetchChunkType fetchChunk,
+ /* If fetchChunk is NULL, pointer to the buffer to be sent, else function context pointer to pass to fetchChunk() */
+ void *ctx,
+ /* Number of bytes to send */
+ int srcsz,
+ /* If nonzero 1024 byte blocks are used (XMODEM-1K) */
+ int onek,
+ /* Transfer mode: 0 - normal, nonzero - transmit YMODEM control packet */
+ int mode,
+ /* Function pointer for receiving a byte with timeout */
+ XmodemInByte _inbyte,
+ /* Function pointer for sending a byte */
+ XmodemOutByte _outbyte);
+
+/***********************************************************************************************************************
+ * Function shortcut - XMODEM Transmit with 128 bytes blocks
+ **********************************************************************************************************************/
+#define XmodemTransmit128b(fetchChunk, ctx, srcsz, _inbyte, _outbyte) XmodemTransmit(fetchChunk, ctx, srcsz, 0, 0, _inbyte, _outbyte)
+
+/***********************************************************************************************************************
+ * Function shortcut - XMODEM Transmit with 1K blocks
+ **********************************************************************************************************************/
+#define XmodemTransmit1K(fetchChunk, ctx, srcsz, _inbyte, _outbyte) XmodemTransmit(fetchChunk, ctx, srcsz, 1, 0, _inbyte, _outbyte)
+
+#endif // XMODEM_H_
diff --git a/fw/User/xmodem/xymodem.txt b/fw/User/xmodem/xymodem.txt
new file mode 100644
index 0000000..24a6578
--- /dev/null
+++ b/fw/User/xmodem/xymodem.txt
@@ -0,0 +1,2112 @@
+
+
+
+ - 1 -
+
+
+
+ XMODEM/YMODEM PROTOCOL REFERENCE
+ A compendium of documents describing the
+
+ XMODEM and YMODEM
+
+ File Transfer Protocols
+
+
+
+
+ This document was formatted 10-14-88.
+
+
+
+
+
+
+
+ Edited by Chuck Forsberg
+
+
+
+
+
+
+
+
+
+ This file may be redistributed without restriction
+ provided the text is not altered.
+
+ Please distribute as widely as possible.
+
+ Questions to Chuck Forsberg
+
+
+
+
+
+ Omen Technology Inc
+ The High Reliability Software
+ 17505-V Sauvie Island Road
+ Portland Oregon 97231
+ VOICE: 503-621-3406 :VOICE
+ TeleGodzilla BBS: 503-621-3746 Speed 19200(Telebit PEP),2400,1200,300
+ CompuServe: 70007,2304
+ GEnie: CAF
+ UUCP: ...!tektronix!reed!omen!caf
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ - 2 -
+
+
+
+ 1. TOWER OF BABEL
+
+ A "YMODEM Tower of Babel" has descended on the microcomputing community
+ bringing with it confusion, frustration, bloated phone bills, and wasted
+ man hours. Sadly, I (Chuck Forsberg) am partly to blame for this mess.
+
+ As author of the early 1980s batch and 1k XMODEM extensions, I assumed
+ readers of earlier versions of this document would implement as much of
+ the YMODEM protocol as their programming skills and computing environments
+ would permit. This proved a rather naive assumption as programmers
+ motivated by competitive pressure implemented as little of YMODEM as
+ possible. Some have taken whatever parts of YMODEM that appealed to them,
+ applied them to MODEM7 Batch, Telink, XMODEM or whatever, and called the
+ result YMODEM.
+
+ Jeff Garbers (Crosstalk package development director) said it all: "With
+ protocols in the public domain, anyone who wants to dink around with them
+ can go ahead." [1]
+
+ Documents containing altered examples derived from YMODEM.DOC have added
+ to the confusion. In one instance, some self styled rewriter of history
+ altered the heading in YMODEM.DOC's Figure 1 from "1024 byte Packets" to
+ "YMODEM/CRC File Transfer Protocol". None of the XMODEM and YMODEM
+ examples shown in that document were correct.
+
+ To put an end to this confusion, we must make "perfectly clear" what
+ YMODEM stands for, as Ward Christensen defined it in his 1985 coining of
+ the term.
+
+ To the majority of you who read, understood, and respected Ward's
+ definition of YMODEM, I apologize for the inconvenience.
+
+ 1.1 Definitions
+
+ ARC ARC is a program that compresses one or more files into an archive
+ and extracts files from such archives.
+
+ XMODEM refers to the file transfer etiquette introduced by Ward
+ Christensen's 1977 MODEM.ASM program. The name XMODEM comes from
+ Keith Petersen's XMODEM.ASM program, an adaptation of MODEM.ASM
+ for Remote CP/M (RCPM) systems. It's also called the MODEM or
+ MODEM2 protocol. Some who are unaware of MODEM7's unusual batch
+ file mode call it MODEM7. Other aliases include "CP/M Users'
+ Group" and "TERM II FTP 3". The name XMODEM caught on partly
+ because it is distinctive and partly because of media interest in
+
+
+ __________
+
+ 1. Page C/12, PC-WEEK July 12, 1987
+
+
+
+
+ Chapter 1
+
+
+
+
+
+
+
+ X/YMODEM Protocol Reference June 18 1988 3
+
+
+
+ bulletin board and RCPM systems where it was accessed with an
+ "XMODEM" command. This protocol is supported by every serious
+ communications program because of its universality, simplicity,
+ and reasonable performance.
+
+ XMODEM/CRC replaces XMODEM's 1 byte checksum with a two byte Cyclical
+ Redundancy Check (CRC-16), giving modern error detection
+ protection.
+
+ XMODEM-1k Refers to the XMODEM/CRC protocol with 1024 byte data blocks.
+
+ YMODEM Refers to the XMODEM/CRC (optional 1k blocks) protocol with batch
+ transmission as described below. In a nutshell, YMODEM means
+ BATCH.
+
+ YMODEM-g Refers to the streaming YMODEM variation described below.
+
+ True YMODEM(TM) In an attempt to sort out the YMODEM Tower of Babel, Omen
+ Technology has trademarked the term True YMODEM(TM) to represent
+ the complete YMODEM protocol described in this document, including
+ pathname, length, and modification date transmitted in block 0.
+ Please contact Omen Technology about certifying programs for True
+ YMODEM(TM) compliance.
+
+ ZMODEM uses familiar XMODEM/CRC and YMODEM technology in a new protocol
+ that provides reliability, throughput, file management, and user
+ amenities appropriate to contemporary data communications.
+
+ ZOO Like ARC, ZOO is a program that compresses one or more files into
+ a "zoo archive". ZOO supports many different operating systems
+ including Unix and VMS.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Chapter 1
+
+
+
+
+
+
+
+ X/YMODEM Protocol Reference June 18 1988 4
+
+
+
+ 2. YMODEM MINIMUM REQUIREMENTS
+
+ All programs claiming to support YMODEM must meet the following minimum
+ requirements:
+
+ + The sending program shall send the pathname (file name) in block 0.
+
+ + The pathname shall be a null terminated ASCII string as described
+ below.
+
+ For those who are too lazy to read the entire document:
+
+ + Unless specifically requested, only the file name portion is
+ sent.
+
+ + No drive letter is sent.
+
+ + Systems that do not distinguish between upper and lower case
+ letters in filenames shall send the pathname in lower case only.
+
+
+ + The receiving program shall use this pathname for the received file
+ name, unless explicitly overridden.
+
+ + When the receiving program receives this block and successfully
+ opened the output file, it shall acknowledge this block with an ACK
+ character and then proceed with a normal XMODEM file transfer
+ beginning with a "C" or NAK tranmsitted by the receiver.
+
+ + The sending program shall use CRC-16 in response to a "C" pathname
+ nak, otherwise use 8 bit checksum.
+
+ + The receiving program must accept any mixture of 128 and 1024 byte
+ blocks within each file it receives. Sending programs may
+ arbitrarily switch between 1024 and 128 byte blocks.
+
+ + The sending program must not change the length of an unacknowledged
+ block.
+
+ + At the end of each file, the sending program shall send EOT up to ten
+ times until it receives an ACK character. (This is part of the
+ XMODEM spec.)
+
+ + The end of a transfer session shall be signified by a null (empty)
+ pathname, this pathname block shall be acknowledged the same as other
+ pathname blocks.
+
+ Programs not meeting all of these requirements are not YMODEM compatible,
+ and shall not be described as supporting YMODEM.
+
+ Meeting these MINIMUM requirements does not guarantee reliable file
+
+
+
+ Chapter 2
+
+
+
+
+
+
+
+ X/YMODEM Protocol Reference June 18 1988 5
+
+
+
+ transfers under stress. Particular attention is called to XMODEM's single
+ character supervisory messages that are easily corrupted by transmission
+ errors.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Chapter 2
+
+
+
+
+
+
+
+ X/YMODEM Protocol Reference June 18 1988 6
+
+
+
+ 3. WHY YMODEM?
+
+ Since its development half a decade ago, the Ward Christensen modem
+ protocol has enabled a wide variety of computer systems to interchange
+ data. There is hardly a communications program that doesn't at least
+ claim to support this protocol.
+
+ Advances in computing, modems and networking have revealed a number of
+ weaknesses in the original protocol:
+
+ + The short block length caused throughput to suffer when used with
+ timesharing systems, packet switched networks, satellite circuits,
+ and buffered (error correcting) modems.
+
+ + The 8 bit arithmetic checksum and other aspects allowed line
+ impairments to interfere with dependable, accurate transfers.
+
+ + Only one file could be sent per command. The file name had to be
+ given twice, first to the sending program and then again to the
+ receiving program.
+
+ + The transmitted file could accumulate as many as 127 extraneous
+ bytes.
+
+ + The modification date of the file was lost.
+
+ A number of other protocols have been developed over the years, but none
+ have displaced XMODEM to date:
+
+ + Lack of public domain documentation and example programs have kept
+ proprietary protocols such as Blast, Relay, and others tightly bound
+ to the fortunes of their suppliers.
+
+ + Complexity discourages the widespread application of BISYNC, SDLC,
+ HDLC, X.25, and X.PC protocols.
+
+ + Performance compromises and complexity have limited the popularity of
+ the Kermit protocol, which was developed to allow file transfers in
+ environments hostile to XMODEM.
+
+ The XMODEM protocol extensions and YMODEM Batch address some of these
+ weaknesses while maintaining most of XMODEM's simplicity.
+
+ YMODEM is supported by the public domain programs YAM (CP/M),
+ YAM(CP/M-86), YAM(CCPM-86), IMP (CP/M), KMD (CP/M), rz/sz (Unix, Xenix,
+ VMS, Berkeley Unix, Venix, Xenix, Coherent, IDRIS, Regulus). Commercial
+ implementations include MIRROR, and Professional-YAM.[1] Communications
+
+
+
+
+
+
+
+ Chapter 3
+
+
+
+
+
+
+
+ X/YMODEM Protocol Reference June 18 1988 7
+
+
+
+ programs supporting these extensions have been in use since 1981.
+
+ The 1k block length (XMODEM-1k) described below may be used in conjunction
+ with YMODEM Batch Protocol, or with single file transfers identical to the
+ XMODEM/CRC protocol except for minimal changes to support 1k blocks.
+
+ Another extension is the YMODEM-g protocol. YMODEM-g provides batch
+ transfers with maximum throughput when used with end to end error
+ correcting media, such as X.PC and error correcting modems, including 9600
+ bps units by TeleBit, U.S.Robotics, Hayes, Electronic Vaults, Data Race,
+ and others.
+
+ To complete this tome, edited versions of Ward Christensen's original
+ protocol document and John Byrns's CRC-16 document are included for
+ reference.
+
+ References to the MODEM or MODEM7 protocol have been changed to XMODEM to
+ accommodate the vernacular. In Australia, it is properly called the
+ Christensen Protocol.
+
+
+ 3.1 Some Messages from the Pioneer
+
+ #: 130940 S0/Communications 25-Apr-85 18:38:47
+ Sb: my protocol
+ Fm: Ward Christensen 76703,302 [2]
+ To: all
+
+ Be aware the article[3] DID quote me correctly in terms of the phrases
+ like "not robust", etc.
+
+ It was a quick hack I threw together, very unplanned (like everything I
+ do), to satisfy a personal need to communicate with "some other" people.
+
+ ONLY the fact that it was done in 8/77, and that I put it in the public
+ domain immediately, made it become the standard that it is.
+
+
+
+
+
+
+
+ __________________________________________________________________________
+
+ 1. Available for IBM PC,XT,AT, Unix and Xenix
+
+ 2. Edited for typesetting appearance
+
+ 3. Infoworld April 29 p. 16
+
+
+
+
+ Chapter 3
+
+
+
+
+
+
+
+ X/YMODEM Protocol Reference June 18 1988 8
+
+
+
+ I think its time for me to
+
+ (1) document it; (people call me and say "my product is going to include
+ it - what can I 'reference'", or "I'm writing a paper on it, what do I put
+ in the bibliography") and
+
+ (2) propose an "incremental extension" to it, which might take "exactly"
+ the form of Chuck Forsberg's YAM protocol. He wrote YAM in C for CP/M and
+ put it in the public domain, and wrote a batch protocol for Unix[4] called
+ rb and sb (receive batch, send batch), which was basically XMODEM with
+ (a) a record 0 containing filename date time and size
+ (b) a 1K block size option
+ (c) CRC-16.
+
+ He did some clever programming to detect false ACK or EOT, but basically
+ left them the same.
+
+ People who suggest I make SIGNIFICANT changes to the protocol, such as
+ "full duplex", "multiple outstanding blocks", "multiple destinations", etc
+ etc don't understand that the incredible simplicity of the protocol is one
+ of the reasons it survived to this day in as many machines and programs as
+ it may be found in!
+
+ Consider the PC-NET group back in '77 or so - documenting to beat the band
+ - THEY had a protocol, but it was "extremely complex", because it tried to
+ be "all things to all people" - i.e. send binary files on a 7-bit system,
+ etc. I was not that "benevolent". I (emphasize > I < ) had an 8-bit UART,
+ so "my protocol was an 8-bit protocol", and I would just say "sorry" to
+ people who were held back by 7-bit limitations. ...
+
+ Block size: Chuck Forsberg created an extension of my protocol, called
+ YAM, which is also supported via his public domain programs for UNIX
+ called rb and sb - receive batch and send batch. They cleverly send a
+ "block 0" which contains the filename, date, time, and size.
+ Unfortunately, its UNIX style, and is a bit weird[5] - octal numbers, etc.
+ BUT, it is a nice way to overcome the kludgy "echo the chars of the name"
+ introduced with MODEM7. Further, chuck uses CRC-16 and optional 1K
+ blocks. Thus the record 0, 1K, and CRC, make it a "pretty slick new
+ protocol" which is not significantly different from my own.
+
+ Also, there is a catchy name - YMODEM. That means to some that it is the
+ "next thing after XMODEM", and to others that it is the Y(am)MODEM
+
+
+ __________
+
+ 4. VAX/VMS versions of these programs are also available.
+
+ 5. The file length, time, and file mode are optional. The pathname and
+ file length may be sent alone if desired.
+
+
+
+
+ Chapter 3
+
+
+
+
+
+
+
+ X/YMODEM Protocol Reference June 18 1988 9
+
+
+
+ protocol. I don't want to emphasize that too much - out of fear that
+ other mfgrs might think it is a "competitive" protocol, rather than an
+ "unaffiliated" protocol. Chuck is currently selling a much-enhanced
+ version of his CP/M-80 C program YAM, calling it Professional Yam, and its
+ for the PC - I'm using it right now. VERY slick! 32K capture buffer,
+ script, scrolling, previously captured text search, plus built-in commands
+ for just about everything - directory (sorted every which way), XMODEM,
+ YMODEM, KERMIT, and ASCII file upload/download, etc. You can program it
+ to "behave" with most any system - for example when trying a number for
+ CIS it detects the "busy" string back from the modem and substitutes a
+ diff phone # into the dialing string and branches back to try it.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Chapter 3
+
+
+
+
+
+
+
+ X/YMODEM Protocol Reference June 18 1988 10
+
+
+
+ 4. XMODEM PROTOCOL ENHANCEMENTS
+
+ This chapter discusses the protocol extensions to Ward Christensen's 1982
+ XMODEM protocol description document.
+
+ The original document recommends the user be asked whether to continue
+ trying or abort after 10 retries. Most programs no longer ask the
+ operator whether he wishes to keep retrying. Virtually all correctable
+ errors are corrected within the first few retransmissions. If the line is
+ so bad that ten attempts are insufficient, there is a significant danger
+ of undetected errors. If the connection is that bad, it's better to
+ redial for a better connection, or mail a floppy disk.
+
+
+ 4.1 Graceful Abort
+
+ The YAM and Professional-YAM X/YMODEM routines recognize a sequence of two
+ consecutive CAN (Hex 18) characters without modem errors (overrun,
+ framing, etc.) as a transfer abort command. This sequence is recognized
+ when is waiting for the beginning of a block or for an acknowledgement to
+ a block that has been sent. The check for two consecutive CAN characters
+ reduces the number of transfers aborted by line hits. YAM sends eight CAN
+ characters when it aborts an XMODEM, YMODEM, or ZMODEM protocol file
+ transfer. Pro-YAM then sends eight backspaces to delete the CAN
+ characters from the remote's keyboard input buffer, in case the remote had
+ already aborted the transfer and was awaiting a keyboarded command.
+
+
+ 4.2 CRC-16 Option
+
+ The XMODEM protocol uses an optional two character CRC-16 instead of the
+ one character arithmetic checksum used by the original protocol and by
+ most commercial implementations. CRC-16 guarantees detection of all
+ single and double bit errors, all errors with an odd number of error
+ bits, all burst errors of length 16 or less, 99.9969% of all 17-bit error
+ bursts, and 99.9984 per cent of all possible longer error bursts. By
+ contrast, a double bit error, or a burst error of 9 bits or more can sneak
+ past the XMODEM protocol arithmetic checksum.
+
+ The XMODEM/CRC protocol is similar to the XMODEM protocol, except that the
+ receiver specifies CRC-16 by sending C (Hex 43) instead of NAK when
+ requesting the FIRST block. A two byte CRC is sent in place of the one
+ byte arithmetic checksum.
+
+ YAM's c option to the r command enables CRC-16 in single file reception,
+ corresponding to the original implementation in the MODEM7 series
+ programs. This remains the default because many commercial communications
+ programs and bulletin board systems still do not support CRC-16,
+ especially those written in Basic or Pascal.
+
+ XMODEM protocol with CRC is accurate provided both sender and receiver
+
+
+
+ Chapter 4 XMODEM Protocol Enhancements
+
+
+
+
+
+
+
+ X/YMODEM Protocol Reference June 18 1988 11
+
+
+
+ both report a successful transmission. The protocol is robust in the
+ presence of characters lost by buffer overloading on timesharing systems.
+
+ The single character ACK/NAK responses generated by the receiving program
+ adapt well to split speed modems, where the reverse channel is limited to
+ ten per cent or less of the main channel's speed.
+
+ XMODEM and YMODEM are half duplex protocols which do not attempt to
+ transmit information and control signals in both directions at the same
+ time. This avoids buffer overrun problems that have been reported by
+ users attempting to exploit full duplex asynchronous file transfer
+ protocols such as Blast.
+
+ Professional-YAM adds several proprietary logic enhancements to XMODEM's
+ error detection and recovery. These compatible enhancements eliminate
+ most of the bad file transfers other programs make when using the XMODEM
+ protocol under less than ideal conditions.
+
+
+ 4.3 XMODEM-1k 1024 Byte Block
+
+ Disappointing throughput downloading from Unix with YMODEM[1] lead to the
+ development of 1024 byte blocks in 1982. 1024 byte blocks reduce the
+ effect of delays from timesharing systems, modems, and packet switched
+ networks on throughput by 87.5 per cent in addition to decreasing XMODEM's
+ 3 per cent overhead (block number, CRC, etc.).
+
+ Some environments cannot accept 1024 byte bursts, including some networks
+ and minicomputer ports. The longer block length should be an option.
+
+ The choice to use 1024 byte blocks is expressed to the sending program on
+ its command line or selection menu.[2] 1024 byte blocks improve throughput
+ in many applications.
+
+ An STX (02) replaces the SOH (01) at the beginning of the transmitted
+ block to notify the receiver of the longer block length. The transmitted
+ block contains 1024 bytes of data. The receiver should be able to accept
+ any mixture of 128 and 1024 byte blocks. The block number (in the second
+ and third bytes of the block) is incremented by one for each block
+ regardless of the block length.
+
+ The sender must not change between 128 and 1024 byte block lengths if it
+ has not received a valid ACK for the current block. Failure to observe
+
+
+ __________
+
+ 1. The name hadn't been coined yet, but the protocol was the same.
+
+ 2. See "KMD/IMP Exceptions to YMODEM" below.
+
+
+
+
+ Chapter 4 XMODEM Protocol Enhancements
+
+
+
+
+
+
+
+ X/YMODEM Protocol Reference June 18 1988 12
+
+
+
+ this restriction allows transmission errors to pass undetected.
+
+ If 1024 byte blocks are being used, it is possible for a file to "grow" up
+ to the next multiple of 1024 bytes. This does not waste disk space if the
+ allocation granularity is 1k or greater. With YMODEM batch transmission,
+ the optional file length transmitted in the file name block allows the
+ receiver to discard the padding, preserving the exact file length and
+ contents.
+
+ 1024 byte blocks may be used with batch file transmission or with single
+ file transmission. CRC-16 should be used with the k option to preserve
+ data integrity over phone lines. If a program wishes to enforce this
+ recommendation, it should cancel the transfer, then issue an informative
+ diagnostic message if the receiver requests checksum instead of CRC-16.
+
+ Under no circumstances may a sending program use CRC-16 unless the
+ receiver commands CRC-16.
+
+ Figure 1. XMODEM-1k Blocks
+
+ SENDER RECEIVER
+ "sx -k foo.bar"
+ "foo.bar open x.x minutes"
+ C
+ STX 01 FE Data[1024] CRC CRC
+ ACK
+ STX 02 FD Data[1024] CRC CRC
+ ACK
+ STX 03 FC Data[1000] CPMEOF[24] CRC CRC
+ ACK
+ EOT
+ ACK
+
+ Figure 2. Mixed 1024 and 128 byte Blocks
+
+ SENDER RECEIVER
+ "sx -k foo.bar"
+ "foo.bar open x.x minutes"
+ C
+ STX 01 FE Data[1024] CRC CRC
+ ACK
+ STX 02 FD Data[1024] CRC CRC
+ ACK
+ SOH 03 FC Data[128] CRC CRC
+ ACK
+ SOH 04 FB Data[100] CPMEOF[28] CRC CRC
+ ACK
+ EOT
+ ACK
+
+
+
+
+
+ Chapter 4 XMODEM Protocol Enhancements
+
+
+
+
+
+
+
+ X/YMODEM Protocol Reference June 18 1988 13
+
+
+
+ 5. YMODEM Batch File Transmission
+
+ The YMODEM Batch protocol is an extension to the XMODEM/CRC protocol that
+ allows 0 or more files to be transmitted with a single command. (Zero
+ files may be sent if none of the requested files is accessible.) The
+ design approach of the YMODEM Batch protocol is to use the normal routines
+ for sending and receiving XMODEM blocks in a layered fashion similar to
+ packet switching methods.
+
+ Why was it necessary to design a new batch protocol when one already
+ existed in MODEM7?[1] The batch file mode used by MODEM7 is unsuitable
+ because it does not permit full pathnames, file length, file date, or
+ other attribute information to be transmitted. Such a restrictive design,
+ hastily implemented with only CP/M in mind, would not have permitted
+ extensions to current areas of personal computing such as Unix, DOS, and
+ object oriented systems. In addition, the MODEM7 batch file mode is
+ somewhat susceptible to transmission impairments.
+
+ As in the case of single a file transfer, the receiver initiates batch
+ file transmission by sending a "C" character (for CRC-16).
+
+ The sender opens the first file and sends block number 0 with the
+ following information.[2]
+
+ Only the pathname (file name) part is required for batch transfers.
+
+ To maintain upwards compatibility, all unused bytes in block 0 must be set
+ to null.
+
+ Pathname The pathname (conventionally, the file name) is sent as a null
+ terminated ASCII string. This is the filename format used by the
+ handle oriented MSDOS(TM) functions and C library fopen functions.
+ An assembly language example follows:
+ DB 'foo.bar',0
+ No spaces are included in the pathname. Normally only the file name
+ stem (no directory prefix) is transmitted unless the sender has
+ selected YAM's f option to send the full pathname. The source drive
+ (A:, B:, etc.) is not sent.
+
+ Filename Considerations:
+
+
+
+ __________
+
+ 1. The MODEM7 batch protocol transmitted CP/M FCB bytes f1...f8 and
+ t1...t3 one character at a time. The receiver echoed these bytes as
+ received, one at a time.
+
+ 2. Only the data part of the block is described here.
+
+
+
+
+ Chapter 5 XMODEM Protocol Enhancements
+
+
+
+
+
+
+
+ X/YMODEM Protocol Reference June 18 1988 14
+
+
+
+ + File names are forced to lower case unless the sending system
+ supports upper/lower case file names. This is a convenience for
+ users of systems (such as Unix) which store filenames in upper
+ and lower case.
+
+ + The receiver should accommodate file names in lower and upper
+ case.
+
+ + When transmitting files between different operating systems,
+ file names must be acceptable to both the sender and receiving
+ operating systems.
+
+ If directories are included, they are delimited by /; i.e.,
+ "subdir/foo" is acceptable, "subdir\foo" is not.
+
+ Length The file length and each of the succeeding fields are optional.[3]
+ The length field is stored in the block as a decimal string counting
+ the number of data bytes in the file. The file length does not
+ include any CPMEOF (^Z) or other garbage characters used to pad the
+ last block.
+
+ If the file being transmitted is growing during transmission, the
+ length field should be set to at least the final expected file
+ length, or not sent.
+
+ The receiver stores the specified number of characters, discarding
+ any padding added by the sender to fill up the last block.
+
+ Modification Date The mod date is optional, and the filename and length
+ may be sent without requiring the mod date to be sent.
+
+ Iff the modification date is sent, a single space separates the
+ modification date from the file length.
+
+ The mod date is sent as an octal number giving the time the contents
+ of the file were last changed, measured in seconds from Jan 1 1970
+ Universal Coordinated Time (GMT). A date of 0 implies the
+ modification date is unknown and should be left as the date the file
+ is received.
+
+ This standard format was chosen to eliminate ambiguities arising from
+ transfers between different time zones.
+
+
+
+
+
+ __________
+
+ 3. Fields may not be skipped.
+
+
+
+
+ Chapter 5 XMODEM Protocol Enhancements
+
+
+
+
+
+
+
+ X/YMODEM Protocol Reference June 18 1988 15
+
+
+
+ Mode Iff the file mode is sent, a single space separates the file mode
+ from the modification date. The file mode is stored as an octal
+ string. Unless the file originated from a Unix system, the file mode
+ is set to 0. rb(1) checks the file mode for the 0x8000 bit which
+ indicates a Unix type regular file. Files with the 0x8000 bit set
+ are assumed to have been sent from another Unix (or similar) system
+ which uses the same file conventions. Such files are not translated
+ in any way.
+
+
+ Serial Number Iff the serial number is sent, a single space separates the
+ serial number from the file mode. The serial number of the
+ transmitting program is stored as an octal string. Programs which do
+ not have a serial number should omit this field, or set it to 0. The
+ receiver's use of this field is optional.
+
+
+ Other Fields YMODEM was designed to allow additional header fields to be
+ added as above without creating compatibility problems with older
+ YMODEM programs. Please contact Omen Technology if other fields are
+ needed for special application requirements.
+
+ The rest of the block is set to nulls. This is essential to preserve
+ upward compatibility.[4]
+
+ If the filename block is received with a CRC or other error, a
+ retransmission is requested. After the filename block has been received,
+ it is ACK'ed if the write open is successful. If the file cannot be
+ opened for writing, the receiver cancels the transfer with CAN characters
+ as described above.
+
+ The receiver then initiates transfer of the file contents with a "C"
+ character, according to the standard XMODEM/CRC protocol.
+
+ After the file contents and XMODEM EOT have been transmitted and
+ acknowledged, the receiver again asks for the next pathname.
+
+ Transmission of a null pathname terminates batch file transmission.
+
+ Note that transmission of no files is not necessarily an error. This is
+ possible if none of the files requested of the sender could be opened for
+ reading.
+
+
+
+ __________
+
+ 4. If, perchance, this information extends beyond 128 bytes (possible
+ with Unix 4.2 BSD extended file names), the block should be sent as a
+ 1k block as described above.
+
+
+
+
+ Chapter 5 XMODEM Protocol Enhancements
+
+
+
+
+
+
+
+ X/YMODEM Protocol Reference June 18 1988 16
+
+
+
+ Most YMODEM receivers request CRC-16 by default.
+
+ The Unix programs sz(1) and rz(1) included in the source code file
+ RZSZ.ZOO should answer other questions about YMODEM batch protocol.
+
+ Figure 3. YMODEM Batch Transmission Session (1 file)
+
+ SENDER RECEIVER
+ "sb foo.*"
+ "sending in batch mode etc."
+ C (command:rb)
+ SOH 00 FF foo.c NUL[123] CRC CRC
+ ACK
+ C
+ SOH 01 FE Data[128] CRC CRC
+ ACK
+ SOH 02 FC Data[128] CRC CRC
+ ACK
+ SOH 03 FB Data[100] CPMEOF[28] CRC CRC
+ ACK
+ EOT
+ NAK
+ EOT
+ ACK
+ C
+ SOH 00 FF NUL[128] CRC CRC
+ ACK
+
+ Figure 7. YMODEM Header Information and Features
+
+ _____________________________________________________________
+ | Program | Length | Date | Mode | S/N | 1k-Blk | YMODEM-g |
+ |___________|________|______|______|_____|________|__________|
+ |Unix rz/sz | yes | yes | yes | no | yes | sb only |
+ |___________|________|______|______|_____|________|__________|
+ |VMS rb/sb | yes | no | no | no | yes | no |
+ |___________|________|______|______|_____|________|__________|
+ |Pro-YAM | yes | yes | no | yes | yes | yes |
+ |___________|________|______|______|_____|________|__________|
+ |CP/M YAM | no | no | no | no | yes | no |
+ |___________|________|______|______|_____|________|__________|
+ |KMD/IMP | ? | no | no | no | yes | no |
+ |___________|________|______|______|_____|________|__________|
+
+ 5.1 KMD/IMP Exceptions to YMODEM
+
+ KMD and IMP use a "CK" character sequence emitted by the receiver to
+ trigger the use of 1024 byte blocks as an alternative to specifying this
+ option to the sending program. This two character sequence generally
+ works well on single process micros in direct communication, provided the
+ programs rigorously adhere to all the XMODEM recommendations included
+
+
+
+ Chapter 5 XMODEM Protocol Enhancements
+
+
+
+
+
+
+
+ X/YMODEM Protocol Reference June 18 1988 17
+
+
+
+ Figure 4. YMODEM Batch Transmission Session (2 files)
+
+ SENDER RECEIVER
+ "sb foo.c baz.c"
+ "sending in batch mode etc."
+ C (command:rb)
+ SOH 00 FF foo.c NUL[123] CRC CRC
+ ACK
+ C
+ SOH 01 FE Data[128] CRC CRC
+ ACK
+ SOH 02 FC Data[128] CRC CRC
+ ACK
+ SOH 03 FB Data[100] CPMEOF[28] CRC CRC
+ ACK
+ EOT
+ NAK
+ EOT
+ ACK
+ C
+ SOH 00 FF baz.c NUL[123] CRC CRC
+ ACK
+ C
+ SOH 01 FB Data[100] CPMEOF[28] CRC CRC
+ ACK
+ EOT
+ NAK
+ EOT
+ ACK
+ C
+ SOH 00 FF NUL[128] CRC CRC
+ ACK
+
+ Figure 5. YMODEM Batch Transmission Session-1k Blocks
+
+ SENDER RECEIVER
+ "sb -k foo.*"
+ "sending in batch mode etc."
+ C (command:rb)
+ SOH 00 FF foo.c NUL[123] CRC CRC
+ ACK
+ C
+ STX 01 FD Data[1024] CRC CRC
+ ACK
+ SOH 02 FC Data[128] CRC CRC
+ ACK
+ SOH 03 FB Data[100] CPMEOF[28] CRC CRC
+ ACK
+ EOT
+ NAK
+ EOT
+
+
+
+ Chapter 5 XMODEM Protocol Enhancements
+
+
+
+
+
+
+
+ X/YMODEM Protocol Reference June 18 1988 18
+
+
+
+ ACK
+ C
+ SOH 00 FF NUL[128] CRC CRC
+ ACK
+
+ Figure 6. YMODEM Filename block transmitted by sz
+
+ -rw-r--r-- 6347 Jun 17 1984 20:34 bbcsched.txt
+
+ 00 0100FF62 62637363 6865642E 74787400 |...bbcsched.txt.|
+ 10 36333437 20333331 34373432 35313320 |6347 3314742513 |
+ 20 31303036 34340000 00000000 00000000 |100644..........|
+ 30 00000000 00000000 00000000 00000000
+ 40 00000000 00000000 00000000 00000000
+ 50 00000000 00000000 00000000 00000000
+ 60 00000000 00000000 00000000 00000000
+ 70 00000000 00000000 00000000 00000000
+ 80 000000CA 56
+
+ herein. Programs with marginal XMODEM implementations do not fare so
+ well. Timesharing systems and packet switched networks can separate the
+ successive characters, rendering this method unreliable.
+
+ Sending programs may detect the CK sequence if the operating enviornment
+ does not preclude reliable implementation.
+
+ Instead of the standard YMODEM file length in decimal, KMD and IMP
+ transmit the CP/M record count in the last two bytes of the header block.
+
+
+ 6. YMODEM-g File Transmission
+
+ Developing technology is providing phone line data transmission at ever
+ higher speeds using very specialized techniques. These high speed modems,
+ as well as session protocols such as X.PC, provide high speed, nearly
+ error free communications at the expense of considerably increased delay
+ time.
+
+ This delay time is moderate compared to human interactions, but it
+ cripples the throughput of most error correcting protocols.
+
+ The g option to YMODEM has proven effective under these circumstances.
+ The g option is driven by the receiver, which initiates the batch transfer
+ by transmitting a G instead of C. When the sender recognizes the G, it
+ bypasses the usual wait for an ACK to each transmitted block, sending
+ succeeding blocks at full speed, subject to XOFF/XON or other flow control
+ exerted by the medium.
+
+ The sender expects an inital G to initiate the transmission of a
+ particular file, and also expects an ACK on the EOT sent at the end of
+ each file. This synchronization allows the receiver time to open and
+
+
+
+ Chapter 6 XMODEM Protocol Enhancements
+
+
+
+
+
+
+
+ X/YMODEM Protocol Reference June 18 1988 19
+
+
+
+ close files as necessary.
+
+ If an error is detected in a YMODEM-g transfer, the receiver aborts the
+ transfer with the multiple CAN abort sequence. The ZMODEM protocol should
+ be used in applications that require both streaming throughput and error
+ recovery.
+
+ Figure 8. YMODEM-g Transmission Session
+
+ SENDER RECEIVER
+ "sb foo.*"
+ "sending in batch mode etc..."
+ G (command:rb -g)
+ SOH 00 FF foo.c NUL[123] CRC CRC
+ G
+ SOH 01 FE Data[128] CRC CRC
+ STX 02 FD Data[1024] CRC CRC
+ SOH 03 FC Data[128] CRC CRC
+ SOH 04 FB Data[100] CPMEOF[28] CRC CRC
+ EOT
+ ACK
+ G
+ SOH 00 FF NUL[128] CRC CRC
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Chapter 6 XMODEM Protocol Enhancements
+
+
+
+
+
+
+
+ X/YMODEM Protocol Reference June 18 1988 20
+
+
+
+ 7. XMODEM PROTOCOL OVERVIEW
+
+ 8/9/82 by Ward Christensen.
+
+ I will maintain a master copy of this. Please pass on changes or
+ suggestions via CBBS/Chicago at (312) 545-8086, CBBS/CPMUG (312) 849-1132
+ or by voice at (312) 849-6279.
+
+ 7.1 Definitions
+
+ 01H
+ 04H
+ 06H
+ 15H
+