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 "content/browser/browser_child_process_host_impl.h"
20 #include "content/browser/gpu/compositor_util.h"
21 #include "content/browser/gpu/gpu_data_manager_impl.h"
22 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
23 #include "content/browser/gpu/shader_disk_cache.h"
24 #include "content/browser/renderer_host/render_widget_host_impl.h"
25 #include "content/browser/renderer_host/render_widget_resize_helper.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"
75 bool GpuProcessHost::gpu_enabled_
= true;
76 bool GpuProcessHost::hardware_gpu_enabled_
= true;
77 int GpuProcessHost::gpu_crash_count_
= 0;
78 int GpuProcessHost::gpu_recent_crash_count_
= 0;
79 bool GpuProcessHost::crashed_before_
= false;
80 int GpuProcessHost::swiftshader_crash_count_
= 0;
84 // Command-line switches to propagate to the GPU process.
85 static const char* const kSwitchNames
[] = {
86 switches::kDisableAcceleratedVideoDecode
,
87 switches::kDisableBreakpad
,
88 switches::kDisableGpuSandbox
,
89 switches::kDisableGpuWatchdog
,
90 switches::kDisableGLExtensions
,
91 switches::kDisableLogging
,
92 switches::kDisableSeccompFilterSandbox
,
93 #if defined(ENABLE_WEBRTC)
94 switches::kDisableWebRtcHWEncoding
,
97 switches::kEnableAcceleratedVpxDecode
,
99 switches::kEnableLogging
,
100 switches::kEnableShareGroupAsyncTextureUpload
,
101 #if defined(OS_CHROMEOS)
102 switches::kDisableVaapiAcceleratedVideoEncode
,
104 switches::kGpuStartupDialog
,
105 switches::kGpuSandboxAllowSysVShm
,
106 switches::kGpuSandboxFailuresFatal
,
107 switches::kGpuSandboxStartEarly
,
108 switches::kLoggingLevel
,
109 switches::kEnableLowEndDeviceMode
,
110 switches::kDisableLowEndDeviceMode
,
111 switches::kNoSandbox
,
112 switches::kProfilerTiming
,
113 switches::kTestGLLib
,
114 switches::kTraceStartup
,
115 switches::kTraceToConsole
,
118 #if defined(OS_MACOSX)
119 switches::kDisableRemoteCoreAnimation
,
120 switches::kDisableNSCGLSurfaceApi
,
121 switches::kForceNSCGLSurfaceApi
,
122 switches::kEnableSandboxLogging
,
124 #if defined(USE_AURA)
125 switches::kUIPrioritizeInGpuProcess
,
127 #if defined(USE_OZONE)
128 switches::kOzonePlatform
,
129 switches::kOzoneUseSurfaceless
,
131 #if defined(USE_X11) && !defined(OS_CHROMEOS)
132 switches::kX11Display
,
136 enum GPUProcessLifetimeEvent
{
142 GPU_PROCESS_LIFETIME_EVENT_MAX
= 100
145 // Indexed by GpuProcessKind. There is one of each kind maximum. This array may
146 // only be accessed from the IO thread.
147 GpuProcessHost
* g_gpu_process_hosts
[GpuProcessHost::GPU_PROCESS_KIND_COUNT
];
150 void SendGpuProcessMessage(GpuProcessHost::GpuProcessKind kind
,
151 CauseForGpuLaunch cause
,
152 IPC::Message
* message
) {
153 GpuProcessHost
* host
= GpuProcessHost::Get(kind
, cause
);
161 // NOTE: changes to this class need to be reviewed by the security team.
162 class GpuSandboxedProcessLauncherDelegate
163 : public SandboxedProcessLauncherDelegate
{
165 GpuSandboxedProcessLauncherDelegate(base::CommandLine
* cmd_line
,
166 ChildProcessHost
* host
)
168 : cmd_line_(cmd_line
) {}
169 #elif defined(OS_POSIX)
170 : ipc_fd_(host
->TakeClientFileDescriptor()) {}
173 ~GpuSandboxedProcessLauncherDelegate() override
{}
176 bool ShouldSandbox() override
{
177 bool sandbox
= !cmd_line_
->HasSwitch(switches::kDisableGpuSandbox
);
179 DVLOG(1) << "GPU sandbox is disabled";
184 void PreSandbox(bool* disable_default_policy
,
185 base::FilePath
* exposed_dir
) override
{
186 *disable_default_policy
= true;
189 // For the GPU process we gotten as far as USER_LIMITED. The next level
190 // which is USER_RESTRICTED breaks both the DirectX backend and the OpenGL
191 // backend. Note that the GPU process is connected to the interactive
193 void PreSpawnTarget(sandbox::TargetPolicy
* policy
, bool* success
) override
{
194 if (base::win::GetVersion() > base::win::VERSION_XP
) {
195 if (cmd_line_
->GetSwitchValueASCII(switches::kUseGL
) ==
196 gfx::kGLImplementationDesktopName
) {
198 policy
->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS
,
199 sandbox::USER_LIMITED
);
200 SetJobLevel(*cmd_line_
, sandbox::JOB_UNPROTECTED
, 0, policy
);
201 policy
->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW
);
203 policy
->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS
,
204 sandbox::USER_LIMITED
);
206 // UI restrictions break when we access Windows from outside our job.
207 // However, we don't want a proxy window in this process because it can
208 // introduce deadlocks where the renderer blocks on the gpu, which in
209 // turn blocks on the browser UI thread. So, instead we forgo a window
210 // message pump entirely and just add job restrictions to prevent child
212 SetJobLevel(*cmd_line_
,
213 sandbox::JOB_LIMITED_USER
,
214 JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS
|
215 JOB_OBJECT_UILIMIT_DESKTOP
|
216 JOB_OBJECT_UILIMIT_EXITWINDOWS
|
217 JOB_OBJECT_UILIMIT_DISPLAYSETTINGS
,
220 policy
->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW
);
223 SetJobLevel(*cmd_line_
, sandbox::JOB_UNPROTECTED
, 0, policy
);
224 policy
->SetTokenLevel(sandbox::USER_UNPROTECTED
,
225 sandbox::USER_LIMITED
);
228 // Allow the server side of GPU sockets, which are pipes that have
229 // the "chrome.gpu" namespace and an arbitrary suffix.
230 sandbox::ResultCode result
= policy
->AddRule(
231 sandbox::TargetPolicy::SUBSYS_NAMED_PIPES
,
232 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY
,
233 L
"\\\\.\\pipe\\chrome.gpu.*");
234 if (result
!= sandbox::SBOX_ALL_OK
) {
239 // Block this DLL even if it is not loaded by the browser process.
240 policy
->AddDllToUnload(L
"cmsetac.dll");
243 // GPU also needs to add sections to the browser for aura
244 // TODO(jschuh): refactor the GPU channel to remove this. crbug.com/128786
245 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES
,
246 sandbox::TargetPolicy::HANDLES_DUP_BROKER
,
248 if (result
!= sandbox::SBOX_ALL_OK
) {
254 if (cmd_line_
->HasSwitch(switches::kEnableLogging
)) {
255 base::string16 log_file_path
= logging::GetLogFileFullPath();
256 if (!log_file_path
.empty()) {
257 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_FILES
,
258 sandbox::TargetPolicy::FILES_ALLOW_ANY
,
259 log_file_path
.c_str());
260 if (result
!= sandbox::SBOX_ALL_OK
) {
267 #elif defined(OS_POSIX)
269 base::ScopedFD
TakeIpcFd() override
{ return ipc_fd_
.Pass(); }
272 SandboxType
GetSandboxType() override
{
273 return SANDBOX_TYPE_GPU
;
278 base::CommandLine
* cmd_line_
;
279 #elif defined(OS_POSIX)
280 base::ScopedFD ipc_fd_
;
284 } // anonymous namespace
287 bool GpuProcessHost::ValidateHost(GpuProcessHost
* host
) {
288 // The Gpu process is invalid if it's not using SwiftShader, the card is
289 // blacklisted, and we can kill it and start over.
290 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
291 switches::kSingleProcess
) ||
292 base::CommandLine::ForCurrentProcess()->HasSwitch(
293 switches::kInProcessGPU
) ||
295 (host
->swiftshader_rendering_
||
296 !GpuDataManagerImpl::GetInstance()->ShouldUseSwiftShader()))) {
300 host
->ForceShutdown();
305 GpuProcessHost
* GpuProcessHost::Get(GpuProcessKind kind
,
306 CauseForGpuLaunch cause
) {
307 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
309 // Don't grant further access to GPU if it is not allowed.
310 GpuDataManagerImpl
* gpu_data_manager
= GpuDataManagerImpl::GetInstance();
311 DCHECK(gpu_data_manager
);
312 if (!gpu_data_manager
->GpuAccessAllowed(NULL
))
315 if (g_gpu_process_hosts
[kind
] && ValidateHost(g_gpu_process_hosts
[kind
]))
316 return g_gpu_process_hosts
[kind
];
318 if (cause
== CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH
)
321 static int last_host_id
= 0;
323 host_id
= ++last_host_id
;
325 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLaunchCause",
327 CAUSE_FOR_GPU_LAUNCH_MAX_ENUM
);
329 GpuProcessHost
* host
= new GpuProcessHost(host_id
, kind
);
333 // TODO(sievers): Revisit this behavior. It's not really a crash, but we also
334 // want the fallback-to-sw behavior if we cannot initialize the GPU.
335 host
->RecordProcessCrash();
342 void GpuProcessHost::GetProcessHandles(
343 const GpuDataManager::GetGpuProcessHandlesCallback
& callback
) {
344 if (!BrowserThread::CurrentlyOn(BrowserThread::IO
)) {
345 BrowserThread::PostTask(
348 base::Bind(&GpuProcessHost::GetProcessHandles
, callback
));
351 std::list
<base::ProcessHandle
> handles
;
352 for (size_t i
= 0; i
< arraysize(g_gpu_process_hosts
); ++i
) {
353 // TODO(rvargas) crbug/417532: don't store ProcessHandles!.
354 GpuProcessHost
* host
= g_gpu_process_hosts
[i
];
355 if (host
&& ValidateHost(host
))
356 handles
.push_back(host
->process_
->GetProcess().Handle());
358 BrowserThread::PostTask(
361 base::Bind(callback
, handles
));
365 void GpuProcessHost::SendOnIO(GpuProcessKind kind
,
366 CauseForGpuLaunch cause
,
367 IPC::Message
* message
) {
368 if (!BrowserThread::PostTask(
369 BrowserThread::IO
, FROM_HERE
,
371 &SendGpuProcessMessage
, kind
, cause
, message
))) {
376 GpuMainThreadFactoryFunction g_gpu_main_thread_factory
= NULL
;
378 void GpuProcessHost::RegisterGpuMainThreadFactory(
379 GpuMainThreadFactoryFunction create
) {
380 g_gpu_main_thread_factory
= create
;
384 GpuProcessHost
* GpuProcessHost::FromID(int host_id
) {
385 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
387 for (int i
= 0; i
< GPU_PROCESS_KIND_COUNT
; ++i
) {
388 GpuProcessHost
* host
= g_gpu_process_hosts
[i
];
389 if (host
&& host
->host_id_
== host_id
&& ValidateHost(host
))
396 GpuProcessHost::GpuProcessHost(int host_id
, GpuProcessKind kind
)
400 swiftshader_rendering_(false),
402 process_launched_(false),
404 uma_memory_stats_received_(false) {
405 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
406 switches::kSingleProcess
) ||
407 base::CommandLine::ForCurrentProcess()->HasSwitch(
408 switches::kInProcessGPU
)) {
412 // If the 'single GPU process' policy ever changes, we still want to maintain
413 // it for 'gpu thread' mode and only create one instance of host and thread.
414 DCHECK(!in_process_
|| g_gpu_process_hosts
[kind
] == NULL
);
416 g_gpu_process_hosts
[kind
] = this;
418 // Post a task to create the corresponding GpuProcessHostUIShim. The
419 // GpuProcessHostUIShim will be destroyed if either the browser exits,
420 // in which case it calls GpuProcessHostUIShim::DestroyAll, or the
421 // GpuProcessHost is destroyed, which happens when the corresponding GPU
422 // process terminates or fails to launch.
423 BrowserThread::PostTask(
426 base::Bind(base::IgnoreResult(&GpuProcessHostUIShim::Create
), host_id
));
428 process_
.reset(new BrowserChildProcessHostImpl(PROCESS_TYPE_GPU
, this));
431 GpuProcessHost::~GpuProcessHost() {
432 DCHECK(CalledOnValidThread());
434 SendOutstandingReplies();
436 // In case we never started, clean up.
437 while (!queued_messages_
.empty()) {
438 delete queued_messages_
.front();
439 queued_messages_
.pop();
442 #if defined(OS_MACOSX) && !defined(OS_IOS)
443 if (!io_surface_manager_token_
.IsZero()) {
444 BrowserIOSurfaceManager::GetInstance()->InvalidateGpuProcessToken();
445 io_surface_manager_token_
.SetZero();
449 // This is only called on the IO thread so no race against the constructor
450 // for another GpuProcessHost.
451 if (g_gpu_process_hosts
[kind_
] == this)
452 g_gpu_process_hosts
[kind_
] = NULL
;
454 // If there are any remaining offscreen contexts at the point the
455 // GPU process exits, assume something went wrong, and block their
456 // URLs from accessing client 3D APIs without prompting.
457 BlockLiveOffscreenContexts();
459 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitSurfaceCount",
460 GpuSurfaceTracker::Get()->GetSurfaceCount());
461 UMA_HISTOGRAM_BOOLEAN("GPU.AtExitReceivedMemoryStats",
462 uma_memory_stats_received_
);
464 if (uma_memory_stats_received_
) {
465 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitManagedMemoryClientCount",
466 uma_memory_stats_
.client_count
);
467 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitContextGroupCount",
468 uma_memory_stats_
.context_group_count
);
469 UMA_HISTOGRAM_CUSTOM_COUNTS(
470 "GPU.AtExitMBytesAllocated",
471 uma_memory_stats_
.bytes_allocated_current
/ 1024 / 1024, 1, 2000, 50);
472 UMA_HISTOGRAM_CUSTOM_COUNTS(
473 "GPU.AtExitMBytesAllocatedMax",
474 uma_memory_stats_
.bytes_allocated_max
/ 1024 / 1024, 1, 2000, 50);
475 UMA_HISTOGRAM_CUSTOM_COUNTS(
476 "GPU.AtExitMBytesLimit",
477 uma_memory_stats_
.bytes_limit
/ 1024 / 1024, 1, 2000, 50);
483 base::TerminationStatus status
= process_
->GetTerminationStatus(
484 false /* known_dead */, &exit_code
);
485 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessTerminationStatus",
487 base::TERMINATION_STATUS_MAX_ENUM
);
489 if (status
== base::TERMINATION_STATUS_NORMAL_TERMINATION
||
490 status
== base::TERMINATION_STATUS_ABNORMAL_TERMINATION
) {
491 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessExitCode",
493 RESULT_CODE_LAST_CODE
);
497 case base::TERMINATION_STATUS_NORMAL_TERMINATION
:
498 message
= "The GPU process exited normally. Everything is okay.";
500 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION
:
501 message
= base::StringPrintf(
502 "The GPU process exited with code %d.",
505 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED
:
506 message
= "You killed the GPU process! Why?";
508 #if defined(OS_CHROMEOS)
509 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM
:
510 message
= "The GUP process was killed due to out of memory.";
513 case base::TERMINATION_STATUS_PROCESS_CRASHED
:
514 message
= "The GPU process crashed!";
521 BrowserThread::PostTask(BrowserThread::UI
,
523 base::Bind(&GpuProcessHostUIShim::Destroy
,
528 bool GpuProcessHost::Init() {
529 init_start_time_
= base::TimeTicks::Now();
531 TRACE_EVENT_INSTANT0("gpu", "LaunchGpuProcess", TRACE_EVENT_SCOPE_THREAD
);
533 std::string channel_id
= process_
->GetHost()->CreateChannel();
534 if (channel_id
.empty())
538 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
539 DCHECK(g_gpu_main_thread_factory
);
540 in_process_gpu_thread_
.reset(
541 g_gpu_main_thread_factory(InProcessChildThreadParams(
542 channel_id
, base::MessageLoop::current()->task_runner())));
543 base::Thread::Options options
;
545 // WGL needs to create its own window and pump messages on it.
546 options
.message_loop_type
= base::MessageLoop::TYPE_UI
;
548 in_process_gpu_thread_
->StartWithOptions(options
);
550 OnProcessLaunched(); // Fake a callback that the process is ready.
551 } else if (!LaunchGpuProcess(channel_id
)) {
555 if (!Send(new GpuMsg_Initialize()))
558 #if defined(OS_MACOSX) && !defined(OS_IOS)
559 io_surface_manager_token_
=
560 BrowserIOSurfaceManager::GetInstance()->GenerateGpuProcessToken();
561 // Note: A valid IOSurface manager token needs to be sent to the Gpu process
562 // before any GpuMemoryBuffer allocation requests can be sent.
563 Send(new ChildProcessMsg_SetIOSurfaceManagerToken(io_surface_manager_token_
));
569 void GpuProcessHost::RouteOnUIThread(const IPC::Message
& message
) {
570 BrowserThread::PostTask(
573 base::Bind(&RouteToGpuProcessHostUIShimTask
, host_id_
, message
));
576 bool GpuProcessHost::Send(IPC::Message
* msg
) {
577 DCHECK(CalledOnValidThread());
578 if (process_
->GetHost()->IsChannelOpening()) {
579 queued_messages_
.push(msg
);
583 bool result
= process_
->Send(msg
);
585 // Channel is hosed, but we may not get destroyed for a while. Send
586 // outstanding channel creation failures now so that the caller can restart
587 // with a new process/channel without waiting.
588 SendOutstandingReplies();
593 void GpuProcessHost::AddFilter(IPC::MessageFilter
* filter
) {
594 DCHECK(CalledOnValidThread());
595 process_
->GetHost()->AddFilter(filter
);
598 bool GpuProcessHost::OnMessageReceived(const IPC::Message
& message
) {
599 DCHECK(CalledOnValidThread());
600 IPC_BEGIN_MESSAGE_MAP(GpuProcessHost
, message
)
601 IPC_MESSAGE_HANDLER(GpuHostMsg_Initialized
, OnInitialized
)
602 IPC_MESSAGE_HANDLER(GpuHostMsg_ChannelEstablished
, OnChannelEstablished
)
603 IPC_MESSAGE_HANDLER(GpuHostMsg_CommandBufferCreated
, OnCommandBufferCreated
)
604 IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyCommandBuffer
, OnDestroyCommandBuffer
)
605 IPC_MESSAGE_HANDLER(GpuHostMsg_GpuMemoryBufferCreated
,
606 OnGpuMemoryBufferCreated
)
607 IPC_MESSAGE_HANDLER(GpuHostMsg_DidCreateOffscreenContext
,
608 OnDidCreateOffscreenContext
)
609 IPC_MESSAGE_HANDLER(GpuHostMsg_DidLoseContext
, OnDidLoseContext
)
610 IPC_MESSAGE_HANDLER(GpuHostMsg_DidDestroyOffscreenContext
,
611 OnDidDestroyOffscreenContext
)
612 IPC_MESSAGE_HANDLER(GpuHostMsg_GpuMemoryUmaStats
,
613 OnGpuMemoryUmaStatsReceived
)
614 #if defined(OS_MACOSX)
615 IPC_MESSAGE_HANDLER_GENERIC(GpuHostMsg_AcceleratedSurfaceBuffersSwapped
,
616 OnAcceleratedSurfaceBuffersSwapped(message
))
618 IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyChannel
,
620 IPC_MESSAGE_HANDLER(GpuHostMsg_CacheShader
,
623 IPC_MESSAGE_UNHANDLED(RouteOnUIThread(message
))
624 IPC_END_MESSAGE_MAP()
629 void GpuProcessHost::OnChannelConnected(int32 peer_pid
) {
630 TRACE_EVENT0("gpu", "GpuProcessHost::OnChannelConnected");
632 while (!queued_messages_
.empty()) {
633 Send(queued_messages_
.front());
634 queued_messages_
.pop();
638 void GpuProcessHost::EstablishGpuChannel(
640 uint64_t client_tracing_id
,
642 bool allow_future_sync_points
,
643 const EstablishChannelCallback
& callback
) {
644 DCHECK(CalledOnValidThread());
645 TRACE_EVENT0("gpu", "GpuProcessHost::EstablishGpuChannel");
647 // If GPU features are already blacklisted, no need to establish the channel.
648 if (!GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL
)) {
649 DVLOG(1) << "GPU blacklisted, refusing to open a GPU channel.";
650 callback
.Run(IPC::ChannelHandle(), gpu::GPUInfo());
654 if (Send(new GpuMsg_EstablishChannel(client_id
, client_tracing_id
,
656 allow_future_sync_points
))) {
657 channel_requests_
.push(callback
);
659 DVLOG(1) << "Failed to send GpuMsg_EstablishChannel.";
660 callback
.Run(IPC::ChannelHandle(), gpu::GPUInfo());
663 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
664 switches::kDisableGpuShaderDiskCache
)) {
665 CreateChannelCache(client_id
);
669 void GpuProcessHost::CreateViewCommandBuffer(
670 const gfx::GLSurfaceHandle
& compositing_surface
,
673 const GPUCreateCommandBufferConfig
& init_params
,
675 const CreateCommandBufferCallback
& callback
) {
676 TRACE_EVENT0("gpu", "GpuProcessHost::CreateViewCommandBuffer");
678 DCHECK(CalledOnValidThread());
680 if (!compositing_surface
.is_null() &&
681 Send(new GpuMsg_CreateViewCommandBuffer(
682 compositing_surface
, surface_id
, client_id
, init_params
, route_id
))) {
683 create_command_buffer_requests_
.push(callback
);
684 surface_refs_
.insert(std::make_pair(surface_id
,
685 GpuSurfaceTracker::GetInstance()->GetSurfaceRefForSurface(surface_id
)));
687 // Could distinguish here between compositing_surface being NULL
688 // and Send failing, if desired.
689 callback
.Run(CREATE_COMMAND_BUFFER_FAILED_AND_CHANNEL_LOST
);
693 void GpuProcessHost::CreateGpuMemoryBuffer(
694 gfx::GpuMemoryBufferId id
,
695 const gfx::Size
& size
,
696 gfx::GpuMemoryBuffer::Format format
,
697 gfx::GpuMemoryBuffer::Usage usage
,
700 const CreateGpuMemoryBufferCallback
& callback
) {
701 TRACE_EVENT0("gpu", "GpuProcessHost::CreateGpuMemoryBuffer");
703 DCHECK(CalledOnValidThread());
705 GpuMsg_CreateGpuMemoryBuffer_Params params
;
708 params
.format
= format
;
709 params
.usage
= usage
;
710 params
.client_id
= client_id
;
711 params
.surface_handle
=
712 GpuSurfaceTracker::GetInstance()->GetSurfaceHandle(surface_id
).handle
;
713 if (Send(new GpuMsg_CreateGpuMemoryBuffer(params
))) {
714 create_gpu_memory_buffer_requests_
.push(callback
);
715 create_gpu_memory_buffer_surface_refs_
.push(surface_id
);
717 surface_refs_
.insert(std::make_pair(
718 surface_id
, GpuSurfaceTracker::GetInstance()->GetSurfaceRefForSurface(
722 callback
.Run(gfx::GpuMemoryBufferHandle());
726 void GpuProcessHost::DestroyGpuMemoryBuffer(gfx::GpuMemoryBufferId id
,
729 TRACE_EVENT0("gpu", "GpuProcessHost::DestroyGpuMemoryBuffer");
731 DCHECK(CalledOnValidThread());
733 Send(new GpuMsg_DestroyGpuMemoryBuffer(id
, client_id
, sync_point
));
736 void GpuProcessHost::OnInitialized(bool result
, const gpu::GPUInfo
& gpu_info
) {
737 UMA_HISTOGRAM_BOOLEAN("GPU.GPUProcessInitialized", result
);
738 initialized_
= result
;
741 GpuDataManagerImpl::GetInstance()->OnGpuProcessInitFailure();
742 else if (!in_process_
)
743 GpuDataManagerImpl::GetInstance()->UpdateGpuInfo(gpu_info
);
746 void GpuProcessHost::OnChannelEstablished(
747 const IPC::ChannelHandle
& channel_handle
) {
748 TRACE_EVENT0("gpu", "GpuProcessHost::OnChannelEstablished");
750 if (channel_requests_
.empty()) {
751 // This happens when GPU process is compromised.
752 RouteOnUIThread(GpuHostMsg_OnLogMessage(
753 logging::LOG_WARNING
,
755 "Received a ChannelEstablished message but no requests in queue."));
758 EstablishChannelCallback callback
= channel_requests_
.front();
759 channel_requests_
.pop();
761 // Currently if any of the GPU features are blacklisted, we don't establish a
763 if (!channel_handle
.name
.empty() &&
764 !GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL
)) {
765 Send(new GpuMsg_CloseChannel(channel_handle
));
766 callback
.Run(IPC::ChannelHandle(), gpu::GPUInfo());
767 RouteOnUIThread(GpuHostMsg_OnLogMessage(
768 logging::LOG_WARNING
,
770 "Hardware acceleration is unavailable."));
774 callback
.Run(channel_handle
,
775 GpuDataManagerImpl::GetInstance()->GetGPUInfo());
778 void GpuProcessHost::OnCommandBufferCreated(CreateCommandBufferResult result
) {
779 TRACE_EVENT0("gpu", "GpuProcessHost::OnCommandBufferCreated");
781 if (create_command_buffer_requests_
.empty())
784 CreateCommandBufferCallback callback
=
785 create_command_buffer_requests_
.front();
786 create_command_buffer_requests_
.pop();
787 callback
.Run(result
);
790 void GpuProcessHost::OnDestroyCommandBuffer(int32 surface_id
) {
791 TRACE_EVENT0("gpu", "GpuProcessHost::OnDestroyCommandBuffer");
792 SurfaceRefMap::iterator it
= surface_refs_
.find(surface_id
);
793 if (it
!= surface_refs_
.end()) {
794 surface_refs_
.erase(it
);
798 void GpuProcessHost::OnGpuMemoryBufferCreated(
799 const gfx::GpuMemoryBufferHandle
& handle
) {
800 TRACE_EVENT0("gpu", "GpuProcessHost::OnGpuMemoryBufferCreated");
802 if (create_gpu_memory_buffer_requests_
.empty())
805 CreateGpuMemoryBufferCallback callback
=
806 create_gpu_memory_buffer_requests_
.front();
807 create_gpu_memory_buffer_requests_
.pop();
808 callback
.Run(handle
);
810 int32 surface_id
= create_gpu_memory_buffer_surface_refs_
.front();
811 create_gpu_memory_buffer_surface_refs_
.pop();
812 SurfaceRefMap::iterator it
= surface_refs_
.find(surface_id
);
813 if (it
!= surface_refs_
.end()) {
814 surface_refs_
.erase(it
);
818 void GpuProcessHost::OnDidCreateOffscreenContext(const GURL
& url
) {
819 urls_with_live_offscreen_contexts_
.insert(url
);
822 void GpuProcessHost::OnDidLoseContext(bool offscreen
,
823 gpu::error::ContextLostReason reason
,
825 // TODO(kbr): would be nice to see the "offscreen" flag too.
826 TRACE_EVENT2("gpu", "GpuProcessHost::OnDidLoseContext",
829 url
.possibly_invalid_spec());
831 if (!offscreen
|| url
.is_empty()) {
832 // Assume that the loss of the compositor's or accelerated canvas'
833 // context is a serious event and blame the loss on all live
834 // offscreen contexts. This more robustly handles situations where
835 // the GPU process may not actually detect the context loss in the
836 // offscreen context.
837 BlockLiveOffscreenContexts();
841 GpuDataManagerImpl::DomainGuilt guilt
;
843 case gpu::error::kGuilty
:
844 guilt
= GpuDataManagerImpl::DOMAIN_GUILT_KNOWN
;
846 case gpu::error::kUnknown
:
847 guilt
= GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN
;
849 case gpu::error::kInnocent
:
856 GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(url
, guilt
);
859 void GpuProcessHost::OnDidDestroyOffscreenContext(const GURL
& url
) {
860 urls_with_live_offscreen_contexts_
.erase(url
);
863 void GpuProcessHost::OnGpuMemoryUmaStatsReceived(
864 const GPUMemoryUmaStats
& stats
) {
865 TRACE_EVENT0("gpu", "GpuProcessHost::OnGpuMemoryUmaStatsReceived");
866 uma_memory_stats_received_
= true;
867 uma_memory_stats_
= stats
;
870 #if defined(OS_MACOSX)
871 void GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped(
872 const IPC::Message
& message
) {
873 RenderWidgetResizeHelper::Get()->PostGpuProcessMsg(host_id_
, message
);
877 void GpuProcessHost::OnProcessLaunched() {
878 UMA_HISTOGRAM_TIMES("GPU.GPUProcessLaunchTime",
879 base::TimeTicks::Now() - init_start_time_
);
882 void GpuProcessHost::OnProcessLaunchFailed() {
883 RecordProcessCrash();
886 void GpuProcessHost::OnProcessCrashed(int exit_code
) {
887 SendOutstandingReplies();
888 RecordProcessCrash();
889 GpuDataManagerImpl::GetInstance()->ProcessCrashed(
890 process_
->GetTerminationStatus(true /* known_dead */, NULL
));
893 GpuProcessHost::GpuProcessKind
GpuProcessHost::kind() {
897 void GpuProcessHost::ForceShutdown() {
898 // This is only called on the IO thread so no race against the constructor
899 // for another GpuProcessHost.
900 if (g_gpu_process_hosts
[kind_
] == this)
901 g_gpu_process_hosts
[kind_
] = NULL
;
903 #if defined(OS_MACOSX) && !defined(OS_IOS)
904 if (!io_surface_manager_token_
.IsZero()) {
905 BrowserIOSurfaceManager::GetInstance()->InvalidateGpuProcessToken();
906 io_surface_manager_token_
.SetZero();
910 process_
->ForceShutdown();
913 void GpuProcessHost::StopGpuProcess() {
914 Send(new GpuMsg_Finalize());
917 void GpuProcessHost::BeginFrameSubscription(
919 base::WeakPtr
<RenderWidgetHostViewFrameSubscriber
> subscriber
) {
920 frame_subscribers_
[surface_id
] = subscriber
;
923 void GpuProcessHost::EndFrameSubscription(int surface_id
) {
924 frame_subscribers_
.erase(surface_id
);
927 bool GpuProcessHost::LaunchGpuProcess(const std::string
& channel_id
) {
928 if (!(gpu_enabled_
&&
929 GpuDataManagerImpl::GetInstance()->ShouldUseSwiftShader()) &&
930 !hardware_gpu_enabled_
) {
931 SendOutstandingReplies();
935 const base::CommandLine
& browser_command_line
=
936 *base::CommandLine::ForCurrentProcess();
938 base::CommandLine::StringType gpu_launcher
=
939 browser_command_line
.GetSwitchValueNative(switches::kGpuLauncher
);
941 #if defined(OS_ANDROID)
942 // crbug.com/447735. readlink("self/proc/exe") sometimes fails on Android
943 // at startup with EACCES. As a workaround ignore this here, since the
944 // executable name is actually not used or useful anyways.
945 base::CommandLine
* cmd_line
=
946 new base::CommandLine(base::CommandLine::NO_PROGRAM
);
948 #if defined(OS_LINUX)
949 int child_flags
= gpu_launcher
.empty() ? ChildProcessHost::CHILD_ALLOW_SELF
:
950 ChildProcessHost::CHILD_NORMAL
;
952 int child_flags
= ChildProcessHost::CHILD_NORMAL
;
955 base::FilePath exe_path
= ChildProcessHost::GetChildPath(child_flags
);
956 if (exe_path
.empty())
959 base::CommandLine
* cmd_line
= new base::CommandLine(exe_path
);
961 cmd_line
->AppendSwitchASCII(switches::kProcessType
, switches::kGpuProcess
);
962 cmd_line
->AppendSwitchASCII(switches::kProcessChannelID
, channel_id
);
964 if (kind_
== GPU_PROCESS_KIND_UNSANDBOXED
)
965 cmd_line
->AppendSwitch(switches::kDisableGpuSandbox
);
967 // If you want a browser command-line switch passed to the GPU process
968 // you need to add it to |kSwitchNames| at the beginning of this file.
969 cmd_line
->CopySwitchesFrom(browser_command_line
, kSwitchNames
,
970 arraysize(kSwitchNames
));
971 cmd_line
->CopySwitchesFrom(
972 browser_command_line
, switches::kGpuSwitches
, switches::kNumGpuSwitches
);
973 cmd_line
->CopySwitchesFrom(
974 browser_command_line
, switches::kGLSwitchesCopiedFromGpuProcessHost
,
975 switches::kGLSwitchesCopiedFromGpuProcessHostNumSwitches
);
977 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
978 cmd_line
, process_
->GetData().id
);
980 GpuDataManagerImpl::GetInstance()->AppendGpuCommandLine(cmd_line
);
982 if (cmd_line
->HasSwitch(switches::kUseGL
)) {
983 swiftshader_rendering_
=
984 (cmd_line
->GetSwitchValueASCII(switches::kUseGL
) == "swiftshader");
987 UMA_HISTOGRAM_BOOLEAN("GPU.GPU.GPUProcessSoftwareRendering",
988 swiftshader_rendering_
);
990 // If specified, prepend a launcher program to the command line.
991 if (!gpu_launcher
.empty())
992 cmd_line
->PrependWrapper(gpu_launcher
);
995 new GpuSandboxedProcessLauncherDelegate(cmd_line
,
996 process_
->GetHost()),
999 process_launched_
= true;
1001 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
1002 LAUNCHED
, GPU_PROCESS_LIFETIME_EVENT_MAX
);
1006 void GpuProcessHost::SendOutstandingReplies() {
1008 // First send empty channel handles for all EstablishChannel requests.
1009 while (!channel_requests_
.empty()) {
1010 EstablishChannelCallback callback
= channel_requests_
.front();
1011 channel_requests_
.pop();
1012 callback
.Run(IPC::ChannelHandle(), gpu::GPUInfo());
1015 while (!create_command_buffer_requests_
.empty()) {
1016 CreateCommandBufferCallback callback
=
1017 create_command_buffer_requests_
.front();
1018 create_command_buffer_requests_
.pop();
1019 callback
.Run(CREATE_COMMAND_BUFFER_FAILED_AND_CHANNEL_LOST
);
1022 while (!create_gpu_memory_buffer_requests_
.empty()) {
1023 CreateGpuMemoryBufferCallback callback
=
1024 create_gpu_memory_buffer_requests_
.front();
1025 create_gpu_memory_buffer_requests_
.pop();
1026 callback
.Run(gfx::GpuMemoryBufferHandle());
1030 void GpuProcessHost::BlockLiveOffscreenContexts() {
1031 for (std::multiset
<GURL
>::iterator iter
=
1032 urls_with_live_offscreen_contexts_
.begin();
1033 iter
!= urls_with_live_offscreen_contexts_
.end(); ++iter
) {
1034 GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(
1035 *iter
, GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN
);
1039 void GpuProcessHost::RecordProcessCrash() {
1040 // Maximum number of times the GPU process is allowed to crash in a session.
1041 // Once this limit is reached, any request to launch the GPU process will
1043 const int kGpuMaxCrashCount
= 3;
1045 // Last time the GPU process crashed.
1046 static base::Time last_gpu_crash_time
;
1048 bool disable_crash_limit
= base::CommandLine::ForCurrentProcess()->HasSwitch(
1049 switches::kDisableGpuProcessCrashLimit
);
1051 // Ending only acts as a failure if the GPU process was actually started and
1052 // was intended for actual rendering (and not just checking caps or other
1054 if (process_launched_
&& kind_
== GPU_PROCESS_KIND_SANDBOXED
) {
1055 if (swiftshader_rendering_
) {
1056 UMA_HISTOGRAM_ENUMERATION("GPU.SwiftShaderLifetimeEvents",
1057 DIED_FIRST_TIME
+ swiftshader_crash_count_
,
1058 GPU_PROCESS_LIFETIME_EVENT_MAX
);
1060 if (++swiftshader_crash_count_
>= kGpuMaxCrashCount
&&
1061 !disable_crash_limit
) {
1062 // SwiftShader is too unstable to use. Disable it for current session.
1063 gpu_enabled_
= false;
1067 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
1068 std::min(DIED_FIRST_TIME
+ gpu_crash_count_
,
1069 GPU_PROCESS_LIFETIME_EVENT_MAX
- 1),
1070 GPU_PROCESS_LIFETIME_EVENT_MAX
);
1072 // Allow about 1 GPU crash per hour to be removed from the crash count,
1073 // so very occasional crashes won't eventually add up and prevent the
1074 // GPU process from launching.
1075 ++gpu_recent_crash_count_
;
1076 base::Time current_time
= base::Time::Now();
1077 if (crashed_before_
) {
1078 int hours_different
= (current_time
- last_gpu_crash_time
).InHours();
1079 gpu_recent_crash_count_
=
1080 std::max(0, gpu_recent_crash_count_
- hours_different
);
1083 crashed_before_
= true;
1084 last_gpu_crash_time
= current_time
;
1086 if ((gpu_recent_crash_count_
>= kGpuMaxCrashCount
&&
1087 !disable_crash_limit
) ||
1089 #if !defined(OS_CHROMEOS)
1090 // The GPU process is too unstable to use. Disable it for current
1092 hardware_gpu_enabled_
= false;
1093 GpuDataManagerImpl::GetInstance()->DisableHardwareAcceleration();
1100 std::string
GpuProcessHost::GetShaderPrefixKey() {
1101 if (shader_prefix_key_
.empty()) {
1102 gpu::GPUInfo info
= GpuDataManagerImpl::GetInstance()->GetGPUInfo();
1104 std::string in_str
= GetContentClient()->GetProduct() + "-" +
1105 #if defined(OS_ANDROID)
1106 base::android::BuildInfo::GetInstance()->android_build_fp() + "-" +
1108 info
.gl_vendor
+ "-" + info
.gl_renderer
+ "-" +
1109 info
.driver_version
+ "-" + info
.driver_vendor
;
1111 base::Base64Encode(base::SHA1HashString(in_str
), &shader_prefix_key_
);
1114 return shader_prefix_key_
;
1117 void GpuProcessHost::LoadedShader(const std::string
& key
,
1118 const std::string
& data
) {
1119 std::string prefix
= GetShaderPrefixKey();
1120 if (!key
.compare(0, prefix
.length(), prefix
))
1121 Send(new GpuMsg_LoadedShader(data
));
1124 void GpuProcessHost::CreateChannelCache(int32 client_id
) {
1125 TRACE_EVENT0("gpu", "GpuProcessHost::CreateChannelCache");
1127 scoped_refptr
<ShaderDiskCache
> cache
=
1128 ShaderCacheFactory::GetInstance()->Get(client_id
);
1132 cache
->set_host_id(host_id_
);
1134 client_id_to_shader_cache_
[client_id
] = cache
;
1137 void GpuProcessHost::OnDestroyChannel(int32 client_id
) {
1138 TRACE_EVENT0("gpu", "GpuProcessHost::OnDestroyChannel");
1139 client_id_to_shader_cache_
.erase(client_id
);
1142 void GpuProcessHost::OnCacheShader(int32 client_id
,
1143 const std::string
& key
,
1144 const std::string
& shader
) {
1145 TRACE_EVENT0("gpu", "GpuProcessHost::OnCacheShader");
1146 ClientIdToShaderCacheMap::iterator iter
=
1147 client_id_to_shader_cache_
.find(client_id
);
1148 // If the cache doesn't exist then this is an off the record profile.
1149 if (iter
== client_id_to_shader_cache_
.end())
1151 iter
->second
->Cache(GetShaderPrefixKey() + ":" + key
, shader
);
1154 } // namespace content