ARMv8 64位共享内存LIFO原子操作汇编实现正确性问询
Fixed Implementation
Here's the corrected code with explanations for each change:
Corrected atomic_lifo_init
First, fix the init function to properly return a status code (your original code had no return statement for an int function, which is undefined behavior):
typedef union { void * head[1]; } lifo; int atomic_lifo_init(lifo * h) { if (h) { h->head[0] = NULL; return 0; // Success } return -1; // Error: invalid input }
Corrected atomic_lifo_delete
inline void * atomic_lifo_delete(lifo *h) { void *ret = NULL; void *tmp = NULL; int stxr_status; // Dedicated 32-bit variable for STXR return status asm volatile ("\n" "2: ldxr %0, [%2] // Load current head pointer into ret\n" " cbz %0, 3f // Exit if LIFO is empty (ret is NULL)\n" " ldr %1, [%0] // Load ret->next (new head candidate) into tmp\n" " stxr %w3, %1, [%2] // Try to store tmp as new head; status in w3\n" " cbnz %w3, 2b // Retry the loop if STXR failed\n" "3:\n" : "=&r" (ret), "=&r" (tmp), "=&r" (stxr_status) : "r" (h) : "memory" ); return ret; }
Key Fixes:
- Added a dedicated
int stxr_statusvariable to hold the 32-bit STXR result, avoiding register reuse issues. - Used
%w3to target the 32-bit subset of the register for the status, matching STXR's return type.
Corrected atomic_lifo_insert
void atomic_lifo_insert(lifo *h, void *__new) { void *next = NULL; int stxr_status; // Dedicated variable for STXR status asm volatile ("\n" "1: ldxr %1, [%2] // Load current head into next\n" " str %1, [%3] // Set __new->next = next (follows your node structure convention)\n" " stxr %w0, %3, [%2] // Try to update head to __new; status in w0\n" " cbnz %w0, 1b // Retry if STXR failed\n" : "=&r" (stxr_status), "=&r" (next) : "r" (h), "r" (__new) : "memory" ); }
Key Fixes:
- Replaced the
void* flagwith anint stxr_statusto correctly hold the 32-bit STXR return value. - Ensured no register reuse breaks the retry logic.
Additional Notes
- Memory Clobber: The
"memory"clobber in both asm blocks is correct—it tells the compiler not to reorder memory operations around the atomic sequence, which is critical for LL/SC correctness. - Node Structure Convention: Your requirement that each node's first member is a
nextpointer works perfectly here, sinceldr %1, [%0]andstr %1, [%3]directly access that first pointer. - LL/SC Semantics: The retry loops (
2band1b) correctly handle cases where another core modified the head pointer between LDXR and STXR, which is exactly how LL/SC is supposed to work.
内容的提问来源于stack exchange,提问作者souradeep
相关产品推荐
相关产品推荐

