Debian Codegraph @

src/libsysprof/sysprof-perf-event-stream.c

raw
1 /* sysprof-perf-event-stream.c
2 *
3 * Copyright 2023 Christian Hergert <[email protected]>
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 *
18 * SPDX-License-Identifier: GPL-3.0-or-later
19 */
20
21 /* Sysprof -- Sampling, systemwide CPU profiler
22 * Copyright 2004, Red Hat, Inc.
23 * Copyright 2004, 2005, Soeren Sandmann
24 *
25 * This program is free software; you can redistribute it and/or modify
26 * it under the terms of the GNU General Public License as published by
27 * the Free Software Foundation; either version 2 of the License, or
28 * (at your option) any later version.
29 *
30 * This program is distributed in the hope that it will be useful,
31 * but WITHOUT ANY WARRANTY; without even the implied warranty of
32 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
33 * GNU General Public License for more details.
34 *
35 * You should have received a copy of the GNU General Public License
36 * along with this program; if not, write to the Free Software
37 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
38 */
39
40 #include "config.h"
41
42 #include <errno.h>
43 #include <linux/perf_event.h>
44 #ifdef HAVE_STDATOMIC_H
45 # include <stdatomic.h>
46 #endif
47 #include <string.h>
48 #include <sys/ioctl.h>
49 #include <sys/mman.h>
50 #include <sys/syscall.h>
51 #include <unistd.h>
52
53 #include <glib/gstdio.h>
54 #include <gio/gio.h>
55 #include <gio/gunixfdlist.h>
56
57 #include "sysprof-perf-event-stream-private.h"
58
59 /*
60 * Number of pages to map for the ring buffer. We map one additional buffer
61 * at the beginning for header information to communicate with perf.
62 */
63 #define N_PAGES 32
64
65 struct _SysprofPerfEventStream
66 {
67 GObject parent_instance;
68
69 GDBusConnection *connection;
70
71 GSource *source;
72
73 struct perf_event_attr attr;
74
75 int self_pid;
76 int cpu;
77 int group_fd;
78 gulong flags;
79
80 SysprofPerfEventCallback callback;
81 gpointer callback_data;
82 GDestroyNotify callback_data_destroy;
83
84 int perf_fd;
85
86 struct perf_event_mmap_page *map;
87 guint8 *map_data;
88 guint64 tail;
89 gsize map_size;
90
91 guint active : 1;
92 };
93
94 typedef struct _SysprofPerfEventSource
95 {
96 GSource source;
97 SysprofPerfEventStream *stream;
98 gint64 next_ready_time;
99 int timeout_msec;
100 } SysprofPerfEventSource;
101
102 enum {
103 PROP_0,
104 PROP_ACTIVE,
105 N_PROPS
106 };
107
108 G_DEFINE_FINAL_TYPE (SysprofPerfEventStream, sysprof_perf_event_stream, G_TYPE_OBJECT)
109
110 static GParamSpec *properties [N_PROPS];
111
112 static int
113 _perf_event_open (const struct perf_event_attr *attr,
114 pid_t pid,
115 int cpu,
116 int group_fd,
117 unsigned long flags)
118 {
119 return syscall (SYS_perf_event_open, attr, pid, cpu, group_fd, flags);
120 }
121
122 GVariant *
123 _sysprof_perf_event_attr_to_variant (const struct perf_event_attr *attr)
124 {
125 return g_variant_take_ref (
126 g_variant_new_parsed ("["
127 "{'comm', <%b>},"
128 #ifdef HAVE_PERF_CLOCKID
129 "{'clockid', <%i>},"
130 "{'use_clockid', <%b>},"
131 #endif
132 "{'config', <%t>},"
133 "{'disabled', <%b>},"
134 "{'exclude_idle', <%b>},"
135 "{'mmap', <%b>},"
136 "{'mmap2', <%b>},"
137 "{'build_id', <%b>},"
138 "{'wakeup_events', <%u>},"
139 "{'sample_id_all', <%b>},"
140 "{'sample_period', <%t>},"
141 "{'sample_type', <%t>},"
142 "{'task', <%b>},"
143 "{'sample_stack_user', <%u>},"
144 "{'sample_regs_user', <%t>},"
145 "{'type', <%u>}"
146 "]",
147 (gboolean)!!attr->comm,
148 #ifdef HAVE_PERF_CLOCKID
149 (gint32)attr->clockid,
150 (gboolean)!!attr->use_clockid,
151 #endif
152 (guint64)attr->config,
153 (gboolean)!!attr->disabled,
154 (gboolean)!!attr->exclude_idle,
155 (gboolean)!!attr->mmap,
156 (gboolean)!!attr->mmap2,
157 (gboolean)!!attr->build_id,
158 (guint32)attr->wakeup_events,
159 (gboolean)!!attr->sample_id_all,
160 (guint64)attr->sample_period,
161 (guint64)attr->sample_type,
162 (gboolean)!!attr->task,
163 (guint32)attr->sample_stack_user,
164 (guint64)attr->sample_regs_user,
165 (guint32)attr->type));
166 }
167
168 static void
169 sysprof_perf_event_stream_flush (SysprofPerfEventStream *self)
170 {
171 SysprofPerfEventSource *source = (SysprofPerfEventSource *)self->source;
172 guint64 n_bytes = N_PAGES * sysprof_getpagesize ();
173 guint64 mask = n_bytes - 1;
174 guint64 head;
175 guint64 tail;
176 gboolean lost_records = FALSE;
177 guint us = 0;
178 guint them = 0;
179
180 g_assert (SYSPROF_IS_PERF_EVENT_STREAM (self));
181
182 tail = self->tail;
183 head = self->map->data_head;
184
185 #ifdef HAVE_STDATOMIC_H
186 atomic_thread_fence (memory_order_acquire);
187 #elif G_GNUC_CHECK_VERSION(3, 0)
188 __sync_synchronize ();
189 #endif
190
191 if (head < tail)
192 tail = head;
193
194 while ((head - tail) >= sizeof (struct perf_event_header))
195 {
196 g_autofree guint8 *free_me = NULL;
197 const SysprofPerfEvent *event;
198 struct perf_event_header *header;
199 guint8 buffer[4096];
200 gboolean is_self = FALSE;
201
202 /* Note that:
203 *
204 * - perf events are a multiple of 64 bits
205 * - the perf event header is 64 bits
206 * - the data area is a multiple of 64 bits
207 *
208 * which means there will always be space for one header, which means we
209 * can safely dereference the size field.
210 */
211 header = (struct perf_event_header *)(gpointer)(self->map_data + (tail & mask));
212
213 if (header->size > head - tail)
214 {
215 /* The kernel did not generate a complete event.
216 * I don't think that can happen, but we may as well
217 * be paranoid.
218 */
219 break;
220 }
221
222 if (self->map_data + (tail & mask) + header->size > self->map_data + n_bytes)
223 {
224 gint n_before;
225 gint n_after;
226 guint8 *b;
227
228 if (header->size > sizeof buffer)
229 free_me = b = g_malloc (header->size);
230 else
231 b = buffer;
232
233 n_after = (tail & mask) + header->size - n_bytes;
234 n_before = header->size - n_after;
235
236 memcpy (b, self->map_data + (tail & mask), n_before);
237 memcpy (b + n_before, self->map_data, n_after);
238
239 header = (struct perf_event_header *)(gpointer)b;
240 }
241
242 event = (SysprofPerfEvent *)header;
243
244 switch (event->header.type)
245 {
246 default:
247 case PERF_RECORD_COMM:
248 case PERF_RECORD_EXIT:
249 case PERF_RECORD_FORK:
250 case PERF_RECORD_MMAP:
251 case PERF_RECORD_MMAP2:
252 break;
253
254 case PERF_RECORD_SAMPLE:
255 is_self = event->callchain.pid == self->self_pid;
256 break;
257
258 case PERF_RECORD_READ:
259 case PERF_RECORD_THROTTLE:
260 case PERF_RECORD_UNTHROTTLE:
261 goto skip_callback;
262
263 case PERF_RECORD_LOST:
264 lost_records = TRUE;
265 g_debug ("Lost records from perf");
266 break;
267 }
268
269 if (self->callback != NULL)
270 self->callback (event, self->cpu, self->callback_data);
271
272 us += is_self;
273 them += !is_self;
274
275 skip_callback:
276 tail += header->size;
277 }
278
279 self->tail = tail;
280
281 #ifdef HAVE_STDATOMIC_H
282 atomic_thread_fence (memory_order_seq_cst);
283 #elif G_GNUC_CHECK_VERSION(3, 0)
284 __sync_synchronize ();
285 #endif
286
287 self->map->data_tail = tail;
288
289 /* If we lost records them we took too long to process events and
290 * need to speed up how often we process incoming records. However,
291 * if we are the cause of that (due to running to frequently), then
292 * we need to back-off.
293 */
294 if (lost_records && us < them/3)
295 {
296 if (source->timeout_msec > 1)
297 source->timeout_msec -= 5;
298 }
299 else
300 {
301 if (source->timeout_msec < 500)
302 {
303 if (us < 5 && them < 5)
304 source->timeout_msec += 100;
305 else
306 source->timeout_msec += 10;
307 }
308 }
309 }
310
311 static gboolean
312 sysprof_perf_event_source_dispatch (GSource *gsource,
313 GSourceFunc callback,
314 gpointer user_data)
315 {
316 SysprofPerfEventSource *source = (SysprofPerfEventSource *)gsource;
317 SysprofPerfEventStream *self = source->stream;
318
319 if (source->next_ready_time <= g_source_get_time (gsource) &&
320 self != NULL &&
321 self->active &&
322 self->map != NULL &&
323 self->tail != self->map->data_head)
324 sysprof_perf_event_stream_flush (self);
325 else
326 source->timeout_msec = MIN (500, source->timeout_msec + 50);
327
328 source->next_ready_time = g_get_monotonic_time () + (source->timeout_msec * 1000);
329 g_source_set_ready_time (self->source, source->next_ready_time);
330
331 return G_SOURCE_CONTINUE;
332 }
333
334 static GSourceFuncs source_funcs = {
335 .dispatch = sysprof_perf_event_source_dispatch,
336 };
337
338 static void
339 sysprof_perf_event_stream_finalize (GObject *object)
340 {
341 SysprofPerfEventStream *self = (SysprofPerfEventStream *)object;
342
343 if (self->callback_data_destroy)
344 {
345 self->callback_data_destroy (self->callback_data);
346 self->callback_data_destroy = NULL;
347 self->callback_data = NULL;
348 }
349
350 self->callback = NULL;
351
352 g_clear_object (&self->connection);
353
354 if (self->source != NULL)
355 {
356 g_source_destroy (self->source);
357 g_source_unref (self->source);
358 self->source = NULL;
359 }
360
361 g_clear_fd (&self->perf_fd, NULL);
362 g_clear_fd (&self->group_fd, NULL);
363
364 if (self->map != NULL && self->map_size > 0)
365 {
366 munmap (self->map, self->map_size);
367 self->map = NULL;
368 self->map_size = 0;
369 }
370
371 G_OBJECT_CLASS (sysprof_perf_event_stream_parent_class)->finalize (object);
372 }
373
374 static void
375 sysprof_perf_event_stream_get_property (GObject *object,
376 guint prop_id,
377 GValue *value,
378 GParamSpec *pspec)
379 {
380 SysprofPerfEventStream *self = SYSPROF_PERF_EVENT_STREAM (object);
381
382 switch (prop_id)
383 {
384 case PROP_ACTIVE:
385 g_value_set_boolean (value, self->active);
386 break;
387
388 default:
389 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
390 }
391 }
392
393 static void
394 sysprof_perf_event_stream_class_init (SysprofPerfEventStreamClass *klass)
395 {
396 GObjectClass *object_class = G_OBJECT_CLASS (klass);
397
398 object_class->finalize = sysprof_perf_event_stream_finalize;
399 object_class->get_property = sysprof_perf_event_stream_get_property;
400
401 properties[PROP_ACTIVE] =
402 g_param_spec_boolean ("active", NULL, NULL,
403 FALSE,
404 (G_PARAM_READABLE | G_PARAM_EXPLICIT_NOTIFY | G_PARAM_STATIC_STRINGS));
405
406 g_object_class_install_properties (object_class, N_PROPS, properties);
407 }
408
409 static void
410 sysprof_perf_event_stream_init (SysprofPerfEventStream *self)
411 {
412 self->perf_fd = -1;
413 self->group_fd = -1;
414 self->self_pid = getpid ();
415 }
416
417 static DexFuture *
418 sysprof_perf_event_stream_new_fiber (gpointer data)
419 {
420 SysprofPerfEventStream *self = data;
421 g_autofd int perf_fd = -1;
422 gsize map_size;
423 guint8 *map;
424
425 g_assert (SYSPROF_IS_PERF_EVENT_STREAM (self));
426
427 if (self->connection != NULL)
428 {
429 g_autoptr(GUnixFDList) fd_list = NULL;
430 g_autoptr(GUnixFDList) out_fd_list = NULL;
431 g_autoptr(GVariant) options = _sysprof_perf_event_attr_to_variant (&self->attr);
432 g_autoptr(DexFuture) future = NULL;
433 g_autoptr(GVariant) reply = NULL;
434 g_autoptr(GError) error = NULL;
435 int group_fd_handle = -1;
436 int handle;
437
438 if (self->group_fd > -1)
439 {
440 fd_list = g_unix_fd_list_new ();
441 group_fd_handle = g_unix_fd_list_append (fd_list, self->group_fd, NULL);
442 }
443
444 future = dex_dbus_connection_call_with_unix_fd_list (self->connection,
445 "org.gnome.Sysprof3",
446 "/org/gnome/Sysprof3",
447 "org.gnome.Sysprof3.Service",
448 "PerfEventOpen",
449 g_variant_new ("(@a{sv}iiht)",
450 options,
451 -1,
452 self->cpu,
453 group_fd_handle,
454 self->flags),
455 G_VARIANT_TYPE ("(h)"),
456 G_DBUS_CALL_FLAGS_NONE,
457 G_MAXUINT,
458 fd_list);
459
460 if (!dex_await (dex_ref (future), &error))
461 return dex_future_new_for_error (g_steal_pointer (&error));
462
463 g_assert (DEX_IS_FUTURE_SET (future));
464
465 if (!(out_fd_list = dex_await_object (dex_ref (dex_future_set_get_future_at (DEX_FUTURE_SET (future), 1)), &error)) ||
466 !(reply = dex_await_variant (dex_ref (dex_future_set_get_future_at (DEX_FUTURE_SET (future), 0)), &error)))
467 return dex_future_new_for_error (g_steal_pointer (&error));
468
469 g_variant_get (reply, "(h)", &handle);
470
471 if (-1 == (perf_fd = g_unix_fd_list_get (out_fd_list, handle, &error)))
472 return dex_future_new_for_error (g_steal_pointer (&error));
473 }
474 else
475 {
476 perf_fd = _perf_event_open (&self->attr, -1, self->cpu, self->group_fd, self->flags);
477
478 if (perf_fd < 0)
479 {
480 int errsv = errno;
481 return dex_future_new_reject (G_IO_ERROR,
482 g_io_error_from_errno (errsv),
483 "%s", g_strerror (errsv));
484 }
485 }
486
487 g_assert (self->perf_fd == -1);
488 g_assert (perf_fd > -1);
489
490 self->perf_fd = g_steal_fd (&perf_fd);
491
492 map_size = N_PAGES * sysprof_getpagesize () + sysprof_getpagesize ();
493 map = mmap (NULL, map_size, PROT_READ | PROT_WRITE, MAP_SHARED, self->perf_fd, 0);
494
495 if ((gpointer)map == MAP_FAILED)
496 {
497 int errsv = errno;
498 return dex_future_new_reject (G_IO_ERROR,
499 g_io_error_from_errno (errsv),
500 "%s", g_strerror (errsv));
501 }
502
503 self->map_size = map_size;
504 self->map = (gpointer)map;
505 self->map_data = map + sysprof_getpagesize ();
506 self->tail = 0;
507
508 return dex_future_new_take_object (g_object_ref (self));
509 }
510
511 DexFuture *
512 sysprof_perf_event_stream_new (GDBusConnection *connection,
513 struct perf_event_attr *attr,
514 int cpu,
515 int group_fd,
516 guint64 flags,
517 SysprofPerfEventCallback callback,
518 gpointer callback_data,
519 GDestroyNotify callback_data_destroy)
520 {
521 SysprofPerfEventSource *source;
522 g_autoptr(SysprofPerfEventStream) self = NULL;
523 g_autofree char *name = NULL;
524
525 g_return_val_if_fail (!connection || G_IS_DBUS_CONNECTION (connection), NULL);
526 g_return_val_if_fail (attr != NULL, NULL);
527 g_return_val_if_fail (cpu > -1, NULL);
528 g_return_val_if_fail (group_fd >= -1, NULL);
529
530 self = g_object_new (SYSPROF_TYPE_PERF_EVENT_STREAM, NULL);
531 self->connection = connection ? g_object_ref (connection) : NULL;
532 self->attr = *attr;
533 self->cpu = cpu;
534 self->group_fd = group_fd > -1 ? dup (group_fd) : -1;
535 self->flags = flags;
536 self->callback = callback;
537 self->callback_data = callback_data;
538 self->callback_data_destroy = callback_data_destroy;
539
540 source = (SysprofPerfEventSource *)
541 g_source_new (&source_funcs, sizeof (SysprofPerfEventSource));
542 source->stream = self;
543 source->timeout_msec = 5;
544 source->next_ready_time = g_get_monotonic_time () + (source->timeout_msec * 1000);
545 self->source = (GSource *)source;
546
547 name = g_strdup_printf ("[perf cpu%d]", cpu);
548
549 g_source_set_ready_time (self->source, source->next_ready_time);
550 g_source_set_name (self->source, name);
551 g_source_attach (self->source, NULL);
552
553 return dex_scheduler_spawn (NULL, 0,
554 sysprof_perf_event_stream_new_fiber,
555 g_object_ref (self),
556 g_object_unref);
557 }
558
559 gboolean
560 sysprof_perf_event_stream_enable (SysprofPerfEventStream *self,
561 GError **error)
562 {
563 g_return_val_if_fail (SYSPROF_IS_PERF_EVENT_STREAM (self), FALSE);
564
565 if (self->active)
566 return TRUE;
567
568 if (0 != ioctl (self->perf_fd, PERF_EVENT_IOC_ENABLE))
569 {
570 int errsv = errno;
571 g_set_error_literal (error,
572 G_IO_ERROR,
573 g_io_error_from_errno (errsv),
574 g_strerror (errsv));
575 return FALSE;
576 }
577
578 self->active = TRUE;
579
580 g_object_notify_by_pspec (G_OBJECT (self), properties [PROP_ACTIVE]);
581
582 return TRUE;
583 }
584
585 gboolean
586 sysprof_perf_event_stream_disable (SysprofPerfEventStream *self,
587 GError **error)
588 {
589 g_return_val_if_fail (SYSPROF_IS_PERF_EVENT_STREAM (self), FALSE);
590
591 if (!self->active)
592 return TRUE;
593
594 if (0 != ioctl (self->perf_fd, PERF_EVENT_IOC_DISABLE))
595 {
596 int errsv = errno;
597 g_set_error_literal (error,
598 G_IO_ERROR,
599 g_io_error_from_errno (errsv),
600 g_strerror (errsv));
601 return FALSE;
602 }
603
604 self->active = FALSE;
605
606 sysprof_perf_event_stream_flush (self);
607
608 g_object_notify_by_pspec (G_OBJECT (self), properties [PROP_ACTIVE]);
609
610 return TRUE;
611 }