]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_clock.c
vn_copy_file_range(): provide ENOSYS fallback to vn_generic_copy_file_range()
[FreeBSD/FreeBSD.git] / sys / kern / kern_clock.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1991, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  * (c) UNIX System Laboratories, Inc.
7  * All or some portions of this file are derived from material licensed
8  * to the University of California by American Telephone and Telegraph
9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10  * the permission of UNIX System Laboratories, Inc.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *      @(#)kern_clock.c        8.5 (Berkeley) 1/21/94
37  */
38
39 #include <sys/cdefs.h>
40 #include "opt_kdb.h"
41 #include "opt_device_polling.h"
42 #include "opt_hwpmc_hooks.h"
43 #include "opt_ntp.h"
44 #include "opt_watchdog.h"
45
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/callout.h>
49 #include <sys/epoch.h>
50 #include <sys/eventhandler.h>
51 #include <sys/gtaskqueue.h>
52 #include <sys/kdb.h>
53 #include <sys/kernel.h>
54 #include <sys/kthread.h>
55 #include <sys/ktr.h>
56 #include <sys/lock.h>
57 #include <sys/mutex.h>
58 #include <sys/proc.h>
59 #include <sys/resource.h>
60 #include <sys/resourcevar.h>
61 #include <sys/sched.h>
62 #include <sys/sdt.h>
63 #include <sys/signalvar.h>
64 #include <sys/sleepqueue.h>
65 #include <sys/smp.h>
66 #include <vm/vm.h>
67 #include <vm/pmap.h>
68 #include <vm/vm_map.h>
69 #include <sys/sysctl.h>
70 #include <sys/bus.h>
71 #include <sys/interrupt.h>
72 #include <sys/limits.h>
73 #include <sys/timetc.h>
74
75 #ifdef GPROF
76 #include <sys/gmon.h>
77 #endif
78
79 #ifdef HWPMC_HOOKS
80 #include <sys/pmckern.h>
81 PMC_SOFT_DEFINE( , , clock, hard);
82 PMC_SOFT_DEFINE( , , clock, stat);
83 PMC_SOFT_DEFINE_EX( , , clock, prof, \
84     cpu_startprofclock, cpu_stopprofclock);
85 #endif
86
87 #ifdef DEVICE_POLLING
88 extern void hardclock_device_poll(void);
89 #endif /* DEVICE_POLLING */
90
91 /* Spin-lock protecting profiling statistics. */
92 static struct mtx time_lock;
93
94 SDT_PROVIDER_DECLARE(sched);
95 SDT_PROBE_DEFINE2(sched, , , tick, "struct thread *", "struct proc *");
96
97 static int
98 sysctl_kern_cp_time(SYSCTL_HANDLER_ARGS)
99 {
100         int error;
101         long cp_time[CPUSTATES];
102 #ifdef SCTL_MASK32
103         int i;
104         unsigned int cp_time32[CPUSTATES];
105 #endif
106
107         read_cpu_time(cp_time);
108 #ifdef SCTL_MASK32
109         if (req->flags & SCTL_MASK32) {
110                 if (!req->oldptr)
111                         return SYSCTL_OUT(req, 0, sizeof(cp_time32));
112                 for (i = 0; i < CPUSTATES; i++)
113                         cp_time32[i] = (unsigned int)cp_time[i];
114                 error = SYSCTL_OUT(req, cp_time32, sizeof(cp_time32));
115         } else
116 #endif
117         {
118                 if (!req->oldptr)
119                         return SYSCTL_OUT(req, 0, sizeof(cp_time));
120                 error = SYSCTL_OUT(req, cp_time, sizeof(cp_time));
121         }
122         return error;
123 }
124
125 SYSCTL_PROC(_kern, OID_AUTO, cp_time, CTLTYPE_LONG|CTLFLAG_RD|CTLFLAG_MPSAFE,
126     0,0, sysctl_kern_cp_time, "LU", "CPU time statistics");
127
128 static long empty[CPUSTATES];
129
130 static int
131 sysctl_kern_cp_times(SYSCTL_HANDLER_ARGS)
132 {
133         struct pcpu *pcpu;
134         int error;
135         int c;
136         long *cp_time;
137 #ifdef SCTL_MASK32
138         unsigned int cp_time32[CPUSTATES];
139         int i;
140 #endif
141
142         if (!req->oldptr) {
143 #ifdef SCTL_MASK32
144                 if (req->flags & SCTL_MASK32)
145                         return SYSCTL_OUT(req, 0, sizeof(cp_time32) * (mp_maxid + 1));
146                 else
147 #endif
148                         return SYSCTL_OUT(req, 0, sizeof(long) * CPUSTATES * (mp_maxid + 1));
149         }
150         for (error = 0, c = 0; error == 0 && c <= mp_maxid; c++) {
151                 if (!CPU_ABSENT(c)) {
152                         pcpu = pcpu_find(c);
153                         cp_time = pcpu->pc_cp_time;
154                 } else {
155                         cp_time = empty;
156                 }
157 #ifdef SCTL_MASK32
158                 if (req->flags & SCTL_MASK32) {
159                         for (i = 0; i < CPUSTATES; i++)
160                                 cp_time32[i] = (unsigned int)cp_time[i];
161                         error = SYSCTL_OUT(req, cp_time32, sizeof(cp_time32));
162                 } else
163 #endif
164                         error = SYSCTL_OUT(req, cp_time, sizeof(long) * CPUSTATES);
165         }
166         return error;
167 }
168
169 SYSCTL_PROC(_kern, OID_AUTO, cp_times, CTLTYPE_LONG|CTLFLAG_RD|CTLFLAG_MPSAFE,
170     0,0, sysctl_kern_cp_times, "LU", "per-CPU time statistics");
171
172 #ifdef DEADLKRES
173 static const char *blessed[] = {
174         "getblk",
175         "so_snd_sx",
176         "so_rcv_sx",
177         NULL
178 };
179 static int slptime_threshold = 1800;
180 static int blktime_threshold = 900;
181 static int sleepfreq = 3;
182
183 static void
184 deadlres_td_on_lock(struct proc *p, struct thread *td, int blkticks)
185 {
186         int tticks;
187
188         sx_assert(&allproc_lock, SX_LOCKED);
189         PROC_LOCK_ASSERT(p, MA_OWNED);
190         THREAD_LOCK_ASSERT(td, MA_OWNED);
191         /*
192          * The thread should be blocked on a turnstile, simply check
193          * if the turnstile channel is in good state.
194          */
195         MPASS(td->td_blocked != NULL);
196
197         tticks = ticks - td->td_blktick;
198         if (tticks > blkticks)
199                 /*
200                  * Accordingly with provided thresholds, this thread is stuck
201                  * for too long on a turnstile.
202                  */
203                 panic("%s: possible deadlock detected for %p (%s), "
204                     "blocked for %d ticks\n", __func__,
205                     td, sched_tdname(td), tticks);
206 }
207
208 static void
209 deadlres_td_sleep_q(struct proc *p, struct thread *td, int slpticks)
210 {
211         const void *wchan;
212         int i, slptype, tticks;
213
214         sx_assert(&allproc_lock, SX_LOCKED);
215         PROC_LOCK_ASSERT(p, MA_OWNED);
216         THREAD_LOCK_ASSERT(td, MA_OWNED);
217         /*
218          * Check if the thread is sleeping on a lock, otherwise skip the check.
219          * Drop the thread lock in order to avoid a LOR with the sleepqueue
220          * spinlock.
221          */
222         wchan = td->td_wchan;
223         tticks = ticks - td->td_slptick;
224         slptype = sleepq_type(wchan);
225         if ((slptype == SLEEPQ_SX || slptype == SLEEPQ_LK) &&
226             tticks > slpticks) {
227                 /*
228                  * Accordingly with provided thresholds, this thread is stuck
229                  * for too long on a sleepqueue.
230                  * However, being on a sleepqueue, we might still check for the
231                  * blessed list.
232                  */
233                 for (i = 0; blessed[i] != NULL; i++)
234                         if (!strcmp(blessed[i], td->td_wmesg))
235                                 return;
236
237                 panic("%s: possible deadlock detected for %p (%s), "
238                     "blocked for %d ticks\n", __func__,
239                     td, sched_tdname(td), tticks);
240         }
241 }
242
243 static void
244 deadlkres(void)
245 {
246         struct proc *p;
247         struct thread *td;
248         int blkticks, slpticks, tryl;
249
250         tryl = 0;
251         for (;;) {
252                 blkticks = blktime_threshold * hz;
253                 slpticks = slptime_threshold * hz;
254
255                 /*
256                  * Avoid to sleep on the sx_lock in order to avoid a
257                  * possible priority inversion problem leading to
258                  * starvation.
259                  * If the lock can't be held after 100 tries, panic.
260                  */
261                 if (!sx_try_slock(&allproc_lock)) {
262                         if (tryl > 100)
263                                 panic("%s: possible deadlock detected "
264                                     "on allproc_lock\n", __func__);
265                         tryl++;
266                         pause("allproc", sleepfreq * hz);
267                         continue;
268                 }
269                 tryl = 0;
270                 FOREACH_PROC_IN_SYSTEM(p) {
271                         PROC_LOCK(p);
272                         if (p->p_state == PRS_NEW) {
273                                 PROC_UNLOCK(p);
274                                 continue;
275                         }
276                         FOREACH_THREAD_IN_PROC(p, td) {
277                                 thread_lock(td);
278                                 if (TD_ON_LOCK(td))
279                                         deadlres_td_on_lock(p, td,
280                                             blkticks);
281                                 else if (TD_IS_SLEEPING(td))
282                                         deadlres_td_sleep_q(p, td,
283                                             slpticks);
284                                 thread_unlock(td);
285                         }
286                         PROC_UNLOCK(p);
287                 }
288                 sx_sunlock(&allproc_lock);
289
290                 /* Sleep for sleepfreq seconds. */
291                 pause("-", sleepfreq * hz);
292         }
293 }
294
295 static struct kthread_desc deadlkres_kd = {
296         "deadlkres",
297         deadlkres,
298         (struct thread **)NULL
299 };
300
301 SYSINIT(deadlkres, SI_SUB_CLOCKS, SI_ORDER_ANY, kthread_start, &deadlkres_kd);
302
303 static SYSCTL_NODE(_debug, OID_AUTO, deadlkres, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
304     "Deadlock resolver");
305 SYSCTL_INT(_debug_deadlkres, OID_AUTO, slptime_threshold, CTLFLAG_RWTUN,
306     &slptime_threshold, 0,
307     "Number of seconds within is valid to sleep on a sleepqueue");
308 SYSCTL_INT(_debug_deadlkres, OID_AUTO, blktime_threshold, CTLFLAG_RWTUN,
309     &blktime_threshold, 0,
310     "Number of seconds within is valid to block on a turnstile");
311 SYSCTL_INT(_debug_deadlkres, OID_AUTO, sleepfreq, CTLFLAG_RWTUN, &sleepfreq, 0,
312     "Number of seconds between any deadlock resolver thread run");
313 #endif  /* DEADLKRES */
314
315 void
316 read_cpu_time(long *cp_time)
317 {
318         struct pcpu *pc;
319         int i, j;
320
321         /* Sum up global cp_time[]. */
322         bzero(cp_time, sizeof(long) * CPUSTATES);
323         CPU_FOREACH(i) {
324                 pc = pcpu_find(i);
325                 for (j = 0; j < CPUSTATES; j++)
326                         cp_time[j] += pc->pc_cp_time[j];
327         }
328 }
329
330 #include <sys/watchdog.h>
331
332 static int watchdog_ticks;
333 static int watchdog_enabled;
334 static void watchdog_fire(void);
335 static void watchdog_config(void *, u_int, int *);
336
337 static void
338 watchdog_attach(void)
339 {
340         EVENTHANDLER_REGISTER(watchdog_list, watchdog_config, NULL, 0);
341 }
342
343 /*
344  * Clock handling routines.
345  *
346  * This code is written to operate with two timers that run independently of
347  * each other.
348  *
349  * The main timer, running hz times per second, is used to trigger interval
350  * timers, timeouts and rescheduling as needed.
351  *
352  * The second timer handles kernel and user profiling,
353  * and does resource use estimation.  If the second timer is programmable,
354  * it is randomized to avoid aliasing between the two clocks.  For example,
355  * the randomization prevents an adversary from always giving up the cpu
356  * just before its quantum expires.  Otherwise, it would never accumulate
357  * cpu ticks.  The mean frequency of the second timer is stathz.
358  *
359  * If no second timer exists, stathz will be zero; in this case we drive
360  * profiling and statistics off the main clock.  This WILL NOT be accurate;
361  * do not do it unless absolutely necessary.
362  *
363  * The statistics clock may (or may not) be run at a higher rate while
364  * profiling.  This profile clock runs at profhz.  We require that profhz
365  * be an integral multiple of stathz.
366  *
367  * If the statistics clock is running fast, it must be divided by the ratio
368  * profhz/stathz for statistics.  (For profiling, every tick counts.)
369  *
370  * Time-of-day is maintained using a "timecounter", which may or may
371  * not be related to the hardware generating the above mentioned
372  * interrupts.
373  */
374
375 int     stathz;
376 int     profhz;
377 int     profprocs;
378 volatile int    ticks;
379 int     psratio;
380
381 DPCPU_DEFINE_STATIC(int, pcputicks);    /* Per-CPU version of ticks. */
382 #ifdef DEVICE_POLLING
383 static int devpoll_run = 0;
384 #endif
385
386 /*
387  * Initialize clock frequencies and start both clocks running.
388  */
389 static void
390 initclocks(void *dummy __unused)
391 {
392         int i;
393
394         /*
395          * Set divisors to 1 (normal case) and let the machine-specific
396          * code do its bit.
397          */
398         mtx_init(&time_lock, "time lock", NULL, MTX_DEF);
399         cpu_initclocks();
400
401         /*
402          * Compute profhz/stathz, and fix profhz if needed.
403          */
404         i = stathz ? stathz : hz;
405         if (profhz == 0)
406                 profhz = i;
407         psratio = profhz / i;
408
409 #ifdef SW_WATCHDOG
410         /* Enable hardclock watchdog now, even if a hardware watchdog exists. */
411         watchdog_attach();
412 #else
413         /* Volunteer to run a software watchdog. */
414         if (wdog_software_attach == NULL)
415                 wdog_software_attach = watchdog_attach;
416 #endif
417 }
418 SYSINIT(clocks, SI_SUB_CLOCKS, SI_ORDER_FIRST, initclocks, NULL);
419
420 static __noinline void
421 hardclock_itimer(struct thread *td, struct pstats *pstats, int cnt, int usermode)
422 {
423         struct proc *p;
424         int flags;
425
426         flags = 0;
427         p = td->td_proc;
428         if (usermode &&
429             timevalisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value)) {
430                 PROC_ITIMLOCK(p);
431                 if (itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL],
432                     tick * cnt) == 0)
433                         flags |= TDF_ALRMPEND | TDF_ASTPENDING;
434                 PROC_ITIMUNLOCK(p);
435         }
436         if (timevalisset(&pstats->p_timer[ITIMER_PROF].it_value)) {
437                 PROC_ITIMLOCK(p);
438                 if (itimerdecr(&pstats->p_timer[ITIMER_PROF],
439                     tick * cnt) == 0)
440                         flags |= TDF_PROFPEND | TDF_ASTPENDING;
441                 PROC_ITIMUNLOCK(p);
442         }
443         if (flags != 0) {
444                 thread_lock(td);
445                 td->td_flags |= flags;
446                 thread_unlock(td);
447         }
448 }
449
450 void
451 hardclock(int cnt, int usermode)
452 {
453         struct pstats *pstats;
454         struct thread *td = curthread;
455         struct proc *p = td->td_proc;
456         int *t = DPCPU_PTR(pcputicks);
457         int global, i, newticks;
458
459         /*
460          * Update per-CPU and possibly global ticks values.
461          */
462         *t += cnt;
463         global = ticks;
464         do {
465                 newticks = *t - global;
466                 if (newticks <= 0) {
467                         if (newticks < -1)
468                                 *t = global - 1;
469                         newticks = 0;
470                         break;
471                 }
472         } while (!atomic_fcmpset_int(&ticks, &global, *t));
473
474         /*
475          * Run current process's virtual and profile time, as needed.
476          */
477         pstats = p->p_stats;
478         if (__predict_false(
479             timevalisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) ||
480             timevalisset(&pstats->p_timer[ITIMER_PROF].it_value)))
481                 hardclock_itimer(td, pstats, cnt, usermode);
482
483 #ifdef  HWPMC_HOOKS
484         if (PMC_CPU_HAS_SAMPLES(PCPU_GET(cpuid)))
485                 PMC_CALL_HOOK_UNLOCKED(curthread, PMC_FN_DO_SAMPLES, NULL);
486         if (td->td_intr_frame != NULL)
487                 PMC_SOFT_CALL_TF( , , clock, hard, td->td_intr_frame);
488 #endif
489         /* We are in charge to handle this tick duty. */
490         if (newticks > 0) {
491                 tc_ticktock(newticks);
492 #ifdef DEVICE_POLLING
493                 /* Dangerous and no need to call these things concurrently. */
494                 if (atomic_cmpset_acq_int(&devpoll_run, 0, 1)) {
495                         /* This is very short and quick. */
496                         hardclock_device_poll();
497                         atomic_store_rel_int(&devpoll_run, 0);
498                 }
499 #endif /* DEVICE_POLLING */
500                 if (watchdog_enabled > 0) {
501                         i = atomic_fetchadd_int(&watchdog_ticks, -newticks);
502                         if (i > 0 && i <= newticks)
503                                 watchdog_fire();
504                 }
505                 intr_event_handle(clk_intr_event, NULL);
506         }
507         if (curcpu == CPU_FIRST())
508                 cpu_tick_calibration();
509         if (__predict_false(DPCPU_GET(epoch_cb_count)))
510                 GROUPTASK_ENQUEUE(DPCPU_PTR(epoch_cb_task));
511 }
512
513 void
514 hardclock_sync(int cpu)
515 {
516         int *t;
517         KASSERT(!CPU_ABSENT(cpu), ("Absent CPU %d", cpu));
518         t = DPCPU_ID_PTR(cpu, pcputicks);
519
520         *t = ticks;
521 }
522
523 /*
524  * Regular integer scaling formula without losing precision:
525  */
526 #define TIME_INT_SCALE(value, mul, div) \
527         (((value) / (div)) * (mul) + (((value) % (div)) * (mul)) / (div))
528
529 /*
530  * Macro for converting seconds and microseconds into actual ticks,
531  * based on the given hz value:
532  */
533 #define TIME_TO_TICKS(sec, usec, hz) \
534         ((sec) * (hz) + TIME_INT_SCALE(usec, hz, 1 << 6) / (1000000 >> 6))
535
536 #define TIME_ASSERT_VALID_HZ(hz)        \
537         _Static_assert(TIME_TO_TICKS(INT_MAX / (hz) - 1, 999999, hz) >= 0 && \
538                        TIME_TO_TICKS(INT_MAX / (hz) - 1, 999999, hz) < INT_MAX, \
539                        "tvtohz() can overflow the regular integer type")
540
541 /*
542  * Compile time assert the maximum and minimum values to fit into a
543  * regular integer when computing TIME_TO_TICKS():
544  */
545 TIME_ASSERT_VALID_HZ(HZ_MAXIMUM);
546 TIME_ASSERT_VALID_HZ(HZ_MINIMUM);
547
548 /*
549  * The formula is mostly linear, but test some more common values just
550  * in case:
551  */
552 TIME_ASSERT_VALID_HZ(1024);
553 TIME_ASSERT_VALID_HZ(1000);
554 TIME_ASSERT_VALID_HZ(128);
555 TIME_ASSERT_VALID_HZ(100);
556
557 /*
558  * Compute number of ticks representing the specified amount of time.
559  * If the specified time is negative, a value of 1 is returned. This
560  * function returns a value from 1 up to and including INT_MAX.
561  */
562 int
563 tvtohz(struct timeval *tv)
564 {
565         int retval;
566
567         /*
568          * The values passed here may come from user-space and these
569          * checks ensure "tv_usec" is within its allowed range:
570          */
571
572         /* check for tv_usec underflow */
573         if (__predict_false(tv->tv_usec < 0)) {
574                 tv->tv_sec += tv->tv_usec / 1000000;
575                 tv->tv_usec = tv->tv_usec % 1000000;
576                 /* convert tv_usec to a positive value */
577                 if (__predict_true(tv->tv_usec < 0)) {
578                         tv->tv_usec += 1000000;
579                         tv->tv_sec -= 1;
580                 }
581         /* check for tv_usec overflow */
582         } else if (__predict_false(tv->tv_usec >= 1000000)) {
583                 tv->tv_sec += tv->tv_usec / 1000000;
584                 tv->tv_usec = tv->tv_usec % 1000000;
585         }
586
587         /* check for tv_sec underflow */
588         if (__predict_false(tv->tv_sec < 0))
589                 return (1);
590         /* check for tv_sec overflow (including room for the tv_usec part) */
591         else if (__predict_false(tv->tv_sec >= tick_seconds_max))
592                 return (INT_MAX);
593
594         /* cast to "int" to avoid platform differences */
595         retval = TIME_TO_TICKS((int)tv->tv_sec, (int)tv->tv_usec, hz);
596
597         /* add one additional tick */
598         return (retval + 1);
599 }
600
601 /*
602  * Start profiling on a process.
603  *
604  * Kernel profiling passes proc0 which never exits and hence
605  * keeps the profile clock running constantly.
606  */
607 void
608 startprofclock(struct proc *p)
609 {
610
611         PROC_LOCK_ASSERT(p, MA_OWNED);
612         if (p->p_flag & P_STOPPROF)
613                 return;
614         if ((p->p_flag & P_PROFIL) == 0) {
615                 p->p_flag |= P_PROFIL;
616                 mtx_lock(&time_lock);
617                 if (++profprocs == 1)
618                         cpu_startprofclock();
619                 mtx_unlock(&time_lock);
620         }
621 }
622
623 /*
624  * Stop profiling on a process.
625  */
626 void
627 stopprofclock(struct proc *p)
628 {
629
630         PROC_LOCK_ASSERT(p, MA_OWNED);
631         if (p->p_flag & P_PROFIL) {
632                 if (p->p_profthreads != 0) {
633                         while (p->p_profthreads != 0) {
634                                 p->p_flag |= P_STOPPROF;
635                                 msleep(&p->p_profthreads, &p->p_mtx, PPAUSE,
636                                     "stopprof", 0);
637                         }
638                 }
639                 if ((p->p_flag & P_PROFIL) == 0)
640                         return;
641                 p->p_flag &= ~P_PROFIL;
642                 mtx_lock(&time_lock);
643                 if (--profprocs == 0)
644                         cpu_stopprofclock();
645                 mtx_unlock(&time_lock);
646         }
647 }
648
649 /*
650  * Statistics clock.  Updates rusage information and calls the scheduler
651  * to adjust priorities of the active thread.
652  *
653  * This should be called by all active processors.
654  */
655 void
656 statclock(int cnt, int usermode)
657 {
658         struct rusage *ru;
659         struct vmspace *vm;
660         struct thread *td;
661         struct proc *p;
662         long rss;
663         long *cp_time;
664         uint64_t runtime, new_switchtime;
665
666         td = curthread;
667         p = td->td_proc;
668
669         cp_time = (long *)PCPU_PTR(cp_time);
670         if (usermode) {
671                 /*
672                  * Charge the time as appropriate.
673                  */
674                 td->td_uticks += cnt;
675                 if (p->p_nice > NZERO)
676                         cp_time[CP_NICE] += cnt;
677                 else
678                         cp_time[CP_USER] += cnt;
679         } else {
680                 /*
681                  * Came from kernel mode, so we were:
682                  * - handling an interrupt,
683                  * - doing syscall or trap work on behalf of the current
684                  *   user process, or
685                  * - spinning in the idle loop.
686                  * Whichever it is, charge the time as appropriate.
687                  * Note that we charge interrupts to the current process,
688                  * regardless of whether they are ``for'' that process,
689                  * so that we know how much of its real time was spent
690                  * in ``non-process'' (i.e., interrupt) work.
691                  */
692                 if ((td->td_pflags & TDP_ITHREAD) ||
693                     td->td_intr_nesting_level >= 2) {
694                         td->td_iticks += cnt;
695                         cp_time[CP_INTR] += cnt;
696                 } else {
697                         td->td_pticks += cnt;
698                         td->td_sticks += cnt;
699                         if (!TD_IS_IDLETHREAD(td))
700                                 cp_time[CP_SYS] += cnt;
701                         else
702                                 cp_time[CP_IDLE] += cnt;
703                 }
704         }
705
706         /* Update resource usage integrals and maximums. */
707         MPASS(p->p_vmspace != NULL);
708         vm = p->p_vmspace;
709         ru = &td->td_ru;
710         ru->ru_ixrss += pgtok(vm->vm_tsize) * cnt;
711         ru->ru_idrss += pgtok(vm->vm_dsize) * cnt;
712         ru->ru_isrss += pgtok(vm->vm_ssize) * cnt;
713         rss = pgtok(vmspace_resident_count(vm));
714         if (ru->ru_maxrss < rss)
715                 ru->ru_maxrss = rss;
716         KTR_POINT2(KTR_SCHED, "thread", sched_tdname(td), "statclock",
717             "prio:%d", td->td_priority, "stathz:%d", (stathz)?stathz:hz);
718         SDT_PROBE2(sched, , , tick, td, td->td_proc);
719         thread_lock_flags(td, MTX_QUIET);
720
721         /*
722          * Compute the amount of time during which the current
723          * thread was running, and add that to its total so far.
724          */
725         new_switchtime = cpu_ticks();
726         runtime = new_switchtime - PCPU_GET(switchtime);
727         td->td_runtime += runtime;
728         td->td_incruntime += runtime;
729         PCPU_SET(switchtime, new_switchtime);
730
731         sched_clock(td, cnt);
732         thread_unlock(td);
733 #ifdef HWPMC_HOOKS
734         if (td->td_intr_frame != NULL)
735                 PMC_SOFT_CALL_TF( , , clock, stat, td->td_intr_frame);
736 #endif
737 }
738
739 void
740 profclock(int cnt, int usermode, uintfptr_t pc)
741 {
742         struct thread *td;
743 #ifdef GPROF
744         struct gmonparam *g;
745         uintfptr_t i;
746 #endif
747
748         td = curthread;
749         if (usermode) {
750                 /*
751                  * Came from user mode; CPU was in user state.
752                  * If this process is being profiled, record the tick.
753                  * if there is no related user location yet, don't
754                  * bother trying to count it.
755                  */
756                 if (td->td_proc->p_flag & P_PROFIL)
757                         addupc_intr(td, pc, cnt);
758         }
759 #ifdef GPROF
760         else {
761                 /*
762                  * Kernel statistics are just like addupc_intr, only easier.
763                  */
764                 g = &_gmonparam;
765                 if (g->state == GMON_PROF_ON && pc >= g->lowpc) {
766                         i = PC_TO_I(g, pc);
767                         if (i < g->textsize) {
768                                 KCOUNT(g, i) += cnt;
769                         }
770                 }
771         }
772 #endif
773 #ifdef HWPMC_HOOKS
774         if (td->td_intr_frame != NULL)
775                 PMC_SOFT_CALL_TF( , , clock, prof, td->td_intr_frame);
776 #endif
777 }
778
779 /*
780  * Return information about system clocks.
781  */
782 static int
783 sysctl_kern_clockrate(SYSCTL_HANDLER_ARGS)
784 {
785         struct clockinfo clkinfo;
786         /*
787          * Construct clockinfo structure.
788          */
789         bzero(&clkinfo, sizeof(clkinfo));
790         clkinfo.hz = hz;
791         clkinfo.tick = tick;
792         clkinfo.profhz = profhz;
793         clkinfo.stathz = stathz ? stathz : hz;
794         return (sysctl_handle_opaque(oidp, &clkinfo, sizeof clkinfo, req));
795 }
796
797 SYSCTL_PROC(_kern, KERN_CLOCKRATE, clockrate,
798         CTLTYPE_STRUCT|CTLFLAG_RD|CTLFLAG_MPSAFE,
799         0, 0, sysctl_kern_clockrate, "S,clockinfo",
800         "Rate and period of various kernel clocks");
801
802 static void
803 watchdog_config(void *unused __unused, u_int cmd, int *error)
804 {
805         u_int u;
806
807         u = cmd & WD_INTERVAL;
808         if (u >= WD_TO_1SEC) {
809                 watchdog_ticks = (1 << (u - WD_TO_1SEC)) * hz;
810                 watchdog_enabled = 1;
811                 *error = 0;
812         } else {
813                 watchdog_enabled = 0;
814         }
815 }
816
817 /*
818  * Handle a watchdog timeout by dumping interrupt information and
819  * then either dropping to DDB or panicking.
820  */
821 static void
822 watchdog_fire(void)
823 {
824         int nintr;
825         uint64_t inttotal;
826         u_long *curintr;
827         char *curname;
828
829         curintr = intrcnt;
830         curname = intrnames;
831         inttotal = 0;
832         nintr = sintrcnt / sizeof(u_long);
833
834         printf("interrupt                   total\n");
835         while (--nintr >= 0) {
836                 if (*curintr)
837                         printf("%-12s %20lu\n", curname, *curintr);
838                 curname += strlen(curname) + 1;
839                 inttotal += *curintr++;
840         }
841         printf("Total        %20ju\n", (uintmax_t)inttotal);
842
843 #if defined(KDB) && !defined(KDB_UNATTENDED)
844         kdb_backtrace();
845         kdb_enter(KDB_WHY_WATCHDOG, "watchdog timeout");
846 #else
847         panic("watchdog timeout");
848 #endif
849 }