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/browser/gpu/browser_gpu_channel_host_factory.h"
10 #include "base/profiler/scoped_tracker.h"
11 #include "base/synchronization/waitable_event.h"
12 #include "base/threading/thread_restrictions.h"
13 #include "base/trace_event/trace_event.h"
14 #include "content/browser/gpu/browser_gpu_memory_buffer_manager.h"
15 #include "content/browser/gpu/gpu_data_manager_impl.h"
16 #include "content/browser/gpu/gpu_process_host.h"
17 #include "content/browser/gpu/gpu_surface_tracker.h"
18 #include "content/common/child_process_host_impl.h"
19 #include "content/common/gpu/gpu_memory_buffer_factory.h"
20 #include "content/common/gpu/gpu_messages.h"
21 #include "content/public/browser/browser_thread.h"
22 #include "content/public/browser/gpu_data_manager.h"
23 #include "content/public/common/content_client.h"
24 #include "gpu/GLES2/gl2extchromium.h"
25 #include "ipc/ipc_channel_handle.h"
26 #include "ipc/ipc_forwarding_message_filter.h"
27 #include "ipc/message_filter.h"
29 #if defined(OS_MACOSX)
30 #include "content/common/gpu/gpu_memory_buffer_factory_io_surface.h"
33 #if defined(OS_ANDROID)
34 #include "content/common/gpu/gpu_memory_buffer_factory_surface_texture.h"
37 #if defined(USE_OZONE)
38 #include "content/common/gpu/gpu_memory_buffer_factory_ozone_native_buffer.h"
44 base::LazyInstance
<std::set
<gfx::GpuMemoryBuffer::Usage
>>
45 g_enabled_gpu_memory_buffer_usages
;
48 BrowserGpuChannelHostFactory
* BrowserGpuChannelHostFactory::instance_
= NULL
;
50 struct BrowserGpuChannelHostFactory::CreateRequest
{
51 CreateRequest(int32 route_id
)
55 result(CREATE_COMMAND_BUFFER_FAILED
) {}
57 base::WaitableEvent event
;
60 CreateCommandBufferResult result
;
63 class BrowserGpuChannelHostFactory::EstablishRequest
64 : public base::RefCountedThreadSafe
<EstablishRequest
> {
66 static scoped_refptr
<EstablishRequest
> Create(CauseForGpuLaunch cause
,
72 int gpu_host_id() { return gpu_host_id_
; }
73 IPC::ChannelHandle
& channel_handle() { return channel_handle_
; }
74 gpu::GPUInfo
gpu_info() { return gpu_info_
; }
77 friend class base::RefCountedThreadSafe
<EstablishRequest
>;
78 explicit EstablishRequest(CauseForGpuLaunch cause
,
81 ~EstablishRequest() {}
83 void OnEstablishedOnIO(const IPC::ChannelHandle
& channel_handle
,
84 const gpu::GPUInfo
& gpu_info
);
88 base::WaitableEvent event_
;
89 CauseForGpuLaunch cause_for_gpu_launch_
;
90 const int gpu_client_id_
;
92 bool reused_gpu_process_
;
93 IPC::ChannelHandle channel_handle_
;
94 gpu::GPUInfo gpu_info_
;
96 scoped_refptr
<base::MessageLoopProxy
> main_loop_
;
99 scoped_refptr
<BrowserGpuChannelHostFactory::EstablishRequest
>
100 BrowserGpuChannelHostFactory::EstablishRequest::Create(CauseForGpuLaunch cause
,
103 scoped_refptr
<EstablishRequest
> establish_request
=
104 new EstablishRequest(cause
, gpu_client_id
, gpu_host_id
);
105 scoped_refptr
<base::MessageLoopProxy
> loop
=
106 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
);
107 // PostTask outside the constructor to ensure at least one reference exists.
110 base::Bind(&BrowserGpuChannelHostFactory::EstablishRequest::EstablishOnIO
,
112 return establish_request
;
115 BrowserGpuChannelHostFactory::EstablishRequest::EstablishRequest(
116 CauseForGpuLaunch cause
,
119 : event_(false, false),
120 cause_for_gpu_launch_(cause
),
121 gpu_client_id_(gpu_client_id
),
122 gpu_host_id_(gpu_host_id
),
123 reused_gpu_process_(false),
125 main_loop_(base::MessageLoopProxy::current()) {
128 void BrowserGpuChannelHostFactory::EstablishRequest::EstablishOnIO() {
129 GpuProcessHost
* host
= GpuProcessHost::FromID(gpu_host_id_
);
131 host
= GpuProcessHost::Get(GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED
,
132 cause_for_gpu_launch_
);
134 LOG(ERROR
) << "Failed to launch GPU process.";
138 gpu_host_id_
= host
->host_id();
139 reused_gpu_process_
= false;
141 if (reused_gpu_process_
) {
142 // We come here if we retried to establish the channel because of a
143 // failure in ChannelEstablishedOnIO, but we ended up with the same
144 // process ID, meaning the failure was not because of a channel error,
145 // but another reason. So fail now.
146 LOG(ERROR
) << "Failed to create channel.";
150 reused_gpu_process_
= true;
153 host
->EstablishGpuChannel(
158 &BrowserGpuChannelHostFactory::EstablishRequest::OnEstablishedOnIO
,
162 void BrowserGpuChannelHostFactory::EstablishRequest::OnEstablishedOnIO(
163 const IPC::ChannelHandle
& channel_handle
,
164 const gpu::GPUInfo
& gpu_info
) {
165 if (channel_handle
.name
.empty() && reused_gpu_process_
) {
166 // We failed after re-using the GPU process, but it may have died in the
167 // mean time. Retry to have a chance to create a fresh GPU process.
168 DVLOG(1) << "Failed to create channel on existing GPU process. Trying to "
169 "restart GPU process.";
172 channel_handle_
= channel_handle
;
173 gpu_info_
= gpu_info
;
178 void BrowserGpuChannelHostFactory::EstablishRequest::FinishOnIO() {
180 main_loop_
->PostTask(
182 base::Bind(&BrowserGpuChannelHostFactory::EstablishRequest::FinishOnMain
,
186 void BrowserGpuChannelHostFactory::EstablishRequest::FinishOnMain() {
188 BrowserGpuChannelHostFactory
* factory
=
189 BrowserGpuChannelHostFactory::instance();
190 factory
->GpuChannelEstablished();
195 void BrowserGpuChannelHostFactory::EstablishRequest::Wait() {
196 DCHECK(main_loop_
->BelongsToCurrentThread());
198 // TODO(vadimt): Remove ScopedTracker below once crbug.com/125248 is fixed.
199 tracked_objects::ScopedTracker
tracking_profile(
200 FROM_HERE_WITH_EXPLICIT_FUNCTION(
201 "125248 BrowserGpuChannelHostFactory::EstablishRequest::Wait"));
203 // We're blocking the UI thread, which is generally undesirable.
204 // In this case we need to wait for this before we can show any UI
205 // /anyway/, so it won't cause additional jank.
206 // TODO(piman): Make this asynchronous (http://crbug.com/125248).
207 TRACE_EVENT0("browser",
208 "BrowserGpuChannelHostFactory::EstablishGpuChannelSync");
209 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
215 void BrowserGpuChannelHostFactory::EstablishRequest::Cancel() {
216 DCHECK(main_loop_
->BelongsToCurrentThread());
220 bool BrowserGpuChannelHostFactory::CanUseForTesting() {
221 return GpuDataManager::GetInstance()->GpuAccessAllowed(NULL
);
224 void BrowserGpuChannelHostFactory::Initialize(bool establish_gpu_channel
) {
226 instance_
= new BrowserGpuChannelHostFactory();
227 if (establish_gpu_channel
) {
228 instance_
->EstablishGpuChannel(CAUSE_FOR_GPU_LAUNCH_BROWSER_STARTUP
,
233 void BrowserGpuChannelHostFactory::Terminate() {
240 void BrowserGpuChannelHostFactory::EnableGpuMemoryBufferFactoryUsage(
241 gfx::GpuMemoryBuffer::Usage usage
) {
242 g_enabled_gpu_memory_buffer_usages
.Get().insert(usage
);
246 bool BrowserGpuChannelHostFactory::IsGpuMemoryBufferFactoryUsageEnabled(
247 gfx::GpuMemoryBuffer::Usage usage
) {
248 return g_enabled_gpu_memory_buffer_usages
.Get().count(usage
) != 0;
252 uint32
BrowserGpuChannelHostFactory::GetImageTextureTarget() {
253 if (!IsGpuMemoryBufferFactoryUsageEnabled(gfx::GpuMemoryBuffer::MAP
))
254 return GL_TEXTURE_2D
;
256 std::vector
<gfx::GpuMemoryBufferType
> supported_types
;
257 GpuMemoryBufferFactory::GetSupportedTypes(&supported_types
);
258 DCHECK(!supported_types
.empty());
260 // The GPU service will always use the preferred type.
261 gfx::GpuMemoryBufferType type
= supported_types
[0];
264 case gfx::SURFACE_TEXTURE_BUFFER
:
265 // Surface texture backed GPU memory buffers require
266 // TEXTURE_EXTERNAL_OES.
267 return GL_TEXTURE_EXTERNAL_OES
;
268 case gfx::IO_SURFACE_BUFFER
:
269 // IOSurface backed images require GL_TEXTURE_RECTANGLE_ARB.
270 return GL_TEXTURE_RECTANGLE_ARB
;
272 return GL_TEXTURE_2D
;
276 BrowserGpuChannelHostFactory::BrowserGpuChannelHostFactory()
277 : gpu_client_id_(ChildProcessHostImpl::GenerateChildProcessUniqueId()),
278 shutdown_event_(new base::WaitableEvent(true, false)),
279 gpu_memory_buffer_manager_(
280 new BrowserGpuMemoryBufferManager(this, gpu_client_id_
)),
282 next_create_gpu_memory_buffer_request_id_(0) {
285 BrowserGpuChannelHostFactory::~BrowserGpuChannelHostFactory() {
286 DCHECK(IsMainThread());
287 if (pending_request_
.get())
288 pending_request_
->Cancel();
289 for (size_t n
= 0; n
< established_callbacks_
.size(); n
++)
290 established_callbacks_
[n
].Run();
291 shutdown_event_
->Signal();
294 bool BrowserGpuChannelHostFactory::IsMainThread() {
295 return BrowserThread::CurrentlyOn(BrowserThread::UI
);
298 base::MessageLoop
* BrowserGpuChannelHostFactory::GetMainLoop() {
299 return BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::UI
);
302 scoped_refptr
<base::MessageLoopProxy
>
303 BrowserGpuChannelHostFactory::GetIOLoopProxy() {
304 return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
);
307 scoped_ptr
<base::SharedMemory
>
308 BrowserGpuChannelHostFactory::AllocateSharedMemory(size_t size
) {
309 scoped_ptr
<base::SharedMemory
> shm(new base::SharedMemory());
310 if (!shm
->CreateAnonymous(size
))
311 return scoped_ptr
<base::SharedMemory
>();
315 void BrowserGpuChannelHostFactory::CreateViewCommandBufferOnIO(
316 CreateRequest
* request
,
318 const GPUCreateCommandBufferConfig
& init_params
) {
319 GpuProcessHost
* host
= GpuProcessHost::FromID(gpu_host_id_
);
321 request
->event
.Signal();
325 gfx::GLSurfaceHandle surface
=
326 GpuSurfaceTracker::Get()->GetSurfaceHandle(surface_id
);
328 host
->CreateViewCommandBuffer(
334 base::Bind(&BrowserGpuChannelHostFactory::CommandBufferCreatedOnIO
,
339 void BrowserGpuChannelHostFactory::CommandBufferCreatedOnIO(
340 CreateRequest
* request
, CreateCommandBufferResult result
) {
341 request
->result
= result
;
342 request
->event
.Signal();
345 CreateCommandBufferResult
BrowserGpuChannelHostFactory::CreateViewCommandBuffer(
347 const GPUCreateCommandBufferConfig
& init_params
,
349 CreateRequest
request(route_id
);
350 GetIOLoopProxy()->PostTask(FROM_HERE
, base::Bind(
351 &BrowserGpuChannelHostFactory::CreateViewCommandBufferOnIO
,
352 base::Unretained(this),
356 // TODO(vadimt): Remove ScopedTracker below once crbug.com/125248 is fixed.
357 tracked_objects::ScopedTracker
tracking_profile(
358 FROM_HERE_WITH_EXPLICIT_FUNCTION(
359 "125248 BrowserGpuChannelHostFactory::CreateViewCommandBuffer"));
361 // We're blocking the UI thread, which is generally undesirable.
362 // In this case we need to wait for this before we can show any UI /anyway/,
363 // so it won't cause additional jank.
364 // TODO(piman): Make this asynchronous (http://crbug.com/125248).
365 TRACE_EVENT0("browser",
366 "BrowserGpuChannelHostFactory::CreateViewCommandBuffer");
367 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
368 request
.event
.Wait();
369 return request
.result
;
372 // Blocking the UI thread to open a GPU channel is not supported on Android.
373 // (Opening the initial channel to a child process involves handling a reply
374 // task on the UI thread first, so we cannot block here.)
375 #if !defined(OS_ANDROID)
376 GpuChannelHost
* BrowserGpuChannelHostFactory::EstablishGpuChannelSync(
377 CauseForGpuLaunch cause_for_gpu_launch
) {
378 EstablishGpuChannel(cause_for_gpu_launch
, base::Closure());
380 if (pending_request_
.get())
381 pending_request_
->Wait();
383 return gpu_channel_
.get();
387 void BrowserGpuChannelHostFactory::EstablishGpuChannel(
388 CauseForGpuLaunch cause_for_gpu_launch
,
389 const base::Closure
& callback
) {
390 if (gpu_channel_
.get() && gpu_channel_
->IsLost()) {
391 DCHECK(!pending_request_
.get());
392 // Recreate the channel if it has been lost.
396 if (!gpu_channel_
.get() && !pending_request_
.get()) {
397 // We should only get here if the context was lost.
398 pending_request_
= EstablishRequest::Create(
399 cause_for_gpu_launch
, gpu_client_id_
, gpu_host_id_
);
402 if (!callback
.is_null()) {
403 if (gpu_channel_
.get())
406 established_callbacks_
.push_back(callback
);
410 GpuChannelHost
* BrowserGpuChannelHostFactory::GetGpuChannel() {
411 if (gpu_channel_
.get() && !gpu_channel_
->IsLost())
412 return gpu_channel_
.get();
417 void BrowserGpuChannelHostFactory::GpuChannelEstablished() {
418 DCHECK(IsMainThread());
419 DCHECK(pending_request_
.get());
420 if (pending_request_
->channel_handle().name
.empty()) {
421 DCHECK(!gpu_channel_
.get());
423 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/466866
425 tracked_objects::ScopedTracker
tracking_profile1(
426 FROM_HERE_WITH_EXPLICIT_FUNCTION(
427 "466866 BrowserGpuChannelHostFactory::GpuChannelEstablished1"));
428 GetContentClient()->SetGpuInfo(pending_request_
->gpu_info());
430 GpuChannelHost::Create(this,
431 pending_request_
->gpu_info(),
432 pending_request_
->channel_handle(),
433 shutdown_event_
.get(),
434 BrowserGpuMemoryBufferManager::current());
436 gpu_host_id_
= pending_request_
->gpu_host_id();
437 pending_request_
= NULL
;
439 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/466866 is
441 tracked_objects::ScopedTracker
tracking_profile2(
442 FROM_HERE_WITH_EXPLICIT_FUNCTION(
443 "466866 BrowserGpuChannelHostFactory::GpuChannelEstablished2"));
445 for (size_t n
= 0; n
< established_callbacks_
.size(); n
++)
446 established_callbacks_
[n
].Run();
448 established_callbacks_
.clear();
452 void BrowserGpuChannelHostFactory::AddFilterOnIO(
454 scoped_refptr
<IPC::MessageFilter
> filter
) {
455 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
457 GpuProcessHost
* host
= GpuProcessHost::FromID(host_id
);
459 host
->AddFilter(filter
.get());
462 bool BrowserGpuChannelHostFactory::IsGpuMemoryBufferConfigurationSupported(
463 gfx::GpuMemoryBuffer::Format format
,
464 gfx::GpuMemoryBuffer::Usage usage
) {
465 // Return early if usage is not enabled.
466 if (!IsGpuMemoryBufferFactoryUsageEnabled(usage
))
469 // Preferred type is always used by factory.
470 std::vector
<gfx::GpuMemoryBufferType
> supported_types
;
471 GpuMemoryBufferFactory::GetSupportedTypes(&supported_types
);
472 DCHECK(!supported_types
.empty());
473 switch (supported_types
[0]) {
474 case gfx::SHARED_MEMORY_BUFFER
:
475 // Shared memory buffers must be created in-process.
477 #if defined(OS_MACOSX)
478 case gfx::IO_SURFACE_BUFFER
:
479 return GpuMemoryBufferFactoryIOSurface::
480 IsGpuMemoryBufferConfigurationSupported(format
, usage
);
482 #if defined(OS_ANDROID)
483 case gfx::SURFACE_TEXTURE_BUFFER
:
484 return GpuMemoryBufferFactorySurfaceTexture::
485 IsGpuMemoryBufferConfigurationSupported(format
, usage
);
487 #if defined(USE_OZONE)
488 case gfx::OZONE_NATIVE_BUFFER
:
489 return GpuMemoryBufferFactoryOzoneNativeBuffer::
490 IsGpuMemoryBufferConfigurationSupported(format
, usage
);
498 void BrowserGpuChannelHostFactory::CreateGpuMemoryBuffer(
499 gfx::GpuMemoryBufferId id
,
500 const gfx::Size
& size
,
501 gfx::GpuMemoryBuffer::Format format
,
502 gfx::GpuMemoryBuffer::Usage usage
,
505 const CreateGpuMemoryBufferCallback
& callback
) {
506 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
508 GpuProcessHost
* host
= GpuProcessHost::FromID(gpu_host_id_
);
510 callback
.Run(gfx::GpuMemoryBufferHandle());
514 uint32 request_id
= next_create_gpu_memory_buffer_request_id_
++;
515 create_gpu_memory_buffer_requests_
[request_id
] = callback
;
517 host
->CreateGpuMemoryBuffer(
518 id
, size
, format
, usage
, client_id
, surface_id
,
519 base::Bind(&BrowserGpuChannelHostFactory::OnGpuMemoryBufferCreated
,
520 base::Unretained(this), request_id
));
523 void BrowserGpuChannelHostFactory::DestroyGpuMemoryBuffer(
524 gfx::GpuMemoryBufferId id
,
527 BrowserThread::PostTask(
530 base::Bind(&BrowserGpuChannelHostFactory::DestroyGpuMemoryBufferOnIO
,
531 base::Unretained(this),
537 void BrowserGpuChannelHostFactory::DestroyGpuMemoryBufferOnIO(
538 gfx::GpuMemoryBufferId id
,
541 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
543 GpuProcessHost
* host
= GpuProcessHost::FromID(gpu_host_id_
);
547 host
->DestroyGpuMemoryBuffer(id
, client_id
, sync_point
);
550 void BrowserGpuChannelHostFactory::OnGpuMemoryBufferCreated(
552 const gfx::GpuMemoryBufferHandle
& handle
) {
553 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
555 CreateGpuMemoryBufferCallbackMap::iterator iter
=
556 create_gpu_memory_buffer_requests_
.find(request_id
);
557 DCHECK(iter
!= create_gpu_memory_buffer_requests_
.end());
558 iter
->second
.Run(handle
);
559 create_gpu_memory_buffer_requests_
.erase(iter
);
562 } // namespace content