perf: Remove the kprof.pdata staging ground
[akaros.git] / kern / src / profiler.c
1 /* Copyright (c) 2015 Google Inc
2  * Davide Libenzi <dlibenzi@google.com>
3  * See LICENSE for details.
4  *
5  * This controls the emitting, collecting, and exporting of samples for perf
6  * events.  Examples of events are PMU counter overflows, mmaps, and process
7  * creation.
8  *
9  * Events are collected in a central qio queue.  High-frequency events (e.g.
10  * profiler_add_hw_sample()) are collected in per-core buffers, which are
11  * flushed to the central queue when they fill up or on command.
12  * Lower-frequency events (e.g. profiler_notify_mmap()) just go straight to the
13  * central queue.
14  *
15  * Currently there is one global profiler.  Kprof is careful to only have one
16  * open profiler at a time.  We assert that this is true.  TODO: stop using the
17  * global profiler!
18  *
19  * A few other notes:
20  * - profiler_control_trace() controls the per-core trace collection.  When it
21  *   is disabled, it also flushes the per-core blocks to the central queue.
22  * - The collection of mmap and comm samples is independent of trace collection.
23  *   Those will occur whenever the profiler is open (refcnt check, for now). */
24
25 #include <ros/common.h>
26 #include <ros/mman.h>
27 #include <sys/types.h>
28 #include <smp.h>
29 #include <trap.h>
30 #include <kthread.h>
31 #include <env.h>
32 #include <process.h>
33 #include <mm.h>
34 #include <vfs.h>
35 #include <kmalloc.h>
36 #include <pmap.h>
37 #include <kref.h>
38 #include <atomic.h>
39 #include <umem.h>
40 #include <elf.h>
41 #include <ns.h>
42 #include <err.h>
43 #include <core_set.h>
44 #include <string.h>
45 #include "profiler.h"
46
47 #define PROFILER_MAX_PRG_PATH   256
48 #define PROFILER_BT_DEPTH 16
49
50 #define VBE_MAX_SIZE(t) ((8 * sizeof(t) + 6) / 7)
51
52 /* Do not rely on the contents of the PCPU ctx with IRQs enabled. */
53 struct profiler_cpu_context {
54         struct block *block;
55         int cpu;
56         int tracing;
57         size_t dropped_data_cnt;
58 };
59
60 static int profiler_queue_limit = 64 * 1024 * 1024;
61 static size_t profiler_cpu_buffer_size = 65536;
62 static qlock_t profiler_mtx = QLOCK_INITIALIZER(profiler_mtx);
63 static struct kref profiler_kref;
64 static struct profiler_cpu_context *profiler_percpu_ctx;
65 static struct queue *profiler_queue;
66
67 static inline struct profiler_cpu_context *profiler_get_cpu_ctx(int cpu)
68 {
69         return profiler_percpu_ctx + cpu;
70 }
71
72 static inline char *vb_encode_uint64(char *data, uint64_t n)
73 {
74         /* Classical variable bytes encoding. Encodes 7 bits at a time, using bit
75          * number 7 in the byte, as indicator of end of sequence (when zero).
76          */
77         for (; n >= 0x80; n >>= 7)
78                 *data++ = (char) (n | 0x80);
79         *data++ = (char) n;
80
81         return data;
82 }
83
84 static struct block *profiler_buffer_write(struct profiler_cpu_context *cpu_buf,
85                                            struct block *b)
86 {
87         /* qpass will drop b if the queue is over its limit.  we're willing to lose
88          * traces, but we won't lose 'control' events, such as MMAP and PID. */
89         if (b) {
90                 if (qpass(profiler_queue, b) < 0)
91                         cpu_buf->dropped_data_cnt++;
92         }
93         return block_alloc(profiler_cpu_buffer_size, MEM_ATOMIC);
94 }
95
96 /* Helper, paired with profiler_cpu_buffer_write_commit.  Ensures there is
97  * enough room in the pcpu block for our write.  May alloc a new one.
98  *
99  * IRQs must be disabled before calling, until after write_commit. */
100 static char *profiler_cpu_buffer_write_reserve(
101         struct profiler_cpu_context *cpu_buf, size_t size, struct block **pb)
102 {
103         struct block *b = cpu_buf->block;
104
105         if (unlikely((!b) || (b->lim - b->wp) < size)) {
106                 cpu_buf->block = b = profiler_buffer_write(cpu_buf, b);
107                 if (unlikely(!b))
108                         return NULL;
109         }
110         *pb = b;
111
112         return (char *) b->wp;
113 }
114
115 /* Helper, paired with write_reserve.  Finalizes the writing into the block's
116  * main body of @size bytes.  IRQs must be disabled until after this is called.
117  */
118 static inline void profiler_cpu_buffer_write_commit(
119         struct profiler_cpu_context *cpu_buf, struct block *b, size_t size)
120 {
121         b->wp += size;
122 }
123
124 static inline size_t profiler_max_envelope_size(void)
125 {
126         return 2 * VBE_MAX_SIZE(uint64_t);
127 }
128
129 static void profiler_push_kernel_trace64(struct profiler_cpu_context *cpu_buf,
130                                          const uintptr_t *trace, size_t count,
131                                          uint64_t info)
132 {
133         size_t size = sizeof(struct proftype_kern_trace64) +
134                 count * sizeof(uint64_t);
135         struct block *b;
136         void *resptr, *ptr;
137
138         assert(!irq_is_enabled());
139         resptr = profiler_cpu_buffer_write_reserve(
140             cpu_buf, size + profiler_max_envelope_size(), &b);
141         ptr = resptr;
142
143         if (likely(ptr)) {
144                 struct proftype_kern_trace64 *record;
145
146                 ptr = vb_encode_uint64(ptr, PROFTYPE_KERN_TRACE64);
147                 ptr = vb_encode_uint64(ptr, size);
148
149                 record = (struct proftype_kern_trace64 *) ptr;
150                 ptr += size;
151
152                 record->info = info;
153                 record->tstamp = nsec();
154                 record->cpu = cpu_buf->cpu;
155                 record->num_traces = count;
156                 for (size_t i = 0; i < count; i++)
157                         record->trace[i] = (uint64_t) trace[i];
158
159                 profiler_cpu_buffer_write_commit(cpu_buf, b, ptr - resptr);
160         }
161 }
162
163 static void profiler_push_user_trace64(struct profiler_cpu_context *cpu_buf,
164                                        struct proc *p, const uintptr_t *trace,
165                                        size_t count, uint64_t info)
166 {
167         size_t size = sizeof(struct proftype_user_trace64) +
168                 count * sizeof(uint64_t);
169         struct block *b;
170         void *resptr, *ptr;
171
172         assert(!irq_is_enabled());
173         resptr = profiler_cpu_buffer_write_reserve(
174             cpu_buf, size + profiler_max_envelope_size(), &b);
175         ptr = resptr;
176
177         if (likely(ptr)) {
178                 struct proftype_user_trace64 *record;
179
180                 ptr = vb_encode_uint64(ptr, PROFTYPE_USER_TRACE64);
181                 ptr = vb_encode_uint64(ptr, size);
182
183                 record = (struct proftype_user_trace64 *) ptr;
184                 ptr += size;
185
186                 record->info = info;
187                 record->tstamp = nsec();
188                 record->pid = p->pid;
189                 record->cpu = cpu_buf->cpu;
190                 record->num_traces = count;
191                 for (size_t i = 0; i < count; i++)
192                         record->trace[i] = (uint64_t) trace[i];
193
194                 profiler_cpu_buffer_write_commit(cpu_buf, b, ptr - resptr);
195         }
196 }
197
198 static void profiler_push_pid_mmap(struct proc *p, uintptr_t addr, size_t msize,
199                                    size_t offset, const char *path)
200 {
201         size_t plen = strlen(path) + 1;
202         size_t size = sizeof(struct proftype_pid_mmap64) + plen;
203         void *resptr = kmalloc(size + profiler_max_envelope_size(), 0);
204
205         if (likely(resptr)) {
206                 void *ptr = resptr;
207                 struct proftype_pid_mmap64 *record;
208
209                 ptr = vb_encode_uint64(ptr, PROFTYPE_PID_MMAP64);
210                 ptr = vb_encode_uint64(ptr, size);
211
212                 record = (struct proftype_pid_mmap64 *) ptr;
213                 ptr += size;
214
215                 record->tstamp = nsec();
216                 record->pid = p->pid;
217                 record->addr = addr;
218                 record->size = msize;
219                 record->offset = offset;
220                 memcpy(record->path, path, plen);
221
222                 qiwrite(profiler_queue, resptr, (int) (ptr - resptr));
223
224                 kfree(resptr);
225         }
226 }
227
228 static void profiler_push_new_process(struct proc *p)
229 {
230         size_t plen = strlen(p->binary_path) + 1;
231         size_t size = sizeof(struct proftype_new_process) + plen;
232         void *resptr = kmalloc(size + profiler_max_envelope_size(), 0);
233
234         if (likely(resptr)) {
235                 void *ptr = resptr;
236                 struct proftype_new_process *record;
237
238                 ptr = vb_encode_uint64(ptr, PROFTYPE_NEW_PROCESS);
239                 ptr = vb_encode_uint64(ptr, size);
240
241                 record = (struct proftype_new_process *) ptr;
242                 ptr += size;
243
244                 record->tstamp = nsec();
245                 record->pid = p->pid;
246                 memcpy(record->path, p->binary_path, plen);
247
248                 qiwrite(profiler_queue, resptr, (int) (ptr - resptr));
249
250                 kfree(resptr);
251         }
252 }
253
254 static void profiler_emit_current_system_status(void)
255 {
256         void enum_proc(struct vm_region *vmr, void *opaque)
257         {
258                 struct proc *p = (struct proc *) opaque;
259
260                 profiler_notify_mmap(p, vmr->vm_base, vmr->vm_end - vmr->vm_base,
261                                      vmr->vm_prot, vmr->vm_flags, vmr->vm_file,
262                                      vmr->vm_foff);
263         }
264
265         ERRSTACK(1);
266         struct process_set pset;
267
268         proc_get_set(&pset);
269         if (waserror()) {
270                 proc_free_set(&pset);
271                 nexterror();
272         }
273
274         for (size_t i = 0; i < pset.num_processes; i++) {
275                 profiler_notify_new_process(pset.procs[i]);
276                 enumerate_vmrs(pset.procs[i], enum_proc, pset.procs[i]);
277         }
278
279         poperror();
280         proc_free_set(&pset);
281 }
282
283 static void free_cpu_buffers(void)
284 {
285         kfree(profiler_percpu_ctx);
286         profiler_percpu_ctx = NULL;
287
288         if (profiler_queue) {
289                 qfree(profiler_queue);
290                 profiler_queue = NULL;
291         }
292 }
293
294 static void alloc_cpu_buffers(void)
295 {
296         ERRSTACK(1);
297
298         /* It is very important that we enqueue and dequeue entire records at once.
299          * If we leave partial records, the entire stream will be corrupt.  Our
300          * reader does its best to make sure it has room for complete records
301          * (checks qlen()).
302          *
303          * If we ever get corrupt streams, try making this a Qmsg.  Though it
304          * doesn't help every situation - we have issues with writes greater than
305          * Maxatomic regardless. */
306         profiler_queue = qopen(profiler_queue_limit, 0, NULL, NULL);
307         if (!profiler_queue)
308                 error(ENOMEM, ERROR_FIXME);
309         if (waserror()) {
310                 free_cpu_buffers();
311                 nexterror();
312         }
313
314         profiler_percpu_ctx =
315             kzmalloc(sizeof(*profiler_percpu_ctx) * num_cores, MEM_WAIT);
316
317         for (int i = 0; i < num_cores; i++) {
318                 struct profiler_cpu_context *b = &profiler_percpu_ctx[i];
319
320                 b->cpu = i;
321         }
322 }
323
324 static long profiler_get_checked_value(const char *value, long k, long minval,
325                                        long maxval)
326 {
327         long lvalue = strtol(value, NULL, 0) * k;
328
329         if (lvalue < minval)
330                 error(EFAIL, "Value should be greater than %ld", minval);
331         if (lvalue > maxval)
332                 error(EFAIL, "Value should be lower than %ld", maxval);
333
334         return lvalue;
335 }
336
337 int profiler_configure(struct cmdbuf *cb)
338 {
339         if (!strcmp(cb->f[0], "prof_qlimit")) {
340                 if (cb->nf < 2)
341                         error(EFAIL, "prof_qlimit KB");
342                 if (kref_refcnt(&profiler_kref) > 0)
343                         error(EFAIL, "Profiler already running");
344                 profiler_queue_limit = (int) profiler_get_checked_value(
345                         cb->f[1], 1024, 1024 * 1024, max_pmem / 32);
346                 return 1;
347         }
348         if (!strcmp(cb->f[0], "prof_cpubufsz")) {
349                 if (cb->nf < 2)
350                         error(EFAIL, "prof_cpubufsz KB");
351                 profiler_cpu_buffer_size = (size_t) profiler_get_checked_value(
352                         cb->f[1], 1024, 16 * 1024, 1024 * 1024);
353                 return 1;
354         }
355
356         return 0;
357 }
358
359 void profiler_append_configure_usage(char *msgbuf, size_t buflen)
360 {
361         const char * const cmds[] = {
362                 "prof_qlimit",
363                 "prof_cpubufsz",
364         };
365
366         for (int i = 0; i < ARRAY_SIZE(cmds); i++) {
367                 strlcat(msgbuf, "|", buflen);
368                 strlcat(msgbuf, cmds[i], buflen);
369         }
370 }
371
372 static void profiler_release(struct kref *kref)
373 {
374         bool got_reference = FALSE;
375
376         assert(kref == &profiler_kref);
377         qlock(&profiler_mtx);
378         /* Make sure we did not race with profiler_setup(), that got the
379          * profiler_mtx lock just before us, and re-initialized the profiler
380          * for a new user.
381          * If we race here from another profiler_release() (user did a
382          * profiler_setup() immediately followed by a profiler_cleanup()) we are
383          * fine because free_cpu_buffers() can be called multiple times.
384          */
385         if (!kref_get_not_zero(kref, 1))
386                 free_cpu_buffers();
387         else
388                 got_reference = TRUE;
389         qunlock(&profiler_mtx);
390         /* We cannot call kref_put() within the profiler_kref lock, as such call
391          * might trigger anohter call to profiler_release().
392          */
393         if (got_reference)
394                 kref_put(kref);
395 }
396
397 void profiler_init(void)
398 {
399         assert(kref_refcnt(&profiler_kref) == 0);
400         kref_init(&profiler_kref, profiler_release, 0);
401 }
402
403 void profiler_setup(void)
404 {
405         ERRSTACK(1);
406
407         qlock(&profiler_mtx);
408         if (waserror()) {
409                 qunlock(&profiler_mtx);
410                 nexterror();
411         }
412         assert(!profiler_queue);
413         alloc_cpu_buffers();
414
415         /* Do this only when everything is initialized (as last init operation).
416          */
417         __kref_get(&profiler_kref, 1);
418
419         profiler_emit_current_system_status();
420
421         poperror();
422         qunlock(&profiler_mtx);
423 }
424
425 void profiler_cleanup(void)
426 {
427         kref_put(&profiler_kref);
428 }
429
430 static void profiler_cpu_flush(struct profiler_cpu_context *cpu_buf)
431 {
432         int8_t irq_state = 0;
433
434         disable_irqsave(&irq_state);
435         if (cpu_buf->block && profiler_queue) {
436                 qibwrite(profiler_queue, cpu_buf->block);
437
438                 cpu_buf->block = NULL;
439         }
440         enable_irqsave(&irq_state);
441 }
442
443 static void profiler_core_trace_enable(void *opaque)
444 {
445         struct profiler_cpu_context *cpu_buf = profiler_get_cpu_ctx(core_id());
446
447         cpu_buf->tracing = (int) (opaque != NULL);
448         if (!cpu_buf->tracing)
449                 profiler_cpu_flush(cpu_buf);
450 }
451
452 static void profiler_control_trace(int onoff)
453 {
454         struct core_set cset;
455
456         error_assert(EINVAL, profiler_percpu_ctx);
457
458         core_set_init(&cset);
459         core_set_fill_available(&cset);
460         smp_do_in_cores(&cset, profiler_core_trace_enable,
461                         (void *) (uintptr_t) onoff);
462 }
463
464 void profiler_start(void)
465 {
466         assert(profiler_queue);
467         profiler_control_trace(1);
468         qreopen(profiler_queue);
469 }
470
471 void profiler_stop(void)
472 {
473         assert(profiler_queue);
474         profiler_control_trace(0);
475         qhangup(profiler_queue, 0);
476 }
477
478 static void profiler_core_flush(void *opaque)
479 {
480         struct profiler_cpu_context *cpu_buf = profiler_get_cpu_ctx(core_id());
481
482         profiler_cpu_flush(cpu_buf);
483 }
484
485 void profiler_trace_data_flush(void)
486 {
487         struct core_set cset;
488
489         error_assert(EINVAL, profiler_percpu_ctx);
490
491         core_set_init(&cset);
492         core_set_fill_available(&cset);
493         smp_do_in_cores(&cset, profiler_core_flush, NULL);
494 }
495
496 void profiler_add_trace(uintptr_t pc, uint64_t info)
497 {
498         if (is_user_raddr((void *) pc, 1))
499                 profiler_add_user_backtrace(pc, 0, info);
500         else
501                 profiler_add_kernel_backtrace(pc, 0, info);
502 }
503
504 void profiler_add_kernel_backtrace(uintptr_t pc, uintptr_t fp, uint64_t info)
505 {
506         if (kref_get_not_zero(&profiler_kref, 1)) {
507                 struct profiler_cpu_context *cpu_buf = profiler_get_cpu_ctx(core_id());
508
509                 if (profiler_percpu_ctx && cpu_buf->tracing) {
510                         uintptr_t trace[PROFILER_BT_DEPTH];
511                         size_t n = 1;
512
513                         trace[0] = pc;
514                         if (likely(fp))
515                                 n = backtrace_list(pc, fp, trace + 1,
516                                                    PROFILER_BT_DEPTH - 1) + 1;
517
518                         profiler_push_kernel_trace64(cpu_buf, trace, n, info);
519                 }
520                 kref_put(&profiler_kref);
521         }
522 }
523
524 void profiler_add_user_backtrace(uintptr_t pc, uintptr_t fp, uint64_t info)
525 {
526         if (kref_get_not_zero(&profiler_kref, 1)) {
527                 struct proc *p = current;
528                 struct profiler_cpu_context *cpu_buf = profiler_get_cpu_ctx(core_id());
529
530                 if (p && profiler_percpu_ctx && cpu_buf->tracing) {
531                         uintptr_t trace[PROFILER_BT_DEPTH];
532                         size_t n = 1;
533
534                         trace[0] = pc;
535                         if (likely(fp))
536                                 n = backtrace_user_list(pc, fp, trace + 1,
537                                                         PROFILER_BT_DEPTH - 1) + 1;
538
539                         profiler_push_user_trace64(cpu_buf, p, trace, n, info);
540                 }
541                 kref_put(&profiler_kref);
542         }
543 }
544
545 void profiler_add_hw_sample(struct hw_trapframe *hw_tf, uint64_t info)
546 {
547         if (in_kernel(hw_tf))
548                 profiler_add_kernel_backtrace(get_hwtf_pc(hw_tf), get_hwtf_fp(hw_tf),
549                                               info);
550         else
551                 profiler_add_user_backtrace(get_hwtf_pc(hw_tf), get_hwtf_fp(hw_tf),
552                                             info);
553 }
554
555 int profiler_size(void)
556 {
557         return profiler_queue ? qlen(profiler_queue) : 0;
558 }
559
560 int profiler_read(void *va, int n)
561 {
562         return profiler_queue ? qread(profiler_queue, va, n) : 0;
563 }
564
565 void profiler_notify_mmap(struct proc *p, uintptr_t addr, size_t size, int prot,
566                           int flags, struct file *f, size_t offset)
567 {
568         if (kref_get_not_zero(&profiler_kref, 1)) {
569                 if (f && (prot & PROT_EXEC) && profiler_percpu_ctx) {
570                         char path_buf[PROFILER_MAX_PRG_PATH];
571                         char *path = file_abs_path(f, path_buf, sizeof(path_buf));
572
573                         if (likely(path))
574                                 profiler_push_pid_mmap(p, addr, size, offset, path);
575                 }
576                 kref_put(&profiler_kref);
577         }
578 }
579
580 void profiler_notify_new_process(struct proc *p)
581 {
582         if (kref_get_not_zero(&profiler_kref, 1)) {
583                 if (profiler_percpu_ctx && p->binary_path)
584                         profiler_push_new_process(p);
585                 kref_put(&profiler_kref);
586         }
587 }