1 // Copyright (c) 2012 The Chromium 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.
6 #include "base/bind_helpers.h"
7 #include "base/command_line.h"
8 #include "base/debug/trace_event.h"
10 #include "base/memory/shared_memory.h"
11 #include "base/time/time.h"
12 #include "build/build_config.h"
13 #include "content/common/gpu/devtools_gpu_instrumentation.h"
14 #include "content/common/gpu/gpu_channel.h"
15 #include "content/common/gpu/gpu_channel_manager.h"
16 #include "content/common/gpu/gpu_command_buffer_stub.h"
17 #include "content/common/gpu/gpu_memory_manager.h"
18 #include "content/common/gpu/gpu_memory_tracking.h"
19 #include "content/common/gpu/gpu_messages.h"
20 #include "content/common/gpu/gpu_watchdog.h"
21 #include "content/common/gpu/image_transport_surface.h"
22 #include "content/common/gpu/media/gpu_video_decode_accelerator.h"
23 #include "content/common/gpu/media/gpu_video_encode_accelerator.h"
24 #include "content/common/gpu/sync_point_manager.h"
25 #include "content/public/common/content_client.h"
26 #include "gpu/command_buffer/common/constants.h"
27 #include "gpu/command_buffer/common/gles2_cmd_utils.h"
28 #include "gpu/command_buffer/common/mailbox.h"
29 #include "gpu/command_buffer/service/gl_context_virtual.h"
30 #include "gpu/command_buffer/service/gl_state_restorer_impl.h"
31 #include "gpu/command_buffer/service/gpu_control_service.h"
32 #include "gpu/command_buffer/service/image_manager.h"
33 #include "gpu/command_buffer/service/logger.h"
34 #include "gpu/command_buffer/service/mailbox_manager.h"
35 #include "gpu/command_buffer/service/memory_tracking.h"
36 #include "gpu/command_buffer/service/query_manager.h"
37 #include "ui/gl/gl_bindings.h"
38 #include "ui/gl/gl_switches.h"
41 #include "content/public/common/sandbox_init.h"
44 #if defined(OS_ANDROID)
45 #include "content/common/gpu/stream_texture_android.h"
49 struct WaitForCommandState
{
50 WaitForCommandState(int32 start
, int32 end
, IPC::Message
* reply
)
51 : start(start
), end(end
), reply(reply
) {}
55 scoped_ptr
<IPC::Message
> reply
;
60 // The GpuCommandBufferMemoryTracker class provides a bridge between the
61 // ContextGroup's memory type managers and the GpuMemoryManager class.
62 class GpuCommandBufferMemoryTracker
: public gpu::gles2::MemoryTracker
{
64 explicit GpuCommandBufferMemoryTracker(GpuChannel
* channel
) :
65 tracking_group_(channel
->gpu_channel_manager()->gpu_memory_manager()->
66 CreateTrackingGroup(channel
->renderer_pid(), this)) {
69 virtual void TrackMemoryAllocatedChange(
72 gpu::gles2::MemoryTracker::Pool pool
) OVERRIDE
{
73 tracking_group_
->TrackMemoryAllocatedChange(
74 old_size
, new_size
, pool
);
77 virtual bool EnsureGPUMemoryAvailable(size_t size_needed
) OVERRIDE
{
78 return tracking_group_
->EnsureGPUMemoryAvailable(size_needed
);
82 virtual ~GpuCommandBufferMemoryTracker() {
84 scoped_ptr
<GpuMemoryTrackingGroup
> tracking_group_
;
86 DISALLOW_COPY_AND_ASSIGN(GpuCommandBufferMemoryTracker
);
89 // FastSetActiveURL will shortcut the expensive call to SetActiveURL when the
91 void FastSetActiveURL(const GURL
& url
, size_t url_hash
) {
92 // Leave the previously set URL in the empty case -- empty URLs are given by
93 // WebKitPlatformSupportImpl::createOffscreenGraphicsContext3D. Hopefully the
94 // onscreen context URL was set previously and will show up even when a crash
95 // occurs during offscreen command processing.
98 static size_t g_last_url_hash
= 0;
99 if (url_hash
!= g_last_url_hash
) {
100 g_last_url_hash
= url_hash
;
101 GetContentClient()->SetActiveURL(url
);
105 // The first time polling a fence, delay some extra time to allow other
106 // stubs to process some work, or else the timing of the fences could
107 // allow a pattern of alternating fast and slow frames to occur.
108 const int64 kHandleMoreWorkPeriodMs
= 2;
109 const int64 kHandleMoreWorkPeriodBusyMs
= 1;
111 // Prevents idle work from being starved.
112 const int64 kMaxTimeSinceIdleMs
= 10;
116 GpuCommandBufferStub::GpuCommandBufferStub(
118 GpuCommandBufferStub
* share_group
,
119 const gfx::GLSurfaceHandle
& handle
,
120 gpu::gles2::MailboxManager
* mailbox_manager
,
121 gpu::gles2::ImageManager
* image_manager
,
122 const gfx::Size
& size
,
123 const gpu::gles2::DisallowedFeatures
& disallowed_features
,
124 const std::vector
<int32
>& attribs
,
125 gfx::GpuPreference gpu_preference
,
126 bool use_virtualized_gl_context
,
129 GpuWatchdog
* watchdog
,
131 const GURL
& active_url
)
135 disallowed_features_(disallowed_features
),
136 requested_attribs_(attribs
),
137 gpu_preference_(gpu_preference
),
138 use_virtualized_gl_context_(use_virtualized_gl_context
),
140 surface_id_(surface_id
),
142 last_flush_count_(0),
143 last_memory_allocation_valid_(false),
145 sync_point_wait_count_(0),
146 delayed_work_scheduled_(false),
147 previous_messages_processed_(0),
148 active_url_(active_url
),
149 total_gpu_memory_(0) {
150 active_url_hash_
= base::Hash(active_url
.possibly_invalid_spec());
151 FastSetActiveURL(active_url_
, active_url_hash_
);
153 gpu::gles2::ContextCreationAttribHelper attrib_parser
;
154 attrib_parser
.Parse(requested_attribs_
);
157 context_group_
= share_group
->context_group_
;
158 DCHECK(context_group_
->bind_generates_resource() ==
159 attrib_parser
.bind_generates_resource_
);
161 context_group_
= new gpu::gles2::ContextGroup(
164 new GpuCommandBufferMemoryTracker(channel
),
165 channel_
->gpu_channel_manager()->shader_translator_cache(),
167 attrib_parser
.bind_generates_resource_
);
170 use_virtualized_gl_context_
|=
171 context_group_
->feature_info()->workarounds().use_virtualized_gl_contexts
;
174 GpuCommandBufferStub::~GpuCommandBufferStub() {
177 GpuChannelManager
* gpu_channel_manager
= channel_
->gpu_channel_manager();
178 gpu_channel_manager
->Send(new GpuHostMsg_DestroyCommandBuffer(surface_id()));
181 GpuMemoryManager
* GpuCommandBufferStub::GetMemoryManager() const {
182 return channel()->gpu_channel_manager()->gpu_memory_manager();
185 bool GpuCommandBufferStub::OnMessageReceived(const IPC::Message
& message
) {
186 devtools_gpu_instrumentation::ScopedGpuTask
task(channel());
187 FastSetActiveURL(active_url_
, active_url_hash_
);
189 bool have_context
= false;
190 // Ensure the appropriate GL context is current before handling any IPC
191 // messages directed at the command buffer. This ensures that the message
192 // handler can assume that the context is current (not necessary for
193 // Echo, RetireSyncPoint, or WaitSyncPoint).
194 if (decoder_
.get() && message
.type() != GpuCommandBufferMsg_Echo::ID
&&
195 message
.type() != GpuCommandBufferMsg_WaitForTokenInRange::ID
&&
196 message
.type() != GpuCommandBufferMsg_WaitForGetOffsetInRange::ID
&&
197 message
.type() != GpuCommandBufferMsg_RetireSyncPoint::ID
&&
198 message
.type() != GpuCommandBufferMsg_SetLatencyInfo::ID
) {
204 // Always use IPC_MESSAGE_HANDLER_DELAY_REPLY for synchronous message handlers
205 // here. This is so the reply can be delayed if the scheduler is unscheduled.
207 IPC_BEGIN_MESSAGE_MAP(GpuCommandBufferStub
, message
)
208 IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuCommandBufferMsg_Initialize
,
210 IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuCommandBufferMsg_SetGetBuffer
,
212 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_ProduceFrontBuffer
,
213 OnProduceFrontBuffer
);
214 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_Echo
, OnEcho
);
215 IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuCommandBufferMsg_WaitForTokenInRange
,
216 OnWaitForTokenInRange
);
217 IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuCommandBufferMsg_WaitForGetOffsetInRange
,
218 OnWaitForGetOffsetInRange
);
219 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_AsyncFlush
, OnAsyncFlush
);
220 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_SetLatencyInfo
, OnSetLatencyInfo
);
221 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_Rescheduled
, OnRescheduled
);
222 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_RegisterTransferBuffer
,
223 OnRegisterTransferBuffer
);
224 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_DestroyTransferBuffer
,
225 OnDestroyTransferBuffer
);
226 IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuCommandBufferMsg_CreateVideoDecoder
,
227 OnCreateVideoDecoder
)
228 IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuCommandBufferMsg_CreateVideoEncoder
,
229 OnCreateVideoEncoder
)
230 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_SetSurfaceVisible
,
232 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_RetireSyncPoint
,
234 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_SignalSyncPoint
,
236 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_SignalQuery
,
239 GpuCommandBufferMsg_SetClientHasMemoryAllocationChangedCallback
,
240 OnSetClientHasMemoryAllocationChangedCallback
)
241 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_RegisterGpuMemoryBuffer
,
242 OnRegisterGpuMemoryBuffer
);
243 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_DestroyGpuMemoryBuffer
,
244 OnDestroyGpuMemoryBuffer
);
245 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_CreateStreamTexture
,
246 OnCreateStreamTexture
)
247 IPC_MESSAGE_UNHANDLED(handled
= false)
248 IPC_END_MESSAGE_MAP()
250 CheckCompleteWaits();
253 // Ensure that any delayed work that was created will be handled.
254 ScheduleDelayedWork(kHandleMoreWorkPeriodMs
);
261 bool GpuCommandBufferStub::Send(IPC::Message
* message
) {
262 return channel_
->Send(message
);
265 bool GpuCommandBufferStub::IsScheduled() {
266 return (!scheduler_
.get() || scheduler_
->IsScheduled());
269 bool GpuCommandBufferStub::HasMoreWork() {
270 return scheduler_
.get() && scheduler_
->HasMoreWork();
273 void GpuCommandBufferStub::PollWork() {
274 TRACE_EVENT0("gpu", "GpuCommandBufferStub::PollWork");
275 delayed_work_scheduled_
= false;
276 FastSetActiveURL(active_url_
, active_url_hash_
);
277 if (decoder_
.get() && !MakeCurrent())
281 bool fences_complete
= scheduler_
->PollUnscheduleFences();
282 // Perform idle work if all fences are complete.
283 if (fences_complete
) {
284 uint64 current_messages_processed
=
285 channel()->gpu_channel_manager()->MessagesProcessed();
286 // We're idle when no messages were processed or scheduled.
288 (previous_messages_processed_
== current_messages_processed
) &&
289 !channel()->gpu_channel_manager()->HandleMessagesScheduled();
290 if (!is_idle
&& !last_idle_time_
.is_null()) {
291 base::TimeDelta time_since_idle
= base::TimeTicks::Now() -
293 base::TimeDelta max_time_since_idle
=
294 base::TimeDelta::FromMilliseconds(kMaxTimeSinceIdleMs
);
296 // Force idle when it's been too long since last time we were idle.
297 if (time_since_idle
> max_time_since_idle
)
302 last_idle_time_
= base::TimeTicks::Now();
303 scheduler_
->PerformIdleWork();
307 ScheduleDelayedWork(kHandleMoreWorkPeriodBusyMs
);
310 bool GpuCommandBufferStub::HasUnprocessedCommands() {
311 if (command_buffer_
) {
312 gpu::CommandBuffer::State state
= command_buffer_
->GetLastState();
313 return state
.put_offset
!= state
.get_offset
&&
314 !gpu::error::IsError(state
.error
);
319 void GpuCommandBufferStub::ScheduleDelayedWork(int64 delay
) {
320 if (!HasMoreWork()) {
321 last_idle_time_
= base::TimeTicks();
325 if (delayed_work_scheduled_
)
327 delayed_work_scheduled_
= true;
329 // Idle when no messages are processed between now and when
330 // PollWork is called.
331 previous_messages_processed_
=
332 channel()->gpu_channel_manager()->MessagesProcessed();
333 if (last_idle_time_
.is_null())
334 last_idle_time_
= base::TimeTicks::Now();
336 // IsScheduled() returns true after passing all unschedule fences
337 // and this is when we can start performing idle work. Idle work
338 // is done synchronously so we can set delay to 0 and instead poll
339 // for more work at the rate idle work is performed. This also ensures
340 // that idle work is done as efficiently as possible without any
341 // unnecessary delays.
342 if (scheduler_
.get() &&
343 scheduler_
->IsScheduled() &&
344 scheduler_
->HasMoreIdleWork()) {
348 base::MessageLoop::current()->PostDelayedTask(
350 base::Bind(&GpuCommandBufferStub::PollWork
, AsWeakPtr()),
351 base::TimeDelta::FromMilliseconds(delay
));
354 void GpuCommandBufferStub::OnEcho(const IPC::Message
& message
) {
355 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnEcho");
356 Send(new IPC::Message(message
));
359 bool GpuCommandBufferStub::MakeCurrent() {
360 if (decoder_
->MakeCurrent())
362 DLOG(ERROR
) << "Context lost because MakeCurrent failed.";
363 command_buffer_
->SetContextLostReason(decoder_
->GetContextLostReason());
364 command_buffer_
->SetParseError(gpu::error::kLostContext
);
369 void GpuCommandBufferStub::Destroy() {
370 if (wait_for_token_
) {
371 Send(wait_for_token_
->reply
.release());
372 wait_for_token_
.reset();
374 if (wait_for_get_offset_
) {
375 Send(wait_for_get_offset_
->reply
.release());
376 wait_for_get_offset_
.reset();
378 if (handle_
.is_null() && !active_url_
.is_empty()) {
379 GpuChannelManager
* gpu_channel_manager
= channel_
->gpu_channel_manager();
380 gpu_channel_manager
->Send(new GpuHostMsg_DidDestroyOffscreenContext(
384 memory_manager_client_state_
.reset();
386 while (!sync_points_
.empty())
387 OnRetireSyncPoint(sync_points_
.front());
390 decoder_
->set_engine(NULL
);
392 // The scheduler has raw references to the decoder and the command buffer so
393 // destroy it before those.
396 bool have_context
= false;
397 if (decoder_
&& command_buffer_
&&
398 command_buffer_
->GetLastState().error
!= gpu::error::kLostContext
)
399 have_context
= decoder_
->MakeCurrent();
400 FOR_EACH_OBSERVER(DestructionObserver
,
401 destruction_observers_
,
402 OnWillDestroyStub());
405 decoder_
->Destroy(have_context
);
409 command_buffer_
.reset();
411 // Remove this after crbug.com/248395 is sorted out.
415 void GpuCommandBufferStub::OnInitializeFailed(IPC::Message
* reply_message
) {
417 GpuCommandBufferMsg_Initialize::WriteReplyParams(
418 reply_message
, false, gpu::Capabilities());
422 void GpuCommandBufferStub::OnInitialize(
423 base::SharedMemoryHandle shared_state_handle
,
424 IPC::Message
* reply_message
) {
425 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnInitialize");
426 DCHECK(!command_buffer_
.get());
428 scoped_ptr
<base::SharedMemory
> shared_state_shm(
429 new base::SharedMemory(shared_state_handle
, false));
431 command_buffer_
.reset(new gpu::CommandBufferService(
432 context_group_
->transfer_buffer_manager()));
434 bool result
= command_buffer_
->Initialize();
437 decoder_
.reset(::gpu::gles2::GLES2Decoder::Create(context_group_
.get()));
439 scheduler_
.reset(new gpu::GpuScheduler(command_buffer_
.get(),
442 if (preemption_flag_
.get())
443 scheduler_
->SetPreemptByFlag(preemption_flag_
);
445 decoder_
->set_engine(scheduler_
.get());
447 if (!handle_
.is_null()) {
448 #if defined(OS_MACOSX) || defined(UI_COMPOSITOR_IMAGE_TRANSPORT)
450 LOG(ERROR
) << "No software support.";
451 OnInitializeFailed(reply_message
);
456 surface_
= ImageTransportSurface::CreateSurface(
457 channel_
->gpu_channel_manager(),
461 GpuChannelManager
* manager
= channel_
->gpu_channel_manager();
462 surface_
= manager
->GetDefaultOffscreenSurface();
465 if (!surface_
.get()) {
466 DLOG(ERROR
) << "Failed to create surface.";
467 OnInitializeFailed(reply_message
);
471 scoped_refptr
<gfx::GLContext
> context
;
472 if (use_virtualized_gl_context_
&& channel_
->share_group()) {
473 context
= channel_
->share_group()->GetSharedContext();
474 if (!context
.get()) {
475 context
= gfx::GLContext::CreateGLContext(
476 channel_
->share_group(),
477 channel_
->gpu_channel_manager()->GetDefaultOffscreenSurface(),
479 if (!context
.get()) {
480 DLOG(ERROR
) << "Failed to create shared context for virtualization.";
481 OnInitializeFailed(reply_message
);
484 channel_
->share_group()->SetSharedContext(context
.get());
486 // This should be a non-virtual GL context.
487 DCHECK(context
->GetHandle());
488 context
= new gpu::GLContextVirtual(
489 channel_
->share_group(), context
.get(), decoder_
->AsWeakPtr());
490 if (!context
->Initialize(surface_
.get(), gpu_preference_
)) {
491 // TODO(sievers): The real context created above for the default
492 // offscreen surface might not be compatible with this surface.
493 // Need to adjust at least GLX to be able to create the initial context
494 // with a config that is compatible with onscreen and offscreen surfaces.
497 DLOG(ERROR
) << "Failed to initialize virtual GL context.";
498 OnInitializeFailed(reply_message
);
502 if (!context
.get()) {
503 context
= gfx::GLContext::CreateGLContext(
504 channel_
->share_group(), surface_
.get(), gpu_preference_
);
506 if (!context
.get()) {
507 DLOG(ERROR
) << "Failed to create context.";
508 OnInitializeFailed(reply_message
);
512 if (!context
->MakeCurrent(surface_
.get())) {
513 LOG(ERROR
) << "Failed to make context current.";
514 OnInitializeFailed(reply_message
);
518 if (!context
->GetGLStateRestorer()) {
519 context
->SetGLStateRestorer(
520 new gpu::GLStateRestorerImpl(decoder_
->AsWeakPtr()));
523 if (!context
->GetTotalGpuMemory(&total_gpu_memory_
))
524 total_gpu_memory_
= 0;
526 if (!context_group_
->has_program_cache()) {
527 context_group_
->set_program_cache(
528 channel_
->gpu_channel_manager()->program_cache());
531 // Initialize the decoder with either the view or pbuffer GLContext.
532 if (!decoder_
->Initialize(surface_
,
536 disallowed_features_
,
537 requested_attribs_
)) {
538 DLOG(ERROR
) << "Failed to initialize decoder.";
539 OnInitializeFailed(reply_message
);
543 gpu_control_service_
.reset(
544 new gpu::GpuControlService(context_group_
->image_manager(), NULL
));
546 if (CommandLine::ForCurrentProcess()->HasSwitch(
547 switches::kEnableGPUServiceLogging
)) {
548 decoder_
->set_log_commands(true);
551 decoder_
->GetLogger()->SetMsgCallback(
552 base::Bind(&GpuCommandBufferStub::SendConsoleMessage
,
553 base::Unretained(this)));
554 decoder_
->SetShaderCacheCallback(
555 base::Bind(&GpuCommandBufferStub::SendCachedShader
,
556 base::Unretained(this)));
557 decoder_
->SetWaitSyncPointCallback(
558 base::Bind(&GpuCommandBufferStub::OnWaitSyncPoint
,
559 base::Unretained(this)));
561 command_buffer_
->SetPutOffsetChangeCallback(
562 base::Bind(&GpuCommandBufferStub::PutChanged
, base::Unretained(this)));
563 command_buffer_
->SetGetBufferChangeCallback(
564 base::Bind(&gpu::GpuScheduler::SetGetBuffer
,
565 base::Unretained(scheduler_
.get())));
566 command_buffer_
->SetParseErrorCallback(
567 base::Bind(&GpuCommandBufferStub::OnParseError
, base::Unretained(this)));
568 scheduler_
->SetSchedulingChangedCallback(
569 base::Bind(&GpuChannel::StubSchedulingChanged
,
570 base::Unretained(channel_
)));
573 scheduler_
->SetCommandProcessedCallback(
574 base::Bind(&GpuCommandBufferStub::OnCommandProcessed
,
575 base::Unretained(this)));
578 const size_t kSharedStateSize
= sizeof(gpu::CommandBufferSharedState
);
579 if (!shared_state_shm
->Map(kSharedStateSize
)) {
580 DLOG(ERROR
) << "Failed to map shared state buffer.";
581 OnInitializeFailed(reply_message
);
584 command_buffer_
->SetSharedStateBuffer(gpu::MakeBackingFromSharedMemory(
585 shared_state_shm
.Pass(), kSharedStateSize
));
587 gpu::Capabilities capabilities
= decoder_
->GetCapabilities();
588 capabilities
.future_sync_points
= channel_
->allow_future_sync_points();
590 GpuCommandBufferMsg_Initialize::WriteReplyParams(
591 reply_message
, true, capabilities
);
594 if (handle_
.is_null() && !active_url_
.is_empty()) {
595 GpuChannelManager
* gpu_channel_manager
= channel_
->gpu_channel_manager();
596 gpu_channel_manager
->Send(new GpuHostMsg_DidCreateOffscreenContext(
601 void GpuCommandBufferStub::OnSetLatencyInfo(
602 const std::vector
<ui::LatencyInfo
>& latency_info
) {
603 if (!ui::LatencyInfo::Verify(latency_info
,
604 "GpuCommandBufferStub::OnSetLatencyInfo"))
606 if (!latency_info_callback_
.is_null())
607 latency_info_callback_
.Run(latency_info
);
610 void GpuCommandBufferStub::OnCreateStreamTexture(
611 uint32 texture_id
, int32 stream_id
, bool* succeeded
) {
612 #if defined(OS_ANDROID)
613 *succeeded
= StreamTexture::Create(this, texture_id
, stream_id
);
619 void GpuCommandBufferStub::SetLatencyInfoCallback(
620 const LatencyInfoCallback
& callback
) {
621 latency_info_callback_
= callback
;
624 int32
GpuCommandBufferStub::GetRequestedAttribute(int attr
) const {
625 // The command buffer is pairs of enum, value
626 // search for the requested attribute, return the value.
627 for (std::vector
<int32
>::const_iterator it
= requested_attribs_
.begin();
628 it
!= requested_attribs_
.end(); ++it
) {
636 void GpuCommandBufferStub::OnSetGetBuffer(int32 shm_id
,
637 IPC::Message
* reply_message
) {
638 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnSetGetBuffer");
640 command_buffer_
->SetGetBuffer(shm_id
);
644 void GpuCommandBufferStub::OnProduceFrontBuffer(const gpu::Mailbox
& mailbox
) {
645 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnProduceFrontBuffer");
647 LOG(ERROR
) << "Can't produce front buffer before initialization.";
651 decoder_
->ProduceFrontBuffer(mailbox
);
654 void GpuCommandBufferStub::OnParseError() {
655 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnParseError");
656 DCHECK(command_buffer_
.get());
657 gpu::CommandBuffer::State state
= command_buffer_
->GetLastState();
658 IPC::Message
* msg
= new GpuCommandBufferMsg_Destroyed(
659 route_id_
, state
.context_lost_reason
);
660 msg
->set_unblock(true);
663 // Tell the browser about this context loss as well, so it can
664 // determine whether client APIs like WebGL need to be immediately
665 // blocked from automatically running.
666 GpuChannelManager
* gpu_channel_manager
= channel_
->gpu_channel_manager();
667 gpu_channel_manager
->Send(new GpuHostMsg_DidLoseContext(
668 handle_
.is_null(), state
.context_lost_reason
, active_url_
));
673 void GpuCommandBufferStub::OnWaitForTokenInRange(int32 start
,
675 IPC::Message
* reply_message
) {
676 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnWaitForTokenInRange");
677 DCHECK(command_buffer_
.get());
680 LOG(ERROR
) << "Got WaitForToken command while currently waiting for token.";
682 make_scoped_ptr(new WaitForCommandState(start
, end
, reply_message
));
683 CheckCompleteWaits();
686 void GpuCommandBufferStub::OnWaitForGetOffsetInRange(
689 IPC::Message
* reply_message
) {
690 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnWaitForGetOffsetInRange");
691 DCHECK(command_buffer_
.get());
693 if (wait_for_get_offset_
) {
695 << "Got WaitForGetOffset command while currently waiting for offset.";
697 wait_for_get_offset_
=
698 make_scoped_ptr(new WaitForCommandState(start
, end
, reply_message
));
699 CheckCompleteWaits();
702 void GpuCommandBufferStub::CheckCompleteWaits() {
703 if (wait_for_token_
|| wait_for_get_offset_
) {
704 gpu::CommandBuffer::State state
= command_buffer_
->GetLastState();
705 if (wait_for_token_
&&
706 (gpu::CommandBuffer::InRange(
707 wait_for_token_
->start
, wait_for_token_
->end
, state
.token
) ||
708 state
.error
!= gpu::error::kNoError
)) {
710 GpuCommandBufferMsg_WaitForTokenInRange::WriteReplyParams(
711 wait_for_token_
->reply
.get(), state
);
712 Send(wait_for_token_
->reply
.release());
713 wait_for_token_
.reset();
715 if (wait_for_get_offset_
&&
716 (gpu::CommandBuffer::InRange(wait_for_get_offset_
->start
,
717 wait_for_get_offset_
->end
,
719 state
.error
!= gpu::error::kNoError
)) {
721 GpuCommandBufferMsg_WaitForGetOffsetInRange::WriteReplyParams(
722 wait_for_get_offset_
->reply
.get(), state
);
723 Send(wait_for_get_offset_
->reply
.release());
724 wait_for_get_offset_
.reset();
729 void GpuCommandBufferStub::OnAsyncFlush(int32 put_offset
, uint32 flush_count
) {
731 "gpu", "GpuCommandBufferStub::OnAsyncFlush", "put_offset", put_offset
);
732 DCHECK(command_buffer_
.get());
733 if (flush_count
- last_flush_count_
< 0x8000000U
) {
734 last_flush_count_
= flush_count
;
735 command_buffer_
->Flush(put_offset
);
737 // We received this message out-of-order. This should not happen but is here
738 // to catch regressions. Ignore the message.
739 NOTREACHED() << "Received a Flush message out-of-order";
745 void GpuCommandBufferStub::OnRescheduled() {
746 gpu::CommandBuffer::State pre_state
= command_buffer_
->GetLastState();
747 command_buffer_
->Flush(pre_state
.put_offset
);
748 gpu::CommandBuffer::State post_state
= command_buffer_
->GetLastState();
750 if (pre_state
.get_offset
!= post_state
.get_offset
)
754 void GpuCommandBufferStub::OnRegisterTransferBuffer(
756 base::SharedMemoryHandle transfer_buffer
,
758 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnRegisterTransferBuffer");
760 // Take ownership of the memory and map it into this process.
761 // This validates the size.
762 scoped_ptr
<base::SharedMemory
> shared_memory(
763 new base::SharedMemory(transfer_buffer
, false));
764 if (!shared_memory
->Map(size
)) {
765 DVLOG(0) << "Failed to map shared memory.";
769 if (command_buffer_
) {
770 command_buffer_
->RegisterTransferBuffer(
771 id
, gpu::MakeBackingFromSharedMemory(shared_memory
.Pass(), size
));
775 void GpuCommandBufferStub::OnDestroyTransferBuffer(int32 id
) {
776 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnDestroyTransferBuffer");
779 command_buffer_
->DestroyTransferBuffer(id
);
782 void GpuCommandBufferStub::OnCommandProcessed() {
784 watchdog_
->CheckArmed();
787 void GpuCommandBufferStub::ReportState() { command_buffer_
->UpdateState(); }
789 void GpuCommandBufferStub::PutChanged() {
790 FastSetActiveURL(active_url_
, active_url_hash_
);
791 scheduler_
->PutChanged();
794 void GpuCommandBufferStub::OnCreateVideoDecoder(
795 media::VideoCodecProfile profile
,
796 int32 decoder_route_id
,
797 IPC::Message
* reply_message
) {
798 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnCreateVideoDecoder");
799 GpuVideoDecodeAccelerator
* decoder
= new GpuVideoDecodeAccelerator(
800 decoder_route_id
, this, channel_
->io_message_loop());
801 decoder
->Initialize(profile
, reply_message
);
802 // decoder is registered as a DestructionObserver of this stub and will
803 // self-delete during destruction of this stub.
806 void GpuCommandBufferStub::OnCreateVideoEncoder(
807 media::VideoFrame::Format input_format
,
808 const gfx::Size
& input_visible_size
,
809 media::VideoCodecProfile output_profile
,
810 uint32 initial_bitrate
,
811 int32 encoder_route_id
,
812 IPC::Message
* reply_message
) {
813 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnCreateVideoEncoder");
814 GpuVideoEncodeAccelerator
* encoder
=
815 new GpuVideoEncodeAccelerator(encoder_route_id
, this);
816 encoder
->Initialize(input_format
,
821 // encoder is registered as a DestructionObserver of this stub and will
822 // self-delete during destruction of this stub.
825 void GpuCommandBufferStub::OnSetSurfaceVisible(bool visible
) {
826 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnSetSurfaceVisible");
827 if (memory_manager_client_state_
)
828 memory_manager_client_state_
->SetVisible(visible
);
831 void GpuCommandBufferStub::AddSyncPoint(uint32 sync_point
) {
832 sync_points_
.push_back(sync_point
);
835 void GpuCommandBufferStub::OnRetireSyncPoint(uint32 sync_point
) {
836 DCHECK(!sync_points_
.empty() && sync_points_
.front() == sync_point
);
837 sync_points_
.pop_front();
838 if (context_group_
->mailbox_manager()->UsesSync() && MakeCurrent())
839 context_group_
->mailbox_manager()->PushTextureUpdates();
840 GpuChannelManager
* manager
= channel_
->gpu_channel_manager();
841 manager
->sync_point_manager()->RetireSyncPoint(sync_point
);
844 bool GpuCommandBufferStub::OnWaitSyncPoint(uint32 sync_point
) {
847 GpuChannelManager
* manager
= channel_
->gpu_channel_manager();
848 if (manager
->sync_point_manager()->IsSyncPointRetired(sync_point
))
851 if (sync_point_wait_count_
== 0) {
852 TRACE_EVENT_ASYNC_BEGIN1("gpu", "WaitSyncPoint", this,
853 "GpuCommandBufferStub", this);
855 scheduler_
->SetScheduled(false);
856 ++sync_point_wait_count_
;
857 manager
->sync_point_manager()->AddSyncPointCallback(
859 base::Bind(&GpuCommandBufferStub::OnSyncPointRetired
,
861 return scheduler_
->IsScheduled();
864 void GpuCommandBufferStub::OnSyncPointRetired() {
865 --sync_point_wait_count_
;
866 if (sync_point_wait_count_
== 0) {
867 TRACE_EVENT_ASYNC_END1("gpu", "WaitSyncPoint", this,
868 "GpuCommandBufferStub", this);
870 scheduler_
->SetScheduled(true);
873 void GpuCommandBufferStub::OnSignalSyncPoint(uint32 sync_point
, uint32 id
) {
874 GpuChannelManager
* manager
= channel_
->gpu_channel_manager();
875 manager
->sync_point_manager()->AddSyncPointCallback(
877 base::Bind(&GpuCommandBufferStub::OnSignalSyncPointAck
,
882 void GpuCommandBufferStub::OnSignalSyncPointAck(uint32 id
) {
883 Send(new GpuCommandBufferMsg_SignalSyncPointAck(route_id_
, id
));
886 void GpuCommandBufferStub::OnSignalQuery(uint32 query_id
, uint32 id
) {
888 gpu::gles2::QueryManager
* query_manager
= decoder_
->GetQueryManager();
890 gpu::gles2::QueryManager::Query
* query
=
891 query_manager
->GetQuery(query_id
);
894 base::Bind(&GpuCommandBufferStub::OnSignalSyncPointAck
,
901 // Something went wrong, run callback immediately.
902 OnSignalSyncPointAck(id
);
906 void GpuCommandBufferStub::OnSetClientHasMemoryAllocationChangedCallback(
910 "GpuCommandBufferStub::OnSetClientHasMemoryAllocationChangedCallback");
912 if (!memory_manager_client_state_
) {
913 memory_manager_client_state_
.reset(GetMemoryManager()->CreateClientState(
914 this, surface_id_
!= 0, true));
917 memory_manager_client_state_
.reset();
921 void GpuCommandBufferStub::OnRegisterGpuMemoryBuffer(
923 gfx::GpuMemoryBufferHandle gpu_memory_buffer
,
926 uint32 internalformat
) {
927 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnRegisterGpuMemoryBuffer");
928 #if defined(OS_ANDROID)
929 // Verify that renderer is not trying to use a surface texture it doesn't own.
930 if (gpu_memory_buffer
.type
== gfx::SURFACE_TEXTURE_BUFFER
&&
931 gpu_memory_buffer
.surface_texture_id
.secondary_id
!=
932 channel()->client_id()) {
933 LOG(ERROR
) << "Illegal surface texture ID for renderer.";
937 if (gpu_control_service_
) {
938 gpu_control_service_
->RegisterGpuMemoryBuffer(
939 id
, gpu_memory_buffer
, width
, height
, internalformat
);
943 void GpuCommandBufferStub::OnDestroyGpuMemoryBuffer(int32 id
) {
944 TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnDestroyGpuMemoryBuffer");
945 if (gpu_control_service_
)
946 gpu_control_service_
->UnregisterGpuMemoryBuffer(id
);
949 void GpuCommandBufferStub::SendConsoleMessage(
951 const std::string
& message
) {
952 GPUCommandBufferConsoleMessage console_message
;
953 console_message
.id
= id
;
954 console_message
.message
= message
;
955 IPC::Message
* msg
= new GpuCommandBufferMsg_ConsoleMsg(
956 route_id_
, console_message
);
957 msg
->set_unblock(true);
961 void GpuCommandBufferStub::SendCachedShader(
962 const std::string
& key
, const std::string
& shader
) {
963 channel_
->CacheShader(key
, shader
);
966 void GpuCommandBufferStub::AddDestructionObserver(
967 DestructionObserver
* observer
) {
968 destruction_observers_
.AddObserver(observer
);
971 void GpuCommandBufferStub::RemoveDestructionObserver(
972 DestructionObserver
* observer
) {
973 destruction_observers_
.RemoveObserver(observer
);
976 void GpuCommandBufferStub::SetPreemptByFlag(
977 scoped_refptr
<gpu::PreemptionFlag
> flag
) {
978 preemption_flag_
= flag
;
980 scheduler_
->SetPreemptByFlag(preemption_flag_
);
983 bool GpuCommandBufferStub::GetTotalGpuMemory(uint64
* bytes
) {
984 *bytes
= total_gpu_memory_
;
985 return !!total_gpu_memory_
;
988 gfx::Size
GpuCommandBufferStub::GetSurfaceSize() const {
991 return surface_
->GetSize();
994 gpu::gles2::MemoryTracker
* GpuCommandBufferStub::GetMemoryTracker() const {
995 return context_group_
->memory_tracker();
998 void GpuCommandBufferStub::SetMemoryAllocation(
999 const gpu::MemoryAllocation
& allocation
) {
1000 if (!last_memory_allocation_valid_
||
1001 !allocation
.Equals(last_memory_allocation_
)) {
1002 Send(new GpuCommandBufferMsg_SetMemoryAllocation(
1003 route_id_
, allocation
));
1006 last_memory_allocation_valid_
= true;
1007 last_memory_allocation_
= allocation
;
1010 void GpuCommandBufferStub::SuggestHaveFrontBuffer(
1011 bool suggest_have_frontbuffer
) {
1012 // This can be called outside of OnMessageReceived, so the context needs
1013 // to be made current before calling methods on the surface.
1014 if (surface_
.get() && MakeCurrent())
1015 surface_
->SetFrontbufferAllocation(suggest_have_frontbuffer
);
1018 bool GpuCommandBufferStub::CheckContextLost() {
1019 DCHECK(command_buffer_
);
1020 gpu::CommandBuffer::State state
= command_buffer_
->GetLastState();
1021 bool was_lost
= state
.error
== gpu::error::kLostContext
;
1022 // Lose all other contexts if the reset was triggered by the robustness
1023 // extension instead of being synthetic.
1024 if (was_lost
&& decoder_
&& decoder_
->WasContextLostByRobustnessExtension() &&
1025 (gfx::GLContext::LosesAllContextsOnContextLost() ||
1026 use_virtualized_gl_context_
))
1027 channel_
->LoseAllContexts();
1028 CheckCompleteWaits();
1032 void GpuCommandBufferStub::MarkContextLost() {
1033 if (!command_buffer_
||
1034 command_buffer_
->GetLastState().error
== gpu::error::kLostContext
)
1037 command_buffer_
->SetContextLostReason(gpu::error::kUnknown
);
1039 decoder_
->LoseContext(GL_UNKNOWN_CONTEXT_RESET_ARB
);
1040 command_buffer_
->SetParseError(gpu::error::kLostContext
);
1043 uint64
GpuCommandBufferStub::GetMemoryUsage() const {
1044 return GetMemoryManager()->GetClientMemoryUsage(this);
1047 } // namespace content