]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/subr_prof.c
hv_kbd: Fix build with EVDEV_SUPPORT kernel option disabled.
[FreeBSD/FreeBSD.git] / sys / kern / subr_prof.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *      @(#)subr_prof.c 8.3 (Berkeley) 9/23/93
32  */
33
34 #include <sys/cdefs.h>
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/sysproto.h>
38 #include <sys/kernel.h>
39 #include <sys/lock.h>
40 #include <sys/mutex.h>
41 #include <sys/proc.h>
42 #include <sys/resourcevar.h>
43 #include <sys/sysctl.h>
44
45 #include <machine/cpu.h>
46
47 #ifdef GPROF
48 #include <sys/malloc.h>
49 #include <sys/gmon.h>
50 #undef MCOUNT
51
52 static MALLOC_DEFINE(M_GPROF, "gprof", "kernel profiling buffer");
53
54 static void kmstartup(void *);
55 SYSINIT(kmem, SI_SUB_KPROF, SI_ORDER_FIRST, kmstartup, NULL);
56
57 struct gmonparam _gmonparam = { GMON_PROF_OFF };
58
59 #ifdef GUPROF
60 void
61 nullfunc_loop_profiled()
62 {
63         int i;
64
65         for (i = 0; i < CALIB_SCALE; i++)
66                 nullfunc_profiled();
67 }
68
69 #define nullfunc_loop_profiled_end      nullfunc_profiled       /* XXX */
70
71 void
72 nullfunc_profiled()
73 {
74 }
75 #endif /* GUPROF */
76
77 /*
78  * Update the histograms to support extending the text region arbitrarily.
79  * This is done slightly naively (no sparse regions), so will waste slight
80  * amounts of memory, but will overall work nicely enough to allow profiling
81  * of KLDs.
82  */
83 void
84 kmupetext(uintfptr_t nhighpc)
85 {
86         struct gmonparam np;    /* slightly large */
87         struct gmonparam *p = &_gmonparam;
88         char *cp;
89
90         GIANT_REQUIRED;
91         bcopy(p, &np, sizeof(*p));
92         np.highpc = ROUNDUP(nhighpc, HISTFRACTION * sizeof(HISTCOUNTER));
93         if (np.highpc <= p->highpc)
94                 return;
95         np.textsize = np.highpc - p->lowpc;
96         np.kcountsize = np.textsize / HISTFRACTION;
97         np.hashfraction = HASHFRACTION;
98         np.fromssize = np.textsize / HASHFRACTION;
99         np.tolimit = np.textsize * ARCDENSITY / 100;
100         if (np.tolimit < MINARCS)
101                 np.tolimit = MINARCS;
102         else if (np.tolimit > MAXARCS)
103                 np.tolimit = MAXARCS;
104         np.tossize = np.tolimit * sizeof(struct tostruct);
105         cp = malloc(np.kcountsize + np.fromssize + np.tossize,
106             M_GPROF, M_WAITOK);
107         /*
108          * Check for something else extending highpc while we slept.
109          */
110         if (np.highpc <= p->highpc) {
111                 free(cp, M_GPROF);
112                 return;
113         }
114         np.tos = (struct tostruct *)cp;
115         cp += np.tossize;
116         np.kcount = (HISTCOUNTER *)cp;
117         cp += np.kcountsize;
118         np.froms = (u_short *)cp;
119 #ifdef GUPROF
120         /* Reinitialize pointers to overhead counters. */
121         np.cputime_count = &KCOUNT(&np, PC_TO_I(&np, cputime));
122         np.mcount_count = &KCOUNT(&np, PC_TO_I(&np, mcount));
123         np.mexitcount_count = &KCOUNT(&np, PC_TO_I(&np, mexitcount));
124 #endif
125         critical_enter();
126         bcopy(p->tos, np.tos, p->tossize);
127         bzero((char *)np.tos + p->tossize, np.tossize - p->tossize);
128         bcopy(p->kcount, np.kcount, p->kcountsize);
129         bzero((char *)np.kcount + p->kcountsize, np.kcountsize -
130             p->kcountsize);
131         bcopy(p->froms, np.froms, p->fromssize);
132         bzero((char *)np.froms + p->fromssize, np.fromssize - p->fromssize);
133         cp = (char *)p->tos;
134         bcopy(&np, p, sizeof(*p));
135         critical_exit();
136         free(cp, M_GPROF);
137 }
138
139 static void
140 kmstartup(void *dummy)
141 {
142         char *cp;
143         struct gmonparam *p = &_gmonparam;
144 #ifdef GUPROF
145         int cputime_overhead;
146         int empty_loop_time;
147         int i;
148         int mcount_overhead;
149         int mexitcount_overhead;
150         int nullfunc_loop_overhead;
151         int nullfunc_loop_profiled_time;
152         uintfptr_t tmp_addr;
153 #endif
154
155         /*
156          * Round lowpc and highpc to multiples of the density we're using
157          * so the rest of the scaling (here and in gprof) stays in ints.
158          */
159         p->lowpc = ROUNDDOWN((u_long)btext, HISTFRACTION * sizeof(HISTCOUNTER));
160         p->highpc = ROUNDUP((u_long)etext, HISTFRACTION * sizeof(HISTCOUNTER));
161         p->textsize = p->highpc - p->lowpc;
162         printf("Profiling kernel, textsize=%lu [%jx..%jx]\n",
163             p->textsize, (uintmax_t)p->lowpc, (uintmax_t)p->highpc);
164         p->kcountsize = p->textsize / HISTFRACTION;
165         p->hashfraction = HASHFRACTION;
166         p->fromssize = p->textsize / HASHFRACTION;
167         p->tolimit = p->textsize * ARCDENSITY / 100;
168         if (p->tolimit < MINARCS)
169                 p->tolimit = MINARCS;
170         else if (p->tolimit > MAXARCS)
171                 p->tolimit = MAXARCS;
172         p->tossize = p->tolimit * sizeof(struct tostruct);
173         cp = (char *)malloc(p->kcountsize + p->fromssize + p->tossize,
174             M_GPROF, M_WAITOK | M_ZERO);
175         p->tos = (struct tostruct *)cp;
176         cp += p->tossize;
177         p->kcount = (HISTCOUNTER *)cp;
178         cp += p->kcountsize;
179         p->froms = (u_short *)cp;
180         p->histcounter_type = FUNCTION_ALIGNMENT / HISTFRACTION * NBBY;
181
182 #ifdef GUPROF
183         /* Signed counters. */
184         p->histcounter_type = -p->histcounter_type;
185
186         /* Initialize pointers to overhead counters. */
187         p->cputime_count = &KCOUNT(p, PC_TO_I(p, cputime));
188         p->mcount_count = &KCOUNT(p, PC_TO_I(p, mcount));
189         p->mexitcount_count = &KCOUNT(p, PC_TO_I(p, mexitcount));
190
191         /*
192          * Disable interrupts to avoid interference while we calibrate
193          * things.
194          */
195         critical_enter();
196
197         /*
198          * Determine overheads.
199          * XXX this needs to be repeated for each useful timer/counter.
200          */
201         cputime_overhead = 0;
202         startguprof(p);
203         for (i = 0; i < CALIB_SCALE; i++)
204                 cputime_overhead += cputime();
205
206         empty_loop();
207         startguprof(p);
208         empty_loop();
209         empty_loop_time = cputime();
210
211         nullfunc_loop_profiled();
212
213         /*
214          * Start profiling.  There won't be any normal function calls since
215          * interrupts are disabled, but we will call the profiling routines
216          * directly to determine their overheads.
217          */
218         p->state = GMON_PROF_HIRES;
219
220         startguprof(p);
221         nullfunc_loop_profiled();
222
223         startguprof(p);
224         for (i = 0; i < CALIB_SCALE; i++)
225                 MCOUNT_OVERHEAD(sys_profil);
226         mcount_overhead = KCOUNT(p, PC_TO_I(p, sys_profil));
227
228         startguprof(p);
229         for (i = 0; i < CALIB_SCALE; i++)
230                 MEXITCOUNT_OVERHEAD();
231         MEXITCOUNT_OVERHEAD_GETLABEL(tmp_addr);
232         mexitcount_overhead = KCOUNT(p, PC_TO_I(p, tmp_addr));
233
234         p->state = GMON_PROF_OFF;
235         stopguprof(p);
236
237         critical_exit();
238
239         nullfunc_loop_profiled_time = 0;
240         for (tmp_addr = (uintfptr_t)nullfunc_loop_profiled;
241              tmp_addr < (uintfptr_t)nullfunc_loop_profiled_end;
242              tmp_addr += HISTFRACTION * sizeof(HISTCOUNTER))
243                 nullfunc_loop_profiled_time += KCOUNT(p, PC_TO_I(p, tmp_addr));
244 #define CALIB_DOSCALE(count)    (((count) + CALIB_SCALE / 3) / CALIB_SCALE)
245 #define c2n(count, freq)        ((int)((count) * 1000000000LL / freq))
246         printf("cputime %d, empty_loop %d, nullfunc_loop_profiled %d, mcount %d, mexitcount %d\n",
247                CALIB_DOSCALE(c2n(cputime_overhead, p->profrate)),
248                CALIB_DOSCALE(c2n(empty_loop_time, p->profrate)),
249                CALIB_DOSCALE(c2n(nullfunc_loop_profiled_time, p->profrate)),
250                CALIB_DOSCALE(c2n(mcount_overhead, p->profrate)),
251                CALIB_DOSCALE(c2n(mexitcount_overhead, p->profrate)));
252         cputime_overhead -= empty_loop_time;
253         mcount_overhead -= empty_loop_time;
254         mexitcount_overhead -= empty_loop_time;
255
256         /*-
257          * Profiling overheads are determined by the times between the
258          * following events:
259          *      MC1: mcount() is called
260          *      MC2: cputime() (called from mcount()) latches the timer
261          *      MC3: mcount() completes
262          *      ME1: mexitcount() is called
263          *      ME2: cputime() (called from mexitcount()) latches the timer
264          *      ME3: mexitcount() completes.
265          * The times between the events vary slightly depending on instruction
266          * combination and cache misses, etc.  Attempt to determine the
267          * minimum times.  These can be subtracted from the profiling times
268          * without much risk of reducing the profiling times below what they
269          * would be when profiling is not configured.  Abbreviate:
270          *      ab = minimum time between MC1 and MC3
271          *      a  = minimum time between MC1 and MC2
272          *      b  = minimum time between MC2 and MC3
273          *      cd = minimum time between ME1 and ME3
274          *      c  = minimum time between ME1 and ME2
275          *      d  = minimum time between ME2 and ME3.
276          * These satisfy the relations:
277          *      ab            <= mcount_overhead                (just measured)
278          *      a + b         <= ab
279          *              cd    <= mexitcount_overhead            (just measured)
280          *              c + d <= cd
281          *      a         + d <= nullfunc_loop_profiled_time    (just measured)
282          *      a >= 0, b >= 0, c >= 0, d >= 0.
283          * Assume that ab and cd are equal to the minimums.
284          */
285         p->cputime_overhead = CALIB_DOSCALE(cputime_overhead);
286         p->mcount_overhead = CALIB_DOSCALE(mcount_overhead - cputime_overhead);
287         p->mexitcount_overhead = CALIB_DOSCALE(mexitcount_overhead
288                                                - cputime_overhead);
289         nullfunc_loop_overhead = nullfunc_loop_profiled_time - empty_loop_time;
290         p->mexitcount_post_overhead = CALIB_DOSCALE((mcount_overhead
291                                                      - nullfunc_loop_overhead)
292                                                     / 4);
293         p->mexitcount_pre_overhead = p->mexitcount_overhead
294                                      + p->cputime_overhead
295                                      - p->mexitcount_post_overhead;
296         p->mcount_pre_overhead = CALIB_DOSCALE(nullfunc_loop_overhead)
297                                  - p->mexitcount_post_overhead;
298         p->mcount_post_overhead = p->mcount_overhead
299                                   + p->cputime_overhead
300                                   - p->mcount_pre_overhead;
301         printf(
302 "Profiling overheads: mcount: %d+%d, %d+%d; mexitcount: %d+%d, %d+%d nsec\n",
303                c2n(p->cputime_overhead, p->profrate),
304                c2n(p->mcount_overhead, p->profrate),
305                c2n(p->mcount_pre_overhead, p->profrate),
306                c2n(p->mcount_post_overhead, p->profrate),
307                c2n(p->cputime_overhead, p->profrate),
308                c2n(p->mexitcount_overhead, p->profrate),
309                c2n(p->mexitcount_pre_overhead, p->profrate),
310                c2n(p->mexitcount_post_overhead, p->profrate));
311         printf(
312 "Profiling overheads: mcount: %d+%d, %d+%d; mexitcount: %d+%d, %d+%d cycles\n",
313                p->cputime_overhead, p->mcount_overhead,
314                p->mcount_pre_overhead, p->mcount_post_overhead,
315                p->cputime_overhead, p->mexitcount_overhead,
316                p->mexitcount_pre_overhead, p->mexitcount_post_overhead);
317 #endif /* GUPROF */
318 }
319
320 /*
321  * Return kernel profiling information.
322  */
323 static int
324 sysctl_kern_prof(SYSCTL_HANDLER_ARGS)
325 {
326         int *name = (int *) arg1;
327         u_int namelen = arg2;
328         struct gmonparam *gp = &_gmonparam;
329         int error;
330         int state;
331
332         /* all sysctl names at this level are terminal */
333         if (namelen != 1)
334                 return (ENOTDIR);               /* overloaded */
335
336         switch (name[0]) {
337         case GPROF_STATE:
338                 state = gp->state;
339                 error = sysctl_handle_int(oidp, &state, 0, req);
340                 if (error)
341                         return (error);
342                 if (!req->newptr)
343                         return (0);
344                 if (state == GMON_PROF_OFF) {
345                         gp->state = state;
346                         PROC_LOCK(&proc0);
347                         stopprofclock(&proc0);
348                         PROC_UNLOCK(&proc0);
349                         stopguprof(gp);
350                 } else if (state == GMON_PROF_ON) {
351                         gp->state = GMON_PROF_OFF;
352                         stopguprof(gp);
353                         gp->profrate = profhz;
354                         PROC_LOCK(&proc0);
355                         startprofclock(&proc0);
356                         PROC_UNLOCK(&proc0);
357                         gp->state = state;
358 #ifdef GUPROF
359                 } else if (state == GMON_PROF_HIRES) {
360                         gp->state = GMON_PROF_OFF;
361                         PROC_LOCK(&proc0);
362                         stopprofclock(&proc0);
363                         PROC_UNLOCK(&proc0);
364                         startguprof(gp);
365                         gp->state = state;
366 #endif
367                 } else if (state != gp->state)
368                         return (EINVAL);
369                 return (0);
370         case GPROF_COUNT:
371                 return (sysctl_handle_opaque(oidp, 
372                         gp->kcount, gp->kcountsize, req));
373         case GPROF_FROMS:
374                 return (sysctl_handle_opaque(oidp, 
375                         gp->froms, gp->fromssize, req));
376         case GPROF_TOS:
377                 return (sysctl_handle_opaque(oidp, 
378                         gp->tos, gp->tossize, req));
379         case GPROF_GMONPARAM:
380                 return (sysctl_handle_opaque(oidp, gp, sizeof *gp, req));
381         default:
382                 return (EOPNOTSUPP);
383         }
384         /* NOTREACHED */
385 }
386
387 static SYSCTL_NODE(_kern, KERN_PROF, prof,
388     CTLFLAG_RW | CTLFLAG_MPSAFE, sysctl_kern_prof,
389     "");
390 #endif /* GPROF */
391
392 /*
393  * Profiling system call.
394  *
395  * The scale factor is a fixed point number with 16 bits of fraction, so that
396  * 1.0 is represented as 0x10000.  A scale factor of 0 turns off profiling.
397  */
398 #ifndef _SYS_SYSPROTO_H_
399 struct profil_args {
400         caddr_t samples;
401         size_t  size;
402         size_t  offset;
403         u_int   scale;
404 };
405 #endif
406 /* ARGSUSED */
407 int
408 sys_profil(struct thread *td, struct profil_args *uap)
409 {
410         struct uprof *upp;
411         struct proc *p;
412
413         if (uap->scale > (1 << 16))
414                 return (EINVAL);
415
416         p = td->td_proc;
417         if (uap->scale == 0) {
418                 PROC_LOCK(p);
419                 stopprofclock(p);
420                 PROC_UNLOCK(p);
421                 return (0);
422         }
423         PROC_LOCK(p);
424         upp = &td->td_proc->p_stats->p_prof;
425         PROC_PROFLOCK(p);
426         upp->pr_off = uap->offset;
427         upp->pr_scale = uap->scale;
428         upp->pr_base = uap->samples;
429         upp->pr_size = uap->size;
430         PROC_PROFUNLOCK(p);
431         startprofclock(p);
432         PROC_UNLOCK(p);
433
434         return (0);
435 }
436
437 /*
438  * Scale is a fixed-point number with the binary point 16 bits
439  * into the value, and is <= 1.0.  pc is at most 32 bits, so the
440  * intermediate result is at most 48 bits.
441  */
442 #define PC_TO_INDEX(pc, prof) \
443         ((int)(((u_quad_t)((pc) - (prof)->pr_off) * \
444             (u_quad_t)((prof)->pr_scale)) >> 16) & ~1)
445
446 /*
447  * Collect user-level profiling statistics; called on a profiling tick,
448  * when a process is running in user-mode.  This routine may be called
449  * from an interrupt context.  We perform the update with an AST
450  * that will vector us to trap() with a context in which copyin and
451  * copyout will work.  Trap will then call addupc_task().
452  *
453  * Note that we may (rarely) not get around to the AST soon enough, and
454  * lose profile ticks when the next tick overwrites this one, but in this
455  * case the system is overloaded and the profile is probably already
456  * inaccurate.
457  */
458 void
459 addupc_intr(struct thread *td, uintfptr_t pc, u_int ticks)
460 {
461         struct uprof *prof;
462
463         if (ticks == 0)
464                 return;
465         prof = &td->td_proc->p_stats->p_prof;
466         PROC_PROFLOCK(td->td_proc);
467         if (pc < prof->pr_off || PC_TO_INDEX(pc, prof) >= prof->pr_size) {
468                 PROC_PROFUNLOCK(td->td_proc);
469                 return;                 /* out of range; ignore */
470         }
471
472         PROC_PROFUNLOCK(td->td_proc);
473         td->td_profil_addr = pc;
474         td->td_profil_ticks = ticks;
475         td->td_pflags |= TDP_OWEUPC;
476         thread_lock(td);
477         td->td_flags |= TDF_ASTPENDING;
478         thread_unlock(td);
479 }
480
481 /*
482  * Actually update the profiling statistics.  If the update fails, we
483  * simply turn off profiling.
484  */
485 void
486 addupc_task(struct thread *td, uintfptr_t pc, u_int ticks)
487 {
488         struct proc *p = td->td_proc; 
489         struct uprof *prof;
490         caddr_t addr;
491         u_int i;
492         u_short v;
493         int stop = 0;
494
495         if (ticks == 0)
496                 return;
497
498         PROC_LOCK(p);
499         if (!(p->p_flag & P_PROFIL)) {
500                 PROC_UNLOCK(p);
501                 return;
502         }
503         p->p_profthreads++;
504         prof = &p->p_stats->p_prof;
505         PROC_PROFLOCK(p);
506         if (pc < prof->pr_off ||
507             (i = PC_TO_INDEX(pc, prof)) >= prof->pr_size) {
508                 PROC_PROFUNLOCK(p);
509                 goto out;
510         }
511
512         addr = prof->pr_base + i;
513         PROC_PROFUNLOCK(p);
514         PROC_UNLOCK(p);
515         if (copyin(addr, &v, sizeof(v)) == 0) {
516                 v += ticks;
517                 if (copyout(&v, addr, sizeof(v)) == 0) {
518                         PROC_LOCK(p);
519                         goto out;
520                 }
521         }
522         stop = 1;
523         PROC_LOCK(p);
524
525 out:
526         if (--p->p_profthreads == 0) {
527                 if (p->p_flag & P_STOPPROF) {
528                         wakeup(&p->p_profthreads);
529                         p->p_flag &= ~P_STOPPROF;
530                         stop = 0;
531                 }
532         }
533         if (stop)
534                 stopprofclock(p);
535         PROC_UNLOCK(p);
536 }