1/*
2 * Copyright © 2019-2021 Collabora, Ltd.
3 * Author: Antonio Caggiano <antonio.caggiano@collabora.com>
4 * Author: Robert Beckett <bob.beckett@collabora.com>
5 * Author: Corentin Noël <corentin.noel@collabora.com>
6 *
7 * SPDX-License-Identifier: MIT
8 */
9
10#pragma once
11
12#include "pps.h"
13#include "pps_driver.h"
14
15namespace pps
16{
17struct GpuIncrementalState {
18   bool was_cleared = true;
19};
20
21struct GpuDataSourceTraits : public perfetto::DefaultDataSourceTraits {
22   using IncrementalStateType = GpuIncrementalState;
23};
24
25class Driver;
26
27/// @brief This datasource samples performance counters at a specified rate.
28/// Once the data is available, it sends a protobuf packet to the perfetto service.
29/// At the very beginning, it sends a description of the counters.
30/// After that, it sends counter values using the IDs set in the description.
31class GpuDataSource : public perfetto::DataSource<GpuDataSource, GpuDataSourceTraits>
32{
33   public:
34   void OnSetup(const SetupArgs &args) override;
35   void OnStart(const StartArgs &args) override;
36   void OnStop(const StopArgs &args) override;
37
38   /// Blocks until the data source starts
39   static void wait_started();
40
41   /// @brief Perfetto trace callback
42   static void trace_callback(TraceContext ctx);
43   static void register_data_source(const std::string &driver_name);
44
45   void trace(TraceContext &ctx);
46
47   private:
48   State state = State::Stop;
49
50   /// Time between trace callbacks
51   std::chrono::nanoseconds time_to_sleep = std::chrono::nanoseconds(1000000);
52
53   /// Used to check whether the datasource is quick enough
54   std::chrono::nanoseconds time_to_trace;
55
56   /// Last CPU timestamp at which we correlated CPU/GPU timestamps
57   uint64_t last_correlation_timestamp = 0;
58
59   /// A data source supports one driver at a time, but if you need more
60   /// than one gpu datasource you can just run another producer
61   Driver *driver = nullptr;
62
63   /// CPU timestamp of packet sent with counter descriptors
64   uint64_t descriptor_timestamp = 0;
65
66   /// GPU timestamp of packet sent with counter descriptors
67   uint64_t descriptor_gpu_timestamp = 0;
68};
69
70} // namespace pps
71