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/sandboxed_process_launcher_delegate.h"
39 #include "gpu/command_buffer/service/gpu_switches.h"
40 #include "ipc/ipc_channel_handle.h"
41 #include "ipc/ipc_switches.h"
42 #include "ipc/message_filter.h"
43 #include "media/base/media_switches.h"
44 #include "ui/base/ui_base_switches.h"
45 #include "ui/events/latency_info.h"
46 #include "ui/gl/gl_switches.h"
49 #include "base/win/windows_version.h"
50 #include "content/common/sandbox_win.h"
51 #include "sandbox/win/src/sandbox_policy.h"
52 #include "ui/gfx/switches.h"
55 #if defined(USE_OZONE)
56 #include "ui/ozone/public/ozone_switches.h"
59 #if defined(USE_X11) && !defined(OS_CHROMEOS)
60 #include "ui/gfx/x/x11_switches.h"
65 bool GpuProcessHost::gpu_enabled_
= true;
66 bool GpuProcessHost::hardware_gpu_enabled_
= true;
67 int GpuProcessHost::gpu_crash_count_
= 0;
68 int GpuProcessHost::gpu_recent_crash_count_
= 0;
69 bool GpuProcessHost::crashed_before_
= false;
70 int GpuProcessHost::swiftshader_crash_count_
= 0;
74 // Command-line switches to propagate to the GPU process.
75 static const char* const kSwitchNames
[] = {
76 switches::kDisableAcceleratedVideoDecode
,
77 switches::kDisableBreakpad
,
78 switches::kDisableGpuSandbox
,
79 switches::kDisableGpuWatchdog
,
80 switches::kDisableLogging
,
81 switches::kDisableSeccompFilterSandbox
,
82 #if defined(ENABLE_WEBRTC)
83 switches::kDisableWebRtcHWEncoding
,
85 switches::kEnableLogging
,
86 switches::kEnableShareGroupAsyncTextureUpload
,
87 #if defined(OS_CHROMEOS)
88 switches::kDisableVaapiAcceleratedVideoEncode
,
90 switches::kGpuStartupDialog
,
91 switches::kGpuSandboxAllowSysVShm
,
92 switches::kGpuSandboxFailuresFatal
,
93 switches::kGpuSandboxStartEarly
,
94 switches::kLoggingLevel
,
95 switches::kEnableLowEndDeviceMode
,
96 switches::kDisableLowEndDeviceMode
,
98 switches::kProfilerTiming
,
100 switches::kTraceStartup
,
101 switches::kTraceToConsole
,
104 #if defined(OS_MACOSX)
105 switches::kDisableRemoteCoreAnimation
,
106 switches::kEnableSandboxLogging
,
108 #if defined(USE_AURA)
109 switches::kUIPrioritizeInGpuProcess
,
111 #if defined(USE_OZONE)
112 switches::kOzonePlatform
,
113 switches::kOzoneUseSurfaceless
,
115 #if defined(USE_X11) && !defined(OS_CHROMEOS)
116 switches::kX11Display
,
120 enum GPUProcessLifetimeEvent
{
126 GPU_PROCESS_LIFETIME_EVENT_MAX
= 100
129 // Indexed by GpuProcessKind. There is one of each kind maximum. This array may
130 // only be accessed from the IO thread.
131 GpuProcessHost
* g_gpu_process_hosts
[GpuProcessHost::GPU_PROCESS_KIND_COUNT
];
134 void SendGpuProcessMessage(GpuProcessHost::GpuProcessKind kind
,
135 CauseForGpuLaunch cause
,
136 IPC::Message
* message
) {
137 GpuProcessHost
* host
= GpuProcessHost::Get(kind
, cause
);
145 // NOTE: changes to this class need to be reviewed by the security team.
146 class GpuSandboxedProcessLauncherDelegate
147 : public SandboxedProcessLauncherDelegate
{
149 GpuSandboxedProcessLauncherDelegate(base::CommandLine
* cmd_line
,
150 ChildProcessHost
* host
)
152 : cmd_line_(cmd_line
) {}
153 #elif defined(OS_POSIX)
154 : ipc_fd_(host
->TakeClientFileDescriptor()) {}
157 ~GpuSandboxedProcessLauncherDelegate() override
{}
160 bool ShouldSandbox() override
{
161 bool sandbox
= !cmd_line_
->HasSwitch(switches::kDisableGpuSandbox
);
163 DVLOG(1) << "GPU sandbox is disabled";
168 void PreSandbox(bool* disable_default_policy
,
169 base::FilePath
* exposed_dir
) override
{
170 *disable_default_policy
= true;
173 // For the GPU process we gotten as far as USER_LIMITED. The next level
174 // which is USER_RESTRICTED breaks both the DirectX backend and the OpenGL
175 // backend. Note that the GPU process is connected to the interactive
177 void PreSpawnTarget(sandbox::TargetPolicy
* policy
, bool* success
) override
{
178 if (base::win::GetVersion() > base::win::VERSION_XP
) {
179 if (cmd_line_
->GetSwitchValueASCII(switches::kUseGL
) ==
180 gfx::kGLImplementationDesktopName
) {
182 policy
->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS
,
183 sandbox::USER_LIMITED
);
184 SetJobLevel(*cmd_line_
, sandbox::JOB_UNPROTECTED
, 0, policy
);
185 policy
->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW
);
187 policy
->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS
,
188 sandbox::USER_LIMITED
);
190 // UI restrictions break when we access Windows from outside our job.
191 // However, we don't want a proxy window in this process because it can
192 // introduce deadlocks where the renderer blocks on the gpu, which in
193 // turn blocks on the browser UI thread. So, instead we forgo a window
194 // message pump entirely and just add job restrictions to prevent child
196 SetJobLevel(*cmd_line_
,
197 sandbox::JOB_LIMITED_USER
,
198 JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS
|
199 JOB_OBJECT_UILIMIT_DESKTOP
|
200 JOB_OBJECT_UILIMIT_EXITWINDOWS
|
201 JOB_OBJECT_UILIMIT_DISPLAYSETTINGS
,
204 policy
->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW
);
207 SetJobLevel(*cmd_line_
, sandbox::JOB_UNPROTECTED
, 0, policy
);
208 policy
->SetTokenLevel(sandbox::USER_UNPROTECTED
,
209 sandbox::USER_LIMITED
);
212 // Allow the server side of GPU sockets, which are pipes that have
213 // the "chrome.gpu" namespace and an arbitrary suffix.
214 sandbox::ResultCode result
= policy
->AddRule(
215 sandbox::TargetPolicy::SUBSYS_NAMED_PIPES
,
216 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY
,
217 L
"\\\\.\\pipe\\chrome.gpu.*");
218 if (result
!= sandbox::SBOX_ALL_OK
) {
223 // Block this DLL even if it is not loaded by the browser process.
224 policy
->AddDllToUnload(L
"cmsetac.dll");
227 // GPU also needs to add sections to the browser for aura
228 // TODO(jschuh): refactor the GPU channel to remove this. crbug.com/128786
229 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES
,
230 sandbox::TargetPolicy::HANDLES_DUP_BROKER
,
232 if (result
!= sandbox::SBOX_ALL_OK
) {
238 if (cmd_line_
->HasSwitch(switches::kEnableLogging
)) {
239 base::string16 log_file_path
= logging::GetLogFileFullPath();
240 if (!log_file_path
.empty()) {
241 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_FILES
,
242 sandbox::TargetPolicy::FILES_ALLOW_ANY
,
243 log_file_path
.c_str());
244 if (result
!= sandbox::SBOX_ALL_OK
) {
251 #elif defined(OS_POSIX)
253 base::ScopedFD
TakeIpcFd() override
{ return ipc_fd_
.Pass(); }
258 base::CommandLine
* cmd_line_
;
259 #elif defined(OS_POSIX)
260 base::ScopedFD ipc_fd_
;
264 } // anonymous namespace
267 bool GpuProcessHost::ValidateHost(GpuProcessHost
* host
) {
268 // The Gpu process is invalid if it's not using SwiftShader, the card is
269 // blacklisted, and we can kill it and start over.
270 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
271 switches::kSingleProcess
) ||
272 base::CommandLine::ForCurrentProcess()->HasSwitch(
273 switches::kInProcessGPU
) ||
275 (host
->swiftshader_rendering_
||
276 !GpuDataManagerImpl::GetInstance()->ShouldUseSwiftShader()))) {
280 host
->ForceShutdown();
285 GpuProcessHost
* GpuProcessHost::Get(GpuProcessKind kind
,
286 CauseForGpuLaunch cause
) {
287 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
289 // Don't grant further access to GPU if it is not allowed.
290 GpuDataManagerImpl
* gpu_data_manager
= GpuDataManagerImpl::GetInstance();
291 DCHECK(gpu_data_manager
);
292 if (!gpu_data_manager
->GpuAccessAllowed(NULL
))
295 if (g_gpu_process_hosts
[kind
] && ValidateHost(g_gpu_process_hosts
[kind
]))
296 return g_gpu_process_hosts
[kind
];
298 if (cause
== CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH
)
301 static int last_host_id
= 0;
303 host_id
= ++last_host_id
;
305 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLaunchCause",
307 CAUSE_FOR_GPU_LAUNCH_MAX_ENUM
);
309 GpuProcessHost
* host
= new GpuProcessHost(host_id
, kind
);
318 void GpuProcessHost::GetProcessHandles(
319 const GpuDataManager::GetGpuProcessHandlesCallback
& callback
) {
320 if (!BrowserThread::CurrentlyOn(BrowserThread::IO
)) {
321 BrowserThread::PostTask(
324 base::Bind(&GpuProcessHost::GetProcessHandles
, callback
));
327 std::list
<base::ProcessHandle
> handles
;
328 for (size_t i
= 0; i
< arraysize(g_gpu_process_hosts
); ++i
) {
329 // TODO(rvargas) crbug/417532: don't store ProcessHandles!.
330 GpuProcessHost
* host
= g_gpu_process_hosts
[i
];
331 if (host
&& ValidateHost(host
))
332 handles
.push_back(host
->process_
->GetProcess().Handle());
334 BrowserThread::PostTask(
337 base::Bind(callback
, handles
));
341 void GpuProcessHost::SendOnIO(GpuProcessKind kind
,
342 CauseForGpuLaunch cause
,
343 IPC::Message
* message
) {
344 if (!BrowserThread::PostTask(
345 BrowserThread::IO
, FROM_HERE
,
347 &SendGpuProcessMessage
, kind
, cause
, message
))) {
352 GpuMainThreadFactoryFunction g_gpu_main_thread_factory
= NULL
;
354 void GpuProcessHost::RegisterGpuMainThreadFactory(
355 GpuMainThreadFactoryFunction create
) {
356 g_gpu_main_thread_factory
= create
;
360 GpuProcessHost
* GpuProcessHost::FromID(int host_id
) {
361 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
363 for (int i
= 0; i
< GPU_PROCESS_KIND_COUNT
; ++i
) {
364 GpuProcessHost
* host
= g_gpu_process_hosts
[i
];
365 if (host
&& host
->host_id_
== host_id
&& ValidateHost(host
))
372 GpuProcessHost::GpuProcessHost(int host_id
, GpuProcessKind kind
)
376 swiftshader_rendering_(false),
378 process_launched_(false),
380 gpu_crash_recorded_(false),
381 uma_memory_stats_received_(false) {
382 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
383 switches::kSingleProcess
) ||
384 base::CommandLine::ForCurrentProcess()->HasSwitch(
385 switches::kInProcessGPU
)) {
389 // If the 'single GPU process' policy ever changes, we still want to maintain
390 // it for 'gpu thread' mode and only create one instance of host and thread.
391 DCHECK(!in_process_
|| g_gpu_process_hosts
[kind
] == NULL
);
393 g_gpu_process_hosts
[kind
] = this;
395 // Post a task to create the corresponding GpuProcessHostUIShim. The
396 // GpuProcessHostUIShim will be destroyed if either the browser exits,
397 // in which case it calls GpuProcessHostUIShim::DestroyAll, or the
398 // GpuProcessHost is destroyed, which happens when the corresponding GPU
399 // process terminates or fails to launch.
400 BrowserThread::PostTask(
403 base::Bind(base::IgnoreResult(&GpuProcessHostUIShim::Create
), host_id
));
405 process_
.reset(new BrowserChildProcessHostImpl(PROCESS_TYPE_GPU
, this));
408 GpuProcessHost::~GpuProcessHost() {
409 DCHECK(CalledOnValidThread());
411 SendOutstandingReplies();
413 RecordProcessCrash();
415 // In case we never started, clean up.
416 while (!queued_messages_
.empty()) {
417 delete queued_messages_
.front();
418 queued_messages_
.pop();
421 // This is only called on the IO thread so no race against the constructor
422 // for another GpuProcessHost.
423 if (g_gpu_process_hosts
[kind_
] == this)
424 g_gpu_process_hosts
[kind_
] = NULL
;
426 // If there are any remaining offscreen contexts at the point the
427 // GPU process exits, assume something went wrong, and block their
428 // URLs from accessing client 3D APIs without prompting.
429 BlockLiveOffscreenContexts();
431 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitSurfaceCount",
432 GpuSurfaceTracker::Get()->GetSurfaceCount());
433 UMA_HISTOGRAM_BOOLEAN("GPU.AtExitReceivedMemoryStats",
434 uma_memory_stats_received_
);
436 if (uma_memory_stats_received_
) {
437 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitManagedMemoryClientCount",
438 uma_memory_stats_
.client_count
);
439 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitContextGroupCount",
440 uma_memory_stats_
.context_group_count
);
441 UMA_HISTOGRAM_CUSTOM_COUNTS(
442 "GPU.AtExitMBytesAllocated",
443 uma_memory_stats_
.bytes_allocated_current
/ 1024 / 1024, 1, 2000, 50);
444 UMA_HISTOGRAM_CUSTOM_COUNTS(
445 "GPU.AtExitMBytesAllocatedMax",
446 uma_memory_stats_
.bytes_allocated_max
/ 1024 / 1024, 1, 2000, 50);
447 UMA_HISTOGRAM_CUSTOM_COUNTS(
448 "GPU.AtExitMBytesLimit",
449 uma_memory_stats_
.bytes_limit
/ 1024 / 1024, 1, 2000, 50);
455 base::TerminationStatus status
= process_
->GetTerminationStatus(
456 false /* known_dead */, &exit_code
);
457 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessTerminationStatus",
459 base::TERMINATION_STATUS_MAX_ENUM
);
461 if (status
== base::TERMINATION_STATUS_NORMAL_TERMINATION
||
462 status
== base::TERMINATION_STATUS_ABNORMAL_TERMINATION
) {
463 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessExitCode",
465 RESULT_CODE_LAST_CODE
);
469 case base::TERMINATION_STATUS_NORMAL_TERMINATION
:
470 message
= "The GPU process exited normally. Everything is okay.";
472 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION
:
473 message
= base::StringPrintf(
474 "The GPU process exited with code %d.",
477 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED
:
478 message
= "You killed the GPU process! Why?";
480 case base::TERMINATION_STATUS_PROCESS_CRASHED
:
481 message
= "The GPU process crashed!";
488 BrowserThread::PostTask(BrowserThread::UI
,
490 base::Bind(&GpuProcessHostUIShim::Destroy
,
495 bool GpuProcessHost::Init() {
496 init_start_time_
= base::TimeTicks::Now();
498 TRACE_EVENT_INSTANT0("gpu", "LaunchGpuProcess", TRACE_EVENT_SCOPE_THREAD
);
500 std::string channel_id
= process_
->GetHost()->CreateChannel();
501 if (channel_id
.empty())
505 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
506 DCHECK(g_gpu_main_thread_factory
);
507 in_process_gpu_thread_
.reset(
508 g_gpu_main_thread_factory(InProcessChildThreadParams(
509 channel_id
, base::MessageLoop::current()->task_runner())));
510 base::Thread::Options options
;
512 // WGL needs to create its own window and pump messages on it.
513 options
.message_loop_type
= base::MessageLoop::TYPE_UI
;
515 in_process_gpu_thread_
->StartWithOptions(options
);
517 OnProcessLaunched(); // Fake a callback that the process is ready.
518 } else if (!LaunchGpuProcess(channel_id
)) {
522 if (!Send(new GpuMsg_Initialize()))
528 void GpuProcessHost::RouteOnUIThread(const IPC::Message
& message
) {
529 BrowserThread::PostTask(
532 base::Bind(&RouteToGpuProcessHostUIShimTask
, host_id_
, message
));
535 bool GpuProcessHost::Send(IPC::Message
* msg
) {
536 DCHECK(CalledOnValidThread());
537 if (process_
->GetHost()->IsChannelOpening()) {
538 queued_messages_
.push(msg
);
542 bool result
= process_
->Send(msg
);
544 // Channel is hosed, but we may not get destroyed for a while. Send
545 // outstanding channel creation failures now so that the caller can restart
546 // with a new process/channel without waiting.
547 SendOutstandingReplies();
552 void GpuProcessHost::AddFilter(IPC::MessageFilter
* filter
) {
553 DCHECK(CalledOnValidThread());
554 process_
->GetHost()->AddFilter(filter
);
557 bool GpuProcessHost::OnMessageReceived(const IPC::Message
& message
) {
558 DCHECK(CalledOnValidThread());
559 IPC_BEGIN_MESSAGE_MAP(GpuProcessHost
, message
)
560 IPC_MESSAGE_HANDLER(GpuHostMsg_Initialized
, OnInitialized
)
561 IPC_MESSAGE_HANDLER(GpuHostMsg_ChannelEstablished
, OnChannelEstablished
)
562 IPC_MESSAGE_HANDLER(GpuHostMsg_CommandBufferCreated
, OnCommandBufferCreated
)
563 IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyCommandBuffer
, OnDestroyCommandBuffer
)
564 IPC_MESSAGE_HANDLER(GpuHostMsg_GpuMemoryBufferCreated
,
565 OnGpuMemoryBufferCreated
)
566 IPC_MESSAGE_HANDLER(GpuHostMsg_DidCreateOffscreenContext
,
567 OnDidCreateOffscreenContext
)
568 IPC_MESSAGE_HANDLER(GpuHostMsg_DidLoseContext
, OnDidLoseContext
)
569 IPC_MESSAGE_HANDLER(GpuHostMsg_DidDestroyOffscreenContext
,
570 OnDidDestroyOffscreenContext
)
571 IPC_MESSAGE_HANDLER(GpuHostMsg_GpuMemoryUmaStats
,
572 OnGpuMemoryUmaStatsReceived
)
573 #if defined(OS_MACOSX)
574 IPC_MESSAGE_HANDLER_GENERIC(GpuHostMsg_AcceleratedSurfaceBuffersSwapped
,
575 OnAcceleratedSurfaceBuffersSwapped(message
))
577 IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyChannel
,
579 IPC_MESSAGE_HANDLER(GpuHostMsg_CacheShader
,
582 IPC_MESSAGE_UNHANDLED(RouteOnUIThread(message
))
583 IPC_END_MESSAGE_MAP()
588 void GpuProcessHost::OnChannelConnected(int32 peer_pid
) {
589 TRACE_EVENT0("gpu", "GpuProcessHost::OnChannelConnected");
591 while (!queued_messages_
.empty()) {
592 Send(queued_messages_
.front());
593 queued_messages_
.pop();
597 void GpuProcessHost::EstablishGpuChannel(
600 bool allow_future_sync_points
,
601 const EstablishChannelCallback
& callback
) {
602 DCHECK(CalledOnValidThread());
603 TRACE_EVENT0("gpu", "GpuProcessHost::EstablishGpuChannel");
605 // If GPU features are already blacklisted, no need to establish the channel.
606 if (!GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL
)) {
607 DVLOG(1) << "GPU blacklisted, refusing to open a GPU channel.";
608 callback
.Run(IPC::ChannelHandle(), gpu::GPUInfo());
612 if (Send(new GpuMsg_EstablishChannel(
613 client_id
, share_context
, allow_future_sync_points
))) {
614 channel_requests_
.push(callback
);
616 DVLOG(1) << "Failed to send GpuMsg_EstablishChannel.";
617 callback
.Run(IPC::ChannelHandle(), gpu::GPUInfo());
620 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
621 switches::kDisableGpuShaderDiskCache
)) {
622 CreateChannelCache(client_id
);
626 void GpuProcessHost::CreateViewCommandBuffer(
627 const gfx::GLSurfaceHandle
& compositing_surface
,
630 const GPUCreateCommandBufferConfig
& init_params
,
632 const CreateCommandBufferCallback
& callback
) {
633 TRACE_EVENT0("gpu", "GpuProcessHost::CreateViewCommandBuffer");
635 DCHECK(CalledOnValidThread());
637 if (!compositing_surface
.is_null() &&
638 Send(new GpuMsg_CreateViewCommandBuffer(
639 compositing_surface
, surface_id
, client_id
, init_params
, route_id
))) {
640 create_command_buffer_requests_
.push(callback
);
641 surface_refs_
.insert(std::make_pair(surface_id
,
642 GpuSurfaceTracker::GetInstance()->GetSurfaceRefForSurface(surface_id
)));
644 // Could distinguish here between compositing_surface being NULL
645 // and Send failing, if desired.
646 callback
.Run(CREATE_COMMAND_BUFFER_FAILED_AND_CHANNEL_LOST
);
650 void GpuProcessHost::CreateGpuMemoryBuffer(
651 gfx::GpuMemoryBufferId id
,
652 const gfx::Size
& size
,
653 gfx::GpuMemoryBuffer::Format format
,
654 gfx::GpuMemoryBuffer::Usage usage
,
657 const CreateGpuMemoryBufferCallback
& callback
) {
658 TRACE_EVENT0("gpu", "GpuProcessHost::CreateGpuMemoryBuffer");
660 DCHECK(CalledOnValidThread());
662 GpuMsg_CreateGpuMemoryBuffer_Params params
;
665 params
.format
= format
;
666 params
.usage
= usage
;
667 params
.client_id
= client_id
;
668 params
.surface_handle
=
669 GpuSurfaceTracker::GetInstance()->GetSurfaceHandle(surface_id
).handle
;
670 if (Send(new GpuMsg_CreateGpuMemoryBuffer(params
))) {
671 create_gpu_memory_buffer_requests_
.push(callback
);
672 create_gpu_memory_buffer_surface_refs_
.push(surface_id
);
674 surface_refs_
.insert(std::make_pair(
675 surface_id
, GpuSurfaceTracker::GetInstance()->GetSurfaceRefForSurface(
679 callback
.Run(gfx::GpuMemoryBufferHandle());
683 void GpuProcessHost::DestroyGpuMemoryBuffer(gfx::GpuMemoryBufferId id
,
686 TRACE_EVENT0("gpu", "GpuProcessHost::DestroyGpuMemoryBuffer");
688 DCHECK(CalledOnValidThread());
690 Send(new GpuMsg_DestroyGpuMemoryBuffer(id
, client_id
, sync_point
));
693 void GpuProcessHost::OnInitialized(bool result
, const gpu::GPUInfo
& gpu_info
) {
694 UMA_HISTOGRAM_BOOLEAN("GPU.GPUProcessInitialized", result
);
695 initialized_
= result
;
698 GpuDataManagerImpl::GetInstance()->OnGpuProcessInitFailure();
699 else if (!in_process_
)
700 GpuDataManagerImpl::GetInstance()->UpdateGpuInfo(gpu_info
);
703 void GpuProcessHost::OnChannelEstablished(
704 const IPC::ChannelHandle
& channel_handle
) {
705 TRACE_EVENT0("gpu", "GpuProcessHost::OnChannelEstablished");
707 if (channel_requests_
.empty()) {
708 // This happens when GPU process is compromised.
709 RouteOnUIThread(GpuHostMsg_OnLogMessage(
710 logging::LOG_WARNING
,
712 "Received a ChannelEstablished message but no requests in queue."));
715 EstablishChannelCallback callback
= channel_requests_
.front();
716 channel_requests_
.pop();
718 // Currently if any of the GPU features are blacklisted, we don't establish a
720 if (!channel_handle
.name
.empty() &&
721 !GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL
)) {
722 Send(new GpuMsg_CloseChannel(channel_handle
));
723 callback
.Run(IPC::ChannelHandle(), gpu::GPUInfo());
724 RouteOnUIThread(GpuHostMsg_OnLogMessage(
725 logging::LOG_WARNING
,
727 "Hardware acceleration is unavailable."));
731 callback
.Run(channel_handle
,
732 GpuDataManagerImpl::GetInstance()->GetGPUInfo());
735 void GpuProcessHost::OnCommandBufferCreated(CreateCommandBufferResult result
) {
736 TRACE_EVENT0("gpu", "GpuProcessHost::OnCommandBufferCreated");
738 if (create_command_buffer_requests_
.empty())
741 CreateCommandBufferCallback callback
=
742 create_command_buffer_requests_
.front();
743 create_command_buffer_requests_
.pop();
744 callback
.Run(result
);
747 void GpuProcessHost::OnDestroyCommandBuffer(int32 surface_id
) {
748 TRACE_EVENT0("gpu", "GpuProcessHost::OnDestroyCommandBuffer");
749 SurfaceRefMap::iterator it
= surface_refs_
.find(surface_id
);
750 if (it
!= surface_refs_
.end()) {
751 surface_refs_
.erase(it
);
755 void GpuProcessHost::OnGpuMemoryBufferCreated(
756 const gfx::GpuMemoryBufferHandle
& handle
) {
757 TRACE_EVENT0("gpu", "GpuProcessHost::OnGpuMemoryBufferCreated");
759 if (create_gpu_memory_buffer_requests_
.empty())
762 CreateGpuMemoryBufferCallback callback
=
763 create_gpu_memory_buffer_requests_
.front();
764 create_gpu_memory_buffer_requests_
.pop();
765 callback
.Run(handle
);
767 int32 surface_id
= create_gpu_memory_buffer_surface_refs_
.front();
768 create_gpu_memory_buffer_surface_refs_
.pop();
769 SurfaceRefMap::iterator it
= surface_refs_
.find(surface_id
);
770 if (it
!= surface_refs_
.end()) {
771 surface_refs_
.erase(it
);
775 void GpuProcessHost::OnDidCreateOffscreenContext(const GURL
& url
) {
776 urls_with_live_offscreen_contexts_
.insert(url
);
779 void GpuProcessHost::OnDidLoseContext(bool offscreen
,
780 gpu::error::ContextLostReason reason
,
782 // TODO(kbr): would be nice to see the "offscreen" flag too.
783 TRACE_EVENT2("gpu", "GpuProcessHost::OnDidLoseContext",
786 url
.possibly_invalid_spec());
788 if (!offscreen
|| url
.is_empty()) {
789 // Assume that the loss of the compositor's or accelerated canvas'
790 // context is a serious event and blame the loss on all live
791 // offscreen contexts. This more robustly handles situations where
792 // the GPU process may not actually detect the context loss in the
793 // offscreen context.
794 BlockLiveOffscreenContexts();
798 GpuDataManagerImpl::DomainGuilt guilt
;
800 case gpu::error::kGuilty
:
801 guilt
= GpuDataManagerImpl::DOMAIN_GUILT_KNOWN
;
803 case gpu::error::kUnknown
:
804 guilt
= GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN
;
806 case gpu::error::kInnocent
:
813 GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(url
, guilt
);
816 void GpuProcessHost::OnDidDestroyOffscreenContext(const GURL
& url
) {
817 urls_with_live_offscreen_contexts_
.erase(url
);
820 void GpuProcessHost::OnGpuMemoryUmaStatsReceived(
821 const GPUMemoryUmaStats
& stats
) {
822 TRACE_EVENT0("gpu", "GpuProcessHost::OnGpuMemoryUmaStatsReceived");
823 uma_memory_stats_received_
= true;
824 uma_memory_stats_
= stats
;
827 #if defined(OS_MACOSX)
828 void GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped(
829 const IPC::Message
& message
) {
830 RenderWidgetResizeHelper::Get()->PostGpuProcessMsg(host_id_
, message
);
834 void GpuProcessHost::OnProcessLaunched() {
835 UMA_HISTOGRAM_TIMES("GPU.GPUProcessLaunchTime",
836 base::TimeTicks::Now() - init_start_time_
);
839 void GpuProcessHost::OnProcessCrashed(int exit_code
) {
840 SendOutstandingReplies();
841 RecordProcessCrash();
842 GpuDataManagerImpl::GetInstance()->ProcessCrashed(
843 process_
->GetTerminationStatus(true /* known_dead */, NULL
));
846 GpuProcessHost::GpuProcessKind
GpuProcessHost::kind() {
850 void GpuProcessHost::ForceShutdown() {
851 // This is only called on the IO thread so no race against the constructor
852 // for another GpuProcessHost.
853 if (g_gpu_process_hosts
[kind_
] == this)
854 g_gpu_process_hosts
[kind_
] = NULL
;
856 process_
->ForceShutdown();
859 void GpuProcessHost::BeginFrameSubscription(
861 base::WeakPtr
<RenderWidgetHostViewFrameSubscriber
> subscriber
) {
862 frame_subscribers_
[surface_id
] = subscriber
;
865 void GpuProcessHost::EndFrameSubscription(int surface_id
) {
866 frame_subscribers_
.erase(surface_id
);
869 bool GpuProcessHost::LaunchGpuProcess(const std::string
& channel_id
) {
870 if (!(gpu_enabled_
&&
871 GpuDataManagerImpl::GetInstance()->ShouldUseSwiftShader()) &&
872 !hardware_gpu_enabled_
) {
873 SendOutstandingReplies();
877 const base::CommandLine
& browser_command_line
=
878 *base::CommandLine::ForCurrentProcess();
880 base::CommandLine::StringType gpu_launcher
=
881 browser_command_line
.GetSwitchValueNative(switches::kGpuLauncher
);
883 #if defined(OS_ANDROID)
884 // crbug.com/447735. readlink("self/proc/exe") sometimes fails on Android
885 // at startup with EACCES. As a workaround ignore this here, since the
886 // executable name is actually not used or useful anyways.
887 base::CommandLine
* cmd_line
=
888 new base::CommandLine(base::CommandLine::NO_PROGRAM
);
890 #if defined(OS_LINUX)
891 int child_flags
= gpu_launcher
.empty() ? ChildProcessHost::CHILD_ALLOW_SELF
:
892 ChildProcessHost::CHILD_NORMAL
;
894 int child_flags
= ChildProcessHost::CHILD_NORMAL
;
897 base::FilePath exe_path
= ChildProcessHost::GetChildPath(child_flags
);
898 if (exe_path
.empty())
901 base::CommandLine
* cmd_line
= new base::CommandLine(exe_path
);
903 cmd_line
->AppendSwitchASCII(switches::kProcessType
, switches::kGpuProcess
);
904 cmd_line
->AppendSwitchASCII(switches::kProcessChannelID
, channel_id
);
906 if (kind_
== GPU_PROCESS_KIND_UNSANDBOXED
)
907 cmd_line
->AppendSwitch(switches::kDisableGpuSandbox
);
909 // If you want a browser command-line switch passed to the GPU process
910 // you need to add it to |kSwitchNames| at the beginning of this file.
911 cmd_line
->CopySwitchesFrom(browser_command_line
, kSwitchNames
,
912 arraysize(kSwitchNames
));
913 cmd_line
->CopySwitchesFrom(
914 browser_command_line
, switches::kGpuSwitches
, switches::kNumGpuSwitches
);
915 cmd_line
->CopySwitchesFrom(
916 browser_command_line
, switches::kGLSwitchesCopiedFromGpuProcessHost
,
917 switches::kGLSwitchesCopiedFromGpuProcessHostNumSwitches
);
919 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
920 cmd_line
, process_
->GetData().id
);
922 GpuDataManagerImpl::GetInstance()->AppendGpuCommandLine(cmd_line
);
924 if (cmd_line
->HasSwitch(switches::kUseGL
)) {
925 swiftshader_rendering_
=
926 (cmd_line
->GetSwitchValueASCII(switches::kUseGL
) == "swiftshader");
929 UMA_HISTOGRAM_BOOLEAN("GPU.GPU.GPUProcessSoftwareRendering",
930 swiftshader_rendering_
);
932 // If specified, prepend a launcher program to the command line.
933 if (!gpu_launcher
.empty())
934 cmd_line
->PrependWrapper(gpu_launcher
);
937 new GpuSandboxedProcessLauncherDelegate(cmd_line
,
938 process_
->GetHost()),
941 process_launched_
= true;
943 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
944 LAUNCHED
, GPU_PROCESS_LIFETIME_EVENT_MAX
);
948 void GpuProcessHost::SendOutstandingReplies() {
950 // First send empty channel handles for all EstablishChannel requests.
951 while (!channel_requests_
.empty()) {
952 EstablishChannelCallback callback
= channel_requests_
.front();
953 channel_requests_
.pop();
954 callback
.Run(IPC::ChannelHandle(), gpu::GPUInfo());
957 while (!create_command_buffer_requests_
.empty()) {
958 CreateCommandBufferCallback callback
=
959 create_command_buffer_requests_
.front();
960 create_command_buffer_requests_
.pop();
961 callback
.Run(CREATE_COMMAND_BUFFER_FAILED_AND_CHANNEL_LOST
);
964 while (!create_gpu_memory_buffer_requests_
.empty()) {
965 CreateGpuMemoryBufferCallback callback
=
966 create_gpu_memory_buffer_requests_
.front();
967 create_gpu_memory_buffer_requests_
.pop();
968 callback
.Run(gfx::GpuMemoryBufferHandle());
972 void GpuProcessHost::BlockLiveOffscreenContexts() {
973 for (std::multiset
<GURL
>::iterator iter
=
974 urls_with_live_offscreen_contexts_
.begin();
975 iter
!= urls_with_live_offscreen_contexts_
.end(); ++iter
) {
976 GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(
977 *iter
, GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN
);
981 void GpuProcessHost::RecordProcessCrash() {
982 // Skip if a GPU process crash was already counted.
983 if (gpu_crash_recorded_
)
986 // Maximum number of times the GPU process is allowed to crash in a session.
987 // Once this limit is reached, any request to launch the GPU process will
989 const int kGpuMaxCrashCount
= 3;
991 // Last time the GPU process crashed.
992 static base::Time last_gpu_crash_time
;
994 bool disable_crash_limit
= base::CommandLine::ForCurrentProcess()->HasSwitch(
995 switches::kDisableGpuProcessCrashLimit
);
997 // Ending only acts as a failure if the GPU process was actually started and
998 // was intended for actual rendering (and not just checking caps or other
1000 if (process_launched_
&& kind_
== GPU_PROCESS_KIND_SANDBOXED
) {
1001 gpu_crash_recorded_
= true;
1002 if (swiftshader_rendering_
) {
1003 UMA_HISTOGRAM_ENUMERATION("GPU.SwiftShaderLifetimeEvents",
1004 DIED_FIRST_TIME
+ swiftshader_crash_count_
,
1005 GPU_PROCESS_LIFETIME_EVENT_MAX
);
1007 if (++swiftshader_crash_count_
>= kGpuMaxCrashCount
&&
1008 !disable_crash_limit
) {
1009 // SwiftShader is too unstable to use. Disable it for current session.
1010 gpu_enabled_
= false;
1014 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
1015 std::min(DIED_FIRST_TIME
+ gpu_crash_count_
,
1016 GPU_PROCESS_LIFETIME_EVENT_MAX
- 1),
1017 GPU_PROCESS_LIFETIME_EVENT_MAX
);
1019 // Allow about 1 GPU crash per hour to be removed from the crash count,
1020 // so very occasional crashes won't eventually add up and prevent the
1021 // GPU process from launching.
1022 ++gpu_recent_crash_count_
;
1023 base::Time current_time
= base::Time::Now();
1024 if (crashed_before_
) {
1025 int hours_different
= (current_time
- last_gpu_crash_time
).InHours();
1026 gpu_recent_crash_count_
=
1027 std::max(0, gpu_recent_crash_count_
- hours_different
);
1030 crashed_before_
= true;
1031 last_gpu_crash_time
= current_time
;
1033 if ((gpu_recent_crash_count_
>= kGpuMaxCrashCount
&&
1034 !disable_crash_limit
) ||
1036 #if !defined(OS_CHROMEOS)
1037 // The GPU process is too unstable to use. Disable it for current
1039 hardware_gpu_enabled_
= false;
1040 GpuDataManagerImpl::GetInstance()->DisableHardwareAcceleration();
1047 std::string
GpuProcessHost::GetShaderPrefixKey() {
1048 if (shader_prefix_key_
.empty()) {
1049 gpu::GPUInfo info
= GpuDataManagerImpl::GetInstance()->GetGPUInfo();
1051 std::string in_str
= GetContentClient()->GetProduct() + "-" +
1052 info
.gl_vendor
+ "-" + info
.gl_renderer
+ "-" +
1053 info
.driver_version
+ "-" + info
.driver_vendor
;
1055 base::Base64Encode(base::SHA1HashString(in_str
), &shader_prefix_key_
);
1058 return shader_prefix_key_
;
1061 void GpuProcessHost::LoadedShader(const std::string
& key
,
1062 const std::string
& data
) {
1063 std::string prefix
= GetShaderPrefixKey();
1064 if (!key
.compare(0, prefix
.length(), prefix
))
1065 Send(new GpuMsg_LoadedShader(data
));
1068 void GpuProcessHost::CreateChannelCache(int32 client_id
) {
1069 TRACE_EVENT0("gpu", "GpuProcessHost::CreateChannelCache");
1071 scoped_refptr
<ShaderDiskCache
> cache
=
1072 ShaderCacheFactory::GetInstance()->Get(client_id
);
1076 cache
->set_host_id(host_id_
);
1078 client_id_to_shader_cache_
[client_id
] = cache
;
1081 void GpuProcessHost::OnDestroyChannel(int32 client_id
) {
1082 TRACE_EVENT0("gpu", "GpuProcessHost::OnDestroyChannel");
1083 client_id_to_shader_cache_
.erase(client_id
);
1086 void GpuProcessHost::OnCacheShader(int32 client_id
,
1087 const std::string
& key
,
1088 const std::string
& shader
) {
1089 TRACE_EVENT0("gpu", "GpuProcessHost::OnCacheShader");
1090 ClientIdToShaderCacheMap::iterator iter
=
1091 client_id_to_shader_cache_
.find(client_id
);
1092 // If the cache doesn't exist then this is an off the record profile.
1093 if (iter
== client_id_to_shader_cache_
.end())
1095 iter
->second
->Cache(GetShaderPrefixKey() + ":" + key
, shader
);
1098 } // namespace content