1 /* $NetBSD: condition.c,v 1.1 2024/02/18 20:57:56 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
isc_condition_waituntil(isc_condition_t * c,isc_mutex_t * m,isc_time_t * t)27 isc_condition_waituntil(isc_condition_t *c, isc_mutex_t *m, isc_time_t *t) {
28 int presult;
29 isc_result_t result;
30 struct timespec ts;
31 char strbuf[ISC_STRERRORSIZE];
32
33 REQUIRE(c != NULL && m != NULL && t != NULL);
34
35 /*
36 * POSIX defines a timespec's tv_sec as time_t.
37 */
38 result = isc_time_secondsastimet(t, &ts.tv_sec);
39
40 /*
41 * If we have a range error ts.tv_sec is most probably a signed
42 * 32 bit value. Set ts.tv_sec to INT_MAX. This is a kludge.
43 */
44 if (result == ISC_R_RANGE) {
45 ts.tv_sec = INT_MAX;
46 } else if (result != ISC_R_SUCCESS) {
47 return (result);
48 }
49
50 /*!
51 * POSIX defines a timespec's tv_nsec as long. isc_time_nanoseconds
52 * ensures its return value is < 1 billion, which will fit in a long.
53 */
54 ts.tv_nsec = (long)isc_time_nanoseconds(t);
55
56 do {
57 #if ISC_MUTEX_PROFILE
58 presult = pthread_cond_timedwait(c, &m->mutex, &ts);
59 #else /* if ISC_MUTEX_PROFILE */
60 presult = pthread_cond_timedwait(c, m, &ts);
61 #endif /* if ISC_MUTEX_PROFILE */
62 if (presult == 0) {
63 return (ISC_R_SUCCESS);
64 }
65 if (presult == ETIMEDOUT) {
66 return (ISC_R_TIMEDOUT);
67 }
68 } while (presult == EINTR);
69
70 strerror_r(presult, strbuf, sizeof(strbuf));
71 UNEXPECTED_ERROR(__FILE__, __LINE__,
72 "pthread_cond_timedwait() returned %s", strbuf);
73 return (ISC_R_UNEXPECTED);
74 }
75