xref: /netbsd-src/external/mpl/bind/dist/lib/isc/condition.c (revision bcda20f65a8566e103791ec395f7f499ef322704)
1 /*	$NetBSD: condition.c,v 1.3 2025/01/26 16:25:36 christos Exp $	*/
2 
3 /*
4  * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
5  *
6  * SPDX-License-Identifier: MPL-2.0
7  *
8  * This Source Code Form is subject to the terms of the Mozilla Public
9  * License, v. 2.0. If a copy of the MPL was not distributed with this
10  * file, you can obtain one at https://mozilla.org/MPL/2.0/.
11  *
12  * See the COPYRIGHT file distributed with this work for additional
13  * information regarding copyright ownership.
14  */
15 
16 /*! \file */
17 
18 #include <errno.h>
19 
20 #include <isc/condition.h>
21 #include <isc/strerr.h>
22 #include <isc/string.h>
23 #include <isc/time.h>
24 #include <isc/util.h>
25 
26 isc_result_t
27 isc__condition_waituntil(pthread_cond_t *c, pthread_mutex_t *m, isc_time_t *t) {
28 	int presult;
29 	isc_result_t result;
30 	struct timespec ts;
31 
32 	REQUIRE(c != NULL && m != NULL && t != NULL);
33 
34 	/*
35 	 * POSIX defines a timespec's tv_sec as time_t.
36 	 */
37 	result = isc_time_secondsastimet(t, &ts.tv_sec);
38 
39 	/*
40 	 * If we have a range error ts.tv_sec is most probably a signed
41 	 * 32 bit value.  Set ts.tv_sec to INT_MAX.  This is a kludge.
42 	 */
43 	if (result == ISC_R_RANGE) {
44 		ts.tv_sec = INT_MAX;
45 	} else if (result != ISC_R_SUCCESS) {
46 		return result;
47 	}
48 
49 	/*!
50 	 * POSIX defines a timespec's tv_nsec as long.  isc_time_nanoseconds
51 	 * ensures its return value is < 1 billion, which will fit in a long.
52 	 */
53 	ts.tv_nsec = (long)isc_time_nanoseconds(t);
54 
55 	do {
56 		presult = pthread_cond_timedwait(c, m, &ts);
57 		if (presult == 0) {
58 			return ISC_R_SUCCESS;
59 		}
60 		if (presult == ETIMEDOUT) {
61 			return ISC_R_TIMEDOUT;
62 		}
63 	} while (presult == EINTR);
64 
65 	UNEXPECTED_SYSERROR(presult, "pthread_cond_timedwait()");
66 	return ISC_R_UNEXPECTED;
67 }
68