This is an automated email from the ASF dual-hosted git repository.

acassis pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/nuttx.git

commit ae4d25eecdf0a111dde76726a88a625065e6c44e
Author: Marco Casaroli <[email protected]>
AuthorDate: Thu Nov 26 17:33:19 2026 +0100

    sched/wqueue: Do not enter the critical section with the queue lock.
    
    On SMP, the work queue held wqueue->lock while it called
    wd_start_abstick(), wd_cancel() and nxsem_post().  These functions
    enter the critical section.  Code in the critical section (task exit,
    drivers, watchdog callbacks) calls work_queue() and work_cancel(),
    which take wqueue->lock.  Two CPUs could take the two locks in the
    opposite order and wait for each other forever.
    
    Remove the edge from wqueue->lock to the critical section:
    
    - With CONFIG_HRTIMER, the work queue timer is an hrtimer.
      hrtimer_start() and hrtimer_cancel() take only the hrtimer lock,
      which never takes the critical section or wqueue->lock.  The timer
      callback runs without the hrtimer lock and only posts the semaphore.
      work_queue_free() waits for a running callback with
      hrtimer_cancel_sync().
    - work_queue() posts the semaphore after it releases wqueue->lock.
      Preemption stays disabled until the post is done, so the post is not
      delayed.  On SMP, a counter keeps the semaphore alive until the post
      is done, and work_queue_free() waits for it.
    - A worker wakes the other workers and the work_cancel_sync() waiters
      after it releases wqueue->lock.  The worker keeps the queue alive.
    
    Zero-delay work does not go through the timer: without
    CONFIG_SCHED_TICKLESS an hrtimer expires only at the next tick.
    
    Without CONFIG_HRTIMER the timer is still a watchdog timer, and
    wd_start_abstick() still enters the critical section with
    wqueue->lock held.  An SMP system that queues or cancels work in the
    critical section must enable CONFIG_HRTIMER.
    
    The hrtimer design is from Fix-Point in apache/nuttx#22164.
    
    Assisted-by: Claude Code:claude-opus-5-5
    Signed-off-by: Marco Casaroli <[email protected]>
---
 sched/wqueue/kwork_queue.c  | 23 +++++++++---
 sched/wqueue/kwork_thread.c | 88 +++++++++++++++++++++++++++++++++++----------
 sched/wqueue/wqueue.h       | 78 +++++++++++++++++++++++++++++++++++++---
 3 files changed, 161 insertions(+), 28 deletions(-)

diff --git a/sched/wqueue/kwork_queue.c b/sched/wqueue/kwork_queue.c
index b7798f5bf94..2b0e4413a64 100644
--- a/sched/wqueue/kwork_queue.c
+++ b/sched/wqueue/kwork_queue.c
@@ -133,8 +133,7 @@ static int work_qqueue(FAR struct kwork_wqueue_s *wqueue,
           /* Start the timer if the work is the earliest expired work. */
 
           retimer = false;
-          wd_start_abstick(&wqueue->timer, work->qtime,
-                           work_timer_expired, (wdparm_t)wqueue);
+          work_timer_start(wqueue, work->qtime);
         }
     }
   else
@@ -142,6 +141,12 @@ static int work_qqueue(FAR struct kwork_wqueue_s *wqueue,
       /* Insert to the expired list of the wqueue. */
 
       list_add_tail(&wqueue->expired, &work->node);
+
+#ifdef CONFIG_SMP
+      /* Keep the semaphore alive until the post below is done. */
+
+      atomic_add(&wqueue->nposting, 1);
+#endif
     }
 
   if (retimer)
@@ -149,14 +154,22 @@ static int work_qqueue(FAR struct kwork_wqueue_s *wqueue,
       work_timer_reset(wqueue);
     }
 
+  /* nxsem_post() can enter the critical section, and code in the critical
+   * section calls work_queue().  So post after the unlock.  Preemption
+   * stays disabled until the post is done.
+   */
+
+  spin_unlock_irqrestore(&wqueue->lock, flags);
+
   if (delay == 0)
     {
-      /* Post while the queue lock keeps the semaphore alive. */
-
       nxsem_post(&wqueue->sem);
+#ifdef CONFIG_SMP
+      atomic_sub(&wqueue->nposting, 1);
+#endif
     }
 
-  spin_unlock_irqrestore_nopreempt(&wqueue->lock, flags);
+  sched_unlock();
   return OK;
 }
 
diff --git a/sched/wqueue/kwork_thread.c b/sched/wqueue/kwork_thread.c
index 65652886032..4a721085f01 100644
--- a/sched/wqueue/kwork_thread.c
+++ b/sched/wqueue/kwork_thread.c
@@ -37,6 +37,7 @@
 #include <nuttx/debug.h>
 
 #include <nuttx/list.h>
+#include <nuttx/nuttx.h>
 #include <nuttx/wqueue.h>
 #include <nuttx/kthread.h>
 #include <nuttx/semaphore.h>
@@ -97,6 +98,23 @@ struct lp_wqueue_s g_lpwork;
  * Private Functions
  ****************************************************************************/
 
+/****************************************************************************
+ * Name: work_post
+ *
+ * Description:
+ *   Post a semaphore count times.  The caller must not hold wqueue->lock:
+ *   nxsem_post() can enter the critical section.
+ *
+ ****************************************************************************/
+
+static inline_function void work_post(FAR sem_t *sem, unsigned int count)
+{
+  while (count-- > 0)
+    {
+      nxsem_post(sem);
+    }
+}
+
 /****************************************************************************
  * Name: work_dispatch
  *
@@ -120,10 +138,13 @@ static inline_function bool work_dispatch(FAR struct 
kwork_wqueue_s *wqueue,
   FAR struct work_s *work;
   FAR struct work_s *next;
   unsigned int count = 0;
+  unsigned int nwake = 0;
+  unsigned int nwait = 0;
   clock_t      ticks = clock_systime_ticks();
   irqstate_t   flags;
   worker_t     worker;
   FAR void    *arg;
+  bool         exit = false;
 
   /* And check first entry in the work queue. Since we have disabled
    * interrupts we know:  (1) we will not be suspended unless we do
@@ -142,7 +163,7 @@ static inline_function bool work_dispatch(FAR struct 
kwork_wqueue_s *wqueue,
    * there might be expired work in the pending queue.
    */
 
-  if (!WDOG_ISACTIVE(&wqueue->timer))
+  if (!work_timer_isactive(wqueue))
     {
       /* Wake up the worker thread once there is expired work.
        * If some worker threads are busy, here the callback will
@@ -160,8 +181,7 @@ static inline_function bool work_dispatch(FAR struct 
kwork_wqueue_s *wqueue,
 
           if (!clock_compare(work->qtime, ticks))
             {
-              wd_start_abstick(&wqueue->timer, work->qtime,
-                               work_timer_expired, (wdparm_t)wqueue);
+              work_timer_start(wqueue, work->qtime);
               break;
             }
 
@@ -172,12 +192,12 @@ static inline_function bool work_dispatch(FAR struct 
kwork_wqueue_s *wqueue,
 
           /* Note that the thread execution this function is also
            * a worker thread, which has already been woken up by the timer.
-           * So only `count - 1` semaphore will be posted.
+           * So only `count - 1` semaphore will be posted, after the unlock.
            */
 
           if (count++ > 0)
             {
-              nxsem_post(&wqueue->sem);
+              nwake++;
             }
         }
     }
@@ -208,6 +228,14 @@ static inline_function bool work_dispatch(FAR struct 
kwork_wqueue_s *wqueue,
 
       spin_unlock_irqrestore_nopreempt(&wqueue->lock, flags);
 
+      /* Wake up the other workers and the waiters of the previous work
+       * without the queue lock.  This worker keeps the queue alive.
+       */
+
+      work_post(&wqueue->sem, nwake);
+      work_post(&kworker->wait, nwait);
+      nwake = 0;
+
       /* Do the work.  Re-enable interrupts while the work is being
        * performed... we don't have any idea how long this will take!
        */
@@ -221,23 +249,23 @@ static inline_function bool work_dispatch(FAR struct 
kwork_wqueue_s *wqueue,
 
       kworker->work = running;
 
-      /* Check if someone is waiting, if so, wakeup it */
+      /* Check if someone is waiting, if so, wake them up later */
 
-      while (kworker->wait_count > 0)
-        {
-          kworker->wait_count--;
-          nxsem_post(&kworker->wait);
-        }
+      nwait = kworker->wait_count;
+      kworker->wait_count = 0;
 
       if (wqueue->exit)
         {
-          spin_unlock_irqrestore_nopreempt(&wqueue->lock, flags);
-          return true;
+          exit = true;
+          break;
         }
     }
 
   spin_unlock_irqrestore_nopreempt(&wqueue->lock, flags);
-  return false;
+
+  work_post(&wqueue->sem, nwake);
+  work_post(&kworker->wait, nwait);
+  return exit;
 }
 
 /****************************************************************************
@@ -431,13 +459,27 @@ void work_queue_dispatch(FAR struct kwork_wqueue_s 
*wqueue)
  * Name: work_timer_expired
  *
  * Description:
- *   The wqueue timer callback.
+ *   The wqueue timer callback.  It runs without wqueue->lock.
  *
  * Input Parameters:
- *   arg  - The work queue.
+ *   arg/timer - The timer of the work queue.
  *
  ****************************************************************************/
 
+#ifdef CONFIG_HRTIMER
+uint64_t work_timer_expired(FAR const hrtimer_t *timer, uint64_t expired)
+{
+  FAR struct kwork_wqueue_s *wq =
+    container_of(timer, struct kwork_wqueue_s, timer);
+
+  UNUSED(expired);
+
+  /* Wake up at least one worker thread to dispatch the expired work. */
+
+  nxsem_post(&wq->sem);
+  return 0;
+}
+#else
 void work_timer_expired(wdparm_t arg)
 {
   /* The work time expired callback will wake up at least one worker thread
@@ -448,6 +490,7 @@ void work_timer_expired(wdparm_t arg)
 
   nxsem_post(&wq->sem);
 }
+#endif
 
 /****************************************************************************
  * Name: work_queue_create
@@ -580,9 +623,18 @@ int work_queue_free(FAR struct kwork_wqueue_s *wqueue)
 
   spin_unlock_irqrestore_nopreempt(&wqueue->lock, flags);
 
-  /* Stop delayed dispatch after new submissions have been disabled. */
+  /* Stop delayed dispatch after new submissions have been disabled, and
+   * wait for the timer callback and the posts of work_queue().
+   */
+
+  work_timer_cancel_sync(wqueue);
 
-  wd_cancel(&wqueue->timer);
+#ifdef CONFIG_SMP
+  while (atomic_read(&wqueue->nposting) != 0)
+    {
+      nxsched_usleep(USEC_PER_TICK);
+    }
+#endif
 
   /* Queue a exit work for all threads */
 
diff --git a/sched/wqueue/wqueue.h b/sched/wqueue/wqueue.h
index 2771fd4f48f..d5e99eead45 100644
--- a/sched/wqueue/wqueue.h
+++ b/sched/wqueue/wqueue.h
@@ -33,11 +33,16 @@
 #include <sys/types.h>
 #include <stdbool.h>
 
+#include <nuttx/atomic.h>
 #include <nuttx/clock.h>
 #include <nuttx/list.h>
 #include <nuttx/wqueue.h>
 #include <nuttx/spinlock.h>
 
+#ifdef CONFIG_HRTIMER
+#  include <nuttx/hrtimer.h>
+#endif
+
 #ifdef CONFIG_SCHED_WORKQUEUE
 
 /****************************************************************************
@@ -82,7 +87,14 @@ struct kwork_wqueue_s
   int              nthreads;  /* Number of worker threads */
   bool             exit;      /* A flag to request the thread to exit */
   bool             dynamic;   /* Dynamically allocated queue */
-  struct wdog_s    timer;     /* Timer to pending. */
+#ifdef CONFIG_SMP
+  atomic_t         nposting;  /* Wakeups posted after the unlock */
+#endif
+#ifdef CONFIG_HRTIMER
+  hrtimer_t        timer;     /* Timer of the pending queue */
+#else
+  struct wdog_s    timer;     /* Timer of the pending queue */
+#endif
 };
 
 /* This structure defines the state of one high-priority work queue.  This
@@ -278,11 +290,68 @@ bool work_remove(FAR struct kwork_wqueue_s *wqueue,
  *   The wqueue timer callback.
  *
  * Input Parameters:
- *   arg  - The work queue.
+ *   arg/timer - The timer of the work queue.
  *
  ****************************************************************************/
 
+#ifdef CONFIG_HRTIMER
+uint64_t work_timer_expired(FAR const hrtimer_t *timer, uint64_t expired);
+#else
 void work_timer_expired(wdparm_t arg);
+#endif
+
+/****************************************************************************
+ * Name: work_timer_isactive/work_timer_cancel/work_timer_cancel_sync
+ *
+ * Description:
+ *   Check whether the timer of the workqueue is pending, and cancel it.
+ *   work_timer_cancel_sync() also waits for a running timer callback.
+ *
+ ****************************************************************************/
+
+#ifdef CONFIG_HRTIMER
+#  define work_timer_isactive(wqueue) ((wqueue)->timer.func != NULL)
+#  define work_timer_cancel(wqueue)   hrtimer_cancel(&(wqueue)->timer)
+#  define work_timer_cancel_sync(wqueue) \
+     hrtimer_cancel_sync(&(wqueue)->timer)
+#else
+#  define work_timer_isactive(wqueue) WDOG_ISACTIVE(&(wqueue)->timer)
+#  define work_timer_cancel(wqueue)   wd_cancel(&(wqueue)->timer)
+#  define work_timer_cancel_sync(wqueue) wd_cancel(&(wqueue)->timer)
+#endif
+
+/****************************************************************************
+ * Name: work_timer_start
+ *
+ * Description:
+ *   Internal public function to start the timer of the workqueue at the
+ *   absolute tick of the first pending work.
+ *
+ *   With CONFIG_HRTIMER the timer is an hrtimer, which has its own lock.
+ *   So the caller can hold wqueue->lock: the order is always wqueue->lock
+ *   first, the hrtimer lock second.  wd_start_abstick() enters the
+ *   critical section instead.
+ *
+ * Input Parameters:
+ *   wqueue - The work queue.
+ *   qtime  - The absolute tick of the expiration.
+ *
+ * Returned Value:
+ *   None.
+ *
+ ****************************************************************************/
+
+static inline_function
+void work_timer_start(FAR struct kwork_wqueue_s *wqueue, clock_t qtime)
+{
+#ifdef CONFIG_HRTIMER
+  hrtimer_start(&wqueue->timer, work_timer_expired, TICK2NSEC(qtime),
+                HRTIMER_MODE_ABS);
+#else
+  wd_start_abstick(&wqueue->timer, qtime,
+                   work_timer_expired, (wdparm_t)wqueue);
+#endif
+}
 
 /****************************************************************************
  * Name: work_timer_reset
@@ -308,12 +377,11 @@ void work_timer_reset(FAR struct kwork_wqueue_s *wqueue)
 
       work = list_first_entry(&wqueue->pending, struct work_s, node);
 
-      wd_start_abstick(&wqueue->timer, work->qtime,
-                       work_timer_expired, (wdparm_t)wqueue);
+      work_timer_start(wqueue, work->qtime);
     }
   else
     {
-      wd_cancel(&wqueue->timer);
+      work_timer_cancel(wqueue);
     }
 }
 

Reply via email to