FreeBSD/Linux Kernel Cross Reference
sys/kern/kern_clock.c
1 /*-
2 * Copyright (c) 1982, 1986, 1991, 1993
3 * The Regents of the University of California. All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 4. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 *
34 * @(#)kern_clock.c 8.5 (Berkeley) 1/21/94
35 */
36
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD: releng/6.4/sys/kern/kern_clock.c 179525 2008-06-03 18:51:53Z jhb $");
39
40 #include "opt_device_polling.h"
41 #include "opt_hwpmc_hooks.h"
42 #include "opt_ntp.h"
43 #include "opt_watchdog.h"
44
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/callout.h>
48 #include <sys/kdb.h>
49 #include <sys/kernel.h>
50 #include <sys/lock.h>
51 #include <sys/ktr.h>
52 #include <sys/mutex.h>
53 #include <sys/proc.h>
54 #include <sys/resource.h>
55 #include <sys/resourcevar.h>
56 #include <sys/sched.h>
57 #include <sys/signalvar.h>
58 #include <sys/smp.h>
59 #include <vm/vm.h>
60 #include <vm/pmap.h>
61 #include <vm/vm_map.h>
62 #include <sys/sysctl.h>
63 #include <sys/bus.h>
64 #include <sys/interrupt.h>
65 #include <sys/limits.h>
66 #include <sys/timetc.h>
67
68 #include <machine/cpu.h>
69
70 #ifdef GPROF
71 #include <sys/gmon.h>
72 #endif
73
74 #ifdef HWPMC_HOOKS
75 #include <sys/pmckern.h>
76 #endif
77
78 #ifdef DEVICE_POLLING
79 extern void hardclock_device_poll(void);
80 #endif /* DEVICE_POLLING */
81
82 static void initclocks(void *dummy);
83 SYSINIT(clocks, SI_SUB_CLOCKS, SI_ORDER_FIRST, initclocks, NULL)
84
85 long cp_time[CPUSTATES];
86
87 static int
88 sysctl_kern_cp_time(SYSCTL_HANDLER_ARGS)
89 {
90 int error;
91 #ifdef SCTL_MASK32
92 int i;
93 unsigned int cp_time32[CPUSTATES];
94 #endif
95
96 #ifdef SCTL_MASK32
97 if (req->flags & SCTL_MASK32) {
98 if (!req->oldptr)
99 return SYSCTL_OUT(req, 0, sizeof(cp_time32));
100 for (i = 0; i < CPUSTATES; i++)
101 cp_time32[i] = (unsigned int)cp_time[i];
102 error = SYSCTL_OUT(req, cp_time32, sizeof(cp_time32));
103 } else
104 #endif
105 {
106 if (!req->oldptr)
107 return SYSCTL_OUT(req, 0, sizeof(cp_time));
108 error = SYSCTL_OUT(req, cp_time, sizeof(cp_time));
109 }
110 return error;
111 }
112
113 SYSCTL_PROC(_kern, OID_AUTO, cp_time, CTLTYPE_LONG|CTLFLAG_RD,
114 0,0, sysctl_kern_cp_time, "LU", "CPU time statistics");
115
116 static long empty[CPUSTATES];
117
118 static int
119 sysctl_kern_cp_times(SYSCTL_HANDLER_ARGS)
120 {
121 struct pcpu *pcpu;
122 int error;
123 int c;
124 long *cp_time;
125 #ifdef SCTL_MASK32
126 unsigned int cp_time32[CPUSTATES];
127 int i;
128 #endif
129
130 if (!req->oldptr) {
131 #ifdef SCTL_MASK32
132 if (req->flags & SCTL_MASK32)
133 return SYSCTL_OUT(req, 0, sizeof(cp_time32) * (mp_maxid + 1));
134 else
135 #endif
136 return SYSCTL_OUT(req, 0, sizeof(long) * CPUSTATES * (mp_maxid + 1));
137 }
138 for (error = 0, c = 0; error == 0 && c <= mp_maxid; c++) {
139 if (!CPU_ABSENT(c)) {
140 pcpu = pcpu_find(c);
141 cp_time = pcpu->pc_cp_time;
142 } else {
143 cp_time = empty;
144 }
145 #ifdef SCTL_MASK32
146 if (req->flags & SCTL_MASK32) {
147 for (i = 0; i < CPUSTATES; i++)
148 cp_time32[i] = (unsigned int)cp_time[i];
149 error = SYSCTL_OUT(req, cp_time32, sizeof(cp_time32));
150 } else
151 #endif
152 error = SYSCTL_OUT(req, cp_time, sizeof(long) * CPUSTATES);
153 }
154 return error;
155 }
156
157 SYSCTL_PROC(_kern, OID_AUTO, cp_times, CTLTYPE_LONG|CTLFLAG_RD,
158 0,0, sysctl_kern_cp_times, "LU", "per-CPU time statistics");
159
160 void
161 read_cpu_time(long *cp_time)
162 {
163 struct pcpu *pc;
164 int i, j;
165
166 /* Sum up global cp_time[]. */
167 bzero(cp_time, sizeof(long) * CPUSTATES);
168 for (i = 0; i <= mp_maxid; i++) {
169 if (CPU_ABSENT(i))
170 continue;
171 pc = pcpu_find(i);
172 for (j = 0; j < CPUSTATES; j++)
173 cp_time[j] += pc->pc_cp_time[j];
174 }
175 }
176
177 #ifdef SW_WATCHDOG
178 #include <sys/watchdog.h>
179
180 static int watchdog_ticks;
181 static int watchdog_enabled;
182 static void watchdog_fire(void);
183 static void watchdog_config(void *, u_int, int *);
184 #endif /* SW_WATCHDOG */
185
186 /*
187 * Clock handling routines.
188 *
189 * This code is written to operate with two timers that run independently of
190 * each other.
191 *
192 * The main timer, running hz times per second, is used to trigger interval
193 * timers, timeouts and rescheduling as needed.
194 *
195 * The second timer handles kernel and user profiling,
196 * and does resource use estimation. If the second timer is programmable,
197 * it is randomized to avoid aliasing between the two clocks. For example,
198 * the randomization prevents an adversary from always giving up the cpu
199 * just before its quantum expires. Otherwise, it would never accumulate
200 * cpu ticks. The mean frequency of the second timer is stathz.
201 *
202 * If no second timer exists, stathz will be zero; in this case we drive
203 * profiling and statistics off the main clock. This WILL NOT be accurate;
204 * do not do it unless absolutely necessary.
205 *
206 * The statistics clock may (or may not) be run at a higher rate while
207 * profiling. This profile clock runs at profhz. We require that profhz
208 * be an integral multiple of stathz.
209 *
210 * If the statistics clock is running fast, it must be divided by the ratio
211 * profhz/stathz for statistics. (For profiling, every tick counts.)
212 *
213 * Time-of-day is maintained using a "timecounter", which may or may
214 * not be related to the hardware generating the above mentioned
215 * interrupts.
216 */
217
218 int stathz;
219 int profhz;
220 int profprocs;
221 int ticks;
222 int psratio;
223
224 /*
225 * Initialize clock frequencies and start both clocks running.
226 */
227 /* ARGSUSED*/
228 static void
229 initclocks(dummy)
230 void *dummy;
231 {
232 register int i;
233
234 /*
235 * Set divisors to 1 (normal case) and let the machine-specific
236 * code do its bit.
237 */
238 cpu_initclocks();
239
240 /*
241 * Compute profhz/stathz, and fix profhz if needed.
242 */
243 i = stathz ? stathz : hz;
244 if (profhz == 0)
245 profhz = i;
246 psratio = profhz / i;
247 #ifdef SW_WATCHDOG
248 EVENTHANDLER_REGISTER(watchdog_list, watchdog_config, NULL, 0);
249 #endif
250 }
251
252 /*
253 * Each time the real-time timer fires, this function is called on all CPUs.
254 * Note that hardclock() calls hardclock_process() for the boot CPU, so only
255 * the other CPUs in the system need to call this function.
256 */
257 void
258 hardclock_process(frame)
259 register struct clockframe *frame;
260 {
261 struct pstats *pstats;
262 struct thread *td = curthread;
263 struct proc *p = td->td_proc;
264
265 /*
266 * Run current process's virtual and profile time, as needed.
267 */
268 mtx_lock_spin_flags(&sched_lock, MTX_QUIET);
269 if (p->p_flag & P_SA) {
270 /* XXXKSE What to do? */
271 } else {
272 pstats = p->p_stats;
273 if (CLKF_USERMODE(frame) &&
274 timevalisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
275 itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0) {
276 p->p_sflag |= PS_ALRMPEND;
277 td->td_flags |= TDF_ASTPENDING;
278 }
279 if (timevalisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
280 itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0) {
281 p->p_sflag |= PS_PROFPEND;
282 td->td_flags |= TDF_ASTPENDING;
283 }
284 }
285 mtx_unlock_spin_flags(&sched_lock, MTX_QUIET);
286
287 #ifdef HWPMC_HOOKS
288 if (PMC_CPU_HAS_SAMPLES(PCPU_GET(cpuid)))
289 PMC_CALL_HOOK_UNLOCKED(curthread, PMC_FN_DO_SAMPLES, NULL);
290 #endif
291 }
292
293 /*
294 * The real-time timer, interrupting hz times per second.
295 */
296 void
297 hardclock(frame)
298 register struct clockframe *frame;
299 {
300 int need_softclock = 0;
301
302 CTR0(KTR_CLK, "hardclock fired");
303 hardclock_process(frame);
304
305 tc_ticktock();
306 /*
307 * If no separate statistics clock is available, run it from here.
308 *
309 * XXX: this only works for UP
310 */
311 if (stathz == 0) {
312 profclock(frame);
313 statclock(frame);
314 }
315
316 #ifdef DEVICE_POLLING
317 hardclock_device_poll(); /* this is very short and quick */
318 #endif /* DEVICE_POLLING */
319
320 /*
321 * Process callouts at a very low cpu priority, so we don't keep the
322 * relatively high clock interrupt priority any longer than necessary.
323 */
324 mtx_lock_spin_flags(&callout_lock, MTX_QUIET);
325 ticks++;
326 if (TAILQ_FIRST(&callwheel[ticks & callwheelmask]) != NULL) {
327 need_softclock = 1;
328 } else if (softticks + 1 == ticks)
329 ++softticks;
330 mtx_unlock_spin_flags(&callout_lock, MTX_QUIET);
331
332 /*
333 * swi_sched acquires sched_lock, so we don't want to call it with
334 * callout_lock held; incorrect locking order.
335 */
336 if (need_softclock)
337 swi_sched(softclock_ih, 0);
338
339 #ifdef SW_WATCHDOG
340 if (watchdog_enabled > 0 && --watchdog_ticks <= 0)
341 watchdog_fire();
342 #endif /* SW_WATCHDOG */
343 }
344
345 /*
346 * Compute number of ticks in the specified amount of time.
347 */
348 int
349 tvtohz(tv)
350 struct timeval *tv;
351 {
352 register unsigned long ticks;
353 register long sec, usec;
354
355 /*
356 * If the number of usecs in the whole seconds part of the time
357 * difference fits in a long, then the total number of usecs will
358 * fit in an unsigned long. Compute the total and convert it to
359 * ticks, rounding up and adding 1 to allow for the current tick
360 * to expire. Rounding also depends on unsigned long arithmetic
361 * to avoid overflow.
362 *
363 * Otherwise, if the number of ticks in the whole seconds part of
364 * the time difference fits in a long, then convert the parts to
365 * ticks separately and add, using similar rounding methods and
366 * overflow avoidance. This method would work in the previous
367 * case but it is slightly slower and assumes that hz is integral.
368 *
369 * Otherwise, round the time difference down to the maximum
370 * representable value.
371 *
372 * If ints have 32 bits, then the maximum value for any timeout in
373 * 10ms ticks is 248 days.
374 */
375 sec = tv->tv_sec;
376 usec = tv->tv_usec;
377 if (usec < 0) {
378 sec--;
379 usec += 1000000;
380 }
381 if (sec < 0) {
382 #ifdef DIAGNOSTIC
383 if (usec > 0) {
384 sec++;
385 usec -= 1000000;
386 }
387 printf("tvotohz: negative time difference %ld sec %ld usec\n",
388 sec, usec);
389 #endif
390 ticks = 1;
391 } else if (sec <= LONG_MAX / 1000000)
392 ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
393 / tick + 1;
394 else if (sec <= LONG_MAX / hz)
395 ticks = sec * hz
396 + ((unsigned long)usec + (tick - 1)) / tick + 1;
397 else
398 ticks = LONG_MAX;
399 if (ticks > INT_MAX)
400 ticks = INT_MAX;
401 return ((int)ticks);
402 }
403
404 /*
405 * Start profiling on a process.
406 *
407 * Kernel profiling passes proc0 which never exits and hence
408 * keeps the profile clock running constantly.
409 */
410 void
411 startprofclock(p)
412 register struct proc *p;
413 {
414
415 /*
416 * XXX; Right now sched_lock protects statclock(), but perhaps
417 * it should be protected later on by a time_lock, which would
418 * cover psdiv, etc. as well.
419 */
420 PROC_LOCK_ASSERT(p, MA_OWNED);
421 if (p->p_flag & P_STOPPROF)
422 return;
423 if ((p->p_flag & P_PROFIL) == 0) {
424 mtx_lock_spin(&sched_lock);
425 p->p_flag |= P_PROFIL;
426 if (++profprocs == 1)
427 cpu_startprofclock();
428 mtx_unlock_spin(&sched_lock);
429 }
430 }
431
432 /*
433 * Stop profiling on a process.
434 */
435 void
436 stopprofclock(p)
437 register struct proc *p;
438 {
439
440 PROC_LOCK_ASSERT(p, MA_OWNED);
441 if (p->p_flag & P_PROFIL) {
442 if (p->p_profthreads != 0) {
443 p->p_flag |= P_STOPPROF;
444 while (p->p_profthreads != 0)
445 msleep(&p->p_profthreads, &p->p_mtx, PPAUSE,
446 "stopprof", 0);
447 p->p_flag &= ~P_STOPPROF;
448 }
449 if ((p->p_flag & P_PROFIL) == 0)
450 return;
451 mtx_lock_spin(&sched_lock);
452 p->p_flag &= ~P_PROFIL;
453 if (--profprocs == 0)
454 cpu_stopprofclock();
455 mtx_unlock_spin(&sched_lock);
456 }
457 }
458
459 /*
460 * Statistics clock. Grab profile sample, and if divider reaches 0,
461 * do process and kernel statistics. Most of the statistics are only
462 * used by user-level statistics programs. The main exceptions are
463 * ke->ke_uticks, p->p_rux.rux_sticks, p->p_rux.rux_iticks, and p->p_estcpu.
464 * This should be called by all active processors.
465 */
466 void
467 statclock(frame)
468 register struct clockframe *frame;
469 {
470 struct rusage *ru;
471 struct vmspace *vm;
472 struct thread *td;
473 struct proc *p;
474 long rss;
475 long *pcp_time;
476
477 td = curthread;
478 p = td->td_proc;
479
480 mtx_lock_spin_flags(&sched_lock, MTX_QUIET);
481 pcp_time = (long *)PCPU_PTR(cp_time);
482 if (CLKF_USERMODE(frame)) {
483 /*
484 * Charge the time as appropriate.
485 */
486 if (p->p_flag & P_SA)
487 thread_statclock(1);
488 p->p_rux.rux_uticks++;
489 if (p->p_nice > NZERO) {
490 cp_time[CP_NICE]++;
491 pcp_time[CP_NICE]++;
492 } else {
493 cp_time[CP_USER]++;
494 pcp_time[CP_USER]++;
495 }
496 } else {
497 /*
498 * Came from kernel mode, so we were:
499 * - handling an interrupt,
500 * - doing syscall or trap work on behalf of the current
501 * user process, or
502 * - spinning in the idle loop.
503 * Whichever it is, charge the time as appropriate.
504 * Note that we charge interrupts to the current process,
505 * regardless of whether they are ``for'' that process,
506 * so that we know how much of its real time was spent
507 * in ``non-process'' (i.e., interrupt) work.
508 */
509 if ((td->td_pflags & TDP_ITHREAD) ||
510 td->td_intr_nesting_level >= 2) {
511 p->p_rux.rux_iticks++;
512 cp_time[CP_INTR]++;
513 pcp_time[CP_INTR]++;
514 } else {
515 if (p->p_flag & P_SA)
516 thread_statclock(0);
517 td->td_sticks++;
518 p->p_rux.rux_sticks++;
519 if (td != PCPU_GET(idlethread)) {
520 cp_time[CP_SYS]++;
521 pcp_time[CP_SYS]++;
522 } else {
523 cp_time[CP_IDLE]++;
524 pcp_time[CP_IDLE]++;
525 }
526 }
527 }
528 CTR4(KTR_SCHED, "statclock: %p(%s) prio %d stathz %d",
529 td, td->td_proc->p_comm, td->td_priority, (stathz)?stathz:hz);
530
531 sched_clock(td);
532
533 /* Update resource usage integrals and maximums. */
534 MPASS(p->p_stats != NULL);
535 MPASS(p->p_vmspace != NULL);
536 vm = p->p_vmspace;
537 ru = &p->p_stats->p_ru;
538 ru->ru_ixrss += pgtok(vm->vm_tsize);
539 ru->ru_idrss += pgtok(vm->vm_dsize);
540 ru->ru_isrss += pgtok(vm->vm_ssize);
541 rss = pgtok(vmspace_resident_count(vm));
542 if (ru->ru_maxrss < rss)
543 ru->ru_maxrss = rss;
544 mtx_unlock_spin_flags(&sched_lock, MTX_QUIET);
545 }
546
547 void
548 profclock(frame)
549 register struct clockframe *frame;
550 {
551 struct thread *td;
552 #ifdef GPROF
553 struct gmonparam *g;
554 int i;
555 #endif
556
557 td = curthread;
558 if (CLKF_USERMODE(frame)) {
559 /*
560 * Came from user mode; CPU was in user state.
561 * If this process is being profiled, record the tick.
562 * if there is no related user location yet, don't
563 * bother trying to count it.
564 */
565 if (td->td_proc->p_flag & P_PROFIL)
566 addupc_intr(td, CLKF_PC(frame), 1);
567 }
568 #ifdef GPROF
569 else {
570 /*
571 * Kernel statistics are just like addupc_intr, only easier.
572 */
573 g = &_gmonparam;
574 if (g->state == GMON_PROF_ON) {
575 i = CLKF_PC(frame) - g->lowpc;
576 if (i < g->textsize) {
577 i /= HISTFRACTION * sizeof(*g->kcount);
578 g->kcount[i]++;
579 }
580 }
581 }
582 #endif
583 }
584
585 /*
586 * Return information about system clocks.
587 */
588 static int
589 sysctl_kern_clockrate(SYSCTL_HANDLER_ARGS)
590 {
591 struct clockinfo clkinfo;
592 /*
593 * Construct clockinfo structure.
594 */
595 bzero(&clkinfo, sizeof(clkinfo));
596 clkinfo.hz = hz;
597 clkinfo.tick = tick;
598 clkinfo.profhz = profhz;
599 clkinfo.stathz = stathz ? stathz : hz;
600 return (sysctl_handle_opaque(oidp, &clkinfo, sizeof clkinfo, req));
601 }
602
603 SYSCTL_PROC(_kern, KERN_CLOCKRATE, clockrate, CTLTYPE_STRUCT|CTLFLAG_RD,
604 0, 0, sysctl_kern_clockrate, "S,clockinfo",
605 "Rate and period of various kernel clocks");
606
607 #ifdef SW_WATCHDOG
608
609 static void
610 watchdog_config(void *unused __unused, u_int cmd, int *error)
611 {
612 u_int u;
613
614 u = cmd & WD_INTERVAL;
615 if (u >= WD_TO_1SEC) {
616 watchdog_ticks = (1 << (u - WD_TO_1SEC)) * hz;
617 watchdog_enabled = 1;
618 *error = 0;
619 } else {
620 watchdog_enabled = 0;
621 }
622 }
623
624 /*
625 * Handle a watchdog timeout by dumping interrupt information and
626 * then either dropping to DDB or panicing.
627 */
628 static void
629 watchdog_fire(void)
630 {
631 int nintr;
632 u_int64_t inttotal;
633 u_long *curintr;
634 char *curname;
635
636 curintr = intrcnt;
637 curname = intrnames;
638 inttotal = 0;
639 nintr = eintrcnt - intrcnt;
640
641 printf("interrupt total\n");
642 while (--nintr >= 0) {
643 if (*curintr)
644 printf("%-12s %20lu\n", curname, *curintr);
645 curname += strlen(curname) + 1;
646 inttotal += *curintr++;
647 }
648 printf("Total %20ju\n", (uintmax_t)inttotal);
649
650 #ifdef KDB
651 kdb_backtrace();
652 kdb_enter("watchdog timeout");
653 #else
654 panic("watchdog timeout");
655 #endif /* KDB */
656 }
657
658 #endif /* SW_WATCHDOG */
Cache object: 592b3c40a6239f373e454ba2cb3b5955
|