1/*
2 * Copyright (c) 2000-2007 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28/* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
29/*-
30 * Copyright (c) 1982, 1986, 1991, 1993
31 *	The Regents of the University of California.  All rights reserved.
32 * (c) UNIX System Laboratories, Inc.
33 * All or some portions of this file are derived from material licensed
34 * to the University of California by American Telephone and Telegraph
35 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
36 * the permission of UNIX System Laboratories, Inc.
37 *
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
40 * are met:
41 * 1. Redistributions of source code must retain the above copyright
42 *    notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 *    notice, this list of conditions and the following disclaimer in the
45 *    documentation and/or other materials provided with the distribution.
46 * 3. All advertising materials mentioning features or use of this software
47 *    must display the following acknowledgement:
48 *	This product includes software developed by the University of
49 *	California, Berkeley and its contributors.
50 * 4. Neither the name of the University nor the names of its contributors
51 *    may be used to endorse or promote products derived from this software
52 *    without specific prior written permission.
53 *
54 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64 * SUCH DAMAGE.
65 *
66 *	@(#)kern_clock.c	8.5 (Berkeley) 1/21/94
67 */
68/*
69 * HISTORY
70 */
71
72#include <machine/spl.h>
73
74#include <sys/param.h>
75#include <sys/systm.h>
76#include <sys/time.h>
77#include <sys/resourcevar.h>
78#include <sys/kernel.h>
79#include <sys/resource.h>
80#include <sys/proc_internal.h>
81#include <sys/vm.h>
82#include <sys/sysctl.h>
83
84#ifdef GPROF
85#include <sys/gmon.h>
86#endif
87
88#include <kern/thread.h>
89#include <kern/ast.h>
90#include <kern/assert.h>
91#include <mach/boolean.h>
92
93#include <kern/thread_call.h>
94
95void bsd_uprofil(struct time_value *syst, user_addr_t pc);
96int tvtohz(struct timeval *tv);
97
98/*
99 * Clock handling routines.
100 *
101 * This code is written to operate with two timers which run
102 * independently of each other. The main clock, running at hz
103 * times per second, is used to do scheduling and timeout calculations.
104 * The second timer does resource utilization estimation statistically
105 * based on the state of the machine phz times a second. Both functions
106 * can be performed by a single clock (ie hz == phz), however the
107 * statistics will be much more prone to errors. Ideally a machine
108 * would have separate clocks measuring time spent in user state, system
109 * state, interrupt state, and idle state. These clocks would allow a non-
110 * approximate measure of resource utilization.
111 */
112
113/*
114 * The hz hardware interval timer.
115 */
116
117int             hz = 100;                /* GET RID OF THIS !!! */
118int             tick = (1000000 / 100);  /* GET RID OF THIS !!! */
119
120/*
121 * Kernel timeout services.
122 */
123
124/*
125 *	Set a timeout.
126 *
127 *	fcn:		function to call
128 *	param:		parameter to pass to function
129 *	interval:	timeout interval, in hz.
130 */
131void
132timeout(
133	timeout_fcn_t			fcn,
134	void					*param,
135	int						interval)
136{
137	uint64_t		deadline;
138
139	clock_interval_to_deadline(interval, NSEC_PER_SEC / hz, &deadline);
140	thread_call_func_delayed((thread_call_func_t)fcn, param, deadline);
141}
142
143/*
144 * Cancel a timeout.
145 */
146void
147untimeout(
148	timeout_fcn_t		fcn,
149	void			*param)
150{
151	thread_call_func_cancel((thread_call_func_t)fcn, param, FALSE);
152}
153
154
155/*
156 *	Set a timeout.
157 *
158 *	fcn:		function to call
159 *	param:		parameter to pass to function
160 *	ts:		timeout interval, in timespec
161 */
162void
163bsd_timeout(
164	timeout_fcn_t			fcn,
165	void					*param,
166	struct timespec         *ts)
167{
168	uint64_t		deadline = 0;
169
170	if (ts && (ts->tv_sec || ts->tv_nsec)) {
171		nanoseconds_to_absolutetime((uint64_t)ts->tv_sec * NSEC_PER_SEC + ts->tv_nsec,  &deadline );
172		clock_absolutetime_interval_to_deadline( deadline, &deadline );
173	}
174	thread_call_func_delayed((thread_call_func_t)fcn, param, deadline);
175}
176
177/*
178 * Cancel a timeout.
179 */
180void
181bsd_untimeout(
182	timeout_fcn_t		fcn,
183	void			*param)
184{
185	thread_call_func_cancel((thread_call_func_t)fcn, param, FALSE);
186}
187
188
189/*
190 * Compute number of hz until specified time.
191 * Used to compute third argument to timeout() from an
192 * absolute time.
193 */
194int
195hzto(struct timeval *tv)
196{
197	struct timeval now;
198	long ticks;
199	long sec;
200
201	microtime(&now);
202	/*
203	 * If number of milliseconds will fit in 32 bit arithmetic,
204	 * then compute number of milliseconds to time and scale to
205	 * ticks.  Otherwise just compute number of hz in time, rounding
206	 * times greater than representible to maximum value.
207	 *
208	 * Delta times less than 25 days can be computed ``exactly''.
209	 * Maximum value for any timeout in 10ms ticks is 250 days.
210	 */
211	sec = tv->tv_sec - now.tv_sec;
212	if (sec <= 0x7fffffff / 1000 - 1000)
213		ticks = ((tv->tv_sec - now.tv_sec) * 1000 +
214			(tv->tv_usec - now.tv_usec) / 1000)
215				/ (tick / 1000);
216	else if (sec <= 0x7fffffff / hz)
217		ticks = sec * hz;
218	else
219		ticks = 0x7fffffff;
220
221	return (ticks);
222}
223
224/*
225 * Return information about system clocks.
226 */
227static int
228sysctl_clockrate
229(__unused struct sysctl_oid *oidp, __unused void *arg1, __unused int arg2, __unused struct sysctl_req *req)
230{
231	struct clockinfo clkinfo;
232
233	/*
234	 * Construct clockinfo structure.
235	 */
236	clkinfo.hz = hz;
237	clkinfo.tick = tick;
238	clkinfo.profhz = hz;
239	clkinfo.stathz = hz;
240	return sysctl_io_opaque(req, &clkinfo, sizeof(clkinfo), NULL);
241}
242
243SYSCTL_PROC(_kern, KERN_CLOCKRATE, clockrate,
244		CTLTYPE_STRUCT | CTLFLAG_RD,
245		0, 0, sysctl_clockrate, "S,clockinfo", "");
246
247
248/*
249 * Compute number of ticks in the specified amount of time.
250 */
251int
252tvtohz(struct timeval *tv)
253{
254	unsigned long ticks;
255	long sec, usec;
256
257	/*
258	 * If the number of usecs in the whole seconds part of the time
259	 * difference fits in a long, then the total number of usecs will
260	 * fit in an unsigned long.  Compute the total and convert it to
261	 * ticks, rounding up and adding 1 to allow for the current tick
262	 * to expire.  Rounding also depends on unsigned long arithmetic
263	 * to avoid overflow.
264	 *
265	 * Otherwise, if the number of ticks in the whole seconds part of
266	 * the time difference fits in a long, then convert the parts to
267	 * ticks separately and add, using similar rounding methods and
268	 * overflow avoidance.  This method would work in the previous
269	 * case but it is slightly slower and assumes that hz is integral.
270	 *
271	 * Otherwise, round the time difference down to the maximum
272	 * representable value.
273	 *
274	 * If ints have 32 bits, then the maximum value for any timeout in
275	 * 10ms ticks is 248 days.
276	 */
277	sec = tv->tv_sec;
278	usec = tv->tv_usec;
279	if (usec < 0) {
280		sec--;
281		usec += 1000000;
282	}
283	if (sec < 0) {
284#ifdef DIAGNOSTIC
285		if (usec > 0) {
286			sec++;
287			usec -= 1000000;
288		}
289		printf("tvotohz: negative time difference %ld sec %ld usec\n",
290		       sec, usec);
291#endif
292		ticks = 1;
293	} else if (sec <= LONG_MAX / 1000000)
294		ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
295			/ tick + 1;
296	else if (sec <= LONG_MAX / hz)
297		ticks = sec * hz
298			+ ((unsigned long)usec + (tick - 1)) / tick + 1;
299	else
300		ticks = LONG_MAX;
301	if (ticks > INT_MAX)
302		ticks = INT_MAX;
303	return ((int)ticks);
304}
305
306
307/*
308 * Start profiling on a process.
309 *
310 * Kernel profiling passes kernel_proc which never exits and hence
311 * keeps the profile clock running constantly.
312 */
313void
314startprofclock(struct proc *p)
315{
316	if ((p->p_flag & P_PROFIL) == 0)
317		OSBitOrAtomic(P_PROFIL, (UInt32 *)&p->p_flag);
318}
319
320/*
321 * Stop profiling on a process.
322 */
323void
324stopprofclock(struct proc *p)
325{
326	if (p->p_flag & P_PROFIL)
327		OSBitAndAtomic(~((uint32_t)P_PROFIL), (UInt32 *)&p->p_flag);
328}
329
330/* TBD locking user profiling is not resolved yet */
331void
332bsd_uprofil(struct time_value *syst, user_addr_t pc)
333{
334	struct proc *p = current_proc();
335	int		ticks;
336	struct timeval	*tv;
337	struct timeval st;
338
339	if (p == NULL)
340	        return;
341	if ( !(p->p_flag & P_PROFIL))
342	        return;
343
344	st.tv_sec = syst->seconds;
345	st.tv_usec = syst->microseconds;
346
347	tv = &(p->p_stats->p_ru.ru_stime);
348
349	ticks = ((tv->tv_sec - st.tv_sec) * 1000 +
350		(tv->tv_usec - st.tv_usec) / 1000) /
351		(tick / 1000);
352	if (ticks)
353		addupc_task(p, pc, ticks);
354}
355
356/* TBD locking user profiling is not resolved yet */
357void
358get_procrustime(time_value_t *tv)
359{
360	struct proc *p = current_proc();
361	struct timeval st;
362
363	if (p == NULL)
364		return;
365	if ( !(p->p_flag & P_PROFIL))
366	        return;
367
368	//proc_lock(p);
369	st = p->p_stats->p_ru.ru_stime;
370	//proc_unlock(p);
371
372	tv->seconds = st.tv_sec;
373	tv->microseconds = st.tv_usec;
374}
375