An assembler implementation of seg_timedwait() for x86/x86_64 wrongly decrements the number of waiting threads stored in block of memory pointed by (sem_t *) when invalid nanosecond value is passed through the second argument. This is caused by jumping over the code, which increments (new_sem *)->nwaiters (because of wrong nanosecond argument) to the end of the seg_timedwait() function, where (new_sem *)->nwaiters is finally decremented. This breaks the subsequent semaphore operations. Please, see the `Additional info' for more details.
Version-Release number of selected component (if applicable):
RHEL5(2,3,4), Fedora 11, the newest upstream sources from ftp.gnu.org (2.10.1)
main: sem_timedwait: errno = 110 strerror = Connection timed out <<< --- it waits here until timeouts, even if the thread calls sem_post()
main: top of loop: sval = 1
main: calling sem_timedwait
main: sem_timedwait: success <<< --- passes
main: calling sem_post
$
If the value of nanosecond field is greater than 1000000000d, it directly jumps to the end of the function and executes the code which decrements the number of waiters, but remember the number of waiters wasn't incremented at the beginning.
addq $1, NWAITERS(%r12) <<< see this incrementation is after jump to 6:
...
6:
movq errno@gottpoff(%rip), %rdx
movl %r14d, %fs:(%rdx)
orl $-1, %eax
jmp 10b <<< jumping to 10:
...
10: LOCK
subq $1, NWAITERS(%r12) <<< we shouldn't increment here
addq $24, %rsp
.Laddq:
popq %r14
.Lpop_r14:
popq %r13
.Lpop_r13:
popq %r12
.Lpop_r12:
retq <<< end of sem_timedwait()
=== end of snip ===
If we move the incrementation of number of waiting threads before checking for the correct value of nanosecond field or change the logic of the code to not decrement the waiters, it works correctly.
The reason why the sem_post() doesn't work in the func() function is that, the sem_timedwait() decreases the number of waiters as described above and the sem_post() checks this value and if it is zero, it jumps over the code, which would otherwise wake the other threads: