diff --git a/examples/stm32/FreeRTOSIPConfig.h b/examples/stm32/FreeRTOSIPConfig.h new file mode 100644 index 00000000..1adbb82b --- /dev/null +++ b/examples/stm32/FreeRTOSIPConfig.h @@ -0,0 +1,310 @@ +/* + * FreeRTOS Kernel V10.3.0 + * 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! + */ + + +/***************************************************************************** + * + * See the following URL for configuration information. + * http://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/TCP_IP_Configuration.html + * + *****************************************************************************/ + +#ifndef FREERTOS_IP_CONFIG_H +#define FREERTOS_IP_CONFIG_H + +/* Prototype for the function used to print out. In this case it prints to the +console before the network is connected then a UDP port after the network has +connected. */ +extern void vLoggingPrintf( const char *pcFormatString, ... ); + +/* Set to 1 to print out debug messages. If ipconfigHAS_DEBUG_PRINTF is set to +1 then FreeRTOS_debug_printf should be defined to the function used to print +out the debugging messages. */ +#define ipconfigHAS_DEBUG_PRINTF 0 +#if( ipconfigHAS_DEBUG_PRINTF == 1 ) + #define FreeRTOS_debug_printf(X) vLoggingPrintf X +#endif + +/* Set to 1 to print out non debugging messages, for example the output of the +FreeRTOS_netstat() command, and ping replies. If ipconfigHAS_PRINTF is set to 1 +then FreeRTOS_printf should be set to the function used to print out the +messages. */ +#define ipconfigHAS_PRINTF 1 +#if( ipconfigHAS_PRINTF == 1 ) + #define FreeRTOS_printf(X) vLoggingPrintf X +#endif + +/* Define the byte order of the target MCU (the MCU FreeRTOS+TCP is executing +on). Valid options are pdFREERTOS_BIG_ENDIAN and pdFREERTOS_LITTLE_ENDIAN. */ +#define ipconfigBYTE_ORDER pdFREERTOS_LITTLE_ENDIAN + +/* If the network card/driver includes checksum offloading (IP/TCP/UDP checksums) +then set ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM to 1 to prevent the software +stack repeating the checksum calculations. */ +#define ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM 1 + +/* Several API's will block until the result is known, or the action has been +performed, for example FreeRTOS_send() and FreeRTOS_recv(). The timeouts can be +set per socket, using setsockopt(). If not set, the times below will be +used as defaults. */ +#define ipconfigSOCK_DEFAULT_RECEIVE_BLOCK_TIME ( 2000 ) +#define ipconfigSOCK_DEFAULT_SEND_BLOCK_TIME ( 5000 ) + +/* Include support for LLMNR: Link-local Multicast Name Resolution +(non-Microsoft) */ +#define ipconfigUSE_LLMNR ( 0 ) + +/* Include support for NBNS: NetBIOS Name Service (Microsoft) */ +#define ipconfigUSE_NBNS ( 0 ) + +/* Include support for DNS caching. For TCP, having a small DNS cache is very +useful. When a cache is present, ipconfigDNS_REQUEST_ATTEMPTS can be kept low +and also DNS may use small timeouts. If a DNS reply comes in after the DNS +socket has been destroyed, the result will be stored into the cache. The next +call to FreeRTOS_gethostbyname() will return immediately, without even creating +a socket. */ +#define ipconfigUSE_DNS_CACHE ( 1 ) +#define ipconfigDNS_CACHE_NAME_LENGTH ( 32 ) +#define ipconfigDNS_CACHE_ENTRIES ( 4 ) +#define ipconfigDNS_REQUEST_ATTEMPTS ( 2 ) + +/* The IP stack executes it its own task (although any application task can make +use of its services through the published sockets API). ipconfigUDP_TASK_PRIORITY +sets the priority of the task that executes the IP stack. The priority is a +standard FreeRTOS task priority so can take any value from 0 (the lowest +priority) to (configMAX_PRIORITIES - 1) (the highest priority). +configMAX_PRIORITIES is a standard FreeRTOS configuration parameter defined in +FreeRTOSConfig.h, not FreeRTOSIPConfig.h. Consideration needs to be given as to +the priority assigned to the task executing the IP stack relative to the +priority assigned to tasks that use the IP stack. */ +#define ipconfigIP_TASK_PRIORITY ( configMAX_PRIORITIES - 2 ) + +/* The size, in words (not bytes), of the stack allocated to the FreeRTOS+TCP +task. This setting is less important when the FreeRTOS Win32 simulator is used +as the Win32 simulator only stores a fixed amount of information on the task +stack. FreeRTOS includes optional stack overflow detection, see: +http://www.freertos.org/Stacks-and-stack-overflow-checking.html */ +#define ipconfigIP_TASK_STACK_SIZE_WORDS ( configMINIMAL_STACK_SIZE * 5 ) + +/* ipconfigRAND32() is called by the IP stack to generate random numbers for +things such as a DHCP transaction number or initial sequence number. Random +number generation is performed via this macro to allow applications to use their +own random number generation method. For example, it might be possible to +generate a random number by sampling noise on an analogue input. */ +extern UBaseType_t uxRand(); +#define ipconfigRAND32() uxRand() + +/* If ipconfigUSE_NETWORK_EVENT_HOOK is set to 1 then FreeRTOS+TCP will call the +network event hook at the appropriate times. If ipconfigUSE_NETWORK_EVENT_HOOK +is not set to 1 then the network event hook will never be called. See +http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_UDP/API/vApplicationIPNetworkEventHook.shtml +*/ +#define ipconfigUSE_NETWORK_EVENT_HOOK 1 + +/* Sockets have a send block time attribute. If FreeRTOS_sendto() is called but +a network buffer cannot be obtained then the calling task is held in the Blocked +state (so other tasks can continue to executed) until either a network buffer +becomes available or the send block time expires. If the send block time expires +then the send operation is aborted. The maximum allowable send block time is +capped to the value set by ipconfigMAX_SEND_BLOCK_TIME_TICKS. Capping the +maximum allowable send block time prevents prevents a deadlock occurring when +all the network buffers are in use and the tasks that process (and subsequently +free) the network buffers are themselves blocked waiting for a network buffer. +ipconfigMAX_SEND_BLOCK_TIME_TICKS is specified in RTOS ticks. A time in +milliseconds can be converted to a time in ticks by dividing the time in +milliseconds by portTICK_PERIOD_MS. */ +#define ipconfigUDP_MAX_SEND_BLOCK_TIME_TICKS ( 5000 / portTICK_PERIOD_MS ) + +/* If ipconfigUSE_DHCP is 1 then FreeRTOS+TCP will attempt to retrieve an IP +address, netmask, DNS server address and gateway address from a DHCP server. If +ipconfigUSE_DHCP is 0 then FreeRTOS+TCP will use a static IP address. The +stack will revert to using the static IP address even when ipconfigUSE_DHCP is +set to 1 if a valid configuration cannot be obtained from a DHCP server for any +reason. The static configuration used is that passed into the stack by the +FreeRTOS_IPInit() function call. */ +#define ipconfigUSE_DHCP 1 + +/* When ipconfigUSE_DHCP is set to 1, DHCP requests will be sent out at +increasing time intervals until either a reply is received from a DHCP server +and accepted, or the interval between transmissions reaches +ipconfigMAXIMUM_DISCOVER_TX_PERIOD. The IP stack will revert to using the +static IP address passed as a parameter to FreeRTOS_IPInit() if the +re-transmission time interval reaches ipconfigMAXIMUM_DISCOVER_TX_PERIOD without +a DHCP reply being received. */ +#define ipconfigMAXIMUM_DISCOVER_TX_PERIOD ( 120000 / portTICK_PERIOD_MS ) + +/* The ARP cache is a table that maps IP addresses to MAC addresses. The IP +stack can only send a UDP message to a remove IP address if it knowns the MAC +address associated with the IP address, or the MAC address of the router used to +contact the remote IP address. When a UDP message is received from a remote IP +address the MAC address and IP address are added to the ARP cache. When a UDP +message is sent to a remote IP address that does not already appear in the ARP +cache then the UDP message is replaced by a ARP message that solicits the +required MAC address information. ipconfigARP_CACHE_ENTRIES defines the maximum +number of entries that can exist in the ARP table at any one time. */ +#define ipconfigARP_CACHE_ENTRIES 6 + +/* ARP requests that do not result in an ARP response will be re-transmitted a +maximum of ipconfigMAX_ARP_RETRANSMISSIONS times before the ARP request is +aborted. */ +#define ipconfigMAX_ARP_RETRANSMISSIONS ( 5 ) + +/* ipconfigMAX_ARP_AGE defines the maximum time between an entry in the ARP +table being created or refreshed and the entry being removed because it is stale. +New ARP requests are sent for ARP cache entries that are nearing their maximum +age. ipconfigMAX_ARP_AGE is specified in tens of seconds, so a value of 150 is +equal to 1500 seconds (or 25 minutes). */ +#define ipconfigMAX_ARP_AGE 150 + +/* Implementing FreeRTOS_inet_addr() necessitates the use of string handling +routines, which are relatively large. To save code space the full +FreeRTOS_inet_addr() implementation is made optional, and a smaller and faster +alternative called FreeRTOS_inet_addr_quick() is provided. FreeRTOS_inet_addr() +takes an IP in decimal dot format (for example, "192.168.0.1") as its parameter. +FreeRTOS_inet_addr_quick() takes an IP address as four separate numerical octets +(for example, 192, 168, 0, 1) as its parameters. If +ipconfigINCLUDE_FULL_INET_ADDR is set to 1 then both FreeRTOS_inet_addr() and +FreeRTOS_indet_addr_quick() are available. If ipconfigINCLUDE_FULL_INET_ADDR is +not set to 1 then only FreeRTOS_indet_addr_quick() is available. */ +#define ipconfigINCLUDE_FULL_INET_ADDR 1 + +/* ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS defines the total number of network buffer that +are available to the IP stack. The total number of network buffers is limited +to ensure the total amount of RAM that can be consumed by the IP stack is capped +to a pre-determinable value. */ +#define ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS 60 + +/* A FreeRTOS queue is used to send events from application tasks to the IP +stack. ipconfigEVENT_QUEUE_LENGTH sets the maximum number of events that can +be queued for processing at any one time. The event queue must be a minimum of +5 greater than the total number of network buffers. */ +#define ipconfigEVENT_QUEUE_LENGTH ( ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS + 5 ) + +/* The address of a socket is the combination of its IP address and its port +number. FreeRTOS_bind() is used to manually allocate a port number to a socket +(to 'bind' the socket to a port), but manual binding is not normally necessary +for client sockets (those sockets that initiate outgoing connections rather than +wait for incoming connections on a known port number). If +ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND is set to 1 then calling +FreeRTOS_sendto() on a socket that has not yet been bound will result in the IP +stack automatically binding the socket to a port number from the range +socketAUTO_PORT_ALLOCATION_START_NUMBER to 0xffff. If +ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND is set to 0 then calling FreeRTOS_sendto() +on a socket that has not yet been bound will result in the send operation being +aborted. */ +#define ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND 1 + +/* Defines the Time To Live (TTL) values used in outgoing UDP packets. */ +#define ipconfigUDP_TIME_TO_LIVE 128 +#define ipconfigTCP_TIME_TO_LIVE 128 /* also defined in FreeRTOSIPConfigDefaults.h */ + +/* USE_TCP: Use TCP and all its features */ +#define ipconfigUSE_TCP ( 1 ) + +/* Use the TCP socket wake context with a callback. */ +#define ipconfigSOCKET_HAS_USER_WAKE_CALLBACK_WITH_CONTEXT ( 1 ) + +/* USE_WIN: Let TCP use windowing mechanism. */ +#define ipconfigUSE_TCP_WIN ( 1 ) + +/* The MTU is the maximum number of bytes the payload of a network frame can +contain. For normal Ethernet V2 frames the maximum MTU is 1500. Setting a +lower value can save RAM, depending on the buffer management scheme used. If +ipconfigCAN_FRAGMENT_OUTGOING_PACKETS is 1 then (ipconfigNETWORK_MTU - 28) must +be divisible by 8. */ +#define ipconfigNETWORK_MTU 1200 + +/* Set ipconfigUSE_DNS to 1 to include a basic DNS client/resolver. DNS is used +through the FreeRTOS_gethostbyname() API function. */ +#define ipconfigUSE_DNS 1 + +/* If ipconfigREPLY_TO_INCOMING_PINGS is set to 1 then the IP stack will +generate replies to incoming ICMP echo (ping) requests. */ +#define ipconfigREPLY_TO_INCOMING_PINGS 1 + +/* If ipconfigSUPPORT_OUTGOING_PINGS is set to 1 then the +FreeRTOS_SendPingRequest() API function is available. */ +#define ipconfigSUPPORT_OUTGOING_PINGS 0 + +/* If ipconfigSUPPORT_SELECT_FUNCTION is set to 1 then the FreeRTOS_select() +(and associated) API function is available. */ +#define ipconfigSUPPORT_SELECT_FUNCTION 1 + +/* If ipconfigFILTER_OUT_NON_ETHERNET_II_FRAMES is set to 1 then Ethernet frames +that are not in Ethernet II format will be dropped. This option is included for +potential future IP stack developments. */ +#define ipconfigFILTER_OUT_NON_ETHERNET_II_FRAMES 1 + +/* If ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES is set to 1 then it is the +responsibility of the Ethernet interface to filter out packets that are of no +interest. If the Ethernet interface does not implement this functionality, then +set ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES to 0 to have the IP stack +perform the filtering instead (it is much less efficient for the stack to do it +because the packet will already have been passed into the stack). If the +Ethernet driver does all the necessary filtering in hardware then software +filtering can be removed by using a value other than 1 or 0. */ +#define ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES 1 + +/* The windows simulator cannot really simulate MAC interrupts, and needs to +block occasionally to allow other tasks to run. */ +#define configWINDOWS_MAC_INTERRUPT_SIMULATOR_DELAY ( 20 / portTICK_PERIOD_MS ) + +/* Advanced only: in order to access 32-bit fields in the IP packets with +32-bit memory instructions, all packets will be stored 32-bit-aligned, plus 16-bits. +This has to do with the contents of the IP-packets: all 32-bit fields are +32-bit-aligned, plus 16-bit(!) */ +#define ipconfigPACKET_FILLER_SIZE 2 + +/* Define the size of the pool of TCP window descriptors. On the average, each +TCP socket will use up to 2 x 6 descriptors, meaning that it can have 2 x 6 +outstanding packets (for Rx and Tx). When using up to 10 TP sockets +simultaneously, one could define TCP_WIN_SEG_COUNT as 120. */ +#define ipconfigTCP_WIN_SEG_COUNT 240 + +/* Each TCP socket has a circular buffers for Rx and Tx, which have a fixed +maximum size. Define the size of Rx buffer for TCP sockets. */ +#define ipconfigTCP_RX_BUFFER_LENGTH ( 1000 ) + +/* Define the size of Tx buffer for TCP sockets. */ +#define ipconfigTCP_TX_BUFFER_LENGTH ( 1000 ) + +/* When using call-back handlers, the driver may check if the handler points to +real program memory (RAM or flash) or just has a random non-zero value. */ +#define ipconfigIS_VALID_PROG_ADDRESS(x) ( (x) != NULL ) + +/* Include support for TCP hang protection. All sockets in a connecting or +disconnecting stage will timeout after a period of non-activity. */ +#define ipconfigTCP_HANG_PROTECTION ( 1 ) +#define ipconfigTCP_HANG_PROTECTION_TIME ( 30 ) + +/* Include support for TCP keep-alive messages. */ +#define ipconfigTCP_KEEP_ALIVE ( 1 ) +#define ipconfigTCP_KEEP_ALIVE_INTERVAL ( 20 ) /* in seconds */ + +#define portINLINE __inline + +#endif /* FREERTOS_IP_CONFIG_H */ diff --git a/examples/stm32/Makefile b/examples/stm32/Makefile new file mode 100644 index 00000000..5822b9c7 --- /dev/null +++ b/examples/stm32/Makefile @@ -0,0 +1,45 @@ +# FreeRTOS/{FreeRTOS-Kernel V10.4.3,FreeRTOS-Plus-TCP V2.3.2} +PROG = firmware +ARCH ?= stm32f1 +ROOT = $(realpath $(CURDIR)/../..) +ENV ?= docker run -it --rm -v $(ROOT):$(ROOT) -w $(CURDIR) mdashnet/armgcc +MFLAGS = -DMG_ENABLE_LINES=1 -DMG_ARCH=MG_ARCH_FREERTOS_TCP -DMG_ENABLE_FS=0 +ifeq "$(ARCH)" "stm32f1" +MCU = -mcpu=cortex-m3 -mthumb -mfloat-abi=soft +else ifeq "$(ARCH)" "stm32f7" +MCU = -mcpu=cortex-m7 -mthumb -mfpu=fpv5-sp-d16 -mfloat-abi=hard +endif +INCS = -I$(ARCH) -I. -I../.. -Ifreertos-kernel/include -Ifreertos-tcp/include -Ifreertos-tcp/portable/Compiler/GCC +CFLAGS = -W -Wall -Og $(MCU) -fdata-sections -ffunction-sections $(INCS) $(MFLAGS) $(EXTRA) +AFLAGS = --warn --fatal-warnings $(MCU) +LDFLAGS = $(MCU) -specs=nano.specs -T$(ARCH)/link.ld -nostartfiles -nostdlib -lc -lm -lnosys -lgcc #-Wl,-Map=obj/$(PROG).map,--cref -Wl,--gc-sections +A_SRC = $(ARCH)/boot.s +C_SRC = main.c # $(wildcard freertos-tcp/*.c) +C_SRC += freertos-kernel/portable/MemMang/heap_4.c $(ARCH)/port.c +C_SRC += freertos-kernel/list.c freertos-kernel/tasks.c freertos-kernel/queue.c +OBJS := $(C_SRC:%.c=obj/%.o) $(A_SRC:%.s=obj/%.o) #obj/mongoose.o + +all: $(PROG).hex + +$(PROG).bin: $(PROG).elf + $(ENV) arm-none-eabi-objcopy -O binary $< $@ + +$(PROG).hex: $(PROG).bin + $(ENV) arm-none-eabi-objcopy -I binary -O ihex --change-address 0x8000000 $< $@ + +$(PROG).elf: $(OBJS) + $(ENV) arm-none-eabi-gcc $^ $(LDFLAGS) -o $@ + +obj/%.o: %.c + @mkdir -p $(dir $@) + $(ENV) arm-none-eabi-gcc $(CFLAGS) -c $< -o $@ + +obj/%.o: %.s + @mkdir -p $(dir $@) + $(ENV) arm-none-eabi-as $(AFLAGS) $< -o $@ + +obj/mongoose.o: + $(ENV) arm-none-eabi-gcc $(CFLAGS) -c ../../mongoose.c -o $@ + +clean: + @rm -rf *.{bin,elf,map,lst,tgz,zip,hex} obj \ No newline at end of file diff --git a/examples/stm32/freertos-kernel/croutine.c b/examples/stm32/freertos-kernel/croutine.c new file mode 100644 index 00000000..64574e3d --- /dev/null +++ b/examples/stm32/freertos-kernel/croutine.c @@ -0,0 +1,361 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#include "FreeRTOS.h" +#include "task.h" +#include "croutine.h" + +/* Remove the whole file is co-routines are not being used. */ +#if ( configUSE_CO_ROUTINES != 0 ) + +/* + * Some kernel aware debuggers require data to be viewed to be global, rather + * than file scope. + */ + #ifdef portREMOVE_STATIC_QUALIFIER + #define static + #endif + + +/* Lists for ready and blocked co-routines. --------------------*/ + static List_t pxReadyCoRoutineLists[ configMAX_CO_ROUTINE_PRIORITIES ]; /*< Prioritised ready co-routines. */ + static List_t xDelayedCoRoutineList1; /*< Delayed co-routines. */ + static List_t xDelayedCoRoutineList2; /*< Delayed co-routines (two lists are used - one for delays that have overflowed the current tick count. */ + static List_t * pxDelayedCoRoutineList = NULL; /*< Points to the delayed co-routine list currently being used. */ + static List_t * pxOverflowDelayedCoRoutineList = NULL; /*< Points to the delayed co-routine list currently being used to hold co-routines that have overflowed the current tick count. */ + static List_t xPendingReadyCoRoutineList; /*< Holds co-routines that have been readied by an external event. They cannot be added directly to the ready lists as the ready lists cannot be accessed by interrupts. */ + +/* Other file private variables. --------------------------------*/ + CRCB_t * pxCurrentCoRoutine = NULL; + static UBaseType_t uxTopCoRoutineReadyPriority = 0; + static TickType_t xCoRoutineTickCount = 0, xLastTickCount = 0, xPassedTicks = 0; + +/* The initial state of the co-routine when it is created. */ + #define corINITIAL_STATE ( 0 ) + +/* + * Place the co-routine represented by pxCRCB into the appropriate ready queue + * for the priority. It is inserted at the end of the list. + * + * This macro accesses the co-routine ready lists and therefore must not be + * used from within an ISR. + */ + #define prvAddCoRoutineToReadyQueue( pxCRCB ) \ + { \ + if( pxCRCB->uxPriority > uxTopCoRoutineReadyPriority ) \ + { \ + uxTopCoRoutineReadyPriority = pxCRCB->uxPriority; \ + } \ + vListInsertEnd( ( List_t * ) &( pxReadyCoRoutineLists[ pxCRCB->uxPriority ] ), &( pxCRCB->xGenericListItem ) ); \ + } + +/* + * Utility to ready all the lists used by the scheduler. This is called + * automatically upon the creation of the first co-routine. + */ + static void prvInitialiseCoRoutineLists( void ); + +/* + * Co-routines that are readied by an interrupt cannot be placed directly into + * the ready lists (there is no mutual exclusion). Instead they are placed in + * in the pending ready list in order that they can later be moved to the ready + * list by the co-routine scheduler. + */ + static void prvCheckPendingReadyList( void ); + +/* + * Macro that looks at the list of co-routines that are currently delayed to + * see if any require waking. + * + * Co-routines are stored in the queue in the order of their wake time - + * meaning once one co-routine has been found whose timer has not expired + * we need not look any further down the list. + */ + static void prvCheckDelayedList( void ); + +/*-----------------------------------------------------------*/ + + BaseType_t xCoRoutineCreate( crCOROUTINE_CODE pxCoRoutineCode, + UBaseType_t uxPriority, + UBaseType_t uxIndex ) + { + BaseType_t xReturn; + CRCB_t * pxCoRoutine; + + /* Allocate the memory that will store the co-routine control block. */ + pxCoRoutine = ( CRCB_t * ) pvPortMalloc( sizeof( CRCB_t ) ); + + if( pxCoRoutine ) + { + /* If pxCurrentCoRoutine is NULL then this is the first co-routine to + * be created and the co-routine data structures need initialising. */ + if( pxCurrentCoRoutine == NULL ) + { + pxCurrentCoRoutine = pxCoRoutine; + prvInitialiseCoRoutineLists(); + } + + /* Check the priority is within limits. */ + if( uxPriority >= configMAX_CO_ROUTINE_PRIORITIES ) + { + uxPriority = configMAX_CO_ROUTINE_PRIORITIES - 1; + } + + /* Fill out the co-routine control block from the function parameters. */ + pxCoRoutine->uxState = corINITIAL_STATE; + pxCoRoutine->uxPriority = uxPriority; + pxCoRoutine->uxIndex = uxIndex; + pxCoRoutine->pxCoRoutineFunction = pxCoRoutineCode; + + /* Initialise all the other co-routine control block parameters. */ + vListInitialiseItem( &( pxCoRoutine->xGenericListItem ) ); + vListInitialiseItem( &( pxCoRoutine->xEventListItem ) ); + + /* Set the co-routine control block as a link back from the ListItem_t. + * This is so we can get back to the containing CRCB from a generic item + * in a list. */ + listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xGenericListItem ), pxCoRoutine ); + listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xEventListItem ), pxCoRoutine ); + + /* Event lists are always in priority order. */ + listSET_LIST_ITEM_VALUE( &( pxCoRoutine->xEventListItem ), ( ( TickType_t ) configMAX_CO_ROUTINE_PRIORITIES - ( TickType_t ) uxPriority ) ); + + /* Now the co-routine has been initialised it can be added to the ready + * list at the correct priority. */ + prvAddCoRoutineToReadyQueue( pxCoRoutine ); + + xReturn = pdPASS; + } + else + { + xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; + } + + return xReturn; + } +/*-----------------------------------------------------------*/ + + void vCoRoutineAddToDelayedList( TickType_t xTicksToDelay, + List_t * pxEventList ) + { + TickType_t xTimeToWake; + + /* Calculate the time to wake - this may overflow but this is + * not a problem. */ + xTimeToWake = xCoRoutineTickCount + xTicksToDelay; + + /* We must remove ourselves from the ready list before adding + * ourselves to the blocked list as the same list item is used for + * both lists. */ + ( void ) uxListRemove( ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) ); + + /* The list item will be inserted in wake time order. */ + listSET_LIST_ITEM_VALUE( &( pxCurrentCoRoutine->xGenericListItem ), xTimeToWake ); + + if( xTimeToWake < xCoRoutineTickCount ) + { + /* Wake time has overflowed. Place this item in the + * overflow list. */ + vListInsert( ( List_t * ) pxOverflowDelayedCoRoutineList, ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) ); + } + else + { + /* The wake time has not overflowed, so we can use the + * current block list. */ + vListInsert( ( List_t * ) pxDelayedCoRoutineList, ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) ); + } + + if( pxEventList ) + { + /* Also add the co-routine to an event list. If this is done then the + * function must be called with interrupts disabled. */ + vListInsert( pxEventList, &( pxCurrentCoRoutine->xEventListItem ) ); + } + } +/*-----------------------------------------------------------*/ + + static void prvCheckPendingReadyList( void ) + { + /* Are there any co-routines waiting to get moved to the ready list? These + * are co-routines that have been readied by an ISR. The ISR cannot access + * the ready lists itself. */ + while( listLIST_IS_EMPTY( &xPendingReadyCoRoutineList ) == pdFALSE ) + { + CRCB_t * pxUnblockedCRCB; + + /* The pending ready list can be accessed by an ISR. */ + portDISABLE_INTERRUPTS(); + { + pxUnblockedCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( ( &xPendingReadyCoRoutineList ) ); + ( void ) uxListRemove( &( pxUnblockedCRCB->xEventListItem ) ); + } + portENABLE_INTERRUPTS(); + + ( void ) uxListRemove( &( pxUnblockedCRCB->xGenericListItem ) ); + prvAddCoRoutineToReadyQueue( pxUnblockedCRCB ); + } + } +/*-----------------------------------------------------------*/ + + static void prvCheckDelayedList( void ) + { + CRCB_t * pxCRCB; + + xPassedTicks = xTaskGetTickCount() - xLastTickCount; + + while( xPassedTicks ) + { + xCoRoutineTickCount++; + xPassedTicks--; + + /* If the tick count has overflowed we need to swap the ready lists. */ + if( xCoRoutineTickCount == 0 ) + { + List_t * pxTemp; + + /* Tick count has overflowed so we need to swap the delay lists. If there are + * any items in pxDelayedCoRoutineList here then there is an error! */ + pxTemp = pxDelayedCoRoutineList; + pxDelayedCoRoutineList = pxOverflowDelayedCoRoutineList; + pxOverflowDelayedCoRoutineList = pxTemp; + } + + /* See if this tick has made a timeout expire. */ + while( listLIST_IS_EMPTY( pxDelayedCoRoutineList ) == pdFALSE ) + { + pxCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxDelayedCoRoutineList ); + + if( xCoRoutineTickCount < listGET_LIST_ITEM_VALUE( &( pxCRCB->xGenericListItem ) ) ) + { + /* Timeout not yet expired. */ + break; + } + + portDISABLE_INTERRUPTS(); + { + /* The event could have occurred just before this critical + * section. If this is the case then the generic list item will + * have been moved to the pending ready list and the following + * line is still valid. Also the pvContainer parameter will have + * been set to NULL so the following lines are also valid. */ + ( void ) uxListRemove( &( pxCRCB->xGenericListItem ) ); + + /* Is the co-routine waiting on an event also? */ + if( pxCRCB->xEventListItem.pxContainer ) + { + ( void ) uxListRemove( &( pxCRCB->xEventListItem ) ); + } + } + portENABLE_INTERRUPTS(); + + prvAddCoRoutineToReadyQueue( pxCRCB ); + } + } + + xLastTickCount = xCoRoutineTickCount; + } +/*-----------------------------------------------------------*/ + + void vCoRoutineSchedule( void ) + { + /* Only run a co-routine after prvInitialiseCoRoutineLists() has been + * called. prvInitialiseCoRoutineLists() is called automatically when a + * co-routine is created. */ + if( pxDelayedCoRoutineList != NULL ) + { + /* See if any co-routines readied by events need moving to the ready lists. */ + prvCheckPendingReadyList(); + + /* See if any delayed co-routines have timed out. */ + prvCheckDelayedList(); + + /* Find the highest priority queue that contains ready co-routines. */ + while( listLIST_IS_EMPTY( &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) ) ) + { + if( uxTopCoRoutineReadyPriority == 0 ) + { + /* No more co-routines to check. */ + return; + } + + --uxTopCoRoutineReadyPriority; + } + + /* listGET_OWNER_OF_NEXT_ENTRY walks through the list, so the co-routines + * of the same priority get an equal share of the processor time. */ + listGET_OWNER_OF_NEXT_ENTRY( pxCurrentCoRoutine, &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) ); + + /* Call the co-routine. */ + ( pxCurrentCoRoutine->pxCoRoutineFunction )( pxCurrentCoRoutine, pxCurrentCoRoutine->uxIndex ); + } + } +/*-----------------------------------------------------------*/ + + static void prvInitialiseCoRoutineLists( void ) + { + UBaseType_t uxPriority; + + for( uxPriority = 0; uxPriority < configMAX_CO_ROUTINE_PRIORITIES; uxPriority++ ) + { + vListInitialise( ( List_t * ) &( pxReadyCoRoutineLists[ uxPriority ] ) ); + } + + vListInitialise( ( List_t * ) &xDelayedCoRoutineList1 ); + vListInitialise( ( List_t * ) &xDelayedCoRoutineList2 ); + vListInitialise( ( List_t * ) &xPendingReadyCoRoutineList ); + + /* Start with pxDelayedCoRoutineList using list1 and the + * pxOverflowDelayedCoRoutineList using list2. */ + pxDelayedCoRoutineList = &xDelayedCoRoutineList1; + pxOverflowDelayedCoRoutineList = &xDelayedCoRoutineList2; + } +/*-----------------------------------------------------------*/ + + BaseType_t xCoRoutineRemoveFromEventList( const List_t * pxEventList ) + { + CRCB_t * pxUnblockedCRCB; + BaseType_t xReturn; + + /* This function is called from within an interrupt. It can only access + * event lists and the pending ready list. This function assumes that a + * check has already been made to ensure pxEventList is not empty. */ + pxUnblockedCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxEventList ); + ( void ) uxListRemove( &( pxUnblockedCRCB->xEventListItem ) ); + vListInsertEnd( ( List_t * ) &( xPendingReadyCoRoutineList ), &( pxUnblockedCRCB->xEventListItem ) ); + + if( pxUnblockedCRCB->uxPriority >= pxCurrentCoRoutine->uxPriority ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + + return xReturn; + } + +#endif /* configUSE_CO_ROUTINES == 0 */ diff --git a/examples/stm32/freertos-kernel/event_groups.c b/examples/stm32/freertos-kernel/event_groups.c new file mode 100644 index 00000000..0ee79906 --- /dev/null +++ b/examples/stm32/freertos-kernel/event_groups.c @@ -0,0 +1,771 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* Standard includes. */ +#include + +/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining + * all the API functions to use the MPU wrappers. That should only be done when + * task.h is included from an application file. */ +#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "timers.h" +#include "event_groups.h" + +/* Lint e961, e750 and e9021 are suppressed as a MISRA exception justified + * because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined + * for the header files above, but not in this file, in order to generate the + * correct privileged Vs unprivileged linkage and placement. */ +#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750 !e9021 See comment above. */ + +/* The following bit fields convey control information in a task's event list + * item value. It is important they don't clash with the + * taskEVENT_LIST_ITEM_VALUE_IN_USE definition. */ +#if configUSE_16_BIT_TICKS == 1 + #define eventCLEAR_EVENTS_ON_EXIT_BIT 0x0100U + #define eventUNBLOCKED_DUE_TO_BIT_SET 0x0200U + #define eventWAIT_FOR_ALL_BITS 0x0400U + #define eventEVENT_BITS_CONTROL_BYTES 0xff00U +#else + #define eventCLEAR_EVENTS_ON_EXIT_BIT 0x01000000UL + #define eventUNBLOCKED_DUE_TO_BIT_SET 0x02000000UL + #define eventWAIT_FOR_ALL_BITS 0x04000000UL + #define eventEVENT_BITS_CONTROL_BYTES 0xff000000UL +#endif + +typedef struct EventGroupDef_t +{ + EventBits_t uxEventBits; + List_t xTasksWaitingForBits; /*< List of tasks waiting for a bit to be set. */ + + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxEventGroupNumber; + #endif + + #if ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the event group is statically allocated to ensure no attempt is made to free the memory. */ + #endif +} EventGroup_t; + +/*-----------------------------------------------------------*/ + +/* + * Test the bits set in uxCurrentEventBits to see if the wait condition is met. + * The wait condition is defined by xWaitForAllBits. If xWaitForAllBits is + * pdTRUE then the wait condition is met if all the bits set in uxBitsToWaitFor + * are also set in uxCurrentEventBits. If xWaitForAllBits is pdFALSE then the + * wait condition is met if any of the bits set in uxBitsToWait for are also set + * in uxCurrentEventBits. + */ +static BaseType_t prvTestWaitCondition( const EventBits_t uxCurrentEventBits, + const EventBits_t uxBitsToWaitFor, + const BaseType_t xWaitForAllBits ) PRIVILEGED_FUNCTION; + +/*-----------------------------------------------------------*/ + +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + + EventGroupHandle_t xEventGroupCreateStatic( StaticEventGroup_t * pxEventGroupBuffer ) + { + EventGroup_t * pxEventBits; + + /* A StaticEventGroup_t object must be provided. */ + configASSERT( pxEventGroupBuffer ); + + #if ( configASSERT_DEFINED == 1 ) + { + /* Sanity check that the size of the structure used to declare a + * variable of type StaticEventGroup_t equals the size of the real + * event group structure. */ + volatile size_t xSize = sizeof( StaticEventGroup_t ); + configASSERT( xSize == sizeof( EventGroup_t ) ); + } /*lint !e529 xSize is referenced if configASSERT() is defined. */ + #endif /* configASSERT_DEFINED */ + + /* The user has provided a statically allocated event group - use it. */ + pxEventBits = ( EventGroup_t * ) pxEventGroupBuffer; /*lint !e740 !e9087 EventGroup_t and StaticEventGroup_t are deliberately aliased for data hiding purposes and guaranteed to have the same size and alignment requirement - checked by configASSERT(). */ + + if( pxEventBits != NULL ) + { + pxEventBits->uxEventBits = 0; + vListInitialise( &( pxEventBits->xTasksWaitingForBits ) ); + + #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + { + /* Both static and dynamic allocation can be used, so note that + * this event group was created statically in case the event group + * is later deleted. */ + pxEventBits->ucStaticallyAllocated = pdTRUE; + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + + traceEVENT_GROUP_CREATE( pxEventBits ); + } + else + { + /* xEventGroupCreateStatic should only ever be called with + * pxEventGroupBuffer pointing to a pre-allocated (compile time + * allocated) StaticEventGroup_t variable. */ + traceEVENT_GROUP_CREATE_FAILED(); + } + + return pxEventBits; + } + +#endif /* configSUPPORT_STATIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + + EventGroupHandle_t xEventGroupCreate( void ) + { + EventGroup_t * pxEventBits; + + /* Allocate the event group. Justification for MISRA deviation as + * follows: pvPortMalloc() always ensures returned memory blocks are + * aligned per the requirements of the MCU stack. In this case + * pvPortMalloc() must return a pointer that is guaranteed to meet the + * alignment requirements of the EventGroup_t structure - which (if you + * follow it through) is the alignment requirements of the TickType_t type + * (EventBits_t being of TickType_t itself). Therefore, whenever the + * stack alignment requirements are greater than or equal to the + * TickType_t alignment requirements the cast is safe. In other cases, + * where the natural word size of the architecture is less than + * sizeof( TickType_t ), the TickType_t variables will be accessed in two + * or more reads operations, and the alignment requirements is only that + * of each individual read. */ + pxEventBits = ( EventGroup_t * ) pvPortMalloc( sizeof( EventGroup_t ) ); /*lint !e9087 !e9079 see comment above. */ + + if( pxEventBits != NULL ) + { + pxEventBits->uxEventBits = 0; + vListInitialise( &( pxEventBits->xTasksWaitingForBits ) ); + + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + /* Both static and dynamic allocation can be used, so note this + * event group was allocated statically in case the event group is + * later deleted. */ + pxEventBits->ucStaticallyAllocated = pdFALSE; + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ + + traceEVENT_GROUP_CREATE( pxEventBits ); + } + else + { + traceEVENT_GROUP_CREATE_FAILED(); /*lint !e9063 Else branch only exists to allow tracing and does not generate code if trace macros are not defined. */ + } + + return pxEventBits; + } + +#endif /* configSUPPORT_DYNAMIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +EventBits_t xEventGroupSync( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToSet, + const EventBits_t uxBitsToWaitFor, + TickType_t xTicksToWait ) +{ + EventBits_t uxOriginalBitValue, uxReturn; + EventGroup_t * pxEventBits = xEventGroup; + BaseType_t xAlreadyYielded; + BaseType_t xTimeoutOccurred = pdFALSE; + + configASSERT( ( uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); + configASSERT( uxBitsToWaitFor != 0 ); + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif + + vTaskSuspendAll(); + { + uxOriginalBitValue = pxEventBits->uxEventBits; + + ( void ) xEventGroupSetBits( xEventGroup, uxBitsToSet ); + + if( ( ( uxOriginalBitValue | uxBitsToSet ) & uxBitsToWaitFor ) == uxBitsToWaitFor ) + { + /* All the rendezvous bits are now set - no need to block. */ + uxReturn = ( uxOriginalBitValue | uxBitsToSet ); + + /* Rendezvous always clear the bits. They will have been cleared + * already unless this is the only task in the rendezvous. */ + pxEventBits->uxEventBits &= ~uxBitsToWaitFor; + + xTicksToWait = 0; + } + else + { + if( xTicksToWait != ( TickType_t ) 0 ) + { + traceEVENT_GROUP_SYNC_BLOCK( xEventGroup, uxBitsToSet, uxBitsToWaitFor ); + + /* Store the bits that the calling task is waiting for in the + * task's event list item so the kernel knows when a match is + * found. Then enter the blocked state. */ + vTaskPlaceOnUnorderedEventList( &( pxEventBits->xTasksWaitingForBits ), ( uxBitsToWaitFor | eventCLEAR_EVENTS_ON_EXIT_BIT | eventWAIT_FOR_ALL_BITS ), xTicksToWait ); + + /* This assignment is obsolete as uxReturn will get set after + * the task unblocks, but some compilers mistakenly generate a + * warning about uxReturn being returned without being set if the + * assignment is omitted. */ + uxReturn = 0; + } + else + { + /* The rendezvous bits were not set, but no block time was + * specified - just return the current event bit value. */ + uxReturn = pxEventBits->uxEventBits; + xTimeoutOccurred = pdTRUE; + } + } + } + xAlreadyYielded = xTaskResumeAll(); + + if( xTicksToWait != ( TickType_t ) 0 ) + { + if( xAlreadyYielded == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* The task blocked to wait for its required bits to be set - at this + * point either the required bits were set or the block time expired. If + * the required bits were set they will have been stored in the task's + * event list item, and they should now be retrieved then cleared. */ + uxReturn = uxTaskResetEventItemValue(); + + if( ( uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET ) == ( EventBits_t ) 0 ) + { + /* The task timed out, just return the current event bit value. */ + taskENTER_CRITICAL(); + { + uxReturn = pxEventBits->uxEventBits; + + /* Although the task got here because it timed out before the + * bits it was waiting for were set, it is possible that since it + * unblocked another task has set the bits. If this is the case + * then it needs to clear the bits before exiting. */ + if( ( uxReturn & uxBitsToWaitFor ) == uxBitsToWaitFor ) + { + pxEventBits->uxEventBits &= ~uxBitsToWaitFor; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + + xTimeoutOccurred = pdTRUE; + } + else + { + /* The task unblocked because the bits were set. */ + } + + /* Control bits might be set as the task had blocked should not be + * returned. */ + uxReturn &= ~eventEVENT_BITS_CONTROL_BYTES; + } + + traceEVENT_GROUP_SYNC_END( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTimeoutOccurred ); + + /* Prevent compiler warnings when trace macros are not used. */ + ( void ) xTimeoutOccurred; + + return uxReturn; +} +/*-----------------------------------------------------------*/ + +EventBits_t xEventGroupWaitBits( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToWaitFor, + const BaseType_t xClearOnExit, + const BaseType_t xWaitForAllBits, + TickType_t xTicksToWait ) +{ + EventGroup_t * pxEventBits = xEventGroup; + EventBits_t uxReturn, uxControlBits = 0; + BaseType_t xWaitConditionMet, xAlreadyYielded; + BaseType_t xTimeoutOccurred = pdFALSE; + + /* Check the user is not attempting to wait on the bits used by the kernel + * itself, and that at least one bit is being requested. */ + configASSERT( xEventGroup ); + configASSERT( ( uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); + configASSERT( uxBitsToWaitFor != 0 ); + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif + + vTaskSuspendAll(); + { + const EventBits_t uxCurrentEventBits = pxEventBits->uxEventBits; + + /* Check to see if the wait condition is already met or not. */ + xWaitConditionMet = prvTestWaitCondition( uxCurrentEventBits, uxBitsToWaitFor, xWaitForAllBits ); + + if( xWaitConditionMet != pdFALSE ) + { + /* The wait condition has already been met so there is no need to + * block. */ + uxReturn = uxCurrentEventBits; + xTicksToWait = ( TickType_t ) 0; + + /* Clear the wait bits if requested to do so. */ + if( xClearOnExit != pdFALSE ) + { + pxEventBits->uxEventBits &= ~uxBitsToWaitFor; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else if( xTicksToWait == ( TickType_t ) 0 ) + { + /* The wait condition has not been met, but no block time was + * specified, so just return the current value. */ + uxReturn = uxCurrentEventBits; + xTimeoutOccurred = pdTRUE; + } + else + { + /* The task is going to block to wait for its required bits to be + * set. uxControlBits are used to remember the specified behaviour of + * this call to xEventGroupWaitBits() - for use when the event bits + * unblock the task. */ + if( xClearOnExit != pdFALSE ) + { + uxControlBits |= eventCLEAR_EVENTS_ON_EXIT_BIT; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + if( xWaitForAllBits != pdFALSE ) + { + uxControlBits |= eventWAIT_FOR_ALL_BITS; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Store the bits that the calling task is waiting for in the + * task's event list item so the kernel knows when a match is + * found. Then enter the blocked state. */ + vTaskPlaceOnUnorderedEventList( &( pxEventBits->xTasksWaitingForBits ), ( uxBitsToWaitFor | uxControlBits ), xTicksToWait ); + + /* This is obsolete as it will get set after the task unblocks, but + * some compilers mistakenly generate a warning about the variable + * being returned without being set if it is not done. */ + uxReturn = 0; + + traceEVENT_GROUP_WAIT_BITS_BLOCK( xEventGroup, uxBitsToWaitFor ); + } + } + xAlreadyYielded = xTaskResumeAll(); + + if( xTicksToWait != ( TickType_t ) 0 ) + { + if( xAlreadyYielded == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* The task blocked to wait for its required bits to be set - at this + * point either the required bits were set or the block time expired. If + * the required bits were set they will have been stored in the task's + * event list item, and they should now be retrieved then cleared. */ + uxReturn = uxTaskResetEventItemValue(); + + if( ( uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET ) == ( EventBits_t ) 0 ) + { + taskENTER_CRITICAL(); + { + /* The task timed out, just return the current event bit value. */ + uxReturn = pxEventBits->uxEventBits; + + /* It is possible that the event bits were updated between this + * task leaving the Blocked state and running again. */ + if( prvTestWaitCondition( uxReturn, uxBitsToWaitFor, xWaitForAllBits ) != pdFALSE ) + { + if( xClearOnExit != pdFALSE ) + { + pxEventBits->uxEventBits &= ~uxBitsToWaitFor; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + xTimeoutOccurred = pdTRUE; + } + taskEXIT_CRITICAL(); + } + else + { + /* The task unblocked because the bits were set. */ + } + + /* The task blocked so control bits may have been set. */ + uxReturn &= ~eventEVENT_BITS_CONTROL_BYTES; + } + + traceEVENT_GROUP_WAIT_BITS_END( xEventGroup, uxBitsToWaitFor, xTimeoutOccurred ); + + /* Prevent compiler warnings when trace macros are not used. */ + ( void ) xTimeoutOccurred; + + return uxReturn; +} +/*-----------------------------------------------------------*/ + +EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToClear ) +{ + EventGroup_t * pxEventBits = xEventGroup; + EventBits_t uxReturn; + + /* Check the user is not attempting to clear the bits used by the kernel + * itself. */ + configASSERT( xEventGroup ); + configASSERT( ( uxBitsToClear & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); + + taskENTER_CRITICAL(); + { + traceEVENT_GROUP_CLEAR_BITS( xEventGroup, uxBitsToClear ); + + /* The value returned is the event group value prior to the bits being + * cleared. */ + uxReturn = pxEventBits->uxEventBits; + + /* Clear the bits. */ + pxEventBits->uxEventBits &= ~uxBitsToClear; + } + taskEXIT_CRITICAL(); + + return uxReturn; +} +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) ) + + BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToClear ) + { + BaseType_t xReturn; + + traceEVENT_GROUP_CLEAR_BITS_FROM_ISR( xEventGroup, uxBitsToClear ); + xReturn = xTimerPendFunctionCallFromISR( vEventGroupClearBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToClear, NULL ); /*lint !e9087 Can't avoid cast to void* as a generic callback function not specific to this use case. Callback casts back to original type so safe. */ + + return xReturn; + } + +#endif /* if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) ) */ +/*-----------------------------------------------------------*/ + +EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup ) +{ + UBaseType_t uxSavedInterruptStatus; + EventGroup_t const * const pxEventBits = xEventGroup; + EventBits_t uxReturn; + + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + uxReturn = pxEventBits->uxEventBits; + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + + return uxReturn; +} /*lint !e818 EventGroupHandle_t is a typedef used in other functions to so can't be pointer to const. */ +/*-----------------------------------------------------------*/ + +EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToSet ) +{ + ListItem_t * pxListItem, * pxNext; + ListItem_t const * pxListEnd; + List_t const * pxList; + EventBits_t uxBitsToClear = 0, uxBitsWaitedFor, uxControlBits; + EventGroup_t * pxEventBits = xEventGroup; + BaseType_t xMatchFound = pdFALSE; + + /* Check the user is not attempting to set the bits used by the kernel + * itself. */ + configASSERT( xEventGroup ); + configASSERT( ( uxBitsToSet & eventEVENT_BITS_CONTROL_BYTES ) == 0 ); + + pxList = &( pxEventBits->xTasksWaitingForBits ); + pxListEnd = listGET_END_MARKER( pxList ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ + vTaskSuspendAll(); + { + traceEVENT_GROUP_SET_BITS( xEventGroup, uxBitsToSet ); + + pxListItem = listGET_HEAD_ENTRY( pxList ); + + /* Set the bits. */ + pxEventBits->uxEventBits |= uxBitsToSet; + + /* See if the new bit value should unblock any tasks. */ + while( pxListItem != pxListEnd ) + { + pxNext = listGET_NEXT( pxListItem ); + uxBitsWaitedFor = listGET_LIST_ITEM_VALUE( pxListItem ); + xMatchFound = pdFALSE; + + /* Split the bits waited for from the control bits. */ + uxControlBits = uxBitsWaitedFor & eventEVENT_BITS_CONTROL_BYTES; + uxBitsWaitedFor &= ~eventEVENT_BITS_CONTROL_BYTES; + + if( ( uxControlBits & eventWAIT_FOR_ALL_BITS ) == ( EventBits_t ) 0 ) + { + /* Just looking for single bit being set. */ + if( ( uxBitsWaitedFor & pxEventBits->uxEventBits ) != ( EventBits_t ) 0 ) + { + xMatchFound = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else if( ( uxBitsWaitedFor & pxEventBits->uxEventBits ) == uxBitsWaitedFor ) + { + /* All bits are set. */ + xMatchFound = pdTRUE; + } + else + { + /* Need all bits to be set, but not all the bits were set. */ + } + + if( xMatchFound != pdFALSE ) + { + /* The bits match. Should the bits be cleared on exit? */ + if( ( uxControlBits & eventCLEAR_EVENTS_ON_EXIT_BIT ) != ( EventBits_t ) 0 ) + { + uxBitsToClear |= uxBitsWaitedFor; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Store the actual event flag value in the task's event list + * item before removing the task from the event list. The + * eventUNBLOCKED_DUE_TO_BIT_SET bit is set so the task knows + * that is was unblocked due to its required bits matching, rather + * than because it timed out. */ + vTaskRemoveFromUnorderedEventList( pxListItem, pxEventBits->uxEventBits | eventUNBLOCKED_DUE_TO_BIT_SET ); + } + + /* Move onto the next list item. Note pxListItem->pxNext is not + * used here as the list item may have been removed from the event list + * and inserted into the ready/pending reading list. */ + pxListItem = pxNext; + } + + /* Clear any bits that matched when the eventCLEAR_EVENTS_ON_EXIT_BIT + * bit was set in the control word. */ + pxEventBits->uxEventBits &= ~uxBitsToClear; + } + ( void ) xTaskResumeAll(); + + return pxEventBits->uxEventBits; +} +/*-----------------------------------------------------------*/ + +void vEventGroupDelete( EventGroupHandle_t xEventGroup ) +{ + EventGroup_t * pxEventBits = xEventGroup; + const List_t * pxTasksWaitingForBits = &( pxEventBits->xTasksWaitingForBits ); + + vTaskSuspendAll(); + { + traceEVENT_GROUP_DELETE( xEventGroup ); + + while( listCURRENT_LIST_LENGTH( pxTasksWaitingForBits ) > ( UBaseType_t ) 0 ) + { + /* Unblock the task, returning 0 as the event list is being deleted + * and cannot therefore have any bits set. */ + configASSERT( pxTasksWaitingForBits->xListEnd.pxNext != ( const ListItem_t * ) &( pxTasksWaitingForBits->xListEnd ) ); + vTaskRemoveFromUnorderedEventList( pxTasksWaitingForBits->xListEnd.pxNext, eventUNBLOCKED_DUE_TO_BIT_SET ); + } + + #if ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) ) + { + /* The event group can only have been allocated dynamically - free + * it again. */ + vPortFree( pxEventBits ); + } + #elif ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + { + /* The event group could have been allocated statically or + * dynamically, so check before attempting to free the memory. */ + if( pxEventBits->ucStaticallyAllocated == ( uint8_t ) pdFALSE ) + { + vPortFree( pxEventBits ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + } + ( void ) xTaskResumeAll(); +} +/*-----------------------------------------------------------*/ + +/* For internal use only - execute a 'set bits' command that was pended from + * an interrupt. */ +void vEventGroupSetBitsCallback( void * pvEventGroup, + const uint32_t ulBitsToSet ) +{ + ( void ) xEventGroupSetBits( pvEventGroup, ( EventBits_t ) ulBitsToSet ); /*lint !e9079 Can't avoid cast to void* as a generic timer callback prototype. Callback casts back to original type so safe. */ +} +/*-----------------------------------------------------------*/ + +/* For internal use only - execute a 'clear bits' command that was pended from + * an interrupt. */ +void vEventGroupClearBitsCallback( void * pvEventGroup, + const uint32_t ulBitsToClear ) +{ + ( void ) xEventGroupClearBits( pvEventGroup, ( EventBits_t ) ulBitsToClear ); /*lint !e9079 Can't avoid cast to void* as a generic timer callback prototype. Callback casts back to original type so safe. */ +} +/*-----------------------------------------------------------*/ + +static BaseType_t prvTestWaitCondition( const EventBits_t uxCurrentEventBits, + const EventBits_t uxBitsToWaitFor, + const BaseType_t xWaitForAllBits ) +{ + BaseType_t xWaitConditionMet = pdFALSE; + + if( xWaitForAllBits == pdFALSE ) + { + /* Task only has to wait for one bit within uxBitsToWaitFor to be + * set. Is one already set? */ + if( ( uxCurrentEventBits & uxBitsToWaitFor ) != ( EventBits_t ) 0 ) + { + xWaitConditionMet = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* Task has to wait for all the bits in uxBitsToWaitFor to be set. + * Are they set already? */ + if( ( uxCurrentEventBits & uxBitsToWaitFor ) == uxBitsToWaitFor ) + { + xWaitConditionMet = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + return xWaitConditionMet; +} +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) ) + + BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToSet, + BaseType_t * pxHigherPriorityTaskWoken ) + { + BaseType_t xReturn; + + traceEVENT_GROUP_SET_BITS_FROM_ISR( xEventGroup, uxBitsToSet ); + xReturn = xTimerPendFunctionCallFromISR( vEventGroupSetBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToSet, pxHigherPriorityTaskWoken ); /*lint !e9087 Can't avoid cast to void* as a generic callback function not specific to this use case. Callback casts back to original type so safe. */ + + return xReturn; + } + +#endif /* if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + UBaseType_t uxEventGroupGetNumber( void * xEventGroup ) + { + UBaseType_t xReturn; + EventGroup_t const * pxEventBits = ( EventGroup_t * ) xEventGroup; /*lint !e9087 !e9079 EventGroupHandle_t is a pointer to an EventGroup_t, but EventGroupHandle_t is kept opaque outside of this file for data hiding purposes. */ + + if( xEventGroup == NULL ) + { + xReturn = 0; + } + else + { + xReturn = pxEventBits->uxEventGroupNumber; + } + + return xReturn; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + void vEventGroupSetNumber( void * xEventGroup, + UBaseType_t uxEventGroupNumber ) + { + ( ( EventGroup_t * ) xEventGroup )->uxEventGroupNumber = uxEventGroupNumber; /*lint !e9087 !e9079 EventGroupHandle_t is a pointer to an EventGroup_t, but EventGroupHandle_t is kept opaque outside of this file for data hiding purposes. */ + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ diff --git a/examples/stm32/freertos-kernel/include/FreeRTOS.h b/examples/stm32/freertos-kernel/include/FreeRTOS.h new file mode 100644 index 00000000..5e443a62 --- /dev/null +++ b/examples/stm32/freertos-kernel/include/FreeRTOS.h @@ -0,0 +1,1345 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#ifndef INC_FREERTOS_H +#define INC_FREERTOS_H + +/* + * Include the generic headers required for the FreeRTOS port being used. + */ +#include + +/* + * If stdint.h cannot be located then: + * + If using GCC ensure the -nostdint options is *not* being used. + * + Ensure the project's include path includes the directory in which your + * compiler stores stdint.h. + * + Set any compiler options necessary for it to support C99, as technically + * stdint.h is only mandatory with C99 (FreeRTOS does not require C99 in any + * other way). + * + The FreeRTOS download includes a simple stdint.h definition that can be + * used in cases where none is provided by the compiler. The files only + * contains the typedefs required to build FreeRTOS. Read the instructions + * in FreeRTOS/source/stdint.readme for more information. + */ +#include /* READ COMMENT ABOVE. */ + +/* *INDENT-OFF* */ +#ifdef __cplusplus + extern "C" { +#endif +/* *INDENT-ON* */ + +/* Application specific configuration options. */ +#include "FreeRTOSConfig.h" + +/* Basic FreeRTOS definitions. */ +#include "projdefs.h" + +/* Definitions specific to the port being used. */ +#include "portable.h" + +/* Must be defaulted before configUSE_NEWLIB_REENTRANT is used below. */ +#ifndef configUSE_NEWLIB_REENTRANT + #define configUSE_NEWLIB_REENTRANT 0 +#endif + +/* Required if struct _reent is used. */ +#if ( configUSE_NEWLIB_REENTRANT == 1 ) + #include +#endif + +/* + * Check all the required application specific macros have been defined. + * These macros are application specific and (as downloaded) are defined + * within FreeRTOSConfig.h. + */ + +#ifndef configMINIMAL_STACK_SIZE + #error Missing definition: configMINIMAL_STACK_SIZE must be defined in FreeRTOSConfig.h. configMINIMAL_STACK_SIZE defines the size (in words) of the stack allocated to the idle task. Refer to the demo project provided for your port for a suitable value. +#endif + +#ifndef configMAX_PRIORITIES + #error Missing definition: configMAX_PRIORITIES must be defined in FreeRTOSConfig.h. See the Configuration section of the FreeRTOS API documentation for details. +#endif + +#if configMAX_PRIORITIES < 1 + #error configMAX_PRIORITIES must be defined to be greater than or equal to 1. +#endif + +#ifndef configUSE_PREEMPTION + #error Missing definition: configUSE_PREEMPTION must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. +#endif + +#ifndef configUSE_IDLE_HOOK + #error Missing definition: configUSE_IDLE_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. +#endif + +#ifndef configUSE_TICK_HOOK + #error Missing definition: configUSE_TICK_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. +#endif + +#ifndef configUSE_16_BIT_TICKS + #error Missing definition: configUSE_16_BIT_TICKS must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. +#endif + +#ifndef configUSE_CO_ROUTINES + #define configUSE_CO_ROUTINES 0 +#endif + +#ifndef INCLUDE_vTaskPrioritySet + #define INCLUDE_vTaskPrioritySet 0 +#endif + +#ifndef INCLUDE_uxTaskPriorityGet + #define INCLUDE_uxTaskPriorityGet 0 +#endif + +#ifndef INCLUDE_vTaskDelete + #define INCLUDE_vTaskDelete 0 +#endif + +#ifndef INCLUDE_vTaskSuspend + #define INCLUDE_vTaskSuspend 0 +#endif + +#ifdef INCLUDE_xTaskDelayUntil + #ifdef INCLUDE_vTaskDelayUntil + /* INCLUDE_vTaskDelayUntil was replaced by INCLUDE_xTaskDelayUntil. Backward + * compatibility is maintained if only one or the other is defined, but + * there is a conflict if both are defined. */ + #error INCLUDE_vTaskDelayUntil and INCLUDE_xTaskDelayUntil are both defined. INCLUDE_vTaskDelayUntil is no longer required and should be removed + #endif +#endif + +#ifndef INCLUDE_xTaskDelayUntil + #ifdef INCLUDE_vTaskDelayUntil + /* If INCLUDE_vTaskDelayUntil is set but INCLUDE_xTaskDelayUntil is not then + * the project's FreeRTOSConfig.h probably pre-dates the introduction of + * xTaskDelayUntil and setting INCLUDE_xTaskDelayUntil to whatever + * INCLUDE_vTaskDelayUntil is set to will ensure backward compatibility. + */ + #define INCLUDE_xTaskDelayUntil INCLUDE_vTaskDelayUntil + #endif +#endif + +#ifndef INCLUDE_xTaskDelayUntil + #define INCLUDE_xTaskDelayUntil 0 +#endif + +#ifndef INCLUDE_vTaskDelay + #define INCLUDE_vTaskDelay 0 +#endif + +#ifndef INCLUDE_xTaskGetIdleTaskHandle + #define INCLUDE_xTaskGetIdleTaskHandle 0 +#endif + +#ifndef INCLUDE_xTaskAbortDelay + #define INCLUDE_xTaskAbortDelay 0 +#endif + +#ifndef INCLUDE_xQueueGetMutexHolder + #define INCLUDE_xQueueGetMutexHolder 0 +#endif + +#ifndef INCLUDE_xSemaphoreGetMutexHolder + #define INCLUDE_xSemaphoreGetMutexHolder INCLUDE_xQueueGetMutexHolder +#endif + +#ifndef INCLUDE_xTaskGetHandle + #define INCLUDE_xTaskGetHandle 0 +#endif + +#ifndef INCLUDE_uxTaskGetStackHighWaterMark + #define INCLUDE_uxTaskGetStackHighWaterMark 0 +#endif + +#ifndef INCLUDE_uxTaskGetStackHighWaterMark2 + #define INCLUDE_uxTaskGetStackHighWaterMark2 0 +#endif + +#ifndef INCLUDE_eTaskGetState + #define INCLUDE_eTaskGetState 0 +#endif + +#ifndef INCLUDE_xTaskResumeFromISR + #define INCLUDE_xTaskResumeFromISR 1 +#endif + +#ifndef INCLUDE_xTimerPendFunctionCall + #define INCLUDE_xTimerPendFunctionCall 0 +#endif + +#ifndef INCLUDE_xTaskGetSchedulerState + #define INCLUDE_xTaskGetSchedulerState 0 +#endif + +#ifndef INCLUDE_xTaskGetCurrentTaskHandle + #define INCLUDE_xTaskGetCurrentTaskHandle 0 +#endif + +#if configUSE_CO_ROUTINES != 0 + #ifndef configMAX_CO_ROUTINE_PRIORITIES + #error configMAX_CO_ROUTINE_PRIORITIES must be greater than or equal to 1. + #endif +#endif + +#ifndef configUSE_DAEMON_TASK_STARTUP_HOOK + #define configUSE_DAEMON_TASK_STARTUP_HOOK 0 +#endif + +#ifndef configUSE_APPLICATION_TASK_TAG + #define configUSE_APPLICATION_TASK_TAG 0 +#endif + +#ifndef configNUM_THREAD_LOCAL_STORAGE_POINTERS + #define configNUM_THREAD_LOCAL_STORAGE_POINTERS 0 +#endif + +#ifndef configUSE_RECURSIVE_MUTEXES + #define configUSE_RECURSIVE_MUTEXES 0 +#endif + +#ifndef configUSE_MUTEXES + #define configUSE_MUTEXES 0 +#endif + +#ifndef configUSE_TIMERS + #define configUSE_TIMERS 0 +#endif + +#ifndef configUSE_COUNTING_SEMAPHORES + #define configUSE_COUNTING_SEMAPHORES 0 +#endif + +#ifndef configUSE_ALTERNATIVE_API + #define configUSE_ALTERNATIVE_API 0 +#endif + +#ifndef portCRITICAL_NESTING_IN_TCB + #define portCRITICAL_NESTING_IN_TCB 0 +#endif + +#ifndef configMAX_TASK_NAME_LEN + #define configMAX_TASK_NAME_LEN 16 +#endif + +#ifndef configIDLE_SHOULD_YIELD + #define configIDLE_SHOULD_YIELD 1 +#endif + +#if configMAX_TASK_NAME_LEN < 1 + #error configMAX_TASK_NAME_LEN must be set to a minimum of 1 in FreeRTOSConfig.h +#endif + +#ifndef configASSERT + #define configASSERT( x ) + #define configASSERT_DEFINED 0 +#else + #define configASSERT_DEFINED 1 +#endif + +/* configPRECONDITION should be defined as configASSERT. + * The CBMC proofs need a way to track assumptions and assertions. + * A configPRECONDITION statement should express an implicit invariant or + * assumption made. A configASSERT statement should express an invariant that must + * hold explicit before calling the code. */ +#ifndef configPRECONDITION + #define configPRECONDITION( X ) configASSERT( X ) + #define configPRECONDITION_DEFINED 0 +#else + #define configPRECONDITION_DEFINED 1 +#endif + +#ifndef portMEMORY_BARRIER + #define portMEMORY_BARRIER() +#endif + +#ifndef portSOFTWARE_BARRIER + #define portSOFTWARE_BARRIER() +#endif + +/* The timers module relies on xTaskGetSchedulerState(). */ +#if configUSE_TIMERS == 1 + + #ifndef configTIMER_TASK_PRIORITY + #error If configUSE_TIMERS is set to 1 then configTIMER_TASK_PRIORITY must also be defined. + #endif /* configTIMER_TASK_PRIORITY */ + + #ifndef configTIMER_QUEUE_LENGTH + #error If configUSE_TIMERS is set to 1 then configTIMER_QUEUE_LENGTH must also be defined. + #endif /* configTIMER_QUEUE_LENGTH */ + + #ifndef configTIMER_TASK_STACK_DEPTH + #error If configUSE_TIMERS is set to 1 then configTIMER_TASK_STACK_DEPTH must also be defined. + #endif /* configTIMER_TASK_STACK_DEPTH */ + +#endif /* configUSE_TIMERS */ + +#ifndef portSET_INTERRUPT_MASK_FROM_ISR + #define portSET_INTERRUPT_MASK_FROM_ISR() 0 +#endif + +#ifndef portCLEAR_INTERRUPT_MASK_FROM_ISR + #define portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedStatusValue ) ( void ) uxSavedStatusValue +#endif + +#ifndef portCLEAN_UP_TCB + #define portCLEAN_UP_TCB( pxTCB ) ( void ) pxTCB +#endif + +#ifndef portPRE_TASK_DELETE_HOOK + #define portPRE_TASK_DELETE_HOOK( pvTaskToDelete, pxYieldPending ) +#endif + +#ifndef portSETUP_TCB + #define portSETUP_TCB( pxTCB ) ( void ) pxTCB +#endif + +#ifndef configQUEUE_REGISTRY_SIZE + #define configQUEUE_REGISTRY_SIZE 0U +#endif + +#if ( configQUEUE_REGISTRY_SIZE < 1 ) + #define vQueueAddToRegistry( xQueue, pcName ) + #define vQueueUnregisterQueue( xQueue ) + #define pcQueueGetName( xQueue ) +#endif + +#ifndef portPOINTER_SIZE_TYPE + #define portPOINTER_SIZE_TYPE uint32_t +#endif + +/* Remove any unused trace macros. */ +#ifndef traceSTART + +/* Used to perform any necessary initialisation - for example, open a file + * into which trace is to be written. */ + #define traceSTART() +#endif + +#ifndef traceEND + +/* Use to close a trace, for example close a file into which trace has been + * written. */ + #define traceEND() +#endif + +#ifndef traceTASK_SWITCHED_IN + +/* Called after a task has been selected to run. pxCurrentTCB holds a pointer + * to the task control block of the selected task. */ + #define traceTASK_SWITCHED_IN() +#endif + +#ifndef traceINCREASE_TICK_COUNT + +/* Called before stepping the tick count after waking from tickless idle + * sleep. */ + #define traceINCREASE_TICK_COUNT( x ) +#endif + +#ifndef traceLOW_POWER_IDLE_BEGIN + /* Called immediately before entering tickless idle. */ + #define traceLOW_POWER_IDLE_BEGIN() +#endif + +#ifndef traceLOW_POWER_IDLE_END + /* Called when returning to the Idle task after a tickless idle. */ + #define traceLOW_POWER_IDLE_END() +#endif + +#ifndef traceTASK_SWITCHED_OUT + +/* Called before a task has been selected to run. pxCurrentTCB holds a pointer + * to the task control block of the task being switched out. */ + #define traceTASK_SWITCHED_OUT() +#endif + +#ifndef traceTASK_PRIORITY_INHERIT + +/* Called when a task attempts to take a mutex that is already held by a + * lower priority task. pxTCBOfMutexHolder is a pointer to the TCB of the task + * that holds the mutex. uxInheritedPriority is the priority the mutex holder + * will inherit (the priority of the task that is attempting to obtain the + * muted. */ + #define traceTASK_PRIORITY_INHERIT( pxTCBOfMutexHolder, uxInheritedPriority ) +#endif + +#ifndef traceTASK_PRIORITY_DISINHERIT + +/* Called when a task releases a mutex, the holding of which had resulted in + * the task inheriting the priority of a higher priority task. + * pxTCBOfMutexHolder is a pointer to the TCB of the task that is releasing the + * mutex. uxOriginalPriority is the task's configured (base) priority. */ + #define traceTASK_PRIORITY_DISINHERIT( pxTCBOfMutexHolder, uxOriginalPriority ) +#endif + +#ifndef traceBLOCKING_ON_QUEUE_RECEIVE + +/* Task is about to block because it cannot read from a + * queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore + * upon which the read was attempted. pxCurrentTCB points to the TCB of the + * task that attempted the read. */ + #define traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ) +#endif + +#ifndef traceBLOCKING_ON_QUEUE_PEEK + +/* Task is about to block because it cannot read from a + * queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore + * upon which the read was attempted. pxCurrentTCB points to the TCB of the + * task that attempted the read. */ + #define traceBLOCKING_ON_QUEUE_PEEK( pxQueue ) +#endif + +#ifndef traceBLOCKING_ON_QUEUE_SEND + +/* Task is about to block because it cannot write to a + * queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore + * upon which the write was attempted. pxCurrentTCB points to the TCB of the + * task that attempted the write. */ + #define traceBLOCKING_ON_QUEUE_SEND( pxQueue ) +#endif + +#ifndef configCHECK_FOR_STACK_OVERFLOW + #define configCHECK_FOR_STACK_OVERFLOW 0 +#endif + +#ifndef configRECORD_STACK_HIGH_ADDRESS + #define configRECORD_STACK_HIGH_ADDRESS 0 +#endif + +#ifndef configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H + #define configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H 0 +#endif + +/* The following event macros are embedded in the kernel API calls. */ + +#ifndef traceMOVED_TASK_TO_READY_STATE + #define traceMOVED_TASK_TO_READY_STATE( pxTCB ) +#endif + +#ifndef tracePOST_MOVED_TASK_TO_READY_STATE + #define tracePOST_MOVED_TASK_TO_READY_STATE( pxTCB ) +#endif + +#ifndef traceQUEUE_CREATE + #define traceQUEUE_CREATE( pxNewQueue ) +#endif + +#ifndef traceQUEUE_CREATE_FAILED + #define traceQUEUE_CREATE_FAILED( ucQueueType ) +#endif + +#ifndef traceCREATE_MUTEX + #define traceCREATE_MUTEX( pxNewQueue ) +#endif + +#ifndef traceCREATE_MUTEX_FAILED + #define traceCREATE_MUTEX_FAILED() +#endif + +#ifndef traceGIVE_MUTEX_RECURSIVE + #define traceGIVE_MUTEX_RECURSIVE( pxMutex ) +#endif + +#ifndef traceGIVE_MUTEX_RECURSIVE_FAILED + #define traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex ) +#endif + +#ifndef traceTAKE_MUTEX_RECURSIVE + #define traceTAKE_MUTEX_RECURSIVE( pxMutex ) +#endif + +#ifndef traceTAKE_MUTEX_RECURSIVE_FAILED + #define traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex ) +#endif + +#ifndef traceCREATE_COUNTING_SEMAPHORE + #define traceCREATE_COUNTING_SEMAPHORE() +#endif + +#ifndef traceCREATE_COUNTING_SEMAPHORE_FAILED + #define traceCREATE_COUNTING_SEMAPHORE_FAILED() +#endif + +#ifndef traceQUEUE_SET_SEND + #define traceQUEUE_SET_SEND traceQUEUE_SEND +#endif + +#ifndef traceQUEUE_SEND + #define traceQUEUE_SEND( pxQueue ) +#endif + +#ifndef traceQUEUE_SEND_FAILED + #define traceQUEUE_SEND_FAILED( pxQueue ) +#endif + +#ifndef traceQUEUE_RECEIVE + #define traceQUEUE_RECEIVE( pxQueue ) +#endif + +#ifndef traceQUEUE_PEEK + #define traceQUEUE_PEEK( pxQueue ) +#endif + +#ifndef traceQUEUE_PEEK_FAILED + #define traceQUEUE_PEEK_FAILED( pxQueue ) +#endif + +#ifndef traceQUEUE_PEEK_FROM_ISR + #define traceQUEUE_PEEK_FROM_ISR( pxQueue ) +#endif + +#ifndef traceQUEUE_RECEIVE_FAILED + #define traceQUEUE_RECEIVE_FAILED( pxQueue ) +#endif + +#ifndef traceQUEUE_SEND_FROM_ISR + #define traceQUEUE_SEND_FROM_ISR( pxQueue ) +#endif + +#ifndef traceQUEUE_SEND_FROM_ISR_FAILED + #define traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ) +#endif + +#ifndef traceQUEUE_RECEIVE_FROM_ISR + #define traceQUEUE_RECEIVE_FROM_ISR( pxQueue ) +#endif + +#ifndef traceQUEUE_RECEIVE_FROM_ISR_FAILED + #define traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue ) +#endif + +#ifndef traceQUEUE_PEEK_FROM_ISR_FAILED + #define traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue ) +#endif + +#ifndef traceQUEUE_DELETE + #define traceQUEUE_DELETE( pxQueue ) +#endif + +#ifndef traceTASK_CREATE + #define traceTASK_CREATE( pxNewTCB ) +#endif + +#ifndef traceTASK_CREATE_FAILED + #define traceTASK_CREATE_FAILED() +#endif + +#ifndef traceTASK_DELETE + #define traceTASK_DELETE( pxTaskToDelete ) +#endif + +#ifndef traceTASK_DELAY_UNTIL + #define traceTASK_DELAY_UNTIL( x ) +#endif + +#ifndef traceTASK_DELAY + #define traceTASK_DELAY() +#endif + +#ifndef traceTASK_PRIORITY_SET + #define traceTASK_PRIORITY_SET( pxTask, uxNewPriority ) +#endif + +#ifndef traceTASK_SUSPEND + #define traceTASK_SUSPEND( pxTaskToSuspend ) +#endif + +#ifndef traceTASK_RESUME + #define traceTASK_RESUME( pxTaskToResume ) +#endif + +#ifndef traceTASK_RESUME_FROM_ISR + #define traceTASK_RESUME_FROM_ISR( pxTaskToResume ) +#endif + +#ifndef traceTASK_INCREMENT_TICK + #define traceTASK_INCREMENT_TICK( xTickCount ) +#endif + +#ifndef traceTIMER_CREATE + #define traceTIMER_CREATE( pxNewTimer ) +#endif + +#ifndef traceTIMER_CREATE_FAILED + #define traceTIMER_CREATE_FAILED() +#endif + +#ifndef traceTIMER_COMMAND_SEND + #define traceTIMER_COMMAND_SEND( xTimer, xMessageID, xMessageValueValue, xReturn ) +#endif + +#ifndef traceTIMER_EXPIRED + #define traceTIMER_EXPIRED( pxTimer ) +#endif + +#ifndef traceTIMER_COMMAND_RECEIVED + #define traceTIMER_COMMAND_RECEIVED( pxTimer, xMessageID, xMessageValue ) +#endif + +#ifndef traceMALLOC + #define traceMALLOC( pvAddress, uiSize ) +#endif + +#ifndef traceFREE + #define traceFREE( pvAddress, uiSize ) +#endif + +#ifndef traceEVENT_GROUP_CREATE + #define traceEVENT_GROUP_CREATE( xEventGroup ) +#endif + +#ifndef traceEVENT_GROUP_CREATE_FAILED + #define traceEVENT_GROUP_CREATE_FAILED() +#endif + +#ifndef traceEVENT_GROUP_SYNC_BLOCK + #define traceEVENT_GROUP_SYNC_BLOCK( xEventGroup, uxBitsToSet, uxBitsToWaitFor ) +#endif + +#ifndef traceEVENT_GROUP_SYNC_END + #define traceEVENT_GROUP_SYNC_END( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTimeoutOccurred ) ( void ) xTimeoutOccurred +#endif + +#ifndef traceEVENT_GROUP_WAIT_BITS_BLOCK + #define traceEVENT_GROUP_WAIT_BITS_BLOCK( xEventGroup, uxBitsToWaitFor ) +#endif + +#ifndef traceEVENT_GROUP_WAIT_BITS_END + #define traceEVENT_GROUP_WAIT_BITS_END( xEventGroup, uxBitsToWaitFor, xTimeoutOccurred ) ( void ) xTimeoutOccurred +#endif + +#ifndef traceEVENT_GROUP_CLEAR_BITS + #define traceEVENT_GROUP_CLEAR_BITS( xEventGroup, uxBitsToClear ) +#endif + +#ifndef traceEVENT_GROUP_CLEAR_BITS_FROM_ISR + #define traceEVENT_GROUP_CLEAR_BITS_FROM_ISR( xEventGroup, uxBitsToClear ) +#endif + +#ifndef traceEVENT_GROUP_SET_BITS + #define traceEVENT_GROUP_SET_BITS( xEventGroup, uxBitsToSet ) +#endif + +#ifndef traceEVENT_GROUP_SET_BITS_FROM_ISR + #define traceEVENT_GROUP_SET_BITS_FROM_ISR( xEventGroup, uxBitsToSet ) +#endif + +#ifndef traceEVENT_GROUP_DELETE + #define traceEVENT_GROUP_DELETE( xEventGroup ) +#endif + +#ifndef tracePEND_FUNC_CALL + #define tracePEND_FUNC_CALL( xFunctionToPend, pvParameter1, ulParameter2, ret ) +#endif + +#ifndef tracePEND_FUNC_CALL_FROM_ISR + #define tracePEND_FUNC_CALL_FROM_ISR( xFunctionToPend, pvParameter1, ulParameter2, ret ) +#endif + +#ifndef traceQUEUE_REGISTRY_ADD + #define traceQUEUE_REGISTRY_ADD( xQueue, pcQueueName ) +#endif + +#ifndef traceTASK_NOTIFY_TAKE_BLOCK + #define traceTASK_NOTIFY_TAKE_BLOCK( uxIndexToWait ) +#endif + +#ifndef traceTASK_NOTIFY_TAKE + #define traceTASK_NOTIFY_TAKE( uxIndexToWait ) +#endif + +#ifndef traceTASK_NOTIFY_WAIT_BLOCK + #define traceTASK_NOTIFY_WAIT_BLOCK( uxIndexToWait ) +#endif + +#ifndef traceTASK_NOTIFY_WAIT + #define traceTASK_NOTIFY_WAIT( uxIndexToWait ) +#endif + +#ifndef traceTASK_NOTIFY + #define traceTASK_NOTIFY( uxIndexToNotify ) +#endif + +#ifndef traceTASK_NOTIFY_FROM_ISR + #define traceTASK_NOTIFY_FROM_ISR( uxIndexToNotify ) +#endif + +#ifndef traceTASK_NOTIFY_GIVE_FROM_ISR + #define traceTASK_NOTIFY_GIVE_FROM_ISR( uxIndexToNotify ) +#endif + +#ifndef traceSTREAM_BUFFER_CREATE_FAILED + #define traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_CREATE_STATIC_FAILED + #define traceSTREAM_BUFFER_CREATE_STATIC_FAILED( xReturn, xIsMessageBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_CREATE + #define traceSTREAM_BUFFER_CREATE( pxStreamBuffer, xIsMessageBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_DELETE + #define traceSTREAM_BUFFER_DELETE( xStreamBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_RESET + #define traceSTREAM_BUFFER_RESET( xStreamBuffer ) +#endif + +#ifndef traceBLOCKING_ON_STREAM_BUFFER_SEND + #define traceBLOCKING_ON_STREAM_BUFFER_SEND( xStreamBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_SEND + #define traceSTREAM_BUFFER_SEND( xStreamBuffer, xBytesSent ) +#endif + +#ifndef traceSTREAM_BUFFER_SEND_FAILED + #define traceSTREAM_BUFFER_SEND_FAILED( xStreamBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_SEND_FROM_ISR + #define traceSTREAM_BUFFER_SEND_FROM_ISR( xStreamBuffer, xBytesSent ) +#endif + +#ifndef traceBLOCKING_ON_STREAM_BUFFER_RECEIVE + #define traceBLOCKING_ON_STREAM_BUFFER_RECEIVE( xStreamBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_RECEIVE + #define traceSTREAM_BUFFER_RECEIVE( xStreamBuffer, xReceivedLength ) +#endif + +#ifndef traceSTREAM_BUFFER_RECEIVE_FAILED + #define traceSTREAM_BUFFER_RECEIVE_FAILED( xStreamBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_RECEIVE_FROM_ISR + #define traceSTREAM_BUFFER_RECEIVE_FROM_ISR( xStreamBuffer, xReceivedLength ) +#endif + +#ifndef configGENERATE_RUN_TIME_STATS + #define configGENERATE_RUN_TIME_STATS 0 +#endif + +#if ( configGENERATE_RUN_TIME_STATS == 1 ) + + #ifndef portCONFIGURE_TIMER_FOR_RUN_TIME_STATS + #error If configGENERATE_RUN_TIME_STATS is defined then portCONFIGURE_TIMER_FOR_RUN_TIME_STATS must also be defined. portCONFIGURE_TIMER_FOR_RUN_TIME_STATS should call a port layer function to setup a peripheral timer/counter that can then be used as the run time counter time base. + #endif /* portCONFIGURE_TIMER_FOR_RUN_TIME_STATS */ + + #ifndef portGET_RUN_TIME_COUNTER_VALUE + #ifndef portALT_GET_RUN_TIME_COUNTER_VALUE + #error If configGENERATE_RUN_TIME_STATS is defined then either portGET_RUN_TIME_COUNTER_VALUE or portALT_GET_RUN_TIME_COUNTER_VALUE must also be defined. See the examples provided and the FreeRTOS web site for more information. + #endif /* portALT_GET_RUN_TIME_COUNTER_VALUE */ + #endif /* portGET_RUN_TIME_COUNTER_VALUE */ + +#endif /* configGENERATE_RUN_TIME_STATS */ + +#ifndef portCONFIGURE_TIMER_FOR_RUN_TIME_STATS + #define portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() +#endif + +#ifndef configUSE_MALLOC_FAILED_HOOK + #define configUSE_MALLOC_FAILED_HOOK 0 +#endif + +#ifndef portPRIVILEGE_BIT + #define portPRIVILEGE_BIT ( ( UBaseType_t ) 0x00 ) +#endif + +#ifndef portYIELD_WITHIN_API + #define portYIELD_WITHIN_API portYIELD +#endif + +#ifndef portSUPPRESS_TICKS_AND_SLEEP + #define portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ) +#endif + +#ifndef configEXPECTED_IDLE_TIME_BEFORE_SLEEP + #define configEXPECTED_IDLE_TIME_BEFORE_SLEEP 2 +#endif + +#if configEXPECTED_IDLE_TIME_BEFORE_SLEEP < 2 + #error configEXPECTED_IDLE_TIME_BEFORE_SLEEP must not be less than 2 +#endif + +#ifndef configUSE_TICKLESS_IDLE + #define configUSE_TICKLESS_IDLE 0 +#endif + +#ifndef configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING + #define configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING( x ) +#endif + +#ifndef configPRE_SLEEP_PROCESSING + #define configPRE_SLEEP_PROCESSING( x ) +#endif + +#ifndef configPOST_SLEEP_PROCESSING + #define configPOST_SLEEP_PROCESSING( x ) +#endif + +#ifndef configUSE_QUEUE_SETS + #define configUSE_QUEUE_SETS 0 +#endif + +#ifndef portTASK_USES_FLOATING_POINT + #define portTASK_USES_FLOATING_POINT() +#endif + +#ifndef portALLOCATE_SECURE_CONTEXT + #define portALLOCATE_SECURE_CONTEXT( ulSecureStackSize ) +#endif + +#ifndef portDONT_DISCARD + #define portDONT_DISCARD +#endif + +#ifndef configUSE_TIME_SLICING + #define configUSE_TIME_SLICING 1 +#endif + +#ifndef configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS + #define configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS 0 +#endif + +#ifndef configUSE_STATS_FORMATTING_FUNCTIONS + #define configUSE_STATS_FORMATTING_FUNCTIONS 0 +#endif + +#ifndef portASSERT_IF_INTERRUPT_PRIORITY_INVALID + #define portASSERT_IF_INTERRUPT_PRIORITY_INVALID() +#endif + +#ifndef configUSE_TRACE_FACILITY + #define configUSE_TRACE_FACILITY 0 +#endif + +#ifndef mtCOVERAGE_TEST_MARKER + #define mtCOVERAGE_TEST_MARKER() +#endif + +#ifndef mtCOVERAGE_TEST_DELAY + #define mtCOVERAGE_TEST_DELAY() +#endif + +#ifndef portASSERT_IF_IN_ISR + #define portASSERT_IF_IN_ISR() +#endif + +#ifndef configUSE_PORT_OPTIMISED_TASK_SELECTION + #define configUSE_PORT_OPTIMISED_TASK_SELECTION 0 +#endif + +#ifndef configAPPLICATION_ALLOCATED_HEAP + #define configAPPLICATION_ALLOCATED_HEAP 0 +#endif + +#ifndef configUSE_TASK_NOTIFICATIONS + #define configUSE_TASK_NOTIFICATIONS 1 +#endif + +#ifndef configTASK_NOTIFICATION_ARRAY_ENTRIES + #define configTASK_NOTIFICATION_ARRAY_ENTRIES 1 +#endif + +#if configTASK_NOTIFICATION_ARRAY_ENTRIES < 1 + #error configTASK_NOTIFICATION_ARRAY_ENTRIES must be at least 1 +#endif + +#ifndef configUSE_POSIX_ERRNO + #define configUSE_POSIX_ERRNO 0 +#endif + +#ifndef portTICK_TYPE_IS_ATOMIC + #define portTICK_TYPE_IS_ATOMIC 0 +#endif + +#ifndef configSUPPORT_STATIC_ALLOCATION + /* Defaults to 0 for backward compatibility. */ + #define configSUPPORT_STATIC_ALLOCATION 0 +#endif + +#ifndef configSUPPORT_DYNAMIC_ALLOCATION + /* Defaults to 1 for backward compatibility. */ + #define configSUPPORT_DYNAMIC_ALLOCATION 1 +#endif + +#ifndef configSTACK_DEPTH_TYPE + +/* Defaults to uint16_t for backward compatibility, but can be overridden + * in FreeRTOSConfig.h if uint16_t is too restrictive. */ + #define configSTACK_DEPTH_TYPE uint16_t +#endif + +#ifndef configMESSAGE_BUFFER_LENGTH_TYPE + +/* Defaults to size_t for backward compatibility, but can be overridden + * in FreeRTOSConfig.h if lengths will always be less than the number of bytes + * in a size_t. */ + #define configMESSAGE_BUFFER_LENGTH_TYPE size_t +#endif + +/* Sanity check the configuration. */ +#if ( configUSE_TICKLESS_IDLE != 0 ) + #if ( INCLUDE_vTaskSuspend != 1 ) + #error INCLUDE_vTaskSuspend must be set to 1 if configUSE_TICKLESS_IDLE is not set to 0 + #endif /* INCLUDE_vTaskSuspend */ +#endif /* configUSE_TICKLESS_IDLE */ + +#if ( ( configSUPPORT_STATIC_ALLOCATION == 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) ) + #error configSUPPORT_STATIC_ALLOCATION and configSUPPORT_DYNAMIC_ALLOCATION cannot both be 0, but can both be 1. +#endif + +#if ( ( configUSE_RECURSIVE_MUTEXES == 1 ) && ( configUSE_MUTEXES != 1 ) ) + #error configUSE_MUTEXES must be set to 1 to use recursive mutexes +#endif + +#ifndef configINITIAL_TICK_COUNT + #define configINITIAL_TICK_COUNT 0 +#endif + +#if ( portTICK_TYPE_IS_ATOMIC == 0 ) + +/* Either variables of tick type cannot be read atomically, or + * portTICK_TYPE_IS_ATOMIC was not set - map the critical sections used when + * the tick count is returned to the standard critical section macros. */ + #define portTICK_TYPE_ENTER_CRITICAL() portENTER_CRITICAL() + #define portTICK_TYPE_EXIT_CRITICAL() portEXIT_CRITICAL() + #define portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR() portSET_INTERRUPT_MASK_FROM_ISR() + #define portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( x ) portCLEAR_INTERRUPT_MASK_FROM_ISR( ( x ) ) +#else + +/* The tick type can be read atomically, so critical sections used when the + * tick count is returned can be defined away. */ + #define portTICK_TYPE_ENTER_CRITICAL() + #define portTICK_TYPE_EXIT_CRITICAL() + #define portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR() 0 + #define portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( x ) ( void ) x +#endif /* if ( portTICK_TYPE_IS_ATOMIC == 0 ) */ + +/* Definitions to allow backward compatibility with FreeRTOS versions prior to + * V8 if desired. */ +#ifndef configENABLE_BACKWARD_COMPATIBILITY + #define configENABLE_BACKWARD_COMPATIBILITY 1 +#endif + +#ifndef configPRINTF + +/* configPRINTF() was not defined, so define it away to nothing. To use + * configPRINTF() then define it as follows (where MyPrintFunction() is + * provided by the application writer): + * + * void MyPrintFunction(const char *pcFormat, ... ); + #define configPRINTF( X ) MyPrintFunction X + * + * Then call like a standard printf() function, but placing brackets around + * all parameters so they are passed as a single parameter. For example: + * configPRINTF( ("Value = %d", MyVariable) ); */ + #define configPRINTF( X ) +#endif + +#ifndef configMAX + +/* The application writer has not provided their own MAX macro, so define + * the following generic implementation. */ + #define configMAX( a, b ) ( ( ( a ) > ( b ) ) ? ( a ) : ( b ) ) +#endif + +#ifndef configMIN + +/* The application writer has not provided their own MAX macro, so define + * the following generic implementation. */ + #define configMIN( a, b ) ( ( ( a ) < ( b ) ) ? ( a ) : ( b ) ) +#endif + +#if configENABLE_BACKWARD_COMPATIBILITY == 1 + #define eTaskStateGet eTaskGetState + #define portTickType TickType_t + #define xTaskHandle TaskHandle_t + #define xQueueHandle QueueHandle_t + #define xSemaphoreHandle SemaphoreHandle_t + #define xQueueSetHandle QueueSetHandle_t + #define xQueueSetMemberHandle QueueSetMemberHandle_t + #define xTimeOutType TimeOut_t + #define xMemoryRegion MemoryRegion_t + #define xTaskParameters TaskParameters_t + #define xTaskStatusType TaskStatus_t + #define xTimerHandle TimerHandle_t + #define xCoRoutineHandle CoRoutineHandle_t + #define pdTASK_HOOK_CODE TaskHookFunction_t + #define portTICK_RATE_MS portTICK_PERIOD_MS + #define pcTaskGetTaskName pcTaskGetName + #define pcTimerGetTimerName pcTimerGetName + #define pcQueueGetQueueName pcQueueGetName + #define vTaskGetTaskInfo vTaskGetInfo + #define xTaskGetIdleRunTimeCounter ulTaskGetIdleRunTimeCounter + +/* Backward compatibility within the scheduler code only - these definitions + * are not really required but are included for completeness. */ + #define tmrTIMER_CALLBACK TimerCallbackFunction_t + #define pdTASK_CODE TaskFunction_t + #define xListItem ListItem_t + #define xList List_t + +/* For libraries that break the list data hiding, and access list structure + * members directly (which is not supposed to be done). */ + #define pxContainer pvContainer +#endif /* configENABLE_BACKWARD_COMPATIBILITY */ + +#if ( configUSE_ALTERNATIVE_API != 0 ) + #error The alternative API was deprecated some time ago, and was removed in FreeRTOS V9.0 0 +#endif + +/* Set configUSE_TASK_FPU_SUPPORT to 0 to omit floating point support even + * if floating point hardware is otherwise supported by the FreeRTOS port in use. + * This constant is not supported by all FreeRTOS ports that include floating + * point support. */ +#ifndef configUSE_TASK_FPU_SUPPORT + #define configUSE_TASK_FPU_SUPPORT 1 +#endif + +/* Set configENABLE_MPU to 1 to enable MPU support and 0 to disable it. This is + * currently used in ARMv8M ports. */ +#ifndef configENABLE_MPU + #define configENABLE_MPU 0 +#endif + +/* Set configENABLE_FPU to 1 to enable FPU support and 0 to disable it. This is + * currently used in ARMv8M ports. */ +#ifndef configENABLE_FPU + #define configENABLE_FPU 1 +#endif + +/* Set configENABLE_TRUSTZONE to 1 enable TrustZone support and 0 to disable it. + * This is currently used in ARMv8M ports. */ +#ifndef configENABLE_TRUSTZONE + #define configENABLE_TRUSTZONE 1 +#endif + +/* Set configRUN_FREERTOS_SECURE_ONLY to 1 to run the FreeRTOS ARMv8M port on + * the Secure Side only. */ +#ifndef configRUN_FREERTOS_SECURE_ONLY + #define configRUN_FREERTOS_SECURE_ONLY 0 +#endif + +/* Sometimes the FreeRTOSConfig.h settings only allow a task to be created using + * dynamically allocated RAM, in which case when any task is deleted it is known + * that both the task's stack and TCB need to be freed. Sometimes the + * FreeRTOSConfig.h settings only allow a task to be created using statically + * allocated RAM, in which case when any task is deleted it is known that neither + * the task's stack or TCB should be freed. Sometimes the FreeRTOSConfig.h + * settings allow a task to be created using either statically or dynamically + * allocated RAM, in which case a member of the TCB is used to record whether the + * stack and/or TCB were allocated statically or dynamically, so when a task is + * deleted the RAM that was allocated dynamically is freed again and no attempt is + * made to free the RAM that was allocated statically. + * tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE is only true if it is possible for a + * task to be created using either statically or dynamically allocated RAM. Note + * that if portUSING_MPU_WRAPPERS is 1 then a protected task can be created with + * a statically allocated stack and a dynamically allocated TCB. + * + * The following table lists various combinations of portUSING_MPU_WRAPPERS, + * configSUPPORT_DYNAMIC_ALLOCATION and configSUPPORT_STATIC_ALLOCATION and + * when it is possible to have both static and dynamic allocation: + * +-----+---------+--------+-----------------------------+-----------------------------------+------------------+-----------+ + * | MPU | Dynamic | Static | Available Functions | Possible Allocations | Both Dynamic and | Need Free | + * | | | | | | Static Possible | | + * +-----+---------+--------+-----------------------------+-----------------------------------+------------------+-----------+ + * | 0 | 0 | 1 | xTaskCreateStatic | TCB - Static, Stack - Static | No | No | + * +-----|---------|--------|-----------------------------|-----------------------------------|------------------|-----------| + * | 0 | 1 | 0 | xTaskCreate | TCB - Dynamic, Stack - Dynamic | No | Yes | + * +-----|---------|--------|-----------------------------|-----------------------------------|------------------|-----------| + * | 0 | 1 | 1 | xTaskCreate, | 1. TCB - Dynamic, Stack - Dynamic | Yes | Yes | + * | | | | xTaskCreateStatic | 2. TCB - Static, Stack - Static | | | + * +-----|---------|--------|-----------------------------|-----------------------------------|------------------|-----------| + * | 1 | 0 | 1 | xTaskCreateStatic, | TCB - Static, Stack - Static | No | No | + * | | | | xTaskCreateRestrictedStatic | | | | + * +-----|---------|--------|-----------------------------|-----------------------------------|------------------|-----------| + * | 1 | 1 | 0 | xTaskCreate, | 1. TCB - Dynamic, Stack - Dynamic | Yes | Yes | + * | | | | xTaskCreateRestricted | 2. TCB - Dynamic, Stack - Static | | | + * +-----|---------|--------|-----------------------------|-----------------------------------|------------------|-----------| + * | 1 | 1 | 1 | xTaskCreate, | 1. TCB - Dynamic, Stack - Dynamic | Yes | Yes | + * | | | | xTaskCreateStatic, | 2. TCB - Dynamic, Stack - Static | | | + * | | | | xTaskCreateRestricted, | 3. TCB - Static, Stack - Static | | | + * | | | | xTaskCreateRestrictedStatic | | | | + * +-----+---------+--------+-----------------------------+-----------------------------------+------------------+-----------+ + */ +#define tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE \ + ( ( ( portUSING_MPU_WRAPPERS == 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) || \ + ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) ) + +/* + * In line with software engineering best practice, FreeRTOS implements a strict + * data hiding policy, so the real structures used by FreeRTOS to maintain the + * state of tasks, queues, semaphores, etc. are not accessible to the application + * code. However, if the application writer wants to statically allocate such + * an object then the size of the object needs to be know. Dummy structures + * that are guaranteed to have the same size and alignment requirements of the + * real objects are used for this purpose. The dummy list and list item + * structures below are used for inclusion in such a dummy structure. + */ +struct xSTATIC_LIST_ITEM +{ + #if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy1; + #endif + TickType_t xDummy2; + void * pvDummy3[ 4 ]; + #if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy4; + #endif +}; +typedef struct xSTATIC_LIST_ITEM StaticListItem_t; + +/* See the comments above the struct xSTATIC_LIST_ITEM definition. */ +struct xSTATIC_MINI_LIST_ITEM +{ + #if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy1; + #endif + TickType_t xDummy2; + void * pvDummy3[ 2 ]; +}; +typedef struct xSTATIC_MINI_LIST_ITEM StaticMiniListItem_t; + +/* See the comments above the struct xSTATIC_LIST_ITEM definition. */ +typedef struct xSTATIC_LIST +{ + #if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy1; + #endif + UBaseType_t uxDummy2; + void * pvDummy3; + StaticMiniListItem_t xDummy4; + #if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy5; + #endif +} StaticList_t; + +/* + * In line with software engineering best practice, especially when supplying a + * library that is likely to change in future versions, FreeRTOS implements a + * strict data hiding policy. This means the Task structure used internally by + * FreeRTOS is not accessible to application code. However, if the application + * writer wants to statically allocate the memory required to create a task then + * the size of the task object needs to be know. The StaticTask_t structure + * below is provided for this purpose. Its sizes and alignment requirements are + * guaranteed to match those of the genuine structure, no matter which + * architecture is being used, and no matter how the values in FreeRTOSConfig.h + * are set. Its contents are somewhat obfuscated in the hope users will + * recognise that it would be unwise to make direct use of the structure members. + */ +typedef struct xSTATIC_TCB +{ + void * pxDummy1; + #if ( portUSING_MPU_WRAPPERS == 1 ) + xMPU_SETTINGS xDummy2; + #endif + StaticListItem_t xDummy3[ 2 ]; + UBaseType_t uxDummy5; + void * pxDummy6; + uint8_t ucDummy7[ configMAX_TASK_NAME_LEN ]; + #if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) ) + void * pxDummy8; + #endif + #if ( portCRITICAL_NESTING_IN_TCB == 1 ) + UBaseType_t uxDummy9; + #endif + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy10[ 2 ]; + #endif + #if ( configUSE_MUTEXES == 1 ) + UBaseType_t uxDummy12[ 2 ]; + #endif + #if ( configUSE_APPLICATION_TASK_TAG == 1 ) + void * pxDummy14; + #endif + #if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) + void * pvDummy15[ configNUM_THREAD_LOCAL_STORAGE_POINTERS ]; + #endif + #if ( configGENERATE_RUN_TIME_STATS == 1 ) + uint32_t ulDummy16; + #endif + #if ( configUSE_NEWLIB_REENTRANT == 1 ) + struct _reent xDummy17; + #endif + #if ( configUSE_TASK_NOTIFICATIONS == 1 ) + uint32_t ulDummy18[ configTASK_NOTIFICATION_ARRAY_ENTRIES ]; + uint8_t ucDummy19[ configTASK_NOTIFICATION_ARRAY_ENTRIES ]; + #endif + #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) + uint8_t uxDummy20; + #endif + + #if ( INCLUDE_xTaskAbortDelay == 1 ) + uint8_t ucDummy21; + #endif + #if ( configUSE_POSIX_ERRNO == 1 ) + int iDummy22; + #endif +} StaticTask_t; + +/* + * In line with software engineering best practice, especially when supplying a + * library that is likely to change in future versions, FreeRTOS implements a + * strict data hiding policy. This means the Queue structure used internally by + * FreeRTOS is not accessible to application code. However, if the application + * writer wants to statically allocate the memory required to create a queue + * then the size of the queue object needs to be know. The StaticQueue_t + * structure below is provided for this purpose. Its sizes and alignment + * requirements are guaranteed to match those of the genuine structure, no + * matter which architecture is being used, and no matter how the values in + * FreeRTOSConfig.h are set. Its contents are somewhat obfuscated in the hope + * users will recognise that it would be unwise to make direct use of the + * structure members. + */ +typedef struct xSTATIC_QUEUE +{ + void * pvDummy1[ 3 ]; + + union + { + void * pvDummy2; + UBaseType_t uxDummy2; + } u; + + StaticList_t xDummy3[ 2 ]; + UBaseType_t uxDummy4[ 3 ]; + uint8_t ucDummy5[ 2 ]; + + #if ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + uint8_t ucDummy6; + #endif + + #if ( configUSE_QUEUE_SETS == 1 ) + void * pvDummy7; + #endif + + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy8; + uint8_t ucDummy9; + #endif +} StaticQueue_t; +typedef StaticQueue_t StaticSemaphore_t; + +/* + * In line with software engineering best practice, especially when supplying a + * library that is likely to change in future versions, FreeRTOS implements a + * strict data hiding policy. This means the event group structure used + * internally by FreeRTOS is not accessible to application code. However, if + * the application writer wants to statically allocate the memory required to + * create an event group then the size of the event group object needs to be + * know. The StaticEventGroup_t structure below is provided for this purpose. + * Its sizes and alignment requirements are guaranteed to match those of the + * genuine structure, no matter which architecture is being used, and no matter + * how the values in FreeRTOSConfig.h are set. Its contents are somewhat + * obfuscated in the hope users will recognise that it would be unwise to make + * direct use of the structure members. + */ +typedef struct xSTATIC_EVENT_GROUP +{ + TickType_t xDummy1; + StaticList_t xDummy2; + + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy3; + #endif + + #if ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + uint8_t ucDummy4; + #endif +} StaticEventGroup_t; + +/* + * In line with software engineering best practice, especially when supplying a + * library that is likely to change in future versions, FreeRTOS implements a + * strict data hiding policy. This means the software timer structure used + * internally by FreeRTOS is not accessible to application code. However, if + * the application writer wants to statically allocate the memory required to + * create a software timer then the size of the queue object needs to be know. + * The StaticTimer_t structure below is provided for this purpose. Its sizes + * and alignment requirements are guaranteed to match those of the genuine + * structure, no matter which architecture is being used, and no matter how the + * values in FreeRTOSConfig.h are set. Its contents are somewhat obfuscated in + * the hope users will recognise that it would be unwise to make direct use of + * the structure members. + */ +typedef struct xSTATIC_TIMER +{ + void * pvDummy1; + StaticListItem_t xDummy2; + TickType_t xDummy3; + void * pvDummy5; + TaskFunction_t pvDummy6; + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy7; + #endif + uint8_t ucDummy8; +} StaticTimer_t; + +/* + * In line with software engineering best practice, especially when supplying a + * library that is likely to change in future versions, FreeRTOS implements a + * strict data hiding policy. This means the stream buffer structure used + * internally by FreeRTOS is not accessible to application code. However, if + * the application writer wants to statically allocate the memory required to + * create a stream buffer then the size of the stream buffer object needs to be + * know. The StaticStreamBuffer_t structure below is provided for this purpose. + * Its size and alignment requirements are guaranteed to match those of the + * genuine structure, no matter which architecture is being used, and no matter + * how the values in FreeRTOSConfig.h are set. Its contents are somewhat + * obfuscated in the hope users will recognise that it would be unwise to make + * direct use of the structure members. + */ +typedef struct xSTATIC_STREAM_BUFFER +{ + size_t uxDummy1[ 4 ]; + void * pvDummy2[ 3 ]; + uint8_t ucDummy3; + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy4; + #endif +} StaticStreamBuffer_t; + +/* Message buffers are built on stream buffers. */ +typedef StaticStreamBuffer_t StaticMessageBuffer_t; + +/* *INDENT-OFF* */ +#ifdef __cplusplus + } +#endif +/* *INDENT-ON* */ + +#endif /* INC_FREERTOS_H */ diff --git a/examples/stm32/freertos-kernel/include/StackMacros.h b/examples/stm32/freertos-kernel/include/StackMacros.h new file mode 100644 index 00000000..dde8136f --- /dev/null +++ b/examples/stm32/freertos-kernel/include/StackMacros.h @@ -0,0 +1,32 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + + +#ifndef _MSC_VER /* Visual Studio doesn't support #warning. */ + #warning The name of this file has changed to stack_macros.h. Please update your code accordingly. This source file (which has the original name) will be removed in future released. +#endif + +#include "stack_macros.h" diff --git a/examples/stm32/freertos-kernel/include/atomic.h b/examples/stm32/freertos-kernel/include/atomic.h new file mode 100644 index 00000000..cd1fd1b0 --- /dev/null +++ b/examples/stm32/freertos-kernel/include/atomic.h @@ -0,0 +1,417 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/** + * @file atomic.h + * @brief FreeRTOS atomic operation support. + * + * This file implements atomic functions by disabling interrupts globally. + * Implementations with architecture specific atomic instructions can be + * provided under each compiler directory. + */ + +#ifndef ATOMIC_H +#define ATOMIC_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h must appear in source files before include atomic.h" +#endif + +/* Standard includes. */ +#include + +/* *INDENT-OFF* */ +#ifdef __cplusplus + extern "C" { +#endif +/* *INDENT-ON* */ + +/* + * Port specific definitions -- entering/exiting critical section. + * Refer template -- ./lib/FreeRTOS/portable/Compiler/Arch/portmacro.h + * + * Every call to ATOMIC_EXIT_CRITICAL() must be closely paired with + * ATOMIC_ENTER_CRITICAL(). + * + */ +#if defined( portSET_INTERRUPT_MASK_FROM_ISR ) + +/* Nested interrupt scheme is supported in this port. */ + #define ATOMIC_ENTER_CRITICAL() \ + UBaseType_t uxCriticalSectionType = portSET_INTERRUPT_MASK_FROM_ISR() + + #define ATOMIC_EXIT_CRITICAL() \ + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxCriticalSectionType ) + +#else + +/* Nested interrupt scheme is NOT supported in this port. */ + #define ATOMIC_ENTER_CRITICAL() portENTER_CRITICAL() + #define ATOMIC_EXIT_CRITICAL() portEXIT_CRITICAL() + +#endif /* portSET_INTERRUPT_MASK_FROM_ISR() */ + +/* + * Port specific definition -- "always inline". + * Inline is compiler specific, and may not always get inlined depending on your + * optimization level. Also, inline is considered as performance optimization + * for atomic. Thus, if portFORCE_INLINE is not provided by portmacro.h, + * instead of resulting error, simply define it away. + */ +#ifndef portFORCE_INLINE + #define portFORCE_INLINE +#endif + +#define ATOMIC_COMPARE_AND_SWAP_SUCCESS 0x1U /**< Compare and swap succeeded, swapped. */ +#define ATOMIC_COMPARE_AND_SWAP_FAILURE 0x0U /**< Compare and swap failed, did not swap. */ + +/*----------------------------- Swap && CAS ------------------------------*/ + +/** + * Atomic compare-and-swap + * + * @brief Performs an atomic compare-and-swap operation on the specified values. + * + * @param[in, out] pulDestination Pointer to memory location from where value is + * to be loaded and checked. + * @param[in] ulExchange If condition meets, write this value to memory. + * @param[in] ulComparand Swap condition. + * + * @return Unsigned integer of value 1 or 0. 1 for swapped, 0 for not swapped. + * + * @note This function only swaps *pulDestination with ulExchange, if previous + * *pulDestination value equals ulComparand. + */ +static portFORCE_INLINE uint32_t Atomic_CompareAndSwap_u32( uint32_t volatile * pulDestination, + uint32_t ulExchange, + uint32_t ulComparand ) +{ + uint32_t ulReturnValue; + + ATOMIC_ENTER_CRITICAL(); + { + if( *pulDestination == ulComparand ) + { + *pulDestination = ulExchange; + ulReturnValue = ATOMIC_COMPARE_AND_SWAP_SUCCESS; + } + else + { + ulReturnValue = ATOMIC_COMPARE_AND_SWAP_FAILURE; + } + } + ATOMIC_EXIT_CRITICAL(); + + return ulReturnValue; +} +/*-----------------------------------------------------------*/ + +/** + * Atomic swap (pointers) + * + * @brief Atomically sets the address pointed to by *ppvDestination to the value + * of *pvExchange. + * + * @param[in, out] ppvDestination Pointer to memory location from where a pointer + * value is to be loaded and written back to. + * @param[in] pvExchange Pointer value to be written to *ppvDestination. + * + * @return The initial value of *ppvDestination. + */ +static portFORCE_INLINE void * Atomic_SwapPointers_p32( void * volatile * ppvDestination, + void * pvExchange ) +{ + void * pReturnValue; + + ATOMIC_ENTER_CRITICAL(); + { + pReturnValue = *ppvDestination; + *ppvDestination = pvExchange; + } + ATOMIC_EXIT_CRITICAL(); + + return pReturnValue; +} +/*-----------------------------------------------------------*/ + +/** + * Atomic compare-and-swap (pointers) + * + * @brief Performs an atomic compare-and-swap operation on the specified pointer + * values. + * + * @param[in, out] ppvDestination Pointer to memory location from where a pointer + * value is to be loaded and checked. + * @param[in] pvExchange If condition meets, write this value to memory. + * @param[in] pvComparand Swap condition. + * + * @return Unsigned integer of value 1 or 0. 1 for swapped, 0 for not swapped. + * + * @note This function only swaps *ppvDestination with pvExchange, if previous + * *ppvDestination value equals pvComparand. + */ +static portFORCE_INLINE uint32_t Atomic_CompareAndSwapPointers_p32( void * volatile * ppvDestination, + void * pvExchange, + void * pvComparand ) +{ + uint32_t ulReturnValue = ATOMIC_COMPARE_AND_SWAP_FAILURE; + + ATOMIC_ENTER_CRITICAL(); + { + if( *ppvDestination == pvComparand ) + { + *ppvDestination = pvExchange; + ulReturnValue = ATOMIC_COMPARE_AND_SWAP_SUCCESS; + } + } + ATOMIC_EXIT_CRITICAL(); + + return ulReturnValue; +} + + +/*----------------------------- Arithmetic ------------------------------*/ + +/** + * Atomic add + * + * @brief Atomically adds count to the value of the specified pointer points to. + * + * @param[in,out] pulAddend Pointer to memory location from where value is to be + * loaded and written back to. + * @param[in] ulCount Value to be added to *pulAddend. + * + * @return previous *pulAddend value. + */ +static portFORCE_INLINE uint32_t Atomic_Add_u32( uint32_t volatile * pulAddend, + uint32_t ulCount ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + { + ulCurrent = *pulAddend; + *pulAddend += ulCount; + } + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} +/*-----------------------------------------------------------*/ + +/** + * Atomic subtract + * + * @brief Atomically subtracts count from the value of the specified pointer + * pointers to. + * + * @param[in,out] pulAddend Pointer to memory location from where value is to be + * loaded and written back to. + * @param[in] ulCount Value to be subtract from *pulAddend. + * + * @return previous *pulAddend value. + */ +static portFORCE_INLINE uint32_t Atomic_Subtract_u32( uint32_t volatile * pulAddend, + uint32_t ulCount ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + { + ulCurrent = *pulAddend; + *pulAddend -= ulCount; + } + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} +/*-----------------------------------------------------------*/ + +/** + * Atomic increment + * + * @brief Atomically increments the value of the specified pointer points to. + * + * @param[in,out] pulAddend Pointer to memory location from where value is to be + * loaded and written back to. + * + * @return *pulAddend value before increment. + */ +static portFORCE_INLINE uint32_t Atomic_Increment_u32( uint32_t volatile * pulAddend ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + { + ulCurrent = *pulAddend; + *pulAddend += 1; + } + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} +/*-----------------------------------------------------------*/ + +/** + * Atomic decrement + * + * @brief Atomically decrements the value of the specified pointer points to + * + * @param[in,out] pulAddend Pointer to memory location from where value is to be + * loaded and written back to. + * + * @return *pulAddend value before decrement. + */ +static portFORCE_INLINE uint32_t Atomic_Decrement_u32( uint32_t volatile * pulAddend ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + { + ulCurrent = *pulAddend; + *pulAddend -= 1; + } + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} + +/*----------------------------- Bitwise Logical ------------------------------*/ + +/** + * Atomic OR + * + * @brief Performs an atomic OR operation on the specified values. + * + * @param [in, out] pulDestination Pointer to memory location from where value is + * to be loaded and written back to. + * @param [in] ulValue Value to be ORed with *pulDestination. + * + * @return The original value of *pulDestination. + */ +static portFORCE_INLINE uint32_t Atomic_OR_u32( uint32_t volatile * pulDestination, + uint32_t ulValue ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + { + ulCurrent = *pulDestination; + *pulDestination |= ulValue; + } + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} +/*-----------------------------------------------------------*/ + +/** + * Atomic AND + * + * @brief Performs an atomic AND operation on the specified values. + * + * @param [in, out] pulDestination Pointer to memory location from where value is + * to be loaded and written back to. + * @param [in] ulValue Value to be ANDed with *pulDestination. + * + * @return The original value of *pulDestination. + */ +static portFORCE_INLINE uint32_t Atomic_AND_u32( uint32_t volatile * pulDestination, + uint32_t ulValue ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + { + ulCurrent = *pulDestination; + *pulDestination &= ulValue; + } + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} +/*-----------------------------------------------------------*/ + +/** + * Atomic NAND + * + * @brief Performs an atomic NAND operation on the specified values. + * + * @param [in, out] pulDestination Pointer to memory location from where value is + * to be loaded and written back to. + * @param [in] ulValue Value to be NANDed with *pulDestination. + * + * @return The original value of *pulDestination. + */ +static portFORCE_INLINE uint32_t Atomic_NAND_u32( uint32_t volatile * pulDestination, + uint32_t ulValue ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + { + ulCurrent = *pulDestination; + *pulDestination = ~( ulCurrent & ulValue ); + } + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} +/*-----------------------------------------------------------*/ + +/** + * Atomic XOR + * + * @brief Performs an atomic XOR operation on the specified values. + * + * @param [in, out] pulDestination Pointer to memory location from where value is + * to be loaded and written back to. + * @param [in] ulValue Value to be XORed with *pulDestination. + * + * @return The original value of *pulDestination. + */ +static portFORCE_INLINE uint32_t Atomic_XOR_u32( uint32_t volatile * pulDestination, + uint32_t ulValue ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + { + ulCurrent = *pulDestination; + *pulDestination ^= ulValue; + } + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} + +/* *INDENT-OFF* */ +#ifdef __cplusplus + } +#endif +/* *INDENT-ON* */ + +#endif /* ATOMIC_H */ diff --git a/examples/stm32/freertos-kernel/include/croutine.h b/examples/stm32/freertos-kernel/include/croutine.h new file mode 100644 index 00000000..4e7b5340 --- /dev/null +++ b/examples/stm32/freertos-kernel/include/croutine.h @@ -0,0 +1,751 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#ifndef CO_ROUTINE_H +#define CO_ROUTINE_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h must appear in source files before include croutine.h" +#endif + +#include "list.h" + +/* *INDENT-OFF* */ +#ifdef __cplusplus + extern "C" { +#endif +/* *INDENT-ON* */ + +/* Used to hide the implementation of the co-routine control block. The + * control block structure however has to be included in the header due to + * the macro implementation of the co-routine functionality. */ +typedef void * CoRoutineHandle_t; + +/* Defines the prototype to which co-routine functions must conform. */ +typedef void (* crCOROUTINE_CODE)( CoRoutineHandle_t, + UBaseType_t ); + +typedef struct corCoRoutineControlBlock +{ + crCOROUTINE_CODE pxCoRoutineFunction; + ListItem_t xGenericListItem; /*< List item used to place the CRCB in ready and blocked queues. */ + ListItem_t xEventListItem; /*< List item used to place the CRCB in event lists. */ + UBaseType_t uxPriority; /*< The priority of the co-routine in relation to other co-routines. */ + UBaseType_t uxIndex; /*< Used to distinguish between co-routines when multiple co-routines use the same co-routine function. */ + uint16_t uxState; /*< Used internally by the co-routine implementation. */ +} CRCB_t; /* Co-routine control block. Note must be identical in size down to uxPriority with TCB_t. */ + +/** + * croutine. h + *
+ * 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 ); + +/* *INDENT-OFF* */ +#ifdef __cplusplus + } +#endif +/* *INDENT-ON* */ + +#endif /* CO_ROUTINE_H */ diff --git a/examples/stm32/freertos-kernel/include/deprecated_definitions.h b/examples/stm32/freertos-kernel/include/deprecated_definitions.h new file mode 100644 index 00000000..efa8a87a --- /dev/null +++ b/examples/stm32/freertos-kernel/include/deprecated_definitions.h @@ -0,0 +1,279 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#ifndef 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/examples/stm32/freertos-kernel/include/event_groups.h b/examples/stm32/freertos-kernel/include/event_groups.h new file mode 100644 index 00000000..70ba8d1b --- /dev/null +++ b/examples/stm32/freertos-kernel/include/event_groups.h @@ -0,0 +1,775 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#ifndef EVENT_GROUPS_H +#define EVENT_GROUPS_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h" must appear in source files before "include event_groups.h" +#endif + +/* FreeRTOS includes. */ +#include "timers.h" + +/* *INDENT-OFF* */ +#ifdef __cplusplus + extern "C" { +#endif +/* *INDENT-ON* */ + +/** + * An event group is a collection of bits to which an application can assign a + * meaning. For example, an application may create an event group to convey + * the status of various CAN bus related events in which bit 0 might mean "A CAN + * message has been received and is ready for processing", bit 1 might mean "The + * application has queued a message that is ready for sending onto the CAN + * network", and bit 2 might mean "It is time to send a SYNC message onto the + * CAN network" etc. A task can then test the bit values to see which events + * are active, and optionally enter the Blocked state to wait for a specified + * bit or a group of specified bits to be active. To continue the CAN bus + * example, a CAN controlling task can enter the Blocked state (and therefore + * not consume any processing time) until either bit 0, bit 1 or bit 2 are + * active, at which time the bit that was actually active would inform the task + * which action it had to take (process a received message, send a message, or + * send a SYNC). + * + * The event groups implementation contains intelligence to avoid race + * conditions that would otherwise occur were an application to use a simple + * variable for the same purpose. This is particularly important with respect + * to when a bit within an event group is to be cleared, and when bits have to + * be set and then tested atomically - as is the case where event groups are + * used to create a synchronisation point between multiple tasks (a + * 'rendezvous'). + * + * \defgroup EventGroup + */ + + + +/** + * event_groups.h + * + * Type by which event groups are referenced. For example, a call to + * xEventGroupCreate() returns an EventGroupHandle_t variable that can then + * be used as a parameter to other event group functions. + * + * \defgroup EventGroupHandle_t EventGroupHandle_t + * \ingroup EventGroup + */ +struct EventGroupDef_t; +typedef struct EventGroupDef_t * EventGroupHandle_t; + +/* + * The type that holds event bits always matches TickType_t - therefore the + * number of bits it holds is set by configUSE_16_BIT_TICKS (16 bits if set to 1, + * 32 bits if set to 0. + * + * \defgroup EventBits_t EventBits_t + * \ingroup EventGroup + */ +typedef TickType_t EventBits_t; + +/** + * event_groups.h + *
+ * 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 https://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 https://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 https://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 synchronisation was made by all
+ *      // three tasks, so there is no need to test the return value.
+ *   }
+ * }
+ *
+ * void vTask2( void *pvParameters )
+ * {
+ *   for( ;; )
+ *   {
+ *      // Perform task functionality here.
+ *
+ *      // Set bit 2 in the event flag to note this task has reached the
+ *      // synchronisation point.  The other two tasks will set the other two
+ *      // bits defined by ALL_SYNC_BITS.  All three tasks have reached the
+ *      // synchronisation point when all the ALL_SYNC_BITS are set.  Wait
+ *      // indefinitely for this to happen.
+ *      xEventGroupSync( xEventBits, TASK_2_BIT, ALL_SYNC_BITS, portMAX_DELAY );
+ *
+ *      // xEventGroupSync() was called with an indefinite block time, so
+ *      // this task will only reach here if the synchronisation was made by all
+ *      // three tasks, so there is no need to test the return value.
+ *  }
+ * }
+ *
+ * 
+ * \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 + +/* *INDENT-OFF* */ +#ifdef __cplusplus + } +#endif +/* *INDENT-ON* */ + +#endif /* EVENT_GROUPS_H */ diff --git a/examples/stm32/freertos-kernel/include/list.h b/examples/stm32/freertos-kernel/include/list.h new file mode 100644 index 00000000..d8a49884 --- /dev/null +++ b/examples/stm32/freertos-kernel/include/list.h @@ -0,0 +1,417 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* + * 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 LIST_H +#define LIST_H + +#ifndef INC_FREERTOS_H + #error "FreeRTOS.h must be included before list.h" +#endif + +/* + * The list structure members are modified from within interrupts, and therefore + * by rights should be declared volatile. However, they are only modified in a + * functionally atomic way (within critical sections of with the scheduler + * suspended) and are either passed by reference into a function or indexed via + * a volatile variable. Therefore, in all use cases tested so far, the volatile + * qualifier can be omitted in order to provide a moderate performance + * improvement without adversely affecting functional behaviour. The assembly + * instructions generated by the IAR, ARM and GCC compilers when the respective + * compiler's options were set for maximum optimisation has been inspected and + * deemed to be as intended. That said, as compiler technology advances, and + * especially if aggressive cross module optimisation is used (a use case that + * has not been exercised to any great extend) then it is feasible that the + * volatile qualifier will be needed for correct optimisation. It is expected + * that a compiler removing essential code because, without the volatile + * qualifier on the list structure members and with aggressive cross module + * optimisation, the compiler deemed the code unnecessary will result in + * complete and obvious failure of the scheduler. If this is ever experienced + * then the volatile qualifier can be inserted in the relevant places within the + * list structures by simply defining configLIST_VOLATILE to volatile in + * FreeRTOSConfig.h (as per the example at the bottom of this comment block). + * If configLIST_VOLATILE is not defined then the preprocessor directives below + * will simply #define configLIST_VOLATILE away completely. + * + * To use volatile list structure members then add the following line to + * FreeRTOSConfig.h (without the quotes): + * "#define configLIST_VOLATILE volatile" + */ +#ifndef configLIST_VOLATILE + #define configLIST_VOLATILE +#endif /* configSUPPORT_CROSS_MODULE_OPTIMISATION */ + +/* *INDENT-OFF* */ +#ifdef __cplusplus + extern "C" { +#endif +/* *INDENT-ON* */ + +/* Macros that can be used to place known values within the list structures, + * then check that the known values do not get corrupted during the execution of + * the application. These may catch the list data structures being overwritten in + * memory. They will not catch data errors caused by incorrect configuration or + * use of FreeRTOS.*/ +#if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 0 ) + /* Define the macros to do nothing. */ + #define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE + #define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE + #define listFIRST_LIST_INTEGRITY_CHECK_VALUE + #define listSECOND_LIST_INTEGRITY_CHECK_VALUE + #define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) + #define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) + #define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ) + #define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ) + #define listTEST_LIST_ITEM_INTEGRITY( pxItem ) + #define listTEST_LIST_INTEGRITY( pxList ) +#else /* if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 0 ) */ + /* Define macros that add new members into the list structures. */ + #define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE TickType_t xListItemIntegrityValue1; + #define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE TickType_t xListItemIntegrityValue2; + #define listFIRST_LIST_INTEGRITY_CHECK_VALUE TickType_t xListIntegrityValue1; + #define listSECOND_LIST_INTEGRITY_CHECK_VALUE TickType_t xListIntegrityValue2; + +/* Define macros that set the new structure members to known values. */ + #define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) ( pxItem )->xListItemIntegrityValue1 = pdINTEGRITY_CHECK_VALUE + #define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) ( pxItem )->xListItemIntegrityValue2 = pdINTEGRITY_CHECK_VALUE + #define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ) ( pxList )->xListIntegrityValue1 = pdINTEGRITY_CHECK_VALUE + #define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ) ( pxList )->xListIntegrityValue2 = pdINTEGRITY_CHECK_VALUE + +/* Define macros that will assert if one of the structure members does not + * contain its expected value. */ + #define listTEST_LIST_ITEM_INTEGRITY( pxItem ) configASSERT( ( ( pxItem )->xListItemIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxItem )->xListItemIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) ) + #define listTEST_LIST_INTEGRITY( pxList ) configASSERT( ( ( pxList )->xListIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxList )->xListIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) ) +#endif /* configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES */ + + +/* + * Definition of the only type of object that a list can contain. + */ +struct xLIST; +struct xLIST_ITEM +{ + listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + configLIST_VOLATILE TickType_t xItemValue; /*< The value being listed. In most cases this is used to sort the list in 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; + +/* *INDENT-OFF* */ +#ifdef __cplusplus + } +#endif +/* *INDENT-ON* */ + +#endif /* ifndef LIST_H */ diff --git a/examples/stm32/freertos-kernel/include/message_buffer.h b/examples/stm32/freertos-kernel/include/message_buffer.h new file mode 100644 index 00000000..a9d21ce6 --- /dev/null +++ b/examples/stm32/freertos-kernel/include/message_buffer.h @@ -0,0 +1,821 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + + +/* + * Message buffers build functionality on top of FreeRTOS stream buffers. + * Whereas stream buffers are used to send a continuous stream of data from one + * task or interrupt to another, message buffers are used to send variable + * length discrete messages from one task or interrupt to another. Their + * implementation is light weight, making them particularly suited for interrupt + * to task and core to core communication scenarios. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xMessageBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xMessageBufferRead()) inside a critical section and set the receive + * timeout to 0. + * + * Message buffers hold variable length messages. To enable that, when a + * message is written to the message buffer an additional sizeof( size_t ) bytes + * are also written to store the message's length (that happens internally, with + * the API function). sizeof( size_t ) is typically 4 bytes on a 32-bit + * architecture, so writing a 10 byte message to a message buffer on a 32-bit + * architecture will actually reduce the available space in the message buffer + * by 14 bytes (10 byte are used by the message, and 4 bytes to hold the length + * of the message). + */ + +#ifndef FREERTOS_MESSAGE_BUFFER_H +#define FREERTOS_MESSAGE_BUFFER_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h must appear in source files before include message_buffer.h" +#endif + +/* Message buffers are built onto of stream buffers. */ +#include "stream_buffer.h" + +/* *INDENT-OFF* */ +#if defined( __cplusplus ) + extern "C" { +#endif +/* *INDENT-ON* */ + +/** + * Type by which message buffers are referenced. For example, a call to + * xMessageBufferCreate() returns an MessageBufferHandle_t variable that can + * then be used as a parameter to xMessageBufferSend(), xMessageBufferReceive(), + * etc. + */ +typedef void * MessageBufferHandle_t; + +/*-----------------------------------------------------------*/ + +/** + * message_buffer.h + * + *
+ * 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 ) + +/* *INDENT-OFF* */ +#if defined( __cplusplus ) + } /* extern "C" */ +#endif +/* *INDENT-ON* */ + +#endif /* !defined( FREERTOS_MESSAGE_BUFFER_H ) */ diff --git a/examples/stm32/freertos-kernel/include/mpu_prototypes.h b/examples/stm32/freertos-kernel/include/mpu_prototypes.h new file mode 100644 index 00000000..61f885d6 --- /dev/null +++ b/examples/stm32/freertos-kernel/include/mpu_prototypes.h @@ -0,0 +1,257 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* + * When the MPU is used the standard (non MPU) API functions are mapped to + * equivalents that start "MPU_", the prototypes for which are defined in this + * header files. This will cause the application code to call the MPU_ version + * which wraps the non-MPU version with privilege promoting then demoting code, + * so the kernel code always runs will full privileges. + */ + + +#ifndef MPU_PROTOTYPES_H +#define MPU_PROTOTYPES_H + +/* MPU versions of tasks.h API functions. */ +BaseType_t MPU_xTaskCreate( TaskFunction_t pxTaskCode, + const char * const pcName, + const uint16_t usStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask ) FREERTOS_SYSTEM_CALL; +TaskHandle_t MPU_xTaskCreateStatic( TaskFunction_t pxTaskCode, + const char * const pcName, + const uint32_t ulStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + StackType_t * const puxStackBuffer, + StaticTask_t * const pxTaskBuffer ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskDelete( TaskHandle_t xTaskToDelete ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskDelay( const TickType_t xTicksToDelay ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskDelayUntil( TickType_t * const pxPreviousWakeTime, + const TickType_t xTimeIncrement ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskAbortDelay( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxTaskPriorityGet( const TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; +eTaskState MPU_eTaskGetState( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskGetInfo( TaskHandle_t xTask, + TaskStatus_t * pxTaskStatus, + BaseType_t xGetFreeStackSpace, + eTaskState eState ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskPrioritySet( TaskHandle_t xTask, + UBaseType_t uxNewPriority ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskSuspend( TaskHandle_t xTaskToSuspend ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskResume( TaskHandle_t xTaskToResume ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskStartScheduler( void ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskSuspendAll( void ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskResumeAll( void ) FREERTOS_SYSTEM_CALL; +TickType_t MPU_xTaskGetTickCount( void ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxTaskGetNumberOfTasks( void ) FREERTOS_SYSTEM_CALL; +char * MPU_pcTaskGetName( TaskHandle_t xTaskToQuery ) FREERTOS_SYSTEM_CALL; +TaskHandle_t MPU_xTaskGetHandle( const char * pcNameToQuery ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxTaskGetStackHighWaterMark( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; +configSTACK_DEPTH_TYPE MPU_uxTaskGetStackHighWaterMark2( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskSetApplicationTaskTag( TaskHandle_t xTask, + TaskHookFunction_t pxHookFunction ) FREERTOS_SYSTEM_CALL; +TaskHookFunction_t MPU_xTaskGetApplicationTaskTag( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, + BaseType_t xIndex, + void * pvValue ) FREERTOS_SYSTEM_CALL; +void * MPU_pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, + BaseType_t xIndex ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskCallApplicationTaskHook( TaskHandle_t xTask, + void * pvParameter ) FREERTOS_SYSTEM_CALL; +TaskHandle_t MPU_xTaskGetIdleTaskHandle( void ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, + const UBaseType_t uxArraySize, + 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, + UBaseType_t uxIndexToNotify, + uint32_t ulValue, + eNotifyAction eAction, + uint32_t * pulPreviousNotificationValue ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskGenericNotifyWait( UBaseType_t uxIndexToWaitOn, + uint32_t ulBitsToClearOnEntry, + uint32_t ulBitsToClearOnExit, + uint32_t * pulNotificationValue, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +uint32_t MPU_ulTaskGenericNotifyTake( UBaseType_t uxIndexToWaitOn, + BaseType_t xClearCountOnExit, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskGenericNotifyStateClear( TaskHandle_t xTask, + UBaseType_t uxIndexToClear ) FREERTOS_SYSTEM_CALL; +uint32_t MPU_ulTaskGenericNotifyValueClear( TaskHandle_t xTask, + UBaseType_t uxIndexToClear, + uint32_t ulBitsToClear ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskIncrementTick( void ) FREERTOS_SYSTEM_CALL; +TaskHandle_t MPU_xTaskGetCurrentTaskHandle( void ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, + TickType_t * const pxTicksToWait ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskMissedYield( void ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskGetSchedulerState( void ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskCatchUpTicks( TickType_t xTicksToCatchUp ) FREERTOS_SYSTEM_CALL; + +/* MPU versions of queue.h API functions. */ +BaseType_t MPU_xQueueGenericSend( QueueHandle_t xQueue, + const void * const pvItemToQueue, + TickType_t xTicksToWait, + const BaseType_t xCopyPosition ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueueReceive( QueueHandle_t xQueue, + void * const pvBuffer, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueuePeek( QueueHandle_t xQueue, + void * const pvBuffer, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueueSemaphoreTake( QueueHandle_t xQueue, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxQueueMessagesWaiting( const QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxQueueSpacesAvailable( const QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; +void MPU_vQueueDelete( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; +QueueHandle_t MPU_xQueueCreateMutex( const uint8_t ucQueueType ) FREERTOS_SYSTEM_CALL; +QueueHandle_t MPU_xQueueCreateMutexStatic( const uint8_t ucQueueType, + StaticQueue_t * pxStaticQueue ) FREERTOS_SYSTEM_CALL; +QueueHandle_t MPU_xQueueCreateCountingSemaphore( const UBaseType_t uxMaxCount, + const UBaseType_t uxInitialCount ) FREERTOS_SYSTEM_CALL; +QueueHandle_t MPU_xQueueCreateCountingSemaphoreStatic( const UBaseType_t uxMaxCount, + const UBaseType_t uxInitialCount, + StaticQueue_t * pxStaticQueue ) FREERTOS_SYSTEM_CALL; +TaskHandle_t MPU_xQueueGetMutexHolder( QueueHandle_t xSemaphore ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueueTakeMutexRecursive( QueueHandle_t xMutex, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueueGiveMutexRecursive( QueueHandle_t pxMutex ) FREERTOS_SYSTEM_CALL; +void MPU_vQueueAddToRegistry( QueueHandle_t xQueue, + const char * pcName ) FREERTOS_SYSTEM_CALL; +void MPU_vQueueUnregisterQueue( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; +const char * MPU_pcQueueGetName( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; +QueueHandle_t MPU_xQueueGenericCreate( const UBaseType_t uxQueueLength, + const UBaseType_t uxItemSize, + const uint8_t ucQueueType ) FREERTOS_SYSTEM_CALL; +QueueHandle_t MPU_xQueueGenericCreateStatic( const UBaseType_t uxQueueLength, + const UBaseType_t uxItemSize, + uint8_t * pucQueueStorage, + StaticQueue_t * pxStaticQueue, + const uint8_t ucQueueType ) FREERTOS_SYSTEM_CALL; +QueueSetHandle_t MPU_xQueueCreateSet( const UBaseType_t uxEventQueueLength ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, + QueueSetHandle_t xQueueSet ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, + QueueSetHandle_t xQueueSet ) FREERTOS_SYSTEM_CALL; +QueueSetMemberHandle_t MPU_xQueueSelectFromSet( QueueSetHandle_t xQueueSet, + const TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueueGenericReset( QueueHandle_t xQueue, + BaseType_t xNewQueue ) FREERTOS_SYSTEM_CALL; +void MPU_vQueueSetQueueNumber( QueueHandle_t xQueue, + UBaseType_t uxQueueNumber ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxQueueGetQueueNumber( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; +uint8_t MPU_ucQueueGetQueueType( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; + +/* MPU versions of timers.h API functions. */ +TimerHandle_t MPU_xTimerCreate( const char * const pcTimerName, + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction ) FREERTOS_SYSTEM_CALL; +TimerHandle_t MPU_xTimerCreateStatic( const char * const pcTimerName, + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction, + StaticTimer_t * pxTimerBuffer ) FREERTOS_SYSTEM_CALL; +void * MPU_pvTimerGetTimerID( const TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; +void MPU_vTimerSetTimerID( TimerHandle_t xTimer, + void * pvNewID ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTimerIsTimerActive( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; +TaskHandle_t MPU_xTimerGetTimerDaemonTaskHandle( void ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, + void * pvParameter1, + uint32_t ulParameter2, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +const char * MPU_pcTimerGetName( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; +void MPU_vTimerSetReloadMode( TimerHandle_t xTimer, + const UBaseType_t uxAutoReload ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxTimerGetReloadMode( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; +TickType_t MPU_xTimerGetPeriod( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; +TickType_t MPU_xTimerGetExpiryTime( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTimerCreateTimerTask( void ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTimerGenericCommand( TimerHandle_t xTimer, + const BaseType_t xCommandID, + const TickType_t xOptionalValue, + BaseType_t * const pxHigherPriorityTaskWoken, + const TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; + +/* MPU versions of event_group.h API functions. */ +EventGroupHandle_t MPU_xEventGroupCreate( void ) FREERTOS_SYSTEM_CALL; +EventGroupHandle_t MPU_xEventGroupCreateStatic( StaticEventGroup_t * pxEventGroupBuffer ) FREERTOS_SYSTEM_CALL; +EventBits_t MPU_xEventGroupWaitBits( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToWaitFor, + const BaseType_t xClearOnExit, + const BaseType_t xWaitForAllBits, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +EventBits_t MPU_xEventGroupClearBits( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToClear ) FREERTOS_SYSTEM_CALL; +EventBits_t MPU_xEventGroupSetBits( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToSet ) FREERTOS_SYSTEM_CALL; +EventBits_t MPU_xEventGroupSync( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToSet, + const EventBits_t uxBitsToWaitFor, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +void MPU_vEventGroupDelete( EventGroupHandle_t xEventGroup ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxEventGroupGetNumber( void * xEventGroup ) FREERTOS_SYSTEM_CALL; + +/* MPU versions of message/stream_buffer.h API functions. */ +size_t MPU_xStreamBufferSend( StreamBufferHandle_t xStreamBuffer, + const void * pvTxData, + size_t xDataLengthBytes, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +size_t MPU_xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer, + void * pvRxData, + size_t xBufferLengthBytes, + TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +size_t MPU_xStreamBufferNextMessageLengthBytes( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; +void MPU_vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xStreamBufferReset( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; +size_t MPU_xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; +size_t MPU_xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, + size_t xTriggerLevel ) FREERTOS_SYSTEM_CALL; +StreamBufferHandle_t MPU_xStreamBufferGenericCreate( size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + BaseType_t xIsMessageBuffer ) FREERTOS_SYSTEM_CALL; +StreamBufferHandle_t MPU_xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + BaseType_t xIsMessageBuffer, + uint8_t * const pucStreamBufferStorageArea, + StaticStreamBuffer_t * const pxStaticStreamBuffer ) FREERTOS_SYSTEM_CALL; + + + +#endif /* MPU_PROTOTYPES_H */ diff --git a/examples/stm32/freertos-kernel/include/mpu_wrappers.h b/examples/stm32/freertos-kernel/include/mpu_wrappers.h new file mode 100644 index 00000000..a5c081ff --- /dev/null +++ b/examples/stm32/freertos-kernel/include/mpu_wrappers.h @@ -0,0 +1,185 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#ifndef 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 vTaskDelete MPU_vTaskDelete + #define vTaskDelay MPU_vTaskDelay + #define xTaskDelayUntil MPU_xTaskDelayUntil + #define xTaskAbortDelay MPU_xTaskAbortDelay + #define uxTaskPriorityGet MPU_uxTaskPriorityGet + #define eTaskGetState MPU_eTaskGetState + #define vTaskGetInfo MPU_vTaskGetInfo + #define vTaskPrioritySet MPU_vTaskPrioritySet + #define vTaskSuspend MPU_vTaskSuspend + #define vTaskResume MPU_vTaskResume + #define vTaskSuspendAll MPU_vTaskSuspendAll + #define xTaskResumeAll MPU_xTaskResumeAll + #define xTaskGetTickCount MPU_xTaskGetTickCount + #define uxTaskGetNumberOfTasks MPU_uxTaskGetNumberOfTasks + #define pcTaskGetName MPU_pcTaskGetName + #define xTaskGetHandle MPU_xTaskGetHandle + #define uxTaskGetStackHighWaterMark MPU_uxTaskGetStackHighWaterMark + #define uxTaskGetStackHighWaterMark2 MPU_uxTaskGetStackHighWaterMark2 + #define vTaskSetApplicationTaskTag MPU_vTaskSetApplicationTaskTag + #define xTaskGetApplicationTaskTag MPU_xTaskGetApplicationTaskTag + #define vTaskSetThreadLocalStoragePointer MPU_vTaskSetThreadLocalStoragePointer + #define pvTaskGetThreadLocalStoragePointer MPU_pvTaskGetThreadLocalStoragePointer + #define xTaskCallApplicationTaskHook MPU_xTaskCallApplicationTaskHook + #define xTaskGetIdleTaskHandle MPU_xTaskGetIdleTaskHandle + #define uxTaskGetSystemState MPU_uxTaskGetSystemState + #define vTaskList MPU_vTaskList + #define vTaskGetRunTimeStats MPU_vTaskGetRunTimeStats + #define ulTaskGetIdleRunTimeCounter MPU_ulTaskGetIdleRunTimeCounter + #define xTaskGenericNotify MPU_xTaskGenericNotify + #define xTaskGenericNotifyWait MPU_xTaskGenericNotifyWait + #define ulTaskGenericNotifyTake MPU_ulTaskGenericNotifyTake + #define xTaskGenericNotifyStateClear MPU_xTaskGenericNotifyStateClear + #define ulTaskGenericNotifyValueClear MPU_ulTaskGenericNotifyValueClear + #define xTaskCatchUpTicks MPU_xTaskCatchUpTicks + + #define xTaskGetCurrentTaskHandle MPU_xTaskGetCurrentTaskHandle + #define vTaskSetTimeOutState MPU_vTaskSetTimeOutState + #define xTaskCheckForTimeOut MPU_xTaskCheckForTimeOut + #define xTaskGetSchedulerState MPU_xTaskGetSchedulerState + +/* Map standard queue.h API functions to the MPU equivalents. */ + #define xQueueGenericSend MPU_xQueueGenericSend + #define xQueueReceive MPU_xQueueReceive + #define xQueuePeek MPU_xQueuePeek + #define xQueueSemaphoreTake MPU_xQueueSemaphoreTake + #define uxQueueMessagesWaiting MPU_uxQueueMessagesWaiting + #define uxQueueSpacesAvailable MPU_uxQueueSpacesAvailable + #define vQueueDelete MPU_vQueueDelete + #define xQueueCreateMutex MPU_xQueueCreateMutex + #define xQueueCreateMutexStatic MPU_xQueueCreateMutexStatic + #define xQueueCreateCountingSemaphore MPU_xQueueCreateCountingSemaphore + #define xQueueCreateCountingSemaphoreStatic MPU_xQueueCreateCountingSemaphoreStatic + #define xQueueGetMutexHolder MPU_xQueueGetMutexHolder + #define xQueueTakeMutexRecursive MPU_xQueueTakeMutexRecursive + #define xQueueGiveMutexRecursive MPU_xQueueGiveMutexRecursive + #define xQueueGenericCreate MPU_xQueueGenericCreate + #define xQueueGenericCreateStatic MPU_xQueueGenericCreateStatic + #define xQueueCreateSet MPU_xQueueCreateSet + #define xQueueAddToSet MPU_xQueueAddToSet + #define xQueueRemoveFromSet MPU_xQueueRemoveFromSet + #define xQueueSelectFromSet MPU_xQueueSelectFromSet + #define xQueueGenericReset MPU_xQueueGenericReset + + #if ( configQUEUE_REGISTRY_SIZE > 0 ) + #define vQueueAddToRegistry MPU_vQueueAddToRegistry + #define vQueueUnregisterQueue MPU_vQueueUnregisterQueue + #define pcQueueGetName MPU_pcQueueGetName + #endif + +/* Map standard timer.h API functions to the MPU equivalents. */ + #define xTimerCreate MPU_xTimerCreate + #define xTimerCreateStatic MPU_xTimerCreateStatic + #define pvTimerGetTimerID MPU_pvTimerGetTimerID + #define vTimerSetTimerID MPU_vTimerSetTimerID + #define xTimerIsTimerActive MPU_xTimerIsTimerActive + #define xTimerGetTimerDaemonTaskHandle MPU_xTimerGetTimerDaemonTaskHandle + #define xTimerPendFunctionCall MPU_xTimerPendFunctionCall + #define pcTimerGetName MPU_pcTimerGetName + #define vTimerSetReloadMode MPU_vTimerSetReloadMode + #define uxTimerGetReloadMode MPU_uxTimerGetReloadMode + #define xTimerGetPeriod MPU_xTimerGetPeriod + #define xTimerGetExpiryTime MPU_xTimerGetExpiryTime + #define xTimerGenericCommand MPU_xTimerGenericCommand + +/* Map standard event_group.h API functions to the MPU equivalents. */ + #define xEventGroupCreate MPU_xEventGroupCreate + #define xEventGroupCreateStatic MPU_xEventGroupCreateStatic + #define xEventGroupWaitBits MPU_xEventGroupWaitBits + #define xEventGroupClearBits MPU_xEventGroupClearBits + #define xEventGroupSetBits MPU_xEventGroupSetBits + #define xEventGroupSync MPU_xEventGroupSync + #define vEventGroupDelete MPU_vEventGroupDelete + +/* Map standard message/stream_buffer.h API functions to the MPU + * equivalents. */ + #define xStreamBufferSend MPU_xStreamBufferSend + #define xStreamBufferReceive MPU_xStreamBufferReceive + #define xStreamBufferNextMessageLengthBytes MPU_xStreamBufferNextMessageLengthBytes + #define vStreamBufferDelete MPU_vStreamBufferDelete + #define xStreamBufferIsFull MPU_xStreamBufferIsFull + #define xStreamBufferIsEmpty MPU_xStreamBufferIsEmpty + #define xStreamBufferReset MPU_xStreamBufferReset + #define xStreamBufferSpacesAvailable MPU_xStreamBufferSpacesAvailable + #define xStreamBufferBytesAvailable MPU_xStreamBufferBytesAvailable + #define xStreamBufferSetTriggerLevel MPU_xStreamBufferSetTriggerLevel + #define xStreamBufferGenericCreate MPU_xStreamBufferGenericCreate + #define xStreamBufferGenericCreateStatic MPU_xStreamBufferGenericCreateStatic + + +/* Remove the privileged function macro, but keep the PRIVILEGED_DATA + * macro so applications can place data in privileged access sections + * (useful when using statically allocated objects). */ + #define PRIVILEGED_FUNCTION + #define PRIVILEGED_DATA __attribute__( ( section( "privileged_data" ) ) ) + #define FREERTOS_SYSTEM_CALL + + #else /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE */ + +/* Ensure API functions go in the privileged execution section. */ + #define PRIVILEGED_FUNCTION __attribute__( ( section( "privileged_functions" ) ) ) + #define PRIVILEGED_DATA __attribute__( ( section( "privileged_data" ) ) ) + #define FREERTOS_SYSTEM_CALL __attribute__( ( section( "freertos_system_calls" ) ) ) + + #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/examples/stm32/freertos-kernel/include/portable.h b/examples/stm32/freertos-kernel/include/portable.h new file mode 100644 index 00000000..4f4c1d52 --- /dev/null +++ b/examples/stm32/freertos-kernel/include/portable.h @@ -0,0 +1,216 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/*----------------------------------------------------------- +* 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 + +/* *INDENT-OFF* */ +#ifdef __cplusplus + extern "C" { +#endif +/* *INDENT-ON* */ + +#include "mpu_wrappers.h" + +/* + * Setup the stack of a new task so it is ready to be placed under the + * scheduler control. The registers have to be placed on the stack in + * the order that the port expects to find them. + * + */ +#if ( portUSING_MPU_WRAPPERS == 1 ) + #if ( portHAS_STACK_OVERFLOW_CHECKING == 1 ) + StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack, + StackType_t * pxEndOfStack, + TaskFunction_t pxCode, + void * pvParameters, + BaseType_t xRunPrivileged ) PRIVILEGED_FUNCTION; + #else + StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack, + TaskFunction_t pxCode, + void * pvParameters, + BaseType_t xRunPrivileged ) PRIVILEGED_FUNCTION; + #endif +#else /* if ( portUSING_MPU_WRAPPERS == 1 ) */ + #if ( portHAS_STACK_OVERFLOW_CHECKING == 1 ) + StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack, + StackType_t * pxEndOfStack, + TaskFunction_t pxCode, + void * pvParameters ) PRIVILEGED_FUNCTION; + #else + StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack, + TaskFunction_t pxCode, + void * pvParameters ) PRIVILEGED_FUNCTION; + #endif +#endif /* if ( portUSING_MPU_WRAPPERS == 1 ) */ + +/* Used by heap_5.c to define the start address and size of each memory region + * that together comprise the total FreeRTOS heap space. */ +typedef struct HeapRegion +{ + uint8_t * pucStartAddress; + size_t xSizeInBytes; +} HeapRegion_t; + +/* Used to pass information about the heap out of vPortGetHeapStats(). */ +typedef struct xHeapStats +{ + size_t xAvailableHeapSpaceInBytes; /* The total heap size currently available - this is the sum of all the free blocks, not the largest block that can be allocated. */ + size_t xSizeOfLargestFreeBlockInBytes; /* The maximum size, in bytes, of all the free blocks within the heap at the time vPortGetHeapStats() is called. */ + size_t xSizeOfSmallestFreeBlockInBytes; /* The minimum size, in bytes, of all the free blocks within the heap at the time vPortGetHeapStats() is called. */ + size_t xNumberOfFreeBlocks; /* The number of free memory blocks within the heap at the time vPortGetHeapStats() is called. */ + size_t xMinimumEverFreeBytesRemaining; /* The minimum amount of total free memory (sum of all free blocks) there has been in the heap since the system booted. */ + size_t xNumberOfSuccessfulAllocations; /* The number of calls to pvPortMalloc() that have returned a valid memory block. */ + size_t xNumberOfSuccessfulFrees; /* The number of calls to vPortFree() that has successfully freed a block of memory. */ +} HeapStats_t; + +/* + * Used to define multiple heap regions for use by heap_5.c. This function + * must be called before any calls to pvPortMalloc() - not creating a task, + * queue, semaphore, mutex, software timer, event group, etc. will result in + * pvPortMalloc being called. + * + * pxHeapRegions passes in an array of HeapRegion_t structures - each of which + * defines a region of memory that can be used as the heap. The array is + * terminated by a HeapRegions_t structure that has a size of 0. The region + * with the lowest start address must appear first in the array. + */ +void vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions ) PRIVILEGED_FUNCTION; + +/* + * Returns a HeapStats_t structure filled with information about the current + * heap state. + */ +void vPortGetHeapStats( HeapStats_t * pxHeapStats ); + +/* + * Map to the memory management routines required for the port. + */ +void * pvPortMalloc( size_t xSize ) PRIVILEGED_FUNCTION; +void vPortFree( void * pv ) PRIVILEGED_FUNCTION; +void vPortInitialiseBlocks( void ) PRIVILEGED_FUNCTION; +size_t xPortGetFreeHeapSize( void ) PRIVILEGED_FUNCTION; +size_t xPortGetMinimumEverFreeHeapSize( void ) PRIVILEGED_FUNCTION; + +/* + * Setup the hardware ready for the scheduler to take control. This generally + * sets up a tick interrupt and sets timers for the correct tick frequency. + */ +BaseType_t xPortStartScheduler( void ) PRIVILEGED_FUNCTION; + +/* + * Undo any hardware/ISR setup that was performed by xPortStartScheduler() so + * the hardware is left in its original condition after the scheduler stops + * executing. + */ +void vPortEndScheduler( void ) PRIVILEGED_FUNCTION; + +/* + * The structures and methods of manipulating the MPU are contained within the + * port layer. + * + * Fills the xMPUSettings structure with the memory region information + * contained in xRegions. + */ +#if ( portUSING_MPU_WRAPPERS == 1 ) + struct xMEMORY_REGION; + void vPortStoreTaskMPUSettings( xMPU_SETTINGS * xMPUSettings, + const struct xMEMORY_REGION * const xRegions, + StackType_t * pxBottomOfStack, + uint32_t ulStackDepth ) PRIVILEGED_FUNCTION; +#endif + +/* *INDENT-OFF* */ +#ifdef __cplusplus + } +#endif +/* *INDENT-ON* */ + +#endif /* PORTABLE_H */ diff --git a/examples/stm32/freertos-kernel/include/projdefs.h b/examples/stm32/freertos-kernel/include/projdefs.h new file mode 100644 index 00000000..fd9072c5 --- /dev/null +++ b/examples/stm32/freertos-kernel/include/projdefs.h @@ -0,0 +1,120 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#ifndef PROJDEFS_H +#define PROJDEFS_H + +/* + * Defines the prototype to which task functions must conform. Defined in this + * file to ensure the type is known before portable.h is included. + */ +typedef void (* TaskFunction_t)( void * ); + +/* Converts a time in milliseconds to a time in ticks. This macro can be + * overridden by a macro of the same name defined in FreeRTOSConfig.h in case the + * definition here is not suitable for your application. */ +#ifndef pdMS_TO_TICKS + #define pdMS_TO_TICKS( xTimeInMs ) ( ( TickType_t ) ( ( ( TickType_t ) ( xTimeInMs ) * ( TickType_t ) configTICK_RATE_HZ ) / ( TickType_t ) 1000U ) ) +#endif + +#define pdFALSE ( ( BaseType_t ) 0 ) +#define pdTRUE ( ( BaseType_t ) 1 ) + +#define pdPASS ( pdTRUE ) +#define pdFAIL ( pdFALSE ) +#define errQUEUE_EMPTY ( ( BaseType_t ) 0 ) +#define errQUEUE_FULL ( ( BaseType_t ) 0 ) + +/* FreeRTOS error definitions. */ +#define errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY ( -1 ) +#define errQUEUE_BLOCKED ( -4 ) +#define errQUEUE_YIELD ( -5 ) + +/* Macros used for basic data corruption checks. */ +#ifndef configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES + #define configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES 0 +#endif + +#if ( configUSE_16_BIT_TICKS == 1 ) + #define pdINTEGRITY_CHECK_VALUE 0x5a5a +#else + #define pdINTEGRITY_CHECK_VALUE 0x5a5a5a5aUL +#endif + +/* The following errno values are used by FreeRTOS+ components, not FreeRTOS + * itself. */ +#define pdFREERTOS_ERRNO_NONE 0 /* No errors */ +#define pdFREERTOS_ERRNO_ENOENT 2 /* No such file or directory */ +#define pdFREERTOS_ERRNO_EINTR 4 /* Interrupted system call */ +#define pdFREERTOS_ERRNO_EIO 5 /* I/O error */ +#define pdFREERTOS_ERRNO_ENXIO 6 /* No such device or address */ +#define pdFREERTOS_ERRNO_EBADF 9 /* Bad file number */ +#define pdFREERTOS_ERRNO_EAGAIN 11 /* No more processes */ +#define pdFREERTOS_ERRNO_EWOULDBLOCK 11 /* Operation would block */ +#define pdFREERTOS_ERRNO_ENOMEM 12 /* Not enough memory */ +#define pdFREERTOS_ERRNO_EACCES 13 /* Permission denied */ +#define pdFREERTOS_ERRNO_EFAULT 14 /* Bad address */ +#define pdFREERTOS_ERRNO_EBUSY 16 /* Mount device busy */ +#define pdFREERTOS_ERRNO_EEXIST 17 /* File exists */ +#define pdFREERTOS_ERRNO_EXDEV 18 /* Cross-device link */ +#define pdFREERTOS_ERRNO_ENODEV 19 /* No such device */ +#define pdFREERTOS_ERRNO_ENOTDIR 20 /* Not a directory */ +#define pdFREERTOS_ERRNO_EISDIR 21 /* Is a directory */ +#define pdFREERTOS_ERRNO_EINVAL 22 /* Invalid argument */ +#define pdFREERTOS_ERRNO_ENOSPC 28 /* No space left on device */ +#define pdFREERTOS_ERRNO_ESPIPE 29 /* Illegal seek */ +#define pdFREERTOS_ERRNO_EROFS 30 /* Read only file system */ +#define pdFREERTOS_ERRNO_EUNATCH 42 /* Protocol driver not attached */ +#define pdFREERTOS_ERRNO_EBADE 50 /* Invalid exchange */ +#define pdFREERTOS_ERRNO_EFTYPE 79 /* Inappropriate file type or format */ +#define pdFREERTOS_ERRNO_ENMFILE 89 /* No more files */ +#define pdFREERTOS_ERRNO_ENOTEMPTY 90 /* Directory not empty */ +#define pdFREERTOS_ERRNO_ENAMETOOLONG 91 /* File or path name too long */ +#define pdFREERTOS_ERRNO_EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ +#define pdFREERTOS_ERRNO_ENOBUFS 105 /* No buffer space available */ +#define pdFREERTOS_ERRNO_ENOPROTOOPT 109 /* Protocol not available */ +#define pdFREERTOS_ERRNO_EADDRINUSE 112 /* Address already in use */ +#define pdFREERTOS_ERRNO_ETIMEDOUT 116 /* Connection timed out */ +#define pdFREERTOS_ERRNO_EINPROGRESS 119 /* Connection already in progress */ +#define pdFREERTOS_ERRNO_EALREADY 120 /* Socket already connected */ +#define pdFREERTOS_ERRNO_EADDRNOTAVAIL 125 /* Address not available */ +#define pdFREERTOS_ERRNO_EISCONN 127 /* Socket is already connected */ +#define pdFREERTOS_ERRNO_ENOTCONN 128 /* Socket is not connected */ +#define pdFREERTOS_ERRNO_ENOMEDIUM 135 /* No medium inserted */ +#define pdFREERTOS_ERRNO_EILSEQ 138 /* An invalid UTF-16 sequence was encountered. */ +#define pdFREERTOS_ERRNO_ECANCELED 140 /* Operation canceled. */ + +/* The following endian values are used by FreeRTOS+ components, not FreeRTOS + * itself. */ +#define pdFREERTOS_LITTLE_ENDIAN 0 +#define pdFREERTOS_BIG_ENDIAN 1 + +/* Re-defining endian values for generic naming. */ +#define pdLITTLE_ENDIAN pdFREERTOS_LITTLE_ENDIAN +#define pdBIG_ENDIAN pdFREERTOS_BIG_ENDIAN + + +#endif /* PROJDEFS_H */ diff --git a/examples/stm32/freertos-kernel/include/queue.h b/examples/stm32/freertos-kernel/include/queue.h new file mode 100644 index 00000000..37ad23c7 --- /dev/null +++ b/examples/stm32/freertos-kernel/include/queue.h @@ -0,0 +1,1716 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + + +#ifndef QUEUE_H +#define QUEUE_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h" must appear in source files before "include queue.h" +#endif + +/* *INDENT-OFF* */ +#ifdef __cplusplus + extern "C" { +#endif +/* *INDENT-ON* */ + +#include "task.h" + +/** + * Type by which queues are referenced. For example, a call to xQueueCreate() + * returns an QueueHandle_t variable that can then be used as a parameter to + * xQueueSend(), xQueueReceive(), etc. + */ +struct QueueDefinition; /* Using old naming convention so as not to break kernel aware debuggers. */ +typedef struct QueueDefinition * QueueHandle_t; + +/** + * Type by which queue sets are referenced. For example, a call to + * xQueueCreateSet() returns an xQueueSet variable that can then be used as a + * parameter to xQueueSelectFromSet(), xQueueAddToSet(), etc. + */ +typedef struct QueueDefinition * QueueSetHandle_t; + +/** + * Queue sets can contain both queues and semaphores, so the + * QueueSetMemberHandle_t is defined as a type to be used where a parameter or + * return value can be either an QueueHandle_t or an SemaphoreHandle_t. + */ +typedef struct QueueDefinition * QueueSetMemberHandle_t; + +/* For internal use only. */ +#define queueSEND_TO_BACK ( ( BaseType_t ) 0 ) +#define queueSEND_TO_FRONT ( ( BaseType_t ) 1 ) +#define queueOVERWRITE ( ( BaseType_t ) 2 ) + +/* For internal use only. These definitions *must* match those in queue.c. */ +#define queueQUEUE_TYPE_BASE ( ( uint8_t ) 0U ) +#define queueQUEUE_TYPE_SET ( ( uint8_t ) 0U ) +#define queueQUEUE_TYPE_MUTEX ( ( uint8_t ) 1U ) +#define queueQUEUE_TYPE_COUNTING_SEMAPHORE ( ( uint8_t ) 2U ) +#define queueQUEUE_TYPE_BINARY_SEMAPHORE ( ( uint8_t ) 3U ) +#define queueQUEUE_TYPE_RECURSIVE_MUTEX ( ( uint8_t ) 4U ) + +/** + * queue. h + *
+ * 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 + * https://www.FreeRTOS.org/a00111.html). If a queue is created using + * xQueueCreateStatic() then the application writer must provide the memory that + * will get used by the queue. xQueueCreateStatic() therefore allows a queue to + * be created without using any dynamic memory allocation. + * + * https://www.FreeRTOS.org/Embedded-RTOS-Queues.html + * + * @param uxQueueLength The maximum number of items that the queue can contain. + * + * @param uxItemSize The number of bytes each item in the queue will require. + * Items are queued by copy, not by reference, so this is the number of bytes + * that will be copied for each posted item. Each item on the queue must be + * the same size. + * + * @return If the queue is successfully create then a handle to the newly + * created queue is returned. If the queue cannot be created then 0 is + * returned. + * + * Example usage: + *
+ * 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 + * https://www.FreeRTOS.org/a00111.html). If a queue is created using + * xQueueCreateStatic() then the application writer must provide the memory that + * will get used by the queue. xQueueCreateStatic() therefore allows a queue to + * be created without using any dynamic memory allocation. + * + * https://www.FreeRTOS.org/Embedded-RTOS-Queues.html + * + * @param uxQueueLength The maximum number of items that the queue can contain. + * + * @param uxItemSize The number of bytes each item in the queue will require. + * Items are queued by copy, not by reference, so this is the number of bytes + * that will be copied for each posted item. Each item on the queue must be + * the same size. + * + * @param 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 create a queue using dynamic memory + * allocation. This is called by other functions and macros that create other + * RTOS objects that use the queue structure as their base. + */ +#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + QueueHandle_t xQueueGenericCreate( const UBaseType_t uxQueueLength, + const UBaseType_t uxItemSize, + const uint8_t ucQueueType ) PRIVILEGED_FUNCTION; +#endif + +/* + * Generic version of the function used to create a queue using dynamic memory + * allocation. This is called by other functions and macros that create other + * RTOS objects that use the queue structure as their base. + */ +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + QueueHandle_t xQueueGenericCreateStatic( const UBaseType_t uxQueueLength, + const UBaseType_t uxItemSize, + uint8_t * pucQueueStorage, + StaticQueue_t * pxStaticQueue, + const uint8_t ucQueueType ) PRIVILEGED_FUNCTION; +#endif + +/* + * Queue sets provide a mechanism to allow a task to block (pend) on a read + * operation from multiple queues or semaphores simultaneously. + * + * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this + * function. + * + * A queue set must be explicitly created using a call to xQueueCreateSet() + * before it can be used. Once created, standard FreeRTOS queues and semaphores + * can be added to the set using calls to xQueueAddToSet(). + * xQueueSelectFromSet() is then used to determine which, if any, of the queues + * or semaphores contained in the set is in a state where a queue read or + * semaphore take operation would be successful. + * + * Note 1: See the documentation on https://www.FreeRTOS.org/RTOS-queue-sets.html + * for reasons why queue sets are very rarely needed in practice as there are + * simpler methods of blocking on multiple objects. + * + * Note 2: Blocking on a queue set that contains a mutex will not cause the + * mutex holder to inherit the priority of the blocked task. + * + * Note 3: An additional 4 bytes of RAM is required for each space in a every + * queue added to a queue set. Therefore counting semaphores that have a high + * maximum count value should not be added to a queue set. + * + * Note 4: A receive (in the case of a queue) or take (in the case of a + * semaphore) operation must not be performed on a member of a queue set unless + * a call to xQueueSelectFromSet() has first returned a handle to that set member. + * + * @param uxEventQueueLength Queue sets store events that occur on + * the queues and semaphores contained in the set. uxEventQueueLength specifies + * the maximum number of events that can be queued at once. To be absolutely + * certain that events are not lost uxEventQueueLength should be set to the + * total sum of the length of the queues added to the set, where binary + * semaphores and mutexes have a length of 1, and counting semaphores have a + * length set by their maximum count value. Examples: + * + If a queue set is to hold a queue of length 5, another queue of length 12, + * and a binary semaphore, then uxEventQueueLength should be set to + * (5 + 12 + 1), or 18. + * + If a queue set is to hold three binary semaphores then uxEventQueueLength + * should be set to (1 + 1 + 1 ), or 3. + * + If a queue set is to hold a counting semaphore that has a maximum count of + * 5, and a counting semaphore that has a maximum count of 3, then + * uxEventQueueLength should be set to (5 + 3), or 8. + * + * @return If the queue set is created successfully then a handle to the created + * queue set is returned. Otherwise NULL is returned. + */ +QueueSetHandle_t xQueueCreateSet( const UBaseType_t uxEventQueueLength ) PRIVILEGED_FUNCTION; + +/* + * Adds a queue or semaphore to a queue set that was previously created by a + * call to xQueueCreateSet(). + * + * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this + * function. + * + * Note 1: A receive (in the case of a queue) or take (in the case of a + * semaphore) operation must not be performed on a member of a queue set unless + * a call to xQueueSelectFromSet() has first returned a handle to that set member. + * + * @param xQueueOrSemaphore The handle of the queue or semaphore being added to + * the queue set (cast to an QueueSetMemberHandle_t type). + * + * @param xQueueSet The handle of the queue set to which the queue or semaphore + * is being added. + * + * @return If the queue or semaphore was successfully added to the queue set + * then pdPASS is returned. If the queue could not be successfully added to the + * queue set because it is already a member of a different queue set then pdFAIL + * is returned. + */ +BaseType_t xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, + QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION; + +/* + * Removes a queue or semaphore from a queue set. A queue or semaphore can only + * be removed from a set if the queue or semaphore is empty. + * + * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this + * function. + * + * @param xQueueOrSemaphore The handle of the queue or semaphore being removed + * from the queue set (cast to an QueueSetMemberHandle_t type). + * + * @param xQueueSet The handle of the queue set in which the queue or semaphore + * is included. + * + * @return If the queue or semaphore was successfully removed from the queue set + * then pdPASS is returned. If the queue was not in the queue set, or the + * queue (or semaphore) was not empty, then pdFAIL is returned. + */ +BaseType_t xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, + QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION; + +/* + * xQueueSelectFromSet() selects from the members of a queue set a queue or + * semaphore that either contains data (in the case of a queue) or is available + * to take (in the case of a semaphore). xQueueSelectFromSet() effectively + * allows a task to block (pend) on a read operation on all the queues and + * semaphores in a queue set simultaneously. + * + * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this + * function. + * + * Note 1: See the documentation on https://www.FreeRTOS.org/RTOS-queue-sets.html + * for reasons why queue sets are very rarely needed in practice as there are + * simpler methods of blocking on multiple objects. + * + * Note 2: Blocking on a queue set that contains a mutex will not cause the + * mutex holder to inherit the priority of the blocked task. + * + * Note 3: A receive (in the case of a queue) or take (in the case of a + * semaphore) operation must not be performed on a member of a queue set unless + * a call to xQueueSelectFromSet() has first returned a handle to that set member. + * + * @param xQueueSet The queue set on which the task will (potentially) block. + * + * @param xTicksToWait The maximum time, in ticks, that the calling task will + * remain in the Blocked state (with other tasks executing) to wait for a member + * of the queue set to be ready for a successful queue read or semaphore take + * operation. + * + * @return xQueueSelectFromSet() will return the handle of a queue (cast to + * a QueueSetMemberHandle_t type) contained in the queue set that contains data, + * or the handle of a semaphore (cast to a QueueSetMemberHandle_t type) contained + * in the queue set that is available, or NULL if no such queue or semaphore + * exists before before the specified block time expires. + */ +QueueSetMemberHandle_t xQueueSelectFromSet( QueueSetHandle_t xQueueSet, + const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/* + * A version of xQueueSelectFromSet() that can be used from an ISR. + */ +QueueSetMemberHandle_t xQueueSelectFromSetFromISR( QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION; + +/* Not public API functions. */ +void vQueueWaitForMessageRestricted( QueueHandle_t xQueue, + TickType_t xTicksToWait, + const BaseType_t xWaitIndefinitely ) PRIVILEGED_FUNCTION; +BaseType_t xQueueGenericReset( QueueHandle_t xQueue, + BaseType_t xNewQueue ) PRIVILEGED_FUNCTION; +void vQueueSetQueueNumber( QueueHandle_t xQueue, + UBaseType_t uxQueueNumber ) PRIVILEGED_FUNCTION; +UBaseType_t uxQueueGetQueueNumber( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; +uint8_t ucQueueGetQueueType( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; + + +/* *INDENT-OFF* */ +#ifdef __cplusplus + } +#endif +/* *INDENT-ON* */ + +#endif /* QUEUE_H */ diff --git a/examples/stm32/freertos-kernel/include/semphr.h b/examples/stm32/freertos-kernel/include/semphr.h new file mode 100644 index 00000000..525a8ec1 --- /dev/null +++ b/examples/stm32/freertos-kernel/include/semphr.h @@ -0,0 +1,1173 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#ifndef 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! + * https://www.FreeRTOS.org/RTOS-task-notifications.html + * + * This old vSemaphoreCreateBinary() macro is now deprecated in favour of the + * xSemaphoreCreateBinary() function. Note that binary semaphores created using + * the vSemaphoreCreateBinary() macro are created in a state such that the + * first call to 'take' the semaphore would pass, whereas binary semaphores + * created using xSemaphoreCreateBinary() are created in a state such that the + * the semaphore must first be 'given' before it can be 'taken'. + * + * Macro that implements a semaphore by using the existing queue mechanism. + * The queue length is 1 as this is a binary semaphore. The data size is 0 + * as we don't want to actually store any data - we just want to know if the + * queue is empty or full. + * + * This type of semaphore can be used for pure synchronisation between tasks or + * between an interrupt and a task. The semaphore need not be given back once + * obtained, so one task/interrupt can continuously 'give' the semaphore while + * another continuously 'takes' the semaphore. For this reason this type of + * semaphore does not use a priority inheritance mechanism. For an alternative + * that does use priority inheritance see xSemaphoreCreateMutex(). + * + * @param xSemaphore Handle to the created semaphore. Should be of type SemaphoreHandle_t. + * + * Example usage: + *
+ * 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! + * https://www.FreeRTOS.org/RTOS-task-notifications.html + * + * Internally, within the FreeRTOS implementation, binary semaphores use a block + * of memory, in which the semaphore structure is stored. If a binary semaphore + * is created using xSemaphoreCreateBinary() then the required memory is + * automatically dynamically allocated inside the xSemaphoreCreateBinary() + * function. (see https://www.FreeRTOS.org/a00111.html). If a binary semaphore + * is created using xSemaphoreCreateBinaryStatic() then the application writer + * must provide the memory. xSemaphoreCreateBinaryStatic() therefore allows a + * binary semaphore to be created without using any dynamic memory allocation. + * + * The old vSemaphoreCreateBinary() macro is now deprecated in favour of this + * xSemaphoreCreateBinary() function. Note that binary semaphores created using + * the vSemaphoreCreateBinary() macro are created in a state such that the + * first call to 'take' the semaphore would pass, whereas binary semaphores + * created using xSemaphoreCreateBinary() are created in a state such that the + * the semaphore must first be 'given' before it can be 'taken'. + * + * This type of semaphore can be used for pure synchronisation between tasks or + * between an interrupt and a task. The semaphore need not be given back once + * obtained, so one task/interrupt can continuously 'give' the semaphore while + * another continuously 'takes' the semaphore. For this reason this type of + * semaphore does not use a priority inheritance mechanism. For an alternative + * that does use priority inheritance see xSemaphoreCreateMutex(). + * + * @return Handle to the created semaphore, or NULL if the memory required to + * hold the semaphore's data structures could not be allocated. + * + * Example usage: + *
+ * 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! + * https://www.FreeRTOS.org/RTOS-task-notifications.html + * + * Internally, within the FreeRTOS implementation, binary semaphores use a block + * of memory, in which the semaphore structure is stored. If a binary semaphore + * is created using xSemaphoreCreateBinary() then the required memory is + * automatically dynamically allocated inside the xSemaphoreCreateBinary() + * function. (see https://www.FreeRTOS.org/a00111.html). If a binary semaphore + * is created using xSemaphoreCreateBinaryStatic() then the application writer + * must provide the memory. xSemaphoreCreateBinaryStatic() therefore allows a + * binary semaphore to be created without using any dynamic memory allocation. + * + * This type of semaphore can be used for pure synchronisation between tasks or + * between an interrupt and a task. The semaphore need not be given back once + * obtained, so one task/interrupt can continuously 'give' the semaphore while + * another continuously 'takes' the semaphore. For this reason this type of + * semaphore does not use a priority inheritance mechanism. For an alternative + * that does use priority inheritance see xSemaphoreCreateMutex(). + * + * @param pxSemaphoreBuffer Must point to a variable of type StaticSemaphore_t, + * which will then be used to hold the semaphore's data structure, removing the + * need for the memory to be allocated dynamically. + * + * @return If the semaphore is created then a handle to the created semaphore is + * returned. If pxSemaphoreBuffer is NULL then NULL is returned. + * + * Example usage: + *
+ * 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 + * https://www.FreeRTOS.org/a00111.html). If a mutex is created using + * xSemaphoreCreateMutexStatic() then the application writer must provided the + * memory. xSemaphoreCreateMutexStatic() therefore allows a mutex to be created + * without using any dynamic memory allocation. + * + * Mutexes created using this function can be accessed using the xSemaphoreTake() + * and xSemaphoreGive() macros. The xSemaphoreTakeRecursive() and + * xSemaphoreGiveRecursive() macros must not be used. + * + * This type of semaphore uses a priority inheritance mechanism so a task + * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the + * semaphore it is no longer required. + * + * Mutex type semaphores cannot be used from within interrupt service routines. + * + * See xSemaphoreCreateBinary() for an alternative implementation that can be + * used for pure synchronisation (where one task or interrupt always 'gives' the + * semaphore and another always 'takes' the semaphore) and from within interrupt + * service routines. + * + * @return If the mutex was successfully created then a handle to the created + * semaphore is returned. If there was not enough heap to allocate the mutex + * data structures then NULL is returned. + * + * Example usage: + *
+ * 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 + * https://www.FreeRTOS.org/a00111.html). If a mutex is created using + * xSemaphoreCreateMutexStatic() then the application writer must provided the + * memory. xSemaphoreCreateMutexStatic() therefore allows a mutex to be created + * without using any dynamic memory allocation. + * + * Mutexes created using this function can be accessed using the xSemaphoreTake() + * and xSemaphoreGive() macros. The xSemaphoreTakeRecursive() and + * xSemaphoreGiveRecursive() macros must not be used. + * + * This type of semaphore uses a priority inheritance mechanism so a task + * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the + * semaphore it is no longer required. + * + * Mutex type semaphores cannot be used from within interrupt service routines. + * + * See xSemaphoreCreateBinary() for an alternative implementation that can be + * used for pure synchronisation (where one task or interrupt always 'gives' the + * semaphore and another always 'takes' the semaphore) and from within interrupt + * service routines. + * + * @param pxMutexBuffer Must point to a variable of type StaticSemaphore_t, + * which will be used to hold the mutex's data structure, removing the need for + * the memory to be allocated dynamically. + * + * @return If the mutex was successfully created then a handle to the created + * mutex is returned. If pxMutexBuffer was NULL then NULL is returned. + * + * Example usage: + *
+ * 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 + * https://www.FreeRTOS.org/a00111.html). If a recursive mutex is created using + * xSemaphoreCreateRecursiveMutexStatic() then the application writer must + * provide the memory that will get used by the mutex. + * xSemaphoreCreateRecursiveMutexStatic() therefore allows a recursive mutex to + * be created without using any dynamic memory allocation. + * + * Mutexes created using this macro can be accessed using the + * xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros. The + * xSemaphoreTake() and xSemaphoreGive() macros must not be used. + * + * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex + * doesn't become available again until the owner has called + * xSemaphoreGiveRecursive() for each successful 'take' request. For example, + * if a task successfully 'takes' the same mutex 5 times then the mutex will + * not be available to any other task until it has also 'given' the mutex back + * exactly five times. + * + * This type of semaphore uses a priority inheritance mechanism so a task + * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the + * semaphore it is no longer required. + * + * Mutex type semaphores cannot be used from within interrupt service routines. + * + * See xSemaphoreCreateBinary() for an alternative implementation that can be + * used for pure synchronisation (where one task or interrupt always 'gives' the + * semaphore and another always 'takes' the semaphore) and from within interrupt + * service routines. + * + * @return xSemaphore Handle to the created mutex semaphore. Should be of type + * SemaphoreHandle_t. + * + * Example usage: + *
+ * 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 + * https://www.FreeRTOS.org/a00111.html). If a recursive mutex is created using + * xSemaphoreCreateRecursiveMutexStatic() then the application writer must + * provide the memory that will get used by the mutex. + * xSemaphoreCreateRecursiveMutexStatic() therefore allows a recursive mutex to + * be created without using any dynamic memory allocation. + * + * Mutexes created using this macro can be accessed using the + * xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros. The + * xSemaphoreTake() and xSemaphoreGive() macros must not be used. + * + * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex + * doesn't become available again until the owner has called + * xSemaphoreGiveRecursive() for each successful 'take' request. For example, + * if a task successfully 'takes' the same mutex 5 times then the mutex will + * not be available to any other task until it has also 'given' the mutex back + * exactly five times. + * + * This type of semaphore uses a priority inheritance mechanism so a task + * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the + * semaphore it is no longer required. + * + * Mutex type semaphores cannot be used from within interrupt service routines. + * + * See xSemaphoreCreateBinary() for an alternative implementation that can be + * used for pure synchronisation (where one task or interrupt always 'gives' the + * semaphore and another always 'takes' the semaphore) and from within interrupt + * service routines. + * + * @param pxMutexBuffer Must point to a variable of type StaticSemaphore_t, + * which will then be used to hold the recursive mutex's data structure, + * removing the need for the memory to be allocated dynamically. + * + * @return If the recursive mutex was successfully created then a handle to the + * created recursive mutex is returned. If pxMutexBuffer was NULL then NULL is + * returned. + * + * Example usage: + *
+ * 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! + * https://www.FreeRTOS.org/RTOS-task-notifications.html + * + * Internally, within the FreeRTOS implementation, counting semaphores use a + * block of memory, in which the counting semaphore structure is stored. If a + * counting semaphore is created using xSemaphoreCreateCounting() then the + * required memory is automatically dynamically allocated inside the + * xSemaphoreCreateCounting() function. (see + * https://www.FreeRTOS.org/a00111.html). If a counting semaphore is created + * using xSemaphoreCreateCountingStatic() then the application writer can + * instead optionally provide the memory that will get used by the counting + * semaphore. xSemaphoreCreateCountingStatic() therefore allows a counting + * semaphore to be created without using any dynamic memory allocation. + * + * Counting semaphores are typically used for two things: + * + * 1) Counting events. + * + * In this usage scenario an event handler will 'give' a semaphore each time + * an event occurs (incrementing the semaphore count value), and a handler + * task will 'take' a semaphore each time it processes an event + * (decrementing the semaphore count value). The count value is therefore + * the difference between the number of events that have occurred and the + * number that have been processed. In this case it is desirable for the + * initial count value to be zero. + * + * 2) Resource management. + * + * In this usage scenario the count value indicates the number of resources + * available. To obtain control of a resource a task must first obtain a + * semaphore - decrementing the semaphore count value. When the count value + * reaches zero there are no free resources. When a task finishes with the + * resource it 'gives' the semaphore back - incrementing the semaphore count + * value. In this case it is desirable for the initial count value to be + * equal to the maximum count value, indicating that all resources are free. + * + * @param uxMaxCount The maximum count value that can be reached. When the + * semaphore reaches this value it can no longer be 'given'. + * + * @param uxInitialCount The count value assigned to the semaphore when it is + * created. + * + * @return Handle to the created semaphore. Null if the semaphore could not be + * created. + * + * Example usage: + *
+ * 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! + * https://www.FreeRTOS.org/RTOS-task-notifications.html + * + * Internally, within the FreeRTOS implementation, counting semaphores use a + * block of memory, in which the counting semaphore structure is stored. If a + * counting semaphore is created using xSemaphoreCreateCounting() then the + * required memory is automatically dynamically allocated inside the + * xSemaphoreCreateCounting() function. (see + * https://www.FreeRTOS.org/a00111.html). If a counting semaphore is created + * using xSemaphoreCreateCountingStatic() then the application writer must + * provide the memory. xSemaphoreCreateCountingStatic() therefore allows a + * counting semaphore to be created without using any dynamic memory allocation. + * + * Counting semaphores are typically used for two things: + * + * 1) Counting events. + * + * In this usage scenario an event handler will 'give' a semaphore each time + * an event occurs (incrementing the semaphore count value), and a handler + * task will 'take' a semaphore each time it processes an event + * (decrementing the semaphore count value). The count value is therefore + * the difference between the number of events that have occurred and the + * number that have been processed. In this case it is desirable for the + * initial count value to be zero. + * + * 2) Resource management. + * + * In this usage scenario the count value indicates the number of resources + * available. To obtain control of a resource a task must first obtain a + * semaphore - decrementing the semaphore count value. When the count value + * reaches zero there are no free resources. When a task finishes with the + * resource it 'gives' the semaphore back - incrementing the semaphore count + * value. In this case it is desirable for the initial count value to be + * equal to the maximum count value, indicating that all resources are free. + * + * @param uxMaxCount The maximum count value that can be reached. When the + * semaphore reaches this value it can no longer be 'given'. + * + * @param uxInitialCount The count value assigned to the semaphore when it is + * created. + * + * @param pxSemaphoreBuffer Must point to a variable of type StaticSemaphore_t, + * which will then be used to hold the semaphore's data structure, removing the + * need for the memory to be allocated dynamically. + * + * @return If the counting semaphore was successfully created then a handle to + * the created counting semaphore is returned. If pxSemaphoreBuffer was NULL + * then NULL is returned. + * + * Example usage: + *
+ * 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/examples/stm32/freertos-kernel/include/stack_macros.h b/examples/stm32/freertos-kernel/include/stack_macros.h new file mode 100644 index 00000000..c8ef4bd3 --- /dev/null +++ b/examples/stm32/freertos-kernel/include/stack_macros.h @@ -0,0 +1,127 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#ifndef 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/examples/stm32/freertos-kernel/include/stdint.readme b/examples/stm32/freertos-kernel/include/stdint.readme new file mode 100644 index 00000000..b1bb60ea --- /dev/null +++ b/examples/stm32/freertos-kernel/include/stdint.readme @@ -0,0 +1,52 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#ifndef FREERTOS_STDINT +#define FREERTOS_STDINT + +/******************************************************************************* + * THIS IS NOT A FULL stdint.h IMPLEMENTATION - It only contains the definitions + * necessary to build the FreeRTOS code. It is provided to allow FreeRTOS to be + * built using compilers that do not provide their own stdint.h definition. + * + * To use this file: + * + * 1) Copy this file into the directory that contains your FreeRTOSConfig.h + * header file, as that directory will already be in the compiler's include + * path. + * + * 2) Rename the copied file stdint.h. + * + */ + +typedef signed char int8_t; +typedef unsigned char uint8_t; +typedef short int16_t; +typedef unsigned short uint16_t; +typedef long int32_t; +typedef unsigned long uint32_t; + +#endif /* FREERTOS_STDINT */ diff --git a/examples/stm32/freertos-kernel/include/stream_buffer.h b/examples/stm32/freertos-kernel/include/stream_buffer.h new file mode 100644 index 00000000..89f6dfb2 --- /dev/null +++ b/examples/stm32/freertos-kernel/include/stream_buffer.h @@ -0,0 +1,867 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* + * Stream buffers are used to send a continuous stream of data from one task or + * interrupt to another. Their implementation is light weight, making them + * particularly suited for interrupt to task and core to core communication + * scenarios. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xStreamBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xStreamBufferReceive()) inside a critical section section and set the + * receive block time to 0. + * + */ + +#ifndef STREAM_BUFFER_H +#define STREAM_BUFFER_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h must appear in source files before include stream_buffer.h" +#endif + +/* *INDENT-OFF* */ +#if defined( __cplusplus ) + extern "C" { +#endif +/* *INDENT-ON* */ + +/** + * Type by which stream buffers are referenced. For example, a call to + * xStreamBufferCreate() returns an StreamBufferHandle_t variable that can + * then be used as a parameter to xStreamBufferSend(), xStreamBufferReceive(), + * etc. + */ +struct StreamBufferDef_t; +typedef struct StreamBufferDef_t * StreamBufferHandle_t; + + +/** + * 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 + +/* *INDENT-OFF* */ +#if defined( __cplusplus ) + } +#endif +/* *INDENT-ON* */ + +#endif /* !defined( STREAM_BUFFER_H ) */ diff --git a/examples/stm32/freertos-kernel/include/task.h b/examples/stm32/freertos-kernel/include/task.h new file mode 100644 index 00000000..66c99c56 --- /dev/null +++ b/examples/stm32/freertos-kernel/include/task.h @@ -0,0 +1,3053 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + + +#ifndef INC_TASK_H +#define INC_TASK_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h must appear in source files before include task.h" +#endif + +#include "list.h" + +/* *INDENT-OFF* */ +#ifdef __cplusplus + extern "C" { +#endif +/* *INDENT-ON* */ + +/*----------------------------------------------------------- +* MACROS AND DEFINITIONS +*----------------------------------------------------------*/ + +#define tskKERNEL_VERSION_NUMBER "V10.4.3" +#define tskKERNEL_VERSION_MAJOR 10 +#define tskKERNEL_VERSION_MINOR 4 +#define tskKERNEL_VERSION_BUILD 3 + +/* MPU region parameters passed in ulParameters + * of MemoryRegion_t struct. */ +#define tskMPU_REGION_READ_ONLY ( 1UL << 0UL ) +#define tskMPU_REGION_READ_WRITE ( 1UL << 1UL ) +#define tskMPU_REGION_EXECUTE_NEVER ( 1UL << 2UL ) +#define tskMPU_REGION_NORMAL_MEMORY ( 1UL << 3UL ) +#define tskMPU_REGION_DEVICE_MEMORY ( 1UL << 4UL ) + +/* The direct to task notification feature used to have only a single notification + * per task. Now there is an array of notifications per task that is dimensioned by + * configTASK_NOTIFICATION_ARRAY_ENTRIES. For backward compatibility, any use of the + * original direct to task notification defaults to using the first index in the + * array. */ +#define tskDEFAULT_INDEX_TO_NOTIFY ( 0 ) + +/** + * task. h + * + * Type by which tasks are referenced. For example, a call to xTaskCreate + * returns (via a pointer parameter) an TaskHandle_t variable that can then + * be used as a parameter to vTaskDelete to delete the task. + * + * \defgroup TaskHandle_t TaskHandle_t + * \ingroup Tasks + */ +struct tskTaskControlBlock; /* The old naming convention is used to prevent breaking kernel aware debuggers. */ +typedef struct tskTaskControlBlock * TaskHandle_t; + +/* + * Defines the prototype to which the application task hook function must + * conform. + */ +typedef BaseType_t (* TaskHookFunction_t)( void * ); + +/* Task states returned by eTaskGetState. */ +typedef enum +{ + eRunning = 0, /* A task is querying the state of itself, so must be running. */ + eReady, /* The task being queried is in a 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 * 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 https://www.FreeRTOS.org/rtos-run-time-stats.html. Only valid when configGENERATE_RUN_TIME_STATS is defined as 1 in FreeRTOSConfig.h. */ + StackType_t * pxStackBase; /* Points to the lowest address of the task's stack area. */ + configSTACK_DEPTH_TYPE usStackHighWaterMark; /* The minimum amount of stack space that has remained for the task since the task was created. The closer this value is to zero the closer the task has come to overflowing its stack. */ +} TaskStatus_t; + +/* Possible return values for eTaskConfirmSleepModeStatus(). */ +typedef enum +{ + eAbortSleep = 0, /* A task has been made ready or a context switch pended since 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 + * https://www.FreeRTOS.org/a00111.html). If a task is created using + * xTaskCreateStatic() then the application writer must provide the required + * memory. xTaskCreateStatic() therefore allows a task to be created without + * using any dynamic memory allocation. + * + * See xTaskCreateStatic() for a version that does not use any dynamic memory + * allocation. + * + * xTaskCreate() can only be used to create a task that has unrestricted + * access to the entire microcontroller memory map. Systems that include MPU + * support can alternatively create an MPU constrained task using + * xTaskCreateRestricted(). + * + * @param 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 + * https://www.FreeRTOS.org/a00111.html). If a task is created using + * xTaskCreateStatic() then the application writer must provide the required + * memory. xTaskCreateStatic() therefore allows a task to be created without + * using any dynamic memory allocation. + * + * @param 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 xTaskDelayUntil() for an alternative API function designed + * to facilitate fixed frequency execution. It does this by specifying an + * absolute time (rather than a relative time) at which the calling task should + * unblock. + * + * @param xTicksToDelay The amount of time, in tick periods, that + * the calling task should block. + * + * Example usage: + * + * void vTaskFunction( void * pvParameters ) + * { + * // Block for 500ms. + * const TickType_t xDelay = 500 / portTICK_PERIOD_MS; + * + * for( ;; ) + * { + * // Simply toggle the LED every 500ms, blocking between each toggle. + * vToggleLED(); + * vTaskDelay( xDelay ); + * } + * } + * + * \defgroup vTaskDelay vTaskDelay + * \ingroup TaskCtrl + */ +void vTaskDelay( const TickType_t xTicksToDelay ) PRIVILEGED_FUNCTION; + +/** + * task. h + *
+ * BaseType_t xTaskDelayUntil( TickType_t *pxPreviousWakeTime, const TickType_t xTimeIncrement );
+ * 
+ * + * INCLUDE_xTaskDelayUntil must be defined as 1 for this function to be available. + * See the configuration section for more information. + * + * Delay a task until a specified time. This function can be used by periodic + * tasks to ensure a constant execution frequency. + * + * This function differs from vTaskDelay () in one important aspect: vTaskDelay () will + * cause a task to block for the specified number of ticks from the time vTaskDelay () is + * called. It is therefore difficult to use vTaskDelay () by itself to generate a fixed + * execution frequency as the time between a task starting to execute and that task + * calling vTaskDelay () may not be fixed [the task may take a different path though the + * code between calls, or may get interrupted or preempted a different number of times + * each time it executes]. + * + * Whereas vTaskDelay () specifies a wake time relative to the time at which the function + * is called, xTaskDelayUntil () specifies the absolute (exact) time at which it wishes to + * unblock. + * + * The macro pdMS_TO_TICKS() can be used to calculate the number of ticks from a + * time specified in milliseconds with a resolution of one tick period. + * + * @param pxPreviousWakeTime Pointer to a variable that holds the time at which the + * task was last unblocked. The variable must be initialised with the current time + * prior to its first use (see the example below). Following this the variable is + * automatically updated within xTaskDelayUntil (). + * + * @param xTimeIncrement The cycle time period. The task will be unblocked at + * time *pxPreviousWakeTime + xTimeIncrement. Calling xTaskDelayUntil with the + * same xTimeIncrement parameter value will cause the task to execute with + * a fixed interface period. + * + * @return Value which can be used to check whether the task was actually delayed. + * Will be pdTRUE if the task way delayed and pdFALSE otherwise. A task will not + * be delayed if the next expected wake time is in the past. + * + * Example usage: + *
+ * // Perform an action every 10 ticks.
+ * void vTaskFunction( void * pvParameters )
+ * {
+ * TickType_t xLastWakeTime;
+ * const TickType_t xFrequency = 10;
+ * BaseType_t xWasDelayed;
+ *
+ *     // Initialise the xLastWakeTime variable with the current time.
+ *     xLastWakeTime = xTaskGetTickCount ();
+ *     for( ;; )
+ *     {
+ *         // Wait for the next cycle.
+ *         xWasDelayed = xTaskDelayUntil( &xLastWakeTime, xFrequency );
+ *
+ *         // Perform action here. xWasDelayed value can be used to determine
+ *         // whether a deadline was missed if the code here took too long.
+ *     }
+ * }
+ * 
+ * \defgroup xTaskDelayUntil xTaskDelayUntil + * \ingroup TaskCtrl + */ +BaseType_t xTaskDelayUntil( TickType_t * const pxPreviousWakeTime, + const TickType_t xTimeIncrement ) PRIVILEGED_FUNCTION; + +/* + * vTaskDelayUntil() is the older version of xTaskDelayUntil() and does not + * return a value. + */ +#define vTaskDelayUntil( pxPreviousWakeTime, xTimeIncrement ) \ +{ \ + ( void ) xTaskDelayUntil( pxPreviousWakeTime, xTimeIncrement ); \ +} + + +/** + * task. h + *
+ * 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, + * xTaskDelayUntil(), 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 + +#if ( configCHECK_FOR_STACK_OVERFLOW > 0 ) + + /** + * task.h + *
void vApplicationStackOverflowHook( TaskHandle_t xTask char *pcTaskName); 
+ * + * The application stack overflow hook is called when a stack overflow is detected for a task. + * + * Details on stack overflow detection can be found here: https://www.FreeRTOS.org/Stacks-and-stack-overflow-checking.html + * + * @param xTask the task that just exceeded its stack boundaries. + * @param pcTaskName A character string containing the name of the offending task. + */ + void vApplicationStackOverflowHook( TaskHandle_t xTask, + char * pcTaskName ); + +#endif + +#if ( configUSE_TICK_HOOK > 0 ) + /** + * task.h + *
void vApplicationTickHook( void ); 
+ * + * This hook function is called in the system tick handler after any OS work is completed. + */ + void vApplicationTickHook( void ); /*lint !e526 Symbol not defined as it is an application callback. */ + +#endif + +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + /** + * task.h + *
void vApplicationGetIdleTaskMemory( StaticTask_t ** ppxIdleTaskTCBBuffer, StackType_t ** ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize ) 
+ * + * This function is used to provide a statically allocated block of memory to FreeRTOS to hold the Idle Task TCB. This function is required when + * configSUPPORT_STATIC_ALLOCATION is set. For more information see this URI: https://www.FreeRTOS.org/a00110.html#configSUPPORT_STATIC_ALLOCATION + * + * @param ppxIdleTaskTCBBuffer A handle to a statically allocated TCB buffer + * @param ppxIdleTaskStackBuffer A handle to a statically allocated Stack buffer for thie idle task + * @param pulIdleTaskStackSize A pointer to the number of elements that will fit in the allocated stack buffer + */ + void vApplicationGetIdleTaskMemory( StaticTask_t ** ppxIdleTaskTCBBuffer, + StackType_t ** ppxIdleTaskStackBuffer, + uint32_t * pulIdleTaskStackSize ); /*lint !e526 Symbol not defined as it is an application callback. */ +#endif + +/** + * task.h + *
+ * 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 + * https://www.FreeRTOS.org/rtos-run-time-stats.html) since the target booted. + * pulTotalRunTime can be set to NULL to omit the total run time information. + * + * @return The number of TaskStatus_t structures that were populated by + * uxTaskGetSystemState(). This should equal the number returned by the + * uxTaskGetNumberOfTasks() API function, but will be zero if the value passed + * in the uxArraySize parameter was too small. + * + * Example usage: + *
+ *  // 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 xTaskNotifyIndexed( TaskHandle_t xTaskToNotify, UBaseType_t uxIndexToNotify, uint32_t ulValue, eNotifyAction eAction );
+ *
BaseType_t xTaskNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction );
+ * + * See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. + * + * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for these + * functions to be available. + * + * Sends a direct to task notification to a task, with an optional value and + * action. + * + * Each task has a private array of "notification values" (or 'notifications'), + * each of which is a 32-bit unsigned integer (uint32_t). The constant + * configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the + * array, and (for backward compatibility) defaults to 1 if left undefined. + * Prior to FreeRTOS V10.4.0 there was only one notification value per task. + * + * Events can be sent to a task using an intermediary object. Examples of such + * objects are queues, semaphores, mutexes and event groups. Task notifications + * are a method of sending an event directly to a task without the need for such + * an intermediary object. + * + * A notification sent to a task can optionally perform an action, such as + * update, overwrite or increment one of the task's notification values. In + * that way task notifications can be used to send data to a task, or be used as + * light weight and fast binary or counting semaphores. + * + * A task can use xTaskNotifyWaitIndexed() to [optionally] block to wait for a + * notification to be pending, or ulTaskNotifyTakeIndexed() to [optionally] block + * to wait for a notification value to have a non-zero value. The task does + * not consume any CPU time while it is in the Blocked state. + * + * A notification sent to a task will remain pending until it is cleared by the + * task calling xTaskNotifyWaitIndexed() or ulTaskNotifyTakeIndexed() (or their + * un-indexed equivalents). If the task was already in the Blocked state to + * wait for a notification when the notification arrives then the task will + * automatically be removed from the Blocked state (unblocked) and the + * notification cleared. + * + * **NOTE** Each notification within the array operates independently - a task + * can only block on one notification within the array at a time and will not be + * unblocked by a notification sent to any other array index. + * + * Backward compatibility information: + * Prior to FreeRTOS V10.4.0 each task had a single "notification value", and + * all task notification API functions operated on that value. Replacing the + * single notification value with an array of notification values necessitated a + * new set of API functions that could address specific notifications within the + * array. xTaskNotify() is the original API function, and remains backward + * compatible by always operating on the notification value at index 0 in the + * array. Calling xTaskNotify() is equivalent to calling xTaskNotifyIndexed() + * with the uxIndexToNotify parameter set to 0. + * + * @param xTaskToNotify The handle of the task being notified. The handle to a + * task can be returned from the xTaskCreate() API function used to create the + * task, and the handle of the currently running task can be obtained by calling + * xTaskGetCurrentTaskHandle(). + * + * @param uxIndexToNotify The index within the target task's array of + * notification values to which the notification is to be sent. uxIndexToNotify + * must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotify() does + * not have this parameter and always sends notifications to index 0. + * + * @param ulValue Data that can be sent with the notification. How the data is + * used depends on the value of the eAction parameter. + * + * @param eAction Specifies how the notification updates the task's notification + * value, if at all. Valid values for eAction are as follows: + * + * eSetBits - + * The target notification value is bitwise ORed with ulValue. + * xTaskNofifyIndexed() always returns pdPASS in this case. + * + * eIncrement - + * The target notification value is incremented. ulValue is not used and + * xTaskNotifyIndexed() always returns pdPASS in this case. + * + * eSetValueWithOverwrite - + * The target notification value is set to the value of ulValue, even if the + * task being notified had not yet processed the previous notification at the + * same array index (the task already had a notification pending at that index). + * xTaskNotifyIndexed() always returns pdPASS in this case. + * + * eSetValueWithoutOverwrite - + * If the task being notified did not already have a notification pending at the + * same array index then the target notification value is set to ulValue and + * xTaskNotifyIndexed() will return pdPASS. If the task being notified already + * had a notification pending at the same array index then no action is + * performed and pdFAIL is returned. + * + * eNoAction - + * The task receives a notification at the specified array index without the + * notification value at that index being updated. ulValue is not used and + * xTaskNotifyIndexed() always returns pdPASS in this case. + * + * pulPreviousNotificationValue - + * Can be used to pass out the subject task's notification value before any + * bits are modified by the notify function. + * + * @return Dependent on the value of eAction. See the description of the + * eAction parameter. + * + * \defgroup xTaskNotifyIndexed xTaskNotifyIndexed + * \ingroup TaskNotifications + */ +BaseType_t xTaskGenericNotify( TaskHandle_t xTaskToNotify, + UBaseType_t uxIndexToNotify, + uint32_t ulValue, + eNotifyAction eAction, + uint32_t * pulPreviousNotificationValue ) PRIVILEGED_FUNCTION; +#define xTaskNotify( xTaskToNotify, ulValue, eAction ) \ + xTaskGenericNotify( ( xTaskToNotify ), ( tskDEFAULT_INDEX_TO_NOTIFY ), ( ulValue ), ( eAction ), NULL ) +#define xTaskNotifyIndexed( xTaskToNotify, uxIndexToNotify, ulValue, eAction ) \ + xTaskGenericNotify( ( xTaskToNotify ), ( uxIndexToNotify ), ( ulValue ), ( eAction ), NULL ) + +/** + * task. h + *
BaseType_t xTaskNotifyAndQueryIndexed( TaskHandle_t xTaskToNotify, UBaseType_t uxIndexToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotifyValue );
+ *
BaseType_t xTaskNotifyAndQuery( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotifyValue );
+ * + * See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. + * + * xTaskNotifyAndQueryIndexed() performs the same operation as + * xTaskNotifyIndexed() with the addition that it also returns the subject + * task's prior notification value (the notification value at the time the + * function is called rather than when the function returns) in the additional + * pulPreviousNotifyValue parameter. + * + * xTaskNotifyAndQuery() performs the same operation as xTaskNotify() with the + * addition that it also returns the subject task's prior notification value + * (the notification value as it was at the time the function is called, rather + * than when the function returns) in the additional pulPreviousNotifyValue + * parameter. + * + * \defgroup xTaskNotifyAndQueryIndexed xTaskNotifyAndQueryIndexed + * \ingroup TaskNotifications + */ +#define xTaskNotifyAndQuery( xTaskToNotify, ulValue, eAction, pulPreviousNotifyValue ) \ + xTaskGenericNotify( ( xTaskToNotify ), ( tskDEFAULT_INDEX_TO_NOTIFY ), ( ulValue ), ( eAction ), ( pulPreviousNotifyValue ) ) +#define xTaskNotifyAndQueryIndexed( xTaskToNotify, uxIndexToNotify, ulValue, eAction, pulPreviousNotifyValue ) \ + xTaskGenericNotify( ( xTaskToNotify ), ( uxIndexToNotify ), ( ulValue ), ( eAction ), ( pulPreviousNotifyValue ) ) + +/** + * task. h + *
BaseType_t xTaskNotifyIndexedFromISR( TaskHandle_t xTaskToNotify, UBaseType_t uxIndexToNotify, uint32_t ulValue, eNotifyAction eAction, BaseType_t *pxHigherPriorityTaskWoken );
+ *
BaseType_t xTaskNotifyFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, BaseType_t *pxHigherPriorityTaskWoken );
+ * + * See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. + * + * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for these + * functions to be available. + * + * A version of xTaskNotifyIndexed() that can be used from an interrupt service + * routine (ISR). + * + * Each task has a private array of "notification values" (or 'notifications'), + * each of which is a 32-bit unsigned integer (uint32_t). The constant + * configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the + * array, and (for backward compatibility) defaults to 1 if left undefined. + * Prior to FreeRTOS V10.4.0 there was only one notification value per task. + * + * Events can be sent to a task using an intermediary object. Examples of such + * objects are queues, semaphores, mutexes and event groups. Task notifications + * are a method of sending an event directly to a task without the need for such + * an intermediary object. + * + * A notification sent to a task can optionally perform an action, such as + * update, overwrite or increment one of the task's notification values. In + * that way task notifications can be used to send data to a task, or be used as + * light weight and fast binary or counting semaphores. + * + * A task can use xTaskNotifyWaitIndexed() to [optionally] block to wait for a + * notification to be pending, or ulTaskNotifyTakeIndexed() to [optionally] block + * to wait for a notification value to have a non-zero value. The task does + * not consume any CPU time while it is in the Blocked state. + * + * A notification sent to a task will remain pending until it is cleared by the + * task calling xTaskNotifyWaitIndexed() or ulTaskNotifyTakeIndexed() (or their + * un-indexed equivalents). If the task was already in the Blocked state to + * wait for a notification when the notification arrives then the task will + * automatically be removed from the Blocked state (unblocked) and the + * notification cleared. + * + * **NOTE** Each notification within the array operates independently - a task + * can only block on one notification within the array at a time and will not be + * unblocked by a notification sent to any other array index. + * + * Backward compatibility information: + * Prior to FreeRTOS V10.4.0 each task had a single "notification value", and + * all task notification API functions operated on that value. Replacing the + * single notification value with an array of notification values necessitated a + * new set of API functions that could address specific notifications within the + * array. xTaskNotifyFromISR() is the original API function, and remains + * backward compatible by always operating on the notification value at index 0 + * within the array. Calling xTaskNotifyFromISR() is equivalent to calling + * xTaskNotifyIndexedFromISR() with the uxIndexToNotify parameter set to 0. + * + * @param uxIndexToNotify The index within the target task's array of + * notification values to which the notification is to be sent. uxIndexToNotify + * must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyFromISR() + * does not have this parameter and always sends notifications to index 0. + * + * @param xTaskToNotify The handle of the task being notified. The handle to a + * task can be returned from the xTaskCreate() API function used to create the + * task, and the handle of the currently running task can be obtained by calling + * xTaskGetCurrentTaskHandle(). + * + * @param ulValue Data that can be sent with the notification. How the data is + * used depends on the value of the eAction parameter. + * + * @param eAction Specifies how the notification updates the task's notification + * value, if at all. Valid values for eAction are as follows: + * + * eSetBits - + * The task's notification value is bitwise ORed with ulValue. 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 xTaskNotifyIndexedFromISR xTaskNotifyIndexedFromISR + * \ingroup TaskNotifications + */ +BaseType_t xTaskGenericNotifyFromISR( TaskHandle_t xTaskToNotify, + UBaseType_t uxIndexToNotify, + uint32_t ulValue, + eNotifyAction eAction, + uint32_t * pulPreviousNotificationValue, + BaseType_t * pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; +#define xTaskNotifyFromISR( xTaskToNotify, ulValue, eAction, pxHigherPriorityTaskWoken ) \ + xTaskGenericNotifyFromISR( ( xTaskToNotify ), ( tskDEFAULT_INDEX_TO_NOTIFY ), ( ulValue ), ( eAction ), NULL, ( pxHigherPriorityTaskWoken ) ) +#define xTaskNotifyIndexedFromISR( xTaskToNotify, uxIndexToNotify, ulValue, eAction, pxHigherPriorityTaskWoken ) \ + xTaskGenericNotifyFromISR( ( xTaskToNotify ), ( uxIndexToNotify ), ( ulValue ), ( eAction ), NULL, ( pxHigherPriorityTaskWoken ) ) + +/** + * task. h + *
BaseType_t xTaskNotifyAndQueryIndexedFromISR( TaskHandle_t xTaskToNotify, UBaseType_t uxIndexToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue, BaseType_t *pxHigherPriorityTaskWoken );
+ *
BaseType_t xTaskNotifyAndQueryFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue, BaseType_t *pxHigherPriorityTaskWoken );
+ * + * See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. + * + * xTaskNotifyAndQueryIndexedFromISR() performs the same operation as + * xTaskNotifyIndexedFromISR() with the addition that it also returns the + * subject task's prior notification value (the notification value at the time + * the function is called rather than at the time the function returns) in the + * additional pulPreviousNotifyValue parameter. + * + * xTaskNotifyAndQueryFromISR() performs the same operation as + * xTaskNotifyFromISR() with the addition that it also returns the subject + * task's prior notification value (the notification value at the time the + * function is called rather than at the time the function returns) in the + * additional pulPreviousNotifyValue parameter. + * + * \defgroup xTaskNotifyAndQueryIndexedFromISR xTaskNotifyAndQueryIndexedFromISR + * \ingroup TaskNotifications + */ +#define xTaskNotifyAndQueryIndexedFromISR( xTaskToNotify, uxIndexToNotify, ulValue, eAction, pulPreviousNotificationValue, pxHigherPriorityTaskWoken ) \ + xTaskGenericNotifyFromISR( ( xTaskToNotify ), ( uxIndexToNotify ), ( ulValue ), ( eAction ), ( pulPreviousNotificationValue ), ( pxHigherPriorityTaskWoken ) ) +#define xTaskNotifyAndQueryFromISR( xTaskToNotify, ulValue, eAction, pulPreviousNotificationValue, pxHigherPriorityTaskWoken ) \ + xTaskGenericNotifyFromISR( ( xTaskToNotify ), ( tskDEFAULT_INDEX_TO_NOTIFY ), ( ulValue ), ( eAction ), ( pulPreviousNotificationValue ), ( pxHigherPriorityTaskWoken ) ) + +/** + * task. h + *
+ * BaseType_t xTaskNotifyWaitIndexed( UBaseType_t uxIndexToWaitOn, uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait );
+ *
+ * BaseType_t xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait );
+ * 
+ * + * Waits for a direct to task notification to be pending at a given index within + * an array of direct to task notifications. + * + * See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. + * + * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this + * function to be available. + * + * Each task has a private array of "notification values" (or 'notifications'), + * each of which is a 32-bit unsigned integer (uint32_t). The constant + * configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the + * array, and (for backward compatibility) defaults to 1 if left undefined. + * Prior to FreeRTOS V10.4.0 there was only one notification value per task. + * + * Events can be sent to a task using an intermediary object. Examples of such + * objects are queues, semaphores, mutexes and event groups. Task notifications + * are a method of sending an event directly to a task without the need for such + * an intermediary object. + * + * A notification sent to a task can optionally perform an action, such as + * update, overwrite or increment one of the task's notification values. In + * that way task notifications can be used to send data to a task, or be used as + * light weight and fast binary or counting semaphores. + * + * A notification sent to a task will remain pending until it is cleared by the + * task calling xTaskNotifyWaitIndexed() or ulTaskNotifyTakeIndexed() (or their + * un-indexed equivalents). If the task was already in the Blocked state to + * wait for a notification when the notification arrives then the task will + * automatically be removed from the Blocked state (unblocked) and the + * notification cleared. + * + * A task can use xTaskNotifyWaitIndexed() to [optionally] block to wait for a + * notification to be pending, or ulTaskNotifyTakeIndexed() to [optionally] block + * to wait for a notification value to have a non-zero value. The task does + * not consume any CPU time while it is in the Blocked state. + * + * **NOTE** Each notification within the array operates independently - a task + * can only block on one notification within the array at a time and will not be + * unblocked by a notification sent to any other array index. + * + * Backward compatibility information: + * Prior to FreeRTOS V10.4.0 each task had a single "notification value", and + * all task notification API functions operated on that value. Replacing the + * single notification value with an array of notification values necessitated a + * new set of API functions that could address specific notifications within the + * array. xTaskNotifyWait() is the original API function, and remains backward + * compatible by always operating on the notification value at index 0 in the + * array. Calling xTaskNotifyWait() is equivalent to calling + * xTaskNotifyWaitIndexed() with the uxIndexToWaitOn parameter set to 0. + * + * @param uxIndexToWaitOn The index within the calling task's array of + * notification values on which the calling task will wait for a notification to + * be received. uxIndexToWaitOn must be less than + * configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyWait() does + * not have this parameter and always waits for notifications on index 0. + * + * @param ulBitsToClearOnEntry Bits that are set in ulBitsToClearOnEntry value + * will be cleared in the calling task's notification value before the task + * checks to see if any notifications are pending, and optionally blocks if no + * notifications are pending. Setting ulBitsToClearOnEntry to ULONG_MAX (if + * limits.h is included) or 0xffffffffUL (if limits.h is not included) will have + * the effect of resetting the task's notification value to 0. Setting + * ulBitsToClearOnEntry to 0 will leave the task's notification value unchanged. + * + * @param ulBitsToClearOnExit If a notification is pending or received before + * the calling task exits the xTaskNotifyWait() function then the task's + * notification value (see the xTaskNotify() API function) is passed out using + * the pulNotificationValue parameter. Then any bits that are set in + * ulBitsToClearOnExit will be cleared in the task's notification value (note + * *pulNotificationValue is set before any bits are cleared). Setting + * ulBitsToClearOnExit to ULONG_MAX (if limits.h is included) or 0xffffffffUL + * (if limits.h is not included) will have the effect of resetting the task's + * notification value to 0 before the function exits. Setting + * ulBitsToClearOnExit to 0 will leave the task's notification value unchanged + * when the function exits (in which case the value passed out in + * pulNotificationValue will match the task's notification value). + * + * @param pulNotificationValue Used to pass the task's notification value out + * of the function. Note the value passed out will not be effected by the + * clearing of any bits caused by ulBitsToClearOnExit being non-zero. + * + * @param xTicksToWait The maximum amount of time that the task should wait in + * the Blocked state for a notification to be received, should a notification + * not already be pending when xTaskNotifyWait() was called. The task + * will not consume any processing time while it is in the Blocked state. This + * is specified in kernel ticks, the macro pdMS_TO_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 xTaskNotifyWaitIndexed xTaskNotifyWaitIndexed + * \ingroup TaskNotifications + */ +BaseType_t xTaskGenericNotifyWait( UBaseType_t uxIndexToWaitOn, + uint32_t ulBitsToClearOnEntry, + uint32_t ulBitsToClearOnExit, + uint32_t * pulNotificationValue, + TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; +#define xTaskNotifyWait( ulBitsToClearOnEntry, ulBitsToClearOnExit, pulNotificationValue, xTicksToWait ) \ + xTaskGenericNotifyWait( tskDEFAULT_INDEX_TO_NOTIFY, ( ulBitsToClearOnEntry ), ( ulBitsToClearOnExit ), ( pulNotificationValue ), ( xTicksToWait ) ) +#define xTaskNotifyWaitIndexed( uxIndexToWaitOn, ulBitsToClearOnEntry, ulBitsToClearOnExit, pulNotificationValue, xTicksToWait ) \ + xTaskGenericNotifyWait( ( uxIndexToWaitOn ), ( ulBitsToClearOnEntry ), ( ulBitsToClearOnExit ), ( pulNotificationValue ), ( xTicksToWait ) ) + +/** + * task. h + *
BaseType_t xTaskNotifyGiveIndexed( TaskHandle_t xTaskToNotify, UBaseType_t uxIndexToNotify );
+ *
BaseType_t xTaskNotifyGive( TaskHandle_t xTaskToNotify );
+ * + * Sends a direct to task notification to a particular index in the target + * task's notification array in a manner similar to giving a counting semaphore. + * + * See https://www.FreeRTOS.org/RTOS-task-notifications.html for more details. + * + * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for these + * macros to be available. + * + * Each task has a private array of "notification values" (or 'notifications'), + * each of which is a 32-bit unsigned integer (uint32_t). The constant + * configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the + * array, and (for backward compatibility) defaults to 1 if left undefined. + * Prior to FreeRTOS V10.4.0 there was only one notification value per task. + * + * Events can be sent to a task using an intermediary object. Examples of such + * objects are queues, semaphores, mutexes and event groups. Task notifications + * are a method of sending an event directly to a task without the need for such + * an intermediary object. + * + * A notification sent to a task can optionally perform an action, such as + * update, overwrite or increment one of the task's notification values. In + * that way task notifications can be used to send data to a task, or be used as + * light weight and fast binary or counting semaphores. + * + * xTaskNotifyGiveIndexed() is a helper macro intended for use when task + * notifications are used as light weight and faster binary or counting + * semaphore equivalents. Actual FreeRTOS semaphores are given using the + * xSemaphoreGive() API function, the equivalent action that instead uses a task + * notification is xTaskNotifyGiveIndexed(). + * + * When task notifications are being used as a binary or counting semaphore + * equivalent then the task being notified should wait for the notification + * using the ulTaskNotificationTakeIndexed() API function rather than the + * xTaskNotifyWaitIndexed() API function. + * + * **NOTE** Each notification within the array operates independently - a task + * can only block on one notification within the array at a time and will not be + * unblocked by a notification sent to any other array index. + * + * Backward compatibility information: + * Prior to FreeRTOS V10.4.0 each task had a single "notification value", and + * all task notification API functions operated on that value. Replacing the + * single notification value with an array of notification values necessitated a + * new set of API functions that could address specific notifications within the + * array. xTaskNotifyGive() is the original API function, and remains backward + * compatible by always operating on the notification value at index 0 in the + * array. Calling xTaskNotifyGive() is equivalent to calling + * xTaskNotifyGiveIndexed() with the uxIndexToNotify parameter set to 0. + * + * @param xTaskToNotify The handle of the task being notified. The handle to a + * task can be returned from the xTaskCreate() API function used to create the + * task, and the handle of the currently running task can be obtained by calling + * xTaskGetCurrentTaskHandle(). + * + * @param uxIndexToNotify The index within the target task's array of + * notification values to which the notification is to be sent. uxIndexToNotify + * must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyGive() + * does not have this parameter and always sends notifications to index 0. + * + * @return xTaskNotifyGive() is a macro that calls xTaskNotify() with the + * eAction parameter set to eIncrement - so pdPASS is always returned. + * + * \defgroup xTaskNotifyGiveIndexed xTaskNotifyGiveIndexed + * \ingroup TaskNotifications + */ +#define xTaskNotifyGive( xTaskToNotify ) \ + xTaskGenericNotify( ( xTaskToNotify ), ( tskDEFAULT_INDEX_TO_NOTIFY ), ( 0 ), eIncrement, NULL ) +#define xTaskNotifyGiveIndexed( xTaskToNotify, uxIndexToNotify ) \ + xTaskGenericNotify( ( xTaskToNotify ), ( uxIndexToNotify ), ( 0 ), eIncrement, NULL ) + +/** + * task. h + *
void vTaskNotifyGiveIndexedFromISR( TaskHandle_t xTaskHandle, UBaseType_t uxIndexToNotify, BaseType_t *pxHigherPriorityTaskWoken );
+ *
void vTaskNotifyGiveFromISR( TaskHandle_t xTaskHandle, BaseType_t *pxHigherPriorityTaskWoken );
+ * + * A version of xTaskNotifyGiveIndexed() that can be called from an interrupt + * service routine (ISR). + * + * See https://www.FreeRTOS.org/RTOS-task-notifications.html for more details. + * + * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this macro + * to be available. + * + * Each task has a private array of "notification values" (or 'notifications'), + * each of which is a 32-bit unsigned integer (uint32_t). The constant + * configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the + * array, and (for backward compatibility) defaults to 1 if left undefined. + * Prior to FreeRTOS V10.4.0 there was only one notification value per task. + * + * Events can be sent to a task using an intermediary object. Examples of such + * objects are queues, semaphores, mutexes and event groups. Task notifications + * are a method of sending an event directly to a task without the need for such + * an intermediary object. + * + * A notification sent to a task can optionally perform an action, such as + * update, overwrite or increment one of the task's notification values. In + * that way task notifications can be used to send data to a task, or be used as + * light weight and fast binary or counting semaphores. + * + * vTaskNotifyGiveIndexedFromISR() is intended for use when task notifications + * are used as light weight and faster binary or counting semaphore equivalents. + * Actual FreeRTOS semaphores are given from an ISR using the + * xSemaphoreGiveFromISR() API function, the equivalent action that instead uses + * a task notification is vTaskNotifyGiveIndexedFromISR(). + * + * When task notifications are being used as a binary or counting semaphore + * equivalent then the task being notified should wait for the notification + * using the ulTaskNotificationTakeIndexed() API function rather than the + * xTaskNotifyWaitIndexed() API function. + * + * **NOTE** Each notification within the array operates independently - a task + * can only block on one notification within the array at a time and will not be + * unblocked by a notification sent to any other array index. + * + * Backward compatibility information: + * Prior to FreeRTOS V10.4.0 each task had a single "notification value", and + * all task notification API functions operated on that value. Replacing the + * single notification value with an array of notification values necessitated a + * new set of API functions that could address specific notifications within the + * array. xTaskNotifyFromISR() is the original API function, and remains + * backward compatible by always operating on the notification value at index 0 + * within the array. Calling xTaskNotifyGiveFromISR() is equivalent to calling + * xTaskNotifyGiveIndexedFromISR() with the uxIndexToNotify parameter set to 0. + * + * @param xTaskToNotify The handle of the task being notified. The handle to a + * task can be returned from the xTaskCreate() API function used to create the + * task, and the handle of the currently running task can be obtained by calling + * xTaskGetCurrentTaskHandle(). + * + * @param uxIndexToNotify The index within the target task's array of + * notification values to which the notification is to be sent. uxIndexToNotify + * must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. + * xTaskNotifyGiveFromISR() does not have this parameter and always sends + * notifications to index 0. + * + * @param pxHigherPriorityTaskWoken vTaskNotifyGiveFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if sending the notification caused the + * task to which the notification was sent to leave the Blocked state, and the + * unblocked task has a priority higher than the currently running task. If + * vTaskNotifyGiveFromISR() sets this value to pdTRUE then a context switch + * should be requested before the interrupt is exited. How a context switch is + * requested from an ISR is dependent on the port - see the documentation page + * for the port in use. + * + * \defgroup vTaskNotifyGiveIndexedFromISR vTaskNotifyGiveIndexedFromISR + * \ingroup TaskNotifications + */ +void vTaskGenericNotifyGiveFromISR( TaskHandle_t xTaskToNotify, + UBaseType_t uxIndexToNotify, + BaseType_t * pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; +#define vTaskNotifyGiveFromISR( xTaskToNotify, pxHigherPriorityTaskWoken ) \ + vTaskGenericNotifyGiveFromISR( ( xTaskToNotify ), ( tskDEFAULT_INDEX_TO_NOTIFY ), ( pxHigherPriorityTaskWoken ) ); +#define vTaskNotifyGiveIndexedFromISR( xTaskToNotify, uxIndexToNotify, pxHigherPriorityTaskWoken ) \ + vTaskGenericNotifyGiveFromISR( ( xTaskToNotify ), ( uxIndexToNotify ), ( pxHigherPriorityTaskWoken ) ); + +/** + * task. h + *
+ * uint32_t ulTaskNotifyTakeIndexed( UBaseType_t uxIndexToWaitOn, BaseType_t xClearCountOnExit, TickType_t xTicksToWait );
+ *
+ * uint32_t ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait );
+ * 
+ * + * Waits for a direct to task notification on a particular index in the calling + * task's notification array in a manner similar to taking a counting semaphore. + * + * See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. + * + * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this + * function to be available. + * + * Each task has a private array of "notification values" (or 'notifications'), + * each of which is a 32-bit unsigned integer (uint32_t). The constant + * configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the + * array, and (for backward compatibility) defaults to 1 if left undefined. + * Prior to FreeRTOS V10.4.0 there was only one notification value per task. + * + * Events can be sent to a task using an intermediary object. Examples of such + * objects are queues, semaphores, mutexes and event groups. Task notifications + * are a method of sending an event directly to a task without the need for such + * an intermediary object. + * + * A notification sent to a task can optionally perform an action, such as + * update, overwrite or increment one of the task's notification values. In + * that way task notifications can be used to send data to a task, or be used as + * light weight and fast binary or counting semaphores. + * + * ulTaskNotifyTakeIndexed() is intended for use when a task notification is + * used as a faster and lighter weight binary or counting semaphore alternative. + * Actual FreeRTOS semaphores are taken using the xSemaphoreTake() API function, + * the equivalent action that instead uses a task notification is + * ulTaskNotifyTakeIndexed(). + * + * When a task is using its notification value as a binary or counting semaphore + * other tasks should send notifications to it using the xTaskNotifyGiveIndexed() + * macro, or xTaskNotifyIndex() function with the eAction parameter set to + * eIncrement. + * + * ulTaskNotifyTakeIndexed() can either clear the task's notification value at + * the array index specified by the uxIndexToWaitOn parameter to zero on exit, + * in which case the notification value acts like a binary semaphore, or + * decrement the notification value on exit, in which case the notification + * value acts like a counting semaphore. + * + * A task can use ulTaskNotifyTakeIndexed() to [optionally] block to wait for + * 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 xTaskNotifyWaitIndexed() will return when a notification is pending, + * ulTaskNotifyTakeIndexed() will return when the task's notification value is + * not zero. + * + * **NOTE** Each notification within the array operates independently - a task + * can only block on one notification within the array at a time and will not be + * unblocked by a notification sent to any other array index. + * + * Backward compatibility information: + * Prior to FreeRTOS V10.4.0 each task had a single "notification value", and + * all task notification API functions operated on that value. Replacing the + * single notification value with an array of notification values necessitated a + * new set of API functions that could address specific notifications within the + * array. ulTaskNotifyTake() is the original API function, and remains backward + * compatible by always operating on the notification value at index 0 in the + * array. Calling ulTaskNotifyTake() is equivalent to calling + * ulTaskNotifyTakeIndexed() with the uxIndexToWaitOn parameter set to 0. + * + * @param uxIndexToWaitOn The index within the calling task's array of + * notification values on which the calling task will wait for a notification to + * be non-zero. uxIndexToWaitOn must be less than + * configTASK_NOTIFICATION_ARRAY_ENTRIES. xTaskNotifyTake() does + * not have this parameter and always waits for notifications on index 0. + * + * @param xClearCountOnExit if xClearCountOnExit is pdFALSE then the task's + * notification value is decremented when the function exits. In this way the + * notification value acts like a counting semaphore. If xClearCountOnExit is + * not pdFALSE then the task's notification value is cleared to zero when the + * function exits. In this way the notification value acts like a binary + * semaphore. + * + * @param xTicksToWait The maximum amount of time that the task should wait in + * the Blocked state for the task's notification value to be greater than zero, + * should the count not already be greater than zero when + * ulTaskNotifyTake() was called. The task will not consume any processing + * time while it is in the Blocked state. This is specified in kernel ticks, + * the macro pdMS_TO_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 ulTaskNotifyTakeIndexed ulTaskNotifyTakeIndexed + * \ingroup TaskNotifications + */ +uint32_t ulTaskGenericNotifyTake( UBaseType_t uxIndexToWaitOn, + BaseType_t xClearCountOnExit, + TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; +#define ulTaskNotifyTake( xClearCountOnExit, xTicksToWait ) \ + ulTaskGenericNotifyTake( ( tskDEFAULT_INDEX_TO_NOTIFY ), ( xClearCountOnExit ), ( xTicksToWait ) ) +#define ulTaskNotifyTakeIndexed( uxIndexToWaitOn, xClearCountOnExit, xTicksToWait ) \ + ulTaskGenericNotifyTake( ( uxIndexToWaitOn ), ( xClearCountOnExit ), ( xTicksToWait ) ) + +/** + * task. h + *
+ * BaseType_t xTaskNotifyStateClearIndexed( TaskHandle_t xTask, UBaseType_t uxIndexToCLear );
+ *
+ * BaseType_t xTaskNotifyStateClear( TaskHandle_t xTask );
+ * 
+ * + * See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. + * + * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for these + * functions to be available. + * + * Each task has a private array of "notification values" (or 'notifications'), + * each of which is a 32-bit unsigned integer (uint32_t). The constant + * configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the + * array, and (for backward compatibility) defaults to 1 if left undefined. + * Prior to FreeRTOS V10.4.0 there was only one notification value per task. + * + * If a notification is sent to an index within the array of notifications then + * the notification at that index is said to be 'pending' until it is read or + * explicitly cleared by the receiving task. xTaskNotifyStateClearIndexed() + * is the function that clears a pending notification without reading the + * notification value. The notification value at the same array index is not + * altered. Set xTask to NULL to clear the notification state of the calling + * task. + * + * Backward compatibility information: + * Prior to FreeRTOS V10.4.0 each task had a single "notification value", and + * all task notification API functions operated on that value. Replacing the + * single notification value with an array of notification values necessitated a + * new set of API functions that could address specific notifications within the + * array. xTaskNotifyStateClear() is the original API function, and remains + * backward compatible by always operating on the notification value at index 0 + * within the array. Calling xTaskNotifyStateClear() is equivalent to calling + * xTaskNotifyStateClearIndexed() with the uxIndexToNotify parameter set to 0. + * + * @param xTask The handle of the RTOS task that will have a notification state + * cleared. Set xTask to NULL to clear a notification state in the calling + * task. To obtain a task's handle create the task using xTaskCreate() and + * make use of the pxCreatedTask parameter, or create the task using + * xTaskCreateStatic() and store the returned value, or use the task's name in + * a call to xTaskGetHandle(). + * + * @param uxIndexToClear The index within the target task's array of + * notification values to act upon. For example, setting uxIndexToClear to 1 + * will clear the state of the notification at index 1 within the array. + * uxIndexToClear must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. + * ulTaskNotifyStateClear() does not have this parameter and always acts on the + * notification at index 0. + * + * @return pdTRUE if the task's notification state was set to + * eNotWaitingNotification, otherwise pdFALSE. + * + * \defgroup xTaskNotifyStateClearIndexed xTaskNotifyStateClearIndexed + * \ingroup TaskNotifications + */ +BaseType_t xTaskGenericNotifyStateClear( TaskHandle_t xTask, + UBaseType_t uxIndexToClear ) PRIVILEGED_FUNCTION; +#define xTaskNotifyStateClear( xTask ) \ + xTaskGenericNotifyStateClear( ( xTask ), ( tskDEFAULT_INDEX_TO_NOTIFY ) ) +#define xTaskNotifyStateClearIndexed( xTask, uxIndexToClear ) \ + xTaskGenericNotifyStateClear( ( xTask ), ( uxIndexToClear ) ) + +/** + * task. h + *
+ * uint32_t ulTaskNotifyValueClearIndexed( TaskHandle_t xTask, UBaseType_t uxIndexToClear, uint32_t ulBitsToClear );
+ *
+ * uint32_t ulTaskNotifyValueClear( TaskHandle_t xTask, uint32_t ulBitsToClear );
+ * 
+ * + * See https://www.FreeRTOS.org/RTOS-task-notifications.html for details. + * + * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for these + * functions to be available. + * + * Each task has a private array of "notification values" (or 'notifications'), + * each of which is a 32-bit unsigned integer (uint32_t). The constant + * configTASK_NOTIFICATION_ARRAY_ENTRIES sets the number of indexes in the + * array, and (for backward compatibility) defaults to 1 if left undefined. + * Prior to FreeRTOS V10.4.0 there was only one notification value per task. + * + * ulTaskNotifyValueClearIndexed() clears the bits specified by the + * ulBitsToClear bit mask in the notification value at array index uxIndexToClear + * of the task referenced by xTask. + * + * Backward compatibility information: + * Prior to FreeRTOS V10.4.0 each task had a single "notification value", and + * all task notification API functions operated on that value. Replacing the + * single notification value with an array of notification values necessitated a + * new set of API functions that could address specific notifications within the + * array. ulTaskNotifyValueClear() is the original API function, and remains + * backward compatible by always operating on the notification value at index 0 + * within the array. Calling ulTaskNotifyValueClear() is equivalent to calling + * ulTaskNotifyValueClearIndexed() with the uxIndexToClear parameter set to 0. + * + * @param xTask The handle of the RTOS task that will have bits in one of its + * notification values cleared. Set xTask to NULL to clear bits in a + * notification value of the calling task. To obtain a task's handle create the + * task using xTaskCreate() and make use of the pxCreatedTask parameter, or + * create the task using xTaskCreateStatic() and store the returned value, or + * use the task's name in a call to xTaskGetHandle(). + * + * @param uxIndexToClear The index within the target task's array of + * notification values in which to clear the bits. uxIndexToClear + * must be less than configTASK_NOTIFICATION_ARRAY_ENTRIES. + * ulTaskNotifyValueClear() does not have this parameter and always clears bits + * in the notification value at index 0. + * + * @param ulBitsToClear Bit mask of the bits to clear in the notification value of + * xTask. Set a bit to 1 to clear the corresponding bits in the task's notification + * value. Set ulBitsToClear to 0xffffffff (UINT_MAX on 32-bit architectures) to clear + * the notification value to 0. Set ulBitsToClear to 0 to query the task's + * notification value without clearing any bits. + * + * + * @return The value of the target task's notification value before the bits + * specified by ulBitsToClear were cleared. + * \defgroup ulTaskNotifyValueClear ulTaskNotifyValueClear + * \ingroup TaskNotifications + */ +uint32_t ulTaskGenericNotifyValueClear( TaskHandle_t xTask, + UBaseType_t uxIndexToClear, + uint32_t ulBitsToClear ) PRIVILEGED_FUNCTION; +#define ulTaskNotifyValueClear( xTask, ulBitsToClear ) \ + ulTaskGenericNotifyValueClear( ( xTask ), ( tskDEFAULT_INDEX_TO_NOTIFY ), ( ulBitsToClear ) ) +#define ulTaskNotifyValueClearIndexed( xTask, uxIndexToClear, ulBitsToClear ) \ + ulTaskGenericNotifyValueClear( ( xTask ), ( uxIndexToClear ), ( ulBitsToClear ) ) + +/** + * task.h + *
+ * 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; + +/** + * task.h + *
+ * BaseType_t xTaskCatchUpTicks( TickType_t xTicksToCatchUp );
+ * 
+ * + * This function corrects the tick count value after the application code has held + * interrupts disabled for an extended period resulting in tick interrupts having + * been missed. + * + * This function is similar to vTaskStepTick(), however, unlike + * vTaskStepTick(), xTaskCatchUpTicks() may move the tick count forward past a + * time at which a task should be removed from the blocked state. That means + * tasks may have to be removed from the blocked state as the tick count is + * moved. + * + * @param xTicksToCatchUp The number of tick interrupts that have been missed due to + * interrupts being disabled. Its value is not computed automatically, so must be + * computed by the application writer. + * + * @return pdTRUE if moving the tick count forward resulted in a task leaving the + * blocked state and a context switch being performed. Otherwise pdFALSE. + * + * \defgroup xTaskCatchUpTicks xTaskCatchUpTicks + * \ingroup TaskCtrl + */ +BaseType_t xTaskCatchUpTicks( TickType_t xTicksToCatchUp ) PRIVILEGED_FUNCTION; + + +/*----------------------------------------------------------- +* SCHEDULER INTERNALS AVAILABLE FOR PORTING PURPOSES +*----------------------------------------------------------*/ + +/* + * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS ONLY + * INTENDED FOR USE WHEN IMPLEMENTING A PORT OF THE SCHEDULER AND IS + * AN INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER. + * + * Called from the real time kernel tick (either preemptive or cooperative), + * this increments the tick count and checks if any tasks that are blocked + * for a finite period required removing from a blocked list and placing on + * a ready list. If a non-zero value is returned then a context switch is + * required because either: + * + A task was removed from a blocked list because its timeout had expired, + * or + * + Time slicing is in use and there is a task of equal priority to the + * currently running task. + */ +BaseType_t xTaskIncrementTick( void ) PRIVILEGED_FUNCTION; + +/* + * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS AN + * INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER. + * + * THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED. + * + * Removes the calling task from the ready list and places it both + * on the list of tasks waiting for a particular event, and the + * list of delayed tasks. The task will be removed from both lists + * and replaced on the ready list should either the event occur (and + * there be no higher priority tasks waiting on the same event) or + * the delay period expires. + * + * The 'unordered' version replaces the event list item value with the + * xItemValue value, and inserts the list item at the end of the list. + * + * The 'ordered' version uses the existing event list item value (which is the + * owning 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; + +/* + * Only available when configUSE_TICKLESS_IDLE is set to 1. + * Provided for use within portSUPPRESS_TICKS_AND_SLEEP() to allow the port + * specific sleep function to determine if it is ok to proceed with the sleep, + * and if it is ok to proceed, if it is ok to sleep indefinitely. + * + * This function is necessary because portSUPPRESS_TICKS_AND_SLEEP() is only + * called with the scheduler suspended, not from within a critical section. It + * is therefore possible for an interrupt to request a context switch between + * portSUPPRESS_TICKS_AND_SLEEP() and the low power mode actually being + * entered. eTaskConfirmSleepModeStatus() should be called from a short + * critical section between the timer being stopped and the sleep mode being + * entered to ensure it is ok to proceed into the sleep mode. + */ +eSleepModeStatus eTaskConfirmSleepModeStatus( void ) PRIVILEGED_FUNCTION; + +/* + * For internal use only. Increment the mutex held count when a mutex is + * taken and return the handle of the task that has taken the mutex. + */ +TaskHandle_t pvTaskIncrementMutexHeldCount( void ) PRIVILEGED_FUNCTION; + +/* + * For internal use only. Same as vTaskSetTimeOutState(), but without a critical + * section. + */ +void vTaskInternalSetTimeOutState( TimeOut_t * const pxTimeOut ) PRIVILEGED_FUNCTION; + + +/* *INDENT-OFF* */ +#ifdef __cplusplus + } +#endif +/* *INDENT-ON* */ +#endif /* INC_TASK_H */ diff --git a/examples/stm32/freertos-kernel/include/timers.h b/examples/stm32/freertos-kernel/include/timers.h new file mode 100644 index 00000000..f767d5c5 --- /dev/null +++ b/examples/stm32/freertos-kernel/include/timers.h @@ -0,0 +1,1351 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + + +#ifndef TIMERS_H +#define TIMERS_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h must appear in source files before include timers.h" +#endif + +/*lint -save -e537 This headers are only multiply included if the application code + * happens to also be including task.h. */ +#include "task.h" +/*lint -restore */ + +/* *INDENT-OFF* */ +#ifdef __cplusplus + extern "C" { +#endif +/* *INDENT-ON* */ + +/*----------------------------------------------------------- +* MACROS AND DEFINITIONS +*----------------------------------------------------------*/ + +/* IDs for commands that can be sent/received on the timer queue. These are to + * be used solely through the macros that make up the public software timer API, + * as defined below. The commands that are sent from interrupts must use the + * highest numbers as tmrFIRST_FROM_ISR_COMMAND is used to determine if the task + * or interrupt version of the queue send function should be used. */ +#define tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR ( ( BaseType_t ) -2 ) +#define tmrCOMMAND_EXECUTE_CALLBACK ( ( BaseType_t ) -1 ) +#define tmrCOMMAND_START_DONT_TRACE ( ( BaseType_t ) 0 ) +#define tmrCOMMAND_START ( ( BaseType_t ) 1 ) +#define tmrCOMMAND_RESET ( ( BaseType_t ) 2 ) +#define tmrCOMMAND_STOP ( ( BaseType_t ) 3 ) +#define tmrCOMMAND_CHANGE_PERIOD ( ( BaseType_t ) 4 ) +#define tmrCOMMAND_DELETE ( ( BaseType_t ) 5 ) + +#define tmrFIRST_FROM_ISR_COMMAND ( ( BaseType_t ) 6 ) +#define tmrCOMMAND_START_FROM_ISR ( ( BaseType_t ) 6 ) +#define tmrCOMMAND_RESET_FROM_ISR ( ( BaseType_t ) 7 ) +#define tmrCOMMAND_STOP_FROM_ISR ( ( BaseType_t ) 8 ) +#define tmrCOMMAND_CHANGE_PERIOD_FROM_ISR ( ( BaseType_t ) 9 ) + + +/** + * Type by which software timers are referenced. For example, a call to + * xTimerCreate() returns an TimerHandle_t variable that can then be used to + * reference the subject timer in calls to other software timer API functions + * (for example, xTimerStart(), xTimerReset(), etc.). + */ +struct tmrTimerControl; /* The old naming convention is used to prevent breaking kernel aware debuggers. */ +typedef struct tmrTimerControl * TimerHandle_t; + +/* + * Defines the prototype to which timer callback functions must conform. + */ +typedef void (* TimerCallbackFunction_t)( TimerHandle_t xTimer ); + +/* + * Defines the prototype to which functions used with the + * xTimerPendFunctionCallFromISR() function must conform. + */ +typedef void (* PendedFunction_t)( void *, + uint32_t ); + +/** + * TimerHandle_t xTimerCreate( const char * const pcTimerName, + * TickType_t xTimerPeriodInTicks, + * UBaseType_t uxAutoReload, + * void * pvTimerID, + * TimerCallbackFunction_t pxCallbackFunction ); + * + * Creates a new software timer instance, and returns a handle by which the + * created software timer can be referenced. + * + * Internally, within the FreeRTOS implementation, software timers use a block + * of memory, in which the timer data structure is stored. If a software timer + * is created using xTimerCreate() then the required memory is automatically + * dynamically allocated inside the xTimerCreate() function. (see + * https://www.FreeRTOS.org/a00111.html). If a software timer is created using + * xTimerCreateStatic() then the application writer must provide the memory that + * will get used by the software timer. xTimerCreateStatic() therefore allows a + * software timer to be created without using any dynamic memory allocation. + * + * Timers are created in the dormant state. The xTimerStart(), xTimerReset(), + * xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and + * xTimerChangePeriodFromISR() API functions can all be used to transition a + * timer into the active state. + * + * @param pcTimerName A text name that is assigned to the timer. This is done + * purely to assist debugging. The kernel itself only ever references a timer + * by its handle, and never by its name. + * + * @param xTimerPeriodInTicks The timer period. The time is defined in tick + * periods so the constant portTICK_PERIOD_MS can be used to convert a time that + * has been specified in milliseconds. For example, if the timer must expire + * after 100 ticks, then xTimerPeriodInTicks should be set to 100. + * Alternatively, if the timer must expire after 500ms, then xPeriod can be set + * to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or + * equal to 1000. Time timer period must be greater than 0. + * + * @param uxAutoReload If uxAutoReload is set to pdTRUE then the timer will + * expire repeatedly with a frequency set by the xTimerPeriodInTicks parameter. + * If uxAutoReload is set to pdFALSE then the timer will be a one-shot timer and + * enter the dormant state after it expires. + * + * @param pvTimerID An identifier that is assigned to the timer being created. + * Typically this would be used in the timer callback function to identify which + * timer expired when the same callback function is assigned to more than one + * timer. + * + * @param pxCallbackFunction The function to call when the timer expires. + * Callback functions must have the prototype defined by TimerCallbackFunction_t, + * which is "void vCallbackFunction( TimerHandle_t xTimer );". + * + * @return If the timer is successfully created then a handle to the newly + * created timer is returned. If the timer cannot be created because there is + * insufficient FreeRTOS heap remaining to allocate the timer + * structures then NULL is returned. + * + * Example usage: + * @verbatim + * #define NUM_TIMERS 5 + * + * // An array to hold handles to the created timers. + * TimerHandle_t xTimers[ NUM_TIMERS ]; + * + * // An array to hold a count of the number of times each timer expires. + * int32_t lExpireCounters[ NUM_TIMERS ] = { 0 }; + * + * // Define a callback function that will be used by multiple timer instances. + * // The callback function does nothing but count the number of times the + * // associated timer expires, and stop the timer once the timer has expired + * // 10 times. + * void vTimerCallback( TimerHandle_t pxTimer ) + * { + * int32_t lArrayIndex; + * const int32_t xMaxExpiryCountBeforeStopping = 10; + * + * // Optionally do something if the pxTimer parameter is NULL. + * configASSERT( pxTimer ); + * + * // Which timer expired? + * lArrayIndex = ( int32_t ) pvTimerGetTimerID( pxTimer ); + * + * // Increment the number of times that pxTimer has expired. + * lExpireCounters[ lArrayIndex ] += 1; + * + * // If the timer has expired 10 times then stop it from running. + * if( lExpireCounters[ lArrayIndex ] == xMaxExpiryCountBeforeStopping ) + * { + * // Do not use a block time if calling a timer API function from a + * // timer callback function, as doing so could cause a deadlock! + * xTimerStop( pxTimer, 0 ); + * } + * } + * + * void main( void ) + * { + * int32_t x; + * + * // Create then start some timers. Starting the timers before the scheduler + * // has been started means the timers will start running immediately that + * // the scheduler starts. + * for( x = 0; x < NUM_TIMERS; x++ ) + * { + * xTimers[ x ] = xTimerCreate( "Timer", // Just a text name, not used by the kernel. + * ( 100 * x ), // The timer period in ticks. + * pdTRUE, // The timers will auto-reload themselves when they expire. + * ( void * ) x, // Assign each timer a unique id equal to its array index. + * vTimerCallback // Each timer calls the same callback when it expires. + * ); + * + * if( xTimers[ x ] == NULL ) + * { + * // The timer was not created. + * } + * else + * { + * // Start the timer. No block time is specified, and even if one was + * // it would be ignored because the scheduler has not yet been + * // started. + * if( xTimerStart( xTimers[ x ], 0 ) != pdPASS ) + * { + * // The timer could not be set into the Active state. + * } + * } + * } + * + * // ... + * // Create tasks here. + * // ... + * + * // Starting the scheduler will start the timers running as they have already + * // been set into the active state. + * vTaskStartScheduler(); + * + * // Should not reach here. + * for( ;; ); + * } + * @endverbatim + */ +#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + TimerHandle_t xTimerCreate( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction ) PRIVILEGED_FUNCTION; +#endif + +/** + * TimerHandle_t xTimerCreateStatic(const char * const pcTimerName, + * TickType_t xTimerPeriodInTicks, + * UBaseType_t uxAutoReload, + * void * pvTimerID, + * TimerCallbackFunction_t pxCallbackFunction, + * StaticTimer_t *pxTimerBuffer ); + * + * Creates a new software timer instance, and returns a handle by which the + * created software timer can be referenced. + * + * Internally, within the FreeRTOS implementation, software timers use a block + * of memory, in which the timer data structure is stored. If a software timer + * is created using xTimerCreate() then the required memory is automatically + * dynamically allocated inside the xTimerCreate() function. (see + * https://www.FreeRTOS.org/a00111.html). If a software timer is created using + * xTimerCreateStatic() then the application writer must provide the memory that + * will get used by the software timer. xTimerCreateStatic() therefore allows a + * software timer to be created without using any dynamic memory allocation. + * + * Timers are created in the dormant state. The xTimerStart(), xTimerReset(), + * xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and + * xTimerChangePeriodFromISR() API functions can all be used to transition a + * timer into the active state. + * + * @param pcTimerName A text name that is assigned to the timer. This is done + * purely to assist debugging. The kernel itself only ever references a timer + * by its handle, and never by its name. + * + * @param xTimerPeriodInTicks The timer period. The time is defined in tick + * periods so the constant portTICK_PERIOD_MS can be used to convert a time that + * has been specified in milliseconds. For example, if the timer must expire + * after 100 ticks, then xTimerPeriodInTicks should be set to 100. + * Alternatively, if the timer must expire after 500ms, then xPeriod can be set + * to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or + * equal to 1000. The timer period must be greater than 0. + * + * @param uxAutoReload If uxAutoReload is set to pdTRUE then the timer will + * expire repeatedly with a frequency set by the xTimerPeriodInTicks parameter. + * If uxAutoReload is set to pdFALSE then the timer will be a one-shot timer and + * enter the dormant state after it expires. + * + * @param pvTimerID An identifier that is assigned to the timer being created. + * Typically this would be used in the timer callback function to identify which + * timer expired when the same callback function is assigned to more than one + * timer. + * + * @param pxCallbackFunction The function to call when the timer expires. + * Callback functions must have the prototype defined by TimerCallbackFunction_t, + * which is "void vCallbackFunction( TimerHandle_t xTimer );". + * + * @param pxTimerBuffer Must point to a variable of type StaticTimer_t, which + * will be then be used to hold the software timer's data structures, removing + * the need for the memory to be allocated dynamically. + * + * @return If the timer is created then a handle to the created timer is + * returned. If pxTimerBuffer was NULL then NULL is returned. + * + * Example usage: + * @verbatim + * + * // The buffer used to hold the software timer's data structure. + * static StaticTimer_t xTimerBuffer; + * + * // A variable that will be incremented by the software timer's callback + * // function. + * UBaseType_t uxVariableToIncrement = 0; + * + * // A software timer callback function that increments a variable passed to + * // it when the software timer was created. After the 5th increment the + * // callback function stops the software timer. + * static void prvTimerCallback( TimerHandle_t xExpiredTimer ) + * { + * UBaseType_t *puxVariableToIncrement; + * BaseType_t xReturned; + * + * // Obtain the address of the variable to increment from the timer ID. + * puxVariableToIncrement = ( UBaseType_t * ) pvTimerGetTimerID( xExpiredTimer ); + * + * // Increment the variable to show the timer callback has executed. + * ( *puxVariableToIncrement )++; + * + * // If this callback has executed the required number of times, stop the + * // timer. + * if( *puxVariableToIncrement == 5 ) + * { + * // This is called from a timer callback so must not block. + * xTimerStop( xExpiredTimer, staticDONT_BLOCK ); + * } + * } + * + * + * void main( void ) + * { + * // Create the software time. xTimerCreateStatic() has an extra parameter + * // than the normal xTimerCreate() API function. The parameter is a pointer + * // to the StaticTimer_t structure that will hold the software timer + * // structure. If the parameter is passed as NULL then the structure will be + * // allocated dynamically, just as if xTimerCreate() had been called. + * xTimer = xTimerCreateStatic( "T1", // Text name for the task. Helps debugging only. Not used by FreeRTOS. + * xTimerPeriod, // The period of the timer in ticks. + * pdTRUE, // This is an auto-reload timer. + * ( void * ) &uxVariableToIncrement, // A variable incremented by the software timer's callback function + * prvTimerCallback, // The function to execute when the timer expires. + * &xTimerBuffer ); // The buffer that will hold the software timer structure. + * + * // The scheduler has not started yet so a block time is not used. + * xReturned = xTimerStart( xTimer, 0 ); + * + * // ... + * // Create tasks here. + * // ... + * + * // Starting the scheduler will start the timers running as they have already + * // been set into the active state. + * vTaskStartScheduler(); + * + * // Should not reach here. + * for( ;; ); + * } + * @endverbatim + */ +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + TimerHandle_t xTimerCreateStatic( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction, + StaticTimer_t * pxTimerBuffer ) PRIVILEGED_FUNCTION; +#endif /* configSUPPORT_STATIC_ALLOCATION */ + +/** + * void *pvTimerGetTimerID( TimerHandle_t xTimer ); + * + * Returns the ID assigned to the timer. + * + * IDs are assigned to timers using the pvTimerID parameter of the call to + * xTimerCreated() that was used to create the timer, and by calling the + * vTimerSetTimerID() API function. + * + * If the same callback function is assigned to multiple timers then the timer + * ID can be used as time specific (timer local) storage. + * + * @param xTimer The timer being queried. + * + * @return The ID assigned to the timer being queried. + * + * Example usage: + * + * See the xTimerCreate() API function example usage scenario. + */ +void * pvTimerGetTimerID( const TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; + +/** + * void vTimerSetTimerID( TimerHandle_t xTimer, void *pvNewID ); + * + * Sets the ID assigned to the timer. + * + * IDs are assigned to timers using the pvTimerID parameter of the call to + * xTimerCreated() that was used to create the timer. + * + * If the same callback function is assigned to multiple timers then the timer + * ID can be used as time specific (timer local) storage. + * + * @param xTimer The timer being updated. + * + * @param pvNewID The ID to assign to the timer. + * + * Example usage: + * + * See the xTimerCreate() API function example usage scenario. + */ +void vTimerSetTimerID( TimerHandle_t xTimer, + void * pvNewID ) PRIVILEGED_FUNCTION; + +/** + * BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer ); + * + * Queries a timer to see if it is active or dormant. + * + * A timer will be dormant if: + * 1) It has been created but not started, or + * 2) It is an expired one-shot timer that has not been restarted. + * + * Timers are created in the dormant state. The xTimerStart(), xTimerReset(), + * xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and + * xTimerChangePeriodFromISR() API functions can all be used to transition a timer into the + * active state. + * + * @param xTimer The timer being queried. + * + * @return pdFALSE will be returned if the timer is dormant. A value other than + * pdFALSE will be returned if the timer is active. + * + * Example usage: + * @verbatim + * // This function assumes xTimer has already been created. + * void vAFunction( TimerHandle_t xTimer ) + * { + * if( xTimerIsTimerActive( xTimer ) != pdFALSE ) // or more simply and equivalently "if( xTimerIsTimerActive( xTimer ) )" + * { + * // xTimer is active, do something. + * } + * else + * { + * // xTimer is not active, do something else. + * } + * } + * @endverbatim + */ +BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; + +/** + * TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ); + * + * Simply returns the handle of the timer service/daemon task. It it not valid + * to call xTimerGetTimerDaemonTaskHandle() before the scheduler has been started. + */ +TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ) PRIVILEGED_FUNCTION; + +/** + * BaseType_t xTimerStart( TimerHandle_t xTimer, TickType_t xTicksToWait ); + * + * Timer functionality is provided by a timer service/daemon task. Many of the + * public FreeRTOS timer API functions send commands to the timer service task + * through a queue called the timer command queue. The timer command queue is + * private to the kernel itself and is not directly accessible to application + * code. The length of the timer command queue is set by the + * configTIMER_QUEUE_LENGTH configuration constant. + * + * xTimerStart() starts a timer that was previously created using the + * xTimerCreate() API function. If the timer had already been started and was + * already in the active state, then xTimerStart() has equivalent functionality + * to the xTimerReset() API function. + * + * Starting a timer ensures the timer is in the active state. If the timer + * is not stopped, deleted, or reset in the mean time, the callback function + * associated with the timer will get called 'n' ticks after xTimerStart() was + * called, where 'n' is the timers defined period. + * + * It is valid to call xTimerStart() before the scheduler has been started, but + * when this is done the timer will not actually start until the scheduler is + * started, and the timers expiry time will be relative to when the scheduler is + * started, not relative to when xTimerStart() was called. + * + * The configUSE_TIMERS configuration constant must be set to 1 for xTimerStart() + * to be available. + * + * @param xTimer The handle of the timer being started/restarted. + * + * @param xTicksToWait Specifies the time, in ticks, that the calling task should + * be held in the Blocked state to wait for the start command to be successfully + * sent to the timer command queue, should the queue already be full when + * xTimerStart() was called. xTicksToWait is ignored if xTimerStart() is called + * before the scheduler is started. + * + * @return pdFAIL will be returned if the start command could not be sent to + * the timer command queue even after xTicksToWait ticks had passed. pdPASS will + * be returned if the command was successfully sent to the timer command queue. + * When the command is actually processed will depend on the priority of the + * timer service/daemon task relative to other tasks in the system, although the + * timers expiry time is relative to when xTimerStart() is actually called. The + * timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY + * configuration constant. + * + * Example usage: + * + * See the xTimerCreate() API function example usage scenario. + * + */ +#define xTimerStart( xTimer, xTicksToWait ) \ + xTimerGenericCommand( ( xTimer ), tmrCOMMAND_START, ( xTaskGetTickCount() ), NULL, ( xTicksToWait ) ) + +/** + * BaseType_t xTimerStop( TimerHandle_t xTimer, TickType_t xTicksToWait ); + * + * Timer functionality is provided by a timer service/daemon task. Many of the + * public FreeRTOS timer API functions send commands to the timer service task + * through a queue called the timer command queue. The timer command queue is + * private to the kernel itself and is not directly accessible to application + * code. The length of the timer command queue is set by the + * configTIMER_QUEUE_LENGTH configuration constant. + * + * xTimerStop() stops a timer that was previously started using either of the + * The xTimerStart(), xTimerReset(), xTimerStartFromISR(), xTimerResetFromISR(), + * xTimerChangePeriod() or xTimerChangePeriodFromISR() API functions. + * + * Stopping a timer ensures the timer is not in the active state. + * + * The configUSE_TIMERS configuration constant must be set to 1 for xTimerStop() + * to be available. + * + * @param xTimer The handle of the timer being stopped. + * + * @param xTicksToWait Specifies the time, in ticks, that the calling task should + * be held in the Blocked state to wait for the stop command to be successfully + * sent to the timer command queue, should the queue already be full when + * xTimerStop() was called. xTicksToWait is ignored if xTimerStop() is called + * before the scheduler is started. + * + * @return pdFAIL will be returned if the stop command could not be sent to + * the timer command queue even after xTicksToWait ticks had passed. pdPASS will + * be returned if the command was successfully sent to the timer command queue. + * When the command is actually processed will depend on the priority of the + * timer service/daemon task relative to other tasks in the system. The timer + * service/daemon task priority is set by the configTIMER_TASK_PRIORITY + * configuration constant. + * + * Example usage: + * + * See the xTimerCreate() API function example usage scenario. + * + */ +#define xTimerStop( xTimer, xTicksToWait ) \ + xTimerGenericCommand( ( xTimer ), tmrCOMMAND_STOP, 0U, NULL, ( xTicksToWait ) ) + +/** + * BaseType_t xTimerChangePeriod( TimerHandle_t xTimer, + * TickType_t xNewPeriod, + * TickType_t xTicksToWait ); + * + * Timer functionality is provided by a timer service/daemon task. Many of the + * public FreeRTOS timer API functions send commands to the timer service task + * through a queue called the timer command queue. The timer command queue is + * private to the kernel itself and is not directly accessible to application + * code. The length of the timer command queue is set by the + * configTIMER_QUEUE_LENGTH configuration constant. + * + * xTimerChangePeriod() changes the period of a timer that was previously + * created using the xTimerCreate() API function. + * + * xTimerChangePeriod() can be called to change the period of an active or + * dormant state timer. + * + * The configUSE_TIMERS configuration constant must be set to 1 for + * xTimerChangePeriod() to be available. + * + * @param xTimer The handle of the timer that is having its period changed. + * + * @param xNewPeriod The new period for xTimer. Timer periods are specified in + * tick periods, so the constant portTICK_PERIOD_MS can be used to convert a time + * that has been specified in milliseconds. For example, if the timer must + * expire after 100 ticks, then xNewPeriod should be set to 100. Alternatively, + * if the timer must expire after 500ms, then xNewPeriod can be set to + * ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than + * or equal to 1000. + * + * @param xTicksToWait Specifies the time, in ticks, that the calling task should + * be held in the Blocked state to wait for the change period command to be + * successfully sent to the timer command queue, should the queue already be + * full when xTimerChangePeriod() was called. xTicksToWait is ignored if + * xTimerChangePeriod() is called before the scheduler is started. + * + * @return pdFAIL will be returned if the change period command could not be + * sent to the timer command queue even after xTicksToWait ticks had passed. + * pdPASS will be returned if the command was successfully sent to the timer + * command queue. When the command is actually processed will depend on the + * priority of the timer service/daemon task relative to other tasks in the + * system. The timer service/daemon task priority is set by the + * configTIMER_TASK_PRIORITY configuration constant. + * + * Example usage: + * @verbatim + * // This function assumes xTimer has already been created. If the timer + * // referenced by xTimer is already active when it is called, then the timer + * // is deleted. If the timer referenced by xTimer is not active when it is + * // called, then the period of the timer is set to 500ms and the timer is + * // started. + * void vAFunction( TimerHandle_t xTimer ) + * { + * if( xTimerIsTimerActive( xTimer ) != pdFALSE ) // or more simply and equivalently "if( xTimerIsTimerActive( xTimer ) )" + * { + * // xTimer is already active - delete it. + * xTimerDelete( xTimer ); + * } + * else + * { + * // xTimer is not active, change its period to 500ms. This will also + * // cause the timer to start. Block for a maximum of 100 ticks if the + * // change period command cannot immediately be sent to the timer + * // command queue. + * if( xTimerChangePeriod( xTimer, 500 / portTICK_PERIOD_MS, 100 ) == pdPASS ) + * { + * // The command was successfully sent. + * } + * else + * { + * // The command could not be sent, even after waiting for 100 ticks + * // to pass. Take appropriate action here. + * } + * } + * } + * @endverbatim + */ +#define xTimerChangePeriod( xTimer, xNewPeriod, xTicksToWait ) \ + xTimerGenericCommand( ( xTimer ), tmrCOMMAND_CHANGE_PERIOD, ( xNewPeriod ), NULL, ( xTicksToWait ) ) + +/** + * BaseType_t xTimerDelete( TimerHandle_t xTimer, TickType_t xTicksToWait ); + * + * Timer functionality is provided by a timer service/daemon task. Many of the + * public FreeRTOS timer API functions send commands to the timer service task + * through a queue called the timer command queue. The timer command queue is + * private to the kernel itself and is not directly accessible to application + * code. The length of the timer command queue is set by the + * configTIMER_QUEUE_LENGTH configuration constant. + * + * xTimerDelete() deletes a timer that was previously created using the + * xTimerCreate() API function. + * + * The configUSE_TIMERS configuration constant must be set to 1 for + * xTimerDelete() to be available. + * + * @param xTimer The handle of the timer being deleted. + * + * @param xTicksToWait Specifies the time, in ticks, that the calling task should + * be held in the Blocked state to wait for the delete command to be + * successfully sent to the timer command queue, should the queue already be + * full when xTimerDelete() was called. xTicksToWait is ignored if xTimerDelete() + * is called before the scheduler is started. + * + * @return pdFAIL will be returned if the delete command could not be sent to + * the timer command queue even after xTicksToWait ticks had passed. pdPASS will + * be returned if the command was successfully sent to the timer command queue. + * When the command is actually processed will depend on the priority of the + * timer service/daemon task relative to other tasks in the system. The timer + * service/daemon task priority is set by the configTIMER_TASK_PRIORITY + * configuration constant. + * + * Example usage: + * + * See the xTimerChangePeriod() API function example usage scenario. + */ +#define xTimerDelete( xTimer, xTicksToWait ) \ + xTimerGenericCommand( ( xTimer ), tmrCOMMAND_DELETE, 0U, NULL, ( xTicksToWait ) ) + +/** + * BaseType_t xTimerReset( TimerHandle_t xTimer, TickType_t xTicksToWait ); + * + * Timer functionality is provided by a timer service/daemon task. Many of the + * public FreeRTOS timer API functions send commands to the timer service task + * through a queue called the timer command queue. The timer command queue is + * private to the kernel itself and is not directly accessible to application + * code. The length of the timer command queue is set by the + * configTIMER_QUEUE_LENGTH configuration constant. + * + * xTimerReset() re-starts a timer that was previously created using the + * xTimerCreate() API function. If the timer had already been started and was + * already in the active state, then xTimerReset() will cause the timer to + * re-evaluate its expiry time so that it is relative to when xTimerReset() was + * called. If the timer was in the dormant state then xTimerReset() has + * equivalent functionality to the xTimerStart() API function. + * + * Resetting a timer ensures the timer is in the active state. If the timer + * is not stopped, deleted, or reset in the mean time, the callback function + * associated with the timer will get called 'n' ticks after xTimerReset() was + * called, where 'n' is the timers defined period. + * + * It is valid to call xTimerReset() before the scheduler has been started, but + * when this is done the timer will not actually start until the scheduler is + * started, and the timers expiry time will be relative to when the scheduler is + * started, not relative to when xTimerReset() was called. + * + * The configUSE_TIMERS configuration constant must be set to 1 for xTimerReset() + * to be available. + * + * @param xTimer The handle of the timer being reset/started/restarted. + * + * @param xTicksToWait Specifies the time, in ticks, that the calling task should + * be held in the Blocked state to wait for the reset command to be successfully + * sent to the timer command queue, should the queue already be full when + * xTimerReset() was called. xTicksToWait is ignored if xTimerReset() is called + * before the scheduler is started. + * + * @return pdFAIL will be returned if the reset command could not be sent to + * the timer command queue even after xTicksToWait ticks had passed. pdPASS will + * be returned if the command was successfully sent to the timer command queue. + * When the command is actually processed will depend on the priority of the + * timer service/daemon task relative to other tasks in the system, although the + * timers expiry time is relative to when xTimerStart() is actually called. The + * timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY + * configuration constant. + * + * Example usage: + * @verbatim + * // When a key is pressed, an LCD back-light is switched on. If 5 seconds pass + * // without a key being pressed, then the LCD back-light is switched off. In + * // this case, the timer is a one-shot timer. + * + * TimerHandle_t xBacklightTimer = NULL; + * + * // The callback function assigned to the one-shot timer. In this case the + * // parameter is not used. + * void vBacklightTimerCallback( TimerHandle_t pxTimer ) + * { + * // The timer expired, therefore 5 seconds must have passed since a key + * // was pressed. Switch off the LCD back-light. + * vSetBacklightState( BACKLIGHT_OFF ); + * } + * + * // The key press event handler. + * void vKeyPressEventHandler( char cKey ) + * { + * // Ensure the LCD back-light is on, then reset the timer that is + * // responsible for turning the back-light off after 5 seconds of + * // key inactivity. Wait 10 ticks for the command to be successfully sent + * // if it cannot be sent immediately. + * vSetBacklightState( BACKLIGHT_ON ); + * if( xTimerReset( xBacklightTimer, 100 ) != pdPASS ) + * { + * // The reset command was not executed successfully. Take appropriate + * // action here. + * } + * + * // Perform the rest of the key processing here. + * } + * + * void main( void ) + * { + * int32_t x; + * + * // Create then start the one-shot timer that is responsible for turning + * // the back-light off if no keys are pressed within a 5 second period. + * xBacklightTimer = xTimerCreate( "BacklightTimer", // Just a text name, not used by the kernel. + * ( 5000 / portTICK_PERIOD_MS), // The timer period in ticks. + * pdFALSE, // The timer is a one-shot timer. + * 0, // The id is not used by the callback so can take any value. + * vBacklightTimerCallback // The callback function that switches the LCD back-light off. + * ); + * + * if( xBacklightTimer == NULL ) + * { + * // The timer was not created. + * } + * else + * { + * // Start the timer. No block time is specified, and even if one was + * // it would be ignored because the scheduler has not yet been + * // started. + * if( xTimerStart( xBacklightTimer, 0 ) != pdPASS ) + * { + * // The timer could not be set into the Active state. + * } + * } + * + * // ... + * // Create tasks here. + * // ... + * + * // Starting the scheduler will start the timer running as it has already + * // been set into the active state. + * vTaskStartScheduler(); + * + * // Should not reach here. + * for( ;; ); + * } + * @endverbatim + */ +#define xTimerReset( xTimer, xTicksToWait ) \ + xTimerGenericCommand( ( xTimer ), tmrCOMMAND_RESET, ( xTaskGetTickCount() ), NULL, ( xTicksToWait ) ) + +/** + * BaseType_t xTimerStartFromISR( TimerHandle_t xTimer, + * BaseType_t *pxHigherPriorityTaskWoken ); + * + * A version of xTimerStart() that can be called from an interrupt service + * routine. + * + * @param xTimer The handle of the timer being started/restarted. + * + * @param pxHigherPriorityTaskWoken The timer service/daemon task spends most + * of its time in the Blocked state, waiting for messages to arrive on the timer + * command queue. Calling xTimerStartFromISR() writes a message to the timer + * command queue, so has the potential to transition the timer service/daemon + * task out of the Blocked state. If calling xTimerStartFromISR() causes the + * timer service/daemon task to leave the Blocked state, and the timer service/ + * daemon task has a priority equal to or greater than the currently executing + * task (the task that was interrupted), then *pxHigherPriorityTaskWoken will + * get set to pdTRUE internally within the xTimerStartFromISR() function. If + * xTimerStartFromISR() sets this value to pdTRUE then a context switch should + * be performed before the interrupt exits. + * + * @return pdFAIL will be returned if the start command could not be sent to + * the timer command queue. pdPASS will be returned if the command was + * successfully sent to the timer command queue. When the command is actually + * processed will depend on the priority of the timer service/daemon task + * relative to other tasks in the system, although the timers expiry time is + * relative to when xTimerStartFromISR() is actually called. The timer + * service/daemon task priority is set by the configTIMER_TASK_PRIORITY + * configuration constant. + * + * Example usage: + * @verbatim + * // This scenario assumes xBacklightTimer has already been created. When a + * // key is pressed, an LCD back-light is switched on. If 5 seconds pass + * // without a key being pressed, then the LCD back-light is switched off. In + * // this case, the timer is a one-shot timer, and unlike the example given for + * // the xTimerReset() function, the key press event handler is an interrupt + * // service routine. + * + * // The callback function assigned to the one-shot timer. In this case the + * // parameter is not used. + * void vBacklightTimerCallback( TimerHandle_t pxTimer ) + * { + * // The timer expired, therefore 5 seconds must have passed since a key + * // was pressed. Switch off the LCD back-light. + * vSetBacklightState( BACKLIGHT_OFF ); + * } + * + * // The key press interrupt service routine. + * void vKeyPressEventInterruptHandler( void ) + * { + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; + * + * // Ensure the LCD back-light is on, then restart the timer that is + * // responsible for turning the back-light off after 5 seconds of + * // key inactivity. This is an interrupt service routine so can only + * // call FreeRTOS API functions that end in "FromISR". + * vSetBacklightState( BACKLIGHT_ON ); + * + * // xTimerStartFromISR() or xTimerResetFromISR() could be called here + * // as both cause the timer to re-calculate its expiry time. + * // xHigherPriorityTaskWoken was initialised to pdFALSE when it was + * // declared (in this function). + * if( xTimerStartFromISR( xBacklightTimer, &xHigherPriorityTaskWoken ) != pdPASS ) + * { + * // The start command was not executed successfully. Take appropriate + * // action here. + * } + * + * // Perform the rest of the key processing here. + * + * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch + * // should be performed. The syntax required to perform a context switch + * // from inside an ISR varies from port to port, and from compiler to + * // compiler. Inspect the demos for the port you are using to find the + * // actual syntax required. + * if( xHigherPriorityTaskWoken != pdFALSE ) + * { + * // Call the interrupt safe yield function here (actual function + * // depends on the FreeRTOS port being used). + * } + * } + * @endverbatim + */ +#define xTimerStartFromISR( xTimer, pxHigherPriorityTaskWoken ) \ + xTimerGenericCommand( ( xTimer ), tmrCOMMAND_START_FROM_ISR, ( xTaskGetTickCountFromISR() ), ( pxHigherPriorityTaskWoken ), 0U ) + +/** + * BaseType_t xTimerStopFromISR( TimerHandle_t xTimer, + * BaseType_t *pxHigherPriorityTaskWoken ); + * + * A version of xTimerStop() that can be called from an interrupt service + * routine. + * + * @param xTimer The handle of the timer being stopped. + * + * @param pxHigherPriorityTaskWoken The timer service/daemon task spends most + * of its time in the Blocked state, waiting for messages to arrive on the timer + * command queue. Calling xTimerStopFromISR() writes a message to the timer + * command queue, so has the potential to transition the timer service/daemon + * task out of the Blocked state. If calling xTimerStopFromISR() causes the + * timer service/daemon task to leave the Blocked state, and the timer service/ + * daemon task has a priority equal to or greater than the currently executing + * task (the task that was interrupted), then *pxHigherPriorityTaskWoken will + * get set to pdTRUE internally within the xTimerStopFromISR() function. If + * xTimerStopFromISR() sets this value to pdTRUE then a context switch should + * be performed before the interrupt exits. + * + * @return pdFAIL will be returned if the stop command could not be sent to + * the timer command queue. pdPASS will be returned if the command was + * successfully sent to the timer command queue. When the command is actually + * processed will depend on the priority of the timer service/daemon task + * relative to other tasks in the system. The timer service/daemon task + * priority is set by the configTIMER_TASK_PRIORITY configuration constant. + * + * Example usage: + * @verbatim + * // This scenario assumes xTimer has already been created and started. When + * // an interrupt occurs, the timer should be simply stopped. + * + * // The interrupt service routine that stops the timer. + * void vAnExampleInterruptServiceRoutine( void ) + * { + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; + * + * // The interrupt has occurred - simply stop the timer. + * // xHigherPriorityTaskWoken was set to pdFALSE where it was defined + * // (within this function). As this is an interrupt service routine, only + * // FreeRTOS API functions that end in "FromISR" can be used. + * if( xTimerStopFromISR( xTimer, &xHigherPriorityTaskWoken ) != pdPASS ) + * { + * // The stop command was not executed successfully. Take appropriate + * // action here. + * } + * + * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch + * // should be performed. The syntax required to perform a context switch + * // from inside an ISR varies from port to port, and from compiler to + * // compiler. Inspect the demos for the port you are using to find the + * // actual syntax required. + * if( xHigherPriorityTaskWoken != pdFALSE ) + * { + * // Call the interrupt safe yield function here (actual function + * // depends on the FreeRTOS port being used). + * } + * } + * @endverbatim + */ +#define xTimerStopFromISR( xTimer, pxHigherPriorityTaskWoken ) \ + xTimerGenericCommand( ( xTimer ), tmrCOMMAND_STOP_FROM_ISR, 0, ( pxHigherPriorityTaskWoken ), 0U ) + +/** + * BaseType_t xTimerChangePeriodFromISR( TimerHandle_t xTimer, + * TickType_t xNewPeriod, + * BaseType_t *pxHigherPriorityTaskWoken ); + * + * A version of xTimerChangePeriod() that can be called from an interrupt + * service routine. + * + * @param xTimer The handle of the timer that is having its period changed. + * + * @param xNewPeriod The new period for xTimer. Timer periods are specified in + * tick periods, so the constant portTICK_PERIOD_MS can be used to convert a time + * that has been specified in milliseconds. For example, if the timer must + * expire after 100 ticks, then xNewPeriod should be set to 100. Alternatively, + * if the timer must expire after 500ms, then xNewPeriod can be set to + * ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than + * or equal to 1000. + * + * @param pxHigherPriorityTaskWoken The timer service/daemon task spends most + * of its time in the Blocked state, waiting for messages to arrive on the timer + * command queue. Calling xTimerChangePeriodFromISR() writes a message to the + * timer command queue, so has the potential to transition the timer service/ + * daemon task out of the Blocked state. If calling xTimerChangePeriodFromISR() + * causes the timer service/daemon task to leave the Blocked state, and the + * timer service/daemon task has a priority equal to or greater than the + * currently executing task (the task that was interrupted), then + * *pxHigherPriorityTaskWoken will get set to pdTRUE internally within the + * xTimerChangePeriodFromISR() function. If xTimerChangePeriodFromISR() sets + * this value to pdTRUE then a context switch should be performed before the + * interrupt exits. + * + * @return pdFAIL will be returned if the command to change the timers period + * could not be sent to the timer command queue. pdPASS will be returned if the + * command was successfully sent to the timer command queue. When the command + * is actually processed will depend on the priority of the timer service/daemon + * task relative to other tasks in the system. The timer service/daemon task + * priority is set by the configTIMER_TASK_PRIORITY configuration constant. + * + * Example usage: + * @verbatim + * // This scenario assumes xTimer has already been created and started. When + * // an interrupt occurs, the period of xTimer should be changed to 500ms. + * + * // The interrupt service routine that changes the period of xTimer. + * void vAnExampleInterruptServiceRoutine( void ) + * { + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; + * + * // The interrupt has occurred - change the period of xTimer to 500ms. + * // xHigherPriorityTaskWoken was set to pdFALSE where it was defined + * // (within this function). As this is an interrupt service routine, only + * // FreeRTOS API functions that end in "FromISR" can be used. + * if( xTimerChangePeriodFromISR( xTimer, &xHigherPriorityTaskWoken ) != pdPASS ) + * { + * // The command to change the timers period was not executed + * // successfully. Take appropriate action here. + * } + * + * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch + * // should be performed. The syntax required to perform a context switch + * // from inside an ISR varies from port to port, and from compiler to + * // compiler. Inspect the demos for the port you are using to find the + * // actual syntax required. + * if( xHigherPriorityTaskWoken != pdFALSE ) + * { + * // Call the interrupt safe yield function here (actual function + * // depends on the FreeRTOS port being used). + * } + * } + * @endverbatim + */ +#define xTimerChangePeriodFromISR( xTimer, xNewPeriod, pxHigherPriorityTaskWoken ) \ + xTimerGenericCommand( ( xTimer ), tmrCOMMAND_CHANGE_PERIOD_FROM_ISR, ( xNewPeriod ), ( pxHigherPriorityTaskWoken ), 0U ) + +/** + * BaseType_t xTimerResetFromISR( TimerHandle_t xTimer, + * BaseType_t *pxHigherPriorityTaskWoken ); + * + * A version of xTimerReset() that can be called from an interrupt service + * routine. + * + * @param xTimer The handle of the timer that is to be started, reset, or + * restarted. + * + * @param pxHigherPriorityTaskWoken The timer service/daemon task spends most + * of its time in the Blocked state, waiting for messages to arrive on the timer + * command queue. Calling xTimerResetFromISR() writes a message to the timer + * command queue, so has the potential to transition the timer service/daemon + * task out of the Blocked state. If calling xTimerResetFromISR() causes the + * timer service/daemon task to leave the Blocked state, and the timer service/ + * daemon task has a priority equal to or greater than the currently executing + * task (the task that was interrupted), then *pxHigherPriorityTaskWoken will + * get set to pdTRUE internally within the xTimerResetFromISR() function. If + * xTimerResetFromISR() sets this value to pdTRUE then a context switch should + * be performed before the interrupt exits. + * + * @return pdFAIL will be returned if the reset command could not be sent to + * the timer command queue. pdPASS will be returned if the command was + * successfully sent to the timer command queue. When the command is actually + * processed will depend on the priority of the timer service/daemon task + * relative to other tasks in the system, although the timers expiry time is + * relative to when xTimerResetFromISR() is actually called. The timer service/daemon + * task priority is set by the configTIMER_TASK_PRIORITY configuration constant. + * + * Example usage: + * @verbatim + * // This scenario assumes xBacklightTimer has already been created. When a + * // key is pressed, an LCD back-light is switched on. If 5 seconds pass + * // without a key being pressed, then the LCD back-light is switched off. In + * // this case, the timer is a one-shot timer, and unlike the example given for + * // the xTimerReset() function, the key press event handler is an interrupt + * // service routine. + * + * // The callback function assigned to the one-shot timer. In this case the + * // parameter is not used. + * void vBacklightTimerCallback( TimerHandle_t pxTimer ) + * { + * // The timer expired, therefore 5 seconds must have passed since a key + * // was pressed. Switch off the LCD back-light. + * vSetBacklightState( BACKLIGHT_OFF ); + * } + * + * // The key press interrupt service routine. + * void vKeyPressEventInterruptHandler( void ) + * { + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; + * + * // Ensure the LCD back-light is on, then reset the timer that is + * // responsible for turning the back-light off after 5 seconds of + * // key inactivity. This is an interrupt service routine so can only + * // call FreeRTOS API functions that end in "FromISR". + * vSetBacklightState( BACKLIGHT_ON ); + * + * // xTimerStartFromISR() or xTimerResetFromISR() could be called here + * // as both cause the timer to re-calculate its expiry time. + * // xHigherPriorityTaskWoken was initialised to pdFALSE when it was + * // declared (in this function). + * if( xTimerResetFromISR( xBacklightTimer, &xHigherPriorityTaskWoken ) != pdPASS ) + * { + * // The reset command was not executed successfully. Take appropriate + * // action here. + * } + * + * // Perform the rest of the key processing here. + * + * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch + * // should be performed. The syntax required to perform a context switch + * // from inside an ISR varies from port to port, and from compiler to + * // compiler. Inspect the demos for the port you are using to find the + * // actual syntax required. + * if( xHigherPriorityTaskWoken != pdFALSE ) + * { + * // Call the interrupt safe yield function here (actual function + * // depends on the FreeRTOS port being used). + * } + * } + * @endverbatim + */ +#define xTimerResetFromISR( xTimer, pxHigherPriorityTaskWoken ) \ + xTimerGenericCommand( ( xTimer ), tmrCOMMAND_RESET_FROM_ISR, ( xTaskGetTickCountFromISR() ), ( pxHigherPriorityTaskWoken ), 0U ) + + +/** + * BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, + * void *pvParameter1, + * uint32_t ulParameter2, + * BaseType_t *pxHigherPriorityTaskWoken ); + * + * + * Used from application interrupt service routines to defer the execution of a + * function to the RTOS daemon task (the timer service task, hence this function + * is implemented in timers.c and is prefixed with 'Timer'). + * + * Ideally an interrupt service routine (ISR) is kept as short as possible, but + * sometimes an ISR either has a lot of processing to do, or needs to perform + * processing that is not deterministic. In these cases + * xTimerPendFunctionCallFromISR() can be used to defer processing of a function + * to the RTOS daemon task. + * + * A mechanism is provided that allows the interrupt to return directly to the + * task that will subsequently execute the pended callback function. This + * allows the callback function to execute contiguously in time with the + * interrupt - just as if the callback had executed in the interrupt itself. + * + * @param xFunctionToPend The function to execute from the timer service/ + * daemon task. The function must conform to the PendedFunction_t + * prototype. + * + * @param pvParameter1 The value of the callback function's first parameter. + * The parameter has a void * type to allow it to be used to pass any type. + * For example, unsigned longs can be cast to a void *, or the void * can be + * used to point to a structure. + * + * @param ulParameter2 The value of the callback function's second parameter. + * + * @param pxHigherPriorityTaskWoken As mentioned above, calling this function + * will result in a message being sent to the timer daemon task. If the + * priority of the timer daemon task (which is set using + * configTIMER_TASK_PRIORITY in FreeRTOSConfig.h) is higher than the priority of + * the currently running task (the task the interrupt interrupted) then + * *pxHigherPriorityTaskWoken will be set to pdTRUE within + * xTimerPendFunctionCallFromISR(), indicating that a context switch should be + * requested before the interrupt exits. For that reason + * *pxHigherPriorityTaskWoken must be initialised to pdFALSE. See the + * example code below. + * + * @return pdPASS is returned if the message was successfully sent to the + * timer daemon task, otherwise pdFALSE is returned. + * + * Example usage: + * @verbatim + * + * // The callback function that will execute in the context of the daemon task. + * // Note callback functions must all use this same prototype. + * void vProcessInterface( void *pvParameter1, uint32_t ulParameter2 ) + * { + * BaseType_t xInterfaceToService; + * + * // The interface that requires servicing is passed in the second + * // parameter. The first parameter is not used in this case. + * xInterfaceToService = ( BaseType_t ) ulParameter2; + * + * // ...Perform the processing here... + * } + * + * // An ISR that receives data packets from multiple interfaces + * void vAnISR( void ) + * { + * BaseType_t xInterfaceToService, xHigherPriorityTaskWoken; + * + * // Query the hardware to determine which interface needs processing. + * xInterfaceToService = prvCheckInterfaces(); + * + * // The actual processing is to be deferred to a task. Request the + * // vProcessInterface() callback function is executed, passing in the + * // number of the interface that needs processing. The interface to + * // service is passed in the second parameter. The first parameter is + * // not used in this case. + * xHigherPriorityTaskWoken = pdFALSE; + * xTimerPendFunctionCallFromISR( vProcessInterface, NULL, ( uint32_t ) xInterfaceToService, &xHigherPriorityTaskWoken ); + * + * // If xHigherPriorityTaskWoken is now set to pdTRUE then a context + * // switch should be requested. The macro used is port specific and will + * // be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() - refer to + * // the documentation page for the port being used. + * portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); + * + * } + * @endverbatim + */ +BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, + void * pvParameter1, + uint32_t ulParameter2, + BaseType_t * pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + +/** + * BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, + * void *pvParameter1, + * uint32_t ulParameter2, + * TickType_t xTicksToWait ); + * + * + * Used to defer the execution of a function to the RTOS daemon task (the timer + * service task, hence this function is implemented in timers.c and is prefixed + * with 'Timer'). + * + * @param xFunctionToPend The function to execute from the timer service/ + * daemon task. The function must conform to the PendedFunction_t + * prototype. + * + * @param pvParameter1 The value of the callback function's first parameter. + * The parameter has a void * type to allow it to be used to pass any type. + * For example, unsigned longs can be cast to a void *, or the void * can be + * used to point to a structure. + * + * @param ulParameter2 The value of the callback function's second parameter. + * + * @param xTicksToWait Calling this function will result in a message being + * sent to the timer daemon task on a queue. xTicksToWait is the amount of + * time the calling task should remain in the Blocked state (so not using any + * processing time) for space to become available on the timer queue if the + * queue is found to be full. + * + * @return pdPASS is returned if the message was successfully sent to the + * timer daemon task, otherwise pdFALSE is returned. + * + */ +BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, + void * pvParameter1, + uint32_t ulParameter2, + TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/** + * const char * const pcTimerGetName( TimerHandle_t xTimer ); + * + * Returns the name that was assigned to a timer when the timer was created. + * + * @param xTimer The handle of the timer being queried. + * + * @return The name assigned to the timer specified by the xTimer parameter. + */ +const char * pcTimerGetName( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + +/** + * void vTimerSetReloadMode( TimerHandle_t xTimer, const UBaseType_t uxAutoReload ); + * + * Updates a timer to be either an auto-reload timer, in which case the timer + * automatically resets itself each time it expires, or a one-shot timer, in + * which case the timer will only expire once unless it is manually restarted. + * + * @param xTimer The handle of the timer being updated. + * + * @param uxAutoReload If uxAutoReload is set to pdTRUE then the timer will + * expire repeatedly with a frequency set by the timer's period (see the + * xTimerPeriodInTicks parameter of the xTimerCreate() API function). If + * uxAutoReload is set to pdFALSE then the timer will be a one-shot timer and + * enter the dormant state after it expires. + */ +void vTimerSetReloadMode( TimerHandle_t xTimer, + const UBaseType_t uxAutoReload ) PRIVILEGED_FUNCTION; + +/** + * UBaseType_t uxTimerGetReloadMode( TimerHandle_t xTimer ); + * + * Queries a timer to determine if it is an auto-reload timer, in which case the timer + * automatically resets itself each time it expires, or a one-shot timer, in + * which case the timer will only expire once unless it is manually restarted. + * + * @param xTimer The handle of the timer being queried. + * + * @return If the timer is an auto-reload timer then pdTRUE is returned, otherwise + * pdFALSE is returned. + */ +UBaseType_t uxTimerGetReloadMode( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; + +/** + * TickType_t xTimerGetPeriod( TimerHandle_t xTimer ); + * + * Returns the period of a timer. + * + * @param xTimer The handle of the timer being queried. + * + * @return The period of the timer in ticks. + */ +TickType_t xTimerGetPeriod( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; + +/** + * TickType_t xTimerGetExpiryTime( TimerHandle_t xTimer ); + * + * Returns the time in ticks at which the timer will expire. If this is less + * than the current tick count then the expiry time has overflowed from the + * current time. + * + * @param xTimer The handle of the timer being queried. + * + * @return If the timer is running then the time in ticks at which the timer + * will next expire is returned. If the timer is not running then the return + * value is undefined. + */ +TickType_t xTimerGetExpiryTime( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; + +/* + * Functions beyond this part are not part of the public API and are intended + * for use by the kernel only. + */ +BaseType_t xTimerCreateTimerTask( void ) PRIVILEGED_FUNCTION; +BaseType_t xTimerGenericCommand( TimerHandle_t xTimer, + const BaseType_t xCommandID, + const TickType_t xOptionalValue, + BaseType_t * const pxHigherPriorityTaskWoken, + const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +#if ( configUSE_TRACE_FACILITY == 1 ) + void vTimerSetTimerNumber( TimerHandle_t xTimer, + UBaseType_t uxTimerNumber ) PRIVILEGED_FUNCTION; + UBaseType_t uxTimerGetTimerNumber( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; +#endif + +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + + /** + * task.h + *
void vApplicationGetTimerTaskMemory( StaticTask_t ** ppxTimerTaskTCBBuffer, StackType_t ** ppxTimerTaskStackBuffer, uint32_t *pulTimerTaskStackSize ) 
+ * + * This function is used to provide a statically allocated block of memory to FreeRTOS to hold the Timer Task TCB. This function is required when + * configSUPPORT_STATIC_ALLOCATION is set. For more information see this URI: https://www.FreeRTOS.org/a00110.html#configSUPPORT_STATIC_ALLOCATION + * + * @param ppxTimerTaskTCBBuffer A handle to a statically allocated TCB buffer + * @param ppxTimerTaskStackBuffer A handle to a statically allocated Stack buffer for thie idle task + * @param pulTimerTaskStackSize A pointer to the number of elements that will fit in the allocated stack buffer + */ + void vApplicationGetTimerTaskMemory( StaticTask_t ** ppxTimerTaskTCBBuffer, + StackType_t ** ppxTimerTaskStackBuffer, + uint32_t * pulTimerTaskStackSize ); + +#endif + +/* *INDENT-OFF* */ +#ifdef __cplusplus + } +#endif +/* *INDENT-ON* */ +#endif /* TIMERS_H */ diff --git a/examples/stm32/freertos-kernel/list.c b/examples/stm32/freertos-kernel/list.c new file mode 100644 index 00000000..17a4e903 --- /dev/null +++ b/examples/stm32/freertos-kernel/list.c @@ -0,0 +1,210 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + + +#include + +/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining + * all the API functions to use the MPU wrappers. That should only be done when + * task.h is included from an application file. */ +#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +#include "FreeRTOS.h" +#include "list.h" + +/* Lint e9021, e961 and e750 are suppressed as a MISRA exception justified + * because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be + * defined for the header files above, but not in this file, in order to + * generate the correct privileged Vs unprivileged linkage and placement. */ +#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750 !e9021. */ + +/*----------------------------------------------------------- +* PUBLIC LIST API documented in list.h +*----------------------------------------------------------*/ + +void vListInitialise( List_t * const pxList ) +{ + /* The list structure contains a list item which is used to mark the + * end of the list. To initialise the list the list end is inserted + * as the only list entry. */ + pxList->pxIndex = ( ListItem_t * ) &( pxList->xListEnd ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ + + /* The list end value is the highest possible value in the list to + * ensure it remains at the end of the list. */ + pxList->xListEnd.xItemValue = portMAX_DELAY; + + /* The list end next and previous pointers point to itself so we know + * when the list is empty. */ + pxList->xListEnd.pxNext = ( ListItem_t * ) &( pxList->xListEnd ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ + pxList->xListEnd.pxPrevious = ( ListItem_t * ) &( pxList->xListEnd ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ + + pxList->uxNumberOfItems = ( UBaseType_t ) 0U; + + /* Write known values into the list if + * configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ); + listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ); +} +/*-----------------------------------------------------------*/ + +void vListInitialiseItem( ListItem_t * const pxItem ) +{ + /* Make sure the list item is not recorded as being on a list. */ + pxItem->pxContainer = NULL; + + /* Write known values into the list item if + * configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ); + listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ); +} +/*-----------------------------------------------------------*/ + +void vListInsertEnd( List_t * const pxList, + ListItem_t * const pxNewListItem ) +{ + ListItem_t * const pxIndex = pxList->pxIndex; + + /* Only effective when configASSERT() is also defined, these tests may catch + * the list data structures being overwritten in memory. They will not catch + * data errors caused by incorrect configuration or use of FreeRTOS. */ + listTEST_LIST_INTEGRITY( pxList ); + listTEST_LIST_ITEM_INTEGRITY( pxNewListItem ); + + /* Insert a new list item into pxList, but rather than sort the list, + * makes the new list item the last item to be removed by a call to + * listGET_OWNER_OF_NEXT_ENTRY(). */ + pxNewListItem->pxNext = pxIndex; + pxNewListItem->pxPrevious = pxIndex->pxPrevious; + + /* Only used during decision coverage testing. */ + mtCOVERAGE_TEST_DELAY(); + + pxIndex->pxPrevious->pxNext = pxNewListItem; + pxIndex->pxPrevious = pxNewListItem; + + /* Remember which list the item is in. */ + pxNewListItem->pxContainer = pxList; + + ( pxList->uxNumberOfItems )++; +} +/*-----------------------------------------------------------*/ + +void vListInsert( List_t * const pxList, + ListItem_t * const pxNewListItem ) +{ + ListItem_t * pxIterator; + const TickType_t xValueOfInsertion = pxNewListItem->xItemValue; + + /* Only effective when configASSERT() is also defined, these tests may catch + * the list data structures being overwritten in memory. They will not catch + * data errors caused by incorrect configuration or use of FreeRTOS. */ + listTEST_LIST_INTEGRITY( pxList ); + listTEST_LIST_ITEM_INTEGRITY( pxNewListItem ); + + /* Insert the new list item into the list, sorted in xItemValue order. + * + * If the list already contains a list item with the same item value then the + * new list item should be placed after it. This ensures that TCBs which are + * stored in ready lists (all of which have the same xItemValue value) get a + * share of the CPU. However, if the xItemValue is the same as the back marker + * the iteration loop below will not end. Therefore the value is checked + * first, and the algorithm slightly modified if necessary. */ + if( xValueOfInsertion == portMAX_DELAY ) + { + pxIterator = pxList->xListEnd.pxPrevious; + } + else + { + /* *** NOTE *********************************************************** + * If you find your application is crashing here then likely causes are + * listed below. In addition see https://www.FreeRTOS.org/FAQHelp.html for + * more tips, and ensure configASSERT() is defined! + * https://www.FreeRTOS.org/a00110.html#configASSERT + * + * 1) Stack overflow - + * see https://www.FreeRTOS.org/Stacks-and-stack-overflow-checking.html + * 2) Incorrect interrupt priority assignment, especially on Cortex-M + * parts where numerically high priority values denote low actual + * interrupt priorities, which can seem counter intuitive. See + * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html and the definition + * of configMAX_SYSCALL_INTERRUPT_PRIORITY on + * https://www.FreeRTOS.org/a00110.html + * 3) Calling an API function from within a critical section or when + * the scheduler is suspended, or calling an API function that does + * not end in "FromISR" from an interrupt. + * 4) Using a queue or semaphore before it has been initialised or + * before the scheduler has been started (are interrupts firing + * before vTaskStartScheduler() has been called?). + **********************************************************************/ + + 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/examples/stm32/freertos-kernel/portable/GCC/ARM_CM7/ReadMe.txt b/examples/stm32/freertos-kernel/portable/GCC/ARM_CM7/ReadMe.txt new file mode 100644 index 00000000..d661449e --- /dev/null +++ b/examples/stm32/freertos-kernel/portable/GCC/ARM_CM7/ReadMe.txt @@ -0,0 +1,18 @@ +There are two options for running FreeRTOS on ARM Cortex-M7 microcontrollers. +The best option depends on the revision of the ARM Cortex-M7 core in use. The +revision is specified by an 'r' number, and a 'p' number, so will look something +like 'r0p1'. Check the documentation for the microcontroller in use to find the +revision of the Cortex-M7 core used in that microcontroller. If in doubt, use +the FreeRTOS port provided specifically for r0p1 revisions, as that can be used +with all core revisions. + +The first option is to use the ARM Cortex-M4F port, and the second option is to +use the Cortex-M7 r0p1 port - the latter containing a minor errata workaround. + +If the revision of the ARM Cortex-M7 core is not r0p1 then either option can be +used, but it is recommended to use the FreeRTOS ARM Cortex-M4F port located in +the /FreeRTOS/Source/portable/GCC/ARM_CM4F directory. + +If the revision of the ARM Cortex-M7 core is r0p1 then use the FreeRTOS ARM +Cortex-M7 r0p1 port located in the /FreeRTOS/Source/portable/GCC/ARM_CM7/r0p1 +directory. \ No newline at end of file diff --git a/examples/stm32/freertos-kernel/portable/GCC/ARM_CM7/r0p1/port.c b/examples/stm32/freertos-kernel/portable/GCC/ARM_CM7/r0p1/port.c new file mode 100644 index 00000000..e30e0767 --- /dev/null +++ b/examples/stm32/freertos-kernel/portable/GCC/ARM_CM7/r0p1/port.c @@ -0,0 +1,773 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/*----------------------------------------------------------- +* Implementation of functions defined in portable.h for the ARM CM7 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_SHPR3_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 ) + +#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" + " .ltorg \n" + ); +} +/*-----------------------------------------------------------*/ + +/* + * See header file for description. + */ +BaseType_t xPortStartScheduler( void ) +{ + /* configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to 0. + * See https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + configASSERT( configMAX_SYSCALL_INTERRUPT_PRIORITY ); + + #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_SHPR3_REG |= portNVIC_PENDSV_PRI; + portNVIC_SHPR3_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" + " cpsid i \n"/* Errata workaround. */ + " msr basepri, r0 \n" + " dsb \n" + " isb \n" + " cpsie i \n"/* Errata workaround. */ + " 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 \n" + " .ltorg \n" + ); +} +/*-----------------------------------------------------------*/ + +#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: + * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html + * https://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/examples/stm32/freertos-kernel/portable/GCC/ARM_CM7/r0p1/portmacro.h b/examples/stm32/freertos-kernel/portable/GCC/ARM_CM7/r0p1/portmacro.h new file mode 100644 index 00000000..4aae2be6 --- /dev/null +++ b/examples/stm32/freertos-kernel/portable/GCC/ARM_CM7/r0p1/portmacro.h @@ -0,0 +1,248 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + * 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 + #define portDONT_DISCARD __attribute__( ( used ) ) +/*-----------------------------------------------------------*/ + +/* 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"\ + " cpsid i \n"\ + " msr basepri, %0 \n"\ + " isb \n"\ + " dsb \n"\ + " cpsie i \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"\ + " cpsid i \n"\ + " msr basepri, %1 \n"\ + " isb \n"\ + " dsb \n"\ + " cpsie i \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/examples/stm32/freertos-kernel/portable/MemMang/ReadMe.url b/examples/stm32/freertos-kernel/portable/MemMang/ReadMe.url new file mode 100644 index 00000000..4d2d0442 --- /dev/null +++ b/examples/stm32/freertos-kernel/portable/MemMang/ReadMe.url @@ -0,0 +1,5 @@ +[{000214A0-0000-0000-C000-000000000046}] +Prop3=19,2 +[InternetShortcut] +URL=https://www.FreeRTOS.org/a00111.html +IDList= diff --git a/examples/stm32/freertos-kernel/portable/MemMang/heap_1.c b/examples/stm32/freertos-kernel/portable/MemMang/heap_1.c new file mode 100644 index 00000000..a1e96bdf --- /dev/null +++ b/examples/stm32/freertos-kernel/portable/MemMang/heap_1.c @@ -0,0 +1,151 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + + +/* + * The simplest possible implementation of pvPortMalloc(). Note that this + * implementation does NOT allow allocated memory to be freed again. + * + * See heap_2.c, heap_3.c and heap_4.c for alternative implementations, and the + * memory management pages of https://www.FreeRTOS.org for more information. + */ +#include + +/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining + * all the API functions to use the MPU wrappers. That should only be done when + * task.h is included from an application file. */ +#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +#include "FreeRTOS.h" +#include "task.h" + +#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +#if ( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) + #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 +#endif + +/* A few bytes might be lost to byte aligning the heap start address. */ +#define configADJUSTED_HEAP_SIZE ( configTOTAL_HEAP_SIZE - portBYTE_ALIGNMENT ) + +/* 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 */ + +/* Index into the ucHeap array. */ +static size_t xNextFreeByte = ( size_t ) 0; + +/*-----------------------------------------------------------*/ + +void * pvPortMalloc( size_t xWantedSize ) +{ + void * pvReturn = NULL; + static uint8_t * pucAlignedHeap = NULL; + + /* Ensure that blocks are always aligned. */ + #if ( portBYTE_ALIGNMENT != 1 ) + { + if( xWantedSize & portBYTE_ALIGNMENT_MASK ) + { + /* Byte alignment required. Check for overflow. */ + if ( (xWantedSize + ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) )) > xWantedSize ) + { + xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); + } + else + { + xWantedSize = 0; + } + } + } + #endif + + vTaskSuspendAll(); + { + if( pucAlignedHeap == NULL ) + { + /* Ensure the heap starts on a correctly aligned boundary. */ + pucAlignedHeap = ( uint8_t * ) ( ( ( portPOINTER_SIZE_TYPE ) & ucHeap[ portBYTE_ALIGNMENT ] ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); + } + + /* Check there is enough room left for the allocation and. */ + if( ( xWantedSize > 0 ) && /* valid size */ + ( ( xNextFreeByte + xWantedSize ) < configADJUSTED_HEAP_SIZE ) && + ( ( xNextFreeByte + xWantedSize ) > xNextFreeByte ) ) /* Check for overflow. */ + { + /* Return the next free byte then increment the index past this + * block. */ + pvReturn = pucAlignedHeap + xNextFreeByte; + xNextFreeByte += xWantedSize; + } + + traceMALLOC( pvReturn, xWantedSize ); + } + ( void ) xTaskResumeAll(); + + #if ( configUSE_MALLOC_FAILED_HOOK == 1 ) + { + if( pvReturn == NULL ) + { + extern void vApplicationMallocFailedHook( void ); + vApplicationMallocFailedHook(); + } + } + #endif + + return pvReturn; +} +/*-----------------------------------------------------------*/ + +void vPortFree( void * pv ) +{ + /* Memory cannot be freed using this scheme. See heap_2.c, heap_3.c and + * heap_4.c for alternative implementations, and the memory management pages of + * https://www.FreeRTOS.org for more information. */ + ( void ) pv; + + /* Force an assert as it is invalid to call this function. */ + configASSERT( pv == NULL ); +} +/*-----------------------------------------------------------*/ + +void vPortInitialiseBlocks( void ) +{ + /* Only required when static memory is not cleared. */ + xNextFreeByte = ( size_t ) 0; +} +/*-----------------------------------------------------------*/ + +size_t xPortGetFreeHeapSize( void ) +{ + return( configADJUSTED_HEAP_SIZE - xNextFreeByte ); +} diff --git a/examples/stm32/freertos-kernel/portable/MemMang/heap_2.c b/examples/stm32/freertos-kernel/portable/MemMang/heap_2.c new file mode 100644 index 00000000..42fdaa96 --- /dev/null +++ b/examples/stm32/freertos-kernel/portable/MemMang/heap_2.c @@ -0,0 +1,284 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* + * A sample implementation of pvPortMalloc() and vPortFree() that permits + * allocated blocks to be freed, but does not combine adjacent free blocks + * into a single larger block (and so will fragment memory). See heap_4.c for + * an equivalent that does combine adjacent blocks into single larger blocks. + * + * See heap_1.c, heap_3.c and heap_4.c for alternative implementations, and the + * memory management pages of https://www.FreeRTOS.org for more information. + */ +#include + +/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining + * all the API functions to use the MPU wrappers. That should only be done when + * task.h is included from an application file. */ +#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +#include "FreeRTOS.h" +#include "task.h" + +#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +#if ( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) + #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 +#endif + +/* A few bytes might be lost to byte aligning the heap start address. */ +#define configADJUSTED_HEAP_SIZE ( configTOTAL_HEAP_SIZE - portBYTE_ALIGNMENT ) + +/* + * Initialises the heap structures before their first use. + */ +static void prvHeapInit( void ); + +/* 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 size. */ +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; + + +static const uint16_t heapSTRUCT_SIZE = ( ( sizeof( BlockLink_t ) + ( portBYTE_ALIGNMENT - 1 ) ) & ~portBYTE_ALIGNMENT_MASK ); +#define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( heapSTRUCT_SIZE * 2 ) ) + +/* Create a couple of list links to mark the start and end of the list. */ +static BlockLink_t xStart, xEnd; + +/* Keeps track of the number of free bytes remaining, but says nothing about + * fragmentation. */ +static size_t xFreeBytesRemaining = configADJUSTED_HEAP_SIZE; + +/* STATIC FUNCTIONS ARE DEFINED AS MACROS TO MINIMIZE THE FUNCTION CALL DEPTH. */ + +/* + * Insert a block into the list of free blocks - which is ordered by size of + * the block. Small blocks at the start of the list and large blocks at the end + * of the list. + */ +#define prvInsertBlockIntoFreeList( pxBlockToInsert ) \ + { \ + BlockLink_t * pxIterator; \ + size_t xBlockSize; \ + \ + xBlockSize = pxBlockToInsert->xBlockSize; \ + \ + /* Iterate through the list until a block is found that has a larger size */ \ + /* than the block we are inserting. */ \ + for( pxIterator = &xStart; pxIterator->pxNextFreeBlock->xBlockSize < xBlockSize; pxIterator = pxIterator->pxNextFreeBlock ) \ + { \ + /* There is nothing to do here - just iterate to the correct position. */ \ + } \ + \ + /* Update the list to include the block being inserted in the correct */ \ + /* position. */ \ + pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock; \ + pxIterator->pxNextFreeBlock = pxBlockToInsert; \ + } +/*-----------------------------------------------------------*/ + +void * pvPortMalloc( size_t xWantedSize ) +{ + BlockLink_t * pxBlock, * pxPreviousBlock, * pxNewBlockLink; + static BaseType_t xHeapHasBeenInitialised = pdFALSE; + 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( xHeapHasBeenInitialised == pdFALSE ) + { + prvHeapInit(); + xHeapHasBeenInitialised = pdTRUE; + } + + /* The wanted size must be increased so it can contain a BlockLink_t + * structure in addition to the requested amount of bytes. */ + if( ( xWantedSize > 0 ) && + ( ( xWantedSize + heapSTRUCT_SIZE ) > xWantedSize ) ) /* Overflow check */ + { + xWantedSize += heapSTRUCT_SIZE; + + /* Byte alignment required. Check for overflow. */ + if( ( xWantedSize + ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ) ) + > xWantedSize ) + { + xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); + configASSERT( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) == 0 ); + } + else + { + xWantedSize = 0; + } + } + else + { + xWantedSize = 0; + } + + + if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) ) + { + /* Blocks are stored in byte order - traverse the list from the start + * (smallest) 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 we found the end marker then a block of adequate size was not found. */ + if( pxBlock != &xEnd ) + { + /* Return the memory space - jumping over the BlockLink_t structure + * at its start. */ + pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + heapSTRUCT_SIZE ); + + /* 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 ); + + /* 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 ) ); + } + + xFreeBytesRemaining -= pxBlock->xBlockSize; + } + } + + traceMALLOC( pvReturn, xWantedSize ); + } + ( void ) xTaskResumeAll(); + + #if ( configUSE_MALLOC_FAILED_HOOK == 1 ) + { + if( pvReturn == NULL ) + { + extern void vApplicationMallocFailedHook( void ); + vApplicationMallocFailedHook(); + } + } + #endif + + 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 -= heapSTRUCT_SIZE; + + /* This unexpected casting is to keep some compilers from issuing + * byte alignment warnings. */ + pxLink = ( void * ) puc; + + vTaskSuspendAll(); + { + /* Add this block to the list of free blocks. */ + prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) ); + xFreeBytesRemaining += pxLink->xBlockSize; + traceFREE( pv, pxLink->xBlockSize ); + } + ( void ) xTaskResumeAll(); + } +} +/*-----------------------------------------------------------*/ + +size_t xPortGetFreeHeapSize( void ) +{ + return xFreeBytesRemaining; +} +/*-----------------------------------------------------------*/ + +void vPortInitialiseBlocks( void ) +{ + /* This just exists to keep the linker quiet. */ +} +/*-----------------------------------------------------------*/ + +static void prvHeapInit( void ) +{ + BlockLink_t * pxFirstFreeBlock; + uint8_t * pucAlignedHeap; + + /* Ensure the heap starts on a correctly aligned boundary. */ + pucAlignedHeap = ( uint8_t * ) ( ( ( portPOINTER_SIZE_TYPE ) & ucHeap[ portBYTE_ALIGNMENT ] ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); + + /* 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; + + /* xEnd is used to mark the end of the list of free blocks. */ + xEnd.xBlockSize = configADJUSTED_HEAP_SIZE; + xEnd.pxNextFreeBlock = NULL; + + /* To start with there is a single free block that is sized to take up the + * entire heap space. */ + pxFirstFreeBlock = ( void * ) pucAlignedHeap; + pxFirstFreeBlock->xBlockSize = configADJUSTED_HEAP_SIZE; + pxFirstFreeBlock->pxNextFreeBlock = &xEnd; +} +/*-----------------------------------------------------------*/ diff --git a/examples/stm32/freertos-kernel/portable/MemMang/heap_3.c b/examples/stm32/freertos-kernel/portable/MemMang/heap_3.c new file mode 100644 index 00000000..677fefb6 --- /dev/null +++ b/examples/stm32/freertos-kernel/portable/MemMang/heap_3.c @@ -0,0 +1,94 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + * 1 tab == 4 spaces! + */ + + +/* + * Implementation of pvPortMalloc() and vPortFree() that relies on the + * compilers own malloc() and free() implementations. + * + * This file can only be used if the linker is configured to to generate + * a heap memory area. + * + * See heap_1.c, heap_2.c and heap_4.c for alternative implementations, and the + * memory management pages of https://www.FreeRTOS.org for more information. + */ + +#include + +/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining + * all the API functions to use the MPU wrappers. That should only be done when + * task.h is included from an application file. */ +#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +#include "FreeRTOS.h" +#include "task.h" + +#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +#if ( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) + #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 +#endif + +/*-----------------------------------------------------------*/ + +void * pvPortMalloc( size_t xWantedSize ) +{ + void * pvReturn; + + vTaskSuspendAll(); + { + pvReturn = malloc( xWantedSize ); + traceMALLOC( pvReturn, xWantedSize ); + } + ( void ) xTaskResumeAll(); + + #if ( configUSE_MALLOC_FAILED_HOOK == 1 ) + { + if( pvReturn == NULL ) + { + extern void vApplicationMallocFailedHook( void ); + vApplicationMallocFailedHook(); + } + } + #endif + + return pvReturn; +} +/*-----------------------------------------------------------*/ + +void vPortFree( void * pv ) +{ + if( pv ) + { + vTaskSuspendAll(); + { + free( pv ); + traceFREE( pv, 0 ); + } + ( void ) xTaskResumeAll(); + } +} diff --git a/examples/stm32/freertos-kernel/portable/MemMang/heap_4.c b/examples/stm32/freertos-kernel/portable/MemMang/heap_4.c new file mode 100644 index 00000000..e4e52a80 --- /dev/null +++ b/examples/stm32/freertos-kernel/portable/MemMang/heap_4.c @@ -0,0 +1,502 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* + * A sample implementation of pvPortMalloc() and vPortFree() that combines + * (coalescences) adjacent memory blocks as they are freed, and in so doing + * limits memory fragmentation. + * + * See heap_1.c, heap_2.c and heap_3.c for alternative implementations, and the + * memory management pages of https://www.FreeRTOS.org for more information. + */ +#include + +/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining + * all the API functions to use the MPU wrappers. That should only be done when + * task.h is included from an application file. */ +#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +#include "FreeRTOS.h" +#include "task.h" + +#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +#if ( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) + #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 +#endif + +/* Block sizes must not get too small. */ +#define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( xHeapStructSize << 1 ) ) + +/* Assumes 8bit bytes! */ +#define heapBITS_PER_BYTE ( ( size_t ) 8 ) + +/* Allocate the memory for the heap. */ +#if ( configAPPLICATION_ALLOCATED_HEAP == 1 ) + +/* The application writer has already defined the array used for the RTOS +* heap - probably so it can be placed in a special segment or address. */ + extern uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; +#else + PRIVILEGED_DATA static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; +#endif /* configAPPLICATION_ALLOCATED_HEAP */ + +/* Define the linked list structure. This is used to link free blocks in order + * of their memory address. */ +typedef struct A_BLOCK_LINK +{ + struct A_BLOCK_LINK * pxNextFreeBlock; /*<< The next free block in the list. */ + size_t xBlockSize; /*<< The size of the free block. */ +} BlockLink_t; + +/*-----------------------------------------------------------*/ + +/* + * Inserts a block of memory that is being freed into the correct position in + * the list of free memory blocks. The block being freed will be merged with + * the block in front it and/or the block behind it if the memory blocks are + * adjacent to each other. + */ +static void prvInsertBlockIntoFreeList( BlockLink_t * pxBlockToInsert ) PRIVILEGED_FUNCTION; + +/* + * Called automatically to setup the required heap structures the first time + * pvPortMalloc() is called. + */ +static void prvHeapInit( void ) PRIVILEGED_FUNCTION; + +/*-----------------------------------------------------------*/ + +/* The size of the structure placed at the beginning of each allocated memory + * block must by correctly byte aligned. */ +static const size_t xHeapStructSize = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); + +/* Create a couple of list links to mark the start and end of the list. */ +PRIVILEGED_DATA static BlockLink_t xStart, * pxEnd = NULL; + +/* Keeps track of the number of calls to allocate and free memory as well as the + * number of free bytes remaining, but says nothing about fragmentation. */ +PRIVILEGED_DATA static size_t xFreeBytesRemaining = 0U; +PRIVILEGED_DATA static size_t xMinimumEverFreeBytesRemaining = 0U; +PRIVILEGED_DATA static size_t xNumberOfSuccessfulAllocations = 0; +PRIVILEGED_DATA static size_t xNumberOfSuccessfulFrees = 0; + +/* Gets set to the top bit of an size_t type. When this bit in the xBlockSize + * member of an BlockLink_t structure is set then the block belongs to the + * application. When the bit is free the block is still part of the free heap + * space. */ +PRIVILEGED_DATA static size_t xBlockAllocatedBit = 0; + +/*-----------------------------------------------------------*/ + +void * pvPortMalloc( size_t xWantedSize ) +{ + BlockLink_t * pxBlock, * pxPreviousBlock, * pxNewBlockLink; + void * pvReturn = NULL; + + vTaskSuspendAll(); + { + /* If this is the first call to malloc then the heap will require + * initialisation to setup the list of free blocks. */ + if( pxEnd == NULL ) + { + prvHeapInit(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Check the requested block size is not so large that the top bit is + * set. The top bit of the block size member of the BlockLink_t structure + * is used to determine who owns the block - the application or the + * kernel, so it must be free. */ + if( ( xWantedSize & xBlockAllocatedBit ) == 0 ) + { + /* The wanted size must be increased so it can contain a BlockLink_t + * structure in addition to the requested amount of bytes. */ + if( ( xWantedSize > 0 ) && + ( ( xWantedSize + xHeapStructSize ) > xWantedSize ) ) /* Overflow check */ + { + xWantedSize += xHeapStructSize; + + /* Ensure that blocks are always aligned. */ + if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 ) + { + /* Byte alignment required. Check for overflow. */ + if( ( xWantedSize + ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ) ) + > xWantedSize ) + { + xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); + configASSERT( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) == 0 ); + } + else + { + xWantedSize = 0; + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + xWantedSize = 0; + } + + if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) ) + { + /* Traverse the list from the start (lowest address) block until + * one of adequate size is found. */ + pxPreviousBlock = &xStart; + pxBlock = xStart.pxNextFreeBlock; + + while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) ) + { + pxPreviousBlock = pxBlock; + pxBlock = pxBlock->pxNextFreeBlock; + } + + /* If the end marker was reached then a block of adequate size + * was not found. */ + if( pxBlock != pxEnd ) + { + /* Return the memory space pointed to - jumping over the + * BlockLink_t structure at its start. */ + pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize ); + + /* This block is being returned for use so must be taken out + * of the list of free blocks. */ + pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock; + + /* If the block is larger than required it can be split into + * two. */ + if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE ) + { + /* This block is to be split into two. Create a new + * block following the number of bytes requested. The void + * cast is used to prevent byte alignment warnings from the + * compiler. */ + pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize ); + configASSERT( ( ( ( size_t ) pxNewBlockLink ) & portBYTE_ALIGNMENT_MASK ) == 0 ); + + /* Calculate the sizes of two blocks split from the + * single block. */ + pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize; + pxBlock->xBlockSize = xWantedSize; + + /* Insert the new block into the list of free blocks. */ + prvInsertBlockIntoFreeList( pxNewBlockLink ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + xFreeBytesRemaining -= pxBlock->xBlockSize; + + if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining ) + { + xMinimumEverFreeBytesRemaining = xFreeBytesRemaining; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* The block is being returned - it is allocated and owned + * by the application and has no "next" block. */ + pxBlock->xBlockSize |= xBlockAllocatedBit; + pxBlock->pxNextFreeBlock = NULL; + xNumberOfSuccessfulAllocations++; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceMALLOC( pvReturn, xWantedSize ); + } + ( void ) xTaskResumeAll(); + + #if ( configUSE_MALLOC_FAILED_HOOK == 1 ) + { + if( pvReturn == NULL ) + { + extern void vApplicationMallocFailedHook( void ); + vApplicationMallocFailedHook(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* if ( configUSE_MALLOC_FAILED_HOOK == 1 ) */ + + configASSERT( ( ( ( size_t ) pvReturn ) & ( size_t ) portBYTE_ALIGNMENT_MASK ) == 0 ); + return pvReturn; +} +/*-----------------------------------------------------------*/ + +void vPortFree( void * pv ) +{ + uint8_t * puc = ( uint8_t * ) pv; + BlockLink_t * pxLink; + + if( pv != NULL ) + { + /* The memory being freed will have an BlockLink_t structure immediately + * before it. */ + puc -= xHeapStructSize; + + /* This casting is to keep the compiler from issuing warnings. */ + pxLink = ( void * ) puc; + + /* Check the block is actually allocated. */ + configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ); + configASSERT( pxLink->pxNextFreeBlock == NULL ); + + if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ) + { + if( pxLink->pxNextFreeBlock == NULL ) + { + /* The block is being returned to the heap - it is no longer + * allocated. */ + pxLink->xBlockSize &= ~xBlockAllocatedBit; + + vTaskSuspendAll(); + { + /* Add this block to the list of free blocks. */ + xFreeBytesRemaining += pxLink->xBlockSize; + traceFREE( pv, pxLink->xBlockSize ); + prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) ); + xNumberOfSuccessfulFrees++; + } + ( void ) xTaskResumeAll(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } +} +/*-----------------------------------------------------------*/ + +size_t xPortGetFreeHeapSize( void ) +{ + return xFreeBytesRemaining; +} +/*-----------------------------------------------------------*/ + +size_t xPortGetMinimumEverFreeHeapSize( void ) +{ + return xMinimumEverFreeBytesRemaining; +} +/*-----------------------------------------------------------*/ + +void vPortInitialiseBlocks( void ) +{ + /* This just exists to keep the linker quiet. */ +} +/*-----------------------------------------------------------*/ + +static void prvHeapInit( void ) /* PRIVILEGED_FUNCTION */ +{ + BlockLink_t * pxFirstFreeBlock; + uint8_t * pucAlignedHeap; + size_t uxAddress; + size_t xTotalHeapSize = configTOTAL_HEAP_SIZE; + + /* Ensure the heap starts on a correctly aligned boundary. */ + uxAddress = ( size_t ) ucHeap; + + if( ( uxAddress & portBYTE_ALIGNMENT_MASK ) != 0 ) + { + uxAddress += ( portBYTE_ALIGNMENT - 1 ); + uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); + xTotalHeapSize -= uxAddress - ( size_t ) ucHeap; + } + + pucAlignedHeap = ( uint8_t * ) uxAddress; + + /* xStart is used to hold a pointer to the first item in the list of free + * blocks. The void cast is used to prevent compiler warnings. */ + xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap; + xStart.xBlockSize = ( size_t ) 0; + + /* pxEnd is used to mark the end of the list of free blocks and is inserted + * at the end of the heap space. */ + uxAddress = ( ( size_t ) pucAlignedHeap ) + xTotalHeapSize; + uxAddress -= xHeapStructSize; + uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); + pxEnd = ( void * ) uxAddress; + pxEnd->xBlockSize = 0; + pxEnd->pxNextFreeBlock = NULL; + + /* To start with there is a single free block that is sized to take up the + * entire heap space, minus the space taken by pxEnd. */ + pxFirstFreeBlock = ( void * ) pucAlignedHeap; + pxFirstFreeBlock->xBlockSize = uxAddress - ( size_t ) pxFirstFreeBlock; + pxFirstFreeBlock->pxNextFreeBlock = pxEnd; + + /* Only one block exists - and it covers the entire usable heap space. */ + xMinimumEverFreeBytesRemaining = pxFirstFreeBlock->xBlockSize; + xFreeBytesRemaining = pxFirstFreeBlock->xBlockSize; + + /* Work out the position of the top bit in a size_t variable. */ + xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 ); +} +/*-----------------------------------------------------------*/ + +static void prvInsertBlockIntoFreeList( BlockLink_t * pxBlockToInsert ) /* PRIVILEGED_FUNCTION */ +{ + BlockLink_t * pxIterator; + uint8_t * puc; + + /* Iterate through the list until a block is found that has a higher address + * than the block being inserted. */ + for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock ) + { + /* Nothing to do here, just iterate to the right position. */ + } + + /* Do the block being inserted, and the block it is being inserted after + * make a contiguous block of memory? */ + puc = ( uint8_t * ) pxIterator; + + if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert ) + { + pxIterator->xBlockSize += pxBlockToInsert->xBlockSize; + pxBlockToInsert = pxIterator; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Do the block being inserted, and the block it is being inserted before + * make a contiguous block of memory? */ + puc = ( uint8_t * ) pxBlockToInsert; + + if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock ) + { + if( pxIterator->pxNextFreeBlock != pxEnd ) + { + /* Form one big block from the two blocks. */ + pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize; + pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock; + } + else + { + pxBlockToInsert->pxNextFreeBlock = pxEnd; + } + } + else + { + pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock; + } + + /* If the block being inserted plugged a gab, so was merged with the block + * before and the block after, then it's pxNextFreeBlock pointer will have + * already been set, and should not be set here as that would make it point + * to itself. */ + if( pxIterator != pxBlockToInsert ) + { + pxIterator->pxNextFreeBlock = pxBlockToInsert; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } +} +/*-----------------------------------------------------------*/ + +void vPortGetHeapStats( HeapStats_t * pxHeapStats ) +{ + BlockLink_t * pxBlock; + size_t xBlocks = 0, xMaxSize = 0, xMinSize = portMAX_DELAY; /* portMAX_DELAY used as a portable way of getting the maximum value. */ + + vTaskSuspendAll(); + { + pxBlock = xStart.pxNextFreeBlock; + + /* pxBlock will be NULL if the heap has not been initialised. The heap + * is initialised automatically when the first allocation is made. */ + if( pxBlock != NULL ) + { + do + { + /* Increment the number of blocks and record the largest block seen + * so far. */ + xBlocks++; + + if( pxBlock->xBlockSize > xMaxSize ) + { + xMaxSize = pxBlock->xBlockSize; + } + + if( pxBlock->xBlockSize < xMinSize ) + { + xMinSize = pxBlock->xBlockSize; + } + + /* Move to the next block in the chain until the last block is + * reached. */ + pxBlock = pxBlock->pxNextFreeBlock; + } while( pxBlock != pxEnd ); + } + } + ( void ) xTaskResumeAll(); + + pxHeapStats->xSizeOfLargestFreeBlockInBytes = xMaxSize; + pxHeapStats->xSizeOfSmallestFreeBlockInBytes = xMinSize; + pxHeapStats->xNumberOfFreeBlocks = xBlocks; + + taskENTER_CRITICAL(); + { + pxHeapStats->xAvailableHeapSpaceInBytes = xFreeBytesRemaining; + pxHeapStats->xNumberOfSuccessfulAllocations = xNumberOfSuccessfulAllocations; + pxHeapStats->xNumberOfSuccessfulFrees = xNumberOfSuccessfulFrees; + pxHeapStats->xMinimumEverFreeBytesRemaining = xMinimumEverFreeBytesRemaining; + } + taskEXIT_CRITICAL(); +} diff --git a/examples/stm32/freertos-kernel/portable/MemMang/heap_5.c b/examples/stm32/freertos-kernel/portable/MemMang/heap_5.c new file mode 100644 index 00000000..52390f59 --- /dev/null +++ b/examples/stm32/freertos-kernel/portable/MemMang/heap_5.c @@ -0,0 +1,557 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* + * A sample implementation of pvPortMalloc() that allows the heap to be defined + * across multiple non-contigous blocks and combines (coalescences) adjacent + * memory blocks as they are freed. + * + * See heap_1.c, heap_2.c, heap_3.c and heap_4.c for alternative + * implementations, and the memory management pages of https://www.FreeRTOS.org + * for more information. + * + * Usage notes: + * + * vPortDefineHeapRegions() ***must*** be called before pvPortMalloc(). + * pvPortMalloc() will be called if any task objects (tasks, queues, event + * groups, etc.) are created, therefore vPortDefineHeapRegions() ***must*** be + * called before any other objects are defined. + * + * vPortDefineHeapRegions() takes a single parameter. The parameter is an array + * of HeapRegion_t structures. HeapRegion_t is defined in portable.h as + * + * typedef struct HeapRegion + * { + * uint8_t *pucStartAddress; << Start address of a block of memory that will be part of the heap. + * size_t xSizeInBytes; << Size of the block of memory. + * } HeapRegion_t; + * + * The array is terminated using a NULL zero sized region definition, and the + * memory regions defined in the array ***must*** appear in address order from + * low address to high address. So the following is a valid example of how + * to use the function. + * + * HeapRegion_t xHeapRegions[] = + * { + * { ( uint8_t * ) 0x80000000UL, 0x10000 }, << Defines a block of 0x10000 bytes starting at address 0x80000000 + * { ( uint8_t * ) 0x90000000UL, 0xa0000 }, << Defines a block of 0xa0000 bytes starting at address of 0x90000000 + * { NULL, 0 } << Terminates the array. + * }; + * + * vPortDefineHeapRegions( xHeapRegions ); << Pass the array into vPortDefineHeapRegions(). + * + * Note 0x80000000 is the lower address so appears in the array first. + * + */ +#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 ) + +/* 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 ); + +/*-----------------------------------------------------------*/ + +/* 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; + + /* The heap must be initialised before the first call to + * prvPortMalloc(). */ + configASSERT( pxEnd ); + + vTaskSuspendAll(); + { + /* 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 ) > xWantedSize ) ) /* Overflow check */ + { + xWantedSize += xHeapStructSize; + + /* Ensure that blocks are always aligned */ + if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 ) + { + /* Byte alignment required. Check for overflow */ + if( ( xWantedSize + ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ) ) > + xWantedSize ) + { + xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); + } + else + { + xWantedSize = 0; + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + xWantedSize = 0; + } + + if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) ) + { + /* Traverse the list from the start (lowest address) block until + * one of adequate size is found. */ + pxPreviousBlock = &xStart; + pxBlock = xStart.pxNextFreeBlock; + + while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) ) + { + pxPreviousBlock = pxBlock; + pxBlock = pxBlock->pxNextFreeBlock; + } + + /* If the end marker was reached then a block of adequate size + * was not found. */ + if( pxBlock != pxEnd ) + { + /* Return the memory space pointed to - jumping over the + * BlockLink_t structure at its start. */ + pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize ); + + /* This block is being returned for use so must be taken out + * of the list of free blocks. */ + pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock; + + /* If the block is larger than required it can be split into + * two. */ + if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE ) + { + /* This block is to be split into two. Create a new + * block following the number of bytes requested. The void + * cast is used to prevent byte alignment warnings from the + * compiler. */ + pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize ); + + /* Calculate the sizes of two blocks split from the + * single block. */ + pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize; + pxBlock->xBlockSize = xWantedSize; + + /* Insert the new block into the list of free blocks. */ + prvInsertBlockIntoFreeList( ( pxNewBlockLink ) ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + xFreeBytesRemaining -= pxBlock->xBlockSize; + + if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining ) + { + xMinimumEverFreeBytesRemaining = xFreeBytesRemaining; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* The block is being returned - it is allocated and owned + * by the application and has no "next" block. */ + pxBlock->xBlockSize |= xBlockAllocatedBit; + pxBlock->pxNextFreeBlock = NULL; + xNumberOfSuccessfulAllocations++; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceMALLOC( pvReturn, xWantedSize ); + } + ( void ) xTaskResumeAll(); + + #if ( configUSE_MALLOC_FAILED_HOOK == 1 ) + { + if( pvReturn == NULL ) + { + extern void vApplicationMallocFailedHook( void ); + vApplicationMallocFailedHook(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* if ( configUSE_MALLOC_FAILED_HOOK == 1 ) */ + + 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; +} +/*-----------------------------------------------------------*/ + +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 vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions ) +{ + BlockLink_t * pxFirstFreeBlockInRegion = NULL, * pxPreviousFreeBlock; + size_t xAlignedHeap; + size_t xTotalRegionSize, xTotalHeapSize = 0; + BaseType_t xDefinedRegions = 0; + size_t xAddress; + const HeapRegion_t * pxHeapRegion; + + /* Can only call once! */ + configASSERT( pxEnd == NULL ); + + pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] ); + + while( pxHeapRegion->xSizeInBytes > 0 ) + { + xTotalRegionSize = pxHeapRegion->xSizeInBytes; + + /* Ensure the heap region starts on a correctly aligned boundary. */ + xAddress = ( size_t ) pxHeapRegion->pucStartAddress; + + if( ( xAddress & portBYTE_ALIGNMENT_MASK ) != 0 ) + { + xAddress += ( portBYTE_ALIGNMENT - 1 ); + xAddress &= ~portBYTE_ALIGNMENT_MASK; + + /* Adjust the size for the bytes lost to alignment. */ + xTotalRegionSize -= xAddress - ( size_t ) pxHeapRegion->pucStartAddress; + } + + xAlignedHeap = xAddress; + + /* Set xStart if it has not already been set. */ + if( xDefinedRegions == 0 ) + { + /* 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 = ( BlockLink_t * ) xAlignedHeap; + xStart.xBlockSize = ( size_t ) 0; + } + else + { + /* Should only get here if one region has already been added to the + * heap. */ + configASSERT( pxEnd != NULL ); + + /* Check blocks are passed in with increasing start addresses. */ + configASSERT( xAddress > ( size_t ) pxEnd ); + } + + /* Remember the location of the end marker in the previous region, if + * any. */ + pxPreviousFreeBlock = pxEnd; + + /* pxEnd is used to mark the end of the list of free blocks and is + * inserted at the end of the region space. */ + xAddress = xAlignedHeap + xTotalRegionSize; + xAddress -= xHeapStructSize; + xAddress &= ~portBYTE_ALIGNMENT_MASK; + pxEnd = ( BlockLink_t * ) xAddress; + pxEnd->xBlockSize = 0; + pxEnd->pxNextFreeBlock = NULL; + + /* To start with there is a single free block in this region that is + * sized to take up the entire heap region minus the space taken by the + * free block structure. */ + pxFirstFreeBlockInRegion = ( BlockLink_t * ) xAlignedHeap; + pxFirstFreeBlockInRegion->xBlockSize = xAddress - ( size_t ) pxFirstFreeBlockInRegion; + pxFirstFreeBlockInRegion->pxNextFreeBlock = pxEnd; + + /* If this is not the first region that makes up the entire heap space + * then link the previous region to this region. */ + if( pxPreviousFreeBlock != NULL ) + { + pxPreviousFreeBlock->pxNextFreeBlock = pxFirstFreeBlockInRegion; + } + + xTotalHeapSize += pxFirstFreeBlockInRegion->xBlockSize; + + /* Move onto the next HeapRegion_t structure. */ + xDefinedRegions++; + pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] ); + } + + xMinimumEverFreeBytesRemaining = xTotalHeapSize; + xFreeBytesRemaining = xTotalHeapSize; + + /* Check something was actually defined before it is accessed. */ + configASSERT( xTotalHeapSize ); + + /* Work out the position of the top bit in a size_t variable. */ + xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 ); +} +/*-----------------------------------------------------------*/ + +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; + } + + /* Heap five will have a zero sized block at the end of each + * each region - the block is only used to link to the next + * heap region so it not a real block. */ + if( pxBlock->xBlockSize != 0 ) + { + if( pxBlock->xBlockSize < xMinSize ) + { + xMinSize = pxBlock->xBlockSize; + } + } + + /* Move to the next block in the chain until the last block is + * reached. */ + pxBlock = pxBlock->pxNextFreeBlock; + } while( pxBlock != pxEnd ); + } + } + ( void ) xTaskResumeAll(); + + pxHeapStats->xSizeOfLargestFreeBlockInBytes = xMaxSize; + pxHeapStats->xSizeOfSmallestFreeBlockInBytes = xMinSize; + pxHeapStats->xNumberOfFreeBlocks = xBlocks; + + taskENTER_CRITICAL(); + { + pxHeapStats->xAvailableHeapSpaceInBytes = xFreeBytesRemaining; + pxHeapStats->xNumberOfSuccessfulAllocations = xNumberOfSuccessfulAllocations; + pxHeapStats->xNumberOfSuccessfulFrees = xNumberOfSuccessfulFrees; + pxHeapStats->xMinimumEverFreeBytesRemaining = xMinimumEverFreeBytesRemaining; + } + taskEXIT_CRITICAL(); +} diff --git a/examples/stm32/freertos-kernel/queue.c b/examples/stm32/freertos-kernel/queue.c new file mode 100644 index 00000000..7ed8e987 --- /dev/null +++ b/examples/stm32/freertos-kernel/queue.c @@ -0,0 +1,3016 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +#include +#include + +/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining + * all the API functions to use the MPU wrappers. That should only be done when + * task.h is included from an application file. */ +#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" + +#if ( configUSE_CO_ROUTINES == 1 ) + #include "croutine.h" +#endif + +/* Lint e9021, e961 and e750 are suppressed as a MISRA exception justified + * because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined + * for the header files above, but not in this file, in order to generate the + * correct privileged Vs unprivileged linkage and placement. */ +#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750 !e9021. */ + + +/* Constants used with the cRxLock and cTxLock structure members. */ +#define queueUNLOCKED ( ( int8_t ) -1 ) +#define queueLOCKED_UNMODIFIED ( ( int8_t ) 0 ) +#define queueINT8_MAX ( ( int8_t ) 127 ) + +/* When the Queue_t structure is used to represent a base queue its pcHead and + * pcTail members are used as pointers into the queue storage area. When the + * Queue_t structure is used to represent a mutex pcHead and pcTail pointers are + * not necessary, and the pcHead pointer is set to NULL to indicate that the + * structure instead holds a pointer to the mutex holder (if any). Map alternative + * names to the pcHead and structure member to ensure the readability of the code + * is maintained. The QueuePointers_t and SemaphoreData_t types are used to form + * a union as their usage is mutually exclusive dependent on what the queue is + * being used for. */ +#define uxQueueType pcHead +#define queueQUEUE_IS_MUTEX NULL + +typedef struct QueuePointers +{ + int8_t * pcTail; /*< Points to the byte at the end of the queue storage area. Once more byte is allocated than necessary to store the queue items, this is used as a marker. */ + int8_t * pcReadFrom; /*< Points to the last place that a queued item was read from when the structure is used as a queue. */ +} QueuePointers_t; + +typedef struct SemaphoreData +{ + TaskHandle_t xMutexHolder; /*< The handle of the task that holds the mutex. */ + UBaseType_t uxRecursiveCallCount; /*< Maintains a count of the number of times a recursive mutex has been recursively 'taken' when the structure is used as a mutex. */ +} SemaphoreData_t; + +/* Semaphores do not actually store or copy data, so have an item size of + * zero. */ +#define queueSEMAPHORE_QUEUE_ITEM_LENGTH ( ( UBaseType_t ) 0 ) +#define queueMUTEX_GIVE_BLOCK_TIME ( ( TickType_t ) 0U ) + +#if ( configUSE_PREEMPTION == 0 ) + +/* If the cooperative scheduler is being used then a yield should not be + * performed just because a higher priority task has been woken. */ + #define queueYIELD_IF_USING_PREEMPTION() +#else + #define queueYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API() +#endif + +/* + * Definition of the queue used by the scheduler. + * Items are queued by copy, not reference. See the following link for the + * rationale: https://www.FreeRTOS.org/Embedded-RTOS-Queues.html + */ +typedef struct QueueDefinition /* The old naming convention is used to prevent breaking kernel aware debuggers. */ +{ + int8_t * pcHead; /*< Points to the beginning of the queue storage area. */ + int8_t * pcWriteTo; /*< Points to the free next place in the storage area. */ + + union + { + QueuePointers_t xQueue; /*< Data required exclusively when this structure is used as a queue. */ + SemaphoreData_t xSemaphore; /*< Data required exclusively when this structure is used as a semaphore. */ + } u; + + List_t xTasksWaitingToSend; /*< List of tasks that are blocked waiting to post onto this queue. Stored in priority order. */ + List_t xTasksWaitingToReceive; /*< List of tasks that are blocked waiting to read from this queue. Stored in priority order. */ + + volatile UBaseType_t uxMessagesWaiting; /*< The number of items currently in the queue. */ + UBaseType_t uxLength; /*< The length of the queue defined as the number of items it will hold, not the number of bytes. */ + UBaseType_t uxItemSize; /*< The size of each items that the queue will hold. */ + + volatile int8_t cRxLock; /*< Stores the number of items received from the queue (removed from the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */ + volatile int8_t cTxLock; /*< Stores the number of items transmitted to the queue (added to the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */ + + #if ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the memory used by the queue was statically allocated to ensure no attempt is made to free the memory. */ + #endif + + #if ( configUSE_QUEUE_SETS == 1 ) + struct QueueDefinition * pxQueueSetContainer; + #endif + + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxQueueNumber; + uint8_t ucQueueType; + #endif +} xQUEUE; + +/* The old xQUEUE name is maintained above then typedefed to the new Queue_t + * name below to enable the use of older kernel aware debuggers. */ +typedef xQUEUE Queue_t; + +/*-----------------------------------------------------------*/ + +/* + * The queue registry is just a means for kernel aware debuggers to locate + * queue structures. It has no other purpose so is an optional component. + */ +#if ( configQUEUE_REGISTRY_SIZE > 0 ) + +/* The type stored within the queue registry array. This allows a name + * to be assigned to each queue making kernel aware debugging a little + * more user friendly. */ + typedef struct QUEUE_REGISTRY_ITEM + { + const char * pcQueueName; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + QueueHandle_t xHandle; + } xQueueRegistryItem; + +/* The old xQueueRegistryItem name is maintained above then typedefed to the + * new xQueueRegistryItem name below to enable the use of older kernel aware + * debuggers. */ + typedef xQueueRegistryItem QueueRegistryItem_t; + +/* The queue registry is simply an array of QueueRegistryItem_t structures. + * The pcQueueName member of a structure being NULL is indicative of the + * array position being vacant. */ + PRIVILEGED_DATA QueueRegistryItem_t xQueueRegistry[ configQUEUE_REGISTRY_SIZE ]; + +#endif /* configQUEUE_REGISTRY_SIZE */ + +/* + * Unlocks a queue locked by a call to prvLockQueue. Locking a queue does not + * prevent an ISR from adding or removing items to the queue, but does prevent + * an ISR from removing tasks from the queue event lists. If an ISR finds a + * queue is locked it will instead increment the appropriate queue lock count + * to indicate that a task may require unblocking. When the queue in unlocked + * these lock counts are inspected, and the appropriate action taken. + */ +static void prvUnlockQueue( Queue_t * const pxQueue ) PRIVILEGED_FUNCTION; + +/* + * Uses a critical section to determine if there is any data in a queue. + * + * @return pdTRUE if the queue contains no items, otherwise pdFALSE. + */ +static BaseType_t prvIsQueueEmpty( const Queue_t * pxQueue ) PRIVILEGED_FUNCTION; + +/* + * Uses a critical section to determine if there is any space in a queue. + * + * @return pdTRUE if there is no space, otherwise pdFALSE; + */ +static BaseType_t prvIsQueueFull( const Queue_t * pxQueue ) PRIVILEGED_FUNCTION; + +/* + * Copies an item into the queue, either at the front of the queue or the + * back of the queue. + */ +static BaseType_t prvCopyDataToQueue( Queue_t * const pxQueue, + const void * pvItemToQueue, + const BaseType_t xPosition ) PRIVILEGED_FUNCTION; + +/* + * Copies an item out of a queue. + */ +static void prvCopyDataFromQueue( Queue_t * const pxQueue, + void * const pvBuffer ) PRIVILEGED_FUNCTION; + +#if ( configUSE_QUEUE_SETS == 1 ) + +/* + * Checks to see if a queue is a member of a queue set, and if so, notifies + * the queue set that the queue contains data. + */ + static BaseType_t prvNotifyQueueSetContainer( const Queue_t * const pxQueue ) PRIVILEGED_FUNCTION; +#endif + +/* + * Called after a Queue_t structure has been allocated either statically or + * dynamically to fill in the structure's members. + */ +static void prvInitialiseNewQueue( const UBaseType_t uxQueueLength, + const UBaseType_t uxItemSize, + uint8_t * pucQueueStorage, + const uint8_t ucQueueType, + Queue_t * pxNewQueue ) PRIVILEGED_FUNCTION; + +/* + * Mutexes are a special type of queue. When a mutex is created, first the + * queue is created, then prvInitialiseMutex() is called to configure the queue + * as a mutex. + */ +#if ( configUSE_MUTEXES == 1 ) + static void prvInitialiseMutex( Queue_t * pxNewQueue ) PRIVILEGED_FUNCTION; +#endif + +#if ( configUSE_MUTEXES == 1 ) + +/* + * If a task waiting for a mutex causes the mutex holder to inherit a + * priority, but the waiting task times out, then the holder should + * disinherit the priority - but only down to the highest priority of any + * other tasks that are waiting for the same mutex. This function returns + * that priority. + */ + static UBaseType_t prvGetDisinheritPriorityAfterTimeout( const Queue_t * const pxQueue ) PRIVILEGED_FUNCTION; +#endif +/*-----------------------------------------------------------*/ + +/* + * Macro to mark a queue as locked. Locking a queue prevents an ISR from + * accessing the queue event lists. + */ +#define prvLockQueue( pxQueue ) \ + taskENTER_CRITICAL(); \ + { \ + if( ( pxQueue )->cRxLock == queueUNLOCKED ) \ + { \ + ( pxQueue )->cRxLock = queueLOCKED_UNMODIFIED; \ + } \ + if( ( pxQueue )->cTxLock == queueUNLOCKED ) \ + { \ + ( pxQueue )->cTxLock = queueLOCKED_UNMODIFIED; \ + } \ + } \ + taskEXIT_CRITICAL() +/*-----------------------------------------------------------*/ + +BaseType_t xQueueGenericReset( QueueHandle_t xQueue, + BaseType_t xNewQueue ) +{ + 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. */ + + /* Check for multiplication overflow. */ + configASSERT( ( uxItemSize == 0 ) || ( uxQueueLength == ( xQueueSizeInBytes / uxItemSize ) ) ); + + /* Check for addition overflow. */ + configASSERT( ( sizeof( Queue_t ) + xQueueSizeInBytes ) > xQueueSizeInBytes ); + + /* 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 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) ) + + TaskHandle_t xQueueGetMutexHolderFromISR( QueueHandle_t xSemaphore ) + { + TaskHandle_t pxReturn; + + configASSERT( xSemaphore ); + + /* Mutexes cannot be used in interrupt service routines, so the mutex + * holder should not change in an ISR, and therefore a critical section is + * not required here. */ + if( ( ( Queue_t * ) xSemaphore )->uxQueueType == queueQUEUE_IS_MUTEX ) + { + pxReturn = ( ( Queue_t * ) xSemaphore )->u.xSemaphore.xMutexHolder; + } + else + { + pxReturn = NULL; + } + + return pxReturn; + } /*lint !e818 xSemaphore cannot be a pointer to const because it is a typedef. */ + +#endif /* if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_RECURSIVE_MUTEXES == 1 ) + + BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) + { + BaseType_t xReturn; + Queue_t * const pxMutex = ( Queue_t * ) xMutex; + + configASSERT( pxMutex ); + + /* If this is the task that holds the mutex then xMutexHolder will not + * change outside of this task. If this task does not hold the mutex then + * pxMutexHolder can never coincidentally equal the tasks handle, and as + * this is the only condition we are interested in it does not matter if + * pxMutexHolder is accessed simultaneously by another task. Therefore no + * mutual exclusion is required to test the pxMutexHolder variable. */ + if( pxMutex->u.xSemaphore.xMutexHolder == xTaskGetCurrentTaskHandle() ) + { + traceGIVE_MUTEX_RECURSIVE( pxMutex ); + + /* uxRecursiveCallCount cannot be zero if xMutexHolder is equal to + * the task handle, therefore no underflow check is required. Also, + * uxRecursiveCallCount is only modified by the mutex holder, and as + * there can only be one, no mutual exclusion is required to modify the + * uxRecursiveCallCount member. */ + ( pxMutex->u.xSemaphore.uxRecursiveCallCount )--; + + /* Has the recursive call count unwound to 0? */ + if( pxMutex->u.xSemaphore.uxRecursiveCallCount == ( UBaseType_t ) 0 ) + { + /* Return the mutex. This will automatically unblock any other + * task that might be waiting to access the mutex. */ + ( void ) xQueueGenericSend( pxMutex, NULL, queueMUTEX_GIVE_BLOCK_TIME, queueSEND_TO_BACK ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + xReturn = pdPASS; + } + else + { + /* The mutex cannot be given because the calling task is not the + * holder. */ + xReturn = pdFAIL; + + traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex ); + } + + return xReturn; + } + +#endif /* configUSE_RECURSIVE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_RECURSIVE_MUTEXES == 1 ) + + BaseType_t xQueueTakeMutexRecursive( QueueHandle_t xMutex, + TickType_t xTicksToWait ) + { + BaseType_t xReturn; + Queue_t * const pxMutex = ( Queue_t * ) xMutex; + + configASSERT( pxMutex ); + + /* Comments regarding mutual exclusion as per those within + * xQueueGiveMutexRecursive(). */ + + traceTAKE_MUTEX_RECURSIVE( pxMutex ); + + if( pxMutex->u.xSemaphore.xMutexHolder == xTaskGetCurrentTaskHandle() ) + { + ( pxMutex->u.xSemaphore.uxRecursiveCallCount )++; + xReturn = pdPASS; + } + else + { + xReturn = xQueueSemaphoreTake( pxMutex, xTicksToWait ); + + /* pdPASS will only be returned if the mutex was successfully + * obtained. The calling task may have entered the Blocked state + * before reaching here. */ + if( xReturn != pdFAIL ) + { + ( pxMutex->u.xSemaphore.uxRecursiveCallCount )++; + } + else + { + traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex ); + } + } + + return xReturn; + } + +#endif /* configUSE_RECURSIVE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + + QueueHandle_t xQueueCreateCountingSemaphoreStatic( const UBaseType_t uxMaxCount, + const UBaseType_t uxInitialCount, + StaticQueue_t * pxStaticQueue ) + { + QueueHandle_t xHandle; + + 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: https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + /* Similar to xQueueGenericSend, except without blocking if there is no room + * in the queue. Also don't directly wake a task that was blocked on a queue + * read, instead return a flag to say whether a context switch is required or + * not (i.e. has a task with a higher priority than us been woken by this + * post). */ + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + if( ( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) || ( xCopyPosition == queueOVERWRITE ) ) + { + const int8_t cTxLock = pxQueue->cTxLock; + const UBaseType_t uxPreviousMessagesWaiting = pxQueue->uxMessagesWaiting; + + traceQUEUE_SEND_FROM_ISR( pxQueue ); + + /* Semaphores use xQueueGiveFromISR(), so pxQueue will not be a + * semaphore or mutex. That means prvCopyDataToQueue() cannot result + * in a task disinheriting a priority and prvCopyDataToQueue() can be + * called here even though the disinherit function does not check if + * the scheduler is suspended before accessing the ready lists. */ + ( void ) prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); + + /* The event list is not altered if the queue is locked. This will + * be done when the queue is unlocked later. */ + if( cTxLock == queueUNLOCKED ) + { + #if ( configUSE_QUEUE_SETS == 1 ) + { + if( pxQueue->pxQueueSetContainer != NULL ) + { + if( ( xCopyPosition == queueOVERWRITE ) && ( uxPreviousMessagesWaiting != ( UBaseType_t ) 0 ) ) + { + /* Do not notify the queue set as an existing item + * was overwritten in the queue so the number of items + * in the queue has not changed. */ + mtCOVERAGE_TEST_MARKER(); + } + else if( prvNotifyQueueSetContainer( pxQueue ) != pdFALSE ) + { + /* The queue is a member of a queue set, and posting + * to the queue set caused a higher priority task to + * unblock. A context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so + * record that a context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + #else /* configUSE_QUEUE_SETS */ + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so record that a + * context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Not used in this path. */ + ( void ) uxPreviousMessagesWaiting; + } + #endif /* configUSE_QUEUE_SETS */ + } + else + { + /* Increment the lock count so the task that unlocks the queue + * knows that data was posted while it was locked. */ + configASSERT( cTxLock != queueINT8_MAX ); + + pxQueue->cTxLock = ( int8_t ) ( cTxLock + 1 ); + } + + xReturn = pdPASS; + } + else + { + traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ); + xReturn = errQUEUE_FULL; + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueueGiveFromISR( QueueHandle_t xQueue, + BaseType_t * const pxHigherPriorityTaskWoken ) +{ + BaseType_t xReturn; + UBaseType_t uxSavedInterruptStatus; + Queue_t * const pxQueue = xQueue; + + /* Similar to xQueueGenericSendFromISR() but used with semaphores where the + * item size is 0. Don't directly wake a task that was blocked on a queue + * read, instead return a flag to say whether a context switch is required or + * not (i.e. has a task with a higher priority than us been woken by this + * post). */ + + configASSERT( pxQueue ); + + /* xQueueGenericSendFromISR() should be used instead of xQueueGiveFromISR() + * if the item size is not 0. */ + configASSERT( pxQueue->uxItemSize == 0 ); + + /* Normally a mutex would not be given from an interrupt, especially if + * there is a mutex holder, as priority inheritance makes no sense for an + * interrupts, only tasks. */ + configASSERT( !( ( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) && ( pxQueue->u.xSemaphore.xMutexHolder != NULL ) ) ); + + /* RTOS ports that support interrupt nesting have the concept of a maximum + * system call (or maximum API call) interrupt priority. Interrupts that are + * above the maximum system call priority are kept permanently enabled, even + * when the RTOS kernel is in a critical section, but cannot make any calls to + * FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h + * then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + * failure if a FreeRTOS API function is called from an interrupt that has been + * assigned a priority above the configured maximum system call priority. + * Only FreeRTOS functions that end in FromISR can be called from interrupts + * that have been assigned a priority at or (logically) below the maximum + * system call interrupt priority. FreeRTOS maintains a separate interrupt + * safe API to ensure interrupt entry is as fast and as simple as possible. + * More information (albeit Cortex-M specific) is provided on the following + * link: https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; + + /* When the queue is used to implement a semaphore no data is ever + * moved through the queue but it is still valid to see if the queue 'has + * space'. */ + if( uxMessagesWaiting < pxQueue->uxLength ) + { + const int8_t cTxLock = pxQueue->cTxLock; + + traceQUEUE_SEND_FROM_ISR( pxQueue ); + + /* A task can only have an inherited priority if it is a mutex + * holder - and if there is a mutex holder then the mutex cannot be + * given from an ISR. As this is the ISR version of the function it + * can be assumed there is no mutex holder and no need to determine if + * priority disinheritance is needed. Simply increase the count of + * messages (semaphores) available. */ + pxQueue->uxMessagesWaiting = uxMessagesWaiting + ( UBaseType_t ) 1; + + /* The event list is not altered if the queue is locked. This will + * be done when the queue is unlocked later. */ + if( cTxLock == queueUNLOCKED ) + { + #if ( configUSE_QUEUE_SETS == 1 ) + { + if( pxQueue->pxQueueSetContainer != NULL ) + { + if( prvNotifyQueueSetContainer( pxQueue ) != pdFALSE ) + { + /* The semaphore is a member of a queue set, and + * posting to the queue set caused a higher priority + * task to unblock. A context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so + * record that a context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + #else /* configUSE_QUEUE_SETS */ + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so record that a + * context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_QUEUE_SETS */ + } + else + { + /* Increment the lock count so the task that unlocks the queue + * knows that data was posted while it was locked. */ + configASSERT( cTxLock != queueINT8_MAX ); + + pxQueue->cTxLock = ( int8_t ) ( cTxLock + 1 ); + } + + xReturn = pdPASS; + } + else + { + traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ); + xReturn = errQUEUE_FULL; + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueueReceive( QueueHandle_t xQueue, + void * const pvBuffer, + TickType_t xTicksToWait ) +{ + BaseType_t xEntryTimeSet = pdFALSE; + TimeOut_t xTimeOut; + Queue_t * const pxQueue = xQueue; + + /* Check the pointer is not NULL. */ + configASSERT( ( pxQueue ) ); + + /* The buffer into which data is received can only be NULL if the data size + * is zero (so no data is copied into the buffer). */ + configASSERT( !( ( ( pvBuffer ) == NULL ) && ( ( pxQueue )->uxItemSize != ( UBaseType_t ) 0U ) ) ); + + /* Cannot block if the scheduler is suspended. */ + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif + + /*lint -save -e904 This function relaxes the coding standard somewhat to + * allow return statements within the function itself. This is done in the + * interest of execution time efficiency. */ + for( ; ; ) + { + taskENTER_CRITICAL(); + { + const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; + + /* Is there data in the queue now? To be running the calling task + * must be the highest priority task wanting to access the queue. */ + if( uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* Data available, remove one item. */ + prvCopyDataFromQueue( pxQueue, pvBuffer ); + traceQUEUE_RECEIVE( pxQueue ); + pxQueue->uxMessagesWaiting = uxMessagesWaiting - ( UBaseType_t ) 1; + + /* There is now space in the queue, were any tasks waiting to + * post to the queue? If so, unblock the highest priority waiting + * task. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + taskEXIT_CRITICAL(); + return pdPASS; + } + else + { + if( xTicksToWait == ( TickType_t ) 0 ) + { + /* The queue was empty and no block time is specified (or + * the block time has expired) so leave now. */ + taskEXIT_CRITICAL(); + traceQUEUE_RECEIVE_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else if( xEntryTimeSet == pdFALSE ) + { + /* The queue was empty and a block time was specified so + * configure the timeout structure. */ + vTaskInternalSetTimeOutState( &xTimeOut ); + xEntryTimeSet = pdTRUE; + } + else + { + /* Entry time was already set. */ + mtCOVERAGE_TEST_MARKER(); + } + } + } + taskEXIT_CRITICAL(); + + /* Interrupts and other tasks can send to and receive from the queue + * now the critical section has been exited. */ + + vTaskSuspendAll(); + prvLockQueue( pxQueue ); + + /* Update the timeout state to see if it has expired yet. */ + if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) + { + /* The timeout has not expired. If the queue is still empty place + * the task on the list of tasks waiting to receive from the queue. */ + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ); + vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); + prvUnlockQueue( pxQueue ); + + if( xTaskResumeAll() == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* The queue contains data again. Loop back to try and read the + * data. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + } + } + else + { + /* Timed out. If there is no data in the queue exit, otherwise loop + * back and attempt to read the data. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceQUEUE_RECEIVE_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } /*lint -restore */ +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueueSemaphoreTake( QueueHandle_t xQueue, + TickType_t xTicksToWait ) +{ + BaseType_t xEntryTimeSet = pdFALSE; + TimeOut_t xTimeOut; + Queue_t * const pxQueue = xQueue; + + #if ( configUSE_MUTEXES == 1 ) + BaseType_t xInheritanceOccurred = pdFALSE; + #endif + + /* Check the queue pointer is not NULL. */ + configASSERT( ( pxQueue ) ); + + /* Check this really is a semaphore, in which case the item size will be + * 0. */ + configASSERT( pxQueue->uxItemSize == 0 ); + + /* Cannot block if the scheduler is suspended. */ + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif + + /*lint -save -e904 This function relaxes the coding standard somewhat to allow return + * statements within the function itself. This is done in the interest + * of execution time efficiency. */ + for( ; ; ) + { + taskENTER_CRITICAL(); + { + /* Semaphores are queues with an item size of 0, and where the + * number of messages in the queue is the semaphore's count value. */ + const UBaseType_t uxSemaphoreCount = pxQueue->uxMessagesWaiting; + + /* Is there data in the queue now? To be running the calling task + * must be the highest priority task wanting to access the queue. */ + if( uxSemaphoreCount > ( UBaseType_t ) 0 ) + { + traceQUEUE_RECEIVE( pxQueue ); + + /* Semaphores are queues with a data size of zero and where the + * messages waiting is the semaphore's count. Reduce the count. */ + pxQueue->uxMessagesWaiting = uxSemaphoreCount - ( UBaseType_t ) 1; + + #if ( configUSE_MUTEXES == 1 ) + { + if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) + { + /* Record the information required to implement + * priority inheritance should it become necessary. */ + pxQueue->u.xSemaphore.xMutexHolder = pvTaskIncrementMutexHeldCount(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_MUTEXES */ + + /* Check to see if other tasks are blocked waiting to give the + * semaphore, and if so, unblock the highest priority such task. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + taskEXIT_CRITICAL(); + return pdPASS; + } + else + { + if( xTicksToWait == ( TickType_t ) 0 ) + { + /* For inheritance to have occurred there must have been an + * initial timeout, and an adjusted timeout cannot become 0, as + * if it were 0 the function would have exited. */ + #if ( configUSE_MUTEXES == 1 ) + { + configASSERT( xInheritanceOccurred == pdFALSE ); + } + #endif /* configUSE_MUTEXES */ + + /* The semaphore count was 0 and no block time is specified + * (or the block time has expired) so exit now. */ + taskEXIT_CRITICAL(); + traceQUEUE_RECEIVE_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else if( xEntryTimeSet == pdFALSE ) + { + /* The semaphore count was 0 and a block time was specified + * so configure the timeout structure ready to block. */ + vTaskInternalSetTimeOutState( &xTimeOut ); + xEntryTimeSet = pdTRUE; + } + else + { + /* Entry time was already set. */ + mtCOVERAGE_TEST_MARKER(); + } + } + } + taskEXIT_CRITICAL(); + + /* Interrupts and other tasks can give to and take from the semaphore + * now the critical section has been exited. */ + + vTaskSuspendAll(); + prvLockQueue( pxQueue ); + + /* Update the timeout state to see if it has expired yet. */ + if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) + { + /* A block time is specified and not expired. If the semaphore + * count is 0 then enter the Blocked state to wait for a semaphore to + * become available. As semaphores are implemented with queues the + * queue being empty is equivalent to the semaphore count being 0. */ + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ); + + #if ( configUSE_MUTEXES == 1 ) + { + if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) + { + taskENTER_CRITICAL(); + { + xInheritanceOccurred = xTaskPriorityInherit( pxQueue->u.xSemaphore.xMutexHolder ); + } + taskEXIT_CRITICAL(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* if ( configUSE_MUTEXES == 1 ) */ + + vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); + prvUnlockQueue( pxQueue ); + + if( xTaskResumeAll() == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* There was no timeout and the semaphore count was not 0, so + * attempt to take the semaphore again. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + } + } + else + { + /* Timed out. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + + /* If the semaphore count is 0 exit now as the timeout has + * expired. Otherwise return to attempt to take the semaphore that is + * known to be available. As semaphores are implemented by queues the + * queue being empty is equivalent to the semaphore count being 0. */ + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + #if ( configUSE_MUTEXES == 1 ) + { + /* xInheritanceOccurred could only have be set if + * pxQueue->uxQueueType == queueQUEUE_IS_MUTEX so no need to + * test the mutex type again to check it is actually a mutex. */ + if( xInheritanceOccurred != pdFALSE ) + { + taskENTER_CRITICAL(); + { + UBaseType_t uxHighestWaitingPriority; + + /* This task blocking on the mutex caused another + * task to inherit this task's priority. Now this task + * has timed out the priority should be disinherited + * again, but only as low as the next highest priority + * task that is waiting for the same mutex. */ + uxHighestWaitingPriority = prvGetDisinheritPriorityAfterTimeout( pxQueue ); + vTaskPriorityDisinheritAfterTimeout( pxQueue->u.xSemaphore.xMutexHolder, uxHighestWaitingPriority ); + } + taskEXIT_CRITICAL(); + } + } + #endif /* configUSE_MUTEXES */ + + traceQUEUE_RECEIVE_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } /*lint -restore */ +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueuePeek( QueueHandle_t xQueue, + void * const pvBuffer, + TickType_t xTicksToWait ) +{ + BaseType_t xEntryTimeSet = pdFALSE; + TimeOut_t xTimeOut; + int8_t * pcOriginalReadPosition; + Queue_t * const pxQueue = xQueue; + + /* Check the pointer is not NULL. */ + configASSERT( ( pxQueue ) ); + + /* The buffer into which data is received can only be NULL if the data size + * is zero (so no data is copied into the buffer. */ + configASSERT( !( ( ( pvBuffer ) == NULL ) && ( ( pxQueue )->uxItemSize != ( UBaseType_t ) 0U ) ) ); + + /* Cannot block if the scheduler is suspended. */ + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif + + /*lint -save -e904 This function relaxes the coding standard somewhat to + * allow return statements within the function itself. This is done in the + * interest of execution time efficiency. */ + for( ; ; ) + { + taskENTER_CRITICAL(); + { + const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; + + /* Is there data in the queue now? To be running the calling task + * must be the highest priority task wanting to access the queue. */ + if( uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* Remember the read position so it can be reset after the data + * is read from the queue as this function is only peeking the + * data, not removing it. */ + pcOriginalReadPosition = pxQueue->u.xQueue.pcReadFrom; + + prvCopyDataFromQueue( pxQueue, pvBuffer ); + traceQUEUE_PEEK( pxQueue ); + + /* The data is not being removed, so reset the read pointer. */ + pxQueue->u.xQueue.pcReadFrom = pcOriginalReadPosition; + + /* The data is being left in the queue, so see if there are + * any other tasks waiting for the data. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority than this task. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + taskEXIT_CRITICAL(); + return pdPASS; + } + else + { + if( xTicksToWait == ( TickType_t ) 0 ) + { + /* The queue was empty and no block time is specified (or + * the block time has expired) so leave now. */ + taskEXIT_CRITICAL(); + traceQUEUE_PEEK_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else if( xEntryTimeSet == pdFALSE ) + { + /* The queue was empty and a block time was specified so + * configure the timeout structure ready to enter the blocked + * state. */ + vTaskInternalSetTimeOutState( &xTimeOut ); + xEntryTimeSet = pdTRUE; + } + else + { + /* Entry time was already set. */ + mtCOVERAGE_TEST_MARKER(); + } + } + } + taskEXIT_CRITICAL(); + + /* Interrupts and other tasks can send to and receive from the queue + * now the critical section has been exited. */ + + vTaskSuspendAll(); + prvLockQueue( pxQueue ); + + /* Update the timeout state to see if it has expired yet. */ + if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) + { + /* Timeout has not expired yet, check to see if there is data in the + * queue now, and if not enter the Blocked state to wait for data. */ + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceBLOCKING_ON_QUEUE_PEEK( pxQueue ); + vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); + prvUnlockQueue( pxQueue ); + + if( xTaskResumeAll() == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* There is data in the queue now, so don't enter the blocked + * state, instead return to try and obtain the data. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + } + } + else + { + /* The timeout has expired. If there is still no data in the queue + * exit, otherwise go back and try to read the data again. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceQUEUE_PEEK_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } /*lint -restore */ +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueueReceiveFromISR( QueueHandle_t xQueue, + void * const pvBuffer, + BaseType_t * const pxHigherPriorityTaskWoken ) +{ + BaseType_t xReturn; + UBaseType_t uxSavedInterruptStatus; + Queue_t * const pxQueue = xQueue; + + configASSERT( pxQueue ); + configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); + + /* RTOS ports that support interrupt nesting have the concept of a maximum + * system call (or maximum API call) interrupt priority. Interrupts that are + * above the maximum system call priority are kept permanently enabled, even + * when the RTOS kernel is in a critical section, but cannot make any calls to + * FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h + * then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + * failure if a FreeRTOS API function is called from an interrupt that has been + * assigned a priority above the configured maximum system call priority. + * Only FreeRTOS functions that end in FromISR can be called from interrupts + * that have been assigned a priority at or (logically) below the maximum + * system call interrupt priority. FreeRTOS maintains a separate interrupt + * safe API to ensure interrupt entry is as fast and as simple as possible. + * More information (albeit Cortex-M specific) is provided on the following + * link: https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; + + /* Cannot block in an ISR, so check there is data available. */ + if( uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + const int8_t cRxLock = pxQueue->cRxLock; + + traceQUEUE_RECEIVE_FROM_ISR( pxQueue ); + + prvCopyDataFromQueue( pxQueue, pvBuffer ); + pxQueue->uxMessagesWaiting = uxMessagesWaiting - ( UBaseType_t ) 1; + + /* If the queue is locked the event list will not be modified. + * Instead update the lock count so the task that unlocks the queue + * will know that an ISR has removed data while the queue was + * locked. */ + if( cRxLock == queueUNLOCKED ) + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + /* The task waiting has a higher priority than us so + * force a context switch. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* Increment the lock count so the task that unlocks the queue + * knows that data was removed while it was locked. */ + configASSERT( cRxLock != queueINT8_MAX ); + + pxQueue->cRxLock = ( int8_t ) ( cRxLock + 1 ); + } + + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue ); + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueuePeekFromISR( QueueHandle_t xQueue, + void * const pvBuffer ) +{ + BaseType_t xReturn; + UBaseType_t uxSavedInterruptStatus; + int8_t * pcOriginalReadPosition; + Queue_t * const pxQueue = xQueue; + + configASSERT( pxQueue ); + configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); + configASSERT( pxQueue->uxItemSize != 0 ); /* Can't peek a semaphore. */ + + /* RTOS ports that support interrupt nesting have the concept of a maximum + * system call (or maximum API call) interrupt priority. Interrupts that are + * above the maximum system call priority are kept permanently enabled, even + * when the RTOS kernel is in a critical section, but cannot make any calls to + * FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h + * then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + * failure if a FreeRTOS API function is called from an interrupt that has been + * assigned a priority above the configured maximum system call priority. + * Only FreeRTOS functions that end in FromISR can be called from interrupts + * that have been assigned a priority at or (logically) below the maximum + * system call interrupt priority. FreeRTOS maintains a separate interrupt + * safe API to ensure interrupt entry is as fast and as simple as possible. + * More information (albeit Cortex-M specific) is provided on the following + * link: https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + /* Cannot block in an ISR, so check there is data available. */ + if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + traceQUEUE_PEEK_FROM_ISR( pxQueue ); + + /* Remember the read position so it can be reset as nothing is + * actually being removed from the queue. */ + pcOriginalReadPosition = pxQueue->u.xQueue.pcReadFrom; + prvCopyDataFromQueue( pxQueue, pvBuffer ); + pxQueue->u.xQueue.pcReadFrom = pcOriginalReadPosition; + + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue ); + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +UBaseType_t uxQueueMessagesWaiting( const QueueHandle_t xQueue ) +{ + UBaseType_t uxReturn; + + configASSERT( xQueue ); + + taskENTER_CRITICAL(); + { + uxReturn = ( ( Queue_t * ) xQueue )->uxMessagesWaiting; + } + taskEXIT_CRITICAL(); + + return uxReturn; +} /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */ +/*-----------------------------------------------------------*/ + +UBaseType_t uxQueueSpacesAvailable( const QueueHandle_t xQueue ) +{ + UBaseType_t uxReturn; + Queue_t * const pxQueue = xQueue; + + configASSERT( pxQueue ); + + taskENTER_CRITICAL(); + { + uxReturn = pxQueue->uxLength - pxQueue->uxMessagesWaiting; + } + taskEXIT_CRITICAL(); + + return uxReturn; +} /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */ +/*-----------------------------------------------------------*/ + +UBaseType_t uxQueueMessagesWaitingFromISR( const QueueHandle_t xQueue ) +{ + UBaseType_t uxReturn; + Queue_t * const pxQueue = xQueue; + + configASSERT( pxQueue ); + uxReturn = pxQueue->uxMessagesWaiting; + + return uxReturn; +} /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */ +/*-----------------------------------------------------------*/ + +void vQueueDelete( QueueHandle_t xQueue ) +{ + Queue_t * const pxQueue = xQueue; + + configASSERT( pxQueue ); + traceQUEUE_DELETE( pxQueue ); + + #if ( configQUEUE_REGISTRY_SIZE > 0 ) + { + vQueueUnregisterQueue( pxQueue ); + } + #endif + + #if ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) ) + { + /* The queue can only have been allocated dynamically - free it + * again. */ + vPortFree( pxQueue ); + } + #elif ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + { + /* The queue could have been allocated statically or dynamically, so + * check before attempting to free the memory. */ + if( pxQueue->ucStaticallyAllocated == ( uint8_t ) pdFALSE ) + { + vPortFree( pxQueue ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #else /* if ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) ) */ + { + /* The queue must have been statically allocated, so is not going to be + * deleted. Avoid compiler warnings about the unused parameter. */ + ( void ) pxQueue; + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ +} +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + UBaseType_t uxQueueGetQueueNumber( QueueHandle_t xQueue ) + { + return ( ( Queue_t * ) xQueue )->uxQueueNumber; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + void vQueueSetQueueNumber( QueueHandle_t xQueue, + UBaseType_t uxQueueNumber ) + { + ( ( Queue_t * ) xQueue )->uxQueueNumber = uxQueueNumber; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + uint8_t ucQueueGetQueueType( QueueHandle_t xQueue ) + { + return ( ( Queue_t * ) xQueue )->ucQueueType; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_MUTEXES == 1 ) + + static UBaseType_t prvGetDisinheritPriorityAfterTimeout( const Queue_t * const pxQueue ) + { + UBaseType_t uxHighestPriorityOfWaitingTasks; + + /* If a task waiting for a mutex causes the mutex holder to inherit a + * priority, but the waiting task times out, then the holder should + * disinherit the priority - but only down to the highest priority of any + * other tasks that are waiting for the same mutex. For this purpose, + * return the priority of the highest priority task that is waiting for the + * mutex. */ + if( listCURRENT_LIST_LENGTH( &( pxQueue->xTasksWaitingToReceive ) ) > 0U ) + { + uxHighestPriorityOfWaitingTasks = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) listGET_ITEM_VALUE_OF_HEAD_ENTRY( &( pxQueue->xTasksWaitingToReceive ) ); + } + else + { + uxHighestPriorityOfWaitingTasks = tskIDLE_PRIORITY; + } + + return uxHighestPriorityOfWaitingTasks; + } + +#endif /* configUSE_MUTEXES */ +/*-----------------------------------------------------------*/ + +static BaseType_t prvCopyDataToQueue( Queue_t * const pxQueue, + const void * pvItemToQueue, + const BaseType_t xPosition ) +{ + BaseType_t xReturn = pdFALSE; + UBaseType_t uxMessagesWaiting; + + /* This function is called from a critical section. */ + + uxMessagesWaiting = pxQueue->uxMessagesWaiting; + + if( pxQueue->uxItemSize == ( UBaseType_t ) 0 ) + { + #if ( configUSE_MUTEXES == 1 ) + { + if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) + { + /* The mutex is no longer being held. */ + xReturn = xTaskPriorityDisinherit( pxQueue->u.xSemaphore.xMutexHolder ); + pxQueue->u.xSemaphore.xMutexHolder = NULL; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_MUTEXES */ + } + else if( xPosition == queueSEND_TO_BACK ) + { + ( void ) memcpy( ( void * ) pxQueue->pcWriteTo, pvItemToQueue, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e418 !e9087 MISRA exception as the casts are only redundant for some ports, plus previous logic ensures a null pointer can only be passed to memcpy() if the copy size is 0. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. */ + pxQueue->pcWriteTo += pxQueue->uxItemSize; /*lint !e9016 Pointer arithmetic on char types ok, especially in this use case where it is the clearest way of conveying intent. */ + + if( pxQueue->pcWriteTo >= pxQueue->u.xQueue.pcTail ) /*lint !e946 MISRA exception justified as comparison of pointers is the cleanest solution. */ + { + pxQueue->pcWriteTo = pxQueue->pcHead; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + ( void ) memcpy( ( void * ) pxQueue->u.xQueue.pcReadFrom, pvItemToQueue, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e9087 !e418 MISRA exception as the casts are only redundant for some ports. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. Assert checks null pointer only used when length is 0. */ + pxQueue->u.xQueue.pcReadFrom -= pxQueue->uxItemSize; + + if( pxQueue->u.xQueue.pcReadFrom < pxQueue->pcHead ) /*lint !e946 MISRA exception justified as comparison of pointers is the cleanest solution. */ + { + pxQueue->u.xQueue.pcReadFrom = ( pxQueue->u.xQueue.pcTail - pxQueue->uxItemSize ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + if( xPosition == queueOVERWRITE ) + { + if( uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* An item is not being added but overwritten, so subtract + * one from the recorded number of items in the queue so when + * one is added again below the number of recorded items remains + * correct. */ + --uxMessagesWaiting; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + pxQueue->uxMessagesWaiting = uxMessagesWaiting + ( UBaseType_t ) 1; + + return xReturn; +} +/*-----------------------------------------------------------*/ + +static void prvCopyDataFromQueue( Queue_t * const pxQueue, + void * const pvBuffer ) +{ + if( pxQueue->uxItemSize != ( UBaseType_t ) 0 ) + { + pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; /*lint !e9016 Pointer arithmetic on char types ok, especially in this use case where it is the clearest way of conveying intent. */ + + if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) /*lint !e946 MISRA exception justified as use of the relational operator is the cleanest solutions. */ + { + pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + ( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e418 !e9087 MISRA exception as the casts are only redundant for some ports. Also previous logic ensures a null pointer can only be passed to memcpy() when the count is 0. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. */ + } +} +/*-----------------------------------------------------------*/ + +static void prvUnlockQueue( Queue_t * const pxQueue ) +{ + /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. */ + + /* The lock counts contains the number of extra data items placed or + * removed from the queue while the queue was locked. When a queue is + * locked items can be added or removed, but the event lists cannot be + * updated. */ + taskENTER_CRITICAL(); + { + int8_t cTxLock = pxQueue->cTxLock; + + /* See if data was added to the queue while it was locked. */ + while( cTxLock > queueLOCKED_UNMODIFIED ) + { + /* Data was posted while the queue was locked. Are any tasks + * blocked waiting for data to become available? */ + #if ( configUSE_QUEUE_SETS == 1 ) + { + if( pxQueue->pxQueueSetContainer != NULL ) + { + if( prvNotifyQueueSetContainer( pxQueue ) != pdFALSE ) + { + /* The queue is a member of a queue set, and posting to + * the queue set caused a higher priority task to unblock. + * A context switch is required. */ + vTaskMissedYield(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* Tasks that are removed from the event list will get + * added to the pending ready list as the scheduler is still + * suspended. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so record that a + * context switch is required. */ + vTaskMissedYield(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + break; + } + } + } + #else /* configUSE_QUEUE_SETS */ + { + /* Tasks that are removed from the event list will get added to + * the pending ready list as the scheduler is still suspended. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so record that + * a context switch is required. */ + vTaskMissedYield(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + break; + } + } + #endif /* configUSE_QUEUE_SETS */ + + --cTxLock; + } + + pxQueue->cTxLock = queueUNLOCKED; + } + taskEXIT_CRITICAL(); + + /* Do the same for the Rx lock. */ + taskENTER_CRITICAL(); + { + int8_t cRxLock = pxQueue->cRxLock; + + while( cRxLock > queueLOCKED_UNMODIFIED ) + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + vTaskMissedYield(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + --cRxLock; + } + else + { + break; + } + } + + pxQueue->cRxLock = queueUNLOCKED; + } + taskEXIT_CRITICAL(); +} +/*-----------------------------------------------------------*/ + +static BaseType_t prvIsQueueEmpty( const Queue_t * pxQueue ) +{ + BaseType_t xReturn; + + taskENTER_CRITICAL(); + { + if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + taskEXIT_CRITICAL(); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueueIsQueueEmptyFromISR( const QueueHandle_t xQueue ) +{ + BaseType_t xReturn; + Queue_t * const pxQueue = xQueue; + + configASSERT( pxQueue ); + + if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + + return xReturn; +} /*lint !e818 xQueue could not be pointer to const because it is a typedef. */ +/*-----------------------------------------------------------*/ + +static BaseType_t prvIsQueueFull( const Queue_t * pxQueue ) +{ + BaseType_t xReturn; + + taskENTER_CRITICAL(); + { + if( pxQueue->uxMessagesWaiting == pxQueue->uxLength ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + taskEXIT_CRITICAL(); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueueIsQueueFullFromISR( const QueueHandle_t xQueue ) +{ + BaseType_t xReturn; + Queue_t * const pxQueue = xQueue; + + configASSERT( pxQueue ); + + if( pxQueue->uxMessagesWaiting == pxQueue->uxLength ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + + return xReturn; +} /*lint !e818 xQueue could not be pointer to const because it is a typedef. */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_CO_ROUTINES == 1 ) + + BaseType_t xQueueCRSend( QueueHandle_t xQueue, + const void * pvItemToQueue, + TickType_t xTicksToWait ) + { + BaseType_t xReturn; + Queue_t * const pxQueue = xQueue; + + /* If the queue is already full we may have to block. A critical section + * is required to prevent an interrupt removing something from the queue + * between the check to see if the queue is full and blocking on the queue. */ + portDISABLE_INTERRUPTS(); + { + if( prvIsQueueFull( pxQueue ) != pdFALSE ) + { + /* The queue is full - do we want to block or just leave without + * posting? */ + if( xTicksToWait > ( TickType_t ) 0 ) + { + /* As this is called from a coroutine we cannot block directly, but + * return indicating that we need to block. */ + vCoRoutineAddToDelayedList( xTicksToWait, &( pxQueue->xTasksWaitingToSend ) ); + portENABLE_INTERRUPTS(); + return errQUEUE_BLOCKED; + } + else + { + portENABLE_INTERRUPTS(); + return errQUEUE_FULL; + } + } + } + portENABLE_INTERRUPTS(); + + portDISABLE_INTERRUPTS(); + { + if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) + { + /* There is room in the queue, copy the data into the queue. */ + prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK ); + xReturn = pdPASS; + + /* Were any co-routines waiting for data to become available? */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + /* In this instance the co-routine could be placed directly + * into the ready list as we are within a critical section. + * Instead the same pending ready list mechanism is used as if + * the event were caused from within an interrupt. */ + if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The co-routine waiting has a higher priority so record + * that a yield might be appropriate. */ + xReturn = errQUEUE_YIELD; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + xReturn = errQUEUE_FULL; + } + } + portENABLE_INTERRUPTS(); + + return xReturn; + } + +#endif /* configUSE_CO_ROUTINES */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_CO_ROUTINES == 1 ) + + BaseType_t xQueueCRReceive( QueueHandle_t xQueue, + void * pvBuffer, + TickType_t xTicksToWait ) + { + BaseType_t xReturn; + Queue_t * const pxQueue = xQueue; + + /* If the queue is already empty we may have to block. A critical section + * is required to prevent an interrupt adding something to the queue + * between the check to see if the queue is empty and blocking on the queue. */ + portDISABLE_INTERRUPTS(); + { + if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) + { + /* There are no messages in the queue, do we want to block or just + * leave with nothing? */ + if( xTicksToWait > ( TickType_t ) 0 ) + { + /* As this is a co-routine we cannot block directly, but return + * indicating that we need to block. */ + vCoRoutineAddToDelayedList( xTicksToWait, &( pxQueue->xTasksWaitingToReceive ) ); + portENABLE_INTERRUPTS(); + return errQUEUE_BLOCKED; + } + else + { + portENABLE_INTERRUPTS(); + return errQUEUE_FULL; + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + portENABLE_INTERRUPTS(); + + portDISABLE_INTERRUPTS(); + { + if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* Data is available from the queue. */ + pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; + + if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) + { + pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + --( pxQueue->uxMessagesWaiting ); + ( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( unsigned ) pxQueue->uxItemSize ); + + xReturn = pdPASS; + + /* Were any co-routines waiting for space to become available? */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + /* In this instance the co-routine could be placed directly + * into the ready list as we are within a critical section. + * Instead the same pending ready list mechanism is used as if + * the event were caused from within an interrupt. */ + if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + xReturn = errQUEUE_YIELD; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + xReturn = pdFAIL; + } + } + portENABLE_INTERRUPTS(); + + return xReturn; + } + +#endif /* configUSE_CO_ROUTINES */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_CO_ROUTINES == 1 ) + + BaseType_t xQueueCRSendFromISR( QueueHandle_t xQueue, + const void * pvItemToQueue, + BaseType_t xCoRoutinePreviouslyWoken ) + { + Queue_t * const pxQueue = xQueue; + + /* Cannot block within an ISR so if there is no space on the queue then + * exit without doing anything. */ + if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) + { + prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK ); + + /* We only want to wake one co-routine per ISR, so check that a + * co-routine has not already been woken. */ + if( xCoRoutinePreviouslyWoken == pdFALSE ) + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + return pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xCoRoutinePreviouslyWoken; + } + +#endif /* configUSE_CO_ROUTINES */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_CO_ROUTINES == 1 ) + + BaseType_t xQueueCRReceiveFromISR( QueueHandle_t xQueue, + void * pvBuffer, + BaseType_t * pxCoRoutineWoken ) + { + BaseType_t xReturn; + Queue_t * const pxQueue = xQueue; + + /* We cannot block from an ISR, so check there is data available. If + * not then just leave without doing anything. */ + if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* Copy the data from the queue. */ + pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; + + if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) + { + pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + --( pxQueue->uxMessagesWaiting ); + ( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( unsigned ) pxQueue->uxItemSize ); + + if( ( *pxCoRoutineWoken ) == pdFALSE ) + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + *pxCoRoutineWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + } + + return xReturn; + } + +#endif /* configUSE_CO_ROUTINES */ +/*-----------------------------------------------------------*/ + +#if ( configQUEUE_REGISTRY_SIZE > 0 ) + + void vQueueAddToRegistry( QueueHandle_t xQueue, + const char * pcQueueName ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + { + UBaseType_t ux; + + /* 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_SET_SEND( pxQueueSetContainer ); + + /* The data copied is the handle of the queue that contains data. */ + xReturn = prvCopyDataToQueue( pxQueueSetContainer, &pxQueue, queueSEND_TO_BACK ); + + if( cTxLock == queueUNLOCKED ) + { + if( listLIST_IS_EMPTY( &( pxQueueSetContainer->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueueSetContainer->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority. */ + xReturn = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + configASSERT( cTxLock != queueINT8_MAX ); + + pxQueueSetContainer->cTxLock = ( int8_t ) ( cTxLock + 1 ); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xReturn; + } + +#endif /* configUSE_QUEUE_SETS */ diff --git a/examples/stm32/freertos-kernel/stream_buffer.c b/examples/stm32/freertos-kernel/stream_buffer.c new file mode 100644 index 00000000..5c6a47e2 --- /dev/null +++ b/examples/stm32/freertos-kernel/stream_buffer.c @@ -0,0 +1,1314 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* Standard includes. */ +#include +#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 overridden. */ +#ifndef sbRECEIVE_COMPLETED + #define sbRECEIVE_COMPLETED( pxStreamBuffer ) \ + vTaskSuspendAll(); \ + { \ + if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) \ + { \ + ( void ) xTaskNotify( ( pxStreamBuffer )->xTaskWaitingToSend, \ + ( uint32_t ) 0, \ + eNoAction ); \ + ( pxStreamBuffer )->xTaskWaitingToSend = NULL; \ + } \ + } \ + ( void ) xTaskResumeAll(); +#endif /* sbRECEIVE_COMPLETED */ + +#ifndef sbRECEIVE_COMPLETED_FROM_ISR + #define sbRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, \ + pxHigherPriorityTaskWoken ) \ + { \ + UBaseType_t uxSavedInterruptStatus; \ + \ + uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); \ + { \ + if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) \ + { \ + ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToSend, \ + ( uint32_t ) 0, \ + eNoAction, \ + pxHigherPriorityTaskWoken ); \ + ( pxStreamBuffer )->xTaskWaitingToSend = NULL; \ + } \ + } \ + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); \ + } +#endif /* sbRECEIVE_COMPLETED_FROM_ISR */ + +/* If the user has not provided an application specific Tx notification macro, + * or #defined the notification macro away, them provide a default implementation + * that uses task notifications. */ +#ifndef sbSEND_COMPLETED + #define sbSEND_COMPLETED( pxStreamBuffer ) \ + vTaskSuspendAll(); \ + { \ + if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) \ + { \ + ( void ) xTaskNotify( ( pxStreamBuffer )->xTaskWaitingToReceive, \ + ( uint32_t ) 0, \ + eNoAction ); \ + ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; \ + } \ + } \ + ( void ) xTaskResumeAll(); +#endif /* sbSEND_COMPLETED */ + +#ifndef sbSEND_COMPLETE_FROM_ISR + #define sbSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ) \ + { \ + UBaseType_t uxSavedInterruptStatus; \ + \ + uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); \ + { \ + if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) \ + { \ + ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToReceive, \ + ( uint32_t ) 0, \ + eNoAction, \ + pxHigherPriorityTaskWoken ); \ + ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; \ + } \ + } \ + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); \ + } +#endif /* sbSEND_COMPLETE_FROM_ISR */ +/*lint -restore (9026) */ + +/* The number of bytes used to hold the length of a message in the buffer. */ +#define sbBYTES_TO_STORE_MESSAGE_LENGTH ( sizeof( configMESSAGE_BUFFER_LENGTH_TYPE ) ) + +/* Bits stored in the ucFlags field of the stream buffer. */ +#define sbFLAGS_IS_MESSAGE_BUFFER ( ( uint8_t ) 1 ) /* Set if the stream buffer was created as a message buffer, in which case it holds discrete messages rather than a stream. */ +#define sbFLAGS_IS_STATICALLY_ALLOCATED ( ( uint8_t ) 2 ) /* Set if the stream buffer was created using statically allocated memory. */ + +/*-----------------------------------------------------------*/ + +/* Structure that hold state information on the buffer. */ +typedef struct StreamBufferDef_t /*lint !e9058 Style convention uses tag. */ +{ + volatile size_t xTail; /* Index to the next item to read within the buffer. */ + volatile size_t xHead; /* Index to the next item to write within the buffer. */ + size_t xLength; /* The length of the buffer pointed to by pucBuffer. */ + size_t xTriggerLevelBytes; /* The number of bytes that must be in the stream buffer before a task that is waiting for data is unblocked. */ + volatile TaskHandle_t xTaskWaitingToReceive; /* Holds the handle of a task waiting for data, or NULL if no tasks are waiting. */ + volatile TaskHandle_t xTaskWaitingToSend; /* Holds the handle of a task waiting to send data to a message buffer that is full. */ + uint8_t * pucBuffer; /* Points to the buffer itself - that is - the RAM that stores the data passed through the buffer. */ + uint8_t ucFlags; + + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxStreamBufferNumber; /* Used for tracing purposes. */ + #endif +} StreamBuffer_t; + +/* + * The number of bytes available to be read from the buffer. + */ +static size_t prvBytesInBuffer( const StreamBuffer_t * const pxStreamBuffer ) PRIVILEGED_FUNCTION; + +/* + * Add xCount bytes from pucData into the pxStreamBuffer 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. */ + if( xBufferSizeBytes < ( xBufferSizeBytes + 1 + sizeof( StreamBuffer_t ) ) ) + { + xBufferSizeBytes++; + pucAllocatedMemory = ( uint8_t * ) pvPortMalloc( xBufferSizeBytes + sizeof( StreamBuffer_t ) ); /*lint !e9079 malloc() only returns void*. */ + } + else + { + pucAllocatedMemory = NULL; + } + + + if( pucAllocatedMemory != NULL ) + { + prvInitialiseNewStreamBuffer( ( StreamBuffer_t * ) pucAllocatedMemory, /* Structure at the start of the allocated memory. */ /*lint !e9087 Safe cast as allocated memory is aligned. */ /*lint !e826 Area is not too small and alignment is guaranteed provided malloc() behaves as expected and returns aligned buffer. */ + pucAllocatedMemory + sizeof( StreamBuffer_t ), /* Storage area follows. */ /*lint !e9016 Indexing past structure valid for uint8_t pointer, also storage area has no alignment requirement. */ + xBufferSizeBytes, + xTriggerLevelBytes, + ucFlags ); + + traceSTREAM_BUFFER_CREATE( ( ( StreamBuffer_t * ) pucAllocatedMemory ), xIsMessageBuffer ); + } + else + { + traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer ); + } + + return ( StreamBufferHandle_t ) pucAllocatedMemory; /*lint !e9087 !e826 Safe cast as allocated memory is aligned. */ + } + +#endif /* configSUPPORT_DYNAMIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + + StreamBufferHandle_t xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + BaseType_t xIsMessageBuffer, + uint8_t * const pucStreamBufferStorageArea, + StaticStreamBuffer_t * const pxStaticStreamBuffer ) + { + StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) pxStaticStreamBuffer; /*lint !e740 !e9087 Safe cast as StaticStreamBuffer_t is opaque Streambuffer_t. */ + StreamBufferHandle_t xReturn; + uint8_t ucFlags; + + configASSERT( pucStreamBufferStorageArea ); + configASSERT( pxStaticStreamBuffer ); + configASSERT( xTriggerLevelBytes <= xBufferSizeBytes ); + + /* A trigger level of 0 would cause a waiting task to unblock even when + * the buffer was empty. */ + if( xTriggerLevelBytes == ( size_t ) 0 ) + { + xTriggerLevelBytes = ( size_t ) 1; + } + + if( xIsMessageBuffer != pdFALSE ) + { + /* Statically allocated message buffer. */ + ucFlags = sbFLAGS_IS_MESSAGE_BUFFER | sbFLAGS_IS_STATICALLY_ALLOCATED; + } + else + { + /* Statically allocated stream buffer. */ + ucFlags = sbFLAGS_IS_STATICALLY_ALLOCATED; + } + + /* In case the stream buffer is going to be used as a message buffer + * (that is, it will hold discrete messages with a little meta data that + * says how big the next message is) check the buffer will be large enough + * to hold at least one message. */ + configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH ); + + #if ( configASSERT_DEFINED == 1 ) + { + /* Sanity check that the size of the structure used to declare a + * variable of type StaticStreamBuffer_t equals the size of the real + * message buffer structure. */ + volatile size_t xSize = sizeof( StaticStreamBuffer_t ); + configASSERT( xSize == sizeof( StreamBuffer_t ) ); + } /*lint !e529 xSize is referenced is configASSERT() is defined. */ + #endif /* configASSERT_DEFINED */ + + if( ( pucStreamBufferStorageArea != NULL ) && ( pxStaticStreamBuffer != NULL ) ) + { + prvInitialiseNewStreamBuffer( pxStreamBuffer, + pucStreamBufferStorageArea, + xBufferSizeBytes, + xTriggerLevelBytes, + ucFlags ); + + /* Remember this was statically allocated in case it is ever deleted + * again. */ + pxStreamBuffer->ucFlags |= sbFLAGS_IS_STATICALLY_ALLOCATED; + + traceSTREAM_BUFFER_CREATE( pxStreamBuffer, xIsMessageBuffer ); + + xReturn = ( StreamBufferHandle_t ) pxStaticStreamBuffer; /*lint !e9087 Data hiding requires cast to opaque type. */ + } + else + { + xReturn = NULL; + traceSTREAM_BUFFER_CREATE_STATIC_FAILED( xReturn, xIsMessageBuffer ); + } + + return xReturn; + } + +#endif /* ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ +/*-----------------------------------------------------------*/ + +void vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer ) +{ + StreamBuffer_t * pxStreamBuffer = xStreamBuffer; + + configASSERT( pxStreamBuffer ); + + traceSTREAM_BUFFER_DELETE( xStreamBuffer ); + + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_STATICALLY_ALLOCATED ) == ( uint8_t ) pdFALSE ) + { + #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + { + /* Both the structure and the buffer were allocated using a single call + * to pvPortMalloc(), hence only one call to vPortFree() is required. */ + vPortFree( ( void * ) pxStreamBuffer ); /*lint !e9087 Standard free() semantics require void *, plus pxStreamBuffer was allocated by pvPortMalloc(). */ + } + #else + { + /* Should not be possible to get here, ucFlags must be corrupt. + * Force an assert. */ + configASSERT( xStreamBuffer == ( StreamBufferHandle_t ) ~0 ); + } + #endif + } + else + { + /* The structure and buffer were not allocated dynamically and cannot be + * freed - just scrub the structure so future use will assert. */ + ( void ) memset( pxStreamBuffer, 0x00, sizeof( StreamBuffer_t ) ); + } +} +/*-----------------------------------------------------------*/ + +BaseType_t xStreamBufferReset( StreamBufferHandle_t xStreamBuffer ) +{ + StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + BaseType_t xReturn = pdFAIL; + + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxStreamBufferNumber; + #endif + + configASSERT( pxStreamBuffer ); + + #if ( configUSE_TRACE_FACILITY == 1 ) + { + /* Store the stream buffer number so it can be restored after the + * reset. */ + uxStreamBufferNumber = pxStreamBuffer->uxStreamBufferNumber; + } + #endif + + /* Can only reset a message buffer if there are no tasks blocked on it. */ + taskENTER_CRITICAL(); + { + if( pxStreamBuffer->xTaskWaitingToReceive == NULL ) + { + if( pxStreamBuffer->xTaskWaitingToSend == NULL ) + { + prvInitialiseNewStreamBuffer( pxStreamBuffer, + pxStreamBuffer->pucBuffer, + pxStreamBuffer->xLength, + pxStreamBuffer->xTriggerLevelBytes, + pxStreamBuffer->ucFlags ); + xReturn = pdPASS; + + #if ( configUSE_TRACE_FACILITY == 1 ) + { + pxStreamBuffer->uxStreamBufferNumber = uxStreamBufferNumber; + } + #endif + + traceSTREAM_BUFFER_RESET( xStreamBuffer ); + } + } + } + taskEXIT_CRITICAL(); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, + size_t xTriggerLevel ) +{ + StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + BaseType_t xReturn; + + configASSERT( pxStreamBuffer ); + + /* It is not valid for the trigger level to be 0. */ + if( xTriggerLevel == ( size_t ) 0 ) + { + xTriggerLevel = ( size_t ) 1; + } + + /* The trigger level is the number of bytes that must be in the stream + * buffer before a task that is waiting for data is unblocked. */ + if( xTriggerLevel <= pxStreamBuffer->xLength ) + { + pxStreamBuffer->xTriggerLevelBytes = xTriggerLevel; + xReturn = pdPASS; + } + else + { + xReturn = pdFALSE; + } + + return xReturn; +} +/*-----------------------------------------------------------*/ + +size_t xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer ) +{ + const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + size_t xSpace; + + 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; + + /* The maximum amount of space a stream buffer will ever report is its length + * minus 1. */ + const size_t xMaxReportedSpace = pxStreamBuffer->xLength - ( size_t ) 1; + + 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 ); + + /* If this is a message buffer then it must be possible to write the + * whole message. */ + if( xRequiredSpace > xMaxReportedSpace ) + { + /* The message would not fit even if the entire buffer was empty, + * so don't wait for space. */ + xTicksToWait = ( TickType_t ) 0; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* If this is a stream buffer then it is acceptable to write only part + * of the message to the buffer. Cap the length to the total length of + * the buffer. */ + if( xRequiredSpace > xMaxReportedSpace ) + { + xRequiredSpace = xMaxReportedSpace; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + if( xTicksToWait != ( TickType_t ) 0 ) + { + vTaskSetTimeOutState( &xTimeOut ); + + do + { + /* Wait until the required number of bytes are free in the message + * buffer. */ + taskENTER_CRITICAL(); + { + xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); + + if( xSpace < xRequiredSpace ) + { + /* Clear notification state as going to wait for space. */ + ( void ) xTaskNotifyStateClear( NULL ); + + /* Should only be one writer. */ + configASSERT( pxStreamBuffer->xTaskWaitingToSend == NULL ); + pxStreamBuffer->xTaskWaitingToSend = xTaskGetCurrentTaskHandle(); + } + else + { + taskEXIT_CRITICAL(); + break; + } + } + taskEXIT_CRITICAL(); + + traceBLOCKING_ON_STREAM_BUFFER_SEND( xStreamBuffer ); + ( void ) xTaskNotifyWait( ( uint32_t ) 0, ( uint32_t ) 0, NULL, xTicksToWait ); + pxStreamBuffer->xTaskWaitingToSend = NULL; + } while( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + if( xSpace == ( size_t ) 0 ) + { + xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + xReturn = prvWriteMessageToBuffer( pxStreamBuffer, pvTxData, xDataLengthBytes, xSpace, xRequiredSpace ); + + if( xReturn > ( size_t ) 0 ) + { + traceSTREAM_BUFFER_SEND( xStreamBuffer, xReturn ); + + /* Was a task waiting for the data? */ + if( prvBytesInBuffer( pxStreamBuffer ) >= pxStreamBuffer->xTriggerLevelBytes ) + { + sbSEND_COMPLETED( pxStreamBuffer ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + traceSTREAM_BUFFER_SEND_FAILED( xStreamBuffer ); + } + + return xReturn; +} +/*-----------------------------------------------------------*/ + +size_t xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer, + const void * pvTxData, + size_t xDataLengthBytes, + BaseType_t * const pxHigherPriorityTaskWoken ) +{ + StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + size_t xReturn, xSpace; + size_t xRequiredSpace = xDataLengthBytes; + + configASSERT( pvTxData ); + configASSERT( pxStreamBuffer ); + + /* This send function is used to write to both message buffers and stream + * buffers. If this is a message buffer then the space needed must be + * increased by the amount of bytes needed to store the length of the + * message. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xRequiredSpace += sbBYTES_TO_STORE_MESSAGE_LENGTH; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); + xReturn = prvWriteMessageToBuffer( pxStreamBuffer, pvTxData, xDataLengthBytes, xSpace, xRequiredSpace ); + + if( xReturn > ( size_t ) 0 ) + { + /* Was a task waiting for the data? */ + if( prvBytesInBuffer( pxStreamBuffer ) >= pxStreamBuffer->xTriggerLevelBytes ) + { + sbSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceSTREAM_BUFFER_SEND_FROM_ISR( xStreamBuffer, xReturn ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +static size_t prvWriteMessageToBuffer( StreamBuffer_t * const pxStreamBuffer, + const void * pvTxData, + size_t xDataLengthBytes, + size_t xSpace, + size_t xRequiredSpace ) +{ + 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, alignment 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/examples/stm32/freertos-kernel/tasks.c b/examples/stm32/freertos-kernel/tasks.c new file mode 100644 index 00000000..884005af --- /dev/null +++ b/examples/stm32/freertos-kernel/tasks.c @@ -0,0 +1,5395 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* Standard includes. */ +#include +#include + +/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining + * all the API functions to use the MPU wrappers. That should only be done when + * task.h is included from an application file. */ +#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "timers.h" +#include "stack_macros.h" + +/* Lint e9021, e961 and e750 are suppressed as a MISRA exception justified + * because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined + * for the header files above, but not in this file, in order to generate the + * correct privileged Vs unprivileged linkage and placement. */ +#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750 !e9021. */ + +/* Set configUSE_STATS_FORMATTING_FUNCTIONS to 2 to include the stats formatting + * functions but without including stdio.h here. */ +#if ( configUSE_STATS_FORMATTING_FUNCTIONS == 1 ) + +/* At the bottom of this file are two optional functions that can be used + * to generate human readable text from the raw data generated by the + * uxTaskGetSystemState() function. Note the formatting functions are provided + * for convenience only, and are NOT considered part of the kernel. */ + #include +#endif /* configUSE_STATS_FORMATTING_FUNCTIONS == 1 ) */ + +#if ( configUSE_PREEMPTION == 0 ) + +/* If the cooperative scheduler is being used then a yield should not be + * performed just because a higher priority task has been woken. */ + #define taskYIELD_IF_USING_PREEMPTION() +#else + #define taskYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API() +#endif + +/* Values that can be assigned to the ucNotifyState member of the TCB. */ +#define taskNOT_WAITING_NOTIFICATION ( ( uint8_t ) 0 ) /* Must be zero as it is the initialised value. */ +#define taskWAITING_NOTIFICATION ( ( uint8_t ) 1 ) +#define taskNOTIFICATION_RECEIVED ( ( uint8_t ) 2 ) + +/* + * The value used to fill the stack of a task when the task is created. This + * is used purely for checking the high water mark for tasks. + */ +#define tskSTACK_FILL_BYTE ( 0xa5U ) + +/* Bits used to 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[ configTASK_NOTIFICATION_ARRAY_ENTRIES ]; + volatile uint8_t ucNotifyState[ configTASK_NOTIFICATION_ARRAY_ENTRIES ]; + #endif + + /* See the comments in FreeRTOS.h with the definition of + * tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE. */ + #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */ + uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the task is a statically allocated to ensure no attempt is made to free the memory. */ + #endif + + #if ( INCLUDE_xTaskAbortDelay == 1 ) + uint8_t ucDelayAborted; + #endif + + #if ( configUSE_POSIX_ERRNO == 1 ) + int iTaskErrno; + #endif +} tskTCB; + +/* The old tskTCB name is maintained above then typedefed to the new TCB_t name + * below to enable the use of older kernel aware debuggers. */ +typedef tskTCB TCB_t; + +/*lint -save -e956 A manual analysis and inspection has been used to determine + * which static variables must be declared volatile. */ +PRIVILEGED_DATA TCB_t * volatile pxCurrentTCB = NULL; + +/* Lists for ready and blocked tasks. -------------------- + * xDelayedTaskList1 and xDelayedTaskList2 could be 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. */ + +/* Improve support for OpenOCD. The kernel tracks Ready tasks via priority lists. + * For tracking the state of remote threads, OpenOCD uses uxTopUsedPriority + * to determine the number of priority lists to read back from the remote target. */ +const volatile UBaseType_t uxTopUsedPriority = configMAX_PRIORITIES - 1U; + +/* Context switches are held pending while the scheduler is suspended. Also, + * interrupts must not manipulate the xStateListItem of a TCB, or any of the + * lists the xStateListItem can be referenced from, if the scheduler is suspended. + * If an interrupt needs to unblock a task while the scheduler is suspended then it + * moves the task's event list item into the xPendingReadyList, ready for the + * kernel to move the task from the pending ready list into the real ready list + * when the scheduler is unsuspended. The pending ready list itself can only be + * accessed from a critical section. */ +PRIVILEGED_DATA static volatile UBaseType_t uxSchedulerSuspended = ( UBaseType_t ) pdFALSE; + +#if ( configGENERATE_RUN_TIME_STATS == 1 ) + +/* Do not move these variables to function scope as doing so prevents the + * code working with debuggers that need to remove the static qualifier. */ + PRIVILEGED_DATA static uint32_t ulTaskSwitchedInTime = 0UL; /*< Holds the value of a timer/counter the last time a task was switched in. */ + PRIVILEGED_DATA static volatile uint32_t ulTotalRunTime = 0UL; /*< Holds the total amount of execution time as defined by the run time counter clock. */ + +#endif + +/*lint -restore */ + +/*-----------------------------------------------------------*/ + +/* File private functions. --------------------------------*/ + +/** + * Utility task that simply returns pdTRUE if the task referenced by xTask is + * currently in the Suspended state, or pdFALSE if the task referenced by xTask + * is in any other state. + */ +#if ( INCLUDE_vTaskSuspend == 1 ) + + static BaseType_t prvTaskIsTaskSuspended( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +#endif /* INCLUDE_vTaskSuspend */ + +/* + * Utility to ready all the lists used by the scheduler. This is called + * automatically upon the creation of the first task. + */ +static void prvInitialiseTaskLists( void ) PRIVILEGED_FUNCTION; + +/* + * The idle task, which as all tasks is implemented as a never ending loop. + * The idle task is automatically created and added to the ready lists upon + * creation of the first user task. + * + * The portTASK_FUNCTION_PROTO() macro is used to allow port/compiler specific + * language extensions. The equivalent prototype for this function is: + * + * void prvIdleTask( void *pvParameters ); + * + */ +static portTASK_FUNCTION_PROTO( prvIdleTask, pvParameters ) PRIVILEGED_FUNCTION; + +/* + * Utility to free all memory allocated by the scheduler to hold a TCB, + * including the stack pointed to by the TCB. + * + * This does not free memory allocated by the task itself (i.e. memory + * allocated by calls to pvPortMalloc from within the tasks application code). + */ +#if ( INCLUDE_vTaskDelete == 1 ) + + static void prvDeleteTCB( TCB_t * pxTCB ) PRIVILEGED_FUNCTION; + +#endif + +/* + * Used only by the idle task. This checks to see if anything has been placed + * in the list of tasks waiting to be deleted. If so the task is cleaned up + * and its TCB deleted. + */ +static void prvCheckTasksWaitingTermination( void ) PRIVILEGED_FUNCTION; + +/* + * The currently executing task is entering the Blocked state. Add the task to + * either the current or the overflow delayed task list. + */ +static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait, + const BaseType_t xCanBlockIndefinitely ) PRIVILEGED_FUNCTION; + +/* + * Fills an TaskStatus_t structure with information on each task that is + * referenced from the pxList list (which may be a ready list, a delayed list, + * a suspended list, etc.). + * + * THIS FUNCTION IS INTENDED FOR DEBUGGING ONLY, AND SHOULD NOT BE CALLED FROM + * NORMAL APPLICATION CODE. + */ +#if ( configUSE_TRACE_FACILITY == 1 ) + + static UBaseType_t prvListTasksWithinSingleList( TaskStatus_t * pxTaskStatusArray, + List_t * pxList, + eTaskState eState ) PRIVILEGED_FUNCTION; + +#endif + +/* + * Searches pxList for a task with name pcNameToQuery - returning a handle to + * the task if it is found, or NULL if the task is not found. + */ +#if ( INCLUDE_xTaskGetHandle == 1 ) + + static TCB_t * prvSearchForNameWithinSingleList( List_t * pxList, + const char pcNameToQuery[] ) PRIVILEGED_FUNCTION; + +#endif + +/* + * When a task is created, the stack of the task is filled with a known value. + * This function determines the 'high water mark' of the task stack by + * determining how much of the stack remains at the original preset value. + */ +#if ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) ) + + static configSTACK_DEPTH_TYPE prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte ) PRIVILEGED_FUNCTION; + +#endif + +/* + * Return the amount of time, in ticks, that will pass before the kernel will + * next move a task from the Blocked state to the Running state. + * + * This conditional compilation should use inequality to 0, not equality to 1. + * This is to ensure portSUPPRESS_TICKS_AND_SLEEP() can be called when user + * defined low power mode implementations require configUSE_TICKLESS_IDLE to be + * set to a value other than 1. + */ +#if ( configUSE_TICKLESS_IDLE != 0 ) + + static TickType_t prvGetExpectedIdleTime( void ) PRIVILEGED_FUNCTION; + +#endif + +/* + * Set xNextTaskUnblockTime to the time at which the next Blocked state task + * will exit the Blocked state. + */ +static void prvResetNextTaskUnblockTime( void ) PRIVILEGED_FUNCTION; + +#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) ) + +/* + * Helper function used to pad task names with spaces when printing out + * human readable tables of task information. + */ + static char * prvWriteNameToBuffer( char * pcBuffer, + const char * pcTaskName ) PRIVILEGED_FUNCTION; + +#endif + +/* + * Called after a Task_t structure has been allocated either statically or + * dynamically to fill in the structure's members. + */ +static void prvInitialiseNewTask( TaskFunction_t pxTaskCode, + const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const uint32_t ulStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask, + TCB_t * pxNewTCB, + const MemoryRegion_t * const xRegions ) PRIVILEGED_FUNCTION; + +/* + * Called after a new task has been created and initialised to place the task + * under the control of the scheduler. + */ +static void prvAddNewTaskToReadyList( TCB_t * pxNewTCB ) PRIVILEGED_FUNCTION; + +/* + * freertos_tasks_c_additions_init() should only be called if the user definable + * macro FREERTOS_TASKS_C_ADDITIONS_INIT() is defined, as that is the only macro + * called by the function. + */ +#ifdef FREERTOS_TASKS_C_ADDITIONS_INIT + + static void freertos_tasks_c_additions_init( void ) PRIVILEGED_FUNCTION; + +#endif + +/*-----------------------------------------------------------*/ + +#if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + + TaskHandle_t xTaskCreateStatic( TaskFunction_t pxTaskCode, + const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const uint32_t ulStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + StackType_t * const puxStackBuffer, + StaticTask_t * const pxTaskBuffer ) + { + TCB_t * pxNewTCB; + TaskHandle_t xReturn; + + configASSERT( puxStackBuffer != NULL ); + configASSERT( pxTaskBuffer != NULL ); + + #if ( configASSERT_DEFINED == 1 ) + { + /* Sanity check that the size of the structure used to declare a + * variable of type StaticTask_t equals the size of the real task + * structure. */ + volatile size_t xSize = sizeof( StaticTask_t ); + configASSERT( xSize == sizeof( TCB_t ) ); + ( void ) xSize; /* Prevent lint warning when configASSERT() is not used. */ + } + #endif /* configASSERT_DEFINED */ + + if( ( pxTaskBuffer != NULL ) && ( puxStackBuffer != NULL ) ) + { + /* The memory used for the task's TCB and stack are passed into this + * function - use them. */ + pxNewTCB = ( TCB_t * ) pxTaskBuffer; /*lint !e740 !e9087 Unusual cast is ok as the structures are designed to have the same alignment, and the size is checked by an assert. */ + pxNewTCB->pxStack = ( StackType_t * ) puxStackBuffer; + + #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */ + { + /* Tasks can be created statically or dynamically, so note this + * task was created statically in case the task is later deleted. */ + pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB; + } + #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ + + prvInitialiseNewTask( pxTaskCode, pcName, ulStackDepth, pvParameters, uxPriority, &xReturn, pxNewTCB, NULL ); + prvAddNewTaskToReadyList( pxNewTCB ); + } + else + { + xReturn = NULL; + } + + return xReturn; + } + +#endif /* SUPPORT_STATIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +#if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + + BaseType_t xTaskCreateRestrictedStatic( const TaskParameters_t * const pxTaskDefinition, + TaskHandle_t * pxCreatedTask ) + { + TCB_t * pxNewTCB; + BaseType_t xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; + + configASSERT( pxTaskDefinition->puxStackBuffer != NULL ); + configASSERT( pxTaskDefinition->pxTaskBuffer != NULL ); + + if( ( pxTaskDefinition->puxStackBuffer != NULL ) && ( pxTaskDefinition->pxTaskBuffer != NULL ) ) + { + /* Allocate space for the TCB. Where the memory comes from depends + * on the implementation of the port malloc function and whether or + * not static allocation is being used. */ + pxNewTCB = ( TCB_t * ) pxTaskDefinition->pxTaskBuffer; + + /* Store the stack location in the TCB. */ + pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer; + + #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) + { + /* Tasks can be created statically or dynamically, so note this + * task was created statically in case the task is later deleted. */ + pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB; + } + #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ + + prvInitialiseNewTask( pxTaskDefinition->pvTaskCode, + pxTaskDefinition->pcName, + ( uint32_t ) pxTaskDefinition->usStackDepth, + pxTaskDefinition->pvParameters, + pxTaskDefinition->uxPriority, + pxCreatedTask, pxNewTCB, + pxTaskDefinition->xRegions ); + + prvAddNewTaskToReadyList( pxNewTCB ); + xReturn = pdPASS; + } + + return xReturn; + } + +#endif /* ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ +/*-----------------------------------------------------------*/ + +#if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + + BaseType_t xTaskCreateRestricted( const TaskParameters_t * const pxTaskDefinition, + TaskHandle_t * pxCreatedTask ) + { + TCB_t * pxNewTCB; + BaseType_t xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; + + configASSERT( pxTaskDefinition->puxStackBuffer ); + + if( pxTaskDefinition->puxStackBuffer != NULL ) + { + /* Allocate space for the TCB. Where the memory comes from depends + * on the implementation of the port malloc function and whether or + * not static allocation is being used. */ + pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); + + if( pxNewTCB != NULL ) + { + /* Store the stack location in the TCB. */ + pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer; + + #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) + { + /* Tasks can be created statically or dynamically, so note + * this task had a statically allocated stack in case it is + * later deleted. The TCB was allocated dynamically. */ + pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_ONLY; + } + #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ + + prvInitialiseNewTask( pxTaskDefinition->pvTaskCode, + pxTaskDefinition->pcName, + ( uint32_t ) pxTaskDefinition->usStackDepth, + pxTaskDefinition->pvParameters, + pxTaskDefinition->uxPriority, + pxCreatedTask, pxNewTCB, + pxTaskDefinition->xRegions ); + + prvAddNewTaskToReadyList( pxNewTCB ); + xReturn = pdPASS; + } + } + + return xReturn; + } + +#endif /* portUSING_MPU_WRAPPERS */ +/*-----------------------------------------------------------*/ + +#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + + BaseType_t xTaskCreate( TaskFunction_t pxTaskCode, + const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const configSTACK_DEPTH_TYPE usStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask ) + { + TCB_t * pxNewTCB; + BaseType_t xReturn; + + /* If the stack grows down then allocate the stack then the TCB so the stack + * does not grow into the TCB. Likewise if the stack grows up then allocate + * the TCB then the stack. */ + #if ( portSTACK_GROWTH > 0 ) + { + /* Allocate space for the TCB. Where the memory comes from depends on + * the implementation of the port malloc function and whether or not static + * allocation is being used. */ + pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); + + if( pxNewTCB != NULL ) + { + /* Allocate space for the stack used by the task being created. + * The base of the stack memory stored in the TCB so the task can + * be deleted later if required. */ + pxNewTCB->pxStack = ( StackType_t * ) 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 ) + { + memset( ( void * ) &( pxNewTCB->pvThreadLocalStoragePointers[ 0 ] ), 0x00, sizeof( pxNewTCB->pvThreadLocalStoragePointers ) ); + } + #endif + + #if ( configUSE_TASK_NOTIFICATIONS == 1 ) + { + memset( ( void * ) &( pxNewTCB->ulNotifiedValue[ 0 ] ), 0x00, sizeof( pxNewTCB->ulNotifiedValue ) ); + memset( ( void * ) &( pxNewTCB->ucNotifyState[ 0 ] ), 0x00, sizeof( pxNewTCB->ucNotifyState ) ); + } + #endif + + #if ( configUSE_NEWLIB_REENTRANT == 1 ) + { + /* Initialise this task's Newlib reent structure. + * See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html + * for additional information. */ + _REENT_INIT_PTR( ( &( pxNewTCB->xNewLib_reent ) ) ); + } + #endif + + #if ( INCLUDE_xTaskAbortDelay == 1 ) + { + pxNewTCB->ucDelayAborted = pdFALSE; + } + #endif + + /* Initialize the TCB stack to look as if the task was already running, + * but had been interrupted by the scheduler. The return address is set + * to the start of the task function. Once the stack has been initialised + * the top of stack variable is updated. */ + #if ( portUSING_MPU_WRAPPERS == 1 ) + { + /* If the port has capability to detect stack overflow, + * pass the stack end address to the stack initialization + * function as well. */ + #if ( portHAS_STACK_OVERFLOW_CHECKING == 1 ) + { + #if ( portSTACK_GROWTH < 0 ) + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxStack, pxTaskCode, pvParameters, xRunPrivileged ); + } + #else /* portSTACK_GROWTH */ + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxEndOfStack, pxTaskCode, pvParameters, xRunPrivileged ); + } + #endif /* portSTACK_GROWTH */ + } + #else /* portHAS_STACK_OVERFLOW_CHECKING */ + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters, xRunPrivileged ); + } + #endif /* portHAS_STACK_OVERFLOW_CHECKING */ + } + #else /* portUSING_MPU_WRAPPERS */ + { + /* If the port has capability to detect stack overflow, + * pass the stack end address to the stack initialization + * function as well. */ + #if ( portHAS_STACK_OVERFLOW_CHECKING == 1 ) + { + #if ( portSTACK_GROWTH < 0 ) + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxStack, pxTaskCode, pvParameters ); + } + #else /* portSTACK_GROWTH */ + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxEndOfStack, pxTaskCode, pvParameters ); + } + #endif /* portSTACK_GROWTH */ + } + #else /* portHAS_STACK_OVERFLOW_CHECKING */ + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters ); + } + #endif /* portHAS_STACK_OVERFLOW_CHECKING */ + } + #endif /* portUSING_MPU_WRAPPERS */ + + if( pxCreatedTask != NULL ) + { + /* Pass the handle out in an anonymous way. The handle can be used to + * change the created task's priority, delete the created task, etc.*/ + *pxCreatedTask = ( TaskHandle_t ) pxNewTCB; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } +} +/*-----------------------------------------------------------*/ + +static void prvAddNewTaskToReadyList( TCB_t * pxNewTCB ) +{ + /* Ensure interrupts don't access the task lists while the lists are being + * updated. */ + taskENTER_CRITICAL(); + { + uxCurrentNumberOfTasks++; + + if( pxCurrentTCB == NULL ) + { + /* There are no other tasks, or all the other tasks are in + * the suspended state - make this the current task. */ + pxCurrentTCB = pxNewTCB; + + if( uxCurrentNumberOfTasks == ( UBaseType_t ) 1 ) + { + /* This is the first task to be created so do the preliminary + * initialisation required. We will not recover if this call + * fails, but we will report the failure. */ + prvInitialiseTaskLists(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* If the scheduler is not already running, make this task the + * current task if it is the highest priority task to be created + * so far. */ + if( xSchedulerRunning == pdFALSE ) + { + if( pxCurrentTCB->uxPriority <= pxNewTCB->uxPriority ) + { + pxCurrentTCB = pxNewTCB; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + uxTaskNumber++; + + #if ( configUSE_TRACE_FACILITY == 1 ) + { + /* Add a counter into the TCB for tracing only. */ + pxNewTCB->uxTCBNumber = uxTaskNumber; + } + #endif /* configUSE_TRACE_FACILITY */ + traceTASK_CREATE( pxNewTCB ); + + prvAddTaskToReadyList( pxNewTCB ); + + portSETUP_TCB( pxNewTCB ); + } + taskEXIT_CRITICAL(); + + if( xSchedulerRunning != pdFALSE ) + { + /* If the created task is of a higher priority than the current task + * then it should run now. */ + if( pxCurrentTCB->uxPriority < pxNewTCB->uxPriority ) + { + taskYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } +} +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_vTaskDelete == 1 ) + + void vTaskDelete( TaskHandle_t xTaskToDelete ) + { + TCB_t * pxTCB; + + taskENTER_CRITICAL(); + { + /* If null is passed in here then it is the calling task that is + * being deleted. */ + pxTCB = prvGetTCBFromHandle( xTaskToDelete ); + + /* Remove task from the ready/delayed list. */ + if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + taskRESET_READY_PRIORITY( pxTCB->uxPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Is the task waiting on an event also? */ + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) + { + ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Increment the uxTaskNumber also so kernel aware debuggers can + * detect that the task lists need re-generating. This is done before + * portPRE_TASK_DELETE_HOOK() as in the Windows port that macro will + * not return. */ + uxTaskNumber++; + + if( pxTCB == pxCurrentTCB ) + { + /* A task is deleting itself. This cannot complete within the + * task itself, as a context switch to another task is required. + * Place the task in the termination list. The idle task will + * check the termination list and free up any memory allocated by + * the scheduler for the TCB and stack of the deleted task. */ + vListInsertEnd( &xTasksWaitingTermination, &( pxTCB->xStateListItem ) ); + + /* Increment the ucTasksDeleted variable so the idle task knows + * there is a task that has been deleted and that it should therefore + * check the xTasksWaitingTermination list. */ + ++uxDeletedTasksWaitingCleanUp; + + /* Call the delete hook before portPRE_TASK_DELETE_HOOK() as + * portPRE_TASK_DELETE_HOOK() does not return in the Win32 port. */ + traceTASK_DELETE( pxTCB ); + + /* The pre-delete hook is primarily for the Windows simulator, + * in which Windows specific clean up operations are performed, + * after which it is not possible to yield away from this task - + * hence xYieldPending is used to latch that a context switch is + * required. */ + portPRE_TASK_DELETE_HOOK( pxTCB, &xYieldPending ); + } + else + { + --uxCurrentNumberOfTasks; + traceTASK_DELETE( pxTCB ); + 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_xTaskDelayUntil == 1 ) + + BaseType_t xTaskDelayUntil( TickType_t * const pxPreviousWakeTime, + const TickType_t xTimeIncrement ) + { + TickType_t xTimeToWake; + BaseType_t xAlreadyYielded, xShouldDelay = pdFALSE; + + configASSERT( pxPreviousWakeTime ); + configASSERT( ( xTimeIncrement > 0U ) ); + configASSERT( uxSchedulerSuspended == 0 ); + + vTaskSuspendAll(); + { + /* Minor optimisation. The tick count cannot change in this + * block. */ + const TickType_t xConstTickCount = xTickCount; + + /* Generate the tick time at which the task wants to wake. */ + xTimeToWake = *pxPreviousWakeTime + xTimeIncrement; + + if( xConstTickCount < *pxPreviousWakeTime ) + { + /* The tick count has overflowed since this function was + * lasted called. In this case the only time we should ever + * actually delay is if the wake time has also overflowed, + * and the wake time is greater than the tick time. When this + * is the case it is as if neither time had overflowed. */ + if( ( xTimeToWake < *pxPreviousWakeTime ) && ( xTimeToWake > xConstTickCount ) ) + { + xShouldDelay = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* The tick time has not overflowed. In this case we will + * delay if either the wake time has overflowed, and/or the + * tick time is less than the wake time. */ + if( ( xTimeToWake < *pxPreviousWakeTime ) || ( xTimeToWake > xConstTickCount ) ) + { + xShouldDelay = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + /* Update the wake time ready for the next call. */ + *pxPreviousWakeTime = xTimeToWake; + + if( xShouldDelay != pdFALSE ) + { + traceTASK_DELAY_UNTIL( xTimeToWake ); + + /* prvAddCurrentTaskToDelayedList() needs the block time, not + * the time to wake, so subtract the current tick count. */ + prvAddCurrentTaskToDelayedList( xTimeToWake - xConstTickCount, pdFALSE ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + xAlreadyYielded = xTaskResumeAll(); + + /* Force a reschedule if xTaskResumeAll has not already done so, we may + * have put ourselves to sleep. */ + if( xAlreadyYielded == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xShouldDelay; + } + +#endif /* INCLUDE_xTaskDelayUntil */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_vTaskDelay == 1 ) + + void vTaskDelay( const TickType_t xTicksToDelay ) + { + BaseType_t xAlreadyYielded = pdFALSE; + + /* A delay time of zero just forces a reschedule. */ + if( xTicksToDelay > ( TickType_t ) 0U ) + { + configASSERT( uxSchedulerSuspended == 0 ); + vTaskSuspendAll(); + { + traceTASK_DELAY(); + + /* A task that is removed from the event list while the + * scheduler is suspended will not get placed in the ready + * list or removed from the blocked list until the scheduler + * is resumed. + * + * This task cannot be in an event list as it is the currently + * executing task. */ + prvAddCurrentTaskToDelayedList( xTicksToDelay, pdFALSE ); + } + xAlreadyYielded = xTaskResumeAll(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Force a reschedule if xTaskResumeAll has not already done so, we may + * have put ourselves to sleep. */ + if( xAlreadyYielded == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + +#endif /* INCLUDE_vTaskDelay */ +/*-----------------------------------------------------------*/ + +#if ( ( INCLUDE_eTaskGetState == 1 ) || ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_xTaskAbortDelay == 1 ) ) + + eTaskState eTaskGetState( TaskHandle_t xTask ) + { + eTaskState eReturn; + List_t const * pxStateList, * pxDelayedList, * pxOverflowedDelayedList; + const TCB_t * const pxTCB = xTask; + + configASSERT( pxTCB ); + + if( pxTCB == pxCurrentTCB ) + { + /* The task calling this function is querying its own state. */ + eReturn = eRunning; + } + else + { + taskENTER_CRITICAL(); + { + pxStateList = listLIST_ITEM_CONTAINER( &( pxTCB->xStateListItem ) ); + pxDelayedList = pxDelayedTaskList; + pxOverflowedDelayedList = pxOverflowDelayedTaskList; + } + taskEXIT_CRITICAL(); + + if( ( pxStateList == pxDelayedList ) || ( pxStateList == pxOverflowedDelayedList ) ) + { + /* The task being queried is referenced from one of the Blocked + * lists. */ + eReturn = eBlocked; + } + + #if ( INCLUDE_vTaskSuspend == 1 ) + else if( pxStateList == &xSuspendedTaskList ) + { + /* The task being queried is referenced from the suspended + * list. Is it genuinely suspended or is it blocked + * indefinitely? */ + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ) + { + #if ( configUSE_TASK_NOTIFICATIONS == 1 ) + { + BaseType_t x; + + /* The task does not appear on the event list item of + * and of the RTOS objects, but could still be in the + * blocked state if it is waiting on its notification + * rather than waiting on an object. If not, is + * suspended. */ + eReturn = eSuspended; + + for( x = 0; x < configTASK_NOTIFICATION_ARRAY_ENTRIES; x++ ) + { + if( pxTCB->ucNotifyState[ x ] == taskWAITING_NOTIFICATION ) + { + eReturn = eBlocked; + break; + } + } + } + #else /* if ( configUSE_TASK_NOTIFICATIONS == 1 ) */ + { + eReturn = eSuspended; + } + #endif /* if ( configUSE_TASK_NOTIFICATIONS == 1 ) */ + } + else + { + eReturn = eBlocked; + } + } + #endif /* if ( INCLUDE_vTaskSuspend == 1 ) */ + + #if ( INCLUDE_vTaskDelete == 1 ) + else if( ( pxStateList == &xTasksWaitingTermination ) || ( pxStateList == NULL ) ) + { + /* The task being queried is referenced from the deleted + * tasks list, or it is not referenced from any lists at + * all. */ + eReturn = eDeleted; + } + #endif + + else /*lint !e525 Negative indentation is intended to make use of pre-processor clearer. */ + { + /* If the task is not in any other state, it must be in the + * Ready (including pending ready) state. */ + eReturn = eReady; + } + } + + return eReturn; + } /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */ + +#endif /* INCLUDE_eTaskGetState */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_uxTaskPriorityGet == 1 ) + + UBaseType_t uxTaskPriorityGet( const TaskHandle_t xTask ) + { + TCB_t const * pxTCB; + UBaseType_t uxReturn; + + taskENTER_CRITICAL(); + { + /* If null is passed in here then it is the priority of the task + * that called uxTaskPriorityGet() that is being queried. */ + pxTCB = prvGetTCBFromHandle( xTask ); + uxReturn = pxTCB->uxPriority; + } + taskEXIT_CRITICAL(); + + return uxReturn; + } + +#endif /* INCLUDE_uxTaskPriorityGet */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_uxTaskPriorityGet == 1 ) + + UBaseType_t uxTaskPriorityGetFromISR( const TaskHandle_t xTask ) + { + TCB_t const * pxTCB; + UBaseType_t uxReturn, uxSavedInterruptState; + + /* RTOS ports that support interrupt nesting have the concept of a + * maximum system call (or maximum API call) interrupt priority. + * Interrupts that are above the maximum system call priority are keep + * permanently enabled, even when the RTOS kernel is in a critical section, + * but cannot make any calls to FreeRTOS API functions. If configASSERT() + * is defined in FreeRTOSConfig.h then + * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + * failure if a FreeRTOS API function is called from an interrupt that has + * been assigned a priority above the configured maximum system call + * priority. Only FreeRTOS functions that end in FromISR can be called + * from interrupts that have been assigned a priority at or (logically) + * below the maximum system call interrupt priority. FreeRTOS maintains a + * separate interrupt safe API to ensure interrupt entry is as fast and as + * simple as possible. More information (albeit Cortex-M specific) is + * provided on the following link: + * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + uxSavedInterruptState = portSET_INTERRUPT_MASK_FROM_ISR(); + { + /* If null is passed in here then it is the priority of the calling + * task that is being queried. */ + pxTCB = prvGetTCBFromHandle( xTask ); + uxReturn = pxTCB->uxPriority; + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptState ); + + return uxReturn; + } + +#endif /* INCLUDE_uxTaskPriorityGet */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_vTaskPrioritySet == 1 ) + + void vTaskPrioritySet( TaskHandle_t xTask, + UBaseType_t uxNewPriority ) + { + TCB_t * pxTCB; + UBaseType_t uxCurrentBasePriority, uxPriorityUsedOnEntry; + BaseType_t xYieldRequired = pdFALSE; + + configASSERT( ( uxNewPriority < configMAX_PRIORITIES ) ); + + /* Ensure the new priority is valid. */ + if( uxNewPriority >= ( UBaseType_t ) configMAX_PRIORITIES ) + { + uxNewPriority = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) 1U; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + taskENTER_CRITICAL(); + { + /* If null is passed in here then it is the priority of the calling + * task that is being changed. */ + pxTCB = prvGetTCBFromHandle( xTask ); + + traceTASK_PRIORITY_SET( pxTCB, uxNewPriority ); + + #if ( configUSE_MUTEXES == 1 ) + { + uxCurrentBasePriority = pxTCB->uxBasePriority; + } + #else + { + uxCurrentBasePriority = pxTCB->uxPriority; + } + #endif + + if( uxCurrentBasePriority != uxNewPriority ) + { + /* The priority change may have readied a task of higher + * priority than the calling task. */ + if( uxNewPriority > uxCurrentBasePriority ) + { + if( pxTCB != pxCurrentTCB ) + { + /* The priority of a task other than the currently + * running task is being raised. Is the priority being + * raised above that of the running task? */ + if( uxNewPriority >= pxCurrentTCB->uxPriority ) + { + xYieldRequired = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* The priority of the running task is being raised, + * but the running task must already be the highest + * priority task able to run so no yield is required. */ + } + } + else if( pxTCB == pxCurrentTCB ) + { + /* Setting the priority of the running task down means + * there may now be another task of higher priority that + * is ready to execute. */ + xYieldRequired = pdTRUE; + } + else + { + /* Setting the priority of any other task down does not + * require a yield as the running task must be above the + * new priority of the task being modified. */ + } + + /* Remember the ready list the task might be referenced from + * before its uxPriority member is changed so the + * taskRESET_READY_PRIORITY() macro can function correctly. */ + uxPriorityUsedOnEntry = pxTCB->uxPriority; + + #if ( configUSE_MUTEXES == 1 ) + { + /* Only change the priority being used if the task is not + * currently using an inherited priority. */ + if( pxTCB->uxBasePriority == pxTCB->uxPriority ) + { + pxTCB->uxPriority = uxNewPriority; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* The base priority gets set whatever. */ + pxTCB->uxBasePriority = uxNewPriority; + } + #else /* if ( configUSE_MUTEXES == 1 ) */ + { + pxTCB->uxPriority = uxNewPriority; + } + #endif /* if ( configUSE_MUTEXES == 1 ) */ + + /* Only reset the event list item value if the value is not + * being used for anything else. */ + if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) + { + listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxNewPriority ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* If the task is in the blocked or suspended list we need do + * nothing more than change its priority variable. However, if + * the task is in a ready list it needs to be removed and placed + * in the list appropriate to its new priority. */ + if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE ) + { + /* The task is currently in its ready list - remove before + * adding it to 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 ) + { + BaseType_t x; + + for( x = 0; x < configTASK_NOTIFICATION_ARRAY_ENTRIES; x++ ) + { + if( pxTCB->ucNotifyState[ x ] == taskWAITING_NOTIFICATION ) + { + /* The task was blocked to wait for a notification, but is + * now suspended, so no notification was received. */ + pxTCB->ucNotifyState[ x ] = taskNOT_WAITING_NOTIFICATION; + } + } + } + #endif /* if ( configUSE_TASK_NOTIFICATIONS == 1 ) */ + } + taskEXIT_CRITICAL(); + + if( xSchedulerRunning != pdFALSE ) + { + /* Reset the next expected unblock time in case it referred to the + * task that is now in the Suspended state. */ + taskENTER_CRITICAL(); + { + prvResetNextTaskUnblockTime(); + } + taskEXIT_CRITICAL(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + if( pxTCB == pxCurrentTCB ) + { + if( xSchedulerRunning != pdFALSE ) + { + /* The current task has just been suspended. */ + configASSERT( uxSchedulerSuspended == 0 ); + portYIELD_WITHIN_API(); + } + else + { + /* The scheduler is not running, but the task that was pointed + * to by pxCurrentTCB has just been suspended and pxCurrentTCB + * must be adjusted to point to a different task. */ + if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == uxCurrentNumberOfTasks ) /*lint !e931 Right has no side effect, just volatile. */ + { + /* No other tasks are ready, so set pxCurrentTCB back to + * NULL so when the next task is created pxCurrentTCB will + * be set to point to it no matter what its relative priority + * is. */ + pxCurrentTCB = NULL; + } + else + { + vTaskSwitchContext(); + } + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + +#endif /* INCLUDE_vTaskSuspend */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_vTaskSuspend == 1 ) + + static BaseType_t prvTaskIsTaskSuspended( const TaskHandle_t xTask ) + { + BaseType_t xReturn = pdFALSE; + const TCB_t * const pxTCB = xTask; + + /* Accesses xPendingReadyList so must be called from a critical + * section. */ + + /* It does not make sense to check if the calling task is suspended. */ + configASSERT( xTask ); + + /* Is the task being resumed actually in the suspended list? */ + if( listIS_CONTAINED_WITHIN( &xSuspendedTaskList, &( pxTCB->xStateListItem ) ) != pdFALSE ) + { + /* Has the task already been resumed from within an ISR? */ + if( listIS_CONTAINED_WITHIN( &xPendingReadyList, &( pxTCB->xEventListItem ) ) == pdFALSE ) + { + /* Is it in the suspended list because it is in the Suspended + * state, or because is is blocked with no timeout? */ + if( listIS_CONTAINED_WITHIN( NULL, &( pxTCB->xEventListItem ) ) != pdFALSE ) /*lint !e961. The cast is only redundant when NULL is used. */ + { + xReturn = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xReturn; + } /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */ + +#endif /* INCLUDE_vTaskSuspend */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_vTaskSuspend == 1 ) + + void vTaskResume( TaskHandle_t xTaskToResume ) + { + TCB_t * const pxTCB = xTaskToResume; + + /* It does not make sense to resume the calling task. */ + configASSERT( xTaskToResume ); + + /* The parameter cannot be NULL as it is impossible to resume the + * currently executing task. */ + if( ( pxTCB != pxCurrentTCB ) && ( pxTCB != NULL ) ) + { + taskENTER_CRITICAL(); + { + if( prvTaskIsTaskSuspended( pxTCB ) != pdFALSE ) + { + traceTASK_RESUME( pxTCB ); + + /* The ready list can be accessed even if the scheduler is + * suspended because this is inside a critical section. */ + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); + + /* A higher priority task may have just been resumed. */ + if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) + { + /* This yield may not cause the task just resumed to run, + * but will leave the lists in the correct state for the + * next yield. */ + taskYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + +#endif /* INCLUDE_vTaskSuspend */ + +/*-----------------------------------------------------------*/ + +#if ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) ) + + BaseType_t xTaskResumeFromISR( TaskHandle_t xTaskToResume ) + { + BaseType_t xYieldRequired = pdFALSE; + TCB_t * const pxTCB = xTaskToResume; + UBaseType_t uxSavedInterruptStatus; + + configASSERT( xTaskToResume ); + + /* RTOS ports that support interrupt nesting have the concept of a + * maximum system call (or maximum API call) interrupt priority. + * Interrupts that are above the maximum system call priority are keep + * permanently enabled, even when the RTOS kernel is in a critical section, + * but cannot make any calls to FreeRTOS API functions. If configASSERT() + * is defined in FreeRTOSConfig.h then + * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + * failure if a FreeRTOS API function is called from an interrupt that has + * been assigned a priority above the configured maximum system call + * priority. Only FreeRTOS functions that end in FromISR can be called + * from interrupts that have been assigned a priority at or (logically) + * below the maximum system call interrupt priority. FreeRTOS maintains a + * separate interrupt safe API to ensure interrupt entry is as fast and as + * simple as possible. More information (albeit Cortex-M specific) is + * provided on the following link: + * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + if( prvTaskIsTaskSuspended( pxTCB ) != pdFALSE ) + { + traceTASK_RESUME_FROM_ISR( pxTCB ); + + /* Check the ready lists can be accessed. */ + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + /* Ready lists can be accessed so move the task from the + * suspended list to the ready list directly. */ + if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) + { + xYieldRequired = pdTRUE; + + /* Mark that a yield is pending in case the user is not + * using the return value to initiate a context switch + * from the ISR using portYIELD_FROM_ISR. */ + xYieldPending = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); + } + else + { + /* The delayed or ready lists cannot be accessed so the task + * is held in the pending ready list until the scheduler is + * unsuspended. */ + vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + + return xYieldRequired; + } + +#endif /* ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) ) */ +/*-----------------------------------------------------------*/ + +void vTaskStartScheduler( void ) +{ + BaseType_t xReturn; + + /* Add the idle task at the lowest priority. */ + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + StaticTask_t * pxIdleTaskTCBBuffer = NULL; + StackType_t * pxIdleTaskStackBuffer = NULL; + uint32_t ulIdleTaskStackSize; + + /* The Idle task is created using user provided RAM - obtain the + * address of the RAM then create the idle task. */ + vApplicationGetIdleTaskMemory( &pxIdleTaskTCBBuffer, &pxIdleTaskStackBuffer, &ulIdleTaskStackSize ); + xIdleTaskHandle = xTaskCreateStatic( prvIdleTask, + configIDLE_TASK_NAME, + ulIdleTaskStackSize, + ( void * ) NULL, /*lint !e961. The cast is not redundant for all compilers. */ + portPRIVILEGE_BIT, /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */ + pxIdleTaskStackBuffer, + pxIdleTaskTCBBuffer ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */ + + if( xIdleTaskHandle != NULL ) + { + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + } + } + #else /* if ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ + { + /* The Idle task is being created using dynamically allocated RAM. */ + xReturn = xTaskCreate( prvIdleTask, + configIDLE_TASK_NAME, + configMINIMAL_STACK_SIZE, + ( void * ) NULL, + portPRIVILEGE_BIT, /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */ + &xIdleTaskHandle ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */ + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ + + #if ( configUSE_TIMERS == 1 ) + { + if( xReturn == pdPASS ) + { + xReturn = xTimerCreateTimerTask(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_TIMERS */ + + if( xReturn == pdPASS ) + { + /* freertos_tasks_c_additions_init() should only be called if the user + * definable macro FREERTOS_TASKS_C_ADDITIONS_INIT() is defined, as that is + * the only macro called by the function. */ + #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT + { + freertos_tasks_c_additions_init(); + } + #endif + + /* Interrupts are turned off here, to ensure a tick does not occur + * before or during the call to xPortStartScheduler(). The stacks of + * the created tasks contain a status word with interrupts switched on + * so interrupts will automatically get re-enabled when the first task + * starts to run. */ + portDISABLE_INTERRUPTS(); + + #if ( configUSE_NEWLIB_REENTRANT == 1 ) + { + /* Switch Newlib's _impure_ptr variable to point to the _reent + * structure specific to the task that will run first. + * See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html + * for additional information. */ + _impure_ptr = &( pxCurrentTCB->xNewLib_reent ); + } + #endif /* configUSE_NEWLIB_REENTRANT */ + + xNextTaskUnblockTime = portMAX_DELAY; + xSchedulerRunning = pdTRUE; + xTickCount = ( TickType_t ) configINITIAL_TICK_COUNT; + + /* If configGENERATE_RUN_TIME_STATS is defined then the following + * macro must be defined to configure the timer/counter used to generate + * the run time counter time base. NOTE: If configGENERATE_RUN_TIME_STATS + * is set to 0 and the following line fails to build then ensure you do not + * have portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() defined in your + * FreeRTOSConfig.h file. */ + portCONFIGURE_TIMER_FOR_RUN_TIME_STATS(); + + traceTASK_SWITCHED_IN(); + + /* Setting up the timer tick is hardware specific and thus in the + * portable interface. */ + if( xPortStartScheduler() != pdFALSE ) + { + /* Should not reach here as if the scheduler is running the + * function will not return. */ + } + else + { + /* Should only reach here if a task calls xTaskEndScheduler(). */ + } + } + else + { + /* This line will only be reached if the kernel could not be started, + * because there was not enough FreeRTOS heap to create the idle task + * or the timer task. */ + configASSERT( xReturn != errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY ); + } + + /* Prevent compiler warnings if INCLUDE_xTaskGetIdleTaskHandle is set to 0, + * meaning xIdleTaskHandle is not used anywhere else. */ + ( void ) xIdleTaskHandle; + + /* OpenOCD makes use of uxTopUsedPriority for thread debugging. Prevent uxTopUsedPriority + * from getting optimized out as it is no longer used by the kernel. */ + ( void ) uxTopUsedPriority; +} +/*-----------------------------------------------------------*/ + +void vTaskEndScheduler( void ) +{ + /* Stop the scheduler interrupts and call the portable scheduler end + * routine so the original ISRs can be restored if necessary. The port + * layer must ensure interrupts enable bit is left in the correct state. */ + portDISABLE_INTERRUPTS(); + xSchedulerRunning = pdFALSE; + vPortEndScheduler(); +} +/*----------------------------------------------------------*/ + +void vTaskSuspendAll( void ) +{ + /* A critical section is not required as the variable is of type + * BaseType_t. Please read Richard Barry's reply in the following link to a + * post in the FreeRTOS support forum before reporting this as a bug! - + * https://goo.gl/wu4acr */ + + /* 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 ( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 ) */ + + if( pxCurrentTCB->uxPriority > tskIDLE_PRIORITY ) + { + xReturn = 0; + } + else if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > 1 ) + { + /* There are other idle priority tasks in the ready state. If + * time slicing is used then the very next tick interrupt must be + * processed. */ + xReturn = 0; + } + else if( uxHigherPriorityReadyTasks != pdFALSE ) + { + /* There are tasks in the Ready state that have a priority above the + * idle priority. This path can only be reached if + * configUSE_PREEMPTION is 0. */ + xReturn = 0; + } + else + { + xReturn = xNextTaskUnblockTime - xTickCount; + } + + return xReturn; + } + +#endif /* configUSE_TICKLESS_IDLE */ +/*----------------------------------------------------------*/ + +BaseType_t xTaskResumeAll( void ) +{ + TCB_t * pxTCB = NULL; + BaseType_t xAlreadyYielded = pdFALSE; + + /* If uxSchedulerSuspended is zero then this function does not match a + * previous call to vTaskSuspendAll(). */ + configASSERT( uxSchedulerSuspended ); + + /* It is possible that an ISR caused a task to be removed from an event + * list while the scheduler was suspended. If this was the case then the + * removed task will have been added to the xPendingReadyList. Once the + * scheduler has been resumed it is safe to move all the pending ready + * tasks from this list into their appropriate ready list. */ + taskENTER_CRITICAL(); + { + --uxSchedulerSuspended; + + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + if( uxCurrentNumberOfTasks > ( UBaseType_t ) 0U ) + { + /* Move any readied tasks from the pending list into the + * appropriate ready list. */ + while( listLIST_IS_EMPTY( &xPendingReadyList ) == pdFALSE ) + { + pxTCB = listGET_OWNER_OF_HEAD_ENTRY( ( &xPendingReadyList ) ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + ( 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 ( configGENERATE_RUN_TIME_STATS == 1 ) */ + { + if( pulTotalRunTime != NULL ) + { + *pulTotalRunTime = 0; + } + } + #endif /* if ( configGENERATE_RUN_TIME_STATS == 1 ) */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + ( void ) xTaskResumeAll(); + + return uxTask; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*----------------------------------------------------------*/ + +#if ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) + + TaskHandle_t xTaskGetIdleTaskHandle( void ) + { + /* If xTaskGetIdleTaskHandle() is called before the scheduler has been + * started, then xIdleTaskHandle will be NULL. */ + configASSERT( ( xIdleTaskHandle != NULL ) ); + return xIdleTaskHandle; + } + +#endif /* INCLUDE_xTaskGetIdleTaskHandle */ +/*----------------------------------------------------------*/ + +/* This conditional compilation should use inequality to 0, not equality to 1. + * This is to ensure vTaskStepTick() is available when user defined low power mode + * implementations require configUSE_TICKLESS_IDLE to be set to a value other than + * 1. */ +#if ( configUSE_TICKLESS_IDLE != 0 ) + + void vTaskStepTick( const TickType_t xTicksToJump ) + { + /* Correct the tick count value after a period during which the tick + * was suppressed. Note this does *not* call the tick hook function for + * each stepped tick. */ + configASSERT( ( xTickCount + xTicksToJump ) <= xNextTaskUnblockTime ); + xTickCount += xTicksToJump; + traceINCREASE_TICK_COUNT( xTicksToJump ); + } + +#endif /* configUSE_TICKLESS_IDLE */ +/*----------------------------------------------------------*/ + +BaseType_t xTaskCatchUpTicks( TickType_t xTicksToCatchUp ) +{ + BaseType_t xYieldOccurred; + + /* Must not be called with the scheduler suspended as the implementation + * relies on xPendedTicks being wound down to 0 in xTaskResumeAll(). */ + configASSERT( uxSchedulerSuspended == 0 ); + + /* Use xPendedTicks to mimic xTicksToCatchUp number of ticks occurring when + * the scheduler is suspended so the ticks are executed in xTaskResumeAll(). */ + vTaskSuspendAll(); + xPendedTicks += xTicksToCatchUp; + xYieldOccurred = xTaskResumeAll(); + + return xYieldOccurred; +} +/*----------------------------------------------------------*/ + +#if ( INCLUDE_xTaskAbortDelay == 1 ) + + BaseType_t xTaskAbortDelay( TaskHandle_t xTask ) + { + TCB_t * pxTCB = xTask; + BaseType_t xReturn; + + configASSERT( pxTCB ); + + vTaskSuspendAll(); + { + /* A task can only be prematurely removed from the Blocked state if + * it is actually in the Blocked state. */ + if( eTaskGetState( xTask ) == eBlocked ) + { + xReturn = pdPASS; + + /* Remove the reference to the task from the blocked list. An + * interrupt won't touch the xStateListItem because the + * scheduler is suspended. */ + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + + /* Is the task waiting on an event also? If so remove it from + * the event list too. Interrupts can touch the event list item, + * even though the scheduler is suspended, so a critical section + * is used. */ + taskENTER_CRITICAL(); + { + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) + { + ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); + + /* This lets the task know it was forcibly removed from the + * blocked state so it should not re-evaluate its block time and + * then block again. */ + pxTCB->ucDelayAborted = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + + /* Place the unblocked task into the appropriate ready list. */ + prvAddTaskToReadyList( pxTCB ); + + /* A task being unblocked cannot cause an immediate context + * switch if preemption is turned off. */ + #if ( configUSE_PREEMPTION == 1 ) + { + /* Preemption is on, but a context switch should only be + * performed if the unblocked task has a priority that is + * 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; + *pxTicksToWait = ( TickType_t ) 0; + } + else if( xElapsedTime < *pxTicksToWait ) /*lint !e961 Explicit casting is only redundant with some compilers, whereas others require it to prevent integer conversion errors. */ + { + /* Not a genuine timeout. Adjust parameters for time remaining. */ + *pxTicksToWait -= xElapsedTime; + vTaskInternalSetTimeOutState( pxTimeOut ); + xReturn = pdFALSE; + } + else + { + *pxTicksToWait = ( TickType_t ) 0; + xReturn = pdTRUE; + } + } + taskEXIT_CRITICAL(); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +void vTaskMissedYield( void ) +{ + xYieldPending = pdTRUE; +} +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + UBaseType_t uxTaskGetTaskNumber( TaskHandle_t xTask ) + { + UBaseType_t uxReturn; + TCB_t const * pxTCB; + + if( xTask != NULL ) + { + pxTCB = xTask; + uxReturn = pxTCB->uxTaskNumber; + } + else + { + uxReturn = 0U; + } + + return uxReturn; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + void vTaskSetTaskNumber( TaskHandle_t xTask, + const UBaseType_t uxHandle ) + { + TCB_t * pxTCB; + + if( xTask != NULL ) + { + pxTCB = xTask; + pxTCB->uxTaskNumber = uxHandle; + } + } + +#endif /* configUSE_TRACE_FACILITY */ + +/* + * ----------------------------------------------------------- + * The Idle task. + * ---------------------------------------------------------- + * + * The portTASK_FUNCTION() macro is used to allow port/compiler specific + * language extensions. The equivalent prototype for this function is: + * + * void prvIdleTask( void *pvParameters ); + * + */ +static portTASK_FUNCTION( prvIdleTask, pvParameters ) +{ + /* Stop warnings. */ + ( void ) pvParameters; + + /** THIS IS THE RTOS IDLE TASK - WHICH IS CREATED AUTOMATICALLY WHEN THE + * SCHEDULER IS STARTED. **/ + + /* In case a task that has a secure context deletes itself, in which case + * the idle task is responsible for deleting the task's secure context, if + * any. */ + portALLOCATE_SECURE_CONTEXT( configMINIMAL_SECURE_STACK_SIZE ); + + for( ; ; ) + { + /* See if any tasks have deleted themselves - if so then the idle task + * is responsible for freeing the deleted task's TCB and stack. */ + prvCheckTasksWaitingTermination(); + + #if ( configUSE_PREEMPTION == 0 ) + { + /* If we are not using preemption we keep forcing a task switch to + * see if any other task has become available. If we are using + * preemption we don't need to do this as any task becoming available + * will automatically get the processor anyway. */ + taskYIELD(); + } + #endif /* configUSE_PREEMPTION */ + + #if ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) + { + /* When using preemption tasks of equal priority will be + * timesliced. If a task that is sharing the idle priority is ready + * to run then the idle task should yield before the end of the + * timeslice. + * + * A critical region is not required here as we are just reading from + * the list, and an occasional incorrect value will not matter. If + * the ready list at the idle priority contains more than one task + * then a task other than the idle task is ready to execute. */ + if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > ( UBaseType_t ) 1 ) + { + taskYIELD(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) */ + + #if ( configUSE_IDLE_HOOK == 1 ) + { + extern void vApplicationIdleHook( void ); + + /* Call the user defined function from within the idle task. This + * allows the application designer to add background functionality + * without the overhead of a separate task. + * NOTE: vApplicationIdleHook() MUST NOT, UNDER ANY CIRCUMSTANCES, + * CALL A FUNCTION THAT MIGHT BLOCK. */ + vApplicationIdleHook(); + } + #endif /* configUSE_IDLE_HOOK */ + + /* This conditional compilation should use inequality to 0, not equality + * to 1. This is to ensure portSUPPRESS_TICKS_AND_SLEEP() is called when + * user defined low power mode implementations require + * configUSE_TICKLESS_IDLE to be set to a value other than 1. */ + #if ( configUSE_TICKLESS_IDLE != 0 ) + { + TickType_t xExpectedIdleTime; + + /* It is not desirable to suspend then resume the scheduler on + * each iteration of the idle task. Therefore, a preliminary + * test of the expected idle time is performed without the + * scheduler suspended. The result here is not necessarily + * valid. */ + xExpectedIdleTime = prvGetExpectedIdleTime(); + + if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP ) + { + vTaskSuspendAll(); + { + /* Now the scheduler is suspended, the expected idle + * time can be sampled again, and this time its value can + * be used. */ + configASSERT( xNextTaskUnblockTime >= xTickCount ); + xExpectedIdleTime = prvGetExpectedIdleTime(); + + /* Define the following macro to set xExpectedIdleTime to 0 + * if the application does not want + * portSUPPRESS_TICKS_AND_SLEEP() to be called. */ + configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING( xExpectedIdleTime ); + + if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP ) + { + traceLOW_POWER_IDLE_BEGIN(); + portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ); + traceLOW_POWER_IDLE_END(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + ( void ) xTaskResumeAll(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_TICKLESS_IDLE */ + } +} +/*-----------------------------------------------------------*/ + +#if ( configUSE_TICKLESS_IDLE != 0 ) + + eSleepModeStatus eTaskConfirmSleepModeStatus( void ) + { + /* The idle task exists in addition to the application tasks. */ + const UBaseType_t uxNonApplicationTasks = 1; + eSleepModeStatus eReturn = eStandardSleep; + + /* This function must be called from a critical section. */ + + if( listCURRENT_LIST_LENGTH( &xPendingReadyList ) != 0 ) + { + /* A task was made ready while the scheduler was suspended. */ + eReturn = eAbortSleep; + } + else if( xYieldPending != pdFALSE ) + { + /* A yield was pended while the scheduler was suspended. */ + eReturn = eAbortSleep; + } + else if( xPendedTicks != 0 ) + { + /* A tick interrupt has already occurred but was held pending + * because the scheduler is suspended. */ + eReturn = eAbortSleep; + } + else + { + /* If all the tasks are in the suspended list (which might mean they + * have an infinite block time rather than actually being suspended) + * then it is safe to turn all clocks off and just wait for external + * interrupts. */ + if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == ( uxCurrentNumberOfTasks - uxNonApplicationTasks ) ) + { + eReturn = eNoTasksWaitingTimeout; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + return eReturn; + } + +#endif /* configUSE_TICKLESS_IDLE */ +/*-----------------------------------------------------------*/ + +#if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) + + void vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, + BaseType_t xIndex, + void * pvValue ) + { + TCB_t * pxTCB; + + if( xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS ) + { + pxTCB = prvGetTCBFromHandle( xTaskToSet ); + configASSERT( pxTCB != NULL ); + pxTCB->pvThreadLocalStoragePointers[ xIndex ] = pvValue; + } + } + +#endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS */ +/*-----------------------------------------------------------*/ + +#if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) + + void * pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, + BaseType_t xIndex ) + { + void * pvReturn = NULL; + TCB_t * pxTCB; + + if( xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS ) + { + pxTCB = prvGetTCBFromHandle( xTaskToQuery ); + pvReturn = pxTCB->pvThreadLocalStoragePointers[ xIndex ]; + } + else + { + pvReturn = NULL; + } + + return pvReturn; + } + +#endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS */ +/*-----------------------------------------------------------*/ + +#if ( portUSING_MPU_WRAPPERS == 1 ) + + void vTaskAllocateMPURegions( TaskHandle_t xTaskToModify, + const MemoryRegion_t * const xRegions ) + { + TCB_t * pxTCB; + + /* If null is passed in here then we are modifying the MPU settings of + * the calling task. */ + pxTCB = prvGetTCBFromHandle( xTaskToModify ); + + vPortStoreTaskMPUSettings( &( pxTCB->xMPUSettings ), xRegions, NULL, 0 ); + } + +#endif /* portUSING_MPU_WRAPPERS */ +/*-----------------------------------------------------------*/ + +static void prvInitialiseTaskLists( void ) +{ + UBaseType_t uxPriority; + + for( uxPriority = ( UBaseType_t ) 0U; uxPriority < ( UBaseType_t ) configMAX_PRIORITIES; uxPriority++ ) + { + vListInitialise( &( pxReadyTasksLists[ uxPriority ] ) ); + } + + vListInitialise( &xDelayedTaskList1 ); + vListInitialise( &xDelayedTaskList2 ); + vListInitialise( &xPendingReadyList ); + + #if ( INCLUDE_vTaskDelete == 1 ) + { + vListInitialise( &xTasksWaitingTermination ); + } + #endif /* INCLUDE_vTaskDelete */ + + #if ( INCLUDE_vTaskSuspend == 1 ) + { + vListInitialise( &xSuspendedTaskList ); + } + #endif /* INCLUDE_vTaskSuspend */ + + /* Start with pxDelayedTaskList using list1 and the pxOverflowDelayedTaskList + * using list2. */ + pxDelayedTaskList = &xDelayedTaskList1; + pxOverflowDelayedTaskList = &xDelayedTaskList2; +} +/*-----------------------------------------------------------*/ + +static void prvCheckTasksWaitingTermination( void ) +{ + /** THIS FUNCTION IS CALLED FROM THE RTOS IDLE TASK **/ + + #if ( INCLUDE_vTaskDelete == 1 ) + { + TCB_t * pxTCB; + + /* uxDeletedTasksWaitingCleanUp is used to prevent taskENTER_CRITICAL() + * being called too often in the idle task. */ + while( uxDeletedTasksWaitingCleanUp > ( UBaseType_t ) 0U ) + { + taskENTER_CRITICAL(); + { + pxTCB = listGET_OWNER_OF_HEAD_ENTRY( ( &xTasksWaitingTermination ) ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + --uxCurrentNumberOfTasks; + --uxDeletedTasksWaitingCleanUp; + } + taskEXIT_CRITICAL(); + + prvDeleteTCB( pxTCB ); + } + } + #endif /* INCLUDE_vTaskDelete */ +} +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + void vTaskGetInfo( TaskHandle_t xTask, + TaskStatus_t * pxTaskStatus, + BaseType_t xGetFreeStackSpace, + eTaskState eState ) + { + TCB_t * pxTCB; + + /* xTask is NULL then get the state of the calling task. */ + pxTCB = prvGetTCBFromHandle( xTask ); + + pxTaskStatus->xHandle = ( TaskHandle_t ) pxTCB; + pxTaskStatus->pcTaskName = ( const char * ) &( pxTCB->pcTaskName[ 0 ] ); + pxTaskStatus->uxCurrentPriority = pxTCB->uxPriority; + pxTaskStatus->pxStackBase = pxTCB->pxStack; + pxTaskStatus->xTaskNumber = pxTCB->uxTCBNumber; + + #if ( configUSE_MUTEXES == 1 ) + { + pxTaskStatus->uxBasePriority = pxTCB->uxBasePriority; + } + #else + { + pxTaskStatus->uxBasePriority = 0; + } + #endif + + #if ( configGENERATE_RUN_TIME_STATS == 1 ) + { + pxTaskStatus->ulRunTimeCounter = pxTCB->ulRunTimeCounter; + } + #else + { + pxTaskStatus->ulRunTimeCounter = 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 ) +{ + if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE ) + { + /* The new current delayed list is empty. Set xNextTaskUnblockTime to + * the maximum possible value so it is extremely unlikely that the + * if( xTickCount >= xNextTaskUnblockTime ) test will pass until + * there is an item in the delayed list. */ + xNextTaskUnblockTime = portMAX_DELAY; + } + else + { + /* The new current delayed list is not empty, get the value of + * the item at the head of the delayed list. This is the time at + * which the task at the head of the delayed list should be removed + * from the Blocked state. */ + xNextTaskUnblockTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxDelayedTaskList ); + } +} +/*-----------------------------------------------------------*/ + +#if ( ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) || ( configUSE_MUTEXES == 1 ) ) + + TaskHandle_t xTaskGetCurrentTaskHandle( void ) + { + TaskHandle_t xReturn; + + /* A critical section is not required as this is not called from + * an interrupt and the current TCB will always be the same for any + * individual execution thread. */ + xReturn = pxCurrentTCB; + + return xReturn; + } + +#endif /* ( ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) || ( configUSE_MUTEXES == 1 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + + BaseType_t xTaskGetSchedulerState( void ) + { + BaseType_t xReturn; + + if( xSchedulerRunning == pdFALSE ) + { + xReturn = taskSCHEDULER_NOT_STARTED; + } + else + { + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + xReturn = taskSCHEDULER_RUNNING; + } + else + { + xReturn = taskSCHEDULER_SUSPENDED; + } + } + + return xReturn; + } + +#endif /* ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_MUTEXES == 1 ) + + BaseType_t xTaskPriorityInherit( TaskHandle_t const pxMutexHolder ) + { + TCB_t * const pxMutexHolderTCB = pxMutexHolder; + BaseType_t xReturn = pdFALSE; + + /* If the mutex was given back by an interrupt while the queue was + * locked then the mutex holder might now be NULL. _RB_ Is this still + * needed as interrupts can no longer use mutexes? */ + if( pxMutexHolder != NULL ) + { + /* If the holder of the mutex has a priority below the priority of + * the task attempting to obtain the mutex then it will temporarily + * inherit the priority of the task attempting to obtain the mutex. */ + if( pxMutexHolderTCB->uxPriority < pxCurrentTCB->uxPriority ) + { + /* Adjust the mutex holder state to account for its new + * priority. Only reset the event list item value if the value is + * not being used for anything else. */ + if( ( listGET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) + { + listSET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxCurrentTCB->uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* If the task being modified is in the ready state it will need + * to be moved into a new list. */ + if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ pxMutexHolderTCB->uxPriority ] ), &( pxMutexHolderTCB->xStateListItem ) ) != pdFALSE ) + { + if( uxListRemove( &( pxMutexHolderTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + /* It is known that the task is in its ready list so + * there is no need to check again and the port level + * reset macro can be called directly. */ + portRESET_READY_PRIORITY( pxMutexHolderTCB->uxPriority, uxTopReadyPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Inherit the priority before being moved into the new list. */ + pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority; + prvAddTaskToReadyList( pxMutexHolderTCB ); + } + else + { + /* Just inherit the priority. */ + pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority; + } + + traceTASK_PRIORITY_INHERIT( pxMutexHolderTCB, pxCurrentTCB->uxPriority ); + + /* Inheritance occurred. */ + xReturn = pdTRUE; + } + else + { + if( pxMutexHolderTCB->uxBasePriority < pxCurrentTCB->uxPriority ) + { + /* The base priority of the mutex holder is lower than the + * priority of the task attempting to take the mutex, but the + * current priority of the mutex holder is not lower than the + * priority of the task attempting to take the mutex. + * Therefore the mutex holder must have already inherited a + * priority, but inheritance would have occurred if that had + * not been the case. */ + xReturn = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xReturn; + } + +#endif /* configUSE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_MUTEXES == 1 ) + + BaseType_t xTaskPriorityDisinherit( TaskHandle_t const pxMutexHolder ) + { + TCB_t * const pxTCB = pxMutexHolder; + BaseType_t xReturn = pdFALSE; + + if( pxMutexHolder != NULL ) + { + /* A task can only have an inherited priority if it holds the mutex. + * If the mutex is held by a task then it cannot be given from an + * interrupt, and if a mutex is given by the holding task then it must + * be the running state task. */ + configASSERT( pxTCB == pxCurrentTCB ); + configASSERT( pxTCB->uxMutexesHeld ); + ( pxTCB->uxMutexesHeld )--; + + /* Has the holder of the mutex inherited the priority of another + * task? */ + if( pxTCB->uxPriority != pxTCB->uxBasePriority ) + { + /* Only disinherit if no other mutexes are held. */ + if( pxTCB->uxMutexesHeld == ( UBaseType_t ) 0 ) + { + /* A task can only have an inherited priority if it holds + * the mutex. If the mutex is held by a task then it cannot be + * given from an interrupt, and if a mutex is given by the + * holding task then it must be the running state task. Remove + * the holding task from the ready list. */ + if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + portRESET_READY_PRIORITY( pxTCB->uxPriority, uxTopReadyPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Disinherit the priority before adding the task into the + * new ready list. */ + traceTASK_PRIORITY_DISINHERIT( pxTCB, pxTCB->uxBasePriority ); + pxTCB->uxPriority = pxTCB->uxBasePriority; + + /* Reset the event list item value. It cannot be in use for + * any other purpose if this task is running, and it must be + * running to give back the mutex. */ + listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxTCB->uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + prvAddTaskToReadyList( pxTCB ); + + /* Return true to indicate that a context switch is required. + * This is only actually required in the corner case whereby + * multiple mutexes were held and the mutexes were given back + * in an order different to that in which they were taken. + * If a context switch did not occur when the first mutex was + * returned, even if a task was waiting on it, then a context + * switch should occur when the last mutex is returned whether + * a task is waiting on it or not. */ + xReturn = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xReturn; + } + +#endif /* configUSE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_MUTEXES == 1 ) + + void vTaskPriorityDisinheritAfterTimeout( TaskHandle_t const pxMutexHolder, + UBaseType_t uxHighestPriorityWaitingTask ) + { + TCB_t * const pxTCB = pxMutexHolder; + UBaseType_t uxPriorityUsedOnEntry, uxPriorityToUse; + const UBaseType_t uxOnlyOneMutexHeld = ( UBaseType_t ) 1; + + if( pxMutexHolder != NULL ) + { + /* If pxMutexHolder is not NULL then the holder must hold at least + * one mutex. */ + configASSERT( pxTCB->uxMutexesHeld ); + + /* Determine the priority to which the priority of the task that + * holds the mutex should be set. This will be the greater of the + * holding task's base priority and the priority of the highest + * priority task that is waiting to obtain the mutex. */ + if( pxTCB->uxBasePriority < uxHighestPriorityWaitingTask ) + { + uxPriorityToUse = uxHighestPriorityWaitingTask; + } + else + { + uxPriorityToUse = pxTCB->uxBasePriority; + } + + /* Does the priority need to change? */ + if( pxTCB->uxPriority != uxPriorityToUse ) + { + /* Only disinherit if no other mutexes are held. This is a + * simplification in the priority inheritance implementation. If + * the task that holds the mutex is also holding other mutexes then + * the other mutexes may have caused the priority inheritance. */ + if( pxTCB->uxMutexesHeld == uxOnlyOneMutexHeld ) + { + /* If a task has timed out because it already holds the + * mutex it was trying to obtain then it cannot of inherited + * its own priority. */ + configASSERT( pxTCB != pxCurrentTCB ); + + /* Disinherit the priority, remembering the previous + * priority to facilitate determining the subject task's + * state. */ + traceTASK_PRIORITY_DISINHERIT( pxTCB, uxPriorityToUse ); + uxPriorityUsedOnEntry = pxTCB->uxPriority; + pxTCB->uxPriority = uxPriorityToUse; + + /* Only reset the event list item value if the value is not + * being used for anything else. */ + if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) + { + listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxPriorityToUse ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* If the running task is not the task that holds the mutex + * then the task that holds the mutex could be in either the + * Ready, Blocked or Suspended states. Only remove the task + * from its current state list if it is in the Ready state as + * the task's priority is going to change and there is one + * Ready list per priority. */ + if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE ) + { + if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + /* It is known that the task is in its ready list so + * there is no need to check again and the port level + * reset macro can be called directly. */ + portRESET_READY_PRIORITY( pxTCB->uxPriority, uxTopReadyPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + prvAddTaskToReadyList( pxTCB ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + +#endif /* configUSE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if ( portCRITICAL_NESTING_IN_TCB == 1 ) + + void vTaskEnterCritical( void ) + { + portDISABLE_INTERRUPTS(); + + if( xSchedulerRunning != pdFALSE ) + { + ( pxCurrentTCB->uxCriticalNesting )++; + + /* This is not the interrupt safe version of the enter critical + * function so assert() if it is being called from an interrupt + * context. Only API functions that end in "FromISR" can be used in an + * interrupt. Only assert if the critical nesting count is 1 to + * protect against recursive calls if the assert function also uses a + * critical section. */ + if( pxCurrentTCB->uxCriticalNesting == 1 ) + { + portASSERT_IF_IN_ISR(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + +#endif /* portCRITICAL_NESTING_IN_TCB */ +/*-----------------------------------------------------------*/ + +#if ( portCRITICAL_NESTING_IN_TCB == 1 ) + + void vTaskExitCritical( void ) + { + if( xSchedulerRunning != pdFALSE ) + { + if( pxCurrentTCB->uxCriticalNesting > 0U ) + { + ( pxCurrentTCB->uxCriticalNesting )--; + + if( pxCurrentTCB->uxCriticalNesting == 0U ) + { + portENABLE_INTERRUPTS(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + +#endif /* portCRITICAL_NESTING_IN_TCB */ +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) ) + + static char * prvWriteNameToBuffer( char * pcBuffer, + const char * pcTaskName ) + { + size_t x; + + /* Start by copying the entire string. */ + strcpy( pcBuffer, pcTaskName ); + + /* Pad the end of the string with spaces to ensure columns line up when + * printed out. */ + for( x = strlen( pcBuffer ); x < ( size_t ) ( configMAX_TASK_NAME_LEN - 1 ); x++ ) + { + pcBuffer[ x ] = ' '; + } + + /* Terminate. */ + pcBuffer[ x ] = ( char ) 0x00; + + /* Return the new end of string. */ + return &( pcBuffer[ x ] ); + } + +#endif /* ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) */ +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + + void vTaskList( char * pcWriteBuffer ) + { + TaskStatus_t * pxTaskStatusArray; + UBaseType_t uxArraySize, x; + char cStatus; + + /* + * PLEASE NOTE: + * + * This function is provided for convenience only, and is used by many + * of the demo applications. Do not consider it to be part of the + * scheduler. + * + * vTaskList() calls uxTaskGetSystemState(), then formats part of the + * uxTaskGetSystemState() output into a human readable table that + * displays task names, states 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 ulTaskGenericNotifyTake( UBaseType_t uxIndexToWait, + BaseType_t xClearCountOnExit, + TickType_t xTicksToWait ) + { + uint32_t ulReturn; + + configASSERT( uxIndexToWait < configTASK_NOTIFICATION_ARRAY_ENTRIES ); + + taskENTER_CRITICAL(); + { + /* Only block if the notification count is not already non-zero. */ + if( pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ] == 0UL ) + { + /* Mark this task as waiting for a notification. */ + pxCurrentTCB->ucNotifyState[ uxIndexToWait ] = taskWAITING_NOTIFICATION; + + if( xTicksToWait > ( TickType_t ) 0 ) + { + prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); + traceTASK_NOTIFY_TAKE_BLOCK( uxIndexToWait ); + + /* All ports are written to allow a yield in a critical + * section (some will yield immediately, others wait until the + * critical section exits) - but it is not something that + * application code should ever do. */ + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + + taskENTER_CRITICAL(); + { + traceTASK_NOTIFY_TAKE( uxIndexToWait ); + ulReturn = pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ]; + + if( ulReturn != 0UL ) + { + if( xClearCountOnExit != pdFALSE ) + { + pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ] = 0UL; + } + else + { + pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ] = ulReturn - ( uint32_t ) 1; + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + pxCurrentTCB->ucNotifyState[ uxIndexToWait ] = taskNOT_WAITING_NOTIFICATION; + } + taskEXIT_CRITICAL(); + + return ulReturn; + } + +#endif /* configUSE_TASK_NOTIFICATIONS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TASK_NOTIFICATIONS == 1 ) + + BaseType_t xTaskGenericNotifyWait( UBaseType_t uxIndexToWait, + uint32_t ulBitsToClearOnEntry, + uint32_t ulBitsToClearOnExit, + uint32_t * pulNotificationValue, + TickType_t xTicksToWait ) + { + BaseType_t xReturn; + + configASSERT( uxIndexToWait < configTASK_NOTIFICATION_ARRAY_ENTRIES ); + + taskENTER_CRITICAL(); + { + /* Only block if a notification is not already pending. */ + if( pxCurrentTCB->ucNotifyState[ uxIndexToWait ] != taskNOTIFICATION_RECEIVED ) + { + /* Clear bits in the task's notification value as bits may get + * set by the notifying task or interrupt. This can be used to + * clear the value to zero. */ + pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ] &= ~ulBitsToClearOnEntry; + + /* Mark this task as waiting for a notification. */ + pxCurrentTCB->ucNotifyState[ uxIndexToWait ] = taskWAITING_NOTIFICATION; + + if( xTicksToWait > ( TickType_t ) 0 ) + { + prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); + traceTASK_NOTIFY_WAIT_BLOCK( uxIndexToWait ); + + /* All ports are written to allow a yield in a critical + * section (some will yield immediately, others wait until the + * critical section exits) - but it is not something that + * application code should ever do. */ + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + + taskENTER_CRITICAL(); + { + traceTASK_NOTIFY_WAIT( uxIndexToWait ); + + if( pulNotificationValue != NULL ) + { + /* Output the current notification value, which may or may not + * have changed. */ + *pulNotificationValue = pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ]; + } + + /* If ucNotifyValue is set then either the task never entered the + * blocked state (because a notification was already pending) or the + * task unblocked because of a notification. Otherwise the task + * unblocked because of a timeout. */ + if( pxCurrentTCB->ucNotifyState[ uxIndexToWait ] != taskNOTIFICATION_RECEIVED ) + { + /* A notification was not received. */ + xReturn = pdFALSE; + } + else + { + /* A notification was already pending or a notification was + * received while the task was waiting. */ + pxCurrentTCB->ulNotifiedValue[ uxIndexToWait ] &= ~ulBitsToClearOnExit; + xReturn = pdTRUE; + } + + pxCurrentTCB->ucNotifyState[ uxIndexToWait ] = taskNOT_WAITING_NOTIFICATION; + } + taskEXIT_CRITICAL(); + + return xReturn; + } + +#endif /* configUSE_TASK_NOTIFICATIONS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TASK_NOTIFICATIONS == 1 ) + + BaseType_t xTaskGenericNotify( TaskHandle_t xTaskToNotify, + UBaseType_t uxIndexToNotify, + uint32_t ulValue, + eNotifyAction eAction, + uint32_t * pulPreviousNotificationValue ) + { + TCB_t * pxTCB; + BaseType_t xReturn = pdPASS; + uint8_t ucOriginalNotifyState; + + configASSERT( uxIndexToNotify < configTASK_NOTIFICATION_ARRAY_ENTRIES ); + configASSERT( xTaskToNotify ); + pxTCB = xTaskToNotify; + + taskENTER_CRITICAL(); + { + if( pulPreviousNotificationValue != NULL ) + { + *pulPreviousNotificationValue = pxTCB->ulNotifiedValue[ uxIndexToNotify ]; + } + + ucOriginalNotifyState = pxTCB->ucNotifyState[ uxIndexToNotify ]; + + pxTCB->ucNotifyState[ uxIndexToNotify ] = taskNOTIFICATION_RECEIVED; + + switch( eAction ) + { + case eSetBits: + pxTCB->ulNotifiedValue[ uxIndexToNotify ] |= ulValue; + break; + + case eIncrement: + ( pxTCB->ulNotifiedValue[ uxIndexToNotify ] )++; + break; + + case eSetValueWithOverwrite: + pxTCB->ulNotifiedValue[ uxIndexToNotify ] = ulValue; + break; + + case eSetValueWithoutOverwrite: + + if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED ) + { + pxTCB->ulNotifiedValue[ uxIndexToNotify ] = ulValue; + } + else + { + /* The value could not be written to the task. */ + xReturn = pdFAIL; + } + + break; + + case eNoAction: + + /* The task is being notified without its notify value being + * updated. */ + break; + + default: + + /* Should not get here if all enums are handled. + * Artificially force an assert by testing a value the + * compiler can't assume is const. */ + configASSERT( xTickCount == ( TickType_t ) 0 ); + + break; + } + + traceTASK_NOTIFY( uxIndexToNotify ); + + /* If the task is in the blocked state specifically to wait for a + * notification then unblock it now. */ + if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) + { + ( 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, + UBaseType_t uxIndexToNotify, + uint32_t ulValue, + eNotifyAction eAction, + uint32_t * pulPreviousNotificationValue, + BaseType_t * pxHigherPriorityTaskWoken ) + { + TCB_t * pxTCB; + uint8_t ucOriginalNotifyState; + BaseType_t xReturn = pdPASS; + UBaseType_t uxSavedInterruptStatus; + + configASSERT( xTaskToNotify ); + configASSERT( uxIndexToNotify < configTASK_NOTIFICATION_ARRAY_ENTRIES ); + + /* RTOS ports that support interrupt nesting have the concept of a + * maximum system call (or maximum API call) interrupt priority. + * Interrupts that are above the maximum system call priority are keep + * permanently enabled, even when the RTOS kernel is in a critical section, + * but cannot make any calls to FreeRTOS API functions. If configASSERT() + * is defined in FreeRTOSConfig.h then + * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + * failure if a FreeRTOS API function is called from an interrupt that has + * been assigned a priority above the configured maximum system call + * priority. Only FreeRTOS functions that end in FromISR can be called + * from interrupts that have been assigned a priority at or (logically) + * below the maximum system call interrupt priority. FreeRTOS maintains a + * separate interrupt safe API to ensure interrupt entry is as fast and as + * simple as possible. More information (albeit Cortex-M specific) is + * provided on the following link: + * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + pxTCB = xTaskToNotify; + + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + if( pulPreviousNotificationValue != NULL ) + { + *pulPreviousNotificationValue = pxTCB->ulNotifiedValue[ uxIndexToNotify ]; + } + + ucOriginalNotifyState = pxTCB->ucNotifyState[ uxIndexToNotify ]; + pxTCB->ucNotifyState[ uxIndexToNotify ] = taskNOTIFICATION_RECEIVED; + + switch( eAction ) + { + case eSetBits: + pxTCB->ulNotifiedValue[ uxIndexToNotify ] |= ulValue; + break; + + case eIncrement: + ( pxTCB->ulNotifiedValue[ uxIndexToNotify ] )++; + break; + + case eSetValueWithOverwrite: + pxTCB->ulNotifiedValue[ uxIndexToNotify ] = ulValue; + break; + + case eSetValueWithoutOverwrite: + + if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED ) + { + pxTCB->ulNotifiedValue[ uxIndexToNotify ] = ulValue; + } + else + { + /* The value could not be written to the task. */ + xReturn = pdFAIL; + } + + break; + + case eNoAction: + + /* The task is being notified without its notify value being + * updated. */ + break; + + default: + + /* Should not get here if all enums are handled. + * Artificially force an assert by testing a value the + * compiler can't assume is const. */ + configASSERT( xTickCount == ( TickType_t ) 0 ); + break; + } + + traceTASK_NOTIFY_FROM_ISR( uxIndexToNotify ); + + /* If the task is in the blocked state specifically to wait for a + * notification then unblock it now. */ + if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) + { + /* The task should not have been on an event list. */ + configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); + + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + ( 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 vTaskGenericNotifyGiveFromISR( TaskHandle_t xTaskToNotify, + UBaseType_t uxIndexToNotify, + BaseType_t * pxHigherPriorityTaskWoken ) + { + TCB_t * pxTCB; + uint8_t ucOriginalNotifyState; + UBaseType_t uxSavedInterruptStatus; + + configASSERT( xTaskToNotify ); + configASSERT( uxIndexToNotify < configTASK_NOTIFICATION_ARRAY_ENTRIES ); + + /* RTOS ports that support interrupt nesting have the concept of a + * maximum system call (or maximum API call) interrupt priority. + * Interrupts that are above the maximum system call priority are keep + * permanently enabled, even when the RTOS kernel is in a critical section, + * but cannot make any calls to FreeRTOS API functions. If configASSERT() + * is defined in FreeRTOSConfig.h then + * portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + * failure if a FreeRTOS API function is called from an interrupt that has + * been assigned a priority above the configured maximum system call + * priority. Only FreeRTOS functions that end in FromISR can be called + * from interrupts that have been assigned a priority at or (logically) + * below the maximum system call interrupt priority. FreeRTOS maintains a + * separate interrupt safe API to ensure interrupt entry is as fast and as + * simple as possible. More information (albeit Cortex-M specific) is + * provided on the following link: + * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + pxTCB = xTaskToNotify; + + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + ucOriginalNotifyState = pxTCB->ucNotifyState[ uxIndexToNotify ]; + pxTCB->ucNotifyState[ uxIndexToNotify ] = taskNOTIFICATION_RECEIVED; + + /* 'Giving' is equivalent to incrementing a count in a counting + * semaphore. */ + ( pxTCB->ulNotifiedValue[ uxIndexToNotify ] )++; + + traceTASK_NOTIFY_GIVE_FROM_ISR( uxIndexToNotify ); + + /* If the task is in the blocked state specifically to wait for a + * notification then unblock it now. */ + if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) + { + /* The task should not have been on an event list. */ + configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); + + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + ( 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 xTaskGenericNotifyStateClear( TaskHandle_t xTask, + UBaseType_t uxIndexToClear ) + { + TCB_t * pxTCB; + BaseType_t xReturn; + + configASSERT( uxIndexToClear < configTASK_NOTIFICATION_ARRAY_ENTRIES ); + + /* If null is passed in here then it is the calling task that is having + * its notification state cleared. */ + pxTCB = prvGetTCBFromHandle( xTask ); + + taskENTER_CRITICAL(); + { + if( pxTCB->ucNotifyState[ uxIndexToClear ] == taskNOTIFICATION_RECEIVED ) + { + pxTCB->ucNotifyState[ uxIndexToClear ] = taskNOT_WAITING_NOTIFICATION; + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + } + } + taskEXIT_CRITICAL(); + + return xReturn; + } + +#endif /* configUSE_TASK_NOTIFICATIONS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TASK_NOTIFICATIONS == 1 ) + + uint32_t ulTaskGenericNotifyValueClear( TaskHandle_t xTask, + UBaseType_t uxIndexToClear, + uint32_t ulBitsToClear ) + { + TCB_t * pxTCB; + uint32_t ulReturn; + + /* If null is passed in here then it is the calling task that is having + * its notification state cleared. */ + pxTCB = prvGetTCBFromHandle( xTask ); + + taskENTER_CRITICAL(); + { + /* Return the notification as it was before the bits were cleared, + * then clear the bit mask. */ + ulReturn = pxTCB->ulNotifiedValue[ uxIndexToClear ]; + pxTCB->ulNotifiedValue[ uxIndexToClear ] &= ~ulBitsToClear; + } + taskEXIT_CRITICAL(); + + return ulReturn; + } + +#endif /* configUSE_TASK_NOTIFICATIONS */ +/*-----------------------------------------------------------*/ + +#if ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) ) + + 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 /* if ( configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H == 1 ) */ diff --git a/examples/stm32/freertos-kernel/timers.c b/examples/stm32/freertos-kernel/timers.c new file mode 100644 index 00000000..eb422969 --- /dev/null +++ b/examples/stm32/freertos-kernel/timers.c @@ -0,0 +1,1144 @@ +/* + * FreeRTOS Kernel V10.4.3 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + +/* Standard includes. */ +#include + +/* 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 */ + +/*-----------------------------------------------------------*/ + +/* + * 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 /* if ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ + { + xReturn = xTaskCreate( prvTimerTask, + configTIMER_SERVICE_TASK_NAME, + configTIMER_TASK_STACK_DEPTH, + NULL, + ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, + &xTimerTaskHandle ); + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + configASSERT( xReturn ); + return xReturn; + } +/*-----------------------------------------------------------*/ + + #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + + TimerHandle_t xTimerCreate( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction ) + { + Timer_t * pxNewTimer; + + pxNewTimer = ( Timer_t * ) pvPortMalloc( sizeof( Timer_t ) ); /*lint !e9087 !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack, and the first member of Timer_t is always a pointer to the timer's mame. */ + + if( pxNewTimer != NULL ) + { + /* Status is thus far zero as the timer is not created statically + * and has not been started. The auto-reload bit may get set in + * prvInitialiseNewTimer. */ + pxNewTimer->ucStatus = 0x00; + prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer ); + } + + return pxNewTimer; + } + + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + + #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) + + TimerHandle_t xTimerCreateStatic( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction, + StaticTimer_t * pxTimerBuffer ) + { + Timer_t * pxNewTimer; + + #if ( configASSERT_DEFINED == 1 ) + { + /* Sanity check that the size of the structure used to declare a + * variable of type StaticTimer_t equals the size of the real timer + * structure. */ + volatile size_t xSize = sizeof( StaticTimer_t ); + configASSERT( xSize == sizeof( Timer_t ) ); + ( void ) xSize; /* Keeps lint quiet when configASSERT() is not defined. */ + } + #endif /* configASSERT_DEFINED */ + + /* A pointer to a StaticTimer_t structure MUST be provided, use it. */ + configASSERT( pxTimerBuffer ); + pxNewTimer = ( Timer_t * ) pxTimerBuffer; /*lint !e740 !e9087 StaticTimer_t is a pointer to a Timer_t, so guaranteed to be aligned and sized correctly (checked by an assert()), so this is safe. */ + + if( pxNewTimer != NULL ) + { + /* Timers can be created statically or dynamically so note this + * timer was created statically in case it is later deleted. The + * auto-reload bit may get set in prvInitialiseNewTimer(). */ + pxNewTimer->ucStatus = tmrSTATUS_IS_STATICALLY_ALLOCATED; + + prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer ); + } + + return pxNewTimer; + } + + #endif /* configSUPPORT_STATIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + + static void prvInitialiseNewTimer( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction, + Timer_t * pxNewTimer ) + { + /* 0 is not a valid value for xTimerPeriodInTicks. */ + configASSERT( ( xTimerPeriodInTicks > 0 ) ); + + 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 ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) */ + { + /* If dynamic allocation is not enabled, the memory + * could not have been dynamically allocated. So there is + * no need to free the memory - just mark the timer as + * "not active". */ + pxTimer->ucStatus &= ~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. */ + PRIVILEGED_DATA static StaticQueue_t xStaticTimerQueue; /*lint !e956 Ok to declare in this manner to prevent additional conditional compilation guards in other locations. */ + PRIVILEGED_DATA static uint8_t ucStaticTimerQueueStorage[ ( size_t ) configTIMER_QUEUE_LENGTH * sizeof( DaemonTaskMessage_t ) ]; /*lint !e956 Ok to declare in this manner to prevent additional conditional compilation guards in other locations. */ + + xTimerQueue = xQueueCreateStatic( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, ( UBaseType_t ) sizeof( DaemonTaskMessage_t ), &( ucStaticTimerQueueStorage[ 0 ] ), &xStaticTimerQueue ); + } + #else + { + xTimerQueue = xQueueCreate( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, sizeof( DaemonTaskMessage_t ) ); + } + #endif /* if ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ + + #if ( configQUEUE_REGISTRY_SIZE > 0 ) + { + if( xTimerQueue != NULL ) + { + vQueueAddToRegistry( xTimerQueue, "TmrQ" ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configQUEUE_REGISTRY_SIZE */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + } +/*-----------------------------------------------------------*/ + + BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer ) + { + BaseType_t xReturn; + Timer_t * pxTimer = xTimer; + + configASSERT( xTimer ); + + /* Is the timer in the list of active timers? */ + taskENTER_CRITICAL(); + { + if( ( pxTimer->ucStatus & tmrSTATUS_IS_ACTIVE ) == 0 ) + { + xReturn = pdFALSE; + } + else + { + xReturn = pdTRUE; + } + } + taskEXIT_CRITICAL(); + + return xReturn; + } /*lint !e818 Can't be pointer to const due to the typedef. */ +/*-----------------------------------------------------------*/ + + void * pvTimerGetTimerID( const TimerHandle_t xTimer ) + { + Timer_t * const pxTimer = xTimer; + void * pvReturn; + + configASSERT( xTimer ); + + taskENTER_CRITICAL(); + { + pvReturn = pxTimer->pvTimerID; + } + taskEXIT_CRITICAL(); + + return pvReturn; + } +/*-----------------------------------------------------------*/ + + void vTimerSetTimerID( TimerHandle_t xTimer, + void * pvNewID ) + { + Timer_t * const pxTimer = xTimer; + + configASSERT( xTimer ); + + taskENTER_CRITICAL(); + { + pxTimer->pvTimerID = pvNewID; + } + taskEXIT_CRITICAL(); + } +/*-----------------------------------------------------------*/ + + #if ( INCLUDE_xTimerPendFunctionCall == 1 ) + + BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, + void * pvParameter1, + uint32_t ulParameter2, + BaseType_t * pxHigherPriorityTaskWoken ) + { + DaemonTaskMessage_t xMessage; + BaseType_t xReturn; + + /* Complete the message with the function parameters and post it to the + * daemon task. */ + xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR; + xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend; + xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1; + xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2; + + xReturn = xQueueSendFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken ); + + tracePEND_FUNC_CALL_FROM_ISR( xFunctionToPend, pvParameter1, ulParameter2, xReturn ); + + return xReturn; + } + + #endif /* INCLUDE_xTimerPendFunctionCall */ +/*-----------------------------------------------------------*/ + + #if ( INCLUDE_xTimerPendFunctionCall == 1 ) + + BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, + void * pvParameter1, + uint32_t ulParameter2, + TickType_t xTicksToWait ) + { + DaemonTaskMessage_t xMessage; + BaseType_t xReturn; + + /* This function can only be called after a timer has been created or + * after the scheduler has been started because, until then, the timer + * queue does not exist. */ + configASSERT( xTimerQueue ); + + /* Complete the message with the function parameters and post it to the + * daemon task. */ + xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK; + xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend; + xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1; + xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2; + + xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait ); + + tracePEND_FUNC_CALL( xFunctionToPend, pvParameter1, ulParameter2, xReturn ); + + return xReturn; + } + + #endif /* INCLUDE_xTimerPendFunctionCall */ +/*-----------------------------------------------------------*/ + + #if ( configUSE_TRACE_FACILITY == 1 ) + + UBaseType_t uxTimerGetTimerNumber( TimerHandle_t xTimer ) + { + return ( ( Timer_t * ) xTimer )->uxTimerNumber; + } + + #endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + + #if ( configUSE_TRACE_FACILITY == 1 ) + + void vTimerSetTimerNumber( TimerHandle_t xTimer, + UBaseType_t uxTimerNumber ) + { + ( ( Timer_t * ) xTimer )->uxTimerNumber = uxTimerNumber; + } + + #endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +/* This entire source file will be skipped if the application is not configured + * to include software timer functionality. If you want to include software timer + * functionality then ensure configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */ +#endif /* configUSE_TIMERS == 1 */ diff --git a/examples/stm32/freertos-tcp/FreeRTOS_ARP.c b/examples/stm32/freertos-tcp/FreeRTOS_ARP.c new file mode 100644 index 00000000..91baca8a --- /dev/null +++ b/examples/stm32/freertos-tcp/FreeRTOS_ARP.c @@ -0,0 +1,951 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +/** + * @file FreeRTOS_ARP.c + * @brief Implements the Address Resolution Protocol for the FreeRTOS+TCP network stack. + */ + +/* Standard includes. */ +#include +#include + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" +#include "semphr.h" + +/* FreeRTOS+TCP includes. */ +#include "FreeRTOS_IP.h" +#include "FreeRTOS_Sockets.h" +#include "FreeRTOS_IP_Private.h" +#include "FreeRTOS_ARP.h" +#include "FreeRTOS_UDP_IP.h" +#include "FreeRTOS_DHCP.h" +#if ( ipconfigUSE_LLMNR == 1 ) + #include "FreeRTOS_DNS.h" +#endif /* ipconfigUSE_LLMNR */ +#include "NetworkBufferManagement.h" +#include "NetworkInterface.h" + +/** @brief When the age of an entry in the ARP table reaches this value (it counts down + * to zero, so this is an old entry) an ARP request will be sent to see if the + * entry is still valid and can therefore be refreshed. */ +#define arpMAX_ARP_AGE_BEFORE_NEW_ARP_REQUEST ( 3 ) + +/** @brief The time between gratuitous ARPs. */ +#ifndef arpGRATUITOUS_ARP_PERIOD + #define arpGRATUITOUS_ARP_PERIOD ( pdMS_TO_TICKS( 20000U ) ) +#endif + +/*-----------------------------------------------------------*/ + +/* + * Lookup an MAC address in the ARP cache from the IP address. + */ +static eARPLookupResult_t prvCacheLookup( uint32_t ulAddressToLookup, + MACAddress_t * const pxMACAddress ); + +/*-----------------------------------------------------------*/ + +/** @brief The ARP cache. */ +_static ARPCacheRow_t xARPCache[ ipconfigARP_CACHE_ENTRIES ]; + +/** @brief The time at which the last gratuitous ARP was sent. Gratuitous ARPs are used + * to ensure ARP tables are up to date and to detect IP address conflicts. */ +static TickType_t xLastGratuitousARPTime = ( TickType_t ) 0; + +/* + * IP-clash detection is currently only used internally. When DHCP doesn't respond, the + * driver can try out a random LinkLayer IP address (169.254.x.x). It will send out a + * gratuitous ARP message and, after a period of time, check the variables here below: + */ +#if ( ipconfigARP_USE_CLASH_DETECTION != 0 ) + /* Becomes non-zero if another device responded to a gratuitous ARP message. */ + BaseType_t xARPHadIPClash; + /* MAC-address of the other device containing the same IP-address. */ + MACAddress_t xARPClashMacAddress; +#endif /* ipconfigARP_USE_CLASH_DETECTION */ + +/*-----------------------------------------------------------*/ + +/** + * @brief Process the ARP packets. + * + * @param[in] pxARPFrame: The ARP Frame (the ARP packet). + * + * @return An enum which says whether to return the frame or to release it. + */ +eFrameProcessingResult_t eARPProcessPacket( ARPPacket_t * const pxARPFrame ) +{ + eFrameProcessingResult_t eReturn = eReleaseBuffer; + ARPHeader_t * pxARPHeader; + uint32_t ulTargetProtocolAddress, ulSenderProtocolAddress; +/* memcpy() helper variables for MISRA Rule 21.15 compliance*/ + const void * pvCopySource; + void * pvCopyDest; + + pxARPHeader = &( pxARPFrame->xARPHeader ); + + /* The field ulSenderProtocolAddress is badly aligned, copy byte-by-byte. */ + + /* + * Use helper variables for memcpy() to remain + * compliant with MISRA Rule 21.15. These should be + * optimized away. + */ + pvCopySource = pxARPHeader->ucSenderProtocolAddress; + pvCopyDest = &ulSenderProtocolAddress; + ( void ) memcpy( pvCopyDest, pvCopySource, sizeof( ulSenderProtocolAddress ) ); + /* The field ulTargetProtocolAddress is well-aligned, a 32-bits copy. */ + ulTargetProtocolAddress = pxARPHeader->ulTargetProtocolAddress; + + traceARP_PACKET_RECEIVED(); + + /* Don't do anything if the local IP address is zero because + * that means a DHCP request has not completed. */ + if( *ipLOCAL_IP_ADDRESS_POINTER != 0UL ) + { + switch( pxARPHeader->usOperation ) + { + case ipARP_REQUEST: + + /* The packet contained an ARP request. Was it for the IP + * address of the node running this code? */ + if( ulTargetProtocolAddress == *ipLOCAL_IP_ADDRESS_POINTER ) + { + iptraceSENDING_ARP_REPLY( ulSenderProtocolAddress ); + + /* The request is for the address of this node. Add the + * entry into the ARP cache, or refresh the entry if it + * already exists. */ + vARPRefreshCacheEntry( &( pxARPHeader->xSenderHardwareAddress ), ulSenderProtocolAddress ); + + /* Generate a reply payload in the same buffer. */ + pxARPHeader->usOperation = ( uint16_t ) ipARP_REPLY; + + if( ulTargetProtocolAddress == ulSenderProtocolAddress ) + { + /* A double IP address is detected! */ + /* Give the sources MAC address the value of the broadcast address, will be swapped later */ + + /* + * Use helper variables for memcpy() to remain + * compliant with MISRA Rule 21.15. These should be + * optimized away. + */ + pvCopySource = xBroadcastMACAddress.ucBytes; + pvCopyDest = pxARPFrame->xEthernetHeader.xSourceAddress.ucBytes; + ( void ) memcpy( pvCopyDest, pvCopySource, sizeof( xBroadcastMACAddress ) ); + + ( void ) memset( pxARPHeader->xTargetHardwareAddress.ucBytes, 0, sizeof( MACAddress_t ) ); + pxARPHeader->ulTargetProtocolAddress = 0UL; + } + else + { + /* + * Use helper variables for memcpy() to remain + * compliant with MISRA Rule 21.15. These should be + * optimized away. + */ + pvCopySource = pxARPHeader->xSenderHardwareAddress.ucBytes; + pvCopyDest = pxARPHeader->xTargetHardwareAddress.ucBytes; + ( void ) memcpy( pvCopyDest, pvCopySource, sizeof( MACAddress_t ) ); + pxARPHeader->ulTargetProtocolAddress = ulSenderProtocolAddress; + } + + /* + * Use helper variables for memcpy() to remain + * compliant with MISRA Rule 21.15. These should be + * optimized away. + */ + pvCopySource = ipLOCAL_MAC_ADDRESS; + pvCopyDest = pxARPHeader->xSenderHardwareAddress.ucBytes; + ( void ) memcpy( pvCopyDest, pvCopySource, sizeof( MACAddress_t ) ); + pvCopySource = ipLOCAL_IP_ADDRESS_POINTER; + pvCopyDest = pxARPHeader->ucSenderProtocolAddress; + ( void ) memcpy( pvCopyDest, pvCopySource, sizeof( pxARPHeader->ucSenderProtocolAddress ) ); + + eReturn = eReturnEthernetFrame; + } + + break; + + case ipARP_REPLY: + iptracePROCESSING_RECEIVED_ARP_REPLY( ulTargetProtocolAddress ); + vARPRefreshCacheEntry( &( pxARPHeader->xSenderHardwareAddress ), ulSenderProtocolAddress ); + /* Process received ARP frame to see if there is a clash. */ + #if ( ipconfigARP_USE_CLASH_DETECTION != 0 ) + { + if( ulSenderProtocolAddress == *ipLOCAL_IP_ADDRESS_POINTER ) + { + xARPHadIPClash = pdTRUE; + /* Remember the MAC-address of the other device which has the same IP-address. */ + ( void ) memcpy( xARPClashMacAddress.ucBytes, pxARPHeader->xSenderHardwareAddress.ucBytes, sizeof( xARPClashMacAddress.ucBytes ) ); + } + } + #endif /* ipconfigARP_USE_CLASH_DETECTION */ + break; + + default: + /* Invalid. */ + break; + } + } + + return eReturn; +} +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_ARP_REMOVE_ENTRY != 0 ) + +/** + * @brief Remove an ARP cache entry that matches with .pxMACAddress. + * + * @param[in] pxMACAddress: Pointer to the MAC address whose entry shall + * be removed.. + * @return When the entry was found and remove: the IP-address, otherwise zero. + */ + uint32_t ulARPRemoveCacheEntryByMac( const MACAddress_t * pxMACAddress ) + { + BaseType_t x; + uint32_t lResult = 0; + + configASSERT( pxMACAddress != NULL ); + + /* For each entry in the ARP cache table. */ + for( x = 0; x < ipconfigARP_CACHE_ENTRIES; x++ ) + { + if( ( memcmp( xARPCache[ x ].xMACAddress.ucBytes, pxMACAddress->ucBytes, sizeof( pxMACAddress->ucBytes ) ) == 0 ) ) + { + lResult = xARPCache[ x ].ulIPAddress; + ( void ) memset( &xARPCache[ x ], 0, sizeof( xARPCache[ x ] ) ); + break; + } + } + + return lResult; + } + +#endif /* ipconfigUSE_ARP_REMOVE_ENTRY != 0 */ +/*-----------------------------------------------------------*/ + +/** + * @brief Add/update the ARP cache entry MAC-address to IP-address mapping. + * + * @param[in] pxMACAddress: Pointer to the MAC address whose mapping is being + * updated. + * @param[in] ulIPAddress: 32-bit representation of the IP-address whose mapping + * is being updated. + */ +void vARPRefreshCacheEntry( const MACAddress_t * pxMACAddress, + const uint32_t ulIPAddress ) +{ + BaseType_t x = 0; + BaseType_t xIpEntry = -1; + BaseType_t xMacEntry = -1; + BaseType_t xUseEntry = 0; + uint8_t ucMinAgeFound = 0U; + + #if ( ipconfigARP_STORES_REMOTE_ADDRESSES == 0 ) + + /* Only process the IP address if it is on the local network. + * Unless: when '*ipLOCAL_IP_ADDRESS_POINTER' equals zero, the IP-address + * and netmask are still unknown. */ + if( ( ( ulIPAddress & xNetworkAddressing.ulNetMask ) == ( ( *ipLOCAL_IP_ADDRESS_POINTER ) & xNetworkAddressing.ulNetMask ) ) || + ( *ipLOCAL_IP_ADDRESS_POINTER == 0UL ) ) + #else + + /* If ipconfigARP_STORES_REMOTE_ADDRESSES is non-zero, IP addresses with + * a different netmask will also be stored. After when replying to a UDP + * message from a different netmask, the IP address can be looped up and a + * reply sent. This option is useful for systems with multiple gateways, + * the reply will surely arrive. If ipconfigARP_STORES_REMOTE_ADDRESSES is + * zero the the gateway address is the only option. */ + + if( pdTRUE ) + #endif + { + /* Start with the maximum possible number. */ + ucMinAgeFound--; + + /* For each entry in the ARP cache table. */ + for( x = 0; x < ipconfigARP_CACHE_ENTRIES; x++ ) + { + BaseType_t xMatchingMAC; + + if( pxMACAddress != NULL ) + { + if( memcmp( xARPCache[ x ].xMACAddress.ucBytes, pxMACAddress->ucBytes, sizeof( pxMACAddress->ucBytes ) ) == 0 ) + { + xMatchingMAC = pdTRUE; + } + else + { + xMatchingMAC = pdFALSE; + } + } + else + { + xMatchingMAC = pdFALSE; + } + + /* Does this line in the cache table hold an entry for the IP + * address being queried? */ + if( xARPCache[ x ].ulIPAddress == ulIPAddress ) + { + if( pxMACAddress == NULL ) + { + /* In case the parameter pxMACAddress is NULL, an entry will be reserved to + * indicate that there is an outstanding ARP request, This entry will have + * "ucValid == pdFALSE". */ + xIpEntry = x; + break; + } + + /* See if the MAC-address also matches. */ + if( xMatchingMAC != pdFALSE ) + { + /* This function will be called for each received packet + * As this is by far the most common path the coding standard + * is relaxed in this case and a return is permitted as an + * optimisation. */ + xARPCache[ x ].ucAge = ( uint8_t ) ipconfigMAX_ARP_AGE; + xARPCache[ x ].ucValid = ( uint8_t ) pdTRUE; + return; + } + + /* Found an entry containing ulIPAddress, but the MAC address + * doesn't match. Might be an entry with ucValid=pdFALSE, waiting + * for an ARP reply. Still want to see if there is match with the + * given MAC address.ucBytes. If found, either of the two entries + * must be cleared. */ + xIpEntry = x; + } + else if( xMatchingMAC != pdFALSE ) + { + /* Found an entry with the given MAC-address, but the IP-address + * is different. Continue looping to find a possible match with + * ulIPAddress. */ + #if ( ipconfigARP_STORES_REMOTE_ADDRESSES != 0 ) + + /* If ARP stores the MAC address of IP addresses outside the + * network, than the MAC address of the gateway should not be + * overwritten. */ + BaseType_t bIsLocal[ 2 ]; + bIsLocal[ 0 ] = ( ( xARPCache[ x ].ulIPAddress & xNetworkAddressing.ulNetMask ) == ( ( *ipLOCAL_IP_ADDRESS_POINTER ) & xNetworkAddressing.ulNetMask ) ); + bIsLocal[ 1 ] = ( ( ulIPAddress & xNetworkAddressing.ulNetMask ) == ( ( *ipLOCAL_IP_ADDRESS_POINTER ) & xNetworkAddressing.ulNetMask ) ); + + if( bIsLocal[ 0 ] == bIsLocal[ 1 ] ) + { + xMacEntry = x; + } + #else /* if ( ipconfigARP_STORES_REMOTE_ADDRESSES != 0 ) */ + xMacEntry = x; + #endif /* if ( ipconfigARP_STORES_REMOTE_ADDRESSES != 0 ) */ + } + + /* _HT_ + * Shouldn't we test for xARPCache[ x ].ucValid == pdFALSE here ? */ + else if( xARPCache[ x ].ucAge < ucMinAgeFound ) + { + /* As the table is traversed, remember the table row that + * contains the oldest entry (the lowest age count, as ages are + * decremented to zero) so the row can be re-used if this function + * needs to add an entry that does not already exist. */ + ucMinAgeFound = xARPCache[ x ].ucAge; + xUseEntry = x; + } + else + { + /* Nothing happens to this cache entry for now. */ + } + } + + if( xMacEntry >= 0 ) + { + xUseEntry = xMacEntry; + + if( xIpEntry >= 0 ) + { + /* Both the MAC address as well as the IP address were found in + * different locations: clear the entry which matches the + * IP-address */ + ( void ) memset( &( xARPCache[ xIpEntry ] ), 0, sizeof( ARPCacheRow_t ) ); + } + } + else if( xIpEntry >= 0 ) + { + /* An entry containing the IP-address was found, but it had a different MAC address */ + xUseEntry = xIpEntry; + } + else + { + /* No matching entry found. */ + } + + /* If the entry was not found, we use the oldest entry and set the IPaddress */ + xARPCache[ xUseEntry ].ulIPAddress = ulIPAddress; + + if( pxMACAddress != NULL ) + { + ( void ) memcpy( xARPCache[ xUseEntry ].xMACAddress.ucBytes, pxMACAddress->ucBytes, sizeof( pxMACAddress->ucBytes ) ); + + iptraceARP_TABLE_ENTRY_CREATED( ulIPAddress, ( *pxMACAddress ) ); + /* And this entry does not need immediate attention */ + xARPCache[ xUseEntry ].ucAge = ( uint8_t ) ipconfigMAX_ARP_AGE; + xARPCache[ xUseEntry ].ucValid = ( uint8_t ) pdTRUE; + } + else if( xIpEntry < 0 ) + { + xARPCache[ xUseEntry ].ucAge = ( uint8_t ) ipconfigMAX_ARP_RETRANSMISSIONS; + xARPCache[ xUseEntry ].ucValid = ( uint8_t ) pdFALSE; + } + else + { + /* Nothing will be stored. */ + } + } +} +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_ARP_REVERSED_LOOKUP == 1 ) + +/** + * @brief Retrieve an entry from the cache table + * + * @param[in] pxMACAddress: The MAC-address of the entry of interest. + * @param[out] pulIPAddress: set to the IP-address found, or unchanged when not found. + * + * @return Either eARPCacheMiss or eARPCacheHit. + */ + eARPLookupResult_t eARPGetCacheEntryByMac( MACAddress_t * const pxMACAddress, + uint32_t * pulIPAddress ) + { + BaseType_t x; + eARPLookupResult_t eReturn = eARPCacheMiss; + + configASSERT( pxMACAddress != NULL ); + configASSERT( pulIPAddress != NULL ); + + /* Loop through each entry in the ARP cache. */ + for( x = 0; x < ipconfigARP_CACHE_ENTRIES; x++ ) + { + /* Does this row in the ARP cache table hold an entry for the MAC + * address being searched? */ + if( memcmp( pxMACAddress->ucBytes, xARPCache[ x ].xMACAddress.ucBytes, sizeof( MACAddress_t ) ) == 0 ) + { + *pulIPAddress = xARPCache[ x ].ulIPAddress; + eReturn = eARPCacheHit; + break; + } + } + + return eReturn; + } +#endif /* ipconfigUSE_ARP_REVERSED_LOOKUP */ + +/*-----------------------------------------------------------*/ + +/** + * @brief Look for ulIPAddress in the ARP cache. + * + * @param[in,out] pulIPAddress: Pointer to the IP-address to be queried to the ARP cache. + * @param[in,out] pxMACAddress: Pointer to a MACAddress_t variable where the MAC address + * will be stored, if found. + * + * @return If the IP address exists, copy the associated MAC address into pxMACAddress, + * refresh the ARP cache entry's age, and return eARPCacheHit. If the IP + * address does not exist in the ARP cache return eARPCacheMiss. If the packet + * cannot be sent for any reason (maybe DHCP is still in process, or the + * addressing needs a gateway but there isn't a gateway defined) then return + * eCantSendPacket. + */ +eARPLookupResult_t eARPGetCacheEntry( uint32_t * pulIPAddress, + MACAddress_t * const pxMACAddress ) +{ + eARPLookupResult_t eReturn; + uint32_t ulAddressToLookup; + + ulAddressToLookup = *pulIPAddress; + + #if ( ipconfigUSE_LLMNR == 1 ) + if( ulAddressToLookup == ipLLMNR_IP_ADDR ) /* Is in network byte order. */ + { + /* The LLMNR IP-address has a fixed virtual MAC address. */ + ( void ) memcpy( pxMACAddress->ucBytes, xLLMNR_MacAdress.ucBytes, sizeof( MACAddress_t ) ); + eReturn = eARPCacheHit; + } + else + #endif + + if( xIsIPv4Multicast( ulAddressToLookup ) != 0 ) + { + /* Get the lowest 23 bits of the IP-address. */ + vSetMultiCastIPv4MacAddress( ulAddressToLookup, pxMACAddress ); + + eReturn = eARPCacheHit; + } + else if( ( *pulIPAddress == ipBROADCAST_IP_ADDRESS ) || /* Is it the general broadcast address 255.255.255.255? */ + ( *pulIPAddress == xNetworkAddressing.ulBroadcastAddress ) ) /* Or a local broadcast address, eg 192.168.1.255? */ + { + /* This is a broadcast so it uses the broadcast MAC address. */ + ( void ) memcpy( pxMACAddress->ucBytes, xBroadcastMACAddress.ucBytes, sizeof( MACAddress_t ) ); + eReturn = eARPCacheHit; + } + else if( *ipLOCAL_IP_ADDRESS_POINTER == 0UL ) + { + /* The IP address has not yet been assigned, so there is nothing that + * can be done. */ + eReturn = eCantSendPacket; + } + else + { + eReturn = eARPCacheMiss; + + if( ( *pulIPAddress & xNetworkAddressing.ulNetMask ) != ( ( *ipLOCAL_IP_ADDRESS_POINTER ) & xNetworkAddressing.ulNetMask ) ) + { + /* No matching end-point is found, look for a gateway. */ + #if ( ipconfigARP_STORES_REMOTE_ADDRESSES == 1 ) + eReturn = prvCacheLookup( *pulIPAddress, pxMACAddress ); + + if( eReturn == eARPCacheHit ) + { + /* The stack is configured to store 'remote IP addresses', i.e. addresses + * belonging to a different the netmask. prvCacheLookup() returned a hit, so + * the MAC address is known. */ + } + else + #endif + { + /* The IP address is off the local network, so look up the + * hardware address of the router, if any. */ + if( xNetworkAddressing.ulGatewayAddress != ( uint32_t ) 0U ) + { + ulAddressToLookup = xNetworkAddressing.ulGatewayAddress; + } + else + { + ulAddressToLookup = *pulIPAddress; + } + } + } + else + { + /* The IP address is on the local network, so lookup the requested + * IP address directly. */ + ulAddressToLookup = *pulIPAddress; + } + + #if ( ipconfigARP_STORES_REMOTE_ADDRESSES == 1 ) + if( eReturn == eARPCacheMiss ) /*lint !e774: (Info -- Boolean within 'if' always evaluates to True, depending on configuration. */ + #else + /* No cache look-up was done, so the result is still 'eARPCacheMiss'. */ + #endif + { + if( ulAddressToLookup == 0UL ) + { + /* The address is not on the local network, and there is not a + * router. */ + eReturn = eCantSendPacket; + } + else + { + eReturn = prvCacheLookup( ulAddressToLookup, pxMACAddress ); + + if( eReturn == eARPCacheMiss ) + { + /* It might be that the ARP has to go to the gateway. */ + *pulIPAddress = ulAddressToLookup; + } + } + } + } + + return eReturn; +} + +/*-----------------------------------------------------------*/ + +/** + * @brief Lookup an IP address in the ARP cache. + * + * @param[in] ulAddressToLookup: The 32-bit representation of an IP address to + * lookup. + * @param[out] pxMACAddress: A pointer to MACAddress_t variable where, if there + * is an ARP cache hit, the MAC address corresponding to + * the IP address will be stored. + * + * @return When the IP-address is found: eARPCacheHit, when not found: eARPCacheMiss, + * and when waiting for a ARP reply: eCantSendPacket. + */ +static eARPLookupResult_t prvCacheLookup( uint32_t ulAddressToLookup, + MACAddress_t * const pxMACAddress ) +{ + BaseType_t x; + eARPLookupResult_t eReturn = eARPCacheMiss; + + /* Loop through each entry in the ARP cache. */ + for( x = 0; x < ipconfigARP_CACHE_ENTRIES; x++ ) + { + /* Does this row in the ARP cache table hold an entry for the IP address + * being queried? */ + if( xARPCache[ x ].ulIPAddress == ulAddressToLookup ) + { + /* A matching valid entry was found. */ + if( xARPCache[ x ].ucValid == ( uint8_t ) pdFALSE ) + { + /* This entry is waiting an ARP reply, so is not valid. */ + eReturn = eCantSendPacket; + } + else + { + /* A valid entry was found. */ + ( void ) memcpy( pxMACAddress->ucBytes, xARPCache[ x ].xMACAddress.ucBytes, sizeof( MACAddress_t ) ); + eReturn = eARPCacheHit; + } + + break; + } + } + + return eReturn; +} +/*-----------------------------------------------------------*/ + +/** + * @brief A call to this function will update (or 'Age') the ARP cache entries. + * The function will also try to prevent a removal of entry by sending + * an ARP query. It will also check whether we are waiting on an ARP + * reply - if we are, then an ARP request will be re-sent. + * In case an ARP entry has 'Aged' to 0, it will be removed from the ARP + * cache. + */ +void vARPAgeCache( void ) +{ + BaseType_t x; + TickType_t xTimeNow; + + /* Loop through each entry in the ARP cache. */ + for( x = 0; x < ipconfigARP_CACHE_ENTRIES; x++ ) + { + /* If the entry is valid (its age is greater than zero). */ + if( xARPCache[ x ].ucAge > 0U ) + { + /* Decrement the age value of the entry in this ARP cache table row. + * When the age reaches zero it is no longer considered valid. */ + ( xARPCache[ x ].ucAge )--; + + /* If the entry is not yet valid, then it is waiting an ARP + * reply, and the ARP request should be retransmitted. */ + if( xARPCache[ x ].ucValid == ( uint8_t ) pdFALSE ) + { + FreeRTOS_OutputARPRequest( xARPCache[ x ].ulIPAddress ); + } + else if( xARPCache[ x ].ucAge <= ( uint8_t ) arpMAX_ARP_AGE_BEFORE_NEW_ARP_REQUEST ) + { + /* This entry will get removed soon. See if the MAC address is + * still valid to prevent this happening. */ + iptraceARP_TABLE_ENTRY_WILL_EXPIRE( xARPCache[ x ].ulIPAddress ); + FreeRTOS_OutputARPRequest( xARPCache[ x ].ulIPAddress ); + } + else + { + /* The age has just ticked down, with nothing to do. */ + } + + if( xARPCache[ x ].ucAge == 0U ) + { + /* The entry is no longer valid. Wipe it out. */ + iptraceARP_TABLE_ENTRY_EXPIRED( xARPCache[ x ].ulIPAddress ); + xARPCache[ x ].ulIPAddress = 0UL; + } + } + } + + xTimeNow = xTaskGetTickCount(); + + if( ( xLastGratuitousARPTime == ( TickType_t ) 0 ) || ( ( xTimeNow - xLastGratuitousARPTime ) > ( TickType_t ) arpGRATUITOUS_ARP_PERIOD ) ) + { + FreeRTOS_OutputARPRequest( *ipLOCAL_IP_ADDRESS_POINTER ); + xLastGratuitousARPTime = xTimeNow; + } +} +/*-----------------------------------------------------------*/ + +/** + * @brief Send a Gratuitous ARP packet to allow this node to announce the IP-MAC + * mapping to the entire network. + */ +void vARPSendGratuitous( void ) +{ + /* Setting xLastGratuitousARPTime to 0 will force a gratuitous ARP the next + * time vARPAgeCache() is called. */ + xLastGratuitousARPTime = ( TickType_t ) 0; + + /* Let the IP-task call vARPAgeCache(). */ + ( void ) xSendEventToIPTask( eARPTimerEvent ); +} + +/*-----------------------------------------------------------*/ + +/** + * @brief Create and send an ARP request packet. + * + * @param[in] ulIPAddress: A 32-bit representation of the IP-address whose + * physical (MAC) address is required. + */ +void FreeRTOS_OutputARPRequest( uint32_t ulIPAddress ) +{ + NetworkBufferDescriptor_t * pxNetworkBuffer; + + /* This is called from the context of the IP event task, so a block time + * must not be used. */ + pxNetworkBuffer = pxGetNetworkBufferWithDescriptor( sizeof( ARPPacket_t ), ( TickType_t ) 0U ); + + if( pxNetworkBuffer != NULL ) + { + pxNetworkBuffer->ulIPAddress = ulIPAddress; + vARPGenerateRequestPacket( pxNetworkBuffer ); + + #if defined( ipconfigETHERNET_MINIMUM_PACKET_BYTES ) + { + if( pxNetworkBuffer->xDataLength < ( size_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES ) + { + BaseType_t xIndex; + + for( xIndex = ( BaseType_t ) pxNetworkBuffer->xDataLength; xIndex < ( BaseType_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES; xIndex++ ) + { + pxNetworkBuffer->pucEthernetBuffer[ xIndex ] = 0U; + } + + pxNetworkBuffer->xDataLength = ( size_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES; + } + } + #endif /* if defined( ipconfigETHERNET_MINIMUM_PACKET_BYTES ) */ + + if( xIsCallingFromIPTask() != 0 ) + { + iptraceNETWORK_INTERFACE_OUTPUT( pxNetworkBuffer->xDataLength, pxNetworkBuffer->pucEthernetBuffer ); + /* Only the IP-task is allowed to call this function directly. */ + ( void ) xNetworkInterfaceOutput( pxNetworkBuffer, pdTRUE ); + } + else + { + IPStackEvent_t xSendEvent; + + /* Send a message to the IP-task to send this ARP packet. */ + xSendEvent.eEventType = eNetworkTxEvent; + xSendEvent.pvData = pxNetworkBuffer; + + if( xSendEventStructToIPTask( &xSendEvent, ( TickType_t ) portMAX_DELAY ) == pdFAIL ) + { + /* Failed to send the message, so release the network buffer. */ + vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer ); + } + } + } +} +/*--------------------------------------*/ + +/** + * @brief Generate an ARP request packet by copying various constant details to + * the buffer. + * + * @param[in,out] pxNetworkBuffer: Pointer to the buffer which has to be filled with + * the ARP request packet details. + */ +void vARPGenerateRequestPacket( NetworkBufferDescriptor_t * const pxNetworkBuffer ) +{ +/* Part of the Ethernet and ARP headers are always constant when sending an IPv4 + * ARP packet. This array defines the constant parts, allowing this part of the + * packet to be filled in using a simple memcpy() instead of individual writes. */ + static const uint8_t xDefaultPartARPPacketHeader[] = + { + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* Ethernet destination address. */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Ethernet source address. */ + 0x08, 0x06, /* Ethernet frame type (ipARP_FRAME_TYPE). */ + 0x00, 0x01, /* usHardwareType (ipARP_HARDWARE_TYPE_ETHERNET). */ + 0x08, 0x00, /* usProtocolType. */ + ipMAC_ADDRESS_LENGTH_BYTES, /* ucHardwareAddressLength. */ + ipIP_ADDRESS_LENGTH_BYTES, /* ucProtocolAddressLength. */ + 0x00, 0x01, /* usOperation (ipARP_REQUEST). */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* xSenderHardwareAddress. */ + 0x00, 0x00, 0x00, 0x00, /* ulSenderProtocolAddress. */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 /* xTargetHardwareAddress. */ + }; + + ARPPacket_t * pxARPPacket; + +/* memcpy() helper variables for MISRA Rule 21.15 compliance*/ + const void * pvCopySource; + void * pvCopyDest; + + /* Buffer allocation ensures that buffers always have space + * for an ARP packet. See buffer allocation implementations 1 + * and 2 under portable/BufferManagement. */ + configASSERT( pxNetworkBuffer != NULL ); + configASSERT( pxNetworkBuffer->xDataLength >= sizeof( ARPPacket_t ) ); + + pxARPPacket = ipCAST_PTR_TO_TYPE_PTR( ARPPacket_t, pxNetworkBuffer->pucEthernetBuffer ); + + /* memcpy the const part of the header information into the correct + * location in the packet. This copies: + * xEthernetHeader.ulDestinationAddress + * xEthernetHeader.usFrameType; + * xARPHeader.usHardwareType; + * xARPHeader.usProtocolType; + * xARPHeader.ucHardwareAddressLength; + * xARPHeader.ucProtocolAddressLength; + * xARPHeader.usOperation; + * xARPHeader.xTargetHardwareAddress; + */ + + /* + * Use helper variables for memcpy() to remain + * compliant with MISRA Rule 21.15. These should be + * optimized away. + */ + pvCopySource = xDefaultPartARPPacketHeader; + pvCopyDest = pxARPPacket; + ( void ) memcpy( pvCopyDest, pvCopySource, sizeof( xDefaultPartARPPacketHeader ) ); + + pvCopySource = ipLOCAL_MAC_ADDRESS; + pvCopyDest = pxARPPacket->xEthernetHeader.xSourceAddress.ucBytes; + ( void ) memcpy( pvCopyDest, pvCopySource, ipMAC_ADDRESS_LENGTH_BYTES ); + + pvCopySource = ipLOCAL_MAC_ADDRESS; + pvCopyDest = pxARPPacket->xARPHeader.xSenderHardwareAddress.ucBytes; + ( void ) memcpy( pvCopyDest, pvCopySource, ipMAC_ADDRESS_LENGTH_BYTES ); + + pvCopySource = ipLOCAL_IP_ADDRESS_POINTER; + pvCopyDest = pxARPPacket->xARPHeader.ucSenderProtocolAddress; + ( void ) memcpy( pvCopyDest, pvCopySource, sizeof( pxARPPacket->xARPHeader.ucSenderProtocolAddress ) ); + pxARPPacket->xARPHeader.ulTargetProtocolAddress = pxNetworkBuffer->ulIPAddress; + + pxNetworkBuffer->xDataLength = sizeof( ARPPacket_t ); + + iptraceCREATING_ARP_REQUEST( pxNetworkBuffer->ulIPAddress ); +} +/*-----------------------------------------------------------*/ + +/** + * @brief A call to this function will clear the ARP cache. + */ +void FreeRTOS_ClearARP( void ) +{ + ( void ) memset( xARPCache, 0, sizeof( xARPCache ) ); +} +/*-----------------------------------------------------------*/ + +#if 1 + +/** + * @brief This function will check if the target IP-address belongs to this device. + * If so, the packet will be passed to the IP-stack, who will answer it. + * The function is to be called within the function xNetworkInterfaceOutput(). + * + * @param[in] pxDescriptor: The network buffer which is to be checked for loop-back. + * @param[in] bReleaseAfterSend: pdTRUE: Driver is allowed to transfer ownership of descriptor. + * pdFALSE: Driver is not allowed to take ownership of descriptor, + * make a copy of it. + * + * @return pdTRUE/pdFALSE: There is/isn't a loopback address in the packet. + */ + BaseType_t xCheckLoopback( NetworkBufferDescriptor_t * const pxDescriptor, + BaseType_t bReleaseAfterSend ) + { + BaseType_t xResult = pdFALSE; + NetworkBufferDescriptor_t * pxUseDescriptor = pxDescriptor; + const IPPacket_t * pxIPPacket = ipCAST_PTR_TO_TYPE_PTR( IPPacket_t, pxUseDescriptor->pucEthernetBuffer ); + + if( pxIPPacket->xEthernetHeader.usFrameType == ipIPv4_FRAME_TYPE ) + { + if( memcmp( pxIPPacket->xEthernetHeader.xDestinationAddress.ucBytes, ipLOCAL_MAC_ADDRESS, ipMAC_ADDRESS_LENGTH_BYTES ) == 0 ) + { + xResult = pdTRUE; + + if( bReleaseAfterSend == pdFALSE ) + { + /* Driver is not allowed to transfer the ownership + * of descriptor, so make a copy of it */ + pxUseDescriptor = + pxDuplicateNetworkBufferWithDescriptor( pxDescriptor, pxDescriptor->xDataLength ); + } + + if( pxUseDescriptor != NULL ) + { + IPStackEvent_t xRxEvent; + + xRxEvent.eEventType = eNetworkRxEvent; + xRxEvent.pvData = pxUseDescriptor; + + if( xSendEventStructToIPTask( &xRxEvent, 0U ) != pdTRUE ) + { + vReleaseNetworkBufferAndDescriptor( pxUseDescriptor ); + iptraceETHERNET_RX_EVENT_LOST(); + FreeRTOS_printf( ( "prvEMACRxPoll: Can not queue return packet!\n" ) ); + } + } + } + } + + return xResult; + } + +#endif /* 0 */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigHAS_PRINTF != 0 ) || ( ipconfigHAS_DEBUG_PRINTF != 0 ) + + void FreeRTOS_PrintARPCache( void ) + { + BaseType_t x, xCount = 0; + + /* Loop through each entry in the ARP cache. */ + for( x = 0; x < ipconfigARP_CACHE_ENTRIES; x++ ) + { + if( ( xARPCache[ x ].ulIPAddress != 0UL ) && ( xARPCache[ x ].ucAge > ( uint8_t ) 0U ) ) + { + /* See if the MAC-address also matches, and we're all happy */ + FreeRTOS_printf( ( "Arp %2ld: %3u - %16lxip : %02x:%02x:%02x : %02x:%02x:%02x\n", + x, + xARPCache[ x ].ucAge, + xARPCache[ x ].ulIPAddress, + xARPCache[ x ].xMACAddress.ucBytes[ 0 ], + xARPCache[ x ].xMACAddress.ucBytes[ 1 ], + xARPCache[ x ].xMACAddress.ucBytes[ 2 ], + xARPCache[ x ].xMACAddress.ucBytes[ 3 ], + xARPCache[ x ].xMACAddress.ucBytes[ 4 ], + xARPCache[ x ].xMACAddress.ucBytes[ 5 ] ) ); + xCount++; + } + } + + FreeRTOS_printf( ( "Arp has %ld entries\n", xCount ) ); + } + +#endif /* ( ipconfigHAS_PRINTF != 0 ) || ( ipconfigHAS_DEBUG_PRINTF != 0 ) */ diff --git a/examples/stm32/freertos-tcp/FreeRTOS_DHCP.c b/examples/stm32/freertos-tcp/FreeRTOS_DHCP.c new file mode 100644 index 00000000..a9d3380f --- /dev/null +++ b/examples/stm32/freertos-tcp/FreeRTOS_DHCP.c @@ -0,0 +1,1322 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +/** + * @file FreeRTOS_DHCP.c + * @brief Implements the Dynamic Host Configuration Protocol for the FreeRTOS+TCP network stack. + */ + +/* Standard includes. */ +#include + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "semphr.h" + +/* FreeRTOS+TCP includes. */ +#include "FreeRTOS_IP.h" +#include "FreeRTOS_Sockets.h" +#include "FreeRTOS_IP_Private.h" +#include "FreeRTOS_UDP_IP.h" +#include "FreeRTOS_DHCP.h" +#include "FreeRTOS_ARP.h" + +/* Exclude the entire file if DHCP is not enabled. */ +#if ( ipconfigUSE_DHCP != 0 ) + + #include "NetworkInterface.h" + #include "NetworkBufferManagement.h" + + #if ( ipconfigUSE_DHCP != 0 ) && ( ipconfigNETWORK_MTU < 586U ) + +/* DHCP must be able to receive an options field of 312 bytes, the fixed + * part of the DHCP packet is 240 bytes, and the IP/UDP headers take 28 bytes. */ + #error ipconfigNETWORK_MTU needs to be at least 586 to use DHCP + #endif + +/* Parameter widths in the DHCP packet. */ + #define dhcpCLIENT_HARDWARE_ADDRESS_LENGTH 16 /**< Client hardware address length.*/ + #define dhcpSERVER_HOST_NAME_LENGTH 64 /**< Server host name length. */ + #define dhcpBOOT_FILE_NAME_LENGTH 128 /**< Boot file name length. */ + +/* Timer parameters */ + #ifndef dhcpINITIAL_TIMER_PERIOD + /** @brief The interval at which the DHCP state handler is called. */ + #define dhcpINITIAL_TIMER_PERIOD ( pdMS_TO_TICKS( 250U ) ) + #endif + + #ifndef dhcpINITIAL_DHCP_TX_PERIOD + +/** @brief The initial amount of time to wait for a DHCP reply. When repeating an + * unanswered request, this time-out shall be multiplied by 2. */ + #define dhcpINITIAL_DHCP_TX_PERIOD ( pdMS_TO_TICKS( 5000U ) ) + #endif + +/* Codes of interest found in the DHCP options field. */ + #define dhcpIPv4_ZERO_PAD_OPTION_CODE ( 0U ) /**< Used to pad other options to make them aligned. See RFC 2132. */ + #define dhcpIPv4_SUBNET_MASK_OPTION_CODE ( 1U ) /**< Subnet mask. See RFC 2132. */ + #define dhcpIPv4_GATEWAY_OPTION_CODE ( 3U ) /**< Available routers. See RFC 2132. */ + #define dhcpIPv4_DNS_SERVER_OPTIONS_CODE ( 6U ) /**< Domain name server. See RFC 2132. */ + #define dhcpIPv4_DNS_HOSTNAME_OPTIONS_CODE ( 12U ) /**< Host name. See RFC 2132. */ + #define dhcpIPv4_REQUEST_IP_ADDRESS_OPTION_CODE ( 50U ) /**< Requested IP-address. See RFC 2132. */ + #define dhcpIPv4_LEASE_TIME_OPTION_CODE ( 51U ) /**< IP-address lease time. See RFC 2132. */ + #define dhcpIPv4_MESSAGE_TYPE_OPTION_CODE ( 53U ) /**< DHCP message type. See RFC 2132. */ + #define dhcpIPv4_SERVER_IP_ADDRESS_OPTION_CODE ( 54U ) /**< Server Identifier. See RFC 2132. */ + #define dhcpIPv4_PARAMETER_REQUEST_OPTION_CODE ( 55U ) /**< Parameter Request list. See RFC 2132. */ + #define dhcpIPv4_CLIENT_IDENTIFIER_OPTION_CODE ( 61U ) /**< Client Identifier. See RFC 2132. */ + +/* The four DHCP message types of interest. */ + #define dhcpMESSAGE_TYPE_DISCOVER ( 1 ) /**< DHCP discover message. */ + #define dhcpMESSAGE_TYPE_OFFER ( 2 ) /**< DHCP offer message. */ + #define dhcpMESSAGE_TYPE_REQUEST ( 3 ) /**< DHCP request message. */ + #define dhcpMESSAGE_TYPE_ACK ( 5 ) /**< DHCP acknowledgement. */ + #define dhcpMESSAGE_TYPE_NACK ( 6 ) /**< DHCP NACK. (Negative acknowledgement) */ + +/* Offsets into the transmitted DHCP options fields at which various parameters + * are located. */ + #define dhcpCLIENT_IDENTIFIER_OFFSET ( 6U ) /**< Offset for the client ID option. */ + #define dhcpREQUESTED_IP_ADDRESS_OFFSET ( 14U ) /**< Offset for the requested IP-address option. */ + #define dhcpDHCP_SERVER_IP_ADDRESS_OFFSET ( 20U ) /**< Offset for the server IP-address option. */ + +/* Values used in the DHCP packets. */ + #define dhcpREQUEST_OPCODE ( 1U ) /**< DHCP request opcode. */ + #define dhcpREPLY_OPCODE ( 2U ) /**< DHCP reply opcode. */ + #define dhcpADDRESS_TYPE_ETHERNET ( 1U ) /**< Address type: ethernet opcode. */ + #define dhcpETHERNET_ADDRESS_LENGTH ( 6U ) /**< Ethernet address length opcode. */ + +/* The following define is temporary and serves to make the /single source + * code more similar to the /multi version. */ + + #define EP_DHCPData xDHCPData /**< Temporary define to make /single source similar to /multi version. */ + #define EP_IPv4_SETTINGS xNetworkAddressing /**< Temporary define to make /single source similar to /multi version. */ + +/** @brief If a lease time is not received, use the default of two days (48 hours in ticks). + * Can not use pdMS_TO_TICKS() as integer overflow can occur. */ + #define dhcpDEFAULT_LEASE_TIME ( ( 48UL * 60UL * 60UL ) * configTICK_RATE_HZ ) + +/** @brief Don't allow the lease time to be too short. */ + #define dhcpMINIMUM_LEASE_TIME ( pdMS_TO_TICKS( 60000UL ) ) /* 60 seconds in ticks. */ + +/** @brief Marks the end of the variable length options field in the DHCP packet. */ + #define dhcpOPTION_END_BYTE 0xffu + +/** @brief Offset into a DHCP message at which the first byte of the options is + * located. */ + #define dhcpFIRST_OPTION_BYTE_OFFSET ( 0xf0U ) + +/* Standard DHCP port numbers and magic cookie value. + * DHCPv4 uses UDP port number 68 for clients and port number 67 for servers. + */ + #if ( ipconfigBYTE_ORDER == pdFREERTOS_LITTLE_ENDIAN ) + #define dhcpCLIENT_PORT_IPv4 0x4400U /**< Little endian representation of port 68. */ + #define dhcpSERVER_PORT_IPv4 0x4300U /**< Little endian representation of port 67. */ + #define dhcpCOOKIE 0x63538263UL /**< Little endian representation of magic cookie. */ + #define dhcpBROADCAST 0x0080U /**< Little endian representation of broadcast flag. */ + #else + #define dhcpCLIENT_PORT_IPv4 0x0044U /**< Big endian representation of port 68. */ + #define dhcpSERVER_PORT_IPv4 0x0043U /**< Big endian representation of port 68. */ + #define dhcpCOOKIE 0x63825363UL /**< Big endian representation of magic cookie. */ + #define dhcpBROADCAST 0x8000U /**< Big endian representation of broadcast flag. */ + #endif /* ( ipconfigBYTE_ORDER == pdFREERTOS_LITTLE_ENDIAN ) */ + + #include "pack_struct_start.h" + struct xDHCPMessage_IPv4 + { + uint8_t ucOpcode; /**< Operation Code: Specifies the general type of message. */ + uint8_t ucAddressType; /**< Hardware type used on the local network. */ + uint8_t ucAddressLength; /**< Hardware Address Length: Specifies how long hardware + * addresses are in this message. */ + uint8_t ucHops; /**< Hops. */ + uint32_t ulTransactionID; /**< A 32-bit identification field generated by the client, + * to allow it to match up the request with replies received + * from DHCP servers. */ + uint16_t usElapsedTime; /**< Number of seconds elapsed since a client began an attempt to acquire or renew a lease. */ + uint16_t usFlags; /**< Just one bit used to indicate broadcast. */ + uint32_t ulClientIPAddress_ciaddr; /**< Client's IP address if it has one or 0 is put in this field. */ + uint32_t ulYourIPAddress_yiaddr; /**< The IP address that the server is assigning to the client. */ + uint32_t ulServerIPAddress_siaddr; /**< The DHCP server address that the client should use. */ + uint32_t ulRelayAgentIPAddress_giaddr; /**< Gateway IP address in case the server client are on different subnets. */ + uint8_t ucClientHardwareAddress[ dhcpCLIENT_HARDWARE_ADDRESS_LENGTH ]; /**< The client hardware address. */ + uint8_t ucServerHostName[ dhcpSERVER_HOST_NAME_LENGTH ]; /**< Server's hostname. */ + uint8_t ucBootFileName[ dhcpBOOT_FILE_NAME_LENGTH ]; /**< Boot file full directory path. */ + uint32_t ulDHCPCookie; /**< Magic cookie option. */ + /* Option bytes from here on. */ + } + #include "pack_struct_end.h" + typedef struct xDHCPMessage_IPv4 DHCPMessage_IPv4_t; + +/** + * @brief Function to cast pointers to DHCPMessage_IPv4_t. + */ + static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( DHCPMessage_IPv4_t ) + { + return ( DHCPMessage_IPv4_t * ) pvArgument; + } + +/** + * @brief Function to cast const pointers to DHCPMessage_IPv4_t. + */ + static portINLINE ipDECL_CAST_CONST_PTR_FUNC_FOR_TYPE( DHCPMessage_IPv4_t ) + { + return ( const DHCPMessage_IPv4_t * ) pvArgument; + } + + +/** @brief The UDP socket used for all incoming and outgoing DHCP traffic. */ + _static Socket_t xDHCPSocket; + + #if ( ipconfigDHCP_FALL_BACK_AUTO_IP != 0 ) + /* Define the Link Layer IP address: 169.254.x.x */ + #define LINK_LAYER_ADDRESS_0 169 + #define LINK_LAYER_ADDRESS_1 254 + +/* Define the netmask used: 255.255.0.0 */ + #define LINK_LAYER_NETMASK_0 255 + #define LINK_LAYER_NETMASK_1 255 + #define LINK_LAYER_NETMASK_2 0 + #define LINK_LAYER_NETMASK_3 0 + #endif + + +/* + * Generate a DHCP discover message and send it on the DHCP socket. + */ + static BaseType_t prvSendDHCPDiscover( void ); + +/* + * Interpret message received on the DHCP socket. + */ + _static BaseType_t prvProcessDHCPReplies( BaseType_t xExpectedMessageType ); + +/* + * Generate a DHCP request packet, and send it on the DHCP socket. + */ + static BaseType_t prvSendDHCPRequest( void ); + +/* + * Prepare to start a DHCP transaction. This initialises some state variables + * and creates the DHCP socket if necessary. + */ + static void prvInitialiseDHCP( void ); + +/* + * Creates the part of outgoing DHCP messages that are common to all outgoing + * DHCP messages. + */ + static uint8_t * prvCreatePartDHCPMessage( struct freertos_sockaddr * pxAddress, + BaseType_t xOpcode, + const uint8_t * const pucOptionsArray, + size_t * pxOptionsArraySize ); + +/* + * Create the DHCP socket, if it has not been created already. + */ + _static void prvCreateDHCPSocket( void ); + +/* + * Close the DHCP socket. + */ + static void prvCloseDHCPSocket( void ); + +/* + * After DHCP has failed to answer, prepare everything to start searching + * for (trying-out) LinkLayer IP-addresses, using the random method: Send + * a gratuitous ARP request and wait if another device responds to it. + */ + #if ( ipconfigDHCP_FALL_BACK_AUTO_IP != 0 ) + static void prvPrepareLinkLayerIPLookUp( void ); + #endif + +/*-----------------------------------------------------------*/ + +/** @brief Hold information in between steps in the DHCP state machine. */ + _static DHCPData_t xDHCPData; + +/*-----------------------------------------------------------*/ + +/** + * @brief Check whether a given socket is the DHCP socket or not. + * + * @param[in] xSocket: The socket to be checked. + * + * @return If the socket given as parameter is the DHCP socket - return + * pdTRUE, else pdFALSE. + */ + BaseType_t xIsDHCPSocket( Socket_t xSocket ) + { + BaseType_t xReturn; + + if( xDHCPSocket == xSocket ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + + return xReturn; + } + /*-----------------------------------------------------------*/ + +/** + * @brief Returns the current state of a DHCP process. + * + * @return The current state ( eDHCPState_t ) of the DHCP process. + */ + eDHCPState_t eGetDHCPState( void ) + { + return EP_DHCPData.eDHCPState; + } + +/** + * @brief Process the DHCP state machine based on current state. + * + * @param[in] xReset: Is the DHCP state machine starting over? pdTRUE/pdFALSE. + * @param[in] eExpectedState: The function will only run if the state is expected. + */ + void vDHCPProcess( BaseType_t xReset, + eDHCPState_t eExpectedState ) + { + BaseType_t xGivingUp = pdFALSE; + + #if ( ipconfigUSE_DHCP_HOOK != 0 ) + eDHCPCallbackAnswer_t eAnswer; + #endif /* ipconfigUSE_DHCP_HOOK */ + + /* Is DHCP starting over? */ + if( xReset != pdFALSE ) + { + EP_DHCPData.eDHCPState = eInitialWait; + } + + if( ( EP_DHCPData.eDHCPState != eExpectedState ) && ( xReset == pdFALSE ) ) + { + /* When the DHCP event was generated, the DHCP client was + * in a different state. Therefore, ignore this event. */ + FreeRTOS_debug_printf( ( "DHCP wrong state: expect: %d got: %d : ignore\n", + eExpectedState, EP_DHCPData.eDHCPState ) ); + } + else + { + switch( EP_DHCPData.eDHCPState ) + { + case eInitialWait: + + /* Initial state. Create the DHCP socket, timer, etc. if they + * have not already been created. */ + prvInitialiseDHCP(); + EP_DHCPData.eDHCPState = eWaitingSendFirstDiscover; + break; + + case eWaitingSendFirstDiscover: + /* Ask the user if a DHCP discovery is required. */ + #if ( ipconfigUSE_DHCP_HOOK != 0 ) + eAnswer = xApplicationDHCPHook( eDHCPPhasePreDiscover, xNetworkAddressing.ulDefaultIPAddress ); + + if( eAnswer == eDHCPContinue ) + #endif /* ipconfigUSE_DHCP_HOOK */ + { + /* See if prvInitialiseDHCP() has creates a socket. */ + if( xDHCPSocket == NULL ) + { + xGivingUp = pdTRUE; + } + else + { + *ipLOCAL_IP_ADDRESS_POINTER = 0UL; + + /* Send the first discover request. */ + EP_DHCPData.xDHCPTxTime = xTaskGetTickCount(); + + if( prvSendDHCPDiscover() == pdPASS ) + { + EP_DHCPData.eDHCPState = eWaitingOffer; + } + else + { + /* Either the creation of a message buffer failed, or sendto(). + * Try again in the next cycle. */ + FreeRTOS_debug_printf( ( "Send failed during eWaitingSendFirstDiscover\n" ) ); + } + } + } + + #if ( ipconfigUSE_DHCP_HOOK != 0 ) + else + { + if( eAnswer == eDHCPUseDefaults ) + { + ( void ) memcpy( &( xNetworkAddressing ), &( xDefaultAddressing ), sizeof( xNetworkAddressing ) ); + } + + /* The user indicates that the DHCP process does not continue. */ + xGivingUp = pdTRUE; + } + #endif /* ipconfigUSE_DHCP_HOOK */ + break; + + case eSendDHCPRequest: + + if( prvSendDHCPRequest() == pdPASS ) + { + /* Send succeeded, go to state 'eWaitingAcknowledge'. */ + EP_DHCPData.xDHCPTxTime = xTaskGetTickCount(); + EP_DHCPData.xDHCPTxPeriod = dhcpINITIAL_DHCP_TX_PERIOD; + EP_DHCPData.eDHCPState = eWaitingAcknowledge; + } + else + { + /* Either the creation of a message buffer failed, or sendto(). + * Try again in the next cycle. */ + FreeRTOS_debug_printf( ( "Send failed during eSendDHCPRequest.\n" ) ); + } + + break; + + case eWaitingOffer: + + xGivingUp = pdFALSE; + + /* Look for offers coming in. */ + if( prvProcessDHCPReplies( dhcpMESSAGE_TYPE_OFFER ) == pdPASS ) + { + #if ( ipconfigUSE_DHCP_HOOK != 0 ) + /* Ask the user if a DHCP request is required. */ + eAnswer = xApplicationDHCPHook( eDHCPPhasePreRequest, EP_DHCPData.ulOfferedIPAddress ); + + if( eAnswer == eDHCPContinue ) + #endif /* ipconfigUSE_DHCP_HOOK */ + { + /* An offer has been made, the user wants to continue, + * generate the request. */ + if( prvSendDHCPRequest() == pdPASS ) + { + EP_DHCPData.xDHCPTxTime = xTaskGetTickCount(); + EP_DHCPData.xDHCPTxPeriod = dhcpINITIAL_DHCP_TX_PERIOD; + EP_DHCPData.eDHCPState = eWaitingAcknowledge; + } + else + { + /* Either the creation of a message buffer failed, or sendto(). + * Try again in the next cycle. */ + FreeRTOS_debug_printf( ( "Send failed during eWaitingOffer/1.\n" ) ); + EP_DHCPData.eDHCPState = eSendDHCPRequest; + } + + break; + } + + #if ( ipconfigUSE_DHCP_HOOK != 0 ) + if( eAnswer == eDHCPUseDefaults ) + { + ( void ) memcpy( &( xNetworkAddressing ), &( xDefaultAddressing ), sizeof( xNetworkAddressing ) ); + } + + /* The user indicates that the DHCP process does not continue. */ + xGivingUp = pdTRUE; + #endif /* ipconfigUSE_DHCP_HOOK */ + } + + /* Is it time to send another Discover? */ + else if( ( xTaskGetTickCount() - EP_DHCPData.xDHCPTxTime ) > EP_DHCPData.xDHCPTxPeriod ) + { + /* It is time to send another Discover. Increase the time + * period, and if it has not got to the point of giving up - send + * another discovery. */ + EP_DHCPData.xDHCPTxPeriod <<= 1; + + if( EP_DHCPData.xDHCPTxPeriod <= ( TickType_t ) ipconfigMAXIMUM_DISCOVER_TX_PERIOD ) + { + if( xApplicationGetRandomNumber( &( EP_DHCPData.ulTransactionId ) ) != pdFALSE ) + { + EP_DHCPData.xDHCPTxTime = xTaskGetTickCount(); + + if( EP_DHCPData.xUseBroadcast != pdFALSE ) + { + EP_DHCPData.xUseBroadcast = pdFALSE; + } + else + { + EP_DHCPData.xUseBroadcast = pdTRUE; + } + + if( prvSendDHCPDiscover() == pdPASS ) + { + FreeRTOS_debug_printf( ( "vDHCPProcess: timeout %lu ticks\n", EP_DHCPData.xDHCPTxPeriod ) ); + } + else + { + /* Either the creation of a message buffer failed, or sendto(). + * Try again in the next cycle. */ + FreeRTOS_debug_printf( ( "Send failed during eWaitingOffer/2.\n" ) ); + EP_DHCPData.eDHCPState = eInitialWait; + } + } + else + { + FreeRTOS_debug_printf( ( "vDHCPProcess: failed to generate a random Transaction ID\n" ) ); + } + } + else + { + FreeRTOS_debug_printf( ( "vDHCPProcess: giving up %lu > %lu ticks\n", EP_DHCPData.xDHCPTxPeriod, ipconfigMAXIMUM_DISCOVER_TX_PERIOD ) ); + + #if ( ipconfigDHCP_FALL_BACK_AUTO_IP != 0 ) + { + /* Only use a fake Ack if the default IP address == 0x00 + * and the link local addressing is used. Start searching + * a free LinkLayer IP-address. Next state will be + * 'eGetLinkLayerAddress'. */ + prvPrepareLinkLayerIPLookUp(); + + /* Setting an IP address manually so set to not using + * leased address mode. */ + EP_DHCPData.eDHCPState = eGetLinkLayerAddress; + } + #else + { + xGivingUp = pdTRUE; + } + #endif /* ipconfigDHCP_FALL_BACK_AUTO_IP */ + } + } + else + { + /* There was no DHCP reply, there was no time-out, just keep on waiting. */ + } + + break; + + case eWaitingAcknowledge: + + /* Look for acks coming in. */ + if( prvProcessDHCPReplies( dhcpMESSAGE_TYPE_ACK ) == pdPASS ) + { + FreeRTOS_debug_printf( ( "vDHCPProcess: acked %lxip\n", FreeRTOS_ntohl( EP_DHCPData.ulOfferedIPAddress ) ) ); + + /* DHCP completed. The IP address can now be used, and the + * timer set to the lease timeout time. */ + *ipLOCAL_IP_ADDRESS_POINTER = EP_DHCPData.ulOfferedIPAddress; + + /* Setting the 'local' broadcast address, something like + * '192.168.1.255'. */ + EP_IPv4_SETTINGS.ulBroadcastAddress = ( EP_DHCPData.ulOfferedIPAddress & xNetworkAddressing.ulNetMask ) | ~xNetworkAddressing.ulNetMask; + EP_DHCPData.eDHCPState = eLeasedAddress; + + iptraceDHCP_SUCCEDEED( EP_DHCPData.ulOfferedIPAddress ); + + /* DHCP failed, the default configured IP-address will be used + * Now call vIPNetworkUpCalls() to send the network-up event and + * start the ARP timer. */ + vIPNetworkUpCalls(); + + /* Close socket to ensure packets don't queue on it. */ + prvCloseDHCPSocket(); + + if( EP_DHCPData.ulLeaseTime == 0UL ) + { + EP_DHCPData.ulLeaseTime = ( uint32_t ) dhcpDEFAULT_LEASE_TIME; + } + else if( EP_DHCPData.ulLeaseTime < dhcpMINIMUM_LEASE_TIME ) + { + EP_DHCPData.ulLeaseTime = dhcpMINIMUM_LEASE_TIME; + } + else + { + /* The lease time is already valid. */ + } + + /* Check for clashes. */ + vARPSendGratuitous(); + vIPReloadDHCPTimer( EP_DHCPData.ulLeaseTime ); + } + else + { + /* Is it time to send another Discover? */ + if( ( xTaskGetTickCount() - EP_DHCPData.xDHCPTxTime ) > EP_DHCPData.xDHCPTxPeriod ) + { + /* Increase the time period, and if it has not got to the + * point of giving up - send another request. */ + EP_DHCPData.xDHCPTxPeriod <<= 1; + + if( EP_DHCPData.xDHCPTxPeriod <= ( TickType_t ) ipconfigMAXIMUM_DISCOVER_TX_PERIOD ) + { + EP_DHCPData.xDHCPTxTime = xTaskGetTickCount(); + + if( prvSendDHCPRequest() == pdPASS ) + { + /* The message is sent. Stay in state 'eWaitingAcknowledge'. */ + } + else + { + /* Either the creation of a message buffer failed, or sendto(). + * Try again in the next cycle. */ + FreeRTOS_debug_printf( ( "Send failed during eWaitingAcknowledge.\n" ) ); + EP_DHCPData.eDHCPState = eSendDHCPRequest; + } + } + else + { + /* Give up, start again. */ + EP_DHCPData.eDHCPState = eInitialWait; + } + } + } + + break; + + #if ( ipconfigDHCP_FALL_BACK_AUTO_IP != 0 ) + case eGetLinkLayerAddress: + + if( ( xTaskGetTickCount() - EP_DHCPData.xDHCPTxTime ) > EP_DHCPData.xDHCPTxPeriod ) + { + if( xARPHadIPClash == pdFALSE ) + { + /* ARP OK. proceed. */ + iptraceDHCP_SUCCEDEED( EP_DHCPData.ulOfferedIPAddress ); + + /* Auto-IP succeeded, the default configured IP-address will + * be used. Now call vIPNetworkUpCalls() to send the + * network-up event and start the ARP timer. */ + vIPNetworkUpCalls(); + EP_DHCPData.eDHCPState = eNotUsingLeasedAddress; + } + else + { + /* ARP clashed - try another IP address. */ + prvPrepareLinkLayerIPLookUp(); + + /* Setting an IP address manually so set to not using leased + * address mode. */ + EP_DHCPData.eDHCPState = eGetLinkLayerAddress; + } + } + break; + #endif /* ipconfigDHCP_FALL_BACK_AUTO_IP */ + + case eLeasedAddress: + + if( FreeRTOS_IsNetworkUp() != 0 ) + { + /* Resend the request at the appropriate time to renew the lease. */ + prvCreateDHCPSocket(); + + if( xDHCPSocket != NULL ) + { + uint32_t ulID; + + if( xApplicationGetRandomNumber( &( ulID ) ) != pdFALSE ) + { + EP_DHCPData.ulTransactionId = ulID; + } + + EP_DHCPData.xDHCPTxTime = xTaskGetTickCount(); + EP_DHCPData.xDHCPTxPeriod = dhcpINITIAL_DHCP_TX_PERIOD; + + if( prvSendDHCPRequest() == pdPASS ) + { + /* The packet was sent successfully, wait for an acknowledgement. */ + EP_DHCPData.eDHCPState = eWaitingAcknowledge; + } + else + { + /* The packet was not sent, try sending it later. */ + EP_DHCPData.eDHCPState = eSendDHCPRequest; + FreeRTOS_debug_printf( ( "Send failed eLeasedAddress.\n" ) ); + } + + /* From now on, we should be called more often */ + vIPReloadDHCPTimer( dhcpINITIAL_TIMER_PERIOD ); + } + } + else + { + /* See PR #53 on github/freertos/freertos */ + FreeRTOS_printf( ( "DHCP: lease time finished but network is down\n" ) ); + vIPReloadDHCPTimer( pdMS_TO_TICKS( 5000U ) ); + } + + break; + + case eNotUsingLeasedAddress: + + vIPSetDHCPTimerEnableState( pdFALSE ); + break; + + default: + /* Lint: all options are included. */ + break; + } + + if( xGivingUp != pdFALSE ) + { + /* xGivingUp became true either because of a time-out, or because + * xApplicationDHCPHook() returned another value than 'eDHCPContinue', + * meaning that the conversion is cancelled from here. */ + + /* Revert to static IP address. */ + taskENTER_CRITICAL(); + { + *ipLOCAL_IP_ADDRESS_POINTER = xNetworkAddressing.ulDefaultIPAddress; + iptraceDHCP_REQUESTS_FAILED_USING_DEFAULT_IP_ADDRESS( xNetworkAddressing.ulDefaultIPAddress ); + } + taskEXIT_CRITICAL(); + + EP_DHCPData.eDHCPState = eNotUsingLeasedAddress; + vIPSetDHCPTimerEnableState( pdFALSE ); + + /* DHCP failed, the default configured IP-address will be used. Now + * call vIPNetworkUpCalls() to send the network-up event and start the ARP + * timer. */ + vIPNetworkUpCalls(); + + /* Close socket to ensure packets don't queue on it. */ + prvCloseDHCPSocket(); + } + } + } + /*-----------------------------------------------------------*/ + +/** + * @brief Close the DHCP socket. + */ + static void prvCloseDHCPSocket( void ) + { + if( xDHCPSocket != NULL ) + { + /* This modules runs from the IP-task. Use the internal + * function 'vSocketClose()` to close the socket. */ + ( void ) vSocketClose( xDHCPSocket ); + xDHCPSocket = NULL; + } + } + /*-----------------------------------------------------------*/ + +/** + * @brief Create a DHCP socket with the defined timeouts. + */ + _static void prvCreateDHCPSocket( void ) + { + struct freertos_sockaddr xAddress; + BaseType_t xReturn; + TickType_t xTimeoutTime = ( TickType_t ) 0; + + /* Create the socket, if it has not already been created. */ + if( xDHCPSocket == NULL ) + { + xDHCPSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_DGRAM, FREERTOS_IPPROTO_UDP ); + + if( xDHCPSocket != FREERTOS_INVALID_SOCKET ) + { + /* Ensure the Rx and Tx timeouts are zero as the DHCP executes in the + * context of the IP task. */ + ( void ) FreeRTOS_setsockopt( xDHCPSocket, 0, FREERTOS_SO_RCVTIMEO, &( xTimeoutTime ), sizeof( TickType_t ) ); + ( void ) FreeRTOS_setsockopt( xDHCPSocket, 0, FREERTOS_SO_SNDTIMEO, &( xTimeoutTime ), sizeof( TickType_t ) ); + + /* Bind to the standard DHCP client port. */ + xAddress.sin_port = ( uint16_t ) dhcpCLIENT_PORT_IPv4; + xReturn = vSocketBind( xDHCPSocket, &xAddress, sizeof( xAddress ), pdFALSE ); + + if( xReturn != 0 ) + { + /* Binding failed, close the socket again. */ + prvCloseDHCPSocket(); + } + } + else + { + /* Change to NULL for easier testing. */ + xDHCPSocket = NULL; + } + } + } + /*-----------------------------------------------------------*/ + +/** + * @brief Initialise the DHCP state machine by creating DHCP socket and + * begin the transaction. + */ + static void prvInitialiseDHCP( void ) + { + /* Initialise the parameters that will be set by the DHCP process. Per + * https://www.ietf.org/rfc/rfc2131.txt, Transaction ID should be a random + * value chosen by the client. */ + + /* Check for random number generator API failure. */ + if( xApplicationGetRandomNumber( &( EP_DHCPData.ulTransactionId ) ) != pdFALSE ) + { + EP_DHCPData.xUseBroadcast = 0; + EP_DHCPData.ulOfferedIPAddress = 0UL; + EP_DHCPData.ulDHCPServerAddress = 0UL; + EP_DHCPData.xDHCPTxPeriod = dhcpINITIAL_DHCP_TX_PERIOD; + + /* Create the DHCP socket if it has not already been created. */ + prvCreateDHCPSocket(); + FreeRTOS_debug_printf( ( "prvInitialiseDHCP: start after %lu ticks\n", dhcpINITIAL_TIMER_PERIOD ) ); + vIPReloadDHCPTimer( dhcpINITIAL_TIMER_PERIOD ); + } + else + { + /* There was a problem with the randomiser. */ + } + } + /*-----------------------------------------------------------*/ + +/** + * @brief Process the DHCP replies. + * + * @param[in] xExpectedMessageType: The type of the message the DHCP state machine is expecting. + * Messages of different type will be dropped. + * + * @return pdPASS: if DHCP options are received correctly; pdFAIL: Otherwise. + */ + _static BaseType_t prvProcessDHCPReplies( BaseType_t xExpectedMessageType ) + { + uint8_t * pucUDPPayload; + int32_t lBytes; + const DHCPMessage_IPv4_t * pxDHCPMessage; + const uint8_t * pucByte; + uint8_t ucOptionCode; + uint32_t ulProcessed, ulParameter; + BaseType_t xReturn = pdFALSE; + const uint32_t ulMandatoryOptions = 2UL; /* DHCP server address, and the correct DHCP message type must be present in the options. */ + /* memcpy() helper variables for MISRA Rule 21.15 compliance*/ + const void * pvCopySource; + void * pvCopyDest; + + /* Passing the address of a pointer (pucUDPPayload) because FREERTOS_ZERO_COPY is used. */ + lBytes = FreeRTOS_recvfrom( xDHCPSocket, &pucUDPPayload, 0UL, FREERTOS_ZERO_COPY, NULL, NULL ); + + if( lBytes > 0 ) + { + /* Map a DHCP structure onto the received data. */ + pxDHCPMessage = ipCAST_CONST_PTR_TO_CONST_TYPE_PTR( DHCPMessage_IPv4_t, pucUDPPayload ); + + /* Sanity check. */ + if( lBytes < ( int32_t ) sizeof( DHCPMessage_IPv4_t ) ) + { + /* Not enough bytes. */ + } + else if( ( pxDHCPMessage->ulDHCPCookie != ( uint32_t ) dhcpCOOKIE ) || + ( pxDHCPMessage->ucOpcode != ( uint8_t ) dhcpREPLY_OPCODE ) ) + { + /* Invalid cookie or unexpected opcode. */ + } + else if( ( pxDHCPMessage->ulTransactionID != FreeRTOS_htonl( EP_DHCPData.ulTransactionId ) ) ) + { + /* Transaction ID does not match. */ + } + else /* Looks like a valid DHCP response, with the same transaction ID. */ + { + if( memcmp( pxDHCPMessage->ucClientHardwareAddress, + ipLOCAL_MAC_ADDRESS, + sizeof( MACAddress_t ) ) != 0 ) + { + /* Target MAC address doesn't match. */ + } + else + { + size_t uxIndex, uxPayloadDataLength, uxLength; + + /* None of the essential options have been processed yet. */ + ulProcessed = 0UL; + + /* Walk through the options until the dhcpOPTION_END_BYTE byte + * is found, taking care not to walk off the end of the options. */ + pucByte = &( pucUDPPayload[ sizeof( DHCPMessage_IPv4_t ) ] ); + uxIndex = 0; + uxPayloadDataLength = ( ( size_t ) lBytes ) - sizeof( DHCPMessage_IPv4_t ); + + while( uxIndex < uxPayloadDataLength ) + { + ucOptionCode = pucByte[ uxIndex ]; + + if( ucOptionCode == ( uint8_t ) dhcpOPTION_END_BYTE ) + { + /* Ready, the last byte has been seen. */ + /* coverity[break_stmt] : Break statement terminating the loop */ + break; + } + + if( ucOptionCode == ( uint8_t ) dhcpIPv4_ZERO_PAD_OPTION_CODE ) + { + /* The value zero is used as a pad byte, + * it is not followed by a length byte. */ + uxIndex = uxIndex + 1U; + continue; + } + + /* Stop if the response is malformed. */ + if( ( uxIndex + 1U ) < uxPayloadDataLength ) + { + /* Fetch the length byte. */ + uxLength = ( size_t ) pucByte[ uxIndex + 1U ]; + uxIndex = uxIndex + 2U; + + if( !( ( ( uxIndex + uxLength ) - 1U ) < uxPayloadDataLength ) ) + { + /* There are not as many bytes left as there should be. */ + break; + } + } + else + { + /* The length byte is missing. */ + break; + } + + /* In most cases, a 4-byte network-endian parameter follows, + * just get it once here and use later. */ + if( uxLength >= sizeof( ulParameter ) ) + { + /* + * Use helper variables for memcpy() to remain + * compliant with MISRA Rule 21.15. These should be + * optimized away. + */ + pvCopySource = &pucByte[ uxIndex ]; + pvCopyDest = &ulParameter; + ( void ) memcpy( pvCopyDest, pvCopySource, sizeof( ulParameter ) ); + /* 'uxIndex' will be increased at the end of this loop. */ + } + else + { + ulParameter = 0; + } + + /* Confirm uxIndex is still a valid index after adjustments to uxIndex above */ + if( !( uxIndex < uxPayloadDataLength ) ) + { + break; + } + + /* Option-specific handling. */ + switch( ucOptionCode ) + { + case dhcpIPv4_MESSAGE_TYPE_OPTION_CODE: + + if( pucByte[ uxIndex ] == ( uint8_t ) xExpectedMessageType ) + { + /* The message type is the message type the + * state machine is expecting. */ + ulProcessed++; + } + else + { + if( pucByte[ uxIndex ] == ( uint8_t ) dhcpMESSAGE_TYPE_NACK ) + { + if( xExpectedMessageType == ( BaseType_t ) dhcpMESSAGE_TYPE_ACK ) + { + /* Start again. */ + EP_DHCPData.eDHCPState = eInitialWait; + } + } + + /* Stop processing further options. */ + uxLength = 0; + } + + break; + + case dhcpIPv4_SUBNET_MASK_OPTION_CODE: + + if( uxLength == sizeof( uint32_t ) ) + { + EP_IPv4_SETTINGS.ulNetMask = ulParameter; + } + + break; + + case dhcpIPv4_GATEWAY_OPTION_CODE: + + /* The DHCP server may send more than 1 gateway addresses. */ + if( uxLength >= sizeof( uint32_t ) ) + { + /* ulProcessed is not incremented in this case + * because the gateway is not essential. */ + EP_IPv4_SETTINGS.ulGatewayAddress = ulParameter; + } + + break; + + case dhcpIPv4_DNS_SERVER_OPTIONS_CODE: + + /* ulProcessed is not incremented in this case + * because the DNS server is not essential. Only the + * first DNS server address is taken. */ + EP_IPv4_SETTINGS.ulDNSServerAddress = ulParameter; + break; + + case dhcpIPv4_SERVER_IP_ADDRESS_OPTION_CODE: + + if( uxLength == sizeof( uint32_t ) ) + { + if( xExpectedMessageType == ( BaseType_t ) dhcpMESSAGE_TYPE_OFFER ) + { + /* Offers state the replying server. */ + ulProcessed++; + EP_DHCPData.ulDHCPServerAddress = ulParameter; + } + else + { + /* The ack must come from the expected server. */ + if( EP_DHCPData.ulDHCPServerAddress == ulParameter ) + { + ulProcessed++; + } + } + } + + break; + + case dhcpIPv4_LEASE_TIME_OPTION_CODE: + + if( uxLength == sizeof( EP_DHCPData.ulLeaseTime ) ) + { + /* ulProcessed is not incremented in this case + * because the lease time is not essential. */ + + /* The DHCP parameter is in seconds, convert + * to host-endian format. */ + EP_DHCPData.ulLeaseTime = FreeRTOS_ntohl( ulParameter ); + + /* Divide the lease time by two to ensure a renew + * request is sent before the lease actually expires. */ + EP_DHCPData.ulLeaseTime >>= 1UL; + + /* Multiply with configTICK_RATE_HZ to get clock ticks. */ + EP_DHCPData.ulLeaseTime = ( uint32_t ) configTICK_RATE_HZ * ( uint32_t ) EP_DHCPData.ulLeaseTime; + } + + break; + + default: + + /* Not interested in this field. */ + + break; + } + + /* Jump over the data to find the next option code. */ + if( uxLength == 0U ) + { + break; + } + + uxIndex = uxIndex + uxLength; + } + + /* Were all the mandatory options received? */ + if( ulProcessed >= ulMandatoryOptions ) + { + /* HT:endian: used to be network order */ + EP_DHCPData.ulOfferedIPAddress = pxDHCPMessage->ulYourIPAddress_yiaddr; + FreeRTOS_printf( ( "vDHCPProcess: offer %lxip\n", FreeRTOS_ntohl( EP_DHCPData.ulOfferedIPAddress ) ) ); + xReturn = pdPASS; + } + } + } + + FreeRTOS_ReleaseUDPPayloadBuffer( pucUDPPayload ); + } /* if( lBytes > 0 ) */ + + return xReturn; + } + /*-----------------------------------------------------------*/ + +/** + * @brief Create a partial DHCP message by filling in all the 'constant' fields. + * + * @param[out] pxAddress: Address to be filled in. + * @param[out] xOpcode: Opcode to be filled in the packet. Will always be 'dhcpREQUEST_OPCODE'. + * @param[in] pucOptionsArray: The options to be added to the packet. + * @param[in,out] pxOptionsArraySize: Byte count of the options. Its value might change. + * + * @return Ethernet buffer of the partially created DHCP packet. + */ + static uint8_t * prvCreatePartDHCPMessage( struct freertos_sockaddr * pxAddress, + BaseType_t xOpcode, + const uint8_t * const pucOptionsArray, + size_t * pxOptionsArraySize ) + { + DHCPMessage_IPv4_t * pxDHCPMessage; + size_t uxRequiredBufferSize = sizeof( DHCPMessage_IPv4_t ) + *pxOptionsArraySize; + const NetworkBufferDescriptor_t * pxNetworkBuffer; + uint8_t * pucUDPPayloadBuffer = NULL; + + #if ( ipconfigDHCP_REGISTER_HOSTNAME == 1 ) + const char * pucHostName = pcApplicationHostnameHook(); + size_t uxNameLength = strlen( pucHostName ); + uint8_t * pucPtr; + +/* memcpy() helper variables for MISRA Rule 21.15 compliance*/ + const void * pvCopySource; + void * pvCopyDest; + + /* Two extra bytes for option code and length. */ + uxRequiredBufferSize += ( 2U + uxNameLength ); + #endif /* if ( ipconfigDHCP_REGISTER_HOSTNAME == 1 ) */ + + /* Obtain a network buffer with the required amount of storage. It doesn't make much sense + * to use a time-out here, because that would cause the IP-task to wait for itself. */ + pxNetworkBuffer = pxGetNetworkBufferWithDescriptor( sizeof( UDPPacket_t ) + uxRequiredBufferSize, 0U ); + + if( pxNetworkBuffer != NULL ) + { + /* Leave space for the UDP header. */ + pucUDPPayloadBuffer = &( pxNetworkBuffer->pucEthernetBuffer[ ipUDP_PAYLOAD_OFFSET_IPv4 ] ); + pxDHCPMessage = ipCAST_PTR_TO_TYPE_PTR( DHCPMessage_IPv4_t, pucUDPPayloadBuffer ); + + /* Most fields need to be zero. */ + ( void ) memset( pxDHCPMessage, 0x00, sizeof( DHCPMessage_IPv4_t ) ); + + /* Create the message. */ + pxDHCPMessage->ucOpcode = ( uint8_t ) xOpcode; + pxDHCPMessage->ucAddressType = ( uint8_t ) dhcpADDRESS_TYPE_ETHERNET; + pxDHCPMessage->ucAddressLength = ( uint8_t ) dhcpETHERNET_ADDRESS_LENGTH; + pxDHCPMessage->ulTransactionID = FreeRTOS_htonl( EP_DHCPData.ulTransactionId ); + pxDHCPMessage->ulDHCPCookie = ( uint32_t ) dhcpCOOKIE; + + if( EP_DHCPData.xUseBroadcast != pdFALSE ) + { + pxDHCPMessage->usFlags = ( uint16_t ) dhcpBROADCAST; + } + else + { + pxDHCPMessage->usFlags = 0U; + } + + ( void ) memcpy( &( pxDHCPMessage->ucClientHardwareAddress[ 0 ] ), ipLOCAL_MAC_ADDRESS, sizeof( MACAddress_t ) ); + + /* Copy in the const part of the options options. */ + ( void ) memcpy( &( pucUDPPayloadBuffer[ dhcpFIRST_OPTION_BYTE_OFFSET ] ), pucOptionsArray, *pxOptionsArraySize ); + + #if ( ipconfigDHCP_REGISTER_HOSTNAME == 1 ) + { + /* With this option, the hostname can be registered as well which makes + * it easier to lookup a device in a router's list of DHCP clients. */ + + /* Point to where the OPTION_END was stored to add data. */ + pucPtr = &( pucUDPPayloadBuffer[ dhcpFIRST_OPTION_BYTE_OFFSET + ( *pxOptionsArraySize - 1U ) ] ); + pucPtr[ 0U ] = dhcpIPv4_DNS_HOSTNAME_OPTIONS_CODE; + pucPtr[ 1U ] = ( uint8_t ) uxNameLength; + + /* + * Use helper variables for memcpy() to remain + * compliant with MISRA Rule 21.15. These should be + * optimized away. + */ + pvCopySource = pucHostName; + pvCopyDest = &pucPtr[ 2U ]; + + ( void ) memcpy( pvCopyDest, pvCopySource, uxNameLength ); + pucPtr[ 2U + uxNameLength ] = ( uint8_t ) dhcpOPTION_END_BYTE; + *pxOptionsArraySize += ( size_t ) ( 2U + uxNameLength ); + } + #endif /* if ( ipconfigDHCP_REGISTER_HOSTNAME == 1 ) */ + + /* Map in the client identifier. */ + ( void ) memcpy( &( pucUDPPayloadBuffer[ dhcpFIRST_OPTION_BYTE_OFFSET + dhcpCLIENT_IDENTIFIER_OFFSET ] ), + ipLOCAL_MAC_ADDRESS, sizeof( MACAddress_t ) ); + + /* Set the addressing. */ + pxAddress->sin_addr = ipBROADCAST_IP_ADDRESS; + pxAddress->sin_port = ( uint16_t ) dhcpSERVER_PORT_IPv4; + } + + return pucUDPPayloadBuffer; + } + /*-----------------------------------------------------------*/ + +/** + * @brief Create and send a DHCP request message through the DHCP socket. + * @return Returns pdPASS when the message is successfully created and sent. + */ + static BaseType_t prvSendDHCPRequest( void ) + { + BaseType_t xResult = pdFAIL; + uint8_t * pucUDPPayloadBuffer; + struct freertos_sockaddr xAddress; + static const uint8_t ucDHCPRequestOptions[] = + { + /* Do not change the ordering without also changing + * dhcpCLIENT_IDENTIFIER_OFFSET, dhcpREQUESTED_IP_ADDRESS_OFFSET and + * dhcpDHCP_SERVER_IP_ADDRESS_OFFSET. */ + dhcpIPv4_MESSAGE_TYPE_OPTION_CODE, 1, dhcpMESSAGE_TYPE_REQUEST, /* Message type option. */ + dhcpIPv4_CLIENT_IDENTIFIER_OPTION_CODE, 7, 1, 0, 0, 0, 0, 0, 0, /* Client identifier. */ + dhcpIPv4_REQUEST_IP_ADDRESS_OPTION_CODE, 4, 0, 0, 0, 0, /* The IP address being requested. */ + dhcpIPv4_SERVER_IP_ADDRESS_OPTION_CODE, 4, 0, 0, 0, 0, /* The IP address of the DHCP server. */ + dhcpOPTION_END_BYTE + }; + size_t uxOptionsLength = sizeof( ucDHCPRequestOptions ); + /* memcpy() helper variables for MISRA Rule 21.15 compliance*/ + const void * pvCopySource; + void * pvCopyDest; + + pucUDPPayloadBuffer = prvCreatePartDHCPMessage( &xAddress, + ( BaseType_t ) dhcpREQUEST_OPCODE, + ucDHCPRequestOptions, + &( uxOptionsLength ) ); + + if( pucUDPPayloadBuffer != NULL ) + { + /* Copy in the IP address being requested. */ + + /* + * Use helper variables for memcpy() source & dest to remain + * compliant with MISRA Rule 21.15. These should be + * optimized away. + */ + pvCopySource = &EP_DHCPData.ulOfferedIPAddress; + pvCopyDest = &pucUDPPayloadBuffer[ dhcpFIRST_OPTION_BYTE_OFFSET + dhcpREQUESTED_IP_ADDRESS_OFFSET ]; + ( void ) memcpy( pvCopyDest, pvCopySource, sizeof( EP_DHCPData.ulOfferedIPAddress ) ); + + /* Copy in the address of the DHCP server being used. */ + pvCopySource = &EP_DHCPData.ulDHCPServerAddress; + pvCopyDest = &pucUDPPayloadBuffer[ dhcpFIRST_OPTION_BYTE_OFFSET + dhcpDHCP_SERVER_IP_ADDRESS_OFFSET ]; + ( void ) memcpy( pvCopyDest, pvCopySource, sizeof( EP_DHCPData.ulDHCPServerAddress ) ); + + FreeRTOS_debug_printf( ( "vDHCPProcess: reply %lxip\n", FreeRTOS_ntohl( EP_DHCPData.ulOfferedIPAddress ) ) ); + iptraceSENDING_DHCP_REQUEST(); + + if( FreeRTOS_sendto( xDHCPSocket, pucUDPPayloadBuffer, sizeof( DHCPMessage_IPv4_t ) + uxOptionsLength, FREERTOS_ZERO_COPY, &xAddress, sizeof( xAddress ) ) == 0 ) + { + /* The packet was not successfully queued for sending and must be + * returned to the stack. */ + FreeRTOS_ReleaseUDPPayloadBuffer( pucUDPPayloadBuffer ); + } + else + { + xResult = pdPASS; + } + } + + return xResult; + } + /*-----------------------------------------------------------*/ + +/** + * @brief Create and send a DHCP discover packet through the DHCP socket. + * @return Returns pdPASS when the message is successfully created and sent. + */ + static BaseType_t prvSendDHCPDiscover( void ) + { + BaseType_t xResult = pdFAIL; + uint8_t const * pucUDPPayloadBuffer; + struct freertos_sockaddr xAddress; + static const uint8_t ucDHCPDiscoverOptions[] = + { + /* Do not change the ordering without also changing dhcpCLIENT_IDENTIFIER_OFFSET. */ + dhcpIPv4_MESSAGE_TYPE_OPTION_CODE, 1, dhcpMESSAGE_TYPE_DISCOVER, /* Message type option. */ + dhcpIPv4_CLIENT_IDENTIFIER_OPTION_CODE, 7, 1, 0, 0, 0, 0, 0, 0, /* Client identifier. */ + dhcpIPv4_PARAMETER_REQUEST_OPTION_CODE, 3, dhcpIPv4_SUBNET_MASK_OPTION_CODE, dhcpIPv4_GATEWAY_OPTION_CODE, dhcpIPv4_DNS_SERVER_OPTIONS_CODE, /* Parameter request option. */ + dhcpOPTION_END_BYTE + }; + size_t uxOptionsLength = sizeof( ucDHCPDiscoverOptions ); + + pucUDPPayloadBuffer = prvCreatePartDHCPMessage( &xAddress, + ( BaseType_t ) dhcpREQUEST_OPCODE, + ucDHCPDiscoverOptions, + &( uxOptionsLength ) ); + + if( pucUDPPayloadBuffer != NULL ) + { + FreeRTOS_debug_printf( ( "vDHCPProcess: discover\n" ) ); + iptraceSENDING_DHCP_DISCOVER(); + + if( FreeRTOS_sendto( xDHCPSocket, + pucUDPPayloadBuffer, + sizeof( DHCPMessage_IPv4_t ) + uxOptionsLength, + FREERTOS_ZERO_COPY, + &( xAddress ), + sizeof( xAddress ) ) == 0 ) + { + /* The packet was not successfully queued for sending and must be + * returned to the stack. */ + FreeRTOS_ReleaseUDPPayloadBuffer( pucUDPPayloadBuffer ); + } + + xResult = pdTRUE; + } + + return xResult; + } + /*-----------------------------------------------------------*/ + + + #if ( ipconfigDHCP_FALL_BACK_AUTO_IP != 0 ) + +/** + * @brief When DHCP has failed, the code can assign a Link-Layer address, and check if + * another device already uses the IP-address. + */ + static void prvPrepareLinkLayerIPLookUp( void ) + { + uint8_t ucLinkLayerIPAddress[ 2 ]; + uint32_t ulNumbers[ 2 ]; + + /* After DHCP has failed to answer, prepare everything to start + * trying-out LinkLayer IP-addresses, using the random method. */ + EP_DHCPData.xDHCPTxTime = xTaskGetTickCount(); + + xApplicationGetRandomNumber( &( ulNumbers[ 0 ] ) ); + xApplicationGetRandomNumber( &( ulNumbers[ 1 ] ) ); + ucLinkLayerIPAddress[ 0 ] = ( uint8_t ) 1 + ( uint8_t ) ( ulNumbers[ 0 ] % 0xFDU ); /* get value 1..254 for IP-address 3rd byte of IP address to try. */ + ucLinkLayerIPAddress[ 1 ] = ( uint8_t ) 1 + ( uint8_t ) ( ulNumbers[ 1 ] % 0xFDU ); /* get value 1..254 for IP-address 4th byte of IP address to try. */ + + EP_IPv4_SETTINGS.ulGatewayAddress = 0UL; + + /* prepare xDHCPData with data to test. */ + EP_DHCPData.ulOfferedIPAddress = + FreeRTOS_inet_addr_quick( LINK_LAYER_ADDRESS_0, LINK_LAYER_ADDRESS_1, ucLinkLayerIPAddress[ 0 ], ucLinkLayerIPAddress[ 1 ] ); + + EP_DHCPData.ulLeaseTime = dhcpDEFAULT_LEASE_TIME; /* don't care about lease time. just put anything. */ + + EP_IPv4_SETTINGS.ulNetMask = + FreeRTOS_inet_addr_quick( LINK_LAYER_NETMASK_0, LINK_LAYER_NETMASK_1, LINK_LAYER_NETMASK_2, LINK_LAYER_NETMASK_3 ); + + /* DHCP completed. The IP address can now be used, and the + * timer set to the lease timeout time. */ + *( ipLOCAL_IP_ADDRESS_POINTER ) = EP_DHCPData.ulOfferedIPAddress; + + /* Setting the 'local' broadcast address, something like 192.168.1.255' */ + EP_IPv4_SETTINGS.ulBroadcastAddress = ( EP_DHCPData.ulOfferedIPAddress & EP_IPv4_SETTINGS.ulNetMask ) | ~EP_IPv4_SETTINGS.ulNetMask; + + /* Close socket to ensure packets don't queue on it. not needed anymore as DHCP failed. but still need timer for ARP testing. */ + prvCloseDHCPSocket(); + + xApplicationGetRandomNumber( &( ulNumbers[ 0 ] ) ); + EP_DHCPData.xDHCPTxPeriod = pdMS_TO_TICKS( 3000UL + ( ulNumbers[ 0 ] & 0x3ffUL ) ); /* do ARP test every (3 + 0-1024mS) seconds. */ + + xARPHadIPClash = pdFALSE; /* reset flag that shows if have ARP clash. */ + vARPSendGratuitous(); + } + + #endif /* ipconfigDHCP_FALL_BACK_AUTO_IP */ +/*-----------------------------------------------------------*/ + +#endif /* ipconfigUSE_DHCP != 0 */ diff --git a/examples/stm32/freertos-tcp/FreeRTOS_DNS.c b/examples/stm32/freertos-tcp/FreeRTOS_DNS.c new file mode 100644 index 00000000..6bc06f22 --- /dev/null +++ b/examples/stm32/freertos-tcp/FreeRTOS_DNS.c @@ -0,0 +1,2120 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +/** + * @file FreeRTOS_DNS.c + * @brief Implements the Domain Name System for the FreeRTOS+TCP network stack. + */ + +/* Standard includes. */ +#include +#include + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "semphr.h" + +/* FreeRTOS+TCP includes. */ +#include "FreeRTOS_IP.h" +#include "FreeRTOS_Sockets.h" +#include "FreeRTOS_IP_Private.h" +#include "FreeRTOS_UDP_IP.h" +#include "FreeRTOS_DNS.h" +#include "FreeRTOS_DHCP.h" +#include "NetworkBufferManagement.h" +#include "NetworkInterface.h" + +/* Exclude the entire file if DNS is not enabled. */ +#if ( ipconfigUSE_DNS != 0 ) + + #if ( ipconfigBYTE_ORDER == pdFREERTOS_LITTLE_ENDIAN ) + #define dnsDNS_PORT 0x3500U /**< Little endian: Port used for DNS. */ + #define dnsONE_QUESTION 0x0100U /**< Little endian representation of a DNS question.*/ + #define dnsOUTGOING_FLAGS 0x0001U /**< Little endian representation of standard query. */ + #define dnsRX_FLAGS_MASK 0x0f80U /**< Little endian: The bits of interest in the flags field of incoming DNS messages. */ + #define dnsEXPECTED_RX_FLAGS 0x0080U /**< Little Endian: Should be a response, without any errors. */ + #else + #define dnsDNS_PORT 0x0035U /**< Big endian: Port used for DNS. */ + #define dnsONE_QUESTION 0x0001U /**< Big endian representation of a DNS question.*/ + #define dnsOUTGOING_FLAGS 0x0100U /**< Big endian representation of standard query. */ + #define dnsRX_FLAGS_MASK 0x800fU /**< Big endian: The bits of interest in the flags field of incoming DNS messages. */ + #define dnsEXPECTED_RX_FLAGS 0x8000U /**< Big endian: Should be a response, without any errors. */ + + #endif /* ipconfigBYTE_ORDER */ + +/** @brief The maximum number of times a DNS request should be sent out if a response + * is not received, before giving up. */ + #ifndef ipconfigDNS_REQUEST_ATTEMPTS + #define ipconfigDNS_REQUEST_ATTEMPTS 5 + #endif + +/** @brief If the top two bits in the first character of a name field are set then the + * name field is an offset to the string, rather than the string itself. */ + #define dnsNAME_IS_OFFSET ( ( uint8_t ) 0xc0 ) + +/* NBNS flags. */ + #if ( ipconfigUSE_NBNS == 1 ) + #define dnsNBNS_FLAGS_RESPONSE 0x8000U /**< NBNS response flag. */ + #define dnsNBNS_FLAGS_OPCODE_MASK 0x7800U /**< NBNS opcode bitmask. */ + #define dnsNBNS_FLAGS_OPCODE_QUERY 0x0000U /**< NBNS opcode query. */ + #endif /* ( ipconfigUSE_NBNS == 1 ) */ + +/* Host types. */ + #define dnsTYPE_A_HOST 0x01U /**< DNS type A host. */ + #define dnsCLASS_IN 0x01U /**< DNS class IN (Internet). */ + + #ifndef _lint + /* LLMNR constants. */ + #define dnsLLMNR_TTL_VALUE 300000UL /**< LLMNR time to live value. */ + #define dnsLLMNR_FLAGS_IS_REPONSE 0x8000U /**< LLMNR flag value for response. */ + #endif /* _lint */ + +/* NBNS constants. */ + #if ( ipconfigUSE_NBNS != 0 ) + #define dnsNBNS_TTL_VALUE 3600UL /**< NBNS TTL: 1 hour valid. */ + #define dnsNBNS_TYPE_NET_BIOS 0x0020U /**< NBNS Type: NetBIOS. */ + #define dnsNBNS_CLASS_IN 0x01U /**< NBNS Class: IN (Internet). */ + #define dnsNBNS_NAME_FLAGS 0x6000U /**< NBNS name flags. */ + #define dnsNBNS_ENCODED_NAME_LENGTH 32 /**< NBNS encoded name length. */ + +/** @brief If the queried NBNS name matches with the device's name, + * the query will be responded to with these flags: */ + #define dnsNBNS_QUERY_RESPONSE_FLAGS ( 0x8500U ) + #endif /* ( ipconfigUSE_NBNS != 0 ) */ + +/** @brief Flag DNS parsing errors in situations where an IPv4 address is the return + * type. */ + #define dnsPARSE_ERROR 0UL + + #ifndef _lint + #if ( ipconfigUSE_DNS_CACHE == 0 ) + #if ( ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY != 1 ) + #error When DNS caching is disabled, please make ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY equal to 1. + #endif + #endif + #endif + +/** @brief Define the ASCII value of '.' (Period/Full-stop). */ + #define ASCII_BASELINE_DOT 46U + +/* + * Create a socket and bind it to the standard DNS port number. Return the + * the created socket - or NULL if the socket could not be created or bound. + */ + static Socket_t prvCreateDNSSocket( void ); + +/* + * Create the DNS message in the zero copy buffer passed in the first parameter. + */ + _static size_t prvCreateDNSMessage( uint8_t * pucUDPPayloadBuffer, + const char * pcHostName, + TickType_t uxIdentifier ); + +/* + * Simple routine that jumps over the NAME field of a resource record. + * It returns the number of bytes read. + */ + _static size_t prvSkipNameField( const uint8_t * pucByte, + size_t uxLength ); + +/* + * Process a response packet from a DNS server. + * The parameter 'xExpected' indicates whether the identifier in the reply + * was expected, and thus if the DNS cache may be updated with the reply. + */ + _static uint32_t prvParseDNSReply( uint8_t * pucUDPPayloadBuffer, + size_t uxBufferLength, + BaseType_t xExpected ); + +/* + * Check if hostname is already known. If not, call prvGetHostByName() to send a DNS request. + */ + #if ( ipconfigDNS_USE_CALLBACKS == 1 ) + static uint32_t prvPrepareLookup( const char * pcHostName, + FOnDNSEvent pCallback, + void * pvSearchID, + TickType_t uxTimeout ); + #else + static uint32_t prvPrepareLookup( const char * pcHostName ); + #endif + +/* + * Prepare and send a message to a DNS server. 'uxReadTimeOut_ticks' will be passed as + * zero, in case the user has supplied a call-back function. + */ + static uint32_t prvGetHostByName( const char * pcHostName, + TickType_t uxIdentifier, + TickType_t uxReadTimeOut_ticks ); + + #if ( ipconfigDNS_USE_CALLBACKS != 0 ) + static void vDNSSetCallBack( const char * pcHostName, + void * pvSearchID, + FOnDNSEvent pCallbackFunction, + TickType_t uxTimeout, + TickType_t uxIdentifier ); + #endif /* ipconfigDNS_USE_CALLBACKS */ + + #if ( ipconfigDNS_USE_CALLBACKS != 0 ) + static BaseType_t xDNSDoCallback( TickType_t uxIdentifier, + const char * pcName, + uint32_t ulIPAddress ); + #endif /* ipconfigDNS_USE_CALLBACKS */ + +/* + * The NBNS and the LLMNR protocol share this reply function. + */ + #if ( ( ipconfigUSE_NBNS == 1 ) || ( ipconfigUSE_LLMNR == 1 ) ) + static void prvReplyDNSMessage( NetworkBufferDescriptor_t * pxNetworkBuffer, + BaseType_t lNetLength ); + #endif + + #if ( ipconfigUSE_NBNS == 1 ) + static portINLINE void prvTreatNBNS( uint8_t * pucPayload, + size_t uxBufferLength, + uint32_t ulIPAddress ); + #endif /* ipconfigUSE_NBNS */ + + + #if ( ipconfigUSE_DNS_CACHE == 1 ) || ( ipconfigDNS_USE_CALLBACKS == 1 ) + _static size_t prvReadNameField( const uint8_t * pucByte, + size_t uxRemainingBytes, + char * pcName, + size_t uxDestLen ); + #endif /* ipconfigUSE_DNS_CACHE || ipconfigDNS_USE_CALLBACKS */ + + #if ( ipconfigUSE_DNS_CACHE == 1 ) + static BaseType_t prvProcessDNSCache( const char * pcName, + uint32_t * pulIP, + uint32_t ulTTL, + BaseType_t xLookUp ); + + typedef struct xDNS_CACHE_TABLE_ROW + { + uint32_t ulIPAddresses[ ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY ]; /* The IP address(es) of an ARP cache entry. */ + char pcName[ ipconfigDNS_CACHE_NAME_LENGTH ]; /* The name of the host */ + uint32_t ulTTL; /* Time-to-Live (in seconds) from the DNS server. */ + uint32_t ulTimeWhenAddedInSeconds; + #if ( ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY > 1 ) + uint8_t ucNumIPAddresses; + uint8_t ucCurrentIPAddress; + #endif + } DNSCacheRow_t; + + static DNSCacheRow_t xDNSCache[ ipconfigDNS_CACHE_ENTRIES ]; + +/* Utility function: Clear DNS cache by calling this function. */ + void FreeRTOS_dnsclear( void ) + { + ( void ) memset( xDNSCache, 0x0, sizeof( xDNSCache ) ); + } + #endif /* ipconfigUSE_DNS_CACHE == 1 */ + + #if ( ipconfigUSE_LLMNR == 1 ) + /** @brief The MAC address used for LLMNR. */ + const MACAddress_t xLLMNR_MacAdress = { { 0x01, 0x00, 0x5e, 0x00, 0x00, 0xfc } }; + #endif /* ipconfigUSE_LLMNR == 1 */ + +/*-----------------------------------------------------------*/ + +/* Below #include just tells the compiler to pack the structure. + * It is included in to make the code more readable */ + #include "pack_struct_start.h" + struct xDNSMessage + { + uint16_t usIdentifier; /**< Query identifier. Used to match up replies to outstanding queries. */ + uint16_t usFlags; /**< Flags. */ + uint16_t usQuestions; /**< Number of questions asked in this query. */ + uint16_t usAnswers; /**< Number of answers being provided in this query. */ + uint16_t usAuthorityRRs; /**< Authoritative name server resource records. */ + uint16_t usAdditionalRRs; /**< Additional resource records.*/ + } + #include "pack_struct_end.h" + typedef struct xDNSMessage DNSMessage_t; + +/** + * @brief Utility function to cast pointer of a type to pointer of type DNSMessage_t. + * + * @return The casted pointer. + */ + static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( DNSMessage_t ) + { + return ( DNSMessage_t * ) pvArgument; + } + +/** + * @brief Utility function to cast a const pointer of a type to a const pointer of type DNSMessage_t. + * + * @return The casted pointer. + */ + static portINLINE ipDECL_CAST_CONST_PTR_FUNC_FOR_TYPE( DNSMessage_t ) + { + return ( const DNSMessage_t * ) pvArgument; + } + +/* A DNS query consists of a header, as described in 'struct xDNSMessage' + * It is followed by 1 or more queries, each one consisting of a name and a tail, + * with two fields: type and class + */ + #include "pack_struct_start.h" + struct xDNSTail + { + uint16_t usType; /**< Type of DNS message. */ + uint16_t usClass; /**< Class of DNS message. */ + } + #include "pack_struct_end.h" + typedef struct xDNSTail DNSTail_t; + +/** + * @brief Utility function to cast pointer of a type to pointer of type DNSTail_t. + * + * @return The casted pointer. + */ + static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( DNSTail_t ) + { + return ( DNSTail_t * ) pvArgument; + } + +/* DNS answer record header. */ + #include "pack_struct_start.h" + struct xDNSAnswerRecord + { + uint16_t usType; /**< Type of DNS answer record. */ + uint16_t usClass; /**< Class of DNS answer record. */ + uint32_t ulTTL; /**< Number of seconds the result can be cached. */ + uint16_t usDataLength; /**< Length of the data field. */ + } + #include "pack_struct_end.h" + typedef struct xDNSAnswerRecord DNSAnswerRecord_t; + +/** + * @brief Utility function to cast pointer of a type to pointer of type DNSAnswerRecord_t. + * + * @return The casted pointer. + */ + static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( DNSAnswerRecord_t ) + { + return ( DNSAnswerRecord_t * ) pvArgument; + } + + #if ( ipconfigUSE_LLMNR == 1 ) + + #include "pack_struct_start.h" + struct xLLMNRAnswer + { + uint8_t ucNameCode; /**< Name type. */ + uint8_t ucNameOffset; /**< The name is not repeated in the answer, only the offset is given with "0xc0 " */ + uint16_t usType; /**< Type of the Resource record. */ + uint16_t usClass; /**< Class of the Resource record. */ + uint32_t ulTTL; /**< Seconds till this entry can be cached. */ + uint16_t usDataLength; /**< Length of the address in this record. */ + uint32_t ulIPAddress; /**< The IP-address. */ + } + #include "pack_struct_end.h" + typedef struct xLLMNRAnswer LLMNRAnswer_t; + +/** + * @brief Utility function to cast pointer of a type to pointer of type LLMNRAnswer_t. + * + * @return The casted pointer. + */ + static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( LLMNRAnswer_t ) + { + return ( LLMNRAnswer_t * ) pvArgument; + } + + + #endif /* ipconfigUSE_LLMNR == 1 */ + + #if ( ipconfigUSE_NBNS == 1 ) + + #include "pack_struct_start.h" + struct xNBNSRequest + { + uint16_t usRequestId; /**< NBNS request ID. */ + uint16_t usFlags; /**< Flags of the DNS message. */ + uint16_t ulRequestCount; /**< The number of requests/questions in this query. */ + uint16_t usAnswerRSS; /**< The number of answers in this query. */ + uint16_t usAuthRSS; /**< Number of authoritative resource records. */ + uint16_t usAdditionalRSS; /**< Number of additional resource records. */ + uint8_t ucNameSpace; /**< Length of name. */ + uint8_t ucName[ dnsNBNS_ENCODED_NAME_LENGTH ]; /**< The domain name. */ + uint8_t ucNameZero; /**< Terminator of the name. */ + uint16_t usType; /**< Type of NBNS record. */ + uint16_t usClass; /**< Class of NBNS request. */ + } + #include "pack_struct_end.h" + typedef struct xNBNSRequest NBNSRequest_t; + + #include "pack_struct_start.h" + struct xNBNSAnswer + { + uint16_t usType; /**< Type of NBNS answer. */ + uint16_t usClass; /**< Class of NBNS answer. */ + uint32_t ulTTL; /**< Time in seconds for which the answer can be cached. */ + uint16_t usDataLength; /**< Data length. */ + uint16_t usNbFlags; /**< NetBIOS flags 0x6000 : IP-address, big-endian. */ + uint32_t ulIPAddress; /**< The IPv4 address. */ + } + #include "pack_struct_end.h" + typedef struct xNBNSAnswer NBNSAnswer_t; + +/** + * @brief Utility function to cast pointer of a type to pointer of type NBNSAnswer_t. + * + * @return The casted pointer. + */ + static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( NBNSAnswer_t ) + { + return ( NBNSAnswer_t * ) pvArgument; + } + + #endif /* ipconfigUSE_NBNS == 1 */ + +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_DNS_CACHE == 1 ) + uint32_t FreeRTOS_dnslookup( const char * pcHostName ) + { + uint32_t ulIPAddress = 0UL; + + ( void ) prvProcessDNSCache( pcHostName, &ulIPAddress, 0, pdTRUE ); + return ulIPAddress; + } + #endif /* ipconfigUSE_DNS_CACHE == 1 */ + /*-----------------------------------------------------------*/ + + #if ( ipconfigDNS_USE_CALLBACKS == 1 ) + +/** @brief The structure to hold information for a DNS callback. */ + typedef struct xDNS_Callback + { + TickType_t uxRemaningTime; /**< Timeout in ms */ + FOnDNSEvent pCallbackFunction; /**< Function to be called when the address has been found or when a timeout has been reached */ + TimeOut_t uxTimeoutState; /**< Timeout state. */ + void * pvSearchID; /**< Search ID of the callback function. */ + struct xLIST_ITEM xListItem; /**< List struct. */ + char pcName[ 1 ]; /**< 1 character name. */ + } DNSCallback_t; + + +/** + * @brief Utility function to cast pointer of a type to pointer of type DNSCallback_t. + * + * @return The casted pointer. + */ + static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( DNSCallback_t ) + { + return ( DNSCallback_t * ) pvArgument; + } + +/** @brief The list of all callback structures. */ + static List_t xCallbackList; + +/** + * @brief Define FreeRTOS_gethostbyname() as a normal blocking call. + * + * @param[in] pcHostName: The hostname whose IP address is being searched for. + * + * @return The IP-address of the hostname. + */ + uint32_t FreeRTOS_gethostbyname( const char * pcHostName ) + { + return FreeRTOS_gethostbyname_a( pcHostName, NULL, ( void * ) NULL, 0U ); + } + /*-----------------------------------------------------------*/ + +/** @brief Initialise the list of call-back structures. + */ + void vDNSInitialise( void ) + { + vListInitialise( &xCallbackList ); + } + /*-----------------------------------------------------------*/ + +/** + * @brief Iterate through the list of call-back structures and remove + * old entries which have reached a timeout. + * As soon as the list has become empty, the DNS timer will be stopped. + * In case pvSearchID is supplied, the user wants to cancel a DNS request. + * + * @param[in] pvSearchID: The search ID of callback function whose associated + * DNS request is being cancelled. If non-ID specific checking of + * all requests is required, then this field should be kept as NULL. + */ + void vDNSCheckCallBack( void * pvSearchID ) + { + const ListItem_t * pxIterator; + const ListItem_t * xEnd = listGET_END_MARKER( &xCallbackList ); + + vTaskSuspendAll(); + { + for( pxIterator = ( const ListItem_t * ) listGET_NEXT( xEnd ); + pxIterator != xEnd; + ) + { + DNSCallback_t * pxCallback = ipCAST_PTR_TO_TYPE_PTR( DNSCallback_t, listGET_LIST_ITEM_OWNER( pxIterator ) ); + /* Move to the next item because we might remove this item */ + pxIterator = ( const ListItem_t * ) listGET_NEXT( pxIterator ); + + if( ( pvSearchID != NULL ) && ( pvSearchID == pxCallback->pvSearchID ) ) + { + ( void ) uxListRemove( &( pxCallback->xListItem ) ); + vPortFree( pxCallback ); + } + else if( xTaskCheckForTimeOut( &pxCallback->uxTimeoutState, &pxCallback->uxRemaningTime ) != pdFALSE ) + { + pxCallback->pCallbackFunction( pxCallback->pcName, pxCallback->pvSearchID, 0 ); + ( void ) uxListRemove( &( pxCallback->xListItem ) ); + vPortFree( pxCallback ); + } + else + { + /* This call-back is still waiting for a reply or a time-out. */ + } + } + } + ( void ) xTaskResumeAll(); + + if( listLIST_IS_EMPTY( &xCallbackList ) != pdFALSE ) + { + vIPSetDnsTimerEnableState( pdFALSE ); + } + } + /*-----------------------------------------------------------*/ + +/** + * @brief Remove the entry defined by the search ID to cancel a DNS request. + * + * @param[in] pvSearchID: The search ID of the callback function associated with + * the DNS request being cancelled. Note that the value of + * the pointer matters, not the pointee. + */ + void FreeRTOS_gethostbyname_cancel( void * pvSearchID ) + { + /* _HT_ Should better become a new API call to have the IP-task remove the callback */ + vDNSCheckCallBack( pvSearchID ); + } + /*-----------------------------------------------------------*/ + +/** + * @brief FreeRTOS_gethostbyname_a() was called along with callback parameters. + * Store them in a list for later reference. + * + * @param[in] pcHostName: The hostname whose IP address is being searched for. + * @param[in] pvSearchID: The search ID of the DNS callback function to set. + * @param[in] pCallbackFunction: The callback function pointer. + * @param[in] uxTimeout: Timeout of the callback function. + * @param[in] uxIdentifier: Random number used as ID in the DNS message. + */ + static void vDNSSetCallBack( const char * pcHostName, + void * pvSearchID, + FOnDNSEvent pCallbackFunction, + TickType_t uxTimeout, + TickType_t uxIdentifier ) + { + size_t lLength = strlen( pcHostName ); + DNSCallback_t * pxCallback = ipCAST_PTR_TO_TYPE_PTR( DNSCallback_t, pvPortMalloc( sizeof( *pxCallback ) + lLength ) ); + + /* Translate from ms to number of clock ticks. */ + uxTimeout /= portTICK_PERIOD_MS; + + if( pxCallback != NULL ) + { + if( listLIST_IS_EMPTY( &xCallbackList ) != pdFALSE ) + { + /* This is the first one, start the DNS timer to check for timeouts */ + vIPReloadDNSTimer( FreeRTOS_min_uint32( 1000U, uxTimeout ) ); + } + + ( void ) strcpy( pxCallback->pcName, pcHostName ); + pxCallback->pCallbackFunction = pCallbackFunction; + pxCallback->pvSearchID = pvSearchID; + pxCallback->uxRemaningTime = uxTimeout; + vTaskSetTimeOutState( &pxCallback->uxTimeoutState ); + listSET_LIST_ITEM_OWNER( &( pxCallback->xListItem ), ( void * ) pxCallback ); + listSET_LIST_ITEM_VALUE( &( pxCallback->xListItem ), uxIdentifier ); + vTaskSuspendAll(); + { + vListInsertEnd( &xCallbackList, &pxCallback->xListItem ); + } + ( void ) xTaskResumeAll(); + } + } + /*-----------------------------------------------------------*/ + +/** + * @brief A DNS reply was received, see if there is any matching entry and + * call the handler. + * + * @param[in] uxIdentifier: Identifier associated with the callback function. + * @param[in] pcName: The name associated with the callback function. + * @param[in] ulIPAddress: IP-address obtained from the DNS server. + * + * @return Returns pdTRUE if uxIdentifier was recognized. + */ + static BaseType_t xDNSDoCallback( TickType_t uxIdentifier, + const char * pcName, + uint32_t ulIPAddress ) + { + BaseType_t xResult = pdFALSE; + const ListItem_t * pxIterator; + const ListItem_t * xEnd = listGET_END_MARKER( &xCallbackList ); + + vTaskSuspendAll(); + { + for( pxIterator = ( const ListItem_t * ) listGET_NEXT( xEnd ); + pxIterator != ( const ListItem_t * ) xEnd; + pxIterator = ( const ListItem_t * ) listGET_NEXT( pxIterator ) ) + { + if( listGET_LIST_ITEM_VALUE( pxIterator ) == uxIdentifier ) + { + DNSCallback_t * pxCallback = ipCAST_PTR_TO_TYPE_PTR( DNSCallback_t, listGET_LIST_ITEM_OWNER( pxIterator ) ); + + pxCallback->pCallbackFunction( pcName, pxCallback->pvSearchID, ulIPAddress ); + ( void ) uxListRemove( &pxCallback->xListItem ); + vPortFree( pxCallback ); + + if( listLIST_IS_EMPTY( &xCallbackList ) != pdFALSE ) + { + /* The list of outstanding requests is empty. No need for periodic polling. */ + vIPSetDnsTimerEnableState( pdFALSE ); + } + + xResult = pdTRUE; + break; + } + } + } + ( void ) xTaskResumeAll(); + return xResult; + } + + #endif /* ipconfigDNS_USE_CALLBACKS == 1 */ + /*-----------------------------------------------------------*/ + + #if ( ipconfigDNS_USE_CALLBACKS == 0 ) + +/** + * @brief Get the IP-address corresponding to the given hostname. + * + * @param[in] pcHostName: The hostname whose IP address is being queried. + * + * @return The IP-address corresponding to the hostname. + */ + uint32_t FreeRTOS_gethostbyname( const char * pcHostName ) + { + return prvPrepareLookup( pcHostName ); + } + #else + +/** + * @brief Get the IP-address corresponding to the given hostname. + * + * @param[in] pcHostName: The hostname whose IP address is being queried. + * @param[in] pCallback: The callback function which will be called upon DNS response. + * @param[in] pvSearchID: Search ID for the callback function. + * @param[in] uxTimeout: Timeout for the callback function. + * + * @return The IP-address corresponding to the hostname. + */ + uint32_t FreeRTOS_gethostbyname_a( const char * pcHostName, + FOnDNSEvent pCallback, + void * pvSearchID, + TickType_t uxTimeout ) + { + return prvPrepareLookup( pcHostName, pCallback, pvSearchID, uxTimeout ); + } + #endif /* if ( ipconfigDNS_USE_CALLBACKS == 0 ) */ + + #if ( ipconfigDNS_USE_CALLBACKS == 1 ) + +/** + * @brief Check if hostname is already known. If not, call prvGetHostByName() to send a DNS request. + * + * @param[in] pcHostName: The hostname whose IP address is being queried. + * @param[in] pCallback: The callback function which will be called upon DNS response. + * @param[in] pvSearchID: Search ID for the callback function. + * @param[in] uxTimeout: Timeout for the callback function. + * + * @return The IP-address corresponding to the hostname. + */ + static uint32_t prvPrepareLookup( const char * pcHostName, + FOnDNSEvent pCallback, + void * pvSearchID, + TickType_t uxTimeout ) + #else + +/** + * @brief Check if hostname is already known. If not, call prvGetHostByName() to send a DNS request. + * + * @param[in] pcHostName: The hostname whose IP address is being queried. + * + * @return The IP-address corresponding to the hostname. + */ + static uint32_t prvPrepareLookup( const char * pcHostName ) + #endif + { + uint32_t ulIPAddress = 0UL; + TickType_t uxReadTimeOut_ticks = ipconfigDNS_RECEIVE_BLOCK_TIME_TICKS; + + /* Generate a unique identifier for this query. Keep it in a local variable + * as gethostbyname() may be called from different threads */ + BaseType_t xHasRandom = pdFALSE; + TickType_t uxIdentifier = 0U; + + #if ( ipconfigUSE_DNS_CACHE != 0 ) + BaseType_t xLengthOk = pdFALSE; + #endif + + #if ( ipconfigUSE_DNS_CACHE != 0 ) + { + if( pcHostName != NULL ) + { + size_t xLength = strlen( pcHostName ) + 1U; + + if( xLength <= ipconfigDNS_CACHE_NAME_LENGTH ) + { + /* The name is not too long. */ + xLengthOk = pdTRUE; + } + else + { + FreeRTOS_printf( ( "prvPrepareLookup: name is too long ( %lu > %lu )\n", + ( uint32_t ) xLength, + ( uint32_t ) ipconfigDNS_CACHE_NAME_LENGTH ) ); + } + } + } + + if( ( pcHostName != NULL ) && ( xLengthOk != pdFALSE ) ) + #else /* if ( ipconfigUSE_DNS_CACHE != 0 ) */ + if( pcHostName != NULL ) + #endif /* ( ipconfigUSE_DNS_CACHE != 0 ) */ + { + /* If the supplied hostname is IP address, convert it to uint32_t + * and return. */ + #if ( ipconfigINCLUDE_FULL_INET_ADDR == 1 ) + { + ulIPAddress = FreeRTOS_inet_addr( pcHostName ); + } + #endif /* ipconfigINCLUDE_FULL_INET_ADDR == 1 */ + + /* If a DNS cache is used then check the cache before issuing another DNS + * request. */ + #if ( ipconfigUSE_DNS_CACHE == 1 ) + { + if( ulIPAddress == 0UL ) + { + ulIPAddress = FreeRTOS_dnslookup( pcHostName ); + + if( ulIPAddress != 0UL ) + { + FreeRTOS_debug_printf( ( "FreeRTOS_gethostbyname: found '%s' in cache: %lxip\n", pcHostName, ulIPAddress ) ); + } + else + { + /* prvGetHostByName will be called to start a DNS lookup. */ + } + } + } + #endif /* ipconfigUSE_DNS_CACHE == 1 */ + + /* Generate a unique identifier. */ + if( ulIPAddress == 0UL ) + { + uint32_t ulNumber; + + xHasRandom = xApplicationGetRandomNumber( &( ulNumber ) ); + /* DNS identifiers are 16-bit. */ + uxIdentifier = ( TickType_t ) ( ulNumber & 0xffffU ); + } + + #if ( ipconfigDNS_USE_CALLBACKS == 1 ) + { + if( pCallback != NULL ) + { + if( ulIPAddress == 0UL ) + { + /* The user has provided a callback function, so do not block on recvfrom() */ + if( xHasRandom != pdFALSE ) + { + uxReadTimeOut_ticks = 0U; + vDNSSetCallBack( pcHostName, pvSearchID, pCallback, uxTimeout, uxIdentifier ); + } + } + else + { + /* The IP address is known, do the call-back now. */ + pCallback( pcHostName, pvSearchID, ulIPAddress ); + } + } + } + #endif /* if ( ipconfigDNS_USE_CALLBACKS == 1 ) */ + + if( ( ulIPAddress == 0UL ) && ( xHasRandom != pdFALSE ) ) + { + ulIPAddress = prvGetHostByName( pcHostName, uxIdentifier, uxReadTimeOut_ticks ); + } + } + + return ulIPAddress; + } + /*-----------------------------------------------------------*/ + +/** + * @brief Prepare and send a message to a DNS server. 'uxReadTimeOut_ticks' will be passed as + * zero, in case the user has supplied a call-back function. + * + * @param[in] pcHostName: The hostname for which an IP address is required. + * @param[in] uxIdentifier: Identifier to send in the DNS message. + * @param[in] uxReadTimeOut_ticks: The timeout in ticks for waiting. In case the user has supplied + * a call-back function, this value should be zero. + * + * @return The IPv4 IP address for the hostname being queried. It will be zero if there is no reply. + */ + static uint32_t prvGetHostByName( const char * pcHostName, + TickType_t uxIdentifier, + TickType_t uxReadTimeOut_ticks ) + { + struct freertos_sockaddr xAddress; + Socket_t xDNSSocket; + uint32_t ulIPAddress = 0UL; + uint32_t ulAddressLength = sizeof( struct freertos_sockaddr ); + BaseType_t xAttempt; + int32_t lBytes; + size_t uxPayloadLength, uxExpectedPayloadLength; + TickType_t uxWriteTimeOut_ticks = ipconfigDNS_SEND_BLOCK_TIME_TICKS; + + #if ( ipconfigUSE_LLMNR == 1 ) + BaseType_t bHasDot = pdFALSE; + #endif /* ipconfigUSE_LLMNR == 1 */ + + /* If LLMNR is being used then determine if the host name includes a '.' - + * if not then LLMNR can be used as the lookup method. */ + #if ( ipconfigUSE_LLMNR == 1 ) + { + const char * pucPtr; + + for( pucPtr = pcHostName; *pucPtr != ( char ) 0; pucPtr++ ) + { + if( *pucPtr == '.' ) + { + bHasDot = pdTRUE; + break; + } + } + } + #endif /* ipconfigUSE_LLMNR == 1 */ + + /* Two is added at the end for the count of characters in the first + * subdomain part and the string end byte. */ + uxExpectedPayloadLength = sizeof( DNSMessage_t ) + strlen( pcHostName ) + sizeof( uint16_t ) + sizeof( uint16_t ) + 2U; + + xDNSSocket = prvCreateDNSSocket(); + + if( xDNSSocket != NULL ) + { + /* Ideally we should check for the return value. But since we are passing + * correct parameters, and xDNSSocket is != NULL, the return value is + * going to be '0' i.e. success. Thus, return value is discarded */ + ( void ) FreeRTOS_setsockopt( xDNSSocket, 0, FREERTOS_SO_SNDTIMEO, &( uxWriteTimeOut_ticks ), sizeof( TickType_t ) ); + ( void ) FreeRTOS_setsockopt( xDNSSocket, 0, FREERTOS_SO_RCVTIMEO, &( uxReadTimeOut_ticks ), sizeof( TickType_t ) ); + + for( xAttempt = 0; xAttempt < ipconfigDNS_REQUEST_ATTEMPTS; xAttempt++ ) + { + size_t uxHeaderBytes; + NetworkBufferDescriptor_t * pxNetworkBuffer; + uint8_t * pucUDPPayloadBuffer = NULL, * pucReceiveBuffer; + + /* Get a buffer. This uses a maximum delay, but the delay will be + * capped to ipconfigUDP_MAX_SEND_BLOCK_TIME_TICKS so the return value + * still needs to be tested. */ + + uxHeaderBytes = ipSIZE_OF_ETH_HEADER + ipSIZE_OF_IPv4_HEADER + ipSIZE_OF_UDP_HEADER; + + pxNetworkBuffer = pxGetNetworkBufferWithDescriptor( uxHeaderBytes + uxExpectedPayloadLength, 0UL ); + + if( pxNetworkBuffer != NULL ) + { + pucUDPPayloadBuffer = &( pxNetworkBuffer->pucEthernetBuffer[ uxHeaderBytes ] ); + } + + if( pucUDPPayloadBuffer != NULL ) + { + /* Create the message in the obtained buffer. */ + uxPayloadLength = prvCreateDNSMessage( pucUDPPayloadBuffer, pcHostName, uxIdentifier ); + + iptraceSENDING_DNS_REQUEST(); + + /* Obtain the DNS server address. */ + FreeRTOS_GetAddressConfiguration( NULL, NULL, NULL, &ulIPAddress ); + + /* Send the DNS message. */ + #if ( ipconfigUSE_LLMNR == 1 ) + if( bHasDot == pdFALSE ) + { + /* Use LLMNR addressing. */ + ( ipCAST_PTR_TO_TYPE_PTR( DNSMessage_t, pucUDPPayloadBuffer ) )->usFlags = 0; + xAddress.sin_addr = ipLLMNR_IP_ADDR; /* Is in network byte order. */ + xAddress.sin_port = ipLLMNR_PORT; + xAddress.sin_port = FreeRTOS_ntohs( xAddress.sin_port ); + } + else + #endif + { + /* Use DNS server. */ + xAddress.sin_addr = ulIPAddress; + xAddress.sin_port = dnsDNS_PORT; + } + + ulIPAddress = 0UL; + + if( FreeRTOS_sendto( xDNSSocket, pucUDPPayloadBuffer, uxPayloadLength, FREERTOS_ZERO_COPY, &xAddress, sizeof( xAddress ) ) != 0 ) + { + /* Wait for the reply. */ + lBytes = FreeRTOS_recvfrom( xDNSSocket, &pucReceiveBuffer, 0, FREERTOS_ZERO_COPY, &xAddress, &ulAddressLength ); + + if( lBytes > 0 ) + { + BaseType_t xExpected; + const DNSMessage_t * pxDNSMessageHeader = ipCAST_CONST_PTR_TO_CONST_TYPE_PTR( DNSMessage_t, pucReceiveBuffer ); + + /* See if the identifiers match. */ + if( uxIdentifier == ( TickType_t ) pxDNSMessageHeader->usIdentifier ) + { + xExpected = pdTRUE; + } + else + { + /* The reply was not expected. */ + xExpected = pdFALSE; + } + + /* The reply was received. Process it. */ + #if ( ipconfigDNS_USE_CALLBACKS == 0 ) + + /* It is useless to analyse the unexpected reply + * unless asynchronous look-ups are enabled. */ + if( xExpected != pdFALSE ) + #endif /* ipconfigDNS_USE_CALLBACKS == 0 */ + { + ulIPAddress = prvParseDNSReply( pucReceiveBuffer, ( size_t ) lBytes, xExpected ); + } + + /* Finished with the buffer. The zero copy interface + * is being used, so the buffer must be freed by the + * task. */ + FreeRTOS_ReleaseUDPPayloadBuffer( pucReceiveBuffer ); + + if( ulIPAddress != 0UL ) + { + /* All done. */ + /* coverity[break_stmt] : Break statement terminating the loop */ + break; + } + } + } + else + { + /* The message was not sent so the stack will not be + * releasing the zero copy - it must be released here. */ + vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer ); + } + } + + if( uxReadTimeOut_ticks == 0U ) + { + /* This DNS lookup is asynchronous, using a call-back: + * send the request only once. */ + break; + } + } + + /* Finished with the socket. */ + ( void ) FreeRTOS_closesocket( xDNSSocket ); + } + + return ulIPAddress; + } + /*-----------------------------------------------------------*/ + +/** + * @brief Create the DNS message in the zero copy buffer passed in the first parameter. + * + * @param[in,out] pucUDPPayloadBuffer: The zero copy buffer where the DNS message will be created. + * @param[in] pcHostName: Hostname to be looked up. + * @param[in] uxIdentifier: The identifier to be added to the DNS message. + * + * @return Total size of the generated message, which is the space from the last written byte + * to the beginning of the buffer. + */ + _static size_t prvCreateDNSMessage( uint8_t * pucUDPPayloadBuffer, + const char * pcHostName, + TickType_t uxIdentifier ) + { + DNSMessage_t * pxDNSMessageHeader; + size_t uxStart, uxIndex; + DNSTail_t const * pxTail; + static const DNSMessage_t xDefaultPartDNSHeader = + { + 0, /* The identifier will be overwritten. */ + dnsOUTGOING_FLAGS, /* Flags set for standard query. */ + dnsONE_QUESTION, /* One question is being asked. */ + 0, /* No replies are included. */ + 0, /* No authorities. */ + 0 /* No additional authorities. */ + }; + + /* memcpy() helper variables for MISRA Rule 21.15 compliance*/ + const void * pvCopySource; + void * pvCopyDest; + + /* Copy in the const part of the header. Intentionally using different + * pointers with memcpy() to put the information in to correct place. */ + + /* + * Use helper variables for memcpy() to remain + * compliant with MISRA Rule 21.15. These should be + * optimized away. + */ + pvCopySource = &xDefaultPartDNSHeader; + pvCopyDest = pucUDPPayloadBuffer; + ( void ) memcpy( pvCopyDest, pvCopySource, sizeof( xDefaultPartDNSHeader ) ); + + /* Write in a unique identifier. Cast the Payload Buffer to DNSMessage_t + * to easily access fields of the DNS Message. */ + pxDNSMessageHeader = ipCAST_PTR_TO_TYPE_PTR( DNSMessage_t, pucUDPPayloadBuffer ); + pxDNSMessageHeader->usIdentifier = ( uint16_t ) uxIdentifier; + + /* Create the resource record at the end of the header. First + * find the end of the header. */ + uxStart = sizeof( xDefaultPartDNSHeader ); + + /* Leave a gap for the first length byte. */ + uxIndex = uxStart + 1U; + + /* Copy in the host name. */ + ( void ) strcpy( ( char * ) &( pucUDPPayloadBuffer[ uxIndex ] ), pcHostName ); + + /* Walk through the string to replace the '.' characters with byte + * counts. pucStart holds the address of the byte count. Walking the + * string starts after the byte count position. */ + uxIndex = uxStart; + + do + { + size_t uxLength; + + /* Skip the length byte. */ + uxIndex++; + + while( ( pucUDPPayloadBuffer[ uxIndex ] != ( uint8_t ) 0U ) && + ( pucUDPPayloadBuffer[ uxIndex ] != ( uint8_t ) ASCII_BASELINE_DOT ) ) + { + uxIndex++; + } + + /* Fill in the byte count, then move the pucStart pointer up to + * the found byte position. */ + uxLength = uxIndex - ( uxStart + 1U ); + pucUDPPayloadBuffer[ uxStart ] = ( uint8_t ) uxLength; + + uxStart = uxIndex; + } while( pucUDPPayloadBuffer[ uxIndex ] != ( uint8_t ) 0U ); + + /* Finish off the record. Cast the record onto DNSTail_t structure to easily + * access the fields of the DNS Message. */ + pxTail = ipCAST_PTR_TO_TYPE_PTR( DNSTail_t, &( pucUDPPayloadBuffer[ uxStart + 1U ] ) ); + + #if defined( _lint ) || defined( __COVERITY__ ) + ( void ) pxTail; + #else + vSetField16( pxTail, DNSTail_t, usType, dnsTYPE_A_HOST ); + vSetField16( pxTail, DNSTail_t, usClass, dnsCLASS_IN ); + #endif + + /* Return the total size of the generated message, which is the space from + * the last written byte to the beginning of the buffer. */ + return uxIndex + sizeof( DNSTail_t ) + 1U; + } + /*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_DNS_CACHE == 1 ) || ( ipconfigDNS_USE_CALLBACKS == 1 ) + +/** + * @brief Read the Name field out of a DNS response packet. + * + * @param[in] pucByte: Pointer to the DNS response. + * @param[in] uxRemainingBytes: Length of the DNS response. + * @param[out] pcName: The pointer in which the name in the DNS response will be returned. + * @param[in] uxDestLen: Size of the pcName array. + * + * @return If a fully formed name was found, then return the number of bytes processed in pucByte. + */ + _static size_t prvReadNameField( const uint8_t * pucByte, + size_t uxRemainingBytes, + char * pcName, + size_t uxDestLen ) + { + size_t uxNameLen = 0U; + size_t uxIndex = 0U; + size_t uxSourceLen = uxRemainingBytes; + + /* uxCount gets the values from pucByte and counts down to 0. + * No need to have a different type than that of pucByte */ + size_t uxCount; + + if( uxSourceLen == ( size_t ) 0U ) + { + /* Return 0 value in case of error. */ + uxIndex = 0U; + } + + /* Determine if the name is the fully coded name, or an offset to the name + * elsewhere in the message. */ + else if( ( pucByte[ uxIndex ] & dnsNAME_IS_OFFSET ) == dnsNAME_IS_OFFSET ) + { + /* Jump over the two byte offset. */ + if( uxSourceLen > sizeof( uint16_t ) ) + { + uxIndex += sizeof( uint16_t ); + } + else + { + uxIndex = 0U; + } + } + else + { + /* 'uxIndex' points to the full name. Walk over the string. */ + while( ( uxIndex < uxSourceLen ) && ( pucByte[ uxIndex ] != ( uint8_t ) 0x00U ) ) + { + /* If this is not the first time through the loop, then add a + * separator in the output. */ + if( ( uxNameLen > 0U ) ) + { + if( uxNameLen >= uxDestLen ) + { + uxIndex = 0U; + /* coverity[break_stmt] : Break statement terminating the loop */ + break; + } + + pcName[ uxNameLen ] = '.'; + uxNameLen++; + } + + /* Process the first/next sub-string. */ + uxCount = ( size_t ) pucByte[ uxIndex ]; + uxIndex++; + + if( ( uxIndex + uxCount ) > uxSourceLen ) + { + uxIndex = 0U; + break; + } + + while( ( uxCount-- != 0U ) && ( uxIndex < uxSourceLen ) ) + { + if( uxNameLen >= uxDestLen ) + { + uxIndex = 0U; + break; + + /* break out of inner loop here + * break out of outer loop at the test uxNameLen >= uxDestLen. */ + } + + pcName[ uxNameLen ] = ( char ) pucByte[ uxIndex ]; + uxNameLen++; + uxIndex++; + } + } + + /* Confirm that a fully formed name was found. */ + if( uxIndex > 0U ) + { + if( ( uxNameLen < uxDestLen ) && ( uxIndex < uxSourceLen ) && ( pucByte[ uxIndex ] == 0U ) ) + { + pcName[ uxNameLen ] = '\0'; + uxIndex++; + } + else + { + uxIndex = 0U; + } + } + } + + return uxIndex; + } + #endif /* ipconfigUSE_DNS_CACHE || ipconfigDNS_USE_CALLBACKS */ + /*-----------------------------------------------------------*/ + +/** + * @brief Simple routine that jumps over the NAME field of a resource record. + * + * @param[in] pucByte: The pointer to the resource record. + * @param[in] uxLength: Length of the resource record. + * + * @return It returns the number of bytes read, or zero when an error has occurred. + */ + _static size_t prvSkipNameField( const uint8_t * pucByte, + size_t uxLength ) + { + size_t uxChunkLength; + size_t uxSourceLenCpy = uxLength; + size_t uxIndex = 0U; + + if( uxSourceLenCpy == 0U ) + { + uxIndex = 0U; + } + + /* Determine if the name is the fully coded name, or an offset to the name + * elsewhere in the message. */ + else if( ( pucByte[ uxIndex ] & dnsNAME_IS_OFFSET ) == dnsNAME_IS_OFFSET ) + { + /* Jump over the two byte offset. */ + if( uxSourceLenCpy > sizeof( uint16_t ) ) + { + uxIndex += sizeof( uint16_t ); + } + else + { + uxIndex = 0U; + } + } + else + { + /* pucByte points to the full name. Walk over the string. */ + while( ( pucByte[ uxIndex ] != 0U ) && ( uxSourceLenCpy > 1U ) ) + { + /* Conversion to size_t causes addition to be done + * in size_t */ + uxChunkLength = ( ( size_t ) pucByte[ uxIndex ] ) + 1U; + + if( uxSourceLenCpy > uxChunkLength ) + { + uxSourceLenCpy -= uxChunkLength; + uxIndex += uxChunkLength; + } + else + { + uxIndex = 0U; + break; + } + } + + /* Confirm that a fully formed name was found. */ + if( uxIndex > 0U ) + { + if( pucByte[ uxIndex ] == 0U ) + { + uxIndex++; + } + else + { + uxIndex = 0U; + } + } + } + + return uxIndex; + } + /*-----------------------------------------------------------*/ + +/* The function below will only be called : + * when ipconfigDNS_USE_CALLBACKS == 1 + * when ipconfigUSE_LLMNR == 1 + * for testing purposes, by the module test_freertos_tcp.c + */ + +/** + * @brief Perform some preliminary checks and then parse the DNS packet. + * + * @param[in] pxNetworkBuffer: The network buffer to be parsed. + * + * @return Always pdFAIL to indicate that the packet was not consumed and must + * be released by the caller. + */ + uint32_t ulDNSHandlePacket( const NetworkBufferDescriptor_t * pxNetworkBuffer ) + { + uint8_t * pucPayLoadBuffer; + size_t uxPayloadSize; + + /* Only proceed if the payload length indicated in the header + * appears to be valid. */ + if( pxNetworkBuffer->xDataLength >= sizeof( UDPPacket_t ) ) + { + uxPayloadSize = pxNetworkBuffer->xDataLength - sizeof( UDPPacket_t ); + + if( uxPayloadSize >= sizeof( DNSMessage_t ) ) + { + pucPayLoadBuffer = &( pxNetworkBuffer->pucEthernetBuffer[ sizeof( UDPPacket_t ) ] ); + + /* The parameter pdFALSE indicates that the reply was not expected. */ + ( void ) prvParseDNSReply( pucPayLoadBuffer, + uxPayloadSize, + pdFALSE ); + } + } + + /* The packet was not consumed. */ + return pdFAIL; + } + /*-----------------------------------------------------------*/ + + + #if ( ipconfigUSE_NBNS == 1 ) + +/** + * @brief Handle an NBNS packet. + * + * @param[in] pxNetworkBuffer: The network buffer holding the NBNS packet. + * + * @return pdFAIL to show that the packet was not consumed. + */ + uint32_t ulNBNSHandlePacket( NetworkBufferDescriptor_t * pxNetworkBuffer ) + { + UDPPacket_t * pxUDPPacket = ipCAST_PTR_TO_TYPE_PTR( UDPPacket_t, pxNetworkBuffer->pucEthernetBuffer ); + uint8_t * pucUDPPayloadBuffer = &( pxNetworkBuffer->pucEthernetBuffer[ sizeof( *pxUDPPacket ) ] ); + + prvTreatNBNS( pucUDPPayloadBuffer, + pxNetworkBuffer->xDataLength, + pxUDPPacket->xIPHeader.ulSourceIPAddress ); + + /* The packet was not consumed. */ + return pdFAIL; + } + + #endif /* ipconfigUSE_NBNS */ + /*-----------------------------------------------------------*/ + +/** + * @brief Process a response packet from a DNS server, or an LLMNR reply. + * + * @param[in] pucUDPPayloadBuffer: The DNS response received as a UDP + * payload. + * @param[in] uxBufferLength: Length of the UDP payload buffer. + * @param[in] xExpected: indicates whether the identifier in the reply + * was expected, and thus if the DNS cache may be + * updated with the reply. + * + * @return The IP address in the DNS response if present and if xExpected is set to pdTRUE. + * An error code (dnsPARSE_ERROR) if there was an error in the DNS response. + * 0 if xExpected set to pdFALSE. + */ + _static uint32_t prvParseDNSReply( uint8_t * pucUDPPayloadBuffer, + size_t uxBufferLength, + BaseType_t xExpected ) + { + DNSMessage_t * pxDNSMessageHeader; + /* This pointer is not used to modify anything */ + const DNSAnswerRecord_t * pxDNSAnswerRecord; + uint32_t ulIPAddress = 0UL; + + #if ( ipconfigUSE_LLMNR == 1 ) + char * pcRequestedName = NULL; + #endif + uint8_t * pucByte; + size_t uxSourceBytesRemaining; + uint16_t x, usDataLength, usQuestions; + uint16_t usType = 0U; + BaseType_t xReturn = pdTRUE; + /* memcpy() helper variables for MISRA Rule 21.15 compliance*/ + const void * pvCopySource; + void * pvCopyDest; + + #if ( ipconfigUSE_LLMNR == 1 ) + uint16_t usClass = 0U; + #endif + #if ( ipconfigUSE_DNS_CACHE == 1 ) || ( ipconfigDNS_USE_CALLBACKS == 1 ) + BaseType_t xDoStore = xExpected; + char pcName[ ipconfigDNS_CACHE_NAME_LENGTH ] = ""; + #endif + const size_t uxAddressLength = ipSIZE_OF_IPv4_ADDRESS; + + /* Ensure that the buffer is of at least minimal DNS message length. */ + if( uxBufferLength < sizeof( DNSMessage_t ) ) + { + xReturn = pdFALSE; + } + else + { + uxSourceBytesRemaining = uxBufferLength; + + /* Parse the DNS message header. Map the byte stream onto a structure + * for easier access. */ + pxDNSMessageHeader = ipCAST_PTR_TO_TYPE_PTR( DNSMessage_t, pucUDPPayloadBuffer ); + + /* Introduce a do {} while (0) to allow the use of breaks. */ + do + { + size_t uxBytesRead = 0U; + size_t uxResult; + + /* Start at the first byte after the header. */ + pucByte = &( pucUDPPayloadBuffer[ sizeof( DNSMessage_t ) ] ); + uxSourceBytesRemaining -= sizeof( DNSMessage_t ); + + /* Skip any question records. */ + usQuestions = FreeRTOS_ntohs( pxDNSMessageHeader->usQuestions ); + + for( x = 0U; x < usQuestions; x++ ) + { + #if ( ipconfigUSE_LLMNR == 1 ) + { + if( x == 0U ) + { + pcRequestedName = ( char * ) pucByte; + } + } + #endif + + #if ( ipconfigUSE_DNS_CACHE == 1 ) || ( ipconfigDNS_USE_CALLBACKS == 1 ) + if( x == 0U ) + { + uxResult = prvReadNameField( pucByte, + uxSourceBytesRemaining, + pcName, + sizeof( pcName ) ); + + /* Check for a malformed response. */ + if( uxResult == 0U ) + { + xReturn = pdFALSE; + break; + } + + uxBytesRead += uxResult; + pucByte = &( pucByte[ uxResult ] ); + uxSourceBytesRemaining -= uxResult; + } + else + #endif /* ipconfigUSE_DNS_CACHE || ipconfigDNS_USE_CALLBACKS */ + { + /* Skip the variable length pcName field. */ + uxResult = prvSkipNameField( pucByte, + uxSourceBytesRemaining ); + + /* Check for a malformed response. */ + if( uxResult == 0U ) + { + xReturn = pdFALSE; + break; + } + + uxBytesRead += uxResult; + pucByte = &( pucByte[ uxResult ] ); + uxSourceBytesRemaining -= uxResult; + } + + /* Check the remaining buffer size. */ + if( uxSourceBytesRemaining >= sizeof( uint32_t ) ) + { + #if ( ipconfigUSE_LLMNR == 1 ) + { + /* usChar2u16 returns value in host endianness. */ + usType = usChar2u16( pucByte ); + usClass = usChar2u16( &( pucByte[ 2 ] ) ); + } + #endif /* ipconfigUSE_LLMNR */ + + /* Skip the type and class fields. */ + pucByte = &( pucByte[ sizeof( uint32_t ) ] ); + uxSourceBytesRemaining -= sizeof( uint32_t ); + } + else + { + xReturn = pdFALSE; + break; + } + } + + if( xReturn == pdFALSE ) + { + /* No need to proceed. Break out of the do-while loop. */ + break; + } + + /* Search through the answer records. */ + pxDNSMessageHeader->usAnswers = FreeRTOS_ntohs( pxDNSMessageHeader->usAnswers ); + + if( ( pxDNSMessageHeader->usFlags & dnsRX_FLAGS_MASK ) == dnsEXPECTED_RX_FLAGS ) + { + const uint16_t usCount = ( uint16_t ) ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY; + uint16_t usNumARecordsStored = 0; + + for( x = 0U; x < pxDNSMessageHeader->usAnswers; x++ ) + { + BaseType_t xDoAccept; + + if( usNumARecordsStored >= usCount ) + { + /* Only count ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY number of records. */ + break; + } + + uxResult = prvSkipNameField( pucByte, + uxSourceBytesRemaining ); + + /* Check for a malformed response. */ + if( uxResult == 0U ) + { + xReturn = pdFALSE; + break; + } + + uxBytesRead += uxResult; + pucByte = &( pucByte[ uxResult ] ); + uxSourceBytesRemaining -= uxResult; + + /* Is there enough data for an IPv4 A record answer and, if so, + * is this an A record? */ + if( uxSourceBytesRemaining < sizeof( uint16_t ) ) + { + xReturn = pdFALSE; + break; + } + + usType = usChar2u16( pucByte ); + + if( usType == ( uint16_t ) dnsTYPE_A_HOST ) + { + if( uxSourceBytesRemaining >= ( sizeof( DNSAnswerRecord_t ) + uxAddressLength ) ) + { + xDoAccept = pdTRUE; + } + else + { + xDoAccept = pdFALSE; + } + } + else + { + /* Unknown host type. */ + xDoAccept = pdFALSE; + } + + if( xDoAccept != pdFALSE ) + { + /* This is the required record type and is of sufficient size. */ + + /* Mapping pucByte to a DNSAnswerRecord allows easy access of the + * fields of the structure. */ + pxDNSAnswerRecord = ipCAST_PTR_TO_TYPE_PTR( DNSAnswerRecord_t, pucByte ); + + /* Sanity check the data length of an IPv4 answer. */ + if( FreeRTOS_ntohs( pxDNSAnswerRecord->usDataLength ) == ( uint16_t ) uxAddressLength ) + { + /* Copy the IP address out of the record. Using different pointers + * to copy only the portion we want is intentional here. */ + + /* + * Use helper variables for memcpy() to remain + * compliant with MISRA Rule 21.15. These should be + * optimized away. + */ + pvCopySource = &pucByte[ sizeof( DNSAnswerRecord_t ) ]; + pvCopyDest = &ulIPAddress; + ( void ) memcpy( pvCopyDest, pvCopySource, uxAddressLength ); + + #if ( ipconfigDNS_USE_CALLBACKS == 1 ) + { + /* See if any asynchronous call was made to FreeRTOS_gethostbyname_a() */ + if( xDNSDoCallback( ( TickType_t ) pxDNSMessageHeader->usIdentifier, pcName, ulIPAddress ) != pdFALSE ) + { + /* This device has requested this DNS look-up. + * The result may be stored in the DNS cache. */ + xDoStore = pdTRUE; + } + } + #endif /* ipconfigDNS_USE_CALLBACKS == 1 */ + #if ( ipconfigUSE_DNS_CACHE == 1 ) + { + char cBuffer[ 16 ]; + + /* The reply will only be stored in the DNS cache when the + * request was issued by this device. */ + if( xDoStore != pdFALSE ) + { + ( void ) prvProcessDNSCache( pcName, &ulIPAddress, pxDNSAnswerRecord->ulTTL, pdFALSE ); + usNumARecordsStored++; /* Track # of A records stored */ + } + + ( void ) FreeRTOS_inet_ntop( FREERTOS_AF_INET, ( const void * ) &( ulIPAddress ), cBuffer, sizeof( cBuffer ) ); + /* Show what has happened. */ + FreeRTOS_printf( ( "DNS[0x%04lX]: The answer to '%s' (%s) will%s be stored\n", + ( UBaseType_t ) pxDNSMessageHeader->usIdentifier, + pcName, + cBuffer, + ( xDoStore != 0 ) ? "" : " NOT" ) ); + } + #endif /* ipconfigUSE_DNS_CACHE */ + } + + pucByte = &( pucByte[ sizeof( DNSAnswerRecord_t ) + uxAddressLength ] ); + uxSourceBytesRemaining -= ( sizeof( DNSAnswerRecord_t ) + uxAddressLength ); + } + else if( uxSourceBytesRemaining >= sizeof( DNSAnswerRecord_t ) ) + { + /* It's not an A record, so skip it. Get the header location + * and then jump over the header. */ + /* Cast the response to DNSAnswerRecord for easy access to fields of the DNS response. */ + pxDNSAnswerRecord = ipCAST_PTR_TO_TYPE_PTR( DNSAnswerRecord_t, pucByte ); + + pucByte = &( pucByte[ sizeof( DNSAnswerRecord_t ) ] ); + uxSourceBytesRemaining -= sizeof( DNSAnswerRecord_t ); + + /* Determine the length of the answer data from the header. */ + usDataLength = FreeRTOS_ntohs( pxDNSAnswerRecord->usDataLength ); + + /* Jump over the answer. */ + if( uxSourceBytesRemaining >= usDataLength ) + { + pucByte = &( pucByte[ usDataLength ] ); + uxSourceBytesRemaining -= usDataLength; + } + else + { + /* Malformed response. */ + xReturn = pdFALSE; + break; + } + } + else + { + /* Do nothing */ + } + } + } + + #if ( ipconfigUSE_LLMNR == 1 ) + else if( ( usQuestions != ( uint16_t ) 0U ) && ( usType == dnsTYPE_A_HOST ) && ( usClass == dnsCLASS_IN ) && ( pcRequestedName != NULL ) ) + { + /* If this is not a reply to our DNS request, it might an LLMNR + * request. */ + if( xApplicationDNSQueryHook( &( pcRequestedName[ 1 ] ) ) != pdFALSE ) + { + int16_t usLength; + NetworkBufferDescriptor_t * pxNewBuffer = NULL; + NetworkBufferDescriptor_t * pxNetworkBuffer = pxUDPPayloadBuffer_to_NetworkBuffer( pucUDPPayloadBuffer ); + LLMNRAnswer_t * pxAnswer; + uint8_t * pucNewBuffer = NULL; + + if( ( xBufferAllocFixedSize == pdFALSE ) && ( pxNetworkBuffer != NULL ) ) + { + size_t uxDataLength = uxBufferLength + sizeof( UDPHeader_t ) + sizeof( EthernetHeader_t ) + sizeof( IPHeader_t ); + + /* Set the size of the outgoing packet. */ + pxNetworkBuffer->xDataLength = uxDataLength; + pxNewBuffer = pxDuplicateNetworkBufferWithDescriptor( pxNetworkBuffer, uxDataLength + sizeof( LLMNRAnswer_t ) ); + + if( pxNewBuffer != NULL ) + { + BaseType_t xOffset1, xOffset2; + + xOffset1 = ( BaseType_t ) ( pucByte - pucUDPPayloadBuffer ); + xOffset2 = ( BaseType_t ) ( ( ( uint8_t * ) pcRequestedName ) - pucUDPPayloadBuffer ); + + pxNetworkBuffer = pxNewBuffer; + pucNewBuffer = &( pxNetworkBuffer->pucEthernetBuffer[ ipUDP_PAYLOAD_OFFSET_IPv4 ] ); + + pucByte = &( pucNewBuffer[ xOffset1 ] ); + pcRequestedName = ( char * ) &( pucNewBuffer[ xOffset2 ] ); + pxDNSMessageHeader = ipCAST_PTR_TO_TYPE_PTR( DNSMessage_t, pucNewBuffer ); + } + else + { + /* Just to indicate that the message may not be answered. */ + pxNetworkBuffer = NULL; + } + } + + /* The test on 'pucNewBuffer' is only to satisfy lint. */ + if( ( pxNetworkBuffer != NULL ) && ( pucNewBuffer != NULL ) ) + { + pxAnswer = ipCAST_PTR_TO_TYPE_PTR( LLMNRAnswer_t, pucByte ); + + /* We leave 'usIdentifier' and 'usQuestions' untouched */ + #ifndef _lint + vSetField16( pxDNSMessageHeader, DNSMessage_t, usFlags, dnsLLMNR_FLAGS_IS_REPONSE ); /* Set the response flag */ + vSetField16( pxDNSMessageHeader, DNSMessage_t, usAnswers, 1 ); /* Provide a single answer */ + vSetField16( pxDNSMessageHeader, DNSMessage_t, usAuthorityRRs, 0 ); /* No authority */ + vSetField16( pxDNSMessageHeader, DNSMessage_t, usAdditionalRRs, 0 ); /* No additional info */ + #endif /* lint */ + + pxAnswer->ucNameCode = dnsNAME_IS_OFFSET; + pxAnswer->ucNameOffset = ( uint8_t ) ( pcRequestedName - ( char * ) pucNewBuffer ); + + #ifndef _lint + vSetField16( pxAnswer, LLMNRAnswer_t, usType, dnsTYPE_A_HOST ); /* Type A: host */ + vSetField16( pxAnswer, LLMNRAnswer_t, usClass, dnsCLASS_IN ); /* 1: Class IN */ + vSetField32( pxAnswer, LLMNRAnswer_t, ulTTL, dnsLLMNR_TTL_VALUE ); + vSetField16( pxAnswer, LLMNRAnswer_t, usDataLength, 4 ); + vSetField32( pxAnswer, LLMNRAnswer_t, ulIPAddress, FreeRTOS_ntohl( *ipLOCAL_IP_ADDRESS_POINTER ) ); + #endif /* lint */ + usLength = ( int16_t ) ( sizeof( *pxAnswer ) + ( size_t ) ( pucByte - pucNewBuffer ) ); + + prvReplyDNSMessage( pxNetworkBuffer, usLength ); + + if( pxNewBuffer != NULL ) + { + vReleaseNetworkBufferAndDescriptor( pxNewBuffer ); + } + } + } + } + else + { + /* Not an expected reply. */ + } + #endif /* ipconfigUSE_LLMNR == 1 */ + ( void ) uxBytesRead; + } while( ipFALSE_BOOL ); + } + + if( xReturn == pdFALSE ) + { + /* There was an error while parsing the DNS response. Return error code. */ + ulIPAddress = dnsPARSE_ERROR; + } + else if( xExpected == pdFALSE ) + { + /* Do not return a valid IP-address in case the reply was not expected. */ + ulIPAddress = 0UL; + } + else + { + /* The IP-address found will be returned. */ + } + + #if ( ipconfigUSE_DNS_CACHE == 1 ) || ( ipconfigDNS_USE_CALLBACKS == 1 ) + ( void ) xDoStore; + #endif + + return ulIPAddress; + } + /*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_NBNS == 1 ) + +/** + * @brief Respond to an NBNS query or an NBNS reply. + * + * @param[in] pucPayload: the UDP payload of the NBNS message. + * @param[in] uxBufferLength: Length of the Buffer. + * @param[in] ulIPAddress: IP address of the sender. + */ + static void prvTreatNBNS( uint8_t * pucPayload, + size_t uxBufferLength, + uint32_t ulIPAddress ) + { + uint16_t usFlags, usType, usClass; + uint8_t * pucSource, * pucTarget; + uint8_t ucByte; + uint8_t ucNBNSName[ 17 ]; + uint8_t * pucUDPPayloadBuffer = pucPayload; + NetworkBufferDescriptor_t * pxNetworkBuffer; + size_t uxBytesNeeded = sizeof( UDPPacket_t ) + sizeof( NBNSRequest_t ); + + /* Check for minimum buffer size. */ + if( uxBufferLength < uxBytesNeeded ) + { + return; + } + + /* Read the request flags in host endianness. */ + usFlags = usChar2u16( &( pucUDPPayloadBuffer[ offsetof( NBNSRequest_t, usFlags ) ] ) ); + + if( ( usFlags & dnsNBNS_FLAGS_OPCODE_MASK ) == dnsNBNS_FLAGS_OPCODE_QUERY ) + { + usType = usChar2u16( &( pucUDPPayloadBuffer[ offsetof( NBNSRequest_t, usType ) ] ) ); + usClass = usChar2u16( &( pucUDPPayloadBuffer[ offsetof( NBNSRequest_t, usClass ) ] ) ); + + /* Not used for now */ + ( void ) usClass; + + /* For NBNS a name is 16 bytes long, written with capitals only. + * Make sure that the copy is terminated with a zero. */ + pucTarget = &( ucNBNSName[ sizeof( ucNBNSName ) - 2U ] ); + pucTarget[ 1 ] = ( uint8_t ) 0U; + + /* Start with decoding the last 2 bytes. */ + pucSource = &( pucUDPPayloadBuffer[ ( dnsNBNS_ENCODED_NAME_LENGTH - 2 ) + offsetof( NBNSRequest_t, ucName ) ] ); + + for( ; ; ) + { + const uint8_t ucCharA = ( uint8_t ) 0x41U; + + ucByte = ( ( uint8_t ) ( ( pucSource[ 0 ] - ucCharA ) << 4 ) ) | ( pucSource[ 1 ] - ucCharA ); + + /* Make sure there are no trailing spaces in the name. */ + if( ( ucByte == ( uint8_t ) ' ' ) && ( pucTarget[ 1 ] == 0U ) ) + { + ucByte = 0U; + } + + *pucTarget = ucByte; + + if( pucTarget == ucNBNSName ) + { + break; + } + + pucTarget -= 1; + pucSource -= 2; + } + + #if ( ipconfigUSE_DNS_CACHE == 1 ) + { + if( ( usFlags & dnsNBNS_FLAGS_RESPONSE ) != 0U ) + { + /* If this is a response from another device, + * add the name to the DNS cache */ + ( void ) prvProcessDNSCache( ( char * ) ucNBNSName, &( ulIPAddress ), 0, pdFALSE ); + } + } + #else + { + /* Avoid compiler warnings. */ + ( void ) ulIPAddress; + } + #endif /* ipconfigUSE_DNS_CACHE */ + + if( ( ( usFlags & dnsNBNS_FLAGS_RESPONSE ) == 0U ) && + ( usType == dnsNBNS_TYPE_NET_BIOS ) && + ( xApplicationDNSQueryHook( ( const char * ) ucNBNSName ) != pdFALSE ) ) + { + uint16_t usLength; + DNSMessage_t * pxMessage; + NBNSAnswer_t * pxAnswer; + + /* Someone is looking for a device with ucNBNSName, + * prepare a positive reply. */ + pxNetworkBuffer = pxUDPPayloadBuffer_to_NetworkBuffer( pucUDPPayloadBuffer ); + + if( ( xBufferAllocFixedSize == pdFALSE ) && ( pxNetworkBuffer != NULL ) ) + { + NetworkBufferDescriptor_t * pxNewBuffer; + + /* The field xDataLength was set to the total length of the UDP packet, + * i.e. the payload size plus sizeof( UDPPacket_t ). */ + pxNewBuffer = pxDuplicateNetworkBufferWithDescriptor( pxNetworkBuffer, pxNetworkBuffer->xDataLength + sizeof( NBNSAnswer_t ) ); + + if( pxNewBuffer != NULL ) + { + pucUDPPayloadBuffer = &( pxNewBuffer->pucEthernetBuffer[ sizeof( UDPPacket_t ) ] ); + pxNetworkBuffer = pxNewBuffer; + } + else + { + /* Just prevent that a reply will be sent */ + pxNetworkBuffer = NULL; + } + } + + /* Should not occur: pucUDPPayloadBuffer is part of a xNetworkBufferDescriptor */ + if( pxNetworkBuffer != NULL ) + { + pxMessage = ipCAST_PTR_TO_TYPE_PTR( DNSMessage_t, pucUDPPayloadBuffer ); + + /* As the fields in the structures are not word-aligned, we have to + * copy the values byte-by-byte using macro's vSetField16() and vSetField32() */ + #ifndef _lint + vSetField16( pxMessage, DNSMessage_t, usFlags, dnsNBNS_QUERY_RESPONSE_FLAGS ); /* 0x8500 */ + vSetField16( pxMessage, DNSMessage_t, usQuestions, 0 ); + vSetField16( pxMessage, DNSMessage_t, usAnswers, 1 ); + vSetField16( pxMessage, DNSMessage_t, usAuthorityRRs, 0 ); + vSetField16( pxMessage, DNSMessage_t, usAdditionalRRs, 0 ); + #else + ( void ) pxMessage; + #endif + + pxAnswer = ipCAST_PTR_TO_TYPE_PTR( NBNSAnswer_t, &( pucUDPPayloadBuffer[ offsetof( NBNSRequest_t, usType ) ] ) ); + + #ifndef _lint + vSetField16( pxAnswer, NBNSAnswer_t, usType, usType ); /* Type */ + vSetField16( pxAnswer, NBNSAnswer_t, usClass, dnsNBNS_CLASS_IN ); /* Class */ + vSetField32( pxAnswer, NBNSAnswer_t, ulTTL, dnsNBNS_TTL_VALUE ); + vSetField16( pxAnswer, NBNSAnswer_t, usDataLength, 6 ); /* 6 bytes including the length field */ + vSetField16( pxAnswer, NBNSAnswer_t, usNbFlags, dnsNBNS_NAME_FLAGS ); + vSetField32( pxAnswer, NBNSAnswer_t, ulIPAddress, FreeRTOS_ntohl( *ipLOCAL_IP_ADDRESS_POINTER ) ); + #else + ( void ) pxAnswer; + #endif + + usLength = ( uint16_t ) ( sizeof( NBNSAnswer_t ) + ( size_t ) offsetof( NBNSRequest_t, usType ) ); + + prvReplyDNSMessage( pxNetworkBuffer, ( BaseType_t ) usLength ); + } + } + } + } + + #endif /* ipconfigUSE_NBNS */ + /*-----------------------------------------------------------*/ + +/** + * @brief Create a socket and bind it to the standard DNS port number. + * + * @return The created socket - or NULL if the socket could not be created or could not be bound. + */ + static Socket_t prvCreateDNSSocket( void ) + { + Socket_t xSocket; + struct freertos_sockaddr xAddress; + BaseType_t xReturn; + + /* This must be the first time this function has been called. Create + * the socket. */ + xSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_DGRAM, FREERTOS_IPPROTO_UDP ); + + if( xSocketValid( xSocket ) == pdFALSE ) + { + /* There was an error, return NULL. */ + xSocket = NULL; + } + else + { + /* Auto bind the port. */ + xAddress.sin_port = 0U; + xReturn = FreeRTOS_bind( xSocket, &xAddress, sizeof( xAddress ) ); + + /* Check the bind was successful, and clean up if not. */ + if( xReturn != 0 ) + { + ( void ) FreeRTOS_closesocket( xSocket ); + xSocket = NULL; + } + else + { + /* The send and receive timeouts will be set later on. */ + } + } + + return xSocket; + } +/*-----------------------------------------------------------*/ + + #if ( ( ipconfigUSE_NBNS == 1 ) || ( ipconfigUSE_LLMNR == 1 ) ) + +/** + * @brief Send a DNS message to be used in NBNS or LLMNR + * + * @param[in] pxNetworkBuffer: The network buffer descriptor with the DNS message. + * @param[in] lNetLength: The length of the DNS message. + */ + static void prvReplyDNSMessage( NetworkBufferDescriptor_t * pxNetworkBuffer, + BaseType_t lNetLength ) + { + UDPPacket_t * pxUDPPacket; + IPHeader_t * pxIPHeader; + UDPHeader_t * pxUDPHeader; + size_t uxDataLength; + + pxUDPPacket = ipCAST_PTR_TO_TYPE_PTR( UDPPacket_t, pxNetworkBuffer->pucEthernetBuffer ); + pxIPHeader = &pxUDPPacket->xIPHeader; + pxUDPHeader = &pxUDPPacket->xUDPHeader; + /* HT: started using defines like 'ipSIZE_OF_xxx' */ + pxIPHeader->usLength = FreeRTOS_htons( ( uint16_t ) lNetLength + ipSIZE_OF_IPv4_HEADER + ipSIZE_OF_UDP_HEADER ); + /* HT:endian: should not be translated, copying from packet to packet */ + pxIPHeader->ulDestinationIPAddress = pxIPHeader->ulSourceIPAddress; + pxIPHeader->ulSourceIPAddress = *ipLOCAL_IP_ADDRESS_POINTER; + pxIPHeader->ucTimeToLive = ipconfigUDP_TIME_TO_LIVE; + pxIPHeader->usIdentification = FreeRTOS_htons( usPacketIdentifier ); + usPacketIdentifier++; + pxUDPHeader->usLength = FreeRTOS_htons( ( uint32_t ) lNetLength + ipSIZE_OF_UDP_HEADER ); + vFlip_16( pxUDPHeader->usSourcePort, pxUDPHeader->usDestinationPort ); + + /* Important: tell NIC driver how many bytes must be sent */ + uxDataLength = ( ( size_t ) lNetLength ) + ipSIZE_OF_IPv4_HEADER + ipSIZE_OF_UDP_HEADER + ipSIZE_OF_ETH_HEADER; + + #if ( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 ) + { + /* Calculate the IP header checksum. */ + pxIPHeader->usHeaderChecksum = 0U; + pxIPHeader->usHeaderChecksum = usGenerateChecksum( 0U, ( uint8_t * ) &( pxIPHeader->ucVersionHeaderLength ), ipSIZE_OF_IPv4_HEADER ); + pxIPHeader->usHeaderChecksum = ~FreeRTOS_htons( pxIPHeader->usHeaderChecksum ); + + /* calculate the UDP checksum for outgoing package */ + ( void ) usGenerateProtocolChecksum( ( uint8_t * ) pxUDPPacket, uxDataLength, pdTRUE ); + } + #endif + + /* Important: tell NIC driver how many bytes must be sent */ + pxNetworkBuffer->xDataLength = uxDataLength; + + /* This function will fill in the eth addresses and send the packet */ + vReturnEthernetFrame( pxNetworkBuffer, pdFALSE ); + } + + #endif /* ipconfigUSE_NBNS == 1 || ipconfigUSE_LLMNR == 1 */ + +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_DNS_CACHE == 1 ) + +/** + * @brief Send a DNS message to be used in NBNS or LLMNR + * + * @param[in] pcName: the name of the host + * @param[in,out] pulIP: when doing a lookup, will be set, when doing an update, + * will be read. + * @param[in] ulTTL: Time To Live + * @param[in] xLookUp: pdTRUE if a look-up is expected, pdFALSE, when the DNS cache must + * be updated. + * + * @return + */ + static BaseType_t prvProcessDNSCache( const char * pcName, + uint32_t * pulIP, + uint32_t ulTTL, + BaseType_t xLookUp ) + { + BaseType_t x; + BaseType_t xFound = pdFALSE; + uint32_t ulCurrentTimeSeconds = ( xTaskGetTickCount() / portTICK_PERIOD_MS ) / 1000UL; + uint32_t ulIPAddressIndex = 0; + static BaseType_t xFreeEntry = 0; + + configASSERT( ( pcName != NULL ) ); + + /* For each entry in the DNS cache table. */ + for( x = 0; x < ipconfigDNS_CACHE_ENTRIES; x++ ) + { + if( xDNSCache[ x ].pcName[ 0 ] == ( char ) 0 ) + { + continue; + } + + if( strcmp( xDNSCache[ x ].pcName, pcName ) == 0 ) + { + /* Is this function called for a lookup or to add/update an IP address? */ + if( xLookUp != pdFALSE ) + { + /* Confirm that the record is still fresh. */ + if( ulCurrentTimeSeconds < ( xDNSCache[ x ].ulTimeWhenAddedInSeconds + FreeRTOS_ntohl( xDNSCache[ x ].ulTTL ) ) ) + { + #if ( ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY > 1 ) + uint8_t ucIndex; + /* The ucCurrentIPAddress value increments without bound and will rollover, */ + /* modulo it by the number of IP addresses to keep it in range. */ + /* Also perform a final modulo by the max number of IP addresses */ + /* per DNS cache entry to prevent out-of-bounds access in the event */ + /* that ucNumIPAddresses has been corrupted. */ + ucIndex = xDNSCache[ x ].ucCurrentIPAddress % xDNSCache[ x ].ucNumIPAddresses; + ucIndex = ucIndex % ( uint8_t ) ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY; + ulIPAddressIndex = ucIndex; + + xDNSCache[ x ].ucCurrentIPAddress++; + #endif /* if ( ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY > 1 ) */ + *pulIP = xDNSCache[ x ].ulIPAddresses[ ulIPAddressIndex ]; + } + else + { + /* Age out the old cached record. */ + xDNSCache[ x ].pcName[ 0 ] = ( char ) 0; + } + } + else + { + #if ( ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY > 1 ) + if( xDNSCache[ x ].ucNumIPAddresses < ( uint8_t ) ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY ) + { + /* If more answers exist than there are IP address storage slots */ + /* they will overwrite entry 0 */ + + ulIPAddressIndex = xDNSCache[ x ].ucNumIPAddresses; + xDNSCache[ x ].ucNumIPAddresses++; + } + #endif + xDNSCache[ x ].ulIPAddresses[ ulIPAddressIndex ] = *pulIP; + xDNSCache[ x ].ulTTL = ulTTL; + xDNSCache[ x ].ulTimeWhenAddedInSeconds = ulCurrentTimeSeconds; + } + + xFound = pdTRUE; + break; + } + } + + if( xFound == pdFALSE ) + { + if( xLookUp != pdFALSE ) + { + *pulIP = 0UL; + } + else + { + /* Add or update the item. */ + if( strlen( pcName ) < ( size_t ) ipconfigDNS_CACHE_NAME_LENGTH ) + { + ( void ) strcpy( xDNSCache[ xFreeEntry ].pcName, pcName ); + + xDNSCache[ xFreeEntry ].ulIPAddresses[ 0 ] = *pulIP; + xDNSCache[ xFreeEntry ].ulTTL = ulTTL; + xDNSCache[ xFreeEntry ].ulTimeWhenAddedInSeconds = ulCurrentTimeSeconds; + #if ( ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY > 1 ) + xDNSCache[ xFreeEntry ].ucNumIPAddresses = 1; + xDNSCache[ xFreeEntry ].ucCurrentIPAddress = 0; + + /* Initialize all remaining IP addresses in this entry to 0 */ + ( void ) memset( &xDNSCache[ xFreeEntry ].ulIPAddresses[ 1 ], + 0, + sizeof( xDNSCache[ xFreeEntry ].ulIPAddresses[ 1 ] ) * + ( ( uint32_t ) ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY - 1U ) ); + #endif + + xFreeEntry++; + + if( xFreeEntry == ipconfigDNS_CACHE_ENTRIES ) + { + xFreeEntry = 0; + } + } + } + } + + if( ( xLookUp == 0 ) || ( *pulIP != 0UL ) ) + { + FreeRTOS_debug_printf( ( "prvProcessDNSCache: %s: '%s' @ %lxip\n", ( xLookUp != 0 ) ? "look-up" : "add", pcName, FreeRTOS_ntohl( *pulIP ) ) ); + } + + return xFound; + } + + #endif /* ipconfigUSE_DNS_CACHE */ + +#endif /* ipconfigUSE_DNS != 0 */ + +/*-----------------------------------------------------------*/ + +/* Provide access to private members for testing. */ +#ifdef FREERTOS_ENABLE_UNIT_TESTS + #include "freertos_tcp_test_access_dns_define.h" +#endif diff --git a/examples/stm32/freertos-tcp/FreeRTOS_IP.c b/examples/stm32/freertos-tcp/FreeRTOS_IP.c new file mode 100644 index 00000000..9b57525c --- /dev/null +++ b/examples/stm32/freertos-tcp/FreeRTOS_IP.c @@ -0,0 +1,3418 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +/** + * @file FreeRTOS_IP.c + * @brief Implements the basic functionality for the FreeRTOS+TCP network stack. + */ + +/* Standard includes. */ +#include +#include +#include + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" +#include "semphr.h" + +/* FreeRTOS+TCP includes. */ +#include "FreeRTOS_IP.h" +#include "FreeRTOS_Sockets.h" +#include "FreeRTOS_IP_Private.h" +#include "FreeRTOS_ARP.h" +#include "FreeRTOS_UDP_IP.h" +#include "FreeRTOS_DHCP.h" +#include "NetworkInterface.h" +#include "NetworkBufferManagement.h" +#include "FreeRTOS_DNS.h" + + +/* Used to ensure the structure packing is having the desired effect. The + * 'volatile' is used to prevent compiler warnings about comparing a constant with + * a constant. */ +#ifndef _lint + #define ipEXPECTED_EthernetHeader_t_SIZE ( ( size_t ) 14 ) /**< Ethernet Header size in bytes. */ + #define ipEXPECTED_ARPHeader_t_SIZE ( ( size_t ) 28 ) /**< ARP header size in bytes. */ + #define ipEXPECTED_IPHeader_t_SIZE ( ( size_t ) 20 ) /**< IP header size in bytes. */ + #define ipEXPECTED_IGMPHeader_t_SIZE ( ( size_t ) 8 ) /**< IGMP header size in bytes. */ + #define ipEXPECTED_ICMPHeader_t_SIZE ( ( size_t ) 8 ) /**< ICMP header size in bytes. */ + #define ipEXPECTED_UDPHeader_t_SIZE ( ( size_t ) 8 ) /**< UDP header size in bytes. */ + #define ipEXPECTED_TCPHeader_t_SIZE ( ( size_t ) 20 ) /**< TCP header size in bytes. */ +#endif + +/* ICMP protocol definitions. */ +#define ipICMP_ECHO_REQUEST ( ( uint8_t ) 8 ) /**< ICMP echo request. */ +#define ipICMP_ECHO_REPLY ( ( uint8_t ) 0 ) /**< ICMP echo reply. */ + +/* IPv4 multi-cast addresses range from 224.0.0.0.0 to 240.0.0.0. */ +#define ipFIRST_MULTI_CAST_IPv4 0xE0000000UL /**< Lower bound of the IPv4 multicast address. */ +#define ipLAST_MULTI_CAST_IPv4 0xF0000000UL /**< Higher bound of the IPv4 multicast address. */ + +/* The first byte in the IPv4 header combines the IP version (4) with + * with the length of the IP header. */ +#define ipIPV4_VERSION_HEADER_LENGTH_MIN 0x45U /**< Minimum IPv4 header length. */ +#define ipIPV4_VERSION_HEADER_LENGTH_MAX 0x4FU /**< Maximum IPv4 header length. */ + +/** @brief Time delay between repeated attempts to initialise the network hardware. */ +#ifndef ipINITIALISATION_RETRY_DELAY + #define ipINITIALISATION_RETRY_DELAY ( pdMS_TO_TICKS( 3000U ) ) +#endif + +/** @brief Defines how often the ARP timer callback function is executed. The time is + * shorter in the Windows simulator as simulated time is not real time. */ +#ifndef ipARP_TIMER_PERIOD_MS + #ifdef _WINDOWS_ + #define ipARP_TIMER_PERIOD_MS ( 500U ) /* For windows simulator builds. */ + #else + #define ipARP_TIMER_PERIOD_MS ( 10000U ) + #endif +#endif + +#ifndef iptraceIP_TASK_STARTING + #define iptraceIP_TASK_STARTING() do {} while( ipFALSE_BOOL ) /**< Empty definition in case iptraceIP_TASK_STARTING is not defined. */ +#endif + +#if ( ( ipconfigUSE_TCP == 1 ) && !defined( ipTCP_TIMER_PERIOD_MS ) ) + /** @brief When initialising the TCP timer, give it an initial time-out of 1 second. */ + #define ipTCP_TIMER_PERIOD_MS ( 1000U ) +#endif + +/** @brief If ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES is set to 1, then the Ethernet + * driver will filter incoming packets and only pass the stack those packets it + * considers need processing. In this case ipCONSIDER_FRAME_FOR_PROCESSING() can + * be #-defined away. If ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES is set to 0 + * then the Ethernet driver will pass all received packets to the stack, and the + * stack must do the filtering itself. In this case ipCONSIDER_FRAME_FOR_PROCESSING + * needs to call eConsiderFrameForProcessing. + */ +#if ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES == 0 + #define ipCONSIDER_FRAME_FOR_PROCESSING( pucEthernetBuffer ) eConsiderFrameForProcessing( ( pucEthernetBuffer ) ) +#else + #define ipCONSIDER_FRAME_FOR_PROCESSING( pucEthernetBuffer ) eProcessBuffer +#endif + +#if ( ipconfigETHERNET_DRIVER_FILTERS_PACKETS == 0 ) + #if ( ipconfigBYTE_ORDER == pdFREERTOS_LITTLE_ENDIAN ) + /** @brief The bits in the two byte IP header field that make up the fragment offset value. */ + #define ipFRAGMENT_OFFSET_BIT_MASK ( ( uint16_t ) 0xff0f ) + #else + /** @brief The bits in the two byte IP header field that make up the fragment offset value. */ + #define ipFRAGMENT_OFFSET_BIT_MASK ( ( uint16_t ) 0x0fff ) + #endif /* ipconfigBYTE_ORDER */ +#endif /* ipconfigETHERNET_DRIVER_FILTERS_PACKETS */ + +/** @brief The maximum time the IP task is allowed to remain in the Blocked state if no + * events are posted to the network event queue. */ +#ifndef ipconfigMAX_IP_TASK_SLEEP_TIME + #define ipconfigMAX_IP_TASK_SLEEP_TIME ( pdMS_TO_TICKS( 10000UL ) ) +#endif + +/** @brief Returned as the (invalid) checksum when the protocol being checked is not + * handled. The value is chosen simply to be easy to spot when debugging. */ +#define ipUNHANDLED_PROTOCOL 0x4321U + +/** @brief Returned to indicate a valid checksum. */ +#define ipCORRECT_CRC 0xffffU + +/** @brief Returned to indicate incorrect checksum. */ +#define ipWRONG_CRC 0x0000U + +/** @brief Returned as the (invalid) checksum when the length of the data being checked + * had an invalid length. */ +#define ipINVALID_LENGTH 0x1234U + +/* Trace macros to aid in debugging, disabled if ipconfigHAS_PRINTF != 1 */ +#if ( ipconfigHAS_PRINTF == 1 ) + #define DEBUG_DECLARE_TRACE_VARIABLE( type, var, init ) type var = ( init ) /**< Trace macro to set "type var = init". */ + #define DEBUG_SET_TRACE_VARIABLE( var, value ) var = ( value ) /**< Trace macro to set var = value. */ +#else + #define DEBUG_DECLARE_TRACE_VARIABLE( type, var, init ) /**< Empty definition since ipconfigHAS_PRINTF != 1. */ + #define DEBUG_SET_TRACE_VARIABLE( var, value ) /**< Empty definition since ipconfigHAS_PRINTF != 1. */ +#endif + +/*-----------------------------------------------------------*/ + +/** + * Used in checksum calculation. + */ +typedef union _xUnion32 +{ + uint32_t u32; /**< The 32-bit member of the union. */ + uint16_t u16[ 2 ]; /**< The array of 2 16-bit members of the union. */ + uint8_t u8[ 4 ]; /**< The array of 4 8-bit members of the union. */ +} xUnion32; + +/** + * Used in checksum calculation. + */ +typedef union _xUnionPtr +{ + uint32_t * u32ptr; /**< The pointer member to a 32-bit variable. */ + uint16_t * u16ptr; /**< The pointer member to a 16-bit variable. */ + uint8_t * u8ptr; /**< The pointer member to an 8-bit variable. */ +} xUnionPtr; + + +/** + * @brief Utility function to cast pointer of a type to pointer of type NetworkBufferDescriptor_t. + * + * @return The casted pointer. + */ +static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( NetworkBufferDescriptor_t ) +{ + return ( NetworkBufferDescriptor_t * ) pvArgument; +} + +/*-----------------------------------------------------------*/ + +/* + * The main TCP/IP stack processing task. This task receives commands/events + * from the network hardware drivers and tasks that are using sockets. It also + * maintains a set of protocol timers. + */ +static void prvIPTask( void * pvParameters ); + +/* + * Called when new data is available from the network interface. + */ +static void prvProcessEthernetPacket( NetworkBufferDescriptor_t * const pxNetworkBuffer ); + +/* + * Process incoming IP packets. + */ +static eFrameProcessingResult_t prvProcessIPPacket( IPPacket_t * pxIPPacket, + NetworkBufferDescriptor_t * const pxNetworkBuffer ); + +#if ( ipconfigREPLY_TO_INCOMING_PINGS == 1 ) || ( ipconfigSUPPORT_OUTGOING_PINGS == 1 ) + +/* + * Process incoming ICMP packets. + */ + static eFrameProcessingResult_t prvProcessICMPPacket( ICMPPacket_t * const pxICMPPacket ); +#endif /* ( ipconfigREPLY_TO_INCOMING_PINGS == 1 ) || ( ipconfigSUPPORT_OUTGOING_PINGS == 1 ) */ + +/* + * Turns around an incoming ping request to convert it into a ping reply. + */ +#if ( ipconfigREPLY_TO_INCOMING_PINGS == 1 ) + static eFrameProcessingResult_t prvProcessICMPEchoRequest( ICMPPacket_t * const pxICMPPacket ); +#endif /* ipconfigREPLY_TO_INCOMING_PINGS */ + +/* + * Processes incoming ping replies. The application callback function + * vApplicationPingReplyHook() is called with the results. + */ +#if ( ipconfigSUPPORT_OUTGOING_PINGS == 1 ) + static void prvProcessICMPEchoReply( ICMPPacket_t * const pxICMPPacket ); +#endif /* ipconfigSUPPORT_OUTGOING_PINGS */ + +/* + * Called to create a network connection when the stack is first started, or + * when the network connection is lost. + */ +static void prvProcessNetworkDownEvent( void ); + +/* + * Checks the ARP, DHCP and TCP timers to see if any periodic or timeout + * processing is required. + */ +static void prvCheckNetworkTimers( void ); + +/* + * Determine how long the IP task can sleep for, which depends on when the next + * periodic or timeout processing must be performed. + */ +static TickType_t prvCalculateSleepTime( void ); + +/* + * The network card driver has received a packet. In the case that it is part + * of a linked packet chain, walk through it to handle every message. + */ +static void prvHandleEthernetPacket( NetworkBufferDescriptor_t * pxBuffer ); + +/* + * Utility functions for the light weight IP timers. + */ +static void prvIPTimerStart( IPTimer_t * pxTimer, + TickType_t xTime ); +static BaseType_t prvIPTimerCheck( IPTimer_t * pxTimer ); +static void prvIPTimerReload( IPTimer_t * pxTimer, + TickType_t xTime ); + +/* The function 'prvAllowIPPacket()' checks if a packets should be processed. */ +static eFrameProcessingResult_t prvAllowIPPacket( const IPPacket_t * const pxIPPacket, + const NetworkBufferDescriptor_t * const pxNetworkBuffer, + UBaseType_t uxHeaderLength ); + +#if ( ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 1 ) + +/* Even when the driver takes care of checksum calculations, + * the IP-task will still check if the length fields are OK. */ + static BaseType_t xCheckSizeFields( const uint8_t * const pucEthernetBuffer, + size_t uxBufferLength ); +#endif /* ( ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 1 ) */ + +/* + * Returns the network buffer descriptor that owns a given packet buffer. + */ +static NetworkBufferDescriptor_t * prvPacketBuffer_to_NetworkBuffer( const void * pvBuffer, + size_t uxOffset ); + +/*-----------------------------------------------------------*/ + +/** @brief The queue used to pass events into the IP-task for processing. */ +QueueHandle_t xNetworkEventQueue = NULL; + +/** @brief The IP packet ID. */ +uint16_t usPacketIdentifier = 0U; + +/** @brief For convenience, a MAC address of all 0xffs is defined const for quick + * reference. */ +const MACAddress_t xBroadcastMACAddress = { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } }; + +/** @brief Structure that stores the netmask, gateway address and DNS server addresses. */ +NetworkAddressingParameters_t xNetworkAddressing = { 0, 0, 0, 0, 0 }; + +/** @brief Default values for the above struct in case DHCP + * does not lead to a confirmed request. */ +NetworkAddressingParameters_t xDefaultAddressing = { 0, 0, 0, 0, 0 }; + +/** @brief Used to ensure network down events cannot be missed when they cannot be + * posted to the network event queue because the network event queue is already + * full. */ +static volatile BaseType_t xNetworkDownEventPending = pdFALSE; + +/** @brief Stores the handle of the task that handles the stack. The handle is used + * (indirectly) by some utility function to determine if the utility function is + * being called by a task (in which case it is ok to block) or by the IP task + * itself (in which case it is not ok to block). */ + +static TaskHandle_t xIPTaskHandle = NULL; + +#if ( ipconfigUSE_TCP != 0 ) + +/** @brief Set to a non-zero value if one or more TCP message have been processed + * within the last round. */ + static BaseType_t xProcessedTCPMessage; +#endif + +/** @brief Simple set to pdTRUE or pdFALSE depending on whether the network is up or + * down (connected, not connected) respectively. */ +static BaseType_t xNetworkUp = pdFALSE; + +/* + * A timer for each of the following processes, all of which need attention on a + * regular basis + */ + +/** @brief ARP timer, to check its table entries. */ +static IPTimer_t xARPTimer; +#if ( ipconfigUSE_DHCP != 0 ) + /** @brief DHCP timer, to send requests and to renew a reservation. */ + static IPTimer_t xDHCPTimer; +#endif +#if ( ipconfigUSE_TCP != 0 ) + /** @brief TCP timer, to check for timeouts, resends. */ + static IPTimer_t xTCPTimer; +#endif +#if ( ipconfigDNS_USE_CALLBACKS != 0 ) + /** @brief DNS timer, to check for timeouts when looking-up a domain. */ + static IPTimer_t xDNSTimer; +#endif + +/** @brief Set to pdTRUE when the IP task is ready to start processing packets. */ +static BaseType_t xIPTaskInitialised = pdFALSE; + +#if ( ipconfigCHECK_IP_QUEUE_SPACE != 0 ) + /** @brief Keep track of the lowest amount of space in 'xNetworkEventQueue'. */ + static UBaseType_t uxQueueMinimumSpace = ipconfigEVENT_QUEUE_LENGTH; +#endif + +/*-----------------------------------------------------------*/ + +/* Coverity wants to make pvParameters const, which would make it incompatible. Leave the + * function signature as is. */ + +/** + * @brief The IP task handles all requests from the user application and the + * network interface. It receives messages through a FreeRTOS queue called + * 'xNetworkEventQueue'. prvIPTask() is the only task which has access to + * the data of the IP-stack, and so it has no need of using mutexes. + * + * @param[in] pvParameters: Not used. + */ +static void prvIPTask( void * pvParameters ) +{ + IPStackEvent_t xReceivedEvent; + TickType_t xNextIPSleep; + FreeRTOS_Socket_t * pxSocket; + struct freertos_sockaddr xAddress; + + /* Just to prevent compiler warnings about unused parameters. */ + ( void ) pvParameters; + + /* A possibility to set some additional task properties. */ + iptraceIP_TASK_STARTING(); + + /* Generate a dummy message to say that the network connection has gone + * down. This will cause this task to initialise the network interface. After + * this it is the responsibility of the network interface hardware driver to + * send this message if a previously connected network is disconnected. */ + FreeRTOS_NetworkDown(); + + #if ( ipconfigUSE_TCP == 1 ) + { + /* Initialise the TCP timer. */ + prvIPTimerReload( &xTCPTimer, pdMS_TO_TICKS( ipTCP_TIMER_PERIOD_MS ) ); + } + #endif + + /* Initialisation is complete and events can now be processed. */ + xIPTaskInitialised = pdTRUE; + + FreeRTOS_debug_printf( ( "prvIPTask started\n" ) ); + + /* Loop, processing IP events. */ + for( ; ; ) + { + ipconfigWATCHDOG_TIMER(); + + /* Check the ARP, DHCP and TCP timers to see if there is any periodic + * or timeout processing to perform. */ + prvCheckNetworkTimers(); + + /* Calculate the acceptable maximum sleep time. */ + xNextIPSleep = prvCalculateSleepTime(); + + /* Wait until there is something to do. If the following call exits + * due to a time out rather than a message being received, set a + * 'NoEvent' value. */ + if( xQueueReceive( xNetworkEventQueue, ( void * ) &xReceivedEvent, xNextIPSleep ) == pdFALSE ) + { + xReceivedEvent.eEventType = eNoEvent; + } + + #if ( ipconfigCHECK_IP_QUEUE_SPACE != 0 ) + { + if( xReceivedEvent.eEventType != eNoEvent ) + { + UBaseType_t uxCount; + + uxCount = uxQueueSpacesAvailable( xNetworkEventQueue ); + + if( uxQueueMinimumSpace > uxCount ) + { + uxQueueMinimumSpace = uxCount; + } + } + } + #endif /* ipconfigCHECK_IP_QUEUE_SPACE */ + + iptraceNETWORK_EVENT_RECEIVED( xReceivedEvent.eEventType ); + + switch( xReceivedEvent.eEventType ) + { + case eNetworkDownEvent: + /* Attempt to establish a connection. */ + xNetworkUp = pdFALSE; + prvProcessNetworkDownEvent(); + break; + + case eNetworkRxEvent: + + /* The network hardware driver has received a new packet. A + * pointer to the received buffer is located in the pvData member + * of the received event structure. */ + prvHandleEthernetPacket( ipCAST_PTR_TO_TYPE_PTR( NetworkBufferDescriptor_t, xReceivedEvent.pvData ) ); + break; + + case eNetworkTxEvent: + + { + NetworkBufferDescriptor_t * pxDescriptor = ipCAST_PTR_TO_TYPE_PTR( NetworkBufferDescriptor_t, xReceivedEvent.pvData ); + + /* Send a network packet. The ownership will be transferred to + * the driver, which will release it after delivery. */ + iptraceNETWORK_INTERFACE_OUTPUT( pxDescriptor->xDataLength, pxDescriptor->pucEthernetBuffer ); + ( void ) xNetworkInterfaceOutput( pxDescriptor, pdTRUE ); + } + + break; + + case eARPTimerEvent: + /* The ARP timer has expired, process the ARP cache. */ + vARPAgeCache(); + break; + + case eSocketBindEvent: + + /* FreeRTOS_bind (a user API) wants the IP-task to bind a socket + * to a port. The port number is communicated in the socket field + * usLocalPort. vSocketBind() will actually bind the socket and the + * API will unblock as soon as the eSOCKET_BOUND event is + * triggered. */ + pxSocket = ipCAST_PTR_TO_TYPE_PTR( FreeRTOS_Socket_t, xReceivedEvent.pvData ); + xAddress.sin_addr = 0U; /* For the moment. */ + xAddress.sin_port = FreeRTOS_ntohs( pxSocket->usLocalPort ); + pxSocket->usLocalPort = 0U; + ( void ) vSocketBind( pxSocket, &xAddress, sizeof( xAddress ), pdFALSE ); + + /* Before 'eSocketBindEvent' was sent it was tested that + * ( xEventGroup != NULL ) so it can be used now to wake up the + * user. */ + pxSocket->xEventBits |= ( EventBits_t ) eSOCKET_BOUND; + vSocketWakeUpUser( pxSocket ); + break; + + case eSocketCloseEvent: + + /* The user API FreeRTOS_closesocket() has sent a message to the + * IP-task to actually close a socket. This is handled in + * vSocketClose(). As the socket gets closed, there is no way to + * report back to the API, so the API won't wait for the result */ + ( void ) vSocketClose( ipCAST_PTR_TO_TYPE_PTR( FreeRTOS_Socket_t, xReceivedEvent.pvData ) ); + break; + + case eStackTxEvent: + + /* The network stack has generated a packet to send. A + * pointer to the generated buffer is located in the pvData + * member of the received event structure. */ + vProcessGeneratedUDPPacket( ipCAST_PTR_TO_TYPE_PTR( NetworkBufferDescriptor_t, xReceivedEvent.pvData ) ); + break; + + case eDHCPEvent: + /* The DHCP state machine needs processing. */ + #if ( ipconfigUSE_DHCP == 1 ) + { + uintptr_t uxState; + eDHCPState_t eState; + + /* Cast in two steps to please MISRA. */ + uxState = ( uintptr_t ) xReceivedEvent.pvData; + eState = ( eDHCPState_t ) uxState; + + /* Process DHCP messages for a given end-point. */ + vDHCPProcess( pdFALSE, eState ); + } + #endif /* ipconfigUSE_DHCP */ + break; + + case eSocketSelectEvent: + + /* FreeRTOS_select() has got unblocked by a socket event, + * vSocketSelect() will check which sockets actually have an event + * and update the socket field xSocketBits. */ + #if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 ) + #if ( ipconfigSELECT_USES_NOTIFY != 0 ) + { + SocketSelectMessage_t * pxMessage = ipCAST_PTR_TO_TYPE_PTR( SocketSelectMessage_t, xReceivedEvent.pvData ); + vSocketSelect( pxMessage->pxSocketSet ); + ( void ) xTaskNotifyGive( pxMessage->xTaskhandle ); + } + #else + { + vSocketSelect( ipCAST_PTR_TO_TYPE_PTR( SocketSelect_t, xReceivedEvent.pvData ) ); + } + #endif /* ( ipconfigSELECT_USES_NOTIFY != 0 ) */ + #endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */ + break; + + case eSocketSignalEvent: + #if ( ipconfigSUPPORT_SIGNALS != 0 ) + + /* Some task wants to signal the user of this socket in + * order to interrupt a call to recv() or a call to select(). */ + ( void ) FreeRTOS_SignalSocket( ipPOINTER_CAST( Socket_t, xReceivedEvent.pvData ) ); + #endif /* ipconfigSUPPORT_SIGNALS */ + break; + + case eTCPTimerEvent: + #if ( ipconfigUSE_TCP == 1 ) + + /* Simply mark the TCP timer as expired so it gets processed + * the next time prvCheckNetworkTimers() is called. */ + xTCPTimer.bExpired = pdTRUE_UNSIGNED; + #endif /* ipconfigUSE_TCP */ + break; + + case eTCPAcceptEvent: + + /* The API FreeRTOS_accept() was called, the IP-task will now + * check if the listening socket (communicated in pvData) actually + * received a new connection. */ + #if ( ipconfigUSE_TCP == 1 ) + pxSocket = ipCAST_PTR_TO_TYPE_PTR( FreeRTOS_Socket_t, xReceivedEvent.pvData ); + + if( xTCPCheckNewClient( pxSocket ) != pdFALSE ) + { + pxSocket->xEventBits |= ( EventBits_t ) eSOCKET_ACCEPT; + vSocketWakeUpUser( pxSocket ); + } + #endif /* ipconfigUSE_TCP */ + break; + + case eTCPNetStat: + + /* FreeRTOS_netstat() was called to have the IP-task print an + * overview of all sockets and their connections */ + #if ( ( ipconfigUSE_TCP == 1 ) && ( ipconfigHAS_PRINTF == 1 ) ) + vTCPNetStat(); + #endif /* ipconfigUSE_TCP */ + break; + + case eNoEvent: + /* xQueueReceive() returned because of a normal time-out. */ + break; + + default: + /* Should not get here. */ + break; + } + + if( xNetworkDownEventPending != pdFALSE ) + { + /* A network down event could not be posted to the network event + * queue because the queue was full. + * As this code runs in the IP-task, it can be done directly by + * calling prvProcessNetworkDownEvent(). */ + prvProcessNetworkDownEvent(); + } + } +} +/*-----------------------------------------------------------*/ + +/** + * @brief Function to check whether the current context belongs to + * the IP-task. + * + * @return If the current context belongs to the IP-task, then pdTRUE is + * returned. Else pdFALSE is returned. + * + * @note Very important: the IP-task is not allowed to call its own API's, + * because it would easily get into a dead-lock. + */ +BaseType_t xIsCallingFromIPTask( void ) +{ + BaseType_t xReturn; + + if( xTaskGetCurrentTaskHandle() == xIPTaskHandle ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + + return xReturn; +} +/*-----------------------------------------------------------*/ + +/** + * @brief Handle the incoming Ethernet packets. + * + * @param[in] pxBuffer: Linked/un-linked network buffer descriptor(s) + * to be processed. + */ +static void prvHandleEthernetPacket( NetworkBufferDescriptor_t * pxBuffer ) +{ + #if ( ipconfigUSE_LINKED_RX_MESSAGES == 0 ) + { + /* When ipconfigUSE_LINKED_RX_MESSAGES is not set to 0 then only one + * buffer will be sent at a time. This is the default way for +TCP to pass + * messages from the MAC to the TCP/IP stack. */ + prvProcessEthernetPacket( pxBuffer ); + } + #else /* ipconfigUSE_LINKED_RX_MESSAGES */ + { + NetworkBufferDescriptor_t * pxNextBuffer; + + /* An optimisation that is useful when there is high network traffic. + * Instead of passing received packets into the IP task one at a time the + * network interface can chain received packets together and pass them into + * the IP task in one go. The packets are chained using the pxNextBuffer + * member. The loop below walks through the chain processing each packet + * in the chain in turn. */ + do + { + /* Store a pointer to the buffer after pxBuffer for use later on. */ + pxNextBuffer = pxBuffer->pxNextBuffer; + + /* Make it NULL to avoid using it later on. */ + pxBuffer->pxNextBuffer = NULL; + + prvProcessEthernetPacket( pxBuffer ); + pxBuffer = pxNextBuffer; + + /* While there is another packet in the chain. */ + } while( pxBuffer != NULL ); + } + #endif /* ipconfigUSE_LINKED_RX_MESSAGES */ +} +/*-----------------------------------------------------------*/ + +/** + * @brief Calculate the maximum sleep time remaining. It will go through all + * timers to see which timer will expire first. That will be the amount + * of time to block in the next call to xQueueReceive(). + * + * @return The maximum sleep time or ipconfigMAX_IP_TASK_SLEEP_TIME, + * whichever is smaller. + */ +static TickType_t prvCalculateSleepTime( void ) +{ + TickType_t xMaximumSleepTime; + + /* Start with the maximum sleep time, then check this against the remaining + * time in any other timers that are active. */ + xMaximumSleepTime = ipconfigMAX_IP_TASK_SLEEP_TIME; + + if( xARPTimer.bActive != pdFALSE_UNSIGNED ) + { + if( xARPTimer.ulRemainingTime < xMaximumSleepTime ) + { + xMaximumSleepTime = xARPTimer.ulReloadTime; + } + } + + #if ( ipconfigUSE_DHCP == 1 ) + { + if( xDHCPTimer.bActive != pdFALSE_UNSIGNED ) + { + if( xDHCPTimer.ulRemainingTime < xMaximumSleepTime ) + { + xMaximumSleepTime = xDHCPTimer.ulRemainingTime; + } + } + } + #endif /* ipconfigUSE_DHCP */ + + #if ( ipconfigUSE_TCP == 1 ) + { + if( xTCPTimer.ulRemainingTime < xMaximumSleepTime ) + { + xMaximumSleepTime = xTCPTimer.ulRemainingTime; + } + } + #endif + + #if ( ipconfigDNS_USE_CALLBACKS != 0 ) + { + if( xDNSTimer.bActive != pdFALSE_UNSIGNED ) + { + if( xDNSTimer.ulRemainingTime < xMaximumSleepTime ) + { + xMaximumSleepTime = xDNSTimer.ulRemainingTime; + } + } + } + #endif + + return xMaximumSleepTime; +} +/*-----------------------------------------------------------*/ + +/** + * @brief Check the network timers (ARP/DHCP/DNS/TCP) and if they are + * expired, send an event to the IP-Task. + */ +static void prvCheckNetworkTimers( void ) +{ + /* Is it time for ARP processing? */ + if( prvIPTimerCheck( &xARPTimer ) != pdFALSE ) + { + ( void ) xSendEventToIPTask( eARPTimerEvent ); + } + + #if ( ipconfigUSE_DHCP == 1 ) + { + /* Is it time for DHCP processing? */ + if( prvIPTimerCheck( &xDHCPTimer ) != pdFALSE ) + { + ( void ) xSendDHCPEvent(); + } + } + #endif /* ipconfigUSE_DHCP */ + + #if ( ipconfigDNS_USE_CALLBACKS != 0 ) + { + /* Is it time for DNS processing? */ + if( prvIPTimerCheck( &xDNSTimer ) != pdFALSE ) + { + vDNSCheckCallBack( NULL ); + } + } + #endif /* ipconfigDNS_USE_CALLBACKS */ + + #if ( ipconfigUSE_TCP == 1 ) + { + BaseType_t xWillSleep; + TickType_t xNextTime; + BaseType_t xCheckTCPSockets; + + /* If the IP task has messages waiting to be processed then + * it will not sleep in any case. */ + if( uxQueueMessagesWaiting( xNetworkEventQueue ) == 0U ) + { + xWillSleep = pdTRUE; + } + else + { + xWillSleep = pdFALSE; + } + + /* Sockets need to be checked if the TCP timer has expired. */ + xCheckTCPSockets = prvIPTimerCheck( &xTCPTimer ); + + /* Sockets will also be checked if there are TCP messages but the + * message queue is empty (indicated by xWillSleep being true). */ + if( ( xProcessedTCPMessage != pdFALSE ) && ( xWillSleep != pdFALSE ) ) + { + xCheckTCPSockets = pdTRUE; + } + + if( xCheckTCPSockets != pdFALSE ) + { + /* Attend to the sockets, returning the period after which the + * check must be repeated. */ + xNextTime = xTCPTimerCheck( xWillSleep ); + prvIPTimerStart( &xTCPTimer, xNextTime ); + xProcessedTCPMessage = 0; + } + } + #endif /* ipconfigUSE_TCP == 1 */ +} +/*-----------------------------------------------------------*/ + +/** + * @brief Start an IP timer. The IP-task has its own implementation of a timer + * called 'IPTimer_t', which is based on the FreeRTOS 'TimeOut_t'. + * + * @param[in] pxTimer: Pointer to the IP timer. When zero, the timer is marked + * as expired. + * @param[in] xTime: Time to be loaded into the IP timer. + */ +static void prvIPTimerStart( IPTimer_t * pxTimer, + TickType_t xTime ) +{ + vTaskSetTimeOutState( &pxTimer->xTimeOut ); + pxTimer->ulRemainingTime = xTime; + + if( xTime == ( TickType_t ) 0 ) + { + pxTimer->bExpired = pdTRUE_UNSIGNED; + } + else + { + pxTimer->bExpired = pdFALSE_UNSIGNED; + } + + pxTimer->bActive = pdTRUE_UNSIGNED; +} +/*-----------------------------------------------------------*/ + +/** + * @brief Sets the reload time of an IP timer and restarts it. + * + * @param[in] pxTimer: Pointer to the IP timer. + * @param[in] xTime: Time to be reloaded into the IP timer. + */ +static void prvIPTimerReload( IPTimer_t * pxTimer, + TickType_t xTime ) +{ + pxTimer->ulReloadTime = xTime; + prvIPTimerStart( pxTimer, xTime ); +} +/*-----------------------------------------------------------*/ + +/** + * @brief Check the IP timer to see whether an IP event should be processed or not. + * + * @param[in] pxTimer: Pointer to the IP timer. + * + * @return If the timer is expired then pdTRUE is returned. Else pdFALSE. + */ +static BaseType_t prvIPTimerCheck( IPTimer_t * pxTimer ) +{ + BaseType_t xReturn; + + if( pxTimer->bActive == pdFALSE_UNSIGNED ) + { + /* The timer is not enabled. */ + xReturn = pdFALSE; + } + else + { + /* The timer might have set the bExpired flag already, if not, check the + * value of xTimeOut against ulRemainingTime. */ + if( pxTimer->bExpired == pdFALSE_UNSIGNED ) + { + if( xTaskCheckForTimeOut( &( pxTimer->xTimeOut ), &( pxTimer->ulRemainingTime ) ) != pdFALSE ) + { + pxTimer->bExpired = pdTRUE_UNSIGNED; + } + } + + if( pxTimer->bExpired != pdFALSE_UNSIGNED ) + { + prvIPTimerStart( pxTimer, pxTimer->ulReloadTime ); + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + + return xReturn; +} +/*-----------------------------------------------------------*/ + +/** + * @brief Send a network down event to the IP-task. If it fails to post a message, + * the failure will be noted in the variable 'xNetworkDownEventPending' + * and later on a 'network-down' event, it will be executed. + */ +void FreeRTOS_NetworkDown( void ) +{ + static const IPStackEvent_t xNetworkDownEvent = { eNetworkDownEvent, NULL }; + const TickType_t xDontBlock = ( TickType_t ) 0; + + /* Simply send the network task the appropriate event. */ + if( xSendEventStructToIPTask( &xNetworkDownEvent, xDontBlock ) != pdPASS ) + { + /* Could not send the message, so it is still pending. */ + xNetworkDownEventPending = pdTRUE; + } + else + { + /* Message was sent so it is not pending. */ + xNetworkDownEventPending = pdFALSE; + } + + iptraceNETWORK_DOWN(); +} +/*-----------------------------------------------------------*/ + +/** + * @brief Utility function. Process Network Down event from ISR. + * This function is supposed to be called form an ISR. It is recommended + * - * use 'FreeRTOS_NetworkDown()', when calling from a normal task. + * + * @return If the event was processed successfully, then return pdTRUE. + * Else pdFALSE. + */ +BaseType_t FreeRTOS_NetworkDownFromISR( void ) +{ + static const IPStackEvent_t xNetworkDownEvent = { eNetworkDownEvent, NULL }; + BaseType_t xHigherPriorityTaskWoken = pdFALSE; + + /* Simply send the network task the appropriate event. */ + if( xQueueSendToBackFromISR( xNetworkEventQueue, &xNetworkDownEvent, &xHigherPriorityTaskWoken ) != pdPASS ) + { + xNetworkDownEventPending = pdTRUE; + } + else + { + xNetworkDownEventPending = pdFALSE; + } + + iptraceNETWORK_DOWN(); + + return xHigherPriorityTaskWoken; +} +/*-----------------------------------------------------------*/ + +/** + * @brief Obtain a buffer big enough for a UDP payload of given size. + * + * @param[in] uxRequestedSizeBytes: The size of the UDP payload. + * @param[in] uxBlockTimeTicks: Maximum amount of time for which this call + * can block. This value is capped internally. + * + * @return If a buffer was created then the pointer to that buffer is returned, + * else a NULL pointer is returned. + */ +void * FreeRTOS_GetUDPPayloadBuffer( size_t uxRequestedSizeBytes, + TickType_t uxBlockTimeTicks ) +{ + NetworkBufferDescriptor_t * pxNetworkBuffer; + void * pvReturn; + TickType_t uxBlockTime = uxBlockTimeTicks; + + /* Cap the block time. The reason for this is explained where + * ipconfigUDP_MAX_SEND_BLOCK_TIME_TICKS is defined (assuming an official + * FreeRTOSIPConfig.h header file is being used). */ + if( uxBlockTime > ipconfigUDP_MAX_SEND_BLOCK_TIME_TICKS ) + { + uxBlockTime = ipconfigUDP_MAX_SEND_BLOCK_TIME_TICKS; + } + + /* Obtain a network buffer with the required amount of storage. */ + pxNetworkBuffer = pxGetNetworkBufferWithDescriptor( sizeof( UDPPacket_t ) + uxRequestedSizeBytes, uxBlockTime ); + + if( pxNetworkBuffer != NULL ) + { + /* Set the actual packet size in case a bigger buffer was returned. */ + pxNetworkBuffer->xDataLength = sizeof( UDPPacket_t ) + uxRequestedSizeBytes; + /* Skip 3 headers. */ + pvReturn = &( pxNetworkBuffer->pucEthernetBuffer[ sizeof( UDPPacket_t ) ] ); + } + else + { + pvReturn = NULL; + } + + return ( void * ) pvReturn; +} +/*-----------------------------------------------------------*/ + +/** + * @brief Duplicate the given network buffer descriptor with a modified length. + * + * @param[in] pxNetworkBuffer: The network buffer to be duplicated. + * @param[in] uxNewLength: The length for the new buffer. + * + * @return If properly duplicated, then the duplicate network buffer or else, NULL. + */ +NetworkBufferDescriptor_t * pxDuplicateNetworkBufferWithDescriptor( const NetworkBufferDescriptor_t * const pxNetworkBuffer, + size_t uxNewLength ) +{ + NetworkBufferDescriptor_t * pxNewBuffer; + + /* This function is only used when 'ipconfigZERO_COPY_TX_DRIVER' is set to 1. + * The transmit routine wants to have ownership of the network buffer + * descriptor, because it will pass the buffer straight to DMA. */ + pxNewBuffer = pxGetNetworkBufferWithDescriptor( uxNewLength, ( TickType_t ) 0 ); + + if( pxNewBuffer != NULL ) + { + /* Set the actual packet size in case a bigger buffer than requested + * was returned. */ + pxNewBuffer->xDataLength = uxNewLength; + + /* Copy the original packet information. */ + pxNewBuffer->ulIPAddress = pxNetworkBuffer->ulIPAddress; + pxNewBuffer->usPort = pxNetworkBuffer->usPort; + pxNewBuffer->usBoundPort = pxNetworkBuffer->usBoundPort; + ( void ) memcpy( pxNewBuffer->pucEthernetBuffer, pxNetworkBuffer->pucEthernetBuffer, pxNetworkBuffer->xDataLength ); + } + + return pxNewBuffer; +} +/*-----------------------------------------------------------*/ + +/** + * @brief Get the network buffer descriptor from the packet buffer. + * + * @param[in] pvBuffer: The pointer to packet buffer. + * @param[in] uxOffset: Additional offset (such as the packet length of UDP packet etc.). + * + * @return The network buffer descriptor if the alignment is correct. Else a NULL is returned. + */ +static NetworkBufferDescriptor_t * prvPacketBuffer_to_NetworkBuffer( const void * pvBuffer, + size_t uxOffset ) +{ + uintptr_t uxBuffer; + NetworkBufferDescriptor_t * pxResult; + + if( pvBuffer == NULL ) + { + pxResult = NULL; + } + else + { + /* Obtain the network buffer from the zero copy pointer. */ + uxBuffer = ipPOINTER_CAST( uintptr_t, pvBuffer ); + + /* The input here is a pointer to a packet buffer plus some offset. Subtract + * this offset, and also the size of the header in the network buffer, usually + * 8 + 2 bytes. */ + uxBuffer -= ( uxOffset + ipBUFFER_PADDING ); + + /* Here a pointer was placed to the network descriptor. As a + * pointer is dereferenced, make sure it is well aligned. */ + if( ( uxBuffer & ( ( ( uintptr_t ) sizeof( uxBuffer ) ) - 1U ) ) == ( uintptr_t ) 0U ) + { + /* The following statement may trigger a: + * warning: cast increases required alignment of target type [-Wcast-align]. + * It has been confirmed though that the alignment is suitable. */ + pxResult = *( ( NetworkBufferDescriptor_t ** ) uxBuffer ); + } + else + { + pxResult = NULL; + } + } + + return pxResult; +} +/*-----------------------------------------------------------*/ + +#if ( ipconfigZERO_COPY_TX_DRIVER != 0 ) || ( ipconfigZERO_COPY_RX_DRIVER != 0 ) + +/** + * @brief Get the network buffer from the packet buffer. + * + * @param[in] pvBuffer: Pointer to the packet buffer. + * + * @return The network buffer if the alignment is correct. Else a NULL is returned. + */ + NetworkBufferDescriptor_t * pxPacketBuffer_to_NetworkBuffer( const void * pvBuffer ) + { + return prvPacketBuffer_to_NetworkBuffer( pvBuffer, 0U ); + } + +#endif /* ( ipconfigZERO_COPY_TX_DRIVER != 0 ) || ( ipconfigZERO_COPY_RX_DRIVER != 0 ) */ +/*-----------------------------------------------------------*/ + +/** + * @brief Get the network buffer from the UDP Payload buffer. + * + * @param[in] pvBuffer: Pointer to the UDP payload buffer. + * + * @return The network buffer if the alignment is correct. Else a NULL is returned. + */ +NetworkBufferDescriptor_t * pxUDPPayloadBuffer_to_NetworkBuffer( const void * pvBuffer ) +{ + return prvPacketBuffer_to_NetworkBuffer( pvBuffer, sizeof( UDPPacket_t ) ); +} +/*-----------------------------------------------------------*/ + +/** + * @brief Release the UDP payload buffer. + * + * @param[in] pvBuffer: Pointer to the UDP buffer that is to be released. + */ +void FreeRTOS_ReleaseUDPPayloadBuffer( void const * pvBuffer ) +{ + vReleaseNetworkBufferAndDescriptor( pxUDPPayloadBuffer_to_NetworkBuffer( pvBuffer ) ); +} +/*-----------------------------------------------------------*/ + +/*_RB_ Should we add an error or assert if the task priorities are set such that the servers won't function as expected? */ + +/*_HT_ There was a bug in FreeRTOS_TCP_IP.c that only occurred when the applications' priority was too high. + * As that bug has been repaired, there is not an urgent reason to warn. + * It is better though to use the advised priority scheme. */ + +/** + * @brief Initialise the FreeRTOS-Plus-TCP network stack and initialise the IP-task. + * + * @param[in] ucIPAddress: Local IP address. + * @param[in] ucNetMask: Local netmask. + * @param[in] ucGatewayAddress: Local gateway address. + * @param[in] ucDNSServerAddress: Local DNS server address. + * @param[in] ucMACAddress: MAC address of the node. + * + * @return pdPASS if the task was successfully created and added to a ready + * list, otherwise an error code defined in the file projdefs.h + */ +BaseType_t FreeRTOS_IPInit( const uint8_t ucIPAddress[ ipIP_ADDRESS_LENGTH_BYTES ], + const uint8_t ucNetMask[ ipIP_ADDRESS_LENGTH_BYTES ], + const uint8_t ucGatewayAddress[ ipIP_ADDRESS_LENGTH_BYTES ], + const uint8_t ucDNSServerAddress[ ipIP_ADDRESS_LENGTH_BYTES ], + const uint8_t ucMACAddress[ ipMAC_ADDRESS_LENGTH_BYTES ] ) +{ + BaseType_t xReturn = pdFALSE; + + /* This function should only be called once. */ + configASSERT( xIPIsNetworkTaskReady() == pdFALSE ); + configASSERT( xNetworkEventQueue == NULL ); + configASSERT( xIPTaskHandle == NULL ); + + if( sizeof( uintptr_t ) == 8 ) + { + /* This is a 64-bit platform, make sure there is enough space in + * pucEthernetBuffer to store a pointer. */ + configASSERT( ipconfigBUFFER_PADDING == 14 ); + } + + #ifndef _lint + { + /* Check if MTU is big enough. */ + configASSERT( ( ( size_t ) ipconfigNETWORK_MTU ) >= ( ipSIZE_OF_IPv4_HEADER + ipSIZE_OF_TCP_HEADER + ipconfigTCP_MSS ) ); + /* Check structure packing is correct. */ + configASSERT( sizeof( EthernetHeader_t ) == ipEXPECTED_EthernetHeader_t_SIZE ); + configASSERT( sizeof( ARPHeader_t ) == ipEXPECTED_ARPHeader_t_SIZE ); + configASSERT( sizeof( IPHeader_t ) == ipEXPECTED_IPHeader_t_SIZE ); + configASSERT( sizeof( ICMPHeader_t ) == ipEXPECTED_ICMPHeader_t_SIZE ); + configASSERT( sizeof( UDPHeader_t ) == ipEXPECTED_UDPHeader_t_SIZE ); + } + #endif /* ifndef _lint */ + /* Attempt to create the queue used to communicate with the IP task. */ + xNetworkEventQueue = xQueueCreate( ipconfigEVENT_QUEUE_LENGTH, sizeof( IPStackEvent_t ) ); + configASSERT( xNetworkEventQueue != NULL ); + + if( xNetworkEventQueue != NULL ) + { + #if ( configQUEUE_REGISTRY_SIZE > 0 ) + { + /* A queue registry is normally used to assist a kernel aware + * debugger. If one is in use then it will be helpful for the debugger + * to show information about the network event queue. */ + vQueueAddToRegistry( xNetworkEventQueue, "NetEvnt" ); + } + #endif /* configQUEUE_REGISTRY_SIZE */ + + if( xNetworkBuffersInitialise() == pdPASS ) + { + /* Store the local IP and MAC address. */ + xNetworkAddressing.ulDefaultIPAddress = FreeRTOS_inet_addr_quick( ucIPAddress[ 0 ], ucIPAddress[ 1 ], ucIPAddress[ 2 ], ucIPAddress[ 3 ] ); + xNetworkAddressing.ulNetMask = FreeRTOS_inet_addr_quick( ucNetMask[ 0 ], ucNetMask[ 1 ], ucNetMask[ 2 ], ucNetMask[ 3 ] ); + xNetworkAddressing.ulGatewayAddress = FreeRTOS_inet_addr_quick( ucGatewayAddress[ 0 ], ucGatewayAddress[ 1 ], ucGatewayAddress[ 2 ], ucGatewayAddress[ 3 ] ); + xNetworkAddressing.ulDNSServerAddress = FreeRTOS_inet_addr_quick( ucDNSServerAddress[ 0 ], ucDNSServerAddress[ 1 ], ucDNSServerAddress[ 2 ], ucDNSServerAddress[ 3 ] ); + xNetworkAddressing.ulBroadcastAddress = ( xNetworkAddressing.ulDefaultIPAddress & xNetworkAddressing.ulNetMask ) | ~xNetworkAddressing.ulNetMask; + + ( void ) memcpy( &xDefaultAddressing, &xNetworkAddressing, sizeof( xDefaultAddressing ) ); + + #if ipconfigUSE_DHCP == 1 + { + /* The IP address is not set until DHCP completes. */ + *ipLOCAL_IP_ADDRESS_POINTER = 0x00UL; + } + #else + { + /* The IP address is set from the value passed in. */ + *ipLOCAL_IP_ADDRESS_POINTER = xNetworkAddressing.ulDefaultIPAddress; + + /* Added to prevent ARP flood to gateway. Ensure the + * gateway is on the same subnet as the IP address. */ + if( xNetworkAddressing.ulGatewayAddress != 0UL ) + { + configASSERT( ( ( *ipLOCAL_IP_ADDRESS_POINTER ) & xNetworkAddressing.ulNetMask ) == ( xNetworkAddressing.ulGatewayAddress & xNetworkAddressing.ulNetMask ) ); + } + } + #endif /* ipconfigUSE_DHCP == 1 */ + + /* The MAC address is stored in the start of the default packet + * header fragment, which is used when sending UDP packets. */ + ( void ) memcpy( ipLOCAL_MAC_ADDRESS, ucMACAddress, ( size_t ) ipMAC_ADDRESS_LENGTH_BYTES ); + + /* Prepare the sockets interface. */ + vNetworkSocketsInit(); + + /* Create the task that processes Ethernet and stack events. */ + xReturn = xTaskCreate( prvIPTask, + "IP-task", + ipconfigIP_TASK_STACK_SIZE_WORDS, + NULL, + ipconfigIP_TASK_PRIORITY, + &( xIPTaskHandle ) ); + } + else + { + FreeRTOS_debug_printf( ( "FreeRTOS_IPInit: xNetworkBuffersInitialise() failed\n" ) ); + + /* Clean up. */ + vQueueDelete( xNetworkEventQueue ); + xNetworkEventQueue = NULL; + } + } + else + { + FreeRTOS_debug_printf( ( "FreeRTOS_IPInit: Network event queue could not be created\n" ) ); + } + + return xReturn; +} +/*-----------------------------------------------------------*/ + +/** + * @brief Get the current address configuration. Only non-NULL pointers will + * be filled in. + * + * @param[out] pulIPAddress: The current IP-address assigned. + * @param[out] pulNetMask: The netmask used for current subnet. + * @param[out] pulGatewayAddress: The gateway address. + * @param[out] pulDNSServerAddress: The DNS server address. + */ +void FreeRTOS_GetAddressConfiguration( uint32_t * pulIPAddress, + uint32_t * pulNetMask, + uint32_t * pulGatewayAddress, + uint32_t * pulDNSServerAddress ) +{ + /* Return the address configuration to the caller. */ + + if( pulIPAddress != NULL ) + { + *pulIPAddress = *ipLOCAL_IP_ADDRESS_POINTER; + } + + if( pulNetMask != NULL ) + { + *pulNetMask = xNetworkAddressing.ulNetMask; + } + + if( pulGatewayAddress != NULL ) + { + *pulGatewayAddress = xNetworkAddressing.ulGatewayAddress; + } + + if( pulDNSServerAddress != NULL ) + { + *pulDNSServerAddress = xNetworkAddressing.ulDNSServerAddress; + } +} +/*-----------------------------------------------------------*/ + +/** + * @brief Set the current network address configuration. Only non-NULL pointers will + * be used. + * + * @param[in] pulIPAddress: The current IP-address assigned. + * @param[in] pulNetMask: The netmask used for current subnet. + * @param[in] pulGatewayAddress: The gateway address. + * @param[in] pulDNSServerAddress: The DNS server address. + */ +void FreeRTOS_SetAddressConfiguration( const uint32_t * pulIPAddress, + const uint32_t * pulNetMask, + const uint32_t * pulGatewayAddress, + const uint32_t * pulDNSServerAddress ) +{ + /* Update the address configuration. */ + + if( pulIPAddress != NULL ) + { + *ipLOCAL_IP_ADDRESS_POINTER = *pulIPAddress; + } + + if( pulNetMask != NULL ) + { + xNetworkAddressing.ulNetMask = *pulNetMask; + } + + if( pulGatewayAddress != NULL ) + { + xNetworkAddressing.ulGatewayAddress = *pulGatewayAddress; + } + + if( pulDNSServerAddress != NULL ) + { + xNetworkAddressing.ulDNSServerAddress = *pulDNSServerAddress; + } +} +/*-----------------------------------------------------------*/ + +#if ( ipconfigSUPPORT_OUTGOING_PINGS == 1 ) + +/** + * @brief Send a ping request to the given IP address. After receiving a reply, + * IP-task will call a user-supplied function 'vApplicationPingReplyHook()'. + * + * @param[in] ulIPAddress: The IP address to which the ping is to be sent. + * @param[in] uxNumberOfBytesToSend: Number of bytes in the ping request. + * @param[in] uxBlockTimeTicks: Maximum number of ticks to wait. + * + * @return If successfully sent to IP task for processing then the sequence + * number of the ping packet or else, pdFAIL. + */ + BaseType_t FreeRTOS_SendPingRequest( uint32_t ulIPAddress, + size_t uxNumberOfBytesToSend, + TickType_t uxBlockTimeTicks ) + { + NetworkBufferDescriptor_t * pxNetworkBuffer; + ICMPHeader_t * pxICMPHeader; + EthernetHeader_t * pxEthernetHeader; + BaseType_t xReturn = pdFAIL; + static uint16_t usSequenceNumber = 0; + uint8_t * pucChar; + size_t uxTotalLength; + IPStackEvent_t xStackTxEvent = { eStackTxEvent, NULL }; + + uxTotalLength = uxNumberOfBytesToSend + sizeof( ICMPPacket_t ); + BaseType_t xEnoughSpace; + + if( uxNumberOfBytesToSend < ( ipconfigNETWORK_MTU - ( sizeof( IPHeader_t ) + sizeof( ICMPHeader_t ) ) ) ) + { + xEnoughSpace = pdTRUE; + } + else + { + xEnoughSpace = pdFALSE; + } + + if( ( uxGetNumberOfFreeNetworkBuffers() >= 4U ) && ( uxNumberOfBytesToSend >= 1U ) && ( xEnoughSpace != pdFALSE ) ) + { + pxNetworkBuffer = pxGetNetworkBufferWithDescriptor( uxTotalLength, uxBlockTimeTicks ); + + if( pxNetworkBuffer != NULL ) + { + pxEthernetHeader = ipCAST_PTR_TO_TYPE_PTR( EthernetHeader_t, pxNetworkBuffer->pucEthernetBuffer ); + pxEthernetHeader->usFrameType = ipIPv4_FRAME_TYPE; + + pxICMPHeader = ipCAST_PTR_TO_TYPE_PTR( ICMPHeader_t, &( pxNetworkBuffer->pucEthernetBuffer[ ipIP_PAYLOAD_OFFSET ] ) ); + usSequenceNumber++; + + /* Fill in the basic header information. */ + pxICMPHeader->ucTypeOfMessage = ipICMP_ECHO_REQUEST; + pxICMPHeader->ucTypeOfService = 0; + pxICMPHeader->usIdentifier = usSequenceNumber; + pxICMPHeader->usSequenceNumber = usSequenceNumber; + + /* Find the start of the data. */ + pucChar = ( uint8_t * ) pxICMPHeader; + pucChar = &( pucChar[ sizeof( ICMPHeader_t ) ] ); + + /* Just memset the data to a fixed value. */ + ( void ) memset( pucChar, ( int ) ipECHO_DATA_FILL_BYTE, uxNumberOfBytesToSend ); + + /* The message is complete, IP and checksum's are handled by + * vProcessGeneratedUDPPacket */ + pxNetworkBuffer->pucEthernetBuffer[ ipSOCKET_OPTIONS_OFFSET ] = FREERTOS_SO_UDPCKSUM_OUT; + pxNetworkBuffer->ulIPAddress = ulIPAddress; + pxNetworkBuffer->usPort = ipPACKET_CONTAINS_ICMP_DATA; + /* xDataLength is the size of the total packet, including the Ethernet header. */ + pxNetworkBuffer->xDataLength = uxTotalLength; + + /* Send to the stack. */ + xStackTxEvent.pvData = pxNetworkBuffer; + + if( xSendEventStructToIPTask( &( xStackTxEvent ), uxBlockTimeTicks ) != pdPASS ) + { + vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer ); + iptraceSTACK_TX_EVENT_LOST( ipSTACK_TX_EVENT ); + } + else + { + xReturn = ( BaseType_t ) usSequenceNumber; + } + } + } + else + { + /* The requested number of bytes will not fit in the available space + * in the network buffer. */ + } + + return xReturn; + } + +#endif /* ipconfigSUPPORT_OUTGOING_PINGS == 1 */ +/*-----------------------------------------------------------*/ + +/** + * @brief Send an event to the IP task. It calls 'xSendEventStructToIPTask' internally. + * + * @param[in] eEvent: The event to be sent. + * + * @return pdPASS if the event was sent (or the desired effect was achieved). Else, pdFAIL. + */ +BaseType_t xSendEventToIPTask( eIPEvent_t eEvent ) +{ + IPStackEvent_t xEventMessage; + const TickType_t xDontBlock = ( TickType_t ) 0; + + xEventMessage.eEventType = eEvent; + xEventMessage.pvData = ( void * ) NULL; + + return xSendEventStructToIPTask( &xEventMessage, xDontBlock ); +} +/*-----------------------------------------------------------*/ + +/** + * @brief Send an event (in form of struct) to the IP task to be processed. + * + * @param[in] pxEvent: The event to be sent. + * @param[in] uxTimeout: Timeout for waiting in case the queue is full. 0 for non-blocking calls. + * + * @return pdPASS if the event was sent (or the desired effect was achieved). Else, pdFAIL. + */ +BaseType_t xSendEventStructToIPTask( const IPStackEvent_t * pxEvent, + TickType_t uxTimeout ) +{ + BaseType_t xReturn, xSendMessage; + TickType_t uxUseTimeout = uxTimeout; + + if( ( xIPIsNetworkTaskReady() == pdFALSE ) && ( pxEvent->eEventType != eNetworkDownEvent ) ) + { + /* Only allow eNetworkDownEvent events if the IP task is not ready + * yet. Not going to attempt to send the message so the send failed. */ + xReturn = pdFAIL; + } + else + { + xSendMessage = pdTRUE; + + #if ( ipconfigUSE_TCP == 1 ) + { + if( pxEvent->eEventType == eTCPTimerEvent ) + { + /* TCP timer events are sent to wake the timer task when + * xTCPTimer has expired, but there is no point sending them if the + * IP task is already awake processing other message. */ + xTCPTimer.bExpired = pdTRUE_UNSIGNED; + + if( uxQueueMessagesWaiting( xNetworkEventQueue ) != 0U ) + { + /* Not actually going to send the message but this is not a + * failure as the message didn't need to be sent. */ + xSendMessage = pdFALSE; + } + } + } + #endif /* ipconfigUSE_TCP */ + + if( xSendMessage != pdFALSE ) + { + /* The IP task cannot block itself while waiting for itself to + * respond. */ + if( ( xIsCallingFromIPTask() == pdTRUE ) && ( uxUseTimeout > ( TickType_t ) 0U ) ) + { + uxUseTimeout = ( TickType_t ) 0; + } + + xReturn = xQueueSendToBack( xNetworkEventQueue, pxEvent, uxUseTimeout ); + + if( xReturn == pdFAIL ) + { + /* A message should have been sent to the IP task, but wasn't. */ + FreeRTOS_debug_printf( ( "xSendEventStructToIPTask: CAN NOT ADD %d\n", pxEvent->eEventType ) ); + iptraceSTACK_TX_EVENT_LOST( pxEvent->eEventType ); + } + } + else + { + /* It was not necessary to send the message to process the event so + * even though the message was not sent the call was successful. */ + xReturn = pdPASS; + } + } + + return xReturn; +} +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_DHCP != 0 ) + +/** + * @brief Create a DHCP event. + * + * @return pdPASS or pdFAIL, depending on whether xSendEventStructToIPTask() + * succeeded. + */ + BaseType_t xSendDHCPEvent( void ) + { + IPStackEvent_t xEventMessage; + const TickType_t uxDontBlock = 0U; + uintptr_t uxOption = eGetDHCPState(); + + xEventMessage.eEventType = eDHCPEvent; + xEventMessage.pvData = ( void * ) uxOption; + + return xSendEventStructToIPTask( &xEventMessage, uxDontBlock ); + } +/*-----------------------------------------------------------*/ +#endif /* ( ipconfigUSE_DHCP != 0 ) */ + +/** + * @brief Decide whether this packet should be processed or not based on the IP address in the packet. + * + * @param[in] pucEthernetBuffer: The ethernet packet under consideration. + * + * @return Enum saying whether to release or to process the packet. + */ +eFrameProcessingResult_t eConsiderFrameForProcessing( const uint8_t * const pucEthernetBuffer ) +{ + eFrameProcessingResult_t eReturn; + const EthernetHeader_t * pxEthernetHeader; + + /* Map the buffer onto Ethernet Header struct for easy access to fields. */ + pxEthernetHeader = ipCAST_CONST_PTR_TO_CONST_TYPE_PTR( EthernetHeader_t, pucEthernetBuffer ); + + if( memcmp( ipLOCAL_MAC_ADDRESS, pxEthernetHeader->xDestinationAddress.ucBytes, sizeof( MACAddress_t ) ) == 0 ) + { + /* The packet was directed to this node - process it. */ + eReturn = eProcessBuffer; + } + else if( memcmp( xBroadcastMACAddress.ucBytes, pxEthernetHeader->xDestinationAddress.ucBytes, sizeof( MACAddress_t ) ) == 0 ) + { + /* The packet was a broadcast - process it. */ + eReturn = eProcessBuffer; + } + else + #if ( ipconfigUSE_LLMNR == 1 ) + if( memcmp( xLLMNR_MacAdress.ucBytes, pxEthernetHeader->xDestinationAddress.ucBytes, sizeof( MACAddress_t ) ) == 0 ) + { + /* The packet is a request for LLMNR - process it. */ + eReturn = eProcessBuffer; + } + else + #endif /* ipconfigUSE_LLMNR */ + { + /* The packet was not a broadcast, or for this node, just release + * the buffer without taking any other action. */ + eReturn = eReleaseBuffer; + } + + #if ( ipconfigFILTER_OUT_NON_ETHERNET_II_FRAMES == 1 ) + { + uint16_t usFrameType; + + if( eReturn == eProcessBuffer ) + { + usFrameType = pxEthernetHeader->usFrameType; + usFrameType = FreeRTOS_ntohs( usFrameType ); + + if( usFrameType <= 0x600U ) + { + /* Not an Ethernet II frame. */ + eReturn = eReleaseBuffer; + } + } + } + #endif /* ipconfigFILTER_OUT_NON_ETHERNET_II_FRAMES == 1 */ + + return eReturn; +} +/*-----------------------------------------------------------*/ + +/** + * @brief Process a 'Network down' event and complete required processing. + */ +static void prvProcessNetworkDownEvent( void ) +{ + /* Stop the ARP timer while there is no network. */ + xARPTimer.bActive = pdFALSE_UNSIGNED; + + #if ipconfigUSE_NETWORK_EVENT_HOOK == 1 + { + static BaseType_t xCallEventHook = pdFALSE; + + /* The first network down event is generated by the IP stack itself to + * initialise the network hardware, so do not call the network down event + * the first time through. */ + if( xCallEventHook == pdTRUE ) + { + vApplicationIPNetworkEventHook( eNetworkDown ); + } + + xCallEventHook = pdTRUE; + } + #endif /* if ipconfigUSE_NETWORK_EVENT_HOOK == 1 */ + + /* Per the ARP Cache Validation section of https://tools.ietf.org/html/rfc1122, + * treat network down as a "delivery problem" and flush the ARP cache for this + * interface. */ + FreeRTOS_ClearARP(); + + /* The network has been disconnected (or is being initialised for the first + * time). Perform whatever hardware processing is necessary to bring it up + * again, or wait for it to be available again. This is hardware dependent. */ + if( xNetworkInterfaceInitialise() != pdPASS ) + { + /* Ideally the network interface initialisation function will only + * return when the network is available. In case this is not the case, + * wait a while before retrying the initialisation. */ + vTaskDelay( ipINITIALISATION_RETRY_DELAY ); + FreeRTOS_NetworkDown(); + } + else + { + /* Set remaining time to 0 so it will become active immediately. */ + #if ipconfigUSE_DHCP == 1 + { + /* The network is not up until DHCP has completed. */ + vDHCPProcess( pdTRUE, eInitialWait ); + } + #else + { + /* Perform any necessary 'network up' processing. */ + vIPNetworkUpCalls(); + } + #endif + } +} +/*-----------------------------------------------------------*/ + +/** + * @brief Perform all the required tasks when the network gets connected. + */ +void vIPNetworkUpCalls( void ) +{ + xNetworkUp = pdTRUE; + + #if ( ipconfigUSE_NETWORK_EVENT_HOOK == 1 ) + { + vApplicationIPNetworkEventHook( eNetworkUp ); + } + #endif /* ipconfigUSE_NETWORK_EVENT_HOOK */ + + #if ( ipconfigDNS_USE_CALLBACKS != 0 ) + { + /* The following function is declared in FreeRTOS_DNS.c and 'private' to + * this library */ + extern void vDNSInitialise( void ); + vDNSInitialise(); + } + #endif /* ipconfigDNS_USE_CALLBACKS != 0 */ + + /* Set remaining time to 0 so it will become active immediately. */ + prvIPTimerReload( &xARPTimer, pdMS_TO_TICKS( ipARP_TIMER_PERIOD_MS ) ); +} +/*-----------------------------------------------------------*/ + +/** + * @brief Process the Ethernet packet. + * + * @param[in,out] pxNetworkBuffer: the network buffer containing the ethernet packet. If the + * buffer is large enough, it may be reused to send a reply. + */ +static void prvProcessEthernetPacket( NetworkBufferDescriptor_t * const pxNetworkBuffer ) +{ + const EthernetHeader_t * pxEthernetHeader; + eFrameProcessingResult_t eReturned = eReleaseBuffer; + + configASSERT( pxNetworkBuffer != NULL ); + + iptraceNETWORK_INTERFACE_INPUT( pxNetworkBuffer->xDataLength, pxNetworkBuffer->pucEthernetBuffer ); + + /* Interpret the Ethernet frame. */ + if( pxNetworkBuffer->xDataLength >= sizeof( EthernetHeader_t ) ) + { + eReturned = ipCONSIDER_FRAME_FOR_PROCESSING( pxNetworkBuffer->pucEthernetBuffer ); + + /* Map the buffer onto the Ethernet Header struct for easy access to the fields. */ + pxEthernetHeader = ipCAST_CONST_PTR_TO_CONST_TYPE_PTR( EthernetHeader_t, pxNetworkBuffer->pucEthernetBuffer ); + + /* The condition "eReturned == eProcessBuffer" must be true. */ + #if ( ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES == 0 ) + if( eReturned == eProcessBuffer ) + #endif + { + /* Interpret the received Ethernet packet. */ + switch( pxEthernetHeader->usFrameType ) + { + case ipARP_FRAME_TYPE: + + /* The Ethernet frame contains an ARP packet. */ + if( pxNetworkBuffer->xDataLength >= sizeof( ARPPacket_t ) ) + { + eReturned = eARPProcessPacket( ipCAST_PTR_TO_TYPE_PTR( ARPPacket_t, pxNetworkBuffer->pucEthernetBuffer ) ); + } + else + { + eReturned = eReleaseBuffer; + } + + break; + + case ipIPv4_FRAME_TYPE: + + /* The Ethernet frame contains an IP packet. */ + if( pxNetworkBuffer->xDataLength >= sizeof( IPPacket_t ) ) + { + eReturned = prvProcessIPPacket( ipCAST_PTR_TO_TYPE_PTR( IPPacket_t, pxNetworkBuffer->pucEthernetBuffer ), pxNetworkBuffer ); + } + else + { + eReturned = eReleaseBuffer; + } + + break; + + default: + /* No other packet types are handled. Nothing to do. */ + eReturned = eReleaseBuffer; + break; + } + } + } + + /* Perform any actions that resulted from processing the Ethernet frame. */ + switch( eReturned ) + { + case eReturnEthernetFrame: + + /* The Ethernet frame will have been updated (maybe it was + * an ARP request or a PING request?) and should be sent back to + * its source. */ + vReturnEthernetFrame( pxNetworkBuffer, pdTRUE ); + + /* parameter pdTRUE: the buffer must be released once + * the frame has been transmitted */ + break; + + case eFrameConsumed: + + /* The frame is in use somewhere, don't release the buffer + * yet. */ + break; + + case eReleaseBuffer: + case eProcessBuffer: + default: + + /* The frame is not being used anywhere, and the + * NetworkBufferDescriptor_t structure containing the frame should + * just be released back to the list of free buffers. */ + vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer ); + break; + } +} +/*-----------------------------------------------------------*/ + +/** + * @brief Is the IP address an IPv4 multicast address. + * + * @param[in] ulIPAddress: The IP address being checked. + * + * @return pdTRUE if the IP address is a multicast address or else, pdFALSE. + */ +BaseType_t xIsIPv4Multicast( uint32_t ulIPAddress ) +{ + BaseType_t xReturn; + uint32_t ulIP = FreeRTOS_ntohl( ulIPAddress ); + + if( ( ulIP >= ipFIRST_MULTI_CAST_IPv4 ) && ( ulIP < ipLAST_MULTI_CAST_IPv4 ) ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + + return xReturn; +} +/*-----------------------------------------------------------*/ + +/** + * @brief Set multicast MAC address. + * + * @param[in] ulIPAddress: IP address. + * @param[out] pxMACAddress: Pointer to MAC address. + */ +void vSetMultiCastIPv4MacAddress( uint32_t ulIPAddress, + MACAddress_t * pxMACAddress ) +{ + uint32_t ulIP = FreeRTOS_ntohl( ulIPAddress ); + + pxMACAddress->ucBytes[ 0 ] = ( uint8_t ) 0x01U; + pxMACAddress->ucBytes[ 1 ] = ( uint8_t ) 0x00U; + pxMACAddress->ucBytes[ 2 ] = ( uint8_t ) 0x5EU; + pxMACAddress->ucBytes[ 3 ] = ( uint8_t ) ( ( ulIP >> 16 ) & 0x7fU ); /* Use 7 bits. */ + pxMACAddress->ucBytes[ 4 ] = ( uint8_t ) ( ( ulIP >> 8 ) & 0xffU ); /* Use 8 bits. */ + pxMACAddress->ucBytes[ 5 ] = ( uint8_t ) ( ( ulIP ) & 0xffU ); /* Use 8 bits. */ +} +/*-----------------------------------------------------------*/ + +/** + * @brief Check whether this IP packet is to be allowed or to be dropped. + * + * @param[in] pxIPPacket: The IP packet under consideration. + * @param[in] pxNetworkBuffer: The whole network buffer. + * @param[in] uxHeaderLength: The length of the header. + * + * @return Whether the packet should be processed or dropped. + */ +static eFrameProcessingResult_t prvAllowIPPacket( const IPPacket_t * const pxIPPacket, + const NetworkBufferDescriptor_t * const pxNetworkBuffer, + UBaseType_t uxHeaderLength ) +{ + eFrameProcessingResult_t eReturn = eProcessBuffer; + + #if ( ( ipconfigETHERNET_DRIVER_FILTERS_PACKETS == 0 ) || ( ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 0 ) ) + const IPHeader_t * pxIPHeader = &( pxIPPacket->xIPHeader ); + #else + + /* or else, the parameter won't be used and the function will be optimised + * away */ + ( void ) pxIPPacket; + #endif + + #if ( ipconfigETHERNET_DRIVER_FILTERS_PACKETS == 0 ) + { + /* In systems with a very small amount of RAM, it might be advantageous + * to have incoming messages checked earlier, by the network card driver. + * This method may decrease the usage of sparse network buffers. */ + uint32_t ulDestinationIPAddress = pxIPHeader->ulDestinationIPAddress; + + /* Ensure that the incoming packet is not fragmented (only outgoing + * packets can be fragmented) as these are the only handled IP frames + * currently. */ + if( ( pxIPHeader->usFragmentOffset & ipFRAGMENT_OFFSET_BIT_MASK ) != 0U ) + { + /* Can not handle, fragmented packet. */ + eReturn = eReleaseBuffer; + } + + /* Test if the length of the IP-header is between 20 and 60 bytes, + * and if the IP-version is 4. */ + else if( ( pxIPHeader->ucVersionHeaderLength < ipIPV4_VERSION_HEADER_LENGTH_MIN ) || + ( pxIPHeader->ucVersionHeaderLength > ipIPV4_VERSION_HEADER_LENGTH_MAX ) ) + { + /* Can not handle, unknown or invalid header version. */ + eReturn = eReleaseBuffer; + } + /* Is the packet for this IP address? */ + else if( ( ulDestinationIPAddress != *ipLOCAL_IP_ADDRESS_POINTER ) && + /* Is it the global broadcast address 255.255.255.255 ? */ + ( ulDestinationIPAddress != ipBROADCAST_IP_ADDRESS ) && + /* Is it a specific broadcast address 192.168.1.255 ? */ + ( ulDestinationIPAddress != xNetworkAddressing.ulBroadcastAddress ) && + #if ( ipconfigUSE_LLMNR == 1 ) + /* Is it the LLMNR multicast address? */ + ( ulDestinationIPAddress != ipLLMNR_IP_ADDR ) && + #endif + /* Or (during DHCP negotiation) we have no IP-address yet? */ + ( *ipLOCAL_IP_ADDRESS_POINTER != 0UL ) ) + { + /* Packet is not for this node, release it */ + eReturn = eReleaseBuffer; + } + else + { + /* Packet is not fragmented, destination is this device. */ + } + } + #endif /* ipconfigETHERNET_DRIVER_FILTERS_PACKETS */ + + #if ( ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 0 ) + { + /* Some drivers of NIC's with checksum-offloading will enable the above + * define, so that the checksum won't be checked again here */ + if( eReturn == eProcessBuffer ) + { + /* Is the IP header checksum correct? */ + if( ( pxIPHeader->ucProtocol != ( uint8_t ) ipPROTOCOL_ICMP ) && + ( usGenerateChecksum( 0U, ( uint8_t * ) &( pxIPHeader->ucVersionHeaderLength ), ( size_t ) uxHeaderLength ) != ipCORRECT_CRC ) ) + { + /* Check sum in IP-header not correct. */ + eReturn = eReleaseBuffer; + } + /* Is the upper-layer checksum (TCP/UDP/ICMP) correct? */ + else if( usGenerateProtocolChecksum( ( uint8_t * ) ( pxNetworkBuffer->pucEthernetBuffer ), pxNetworkBuffer->xDataLength, pdFALSE ) != ipCORRECT_CRC ) + { + /* Protocol checksum not accepted. */ + eReturn = eReleaseBuffer; + } + else + { + /* The checksum of the received packet is OK. */ + } + } + } + #else /* if ( ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 0 ) */ + { + if( eReturn == eProcessBuffer ) + { + if( xCheckSizeFields( ( uint8_t * ) ( pxNetworkBuffer->pucEthernetBuffer ), pxNetworkBuffer->xDataLength ) != pdPASS ) + { + /* Some of the length checks were not successful. */ + eReturn = eReleaseBuffer; + } + } + + #if ( ipconfigUDP_PASS_ZERO_CHECKSUM_PACKETS == 0 ) + { + /* Check if this is a UDP packet without a checksum. */ + if( eReturn == eProcessBuffer ) + { + /* ipconfigUDP_PASS_ZERO_CHECKSUM_PACKETS is defined as 0, + * and so UDP packets carrying a protocol checksum of 0, will + * be dropped. */ + + /* Identify the next protocol. */ + if( pxIPPacket->xIPHeader.ucProtocol == ( uint8_t ) ipPROTOCOL_UDP ) + { + ProtocolPacket_t * pxProtPack; + const uint16_t * pusChecksum; + + /* pxProtPack will point to the offset were the protocols begin. */ + pxProtPack = ipCAST_PTR_TO_TYPE_PTR( ProtocolPacket_t, &( pxNetworkBuffer->pucEthernetBuffer[ uxHeaderLength - ipSIZE_OF_IPv4_HEADER ] ) ); + pusChecksum = ( const uint16_t * ) ( &( pxProtPack->xUDPPacket.xUDPHeader.usChecksum ) ); + + if( *pusChecksum == ( uint16_t ) 0U ) + { + #if ( ipconfigHAS_PRINTF != 0 ) + { + static BaseType_t xCount = 0; + + if( xCount < 5 ) + { + FreeRTOS_printf( ( "prvAllowIPPacket: UDP packet from %xip without CRC dropped\n", + FreeRTOS_ntohl( pxIPPacket->xIPHeader.ulSourceIPAddress ) ) ); + xCount++; + } + } + #endif /* ( ipconfigHAS_PRINTF != 0 ) */ + + /* Protocol checksum not accepted. */ + eReturn = eReleaseBuffer; + } + } + } + } + #endif /* ( ipconfigUDP_PASS_ZERO_CHECKSUM_PACKETS == 0 ) */ + + /* to avoid warning unused parameters */ + ( void ) uxHeaderLength; + } + #endif /* ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 0 */ + + return eReturn; +} +/*-----------------------------------------------------------*/ + +/** + * @brief Process an IP-packet. + * + * @param[in] pxIPPacket: The IP packet to be processed. + * @param[in] pxNetworkBuffer: The networkbuffer descriptor having the IP packet. + * + * @return An enum to show whether the packet should be released/kept/processed etc. + */ +static eFrameProcessingResult_t prvProcessIPPacket( IPPacket_t * pxIPPacket, + NetworkBufferDescriptor_t * const pxNetworkBuffer ) +{ + eFrameProcessingResult_t eReturn; + IPHeader_t * pxIPHeader = &( pxIPPacket->xIPHeader ); + size_t uxLength = ( size_t ) pxIPHeader->ucVersionHeaderLength; + UBaseType_t uxHeaderLength = ( UBaseType_t ) ( ( uxLength & 0x0FU ) << 2 ); + uint8_t ucProtocol; + + /* Bound the calculated header length: take away the Ethernet header size, + * then check if the IP header is claiming to be longer than the remaining + * total packet size. Also check for minimal header field length. */ + if( ( uxHeaderLength > ( pxNetworkBuffer->xDataLength - ipSIZE_OF_ETH_HEADER ) ) || + ( uxHeaderLength < ipSIZE_OF_IPv4_HEADER ) ) + { + eReturn = eReleaseBuffer; + } + else + { + ucProtocol = pxIPPacket->xIPHeader.ucProtocol; + /* Check if the IP headers are acceptable and if it has our destination. */ + eReturn = prvAllowIPPacket( pxIPPacket, pxNetworkBuffer, uxHeaderLength ); + + if( eReturn == eProcessBuffer ) + { + /* Are there IP-options. */ + if( uxHeaderLength > ipSIZE_OF_IPv4_HEADER ) + { + /* The size of the IP-header is larger than 20 bytes. + * The extra space is used for IP-options. */ + #if ( ipconfigIP_PASS_PACKETS_WITH_IP_OPTIONS != 0 ) + { + /* All structs of headers expect a IP header size of 20 bytes + * IP header options were included, we'll ignore them and cut them out. */ + const size_t optlen = ( ( size_t ) uxHeaderLength ) - ipSIZE_OF_IPv4_HEADER; + /* From: the previous start of UDP/ICMP/TCP data. */ + const uint8_t * pucSource = ( const uint8_t * ) &( pxNetworkBuffer->pucEthernetBuffer[ sizeof( EthernetHeader_t ) + uxHeaderLength ] ); + /* To: the usual start of UDP/ICMP/TCP data at offset 20 (decimal ) from IP header. */ + uint8_t * pucTarget = ( uint8_t * ) &( pxNetworkBuffer->pucEthernetBuffer[ sizeof( EthernetHeader_t ) + ipSIZE_OF_IPv4_HEADER ] ); + /* How many: total length minus the options and the lower headers. */ + const size_t xMoveLen = pxNetworkBuffer->xDataLength - ( optlen + ipSIZE_OF_IPv4_HEADER + ipSIZE_OF_ETH_HEADER ); + + ( void ) memmove( pucTarget, pucSource, xMoveLen ); + pxNetworkBuffer->xDataLength -= optlen; + + /* Rewrite the Version/IHL byte to indicate that this packet has no IP options. */ + pxIPHeader->ucVersionHeaderLength = ( pxIPHeader->ucVersionHeaderLength & 0xF0U ) | /* High nibble is the version. */ + ( ( ipSIZE_OF_IPv4_HEADER >> 2 ) & 0x0FU ); + } + #else /* if ( ipconfigIP_PASS_PACKETS_WITH_IP_OPTIONS != 0 ) */ + { + /* 'ipconfigIP_PASS_PACKETS_WITH_IP_OPTIONS' is not set, so packets carrying + * IP-options will be dropped. */ + eReturn = eReleaseBuffer; + } + #endif /* if ( ipconfigIP_PASS_PACKETS_WITH_IP_OPTIONS != 0 ) */ + } + + if( eReturn != eReleaseBuffer ) + { + /* Add the IP and MAC addresses to the ARP table if they are not + * already there - otherwise refresh the age of the existing + * entry. */ + if( ucProtocol != ( uint8_t ) ipPROTOCOL_UDP ) + { + /* Refresh the ARP cache with the IP/MAC-address of the received + * packet. For UDP packets, this will be done later in + * xProcessReceivedUDPPacket(), as soon as it's know that the message + * will be handled. This will prevent the ARP cache getting + * overwritten with the IP address of useless broadcast packets. */ + vARPRefreshCacheEntry( &( pxIPPacket->xEthernetHeader.xSourceAddress ), pxIPHeader->ulSourceIPAddress ); + } + + switch( ucProtocol ) + { + case ipPROTOCOL_ICMP: + + /* The IP packet contained an ICMP frame. Don't bother checking + * the ICMP checksum, as if it is wrong then the wrong data will + * also be returned, and the source of the ping will know something + * went wrong because it will not be able to validate what it + * receives. */ + #if ( ipconfigREPLY_TO_INCOMING_PINGS == 1 ) || ( ipconfigSUPPORT_OUTGOING_PINGS == 1 ) + if( pxNetworkBuffer->xDataLength >= sizeof( ICMPPacket_t ) ) + { + /* Map the buffer onto a ICMP-Packet struct to easily access the + * fields of ICMP packet. */ + ICMPPacket_t * pxICMPPacket = ipCAST_PTR_TO_TYPE_PTR( ICMPPacket_t, pxNetworkBuffer->pucEthernetBuffer ); + + if( pxIPHeader->ulDestinationIPAddress == *ipLOCAL_IP_ADDRESS_POINTER ) + { + eReturn = prvProcessICMPPacket( pxICMPPacket ); + } + } + else + { + eReturn = eReleaseBuffer; + } + #endif /* ( ipconfigREPLY_TO_INCOMING_PINGS == 1 ) || ( ipconfigSUPPORT_OUTGOING_PINGS == 1 ) */ + break; + + case ipPROTOCOL_UDP: + { + /* The IP packet contained a UDP frame. */ + + /* Map the buffer onto a UDP-Packet struct to easily access the + * fields of UDP packet. */ + const UDPPacket_t * pxUDPPacket = ipCAST_CONST_PTR_TO_CONST_TYPE_PTR( UDPPacket_t, pxNetworkBuffer->pucEthernetBuffer ); + uint16_t usLength; + + /* Note the header values required prior to the checksum + * generation as the checksum pseudo header may clobber some of + * these values. */ + usLength = FreeRTOS_ntohs( pxUDPPacket->xUDPHeader.usLength ); + + if( ( pxNetworkBuffer->xDataLength >= sizeof( UDPPacket_t ) ) && + ( ( ( size_t ) usLength ) >= sizeof( UDPHeader_t ) ) ) + { + size_t uxPayloadSize_1, uxPayloadSize_2; + + /* Ensure that downstream UDP packet handling has the lesser + * of: the actual network buffer Ethernet frame length, or + * the sender's UDP packet header payload length, minus the + * size of the UDP header. + * + * The size of the UDP packet structure in this implementation + * includes the size of the Ethernet header, the size of + * the IP header, and the size of the UDP header. */ + uxPayloadSize_1 = pxNetworkBuffer->xDataLength - sizeof( UDPPacket_t ); + uxPayloadSize_2 = ( ( size_t ) usLength ) - sizeof( UDPHeader_t ); + + if( uxPayloadSize_1 > uxPayloadSize_2 ) + { + pxNetworkBuffer->xDataLength = uxPayloadSize_2 + sizeof( UDPPacket_t ); + } + + /* Fields in pxNetworkBuffer (usPort, ulIPAddress) are network order. */ + pxNetworkBuffer->usPort = pxUDPPacket->xUDPHeader.usSourcePort; + pxNetworkBuffer->ulIPAddress = pxUDPPacket->xIPHeader.ulSourceIPAddress; + + /* ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM: + * In some cases, the upper-layer checksum has been calculated + * by the NIC driver. */ + + /* Pass the packet payload to the UDP sockets + * implementation. */ + if( xProcessReceivedUDPPacket( pxNetworkBuffer, + pxUDPPacket->xUDPHeader.usDestinationPort ) == pdPASS ) + { + eReturn = eFrameConsumed; + } + } + else + { + eReturn = eReleaseBuffer; + } + } + break; + + #if ipconfigUSE_TCP == 1 + case ipPROTOCOL_TCP: + + if( xProcessReceivedTCPPacket( pxNetworkBuffer ) == pdPASS ) + { + eReturn = eFrameConsumed; + } + + /* Setting this variable will cause xTCPTimerCheck() + * to be called just before the IP-task blocks. */ + xProcessedTCPMessage++; + break; + #endif /* if ipconfigUSE_TCP == 1 */ + default: + /* Not a supported frame type. */ + break; + } + } + } + } + + return eReturn; +} +/*-----------------------------------------------------------*/ + +#if ( ipconfigSUPPORT_OUTGOING_PINGS == 1 ) + +/** + * @brief Process an ICMP echo reply. + * + * @param[in] pxICMPPacket: The IP packet that contains the ICMP message. + */ + static void prvProcessICMPEchoReply( ICMPPacket_t * const pxICMPPacket ) + { + ePingReplyStatus_t eStatus = eSuccess; + uint16_t usDataLength, usCount; + uint8_t * pucByte; + + /* Find the total length of the IP packet. */ + usDataLength = pxICMPPacket->xIPHeader.usLength; + usDataLength = FreeRTOS_ntohs( usDataLength ); + + /* Remove the length of the IP headers to obtain the length of the ICMP + * message itself. */ + usDataLength = ( uint16_t ) ( ( ( uint32_t ) usDataLength ) - ipSIZE_OF_IPv4_HEADER ); + + /* Remove the length of the ICMP header, to obtain the length of + * data contained in the ping. */ + usDataLength = ( uint16_t ) ( ( ( uint32_t ) usDataLength ) - ipSIZE_OF_ICMP_HEADER ); + + /* Checksum has already been checked before in prvProcessIPPacket */ + + /* Find the first byte of the data within the ICMP packet. */ + pucByte = ( uint8_t * ) pxICMPPacket; + pucByte = &( pucByte[ sizeof( ICMPPacket_t ) ] ); + + /* Check each byte. */ + for( usCount = 0; usCount < usDataLength; usCount++ ) + { + if( *pucByte != ( uint8_t ) ipECHO_DATA_FILL_BYTE ) + { + eStatus = eInvalidData; + break; + } + + pucByte++; + } + + /* Call back into the application to pass it the result. */ + vApplicationPingReplyHook( eStatus, pxICMPPacket->xICMPHeader.usIdentifier ); + } + +#endif /* if ( ipconfigSUPPORT_OUTGOING_PINGS == 1 ) */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigREPLY_TO_INCOMING_PINGS == 1 ) + +/** + * @brief Process an ICMP echo request. + * + * @param[in,out] pxICMPPacket: The IP packet that contains the ICMP message. + */ + static eFrameProcessingResult_t prvProcessICMPEchoRequest( ICMPPacket_t * const pxICMPPacket ) + { + ICMPHeader_t * pxICMPHeader; + IPHeader_t * pxIPHeader; + uint16_t usRequest; + + pxICMPHeader = &( pxICMPPacket->xICMPHeader ); + pxIPHeader = &( pxICMPPacket->xIPHeader ); + + /* HT:endian: changed back */ + iptraceSENDING_PING_REPLY( pxIPHeader->ulSourceIPAddress ); + + /* The checksum can be checked here - but a ping reply should be + * returned even if the checksum is incorrect so the other end can + * tell that the ping was received - even if the ping reply contains + * invalid data. */ + pxICMPHeader->ucTypeOfMessage = ( uint8_t ) ipICMP_ECHO_REPLY; + pxIPHeader->ulDestinationIPAddress = pxIPHeader->ulSourceIPAddress; + pxIPHeader->ulSourceIPAddress = *ipLOCAL_IP_ADDRESS_POINTER; + + /* Update the checksum because the ucTypeOfMessage member in the header + * has been changed to ipICMP_ECHO_REPLY. This is faster than calling + * usGenerateChecksum(). */ + + /* due to compiler warning "integer operation result is out of range" */ + + usRequest = ( uint16_t ) ( ( uint16_t ) ipICMP_ECHO_REQUEST << 8 ); + + if( pxICMPHeader->usChecksum >= FreeRTOS_htons( 0xFFFFU - usRequest ) ) + { + pxICMPHeader->usChecksum = pxICMPHeader->usChecksum + FreeRTOS_htons( usRequest + 1U ); + } + else + { + pxICMPHeader->usChecksum = pxICMPHeader->usChecksum + FreeRTOS_htons( usRequest ); + } + + return eReturnEthernetFrame; + } + +#endif /* ipconfigREPLY_TO_INCOMING_PINGS == 1 */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigREPLY_TO_INCOMING_PINGS == 1 ) || ( ipconfigSUPPORT_OUTGOING_PINGS == 1 ) + +/** + * @brief Process an ICMP packet. Only echo requests and echo replies are recognised and handled. + * + * @param[in,out] pxICMPPacket: The IP packet that contains the ICMP message. + * + * @return eReleaseBuffer when the message buffer should be released, or eReturnEthernetFrame + * when the packet should be returned. + */ + static eFrameProcessingResult_t prvProcessICMPPacket( ICMPPacket_t * const pxICMPPacket ) + { + eFrameProcessingResult_t eReturn = eReleaseBuffer; + + iptraceICMP_PACKET_RECEIVED(); + + switch( pxICMPPacket->xICMPHeader.ucTypeOfMessage ) + { + case ipICMP_ECHO_REQUEST: + #if ( ipconfigREPLY_TO_INCOMING_PINGS == 1 ) + eReturn = prvProcessICMPEchoRequest( pxICMPPacket ); + #endif /* ( ipconfigREPLY_TO_INCOMING_PINGS == 1 ) */ + break; + + case ipICMP_ECHO_REPLY: + #if ( ipconfigSUPPORT_OUTGOING_PINGS == 1 ) + prvProcessICMPEchoReply( pxICMPPacket ); + #endif /* ipconfigSUPPORT_OUTGOING_PINGS */ + break; + + default: + /* Only ICMP echo packets are handled. */ + break; + } + + return eReturn; + } + +#endif /* ( ipconfigREPLY_TO_INCOMING_PINGS == 1 ) || ( ipconfigSUPPORT_OUTGOING_PINGS == 1 ) */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 1 ) + +/** + * @brief Although the driver will take care of checksum calculations, the IP-task + * will still check if the length fields are OK. + * + * @param[in] pucEthernetBuffer: The Ethernet packet received. + * @param[in] uxBufferLength: The total number of bytes received. + * + * @return pdPASS when the length fields in the packet OK, pdFAIL when the packet + * should be dropped. + */ + static BaseType_t xCheckSizeFields( const uint8_t * const pucEthernetBuffer, + size_t uxBufferLength ) + { + size_t uxLength; + const IPPacket_t * pxIPPacket; + UBaseType_t uxIPHeaderLength; + const ProtocolPacket_t * pxProtPack; + uint8_t ucProtocol; + uint16_t usLength; + uint16_t ucVersionHeaderLength; + size_t uxMinimumLength; + BaseType_t xResult = pdFAIL; + + DEBUG_DECLARE_TRACE_VARIABLE( BaseType_t, xLocation, 0 ); + + do + { + /* Check for minimum packet size: Ethernet header and an IP-header, 34 bytes */ + if( uxBufferLength < sizeof( IPPacket_t ) ) + { + DEBUG_SET_TRACE_VARIABLE( xLocation, 1 ); + break; + } + + /* Map the buffer onto a IP-Packet struct to easily access the + * fields of the IP packet. */ + pxIPPacket = ipCAST_CONST_PTR_TO_CONST_TYPE_PTR( IPPacket_t, pucEthernetBuffer ); + + ucVersionHeaderLength = pxIPPacket->xIPHeader.ucVersionHeaderLength; + + /* Test if the length of the IP-header is between 20 and 60 bytes, + * and if the IP-version is 4. */ + if( ( ucVersionHeaderLength < ipIPV4_VERSION_HEADER_LENGTH_MIN ) || + ( ucVersionHeaderLength > ipIPV4_VERSION_HEADER_LENGTH_MAX ) ) + { + DEBUG_SET_TRACE_VARIABLE( xLocation, 2 ); + break; + } + + ucVersionHeaderLength = ( ucVersionHeaderLength & ( uint8_t ) 0x0FU ) << 2; + uxIPHeaderLength = ( UBaseType_t ) ucVersionHeaderLength; + + /* Check if the complete IP-header is transferred. */ + if( uxBufferLength < ( ipSIZE_OF_ETH_HEADER + uxIPHeaderLength ) ) + { + DEBUG_SET_TRACE_VARIABLE( xLocation, 3 ); + break; + } + + /* Check if the complete IP-header plus protocol data have been transferred: */ + usLength = pxIPPacket->xIPHeader.usLength; + usLength = FreeRTOS_ntohs( usLength ); + + if( uxBufferLength < ( size_t ) ( ipSIZE_OF_ETH_HEADER + ( size_t ) usLength ) ) + { + DEBUG_SET_TRACE_VARIABLE( xLocation, 4 ); + break; + } + + /* Identify the next protocol. */ + ucProtocol = pxIPPacket->xIPHeader.ucProtocol; + + /* If this IP packet header includes Options, then the following + * assignment results in a pointer into the protocol packet with the Ethernet + * and IP headers incorrectly aligned. However, either way, the "third" + * protocol (Layer 3 or 4) header will be aligned, which is the convenience + * of this calculation. */ + + /* Map the Buffer onto the Protocol Packet struct for easy access to the + * struct fields. */ + pxProtPack = ipCAST_CONST_PTR_TO_CONST_TYPE_PTR( ProtocolPacket_t, &( pucEthernetBuffer[ uxIPHeaderLength - ipSIZE_OF_IPv4_HEADER ] ) ); + + /* Switch on the Layer 3/4 protocol. */ + if( ucProtocol == ( uint8_t ) ipPROTOCOL_UDP ) + { + /* Expect at least a complete UDP header. */ + uxMinimumLength = uxIPHeaderLength + ipSIZE_OF_ETH_HEADER + ipSIZE_OF_UDP_HEADER; + } + else if( ucProtocol == ( uint8_t ) ipPROTOCOL_TCP ) + { + uxMinimumLength = uxIPHeaderLength + ipSIZE_OF_ETH_HEADER + ipSIZE_OF_TCP_HEADER; + } + else if( ( ucProtocol == ( uint8_t ) ipPROTOCOL_ICMP ) || + ( ucProtocol == ( uint8_t ) ipPROTOCOL_IGMP ) ) + { + uxMinimumLength = uxIPHeaderLength + ipSIZE_OF_ETH_HEADER + ipSIZE_OF_ICMP_HEADER; + } + else + { + /* Unhandled protocol, other than ICMP, IGMP, UDP, or TCP. */ + DEBUG_SET_TRACE_VARIABLE( xLocation, 5 ); + break; + } + + if( uxBufferLength < uxMinimumLength ) + { + DEBUG_SET_TRACE_VARIABLE( xLocation, 6 ); + break; + } + + uxLength = ( size_t ) usLength; + uxLength -= ( ( uint16_t ) uxIPHeaderLength ); /* normally, minus 20. */ + + if( ( uxLength < ( ( size_t ) sizeof( pxProtPack->xUDPPacket.xUDPHeader ) ) ) || + ( uxLength > ( ( size_t ) ipconfigNETWORK_MTU - ( size_t ) uxIPHeaderLength ) ) ) + { + /* For incoming packets, the length is out of bound: either + * too short or too long. For outgoing packets, there is a + * serious problem with the format/length. */ + DEBUG_SET_TRACE_VARIABLE( xLocation, 7 ); + break; + } + + xResult = pdPASS; + } while( ipFALSE_BOOL ); + + if( xResult != pdPASS ) + { + /* NOP if ipconfigHAS_PRINTF != 1 */ + FreeRTOS_printf( ( "xCheckSizeFields: location %ld\n", xLocation ) ); + } + + return xResult; + } +#endif /* ( ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 1 ) */ +/*-----------------------------------------------------------*/ + +/** + * @brief Generate or check the protocol checksum of the data sent in the first parameter. + * At the same time, the length of the packet and the length of the different layers + * will be checked. + * + * @param[in] pucEthernetBuffer: The Ethernet buffer for which the checksum is to be calculated + * or checked. + * @param[in] uxBufferLength: the total number of bytes received, or the number of bytes written + * in the packet buffer. + * @param[in] xOutgoingPacket: Whether this is an outgoing packet or not. + * + * @return When xOutgoingPacket is false: the error code can be either: ipINVALID_LENGTH, + * ipUNHANDLED_PROTOCOL, ipWRONG_CRC, or ipCORRECT_CRC. + * When xOutgoingPacket is true: either ipINVALID_LENGTH or ipCORRECT_CRC. + */ +uint16_t usGenerateProtocolChecksum( const uint8_t * const pucEthernetBuffer, + size_t uxBufferLength, + BaseType_t xOutgoingPacket ) +{ + uint32_t ulLength; + uint16_t usChecksum, * pusChecksum; + const IPPacket_t * pxIPPacket; + UBaseType_t uxIPHeaderLength; + const ProtocolPacket_t * pxProtPack; + uint8_t ucProtocol; + + #if ( ipconfigHAS_DEBUG_PRINTF != 0 ) + const char * pcType; + #endif + uint16_t usLength; + uint16_t ucVersionHeaderLength; + DEBUG_DECLARE_TRACE_VARIABLE( BaseType_t, xLocation, 0 ); + + /* Introduce a do-while loop to allow use of break statements. + * Note: MISRA prohibits use of 'goto', thus replaced with breaks. */ + do + { + /* Check for minimum packet size. */ + if( uxBufferLength < sizeof( IPPacket_t ) ) + { + usChecksum = ipINVALID_LENGTH; + DEBUG_SET_TRACE_VARIABLE( xLocation, 1 ); + break; + } + + /* Parse the packet length. */ + pxIPPacket = ipCAST_CONST_PTR_TO_CONST_TYPE_PTR( IPPacket_t, pucEthernetBuffer ); + + /* Per https://tools.ietf.org/html/rfc791, the four-bit Internet Header + * Length field contains the length of the internet header in 32-bit words. */ + ucVersionHeaderLength = pxIPPacket->xIPHeader.ucVersionHeaderLength; + ucVersionHeaderLength = ( ucVersionHeaderLength & ( uint8_t ) 0x0FU ) << 2; + uxIPHeaderLength = ( UBaseType_t ) ucVersionHeaderLength; + + /* Check for minimum packet size. */ + if( uxBufferLength < ( sizeof( IPPacket_t ) + ( uxIPHeaderLength - ipSIZE_OF_IPv4_HEADER ) ) ) + { + usChecksum = ipINVALID_LENGTH; + DEBUG_SET_TRACE_VARIABLE( xLocation, 2 ); + break; + } + + usLength = pxIPPacket->xIPHeader.usLength; + usLength = FreeRTOS_ntohs( usLength ); + + if( uxBufferLength < ( size_t ) ( ipSIZE_OF_ETH_HEADER + ( size_t ) usLength ) ) + { + usChecksum = ipINVALID_LENGTH; + DEBUG_SET_TRACE_VARIABLE( xLocation, 3 ); + break; + } + + /* Identify the next protocol. */ + ucProtocol = pxIPPacket->xIPHeader.ucProtocol; + + /* N.B., if this IP packet header includes Options, then the following + * assignment results in a pointer into the protocol packet with the Ethernet + * and IP headers incorrectly aligned. However, either way, the "third" + * protocol (Layer 3 or 4) header will be aligned, which is the convenience + * of this calculation. */ + pxProtPack = ipCAST_CONST_PTR_TO_CONST_TYPE_PTR( ProtocolPacket_t, &( pucEthernetBuffer[ uxIPHeaderLength - ipSIZE_OF_IPv4_HEADER ] ) ); + + /* Switch on the Layer 3/4 protocol. */ + if( ucProtocol == ( uint8_t ) ipPROTOCOL_UDP ) + { + if( uxBufferLength < ( uxIPHeaderLength + ipSIZE_OF_ETH_HEADER + ipSIZE_OF_UDP_HEADER ) ) + { + usChecksum = ipINVALID_LENGTH; + DEBUG_SET_TRACE_VARIABLE( xLocation, 4 ); + break; + } + + pusChecksum = ( uint16_t * ) ( &( pxProtPack->xUDPPacket.xUDPHeader.usChecksum ) ); + #if ( ipconfigHAS_DEBUG_PRINTF != 0 ) + { + pcType = "UDP"; + } + #endif /* ipconfigHAS_DEBUG_PRINTF != 0 */ + } + else if( ucProtocol == ( uint8_t ) ipPROTOCOL_TCP ) + { + if( uxBufferLength < ( uxIPHeaderLength + ipSIZE_OF_ETH_HEADER + ipSIZE_OF_TCP_HEADER ) ) + { + usChecksum = ipINVALID_LENGTH; + DEBUG_SET_TRACE_VARIABLE( xLocation, 5 ); + break; + } + + pusChecksum = ( uint16_t * ) ( &( pxProtPack->xTCPPacket.xTCPHeader.usChecksum ) ); + #if ( ipconfigHAS_DEBUG_PRINTF != 0 ) + { + pcType = "TCP"; + } + #endif /* ipconfigHAS_DEBUG_PRINTF != 0 */ + } + else if( ( ucProtocol == ( uint8_t ) ipPROTOCOL_ICMP ) || + ( ucProtocol == ( uint8_t ) ipPROTOCOL_IGMP ) ) + { + if( uxBufferLength < ( uxIPHeaderLength + ipSIZE_OF_ETH_HEADER + ipSIZE_OF_ICMP_HEADER ) ) + { + usChecksum = ipINVALID_LENGTH; + DEBUG_SET_TRACE_VARIABLE( xLocation, 6 ); + break; + } + + pusChecksum = ( uint16_t * ) ( &( pxProtPack->xICMPPacket.xICMPHeader.usChecksum ) ); + #if ( ipconfigHAS_DEBUG_PRINTF != 0 ) + { + if( ucProtocol == ( uint8_t ) ipPROTOCOL_ICMP ) + { + pcType = "ICMP"; + } + else + { + pcType = "IGMP"; + } + } + #endif /* ipconfigHAS_DEBUG_PRINTF != 0 */ + } + else + { + /* Unhandled protocol, other than ICMP, IGMP, UDP, or TCP. */ + usChecksum = ipUNHANDLED_PROTOCOL; + DEBUG_SET_TRACE_VARIABLE( xLocation, 7 ); + break; + } + + /* The protocol and checksum field have been identified. Check the direction + * of the packet. */ + if( xOutgoingPacket != pdFALSE ) + { + /* This is an outgoing packet. Before calculating the checksum, set it + * to zero. */ + *( pusChecksum ) = 0U; + } + else if( ( *pusChecksum == 0U ) && ( ucProtocol == ( uint8_t ) ipPROTOCOL_UDP ) ) + { + #if ( ipconfigUDP_PASS_ZERO_CHECKSUM_PACKETS == 0 ) + { + /* Sender hasn't set the checksum, drop the packet because + * ipconfigUDP_PASS_ZERO_CHECKSUM_PACKETS is not set. */ + usChecksum = ipWRONG_CRC; + #if ( ipconfigHAS_PRINTF != 0 ) + { + static BaseType_t xCount = 0; + + if( xCount < 5 ) + { + FreeRTOS_printf( ( "usGenerateProtocolChecksum: UDP packet from %xip without CRC dropped\n", + FreeRTOS_ntohl( pxIPPacket->xIPHeader.ulSourceIPAddress ) ) ); + xCount++; + } + } + #endif /* ( ipconfigHAS_PRINTF != 0 ) */ + } + #else /* if ( ipconfigUDP_PASS_ZERO_CHECKSUM_PACKETS == 0 ) */ + { + /* Sender hasn't set the checksum, no use to calculate it. */ + usChecksum = ipCORRECT_CRC; + } + #endif /* if ( ipconfigUDP_PASS_ZERO_CHECKSUM_PACKETS == 0 ) */ + DEBUG_SET_TRACE_VARIABLE( xLocation, 8 ); + break; + } + else + { + /* Other incoming packet than UDP. */ + } + + usLength = pxIPPacket->xIPHeader.usLength; + usLength = FreeRTOS_ntohs( usLength ); + ulLength = ( uint32_t ) usLength; + ulLength -= ( ( uint16_t ) uxIPHeaderLength ); /* normally minus 20 */ + + if( ( ulLength < ( ( uint32_t ) sizeof( pxProtPack->xUDPPacket.xUDPHeader ) ) ) || + ( ulLength > ( ( uint32_t ) ipconfigNETWORK_MTU - ( uint32_t ) uxIPHeaderLength ) ) ) + { + #if ( ipconfigHAS_DEBUG_PRINTF != 0 ) + { + FreeRTOS_debug_printf( ( "usGenerateProtocolChecksum[%s]: len invalid: %lu\n", pcType, ulLength ) ); + } + #endif /* ipconfigHAS_DEBUG_PRINTF != 0 */ + + /* Again, in a 16-bit return value there is no space to indicate an + * error. For incoming packets, 0x1234 will cause dropping of the packet. + * For outgoing packets, there is a serious problem with the + * format/length */ + usChecksum = ipINVALID_LENGTH; + DEBUG_SET_TRACE_VARIABLE( xLocation, 9 ); + break; + } + + if( ucProtocol <= ( uint8_t ) ipPROTOCOL_IGMP ) + { + /* ICMP/IGMP do not have a pseudo header for CRC-calculation. */ + usChecksum = ( uint16_t ) + ( ~usGenerateChecksum( 0U, + ( const uint8_t * ) &( pxProtPack->xTCPPacket.xTCPHeader ), ( size_t ) ulLength ) ); + } + else + { + /* For UDP and TCP, sum the pseudo header, i.e. IP protocol + length + * fields */ + usChecksum = ( uint16_t ) ( ulLength + ( ( uint16_t ) ucProtocol ) ); + + /* And then continue at the IPv4 source and destination addresses. */ + usChecksum = ( uint16_t ) + ( ~usGenerateChecksum( usChecksum, + ipPOINTER_CAST( const uint8_t *, &( pxIPPacket->xIPHeader.ulSourceIPAddress ) ), + ( size_t ) ( ( 2U * ipSIZE_OF_IPv4_ADDRESS ) + ulLength ) ) ); + /* Sum TCP header and data. */ + } + + if( xOutgoingPacket == pdFALSE ) + { + /* This is in incoming packet. If the CRC is correct, it should be zero. */ + if( usChecksum == 0U ) + { + usChecksum = ( uint16_t ) ipCORRECT_CRC; + } + } + else + { + if( ( usChecksum == 0U ) && ( ucProtocol == ( uint8_t ) ipPROTOCOL_UDP ) ) + { + /* In case of UDP, a calculated checksum of 0x0000 is transmitted + * as 0xffff. A value of zero would mean that the checksum is not used. */ + #if ( ipconfigHAS_DEBUG_PRINTF != 0 ) + { + if( xOutgoingPacket != pdFALSE ) + { + FreeRTOS_debug_printf( ( "usGenerateProtocolChecksum[%s]: crc swap: %04X\n", pcType, usChecksum ) ); + } + } + #endif /* ipconfigHAS_DEBUG_PRINTF != 0 */ + + usChecksum = ( uint16_t ) 0xffffu; + } + } + + usChecksum = FreeRTOS_htons( usChecksum ); + + if( xOutgoingPacket != pdFALSE ) + { + *( pusChecksum ) = usChecksum; + } + + #if ( ipconfigHAS_DEBUG_PRINTF != 0 ) + else if( ( xOutgoingPacket == pdFALSE ) && ( usChecksum != ipCORRECT_CRC ) ) + { + FreeRTOS_debug_printf( ( "usGenerateProtocolChecksum[%s]: ID %04X: from %lxip to %lxip bad crc: %04X\n", + pcType, + FreeRTOS_ntohs( pxIPPacket->xIPHeader.usIdentification ), + FreeRTOS_ntohl( pxIPPacket->xIPHeader.ulSourceIPAddress ), + FreeRTOS_ntohl( pxIPPacket->xIPHeader.ulDestinationIPAddress ), + FreeRTOS_ntohs( *pusChecksum ) ) ); + } + else + { + /* Nothing. */ + } + #endif /* ipconfigHAS_DEBUG_PRINTF != 0 */ + } while( ipFALSE_BOOL ); + + if( ( usChecksum == ipUNHANDLED_PROTOCOL ) || + ( usChecksum == ipINVALID_LENGTH ) ) + { + /* NOP if ipconfigHAS_PRINTF != 0 */ + FreeRTOS_printf( ( "CRC error: %04x location %ld\n", usChecksum, xLocation ) ); + } + + return usChecksum; +} +/*-----------------------------------------------------------*/ + +/** + * This method generates a checksum for a given IPv4 header, per RFC791 (page 14). + * The checksum algorithm is described as: + * "[T]he 16 bit one's complement of the one's complement sum of all 16 bit words in the + * header. For purposes of computing the checksum, the value of the checksum field is zero." + * + * In a nutshell, that means that each 16-bit 'word' must be summed, after which + * the number of 'carries' (overflows) is added to the result. If that addition + * produces an overflow, that 'carry' must also be added to the final result. The final checksum + * should be the bitwise 'not' (ones-complement) of the result if the packet is + * meant to be transmitted, but this method simply returns the raw value, probably + * because when a packet is received, the checksum is verified by checking that + * ((received & calculated) == 0) without applying a bitwise 'not' to the 'calculated' checksum. + * + * This logic is optimized for microcontrollers which have limited resources, so the logic looks odd. + * It iterates over the full range of 16-bit words, but it does so by processing several 32-bit + * words at once whenever possible. Its first step is to align the memory pointer to a 32-bit boundary, + * after which it runs a fast loop to process multiple 32-bit words at once and adding their 'carries'. + * Finally, it finishes up by processing any remaining 16-bit words, and adding up all of the 'carries'. + * With 32-bit arithmetic, the number of 16-bit 'carries' produced by sequential additions can be found + * by looking at the 16 most-significant bits of the 32-bit integer, since a 32-bit int will continue + * counting up instead of overflowing after 16 bits. That is why the actual checksum calculations look like: + * union.u32 = ( uint32_t ) union.u16[ 0 ] + union.u16[ 1 ]; + * + * Arguments: + * ulSum: This argument provides a value to initialise the progressive summation + * of the header's values to. It is often 0, but protocols like TCP or UDP + * can have pseudo-header fields which need to be included in the checksum. + * pucNextData: This argument contains the address of the first byte which this + * method should process. The method's memory iterator is initialised to this value. + * uxDataLengthBytes: This argument contains the number of bytes that this method + * should process. + */ + +/** + * @brief Calculates the 16-bit checksum of an array of bytes + * + * @param[in] usSum: The initial sum, obtained from earlier data. + * @param[in] pucNextData: The actual data. + * @param[in] uxByteCount: The number of bytes. + * + * @return The 16-bit one's complement of the one's complement sum of all 16-bit + * words in the header + */ +uint16_t usGenerateChecksum( uint16_t usSum, + const uint8_t * pucNextData, + size_t uxByteCount ) +{ +/* MISRA/PC-lint doesn't like the use of unions. Here, they are a great + * aid though to optimise the calculations. */ + xUnion32 xSum2, xSum, xTerm; + xUnionPtr xSource; + xUnionPtr xLastSource; + uintptr_t uxAlignBits; + uint32_t ulCarry = 0UL; + uint16_t usTemp; + size_t uxDataLengthBytes = uxByteCount; + + /* Small MCUs often spend up to 30% of the time doing checksum calculations + * This function is optimised for 32-bit CPUs; Each time it will try to fetch + * 32-bits, sums it with an accumulator and counts the number of carries. */ + + /* Swap the input (little endian platform only). */ + usTemp = FreeRTOS_ntohs( usSum ); + xSum.u32 = ( uint32_t ) usTemp; + xTerm.u32 = 0UL; + + xSource.u8ptr = ipPOINTER_CAST( uint8_t *, pucNextData ); + uxAlignBits = ( ( ( uintptr_t ) pucNextData ) & 0x03U ); + + /* + * If pucNextData is non-aligned then the checksum is starting at an + * odd position and we need to make sure the usSum value now in xSum is + * as if it had been "aligned" in the same way. + */ + if( ( uxAlignBits & 1UL ) != 0U ) + { + xSum.u32 = ( ( xSum.u32 & 0xffU ) << 8 ) | ( ( xSum.u32 & 0xff00U ) >> 8 ); + } + + /* If byte (8-bit) aligned... */ + if( ( ( uxAlignBits & 1UL ) != 0UL ) && ( uxDataLengthBytes >= ( size_t ) 1 ) ) + { + xTerm.u8[ 1 ] = *( xSource.u8ptr ); + xSource.u8ptr++; + uxDataLengthBytes--; + /* Now xSource is word (16-bit) aligned. */ + } + + /* If half-word (16-bit) aligned... */ + if( ( ( uxAlignBits == 1U ) || ( uxAlignBits == 2U ) ) && ( uxDataLengthBytes >= 2U ) ) + { + xSum.u32 += *( xSource.u16ptr ); + xSource.u16ptr++; + uxDataLengthBytes -= 2U; + /* Now xSource is word (32-bit) aligned. */ + } + + /* Word (32-bit) aligned, do the most part. */ + xLastSource.u32ptr = ( xSource.u32ptr + ( uxDataLengthBytes / 4U ) ) - 3U; + + /* In this loop, four 32-bit additions will be done, in total 16 bytes. + * Indexing with constants (0,1,2,3) gives faster code than using + * post-increments. */ + while( xSource.u32ptr < xLastSource.u32ptr ) + { + /* Use a secondary Sum2, just to see if the addition produced an + * overflow. */ + xSum2.u32 = xSum.u32 + xSource.u32ptr[ 0 ]; + + if( xSum2.u32 < xSum.u32 ) + { + ulCarry++; + } + + /* Now add the secondary sum to the major sum, and remember if there was + * a carry. */ + xSum.u32 = xSum2.u32 + xSource.u32ptr[ 1 ]; + + if( xSum2.u32 > xSum.u32 ) + { + ulCarry++; + } + + /* And do the same trick once again for indexes 2 and 3 */ + xSum2.u32 = xSum.u32 + xSource.u32ptr[ 2 ]; + + if( xSum2.u32 < xSum.u32 ) + { + ulCarry++; + } + + xSum.u32 = xSum2.u32 + xSource.u32ptr[ 3 ]; + + if( xSum2.u32 > xSum.u32 ) + { + ulCarry++; + } + + /* And finally advance the pointer 4 * 4 = 16 bytes. */ + xSource.u32ptr = &( xSource.u32ptr[ 4 ] ); + } + + /* Now add all carries. */ + xSum.u32 = ( uint32_t ) xSum.u16[ 0 ] + xSum.u16[ 1 ] + ulCarry; + + uxDataLengthBytes %= 16U; + xLastSource.u8ptr = ( uint8_t * ) ( xSource.u8ptr + ( uxDataLengthBytes & ~( ( size_t ) 1 ) ) ); + + /* Half-word aligned. */ + + /* Coverity does not like Unions. Warning issued here: "The operator "<" + * is being applied to the pointers "xSource.u16ptr" and "xLastSource.u16ptr", + * which do not point into the same object." */ + while( xSource.u16ptr < xLastSource.u16ptr ) + { + /* At least one more short. */ + xSum.u32 += xSource.u16ptr[ 0 ]; + xSource.u16ptr++; + } + + if( ( uxDataLengthBytes & ( size_t ) 1 ) != 0U ) /* Maybe one more ? */ + { + xTerm.u8[ 0 ] = xSource.u8ptr[ 0 ]; + } + + xSum.u32 += xTerm.u32; + + /* Now add all carries again. */ + + /* Assigning value from "xTerm.u32" to "xSum.u32" here, but that stored value is overwritten before it can be used. + * Coverity doesn't understand about union variables. */ + xSum.u32 = ( uint32_t ) xSum.u16[ 0 ] + xSum.u16[ 1 ]; + + /* coverity[value_overwrite] */ + xSum.u32 = ( uint32_t ) xSum.u16[ 0 ] + xSum.u16[ 1 ]; + + if( ( uxAlignBits & 1U ) != 0U ) + { + /* Quite unlikely, but pucNextData might be non-aligned, which would + * mean that a checksum is calculated starting at an odd position. */ + xSum.u32 = ( ( xSum.u32 & 0xffU ) << 8 ) | ( ( xSum.u32 & 0xff00U ) >> 8 ); + } + + /* swap the output (little endian platform only). */ + return FreeRTOS_htons( ( ( uint16_t ) xSum.u32 ) ); +} +/*-----------------------------------------------------------*/ + +/* This function is used in other files, has external linkage e.g. in + * FreeRTOS_DNS.c. Not to be made static. */ + +/** + * @brief Send the Ethernet frame after checking for some conditions. + * + * @param[in,out] pxNetworkBuffer: The network buffer which is to be sent. + * @param[in] xReleaseAfterSend: Whether this network buffer is to be released or not. + */ +void vReturnEthernetFrame( NetworkBufferDescriptor_t * pxNetworkBuffer, + BaseType_t xReleaseAfterSend ) +{ + EthernetHeader_t * pxEthernetHeader; +/* memcpy() helper variables for MISRA Rule 21.15 compliance*/ + const void * pvCopySource; + void * pvCopyDest; + + #if ( ipconfigZERO_COPY_TX_DRIVER != 0 ) + NetworkBufferDescriptor_t * pxNewBuffer; + #endif + + #if defined( ipconfigETHERNET_MINIMUM_PACKET_BYTES ) + { + if( pxNetworkBuffer->xDataLength < ( size_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES ) + { + BaseType_t xIndex; + + FreeRTOS_printf( ( "vReturnEthernetFrame: length %u\n", ( unsigned ) pxNetworkBuffer->xDataLength ) ); + + for( xIndex = ( BaseType_t ) pxNetworkBuffer->xDataLength; xIndex < ( BaseType_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES; xIndex++ ) + { + pxNetworkBuffer->pucEthernetBuffer[ xIndex ] = 0U; + } + + pxNetworkBuffer->xDataLength = ( size_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES; + } + } + #endif /* if defined( ipconfigETHERNET_MINIMUM_PACKET_BYTES ) */ + + #if ( ipconfigZERO_COPY_TX_DRIVER != 0 ) + if( xReleaseAfterSend == pdFALSE ) + { + pxNewBuffer = pxDuplicateNetworkBufferWithDescriptor( pxNetworkBuffer, pxNetworkBuffer->xDataLength ); + + if( pxNewBuffer != NULL ) + { + xReleaseAfterSend = pdTRUE; + /* Want no rounding up. */ + pxNewBuffer->xDataLength = pxNetworkBuffer->xDataLength; + } + + pxNetworkBuffer = pxNewBuffer; + } + + if( pxNetworkBuffer != NULL ) + #endif /* if ( ipconfigZERO_COPY_TX_DRIVER != 0 ) */ + { + /* Map the Buffer to Ethernet Header struct for easy access to fields. */ + pxEthernetHeader = ipCAST_PTR_TO_TYPE_PTR( EthernetHeader_t, pxNetworkBuffer->pucEthernetBuffer ); + + /* + * Use helper variables for memcpy() to remain + * compliant with MISRA Rule 21.15. These should be + * optimized away. + */ + /* Swap source and destination MAC addresses. */ + pvCopySource = &pxEthernetHeader->xSourceAddress; + pvCopyDest = &pxEthernetHeader->xDestinationAddress; + ( void ) memcpy( pvCopyDest, pvCopySource, sizeof( pxEthernetHeader->xDestinationAddress ) ); + + pvCopySource = ipLOCAL_MAC_ADDRESS; + pvCopyDest = &pxEthernetHeader->xSourceAddress; + ( void ) memcpy( pvCopyDest, pvCopySource, ( size_t ) ipMAC_ADDRESS_LENGTH_BYTES ); + + /* Send! */ + iptraceNETWORK_INTERFACE_OUTPUT( pxNetworkBuffer->xDataLength, pxNetworkBuffer->pucEthernetBuffer ); + ( void ) xNetworkInterfaceOutput( pxNetworkBuffer, xReleaseAfterSend ); + } +} +/*-----------------------------------------------------------*/ + + +#if ( ipconfigHAS_PRINTF != 0 ) + + #ifndef ipMONITOR_MAX_HEAP + +/* As long as the heap has more space than e.g. 1 MB, there + * will be no messages. */ + #define ipMONITOR_MAX_HEAP ( 1024U * 1024U ) + #endif /* ipMONITOR_MAX_HEAP */ + + #ifndef ipMONITOR_PERCENTAGE_90 + /* Make this number lower to get less logging messages. */ + #define ipMONITOR_PERCENTAGE_90 ( 90U ) + #endif + + #define ipMONITOR_PERCENTAGE_100 ( 100U ) + +/** + * @brief A function that monitors a three resources: the heap, the space in the message + * queue of the IP-task, the number of available network buffer descriptors. + */ + void vPrintResourceStats( void ) + { + static UBaseType_t uxLastMinBufferCount = ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS; + static size_t uxMinLastSize = 0u; + UBaseType_t uxCurrentBufferCount; + size_t uxMinSize; + + /* When setting up and testing a project with FreeRTOS+TCP, it is + * can be helpful to monitor a few resources: the number of network + * buffers and the amount of available heap. + * This function will issue some logging when a minimum value has + * changed. */ + uxCurrentBufferCount = uxGetMinimumFreeNetworkBuffers(); + + if( uxLastMinBufferCount > uxCurrentBufferCount ) + { + /* The logging produced below may be helpful + * while tuning +TCP: see how many buffers are in use. */ + uxLastMinBufferCount = uxCurrentBufferCount; + FreeRTOS_printf( ( "Network buffers: %lu lowest %lu\n", + uxGetNumberOfFreeNetworkBuffers(), + uxCurrentBufferCount ) ); + } + + uxMinSize = xPortGetMinimumEverFreeHeapSize(); + + if( uxMinLastSize == 0U ) + { + /* Probably the first time this function is called. */ + uxMinLastSize = uxMinSize; + } + else if( uxMinSize >= ipMONITOR_MAX_HEAP ) + { + /* There is more than enough heap space. No need for logging. */ + } + /* Write logging if there is a 10% decrease since the last time logging was written. */ + else if( ( uxMinLastSize * ipMONITOR_PERCENTAGE_90 ) > ( uxMinSize * ipMONITOR_PERCENTAGE_100 ) ) + { + uxMinLastSize = uxMinSize; + FreeRTOS_printf( ( "Heap: current %lu lowest %lu\n", xPortGetFreeHeapSize(), uxMinSize ) ); + } + else + { + /* Nothing to log. */ + } + + #if ( ipconfigCHECK_IP_QUEUE_SPACE != 0 ) + { + static UBaseType_t uxLastMinQueueSpace = 0; + UBaseType_t uxCurrentCount = 0u; + + uxCurrentCount = uxGetMinimumIPQueueSpace(); + + if( uxLastMinQueueSpace != uxCurrentCount ) + { + /* The logging produced below may be helpful + * while tuning +TCP: see how many buffers are in use. */ + uxLastMinQueueSpace = uxCurrentCount; + FreeRTOS_printf( ( "Queue space: lowest %lu\n", uxCurrentCount ) ); + } + } + #endif /* ipconfigCHECK_IP_QUEUE_SPACE */ + } +#endif /* ( ipconfigHAS_PRINTF != 0 ) */ +/*-----------------------------------------------------------*/ + +/** + * @brief Returns the IP address of the NIC. + * + * @return The IP address of the NIC. + */ +uint32_t FreeRTOS_GetIPAddress( void ) +{ + return *ipLOCAL_IP_ADDRESS_POINTER; +} +/*-----------------------------------------------------------*/ + +/** + * @brief Sets the IP address of the NIC. + * + * @param[in] ulIPAddress: IP address of the NIC to be set. + */ +void FreeRTOS_SetIPAddress( uint32_t ulIPAddress ) +{ + *ipLOCAL_IP_ADDRESS_POINTER = ulIPAddress; +} +/*-----------------------------------------------------------*/ + +/** + * @brief Get the gateway address of the subnet. + * + * @return The IP-address of the gateway, zero if a gateway is + * not used/defined. + */ +uint32_t FreeRTOS_GetGatewayAddress( void ) +{ + return xNetworkAddressing.ulGatewayAddress; +} +/*-----------------------------------------------------------*/ + +/** + * @brief Get the DNS server address. + * + * @return The IP address of the DNS server. + */ +uint32_t FreeRTOS_GetDNSServerAddress( void ) +{ + return xNetworkAddressing.ulDNSServerAddress; +} +/*-----------------------------------------------------------*/ + +/** + * @brief Get the netmask for the subnet. + * + * @return The 32 bit netmask for the subnet. + */ +uint32_t FreeRTOS_GetNetmask( void ) +{ + return xNetworkAddressing.ulNetMask; +} +/*-----------------------------------------------------------*/ + +/** + * @brief Update the MAC address. + * + * @param[in] ucMACAddress: the MAC address to be set. + */ +void FreeRTOS_UpdateMACAddress( const uint8_t ucMACAddress[ ipMAC_ADDRESS_LENGTH_BYTES ] ) +{ + /* Copy the MAC address at the start of the default packet header fragment. */ + ( void ) memcpy( ipLOCAL_MAC_ADDRESS, ucMACAddress, ( size_t ) ipMAC_ADDRESS_LENGTH_BYTES ); +} +/*-----------------------------------------------------------*/ + +/** + * @brief Get the MAC address. + * + * @return The pointer to MAC address. + */ +const uint8_t * FreeRTOS_GetMACAddress( void ) +{ + return ipLOCAL_MAC_ADDRESS; +} +/*-----------------------------------------------------------*/ + +/** + * @brief Set the netmask for the subnet. + * + * @param[in] ulNetmask: The 32 bit netmask of the subnet. + */ +void FreeRTOS_SetNetmask( uint32_t ulNetmask ) +{ + xNetworkAddressing.ulNetMask = ulNetmask; +} +/*-----------------------------------------------------------*/ + +/** + * @brief Set the gateway address. + * + * @param[in] ulGatewayAddress: The gateway address. + */ +void FreeRTOS_SetGatewayAddress( uint32_t ulGatewayAddress ) +{ + xNetworkAddressing.ulGatewayAddress = ulGatewayAddress; +} +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_DHCP == 1 ) + +/** + * @brief Enable/disable the DHCP timer. + * + * @param[in] xEnableState: pdTRUE - enable timer; pdFALSE - disable timer. + */ + void vIPSetDHCPTimerEnableState( BaseType_t xEnableState ) + { + if( xEnableState != pdFALSE ) + { + xDHCPTimer.bActive = pdTRUE_UNSIGNED; + } + else + { + xDHCPTimer.bActive = pdFALSE_UNSIGNED; + } + } +#endif /* ipconfigUSE_DHCP */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_DHCP == 1 ) + +/** + * @brief Reload the DHCP timer. + * + * @param[in] ulLeaseTime: The reload value. + */ + void vIPReloadDHCPTimer( uint32_t ulLeaseTime ) + { + prvIPTimerReload( &xDHCPTimer, ulLeaseTime ); + } +#endif /* ipconfigUSE_DHCP */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigDNS_USE_CALLBACKS == 1 ) + +/** + * @brief Enable/disable the DNS timer. + * + * @param[in] xEnableState: pdTRUE - enable timer; pdFALSE - disable timer. + */ + void vIPSetDnsTimerEnableState( BaseType_t xEnableState ) + { + if( xEnableState != 0 ) + { + xDNSTimer.bActive = pdTRUE; + } + else + { + xDNSTimer.bActive = pdFALSE; + } + } + +#endif /* ipconfigUSE_DHCP */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigDNS_USE_CALLBACKS != 0 ) + +/** + * @brief Reload the DNS timer. + * + * @param[in] ulCheckTime: The reload value. + */ + void vIPReloadDNSTimer( uint32_t ulCheckTime ) + { + prvIPTimerReload( &xDNSTimer, ulCheckTime ); + } +#endif /* ipconfigDNS_USE_CALLBACKS != 0 */ +/*-----------------------------------------------------------*/ + +/** + * @brief Returns whether the IP task is ready. + * + * @return pdTRUE if IP task is ready, else pdFALSE. + */ +BaseType_t xIPIsNetworkTaskReady( void ) +{ + return xIPTaskInitialised; +} +/*-----------------------------------------------------------*/ + +/** + * @brief Returns whether this node is connected to network or not. + * + * @return pdTRUE if network is connected, else pdFALSE. + */ +BaseType_t FreeRTOS_IsNetworkUp( void ) +{ + return xNetworkUp; +} +/*-----------------------------------------------------------*/ + +#if ( ipconfigCHECK_IP_QUEUE_SPACE != 0 ) + +/** + * @brief Get the minimum space in the IP task queue. + * + * @return The minimum possible space in the IP task queue. + */ + UBaseType_t uxGetMinimumIPQueueSpace( void ) + { + return uxQueueMinimumSpace; + } +#endif +/*-----------------------------------------------------------*/ + +/** + * @brief Utility function: Convert error number to a human readable + * string. Declaration in FreeRTOS_errno_TCP.h. + * + * @param[in] xErrnum: The error number. + * @param[in] pcBuffer: Buffer big enough to be filled with the human readable message. + * @param[in] uxLength: Maximum length of the buffer. + * + * @return The buffer filled with human readable error string. + */ +const char * FreeRTOS_strerror_r( BaseType_t xErrnum, + char * pcBuffer, + size_t uxLength ) +{ + const char * pcName; + + switch( xErrnum ) + { + case pdFREERTOS_ERRNO_EADDRINUSE: + pcName = "EADDRINUSE"; + break; + + case pdFREERTOS_ERRNO_ENOMEM: + pcName = "ENOMEM"; + break; + + case pdFREERTOS_ERRNO_EADDRNOTAVAIL: + pcName = "EADDRNOTAVAIL"; + break; + + case pdFREERTOS_ERRNO_ENOPROTOOPT: + pcName = "ENOPROTOOPT"; + break; + + case pdFREERTOS_ERRNO_EBADF: + pcName = "EBADF"; + break; + + case pdFREERTOS_ERRNO_ENOSPC: + pcName = "ENOSPC"; + break; + + case pdFREERTOS_ERRNO_ECANCELED: + pcName = "ECANCELED"; + break; + + case pdFREERTOS_ERRNO_ENOTCONN: + pcName = "ENOTCONN"; + break; + + case pdFREERTOS_ERRNO_EINPROGRESS: + pcName = "EINPROGRESS"; + break; + + case pdFREERTOS_ERRNO_EOPNOTSUPP: + pcName = "EOPNOTSUPP"; + break; + + case pdFREERTOS_ERRNO_EINTR: + pcName = "EINTR"; + break; + + case pdFREERTOS_ERRNO_ETIMEDOUT: + pcName = "ETIMEDOUT"; + break; + + case pdFREERTOS_ERRNO_EINVAL: + pcName = "EINVAL"; + break; + + case pdFREERTOS_ERRNO_EWOULDBLOCK: + pcName = "EWOULDBLOCK"; + break; /* same as EAGAIN */ + + case pdFREERTOS_ERRNO_EISCONN: + pcName = "EISCONN"; + break; + + default: + /* Using function "snprintf". */ + ( void ) snprintf( pcBuffer, uxLength, "Errno %d", ( int32_t ) xErrnum ); + pcName = NULL; + break; + } + + if( pcName != NULL ) + { + /* Using function "snprintf". */ + ( void ) snprintf( pcBuffer, uxLength, "%s", pcName ); + } + + if( uxLength > 0U ) + { + pcBuffer[ uxLength - 1U ] = '\0'; + } + + return pcBuffer; +} +/*-----------------------------------------------------------*/ + +/* Provide access to private members for verification. */ +#ifdef FREERTOS_TCP_ENABLE_VERIFICATION + #include "aws_freertos_ip_verification_access_ip_define.h" +#endif diff --git a/examples/stm32/freertos-tcp/FreeRTOS_Sockets.c b/examples/stm32/freertos-tcp/FreeRTOS_Sockets.c new file mode 100644 index 00000000..2ed1e9a1 --- /dev/null +++ b/examples/stm32/freertos-tcp/FreeRTOS_Sockets.c @@ -0,0 +1,4853 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +/** + * @file FreeRTOS_Sockets.c + * @brief Implements the Sockets API based on Berkeley sockets for the FreeRTOS+TCP network stack. + * Sockets are used by the application processes to interact with the IP-task which in turn + * interacts with the hardware. + */ + +/* Standard includes. */ +#include +#include + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" +#include "semphr.h" + +/* FreeRTOS+TCP includes. */ +#include "FreeRTOS_UDP_IP.h" +#include "FreeRTOS_IP.h" +#include "FreeRTOS_Sockets.h" +#include "FreeRTOS_IP_Private.h" +#include "FreeRTOS_DNS.h" +#include "NetworkBufferManagement.h" + +/* The ItemValue of the sockets xBoundSocketListItem member holds the socket's + * port number. */ +/** @brief Set the port number for the socket in the xBoundSocketListItem. */ +#define socketSET_SOCKET_PORT( pxSocket, usPort ) listSET_LIST_ITEM_VALUE( ( &( ( pxSocket )->xBoundSocketListItem ) ), ( usPort ) ) +/** @brief Get the port number for the socket in the xBoundSocketListItem. */ +#define socketGET_SOCKET_PORT( pxSocket ) listGET_LIST_ITEM_VALUE( ( &( ( pxSocket )->xBoundSocketListItem ) ) ) + +/** @brief Test if a socket it bound which means it is either included in + * xBoundUDPSocketsList or xBoundTCPSocketsList + */ +#define socketSOCKET_IS_BOUND( pxSocket ) ( listLIST_ITEM_CONTAINER( &( pxSocket )->xBoundSocketListItem ) != NULL ) + +/** @brief If FreeRTOS_sendto() is called on a socket that is not bound to a port + * number then, depending on the FreeRTOSIPConfig.h settings, it might be + * that a port number is automatically generated for the socket. + * Automatically generated port numbers will be between + * socketAUTO_PORT_ALLOCATION_START_NUMBER and 0xffff. + * + * @note Per https://tools.ietf.org/html/rfc6056, "the dynamic ports consist of + * the range 49152-65535. However, ephemeral port selection algorithms should + * use the whole range 1024-65535" excluding those already in use (inbound + * or outbound). + */ +#if !defined( socketAUTO_PORT_ALLOCATION_START_NUMBER ) + #define socketAUTO_PORT_ALLOCATION_START_NUMBER ( ( uint16_t ) 0x0400 ) +#endif + +/** @brief Maximum value of port number which can be auto assigned. */ +#define socketAUTO_PORT_ALLOCATION_MAX_NUMBER ( ( uint16_t ) 0xffff ) + +/** @brief The number of octets that make up an IP address. */ +#define socketMAX_IP_ADDRESS_OCTETS 4U + +/** @brief A block time of 0 simply means "don't block". */ +#define socketDONT_BLOCK ( ( TickType_t ) 0 ) + +/** @brief TCP timer period in milliseconds. */ +#if ( ( ipconfigUSE_TCP == 1 ) && !defined( ipTCP_TIMER_PERIOD_MS ) ) + #define ipTCP_TIMER_PERIOD_MS ( 1000U ) +#endif + +/* Some helper macro's for defining the 20/80 % limits of uxLittleSpace / uxEnoughSpace. */ +#define sock20_PERCENT 20U /**< 20% of the defined limit. */ +#define sock80_PERCENT 80U /**< 80% of the defined limit. */ +#define sock100_PERCENT 100U /**< 100% of the defined limit. */ + +#if ( ipconfigUSE_CALLBACKS != 0 ) + static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( F_TCP_UDP_Handler_t ) + { + return ( F_TCP_UDP_Handler_t * ) pvArgument; + } + static portINLINE ipDECL_CAST_CONST_PTR_FUNC_FOR_TYPE( F_TCP_UDP_Handler_t ) + { + return ( const F_TCP_UDP_Handler_t * ) pvArgument; + } +#endif + + +/** + * @brief Utility function to cast pointer of a type to pointer of type NetworkBufferDescriptor_t. + * + * @return The casted pointer. + */ +static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( NetworkBufferDescriptor_t ) +{ + return ( NetworkBufferDescriptor_t * ) pvArgument; +} + + +/** + * @brief Utility function to cast pointer of a type to pointer of type StreamBuffer_t. + * + * @return The casted pointer. + */ +static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( StreamBuffer_t ) +{ + return ( StreamBuffer_t * ) pvArgument; +} +/*-----------------------------------------------------------*/ + +/* + * Allocate the next port number from the private allocation range. + * TCP and UDP each have their own series of port numbers + * ulProtocol is either ipPROTOCOL_UDP or ipPROTOCOL_TCP + */ +static uint16_t prvGetPrivatePortNumber( BaseType_t xProtocol ); + +/* + * Return the list item from within pxList that has an item value of + * xWantedItemValue. If there is no such list item return NULL. + */ +static const ListItem_t * pxListFindListItemWithValue( const List_t * pxList, + TickType_t xWantedItemValue ); + +/* + * Return pdTRUE only if pxSocket is valid and bound, as far as can be + * determined. + */ +static BaseType_t prvValidSocket( const FreeRTOS_Socket_t * pxSocket, + BaseType_t xProtocol, + BaseType_t xIsBound ); + +#if ( ipconfigUSE_TCP == 1 ) + +/* + * Internal function prvSockopt_so_buffer(): sets FREERTOS_SO_SNDBUF or + * FREERTOS_SO_RCVBUF properties of a socket. + */ + static BaseType_t prvSockopt_so_buffer( FreeRTOS_Socket_t * pxSocket, + int32_t lOptionName, + const void * pvOptionValue ); +#endif /* ipconfigUSE_TCP == 1 */ + +/* + * Before creating a socket, check the validity of the parameters used + * and find the size of the socket space, which is different for UDP and TCP + */ +static BaseType_t prvDetermineSocketSize( BaseType_t xDomain, + BaseType_t xType, + BaseType_t xProtocol, + size_t * pxSocketSize ); + +#if ( ipconfigUSE_TCP == 1 ) + +/* + * Create a txStream or a rxStream, depending on the parameter 'xIsInputStream' + */ + static StreamBuffer_t * prvTCPCreateStream( FreeRTOS_Socket_t * pxSocket, + BaseType_t xIsInputStream ); +#endif /* ipconfigUSE_TCP == 1 */ + +#if ( ipconfigUSE_TCP == 1 ) + +/* + * Called from FreeRTOS_send(): some checks which will be done before + * sending a TCP packed. + */ + static int32_t prvTCPSendCheck( FreeRTOS_Socket_t * pxSocket, + size_t uxDataLength ); +#endif /* ipconfigUSE_TCP */ + +#if ( ipconfigUSE_TCP == 1 ) + +/* + * When a child socket gets closed, make sure to update the child-count of the parent + */ + static void prvTCPSetSocketCount( FreeRTOS_Socket_t const * pxSocketToDelete ); +#endif /* ipconfigUSE_TCP == 1 */ + +#if ( ipconfigUSE_TCP == 1 ) + +/* + * Called from FreeRTOS_connect(): make some checks and if allowed, send a + * message to the IP-task to start connecting to a remote socket + */ + static BaseType_t prvTCPConnectStart( FreeRTOS_Socket_t * pxSocket, + struct freertos_sockaddr const * pxAddress ); +#endif /* ipconfigUSE_TCP */ + +#if ( ipconfigUSE_TCP == 1 ) + +/* + * Check if it makes any sense to wait for a connect event. + * It may return: -EINPROGRESS, -EAGAIN, or 0 for OK. + */ + static BaseType_t bMayConnect( FreeRTOS_Socket_t const * pxSocket ); +#endif /* ipconfigUSE_TCP */ + +#if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 ) + +/* Executed by the IP-task, it will check all sockets belonging to a set */ + static void prvFindSelectedSocket( SocketSelect_t * pxSocketSet ); + +#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */ +/*-----------------------------------------------------------*/ + +/** @brief The list that contains mappings between sockets and port numbers. + * Accesses to this list must be protected by critical sections of + * some kind. + */ +List_t xBoundUDPSocketsList; + +#if ipconfigUSE_TCP == 1 + +/** @brief The list that contains mappings between sockets and port numbers. + * Accesses to this list must be protected by critical sections of + * some kind. + */ + List_t xBoundTCPSocketsList; + +#endif /* ipconfigUSE_TCP == 1 */ + +/*-----------------------------------------------------------*/ + +/** + * @brief Check whether the socket is valid or not. + * + * @param[in] pxSocket: The socket being checked. + * @param[in] xProtocol: The protocol for which the socket was created. + * @param[in] xIsBound: pdTRUE when the socket should be bound, otherwise pdFALSE. + * + * @return If the socket is valid, then pdPASS is returned or else, pdFAIL + * is returned. + */ +static BaseType_t prvValidSocket( const FreeRTOS_Socket_t * pxSocket, + BaseType_t xProtocol, + BaseType_t xIsBound ) +{ + BaseType_t xReturn; + + if( ( pxSocket == NULL ) || ( pxSocket == FREERTOS_INVALID_SOCKET ) ) + { + xReturn = pdFALSE; + } + else if( ( xIsBound != pdFALSE ) && !socketSOCKET_IS_BOUND( pxSocket ) ) + { + /* The caller expects the socket to be bound, but it isn't. */ + xReturn = pdFALSE; + } + else if( pxSocket->ucProtocol != ( uint8_t ) xProtocol ) + { + /* Socket has a wrong type (UDP != TCP). */ + xReturn = pdFALSE; + } + else + { + xReturn = pdTRUE; + } + + return xReturn; +} +/*-----------------------------------------------------------*/ + +/** + * @brief Initialise the bound TCP/UDP socket lists. + */ +void vNetworkSocketsInit( void ) +{ + vListInitialise( &xBoundUDPSocketsList ); + + #if ( ipconfigUSE_TCP == 1 ) + { + vListInitialise( &xBoundTCPSocketsList ); + } + #endif /* ipconfigUSE_TCP == 1 */ +} +/*-----------------------------------------------------------*/ + +/** + * @brief Determine the socket size for the given protocol. + * + * @param[in] xDomain: The domain for which the size of socket is being determined. + * @param[in] xType: Is this a datagram socket or a stream socket. + * @param[in] xProtocol: The protocol being used. + * @param[out] pxSocketSize: Pointer to a variable in which the size shall be returned + * if all checks pass. + * + * @return pdPASS if socket size was determined and put in the parameter pxSocketSize + * correctly, else pdFAIL. + */ +static BaseType_t prvDetermineSocketSize( BaseType_t xDomain, + BaseType_t xType, + BaseType_t xProtocol, + size_t * pxSocketSize ) +{ + BaseType_t xReturn = pdPASS; + FreeRTOS_Socket_t const * pxSocket = NULL; + + /* Asserts must not appear before it has been determined that the network + * task is ready - otherwise the asserts will fail. */ + if( xIPIsNetworkTaskReady() == pdFALSE ) + { + xReturn = pdFAIL; + } + else + { + /* Only Ethernet is currently supported. */ + configASSERT( xDomain == FREERTOS_AF_INET ); + + /* Check if the UDP socket-list has been initialised. */ + configASSERT( listLIST_IS_INITIALISED( &xBoundUDPSocketsList ) ); + #if ( ipconfigUSE_TCP == 1 ) + { + /* Check if the TCP socket-list has been initialised. */ + configASSERT( listLIST_IS_INITIALISED( &xBoundTCPSocketsList ) ); + } + #endif /* ipconfigUSE_TCP == 1 */ + + if( xProtocol == FREERTOS_IPPROTO_UDP ) + { + if( xType != FREERTOS_SOCK_DGRAM ) + { + xReturn = pdFAIL; + configASSERT( xReturn == pdPASS ); + } + + /* In case a UDP socket is created, do not allocate space for TCP data. */ + *pxSocketSize = ( sizeof( *pxSocket ) - sizeof( pxSocket->u ) ) + sizeof( pxSocket->u.xUDP ); + } + + #if ( ipconfigUSE_TCP == 1 ) + else if( xProtocol == FREERTOS_IPPROTO_TCP ) + { + if( xType != FREERTOS_SOCK_STREAM ) + { + xReturn = pdFAIL; + configASSERT( xReturn == pdPASS ); + } + + *pxSocketSize = ( sizeof( *pxSocket ) - sizeof( pxSocket->u ) ) + sizeof( pxSocket->u.xTCP ); + } + #endif /* ipconfigUSE_TCP == 1 */ + else + { + xReturn = pdFAIL; + configASSERT( xReturn == pdPASS ); + } + } + + /* In case configASSERT() is not used */ + ( void ) xDomain; + ( void ) pxSocket; /* Was only used for sizeof. */ + return xReturn; +} +/*-----------------------------------------------------------*/ + +/** + * @brief allocate and initialise a socket. + * + * @param[in] xDomain: The domain in which the socket should be created. + * @param[in] xType: The type of the socket. + * @param[in] xProtocol: The protocol of the socket. + * + * @return FREERTOS_INVALID_SOCKET if the allocation failed, or if there was + * a parameter error, otherwise a valid socket. + */ +Socket_t FreeRTOS_socket( BaseType_t xDomain, + BaseType_t xType, + BaseType_t xProtocol ) +{ + FreeRTOS_Socket_t * pxSocket; + +/* Note that this value will be over-written by the call to prvDetermineSocketSize. */ + size_t uxSocketSize = 1; + EventGroupHandle_t xEventGroup; + Socket_t xReturn; + + if( prvDetermineSocketSize( xDomain, xType, xProtocol, &uxSocketSize ) == pdFAIL ) + { + xReturn = FREERTOS_INVALID_SOCKET; + } + else + { + /* Allocate the structure that will hold the socket information. The + * size depends on the type of socket: UDP sockets need less space. A + * define 'pvPortMallocSocket' will used to allocate the necessary space. + * By default it points to the FreeRTOS function 'pvPortMalloc()'. */ + pxSocket = ipCAST_PTR_TO_TYPE_PTR( FreeRTOS_Socket_t, pvPortMallocSocket( uxSocketSize ) ); + + if( pxSocket == NULL ) + { + xReturn = FREERTOS_INVALID_SOCKET; + iptraceFAILED_TO_CREATE_SOCKET(); + } + else + { + xEventGroup = xEventGroupCreate(); + + if( xEventGroup == NULL ) + { + vPortFreeSocket( pxSocket ); + xReturn = FREERTOS_INVALID_SOCKET; + iptraceFAILED_TO_CREATE_EVENT_GROUP(); + } + else + { + if( xProtocol == FREERTOS_IPPROTO_UDP ) + { + iptraceMEM_STATS_CREATE( tcpSOCKET_UDP, pxSocket, uxSocketSize + sizeof( StaticEventGroup_t ) ); + } + else + { + /* Lint wants at least a comment, in case the macro is empty. */ + iptraceMEM_STATS_CREATE( tcpSOCKET_TCP, pxSocket, uxSocketSize + sizeof( StaticEventGroup_t ) ); + } + + /* Clear the entire space to avoid nulling individual entries. */ + ( void ) memset( pxSocket, 0, uxSocketSize ); + + pxSocket->xEventGroup = xEventGroup; + + /* Initialise the socket's members. The semaphore will be created + * if the socket is bound to an address, for now the pointer to the + * semaphore is just set to NULL to show it has not been created. */ + if( xProtocol == FREERTOS_IPPROTO_UDP ) + { + vListInitialise( &( pxSocket->u.xUDP.xWaitingPacketsList ) ); + + #if ( ipconfigUDP_MAX_RX_PACKETS > 0U ) + { + pxSocket->u.xUDP.uxMaxPackets = ( UBaseType_t ) ipconfigUDP_MAX_RX_PACKETS; + } + #endif /* ipconfigUDP_MAX_RX_PACKETS > 0 */ + } + + vListInitialiseItem( &( pxSocket->xBoundSocketListItem ) ); + listSET_LIST_ITEM_OWNER( &( pxSocket->xBoundSocketListItem ), ipPOINTER_CAST( void *, pxSocket ) ); + + pxSocket->xReceiveBlockTime = ipconfigSOCK_DEFAULT_RECEIVE_BLOCK_TIME; + pxSocket->xSendBlockTime = ipconfigSOCK_DEFAULT_SEND_BLOCK_TIME; + pxSocket->ucSocketOptions = ( uint8_t ) FREERTOS_SO_UDPCKSUM_OUT; + pxSocket->ucProtocol = ( uint8_t ) xProtocol; /* protocol: UDP or TCP */ + + #if ( ipconfigUSE_TCP == 1 ) + { + if( xProtocol == FREERTOS_IPPROTO_TCP ) + { + /* StreamSize is expressed in number of bytes */ + /* Round up buffer sizes to nearest multiple of MSS */ + pxSocket->u.xTCP.usCurMSS = ( uint16_t ) ipconfigTCP_MSS; + pxSocket->u.xTCP.usInitMSS = ( uint16_t ) ipconfigTCP_MSS; + pxSocket->u.xTCP.uxRxStreamSize = ( size_t ) ipconfigTCP_RX_BUFFER_LENGTH; + pxSocket->u.xTCP.uxTxStreamSize = ( size_t ) FreeRTOS_round_up( ipconfigTCP_TX_BUFFER_LENGTH, ipconfigTCP_MSS ); + /* Use half of the buffer size of the TCP windows */ + #if ( ipconfigUSE_TCP_WIN == 1 ) + { + pxSocket->u.xTCP.uxRxWinSize = FreeRTOS_max_uint32( 1UL, ( uint32_t ) ( pxSocket->u.xTCP.uxRxStreamSize / 2U ) / ipconfigTCP_MSS ); + pxSocket->u.xTCP.uxTxWinSize = FreeRTOS_max_uint32( 1UL, ( uint32_t ) ( pxSocket->u.xTCP.uxTxStreamSize / 2U ) / ipconfigTCP_MSS ); + } + #else + { + pxSocket->u.xTCP.uxRxWinSize = 1U; + pxSocket->u.xTCP.uxTxWinSize = 1U; + } + #endif + + /* The above values are just defaults, and can be overridden by + * calling FreeRTOS_setsockopt(). No buffers will be allocated until a + * socket is connected and data is exchanged. */ + } + } + #endif /* ipconfigUSE_TCP == 1 */ + xReturn = pxSocket; + } + } + } + + /* Remove compiler warnings in the case the configASSERT() is not defined. */ + ( void ) xDomain; + + return xReturn; +} +/*-----------------------------------------------------------*/ + +#if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 ) + +/** + * @brief Create a socket set. + * + * @return The new socket set which was created, or NULL when allocation has failed. + */ + SocketSet_t FreeRTOS_CreateSocketSet( void ) + { + SocketSelect_t * pxSocketSet; + + pxSocketSet = ipCAST_PTR_TO_TYPE_PTR( SocketSelect_t, pvPortMalloc( sizeof( *pxSocketSet ) ) ); + + if( pxSocketSet != NULL ) + { + ( void ) memset( pxSocketSet, 0, sizeof( *pxSocketSet ) ); + pxSocketSet->xSelectGroup = xEventGroupCreate(); + + if( pxSocketSet->xSelectGroup == NULL ) + { + vPortFree( pxSocketSet ); + pxSocketSet = NULL; + } + else + { + /* Lint wants at least a comment, in case the macro is empty. */ + iptraceMEM_STATS_CREATE( tcpSOCKET_SET, pxSocketSet, sizeof( *pxSocketSet ) + sizeof( StaticEventGroup_t ) ); + } + } + + return ( SocketSet_t ) pxSocketSet; + } + +#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 ) + +/** + * @brief Delete a given socket set. + * + * @param[in] xSocketSet: The socket set being deleted. + */ + void FreeRTOS_DeleteSocketSet( SocketSet_t xSocketSet ) + { + SocketSelect_t * pxSocketSet = ( SocketSelect_t * ) xSocketSet; + + + iptraceMEM_STATS_DELETE( pxSocketSet ); + + vEventGroupDelete( pxSocketSet->xSelectGroup ); + vPortFree( pxSocketSet ); + } + +#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 ) + +/** + * @brief Add a socket to a set. + * + * @param[in] xSocket: The socket being added. + * @param[in] xSocketSet: The socket set being added to. + * @param[in] xBitsToSet: The event bits to set, a combination of the values defined + * in 'eSelectEvent_t', for read, write, exception, etc. + */ + void FreeRTOS_FD_SET( Socket_t xSocket, + SocketSet_t xSocketSet, + EventBits_t xBitsToSet ) + { + FreeRTOS_Socket_t * pxSocket = ( FreeRTOS_Socket_t * ) xSocket; + SocketSelect_t * pxSocketSet = ( SocketSelect_t * ) xSocketSet; + + + configASSERT( pxSocket != NULL ); + configASSERT( xSocketSet != NULL ); + + /* Make sure we're not adding bits which are reserved for internal use, + * such as eSELECT_CALL_IP */ + pxSocket->xSelectBits |= xBitsToSet & ( ( EventBits_t ) eSELECT_ALL ); + + if( ( pxSocket->xSelectBits & ( ( EventBits_t ) eSELECT_ALL ) ) != ( EventBits_t ) 0U ) + { + /* Adding a socket to a socket set. */ + pxSocket->pxSocketSet = ( SocketSelect_t * ) xSocketSet; + + /* Now have the IP-task call vSocketSelect() to see if the set contains + * any sockets which are 'ready' and set the proper bits. */ + prvFindSelectedSocket( pxSocketSet ); + } + } + +#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 ) + +/** + * @brief Clear select bits for a socket. If the mask becomes 0, + * remove the socket from the set. + * + * @param[in] xSocket: The socket whose select bits are being cleared. + * @param[in] xSocketSet: The socket set of the socket. + * @param[in] xBitsToClear: The bits to be cleared. Every '1' means that the + * corresponding bit will be cleared. See 'eSelectEvent_t' for + * the possible values. + */ + void FreeRTOS_FD_CLR( Socket_t xSocket, + SocketSet_t xSocketSet, + EventBits_t xBitsToClear ) + { + FreeRTOS_Socket_t * pxSocket = ( FreeRTOS_Socket_t * ) xSocket; + + configASSERT( pxSocket != NULL ); + configASSERT( xSocketSet != NULL ); + + pxSocket->xSelectBits &= ~( xBitsToClear & ( ( EventBits_t ) eSELECT_ALL ) ); + + if( ( pxSocket->xSelectBits & ( ( EventBits_t ) eSELECT_ALL ) ) != ( EventBits_t ) 0U ) + { + pxSocket->pxSocketSet = ( SocketSelect_t * ) xSocketSet; + } + else + { + /* disconnect it from the socket set */ + pxSocket->pxSocketSet = NULL; + } + } + + +#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */ +/*-----------------------------------------------------------*/ + + +#if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 ) + +/** + * @brief Test if a socket belongs to a socket-set and if so, which event bit(s) + * are set. + * + * @param[in] xSocket: The socket of interest. + * @param[in] xSocketSet: The socket set to which the socket belongs. + * + * @return If the socket belongs to the socket set: the event bits, otherwise zero. + */ + EventBits_t FreeRTOS_FD_ISSET( Socket_t xSocket, + SocketSet_t xSocketSet ) + { + EventBits_t xReturn; + const FreeRTOS_Socket_t * pxSocket = ( const FreeRTOS_Socket_t * ) xSocket; + + configASSERT( pxSocket != NULL ); + configASSERT( xSocketSet != NULL ); + + if( xSocketSet == ( SocketSet_t ) pxSocket->pxSocketSet ) + { + /* Make sure we're not adding bits which are reserved for internal + * use. */ + xReturn = pxSocket->xSocketBits & ( ( EventBits_t ) eSELECT_ALL ); + } + else + { + xReturn = 0; + } + + return xReturn; + } + + +#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 ) + +/** + * @brief The select() statement: wait for an event to occur on any of the sockets + * included in a socket set. + * + * @param[in] xSocketSet: The socket set including the sockets on which we are + * waiting for an event to occur. + * @param[in] xBlockTimeTicks: Maximum time ticks to wait for an event to occur. + * If the value is 'portMAX_DELAY' then the function will wait + * indefinitely for an event to occur. + * + * @return The socket which might have triggered the event bit. + */ + BaseType_t FreeRTOS_select( SocketSet_t xSocketSet, + TickType_t xBlockTimeTicks ) + { + TimeOut_t xTimeOut; + TickType_t xRemainingTime; + SocketSelect_t * pxSocketSet = ( SocketSelect_t * ) xSocketSet; + EventBits_t uxResult; + + configASSERT( xSocketSet != NULL ); + + /* Only in the first round, check for non-blocking */ + xRemainingTime = xBlockTimeTicks; + + /* Fetch the current time */ + vTaskSetTimeOutState( &xTimeOut ); + + for( ; ; ) + { + /* Find a socket which might have triggered the bit + * This function might return immediately or block for a limited time */ + uxResult = xEventGroupWaitBits( pxSocketSet->xSelectGroup, ( ( EventBits_t ) eSELECT_ALL ), pdFALSE, pdFALSE, xRemainingTime ); + + #if ( ipconfigSUPPORT_SIGNALS != 0 ) + { + if( ( uxResult & ( ( EventBits_t ) eSELECT_INTR ) ) != 0U ) + { + ( void ) xEventGroupClearBits( pxSocketSet->xSelectGroup, ( EventBits_t ) eSELECT_INTR ); + FreeRTOS_debug_printf( ( "FreeRTOS_select: interrupted\n" ) ); + break; + } + } + #endif /* ipconfigSUPPORT_SIGNALS */ + + /* Have the IP-task find the socket which had an event */ + prvFindSelectedSocket( pxSocketSet ); + + uxResult = xEventGroupGetBits( pxSocketSet->xSelectGroup ); + + if( uxResult != 0U ) + { + break; + } + + /* Has the timeout been reached? */ + if( xTaskCheckForTimeOut( &xTimeOut, &xRemainingTime ) != pdFALSE ) + { + break; + } + } + + return ( BaseType_t ) uxResult; + } + + +#endif /* ipconfigSUPPORT_SELECT_FUNCTION */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 ) + +/** + * @brief Send a message to the IP-task to have it check all sockets belonging to + * 'pxSocketSet' + * + * @param[in] pxSocketSet: The socket set being asked to check. + */ + static void prvFindSelectedSocket( SocketSelect_t * pxSocketSet ) + { + IPStackEvent_t xSelectEvent; + + #if ( ipconfigSELECT_USES_NOTIFY != 0 ) + SocketSelectMessage_t xSelectMessage; + #endif + + xSelectEvent.eEventType = eSocketSelectEvent; + #if ( ipconfigSELECT_USES_NOTIFY != 0 ) + { + xSelectMessage.pxSocketSet = pxSocketSet; + xSelectMessage.xTaskhandle = xTaskGetCurrentTaskHandle(); + xSelectEvent.pvData = &( xSelectMessage ); + } + #else + { + xSelectEvent.pvData = pxSocketSet; + + /* while the IP-task works on the request, the API will block on + * 'eSELECT_CALL_IP'. So clear it first. */ + ( void ) xEventGroupClearBits( pxSocketSet->xSelectGroup, ( BaseType_t ) eSELECT_CALL_IP ); + } + #endif /* if ( ipconfigSELECT_USES_NOTIFY != 0 ) */ + + /* Now send the socket select event */ + if( xSendEventStructToIPTask( &xSelectEvent, ( TickType_t ) portMAX_DELAY ) == pdFAIL ) + { + /* Oops, we failed to wake-up the IP task. No use to wait for it. */ + FreeRTOS_debug_printf( ( "prvFindSelectedSocket: failed\n" ) ); + } + else + { + /* As soon as the IP-task is ready, it will set 'eSELECT_CALL_IP' to + * wakeup the calling API */ + #if ( ipconfigSELECT_USES_NOTIFY != 0 ) + { + ( void ) ulTaskNotifyTake( pdFALSE, portMAX_DELAY ); + } + #else + { + ( void ) xEventGroupWaitBits( pxSocketSet->xSelectGroup, ( BaseType_t ) eSELECT_CALL_IP, pdTRUE, pdFALSE, portMAX_DELAY ); + } + #endif + } + } + + +#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */ +/*-----------------------------------------------------------*/ + +/** + * @brief Receive data from a bound socket. In this library, the function + * can only be used with connection-less sockets (UDP). For TCP sockets, + * please use FreeRTOS_recv(). + * + * @param[in] xSocket: The socket to which the data is sent i.e. the + * listening socket. + * @param[out] pvBuffer: The buffer in which the data being received is to + * be stored. + * @param[in] uxBufferLength: The length of the buffer. + * @param[in] xFlags: The flags to indicate preferences while calling this function. + * @param[out] pxSourceAddress: The source address from which the data is being sent. + * @param[out] pxSourceAddressLength: This parameter is used only to adhere to Berkeley + * sockets standard. It is not used internally. + * + * @return The number of bytes received. Or else, an error code is returned. When it + * returns a negative value, the cause can be looked-up in + * 'FreeRTOS_errno_TCP.h'. + */ +int32_t FreeRTOS_recvfrom( Socket_t xSocket, + void * pvBuffer, + size_t uxBufferLength, + BaseType_t xFlags, + struct freertos_sockaddr * pxSourceAddress, + socklen_t * pxSourceAddressLength ) +{ + BaseType_t lPacketCount; + NetworkBufferDescriptor_t * pxNetworkBuffer; + const void * pvCopySource; + FreeRTOS_Socket_t const * pxSocket = xSocket; + TickType_t xRemainingTime = ( TickType_t ) 0; /* Obsolete assignment, but some compilers output a warning if its not done. */ + BaseType_t xTimed = pdFALSE; + TimeOut_t xTimeOut; + int32_t lReturn; + EventBits_t xEventBits = ( EventBits_t ) 0; + size_t uxPayloadLength; + + if( prvValidSocket( pxSocket, FREERTOS_IPPROTO_UDP, pdTRUE ) == pdFALSE ) + { + lReturn = -pdFREERTOS_ERRNO_EINVAL; + } + else + { + lPacketCount = ( BaseType_t ) listCURRENT_LIST_LENGTH( &( pxSocket->u.xUDP.xWaitingPacketsList ) ); + + /* The function prototype is designed to maintain the expected Berkeley + * sockets standard, but this implementation does not use all the parameters. */ + ( void ) pxSourceAddressLength; + + while( lPacketCount == 0 ) + { + if( xTimed == pdFALSE ) + { + /* Check to see if the socket is non blocking on the first + * iteration. */ + xRemainingTime = pxSocket->xReceiveBlockTime; + + if( xRemainingTime == ( TickType_t ) 0 ) + { + #if ( ipconfigSUPPORT_SIGNALS != 0 ) + { + /* Just check for the interrupt flag. */ + xEventBits = xEventGroupWaitBits( pxSocket->xEventGroup, ( EventBits_t ) eSOCKET_INTR, + pdTRUE /*xClearOnExit*/, pdFALSE /*xWaitAllBits*/, socketDONT_BLOCK ); + } + #endif /* ipconfigSUPPORT_SIGNALS */ + break; + } + + if( ( ( ( UBaseType_t ) xFlags ) & ( ( UBaseType_t ) FREERTOS_MSG_DONTWAIT ) ) != 0U ) + { + break; + } + + /* To ensure this part only executes once. */ + xTimed = pdTRUE; + + /* Fetch the current time. */ + vTaskSetTimeOutState( &xTimeOut ); + } + + /* Wait for arrival of data. While waiting, the IP-task may set the + * 'eSOCKET_RECEIVE' bit in 'xEventGroup', if it receives data for this + * socket, thus unblocking this API call. */ + xEventBits = xEventGroupWaitBits( pxSocket->xEventGroup, ( ( EventBits_t ) eSOCKET_RECEIVE ) | ( ( EventBits_t ) eSOCKET_INTR ), + pdTRUE /*xClearOnExit*/, pdFALSE /*xWaitAllBits*/, xRemainingTime ); + + #if ( ipconfigSUPPORT_SIGNALS != 0 ) + { + if( ( xEventBits & ( EventBits_t ) eSOCKET_INTR ) != 0U ) + { + if( ( xEventBits & ( EventBits_t ) eSOCKET_RECEIVE ) != 0U ) + { + /* Shouldn't have cleared the eSOCKET_RECEIVE flag. */ + ( void ) xEventGroupSetBits( pxSocket->xEventGroup, ( EventBits_t ) eSOCKET_RECEIVE ); + } + + break; + } + } + #else /* if ( ipconfigSUPPORT_SIGNALS != 0 ) */ + { + ( void ) xEventBits; + } + #endif /* ipconfigSUPPORT_SIGNALS */ + + lPacketCount = ( BaseType_t ) listCURRENT_LIST_LENGTH( &( pxSocket->u.xUDP.xWaitingPacketsList ) ); + + if( lPacketCount != 0 ) + { + break; + } + + /* Has the timeout been reached ? */ + if( xTaskCheckForTimeOut( &xTimeOut, &xRemainingTime ) != pdFALSE ) + { + break; + } + } /* while( lPacketCount == 0 ) */ + + if( lPacketCount != 0 ) + { + taskENTER_CRITICAL(); + { + /* The owner of the list item is the network buffer. */ + pxNetworkBuffer = ipCAST_PTR_TO_TYPE_PTR( NetworkBufferDescriptor_t, listGET_OWNER_OF_HEAD_ENTRY( &( pxSocket->u.xUDP.xWaitingPacketsList ) ) ); + + if( ( ( UBaseType_t ) xFlags & ( UBaseType_t ) FREERTOS_MSG_PEEK ) == 0U ) + { + /* Remove the network buffer from the list of buffers waiting to + * be processed by the socket. */ + ( void ) uxListRemove( &( pxNetworkBuffer->xBufferListItem ) ); + } + } + taskEXIT_CRITICAL(); + + /* The returned value is the length of the payload data, which is + * calculated at the total packet size minus the headers. + * The validity of `xDataLength` prvProcessIPPacket has been confirmed + * in 'prvProcessIPPacket()'. */ + uxPayloadLength = pxNetworkBuffer->xDataLength - sizeof( UDPPacket_t ); + lReturn = ( int32_t ) uxPayloadLength; + + if( pxSourceAddress != NULL ) + { + pxSourceAddress->sin_port = pxNetworkBuffer->usPort; + pxSourceAddress->sin_addr = pxNetworkBuffer->ulIPAddress; + } + + if( ( ( UBaseType_t ) xFlags & ( UBaseType_t ) FREERTOS_ZERO_COPY ) == 0U ) + { + /* The zero copy flag is not set. Truncate the length if it won't + * fit in the provided buffer. */ + if( lReturn > ( int32_t ) uxBufferLength ) + { + iptraceRECVFROM_DISCARDING_BYTES( ( uxBufferLength - lReturn ) ); + lReturn = ( int32_t ) uxBufferLength; + } + + /* Copy the received data into the provided buffer, then release the + * network buffer. */ + pvCopySource = ( const void * ) &pxNetworkBuffer->pucEthernetBuffer[ ipUDP_PAYLOAD_OFFSET_IPv4 ]; + ( void ) memcpy( pvBuffer, pvCopySource, ( size_t ) lReturn ); + + if( ( ( UBaseType_t ) xFlags & ( UBaseType_t ) FREERTOS_MSG_PEEK ) == 0U ) + { + vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer ); + } + } + else + { + /* The zero copy flag was set. pvBuffer is not a buffer into which + * the received data can be copied, but a pointer that must be set to + * point to the buffer in which the received data has already been + * placed. */ + *( ( void ** ) pvBuffer ) = ipPOINTER_CAST( void *, &( pxNetworkBuffer->pucEthernetBuffer[ ipUDP_PAYLOAD_OFFSET_IPv4 ] ) ); + } + } + + #if ( ipconfigSUPPORT_SIGNALS != 0 ) + else if( ( xEventBits & ( EventBits_t ) eSOCKET_INTR ) != 0U ) + { + lReturn = -pdFREERTOS_ERRNO_EINTR; + iptraceRECVFROM_INTERRUPTED(); + } + #endif /* ipconfigSUPPORT_SIGNALS */ + else + { + lReturn = -pdFREERTOS_ERRNO_EWOULDBLOCK; + iptraceRECVFROM_TIMEOUT(); + } + } + + return lReturn; +} +/*-----------------------------------------------------------*/ + +/** + * @brief Send data to a socket. The socket must have already been created by a + * successful call to FreeRTOS_socket(). It works for UDP-sockets only. + * + * @param[in] xSocket: The socket being sent to. + * @param[in] pvBuffer: Pointer to the data being sent. + * @param[in] uxTotalDataLength: Length (in bytes) of the data being sent. + * @param[in] xFlags: Flags used to communicate preferences to the function. + * Possibly FREERTOS_MSG_DONTWAIT and/or FREERTOS_ZERO_COPY. + * @param[in] pxDestinationAddress: The address to which the data is to be sent. + * @param[in] xDestinationAddressLength: This parameter is present to adhere to the + * Berkeley sockets standard. Else, it is not used. + * + * @return When positive: the total number of bytes sent, when negative an error + * has occurred: it can be looked-up in 'FreeRTOS_errno_TCP.h'. + */ +int32_t FreeRTOS_sendto( Socket_t xSocket, + const void * pvBuffer, + size_t uxTotalDataLength, + BaseType_t xFlags, + const struct freertos_sockaddr * pxDestinationAddress, + socklen_t xDestinationAddressLength ) +{ + NetworkBufferDescriptor_t * pxNetworkBuffer; + void * pvCopyDest; + IPStackEvent_t xStackTxEvent = { eStackTxEvent, NULL }; + TimeOut_t xTimeOut; + TickType_t xTicksToWait; + int32_t lReturn = 0; + FreeRTOS_Socket_t const * pxSocket; + const size_t uxMaxPayloadLength = ipMAX_UDP_PAYLOAD_LENGTH; + const size_t uxPayloadOffset = ipUDP_PAYLOAD_OFFSET_IPv4; + + + pxSocket = ( FreeRTOS_Socket_t * ) xSocket; + + /* The function prototype is designed to maintain the expected Berkeley + * sockets standard, but this implementation does not use all the + * parameters. */ + ( void ) xDestinationAddressLength; + configASSERT( pvBuffer != NULL ); + + if( uxTotalDataLength <= ( size_t ) uxMaxPayloadLength ) + { + /* If the socket is not already bound to an address, bind it now. + * Passing NULL as the address parameter tells FreeRTOS_bind() to select + * the address to bind to. */ + if( socketSOCKET_IS_BOUND( pxSocket ) || + ( FreeRTOS_bind( xSocket, NULL, 0U ) == 0 ) ) + { + xTicksToWait = pxSocket->xSendBlockTime; + + #if ( ipconfigUSE_CALLBACKS != 0 ) + { + if( xIsCallingFromIPTask() != pdFALSE ) + { + /* If this send function is called from within a call-back + * handler it may not block, otherwise chances would be big to + * get a deadlock: the IP-task waiting for itself. */ + xTicksToWait = ( TickType_t ) 0; + } + } + #endif /* ipconfigUSE_CALLBACKS */ + + if( ( ( UBaseType_t ) xFlags & ( UBaseType_t ) FREERTOS_MSG_DONTWAIT ) != 0U ) + { + xTicksToWait = ( TickType_t ) 0; + } + + if( ( ( UBaseType_t ) xFlags & ( UBaseType_t ) FREERTOS_ZERO_COPY ) == 0U ) + { + /* Zero copy is not set, so obtain a network buffer into + * which the payload will be copied. */ + vTaskSetTimeOutState( &xTimeOut ); + + /* Block until a buffer becomes available, or until a + * timeout has been reached */ + pxNetworkBuffer = pxGetNetworkBufferWithDescriptor( uxPayloadOffset + uxTotalDataLength, xTicksToWait ); + + if( pxNetworkBuffer != NULL ) + { + pvCopyDest = ( void * ) &pxNetworkBuffer->pucEthernetBuffer[ uxPayloadOffset ]; + ( void ) memcpy( pvCopyDest, pvBuffer, uxTotalDataLength ); + + if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdTRUE ) + { + /* The entire block time has been used up. */ + xTicksToWait = ( TickType_t ) 0; + } + } + } + else + { + /* When zero copy is used, pvBuffer is a pointer to the + * payload of a buffer that has already been obtained from the + * stack. Obtain the network buffer pointer from the buffer. */ + pxNetworkBuffer = pxUDPPayloadBuffer_to_NetworkBuffer( pvBuffer ); + } + + if( pxNetworkBuffer != NULL ) + { + /* xDataLength is the size of the total packet, including the Ethernet header. */ + pxNetworkBuffer->xDataLength = uxTotalDataLength + sizeof( UDPPacket_t ); + pxNetworkBuffer->usPort = pxDestinationAddress->sin_port; + pxNetworkBuffer->usBoundPort = ( uint16_t ) socketGET_SOCKET_PORT( pxSocket ); + pxNetworkBuffer->ulIPAddress = pxDestinationAddress->sin_addr; + + /* The socket options are passed to the IP layer in the + * space that will eventually get used by the Ethernet header. */ + pxNetworkBuffer->pucEthernetBuffer[ ipSOCKET_OPTIONS_OFFSET ] = pxSocket->ucSocketOptions; + + /* Tell the networking task that the packet needs sending. */ + xStackTxEvent.pvData = pxNetworkBuffer; + + /* Ask the IP-task to send this packet */ + if( xSendEventStructToIPTask( &xStackTxEvent, xTicksToWait ) == pdPASS ) + { + /* The packet was successfully sent to the IP task. */ + lReturn = ( int32_t ) uxTotalDataLength; + #if ( ipconfigUSE_CALLBACKS == 1 ) + { + if( ipconfigIS_VALID_PROG_ADDRESS( pxSocket->u.xUDP.pxHandleSent ) ) + { + pxSocket->u.xUDP.pxHandleSent( xSocket, uxTotalDataLength ); + } + } + #endif /* ipconfigUSE_CALLBACKS */ + } + else + { + /* If the buffer was allocated in this function, release + * it. */ + if( ( ( UBaseType_t ) xFlags & ( UBaseType_t ) FREERTOS_ZERO_COPY ) == 0U ) + { + vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer ); + } + + iptraceSTACK_TX_EVENT_LOST( ipSTACK_TX_EVENT ); + } + } + else + { + /* If errno was available, errno would be set to + * FREERTOS_ENOPKTS. As it is, the function must return the + * number of transmitted bytes, so the calling function knows + * how much data was actually sent. */ + iptraceNO_BUFFER_FOR_SENDTO(); + } + } + else + { + /* No comment. */ + iptraceSENDTO_SOCKET_NOT_BOUND(); + } + } + else + { + /* The data is longer than the available buffer space. */ + iptraceSENDTO_DATA_TOO_LONG(); + } + + return lReturn; +} /* Tested */ +/*-----------------------------------------------------------*/ + +/** + * @brief binds a socket to a local port number. If port 0 is provided, + * a system provided port number will be assigned. This function + * can be used for both UDP and TCP sockets. The actual binding + * will be performed by the IP-task to avoid mutual access to the + * bound-socket-lists (xBoundUDPSocketsList or xBoundTCPSocketsList). + * + * @param[in] xSocket: The socket being bound. + * @param[in] pxAddress: The address struct carrying the port number to which + * this socket is to be bound. + * @param[in] xAddressLength: This parameter is not used internally. The + * function signature is used to adhere to standard + * Berkeley sockets API. + * + * @return The return value is 0 if the bind is successful. + * If some error occurred, then a negative value is returned. + */ +BaseType_t FreeRTOS_bind( Socket_t xSocket, + struct freertos_sockaddr const * pxAddress, + socklen_t xAddressLength ) +{ + IPStackEvent_t xBindEvent; + FreeRTOS_Socket_t * pxSocket = ( FreeRTOS_Socket_t * ) xSocket; + BaseType_t xReturn = 0; + + ( void ) xAddressLength; + + configASSERT( xIsCallingFromIPTask() == pdFALSE ); + + if( ( pxSocket == NULL ) || ( pxSocket == FREERTOS_INVALID_SOCKET ) ) + { + xReturn = -pdFREERTOS_ERRNO_EINVAL; + } + + /* Once a socket is bound to a port, it can not be bound to a different + * port number */ + else if( socketSOCKET_IS_BOUND( pxSocket ) ) + { + /* The socket is already bound. */ + FreeRTOS_debug_printf( ( "vSocketBind: Socket already bound to %d\n", pxSocket->usLocalPort ) ); + xReturn = -pdFREERTOS_ERRNO_EINVAL; + } + else + { + /* Prepare a messages to the IP-task in order to perform the binding. + * The desired port number will be passed in usLocalPort. */ + xBindEvent.eEventType = eSocketBindEvent; + xBindEvent.pvData = xSocket; + + if( pxAddress != NULL ) + { + pxSocket->usLocalPort = FreeRTOS_ntohs( pxAddress->sin_port ); + } + else + { + /* Caller wants to bind to a random port number. */ + pxSocket->usLocalPort = 0U; + } + + /* portMAX_DELAY is used as a the time-out parameter, as binding *must* + * succeed before the socket can be used. _RB_ The use of an infinite + * block time needs be changed as it could result in the task hanging. */ + if( xSendEventStructToIPTask( &xBindEvent, ( TickType_t ) portMAX_DELAY ) == pdFAIL ) + { + /* Failed to wake-up the IP-task, no use to wait for it */ + FreeRTOS_debug_printf( ( "FreeRTOS_bind: send event failed\n" ) ); + xReturn = -pdFREERTOS_ERRNO_ECANCELED; + } + else + { + /* The IP-task will set the 'eSOCKET_BOUND' bit when it has done its + * job. */ + ( void ) xEventGroupWaitBits( pxSocket->xEventGroup, ( EventBits_t ) eSOCKET_BOUND, pdTRUE /*xClearOnExit*/, pdFALSE /*xWaitAllBits*/, portMAX_DELAY ); + + if( !socketSOCKET_IS_BOUND( pxSocket ) ) + { + xReturn = -pdFREERTOS_ERRNO_EINVAL; + } + } + } + + return xReturn; +} +/*-----------------------------------------------------------*/ + +/** + * @brief Internal version of bind() that should not be called directly. + * 'xInternal' is used for TCP sockets only: it allows to have several + * (connected) child sockets bound to the same server port. + * + * @param[in] pxSocket: The socket is to be bound. + * @param[in] pxBindAddress: The port to which this socket should be bound. + * @param[in] uxAddressLength: The address length. + * @param[in] xInternal: pdTRUE is calling internally, else pdFALSE. + * + * @return If the socket was bound to a port successfully, then a 0 is returned. + * Or else, an error code is returned. + */ +BaseType_t vSocketBind( FreeRTOS_Socket_t * pxSocket, + struct freertos_sockaddr * pxBindAddress, + size_t uxAddressLength, + BaseType_t xInternal ) +{ + BaseType_t xReturn = 0; /* In Berkeley sockets, 0 means pass for bind(). */ + List_t * pxSocketList; + struct freertos_sockaddr * pxAddress = pxBindAddress; + + #if ( ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND == 1 ) + struct freertos_sockaddr xAddress; + #endif /* ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND */ + + #if ( ipconfigUSE_TCP == 1 ) + if( pxSocket->ucProtocol == ( uint8_t ) FREERTOS_IPPROTO_TCP ) + { + pxSocketList = &xBoundTCPSocketsList; + } + else + #endif /* ipconfigUSE_TCP == 1 */ + { + pxSocketList = &xBoundUDPSocketsList; + } + + /* The function prototype is designed to maintain the expected Berkeley + * sockets standard, but this implementation does not use all the parameters. */ + ( void ) uxAddressLength; + + configASSERT( pxSocket != NULL ); + configASSERT( pxSocket != FREERTOS_INVALID_SOCKET ); + + #if ( ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND == 1 ) + { + /* pxAddress will be NULL if sendto() was called on a socket without the + * socket being bound to an address. In this case, automatically allocate + * an address to the socket. There is a small chance that the allocated + * port will already be in use - if that is the case, then the check below + * [pxListFindListItemWithValue()] will result in an error being returned. */ + if( pxAddress == NULL ) + { + pxAddress = &xAddress; + /* Put the port to zero to be assigned later. */ + pxAddress->sin_port = 0U; + } + } + #endif /* ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND == 1 */ + + /* Sockets must be bound before calling FreeRTOS_sendto() if + * ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND is not set to 1. */ + configASSERT( pxAddress != NULL ); + + #if ( ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND == 1 ) + /* pxAddress is not NULL, no testing needed. */ + #else + if( pxAddress != NULL ) + #endif + { + /* Add a do-while loop to facilitate use of 'break' statements. */ + do + { + if( pxAddress->sin_port == 0U ) + { + pxAddress->sin_port = prvGetPrivatePortNumber( ( BaseType_t ) pxSocket->ucProtocol ); + + if( pxAddress->sin_port == ( uint16_t ) 0U ) + { + xReturn = -pdFREERTOS_ERRNO_EADDRNOTAVAIL; + break; + } + } + + /* If vSocketBind() is called from the API FreeRTOS_bind() it has been + * confirmed that the socket was not yet bound to a port. If it is called + * from the IP-task, no such check is necessary. */ + + /* Check to ensure the port is not already in use. If the bind is + * called internally, a port MAY be used by more than one socket. */ + if( ( ( xInternal == pdFALSE ) || ( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP ) ) && + ( pxListFindListItemWithValue( pxSocketList, ( TickType_t ) pxAddress->sin_port ) != NULL ) ) + { + FreeRTOS_debug_printf( ( "vSocketBind: %sP port %d in use\n", + ( pxSocket->ucProtocol == ( uint8_t ) FREERTOS_IPPROTO_TCP ) ? "TC" : "UD", + FreeRTOS_ntohs( pxAddress->sin_port ) ) ); + xReturn = -pdFREERTOS_ERRNO_EADDRINUSE; + } + else + { + /* Allocate the port number to the socket. + * This macro will set 'xBoundSocketListItem->xItemValue' */ + socketSET_SOCKET_PORT( pxSocket, pxAddress->sin_port ); + + /* And also store it in a socket field 'usLocalPort' in host-byte-order, + * mostly used for logging and debugging purposes */ + pxSocket->usLocalPort = FreeRTOS_ntohs( pxAddress->sin_port ); + + /* Add the socket to the list of bound ports. */ + { + /* If the network driver can iterate through 'xBoundUDPSocketsList', + * by calling xPortHasUDPSocket() then the IP-task must temporarily + * suspend the scheduler to keep the list in a consistent state. */ + #if ( ipconfigETHERNET_DRIVER_FILTERS_PACKETS == 1 ) + { + vTaskSuspendAll(); + } + #endif /* ipconfigETHERNET_DRIVER_FILTERS_PACKETS */ + + /* Add the socket to 'xBoundUDPSocketsList' or 'xBoundTCPSocketsList' */ + vListInsertEnd( pxSocketList, &( pxSocket->xBoundSocketListItem ) ); + + #if ( ipconfigETHERNET_DRIVER_FILTERS_PACKETS == 1 ) + { + ( void ) xTaskResumeAll(); + } + #endif /* ipconfigETHERNET_DRIVER_FILTERS_PACKETS */ + } + } + } while( ipFALSE_BOOL ); + } + + #if ( ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND == 0 ) + else + { + xReturn = -pdFREERTOS_ERRNO_EADDRNOTAVAIL; + FreeRTOS_debug_printf( ( "vSocketBind: Socket no addr\n" ) ); + } + #endif + + if( xReturn != 0 ) + { + iptraceBIND_FAILED( xSocket, ( FreeRTOS_ntohs( pxAddress->sin_port ) ) ); + } + + return xReturn; +} /* Tested */ +/*-----------------------------------------------------------*/ + +/** + * @brief Close a socket and free the allocated space. In case of a TCP socket: + * the connection will not be closed automatically. Subsequent messages + * for the closed socket will be responded to with a RST. The IP-task + * will actually close the socket, after receiving a 'eSocketCloseEvent' + * message. + * + * @param[in] xSocket: the socket being closed. + * + * @return There are three distinct values which can be returned: + * 0: If the xSocket is NULL/invalid. + * 1: If the socket was successfully closed (read the brief above). + * -1: If the socket was valid but could not be closed because the message + * could not be delivered to the IP-task. Try again later. + */ +BaseType_t FreeRTOS_closesocket( Socket_t xSocket ) +{ + BaseType_t xResult; + + #if ( ipconfigUSE_TCP == 1 ) && ( ipconfigUSE_CALLBACKS == 1 ) + FreeRTOS_Socket_t * pxSocket = ( FreeRTOS_Socket_t * ) xSocket; + #endif + IPStackEvent_t xCloseEvent; + xCloseEvent.eEventType = eSocketCloseEvent; + xCloseEvent.pvData = xSocket; + + if( ( xSocket == NULL ) || ( xSocket == FREERTOS_INVALID_SOCKET ) ) + { + xResult = 0; + } + else + { + #if ( ( ipconfigUSE_TCP == 1 ) && ( ipconfigUSE_CALLBACKS == 1 ) ) + { + if( pxSocket->ucProtocol == ( uint8_t ) FREERTOS_IPPROTO_TCP ) + { + /* Make sure that IP-task won't call the user callback's anymore */ + pxSocket->u.xTCP.pxHandleConnected = NULL; + pxSocket->u.xTCP.pxHandleReceive = NULL; + pxSocket->u.xTCP.pxHandleSent = NULL; + } + } + #endif /* ( ( ipconfigUSE_TCP == 1 ) && ( ipconfigUSE_CALLBACKS == 1 ) ) */ + + /* Let the IP task close the socket to keep it synchronised with the + * packet handling. */ + + /* Note when changing the time-out value below, it must be checked who is calling + * this function. If it is called by the IP-task, a deadlock could occur. + * The IP-task would only call it in case of a user call-back */ + if( xSendEventStructToIPTask( &xCloseEvent, ( TickType_t ) 0 ) == pdFAIL ) + { + FreeRTOS_debug_printf( ( "FreeRTOS_closesocket: failed\n" ) ); + xResult = -1; + } + else + { + xResult = 1; + } + } + + return xResult; +} + +/** + * @brief This is the internal version of FreeRTOS_closesocket(). It will + * be called by the IPtask only to avoid problems with synchronicity. + * + * @param[in] pxSocket: The socket descriptor of the socket being closed. + * + * @return Returns NULL, always. + */ +void * vSocketClose( FreeRTOS_Socket_t * pxSocket ) +{ + NetworkBufferDescriptor_t * pxNetworkBuffer; + + #if ( ipconfigUSE_TCP == 1 ) + { + /* For TCP: clean up a little more. */ + if( pxSocket->ucProtocol == ( uint8_t ) FREERTOS_IPPROTO_TCP ) + { + #if ( ipconfigUSE_TCP_WIN == 1 ) + { + if( pxSocket->u.xTCP.pxAckMessage != NULL ) + { + vReleaseNetworkBufferAndDescriptor( pxSocket->u.xTCP.pxAckMessage ); + } + + /* Free the resources which were claimed by the tcpWin member */ + vTCPWindowDestroy( &pxSocket->u.xTCP.xTCPWindow ); + } + #endif /* ipconfigUSE_TCP_WIN */ + + /* Free the input and output streams */ + if( pxSocket->u.xTCP.rxStream != NULL ) + { + iptraceMEM_STATS_DELETE( pxSocket->u.xTCP.rxStream ); + vPortFreeLarge( pxSocket->u.xTCP.rxStream ); + } + + if( pxSocket->u.xTCP.txStream != NULL ) + { + iptraceMEM_STATS_DELETE( pxSocket->u.xTCP.txStream ); + vPortFreeLarge( pxSocket->u.xTCP.txStream ); + } + + /* In case this is a child socket, make sure the child-count of the + * parent socket is decreased. */ + prvTCPSetSocketCount( pxSocket ); + } + } + #endif /* ipconfigUSE_TCP == 1 */ + + /* Socket must be unbound first, to ensure no more packets are queued on + * it. */ + if( socketSOCKET_IS_BOUND( pxSocket ) ) + { + /* If the network driver can iterate through 'xBoundUDPSocketsList', + * by calling xPortHasUDPSocket(), then the IP-task must temporarily + * suspend the scheduler to keep the list in a consistent state. */ + #if ( ipconfigETHERNET_DRIVER_FILTERS_PACKETS == 1 ) + { + vTaskSuspendAll(); + } + #endif /* ipconfigETHERNET_DRIVER_FILTERS_PACKETS */ + + ( void ) uxListRemove( &( pxSocket->xBoundSocketListItem ) ); + + #if ( ipconfigETHERNET_DRIVER_FILTERS_PACKETS == 1 ) + { + ( void ) xTaskResumeAll(); + } + #endif /* ipconfigETHERNET_DRIVER_FILTERS_PACKETS */ + } + + /* Now the socket is not bound the list of waiting packets can be + * drained. */ + if( pxSocket->ucProtocol == ( uint8_t ) FREERTOS_IPPROTO_UDP ) + { + while( listCURRENT_LIST_LENGTH( &( pxSocket->u.xUDP.xWaitingPacketsList ) ) > 0U ) + { + pxNetworkBuffer = ipCAST_PTR_TO_TYPE_PTR( NetworkBufferDescriptor_t, listGET_OWNER_OF_HEAD_ENTRY( &( pxSocket->u.xUDP.xWaitingPacketsList ) ) ); + ( void ) uxListRemove( &( pxNetworkBuffer->xBufferListItem ) ); + vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer ); + } + } + + if( pxSocket->xEventGroup != NULL ) + { + vEventGroupDelete( pxSocket->xEventGroup ); + } + + #if ( ipconfigUSE_TCP == 1 ) && ( ipconfigHAS_DEBUG_PRINTF != 0 ) + { + if( pxSocket->ucProtocol == ( uint8_t ) FREERTOS_IPPROTO_TCP ) + { + FreeRTOS_debug_printf( ( "FreeRTOS_closesocket[%u to %lxip:%u]: buffers %lu socks %lu\n", + pxSocket->usLocalPort, + pxSocket->u.xTCP.ulRemoteIP, + pxSocket->u.xTCP.usRemotePort, + uxGetNumberOfFreeNetworkBuffers(), + listCURRENT_LIST_LENGTH( &xBoundTCPSocketsList ) ) ); + } + } + #endif /* ( ipconfigUSE_TCP == 1 ) && ( ipconfigHAS_DEBUG_PRINTF != 0 ) */ + + /* And finally, after all resources have been freed, free the socket space */ + iptraceMEM_STATS_DELETE( pxSocket ); + vPortFreeSocket( pxSocket ); + + return NULL; +} /* Tested */ + +/*-----------------------------------------------------------*/ + +#if ipconfigUSE_TCP == 1 + +/** + * @brief When a child socket gets closed, make sure to update the child-count of the + * parent. When a listening parent socket is closed, make sure no child-sockets + * keep a pointer to it. + * + * @param[in] pxSocketToDelete: The socket being closed. + */ + static void prvTCPSetSocketCount( FreeRTOS_Socket_t const * pxSocketToDelete ) + { + const ListItem_t * pxIterator; + const ListItem_t * pxEnd = listGET_END_MARKER( &xBoundTCPSocketsList ); + FreeRTOS_Socket_t * pxOtherSocket; + uint16_t usLocalPort = pxSocketToDelete->usLocalPort; + + for( pxIterator = listGET_NEXT( pxEnd ); + pxIterator != pxEnd; + pxIterator = listGET_NEXT( pxIterator ) ) + { + pxOtherSocket = ipCAST_PTR_TO_TYPE_PTR( FreeRTOS_Socket_t, listGET_LIST_ITEM_OWNER( pxIterator ) ); + + if( ( pxOtherSocket->u.xTCP.ucTCPState == ( uint8_t ) eTCP_LISTEN ) && + ( pxOtherSocket->usLocalPort == usLocalPort ) && + ( pxOtherSocket->u.xTCP.usChildCount != 0U ) ) + { + pxOtherSocket->u.xTCP.usChildCount--; + FreeRTOS_debug_printf( ( "Lost: Socket %u now has %u / %u child%s\n", + pxOtherSocket->usLocalPort, + pxOtherSocket->u.xTCP.usChildCount, + pxOtherSocket->u.xTCP.usBacklog, + ( pxOtherSocket->u.xTCP.usChildCount == 1U ) ? "" : "ren" ) ); + break; + } + } + } + + +#endif /* ipconfigUSE_TCP == 1 */ + +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_TCP == 1 ) + +/** + * @brief Set the value of receive/send buffer after some preliminary checks. + * + * @param[in] pxSocket: The socket whose options are being set. + * @param[in] lOptionName: The option name: either FREERTOS_SO_SNDBUF or + * FREERTOS_SO_SNDBUF. + * @param[in] pvOptionValue: The value of the option being set. + * + * @return If there is no error, then 0 is returned. Or a negative errno + * value is returned. + */ + static BaseType_t prvSockopt_so_buffer( FreeRTOS_Socket_t * pxSocket, + int32_t lOptionName, + const void * pvOptionValue ) + { + uint32_t ulNewValue; + BaseType_t xReturn; + + if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP ) + { + FreeRTOS_debug_printf( ( "Set SO_%sBUF: wrong socket type\n", + ( lOptionName == FREERTOS_SO_SNDBUF ) ? "SND" : "RCV" ) ); + xReturn = -pdFREERTOS_ERRNO_EINVAL; + } + else if( ( ( lOptionName == FREERTOS_SO_SNDBUF ) && ( pxSocket->u.xTCP.txStream != NULL ) ) || + ( ( lOptionName == FREERTOS_SO_RCVBUF ) && ( pxSocket->u.xTCP.rxStream != NULL ) ) ) + { + FreeRTOS_debug_printf( ( "Set SO_%sBUF: buffer already created\n", + ( lOptionName == FREERTOS_SO_SNDBUF ) ? "SND" : "RCV" ) ); + xReturn = -pdFREERTOS_ERRNO_EINVAL; + } + else + { + ulNewValue = *( ipPOINTER_CAST( const uint32_t *, pvOptionValue ) ); + + if( lOptionName == FREERTOS_SO_SNDBUF ) + { + /* Round up to nearest MSS size */ + ulNewValue = FreeRTOS_round_up( ulNewValue, ( uint32_t ) pxSocket->u.xTCP.usInitMSS ); + pxSocket->u.xTCP.uxTxStreamSize = ulNewValue; + } + else + { + pxSocket->u.xTCP.uxRxStreamSize = ulNewValue; + } + + xReturn = 0; + } + + return xReturn; + } +#endif /* ipconfigUSE_TCP == 1 */ +/*-----------------------------------------------------------*/ + +/* FreeRTOS_setsockopt calls itself, but in a very limited way, + * only when FREERTOS_SO_WIN_PROPERTIES is being set. */ + +/** + * @brief Set the socket options for the given socket. + * + * @param[in] xSocket: The socket for which the options are to be set. + * @param[in] lLevel: Not used. Parameter is used to maintain the Berkeley sockets + * standard. + * @param[in] lOptionName: The name of the option to be set. + * @param[in] pvOptionValue: The value of the option to be set. + * @param[in] uxOptionLength: Not used. Parameter is used to maintain the Berkeley + * sockets standard. + * + * @return If the option can be set with the given value, then 0 is returned. Else, + * an error code is returned. + */ +BaseType_t FreeRTOS_setsockopt( Socket_t xSocket, + int32_t lLevel, + int32_t lOptionName, + const void * pvOptionValue, + size_t uxOptionLength ) +{ +/* The standard Berkeley function returns 0 for success. */ + BaseType_t xReturn = -pdFREERTOS_ERRNO_EINVAL; + FreeRTOS_Socket_t * pxSocket; + + pxSocket = ( FreeRTOS_Socket_t * ) xSocket; + + /* The function prototype is designed to maintain the expected Berkeley + * sockets standard, but this implementation does not use all the parameters. */ + ( void ) lLevel; + ( void ) uxOptionLength; + + if( ( pxSocket == NULL ) || ( pxSocket == FREERTOS_INVALID_SOCKET ) ) + { + xReturn = -pdFREERTOS_ERRNO_EINVAL; + return xReturn; + } + + switch( lOptionName ) + { + case FREERTOS_SO_RCVTIMEO: + /* Receive time out. */ + pxSocket->xReceiveBlockTime = *( ( const TickType_t * ) pvOptionValue ); + xReturn = 0; + break; + + case FREERTOS_SO_SNDTIMEO: + pxSocket->xSendBlockTime = *( ( const TickType_t * ) pvOptionValue ); + + if( pxSocket->ucProtocol == ( uint8_t ) FREERTOS_IPPROTO_UDP ) + { + /* The send time out is capped for the reason stated in the + * comments where ipconfigUDP_MAX_SEND_BLOCK_TIME_TICKS is defined + * in FreeRTOSIPConfig.h (assuming an official configuration file + * is being used. */ + if( pxSocket->xSendBlockTime > ipconfigUDP_MAX_SEND_BLOCK_TIME_TICKS ) + { + pxSocket->xSendBlockTime = ipconfigUDP_MAX_SEND_BLOCK_TIME_TICKS; + } + } + else + { + /* For TCP socket, it isn't necessary to limit the blocking time + * because the FreeRTOS_send() function does not wait for a network + * buffer to become available. */ + } + + xReturn = 0; + break; + + #if ( ipconfigUDP_MAX_RX_PACKETS > 0U ) + case FREERTOS_SO_UDP_MAX_RX_PACKETS: + + if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_UDP ) + { + break; /* will return -pdFREERTOS_ERRNO_EINVAL */ + } + + pxSocket->u.xUDP.uxMaxPackets = *( ( const UBaseType_t * ) pvOptionValue ); + xReturn = 0; + break; + #endif /* ipconfigUDP_MAX_RX_PACKETS */ + + case FREERTOS_SO_UDPCKSUM_OUT: + + /* Turn calculating of the UDP checksum on/off for this socket. If pvOptionValue + * is anything else than NULL, the checksum generation will be turned on. */ + + if( pvOptionValue == NULL ) + { + pxSocket->ucSocketOptions &= ~( ( uint8_t ) FREERTOS_SO_UDPCKSUM_OUT ); + } + else + { + pxSocket->ucSocketOptions |= ( uint8_t ) FREERTOS_SO_UDPCKSUM_OUT; + } + + xReturn = 0; + break; + + #if ( ipconfigUSE_CALLBACKS == 1 ) + #if ( ipconfigUSE_TCP == 1 ) + case FREERTOS_SO_TCP_CONN_HANDLER: /* Set a callback for (dis)connection events */ + case FREERTOS_SO_TCP_RECV_HANDLER: /* Install a callback for receiving TCP data. Supply pointer to 'F_TCP_UDP_Handler_t' (see below) */ + case FREERTOS_SO_TCP_SENT_HANDLER: /* Install a callback for sending TCP data. Supply pointer to 'F_TCP_UDP_Handler_t' (see below) */ + #endif /* ipconfigUSE_TCP */ + case FREERTOS_SO_UDP_RECV_HANDLER: /* Install a callback for receiving UDP data. Supply pointer to 'F_TCP_UDP_Handler_t' (see below) */ + case FREERTOS_SO_UDP_SENT_HANDLER: /* Install a callback for sending UDP data. Supply pointer to 'F_TCP_UDP_Handler_t' (see below) */ + { + #if ( ipconfigUSE_TCP == 1 ) + { + UBaseType_t uxProtocol; + + if( ( lOptionName == FREERTOS_SO_UDP_RECV_HANDLER ) || + ( lOptionName == FREERTOS_SO_UDP_SENT_HANDLER ) ) + { + uxProtocol = ( UBaseType_t ) FREERTOS_IPPROTO_UDP; + } + else + { + uxProtocol = ( UBaseType_t ) FREERTOS_IPPROTO_TCP; + } + + if( pxSocket->ucProtocol != ( uint8_t ) uxProtocol ) + { + break; /* will return -pdFREERTOS_ERRNO_EINVAL */ + } + } + #else /* if ( ipconfigUSE_TCP == 1 ) */ + { + /* No need to check if the socket has the right + * protocol, because only UDP socket can be created. */ + } + #endif /* ipconfigUSE_TCP */ + + switch( lOptionName ) + { + #if ipconfigUSE_TCP == 1 + case FREERTOS_SO_TCP_CONN_HANDLER: + pxSocket->u.xTCP.pxHandleConnected = ipCAST_CONST_PTR_TO_CONST_TYPE_PTR( F_TCP_UDP_Handler_t, pvOptionValue )->pxOnTCPConnected; + break; + + case FREERTOS_SO_TCP_RECV_HANDLER: + pxSocket->u.xTCP.pxHandleReceive = ipCAST_CONST_PTR_TO_CONST_TYPE_PTR( F_TCP_UDP_Handler_t, pvOptionValue )->pxOnTCPReceive; + break; + + case FREERTOS_SO_TCP_SENT_HANDLER: + pxSocket->u.xTCP.pxHandleSent = ipCAST_CONST_PTR_TO_CONST_TYPE_PTR( F_TCP_UDP_Handler_t, pvOptionValue )->pxOnTCPSent; + break; + #endif /* ipconfigUSE_TCP */ + case FREERTOS_SO_UDP_RECV_HANDLER: + pxSocket->u.xUDP.pxHandleReceive = ipCAST_CONST_PTR_TO_CONST_TYPE_PTR( F_TCP_UDP_Handler_t, pvOptionValue )->pxOnUDPReceive; + break; + + case FREERTOS_SO_UDP_SENT_HANDLER: + pxSocket->u.xUDP.pxHandleSent = ipCAST_CONST_PTR_TO_CONST_TYPE_PTR( F_TCP_UDP_Handler_t, pvOptionValue )->pxOnUDPSent; + break; + + default: + /* Should it throw an error here? */ + break; + } + } + + xReturn = 0; + break; + #endif /* ipconfigUSE_CALLBACKS */ + + #if ( ipconfigUSE_TCP != 0 ) + #if ( ipconfigSOCKET_HAS_USER_SEMAPHORE != 0 ) + + /* Each socket has a semaphore on which the using task normally + * sleeps. */ + case FREERTOS_SO_SET_SEMAPHORE: + { + pxSocket->pxUserSemaphore = *( ipPOINTER_CAST( SemaphoreHandle_t *, pvOptionValue ) ); + } + xReturn = 0; + break; + #endif /* ipconfigSOCKET_HAS_USER_SEMAPHORE */ + + #if ( ipconfigSOCKET_HAS_USER_WAKE_CALLBACK != 0 ) + case FREERTOS_SO_WAKEUP_CALLBACK: + + /* Each socket can have a callback function that is executed + * when there is an event the socket's owner might want to + * process. */ + /* The type cast of the pointer expression "A" to type "B" removes const qualifier from the pointed to type. */ + pxSocket->pxUserWakeCallback = ( const SocketWakeupCallback_t ) pvOptionValue; + xReturn = 0; + break; + #endif /* ipconfigSOCKET_HAS_USER_WAKE_CALLBACK */ + + case FREERTOS_SO_SET_LOW_HIGH_WATER: + { + const LowHighWater_t * pxLowHighWater = ipPOINTER_CAST( const LowHighWater_t *, pvOptionValue ); + + if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP ) + { + /* It is not allowed to access 'pxSocket->u.xTCP'. */ + FreeRTOS_debug_printf( ( "FREERTOS_SO_SET_LOW_HIGH_WATER: wrong socket type\n" ) ); + break; /* will return -pdFREERTOS_ERRNO_EINVAL */ + } + + if( ( pxLowHighWater->uxLittleSpace >= pxLowHighWater->uxEnoughSpace ) || + ( pxLowHighWater->uxEnoughSpace > pxSocket->u.xTCP.uxRxStreamSize ) ) + { + /* Impossible values. */ + FreeRTOS_debug_printf( ( "FREERTOS_SO_SET_LOW_HIGH_WATER: bad values\n" ) ); + break; /* will return -pdFREERTOS_ERRNO_EINVAL */ + } + + /* Send a STOP when buffer space drops below 'uxLittleSpace' bytes. */ + pxSocket->u.xTCP.uxLittleSpace = pxLowHighWater->uxLittleSpace; + /* Send a GO when buffer space grows above 'uxEnoughSpace' bytes. */ + pxSocket->u.xTCP.uxEnoughSpace = pxLowHighWater->uxEnoughSpace; + xReturn = 0; + } + break; + + case FREERTOS_SO_SNDBUF: /* Set the size of the send buffer, in units of MSS (TCP only) */ + case FREERTOS_SO_RCVBUF: /* Set the size of the receive buffer, in units of MSS (TCP only) */ + xReturn = prvSockopt_so_buffer( pxSocket, lOptionName, pvOptionValue ); + break; + + case FREERTOS_SO_WIN_PROPERTIES: /* Set all buffer and window properties in one call, parameter is pointer to WinProperties_t */ + { + const WinProperties_t * pxProps; + + if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP ) + { + FreeRTOS_debug_printf( ( "Set SO_WIN_PROP: wrong socket type\n" ) ); + break; /* will return -pdFREERTOS_ERRNO_EINVAL */ + } + + if( ( pxSocket->u.xTCP.txStream != NULL ) || ( pxSocket->u.xTCP.rxStream != NULL ) ) + { + FreeRTOS_debug_printf( ( "Set SO_WIN_PROP: buffer already created\n" ) ); + break; /* will return -pdFREERTOS_ERRNO_EINVAL */ + } + + pxProps = ipPOINTER_CAST( const WinProperties_t *, pvOptionValue ); + + xReturn = prvSockopt_so_buffer( pxSocket, FREERTOS_SO_SNDBUF, &( pxProps->lTxBufSize ) ); + + if( xReturn != 0 ) + { + break; /* will return an error. */ + } + + xReturn = prvSockopt_so_buffer( pxSocket, FREERTOS_SO_RCVBUF, &( pxProps->lRxBufSize ) ); + + if( xReturn != 0 ) + { + break; /* will return an error. */ + } + + #if ( ipconfigUSE_TCP_WIN == 1 ) + { + pxSocket->u.xTCP.uxRxWinSize = ( uint32_t ) pxProps->lRxWinSize; /* Fixed value: size of the TCP reception window */ + pxSocket->u.xTCP.uxTxWinSize = ( uint32_t ) pxProps->lTxWinSize; /* Fixed value: size of the TCP transmit window */ + } + #else + { + pxSocket->u.xTCP.uxRxWinSize = 1U; + pxSocket->u.xTCP.uxTxWinSize = 1U; + } + #endif + + /* In case the socket has already initialised its tcpWin, + * adapt the window size parameters */ + if( pxSocket->u.xTCP.xTCPWindow.u.bits.bHasInit != pdFALSE_UNSIGNED ) + { + pxSocket->u.xTCP.xTCPWindow.xSize.ulRxWindowLength = pxSocket->u.xTCP.uxRxWinSize * pxSocket->u.xTCP.usInitMSS; + pxSocket->u.xTCP.xTCPWindow.xSize.ulTxWindowLength = pxSocket->u.xTCP.uxTxWinSize * pxSocket->u.xTCP.usInitMSS; + } + } + + xReturn = 0; + break; + + case FREERTOS_SO_REUSE_LISTEN_SOCKET: /* If true, the server-socket will turn into a connected socket */ + { + if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP ) + { + break; /* will return -pdFREERTOS_ERRNO_EINVAL */ + } + + if( *( ( const BaseType_t * ) pvOptionValue ) != 0 ) + { + pxSocket->u.xTCP.bits.bReuseSocket = pdTRUE; + } + else + { + pxSocket->u.xTCP.bits.bReuseSocket = pdFALSE; + } + } + xReturn = 0; + break; + + case FREERTOS_SO_CLOSE_AFTER_SEND: /* As soon as the last byte has been transmitted, finalise the connection */ + { + if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP ) + { + break; /* will return -pdFREERTOS_ERRNO_EINVAL */ + } + + if( *( ( const BaseType_t * ) pvOptionValue ) != 0 ) + { + pxSocket->u.xTCP.bits.bCloseAfterSend = pdTRUE; + } + else + { + pxSocket->u.xTCP.bits.bCloseAfterSend = pdFALSE; + } + } + xReturn = 0; + break; + + case FREERTOS_SO_SET_FULL_SIZE: /* Refuse to send packets smaller than MSS */ + { + if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP ) + { + break; /* will return -pdFREERTOS_ERRNO_EINVAL */ + } + + if( *( ( const BaseType_t * ) pvOptionValue ) != 0 ) + { + pxSocket->u.xTCP.xTCPWindow.u.bits.bSendFullSize = pdTRUE; + } + else + { + pxSocket->u.xTCP.xTCPWindow.u.bits.bSendFullSize = pdFALSE; + } + + if( ( pxSocket->u.xTCP.xTCPWindow.u.bits.bSendFullSize == pdFALSE_UNSIGNED ) && + ( pxSocket->u.xTCP.ucTCPState >= ( uint8_t ) eESTABLISHED ) && + ( FreeRTOS_outstanding( pxSocket ) != 0 ) ) + { + pxSocket->u.xTCP.usTimeout = 1U; /* to set/clear bSendFullSize */ + ( void ) xSendEventToIPTask( eTCPTimerEvent ); + } + } + xReturn = 0; + break; + + case FREERTOS_SO_STOP_RX: /* Refuse to receive more packets. */ + { + if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP ) + { + break; /* will return -pdFREERTOS_ERRNO_EINVAL */ + } + + if( *( ( const BaseType_t * ) pvOptionValue ) != 0 ) + { + pxSocket->u.xTCP.bits.bRxStopped = pdTRUE; + } + else + { + pxSocket->u.xTCP.bits.bRxStopped = pdFALSE; + } + + pxSocket->u.xTCP.bits.bWinChange = pdTRUE; + pxSocket->u.xTCP.usTimeout = 1U; /* to set/clear bRxStopped */ + ( void ) xSendEventToIPTask( eTCPTimerEvent ); + } + xReturn = 0; + break; + #endif /* ipconfigUSE_TCP == 1 */ + + default: + /* No other options are handled. */ + xReturn = -pdFREERTOS_ERRNO_ENOPROTOOPT; + break; + } + + return xReturn; +} /* Tested */ + +/*-----------------------------------------------------------*/ + +/** + * @brief Find an available port number per https://tools.ietf.org/html/rfc6056. + * + * @param[in] xProtocol: FREERTOS_IPPROTO_TCP/FREERTOS_IPPROTO_UDP. + * + * @return If an available protocol port is found then that port number is returned. + * Or else, 0 is returned. + */ +static uint16_t prvGetPrivatePortNumber( BaseType_t xProtocol ) +{ + const uint16_t usEphemeralPortCount = + socketAUTO_PORT_ALLOCATION_MAX_NUMBER - ( socketAUTO_PORT_ALLOCATION_START_NUMBER - 1U ); + uint16_t usIterations = usEphemeralPortCount; + uint32_t ulRandomSeed = 0; + uint16_t usResult = 0; + const List_t * pxList; + + #if ipconfigUSE_TCP == 1 + if( xProtocol == ( BaseType_t ) FREERTOS_IPPROTO_TCP ) + { + pxList = &xBoundTCPSocketsList; + } + else + #endif + { + pxList = &xBoundUDPSocketsList; + } + + /* Avoid compiler warnings if ipconfigUSE_TCP is not defined. */ + ( void ) xProtocol; + + /* Find the next available port using the random seed as a starting + * point. */ + do + { + /* Only proceed if the random number generator succeeded. */ + if( xApplicationGetRandomNumber( &( ulRandomSeed ) ) == pdFALSE ) + { + break; + } + + /* Map the random to a candidate port. */ + usResult = + socketAUTO_PORT_ALLOCATION_START_NUMBER + + ( ( ( uint16_t ) ulRandomSeed ) % usEphemeralPortCount ); + + /* Check if there's already an open socket with the same protocol + * and port. */ + if( NULL == pxListFindListItemWithValue( + pxList, + ( TickType_t ) FreeRTOS_htons( usResult ) ) ) + { + usResult = FreeRTOS_htons( usResult ); + break; + } + else + { + usResult = 0; + } + + usIterations--; + } + while( usIterations > 0U ); + + return usResult; +} +/*-----------------------------------------------------------*/ + +/** + * @brief Find a list item associated with the wanted-item. + * + * @param[in] pxList: The list through which the search is to be conducted. + * @param[in] xWantedItemValue: The wanted item whose association is to be found. + * + * @return The list item holding the value being searched for. If nothing is found, + * then a NULL is returned. + */ +static const ListItem_t * pxListFindListItemWithValue( const List_t * pxList, + TickType_t xWantedItemValue ) +{ + const ListItem_t * pxResult = NULL; + + if( ( xIPIsNetworkTaskReady() != pdFALSE ) && ( pxList != NULL ) ) + { + const ListItem_t * pxIterator; + const ListItem_t * pxEnd = listGET_END_MARKER( pxList ); + + for( pxIterator = listGET_NEXT( pxEnd ); + pxIterator != pxEnd; + pxIterator = listGET_NEXT( pxIterator ) ) + { + if( listGET_LIST_ITEM_VALUE( pxIterator ) == xWantedItemValue ) + { + pxResult = pxIterator; + break; + } + } + } + + return pxResult; +} /* Tested */ + +/*-----------------------------------------------------------*/ + +/** + * @brief Find the UDP socket corresponding to the port number. + * + * @param[in] uxLocalPort: The port whose corresponding bound UDP socket + * is to be found. + * + * @return The socket owning the port if found or else NULL. + */ +FreeRTOS_Socket_t * pxUDPSocketLookup( UBaseType_t uxLocalPort ) +{ + const ListItem_t * pxListItem; + FreeRTOS_Socket_t * pxSocket = NULL; + + /* Looking up a socket is quite simple, find a match with the local port. + * + * See if there is a list item associated with the port number on the + * list of bound sockets. */ + pxListItem = pxListFindListItemWithValue( &xBoundUDPSocketsList, ( TickType_t ) uxLocalPort ); + + if( pxListItem != NULL ) + { + /* The owner of the list item is the socket itself. */ + pxSocket = ipCAST_PTR_TO_TYPE_PTR( FreeRTOS_Socket_t, listGET_LIST_ITEM_OWNER( pxListItem ) ); + configASSERT( pxSocket != NULL ); + } + + return pxSocket; +} + +/*-----------------------------------------------------------*/ + +#define sockDIGIT_COUNT ( 3U ) /**< Each nibble is expressed in at most 3 digits such as "192". */ + +/** + * @brief Convert the 32-bit representation of the IP-address to the dotted decimal + * notation after some checks. + * A safe alternative is FreeRTOS_inet_ntop4(). + * + * @param[in] ulIPAddress: 32-bit representation of the IP-address. + * @param[out] pcBuffer: The buffer where the dotted decimal representation will be + * stored if all checks pass. The buffer must be at least 16 + * bytes long. + * + * @return If all checks pass, then the pointer returned will be same as pcBuffer + * and will have the address stored in the location. Else, NULL is returned. + */ +const char * FreeRTOS_inet_ntoa( uint32_t ulIPAddress, + char * pcBuffer ) +{ + socklen_t uxNibble; + socklen_t uxIndex = 0; + const uint8_t * pucAddress = ( const uint8_t * ) &( ulIPAddress ); + const char * pcResult = pcBuffer; + const socklen_t uxSize = 16; + + for( uxNibble = 0; uxNibble < ipSIZE_OF_IPv4_ADDRESS; uxNibble++ ) + { + uint8_t pucDigits[ sockDIGIT_COUNT ]; + uint8_t ucValue = pucAddress[ uxNibble ]; + socklen_t uxSource = ( socklen_t ) sockDIGIT_COUNT - ( socklen_t ) 1U; + socklen_t uxNeeded; + + for( ; ; ) + { + pucDigits[ uxSource ] = ucValue % ( uint8_t ) 10U; + ucValue /= ( uint8_t ) 10U; + + if( uxSource == 1U ) + { + break; + } + + uxSource--; + } + + pucDigits[ 0 ] = ucValue; + + /* Skip leading zeros. */ + for( uxSource = 0; uxSource < ( ( socklen_t ) sockDIGIT_COUNT - ( socklen_t ) 1U ); uxSource++ ) + { + if( pucDigits[ uxSource ] != 0U ) + { + break; + } + } + + /* Write e.g. "192.", which is 3 digits and a dot. */ + uxNeeded = ( ( socklen_t ) sockDIGIT_COUNT - uxSource ) + 1U; + + if( ( uxIndex + uxNeeded ) > uxSize ) + { + /* The result won't fit. */ + pcResult = NULL; + break; + } + + for( ; uxSource < ( socklen_t ) sockDIGIT_COUNT; uxSource++ ) + { + pcBuffer[ uxIndex ] = ( char ) ( pucDigits[ uxSource ] + ( char ) '0' ); + uxIndex++; + } + + if( uxNibble < ( ipSIZE_OF_IPv4_ADDRESS - 1U ) ) + { + pcBuffer[ uxIndex ] = '.'; + } + else + { + pcBuffer[ uxIndex ] = '\0'; + } + + uxIndex++; + } + + return pcResult; +} +/*-----------------------------------------------------------*/ + +/** + * @brief Convert the dotted decimal format of the IP-address to the 32-bit representation. + * + * @param[in] xAddressFamily: The Address family to which the IP-address belongs to. Only + * FREERTOS_AF_INET (IPv4) is supported. + * @param[in] pcSource: Pointer to the string holding the dotted decimal representation of + * the IP-address. + * @param[out] pvDestination: The pointer to the address struct/variable where the converted + * IP-address will be stored. The buffer must be 4 bytes long + * in case of a IPv4 address. + * + * @return If all checks pass, then pdPASS is returned or else pdFAIL is returned. + */ +BaseType_t FreeRTOS_inet_pton( BaseType_t xAddressFamily, + const char * pcSource, + void * pvDestination ) +{ + BaseType_t xResult; + + /* Printable string to struct sockaddr. */ + switch( xAddressFamily ) + { + case FREERTOS_AF_INET: + xResult = FreeRTOS_inet_pton4( pcSource, pvDestination ); + break; + + default: + xResult = -pdFREERTOS_ERRNO_EAFNOSUPPORT; + break; + } + + return xResult; +} +/*-----------------------------------------------------------*/ + +/** + * @brief Convert the 32-bit representation of the IP-address to the dotted + * decimal format based on the Address Family. (Only FREERTOS_AF_INET + * is allowed). + * + * @param[in] xAddressFamily: The address family of the IP-address. + * @param[in] pvSource: Pointer to the 32-bit representation of IP-address. + * @param[out] pcDestination: The pointer to the character array where the dotted + * decimal address will be stored if every check does pass. + * @param[in] uxSize: Size of the character array. This value makes sure that the code + * doesn't write beyond it's bounds. + * + * @return If every check does pass, then the pointer to the pcDestination is returned + * holding the dotted decimal format of IP-address. Else, a NULL is returned. + */ +const char * FreeRTOS_inet_ntop( BaseType_t xAddressFamily, + const void * pvSource, + char * pcDestination, + socklen_t uxSize ) +{ + const char * pcResult; + + /* Printable struct sockaddr to string. */ + switch( xAddressFamily ) + { + case FREERTOS_AF_INET: + pcResult = FreeRTOS_inet_ntop4( pvSource, pcDestination, uxSize ); + break; + + default: + /* errno should be set to pdFREERTOS_ERRNO_EAFNOSUPPORT. */ + pcResult = NULL; + break; + } + + return pcResult; +} +/*-----------------------------------------------------------*/ + +/** + * @brief Convert the 32-bit representation of the IP-address to the dotted decimal format. + * + * @param[in] pvSource: The pointer to the 32-bit representation of the IP-address. + * @param[out] pcDestination: The pointer to a character array where the string of the + * dotted decimal IP format. + * @param[in] uxSize: Size of the character array. This value makes sure that the code + * doesn't write beyond it's bounds. + * + * @return The pointer to the string holding the dotted decimal format of the IP-address. If + * everything passes correctly, then the pointer being returned is the same as + * pcDestination, else a NULL is returned. + */ +const char * FreeRTOS_inet_ntop4( const void * pvSource, + char * pcDestination, + socklen_t uxSize ) +{ + uint32_t ulIPAddress; + void * pvCopyDest; + const char * pcReturn; + + if( uxSize < 16U ) + { + /* There must be space for "255.255.255.255". */ + pcReturn = NULL; + } + else + { + pvCopyDest = ( void * ) &ulIPAddress; + ( void ) memcpy( pvCopyDest, pvSource, sizeof( ulIPAddress ) ); + ( void ) FreeRTOS_inet_ntoa( ulIPAddress, pcDestination ); + pcReturn = pcDestination; + } + + return pcReturn; +} +/*-----------------------------------------------------------*/ + +/** + * @brief This function converts the character string pcSource into a network address + * structure, then copies the network address structure to pvDestination. + * pvDestination is written in network byte order. + * + * @param[in] pcSource: The character string in holding the IP address. + * @param[out] pvDestination: The returned network address in 32-bit network-endian format. + * + * @return pdPASS if the translation was successful or else pdFAIL. + */ +BaseType_t FreeRTOS_inet_pton4( const char * pcSource, + void * pvDestination ) +{ + const uint32_t ulDecimalBase = 10U; + uint8_t ucOctet[ socketMAX_IP_ADDRESS_OCTETS ]; + uint32_t ulReturn = 0UL, ulValue; + UBaseType_t uxOctetNumber; + BaseType_t xResult = pdPASS; + const char * pcIPAddress = pcSource; + const void * pvCopySource; + + /* Translate "192.168.2.100" to a 32-bit number, network-endian. */ + for( uxOctetNumber = 0U; uxOctetNumber < socketMAX_IP_ADDRESS_OCTETS; uxOctetNumber++ ) + { + ulValue = 0UL; + + while( ( *pcIPAddress >= '0' ) && ( *pcIPAddress <= '9' ) ) + { + BaseType_t xChar; + + /* Move previous read characters into the next decimal + * position. */ + ulValue *= ulDecimalBase; + + /* Add the binary value of the ascii character. */ + xChar = ( BaseType_t ) pcIPAddress[ 0 ]; + xChar = xChar - ( BaseType_t ) '0'; + ulValue += ( uint32_t ) xChar; + + /* Move to next character in the string. */ + pcIPAddress++; + } + + /* Check characters were read. */ + if( pcIPAddress == pcSource ) + { + xResult = pdFAIL; + } + + /* Check the value fits in an 8-bit number. */ + if( ulValue > 0xffUL ) + { + xResult = pdFAIL; + } + else + { + ucOctet[ uxOctetNumber ] = ( uint8_t ) ulValue; + + /* Check the next character is as expected. */ + if( uxOctetNumber < ( socketMAX_IP_ADDRESS_OCTETS - 1U ) ) + { + if( *pcIPAddress != '.' ) + { + xResult = pdFAIL; + } + else + { + /* Move past the dot. */ + pcIPAddress++; + } + } + } + + if( xResult == pdFAIL ) + { + /* No point going on. */ + break; + } + } + + if( *pcIPAddress != ( char ) 0 ) + { + /* Expected the end of the string. */ + xResult = pdFAIL; + } + + if( uxOctetNumber != socketMAX_IP_ADDRESS_OCTETS ) + { + /* Didn't read enough octets. */ + xResult = pdFAIL; + } + + if( xResult == pdPASS ) + { + /* lint: ucOctet has been set because xResult == pdPASS. */ + ulReturn = FreeRTOS_inet_addr_quick( ucOctet[ 0 ], ucOctet[ 1 ], ucOctet[ 2 ], ucOctet[ 3 ] ); + } + else + { + ulReturn = 0UL; + } + + pvCopySource = ( const void * ) &ulReturn; + ( void ) memcpy( pvDestination, pvCopySource, sizeof( ulReturn ) ); + + return xResult; +} +/*-----------------------------------------------------------*/ + +/** + * @brief Convert the IP address from "w.x.y.z" (dotted decimal) format to the 32-bit format. + * + * @param[in] pcIPAddress: The character string pointer holding the IP-address in the "W.X.Y.Z" + * (dotted decimal) format. + * + * @return The 32-bit representation of IP(v4) address. + */ +uint32_t FreeRTOS_inet_addr( const char * pcIPAddress ) +{ + uint32_t ulReturn = 0UL; + + /* inet_pton AF_INET target is a 4-byte 'struct in_addr'. */ + ( void ) FreeRTOS_inet_pton4( pcIPAddress, &( ulReturn ) ); + + return ulReturn; +} +/*-----------------------------------------------------------*/ + + +/** + * @brief Function to get the local address and IP port of the given socket. + * + * @param[in] xSocket: Socket whose port is to be added to the pxAddress. + * @param[out] pxAddress: Structure in which the IP address and the port number + * is returned. + * + * @return Size of the freertos_sockaddr structure. + */ +size_t FreeRTOS_GetLocalAddress( ConstSocket_t xSocket, + struct freertos_sockaddr * pxAddress ) +{ + const FreeRTOS_Socket_t * pxSocket = ( const FreeRTOS_Socket_t * ) xSocket; + + /* IP address of local machine. */ + pxAddress->sin_addr = *ipLOCAL_IP_ADDRESS_POINTER; + + /* Local port on this machine. */ + pxAddress->sin_port = FreeRTOS_htons( pxSocket->usLocalPort ); + + return sizeof( *pxAddress ); +} + +/*-----------------------------------------------------------*/ + +/** + * @brief Wake up the user of the given socket through event-groups. + * + * @param[in] pxSocket: The socket whose user is to be woken up. + */ +void vSocketWakeUpUser( FreeRTOS_Socket_t * pxSocket ) +{ +/* _HT_ must work this out, now vSocketWakeUpUser will be called for any important + * event or transition */ + #if ( ipconfigSOCKET_HAS_USER_SEMAPHORE == 1 ) + { + if( pxSocket->pxUserSemaphore != NULL ) + { + ( void ) xSemaphoreGive( pxSocket->pxUserSemaphore ); + } + } + #endif /* ipconfigSOCKET_HAS_USER_SEMAPHORE */ + + #if ( ipconfigSOCKET_HAS_USER_WAKE_CALLBACK == 1 ) + { + if( pxSocket->pxUserWakeCallback != NULL ) + { + pxSocket->pxUserWakeCallback( pxSocket ); + } + } + #endif /* ipconfigSOCKET_HAS_USER_WAKE_CALLBACK */ + + #if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 ) + { + if( pxSocket->pxSocketSet != NULL ) + { + EventBits_t xSelectBits = ( pxSocket->xEventBits >> SOCKET_EVENT_BIT_COUNT ) & ( ( EventBits_t ) eSELECT_ALL ); + + if( xSelectBits != 0UL ) + { + pxSocket->xSocketBits |= xSelectBits; + ( void ) xEventGroupSetBits( pxSocket->pxSocketSet->xSelectGroup, xSelectBits ); + } + } + + pxSocket->xEventBits &= ( EventBits_t ) eSOCKET_ALL; + } + #endif /* ipconfigSUPPORT_SELECT_FUNCTION */ + + if( ( pxSocket->xEventGroup != NULL ) && ( pxSocket->xEventBits != 0U ) ) + { + ( void ) xEventGroupSetBits( pxSocket->xEventGroup, pxSocket->xEventBits ); + } + + pxSocket->xEventBits = 0UL; +} + +/*-----------------------------------------------------------*/ + +#if ( ipconfigETHERNET_DRIVER_FILTERS_PACKETS == 1 ) + +/** + * @brief This define makes it possible for network interfaces to inspect + * UDP messages and see if there is any UDP socket bound to a given port + * number. This is probably only useful in systems with a minimum of + * RAM and when lots of anonymous broadcast messages come in. + * + * @param[in] usPortNr: the port number to look for. + * + * @return xFound if a socket with the port number is found. + */ + BaseType_t xPortHasUDPSocket( uint16_t usPortNr ) + { + BaseType_t xFound = pdFALSE; + + vTaskSuspendAll(); + { + if( ( pxListFindListItemWithValue( &xBoundUDPSocketsList, ( TickType_t ) usPortNr ) != NULL ) ) + { + xFound = pdTRUE; + } + } + ( void ) xTaskResumeAll(); + + return xFound; + } + +#endif /* ipconfigETHERNET_DRIVER_FILTERS_PACKETS */ + +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_TCP == 1 ) + +/** + * @brief Check if it makes any sense to wait for a connect event. + * + * @param[in] pxSocket: The socket trying to connect. + * + * @return It may return: -EINPROGRESS, -EAGAIN, or 0 for OK. + */ + static BaseType_t bMayConnect( FreeRTOS_Socket_t const * pxSocket ) + { + BaseType_t xResult; + eIPTCPState_t eState = ipNUMERIC_CAST( eIPTCPState_t, pxSocket->u.xTCP.ucTCPState ); + + switch( eState ) + { + case eCLOSED: + case eCLOSE_WAIT: + xResult = 0; + break; + + case eCONNECT_SYN: + xResult = -pdFREERTOS_ERRNO_EINPROGRESS; + break; + + case eTCP_LISTEN: + case eSYN_FIRST: + case eSYN_RECEIVED: + case eESTABLISHED: + case eFIN_WAIT_1: + case eFIN_WAIT_2: + case eCLOSING: + case eLAST_ACK: + case eTIME_WAIT: + default: + xResult = -pdFREERTOS_ERRNO_EAGAIN; + break; + } + + return xResult; + } + + +#endif /* ipconfigUSE_TCP */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_TCP == 1 ) + +/** + * @brief Called from #FreeRTOS_connect(): make some checks and if allowed, + * send a message to the IP-task to start connecting to a remote socket. + * + * @param[in] pxSocket: The socket attempting to connect to a remote port. + * @param[in] pxAddress: The address the socket is trying to connect to. + * + * @return 0 on successful checks or a negative error code. + */ + static BaseType_t prvTCPConnectStart( FreeRTOS_Socket_t * pxSocket, + struct freertos_sockaddr const * pxAddress ) + { + BaseType_t xResult = 0; + + if( pxAddress == NULL ) + { + /* NULL address passed to the function. Invalid value. */ + xResult = -pdFREERTOS_ERRNO_EINVAL; + } + else if( prvValidSocket( pxSocket, FREERTOS_IPPROTO_TCP, pdFALSE ) == pdFALSE ) + { + /* Not a valid socket or wrong type */ + xResult = -pdFREERTOS_ERRNO_EBADF; + } + else if( FreeRTOS_issocketconnected( pxSocket ) > 0 ) + { + /* The socket is already connected. */ + xResult = -pdFREERTOS_ERRNO_EISCONN; + } + else if( !socketSOCKET_IS_BOUND( pxSocket ) ) + { + /* Bind the socket to the port that the client task will send from. + * Non-standard, so the error returned is that returned by bind(). */ + xResult = FreeRTOS_bind( pxSocket, NULL, 0U ); + } + else + { + /* The socket is valid, not yet connected, and already bound to a port number. */ + } + + if( xResult == 0 ) + { + /* Check if it makes any sense to wait for a connect event, this condition + * might change while sleeping, so it must be checked within each loop */ + xResult = bMayConnect( pxSocket ); /* -EINPROGRESS, -EAGAIN, or 0 for OK */ + + /* Start the connect procedure, kernel will start working on it */ + if( xResult == 0 ) + { + pxSocket->u.xTCP.bits.bConnPrepared = pdFALSE; + pxSocket->u.xTCP.ucRepCount = 0U; + + FreeRTOS_debug_printf( ( "FreeRTOS_connect: %u to %lxip:%u\n", + pxSocket->usLocalPort, FreeRTOS_ntohl( pxAddress->sin_addr ), FreeRTOS_ntohs( pxAddress->sin_port ) ) ); + + /* Port on remote machine. */ + pxSocket->u.xTCP.usRemotePort = FreeRTOS_ntohs( pxAddress->sin_port ); + + /* IP address of remote machine. */ + pxSocket->u.xTCP.ulRemoteIP = FreeRTOS_ntohl( pxAddress->sin_addr ); + + /* (client) internal state: socket wants to send a connect. */ + vTCPStateChange( pxSocket, eCONNECT_SYN ); + + /* To start an active connect. */ + pxSocket->u.xTCP.usTimeout = 1U; + + if( xSendEventToIPTask( eTCPTimerEvent ) != pdPASS ) + { + xResult = -pdFREERTOS_ERRNO_ECANCELED; + } + } + } + + return xResult; + } + + +#endif /* ipconfigUSE_TCP */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_TCP == 1 ) + +/** + * @brief Connect to a remote port. + * + * @param[in] xClientSocket: The socket initiating the connection. + * @param[in] pxAddress: The address of the remote socket. + * @param[in] xAddressLength: This parameter is not used. It is kept in + * the function signature to adhere to the Berkeley + * sockets standard. + * + * @return 0 is returned on a successful connection, else a negative + * error code is returned. + */ + BaseType_t FreeRTOS_connect( Socket_t xClientSocket, + struct freertos_sockaddr * pxAddress, + socklen_t xAddressLength ) + { + FreeRTOS_Socket_t * pxSocket = ( FreeRTOS_Socket_t * ) xClientSocket; + TickType_t xRemainingTime; + BaseType_t xTimed = pdFALSE; + BaseType_t xResult = -pdFREERTOS_ERRNO_EINVAL; + TimeOut_t xTimeOut; + + ( void ) xAddressLength; + + xResult = prvTCPConnectStart( pxSocket, pxAddress ); + + if( xResult == 0 ) + { + /* And wait for the result */ + for( ; ; ) + { + if( xTimed == pdFALSE ) + { + /* Only in the first round, check for non-blocking */ + xRemainingTime = pxSocket->xReceiveBlockTime; + + if( xRemainingTime == ( TickType_t ) 0 ) + { + /* Not yet connected, correct state, non-blocking. */ + xResult = -pdFREERTOS_ERRNO_EWOULDBLOCK; + break; + } + + /* Don't get here a second time. */ + xTimed = pdTRUE; + + /* Fetch the current time */ + vTaskSetTimeOutState( &xTimeOut ); + } + + /* Did it get connected while sleeping ? */ + xResult = FreeRTOS_issocketconnected( pxSocket ); + + /* Returns positive when connected, negative means an error */ + if( xResult < 0 ) + { + /* Return the error */ + break; + } + + if( xResult > 0 ) + { + /* Socket now connected, return a zero */ + xResult = 0; + break; + } + + /* Is it allowed to sleep more? */ + if( xTaskCheckForTimeOut( &xTimeOut, &xRemainingTime ) != pdFALSE ) + { + xResult = -pdFREERTOS_ERRNO_ETIMEDOUT; + break; + } + + /* Go sleeping until we get any down-stream event */ + ( void ) xEventGroupWaitBits( pxSocket->xEventGroup, ( EventBits_t ) eSOCKET_CONNECT, pdTRUE /*xClearOnExit*/, pdFALSE /*xWaitAllBits*/, xRemainingTime ); + } + } + + return xResult; + } + +#endif /* ipconfigUSE_TCP */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_TCP == 1 ) + +/** + * @brief Accept a connection on an listening socket. + * + * @param[in] xServerSocket: The socket in listening mode. + * @param[out] pxAddress: The address of the machine trying to connect to this node + * is returned in this pointer. + * @param[out] pxAddressLength: The length of the address of the remote machine. + * + * @return FreeRTOS_accept: can return a new connected socket if the server socket + * is in listen mode and receives a connection request. The new socket will + * be bound already to the same port number as the listening socket. + */ + Socket_t FreeRTOS_accept( Socket_t xServerSocket, + struct freertos_sockaddr * pxAddress, + socklen_t * pxAddressLength ) + { + FreeRTOS_Socket_t * pxSocket = ( FreeRTOS_Socket_t * ) xServerSocket; + FreeRTOS_Socket_t * pxClientSocket = NULL; + TickType_t xRemainingTime; + BaseType_t xTimed = pdFALSE, xAsk = pdFALSE; + TimeOut_t xTimeOut; + IPStackEvent_t xAskEvent; + + if( prvValidSocket( pxSocket, FREERTOS_IPPROTO_TCP, pdTRUE ) == pdFALSE ) + { + /* Not a valid socket or wrong type */ + pxClientSocket = FREERTOS_INVALID_SOCKET; + } + else if( ( pxSocket->u.xTCP.bits.bReuseSocket == pdFALSE_UNSIGNED ) && + ( pxSocket->u.xTCP.ucTCPState != ( uint8_t ) eTCP_LISTEN ) ) + { + /* Parent socket is not in listening mode */ + pxClientSocket = FREERTOS_INVALID_SOCKET; + } + else + { + /* Loop will stop with breaks. */ + for( ; ; ) + { + /* Is there a new client? */ + vTaskSuspendAll(); + { + if( pxSocket->u.xTCP.bits.bReuseSocket == pdFALSE_UNSIGNED ) + { + pxClientSocket = pxSocket->u.xTCP.pxPeerSocket; + } + else + { + pxClientSocket = pxSocket; + } + + if( pxClientSocket != NULL ) + { + pxSocket->u.xTCP.pxPeerSocket = NULL; + + /* Is it still not taken ? */ + if( pxClientSocket->u.xTCP.bits.bPassAccept != pdFALSE_UNSIGNED ) + { + pxClientSocket->u.xTCP.bits.bPassAccept = pdFALSE; + } + else + { + pxClientSocket = NULL; + } + } + } + ( void ) xTaskResumeAll(); + + if( pxClientSocket != NULL ) + { + if( pxAddress != NULL ) + { + /* IP address of remote machine. */ + pxAddress->sin_addr = FreeRTOS_ntohl( pxClientSocket->u.xTCP.ulRemoteIP ); + + /* Port on remote machine. */ + pxAddress->sin_port = FreeRTOS_ntohs( pxClientSocket->u.xTCP.usRemotePort ); + } + + if( pxAddressLength != NULL ) + { + *pxAddressLength = sizeof( *pxAddress ); + } + + if( pxSocket->u.xTCP.bits.bReuseSocket == pdFALSE_UNSIGNED ) + { + xAsk = pdTRUE; + } + } + + if( xAsk != pdFALSE ) + { + /* Ask to set an event in 'xEventGroup' as soon as a new + * client gets connected for this listening socket. */ + xAskEvent.eEventType = eTCPAcceptEvent; + xAskEvent.pvData = pxSocket; + ( void ) xSendEventStructToIPTask( &xAskEvent, portMAX_DELAY ); + } + + if( pxClientSocket != NULL ) + { + break; + } + + if( xTimed == pdFALSE ) + { + /* Only in the first round, check for non-blocking */ + xRemainingTime = pxSocket->xReceiveBlockTime; + + if( xRemainingTime == ( TickType_t ) 0 ) + { + break; + } + + /* Don't get here a second time */ + xTimed = pdTRUE; + + /* Fetch the current time */ + vTaskSetTimeOutState( &xTimeOut ); + } + + /* Has the timeout been reached? */ + if( xTaskCheckForTimeOut( &xTimeOut, &xRemainingTime ) != pdFALSE ) + { + break; + } + + /* Go sleeping until we get any down-stream event */ + ( void ) xEventGroupWaitBits( pxSocket->xEventGroup, ( EventBits_t ) eSOCKET_ACCEPT, pdTRUE /*xClearOnExit*/, pdFALSE /*xWaitAllBits*/, xRemainingTime ); + } + } + + return pxClientSocket; + } + +#endif /* ipconfigUSE_TCP */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_TCP == 1 ) + +/** + * @brief Read incoming data from a TCP socket. Only after the last + * byte has been read, a close error might be returned. + * + * @param[in] xSocket: The socket owning the connection. + * @param[out] pvBuffer: The buffer to store the incoming data in. + * @param[in] uxBufferLength: The length of the buffer so that the function + * does not do out of bound access. + * @param[in] xFlags: The flags for conveying preference. The values + * FREERTOS_MSG_DONTWAIT, FREERTOS_ZERO_COPY and/or + * FREERTOS_MSG_PEEK can be used. + * + * @return The number of bytes actually received and stored in the pvBuffer. + */ + BaseType_t FreeRTOS_recv( Socket_t xSocket, + void * pvBuffer, + size_t uxBufferLength, + BaseType_t xFlags ) + { + BaseType_t xByteCount; + FreeRTOS_Socket_t * pxSocket = ( FreeRTOS_Socket_t * ) xSocket; + TickType_t xRemainingTime; + BaseType_t xTimed = pdFALSE; + TimeOut_t xTimeOut; + EventBits_t xEventBits = ( EventBits_t ) 0; + + /* Check if the socket is valid, has type TCP and if it is bound to a + * port. */ + if( prvValidSocket( pxSocket, FREERTOS_IPPROTO_TCP, pdTRUE ) == pdFALSE ) + { + xByteCount = -pdFREERTOS_ERRNO_EINVAL; + } + else if( ( ( ( uint32_t ) xFlags & ( uint32_t ) FREERTOS_ZERO_COPY ) != 0U ) && + ( pvBuffer == NULL ) ) + { + /* In zero-copy mode, pvBuffer is a pointer to a pointer ( not NULL ). */ + xByteCount = -pdFREERTOS_ERRNO_EINVAL; + } + else + { + if( pxSocket->u.xTCP.rxStream != NULL ) + { + xByteCount = ( BaseType_t ) uxStreamBufferGetSize( pxSocket->u.xTCP.rxStream ); + } + else + { + xByteCount = 0; + } + + while( xByteCount == 0 ) + { + switch( ipNUMERIC_CAST( eIPTCPState_t, pxSocket->u.xTCP.ucTCPState ) ) + { + case eCLOSED: + case eCLOSE_WAIT: /* (server + client) waiting for a connection termination request from the local user. */ + case eCLOSING: /* (server + client) waiting for a connection termination request acknowledgement from the remote TCP. */ + + if( pxSocket->u.xTCP.bits.bMallocError != pdFALSE_UNSIGNED ) + { + /* The no-memory error has priority above the non-connected error. + * Both are fatal and will lead to closing the socket. */ + xByteCount = -pdFREERTOS_ERRNO_ENOMEM; + } + else + { + xByteCount = -pdFREERTOS_ERRNO_ENOTCONN; + } + + break; + + case eTCP_LISTEN: + case eCONNECT_SYN: + case eSYN_FIRST: + case eSYN_RECEIVED: + case eESTABLISHED: + case eFIN_WAIT_1: + case eFIN_WAIT_2: + case eLAST_ACK: + case eTIME_WAIT: + default: + /* Nothing. */ + break; + } + + if( xByteCount < 0 ) + { + break; + } + + if( xTimed == pdFALSE ) + { + /* Only in the first round, check for non-blocking. */ + xRemainingTime = pxSocket->xReceiveBlockTime; + + if( xRemainingTime == ( TickType_t ) 0 ) + { + #if ( ipconfigSUPPORT_SIGNALS != 0 ) + { + /* Just check for the interrupt flag. */ + xEventBits = xEventGroupWaitBits( pxSocket->xEventGroup, ( EventBits_t ) eSOCKET_INTR, + pdTRUE /*xClearOnExit*/, pdFALSE /*xWaitAllBits*/, socketDONT_BLOCK ); + } + #endif /* ipconfigSUPPORT_SIGNALS */ + break; + } + + if( ( ( uint32_t ) xFlags & ( uint32_t ) FREERTOS_MSG_DONTWAIT ) != 0U ) + { + break; + } + + /* Don't get here a second time. */ + xTimed = pdTRUE; + + /* Fetch the current time. */ + vTaskSetTimeOutState( &xTimeOut ); + } + + /* Has the timeout been reached? */ + if( xTaskCheckForTimeOut( &xTimeOut, &xRemainingTime ) != pdFALSE ) + { + break; + } + + /* Block until there is a down-stream event. */ + xEventBits = xEventGroupWaitBits( pxSocket->xEventGroup, + ( EventBits_t ) eSOCKET_RECEIVE | ( EventBits_t ) eSOCKET_CLOSED | ( EventBits_t ) eSOCKET_INTR, + pdTRUE /*xClearOnExit*/, pdFALSE /*xWaitAllBits*/, xRemainingTime ); + #if ( ipconfigSUPPORT_SIGNALS != 0 ) + { + if( ( xEventBits & ( EventBits_t ) eSOCKET_INTR ) != 0U ) + { + break; + } + } + #else + { + ( void ) xEventBits; + } + #endif /* ipconfigSUPPORT_SIGNALS */ + + if( pxSocket->u.xTCP.rxStream != NULL ) + { + xByteCount = ( BaseType_t ) uxStreamBufferGetSize( pxSocket->u.xTCP.rxStream ); + } + else + { + xByteCount = 0; + } + } + + #if ( ipconfigSUPPORT_SIGNALS != 0 ) + if( ( xEventBits & ( EventBits_t ) eSOCKET_INTR ) != 0U ) + { + if( ( xEventBits & ( ( EventBits_t ) eSOCKET_RECEIVE | ( EventBits_t ) eSOCKET_CLOSED ) ) != 0U ) + { + /* Shouldn't have cleared other flags. */ + xEventBits &= ~( ( EventBits_t ) eSOCKET_INTR ); + ( void ) xEventGroupSetBits( pxSocket->xEventGroup, xEventBits ); + } + + xByteCount = -pdFREERTOS_ERRNO_EINTR; + } + else + #endif /* ipconfigSUPPORT_SIGNALS */ + + if( xByteCount > 0 ) + { + if( ( ( uint32_t ) xFlags & ( uint32_t ) FREERTOS_ZERO_COPY ) == 0U ) + { + BaseType_t xIsPeek = ( ( ( uint32_t ) xFlags & ( uint32_t ) FREERTOS_MSG_PEEK ) != 0U ) ? 1L : 0L; + + xByteCount = ( BaseType_t ) + uxStreamBufferGet( pxSocket->u.xTCP.rxStream, + 0UL, + ipPOINTER_CAST( uint8_t *, pvBuffer ), + ( size_t ) uxBufferLength, + xIsPeek ); + + if( pxSocket->u.xTCP.bits.bLowWater != pdFALSE_UNSIGNED ) + { + /* We had reached the low-water mark, now see if the flag + * can be cleared */ + size_t uxFrontSpace = uxStreamBufferFrontSpace( pxSocket->u.xTCP.rxStream ); + + if( uxFrontSpace >= pxSocket->u.xTCP.uxEnoughSpace ) + { + pxSocket->u.xTCP.bits.bLowWater = pdFALSE; + pxSocket->u.xTCP.bits.bWinChange = pdTRUE; + pxSocket->u.xTCP.usTimeout = 1U; /* because bLowWater is cleared. */ + ( void ) xSendEventToIPTask( eTCPTimerEvent ); + } + } + } + else + { + /* Zero-copy reception of data: pvBuffer is a pointer to a pointer. */ + xByteCount = ( BaseType_t ) uxStreamBufferGetPtr( pxSocket->u.xTCP.rxStream, ipPOINTER_CAST( uint8_t * *, pvBuffer ) ); + } + } + else + { + /* Nothing. */ + } + } /* prvValidSocket() */ + + return xByteCount; + } + + +#endif /* ipconfigUSE_TCP */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_TCP == 1 ) + +/** + * @brief Called from FreeRTOS_send(): some checks which will be done before + * sending a TCP packed. + * + * @param[in] pxSocket: The socket owning the connection. + * @param[in] uxDataLength: The length of the data to be sent. + * + * @return 0: representing OK, else a negative error code will be returned. + */ + static int32_t prvTCPSendCheck( FreeRTOS_Socket_t * pxSocket, + size_t uxDataLength ) + { + int32_t xResult = 1; + + /* Is this a socket of type TCP and is it already bound to a port number ? */ + if( prvValidSocket( pxSocket, FREERTOS_IPPROTO_TCP, pdTRUE ) == pdFALSE ) + { + xResult = -pdFREERTOS_ERRNO_EINVAL; + } + else if( pxSocket->u.xTCP.bits.bMallocError != pdFALSE_UNSIGNED ) + { + xResult = -pdFREERTOS_ERRNO_ENOMEM; + } + else if( ( pxSocket->u.xTCP.ucTCPState == ( uint8_t ) eCLOSED ) || + ( pxSocket->u.xTCP.ucTCPState == ( uint8_t ) eCLOSE_WAIT ) || + ( pxSocket->u.xTCP.ucTCPState == ( uint8_t ) eCLOSING ) ) + { + xResult = -pdFREERTOS_ERRNO_ENOTCONN; + } + else if( pxSocket->u.xTCP.bits.bFinSent != pdFALSE_UNSIGNED ) + { + /* This TCP connection is closing already, the FIN flag has been sent. + * Maybe it is still delivering or receiving data. + * Return OK in order not to get closed/deleted too quickly */ + xResult = 0; + } + else if( uxDataLength == 0UL ) + { + /* send() is being called to send zero bytes */ + xResult = 0; + } + else if( pxSocket->u.xTCP.txStream == NULL ) + { + /* Create the outgoing stream only when it is needed */ + ( void ) prvTCPCreateStream( pxSocket, pdFALSE ); + + if( pxSocket->u.xTCP.txStream == NULL ) + { + xResult = -pdFREERTOS_ERRNO_ENOMEM; + } + } + else + { + /* Nothing. */ + } + + return xResult; + } + +#endif /* ipconfigUSE_TCP */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_TCP == 1 ) + +/** + * @brief Get a direct pointer to the circular transmit buffer. + * + * @param[in] xSocket: The socket owning the buffer. + * @param[in] pxLength: This will contain the number of bytes that may be written. + * + * @return Head of the circular transmit buffer if all checks pass. Or else, NULL + * is returned. + */ + uint8_t * FreeRTOS_get_tx_head( ConstSocket_t xSocket, + BaseType_t * pxLength ) + { + uint8_t * pucReturn = NULL; + const FreeRTOS_Socket_t * pxSocket = ( const FreeRTOS_Socket_t * ) xSocket; + StreamBuffer_t * pxBuffer = NULL; + + *pxLength = 0; + + /* Confirm that this is a TCP socket before dereferencing structure + * member pointers. */ + if( prvValidSocket( pxSocket, FREERTOS_IPPROTO_TCP, pdFALSE ) == pdTRUE ) + { + pxBuffer = pxSocket->u.xTCP.txStream; + + if( pxBuffer != NULL ) + { + BaseType_t xSpace = ( BaseType_t ) uxStreamBufferGetSpace( pxBuffer ); + BaseType_t xRemain = ( BaseType_t ) pxBuffer->LENGTH - ( BaseType_t ) pxBuffer->uxHead; + + *pxLength = FreeRTOS_min_BaseType( xSpace, xRemain ); + pucReturn = &( pxBuffer->ucArray[ pxBuffer->uxHead ] ); + } + } + + return pucReturn; + } + +#endif /* ipconfigUSE_TCP */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_TCP == 1 ) + +/** + * @brief Send data using a TCP socket. It is not necessary to have the socket + * connected already. Outgoing data will be stored and delivered as soon as + * the socket gets connected. + * + * @param[in] xSocket: The socket owning the connection. + * @param[in] pvBuffer: The buffer containing the data. + * @param[in] uxDataLength: The length of the data to be added. + * @param[in] xFlags: This parameter is not used. (zero or FREERTOS_MSG_DONTWAIT). + * + * @return The number of bytes actually sent. Zero when nothing could be sent + * or a negative error code in case an error occurred. + */ + BaseType_t FreeRTOS_send( Socket_t xSocket, + const void * pvBuffer, + size_t uxDataLength, + BaseType_t xFlags ) + { + BaseType_t xByteCount = -pdFREERTOS_ERRNO_EINVAL; + BaseType_t xBytesLeft; + FreeRTOS_Socket_t * pxSocket = ( FreeRTOS_Socket_t * ) xSocket; + TickType_t xRemainingTime; + BaseType_t xTimed = pdFALSE; + TimeOut_t xTimeOut; + BaseType_t xCloseAfterSend; + const uint8_t * pucSource = ipPOINTER_CAST( const uint8_t *, pvBuffer ); + + /* Prevent compiler warnings about unused parameters. The parameter + * may be used in future versions. */ + ( void ) xFlags; + + if( pvBuffer != NULL ) + { + xByteCount = ( BaseType_t ) prvTCPSendCheck( pxSocket, uxDataLength ); + } + + if( xByteCount > 0 ) + { + /* xBytesLeft is number of bytes to send, will count to zero. */ + xBytesLeft = ( BaseType_t ) uxDataLength; + + /* xByteCount is number of bytes that can be sent now. */ + xByteCount = ( BaseType_t ) uxStreamBufferGetSpace( pxSocket->u.xTCP.txStream ); + + /* While there are still bytes to be sent. */ + while( xBytesLeft > 0 ) + { + /* If txStream has space. */ + if( xByteCount > 0 ) + { + /* Don't send more than necessary. */ + if( xByteCount > xBytesLeft ) + { + xByteCount = xBytesLeft; + } + + /* Is the close-after-send flag set and is this really the + * last transmission? */ + if( ( pxSocket->u.xTCP.bits.bCloseAfterSend != pdFALSE_UNSIGNED ) && ( xByteCount == xBytesLeft ) ) + { + xCloseAfterSend = pdTRUE; + } + else + { + xCloseAfterSend = pdFALSE; + } + + /* The flag 'bCloseAfterSend' can be set before sending data + * using setsockopt() + * + * When the last data packet is being sent out, a FIN flag will + * be included to let the peer know that no more data is to be + * expected. The use of 'bCloseAfterSend' is not mandatory, it + * is just a faster way of transferring files (e.g. when using + * FTP). */ + if( xCloseAfterSend != pdFALSE ) + { + /* Now suspend the scheduler: sending the last data and + * setting bCloseRequested must be done together */ + vTaskSuspendAll(); + pxSocket->u.xTCP.bits.bCloseRequested = pdTRUE; + } + + xByteCount = ( BaseType_t ) uxStreamBufferAdd( pxSocket->u.xTCP.txStream, 0UL, pucSource, ( size_t ) xByteCount ); + + if( xCloseAfterSend != pdFALSE ) + { + /* Now when the IP-task transmits the data, it will also + * see that bCloseRequested is true and include the FIN + * flag to start closure of the connection. */ + ( void ) xTaskResumeAll(); + } + + /* Send a message to the IP-task so it can work on this + * socket. Data is sent, let the IP-task work on it. */ + pxSocket->u.xTCP.usTimeout = 1U; + + if( xIsCallingFromIPTask() == pdFALSE ) + { + /* Only send a TCP timer event when not called from the + * IP-task. */ + ( void ) xSendEventToIPTask( eTCPTimerEvent ); + } + + xBytesLeft -= xByteCount; + + if( xBytesLeft == 0 ) + { + break; + } + + /* As there are still bytes left to be sent, increase the + * data pointer. */ + pucSource = &( pucSource[ xByteCount ] ); + } + + /* Not all bytes have been sent. In case the socket is marked as + * blocking sleep for a while. */ + if( xTimed == pdFALSE ) + { + /* Only in the first round, check for non-blocking. */ + xRemainingTime = pxSocket->xSendBlockTime; + + #if ( ipconfigUSE_CALLBACKS != 0 ) + { + if( xIsCallingFromIPTask() != pdFALSE ) + { + /* If this send function is called from within a + * call-back handler it may not block, otherwise + * chances would be big to get a deadlock: the IP-task + * waiting for itself. */ + xRemainingTime = ( TickType_t ) 0; + } + } + #endif /* ipconfigUSE_CALLBACKS */ + + if( xRemainingTime == ( TickType_t ) 0 ) + { + break; + } + + if( ( ( uint32_t ) xFlags & ( uint32_t ) FREERTOS_MSG_DONTWAIT ) != 0U ) + { + break; + } + + /* Don't get here a second time. */ + xTimed = pdTRUE; + + /* Fetch the current time. */ + vTaskSetTimeOutState( &xTimeOut ); + } + else + { + /* Has the timeout been reached? */ + if( xTaskCheckForTimeOut( &xTimeOut, &xRemainingTime ) != pdFALSE ) + { + break; + } + } + + /* Go sleeping until down-stream events are received. */ + ( void ) xEventGroupWaitBits( pxSocket->xEventGroup, ( EventBits_t ) eSOCKET_SEND | ( EventBits_t ) eSOCKET_CLOSED, + pdTRUE /*xClearOnExit*/, pdFALSE /*xWaitAllBits*/, xRemainingTime ); + + xByteCount = ( BaseType_t ) uxStreamBufferGetSpace( pxSocket->u.xTCP.txStream ); + } + + /* How much was actually sent? */ + xByteCount = ( ( BaseType_t ) uxDataLength ) - xBytesLeft; + + if( xByteCount == 0 ) + { + if( pxSocket->u.xTCP.ucTCPState > ( uint8_t ) eESTABLISHED ) + { + xByteCount = ( BaseType_t ) -pdFREERTOS_ERRNO_ENOTCONN; + } + else + { + if( ipconfigTCP_MAY_LOG_PORT( pxSocket->usLocalPort ) ) + { + FreeRTOS_debug_printf( ( "FreeRTOS_send: %u -> %lxip:%d: no space\n", + pxSocket->usLocalPort, + pxSocket->u.xTCP.ulRemoteIP, + pxSocket->u.xTCP.usRemotePort ) ); + } + + xByteCount = ( BaseType_t ) -pdFREERTOS_ERRNO_ENOSPC; + } + } + } + + return xByteCount; + } + + +#endif /* ipconfigUSE_TCP */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_TCP == 1 ) + +/** + * @brief Request to put a socket in listen mode. + * + * @param[in] xSocket: the socket to be put in listening mode. + * @param[in] xBacklog: Maximum number of child sockets. + * + * @return 0 in case of success, or else a negative error code is + * returned. + */ + BaseType_t FreeRTOS_listen( Socket_t xSocket, + BaseType_t xBacklog ) + { + FreeRTOS_Socket_t * pxSocket; + BaseType_t xResult = 0; + + pxSocket = ( FreeRTOS_Socket_t * ) xSocket; + + /* listen() is allowed for a valid TCP socket in Closed state and already + * bound. */ + if( prvValidSocket( pxSocket, FREERTOS_IPPROTO_TCP, pdTRUE ) == pdFALSE ) + { + xResult = -pdFREERTOS_ERRNO_EOPNOTSUPP; + } + else if( ( pxSocket->u.xTCP.ucTCPState != ( uint8_t ) eCLOSED ) && ( pxSocket->u.xTCP.ucTCPState != ( uint8_t ) eCLOSE_WAIT ) ) + { + /* Socket is in a wrong state. */ + xResult = -pdFREERTOS_ERRNO_EOPNOTSUPP; + } + else + { + /* Backlog is interpreted here as "the maximum number of child + * sockets. */ + pxSocket->u.xTCP.usBacklog = ( uint16_t ) FreeRTOS_min_int32( ( int32_t ) 0xffff, ( int32_t ) xBacklog ); + + /* This cleaning is necessary only if a listening socket is being + * reused as it might have had a previous connection. */ + if( pxSocket->u.xTCP.bits.bReuseSocket != pdFALSE_UNSIGNED ) + { + if( pxSocket->u.xTCP.rxStream != NULL ) + { + vStreamBufferClear( pxSocket->u.xTCP.rxStream ); + } + + if( pxSocket->u.xTCP.txStream != NULL ) + { + vStreamBufferClear( pxSocket->u.xTCP.txStream ); + } + + ( void ) memset( pxSocket->u.xTCP.xPacket.u.ucLastPacket, 0, sizeof( pxSocket->u.xTCP.xPacket.u.ucLastPacket ) ); + ( void ) memset( &pxSocket->u.xTCP.xTCPWindow, 0, sizeof( pxSocket->u.xTCP.xTCPWindow ) ); + ( void ) memset( &pxSocket->u.xTCP.bits, 0, sizeof( pxSocket->u.xTCP.bits ) ); + + /* Now set the bReuseSocket flag again, because the bits have + * just been cleared. */ + pxSocket->u.xTCP.bits.bReuseSocket = pdTRUE; + } + + vTCPStateChange( pxSocket, eTCP_LISTEN ); + } + + return xResult; + } + + +#endif /* ipconfigUSE_TCP */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_TCP == 1 ) + +/** + * @brief Shutdown - This function will shut down the connection in both + * directions. However, it will first deliver all data queued for + * transmission, and also it will first wait to receive any missing + * packets from the peer. + * + * @param[in] xSocket: The socket owning the connection. + * @param[in] xHow: Not used. Just present to stick to Berkeley standard. + * + * @return 0 on successful shutdown or else a negative error code. + */ + BaseType_t FreeRTOS_shutdown( Socket_t xSocket, + BaseType_t xHow ) + { + FreeRTOS_Socket_t * pxSocket = ( FreeRTOS_Socket_t * ) xSocket; + BaseType_t xResult; + + if( prvValidSocket( pxSocket, FREERTOS_IPPROTO_TCP, pdTRUE ) == pdFALSE ) + { + /*_RB_ Is this comment correct? The socket is not of a type that + * supports the listen() operation. */ + xResult = -pdFREERTOS_ERRNO_EOPNOTSUPP; + } + else if( pxSocket->u.xTCP.ucTCPState != ( uint8_t ) eESTABLISHED ) + { + /*_RB_ Is this comment correct? The socket is not of a type that + * supports the listen() operation. */ + xResult = -pdFREERTOS_ERRNO_EOPNOTSUPP; + } + else + { + pxSocket->u.xTCP.bits.bUserShutdown = pdTRUE_UNSIGNED; + + /* Let the IP-task perform the shutdown of the connection. */ + pxSocket->u.xTCP.usTimeout = 1U; + ( void ) xSendEventToIPTask( eTCPTimerEvent ); + xResult = 0; + } + + ( void ) xHow; + + return xResult; + } + + +#endif /* ipconfigUSE_TCP */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_TCP == 1 ) + +/** + * @brief A TCP timer has expired, now check all TCP sockets for: + * - Active connect + * - Send a delayed ACK + * - Send new data + * - Send a keep-alive packet + * - Check for timeout (in non-connected states only) + * + * @param[in] xWillSleep: Whether the calling task is going to sleep. + * + * @return Minimum amount of time before the timer shall expire. + */ + TickType_t xTCPTimerCheck( BaseType_t xWillSleep ) + { + FreeRTOS_Socket_t * pxSocket; + TickType_t xShortest = pdMS_TO_TICKS( ( TickType_t ) ipTCP_TIMER_PERIOD_MS ); + TickType_t xNow = xTaskGetTickCount(); + static TickType_t xLastTime = 0U; + TickType_t xDelta = xNow - xLastTime; + const ListItem_t * pxEnd = listGET_END_MARKER( &xBoundTCPSocketsList ); + const ListItem_t * pxIterator = ( const ListItem_t * ) listGET_HEAD_ENTRY( &xBoundTCPSocketsList ); + + xLastTime = xNow; + + if( xDelta == 0U ) + { + xDelta = 1U; + } + + while( pxIterator != pxEnd ) + { + pxSocket = ipCAST_PTR_TO_TYPE_PTR( FreeRTOS_Socket_t, listGET_LIST_ITEM_OWNER( pxIterator ) ); + pxIterator = ( ListItem_t * ) listGET_NEXT( pxIterator ); + + /* Sockets with 'timeout == 0' do not need any regular attention. */ + if( pxSocket->u.xTCP.usTimeout == 0U ) + { + continue; + } + + if( xDelta < ( TickType_t ) pxSocket->u.xTCP.usTimeout ) + { + pxSocket->u.xTCP.usTimeout = ( uint16_t ) ( ( ( TickType_t ) pxSocket->u.xTCP.usTimeout ) - xDelta ); + } + else + { + BaseType_t xRc; + + pxSocket->u.xTCP.usTimeout = 0U; + xRc = xTCPSocketCheck( pxSocket ); + + /* Within this function, the socket might want to send a delayed + * ack or send out data or whatever it needs to do. */ + if( xRc < 0 ) + { + /* Continue because the socket was deleted. */ + continue; + } + } + + /* In xEventBits the driver may indicate that the socket has + * important events for the user. These are only done just before the + * IP-task goes to sleep. */ + if( pxSocket->xEventBits != 0U ) + { + if( xWillSleep != pdFALSE ) + { + /* The IP-task is about to go to sleep, so messages can be + * sent to the socket owners. */ + vSocketWakeUpUser( pxSocket ); + } + else + { + /* Or else make sure this will be called again to wake-up + * the sockets' owner. */ + xShortest = ( TickType_t ) 0; + } + } + + if( ( pxSocket->u.xTCP.usTimeout != 0U ) && ( xShortest > ( TickType_t ) pxSocket->u.xTCP.usTimeout ) ) + { + xShortest = ( TickType_t ) pxSocket->u.xTCP.usTimeout; + } + } + + return xShortest; + } + + +#endif /* ipconfigUSE_TCP */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_TCP == 1 ) + +/** + * @brief As multiple sockets may be bound to the same local port number + * looking up a socket is a little more complex: Both a local port, + * and a remote port and IP address are being used to find a match. + * For a socket in listening mode, the remote port and IP address + * are both 0. + * + * @param[in] ulLocalIP: Local IP address. Ignored for now. + * @param[in] uxLocalPort: Local port number. + * @param[in] ulRemoteIP: Remote (peer) IP address. + * @param[in] uxRemotePort: Remote (peer) port. + * + * @return The socket which was found. + */ + FreeRTOS_Socket_t * pxTCPSocketLookup( uint32_t ulLocalIP, + UBaseType_t uxLocalPort, + uint32_t ulRemoteIP, + UBaseType_t uxRemotePort ) + { + const ListItem_t * pxIterator; + FreeRTOS_Socket_t * pxResult = NULL, * pxListenSocket = NULL; + const ListItem_t * pxEnd = listGET_END_MARKER( &xBoundTCPSocketsList ); + + /* Parameter not yet supported. */ + ( void ) ulLocalIP; + + for( pxIterator = listGET_NEXT( pxEnd ); + pxIterator != pxEnd; + pxIterator = listGET_NEXT( pxIterator ) ) + { + FreeRTOS_Socket_t * pxSocket = ipCAST_PTR_TO_TYPE_PTR( FreeRTOS_Socket_t, listGET_LIST_ITEM_OWNER( pxIterator ) ); + + if( pxSocket->usLocalPort == ( uint16_t ) uxLocalPort ) + { + if( pxSocket->u.xTCP.ucTCPState == ( uint8_t ) eTCP_LISTEN ) + { + /* If this is a socket listening to uxLocalPort, remember it + * in case there is no perfect match. */ + pxListenSocket = pxSocket; + } + else if( ( pxSocket->u.xTCP.usRemotePort == ( uint16_t ) uxRemotePort ) && ( pxSocket->u.xTCP.ulRemoteIP == ulRemoteIP ) ) + { + /* For sockets not in listening mode, find a match with + * xLocalPort, ulRemoteIP AND xRemotePort. */ + pxResult = pxSocket; + break; + } + else + { + /* This 'pxSocket' doesn't match. */ + } + } + } + + if( pxResult == NULL ) + { + /* An exact match was not found, maybe a listening socket was + * found. */ + pxResult = pxListenSocket; + } + + return pxResult; + } + +#endif /* ipconfigUSE_TCP */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_TCP == 1 ) + +/** + * @brief For the web server: borrow the circular Rx buffer for inspection. + * HTML driver wants to see if a sequence of 13/10/13/10 is available. + * + * @param[in] xSocket: The socket whose Rx stream is to be returned. + * + * @return The Rx stream of the socket if all checks pass, else NULL. + */ + const struct xSTREAM_BUFFER * FreeRTOS_get_rx_buf( ConstSocket_t xSocket ) + { + const FreeRTOS_Socket_t * pxSocket = ( const FreeRTOS_Socket_t * ) xSocket; + const struct xSTREAM_BUFFER * pxReturn = NULL; + + + /* Confirm that this is a TCP socket before dereferencing structure + * member pointers. */ + if( prvValidSocket( pxSocket, FREERTOS_IPPROTO_TCP, pdFALSE ) == pdTRUE ) + { + pxReturn = pxSocket->u.xTCP.rxStream; + } + + return pxReturn; + } + +#endif /* ipconfigUSE_TCP */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_TCP == 1 ) + +/** + * @brief Create the stream buffer for the given socket. + * + * @param[in] pxSocket: the socket to create the stream for. + * @param[in] xIsInputStream: Is this input stream? pdTRUE/pdFALSE? + * + * @return The stream buffer. + */ + static StreamBuffer_t * prvTCPCreateStream( FreeRTOS_Socket_t * pxSocket, + BaseType_t xIsInputStream ) + { + StreamBuffer_t * pxBuffer; + size_t uxLength; + size_t uxSize; + + /* Now that a stream is created, the maximum size is fixed before + * creation, it could still be changed with setsockopt(). */ + if( xIsInputStream != pdFALSE ) + { + uxLength = pxSocket->u.xTCP.uxRxStreamSize; + + if( pxSocket->u.xTCP.uxLittleSpace == 0UL ) + { + pxSocket->u.xTCP.uxLittleSpace = ( sock20_PERCENT * pxSocket->u.xTCP.uxRxStreamSize ) / sock100_PERCENT; + } + + if( pxSocket->u.xTCP.uxEnoughSpace == 0UL ) + { + pxSocket->u.xTCP.uxEnoughSpace = ( sock80_PERCENT * pxSocket->u.xTCP.uxRxStreamSize ) / sock100_PERCENT; + } + } + else + { + uxLength = pxSocket->u.xTCP.uxTxStreamSize; + } + + /* Add an extra 4 (or 8) bytes. */ + uxLength += sizeof( size_t ); + + /* And make the length a multiple of sizeof( size_t ). */ + uxLength &= ~( sizeof( size_t ) - 1U ); + + uxSize = ( sizeof( *pxBuffer ) + uxLength ) - sizeof( pxBuffer->ucArray ); + + pxBuffer = ipCAST_PTR_TO_TYPE_PTR( StreamBuffer_t, pvPortMallocLarge( uxSize ) ); + + if( pxBuffer == NULL ) + { + FreeRTOS_debug_printf( ( "prvTCPCreateStream: malloc failed\n" ) ); + pxSocket->u.xTCP.bits.bMallocError = pdTRUE; + vTCPStateChange( pxSocket, eCLOSE_WAIT ); + } + else + { + /* Clear the markers of the stream */ + ( void ) memset( pxBuffer, 0, sizeof( *pxBuffer ) - sizeof( pxBuffer->ucArray ) ); + pxBuffer->LENGTH = ( size_t ) uxLength; + + if( xTCPWindowLoggingLevel != 0 ) + { + FreeRTOS_debug_printf( ( "prvTCPCreateStream: %cxStream created %u bytes (total %u)\n", ( xIsInputStream != 0 ) ? 'R' : 'T', uxLength, uxSize ) ); + } + + if( xIsInputStream != 0 ) + { + iptraceMEM_STATS_CREATE( tcpRX_STREAM_BUFFER, pxBuffer, uxSize ); + pxSocket->u.xTCP.rxStream = pxBuffer; + } + else + { + iptraceMEM_STATS_CREATE( tcpTX_STREAM_BUFFER, pxBuffer, uxSize ); + pxSocket->u.xTCP.txStream = pxBuffer; + } + } + + return pxBuffer; + } + + +#endif /* ipconfigUSE_TCP */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_TCP == 1 ) + +/** + * @brief Add data to the RxStream. When uxOffset > 0, data has come in out-of-order + * and will be put in front of the head so it can not be popped by the user. + * + * @param[in] pxSocket: The socket to whose RxStream data is to be added. + * @param[in] uxOffset: Offset of the packet. + * @param[in] pcData: The data to be added to the RxStream. + * @param[in] ulByteCount: Number of bytes in the data. + * + * @return The number of bytes actually added to the RxStream. Or else, a negative + * error code is returned. + */ + int32_t lTCPAddRxdata( FreeRTOS_Socket_t * pxSocket, + size_t uxOffset, + const uint8_t * pcData, + uint32_t ulByteCount ) + { + StreamBuffer_t * pxStream = pxSocket->u.xTCP.rxStream; + int32_t xResult = 0; + + #if ( ipconfigUSE_CALLBACKS == 1 ) + BaseType_t bHasHandler = ipconfigIS_VALID_PROG_ADDRESS( pxSocket->u.xTCP.pxHandleReceive ) ? pdTRUE : pdFALSE; + const uint8_t * pucBuffer = NULL; + #endif /* ipconfigUSE_CALLBACKS */ + + /* int32_t uxStreamBufferAdd( pxBuffer, uxOffset, pucData, aCount ) + * if( pucData != NULL ) copy data the the buffer + * if( pucData == NULL ) no copying, just advance rxHead + * if( uxOffset != 0 ) Just store data which has come out-of-order + * if( uxOffset == 0 ) Also advance rxHead */ + if( pxStream == NULL ) + { + pxStream = prvTCPCreateStream( pxSocket, pdTRUE ); + + if( pxStream == NULL ) + { + xResult = -1; + } + } + + if( xResult >= 0 ) + { + #if ( ipconfigUSE_CALLBACKS == 1 ) + { + if( ( bHasHandler != pdFALSE ) && ( uxStreamBufferGetSize( pxStream ) == 0U ) && ( uxOffset == 0UL ) && ( pcData != NULL ) ) + { + /* Data can be passed directly to the user */ + pucBuffer = pcData; + + pcData = NULL; + } + } + #endif /* ipconfigUSE_CALLBACKS */ + + xResult = ( int32_t ) uxStreamBufferAdd( pxStream, uxOffset, pcData, ( size_t ) ulByteCount ); + + #if ( ipconfigHAS_DEBUG_PRINTF != 0 ) + { + if( xResult != ( int32_t ) ulByteCount ) + { + FreeRTOS_debug_printf( ( "lTCPAddRxdata: at %u: %d/%u bytes (tail %u head %u space %u front %u)\n", + ( UBaseType_t ) uxOffset, + ( BaseType_t ) xResult, + ( UBaseType_t ) ulByteCount, + ( UBaseType_t ) pxStream->uxTail, + ( UBaseType_t ) pxStream->uxHead, + ( UBaseType_t ) uxStreamBufferFrontSpace( pxStream ), + ( UBaseType_t ) pxStream->uxFront ) ); + } + } + #endif /* ipconfigHAS_DEBUG_PRINTF */ + + if( uxOffset == 0U ) + { + /* Data is being added to rxStream at the head (offs = 0) */ + #if ( ipconfigUSE_CALLBACKS == 1 ) + if( bHasHandler != pdFALSE ) + { + /* The socket owner has installed an OnReceive handler. Pass the + * Rx data, without copying from the rxStream, to the user. */ + for( ; ; ) + { + uint8_t * ucReadPtr = NULL; + uint32_t ulCount; + + if( pucBuffer != NULL ) + { + ucReadPtr = ipPOINTER_CAST( uint8_t *, pucBuffer ); + ulCount = ulByteCount; + pucBuffer = NULL; + } + else + { + ulCount = ( uint32_t ) uxStreamBufferGetPtr( pxStream, &( ucReadPtr ) ); + } + + if( ulCount == 0UL ) + { + break; + } + + ( void ) pxSocket->u.xTCP.pxHandleReceive( pxSocket, ucReadPtr, ( size_t ) ulCount ); + ( void ) uxStreamBufferGet( pxStream, 0UL, NULL, ( size_t ) ulCount, pdFALSE ); + } + } + else + #endif /* ipconfigUSE_CALLBACKS */ + { + /* See if running out of space. */ + if( pxSocket->u.xTCP.bits.bLowWater == pdFALSE_UNSIGNED ) + { + size_t uxFrontSpace = uxStreamBufferFrontSpace( pxSocket->u.xTCP.rxStream ); + + if( uxFrontSpace <= pxSocket->u.xTCP.uxLittleSpace ) + { + pxSocket->u.xTCP.bits.bLowWater = pdTRUE; + pxSocket->u.xTCP.bits.bWinChange = pdTRUE; + + /* bLowWater was reached, send the changed window size. */ + pxSocket->u.xTCP.usTimeout = 1U; + ( void ) xSendEventToIPTask( eTCPTimerEvent ); + } + } + + /* New incoming data is available, wake up the user. User's + * semaphores will be set just before the IP-task goes asleep. */ + pxSocket->xEventBits |= ( EventBits_t ) eSOCKET_RECEIVE; + + #if ipconfigSUPPORT_SELECT_FUNCTION == 1 + { + if( ( pxSocket->xSelectBits & ( EventBits_t ) eSELECT_READ ) != 0U ) + { + pxSocket->xEventBits |= ( ( ( EventBits_t ) eSELECT_READ ) << SOCKET_EVENT_BIT_COUNT ); + } + } + #endif + } + } + } + + return xResult; + } + + +#endif /* ipconfigUSE_TCP */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_TCP == 1 ) + +/** + * @brief Function to get the remote IP-address and port number. + * + * @param[in] xSocket: Socket owning the connection. + * @param[out] pxAddress: The address pointer to which the address + * is to be added. + * + * @return The size of the address being returned. Or else a negative + * error code will be returned. + */ + BaseType_t FreeRTOS_GetRemoteAddress( ConstSocket_t xSocket, + struct freertos_sockaddr * pxAddress ) + { + const FreeRTOS_Socket_t * pxSocket = ( const FreeRTOS_Socket_t * ) xSocket; + BaseType_t xResult; + + if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP ) + { + xResult = -pdFREERTOS_ERRNO_EINVAL; + } + else + { + /* BSD style sockets communicate IP and port addresses in network + * byte order. + * IP address of remote machine. */ + pxAddress->sin_addr = FreeRTOS_htonl( pxSocket->u.xTCP.ulRemoteIP ); + + /* Port on remote machine. */ + pxAddress->sin_port = FreeRTOS_htons( pxSocket->u.xTCP.usRemotePort ); + + xResult = ( BaseType_t ) sizeof( *pxAddress ); + } + + return xResult; + } + + +#endif /* ipconfigUSE_TCP */ + +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_TCP == 1 ) + +/** + * @brief Check the number of bytes that may be added to txStream. + * + * @param[in] xSocket: The socket to be checked. + * + * @return the number of bytes that may be added to txStream or + * else a negative error code. + */ + BaseType_t FreeRTOS_maywrite( ConstSocket_t xSocket ) + { + const FreeRTOS_Socket_t * pxSocket = ( const FreeRTOS_Socket_t * ) xSocket; + BaseType_t xResult; + + if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP ) + { + xResult = -pdFREERTOS_ERRNO_EINVAL; + } + else if( pxSocket->u.xTCP.ucTCPState != ( uint8_t ) eESTABLISHED ) + { + if( ( pxSocket->u.xTCP.ucTCPState < ( uint8_t ) eCONNECT_SYN ) || ( pxSocket->u.xTCP.ucTCPState > ( EventBits_t ) eESTABLISHED ) ) + { + xResult = -1; + } + else + { + xResult = 0; + } + } + else if( pxSocket->u.xTCP.txStream == NULL ) + { + xResult = ( BaseType_t ) pxSocket->u.xTCP.uxTxStreamSize; + } + else + { + xResult = ( BaseType_t ) uxStreamBufferGetSpace( pxSocket->u.xTCP.txStream ); + } + + return xResult; + } + + +#endif /* ipconfigUSE_TCP */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_TCP == 1 ) + +/** + * @brief Get the number of bytes that can be written in the Tx buffer + * of the given socket. + * + * @param[in] xSocket: the socket to be checked. + * + * @return The bytes that can be written. Or else an error code. + */ + BaseType_t FreeRTOS_tx_space( ConstSocket_t xSocket ) + { + const FreeRTOS_Socket_t * pxSocket = ( const FreeRTOS_Socket_t * ) xSocket; + BaseType_t xReturn; + + if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP ) + { + xReturn = -pdFREERTOS_ERRNO_EINVAL; + } + else + { + if( pxSocket->u.xTCP.txStream != NULL ) + { + xReturn = ( BaseType_t ) uxStreamBufferGetSpace( pxSocket->u.xTCP.txStream ); + } + else + { + xReturn = ( BaseType_t ) pxSocket->u.xTCP.uxTxStreamSize; + } + } + + return xReturn; + } + + +#endif /* ipconfigUSE_TCP */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_TCP == 1 ) + +/** + * @brief Returns the number of bytes stored in the Tx buffer. + * + * @param[in] xSocket: The socket to be checked. + * + * @return The number of bytes stored in the Tx buffer of the socket. + * Or an error code. + */ + BaseType_t FreeRTOS_tx_size( ConstSocket_t xSocket ) + { + const FreeRTOS_Socket_t * pxSocket = ( const FreeRTOS_Socket_t * ) xSocket; + BaseType_t xReturn; + + if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP ) + { + xReturn = -pdFREERTOS_ERRNO_EINVAL; + } + else + { + if( pxSocket->u.xTCP.txStream != NULL ) + { + xReturn = ( BaseType_t ) uxStreamBufferGetSize( pxSocket->u.xTCP.txStream ); + } + else + { + xReturn = 0; + } + } + + return xReturn; + } + + +#endif /* ipconfigUSE_TCP */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_TCP == 1 ) + +/** + * @brief Is the socket connected. + * + * @param[in] xSocket: The socket being checked. + * + * @return pdTRUE if TCP socket is connected. + */ + BaseType_t FreeRTOS_issocketconnected( ConstSocket_t xSocket ) + { + const FreeRTOS_Socket_t * pxSocket = ( const FreeRTOS_Socket_t * ) xSocket; + BaseType_t xReturn = pdFALSE; + + if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP ) + { + xReturn = -pdFREERTOS_ERRNO_EINVAL; + } + else + { + if( pxSocket->u.xTCP.ucTCPState >= ( uint8_t ) eESTABLISHED ) + { + if( pxSocket->u.xTCP.ucTCPState < ( uint8_t ) eCLOSE_WAIT ) + { + xReturn = pdTRUE; + } + } + } + + return xReturn; + } + + +#endif /* ipconfigUSE_TCP */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_TCP == 1 ) + +/** + * @brief Get the actual value of Maximum Segment Size ( MSS ) being used. + * + * @param[in] xSocket: The socket whose MSS is to be returned. + * + * @return the actual size of MSS being used or an error code. + */ + BaseType_t FreeRTOS_mss( ConstSocket_t xSocket ) + { + const FreeRTOS_Socket_t * pxSocket = ( const FreeRTOS_Socket_t * ) xSocket; + BaseType_t xReturn; + + if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP ) + { + xReturn = -pdFREERTOS_ERRNO_EINVAL; + } + else + { + /* usCurMSS is declared as uint16_t to save space. FreeRTOS_mss() + * will often be used in signed native-size expressions cast it to + * BaseType_t. */ + xReturn = ( BaseType_t ) ( pxSocket->u.xTCP.usCurMSS ); + } + + return xReturn; + } + + +#endif /* ipconfigUSE_TCP */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_TCP == 1 ) + +/** + * @brief Get the connection status. The values correspond to the members + * of the enum 'eIPTCPState_t'. + * + * @param[in] xSocket: Socket to get the connection status from. + * + * @return The connection status or an error code. + * + * @note For internal use only. + */ + BaseType_t FreeRTOS_connstatus( ConstSocket_t xSocket ) + { + const FreeRTOS_Socket_t * pxSocket = ( const FreeRTOS_Socket_t * ) xSocket; + BaseType_t xReturn; + + if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP ) + { + xReturn = -pdFREERTOS_ERRNO_EINVAL; + } + else + { + /* Cast it to BaseType_t. */ + xReturn = ( BaseType_t ) ( pxSocket->u.xTCP.ucTCPState ); + } + + return xReturn; + } + + +#endif /* ipconfigUSE_TCP */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigUSE_TCP == 1 ) + +/** + * @brief Returns the number of bytes which can be read from the RX stream buffer. + * + * @param[in] xSocket: the socket to get the number of bytes from. + * + * @return Returns the number of bytes which can be read. Or an error + * code is returned. + */ + BaseType_t FreeRTOS_rx_size( ConstSocket_t xSocket ) + { + const FreeRTOS_Socket_t * pxSocket = ( const FreeRTOS_Socket_t * ) xSocket; + BaseType_t xReturn; + + if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP ) + { + xReturn = -pdFREERTOS_ERRNO_EINVAL; + } + else if( pxSocket->u.xTCP.rxStream != NULL ) + { + xReturn = ( BaseType_t ) uxStreamBufferGetSize( pxSocket->u.xTCP.rxStream ); + } + else + { + xReturn = 0; + } + + return xReturn; + } + + +#endif /* ipconfigUSE_TCP */ +/*-----------------------------------------------------------*/ + +#if 0 + +/** + * @brief Returns the number of packets that are stored in a UDP socket. + * + * @param[in] xSocket: the socket to get the number of bytes from. + * + * @return Returns the number of packets that are stored. Use FreeRTOS_recvfrom() + * to retrieve those packets. + */ + BaseType_t FreeRTOS_udp_rx_size( Socket_t xSocket ) + { + BaseType_t xReturn = 0; + const FreeRTOS_Socket_t * pxSocket = ( const FreeRTOS_Socket_t * ) xSocket; + + if( pxSocket->ucProtocol == ( uint8_t ) FREERTOS_IPPROTO_UDP ) + { + xReturn = ( BaseType_t ) listCURRENT_LIST_LENGTH( &( pxSocket->u.xUDP.xWaitingPacketsList ) ); + } + else + { + xReturn = -pdFREERTOS_ERRNO_EINVAL; + } + + return xReturn; + } +#endif /* 0 */ + +#if ( ipconfigUSE_TCP == 1 ) + +/** + * @brief Get the net status. The IP-task will print a summary of all sockets and + * their connections. + */ + void FreeRTOS_netstat( void ) + { + IPStackEvent_t xAskEvent; + + /* Ask the IP-task to call vTCPNetStat() + * to avoid accessing xBoundTCPSocketsList + */ + xAskEvent.eEventType = eTCPNetStat; + xAskEvent.pvData = ( void * ) NULL; + ( void ) xSendEventStructToIPTask( &xAskEvent, pdMS_TO_TICKS( 1000U ) ); + } + +#endif /* ipconfigUSE_TCP */ +/*-----------------------------------------------------------*/ + +#if ( ( ipconfigHAS_PRINTF != 0 ) && ( ipconfigUSE_TCP == 1 ) ) + +/** + * @brief Print a summary of all sockets and their connections. + */ + void vTCPNetStat( void ) + { + /* Show a simple listing of all created sockets and their connections */ + const ListItem_t * pxIterator; + BaseType_t count = 0; + size_t uxMinimum = uxGetMinimumFreeNetworkBuffers(); + size_t uxCurrent = uxGetNumberOfFreeNetworkBuffers(); + + if( !listLIST_IS_INITIALISED( &xBoundTCPSocketsList ) ) + { + FreeRTOS_printf( ( "PLUS-TCP not initialized\n" ) ); + } + else + { + const ListItem_t * pxEndTCP = listGET_END_MARKER( &xBoundTCPSocketsList ); + const ListItem_t * pxEndUDP = listGET_END_MARKER( &xBoundUDPSocketsList ); + FreeRTOS_printf( ( "Prot Port IP-Remote : Port R/T Status Alive tmout Child\n" ) ); + + for( pxIterator = listGET_HEAD_ENTRY( &xBoundTCPSocketsList ); + pxIterator != pxEndTCP; + pxIterator = listGET_NEXT( pxIterator ) ) + { + const FreeRTOS_Socket_t * pxSocket = ipCAST_CONST_PTR_TO_CONST_TYPE_PTR( FreeRTOS_Socket_t, listGET_LIST_ITEM_OWNER( pxIterator ) ); + #if ( ipconfigTCP_KEEP_ALIVE == 1 ) + TickType_t age = xTaskGetTickCount() - pxSocket->u.xTCP.xLastAliveTime; + #else + TickType_t age = 0U; + #endif + + char ucChildText[ 16 ] = ""; + + if( pxSocket->u.xTCP.ucTCPState == ( uint8_t ) eTCP_LISTEN ) + { + /* Using function "snprintf". */ + const int32_t copied_len = snprintf( ucChildText, sizeof( ucChildText ), " %d/%d", + ( int32_t ) pxSocket->u.xTCP.usChildCount, + ( int32_t ) pxSocket->u.xTCP.usBacklog ); + ( void ) copied_len; + /* These should never evaluate to false since the buffers are both shorter than 5-6 characters (<=65535) */ + configASSERT( copied_len >= 0 ); + configASSERT( copied_len < ( int32_t ) sizeof( ucChildText ) ); + } + + FreeRTOS_printf( ( "TCP %5d %-16lxip:%5d %d/%d %-13.13s %6lu %6u%s\n", + pxSocket->usLocalPort, /* Local port on this machine */ + pxSocket->u.xTCP.ulRemoteIP, /* IP address of remote machine */ + pxSocket->u.xTCP.usRemotePort, /* Port on remote machine */ + ( pxSocket->u.xTCP.rxStream != NULL ) ? 1 : 0, + ( pxSocket->u.xTCP.txStream != NULL ) ? 1 : 0, + FreeRTOS_GetTCPStateName( pxSocket->u.xTCP.ucTCPState ), + ( age > 999999u ) ? 999999u : age, /* Format 'age' for printing */ + pxSocket->u.xTCP.usTimeout, + ucChildText ) ); + count++; + } + + for( pxIterator = listGET_HEAD_ENTRY( &xBoundUDPSocketsList ); + pxIterator != pxEndUDP; + pxIterator = listGET_NEXT( pxIterator ) ) + { + /* Local port on this machine */ + FreeRTOS_printf( ( "UDP Port %5u\n", + FreeRTOS_ntohs( listGET_LIST_ITEM_VALUE( pxIterator ) ) ) ); + count++; + } + + FreeRTOS_printf( ( "FreeRTOS_netstat: %lu sockets %lu < %lu < %ld buffers free\n", + ( UBaseType_t ) count, + ( UBaseType_t ) uxMinimum, + ( UBaseType_t ) uxCurrent, + ( BaseType_t ) ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS ) ); + } + } + +#endif /* ( ( ipconfigHAS_PRINTF != 0 ) && ( ipconfigUSE_TCP == 1 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 ) + +/** + * @brief This internal non-blocking function will check all sockets that belong + * to a select set. The events bits of each socket will be updated, and it + * will check if an ongoing select() call must be interrupted because of an + * event has occurred. + * + * @param[in] pxSocketSet: The socket-set which is to be waited on for change. + */ + void vSocketSelect( SocketSelect_t * pxSocketSet ) + { + BaseType_t xRound; + EventBits_t xSocketBits, xBitsToClear; + + #if ipconfigUSE_TCP == 1 + BaseType_t xLastRound = 1; + #else + BaseType_t xLastRound = 0; + #endif + + /* These flags will be switched on after checking the socket status. */ + EventBits_t xGroupBits = 0; + + for( xRound = 0; xRound <= xLastRound; xRound++ ) + { + const ListItem_t * pxIterator; + const ListItem_t * pxEnd; + + if( xRound == 0 ) + { + pxEnd = listGET_END_MARKER( &xBoundUDPSocketsList ); + } + + #if ipconfigUSE_TCP == 1 + else + { + pxEnd = listGET_END_MARKER( &xBoundTCPSocketsList ); + } + #endif /* ipconfigUSE_TCP == 1 */ + + for( pxIterator = listGET_NEXT( pxEnd ); + pxIterator != pxEnd; + pxIterator = listGET_NEXT( pxIterator ) ) + { + FreeRTOS_Socket_t * pxSocket = ipCAST_PTR_TO_TYPE_PTR( FreeRTOS_Socket_t, listGET_LIST_ITEM_OWNER( pxIterator ) ); + + if( pxSocket->pxSocketSet != pxSocketSet ) + { + /* Socket does not belong to this select group. */ + continue; + } + + xSocketBits = 0; + + #if ( ipconfigUSE_TCP == 1 ) + if( pxSocket->ucProtocol == ( uint8_t ) FREERTOS_IPPROTO_TCP ) + { + /* Check if the socket has already been accepted by the + * owner. If not, it is useless to return it from a + * select(). */ + BaseType_t bAccepted = pdFALSE; + + if( pxSocket->u.xTCP.bits.bPassQueued == pdFALSE_UNSIGNED ) + { + if( pxSocket->u.xTCP.bits.bPassAccept == pdFALSE_UNSIGNED ) + { + bAccepted = pdTRUE; + } + } + + /* Is the set owner interested in READ events? */ + if( ( pxSocket->xSelectBits & ( EventBits_t ) eSELECT_READ ) != ( EventBits_t ) 0U ) + { + if( pxSocket->u.xTCP.ucTCPState == ( uint8_t ) eTCP_LISTEN ) + { + if( ( pxSocket->u.xTCP.pxPeerSocket != NULL ) && ( pxSocket->u.xTCP.pxPeerSocket->u.xTCP.bits.bPassAccept != pdFALSE_UNSIGNED ) ) + { + xSocketBits |= ( EventBits_t ) eSELECT_READ; + } + } + else if( ( pxSocket->u.xTCP.bits.bReuseSocket != pdFALSE_UNSIGNED ) && ( pxSocket->u.xTCP.bits.bPassAccept != pdFALSE_UNSIGNED ) ) + { + /* This socket has the re-use flag. After connecting it turns into + * a connected socket. Set the READ event, so that accept() will be called. */ + xSocketBits |= ( EventBits_t ) eSELECT_READ; + } + else if( ( bAccepted != 0 ) && ( FreeRTOS_recvcount( pxSocket ) > 0 ) ) + { + xSocketBits |= ( EventBits_t ) eSELECT_READ; + } + else + { + /* Nothing. */ + } + } + + /* Is the set owner interested in EXCEPTION events? */ + if( ( pxSocket->xSelectBits & ( EventBits_t ) eSELECT_EXCEPT ) != 0U ) + { + if( ( pxSocket->u.xTCP.ucTCPState == ( uint8_t ) eCLOSE_WAIT ) || ( pxSocket->u.xTCP.ucTCPState == ( uint8_t ) eCLOSED ) ) + { + xSocketBits |= ( EventBits_t ) eSELECT_EXCEPT; + } + } + + /* Is the set owner interested in WRITE events? */ + if( ( pxSocket->xSelectBits & ( EventBits_t ) eSELECT_WRITE ) != 0U ) + { + BaseType_t bMatch = pdFALSE; + + if( bAccepted != 0 ) + { + if( FreeRTOS_tx_space( pxSocket ) > 0 ) + { + bMatch = pdTRUE; + } + } + + if( bMatch == pdFALSE ) + { + if( ( pxSocket->u.xTCP.bits.bConnPrepared != pdFALSE_UNSIGNED ) && + ( pxSocket->u.xTCP.ucTCPState >= ( uint8_t ) eESTABLISHED ) && + ( pxSocket->u.xTCP.bits.bConnPassed == pdFALSE_UNSIGNED ) ) + { + pxSocket->u.xTCP.bits.bConnPassed = pdTRUE; + bMatch = pdTRUE; + } + } + + if( bMatch != pdFALSE ) + { + xSocketBits |= ( EventBits_t ) eSELECT_WRITE; + } + } + } + else + #endif /* ipconfigUSE_TCP == 1 */ + { + /* Select events for UDP are simpler. */ + if( ( ( pxSocket->xSelectBits & ( EventBits_t ) eSELECT_READ ) != 0U ) && + ( listCURRENT_LIST_LENGTH( &( pxSocket->u.xUDP.xWaitingPacketsList ) ) > 0U ) ) + { + xSocketBits |= ( EventBits_t ) eSELECT_READ; + } + + /* The WRITE and EXCEPT bits are not used for UDP */ + } /* if( pxSocket->ucProtocol == FREERTOS_IPPROTO_TCP ) */ + + /* Each socket keeps its own event flags, which are looked-up + * by FreeRTOS_FD_ISSSET() */ + pxSocket->xSocketBits = xSocketBits; + + /* The ORed value will be used to set the bits in the event + * group. */ + xGroupBits |= xSocketBits; + } /* for( pxIterator ... ) */ + } /* for( xRound = 0; xRound <= xLastRound; xRound++ ) */ + + xBitsToClear = xEventGroupGetBits( pxSocketSet->xSelectGroup ); + + /* Now set the necessary bits. */ + xBitsToClear = ( xBitsToClear & ~xGroupBits ) & ( ( EventBits_t ) eSELECT_ALL ); + + #if ( ipconfigSUPPORT_SIGNALS != 0 ) + { + /* Maybe the socketset was signalled, but don't + * clear the 'eSELECT_INTR' bit here, as it will be used + * and cleared in FreeRTOS_select(). */ + xBitsToClear &= ~( ( EventBits_t ) eSELECT_INTR ); + } + #endif /* ipconfigSUPPORT_SIGNALS */ + + if( xBitsToClear != 0U ) + { + ( void ) xEventGroupClearBits( pxSocketSet->xSelectGroup, xBitsToClear ); + } + + /* Now include eSELECT_CALL_IP to wakeup the caller. */ + ( void ) xEventGroupSetBits( pxSocketSet->xSelectGroup, xGroupBits | ( EventBits_t ) eSELECT_CALL_IP ); + } + + +#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigSUPPORT_SIGNALS != 0 ) + +/** + * @brief Send a signal to the task which reads from this socket. + * The socket will receive an event of the type 'eSOCKET_INTR'. + * Any ongoing blocking API ( e.g. FreeRTOS_recv() ) will be terminated + * and return the value -pdFREERTOS_ERRNO_EINTR ( -4 ). + * + * @param[in] xSocket: The socket that will be signalled. + */ + BaseType_t FreeRTOS_SignalSocket( Socket_t xSocket ) + { + FreeRTOS_Socket_t * pxSocket = ( FreeRTOS_Socket_t * ) xSocket; + BaseType_t xReturn; + + if( pxSocket == NULL ) + { + xReturn = -pdFREERTOS_ERRNO_EINVAL; + } + else + #if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 ) + if( ( pxSocket->pxSocketSet != NULL ) && ( pxSocket->pxSocketSet->xSelectGroup != NULL ) ) + { + ( void ) xEventGroupSetBits( pxSocket->pxSocketSet->xSelectGroup, ( EventBits_t ) eSELECT_INTR ); + xReturn = 0; + } + else + #endif /* ipconfigSUPPORT_SELECT_FUNCTION */ + if( pxSocket->xEventGroup != NULL ) + { + ( void ) xEventGroupSetBits( pxSocket->xEventGroup, ( EventBits_t ) eSOCKET_INTR ); + xReturn = 0; + } + else + { + xReturn = -pdFREERTOS_ERRNO_EINVAL; + } + + return xReturn; + } + +#endif /* ipconfigSUPPORT_SIGNALS */ +/*-----------------------------------------------------------*/ + +#if ( ipconfigSUPPORT_SIGNALS != 0 ) + +/** + * @brief The same as 'FreeRTOS_SignalSocket()', except that this function should + * be called from an ISR context. + * + * @param[in] xSocket: The socket that will be signalled. + * @param[in,out] pxHigherPriorityTaskWoken: will be set to non-zero in case a higher- + * priority task has become runnable. + */ + BaseType_t FreeRTOS_SignalSocketFromISR( Socket_t xSocket, + BaseType_t * pxHigherPriorityTaskWoken ) + { + FreeRTOS_Socket_t * pxSocket = ( FreeRTOS_Socket_t * ) xSocket; + BaseType_t xReturn; + IPStackEvent_t xEvent; + + configASSERT( pxSocket != NULL ); + configASSERT( pxSocket->ucProtocol == ( uint8_t ) FREERTOS_IPPROTO_TCP ); + configASSERT( pxSocket->xEventGroup != NULL ); + + xEvent.eEventType = eSocketSignalEvent; + xEvent.pvData = pxSocket; + + /* The IP-task will call FreeRTOS_SignalSocket for this socket. */ + xReturn = xQueueSendToBackFromISR( xNetworkEventQueue, &xEvent, pxHigherPriorityTaskWoken ); + + return xReturn; + } + +#endif /* ipconfigSUPPORT_SIGNALS */ +/*-----------------------------------------------------------*/ + +#if 0 + #if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 ) + struct pollfd + { + Socket_t fd; /* file descriptor */ + EventBits_t events; /* requested events */ + EventBits_t revents; /* returned events */ + }; + + typedef BaseType_t nfds_t; + + BaseType_t poll( struct pollfd * fds, + nfds_t nfds, + BaseType_t timeout ); + BaseType_t poll( struct pollfd * fds, + nfds_t nfds, + BaseType_t timeout ) + { + BaseType_t index; + SocketSelect_t * pxSocketSet = NULL; + BaseType_t xReturn = 0; + + /* See which socket-sets have been created and bound to the sockets involved. */ + for( index = 0; index < nfds; index++ ) + { + FreeRTOS_Socket_t * pxSocket = ( FreeRTOS_Socket_t * ) fds[ index ].fd; + + if( pxSocket->pxSocketSet != NULL ) + { + if( pxSocketSet == NULL ) + { + /* Use this socket-set. */ + pxSocketSet = pxSocket->pxSocketSet; + xReturn = 1; + } + else if( pxSocketSet == pxSocket->pxSocketSet ) + { + /* Good: associated with the same socket-set. */ + } + else + { + /* More than one socket-set is found: can not do a select on 2 sets. */ + xReturn = -1; + break; + } + } + } + + if( xReturn == 0 ) + { + /* Create a new socket-set, and attach all sockets to it. */ + pxSocketSet = FreeRTOS_CreateSocketSet(); + + if( pxSocketSet != NULL ) + { + xReturn = 1; + } + else + { + xReturn = -2; + } + + /* Memory leak: when the last socket closes, there is no more reference to + * this socket-set. It should be marked as an automatic or anonymous socket-set, + * so when closing the last member, its memory will be freed. */ + } + + if( xReturn > 0 ) + { + /* Only one socket-set is found. Connect all sockets to this socket-set. */ + for( index = 0; index < nfds; index++ ) + { + FreeRTOS_Socket_t * pxSocket = ( FreeRTOS_Socket_t * ) fds[ index ].fd; + EventBits_t xEventBits = fds[ index ].events; + + FreeRTOS_FD_SET( pxSocket, pxSocketSet, xEventBits ); + FreeRTOS_FD_CLR( pxSocket, pxSocketSet, ( EventBits_t ) ~xEventBits ); + } + + /* And sleep until an event happens or a time-out. */ + xReturn = FreeRTOS_select( pxSocketSet, timeout ); + + /* Now set the return events, copying from the socked field 'xSocketBits'. */ + for( index = 0; index < nfds; index++ ) + { + FreeRTOS_Socket_t * pxSocket = ( FreeRTOS_Socket_t * ) fds[ index ].fd; + + fds[ index ].revents = pxSocket->xSocketBits & ( ( EventBits_t ) eSELECT_ALL ); + } + } + else + { + /* -1: Sockets are connected to different socket sets. */ + /* -2: FreeRTOS_CreateSocketSet() failed. */ + } + + return xReturn; + } + + #endif /* ipconfigSUPPORT_SELECT_FUNCTION */ +#endif /* 0 */ diff --git a/examples/stm32/freertos-tcp/FreeRTOS_Stream_Buffer.c b/examples/stm32/freertos-tcp/FreeRTOS_Stream_Buffer.c new file mode 100644 index 00000000..c824c4fd --- /dev/null +++ b/examples/stm32/freertos-tcp/FreeRTOS_Stream_Buffer.c @@ -0,0 +1,225 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +/** + * @file FreeRTOS_Stream_Buffer.c + * @brief Provides the API for managing/creating the stream buffers in the FreeRTOS+TCP network stack. + */ + +/* Standard includes. */ +#include + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "semphr.h" + +/* FreeRTOS+TCP includes. */ +#include "FreeRTOS_UDP_IP.h" +#include "FreeRTOS_IP.h" +#include "FreeRTOS_Sockets.h" +#include "FreeRTOS_IP_Private.h" + + +/** + * @brief Adds data to a stream buffer. + * + * @param[in,out] pxBuffer: The buffer to which the bytes will be added. + * @param[in] uxOffset: If uxOffset > 0, data will be written at an offset from uxHead + * while uxHead will not be moved yet. + * @param[in] pucData: A pointer to the data to be added. + * @param[in] uxByteCount: The number of bytes to add. + * + * @return The number of bytes added to the buffer. + */ +size_t uxStreamBufferAdd( StreamBuffer_t * pxBuffer, + size_t uxOffset, + const uint8_t * pucData, + size_t uxByteCount ) +{ + size_t uxSpace, uxNextHead, uxFirst; + size_t uxCount = uxByteCount; + + uxSpace = uxStreamBufferGetSpace( pxBuffer ); + + /* If uxOffset > 0, items can be placed in front of uxHead */ + if( uxSpace > uxOffset ) + { + uxSpace -= uxOffset; + } + else + { + uxSpace = 0U; + } + + /* The number of bytes that can be written is the minimum of the number of + * bytes requested and the number available. */ + uxCount = FreeRTOS_min_uint32( uxSpace, uxCount ); + + if( uxCount != 0U ) + { + uxNextHead = pxBuffer->uxHead; + + if( uxOffset != 0U ) + { + /* ( uxOffset > 0 ) means: write in front if the uxHead marker */ + uxNextHead += uxOffset; + + if( uxNextHead >= pxBuffer->LENGTH ) + { + uxNextHead -= pxBuffer->LENGTH; + } + } + + if( pucData != NULL ) + { + /* 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. */ + uxFirst = FreeRTOS_min_uint32( pxBuffer->LENGTH - uxNextHead, uxCount ); + + /* Write as many bytes as can be written in the first write. */ + ( void ) memcpy( &( pxBuffer->ucArray[ uxNextHead ] ), pucData, uxFirst ); + + /* If the number of bytes written was less than the number that + * could be written in the first write... */ + if( uxCount > uxFirst ) + { + /* ...then write the remaining bytes to the start of the + * buffer. */ + ( void ) memcpy( pxBuffer->ucArray, &( pucData[ uxFirst ] ), uxCount - uxFirst ); + } + } + + if( uxOffset == 0U ) + { + /* ( uxOffset == 0 ) means: write at uxHead position */ + uxNextHead += uxCount; + + if( uxNextHead >= pxBuffer->LENGTH ) + { + uxNextHead -= pxBuffer->LENGTH; + } + + pxBuffer->uxHead = uxNextHead; + } + + if( xStreamBufferLessThenEqual( pxBuffer, pxBuffer->uxFront, uxNextHead ) != pdFALSE ) + { + /* Advance the front pointer */ + pxBuffer->uxFront = uxNextHead; + } + } + + return uxCount; +} +/*-----------------------------------------------------------*/ + +/** + * @brief Read bytes from stream buffer. + * + * @param[in] pxBuffer: The buffer from which the bytes will be read. + * @param[in] uxOffset: can be used to read data located at a certain offset from 'lTail'. + * @param[in,out] pucData: If 'pucData' equals NULL, the function is called to advance 'lTail' only. + * @param[in] uxMaxCount: The number of bytes to read. + * @param[in] xPeek: if 'xPeek' is pdTRUE, or if 'uxOffset' is non-zero, the 'lTail' pointer will + * not be advanced. + * + * @return The count of the bytes read. + */ +size_t uxStreamBufferGet( StreamBuffer_t * pxBuffer, + size_t uxOffset, + uint8_t * pucData, + size_t uxMaxCount, + BaseType_t xPeek ) +{ + size_t uxSize, uxCount, uxFirst, uxNextTail; + + /* How much data is available? */ + uxSize = uxStreamBufferGetSize( pxBuffer ); + + if( uxSize > uxOffset ) + { + uxSize -= uxOffset; + } + else + { + uxSize = 0U; + } + + /* Use the minimum of the wanted bytes and the available bytes. */ + uxCount = FreeRTOS_min_uint32( uxSize, uxMaxCount ); + + if( uxCount > 0U ) + { + uxNextTail = pxBuffer->uxTail; + + if( uxOffset != 0U ) + { + uxNextTail += uxOffset; + + if( uxNextTail >= pxBuffer->LENGTH ) + { + uxNextTail -= pxBuffer->LENGTH; + } + } + + if( pucData != NULL ) + { + /* 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. */ + uxFirst = FreeRTOS_min_uint32( pxBuffer->LENGTH - uxNextTail, uxCount ); + + /* Obtain the number of bytes it is possible to obtain in the first + * read. */ + ( void ) memcpy( pucData, &( pxBuffer->ucArray[ uxNextTail ] ), uxFirst ); + + /* If the total number of wanted bytes is greater than the number + * that could be read in the first read... */ + if( uxCount > uxFirst ) + { + /*...then read the remaining bytes from the start of the buffer. */ + ( void ) memcpy( &( pucData[ uxFirst ] ), pxBuffer->ucArray, uxCount - uxFirst ); + } + } + + if( ( xPeek == pdFALSE ) && ( uxOffset == 0UL ) ) + { + /* Move the tail pointer to effectively remove the data read from + * the buffer. */ + uxNextTail += uxCount; + + if( uxNextTail >= pxBuffer->LENGTH ) + { + uxNextTail -= pxBuffer->LENGTH; + } + + pxBuffer->uxTail = uxNextTail; + } + } + + return uxCount; +} diff --git a/examples/stm32/freertos-tcp/FreeRTOS_TCP_IP.c b/examples/stm32/freertos-tcp/FreeRTOS_TCP_IP.c new file mode 100644 index 00000000..314d2b24 --- /dev/null +++ b/examples/stm32/freertos-tcp/FreeRTOS_TCP_IP.c @@ -0,0 +1,3980 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +/** + * @file FreeRTOS_TCP_IP.c + * @brief Module which handles the TCP connections for FreeRTOS+TCP. + * It depends on FreeRTOS_TCP_WIN.c, which handles the TCP windowing + * schemes. + * + * Endianness: in this module all ports and IP addresses are stored in + * host byte-order, except fields in the IP-packets + */ + +/* Standard includes. */ +#include +#include + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" +#include "semphr.h" + +/* FreeRTOS+TCP includes. */ +#include "FreeRTOS_IP.h" +#include "FreeRTOS_Sockets.h" +#include "FreeRTOS_IP_Private.h" +#include "FreeRTOS_UDP_IP.h" +#include "FreeRTOS_DHCP.h" +#include "NetworkInterface.h" +#include "NetworkBufferManagement.h" +#include "FreeRTOS_ARP.h" + + +/* Just make sure the contents doesn't get compiled if TCP is not enabled. */ +#if ipconfigUSE_TCP == 1 + +/*lint -e750 local macro not referenced [MISRA 2012 Rule 2.5, advisory] */ + +/* + * The meaning of the TCP flags: + */ + #define tcpTCP_FLAG_FIN ( ( uint8_t ) 0x01U ) /**< No more data from sender. */ + #define tcpTCP_FLAG_SYN ( ( uint8_t ) 0x02U ) /**< Synchronize sequence numbers. */ + #define tcpTCP_FLAG_RST ( ( uint8_t ) 0x04U ) /**< Reset the connection. */ + #define tcpTCP_FLAG_PSH ( ( uint8_t ) 0x08U ) /**< Push function: please push buffered data to the recv application. */ + #define tcpTCP_FLAG_ACK ( ( uint8_t ) 0x10U ) /**< Acknowledgment field is significant. */ + #define tcpTCP_FLAG_URG ( ( uint8_t ) 0x20U ) /**< Urgent pointer field is significant. */ + #define tcpTCP_FLAG_ECN ( ( uint8_t ) 0x40U ) /**< ECN-Echo. */ + #define tcpTCP_FLAG_CWR ( ( uint8_t ) 0x80U ) /**< Congestion Window Reduced. */ + + #define tcpTCP_FLAG_CTRL ( ( uint8_t ) 0x1FU ) /**< A mask to filter all protocol flags. */ + + +/* + * A few values of the TCP options: + */ + #define tcpTCP_OPT_END 0U /**< End of TCP options list. */ + #define tcpTCP_OPT_NOOP 1U /**< "No-operation" TCP option. */ + #define tcpTCP_OPT_MSS 2U /**< Maximum segment size TCP option. */ + #define tcpTCP_OPT_WSOPT 3U /**< TCP Window Scale Option (3-byte long). */ + #define tcpTCP_OPT_SACK_P 4U /**< Advertise that SACK is permitted. */ + #define tcpTCP_OPT_SACK_A 5U /**< SACK option with first/last. */ + #define tcpTCP_OPT_TIMESTAMP 8U /**< Time-stamp option. */ + + + #define tcpTCP_OPT_MSS_LEN 4U /**< Length of TCP MSS option. */ + #define tcpTCP_OPT_WSOPT_LEN 3U /**< Length of TCP WSOPT option. */ + + #define tcpTCP_OPT_TIMESTAMP_LEN 10 /**< fixed length of the time-stamp option. */ + + #ifndef ipconfigTCP_ACK_EARLIER_PACKET + #define ipconfigTCP_ACK_EARLIER_PACKET 1 /**< Acknowledge an earlier packet. */ + #endif + + +/** @brief + * The macro tcpNOW_CONNECTED() is use to determine if the connection makes a + * transition from connected to non-connected and vice versa. + * tcpNOW_CONNECTED() returns true when the status has one of these values: + * eESTABLISHED, eFIN_WAIT_1, eFIN_WAIT_2, eCLOSING, eLAST_ACK, eTIME_WAIT + * Technically the connection status is closed earlier, but the library wants + * to prevent that the socket will be deleted before the last ACK has been + * and thus causing a 'RST' packet on either side. + */ + #define tcpNOW_CONNECTED( status ) \ + ( ( ( ( status ) >= ( BaseType_t ) eESTABLISHED ) && ( ( status ) != ( BaseType_t ) eCLOSE_WAIT ) ) ? 1 : 0 ) + +/** @brief + * The highest 4 bits in the TCP offset byte indicate the total length of the + * TCP header, divided by 4. + */ + #define tcpVALID_BITS_IN_TCP_OFFSET_BYTE ( 0xF0U ) + +/* + * Acknowledgements to TCP data packets may be delayed as long as more is being expected. + * A normal delay would be 200ms. Here a much shorter delay of 20 ms is being used to + * gain performance. + */ + #define tcpDELAYED_ACK_SHORT_DELAY_MS ( 2 ) /**< Should not become smaller than 1. */ + #define tcpDELAYED_ACK_LONGER_DELAY_MS ( 20 ) /**< Longer delay for ACK. */ + + +/** @brief + * The MSS (Maximum Segment Size) will be taken as large as possible. However, packets with + * an MSS of 1460 bytes won't be transported through the internet. The MSS will be reduced + * to 1400 bytes. + */ + #define tcpREDUCED_MSS_THROUGH_INTERNET ( 1400 ) + +/** @brief + * When there are no TCP options, the TCP offset equals 20 bytes, which is stored as + * the number 5 (words) in the higher nibble of the TCP-offset byte. + */ + #define tcpTCP_OFFSET_LENGTH_BITS ( 0xf0U ) + #define tcpTCP_OFFSET_STANDARD_LENGTH ( 0x50U ) /**< Standard TCP packet offset. */ + + +/** @brief + * Each TCP socket is checked regularly to see if it can send data packets. + * By default, the maximum number of packets sent during one check is limited to 8. + * This amount may be further limited by setting the socket's TX window size. + */ + #if ( !defined( SEND_REPEATED_COUNT ) ) + #define SEND_REPEATED_COUNT ( 8 ) + #endif /* !defined( SEND_REPEATED_COUNT ) */ + +/** @brief + * Define a maximum period of time (ms) to leave a TCP-socket unattended. + * When a TCP timer expires, retries and keep-alive messages will be checked. + */ + #ifndef tcpMAXIMUM_TCP_WAKEUP_TIME_MS + #define tcpMAXIMUM_TCP_WAKEUP_TIME_MS 20000U + #endif + +/* Two macro's that were introduced to work with both IPv4 and IPv6. */ + #define xIPHeaderSize( pxNetworkBuffer ) ( ipSIZE_OF_IPv4_HEADER ) /**< Size of IP Header. */ + #define uxIPHeaderSizeSocket( pxSocket ) ( ipSIZE_OF_IPv4_HEADER ) /**< Size of IP Header socket. */ + + +/* + * Returns true if the socket must be checked. Non-active sockets are waiting + * for user action, either connect() or close(). + */ + static BaseType_t prvTCPSocketIsActive( eIPTCPState_t xStatus ); + +/* + * Either sends a SYN or calls prvTCPSendRepeated (for regular messages). + */ + static int32_t prvTCPSendPacket( FreeRTOS_Socket_t * pxSocket ); + +/* + * Try to send a series of messages. + */ + static int32_t prvTCPSendRepeated( FreeRTOS_Socket_t * pxSocket, + NetworkBufferDescriptor_t ** ppxNetworkBuffer ); + +/* + * Return or send a packet to the other party. + */ + static void prvTCPReturnPacket( FreeRTOS_Socket_t * pxSocket, + NetworkBufferDescriptor_t * pxDescriptor, + uint32_t ulLen, + BaseType_t xReleaseAfterSend ); + +/* + * Initialise the data structures which keep track of the TCP windowing system. + */ + static void prvTCPCreateWindow( FreeRTOS_Socket_t * pxSocket ); + +/* + * Let ARP look-up the MAC-address of the peer and initialise the first SYN + * packet. + */ + static BaseType_t prvTCPPrepareConnect( FreeRTOS_Socket_t * pxSocket ); + + #if ( ipconfigHAS_DEBUG_PRINTF != 0 ) + +/* + * For logging and debugging: make a string showing the TCP flags. + */ + static const char * prvTCPFlagMeaning( UBaseType_t xFlags ); + #endif /* ipconfigHAS_DEBUG_PRINTF != 0 */ + +/* + * Parse the TCP option(s) received, if present. + */ + _static void prvCheckOptions( FreeRTOS_Socket_t * pxSocket, + const NetworkBufferDescriptor_t * pxNetworkBuffer ); + +/* + * Identify and deal with a single TCP header option, advancing the pointer to + * the header. This function returns pdTRUE or pdFALSE depending on whether the + * caller should continue to parse more header options or break the loop. + */ + _static size_t prvSingleStepTCPHeaderOptions( const uint8_t * const pucPtr, + size_t uxTotalLength, + FreeRTOS_Socket_t * const pxSocket, + BaseType_t xHasSYNFlag ); + + #if ( ipconfigUSE_TCP_WIN == 1 ) + +/* + * Skip past TCP header options when doing Selective ACK, until there are no + * more options left. + */ + _static void prvReadSackOption( const uint8_t * const pucPtr, + size_t uxIndex, + FreeRTOS_Socket_t * const pxSocket ); + #endif /* ( ipconfigUSE_TCP_WIN == 1 ) */ + + +/* + * Set the initial properties in the options fields, like the preferred + * value of MSS and whether SACK allowed. Will be transmitted in the state + * 'eCONNECT_SYN'. + */ + static UBaseType_t prvSetSynAckOptions( FreeRTOS_Socket_t * pxSocket, + TCPHeader_t * pxTCPHeader ); + +/* + * For anti-hang protection and TCP keep-alive messages. Called in two places: + * after receiving a packet and after a state change. The socket's alive timer + * may be reset. + */ + static void prvTCPTouchSocket( FreeRTOS_Socket_t * pxSocket ); + +/* + * Prepare an outgoing message, if anything has to be sent. + */ + static int32_t prvTCPPrepareSend( FreeRTOS_Socket_t * pxSocket, + NetworkBufferDescriptor_t ** ppxNetworkBuffer, + UBaseType_t uxOptionsLength ); + +/* + * Calculate when this socket needs to be checked to do (re-)transmissions. + */ + static TickType_t prvTCPNextTimeout( FreeRTOS_Socket_t * pxSocket ); + +/* + * The API FreeRTOS_send() adds data to the TX stream. Add + * this data to the windowing system to it can be transmitted. + */ + static void prvTCPAddTxData( FreeRTOS_Socket_t * pxSocket ); + +/* + * Called to handle the closure of a TCP connection. + */ + static BaseType_t prvTCPHandleFin( FreeRTOS_Socket_t * pxSocket, + const NetworkBufferDescriptor_t * pxNetworkBuffer ); + +/* + * Called from prvTCPHandleState(). Find the TCP payload data and check and + * return its length. + */ + static BaseType_t prvCheckRxData( const NetworkBufferDescriptor_t * pxNetworkBuffer, + uint8_t ** ppucRecvData ); + +/* + * Called from prvTCPHandleState(). Check if the payload data may be accepted. + * If so, it will be added to the socket's reception queue. + */ + static BaseType_t prvStoreRxData( FreeRTOS_Socket_t * pxSocket, + const uint8_t * pucRecvData, + NetworkBufferDescriptor_t * pxNetworkBuffer, + uint32_t ulReceiveLength ); + +/* + * Set the TCP options (if any) for the outgoing packet. + */ + static UBaseType_t prvSetOptions( FreeRTOS_Socket_t * pxSocket, + const NetworkBufferDescriptor_t * pxNetworkBuffer ); + +/* + * Called from prvTCPHandleState() as long as the TCP status is eSYN_RECEIVED to + * eCONNECT_SYN. + */ + static BaseType_t prvHandleSynReceived( FreeRTOS_Socket_t * pxSocket, + const NetworkBufferDescriptor_t * pxNetworkBuffer, + uint32_t ulReceiveLength, + UBaseType_t uxOptionsLength ); + +/* + * Called from prvTCPHandleState() as long as the TCP status is eESTABLISHED. + */ + static BaseType_t prvHandleEstablished( FreeRTOS_Socket_t * pxSocket, + NetworkBufferDescriptor_t ** ppxNetworkBuffer, + uint32_t ulReceiveLength, + UBaseType_t uxOptionsLength ); + +/* + * Called from prvTCPHandleState(). There is data to be sent. + * If ipconfigUSE_TCP_WIN is defined, and if only an ACK must be sent, it will + * be checked if it would better be postponed for efficiency. + */ + static BaseType_t prvSendData( FreeRTOS_Socket_t * pxSocket, + NetworkBufferDescriptor_t ** ppxNetworkBuffer, + uint32_t ulReceiveLength, + BaseType_t xByteCount ); + +/* + * The heart of all: check incoming packet for valid data and acks and do what + * is necessary in each state. + */ + static BaseType_t prvTCPHandleState( FreeRTOS_Socket_t * pxSocket, + NetworkBufferDescriptor_t ** ppxNetworkBuffer ); + +/* + * Common code for sending a TCP protocol control packet (i.e. no options, no + * payload, just flags). + */ + static BaseType_t prvTCPSendSpecialPacketHelper( NetworkBufferDescriptor_t * pxNetworkBuffer, + uint8_t ucTCPFlags ); + +/* + * A "challenge ACK" is as per https://tools.ietf.org/html/rfc5961#section-3.2, + * case #3. In summary, an RST was received with a sequence number that is + * unexpected but still within the window. + */ + static BaseType_t prvTCPSendChallengeAck( NetworkBufferDescriptor_t * pxNetworkBuffer ); + +/* + * Reply to a peer with the RST flag on, in case a packet can not be handled. + */ + static BaseType_t prvTCPSendReset( NetworkBufferDescriptor_t * pxNetworkBuffer ); + +/* + * Set the initial value for MSS (Maximum Segment Size) to be used. + */ + static void prvSocketSetMSS( FreeRTOS_Socket_t * pxSocket ); + +/* + * Return either a newly created socket, or the current socket in a connected + * state (depends on the 'bReuseSocket' flag). + */ + static FreeRTOS_Socket_t * prvHandleListen( FreeRTOS_Socket_t * pxSocket, + NetworkBufferDescriptor_t * pxNetworkBuffer ); + +/* + * After a listening socket receives a new connection, it may duplicate itself. + * The copying takes place in prvTCPSocketCopy. + */ + static BaseType_t prvTCPSocketCopy( FreeRTOS_Socket_t * pxNewSocket, + FreeRTOS_Socket_t * pxSocket ); + +/* + * prvTCPStatusAgeCheck() will see if the socket has been in a non-connected + * state for too long. If so, the socket will be closed, and -1 will be + * returned. + */ + #if ( ipconfigTCP_HANG_PROTECTION == 1 ) + static BaseType_t prvTCPStatusAgeCheck( FreeRTOS_Socket_t * pxSocket ); + #endif + + static NetworkBufferDescriptor_t * prvTCPBufferResize( const FreeRTOS_Socket_t * pxSocket, + NetworkBufferDescriptor_t * pxNetworkBuffer, + int32_t lDataLen, + UBaseType_t uxOptionsLength ); + + #if ( ipconfigUSE_TCP_WIN != 0 ) + static uint8_t prvWinScaleFactor( const FreeRTOS_Socket_t * pxSocket ); + #endif + +/*-----------------------------------------------------------*/ + +/** + * @brief Check whether the socket is active or not. + * + * @param[in] xStatus: The status of the socket. + * + * @return pdTRUE if the socket must be checked. Non-active sockets + * are waiting for user action, either connect() or close(). + */ + static BaseType_t prvTCPSocketIsActive( eIPTCPState_t xStatus ) + { + BaseType_t xResult; + + switch( xStatus ) + { + case eCLOSED: + case eCLOSE_WAIT: + case eFIN_WAIT_2: + case eCLOSING: + case eTIME_WAIT: + xResult = pdFALSE; + break; + + case eTCP_LISTEN: + case eCONNECT_SYN: + case eSYN_FIRST: + case eSYN_RECEIVED: + case eESTABLISHED: + case eFIN_WAIT_1: + case eLAST_ACK: + default: + xResult = pdTRUE; + break; + } + + return xResult; + } + /*-----------------------------------------------------------*/ + + #if ( ipconfigTCP_HANG_PROTECTION == 1 ) + +/** + * @brief Some of the TCP states may only last a certain amount of time. + * This function checks if the socket is 'hanging', i.e. staying + * too long in the same state. + * + * @param[in] The socket to be checked. + * + * @return pdFALSE if no checks are needed, pdTRUE if checks were done, or negative + * in case the socket has reached a critical time-out. The socket will go to + * the eCLOSE_WAIT state. + */ + static BaseType_t prvTCPStatusAgeCheck( FreeRTOS_Socket_t * pxSocket ) + { + BaseType_t xResult; + eIPTCPState_t eState = ipNUMERIC_CAST( eIPTCPState_t, pxSocket->u.xTCP.ucTCPState ); + + switch( eState ) + { + case eESTABLISHED: + + /* If the 'ipconfigTCP_KEEP_ALIVE' option is enabled, sockets in + * state ESTABLISHED can be protected using keep-alive messages. */ + xResult = pdFALSE; + break; + + case eCLOSED: + case eTCP_LISTEN: + case eCLOSE_WAIT: + /* These 3 states may last for ever, up to the owner. */ + xResult = pdFALSE; + break; + + case eCONNECT_SYN: + case eSYN_FIRST: + case eSYN_RECEIVED: + case eFIN_WAIT_1: + case eFIN_WAIT_2: + case eCLOSING: + case eLAST_ACK: + case eTIME_WAIT: + default: + + /* All other (non-connected) states will get anti-hanging + * protection. */ + xResult = pdTRUE; + break; + } + + if( xResult != pdFALSE ) + { + /* How much time has past since the last active moment which is + * defined as A) a state change or B) a packet has arrived. */ + TickType_t xAge = xTaskGetTickCount() - pxSocket->u.xTCP.xLastActTime; + + /* ipconfigTCP_HANG_PROTECTION_TIME is in units of seconds. */ + if( xAge > ( ( TickType_t ) ipconfigTCP_HANG_PROTECTION_TIME * ( TickType_t ) configTICK_RATE_HZ ) ) + { + #if ( ipconfigHAS_DEBUG_PRINTF == 1 ) + { + FreeRTOS_debug_printf( ( "Inactive socket closed: port %u rem %lxip:%u status %s\n", + pxSocket->usLocalPort, + pxSocket->u.xTCP.ulRemoteIP, + pxSocket->u.xTCP.usRemotePort, + FreeRTOS_GetTCPStateName( ( UBaseType_t ) pxSocket->u.xTCP.ucTCPState ) ) ); + } + #endif /* ipconfigHAS_DEBUG_PRINTF */ + + /* Move to eCLOSE_WAIT, user may close the socket. */ + vTCPStateChange( pxSocket, eCLOSE_WAIT ); + + /* When 'bPassQueued' true, this socket is an orphan until it + * gets connected. */ + if( pxSocket->u.xTCP.bits.bPassQueued != pdFALSE_UNSIGNED ) + { + /* vTCPStateChange() has called FreeRTOS_closesocket() + * in case the socket is not yet owned by the application. + * Return a negative value to inform the caller that + * the socket will be closed in the next cycle. */ + xResult = -1; + } + } + } + + return xResult; + } + /*-----------------------------------------------------------*/ + + #endif /* if ( ipconfigTCP_HANG_PROTECTION == 1 ) */ + +/** + * @brief As soon as a TCP socket timer expires, this function will be called + * (from xTCPTimerCheck). It can send a delayed ACK or new data. + * + * @param[in] pxSocket: socket to be checked. + * + * @return 0 on success, a negative error code on failure. A negative value will be + * returned in case the hang-protection has put the socket in a wait-close state. + * + * @note Sequence of calling (normally) : + * IP-Task: + * xTCPTimerCheck() // Check all sockets ( declared in FreeRTOS_Sockets.c ) + * xTCPSocketCheck() // Either send a delayed ACK or call prvTCPSendPacket() + * prvTCPSendPacket() // Either send a SYN or call prvTCPSendRepeated ( regular messages ) + * prvTCPSendRepeated() // Send at most 8 messages on a row + * prvTCPReturnPacket() // Prepare for returning + * xNetworkInterfaceOutput() // Sends data to the NIC ( declared in portable/NetworkInterface/xxx ) + */ + BaseType_t xTCPSocketCheck( FreeRTOS_Socket_t * pxSocket ) + { + BaseType_t xResult = 0; + BaseType_t xReady = pdFALSE; + + if( ( pxSocket->u.xTCP.ucTCPState >= ( uint8_t ) eESTABLISHED ) && ( pxSocket->u.xTCP.txStream != NULL ) ) + { + /* The API FreeRTOS_send() might have added data to the TX stream. Add + * this data to the windowing system so it can be transmitted. */ + prvTCPAddTxData( pxSocket ); + } + + #if ( ipconfigUSE_TCP_WIN == 1 ) + { + if( pxSocket->u.xTCP.pxAckMessage != NULL ) + { + /* The first task of this regular socket check is to send-out delayed + * ACK's. */ + if( pxSocket->u.xTCP.bits.bUserShutdown == pdFALSE_UNSIGNED ) + { + /* Earlier data was received but not yet acknowledged. This + * function is called when the TCP timer for the socket expires, the + * ACK may be sent now. */ + if( pxSocket->u.xTCP.ucTCPState != ( uint8_t ) eCLOSED ) + { + if( ( xTCPWindowLoggingLevel > 1 ) && ipconfigTCP_MAY_LOG_PORT( pxSocket->usLocalPort ) ) + { + FreeRTOS_debug_printf( ( "Send[%u->%u] del ACK %lu SEQ %lu (len %u)\n", + pxSocket->usLocalPort, + pxSocket->u.xTCP.usRemotePort, + pxSocket->u.xTCP.xTCPWindow.rx.ulCurrentSequenceNumber - pxSocket->u.xTCP.xTCPWindow.rx.ulFirstSequenceNumber, + pxSocket->u.xTCP.xTCPWindow.ulOurSequenceNumber - pxSocket->u.xTCP.xTCPWindow.tx.ulFirstSequenceNumber, + ( unsigned ) ipSIZE_OF_IPv4_HEADER + ipSIZE_OF_TCP_HEADER ) ); + } + + prvTCPReturnPacket( pxSocket, pxSocket->u.xTCP.pxAckMessage, ipSIZE_OF_IPv4_HEADER + ipSIZE_OF_TCP_HEADER, ipconfigZERO_COPY_TX_DRIVER ); + + #if ( ipconfigZERO_COPY_TX_DRIVER != 0 ) + { + /* The ownership has been passed to the SEND routine, + * clear the pointer to it. */ + pxSocket->u.xTCP.pxAckMessage = NULL; + } + #endif /* ipconfigZERO_COPY_TX_DRIVER */ + } + + if( prvTCPNextTimeout( pxSocket ) > 1U ) + { + /* Tell the code below that this function is ready. */ + xReady = pdTRUE; + } + } + else + { + /* The user wants to perform an active shutdown(), skip sending + * the delayed ACK. The function prvTCPSendPacket() will send the + * FIN along with the ACK's. */ + } + + if( pxSocket->u.xTCP.pxAckMessage != NULL ) + { + vReleaseNetworkBufferAndDescriptor( pxSocket->u.xTCP.pxAckMessage ); + pxSocket->u.xTCP.pxAckMessage = NULL; + } + } + } + #endif /* ipconfigUSE_TCP_WIN */ + + if( xReady == pdFALSE ) + { + /* The second task of this regular socket check is sending out data. */ + if( ( pxSocket->u.xTCP.ucTCPState >= ( uint8_t ) eESTABLISHED ) || + ( pxSocket->u.xTCP.ucTCPState == ( uint8_t ) eCONNECT_SYN ) ) + { + ( void ) prvTCPSendPacket( pxSocket ); + } + + /* Set the time-out for the next wakeup for this socket. */ + ( void ) prvTCPNextTimeout( pxSocket ); + + #if ( ipconfigTCP_HANG_PROTECTION == 1 ) + { + /* In all (non-connected) states in which keep-alive messages can not be sent + * the anti-hang protocol will close sockets that are 'hanging'. */ + xResult = prvTCPStatusAgeCheck( pxSocket ); + } + #endif + } + + return xResult; + } + /*-----------------------------------------------------------*/ + +/** + * @brief prvTCPSendPacket() will be called when the socket time-out has been reached. + * + * @param[in] pxSocket: The socket owning the connection. + * + * @return Number of bytes to be sent. + * + * @note It is only called by xTCPSocketCheck(). + */ + static int32_t prvTCPSendPacket( FreeRTOS_Socket_t * pxSocket ) + { + int32_t lResult = 0; + UBaseType_t uxOptionsLength, uxIntermediateResult = 0; + NetworkBufferDescriptor_t * pxNetworkBuffer; + + if( pxSocket->u.xTCP.ucTCPState != ( uint8_t ) eCONNECT_SYN ) + { + /* The connection is in a state other than SYN. */ + pxNetworkBuffer = NULL; + + /* prvTCPSendRepeated() will only create a network buffer if necessary, + * i.e. when data must be sent to the peer. */ + lResult = prvTCPSendRepeated( pxSocket, &pxNetworkBuffer ); + + if( pxNetworkBuffer != NULL ) + { + vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer ); + } + } + else + { + if( pxSocket->u.xTCP.ucRepCount >= 3U ) + { + /* The connection is in the SYN status. The packet will be repeated + * to most 3 times. When there is no response, the socket get the + * status 'eCLOSE_WAIT'. */ + FreeRTOS_debug_printf( ( "Connect: giving up %lxip:%u\n", + pxSocket->u.xTCP.ulRemoteIP, /* IP address of remote machine. */ + pxSocket->u.xTCP.usRemotePort ) ); /* Port on remote machine. */ + vTCPStateChange( pxSocket, eCLOSE_WAIT ); + } + else if( ( pxSocket->u.xTCP.bits.bConnPrepared != pdFALSE_UNSIGNED ) || ( prvTCPPrepareConnect( pxSocket ) == pdTRUE ) ) + { + ProtocolHeaders_t * pxProtocolHeaders; + const UBaseType_t uxHeaderSize = ipSIZE_OF_IPv4_HEADER; + + /* Or else, if the connection has been prepared, or can be prepared + * now, proceed to send the packet with the SYN flag. + * prvTCPPrepareConnect() prepares 'xPacket' and returns pdTRUE if + * the Ethernet address of the peer or the gateway is found. */ + pxProtocolHeaders = ipCAST_PTR_TO_TYPE_PTR( ProtocolHeaders_t, &( pxSocket->u.xTCP.xPacket.u.ucLastPacket[ ipSIZE_OF_ETH_HEADER + uxHeaderSize ] ) ); + + /* About to send a SYN packet. Call prvSetSynAckOptions() to set + * the proper options: The size of MSS and whether SACK's are + * allowed. */ + uxOptionsLength = prvSetSynAckOptions( pxSocket, &( pxProtocolHeaders->xTCPHeader ) ); + + /* Return the number of bytes to be sent. */ + uxIntermediateResult = uxIPHeaderSizeSocket( pxSocket ) + ipSIZE_OF_TCP_HEADER + uxOptionsLength; + lResult = ( int32_t ) uxIntermediateResult; + + /* Set the TCP offset field: ipSIZE_OF_TCP_HEADER equals 20 and + * uxOptionsLength is always a multiple of 4. The complete expression + * would be: + * ucTCPOffset = ( ( ipSIZE_OF_TCP_HEADER + uxOptionsLength ) / 4 ) << 4 */ + pxProtocolHeaders->xTCPHeader.ucTCPOffset = ( uint8_t ) ( ( ipSIZE_OF_TCP_HEADER + uxOptionsLength ) << 2 ); + + /* Repeat Count is used for a connecting socket, to limit the number + * of tries. */ + pxSocket->u.xTCP.ucRepCount++; + + /* Send the SYN message to make a connection. The messages is + * stored in the socket field 'xPacket'. It will be wrapped in a + * pseudo network buffer descriptor before it will be sent. */ + prvTCPReturnPacket( pxSocket, NULL, ( uint32_t ) lResult, pdFALSE ); + } + else + { + /* Nothing to do. */ + } + } + + /* Return the total number of bytes sent. */ + return lResult; + } + /*-----------------------------------------------------------*/ + +/** + * @brief prvTCPSendRepeated will try to send a series of messages, as + * long as there is data to be sent and as long as the transmit + * window isn't full. + * + * @param[in] pxSocket: The socket owning the connection. + * @param[in,out] ppxNetworkBuffer: Pointer to pointer to the network buffer. + * + * @return Total number of bytes sent. + */ + static int32_t prvTCPSendRepeated( FreeRTOS_Socket_t * pxSocket, + NetworkBufferDescriptor_t ** ppxNetworkBuffer ) + { + UBaseType_t uxIndex; + int32_t lResult = 0; + UBaseType_t uxOptionsLength = 0U; + int32_t xSendLength; + + for( uxIndex = 0U; uxIndex < ( UBaseType_t ) SEND_REPEATED_COUNT; uxIndex++ ) + { + /* prvTCPPrepareSend() might allocate a network buffer if there is data + * to be sent. */ + xSendLength = prvTCPPrepareSend( pxSocket, ppxNetworkBuffer, uxOptionsLength ); + + if( xSendLength <= 0 ) + { + break; + } + + /* And return the packet to the peer. */ + prvTCPReturnPacket( pxSocket, *ppxNetworkBuffer, ( uint32_t ) xSendLength, ipconfigZERO_COPY_TX_DRIVER ); + + #if ( ipconfigZERO_COPY_TX_DRIVER != 0 ) + { + *ppxNetworkBuffer = NULL; + } + #endif /* ipconfigZERO_COPY_TX_DRIVER */ + + lResult += xSendLength; + } + + /* Return the total number of bytes sent. */ + return lResult; + } + /*-----------------------------------------------------------*/ + +/** + * @brief Return (or send) a packet to the peer. The data is stored in pxBuffer, + * which may either point to a real network buffer or to a TCP socket field + * called 'xTCP.xPacket'. A temporary xNetworkBuffer will be used to pass + * the data to the NIC. + * + * @param[in] pxSocket: The socket owning the connection. + * @param[in] pxDescriptor: The network buffer descriptor carrying the packet. + * @param[in] ulLen: Length of the packet being sent. + * @param[in] xReleaseAfterSend: pdTRUE if the ownership of the descriptor is + * transferred to the network interface. + */ + static void prvTCPReturnPacket( FreeRTOS_Socket_t * pxSocket, + NetworkBufferDescriptor_t * pxDescriptor, + uint32_t ulLen, + BaseType_t xReleaseAfterSend ) + { + TCPPacket_t * pxTCPPacket; + IPHeader_t * pxIPHeader; + BaseType_t xDoRelease = xReleaseAfterSend; + EthernetHeader_t * pxEthernetHeader; + uint32_t ulFrontSpace, ulSpace, ulSourceAddress, ulWinSize; + const TCPWindow_t * pxTCPWindow; + NetworkBufferDescriptor_t * pxNetworkBuffer = pxDescriptor; + NetworkBufferDescriptor_t xTempBuffer; + /* memcpy() helper variables for MISRA Rule 21.15 compliance*/ + const void * pvCopySource; + void * pvCopyDest; + + + /* For sending, a pseudo network buffer will be used, as explained above. */ + + if( pxNetworkBuffer == NULL ) + { + pxNetworkBuffer = &xTempBuffer; + + #if ( ipconfigUSE_LINKED_RX_MESSAGES != 0 ) + { + pxNetworkBuffer->pxNextBuffer = NULL; + } + #endif + pxNetworkBuffer->pucEthernetBuffer = pxSocket->u.xTCP.xPacket.u.ucLastPacket; + pxNetworkBuffer->xDataLength = sizeof( pxSocket->u.xTCP.xPacket.u.ucLastPacket ); + xDoRelease = pdFALSE; + } + + #if ( ipconfigZERO_COPY_TX_DRIVER != 0 ) + { + if( xDoRelease == pdFALSE ) + { + pxNetworkBuffer = pxDuplicateNetworkBufferWithDescriptor( pxNetworkBuffer, ( size_t ) pxNetworkBuffer->xDataLength ); + + if( pxNetworkBuffer == NULL ) + { + FreeRTOS_debug_printf( ( "prvTCPReturnPacket: duplicate failed\n" ) ); + } + + xDoRelease = pdTRUE; + } + } + #endif /* ipconfigZERO_COPY_TX_DRIVER */ + + #ifndef __COVERITY__ + if( pxNetworkBuffer != NULL ) + #endif + { + /* Map the ethernet buffer onto a TCPPacket_t struct for easy access to the fields. */ + pxTCPPacket = ipCAST_PTR_TO_TYPE_PTR( TCPPacket_t, pxNetworkBuffer->pucEthernetBuffer ); + pxIPHeader = &pxTCPPacket->xIPHeader; + pxEthernetHeader = &pxTCPPacket->xEthernetHeader; + + /* Fill the packet, using hton translations. */ + if( pxSocket != NULL ) + { + /* Calculate the space in the RX buffer in order to advertise the + * size of this socket's reception window. */ + pxTCPWindow = &( pxSocket->u.xTCP.xTCPWindow ); + + if( pxSocket->u.xTCP.rxStream != NULL ) + { + /* An RX stream was created already, see how much space is + * available. */ + ulFrontSpace = ( uint32_t ) uxStreamBufferFrontSpace( pxSocket->u.xTCP.rxStream ); + } + else + { + /* No RX stream has been created, the full stream size is + * available. */ + ulFrontSpace = ( uint32_t ) pxSocket->u.xTCP.uxRxStreamSize; + } + + /* Take the minimum of the RX buffer space and the RX window size. */ + ulSpace = FreeRTOS_min_uint32( pxTCPWindow->xSize.ulRxWindowLength, ulFrontSpace ); + + if( ( pxSocket->u.xTCP.bits.bLowWater != pdFALSE_UNSIGNED ) || ( pxSocket->u.xTCP.bits.bRxStopped != pdFALSE_UNSIGNED ) ) + { + /* The low-water mark was reached, meaning there was little + * space left. The socket will wait until the application has read + * or flushed the incoming data, and 'zero-window' will be + * advertised. */ + ulSpace = 0U; + } + + /* If possible, advertise an RX window size of at least 1 MSS, otherwise + * the peer might start 'zero window probing', i.e. sending small packets + * (1, 2, 4, 8... bytes). */ + if( ( ulSpace < pxSocket->u.xTCP.usCurMSS ) && ( ulFrontSpace >= pxSocket->u.xTCP.usCurMSS ) ) + { + ulSpace = pxSocket->u.xTCP.usCurMSS; + } + + /* Avoid overflow of the 16-bit win field. */ + #if ( ipconfigUSE_TCP_WIN != 0 ) + { + ulWinSize = ( ulSpace >> pxSocket->u.xTCP.ucMyWinScaleFactor ); + } + #else + { + ulWinSize = ulSpace; + } + #endif + + if( ulWinSize > 0xfffcUL ) + { + ulWinSize = 0xfffcUL; + } + + pxTCPPacket->xTCPHeader.usWindow = FreeRTOS_htons( ( uint16_t ) ulWinSize ); + + /* The new window size has been advertised, switch off the flag. */ + pxSocket->u.xTCP.bits.bWinChange = pdFALSE_UNSIGNED; + + /* Later on, when deciding to delay an ACK, a precise estimate is needed + * of the free RX space. At this moment, 'ulHighestRxAllowed' would be the + * highest sequence number minus 1 that the socket will accept. */ + pxSocket->u.xTCP.ulHighestRxAllowed = pxTCPWindow->rx.ulCurrentSequenceNumber + ulSpace; + + #if ( ipconfigTCP_KEEP_ALIVE == 1 ) + if( pxSocket->u.xTCP.bits.bSendKeepAlive != pdFALSE_UNSIGNED ) + { + /* Sending a keep-alive packet, send the current sequence number + * minus 1, which will be recognised as a keep-alive packet and + * responded to by acknowledging the last byte. */ + pxSocket->u.xTCP.bits.bSendKeepAlive = pdFALSE_UNSIGNED; + pxSocket->u.xTCP.bits.bWaitKeepAlive = pdTRUE_UNSIGNED; + + pxTCPPacket->xTCPHeader.ulSequenceNumber = pxSocket->u.xTCP.xTCPWindow.ulOurSequenceNumber - 1UL; + pxTCPPacket->xTCPHeader.ulSequenceNumber = FreeRTOS_htonl( pxTCPPacket->xTCPHeader.ulSequenceNumber ); + } + else + #endif /* if ( ipconfigTCP_KEEP_ALIVE == 1 ) */ + { + pxTCPPacket->xTCPHeader.ulSequenceNumber = FreeRTOS_htonl( pxSocket->u.xTCP.xTCPWindow.ulOurSequenceNumber ); + + if( ( pxTCPPacket->xTCPHeader.ucTCPFlags & ( uint8_t ) tcpTCP_FLAG_FIN ) != 0U ) + { + /* Suppress FIN in case this packet carries earlier data to be + * retransmitted. */ + uint32_t ulDataLen = ( uint32_t ) ( ulLen - ( ipSIZE_OF_TCP_HEADER + ipSIZE_OF_IPv4_HEADER ) ); + + if( ( pxTCPWindow->ulOurSequenceNumber + ulDataLen ) != pxTCPWindow->tx.ulFINSequenceNumber ) + { + pxTCPPacket->xTCPHeader.ucTCPFlags &= ( ( uint8_t ) ~tcpTCP_FLAG_FIN ); + FreeRTOS_debug_printf( ( "Suppress FIN for %lu + %lu < %lu\n", + pxTCPWindow->ulOurSequenceNumber - pxTCPWindow->tx.ulFirstSequenceNumber, + ulDataLen, + pxTCPWindow->tx.ulFINSequenceNumber - pxTCPWindow->tx.ulFirstSequenceNumber ) ); + } + } + } + + /* Tell which sequence number is expected next time */ + pxTCPPacket->xTCPHeader.ulAckNr = FreeRTOS_htonl( pxTCPWindow->rx.ulCurrentSequenceNumber ); + } + else + { + /* Sending data without a socket, probably replying with a RST flag + * Just swap the two sequence numbers. */ + vFlip_32( pxTCPPacket->xTCPHeader.ulSequenceNumber, pxTCPPacket->xTCPHeader.ulAckNr ); + } + + pxIPHeader->ucTimeToLive = ( uint8_t ) ipconfigTCP_TIME_TO_LIVE; + pxIPHeader->usLength = FreeRTOS_htons( ulLen ); + + if( ( pxSocket == NULL ) || ( *ipLOCAL_IP_ADDRESS_POINTER == 0UL ) ) + { + /* When pxSocket is NULL, this function is called by prvTCPSendReset() + * and the IP-addresses must be swapped. + * Also swap the IP-addresses in case the IP-tack doesn't have an + * IP-address yet, i.e. when ( *ipLOCAL_IP_ADDRESS_POINTER == 0UL ). */ + ulSourceAddress = pxIPHeader->ulDestinationIPAddress; + } + else + { + ulSourceAddress = *ipLOCAL_IP_ADDRESS_POINTER; + } + + pxIPHeader->ulDestinationIPAddress = pxIPHeader->ulSourceIPAddress; + pxIPHeader->ulSourceIPAddress = ulSourceAddress; + vFlip_16( pxTCPPacket->xTCPHeader.usSourcePort, pxTCPPacket->xTCPHeader.usDestinationPort ); + + /* Just an increasing number. */ + pxIPHeader->usIdentification = FreeRTOS_htons( usPacketIdentifier ); + usPacketIdentifier++; + pxIPHeader->usFragmentOffset = 0U; + + /* Important: tell NIC driver how many bytes must be sent. */ + pxNetworkBuffer->xDataLength = ulLen + ipSIZE_OF_ETH_HEADER; + + #if ( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 ) + { + /* calculate the IP header checksum, in case the driver won't do that. */ + pxIPHeader->usHeaderChecksum = 0x00U; + pxIPHeader->usHeaderChecksum = usGenerateChecksum( 0U, ( uint8_t * ) &( pxIPHeader->ucVersionHeaderLength ), ipSIZE_OF_IPv4_HEADER ); + pxIPHeader->usHeaderChecksum = ~FreeRTOS_htons( pxIPHeader->usHeaderChecksum ); + + /* calculate the TCP checksum for an outgoing packet. */ + ( void ) usGenerateProtocolChecksum( ( uint8_t * ) pxTCPPacket, pxNetworkBuffer->xDataLength, pdTRUE ); + + /* A calculated checksum of 0 must be inverted as 0 means the checksum + * is disabled. */ + if( pxTCPPacket->xTCPHeader.usChecksum == 0U ) + { + pxTCPPacket->xTCPHeader.usChecksum = 0xffffU; + } + } + #endif /* if ( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 ) */ + + #if ( ipconfigUSE_LINKED_RX_MESSAGES != 0 ) + { + pxNetworkBuffer->pxNextBuffer = NULL; + } + #endif + + /* Fill in the destination MAC addresses. */ + ( void ) memcpy( ( void * ) ( &( pxEthernetHeader->xDestinationAddress ) ), + ( const void * ) ( &( pxEthernetHeader->xSourceAddress ) ), + sizeof( pxEthernetHeader->xDestinationAddress ) ); + + /* + * Use helper variables for memcpy() to remain + * compliant with MISRA Rule 21.15. These should be + * optimized away. + */ + /* The source MAC addresses is fixed to 'ipLOCAL_MAC_ADDRESS'. */ + pvCopySource = ipLOCAL_MAC_ADDRESS; + pvCopyDest = &pxEthernetHeader->xSourceAddress; + ( void ) memcpy( pvCopyDest, pvCopySource, ( size_t ) ipMAC_ADDRESS_LENGTH_BYTES ); + + #if defined( ipconfigETHERNET_MINIMUM_PACKET_BYTES ) + { + if( pxNetworkBuffer->xDataLength < ( size_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES ) + { + BaseType_t xIndex; + + for( xIndex = ( BaseType_t ) pxNetworkBuffer->xDataLength; xIndex < ( BaseType_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES; xIndex++ ) + { + pxNetworkBuffer->pucEthernetBuffer[ xIndex ] = 0U; + } + + pxNetworkBuffer->xDataLength = ( size_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES; + } + } + #endif /* if defined( ipconfigETHERNET_MINIMUM_PACKET_BYTES ) */ + + /* Send! */ + iptraceNETWORK_INTERFACE_OUTPUT( pxNetworkBuffer->xDataLength, pxNetworkBuffer->pucEthernetBuffer ); + ( void ) xNetworkInterfaceOutput( pxNetworkBuffer, xDoRelease ); + + if( xDoRelease == pdFALSE ) + { + /* Swap-back some fields, as pxBuffer probably points to a socket field + * containing the packet header. */ + vFlip_16( pxTCPPacket->xTCPHeader.usSourcePort, pxTCPPacket->xTCPHeader.usDestinationPort ); + pxTCPPacket->xIPHeader.ulSourceIPAddress = pxTCPPacket->xIPHeader.ulDestinationIPAddress; + ( void ) memcpy( ( void * ) ( pxEthernetHeader->xSourceAddress.ucBytes ), ( const void * ) ( pxEthernetHeader->xDestinationAddress.ucBytes ), ( size_t ) ipMAC_ADDRESS_LENGTH_BYTES ); + } + else + { + /* Nothing to do: the buffer has been passed to DMA and will be released after use */ + } + } /* if( pxNetworkBuffer != NULL ) */ + } + /*-----------------------------------------------------------*/ + +/** + * @brief Create the TCP window for the given socket. + * + * @param[in] pxSocket: The socket for which the window is being created. + * + * @note The SYN event is very important: the sequence numbers, which have a kind of + * random starting value, are being synchronized. The sliding window manager + * (in FreeRTOS_TCP_WIN.c) needs to know them, along with the Maximum Segment + * Size (MSS). + */ + static void prvTCPCreateWindow( FreeRTOS_Socket_t * pxSocket ) + { + if( xTCPWindowLoggingLevel != 0 ) + { + FreeRTOS_debug_printf( ( "Limits (using): TCP Win size %u Water %u <= %u <= %u\n", + ( unsigned ) pxSocket->u.xTCP.uxRxWinSize * ipconfigTCP_MSS, + ( unsigned ) pxSocket->u.xTCP.uxLittleSpace, + ( unsigned ) pxSocket->u.xTCP.uxEnoughSpace, + ( unsigned ) pxSocket->u.xTCP.uxRxStreamSize ) ); + } + + vTCPWindowCreate( + &pxSocket->u.xTCP.xTCPWindow, + ipconfigTCP_MSS * pxSocket->u.xTCP.uxRxWinSize, + ipconfigTCP_MSS * pxSocket->u.xTCP.uxTxWinSize, + pxSocket->u.xTCP.xTCPWindow.rx.ulCurrentSequenceNumber, + pxSocket->u.xTCP.xTCPWindow.ulOurSequenceNumber, + ( uint32_t ) pxSocket->u.xTCP.usInitMSS ); + } + /*-----------------------------------------------------------*/ + +/** + * @brief Let ARP look-up the MAC-address of the peer and initialise the first SYN + * packet. + * + * @param[in] pxSocket: The socket owning the TCP connection. The first packet shall + * be created in this socket. + * + * @return pdTRUE: if the packet was successfully created and the first SYN can be sent. + * Else pdFALSE. + * + * @note Connecting sockets have a special state: eCONNECT_SYN. In this phase, + * the Ethernet address of the target will be found using ARP. In case the + * target IP address is not within the netmask, the hardware address of the + * gateway will be used. + */ + static BaseType_t prvTCPPrepareConnect( FreeRTOS_Socket_t * pxSocket ) + { + TCPPacket_t * pxTCPPacket; + IPHeader_t * pxIPHeader; + eARPLookupResult_t eReturned; + uint32_t ulRemoteIP; + MACAddress_t xEthAddress; + BaseType_t xReturn = pdTRUE; + uint32_t ulInitialSequenceNumber = 0; + + #if ( ipconfigHAS_PRINTF != 0 ) + { + /* Only necessary for nicer logging. */ + ( void ) memset( xEthAddress.ucBytes, 0, sizeof( xEthAddress.ucBytes ) ); + } + #endif /* ipconfigHAS_PRINTF != 0 */ + + ulRemoteIP = FreeRTOS_htonl( pxSocket->u.xTCP.ulRemoteIP ); + + /* Determine the ARP cache status for the requested IP address. */ + eReturned = eARPGetCacheEntry( &( ulRemoteIP ), &( xEthAddress ) ); + + switch( eReturned ) + { + case eARPCacheHit: /* An ARP table lookup found a valid entry. */ + break; /* We can now prepare the SYN packet. */ + + case eARPCacheMiss: /* An ARP table lookup did not find a valid entry. */ + case eCantSendPacket: /* There is no IP address, or an ARP is still in progress. */ + default: + /* Count the number of times it could not find the ARP address. */ + pxSocket->u.xTCP.ucRepCount++; + + FreeRTOS_debug_printf( ( "ARP for %lxip (using %lxip): rc=%d %02X:%02X:%02X %02X:%02X:%02X\n", + pxSocket->u.xTCP.ulRemoteIP, + FreeRTOS_htonl( ulRemoteIP ), + eReturned, + xEthAddress.ucBytes[ 0 ], + xEthAddress.ucBytes[ 1 ], + xEthAddress.ucBytes[ 2 ], + xEthAddress.ucBytes[ 3 ], + xEthAddress.ucBytes[ 4 ], + xEthAddress.ucBytes[ 5 ] ) ); + + /* And issue a (new) ARP request */ + FreeRTOS_OutputARPRequest( ulRemoteIP ); + xReturn = pdFALSE; + break; + } + + if( xReturn != pdFALSE ) + { + /* Get a difficult-to-predict initial sequence number for this 4-tuple. */ + ulInitialSequenceNumber = ulApplicationGetNextSequenceNumber( *ipLOCAL_IP_ADDRESS_POINTER, + pxSocket->usLocalPort, + pxSocket->u.xTCP.ulRemoteIP, + pxSocket->u.xTCP.usRemotePort ); + + /* Check for a random number generation error. */ + if( ulInitialSequenceNumber == 0UL ) + { + xReturn = pdFALSE; + } + } + + if( xReturn != pdFALSE ) + { + uint16_t usLength; + + /* The MAC-address of the peer (or gateway) has been found, + * now prepare the initial TCP packet and some fields in the socket. Map + * the buffer onto the TCPPacket_t struct to easily access it's field. */ + pxTCPPacket = ipCAST_PTR_TO_TYPE_PTR( TCPPacket_t, pxSocket->u.xTCP.xPacket.u.ucLastPacket ); + pxIPHeader = &pxTCPPacket->xIPHeader; + + /* reset the retry counter to zero. */ + pxSocket->u.xTCP.ucRepCount = 0U; + + /* And remember that the connect/SYN data are prepared. */ + pxSocket->u.xTCP.bits.bConnPrepared = pdTRUE_UNSIGNED; + + /* Now that the Ethernet address is known, the initial packet can be + * prepared. */ + ( void ) memset( pxSocket->u.xTCP.xPacket.u.ucLastPacket, 0, sizeof( pxSocket->u.xTCP.xPacket.u.ucLastPacket ) ); + + /* Write the Ethernet address in Source, because it will be swapped by + * prvTCPReturnPacket(). */ + ( void ) memcpy( ( void * ) ( &pxTCPPacket->xEthernetHeader.xSourceAddress ), ( const void * ) ( &xEthAddress ), sizeof( xEthAddress ) ); + + /* 'ipIPv4_FRAME_TYPE' is already in network-byte-order. */ + pxTCPPacket->xEthernetHeader.usFrameType = ipIPv4_FRAME_TYPE; + + pxIPHeader->ucVersionHeaderLength = 0x45U; + usLength = ( uint16_t ) ( sizeof( TCPPacket_t ) - sizeof( pxTCPPacket->xEthernetHeader ) ); + pxIPHeader->usLength = FreeRTOS_htons( usLength ); + pxIPHeader->ucTimeToLive = ( uint8_t ) ipconfigTCP_TIME_TO_LIVE; + + pxIPHeader->ucProtocol = ( uint8_t ) ipPROTOCOL_TCP; + + /* Addresses and ports will be stored swapped because prvTCPReturnPacket + * will swap them back while replying. */ + pxIPHeader->ulDestinationIPAddress = *ipLOCAL_IP_ADDRESS_POINTER; + pxIPHeader->ulSourceIPAddress = FreeRTOS_htonl( pxSocket->u.xTCP.ulRemoteIP ); + + pxTCPPacket->xTCPHeader.usSourcePort = FreeRTOS_htons( pxSocket->u.xTCP.usRemotePort ); + pxTCPPacket->xTCPHeader.usDestinationPort = FreeRTOS_htons( pxSocket->usLocalPort ); + + /* We are actively connecting, so the peer's Initial Sequence Number (ISN) + * isn't known yet. */ + pxSocket->u.xTCP.xTCPWindow.rx.ulCurrentSequenceNumber = 0UL; + + /* Start with ISN (Initial Sequence Number). */ + pxSocket->u.xTCP.xTCPWindow.ulOurSequenceNumber = ulInitialSequenceNumber; + + /* The TCP header size is 20 bytes, divided by 4 equals 5, which is put in + * the high nibble of the TCP offset field. */ + pxTCPPacket->xTCPHeader.ucTCPOffset = 0x50U; + + /* Only set the SYN flag. */ + pxTCPPacket->xTCPHeader.ucTCPFlags = tcpTCP_FLAG_SYN; + + /* Set the values of usInitMSS / usCurMSS for this socket. */ + prvSocketSetMSS( pxSocket ); + + /* The initial sequence numbers at our side are known. Later + * vTCPWindowInit() will be called to fill in the peer's sequence numbers, but + * first wait for a SYN+ACK reply. */ + prvTCPCreateWindow( pxSocket ); + } + + return xReturn; + } + /*-----------------------------------------------------------*/ + +/* For logging and debugging: make a string showing the TCP flags + */ + #if ( ipconfigHAS_DEBUG_PRINTF != 0 ) + +/** + * @brief Print out the value of flags in a human readable manner. + * + * @param[in] xFlags: The TCP flags. + * + * @return The string containing the flags. + */ + static const char * prvTCPFlagMeaning( UBaseType_t xFlags ) + { + static char retString[ 10 ]; + size_t uxFlags = ( size_t ) xFlags; + + ( void ) snprintf( retString, + sizeof( retString ), "%c%c%c%c%c%c%c%c", + ( ( uxFlags & ( size_t ) tcpTCP_FLAG_FIN ) != 0 ) ? 'F' : '.', /* 0x0001: No more data from sender */ + ( ( uxFlags & ( size_t ) tcpTCP_FLAG_SYN ) != 0 ) ? 'S' : '.', /* 0x0002: Synchronize sequence numbers */ + ( ( uxFlags & ( size_t ) tcpTCP_FLAG_RST ) != 0 ) ? 'R' : '.', /* 0x0004: Reset the connection */ + ( ( uxFlags & ( size_t ) tcpTCP_FLAG_PSH ) != 0 ) ? 'P' : '.', /* 0x0008: Push function: please push buffered data to the recv application */ + ( ( uxFlags & ( size_t ) tcpTCP_FLAG_ACK ) != 0 ) ? 'A' : '.', /* 0x0010: Acknowledgment field is significant */ + ( ( uxFlags & ( size_t ) tcpTCP_FLAG_URG ) != 0 ) ? 'U' : '.', /* 0x0020: Urgent pointer field is significant */ + ( ( uxFlags & ( size_t ) tcpTCP_FLAG_ECN ) != 0 ) ? 'E' : '.', /* 0x0040: ECN-Echo */ + ( ( uxFlags & ( size_t ) tcpTCP_FLAG_CWR ) != 0 ) ? 'C' : '.' ); /* 0x0080: Congestion Window Reduced */ + return retString; + } + /*-----------------------------------------------------------*/ + + #endif /* ipconfigHAS_DEBUG_PRINTF */ + +/** + * @brief Parse the TCP option(s) received, if present. + * + * @param[in] pxSocket: The socket handling the connection. + * @param[in] pxNetworkBuffer: The network buffer containing the TCP + * packet. + * + * @note It has already been verified that: + * ((pxTCPHeader->ucTCPOffset & 0xf0) > 0x50), meaning that + * the TP header is longer than the usual 20 (5 x 4) bytes. + */ + _static void prvCheckOptions( FreeRTOS_Socket_t * pxSocket, + const NetworkBufferDescriptor_t * pxNetworkBuffer ) + { + size_t uxTCPHeaderOffset = ipSIZE_OF_ETH_HEADER + xIPHeaderSize( pxNetworkBuffer ); + const ProtocolHeaders_t * pxProtocolHeaders = ipCAST_PTR_TO_TYPE_PTR( ProtocolHeaders_t, + &( pxNetworkBuffer->pucEthernetBuffer[ uxTCPHeaderOffset ] ) ); + const TCPHeader_t * pxTCPHeader; + const uint8_t * pucPtr; + BaseType_t xHasSYNFlag; + /* Offset in the network packet where the first option byte is stored. */ + size_t uxOptionOffset = uxTCPHeaderOffset + ( sizeof( TCPHeader_t ) - sizeof( pxTCPHeader->ucOptdata ) ); + size_t uxOptionsLength; + size_t uxResult; + uint8_t ucLength; + + pxTCPHeader = &( pxProtocolHeaders->xTCPHeader ); + + + /* A character pointer to iterate through the option data */ + pucPtr = pxTCPHeader->ucOptdata; + + if( pxTCPHeader->ucTCPOffset <= ( 5U << 4U ) ) + { + /* Avoid integer underflow in computation of ucLength. */ + } + else + { + ucLength = ( ( ( pxTCPHeader->ucTCPOffset >> 4U ) - 5U ) << 2U ); + uxOptionsLength = ( size_t ) ucLength; + + if( pxNetworkBuffer->xDataLength > uxOptionOffset ) + { + /* Validate options size calculation. */ + if( ( pxNetworkBuffer->xDataLength > uxOptionOffset ) && + ( uxOptionsLength <= ( pxNetworkBuffer->xDataLength - uxOptionOffset ) ) ) + { + if( ( pxTCPHeader->ucTCPFlags & tcpTCP_FLAG_SYN ) != ( uint8_t ) 0U ) + { + xHasSYNFlag = pdTRUE; + } + else + { + xHasSYNFlag = pdFALSE; + } + + /* The length check is only necessary in case the option data are + * corrupted, we don't like to run into invalid memory and crash. */ + for( ; ; ) + { + if( uxOptionsLength == 0U ) + { + /* coverity[break_stmt] : Break statement terminating the loop */ + break; + } + + uxResult = prvSingleStepTCPHeaderOptions( pucPtr, uxOptionsLength, pxSocket, xHasSYNFlag ); + + if( uxResult == 0UL ) + { + break; + } + + uxOptionsLength -= uxResult; + pucPtr = &( pucPtr[ uxResult ] ); + } + } + } + } + } + /*-----------------------------------------------------------*/ + +/** + * @brief Identify and deal with a single TCP header option, advancing the pointer to + * the header. + * + * @param[in] pucPtr: Pointer to the TCP packet options. + * @param[in] uxTotalLength: Length of the TCP packet options. + * @param[in] pxSocket: Socket handling the connection. + * @param[in] xHasSYNFlag: Whether the header has SYN flag or not. + * + * @return This function returns pdTRUE or pdFALSE depending on whether the caller + * should continue to parse more header options or break the loop. + */ + _static size_t prvSingleStepTCPHeaderOptions( const uint8_t * const pucPtr, + size_t uxTotalLength, + FreeRTOS_Socket_t * const pxSocket, + BaseType_t xHasSYNFlag ) + { + UBaseType_t uxNewMSS; + size_t uxRemainingOptionsBytes = uxTotalLength; + uint8_t ucLen; + size_t uxIndex; + TCPWindow_t * pxTCPWindow = &( pxSocket->u.xTCP.xTCPWindow ); + BaseType_t xReturn = pdFALSE; + + if( pucPtr[ 0U ] == tcpTCP_OPT_END ) + { + /* End of options. */ + uxIndex = 0U; + } + else if( pucPtr[ 0U ] == tcpTCP_OPT_NOOP ) + { + /* NOP option, inserted to make the length a multiple of 4. */ + uxIndex = 1U; + } + else if( uxRemainingOptionsBytes < 2U ) + { + /* Any other well-formed option must be at least two bytes: the option + * type byte followed by a length byte. */ + uxIndex = 0U; + } + + #if ( ipconfigUSE_TCP_WIN != 0 ) + else if( pucPtr[ 0 ] == tcpTCP_OPT_WSOPT ) + { + /* The TCP Window Scale Option. */ + /* Confirm that the option fits in the remaining buffer space. */ + if( ( uxRemainingOptionsBytes < tcpTCP_OPT_WSOPT_LEN ) || ( pucPtr[ 1 ] != tcpTCP_OPT_WSOPT_LEN ) ) + { + uxIndex = 0U; + } + else + { + /* Option is only valid in SYN phase. */ + if( xHasSYNFlag != 0 ) + { + pxSocket->u.xTCP.ucPeerWinScaleFactor = pucPtr[ 2 ]; + pxSocket->u.xTCP.bits.bWinScaling = pdTRUE_UNSIGNED; + } + + uxIndex = tcpTCP_OPT_WSOPT_LEN; + } + } + #endif /* ipconfigUSE_TCP_WIN */ + else if( pucPtr[ 0 ] == tcpTCP_OPT_MSS ) + { + /* Confirm that the option fits in the remaining buffer space. */ + if( ( uxRemainingOptionsBytes < tcpTCP_OPT_MSS_LEN ) || ( pucPtr[ 1 ] != tcpTCP_OPT_MSS_LEN ) ) + { + uxIndex = 0U; + } + else + { + /* An MSS option with the correct option length. FreeRTOS_htons() + * is not needed here because usChar2u16() already returns a host + * endian number. */ + uxNewMSS = usChar2u16( &( pucPtr[ 2 ] ) ); + + if( pxSocket->u.xTCP.usInitMSS != uxNewMSS ) + { + /* Perform a basic check on the the new MSS. */ + if( uxNewMSS == 0U ) + { + uxIndex = 0U; + + /* Return Condition found. */ + xReturn = pdTRUE; + } + else + { + FreeRTOS_debug_printf( ( "MSS change %u -> %lu\n", pxSocket->u.xTCP.usInitMSS, uxNewMSS ) ); + } + } + + /* If a 'return' condition has not been found. */ + if( xReturn == pdFALSE ) + { + if( pxSocket->u.xTCP.usInitMSS > uxNewMSS ) + { + /* our MSS was bigger than the MSS of the other party: adapt it. */ + pxSocket->u.xTCP.bits.bMssChange = pdTRUE_UNSIGNED; + + if( pxSocket->u.xTCP.usCurMSS > uxNewMSS ) + { + /* The peer advertises a smaller MSS than this socket was + * using. Use that as well. */ + FreeRTOS_debug_printf( ( "Change mss %d => %lu\n", pxSocket->u.xTCP.usCurMSS, uxNewMSS ) ); + pxSocket->u.xTCP.usCurMSS = ( uint16_t ) uxNewMSS; + } + + pxTCPWindow->xSize.ulRxWindowLength = ( ( uint32_t ) uxNewMSS ) * ( pxTCPWindow->xSize.ulRxWindowLength / ( ( uint32_t ) uxNewMSS ) ); + pxTCPWindow->usMSSInit = ( uint16_t ) uxNewMSS; + pxTCPWindow->usMSS = ( uint16_t ) uxNewMSS; + pxSocket->u.xTCP.usInitMSS = ( uint16_t ) uxNewMSS; + pxSocket->u.xTCP.usCurMSS = ( uint16_t ) uxNewMSS; + } + + uxIndex = tcpTCP_OPT_MSS_LEN; + } + } + } + else + { + /* All other options have a length field, so that we easily + * can skip past them. */ + ucLen = pucPtr[ 1 ]; + uxIndex = 0U; + + if( ( ucLen < ( uint8_t ) 2U ) || ( uxRemainingOptionsBytes < ( size_t ) ucLen ) ) + { + /* If the length field is too small or too big, the options are + * malformed, don't process them further. + */ + } + else + { + #if ( ipconfigUSE_TCP_WIN == 1 ) + { + /* Selective ACK: the peer has received a packet but it is missing + * earlier packets. At least this packet does not need retransmission + * anymore. ulTCPWindowTxSack( ) takes care of this administration. + */ + if( pucPtr[ 0U ] == tcpTCP_OPT_SACK_A ) + { + ucLen -= 2U; + uxIndex += 2U; + + while( ucLen >= ( uint8_t ) 8U ) + { + prvReadSackOption( pucPtr, uxIndex, pxSocket ); + uxIndex += 8U; + ucLen -= 8U; + } + + /* ucLen should be 0 by now. */ + } + } + #endif /* ipconfigUSE_TCP_WIN == 1 */ + + uxIndex += ( size_t ) ucLen; + } + } + return uxIndex; + } + /*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 1 ) + +/** + * @brief Skip past TCP header options when doing Selective ACK, until there are no + * more options left. + * + * @param[in] pucPtr: Pointer to the TCP packet options. + * @param[in] uxIndex: Index of options in the TCP packet options. + * @param[in] pxSocket: Socket handling the TCP connection. + */ + _static void prvReadSackOption( const uint8_t * const pucPtr, + size_t uxIndex, + FreeRTOS_Socket_t * const pxSocket ) + { + uint32_t ulFirst = ulChar2u32( &( pucPtr[ uxIndex ] ) ); + uint32_t ulLast = ulChar2u32( &( pucPtr[ uxIndex + 4U ] ) ); + uint32_t ulCount = ulTCPWindowTxSack( &( pxSocket->u.xTCP.xTCPWindow ), ulFirst, ulLast ); + + /* ulTCPWindowTxSack( ) returns the number of bytes which have been acked + * starting from the head position. Advance the tail pointer in txStream. + */ + if( ( pxSocket->u.xTCP.txStream != NULL ) && ( ulCount > 0U ) ) + { + /* Just advancing the tail index, 'ulCount' bytes have been confirmed. */ + ( void ) uxStreamBufferGet( pxSocket->u.xTCP.txStream, 0, NULL, ( size_t ) ulCount, pdFALSE ); + pxSocket->xEventBits |= ( EventBits_t ) eSOCKET_SEND; + + #if ipconfigSUPPORT_SELECT_FUNCTION == 1 + { + if( ( pxSocket->xSelectBits & ( EventBits_t ) eSELECT_WRITE ) != 0U ) + { + /* The field 'xEventBits' is used to store regular socket events + * (at most 8), as well as 'select events', which will be left-shifted. + */ + pxSocket->xEventBits |= ( ( EventBits_t ) eSELECT_WRITE ) << SOCKET_EVENT_BIT_COUNT; + } + } + #endif + + /* In case the socket owner has installed an OnSent handler, + * call it now. */ + #if ( ipconfigUSE_CALLBACKS == 1 ) + { + if( ipconfigIS_VALID_PROG_ADDRESS( pxSocket->u.xTCP.pxHandleSent ) ) + { + pxSocket->u.xTCP.pxHandleSent( pxSocket, ulCount ); + } + } + #endif /* ipconfigUSE_CALLBACKS == 1 */ + } + } + + #endif /* ( ipconfigUSE_TCP_WIN != 0 ) */ + /*-----------------------------------------------------------*/ + + + #if ( ipconfigUSE_TCP_WIN != 0 ) + +/** + * @brief Get the window scaling factor for the TCP connection. + * + * @param[in] pxSocket: The socket owning the TCP connection. + * + * @return The scaling factor. + */ + static uint8_t prvWinScaleFactor( const FreeRTOS_Socket_t * pxSocket ) + { + size_t uxWinSize; + uint8_t ucFactor; + + + /* 'xTCP.uxRxWinSize' is the size of the reception window in units of MSS. */ + uxWinSize = pxSocket->u.xTCP.uxRxWinSize * ( size_t ) pxSocket->u.xTCP.usInitMSS; + ucFactor = 0U; + + while( uxWinSize > 0xffffUL ) + { + /* Divide by two and increase the binary factor by 1. */ + uxWinSize >>= 1; + ucFactor++; + } + + FreeRTOS_debug_printf( ( "prvWinScaleFactor: uxRxWinSize %u MSS %u Factor %u\n", + ( unsigned ) pxSocket->u.xTCP.uxRxWinSize, + ( unsigned ) pxSocket->u.xTCP.usInitMSS, + ucFactor ) ); + + return ucFactor; + } + + #endif /* if ( ipconfigUSE_TCP_WIN != 0 ) */ + /*-----------------------------------------------------------*/ + +/** + * @brief When opening a TCP connection, while SYN's are being sent, the parties may + * communicate what MSS (Maximum Segment Size) they intend to use, whether Selective + * ACK's ( SACK ) are supported, and the size of the reception window ( WSOPT ). + * + * @param[in] pxSocket: The socket being used for communication. It is used to set + * the MSS. + * @param[in,out] pxTCPHeader: The TCP packet header being used in the SYN transmission. + * The MSS and corresponding options shall be set in this + * header itself. + * + * @return The option length after the TCP header was updated. + * + * @note MSS is the net size of the payload, an is always smaller than MTU. + */ + static UBaseType_t prvSetSynAckOptions( FreeRTOS_Socket_t * pxSocket, + TCPHeader_t * pxTCPHeader ) + { + uint16_t usMSS = pxSocket->u.xTCP.usInitMSS; + UBaseType_t uxOptionsLength; + + /* We send out the TCP Maximum Segment Size option with our SYN[+ACK]. */ + + pxTCPHeader->ucOptdata[ 0 ] = ( uint8_t ) tcpTCP_OPT_MSS; + pxTCPHeader->ucOptdata[ 1 ] = ( uint8_t ) tcpTCP_OPT_MSS_LEN; + pxTCPHeader->ucOptdata[ 2 ] = ( uint8_t ) ( usMSS >> 8 ); + pxTCPHeader->ucOptdata[ 3 ] = ( uint8_t ) ( usMSS & 0xffU ); + + #if ( ipconfigUSE_TCP_WIN != 0 ) + { + pxSocket->u.xTCP.ucMyWinScaleFactor = prvWinScaleFactor( pxSocket ); + + pxTCPHeader->ucOptdata[ 4 ] = tcpTCP_OPT_NOOP; + pxTCPHeader->ucOptdata[ 5 ] = ( uint8_t ) ( tcpTCP_OPT_WSOPT ); + pxTCPHeader->ucOptdata[ 6 ] = ( uint8_t ) ( tcpTCP_OPT_WSOPT_LEN ); + pxTCPHeader->ucOptdata[ 7 ] = ( uint8_t ) pxSocket->u.xTCP.ucMyWinScaleFactor; + uxOptionsLength = 8U; + } + #else + { + uxOptionsLength = 4U; + } + #endif /* if ( ipconfigUSE_TCP_WIN != 0 ) */ + + #if ( ipconfigUSE_TCP_WIN != 0 ) + { + pxTCPHeader->ucOptdata[ uxOptionsLength ] = tcpTCP_OPT_NOOP; + pxTCPHeader->ucOptdata[ uxOptionsLength + 1U ] = tcpTCP_OPT_NOOP; + pxTCPHeader->ucOptdata[ uxOptionsLength + 2U ] = tcpTCP_OPT_SACK_P; /* 4: Sack-Permitted Option. */ + pxTCPHeader->ucOptdata[ uxOptionsLength + 3U ] = 2U; /* 2: length of this option. */ + uxOptionsLength += 4U; + } + #endif /* ipconfigUSE_TCP_WIN == 0 */ + return uxOptionsLength; /* bytes, not words. */ + } + +/** + * @brief 'Touch' the socket to keep it alive/updated. + * + * @param[in] pxSocket: The socket to be updated. + * + * @note This is used for anti-hanging protection and TCP keep-alive messages. + * Called in two places: after receiving a packet and after a state change. + * The socket's alive timer may be reset. + */ + static void prvTCPTouchSocket( FreeRTOS_Socket_t * pxSocket ) + { + #if ( ipconfigTCP_HANG_PROTECTION == 1 ) + { + pxSocket->u.xTCP.xLastActTime = xTaskGetTickCount(); + } + #endif + + #if ( ipconfigTCP_KEEP_ALIVE == 1 ) + { + pxSocket->u.xTCP.bits.bWaitKeepAlive = pdFALSE_UNSIGNED; + pxSocket->u.xTCP.bits.bSendKeepAlive = pdFALSE_UNSIGNED; + pxSocket->u.xTCP.ucKeepRepCount = 0U; + pxSocket->u.xTCP.xLastAliveTime = xTaskGetTickCount(); + } + #endif + + ( void ) pxSocket; + } + /*-----------------------------------------------------------*/ + +/** + * @brief Changing to a new state. Centralised here to do specific actions such as + * resetting the alive timer, calling the user's OnConnect handler to notify + * that a socket has got (dis)connected, and setting bit to unblock a call to + * FreeRTOS_select(). + * + * @param[in] pxSocket: The socket whose state we are trying to change. + * @param[in] eTCPState: The state to which we want to change to. + */ + void vTCPStateChange( FreeRTOS_Socket_t * pxSocket, + enum eTCP_STATE eTCPState ) + { + FreeRTOS_Socket_t * xParent = NULL; + BaseType_t bBefore = ipNUMERIC_CAST( BaseType_t, tcpNOW_CONNECTED( ( BaseType_t ) pxSocket->u.xTCP.ucTCPState ) ); /* Was it connected ? */ + BaseType_t bAfter = ipNUMERIC_CAST( BaseType_t, tcpNOW_CONNECTED( ( BaseType_t ) eTCPState ) ); /* Is it connected now ? */ + + #if ( ipconfigHAS_DEBUG_PRINTF != 0 ) + BaseType_t xPreviousState = ( BaseType_t ) pxSocket->u.xTCP.ucTCPState; + #endif + #if ( ipconfigUSE_CALLBACKS == 1 ) + FreeRTOS_Socket_t * xConnected = NULL; + #endif + + /* Has the connected status changed? */ + if( bBefore != bAfter ) + { + /* Is the socket connected now ? */ + if( bAfter != pdFALSE ) + { + /* if bPassQueued is true, this socket is an orphan until it gets connected. */ + if( pxSocket->u.xTCP.bits.bPassQueued != pdFALSE_UNSIGNED ) + { + /* Now that it is connected, find it's parent. */ + if( pxSocket->u.xTCP.bits.bReuseSocket != pdFALSE_UNSIGNED ) + { + xParent = pxSocket; + } + else + { + xParent = pxSocket->u.xTCP.pxPeerSocket; + configASSERT( xParent != NULL ); + } + + if( xParent != NULL ) + { + if( xParent->u.xTCP.pxPeerSocket == NULL ) + { + xParent->u.xTCP.pxPeerSocket = pxSocket; + } + + xParent->xEventBits |= ( EventBits_t ) eSOCKET_ACCEPT; + + #if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 ) + { + /* Library support FreeRTOS_select(). Receiving a new + * connection is being translated as a READ event. */ + if( ( xParent->xSelectBits & ( ( EventBits_t ) eSELECT_READ ) ) != 0U ) + { + xParent->xEventBits |= ( ( EventBits_t ) eSELECT_READ ) << SOCKET_EVENT_BIT_COUNT; + } + } + #endif + + #if ( ipconfigUSE_CALLBACKS == 1 ) + { + if( ( ipconfigIS_VALID_PROG_ADDRESS( xParent->u.xTCP.pxHandleConnected ) ) && + ( xParent->u.xTCP.bits.bReuseSocket == pdFALSE_UNSIGNED ) ) + { + /* The listening socket does not become connected itself, in stead + * a child socket is created. + * Postpone a call the OnConnect event until the end of this function. */ + xConnected = xParent; + } + } + #endif + } + + /* Don't need to access the parent socket anymore, so the + * reference 'pxPeerSocket' may be cleared. */ + pxSocket->u.xTCP.pxPeerSocket = NULL; + pxSocket->u.xTCP.bits.bPassQueued = pdFALSE_UNSIGNED; + + /* When true, this socket may be returned in a call to accept(). */ + pxSocket->u.xTCP.bits.bPassAccept = pdTRUE_UNSIGNED; + } + else + { + pxSocket->xEventBits |= ( EventBits_t ) eSOCKET_CONNECT; + + #if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 ) + { + if( ( pxSocket->xSelectBits & ( ( EventBits_t ) eSELECT_WRITE ) ) != 0U ) + { + pxSocket->xEventBits |= ( ( EventBits_t ) eSELECT_WRITE ) << SOCKET_EVENT_BIT_COUNT; + } + } + #endif + } + } + else /* bAfter == pdFALSE, connection is closed. */ + { + /* Notify/wake-up the socket-owner by setting a semaphore. */ + pxSocket->xEventBits |= ( EventBits_t ) eSOCKET_CLOSED; + + #if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 ) + { + if( ( pxSocket->xSelectBits & ( EventBits_t ) eSELECT_EXCEPT ) != 0U ) + { + pxSocket->xEventBits |= ( ( EventBits_t ) eSELECT_EXCEPT ) << SOCKET_EVENT_BIT_COUNT; + } + } + #endif + } + + #if ( ipconfigUSE_CALLBACKS == 1 ) + { + if( ( ipconfigIS_VALID_PROG_ADDRESS( pxSocket->u.xTCP.pxHandleConnected ) ) && ( xConnected == NULL ) ) + { + /* The 'connected' state has changed, call the user handler. */ + xConnected = pxSocket; + } + } + #endif /* ipconfigUSE_CALLBACKS */ + + if( prvTCPSocketIsActive( ipNUMERIC_CAST( eIPTCPState_t, pxSocket->u.xTCP.ucTCPState ) ) == 0 ) + { + /* Now the socket isn't in an active state anymore so it + * won't need further attention of the IP-task. + * Setting time-out to zero means that the socket won't get checked during + * timer events. */ + pxSocket->u.xTCP.usTimeout = 0U; + } + } + else + { + if( ( eTCPState == eCLOSED ) || + ( eTCPState == eCLOSE_WAIT ) ) + { + /* Socket goes to status eCLOSED because of a RST. + * When nobody owns the socket yet, delete it. */ + if( ( pxSocket->u.xTCP.bits.bPassQueued != pdFALSE_UNSIGNED ) || + ( pxSocket->u.xTCP.bits.bPassAccept != pdFALSE_UNSIGNED ) ) + { + FreeRTOS_debug_printf( ( "vTCPStateChange: Closing socket\n" ) ); + + if( pxSocket->u.xTCP.bits.bReuseSocket == pdFALSE_UNSIGNED ) + { + ( void ) FreeRTOS_closesocket( pxSocket ); + } + } + } + } + + /* Fill in the new state. */ + pxSocket->u.xTCP.ucTCPState = ( uint8_t ) eTCPState; + + /* Touch the alive timers because moving to another state. */ + prvTCPTouchSocket( pxSocket ); + + #if ( ipconfigHAS_DEBUG_PRINTF == 1 ) + { + if( ( xTCPWindowLoggingLevel >= 0 ) && ( ipconfigTCP_MAY_LOG_PORT( pxSocket->usLocalPort ) ) ) + { + FreeRTOS_debug_printf( ( "Socket %d -> %lxip:%u State %s->%s\n", + pxSocket->usLocalPort, + pxSocket->u.xTCP.ulRemoteIP, + pxSocket->u.xTCP.usRemotePort, + FreeRTOS_GetTCPStateName( ( UBaseType_t ) xPreviousState ), + FreeRTOS_GetTCPStateName( ( UBaseType_t ) eTCPState ) ) ); + } + } + #endif /* ipconfigHAS_DEBUG_PRINTF */ + + #if ( ipconfigUSE_CALLBACKS == 1 ) + { + if( xConnected != NULL ) + { + /* The 'connected' state has changed, call the OnConnect handler of the parent. */ + xConnected->u.xTCP.pxHandleConnected( ( Socket_t ) xConnected, bAfter ); + } + } + #endif + + if( xParent != NULL ) + { + vSocketWakeUpUser( xParent ); + } + } + /*-----------------------------------------------------------*/ + +/** + * @brief Check if the size of a network buffer is big enough to hold the outgoing message. + * Allocate a new bigger network buffer when necessary. + * + * @param[in] pxSocket: Socket whose buffer is being resized. + * @param[in] pxNetworkBuffer: The network buffer whose size is being increased. + * @param[in] lDataLen: Length of the data to be put in the buffer. + * @param[in] uxOptionsLength: Length of options. + * + * @return If the resizing is successful: The new buffer with the size being asked for + * with old data copied in it. + * Else, NULL. + * + * @note The old network buffer will be released if the resizing is successful and + * cannot be used any longer. + */ + static NetworkBufferDescriptor_t * prvTCPBufferResize( const FreeRTOS_Socket_t * pxSocket, + NetworkBufferDescriptor_t * pxNetworkBuffer, + int32_t lDataLen, + UBaseType_t uxOptionsLength ) + { + NetworkBufferDescriptor_t * pxReturn; + size_t uxNeeded; + BaseType_t xResize; + + if( xBufferAllocFixedSize != pdFALSE ) + { + /* Network buffers are created with a fixed size and can hold the largest + * MTU. */ + uxNeeded = ( size_t ) ipTOTAL_ETHERNET_FRAME_SIZE; + + /* and therefore, the buffer won't be too small. + * Only ask for a new network buffer in case none was supplied. */ + if( pxNetworkBuffer == NULL ) + { + xResize = pdTRUE; + } + else + { + xResize = pdFALSE; + } + } + else + { + /* Network buffers are created with a variable size. See if it must + * grow. */ + uxNeeded = ipNUMERIC_CAST( size_t, ipSIZE_OF_ETH_HEADER + uxIPHeaderSizeSocket( pxSocket ) + ipSIZE_OF_TCP_HEADER + uxOptionsLength ) + lDataLen; + + if( uxNeeded < sizeof( pxSocket->u.xTCP.xPacket.u.ucLastPacket ) ) + { + uxNeeded = sizeof( pxSocket->u.xTCP.xPacket.u.ucLastPacket ); + } + + /* In case we were called from a TCP timer event, a buffer must be + * created. Otherwise, test 'xDataLength' of the provided buffer. */ + if( ( pxNetworkBuffer == NULL ) || ( pxNetworkBuffer->xDataLength < uxNeeded ) ) + { + xResize = pdTRUE; + } + else + { + xResize = pdFALSE; + } + } + + if( xResize != pdFALSE ) + { + /* The caller didn't provide a network buffer or the provided buffer is + * too small. As we must send-out a data packet, a buffer will be created + * here. */ + pxReturn = pxGetNetworkBufferWithDescriptor( uxNeeded, 0U ); + + if( pxReturn != NULL ) + { + /* Set the actual packet size, in case the returned buffer is larger. */ + pxReturn->xDataLength = uxNeeded; + + /* Copy the existing data to the new created buffer. */ + if( pxNetworkBuffer != NULL ) + { + /* Either from the previous buffer... */ + ( void ) memcpy( pxReturn->pucEthernetBuffer, pxNetworkBuffer->pucEthernetBuffer, pxNetworkBuffer->xDataLength ); + + /* ...and release it. */ + vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer ); + } + else + { + /* Or from the socket field 'xTCP.xPacket'. */ + ( void ) memcpy( pxReturn->pucEthernetBuffer, pxSocket->u.xTCP.xPacket.u.ucLastPacket, sizeof( pxSocket->u.xTCP.xPacket.u.ucLastPacket ) ); + } + } + } + else + { + /* xResize is false, the network buffer provided was big enough. */ + configASSERT( pxNetworkBuffer != NULL ); /* to tell lint: when xResize is false, pxNetworkBuffer is not NULL. */ + pxReturn = pxNetworkBuffer; + + pxNetworkBuffer->xDataLength = ( size_t ) ( ipSIZE_OF_ETH_HEADER + uxIPHeaderSizeSocket( pxSocket ) + ipSIZE_OF_TCP_HEADER + uxOptionsLength ) + ( size_t ) lDataLen; + } + + return pxReturn; + } + /*-----------------------------------------------------------*/ + +/** + * @brief Prepare an outgoing message, in case anything has to be sent. + * + * @param[in] pxSocket: The socket owning the connection. + * @param[in,out] ppxNetworkBuffer: Pointer to the pointer to the network buffer. + * @param[in] uxOptionsLength: The length of the TCP options. + * + * @return Length of the data to be sent if everything is correct. Else, -1 + * is returned in case of any error. + */ + static int32_t prvTCPPrepareSend( FreeRTOS_Socket_t * pxSocket, + NetworkBufferDescriptor_t ** ppxNetworkBuffer, + UBaseType_t uxOptionsLength ) + { + int32_t lDataLen; + uint8_t * pucEthernetBuffer, * pucSendData; + ProtocolHeaders_t * pxProtocolHeaders; + size_t uxOffset; + uint32_t ulDataGot, ulDistance; + TCPWindow_t * pxTCPWindow; + NetworkBufferDescriptor_t * pxNewBuffer; + int32_t lStreamPos; + UBaseType_t uxIntermediateResult = 0; + + if( ( *ppxNetworkBuffer ) != NULL ) + { + /* A network buffer descriptor was already supplied */ + pucEthernetBuffer = ( *ppxNetworkBuffer )->pucEthernetBuffer; + } + else + { + /* For now let it point to the last packet header */ + pucEthernetBuffer = pxSocket->u.xTCP.xPacket.u.ucLastPacket; + } + + /* Map the ethernet buffer onto the ProtocolHeader_t struct for easy access to the fields. */ + pxProtocolHeaders = ipCAST_PTR_TO_TYPE_PTR( ProtocolHeaders_t, &( pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER + uxIPHeaderSizeSocket( pxSocket ) ] ) ); + pxTCPWindow = &( pxSocket->u.xTCP.xTCPWindow ); + lDataLen = 0; + lStreamPos = 0; + pxProtocolHeaders->xTCPHeader.ucTCPFlags |= tcpTCP_FLAG_ACK; + + if( pxSocket->u.xTCP.txStream != NULL ) + { + /* ulTCPWindowTxGet will return the amount of data which may be sent + * along with the position in the txStream. + * Why check for MSS > 1 ? + * Because some TCP-stacks (like uIP) use it for flow-control. */ + if( pxSocket->u.xTCP.usCurMSS > 1U ) + { + lDataLen = ( int32_t ) ulTCPWindowTxGet( pxTCPWindow, pxSocket->u.xTCP.ulWindowSize, &lStreamPos ); + } + + if( lDataLen > 0 ) + { + /* Check if the current network buffer is big enough, if not, + * resize it. */ + pxNewBuffer = prvTCPBufferResize( pxSocket, *ppxNetworkBuffer, lDataLen, uxOptionsLength ); + + if( pxNewBuffer != NULL ) + { + *ppxNetworkBuffer = pxNewBuffer; + pucEthernetBuffer = pxNewBuffer->pucEthernetBuffer; + + /* Map the byte stream onto ProtocolHeaders_t struct for easy + * access to the fields. */ + pxProtocolHeaders = ipCAST_PTR_TO_TYPE_PTR( ProtocolHeaders_t, &( pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER + uxIPHeaderSizeSocket( pxSocket ) ] ) ); + + pucSendData = &( pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER + uxIPHeaderSizeSocket( pxSocket ) + ipSIZE_OF_TCP_HEADER + uxOptionsLength ] ); + + /* Translate the position in txStream to an offset from the tail + * marker. */ + uxOffset = uxStreamBufferDistance( pxSocket->u.xTCP.txStream, pxSocket->u.xTCP.txStream->uxTail, ( size_t ) lStreamPos ); + + /* Here data is copied from the txStream in 'peek' mode. Only + * when the packets are acked, the tail marker will be updated. */ + ulDataGot = ( uint32_t ) uxStreamBufferGet( pxSocket->u.xTCP.txStream, uxOffset, pucSendData, ( size_t ) lDataLen, pdTRUE ); + + #if ( ipconfigHAS_DEBUG_PRINTF != 0 ) + { + if( ulDataGot != ( uint32_t ) lDataLen ) + { + FreeRTOS_debug_printf( ( "uxStreamBufferGet: pos %d offs %u only %u != %d\n", + ( int ) lStreamPos, ( unsigned ) uxOffset, ( unsigned ) ulDataGot, ( int ) lDataLen ) ); + } + } + #endif + + /* If the owner of the socket requests a closure, add the FIN + * flag to the last packet. */ + if( ( pxSocket->u.xTCP.bits.bCloseRequested != pdFALSE_UNSIGNED ) && ( pxSocket->u.xTCP.bits.bFinSent == pdFALSE_UNSIGNED ) ) + { + ulDistance = ( uint32_t ) uxStreamBufferDistance( pxSocket->u.xTCP.txStream, ( size_t ) lStreamPos, pxSocket->u.xTCP.txStream->uxHead ); + + if( ulDistance == ulDataGot ) + { + #if ( ipconfigHAS_DEBUG_PRINTF == 1 ) + { + /* the order of volatile accesses is undefined + * so such workaround */ + size_t uxHead = pxSocket->u.xTCP.txStream->uxHead; + size_t uxMid = pxSocket->u.xTCP.txStream->uxMid; + size_t uxTail = pxSocket->u.xTCP.txStream->uxTail; + + FreeRTOS_debug_printf( ( "CheckClose %u <= %u (%u <= %u <= %u)\n", + ( unsigned ) ulDataGot, ( unsigned ) ulDistance, + ( unsigned ) uxTail, ( unsigned ) uxMid, ( unsigned ) uxHead ) ); + } + #endif /* if ( ipconfigHAS_DEBUG_PRINTF == 1 ) */ + + /* Although the socket sends a FIN, it will stay in + * ESTABLISHED until all current data has been received or + * delivered. */ + pxProtocolHeaders->xTCPHeader.ucTCPFlags |= tcpTCP_FLAG_FIN; + pxTCPWindow->tx.ulFINSequenceNumber = pxTCPWindow->ulOurSequenceNumber + ( uint32_t ) lDataLen; + pxSocket->u.xTCP.bits.bFinSent = pdTRUE_UNSIGNED; + } + } + } + else + { + lDataLen = -1; + } + } + } + + if( ( lDataLen >= 0 ) && ( pxSocket->u.xTCP.ucTCPState == ( uint8_t ) eESTABLISHED ) ) + { + /* See if the socket owner wants to shutdown this connection. */ + if( ( pxSocket->u.xTCP.bits.bUserShutdown != pdFALSE_UNSIGNED ) && + ( xTCPWindowTxDone( pxTCPWindow ) != pdFALSE ) ) + { + pxSocket->u.xTCP.bits.bUserShutdown = pdFALSE_UNSIGNED; + pxProtocolHeaders->xTCPHeader.ucTCPFlags |= tcpTCP_FLAG_FIN; + pxSocket->u.xTCP.bits.bFinSent = pdTRUE_UNSIGNED; + pxSocket->u.xTCP.bits.bWinChange = pdTRUE_UNSIGNED; + pxTCPWindow->tx.ulFINSequenceNumber = pxTCPWindow->tx.ulCurrentSequenceNumber; + vTCPStateChange( pxSocket, eFIN_WAIT_1 ); + } + + #if ( ipconfigTCP_KEEP_ALIVE != 0 ) + { + if( pxSocket->u.xTCP.ucKeepRepCount > 3U ) /*_RB_ Magic number. */ + { + FreeRTOS_debug_printf( ( "keep-alive: giving up %lxip:%u\n", + pxSocket->u.xTCP.ulRemoteIP, /* IP address of remote machine. */ + pxSocket->u.xTCP.usRemotePort ) ); /* Port on remote machine. */ + vTCPStateChange( pxSocket, eCLOSE_WAIT ); + lDataLen = -1; + } + + if( ( lDataLen == 0 ) && ( pxSocket->u.xTCP.bits.bWinChange == pdFALSE_UNSIGNED ) ) + { + /* If there is no data to be sent, and no window-update message, + * we might want to send a keep-alive message. */ + TickType_t xAge = xTaskGetTickCount() - pxSocket->u.xTCP.xLastAliveTime; + TickType_t xMax; + xMax = ( ( TickType_t ) ipconfigTCP_KEEP_ALIVE_INTERVAL * ( TickType_t ) configTICK_RATE_HZ ); + + if( pxSocket->u.xTCP.ucKeepRepCount != ( uint8_t ) 0U ) + { + xMax = ( TickType_t ) ( 3U * configTICK_RATE_HZ ); + } + + if( xAge > xMax ) + { + pxSocket->u.xTCP.xLastAliveTime = xTaskGetTickCount(); + + if( xTCPWindowLoggingLevel != 0 ) + { + FreeRTOS_debug_printf( ( "keep-alive: %lxip:%u count %u\n", + pxSocket->u.xTCP.ulRemoteIP, + pxSocket->u.xTCP.usRemotePort, + pxSocket->u.xTCP.ucKeepRepCount ) ); + } + + pxSocket->u.xTCP.bits.bSendKeepAlive = pdTRUE_UNSIGNED; + pxSocket->u.xTCP.usTimeout = ( ( uint16_t ) pdMS_TO_TICKS( 2500U ) ); + pxSocket->u.xTCP.ucKeepRepCount++; + } + } + } + #endif /* ipconfigTCP_KEEP_ALIVE */ + } + + /* Anything to send, a change of the advertised window size, or maybe send a + * keep-alive message? */ + if( ( lDataLen > 0 ) || + ( pxSocket->u.xTCP.bits.bWinChange != pdFALSE_UNSIGNED ) || + ( pxSocket->u.xTCP.bits.bSendKeepAlive != pdFALSE_UNSIGNED ) ) + { + pxProtocolHeaders->xTCPHeader.ucTCPFlags &= ( ( uint8_t ) ~tcpTCP_FLAG_PSH ); + pxProtocolHeaders->xTCPHeader.ucTCPOffset = ( uint8_t ) ( ( ipSIZE_OF_TCP_HEADER + uxOptionsLength ) << 2 ); /*_RB_ "2" needs comment. */ + + pxProtocolHeaders->xTCPHeader.ucTCPFlags |= ( uint8_t ) tcpTCP_FLAG_ACK; + + if( lDataLen != 0L ) + { + pxProtocolHeaders->xTCPHeader.ucTCPFlags |= ( uint8_t ) tcpTCP_FLAG_PSH; + } + + uxIntermediateResult = uxIPHeaderSizeSocket( pxSocket ) + ipSIZE_OF_TCP_HEADER + uxOptionsLength; + lDataLen += ( int32_t ) uxIntermediateResult; + } + + return lDataLen; + } + /*-----------------------------------------------------------*/ + +/** + * @brief Calculate after how much time this socket needs to be checked again. + * + * @param[in] pxSocket: The socket to be checked. + * + * @return The number of clock ticks before the timer expires. + */ + static TickType_t prvTCPNextTimeout( FreeRTOS_Socket_t * pxSocket ) + { + TickType_t ulDelayMs = ( TickType_t ) tcpMAXIMUM_TCP_WAKEUP_TIME_MS; + + if( pxSocket->u.xTCP.ucTCPState == ( uint8_t ) eCONNECT_SYN ) + { + /* The socket is actively connecting to a peer. */ + if( pxSocket->u.xTCP.bits.bConnPrepared != pdFALSE_UNSIGNED ) + { + /* Ethernet address has been found, use progressive timeout for + * active connect(). */ + if( pxSocket->u.xTCP.ucRepCount < 3U ) + { + ulDelayMs = ( 3000UL << ( pxSocket->u.xTCP.ucRepCount - 1U ) ); + } + else + { + ulDelayMs = 11000UL; + } + } + else + { + /* Still in the ARP phase: check every half second. */ + ulDelayMs = 500UL; + } + + FreeRTOS_debug_printf( ( "Connect[%lxip:%u]: next timeout %u: %lu ms\n", + pxSocket->u.xTCP.ulRemoteIP, pxSocket->u.xTCP.usRemotePort, + pxSocket->u.xTCP.ucRepCount, ulDelayMs ) ); + pxSocket->u.xTCP.usTimeout = ( uint16_t ) ipMS_TO_MIN_TICKS( ulDelayMs ); + } + else if( pxSocket->u.xTCP.usTimeout == 0U ) + { + /* Let the sliding window mechanism decide what time-out is appropriate. */ + BaseType_t xResult = xTCPWindowTxHasData( &pxSocket->u.xTCP.xTCPWindow, pxSocket->u.xTCP.ulWindowSize, &ulDelayMs ); + + if( ulDelayMs == 0U ) + { + if( xResult != ( BaseType_t ) 0 ) + { + ulDelayMs = 1UL; + } + else + { + ulDelayMs = tcpMAXIMUM_TCP_WAKEUP_TIME_MS; + } + } + else + { + /* ulDelayMs contains the time to wait before a re-transmission. */ + } + + pxSocket->u.xTCP.usTimeout = ( uint16_t ) ipMS_TO_MIN_TICKS( ulDelayMs ); + } + else + { + /* field '.usTimeout' has already been set (by the + * keep-alive/delayed-ACK mechanism). */ + } + + /* Return the number of clock ticks before the timer expires. */ + return ( TickType_t ) pxSocket->u.xTCP.usTimeout; + } + /*-----------------------------------------------------------*/ + +/** + * @brief The API FreeRTOS_send() adds data to the TX stream. Add + * this data to the windowing system to it can be transmitted. + * + * @param[in] pxSocket: The socket owning the connection. + */ + static void prvTCPAddTxData( FreeRTOS_Socket_t * pxSocket ) + { + int32_t lCount, lLength; + + /* A txStream has been created already, see if the socket has new data for + * the sliding window. + * + * uxStreamBufferMidSpace() returns the distance between rxHead and rxMid. It + * contains new Tx data which has not been passed to the sliding window yet. + * The oldest data not-yet-confirmed can be found at rxTail. */ + lLength = ( int32_t ) uxStreamBufferMidSpace( pxSocket->u.xTCP.txStream ); + + if( lLength > 0 ) + { + /* All data between txMid and rxHead will now be passed to the sliding + * window manager, so it can start transmitting them. + * + * Hand over the new data to the sliding window handler. It will be + * split-up in chunks of 1460 bytes each (or less, depending on + * ipconfigTCP_MSS). */ + lCount = lTCPWindowTxAdd( &pxSocket->u.xTCP.xTCPWindow, + ( uint32_t ) lLength, + ( int32_t ) pxSocket->u.xTCP.txStream->uxMid, + ( int32_t ) pxSocket->u.xTCP.txStream->LENGTH ); + + /* Move the rxMid pointer forward up to rxHead. */ + if( lCount > 0 ) + { + vStreamBufferMoveMid( pxSocket->u.xTCP.txStream, ( size_t ) lCount ); + } + } + } + /*-----------------------------------------------------------*/ + +/** + * @brief prvTCPHandleFin() will be called to handle connection closure. The + * closure starts when either a FIN has been received and accepted, + * or when the socket has sent a FIN flag to the peer. Before being + * called, it has been checked that both reception and transmission + * are complete. + * + * @param[in] pxSocket: Socket owning the the connection. + * @param[in] pxNetworkBuffer: The network buffer carrying the TCP packet. + * + * @return Length of the packet to be sent. + */ + static BaseType_t prvTCPHandleFin( FreeRTOS_Socket_t * pxSocket, + const NetworkBufferDescriptor_t * pxNetworkBuffer ) + { + /* Map the ethernet buffer onto the ProtocolHeader_t struct for easy access to the fields. */ + ProtocolHeaders_t * pxProtocolHeaders = ipCAST_PTR_TO_TYPE_PTR( ProtocolHeaders_t, + &( pxNetworkBuffer->pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER + xIPHeaderSize( pxNetworkBuffer ) ] ) ); + TCPHeader_t * pxTCPHeader = &( pxProtocolHeaders->xTCPHeader ); + uint8_t ucIntermediateResult = 0, ucTCPFlags = pxTCPHeader->ucTCPFlags; + TCPWindow_t * pxTCPWindow = &pxSocket->u.xTCP.xTCPWindow; + BaseType_t xSendLength = 0; + uint32_t ulAckNr = FreeRTOS_ntohl( pxTCPHeader->ulAckNr ); + + if( ( ucTCPFlags & tcpTCP_FLAG_FIN ) != 0U ) + { + pxTCPWindow->rx.ulCurrentSequenceNumber = pxTCPWindow->rx.ulFINSequenceNumber + 1U; + } + + if( pxSocket->u.xTCP.bits.bFinSent == pdFALSE_UNSIGNED ) + { + /* We haven't yet replied with a FIN, do so now. */ + pxTCPWindow->tx.ulFINSequenceNumber = pxTCPWindow->tx.ulCurrentSequenceNumber; + pxSocket->u.xTCP.bits.bFinSent = pdTRUE_UNSIGNED; + } + else + { + /* We did send a FIN already, see if it's ACK'd. */ + if( ulAckNr == ( pxTCPWindow->tx.ulFINSequenceNumber + 1UL ) ) + { + pxSocket->u.xTCP.bits.bFinAcked = pdTRUE_UNSIGNED; + } + } + + if( pxSocket->u.xTCP.bits.bFinAcked == pdFALSE_UNSIGNED ) + { + pxTCPWindow->tx.ulCurrentSequenceNumber = pxTCPWindow->tx.ulFINSequenceNumber; + pxTCPHeader->ucTCPFlags = ( uint8_t ) tcpTCP_FLAG_ACK | ( uint8_t ) tcpTCP_FLAG_FIN; + + /* And wait for the final ACK. */ + vTCPStateChange( pxSocket, eLAST_ACK ); + } + else + { + /* Our FIN has been ACK'd, the outgoing sequence number is now fixed. */ + pxTCPWindow->tx.ulCurrentSequenceNumber = pxTCPWindow->tx.ulFINSequenceNumber + 1U; + + if( pxSocket->u.xTCP.bits.bFinRecv == pdFALSE_UNSIGNED ) + { + /* We have sent out a FIN but the peer hasn't replied with a FIN + * yet. Do nothing for the moment. */ + pxTCPHeader->ucTCPFlags = 0U; + } + else + { + if( pxSocket->u.xTCP.bits.bFinLast == pdFALSE_UNSIGNED ) + { + /* This is the third of the three-way hand shake: the last + * ACK. */ + pxTCPHeader->ucTCPFlags = tcpTCP_FLAG_ACK; + } + else + { + /* The other party started the closure, so we just wait for the + * last ACK. */ + pxTCPHeader->ucTCPFlags = 0U; + } + + /* And wait for the user to close this socket. */ + vTCPStateChange( pxSocket, eCLOSE_WAIT ); + } + } + + pxTCPWindow->ulOurSequenceNumber = pxTCPWindow->tx.ulCurrentSequenceNumber; + + if( pxTCPHeader->ucTCPFlags != 0U ) + { + ucIntermediateResult = uxIPHeaderSizeSocket( pxSocket ) + ipSIZE_OF_TCP_HEADER + pxTCPWindow->ucOptionLength; + xSendLength = ( BaseType_t ) ucIntermediateResult; + } + + pxTCPHeader->ucTCPOffset = ( uint8_t ) ( ( ipSIZE_OF_TCP_HEADER + pxTCPWindow->ucOptionLength ) << 2 ); + + if( xTCPWindowLoggingLevel != 0 ) + { + FreeRTOS_debug_printf( ( "TCP: send FIN+ACK (ack %lu, cur/nxt %lu/%lu) ourSeqNr %lu | Rx %lu\n", + ulAckNr - pxTCPWindow->tx.ulFirstSequenceNumber, + pxTCPWindow->tx.ulCurrentSequenceNumber - pxTCPWindow->tx.ulFirstSequenceNumber, + pxTCPWindow->ulNextTxSequenceNumber - pxTCPWindow->tx.ulFirstSequenceNumber, + pxTCPWindow->ulOurSequenceNumber - pxTCPWindow->tx.ulFirstSequenceNumber, + pxTCPWindow->rx.ulCurrentSequenceNumber - pxTCPWindow->rx.ulFirstSequenceNumber ) ); + } + + return xSendLength; + } + /*-----------------------------------------------------------*/ + +/** + * @brief prvCheckRxData(): called from prvTCPHandleState(). The + * first thing that will be done is find the TCP payload data + * and check the length of this data. + * + * @param[in] pxNetworkBuffer: The network buffer holding the received data. + * @param[out] ppucRecvData: It will point to first byte of the TCP payload. + * + * @return Length of the received buffer. + */ + static BaseType_t prvCheckRxData( const NetworkBufferDescriptor_t * pxNetworkBuffer, + uint8_t ** ppucRecvData ) + { + /* Map the ethernet buffer onto the ProtocolHeader_t struct for easy access to the fields. */ + const ProtocolHeaders_t * pxProtocolHeaders = ipCAST_PTR_TO_TYPE_PTR( ProtocolHeaders_t, + &( pxNetworkBuffer->pucEthernetBuffer[ ( size_t ) ipSIZE_OF_ETH_HEADER + xIPHeaderSize( pxNetworkBuffer ) ] ) ); + const TCPHeader_t * pxTCPHeader = &( pxProtocolHeaders->xTCPHeader ); + int32_t lLength, lTCPHeaderLength, lReceiveLength, lUrgentLength; + + /* Map the buffer onto an IPHeader_t struct for easy access to fields. */ + const IPHeader_t * pxIPHeader = ipCAST_CONST_PTR_TO_CONST_TYPE_PTR( IPHeader_t, &( pxNetworkBuffer->pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER ] ) ); + const size_t xIPHeaderLength = ipSIZE_OF_IPv4_HEADER; + uint16_t usLength; + uint8_t ucIntermediateResult = 0; + + /* Determine the length and the offset of the user-data sent to this + * node. + * + * The size of the TCP header is given in a multiple of 4-byte words (single + * byte, needs no ntoh() translation). A shift-right 2: is the same as + * (offset >> 4) * 4. */ + ucIntermediateResult = ( pxTCPHeader->ucTCPOffset & tcpVALID_BITS_IN_TCP_OFFSET_BYTE ) >> 2; + lTCPHeaderLength = ( int32_t ) ucIntermediateResult; + + /* Let pucRecvData point to the first byte received. */ + *ppucRecvData = &( pxNetworkBuffer->pucEthernetBuffer[ ( size_t ) ipSIZE_OF_ETH_HEADER + xIPHeaderLength + ( size_t ) lTCPHeaderLength ] ); + + /* Calculate lReceiveLength - the length of the TCP data received. This is + * equal to the total packet length minus: + * ( LinkLayer length (14) + IP header length (20) + size of TCP header(20 +) ).*/ + lReceiveLength = ipNUMERIC_CAST( int32_t, pxNetworkBuffer->xDataLength ) - ( int32_t ) ipSIZE_OF_ETH_HEADER; + + usLength = FreeRTOS_htons( pxIPHeader->usLength ); + lLength = ( int32_t ) usLength; + + if( lReceiveLength > lLength ) + { + /* More bytes were received than the reported length, often because of + * padding bytes at the end. */ + lReceiveLength = lLength; + } + + /* Subtract the size of the TCP and IP headers and the actual data size is + * known. */ + if( lReceiveLength > ( lTCPHeaderLength + ( int32_t ) xIPHeaderLength ) ) + { + lReceiveLength -= ( lTCPHeaderLength + ( int32_t ) xIPHeaderLength ); + } + else + { + lReceiveLength = 0; + } + + /* Urgent Pointer: + * This field communicates the current value of the urgent pointer as a + * positive offset from the sequence number in this segment. The urgent + * pointer points to the sequence number of the octet following the urgent + * data. This field is only be interpreted in segments with the URG control + * bit set. */ + if( ( pxTCPHeader->ucTCPFlags & tcpTCP_FLAG_URG ) != 0U ) + { + /* Although we ignore the urgent data, we have to skip it. */ + lUrgentLength = ( int32_t ) FreeRTOS_htons( pxTCPHeader->usUrgent ); + *ppucRecvData += lUrgentLength; + lReceiveLength -= FreeRTOS_min_int32( lReceiveLength, lUrgentLength ); + } + + return ( BaseType_t ) lReceiveLength; + } + /*-----------------------------------------------------------*/ + +/** + * @brief prvStoreRxData(): called from prvTCPHandleState(). + * The second thing is to do is check if the payload data may + * be accepted. If so, they will be added to the reception queue. + * + * @param[in] pxSocket: The socket owning the connection. + * @param[in] pucRecvData: Pointer to received data. + * @param[in] pxNetworkBuffer: The network buffer descriptor. + * @param[in] ulReceiveLength: The length of the received data. + * + * @return 0 on success, -1 on failure of storing data. + */ + static BaseType_t prvStoreRxData( FreeRTOS_Socket_t * pxSocket, + const uint8_t * pucRecvData, + NetworkBufferDescriptor_t * pxNetworkBuffer, + uint32_t ulReceiveLength ) + { + /* Map the ethernet buffer onto the ProtocolHeader_t struct for easy access to the fields. */ + const ProtocolHeaders_t * pxProtocolHeaders = ipCAST_CONST_PTR_TO_CONST_TYPE_PTR( ProtocolHeaders_t, + &( pxNetworkBuffer->pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER + xIPHeaderSize( pxNetworkBuffer ) ] ) ); + const TCPHeader_t * pxTCPHeader = &pxProtocolHeaders->xTCPHeader; + TCPWindow_t * pxTCPWindow = &pxSocket->u.xTCP.xTCPWindow; + uint32_t ulSequenceNumber, ulSpace; + int32_t lOffset, lStored; + BaseType_t xResult = 0; + + ulSequenceNumber = FreeRTOS_ntohl( pxTCPHeader->ulSequenceNumber ); + + if( ( ulReceiveLength > 0U ) && ( pxSocket->u.xTCP.ucTCPState >= ( uint8_t ) eSYN_RECEIVED ) ) + { + /* See if way may accept the data contents and forward it to the socket + * owner. + * + * If it can't be "accept"ed it may have to be stored and send a selective + * ack (SACK) option to confirm it. In that case, lTCPAddRxdata() will be + * called later to store an out-of-order packet (in case lOffset is + * negative). */ + if( pxSocket->u.xTCP.rxStream != NULL ) + { + ulSpace = ( uint32_t ) uxStreamBufferGetSpace( pxSocket->u.xTCP.rxStream ); + } + else + { + ulSpace = ( uint32_t ) pxSocket->u.xTCP.uxRxStreamSize; + } + + lOffset = lTCPWindowRxCheck( pxTCPWindow, ulSequenceNumber, ulReceiveLength, ulSpace ); + + if( lOffset >= 0 ) + { + /* New data has arrived and may be made available to the user. See + * if the head marker in rxStream may be advanced, only if lOffset == 0. + * In case the low-water mark is reached, bLowWater will be set + * "low-water" here stands for "little space". */ + lStored = lTCPAddRxdata( pxSocket, ( uint32_t ) lOffset, pucRecvData, ulReceiveLength ); + + if( lStored != ( int32_t ) ulReceiveLength ) + { + FreeRTOS_debug_printf( ( "lTCPAddRxdata: stored %ld / %lu bytes? ?\n", lStored, ulReceiveLength ) ); + + /* Received data could not be stored. The socket's flag + * bMallocError has been set. The socket now has the status + * eCLOSE_WAIT and a RST packet will be sent back. */ + ( void ) prvTCPSendReset( pxNetworkBuffer ); + xResult = -1; + } + } + + /* After a missing packet has come in, higher packets may be passed to + * the user. */ + #if ( ipconfigUSE_TCP_WIN == 1 ) + { + /* Now lTCPAddRxdata() will move the rxHead pointer forward + * so data becomes available to the user immediately + * In case the low-water mark is reached, bLowWater will be set. */ + if( ( xResult == 0 ) && ( pxTCPWindow->ulUserDataLength > 0UL ) ) + { + ( void ) lTCPAddRxdata( pxSocket, 0UL, NULL, pxTCPWindow->ulUserDataLength ); + pxTCPWindow->ulUserDataLength = 0; + } + } + #endif /* ipconfigUSE_TCP_WIN */ + } + else + { + pxTCPWindow->ucOptionLength = 0U; + } + + return xResult; + } + /*-----------------------------------------------------------*/ + +/** + * @brief Set the TCP options (if any) for the outgoing packet. + * + * @param[in] pxSocket: The socket owning the connection. + * @param[in] pxNetworkBuffer: The network buffer holding the packet. + * + * @return Length of the TCP options after they are set. + */ + static UBaseType_t prvSetOptions( FreeRTOS_Socket_t * pxSocket, + const NetworkBufferDescriptor_t * pxNetworkBuffer ) + { + /* Map the ethernet buffer onto the ProtocolHeader_t struct for easy access to the fields. */ + ProtocolHeaders_t * pxProtocolHeaders = ipCAST_PTR_TO_TYPE_PTR( ProtocolHeaders_t, + &( pxNetworkBuffer->pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER + xIPHeaderSize( pxNetworkBuffer ) ] ) ); + TCPHeader_t * pxTCPHeader = &pxProtocolHeaders->xTCPHeader; + const TCPWindow_t * pxTCPWindow = &pxSocket->u.xTCP.xTCPWindow; + UBaseType_t uxOptionsLength = pxTCPWindow->ucOptionLength; + /* memcpy() helper variables for MISRA Rule 21.15 compliance*/ + const void * pvCopySource; + void * pvCopyDest; + + #if ( ipconfigUSE_TCP_WIN == 1 ) + if( uxOptionsLength != 0U ) + { + /* TCP options must be sent because a packet which is out-of-order + * was received. */ + if( xTCPWindowLoggingLevel >= 0 ) + { + FreeRTOS_debug_printf( ( "SACK[%d,%d]: optlen %lu sending %lu - %lu\n", + pxSocket->usLocalPort, + pxSocket->u.xTCP.usRemotePort, + uxOptionsLength, + FreeRTOS_ntohl( pxTCPWindow->ulOptionsData[ 1 ] ) - pxSocket->u.xTCP.xTCPWindow.rx.ulFirstSequenceNumber, + FreeRTOS_ntohl( pxTCPWindow->ulOptionsData[ 2 ] ) - pxSocket->u.xTCP.xTCPWindow.rx.ulFirstSequenceNumber ) ); + } + + /* + * Use helper variables for memcpy() source & dest to remain + * compliant with MISRA Rule 21.15. These should be + * optimized away. + */ + pvCopySource = pxTCPWindow->ulOptionsData; + pvCopyDest = pxTCPHeader->ucOptdata; + ( void ) memcpy( pvCopyDest, pvCopySource, ( size_t ) uxOptionsLength ); + + /* The header length divided by 4, goes into the higher nibble, + * effectively a shift-left 2. */ + pxTCPHeader->ucTCPOffset = ( uint8_t ) ( ( ipSIZE_OF_TCP_HEADER + uxOptionsLength ) << 2 ); + } + else + #endif /* ipconfigUSE_TCP_WIN */ + + if( ( pxSocket->u.xTCP.ucTCPState >= ( EventBits_t ) eESTABLISHED ) && ( pxSocket->u.xTCP.bits.bMssChange != pdFALSE_UNSIGNED ) ) + { + /* TCP options must be sent because the MSS has changed. */ + pxSocket->u.xTCP.bits.bMssChange = pdFALSE_UNSIGNED; + + if( xTCPWindowLoggingLevel >= 0 ) + { + FreeRTOS_debug_printf( ( "MSS: sending %d\n", pxSocket->u.xTCP.usCurMSS ) ); + } + + pxTCPHeader->ucOptdata[ 0 ] = tcpTCP_OPT_MSS; + pxTCPHeader->ucOptdata[ 1 ] = tcpTCP_OPT_MSS_LEN; + pxTCPHeader->ucOptdata[ 2 ] = ( uint8_t ) ( ( pxSocket->u.xTCP.usCurMSS ) >> 8 ); + pxTCPHeader->ucOptdata[ 3 ] = ( uint8_t ) ( ( pxSocket->u.xTCP.usCurMSS ) & 0xffU ); + uxOptionsLength = 4U; + pxTCPHeader->ucTCPOffset = ( uint8_t ) ( ( ipSIZE_OF_TCP_HEADER + uxOptionsLength ) << 2 ); + } + else + { + /* Nothing. */ + } + + return uxOptionsLength; + } + /*-----------------------------------------------------------*/ + +/** + * @brief prvHandleSynReceived(): called from prvTCPHandleState(). Called + * from the states: eSYN_RECEIVED and eCONNECT_SYN. If the flags + * received are correct, the socket will move to eESTABLISHED. + * + * @param[in] pxSocket: The socket handling the connection. + * @param[in] pxNetworkBuffer: The pointer to the network buffer carrying + * the packet. + * @param[in] ulReceiveLength: Length in bytes of the data received. + * @param[in] uxOptionsLength: Length of the TCP options in bytes. + * + * @return Length of the data to be sent. + */ + static BaseType_t prvHandleSynReceived( FreeRTOS_Socket_t * pxSocket, + const NetworkBufferDescriptor_t * pxNetworkBuffer, + uint32_t ulReceiveLength, + UBaseType_t uxOptionsLength ) + { + /* Map the ethernet buffer onto the ProtocolHeader_t struct for easy access to the fields. */ + ProtocolHeaders_t * pxProtocolHeaders = ipCAST_PTR_TO_TYPE_PTR( ProtocolHeaders_t, + &( pxNetworkBuffer->pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER + uxIPHeaderSizeSocket( pxSocket ) ] ) ); + TCPHeader_t * pxTCPHeader = &pxProtocolHeaders->xTCPHeader; + TCPWindow_t * pxTCPWindow = &pxSocket->u.xTCP.xTCPWindow; + uint8_t ucTCPFlags = pxTCPHeader->ucTCPFlags; + uint32_t ulSequenceNumber = FreeRTOS_ntohl( pxTCPHeader->ulSequenceNumber ); + BaseType_t xSendLength = 0; + UBaseType_t uxIntermediateResult = 0U; + + /* Either expect a ACK or a SYN+ACK. */ + uint8_t ucExpect = tcpTCP_FLAG_ACK; + const uint8_t ucFlagsMask = tcpTCP_FLAG_ACK | tcpTCP_FLAG_RST | tcpTCP_FLAG_SYN | tcpTCP_FLAG_FIN; + + if( pxSocket->u.xTCP.ucTCPState == ( uint8_t ) eCONNECT_SYN ) + { + ucExpect |= tcpTCP_FLAG_SYN; + } + + if( ( ucTCPFlags & ucFlagsMask ) != ucExpect ) + { + /* eSYN_RECEIVED: flags 0010 expected, not 0002. */ + /* eSYN_RECEIVED: flags ACK expected, not SYN. */ + FreeRTOS_debug_printf( ( "%s: flags %04X expected, not %04X\n", + ( pxSocket->u.xTCP.ucTCPState == ( uint8_t ) eSYN_RECEIVED ) ? "eSYN_RECEIVED" : "eCONNECT_SYN", + ucExpect, ucTCPFlags ) ); + + /* In case pxSocket is not yet owned by the application, a closure + * of the socket will be scheduled for the next cycle. */ + vTCPStateChange( pxSocket, eCLOSE_WAIT ); + + /* Send RST with the expected sequence and ACK numbers, + * otherwise the packet will be ignored. */ + pxTCPWindow->ulOurSequenceNumber = FreeRTOS_htonl( pxTCPHeader->ulAckNr ); + pxTCPWindow->rx.ulCurrentSequenceNumber = ulSequenceNumber; + + pxTCPHeader->ucTCPFlags |= tcpTCP_FLAG_RST; + + uxIntermediateResult = uxIPHeaderSizeSocket( pxSocket ) + ipSIZE_OF_TCP_HEADER + uxOptionsLength; + xSendLength = ( BaseType_t ) uxIntermediateResult; + + pxTCPHeader->ucTCPOffset = ( uint8_t ) ( ( ipSIZE_OF_TCP_HEADER + uxOptionsLength ) << 2 ); + } + else + { + pxTCPWindow->usPeerPortNumber = pxSocket->u.xTCP.usRemotePort; + pxTCPWindow->usOurPortNumber = pxSocket->usLocalPort; + + if( pxSocket->u.xTCP.ucTCPState == ( uint8_t ) eCONNECT_SYN ) + { + /* Map the Last packet onto the ProtocolHeader_t struct for easy access to the fields. */ + ProtocolHeaders_t * pxLastHeaders = ipCAST_PTR_TO_TYPE_PTR( ProtocolHeaders_t, + &( pxSocket->u.xTCP.xPacket.u.ucLastPacket[ ipSIZE_OF_ETH_HEADER + uxIPHeaderSizeSocket( pxSocket ) ] ) ); + + /* Clear the SYN flag in lastPacket. */ + pxLastHeaders->xTCPHeader.ucTCPFlags = tcpTCP_FLAG_ACK; + pxProtocolHeaders->xTCPHeader.ucTCPFlags = tcpTCP_FLAG_ACK; + + /* This socket was the one connecting actively so now perform the + * synchronisation. */ + vTCPWindowInit( &pxSocket->u.xTCP.xTCPWindow, + ulSequenceNumber, pxSocket->u.xTCP.xTCPWindow.ulOurSequenceNumber, ( uint32_t ) pxSocket->u.xTCP.usCurMSS ); + pxTCPWindow->rx.ulHighestSequenceNumber = ulSequenceNumber + 1U; + pxTCPWindow->rx.ulCurrentSequenceNumber = ulSequenceNumber + 1U; + pxTCPWindow->tx.ulCurrentSequenceNumber++; /* because we send a TCP_SYN [ | TCP_ACK ]; */ + pxTCPWindow->ulNextTxSequenceNumber++; + } + else if( ulReceiveLength == 0U ) + { + pxTCPWindow->rx.ulCurrentSequenceNumber = ulSequenceNumber; + } + else + { + /* Nothing. */ + } + + /* The SYN+ACK has been confirmed, increase the next sequence number by + * 1. */ + pxTCPWindow->ulOurSequenceNumber = pxTCPWindow->tx.ulFirstSequenceNumber + 1U; + + #if ( ipconfigUSE_TCP_WIN == 1 ) + { + FreeRTOS_debug_printf( ( "TCP: %s %d => %lxip:%d set ESTAB (scaling %u)\n", + ( pxSocket->u.xTCP.ucTCPState == ( uint8_t ) eCONNECT_SYN ) ? "active" : "passive", + pxSocket->usLocalPort, + pxSocket->u.xTCP.ulRemoteIP, + pxSocket->u.xTCP.usRemotePort, + ( unsigned ) pxSocket->u.xTCP.bits.bWinScaling ) ); + } + #endif /* ipconfigUSE_TCP_WIN */ + + if( ( pxSocket->u.xTCP.ucTCPState == ( EventBits_t ) eCONNECT_SYN ) || ( ulReceiveLength != 0UL ) ) + { + pxTCPHeader->ucTCPFlags = tcpTCP_FLAG_ACK; + + uxIntermediateResult = uxIPHeaderSizeSocket( pxSocket ) + ( size_t ) ipSIZE_OF_TCP_HEADER + uxOptionsLength; + xSendLength = ( BaseType_t ) uxIntermediateResult; + pxTCPHeader->ucTCPOffset = ( uint8_t ) ( ( ipSIZE_OF_TCP_HEADER + uxOptionsLength ) << 2 ); + } + + #if ( ipconfigUSE_TCP_WIN != 0 ) + { + if( pxSocket->u.xTCP.bits.bWinScaling == pdFALSE_UNSIGNED ) + { + /* The other party did not send a scaling factor. + * A shifting factor in this side must be canceled. */ + pxSocket->u.xTCP.ucMyWinScaleFactor = 0; + pxSocket->u.xTCP.ucPeerWinScaleFactor = 0; + } + } + #endif /* ipconfigUSE_TCP_WIN */ + + /* This was the third step of connecting: SYN, SYN+ACK, ACK so now the + * connection is established. */ + vTCPStateChange( pxSocket, eESTABLISHED ); + } + + return xSendLength; + } + /*-----------------------------------------------------------*/ + +/** + * @brief prvHandleEstablished(): called from prvTCPHandleState() + * Called if the status is eESTABLISHED. Data reception has been handled + * earlier. Here the ACK's from peer will be checked, and if a FIN is received, + * the code will check if it may be accepted, i.e. if all expected data has been + * completely received. + * + * @param[in] pxSocket: The socket owning the connection. + * @param[in,out] ppxNetworkBuffer: Pointer to pointer to the network buffer. + * @param[in] ulReceiveLength: The length of the received packet. + * @param[in] uxOptionsLength: Length of TCP options. + * + * @return The send length of the packet to be sent. + */ + static BaseType_t prvHandleEstablished( FreeRTOS_Socket_t * pxSocket, + NetworkBufferDescriptor_t ** ppxNetworkBuffer, + uint32_t ulReceiveLength, + UBaseType_t uxOptionsLength ) + { + /* Map the buffer onto the ProtocolHeader_t struct for easy access to the fields. */ + ProtocolHeaders_t * pxProtocolHeaders = ipCAST_PTR_TO_TYPE_PTR( ProtocolHeaders_t, + &( ( *ppxNetworkBuffer )->pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER + uxIPHeaderSizeSocket( pxSocket ) ] ) ); + TCPHeader_t * pxTCPHeader = &pxProtocolHeaders->xTCPHeader; + TCPWindow_t * pxTCPWindow = &pxSocket->u.xTCP.xTCPWindow; + uint8_t ucTCPFlags = pxTCPHeader->ucTCPFlags; + uint32_t ulSequenceNumber = FreeRTOS_ntohl( pxTCPHeader->ulSequenceNumber ), ulCount, ulIntermediateResult = 0; + BaseType_t xSendLength = 0, xMayClose = pdFALSE, bRxComplete, bTxDone; + int32_t lDistance, lSendResult; + uint16_t usWindow; + UBaseType_t uxIntermediateResult = 0; + + /* Remember the window size the peer is advertising. */ + usWindow = FreeRTOS_ntohs( pxTCPHeader->usWindow ); + pxSocket->u.xTCP.ulWindowSize = ( uint32_t ) usWindow; + #if ( ipconfigUSE_TCP_WIN != 0 ) + { + pxSocket->u.xTCP.ulWindowSize = + ( pxSocket->u.xTCP.ulWindowSize << pxSocket->u.xTCP.ucPeerWinScaleFactor ); + } + #endif /* ipconfigUSE_TCP_WIN */ + + if( ( ucTCPFlags & ( uint8_t ) tcpTCP_FLAG_ACK ) != 0U ) + { + ulCount = ulTCPWindowTxAck( pxTCPWindow, FreeRTOS_ntohl( pxTCPHeader->ulAckNr ) ); + + /* ulTCPWindowTxAck() returns the number of bytes which have been acked, + * starting at 'tx.ulCurrentSequenceNumber'. Advance the tail pointer in + * txStream. */ + if( ( pxSocket->u.xTCP.txStream != NULL ) && ( ulCount > 0U ) ) + { + /* Just advancing the tail index, 'ulCount' bytes have been + * confirmed, and because there is new space in the txStream, the + * user/owner should be woken up. */ + /* _HT_ : only in case the socket's waiting? */ + if( uxStreamBufferGet( pxSocket->u.xTCP.txStream, 0U, NULL, ( size_t ) ulCount, pdFALSE ) != 0U ) + { + pxSocket->xEventBits |= ( EventBits_t ) eSOCKET_SEND; + + #if ipconfigSUPPORT_SELECT_FUNCTION == 1 + { + if( ( pxSocket->xSelectBits & ( ( EventBits_t ) eSELECT_WRITE ) ) != 0U ) + { + pxSocket->xEventBits |= ( ( EventBits_t ) eSELECT_WRITE ) << SOCKET_EVENT_BIT_COUNT; + } + } + #endif + + /* In case the socket owner has installed an OnSent handler, + * call it now. */ + #if ( ipconfigUSE_CALLBACKS == 1 ) + { + if( ipconfigIS_VALID_PROG_ADDRESS( pxSocket->u.xTCP.pxHandleSent ) ) + { + pxSocket->u.xTCP.pxHandleSent( ( Socket_t ) pxSocket, ulCount ); + } + } + #endif /* ipconfigUSE_CALLBACKS == 1 */ + } + } + } + + /* If this socket has a stream for transmission, add the data to the + * outgoing segment(s). */ + if( pxSocket->u.xTCP.txStream != NULL ) + { + prvTCPAddTxData( pxSocket ); + } + + pxSocket->u.xTCP.xTCPWindow.ulOurSequenceNumber = pxTCPWindow->tx.ulCurrentSequenceNumber; + + if( ( pxSocket->u.xTCP.bits.bFinAccepted != pdFALSE_UNSIGNED ) || ( ( ucTCPFlags & ( uint8_t ) tcpTCP_FLAG_FIN ) != 0U ) ) + { + /* Peer is requesting to stop, see if we're really finished. */ + xMayClose = pdTRUE; + + /* Checks are only necessary if we haven't sent a FIN yet. */ + if( pxSocket->u.xTCP.bits.bFinSent == pdFALSE_UNSIGNED ) + { + /* xTCPWindowTxDone returns true when all Tx queues are empty. */ + bRxComplete = xTCPWindowRxEmpty( pxTCPWindow ); + bTxDone = xTCPWindowTxDone( pxTCPWindow ); + + if( ( bRxComplete == 0 ) || ( bTxDone == 0 ) ) + { + /* Refusing FIN: Rx incomplete 1 optlen 4 tx done 1. */ + FreeRTOS_debug_printf( ( "Refusing FIN[%u,%u]: RxCompl %lu tx done %ld\n", + pxSocket->usLocalPort, + pxSocket->u.xTCP.usRemotePort, + bRxComplete, bTxDone ) ); + xMayClose = pdFALSE; + } + else + { + ulIntermediateResult = ulSequenceNumber + ulReceiveLength - pxTCPWindow->rx.ulCurrentSequenceNumber; + lDistance = ( int32_t ) ulIntermediateResult; + + if( lDistance > 1 ) + { + FreeRTOS_debug_printf( ( "Refusing FIN: Rx not complete %ld (cur %lu high %lu)\n", + lDistance, pxTCPWindow->rx.ulCurrentSequenceNumber - pxTCPWindow->rx.ulFirstSequenceNumber, + pxTCPWindow->rx.ulHighestSequenceNumber - pxTCPWindow->rx.ulFirstSequenceNumber ) ); + + xMayClose = pdFALSE; + } + } + } + + if( xTCPWindowLoggingLevel > 0 ) + { + FreeRTOS_debug_printf( ( "TCP: FIN received, mayClose = %ld (Rx %lu Len %ld, Tx %lu)\n", + xMayClose, ulSequenceNumber - pxSocket->u.xTCP.xTCPWindow.rx.ulFirstSequenceNumber, ulReceiveLength, + pxTCPWindow->tx.ulCurrentSequenceNumber - pxSocket->u.xTCP.xTCPWindow.tx.ulFirstSequenceNumber ) ); + } + + if( xMayClose != pdFALSE ) + { + pxSocket->u.xTCP.bits.bFinAccepted = pdTRUE_UNSIGNED; + xSendLength = prvTCPHandleFin( pxSocket, *ppxNetworkBuffer ); + } + } + + if( xMayClose == pdFALSE ) + { + pxTCPHeader->ucTCPFlags = tcpTCP_FLAG_ACK; + + if( ulReceiveLength != 0U ) + { + uxIntermediateResult = uxIPHeaderSizeSocket( pxSocket ) + ipSIZE_OF_TCP_HEADER + uxOptionsLength; + xSendLength = ( BaseType_t ) uxIntermediateResult; + /* TCP-offset equals '( ( length / 4 ) << 4 )', resulting in a shift-left 2 */ + pxTCPHeader->ucTCPOffset = ( uint8_t ) ( ( ipSIZE_OF_TCP_HEADER + uxOptionsLength ) << 2 ); + + if( pxSocket->u.xTCP.bits.bFinSent != pdFALSE_UNSIGNED ) + { + pxTCPWindow->tx.ulCurrentSequenceNumber = pxTCPWindow->tx.ulFINSequenceNumber; + } + } + + /* Now get data to be transmitted. */ + + /* _HT_ patch: since the MTU has be fixed at 1500 in stead of 1526, TCP + * can not send-out both TCP options and also a full packet. Sending + * options (SACK) is always more urgent than sending data, which can be + * sent later. */ + if( uxOptionsLength == 0U ) + { + /* prvTCPPrepareSend might allocate a bigger network buffer, if + * necessary. */ + lSendResult = prvTCPPrepareSend( pxSocket, ppxNetworkBuffer, uxOptionsLength ); + + if( lSendResult > 0 ) + { + xSendLength = ( BaseType_t ) lSendResult; + } + } + } + + return xSendLength; + } + /*-----------------------------------------------------------*/ + +/** + * @brief Called from prvTCPHandleState(). There is data to be sent. If + * ipconfigUSE_TCP_WIN is defined, and if only an ACK must be sent, it will be + * checked if it would better be postponed for efficiency. + * + * @param[in] pxSocket: The socket owning the TCP connection. + * @param[in] ppxNetworkBuffer: Pointer to pointer to the network buffer. + * @param[in] ulReceiveLength: The length of the received buffer. + * @param[in] xByteCount: Length of the data to be sent. + * + * @return The number of bytes actually sent. + */ + static BaseType_t prvSendData( FreeRTOS_Socket_t * pxSocket, + NetworkBufferDescriptor_t ** ppxNetworkBuffer, + uint32_t ulReceiveLength, + BaseType_t xByteCount ) + { + /* Map the buffer onto the ProtocolHeader_t struct for easy access to the fields. */ + const ProtocolHeaders_t * pxProtocolHeaders = ipCAST_PTR_TO_TYPE_PTR( ProtocolHeaders_t, + &( ( *ppxNetworkBuffer )->pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER + xIPHeaderSize( *ppxNetworkBuffer ) ] ) ); + const TCPHeader_t * pxTCPHeader = &pxProtocolHeaders->xTCPHeader; + const TCPWindow_t * pxTCPWindow = &pxSocket->u.xTCP.xTCPWindow; + /* Find out what window size we may advertised. */ + int32_t lRxSpace; + BaseType_t xSendLength = xByteCount; + uint32_t ulRxBufferSpace; + + #if ( ipconfigUSE_TCP_WIN == 1 ) + #if ( ipconfigTCP_ACK_EARLIER_PACKET == 0 ) + const int32_t lMinLength = 0; + #else + int32_t lMinLength; + #endif + #endif + + /* Set the time-out field, so that we'll be called by the IP-task in case no + * next message will be received. */ + ulRxBufferSpace = pxSocket->u.xTCP.ulHighestRxAllowed - pxTCPWindow->rx.ulCurrentSequenceNumber; + lRxSpace = ( int32_t ) ulRxBufferSpace; + + #if ipconfigUSE_TCP_WIN == 1 + { + #if ( ipconfigTCP_ACK_EARLIER_PACKET != 0 ) + { + lMinLength = ( ( int32_t ) 2 ) * ( ( int32_t ) pxSocket->u.xTCP.usCurMSS ); + } + #endif /* ipconfigTCP_ACK_EARLIER_PACKET */ + + /* In case we're receiving data continuously, we might postpone sending + * an ACK to gain performance. */ + /* lint e9007 is OK because 'uxIPHeaderSizeSocket()' has no side-effects. */ + if( ( ulReceiveLength > 0U ) && /* Data was sent to this socket. */ + ( lRxSpace >= lMinLength ) && /* There is Rx space for more data. */ + ( pxSocket->u.xTCP.bits.bFinSent == pdFALSE_UNSIGNED ) && /* Not in a closure phase. */ + ( xSendLength == uxIPHeaderSizeSocket( pxSocket ) + ipSIZE_OF_TCP_HEADER ) && /* No Tx data or options to be sent. */ + ( pxSocket->u.xTCP.ucTCPState == ( uint8_t ) eESTABLISHED ) && /* Connection established. */ + ( pxTCPHeader->ucTCPFlags == tcpTCP_FLAG_ACK ) ) /* There are no other flags than an ACK. */ + { + if( pxSocket->u.xTCP.pxAckMessage != *ppxNetworkBuffer ) + { + /* There was still a delayed in queue, delete it. */ + if( pxSocket->u.xTCP.pxAckMessage != NULL ) + { + vReleaseNetworkBufferAndDescriptor( pxSocket->u.xTCP.pxAckMessage ); + } + + pxSocket->u.xTCP.pxAckMessage = *ppxNetworkBuffer; + } + + if( ( ulReceiveLength < ( uint32_t ) pxSocket->u.xTCP.usCurMSS ) || /* Received a small message. */ + ( lRxSpace < ipNUMERIC_CAST( int32_t, 2U * pxSocket->u.xTCP.usCurMSS ) ) ) /* There are less than 2 x MSS space in the Rx buffer. */ + { + pxSocket->u.xTCP.usTimeout = ( uint16_t ) tcpDELAYED_ACK_SHORT_DELAY_MS; + } + else + { + /* Normally a delayed ACK should wait 200 ms for a next incoming + * packet. Only wait 20 ms here to gain performance. A slow ACK + * for full-size message. */ + pxSocket->u.xTCP.usTimeout = ( uint16_t ) ipMS_TO_MIN_TICKS( tcpDELAYED_ACK_LONGER_DELAY_MS ); + } + + if( ( xTCPWindowLoggingLevel > 1 ) && ( ipconfigTCP_MAY_LOG_PORT( pxSocket->usLocalPort ) ) ) + { + FreeRTOS_debug_printf( ( "Send[%u->%u] del ACK %lu SEQ %lu (len %lu) tmout %u d %lu\n", + pxSocket->usLocalPort, + pxSocket->u.xTCP.usRemotePort, + pxTCPWindow->rx.ulCurrentSequenceNumber - pxTCPWindow->rx.ulFirstSequenceNumber, + pxSocket->u.xTCP.xTCPWindow.ulOurSequenceNumber - pxTCPWindow->tx.ulFirstSequenceNumber, + xSendLength, + pxSocket->u.xTCP.usTimeout, lRxSpace ) ); + } + + *ppxNetworkBuffer = NULL; + xSendLength = 0; + } + else if( pxSocket->u.xTCP.pxAckMessage != NULL ) + { + /* As an ACK is not being delayed, remove any earlier delayed ACK + * message. */ + if( pxSocket->u.xTCP.pxAckMessage != *ppxNetworkBuffer ) + { + vReleaseNetworkBufferAndDescriptor( pxSocket->u.xTCP.pxAckMessage ); + } + + pxSocket->u.xTCP.pxAckMessage = NULL; + } + else + { + /* The ack will not be postponed, and there was no stored ack ( in 'pxAckMessage' ). */ + } + } + #else /* if ipconfigUSE_TCP_WIN == 1 */ + { + /* Remove compiler warnings. */ + ( void ) ulReceiveLength; + ( void ) pxTCPHeader; + ( void ) lRxSpace; + } + #endif /* ipconfigUSE_TCP_WIN */ + + if( xSendLength != 0 ) + { + if( ( xTCPWindowLoggingLevel > 1 ) && ( ipconfigTCP_MAY_LOG_PORT( pxSocket->usLocalPort ) ) ) + { + FreeRTOS_debug_printf( ( "Send[%u->%u] imm ACK %lu SEQ %lu (len %lu)\n", + pxSocket->usLocalPort, + pxSocket->u.xTCP.usRemotePort, + pxTCPWindow->rx.ulCurrentSequenceNumber - pxTCPWindow->rx.ulFirstSequenceNumber, + pxTCPWindow->ulOurSequenceNumber - pxTCPWindow->tx.ulFirstSequenceNumber, + xSendLength ) ); + } + + /* Set the parameter 'xReleaseAfterSend' to the value of + * ipconfigZERO_COPY_TX_DRIVER. */ + prvTCPReturnPacket( pxSocket, *ppxNetworkBuffer, ( uint32_t ) xSendLength, ipconfigZERO_COPY_TX_DRIVER ); + #if ( ipconfigZERO_COPY_TX_DRIVER != 0 ) + { + /* The driver has taken ownership of the Network Buffer. */ + *ppxNetworkBuffer = NULL; + } + #endif + } + + return xSendLength; + } + /*-----------------------------------------------------------*/ + +/** + * @brief Check incoming packets for valid data and handle the state of the + * TCP connection and respond according to the situation. + * + * @param[in] pxSocket: The socket whose connection state is being handled. + * @param[in] ppxNetworkBuffer: The network buffer descriptor holding the + * packet received from the peer. + * + * @return If the data is correct and some packet was sent to the peer, then + * the number of bytes sent is returned, or else a negative value is + * returned indicating an error. + * + * @note prvTCPHandleState() is the most important function of this TCP stack + * We've tried to keep it (relatively short) by putting a lot of code in + * the static functions above: + * + * prvCheckRxData() + * prvStoreRxData() + * prvSetOptions() + * prvHandleSynReceived() + * prvHandleEstablished() + * prvSendData() + * + * As these functions are declared static, and they're called from one location + * only, most compilers will inline them, thus avoiding a call and return. + */ + static BaseType_t prvTCPHandleState( FreeRTOS_Socket_t * pxSocket, + NetworkBufferDescriptor_t ** ppxNetworkBuffer ) + { + /* Map the buffer onto the ProtocolHeader_t struct for easy access to the fields. */ + ProtocolHeaders_t * pxProtocolHeaders = ipCAST_PTR_TO_TYPE_PTR( ProtocolHeaders_t, + &( ( *ppxNetworkBuffer )->pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER + xIPHeaderSize( *ppxNetworkBuffer ) ] ) ); + TCPHeader_t * pxTCPHeader = &( pxProtocolHeaders->xTCPHeader ); + BaseType_t xSendLength = 0; + uint32_t ulReceiveLength; /* Number of bytes contained in the TCP message. */ + uint8_t * pucRecvData; + uint32_t ulSequenceNumber = FreeRTOS_ntohl( pxTCPHeader->ulSequenceNumber ); + + /* uxOptionsLength: the size of the options to be sent (always a multiple of + * 4 bytes) + * 1. in the SYN phase, we shall communicate the MSS + * 2. in case of a SACK, Selective ACK, ack a segment which comes in + * out-of-order. */ + UBaseType_t uxOptionsLength = 0U; + uint8_t ucTCPFlags = pxTCPHeader->ucTCPFlags; + TCPWindow_t * pxTCPWindow = &( pxSocket->u.xTCP.xTCPWindow ); + UBaseType_t uxIntermediateResult = 0; + + /* First get the length and the position of the received data, if any. + * pucRecvData will point to the first byte of the TCP payload. */ + ulReceiveLength = ( uint32_t ) prvCheckRxData( *ppxNetworkBuffer, &pucRecvData ); + + if( pxSocket->u.xTCP.ucTCPState >= ( uint8_t ) eESTABLISHED ) + { + if( pxTCPWindow->rx.ulCurrentSequenceNumber == ( ulSequenceNumber + 1UL ) ) + { + /* This is most probably a keep-alive message from peer. Setting + * 'bWinChange' doesn't cause a window-size-change, the flag is used + * here to force sending an immediate ACK. */ + pxSocket->u.xTCP.bits.bWinChange = pdTRUE_UNSIGNED; + } + } + + /* Keep track of the highest sequence number that might be expected within + * this connection. */ + if( ( ( int32_t ) ( ulSequenceNumber + ulReceiveLength - pxTCPWindow->rx.ulHighestSequenceNumber ) ) > 0L ) + { + pxTCPWindow->rx.ulHighestSequenceNumber = ulSequenceNumber + ulReceiveLength; + } + + /* Storing data may result in a fatal error if malloc() fails. */ + if( prvStoreRxData( pxSocket, pucRecvData, *ppxNetworkBuffer, ulReceiveLength ) < 0 ) + { + xSendLength = -1; + } + else + { + uxOptionsLength = prvSetOptions( pxSocket, *ppxNetworkBuffer ); + + if( ( pxSocket->u.xTCP.ucTCPState == ( uint8_t ) eSYN_RECEIVED ) && ( ( ucTCPFlags & ( uint8_t ) tcpTCP_FLAG_CTRL ) == ( uint8_t ) tcpTCP_FLAG_SYN ) ) + { + FreeRTOS_debug_printf( ( "eSYN_RECEIVED: ACK expected, not SYN: peer missed our SYN+ACK\n" ) ); + + /* In eSYN_RECEIVED a simple ACK is expected, but apparently the + * 'SYN+ACK' didn't arrive. Step back to the previous state in which + * a first incoming SYN is handled. The SYN was counted already so + * decrease it first. */ + vTCPStateChange( pxSocket, eSYN_FIRST ); + } + + if( ( ( ucTCPFlags & tcpTCP_FLAG_FIN ) != 0U ) && ( pxSocket->u.xTCP.bits.bFinRecv == pdFALSE_UNSIGNED ) ) + { + /* It's the first time a FIN has been received, remember its + * sequence number. */ + pxTCPWindow->rx.ulFINSequenceNumber = ulSequenceNumber + ulReceiveLength; + pxSocket->u.xTCP.bits.bFinRecv = pdTRUE_UNSIGNED; + + /* Was peer the first one to send a FIN? */ + if( pxSocket->u.xTCP.bits.bFinSent == pdFALSE_UNSIGNED ) + { + /* If so, don't send the-last-ACK. */ + pxSocket->u.xTCP.bits.bFinLast = pdTRUE_UNSIGNED; + } + } + + switch( ipNUMERIC_CAST( eIPTCPState_t, pxSocket->u.xTCP.ucTCPState ) ) + { + case eCLOSED: /* (server + client) no connection state at all. */ + + /* Nothing to do for a closed socket, except waiting for the + * owner. */ + break; + + case eTCP_LISTEN: /* (server) waiting for a connection request from + * any remote TCP and port. */ + + /* The listen state was handled in xProcessReceivedTCPPacket(). + * Should not come here. */ + break; + + case eSYN_FIRST: /* (server) Just received a SYN request for a server + * socket. */ + + /* A new socket has been created, reply with a SYN+ACK. + * Acknowledge with seq+1 because the SYN is seen as pseudo data + * with len = 1. */ + uxOptionsLength = prvSetSynAckOptions( pxSocket, pxTCPHeader ); + pxTCPHeader->ucTCPFlags = ( uint8_t ) tcpTCP_FLAG_SYN | ( uint8_t ) tcpTCP_FLAG_ACK; + + uxIntermediateResult = uxIPHeaderSizeSocket( pxSocket ) + ipSIZE_OF_TCP_HEADER + uxOptionsLength; + xSendLength = ( BaseType_t ) uxIntermediateResult; + + /* Set the TCP offset field: ipSIZE_OF_TCP_HEADER equals 20 and + * uxOptionsLength is a multiple of 4. The complete expression is: + * ucTCPOffset = ( ( ipSIZE_OF_TCP_HEADER + uxOptionsLength ) / 4 ) << 4 */ + pxTCPHeader->ucTCPOffset = ( uint8_t ) ( ( ipSIZE_OF_TCP_HEADER + uxOptionsLength ) << 2 ); + vTCPStateChange( pxSocket, eSYN_RECEIVED ); + + pxTCPWindow->rx.ulHighestSequenceNumber = ulSequenceNumber + 1UL; + pxTCPWindow->rx.ulCurrentSequenceNumber = ulSequenceNumber + 1UL; + pxTCPWindow->ulNextTxSequenceNumber = pxTCPWindow->tx.ulFirstSequenceNumber + 1UL; + pxTCPWindow->tx.ulCurrentSequenceNumber = pxTCPWindow->tx.ulFirstSequenceNumber + 1UL; /* because we send a TCP_SYN. */ + break; + + case eCONNECT_SYN: /* (client) also called SYN_SENT: we've just send a + * SYN, expect a SYN+ACK and send a ACK now. */ + /* Fall through */ + case eSYN_RECEIVED: /* (server) we've had a SYN, replied with SYN+SCK + * expect a ACK and do nothing. */ + xSendLength = prvHandleSynReceived( pxSocket, *( ppxNetworkBuffer ), ulReceiveLength, uxOptionsLength ); + break; + + case eESTABLISHED: /* (server + client) an open connection, data + * received can be delivered to the user. The normal + * state for the data transfer phase of the connection + * The closing states are also handled here with the + * use of some flags. */ + xSendLength = prvHandleEstablished( pxSocket, ppxNetworkBuffer, ulReceiveLength, uxOptionsLength ); + break; + + case eLAST_ACK: /* (server + client) waiting for an acknowledgement + * of the connection termination request previously + * sent to the remote TCP (which includes an + * acknowledgement of its connection termination + * request). */ + /* Fall through */ + case eFIN_WAIT_1: /* (server + client) waiting for a connection termination request from the remote TCP, + * or an acknowledgement of the connection termination request previously sent. */ + /* Fall through */ + case eFIN_WAIT_2: /* (server + client) waiting for a connection termination request from the remote TCP. */ + xSendLength = prvTCPHandleFin( pxSocket, *ppxNetworkBuffer ); + break; + + case eCLOSE_WAIT: /* (server + client) waiting for a connection + * termination request from the local user. Nothing to + * do, connection is closed, wait for owner to close + * this socket. */ + break; + + case eCLOSING: /* (server + client) waiting for a connection + * termination request acknowledgement from the remote + * TCP. */ + break; + + case eTIME_WAIT: /* (either server or client) waiting for enough time + * to pass to be sure the remote TCP received the + * acknowledgement of its connection termination + * request. [According to RFC 793 a connection can stay + * in TIME-WAIT for a maximum of four minutes known as + * a MSL (maximum segment lifetime).] These states are + * implemented implicitly by settings flags like + * 'bFinSent', 'bFinRecv', and 'bFinAcked'. */ + break; + + default: + /* No more known states. */ + break; + } + } + + if( xSendLength > 0 ) + { + xSendLength = prvSendData( pxSocket, ppxNetworkBuffer, ulReceiveLength, xSendLength ); + } + + return xSendLength; + } + /*-----------------------------------------------------------*/ + +/** + * @brief Common code for sending a TCP protocol control packet (i.e. no options, no + * payload, just flags). + * + * @param[in] pxNetworkBuffer: The network buffer received from the peer. + * @param[in] ucTCPFlags: The flags to determine what kind of packet this is. + * + * @return pdFAIL always indicating that the packet was not consumed. + */ + static BaseType_t prvTCPSendSpecialPacketHelper( NetworkBufferDescriptor_t * pxNetworkBuffer, + uint8_t ucTCPFlags ) + { + #if ( ipconfigIGNORE_UNKNOWN_PACKETS == 1 ) + /* Configured to ignore unknown packets just suppress a compiler warning. */ + ( void ) pxNetworkBuffer; + ( void ) ucTCPFlags; + #else + { + /* Map the ethernet buffer onto the TCPPacket_t struct for easy access to the fields. */ + TCPPacket_t * pxTCPPacket = ipCAST_PTR_TO_TYPE_PTR( TCPPacket_t, pxNetworkBuffer->pucEthernetBuffer ); + const uint32_t ulSendLength = + ( ipSIZE_OF_IPv4_HEADER + ipSIZE_OF_TCP_HEADER ); /* Plus 0 options. */ + + pxTCPPacket->xTCPHeader.ucTCPFlags = ucTCPFlags; + pxTCPPacket->xTCPHeader.ucTCPOffset = ( ipSIZE_OF_TCP_HEADER ) << 2; + + prvTCPReturnPacket( NULL, pxNetworkBuffer, ulSendLength, pdFALSE ); + } + #endif /* !ipconfigIGNORE_UNKNOWN_PACKETS */ + + /* The packet was not consumed. */ + return pdFAIL; + } + /*-----------------------------------------------------------*/ + +/** + * @brief A "challenge ACK" is as per https://tools.ietf.org/html/rfc5961#section-3.2, + * case #3. In summary, an RST was received with a sequence number that is + * unexpected but still within the window. + * + * @param[in] pxNetworkBuffer: The network buffer descriptor with the packet. + * + * @return Returns the value back from #prvTCPSendSpecialPacketHelper. + */ + static BaseType_t prvTCPSendChallengeAck( NetworkBufferDescriptor_t * pxNetworkBuffer ) + { + return prvTCPSendSpecialPacketHelper( pxNetworkBuffer, tcpTCP_FLAG_ACK ); + } + /*-----------------------------------------------------------*/ + +/** + * @brief Send a RST (Reset) to peer in case the packet cannot be handled. + * + * @param[in] pxNetworkBuffer: The network buffer descriptor with the packet. + * + * @return Returns the value back from #prvTCPSendSpecialPacketHelper. + */ + static BaseType_t prvTCPSendReset( NetworkBufferDescriptor_t * pxNetworkBuffer ) + { + return prvTCPSendSpecialPacketHelper( pxNetworkBuffer, + ( uint8_t ) tcpTCP_FLAG_ACK | ( uint8_t ) tcpTCP_FLAG_RST ); + } + /*-----------------------------------------------------------*/ + +/** + * @brief Set the MSS (Maximum segment size) associated with the given socket. + * + * @param[in] pxSocket: The socket whose MSS is to be set. + */ + static void prvSocketSetMSS( FreeRTOS_Socket_t * pxSocket ) + { + uint32_t ulMSS = ipconfigTCP_MSS; + + if( ( ( FreeRTOS_ntohl( pxSocket->u.xTCP.ulRemoteIP ) ^ *ipLOCAL_IP_ADDRESS_POINTER ) & xNetworkAddressing.ulNetMask ) != 0UL ) + { + /* Data for this peer will pass through a router, and maybe through + * the internet. Limit the MSS to 1400 bytes or less. */ + ulMSS = FreeRTOS_min_uint32( ( uint32_t ) tcpREDUCED_MSS_THROUGH_INTERNET, ulMSS ); + } + + FreeRTOS_debug_printf( ( "prvSocketSetMSS: %lu bytes for %lxip:%u\n", ulMSS, pxSocket->u.xTCP.ulRemoteIP, pxSocket->u.xTCP.usRemotePort ) ); + + pxSocket->u.xTCP.usInitMSS = ( uint16_t ) ulMSS; + pxSocket->u.xTCP.usCurMSS = ( uint16_t ) ulMSS; + } + /*-----------------------------------------------------------*/ + +/** + * @brief Process the received TCP packet. + * + * @param[in] pxDescriptor: The descriptor in which the TCP packet is held. + * + * @return If the processing of the packet was successful, then pdPASS is returned + * or else pdFAIL. + * + * @note FreeRTOS_TCP_IP has only 2 public functions, this is the second one: + * xProcessReceivedTCPPacket() + * prvTCPHandleState() + * prvTCPPrepareSend() + * prvTCPReturnPacket() + * xNetworkInterfaceOutput() // Sends data to the NIC + * prvTCPSendRepeated() + * prvTCPReturnPacket() // Prepare for returning + * xNetworkInterfaceOutput() // Sends data to the NIC + */ + BaseType_t xProcessReceivedTCPPacket( NetworkBufferDescriptor_t * pxDescriptor ) + { + /* Function might modify the parameter. */ + NetworkBufferDescriptor_t * pxNetworkBuffer = pxDescriptor; + + /* Map the buffer onto a ProtocolHeaders_t struct for easy access to the fields. */ + const ProtocolHeaders_t * pxProtocolHeaders = ipCAST_CONST_PTR_TO_CONST_TYPE_PTR( ProtocolHeaders_t, + &( pxNetworkBuffer->pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER + xIPHeaderSize( pxNetworkBuffer ) ] ) ); + FreeRTOS_Socket_t * pxSocket; + uint16_t ucTCPFlags = pxProtocolHeaders->xTCPHeader.ucTCPFlags; + uint32_t ulLocalIP; + uint16_t xLocalPort = FreeRTOS_htons( pxProtocolHeaders->xTCPHeader.usDestinationPort ); + uint16_t xRemotePort = FreeRTOS_htons( pxProtocolHeaders->xTCPHeader.usSourcePort ); + uint32_t ulRemoteIP; + uint32_t ulSequenceNumber = FreeRTOS_ntohl( pxProtocolHeaders->xTCPHeader.ulSequenceNumber ); + uint32_t ulAckNumber = FreeRTOS_ntohl( pxProtocolHeaders->xTCPHeader.ulAckNr ); + BaseType_t xResult = pdPASS; + + configASSERT( pxNetworkBuffer != NULL ); + configASSERT( pxNetworkBuffer->pucEthernetBuffer != NULL ); + const IPHeader_t * pxIPHeader; + + /* Check for a minimum packet size. */ + if( pxNetworkBuffer->xDataLength < ( ipSIZE_OF_ETH_HEADER + xIPHeaderSize( pxNetworkBuffer ) + ipSIZE_OF_TCP_HEADER ) ) + { + xResult = pdFAIL; + } + else + { + /* Map the ethernet buffer onto the IPHeader_t struct for easy access to the fields. */ + pxIPHeader = ipCAST_CONST_PTR_TO_CONST_TYPE_PTR( IPHeader_t, &( pxNetworkBuffer->pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER ] ) ); + ulLocalIP = FreeRTOS_htonl( pxIPHeader->ulDestinationIPAddress ); + ulRemoteIP = FreeRTOS_htonl( pxIPHeader->ulSourceIPAddress ); + + /* Find the destination socket, and if not found: return a socket listing to + * the destination PORT. */ + pxSocket = ( FreeRTOS_Socket_t * ) pxTCPSocketLookup( ulLocalIP, xLocalPort, ulRemoteIP, xRemotePort ); + + if( ( pxSocket == NULL ) || ( prvTCPSocketIsActive( ipNUMERIC_CAST( eIPTCPState_t, pxSocket->u.xTCP.ucTCPState ) ) == pdFALSE ) ) + { + /* A TCP messages is received but either there is no socket with the + * given port number or the there is a socket, but it is in one of these + * non-active states: eCLOSED, eCLOSE_WAIT, eFIN_WAIT_2, eCLOSING, or + * eTIME_WAIT. */ + + FreeRTOS_debug_printf( ( "TCP: No active socket on port %d (%lxip:%d)\n", xLocalPort, ulRemoteIP, xRemotePort ) ); + + /* Send a RST to all packets that can not be handled. As a result + * the other party will get a ECONN error. There are two exceptions: + * 1) A packet that already has the RST flag set. + * 2) A packet that only has the ACK flag set. + * A packet with only the ACK flag set might be the last ACK in + * a three-way hand-shake that closes a connection. */ + if( ( ( ucTCPFlags & tcpTCP_FLAG_CTRL ) != tcpTCP_FLAG_ACK ) && + ( ( ucTCPFlags & tcpTCP_FLAG_RST ) == 0U ) ) + { + ( void ) prvTCPSendReset( pxNetworkBuffer ); + } + + /* The packet can't be handled. */ + xResult = pdFAIL; + } + else + { + pxSocket->u.xTCP.ucRepCount = 0U; + + if( pxSocket->u.xTCP.ucTCPState == ( uint8_t ) eTCP_LISTEN ) + { + /* The matching socket is in a listening state. Test if the peer + * has set the SYN flag. */ + if( ( ucTCPFlags & tcpTCP_FLAG_CTRL ) != tcpTCP_FLAG_SYN ) + { + /* What happens: maybe after a reboot, a client doesn't know the + * connection had gone. Send a RST in order to get a new connect + * request. */ + #if ( ipconfigHAS_DEBUG_PRINTF == 1 ) + { + FreeRTOS_debug_printf( ( "TCP: Server can't handle flags: %s from %lxip:%u to port %u\n", + prvTCPFlagMeaning( ( UBaseType_t ) ucTCPFlags ), ulRemoteIP, xRemotePort, xLocalPort ) ); + } + #endif /* ipconfigHAS_DEBUG_PRINTF */ + + if( ( ucTCPFlags & tcpTCP_FLAG_RST ) == 0U ) + { + ( void ) prvTCPSendReset( pxNetworkBuffer ); + } + + xResult = pdFAIL; + } + else + { + /* prvHandleListen() will either return a newly created socket + * (if bReuseSocket is false), otherwise it returns the current + * socket which will later get connected. */ + pxSocket = prvHandleListen( pxSocket, pxNetworkBuffer ); + + if( pxSocket == NULL ) + { + xResult = pdFAIL; + } + } + } /* if( pxSocket->u.xTCP.ucTCPState == eTCP_LISTEN ). */ + else + { + /* This is not a socket in listening mode. Check for the RST + * flag. */ + if( ( ucTCPFlags & tcpTCP_FLAG_RST ) != 0U ) + { + FreeRTOS_debug_printf( ( "TCP: RST received from %lxip:%u for %u\n", ulRemoteIP, xRemotePort, xLocalPort ) ); + + /* Implement https://tools.ietf.org/html/rfc5961#section-3.2. */ + if( pxSocket->u.xTCP.ucTCPState == ( uint8_t ) eCONNECT_SYN ) + { + /* Per the above RFC, "In the SYN-SENT state ... the RST is + * acceptable if the ACK field acknowledges the SYN." */ + if( ulAckNumber == ( pxSocket->u.xTCP.xTCPWindow.ulOurSequenceNumber + 1UL ) ) + { + vTCPStateChange( pxSocket, eCLOSED ); + } + } + else + { + /* Check whether the packet matches the next expected sequence number. */ + if( ulSequenceNumber == pxSocket->u.xTCP.xTCPWindow.rx.ulCurrentSequenceNumber ) + { + vTCPStateChange( pxSocket, eCLOSED ); + } + /* Otherwise, check whether the packet is within the receive window. */ + else if( ( ulSequenceNumber > pxSocket->u.xTCP.xTCPWindow.rx.ulCurrentSequenceNumber ) && + ( ulSequenceNumber < ( pxSocket->u.xTCP.xTCPWindow.rx.ulCurrentSequenceNumber + + pxSocket->u.xTCP.xTCPWindow.xSize.ulRxWindowLength ) ) ) + { + /* Send a challenge ACK. */ + ( void ) prvTCPSendChallengeAck( pxNetworkBuffer ); + } + else + { + /* Nothing. */ + } + } + + /* Otherwise, do nothing. In any case, the packet cannot be handled. */ + xResult = pdFAIL; + } + else if( ( ( ucTCPFlags & tcpTCP_FLAG_CTRL ) == tcpTCP_FLAG_SYN ) && ( pxSocket->u.xTCP.ucTCPState >= ( uint8_t ) eESTABLISHED ) ) + { + /* SYN flag while this socket is already connected. */ + FreeRTOS_debug_printf( ( "TCP: SYN unexpected from %lxip:%u\n", ulRemoteIP, xRemotePort ) ); + + /* The packet cannot be handled. */ + xResult = pdFAIL; + } + else + { + /* Update the copy of the TCP header only (skipping eth and IP + * headers). It might be used later on, whenever data must be sent + * to the peer. */ + const size_t uxOffset = ipSIZE_OF_ETH_HEADER + uxIPHeaderSizeSocket( pxSocket ); + ( void ) memcpy( ( void * ) ( &( pxSocket->u.xTCP.xPacket.u.ucLastPacket[ uxOffset ] ) ), + ( const void * ) ( &( pxNetworkBuffer->pucEthernetBuffer[ uxOffset ] ) ), + ipSIZE_OF_TCP_HEADER ); + } + } + } + + if( xResult != pdFAIL ) + { + uint16_t usWindow; + + /* pxSocket is not NULL when xResult != pdFAIL. */ + configASSERT( pxSocket != NULL ); + + /* Touch the alive timers because we received a message for this + * socket. */ + prvTCPTouchSocket( pxSocket ); + + /* Parse the TCP option(s), if present. */ + + /* _HT_ : if we're in the SYN phase, and peer does not send a MSS option, + * then we MUST assume an MSS size of 536 bytes for backward compatibility. */ + + /* When there are no TCP options, the TCP offset equals 20 bytes, which is stored as + * the number 5 (words) in the higher nibble of the TCP-offset byte. */ + if( ( pxProtocolHeaders->xTCPHeader.ucTCPOffset & tcpTCP_OFFSET_LENGTH_BITS ) > tcpTCP_OFFSET_STANDARD_LENGTH ) + { + prvCheckOptions( pxSocket, pxNetworkBuffer ); + } + + usWindow = FreeRTOS_ntohs( pxProtocolHeaders->xTCPHeader.usWindow ); + pxSocket->u.xTCP.ulWindowSize = ( uint32_t ) usWindow; + #if ( ipconfigUSE_TCP_WIN == 1 ) + { + /* rfc1323 : The Window field in a SYN (i.e., a or ) + * segment itself is never scaled. */ + if( ( ucTCPFlags & ( uint8_t ) tcpTCP_FLAG_SYN ) == 0U ) + { + pxSocket->u.xTCP.ulWindowSize = + ( pxSocket->u.xTCP.ulWindowSize << pxSocket->u.xTCP.ucPeerWinScaleFactor ); + } + } + #endif /* ipconfigUSE_TCP_WIN */ + + /* In prvTCPHandleState() the incoming messages will be handled + * depending on the current state of the connection. */ + if( prvTCPHandleState( pxSocket, &pxNetworkBuffer ) > 0 ) + { + /* prvTCPHandleState() has sent a message, see if there are more to + * be transmitted. */ + #if ( ipconfigUSE_TCP_WIN == 1 ) + { + ( void ) prvTCPSendRepeated( pxSocket, &pxNetworkBuffer ); + } + #endif /* ipconfigUSE_TCP_WIN */ + } + + if( pxNetworkBuffer != NULL ) + { + /* We must check if the buffer is unequal to NULL, because the + * socket might keep a reference to it in case a delayed ACK must be + * sent. */ + vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer ); + #ifndef _lint + /* Clear pointers that are freed. */ + pxNetworkBuffer = NULL; + #endif + } + + /* And finally, calculate when this socket wants to be woken up. */ + ( void ) prvTCPNextTimeout( pxSocket ); + /* Return pdPASS to tell that the network buffer is 'consumed'. */ + xResult = pdPASS; + } + } + + /* pdPASS being returned means the buffer has been consumed. */ + return xResult; + } + /*-----------------------------------------------------------*/ + +/** + * @brief Handle 'listen' event on the given socket. + * + * @param[in] pxSocket: The socket on which the listen occurred. + * @param[in] pxNetworkBuffer: The network buffer carrying the packet. + * + * @return If a new socket/duplicate socket is created, then the pointer to + * that socket is returned or else, a NULL pointer is returned. + */ + static FreeRTOS_Socket_t * prvHandleListen( FreeRTOS_Socket_t * pxSocket, + NetworkBufferDescriptor_t * pxNetworkBuffer ) + { + /* Map the ethernet buffer onto a TCPPacket_t struct for easy access to the fields. */ + const TCPPacket_t * pxTCPPacket = ipCAST_CONST_PTR_TO_CONST_TYPE_PTR( TCPPacket_t, pxNetworkBuffer->pucEthernetBuffer ); + FreeRTOS_Socket_t * pxReturn = NULL; + uint32_t ulInitialSequenceNumber; + + /* Assume that a new Initial Sequence Number will be required. Request + * it now in order to fail out if necessary. */ + ulInitialSequenceNumber = ulApplicationGetNextSequenceNumber( *ipLOCAL_IP_ADDRESS_POINTER, + pxSocket->usLocalPort, + pxTCPPacket->xIPHeader.ulSourceIPAddress, + pxTCPPacket->xTCPHeader.usSourcePort ); + + /* A pure SYN (without ACK) has come in, create a new socket to answer + * it. */ + if( ulInitialSequenceNumber != 0UL ) + { + if( pxSocket->u.xTCP.bits.bReuseSocket != pdFALSE_UNSIGNED ) + { + /* The flag bReuseSocket indicates that the same instance of the + * listening socket should be used for the connection. */ + pxReturn = pxSocket; + pxSocket->u.xTCP.bits.bPassQueued = pdTRUE_UNSIGNED; + pxSocket->u.xTCP.pxPeerSocket = pxSocket; + } + else + { + /* The socket does not have the bReuseSocket flag set meaning create a + * new socket when a connection comes in. */ + pxReturn = NULL; + + if( pxSocket->u.xTCP.usChildCount >= pxSocket->u.xTCP.usBacklog ) + { + FreeRTOS_printf( ( "Check: Socket %u already has %u / %u child%s\n", + pxSocket->usLocalPort, + pxSocket->u.xTCP.usChildCount, + pxSocket->u.xTCP.usBacklog, + ( pxSocket->u.xTCP.usChildCount == 1U ) ? "" : "ren" ) ); + ( void ) prvTCPSendReset( pxNetworkBuffer ); + } + else + { + FreeRTOS_Socket_t * pxNewSocket = ( FreeRTOS_Socket_t * ) + FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_STREAM, FREERTOS_IPPROTO_TCP ); + + if( ( pxNewSocket == NULL ) || ( pxNewSocket == FREERTOS_INVALID_SOCKET ) ) + { + FreeRTOS_debug_printf( ( "TCP: Listen: new socket failed\n" ) ); + ( void ) prvTCPSendReset( pxNetworkBuffer ); + } + else if( prvTCPSocketCopy( pxNewSocket, pxSocket ) != pdFALSE ) + { + /* The socket will be connected immediately, no time for the + * owner to setsockopt's, therefore copy properties of the server + * socket to the new socket. Only the binding might fail (due to + * lack of resources). */ + pxReturn = pxNewSocket; + } + else + { + /* Copying failed somehow. */ + } + } + } + } + + if( ( ulInitialSequenceNumber != 0U ) && ( pxReturn != NULL ) ) + { + /* Map the byte stream onto the ProtocolHeaders_t for easy access to the fields. */ + const ProtocolHeaders_t * pxProtocolHeaders = ipCAST_CONST_PTR_TO_CONST_TYPE_PTR( ProtocolHeaders_t, + &( pxNetworkBuffer->pucEthernetBuffer[ ipSIZE_OF_ETH_HEADER + xIPHeaderSize( pxNetworkBuffer ) ] ) ); + + pxReturn->u.xTCP.usRemotePort = FreeRTOS_htons( pxTCPPacket->xTCPHeader.usSourcePort ); + pxReturn->u.xTCP.ulRemoteIP = FreeRTOS_htonl( pxTCPPacket->xIPHeader.ulSourceIPAddress ); + pxReturn->u.xTCP.xTCPWindow.ulOurSequenceNumber = ulInitialSequenceNumber; + + /* Here is the SYN action. */ + pxReturn->u.xTCP.xTCPWindow.rx.ulCurrentSequenceNumber = FreeRTOS_ntohl( pxProtocolHeaders->xTCPHeader.ulSequenceNumber ); + prvSocketSetMSS( pxReturn ); + + prvTCPCreateWindow( pxReturn ); + + vTCPStateChange( pxReturn, eSYN_FIRST ); + + /* Make a copy of the header up to the TCP header. It is needed later + * on, whenever data must be sent to the peer. */ + ( void ) memcpy( ( void * ) pxReturn->u.xTCP.xPacket.u.ucLastPacket, + ( const void * ) pxNetworkBuffer->pucEthernetBuffer, + sizeof( pxReturn->u.xTCP.xPacket.u.ucLastPacket ) ); + } + + return pxReturn; + } + /*-----------------------------------------------------------*/ + +/** + * @brief Duplicates a socket after a listening socket receives a connection and bind + * the new socket to the same port as the listening socket. + * Also, let the new socket inherit all properties from the listening socket. + * + * @param[in] pxNewSocket: Pointer to the new socket. + * @param[in] pxSocket: Pointer to the socket being duplicated. + * + * @return If all steps all successful, then pdTRUE is returned. Else, pdFALSE. + */ + static BaseType_t prvTCPSocketCopy( FreeRTOS_Socket_t * pxNewSocket, + FreeRTOS_Socket_t * pxSocket ) + { + struct freertos_sockaddr xAddress; + BaseType_t xResult; + + pxNewSocket->xReceiveBlockTime = pxSocket->xReceiveBlockTime; + pxNewSocket->xSendBlockTime = pxSocket->xSendBlockTime; + pxNewSocket->ucSocketOptions = pxSocket->ucSocketOptions; + pxNewSocket->u.xTCP.uxRxStreamSize = pxSocket->u.xTCP.uxRxStreamSize; + pxNewSocket->u.xTCP.uxTxStreamSize = pxSocket->u.xTCP.uxTxStreamSize; + pxNewSocket->u.xTCP.uxLittleSpace = pxSocket->u.xTCP.uxLittleSpace; + pxNewSocket->u.xTCP.uxEnoughSpace = pxSocket->u.xTCP.uxEnoughSpace; + pxNewSocket->u.xTCP.uxRxWinSize = pxSocket->u.xTCP.uxRxWinSize; + pxNewSocket->u.xTCP.uxTxWinSize = pxSocket->u.xTCP.uxTxWinSize; + + #if ( ipconfigSOCKET_HAS_USER_SEMAPHORE == 1 ) + { + pxNewSocket->pxUserSemaphore = pxSocket->pxUserSemaphore; + } + #endif /* ipconfigSOCKET_HAS_USER_SEMAPHORE */ + + #if ( ipconfigUSE_CALLBACKS == 1 ) + { + /* In case call-backs are used, copy them from parent to child. */ + pxNewSocket->u.xTCP.pxHandleConnected = pxSocket->u.xTCP.pxHandleConnected; + pxNewSocket->u.xTCP.pxHandleReceive = pxSocket->u.xTCP.pxHandleReceive; + pxNewSocket->u.xTCP.pxHandleSent = pxSocket->u.xTCP.pxHandleSent; + } + #endif /* ipconfigUSE_CALLBACKS */ + + #if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 ) + { + /* Child socket of listening sockets will inherit the Socket Set + * Otherwise the owner has no chance of including it into the set. */ + if( pxSocket->pxSocketSet != NULL ) + { + pxNewSocket->pxSocketSet = pxSocket->pxSocketSet; + pxNewSocket->xSelectBits = pxSocket->xSelectBits | ( ( EventBits_t ) eSELECT_READ ) | ( ( EventBits_t ) eSELECT_EXCEPT ); + } + } + #endif /* ipconfigSUPPORT_SELECT_FUNCTION */ + + /* And bind it to the same local port as its parent. */ + xAddress.sin_addr = *ipLOCAL_IP_ADDRESS_POINTER; + xAddress.sin_port = FreeRTOS_htons( pxSocket->usLocalPort ); + + #if ( ipconfigTCP_HANG_PROTECTION == 1 ) + { + /* Only when there is anti-hanging protection, a socket may become an + * orphan temporarily. Once this socket is really connected, the owner of + * the server socket will be notified. */ + + /* When bPassQueued is true, the socket is an orphan until it gets + * connected. */ + pxNewSocket->u.xTCP.bits.bPassQueued = pdTRUE_UNSIGNED; + pxNewSocket->u.xTCP.pxPeerSocket = pxSocket; + } + #else + { + /* A reference to the new socket may be stored and the socket is marked + * as 'passable'. */ + + /* When bPassAccept is true, this socket may be returned in a call to + * accept(). */ + pxNewSocket->u.xTCP.bits.bPassAccept = pdTRUE_UNSIGNED; + + if( pxSocket->u.xTCP.pxPeerSocket == NULL ) + { + pxSocket->u.xTCP.pxPeerSocket = pxNewSocket; + } + } + #endif /* if ( ipconfigTCP_HANG_PROTECTION == 1 ) */ + + pxSocket->u.xTCP.usChildCount++; + + FreeRTOS_debug_printf( ( "Gain: Socket %u now has %u / %u child%s\n", + pxSocket->usLocalPort, + pxSocket->u.xTCP.usChildCount, + pxSocket->u.xTCP.usBacklog, + ( pxSocket->u.xTCP.usChildCount == 1U ) ? "" : "ren" ) ); + + /* Now bind the child socket to the same port as the listening socket. */ + if( vSocketBind( pxNewSocket, &xAddress, sizeof( xAddress ), pdTRUE ) != 0 ) + { + FreeRTOS_debug_printf( ( "TCP: Listen: new socket bind error\n" ) ); + ( void ) FreeRTOS_closesocket( pxNewSocket ); + xResult = pdFALSE; + } + else + { + xResult = pdTRUE; + } + + return xResult; + } + /*-----------------------------------------------------------*/ + + #if ( ( ipconfigHAS_DEBUG_PRINTF != 0 ) || ( ipconfigHAS_PRINTF != 0 ) ) + + const char * FreeRTOS_GetTCPStateName( UBaseType_t ulState ) + { + static const char * const pcStateNames[] = + { + "eCLOSED", + "eTCP_LISTEN", + "eCONNECT_SYN", + "eSYN_FIRST", + "eSYN_RECEIVED", + "eESTABLISHED", + "eFIN_WAIT_1", + "eFIN_WAIT_2", + "eCLOSE_WAIT", + "eCLOSING", + "eLAST_ACK", + "eTIME_WAIT", + "eUNKNOWN", + }; + BaseType_t xIndex = ( BaseType_t ) ulState; + + if( ( xIndex < 0 ) || ( xIndex >= ARRAY_SIZE( pcStateNames ) ) ) + { + /* The last item is called 'eUNKNOWN' */ + xIndex = ARRAY_SIZE( pcStateNames ); + xIndex--; + } + + return pcStateNames[ xIndex ]; + } + + #endif /* ( ( ipconfigHAS_DEBUG_PRINTF != 0 ) || ( ipconfigHAS_PRINTF != 0 ) ) */ + /*-----------------------------------------------------------*/ + +/** + * @brief In the API accept(), the user asks is there is a new client? As API's can + * not walk through the xBoundTCPSocketsList the IP-task will do this. + * + * @param[in] pxSocket: The socket for which the bound socket list will be iterated. + * + * @return if there is a new client, then pdTRUE is returned or else, pdFALSE. + */ + BaseType_t xTCPCheckNewClient( FreeRTOS_Socket_t * pxSocket ) + { + TickType_t uxLocalPort = ( TickType_t ) FreeRTOS_htons( pxSocket->usLocalPort ); + const ListItem_t * pxIterator; + FreeRTOS_Socket_t * pxFound; + BaseType_t xResult = pdFALSE; + const ListItem_t * pxEndTCP = listGET_END_MARKER( &xBoundTCPSocketsList ); + + /* Here xBoundTCPSocketsList can be accessed safely IP-task is the only one + * who has access. */ + for( pxIterator = ( const ListItem_t * ) listGET_HEAD_ENTRY( &xBoundTCPSocketsList ); + pxIterator != pxEndTCP; + pxIterator = ( const ListItem_t * ) listGET_NEXT( pxIterator ) ) + { + if( listGET_LIST_ITEM_VALUE( pxIterator ) == ( configLIST_VOLATILE TickType_t ) uxLocalPort ) + { + pxFound = ipCAST_PTR_TO_TYPE_PTR( FreeRTOS_Socket_t, listGET_LIST_ITEM_OWNER( pxIterator ) ); + + if( ( pxFound->ucProtocol == ( uint8_t ) FREERTOS_IPPROTO_TCP ) && ( pxFound->u.xTCP.bits.bPassAccept != pdFALSE_UNSIGNED ) ) + { + pxSocket->u.xTCP.pxPeerSocket = pxFound; + FreeRTOS_debug_printf( ( "xTCPCheckNewClient[0]: client on port %u\n", pxSocket->usLocalPort ) ); + xResult = pdTRUE; + break; + } + } + } + + return xResult; + } + /*-----------------------------------------------------------*/ + + +#endif /* ipconfigUSE_TCP == 1 */ + +/* Provide access to private members for testing. */ +#ifdef FREERTOS_ENABLE_UNIT_TESTS + #include "freertos_tcp_test_access_tcp_define.h" +#endif + +/* Provide access to private members for verification. */ +#ifdef FREERTOS_TCP_ENABLE_VERIFICATION + #include "aws_freertos_tcp_verification_access_tcp_define.h" +#endif diff --git a/examples/stm32/freertos-tcp/FreeRTOS_TCP_WIN.c b/examples/stm32/freertos-tcp/FreeRTOS_TCP_WIN.c new file mode 100644 index 00000000..7670c3ee --- /dev/null +++ b/examples/stm32/freertos-tcp/FreeRTOS_TCP_WIN.c @@ -0,0 +1,2515 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + + +/** + * @file FreeRTOS_TCP_WIN.c + * @brief Module which handles the TCP windowing schemes for FreeRTOS+TCP. Many + * functions have two versions - one for FreeRTOS+TCP (full) and one for + * FreeRTOS+TCP (lite). + * + * In this module all ports and IP addresses and sequence numbers are + * being stored in host byte-order. + */ + +/* Standard includes. */ +#include + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" +#include "task.h" + +/* FreeRTOS+TCP includes. */ +#include "FreeRTOS_UDP_IP.h" +#include "FreeRTOS_IP.h" +#include "FreeRTOS_Sockets.h" +#include "FreeRTOS_IP_Private.h" + + +#ifndef FREERTOS_DEFAULT_IP_CONFIG_H + #error "FreeRTOSIPConfigDefaults.h not included." +#endif + +#if ( ipconfigUSE_TCP == 1 ) + +/* Constants used for Smoothed Round Trip Time (SRTT). */ + #define winSRTT_INCREMENT_NEW 2 /**< New increment for the smoothed RTT. */ + #define winSRTT_INCREMENT_CURRENT 6 /**< Current increment for the smoothed RTT. */ + #define winSRTT_DECREMENT_NEW 1 /**< New decrement for the smoothed RTT. */ + #define winSRTT_DECREMENT_CURRENT 7 /**< Current decrement for the smoothed RTT. */ + #define winSRTT_CAP_mS 50 /**< Cap in milliseconds. */ + +/** + * @brief Utility function to cast pointer of a type to pointer of type TCPSegment_t. + * + * @return The casted pointer. + */ + static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( TCPSegment_t ) + { + return ( TCPSegment_t * ) pvArgument; + } + + + #if ( ipconfigUSE_TCP_WIN == 1 ) + +/** @brief Create a new Rx window. */ + #define xTCPWindowRxNew( pxWindow, ulSequenceNumber, lCount ) xTCPWindowNew( pxWindow, ulSequenceNumber, lCount, pdTRUE ) + +/** @brief Create a new Tx window. */ + #define xTCPWindowTxNew( pxWindow, ulSequenceNumber, lCount ) xTCPWindowNew( pxWindow, ulSequenceNumber, lCount, pdFALSE ) + +/** @brief The code to send a single Selective ACK (SACK): + * NOP (0x01), NOP (0x01), SACK (0x05), LEN (0x0a), + * followed by a lower and a higher sequence number, + * where LEN is 2 + 2*4 = 10 bytes. */ + #if ( ipconfigBYTE_ORDER == pdFREERTOS_BIG_ENDIAN ) + #define OPTION_CODE_SINGLE_SACK ( 0x0101050aUL ) + #else + #define OPTION_CODE_SINGLE_SACK ( 0x0a050101UL ) + #endif + +/** @brief Normal retransmission: + * A packet will be retransmitted after a Retransmit Time-Out (RTO). + * Fast retransmission: + * When 3 packets with a higher sequence number have been acknowledged + * by the peer, it is very unlikely a current packet will ever arrive. + * It will be retransmitted far before the RTO. + */ + #define DUPLICATE_ACKS_BEFORE_FAST_RETRANSMIT ( 3U ) + +/** @brief If there have been several retransmissions (4), decrease the + * size of the transmission window to at most 2 times MSS. + */ + #define MAX_TRANSMIT_COUNT_USING_LARGE_WINDOW ( 4U ) + + #endif /* configUSE_TCP_WIN */ +/*-----------------------------------------------------------*/ + + static void vListInsertGeneric( List_t * const pxList, + ListItem_t * const pxNewListItem, + MiniListItem_t * const pxWhere ); + +/* + * All TCP sockets share a pool of segment descriptors (TCPSegment_t) + * Available descriptors are stored in the 'xSegmentList' + * When a socket owns a descriptor, it will either be stored in + * 'xTxSegments' or 'xRxSegments' + * As soon as a package has been confirmed, the descriptor will be returned + * to the segment pool + */ + #if ( ipconfigUSE_TCP_WIN == 1 ) + static BaseType_t prvCreateSectors( void ); + #endif /* ipconfigUSE_TCP_WIN == 1 */ + +/* + * Find a segment with a given sequence number in the list of received + * segments: 'pxWindow->xRxSegments'. + */ + #if ( ipconfigUSE_TCP_WIN == 1 ) + static TCPSegment_t * xTCPWindowRxFind( const TCPWindow_t * pxWindow, + uint32_t ulSequenceNumber ); + #endif /* ipconfigUSE_TCP_WIN == 1 */ + +/* + * Allocate a new segment + * The socket will borrow all segments from a common pool: 'xSegmentList', + * which is a list of 'TCPSegment_t' + */ + #if ( ipconfigUSE_TCP_WIN == 1 ) + static TCPSegment_t * xTCPWindowNew( TCPWindow_t * pxWindow, + uint32_t ulSequenceNumber, + int32_t lCount, + BaseType_t xIsForRx ); + #endif /* ipconfigUSE_TCP_WIN == 1 */ + +/* + * Detaches and returns the head of a queue + */ + #if ( ipconfigUSE_TCP_WIN == 1 ) + static TCPSegment_t * xTCPWindowGetHead( const List_t * pxList ); + #endif /* ipconfigUSE_TCP_WIN == 1 */ + +/* + * Returns the head of a queue but it won't be detached + */ + #if ( ipconfigUSE_TCP_WIN == 1 ) + static TCPSegment_t * xTCPWindowPeekHead( const List_t * pxList ); + #endif /* ipconfigUSE_TCP_WIN == 1 */ + +/* + * Free entry pxSegment because it's not used anymore + * The ownership will be passed back to the segment pool + */ + #if ( ipconfigUSE_TCP_WIN == 1 ) + static void vTCPWindowFree( TCPSegment_t * pxSegment ); + #endif /* ipconfigUSE_TCP_WIN == 1 */ + +/* + * A segment has been received with sequence number 'ulSequenceNumber', where + * 'ulCurrentSequenceNumber == ulSequenceNumber', which means that exactly this + * segment was expected. xTCPWindowRxConfirm() will check if there is already + * another segment with a sequence number between (ulSequenceNumber) and + * (ulSequenceNumber+xLength). Normally none will be found, because the next Rx + * segment should have a sequence number equal to '(ulSequenceNumber+xLength)'. + */ + #if ( ipconfigUSE_TCP_WIN == 1 ) + static TCPSegment_t * xTCPWindowRxConfirm( const TCPWindow_t * pxWindow, + uint32_t ulSequenceNumber, + uint32_t ulLength ); + #endif /* ipconfigUSE_TCP_WIN == 1 */ + +/* + * FreeRTOS+TCP stores data in circular buffers. Calculate the next position to + * store. + */ + #if ( ipconfigUSE_TCP_WIN == 1 ) + static int32_t lTCPIncrementTxPosition( int32_t lPosition, + int32_t lMax, + int32_t lCount ); + #endif /* ipconfigUSE_TCP_WIN == 1 */ + +/* + * This function will look if there is new transmission data. It will return + * true if there is data to be sent. + */ + #if ( ipconfigUSE_TCP_WIN == 1 ) + static BaseType_t prvTCPWindowTxHasSpace( TCPWindow_t const * pxWindow, + uint32_t ulWindowSize ); + #endif /* ipconfigUSE_TCP_WIN == 1 */ + +/* + * An acknowledge was received. See if some outstanding data may be removed + * from the transmission queue(s). + */ + #if ( ipconfigUSE_TCP_WIN == 1 ) + static uint32_t prvTCPWindowTxCheckAck( TCPWindow_t * pxWindow, + uint32_t ulFirst, + uint32_t ulLast ); + #endif /* ipconfigUSE_TCP_WIN == 1 */ + +/* + * A higher Tx block has been acknowledged. Now iterate through the xWaitQueue + * to find a possible condition for a FAST retransmission. + */ + #if ( ipconfigUSE_TCP_WIN == 1 ) + static uint32_t prvTCPWindowFastRetransmit( TCPWindow_t * pxWindow, + uint32_t ulFirst ); + #endif /* ipconfigUSE_TCP_WIN == 1 */ + +/*-----------------------------------------------------------*/ + +/**< TCP segment pool. */ + #if ( ipconfigUSE_TCP_WIN == 1 ) + static TCPSegment_t * xTCPSegments = NULL; + #endif /* ipconfigUSE_TCP_WIN == 1 */ + +/**< List of free TCP segments. */ + #if ( ipconfigUSE_TCP_WIN == 1 ) + _static List_t xSegmentList; + #endif + +/** @brief Logging verbosity level. */ + BaseType_t xTCPWindowLoggingLevel = 0; + + #if ( ipconfigUSE_TCP_WIN == 1 ) + /* Some 32-bit arithmetic: comparing sequence numbers */ + static portINLINE BaseType_t xSequenceLessThanOrEqual( uint32_t a, + uint32_t b ); + +/** + * @brief Check if a <= b. + * + * @param[in] a: The value on the left-hand side. + * @param[in] b: The value on the right-hand side. + * + * @return pdTRUE when "( b - a ) < 0x80000000". Else, pdFALSE. + */ + static portINLINE BaseType_t xSequenceLessThanOrEqual( uint32_t a, + uint32_t b ) + { + BaseType_t xResult; + + /* Test if a <= b + * Return true if the unsigned subtraction of (b-a) doesn't generate an + * arithmetic overflow. */ + if( ( ( b - a ) & 0x80000000UL ) == 0UL ) + { + xResult = pdTRUE; + } + else + { + xResult = pdFALSE; + } + + return xResult; + } + + #endif /* ipconfigUSE_TCP_WIN */ +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 1 ) + static portINLINE BaseType_t xSequenceLessThan( uint32_t a, + uint32_t b ); + +/** + * @brief Check if a < b. + * + * @param[in] a: The value on the left-hand side. + * @param[in] b: The value on the right-hand side. + * + * @return pdTRUE when "( b - ( a + 1 ) ) < 0x80000000", else pdFALSE. + */ + static portINLINE BaseType_t xSequenceLessThan( uint32_t a, + uint32_t b ) + { + BaseType_t xResult; + + /* Test if a < b */ + if( ( ( b - ( a + 1UL ) ) & 0x80000000UL ) == 0UL ) + { + xResult = pdTRUE; + } + else + { + xResult = pdFALSE; + } + + return xResult; + } + + #endif /* ipconfigUSE_TCP_WIN */ +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 1 ) + static portINLINE BaseType_t xSequenceGreaterThan( uint32_t a, + uint32_t b ); + +/** + * @brief Check if a > b. + * + * @param[in] a: The value on the left-hand side. + * @param[in] b: The value on the right-hand side. + * + * @return pdTRUE when "( a - b ) < 0x80000000", else pdFALSE. + */ + static portINLINE BaseType_t xSequenceGreaterThan( uint32_t a, + uint32_t b ) + { + BaseType_t xResult; + + /* Test if a > b */ + if( ( ( a - ( b + 1UL ) ) & 0x80000000UL ) == 0UL ) + { + xResult = pdTRUE; + } + else + { + xResult = pdFALSE; + } + + return xResult; + } + + #endif /* ipconfigUSE_TCP_WIN */ + +/*-----------------------------------------------------------*/ + static portINLINE BaseType_t xSequenceGreaterThanOrEqual( uint32_t a, + uint32_t b ); + +/** + * @brief Test if a>=b. This function is required since the sequence numbers can roll over. + * + * @param[in] a: The first sequence number. + * @param[in] b: The second sequence number. + * + * @return pdTRUE if a>=b, else pdFALSE. + */ + + static portINLINE BaseType_t xSequenceGreaterThanOrEqual( uint32_t a, + uint32_t b ) + { + BaseType_t xResult; + + /* Test if a >= b */ + if( ( ( a - b ) & 0x80000000UL ) == 0UL ) + { + xResult = pdTRUE; + } + else + { + xResult = pdFALSE; + } + + return xResult; + } +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 1 ) + static portINLINE void vListInsertFifo( List_t * const pxList, + ListItem_t * const pxNewListItem ); + +/** + * @brief Insert the given item in the list in FIFO manner. + * + * @param[in] pxList: The list in which the item is to inserted. + * @param[in] pxNewListItem: The item to be inserted. + */ + static portINLINE void vListInsertFifo( List_t * const pxList, + ListItem_t * const pxNewListItem ) + { + vListInsertGeneric( pxList, pxNewListItem, &pxList->xListEnd ); + } + #endif +/*-----------------------------------------------------------*/ + + static portINLINE void vTCPTimerSet( TCPTimer_t * pxTimer ); + +/** + * @brief Set the timer's "born" time. + * + * @param[in] pxTimer: The TCP timer. + */ + static portINLINE void vTCPTimerSet( TCPTimer_t * pxTimer ) + { + pxTimer->ulBorn = xTaskGetTickCount(); + } +/*-----------------------------------------------------------*/ + + static portINLINE uint32_t ulTimerGetAge( const TCPTimer_t * pxTimer ); + +/** + * @brief Get the timer age in milliseconds. + * + * @param[in] pxTimer: The timer whose age is to be fetched. + * + * @return The time in milliseconds since the timer was born. + */ + static portINLINE uint32_t ulTimerGetAge( const TCPTimer_t * pxTimer ) + { + return( ( xTaskGetTickCount() - ( ( TickType_t ) pxTimer->ulBorn ) ) * portTICK_PERIOD_MS ); + } +/*-----------------------------------------------------------*/ + +/** + * @brief Insert a new list item into a list. + * + * @param[in] pxList: The list in which the item is to be inserted. + * @param[in] pxNewListItem: The item to be inserted. + * @param[in] pxWhere: Where should the item be inserted. + */ + static void vListInsertGeneric( List_t * const pxList, + ListItem_t * const pxNewListItem, + MiniListItem_t * const pxWhere ) + { + /* Insert a new list item into pxList, it does not sort the list, + * but it puts the item just before xListEnd, so it will be the last item + * returned by listGET_HEAD_ENTRY() */ + pxNewListItem->pxNext = ( struct xLIST_ITEM * configLIST_VOLATILE ) pxWhere; + pxNewListItem->pxPrevious = pxWhere->pxPrevious; + pxWhere->pxPrevious->pxNext = pxNewListItem; + pxWhere->pxPrevious = pxNewListItem; + + /* Remember which list the item is in. */ + listLIST_ITEM_CONTAINER( pxNewListItem ) = ( struct xLIST * configLIST_VOLATILE ) pxList; + + ( pxList->uxNumberOfItems )++; + } +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 1 ) + +/** + * @brief Creates a pool of 'ipconfigTCP_WIN_SEG_COUNT' sector buffers. Should be called once only. + * + * @return When the allocation was successful: pdPASS, otherwise pdFAIL. + */ + static BaseType_t prvCreateSectors( void ) + { + BaseType_t xIndex, xReturn; + + /* Allocate space for 'xTCPSegments' and store them in 'xSegmentList'. */ + + vListInitialise( &xSegmentList ); + xTCPSegments = ipCAST_PTR_TO_TYPE_PTR( TCPSegment_t, pvPortMallocLarge( ( size_t ) ipconfigTCP_WIN_SEG_COUNT * sizeof( xTCPSegments[ 0 ] ) ) ); + + if( xTCPSegments == NULL ) + { + FreeRTOS_debug_printf( ( "prvCreateSectors: malloc %u failed\n", + ( unsigned ) ipconfigTCP_WIN_SEG_COUNT * sizeof( xTCPSegments[ 0 ] ) ) ); + + xReturn = pdFAIL; + } + else + { + /* Clear the allocated space. */ + ( void ) memset( xTCPSegments, 0, ( size_t ) ipconfigTCP_WIN_SEG_COUNT * sizeof( xTCPSegments[ 0 ] ) ); + + for( xIndex = 0; xIndex < ipconfigTCP_WIN_SEG_COUNT; xIndex++ ) + { + /* Could call vListInitialiseItem here but all data has been + * nulled already. Set the owner to a segment descriptor. */ + listSET_LIST_ITEM_OWNER( &( xTCPSegments[ xIndex ].xSegmentItem ), ( void * ) &( xTCPSegments[ xIndex ] ) ); + listSET_LIST_ITEM_OWNER( &( xTCPSegments[ xIndex ].xQueueItem ), ( void * ) &( xTCPSegments[ xIndex ] ) ); + + /* And add it to the pool of available segments */ + vListInsertFifo( &xSegmentList, &( xTCPSegments[ xIndex ].xSegmentItem ) ); + } + + xReturn = pdPASS; + } + + return xReturn; + } + + #endif /* ipconfigUSE_TCP_WIN == 1 */ +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 1 ) + +/** + * @brief Find a segment with a given sequence number in the list of received segments. + * + * @param[in] pxWindow: The descriptor of the TCP sliding windows. + * @param[in] ulSequenceNumber: the sequence number to look-up + * + * @return The address of the segment descriptor found, or NULL when not found. + */ + static TCPSegment_t * xTCPWindowRxFind( const TCPWindow_t * pxWindow, + uint32_t ulSequenceNumber ) + { + const ListItem_t * pxIterator; + const ListItem_t * pxEnd; + TCPSegment_t * pxSegment, * pxReturn = NULL; + + /* Find a segment with a given sequence number in the list of received + * segments. */ + pxEnd = listGET_END_MARKER( &pxWindow->xRxSegments ); + + for( pxIterator = listGET_NEXT( pxEnd ); + pxIterator != pxEnd; + pxIterator = listGET_NEXT( pxIterator ) ) + { + pxSegment = ipCAST_PTR_TO_TYPE_PTR( TCPSegment_t, listGET_LIST_ITEM_OWNER( pxIterator ) ); + + if( pxSegment->ulSequenceNumber == ulSequenceNumber ) + { + pxReturn = pxSegment; + break; + } + } + + return pxReturn; + } + + #endif /* ipconfigUSE_TCP_WIN == 1 */ +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 1 ) + +/** + * @brief Allocate a new segment object, either for transmission or reception. + * + * @param[in] pxWindow: The descriptor of the TCP sliding windows. + * @param[in] ulSequenceNumber: The sequence number. + * @param[in] lCount: The number of bytes stored in this segment. + * @param[in] xIsForRx: True when this is a reception segment. + * + * @return Allocate and initialise a segment descriptor, or NULL when none was available. + */ + static TCPSegment_t * xTCPWindowNew( TCPWindow_t * pxWindow, + uint32_t ulSequenceNumber, + int32_t lCount, + BaseType_t xIsForRx ) + { + TCPSegment_t * pxSegment; + ListItem_t * pxItem; + + /* Allocate a new segment. The socket will borrow all segments from a + * common pool: 'xSegmentList', which is a list of 'TCPSegment_t' */ + if( listLIST_IS_EMPTY( &xSegmentList ) != pdFALSE ) + { + /* If the TCP-stack runs out of segments, you might consider + * increasing 'ipconfigTCP_WIN_SEG_COUNT'. */ + FreeRTOS_debug_printf( ( "xTCPWindow%cxNew: Error: all segments occupied\n", ( xIsForRx != 0 ) ? 'R' : 'T' ) ); + pxSegment = NULL; + } + else + { + /* Pop the item at the head of the list. Semaphore protection is + * not required as only the IP task will call these functions. */ + pxItem = ( ListItem_t * ) listGET_HEAD_ENTRY( &xSegmentList ); + pxSegment = ipCAST_PTR_TO_TYPE_PTR( TCPSegment_t, listGET_LIST_ITEM_OWNER( pxItem ) ); + + configASSERT( pxItem != NULL ); + configASSERT( pxSegment != NULL ); + + /* Remove the item from xSegmentList. */ + ( void ) uxListRemove( pxItem ); + + /* Add it to either the connections' Rx or Tx queue. */ + if( xIsForRx != 0 ) + { + vListInsertFifo( &pxWindow->xRxSegments, pxItem ); + } + else + { + vListInsertFifo( &pxWindow->xTxSegments, pxItem ); + } + + /* And set the segment's timer to zero */ + vTCPTimerSet( &pxSegment->xTransmitTimer ); + + pxSegment->u.ulFlags = 0; + pxSegment->u.bits.bIsForRx = ( xIsForRx != 0 ) ? 1U : 0U; + pxSegment->lMaxLength = lCount; + pxSegment->lDataLength = lCount; + pxSegment->ulSequenceNumber = ulSequenceNumber; + #if ( ipconfigHAS_DEBUG_PRINTF != 0 ) + { + static UBaseType_t xLowestLength = ipconfigTCP_WIN_SEG_COUNT; + UBaseType_t xLength = listCURRENT_LIST_LENGTH( &xSegmentList ); + + if( xLowestLength > xLength ) + { + xLowestLength = xLength; + } + } + #endif /* ipconfigHAS_DEBUG_PRINTF */ + } + + return pxSegment; + } + + + #endif /* ipconfigUSE_TCP_WIN == 1 */ +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 1 ) + +/** + * @brief See if the peer has more packets for this node, before allowing to shut down the connection. + * + * @param[in] pxWindow: The descriptor of the TCP sliding windows. + * + * @return pdTRUE if the connection can be closed. Else, pdFALSE. + */ + BaseType_t xTCPWindowRxEmpty( const TCPWindow_t * pxWindow ) + { + BaseType_t xReturn; + + /* When the peer has a close request (FIN flag), the driver will check + * if there are missing packets in the Rx-queue. It will accept the + * closure of the connection if both conditions are true: + * - the Rx-queue is empty + * - the highest Rx sequence number has been ACK'ed */ + if( listLIST_IS_EMPTY( ( &pxWindow->xRxSegments ) ) == pdFALSE ) + { + /* Rx data has been stored while earlier packets were missing. */ + xReturn = pdFALSE; + } + else if( xSequenceGreaterThanOrEqual( pxWindow->rx.ulCurrentSequenceNumber, pxWindow->rx.ulHighestSequenceNumber ) != pdFALSE ) + { + /* No Rx packets are being stored and the highest sequence number + * that has been received has been ACKed. */ + xReturn = pdTRUE; + } + else + { + FreeRTOS_debug_printf( ( "xTCPWindowRxEmpty: cur %lu highest %lu (empty)\n", + ( pxWindow->rx.ulCurrentSequenceNumber - pxWindow->rx.ulFirstSequenceNumber ), + ( pxWindow->rx.ulHighestSequenceNumber - pxWindow->rx.ulFirstSequenceNumber ) ) ); + xReturn = pdFALSE; + } + + return xReturn; + } + + + #endif /* ipconfigUSE_TCP_WIN == 1 */ +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 1 ) + +/** + * @brief Remove the head item of a list (generic function). + * + * @param[in] pxList: The list of segment descriptors. + * + * @return The address of the segment descriptor, or NULL when not found. + */ + static TCPSegment_t * xTCPWindowGetHead( const List_t * pxList ) + { + TCPSegment_t * pxSegment; + ListItem_t * pxItem; + + /* Detaches and returns the head of a queue. */ + if( listLIST_IS_EMPTY( pxList ) != pdFALSE ) + { + pxSegment = NULL; + } + else + { + pxItem = ( ListItem_t * ) listGET_HEAD_ENTRY( pxList ); + pxSegment = ipCAST_PTR_TO_TYPE_PTR( TCPSegment_t, listGET_LIST_ITEM_OWNER( pxItem ) ); + + ( void ) uxListRemove( pxItem ); + } + + return pxSegment; + } + + #endif /* ipconfigUSE_TCP_WIN == 1 */ +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 1 ) + +/** + * @brief Return the head item of a list (generic function). + * + * @param[in] pxList: The list of segment descriptors. + * + * @return The address of the segment descriptor, or NULL when the list is empty. + */ + static TCPSegment_t * xTCPWindowPeekHead( const List_t * pxList ) + { + const ListItem_t * pxItem; + TCPSegment_t * pxReturn; + + /* Returns the head of a queue but it won't be detached. */ + if( listLIST_IS_EMPTY( pxList ) != pdFALSE ) + { + pxReturn = NULL; + } + else + { + pxItem = ( ListItem_t * ) listGET_HEAD_ENTRY( pxList ); + pxReturn = ipCAST_PTR_TO_TYPE_PTR( TCPSegment_t, listGET_LIST_ITEM_OWNER( pxItem ) ); + } + + return pxReturn; + } + + #endif /* ipconfigUSE_TCP_WIN == 1 */ +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 1 ) + +/** + * @brief Release a segment object, return it to the list of available segment holders. + * + * @param[in] pxSegment: The segment descriptor that must be freed. + */ + static void vTCPWindowFree( TCPSegment_t * pxSegment ) + { + /* Free entry pxSegment because it's not used any more. The ownership + * will be passed back to the segment pool. + * + * Unlink it from one of the queues, if any. */ + if( listLIST_ITEM_CONTAINER( &( pxSegment->xQueueItem ) ) != NULL ) + { + ( void ) uxListRemove( &( pxSegment->xQueueItem ) ); + } + + pxSegment->ulSequenceNumber = 0UL; + pxSegment->lDataLength = 0L; + pxSegment->u.ulFlags = 0UL; + + /* Take it out of xRxSegments/xTxSegments */ + if( listLIST_ITEM_CONTAINER( &( pxSegment->xSegmentItem ) ) != NULL ) + { + ( void ) uxListRemove( &( pxSegment->xSegmentItem ) ); + } + + /* Return it to xSegmentList */ + vListInsertFifo( &xSegmentList, &( pxSegment->xSegmentItem ) ); + } + + + #endif /* ipconfigUSE_TCP_WIN == 1 */ +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 1 ) + +/** + * @brief Return all segment descriptor to the poll of descriptors, before deleting a socket. + * + * @param[in] pxWindow: The descriptor of the TCP sliding windows. + */ + void vTCPWindowDestroy( TCPWindow_t const * pxWindow ) + { + const List_t * pxSegments; + BaseType_t xRound; + TCPSegment_t * pxSegment; + + /* Destroy a window. A TCP window doesn't serve any more. Return all + * owned segments to the pool. In order to save code, it will make 2 rounds, + * one to remove the segments from xRxSegments, and a second round to clear + * xTxSegments*/ + for( xRound = 0; xRound < 2; xRound++ ) + { + if( xRound != 0 ) + { + pxSegments = &( pxWindow->xRxSegments ); + } + else + { + pxSegments = &( pxWindow->xTxSegments ); + } + + if( listLIST_IS_INITIALISED( pxSegments ) ) + { + while( listCURRENT_LIST_LENGTH( pxSegments ) > 0U ) + { + pxSegment = ipCAST_PTR_TO_TYPE_PTR( TCPSegment_t, listGET_OWNER_OF_HEAD_ENTRY( pxSegments ) ); + vTCPWindowFree( pxSegment ); + } + } + } + } + + + #endif /* ipconfigUSE_TCP_WIN == 1 */ +/*-----------------------------------------------------------*/ + +/** + * @brief Create a window for TCP. + * + * @param[in] pxWindow: The window to be created. + * @param[in] ulRxWindowLength: The length of the receive window. + * @param[in] ulTxWindowLength: The length of the transmit window. + * @param[in] ulAckNumber: The first ACK number. + * @param[in] ulSequenceNumber: The first sequence number. + * @param[in] ulMSS: The MSS of the connection. + */ + void vTCPWindowCreate( TCPWindow_t * pxWindow, + uint32_t ulRxWindowLength, + uint32_t ulTxWindowLength, + uint32_t ulAckNumber, + uint32_t ulSequenceNumber, + uint32_t ulMSS ) + { + /* Create and initialize a window. */ + + #if ( ipconfigUSE_TCP_WIN == 1 ) + { + if( xTCPSegments == NULL ) + { + ( void ) prvCreateSectors(); + } + + vListInitialise( &( pxWindow->xTxSegments ) ); + vListInitialise( &( pxWindow->xRxSegments ) ); + + vListInitialise( &( pxWindow->xPriorityQueue ) ); /* Priority queue: segments which must be sent immediately */ + vListInitialise( &( pxWindow->xTxQueue ) ); /* Transmit queue: segments queued for transmission */ + vListInitialise( &( pxWindow->xWaitQueue ) ); /* Waiting queue: outstanding segments */ + } + #endif /* ipconfigUSE_TCP_WIN == 1 */ + + if( xTCPWindowLoggingLevel != 0 ) + { + FreeRTOS_debug_printf( ( "vTCPWindowCreate: for WinLen = Rx/Tx: %lu/%lu\n", + ulRxWindowLength, ulTxWindowLength ) ); + } + + pxWindow->xSize.ulRxWindowLength = ulRxWindowLength; + pxWindow->xSize.ulTxWindowLength = ulTxWindowLength; + + vTCPWindowInit( pxWindow, ulAckNumber, ulSequenceNumber, ulMSS ); + } +/*-----------------------------------------------------------*/ + +/** + * @brief Initialise a TCP window. + * + * @param[in] pxWindow: The window to be initialised. + * @param[in] ulAckNumber: The number of the first ACK. + * @param[in] ulSequenceNumber: The first sequence number. + * @param[in] ulMSS: The MSS of the connection. + */ + void vTCPWindowInit( TCPWindow_t * pxWindow, + uint32_t ulAckNumber, + uint32_t ulSequenceNumber, + uint32_t ulMSS ) + { + const int32_t l500ms = 500; + + pxWindow->u.ulFlags = 0UL; + pxWindow->u.bits.bHasInit = pdTRUE_UNSIGNED; + + if( ulMSS != 0UL ) + { + if( pxWindow->usMSSInit != 0U ) + { + pxWindow->usMSSInit = ( uint16_t ) ulMSS; + } + + if( ( ulMSS < ( uint32_t ) pxWindow->usMSS ) || ( pxWindow->usMSS == 0U ) ) + { + pxWindow->xSize.ulRxWindowLength = ( pxWindow->xSize.ulRxWindowLength / ulMSS ) * ulMSS; + pxWindow->usMSS = ( uint16_t ) ulMSS; + } + } + + #if ( ipconfigUSE_TCP_WIN == 0 ) + { + pxWindow->xTxSegment.lMaxLength = ( int32_t ) pxWindow->usMSS; + } + #endif /* ipconfigUSE_TCP_WIN == 1 */ + + /*Start with a timeout of 2 * 500 ms (1 sec). */ + pxWindow->lSRTT = l500ms; + + /* Just for logging, to print relative sequence numbers. */ + pxWindow->rx.ulFirstSequenceNumber = ulAckNumber; + + /* The segment asked for in the next transmission. */ + pxWindow->rx.ulCurrentSequenceNumber = ulAckNumber; + + /* The right-hand side of the receive window. */ + pxWindow->rx.ulHighestSequenceNumber = ulAckNumber; + + pxWindow->tx.ulFirstSequenceNumber = ulSequenceNumber; + + /* The segment asked for in next transmission. */ + pxWindow->tx.ulCurrentSequenceNumber = ulSequenceNumber; + + /* The sequence number given to the next outgoing byte to be added is + * maintained by lTCPWindowTxAdd(). */ + pxWindow->ulNextTxSequenceNumber = ulSequenceNumber; + + /* The right-hand side of the transmit window. */ + pxWindow->tx.ulHighestSequenceNumber = ulSequenceNumber; + pxWindow->ulOurSequenceNumber = ulSequenceNumber; + } +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 1 ) + +/** + * @brief Free the space occupied by the pool of segment descriptors, normally never used + */ + void vTCPSegmentCleanup( void ) + { + /* Free and clear the TCP segments pointer. This function should only be called + * once FreeRTOS+TCP will no longer be used. No thread-safety is provided for this + * function. */ + if( xTCPSegments != NULL ) + { + vPortFreeLarge( xTCPSegments ); + xTCPSegments = NULL; + } + } + + + #endif /* ipconfgiUSE_TCP_WIN == 1 */ +/*-----------------------------------------------------------*/ + +/*============================================================================= + * + * ###### # # + * # # # # + * # # # # + * # # #### + * ###### ## + * # ## #### + * # # # # + * # # # # + * ### ## # # + * Rx functions + * + *=============================================================================*/ + + #if ( ipconfigUSE_TCP_WIN == 1 ) + +/** + * @brief A expected segment has been received, see if there is overlap with earlier segments. + * + * @param[in] pxWindow: The descriptor of the TCP sliding windows. + * @param[in] ulSequenceNumber: The sequence number of the segment that was received. + * @param[in] ulLength: The number of bytes that were received. + * + * @return The first segment descriptor involved, or NULL when no matching descriptor was found. + */ + static TCPSegment_t * xTCPWindowRxConfirm( const TCPWindow_t * pxWindow, + uint32_t ulSequenceNumber, + uint32_t ulLength ) + { + TCPSegment_t * pxBest = NULL; + const ListItem_t * pxIterator; + uint32_t ulNextSequenceNumber = ulSequenceNumber + ulLength; + const ListItem_t * pxEnd = listGET_END_MARKER( &pxWindow->xRxSegments ); + TCPSegment_t * pxSegment; + + /* A segment has been received with sequence number 'ulSequenceNumber', + * where 'ulCurrentSequenceNumber == ulSequenceNumber', which means that + * exactly this segment was expected. xTCPWindowRxConfirm() will check if + * there is already another segment with a sequence number between (ulSequenceNumber) + * and (ulSequenceNumber+ulLength). Normally none will be found, because + * the next RX segment should have a sequence number equal to + * '(ulSequenceNumber+ulLength)'. */ + + /* Iterate through all RX segments that are stored: */ + for( pxIterator = listGET_NEXT( pxEnd ); + pxIterator != pxEnd; + pxIterator = listGET_NEXT( pxIterator ) ) + { + pxSegment = ipCAST_PTR_TO_TYPE_PTR( TCPSegment_t, listGET_LIST_ITEM_OWNER( pxIterator ) ); + + /* And see if there is a segment for which: + * 'ulSequenceNumber' <= 'pxSegment->ulSequenceNumber' < 'ulNextSequenceNumber' + * If there are more matching segments, the one with the lowest sequence number + * shall be taken */ + if( ( xSequenceGreaterThanOrEqual( pxSegment->ulSequenceNumber, ulSequenceNumber ) != 0 ) && + ( xSequenceLessThan( pxSegment->ulSequenceNumber, ulNextSequenceNumber ) != 0 ) ) + { + if( ( pxBest == NULL ) || ( xSequenceLessThan( pxSegment->ulSequenceNumber, pxBest->ulSequenceNumber ) != 0 ) ) + { + pxBest = pxSegment; + } + } + } + + if( ( pxBest != NULL ) && + ( ( pxBest->ulSequenceNumber != ulSequenceNumber ) || ( pxBest->lDataLength != ( int32_t ) ulLength ) ) ) + { + FreeRTOS_debug_printf( ( "xTCPWindowRxConfirm[%u]: search %lu (+%ld=%lu) found %lu (+%ld=%lu)\n", + pxWindow->usPeerPortNumber, + ulSequenceNumber - pxWindow->rx.ulFirstSequenceNumber, + ulLength, + ulSequenceNumber + ulLength - pxWindow->rx.ulFirstSequenceNumber, + pxBest->ulSequenceNumber - pxWindow->rx.ulFirstSequenceNumber, + pxBest->lDataLength, + pxBest->ulSequenceNumber + ( ( uint32_t ) pxBest->lDataLength ) - pxWindow->rx.ulFirstSequenceNumber ) ); + } + + return pxBest; + } + #endif /* ipconfgiUSE_TCP_WIN == 1 */ +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 1 ) + +/** + * @brief Check what to do with a new incoming packet: store or ignore. + * + * @param[in] pxWindow: The descriptor of the TCP sliding windows. + * @param[in] ulSequenceNumber: The sequence number of the packet received. + * @param[in] ulLength: The number of bytes received. + * @param[in] ulSpace: The available space in the RX stream buffer. + * + * @return 0 or positive value indicating the offset at which the packet is to + * be stored, -1 if the packet is to be ignored. + */ + int32_t lTCPWindowRxCheck( TCPWindow_t * pxWindow, + uint32_t ulSequenceNumber, + uint32_t ulLength, + uint32_t ulSpace ) + { + uint32_t ulCurrentSequenceNumber, ulLast, ulSavedSequenceNumber, ulIntermediateResult = 0; + int32_t lReturn, lDistance; + TCPSegment_t * pxFound; + + /* If lTCPWindowRxCheck( ) returns == 0, the packet will be passed + * directly to user (segment is expected). If it returns a positive + * number, an earlier packet is missing, but this packet may be stored. + * If negative, the packet has already been stored, or it is out-of-order, + * or there is not enough space. + * + * As a side-effect, pxWindow->ulUserDataLength will get set to non-zero, + * if more Rx data may be passed to the user after this packet. */ + + ulCurrentSequenceNumber = pxWindow->rx.ulCurrentSequenceNumber; + + /* For Selective Ack (SACK), used when out-of-sequence data come in. */ + pxWindow->ucOptionLength = 0U; + + /* Non-zero if TCP-windows contains data which must be popped. */ + pxWindow->ulUserDataLength = 0UL; + + if( ulCurrentSequenceNumber == ulSequenceNumber ) + { + /* This is the packet with the lowest sequence number we're waiting + * for. It can be passed directly to the rx stream. */ + if( ulLength > ulSpace ) + { + FreeRTOS_debug_printf( ( "lTCPWindowRxCheck: Refuse %lu bytes, due to lack of space (%lu)\n", ulLength, ulSpace ) ); + lReturn = -1; + } + else + { + ulCurrentSequenceNumber += ulLength; + + if( listCURRENT_LIST_LENGTH( &( pxWindow->xRxSegments ) ) != 0U ) + { + ulSavedSequenceNumber = ulCurrentSequenceNumber; + + /* Clean up all sequence received between ulSequenceNumber and ulSequenceNumber + ulLength since they are duplicated. + * If the server is forced to retransmit packets several time in a row it might send a batch of concatenated packet for speed. + * So we cannot rely on the packets between ulSequenceNumber and ulSequenceNumber + ulLength to be sequential and it is better to just + * clean them out. */ + do + { + pxFound = xTCPWindowRxConfirm( pxWindow, ulSequenceNumber, ulLength ); + + if( pxFound != NULL ) + { + /* Remove it because it will be passed to user directly. */ + vTCPWindowFree( pxFound ); + } + } while( pxFound != NULL ); + + /* Check for following segments that are already in the + * queue and increment ulCurrentSequenceNumber. */ + for( ; ; ) + { + pxFound = xTCPWindowRxFind( pxWindow, ulCurrentSequenceNumber ); + + if( pxFound == NULL ) + { + break; + } + + ulCurrentSequenceNumber += ( uint32_t ) pxFound->lDataLength; + + /* As all packet below this one have been passed to the + * user it can be discarded. */ + vTCPWindowFree( pxFound ); + } + + if( ulSavedSequenceNumber != ulCurrentSequenceNumber ) + { + /* After the current data-package, there is more data + * to be popped. */ + pxWindow->ulUserDataLength = ulCurrentSequenceNumber - ulSavedSequenceNumber; + + if( xTCPWindowLoggingLevel >= 1 ) + { + FreeRTOS_debug_printf( ( "lTCPWindowRxCheck[%d,%d]: retran %lu (Found %lu bytes at %lu cnt %ld)\n", + pxWindow->usPeerPortNumber, pxWindow->usOurPortNumber, + ulSequenceNumber - pxWindow->rx.ulFirstSequenceNumber, + pxWindow->ulUserDataLength, + ulSavedSequenceNumber - pxWindow->rx.ulFirstSequenceNumber, + listCURRENT_LIST_LENGTH( &pxWindow->xRxSegments ) ) ); + } + } + } + + pxWindow->rx.ulCurrentSequenceNumber = ulCurrentSequenceNumber; + + /* Packet was expected, may be passed directly to the socket + * buffer or application. Store the packet at offset 0. */ + lReturn = 0; + } + } + else if( ulCurrentSequenceNumber == ( ulSequenceNumber + 1UL ) ) + { + /* Looks like a TCP keep-alive message. Do not accept/store Rx data + * ulUserDataLength = 0. Not packet out-of-sync. Just reply to it. */ + lReturn = -1; + } + else + { + /* The packet is not the one expected. See if it falls within the Rx + * window so it can be stored. */ + + /* An "out-of-sequence" segment was received, must have missed one. + * Prepare a SACK (Selective ACK). */ + ulLast = ulSequenceNumber + ulLength; + + ulIntermediateResult = ulLast - ulCurrentSequenceNumber; + /* The cast from unsigned long to signed long is on purpose. */ + lDistance = ( int32_t ) ulIntermediateResult; + + if( lDistance <= 0 ) + { + /* An earlier has been received, must be a retransmission of a + * packet that has been accepted already. No need to send out a + * Selective ACK (SACK). */ + lReturn = -1; + } + else if( lDistance > ( int32_t ) ulSpace ) + { + /* The new segment is ahead of rx.ulCurrentSequenceNumber. The + * sequence number of this packet is too far ahead, ignore it. */ + FreeRTOS_debug_printf( ( "lTCPWindowRxCheck: Refuse %lu+%lu bytes, due to lack of space (%lu)\n", lDistance, ulLength, ulSpace ) ); + lReturn = -1; + } + else + { + /* See if there is more data in a contiguous block to make the + * SACK describe a longer range of data. */ + + /* TODO: SACK's may also be delayed for a short period + * This is useful because subsequent packets will be SACK'd with + * single one message + */ + for( ; ; ) + { + pxFound = xTCPWindowRxFind( pxWindow, ulLast ); + + if( pxFound == NULL ) + { + break; + } + + ulLast += ( uint32_t ) pxFound->lDataLength; + } + + if( xTCPWindowLoggingLevel >= 1 ) + { + FreeRTOS_debug_printf( ( "lTCPWindowRxCheck[%d,%d]: seqnr %u exp %u (dist %d) SACK to %u\n", + ( int ) pxWindow->usPeerPortNumber, + ( int ) pxWindow->usOurPortNumber, + ( unsigned ) ulSequenceNumber - pxWindow->rx.ulFirstSequenceNumber, + ( unsigned ) ulCurrentSequenceNumber - pxWindow->rx.ulFirstSequenceNumber, + ( unsigned ) ( ulSequenceNumber - ulCurrentSequenceNumber ), /* want this signed */ + ( unsigned ) ( ulLast - pxWindow->rx.ulFirstSequenceNumber ) ) ); + } + + /* Now prepare the SACK message. + * Code OPTION_CODE_SINGLE_SACK already in network byte order. */ + pxWindow->ulOptionsData[ 0 ] = OPTION_CODE_SINGLE_SACK; + + /* First sequence number that we received. */ + pxWindow->ulOptionsData[ 1 ] = FreeRTOS_htonl( ulSequenceNumber ); + + /* Last + 1 */ + pxWindow->ulOptionsData[ 2 ] = FreeRTOS_htonl( ulLast ); + + /* Which make 12 (3*4) option bytes. */ + pxWindow->ucOptionLength = ( uint8_t ) ( 3U * sizeof( pxWindow->ulOptionsData[ 0 ] ) ); + + pxFound = xTCPWindowRxFind( pxWindow, ulSequenceNumber ); + + if( pxFound != NULL ) + { + /* This out-of-sequence packet has been received for a + * second time. It is already stored but do send a SACK + * again. */ + lReturn = -1; + } + else + { + pxFound = xTCPWindowRxNew( pxWindow, ulSequenceNumber, ( int32_t ) ulLength ); + + if( pxFound == NULL ) + { + /* Can not send a SACK, because the segment cannot be + * stored. */ + pxWindow->ucOptionLength = 0U; + + /* Needs to be stored but there is no segment + * available. */ + lReturn = -1; + } + else + { + if( xTCPWindowLoggingLevel != 0 ) + { + FreeRTOS_debug_printf( ( "lTCPWindowRxCheck[%u,%u]: seqnr %lu (cnt %lu)\n", + pxWindow->usPeerPortNumber, pxWindow->usOurPortNumber, ulSequenceNumber - pxWindow->rx.ulFirstSequenceNumber, + listCURRENT_LIST_LENGTH( &pxWindow->xRxSegments ) ) ); + FreeRTOS_flush_logging(); + } + + /* Return a positive value. The packet may be accepted + * and stored but an earlier packet is still missing. */ + ulIntermediateResult = ulSequenceNumber - ulCurrentSequenceNumber; + lReturn = ( int32_t ) ulIntermediateResult; + } + } + } + } + + return lReturn; + } + + + #endif /* ipconfgiUSE_TCP_WIN == 1 */ +/*-----------------------------------------------------------*/ + +/*============================================================================= + * + * ######### # # + * # # # # # + * # # # + * # #### + * # ## + * # #### + * # # # + * # # # + * ##### # # + * + * Tx functions + * + *=============================================================================*/ + + #if ( ipconfigUSE_TCP_WIN == 1 ) + +/** + * @brief Increment the position in a circular buffer of size 'lMax'. + * + * @param[in] lPosition: The current index in the buffer. + * @param[in] lMax: The total number of items in this buffer. + * @param[in] lCount: The number of bytes that must be advanced. + * + * @return The new incremented position, or "( lPosition + lCount ) % lMax". + */ + static int32_t lTCPIncrementTxPosition( int32_t lPosition, + int32_t lMax, + int32_t lCount ) + { + int32_t lReturn; + + + /* +TCP stores data in circular buffers. Calculate the next position to + * store. */ + lReturn = lPosition + lCount; + + if( lReturn >= lMax ) + { + lReturn -= lMax; + } + + return lReturn; + } + + #endif /* ipconfigUSE_TCP_WIN == 1 */ +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 1 ) + +/** + * @brief Will add data to be transmitted to the front of the segment fifo. + * + * @param[in] pxWindow: The descriptor of the TCP sliding windows. + * @param[in] ulLength: The number of bytes that will be sent. + * @param[in] lPosition: The index in the TX stream buffer. + * @param[in] lMax: The size of the ( circular ) TX stream buffer. + * + * @return The number of bytes added to the sliding window for transmission. + * + */ + int32_t lTCPWindowTxAdd( TCPWindow_t * pxWindow, + uint32_t ulLength, + int32_t lPosition, + int32_t lMax ) + { + int32_t lBytesLeft = ( int32_t ) ulLength, lToWrite; + int32_t lDone = 0; + int32_t lBufferIndex = lPosition; + TCPSegment_t * pxSegment = pxWindow->pxHeadSegment; + + /* Puts a message in the Tx-window (after buffer size has been + * verified). */ + if( pxSegment != NULL ) + { + if( pxSegment->lDataLength < pxSegment->lMaxLength ) + { + if( ( pxSegment->u.bits.bOutstanding == pdFALSE_UNSIGNED ) && ( pxSegment->lDataLength != 0 ) ) + { + /* Adding data to a segment that was already in the TX queue. It + * will be filled-up to a maximum of MSS (maximum segment size). */ + lToWrite = FreeRTOS_min_int32( lBytesLeft, pxSegment->lMaxLength - pxSegment->lDataLength ); + + pxSegment->lDataLength += lToWrite; + + if( pxSegment->lDataLength >= pxSegment->lMaxLength ) + { + /* This segment is full, don't add more bytes. */ + pxWindow->pxHeadSegment = NULL; + } + + lBytesLeft -= lToWrite; + + /* ulNextTxSequenceNumber is the sequence number of the next byte to + * be stored for transmission. */ + pxWindow->ulNextTxSequenceNumber += ( uint32_t ) lToWrite; + + /* Increased the return value. */ + lDone += lToWrite; + + /* Some detailed logging, for those who're interested. */ + if( ( xTCPWindowLoggingLevel >= 2 ) && ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) ) + { + FreeRTOS_debug_printf( ( "lTCPWindowTxAdd: Add %4lu bytes for seqNr %lu len %4lu (nxt %lu) pos %lu\n", + ulLength, + pxSegment->ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, + pxSegment->lDataLength, + pxWindow->ulNextTxSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, + pxSegment->lStreamPos ) ); + FreeRTOS_flush_logging(); + } + + /* Calculate the next position in the circular data buffer, knowing + * its maximum length 'lMax'. */ + lBufferIndex = lTCPIncrementTxPosition( lBufferIndex, lMax, lToWrite ); + } + } + } + + while( lBytesLeft > 0 ) + { + /* The current transmission segment is full, create new segments as + * needed. */ + pxSegment = xTCPWindowTxNew( pxWindow, pxWindow->ulNextTxSequenceNumber, ( int32_t ) pxWindow->usMSS ); + + if( pxSegment != NULL ) + { + /* Store as many as needed, but no more than the maximum + * (MSS). */ + lToWrite = FreeRTOS_min_int32( lBytesLeft, pxSegment->lMaxLength ); + + pxSegment->lDataLength = lToWrite; + pxSegment->lStreamPos = lBufferIndex; + lBytesLeft -= lToWrite; + lBufferIndex = lTCPIncrementTxPosition( lBufferIndex, lMax, lToWrite ); + pxWindow->ulNextTxSequenceNumber += ( uint32_t ) lToWrite; + lDone += lToWrite; + + /* Link this segment in the Tx-Queue. */ + vListInsertFifo( &( pxWindow->xTxQueue ), &( pxSegment->xQueueItem ) ); + + /* Let 'pxHeadSegment' point to this segment if there is still + * space. */ + if( pxSegment->lDataLength < pxSegment->lMaxLength ) + { + pxWindow->pxHeadSegment = pxSegment; + } + else + { + pxWindow->pxHeadSegment = NULL; + } + + if( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) ) + { + if( ( xTCPWindowLoggingLevel >= 3 ) || + ( ( xTCPWindowLoggingLevel >= 2 ) && ( pxWindow->pxHeadSegment != NULL ) ) ) + { + FreeRTOS_debug_printf( ( "lTCPWindowTxAdd: New %4ld bytes for seqNr %lu len %4lu (nxt %lu) pos %lu\n", + ulLength, + pxSegment->ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, + pxSegment->lDataLength, + pxWindow->ulNextTxSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, + pxSegment->lStreamPos ) ); + FreeRTOS_flush_logging(); + } + } + } + else + { + /* A sever situation: running out of segments for transmission. + * No more data can be sent at the moment. */ + if( lDone != 0 ) + { + FreeRTOS_debug_printf( ( "lTCPWindowTxAdd: Sorry all buffers full (cancel %ld bytes)\n", lBytesLeft ) ); + } + + break; + } + } + + return lDone; + } + + + #endif /* ipconfigUSE_TCP_WIN == 1 */ +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 1 ) + +/** + * @brief Returns true if there are no more outstanding TX segments. + * + * @param[in] pxWindow: The descriptor of the TCP sliding windows. + * + * @return pdTRUE if there are no more outstanding Tx segments, else pdFALSE. + */ + BaseType_t xTCPWindowTxDone( const TCPWindow_t * pxWindow ) + { + return listLIST_IS_EMPTY( ( &pxWindow->xTxSegments ) ); + } + + #endif /* ipconfigUSE_TCP_WIN == 1 */ +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 1 ) + +/** + * @brief Find out if the peer is able to receive more data. + * + * @param[in] pxWindow: The descriptor of the TCP sliding windows. + * @param[in] ulWindowSize: The number of bytes in this segment. + * + * @return True if the peer has space in it window to receive more data. + */ + static BaseType_t prvTCPWindowTxHasSpace( TCPWindow_t const * pxWindow, + uint32_t ulWindowSize ) + { + uint32_t ulTxOutstanding; + BaseType_t xHasSpace; + const TCPSegment_t * pxSegment; + uint32_t ulNettSize; + + /* This function will look if there is new transmission data. It will + * return true if there is data to be sent. */ + + pxSegment = xTCPWindowPeekHead( &( pxWindow->xTxQueue ) ); + + if( pxSegment == NULL ) + { + xHasSpace = pdFALSE; + } + else + { + /* How much data is outstanding, i.e. how much data has been sent + * but not yet acknowledged ? */ + if( pxWindow->tx.ulHighestSequenceNumber >= pxWindow->tx.ulCurrentSequenceNumber ) + { + ulTxOutstanding = pxWindow->tx.ulHighestSequenceNumber - pxWindow->tx.ulCurrentSequenceNumber; + } + else + { + ulTxOutstanding = 0UL; + } + + /* Subtract this from the peer's space. */ + ulNettSize = ulWindowSize - FreeRTOS_min_uint32( ulWindowSize, ulTxOutstanding ); + + /* See if the next segment may be sent. */ + if( ulNettSize >= ( uint32_t ) pxSegment->lDataLength ) + { + xHasSpace = pdTRUE; + } + else + { + xHasSpace = pdFALSE; + } + + /* If 'xHasSpace', it looks like the peer has at least space for 1 + * more new segment of size MSS. xSize.ulTxWindowLength is the self-imposed + * limitation of the transmission window (in case of many resends it + * may be decreased). */ + if( ( ulTxOutstanding != 0UL ) && ( pxWindow->xSize.ulTxWindowLength < ( ulTxOutstanding + ( ( uint32_t ) pxSegment->lDataLength ) ) ) ) + { + xHasSpace = pdFALSE; + } + } + + return xHasSpace; + } + + + #endif /* ipconfigUSE_TCP_WIN == 1 */ +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 1 ) + +/** + * @brief Returns true if there is TX data that can be sent right now. + * + * @param[in] pxWindow: The descriptor of the TCP sliding windows. + * @param[in] ulWindowSize: The current size of the sliding RX window of the peer. + * @param[out] pulDelay: The delay before the packet may be sent. + * + * @return pdTRUE if there is Tx data that can be sent, else pdFALSE. + */ + BaseType_t xTCPWindowTxHasData( TCPWindow_t const * pxWindow, + uint32_t ulWindowSize, + TickType_t * pulDelay ) + { + TCPSegment_t const * pxSegment; + BaseType_t xReturn; + TickType_t ulAge, ulMaxAge; + + *pulDelay = 0U; + + if( listLIST_IS_EMPTY( &pxWindow->xPriorityQueue ) == pdFALSE ) + { + /* No need to look at retransmissions or new transmission as long as + * there are priority segments. *pulDelay equals zero, meaning it must + * be sent out immediately. */ + xReturn = pdTRUE; + } + else + { + pxSegment = xTCPWindowPeekHead( &( pxWindow->xWaitQueue ) ); + + if( pxSegment != NULL ) + { + /* There is an outstanding segment, see if it is time to resend + * it. */ + ulAge = ulTimerGetAge( &pxSegment->xTransmitTimer ); + + /* After a packet has been sent for the first time, it will wait + * '1 * lSRTT' ms for an ACK. A second time it will wait '2 * lSRTT' ms, + * each time doubling the time-out */ + ulMaxAge = ( 1UL << pxSegment->u.bits.ucTransmitCount ) * ( ( uint32_t ) pxWindow->lSRTT ); + + if( ulMaxAge > ulAge ) + { + /* A segment must be sent after this amount of msecs */ + *pulDelay = ulMaxAge - ulAge; + } + + xReturn = pdTRUE; + } + else + { + /* No priority segment, no outstanding data, see if there is new + * transmission data. */ + pxSegment = xTCPWindowPeekHead( &pxWindow->xTxQueue ); + + /* See if it fits in the peer's reception window. */ + if( pxSegment == NULL ) + { + xReturn = pdFALSE; + } + else if( prvTCPWindowTxHasSpace( pxWindow, ulWindowSize ) == pdFALSE ) + { + /* Too many outstanding messages. */ + xReturn = pdFALSE; + } + else if( ( pxWindow->u.bits.bSendFullSize != pdFALSE_UNSIGNED ) && ( pxSegment->lDataLength < pxSegment->lMaxLength ) ) + { + /* 'bSendFullSize' is a special optimisation. If true, the + * driver will only sent completely filled packets (of MSS + * bytes). */ + xReturn = pdFALSE; + } + else + { + xReturn = pdTRUE; + } + } + } + + return xReturn; + } + + + #endif /* ipconfigUSE_TCP_WIN == 1 */ +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 1 ) + +/** + * @brief Get data that can be transmitted right now. + * + * @param[in] pxWindow: The descriptor of the TCP sliding windows. + * @param[in] ulWindowSize: The current size of the sliding RX window of the peer. + * @param[out] plPosition: The index within the TX stream buffer of the first byte to be sent. + * + * @return The amount of data in bytes that can be transmitted right now. + */ + uint32_t ulTCPWindowTxGet( TCPWindow_t * pxWindow, + uint32_t ulWindowSize, + int32_t * plPosition ) + { + TCPSegment_t * pxSegment; + uint32_t ulMaxTime; + uint32_t ulReturn = ~0UL; + + + /* Fetches data to be sent-out now. + * + * Priority messages: segments with a resend need no check current sliding + * window size. */ + pxSegment = xTCPWindowGetHead( &( pxWindow->xPriorityQueue ) ); + pxWindow->ulOurSequenceNumber = pxWindow->tx.ulHighestSequenceNumber; + + if( pxSegment == NULL ) + { + /* Waiting messages: outstanding messages with a running timer + * neither check peer's reception window size because these packets + * have been sent earlier. */ + pxSegment = xTCPWindowPeekHead( &( pxWindow->xWaitQueue ) ); + + if( pxSegment != NULL ) + { + /* Do check the timing. */ + ulMaxTime = ( 1UL << pxSegment->u.bits.ucTransmitCount ) * ( ( uint32_t ) pxWindow->lSRTT ); + + if( ulTimerGetAge( &pxSegment->xTransmitTimer ) > ulMaxTime ) + { + /* A normal (non-fast) retransmission. Move it from the + * head of the waiting queue. */ + pxSegment = xTCPWindowGetHead( &( pxWindow->xWaitQueue ) ); + pxSegment->u.bits.ucDupAckCount = ( uint8_t ) pdFALSE_UNSIGNED; + + /* Some detailed logging. */ + if( ( xTCPWindowLoggingLevel != 0 ) && ( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) ) ) + { + FreeRTOS_debug_printf( ( "ulTCPWindowTxGet[%u,%u]: WaitQueue %ld bytes for sequence number %lu (%lX)\n", + pxWindow->usPeerPortNumber, + pxWindow->usOurPortNumber, + pxSegment->lDataLength, + pxSegment->ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, + pxSegment->ulSequenceNumber ) ); + FreeRTOS_flush_logging(); + } + } + else + { + pxSegment = NULL; + } + } + + if( pxSegment == NULL ) + { + /* New messages: sent-out for the first time. Check current + * sliding window size of peer. */ + pxSegment = xTCPWindowPeekHead( &( pxWindow->xTxQueue ) ); + + if( pxSegment == NULL ) + { + /* No segments queued. */ + ulReturn = 0UL; + } + else if( ( pxWindow->u.bits.bSendFullSize != pdFALSE_UNSIGNED ) && ( pxSegment->lDataLength < pxSegment->lMaxLength ) ) + { + /* A segment has been queued but the driver waits until it + * has a full size of MSS. */ + ulReturn = 0; + } + else if( prvTCPWindowTxHasSpace( pxWindow, ulWindowSize ) == pdFALSE ) + { + /* Peer has no more space at this moment. */ + ulReturn = 0; + } + else + { + /* Move it out of the Tx queue. */ + pxSegment = xTCPWindowGetHead( &( pxWindow->xTxQueue ) ); + + /* Don't let pxHeadSegment point to this segment any more, + * so no more data will be added. */ + if( pxWindow->pxHeadSegment == pxSegment ) + { + pxWindow->pxHeadSegment = NULL; + } + + /* pxWindow->tx.highest registers the highest sequence + * number in our transmission window. */ + pxWindow->tx.ulHighestSequenceNumber = pxSegment->ulSequenceNumber + ( ( uint32_t ) pxSegment->lDataLength ); + + /* ...and more detailed logging */ + if( ( xTCPWindowLoggingLevel >= 2 ) && ( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) ) ) + { + FreeRTOS_debug_printf( ( "ulTCPWindowTxGet[%u,%u]: XmitQueue %ld bytes for sequence number %lu (ws %lu)\n", + pxWindow->usPeerPortNumber, + pxWindow->usOurPortNumber, + pxSegment->lDataLength, + pxSegment->ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, + ulWindowSize ) ); + FreeRTOS_flush_logging(); + } + } + } + } + else + { + /* There is a priority segment. It doesn't need any checking for + * space or timeouts. */ + if( xTCPWindowLoggingLevel != 0 ) + { + FreeRTOS_debug_printf( ( "ulTCPWindowTxGet[%u,%u]: PrioQueue %ld bytes for sequence number %lu (ws %lu)\n", + pxWindow->usPeerPortNumber, + pxWindow->usOurPortNumber, + pxSegment->lDataLength, + pxSegment->ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, + ulWindowSize ) ); + FreeRTOS_flush_logging(); + } + } + + /* See if it has already been determined to return 0. */ + if( ulReturn != 0UL ) + { + /* pxSegment is not NULL when ulReturn != 0UL. */ + configASSERT( pxSegment != NULL ); + configASSERT( listLIST_ITEM_CONTAINER( &( pxSegment->xQueueItem ) ) == NULL ); + + /* Now that the segment will be transmitted, add it to the tail of + * the waiting queue. */ + vListInsertFifo( &pxWindow->xWaitQueue, &pxSegment->xQueueItem ); + + /* And mark it as outstanding. */ + pxSegment->u.bits.bOutstanding = pdTRUE_UNSIGNED; + + /* Administer the transmit count, needed for fast + * retransmissions. */ + ( pxSegment->u.bits.ucTransmitCount )++; + + /* If there have been several retransmissions (4), decrease the + * size of the transmission window to at most 2 times MSS. */ + if( pxSegment->u.bits.ucTransmitCount == MAX_TRANSMIT_COUNT_USING_LARGE_WINDOW ) + { + if( pxWindow->xSize.ulTxWindowLength > ( 2U * ( ( uint32_t ) pxWindow->usMSS ) ) ) + { + FreeRTOS_debug_printf( ( "ulTCPWindowTxGet[%u - %d]: Change Tx window: %lu -> %u\n", + pxWindow->usPeerPortNumber, + pxWindow->usOurPortNumber, + pxWindow->xSize.ulTxWindowLength, + 2U * pxWindow->usMSS ) ); + pxWindow->xSize.ulTxWindowLength = ( 2UL * pxWindow->usMSS ); + } + } + + /* Clear the transmit timer. */ + vTCPTimerSet( &( pxSegment->xTransmitTimer ) ); + + pxWindow->ulOurSequenceNumber = pxSegment->ulSequenceNumber; + + /* Inform the caller where to find the data within the queue. */ + *plPosition = pxSegment->lStreamPos; + + /* And return the length of the data segment */ + ulReturn = ( uint32_t ) pxSegment->lDataLength; + } + + return ulReturn; + } + + + #endif /* ipconfigUSE_TCP_WIN == 1 */ +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 1 ) + +/** + * @brief An acknowledgement or a selective ACK (SACK) was received. See if some outstanding data + * may be removed from the transmission queue(s). All TX segments for which + * ( ( ulSequenceNumber >= ulFirst ) && ( ulSequenceNumber < ulLast ) in a contiguous block. + * Note that the segments are stored in xTxSegments in a strict sequential order. + * + * @param[in] pxWindow: The TCP-window object of the current connection. + * @param[in] ulFirst: The sequence number of the first byte that was acknowledged. + * @param[in] ulLast: The sequence number of the last byte ( minus one ) that was acknowledged. + * + * @return number of bytes that the tail of txStream may be advanced. + */ + static uint32_t prvTCPWindowTxCheckAck( TCPWindow_t * pxWindow, + uint32_t ulFirst, + uint32_t ulLast ) + { + uint32_t ulBytesConfirmed = 0U; + uint32_t ulSequenceNumber = ulFirst, ulDataLength; + const ListItem_t * pxIterator; + const ListItem_t * pxEnd = listGET_END_MARKER( &pxWindow->xTxSegments ); + BaseType_t xDoUnlink; + TCPSegment_t * pxSegment; + + /* An acknowledgement or a selective ACK (SACK) was received. See if some outstanding data + * may be removed from the transmission queue(s). + * All TX segments for which + * ( ( ulSequenceNumber >= ulFirst ) && ( ulSequenceNumber < ulLast ) in a + * contiguous block. Note that the segments are stored in xTxSegments in a + * strict sequential order. */ + + /* SRTT[i] = (1-a) * SRTT[i-1] + a * RTT + * + * 0 < a < 1; usually a = 1/8 + * + * RTO = 2 * SRTT + * + * where: + * RTT is Round Trip Time + * SRTT is Smoothed RTT + * RTO is Retransmit timeout + * + * A Smoothed RTT will increase quickly, but it is conservative when + * becoming smaller. */ + + pxIterator = listGET_NEXT( pxEnd ); + + while( ( pxIterator != pxEnd ) && ( xSequenceLessThan( ulSequenceNumber, ulLast ) != 0 ) ) + { + xDoUnlink = pdFALSE; + pxSegment = ipCAST_PTR_TO_TYPE_PTR( TCPSegment_t, listGET_LIST_ITEM_OWNER( pxIterator ) ); + + /* Move to the next item because the current item might get + * removed. */ + pxIterator = ( const ListItem_t * ) listGET_NEXT( pxIterator ); + + /* Continue if this segment does not fall within the ACK'd range. */ + if( xSequenceGreaterThan( ulSequenceNumber, pxSegment->ulSequenceNumber ) != pdFALSE ) + { + continue; + } + + /* Is it ready? */ + if( ulSequenceNumber != pxSegment->ulSequenceNumber ) + { + /* coverity[break_stmt] : Break statement terminating the loop */ + break; + } + + ulDataLength = ( uint32_t ) pxSegment->lDataLength; + + if( pxSegment->u.bits.bAcked == pdFALSE_UNSIGNED ) + { + if( xSequenceGreaterThan( pxSegment->ulSequenceNumber + ( uint32_t ) ulDataLength, ulLast ) != pdFALSE ) + { + /* What happens? Only part of this segment was accepted, + * probably due to WND limits + * + * AAAAAAA BBBBBBB << acked + * aaaaaaa aaaa << sent */ + #if ( ipconfigHAS_DEBUG_PRINTF != 0 ) + { + uint32_t ulFirstSeq = pxSegment->ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber; + FreeRTOS_debug_printf( ( "prvTCPWindowTxCheckAck[%u.%u]: %lu - %lu Partial sequence number %lu - %lu\n", + pxWindow->usPeerPortNumber, + pxWindow->usOurPortNumber, + ulFirstSeq - pxWindow->tx.ulFirstSequenceNumber, + ulLast - pxWindow->tx.ulFirstSequenceNumber, + ulFirstSeq, ulFirstSeq + ulDataLength ) ); + } + #endif /* ipconfigHAS_DEBUG_PRINTF */ + break; + } + + /* This segment is fully ACK'd, set the flag. */ + pxSegment->u.bits.bAcked = pdTRUE; + + /* Calculate the RTT only if the segment was sent-out for the + * first time and if this is the last ACK'd segment in a range. */ + if( ( pxSegment->u.bits.ucTransmitCount == 1U ) && ( ( pxSegment->ulSequenceNumber + ulDataLength ) == ulLast ) ) + { + int32_t mS = ( int32_t ) ulTimerGetAge( &( pxSegment->xTransmitTimer ) ); + + if( pxWindow->lSRTT >= mS ) + { + /* RTT becomes smaller: adapt slowly. */ + pxWindow->lSRTT = ( ( winSRTT_DECREMENT_NEW * mS ) + ( winSRTT_DECREMENT_CURRENT * pxWindow->lSRTT ) ) / ( winSRTT_DECREMENT_NEW + winSRTT_DECREMENT_CURRENT ); + } + else + { + /* RTT becomes larger: adapt quicker */ + pxWindow->lSRTT = ( ( winSRTT_INCREMENT_NEW * mS ) + ( winSRTT_INCREMENT_CURRENT * pxWindow->lSRTT ) ) / ( winSRTT_INCREMENT_NEW + winSRTT_INCREMENT_CURRENT ); + } + + /* Cap to the minimum of 50ms. */ + if( pxWindow->lSRTT < winSRTT_CAP_mS ) + { + pxWindow->lSRTT = winSRTT_CAP_mS; + } + } + + /* Unlink it from the 3 queues, but do not destroy it (yet). */ + xDoUnlink = pdTRUE; + } + + /* pxSegment->u.bits.bAcked is now true. Is it located at the left + * side of the transmission queue? If so, it may be freed. */ + if( ulSequenceNumber == pxWindow->tx.ulCurrentSequenceNumber ) + { + if( ( xTCPWindowLoggingLevel >= 2 ) && ( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) ) ) + { + FreeRTOS_debug_printf( ( "prvTCPWindowTxCheckAck: %lu - %lu Ready sequence number %lu\n", + ulFirst - pxWindow->tx.ulFirstSequenceNumber, + ulLast - pxWindow->tx.ulFirstSequenceNumber, + pxSegment->ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber ) ); + } + + /* Increase the left-hand value of the transmission window. */ + pxWindow->tx.ulCurrentSequenceNumber += ulDataLength; + + /* This function will return the number of bytes that the tail + * of txStream may be advanced. */ + ulBytesConfirmed += ulDataLength; + + /* All segments below tx.ulCurrentSequenceNumber may be freed. */ + vTCPWindowFree( pxSegment ); + + /* No need to unlink it any more. */ + xDoUnlink = pdFALSE; + } + + if( ( xDoUnlink != pdFALSE ) && ( listLIST_ITEM_CONTAINER( &( pxSegment->xQueueItem ) ) != NULL ) ) + { + /* Remove item from its queues. */ + ( void ) uxListRemove( &pxSegment->xQueueItem ); + } + + ulSequenceNumber += ulDataLength; + } + + return ulBytesConfirmed; + } + + #endif /* ipconfigUSE_TCP_WIN == 1 */ +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 1 ) + +/** + * @brief See if there are segments that need a fast retransmission. + * + * @param[in] pxWindow: The descriptor of the TCP sliding windows. + * @param[in] ulFirst: The sequence number of the first segment that must be checked. + * + * @return The number of segments that need a fast retransmission. + */ + static uint32_t prvTCPWindowFastRetransmit( TCPWindow_t * pxWindow, + uint32_t ulFirst ) + { + const ListItem_t * pxIterator; + const ListItem_t * pxEnd; + TCPSegment_t * pxSegment; + uint32_t ulCount = 0UL; + + /* A higher Tx block has been acknowledged. Now iterate through the + * xWaitQueue to find a possible condition for a FAST retransmission. */ + + pxEnd = listGET_END_MARKER( &( pxWindow->xWaitQueue ) ); + + pxIterator = listGET_NEXT( pxEnd ); + + while( pxIterator != pxEnd ) + { + /* Get the owner, which is a TCP segment. */ + pxSegment = ipCAST_PTR_TO_TYPE_PTR( TCPSegment_t, listGET_LIST_ITEM_OWNER( pxIterator ) ); + + /* Hop to the next item before the current gets unlinked. */ + pxIterator = listGET_NEXT( pxIterator ); + + /* Fast retransmission: + * When 3 packets with a higher sequence number have been acknowledged + * by the peer, it is very unlikely a current packet will ever arrive. + * It will be retransmitted far before the RTO. */ + if( pxSegment->u.bits.bAcked == pdFALSE_UNSIGNED ) + { + if( xSequenceLessThan( pxSegment->ulSequenceNumber, ulFirst ) != pdFALSE ) + { + pxSegment->u.bits.ucDupAckCount++; + + if( pxSegment->u.bits.ucDupAckCount == DUPLICATE_ACKS_BEFORE_FAST_RETRANSMIT ) + { + pxSegment->u.bits.ucTransmitCount = ( uint8_t ) pdFALSE; + + /* Not clearing 'ucDupAckCount' yet as more SACK's might come in + * which might lead to a second fast rexmit. */ + if( ( xTCPWindowLoggingLevel >= 0 ) && ( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) ) ) + { + FreeRTOS_debug_printf( ( "prvTCPWindowFastRetransmit: Requeue sequence number %lu < %lu\n", + pxSegment->ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, + ulFirst - pxWindow->tx.ulFirstSequenceNumber ) ); + FreeRTOS_flush_logging(); + } + + /* Remove it from xWaitQueue. */ + ( void ) uxListRemove( &pxSegment->xQueueItem ); + + /* Add this segment to the priority queue so it gets + * retransmitted immediately. */ + vListInsertFifo( &( pxWindow->xPriorityQueue ), &( pxSegment->xQueueItem ) ); + ulCount++; + } + } + } + } + + return ulCount; + } + + #endif /* ipconfigUSE_TCP_WIN == 1 */ +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 1 ) + +/** + * @brief Receive a normal ACK. + * + * @param[in] pxWindow: Window in which a data is receive. + * @param[in] ulSequenceNumber: The sequence number of the ACK. + * + * @return The location where the packet should be added. + */ + uint32_t ulTCPWindowTxAck( TCPWindow_t * pxWindow, + uint32_t ulSequenceNumber ) + { + uint32_t ulFirstSequence, ulReturn; + + /* Receive a normal ACK. */ + + ulFirstSequence = pxWindow->tx.ulCurrentSequenceNumber; + + if( xSequenceLessThanOrEqual( ulSequenceNumber, ulFirstSequence ) != pdFALSE ) + { + ulReturn = 0UL; + } + else + { + ulReturn = prvTCPWindowTxCheckAck( pxWindow, ulFirstSequence, ulSequenceNumber ); + } + + return ulReturn; + } + + #endif /* ipconfigUSE_TCP_WIN == 1 */ +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 1 ) + +/** + * @brief Receive a SACK option. + * + * @param[in] pxWindow: Window in which the data is received. + * @param[in] ulFirst: Index of starting position of options. + * @param[in] ulLast: Index of end position of the options. + * + * @return returns the number of bytes which have been acked starting from + * the head position. + */ + uint32_t ulTCPWindowTxSack( TCPWindow_t * pxWindow, + uint32_t ulFirst, + uint32_t ulLast ) + { + uint32_t ulAckCount; + uint32_t ulCurrentSequenceNumber = pxWindow->tx.ulCurrentSequenceNumber; + + /* Receive a SACK option. */ + ulAckCount = prvTCPWindowTxCheckAck( pxWindow, ulFirst, ulLast ); + ( void ) prvTCPWindowFastRetransmit( pxWindow, ulFirst ); + + if( ( xTCPWindowLoggingLevel >= 1 ) && ( xSequenceGreaterThan( ulFirst, ulCurrentSequenceNumber ) != pdFALSE ) ) + { + FreeRTOS_debug_printf( ( "ulTCPWindowTxSack[%u,%u]: from %lu to %lu (ack = %lu)\n", + pxWindow->usPeerPortNumber, + pxWindow->usOurPortNumber, + ulFirst - pxWindow->tx.ulFirstSequenceNumber, + ulLast - pxWindow->tx.ulFirstSequenceNumber, + pxWindow->tx.ulCurrentSequenceNumber - pxWindow->tx.ulFirstSequenceNumber ) ); + FreeRTOS_flush_logging(); + } + + return ulAckCount; + } + + + #endif /* ipconfigUSE_TCP_WIN == 1 */ +/*-----------------------------------------------------------*/ + +/* + ##### # ##### #### ###### + # # # # # # # # # # # + # # # # # # + # ### ##### # # # # # # + # # # # # # # # ##### + # # # # # # #### # # # + # # # # # # # # # # + # # # # #### # # # # + #### ##### # # # #### #### #### + # + ### + */ + #if ( ipconfigUSE_TCP_WIN == 0 ) + +/** + * @brief Data was received at 'ulSequenceNumber'. See if it was expected + * and if there is enough space to store the new data. + * + * @param[in] pxWindow: The window to be checked. + * @param[in] ulSequenceNumber: Sequence number of the data received. + * @param[in] ulLength: Length of the data received. + * @param[in] ulSpace: Space in the buffer. + * + * @return A 0 is returned if there is enough space and the sequence number is correct, + * if not then a -1 is returned. + * + * @note if true may be passed directly to user (segment expected and window is empty). + * But pxWindow->ackno should always be used to set "BUF->ackno". + */ + int32_t lTCPWindowRxCheck( TCPWindow_t * pxWindow, + uint32_t ulSequenceNumber, + uint32_t ulLength, + uint32_t ulSpace ) + { + int32_t iReturn; + + /* Data was received at 'ulSequenceNumber'. See if it was expected + * and if there is enough space to store the new data. */ + if( ( pxWindow->rx.ulCurrentSequenceNumber != ulSequenceNumber ) || ( ulSpace < ulLength ) ) + { + iReturn = -1; + } + else + { + pxWindow->rx.ulCurrentSequenceNumber += ( uint32_t ) ulLength; + iReturn = 0; + } + + return iReturn; + } + + + #endif /* ipconfigUSE_TCP_WIN == 0 */ +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 0 ) + +/** + * @brief Add data to the Tx Window. + * + * @param[in] pxWindow: The window to which the data is to be added. + * @param[in] ulLength: The length of the data to be added. + * @param[in] lPosition: Position in the stream. + * @param[in] lMax: Size of the Tx stream. + * + * @return The data actually added. + */ + int32_t lTCPWindowTxAdd( TCPWindow_t * pxWindow, + uint32_t ulLength, + int32_t lPosition, + int32_t lMax ) + { + TCPSegment_t * pxSegment = &( pxWindow->xTxSegment ); + int32_t lResult; + + /* Data is being scheduled for transmission. */ + + /* lMax would indicate the size of the txStream. */ + ( void ) lMax; + + /* This is tiny TCP: there is only 1 segment for outgoing data. + * As long as 'lDataLength' is unequal to zero, the segment is still occupied. */ + if( pxSegment->lDataLength > 0 ) + { + lResult = 0L; + } + else + { + if( ulLength > ( uint32_t ) pxSegment->lMaxLength ) + { + if( ( xTCPWindowLoggingLevel != 0 ) && ( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) != pdFALSE ) ) + { + FreeRTOS_debug_printf( ( "lTCPWindowTxAdd: can only store %ld / %ld bytes\n", ulLength, pxSegment->lMaxLength ) ); + } + + ulLength = ( uint32_t ) pxSegment->lMaxLength; + } + + if( ( xTCPWindowLoggingLevel != 0 ) && ( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) != pdFALSE ) ) + { + FreeRTOS_debug_printf( ( "lTCPWindowTxAdd: SeqNr %ld (%ld) Len %ld\n", + pxWindow->ulNextTxSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, + pxWindow->tx.ulCurrentSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, + ulLength ) ); + } + + /* The sequence number of the first byte in this packet. */ + pxSegment->ulSequenceNumber = pxWindow->ulNextTxSequenceNumber; + pxSegment->lDataLength = ( int32_t ) ulLength; + pxSegment->lStreamPos = lPosition; + pxSegment->u.ulFlags = 0UL; + vTCPTimerSet( &( pxSegment->xTransmitTimer ) ); + + /* Increase the sequence number of the next data to be stored for + * transmission. */ + pxWindow->ulNextTxSequenceNumber += ulLength; + lResult = ( int32_t ) ulLength; + } + + return lResult; + } + + + #endif /* ipconfigUSE_TCP_WIN == 0 */ +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 0 ) + +/** + * @brief Fetches data to be sent. + * + * @param[in] pxWindow: The window for the connection. + * @param[in] ulWindowSize: The size of the window. + * @param[out] plPosition: plPosition will point to a location with the circular data buffer: txStream. + * + * @return return the amount of data which may be sent along with the position in the txStream. + */ + uint32_t ulTCPWindowTxGet( TCPWindow_t * pxWindow, + uint32_t ulWindowSize, + int32_t * plPosition ) + { + TCPSegment_t * pxSegment = &( pxWindow->xTxSegment ); + uint32_t ulLength = ( uint32_t ) pxSegment->lDataLength; + uint32_t ulMaxTime; + + if( ulLength != 0UL ) + { + /* _HT_ Still under investigation */ + ( void ) ulWindowSize; + + if( pxSegment->u.bits.bOutstanding != pdFALSE_UNSIGNED ) + { + /* As 'ucTransmitCount' has a minimum of 1, take 2 * RTT */ + ulMaxTime = ( ( uint32_t ) 1U << pxSegment->u.bits.ucTransmitCount ) * ( ( uint32_t ) pxWindow->lSRTT ); + + if( ulTimerGetAge( &( pxSegment->xTransmitTimer ) ) < ulMaxTime ) + { + ulLength = 0UL; + } + } + + if( ulLength != 0UL ) + { + pxSegment->u.bits.bOutstanding = pdTRUE_UNSIGNED; + pxSegment->u.bits.ucTransmitCount++; + vTCPTimerSet( &pxSegment->xTransmitTimer ); + pxWindow->ulOurSequenceNumber = pxSegment->ulSequenceNumber; + *plPosition = pxSegment->lStreamPos; + } + } + + return ulLength; + } + + + #endif /* ipconfigUSE_TCP_WIN == 0 */ +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 0 ) + +/** + * @brief Has the transmission completed. + * + * @param[in] pxWindow: The window whose transmission window is to be checked. + * + * @return If there is no outstanding data then pdTRUE is returned, + * else pdFALSE. + */ + BaseType_t xTCPWindowTxDone( const TCPWindow_t * pxWindow ) + { + BaseType_t xReturn; + + /* Has the outstanding data been sent because user wants to shutdown? */ + if( pxWindow->xTxSegment.lDataLength == 0 ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + + return xReturn; + } + + #endif /* ipconfigUSE_TCP_WIN == 0 */ +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 0 ) + + static BaseType_t prvTCPWindowTxHasSpace( TCPWindow_t const * pxWindow, + uint32_t ulWindowSize ); + +/** + * @brief Check if the window has space for one message. + * + * @param[in] pxWindow: The window to be checked. + * @param[in] ulWindowSize: Size of the window. + * + * @return pdTRUE if the window has space, pdFALSE otherwise. + */ + static BaseType_t prvTCPWindowTxHasSpace( TCPWindow_t const * pxWindow, + uint32_t ulWindowSize ) + { + BaseType_t xReturn; + + if( ulWindowSize >= pxWindow->usMSSInit ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + + return xReturn; + } + + #endif /* ipconfigUSE_TCP_WIN == 0 */ +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 0 ) + +/** + * @brief Check data to be sent and calculate the time period the process may sleep. + * + * @param[in] pxWindow: The window to be checked. + * @param[in] ulWindowSize: Size of the window. + * @param[out] pulDelay: The time period (in ticks) that the process may sleep. + * + * @return pdTRUE if the process should sleep or pdFALSE. + */ + BaseType_t xTCPWindowTxHasData( TCPWindow_t const * pxWindow, + uint32_t ulWindowSize, + TickType_t * pulDelay ) + { + TCPSegment_t const * pxSegment = &( pxWindow->xTxSegment ); + BaseType_t xReturn; + TickType_t ulAge, ulMaxAge; + + /* Check data to be sent. */ + *pulDelay = ( TickType_t ) 0; + + if( pxSegment->lDataLength == 0 ) + { + /* Got nothing to send right now. */ + xReturn = pdFALSE; + } + else + { + if( pxSegment->u.bits.bOutstanding != pdFALSE_UNSIGNED ) + { + ulAge = ulTimerGetAge( &pxSegment->xTransmitTimer ); + ulMaxAge = ( ( TickType_t ) 1U << pxSegment->u.bits.ucTransmitCount ) * ( ( uint32_t ) pxWindow->lSRTT ); + + if( ulMaxAge > ulAge ) + { + *pulDelay = ulMaxAge - ulAge; + } + + xReturn = pdTRUE; + } + else if( prvTCPWindowTxHasSpace( pxWindow, ulWindowSize ) == pdFALSE ) + { + /* Too many outstanding messages. */ + xReturn = pdFALSE; + } + else + { + xReturn = pdTRUE; + } + } + + return xReturn; + } + + + #endif /* ipconfigUSE_TCP_WIN == 0 */ +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 0 ) + +/** + * @brief Receive a normal ACK. + * + * @param[in] pxWindow: The window for this particular connection. + * @param[in] ulSequenceNumber: The sequence number of the packet. + * + * @return Number of bytes to send. + */ + uint32_t ulTCPWindowTxAck( TCPWindow_t * pxWindow, + uint32_t ulSequenceNumber ) + { + TCPSegment_t * pxSegment = &( pxWindow->xTxSegment ); + uint32_t ulDataLength = ( uint32_t ) pxSegment->lDataLength; + + /* Receive a normal ACK */ + + if( ulDataLength != 0UL ) + { + if( ulSequenceNumber < ( pxWindow->tx.ulCurrentSequenceNumber + ulDataLength ) ) + { + if( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) != pdFALSE ) + { + FreeRTOS_debug_printf( ( "win_tx_ack: acked %ld expc %ld len %ld\n", + ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, + pxWindow->tx.ulCurrentSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, + ulDataLength ) ); + } + + /* Nothing to send right now. */ + ulDataLength = 0UL; + } + else + { + pxWindow->tx.ulCurrentSequenceNumber += ulDataLength; + + if( ( xTCPWindowLoggingLevel != 0 ) && ( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) != pdFALSE ) ) + { + FreeRTOS_debug_printf( ( "win_tx_ack: acked seqnr %ld len %ld\n", + ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, + ulDataLength ) ); + } + + pxSegment->lDataLength = 0; + } + } + + return ulDataLength; + } + + + #endif /* ipconfigUSE_TCP_WIN == 0 */ +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 0 ) + +/** + * @brief This function will be called as soon as a FIN is received to check + * whether all transmit queues are empty or not. + * + * @param[in] pxWindow: The window to be checked. + * + * @return It will return true if there are no 'open' reception segments. + */ + BaseType_t xTCPWindowRxEmpty( const TCPWindow_t * pxWindow ) + { + /* Return true if 'ulCurrentSequenceNumber >= ulHighestSequenceNumber' + * 'ulCurrentSequenceNumber' is the highest sequence number stored, + * 'ulHighestSequenceNumber' is the highest sequence number seen. */ + return xSequenceGreaterThanOrEqual( pxWindow->rx.ulCurrentSequenceNumber, pxWindow->rx.ulHighestSequenceNumber ); + } + + #endif /* ipconfigUSE_TCP_WIN == 0 */ +/*-----------------------------------------------------------*/ + + #if ( ipconfigUSE_TCP_WIN == 0 ) + +/** + * @brief Destroy a window. + * + * @param[in] pxWindow: Pointer to the window to be destroyed. + * + * @return Always returns a NULL. + */ + void vTCPWindowDestroy( const TCPWindow_t * pxWindow ) + { + /* As in tiny TCP there are no shared segments descriptors, there is + * nothing to release. */ + ( void ) pxWindow; + } + + + #endif /* ipconfigUSE_TCP_WIN == 0 */ +/*-----------------------------------------------------------*/ + +#endif /* ipconfigUSE_TCP == 1 */ diff --git a/examples/stm32/freertos-tcp/FreeRTOS_UDP_IP.c b/examples/stm32/freertos-tcp/FreeRTOS_UDP_IP.c new file mode 100644 index 00000000..9f34fd31 --- /dev/null +++ b/examples/stm32/freertos-tcp/FreeRTOS_UDP_IP.c @@ -0,0 +1,448 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +/** + * @file FreeRTOS_UDP_IP.c + * @brief This file has the source code for the UDP-IP functionality of the FreeRTOS+TCP + * network stack. + */ + +/* Standard includes. */ +#include +#include + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" +#include "semphr.h" + +/* FreeRTOS+TCP includes. */ +#include "FreeRTOS_IP.h" +#include "FreeRTOS_Sockets.h" +#include "FreeRTOS_IP_Private.h" +#include "FreeRTOS_UDP_IP.h" +#include "FreeRTOS_ARP.h" +#include "FreeRTOS_DHCP.h" +#include "NetworkInterface.h" +#include "NetworkBufferManagement.h" + +#if ( ipconfigUSE_DNS == 1 ) + #include "FreeRTOS_DNS.h" +#endif + +/** @brief The expected IP version and header length coded into the IP header itself. */ +#define ipIP_VERSION_AND_HEADER_LENGTH_BYTE ( ( uint8_t ) 0x45 ) + +/** @brief Part of the Ethernet and IP headers are always constant when sending an IPv4 + * UDP packet. This array defines the constant parts, allowing this part of the + * packet to be filled in using a simple memcpy() instead of individual writes. */ +/*lint -e708 (Info -- union initialization). */ +UDPPacketHeader_t xDefaultPartUDPPacketHeader = +{ + /* .ucBytes : */ + { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Ethernet source MAC address. */ + 0x08, 0x00, /* Ethernet frame type. */ + ipIP_VERSION_AND_HEADER_LENGTH_BYTE, /* ucVersionHeaderLength. */ + 0x00, /* ucDifferentiatedServicesCode. */ + 0x00, 0x00, /* usLength. */ + 0x00, 0x00, /* usIdentification. */ + 0x00, 0x00, /* usFragmentOffset. */ + ipconfigUDP_TIME_TO_LIVE, /* ucTimeToLive */ + ipPROTOCOL_UDP, /* ucProtocol. */ + 0x00, 0x00, /* usHeaderChecksum. */ + 0x00, 0x00, 0x00, 0x00 /* Source IP address. */ + } +}; +/*-----------------------------------------------------------*/ + +/** + * @brief Process the generated UDP packet and do other checks before sending the + * packet such as ARP cache check and address resolution. + * + * @param[in] pxNetworkBuffer: The network buffer carrying the packet. + */ +void vProcessGeneratedUDPPacket( NetworkBufferDescriptor_t * const pxNetworkBuffer ) +{ + UDPPacket_t * pxUDPPacket; + IPHeader_t * pxIPHeader; + eARPLookupResult_t eReturned; + uint32_t ulIPAddress = pxNetworkBuffer->ulIPAddress; + size_t uxPayloadSize; + /* memcpy() helper variables for MISRA Rule 21.15 compliance*/ + const void * pvCopySource; + void * pvCopyDest; + + /* Map the UDP packet onto the start of the frame. */ + pxUDPPacket = ipCAST_PTR_TO_TYPE_PTR( UDPPacket_t, pxNetworkBuffer->pucEthernetBuffer ); + + #if ipconfigSUPPORT_OUTGOING_PINGS == 1 + if( pxNetworkBuffer->usPort == ( uint16_t ) ipPACKET_CONTAINS_ICMP_DATA ) + { + uxPayloadSize = pxNetworkBuffer->xDataLength - sizeof( ICMPPacket_t ); + } + else + #endif + { + uxPayloadSize = pxNetworkBuffer->xDataLength - sizeof( UDPPacket_t ); + } + + /* Determine the ARP cache status for the requested IP address. */ + eReturned = eARPGetCacheEntry( &( ulIPAddress ), &( pxUDPPacket->xEthernetHeader.xDestinationAddress ) ); + + if( eReturned != eCantSendPacket ) + { + if( eReturned == eARPCacheHit ) + { + #if ( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 ) + uint8_t ucSocketOptions; + #endif + iptraceSENDING_UDP_PACKET( pxNetworkBuffer->ulIPAddress ); + + /* Create short cuts to the data within the packet. */ + pxIPHeader = &( pxUDPPacket->xIPHeader ); + + #if ( ipconfigSUPPORT_OUTGOING_PINGS == 1 ) + + /* Is it possible that the packet is not actually a UDP packet + * after all, but an ICMP packet. */ + if( pxNetworkBuffer->usPort != ( uint16_t ) ipPACKET_CONTAINS_ICMP_DATA ) + #endif /* ipconfigSUPPORT_OUTGOING_PINGS */ + { + UDPHeader_t * pxUDPHeader; + + pxUDPHeader = &( pxUDPPacket->xUDPHeader ); + + pxUDPHeader->usDestinationPort = pxNetworkBuffer->usPort; + pxUDPHeader->usSourcePort = pxNetworkBuffer->usBoundPort; + pxUDPHeader->usLength = ( uint16_t ) ( uxPayloadSize + sizeof( UDPHeader_t ) ); + pxUDPHeader->usLength = FreeRTOS_htons( pxUDPHeader->usLength ); + pxUDPHeader->usChecksum = 0U; + } + + /* memcpy() the constant parts of the header information into + * the correct location within the packet. This fills in: + * xEthernetHeader.xSourceAddress + * xEthernetHeader.usFrameType + * xIPHeader.ucVersionHeaderLength + * xIPHeader.ucDifferentiatedServicesCode + * xIPHeader.usLength + * xIPHeader.usIdentification + * xIPHeader.usFragmentOffset + * xIPHeader.ucTimeToLive + * xIPHeader.ucProtocol + * and + * xIPHeader.usHeaderChecksum + */ + + /* Save options now, as they will be overwritten by memcpy */ + #if ( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 ) + { + ucSocketOptions = pxNetworkBuffer->pucEthernetBuffer[ ipSOCKET_OPTIONS_OFFSET ]; + } + #endif + + /* + * Offset the memcpy by the size of a MAC address to start at the packet's + * Ethernet header 'source' MAC address; the preceding 'destination' should not be altered. + */ + + /* + * Use helper variables for memcpy() to remain + * compliant with MISRA Rule 21.15. These should be + * optimized away. + */ + pvCopySource = xDefaultPartUDPPacketHeader.ucBytes; + /* The Ethernet source address is at offset 6. */ + pvCopyDest = &pxNetworkBuffer->pucEthernetBuffer[ sizeof( MACAddress_t ) ]; + ( void ) memcpy( pvCopyDest, pvCopySource, sizeof( xDefaultPartUDPPacketHeader ) ); + + #if ipconfigSUPPORT_OUTGOING_PINGS == 1 + if( pxNetworkBuffer->usPort == ( uint16_t ) ipPACKET_CONTAINS_ICMP_DATA ) + { + pxIPHeader->ucProtocol = ipPROTOCOL_ICMP; + pxIPHeader->usLength = ( uint16_t ) ( uxPayloadSize + sizeof( IPHeader_t ) + sizeof( ICMPHeader_t ) ); + } + else + #endif /* ipconfigSUPPORT_OUTGOING_PINGS */ + { + pxIPHeader->usLength = ( uint16_t ) ( uxPayloadSize + sizeof( IPHeader_t ) + sizeof( UDPHeader_t ) ); + } + + pxIPHeader->usLength = FreeRTOS_htons( pxIPHeader->usLength ); + pxIPHeader->ulDestinationIPAddress = pxNetworkBuffer->ulIPAddress; + + #if ( ipconfigUSE_LLMNR == 1 ) + { + /* LLMNR messages are typically used on a LAN and they're + * not supposed to cross routers */ + if( pxNetworkBuffer->ulIPAddress == ipLLMNR_IP_ADDR ) + { + pxIPHeader->ucTimeToLive = 0x01; + } + } + #endif + + #if ( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 ) + { + pxIPHeader->usHeaderChecksum = 0U; + pxIPHeader->usHeaderChecksum = usGenerateChecksum( 0U, ( uint8_t * ) &( pxIPHeader->ucVersionHeaderLength ), ipSIZE_OF_IPv4_HEADER ); + pxIPHeader->usHeaderChecksum = ~FreeRTOS_htons( pxIPHeader->usHeaderChecksum ); + + if( ( ucSocketOptions & ( uint8_t ) FREERTOS_SO_UDPCKSUM_OUT ) != 0U ) + { + ( void ) usGenerateProtocolChecksum( ( uint8_t * ) pxUDPPacket, pxNetworkBuffer->xDataLength, pdTRUE ); + } + else + { + pxUDPPacket->xUDPHeader.usChecksum = 0U; + } + } + #endif /* if ( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 ) */ + } + else if( eReturned == eARPCacheMiss ) + { + /* Add an entry to the ARP table with a null hardware address. + * This allows the ARP timer to know that an ARP reply is + * outstanding, and perform retransmissions if necessary. */ + vARPRefreshCacheEntry( NULL, ulIPAddress ); + + /* Generate an ARP for the required IP address. */ + iptracePACKET_DROPPED_TO_GENERATE_ARP( pxNetworkBuffer->ulIPAddress ); + pxNetworkBuffer->ulIPAddress = ulIPAddress; + vARPGenerateRequestPacket( pxNetworkBuffer ); + } + else + { + /* The lookup indicated that an ARP request has already been + * sent out for the queried IP address. */ + eReturned = eCantSendPacket; + } + } + + if( eReturned != eCantSendPacket ) + { + /* The network driver is responsible for freeing the network buffer + * after the packet has been sent. */ + + #if defined( ipconfigETHERNET_MINIMUM_PACKET_BYTES ) + { + if( pxNetworkBuffer->xDataLength < ( size_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES ) + { + BaseType_t xIndex; + + for( xIndex = ( BaseType_t ) pxNetworkBuffer->xDataLength; xIndex < ( BaseType_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES; xIndex++ ) + { + pxNetworkBuffer->pucEthernetBuffer[ xIndex ] = 0U; + } + + pxNetworkBuffer->xDataLength = ( size_t ) ipconfigETHERNET_MINIMUM_PACKET_BYTES; + } + } + #endif /* if defined( ipconfigETHERNET_MINIMUM_PACKET_BYTES ) */ + iptraceNETWORK_INTERFACE_OUTPUT( pxNetworkBuffer->xDataLength, pxNetworkBuffer->pucEthernetBuffer ); + ( void ) xNetworkInterfaceOutput( pxNetworkBuffer, pdTRUE ); + } + else + { + /* The packet can't be sent (DHCP not completed?). Just drop the + * packet. */ + vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer ); + } +} +/*-----------------------------------------------------------*/ + +/** + * @brief Process the received UDP packet. + * + * @param[in] pxNetworkBuffer: The network buffer carrying the UDP packet. + * @param[in] usPort: The port number on which this packet was received. + * + * @return pdPASS in case the UDP packet could be processed. Else pdFAIL is returned. + */ +BaseType_t xProcessReceivedUDPPacket( NetworkBufferDescriptor_t * pxNetworkBuffer, + uint16_t usPort ) +{ + BaseType_t xReturn = pdPASS; + FreeRTOS_Socket_t * pxSocket; + + configASSERT( pxNetworkBuffer != NULL ); + configASSERT( pxNetworkBuffer->pucEthernetBuffer != NULL ); + + /* Map the ethernet buffer to the UDPPacket_t struct for easy access to the fields. */ + const UDPPacket_t * pxUDPPacket = ipCAST_CONST_PTR_TO_CONST_TYPE_PTR( UDPPacket_t, pxNetworkBuffer->pucEthernetBuffer ); + + /* Caller must check for minimum packet size. */ + pxSocket = pxUDPSocketLookup( usPort ); + + if( pxSocket != NULL ) + { + /* When refreshing the ARP cache with received UDP packets we must be + * careful; hundreds of broadcast messages may pass and if we're not + * handling them, no use to fill the ARP cache with those IP addresses. */ + vARPRefreshCacheEntry( &( pxUDPPacket->xEthernetHeader.xSourceAddress ), pxUDPPacket->xIPHeader.ulSourceIPAddress ); + + #if ( ipconfigUSE_CALLBACKS == 1 ) + { + /* Did the owner of this socket register a reception handler ? */ + if( ipconfigIS_VALID_PROG_ADDRESS( pxSocket->u.xUDP.pxHandleReceive ) ) + { + struct freertos_sockaddr xSourceAddress, destinationAddress; + void * pcData = &( pxNetworkBuffer->pucEthernetBuffer[ ipUDP_PAYLOAD_OFFSET_IPv4 ] ); + FOnUDPReceive_t xHandler = ( FOnUDPReceive_t ) pxSocket->u.xUDP.pxHandleReceive; + xSourceAddress.sin_port = pxNetworkBuffer->usPort; + xSourceAddress.sin_addr = pxNetworkBuffer->ulIPAddress; + destinationAddress.sin_port = usPort; + destinationAddress.sin_addr = pxUDPPacket->xIPHeader.ulDestinationIPAddress; + + /* The value of 'xDataLength' was proven to be at least the size of a UDP packet in prvProcessIPPacket(). */ + if( xHandler( ( Socket_t ) pxSocket, + ( void * ) pcData, + ( size_t ) ( pxNetworkBuffer->xDataLength - ipUDP_PAYLOAD_OFFSET_IPv4 ), + &( xSourceAddress ), + &( destinationAddress ) ) != 0 ) + { + xReturn = pdFAIL; /* xHandler has consumed the data, do not add it to .xWaitingPacketsList'. */ + } + } + } + #endif /* ipconfigUSE_CALLBACKS */ + + #if ( ipconfigUDP_MAX_RX_PACKETS > 0U ) + { + if( xReturn == pdPASS ) + { + if( listCURRENT_LIST_LENGTH( &( pxSocket->u.xUDP.xWaitingPacketsList ) ) >= pxSocket->u.xUDP.uxMaxPackets ) + { + FreeRTOS_debug_printf( ( "xProcessReceivedUDPPacket: buffer full %ld >= %ld port %u\n", + listCURRENT_LIST_LENGTH( &( pxSocket->u.xUDP.xWaitingPacketsList ) ), + pxSocket->u.xUDP.uxMaxPackets, pxSocket->usLocalPort ) ); + xReturn = pdFAIL; /* we did not consume or release the buffer */ + } + } + } + #endif /* if ( ipconfigUDP_MAX_RX_PACKETS > 0U ) */ + + #if ( ipconfigUSE_CALLBACKS == 1 ) || ( ipconfigUDP_MAX_RX_PACKETS > 0U ) + if( xReturn == pdPASS ) /*lint !e774: Boolean within 'if' always evaluates to True, depending on configuration. [MISRA 2012 Rule 14.3, required. */ + #else + /* xReturn is still pdPASS. */ + #endif + { + vTaskSuspendAll(); + { + taskENTER_CRITICAL(); + { + /* Add the network packet to the list of packets to be + * processed by the socket. */ + vListInsertEnd( &( pxSocket->u.xUDP.xWaitingPacketsList ), &( pxNetworkBuffer->xBufferListItem ) ); + } + taskEXIT_CRITICAL(); + } + ( void ) xTaskResumeAll(); + + /* Set the socket's receive event */ + if( pxSocket->xEventGroup != NULL ) + { + ( void ) xEventGroupSetBits( pxSocket->xEventGroup, ( EventBits_t ) eSOCKET_RECEIVE ); + } + + #if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 ) + { + if( ( pxSocket->pxSocketSet != NULL ) && ( ( pxSocket->xSelectBits & ( ( EventBits_t ) eSELECT_READ ) ) != 0U ) ) + { + ( void ) xEventGroupSetBits( pxSocket->pxSocketSet->xSelectGroup, ( EventBits_t ) eSELECT_READ ); + } + } + #endif + + #if ( ipconfigSOCKET_HAS_USER_SEMAPHORE == 1 ) + { + if( pxSocket->pxUserSemaphore != NULL ) + { + ( void ) xSemaphoreGive( pxSocket->pxUserSemaphore ); + } + } + #endif + + #if ( ipconfigUSE_DHCP == 1 ) + { + if( xIsDHCPSocket( pxSocket ) != 0 ) + { + ( void ) xSendDHCPEvent(); + } + } + #endif + } + } + else + { + /* There is no socket listening to the target port, but still it might + * be for this node. */ + + #if ( ipconfigUSE_DNS == 1 ) && ( ipconfigDNS_USE_CALLBACKS == 1 ) + + /* A DNS reply, check for the source port. Although the DNS client + * does open a UDP socket to send a messages, this socket will be + * closed after a short timeout. Messages that come late (after the + * socket is closed) will be treated here. */ + if( FreeRTOS_ntohs( pxUDPPacket->xUDPHeader.usSourcePort ) == ( uint16_t ) ipDNS_PORT ) + { + vARPRefreshCacheEntry( &( pxUDPPacket->xEthernetHeader.xSourceAddress ), pxUDPPacket->xIPHeader.ulSourceIPAddress ); + xReturn = ( BaseType_t ) ulDNSHandlePacket( pxNetworkBuffer ); + } + else + #endif + + #if ( ipconfigUSE_LLMNR == 1 ) + /* A LLMNR request, check for the destination port. */ + if( ( usPort == FreeRTOS_ntohs( ipLLMNR_PORT ) ) || + ( pxUDPPacket->xUDPHeader.usSourcePort == FreeRTOS_ntohs( ipLLMNR_PORT ) ) ) + { + vARPRefreshCacheEntry( &( pxUDPPacket->xEthernetHeader.xSourceAddress ), pxUDPPacket->xIPHeader.ulSourceIPAddress ); + xReturn = ( BaseType_t ) ulDNSHandlePacket( pxNetworkBuffer ); + } + else + #endif /* ipconfigUSE_LLMNR */ + + #if ( ipconfigUSE_NBNS == 1 ) + /* a NetBIOS request, check for the destination port */ + if( ( usPort == FreeRTOS_ntohs( ipNBNS_PORT ) ) || + ( pxUDPPacket->xUDPHeader.usSourcePort == FreeRTOS_ntohs( ipNBNS_PORT ) ) ) + { + vARPRefreshCacheEntry( &( pxUDPPacket->xEthernetHeader.xSourceAddress ), pxUDPPacket->xIPHeader.ulSourceIPAddress ); + xReturn = ( BaseType_t ) ulNBNSHandlePacket( pxNetworkBuffer ); + } + else + #endif /* ipconfigUSE_NBNS */ + { + xReturn = pdFAIL; + } + } + + return xReturn; +} +/*-----------------------------------------------------------*/ diff --git a/examples/stm32/freertos-tcp/include/FreeRTOSIPConfigDefaults.h b/examples/stm32/freertos-tcp/include/FreeRTOSIPConfigDefaults.h new file mode 100644 index 00000000..bbbab54d --- /dev/null +++ b/examples/stm32/freertos-tcp/include/FreeRTOSIPConfigDefaults.h @@ -0,0 +1,624 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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 FREERTOS_DEFAULT_IP_CONFIG_H +#define FREERTOS_DEFAULT_IP_CONFIG_H + +/* The error numbers defined in this file will be moved to the core FreeRTOS + * code in future versions of FreeRTOS - at which time the following header file + * will be removed. */ +#include "FreeRTOS_errno_TCP.h" + +/* This file provides default values for configuration options that are missing + * from the FreeRTOSIPConfig.h configuration header file. */ + +/* These macros are used to define away static keyword for CBMC proofs */ +#ifndef _static + #define _static static +#endif + +/* Ensure defined configuration constants are using the most up to date naming. */ +#ifdef tcpconfigIP_TIME_TO_LIVE + #error now called: ipconfigTCP_TIME_TO_LIVE +#endif + +#ifdef updconfigIP_TIME_TO_LIVE + #error now called: ipconfigUDP_TIME_TO_LIVE +#endif + +#ifdef ipFILLER_SIZE + #error now called: ipconfigPACKET_FILLER_SIZE +#endif + +#ifdef dnsMAX_REQUEST_ATTEMPTS + #error now called: ipconfigDNS_REQUEST_ATTEMPTS +#endif + +#ifdef ipconfigUDP_TASK_PRIORITY + #error now called: ipconfigIP_TASK_PRIORITY +#endif + +#ifdef ipconfigUDP_TASK_STACK_SIZE_WORDS + #error now called: ipconfigIP_TASK_STACK_SIZE_WORDS +#endif + +#ifdef ipconfigDRIVER_INCLUDED_RX_IP_FILTERING + #error now called: ipconfigETHERNET_DRIVER_FILTERS_PACKETS +#endif + +#ifdef ipconfigMAX_SEND_BLOCK_TIME_TICKS + #error now called: ipconfigUDP_MAX_SEND_BLOCK_TIME_TICKS +#endif + +#ifdef ipconfigUSE_RECEIVE_CONNECT_CALLBACKS + #error now called: ipconfigUSE_CALLBACKS +#endif + +#ifdef ipconfigNUM_NETWORK_BUFFERS + #error now called: ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS +#endif + +#ifdef ipconfigTCP_HANG_PROT + #error now called: ipconfigTCP_HANG_PROTECTION +#endif + +#ifdef ipconfigTCP_HANG_PROT_TIME + #error now called: ipconfigTCP_HANG_PROTECTION_TIME +#endif + +#ifdef FreeRTOS_lprintf + #error now called: FreeRTOS_debug_printf +#endif + +#if ( ipconfigEVENT_QUEUE_LENGTH < ( ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS + 5 ) ) + #error The ipconfigEVENT_QUEUE_LENGTH parameter must be at least ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS + 5 +#endif + +#if ( ipconfigNETWORK_MTU < 46 ) + #error ipconfigNETWORK_MTU must be at least 46. +#endif + +#ifdef ipconfigBUFFER_ALLOC_FIXED_SIZE + #error ipconfigBUFFER_ALLOC_FIXED_SIZE was dropped and replaced by a const value, declared in BufferAllocation[12].c +#endif + +#ifdef ipconfigNIC_SEND_PASSES_DMA + #error now called: ipconfigZERO_COPY_TX_DRIVER +#endif + +#ifdef HAS_TX_CRC_OFFLOADING + +/* _HT_ As these macro names have changed, throw an error + * if they're still defined. */ + #error now called: ipconfigHAS_TX_CRC_OFFLOADING +#endif + +#ifdef HAS_RX_CRC_OFFLOADING + #error now called: ipconfigHAS_RX_CRC_OFFLOADING +#endif + +#ifdef ipconfigTCP_RX_BUF_LEN + #error ipconfigTCP_RX_BUF_LEN is now called ipconfigTCP_RX_BUFFER_LENGTH +#endif + +#ifdef ipconfigTCP_TX_BUF_LEN + #error ipconfigTCP_TX_BUF_LEN is now called ipconfigTCP_TX_BUFFER_LENGTH +#endif + +#ifdef ipconfigDHCP_USES_USER_HOOK + #error ipconfigDHCP_USES_USER_HOOK and its associated callback have been superseded - see http: /*www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/TCP_IP_Configuration.html#ipconfigUSE_DHCP_HOOK */ +#endif + +#ifndef ipconfigUSE_TCP + #define ipconfigUSE_TCP ( 1 ) +#endif + +#if ipconfigUSE_TCP + +/* Include support for TCP scaling windows */ + #ifndef ipconfigUSE_TCP_WIN + #define ipconfigUSE_TCP_WIN ( 1 ) + #endif + + #ifndef ipconfigTCP_WIN_SEG_COUNT + #define ipconfigTCP_WIN_SEG_COUNT ( 256 ) + #endif + + #ifndef ipconfigIGNORE_UNKNOWN_PACKETS + +/* When non-zero, TCP will not send RST packets in reply to + * TCP packets which are unknown, or out-of-order. */ + #define ipconfigIGNORE_UNKNOWN_PACKETS ( 0 ) + #endif +#endif /* if ipconfigUSE_TCP */ + +/* + * For debugging/logging: check if the port number is used for telnet + * Some events will not be logged for telnet connections + * because it would produce logging about the transmission of the logging... + * This macro will only be used if FreeRTOS_debug_printf() is defined for logging + */ +#ifndef ipconfigTCP_MAY_LOG_PORT + #define ipconfigTCP_MAY_LOG_PORT( xPort ) ( ( xPort ) != 23U ) +#endif + + +#ifndef ipconfigSOCK_DEFAULT_RECEIVE_BLOCK_TIME + #define ipconfigSOCK_DEFAULT_RECEIVE_BLOCK_TIME portMAX_DELAY +#endif + +#ifndef ipconfigSOCK_DEFAULT_SEND_BLOCK_TIME + #define ipconfigSOCK_DEFAULT_SEND_BLOCK_TIME portMAX_DELAY +#endif + + +#ifndef ipconfigDNS_RECEIVE_BLOCK_TIME_TICKS + #define ipconfigDNS_RECEIVE_BLOCK_TIME_TICKS pdMS_TO_TICKS( 5000U ) +#endif + +#ifndef ipconfigDNS_SEND_BLOCK_TIME_TICKS + #define ipconfigDNS_SEND_BLOCK_TIME_TICKS pdMS_TO_TICKS( 500U ) +#endif + +/* + * FreeRTOS debug logging routine (proposal) + * The macro will be called in the printf() style. Users can define + * their own logging routine as: + * + * #define FreeRTOS_debug_printf( MSG ) my_printf MSG + * + * The FreeRTOS_debug_printf() must be thread-safe but does not have to be + * interrupt-safe. + */ +#ifdef ipconfigHAS_DEBUG_PRINTF + #if ( ipconfigHAS_DEBUG_PRINTF == 0 ) + #ifdef FreeRTOS_debug_printf + #error Do not define FreeRTOS_debug_print if ipconfigHAS_DEBUG_PRINTF is set to 0 + #endif /* ifdef FreeRTOS_debug_printf */ + #endif /* ( ipconfigHAS_DEBUG_PRINTF == 0 ) */ +#endif /* ifdef ipconfigHAS_DEBUG_PRINTF */ + +#ifndef FreeRTOS_debug_printf + #define FreeRTOS_debug_printf( MSG ) do {} while( ipFALSE_BOOL ) + #define ipconfigHAS_DEBUG_PRINTF 0 +#endif + +/* + * FreeRTOS general logging routine (proposal) + * Used in some utility functions such as FreeRTOS_netstat() and FreeRTOS_PrintARPCache() + * + * #define FreeRTOS_printf( MSG ) my_printf MSG + * + * The FreeRTOS_printf() must be thread-safe but does not have to be interrupt-safe + */ +#ifdef ipconfigHAS_PRINTF + #if ( ipconfigHAS_PRINTF == 0 ) + #ifdef FreeRTOS_printf + #error Do not define FreeRTOS_print if ipconfigHAS_PRINTF is set to 0 + #endif /* ifdef FreeRTOS_debug_printf */ + #endif /* ( ipconfigHAS_PRINTF == 0 ) */ +#endif /* ifdef ipconfigHAS_PRINTF */ + +#ifndef FreeRTOS_printf + #define FreeRTOS_printf( MSG ) do {} while( ipFALSE_BOOL ) + #define ipconfigHAS_PRINTF 0 +#endif + +/* + * In cases where a lot of logging is produced, FreeRTOS_flush_logging( ) + * will be called to give the logging module a chance to flush the data + * An example of this is the netstat command, which produces many lines of logging + */ +#ifndef FreeRTOS_flush_logging + #define FreeRTOS_flush_logging() do {} while( ipFALSE_BOOL ) +#endif + +/* Malloc functions. Within most applications of FreeRTOS, the couple + * pvPortMalloc()/vPortFree() will be used. + * If there is also SDRAM, the user may decide to use a different memory + * allocator: + * MallocLarge is used to allocate large TCP buffers (for Rx/Tx) + * MallocSocket is used to allocate the space for the sockets + */ +#ifndef pvPortMallocLarge + #define pvPortMallocLarge( x ) pvPortMalloc( x ) +#endif + +#ifndef vPortFreeLarge + #define vPortFreeLarge( ptr ) vPortFree( ptr ) +#endif + +#ifndef pvPortMallocSocket + #define pvPortMallocSocket( x ) pvPortMalloc( x ) +#endif + +#ifndef vPortFreeSocket + #define vPortFreeSocket( ptr ) vPortFree( ptr ) +#endif + +/* + * At several places within the library, random numbers are needed: + * - DHCP: For creating a DHCP transaction number + * - TCP: Set the Initial Sequence Number: this is the value of the first outgoing + * sequence number being used when connecting to a peer. + * Having a well randomized ISN is important to avoid spoofing + * - UDP/TCP: for setting the first port number to be used, in case a socket + * uses a 'random' or anonymous port number + */ +#ifndef ipconfigRAND32 + #define ipconfigRAND32() rand() +#endif + +/* -------------------------------------------------------- + * End of: HT Added some macro defaults for the PLUS-UDP project + * -------------------------------------------------------- */ + +#ifndef ipconfigUSE_NETWORK_EVENT_HOOK + #define ipconfigUSE_NETWORK_EVENT_HOOK 0 +#endif + +#ifndef ipconfigUDP_MAX_SEND_BLOCK_TIME_TICKS + #define ipconfigUDP_MAX_SEND_BLOCK_TIME_TICKS ( pdMS_TO_TICKS( 20U ) ) +#endif + +#ifndef ipconfigARP_CACHE_ENTRIES + #define ipconfigARP_CACHE_ENTRIES 10 +#endif + +#ifndef ipconfigMAX_ARP_RETRANSMISSIONS + #define ipconfigMAX_ARP_RETRANSMISSIONS ( 5U ) +#endif + +#ifndef ipconfigMAX_ARP_AGE + #define ipconfigMAX_ARP_AGE 150U +#endif + +#ifndef ipconfigUSE_ARP_REVERSED_LOOKUP + #define ipconfigUSE_ARP_REVERSED_LOOKUP 0 +#endif + +#ifndef ipconfigUSE_ARP_REMOVE_ENTRY + #define ipconfigUSE_ARP_REMOVE_ENTRY 0 +#endif + +#ifndef ipconfigINCLUDE_FULL_INET_ADDR + #define ipconfigINCLUDE_FULL_INET_ADDR 1 +#endif + +#ifndef ipconfigUSE_LINKED_RX_MESSAGES + #define ipconfigUSE_LINKED_RX_MESSAGES 0 +#endif + +#ifndef ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS + #define ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS 45 +#endif + +#ifndef ipconfigEVENT_QUEUE_LENGTH + #define ipconfigEVENT_QUEUE_LENGTH ( ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS + 5 ) +#endif + +#ifndef ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND + #define ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND 1 +#endif + +/* Configuration to control whether packets with IP options, + * received over the network, should be passed up to the + * software stack OR should be dropped. + * If set to 1, the stack accepts IP packets that contain IP options, but does + * not process the options (IP options are not supported). + * If set to 0, the stack will drop IP packets that contain IP options. + */ +#ifndef ipconfigIP_PASS_PACKETS_WITH_IP_OPTIONS + #define ipconfigIP_PASS_PACKETS_WITH_IP_OPTIONS 1 +#endif + +/* Configuration to control whether UDP packets with + * checksum value of zero should be passed up the software + * stack OR should be dropped. + * If set to 1, the stack will accept UDP packets that have their checksum + * value set to 0. + * If set to 0, the stack will drop UDP packets that have their checksum value + * set to 0. + */ +#ifndef ipconfigUDP_PASS_ZERO_CHECKSUM_PACKETS + #define ipconfigUDP_PASS_ZERO_CHECKSUM_PACKETS 0 +#endif + +#ifndef ipconfigUDP_TIME_TO_LIVE + #define ipconfigUDP_TIME_TO_LIVE 128 +#endif + +#ifndef ipconfigTCP_TIME_TO_LIVE + #define ipconfigTCP_TIME_TO_LIVE 128 +#endif + +#ifndef ipconfigUDP_MAX_RX_PACKETS + +/* Make positive to define the maximum number of packets which will be buffered + * for each UDP socket. + * Can be overridden with the socket option FREERTOS_SO_UDP_MAX_RX_PACKETS + */ + #define ipconfigUDP_MAX_RX_PACKETS 0U +#endif + +#ifndef ipconfigUSE_DHCP + #define ipconfigUSE_DHCP 1 +#endif + +#ifndef ipconfigUSE_DHCP_HOOK + #define ipconfigUSE_DHCP_HOOK 0 +#endif + +#ifndef ipconfigDHCP_FALL_BACK_AUTO_IP + +/* + * Only applicable when DHCP is in use: + * If no DHCP server responds, use "Auto-IP" : the + * device will allocate a random LinkLayer IP address. + */ + #define ipconfigDHCP_FALL_BACK_AUTO_IP ( 0 ) +#endif + +#if ( ipconfigDHCP_FALL_BACK_AUTO_IP != 0 ) + #define ipconfigARP_USE_CLASH_DETECTION 1 +#endif + +#ifndef ipconfigARP_USE_CLASH_DETECTION + #define ipconfigARP_USE_CLASH_DETECTION 0 +#endif + +#ifndef ipconfigNETWORK_MTU + #define ipconfigNETWORK_MTU 1500 +#endif + +#ifndef ipconfigTCP_MSS + #define ipconfigTCP_MSS ( ipconfigNETWORK_MTU - ( ipSIZE_OF_IPv4_HEADER + ipSIZE_OF_TCP_HEADER ) ) +#endif + +/* Each TCP socket has circular stream buffers for Rx and Tx, which + * have a fixed maximum size. + * The defaults for these size are defined here, although + * they can be overridden at runtime by using the setsockopt() call */ +#ifndef ipconfigTCP_RX_BUFFER_LENGTH + #define ipconfigTCP_RX_BUFFER_LENGTH ( 4U * ipconfigTCP_MSS ) /* defaults to 5840 bytes */ +#endif + +/* Define the size of Tx stream buffer for TCP sockets */ +#ifndef ipconfigTCP_TX_BUFFER_LENGTH + #define ipconfigTCP_TX_BUFFER_LENGTH ( 4U * ipconfigTCP_MSS ) /* defaults to 5840 bytes */ +#endif + +#ifndef ipconfigMAXIMUM_DISCOVER_TX_PERIOD + #ifdef _WINDOWS_ + #define ipconfigMAXIMUM_DISCOVER_TX_PERIOD ( pdMS_TO_TICKS( 999U ) ) + #else + #define ipconfigMAXIMUM_DISCOVER_TX_PERIOD ( pdMS_TO_TICKS( 30000U ) ) + #endif /* _WINDOWS_ */ +#endif /* ipconfigMAXIMUM_DISCOVER_TX_PERIOD */ + +#if ( ipconfigUSE_DNS == 0 ) + /* The DNS module will not be included. */ + #if ( ( ipconfigUSE_LLMNR != 0 ) || ( ipconfigUSE_NBNS != 0 ) ) + /* LLMNR and NBNS depend on DNS because those protocols share a lot of code. */ + #error When either LLMNR or NBNS is used, ipconfigUSE_DNS must be defined + #endif +#endif + +#ifndef ipconfigUSE_DNS + #define ipconfigUSE_DNS 1 +#endif + +#ifndef ipconfigDNS_REQUEST_ATTEMPTS + #define ipconfigDNS_REQUEST_ATTEMPTS 5 +#endif + +#ifndef ipconfigUSE_DNS_CACHE + #define ipconfigUSE_DNS_CACHE 0 +#endif + +#if ( ipconfigUSE_DNS_CACHE != 0 ) + #ifndef ipconfigDNS_CACHE_NAME_LENGTH + +/* Per https://tools.ietf.org/html/rfc1035, 253 is the maximum string length + * of a DNS name. The following default accounts for a null terminator. */ + #define ipconfigDNS_CACHE_NAME_LENGTH 254U + #endif + + #ifndef ipconfigDNS_CACHE_ENTRIES + #define ipconfigDNS_CACHE_ENTRIES 1 + #endif + +#endif /* ipconfigUSE_DNS_CACHE != 0 */ + +/* When accessing services which have multiple IP addresses, setting this + * greater than 1 can improve reliability by returning different IP address + * answers on successive calls to FreeRTOS_gethostbyname(). */ +#ifndef ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY + #define ipconfigDNS_CACHE_ADDRESSES_PER_ENTRY 1 +#endif + +#ifndef ipconfigCHECK_IP_QUEUE_SPACE + #define ipconfigCHECK_IP_QUEUE_SPACE 0 +#endif + +#ifndef ipconfigUSE_LLMNR + /* Include support for LLMNR: Link-local Multicast Name Resolution (non-Microsoft) */ + #define ipconfigUSE_LLMNR ( 0 ) +#endif + +#ifndef ipconfigREPLY_TO_INCOMING_PINGS + #define ipconfigREPLY_TO_INCOMING_PINGS 1 +#endif + +#ifndef ipconfigSUPPORT_OUTGOING_PINGS + #define ipconfigSUPPORT_OUTGOING_PINGS 0 +#endif + +#ifndef ipconfigFILTER_OUT_NON_ETHERNET_II_FRAMES + #define ipconfigFILTER_OUT_NON_ETHERNET_II_FRAMES 1 +#endif + +#ifndef ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES + #define ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES 1 +#endif + +#ifndef configINCLUDE_TRACE_RELATED_CLI_COMMANDS + #define ipconfigINCLUDE_EXAMPLE_FREERTOS_PLUS_TRACE_CALLS 0 +#else + #define ipconfigINCLUDE_EXAMPLE_FREERTOS_PLUS_TRACE_CALLS configINCLUDE_TRACE_RELATED_CLI_COMMANDS +#endif + +#ifndef ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM + #define ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM ( 0 ) +#endif + +#ifndef ipconfigETHERNET_DRIVER_FILTERS_PACKETS + #define ipconfigETHERNET_DRIVER_FILTERS_PACKETS ( 0 ) +#endif + +#ifndef ipconfigWATCHDOG_TIMER + +/* This macro will be called in every loop the IP-task makes. It may be + * replaced by user-code that triggers a watchdog */ + #define ipconfigWATCHDOG_TIMER() +#endif + +#ifndef ipconfigUSE_CALLBACKS + #define ipconfigUSE_CALLBACKS ( 0 ) +#endif + +#if ( ipconfigUSE_CALLBACKS != 0 ) + #ifndef ipconfigIS_VALID_PROG_ADDRESS + +/* Replace this macro with a test returning non-zero if the memory pointer to by x + * is valid memory which can contain executable code + * In fact this is an extra safety measure: if a handler points to invalid memory, + * it will not be called + */ + #define ipconfigIS_VALID_PROG_ADDRESS( x ) ( ( x ) != NULL ) + #endif +#endif + +#ifndef ipconfigHAS_INLINE_FUNCTIONS + #define ipconfigHAS_INLINE_FUNCTIONS ( 1 ) +#endif + +#ifndef portINLINE + #define portINLINE inline +#endif + +#ifndef ipconfigZERO_COPY_TX_DRIVER + +/* When non-zero, the buffers passed to the SEND routine may be passed + * to DMA. As soon as sending is ready, the buffers must be released by + * calling vReleaseNetworkBufferAndDescriptor(), */ + #define ipconfigZERO_COPY_TX_DRIVER ( 0 ) +#endif + +#ifndef ipconfigZERO_COPY_RX_DRIVER + +/* This define doesn't mean much to the driver, except that it makes + * sure that pxPacketBuffer_to_NetworkBuffer() will be included. */ + #define ipconfigZERO_COPY_RX_DRIVER ( 0 ) +#endif + +#ifndef ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM + #define ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM 0 +#endif + +#ifndef ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM + #define ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM 0 +#endif + +#ifndef ipconfigDHCP_REGISTER_HOSTNAME + #define ipconfigDHCP_REGISTER_HOSTNAME 0 +#endif + +#ifndef ipconfigSOCKET_HAS_USER_SEMAPHORE + #define ipconfigSOCKET_HAS_USER_SEMAPHORE 0 +#endif + +#ifndef ipconfigSOCKET_HAS_USER_WAKE_CALLBACK + #define ipconfigSOCKET_HAS_USER_WAKE_CALLBACK 0 +#endif + +#ifndef ipconfigSUPPORT_SELECT_FUNCTION + #define ipconfigSUPPORT_SELECT_FUNCTION 0 +#endif + +#ifndef ipconfigTCP_KEEP_ALIVE + #define ipconfigTCP_KEEP_ALIVE 0 +#endif + +#ifndef ipconfigDNS_USE_CALLBACKS + #define ipconfigDNS_USE_CALLBACKS 0 +#endif + +#ifndef ipconfigSUPPORT_SIGNALS + #define ipconfigSUPPORT_SIGNALS 0 +#endif + +#ifndef ipconfigUSE_NBNS + #define ipconfigUSE_NBNS 0 +#endif + +/* As an attack surface reduction for ports that listen for inbound + * connections, hang protection can help reduce the impact of SYN floods. */ +#ifndef ipconfigTCP_HANG_PROTECTION + #define ipconfigTCP_HANG_PROTECTION 1 +#endif + +/* Non-activity timeout is expressed in seconds. */ +#ifndef ipconfigTCP_HANG_PROTECTION_TIME + #define ipconfigTCP_HANG_PROTECTION_TIME 30U +#endif + +#ifndef ipconfigTCP_IP_SANITY + #define ipconfigTCP_IP_SANITY 0 +#endif + +#ifndef ipconfigARP_STORES_REMOTE_ADDRESSES + #define ipconfigARP_STORES_REMOTE_ADDRESSES 0 +#endif + +#ifndef ipconfigBUFFER_PADDING + +/* Expert option: define a value for 'ipBUFFER_PADDING'. + * When 'ipconfigBUFFER_PADDING' equals 0, + * 'ipBUFFER_PADDING' will get a default value of 8 + 2 bytes. */ + #define ipconfigBUFFER_PADDING 0U +#endif + +#ifndef ipconfigPACKET_FILLER_SIZE + #define ipconfigPACKET_FILLER_SIZE 2U +#endif + +#ifndef ipconfigSELECT_USES_NOTIFY + #define ipconfigSELECT_USES_NOTIFY 0 +#endif + +#endif /* FREERTOS_DEFAULT_IP_CONFIG_H */ diff --git a/examples/stm32/freertos-tcp/include/FreeRTOS_ARP.h b/examples/stm32/freertos-tcp/include/FreeRTOS_ARP.h new file mode 100644 index 00000000..54193f53 --- /dev/null +++ b/examples/stm32/freertos-tcp/include/FreeRTOS_ARP.h @@ -0,0 +1,147 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +#ifndef FREERTOS_ARP_H + #define FREERTOS_ARP_H + + #ifdef __cplusplus + extern "C" { + #endif + +/* Application level configuration options. */ + #include "FreeRTOSIPConfig.h" + #include "FreeRTOSIPConfigDefaults.h" + #include "IPTraceMacroDefaults.h" + +/*-----------------------------------------------------------*/ +/* Miscellaneous structure and definitions. */ +/*-----------------------------------------------------------*/ + +/** + * Structure for one row in the ARP cache table. + */ + typedef struct xARP_CACHE_TABLE_ROW + { + uint32_t ulIPAddress; /**< The IP address of an ARP cache entry. */ + MACAddress_t xMACAddress; /**< The MAC address of an ARP cache entry. */ + uint8_t ucAge; /**< A value that is periodically decremented but can also be refreshed by active communication. The ARP cache entry is removed if the value reaches zero. */ + uint8_t ucValid; /**< pdTRUE: xMACAddress is valid, pdFALSE: waiting for ARP reply */ + } ARPCacheRow_t; + + typedef enum + { + eARPCacheMiss = 0, /* 0 An ARP table lookup did not find a valid entry. */ + eARPCacheHit, /* 1 An ARP table lookup found a valid entry. */ + eCantSendPacket /* 2 There is no IP address, or an ARP is still in progress, so the packet cannot be sent. */ + } eARPLookupResult_t; + +/* + * If ulIPAddress is already in the ARP cache table then reset the age of the + * entry back to its maximum value. If ulIPAddress is not already in the ARP + * cache table then add it - replacing the oldest current entry if there is not + * a free space available. + */ + void vARPRefreshCacheEntry( const MACAddress_t * pxMACAddress, + const uint32_t ulIPAddress ); + + #if ( ipconfigARP_USE_CLASH_DETECTION != 0 ) + /* Becomes non-zero if another device responded to a gratuitous ARP message. */ + extern BaseType_t xARPHadIPClash; + /* MAC-address of the other device containing the same IP-address. */ + extern MACAddress_t xARPClashMacAddress; + #endif /* ipconfigARP_USE_CLASH_DETECTION */ + + #if ( ipconfigUSE_ARP_REMOVE_ENTRY != 0 ) + +/* + * In some rare cases, it might be useful to remove a ARP cache entry of a + * known MAC address to make sure it gets refreshed. + */ + uint32_t ulARPRemoveCacheEntryByMac( const MACAddress_t * pxMACAddress ); + + #endif /* ipconfigUSE_ARP_REMOVE_ENTRY != 0 */ + +/* + * Look for ulIPAddress in the ARP cache. If the IP address exists, copy the + * associated MAC address into pxMACAddress, refresh the ARP cache entry's + * age, and return eARPCacheHit. If the IP address does not exist in the ARP + * cache return eARPCacheMiss. If the packet cannot be sent for any reason + * (maybe DHCP is still in process, or the addressing needs a gateway but there + * isn't a gateway defined) then return eCantSendPacket. + */ + eARPLookupResult_t eARPGetCacheEntry( uint32_t * pulIPAddress, + MACAddress_t * const pxMACAddress ); + + #if ( ipconfigUSE_ARP_REVERSED_LOOKUP != 0 ) + +/* Lookup an IP-address if only the MAC-address is known */ + eARPLookupResult_t eARPGetCacheEntryByMac( MACAddress_t * const pxMACAddress, + uint32_t * pulIPAddress ); + + #endif + +/* + * Reduce the age count in each entry within the ARP cache. An entry is no + * longer considered valid and is deleted if its age reaches zero. + */ + void vARPAgeCache( void ); + +/* + * Send out an ARP request for the IP address contained in pxNetworkBuffer, and + * add an entry into the ARP table that indicates that an ARP reply is + * outstanding so re-transmissions can be generated. + */ + void vARPGenerateRequestPacket( NetworkBufferDescriptor_t * const pxNetworkBuffer ); + +/* + * After DHCP is ready and when changing IP address, force a quick send of our new IP + * address + */ + void vARPSendGratuitous( void ); + +/* This function will check if the target IP-address belongs to this device. + * If so, the packet will be passed to the IP-stack, who will answer it. + * The function is to be called within the function xNetworkInterfaceOutput() + * in NetworkInterface.c as follows: + * + * if( xCheckLoopback( pxDescriptor, bReleaseAfterSend ) != 0 ) + * { + * / * The packet has been sent back to the IP-task. + * * The IP-task will further handle it. + * * Do not release the descriptor. + * * / + * return pdTRUE; + * } + * / * Send the packet as usual. * / + */ + BaseType_t xCheckLoopback( NetworkBufferDescriptor_t * const pxDescriptor, + BaseType_t bReleaseAfterSend ); + + #ifdef __cplusplus + } /* extern "C" */ + #endif + + +#endif /* FREERTOS_ARP_H */ diff --git a/examples/stm32/freertos-tcp/include/FreeRTOS_DHCP.h b/examples/stm32/freertos-tcp/include/FreeRTOS_DHCP.h new file mode 100644 index 00000000..3dd43ea1 --- /dev/null +++ b/examples/stm32/freertos-tcp/include/FreeRTOS_DHCP.h @@ -0,0 +1,121 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +#ifndef FREERTOS_DHCP_H + #define FREERTOS_DHCP_H + + #ifdef __cplusplus + extern "C" { + #endif + +/* Application level configuration options. */ + #include "FreeRTOSIPConfig.h" + #include "IPTraceMacroDefaults.h" + + #if ( ipconfigUSE_DHCP_HOOK != 0 ) + /* Used in the DHCP callback if ipconfigUSE_DHCP_HOOK is set to 1. */ + typedef enum eDHCP_PHASE + { + eDHCPPhasePreDiscover, /* Driver is about to send a DHCP discovery. */ + eDHCPPhasePreRequest /* Driver is about to request DHCP an IP address. */ + } eDHCPCallbackPhase_t; + +/* Used in the DHCP callback if ipconfigUSE_DHCP_HOOK is set to 1. */ + typedef enum eDHCP_ANSWERS + { + eDHCPContinue, /* Continue the DHCP process */ + eDHCPUseDefaults, /* Stop DHCP and use the static defaults. */ + eDHCPStopNoChanges, /* Stop DHCP and continue with current settings. */ + } eDHCPCallbackAnswer_t; + #endif /* #if( ipconfigUSE_DHCP_HOOK != 0 ) */ + +/* DHCP state machine states. */ + typedef enum + { + eInitialWait = 0, /**< Initial state: open a socket and wait a short time. */ + eWaitingSendFirstDiscover, /**< Send a discover the first time it is called, and reset all timers. */ + eWaitingOffer, /**< Either resend the discover, or, if the offer is forthcoming, send a request. */ + eWaitingAcknowledge, /**< Either resend the request. */ + eSendDHCPRequest, /**< Sendto failed earlier, resend the request to lease the IP-address offered. */ + #if ( ipconfigDHCP_FALL_BACK_AUTO_IP != 0 ) + eGetLinkLayerAddress, /* When DHCP didn't respond, try to obtain a LinkLayer address 168.254.x.x. */ + #endif + eLeasedAddress, /**< Resend the request at the appropriate time to renew the lease. */ + eNotUsingLeasedAddress /**< DHCP failed, and a default IP address is being used. */ + } eDHCPState_t; + +/** + * Hold information in between steps in the DHCP state machine. + */ + struct xDHCP_DATA + { + uint32_t ulTransactionId; /**< The ID of the DHCP transaction */ + uint32_t ulOfferedIPAddress; /**< The IP address offered by the DHCP server */ + uint32_t ulDHCPServerAddress; /**< The IP address of the DHCP server */ + uint32_t ulLeaseTime; /**< The time for which the current IP address is leased */ + TickType_t xDHCPTxTime; /**< The time at which a DHCP request was sent. */ + TickType_t xDHCPTxPeriod; /**< The maximum time that the client will wait for a reply. */ + BaseType_t xUseBroadcast; /**< Try both without and with the broadcast flag */ + eDHCPState_t eDHCPState; /**< Maintains the DHCP state machine state. */ + }; + + typedef struct xDHCP_DATA DHCPData_t; + +/* Returns the current state of a DHCP process. */ + eDHCPState_t eGetDHCPState( void ); + +/* + * Send a message to the IP-task, which will call vDHCPProcess(). + * + */ + BaseType_t xSendDHCPEvent( void ); + +/* + * NOT A PUBLIC API FUNCTION. + * It will be called when the DHCP timer expires, or when + * data has been received on the DHCP socket. + */ + void vDHCPProcess( BaseType_t xReset, + eDHCPState_t eExpectedState ); + +/* Internal call: returns true if socket is the current DHCP socket */ + BaseType_t xIsDHCPSocket( Socket_t xSocket ); + + #if ( ipconfigUSE_DHCP_HOOK != 0 ) + +/* Prototype of the hook (or callback) function that must be provided by the + * application if ipconfigUSE_DHCP_HOOK is set to 1. See the following URL for + * usage information: + * http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/TCP_IP_Configuration.html#ipconfigUSE_DHCP_HOOK + */ + eDHCPCallbackAnswer_t xApplicationDHCPHook( eDHCPCallbackPhase_t eDHCPPhase, + uint32_t ulIPAddress ); + #endif /* ( ipconfigUSE_DHCP_HOOK != 0 ) */ + + #ifdef __cplusplus + } /* extern "C" */ + #endif + +#endif /* FREERTOS_DHCP_H */ diff --git a/examples/stm32/freertos-tcp/include/FreeRTOS_DNS.h b/examples/stm32/freertos-tcp/include/FreeRTOS_DNS.h new file mode 100644 index 00000000..f89a1996 --- /dev/null +++ b/examples/stm32/freertos-tcp/include/FreeRTOS_DNS.h @@ -0,0 +1,151 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +#ifndef FREERTOS_DNS_H + #define FREERTOS_DNS_H + + #ifdef __cplusplus + extern "C" { + #endif + +/* Application level configuration options. */ + #include "FreeRTOSIPConfig.h" + #include "IPTraceMacroDefaults.h" + + +/* The Link-local Multicast Name Resolution (LLMNR) + * is included. + * Note that a special MAC address is required in addition to the NIC's actual + * MAC address: 01:00:5E:00:00:FC + * + * The target IP address will be 224.0.0.252 + */ + #if ( ipconfigBYTE_ORDER == pdFREERTOS_BIG_ENDIAN ) + #define ipLLMNR_IP_ADDR 0xE00000FCUL + #else + #define ipLLMNR_IP_ADDR 0xFC0000E0UL + #endif /* ipconfigBYTE_ORDER == pdFREERTOS_BIG_ENDIAN */ + + #define ipLLMNR_PORT 5355 /* Standard LLMNR port. */ + #define ipDNS_PORT 53 /* Standard DNS port. */ + #define ipDHCP_CLIENT 67 + #define ipDHCP_SERVER 68 + #define ipNBNS_PORT 137 /* NetBIOS Name Service. */ + #define ipNBDGM_PORT 138 /* Datagram Service, not included. */ + + #if ( ipconfigUSE_LLMNR == 1 ) || ( ipconfigUSE_NBNS == 1 ) + +/* + * The following function should be provided by the user and return true if it + * matches the domain name. + */ + extern BaseType_t xApplicationDNSQueryHook( const char * pcName ); + #endif /* ( ipconfigUSE_LLMNR == 1 ) || ( ipconfigUSE_NBNS == 1 ) */ + +/* + * LLMNR is very similar to DNS, so is handled by the DNS routines. + */ + uint32_t ulDNSHandlePacket( const NetworkBufferDescriptor_t * pxNetworkBuffer ); + + #if ( ipconfigUSE_LLMNR == 1 ) + /* The LLMNR MAC address is 01:00:5e:00:00:fc */ + extern const MACAddress_t xLLMNR_MacAdress; + #endif /* ipconfigUSE_LLMNR */ + + #if ( ipconfigUSE_NBNS != 0 ) + +/* + * Inspect a NetBIOS Names-Service message. If the name matches with ours + * (xApplicationDNSQueryHook returns true) an answer will be sent back. + * Note that LLMNR is a better protocol for name services on a LAN as it is + * less polluted + */ + uint32_t ulNBNSHandlePacket( NetworkBufferDescriptor_t * pxNetworkBuffer ); + + #endif /* ipconfigUSE_NBNS */ + + #if ( ipconfigUSE_DNS_CACHE != 0 ) + +/* Look for the indicated host name in the DNS cache. Returns the IPv4 + * address if present, or 0x0 otherwise. */ + uint32_t FreeRTOS_dnslookup( const char * pcHostName ); + +/* Remove all entries from the DNS cache. */ + void FreeRTOS_dnsclear( void ); + + #endif /* ipconfigUSE_DNS_CACHE != 0 */ + + #if ( ipconfigDNS_USE_CALLBACKS != 0 ) + +/* + * Users may define this type of function as a callback. + * It will be called when a DNS reply is received or when a timeout has been reached. + */ + typedef void (* FOnDNSEvent ) ( const char * /* pcName */, + void * /* pvSearchID */, + uint32_t /* ulIPAddress */ ); + +/* + * Asynchronous version of gethostbyname() + * xTimeout is in units of ms. + */ + uint32_t FreeRTOS_gethostbyname_a( const char * pcHostName, + FOnDNSEvent pCallback, + void * pvSearchID, + TickType_t uxTimeout ); + void FreeRTOS_gethostbyname_cancel( void * pvSearchID ); + + #endif /* if ( ipconfigDNS_USE_CALLBACKS != 0 ) */ + +/* + * Lookup a IPv4 node in a blocking-way. + * It returns a 32-bit IP-address, 0 when not found. + * gethostbyname() is already deprecated. + */ + uint32_t FreeRTOS_gethostbyname( const char * pcHostName ); + + #if ( ipconfigDNS_USE_CALLBACKS == 1 ) + +/* + * The function vDNSInitialise() initialises the DNS module. + * It will be called "internally", by the IP-task. + */ + void vDNSInitialise( void ); + #endif /* ( ipconfigDNS_USE_CALLBACKS == 1 ) */ + + #if ( ipconfigDNS_USE_CALLBACKS == 1 ) + +/* + * A function local to the library. + */ + extern void vDNSCheckCallBack( void * pvSearchID ); + #endif + + + #ifdef __cplusplus + } /* extern "C" */ + #endif + +#endif /* FREERTOS_DNS_H */ diff --git a/examples/stm32/freertos-tcp/include/FreeRTOS_IP.h b/examples/stm32/freertos-tcp/include/FreeRTOS_IP.h new file mode 100644 index 00000000..3354d6ae --- /dev/null +++ b/examples/stm32/freertos-tcp/include/FreeRTOS_IP.h @@ -0,0 +1,432 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +#ifndef FREERTOS_IP_H + #define FREERTOS_IP_H + + #ifdef __cplusplus + extern "C" { + #endif + + #include "FreeRTOS.h" + #include "task.h" + +/* Application level configuration options. */ + #include "FreeRTOSIPConfig.h" + #include "FreeRTOSIPConfigDefaults.h" + #include "IPTraceMacroDefaults.h" + +/* Some constants defining the sizes of several parts of a packet. + * These defines come before including the configuration header files. */ + +/* The size of the Ethernet header is 14, meaning that 802.1Q VLAN tags + * are not ( yet ) supported. */ + #define ipSIZE_OF_ETH_HEADER 14U + #define ipSIZE_OF_IPv4_HEADER 20U + #define ipSIZE_OF_IGMP_HEADER 8U + #define ipSIZE_OF_ICMP_HEADER 8U + #define ipSIZE_OF_UDP_HEADER 8U + #define ipSIZE_OF_TCP_HEADER 20U + + #define ipSIZE_OF_IPv4_ADDRESS 4U + +/* + * Generate a randomized TCP Initial Sequence Number per RFC. + * This function must be provided by the application builder. + */ +/* This function is defined generally by the application. */ + extern uint32_t ulApplicationGetNextSequenceNumber( uint32_t ulSourceAddress, + uint16_t usSourcePort, + uint32_t ulDestinationAddress, + uint16_t usDestinationPort ); + +/* The number of octets in the MAC and IP addresses respectively. */ + #define ipMAC_ADDRESS_LENGTH_BYTES ( 6 ) + #define ipIP_ADDRESS_LENGTH_BYTES ( 4 ) + +/* IP protocol definitions. */ + #define ipPROTOCOL_ICMP ( 1U ) + #define ipPROTOCOL_IGMP ( 2U ) + #define ipPROTOCOL_TCP ( 6U ) + #define ipPROTOCOL_UDP ( 17U ) + +/* The character used to fill ICMP echo requests, and therefore also the + * character expected to fill ICMP echo replies. */ + #define ipECHO_DATA_FILL_BYTE 'x' + +/* Dimensions the buffers that are filled by received Ethernet frames. */ + #define ipSIZE_OF_ETH_CRC_BYTES ( 4UL ) + #define ipSIZE_OF_ETH_OPTIONAL_802_1Q_TAG_BYTES ( 4UL ) + #define ipTOTAL_ETHERNET_FRAME_SIZE ( ( ( uint32_t ) ipconfigNETWORK_MTU ) + ( ( uint32_t ) ipSIZE_OF_ETH_HEADER ) + ipSIZE_OF_ETH_CRC_BYTES + ipSIZE_OF_ETH_OPTIONAL_802_1Q_TAG_BYTES ) + + +/* Space left at the beginning of a network buffer storage area to store a + * pointer back to the network buffer. Should be a multiple of 8 to ensure 8 byte + * alignment is maintained on architectures that require it. + * + * In order to get a 32-bit alignment of network packets, an offset of 2 bytes + * would be desirable, as defined by ipconfigPACKET_FILLER_SIZE. So the malloc'd + * buffer will have the following contents: + * uint32_t pointer; // word-aligned + * uchar_8 filler[6]; + * << ETH-header >> // half-word-aligned + * uchar_8 dest[6]; // start of pucEthernetBuffer + * uchar_8 dest[6]; + * uchar16_t type; + * << IP-header >> // word-aligned + * uint8_t ucVersionHeaderLength; + * etc + */ + + #if ( ipconfigBUFFER_PADDING != 0 ) + #define ipBUFFER_PADDING ipconfigBUFFER_PADDING + #else + #define ipBUFFER_PADDING ( 8U + ipconfigPACKET_FILLER_SIZE ) + #endif + +/** + * The structure used to store buffers and pass them around the network stack. + * Buffers can be in use by the stack, in use by the network interface hardware + * driver, or free (not in use). + */ + typedef struct xNETWORK_BUFFER + { + ListItem_t xBufferListItem; /**< Used to reference the buffer form the free buffer list or a socket. */ + uint32_t ulIPAddress; /**< Source or destination IP address, depending on usage scenario. */ + uint8_t * pucEthernetBuffer; /**< Pointer to the start of the Ethernet frame. */ + size_t xDataLength; /**< Starts by holding the total Ethernet frame length, then the UDP/TCP payload length. */ + uint16_t usPort; /**< Source or destination port, depending on usage scenario. */ + uint16_t usBoundPort; /**< The port to which a transmitting socket is bound. */ + #if ( ipconfigUSE_LINKED_RX_MESSAGES != 0 ) + struct xNETWORK_BUFFER * pxNextBuffer; /**< Possible optimisation for expert users - requires network driver support. */ + #endif + } NetworkBufferDescriptor_t; + + #include "pack_struct_start.h" + +/** + * MAC address structure. + */ + struct xMAC_ADDRESS + { + uint8_t ucBytes[ ipMAC_ADDRESS_LENGTH_BYTES ]; /**< Byte array of the MAC address */ + } + #include "pack_struct_end.h" + + typedef struct xMAC_ADDRESS MACAddress_t; + + typedef enum eNETWORK_EVENTS + { + eNetworkUp, /* The network is configured. */ + eNetworkDown /* The network connection has been lost. */ + } eIPCallbackEvent_t; + +/* MISRA check: some modules refer to this typedef even though + * ipconfigSUPPORT_OUTGOING_PINGS is not enabled. */ + typedef enum ePING_REPLY_STATUS + { + eSuccess = 0, /**< A correct reply has been received for an outgoing ping. */ + eInvalidChecksum, /**< A reply was received for an outgoing ping but the checksum of the reply was incorrect. */ + eInvalidData /**< A reply was received to an outgoing ping but the payload of the reply was not correct. */ + } ePingReplyStatus_t; + +/** + * The software timer struct for various IP functions + */ + typedef struct xIP_TIMER + { + uint32_t + bActive : 1, /**< This timer is running and must be processed. */ + bExpired : 1; /**< Timer has expired and a task must be processed. */ + TimeOut_t xTimeOut; /**< The timeout value. */ + TickType_t ulRemainingTime; /**< The amount of time remaining. */ + TickType_t ulReloadTime; /**< The value of reload time. */ + } IPTimer_t; + + +/* Endian related definitions. */ + #if ( ipconfigBYTE_ORDER == pdFREERTOS_LITTLE_ENDIAN ) + +/* FreeRTOS_htons / FreeRTOS_htonl: some platforms might have built-in versions + * using a single instruction so allow these versions to be overridden. */ + #ifndef FreeRTOS_htons + #define FreeRTOS_htons( usIn ) ( ( uint16_t ) ( ( ( usIn ) << 8U ) | ( ( usIn ) >> 8U ) ) ) + #endif + + #ifndef FreeRTOS_htonl + #define FreeRTOS_htonl( ulIn ) \ + ( \ + ( uint32_t ) \ + ( \ + ( ( ( ( uint32_t ) ( ulIn ) ) ) << 24 ) | \ + ( ( ( ( uint32_t ) ( ulIn ) ) & 0x0000ff00UL ) << 8 ) | \ + ( ( ( ( uint32_t ) ( ulIn ) ) & 0x00ff0000UL ) >> 8 ) | \ + ( ( ( ( uint32_t ) ( ulIn ) ) ) >> 24 ) \ + ) \ + ) + #endif /* ifndef FreeRTOS_htonl */ + + #else /* ipconfigBYTE_ORDER */ + + #define FreeRTOS_htons( x ) ( ( uint16_t ) ( x ) ) + #define FreeRTOS_htonl( x ) ( ( uint32_t ) ( x ) ) + + #endif /* ipconfigBYTE_ORDER == pdFREERTOS_LITTLE_ENDIAN */ + + #define FreeRTOS_ntohs( x ) FreeRTOS_htons( x ) + #define FreeRTOS_ntohl( x ) FreeRTOS_htonl( x ) + + #if ( ipconfigHAS_INLINE_FUNCTIONS == 1 ) + + static portINLINE int32_t FreeRTOS_max_int32( int32_t a, + int32_t b ); + static portINLINE uint32_t FreeRTOS_max_uint32( uint32_t a, + uint32_t b ); + static portINLINE int32_t FreeRTOS_min_int32( int32_t a, + int32_t b ); + static portINLINE uint32_t FreeRTOS_min_uint32( uint32_t a, + uint32_t b ); + static portINLINE uint32_t FreeRTOS_round_up( uint32_t a, + uint32_t d ); + static portINLINE uint32_t FreeRTOS_round_down( uint32_t a, + uint32_t d ); + static portINLINE BaseType_t FreeRTOS_min_BaseType( BaseType_t a, + BaseType_t b ); + + static portINLINE int32_t FreeRTOS_max_int32( int32_t a, + int32_t b ) + { + return ( a >= b ) ? a : b; + } + static portINLINE uint32_t FreeRTOS_max_uint32( uint32_t a, + uint32_t b ) + { + return ( a >= b ) ? a : b; + } + static portINLINE int32_t FreeRTOS_min_int32( int32_t a, + int32_t b ) + { + return ( a <= b ) ? a : b; + } + static portINLINE uint32_t FreeRTOS_min_uint32( uint32_t a, + uint32_t b ) + { + return ( a <= b ) ? a : b; + } + static portINLINE uint32_t FreeRTOS_round_up( uint32_t a, + uint32_t d ) + { + return d * ( ( a + d - 1U ) / d ); + } + static portINLINE uint32_t FreeRTOS_round_down( uint32_t a, + uint32_t d ) + { + return d * ( a / d ); + } + + static portINLINE BaseType_t FreeRTOS_min_BaseType( BaseType_t a, + BaseType_t b ) + { + return ( a <= b ) ? a : b; + } + + #else /* if ( ipconfigHAS_INLINE_FUNCTIONS == 1 ) */ + + #define FreeRTOS_max_int32( a, b ) ( ( ( ( int32_t ) ( a ) ) >= ( ( int32_t ) ( b ) ) ) ? ( ( int32_t ) ( a ) ) : ( ( int32_t ) ( b ) ) ) + #define FreeRTOS_max_uint32( a, b ) ( ( ( ( uint32_t ) ( a ) ) >= ( ( uint32_t ) ( b ) ) ) ? ( ( uint32_t ) ( a ) ) : ( ( uint32_t ) ( b ) ) ) + + #define FreeRTOS_min_int32( a, b ) ( ( ( ( int32_t ) a ) <= ( ( int32_t ) b ) ) ? ( ( int32_t ) a ) : ( ( int32_t ) b ) ) + #define FreeRTOS_min_uint32( a, b ) ( ( ( ( uint32_t ) a ) <= ( ( uint32_t ) b ) ) ? ( ( uint32_t ) a ) : ( ( uint32_t ) b ) ) + +/* Round-up: divide a by d and round=up the result. */ + #define FreeRTOS_round_up( a, d ) ( ( ( uint32_t ) ( d ) ) * ( ( ( ( uint32_t ) ( a ) ) + ( ( uint32_t ) ( d ) ) - 1UL ) / ( ( uint32_t ) ( d ) ) ) ) + #define FreeRTOS_round_down( a, d ) ( ( ( uint32_t ) ( d ) ) * ( ( ( uint32_t ) ( a ) ) / ( ( uint32_t ) ( d ) ) ) ) + + #define FreeRTOS_min_BaseType( a, b ) ( ( ( BaseType_t ) ( a ) ) <= ( ( BaseType_t ) ( b ) ) ? ( ( BaseType_t ) ( a ) ) : ( ( BaseType_t ) ( b ) ) ) + + #endif /* ipconfigHAS_INLINE_FUNCTIONS */ + + #define ipMS_TO_MIN_TICKS( xTimeInMs ) ( ( pdMS_TO_TICKS( ( xTimeInMs ) ) < ( ( TickType_t ) 1U ) ) ? ( ( TickType_t ) 1U ) : pdMS_TO_TICKS( ( xTimeInMs ) ) ) + +/* For backward compatibility. */ + #define pdMS_TO_MIN_TICKS( xTimeInMs ) ipMS_TO_MIN_TICKS( xTimeInMs ) + + #ifndef pdTRUE_SIGNED + /* Temporary solution: eventually the defines below will appear in 'Source\include\projdefs.h' */ + #define pdTRUE_SIGNED pdTRUE + #define pdFALSE_SIGNED pdFALSE + #define pdTRUE_UNSIGNED ( 1U ) + #define pdFALSE_UNSIGNED ( 0U ) + #define ipTRUE_BOOL ( 1 == 1 ) + #define ipFALSE_BOOL ( 1 == 2 ) + #endif + +/* + * FULL, UP-TO-DATE AND MAINTAINED REFERENCE DOCUMENTATION FOR ALL THESE + * FUNCTIONS IS AVAILABLE ON THE FOLLOWING URL: + * http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/FreeRTOS_TCP_API_Functions.html + */ + BaseType_t FreeRTOS_IPInit( const uint8_t ucIPAddress[ ipIP_ADDRESS_LENGTH_BYTES ], + const uint8_t ucNetMask[ ipIP_ADDRESS_LENGTH_BYTES ], + const uint8_t ucGatewayAddress[ ipIP_ADDRESS_LENGTH_BYTES ], + const uint8_t ucDNSServerAddress[ ipIP_ADDRESS_LENGTH_BYTES ], + const uint8_t ucMACAddress[ ipMAC_ADDRESS_LENGTH_BYTES ] ); + + void * FreeRTOS_GetUDPPayloadBuffer( size_t uxRequestedSizeBytes, + TickType_t uxBlockTimeTicks ); + void FreeRTOS_GetAddressConfiguration( uint32_t * pulIPAddress, + uint32_t * pulNetMask, + uint32_t * pulGatewayAddress, + uint32_t * pulDNSServerAddress ); + + void FreeRTOS_SetAddressConfiguration( const uint32_t * pulIPAddress, + const uint32_t * pulNetMask, + const uint32_t * pulGatewayAddress, + const uint32_t * pulDNSServerAddress ); + +/* MISRA defining 'FreeRTOS_SendPingRequest' should be dependent on 'ipconfigSUPPORT_OUTGOING_PINGS'. + * In order not to break some existing project, define it unconditionally. */ + BaseType_t FreeRTOS_SendPingRequest( uint32_t ulIPAddress, + size_t uxNumberOfBytesToSend, + TickType_t uxBlockTimeTicks ); + + void FreeRTOS_ReleaseUDPPayloadBuffer( void const * pvBuffer ); + const uint8_t * FreeRTOS_GetMACAddress( void ); + void FreeRTOS_UpdateMACAddress( const uint8_t ucMACAddress[ ipMAC_ADDRESS_LENGTH_BYTES ] ); + #if ( ipconfigUSE_NETWORK_EVENT_HOOK == 1 ) + /* This function shall be defined by the application. */ + void vApplicationIPNetworkEventHook( eIPCallbackEvent_t eNetworkEvent ); + #endif + #if ( ipconfigSUPPORT_OUTGOING_PINGS == 1 ) + void vApplicationPingReplyHook( ePingReplyStatus_t eStatus, + uint16_t usIdentifier ); + #endif + uint32_t FreeRTOS_GetIPAddress( void ); + void FreeRTOS_SetIPAddress( uint32_t ulIPAddress ); + void FreeRTOS_SetNetmask( uint32_t ulNetmask ); + void FreeRTOS_SetGatewayAddress( uint32_t ulGatewayAddress ); + uint32_t FreeRTOS_GetGatewayAddress( void ); + uint32_t FreeRTOS_GetDNSServerAddress( void ); + uint32_t FreeRTOS_GetNetmask( void ); + void FreeRTOS_OutputARPRequest( uint32_t ulIPAddress ); + BaseType_t FreeRTOS_IsNetworkUp( void ); + + #if ( ipconfigCHECK_IP_QUEUE_SPACE != 0 ) + UBaseType_t uxGetMinimumIPQueueSpace( void ); + #endif + + #if ( ipconfigHAS_PRINTF != 0 ) + extern void vPrintResourceStats( void ); + #else + #define vPrintResourceStats() do {} while( ipFALSE_BOOL ) + #endif + +/* + * Defined in FreeRTOS_Sockets.c + * //_RB_ Don't think this comment is correct. If this is for internal use only it should appear after all the public API functions and not start with FreeRTOS_. + * Socket has had activity, reset the timer so it will not be closed + * because of inactivity + */ + #if ( ( ipconfigHAS_DEBUG_PRINTF != 0 ) || ( ipconfigHAS_PRINTF != 0 ) ) + const char * FreeRTOS_GetTCPStateName( UBaseType_t ulState ); + #endif + +/* _HT_ Temporary: show all valid ARP entries + */ + #if ( ipconfigHAS_PRINTF != 0 ) || ( ipconfigHAS_DEBUG_PRINTF != 0 ) + void FreeRTOS_PrintARPCache( void ); + #endif + + void FreeRTOS_ClearARP( void ); + +/* Return pdTRUE if the IPv4 address is a multicast address. */ + BaseType_t xIsIPv4Multicast( uint32_t ulIPAddress ); + +/* Set the MAC-address that belongs to a given IPv4 multi-cast address. */ + void vSetMultiCastIPv4MacAddress( uint32_t ulIPAddress, + MACAddress_t * pxMACAddress ); + + #if ( ipconfigDHCP_REGISTER_HOSTNAME == 1 ) + +/* DHCP has an option for clients to register their hostname. It doesn't + * have much use, except that a device can be found in a router along with its + * name. If this option is used the callback below must be provided by the + * application writer to return a const string, denoting the device's name. */ +/* Typically this function is defined in a user module. */ + const char * pcApplicationHostnameHook( void ); + + #endif /* ipconfigDHCP_REGISTER_HOSTNAME */ + + +/* This xApplicationGetRandomNumber() will set *pulNumber to a random number, + * and return pdTRUE. When the random number generator is broken, it shall return + * pdFALSE. + * The function is defined in 'iot_secure_sockets.c'. + * If that module is not included in the project, the application must provide an + * implementation of it. + * The macro's ipconfigRAND32() and configRAND32() are not in use anymore. */ + +/* "xApplicationGetRandomNumber" is declared but never defined, because it may + * be defined in a user module. */ + extern BaseType_t xApplicationGetRandomNumber( uint32_t * pulNumber ); + +/* For backward compatibility define old structure names to the newer equivalent + * structure name. */ + #ifndef ipconfigENABLE_BACKWARD_COMPATIBILITY + #define ipconfigENABLE_BACKWARD_COMPATIBILITY 1 + #endif + + #if ( ipconfigENABLE_BACKWARD_COMPATIBILITY == 1 ) + #define xIPStackEvent_t IPStackEvent_t + #define xNetworkBufferDescriptor_t NetworkBufferDescriptor_t + #define xMACAddress_t MACAddress_t + #define xWinProperties_t WinProperties_t + #define xSocket_t Socket_t + #define xSocketSet_t SocketSet_t + #define ipSIZE_OF_IP_HEADER ipSIZE_OF_IPv4_HEADER + +/* Since August 2016, the public types and fields below have changed name: + * abbreviations TCP/UDP are now written in capitals, and type names now end with "_t". */ + #define FOnConnected FOnConnected_t + #define FOnTcpReceive FOnTCPReceive_t + #define FOnTcpSent FOnTCPSent_t + #define FOnUdpReceive FOnUDPReceive_t + #define FOnUdpSent FOnUDPSent_t + + #define pOnTcpConnected pxOnTCPConnected + #define pOnTcpReceive pxOnTCPReceive + #define pOnTcpSent pxOnTCPSent + #define pOnUdpReceive pxOnUDPReceive + #define pOnUdpSent pxOnUDPSent + + #define FOnUdpSent FOnUDPSent_t + #define FOnTcpSent FOnTCPSent_t + #endif /* ipconfigENABLE_BACKWARD_COMPATIBILITY */ + + #ifdef __cplusplus + } /* extern "C" */ + #endif + +#endif /* FREERTOS_IP_H */ diff --git a/examples/stm32/freertos-tcp/include/FreeRTOS_IP_Private.h b/examples/stm32/freertos-tcp/include/FreeRTOS_IP_Private.h new file mode 100644 index 00000000..c8004418 --- /dev/null +++ b/examples/stm32/freertos-tcp/include/FreeRTOS_IP_Private.h @@ -0,0 +1,1009 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +#ifndef FREERTOS_IP_PRIVATE_H + #define FREERTOS_IP_PRIVATE_H + + #ifdef __cplusplus + extern "C" { + #endif + +/* Application level configuration options. */ + #include "FreeRTOSIPConfig.h" + #include "FreeRTOSIPConfigDefaults.h" + #include "FreeRTOS_Sockets.h" + #include "IPTraceMacroDefaults.h" + #include "FreeRTOS_Stream_Buffer.h" + #if ( ipconfigUSE_TCP == 1 ) + #include "FreeRTOS_TCP_WIN.h" + #include "FreeRTOS_TCP_IP.h" + #endif + + #include "semphr.h" + + #include "event_groups.h" + +/*-----------------------------------------------------------*/ +/* Utility macros for marking casts as recognized during */ +/* static analysis. */ +/*-----------------------------------------------------------*/ + #define ipCAST_PTR_TO_TYPE_PTR( TYPE, pointer ) ( vCastPointerTo_ ## TYPE( ( void * ) ( pointer ) ) ) + #define ipCAST_CONST_PTR_TO_CONST_TYPE_PTR( TYPE, pointer ) ( vCastConstPointerTo_ ## TYPE( ( const void * ) ( pointer ) ) ) + +/*-----------------------------------------------------------*/ +/* Utility macros for declaring cast utility functions in */ +/* order to centralize typecasting for static analysis. */ +/*-----------------------------------------------------------*/ + #define ipDECL_CAST_PTR_FUNC_FOR_TYPE( TYPE ) TYPE * vCastPointerTo_ ## TYPE( void * pvArgument ) + #define ipDECL_CAST_CONST_PTR_FUNC_FOR_TYPE( TYPE ) const TYPE * vCastConstPointerTo_ ## TYPE( const void * pvArgument ) + +/** + * Structure to hold the information about the Network parameters. + */ + typedef struct xNetworkAddressingParameters + { + uint32_t ulDefaultIPAddress; /**< The default IP address */ + uint32_t ulNetMask; /**< The netmask */ + uint32_t ulGatewayAddress; /**< The gateway address */ + uint32_t ulDNSServerAddress; /**< The DNS server address */ + uint32_t ulBroadcastAddress; /**< The Broadcast address */ + } NetworkAddressingParameters_t; + + extern BaseType_t xTCPWindowLoggingLevel; + extern QueueHandle_t xNetworkEventQueue; + +/*-----------------------------------------------------------*/ +/* Protocol headers. */ +/*-----------------------------------------------------------*/ + + #include "pack_struct_start.h" + struct xETH_HEADER + { + MACAddress_t xDestinationAddress; /**< Destination address 0 + 6 = 6 */ + MACAddress_t xSourceAddress; /**< Source address 6 + 6 = 12 */ + uint16_t usFrameType; /**< The EtherType field 12 + 2 = 14 */ + } + #include "pack_struct_end.h" + typedef struct xETH_HEADER EthernetHeader_t; + + static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( EthernetHeader_t ) + { + return ( EthernetHeader_t * ) pvArgument; + } + + static portINLINE ipDECL_CAST_CONST_PTR_FUNC_FOR_TYPE( EthernetHeader_t ) + { + return ( const EthernetHeader_t * ) pvArgument; + } + + + #include "pack_struct_start.h" + struct xARP_HEADER + { + uint16_t usHardwareType; /**< Network Link Protocol type 0 + 2 = 2 */ + uint16_t usProtocolType; /**< The internetwork protocol 2 + 2 = 4 */ + uint8_t ucHardwareAddressLength; /**< Length in octets of a hardware address 4 + 1 = 5 */ + uint8_t ucProtocolAddressLength; /**< Length in octets of the internetwork protocol 5 + 1 = 6 */ + uint16_t usOperation; /**< Operation that the sender is performing 6 + 2 = 8 */ + MACAddress_t xSenderHardwareAddress; /**< Media address of the sender 8 + 6 = 14 */ + uint8_t ucSenderProtocolAddress[ 4 ]; /**< Internetwork address of sender 14 + 4 = 18 */ + MACAddress_t xTargetHardwareAddress; /**< Media address of the intended receiver 18 + 6 = 24 */ + uint32_t ulTargetProtocolAddress; /**< Internetwork address of the intended receiver 24 + 4 = 28 */ + } + #include "pack_struct_end.h" + typedef struct xARP_HEADER ARPHeader_t; + + #include "pack_struct_start.h" + struct xIP_HEADER + { + uint8_t ucVersionHeaderLength; /**< The version field + internet header length 0 + 1 = 1 */ + uint8_t ucDifferentiatedServicesCode; /**< Differentiated services code point + ECN 1 + 1 = 2 */ + uint16_t usLength; /**< Entire Packet size 2 + 2 = 4 */ + uint16_t usIdentification; /**< Identification field 4 + 2 = 6 */ + uint16_t usFragmentOffset; /**< Fragment flags and fragment offset 6 + 2 = 8 */ + uint8_t ucTimeToLive; /**< Time to live field 8 + 1 = 9 */ + uint8_t ucProtocol; /**< Protocol used in the IP-datagram 9 + 1 = 10 */ + uint16_t usHeaderChecksum; /**< Checksum of the IP-header 10 + 2 = 12 */ + uint32_t ulSourceIPAddress; /**< IP address of the source 12 + 4 = 16 */ + uint32_t ulDestinationIPAddress; /**< IP address of the destination 16 + 4 = 20 */ + } + #include "pack_struct_end.h" + typedef struct xIP_HEADER IPHeader_t; + + static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( IPHeader_t ) + { + return ( IPHeader_t * ) pvArgument; + } + static portINLINE ipDECL_CAST_CONST_PTR_FUNC_FOR_TYPE( IPHeader_t ) + { + return ( const IPHeader_t * ) pvArgument; + } + + + #include "pack_struct_start.h" + struct xICMP_HEADER + { + uint8_t ucTypeOfMessage; /**< The ICMP type 0 + 1 = 1 */ + uint8_t ucTypeOfService; /**< The ICMP subtype 1 + 1 = 2 */ + uint16_t usChecksum; /**< The checksum of whole ICMP packet 2 + 2 = 4 */ + uint16_t usIdentifier; /**< Used in some types of ICMP 4 + 2 = 6 */ + uint16_t usSequenceNumber; /**< Used in some types of ICMP 6 + 2 = 8 */ + } + #include "pack_struct_end.h" + typedef struct xICMP_HEADER ICMPHeader_t; + + static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( ICMPHeader_t ) + { + return ( ICMPHeader_t * ) pvArgument; + } + static portINLINE ipDECL_CAST_CONST_PTR_FUNC_FOR_TYPE( ICMPHeader_t ) + { + return ( const ICMPHeader_t * ) pvArgument; + } + + + #include "pack_struct_start.h" + struct xUDP_HEADER + { + uint16_t usSourcePort; /**< The source port 0 + 2 = 2 */ + uint16_t usDestinationPort; /**< The destination port 2 + 2 = 4 */ + uint16_t usLength; /**< The size of the whole UDP packet 4 + 2 = 6 */ + uint16_t usChecksum; /**< The checksum of the whole UDP Packet 6 + 2 = 8 */ + } + #include "pack_struct_end.h" + typedef struct xUDP_HEADER UDPHeader_t; + + #include "pack_struct_start.h" + struct xTCP_HEADER + { + uint16_t usSourcePort; /**< The Source port + 2 = 2 */ + uint16_t usDestinationPort; /**< The destination port + 2 = 4 */ + uint32_t ulSequenceNumber; /**< The Sequence number + 4 = 8 */ + uint32_t ulAckNr; /**< The acknowledgement number + 4 = 12 */ + uint8_t ucTCPOffset; /**< The value of TCP offset + 1 = 13 */ + uint8_t ucTCPFlags; /**< The TCP-flags field + 1 = 14 */ + uint16_t usWindow; /**< The size of the receive window + 2 = 15 */ + uint16_t usChecksum; /**< The checksum of the header + 2 = 18 */ + uint16_t usUrgent; /**< Pointer to the last urgent data byte + 2 = 20 */ + #if ipconfigUSE_TCP == 1 + uint8_t ucOptdata[ ipSIZE_TCP_OPTIONS ]; /**< The options + 12 = 32 */ + #endif + } + #include "pack_struct_end.h" + typedef struct xTCP_HEADER TCPHeader_t; + + +/*-----------------------------------------------------------*/ +/* Nested protocol packets. */ +/*-----------------------------------------------------------*/ + + #include "pack_struct_start.h" + struct xARP_PACKET + { + EthernetHeader_t xEthernetHeader; /**< The ethernet header of an ARP Packet 0 + 14 = 14 */ + ARPHeader_t xARPHeader; /**< The ARP header of an ARP Packet 14 + 28 = 42 */ + } + #include "pack_struct_end.h" + typedef struct xARP_PACKET ARPPacket_t; + + static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( ARPPacket_t ) + { + return ( ARPPacket_t * ) pvArgument; + } + static portINLINE ipDECL_CAST_CONST_PTR_FUNC_FOR_TYPE( ARPPacket_t ) + { + return ( const ARPPacket_t * ) pvArgument; + } + + + #include "pack_struct_start.h" + struct xIP_PACKET + { + EthernetHeader_t xEthernetHeader; + IPHeader_t xIPHeader; + } + #include "pack_struct_end.h" + typedef struct xIP_PACKET IPPacket_t; + + static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( IPPacket_t ) + { + return ( IPPacket_t * ) pvArgument; + } + static portINLINE ipDECL_CAST_CONST_PTR_FUNC_FOR_TYPE( IPPacket_t ) + { + return ( const IPPacket_t * ) pvArgument; + } + + + #include "pack_struct_start.h" + struct xICMP_PACKET + { + EthernetHeader_t xEthernetHeader; /**< The Ethernet header of an ICMP packet. */ + IPHeader_t xIPHeader; /**< The IP header of an ICMP packet. */ + ICMPHeader_t xICMPHeader; /**< The ICMP header of an ICMP packet. */ + } + #include "pack_struct_end.h" + typedef struct xICMP_PACKET ICMPPacket_t; + + static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( ICMPPacket_t ) + { + return ( ICMPPacket_t * ) pvArgument; + } + + + #include "pack_struct_start.h" + struct xUDP_PACKET + { + EthernetHeader_t xEthernetHeader; /**< UDP-Packet ethernet header 0 + 14 = 14 */ + IPHeader_t xIPHeader; /**< UDP-Packet IP header 14 + 20 = 34 */ + UDPHeader_t xUDPHeader; /**< UDP-Packet UDP header 34 + 8 = 42 */ + } + #include "pack_struct_end.h" + typedef struct xUDP_PACKET UDPPacket_t; + + static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( UDPPacket_t ) + { + return ( UDPPacket_t * ) pvArgument; + } + static portINLINE ipDECL_CAST_CONST_PTR_FUNC_FOR_TYPE( UDPPacket_t ) + { + return ( const UDPPacket_t * ) pvArgument; + } + + #include "pack_struct_start.h" + struct xTCP_PACKET + { + EthernetHeader_t xEthernetHeader; /**< The ethernet header 0 + 14 = 14 */ + IPHeader_t xIPHeader; /**< The IP header 14 + 20 = 34 */ + TCPHeader_t xTCPHeader; /**< The TCP header 34 + 32 = 66 */ + } + #include "pack_struct_end.h" + typedef struct xTCP_PACKET TCPPacket_t; + + static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( TCPPacket_t ) + { + return ( TCPPacket_t * ) pvArgument; + } + + static portINLINE ipDECL_CAST_CONST_PTR_FUNC_FOR_TYPE( TCPPacket_t ) + { + return ( const TCPPacket_t * ) pvArgument; + } + + +/** + * Union for the protocol packet to save space. Any packet cannot have more than one + * of the below protocol packets. + */ + typedef union XPROT_PACKET + { + ARPPacket_t xARPPacket; /**< Union member: ARP packet struct */ + TCPPacket_t xTCPPacket; /**< Union member: TCP packet struct */ + UDPPacket_t xUDPPacket; /**< Union member: UDP packet struct */ + ICMPPacket_t xICMPPacket; /**< Union member: ICMP packet struct */ + } ProtocolPacket_t; + + static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( ProtocolPacket_t ) + { + return ( ProtocolPacket_t * ) pvArgument; + } + static portINLINE ipDECL_CAST_CONST_PTR_FUNC_FOR_TYPE( ProtocolPacket_t ) + { + return ( const ProtocolPacket_t * ) pvArgument; + } + +/** + * Union for protocol headers to save space (RAM). Any packet cannot have more than one of + * the below protocols. + */ + typedef union xPROT_HEADERS + { + ICMPHeader_t xICMPHeader; /**< Union member: ICMP header */ + UDPHeader_t xUDPHeader; /**< Union member: UDP header */ + TCPHeader_t xTCPHeader; /**< Union member: TCP header */ + } ProtocolHeaders_t; + + static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( ProtocolHeaders_t ) + { + return ( ProtocolHeaders_t * ) pvArgument; + } + + static portINLINE ipDECL_CAST_CONST_PTR_FUNC_FOR_TYPE( ProtocolHeaders_t ) + { + return ( const ProtocolHeaders_t * ) pvArgument; + } + +/* The maximum UDP payload length. */ + #define ipMAX_UDP_PAYLOAD_LENGTH ( ( ipconfigNETWORK_MTU - ipSIZE_OF_IPv4_HEADER ) - ipSIZE_OF_UDP_HEADER ) + + typedef enum + { + eReleaseBuffer = 0, /* Processing the frame did not find anything to do - just release the buffer. */ + eProcessBuffer, /* An Ethernet frame has a valid address - continue process its contents. */ + eReturnEthernetFrame, /* The Ethernet frame contains an ARP or ICMP packet that can be returned to its source. */ + eFrameConsumed /* Processing the Ethernet packet contents resulted in the payload being sent to the stack. */ + } eFrameProcessingResult_t; + + typedef enum + { + eNoEvent = -1, + eNetworkDownEvent, /* 0: The network interface has been lost and/or needs [re]connecting. */ + eNetworkRxEvent, /* 1: The network interface has queued a received Ethernet frame. */ + eNetworkTxEvent, /* 2: Let the IP-task send a network packet. */ + eARPTimerEvent, /* 3: The ARP timer expired. */ + eStackTxEvent, /* 4: The software stack has queued a packet to transmit. */ + eDHCPEvent, /* 5: Process the DHCP state machine. */ + eTCPTimerEvent, /* 6: See if any TCP socket needs attention. */ + eTCPAcceptEvent, /* 7: Client API FreeRTOS_accept() waiting for client connections. */ + eTCPNetStat, /* 8: IP-task is asked to produce a netstat listing. */ + eSocketBindEvent, /* 9: Send a message to the IP-task to bind a socket to a port. */ + eSocketCloseEvent, /*10: Send a message to the IP-task to close a socket. */ + eSocketSelectEvent, /*11: Send a message to the IP-task for select(). */ + eSocketSignalEvent, /*12: A socket must be signalled. */ + } eIPEvent_t; + +/** + * Structure for the information of the commands issued to the IP task. + */ + typedef struct IP_TASK_COMMANDS + { + eIPEvent_t eEventType; /**< The event-type enum */ + void * pvData; /**< The data in the event */ + } IPStackEvent_t; + + #define ipBROADCAST_IP_ADDRESS 0xffffffffUL + + +/* Offset into the Ethernet frame that is used to temporarily store information + * on the fragmentation status of the packet being sent. The value is important, + * as it is past the location into which the destination address will get placed. */ + #define ipFRAGMENTATION_PARAMETERS_OFFSET ( 6 ) + #define ipSOCKET_OPTIONS_OFFSET ( 6 ) + +/* Only used when outgoing fragmentation is being used (FreeRTOSIPConfig.h + * setting. */ + #define ipGET_UDP_PAYLOAD_OFFSET_FOR_FRAGMENT( usFragmentOffset ) ( ( ( usFragmentOffset ) == 0 ) ? ipUDP_PAYLOAD_OFFSET_IPv4 : ipIP_PAYLOAD_OFFSET ) + +/* The offset into a UDP packet at which the UDP data (payload) starts. */ + #define ipUDP_PAYLOAD_OFFSET_IPv4 ( sizeof( UDPPacket_t ) ) + +/* The offset into an IP packet into which the IP data (payload) starts. */ + #define ipIP_PAYLOAD_OFFSET ( sizeof( IPPacket_t ) ) + + #if ( ipconfigBYTE_ORDER == pdFREERTOS_LITTLE_ENDIAN ) + +/* Ethernet frame types. */ + #define ipARP_FRAME_TYPE ( 0x0608U ) + #define ipIPv4_FRAME_TYPE ( 0x0008U ) + +/* ARP related definitions. */ + #define ipARP_PROTOCOL_TYPE ( 0x0008U ) + #define ipARP_HARDWARE_TYPE_ETHERNET ( 0x0100U ) + #define ipARP_REQUEST ( 0x0100U ) + #define ipARP_REPLY ( 0x0200U ) + + #else /* if ( ipconfigBYTE_ORDER == pdFREERTOS_LITTLE_ENDIAN ) */ + +/* Ethernet frame types. */ + #define ipARP_FRAME_TYPE ( 0x0806U ) + #define ipIPv4_FRAME_TYPE ( 0x0800U ) + +/* ARP related definitions. */ + #define ipARP_PROTOCOL_TYPE ( 0x0800U ) + #define ipARP_HARDWARE_TYPE_ETHERNET ( 0x0001U ) + #define ipARP_REQUEST ( 0x0001 ) + #define ipARP_REPLY ( 0x0002 ) + + #endif /* ipconfigBYTE_ORDER == pdFREERTOS_LITTLE_ENDIAN */ + + +/* For convenience, a MAC address of all zeros and another of all 0xffs are + * defined const for quick reference. */ + extern const MACAddress_t xBroadcastMACAddress; /* all 0xff's */ + extern uint16_t usPacketIdentifier; + +/** + * Define a default UDP packet header (declared in FreeRTOS_UDP_IP.c) + */ + typedef union xUDPPacketHeader + { + uint8_t ucBytes[ 24 ]; /**< Member: 8-bit array */ + uint32_t ulWords[ 6 ]; /**< Member: 32-bit array */ + } UDPPacketHeader_t; + extern UDPPacketHeader_t xDefaultPartUDPPacketHeader; + + +/* Structure that stores the netmask, gateway address and DNS server addresses. */ + extern NetworkAddressingParameters_t xNetworkAddressing; + +/* Structure that stores the defaults for netmask, gateway address and DNS. + * These values will be copied to 'xNetworkAddressing' in case DHCP is not used, + * and also in case DHCP does not lead to a confirmed request. */ +/*lint -e9003*/ + extern NetworkAddressingParameters_t xDefaultAddressing; /*lint !e9003 could define variable 'xDefaultAddressing' at block scope [MISRA 2012 Rule 8.9, advisory]. */ + +/* True when BufferAllocation_1.c was included, false for BufferAllocation_2.c */ + extern const BaseType_t xBufferAllocFixedSize; + +/* Defined in FreeRTOS_Sockets.c */ + #if ( ipconfigUSE_TCP == 1 ) + extern List_t xBoundTCPSocketsList; + #endif + +/* The local IP address is accessed from within xDefaultPartUDPPacketHeader, + * rather than duplicated in its own variable. */ + #define ipLOCAL_IP_ADDRESS_POINTER ( ( uint32_t * ) &( xDefaultPartUDPPacketHeader.ulWords[ 20U / sizeof( uint32_t ) ] ) ) + +/* The local MAC address is accessed from within xDefaultPartUDPPacketHeader, + * rather than duplicated in its own variable. */ + #define ipLOCAL_MAC_ADDRESS ( xDefaultPartUDPPacketHeader.ucBytes ) + +/* In this library, there is often a cast from a character pointer + * to a pointer to a struct. + * In order to suppress MISRA warnings, do the cast within a macro, + * which can be exempt from warnings: + * + * 3 required by MISRA: + * -emacro(740,ipPOINTER_CAST) // 750: Unusual pointer cast (incompatible indirect types) [MISRA 2012 Rule 1.3, required]) + * -emacro(9005,ipPOINTER_CAST) // 9005: attempt to cast away const/volatile from a pointer or reference [MISRA 2012 Rule 11.8, required] + * -emacro(9087,ipPOINTER_CAST) // 9087: cast performed between a pointer to object type and a pointer to a different object type [MISRA 2012 Rule 11.3, required] + * + * 2 advisory by MISRA: + * -emacro(9079,ipPOINTER_CAST) // 9079: conversion from pointer to void to pointer to other type [MISRA 2012 Rule 11.5, advisory]) + * --emacro((826),ipPOINTER_CAST) // 826: Suspicious pointer-to-pointer conversion (area too small) + * + * The MISRA warnings can safely be suppressed because all casts are planned with care. + */ + + #define ipPOINTER_CAST( TYPE, pointer ) ( ( TYPE ) ( pointer ) ) + +/* Sequence and ACK numbers are essentially unsigned (uint32_t). But when + * a distance is calculated, it is useful to use signed numbers: + * int32_t lDistance = ( int32_t ) ( ulSeq1 - ulSeq2 ); + * + * 1 required by MISRA: + * -emacro(9033,ipNUMERIC_CAST) // 9033: Impermissible cast of composite expression (different essential type categories) [MISRA 2012 Rule 10.8, required]) + * + * 1 advisory by MISRA: + * -emacro(9030,ipNUMERIC_CAST) // 9030: Impermissible cast; cannot cast from 'essentially Boolean' to 'essentially signed' [MISRA 2012 Rule 10.5, advisory]) + */ + + #define ipNUMERIC_CAST( TYPE, expression ) ( ( TYPE ) ( expression ) ) + +/* ICMP packets are sent using the same function as UDP packets. The port + * number is used to distinguish between the two, as 0 is an invalid UDP port. */ + #define ipPACKET_CONTAINS_ICMP_DATA ( 0 ) + +/* For now, the lower 8 bits in 'xEventBits' will be reserved for the above + * socket events. */ + #define SOCKET_EVENT_BIT_COUNT 8 + + #define vSetField16( pxBase, xType, xField, usValue ) \ + { \ + ( ( uint8_t * ) ( pxBase ) )[ offsetof( xType, xField ) + 0 ] = ( uint8_t ) ( ( usValue ) >> 8 ); \ + ( ( uint8_t * ) ( pxBase ) )[ offsetof( xType, xField ) + 1 ] = ( uint8_t ) ( ( usValue ) & 0xffU ); \ + } + + #define vSetField32( pxBase, xType, xField, ulValue ) \ + { \ + ( ( uint8_t * ) ( pxBase ) )[ offsetof( xType, xField ) + 0 ] = ( uint8_t ) ( ( ulValue ) >> 24 ); \ + ( ( uint8_t * ) ( pxBase ) )[ offsetof( xType, xField ) + 1 ] = ( uint8_t ) ( ( ( ulValue ) >> 16 ) & 0xffU ); \ + ( ( uint8_t * ) ( pxBase ) )[ offsetof( xType, xField ) + 2 ] = ( uint8_t ) ( ( ( ulValue ) >> 8 ) & 0xffU ); \ + ( ( uint8_t * ) ( pxBase ) )[ offsetof( xType, xField ) + 3 ] = ( uint8_t ) ( ( ulValue ) & 0xffU ); \ + } + + #define vFlip_16( left, right ) \ + do { \ + uint16_t tmp = ( left ); \ + ( left ) = ( right ); \ + ( right ) = tmp; \ + } while( ipFALSE_BOOL ) + + #define vFlip_32( left, right ) \ + do { \ + uint32_t tmp = ( left ); \ + ( left ) = ( right ); \ + ( right ) = tmp; \ + } while( ipFALSE_BOOL ) + +/* WARNING: Do NOT use this macro when the array was received as a parameter. */ + #ifndef ARRAY_SIZE + #define ARRAY_SIZE( x ) ( ( BaseType_t ) ( sizeof( x ) / sizeof( ( x )[ 0 ] ) ) ) + #endif + +/* + * Create a message that contains a command to initialise the network interface. + * This is used during initialisation, and at any time the network interface + * goes down thereafter. The network interface hardware driver is responsible + * for sending the message that contains the network interface down command/ + * event. + * + * Only use the FreeRTOS_NetworkDownFromISR() version if the function is to be + * called from an interrupt service routine. If FreeRTOS_NetworkDownFromISR() + * returns a non-zero value then a context switch should be performed before + * the interrupt is exited. + */ + void FreeRTOS_NetworkDown( void ); + BaseType_t FreeRTOS_NetworkDownFromISR( void ); + +/* + * Processes incoming ARP packets. + */ + eFrameProcessingResult_t eARPProcessPacket( ARPPacket_t * const pxARPFrame ); + +/* + * Inspect an Ethernet frame to see if it contains data that the stack needs to + * process. eProcessBuffer is returned if the frame should be processed by the + * stack. eReleaseBuffer is returned if the frame should be discarded. + */ + eFrameProcessingResult_t eConsiderFrameForProcessing( const uint8_t * const pucEthernetBuffer ); + +/* + * Return the checksum generated over xDataLengthBytes from pucNextData. + */ + uint16_t usGenerateChecksum( uint16_t usSum, + const uint8_t * pucNextData, + size_t uxByteCount ); + +/* Socket related private functions. */ + +/* + * The caller must ensure that pxNetworkBuffer->xDataLength is the UDP packet + * payload size (excluding packet headers) and that the packet in pucEthernetBuffer + * is at least the size of UDPPacket_t. + */ + BaseType_t xProcessReceivedUDPPacket( NetworkBufferDescriptor_t * pxNetworkBuffer, + uint16_t usPort ); + +/* + * Initialize the socket list data structures for TCP and UDP. + */ + void vNetworkSocketsInit( void ); + +/* + * Returns pdTRUE if the IP task has been created and is initialised. Otherwise + * returns pdFALSE. + */ + BaseType_t xIPIsNetworkTaskReady( void ); + + #if ( ipconfigSOCKET_HAS_USER_WAKE_CALLBACK == 1 ) + struct xSOCKET; + typedef void (* SocketWakeupCallback_t)( struct xSOCKET * pxSocket ); + #endif + + #if ( ipconfigUSE_TCP == 1 ) + +/* + * Actually a user thing, but because xBoundTCPSocketsList, let it do by the + * IP-task + */ + #if ( ipconfigHAS_PRINTF != 0 ) + void vTCPNetStat( void ); + #endif + +/* + * At least one socket needs to check for timeouts + */ + TickType_t xTCPTimerCheck( BaseType_t xWillSleep ); + +/** + * Every TCP socket has a buffer space just big enough to store + * the last TCP header received. + * As a reference of this field may be passed to DMA, force the + * alignment to 8 bytes. + */ + typedef union + { + struct + { + uint64_t ullAlignmentWord; /**< Increase the alignment of this union by adding a 64-bit variable. */ + } a; /**< A struct to increase alignment. */ + struct + { + /* The next field only serves to give 'ucLastPacket' a correct + * alignment of 8 + 2. See comments in FreeRTOS_IP.h */ + uint8_t ucFillPacket[ ipconfigPACKET_FILLER_SIZE ]; + uint8_t ucLastPacket[ sizeof( TCPPacket_t ) ]; + } u; /**< The structure to give an alignment of 8 + 2 */ + } LastTCPPacket_t; + +/** + * Note that the values of all short and long integers in these structs + * are being stored in the native-endian way + * Translation should take place when accessing any structure which defines + * network packets, such as IPHeader_t and TCPHeader_t + */ + typedef struct TCPSOCKET + { + uint32_t ulRemoteIP; /**< IP address of remote machine */ + uint16_t usRemotePort; /**< Port on remote machine */ + struct + { + /* Most compilers do like bit-flags */ + uint32_t + bMssChange : 1, /**< This socket has seen a change in MSS */ + bPassAccept : 1, /**< when true, this socket may be returned in a call to accept() */ + bPassQueued : 1, /**< when true, this socket is an orphan until it gets connected + * Why an orphan? Because it may not be returned in a accept() call until it + * gets the state eESTABLISHED */ + bReuseSocket : 1, /**< When a listening socket gets a connection, do not create a new instance but keep on using it */ + bCloseAfterSend : 1, /**< As soon as the last byte has been transmitted, finalise the connection + * Useful in e.g. FTP connections, where the last data bytes are sent along with the FIN flag */ + bUserShutdown : 1, /**< User requesting a graceful shutdown */ + bCloseRequested : 1, /**< Request to finalise the connection */ + bLowWater : 1, /**< high-water level has been reached. Cleared as soon as 'rx-count < lo-water' */ + bWinChange : 1, /**< The value of bLowWater has changed, must send a window update */ + bSendKeepAlive : 1, /**< When this flag is true, a TCP keep-alive message must be send */ + bWaitKeepAlive : 1, /**< When this flag is true, a TCP keep-alive reply is expected */ + bConnPrepared : 1, /**< Connecting socket: Message has been prepared */ + #if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 ) + bConnPassed : 1, /**< Connecting socket: Socket has been passed in a successful select() */ + #endif /* ipconfigSUPPORT_SELECT_FUNCTION */ + bFinAccepted : 1, /**< This socket has received (or sent) a FIN and accepted it */ + bFinSent : 1, /**< We've sent out a FIN */ + bFinRecv : 1, /**< We've received a FIN from our peer */ + bFinAcked : 1, /**< Our FIN packet has been acked */ + bFinLast : 1, /**< The last ACK (after FIN and FIN+ACK) has been sent or will be sent by the peer */ + bRxStopped : 1, /**< Application asked to temporarily stop reception */ + bMallocError : 1, /**< There was an error allocating a stream */ + bWinScaling : 1; /**< A TCP-Window Scaling option was offered and accepted in the SYN phase. */ + } bits; /**< The bits structure */ + uint32_t ulHighestRxAllowed; /**< The highest sequence number that we can receive at any moment */ + uint16_t usTimeout; /**< Time (in ticks) after which this socket needs attention */ + uint16_t usCurMSS; /**< Current Maximum Segment Size */ + uint16_t usInitMSS; /**< Initial maximum segment Size */ + uint16_t usChildCount; /**< In case of a listening socket: number of connections on this port number */ + uint16_t usBacklog; /**< In case of a listening socket: maximum number of concurrent connections on this port number */ + uint8_t ucRepCount; /**< Send repeat count, for retransmissions + * This counter is separate from the xmitCount in the + * TCP win segments */ + uint8_t ucTCPState; /**< TCP state: see eTCP_STATE */ + struct xSOCKET * pxPeerSocket; /**< for server socket: child, for child socket: parent */ + #if ( ipconfigTCP_KEEP_ALIVE == 1 ) + uint8_t ucKeepRepCount; + TickType_t xLastAliveTime; /**< The last value of keepalive time.*/ + #endif /* ipconfigTCP_KEEP_ALIVE */ + #if ( ipconfigTCP_HANG_PROTECTION == 1 ) + TickType_t xLastActTime; /**< The last time when hang-protection was done.*/ + #endif /* ipconfigTCP_HANG_PROTECTION */ + size_t uxLittleSpace; /**< The value deemed as low amount of space. */ + size_t uxEnoughSpace; /**< The value deemed as enough space. */ + size_t uxRxStreamSize; /**< The Receive stream size */ + size_t uxTxStreamSize; /**< The transmit stream size */ + StreamBuffer_t * rxStream; /**< The pointer to the receive stream buffer. */ + StreamBuffer_t * txStream; /**< The pointer to the transmit stream buffer. */ + #if ( ipconfigUSE_TCP_WIN == 1 ) + NetworkBufferDescriptor_t * pxAckMessage; /**< The pointer to the ACK message */ + #endif /* ipconfigUSE_TCP_WIN */ + LastTCPPacket_t xPacket; /**< Buffer space to store the last TCP header received. */ + uint8_t tcpflags; /**< TCP flags */ + #if ( ipconfigUSE_TCP_WIN != 0 ) + uint8_t ucMyWinScaleFactor; /**< Scaling factor of this device. */ + uint8_t ucPeerWinScaleFactor; /**< Scaling factor of the peer. */ + #endif + #if ( ipconfigUSE_CALLBACKS == 1 ) + FOnTCPReceive_t pxHandleReceive; /**< + * In case of a TCP socket: + * typedef void (* FOnTCPReceive_t) (Socket_t xSocket, void *pData, size_t xLength ); + */ + FOnTCPSent_t pxHandleSent; /**< Function pointer to handle a successful send event. */ + FOnConnected_t pxHandleConnected; /**< Actually type: typedef void (* FOnConnected_t) (Socket_t xSocket, BaseType_t ulConnected ); */ + #endif /* ipconfigUSE_CALLBACKS */ + uint32_t ulWindowSize; /**< Current Window size advertised by peer */ + size_t uxRxWinSize; /**< Fixed value: size of the TCP reception window */ + size_t uxTxWinSize; /**< Fixed value: size of the TCP transmit window */ + + TCPWindow_t xTCPWindow; /**< The TCP window struct*/ + } IPTCPSocket_t; + + #endif /* ipconfigUSE_TCP */ + +/** + * Structure to hold the information about a UDP socket. + */ + typedef struct UDPSOCKET + { + List_t xWaitingPacketsList; /**< Incoming packets */ + #if ( ipconfigUDP_MAX_RX_PACKETS > 0 ) + UBaseType_t uxMaxPackets; /**< Protection: limits the number of packets buffered per socket */ + #endif /* ipconfigUDP_MAX_RX_PACKETS */ + #if ( ipconfigUSE_CALLBACKS == 1 ) + FOnUDPReceive_t pxHandleReceive; /**< + * In case of a UDP socket: + * typedef void (* FOnUDPReceive_t) (Socket_t xSocket, void *pData, size_t xLength, struct freertos_sockaddr *pxAddr ); + */ + FOnUDPSent_t pxHandleSent; /**< Function pointer to handle the events after a successful send. */ + #endif /* ipconfigUSE_CALLBACKS */ + } IPUDPSocket_t; + +/* Formally typedef'd as eSocketEvent_t. */ + enum eSOCKET_EVENT + { + eSOCKET_RECEIVE = 0x0001, + eSOCKET_SEND = 0x0002, + eSOCKET_ACCEPT = 0x0004, + eSOCKET_CONNECT = 0x0008, + eSOCKET_BOUND = 0x0010, + eSOCKET_CLOSED = 0x0020, + eSOCKET_INTR = 0x0040, + eSOCKET_ALL = 0x007F, + }; + + +/** + * Structure to hold information for a socket. + */ + typedef struct xSOCKET + { + EventBits_t xEventBits; /**< The eventbits to keep track of events. */ + EventGroupHandle_t xEventGroup; /**< The event group for this socket. */ + + ListItem_t xBoundSocketListItem; /**< Used to reference the socket from a bound sockets list. */ + TickType_t xReceiveBlockTime; /**< if recv[to] is called while no data is available, wait this amount of time. Unit in clock-ticks */ + TickType_t xSendBlockTime; /**< if send[to] is called while there is not enough space to send, wait this amount of time. Unit in clock-ticks */ + + uint16_t usLocalPort; /**< Local port on this machine */ + uint8_t ucSocketOptions; /**< Socket options */ + uint8_t ucProtocol; /**< choice of FREERTOS_IPPROTO_UDP/TCP */ + #if ( ipconfigSOCKET_HAS_USER_SEMAPHORE == 1 ) + SemaphoreHandle_t pxUserSemaphore; /**< The user semaphore */ + #endif /* ipconfigSOCKET_HAS_USER_SEMAPHORE */ + #if ( ipconfigSOCKET_HAS_USER_WAKE_CALLBACK == 1 ) + SocketWakeupCallback_t pxUserWakeCallback; /**< Pointer to the callback function. */ + #endif /* ipconfigSOCKET_HAS_USER_WAKE_CALLBACK */ + + #if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 ) + struct xSOCKET_SET * pxSocketSet; /**< Pointer to the socket set structure */ + EventBits_t xSelectBits; /**< User may indicate which bits are interesting for this socket. */ + + EventBits_t xSocketBits; /**< These bits indicate the events which have actually occurred. + * They are maintained by the IP-task */ + #endif /* ipconfigSUPPORT_SELECT_FUNCTION */ + /* TCP/UDP specific fields: */ + /* Before accessing any member of this structure, it should be confirmed */ + /* that the protocol corresponds with the type of structure */ + + union + { + IPUDPSocket_t xUDP; /**< Union member: UDP socket*/ + #if ( ipconfigUSE_TCP == 1 ) + IPTCPSocket_t xTCP; /**< Union member: TCP socket */ + + uint64_t ullTCPAlignment; /**< Make sure that xTCP is 8-bytes aligned by + * declaring a 64-bit variable in the same union */ + #endif /* ipconfigUSE_TCP */ + } u; /**< Union of TCP/UDP socket */ + } FreeRTOS_Socket_t; + + static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( FreeRTOS_Socket_t ) + { + return ( FreeRTOS_Socket_t * ) pvArgument; + } + static portINLINE ipDECL_CAST_CONST_PTR_FUNC_FOR_TYPE( FreeRTOS_Socket_t ) + { + return ( const FreeRTOS_Socket_t * ) pvArgument; + } + + #if ( ipconfigUSE_TCP == 1 ) + +/* + * Lookup a TCP socket, using a multiple matching: both port numbers and + * return IP address. + */ + FreeRTOS_Socket_t * pxTCPSocketLookup( uint32_t ulLocalIP, + UBaseType_t uxLocalPort, + uint32_t ulRemoteIP, + UBaseType_t uxRemotePort ); + + #endif /* ipconfigUSE_TCP */ + + +/* + * Look up a local socket by finding a match with the local port. + */ + FreeRTOS_Socket_t * pxUDPSocketLookup( UBaseType_t uxLocalPort ); + +/* + * Called when the application has generated a UDP packet to send. + */ + void vProcessGeneratedUDPPacket( NetworkBufferDescriptor_t * const pxNetworkBuffer ); + +/* + * Calculate the upper-layer checksum + * Works both for UDP, ICMP and TCP packages + * bOut = true: checksum will be set in outgoing packets + * bOut = false: checksum will be calculated for incoming packets + * returning 0xffff means: checksum was correct + */ + uint16_t usGenerateProtocolChecksum( const uint8_t * const pucEthernetBuffer, + size_t uxBufferLength, + BaseType_t xOutgoingPacket ); + +/* + * An Ethernet frame has been updated (maybe it was an ARP request or a PING + * request?) and is to be sent back to its source. + */ + void vReturnEthernetFrame( NetworkBufferDescriptor_t * pxNetworkBuffer, + BaseType_t xReleaseAfterSend ); + +/* + * The internal version of bind() + * If 'ulInternal' is true, it is called by the driver + * The TCP driver needs to bind a socket at the moment a listening socket + * creates a new connected socket + */ + BaseType_t vSocketBind( FreeRTOS_Socket_t * pxSocket, + struct freertos_sockaddr * pxBindAddress, + size_t uxAddressLength, + BaseType_t xInternal ); + +/* + * Internal function to add streaming data to a TCP socket. If ulIn == true, + * data will be added to the rxStream, otherwise to the tXStream. Normally data + * will be written with ulOffset == 0, meaning: at the end of the FIFO. When + * packet come in out-of-order, an offset will be used to put it in front and + * the head will not change yet. + */ + int32_t lTCPAddRxdata( FreeRTOS_Socket_t * pxSocket, + size_t uxOffset, + const uint8_t * pcData, + uint32_t ulByteCount ); + +/* + * Currently called for any important event. + */ + void vSocketWakeUpUser( FreeRTOS_Socket_t * pxSocket ); + +/* + * Some helping function, their meaning should be clear. + * Going by MISRA rules, these utility functions should not be defined + * if they are not being used anywhere. But their use depends on the + * application and hence these functions are defined unconditionally. + */ + static portINLINE uint32_t ulChar2u32( const uint8_t * apChr ); + static portINLINE uint32_t ulChar2u32( const uint8_t * apChr ) + { + return ( ( ( uint32_t ) apChr[ 0 ] ) << 24 ) | + ( ( ( uint32_t ) apChr[ 1 ] ) << 16 ) | + ( ( ( uint32_t ) apChr[ 2 ] ) << 8 ) | + ( ( ( uint32_t ) apChr[ 3 ] ) ); + } + + static portINLINE uint16_t usChar2u16( const uint8_t * apChr ); + static portINLINE uint16_t usChar2u16( const uint8_t * apChr ) + { + return ( uint16_t ) + ( ( ( ( uint32_t ) apChr[ 0 ] ) << 8 ) | + ( ( ( uint32_t ) apChr[ 1 ] ) ) ); + } + +/* Check a single socket for retransmissions and timeouts */ + BaseType_t xTCPSocketCheck( FreeRTOS_Socket_t * pxSocket ); + + BaseType_t xTCPCheckNewClient( FreeRTOS_Socket_t * pxSocket ); + +/* Defined in FreeRTOS_Sockets.c + * Close a socket + */ + void * vSocketClose( FreeRTOS_Socket_t * pxSocket ); + +/* + * Send the event eEvent to the IP task event queue, using a block time of + * zero. Return pdPASS if the message was sent successfully, otherwise return + * pdFALSE. + */ + BaseType_t xSendEventToIPTask( eIPEvent_t eEvent ); + +/* + * The same as above, but a struct as a parameter, containing: + * eIPEvent_t eEventType; + * void *pvData; + */ + BaseType_t xSendEventStructToIPTask( const IPStackEvent_t * pxEvent, + TickType_t uxTimeout ); + +/* + * Returns a pointer to the original NetworkBuffer from a pointer to a UDP + * payload buffer. + */ + NetworkBufferDescriptor_t * pxUDPPayloadBuffer_to_NetworkBuffer( const void * pvBuffer ); + + #if ( ipconfigZERO_COPY_TX_DRIVER != 0 ) + +/* + * For the case where the network driver passes a buffer directly to a DMA + * descriptor, this function can be used to translate a 'network buffer' to + * a 'network buffer descriptor'. + */ + NetworkBufferDescriptor_t * pxPacketBuffer_to_NetworkBuffer( const void * pvBuffer ); + #endif + +/* + * Internal: Sets a new state for a TCP socket and performs the necessary + * actions like calling a OnConnected handler to notify the socket owner. + */ + #if ( ipconfigUSE_TCP == 1 ) + void vTCPStateChange( FreeRTOS_Socket_t * pxSocket, + enum eTCP_STATE eTCPState ); + #endif /* ipconfigUSE_TCP */ + +/* Returns pdTRUE is this function is called from the IP-task */ + BaseType_t xIsCallingFromIPTask( void ); + + #if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 ) + +/** @brief Structure for event groups of the Socket Select functions */ + typedef struct xSOCKET_SET + { + /** @brief Event group for the socket select function. + */ + EventGroupHandle_t xSelectGroup; + } SocketSelect_t; + + static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( SocketSelect_t ) + { + return ( SocketSelect_t * ) pvArgument; + } + static portINLINE ipDECL_CAST_CONST_PTR_FUNC_FOR_TYPE( SocketSelect_t ) + { + return ( const SocketSelect_t * ) pvArgument; + } + + extern void vSocketSelect( SocketSelect_t * pxSocketSet ); + +/** @brief Define the data that must be passed for a 'eSocketSelectEvent'. */ + typedef struct xSocketSelectMessage + { + TaskHandle_t xTaskhandle; /**< Task handle for use in the socket select functionality. */ + SocketSelect_t * pxSocketSet; /**< The event group for the socket select functionality. */ + } SocketSelectMessage_t; + + static portINLINE ipDECL_CAST_PTR_FUNC_FOR_TYPE( SocketSelectMessage_t ) + { + return ( SocketSelectMessage_t * ) pvArgument; + } + static portINLINE ipDECL_CAST_CONST_PTR_FUNC_FOR_TYPE( SocketSelectMessage_t ) + { + return ( const SocketSelectMessage_t * ) pvArgument; + } + + #endif /* ipconfigSUPPORT_SELECT_FUNCTION */ + + void vIPSetDHCPTimerEnableState( BaseType_t xEnableState ); + void vIPReloadDHCPTimer( uint32_t ulLeaseTime ); + #if ( ipconfigDNS_USE_CALLBACKS != 0 ) + void vIPReloadDNSTimer( uint32_t ulCheckTime ); + void vIPSetDnsTimerEnableState( BaseType_t xEnableState ); + #endif + + +/* Send the network-up event and start the ARP timer. */ + void vIPNetworkUpCalls( void ); + + #ifdef __cplusplus + } /* extern "C" */ + #endif + +#endif /* FREERTOS_IP_PRIVATE_H */ diff --git a/examples/stm32/freertos-tcp/include/FreeRTOS_Sockets.h b/examples/stm32/freertos-tcp/include/FreeRTOS_Sockets.h new file mode 100644 index 00000000..ac5218cb --- /dev/null +++ b/examples/stm32/freertos-tcp/include/FreeRTOS_Sockets.h @@ -0,0 +1,520 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +#ifndef FREERTOS_SOCKETS_H + #define FREERTOS_SOCKETS_H + + #ifdef __cplusplus + extern "C" { + #endif + +/* Standard includes. */ + #include + +/* Application level configuration options. */ + #include "FreeRTOSIPConfig.h" + + #ifndef FREERTOS_IP_CONFIG_H + #error FreeRTOSIPConfig.h has not been included yet + #endif + +/* Event bit definitions are required by the select functions. */ + #include "event_groups.h" + + #ifndef INC_FREERTOS_H + #error FreeRTOS.h must be included before FreeRTOS_Sockets.h. + #endif + + #ifndef INC_TASK_H + #ifndef TASK_H /* For compatibility with older FreeRTOS versions. */ + #error The FreeRTOS header file task.h must be included before FreeRTOS_Sockets.h. + #endif + #endif + +/* Assigned to an Socket_t variable when the socket is not valid, probably + * because it could not be created. */ + #define FREERTOS_INVALID_SOCKET ( ( Socket_t ) ~0U ) + +/* API function error values. As errno is supported, the FreeRTOS sockets + * functions return error codes rather than just a pass or fail indication. */ + +/* HT: Extended the number of error codes, gave them positive values and if possible + * the corresponding found in errno.h + * In case of an error, API's will still return negative numbers, e.g. + * return -pdFREERTOS_ERRNO_EWOULDBLOCK; + * in case an operation would block */ + +/* The following defines are obsolete, please use -pdFREERTOS_ERRNO_Exxx */ + + #define FREERTOS_SOCKET_ERROR ( -1 ) + #define FREERTOS_EWOULDBLOCK ( -pdFREERTOS_ERRNO_EWOULDBLOCK ) + #define FREERTOS_EINVAL ( -pdFREERTOS_ERRNO_EINVAL ) + #define FREERTOS_EADDRNOTAVAIL ( -pdFREERTOS_ERRNO_EADDRNOTAVAIL ) + #define FREERTOS_EADDRINUSE ( -pdFREERTOS_ERRNO_EADDRINUSE ) + #define FREERTOS_ENOBUFS ( -pdFREERTOS_ERRNO_ENOBUFS ) + #define FREERTOS_ENOPROTOOPT ( -pdFREERTOS_ERRNO_ENOPROTOOPT ) + #define FREERTOS_ECLOSED ( -pdFREERTOS_ERRNO_ENOTCONN ) + +/* Values for the parameters to FreeRTOS_socket(), inline with the Berkeley + * standard. See the documentation of FreeRTOS_socket() for more information. */ + #define FREERTOS_AF_INET ( 2 ) + #define FREERTOS_AF_INET6 ( 10 ) + #define FREERTOS_SOCK_DGRAM ( 2 ) + #define FREERTOS_IPPROTO_UDP ( 17 ) + + #define FREERTOS_SOCK_STREAM ( 1 ) + #define FREERTOS_IPPROTO_TCP ( 6 ) + +/* IP packet of type "Any local network" + * can be used in stead of TCP for testing with sockets in raw mode + */ + #define FREERTOS_IPPROTO_USR_LAN ( 63 ) + +/* A bit value that can be passed into the FreeRTOS_sendto() function as part of + * the flags parameter. Setting the FREERTOS_ZERO_COPY in the flags parameter + * indicates that the zero copy interface is being used. See the documentation for + * FreeRTOS_sockets() for more information. */ + #define FREERTOS_ZERO_COPY ( 1 ) + +/* Values that can be passed in the option name parameter of calls to + * FreeRTOS_setsockopt(). */ + #define FREERTOS_SO_RCVTIMEO ( 0 ) /* Used to set the receive time out. */ + #define FREERTOS_SO_SNDTIMEO ( 1 ) /* Used to set the send time out. */ + #define FREERTOS_SO_UDPCKSUM_OUT ( 2 ) /* Used to turn the use of the UDP checksum by a socket on or off. This also doubles as part of an 8-bit bitwise socket option. */ + #if ( ipconfigSOCKET_HAS_USER_SEMAPHORE == 1 ) + #define FREERTOS_SO_SET_SEMAPHORE ( 3 ) /* Used to set a user's semaphore */ + #endif + #define FREERTOS_SO_SNDBUF ( 4 ) /* Set the size of the send buffer (TCP only) */ + #define FREERTOS_SO_RCVBUF ( 5 ) /* Set the size of the receive buffer (TCP only) */ + + #if ipconfigUSE_CALLBACKS == 1 + #define FREERTOS_SO_TCP_CONN_HANDLER ( 6 ) /* Install a callback for (dis) connection events. Supply pointer to 'F_TCP_UDP_Handler_t' (see below) */ + #define FREERTOS_SO_TCP_RECV_HANDLER ( 7 ) /* Install a callback for receiving TCP data. Supply pointer to 'F_TCP_UDP_Handler_t' (see below) */ + #define FREERTOS_SO_TCP_SENT_HANDLER ( 8 ) /* Install a callback for sending TCP data. Supply pointer to 'F_TCP_UDP_Handler_t' (see below) */ + #define FREERTOS_SO_UDP_RECV_HANDLER ( 9 ) /* Install a callback for receiving UDP data. Supply pointer to 'F_TCP_UDP_Handler_t' (see below) */ + #define FREERTOS_SO_UDP_SENT_HANDLER ( 10 ) /* Install a callback for sending UDP data. Supply pointer to 'F_TCP_UDP_Handler_t' (see below) */ + #endif /* ipconfigUSE_CALLBACKS */ + + #define FREERTOS_SO_REUSE_LISTEN_SOCKET ( 11 ) /* When a listening socket gets connected, do not create a new one but re-use it */ + #define FREERTOS_SO_CLOSE_AFTER_SEND ( 12 ) /* As soon as the last byte has been transmitted, finalise the connection */ + #define FREERTOS_SO_WIN_PROPERTIES ( 13 ) /* Set all buffer and window properties in one call, parameter is pointer to WinProperties_t */ + #define FREERTOS_SO_SET_FULL_SIZE ( 14 ) /* Refuse to send packets smaller than MSS */ + + #define FREERTOS_SO_STOP_RX ( 15 ) /* Temporarily hold up reception, used by streaming client */ + + #if ( ipconfigUDP_MAX_RX_PACKETS > 0 ) + #define FREERTOS_SO_UDP_MAX_RX_PACKETS ( 16 ) /* This option helps to limit the maximum number of packets a UDP socket will buffer */ + #endif + + #if ( ipconfigSOCKET_HAS_USER_WAKE_CALLBACK == 1 ) + #define FREERTOS_SO_WAKEUP_CALLBACK ( 17 ) + #endif + + #define FREERTOS_SO_SET_LOW_HIGH_WATER ( 18 ) + + #define FREERTOS_NOT_LAST_IN_FRAGMENTED_PACKET ( 0x80 ) /* For internal use only, but also part of an 8-bit bitwise value. */ + #define FREERTOS_FRAGMENTED_PACKET ( 0x40 ) /* For internal use only, but also part of an 8-bit bitwise value. */ + +/* Values for flag for FreeRTOS_shutdown(). */ + #define FREERTOS_SHUT_RD ( 0 ) /* Not really at this moment, just for compatibility of the interface */ + #define FREERTOS_SHUT_WR ( 1 ) + #define FREERTOS_SHUT_RDWR ( 2 ) + +/* Values for flag for FreeRTOS_recv(). */ + #define FREERTOS_MSG_OOB ( 2 ) /* process out-of-band data */ + #define FREERTOS_MSG_PEEK ( 4 ) /* peek at incoming message */ + #define FREERTOS_MSG_DONTROUTE ( 8 ) /* send without using routing tables */ + #define FREERTOS_MSG_DONTWAIT ( 16 ) /* Can be used with recvfrom(), sendto(), recv(), and send(). */ + + +/** + * Structure to hold the properties of Tx/Rx buffers and windows. + */ + typedef struct xWIN_PROPS + { + /* Properties of the Tx buffer and Tx window */ + int32_t lTxBufSize; /**< Unit: bytes */ + int32_t lTxWinSize; /**< Unit: MSS */ + + /* Properties of the Rx buffer and Rx window */ + int32_t lRxBufSize; /**< Unit: bytes */ + int32_t lRxWinSize; /**< Unit: MSS */ + } WinProperties_t; + +/** + * Structure to pass for the 'FREERTOS_SO_SET_LOW_HIGH_WATER' option + */ + typedef struct xLOW_HIGH_WATER + { + size_t uxLittleSpace; /**< Send a STOP when buffer space drops below X bytes */ + size_t uxEnoughSpace; /**< Send a GO when buffer space grows above X bytes */ + } LowHighWater_t; + +/* For compatibility with the expected Berkeley sockets naming. */ + #define socklen_t uint32_t + +/** + * For this limited implementation, only two members are required in the + * Berkeley style sockaddr structure. + */ + struct freertos_sockaddr + { + /* _HT_ On 32- and 64-bit architectures, the addition of the two uint8_t + * fields doesn't make the structure bigger, due to alignment. + * The fields are inserted as a preparation for IPv6. */ + + /* sin_len and sin_family not used in the IPv4-only release. */ + uint8_t sin_len; /**< length of this structure. */ + uint8_t sin_family; /**< FREERTOS_AF_INET. */ + uint16_t sin_port; /**< The port */ + uint32_t sin_addr; /**< The IP address */ + }; + + + extern const char * FreeRTOS_inet_ntoa( uint32_t ulIPAddress, + char * pcBuffer ); + + #if ipconfigBYTE_ORDER == pdFREERTOS_LITTLE_ENDIAN + + #define FreeRTOS_inet_addr_quick( ucOctet0, ucOctet1, ucOctet2, ucOctet3 ) \ + ( ( ( ( uint32_t ) ( ucOctet3 ) ) << 24UL ) | \ + ( ( ( uint32_t ) ( ucOctet2 ) ) << 16UL ) | \ + ( ( ( uint32_t ) ( ucOctet1 ) ) << 8UL ) | \ + ( ( uint32_t ) ( ucOctet0 ) ) ) + + #else /* ipconfigBYTE_ORDER */ + + #define FreeRTOS_inet_addr_quick( ucOctet0, ucOctet1, ucOctet2, ucOctet3 ) \ + ( ( ( ( uint32_t ) ( ucOctet0 ) ) << 24UL ) | \ + ( ( ( uint32_t ) ( ucOctet1 ) ) << 16UL ) | \ + ( ( ( uint32_t ) ( ucOctet2 ) ) << 8UL ) | \ + ( ( uint32_t ) ( ucOctet3 ) ) ) + + #endif /* ipconfigBYTE_ORDER */ + +/* The socket type itself. */ + struct xSOCKET; + typedef struct xSOCKET * Socket_t; + typedef struct xSOCKET const * ConstSocket_t; + + static portINLINE BaseType_t xSocketValid( Socket_t xSocket ) + { + BaseType_t xReturnValue = pdFALSE; + + /* + * There are two values which can indicate an invalid socket: + * FREERTOS_INVALID_SOCKET and NULL. In order to compare against + * both values, the code cannot be compliant with rule 11.4, + * hence the Coverity suppression statement below. + */ + /* coverity[misra_c_2012_rule_11_4_violation] */ + if( ( xSocket != FREERTOS_INVALID_SOCKET ) && ( xSocket != NULL ) ) + { + xReturnValue = pdTRUE; + } + + return xReturnValue; + } + + #if ( ipconfigSUPPORT_SELECT_FUNCTION == 1 ) + +/* The SocketSet_t type is the equivalent to the fd_set type used by the + * Berkeley API. */ + struct xSOCKET_SET; + typedef struct xSOCKET_SET * SocketSet_t; + #endif /* ( ipconfigSUPPORT_SELECT_FUNCTION == 1 ) */ + +/** + * FULL, UP-TO-DATE AND MAINTAINED REFERENCE DOCUMENTATION FOR ALL THESE + * FUNCTIONS IS AVAILABLE ON THE FOLLOWING URL: + * http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/FreeRTOS_TCP_API_Functions.html + */ + Socket_t FreeRTOS_socket( BaseType_t xDomain, + BaseType_t xType, + BaseType_t xProtocol ); + int32_t FreeRTOS_recvfrom( Socket_t xSocket, + void * pvBuffer, + size_t uxBufferLength, + BaseType_t xFlags, + struct freertos_sockaddr * pxSourceAddress, + socklen_t * pxSourceAddressLength ); + int32_t FreeRTOS_sendto( Socket_t xSocket, + const void * pvBuffer, + size_t uxTotalDataLength, + BaseType_t xFlags, + const struct freertos_sockaddr * pxDestinationAddress, + socklen_t xDestinationAddressLength ); + BaseType_t FreeRTOS_bind( Socket_t xSocket, + struct freertos_sockaddr const * pxAddress, + socklen_t xAddressLength ); + +/* function to get the local address and IP port */ + size_t FreeRTOS_GetLocalAddress( ConstSocket_t xSocket, + struct freertos_sockaddr * pxAddress ); + + #if ( ipconfigETHERNET_DRIVER_FILTERS_PACKETS == 1 ) + /* Returns true if an UDP socket exists bound to mentioned port number. */ + BaseType_t xPortHasUDPSocket( uint16_t usPortNr ); + #endif + + #if ipconfigUSE_TCP == 1 + + BaseType_t FreeRTOS_connect( Socket_t xClientSocket, + struct freertos_sockaddr * pxAddress, + socklen_t xAddressLength ); + BaseType_t FreeRTOS_listen( Socket_t xSocket, + BaseType_t xBacklog ); + BaseType_t FreeRTOS_recv( Socket_t xSocket, + void * pvBuffer, + size_t uxBufferLength, + BaseType_t xFlags ); + BaseType_t FreeRTOS_send( Socket_t xSocket, + const void * pvBuffer, + size_t uxDataLength, + BaseType_t xFlags ); + Socket_t FreeRTOS_accept( Socket_t xServerSocket, + struct freertos_sockaddr * pxAddress, + socklen_t * pxAddressLength ); + BaseType_t FreeRTOS_shutdown( Socket_t xSocket, + BaseType_t xHow ); + + #if ( ipconfigSUPPORT_SIGNALS != 0 ) + /* Send a signal to the task which is waiting for a given socket. */ + BaseType_t FreeRTOS_SignalSocket( Socket_t xSocket ); + +/* Send a signal to the task which reads from this socket (FromISR + * version). */ + BaseType_t FreeRTOS_SignalSocketFromISR( Socket_t xSocket, + BaseType_t * pxHigherPriorityTaskWoken ); + #endif /* ipconfigSUPPORT_SIGNALS */ + +/* Return the remote address and IP port. */ + BaseType_t FreeRTOS_GetRemoteAddress( ConstSocket_t xSocket, + struct freertos_sockaddr * pxAddress ); + + #if ( ipconfigUSE_TCP == 1 ) + +/* Returns pdTRUE if TCP socket is connected. */ + BaseType_t FreeRTOS_issocketconnected( ConstSocket_t xSocket ); + +/* Returns the actual size of MSS being used. */ + BaseType_t FreeRTOS_mss( ConstSocket_t xSocket ); + + #endif /* ( ipconfigUSE_TCP == 1 ) */ + +/* For internal use only: return the connection status. */ + BaseType_t FreeRTOS_connstatus( ConstSocket_t xSocket ); + +/* Returns the number of bytes that may be added to txStream */ + BaseType_t FreeRTOS_maywrite( ConstSocket_t xSocket ); + +/* + * Two helper functions, mostly for testing + * rx_size returns the number of bytes available in the Rx buffer + * tx_space returns the free space in the Tx buffer + */ + #if ( ipconfigUSE_TCP == 1 ) + BaseType_t FreeRTOS_rx_size( ConstSocket_t xSocket ); + BaseType_t FreeRTOS_tx_space( ConstSocket_t xSocket ); + BaseType_t FreeRTOS_tx_size( ConstSocket_t xSocket ); + #endif + +/* Returns the number of outstanding bytes in txStream. */ + +/* The function FreeRTOS_outstanding() was already implemented + * FreeRTOS_tx_size(). */ + #define FreeRTOS_outstanding( xSocket ) FreeRTOS_tx_size( xSocket ) + +/* Returns the number of bytes in the socket's rxStream. */ + +/* The function FreeRTOS_recvcount() was already implemented + * FreeRTOS_rx_size(). */ + #define FreeRTOS_recvcount( xSocket ) FreeRTOS_rx_size( xSocket ) + +/* + * For advanced applications only: + * Get a direct pointer to the circular transmit buffer. + * '*pxLength' will contain the number of bytes that may be written. + */ + uint8_t * FreeRTOS_get_tx_head( ConstSocket_t xSocket, + BaseType_t * pxLength ); + + #endif /* ipconfigUSE_TCP */ + + #if ( ipconfigUSE_CALLBACKS != 0 ) + +/* + * Connect / disconnect handler for a TCP socket + * For example: + * static void vMyConnectHandler (Socket_t xSocket, BaseType_t ulConnected) + * { + * } + * F_TCP_UDP_Handler_t xHnd = { vMyConnectHandler }; + * FreeRTOS_setsockopt( sock, 0, FREERTOS_SO_TCP_CONN_HANDLER, ( void * ) &xHnd, sizeof( xHnd ) ); + */ + + #ifdef __COVERITY__ + typedef void (* FOnConnected_t )( Socket_t xSocket, + BaseType_t ulConnected ); + #else + typedef void (* FOnConnected_t )( Socket_t, + BaseType_t ); + #endif + +/* + * Reception handler for a TCP socket + * A user-proved function will be called on reception of a message + * If the handler returns a positive number, the messages will not be stored + * For example: + * static BaseType_t xOnTCPReceive( Socket_t xSocket, void * pData, size_t uxLength ) + * { + * // handle the message + * return 1; + * } + * F_TCP_UDP_Handler_t xHand = { xOnTCPReceive }; + * FreeRTOS_setsockopt( sock, 0, FREERTOS_SO_TCP_RECV_HANDLER, ( void * ) &xHand, sizeof( xHand ) ); + */ + #ifdef __COVERITY__ + typedef BaseType_t (* FOnTCPReceive_t )( Socket_t xSocket, + void * pData, + size_t xLength ); + typedef void (* FOnTCPSent_t )( Socket_t xSocket, + size_t xLength ); + #else + typedef BaseType_t (* FOnTCPReceive_t )( Socket_t, + void *, + size_t ); + typedef void (* FOnTCPSent_t )( Socket_t, + size_t ); + #endif /* ifdef __COVERITY__ */ + +/* + * Reception handler for a UDP socket + * A user-proved function will be called on reception of a message + * If the handler returns a positive number, the messages will not be stored + */ + #ifdef __COVERITY__ + typedef BaseType_t (* FOnUDPReceive_t ) ( Socket_t xSocket, + void * pData, + size_t xLength, + const struct freertos_sockaddr * pxFrom, + const struct freertos_sockaddr * pxDest ); + typedef void (* FOnUDPSent_t )( Socket_t xSocket, + size_t xLength ); + #else + typedef BaseType_t (* FOnUDPReceive_t ) ( Socket_t, + void *, + size_t, + const struct freertos_sockaddr *, + const struct freertos_sockaddr * ); + typedef void (* FOnUDPSent_t )( Socket_t, + size_t ); + #endif /* ifdef __COVERITY__ */ + + typedef union xTCP_UDP_HANDLER + { + FOnConnected_t pxOnTCPConnected; /* FREERTOS_SO_TCP_CONN_HANDLER */ + FOnTCPReceive_t pxOnTCPReceive; /* FREERTOS_SO_TCP_RECV_HANDLER */ + FOnTCPSent_t pxOnTCPSent; /* FREERTOS_SO_TCP_SENT_HANDLER */ + FOnUDPReceive_t pxOnUDPReceive; /* FREERTOS_SO_UDP_RECV_HANDLER */ + FOnUDPSent_t pxOnUDPSent; /* FREERTOS_SO_UDP_SENT_HANDLER */ + } F_TCP_UDP_Handler_t; + #endif /* ( ipconfigUSE_CALLBACKS != 0 ) */ + + BaseType_t FreeRTOS_setsockopt( Socket_t xSocket, + int32_t lLevel, + int32_t lOptionName, + const void * pvOptionValue, + size_t uxOptionLength ); + BaseType_t FreeRTOS_closesocket( Socket_t xSocket ); + +/* The following function header should be placed in FreeRTOS_DNS.h. + * It is kept here because some applications expect it in FreeRTOS_Sockets.h.*/ + #ifndef __COVERITY__ + uint32_t FreeRTOS_gethostbyname( const char * pcHostName ); + #endif + + BaseType_t FreeRTOS_inet_pton( BaseType_t xAddressFamily, + const char * pcSource, + void * pvDestination ); + const char * FreeRTOS_inet_ntop( BaseType_t xAddressFamily, + const void * pvSource, + char * pcDestination, + socklen_t uxSize ); + +/* Convert a null-terminated string in dot-decimal-notation (d.d.d.d) to a 32-bit unsigned integer. */ + uint32_t FreeRTOS_inet_addr( const char * pcIPAddress ); + + BaseType_t FreeRTOS_inet_pton4( const char * pcSource, + void * pvDestination ); + const char * FreeRTOS_inet_ntop4( const void * pvSource, + char * pcDestination, + socklen_t uxSize ); + + +/* + * For the web server: borrow the circular Rx buffer for inspection + * HTML driver wants to see if a sequence of 13/10/13/10 is available + */ + const struct xSTREAM_BUFFER * FreeRTOS_get_rx_buf( ConstSocket_t xSocket ); + + void FreeRTOS_netstat( void ); + + #if ipconfigSUPPORT_SELECT_FUNCTION == 1 + +/* For FD_SET and FD_CLR, a combination of the following bits can be used: */ + + typedef enum eSELECT_EVENT + { + eSELECT_READ = 0x0001, + eSELECT_WRITE = 0x0002, + eSELECT_EXCEPT = 0x0004, + eSELECT_INTR = 0x0008, + eSELECT_ALL = 0x000F, + /* Reserved for internal use: */ + eSELECT_CALL_IP = 0x0010, + /* end */ + } eSelectEvent_t; + + SocketSet_t FreeRTOS_CreateSocketSet( void ); + void FreeRTOS_DeleteSocketSet( SocketSet_t xSocketSet ); + void FreeRTOS_FD_SET( Socket_t xSocket, + SocketSet_t xSocketSet, + EventBits_t xBitsToSet ); + void FreeRTOS_FD_CLR( Socket_t xSocket, + SocketSet_t xSocketSet, + EventBits_t xBitsToClear ); + EventBits_t FreeRTOS_FD_ISSET( Socket_t xSocket, + SocketSet_t xSocketSet ); + BaseType_t FreeRTOS_select( SocketSet_t xSocketSet, + TickType_t xBlockTimeTicks ); + + #endif /* ipconfigSUPPORT_SELECT_FUNCTION */ + + #ifdef __cplusplus + } /* extern "C" */ + #endif + +#endif /* FREERTOS_SOCKETS_H */ diff --git a/examples/stm32/freertos-tcp/include/FreeRTOS_Stream_Buffer.h b/examples/stm32/freertos-tcp/include/FreeRTOS_Stream_Buffer.h new file mode 100644 index 00000000..c2f814b3 --- /dev/null +++ b/examples/stm32/freertos-tcp/include/FreeRTOS_Stream_Buffer.h @@ -0,0 +1,266 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +/* + * FreeRTOS_Stream_Buffer.h + * + * A circular character buffer + * An implementation of a circular buffer without a length field + * If LENGTH defines the size of the buffer, a maximum of (LENGTH-1) bytes can be stored + * In order to add or read data from the buffer, memcpy() will be called at most 2 times + */ + +#ifndef FREERTOS_STREAM_BUFFER_H + + #define FREERTOS_STREAM_BUFFER_H + + #ifdef __cplusplus + extern "C" { + #endif + +/** + * structure to store all the details of a stream buffer. + */ + typedef struct xSTREAM_BUFFER + { + volatile size_t uxTail; /**< next item to read */ + volatile size_t uxMid; /**< iterator within the valid items */ + volatile size_t uxHead; /**< next position store a new item */ + volatile size_t uxFront; /**< iterator within the free space */ + size_t LENGTH; /**< const value: number of reserved elements */ + uint8_t ucArray[ sizeof( size_t ) ]; /**< array big enough to store any pointer address */ + } StreamBuffer_t; + + static portINLINE void vStreamBufferClear( StreamBuffer_t * pxBuffer ); + static portINLINE void vStreamBufferClear( StreamBuffer_t * pxBuffer ) + { + /* Make the circular buffer empty */ + pxBuffer->uxHead = 0U; + pxBuffer->uxTail = 0U; + pxBuffer->uxFront = 0U; + pxBuffer->uxMid = 0U; + } + +/*-----------------------------------------------------------*/ + + static portINLINE size_t uxStreamBufferSpace( const StreamBuffer_t * pxBuffer, + const size_t uxLower, + const size_t uxUpper ); + static portINLINE size_t uxStreamBufferSpace( const StreamBuffer_t * pxBuffer, + const size_t uxLower, + const size_t uxUpper ) + { +/* Returns the space between uxLower and uxUpper, which equals to the distance minus 1 */ + size_t uxCount; + + uxCount = pxBuffer->LENGTH + uxUpper - uxLower - 1U; + + if( uxCount >= pxBuffer->LENGTH ) + { + uxCount -= pxBuffer->LENGTH; + } + + return uxCount; + } +/*-----------------------------------------------------------*/ + + static portINLINE size_t uxStreamBufferDistance( const StreamBuffer_t * pxBuffer, + const size_t uxLower, + const size_t uxUpper ); + static portINLINE size_t uxStreamBufferDistance( const StreamBuffer_t * pxBuffer, + const size_t uxLower, + const size_t uxUpper ) + { +/* Returns the distance between uxLower and uxUpper */ + size_t uxCount; + + uxCount = pxBuffer->LENGTH + uxUpper - uxLower; + + if( uxCount >= pxBuffer->LENGTH ) + { + uxCount -= pxBuffer->LENGTH; + } + + return uxCount; + } +/*-----------------------------------------------------------*/ + + static portINLINE size_t uxStreamBufferGetSpace( const StreamBuffer_t * pxBuffer ); + static portINLINE size_t uxStreamBufferGetSpace( const StreamBuffer_t * pxBuffer ) + { +/* Returns the number of items which can still be added to uxHead + * before hitting on uxTail */ + size_t uxHead = pxBuffer->uxHead; + size_t uxTail = pxBuffer->uxTail; + + return uxStreamBufferSpace( pxBuffer, uxHead, uxTail ); + } +/*-----------------------------------------------------------*/ + + static portINLINE size_t uxStreamBufferFrontSpace( const StreamBuffer_t * pxBuffer ); + static portINLINE size_t uxStreamBufferFrontSpace( const StreamBuffer_t * pxBuffer ) + { +/* Distance between uxFront and uxTail + * or the number of items which can still be added to uxFront, + * before hitting on uxTail */ + + size_t uxFront = pxBuffer->uxFront; + size_t uxTail = pxBuffer->uxTail; + + return uxStreamBufferSpace( pxBuffer, uxFront, uxTail ); + } +/*-----------------------------------------------------------*/ + + static portINLINE size_t uxStreamBufferGetSize( const StreamBuffer_t * pxBuffer ); + static portINLINE size_t uxStreamBufferGetSize( const StreamBuffer_t * pxBuffer ) + { +/* Returns the number of items which can be read from uxTail + * before reaching uxHead */ + size_t uxHead = pxBuffer->uxHead; + size_t uxTail = pxBuffer->uxTail; + + return uxStreamBufferDistance( pxBuffer, uxTail, uxHead ); + } +/*-----------------------------------------------------------*/ + + static portINLINE size_t uxStreamBufferMidSpace( const StreamBuffer_t * pxBuffer ); + static portINLINE size_t uxStreamBufferMidSpace( const StreamBuffer_t * pxBuffer ) + { +/* Returns the distance between uxHead and uxMid */ + size_t uxHead = pxBuffer->uxHead; + size_t uxMid = pxBuffer->uxMid; + + return uxStreamBufferDistance( pxBuffer, uxMid, uxHead ); + } +/*-----------------------------------------------------------*/ + + static portINLINE void vStreamBufferMoveMid( StreamBuffer_t * pxBuffer, + size_t uxCount ); + static portINLINE void vStreamBufferMoveMid( StreamBuffer_t * pxBuffer, + size_t uxCount ) + { +/* Increment uxMid, but no further than uxHead */ + size_t uxSize = uxStreamBufferMidSpace( pxBuffer ); + size_t uxMoveCount = uxCount; + + if( uxMoveCount > uxSize ) + { + uxMoveCount = uxSize; + } + + pxBuffer->uxMid += uxMoveCount; + + if( pxBuffer->uxMid >= pxBuffer->LENGTH ) + { + pxBuffer->uxMid -= pxBuffer->LENGTH; + } + } +/*-----------------------------------------------------------*/ + + static portINLINE BaseType_t xStreamBufferLessThenEqual( const StreamBuffer_t * pxBuffer, + const size_t uxLeft, + const size_t uxRight ); + static portINLINE BaseType_t xStreamBufferLessThenEqual( const StreamBuffer_t * pxBuffer, + const size_t uxLeft, + const size_t uxRight ) + { + BaseType_t xReturn; + size_t uxTail = pxBuffer->uxTail; + + /* Returns true if ( uxLeft < uxRight ) */ + if( ( ( ( uxLeft < uxTail ) ? 1U : 0U ) ^ ( ( uxRight < uxTail ) ? 1U : 0U ) ) != 0U ) + { + if( uxRight < uxTail ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + else + { + if( uxLeft <= uxRight ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + + return xReturn; + } +/*-----------------------------------------------------------*/ + + static portINLINE size_t uxStreamBufferGetPtr( StreamBuffer_t * pxBuffer, + uint8_t ** ppucData ); + static portINLINE size_t uxStreamBufferGetPtr( StreamBuffer_t * pxBuffer, + uint8_t ** ppucData ) + { + size_t uxNextTail = pxBuffer->uxTail; + size_t uxSize = uxStreamBufferGetSize( pxBuffer ); + + *ppucData = pxBuffer->ucArray + uxNextTail; + + return FreeRTOS_min_uint32( uxSize, pxBuffer->LENGTH - uxNextTail ); + } + +/* + * Add bytes to a stream buffer. + * + * pxBuffer - The buffer to which the bytes will be added. + * uxOffset - If uxOffset > 0, data will be written at an offset from uxHead + * while uxHead will not be moved yet. + * pucData - A pointer to the data to be added. + * uxCount - The number of bytes to add. + */ + size_t uxStreamBufferAdd( StreamBuffer_t * pxBuffer, + size_t uxOffset, + const uint8_t * pucData, + size_t uxByteCount ); + +/* + * Read bytes from a stream buffer. + * + * pxBuffer - The buffer from which the bytes will be read. + * uxOffset - Can be used to read data located at a certain offset from 'uxTail'. + * pucData - A pointer to the buffer into which data will be read. + * uxMaxCount - The number of bytes to read. + * xPeek - If set to pdTRUE the data will remain in the buffer. + */ + size_t uxStreamBufferGet( StreamBuffer_t * pxBuffer, + size_t uxOffset, + uint8_t * pucData, + size_t uxMaxCount, + BaseType_t xPeek ); + + #ifdef __cplusplus + } /* extern "C" */ + #endif + +#endif /* !defined( FREERTOS_STREAM_BUFFER_H ) */ diff --git a/examples/stm32/freertos-tcp/include/FreeRTOS_TCP_IP.h b/examples/stm32/freertos-tcp/include/FreeRTOS_TCP_IP.h new file mode 100644 index 00000000..d730c056 --- /dev/null +++ b/examples/stm32/freertos-tcp/include/FreeRTOS_TCP_IP.h @@ -0,0 +1,68 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +#ifndef FREERTOS_TCP_IP_H + #define FREERTOS_TCP_IP_H + + #ifdef __cplusplus + extern "C" { + #endif + + BaseType_t xProcessReceivedTCPPacket( NetworkBufferDescriptor_t * pxDescriptor ); + + typedef enum eTCP_STATE + { + /* Comments about the TCP states are borrowed from the very useful + * Wiki page: + * http://en.wikipedia.org/wiki/Transmission_Control_Protocol */ + eCLOSED = 0U, /* 0 (server + client) no connection state at all. */ + eTCP_LISTEN, /* 1 (server) waiting for a connection request + * from any remote TCP and port. */ + eCONNECT_SYN, /* 2 (client) internal state: socket wants to send + * a connect */ + eSYN_FIRST, /* 3 (server) Just created, must ACK the SYN request. */ + eSYN_RECEIVED, /* 4 (server) waiting for a confirming connection request + * acknowledgement after having both received and sent a connection request. */ + eESTABLISHED, /* 5 (server + client) an open connection, data received can be + * delivered to the user. The normal state for the data transfer phase of the connection. */ + eFIN_WAIT_1, /* 6 (server + client) waiting for a connection termination request from the remote TCP, + * or an acknowledgement of the connection termination request previously sent. */ + eFIN_WAIT_2, /* 7 (server + client) waiting for a connection termination request from the remote TCP. */ + eCLOSE_WAIT, /* 8 (server + client) waiting for a connection termination request from the local user. */ + eCLOSING, /* 9 (server + client) waiting for a connection termination request acknowledgement from the remote TCP. */ + eLAST_ACK, /*10 (server + client) waiting for an acknowledgement of the connection termination request + * previously sent to the remote TCP + * (which includes an acknowledgement of its connection termination request). */ + eTIME_WAIT, /*11 (either server or client) waiting for enough time to pass to be sure the remote TCP received the + * acknowledgement of its connection termination request. [According to RFC 793 a connection can + * stay in TIME-WAIT for a maximum of four minutes known as a MSL (maximum segment lifetime).] */ + } eIPTCPState_t; + + + #ifdef __cplusplus + } /* extern "C" */ + #endif + +#endif /* FREERTOS_TCP_IP_H */ diff --git a/examples/stm32/freertos-tcp/include/FreeRTOS_TCP_WIN.h b/examples/stm32/freertos-tcp/include/FreeRTOS_TCP_WIN.h new file mode 100644 index 00000000..00f154e8 --- /dev/null +++ b/examples/stm32/freertos-tcp/include/FreeRTOS_TCP_WIN.h @@ -0,0 +1,237 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +/* + * FreeRTOS_TCP_WIN.c + * Module which handles the TCP windowing schemes for FreeRTOS-PLUS-TCP + */ + +#ifndef FREERTOS_TCP_WIN_H + #define FREERTOS_TCP_WIN_H + + #ifdef __cplusplus + extern "C" { + #endif + +/** + * The name xTCPTimer was already use as the name of an IP-timer. + */ + typedef struct xTCPTimerStruct + { + uint32_t ulBorn; /**< The time when this timer is created. */ + } TCPTimer_t; + +/** + * Structure to hold the information about a TCP segment. + */ + typedef struct xTCP_SEGMENT + { + uint32_t ulSequenceNumber; /**< The sequence number of the first byte in this packet */ + int32_t lMaxLength; /**< Maximum space, number of bytes which can be stored in this segment */ + int32_t lDataLength; /**< Actual number of bytes */ + int32_t lStreamPos; /**< reference to the [t|r]xStream of the socket */ + TCPTimer_t xTransmitTimer; /**< saves a timestamp at the moment this segment gets transmitted (TX only) */ + union + { + struct + { + uint32_t + ucTransmitCount : 8, /**< Number of times the segment has been transmitted, used to calculate the RTT */ + ucDupAckCount : 8, /**< Counts the number of times that a higher segment was ACK'd. After 3 times a Fast Retransmission takes place */ + bOutstanding : 1, /**< It the peer's turn, we're just waiting for an ACK */ + bAcked : 1, /**< This segment has been acknowledged */ + bIsForRx : 1; /**< pdTRUE if segment is used for reception */ + } bits; + uint32_t ulFlags; + } u; /**< Use a union to store the 32-bit flag field and the breakdown in the same location. */ + #if ( ipconfigUSE_TCP_WIN != 0 ) + struct xLIST_ITEM xQueueItem; /**< TX only: segments can be linked in one of three queues: xPriorityQueue, xTxQueue, and xWaitQueue */ + struct xLIST_ITEM xSegmentItem; /**< With this item the segment can be connected to a list, depending on who is owning it */ + #endif + } TCPSegment_t; + +/** + * Structure to store the Rx/Tx window length. + */ + typedef struct xTCP_WINSIZE + { + uint32_t ulRxWindowLength; /**< The size of the receive window. */ + uint32_t ulTxWindowLength; /**< The size of the send window. */ + } TCPWinSize_t; + + +/* + * If TCP time-stamps are being used, they will occupy 12 bytes in + * each packet, and thus the message space will become smaller + */ +/* Keep this as a multiple of 4 */ + #if ( ipconfigUSE_TCP_WIN == 1 ) + #define ipSIZE_TCP_OPTIONS 16U + #else + #define ipSIZE_TCP_OPTIONS 12U + #endif + +/** + * Every TCP connection owns a TCP window for the administration of all packets + * It owns two sets of segment descriptors, incoming and outgoing + */ + typedef struct xTCP_WINDOW + { + union + { + struct + { + uint32_t + bHasInit : 1, /**< The window structure has been initialised */ + bSendFullSize : 1, /**< May only send packets with a size equal to MSS (for optimisation) */ + bTimeStamps : 1; /**< Socket is supposed to use TCP time-stamps. This depends on the */ + } bits; /**< party which opens the connection */ + uint32_t ulFlags; + } u; /**< Use a union to store the 32-bit flag field and the breakdown at the same place. */ + TCPWinSize_t xSize; /**< Size of the TCP window. */ + struct + { + uint32_t ulFirstSequenceNumber; /**< Logging & debug: the first segment received/sent in this connection + * for Tx: initial send sequence number (ISS) + * for Rx: initial receive sequence number (IRS) */ + uint32_t ulCurrentSequenceNumber; /**< Tx/Rx: the oldest sequence number not yet confirmed, also SND.UNA / RCV.NXT + * In other words: the sequence number of the left side of the sliding window */ + uint32_t ulFINSequenceNumber; /**< The sequence number which carried the FIN flag */ + uint32_t ulHighestSequenceNumber; /**< Sequence number of the right-most byte + 1 */ + } rx, /**< Structure for the receiver for TCP. */ + tx; /**< Structure for the transmitter for TCP. */ + + uint32_t ulOurSequenceNumber; /**< The SEQ number we're sending out */ + uint32_t ulUserDataLength; /**< Number of bytes in Rx buffer which may be passed to the user, after having received a 'missing packet' */ + uint32_t ulNextTxSequenceNumber; /**< The sequence number given to the next byte to be added for transmission */ + int32_t lSRTT; /**< Smoothed Round Trip Time, it may increment quickly and it decrements slower */ + uint8_t ucOptionLength; /**< Number of valid bytes in ulOptionsData[] */ + #if ( ipconfigUSE_TCP_WIN == 1 ) + List_t xPriorityQueue; /**< Priority queue: segments which must be sent immediately */ + List_t xTxQueue; /**< Transmit queue: segments queued for transmission */ + List_t xWaitQueue; /**< Waiting queue: outstanding segments */ + TCPSegment_t * pxHeadSegment; /**< points to a segment which has not been transmitted and it's size is still growing (user data being added) */ + uint32_t ulOptionsData[ ipSIZE_TCP_OPTIONS / sizeof( uint32_t ) ]; /**< Contains the options we send out */ + List_t xTxSegments; /**< A linked list of all transmission segments, sorted on sequence number */ + List_t xRxSegments; /**< A linked list of reception segments, order depends on sequence of arrival */ + #else + /* For tiny TCP, there is only 1 outstanding TX segment */ + TCPSegment_t xTxSegment; /**< Priority queue */ + #endif + uint16_t usOurPortNumber; /**< Mostly for debugging/logging: our TCP port number */ + uint16_t usPeerPortNumber; /**< debugging/logging: the peer's TCP port number */ + uint16_t usMSS; /**< Current accepted MSS */ + uint16_t usMSSInit; /**< MSS as configured by the socket owner */ + } TCPWindow_t; + + + +/*============================================================================= + * + * Creation and destruction + * + *=============================================================================*/ + +/* Create and initialize a window */ + void vTCPWindowCreate( TCPWindow_t * pxWindow, + uint32_t ulRxWindowLength, + uint32_t ulTxWindowLength, + uint32_t ulAckNumber, + uint32_t ulSequenceNumber, + uint32_t ulMSS ); + +/* Destroy a window (always returns NULL) + * It will free some resources: a collection of segments */ + void vTCPWindowDestroy( TCPWindow_t const * pxWindow ); + +/* Initialize a window */ + void vTCPWindowInit( TCPWindow_t * pxWindow, + uint32_t ulAckNumber, + uint32_t ulSequenceNumber, + uint32_t ulMSS ); + +/* Clean up allocated segments. Should only be called when FreeRTOS+TCP will no longer be used. */ + void vTCPSegmentCleanup( void ); + +/*============================================================================= + * + * Rx functions + * + *=============================================================================*/ + +/* if true may be passed directly to user (segment expected and window is empty) + * But pxWindow->ackno should always be used to set "BUF->ackno" */ + int32_t lTCPWindowRxCheck( TCPWindow_t * pxWindow, + uint32_t ulSequenceNumber, + uint32_t ulLength, + uint32_t ulSpace ); + +/* This function will be called as soon as a FIN is received. It will return true + * if there are no 'open' reception segments */ + BaseType_t xTCPWindowRxEmpty( const TCPWindow_t * pxWindow ); + +/*============================================================================= + * + * Tx functions + * + *=============================================================================*/ + +/* Adds data to the Tx-window */ + int32_t lTCPWindowTxAdd( TCPWindow_t * pxWindow, + uint32_t ulLength, + int32_t lPosition, + int32_t lMax ); + +/* Check data to be sent and calculate the time period we may sleep */ + BaseType_t xTCPWindowTxHasData( TCPWindow_t const * pxWindow, + uint32_t ulWindowSize, + TickType_t * pulDelay ); + +/* See if anything is left to be sent + * Function will be called when a FIN has been received. Only when the TX window is clean, + * it will return pdTRUE */ + BaseType_t xTCPWindowTxDone( const TCPWindow_t * pxWindow ); + +/* Fetches data to be sent. + * plPosition will point to a location with the circular data buffer: txStream */ + uint32_t ulTCPWindowTxGet( TCPWindow_t * pxWindow, + uint32_t ulWindowSize, + int32_t * plPosition ); + +/* Receive a normal ACK */ + uint32_t ulTCPWindowTxAck( TCPWindow_t * pxWindow, + uint32_t ulSequenceNumber ); + +/* Receive a SACK option */ + uint32_t ulTCPWindowTxSack( TCPWindow_t * pxWindow, + uint32_t ulFirst, + uint32_t ulLast ); + + + #ifdef __cplusplus + } /* extern "C" */ + #endif + +#endif /* FREERTOS_TCP_WIN_H */ diff --git a/examples/stm32/freertos-tcp/include/FreeRTOS_UDP_IP.h b/examples/stm32/freertos-tcp/include/FreeRTOS_UDP_IP.h new file mode 100644 index 00000000..787ec7ad --- /dev/null +++ b/examples/stm32/freertos-tcp/include/FreeRTOS_UDP_IP.h @@ -0,0 +1,43 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +#ifndef FREERTOS_UDP_IP_H + #define FREERTOS_UDP_IP_H + + #ifdef __cplusplus + extern "C" { + #endif + +/* Application level configuration options. */ + #include "FreeRTOSIPConfig.h" + #include "FreeRTOSIPConfigDefaults.h" + #include "IPTraceMacroDefaults.h" + + + #ifdef __cplusplus + } /* extern "C" */ + #endif + +#endif /* FREERTOS_UDP_IP_H */ diff --git a/examples/stm32/freertos-tcp/include/FreeRTOS_errno_TCP.h b/examples/stm32/freertos-tcp/include/FreeRTOS_errno_TCP.h new file mode 100644 index 00000000..e3fbfea0 --- /dev/null +++ b/examples/stm32/freertos-tcp/include/FreeRTOS_errno_TCP.h @@ -0,0 +1,96 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +#ifndef FREERTOS_ERRNO_TCP +#define FREERTOS_ERRNO_TCP + +/* The following definitions will be included in the core FreeRTOS code in + * future versions of FreeRTOS - hence the 'pd' (ProjDefs) prefix - at which time + * this file will be removed. */ + +/* The following errno values are used by FreeRTOS+ components, not FreeRTOS + * itself. */ + +/* For future compatibility (see comment above), check the definitions have not + * already been made. */ +#ifndef pdFREERTOS_ERRNO_NONE + #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_EAFNOSUPPORT 97 /* Address family not supported by protocol */ + #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 +#else /* ifndef pdFREERTOS_ERRNO_NONE */ + #ifndef pdFREERTOS_ERRNO_EAFNOSUPPORT + #define pdFREERTOS_ERRNO_EAFNOSUPPORT 97 /* Address family not supported by protocol */ + #endif /* pdFREERTOS_ERRNO_EAFNOSUPPORT */ +#endif /* pdFREERTOS_ERRNO_NONE */ + +/* Translate a pdFREERTOS_ERRNO code to a human readable string. */ +const char * FreeRTOS_strerror_r( BaseType_t xErrnum, + char * pcBuffer, + size_t uxLength ); + +#endif /* FREERTOS_ERRNO_TCP */ diff --git a/examples/stm32/freertos-tcp/include/IPTraceMacroDefaults.h b/examples/stm32/freertos-tcp/include/IPTraceMacroDefaults.h new file mode 100644 index 00000000..27f149de --- /dev/null +++ b/examples/stm32/freertos-tcp/include/IPTraceMacroDefaults.h @@ -0,0 +1,243 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +/* This file provides default (empty) implementations for any IP trace macros + * that are not defined by the user. See + * http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/TCP_IP_Trace.html */ + +#ifndef UDP_TRACE_MACRO_DEFAULTS_H +#define UDP_TRACE_MACRO_DEFAULTS_H + +#ifndef iptraceNETWORK_DOWN + #define iptraceNETWORK_DOWN() +#endif + +#ifndef iptraceNETWORK_BUFFER_RELEASED + #define iptraceNETWORK_BUFFER_RELEASED( pxBufferAddress ) +#endif + +#ifndef iptraceNETWORK_BUFFER_OBTAINED + #define iptraceNETWORK_BUFFER_OBTAINED( pxBufferAddress ) +#endif + +#ifndef iptraceNETWORK_BUFFER_OBTAINED_FROM_ISR + #define iptraceNETWORK_BUFFER_OBTAINED_FROM_ISR( pxBufferAddress ) +#endif + +#ifndef iptraceNETWORK_INTERFACE_INPUT + /* An Ethernet packet has been received. */ + #define iptraceNETWORK_INTERFACE_INPUT( uxDataLength, pucEthernetBuffer ) +#endif + +#ifndef iptraceNETWORK_INTERFACE_OUTPUT + /* An Ethernet packet will be sent. */ + #define iptraceNETWORK_INTERFACE_OUTPUT( uxDataLength, pucEthernetBuffer ) +#endif + +#ifndef iptraceFAILED_TO_OBTAIN_NETWORK_BUFFER + #define iptraceFAILED_TO_OBTAIN_NETWORK_BUFFER() +#endif + +#ifndef iptraceFAILED_TO_OBTAIN_NETWORK_BUFFER_FROM_ISR + #define iptraceFAILED_TO_OBTAIN_NETWORK_BUFFER_FROM_ISR() +#endif + +#ifndef iptraceCREATING_ARP_REQUEST + #define iptraceCREATING_ARP_REQUEST( ulIPAddress ) +#endif + +#ifndef iptraceARP_TABLE_ENTRY_WILL_EXPIRE + #define iptraceARP_TABLE_ENTRY_WILL_EXPIRE( ulIPAddress ) +#endif + +#ifndef iptraceARP_TABLE_ENTRY_EXPIRED + #define iptraceARP_TABLE_ENTRY_EXPIRED( ulIPAddress ) +#endif + +#ifndef iptraceARP_TABLE_ENTRY_CREATED + #define iptraceARP_TABLE_ENTRY_CREATED( ulIPAddress, ucMACAddress ) +#endif + +#ifndef iptraceSENDING_UDP_PACKET + #define iptraceSENDING_UDP_PACKET( ulIPAddress ) +#endif + +#ifndef iptracePACKET_DROPPED_TO_GENERATE_ARP + #define iptracePACKET_DROPPED_TO_GENERATE_ARP( ulIPAddress ) +#endif + +#ifndef iptraceICMP_PACKET_RECEIVED + #define iptraceICMP_PACKET_RECEIVED() +#endif + +#ifndef iptraceSENDING_PING_REPLY + #define iptraceSENDING_PING_REPLY( ulIPAddress ) +#endif + +#ifndef traceARP_PACKET_RECEIVED + #define traceARP_PACKET_RECEIVED() +#endif + +#ifndef iptracePROCESSING_RECEIVED_ARP_REPLY + #define iptracePROCESSING_RECEIVED_ARP_REPLY( ulIPAddress ) +#endif + +#ifndef iptraceSENDING_ARP_REPLY + #define iptraceSENDING_ARP_REPLY( ulIPAddress ) +#endif + +#ifndef iptraceFAILED_TO_CREATE_SOCKET + #define iptraceFAILED_TO_CREATE_SOCKET() +#endif + +#ifndef iptraceFAILED_TO_CREATE_EVENT_GROUP + #define iptraceFAILED_TO_CREATE_EVENT_GROUP() +#endif + +#ifndef iptraceRECVFROM_DISCARDING_BYTES + #define iptraceRECVFROM_DISCARDING_BYTES( xNumberOfBytesDiscarded ) +#endif + +#ifndef iptraceETHERNET_RX_EVENT_LOST + #define iptraceETHERNET_RX_EVENT_LOST() +#endif + +#ifndef iptraceSTACK_TX_EVENT_LOST + #define iptraceSTACK_TX_EVENT_LOST( xEvent ) +#endif + +#ifndef iptraceNETWORK_EVENT_RECEIVED + #define iptraceNETWORK_EVENT_RECEIVED( eEvent ) +#endif + +#ifndef iptraceBIND_FAILED + #define iptraceBIND_FAILED( xSocket, usPort ) +#endif + +#ifndef iptraceDHCP_REQUESTS_FAILED_USING_DEFAULT_IP_ADDRESS + #define iptraceDHCP_REQUESTS_FAILED_USING_DEFAULT_IP_ADDRESS( ulIPAddress ) +#endif + +#ifndef iptraceSENDING_DHCP_DISCOVER + #define iptraceSENDING_DHCP_DISCOVER() +#endif + +#ifndef iptraceSENDING_DHCP_REQUEST + #define iptraceSENDING_DHCP_REQUEST() +#endif + +#ifndef iptraceDHCP_SUCCEDEED + #define iptraceDHCP_SUCCEDEED( address ) +#endif + +#ifndef iptraceNETWORK_INTERFACE_TRANSMIT + #define iptraceNETWORK_INTERFACE_TRANSMIT() +#endif + +#ifndef iptraceNETWORK_INTERFACE_RECEIVE + #define iptraceNETWORK_INTERFACE_RECEIVE() +#endif + +#ifndef iptraceSENDING_DNS_REQUEST + #define iptraceSENDING_DNS_REQUEST() +#endif + +#ifndef iptraceWAITING_FOR_TX_DMA_DESCRIPTOR + #define iptraceWAITING_FOR_TX_DMA_DESCRIPTOR() +#endif + +#ifndef ipconfigINCLUDE_EXAMPLE_FREERTOS_PLUS_TRACE_CALLS + #define ipconfigINCLUDE_EXAMPLE_FREERTOS_PLUS_TRACE_CALLS 0 +#endif + +#ifndef iptraceFAILED_TO_NOTIFY_SELECT_GROUP + #define iptraceFAILED_TO_NOTIFY_SELECT_GROUP( xSocket ) +#endif + +#ifndef pvPortMallocSocket + #define pvPortMallocSocket( xSize ) pvPortMalloc( ( xSize ) ) +#endif + +#ifndef iptraceRECVFROM_TIMEOUT + #define iptraceRECVFROM_TIMEOUT() +#endif + +#ifndef iptraceRECVFROM_INTERRUPTED + #define iptraceRECVFROM_INTERRUPTED() +#endif + +#ifndef iptraceNO_BUFFER_FOR_SENDTO + #define iptraceNO_BUFFER_FOR_SENDTO() +#endif + +#ifndef iptraceSENDTO_SOCKET_NOT_BOUND + #define iptraceSENDTO_SOCKET_NOT_BOUND() +#endif + +#ifndef iptraceSENDTO_DATA_TOO_LONG + #define iptraceSENDTO_DATA_TOO_LONG() +#endif + +#ifndef ipconfigUSE_TCP_MEM_STATS + #define ipconfigUSE_TCP_MEM_STATS 0 +#endif + +#if ( ipconfigUSE_TCP_MEM_STATS == 0 ) + +/* See tools/tcp_mem_stat.c */ + + #ifndef iptraceMEM_STATS_CREATE + #define iptraceMEM_STATS_CREATE( xMemType, pxObject, uxSize ) + #endif + + #ifndef iptraceMEM_STATS_DELETE + #define iptraceMEM_STATS_DELETE( pxObject ) + #endif + + #ifndef iptraceMEM_STATS_CLOSE + #define iptraceMEM_STATS_CLOSE() + #endif + +#endif /* ( ipconfigUSE_TCP_MEM_STATS != 0 ) */ + +#ifndef ipconfigUSE_DUMP_PACKETS + #define ipconfigUSE_DUMP_PACKETS 0 +#endif + +#if ( ipconfigUSE_DUMP_PACKETS == 0 ) + +/* See tools/tcp_dump_packets.c */ + + #ifndef iptraceDUMP_INIT + #define iptraceDUMP_INIT( pcFileName, pxEntries ) + #endif + + #ifndef iptraceDUMP_PACKET + #define iptraceDUMP_PACKET( pucBuffer, uxLength, xIncoming ) + #endif + +#endif /* ( ipconfigUSE_DUMP_PACKETS != 0 ) */ + +#endif /* UDP_TRACE_MACRO_DEFAULTS_H */ diff --git a/examples/stm32/freertos-tcp/include/NetworkBufferManagement.h b/examples/stm32/freertos-tcp/include/NetworkBufferManagement.h new file mode 100644 index 00000000..aa3d7da5 --- /dev/null +++ b/examples/stm32/freertos-tcp/include/NetworkBufferManagement.h @@ -0,0 +1,76 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +#ifndef NETWORK_BUFFER_MANAGEMENT_H + #define NETWORK_BUFFER_MANAGEMENT_H + + #ifdef __cplusplus + extern "C" { + #endif + +/* NOTE PUBLIC API FUNCTIONS. */ + BaseType_t xNetworkBuffersInitialise( void ); + NetworkBufferDescriptor_t * pxGetNetworkBufferWithDescriptor( size_t xRequestedSizeBytes, + TickType_t xBlockTimeTicks ); + +/* The definition of the below function is only available if BufferAllocation_2.c has been linked into the source. */ + NetworkBufferDescriptor_t * pxNetworkBufferGetFromISR( size_t xRequestedSizeBytes ); + void vReleaseNetworkBufferAndDescriptor( NetworkBufferDescriptor_t * const pxNetworkBuffer ); + +/* The definition of the below function is only available if BufferAllocation_2.c has been linked into the source. */ + BaseType_t vNetworkBufferReleaseFromISR( NetworkBufferDescriptor_t * const pxNetworkBuffer ); + uint8_t * pucGetNetworkBuffer( size_t * pxRequestedSizeBytes ); + void vReleaseNetworkBuffer( uint8_t * pucEthernetBuffer ); + +/* Get the current number of free network buffers. */ + UBaseType_t uxGetNumberOfFreeNetworkBuffers( void ); + +/* Get the lowest number of free network buffers. */ + UBaseType_t uxGetMinimumFreeNetworkBuffers( void ); + +/* Copy a network buffer into a bigger buffer. */ + NetworkBufferDescriptor_t * pxDuplicateNetworkBufferWithDescriptor( const NetworkBufferDescriptor_t * const pxNetworkBuffer, + size_t uxNewLength ); + +/* Increase the size of a Network Buffer. + * In case BufferAllocation_2.c is used, the new space must be allocated. */ + NetworkBufferDescriptor_t * pxResizeNetworkBufferWithDescriptor( NetworkBufferDescriptor_t * pxNetworkBuffer, + size_t xNewSizeBytes ); + + #if ipconfigTCP_IP_SANITY + +/* + * Check if an address is a valid pointer to a network descriptor + * by looking it up in the array of network descriptors + */ + UBaseType_t bIsValidNetworkDescriptor( const NetworkBufferDescriptor_t * pxDesc ); + BaseType_t prvIsFreeBuffer( const NetworkBufferDescriptor_t * pxDescr ); + #endif + + #ifdef __cplusplus + } /* extern "C" */ + #endif + +#endif /* NETWORK_BUFFER_MANAGEMENT_H */ diff --git a/examples/stm32/freertos-tcp/include/NetworkInterface.h b/examples/stm32/freertos-tcp/include/NetworkInterface.h new file mode 100644 index 00000000..520577ed --- /dev/null +++ b/examples/stm32/freertos-tcp/include/NetworkInterface.h @@ -0,0 +1,48 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +#ifndef NETWORK_INTERFACE_H + #define NETWORK_INTERFACE_H + + #ifdef __cplusplus + extern "C" { + #endif + +/* INTERNAL API FUNCTIONS. */ + BaseType_t xNetworkInterfaceInitialise( void ); + BaseType_t xNetworkInterfaceOutput( NetworkBufferDescriptor_t * const pxNetworkBuffer, + BaseType_t xReleaseAfterSend ); + +/* The following function is defined only when BufferAllocation_1.c is linked in the project. */ + void vNetworkInterfaceAllocateRAMToBuffers( NetworkBufferDescriptor_t pxNetworkBuffers[ ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS ] ); + +/* The following function is defined only when BufferAllocation_1.c is linked in the project. */ + BaseType_t xGetPhyLinkStatus( void ); + + #ifdef __cplusplus + } /* extern "C" */ + #endif + +#endif /* NETWORK_INTERFACE_H */ diff --git a/examples/stm32/freertos-tcp/portable/Compiler/CompilerName/ReadMe.txt b/examples/stm32/freertos-tcp/portable/Compiler/CompilerName/ReadMe.txt new file mode 100644 index 00000000..04a632a9 --- /dev/null +++ b/examples/stm32/freertos-tcp/portable/Compiler/CompilerName/ReadMe.txt @@ -0,0 +1,3 @@ +Update pack_struct_start.h and pack_struct_end.h for your architecure. +These files define the specifiers needed by your compiler to properly pack struct data +need by FreeRTOS+TCP. diff --git a/examples/stm32/freertos-tcp/portable/Compiler/CompilerName/pack_struct_end.h b/examples/stm32/freertos-tcp/portable/Compiler/CompilerName/pack_struct_end.h new file mode 100644 index 00000000..d80be34b --- /dev/null +++ b/examples/stm32/freertos-tcp/portable/Compiler/CompilerName/pack_struct_end.h @@ -0,0 +1,32 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +/***************************************************************************** +* +* See the following URL for an explanation of this file: +* http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/Embedded_Compiler_Porting.html +* +*****************************************************************************/ +; /* FIX ME. Update for the compiler specifier needed at end of a struct declaration to pack the struct. */ diff --git a/examples/stm32/freertos-tcp/portable/Compiler/CompilerName/pack_struct_start.h b/examples/stm32/freertos-tcp/portable/Compiler/CompilerName/pack_struct_start.h new file mode 100644 index 00000000..2ba45066 --- /dev/null +++ b/examples/stm32/freertos-tcp/portable/Compiler/CompilerName/pack_struct_start.h @@ -0,0 +1,32 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +/***************************************************************************** +* +* See the following URL for an explanation of this file: +* http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/Embedded_Compiler_Porting.html +* +*****************************************************************************/ +/* FIX ME. Update for the compiler specifier needed at the start of a struct declaration to pack the struct. */ diff --git a/examples/stm32/freertos-tcp/portable/Compiler/GCC/pack_struct_end.h b/examples/stm32/freertos-tcp/portable/Compiler/GCC/pack_struct_end.h new file mode 100644 index 00000000..da06ad43 --- /dev/null +++ b/examples/stm32/freertos-tcp/portable/Compiler/GCC/pack_struct_end.h @@ -0,0 +1,32 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +/***************************************************************************** +* +* See the following URL for an explanation of this file: +* http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/Embedded_Compiler_Porting.html +* +*****************************************************************************/ +__attribute__( ( packed ) ); diff --git a/examples/stm32/freertos-tcp/portable/Compiler/GCC/pack_struct_start.h b/examples/stm32/freertos-tcp/portable/Compiler/GCC/pack_struct_start.h new file mode 100644 index 00000000..9b71fcb3 --- /dev/null +++ b/examples/stm32/freertos-tcp/portable/Compiler/GCC/pack_struct_start.h @@ -0,0 +1,33 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +/***************************************************************************** +* +* See the following URL for an explanation of this file: +* http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/Embedded_Compiler_Porting.html +* +*****************************************************************************/ + +/* Nothing to do here. */ diff --git a/examples/stm32/freertos-tcp/portable/Compiler/IAR/pack_struct_end.h b/examples/stm32/freertos-tcp/portable/Compiler/IAR/pack_struct_end.h new file mode 100644 index 00000000..e8af1df3 --- /dev/null +++ b/examples/stm32/freertos-tcp/portable/Compiler/IAR/pack_struct_end.h @@ -0,0 +1,33 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +/***************************************************************************** +* +* See the following URL for an explanation of this file: +* http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/Embedded_Compiler_Porting.html +* +*****************************************************************************/ + +; diff --git a/examples/stm32/freertos-tcp/portable/Compiler/IAR/pack_struct_start.h b/examples/stm32/freertos-tcp/portable/Compiler/IAR/pack_struct_start.h new file mode 100644 index 00000000..71f2be62 --- /dev/null +++ b/examples/stm32/freertos-tcp/portable/Compiler/IAR/pack_struct_start.h @@ -0,0 +1,33 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +/***************************************************************************** +* +* See the following URL for an explanation of this file: +* http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/Embedded_Compiler_Porting.html +* +*****************************************************************************/ + +__packed diff --git a/examples/stm32/freertos-tcp/portable/Compiler/Keil/pack_struct_end.h b/examples/stm32/freertos-tcp/portable/Compiler/Keil/pack_struct_end.h new file mode 100644 index 00000000..74e7e088 --- /dev/null +++ b/examples/stm32/freertos-tcp/portable/Compiler/Keil/pack_struct_end.h @@ -0,0 +1,33 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +/***************************************************************************** +* +* See the following URL for an explanation of this file: +* http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/Embedded_Compiler_Porting.html +* +*****************************************************************************/ +; +#pragma pack(pop) diff --git a/examples/stm32/freertos-tcp/portable/Compiler/Keil/pack_struct_start.h b/examples/stm32/freertos-tcp/portable/Compiler/Keil/pack_struct_start.h new file mode 100644 index 00000000..259631e1 --- /dev/null +++ b/examples/stm32/freertos-tcp/portable/Compiler/Keil/pack_struct_start.h @@ -0,0 +1,33 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +/***************************************************************************** +* +* See the following URL for an explanation of this file: +* http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/Embedded_Compiler_Porting.html +* +*****************************************************************************/ + +#pragma pack(push,1) diff --git a/examples/stm32/freertos-tcp/portable/Compiler/MSVC/pack_struct_end.h b/examples/stm32/freertos-tcp/portable/Compiler/MSVC/pack_struct_end.h new file mode 100644 index 00000000..a9da30a0 --- /dev/null +++ b/examples/stm32/freertos-tcp/portable/Compiler/MSVC/pack_struct_end.h @@ -0,0 +1,34 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +/***************************************************************************** +* +* See the following URL for an explanation of this file: +* http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/Embedded_Compiler_Porting.html +* +*****************************************************************************/ + +; +#pragma pack( pop ) diff --git a/examples/stm32/freertos-tcp/portable/Compiler/MSVC/pack_struct_start.h b/examples/stm32/freertos-tcp/portable/Compiler/MSVC/pack_struct_start.h new file mode 100644 index 00000000..b485de6b --- /dev/null +++ b/examples/stm32/freertos-tcp/portable/Compiler/MSVC/pack_struct_start.h @@ -0,0 +1,33 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +/***************************************************************************** +* +* See the following URL for an explanation of this file: +* http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/Embedded_Compiler_Porting.html +* +*****************************************************************************/ + +#pragma pack( push, 1 ) diff --git a/examples/stm32/freertos-tcp/portable/Compiler/Renesas/pack_struct_end.h b/examples/stm32/freertos-tcp/portable/Compiler/Renesas/pack_struct_end.h new file mode 100644 index 00000000..52b1a67d --- /dev/null +++ b/examples/stm32/freertos-tcp/portable/Compiler/Renesas/pack_struct_end.h @@ -0,0 +1,45 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +/***************************************************************************** +* +* See the following URL for an explanation of this file: +* http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/Embedded_Compiler_Porting.html +* +*****************************************************************************/ + + +#ifdef _SH + #ifdef __RENESAS__ + ; + #pragma unpack + #endif +#endif +#ifdef __RX + #ifdef __CCRX__ + ; + #pragma packoption + #endif +#endif diff --git a/examples/stm32/freertos-tcp/portable/Compiler/Renesas/pack_struct_start.h b/examples/stm32/freertos-tcp/portable/Compiler/Renesas/pack_struct_start.h new file mode 100644 index 00000000..63ea6fb6 --- /dev/null +++ b/examples/stm32/freertos-tcp/portable/Compiler/Renesas/pack_struct_start.h @@ -0,0 +1,43 @@ +/* + * FreeRTOS+TCP V2.3.2 + * 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://aws.amazon.com/freertos + * http://www.FreeRTOS.org + */ + +/***************************************************************************** +* +* See the following URL for an explanation of this file: +* http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/Embedded_Compiler_Porting.html +* +*****************************************************************************/ + + +#ifdef _SH + #ifdef __RENESAS__ + #pragma pack 1 + #endif +#endif +#ifdef __RX + #ifdef __CCRX__ + #pragma pack + #endif +#endif diff --git a/examples/stm32/main.c b/examples/stm32/main.c new file mode 100644 index 00000000..897370d4 --- /dev/null +++ b/examples/stm32/main.c @@ -0,0 +1,47 @@ +// Copyright (c) 2021 Cesanta Software Limited +// All rights reserved + +#include "device.h" +#include "mongoose.h" + +// static const char *s_debug_level = "2"; +// static const char *s_listening_address = "http://0.0.0.0:80"; + +// Event handler for the listening connection. +// static void cb(struct mg_connection *c, int ev, void *ev_data, void *fn_data) +// { +// if (ev == MG_EV_HTTP_MSG) { +// mg_http_reply(c, 200, "", "hello, %s!\n", "world"); +// } +// (void) fn_data; +// (void) ev_data; +// } + +static void fn(void *args) { + // struct mg_mgr mgr; + // struct mg_connection *c; + + // mg_log_set(s_debug_level); + // mg_mgr_init(&mgr); + // if ((c = mg_http_listen(&mgr, s_listening_address, cb, &mgr)) == NULL) { + // LOG(LL_ERROR, ("Cannot listen on %s. Use http://ADDR:PORT or :PORT", + // s_listening_address)); + // } + // LOG(LL_INFO, ("Starting Mongoose v%s", MG_VERSION)); + // for (;;) mg_mgr_poll(&mgr, 1000); + // mg_mgr_free(&mgr); + // int delay_ms = *(int *) args; + for (;;) { + led_toggle(); + vTaskDelay(pdMS_TO_TICKS(300)); + }; + (void) args; +} + +int main(void) { + init_ram(); + init_hardware(); + xTaskCreate(fn, "server", 512, NULL, configMAX_PRIORITIES - 1, NULL); + vTaskStartScheduler(); + return 0; +} diff --git a/examples/stm32/stm32f1/FreeRTOSConfig.h b/examples/stm32/stm32f1/FreeRTOSConfig.h new file mode 100644 index 00000000..fce3b1a3 --- /dev/null +++ b/examples/stm32/stm32f1/FreeRTOSConfig.h @@ -0,0 +1,94 @@ +#pragma once + +#define configUSE_PREEMPTION 1 +#define configUSE_PORT_OPTIMISED_TASK_SELECTION 0 +#define configUSE_TICKLESS_IDLE 0 +#define configCPU_CLOCK_HZ ((unsigned long) 72000000) +#define configSYSTICK_CLOCK_HZ (configCPU_CLOCK_HZ / 8) +#define configTICK_RATE_HZ 250 +#define configMAX_PRIORITIES 5 +#define configMINIMAL_STACK_SIZE 128 +#define configMAX_TASK_NAME_LEN 16 +#define configUSE_16_BIT_TICKS 0 +#define configIDLE_SHOULD_YIELD 1 +#define configUSE_TASK_NOTIFICATIONS 0 +#define configUSE_MUTEXES 0 +#define configUSE_RECURSIVE_MUTEXES 0 +#define configUSE_COUNTING_SEMAPHORES 0 +#define configQUEUE_REGISTRY_SIZE 10 +#define configUSE_QUEUE_SETS 0 +#define configUSE_TIME_SLICING 0 +#define configUSE_NEWLIB_REENTRANT 0 +#define configENABLE_BACKWARD_COMPATIBILITY 0 +#define configNUM_THREAD_LOCAL_STORAGE_POINTERS 5 + +/* Memory allocation related definitions. */ +#define configSUPPORT_STATIC_ALLOCATION 0 +#define configSUPPORT_DYNAMIC_ALLOCATION 1 +#define configTOTAL_HEAP_SIZE ((size_t)(8 * 1024)) +#define configAPPLICATION_ALLOCATED_HEAP 0 + +/* Hook function related definitions. */ +#define configUSE_IDLE_HOOK 0 +#define configUSE_TICK_HOOK 0 +#define configCHECK_FOR_STACK_OVERFLOW 0 +#define configUSE_MALLOC_FAILED_HOOK 0 +#define configUSE_DAEMON_TASK_STARTUP_HOOK 0 + +/* Run time and task stats gathering related definitions. */ +#define configGENERATE_RUN_TIME_STATS 0 +#define configUSE_TRACE_FACILITY 0 +#define configUSE_STATS_FORMATTING_FUNCTIONS 0 + +/* Co-routine related definitions. */ +#define configUSE_CO_ROUTINES 0 +#define configMAX_CO_ROUTINE_PRIORITIES 1 + +/* Software timer related definitions. */ +#define configUSE_TIMERS 0 +#define configTIMER_TASK_PRIORITY 3 +#define configTIMER_QUEUE_LENGTH 10 +#define configTIMER_TASK_STACK_DEPTH configMINIMAL_STACK_SIZE + +/* Interrupt nesting behaviour configuration. */ +/* Cortex-M specific definitions. */ +#ifdef __NVIC_PRIO_BITS +#define configPRIO_BITS __NVIC_PRIO_BITS +#else +#define configPRIO_BITS 4 +#endif +#define configLIBRARY_LOWEST_INTERRUPT_PRIORITY 15 +#define configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY 5 +#define configKERNEL_INTERRUPT_PRIORITY \ + (configLIBRARY_LOWEST_INTERRUPT_PRIORITY << (8 - configPRIO_BITS)) +/* !!!! configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to zero !!!! +See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html. */ +#define configMAX_SYSCALL_INTERRUPT_PRIORITY \ + (configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 - configPRIO_BITS)) + +/* FreeRTOS MPU specific definitions. */ +#define configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS 0 + +/* Optional functions - most linkers will remove unused functions anyway. */ +#define INCLUDE_vTaskPrioritySet 0 +#define INCLUDE_uxTaskPriorityGet 0 +#define INCLUDE_vTaskDelete 0 +#define INCLUDE_vTaskSuspend 0 +#define INCLUDE_xResumeFromISR 0 +#define INCLUDE_vTaskDelayUntil 0 +#define INCLUDE_vTaskDelay 1 +#define INCLUDE_xTaskGetSchedulerState 0 +#define INCLUDE_xTaskGetCurrentTaskHandle 0 +#define INCLUDE_uxTaskGetStackHighWaterMark 0 +#define INCLUDE_xTaskGetIdleTaskHandle 0 +#define INCLUDE_eTaskGetState 0 +#define INCLUDE_xEventGroupSetBitFromISR 0 +#define INCLUDE_xTimerPendFunctionCall 0 +#define INCLUDE_xTaskAbortDelay 0 +#define INCLUDE_xTaskGetHandle 0 +#define INCLUDE_xTaskResumeFromISR 0 + +/* Redirect FreeRTOS port interrupts. */ +#define vPortSVCHandler SVC_handler +#define xPortPendSVHandler pending_SV_handler +#define xPortSysTickHandler SysTick_handler \ No newline at end of file diff --git a/examples/stm32/stm32f1/boot.s b/examples/stm32/stm32f1/boot.s new file mode 100644 index 00000000..4956c315 --- /dev/null +++ b/examples/stm32/stm32f1/boot.s @@ -0,0 +1,32 @@ +.cpu cortex-m0 +.thumb + +.word _estack /* stack top address */ +.word _reset /* 1 Reset */ +.word spin /* 2 NMI */ +.word spin /* 3 Hard Fault */ +.word spin /* 4 MM Fault */ +.word spin /* 5 Bus Fault */ +.word spin /* 6 Usage Fault */ +.word spin /* 7 RESERVED */ +.word spin /* 8 RESERVED */ +.word spin /* 9 RESERVED*/ +.word spin /* 10 RESERVED */ +.word spin /* 11 SV call */ +.word spin /* 12 Debug reserved */ +.word spin /* 13 RESERVED */ +.word spin /* 14 PendSV */ +.word spin /* 15 SysTick */ +.word spin /* 16 IRQ0 */ +.word spin /* 17 IRQ1 */ +.word spin /* 18 IRQ2 */ +.word spin /* 19 ... */ + /* On to IRQ67 */ + +spin: b spin + +.thumb_func +.global _reset +_reset: + bl main + b . diff --git a/examples/stm32/stm32f1/device.h b/examples/stm32/stm32f1/device.h new file mode 100644 index 00000000..87599f67 --- /dev/null +++ b/examples/stm32/stm32f1/device.h @@ -0,0 +1,67 @@ +// Copyright (c) 2018-2021 Cesanta Software Limited +// All rights reserved +// +// TRM: https://www.st.com/resource/en/reference_manual/cd00171190.pdf + +#include +#include + +#define LED_PIN 13 // PC13 +#define TX_PIN 9 // PA9 +#define RX_PIN 10 // PA10 +#define BIT(x) ((uint32_t) 1 << (x)) + +// RCC registers, TRM section 7.3 +struct rcc { + volatile uint32_t CR, CFGR, CIR, APB2RSTR, APB1RSTR, AHBENR; + volatile uint32_t APB2ENR, APB1ENR, BDCR, CSR; +}; +#define RCC ((struct rcc *) 0x40021000) + +// GPIO registers, TRM section 9.2 +struct gpio { + volatile uint32_t CRL, CRH, IDR, ODR, BSRR, BRR, LCKR; +}; +#define GPIOA ((struct gpio *) 0x40010800) +#define GPIOB ((struct gpio *) 0x4001c000) +#define GPIOC ((struct gpio *) 0x40011000) +// enum { MODE_INPUT = 0, MODE_OUTPUT_1, MODE_OUTPUT_2, MODE_OUTPUT_3 }; + +// UART registers, TRM section 27.6 +struct uart { + volatile uint32_t SR, DR, BRR, CR1, CR2, CR3, GTPR; +}; +#define UART1 ((struct uart *) 0x40013800) +#define UART2 ((struct uart *) 0x40004400) +#define UART3 ((struct uart *) 0x40004800) +#define UART4 ((struct uart *) 0x40004c00) +#define UART5 ((struct uart *) 0x40005000) +#define UART_HAS_DATA(u) ((u)->SR & BIT(5)) // RXNE +#define UART_READ(u) ((u)->DR & 255) + +static inline void setreg(uint32_t r, uint32_t clear_mask, uint32_t set_mask) { + r &= ~(clear_mask); + r |= (set_mask); +} + +static inline void pinmode(struct gpio *gpio, uint32_t pin, uint32_t mode) { + uint32_t shift = ((pin) -8) * 4; + setreg(gpio->CRH, 0xf << shift, mode << shift); +} + +static inline void init_ram(void) { + extern uint32_t _bss_start, _bss_end; + extern uint32_t _data_start, _data_end, _data_flash_start; + memset(&_bss_start, 0, ((char *) &_bss_end - (char *) &_bss_start)); + memcpy(&_data_start, &_data_flash_start, + ((char *) &_data_end - (char *) &_data_start)); +} + +static inline void led_toggle(void) { + GPIOC->ODR ^= (1 << LED_PIN); +} + +static inline void init_hardware(void) { + RCC->APB2ENR |= BIT(4); // GPIOC, for LED on PC13 + pinmode(GPIOC, LED_PIN, 0b0110); // open drain, output 2 +} diff --git a/examples/stm32/stm32f1/link.ld b/examples/stm32/stm32f1/link.ld new file mode 100644 index 00000000..6b40a89e --- /dev/null +++ b/examples/stm32/stm32f1/link.ld @@ -0,0 +1,23 @@ +ENTRY(_reset) +_estack = 0x20001000; +MEMORY { + rom(rx) : ORIGIN = 0x08000000, LENGTH = 128k + ram(rwx) : ORIGIN = 0x20000000, LENGTH = 20k +} +SECTIONS { + .text : { *(.text*) } > rom + .rodata : { *(.rodata*) } > rom + + .bss : { + _bss_start = .; + *(.bss SORT(.bss.*) COMMON) + _bss_end = .; + } > ram + + .data : { + _data_start = .; + *(.data SORT(.data.*)) + _data_end = .; + } > ram AT > rom + _data_flash_start = LOADADDR(.data); +} diff --git a/examples/stm32/stm32f1/port.c b/examples/stm32/stm32f1/port.c new file mode 100644 index 00000000..19d8d9bd --- /dev/null +++ b/examples/stm32/stm32f1/port.c @@ -0,0 +1,717 @@ +/* + * FreeRTOS Kernel V10.0.1 + * Copyright (C) 2017 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 CM3 port. + *----------------------------------------------------------*/ + +/* Scheduler includes. */ +#include "FreeRTOS.h" +#include "task.h" + +/* For backward compatibility, ensure configKERNEL_INTERRUPT_PRIORITY is +defined. The value should also ensure backward compatibility. +FreeRTOS.org versions prior to V4.4.0 did not include this definition. */ +#ifndef configKERNEL_INTERRUPT_PRIORITY + #define configKERNEL_INTERRUPT_PRIORITY 255 +#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 ) + +#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 set up the initial stack. */ +#define portINITIAL_XPSR ( 0x01000000UL ) + +/* The systick is a 24-bit counter. */ +#define portMAX_24_BIT_NUMBER ( 0xffffffUL ) + +/* 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 ) + +/* 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 ) + +/* 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 )); + +/* + * 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. */ + pxTopOfStack--; /* Offset added to account for the way the MCU uses the stack on entry/exit of interrupts. */ + *pxTopOfStack = portINITIAL_XPSR; /* xPSR */ + pxTopOfStack--; + *pxTopOfStack = ( ( StackType_t ) pxCode ) & portSTART_ADDRESS_MASK; /* PC */ + pxTopOfStack--; + *pxTopOfStack = ( StackType_t ) portTASK_RETURN_ADDRESS; /* LR */ + pxTopOfStack -= 5; /* R12, R3, R2 and R1. */ + *pxTopOfStack = ( StackType_t ) pvParameters; /* R0 */ + pxTopOfStack -= 8; /* R11, R10, R9, R8, R7, R6, R5 and R4. */ + + return pxTopOfStack; +} +/*-----------------------------------------------------------*/ + +static void prvTaskExitError( void ) +{ +volatile uint32_t ulDummy = 0UL; + + /* 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} \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" + " orr r14, #0xd \n" + " bx r14 \n" + " \n" + " .align 4 \n" + "pxCurrentTCBConst2: .word pxCurrentTCB \n" + ); +} +/*-----------------------------------------------------------*/ + +static void prvPortStartFirstTask( void ) +{ + __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. */ + " 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 ); + + #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; + + /* 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" + " stmdb r0!, {r4-r11} \n" /* Save the remaining registers. */ + " str r0, [r2] \n" /* Save the new top of stack into the first member of the TCB. */ + " \n" + " stmdb sp!, {r3, r14} \n" + " mov r0, %0 \n" + " msr basepri, r0 \n" + " bl vTaskSwitchContext \n" + " mov r0, #0 \n" + " msr basepri, r0 \n" + " ldmia sp!, {r3, r14} \n" + " \n" /* Restore the context, including the critical nesting count. */ + " ldr r1, [r3] \n" + " ldr r0, [r1] \n" /* The first item in pxCurrentTCB is the task top of stack. */ + " ldmia r0!, {r4-r11} \n" /* Pop the registers. */ + " msr psp, r0 \n" + " isb \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 interrpts enabled. */ + __asm volatile( "cpsie i" ::: "memory" ); + } + } + +#endif /* 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 ); +} +/*-----------------------------------------------------------*/ + +#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/examples/stm32/stm32f1/portmacro.h b/examples/stm32/stm32f1/portmacro.h new file mode 100644 index 00000000..860ad5bb --- /dev/null +++ b/examples/stm32/stm32f1/portmacro.h @@ -0,0 +1,242 @@ +/* + * FreeRTOS Kernel V10.0.1 + * Copyright (C) 2017 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" + ); +} +/*-----------------------------------------------------------*/ + + +#ifdef __cplusplus +} +#endif + +#endif /* PORTMACRO_H */ + diff --git a/mongoose.c b/mongoose.c index 2742d7f1..fc9a2831 100644 --- a/mongoose.c +++ b/mongoose.c @@ -22,7 +22,7 @@ #endif void mg_connect_resolved(struct mg_connection *); -#if MG_ARCH == MG_ARCH_FREERTOS +#if MG_ARCH == MG_ARCH_FREERTOS_TCP static inline void *mg_calloc(int cnt, size_t size) { void *p = pvPortMalloc(size); if (p != NULL) memset(p, 0, size); @@ -983,7 +983,7 @@ void mg_http_serve_file(struct mg_connection *c, struct mg_http_message *hm, } #if MG_ARCH == MG_ARCH_ESP32 || MG_ARCH == MG_ARCH_ESP8266 || \ - MG_ARCH == MG_ARCH_FREERTOS + MG_ARCH == MG_ARCH_FREERTOS_TCP char *realpath(const char *src, char *dst) { int len = strlen(src); if (len > MG_PATH_MAX - 1) len = MG_PATH_MAX - 1; @@ -997,7 +997,7 @@ char *realpath(const char *src, char *dst) { // Allow user to override this function bool mg_is_dir(const char *path) WEAK; bool mg_is_dir(const char *path) { -#if MG_ARCH == MG_ARCH_FREERTOS +#if MG_ARCH == MG_ARCH_FREERTOS_TCP && defined(MG_ENABLE_FF) struct FF_STAT st; return (ff_stat(path, &st) == 0) && (st.st_mode & FF_IFDIR); #else @@ -2810,7 +2810,7 @@ struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr, const char *url, #ifndef SO_EXCLUSIVEADDRUSE #define SO_EXCLUSIVEADDRUSE ((int) (~SO_REUSEADDR)) #endif -#elif MG_ARCH == MG_ARCH_FREERTOS +#elif MG_ARCH == MG_ARCH_FREERTOS_TCP #define MG_SOCK_ERRNO errno typedef Socket_t SOCKET; #define INVALID_SOCKET FREERTOS_INVALID_SOCKET @@ -2980,7 +2980,7 @@ static void mg_set_non_blocking_mode(SOCKET fd) { #if defined(_WIN32) && MG_ENABLE_WINSOCK unsigned long on = 1; ioctlsocket(fd, FIONBIO, &on); -#elif MG_ARCH == MG_ARCH_FREERTOS +#elif MG_ARCH == MG_ARCH_FREERTOS_TCP const BaseType_t off = 0; setsockopt(fd, 0, FREERTOS_SO_RCVTIMEO, &off, sizeof(off)); setsockopt(fd, 0, FREERTOS_SO_SNDTIMEO, &off, sizeof(off)); @@ -3086,7 +3086,7 @@ static void close_conn(struct mg_connection *c) { LOG(LL_DEBUG, ("%lu closed", c->id)); if (FD(c) != INVALID_SOCKET) { closesocket(FD(c)); -#if MG_ARCH == MG_ARCH_FREERTOS +#if MG_ARCH == MG_ARCH_FREERTOS_TCP FreeRTOS_FD_CLR(c->fd, c->mgr->ss, eSELECT_ALL); #endif } @@ -3098,7 +3098,7 @@ static void close_conn(struct mg_connection *c) { } static void setsockopts(struct mg_connection *c) { -#if MG_ARCH == MG_ARCH_FREERTOS +#if MG_ARCH == MG_ARCH_FREERTOS_TCP FreeRTOS_FD_SET(c->fd, c->mgr->ss, eSELECT_READ | eSELECT_EXCEPT); #else int on = 1; @@ -3281,7 +3281,7 @@ struct mg_connection *mg_listen(struct mg_mgr *mgr, const char *url, } static void mg_iotest(struct mg_mgr *mgr, int ms) { -#if MG_ARCH == MG_ARCH_FREERTOS +#if MG_ARCH == MG_ARCH_FREERTOS_TCP struct mg_connection *c; for (c = mgr->conns; c != NULL; c = c->next) { FreeRTOS_FD_CLR(c->fd, mgr->ss, eSELECT_WRITE); @@ -4118,7 +4118,7 @@ FILE *mg_fopen(const char *path, const char *mode) { } int64_t mg_file_size(const char *path) { -#if MG_ARCH == MG_ARCH_FREERTOS +#if MG_ARCH == MG_ARCH_FREERTOS_TCP && defined(MG_ENABLE_FF) struct FF_STAT st; return ff_stat(path, &st) == 0 ? st.st_size : 0; #else @@ -4288,8 +4288,9 @@ unsigned long mg_unhexn(const char *s, int len) { for (i = 0; i < (unsigned long) len; i++) { int c = s[i]; if (i > 0) v <<= 4; - v |= (c >= '0' && c <= '9') ? c - '0' - : (c >= 'A' && c <= 'F') ? c - '7' : c - 'W'; + v |= (c >= '0' && c <= '9') ? c - '0' + : (c >= 'A' && c <= 'F') ? c - '7' + : c - 'W'; } return v; } @@ -4421,7 +4422,7 @@ unsigned long mg_millis(void) { #elif MG_ARCH == MG_ARCH_ESP8266 // return system_get_time() / 1000; return xTaskGetTickCount() * portTICK_PERIOD_MS; -#elif MG_ARCH == MG_ARCH_FREERTOS +#elif MG_ARCH == MG_ARCH_FREERTOS_TCP return xTaskGetTickCount() * portTICK_PERIOD_MS; #else struct timespec ts; diff --git a/mongoose.h b/mongoose.h index e85bf489..e6c81bbd 100644 --- a/mongoose.h +++ b/mongoose.h @@ -23,54 +23,17 @@ #define MG_ARCH_WIN32 2 #define MG_ARCH_ESP32 3 #define MG_ARCH_ESP8266 4 -#define MG_ARCH_CC3100 5 -#define MG_ARCH_CC3200 6 -#define MG_ARCH_CC3220 7 -#define MG_ARCH_MSP432 8 -#define MG_ARCH_TM4C129 9 -#define MG_ARCH_MBED 10 -#define MG_ARCH_WINCE 11 -#define MG_ARCH_NXP_LPC 12 -#define MG_ARCH_NXP_KINETIS 13 -#define MG_ARCH_NRF51 14 -#define MG_ARCH_NRF52 15 -#define MG_ARCH_PIC32 16 -#define MG_ARCH_RS14100 17 -#define MG_ARCH_STM32 18 -#define MG_ARCH_FREERTOS 19 +#define MG_ARCH_FREERTOS_TCP 5 #if !defined(MG_ARCH) -#if defined(TARGET_IS_MSP432P4XX) || defined(__MSP432P401R__) -#define MG_ARCH MG_ARCH_MSP432 -#elif defined(cc3200) || defined(TARGET_IS_CC3200) -#define MG_ARCH MG_ARCH_CC3200 -#elif defined(cc3220) || defined(TARGET_IS_CC3220) -#define MG_ARCH MG_ARCH_CC3220 -#elif defined(__unix__) || defined(__APPLE__) +#if defined(__unix__) || defined(__APPLE__) #define MG_ARCH MG_ARCH_UNIX -#elif defined(WINCE) -#define MG_ARCH MG_ARCH_WINCE #elif defined(_WIN32) #define MG_ARCH MG_ARCH_WIN32 -#elif defined(__MBED__) -#define MG_ARCH MG_ARCH_MBED -#elif defined(__USE_LPCOPEN) -#define MG_ARCH MG_ARCH_NXP_LPC -#elif defined(FRDM_K64F) || defined(FREEDOM) -#define MG_ARCH MG_ARCH_NXP_KINETIS -#elif defined(PIC32) -#define MG_ARCH MG_ARCH_PIC32 #elif defined(ICACHE_FLASH) || defined(ICACHE_RAM_ATTR) #define MG_ARCH MG_ARCH_ESP8266 #elif defined(ESP_PLATFORM) #define MG_ARCH MG_ARCH_ESP32 -#elif defined(TARGET_IS_TM4C129_RA0) || defined(TARGET_IS_TM4C129_RA1) || \ - defined(TARGET_IS_TM4C129_RA2) -#define MG_ARCH MG_ARCH_TM4C129 -#elif defined(RS14100) -#define MG_ARCH MG_ARCH_RS14100 -#elif defined(STM32) -#define MG_ARCH MG_ARCH_STM32 #endif #if !defined(MG_ARCH) @@ -154,31 +117,32 @@ #endif -#if MG_ARCH == MG_ARCH_FREERTOS +#if MG_ARCH == MG_ARCH_FREERTOS_TCP #include #include #include #include #include +#include #include #include #include #include #include +#include #include #include +#include #include - -#include - #include #include -#include +#include #define MG_INT64_FMT "%lld" #define MG_DIRSEP '/' + #define IPPROTO_TCP FREERTOS_IPPROTO_TCP #define IPPROTO_UDP FREERTOS_IPPROTO_UDP #define AF_INET FREERTOS_AF_INET @@ -206,12 +170,11 @@ struct sockaddr { #define closesocket(x) FreeRTOS_closesocket(x) #define gethostbyname(x) FreeRTOS_gethostbyname(x) +#ifdef MG_ENABLE_FF #include #undef FILE #define FILE FF_FILE -//#define SEEK_SET FF_SEEK_SET -//#define SEEK_END FF_SEEK_END #define stat(a, b) ff_stat((a), (b)) #define fopen(a, b) ff_fopen((a), (b)) #define fclose(a) ff_fclose(a) @@ -228,8 +191,9 @@ static inline int ff_vfprintf(FF_FILE *fp, const char *fmt, va_list ap) { if (buf != NULL) ff_fwrite(buf, 1, n, fp), free(buf); return n; } +#endif // MG_ENABLE_FF -#endif +#endif // MG_ARCH == MG_ARCH_FREERTOS_TCP #if MG_ARCH == MG_ARCH_UNIX @@ -679,7 +643,7 @@ struct mg_mgr { int dnstimeout; // DNS resolve timeout in milliseconds unsigned long nextid; // Next connection ID void *userdata; // Arbitrary user data pointer -#if MG_ARCH == MG_ARCH_FREERTOS +#if MG_ARCH == MG_ARCH_FREERTOS_TCP SocketSet_t ss; // NOTE(lsm): referenced from socket struct #endif }; diff --git a/src/arch.h b/src/arch.h index f023894b..ffa6a96a 100644 --- a/src/arch.h +++ b/src/arch.h @@ -5,54 +5,17 @@ #define MG_ARCH_WIN32 2 #define MG_ARCH_ESP32 3 #define MG_ARCH_ESP8266 4 -#define MG_ARCH_CC3100 5 -#define MG_ARCH_CC3200 6 -#define MG_ARCH_CC3220 7 -#define MG_ARCH_MSP432 8 -#define MG_ARCH_TM4C129 9 -#define MG_ARCH_MBED 10 -#define MG_ARCH_WINCE 11 -#define MG_ARCH_NXP_LPC 12 -#define MG_ARCH_NXP_KINETIS 13 -#define MG_ARCH_NRF51 14 -#define MG_ARCH_NRF52 15 -#define MG_ARCH_PIC32 16 -#define MG_ARCH_RS14100 17 -#define MG_ARCH_STM32 18 -#define MG_ARCH_FREERTOS 19 +#define MG_ARCH_FREERTOS_TCP 5 #if !defined(MG_ARCH) -#if defined(TARGET_IS_MSP432P4XX) || defined(__MSP432P401R__) -#define MG_ARCH MG_ARCH_MSP432 -#elif defined(cc3200) || defined(TARGET_IS_CC3200) -#define MG_ARCH MG_ARCH_CC3200 -#elif defined(cc3220) || defined(TARGET_IS_CC3220) -#define MG_ARCH MG_ARCH_CC3220 -#elif defined(__unix__) || defined(__APPLE__) +#if defined(__unix__) || defined(__APPLE__) #define MG_ARCH MG_ARCH_UNIX -#elif defined(WINCE) -#define MG_ARCH MG_ARCH_WINCE #elif defined(_WIN32) #define MG_ARCH MG_ARCH_WIN32 -#elif defined(__MBED__) -#define MG_ARCH MG_ARCH_MBED -#elif defined(__USE_LPCOPEN) -#define MG_ARCH MG_ARCH_NXP_LPC -#elif defined(FRDM_K64F) || defined(FREEDOM) -#define MG_ARCH MG_ARCH_NXP_KINETIS -#elif defined(PIC32) -#define MG_ARCH MG_ARCH_PIC32 #elif defined(ICACHE_FLASH) || defined(ICACHE_RAM_ATTR) #define MG_ARCH MG_ARCH_ESP8266 #elif defined(ESP_PLATFORM) #define MG_ARCH MG_ARCH_ESP32 -#elif defined(TARGET_IS_TM4C129_RA0) || defined(TARGET_IS_TM4C129_RA1) || \ - defined(TARGET_IS_TM4C129_RA2) -#define MG_ARCH MG_ARCH_TM4C129 -#elif defined(RS14100) -#define MG_ARCH MG_ARCH_RS14100 -#elif defined(STM32) -#define MG_ARCH MG_ARCH_STM32 #endif #if !defined(MG_ARCH) diff --git a/src/arch_freertos.h b/src/arch_freertos_tcp.h similarity index 92% rename from src/arch_freertos.h rename to src/arch_freertos_tcp.h index 1048cd19..fb54ec5a 100644 --- a/src/arch_freertos.h +++ b/src/arch_freertos_tcp.h @@ -1,30 +1,31 @@ #pragma once -#if MG_ARCH == MG_ARCH_FREERTOS +#if MG_ARCH == MG_ARCH_FREERTOS_TCP #include #include #include #include #include +#include #include #include #include #include #include +#include #include #include +#include #include - -#include - #include #include -#include +#include #define MG_INT64_FMT "%lld" #define MG_DIRSEP '/' + #define IPPROTO_TCP FREERTOS_IPPROTO_TCP #define IPPROTO_UDP FREERTOS_IPPROTO_UDP #define AF_INET FREERTOS_AF_INET @@ -52,12 +53,11 @@ struct sockaddr { #define closesocket(x) FreeRTOS_closesocket(x) #define gethostbyname(x) FreeRTOS_gethostbyname(x) +#ifdef MG_ENABLE_FF #include #undef FILE #define FILE FF_FILE -//#define SEEK_SET FF_SEEK_SET -//#define SEEK_END FF_SEEK_END #define stat(a, b) ff_stat((a), (b)) #define fopen(a, b) ff_fopen((a), (b)) #define fclose(a) ff_fclose(a) @@ -74,5 +74,6 @@ static inline int ff_vfprintf(FF_FILE *fp, const char *fmt, va_list ap) { if (buf != NULL) ff_fwrite(buf, 1, n, fp), free(buf); return n; } +#endif // MG_ENABLE_FF -#endif +#endif // MG_ARCH == MG_ARCH_FREERTOS_TCP diff --git a/src/http.c b/src/http.c index bc92b191..6949c361 100644 --- a/src/http.c +++ b/src/http.c @@ -1,6 +1,6 @@ +#include "http.h" #include "arch.h" #include "base64.h" -#include "http.h" #include "log.h" #include "net.h" #include "private.h" @@ -561,7 +561,7 @@ void mg_http_serve_file(struct mg_connection *c, struct mg_http_message *hm, } #if MG_ARCH == MG_ARCH_ESP32 || MG_ARCH == MG_ARCH_ESP8266 || \ - MG_ARCH == MG_ARCH_FREERTOS + MG_ARCH == MG_ARCH_FREERTOS_TCP char *realpath(const char *src, char *dst) { int len = strlen(src); if (len > MG_PATH_MAX - 1) len = MG_PATH_MAX - 1; @@ -575,7 +575,7 @@ char *realpath(const char *src, char *dst) { // Allow user to override this function bool mg_is_dir(const char *path) WEAK; bool mg_is_dir(const char *path) { -#if MG_ARCH == MG_ARCH_FREERTOS +#if MG_ARCH == MG_ARCH_FREERTOS_TCP && defined(MG_ENABLE_FF) struct FF_STAT st; return (ff_stat(path, &st) == 0) && (st.st_mode & FF_IFDIR); #else diff --git a/src/net.h b/src/net.h index 450e755b..72bb83c0 100644 --- a/src/net.h +++ b/src/net.h @@ -24,7 +24,7 @@ struct mg_mgr { int dnstimeout; // DNS resolve timeout in milliseconds unsigned long nextid; // Next connection ID void *userdata; // Arbitrary user data pointer -#if MG_ARCH == MG_ARCH_FREERTOS +#if MG_ARCH == MG_ARCH_FREERTOS_TCP SocketSet_t ss; // NOTE(lsm): referenced from socket struct #endif }; diff --git a/src/private.h b/src/private.h index 8d01aae8..53e303da 100644 --- a/src/private.h +++ b/src/private.h @@ -1,6 +1,6 @@ void mg_connect_resolved(struct mg_connection *); -#if MG_ARCH == MG_ARCH_FREERTOS +#if MG_ARCH == MG_ARCH_FREERTOS_TCP static inline void *mg_calloc(int cnt, size_t size) { void *p = pvPortMalloc(size); if (p != NULL) memset(p, 0, size); diff --git a/src/sock.c b/src/sock.c index 1070c722..f26063d8 100644 --- a/src/sock.c +++ b/src/sock.c @@ -15,7 +15,7 @@ #ifndef SO_EXCLUSIVEADDRUSE #define SO_EXCLUSIVEADDRUSE ((int) (~SO_REUSEADDR)) #endif -#elif MG_ARCH == MG_ARCH_FREERTOS +#elif MG_ARCH == MG_ARCH_FREERTOS_TCP #define MG_SOCK_ERRNO errno typedef Socket_t SOCKET; #define INVALID_SOCKET FREERTOS_INVALID_SOCKET @@ -185,7 +185,7 @@ static void mg_set_non_blocking_mode(SOCKET fd) { #if defined(_WIN32) && MG_ENABLE_WINSOCK unsigned long on = 1; ioctlsocket(fd, FIONBIO, &on); -#elif MG_ARCH == MG_ARCH_FREERTOS +#elif MG_ARCH == MG_ARCH_FREERTOS_TCP const BaseType_t off = 0; setsockopt(fd, 0, FREERTOS_SO_RCVTIMEO, &off, sizeof(off)); setsockopt(fd, 0, FREERTOS_SO_SNDTIMEO, &off, sizeof(off)); @@ -291,7 +291,7 @@ static void close_conn(struct mg_connection *c) { LOG(LL_DEBUG, ("%lu closed", c->id)); if (FD(c) != INVALID_SOCKET) { closesocket(FD(c)); -#if MG_ARCH == MG_ARCH_FREERTOS +#if MG_ARCH == MG_ARCH_FREERTOS_TCP FreeRTOS_FD_CLR(c->fd, c->mgr->ss, eSELECT_ALL); #endif } @@ -303,7 +303,7 @@ static void close_conn(struct mg_connection *c) { } static void setsockopts(struct mg_connection *c) { -#if MG_ARCH == MG_ARCH_FREERTOS +#if MG_ARCH == MG_ARCH_FREERTOS_TCP FreeRTOS_FD_SET(c->fd, c->mgr->ss, eSELECT_READ | eSELECT_EXCEPT); #else int on = 1; @@ -486,7 +486,7 @@ struct mg_connection *mg_listen(struct mg_mgr *mgr, const char *url, } static void mg_iotest(struct mg_mgr *mgr, int ms) { -#if MG_ARCH == MG_ARCH_FREERTOS +#if MG_ARCH == MG_ARCH_FREERTOS_TCP struct mg_connection *c; for (c = mgr->conns; c != NULL; c = c->next) { FreeRTOS_FD_CLR(c->fd, mgr->ss, eSELECT_WRITE); diff --git a/src/util.c b/src/util.c index a5b590d4..17d05ba1 100644 --- a/src/util.c +++ b/src/util.c @@ -1,5 +1,5 @@ -#include "config.h" #include "util.h" +#include "config.h" #if MG_ENABLE_FS int mg_stat(const char *path, mg_stat_t *st) { @@ -24,7 +24,7 @@ FILE *mg_fopen(const char *path, const char *mode) { } int64_t mg_file_size(const char *path) { -#if MG_ARCH == MG_ARCH_FREERTOS +#if MG_ARCH == MG_ARCH_FREERTOS_TCP && defined(MG_ENABLE_FF) struct FF_STAT st; return ff_stat(path, &st) == 0 ? st.st_size : 0; #else @@ -194,8 +194,9 @@ unsigned long mg_unhexn(const char *s, int len) { for (i = 0; i < (unsigned long) len; i++) { int c = s[i]; if (i > 0) v <<= 4; - v |= (c >= '0' && c <= '9') ? c - '0' - : (c >= 'A' && c <= 'F') ? c - '7' : c - 'W'; + v |= (c >= '0' && c <= '9') ? c - '0' + : (c >= 'A' && c <= 'F') ? c - '7' + : c - 'W'; } return v; } @@ -327,7 +328,7 @@ unsigned long mg_millis(void) { #elif MG_ARCH == MG_ARCH_ESP8266 // return system_get_time() / 1000; return xTaskGetTickCount() * portTICK_PERIOD_MS; -#elif MG_ARCH == MG_ARCH_FREERTOS +#elif MG_ARCH == MG_ARCH_FREERTOS_TCP return xTaskGetTickCount() * portTICK_PERIOD_MS; #else struct timespec ts;