kern_clock.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. /* $OpenBSD: kern_clock.c,v 1.88 2015/06/11 16:03:04 mikeb Exp $ */
  2. /* $NetBSD: kern_clock.c,v 1.34 1996/06/09 04:51:03 briggs Exp $ */
  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. #include <sys/param.h>
  39. #include <sys/systm.h>
  40. #include <sys/timeout.h>
  41. #include <sys/kernel.h>
  42. #include <sys/limits.h>
  43. #include <sys/proc.h>
  44. #include <sys/user.h>
  45. #include <sys/resourcevar.h>
  46. #include <sys/signalvar.h>
  47. #include <sys/sysctl.h>
  48. #include <sys/sched.h>
  49. #include <sys/timetc.h>
  50. #ifdef GPROF
  51. #include <sys/gmon.h>
  52. #endif
  53. /*
  54. * Clock handling routines.
  55. *
  56. * This code is written to operate with two timers that run independently of
  57. * each other. The main clock, running hz times per second, is used to keep
  58. * track of real time. The second timer handles kernel and user profiling,
  59. * and does resource use estimation. If the second timer is programmable,
  60. * it is randomized to avoid aliasing between the two clocks. For example,
  61. * the randomization prevents an adversary from always giving up the cpu
  62. * just before its quantum expires. Otherwise, it would never accumulate
  63. * cpu ticks. The mean frequency of the second timer is stathz.
  64. *
  65. * If no second timer exists, stathz will be zero; in this case we drive
  66. * profiling and statistics off the main clock. This WILL NOT be accurate;
  67. * do not do it unless absolutely necessary.
  68. *
  69. * The statistics clock may (or may not) be run at a higher rate while
  70. * profiling. This profile clock runs at profhz. We require that profhz
  71. * be an integral multiple of stathz.
  72. *
  73. * If the statistics clock is running fast, it must be divided by the ratio
  74. * profhz/stathz for statistics. (For profiling, every tick counts.)
  75. */
  76. /*
  77. * Bump a timeval by a small number of usec's.
  78. */
  79. #define BUMPTIME(t, usec) { \
  80. volatile struct timeval *tp = (t); \
  81. long us; \
  82. \
  83. tp->tv_usec = us = tp->tv_usec + (usec); \
  84. if (us >= 1000000) { \
  85. tp->tv_usec = us - 1000000; \
  86. tp->tv_sec++; \
  87. } \
  88. }
  89. int stathz;
  90. int schedhz;
  91. int profhz;
  92. int profprocs;
  93. int ticks;
  94. static int psdiv, pscnt; /* prof => stat divider */
  95. int psratio; /* ratio: prof / stat */
  96. void *softclock_si;
  97. /*
  98. * Initialize clock frequencies and start both clocks running.
  99. */
  100. void
  101. initclocks(void)
  102. {
  103. int i;
  104. softclock_si = softintr_establish(IPL_SOFTCLOCK, softclock, NULL);
  105. if (softclock_si == NULL)
  106. panic("initclocks: unable to register softclock intr");
  107. /*
  108. * Set divisors to 1 (normal case) and let the machine-specific
  109. * code do its bit.
  110. */
  111. psdiv = pscnt = 1;
  112. cpu_initclocks();
  113. /*
  114. * Compute profhz/stathz, and fix profhz if needed.
  115. */
  116. i = stathz ? stathz : hz;
  117. if (profhz == 0)
  118. profhz = i;
  119. psratio = profhz / i;
  120. /* For very large HZ, ensure that division by 0 does not occur later */
  121. if (tickadj == 0)
  122. tickadj = 1;
  123. inittimecounter();
  124. }
  125. /*
  126. * hardclock does the accounting needed for ITIMER_PROF and ITIMER_VIRTUAL.
  127. * We don't want to send signals with psignal from hardclock because it makes
  128. * MULTIPROCESSOR locking very complicated. Instead, to use an idea from
  129. * FreeBSD, we set a flag on the thread and when it goes to return to
  130. * userspace it signals itself.
  131. */
  132. /*
  133. * The real-time timer, interrupting hz times per second.
  134. */
  135. void
  136. hardclock(struct clockframe *frame)
  137. {
  138. struct proc *p;
  139. struct cpu_info *ci = curcpu();
  140. p = curproc;
  141. if (p && ((p->p_flag & (P_SYSTEM | P_WEXIT)) == 0)) {
  142. struct process *pr = p->p_p;
  143. /*
  144. * Run current process's virtual and profile time, as needed.
  145. */
  146. if (CLKF_USERMODE(frame) &&
  147. timerisset(&pr->ps_timer[ITIMER_VIRTUAL].it_value) &&
  148. itimerdecr(&pr->ps_timer[ITIMER_VIRTUAL], tick) == 0) {
  149. atomic_setbits_int(&p->p_flag, P_ALRMPEND);
  150. need_proftick(p);
  151. }
  152. if (timerisset(&pr->ps_timer[ITIMER_PROF].it_value) &&
  153. itimerdecr(&pr->ps_timer[ITIMER_PROF], tick) == 0) {
  154. atomic_setbits_int(&p->p_flag, P_PROFPEND);
  155. need_proftick(p);
  156. }
  157. }
  158. /*
  159. * If no separate statistics clock is available, run it from here.
  160. */
  161. if (stathz == 0)
  162. statclock(frame);
  163. if (--ci->ci_schedstate.spc_rrticks <= 0)
  164. roundrobin(ci);
  165. /*
  166. * If we are not the primary CPU, we're not allowed to do
  167. * any more work.
  168. */
  169. if (CPU_IS_PRIMARY(ci) == 0)
  170. return;
  171. tc_ticktock();
  172. /*
  173. * Update real-time timeout queue.
  174. * Process callouts at a very low cpu priority, so we don't keep the
  175. * relatively high clock interrupt priority any longer than necessary.
  176. */
  177. if (timeout_hardclock_update())
  178. softintr_schedule(softclock_si);
  179. }
  180. /*
  181. * Compute number of hz in the specified amount of time.
  182. */
  183. int
  184. tvtohz(const struct timeval *tv)
  185. {
  186. unsigned long nticks;
  187. time_t sec;
  188. long usec;
  189. /*
  190. * If the number of usecs in the whole seconds part of the time
  191. * fits in a long, then the total number of usecs will
  192. * fit in an unsigned long. Compute the total and convert it to
  193. * ticks, rounding up and adding 1 to allow for the current tick
  194. * to expire. Rounding also depends on unsigned long arithmetic
  195. * to avoid overflow.
  196. *
  197. * Otherwise, if the number of ticks in the whole seconds part of
  198. * the time fits in a long, then convert the parts to
  199. * ticks separately and add, using similar rounding methods and
  200. * overflow avoidance. This method would work in the previous
  201. * case but it is slightly slower and assumes that hz is integral.
  202. *
  203. * Otherwise, round the time down to the maximum
  204. * representable value.
  205. *
  206. * If ints have 32 bits, then the maximum value for any timeout in
  207. * 10ms ticks is 248 days.
  208. */
  209. sec = tv->tv_sec;
  210. usec = tv->tv_usec;
  211. if (sec < 0 || (sec == 0 && usec <= 0))
  212. nticks = 0;
  213. else if (sec <= LONG_MAX / 1000000)
  214. nticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
  215. / tick + 1;
  216. else if (sec <= LONG_MAX / hz)
  217. nticks = sec * hz
  218. + ((unsigned long)usec + (tick - 1)) / tick + 1;
  219. else
  220. nticks = LONG_MAX;
  221. if (nticks > INT_MAX)
  222. nticks = INT_MAX;
  223. return ((int)nticks);
  224. }
  225. int
  226. tstohz(const struct timespec *ts)
  227. {
  228. struct timeval tv;
  229. TIMESPEC_TO_TIMEVAL(&tv, ts);
  230. /* Round up. */
  231. if ((ts->tv_nsec % 1000) != 0) {
  232. tv.tv_usec += 1;
  233. if (tv.tv_usec >= 1000000) {
  234. tv.tv_usec -= 1000000;
  235. tv.tv_sec += 1;
  236. }
  237. }
  238. return (tvtohz(&tv));
  239. }
  240. /*
  241. * Start profiling on a process.
  242. *
  243. * Kernel profiling passes proc0 which never exits and hence
  244. * keeps the profile clock running constantly.
  245. */
  246. void
  247. startprofclock(struct process *pr)
  248. {
  249. int s;
  250. if ((pr->ps_flags & PS_PROFIL) == 0) {
  251. atomic_setbits_int(&pr->ps_flags, PS_PROFIL);
  252. if (++profprocs == 1 && stathz != 0) {
  253. s = splstatclock();
  254. psdiv = pscnt = psratio;
  255. setstatclockrate(profhz);
  256. splx(s);
  257. }
  258. }
  259. }
  260. /*
  261. * Stop profiling on a process.
  262. */
  263. void
  264. stopprofclock(struct process *pr)
  265. {
  266. int s;
  267. if (pr->ps_flags & PS_PROFIL) {
  268. atomic_clearbits_int(&pr->ps_flags, PS_PROFIL);
  269. if (--profprocs == 0 && stathz != 0) {
  270. s = splstatclock();
  271. psdiv = pscnt = 1;
  272. setstatclockrate(stathz);
  273. splx(s);
  274. }
  275. }
  276. }
  277. /*
  278. * Statistics clock. Grab profile sample, and if divider reaches 0,
  279. * do process and kernel statistics.
  280. */
  281. void
  282. statclock(struct clockframe *frame)
  283. {
  284. #ifdef GPROF
  285. struct gmonparam *g;
  286. u_long i;
  287. #endif
  288. struct cpu_info *ci = curcpu();
  289. struct schedstate_percpu *spc = &ci->ci_schedstate;
  290. struct proc *p = curproc;
  291. struct process *pr;
  292. /*
  293. * Notice changes in divisor frequency, and adjust clock
  294. * frequency accordingly.
  295. */
  296. if (spc->spc_psdiv != psdiv) {
  297. spc->spc_psdiv = psdiv;
  298. spc->spc_pscnt = psdiv;
  299. if (psdiv == 1) {
  300. setstatclockrate(stathz);
  301. } else {
  302. setstatclockrate(profhz);
  303. }
  304. }
  305. if (CLKF_USERMODE(frame)) {
  306. pr = p->p_p;
  307. if (pr->ps_flags & PS_PROFIL)
  308. addupc_intr(p, CLKF_PC(frame));
  309. if (--spc->spc_pscnt > 0)
  310. return;
  311. /*
  312. * Came from user mode; CPU was in user state.
  313. * If this process is being profiled record the tick.
  314. */
  315. p->p_uticks++;
  316. if (pr->ps_nice > NZERO)
  317. spc->spc_cp_time[CP_NICE]++;
  318. else
  319. spc->spc_cp_time[CP_USER]++;
  320. } else {
  321. #ifdef GPROF
  322. /*
  323. * Kernel statistics are just like addupc_intr, only easier.
  324. */
  325. g = ci->ci_gmon;
  326. if (g != NULL && g->state == GMON_PROF_ON) {
  327. i = CLKF_PC(frame) - g->lowpc;
  328. if (i < g->textsize) {
  329. i /= HISTFRACTION * sizeof(*g->kcount);
  330. g->kcount[i]++;
  331. }
  332. }
  333. #endif
  334. #if defined(PROC_PC)
  335. if (p != NULL && p->p_p->ps_flags & PS_PROFIL)
  336. addupc_intr(p, PROC_PC(p));
  337. #endif
  338. if (--spc->spc_pscnt > 0)
  339. return;
  340. /*
  341. * Came from kernel mode, so we were:
  342. * - handling an interrupt,
  343. * - doing syscall or trap work on behalf of the current
  344. * user process, or
  345. * - spinning in the idle loop.
  346. * Whichever it is, charge the time as appropriate.
  347. * Note that we charge interrupts to the current process,
  348. * regardless of whether they are ``for'' that process,
  349. * so that we know how much of its real time was spent
  350. * in ``non-process'' (i.e., interrupt) work.
  351. */
  352. if (CLKF_INTR(frame)) {
  353. if (p != NULL)
  354. p->p_iticks++;
  355. spc->spc_cp_time[CP_INTR]++;
  356. } else if (p != NULL && p != spc->spc_idleproc) {
  357. p->p_sticks++;
  358. spc->spc_cp_time[CP_SYS]++;
  359. } else
  360. spc->spc_cp_time[CP_IDLE]++;
  361. }
  362. spc->spc_pscnt = psdiv;
  363. if (p != NULL) {
  364. p->p_cpticks++;
  365. /*
  366. * If no schedclock is provided, call it here at ~~12-25 Hz;
  367. * ~~16 Hz is best
  368. */
  369. if (schedhz == 0) {
  370. if ((++curcpu()->ci_schedstate.spc_schedticks & 3) ==
  371. 0)
  372. schedclock(p);
  373. }
  374. }
  375. }
  376. /*
  377. * Return information about system clocks.
  378. */
  379. int
  380. sysctl_clockrate(char *where, size_t *sizep, void *newp)
  381. {
  382. struct clockinfo clkinfo;
  383. /*
  384. * Construct clockinfo structure.
  385. */
  386. clkinfo.tick = tick;
  387. clkinfo.tickadj = tickadj;
  388. clkinfo.hz = hz;
  389. clkinfo.profhz = profhz;
  390. clkinfo.stathz = stathz ? stathz : hz;
  391. return (sysctl_rdstruct(where, sizep, newp, &clkinfo, sizeof(clkinfo)));
  392. }