Debian Codegraph @

src/libsysprof/sysprof-sampler.c

raw
1 /* sysprof-sampler.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 #include "config.h"
22
23 #include "sysprof-instrument-private.h"
24 #include "sysprof-perf-event-stream-private.h"
25 #include "sysprof-recording-private.h"
26 #include "sysprof-sampler.h"
27
28 #define N_WAKEUP_EVENTS 149
29
30 struct _SysprofSampler
31 {
32 SysprofInstrument parent_instance;
33 GDBusConnection *connection;
34 GPtrArray *perf_event_streams;
35 guint sample_lost_counter_id;
36 gint64 lost_count;
37 };
38
39 struct _SysprofSamplerClass
40 {
41 SysprofInstrumentClass parent_class;
42 };
43
44 typedef struct
45 {
46 SysprofRecording *recording;
47 SysprofCaptureWriter *writer;
48 guint lost_counter_id;
49 gint64 lost;
50 } StreamData;
51
52 G_DEFINE_FINAL_TYPE (SysprofSampler, sysprof_sampler, SYSPROF_TYPE_INSTRUMENT)
53
54 static StreamData *
55 stream_data_new (SysprofRecording *recording)
56 {
57 SysprofCaptureCounter info = {0};
58 StreamData *data;
59
60 g_assert (SYSPROF_IS_RECORDING (recording));
61
62 data = g_atomic_rc_box_new0 (StreamData);
63 data->recording = g_object_ref (recording);
64 data->writer = sysprof_capture_writer_ref (_sysprof_recording_writer (recording));
65 data->lost_counter_id = sysprof_capture_writer_request_counter (data->writer, 1);
66 data->lost = 0;
67
68 g_strlcpy (info.category, "Sampler", sizeof info.category);
69 g_strlcpy (info.name, "Lost Samples", sizeof info.name);
70 g_strlcpy (info.description, "Samples dropped due to full ring buffer", sizeof info.description);
71 info.id = data->lost_counter_id;
72 info.type = SYSPROF_CAPTURE_COUNTER_INT64;
73 info.value.v64 = 0;
74
75 sysprof_capture_writer_define_counters (data->writer,
76 SYSPROF_CAPTURE_CURRENT_TIME, -1, -1,
77 &info, 1);
78
79 return data;
80 }
81
82 static StreamData *
83 stream_data_ref (StreamData *data)
84 {
85 return g_atomic_rc_box_acquire (data);
86 }
87
88 static void
89 stream_data_finalize (gpointer ptr)
90 {
91 StreamData *data = ptr;
92
93 g_clear_pointer (&data->writer, sysprof_capture_writer_unref);
94 g_clear_object (&data->recording);
95 }
96
97 static void
98 stream_data_unref (StreamData *data)
99 {
100 g_atomic_rc_box_release_full (data, stream_data_finalize);
101 }
102
103 G_DEFINE_AUTOPTR_CLEANUP_FUNC (StreamData, stream_data_unref)
104
105 static char **
106 sysprof_sampler_list_required_policy (SysprofInstrument *instrument)
107 {
108 static const char *policy[] = {"org.gnome.sysprof3.profile", NULL};
109
110 return g_strdupv ((char **)policy);
111 }
112
113 static inline void
114 realign (gsize *pos,
115 gsize align)
116 {
117 *pos = (*pos + align - 1) & ~(align - 1);
118 }
119
120 static void
121 sysprof_sampler_add_callback (SysprofCaptureWriter *writer,
122 int cpu,
123 const SysprofPerfEventCallchain *sample)
124 {
125 const guint64 *ips;
126 guint64 trace[3];
127 int n_ips;
128
129 g_assert (writer != NULL);
130 g_assert (sample != NULL);
131
132 ips = sample->ips;
133 n_ips = sample->n_ips;
134
135 if (n_ips == 0)
136 {
137 if (sample->header.misc & PERF_RECORD_MISC_KERNEL)
138 {
139 trace[0] = PERF_CONTEXT_KERNEL;
140 trace[1] = sample->ip;
141 trace[2] = PERF_CONTEXT_USER;
142
143 ips = trace;
144 n_ips = 3;
145 }
146 else
147 {
148 trace[0] = PERF_CONTEXT_USER;
149 trace[1] = sample->ip;
150
151 ips = trace;
152 n_ips = 2;
153 }
154 }
155
156 sysprof_capture_writer_add_sample (writer,
157 sample->time,
158 cpu,
159 sample->pid,
160 sample->tid,
161 ips,
162 n_ips);
163 }
164
165 static void
166 sysprof_sampler_perf_event_stream_cb (const SysprofPerfEvent *event,
167 guint cpu,
168 gpointer user_data)
169 {
170 StreamData *data = user_data;
171 SysprofRecording *recording = data->recording;
172 SysprofCaptureWriter *writer = data->writer;
173 gsize offset;
174 gint64 time;
175
176 g_assert (data != NULL);
177 g_assert (event != NULL);
178
179 switch (event->header.type)
180 {
181 case PERF_RECORD_COMM:
182 offset = strlen (event->comm.comm) + 1;
183 realign (&offset, sizeof (guint64));
184 offset += sizeof (GPid) + sizeof (GPid);
185 memcpy (&time, event->comm.comm + offset, sizeof time);
186
187 if (event->comm.pid == event->comm.tid)
188 {
189 sysprof_capture_writer_add_process (writer,
190 time,
191 cpu,
192 event->comm.pid,
193 event->comm.comm);
194
195 _sysprof_recording_follow_process (recording,
196 event->comm.pid,
197 event->comm.comm);
198 }
199
200 break;
201
202 case PERF_RECORD_EXIT:
203 /* Ignore fork exits for now */
204 if (event->exit.tid != event->exit.pid)
205 break;
206
207 sysprof_capture_writer_add_exit (writer,
208 event->exit.time,
209 cpu,
210 event->exit.pid);
211
212 break;
213
214 case PERF_RECORD_FORK:
215 sysprof_capture_writer_add_fork (writer,
216 event->fork.time,
217 cpu,
218 event->fork.ptid,
219 event->fork.tid);
220 break;
221
222 case PERF_RECORD_LOST:
223 {
224 SysprofCaptureCounterValue value;
225 gint64 now = SYSPROF_CAPTURE_CURRENT_TIME;
226 char message[64];
227
228 g_snprintf (message, sizeof message,
229 "Lost %"G_GUINT64_FORMAT" samples",
230 event->lost.lost);
231 sysprof_capture_writer_add_log (writer, now, -1, -1, G_LOG_LEVEL_CRITICAL,
232 "Sampler", message);
233
234 value.v64 = (data->lost += event->lost.lost);
235 sysprof_capture_writer_set_counters (writer, now, -1, -1,
236 &data->lost_counter_id, &value, 1);
237 break;
238 }
239
240 case PERF_RECORD_MMAP:
241 offset = strlen (event->mmap.filename) + 1;
242 realign (&offset, sizeof (guint64));
243 offset += sizeof (GPid) + sizeof (GPid);
244 memcpy (&time, event->mmap.filename + offset, sizeof time);
245
246 sysprof_capture_writer_add_map (writer,
247 time,
248 cpu,
249 event->mmap.pid,
250 event->mmap.addr,
251 event->mmap.addr + event->mmap.len,
252 event->mmap.pgoff,
253 0,
254 event->mmap.filename);
255
256 break;
257
258 case PERF_RECORD_MMAP2:
259 offset = strlen (event->mmap2.filename) + 1;
260 realign (&offset, sizeof (guint64));
261 offset += sizeof (GPid) + sizeof (GPid);
262 memcpy (&time, event->mmap2.filename + offset, sizeof time);
263
264 if ((event->header.misc & PERF_RECORD_MISC_MMAP_BUILD_ID) != 0)
265 {
266 char build_id[G_N_ELEMENTS (event->mmap2.build_id) * 2 + 1];
267 guint len = MIN (G_N_ELEMENTS (event->mmap2.build_id), event->mmap2.build_id_size);
268
269 for (guint i = 0; i < len; i++)
270 g_snprintf (&build_id[len*2], 3, "%02x", event->mmap2.build_id[i]);
271 build_id[len*2] = 0;
272
273 sysprof_capture_writer_add_map_with_build_id (writer,
274 time,
275 cpu,
276 event->mmap2.pid,
277 event->mmap2.addr,
278 event->mmap2.addr + event->mmap2.len,
279 event->mmap2.pgoff,
280 event->mmap2.ino,
281 event->mmap2.filename,
282 build_id);
283 }
284 else
285 {
286 sysprof_capture_writer_add_map (writer,
287 time,
288 cpu,
289 event->mmap2.pid,
290 event->mmap2.addr,
291 event->mmap2.addr + event->mmap2.len,
292 event->mmap2.pgoff,
293 event->mmap2.ino,
294 event->mmap2.filename);
295 }
296 break;
297
298 case PERF_RECORD_READ:
299 break;
300
301 case PERF_RECORD_SAMPLE:
302 if (recording->start_time != 0 && event->callchain.time >= recording->start_time)
303 sysprof_sampler_add_callback (writer, cpu, &event->callchain);
304 break;
305
306 case PERF_RECORD_THROTTLE:
307 case PERF_RECORD_UNTHROTTLE:
308 default:
309 break;
310 }
311 }
312
313 typedef struct _Prepare
314 {
315 SysprofRecording *recording;
316 SysprofSampler *sampler;
317 GDBusConnection *connection;
318 } Prepare;
319
320 static void
321 prepare_free (Prepare *prepare)
322 {
323 g_clear_object (&prepare->recording);
324 g_clear_object (&prepare->sampler);
325 g_clear_object (&prepare->connection);
326 g_free (prepare);
327 }
328
329 static DexFuture *
330 sysprof_sampler_prepare_fiber (gpointer user_data)
331 {
332 Prepare *prepare = user_data;
333 g_autoptr(StreamData) stream_data = NULL;
334 g_autoptr(GPtrArray) futures = NULL;
335 g_autoptr(GError) error = NULL;
336 struct perf_event_attr attr = {0};
337 gboolean with_mmap2 = TRUE;
338 guint n_cpu;
339 gboolean use_software = FALSE;
340
341 g_assert (prepare != NULL);
342 g_assert (SYSPROF_IS_RECORDING (prepare->recording));
343 g_assert (SYSPROF_IS_SAMPLER (prepare->sampler));
344 g_assert (!prepare->connection || G_IS_DBUS_CONNECTION (prepare->connection));
345
346 /* First thing we need to do is to ensure the consumer has
347 * access to kallsyms, which may be from a machine, or boot
348 * different than this boot (and therefore symbols exist in
349 * different locations). Embed the kallsyms, but gzip it as
350 * those files can be quite large.
351 */
352 if (!dex_await (_sysprof_recording_add_file (prepare->recording,
353 "/proc/kallsyms",
354 TRUE),
355 &error))
356 {
357 _sysprof_recording_diagnostic (prepare->recording,
358 "Sampler",
359 "Failed to record copy of “kallsyms” to capture: %s",
360 error->message);
361 g_clear_error (&error);
362 }
363
364 /* Now create a SysprofPerfEventStream for every CPU on the
365 * system. Linux Perf will only let us create a stream for
366 * a single PID on all CPU, or all PID on a single CPU. So
367 * we create one per-CPU and stream those results into the
368 * capture file during recording.
369 *
370 * Previously, we supported recording a single process but
371 * that is more effort than it is worth, since virtually
372 * nobody uses Sysprof that way.
373 */
374 n_cpu = g_get_num_processors ();
375 futures = g_ptr_array_new_with_free_func (dex_unref);
376
377 try_again:
378 attr.sample_type = PERF_SAMPLE_IP
379 | PERF_SAMPLE_TID
380 | PERF_SAMPLE_IDENTIFIER
381 | PERF_SAMPLE_CALLCHAIN
382 | PERF_SAMPLE_TIME;
383 attr.wakeup_events = N_WAKEUP_EVENTS;
384 attr.disabled = TRUE;
385 attr.mmap = TRUE;
386 attr.mmap2 = with_mmap2;
387 attr.comm = 1;
388 attr.task = 1;
389 attr.exclude_idle = 1;
390 attr.sample_id_all = 1;
391
392 #ifdef HAVE_PERF_CLOCKID
393 attr.clockid = sysprof_clock;
394 attr.use_clockid = 1;
395 #endif
396
397 attr.size = sizeof attr;
398
399 if (use_software)
400 {
401 attr.type = PERF_TYPE_SOFTWARE;
402 attr.config = PERF_COUNT_SW_CPU_CLOCK;
403 attr.sample_period = 1000000;
404 }
405 else
406 {
407 attr.type = PERF_TYPE_HARDWARE;
408 attr.config = PERF_COUNT_HW_CPU_CYCLES;
409 attr.sample_period = 1200000;
410 }
411
412 /* Pipeline our request for n_cpu perf_event_open calls and then
413 * await them all to complete.
414 */
415 stream_data = stream_data_new (prepare->recording);
416 for (guint i = 0; i < n_cpu; i++)
417 g_ptr_array_add (futures,
418 sysprof_perf_event_stream_new (prepare->connection,
419 &attr,
420 i,
421 -1,
422 0,
423 sysprof_sampler_perf_event_stream_cb,
424 stream_data_ref (stream_data),
425 (GDestroyNotify)stream_data_unref));
426
427 if (!dex_await (dex_future_allv ((DexFuture **)futures->pdata, futures->len), &error))
428 {
429 guint failed = 0;
430
431 for (guint i = 0; i < futures->len; i++)
432 {
433 DexFuture *future = g_ptr_array_index (futures, i);
434
435 if (dex_future_get_status (future) == DEX_FUTURE_STATUS_REJECTED)
436 {
437 g_autoptr(GError) future_error = NULL;
438
439 dex_future_get_value (future, &future_error);
440
441 if (!with_mmap2)
442 _sysprof_recording_diagnostic (prepare->recording,
443 "Sampler",
444 "Failed to load Perf event stream for CPU %d: %s",
445 i, future_error->message);
446 failed++;
447 }
448 }
449
450 if (failed == futures->len)
451 {
452 if (with_mmap2)
453 {
454 with_mmap2 = FALSE;
455 g_ptr_array_remove_range (futures, 0, futures->len);
456 goto try_again;
457 }
458
459 if (use_software == FALSE)
460 {
461 with_mmap2 = TRUE;
462 use_software = TRUE;
463 g_ptr_array_remove_range (futures, 0, futures->len);
464 goto try_again;
465 }
466
467 return dex_future_new_for_error (g_steal_pointer (&error));
468 }
469 }
470
471 /* Save each of the streams (currently corked), so that we can
472 * uncork them while recording. We already checked that all the
473 * futures have succeeded above, so dex_await_object() must
474 * always return an object for each sub-future.
475 */
476 for (guint i = 0; i < futures->len; i++)
477 {
478 DexFuture *future = g_ptr_array_index (futures, i);
479 g_autoptr(SysprofPerfEventStream) stream = NULL;
480 g_autoptr(GError) stream_error = NULL;
481
482 if ((stream = dex_await_object (dex_ref (future), &stream_error)))
483 g_ptr_array_add (prepare->sampler->perf_event_streams, g_steal_pointer (&stream));
484 }
485
486 /* Start all of the samplers immediately as we will drop events that
487 * are incoming before our start time. This allows the linux instrument
488 * to collect processes in prepare and not race to get new process info.
489 */
490 for (guint i = 0; i < prepare->sampler->perf_event_streams->len; i++)
491 {
492 SysprofPerfEventStream *stream = g_ptr_array_index (prepare->sampler->perf_event_streams, i);
493
494 if (!sysprof_perf_event_stream_enable (stream, &error))
495 g_debug ("%s", error->message);
496 else
497 g_debug ("Sampler %d enabled", i);
498
499 g_clear_error (&error);
500 }
501
502 return dex_future_new_for_boolean (TRUE);
503 }
504
505 static DexFuture *
506 sysprof_sampler_prepare (SysprofInstrument *instrument,
507 SysprofRecording *recording)
508 {
509 SysprofSampler *self = (SysprofSampler *)instrument;
510 Prepare *prepare;
511
512 g_assert (SYSPROF_IS_INSTRUMENT (instrument));
513 g_assert (SYSPROF_IS_RECORDING (recording));
514
515 prepare = g_new0 (Prepare, 1);
516 g_set_object (&prepare->recording, recording);
517 g_set_object (&prepare->sampler, self);
518 g_set_object (&prepare->connection, self->connection);
519
520 return dex_scheduler_spawn (NULL, 0,
521 sysprof_sampler_prepare_fiber,
522 prepare,
523 (GDestroyNotify)prepare_free);
524 }
525
526 typedef struct _Record
527 {
528 SysprofRecording *recording;
529 SysprofSampler *sampler;
530 DexFuture *cancellable;
531 } Record;
532
533 static void
534 record_free (Record *record)
535 {
536 g_clear_object (&record->recording);
537 g_clear_object (&record->sampler);
538 dex_clear (&record->cancellable);
539 g_free (record);
540 }
541
542 static DexFuture *
543 sysprof_sampler_record_fiber (gpointer user_data)
544 {
545 Record *record = user_data;
546 g_autoptr(GError) error = NULL;
547
548 g_assert (record != NULL);
549 g_assert (SYSPROF_IS_SAMPLER (record->sampler));
550 g_assert (SYSPROF_IS_RECORDING (record->recording));
551 g_assert (DEX_IS_FUTURE (record->cancellable));
552
553 if (!dex_await (dex_ref (record->cancellable), &error))
554 g_debug ("Sampler shutting down for reason: %s", error->message);
555
556 for (guint i = 0; i < record->sampler->perf_event_streams->len; i++)
557 {
558 SysprofPerfEventStream *stream = g_ptr_array_index (record->sampler->perf_event_streams, i);
559
560 if (!sysprof_perf_event_stream_disable (stream, &error))
561 g_debug ("%s", error->message);
562 else
563 g_debug ("Sampler %d disabled", i);
564
565 g_clear_error (&error);
566 }
567
568 return dex_future_new_for_boolean (TRUE);
569 }
570
571 static DexFuture *
572 sysprof_sampler_record (SysprofInstrument *instrument,
573 SysprofRecording *recording,
574 GCancellable *cancellable)
575 {
576 SysprofSampler *self = (SysprofSampler *)instrument;
577 Record *record;
578
579 g_assert (SYSPROF_IS_INSTRUMENT (instrument));
580 g_assert (SYSPROF_IS_RECORDING (recording));
581 g_assert (!cancellable || G_IS_CANCELLABLE (cancellable));
582
583 record = g_new0 (Record, 1);
584 record->recording = g_object_ref (recording);
585 record->sampler = g_object_ref (self);
586 record->cancellable = dex_cancellable_new_from_cancellable (cancellable);
587
588 return dex_scheduler_spawn (NULL, 0,
589 sysprof_sampler_record_fiber,
590 record,
591 (GDestroyNotify)record_free);
592 }
593
594 static void
595 sysprof_sampler_set_connection (SysprofInstrument *instrument,
596 GDBusConnection *connection)
597 {
598 SysprofSampler *self = SYSPROF_SAMPLER (instrument);
599
600 g_set_object (&self->connection, connection);
601 }
602
603 static void
604 sysprof_sampler_finalize (GObject *object)
605 {
606 SysprofSampler *self = (SysprofSampler *)object;
607
608 g_clear_pointer (&self->perf_event_streams, g_ptr_array_unref);
609 g_clear_object (&self->connection);
610
611 G_OBJECT_CLASS (sysprof_sampler_parent_class)->finalize (object);
612 }
613
614 static void
615 sysprof_sampler_class_init (SysprofSamplerClass *klass)
616 {
617 GObjectClass *object_class = G_OBJECT_CLASS (klass);
618 SysprofInstrumentClass *instrument_class = SYSPROF_INSTRUMENT_CLASS (klass);
619
620 object_class->finalize = sysprof_sampler_finalize;
621
622 instrument_class->list_required_policy = sysprof_sampler_list_required_policy;
623 instrument_class->prepare = sysprof_sampler_prepare;
624 instrument_class->record = sysprof_sampler_record;
625 instrument_class->set_connection = sysprof_sampler_set_connection;
626 }
627
628 static void
629 sysprof_sampler_init (SysprofSampler *self)
630 {
631 self->perf_event_streams = g_ptr_array_new_with_free_func (g_object_unref);
632 }
633
634 SysprofInstrument *
635 sysprof_sampler_new (void)
636 {
637 return g_object_new (SYSPROF_TYPE_SAMPLER, NULL);
638 }