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