DHCP Timeout Options


When my device is turned on it will start to send DHCP discover messages. I have set the search to timeout after 10 minutes. I would like a way to restart the search after this timeout. The problem with extending the maximum timeout is the interval between discover messages is too long. Is there a way that I could restart the search without editing the actual FreeRTOS library?

Setting the network down only seems to work if the device previously found a DHCP response. If a timeout has occurred, I cannot figure out how to restart the DHCP search.

Any thoughts are appreciated!

I believe I have managed to solve this. It seems like if I close the ethernet then call NetworkDown this is restarting the DHCP process.

Hi @drowsell,
Yes, you’re right. Restarting network interface by calling FreeRTOS_NetworkDown can also restart whole DHCP procedure.

Over the weekend I was testing this and have spotted a bug. After I call FreeRTOS_NetworkDown(); I seem to lose 0x1100 heap every time. I was calling FreeRTOS_NetworkDown() every 30 minutes and it was consistent each time.

Is there a proper way to do this that I am missing? I am trying to find this memory leak. My goal is still to start the DHCP process after a timeout.

Hi @drowsell,
Could you help to share the version of FreeRTOS-Plus-TCP you’re using?

And it can also be useful to know the platform you’re using, and a copy of your configuration files:


My version is:

FreeRTOS+TCP V2.4.0

Edit: These files were generated with the Renesas Smart Config tool.

Requested files are below:

/* generated configuration header file - do not edit */
            * Application specific definitions.
            * These definitions should be adjusted for your particular hardware and
            * application requirements.
            * See http://www.freertos.org/a00110.html
            #include "bsp_api.h"

            /* Common macro for FSP header files. There is also a corresponding FSP_FOOTER macro at the end of this file. */

            #ifndef configUSE_PREEMPTION
            #define configUSE_PREEMPTION (1)
            #ifndef configUSE_PORT_OPTIMISED_TASK_SELECTION
            #define configUSE_PORT_OPTIMISED_TASK_SELECTION (0)
            #ifndef configUSE_TICKLESS_IDLE
            #define configUSE_TICKLESS_IDLE (0)
            #ifndef configUSE_IDLE_HOOK
            #define configUSE_IDLE_HOOK (0)
            #ifndef configUSE_MALLOC_FAILED_HOOK
            #define configUSE_MALLOC_FAILED_HOOK (0)
            #ifndef configUSE_DAEMON_TASK_STARTUP_HOOK
            #define configUSE_DAEMON_TASK_STARTUP_HOOK (0)
            #ifndef configUSE_TICK_HOOK
            #define configUSE_TICK_HOOK (0)
            #ifndef configCPU_CLOCK_HZ
            #define configCPU_CLOCK_HZ (SystemCoreClock)
            #ifndef configTICK_RATE_HZ
            #define configTICK_RATE_HZ (1000)
            #ifndef configMAX_PRIORITIES
            #define configMAX_PRIORITIES (5)
            #ifndef configMINIMAL_STACK_SIZE
            #define configMINIMAL_STACK_SIZE (512)
            #ifndef configMINIMAL_SECURE_STACK_SIZE
            #define configMINIMAL_SECURE_STACK_SIZE (256U)  /* Unused in RA port. */
            #ifndef configMAX_TASK_NAME_LEN
            #define configMAX_TASK_NAME_LEN (16)
            #ifndef configUSE_TRACE_FACILITY
            #define configUSE_TRACE_FACILITY (0)
            #ifndef configUSE_STATS_FORMATTING_FUNCTIONS
            #define configUSE_STATS_FORMATTING_FUNCTIONS (0)
            #ifndef configUSE_16_BIT_TICKS
            #define configUSE_16_BIT_TICKS (0)
            #ifndef configIDLE_SHOULD_YIELD
            #define configIDLE_SHOULD_YIELD (1)
            #ifndef configUSE_TASK_NOTIFICATIONS
            #define configUSE_TASK_NOTIFICATIONS (1)
            #ifndef configUSE_MUTEXES
            #define configUSE_MUTEXES (1)
            #ifndef configUSE_RECURSIVE_MUTEXES
            #define configUSE_RECURSIVE_MUTEXES (1)
            #ifndef configUSE_COUNTING_SEMAPHORES
            #define configUSE_COUNTING_SEMAPHORES (1)
            #ifndef configUSE_ALTERNATIVE_API
            #define configUSE_ALTERNATIVE_API (0U)
            #ifndef configCHECK_FOR_STACK_OVERFLOW
            #define configCHECK_FOR_STACK_OVERFLOW (0)
            #ifndef configQUEUE_REGISTRY_SIZE
            #define configQUEUE_REGISTRY_SIZE (10)
            #ifndef configUSE_QUEUE_SETS
            #define configUSE_QUEUE_SETS (0)
            #ifndef configUSE_TIME_SLICING
            #define configUSE_TIME_SLICING (0)
            #ifndef configUSE_NEWLIB_REENTRANT
            #define configUSE_NEWLIB_REENTRANT (0)
            #ifndef configENABLE_BACKWARD_COMPATIBILITY
            #define configENABLE_BACKWARD_COMPATIBILITY (0)
            #ifndef configNUM_THREAD_LOCAL_STORAGE_POINTERS
            #define configNUM_THREAD_LOCAL_STORAGE_POINTERS (5)
            #ifndef configSTACK_DEPTH_TYPE
            #define configSTACK_DEPTH_TYPE uint32_t
            #ifndef configMESSAGE_BUFFER_LENGTH_TYPE
            #define configMESSAGE_BUFFER_LENGTH_TYPE size_t
            #ifndef configSUPPORT_STATIC_ALLOCATION
            #define configSUPPORT_STATIC_ALLOCATION (1)
            #ifndef configSUPPORT_DYNAMIC_ALLOCATION
            #define configSUPPORT_DYNAMIC_ALLOCATION (1)
            #ifndef configTOTAL_HEAP_SIZE
            #define configTOTAL_HEAP_SIZE (0x18000)
            #ifndef configAPPLICATION_ALLOCATED_HEAP
            #define configAPPLICATION_ALLOCATED_HEAP (0)
            #ifndef configGENERATE_RUN_TIME_STATS
            #define configGENERATE_RUN_TIME_STATS (0)
            #ifndef configUSE_CO_ROUTINES
            #define configUSE_CO_ROUTINES (0)
            #ifndef configUSE_TIMERS
            #define configUSE_TIMERS (1)
            #ifndef configTIMER_TASK_PRIORITY
            #define configTIMER_TASK_PRIORITY (3)
            #ifndef configTIMER_QUEUE_LENGTH
            #define configTIMER_QUEUE_LENGTH (10)
            #ifndef configTIMER_TASK_STACK_DEPTH
            #define configTIMER_TASK_STACK_DEPTH (128)
            #define configLIBRARY_LOWEST_INTERRUPT_PRIORITY ((1 << __NVIC_PRIO_BITS) - 1)
            #define configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY ((1))
            #ifndef configMAX_SYSCALL_INTERRUPT_PRIORITY
            #ifndef configMAX_API_CALL_INTERRUPT_PRIORITY
            #ifndef configASSERT
            #define configASSERT( x ) assert(x)
            #ifndef INCLUDE_vTaskPrioritySet
            #define INCLUDE_vTaskPrioritySet (1)
            #ifndef INCLUDE_uxTaskPriorityGet
            #define INCLUDE_uxTaskPriorityGet (1)
            #ifndef INCLUDE_vTaskDelete
            #define INCLUDE_vTaskDelete (1)
            #ifndef INCLUDE_vTaskSuspend
            #define INCLUDE_vTaskSuspend (1)
            #ifndef INCLUDE_xResumeFromISR
            #define INCLUDE_xResumeFromISR (1)
            #ifndef INCLUDE_vTaskDelayUntil
            #define INCLUDE_vTaskDelayUntil (1)
            #ifndef INCLUDE_vTaskDelay
            #define INCLUDE_vTaskDelay (1)
            #ifndef INCLUDE_xTaskGetSchedulerState
            #define INCLUDE_xTaskGetSchedulerState (1)
            #ifndef INCLUDE_xTaskGetCurrentTaskHandle
            #define INCLUDE_xTaskGetCurrentTaskHandle (1)
            #ifndef INCLUDE_uxTaskGetStackHighWaterMark
            #define INCLUDE_uxTaskGetStackHighWaterMark (0)
            #ifndef INCLUDE_xTaskGetIdleTaskHandle
            #define INCLUDE_xTaskGetIdleTaskHandle (0)
            #ifndef INCLUDE_eTaskGetState
            #define INCLUDE_eTaskGetState (1)
            #ifndef INCLUDE_xEventGroupSetBitFromISR
            #define INCLUDE_xEventGroupSetBitFromISR (1)
            #ifndef INCLUDE_xTimerPendFunctionCall
            #define INCLUDE_xTimerPendFunctionCall (0)
            #ifndef INCLUDE_xTaskAbortDelay
            #define INCLUDE_xTaskAbortDelay (0)
            #ifndef INCLUDE_xTaskGetHandle
            #define INCLUDE_xTaskGetHandle (0)
            #ifndef INCLUDE_xTaskResumeFromISR
            #define INCLUDE_xTaskResumeFromISR (1)
            #ifndef configPRINT_STRING
            #define configPRINT_STRING(x)                      (printf(x))
            #ifndef configLOGGING_INCLUDE_TIME_AND_TASK_NAME
            #define configLOGGING_INCLUDE_TIME_AND_TASK_NAME   (0)
            #ifndef configLOGGING_MAX_MESSAGE_LENGTH
            #define configLOGGING_MAX_MESSAGE_LENGTH           (192)

            /* Common macro for FSP header files. There is also a corresponding FSP_HEADER macro at the top of this file. */
#endif /* FREERTOSCONFIG_H_ */
/* generated configuration header file - do not edit */
 * 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.
 * http://www.FreeRTOS.org
 * http://aws.amazon.com/freertos

* See the following URL for configuration information.
* http://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/TCP_IP_Configuration.html
#include "r_ether_cfg.h"


#ifdef __cplusplus
extern "C" {

/* 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    1
#if ( ipconfigHAS_DEBUG_PRINTF == 1 )
    #define FreeRTOS_debug_printf( X )    configPRINTF( X )

/* 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 )    configPRINTF( X )

/* 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    (8000)
#define ipconfigSOCK_DEFAULT_SEND_BLOCK_TIME       (8000)

/* 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                      (0)
#define ipconfigDNS_REQUEST_ATTEMPTS               (5)

/* 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 - 1)

/* 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 * 10)

/* 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. */
uint32_t ulRand(void);
#define ipconfigRAND32()    ulRand()

/* 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    (15000 / 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
#define ipconfigDHCP_REGISTER_HOSTNAME           1
#define ipconfigDHCP_USES_UNICAST                1

/* If ipconfigDHCP_USES_USER_HOOK is set to 1 then the application writer must
 * provide an implementation of the DHCP callback function,
 * xApplicationDHCPUserHook(). */
#define ipconfigUSE_DHCP_HOOK                    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     (1800000 / 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, "") 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. */

/* 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. */

/* 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
 * 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
/* Also defined in FreeRTOSIPConfigDefaults.h. */
#define ipconfigTCP_TIME_TO_LIVE                       128

/* USE_TCP: Use TCP and all its features. */
#define ipconfigUSE_TCP                                (1)

/* USE_WIN: Let TCP use windowing mechanism. */
#define ipconfigUSE_TCP_WIN                            (0)

/* 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                            1500

/* 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                 1

/* 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. */

/* 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

/* 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 )

/* 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                   (3000)

/* Define the size of Tx buffer for TCP sockets. */
#define ipconfigTCP_TX_BUFFER_LENGTH                   (3000)

/* 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 keep-alive messages. */
#define ipconfigTCP_KEEP_ALIVE                   (1)
#define ipconfigTCP_KEEP_ALIVE_INTERVAL          (5) /* Seconds. */

/* The socket semaphore is used to unblock the MQTT task. */
#define ipconfigSOCKET_HAS_USER_SEMAPHORE        (0)

#define ipconfigSOCKET_HAS_USER_WAKE_CALLBACK    (0)
#define ipconfigUSE_CALLBACKS                    (0)

#define ipconfigZERO_COPY_TX_DRIVER              (0)
#define ipconfigZERO_COPY_RX_DRIVER              (0)

/* Possible optimisation for expert users - requires network driver support.
 * When ipconfigUSE_LINKED_RX_MESSAGES is set to non-zero value then
 * 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. This optimisation is useful when there is high network traffic.
 * When ipconfigUSE_LINKED_RX_MESSAGES is 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. */
#define ipconfigUSE_LINKED_RX_MESSAGES           (0)

#define portINLINE                               __inline

void vApplicationMQTTGetKeys( const char ** ppcRootCA,
                              const char ** ppcClientCert,
                              const char ** ppcClientPrivateKey );

#ifdef __cplusplus


Could it be possible that network down is filling up a queue somewhere? 0x1100 seems like a lot of memory for a leak though.

Can you add some logs to alloc and free APIs:

  1. Print the requested size and allocated block pointer.
  2. Print the freed block pointer.

We can then parse those logs using a script and find which blocks did not get freed. Lets say that it truns out to be one block of size 0x1100. We can then update the malloc like the following -

void * pvPortMalloc( size_t xWantedSize )
    if( xWantedSize  == 0x1100 )

If the application allocated too many blocks of size 0x1100, we may need to make the check more specific, like break at the 10th allocation of this size. Then we can examine the call stack and try to find the cause of leak.

Hi @drowsell,
I tried to run DHCP loop with FreeRTOS-Plus-TCP V2.4.0, but I can’t reproduce the memory leak locally.
Could you help to try @aggarg recommendation to catch it?

DHCP loop:
1. get IP address via DHCP
2. check network status by FreeRTOS_IsNetworkUp()
3. establish MQTT connection
4. send test message to MQTT server
5. close socket
6. call FreeRTOS_NetworkDown() to restart DHCP procedure
7. back to step 1


I have found the issue:

I followed the advice given here and I caught the malloc that was responsible. In the NetworkInterface.c file the following function was the problem:

 * @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. */

    /* 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. */
        /* 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 );
                /* Perform any necessary 'network up' processing. */

Above if xNetworkInterfaceInitialise() returns false it will not start the DHCP routine. If it returns true it will.

BaseType_t xNetworkInterfaceInitialise (void)
    fsp_err_t  err;
    BaseType_t xReturn = pdFAIL;

    if (ETHER_ZEROCOPY_ENABLE == gp_freertos_ether->p_cfg->zerocopy)
        /*NOTE:Currently does not support zero copy mode*/
        while (1)

    err = gp_freertos_ether->p_api->open(gp_freertos_ether->p_ctrl, gp_freertos_ether->p_cfg);

    if (FSP_SUCCESS != err)
        return pdFAIL;


    xReturn = xTaskCreate(prvRXHandlerTask,
                          configMAX_PRIORITIES - 1,

    if (pdFALSE != xReturn)
        xReturn = xTaskCreate(prvCheckLinkStatusTask,
                              configMAX_PRIORITIES - 1,

    return xReturn;

If the ether was already open this would return a fail. If the ether was closed then this would create two new tasks.

So since I am closing the ether before calling FreeRTOS_NetworkDown() these tasks get started each time. If I do not close the ether, the DHCP routine will get an error that the device is already open. I can fix this by adding the following code:

    err = gp_freertos_ether->p_api->open(gp_freertos_ether->p_ctrl,     gp_freertos_ether->p_cfg);

    if ( FSP_ERR_ALREADY_OPEN == err )
        return pdPASS;
    else if (FSP_SUCCESS != err)
        return pdFAIL;

However, this leaves me with the problem of having to change this in the library. I am using the Renesas FSP which auto-generates these files, so this will be overwritten when I run that tool.

Hi @drowsell,
Thanks for your feedback!

We have RX portable layer for Renesas RX series platforms in FreeRTOS-Plus-TCP.
If you’re using RX series, could you help to create a pull request to update that portable layer?
If you’re not using RX series, could you help to post a topic in Renesas forum, such as RA forum?


Thank you for reporting your findings! I checked the file in our repo that @ActoryOu metnioned - it does not seem like you are using this one. Therefore, the right thing to do here is to report it to Renesas so that they can update their Network interface implementation.

@ActoryOu we should also update the driver above by adding the following at this line:

+  if( ether_receive_check_task_handle == NULL )
+  {
        return_code = xTaskCreate( prvEMACDeferredInterruptHandlerTask,
                                   configMAX_PRIORITIES - 1,
                                   &ether_receive_check_task_handle );
+  }
+  else
+  {
+   return_code = pdTRUE;
+  }

Here is a PR for it: Fix RX network interface to create task only once.

@ActoryOu and @aggarg can you help me in reviewing the PR?


1 Like

Thank you for the change @kanherea.

Thanks everyone. I submitted a ticket to Renesas for the bug. I will keep an eye on this to see if my change truly fixes the issue.