xref: /titanic_41/usr/src/uts/common/os/msacct.c (revision 02e56f3f1bfc8d9977bafb8cb5202f576dcded27)
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 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <sys/types.h>
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/user.h>
33 #include <sys/proc.h>
34 #include <sys/cpuvar.h>
35 #include <sys/thread.h>
36 #include <sys/debug.h>
37 #include <sys/msacct.h>
38 #include <sys/time.h>
39 
40 /*
41  * Mega-theory block comment:
42  *
43  * Microstate accounting uses finite states and the transitions between these
44  * states to measure timing and accounting information.  The state information
45  * is presently tracked for threads (via microstate accounting) and cpus (via
46  * cpu microstate accounting).  In each case, these accounting mechanisms use
47  * states and transitions to measure time spent in each state instead of
48  * clock-based sampling methodologies.
49  *
50  * For microstate accounting:
51  * state transitions are accomplished by calling new_mstate() to switch between
52  * states.  Transitions from a sleeping state (LMS_SLEEP and LMS_STOPPED) occur
53  * by calling restore_mstate() which restores a thread to its previously running
54  * state.  This code is primarialy executed by the dispatcher in disp() before
55  * running a process that was put to sleep.  If the thread was not in a sleeping
56  * state, this call has little effect other than to update the count of time the
57  * thread has spent waiting on run-queues in its lifetime.
58  *
59  * For cpu microstate accounting:
60  * Cpu microstate accounting is similar to the microstate accounting for threads
61  * but it tracks user, system, and idle time for cpus.  Cpu microstate
62  * accounting does not track interrupt times as there is a pre-existing
63  * interrupt accounting mechanism for this purpose.  Cpu microstate accounting
64  * tracks time that user threads have spent active, idle, or in the system on a
65  * given cpu.  Cpu microstate accounting has fewer states which allows it to
66  * have better defined transitions.  The states transition in the following
67  * order:
68  *
69  *  CMS_USER <-> CMS_SYSTEM <-> CMS_IDLE
70  *
71  * In order to get to the idle state, the cpu microstate must first go through
72  * the system state, and vice-versa for the user state from idle.  The switching
73  * of the microstates from user to system is done as part of the regular thread
74  * microstate accounting code, except for the idle state which is switched by
75  * the dispatcher before it runs the idle loop.
76  *
77  * Cpu percentages:
78  * Cpu percentages are now handled by and based upon microstate accounting
79  * information (the same is true for load averages).  The routines which handle
80  * the growing/shrinking and exponentiation of cpu percentages have been moved
81  * here as it now makes more sense for them to be generated from the microstate
82  * code.  Cpu percentages are generated similarly to the way they were before;
83  * however, now they are based upon high-resolution timestamps and the
84  * timestamps are modified at various state changes instead of during a clock()
85  * interrupt.  This allows us to generate more accurate cpu percentages which
86  * are also in-sync with microstate data.
87  */
88 
89 /*
90  * Initialize the microstate level and the
91  * associated accounting information for an LWP.
92  */
93 void
94 init_mstate(
95 	kthread_t	*t,
96 	int		init_state)
97 {
98 	struct mstate *ms;
99 	klwp_t *lwp;
100 	hrtime_t curtime;
101 
102 	ASSERT(init_state != LMS_WAIT_CPU);
103 	ASSERT((unsigned)init_state < NMSTATES);
104 
105 	if ((lwp = ttolwp(t)) != NULL) {
106 		ms = &lwp->lwp_mstate;
107 		curtime = gethrtime_unscaled();
108 		ms->ms_prev = LMS_SYSTEM;
109 		ms->ms_start = curtime;
110 		ms->ms_term = 0;
111 		ms->ms_state_start = curtime;
112 		t->t_mstate = init_state;
113 		t->t_waitrq = 0;
114 		t->t_hrtime = curtime;
115 		if ((t->t_proc_flag & TP_MSACCT) == 0)
116 			t->t_proc_flag |= TP_MSACCT;
117 		bzero((caddr_t)&ms->ms_acct[0], sizeof (ms->ms_acct));
118 	}
119 }
120 
121 /*
122  * Initialize the microstate level and associated accounting information
123  * for the specified cpu
124  */
125 
126 void
127 init_cpu_mstate(
128 	cpu_t *cpu,
129 	int init_state)
130 {
131 	ASSERT(init_state != CMS_DISABLED);
132 
133 	cpu->cpu_mstate = init_state;
134 	cpu->cpu_mstate_start = gethrtime_unscaled();
135 	cpu->cpu_waitrq = 0;
136 	bzero((caddr_t)&cpu->cpu_acct[0], sizeof (cpu->cpu_acct));
137 }
138 
139 /*
140  * sets cpu state to OFFLINE.  We don't actually track this time,
141  * but it serves as a useful placeholder state for when we're not
142  * doing anything.
143  */
144 
145 void
146 term_cpu_mstate(struct cpu *cpu)
147 {
148 	ASSERT(cpu->cpu_mstate != CMS_DISABLED);
149 	cpu->cpu_mstate = CMS_DISABLED;
150 	cpu->cpu_mstate_start = 0;
151 }
152 
153 void
154 new_cpu_mstate(cpu_t *cpu, int cmstate)
155 {
156 	hrtime_t curtime;
157 	hrtime_t newtime;
158 	hrtime_t oldtime;
159 	hrtime_t *mstimep;
160 
161 	ASSERT(cpu->cpu_mstate != CMS_DISABLED);
162 	ASSERT(cmstate < NCMSTATES);
163 	ASSERT(cmstate != CMS_DISABLED);
164 	ASSERT(curthread->t_preempt > 0 || curthread == cpu->cpu_idle_thread);
165 
166 	curtime = gethrtime_unscaled();
167 	mstimep = &cpu->cpu_acct[cpu->cpu_mstate];
168 	do {
169 		newtime = curtime - cpu->cpu_mstate_start;
170 		if (newtime < 0) {
171 			/* force CAS to fail */
172 			curtime = gethrtime_unscaled();
173 			oldtime = *mstimep - 1;
174 			continue;
175 		}
176 		oldtime = *mstimep;
177 		newtime += oldtime;
178 		cpu->cpu_mstate = cmstate;
179 		cpu->cpu_mstate_start = curtime;
180 	} while (cas64((uint64_t *)mstimep, oldtime, newtime) != oldtime);
181 }
182 
183 /*
184  * Return an aggregation of microstate times in scaled nanoseconds (high-res
185  * time).  This keeps in mind that p_acct is already scaled, and ms_acct is
186  * not.
187  */
188 hrtime_t
189 mstate_aggr_state(proc_t *p, int a_state)
190 {
191 	struct mstate *ms;
192 	kthread_t *t;
193 	klwp_t *lwp;
194 	hrtime_t aggr_time;
195 	hrtime_t scaledtime;
196 
197 	ASSERT(MUTEX_HELD(&p->p_lock));
198 	ASSERT((unsigned)a_state < NMSTATES);
199 
200 	aggr_time = p->p_acct[a_state];
201 	if (a_state == LMS_SYSTEM)
202 		aggr_time += p->p_acct[LMS_TRAP];
203 
204 	t = p->p_tlist;
205 	if (t == NULL)
206 		return (aggr_time);
207 
208 	do {
209 		if (t->t_proc_flag & TP_LWPEXIT)
210 			continue;
211 
212 		lwp = ttolwp(t);
213 		ms = &lwp->lwp_mstate;
214 		scaledtime = ms->ms_acct[a_state];
215 		scalehrtime(&scaledtime);
216 		aggr_time += scaledtime;
217 		if (a_state == LMS_SYSTEM) {
218 			scaledtime = ms->ms_acct[LMS_TRAP];
219 			scalehrtime(&scaledtime);
220 			aggr_time += scaledtime;
221 		}
222 	} while ((t = t->t_forw) != p->p_tlist);
223 
224 	return (aggr_time);
225 }
226 
227 void
228 syscall_mstate(int fromms, int toms)
229 {
230 	kthread_t *t = curthread;
231 	struct mstate *ms;
232 	hrtime_t *mstimep;
233 	hrtime_t curtime;
234 	klwp_t *lwp;
235 	struct cpu *cpup;
236 	hrtime_t newtime;
237 
238 	if ((lwp = ttolwp(t)) == NULL)
239 		return;
240 
241 	ASSERT(fromms < NMSTATES);
242 	ASSERT(toms < NMSTATES);
243 
244 	ms = &lwp->lwp_mstate;
245 	mstimep = &ms->ms_acct[fromms];
246 	curtime = gethrtime_unscaled();
247 	newtime = curtime - ms->ms_state_start;
248 	while (newtime < 0) {
249 		curtime = gethrtime_unscaled();
250 		newtime = curtime - ms->ms_state_start;
251 	}
252 	*mstimep += newtime;
253 	t->t_mstate = toms;
254 	ms->ms_state_start = curtime;
255 	ms->ms_prev = fromms;
256 	/*
257 	 * Here, you could call new_cpu_mstate() to switch the cpu
258 	 * microstate.  However, in the interest of making things
259 	 * as expeditious as possible, the relevant work has been inlined.
260 	 */
261 	kpreempt_disable(); /* MUST disable kpreempt before touching t->cpu */
262 	cpup = t->t_cpu;
263 	ASSERT(cpup->cpu_mstate != CMS_DISABLED);
264 	if ((toms != LMS_USER) && (cpup->cpu_mstate != CMS_SYSTEM)) {
265 		mstimep = &cpup->cpu_acct[CMS_USER];
266 		newtime = curtime - cpup->cpu_mstate_start;
267 		while (newtime < 0) {
268 			curtime = gethrtime_unscaled();
269 			newtime = curtime - cpup->cpu_mstate_start;
270 		}
271 		*mstimep += newtime;
272 		cpup->cpu_mstate = CMS_SYSTEM;
273 		cpup->cpu_mstate_start = curtime;
274 	} else if ((toms == LMS_USER) && (cpup->cpu_mstate != CMS_USER)) {
275 		mstimep = &cpup->cpu_acct[CMS_SYSTEM];
276 		newtime = curtime - cpup->cpu_mstate_start;
277 		while (newtime < 0) {
278 			curtime = gethrtime_unscaled();
279 			newtime = curtime - cpup->cpu_mstate_start;
280 		}
281 		*mstimep += newtime;
282 		cpup->cpu_mstate = CMS_USER;
283 		cpup->cpu_mstate_start = curtime;
284 	}
285 	kpreempt_enable();
286 }
287 
288 /*
289  * The following is for computing the percentage of cpu time used recently
290  * by an lwp.  The function cpu_decay() is also called from /proc code.
291  *
292  * exp_x(x):
293  * Given x as a 64-bit non-negative scaled integer of arbitrary magnitude,
294  * Return exp(-x) as a 64-bit scaled integer in the range [0 .. 1].
295  *
296  * Scaling for 64-bit scaled integer:
297  * The binary point is to the right of the high-order bit
298  * of the low-order 32-bit word.
299  */
300 
301 #define	LSHIFT	31
302 #define	LSI_ONE	((uint32_t)1 << LSHIFT)	/* 32-bit scaled integer 1 */
303 
304 #ifdef DEBUG
305 uint_t expx_cnt = 0;	/* number of calls to exp_x() */
306 uint_t expx_mul = 0;	/* number of long multiplies in exp_x() */
307 #endif
308 
309 static uint64_t
310 exp_x(uint64_t x)
311 {
312 	int i;
313 	uint64_t ull;
314 	uint32_t ui;
315 
316 #ifdef DEBUG
317 	expx_cnt++;
318 #endif
319 	/*
320 	 * By the formula:
321 	 *	exp(-x) = exp(-x/2) * exp(-x/2)
322 	 * we keep halving x until it becomes small enough for
323 	 * the following approximation to be accurate enough:
324 	 *	exp(-x) = 1 - x
325 	 * We reduce x until it is less than 1/4 (the 2 in LSHIFT-2 below).
326 	 * Our final error will be smaller than 4% .
327 	 */
328 
329 	/*
330 	 * Use a uint64_t for the initial shift calculation.
331 	 */
332 	ull = x >> (LSHIFT-2);
333 
334 	/*
335 	 * Short circuit:
336 	 * A number this large produces effectively 0 (actually .005).
337 	 * This way, we will never do more than 5 multiplies.
338 	 */
339 	if (ull >= (1 << 5))
340 		return (0);
341 
342 	ui = ull;	/* OK.  Now we can use a uint_t. */
343 	for (i = 0; ui != 0; i++)
344 		ui >>= 1;
345 
346 	if (i != 0) {
347 #ifdef DEBUG
348 		expx_mul += i;	/* seldom happens */
349 #endif
350 		x >>= i;
351 	}
352 
353 	/*
354 	 * Now we compute 1 - x and square it the number of times
355 	 * that we halved x above to produce the final result:
356 	 */
357 	x = LSI_ONE - x;
358 	while (i--)
359 		x = (x * x) >> LSHIFT;
360 
361 	return (x);
362 }
363 
364 /*
365  * Given the old percent cpu and a time delta in nanoseconds,
366  * return the new decayed percent cpu:  pct * exp(-tau),
367  * where 'tau' is the time delta multiplied by a decay factor.
368  * We have chosen the decay factor (cpu_decay_factor in param.c)
369  * to make the decay over five seconds be approximately 20%.
370  *
371  * 'pct' is a 32-bit scaled integer <= 1
372  * The binary point is to the right of the high-order bit
373  * of the 32-bit word.
374  */
375 static uint32_t
376 cpu_decay(uint32_t pct, hrtime_t nsec)
377 {
378 	uint64_t delta = (uint64_t)nsec;
379 
380 	delta /= cpu_decay_factor;
381 	return ((pct * exp_x(delta)) >> LSHIFT);
382 }
383 
384 /*
385  * Given the old percent cpu and a time delta in nanoseconds,
386  * return the new grown percent cpu:  1 - ( 1 - pct ) * exp(-tau)
387  */
388 static uint32_t
389 cpu_grow(uint32_t pct, hrtime_t nsec)
390 {
391 	return (LSI_ONE - cpu_decay(LSI_ONE - pct, nsec));
392 }
393 
394 
395 /*
396  * Defined to determine whether a lwp is still on a processor.
397  */
398 
399 #define	T_ONPROC(kt)	\
400 	((kt)->t_mstate < LMS_SLEEP)
401 #define	T_OFFPROC(kt)	\
402 	((kt)->t_mstate >= LMS_SLEEP)
403 
404 uint_t
405 cpu_update_pct(kthread_t *t, hrtime_t newtime)
406 {
407 	hrtime_t delta;
408 	hrtime_t hrlb;
409 	uint_t pctcpu;
410 	uint_t npctcpu;
411 
412 	/*
413 	 * This routine can get called at PIL > 0, this *has* to be
414 	 * done atomically. Holding locks here causes bad things to happen.
415 	 * (read: deadlock).
416 	 */
417 
418 	do {
419 		if (T_ONPROC(t) && t->t_waitrq == 0) {
420 			hrlb = t->t_hrtime;
421 			delta = newtime - hrlb;
422 			if (delta < 0) {
423 				newtime = gethrtime_unscaled();
424 				delta = newtime - hrlb;
425 			}
426 			t->t_hrtime = newtime;
427 			scalehrtime(&delta);
428 			pctcpu = t->t_pctcpu;
429 			npctcpu = cpu_grow(pctcpu, delta);
430 		} else {
431 			hrlb = t->t_hrtime;
432 			delta = newtime - hrlb;
433 			if (delta < 0) {
434 				newtime = gethrtime_unscaled();
435 				delta = newtime - hrlb;
436 			}
437 			t->t_hrtime = newtime;
438 			scalehrtime(&delta);
439 			pctcpu = t->t_pctcpu;
440 			npctcpu = cpu_decay(pctcpu, delta);
441 		}
442 	} while (cas32(&t->t_pctcpu, pctcpu, npctcpu) != pctcpu);
443 
444 	return (npctcpu);
445 }
446 
447 /*
448  * Change the microstate level for the LWP and update the
449  * associated accounting information.  Return the previous
450  * LWP state.
451  */
452 int
453 new_mstate(kthread_t *t, int new_state)
454 {
455 	struct mstate *ms;
456 	unsigned state;
457 	hrtime_t *mstimep;
458 	hrtime_t curtime;
459 	hrtime_t newtime;
460 	hrtime_t oldtime;
461 	klwp_t *lwp;
462 
463 	ASSERT(new_state != LMS_WAIT_CPU);
464 	ASSERT((unsigned)new_state < NMSTATES);
465 	ASSERT(t == curthread || THREAD_LOCK_HELD(t));
466 
467 	if ((lwp = ttolwp(t)) == NULL)
468 		return (LMS_SYSTEM);
469 
470 	curtime = gethrtime_unscaled();
471 
472 	/* adjust cpu percentages before we go any further */
473 	(void) cpu_update_pct(t, curtime);
474 
475 	ms = &lwp->lwp_mstate;
476 	state = t->t_mstate;
477 	do {
478 		switch (state) {
479 		case LMS_TFAULT:
480 		case LMS_DFAULT:
481 		case LMS_KFAULT:
482 		case LMS_USER_LOCK:
483 			mstimep = &ms->ms_acct[LMS_SYSTEM];
484 			break;
485 		default:
486 			mstimep = &ms->ms_acct[state];
487 			break;
488 		}
489 		newtime = curtime - ms->ms_state_start;
490 		if (newtime < 0) {
491 			curtime = gethrtime_unscaled();
492 			oldtime = *mstimep - 1; /* force CAS to fail */
493 			continue;
494 		}
495 		oldtime = *mstimep;
496 		newtime += oldtime;
497 		t->t_mstate = new_state;
498 		ms->ms_state_start = curtime;
499 	} while (cas64((uint64_t *)mstimep, oldtime, newtime) != oldtime);
500 	/*
501 	 * Remember the previous running microstate.
502 	 */
503 	if (state != LMS_SLEEP && state != LMS_STOPPED)
504 		ms->ms_prev = state;
505 
506 	/*
507 	 * Switch CPU microstate if appropriate
508 	 */
509 	kpreempt_disable(); /* MUST disable kpreempt before touching t->cpu */
510 	if (new_state == LMS_USER && t->t_cpu->cpu_mstate != CMS_USER) {
511 		new_cpu_mstate(t->t_cpu, CMS_USER);
512 	} else if (new_state != LMS_USER &&
513 	    t->t_cpu->cpu_mstate != CMS_SYSTEM) {
514 		new_cpu_mstate(t->t_cpu, CMS_SYSTEM);
515 	}
516 	kpreempt_enable();
517 
518 	return (ms->ms_prev);
519 }
520 
521 static long waitrqis0 = 0;
522 
523 /*
524  * Restore the LWP microstate to the previous runnable state.
525  * Called from disp() with the newly selected lwp.
526  */
527 void
528 restore_mstate(kthread_t *t)
529 {
530 	struct mstate *ms;
531 	hrtime_t *mstimep;
532 	klwp_t *lwp;
533 	hrtime_t curtime;
534 	hrtime_t waitrq;
535 	hrtime_t newtime;
536 	hrtime_t oldtime;
537 
538 	if ((lwp = ttolwp(t)) == NULL)
539 		return;
540 
541 	curtime = gethrtime_unscaled();
542 	(void) cpu_update_pct(t, curtime);
543 	ms = &lwp->lwp_mstate;
544 	ASSERT((unsigned)t->t_mstate < NMSTATES);
545 	do {
546 		switch (t->t_mstate) {
547 		case LMS_SLEEP:
548 			/*
549 			 * Update the timer for the current sleep state.
550 			 */
551 			ASSERT((unsigned)ms->ms_prev < NMSTATES);
552 			switch (ms->ms_prev) {
553 			case LMS_TFAULT:
554 			case LMS_DFAULT:
555 			case LMS_KFAULT:
556 			case LMS_USER_LOCK:
557 				mstimep = &ms->ms_acct[ms->ms_prev];
558 				break;
559 			default:
560 				mstimep = &ms->ms_acct[LMS_SLEEP];
561 				break;
562 			}
563 			/*
564 			 * Return to the previous run state.
565 			 */
566 			t->t_mstate = ms->ms_prev;
567 			break;
568 		case LMS_STOPPED:
569 			mstimep = &ms->ms_acct[LMS_STOPPED];
570 			/*
571 			 * Return to the previous run state.
572 			 */
573 			t->t_mstate = ms->ms_prev;
574 			break;
575 		case LMS_TFAULT:
576 		case LMS_DFAULT:
577 		case LMS_KFAULT:
578 		case LMS_USER_LOCK:
579 			mstimep = &ms->ms_acct[LMS_SYSTEM];
580 			break;
581 		default:
582 			mstimep = &ms->ms_acct[t->t_mstate];
583 			break;
584 		}
585 		waitrq = t->t_waitrq;	/* hopefully atomic */
586 		t->t_waitrq = 0;
587 		if (waitrq == 0) {	/* should only happen during boot */
588 			waitrq = curtime;
589 			waitrqis0++;
590 		}
591 		newtime = waitrq - ms->ms_state_start;
592 		if (newtime < 0) {
593 			curtime = gethrtime_unscaled();
594 			oldtime = *mstimep - 1; /* force CAS to fail */
595 			continue;
596 		}
597 		oldtime = *mstimep;
598 		newtime += oldtime;
599 	} while (cas64((uint64_t *)mstimep, oldtime, newtime) != oldtime);
600 	/*
601 	 * Update the WAIT_CPU timer and per-cpu waitrq total.
602 	 */
603 	ms->ms_acct[LMS_WAIT_CPU] += (curtime - waitrq);
604 	CPU->cpu_waitrq += (curtime - waitrq);
605 	ms->ms_state_start = curtime;
606 }
607 
608 /*
609  * Copy lwp microstate accounting and resource usage information
610  * to the process.  (lwp is terminating)
611  */
612 void
613 term_mstate(kthread_t *t)
614 {
615 	struct mstate *ms;
616 	proc_t *p = ttoproc(t);
617 	klwp_t *lwp = ttolwp(t);
618 	int i;
619 	hrtime_t tmp;
620 
621 	ASSERT(MUTEX_HELD(&p->p_lock));
622 
623 	ms = &lwp->lwp_mstate;
624 	(void) new_mstate(t, LMS_STOPPED);
625 	ms->ms_term = ms->ms_state_start;
626 	tmp = ms->ms_term - ms->ms_start;
627 	scalehrtime(&tmp);
628 	p->p_mlreal += tmp;
629 	for (i = 0; i < NMSTATES; i++) {
630 		tmp = ms->ms_acct[i];
631 		scalehrtime(&tmp);
632 		p->p_acct[i] += tmp;
633 	}
634 	p->p_ru.minflt   += lwp->lwp_ru.minflt;
635 	p->p_ru.majflt   += lwp->lwp_ru.majflt;
636 	p->p_ru.nswap    += lwp->lwp_ru.nswap;
637 	p->p_ru.inblock  += lwp->lwp_ru.inblock;
638 	p->p_ru.oublock  += lwp->lwp_ru.oublock;
639 	p->p_ru.msgsnd   += lwp->lwp_ru.msgsnd;
640 	p->p_ru.msgrcv   += lwp->lwp_ru.msgrcv;
641 	p->p_ru.nsignals += lwp->lwp_ru.nsignals;
642 	p->p_ru.nvcsw    += lwp->lwp_ru.nvcsw;
643 	p->p_ru.nivcsw   += lwp->lwp_ru.nivcsw;
644 	p->p_ru.sysc	 += lwp->lwp_ru.sysc;
645 	p->p_ru.ioch	 += lwp->lwp_ru.ioch;
646 	p->p_defunct++;
647 }
648