Mbedtls_ssl_close_notify takes more than 30 seconds if a delay is not provided before the function

Hi

We have a code called Freertos_TLS_Disconnect() which calls mbedtls_ssl_close_notify() internally.

The function takes 45 seconds with an error code -27648 when there is no delay added before the code as shown below

            APP_PRINT("before TLS_FreeRTOS_Disconnect\r\n");
            //R_BSP_SoftwareDelay(1000, BSP_DELAY_UNITS_MILLISECONDS);
            gpt_init_data_process(0,1);
            TLS_FreeRTOS_Disconnect (&xNetworkContext);
            gpt_init_data_process(1,1);
            APP_PRINT(" after TLS_FreeRTOS_Disconnect\r\n");
            isSocketConnected = FALSE;

But when the delay is added (to the above code) the mbedtls_ssl_close_notify succeeds and the time taken for the function to execiute is a mere 15 ms.

The question is, does the mbedtls_ssl_close_notify function require a delay before gracefully closing the connection? if not what is the fix?

Implementation of TLS_Freertos_disconnect function is as below

void TLS_FreeRTOS_Disconnect( NetworkContext_t * pNetworkContext )
{
    TlsTransportParams_t * pTlsTransportParams = NULL;
    BaseType_t tlsStatus = 0;

    if( ( pNetworkContext != NULL ) && ( pNetworkContext->pParams != NULL ) )
    {
        pTlsTransportParams = pNetworkContext->pParams;
        /* Attempting to terminate TLS connection. */
        tlsStatus = ( BaseType_t ) mbedtls_ssl_close_notify( &( pTlsTransportParams->sslContext.context ) );

        /* Ignore the WANT_READ and WANT_WRITE return values. */
        if( ( tlsStatus != ( BaseType_t ) MBEDTLS_ERR_SSL_WANT_READ ) &&
            ( tlsStatus != ( BaseType_t ) MBEDTLS_ERR_SSL_WANT_WRITE ) )
        {
            if( tlsStatus == 0 )
            {
                LogInfo( ( "(Network connection %p) TLS close-notify sent.",
                           pNetworkContext ) );
            }
            else
            {
                LogError( ( "(Network connection %p) Failed to send TLS close-notify: mbedTLSError= %s : %s.",
                            pNetworkContext,
                            mbedtlsHighLevelCodeOrDefault( tlsStatus ),
                            mbedtlsLowLevelCodeOrDefault( tlsStatus ) ) );
            }
        }

        /* Call socket shutdown function to close connection. */
        TCP_Sockets_Disconnect( pTlsTransportParams->tcpSocket );

        /* Free mbed TLS contexts. */
        sslContextFree( &( pTlsTransportParams->sslContext ) );
    }
}