Skip to main content

starnix_modules_perfetto_consumer/
lib.rs

1// Copyright 2023 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#![recursion_limit = "256"]
6
7use anyhow::bail;
8use fuchsia_trace::{
9    BufferingMode, ProlongedContext, TraceState, category_enabled, trace_state, trace_string_ref_t,
10};
11use fuchsia_trace_observer::TraceObserver;
12use futures::{SinkExt, StreamExt};
13use fxt::blob::{BlobHeader, BlobType};
14use perfetto_protos::perfetto::protos::trace_config::buffer_config::FillPolicy;
15use perfetto_protos::perfetto::protos::trace_config::{BufferConfig, DataSource};
16use perfetto_protos::perfetto::protos::{
17    DataSourceConfig, DisableTracingRequest, EnableTracingRequest, FreeBuffersRequest,
18    FtraceConfig, ReadBuffersRequest, TraceConfig, ipc_frame,
19};
20use perfetto_trace_protos::perfetto::protos::frame_timeline_event::{
21    ActualDisplayFrameStart, ActualSurfaceFrameStart, Event, ExpectedDisplayFrameStart,
22    ExpectedSurfaceFrameStart,
23};
24use perfetto_trace_protos::perfetto::protos::ftrace_event::Event::Print;
25use perfetto_trace_protos::perfetto::protos::trace_packet;
26use starnix_core::security;
27use starnix_core::task::dynamic_thread_spawner::SpawnRequestBuilder;
28use starnix_core::task::tracing::PidKoidSession;
29use starnix_core::task::{CurrentTask, Kernel};
30use starnix_core::vfs::FsString;
31use starnix_logging::{
32    CATEGORY_ATRACE, NAME_PERFETTO_BLOB, log_debug, log_error, log_info, log_warn,
33};
34use starnix_perfetto_trace_decoder::{decode_read_buffers_response, decode_trace, encode_trace};
35
36use starnix_uapi::errors::Errno;
37
38mod atrace;
39
40const PERFETTO_BUFFER_SIZE_KB: u32 = 63488;
41
42/// State needed to act upon trace state changes.
43struct CallbackState {
44    /// The previously observed trace state.
45    prev_state: TraceState,
46    /// Path to the Perfetto consumer socket.
47    socket_path: FsString,
48    /// Connection to the consumer socket, if it has been initialized. This gets initialized the
49    /// first time it is needed.
50    connection: Option<perfetto::Consumer>,
51    /// Prolonged trace context to prevent the Fuchsia trace session from terminating while reading
52    /// data from Perfetto.
53    prolonged_context: Option<ProlongedContext>,
54    /// Partial trace packet returned from Perfetto but not yet written to Fuchsia.
55    packet_data: Vec<u8>,
56
57    /// Recording session for pid/koid mappings, held while tracing is started. Dropping
58    /// it (on stop) releases this client's interest in the shared manager.
59    session: Option<PidKoidSession>,
60}
61
62impl CallbackState {
63    fn connection(
64        &mut self,
65        current_task: &CurrentTask,
66    ) -> Result<&mut perfetto::Consumer, anyhow::Error> {
67        match self.connection {
68            None => {
69                self.connection =
70                    Some(perfetto::Consumer::new(current_task, self.socket_path.as_ref())?);
71                Ok(self.connection.as_mut().unwrap())
72            }
73            Some(ref mut conn) => Ok(conn),
74        }
75    }
76
77    fn handle_stopped(&mut self) {
78        self.prolonged_context = None;
79        self.packet_data.clear();
80        self.session = None;
81    }
82
83    fn on_state_change(
84        &mut self,
85        new_state: TraceState,
86        current_task: &CurrentTask,
87    ) -> Result<(), anyhow::Error> {
88        let prev_state = self.prev_state;
89        self.prev_state = new_state;
90        log_debug!(
91            "Perfetto consumer state change. new_state: {new_state:?}, prev_state: {prev_state:?}"
92        );
93        match new_state {
94            TraceState::Started => {
95                if prev_state != TraceState::Stopped {
96                    // This means something unexpected has caused the trace_engine to change
97                    // states faster than we're processing the trace observer events.
98                    log_error!(
99                        "Started received in {prev_state:?} state! Cleaning up then starting."
100                    );
101                    self.handle_stopped();
102                }
103                self.prolonged_context = ProlongedContext::acquire();
104                let connection = self.connection(current_task)?;
105                // A fixed set of data sources that may be of interest. As demand for other sources
106                // is found, add them here, and it may become worthwhile to allow this set to be
107                // configurable per trace session.
108                let mut data_sources = vec![
109                    DataSource {
110                        config: Some(DataSourceConfig {
111                            name: Some("track_event".to_string()),
112                            ..Default::default()
113                        }),
114                        ..Default::default()
115                    },
116                    DataSource {
117                        config: Some(DataSourceConfig {
118                            name: Some("android.surfaceflinger.frame".to_string()),
119                            target_buffer: Some(0),
120                            ..Default::default()
121                        }),
122                        ..Default::default()
123                    },
124                    DataSource {
125                        config: Some(DataSourceConfig {
126                            name: Some("android.surfaceflinger.frametimeline".to_string()),
127                            target_buffer: Some(0),
128                            ..Default::default()
129                        }),
130                        ..Default::default()
131                    },
132                ];
133                if category_enabled(CATEGORY_ATRACE) {
134                    data_sources.push(DataSource {
135                        config: Some(DataSourceConfig {
136                            name: Some("linux.ftrace".to_string()),
137                            ftrace_config: Some(FtraceConfig {
138                                ftrace_events: vec!["ftrace/print".to_string()],
139                                // Enable all supported atrace categories. This could be improved
140                                // in the future to be a subset that is configurable by each trace
141                                // session.
142                                atrace_categories: vec![
143                                    "am".to_string(),
144                                    "adb".to_string(),
145                                    "aidl".to_string(),
146                                    "dalvik".to_string(),
147                                    "audio".to_string(),
148                                    "binder_lock".to_string(),
149                                    "binder_driver".to_string(),
150                                    "bionic".to_string(),
151                                    "camera".to_string(),
152                                    "database".to_string(),
153                                    "gfx".to_string(),
154                                    "hal".to_string(),
155                                    "input".to_string(),
156                                    "network".to_string(),
157                                    "nnapi".to_string(),
158                                    "pm".to_string(),
159                                    "power".to_string(),
160                                    "rs".to_string(),
161                                    "res".to_string(),
162                                    "rro".to_string(),
163                                    "sched".to_string(),
164                                    "sm".to_string(),
165                                    "ss".to_string(),
166                                    "vibrator".to_string(),
167                                    "video".to_string(),
168                                    "view".to_string(),
169                                    "webview".to_string(),
170                                    "wm".to_string(),
171                                ],
172                                atrace_apps: vec!["*".to_string()],
173                                ..Default::default()
174                            }),
175                            ..Default::default()
176                        }),
177                        ..Default::default()
178                    });
179                }
180                connection.enable_tracing(
181                    current_task,
182                    EnableTracingRequest {
183                        trace_config: Some(TraceConfig {
184                            buffers: vec![BufferConfig {
185                                size_kb: Some(PERFETTO_BUFFER_SIZE_KB),
186                                fill_policy: Some(FillPolicy::Discard.into()),
187                                ..Default::default()
188                            }],
189                            data_sources,
190                            ..Default::default()
191                        }),
192                        attach_notification_only: None,
193                    },
194                )?;
195                // Once tracing has started, open a recording session so pid/koid
196                // mappings are tracked for the duration of the trace.
197                self.session = Some(current_task.kernel().trace_event_manager.open());
198            }
199            TraceState::Stopping => {
200                if prev_state != TraceState::Started {
201                    // If we receive a stop request and we don't think we're actually tracing, our
202                    // local state likely desynced from the global trace state. Clean up our state
203                    // and ensure we're stopped so we re-synchronize.
204                    log_error!("Stopping received in {prev_state:?} state! Cleaning up.");
205                    self.handle_stopped();
206                    return Ok(());
207                }
208
209                // We want to hold the prolonged context to ensure the trace session doesn't
210                // exit out from under us, but we also want to ensure we drop the prolonged
211                // context if we bail for whatever reason below.
212                let _local_prolonged_context = std::mem::replace(&mut self.prolonged_context, None);
213                let start_time = std::time::Instant::now();
214
215                let connection = self.connection(current_task)?;
216                let disable_request =
217                    connection.disable_tracing(current_task, DisableTracingRequest {})?;
218                loop {
219                    let frame = connection.next_frame_blocking(current_task)?;
220                    if frame.request_id == Some(disable_request) {
221                        break;
222                    } else {
223                        log_error!(
224                            "Ignoring frame while looking for DisableTracingRequest: {frame:?}"
225                        );
226                    }
227                }
228
229                let read_buffers_request =
230                    connection.read_buffers(current_task, ReadBuffersRequest {})?;
231
232                let blob_name_ref = {
233                    let Some(context) = fuchsia_trace::Context::acquire() else {
234                        bail!("Tracing stopped despite holding prolonged context");
235                    };
236                    context.register_string_literal(NAME_PERFETTO_BLOB)
237                };
238
239                // IPC responses may be spread across multiple frames, so loop until we get a
240                // message that indicates it is the last one. Additionally, if there are
241                // unrelated messages on the socket (e.g. leftover from a previous trace
242                // session), the loop will read past and ignore them.
243                loop {
244                    let frame = self.connection(current_task)?.next_frame_blocking(current_task)?;
245                    if frame.request_id != Some(read_buffers_request) {
246                        continue;
247                    } else {
248                        log_debug!(
249                            "perfetto_consumer ignoring frame while looking for ReadBuffersRequest {read_buffers_request}: {frame:?}"
250                        );
251                    }
252                    if let Some(ipc_frame::Msg::MsgInvokeMethodReply(reply)) = &frame.msg {
253                        if let Ok(response) = decode_read_buffers_response(
254                            reply.reply_proto.as_deref().unwrap_or(&[]),
255                        ) {
256                            for slice in &response.slices {
257                                if let Some(data) = &slice.data {
258                                    self.packet_data.extend(data);
259                                }
260                                if slice.last_slice_for_packet.unwrap_or(false) {
261                                    let mut blob_data = Vec::new();
262                                    // Packet field number = 1, length delimited type = 2.
263                                    blob_data.push(1 << 3 | 2);
264                                    // Push a varint encoded length.
265                                    // See https://protobuf.dev/programming-guides/encoding/
266                                    const HIGH_BIT: u8 = 0x80;
267                                    const LOW_SEVEN_BITS: usize = 0x7F;
268                                    let mut value = self.packet_data.len();
269                                    while value >= HIGH_BIT as usize {
270                                        blob_data.push((value & LOW_SEVEN_BITS) as u8 | HIGH_BIT);
271                                        value >>= 7;
272                                    }
273                                    blob_data.push(value as u8);
274                                    // `append` moves all data out of the passed Vec, so
275                                    // s.packet_data will be empty after this call.
276                                    blob_data.append(&mut self.packet_data);
277
278                                    // At this point blob_data is a full Perfetto Trace protobuf.
279                                    // Parse the data and replace the linux pids with their
280                                    // corresponding koid.
281                                    let rewritten =
282                                        self.rewrite_pids(&blob_data).unwrap_or(blob_data);
283
284                                    // Ignore a failure to write the packet here. We don't
285                                    // return immediately because we want to allow the
286                                    // remaining records to be recorded as dropped.
287                                    //
288                                    // Once we fill a buffer in oneshot mode, we expect to drop
289                                    // the remaining packets here.
290                                    //
291                                    // Rather than logging here, allow the trace system to
292                                    // aggregate the number of records dropped and we can query
293                                    // the trace system later to determine if we dropped
294                                    // records when it's more efficient to do so.
295                                    let _ = self.forward_packet(blob_name_ref, rewritten);
296                                }
297                            }
298                        } else {
299                            log_error!("perfetto_consumer cannot decode protobuf from {reply:?}");
300                        }
301                        if reply.has_more != Some(true) {
302                            break;
303                        }
304                    } else {
305                        log_error!(
306                            "perfetto_consumer ignoring non-MsgInvokeMethodReply message: {frame:?}"
307                        );
308                    }
309                }
310                // The response to a free buffers request does not have anything meaningful,
311                // so we don't need to worry about tracking the request id to match to the
312                // response.
313                let _free_buffers_request_id = self
314                    .connection(current_task)?
315                    .free_buffers(current_task, FreeBuffersRequest { buffer_ids: vec![0] })?;
316                let elapsed = start_time.elapsed().as_millis();
317                log_info!(
318                    "Perfetto frames copied, dropping prolonged trace context. Processing took {elapsed} ms"
319                );
320            }
321            TraceState::Stopped => {
322                self.handle_stopped();
323            }
324        }
325        Ok(())
326    }
327
328    // Forward `data` to the trace buffer by wrapping it in fxt blob records with the name
329    // `blob_name_ref`..
330    fn forward_packet(&self, blob_name_ref: trace_string_ref_t, data: Vec<u8>) -> Option<usize> {
331        // The blob data may be larger than what we can fit in a single record. If so, split it up
332        // over multiple chunks.
333        let mut bytes_written = 0;
334        let mut data_to_write = &data[..];
335
336        // We want to break the data into chunks:
337        // - Bigger chunks means less per-write overheader
338        // - Bigger chunks means less overhead due to blob meta
339        //
340        // However, too big and the blobs won't fit nicely into the trace buffer.
341        // The trace buffer is minimum 1MiB in size, so writing 4k at a time seems like a
342        // reasonable place to start that is both reasonably large and not going to leave a ton of
343        // space at the end of the trace buffer.
344        let max_chunk_size = 4096;
345        while !data_to_write.is_empty() {
346            let chunk_size = data_to_write.len().min(max_chunk_size);
347            let chunk = &data_to_write[..chunk_size];
348            self.forward_blob(blob_name_ref, &chunk)?;
349            data_to_write = &data_to_write[chunk_size..];
350            bytes_written += chunk_size;
351        }
352        Some(bytes_written)
353    }
354
355    // Given a blob name, wrap the data in an fxt perfetto blob and write it to the trace buffer.
356    fn forward_blob(&self, blob_name_ref: trace_string_ref_t, blob_data: &[u8]) -> Option<usize> {
357        let mut header = BlobHeader::empty();
358        header.set_name_ref(blob_name_ref.encoded_value);
359        header.set_payload_len(blob_data.len() as u16);
360        header.set_blob_format_type(BlobType::Perfetto.into());
361
362        let record_bytes = fxt::fxt_builder::FxtBuilder::new(header).atom(blob_data).build();
363        assert!(record_bytes.len() % std::mem::size_of::<u64>() == 0);
364        let num_words = record_bytes.len() / std::mem::size_of::<u64>();
365        let record_data = record_bytes.as_ptr();
366        #[allow(
367            clippy::undocumented_unsafe_blocks,
368            reason = "Force documented unsafe blocks in Starnix"
369        )]
370        let record_words =
371            unsafe { std::slice::from_raw_parts(record_data.cast::<u64>(), num_words) };
372
373        while let Some(context) = fuchsia_trace::Context::acquire() {
374            if let Some(bytes) = context.copy_record(record_words) {
375                return Some(bytes);
376            }
377            if context.buffering_mode() != BufferingMode::Streaming {
378                // If we're not in streaming mode, there will never be room for this record. Drop
379                // it.
380                return None;
381            }
382            // We're writing records pretty quick here, we're just forwarding data from
383            // perfetto with no breaks. trace_manager might not be able to keep up if it's also
384            // servicing other trace-providers. We want to back off we if find that we run out
385            // of space.
386            //
387            // We drop the context to decrement the refcount on the trace session. This allows
388            // trace-engine to switch the buffers if needed and drain out the buffers so that
389            // when we wake, there will hopefully be room.
390            //
391            // TODO(b/304532640)
392            drop(context);
393            std::thread::sleep(std::time::Duration::from_millis(100));
394        }
395        None
396    }
397
398    fn rewrite_pids(&mut self, protobuf_blob: &Vec<u8>) -> anyhow::Result<Vec<u8>> {
399        let mut proto = decode_trace(protobuf_blob.as_slice())?;
400        for p in &mut proto.packet {
401            if let Some(ref mut data) = p.data {
402                match data {
403                    trace_packet::Data::FrameTimelineEvent(frame_timeline_event) => {
404                        if let Some(evt) = &mut frame_timeline_event.event {
405                            // Update the linux pid to the Fuchsia pid. Each event has its own
406                            // match arm since the variant data is of a different type for each event.
407                            match evt {
408                                Event::ExpectedDisplayFrameStart(ExpectedDisplayFrameStart {
409                                    pid,
410                                    ..
411                                })
412                                | Event::ActualDisplayFrameStart(ActualDisplayFrameStart {
413                                    pid,
414                                    ..
415                                })
416                                | Event::ExpectedSurfaceFrameStart(ExpectedSurfaceFrameStart {
417                                    pid,
418                                    ..
419                                })
420                                | Event::ActualSurfaceFrameStart(ActualSurfaceFrameStart {
421                                    pid,
422                                    ..
423                                }) => {
424                                    pid.as_mut().map(|pid| {
425                                        *pid = self.map_to_koid_val(*pid);
426                                    });
427                                }
428                                Event::FrameEnd(_frame_end) => {}
429                            }
430                        }
431                    }
432                    trace_packet::Data::FtraceEvents(ftrace_bundle) => {
433                        for evt in &mut ftrace_bundle.event {
434                            if let Some(ref mut pid) = evt.pid {
435                                *pid = self.map_thread_to_koid_val(*pid as i32) as u32;
436                            }
437                            if let Some(ref mut event_data) = evt.event {
438                                match event_data {
439                                    Print(print) => {
440                                        if let Some(ref mut data) = print.buf {
441                                            *data = self.map_print_event(data)
442                                        }
443                                    }
444                                    _ => (),
445                                }
446                            }
447                        }
448                    }
449                    // No need to process other data; we only fixup data that references the pid.
450                    _ => (),
451                }
452            }
453        }
454        Ok(encode_trace(&proto))
455    }
456
457    fn map_print_event(&mut self, data: &String) -> String {
458        if let Some(mut event) = atrace::ATraceEvent::parse(&data) {
459            match event {
460                atrace::ATraceEvent::Begin { ref mut pid, .. }
461                | atrace::ATraceEvent::End { ref mut pid }
462                | atrace::ATraceEvent::Instant { ref mut pid, .. }
463                | atrace::ATraceEvent::AsyncBegin { ref mut pid, .. }
464                | atrace::ATraceEvent::AsyncEnd { ref mut pid, .. }
465                | atrace::ATraceEvent::Counter { ref mut pid, .. }
466                | atrace::ATraceEvent::AsyncTrackBegin { ref mut pid, .. }
467                | atrace::ATraceEvent::AsyncTrackEnd { ref mut pid, .. }
468                | atrace::ATraceEvent::Track { ref mut pid, .. } => {
469                    *pid = self.map_to_koid_val(*pid as i32) as u64
470                }
471            }
472            event.data()
473        } else {
474            data.to_string()
475        }
476    }
477
478    fn map_thread_to_koid_val(&mut self, pid: i32) -> i32 {
479        self.session
480            .as_ref()
481            .and_then(|s| s.resolve_tid_to_koid(pid))
482            .map(|k| k.raw_koid() as i32)
483            .unwrap_or(pid)
484    }
485
486    fn map_to_koid_val(&mut self, pid: i32) -> i32 {
487        self.session
488            .as_ref()
489            .and_then(|s| s.resolve_pid_to_koid(pid))
490            .map(|k| k.raw_koid() as i32)
491            .unwrap_or(pid)
492    }
493}
494
495pub fn start_perfetto_consumer_thread(kernel: &Kernel, socket_path: FsString) -> Result<(), Errno> {
496    let (mut tx, mut rx) = futures::channel::mpsc::channel::<TraceState>(32);
497
498    // Listens for trace state changes and sends them to Perfetto consumer thread.
499    // Unlike the perfetto thread, it won't block, so we can spawn it on the main async executor.
500    kernel.kthreads.spawn_future(
501        move || async move {
502            let observer = TraceObserver::new();
503            while let Ok(state) = observer.on_state_changed().await {
504                if let Err(e) = tx.send(state).await {
505                    log_error!("perfetto-trace-observer failed to send trace state change: {:?}. Receiver dropped.", e);
506                    return;
507                }
508            }
509        },
510        "perfetto-trace-observer",
511    );
512
513    // Perfetto consumer task: reads state changes from the channel and handles them.
514    // This task can block, so we spawn it on a dedicated thread to not block the observer or the
515    // main async executor.
516    let worker_closure = async move |current_task: &CurrentTask| {
517        let mut callback_state = CallbackState {
518            prev_state: TraceState::Stopped,
519            socket_path,
520            connection: None,
521            prolonged_context: None,
522            packet_data: Vec::new(),
523            session: None,
524        };
525
526        fn handle_state_change(
527            callback_state: &mut CallbackState,
528            current_task: &&CurrentTask,
529            state: TraceState,
530        ) -> Result<(), anyhow::Error> {
531            let current_task = current_task;
532            // TODO: https://fxbug.dev/457381697 - Revise how this kernel-internal work is security-
533            // checked.
534            let creds = security::creds_start_internal_operation(current_task);
535            current_task
536                .override_creds(creds, || callback_state.on_state_change(state, current_task))
537        }
538
539        // Check for tracing already started before we began observing.
540        // This happens when tracing is started on boot.
541        let mut state = trace_state();
542        if trace_state() == TraceState::Started {
543            const RETRY_DELAY: std::time::Duration = std::time::Duration::from_secs(5);
544            // When we do boot tracing, it is possible (even likely), that starnix has started but
545            // perfetto may not be ready to be connected to yet.
546            // In that case poll until it has started.
547            loop {
548                match handle_state_change(&mut callback_state, &current_task, state) {
549                    Ok(_) => break, // Success, exit loop.
550                    Err(e) => {
551                        if let Some(errno) = e.downcast_ref::<Errno>() {
552                            if errno == &starnix_uapi::errors::ENOENT
553                                || errno == &starnix_uapi::errors::ECONNREFUSED
554                            {
555                                log_warn!(
556                                    "perfetto_consumer initial start tracing failed because perfetto socket connection not established: {e:?} retrying in 5 seconds..."
557                                );
558                                std::thread::sleep(RETRY_DELAY);
559                                callback_state.prev_state = TraceState::Stopped;
560                                callback_state.connection = None;
561                                callback_state.prolonged_context = None;
562                                state = trace_state();
563                                continue; // Retry
564                            }
565                        }
566                        // For any other error, log and exit loop.
567                        log_error!(
568                            "perfetto_consumer initial start tracing failed with error: {e:?}"
569                        );
570                        break;
571                    }
572                }
573            }
574        }
575
576        while let Some(state) = rx.next().await {
577            handle_state_change(&mut callback_state, &current_task, state).unwrap_or_else(|e| {
578                log_error!("perfetto_consumer state change callback error: {:?}", e);
579            })
580        }
581    };
582    let worker_req = SpawnRequestBuilder::new()
583        .with_debug_name("perfetto-consumer")
584        .with_async_closure(worker_closure)
585        .build();
586    kernel.kthreads.spawner().spawn_from_request(worker_req);
587
588    Ok(())
589}