xref: /titanic_50/usr/src/uts/common/syscall/alarm.c (revision ae115bc77f6fcde83175c75b4206dc2e50747966)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
23 /*	  All Rights Reserved	*/
24 
25 
26 /*
27  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
28  * Use is subject to license terms.
29  */
30 
31 #pragma ident	"%Z%%M%	%I%	%E% SMI"
32 
33 #include <sys/param.h>
34 #include <sys/types.h>
35 #include <sys/sysmacros.h>
36 #include <sys/systm.h>
37 #include <sys/errno.h>
38 #include <sys/signal.h>
39 #include <sys/proc.h>
40 #include <sys/time.h>
41 #include <sys/cmn_err.h>
42 #include <sys/debug.h>
43 
44 static void
45 sigalarm2proc(void *arg)
46 {
47 	proc_t *p = arg;
48 
49 	mutex_enter(&p->p_lock);
50 	p->p_alarmid = 0;
51 	sigtoproc(p, NULL, SIGALRM);
52 	mutex_exit(&p->p_lock);
53 }
54 
55 int
56 alarm(int deltat)
57 {
58 	proc_t *p = ttoproc(curthread);
59 	clock_t del = 0;
60 	clock_t ret;
61 	timeout_id_t tmp_id;
62 
63 	/*
64 	 * We must single-thread this code relative to other
65 	 * lwps in the same process also performing an alarm().
66 	 * The mutex dance in the while loop is necessary because
67 	 * we cannot call untimeout() while holding a lock that
68 	 * is grabbed by the timeout function, sigalarm2proc().
69 	 * We can, however, hold p->p_lock across realtime_timeout().
70 	 */
71 	mutex_enter(&p->p_lock);
72 	while ((tmp_id = p->p_alarmid) != 0) {
73 		p->p_alarmid = 0;
74 		mutex_exit(&p->p_lock);
75 		del = untimeout(tmp_id);
76 		mutex_enter(&p->p_lock);
77 	}
78 
79 	if (del < 0)
80 		ret = 0;
81 	else
82 		ret = (del + hz - 1) / hz;	/* convert to seconds */
83 
84 	/*
85 	 * Our implementation defined limit for alarm is
86 	 * INT_MAX / hz. Anything larger gets truncated
87 	 * to that limit. If deltat is negative we can
88 	 * assume a wrap has occurred so peg deltat in
89 	 * that case too.
90 	 */
91 	if (deltat > (INT_MAX / hz) || deltat < 0)
92 		deltat = INT_MAX / hz;
93 
94 	if (deltat)
95 		p->p_alarmid = realtime_timeout(sigalarm2proc, p, deltat * hz);
96 	mutex_exit(&p->p_lock);
97 	return (ret);
98 }
99