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.
5 #include "content/common/gpu/client/command_buffer_proxy_impl.h"
7 #include "base/callback.h"
8 #include "base/debug/trace_event.h"
9 #include "base/logging.h"
10 #include "base/memory/shared_memory.h"
11 #include "base/stl_util.h"
12 #include "content/common/child_process_messages.h"
13 #include "content/common/gpu/client/gpu_channel_host.h"
14 #include "content/common/gpu/client/gpu_video_decode_accelerator_host.h"
15 #include "content/common/gpu/gpu_messages.h"
16 #include "content/common/view_messages.h"
17 #include "gpu/command_buffer/common/cmd_buffer_common.h"
18 #include "gpu/command_buffer/common/command_buffer_shared.h"
19 #include "gpu/command_buffer/common/gpu_memory_allocation.h"
20 #include "ui/gfx/size.h"
24 CommandBufferProxyImpl::CommandBufferProxyImpl(
25 GpuChannelHost* channel,
34 CommandBufferProxyImpl::~CommandBufferProxyImpl() {
35 FOR_EACH_OBSERVER(DeletionObserver,
39 // Delete all the locally cached shared memory objects, closing the handle
41 for (TransferBufferMap::iterator it = transfer_buffers_.begin();
42 it != transfer_buffers_.end();
44 delete it->second.shared_memory;
45 it->second.shared_memory = NULL;
49 bool CommandBufferProxyImpl::OnMessageReceived(const IPC::Message& message) {
51 IPC_BEGIN_MESSAGE_MAP(CommandBufferProxyImpl, message)
52 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_Destroyed, OnDestroyed);
53 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_EchoAck, OnEchoAck);
54 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_ConsoleMsg, OnConsoleMessage);
55 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_SetMemoryAllocation,
56 OnSetMemoryAllocation);
57 IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_SignalSyncPointAck,
58 OnSignalSyncPointAck);
59 IPC_MESSAGE_UNHANDLED(handled = false)
66 void CommandBufferProxyImpl::OnChannelError() {
67 OnDestroyed(gpu::error::kUnknown);
70 void CommandBufferProxyImpl::OnDestroyed(gpu::error::ContextLostReason reason) {
71 // Prevent any further messages from being sent.
74 // When the client sees that the context is lost, they should delete this
75 // CommandBufferProxyImpl and create a new one.
76 last_state_.error = gpu::error::kLostContext;
77 last_state_.context_lost_reason = reason;
79 if (!channel_error_callback_.is_null()) {
80 channel_error_callback_.Run();
81 // Avoid calling the error callback more than once.
82 channel_error_callback_.Reset();
86 void CommandBufferProxyImpl::OnEchoAck() {
87 DCHECK(!echo_tasks_.empty());
88 base::Closure callback = echo_tasks_.front();
93 void CommandBufferProxyImpl::OnConsoleMessage(
94 const GPUCommandBufferConsoleMessage& message) {
95 if (!console_message_callback_.is_null()) {
96 console_message_callback_.Run(message.message, message.id);
100 void CommandBufferProxyImpl::SetMemoryAllocationChangedCallback(
101 const MemoryAllocationChangedCallback& callback) {
102 if (last_state_.error != gpu::error::kNoError)
105 memory_allocation_changed_callback_ = callback;
106 Send(new GpuCommandBufferMsg_SetClientHasMemoryAllocationChangedCallback(
107 route_id_, !memory_allocation_changed_callback_.is_null()));
110 void CommandBufferProxyImpl::AddDeletionObserver(DeletionObserver* observer) {
111 deletion_observers_.AddObserver(observer);
114 void CommandBufferProxyImpl::RemoveDeletionObserver(
115 DeletionObserver* observer) {
116 deletion_observers_.RemoveObserver(observer);
119 void CommandBufferProxyImpl::OnSetMemoryAllocation(
120 const gpu::MemoryAllocation& allocation) {
121 if (!memory_allocation_changed_callback_.is_null())
122 memory_allocation_changed_callback_.Run(allocation);
125 void CommandBufferProxyImpl::OnSignalSyncPointAck(uint32 id) {
126 SignalTaskMap::iterator it = signal_tasks_.find(id);
127 DCHECK(it != signal_tasks_.end());
128 base::Closure callback = it->second;
129 signal_tasks_.erase(it);
133 void CommandBufferProxyImpl::SetChannelErrorCallback(
134 const base::Closure& callback) {
135 channel_error_callback_ = callback;
138 bool CommandBufferProxyImpl::Initialize() {
139 shared_state_shm_.reset(channel_->factory()->AllocateSharedMemory(
140 sizeof(*shared_state())).release());
141 if (!shared_state_shm_)
144 if (!shared_state_shm_->Map(sizeof(*shared_state())))
147 shared_state()->Initialize();
149 // This handle is owned by the GPU process and must be passed to it or it
150 // will leak. In otherwords, do not early out on error between here and the
151 // sending of the Initialize IPC below.
152 base::SharedMemoryHandle handle =
153 channel_->ShareToGpuProcess(shared_state_shm_->handle());
154 if (!base::SharedMemory::IsHandleValid(handle))
158 if (!Send(new GpuCommandBufferMsg_Initialize(
159 route_id_, handle, &result, &capabilities_))) {
160 LOG(ERROR) << "Could not send GpuCommandBufferMsg_Initialize.";
165 LOG(ERROR) << "Failed to initialize command buffer service.";
169 capabilities_.map_image = true;
174 gpu::CommandBuffer::State CommandBufferProxyImpl::GetState() {
175 // Send will flag state with lost context if IPC fails.
176 if (last_state_.error == gpu::error::kNoError) {
177 gpu::CommandBuffer::State state;
178 if (Send(new GpuCommandBufferMsg_GetState(route_id_, &state)))
179 OnUpdateState(state);
186 gpu::CommandBuffer::State CommandBufferProxyImpl::GetLastState() {
190 int32 CommandBufferProxyImpl::GetLastToken() {
192 return last_state_.token;
195 void CommandBufferProxyImpl::Flush(int32 put_offset) {
196 if (last_state_.error != gpu::error::kNoError)
200 "CommandBufferProxyImpl::Flush",
204 if (last_put_offset_ == put_offset)
207 last_put_offset_ = put_offset;
209 Send(new GpuCommandBufferMsg_AsyncFlush(route_id_,
214 void CommandBufferProxyImpl::SetLatencyInfo(
215 const std::vector<ui::LatencyInfo>& latency_info) {
216 if (last_state_.error != gpu::error::kNoError)
218 Send(new GpuCommandBufferMsg_SetLatencyInfo(route_id_, latency_info));
221 gpu::CommandBuffer::State CommandBufferProxyImpl::FlushSync(
223 int32 last_known_get) {
224 TRACE_EVENT1("gpu", "CommandBufferProxyImpl::FlushSync", "put_offset",
228 if (last_known_get == last_state_.get_offset) {
229 // Send will flag state with lost context if IPC fails.
230 if (last_state_.error == gpu::error::kNoError) {
231 gpu::CommandBuffer::State state;
232 if (Send(new GpuCommandBufferMsg_GetStateFast(route_id_,
234 OnUpdateState(state);
242 void CommandBufferProxyImpl::SetGetBuffer(int32 shm_id) {
243 if (last_state_.error != gpu::error::kNoError)
246 Send(new GpuCommandBufferMsg_SetGetBuffer(route_id_, shm_id));
247 last_put_offset_ = -1;
250 void CommandBufferProxyImpl::SetGetOffset(int32 get_offset) {
251 // Not implemented in proxy.
255 gpu::Buffer CommandBufferProxyImpl::CreateTransferBuffer(size_t size,
259 if (last_state_.error != gpu::error::kNoError)
260 return gpu::Buffer();
262 int32 new_id = channel_->ReserveTransferBufferId();
263 DCHECK(transfer_buffers_.find(new_id) == transfer_buffers_.end());
265 scoped_ptr<base::SharedMemory> shared_memory(
266 channel_->factory()->AllocateSharedMemory(size));
268 return gpu::Buffer();
270 DCHECK(!shared_memory->memory());
271 if (!shared_memory->Map(size))
272 return gpu::Buffer();
274 // This handle is owned by the GPU process and must be passed to it or it
275 // will leak. In otherwords, do not early out on error between here and the
276 // sending of the RegisterTransferBuffer IPC below.
277 base::SharedMemoryHandle handle =
278 channel_->ShareToGpuProcess(shared_memory->handle());
279 if (!base::SharedMemory::IsHandleValid(handle))
280 return gpu::Buffer();
282 if (!Send(new GpuCommandBufferMsg_RegisterTransferBuffer(route_id_,
286 return gpu::Buffer();
291 buffer.ptr = shared_memory->memory();
293 buffer.shared_memory = shared_memory.release();
294 transfer_buffers_[new_id] = buffer;
299 void CommandBufferProxyImpl::DestroyTransferBuffer(int32 id) {
300 if (last_state_.error != gpu::error::kNoError)
303 // Remove the transfer buffer from the client side cache.
304 TransferBufferMap::iterator it = transfer_buffers_.find(id);
305 if (it != transfer_buffers_.end()) {
306 delete it->second.shared_memory;
307 transfer_buffers_.erase(it);
310 Send(new GpuCommandBufferMsg_DestroyTransferBuffer(route_id_, id));
313 gpu::Buffer CommandBufferProxyImpl::GetTransferBuffer(int32 id) {
314 if (last_state_.error != gpu::error::kNoError)
315 return gpu::Buffer();
317 // Check local cache to see if there is already a client side shared memory
318 // object for this id.
319 TransferBufferMap::iterator it = transfer_buffers_.find(id);
320 if (it != transfer_buffers_.end()) {
324 // Assuming we are in the renderer process, the service is responsible for
325 // duplicating the handle. This might not be true for NaCl.
326 base::SharedMemoryHandle handle = base::SharedMemoryHandle();
328 if (!Send(new GpuCommandBufferMsg_GetTransferBuffer(route_id_,
332 return gpu::Buffer();
335 // Cache the transfer buffer shared memory object client side.
336 scoped_ptr<base::SharedMemory> shared_memory(
337 new base::SharedMemory(handle, false));
339 // Map the shared memory on demand.
340 if (!shared_memory->memory()) {
341 if (!shared_memory->Map(size))
342 return gpu::Buffer();
346 buffer.ptr = shared_memory->memory();
348 buffer.shared_memory = shared_memory.release();
349 transfer_buffers_[id] = buffer;
354 void CommandBufferProxyImpl::SetToken(int32 token) {
355 // Not implemented in proxy.
359 void CommandBufferProxyImpl::SetParseError(
360 gpu::error::Error error) {
361 // Not implemented in proxy.
365 void CommandBufferProxyImpl::SetContextLostReason(
366 gpu::error::ContextLostReason reason) {
367 // Not implemented in proxy.
371 gpu::Capabilities CommandBufferProxyImpl::GetCapabilities() {
372 return capabilities_;
375 gfx::GpuMemoryBuffer* CommandBufferProxyImpl::CreateGpuMemoryBuffer(
378 unsigned internalformat,
382 if (last_state_.error != gpu::error::kNoError)
385 int32 new_id = channel_->ReserveGpuMemoryBufferId();
386 DCHECK(gpu_memory_buffers_.find(new_id) == gpu_memory_buffers_.end());
388 scoped_ptr<gfx::GpuMemoryBuffer> gpu_memory_buffer(
389 channel_->factory()->AllocateGpuMemoryBuffer(width,
392 if (!gpu_memory_buffer)
395 DCHECK(GpuChannelHost::IsValidGpuMemoryBuffer(
396 gpu_memory_buffer->GetHandle()));
398 // This handle is owned by the GPU process and must be passed to it or it
399 // will leak. In otherwords, do not early out on error between here and the
400 // sending of the RegisterGpuMemoryBuffer IPC below.
401 gfx::GpuMemoryBufferHandle handle =
402 channel_->ShareGpuMemoryBufferToGpuProcess(
403 gpu_memory_buffer->GetHandle());
405 if (!Send(new GpuCommandBufferMsg_RegisterGpuMemoryBuffer(
416 gpu_memory_buffers_[new_id] = gpu_memory_buffer.release();
417 return gpu_memory_buffers_[new_id];
420 void CommandBufferProxyImpl::DestroyGpuMemoryBuffer(int32 id) {
421 if (last_state_.error != gpu::error::kNoError)
424 // Remove the gpu memory buffer from the client side cache.
425 GpuMemoryBufferMap::iterator it = gpu_memory_buffers_.find(id);
426 if (it != gpu_memory_buffers_.end()) {
428 gpu_memory_buffers_.erase(it);
431 Send(new GpuCommandBufferMsg_DestroyGpuMemoryBuffer(route_id_, id));
434 int CommandBufferProxyImpl::GetRouteID() const {
438 void CommandBufferProxyImpl::Echo(const base::Closure& callback) {
439 if (last_state_.error != gpu::error::kNoError) {
443 if (!Send(new GpuCommandBufferMsg_Echo(
444 route_id_, GpuCommandBufferMsg_EchoAck(route_id_)))) {
448 echo_tasks_.push(callback);
451 uint32 CommandBufferProxyImpl::CreateStreamTexture(uint32 texture_id) {
452 if (last_state_.error != gpu::error::kNoError)
456 Send(new GpuCommandBufferMsg_CreateStreamTexture(
457 route_id_, texture_id, &stream_id));
461 uint32 CommandBufferProxyImpl::InsertSyncPoint() {
462 if (last_state_.error != gpu::error::kNoError)
465 uint32 sync_point = 0;
466 Send(new GpuCommandBufferMsg_InsertSyncPoint(route_id_, &sync_point));
470 void CommandBufferProxyImpl::SignalSyncPoint(uint32 sync_point,
471 const base::Closure& callback) {
472 if (last_state_.error != gpu::error::kNoError)
475 uint32 signal_id = next_signal_id_++;
476 if (!Send(new GpuCommandBufferMsg_SignalSyncPoint(route_id_,
482 signal_tasks_.insert(std::make_pair(signal_id, callback));
485 void CommandBufferProxyImpl::SignalQuery(uint32 query,
486 const base::Closure& callback) {
487 if (last_state_.error != gpu::error::kNoError)
490 // Signal identifiers are hidden, so nobody outside of this class will see
491 // them. (And thus, they cannot save them.) The IDs themselves only last
492 // until the callback is invoked, which will happen as soon as the GPU
493 // catches upwith the command buffer.
494 // A malicious caller trying to create a collision by making next_signal_id
495 // would have to make calls at an astounding rate (300B/s) and even if they
496 // could do that, all they would do is to prevent some callbacks from getting
497 // called, leading to stalled threads and/or memory leaks.
498 uint32 signal_id = next_signal_id_++;
499 if (!Send(new GpuCommandBufferMsg_SignalQuery(route_id_,
505 signal_tasks_.insert(std::make_pair(signal_id, callback));
508 void CommandBufferProxyImpl::SetSurfaceVisible(bool visible) {
509 if (last_state_.error != gpu::error::kNoError)
512 Send(new GpuCommandBufferMsg_SetSurfaceVisible(route_id_, visible));
515 void CommandBufferProxyImpl::SendManagedMemoryStats(
516 const gpu::ManagedMemoryStats& stats) {
517 if (last_state_.error != gpu::error::kNoError)
520 Send(new GpuCommandBufferMsg_SendClientManagedMemoryStats(route_id_,
524 bool CommandBufferProxyImpl::GenerateMailboxNames(
526 std::vector<gpu::Mailbox>* names) {
527 if (last_state_.error != gpu::error::kNoError)
530 return channel_->GenerateMailboxNames(num, names);
533 bool CommandBufferProxyImpl::ProduceFrontBuffer(const gpu::Mailbox& mailbox) {
534 if (last_state_.error != gpu::error::kNoError)
537 return Send(new GpuCommandBufferMsg_ProduceFrontBuffer(route_id_, mailbox));
540 scoped_ptr<media::VideoDecodeAccelerator>
541 CommandBufferProxyImpl::CreateVideoDecoder(
542 media::VideoCodecProfile profile,
543 media::VideoDecodeAccelerator::Client* client) {
544 int decoder_route_id;
545 scoped_ptr<media::VideoDecodeAccelerator> vda;
546 if (!Send(new GpuCommandBufferMsg_CreateVideoDecoder(route_id_, profile,
547 &decoder_route_id))) {
548 LOG(ERROR) << "Send(GpuCommandBufferMsg_CreateVideoDecoder) failed";
552 if (decoder_route_id < 0) {
553 DLOG(ERROR) << "Failed to Initialize GPU decoder on profile: " << profile;
557 GpuVideoDecodeAcceleratorHost* decoder_host =
558 new GpuVideoDecodeAcceleratorHost(channel_, decoder_route_id, client,
560 vda.reset(decoder_host);
564 gpu::error::Error CommandBufferProxyImpl::GetLastError() {
565 return last_state_.error;
568 bool CommandBufferProxyImpl::Send(IPC::Message* msg) {
569 // Caller should not intentionally send a message if the context is lost.
570 DCHECK(last_state_.error == gpu::error::kNoError);
573 if (channel_->Send(msg)) {
576 // Flag the command buffer as lost. Defer deleting the channel until
577 // OnChannelError is called after returning to the message loop in case
578 // it is referenced elsewhere.
579 last_state_.error = gpu::error::kLostContext;
584 // Callee takes ownership of message, regardless of whether Send is
585 // successful. See IPC::Sender.
590 void CommandBufferProxyImpl::OnUpdateState(
591 const gpu::CommandBuffer::State& state) {
592 // Handle wraparound. It works as long as we don't have more than 2B state
593 // updates in flight across which reordering occurs.
594 if (state.generation - last_state_.generation < 0x80000000U)
598 void CommandBufferProxyImpl::SetOnConsoleMessageCallback(
599 const GpuConsoleMessageCallback& callback) {
600 console_message_callback_ = callback;
603 void CommandBufferProxyImpl::TryUpdateState() {
604 if (last_state_.error == gpu::error::kNoError)
605 shared_state()->Read(&last_state_);
608 } // namespace content