Timeout with QSPI device

Hello,

I am working on a project which is using a QSPI peripheral to talk to a QSPI Flash device. I am using the XQspiPs driver provided by Xilinx. However, since this driver is not thread-safe, I have created my own wrapper around it using a mutex. I have created a higher level driver that uses my QSPI driver to talk to the QSPI flash memory. A part of any write functions in that driver is a loop that continuously checks if the write was successful by reading the flash status. I want to make sure that if the write is not successful within a certain amount of time, the while loop will timeout and break. I have done it in this way and want to know if this is the best way to do it:

/* Initialize timeout.  This records the time at which this function was entered. */
vTaskSetTimeOutState( &timeout );
while (1)
{
    /*
     * Poll the status register of the FLASH to determine when
     * Quad Mode is enabled and the device is ready, by sending
     * a read status command and receiving the status byte
     */
    status = qspi_read(_p_qspi_master_device, read_status_command, flash_status, sizeof(read_status_command));
    if (status != CR02_SUCCESS)
    {
        CR02_DEBUG_PRINT(CR02_DEBUG_ERROR, "qspi_flash_quad_enable : Unable to read status register from QSPI flash.\r\n");
        return status;
    }

    /*
     * If 6th bit is set & 0th bit is reset, then Quad is Enabled
     * and device is ready.
     */
    if ((flash_status[0] == 0x40) && (flash_status[1] == 0x40))
    {
        break;
    }

    if(xTaskCheckForTimeOut(&timeout, &ticks_to_wait) != pdFALSE)
    {
        /* Timeout occurred - flash took too long to indicate quad spi enable successful. Exit the loop. */
        CR02_DEBUG_PRINT(CR02_DEBUG_ERROR, "qspi_flash_quad_enable : Quad enable timeout.\r\n");
        return CR02_FAILURE;
    }
}

If this is not the best way to implement a timeout in FreeRTOS, is there a best-known-method?

Thank you for your time,
-Sid

Yes, that looks reasonable, unless the changing of the status is able to generate an interrupt - in which case you would not need to poll. xTaskCheckForTimeOut() simplifies things if the tick count overflows during the timeout.

There is a corner case with this timeout guarded polling solution I came across recently.
If the task is preempted by another one after checking the HW status and before checking for timeout for a duration long enough that the timeout already expired when the task continues to run, the HW is checked only once during the very 1st loop. That might cause false timeouts and possibly problems with the peripheral.
For a bullet proof solution a post-check of the HW status is needed after timeout detection (with non-matching HW status) to ensure the HW status is really checked long enough.