Skip to content

fix(freertos): notifiy-based sync can be initialized from any task - #6692

Merged
kisvegabor merged 3 commits into
lvgl:masterfrom
liamHowatt:fix/freertos-task-notify
Aug 26, 2024
Merged

kisvegabor merged 3 commits into
lvgl:masterfrom
liamHowatt:fix/freertos-task-notify

Conversation

@liamHowatt

Copy link
Copy Markdown
Contributor

Description of the feature or fix

Fixes #6414

lv_thread_sync_wait can be called from a thread other than the one that called lv_thread_sync_init.

@nicusorcitu

Notes

@kisvegabor

Copy link
Copy Markdown
Member

cc @espzav @Jvsjvs

kisvegabor
kisvegabor previously approved these changes Aug 17, 2024

@kisvegabor kisvegabor left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you Liam!

I wonder if other operating systems don't have the same issue.

Anyway, I've looked into LVGL and couldn't see an obvious way to restructure it to make it work even without this fix. So I suggest merging this fix now and see if the issue shows up for others too.

@Jvsjvs

Jvsjvs commented Aug 17, 2024

Copy link
Copy Markdown

Thanks for picking it up.

If there is a performance hit, then I believe it is better to simply enforce the users to use the same thread with proper documentation.

This restriction is easy to address by the users, maybe you can propose to the users to use a similar setup as I did and documented in the original issue.

If it works now without performance hit then this is of course perfect!!

@nicusorcitu

Copy link
Copy Markdown
Contributor

@liamHowatt thanks for this PR.

Comment thread src/osal/lv_freertos.c
/* Send a notification to the task waiting. */
xTaskNotifyGive(pxCond->xTaskToNotify);
_enter_critical();
TaskHandle_t task_to_notify = pxCond->xTaskToNotify;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use the new member BaseType_t xIsInitialized; to verify if the task to notify is valid.

Comment thread src/osal/lv_freertos.h Outdated
typedef struct {
#if USE_FREERTOS_TASK_NOTIFY
TaskHandle_t xTaskToNotify;
BaseType_t xSignalSent;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use the freertos naming convention all over in this file:
https://www.freertos.org/Documentation/02-Kernel/06-Coding-guidelines/02-FreeRTOS-Coding-Standard-and-Style-Guide#naming-conventions

At a better look, I think you can use a member like
BaseType_t xIsInitialized;
similar as it is done on semaphore implementation.

E.G. no signal can be done until the initialization is done.

Comment thread src/osal/lv_freertos.c Outdated
#if USE_FREERTOS_TASK_NOTIFY
/* Store the handle of the calling task. */
pxCond->xTaskToNotify = xTaskGetCurrentTaskHandle();
pxCond->xTaskToNotify = NULL;

@nicusorcitu nicusorcitu Aug 19, 2024 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please don't remove the scope of the init API.

Add a local function here like:

    /* If the cond is uninitialized, perform initialization. */
    prvCheckCondInit(pxCond);

and let the initialization happen if it get called explicitly.

Then make use of the same static function prvCheckCondInit(pxCond); in the lv_thread_sync_wait().

@liamHowatt

Copy link
Copy Markdown
Contributor Author

Thanks for the review!

Comment thread src/osal/lv_freertos.h
typedef struct {
void (*pvStartRoutine)(void *); /**< Application thread function. */
void * xTaskArg; /**< Arguments for application thread function. */
void * pTaskArg; /**< Arguments for application thread function. */

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pvTaskArg

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the coding standard naming conventions you linked, the "v" seems to only apply for function names that return void (nothing), not void pointer variables.

Comment thread src/osal/lv_freertos.h Outdated
xIsInitialized; /**< Set to pdTRUE if this condition variable is initialized, pdFALSE otherwise. */
#if USE_FREERTOS_TASK_NOTIFY
TaskHandle_t xTaskToNotify;
BaseType_t xSignalSent;

@nicusorcitu nicusorcitu Aug 21, 2024 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need for xSignalSent, so it can be removed, correct? We make use of the pxCond->xSyncSignal now.

@liamHowatt liamHowatt Aug 21, 2024 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not currently, but I can make that variable common between both implementations 👍

Comment thread src/osal/lv_freertos.c
static void prvCondInit(lv_thread_sync_t * pxCond)
{
#if USE_FREERTOS_TASK_NOTIFY
pxCond->xTaskToNotify = NULL;

@nicusorcitu nicusorcitu Aug 21, 2024 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Implement this, similar as it is done for semaphores.
I see it like:

#if USE_FREERTOS_TASK_NOTIFY
    pxCond->xTaskToNotify = xTaskGetCurrentTaskHandle();
    pxCond->xIsInitialized = pdTRUE;
    pxCond->xSyncSignal = pdFALSE;
#else

You might have the last two common for semaphores and sygnal thread.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mean to replace all the code under #if USE_FREERTOS_TASK_NOTIFY with the above suggestion and see if it works to you.

Comment thread src/osal/lv_freertos.c
prvCheckCondInit(pxCond);

#if USE_FREERTOS_TASK_NOTIFY
_enter_critical();

@nicusorcitu nicusorcitu Aug 21, 2024 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replace all new code with:

#if USE_FREERTOS_TASK_NOTIFY
    xTaskNotifyGive(pxCond->xTaskToNotify);
    pxCond->xSyncSignal = pdTRUE;
#else

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mean to replace all the code under #if USE_FREERTOS_TASK_NOTIFY with the above suggestion and see if it works to you.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replace all new code with:

#if USE_FREERTOS_TASK_NOTIFY
    xTaskNotifyGive(pxCond->xTaskToNotify);
    pxCond->xSyncSignal = pdTRUE;
#else

pxCond->xTaskToNotify may be NULL which is why there is the current logic to determine which task to notify, if any.

Comment thread src/osal/lv_freertos.c
lv_result_t lvRes = LV_RESULT_OK;

/* If the cond is uninitialized, perform initialization. */
prvCheckCondInit(pxCond);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If wait gets called prior of any init, this call will do the initialization.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct. I applied your feedback after your last review to make it work that way. Is there something you want me to change?

Comment thread src/osal/lv_freertos.c

#if USE_FREERTOS_TASK_NOTIFY
LV_UNUSED(pxCond);
TaskHandle_t current_task_handle = xTaskGetCurrentTaskHandle();

@nicusorcitu nicusorcitu Aug 21, 2024 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replace all new code with:

#if USE_FREERTOS_TASK_NOTIFY
    while(!pxCond->xSyncSignal) {
        ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
    }
    pxCond->xSyncSignal = pdFALSE;
#else

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not completely clear on this. Is this a different solution?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mean to replace all the code under #if USE_FREERTOS_TASK_NOTIFY with the above suggestion and see if it works to you.

Comment thread src/osal/lv_freertos.c
prvCheckCondInit(pxCond);

#if USE_FREERTOS_TASK_NOTIFY
_enter_critical();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similar as done for sync_signal.

@liamHowatt

Copy link
Copy Markdown
Contributor Author

I mean to replace all the code under #if USE_FREERTOS_TASK_NOTIFY with the above suggestion and see if it works to you.

Gotcha, I will have time to try tomorrow.

@kisvegabor

Copy link
Copy Markdown
Member

@liamHowatt @nicusorcitu
Does it work in its current form? If so, let's merge it and improve later.

@liamHowatt

Copy link
Copy Markdown
Contributor Author

Yes, it is currently working.

@kisvegabor

Copy link
Copy Markdown
Member

Thanks, merging then to make sure that it's fixed in v9.2.

@kisvegabor
kisvegabor merged commit 0bd8cbc into lvgl:master Aug 26, 2024

@liamHowatt liamHowatt left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you have a simpler way to do it than what I've done. Would you mind opening a PR? 🙂

Comment thread src/osal/lv_freertos.c
prvCheckCondInit(pxCond);

#if USE_FREERTOS_TASK_NOTIFY
_enter_critical();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replace all new code with:

#if USE_FREERTOS_TASK_NOTIFY
    xTaskNotifyGive(pxCond->xTaskToNotify);
    pxCond->xSyncSignal = pdTRUE;
#else

pxCond->xTaskToNotify may be NULL which is why there is the current logic to determine which task to notify, if any.

@nicusorcitu

Copy link
Copy Markdown
Contributor

prvCheckCondInit(pxCond); should always make sure that pxCond->xTaskToNotify is not null, (e.g. the conditional wait is always initialized).

Comment thread src/osal/lv_freertos.c
prvCheckCondInit(pxCond);

#if USE_FREERTOS_TASK_NOTIFY
_enter_critical();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_enter_critical() does not work for ISR, it will hang.
You would have to add new defines:

#define _enter_critical_isr() taskENTER_CRITICAL_FROM_ISR();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very good catch! 😮 In all of the environments I've seen so far, the same critical section API is used inside and outside of ISRs. I tested on ESP32-S3 and it worked for me. Maybe only some ports of FreeRTOS implement the ISR version with important extra steps.

@nicusorcitu

Copy link
Copy Markdown
Contributor

I think you have a simpler way to do it than what I've done. Would you mind opening a PR? 🙂

We have a strict way of pushing commits to upstream, need to pass some additional checks.

For this particular issue we might send a commit with the proposal, will open a PR soon.
@cosmindanielradu19

@nicusorcitu

Copy link
Copy Markdown
Contributor

I have done a lot of tests and investigated the new code which does not seem to work anymore on FreeRTOS.
The whole story start from this sentence:

lv_thread_sync_wait can be called from a thread other than the one that called lv_thread_sync_init.

But why? Task notification is different than semaphore implementation.
On semaphores there is a single sync that can be used in both directions.
On task notification you can use the sync only in a single direction. If you want to be both ways you will need two synchronizations, hence two init calls.

I would revert the changes due to this commit and revise it from the application level. It had more sense as it was before.

@liamHowatt

Copy link
Copy Markdown
Contributor Author

Even after using the taskENTER_CRITICAL_FROM_ISR fix? Do you know what usage pattern causes the failure you're seeing? I would like to understand why these changes aren't working.

Please see the issue this PR is linked to #6414. It's non-obvious to users that the task that calls lv_timer_handler must be the same task that called lv_init. Vendor port code also made the mistake.

It seems like the task notify vs semaphore choice is not very configurable. It's a define in a header file, not part of the config. I think the task notify implementation has the potential to deprecate the semaphore implementation at some point, but only if it doesn't have too many tradeoffs. If both implementations stay, I think it should be easier for a user to choose which implementation they want.

@nicusorcitu

nicusorcitu commented Sep 9, 2024 •

Copy link
Copy Markdown
Contributor

Even after using the taskENTER_CRITICAL_FROM_ISR fix?

Yes, that would fix only the hang from ISR.

Let's say Task1 is the LVGL and Task2 is the GPU unit.
Task1 have _draw_info.sync to know when it has to dispatch again.
Task2 have u.sync to know when to process a task.

Task1 waits on _draw_info.sync and Task2 signals the Task1 Handle. So it works only in one direction.
Task2 waits on u.sync until a new task is passed to the unit and signaled from Task1. This works on the other way.

  1. In this PR you changed the behavior of what sync means. E.G. if Task2 signals before Task1 waits, then Task1 wait will skip waiting.
    And is fine, this behavior is needed in case Task2 have higher priority than Task1.

  2. But, in Task1 dispatcher, while there is a need for Task2 to wait_for_completion it will signal Task2 and will return to dispatcher.
    image
    But during dispatching, there will be no wait at all because of the previous signal:
    image
    Hence, Task1 will spin on these steps: signal, wait, signal, wait, signal, wait.... on its own thread handle. So Task1 will never wait (just skip waiting because of the previously signal), so Task1 will never sleep so FreeRTOS will never returned to scheduler to give the possibility to Task2 to wake up and complete his job.

I really suggest to revert back the change and I will add the config LV_USE_TASK_NOTIFICATION under LV_USE_FREETOS to let it configurable by user.
If used want, he can switch back to the semaphores implementation.
If user want to stay with task notification then he need to be aware that task notification is unidirectional. It is what the name says.

@liamHowatt

Copy link
Copy Markdown
Contributor Author

I'm looking at the code you're talking about. I think lv_draw_dispatch_wait_for_request will block the next time it's called. It should block until the next lv_draw_dispatch_request.

I don't think lv_draw_dispatch_wait_for_request will return immediately every time while being called in a loop. If the signal was already sent, yes, it will return immediately. But the next time it will block at ulTaskNotifyTake until another lv_draw_dispatch_request is called from Task2 (the GPU).

@nicusorcitu

Copy link
Copy Markdown
Contributor

Exactly that is the case, the sync goes first then wait will return immediately. So It will create a loop in dispatcher.

All the user need to do is to keep in mind that the sync point means that the thread handle pxCond->xTaskToNotify is the task that waits. Any other task can signal it to unblock. This already is functioning on LVGL, there are 2 sync points for signaling in both direction:

Let's say Task1 is the LVGL and Task2 is the GPU unit.
Task1 have _draw_info.sync to know when it has to dispatch again.
Task2 have u.sync to know when to process a task.

Please also see the example in FreeRTOS: https://www.freertos.org/Documentation/02-Kernel/04-API-references/05-Direct-to-task-notifications/01-xTaskNotifyGive

I will prepare a patch and will push it to github on PR #6793

@liamHowatt

liamHowatt commented Sep 11, 2024 •

Copy link
Copy Markdown
Contributor Author

Exactly that is the case, the sync goes first then wait will return immediately. So It will create a loop in dispatcher.

It would block at the next call, though. No? xSyncSignal is reset to pdFALSE so at most it can only return immediately once and then block the next time. How does it become an infinite loop?

lv_result_t lv_thread_sync_wait(lv_thread_sync_t * pxCond)
{
    lv_result_t lvRes = LV_RESULT_OK;

    /* If the cond is uninitialized, perform initialization. */
    prvCheckCondInit(pxCond);

#if USE_FREERTOS_TASK_NOTIFY
    TaskHandle_t current_task_handle = xTaskGetCurrentTaskHandle();

    _enter_critical();
    BaseType_t signal_sent = pxCond->xSyncSignal;
    pxCond->xSyncSignal = pdFALSE;
    if(signal_sent == pdFALSE) {
        /* The signal hasn't been sent yet. Tell the sender to notify this task */
        pxCond->xTaskToNotify = current_task_handle;
    }
    /* If we have a signal from the other task, we should not ask to be notified */
    _exit_critical();

    if(signal_sent == pdFALSE) {
        /* Wait for other task to notify this task. */
        ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
    }
    /* If the signal was received, no wait needs to be done */
#else
    /* ... */
#endif

    return lvRes;
}

nicusorcitu added a commit to nxp-mcuxpresso/lvgl that referenced this pull request Sep 11, 2024
@nicusorcitu

Copy link
Copy Markdown
Contributor

I will loop because the signal will always come first in this order: signal, wait, signal, wait, signal, wait....

@liamHowatt

Copy link
Copy Markdown
Contributor Author

So it's not spinning in an infinite loop in one task. It's switching between tasks. What's wrong with signal, wait, signal, wait, signal, wait?

@nicusorcitu

Copy link
Copy Markdown
Contributor

Both lv_draw_dispatch_request() and lv_draw_dispatch() are called by the same thread, LVGL main thread, the one that dispatch tasks.
Is like the LVGL thread signals itself. Is the way the dispatcher works.

@liamHowatt

Copy link
Copy Markdown
Contributor Author

Ok I see. Hmm.

@nicusorcitu

Copy link
Copy Markdown
Contributor

Please see the PR #6793
I also introduced the possibility for the user to configure the synchronization way (notification task or semaphore).

@liamHowatt

liamHowatt commented Sep 11, 2024 •

Copy link
Copy Markdown
Contributor Author

It looks like draw drivers are supposed to provide a wait_for_finish_cb which is called in lv_draw_wait_for_finish to trigger the context switch if they have their own threads. Looks like vglite is the only one that has a wait_for_finish_cb. draw_sw doesn't have a wait_for_finish_cb. I think it's a bit strange that we are relying on the signal to always context switch even if the thread is signalling itself.

How did the old implementation work? How does a high priority task trigger a context switch to a lower priority task by the high priority task sending a signal to itself?

@nicusorcitu

Copy link
Copy Markdown
Contributor

Units does not mandatory need to have wait_for_finish_cb. Indeed this is only used by VGLite to increase the performance.
But the signal to the task itself was there from the beginning lv_draw_dispatch_request, I only introduced the call to signal the VGLite to complete.
image

In any case, please don't try to change the scope of the task notify. It is what it is, a task notification who can be used in one way. That is what the comment says from the beginning on the implementation:

* RTOS task notifications can only be used when there is only one task that can be the recipient of the event.

It is by design to do so. I gave you an FreeRTOS example to clearly show how it should work on synchronization between two tasks.

Comment thread src/osal/lv_freertos.c
}
/* If we have a signal from the other task, we should not ask to be notified */
_exit_critical();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After exiting from critical section the pxCond->xSyncSignal might get changed, so this is not thread safe.

Comment thread src/osal/lv_freertos.c
}
/* If a task is already waiting, there is no need to set the sync signal */
_exit_critical();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here, you exit from critical section but still rely on the task_to_notify. Not thread safe.

@nicusorcitu

nicusorcitu commented Dec 2, 2024 •

Copy link
Copy Markdown
Contributor

@cosmindanielradu19 @cristian-stoica
This PR generated another task synchronization issue with both VGLite draw and PXP screen rotation enabled.
I still believe we should get back to the original implementation where a single task can wait and a single task can signal.

I really suggest to revert back the change and I will add the config LV_USE_TASK_NOTIFICATION under LV_USE_FREETOS to let it configurable by user.
If used want, he can switch back to the semaphores implementation.
If user want to stay with task notification then he need to be aware that task notification is unidirectional. It is what the name says.

@kisvegabor

kisvegabor commented Dec 3, 2024 •

Copy link
Copy Markdown
Member

@nicusorcitu Please open a PR to see the proposed changes. @liamHowatt, you were more involved into this issue, please take a look on @nicusorcitu's comment.

@nicusorcitu

Copy link
Copy Markdown
Contributor

I do not have a fix yet, neither time to look at it right now. But I will try a patch till 20Dec. I will let you know both about it.

@liamHowatt

Copy link
Copy Markdown
Contributor Author

I would like to understand what's wrong with the fix I did. You raised some concerns in the PR during review. Can you reiterate the ones that you still believe are potential causes of instability? I truly believe the parts you flagged as thread-unsafe are thread-safe. Can we begin reviewing those changes, starting with a specific bug?

@cristian-stoica

cristian-stoica commented Dec 5, 2024 •

Copy link
Copy Markdown
Contributor

@liamHowatt I'm looking at a situation when running lv_demo_benchmark with both VGLITE and PXP enabled (SW draw unit = 0). Tests run as expected until rotated_argb_image_cb when the screen turns black and app stops. Debugging shows the code is still running in a dispatch-execute loop without any progress at all. I'm not sure what is actually going on. What I've also tried is disabling TASK_NOTIFY and the application runs. I can reproduce the issue under MCUX when running from flash (LVGL 9.2.1).
It's strange because I've had reproducibility issues when running the project built with different compilers IAR, MCUX and running under debugger (no breakpoints) or without it.

@nicusorcitu

nicusorcitu commented Dec 5, 2024 •

Copy link
Copy Markdown
Contributor

The issue we see works just fine with semaphore implementation. It hangs only if we use LV_USE_FREERTOS_TASK_NOTIFY.

I truly believe the parts you flagged as thread-unsafe are thread-safe. Can we begin reviewing those changes, starting with a specific bug?

lv_result_t lv_thread_sync_wait(lv_thread_sync_t * pxCond)
{
    lv_result_t lvRes = LV_RESULT_OK;

    /* If the cond is uninitialized, perform initialization. */
    prvCheckCondInit(pxCond);

#if LV_USE_FREERTOS_TASK_NOTIFY
    TaskHandle_t xCurrentTaskHandle = xTaskGetCurrentTaskHandle();

    _enter_critical();
    BaseType_t xSyncSygnal = pxCond->xSyncSignal; ---> This might be TRUE
    pxCond->xSyncSignal = pdFALSE; ---> Becoming FALSE
    if(xSyncSygnal == pdFALSE) {
        /* The signal hasn't been sent yet. Tell the sender to notify this task */
        pxCond->xTaskToNotify = xCurrentTaskHandle;
    }
    /* If we have a signal from the other task, we should not ask to be notified */
    _exit_critical();

    if(xSyncSygnal == pdFALSE) { ---> Another Thread might just set pxCond->xSyncSignal = pdTRUE so this check no longer represent the present state
        /* Wait for other task to notify this task. */
        ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
    }
    /* If the signal was received, no wait needs to be done */
#else

I will try to do some debugs but can't have right now, I will let you know when I have something.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

lv_timer_handler hangs when running on separate thread on ESP32 using FREERTOS using Arduino framework

5 participants