Skip to content

Commit

Permalink
Fix mutex locking in _pkcs11h_threading_cond{Init,Wait} functions.
Browse files Browse the repository at this point in the history
According to pthread_cond_wait manpage, the mutex has to be locked by the same
thread that is going to call pthread_cond_wait afterwards. This was not true
before this change and was causing test-slotevent to busy-loop on FreeBSD.

Signed-off-by: Gleb Popov <[email protected]>
  • Loading branch information
arrowd committed Jan 22, 2024
1 parent 7326442 commit ce74e10
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions lib/pkcs11h-threading.c
Original file line number Diff line number Diff line change
Expand Up @@ -388,8 +388,7 @@ _pkcs11h_threading_condInit (
if (
(
pthread_mutex_init (&cond->mut, NULL) ||
pthread_cond_init (&cond->cond, NULL) ||
pthread_mutex_lock (&cond->mut)
pthread_cond_init (&cond->cond, NULL)
)
) {
rv = CKR_FUNCTION_FAILED;
Expand Down Expand Up @@ -423,7 +422,13 @@ _pkcs11h_threading_condWait (
goto cleanup;
}
#else
int unlock_mutex = 0;
if (milli == PKCS11H_COND_INFINITE) {
if (pthread_mutex_lock (&cond->mut)) {
rv = CKR_FUNCTION_FAILED;
goto cleanup;
}
unlock_mutex = 1;
if (pthread_cond_wait (&cond->cond, &cond->mut) ) {
rv = CKR_FUNCTION_FAILED;
goto cleanup;
Expand All @@ -441,6 +446,11 @@ _pkcs11h_threading_condWait (
timeout.tv_sec = now.tv_sec + milli/1000;
timeout.tv_nsec = now.tv_usec*1000 + milli%1000;

if (pthread_mutex_trylock (&cond->mut)) {
rv = CKR_FUNCTION_FAILED;
goto cleanup;
}
unlock_mutex = 1;
if (pthread_cond_timedwait (&cond->cond, &cond->mut, &timeout)) {
rv = CKR_FUNCTION_FAILED;
goto cleanup;
Expand All @@ -449,6 +459,9 @@ _pkcs11h_threading_condWait (
#endif
rv = CKR_OK;
cleanup:
if (unlock_mutex) {
pthread_mutex_unlock (&cond->mut);
}
return rv;
}

Expand Down

0 comments on commit ce74e10

Please sign in to comment.