summaryrefslogtreecommitdiffstats
path: root/gpu/command_buffer/service/gpu_tracer.cc
blob: 2cd38e79ca470b6a5c595541c5c3a5c8f640d320 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "gpu/command_buffer/service/gpu_tracer.h"

#include <deque>

#include "base/bind.h"
#include "base/debug/trace_event.h"
#include "base/strings/string_util.h"
#include "base/time/time.h"
#include "gpu/command_buffer/common/gles2_cmd_utils.h"

namespace gpu {
namespace gles2 {

static const unsigned int kProcessInterval = 16;
static TraceOutputter* g_outputter_thread = NULL;

scoped_refptr<TraceOutputter> TraceOutputter::Create(const std::string& name) {
  if (!g_outputter_thread) {
    g_outputter_thread = new TraceOutputter(name);
  }
  return g_outputter_thread;
}

TraceOutputter::TraceOutputter(const std::string& name)
    : named_thread_(name.c_str()), local_trace_id_(0) {
  named_thread_.Start();
  named_thread_.Stop();
}

TraceOutputter::~TraceOutputter() { g_outputter_thread = NULL; }

void TraceOutputter::Trace(const std::string& name,
                           int64 start_time,
                           int64 end_time) {
  TRACE_EVENT_COPY_BEGIN_WITH_ID_TID_AND_TIMESTAMP0(
      TRACE_DISABLED_BY_DEFAULT("gpu.device"),
      name.c_str(),
      local_trace_id_,
      named_thread_.thread_id(),
      start_time);
  TRACE_EVENT_COPY_END_WITH_ID_TID_AND_TIMESTAMP0(
      TRACE_DISABLED_BY_DEFAULT("gpu.device"),
      name.c_str(),
      local_trace_id_,
      named_thread_.thread_id(),
      end_time);
  ++local_trace_id_;
}

class NoopTrace : public Trace {
 public:
  explicit NoopTrace(const std::string& name) : Trace(name) {}

  // Implementation of Tracer
  virtual void Start() OVERRIDE {
    TRACE_EVENT_COPY_ASYNC_BEGIN0(
        TRACE_DISABLED_BY_DEFAULT("gpu.service"), name().c_str(), this);
  }
  virtual void End() OVERRIDE {
    TRACE_EVENT_COPY_ASYNC_END0(
        TRACE_DISABLED_BY_DEFAULT("gpu.service"), name().c_str(), this);
  }
  virtual bool IsAvailable() OVERRIDE { return true; }
  virtual bool IsProcessable() OVERRIDE { return false; }
  virtual void Process() OVERRIDE {}

 private:
  virtual ~NoopTrace() {}

  DISALLOW_COPY_AND_ASSIGN(NoopTrace);
};

struct TraceMarker {
  TraceMarker(const std::string& name, GpuTracerSource source)
      : name_(name), source_(source) {}

  std::string name_;
  GpuTracerSource source_;
  scoped_refptr<Trace> trace_;
};

class GPUTracerImpl
    : public GPUTracer,
      public base::SupportsWeakPtr<GPUTracerImpl> {
 public:
  GPUTracerImpl()
      : gpu_trace_srv_category(TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
            TRACE_DISABLED_BY_DEFAULT("gpu.service"))),
        gpu_trace_dev_category(TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
            TRACE_DISABLED_BY_DEFAULT("gpu.device"))),
        gpu_executing_(false),
        process_posted_(false) {}
  virtual ~GPUTracerImpl() {}

  // Implementation of gpu::gles2::GPUTracer
  virtual bool BeginDecoding() OVERRIDE;
  virtual bool EndDecoding() OVERRIDE;
  virtual bool Begin(const std::string& name, GpuTracerSource source) OVERRIDE;
  virtual bool End(GpuTracerSource source) OVERRIDE;
  virtual const std::string& CurrentName() const OVERRIDE;
  virtual bool IsTracing() OVERRIDE {
    return (*gpu_trace_srv_category != 0) || (*gpu_trace_dev_category != 0);
  }
  virtual void CalculateTimerOffset() {}

  // Process any completed traces.
  virtual void Process();
  virtual void ProcessTraces();

 protected:
  // Create a new trace.
  virtual scoped_refptr<Trace> CreateTrace(const std::string& name);

  const unsigned char* gpu_trace_srv_category;
  const unsigned char* gpu_trace_dev_category;

 protected:
  void IssueProcessTask();

  std::vector<TraceMarker> markers_;
  std::deque<scoped_refptr<Trace> > traces_;

  bool gpu_executing_;
  bool process_posted_;

  DISALLOW_COPY_AND_ASSIGN(GPUTracerImpl);
};

class GPUTracerARBTimerQuery : public GPUTracerImpl {
 public:
  explicit GPUTracerARBTimerQuery(gles2::GLES2Decoder* decoder);
  virtual ~GPUTracerARBTimerQuery();

  // Implementation of GPUTracerImpl
  virtual void ProcessTraces() OVERRIDE;

 protected:
  // Implementation of GPUTracerImpl.
  virtual bool BeginDecoding() OVERRIDE;
  virtual bool EndDecoding() OVERRIDE;
  virtual scoped_refptr<Trace> CreateTrace(const std::string& name) OVERRIDE;
  virtual void CalculateTimerOffset() OVERRIDE;

  scoped_refptr<Outputter> outputter_;

  bool gpu_timing_synced_;
  int64 timer_offset_;

  gles2::GLES2Decoder* decoder_;

  DISALLOW_COPY_AND_ASSIGN(GPUTracerARBTimerQuery);
};

bool Trace::IsProcessable() { return true; }

const std::string& Trace::name() { return name_; }

GLARBTimerTrace::GLARBTimerTrace(scoped_refptr<Outputter> outputter,
                                 const std::string& name,
                                 int64 offset)
    : Trace(name),
      outputter_(outputter),
      offset_(offset),
      start_time_(0),
      end_time_(0),
      end_requested_(false) {
  glGenQueries(2, queries_);
}

GLARBTimerTrace::~GLARBTimerTrace() { glDeleteQueries(2, queries_); }

void GLARBTimerTrace::Start() {
  TRACE_EVENT_COPY_ASYNC_BEGIN0(
      TRACE_DISABLED_BY_DEFAULT("gpu.service"), name().c_str(), this);
  glQueryCounter(queries_[0], GL_TIMESTAMP);
}

void GLARBTimerTrace::End() {
  glQueryCounter(queries_[1], GL_TIMESTAMP);
  end_requested_ = true;
  TRACE_EVENT_COPY_ASYNC_END0(
      TRACE_DISABLED_BY_DEFAULT("gpu.service"), name().c_str(), this);
}

bool GLARBTimerTrace::IsAvailable() {
  if (!end_requested_)
    return false;

  GLint done = 0;
  glGetQueryObjectiv(queries_[1], GL_QUERY_RESULT_AVAILABLE, &done);
  return !!done;
}

void GLARBTimerTrace::Process() {
  DCHECK(IsAvailable());

  GLuint64 timestamp;

  // TODO(dsinclair): It's possible for the timer to wrap during the start/end.
  // We need to detect if the end is less then the start and correct for the
  // wrapping.
  glGetQueryObjectui64v(queries_[0], GL_QUERY_RESULT, &timestamp);
  start_time_ = (timestamp / base::Time::kNanosecondsPerMicrosecond) + offset_;

  glGetQueryObjectui64v(queries_[1], GL_QUERY_RESULT, &timestamp);
  end_time_ = (timestamp / base::Time::kNanosecondsPerMicrosecond) + offset_;

  glDeleteQueries(2, queries_);
  outputter_->Trace(name(), start_time_, end_time_);
}

bool GPUTracerImpl::BeginDecoding() {
  if (gpu_executing_)
    return false;

  gpu_executing_ = true;

  if (IsTracing()) {
    // Begin a Trace for all active markers
    for (size_t i = 0; i < markers_.size(); i++) {
      markers_[i].trace_ = CreateTrace(markers_[i].name_);
      markers_[i].trace_->Start();
    }
  }
  return true;
}

bool GPUTracerImpl::EndDecoding() {
  if (!gpu_executing_)
    return false;

  // End Trace for all active markers
  if (IsTracing()) {
    for (size_t i = 0; i < markers_.size(); i++) {
      if (markers_[i].trace_) {
        markers_[i].trace_->End();
        if (markers_[i].trace_->IsProcessable())
          traces_.push_back(markers_[i].trace_);
        markers_[i].trace_ = 0;
      }
    }
    IssueProcessTask();
  }

  gpu_executing_ = false;
  return true;
}

bool GPUTracerImpl::Begin(const std::string& name, GpuTracerSource source) {
  if (!gpu_executing_)
    return false;

  // Push new marker from given 'source'
  markers_.push_back(TraceMarker(name, source));

  // Create trace
  if (IsTracing()) {
    scoped_refptr<Trace> trace = CreateTrace(name);
    trace->Start();
    markers_.back().trace_ = trace;
  }
  return true;
}

bool GPUTracerImpl::End(GpuTracerSource source) {
  if (!gpu_executing_)
    return false;

  // Pop last marker with matching 'source'
  for (int i = markers_.size() - 1; i >= 0; i--) {
    if (markers_[i].source_ == source) {
      // End trace
      if (IsTracing()) {
        scoped_refptr<Trace> trace = markers_[i].trace_;
        if (trace) {
          trace->End();
          if (trace->IsProcessable())
            traces_.push_back(trace);
          IssueProcessTask();
        }
      }

      markers_.erase(markers_.begin() + i);
      return true;
    }
  }
  return false;
}

void GPUTracerImpl::Process() {
  process_posted_ = false;
  ProcessTraces();
  IssueProcessTask();
}

void GPUTracerImpl::ProcessTraces() {
  while (!traces_.empty() && traces_.front()->IsAvailable()) {
    traces_.front()->Process();
    traces_.pop_front();
  }
}

const std::string& GPUTracerImpl::CurrentName() const {
  if (markers_.empty())
    return base::EmptyString();
  return markers_.back().name_;
}

scoped_refptr<Trace> GPUTracerImpl::CreateTrace(const std::string& name) {
  return new NoopTrace(name);
}

void GPUTracerImpl::IssueProcessTask() {
  if (traces_.empty() || process_posted_)
    return;

  process_posted_ = true;
  base::MessageLoop::current()->PostDelayedTask(
      FROM_HERE,
      base::Bind(&GPUTracerImpl::Process, base::AsWeakPtr(this)),
      base::TimeDelta::FromMilliseconds(kProcessInterval));
}

GPUTracerARBTimerQuery::GPUTracerARBTimerQuery(gles2::GLES2Decoder* decoder)
    : timer_offset_(0), decoder_(decoder) {
  outputter_ = TraceOutputter::Create("GL_ARB_timer_query");
}

GPUTracerARBTimerQuery::~GPUTracerARBTimerQuery() {
}

scoped_refptr<Trace> GPUTracerARBTimerQuery::CreateTrace(
    const std::string& name) {
  if (*gpu_trace_dev_category)
    return new GLARBTimerTrace(outputter_, name, timer_offset_);
  return GPUTracerImpl::CreateTrace(name);
}

bool GPUTracerARBTimerQuery::BeginDecoding() {
  if (*gpu_trace_dev_category) {
    // Make sure timing is synced before tracing
    if (!gpu_timing_synced_) {
      CalculateTimerOffset();
      gpu_timing_synced_ = true;
    }
  } else {
    // If GPU device category is off, invalidate timing sync
    gpu_timing_synced_ = false;
  }

  return GPUTracerImpl::BeginDecoding();
}

bool GPUTracerARBTimerQuery::EndDecoding() {
  bool ret = GPUTracerImpl::EndDecoding();

  // NOTE(vmiura_: glFlush() here can help give better trace results,
  // but it distorts the normal device behavior.
  return ret;
}

void GPUTracerARBTimerQuery::ProcessTraces() {
  TRACE_EVENT0("gpu", "GPUTracerARBTimerQuery::ProcessTraces");

  // Make owning decoder's GL context current
  if (!decoder_->MakeCurrent()) {
    // Skip subsequent GL calls if MakeCurrent fails
    traces_.clear();
    return;
  }

  while (!traces_.empty() && traces_.front()->IsAvailable()) {
    traces_.front()->Process();
    traces_.pop_front();
  }

  // Clear pending traces if there were are any errors
  GLenum err = glGetError();
  if (err != GL_NO_ERROR)
    traces_.clear();
}

void GPUTracerARBTimerQuery::CalculateTimerOffset() {
  TRACE_EVENT0("gpu", "GPUTracerARBTimerQuery::CalculateTimerOffset");

  // NOTE(vmiura): It would be better to use glGetInteger64v, however
  // it's not available everywhere.
  GLuint64 gl_now = 0;
  GLuint query;
  glFinish();
  glGenQueries(1, &query);
  glQueryCounter(query, GL_TIMESTAMP);
  glFinish();
  glGetQueryObjectui64v(query, GL_QUERY_RESULT, &gl_now);
  base::TimeTicks system_now = base::TimeTicks::NowFromSystemTraceTime();

  gl_now /= base::Time::kNanosecondsPerMicrosecond;
  timer_offset_ = system_now.ToInternalValue() - gl_now;
  glDeleteQueries(1, &query);
}

GPUTracer::GPUTracer() {}

GPUTracer::~GPUTracer() {}

scoped_ptr<GPUTracer> GPUTracer::Create(gles2::GLES2Decoder* decoder) {
  if (gfx::g_driver_gl.ext.b_GL_ARB_timer_query) {
    return scoped_ptr<GPUTracer>(new GPUTracerARBTimerQuery(decoder));
  }
  return scoped_ptr<GPUTracer>(new GPUTracerImpl());
}

}  // namespace gles2
}  // namespace gpu