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/gpu_process_host.h"
7 #include "base/base64.h"
8 #include "base/base_switches.h"
9 #include "base/basictypes.h"
10 #include "base/bind.h"
11 #include "base/callback_helpers.h"
12 #include "base/command_line.h"
13 #include "base/logging.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/metrics/histogram.h"
16 #include "base/sha1.h"
17 #include "base/threading/thread.h"
18 #include "base/trace_event/trace_event.h"
19 #include "components/tracing/tracing_switches.h"
20 #include "content/browser/browser_child_process_host_impl.h"
21 #include "content/browser/gpu/compositor_util.h"
22 #include "content/browser/gpu/gpu_data_manager_impl.h"
23 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
24 #include "content/browser/gpu/shader_disk_cache.h"
25 #include "content/browser/renderer_host/render_widget_host_impl.h"
26 #include "content/common/child_process_host_impl.h"
27 #include "content/common/gpu/gpu_messages.h"
28 #include "content/common/in_process_child_thread_params.h"
29 #include "content/common/view_messages.h"
30 #include "content/public/browser/browser_thread.h"
31 #include "content/public/browser/content_browser_client.h"
32 #include "content/public/browser/render_process_host.h"
33 #include "content/public/browser/render_widget_host_view.h"
34 #include "content/public/browser/render_widget_host_view_frame_subscriber.h"
35 #include "content/public/common/content_client.h"
36 #include "content/public/common/content_switches.h"
37 #include "content/public/common/result_codes.h"
38 #include "content/public/common/sandbox_type.h"
39 #include "content/public/common/sandboxed_process_launcher_delegate.h"
40 #include "gpu/command_buffer/service/gpu_switches.h"
41 #include "ipc/ipc_channel_handle.h"
42 #include "ipc/ipc_switches.h"
43 #include "ipc/message_filter.h"
44 #include "media/base/media_switches.h"
45 #include "ui/base/ui_base_switches.h"
46 #include "ui/events/latency_info.h"
47 #include "ui/gl/gl_switches.h"
49 #if defined(OS_ANDROID)
50 #include "base/android/build_info.h"
54 #include "base/win/windows_version.h"
55 #include "content/common/sandbox_win.h"
56 #include "sandbox/win/src/sandbox_policy.h"
57 #include "ui/gfx/switches.h"
60 #if defined(USE_OZONE)
61 #include "ui/ozone/public/ozone_switches.h"
64 #if defined(USE_X11) && !defined(OS_CHROMEOS)
65 #include "ui/gfx/x/x11_switches.h"
68 #if defined(OS_MACOSX) && !defined(OS_IOS)
69 #include "content/browser/browser_io_surface_manager_mac.h"
70 #include "content/common/child_process_messages.h"
73 #if defined(OS_MACOSX)
74 #include "content/browser/renderer_host/render_widget_resize_helper_mac.h"
79 bool GpuProcessHost::gpu_enabled_
= true;
80 bool GpuProcessHost::hardware_gpu_enabled_
= true;
81 int GpuProcessHost::gpu_crash_count_
= 0;
82 int GpuProcessHost::gpu_recent_crash_count_
= 0;
83 bool GpuProcessHost::crashed_before_
= false;
84 int GpuProcessHost::swiftshader_crash_count_
= 0;
88 // Command-line switches to propagate to the GPU process.
89 static const char* const kSwitchNames
[] = {
90 switches::kDisableAcceleratedVideoDecode
,
91 switches::kDisableBreakpad
,
92 switches::kDisableGpuSandbox
,
93 switches::kDisableGpuWatchdog
,
94 switches::kDisableGLExtensions
,
95 switches::kDisableLogging
,
96 switches::kDisableSeccompFilterSandbox
,
97 #if defined(ENABLE_WEBRTC)
98 switches::kDisableWebRtcHWEncoding
,
101 switches::kEnableAcceleratedVpxDecode
,
103 switches::kEnableLogging
,
104 switches::kEnableShareGroupAsyncTextureUpload
,
105 #if defined(OS_CHROMEOS)
106 switches::kDisableVaapiAcceleratedVideoEncode
,
108 switches::kGpuStartupDialog
,
109 switches::kGpuSandboxAllowSysVShm
,
110 switches::kGpuSandboxFailuresFatal
,
111 switches::kGpuSandboxStartEarly
,
112 switches::kLoggingLevel
,
113 switches::kEnableLowEndDeviceMode
,
114 switches::kDisableLowEndDeviceMode
,
115 switches::kEnableMemoryBenchmarking
,
116 switches::kNoSandbox
,
117 switches::kProfilerTiming
,
118 switches::kTestGLLib
,
119 switches::kTraceConfigFile
,
120 switches::kTraceStartup
,
121 switches::kTraceToConsole
,
124 #if defined(OS_MACOSX)
125 switches::kDisableRemoteCoreAnimation
,
126 switches::kDisableMacOverlays
,
127 switches::kEnableSandboxLogging
,
128 switches::kShowMacOverlayBorders
,
130 #if defined(USE_AURA)
131 switches::kUIPrioritizeInGpuProcess
,
133 #if defined(USE_OZONE)
134 switches::kOzonePlatform
,
136 #if defined(USE_X11) && !defined(OS_CHROMEOS)
137 switches::kX11Display
,
141 enum GPUProcessLifetimeEvent
{
147 GPU_PROCESS_LIFETIME_EVENT_MAX
= 100
150 // Indexed by GpuProcessKind. There is one of each kind maximum. This array may
151 // only be accessed from the IO thread.
152 GpuProcessHost
* g_gpu_process_hosts
[GpuProcessHost::GPU_PROCESS_KIND_COUNT
];
155 void SendGpuProcessMessage(GpuProcessHost::GpuProcessKind kind
,
156 CauseForGpuLaunch cause
,
157 IPC::Message
* message
) {
158 GpuProcessHost
* host
= GpuProcessHost::Get(kind
, cause
);
166 // NOTE: changes to this class need to be reviewed by the security team.
167 class GpuSandboxedProcessLauncherDelegate
168 : public SandboxedProcessLauncherDelegate
{
170 GpuSandboxedProcessLauncherDelegate(base::CommandLine
* cmd_line
,
171 ChildProcessHost
* host
)
173 : cmd_line_(cmd_line
) {}
174 #elif defined(OS_POSIX)
175 : ipc_fd_(host
->TakeClientFileDescriptor()) {}
178 ~GpuSandboxedProcessLauncherDelegate() override
{}
181 bool ShouldSandbox() override
{
182 bool sandbox
= !cmd_line_
->HasSwitch(switches::kDisableGpuSandbox
);
184 DVLOG(1) << "GPU sandbox is disabled";
189 void PreSandbox(bool* disable_default_policy
,
190 base::FilePath
* exposed_dir
) override
{
191 *disable_default_policy
= true;
194 // For the GPU process we gotten as far as USER_LIMITED. The next level
195 // which is USER_RESTRICTED breaks both the DirectX backend and the OpenGL
196 // backend. Note that the GPU process is connected to the interactive
198 void PreSpawnTarget(sandbox::TargetPolicy
* policy
, bool* success
) override
{
199 if (base::win::GetVersion() > base::win::VERSION_XP
) {
200 if (cmd_line_
->GetSwitchValueASCII(switches::kUseGL
) ==
201 gfx::kGLImplementationDesktopName
) {
203 policy
->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS
,
204 sandbox::USER_LIMITED
);
205 SetJobLevel(*cmd_line_
, sandbox::JOB_UNPROTECTED
, 0, policy
);
206 policy
->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW
);
208 policy
->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS
,
209 sandbox::USER_LIMITED
);
211 // UI restrictions break when we access Windows from outside our job.
212 // However, we don't want a proxy window in this process because it can
213 // introduce deadlocks where the renderer blocks on the gpu, which in
214 // turn blocks on the browser UI thread. So, instead we forgo a window
215 // message pump entirely and just add job restrictions to prevent child
217 SetJobLevel(*cmd_line_
,
218 sandbox::JOB_LIMITED_USER
,
219 JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS
|
220 JOB_OBJECT_UILIMIT_DESKTOP
|
221 JOB_OBJECT_UILIMIT_EXITWINDOWS
|
222 JOB_OBJECT_UILIMIT_DISPLAYSETTINGS
,
225 policy
->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW
);
228 SetJobLevel(*cmd_line_
, sandbox::JOB_UNPROTECTED
, 0, policy
);
229 policy
->SetTokenLevel(sandbox::USER_UNPROTECTED
,
230 sandbox::USER_LIMITED
);
233 // Allow the server side of GPU sockets, which are pipes that have
234 // the "chrome.gpu" namespace and an arbitrary suffix.
235 sandbox::ResultCode result
= policy
->AddRule(
236 sandbox::TargetPolicy::SUBSYS_NAMED_PIPES
,
237 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY
,
238 L
"\\\\.\\pipe\\chrome.gpu.*");
239 if (result
!= sandbox::SBOX_ALL_OK
) {
244 // Block this DLL even if it is not loaded by the browser process.
245 policy
->AddDllToUnload(L
"cmsetac.dll");
248 // GPU also needs to add sections to the browser for aura
249 // TODO(jschuh): refactor the GPU channel to remove this. crbug.com/128786
250 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES
,
251 sandbox::TargetPolicy::HANDLES_DUP_BROKER
,
253 if (result
!= sandbox::SBOX_ALL_OK
) {
259 if (cmd_line_
->HasSwitch(switches::kEnableLogging
)) {
260 base::string16 log_file_path
= logging::GetLogFileFullPath();
261 if (!log_file_path
.empty()) {
262 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_FILES
,
263 sandbox::TargetPolicy::FILES_ALLOW_ANY
,
264 log_file_path
.c_str());
265 if (result
!= sandbox::SBOX_ALL_OK
) {
272 #elif defined(OS_POSIX)
274 base::ScopedFD
TakeIpcFd() override
{ return ipc_fd_
.Pass(); }
277 SandboxType
GetSandboxType() override
{
278 return SANDBOX_TYPE_GPU
;
283 base::CommandLine
* cmd_line_
;
284 #elif defined(OS_POSIX)
285 base::ScopedFD ipc_fd_
;
289 } // anonymous namespace
292 bool GpuProcessHost::ValidateHost(GpuProcessHost
* host
) {
293 // The Gpu process is invalid if it's not using SwiftShader, the card is
294 // blacklisted, and we can kill it and start over.
295 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
296 switches::kSingleProcess
) ||
297 base::CommandLine::ForCurrentProcess()->HasSwitch(
298 switches::kInProcessGPU
) ||
300 (host
->swiftshader_rendering_
||
301 !GpuDataManagerImpl::GetInstance()->ShouldUseSwiftShader()))) {
305 host
->ForceShutdown();
310 GpuProcessHost
* GpuProcessHost::Get(GpuProcessKind kind
,
311 CauseForGpuLaunch cause
) {
312 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
314 // Don't grant further access to GPU if it is not allowed.
315 GpuDataManagerImpl
* gpu_data_manager
= GpuDataManagerImpl::GetInstance();
316 DCHECK(gpu_data_manager
);
317 if (!gpu_data_manager
->GpuAccessAllowed(NULL
))
320 if (g_gpu_process_hosts
[kind
] && ValidateHost(g_gpu_process_hosts
[kind
]))
321 return g_gpu_process_hosts
[kind
];
323 if (cause
== CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH
)
326 static int last_host_id
= 0;
328 host_id
= ++last_host_id
;
330 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLaunchCause",
332 CAUSE_FOR_GPU_LAUNCH_MAX_ENUM
);
334 GpuProcessHost
* host
= new GpuProcessHost(host_id
, kind
);
338 // TODO(sievers): Revisit this behavior. It's not really a crash, but we also
339 // want the fallback-to-sw behavior if we cannot initialize the GPU.
340 host
->RecordProcessCrash();
347 void GpuProcessHost::GetProcessHandles(
348 const GpuDataManager::GetGpuProcessHandlesCallback
& callback
) {
349 if (!BrowserThread::CurrentlyOn(BrowserThread::IO
)) {
350 BrowserThread::PostTask(
353 base::Bind(&GpuProcessHost::GetProcessHandles
, callback
));
356 std::list
<base::ProcessHandle
> handles
;
357 for (size_t i
= 0; i
< arraysize(g_gpu_process_hosts
); ++i
) {
358 // TODO(rvargas) crbug/417532: don't store ProcessHandles!.
359 GpuProcessHost
* host
= g_gpu_process_hosts
[i
];
360 if (host
&& ValidateHost(host
))
361 handles
.push_back(host
->process_
->GetProcess().Handle());
363 BrowserThread::PostTask(
366 base::Bind(callback
, handles
));
370 void GpuProcessHost::SendOnIO(GpuProcessKind kind
,
371 CauseForGpuLaunch cause
,
372 IPC::Message
* message
) {
373 if (!BrowserThread::PostTask(
374 BrowserThread::IO
, FROM_HERE
,
376 &SendGpuProcessMessage
, kind
, cause
, message
))) {
381 GpuMainThreadFactoryFunction g_gpu_main_thread_factory
= NULL
;
383 void GpuProcessHost::RegisterGpuMainThreadFactory(
384 GpuMainThreadFactoryFunction create
) {
385 g_gpu_main_thread_factory
= create
;
389 GpuProcessHost
* GpuProcessHost::FromID(int host_id
) {
390 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
392 for (int i
= 0; i
< GPU_PROCESS_KIND_COUNT
; ++i
) {
393 GpuProcessHost
* host
= g_gpu_process_hosts
[i
];
394 if (host
&& host
->host_id_
== host_id
&& ValidateHost(host
))
401 GpuProcessHost::GpuProcessHost(int host_id
, GpuProcessKind kind
)
405 swiftshader_rendering_(false),
407 process_launched_(false),
409 uma_memory_stats_received_(false) {
410 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
411 switches::kSingleProcess
) ||
412 base::CommandLine::ForCurrentProcess()->HasSwitch(
413 switches::kInProcessGPU
)) {
417 // If the 'single GPU process' policy ever changes, we still want to maintain
418 // it for 'gpu thread' mode and only create one instance of host and thread.
419 DCHECK(!in_process_
|| g_gpu_process_hosts
[kind
] == NULL
);
421 g_gpu_process_hosts
[kind
] = this;
423 // Post a task to create the corresponding GpuProcessHostUIShim. The
424 // GpuProcessHostUIShim will be destroyed if either the browser exits,
425 // in which case it calls GpuProcessHostUIShim::DestroyAll, or the
426 // GpuProcessHost is destroyed, which happens when the corresponding GPU
427 // process terminates or fails to launch.
428 BrowserThread::PostTask(
431 base::Bind(base::IgnoreResult(&GpuProcessHostUIShim::Create
), host_id
));
433 process_
.reset(new BrowserChildProcessHostImpl(PROCESS_TYPE_GPU
, this));
436 GpuProcessHost::~GpuProcessHost() {
437 DCHECK(CalledOnValidThread());
439 SendOutstandingReplies();
441 // In case we never started, clean up.
442 while (!queued_messages_
.empty()) {
443 delete queued_messages_
.front();
444 queued_messages_
.pop();
447 #if defined(OS_MACOSX) && !defined(OS_IOS)
448 if (!io_surface_manager_token_
.IsZero()) {
449 BrowserIOSurfaceManager::GetInstance()->InvalidateGpuProcessToken();
450 io_surface_manager_token_
.SetZero();
454 // This is only called on the IO thread so no race against the constructor
455 // for another GpuProcessHost.
456 if (g_gpu_process_hosts
[kind_
] == this)
457 g_gpu_process_hosts
[kind_
] = NULL
;
459 // If there are any remaining offscreen contexts at the point the
460 // GPU process exits, assume something went wrong, and block their
461 // URLs from accessing client 3D APIs without prompting.
462 BlockLiveOffscreenContexts();
464 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitSurfaceCount",
465 GpuSurfaceTracker::Get()->GetSurfaceCount());
466 UMA_HISTOGRAM_BOOLEAN("GPU.AtExitReceivedMemoryStats",
467 uma_memory_stats_received_
);
469 if (uma_memory_stats_received_
) {
470 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitManagedMemoryClientCount",
471 uma_memory_stats_
.client_count
);
472 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitContextGroupCount",
473 uma_memory_stats_
.context_group_count
);
474 UMA_HISTOGRAM_CUSTOM_COUNTS(
475 "GPU.AtExitMBytesAllocated",
476 uma_memory_stats_
.bytes_allocated_current
/ 1024 / 1024, 1, 2000, 50);
477 UMA_HISTOGRAM_CUSTOM_COUNTS(
478 "GPU.AtExitMBytesAllocatedMax",
479 uma_memory_stats_
.bytes_allocated_max
/ 1024 / 1024, 1, 2000, 50);
480 UMA_HISTOGRAM_CUSTOM_COUNTS(
481 "GPU.AtExitMBytesLimit",
482 uma_memory_stats_
.bytes_limit
/ 1024 / 1024, 1, 2000, 50);
488 base::TerminationStatus status
= process_
->GetTerminationStatus(
489 false /* known_dead */, &exit_code
);
490 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessTerminationStatus",
492 base::TERMINATION_STATUS_MAX_ENUM
);
494 if (status
== base::TERMINATION_STATUS_NORMAL_TERMINATION
||
495 status
== base::TERMINATION_STATUS_ABNORMAL_TERMINATION
) {
496 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessExitCode",
498 RESULT_CODE_LAST_CODE
);
502 case base::TERMINATION_STATUS_NORMAL_TERMINATION
:
503 message
= "The GPU process exited normally. Everything is okay.";
505 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION
:
506 message
= base::StringPrintf(
507 "The GPU process exited with code %d.",
510 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED
:
511 message
= "You killed the GPU process! Why?";
513 #if defined(OS_CHROMEOS)
514 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM
:
515 message
= "The GUP process was killed due to out of memory.";
518 case base::TERMINATION_STATUS_PROCESS_CRASHED
:
519 message
= "The GPU process crashed!";
521 case base::TERMINATION_STATUS_LAUNCH_FAILED
:
522 message
= "The GPU process failed to start!";
529 BrowserThread::PostTask(BrowserThread::UI
,
531 base::Bind(&GpuProcessHostUIShim::Destroy
,
536 bool GpuProcessHost::Init() {
537 init_start_time_
= base::TimeTicks::Now();
539 TRACE_EVENT_INSTANT0("gpu", "LaunchGpuProcess", TRACE_EVENT_SCOPE_THREAD
);
541 std::string channel_id
= process_
->GetHost()->CreateChannel();
542 if (channel_id
.empty())
546 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
547 DCHECK(g_gpu_main_thread_factory
);
548 in_process_gpu_thread_
.reset(
549 g_gpu_main_thread_factory(InProcessChildThreadParams(
550 channel_id
, base::MessageLoop::current()->task_runner())));
551 base::Thread::Options options
;
553 // WGL needs to create its own window and pump messages on it.
554 options
.message_loop_type
= base::MessageLoop::TYPE_UI
;
556 in_process_gpu_thread_
->StartWithOptions(options
);
558 OnProcessLaunched(); // Fake a callback that the process is ready.
559 } else if (!LaunchGpuProcess(channel_id
)) {
563 if (!Send(new GpuMsg_Initialize()))
566 #if defined(OS_MACOSX) && !defined(OS_IOS)
567 io_surface_manager_token_
=
568 BrowserIOSurfaceManager::GetInstance()->GenerateGpuProcessToken();
569 // Note: A valid IOSurface manager token needs to be sent to the Gpu process
570 // before any GpuMemoryBuffer allocation requests can be sent.
571 Send(new ChildProcessMsg_SetIOSurfaceManagerToken(io_surface_manager_token_
));
577 void GpuProcessHost::RouteOnUIThread(const IPC::Message
& message
) {
578 BrowserThread::PostTask(
581 base::Bind(&RouteToGpuProcessHostUIShimTask
, host_id_
, message
));
584 bool GpuProcessHost::Send(IPC::Message
* msg
) {
585 DCHECK(CalledOnValidThread());
586 if (process_
->GetHost()->IsChannelOpening()) {
587 queued_messages_
.push(msg
);
591 bool result
= process_
->Send(msg
);
593 // Channel is hosed, but we may not get destroyed for a while. Send
594 // outstanding channel creation failures now so that the caller can restart
595 // with a new process/channel without waiting.
596 SendOutstandingReplies();
601 void GpuProcessHost::AddFilter(IPC::MessageFilter
* filter
) {
602 DCHECK(CalledOnValidThread());
603 process_
->GetHost()->AddFilter(filter
);
606 bool GpuProcessHost::OnMessageReceived(const IPC::Message
& message
) {
607 DCHECK(CalledOnValidThread());
608 IPC_BEGIN_MESSAGE_MAP(GpuProcessHost
, message
)
609 IPC_MESSAGE_HANDLER(GpuHostMsg_Initialized
, OnInitialized
)
610 IPC_MESSAGE_HANDLER(GpuHostMsg_ChannelEstablished
, OnChannelEstablished
)
611 IPC_MESSAGE_HANDLER(GpuHostMsg_CommandBufferCreated
, OnCommandBufferCreated
)
612 IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyCommandBuffer
, OnDestroyCommandBuffer
)
613 IPC_MESSAGE_HANDLER(GpuHostMsg_GpuMemoryBufferCreated
,
614 OnGpuMemoryBufferCreated
)
615 IPC_MESSAGE_HANDLER(GpuHostMsg_DidCreateOffscreenContext
,
616 OnDidCreateOffscreenContext
)
617 IPC_MESSAGE_HANDLER(GpuHostMsg_DidLoseContext
, OnDidLoseContext
)
618 IPC_MESSAGE_HANDLER(GpuHostMsg_DidDestroyOffscreenContext
,
619 OnDidDestroyOffscreenContext
)
620 IPC_MESSAGE_HANDLER(GpuHostMsg_GpuMemoryUmaStats
,
621 OnGpuMemoryUmaStatsReceived
)
622 #if defined(OS_MACOSX)
623 IPC_MESSAGE_HANDLER_GENERIC(GpuHostMsg_AcceleratedSurfaceBuffersSwapped
,
624 OnAcceleratedSurfaceBuffersSwapped(message
))
626 IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyChannel
,
628 IPC_MESSAGE_HANDLER(GpuHostMsg_CacheShader
,
631 IPC_MESSAGE_UNHANDLED(RouteOnUIThread(message
))
632 IPC_END_MESSAGE_MAP()
637 void GpuProcessHost::OnChannelConnected(int32 peer_pid
) {
638 TRACE_EVENT0("gpu", "GpuProcessHost::OnChannelConnected");
640 while (!queued_messages_
.empty()) {
641 Send(queued_messages_
.front());
642 queued_messages_
.pop();
646 void GpuProcessHost::EstablishGpuChannel(
648 uint64_t client_tracing_id
,
650 bool allow_future_sync_points
,
651 bool allow_real_time_streams
,
652 const EstablishChannelCallback
& callback
) {
653 DCHECK(CalledOnValidThread());
654 TRACE_EVENT0("gpu", "GpuProcessHost::EstablishGpuChannel");
656 // If GPU features are already blacklisted, no need to establish the channel.
657 if (!GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL
)) {
658 DVLOG(1) << "GPU blacklisted, refusing to open a GPU channel.";
659 callback
.Run(IPC::ChannelHandle(), gpu::GPUInfo());
663 if (Send(new GpuMsg_EstablishChannel(client_id
, client_tracing_id
,
664 share_context
, allow_future_sync_points
,
665 allow_real_time_streams
))) {
666 channel_requests_
.push(callback
);
668 DVLOG(1) << "Failed to send GpuMsg_EstablishChannel.";
669 callback
.Run(IPC::ChannelHandle(), gpu::GPUInfo());
672 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
673 switches::kDisableGpuShaderDiskCache
)) {
674 CreateChannelCache(client_id
);
678 void GpuProcessHost::CreateViewCommandBuffer(
679 const gfx::GLSurfaceHandle
& compositing_surface
,
682 const GPUCreateCommandBufferConfig
& init_params
,
684 const CreateCommandBufferCallback
& callback
) {
685 TRACE_EVENT0("gpu", "GpuProcessHost::CreateViewCommandBuffer");
687 DCHECK(CalledOnValidThread());
689 if (!compositing_surface
.is_null() &&
690 Send(new GpuMsg_CreateViewCommandBuffer(
691 compositing_surface
, surface_id
, client_id
, init_params
, route_id
))) {
692 create_command_buffer_requests_
.push(callback
);
693 surface_refs_
.insert(std::make_pair(surface_id
,
694 GpuSurfaceTracker::GetInstance()->GetSurfaceRefForSurface(surface_id
)));
696 // Could distinguish here between compositing_surface being NULL
697 // and Send failing, if desired.
698 callback
.Run(CREATE_COMMAND_BUFFER_FAILED_AND_CHANNEL_LOST
);
702 void GpuProcessHost::CreateGpuMemoryBuffer(
703 gfx::GpuMemoryBufferId id
,
704 const gfx::Size
& size
,
705 gfx::BufferFormat format
,
706 gfx::BufferUsage usage
,
709 const CreateGpuMemoryBufferCallback
& callback
) {
710 TRACE_EVENT0("gpu", "GpuProcessHost::CreateGpuMemoryBuffer");
712 DCHECK(CalledOnValidThread());
714 GpuMsg_CreateGpuMemoryBuffer_Params params
;
717 params
.format
= format
;
718 params
.usage
= usage
;
719 params
.client_id
= client_id
;
720 params
.surface_handle
=
721 GpuSurfaceTracker::GetInstance()->GetSurfaceHandle(surface_id
).handle
;
722 if (Send(new GpuMsg_CreateGpuMemoryBuffer(params
))) {
723 create_gpu_memory_buffer_requests_
.push(callback
);
724 create_gpu_memory_buffer_surface_refs_
.push(surface_id
);
726 surface_refs_
.insert(std::make_pair(
727 surface_id
, GpuSurfaceTracker::GetInstance()->GetSurfaceRefForSurface(
731 callback
.Run(gfx::GpuMemoryBufferHandle());
735 void GpuProcessHost::DestroyGpuMemoryBuffer(gfx::GpuMemoryBufferId id
,
738 TRACE_EVENT0("gpu", "GpuProcessHost::DestroyGpuMemoryBuffer");
740 DCHECK(CalledOnValidThread());
742 Send(new GpuMsg_DestroyGpuMemoryBuffer(id
, client_id
, sync_point
));
745 void GpuProcessHost::OnInitialized(bool result
, const gpu::GPUInfo
& gpu_info
) {
746 UMA_HISTOGRAM_BOOLEAN("GPU.GPUProcessInitialized", result
);
747 initialized_
= result
;
750 GpuDataManagerImpl::GetInstance()->OnGpuProcessInitFailure();
751 else if (!in_process_
)
752 GpuDataManagerImpl::GetInstance()->UpdateGpuInfo(gpu_info
);
755 void GpuProcessHost::OnChannelEstablished(
756 const IPC::ChannelHandle
& channel_handle
) {
757 TRACE_EVENT0("gpu", "GpuProcessHost::OnChannelEstablished");
759 if (channel_requests_
.empty()) {
760 // This happens when GPU process is compromised.
761 RouteOnUIThread(GpuHostMsg_OnLogMessage(
762 logging::LOG_WARNING
,
764 "Received a ChannelEstablished message but no requests in queue."));
767 EstablishChannelCallback callback
= channel_requests_
.front();
768 channel_requests_
.pop();
770 // Currently if any of the GPU features are blacklisted, we don't establish a
772 if (!channel_handle
.name
.empty() &&
773 !GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL
)) {
774 Send(new GpuMsg_CloseChannel(channel_handle
));
775 callback
.Run(IPC::ChannelHandle(), gpu::GPUInfo());
776 RouteOnUIThread(GpuHostMsg_OnLogMessage(
777 logging::LOG_WARNING
,
779 "Hardware acceleration is unavailable."));
783 callback
.Run(channel_handle
,
784 GpuDataManagerImpl::GetInstance()->GetGPUInfo());
787 void GpuProcessHost::OnCommandBufferCreated(CreateCommandBufferResult result
) {
788 TRACE_EVENT0("gpu", "GpuProcessHost::OnCommandBufferCreated");
790 if (create_command_buffer_requests_
.empty())
793 CreateCommandBufferCallback callback
=
794 create_command_buffer_requests_
.front();
795 create_command_buffer_requests_
.pop();
796 callback
.Run(result
);
799 void GpuProcessHost::OnDestroyCommandBuffer(int32 surface_id
) {
800 TRACE_EVENT0("gpu", "GpuProcessHost::OnDestroyCommandBuffer");
801 SurfaceRefMap::iterator it
= surface_refs_
.find(surface_id
);
802 if (it
!= surface_refs_
.end()) {
803 surface_refs_
.erase(it
);
807 void GpuProcessHost::OnGpuMemoryBufferCreated(
808 const gfx::GpuMemoryBufferHandle
& handle
) {
809 TRACE_EVENT0("gpu", "GpuProcessHost::OnGpuMemoryBufferCreated");
811 if (create_gpu_memory_buffer_requests_
.empty())
814 CreateGpuMemoryBufferCallback callback
=
815 create_gpu_memory_buffer_requests_
.front();
816 create_gpu_memory_buffer_requests_
.pop();
817 callback
.Run(handle
);
819 int32 surface_id
= create_gpu_memory_buffer_surface_refs_
.front();
820 create_gpu_memory_buffer_surface_refs_
.pop();
821 SurfaceRefMap::iterator it
= surface_refs_
.find(surface_id
);
822 if (it
!= surface_refs_
.end()) {
823 surface_refs_
.erase(it
);
827 void GpuProcessHost::OnDidCreateOffscreenContext(const GURL
& url
) {
828 urls_with_live_offscreen_contexts_
.insert(url
);
831 void GpuProcessHost::OnDidLoseContext(bool offscreen
,
832 gpu::error::ContextLostReason reason
,
834 // TODO(kbr): would be nice to see the "offscreen" flag too.
835 TRACE_EVENT2("gpu", "GpuProcessHost::OnDidLoseContext",
838 url
.possibly_invalid_spec());
840 if (!offscreen
|| url
.is_empty()) {
841 // Assume that the loss of the compositor's or accelerated canvas'
842 // context is a serious event and blame the loss on all live
843 // offscreen contexts. This more robustly handles situations where
844 // the GPU process may not actually detect the context loss in the
845 // offscreen context.
846 BlockLiveOffscreenContexts();
850 GpuDataManagerImpl::DomainGuilt guilt
;
852 case gpu::error::kGuilty
:
853 guilt
= GpuDataManagerImpl::DOMAIN_GUILT_KNOWN
;
855 case gpu::error::kUnknown
:
856 guilt
= GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN
;
858 case gpu::error::kInnocent
:
865 GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(url
, guilt
);
868 void GpuProcessHost::OnDidDestroyOffscreenContext(const GURL
& url
) {
869 urls_with_live_offscreen_contexts_
.erase(url
);
872 void GpuProcessHost::OnGpuMemoryUmaStatsReceived(
873 const GPUMemoryUmaStats
& stats
) {
874 TRACE_EVENT0("gpu", "GpuProcessHost::OnGpuMemoryUmaStatsReceived");
875 uma_memory_stats_received_
= true;
876 uma_memory_stats_
= stats
;
879 #if defined(OS_MACOSX)
880 void GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped(
881 const IPC::Message
& message
) {
882 RenderWidgetResizeHelper::Get()->PostGpuProcessMsg(host_id_
, message
);
886 void GpuProcessHost::OnProcessLaunched() {
887 UMA_HISTOGRAM_TIMES("GPU.GPUProcessLaunchTime",
888 base::TimeTicks::Now() - init_start_time_
);
891 void GpuProcessHost::OnProcessLaunchFailed() {
892 RecordProcessCrash();
895 void GpuProcessHost::OnProcessCrashed(int exit_code
) {
896 SendOutstandingReplies();
897 RecordProcessCrash();
898 GpuDataManagerImpl::GetInstance()->ProcessCrashed(
899 process_
->GetTerminationStatus(true /* known_dead */, NULL
));
902 GpuProcessHost::GpuProcessKind
GpuProcessHost::kind() {
906 void GpuProcessHost::ForceShutdown() {
907 // This is only called on the IO thread so no race against the constructor
908 // for another GpuProcessHost.
909 if (g_gpu_process_hosts
[kind_
] == this)
910 g_gpu_process_hosts
[kind_
] = NULL
;
912 #if defined(OS_MACOSX) && !defined(OS_IOS)
913 if (!io_surface_manager_token_
.IsZero()) {
914 BrowserIOSurfaceManager::GetInstance()->InvalidateGpuProcessToken();
915 io_surface_manager_token_
.SetZero();
919 process_
->ForceShutdown();
922 void GpuProcessHost::StopGpuProcess() {
923 Send(new GpuMsg_Finalize());
926 void GpuProcessHost::BeginFrameSubscription(
928 base::WeakPtr
<RenderWidgetHostViewFrameSubscriber
> subscriber
) {
929 frame_subscribers_
[surface_id
] = subscriber
;
932 void GpuProcessHost::EndFrameSubscription(int surface_id
) {
933 frame_subscribers_
.erase(surface_id
);
936 bool GpuProcessHost::LaunchGpuProcess(const std::string
& channel_id
) {
937 if (!(gpu_enabled_
&&
938 GpuDataManagerImpl::GetInstance()->ShouldUseSwiftShader()) &&
939 !hardware_gpu_enabled_
) {
940 SendOutstandingReplies();
944 const base::CommandLine
& browser_command_line
=
945 *base::CommandLine::ForCurrentProcess();
947 base::CommandLine::StringType gpu_launcher
=
948 browser_command_line
.GetSwitchValueNative(switches::kGpuLauncher
);
950 #if defined(OS_ANDROID)
951 // crbug.com/447735. readlink("self/proc/exe") sometimes fails on Android
952 // at startup with EACCES. As a workaround ignore this here, since the
953 // executable name is actually not used or useful anyways.
954 base::CommandLine
* cmd_line
=
955 new base::CommandLine(base::CommandLine::NO_PROGRAM
);
957 #if defined(OS_LINUX)
958 int child_flags
= gpu_launcher
.empty() ? ChildProcessHost::CHILD_ALLOW_SELF
:
959 ChildProcessHost::CHILD_NORMAL
;
961 int child_flags
= ChildProcessHost::CHILD_NORMAL
;
964 base::FilePath exe_path
= ChildProcessHost::GetChildPath(child_flags
);
965 if (exe_path
.empty())
968 base::CommandLine
* cmd_line
= new base::CommandLine(exe_path
);
970 cmd_line
->AppendSwitchASCII(switches::kProcessType
, switches::kGpuProcess
);
971 cmd_line
->AppendSwitchASCII(switches::kProcessChannelID
, channel_id
);
973 if (kind_
== GPU_PROCESS_KIND_UNSANDBOXED
)
974 cmd_line
->AppendSwitch(switches::kDisableGpuSandbox
);
976 // If you want a browser command-line switch passed to the GPU process
977 // you need to add it to |kSwitchNames| at the beginning of this file.
978 cmd_line
->CopySwitchesFrom(browser_command_line
, kSwitchNames
,
979 arraysize(kSwitchNames
));
980 cmd_line
->CopySwitchesFrom(
981 browser_command_line
, switches::kGpuSwitches
, switches::kNumGpuSwitches
);
982 cmd_line
->CopySwitchesFrom(
983 browser_command_line
, switches::kGLSwitchesCopiedFromGpuProcessHost
,
984 switches::kGLSwitchesCopiedFromGpuProcessHostNumSwitches
);
986 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
987 cmd_line
, process_
->GetData().id
);
989 GpuDataManagerImpl::GetInstance()->AppendGpuCommandLine(cmd_line
);
991 if (cmd_line
->HasSwitch(switches::kUseGL
)) {
992 swiftshader_rendering_
=
993 (cmd_line
->GetSwitchValueASCII(switches::kUseGL
) == "swiftshader");
996 UMA_HISTOGRAM_BOOLEAN("GPU.GPU.GPUProcessSoftwareRendering",
997 swiftshader_rendering_
);
999 // If specified, prepend a launcher program to the command line.
1000 if (!gpu_launcher
.empty())
1001 cmd_line
->PrependWrapper(gpu_launcher
);
1004 new GpuSandboxedProcessLauncherDelegate(cmd_line
,
1005 process_
->GetHost()),
1008 process_launched_
= true;
1010 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
1011 LAUNCHED
, GPU_PROCESS_LIFETIME_EVENT_MAX
);
1015 void GpuProcessHost::SendOutstandingReplies() {
1017 // First send empty channel handles for all EstablishChannel requests.
1018 while (!channel_requests_
.empty()) {
1019 EstablishChannelCallback callback
= channel_requests_
.front();
1020 channel_requests_
.pop();
1021 callback
.Run(IPC::ChannelHandle(), gpu::GPUInfo());
1024 while (!create_command_buffer_requests_
.empty()) {
1025 CreateCommandBufferCallback callback
=
1026 create_command_buffer_requests_
.front();
1027 create_command_buffer_requests_
.pop();
1028 callback
.Run(CREATE_COMMAND_BUFFER_FAILED_AND_CHANNEL_LOST
);
1031 while (!create_gpu_memory_buffer_requests_
.empty()) {
1032 CreateGpuMemoryBufferCallback callback
=
1033 create_gpu_memory_buffer_requests_
.front();
1034 create_gpu_memory_buffer_requests_
.pop();
1035 callback
.Run(gfx::GpuMemoryBufferHandle());
1039 void GpuProcessHost::BlockLiveOffscreenContexts() {
1040 for (std::multiset
<GURL
>::iterator iter
=
1041 urls_with_live_offscreen_contexts_
.begin();
1042 iter
!= urls_with_live_offscreen_contexts_
.end(); ++iter
) {
1043 GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(
1044 *iter
, GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN
);
1048 void GpuProcessHost::RecordProcessCrash() {
1049 // Maximum number of times the GPU process is allowed to crash in a session.
1050 // Once this limit is reached, any request to launch the GPU process will
1052 const int kGpuMaxCrashCount
= 3;
1054 // Last time the GPU process crashed.
1055 static base::Time last_gpu_crash_time
;
1057 bool disable_crash_limit
= base::CommandLine::ForCurrentProcess()->HasSwitch(
1058 switches::kDisableGpuProcessCrashLimit
);
1060 // Ending only acts as a failure if the GPU process was actually started and
1061 // was intended for actual rendering (and not just checking caps or other
1063 if (process_launched_
&& kind_
== GPU_PROCESS_KIND_SANDBOXED
) {
1064 if (swiftshader_rendering_
) {
1065 UMA_HISTOGRAM_ENUMERATION("GPU.SwiftShaderLifetimeEvents",
1066 DIED_FIRST_TIME
+ swiftshader_crash_count_
,
1067 GPU_PROCESS_LIFETIME_EVENT_MAX
);
1069 if (++swiftshader_crash_count_
>= kGpuMaxCrashCount
&&
1070 !disable_crash_limit
) {
1071 // SwiftShader is too unstable to use. Disable it for current session.
1072 gpu_enabled_
= false;
1076 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
1077 std::min(DIED_FIRST_TIME
+ gpu_crash_count_
,
1078 GPU_PROCESS_LIFETIME_EVENT_MAX
- 1),
1079 GPU_PROCESS_LIFETIME_EVENT_MAX
);
1081 // Allow about 1 GPU crash per hour to be removed from the crash count,
1082 // so very occasional crashes won't eventually add up and prevent the
1083 // GPU process from launching.
1084 ++gpu_recent_crash_count_
;
1085 base::Time current_time
= base::Time::Now();
1086 if (crashed_before_
) {
1087 int hours_different
= (current_time
- last_gpu_crash_time
).InHours();
1088 gpu_recent_crash_count_
=
1089 std::max(0, gpu_recent_crash_count_
- hours_different
);
1092 crashed_before_
= true;
1093 last_gpu_crash_time
= current_time
;
1095 if ((gpu_recent_crash_count_
>= kGpuMaxCrashCount
&&
1096 !disable_crash_limit
) ||
1098 #if !defined(OS_CHROMEOS)
1099 // The GPU process is too unstable to use. Disable it for current
1101 hardware_gpu_enabled_
= false;
1102 GpuDataManagerImpl::GetInstance()->DisableHardwareAcceleration();
1109 std::string
GpuProcessHost::GetShaderPrefixKey() {
1110 if (shader_prefix_key_
.empty()) {
1111 gpu::GPUInfo info
= GpuDataManagerImpl::GetInstance()->GetGPUInfo();
1113 std::string in_str
= GetContentClient()->GetProduct() + "-" +
1114 #if defined(OS_ANDROID)
1115 base::android::BuildInfo::GetInstance()->android_build_fp() + "-" +
1117 info
.gl_vendor
+ "-" + info
.gl_renderer
+ "-" +
1118 info
.driver_version
+ "-" + info
.driver_vendor
;
1120 base::Base64Encode(base::SHA1HashString(in_str
), &shader_prefix_key_
);
1123 return shader_prefix_key_
;
1126 void GpuProcessHost::LoadedShader(const std::string
& key
,
1127 const std::string
& data
) {
1128 std::string prefix
= GetShaderPrefixKey();
1129 if (!key
.compare(0, prefix
.length(), prefix
))
1130 Send(new GpuMsg_LoadedShader(data
));
1133 void GpuProcessHost::CreateChannelCache(int32 client_id
) {
1134 TRACE_EVENT0("gpu", "GpuProcessHost::CreateChannelCache");
1136 scoped_refptr
<ShaderDiskCache
> cache
=
1137 ShaderCacheFactory::GetInstance()->Get(client_id
);
1141 cache
->set_host_id(host_id_
);
1143 client_id_to_shader_cache_
[client_id
] = cache
;
1146 void GpuProcessHost::OnDestroyChannel(int32 client_id
) {
1147 TRACE_EVENT0("gpu", "GpuProcessHost::OnDestroyChannel");
1148 client_id_to_shader_cache_
.erase(client_id
);
1151 void GpuProcessHost::OnCacheShader(int32 client_id
,
1152 const std::string
& key
,
1153 const std::string
& shader
) {
1154 TRACE_EVENT0("gpu", "GpuProcessHost::OnCacheShader");
1155 ClientIdToShaderCacheMap::iterator iter
=
1156 client_id_to_shader_cache_
.find(client_id
);
1157 // If the cache doesn't exist then this is an off the record profile.
1158 if (iter
== client_id_to_shader_cache_
.end())
1160 iter
->second
->Cache(GetShaderPrefixKey() + ":" + key
, shader
);
1163 } // namespace content