]> CyberLeo.Net >> Repos - FreeBSD/releng/8.0.git/blob - sys/dev/hwpmc/hwpmc_logging.c
Adjust to reflect 8.0-RELEASE.
[FreeBSD/releng/8.0.git] / sys / dev / hwpmc / hwpmc_logging.c
1 /*-
2  * Copyright (c) 2005-2007 Joseph Koshy
3  * Copyright (c) 2007 The FreeBSD Foundation
4  * All rights reserved.
5  *
6  * Portions of this software were developed by A. Joseph Koshy under
7  * sponsorship from the FreeBSD Foundation and Google, Inc.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  */
31
32 /*
33  * Logging code for hwpmc(4)
34  */
35
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
38
39 #include <sys/param.h>
40 #include <sys/file.h>
41 #include <sys/kernel.h>
42 #include <sys/kthread.h>
43 #include <sys/lock.h>
44 #include <sys/module.h>
45 #include <sys/mutex.h>
46 #include <sys/pmc.h>
47 #include <sys/pmckern.h>
48 #include <sys/pmclog.h>
49 #include <sys/proc.h>
50 #include <sys/signalvar.h>
51 #include <sys/sysctl.h>
52 #include <sys/systm.h>
53 #include <sys/uio.h>
54 #include <sys/unistd.h>
55 #include <sys/vnode.h>
56
57 /*
58  * Sysctl tunables
59  */
60
61 SYSCTL_DECL(_kern_hwpmc);
62
63 /*
64  * kern.hwpmc.logbuffersize -- size of the per-cpu owner buffers.
65  */
66
67 static int pmclog_buffer_size = PMC_LOG_BUFFER_SIZE;
68 TUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "logbuffersize", &pmclog_buffer_size);
69 SYSCTL_INT(_kern_hwpmc, OID_AUTO, logbuffersize, CTLFLAG_TUN|CTLFLAG_RD,
70     &pmclog_buffer_size, 0, "size of log buffers in kilobytes");
71
72 /*
73  * kern.hwpmc.nbuffer -- number of global log buffers
74  */
75
76 static int pmc_nlogbuffers = PMC_NLOGBUFFERS;
77 TUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "nbuffers", &pmc_nlogbuffers);
78 SYSCTL_INT(_kern_hwpmc, OID_AUTO, nbuffers, CTLFLAG_TUN|CTLFLAG_RD,
79     &pmc_nlogbuffers, 0, "number of global log buffers");
80
81 /*
82  * Global log buffer list and associated spin lock.
83  */
84
85 TAILQ_HEAD(, pmclog_buffer) pmc_bufferlist =
86         TAILQ_HEAD_INITIALIZER(pmc_bufferlist);
87 static struct mtx pmc_bufferlist_mtx;   /* spin lock */
88 static struct mtx pmc_kthread_mtx;      /* sleep lock */
89
90 #define PMCLOG_INIT_BUFFER_DESCRIPTOR(D) do {                           \
91                 const int __roundup = roundup(sizeof(*D),               \
92                         sizeof(uint32_t));                              \
93                 (D)->plb_fence = ((char *) (D)) +                       \
94                          1024*pmclog_buffer_size;                       \
95                 (D)->plb_base  = (D)->plb_ptr = ((char *) (D)) +        \
96                         __roundup;                                      \
97         } while (0)
98
99
100 /*
101  * Log file record constructors.
102  */
103 #define _PMCLOG_TO_HEADER(T,L)                                          \
104         ((PMCLOG_HEADER_MAGIC << 24) |                                  \
105          (PMCLOG_TYPE_ ## T << 16)   |                                  \
106          ((L) & 0xFFFF))
107
108 /* reserve LEN bytes of space and initialize the entry header */
109 #define _PMCLOG_RESERVE(PO,TYPE,LEN,ACTION) do {                        \
110                 uint32_t *_le;                                          \
111                 int _len = roundup((LEN), sizeof(uint32_t));            \
112                 if ((_le = pmclog_reserve((PO), _len)) == NULL) {       \
113                         ACTION;                                         \
114                 }                                                       \
115                 *_le = _PMCLOG_TO_HEADER(TYPE,_len);                    \
116                 _le += 3        /* skip over timestamp */
117
118 #define PMCLOG_RESERVE(P,T,L)           _PMCLOG_RESERVE(P,T,L,return)
119 #define PMCLOG_RESERVE_WITH_ERROR(P,T,L) _PMCLOG_RESERVE(P,T,L,         \
120         error=ENOMEM;goto error)
121
122 #define PMCLOG_EMIT32(V)        do { *_le++ = (V); } while (0)
123 #define PMCLOG_EMIT64(V)        do {                                    \
124                 *_le++ = (uint32_t) ((V) & 0xFFFFFFFF);                 \
125                 *_le++ = (uint32_t) (((V) >> 32) & 0xFFFFFFFF);         \
126         } while (0)
127
128
129 /* Emit a string.  Caution: does NOT update _le, so needs to be last */
130 #define PMCLOG_EMITSTRING(S,L)  do { bcopy((S), _le, (L)); } while (0)
131
132 #define PMCLOG_DESPATCH(PO)                                             \
133                 pmclog_release((PO));                                   \
134         } while (0)
135
136
137 /*
138  * Assertions about the log file format.
139  */
140
141 CTASSERT(sizeof(struct pmclog_callchain) == 6*4 +
142     PMC_CALLCHAIN_DEPTH_MAX*sizeof(uintfptr_t));
143 CTASSERT(sizeof(struct pmclog_closelog) == 3*4);
144 CTASSERT(sizeof(struct pmclog_dropnotify) == 3*4);
145 CTASSERT(sizeof(struct pmclog_map_in) == PATH_MAX +
146     4*4 + sizeof(uintfptr_t));
147 CTASSERT(offsetof(struct pmclog_map_in,pl_pathname) ==
148     4*4 + sizeof(uintfptr_t));
149 CTASSERT(sizeof(struct pmclog_map_out) == 4*4 + 2*sizeof(uintfptr_t));
150 CTASSERT(sizeof(struct pmclog_pcsample) == 6*4 + sizeof(uintfptr_t));
151 CTASSERT(sizeof(struct pmclog_pmcallocate) == 6*4);
152 CTASSERT(sizeof(struct pmclog_pmcattach) == 5*4 + PATH_MAX);
153 CTASSERT(offsetof(struct pmclog_pmcattach,pl_pathname) == 5*4);
154 CTASSERT(sizeof(struct pmclog_pmcdetach) == 5*4);
155 CTASSERT(sizeof(struct pmclog_proccsw) == 5*4 + 8);
156 CTASSERT(sizeof(struct pmclog_procexec) == 5*4 + PATH_MAX +
157     sizeof(uintfptr_t));
158 CTASSERT(offsetof(struct pmclog_procexec,pl_pathname) == 5*4 +
159     sizeof(uintfptr_t));
160 CTASSERT(sizeof(struct pmclog_procexit) == 5*4 + 8);
161 CTASSERT(sizeof(struct pmclog_procfork) == 5*4);
162 CTASSERT(sizeof(struct pmclog_sysexit) == 4*4);
163 CTASSERT(sizeof(struct pmclog_userdata) == 4*4);
164
165 /*
166  * Log buffer structure
167  */
168
169 struct pmclog_buffer {
170         TAILQ_ENTRY(pmclog_buffer) plb_next;
171         char            *plb_base;
172         char            *plb_ptr;
173         char            *plb_fence;
174 };
175
176 /*
177  * Prototypes
178  */
179
180 static int pmclog_get_buffer(struct pmc_owner *po);
181 static void pmclog_loop(void *arg);
182 static void pmclog_release(struct pmc_owner *po);
183 static uint32_t *pmclog_reserve(struct pmc_owner *po, int length);
184 static void pmclog_schedule_io(struct pmc_owner *po);
185 static void pmclog_stop_kthread(struct pmc_owner *po);
186
187 /*
188  * Helper functions
189  */
190
191 /*
192  * Get a log buffer
193  */
194
195 static int
196 pmclog_get_buffer(struct pmc_owner *po)
197 {
198         struct pmclog_buffer *plb;
199
200         mtx_assert(&po->po_mtx, MA_OWNED);
201
202         KASSERT(po->po_curbuf == NULL,
203             ("[pmclog,%d] po=%p current buffer still valid", __LINE__, po));
204
205         mtx_lock_spin(&pmc_bufferlist_mtx);
206         if ((plb = TAILQ_FIRST(&pmc_bufferlist)) != NULL)
207                 TAILQ_REMOVE(&pmc_bufferlist, plb, plb_next);
208         mtx_unlock_spin(&pmc_bufferlist_mtx);
209
210         PMCDBG(LOG,GTB,1, "po=%p plb=%p", po, plb);
211
212 #ifdef  DEBUG
213         if (plb)
214                 KASSERT(plb->plb_ptr == plb->plb_base &&
215                     plb->plb_base < plb->plb_fence,
216                     ("[pmclog,%d] po=%p buffer invariants: ptr=%p "
217                     "base=%p fence=%p", __LINE__, po, plb->plb_ptr,
218                     plb->plb_base, plb->plb_fence));
219 #endif
220
221         po->po_curbuf = plb;
222
223         /* update stats */
224         atomic_add_int(&pmc_stats.pm_buffer_requests, 1);
225         if (plb == NULL)
226                 atomic_add_int(&pmc_stats.pm_buffer_requests_failed, 1);
227
228         return (plb ? 0 : ENOMEM);
229 }
230
231 /*
232  * Log handler loop.
233  *
234  * This function is executed by each pmc owner's helper thread.
235  */
236
237 static void
238 pmclog_loop(void *arg)
239 {
240         int error;
241         struct pmc_owner *po;
242         struct pmclog_buffer *lb;
243         struct ucred *ownercred;
244         struct ucred *mycred;
245         struct thread *td;
246         struct uio auio;
247         struct iovec aiov;
248         size_t nbytes;
249
250         po = (struct pmc_owner *) arg;
251         td = curthread;
252         mycred = td->td_ucred;
253
254         PROC_LOCK(po->po_owner);
255         ownercred = crhold(po->po_owner->p_ucred);
256         PROC_UNLOCK(po->po_owner);
257
258         PMCDBG(LOG,INI,1, "po=%p kt=%p", po, po->po_kthread);
259         KASSERT(po->po_kthread == curthread->td_proc,
260             ("[pmclog,%d] proc mismatch po=%p po/kt=%p curproc=%p", __LINE__,
261                 po, po->po_kthread, curthread->td_proc));
262
263         lb = NULL;
264
265
266         /*
267          * Loop waiting for I/O requests to be added to the owner
268          * struct's queue.  The loop is exited when the log file
269          * is deconfigured.
270          */
271
272         mtx_lock(&pmc_kthread_mtx);
273
274         for (;;) {
275
276                 /* check if we've been asked to exit */
277                 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
278                         break;
279
280                 if (lb == NULL) { /* look for a fresh buffer to write */
281                         mtx_lock_spin(&po->po_mtx);
282                         if ((lb = TAILQ_FIRST(&po->po_logbuffers)) == NULL) {
283                                 mtx_unlock_spin(&po->po_mtx);
284
285                                 /*
286                                  * Wakeup the thread waiting for the
287                                  * PMC_OP_FLUSHLOG request to
288                                  * complete.
289                                  */
290                                 if (po->po_flags & PMC_PO_IN_FLUSH) {
291                                         po->po_flags &= ~PMC_PO_IN_FLUSH;
292                                         wakeup_one(po->po_kthread);
293                                 }
294
295                                 (void) msleep(po, &pmc_kthread_mtx, PWAIT,
296                                     "pmcloop", 0);
297                                 continue;
298                         }
299
300                         TAILQ_REMOVE(&po->po_logbuffers, lb, plb_next);
301                         mtx_unlock_spin(&po->po_mtx);
302                 }
303
304                 mtx_unlock(&pmc_kthread_mtx);
305
306                 /* process the request */
307                 PMCDBG(LOG,WRI,2, "po=%p base=%p ptr=%p", po,
308                     lb->plb_base, lb->plb_ptr);
309                 /* change our thread's credentials before issuing the I/O */
310
311                 aiov.iov_base = lb->plb_base;
312                 aiov.iov_len  = nbytes = lb->plb_ptr - lb->plb_base;
313
314                 auio.uio_iov    = &aiov;
315                 auio.uio_iovcnt = 1;
316                 auio.uio_offset = -1;
317                 auio.uio_resid  = nbytes;
318                 auio.uio_rw     = UIO_WRITE;
319                 auio.uio_segflg = UIO_SYSSPACE;
320                 auio.uio_td     = td;
321
322                 /* switch thread credentials -- see kern_ktrace.c */
323                 td->td_ucred = ownercred;
324                 error = fo_write(po->po_file, &auio, ownercred, 0, td);
325                 td->td_ucred = mycred;
326
327                 mtx_lock(&pmc_kthread_mtx);
328
329                 if (error) {
330                         /* XXX some errors are recoverable */
331                         /* XXX also check for SIGPIPE if a socket */
332
333                         /* send a SIGIO to the owner and exit */
334                         PROC_LOCK(po->po_owner);
335                         psignal(po->po_owner, SIGIO);
336                         PROC_UNLOCK(po->po_owner);
337
338                         po->po_error = error; /* save for flush log */
339
340                         PMCDBG(LOG,WRI,2, "po=%p error=%d", po, error);
341
342                         break;
343                 }
344
345                 /* put the used buffer back into the global pool */
346                 PMCLOG_INIT_BUFFER_DESCRIPTOR(lb);
347
348                 mtx_lock_spin(&pmc_bufferlist_mtx);
349                 TAILQ_INSERT_HEAD(&pmc_bufferlist, lb, plb_next);
350                 mtx_unlock_spin(&pmc_bufferlist_mtx);
351
352                 lb = NULL;
353         }
354
355         po->po_kthread = NULL;
356
357         mtx_unlock(&pmc_kthread_mtx);
358
359         /* return the current I/O buffer to the global pool */
360         if (lb) {
361                 PMCLOG_INIT_BUFFER_DESCRIPTOR(lb);
362
363                 mtx_lock_spin(&pmc_bufferlist_mtx);
364                 TAILQ_INSERT_HEAD(&pmc_bufferlist, lb, plb_next);
365                 mtx_unlock_spin(&pmc_bufferlist_mtx);
366         }
367
368         /*
369          * Exit this thread, signalling the waiter
370          */
371
372         crfree(ownercred);
373
374         kproc_exit(0);
375 }
376
377 /*
378  * Release and log entry and schedule an I/O if needed.
379  */
380
381 static void
382 pmclog_release(struct pmc_owner *po)
383 {
384         KASSERT(po->po_curbuf->plb_ptr >= po->po_curbuf->plb_base,
385             ("[pmclog,%d] buffer invariants po=%p ptr=%p base=%p", __LINE__,
386                 po, po->po_curbuf->plb_ptr, po->po_curbuf->plb_base));
387         KASSERT(po->po_curbuf->plb_ptr <= po->po_curbuf->plb_fence,
388             ("[pmclog,%d] buffer invariants po=%p ptr=%p fenc=%p", __LINE__,
389                 po, po->po_curbuf->plb_ptr, po->po_curbuf->plb_fence));
390
391         /* schedule an I/O if we've filled a buffer */
392         if (po->po_curbuf->plb_ptr >= po->po_curbuf->plb_fence)
393                 pmclog_schedule_io(po);
394
395         mtx_unlock_spin(&po->po_mtx);
396
397         PMCDBG(LOG,REL,1, "po=%p", po);
398 }
399
400
401 /*
402  * Attempt to reserve 'length' bytes of space in an owner's log
403  * buffer.  The function returns a pointer to 'length' bytes of space
404  * if there was enough space or returns NULL if no space was
405  * available.  Non-null returns do so with the po mutex locked.  The
406  * caller must invoke pmclog_release() on the pmc owner structure
407  * when done.
408  */
409
410 static uint32_t *
411 pmclog_reserve(struct pmc_owner *po, int length)
412 {
413         uintptr_t newptr, oldptr;
414         uint32_t *lh;
415         struct timespec ts;
416
417         PMCDBG(LOG,ALL,1, "po=%p len=%d", po, length);
418
419         KASSERT(length % sizeof(uint32_t) == 0,
420             ("[pmclog,%d] length not a multiple of word size", __LINE__));
421
422         mtx_lock_spin(&po->po_mtx);
423
424         if (po->po_curbuf == NULL)
425                 if (pmclog_get_buffer(po) != 0) {
426                         mtx_unlock_spin(&po->po_mtx);
427                         return (NULL);
428                 }
429
430         KASSERT(po->po_curbuf != NULL,
431             ("[pmclog,%d] po=%p no current buffer", __LINE__, po));
432
433         KASSERT(po->po_curbuf->plb_ptr >= po->po_curbuf->plb_base &&
434             po->po_curbuf->plb_ptr <= po->po_curbuf->plb_fence,
435             ("[pmclog,%d] po=%p buffer invariants: ptr=%p base=%p fence=%p",
436                 __LINE__, po, po->po_curbuf->plb_ptr, po->po_curbuf->plb_base,
437                 po->po_curbuf->plb_fence));
438
439         oldptr = (uintptr_t) po->po_curbuf->plb_ptr;
440         newptr = oldptr + length;
441
442         KASSERT(oldptr != (uintptr_t) NULL,
443             ("[pmclog,%d] po=%p Null log buffer pointer", __LINE__, po));
444
445         /*
446          * If we have space in the current buffer, return a pointer to
447          * available space with the PO structure locked.
448          */
449         if (newptr <= (uintptr_t) po->po_curbuf->plb_fence) {
450                 po->po_curbuf->plb_ptr = (char *) newptr;
451                 goto done;
452         }
453
454         /*
455          * Otherwise, schedule the current buffer for output and get a
456          * fresh buffer.
457          */
458         pmclog_schedule_io(po);
459
460         if (pmclog_get_buffer(po) != 0) {
461                 mtx_unlock_spin(&po->po_mtx);
462                 return (NULL);
463         }
464
465         KASSERT(po->po_curbuf != NULL,
466             ("[pmclog,%d] po=%p no current buffer", __LINE__, po));
467
468         KASSERT(po->po_curbuf->plb_ptr != NULL,
469             ("[pmclog,%d] null return from pmc_get_log_buffer", __LINE__));
470
471         KASSERT(po->po_curbuf->plb_ptr == po->po_curbuf->plb_base &&
472             po->po_curbuf->plb_ptr <= po->po_curbuf->plb_fence,
473             ("[pmclog,%d] po=%p buffer invariants: ptr=%p base=%p fence=%p",
474                 __LINE__, po, po->po_curbuf->plb_ptr, po->po_curbuf->plb_base,
475                 po->po_curbuf->plb_fence));
476
477         oldptr = (uintptr_t) po->po_curbuf->plb_ptr;
478
479  done:
480         lh = (uint32_t *) oldptr;
481         lh++;                           /* skip header */
482         getnanotime(&ts);               /* fill in the timestamp */
483         *lh++ = ts.tv_sec & 0xFFFFFFFF;
484         *lh++ = ts.tv_nsec & 0xFFFFFFF;
485         return ((uint32_t *) oldptr);
486 }
487
488 /*
489  * Schedule an I/O.
490  *
491  * Transfer the current buffer to the helper kthread.
492  */
493
494 static void
495 pmclog_schedule_io(struct pmc_owner *po)
496 {
497         KASSERT(po->po_curbuf != NULL,
498             ("[pmclog,%d] schedule_io with null buffer po=%p", __LINE__, po));
499
500         KASSERT(po->po_curbuf->plb_ptr >= po->po_curbuf->plb_base,
501             ("[pmclog,%d] buffer invariants po=%p ptr=%p base=%p", __LINE__,
502                 po, po->po_curbuf->plb_ptr, po->po_curbuf->plb_base));
503         KASSERT(po->po_curbuf->plb_ptr <= po->po_curbuf->plb_fence,
504             ("[pmclog,%d] buffer invariants po=%p ptr=%p fenc=%p", __LINE__,
505                 po, po->po_curbuf->plb_ptr, po->po_curbuf->plb_fence));
506
507         PMCDBG(LOG,SIO, 1, "po=%p", po);
508
509         mtx_assert(&po->po_mtx, MA_OWNED);
510
511         /*
512          * Add the current buffer to the tail of the buffer list and
513          * wakeup the helper.
514          */
515         TAILQ_INSERT_TAIL(&po->po_logbuffers, po->po_curbuf, plb_next);
516         po->po_curbuf = NULL;
517         wakeup_one(po);
518 }
519
520 /*
521  * Stop the helper kthread.
522  */
523
524 static void
525 pmclog_stop_kthread(struct pmc_owner *po)
526 {
527         /*
528          * Unset flag, wakeup the helper thread,
529          * wait for it to exit
530          */
531
532         mtx_assert(&pmc_kthread_mtx, MA_OWNED);
533         po->po_flags &= ~PMC_PO_OWNS_LOGFILE;
534         wakeup_one(po);
535         if (po->po_kthread)
536                 msleep(po->po_kthread, &pmc_kthread_mtx, PPAUSE, "pmckstp", 0);
537 }
538
539 /*
540  * Public functions
541  */
542
543 /*
544  * Configure a log file for pmc owner 'po'.
545  *
546  * Parameter 'logfd' is a file handle referencing an open file in the
547  * owner process.  This file needs to have been opened for writing.
548  */
549
550 int
551 pmclog_configure_log(struct pmc_mdep *md, struct pmc_owner *po, int logfd)
552 {
553         int error;
554         struct proc *p;
555
556         /*
557          * As long as it is possible to get a LOR between pmc_sx lock and
558          * proctree/allproc sx locks used for adding a new process, assure
559          * the former is not held here.
560          */
561         sx_assert(&pmc_sx, SA_UNLOCKED);
562         PMCDBG(LOG,CFG,1, "config po=%p logfd=%d", po, logfd);
563
564         p = po->po_owner;
565
566         /* return EBUSY if a log file was already present */
567         if (po->po_flags & PMC_PO_OWNS_LOGFILE)
568                 return (EBUSY);
569
570         KASSERT(po->po_kthread == NULL,
571             ("[pmclog,%d] po=%p kthread (%p) already present", __LINE__, po,
572                 po->po_kthread));
573         KASSERT(po->po_file == NULL,
574             ("[pmclog,%d] po=%p file (%p) already present", __LINE__, po,
575                 po->po_file));
576
577         /* get a reference to the file state */
578         error = fget_write(curthread, logfd, &po->po_file);
579         if (error)
580                 goto error;
581
582         /* mark process as owning a log file */
583         po->po_flags |= PMC_PO_OWNS_LOGFILE;
584         error = kproc_create(pmclog_loop, po, &po->po_kthread,
585             RFHIGHPID, 0, "hwpmc: proc(%d)", p->p_pid);
586         if (error)
587                 goto error;
588
589         /* mark process as using HWPMCs */
590         PROC_LOCK(p);
591         p->p_flag |= P_HWPMC;
592         PROC_UNLOCK(p);
593
594         /* create a log initialization entry */
595         PMCLOG_RESERVE_WITH_ERROR(po, INITIALIZE,
596             sizeof(struct pmclog_initialize));
597         PMCLOG_EMIT32(PMC_VERSION);
598         PMCLOG_EMIT32(md->pmd_cputype);
599         PMCLOG_DESPATCH(po);
600
601         return (0);
602
603  error:
604         /* shutdown the thread */
605         mtx_lock(&pmc_kthread_mtx);
606         if (po->po_kthread)
607                 pmclog_stop_kthread(po);
608         mtx_unlock(&pmc_kthread_mtx);
609
610         KASSERT(po->po_kthread == NULL, ("[pmclog,%d] po=%p kthread not "
611             "stopped", __LINE__, po));
612
613         if (po->po_file)
614                 (void) fdrop(po->po_file, curthread);
615         po->po_file  = NULL;    /* clear file and error state */
616         po->po_error = 0;
617
618         return (error);
619 }
620
621
622 /*
623  * De-configure a log file.  This will throw away any buffers queued
624  * for this owner process.
625  */
626
627 int
628 pmclog_deconfigure_log(struct pmc_owner *po)
629 {
630         int error;
631         struct pmclog_buffer *lb;
632
633         PMCDBG(LOG,CFG,1, "de-config po=%p", po);
634
635         if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
636                 return (EINVAL);
637
638         KASSERT(po->po_sscount == 0,
639             ("[pmclog,%d] po=%p still owning SS PMCs", __LINE__, po));
640         KASSERT(po->po_file != NULL,
641             ("[pmclog,%d] po=%p no log file", __LINE__, po));
642
643         /* stop the kthread, this will reset the 'OWNS_LOGFILE' flag */
644         mtx_lock(&pmc_kthread_mtx);
645         if (po->po_kthread)
646                 pmclog_stop_kthread(po);
647         mtx_unlock(&pmc_kthread_mtx);
648
649         KASSERT(po->po_kthread == NULL,
650             ("[pmclog,%d] po=%p kthread not stopped", __LINE__, po));
651
652         /* return all queued log buffers to the global pool */
653         while ((lb = TAILQ_FIRST(&po->po_logbuffers)) != NULL) {
654                 TAILQ_REMOVE(&po->po_logbuffers, lb, plb_next);
655                 PMCLOG_INIT_BUFFER_DESCRIPTOR(lb);
656                 mtx_lock_spin(&pmc_bufferlist_mtx);
657                 TAILQ_INSERT_HEAD(&pmc_bufferlist, lb, plb_next);
658                 mtx_unlock_spin(&pmc_bufferlist_mtx);
659         }
660
661         /* return the 'current' buffer to the global pool */
662         if ((lb = po->po_curbuf) != NULL) {
663                 PMCLOG_INIT_BUFFER_DESCRIPTOR(lb);
664                 mtx_lock_spin(&pmc_bufferlist_mtx);
665                 TAILQ_INSERT_HEAD(&pmc_bufferlist, lb, plb_next);
666                 mtx_unlock_spin(&pmc_bufferlist_mtx);
667         }
668
669         /* drop a reference to the fd */
670         error = fdrop(po->po_file, curthread);
671         po->po_file  = NULL;
672         po->po_error = 0;
673
674         return (error);
675 }
676
677 /*
678  * Flush a process' log buffer.
679  */
680
681 int
682 pmclog_flush(struct pmc_owner *po)
683 {
684         int error, has_pending_buffers;
685
686         PMCDBG(LOG,FLS,1, "po=%p", po);
687
688         /*
689          * If there is a pending error recorded by the logger thread,
690          * return that.
691          */
692         if (po->po_error)
693                 return (po->po_error);
694
695         error = 0;
696
697         /*
698          * Check that we do have an active log file.
699          */
700         mtx_lock(&pmc_kthread_mtx);
701         if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0) {
702                 error = EINVAL;
703                 goto error;
704         }
705
706         /*
707          * Schedule the current buffer if any.
708          */
709         mtx_lock_spin(&po->po_mtx);
710         if (po->po_curbuf)
711                 pmclog_schedule_io(po);
712         has_pending_buffers = !TAILQ_EMPTY(&po->po_logbuffers);
713         mtx_unlock_spin(&po->po_mtx);
714
715         if (has_pending_buffers) {
716                 po->po_flags |= PMC_PO_IN_FLUSH; /* ask for a wakeup */
717                 error = msleep(po->po_kthread, &pmc_kthread_mtx, PWAIT,
718                     "pmcflush", 0);
719                 if (error == 0)
720                         error = po->po_error;
721         }
722
723  error:
724         mtx_unlock(&pmc_kthread_mtx);
725
726         return (error);
727 }
728
729
730 void
731 pmclog_process_callchain(struct pmc *pm, struct pmc_sample *ps)
732 {
733         int n, recordlen;
734         uint32_t flags;
735         struct pmc_owner *po;
736
737         PMCDBG(LOG,SAM,1,"pm=%p pid=%d n=%d", pm, ps->ps_pid,
738             ps->ps_nsamples);
739
740         recordlen = offsetof(struct pmclog_callchain, pl_pc) +
741             ps->ps_nsamples * sizeof(uintfptr_t);
742         po = pm->pm_owner;
743         flags = PMC_CALLCHAIN_TO_CPUFLAGS(ps->ps_cpu,ps->ps_flags);
744         PMCLOG_RESERVE(po, CALLCHAIN, recordlen);
745         PMCLOG_EMIT32(ps->ps_pid);
746         PMCLOG_EMIT32(pm->pm_id);
747         PMCLOG_EMIT32(flags);
748         for (n = 0; n < ps->ps_nsamples; n++)
749                 PMCLOG_EMITADDR(ps->ps_pc[n]);
750         PMCLOG_DESPATCH(po);
751 }
752
753 void
754 pmclog_process_closelog(struct pmc_owner *po)
755 {
756         PMCLOG_RESERVE(po,CLOSELOG,sizeof(struct pmclog_closelog));
757         PMCLOG_DESPATCH(po);
758 }
759
760 void
761 pmclog_process_dropnotify(struct pmc_owner *po)
762 {
763         PMCLOG_RESERVE(po,DROPNOTIFY,sizeof(struct pmclog_dropnotify));
764         PMCLOG_DESPATCH(po);
765 }
766
767 void
768 pmclog_process_map_in(struct pmc_owner *po, pid_t pid, uintfptr_t start,
769     const char *path)
770 {
771         int pathlen, recordlen;
772
773         KASSERT(path != NULL, ("[pmclog,%d] map-in, null path", __LINE__));
774
775         pathlen = strlen(path) + 1;     /* #bytes for path name */
776         recordlen = offsetof(struct pmclog_map_in, pl_pathname) +
777             pathlen;
778
779         PMCLOG_RESERVE(po, MAP_IN, recordlen);
780         PMCLOG_EMIT32(pid);
781         PMCLOG_EMITADDR(start);
782         PMCLOG_EMITSTRING(path,pathlen);
783         PMCLOG_DESPATCH(po);
784 }
785
786 void
787 pmclog_process_map_out(struct pmc_owner *po, pid_t pid, uintfptr_t start,
788     uintfptr_t end)
789 {
790         KASSERT(start <= end, ("[pmclog,%d] start > end", __LINE__));
791
792         PMCLOG_RESERVE(po, MAP_OUT, sizeof(struct pmclog_map_out));
793         PMCLOG_EMIT32(pid);
794         PMCLOG_EMITADDR(start);
795         PMCLOG_EMITADDR(end);
796         PMCLOG_DESPATCH(po);
797 }
798
799 void
800 pmclog_process_pmcallocate(struct pmc *pm)
801 {
802         struct pmc_owner *po;
803
804         po = pm->pm_owner;
805
806         PMCDBG(LOG,ALL,1, "pm=%p", pm);
807
808         PMCLOG_RESERVE(po, PMCALLOCATE, sizeof(struct pmclog_pmcallocate));
809         PMCLOG_EMIT32(pm->pm_id);
810         PMCLOG_EMIT32(pm->pm_event);
811         PMCLOG_EMIT32(pm->pm_flags);
812         PMCLOG_DESPATCH(po);
813 }
814
815 void
816 pmclog_process_pmcattach(struct pmc *pm, pid_t pid, char *path)
817 {
818         int pathlen, recordlen;
819         struct pmc_owner *po;
820
821         PMCDBG(LOG,ATT,1,"pm=%p pid=%d", pm, pid);
822
823         po = pm->pm_owner;
824
825         pathlen = strlen(path) + 1;     /* #bytes for the string */
826         recordlen = offsetof(struct pmclog_pmcattach, pl_pathname) + pathlen;
827
828         PMCLOG_RESERVE(po, PMCATTACH, recordlen);
829         PMCLOG_EMIT32(pm->pm_id);
830         PMCLOG_EMIT32(pid);
831         PMCLOG_EMITSTRING(path, pathlen);
832         PMCLOG_DESPATCH(po);
833 }
834
835 void
836 pmclog_process_pmcdetach(struct pmc *pm, pid_t pid)
837 {
838         struct pmc_owner *po;
839
840         PMCDBG(LOG,ATT,1,"!pm=%p pid=%d", pm, pid);
841
842         po = pm->pm_owner;
843
844         PMCLOG_RESERVE(po, PMCDETACH, sizeof(struct pmclog_pmcdetach));
845         PMCLOG_EMIT32(pm->pm_id);
846         PMCLOG_EMIT32(pid);
847         PMCLOG_DESPATCH(po);
848 }
849
850 /*
851  * Log a context switch event to the log file.
852  */
853
854 void
855 pmclog_process_proccsw(struct pmc *pm, struct pmc_process *pp, pmc_value_t v)
856 {
857         struct pmc_owner *po;
858
859         KASSERT(pm->pm_flags & PMC_F_LOG_PROCCSW,
860             ("[pmclog,%d] log-process-csw called gratuitously", __LINE__));
861
862         PMCDBG(LOG,SWO,1,"pm=%p pid=%d v=%jx", pm, pp->pp_proc->p_pid,
863             v);
864
865         po = pm->pm_owner;
866
867         PMCLOG_RESERVE(po, PROCCSW, sizeof(struct pmclog_proccsw));
868         PMCLOG_EMIT32(pm->pm_id);
869         PMCLOG_EMIT64(v);
870         PMCLOG_EMIT32(pp->pp_proc->p_pid);
871         PMCLOG_DESPATCH(po);
872 }
873
874 void
875 pmclog_process_procexec(struct pmc_owner *po, pmc_id_t pmid, pid_t pid,
876     uintfptr_t startaddr, char *path)
877 {
878         int pathlen, recordlen;
879
880         PMCDBG(LOG,EXC,1,"po=%p pid=%d path=\"%s\"", po, pid, path);
881
882         pathlen   = strlen(path) + 1;   /* #bytes for the path */
883         recordlen = offsetof(struct pmclog_procexec, pl_pathname) + pathlen;
884
885         PMCLOG_RESERVE(po, PROCEXEC, recordlen);
886         PMCLOG_EMIT32(pid);
887         PMCLOG_EMITADDR(startaddr);
888         PMCLOG_EMIT32(pmid);
889         PMCLOG_EMITSTRING(path,pathlen);
890         PMCLOG_DESPATCH(po);
891 }
892
893 /*
894  * Log a process exit event (and accumulated pmc value) to the log file.
895  */
896
897 void
898 pmclog_process_procexit(struct pmc *pm, struct pmc_process *pp)
899 {
900         int ri;
901         struct pmc_owner *po;
902
903         ri = PMC_TO_ROWINDEX(pm);
904         PMCDBG(LOG,EXT,1,"pm=%p pid=%d v=%jx", pm, pp->pp_proc->p_pid,
905             pp->pp_pmcs[ri].pp_pmcval);
906
907         po = pm->pm_owner;
908
909         PMCLOG_RESERVE(po, PROCEXIT, sizeof(struct pmclog_procexit));
910         PMCLOG_EMIT32(pm->pm_id);
911         PMCLOG_EMIT64(pp->pp_pmcs[ri].pp_pmcval);
912         PMCLOG_EMIT32(pp->pp_proc->p_pid);
913         PMCLOG_DESPATCH(po);
914 }
915
916 /*
917  * Log a fork event.
918  */
919
920 void
921 pmclog_process_procfork(struct pmc_owner *po, pid_t oldpid, pid_t newpid)
922 {
923         PMCLOG_RESERVE(po, PROCFORK, sizeof(struct pmclog_procfork));
924         PMCLOG_EMIT32(oldpid);
925         PMCLOG_EMIT32(newpid);
926         PMCLOG_DESPATCH(po);
927 }
928
929 /*
930  * Log a process exit event of the form suitable for system-wide PMCs.
931  */
932
933 void
934 pmclog_process_sysexit(struct pmc_owner *po, pid_t pid)
935 {
936         PMCLOG_RESERVE(po, SYSEXIT, sizeof(struct pmclog_sysexit));
937         PMCLOG_EMIT32(pid);
938         PMCLOG_DESPATCH(po);
939 }
940
941 /*
942  * Write a user log entry.
943  */
944
945 int
946 pmclog_process_userlog(struct pmc_owner *po, struct pmc_op_writelog *wl)
947 {
948         int error;
949
950         PMCDBG(LOG,WRI,1, "writelog po=%p ud=0x%x", po, wl->pm_userdata);
951
952         error = 0;
953
954         PMCLOG_RESERVE_WITH_ERROR(po, USERDATA,
955             sizeof(struct pmclog_userdata));
956         PMCLOG_EMIT32(wl->pm_userdata);
957         PMCLOG_DESPATCH(po);
958
959  error:
960         return (error);
961 }
962
963 /*
964  * Initialization.
965  *
966  * Create a pool of log buffers and initialize mutexes.
967  */
968
969 void
970 pmclog_initialize()
971 {
972         int n;
973         struct pmclog_buffer *plb;
974
975         if (pmclog_buffer_size <= 0) {
976                 (void) printf("hwpmc: tunable logbuffersize=%d must be "
977                     "greater than zero.\n", pmclog_buffer_size);
978                 pmclog_buffer_size = PMC_LOG_BUFFER_SIZE;
979         }
980
981         if (pmc_nlogbuffers <= 0) {
982                 (void) printf("hwpmc: tunable nlogbuffers=%d must be greater "
983                     "than zero.\n", pmc_nlogbuffers);
984                 pmc_nlogbuffers = PMC_NLOGBUFFERS;
985         }
986
987         /* create global pool of log buffers */
988         for (n = 0; n < pmc_nlogbuffers; n++) {
989                 plb = malloc(1024 * pmclog_buffer_size, M_PMC,
990                     M_WAITOK|M_ZERO);
991                 PMCLOG_INIT_BUFFER_DESCRIPTOR(plb);
992                 TAILQ_INSERT_HEAD(&pmc_bufferlist, plb, plb_next);
993         }
994         mtx_init(&pmc_bufferlist_mtx, "pmc-buffer-list", "pmc-leaf",
995             MTX_SPIN);
996         mtx_init(&pmc_kthread_mtx, "pmc-kthread", "pmc-sleep", MTX_DEF);
997 }
998
999 /*
1000  * Shutdown logging.
1001  *
1002  * Destroy mutexes and release memory back the to free pool.
1003  */
1004
1005 void
1006 pmclog_shutdown()
1007 {
1008         struct pmclog_buffer *plb;
1009
1010         mtx_destroy(&pmc_kthread_mtx);
1011         mtx_destroy(&pmc_bufferlist_mtx);
1012
1013         while ((plb = TAILQ_FIRST(&pmc_bufferlist)) != NULL) {
1014                 TAILQ_REMOVE(&pmc_bufferlist, plb, plb_next);
1015                 free(plb, M_PMC);
1016         }
1017 }