perfetto icon indicating copy to clipboard operation
perfetto copied to clipboard

time sync problem between trace_event and ftrace

Open sifangli-labs opened this issue 1 year ago • 21 comments

On Linux, I use 3 data sources at the same time to capture a trace:

linux.ftrace
linux.process_stats
track_event

My goal is obvious - to see details of how CPU scheduling influence the thread's CPU access. When I see the generated trace, the track event slices and the thread's ftrace (runnable/runing) slices, I find they do not match: When my code runs (indicated by my instrumented track events), the thread is blank (not in the running or runnable segments - which is logically impossible since if the thread did not run on a CPU, it could NOT have generated the track events). Since my code is periodic in nature, I can see there is likely an offset/delay between these two data sources' clocks (the offset is also as long as 0.5sec) - so a clock sync issue? I do see ClockSnapshot packets in the trace and somehow they are not helpful? I can post more trace content if it helps. Here is an example - (my understanding is the track event use clock 64 and 64 and 6 are the same clock)

packet {
  first_packet_on_sequence: true
  timestamp: 0
  sequence_flags: 1
  trace_packet_defaults {
    timestamp_clock_id: 64
    track_event_defaults {
      track_uuid: 13343412599035999059
    }
  }
  clock_snapshot {
    clocks {
      clock_id: 6
      timestamp: 216110655115
    }
    clocks {
      clock_id: 64
      timestamp: 216110655115
      is_incremental: true
      unit_multiplier_ns: 1
    }
  }
  trusted_uid: 0
  trusted_packet_sequence_id: 3
  trusted_pid: 4910
  previous_packet_dropped: true
}

Can you explain why I am seeing the logically impossible results and how to fix it? Thanks!

sifangli-labs avatar May 29 '25 23:05 sifangli-labs

Clock sync seems a likely issue but to confirm, can you try setting disable_incremental_timestamps in your trace config (as specified by https://perfetto.dev/docs/reference/trace-config-proto#TrackEventConfig)?

LalitMaganti avatar May 29 '25 23:05 LalitMaganti

Thanks for the response and I will set it to be true and get back to you!

sifangli-labs avatar May 30 '25 00:05 sifangli-labs

after I set disable_incremental_timestamps: true I still see the mismatch - seemingly a delay of dozens of ms. Since the track event slice I am examine is small - 90us in this case, I wonder if the ftrace perfetto skipped the thread sched info and not showing ? I am under the impression the ftraces is complete that includes all the thread scheduling behavior.

sifangli-labs avatar May 30 '25 20:05 sifangli-labs

Unless you are observing Perfetto reporting data loss with a warning flag in the top-right of the UI, scheduling data in Perfetto is complete.

Would be difficult to look into this further without access to the trace.

LalitMaganti avatar May 30 '25 20:05 LalitMaganti

Right now I am not seeing any signs of ftrace loss - but the clock sync problem remains - interestingly it happens to some applications but not all (BTW, I am using one perfetto to profile multiple apps's track events) - the less busier threads aligned both sides of data perfectly. PS, the matching case might be coincidental - I just discovered a counter example with a delay offset of dozens of ms. The data suggest track event uses a clock 23ms 'ahead' of the clock ftrace uses.

sifangli-labs avatar May 30 '25 22:05 sifangli-labs

The data suggest track event uses a clock 23ms 'ahead' of the clock ftrace uses.

Unless you are on a very old or a strange kernel, ftrace and track event both use the boottime clock. You can check this by doing sudo cat /sys/kernel/tracing/trace_clock. If you see boot as an option there, ftrace supports boottime and there should be no need for clock sync.

LalitMaganti avatar May 31 '25 17:05 LalitMaganti

Here is where, in the track_event code, you can see that we use boottime on Linux: https://source.chromium.org/chromium/chromium/src/+/main:third_party/perfetto/src/tracing/internal/track_event_internal.cc;l=199;drc=dfb49a410ff213451f72db8d792973550025033e;bpv=0;bpt=1

LalitMaganti avatar May 31 '25 17:05 LalitMaganti

And here is our prioritsation of clocks for ftrace: https://source.chromium.org/chromium/chromium/src/+/main:third_party/perfetto/src/traced/probes/ftrace/ftrace_config_muxer.cc;l=60?q=SetClock&ss=chromium%2Fchromium%2Fsrc:third_party%2Fperfetto%2Fsrc%2Ftraced%2Fprobes%2Fftrace%2F

LalitMaganti avatar May 31 '25 17:05 LalitMaganti

I am seeing the problem on both x86 and aarch64 systems and I can confirm boot is among the output of /sys/kernel/tracing/trace_clock in both systems. From the content of the trace, can we already conclude that clock 6 (BOOTTIME) has been used in both ftrace and track events ? - see below.

$ fgrep timestamp_clock_id trace.txt
    timestamp_clock_id: 6
$ fgrep CLOCK trace.txt | sort -u
    primary_trace_clock: BUILTIN_CLOCK_BOOTTIME

If so I think we are actually using the same clock in both type of events, but there is an offset somehow. Is it possible when timing the track events the clock is not update as fast as in the kernel side?

sifangli-labs avatar Jun 02 '25 17:06 sifangli-labs

$ fgrep timestamp_clock_id trace.txt
    timestamp_clock_id: 6
$ fgrep CLOCK trace.txt | sort -u
    primary_trace_clock: BUILTIN_CLOCK_BOOTTIME

Both of these suggest that you are using BOOTTIME for track_event. They don't say anything about ftrace. For ftrace you should search for ftrace_clock in the trace: if that does not exist, then it's boottime.

If so I think we are actually using the same clock in both type of events, but there is an offset somehow. Is it possible when timing the track events the clock is not update as fast as in the kernel side?

That doesn't make sense really as we're getting the clock value from the kernel :) We don't do any caching or fiddling with the clocks, just directly say "at this time, this event happened" and ofc those events can only happen when the thread is scheduled.

FWIW I don't think we've seen anything like this behaviour before and we should have noticed: Chromium has long been an extensive user of track_event + scheduling traces and would have told us if theere was a 10-100ms desync between the two. Even Android is using track_event these days and we've not heard anything from them either.

LalitMaganti avatar Jun 02 '25 18:06 LalitMaganti

Hmm, there is no ftrace_clock in the trace: fgrep ftrace_clock /root/.cache/p-jetsonf.txt produces nothing. I assumed 'primary_trace_clock: BUILTIN_CLOCK_BOOTTIME' imples that is the clock.

data_sources {
      config {
        name: "linux.ftrace"
        target_buffer: 0
        ftrace_config {
          ftrace_events: "sched_switch"
          ftrace_events: "sched_waking"
          ftrace_events: "sched_wakeup_new"
          ftrace_events: "task_newtask"
          ftrace_events: "task_rename"
          ftrace_events: "sched_process_exec"
          ftrace_events: "sched_process_exit"
          ftrace_events: "sched_process_fork"
          ftrace_events: "sched_process_free"
          ftrace_events: "sched_process_hang"
          ftrace_events: "sched_process_wait"
          preserve_ftrace_buffer: true
        }
      }
    }

The following packets do not indicate what clock is being used in the ftrace - I suppose it would be the primary?:

packet {
  first_packet_on_sequence: true
  ftrace_stats {
    phase: START_OF_TRACE
    preserve_ftrace_buffer: true
  }
  trusted_uid: 0
  trusted_packet_sequence_id: 2
  trusted_pid: 113130
  previous_packet_dropped: true
}
packet {
  ftrace_events {
    cpu: 0
    previous_bundle_end_timestamp: 0
    event {
      timestamp: 80958107101056
      pid: 112837
      task_newtask {
        pid: 113970
   ...

sifangli-labs avatar Jun 02 '25 20:06 sifangli-labs

primary_trace_clock has nothing to do with collection of data (e.g. ftrace), it's all about how trace processor will interpret the data.

If you don't see any ftrace clock info, it's using boot time. Any other clock would have some information about which clock and the offsets to perform clock sync.

LalitMaganti avatar Jun 02 '25 20:06 LalitMaganti

That just confrims those two categories trace use the same clock since BUILTIN_CLOCK_BOOTTIME = 6, On both systems I have NTP running and the clocks are adjusted as the systems run. Do not know if that caused the issue.

I will see if the following change make any diff for the results:

--- a/src/tracing/internal/track_event_internal.cc
+++ b/src/tracing/internal/track_event_internal.cc
@@ -197,7 +197,8 @@ void TrackEventInternal::RemoveSessionObserver(
 #if !PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE) && \
     !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
 static constexpr protos::pbzero::BuiltinClock kDefaultTraceClock =
-    protos::pbzero::BUILTIN_CLOCK_BOOTTIME;
+    protos::pbzero::BUILTIN_CLOCK_REALTIME;
+    // protos::pbzero::BUILTIN_CLOCK_BOOTTIME;

sifangli-labs avatar Jun 02 '25 21:06 sifangli-labs

NTP will not affect anything. Boot time is a monotonic clock which only counts up since the time the decide is booted

Your patch has a high chance of not working at all and a small chance of simply making the probkem worse. I'll be shocked if it actually helps.

LalitMaganti avatar Jun 02 '25 21:06 LalitMaganti

I think I know where the problem is now. Linux by default uses local clock for ftrace - but Perfetto assumes boot clock is used:

sudo cat /sys/kernel/tracing/trace_clock
[local] global counter uptime perf mono mono_raw boot x86-tsc

I understand that the local clock (also called HW clock) is not influenced by NTP adjustment but boot clock is.

Here is the Linux man page. Note BOOTTIME is identical to MONOTONIC in this case since we do not have system suspension in the tests and NTP DOES plays a role here. On the otherhand, ftrace on Linux uses local clock (hardware clock) which is not influenced by NTP. Maybe that is the problem: perf etto assumes ftrace uses BOOTTIME as you have said - but that is probably not true for default Linux - which I have checked.

      CLOCK_MONOTONIC
              Clock that cannot be set and represents monotonic time since—as described by POSIX—"some unspeci‐
              fied point in the past".  On Linux, that point corresponds to the number of seconds that the sys‐
              tem has been running since it was booted.

              The CLOCK_MONOTONIC clock is not affected by discontinuous jumps in the system time (e.g., if the
              system administrator manually changes the clock), but is affected by the incremental  adjustments
              performed by adjtime(3) and NTP.  This clock does not count time that the system is suspended.
      ...
       CLOCK_BOOTTIME (since Linux 2.6.39; Linux-specific)
              Identical  to  CLOCK_MONOTONIC,  except  it  also includes any time that the system is suspended.
              This allows applications to get a suspend-aware monotonic clock without having to deal  with  the
              complications of CLOCK_REALTIME, which may have discontinuities if the time is changed using set‐
              timeofday(2) or similar.

sifangli-labs avatar Jun 02 '25 21:06 sifangli-labs

but Perfetto assumes boot clock is used

This is very much incorrect. We do not assume anything but set the clock ourselves when tracing is started. Here's the line of code when that happens: https://source.chromium.org/chromium/chromium/src/+/main:third_party/perfetto/src/traced/probes/ftrace/ftrace_config_muxer.cc;l=790;bpv=1;bpt=0

Unless you have an extremely old version of perfetto (multiple years old), if the boot clock is available, it should be used.

and NTP DOES plays a role here.

NTP does not play a role. The documentation explicitly says that BOOTIME is for cases when you want a clock which includes suspend but is not affected by timeofday (which is what NTP is changing).

LalitMaganti avatar Jun 02 '25 22:06 LalitMaganti

I am using PR 49.0 - thx for pointing out the code that sets the trace clock in PF, and I think we are very close to have this figured out - my test shows the following setting would silently bypass that part of code and leave the clock being used as 'local' while Perfetto assumes 'boot' clock is being used in ftrace (and track events too), that caused the clock sync issue seen.

preserve_ftrace_buffer : true

You can test by setting the trace clock to be 'local', and add the above in the ftrace cfg. Whether NTP has anything to do with it is not relevant at this point as long as local and boot are not the same - which is true.

sifangli-labs avatar Jun 03 '25 16:06 sifangli-labs

Ahhhhhhh I missed the fact that you set preserve_ftrace_buffer: true in your config. You're right: that would cause the issue.

preserve_ftrace_buffer: true is a very special argument: it basically tells us "do not do anything that would destroy the state of the existing buffers, just use the ftrace buffers as-is. Setting the tracing clock to a different value would cause destruction of the tracing data so we don't touch that option when it's there.

Now there are three points spawned as a result of this:

  1. If this option is set, we should read the ftrace clock from the kernel instead of assuming it to be boot (which is what we do today): that is definitely a bug on our side and something we should fix.
  2. One question: do you really need to set this option? it's a pretty advanced option to set and interferes with a bunch of the setup work we do on our side to make tracing consistent (setting ftrace buffer sizes, clocks, polling fill notify periods). You should really know what you're doing if you set this
  3. If the answer to 2) is "yes this is intentional and I know what I'm doing" and you want answers right now, there's a pretty easy workaround. Just run echo boot | sudo tee /sys/kernel/tracing/trace_clock at some point before you start tracing.

LalitMaganti avatar Jun 03 '25 16:06 LalitMaganti

yes, this option is needed and yes, I already tested your suggestion and it fixed it - thx for the quick responses for this issue!

Agree with you on #1 but I understand it might be challenging when you need to have PF work on other platforms and cannot handle all Linux clock choices - I would be satisfied if PF complains loudly and bail out with a suggestion to the user to set the trace clock to be boot before using PF. Thanks for working with me on this, please feel free to close this.

sifangli-labs avatar Jun 03 '25 16:06 sifangli-labs

We already have a bunch of logic to read/sync the ftrace clocks, we just have a bug which skips the clock read (making the code assume boot) when preserve_ftrace_buffer is set.

https://github.com/google/perfetto/pull/1722 will fix this oversight.

LalitMaganti avatar Jun 03 '25 18:06 LalitMaganti