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
);
338 void GpuProcessHost::GetProcessHandles(
339 const GpuDataManager::GetGpuProcessHandlesCallback
& callback
) {
340 if (!BrowserThread::CurrentlyOn(BrowserThread::IO
)) {
341 BrowserThread::PostTask(
344 base::Bind(&GpuProcessHost::GetProcessHandles
, callback
));
347 std::list
<base::ProcessHandle
> handles
;
348 for (size_t i
= 0; i
< arraysize(g_gpu_process_hosts
); ++i
) {
349 // TODO(rvargas) crbug/417532: don't store ProcessHandles!.
350 GpuProcessHost
* host
= g_gpu_process_hosts
[i
];
351 if (host
&& ValidateHost(host
))
352 handles
.push_back(host
->process_
->GetProcess().Handle());
354 BrowserThread::PostTask(
357 base::Bind(callback
, handles
));
361 void GpuProcessHost::SendOnIO(GpuProcessKind kind
,
362 CauseForGpuLaunch cause
,
363 IPC::Message
* message
) {
364 if (!BrowserThread::PostTask(
365 BrowserThread::IO
, FROM_HERE
,
367 &SendGpuProcessMessage
, kind
, cause
, message
))) {
372 GpuMainThreadFactoryFunction g_gpu_main_thread_factory
= NULL
;
374 void GpuProcessHost::RegisterGpuMainThreadFactory(
375 GpuMainThreadFactoryFunction create
) {
376 g_gpu_main_thread_factory
= create
;
380 GpuProcessHost
* GpuProcessHost::FromID(int host_id
) {
381 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
383 for (int i
= 0; i
< GPU_PROCESS_KIND_COUNT
; ++i
) {
384 GpuProcessHost
* host
= g_gpu_process_hosts
[i
];
385 if (host
&& host
->host_id_
== host_id
&& ValidateHost(host
))
392 GpuProcessHost::GpuProcessHost(int host_id
, GpuProcessKind kind
)
396 swiftshader_rendering_(false),
398 process_launched_(false),
400 gpu_crash_recorded_(false),
401 uma_memory_stats_received_(false) {
402 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
403 switches::kSingleProcess
) ||
404 base::CommandLine::ForCurrentProcess()->HasSwitch(
405 switches::kInProcessGPU
)) {
409 // If the 'single GPU process' policy ever changes, we still want to maintain
410 // it for 'gpu thread' mode and only create one instance of host and thread.
411 DCHECK(!in_process_
|| g_gpu_process_hosts
[kind
] == NULL
);
413 g_gpu_process_hosts
[kind
] = this;
415 // Post a task to create the corresponding GpuProcessHostUIShim. The
416 // GpuProcessHostUIShim will be destroyed if either the browser exits,
417 // in which case it calls GpuProcessHostUIShim::DestroyAll, or the
418 // GpuProcessHost is destroyed, which happens when the corresponding GPU
419 // process terminates or fails to launch.
420 BrowserThread::PostTask(
423 base::Bind(base::IgnoreResult(&GpuProcessHostUIShim::Create
), host_id
));
425 process_
.reset(new BrowserChildProcessHostImpl(PROCESS_TYPE_GPU
, this));
428 GpuProcessHost::~GpuProcessHost() {
429 DCHECK(CalledOnValidThread());
431 SendOutstandingReplies();
433 RecordProcessCrash();
435 // In case we never started, clean up.
436 while (!queued_messages_
.empty()) {
437 delete queued_messages_
.front();
438 queued_messages_
.pop();
441 #if defined(OS_MACOSX) && !defined(OS_IOS)
442 if (!io_surface_manager_token_
.IsZero()) {
443 BrowserIOSurfaceManager::GetInstance()->InvalidateGpuProcessToken();
444 io_surface_manager_token_
.SetZero();
448 // This is only called on the IO thread so no race against the constructor
449 // for another GpuProcessHost.
450 if (g_gpu_process_hosts
[kind_
] == this)
451 g_gpu_process_hosts
[kind_
] = NULL
;
453 // If there are any remaining offscreen contexts at the point the
454 // GPU process exits, assume something went wrong, and block their
455 // URLs from accessing client 3D APIs without prompting.
456 BlockLiveOffscreenContexts();
458 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitSurfaceCount",
459 GpuSurfaceTracker::Get()->GetSurfaceCount());
460 UMA_HISTOGRAM_BOOLEAN("GPU.AtExitReceivedMemoryStats",
461 uma_memory_stats_received_
);
463 if (uma_memory_stats_received_
) {
464 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitManagedMemoryClientCount",
465 uma_memory_stats_
.client_count
);
466 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitContextGroupCount",
467 uma_memory_stats_
.context_group_count
);
468 UMA_HISTOGRAM_CUSTOM_COUNTS(
469 "GPU.AtExitMBytesAllocated",
470 uma_memory_stats_
.bytes_allocated_current
/ 1024 / 1024, 1, 2000, 50);
471 UMA_HISTOGRAM_CUSTOM_COUNTS(
472 "GPU.AtExitMBytesAllocatedMax",
473 uma_memory_stats_
.bytes_allocated_max
/ 1024 / 1024, 1, 2000, 50);
474 UMA_HISTOGRAM_CUSTOM_COUNTS(
475 "GPU.AtExitMBytesLimit",
476 uma_memory_stats_
.bytes_limit
/ 1024 / 1024, 1, 2000, 50);
482 base::TerminationStatus status
= process_
->GetTerminationStatus(
483 false /* known_dead */, &exit_code
);
484 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessTerminationStatus",
486 base::TERMINATION_STATUS_MAX_ENUM
);
488 if (status
== base::TERMINATION_STATUS_NORMAL_TERMINATION
||
489 status
== base::TERMINATION_STATUS_ABNORMAL_TERMINATION
) {
490 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessExitCode",
492 RESULT_CODE_LAST_CODE
);
496 case base::TERMINATION_STATUS_NORMAL_TERMINATION
:
497 message
= "The GPU process exited normally. Everything is okay.";
499 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION
:
500 message
= base::StringPrintf(
501 "The GPU process exited with code %d.",
504 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED
:
505 message
= "You killed the GPU process! Why?";
507 #if defined(OS_CHROMEOS)
508 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM
:
509 message
= "The GUP process was killed due to out of memory.";
512 case base::TERMINATION_STATUS_PROCESS_CRASHED
:
513 message
= "The GPU process crashed!";
520 BrowserThread::PostTask(BrowserThread::UI
,
522 base::Bind(&GpuProcessHostUIShim::Destroy
,
527 bool GpuProcessHost::Init() {
528 init_start_time_
= base::TimeTicks::Now();
530 TRACE_EVENT_INSTANT0("gpu", "LaunchGpuProcess", TRACE_EVENT_SCOPE_THREAD
);
532 std::string channel_id
= process_
->GetHost()->CreateChannel();
533 if (channel_id
.empty())
537 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
538 DCHECK(g_gpu_main_thread_factory
);
539 in_process_gpu_thread_
.reset(
540 g_gpu_main_thread_factory(InProcessChildThreadParams(
541 channel_id
, base::MessageLoop::current()->task_runner())));
542 base::Thread::Options options
;
544 // WGL needs to create its own window and pump messages on it.
545 options
.message_loop_type
= base::MessageLoop::TYPE_UI
;
547 in_process_gpu_thread_
->StartWithOptions(options
);
549 OnProcessLaunched(); // Fake a callback that the process is ready.
550 } else if (!LaunchGpuProcess(channel_id
)) {
554 if (!Send(new GpuMsg_Initialize()))
557 #if defined(OS_MACOSX) && !defined(OS_IOS)
558 io_surface_manager_token_
=
559 BrowserIOSurfaceManager::GetInstance()->GenerateGpuProcessToken();
560 // Note: A valid IOSurface manager token needs to be sent to the Gpu process
561 // before any GpuMemoryBuffer allocation requests can be sent.
562 Send(new ChildProcessMsg_SetIOSurfaceManagerToken(io_surface_manager_token_
));
568 void GpuProcessHost::RouteOnUIThread(const IPC::Message
& message
) {
569 BrowserThread::PostTask(
572 base::Bind(&RouteToGpuProcessHostUIShimTask
, host_id_
, message
));
575 bool GpuProcessHost::Send(IPC::Message
* msg
) {
576 DCHECK(CalledOnValidThread());
577 if (process_
->GetHost()->IsChannelOpening()) {
578 queued_messages_
.push(msg
);
582 bool result
= process_
->Send(msg
);
584 // Channel is hosed, but we may not get destroyed for a while. Send
585 // outstanding channel creation failures now so that the caller can restart
586 // with a new process/channel without waiting.
587 SendOutstandingReplies();
592 void GpuProcessHost::AddFilter(IPC::MessageFilter
* filter
) {
593 DCHECK(CalledOnValidThread());
594 process_
->GetHost()->AddFilter(filter
);
597 bool GpuProcessHost::OnMessageReceived(const IPC::Message
& message
) {
598 DCHECK(CalledOnValidThread());
599 IPC_BEGIN_MESSAGE_MAP(GpuProcessHost
, message
)
600 IPC_MESSAGE_HANDLER(GpuHostMsg_Initialized
, OnInitialized
)
601 IPC_MESSAGE_HANDLER(GpuHostMsg_ChannelEstablished
, OnChannelEstablished
)
602 IPC_MESSAGE_HANDLER(GpuHostMsg_CommandBufferCreated
, OnCommandBufferCreated
)
603 IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyCommandBuffer
, OnDestroyCommandBuffer
)
604 IPC_MESSAGE_HANDLER(GpuHostMsg_GpuMemoryBufferCreated
,
605 OnGpuMemoryBufferCreated
)
606 IPC_MESSAGE_HANDLER(GpuHostMsg_DidCreateOffscreenContext
,
607 OnDidCreateOffscreenContext
)
608 IPC_MESSAGE_HANDLER(GpuHostMsg_DidLoseContext
, OnDidLoseContext
)
609 IPC_MESSAGE_HANDLER(GpuHostMsg_DidDestroyOffscreenContext
,
610 OnDidDestroyOffscreenContext
)
611 IPC_MESSAGE_HANDLER(GpuHostMsg_GpuMemoryUmaStats
,
612 OnGpuMemoryUmaStatsReceived
)
613 #if defined(OS_MACOSX)
614 IPC_MESSAGE_HANDLER_GENERIC(GpuHostMsg_AcceleratedSurfaceBuffersSwapped
,
615 OnAcceleratedSurfaceBuffersSwapped(message
))
617 IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyChannel
,
619 IPC_MESSAGE_HANDLER(GpuHostMsg_CacheShader
,
622 IPC_MESSAGE_UNHANDLED(RouteOnUIThread(message
))
623 IPC_END_MESSAGE_MAP()
628 void GpuProcessHost::OnChannelConnected(int32 peer_pid
) {
629 TRACE_EVENT0("gpu", "GpuProcessHost::OnChannelConnected");
631 while (!queued_messages_
.empty()) {
632 Send(queued_messages_
.front());
633 queued_messages_
.pop();
637 void GpuProcessHost::EstablishGpuChannel(
640 bool allow_future_sync_points
,
641 const EstablishChannelCallback
& callback
) {
642 DCHECK(CalledOnValidThread());
643 TRACE_EVENT0("gpu", "GpuProcessHost::EstablishGpuChannel");
645 // If GPU features are already blacklisted, no need to establish the channel.
646 if (!GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL
)) {
647 DVLOG(1) << "GPU blacklisted, refusing to open a GPU channel.";
648 callback
.Run(IPC::ChannelHandle(), gpu::GPUInfo());
652 if (Send(new GpuMsg_EstablishChannel(
653 client_id
, share_context
, allow_future_sync_points
))) {
654 channel_requests_
.push(callback
);
656 DVLOG(1) << "Failed to send GpuMsg_EstablishChannel.";
657 callback
.Run(IPC::ChannelHandle(), gpu::GPUInfo());
660 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
661 switches::kDisableGpuShaderDiskCache
)) {
662 CreateChannelCache(client_id
);
666 void GpuProcessHost::CreateViewCommandBuffer(
667 const gfx::GLSurfaceHandle
& compositing_surface
,
670 const GPUCreateCommandBufferConfig
& init_params
,
672 const CreateCommandBufferCallback
& callback
) {
673 TRACE_EVENT0("gpu", "GpuProcessHost::CreateViewCommandBuffer");
675 DCHECK(CalledOnValidThread());
677 if (!compositing_surface
.is_null() &&
678 Send(new GpuMsg_CreateViewCommandBuffer(
679 compositing_surface
, surface_id
, client_id
, init_params
, route_id
))) {
680 create_command_buffer_requests_
.push(callback
);
681 surface_refs_
.insert(std::make_pair(surface_id
,
682 GpuSurfaceTracker::GetInstance()->GetSurfaceRefForSurface(surface_id
)));
684 // Could distinguish here between compositing_surface being NULL
685 // and Send failing, if desired.
686 callback
.Run(CREATE_COMMAND_BUFFER_FAILED_AND_CHANNEL_LOST
);
690 void GpuProcessHost::CreateGpuMemoryBuffer(
691 gfx::GpuMemoryBufferId id
,
692 const gfx::Size
& size
,
693 gfx::GpuMemoryBuffer::Format format
,
694 gfx::GpuMemoryBuffer::Usage usage
,
697 const CreateGpuMemoryBufferCallback
& callback
) {
698 TRACE_EVENT0("gpu", "GpuProcessHost::CreateGpuMemoryBuffer");
700 DCHECK(CalledOnValidThread());
702 GpuMsg_CreateGpuMemoryBuffer_Params params
;
705 params
.format
= format
;
706 params
.usage
= usage
;
707 params
.client_id
= client_id
;
708 params
.surface_handle
=
709 GpuSurfaceTracker::GetInstance()->GetSurfaceHandle(surface_id
).handle
;
710 if (Send(new GpuMsg_CreateGpuMemoryBuffer(params
))) {
711 create_gpu_memory_buffer_requests_
.push(callback
);
712 create_gpu_memory_buffer_surface_refs_
.push(surface_id
);
714 surface_refs_
.insert(std::make_pair(
715 surface_id
, GpuSurfaceTracker::GetInstance()->GetSurfaceRefForSurface(
719 callback
.Run(gfx::GpuMemoryBufferHandle());
723 void GpuProcessHost::DestroyGpuMemoryBuffer(gfx::GpuMemoryBufferId id
,
726 TRACE_EVENT0("gpu", "GpuProcessHost::DestroyGpuMemoryBuffer");
728 DCHECK(CalledOnValidThread());
730 Send(new GpuMsg_DestroyGpuMemoryBuffer(id
, client_id
, sync_point
));
733 void GpuProcessHost::OnInitialized(bool result
, const gpu::GPUInfo
& gpu_info
) {
734 UMA_HISTOGRAM_BOOLEAN("GPU.GPUProcessInitialized", result
);
735 initialized_
= result
;
738 GpuDataManagerImpl::GetInstance()->OnGpuProcessInitFailure();
739 else if (!in_process_
)
740 GpuDataManagerImpl::GetInstance()->UpdateGpuInfo(gpu_info
);
743 void GpuProcessHost::OnChannelEstablished(
744 const IPC::ChannelHandle
& channel_handle
) {
745 TRACE_EVENT0("gpu", "GpuProcessHost::OnChannelEstablished");
747 if (channel_requests_
.empty()) {
748 // This happens when GPU process is compromised.
749 RouteOnUIThread(GpuHostMsg_OnLogMessage(
750 logging::LOG_WARNING
,
752 "Received a ChannelEstablished message but no requests in queue."));
755 EstablishChannelCallback callback
= channel_requests_
.front();
756 channel_requests_
.pop();
758 // Currently if any of the GPU features are blacklisted, we don't establish a
760 if (!channel_handle
.name
.empty() &&
761 !GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL
)) {
762 Send(new GpuMsg_CloseChannel(channel_handle
));
763 callback
.Run(IPC::ChannelHandle(), gpu::GPUInfo());
764 RouteOnUIThread(GpuHostMsg_OnLogMessage(
765 logging::LOG_WARNING
,
767 "Hardware acceleration is unavailable."));
771 callback
.Run(channel_handle
,
772 GpuDataManagerImpl::GetInstance()->GetGPUInfo());
775 void GpuProcessHost::OnCommandBufferCreated(CreateCommandBufferResult result
) {
776 TRACE_EVENT0("gpu", "GpuProcessHost::OnCommandBufferCreated");
778 if (create_command_buffer_requests_
.empty())
781 CreateCommandBufferCallback callback
=
782 create_command_buffer_requests_
.front();
783 create_command_buffer_requests_
.pop();
784 callback
.Run(result
);
787 void GpuProcessHost::OnDestroyCommandBuffer(int32 surface_id
) {
788 TRACE_EVENT0("gpu", "GpuProcessHost::OnDestroyCommandBuffer");
789 SurfaceRefMap::iterator it
= surface_refs_
.find(surface_id
);
790 if (it
!= surface_refs_
.end()) {
791 surface_refs_
.erase(it
);
795 void GpuProcessHost::OnGpuMemoryBufferCreated(
796 const gfx::GpuMemoryBufferHandle
& handle
) {
797 TRACE_EVENT0("gpu", "GpuProcessHost::OnGpuMemoryBufferCreated");
799 if (create_gpu_memory_buffer_requests_
.empty())
802 CreateGpuMemoryBufferCallback callback
=
803 create_gpu_memory_buffer_requests_
.front();
804 create_gpu_memory_buffer_requests_
.pop();
805 callback
.Run(handle
);
807 int32 surface_id
= create_gpu_memory_buffer_surface_refs_
.front();
808 create_gpu_memory_buffer_surface_refs_
.pop();
809 SurfaceRefMap::iterator it
= surface_refs_
.find(surface_id
);
810 if (it
!= surface_refs_
.end()) {
811 surface_refs_
.erase(it
);
815 void GpuProcessHost::OnDidCreateOffscreenContext(const GURL
& url
) {
816 urls_with_live_offscreen_contexts_
.insert(url
);
819 void GpuProcessHost::OnDidLoseContext(bool offscreen
,
820 gpu::error::ContextLostReason reason
,
822 // TODO(kbr): would be nice to see the "offscreen" flag too.
823 TRACE_EVENT2("gpu", "GpuProcessHost::OnDidLoseContext",
826 url
.possibly_invalid_spec());
828 if (!offscreen
|| url
.is_empty()) {
829 // Assume that the loss of the compositor's or accelerated canvas'
830 // context is a serious event and blame the loss on all live
831 // offscreen contexts. This more robustly handles situations where
832 // the GPU process may not actually detect the context loss in the
833 // offscreen context.
834 BlockLiveOffscreenContexts();
838 GpuDataManagerImpl::DomainGuilt guilt
;
840 case gpu::error::kGuilty
:
841 guilt
= GpuDataManagerImpl::DOMAIN_GUILT_KNOWN
;
843 case gpu::error::kUnknown
:
844 guilt
= GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN
;
846 case gpu::error::kInnocent
:
853 GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(url
, guilt
);
856 void GpuProcessHost::OnDidDestroyOffscreenContext(const GURL
& url
) {
857 urls_with_live_offscreen_contexts_
.erase(url
);
860 void GpuProcessHost::OnGpuMemoryUmaStatsReceived(
861 const GPUMemoryUmaStats
& stats
) {
862 TRACE_EVENT0("gpu", "GpuProcessHost::OnGpuMemoryUmaStatsReceived");
863 uma_memory_stats_received_
= true;
864 uma_memory_stats_
= stats
;
867 #if defined(OS_MACOSX)
868 void GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped(
869 const IPC::Message
& message
) {
870 RenderWidgetResizeHelper::Get()->PostGpuProcessMsg(host_id_
, message
);
874 void GpuProcessHost::OnProcessLaunched() {
875 UMA_HISTOGRAM_TIMES("GPU.GPUProcessLaunchTime",
876 base::TimeTicks::Now() - init_start_time_
);
879 void GpuProcessHost::OnProcessCrashed(int exit_code
) {
880 SendOutstandingReplies();
881 RecordProcessCrash();
882 GpuDataManagerImpl::GetInstance()->ProcessCrashed(
883 process_
->GetTerminationStatus(true /* known_dead */, NULL
));
886 GpuProcessHost::GpuProcessKind
GpuProcessHost::kind() {
890 void GpuProcessHost::ForceShutdown() {
891 // This is only called on the IO thread so no race against the constructor
892 // for another GpuProcessHost.
893 if (g_gpu_process_hosts
[kind_
] == this)
894 g_gpu_process_hosts
[kind_
] = NULL
;
896 #if defined(OS_MACOSX) && !defined(OS_IOS)
897 if (!io_surface_manager_token_
.IsZero()) {
898 BrowserIOSurfaceManager::GetInstance()->InvalidateGpuProcessToken();
899 io_surface_manager_token_
.SetZero();
903 process_
->ForceShutdown();
906 void GpuProcessHost::BeginFrameSubscription(
908 base::WeakPtr
<RenderWidgetHostViewFrameSubscriber
> subscriber
) {
909 frame_subscribers_
[surface_id
] = subscriber
;
912 void GpuProcessHost::EndFrameSubscription(int surface_id
) {
913 frame_subscribers_
.erase(surface_id
);
916 bool GpuProcessHost::LaunchGpuProcess(const std::string
& channel_id
) {
917 if (!(gpu_enabled_
&&
918 GpuDataManagerImpl::GetInstance()->ShouldUseSwiftShader()) &&
919 !hardware_gpu_enabled_
) {
920 SendOutstandingReplies();
924 const base::CommandLine
& browser_command_line
=
925 *base::CommandLine::ForCurrentProcess();
927 base::CommandLine::StringType gpu_launcher
=
928 browser_command_line
.GetSwitchValueNative(switches::kGpuLauncher
);
930 #if defined(OS_ANDROID)
931 // crbug.com/447735. readlink("self/proc/exe") sometimes fails on Android
932 // at startup with EACCES. As a workaround ignore this here, since the
933 // executable name is actually not used or useful anyways.
934 base::CommandLine
* cmd_line
=
935 new base::CommandLine(base::CommandLine::NO_PROGRAM
);
937 #if defined(OS_LINUX)
938 int child_flags
= gpu_launcher
.empty() ? ChildProcessHost::CHILD_ALLOW_SELF
:
939 ChildProcessHost::CHILD_NORMAL
;
941 int child_flags
= ChildProcessHost::CHILD_NORMAL
;
944 base::FilePath exe_path
= ChildProcessHost::GetChildPath(child_flags
);
945 if (exe_path
.empty())
948 base::CommandLine
* cmd_line
= new base::CommandLine(exe_path
);
950 cmd_line
->AppendSwitchASCII(switches::kProcessType
, switches::kGpuProcess
);
951 cmd_line
->AppendSwitchASCII(switches::kProcessChannelID
, channel_id
);
953 if (kind_
== GPU_PROCESS_KIND_UNSANDBOXED
)
954 cmd_line
->AppendSwitch(switches::kDisableGpuSandbox
);
956 // If you want a browser command-line switch passed to the GPU process
957 // you need to add it to |kSwitchNames| at the beginning of this file.
958 cmd_line
->CopySwitchesFrom(browser_command_line
, kSwitchNames
,
959 arraysize(kSwitchNames
));
960 cmd_line
->CopySwitchesFrom(
961 browser_command_line
, switches::kGpuSwitches
, switches::kNumGpuSwitches
);
962 cmd_line
->CopySwitchesFrom(
963 browser_command_line
, switches::kGLSwitchesCopiedFromGpuProcessHost
,
964 switches::kGLSwitchesCopiedFromGpuProcessHostNumSwitches
);
966 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
967 cmd_line
, process_
->GetData().id
);
969 GpuDataManagerImpl::GetInstance()->AppendGpuCommandLine(cmd_line
);
971 if (cmd_line
->HasSwitch(switches::kUseGL
)) {
972 swiftshader_rendering_
=
973 (cmd_line
->GetSwitchValueASCII(switches::kUseGL
) == "swiftshader");
976 UMA_HISTOGRAM_BOOLEAN("GPU.GPU.GPUProcessSoftwareRendering",
977 swiftshader_rendering_
);
979 // If specified, prepend a launcher program to the command line.
980 if (!gpu_launcher
.empty())
981 cmd_line
->PrependWrapper(gpu_launcher
);
984 new GpuSandboxedProcessLauncherDelegate(cmd_line
,
985 process_
->GetHost()),
988 process_launched_
= true;
990 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
991 LAUNCHED
, GPU_PROCESS_LIFETIME_EVENT_MAX
);
995 void GpuProcessHost::SendOutstandingReplies() {
997 // First send empty channel handles for all EstablishChannel requests.
998 while (!channel_requests_
.empty()) {
999 EstablishChannelCallback callback
= channel_requests_
.front();
1000 channel_requests_
.pop();
1001 callback
.Run(IPC::ChannelHandle(), gpu::GPUInfo());
1004 while (!create_command_buffer_requests_
.empty()) {
1005 CreateCommandBufferCallback callback
=
1006 create_command_buffer_requests_
.front();
1007 create_command_buffer_requests_
.pop();
1008 callback
.Run(CREATE_COMMAND_BUFFER_FAILED_AND_CHANNEL_LOST
);
1011 while (!create_gpu_memory_buffer_requests_
.empty()) {
1012 CreateGpuMemoryBufferCallback callback
=
1013 create_gpu_memory_buffer_requests_
.front();
1014 create_gpu_memory_buffer_requests_
.pop();
1015 callback
.Run(gfx::GpuMemoryBufferHandle());
1019 void GpuProcessHost::BlockLiveOffscreenContexts() {
1020 for (std::multiset
<GURL
>::iterator iter
=
1021 urls_with_live_offscreen_contexts_
.begin();
1022 iter
!= urls_with_live_offscreen_contexts_
.end(); ++iter
) {
1023 GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(
1024 *iter
, GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN
);
1028 void GpuProcessHost::RecordProcessCrash() {
1029 // Skip if a GPU process crash was already counted.
1030 if (gpu_crash_recorded_
)
1033 // Maximum number of times the GPU process is allowed to crash in a session.
1034 // Once this limit is reached, any request to launch the GPU process will
1036 const int kGpuMaxCrashCount
= 3;
1038 // Last time the GPU process crashed.
1039 static base::Time last_gpu_crash_time
;
1041 bool disable_crash_limit
= base::CommandLine::ForCurrentProcess()->HasSwitch(
1042 switches::kDisableGpuProcessCrashLimit
);
1044 // Ending only acts as a failure if the GPU process was actually started and
1045 // was intended for actual rendering (and not just checking caps or other
1047 if (process_launched_
&& kind_
== GPU_PROCESS_KIND_SANDBOXED
) {
1048 gpu_crash_recorded_
= true;
1049 if (swiftshader_rendering_
) {
1050 UMA_HISTOGRAM_ENUMERATION("GPU.SwiftShaderLifetimeEvents",
1051 DIED_FIRST_TIME
+ swiftshader_crash_count_
,
1052 GPU_PROCESS_LIFETIME_EVENT_MAX
);
1054 if (++swiftshader_crash_count_
>= kGpuMaxCrashCount
&&
1055 !disable_crash_limit
) {
1056 // SwiftShader is too unstable to use. Disable it for current session.
1057 gpu_enabled_
= false;
1061 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
1062 std::min(DIED_FIRST_TIME
+ gpu_crash_count_
,
1063 GPU_PROCESS_LIFETIME_EVENT_MAX
- 1),
1064 GPU_PROCESS_LIFETIME_EVENT_MAX
);
1066 // Allow about 1 GPU crash per hour to be removed from the crash count,
1067 // so very occasional crashes won't eventually add up and prevent the
1068 // GPU process from launching.
1069 ++gpu_recent_crash_count_
;
1070 base::Time current_time
= base::Time::Now();
1071 if (crashed_before_
) {
1072 int hours_different
= (current_time
- last_gpu_crash_time
).InHours();
1073 gpu_recent_crash_count_
=
1074 std::max(0, gpu_recent_crash_count_
- hours_different
);
1077 crashed_before_
= true;
1078 last_gpu_crash_time
= current_time
;
1080 if ((gpu_recent_crash_count_
>= kGpuMaxCrashCount
&&
1081 !disable_crash_limit
) ||
1083 #if !defined(OS_CHROMEOS)
1084 // The GPU process is too unstable to use. Disable it for current
1086 hardware_gpu_enabled_
= false;
1087 GpuDataManagerImpl::GetInstance()->DisableHardwareAcceleration();
1094 std::string
GpuProcessHost::GetShaderPrefixKey() {
1095 if (shader_prefix_key_
.empty()) {
1096 gpu::GPUInfo info
= GpuDataManagerImpl::GetInstance()->GetGPUInfo();
1098 std::string in_str
= GetContentClient()->GetProduct() + "-" +
1099 #if defined(OS_ANDROID)
1100 base::android::BuildInfo::GetInstance()->android_build_fp() + "-" +
1102 info
.gl_vendor
+ "-" + info
.gl_renderer
+ "-" +
1103 info
.driver_version
+ "-" + info
.driver_vendor
;
1105 base::Base64Encode(base::SHA1HashString(in_str
), &shader_prefix_key_
);
1108 return shader_prefix_key_
;
1111 void GpuProcessHost::LoadedShader(const std::string
& key
,
1112 const std::string
& data
) {
1113 std::string prefix
= GetShaderPrefixKey();
1114 if (!key
.compare(0, prefix
.length(), prefix
))
1115 Send(new GpuMsg_LoadedShader(data
));
1118 void GpuProcessHost::CreateChannelCache(int32 client_id
) {
1119 TRACE_EVENT0("gpu", "GpuProcessHost::CreateChannelCache");
1121 scoped_refptr
<ShaderDiskCache
> cache
=
1122 ShaderCacheFactory::GetInstance()->Get(client_id
);
1126 cache
->set_host_id(host_id_
);
1128 client_id_to_shader_cache_
[client_id
] = cache
;
1131 void GpuProcessHost::OnDestroyChannel(int32 client_id
) {
1132 TRACE_EVENT0("gpu", "GpuProcessHost::OnDestroyChannel");
1133 client_id_to_shader_cache_
.erase(client_id
);
1136 void GpuProcessHost::OnCacheShader(int32 client_id
,
1137 const std::string
& key
,
1138 const std::string
& shader
) {
1139 TRACE_EVENT0("gpu", "GpuProcessHost::OnCacheShader");
1140 ClientIdToShaderCacheMap::iterator iter
=
1141 client_id_to_shader_cache_
.find(client_id
);
1142 // If the cache doesn't exist then this is an off the record profile.
1143 if (iter
== client_id_to_shader_cache_
.end())
1145 iter
->second
->Cache(GetShaderPrefixKey() + ":" + key
, shader
);
1148 } // namespace content