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 48328edca06643468f15d585050d628fe8a86ba3
Author: wangjianyu3 <[email protected]>
AuthorDate: Thu Jun 11 12:25:00 2026 +0800

    include/nuttx/ring: fix ring_is_valid_cons for 24-bit index wrap
    
    ring_is_valid_cons compared the raw 32-bit signed difference of two
    indices, but ring indices are 24-bit free-running counters (RTS_IDX_MASK)
    that wrap at 2^24.  Near the wrap boundary the comparison is wrong: e.g.
    cons_index=0x000003 is actually ahead of cons_tail=0xfffffe, yet the plain
    signed difference is large and negative, so the macro misjudged live data
    as lapped.
    
    Shift the 24-bit difference left by 8 so bit 23 lines up with the 32-bit
    sign bit, turning the test into a correct modular "within half the 24-bit
    range" comparison.  Since the live window is bounded by capacity <=
    RING_SIZE_MAX (2^23), the half-range split exactly separates
    ahead-of-cons from lapped-behind-cons.
    
    Signed-off-by: wangjianyu3 <[email protected]>
---
 include/nuttx/ring.h | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)

diff --git a/include/nuttx/ring.h b/include/nuttx/ring.h
index b020df2fda9..57fbd7102c0 100644
--- a/include/nuttx/ring.h
+++ b/include/nuttx/ring.h
@@ -339,12 +339,13 @@
 #define ring_capacity(r)    (RING_BASE(r)->capacity)
 #define ring_space(r)       (ring_capacity(r) - ring_count(r))
 
-/* Check whether cons_index is still valid (not overwritten).
- * Returns true if cons_index >= current cons_tail (data still valid).
+/* Check whether cons_index is still live (not lapped by the writer).
+ * Indices are 24-bit (RTS_IDX_MASK); the << 8 aligns bit 23 with the
+ * 32-bit sign bit so the signed compare works correctly modulo 2^24.
  */
 
 #define ring_is_valid_cons(cons_index, cons_tail) \
-  ((int32_t)((cons_index) - (cons_tail)) >= 0)
+  ((int32_t)(((cons_index) - (cons_tail)) << 8) >= 0)
 
 /* Clamp an external index if it fell behind cons_tail (overwritten).
  * Returns the effective read position.

Reply via email to