error: return usable error strings, not nothing.
[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
6 #include <ros/common.h>
7 #include <ros/mman.h>
8 #include <sys/types.h>
9 #include <smp.h>
10 #include <trap.h>
11 #include <kthread.h>
12 #include <env.h>
13 #include <process.h>
14 #include <mm.h>
15 #include <vfs.h>
16 #include <kmalloc.h>
17 #include <pmap.h>
18 #include <kref.h>
19 #include <atomic.h>
20 #include <umem.h>
21 #include <elf.h>
22 #include <ns.h>
23 #include <err.h>
24 #include <core_set.h>
25 #include <string.h>
26 #include "profiler.h"
27
28 #define PROFILER_MAX_PRG_PATH   256
29 #define PROFILER_BT_DEPTH 16
30
31 #define VBE_MAX_SIZE(t) ((8 * sizeof(t) + 6) / 7)
32
33 struct profiler_cpu_context {
34         struct block *block;
35     int cpu;
36         int tracing;
37         size_t dropped_data_size;
38 };
39
40 static int profiler_queue_limit = 64 * 1024 * 1024;
41 static size_t profiler_cpu_buffer_size = 65536;
42 static qlock_t profiler_mtx = QLOCK_INITIALIZER(profiler_mtx);
43 static struct kref profiler_kref;
44 static struct profiler_cpu_context *profiler_percpu_ctx;
45 static struct queue *profiler_queue;
46
47 static inline struct profiler_cpu_context *profiler_get_cpu_ctx(int cpu)
48 {
49         return profiler_percpu_ctx + cpu;
50 }
51
52 static inline char *vb_encode_uint64(char *data, uint64_t n)
53 {
54         /* Classical variable bytes encoding. Encodes 7 bits at a time, using bit
55          * number 7 in the byte, as indicator of end of sequence (when zero).
56          */
57         for (; n >= 0x80; n >>= 7)
58                 *data++ = (char) (n | 0x80);
59         *data++ = (char) n;
60
61         return data;
62 }
63
64 static struct block *profiler_buffer_write(struct profiler_cpu_context *cpu_buf,
65                                                                                    struct block *b)
66 {
67         if (b) {
68                 qibwrite(profiler_queue, b);
69
70                 if (qlen(profiler_queue) > profiler_queue_limit) {
71                         b = qget(profiler_queue);
72                         if (likely(b)) {
73                                 cpu_buf->dropped_data_size += BLEN(b);
74                                 freeb(b);
75                         }
76                 }
77         }
78
79         return iallocb(profiler_cpu_buffer_size);
80 }
81
82 static char *profiler_cpu_buffer_write_reserve(
83         struct profiler_cpu_context *cpu_buf, size_t size, struct block **pb)
84 {
85         struct block *b = cpu_buf->block;
86
87         if (unlikely((!b) || (b->lim - b->wp) < size)) {
88                 cpu_buf->block = b = profiler_buffer_write(cpu_buf, b);
89         if (unlikely(!b))
90                         return NULL;
91         }
92         *pb = b;
93
94         return (char *) b->wp;
95 }
96
97 static inline void profiler_cpu_buffer_write_commit(
98         struct profiler_cpu_context *cpu_buf, struct block *b, size_t size)
99 {
100         b->wp += size;
101 }
102
103 static inline size_t profiler_max_envelope_size(void)
104 {
105         return 2 * VBE_MAX_SIZE(uint64_t);
106 }
107
108 static void profiler_push_kernel_trace64(struct profiler_cpu_context *cpu_buf,
109                                                                                  const uintptr_t *trace, size_t count,
110                                                                                  uint64_t info)
111 {
112         size_t i, size = sizeof(struct proftype_kern_trace64) +
113                 count * sizeof(uint64_t);
114         struct block *b;
115         char *resptr = profiler_cpu_buffer_write_reserve(
116                 cpu_buf, size + profiler_max_envelope_size(), &b);
117         char *ptr = resptr;
118
119         if (likely(ptr)) {
120                 struct proftype_kern_trace64 *record;
121
122                 ptr = vb_encode_uint64(ptr, PROFTYPE_KERN_TRACE64);
123                 ptr = vb_encode_uint64(ptr, size);
124
125                 record = (struct proftype_kern_trace64 *) ptr;
126                 ptr += size;
127
128                 record->info = info;
129                 record->tstamp = nsec();
130                 record->cpu = cpu_buf->cpu;
131                 record->num_traces = count;
132                 for (i = 0; i < count; i++)
133                         record->trace[i] = (uint64_t) trace[i];
134
135                 profiler_cpu_buffer_write_commit(cpu_buf, b, ptr - resptr);
136         }
137 }
138
139 static void profiler_push_user_trace64(struct profiler_cpu_context *cpu_buf,
140                                                                            struct proc *p, const uintptr_t *trace,
141                                                                            size_t count, uint64_t info)
142 {
143         size_t i, size = sizeof(struct proftype_user_trace64) +
144                 count * sizeof(uint64_t);
145         struct block *b;
146         char *resptr = profiler_cpu_buffer_write_reserve(
147                 cpu_buf, size + profiler_max_envelope_size(), &b);
148         char *ptr = resptr;
149
150         if (likely(ptr)) {
151                 struct proftype_user_trace64 *record;
152
153                 ptr = vb_encode_uint64(ptr, PROFTYPE_USER_TRACE64);
154                 ptr = vb_encode_uint64(ptr, size);
155
156                 record = (struct proftype_user_trace64 *) ptr;
157                 ptr += size;
158
159                 record->info = info;
160                 record->tstamp = nsec();
161                 record->pid = p->pid;
162                 record->cpu = cpu_buf->cpu;
163                 record->num_traces = count;
164                 for (i = 0; i < count; i++)
165                         record->trace[i] = (uint64_t) trace[i];
166
167                 profiler_cpu_buffer_write_commit(cpu_buf, b, ptr - resptr);
168         }
169 }
170
171 static void profiler_push_pid_mmap(struct proc *p, uintptr_t addr, size_t msize,
172                                                                    size_t offset, const char *path)
173 {
174         size_t i, plen = strlen(path) + 1,
175                 size = sizeof(struct proftype_pid_mmap64) + plen;
176         char *resptr = kmalloc(size + profiler_max_envelope_size(), 0);
177
178         if (likely(resptr)) {
179                 char *ptr = resptr;
180                 struct proftype_pid_mmap64 *record;
181
182                 ptr = vb_encode_uint64(ptr, PROFTYPE_PID_MMAP64);
183                 ptr = vb_encode_uint64(ptr, size);
184
185                 record = (struct proftype_pid_mmap64 *) ptr;
186                 ptr += size;
187
188                 record->tstamp = nsec();
189                 record->pid = p->pid;
190                 record->addr = addr;
191                 record->size = msize;
192                 record->offset = offset;
193                 memcpy(record->path, path, plen);
194
195                 qiwrite(profiler_queue, resptr, (int) (ptr - resptr));
196
197                 kfree(resptr);
198         }
199 }
200
201 static void profiler_push_new_process(struct proc *p)
202 {
203         size_t i, plen = strlen(p->binary_path) + 1,
204                 size = sizeof(struct proftype_new_process) + plen;
205         char *resptr = kmalloc(size + profiler_max_envelope_size(), 0);
206
207         if (likely(resptr)) {
208                 char *ptr = resptr;
209                 struct proftype_new_process *record;
210
211                 ptr = vb_encode_uint64(ptr, PROFTYPE_NEW_PROCESS);
212                 ptr = vb_encode_uint64(ptr, size);
213
214                 record = (struct proftype_new_process *) ptr;
215                 ptr += size;
216
217                 record->tstamp = nsec();
218                 record->pid = p->pid;
219                 memcpy(record->path, p->binary_path, plen);
220
221                 qiwrite(profiler_queue, resptr, (int) (ptr - resptr));
222
223                 kfree(resptr);
224         }
225 }
226
227 static void profiler_emit_current_system_status(void)
228 {
229         void enum_proc(struct vm_region *vmr, void *opaque)
230         {
231                 struct proc *p = (struct proc *) opaque;
232
233                 profiler_notify_mmap(p, vmr->vm_base, vmr->vm_end - vmr->vm_base,
234                                                          vmr->vm_prot, vmr->vm_flags, vmr->vm_file,
235                                                          vmr->vm_foff);
236         }
237
238         ERRSTACK(1);
239         struct process_set pset;
240
241         proc_get_set(&pset);
242         if (waserror()) {
243                 proc_free_set(&pset);
244                 nexterror();
245         }
246
247         for (size_t i = 0; i < pset.num_processes; i++)
248                 enumerate_vmrs(pset.procs[i], enum_proc, pset.procs[i]);
249
250         poperror();
251         proc_free_set(&pset);
252 }
253
254 static void free_cpu_buffers(void)
255 {
256         kfree(profiler_percpu_ctx);
257         profiler_percpu_ctx = NULL;
258
259         if (profiler_queue) {
260                 qclose(profiler_queue);
261                 profiler_queue = NULL;
262         }
263 }
264
265 static void alloc_cpu_buffers(void)
266 {
267         ERRSTACK(1);
268         int i;
269
270         profiler_queue = qopen(profiler_queue_limit, 0, NULL, NULL);
271         if (!profiler_queue)
272                 error(ENOMEM, ERROR_FIXME);
273         if (waserror()) {
274                 free_cpu_buffers();
275                 nexterror();
276         }
277
278         qdropoverflow(profiler_queue, TRUE);
279         qnonblock(profiler_queue, TRUE);
280
281         profiler_percpu_ctx =
282                 kzmalloc(sizeof(*profiler_percpu_ctx) * num_cores, KMALLOC_WAIT);
283
284         for (i = 0; i < num_cores; i++) {
285                 struct profiler_cpu_context *b = &profiler_percpu_ctx[i];
286
287                 b->cpu = i;
288         }
289 }
290
291 static long profiler_get_checked_value(const char *value, long k, long minval,
292                                                                            long maxval)
293 {
294         long lvalue = strtol(value, NULL, 0) * k;
295
296         if (lvalue < minval)
297                 error(EFAIL, "Value should be greater than %ld", minval);
298         if (lvalue > maxval)
299                 error(EFAIL, "Value should be lower than %ld", maxval);
300
301         return lvalue;
302 }
303
304 int profiler_configure(struct cmdbuf *cb)
305 {
306         if (!strcmp(cb->f[0], "prof_qlimit")) {
307                 if (cb->nf < 2)
308                         error(EFAIL, "prof_qlimit KB");
309                 if (kref_refcnt(&profiler_kref) > 0)
310                         error(EFAIL, "Profiler already running");
311                 profiler_queue_limit = (int) profiler_get_checked_value(
312                         cb->f[1], 1024, 1024 * 1024, max_pmem / 32);
313         } else if (!strcmp(cb->f[0], "prof_cpubufsz")) {
314                 if (cb->nf < 2)
315                         error(EFAIL, "prof_cpubufsz KB");
316                 profiler_cpu_buffer_size = (size_t) profiler_get_checked_value(
317                         cb->f[1], 1024, 16 * 1024, 1024 * 1024);
318         } else {
319                 return 0;
320         }
321
322         return 1;
323 }
324
325 const char* const *profiler_configure_cmds(void)
326 {
327         static const char * const cmds[] = {
328                 "prof_qlimit", "prof_cpubufsz",
329                 NULL
330         };
331
332         return cmds;
333 }
334
335 static void profiler_release(struct kref *kref)
336 {
337         bool got_reference = FALSE;
338
339         assert(kref == &profiler_kref);
340         qlock(&profiler_mtx);
341         /* Make sure we did not race with profiler_setup(), that got the
342          * profiler_mtx lock just before us, and re-initialized the profiler
343          * for a new user.
344          * If we race here from another profiler_release() (user did a
345          * profiler_setup() immediately followed by a profiler_cleanup()) we are
346          * fine because free_cpu_buffers() can be called multiple times.
347          */
348         if (!kref_get_not_zero(kref, 1))
349                 free_cpu_buffers();
350         else
351                 got_reference = TRUE;
352         qunlock(&profiler_mtx);
353         /* We cannot call kref_put() within the profiler_kref lock, as such call
354          * might trigger anohter call to profiler_release().
355          */
356         if (got_reference)
357                 kref_put(kref);
358 }
359
360 void profiler_init(void)
361 {
362         assert(kref_refcnt(&profiler_kref) == 0);
363         kref_init(&profiler_kref, profiler_release, 0);
364 }
365
366 void profiler_setup(void)
367 {
368         ERRSTACK(1);
369
370         qlock(&profiler_mtx);
371         if (waserror()) {
372                 qunlock(&profiler_mtx);
373                 nexterror();
374         }
375         if (!profiler_queue)
376                 alloc_cpu_buffers();
377
378         /* Do this only when everything is initialized (as last init operation).
379          */
380         __kref_get(&profiler_kref, 1);
381
382         profiler_emit_current_system_status();
383
384         poperror();
385         qunlock(&profiler_mtx);
386 }
387
388 void profiler_cleanup(void)
389 {
390         kref_put(&profiler_kref);
391 }
392
393 static void profiler_cpu_flush(struct profiler_cpu_context *cpu_buf)
394 {
395         if (cpu_buf->block && profiler_queue) {
396                 qibwrite(profiler_queue, cpu_buf->block);
397
398                 cpu_buf->block = NULL;
399         }
400 }
401
402 static void profiler_core_trace_enable(void *opaque)
403 {
404         struct profiler_cpu_context *cpu_buf = profiler_get_cpu_ctx(core_id());
405
406         cpu_buf->tracing = (int) (opaque != NULL);
407         if (!cpu_buf->tracing)
408                 profiler_cpu_flush(cpu_buf);
409 }
410
411 void profiler_control_trace(int onoff)
412 {
413         struct core_set cset;
414
415         error_assert(EINVAL, profiler_percpu_ctx);
416
417         core_set_init(&cset);
418         core_set_fill_available(&cset);
419         smp_do_in_cores(&cset, profiler_core_trace_enable,
420                                         (void *) (uintptr_t) onoff);
421 }
422
423 static void profiler_core_flush(void *opaque)
424 {
425         struct profiler_cpu_context *cpu_buf = profiler_get_cpu_ctx(core_id());
426
427         profiler_cpu_flush(cpu_buf);
428 }
429
430 void profiler_trace_data_flush(void)
431 {
432         struct core_set cset;
433
434         error_assert(EINVAL, profiler_percpu_ctx);
435
436         core_set_init(&cset);
437         core_set_fill_available(&cset);
438         smp_do_in_cores(&cset, profiler_core_flush, NULL);
439 }
440
441 void profiler_add_trace(uintptr_t pc, uint64_t info)
442 {
443         if (is_user_raddr((void *) pc, 1))
444                 profiler_add_user_backtrace(pc, 0, info);
445         else
446                 profiler_add_kernel_backtrace(pc, 0, info);
447 }
448
449 void profiler_add_kernel_backtrace(uintptr_t pc, uintptr_t fp, uint64_t info)
450 {
451         if (kref_get_not_zero(&profiler_kref, 1)) {
452                 struct profiler_cpu_context *cpu_buf = profiler_get_cpu_ctx(core_id());
453
454                 if (profiler_percpu_ctx && cpu_buf->tracing) {
455                         uintptr_t trace[PROFILER_BT_DEPTH];
456                         size_t n = 1;
457
458                         trace[0] = pc;
459                         if (likely(fp))
460                                 n = backtrace_list(pc, fp, trace + 1,
461                                                                    PROFILER_BT_DEPTH - 1) + 1;
462
463                         profiler_push_kernel_trace64(cpu_buf, trace, n, info);
464                 }
465                 kref_put(&profiler_kref);
466         }
467 }
468
469 void profiler_add_user_backtrace(uintptr_t pc, uintptr_t fp, uint64_t info)
470 {
471         if (kref_get_not_zero(&profiler_kref, 1)) {
472                 struct proc *p = current;
473                 struct profiler_cpu_context *cpu_buf = profiler_get_cpu_ctx(core_id());
474
475                 if (p && profiler_percpu_ctx && cpu_buf->tracing) {
476                         uintptr_t trace[PROFILER_BT_DEPTH];
477                         size_t n = 1;
478
479                         trace[0] = pc;
480                         if (likely(fp))
481                                 n = backtrace_user_list(pc, fp, trace + 1,
482                                                                                 PROFILER_BT_DEPTH - 1) + 1;
483
484                         profiler_push_user_trace64(cpu_buf, p, trace, n, info);
485                 }
486                 kref_put(&profiler_kref);
487         }
488 }
489
490 void profiler_add_hw_sample(struct hw_trapframe *hw_tf, uint64_t info)
491 {
492         if (in_kernel(hw_tf))
493                 profiler_add_kernel_backtrace(get_hwtf_pc(hw_tf), get_hwtf_fp(hw_tf),
494                                                                           info);
495         else
496                 profiler_add_user_backtrace(get_hwtf_pc(hw_tf), get_hwtf_fp(hw_tf),
497                                                                         info);
498 }
499
500 int profiler_size(void)
501 {
502         return profiler_queue ? qlen(profiler_queue) : 0;
503 }
504
505 int profiler_read(void *va, int n)
506 {
507         return profiler_queue ? qread(profiler_queue, va, n) : 0;
508 }
509
510 void profiler_notify_mmap(struct proc *p, uintptr_t addr, size_t size, int prot,
511                                                   int flags, struct file *f, size_t offset)
512 {
513         if (kref_get_not_zero(&profiler_kref, 1)) {
514                 if (f && (prot & PROT_EXEC) && profiler_percpu_ctx) {
515                         char path_buf[PROFILER_MAX_PRG_PATH];
516                         char *path = file_abs_path(f, path_buf, sizeof(path_buf));
517
518                         if (likely(path))
519                                 profiler_push_pid_mmap(p, addr, size, offset, path);
520                 }
521                 kref_put(&profiler_kref);
522         }
523 }
524
525 void profiler_notify_new_process(struct proc *p)
526 {
527         if (kref_get_not_zero(&profiler_kref, 1)) {
528                 if (profiler_percpu_ctx && p->binary_path)
529                         profiler_push_new_process(p);
530                 kref_put(&profiler_kref);
531         }
532 }