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

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

commit 179d720ac4493c202b90c567fa0526884f1c88cd
Author: Marco Casaroli <[email protected]>
AuthorDate: Thu Oct 22 09:23:21 2026 +0200

    libs/libc/pthread: Implement spin locks with atomics.
    
    pthread_spin_*() needed CONFIG_SPINLOCK and, outside a flat build,
    BOARDCTL: every lock and unlock was a boardctl(BOARDIOC_SPINLOCK) call,
    so a system call in protected and kernel builds.
    
    Implement the functions in libc with an atomic compare-and-swap on the
    lock word (nuttx/atomic.h), so they need no system call.  A waiting
    thread only reads the lock word, and calls sched_yield() after 100
    reads with CONFIG_SMP and after each read without it, so that the holder
    can run.  The lock word is an atomic_t, so
    PTHREAD_PROCESS_SHARED also works.  pthread_spin_unlock() by a thread
    that does not hold the lock returns EPERM also in a debug build, and
    pthread_spin_init() returns EINVAL for a pshared value that is not
    valid.  Add the functions to libc.csv.
    
    CONFIG_PTHREAD_SPINLOCKS no longer needs CONFIG_SPINLOCK and
    CONFIG_BOARDCTL, and no longer selects CONFIG_BOARDCTL_SPINLOCK.  Outside
    a flat build the atomic operations run in user mode.  LIBC_ATOMIC_IRQ
    and LIBC_ATOMIC_HWSPINLOCK disable the interrupts, which user mode
    cannot do, so there the option needs LIBC_ATOMIC_TOOLCHAIN or
    LIBC_ATOMIC_ARCH.
    
    Assisted-by: Claude Code:claude-opus-5-5
    Signed-off-by: Marco Casaroli <[email protected]>
---
 include/pthread.h                    |  16 +--
 libs/libc/libc.csv                   |   5 +
 libs/libc/pthread/Kconfig            |  15 ++-
 libs/libc/pthread/pthread_spinlock.c | 234 ++++++++++-------------------------
 4 files changed, 85 insertions(+), 185 deletions(-)

diff --git a/include/pthread.h b/include/pthread.h
index 846df728944..9dfdb0b4e01 100644
--- a/include/pthread.h
+++ b/include/pthread.h
@@ -40,17 +40,7 @@
 #include <time.h>            /* Needed for struct timespec */
 
 #ifdef CONFIG_PTHREAD_SPINLOCKS
-/* The architecture specific spinlock.h header file must provide the
- * following:
- *
- *   SP_LOCKED   - A definition of the locked state value (usually 1)
- *   SP_UNLOCKED - A definition of the unlocked state value (usually 0)
- *   spinlock_t  - The type of a spinlock memory object.
- *
- * SP_LOCKED and SP_UNLOCKED must constants of type spinlock_t.
- */
-
-#  include <nuttx/spinlock_type.h>
+#  include <nuttx/atomic.h>  /* atomic_t, the lock word of a spin lock */
 #endif
 
 /****************************************************************************
@@ -435,9 +425,7 @@ typedef struct pthread_rwlock_s pthread_rwlock_t;
 
 struct pthread_spinlock_s
 {
-  volatile spinlock_t sp_lock;  /* Indicates if the spinlock is locked or
-                                 * not.  See the values SP_LOCKED and
-                                 * SP_UNLOCKED. */
+  atomic_t sp_lock;             /* 1 if locked, 0 if not */
   pthread_t sp_holder;          /* ID of the thread that holds the spinlock */
 };
 #  ifndef __PTHREAD_SPINLOCK_T_DEFINED
diff --git a/libs/libc/libc.csv b/libs/libc/libc.csv
index cfe57826d7c..9f1053cbc51 100644
--- a/libs/libc/libc.csv
+++ b/libs/libc/libc.csv
@@ -274,6 +274,11 @@
 
"pthread_self","pthread.h","!defined(CONFIG_DISABLE_PTHREAD)","pthread_t","void"
 
"pthread_setname_np","pthread.h","!defined(CONFIG_DISABLE_PTHREAD)","int","pthread_t","const
 char *"
 "pthread_setspecific","pthread.h","!defined(CONFIG_DISABLE_PTHREAD) && 
CONFIG_TLS_NELEM > 0","int","pthread_key_t","FAR const void *"
+"pthread_spin_destroy","pthread.h","!defined(CONFIG_DISABLE_PTHREAD) && 
defined(CONFIG_PTHREAD_SPINLOCKS)","int","FAR pthread_spinlock_t *"
+"pthread_spin_init","pthread.h","!defined(CONFIG_DISABLE_PTHREAD) && 
defined(CONFIG_PTHREAD_SPINLOCKS)","int","FAR pthread_spinlock_t *","int"
+"pthread_spin_lock","pthread.h","!defined(CONFIG_DISABLE_PTHREAD) && 
defined(CONFIG_PTHREAD_SPINLOCKS)","int","FAR pthread_spinlock_t *"
+"pthread_spin_trylock","pthread.h","!defined(CONFIG_DISABLE_PTHREAD) && 
defined(CONFIG_PTHREAD_SPINLOCKS)","int","FAR pthread_spinlock_t *"
+"pthread_spin_unlock","pthread.h","!defined(CONFIG_DISABLE_PTHREAD) && 
defined(CONFIG_PTHREAD_SPINLOCKS)","int","FAR pthread_spinlock_t *"
 "pthread_yield","pthread.h","!defined(CONFIG_DISABLE_PTHREAD)","void"
 "putenv","stdlib.h","!defined(CONFIG_DISABLE_ENVIRON)","int","FAR char *"
 "puts","stdio.h","defined(CONFIG_FILE_STREAM)","int","FAR const IPTR char *"
diff --git a/libs/libc/pthread/Kconfig b/libs/libc/pthread/Kconfig
index 70aad3ea3bd..9d13096606f 100644
--- a/libs/libc/pthread/Kconfig
+++ b/libs/libc/pthread/Kconfig
@@ -9,10 +9,19 @@ menu "pthread support"
 config PTHREAD_SPINLOCKS
        bool "pthread spinlock support"
        default n
-       depends on SPINLOCK && (BUILD_FLAT || BOARDCTL)
-       select BOARDCTL_SPINLOCK
+       depends on BUILD_FLAT || LIBC_ATOMIC_TOOLCHAIN || LIBC_ATOMIC_ARCH
        ---help---
-               Enable support for pthread spinlocks.
+               Enable support for pthread spinlocks (pthread_spin_init() and
+               the other pthread_spin_*() functions).  A spin lock is an atomic
+               variable in the memory of the program: lock and unlock need no
+               system call, also in protected and kernel builds.
+
+               Outside a flat build, the atomic operations must work in user
+               mode.  LIBC_ATOMIC_IRQ and LIBC_ATOMIC_HWSPINLOCK disable the
+               interrupts, which user mode cannot do.
+
+               Prefer a mutex: a spin lock only helps on SMP, with very short
+               critical sections.
 
 config PTHREAD_ATFORK
        bool "pthread_atfork support"
diff --git a/libs/libc/pthread/pthread_spinlock.c 
b/libs/libc/pthread/pthread_spinlock.c
index 465dbab5f39..63d8b911c7f 100644
--- a/libs/libc/pthread/pthread_spinlock.c
+++ b/libs/libc/pthread/pthread_spinlock.c
@@ -26,17 +26,11 @@
 
 #include <nuttx/config.h>
 
-#include <sys/types.h>
-#include <sys/boardctl.h>
-#include <nuttx/spinlock.h>
-
-#include <assert.h>
 #include <errno.h>
-#include <nuttx/debug.h>
 #include <pthread.h>
 #include <sched.h>
 
-#ifdef CONFIG_PTHREAD_SPINLOCKS
+#include <nuttx/atomic.h>
 
 /****************************************************************************
  * Pre-processor Definitions
@@ -44,6 +38,16 @@
 
 #define IMPOSSIBLE_THREAD ((pthread_t)-1)
 
+/* Number of tests of a busy lock before the thread yields the CPU.  With
+ * one CPU the holder cannot run while this thread spins: yield at once.
+ */
+
+#ifdef CONFIG_SMP
+#  define SPIN_TRIES      100
+#else
+#  define SPIN_TRIES      1
+#endif
+
 /****************************************************************************
  * Public Functions
  ****************************************************************************/
@@ -52,267 +56,161 @@
  * Name: pthread_spin_init
  *
  * Description:
- *   The pthread_spin_init() function will allocate any resources required
- *   to use the spin lock referenced by lock and initialize the lock to an
- *   unlocked state.
- *
- *   The results are undefined if pthread_spin_init() is called specifying
- *   an already initialized spin lock. The results are undefined if a spin
- *   lock is used without first being initialized.
- *
- *   If the pthread_spin_init() function fails, the lock is not initialized
- *   and the contents of lock are undefined.
- *
- *   Only the object referenced by lock may be used for performing
- *   synchronization.  The result of referring to copies of that object in
- *   calls to pthread_spin_destroy(), pthread_spin_lock(),
- *   pthread_spin_trylock(), or pthread_spin_unlock() is undefined.
+ *   Initialize the spin lock to the unlocked state.  The lock is an atomic
+ *   variable, so it also works in memory that processes share
+ *   (PTHREAD_PROCESS_SHARED).
  *
  * Input Parameters:
- *   lock - A reference to the spinlock object to be initialized.
- *   pshared - Unused
+ *   lock    - A reference to the spinlock object to be initialized.
+ *   pshared - PTHREAD_PROCESS_PRIVATE or PTHREAD_PROCESS_SHARED
  *
  * Returned Value:
- *   Zero (OK) is returned if a valid lock value is provided.
- *
- * POSIX Compatibility:
- *   Not supported: "If the Thread Process-Shared Synchronization option is
- *   supported and the value of pshared is PTHREAD_PROCESS_SHARED, the
- *   implementation shall permit the spin lock to be operated upon by any
- *   thread that has access to the memory where the spin lock is allocated,
- *   even if it is allocated in memory that is shared by multiple
- *   processes."
+ *   Zero (OK) on success, EINVAL if an argument is not valid.
  *
  ****************************************************************************/
 
 int pthread_spin_init(FAR pthread_spinlock_t *lock, int pshared)
 {
-  int ret = EINVAL;
-
-  DEBUGASSERT(lock != NULL);
-  if (lock != NULL)
+  if (lock == NULL || (pshared != PTHREAD_PROCESS_PRIVATE &&
+                       pshared != PTHREAD_PROCESS_SHARED))
     {
-      spin_lock_init(&lock->sp_lock);
-      lock->sp_holder = IMPOSSIBLE_THREAD;
-      ret             = OK;
+      return EINVAL;
     }
 
-  return ret;
+  atomic_set(&lock->sp_lock, 0);
+  lock->sp_holder = IMPOSSIBLE_THREAD;
+  return OK;
 }
 
 /****************************************************************************
  * Name: pthread_spin_destroy
  *
  * Description:
- *   The pthread_spin_destroy() function will destroy the spin lock
- *   referenced by lock and release any resources used by the lock.  The
- *   effect of subsequent use of the lock is undefined until the lock is
- *   reinitialized by another call to pthread_spin_init(). The results are
- *   undefined if pthread_spin_destroy() is called when a thread holds the
- *   lock, or if this function is called with an uninitialized thread spin
- *   lock.
+ *   Destroy the spin lock.  A spin lock has no resources to release.
  *
  * Input Parameters:
- *   lock    - A reference to the spinlock object to be initialized.
- *   pshared - Unused
+ *   lock - A reference to the spinlock object.
  *
  * Returned Value:
  *   Zero (OK) is always returned.
  *
- * POSIX Compatibility:
- *   Not supported: "If the Thread Process-Shared Synchronization option is
- *   supported and the value of pshared is PTHREAD_PROCESS_SHARED, the
- *   implementation shall permit the spin lock to be operated upon by any
- *   thread that has access to the memory where the spin lock is allocated,
- *   even if it is allocated in memory that is shared by multiple
- *   processes."
- *
  ****************************************************************************/
 
-int pthread_spin_destroy(pthread_spinlock_t *lock)
+int pthread_spin_destroy(FAR pthread_spinlock_t *lock)
 {
   return OK;
 }
 
 /****************************************************************************
- * Name: pthread_spin_lock
+ * Name: pthread_spin_trylock
  *
  * Description:
- *   The pthread_spin_lock() function will lock the spin lock referenced by
- *   lock. The calling thread will acquire the lock if it is not held by
- *   another thread. Otherwise, the thread will spin (that is, will not
- *   return from the pthread_spin_lock() call) until the lock becomes
- *   available.
- *
- *   If it is determined the value specified by the lock argument to
- *   pthread_spin_lock() refers to a spin lock object for which the calling
- *   thread already holds the lock, it is recommended that the function will
- *   fail and report an EDEADLK error.
+ *   Lock the spin lock if no thread holds it.
  *
  * Input Parameters:
  *   lock - A reference to the spinlock object to lock.
  *
  * Returned Value:
- *   Zero is returned if the lock was successfully acquired.  Otherwise one
- *   of the following errno values are returned:
- *
- *   EINVAL    - 'lock' does not refer to a valid spinlock object
- *   EDEADLOCK - The caller already holds the spinlock
+ *   Zero if the lock was acquired; EINVAL if 'lock' is not valid; EBUSY if
+ *   a thread (also the caller) holds the lock.
  *
  ****************************************************************************/
 
-int pthread_spin_lock(pthread_spinlock_t *lock)
+int pthread_spin_trylock(FAR pthread_spinlock_t *lock)
 {
-  struct boardioc_spinlock_s spinlock;
-  pthread_t me = pthread_self();
-  int ret;
+  int32_t expected = 0;
 
-  DEBUGASSERT(lock != NULL);
   if (lock == NULL)
     {
       return EINVAL;
     }
-  else if (lock->sp_holder == me)
-    {
-      return EDEADLOCK;
-    }
-
-  spinlock.action = BOARDIOC_SPINLOCK_LOCK;
-  spinlock.lock = &lock->sp_lock;
-  spinlock.flags = NULL;
-  ret = boardctl(BOARDIOC_SPINLOCK, (uintptr_t)&spinlock);
 
-  /* Check for success (previous state was SP_UNLOCKED) */
-
-  if (ret == 0)
+  if (!atomic_cmpxchg_acquire(&lock->sp_lock, &expected, 1))
     {
-      lock->sp_holder = me;
+      return EBUSY;
     }
-  else
-    {
-      /* An error of some kind is the only other possibility */
 
-      DEBUGASSERT(ret < 0);
-      ret = get_errno();
-    }
-
-  return ret;
+  lock->sp_holder = pthread_self();
+  return OK;
 }
 
 /****************************************************************************
- * Name: pthread_spin_trylock
+ * Name: pthread_spin_lock
  *
  * Description:
- *   The pthread_spin_trylock() function will lock the spin lock referenced
- *   by lock. The calling thread will acquire the lock if it is not held by
- *   another thread. Otherwise, The pthread_spin_trylock() will return a
- *   failure.
+ *   Lock the spin lock.  The thread spins while another thread holds the
+ *   lock, and yields the CPU after SPIN_TRIES tests, so that a holder that
+ *   was preempted can run.
  *
  * Input Parameters:
  *   lock - A reference to the spinlock object to lock.
  *
  * Returned Value:
- *   Zero is returned if the lock was successfully acquired.  Otherwise one
- *   of the following errno values are returned:
- *
- *   EINVAL - 'lock' does not refer to a valid spinlock object
- *   EBUSY  - The spinlock is held by a thread, also by the caller
+ *   Zero if the lock was acquired; EINVAL if 'lock' is not valid; EDEADLK
+ *   if the caller already holds the lock.
  *
  ****************************************************************************/
 
-int pthread_spin_trylock(pthread_spinlock_t *lock)
+int pthread_spin_lock(FAR pthread_spinlock_t *lock)
 {
-  struct boardioc_spinlock_s spinlock;
-  pthread_t me = pthread_self();
-  int ret;
+  int tries = 0;
 
-  DEBUGASSERT(lock != NULL);
   if (lock == NULL)
     {
-      ret = EINVAL;
+      return EINVAL;
     }
-  else if (lock->sp_holder == me)
+
+  if (lock->sp_holder == pthread_self())
     {
-      ret = EBUSY;
+      return EDEADLK;
     }
-  else
+
+  while (pthread_spin_trylock(lock) != OK)
     {
-      /* Perform the test/set operation via boardctl() */
+      /* Wait with plain reads, not with atomic writes */
 
-      spinlock.action = BOARDIOC_SPINLOCK_TRYLOCK;
-      spinlock.lock = &lock->sp_lock;
-      spinlock.flags = NULL;
-      ret = boardctl(BOARDIOC_SPINLOCK, (uintptr_t)&spinlock);
-      if (ret == 0) /* Previously unlocked.  We hold the spinlock */
-        {
-          lock->sp_holder = me;
-        }
-      else /* Previously locked.  We did not get the spinlock  */
+      while (atomic_read(&lock->sp_lock) != 0)
         {
-          DEBUGASSERT(ret < 0);
-          ret = get_errno();
+          if (++tries >= SPIN_TRIES)
+            {
+              sched_yield();
+              tries = 0;
+            }
         }
     }
 
-  return ret;
+  return OK;
 }
 
 /****************************************************************************
  * Name: pthread_spin_unlock
  *
  * Description:
- *   The pthread_spin_unlock() function will release the spin lock
- *   referenced by lock which was locked via the pthread_spin_lock() or
- *   pthread_spin_trylock() functions.
- *
- *   The results are undefined if the lock is not held by the calling thread.
- *
- *   If there are threads spinning on the lock when pthread_spin_unlock() is
- *   called, the lock becomes available and an unspecified spinning thread
- *   will acquire the lock.
- *
- *   The results are undefined if this function is called with an
- *   uninitialized thread spin lock.
+ *   Release the spin lock that the caller holds.
  *
  * Input Parameters:
  *   lock - A reference to the spinlock object to unlock.
  *
  * Returned Value:
- *   Zero is returned if the lock was successfully released.  Otherwise one
- *   of the following errno values are returned:
- *
- *   EINVAL    - 'lock' does not refer to a valid spinlock object
- *   EPERM     - The caller does not hold the spinlock or it is not locked
+ *   Zero if the lock was released; EINVAL if 'lock' is not valid; EPERM if
+ *   the caller does not hold the lock.
  *
  ****************************************************************************/
 
-int pthread_spin_unlock(pthread_spinlock_t *lock)
+int pthread_spin_unlock(FAR pthread_spinlock_t *lock)
 {
-  struct boardioc_spinlock_s spinlock;
-  pthread_t me = pthread_self();
-
-  DEBUGASSERT(lock != NULL &&
-              spin_is_locked(&lock->sp_lock) &&
-              lock->sp_holder == me);
-
   if (lock == NULL)
     {
       return EINVAL;
     }
-  else if (!spin_is_locked(&lock->sp_lock) || lock->sp_holder != me)
+
+  if (atomic_read(&lock->sp_lock) == 0 ||
+      lock->sp_holder != pthread_self())
     {
       return EPERM;
     }
 
-  /* Release the lock */
-
   lock->sp_holder = IMPOSSIBLE_THREAD;
-  spinlock.action = BOARDIOC_SPINLOCK_UNLOCK;
-  spinlock.lock = &lock->sp_lock;
-  spinlock.flags = NULL;
-  boardctl(BOARDIOC_SPINLOCK, (uintptr_t)&spinlock);
-
+  atomic_set_release(&lock->sp_lock, 0);
   return OK;
 }
-
-#endif /* CONFIG_PTHREAD_SPINLOCKS */

Reply via email to