]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/dev/hwpmc/hwpmc_logging.c
MFC r362623:
[FreeBSD/stable/8.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 proc *p;
244         struct ucred *ownercred;
245         struct ucred *mycred;
246         struct thread *td;
247         struct uio auio;
248         struct iovec aiov;
249         size_t nbytes;
250
251         po = (struct pmc_owner *) arg;
252         p = po->po_owner;
253         td = curthread;
254         mycred = td->td_ucred;
255
256         PROC_LOCK(p);
257         ownercred = crhold(p->p_ucred);
258         PROC_UNLOCK(p);
259
260         PMCDBG(LOG,INI,1, "po=%p kt=%p", po, po->po_kthread);
261         KASSERT(po->po_kthread == curthread->td_proc,
262             ("[pmclog,%d] proc mismatch po=%p po/kt=%p curproc=%p", __LINE__,
263                 po, po->po_kthread, curthread->td_proc));
264
265         lb = NULL;
266
267
268         /*
269          * Loop waiting for I/O requests to be added to the owner
270          * struct's queue.  The loop is exited when the log file
271          * is deconfigured.
272          */
273
274         mtx_lock(&pmc_kthread_mtx);
275
276         for (;;) {
277
278                 /* check if we've been asked to exit */
279                 if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
280                         break;
281
282                 if (lb == NULL) { /* look for a fresh buffer to write */
283                         mtx_lock_spin(&po->po_mtx);
284                         if ((lb = TAILQ_FIRST(&po->po_logbuffers)) == NULL) {
285                                 mtx_unlock_spin(&po->po_mtx);
286
287                                 /* No more buffers and shutdown required. */
288                                 if (po->po_flags & PMC_PO_SHUTDOWN) {
289                                         mtx_unlock(&pmc_kthread_mtx);
290                                         /*
291                                          * Close the file to get PMCLOG_EOF
292                                          * error in pmclog(3).
293                                          */
294                                         fo_close(po->po_file, curthread);
295                                         mtx_lock(&pmc_kthread_mtx);
296                                         break;
297                                 }
298
299                                 (void) msleep(po, &pmc_kthread_mtx, PWAIT,
300                                     "pmcloop", 0);
301                                 continue;
302                         }
303
304                         TAILQ_REMOVE(&po->po_logbuffers, lb, plb_next);
305                         mtx_unlock_spin(&po->po_mtx);
306                 }
307
308                 mtx_unlock(&pmc_kthread_mtx);
309
310                 /* process the request */
311                 PMCDBG(LOG,WRI,2, "po=%p base=%p ptr=%p", po,
312                     lb->plb_base, lb->plb_ptr);
313                 /* change our thread's credentials before issuing the I/O */
314
315                 aiov.iov_base = lb->plb_base;
316                 aiov.iov_len  = nbytes = lb->plb_ptr - lb->plb_base;
317
318                 auio.uio_iov    = &aiov;
319                 auio.uio_iovcnt = 1;
320                 auio.uio_offset = -1;
321                 auio.uio_resid  = nbytes;
322                 auio.uio_rw     = UIO_WRITE;
323                 auio.uio_segflg = UIO_SYSSPACE;
324                 auio.uio_td     = td;
325
326                 /* switch thread credentials -- see kern_ktrace.c */
327                 td->td_ucred = ownercred;
328                 error = fo_write(po->po_file, &auio, ownercred, 0, td);
329                 td->td_ucred = mycred;
330
331                 if (error) {
332                         /* XXX some errors are recoverable */
333                         /* send a SIGIO to the owner and exit */
334                         PROC_LOCK(p);
335                         psignal(p, SIGIO);
336                         PROC_UNLOCK(p);
337
338                         mtx_lock(&pmc_kthread_mtx);
339
340                         po->po_error = error; /* save for flush log */
341
342                         PMCDBG(LOG,WRI,2, "po=%p error=%d", po, error);
343
344                         break;
345                 }
346
347                 mtx_lock(&pmc_kthread_mtx);
348
349                 /* put the used buffer back into the global pool */
350                 PMCLOG_INIT_BUFFER_DESCRIPTOR(lb);
351
352                 mtx_lock_spin(&pmc_bufferlist_mtx);
353                 TAILQ_INSERT_HEAD(&pmc_bufferlist, lb, plb_next);
354                 mtx_unlock_spin(&pmc_bufferlist_mtx);
355
356                 lb = NULL;
357         }
358
359         wakeup_one(po->po_kthread);
360         po->po_kthread = NULL;
361
362         mtx_unlock(&pmc_kthread_mtx);
363
364         /* return the current I/O buffer to the global pool */
365         if (lb) {
366                 PMCLOG_INIT_BUFFER_DESCRIPTOR(lb);
367
368                 mtx_lock_spin(&pmc_bufferlist_mtx);
369                 TAILQ_INSERT_HEAD(&pmc_bufferlist, lb, plb_next);
370                 mtx_unlock_spin(&pmc_bufferlist_mtx);
371         }
372
373         /*
374          * Exit this thread, signalling the waiter
375          */
376
377         crfree(ownercred);
378
379         kproc_exit(0);
380 }
381
382 /*
383  * Release and log entry and schedule an I/O if needed.
384  */
385
386 static void
387 pmclog_release(struct pmc_owner *po)
388 {
389         KASSERT(po->po_curbuf->plb_ptr >= po->po_curbuf->plb_base,
390             ("[pmclog,%d] buffer invariants po=%p ptr=%p base=%p", __LINE__,
391                 po, po->po_curbuf->plb_ptr, po->po_curbuf->plb_base));
392         KASSERT(po->po_curbuf->plb_ptr <= po->po_curbuf->plb_fence,
393             ("[pmclog,%d] buffer invariants po=%p ptr=%p fenc=%p", __LINE__,
394                 po, po->po_curbuf->plb_ptr, po->po_curbuf->plb_fence));
395
396         /* schedule an I/O if we've filled a buffer */
397         if (po->po_curbuf->plb_ptr >= po->po_curbuf->plb_fence)
398                 pmclog_schedule_io(po);
399
400         mtx_unlock_spin(&po->po_mtx);
401
402         PMCDBG(LOG,REL,1, "po=%p", po);
403 }
404
405
406 /*
407  * Attempt to reserve 'length' bytes of space in an owner's log
408  * buffer.  The function returns a pointer to 'length' bytes of space
409  * if there was enough space or returns NULL if no space was
410  * available.  Non-null returns do so with the po mutex locked.  The
411  * caller must invoke pmclog_release() on the pmc owner structure
412  * when done.
413  */
414
415 static uint32_t *
416 pmclog_reserve(struct pmc_owner *po, int length)
417 {
418         uintptr_t newptr, oldptr;
419         uint32_t *lh;
420         struct timespec ts;
421
422         PMCDBG(LOG,ALL,1, "po=%p len=%d", po, length);
423
424         KASSERT(length % sizeof(uint32_t) == 0,
425             ("[pmclog,%d] length not a multiple of word size", __LINE__));
426
427         mtx_lock_spin(&po->po_mtx);
428
429         /* No more data when shutdown in progress. */
430         if (po->po_flags & PMC_PO_SHUTDOWN) {
431                 mtx_unlock_spin(&po->po_mtx);
432                 return (NULL);
433         }
434
435         if (po->po_curbuf == NULL)
436                 if (pmclog_get_buffer(po) != 0) {
437                         mtx_unlock_spin(&po->po_mtx);
438                         return (NULL);
439                 }
440
441         KASSERT(po->po_curbuf != NULL,
442             ("[pmclog,%d] po=%p no current buffer", __LINE__, po));
443
444         KASSERT(po->po_curbuf->plb_ptr >= po->po_curbuf->plb_base &&
445             po->po_curbuf->plb_ptr <= po->po_curbuf->plb_fence,
446             ("[pmclog,%d] po=%p buffer invariants: ptr=%p base=%p fence=%p",
447                 __LINE__, po, po->po_curbuf->plb_ptr, po->po_curbuf->plb_base,
448                 po->po_curbuf->plb_fence));
449
450         oldptr = (uintptr_t) po->po_curbuf->plb_ptr;
451         newptr = oldptr + length;
452
453         KASSERT(oldptr != (uintptr_t) NULL,
454             ("[pmclog,%d] po=%p Null log buffer pointer", __LINE__, po));
455
456         /*
457          * If we have space in the current buffer, return a pointer to
458          * available space with the PO structure locked.
459          */
460         if (newptr <= (uintptr_t) po->po_curbuf->plb_fence) {
461                 po->po_curbuf->plb_ptr = (char *) newptr;
462                 goto done;
463         }
464
465         /*
466          * Otherwise, schedule the current buffer for output and get a
467          * fresh buffer.
468          */
469         pmclog_schedule_io(po);
470
471         if (pmclog_get_buffer(po) != 0) {
472                 mtx_unlock_spin(&po->po_mtx);
473                 return (NULL);
474         }
475
476         KASSERT(po->po_curbuf != NULL,
477             ("[pmclog,%d] po=%p no current buffer", __LINE__, po));
478
479         KASSERT(po->po_curbuf->plb_ptr != NULL,
480             ("[pmclog,%d] null return from pmc_get_log_buffer", __LINE__));
481
482         KASSERT(po->po_curbuf->plb_ptr == po->po_curbuf->plb_base &&
483             po->po_curbuf->plb_ptr <= po->po_curbuf->plb_fence,
484             ("[pmclog,%d] po=%p buffer invariants: ptr=%p base=%p fence=%p",
485                 __LINE__, po, po->po_curbuf->plb_ptr, po->po_curbuf->plb_base,
486                 po->po_curbuf->plb_fence));
487
488         oldptr = (uintptr_t) po->po_curbuf->plb_ptr;
489
490  done:
491         lh = (uint32_t *) oldptr;
492         lh++;                           /* skip header */
493         getnanotime(&ts);               /* fill in the timestamp */
494         *lh++ = ts.tv_sec & 0xFFFFFFFF;
495         *lh++ = ts.tv_nsec & 0xFFFFFFF;
496         return ((uint32_t *) oldptr);
497 }
498
499 /*
500  * Schedule an I/O.
501  *
502  * Transfer the current buffer to the helper kthread.
503  */
504
505 static void
506 pmclog_schedule_io(struct pmc_owner *po)
507 {
508         KASSERT(po->po_curbuf != NULL,
509             ("[pmclog,%d] schedule_io with null buffer po=%p", __LINE__, po));
510
511         KASSERT(po->po_curbuf->plb_ptr >= po->po_curbuf->plb_base,
512             ("[pmclog,%d] buffer invariants po=%p ptr=%p base=%p", __LINE__,
513                 po, po->po_curbuf->plb_ptr, po->po_curbuf->plb_base));
514         KASSERT(po->po_curbuf->plb_ptr <= po->po_curbuf->plb_fence,
515             ("[pmclog,%d] buffer invariants po=%p ptr=%p fenc=%p", __LINE__,
516                 po, po->po_curbuf->plb_ptr, po->po_curbuf->plb_fence));
517
518         PMCDBG(LOG,SIO, 1, "po=%p", po);
519
520         mtx_assert(&po->po_mtx, MA_OWNED);
521
522         /*
523          * Add the current buffer to the tail of the buffer list and
524          * wakeup the helper.
525          */
526         TAILQ_INSERT_TAIL(&po->po_logbuffers, po->po_curbuf, plb_next);
527         po->po_curbuf = NULL;
528         wakeup_one(po);
529 }
530
531 /*
532  * Stop the helper kthread.
533  */
534
535 static void
536 pmclog_stop_kthread(struct pmc_owner *po)
537 {
538         /*
539          * Close the file to force the thread out of fo_write,
540          * unset flag, wakeup the helper thread,
541          * wait for it to exit
542          */
543
544         if (po->po_file != NULL)
545                 fo_close(po->po_file, curthread);
546
547         mtx_lock(&pmc_kthread_mtx);
548         po->po_flags &= ~PMC_PO_OWNS_LOGFILE;
549         wakeup_one(po);
550         if (po->po_kthread)
551                 msleep(po->po_kthread, &pmc_kthread_mtx, PPAUSE, "pmckstp", 0);
552         mtx_unlock(&pmc_kthread_mtx);
553 }
554
555 /*
556  * Public functions
557  */
558
559 /*
560  * Configure a log file for pmc owner 'po'.
561  *
562  * Parameter 'logfd' is a file handle referencing an open file in the
563  * owner process.  This file needs to have been opened for writing.
564  */
565
566 int
567 pmclog_configure_log(struct pmc_mdep *md, struct pmc_owner *po, int logfd)
568 {
569         int error;
570         struct proc *p;
571
572         /*
573          * As long as it is possible to get a LOR between pmc_sx lock and
574          * proctree/allproc sx locks used for adding a new process, assure
575          * the former is not held here.
576          */
577         sx_assert(&pmc_sx, SA_UNLOCKED);
578         PMCDBG(LOG,CFG,1, "config po=%p logfd=%d", po, logfd);
579
580         p = po->po_owner;
581
582         /* return EBUSY if a log file was already present */
583         if (po->po_flags & PMC_PO_OWNS_LOGFILE)
584                 return (EBUSY);
585
586         KASSERT(po->po_kthread == NULL,
587             ("[pmclog,%d] po=%p kthread (%p) already present", __LINE__, po,
588                 po->po_kthread));
589         KASSERT(po->po_file == NULL,
590             ("[pmclog,%d] po=%p file (%p) already present", __LINE__, po,
591                 po->po_file));
592
593         /* get a reference to the file state */
594         error = fget_write(curthread, logfd, &po->po_file);
595         if (error)
596                 goto error;
597
598         /* mark process as owning a log file */
599         po->po_flags |= PMC_PO_OWNS_LOGFILE;
600         error = kproc_create(pmclog_loop, po, &po->po_kthread,
601             RFHIGHPID, 0, "hwpmc: proc(%d)", p->p_pid);
602         if (error)
603                 goto error;
604
605         /* mark process as using HWPMCs */
606         PROC_LOCK(p);
607         p->p_flag |= P_HWPMC;
608         PROC_UNLOCK(p);
609
610         /* create a log initialization entry */
611         PMCLOG_RESERVE_WITH_ERROR(po, INITIALIZE,
612             sizeof(struct pmclog_initialize));
613         PMCLOG_EMIT32(PMC_VERSION);
614         PMCLOG_EMIT32(md->pmd_cputype);
615         PMCLOG_DESPATCH(po);
616
617         return (0);
618
619  error:
620         /* shutdown the thread */
621         if (po->po_kthread)
622                 pmclog_stop_kthread(po);
623
624         KASSERT(po->po_kthread == NULL, ("[pmclog,%d] po=%p kthread not "
625             "stopped", __LINE__, po));
626
627         if (po->po_file)
628                 (void) fdrop(po->po_file, curthread);
629         po->po_file  = NULL;    /* clear file and error state */
630         po->po_error = 0;
631
632         return (error);
633 }
634
635
636 /*
637  * De-configure a log file.  This will throw away any buffers queued
638  * for this owner process.
639  */
640
641 int
642 pmclog_deconfigure_log(struct pmc_owner *po)
643 {
644         int error;
645         struct pmclog_buffer *lb;
646
647         PMCDBG(LOG,CFG,1, "de-config po=%p", po);
648
649         if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0)
650                 return (EINVAL);
651
652         KASSERT(po->po_sscount == 0,
653             ("[pmclog,%d] po=%p still owning SS PMCs", __LINE__, po));
654         KASSERT(po->po_file != NULL,
655             ("[pmclog,%d] po=%p no log file", __LINE__, po));
656
657         /* stop the kthread, this will reset the 'OWNS_LOGFILE' flag */
658         pmclog_stop_kthread(po);
659
660         KASSERT(po->po_kthread == NULL,
661             ("[pmclog,%d] po=%p kthread not stopped", __LINE__, po));
662
663         /* return all queued log buffers to the global pool */
664         while ((lb = TAILQ_FIRST(&po->po_logbuffers)) != NULL) {
665                 TAILQ_REMOVE(&po->po_logbuffers, lb, plb_next);
666                 PMCLOG_INIT_BUFFER_DESCRIPTOR(lb);
667                 mtx_lock_spin(&pmc_bufferlist_mtx);
668                 TAILQ_INSERT_HEAD(&pmc_bufferlist, lb, plb_next);
669                 mtx_unlock_spin(&pmc_bufferlist_mtx);
670         }
671
672         /* return the 'current' buffer to the global pool */
673         if ((lb = po->po_curbuf) != NULL) {
674                 PMCLOG_INIT_BUFFER_DESCRIPTOR(lb);
675                 mtx_lock_spin(&pmc_bufferlist_mtx);
676                 TAILQ_INSERT_HEAD(&pmc_bufferlist, lb, plb_next);
677                 mtx_unlock_spin(&pmc_bufferlist_mtx);
678         }
679
680         /* drop a reference to the fd */
681         error = fdrop(po->po_file, curthread);
682         po->po_file  = NULL;
683         po->po_error = 0;
684
685         return (error);
686 }
687
688 /*
689  * Flush a process' log buffer.
690  */
691
692 int
693 pmclog_flush(struct pmc_owner *po)
694 {
695         int error;
696         struct pmclog_buffer *lb;
697
698         PMCDBG(LOG,FLS,1, "po=%p", po);
699
700         /*
701          * If there is a pending error recorded by the logger thread,
702          * return that.
703          */
704         if (po->po_error)
705                 return (po->po_error);
706
707         error = 0;
708
709         /*
710          * Check that we do have an active log file.
711          */
712         mtx_lock(&pmc_kthread_mtx);
713         if ((po->po_flags & PMC_PO_OWNS_LOGFILE) == 0) {
714                 error = EINVAL;
715                 goto error;
716         }
717
718         /*
719          * Schedule the current buffer if any and not empty.
720          */
721         mtx_lock_spin(&po->po_mtx);
722         lb = po->po_curbuf;
723         if (lb && lb->plb_ptr != lb->plb_base) {
724                 pmclog_schedule_io(po);
725         } else
726                 error = ENOBUFS;
727         mtx_unlock_spin(&po->po_mtx);
728
729  error:
730         mtx_unlock(&pmc_kthread_mtx);
731
732         return (error);
733 }
734
735 int
736 pmclog_close(struct pmc_owner *po)
737 {
738
739         PMCDBG(LOG,CLO,1, "po=%p", po);
740
741         mtx_lock(&pmc_kthread_mtx);
742
743         /*
744          * Schedule the current buffer.
745          */
746         mtx_lock_spin(&po->po_mtx);
747         if (po->po_curbuf)
748                 pmclog_schedule_io(po);
749         else
750                 wakeup_one(po);
751         mtx_unlock_spin(&po->po_mtx);
752
753         /*
754          * Initiate shutdown: no new data queued,
755          * thread will close file on last block.
756          */
757         po->po_flags |= PMC_PO_SHUTDOWN;
758
759         mtx_unlock(&pmc_kthread_mtx);
760
761         return (0);
762 }
763
764 void
765 pmclog_process_callchain(struct pmc *pm, struct pmc_sample *ps)
766 {
767         int n, recordlen;
768         uint32_t flags;
769         struct pmc_owner *po;
770
771         PMCDBG(LOG,SAM,1,"pm=%p pid=%d n=%d", pm, ps->ps_pid,
772             ps->ps_nsamples);
773
774         recordlen = offsetof(struct pmclog_callchain, pl_pc) +
775             ps->ps_nsamples * sizeof(uintfptr_t);
776         po = pm->pm_owner;
777         flags = PMC_CALLCHAIN_TO_CPUFLAGS(ps->ps_cpu,ps->ps_flags);
778         PMCLOG_RESERVE(po, CALLCHAIN, recordlen);
779         PMCLOG_EMIT32(ps->ps_pid);
780         PMCLOG_EMIT32(pm->pm_id);
781         PMCLOG_EMIT32(flags);
782         for (n = 0; n < ps->ps_nsamples; n++)
783                 PMCLOG_EMITADDR(ps->ps_pc[n]);
784         PMCLOG_DESPATCH(po);
785 }
786
787 void
788 pmclog_process_closelog(struct pmc_owner *po)
789 {
790         PMCLOG_RESERVE(po,CLOSELOG,sizeof(struct pmclog_closelog));
791         PMCLOG_DESPATCH(po);
792 }
793
794 void
795 pmclog_process_dropnotify(struct pmc_owner *po)
796 {
797         PMCLOG_RESERVE(po,DROPNOTIFY,sizeof(struct pmclog_dropnotify));
798         PMCLOG_DESPATCH(po);
799 }
800
801 void
802 pmclog_process_map_in(struct pmc_owner *po, pid_t pid, uintfptr_t start,
803     const char *path)
804 {
805         int pathlen, recordlen;
806
807         KASSERT(path != NULL, ("[pmclog,%d] map-in, null path", __LINE__));
808
809         pathlen = strlen(path) + 1;     /* #bytes for path name */
810         recordlen = offsetof(struct pmclog_map_in, pl_pathname) +
811             pathlen;
812
813         PMCLOG_RESERVE(po, MAP_IN, recordlen);
814         PMCLOG_EMIT32(pid);
815         PMCLOG_EMITADDR(start);
816         PMCLOG_EMITSTRING(path,pathlen);
817         PMCLOG_DESPATCH(po);
818 }
819
820 void
821 pmclog_process_map_out(struct pmc_owner *po, pid_t pid, uintfptr_t start,
822     uintfptr_t end)
823 {
824         KASSERT(start <= end, ("[pmclog,%d] start > end", __LINE__));
825
826         PMCLOG_RESERVE(po, MAP_OUT, sizeof(struct pmclog_map_out));
827         PMCLOG_EMIT32(pid);
828         PMCLOG_EMITADDR(start);
829         PMCLOG_EMITADDR(end);
830         PMCLOG_DESPATCH(po);
831 }
832
833 void
834 pmclog_process_pmcallocate(struct pmc *pm)
835 {
836         struct pmc_owner *po;
837
838         po = pm->pm_owner;
839
840         PMCDBG(LOG,ALL,1, "pm=%p", pm);
841
842         PMCLOG_RESERVE(po, PMCALLOCATE, sizeof(struct pmclog_pmcallocate));
843         PMCLOG_EMIT32(pm->pm_id);
844         PMCLOG_EMIT32(pm->pm_event);
845         PMCLOG_EMIT32(pm->pm_flags);
846         PMCLOG_DESPATCH(po);
847 }
848
849 void
850 pmclog_process_pmcattach(struct pmc *pm, pid_t pid, char *path)
851 {
852         int pathlen, recordlen;
853         struct pmc_owner *po;
854
855         PMCDBG(LOG,ATT,1,"pm=%p pid=%d", pm, pid);
856
857         po = pm->pm_owner;
858
859         pathlen = strlen(path) + 1;     /* #bytes for the string */
860         recordlen = offsetof(struct pmclog_pmcattach, pl_pathname) + pathlen;
861
862         PMCLOG_RESERVE(po, PMCATTACH, recordlen);
863         PMCLOG_EMIT32(pm->pm_id);
864         PMCLOG_EMIT32(pid);
865         PMCLOG_EMITSTRING(path, pathlen);
866         PMCLOG_DESPATCH(po);
867 }
868
869 void
870 pmclog_process_pmcdetach(struct pmc *pm, pid_t pid)
871 {
872         struct pmc_owner *po;
873
874         PMCDBG(LOG,ATT,1,"!pm=%p pid=%d", pm, pid);
875
876         po = pm->pm_owner;
877
878         PMCLOG_RESERVE(po, PMCDETACH, sizeof(struct pmclog_pmcdetach));
879         PMCLOG_EMIT32(pm->pm_id);
880         PMCLOG_EMIT32(pid);
881         PMCLOG_DESPATCH(po);
882 }
883
884 /*
885  * Log a context switch event to the log file.
886  */
887
888 void
889 pmclog_process_proccsw(struct pmc *pm, struct pmc_process *pp, pmc_value_t v)
890 {
891         struct pmc_owner *po;
892
893         KASSERT(pm->pm_flags & PMC_F_LOG_PROCCSW,
894             ("[pmclog,%d] log-process-csw called gratuitously", __LINE__));
895
896         PMCDBG(LOG,SWO,1,"pm=%p pid=%d v=%jx", pm, pp->pp_proc->p_pid,
897             v);
898
899         po = pm->pm_owner;
900
901         PMCLOG_RESERVE(po, PROCCSW, sizeof(struct pmclog_proccsw));
902         PMCLOG_EMIT32(pm->pm_id);
903         PMCLOG_EMIT64(v);
904         PMCLOG_EMIT32(pp->pp_proc->p_pid);
905         PMCLOG_DESPATCH(po);
906 }
907
908 void
909 pmclog_process_procexec(struct pmc_owner *po, pmc_id_t pmid, pid_t pid,
910     uintfptr_t startaddr, char *path)
911 {
912         int pathlen, recordlen;
913
914         PMCDBG(LOG,EXC,1,"po=%p pid=%d path=\"%s\"", po, pid, path);
915
916         pathlen   = strlen(path) + 1;   /* #bytes for the path */
917         recordlen = offsetof(struct pmclog_procexec, pl_pathname) + pathlen;
918
919         PMCLOG_RESERVE(po, PROCEXEC, recordlen);
920         PMCLOG_EMIT32(pid);
921         PMCLOG_EMITADDR(startaddr);
922         PMCLOG_EMIT32(pmid);
923         PMCLOG_EMITSTRING(path,pathlen);
924         PMCLOG_DESPATCH(po);
925 }
926
927 /*
928  * Log a process exit event (and accumulated pmc value) to the log file.
929  */
930
931 void
932 pmclog_process_procexit(struct pmc *pm, struct pmc_process *pp)
933 {
934         int ri;
935         struct pmc_owner *po;
936
937         ri = PMC_TO_ROWINDEX(pm);
938         PMCDBG(LOG,EXT,1,"pm=%p pid=%d v=%jx", pm, pp->pp_proc->p_pid,
939             pp->pp_pmcs[ri].pp_pmcval);
940
941         po = pm->pm_owner;
942
943         PMCLOG_RESERVE(po, PROCEXIT, sizeof(struct pmclog_procexit));
944         PMCLOG_EMIT32(pm->pm_id);
945         PMCLOG_EMIT64(pp->pp_pmcs[ri].pp_pmcval);
946         PMCLOG_EMIT32(pp->pp_proc->p_pid);
947         PMCLOG_DESPATCH(po);
948 }
949
950 /*
951  * Log a fork event.
952  */
953
954 void
955 pmclog_process_procfork(struct pmc_owner *po, pid_t oldpid, pid_t newpid)
956 {
957         PMCLOG_RESERVE(po, PROCFORK, sizeof(struct pmclog_procfork));
958         PMCLOG_EMIT32(oldpid);
959         PMCLOG_EMIT32(newpid);
960         PMCLOG_DESPATCH(po);
961 }
962
963 /*
964  * Log a process exit event of the form suitable for system-wide PMCs.
965  */
966
967 void
968 pmclog_process_sysexit(struct pmc_owner *po, pid_t pid)
969 {
970         PMCLOG_RESERVE(po, SYSEXIT, sizeof(struct pmclog_sysexit));
971         PMCLOG_EMIT32(pid);
972         PMCLOG_DESPATCH(po);
973 }
974
975 /*
976  * Write a user log entry.
977  */
978
979 int
980 pmclog_process_userlog(struct pmc_owner *po, struct pmc_op_writelog *wl)
981 {
982         int error;
983
984         PMCDBG(LOG,WRI,1, "writelog po=%p ud=0x%x", po, wl->pm_userdata);
985
986         error = 0;
987
988         PMCLOG_RESERVE_WITH_ERROR(po, USERDATA,
989             sizeof(struct pmclog_userdata));
990         PMCLOG_EMIT32(wl->pm_userdata);
991         PMCLOG_DESPATCH(po);
992
993  error:
994         return (error);
995 }
996
997 /*
998  * Initialization.
999  *
1000  * Create a pool of log buffers and initialize mutexes.
1001  */
1002
1003 void
1004 pmclog_initialize()
1005 {
1006         int n;
1007         struct pmclog_buffer *plb;
1008
1009         if (pmclog_buffer_size <= 0) {
1010                 (void) printf("hwpmc: tunable logbuffersize=%d must be "
1011                     "greater than zero.\n", pmclog_buffer_size);
1012                 pmclog_buffer_size = PMC_LOG_BUFFER_SIZE;
1013         }
1014
1015         if (pmc_nlogbuffers <= 0) {
1016                 (void) printf("hwpmc: tunable nlogbuffers=%d must be greater "
1017                     "than zero.\n", pmc_nlogbuffers);
1018                 pmc_nlogbuffers = PMC_NLOGBUFFERS;
1019         }
1020
1021         /* create global pool of log buffers */
1022         for (n = 0; n < pmc_nlogbuffers; n++) {
1023                 plb = malloc(1024 * pmclog_buffer_size, M_PMC,
1024                     M_WAITOK|M_ZERO);
1025                 PMCLOG_INIT_BUFFER_DESCRIPTOR(plb);
1026                 TAILQ_INSERT_HEAD(&pmc_bufferlist, plb, plb_next);
1027         }
1028         mtx_init(&pmc_bufferlist_mtx, "pmc-buffer-list", "pmc-leaf",
1029             MTX_SPIN);
1030         mtx_init(&pmc_kthread_mtx, "pmc-kthread", "pmc-sleep", MTX_DEF);
1031 }
1032
1033 /*
1034  * Shutdown logging.
1035  *
1036  * Destroy mutexes and release memory back the to free pool.
1037  */
1038
1039 void
1040 pmclog_shutdown()
1041 {
1042         struct pmclog_buffer *plb;
1043
1044         mtx_destroy(&pmc_kthread_mtx);
1045         mtx_destroy(&pmc_bufferlist_mtx);
1046
1047         while ((plb = TAILQ_FIRST(&pmc_bufferlist)) != NULL) {
1048                 TAILQ_REMOVE(&pmc_bufferlist, plb, plb_next);
1049                 free(plb, M_PMC);
1050         }
1051 }