1 /*	$NetBSD: condition.c,v 1.5 2014/12/10 04:38:00 christos Exp $	*/
2 
3 /*
4  * Copyright (C) 2004, 2005, 2007, 2012  Internet Systems Consortium, Inc. ("ISC")
5  * Copyright (C) 1998-2001  Internet Software Consortium.
6  *
7  * Permission to use, copy, modify, and/or distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
12  * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13  * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
14  * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
15  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
16  * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
17  * PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 /* Id: condition.c,v 1.36 2007/06/19 23:47:18 tbox Exp  */
21 
22 /*! \file */
23 
24 #include <config.h>
25 
26 #include <errno.h>
27 
28 #include <isc/condition.h>
29 #include <isc/msgs.h>
30 #include <isc/strerror.h>
31 #include <isc/string.h>
32 #include <isc/time.h>
33 #include <isc/util.h>
34 
35 isc_result_t
36 isc_condition_waituntil(isc_condition_t *c, isc_mutex_t *m, isc_time_t *t) {
37 	int presult;
38 	isc_result_t result;
39 	struct timespec ts;
40 	char strbuf[ISC_STRERRORSIZE];
41 
42 	REQUIRE(c != NULL && m != NULL && t != NULL);
43 
44 	/*
45 	 * POSIX defines a timespec's tv_sec as time_t.
46 	 */
47 	result = isc_time_secondsastimet(t, &ts.tv_sec);
48 
49 	/*
50 	 * If we have a range error ts.tv_sec is most probably a signed
51 	 * 32 bit value.  Set ts.tv_sec to INT_MAX.  This is a kludge.
52 	 */
53 	if (result == ISC_R_RANGE)
54 		ts.tv_sec = INT_MAX;
55 	else if (result != ISC_R_SUCCESS)
56 		return (result);
57 
58 	/*!
59 	 * POSIX defines a timespec's tv_nsec as long.  isc_time_nanoseconds
60 	 * ensures its return value is < 1 billion, which will fit in a long.
61 	 */
62 	ts.tv_nsec = (long)isc_time_nanoseconds(t);
63 
64 	do {
65 #if ISC_MUTEX_PROFILE
66 		presult = pthread_cond_timedwait(c, &m->mutex, &ts);
67 #else
68 		presult = pthread_cond_timedwait(c, m, &ts);
69 #endif
70 		if (presult == 0)
71 			return (ISC_R_SUCCESS);
72 		if (presult == ETIMEDOUT)
73 			return (ISC_R_TIMEDOUT);
74 	} while (presult == EINTR);
75 
76 	isc__strerror(presult, strbuf, sizeof(strbuf));
77 	UNEXPECTED_ERROR(__FILE__, __LINE__,
78 			 "pthread_cond_timedwait() %s %s",
79 			 isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL,
80 					ISC_MSG_RETURNED, "returned"),
81 			 strbuf);
82 	return (ISC_R_UNEXPECTED);
83 }
84