1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/gpu/gpu_process_host.h"
7 #include "base/base64.h"
8 #include "base/base_switches.h"
9 #include "base/basictypes.h"
10 #include "base/bind.h"
11 #include "base/callback_helpers.h"
12 #include "base/command_line.h"
13 #include "base/logging.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/metrics/histogram.h"
16 #include "base/sha1.h"
17 #include "base/threading/thread.h"
18 #include "base/trace_event/trace_event.h"
19 #include "components/tracing/tracing_switches.h"
20 #include "content/browser/browser_child_process_host_impl.h"
21 #include "content/browser/gpu/compositor_util.h"
22 #include "content/browser/gpu/gpu_data_manager_impl.h"
23 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
24 #include "content/browser/gpu/shader_disk_cache.h"
25 #include "content/browser/renderer_host/render_widget_host_impl.h"
26 #include "content/browser/renderer_host/render_widget_resize_helper.h"
27 #include "content/common/child_process_host_impl.h"
28 #include "content/common/gpu/gpu_messages.h"
29 #include "content/common/in_process_child_thread_params.h"
30 #include "content/common/view_messages.h"
31 #include "content/public/browser/browser_thread.h"
32 #include "content/public/browser/content_browser_client.h"
33 #include "content/public/browser/render_process_host.h"
34 #include "content/public/browser/render_widget_host_view.h"
35 #include "content/public/browser/render_widget_host_view_frame_subscriber.h"
36 #include "content/public/common/content_client.h"
37 #include "content/public/common/content_switches.h"
38 #include "content/public/common/result_codes.h"
39 #include "content/public/common/sandbox_type.h"
40 #include "content/public/common/sandboxed_process_launcher_delegate.h"
41 #include "gpu/command_buffer/service/gpu_switches.h"
42 #include "ipc/ipc_channel_handle.h"
43 #include "ipc/ipc_switches.h"
44 #include "ipc/message_filter.h"
45 #include "media/base/media_switches.h"
46 #include "ui/base/ui_base_switches.h"
47 #include "ui/events/latency_info.h"
48 #include "ui/gl/gl_switches.h"
50 #if defined(OS_ANDROID)
51 #include "base/android/build_info.h"
55 #include "base/win/windows_version.h"
56 #include "content/common/sandbox_win.h"
57 #include "sandbox/win/src/sandbox_policy.h"
58 #include "ui/gfx/switches.h"
61 #if defined(USE_OZONE)
62 #include "ui/ozone/public/ozone_switches.h"
65 #if defined(USE_X11) && !defined(OS_CHROMEOS)
66 #include "ui/gfx/x/x11_switches.h"
69 #if defined(OS_MACOSX) && !defined(OS_IOS)
70 #include "content/browser/browser_io_surface_manager_mac.h"
71 #include "content/common/child_process_messages.h"
76 bool GpuProcessHost::gpu_enabled_
= true;
77 bool GpuProcessHost::hardware_gpu_enabled_
= true;
78 int GpuProcessHost::gpu_crash_count_
= 0;
79 int GpuProcessHost::gpu_recent_crash_count_
= 0;
80 bool GpuProcessHost::crashed_before_
= false;
81 int GpuProcessHost::swiftshader_crash_count_
= 0;
85 // Command-line switches to propagate to the GPU process.
86 static const char* const kSwitchNames
[] = {
87 switches::kDisableAcceleratedVideoDecode
,
88 switches::kDisableBreakpad
,
89 switches::kDisableGpuSandbox
,
90 switches::kDisableGpuWatchdog
,
91 switches::kDisableGLExtensions
,
92 switches::kDisableLogging
,
93 switches::kDisableSeccompFilterSandbox
,
94 #if defined(ENABLE_WEBRTC)
95 switches::kDisableWebRtcHWEncoding
,
98 switches::kEnableAcceleratedVpxDecode
,
100 switches::kEnableLogging
,
101 switches::kEnableShareGroupAsyncTextureUpload
,
102 #if defined(OS_CHROMEOS)
103 switches::kDisableVaapiAcceleratedVideoEncode
,
105 switches::kGpuStartupDialog
,
106 switches::kGpuSandboxAllowSysVShm
,
107 switches::kGpuSandboxFailuresFatal
,
108 switches::kGpuSandboxStartEarly
,
109 switches::kLoggingLevel
,
110 switches::kEnableLowEndDeviceMode
,
111 switches::kDisableLowEndDeviceMode
,
112 switches::kEnableMemoryBenchmarking
,
113 switches::kNoSandbox
,
114 switches::kProfilerTiming
,
115 switches::kTestGLLib
,
116 switches::kTraceStartup
,
117 switches::kTraceToConsole
,
120 #if defined(OS_MACOSX)
121 switches::kDisableRemoteCoreAnimation
,
122 switches::kDisableMacOverlays
,
123 switches::kEnableSandboxLogging
,
124 switches::kShowMacOverlayBorders
,
126 #if defined(USE_AURA)
127 switches::kUIPrioritizeInGpuProcess
,
129 #if defined(USE_OZONE)
130 switches::kOzonePlatform
,
131 switches::kOzoneUseSurfaceless
,
133 #if defined(USE_X11) && !defined(OS_CHROMEOS)
134 switches::kX11Display
,
138 enum GPUProcessLifetimeEvent
{
144 GPU_PROCESS_LIFETIME_EVENT_MAX
= 100
147 // Indexed by GpuProcessKind. There is one of each kind maximum. This array may
148 // only be accessed from the IO thread.
149 GpuProcessHost
* g_gpu_process_hosts
[GpuProcessHost::GPU_PROCESS_KIND_COUNT
];
152 void SendGpuProcessMessage(GpuProcessHost::GpuProcessKind kind
,
153 CauseForGpuLaunch cause
,
154 IPC::Message
* message
) {
155 GpuProcessHost
* host
= GpuProcessHost::Get(kind
, cause
);
163 // NOTE: changes to this class need to be reviewed by the security team.
164 class GpuSandboxedProcessLauncherDelegate
165 : public SandboxedProcessLauncherDelegate
{
167 GpuSandboxedProcessLauncherDelegate(base::CommandLine
* cmd_line
,
168 ChildProcessHost
* host
)
170 : cmd_line_(cmd_line
) {}
171 #elif defined(OS_POSIX)
172 : ipc_fd_(host
->TakeClientFileDescriptor()) {}
175 ~GpuSandboxedProcessLauncherDelegate() override
{}
178 bool ShouldSandbox() override
{
179 bool sandbox
= !cmd_line_
->HasSwitch(switches::kDisableGpuSandbox
);
181 DVLOG(1) << "GPU sandbox is disabled";
186 void PreSandbox(bool* disable_default_policy
,
187 base::FilePath
* exposed_dir
) override
{
188 *disable_default_policy
= true;
191 // For the GPU process we gotten as far as USER_LIMITED. The next level
192 // which is USER_RESTRICTED breaks both the DirectX backend and the OpenGL
193 // backend. Note that the GPU process is connected to the interactive
195 void PreSpawnTarget(sandbox::TargetPolicy
* policy
, bool* success
) override
{
196 if (base::win::GetVersion() > base::win::VERSION_XP
) {
197 if (cmd_line_
->GetSwitchValueASCII(switches::kUseGL
) ==
198 gfx::kGLImplementationDesktopName
) {
200 policy
->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS
,
201 sandbox::USER_LIMITED
);
202 SetJobLevel(*cmd_line_
, sandbox::JOB_UNPROTECTED
, 0, policy
);
203 policy
->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW
);
205 policy
->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS
,
206 sandbox::USER_LIMITED
);
208 // UI restrictions break when we access Windows from outside our job.
209 // However, we don't want a proxy window in this process because it can
210 // introduce deadlocks where the renderer blocks on the gpu, which in
211 // turn blocks on the browser UI thread. So, instead we forgo a window
212 // message pump entirely and just add job restrictions to prevent child
214 SetJobLevel(*cmd_line_
,
215 sandbox::JOB_LIMITED_USER
,
216 JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS
|
217 JOB_OBJECT_UILIMIT_DESKTOP
|
218 JOB_OBJECT_UILIMIT_EXITWINDOWS
|
219 JOB_OBJECT_UILIMIT_DISPLAYSETTINGS
,
222 policy
->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW
);
225 SetJobLevel(*cmd_line_
, sandbox::JOB_UNPROTECTED
, 0, policy
);
226 policy
->SetTokenLevel(sandbox::USER_UNPROTECTED
,
227 sandbox::USER_LIMITED
);
230 // Allow the server side of GPU sockets, which are pipes that have
231 // the "chrome.gpu" namespace and an arbitrary suffix.
232 sandbox::ResultCode result
= policy
->AddRule(
233 sandbox::TargetPolicy::SUBSYS_NAMED_PIPES
,
234 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY
,
235 L
"\\\\.\\pipe\\chrome.gpu.*");
236 if (result
!= sandbox::SBOX_ALL_OK
) {
241 // Block this DLL even if it is not loaded by the browser process.
242 policy
->AddDllToUnload(L
"cmsetac.dll");
245 // GPU also needs to add sections to the browser for aura
246 // TODO(jschuh): refactor the GPU channel to remove this. crbug.com/128786
247 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES
,
248 sandbox::TargetPolicy::HANDLES_DUP_BROKER
,
250 if (result
!= sandbox::SBOX_ALL_OK
) {
256 if (cmd_line_
->HasSwitch(switches::kEnableLogging
)) {
257 base::string16 log_file_path
= logging::GetLogFileFullPath();
258 if (!log_file_path
.empty()) {
259 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_FILES
,
260 sandbox::TargetPolicy::FILES_ALLOW_ANY
,
261 log_file_path
.c_str());
262 if (result
!= sandbox::SBOX_ALL_OK
) {
269 #elif defined(OS_POSIX)
271 base::ScopedFD
TakeIpcFd() override
{ return ipc_fd_
.Pass(); }
274 SandboxType
GetSandboxType() override
{
275 return SANDBOX_TYPE_GPU
;
280 base::CommandLine
* cmd_line_
;
281 #elif defined(OS_POSIX)
282 base::ScopedFD ipc_fd_
;
286 } // anonymous namespace
289 bool GpuProcessHost::ValidateHost(GpuProcessHost
* host
) {
290 // The Gpu process is invalid if it's not using SwiftShader, the card is
291 // blacklisted, and we can kill it and start over.
292 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
293 switches::kSingleProcess
) ||
294 base::CommandLine::ForCurrentProcess()->HasSwitch(
295 switches::kInProcessGPU
) ||
297 (host
->swiftshader_rendering_
||
298 !GpuDataManagerImpl::GetInstance()->ShouldUseSwiftShader()))) {
302 host
->ForceShutdown();
307 GpuProcessHost
* GpuProcessHost::Get(GpuProcessKind kind
,
308 CauseForGpuLaunch cause
) {
309 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
311 // Don't grant further access to GPU if it is not allowed.
312 GpuDataManagerImpl
* gpu_data_manager
= GpuDataManagerImpl::GetInstance();
313 DCHECK(gpu_data_manager
);
314 if (!gpu_data_manager
->GpuAccessAllowed(NULL
))
317 if (g_gpu_process_hosts
[kind
] && ValidateHost(g_gpu_process_hosts
[kind
]))
318 return g_gpu_process_hosts
[kind
];
320 if (cause
== CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH
)
323 static int last_host_id
= 0;
325 host_id
= ++last_host_id
;
327 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLaunchCause",
329 CAUSE_FOR_GPU_LAUNCH_MAX_ENUM
);
331 GpuProcessHost
* host
= new GpuProcessHost(host_id
, kind
);
335 // TODO(sievers): Revisit this behavior. It's not really a crash, but we also
336 // want the fallback-to-sw behavior if we cannot initialize the GPU.
337 host
->RecordProcessCrash();
344 void GpuProcessHost::GetProcessHandles(
345 const GpuDataManager::GetGpuProcessHandlesCallback
& callback
) {
346 if (!BrowserThread::CurrentlyOn(BrowserThread::IO
)) {
347 BrowserThread::PostTask(
350 base::Bind(&GpuProcessHost::GetProcessHandles
, callback
));
353 std::list
<base::ProcessHandle
> handles
;
354 for (size_t i
= 0; i
< arraysize(g_gpu_process_hosts
); ++i
) {
355 // TODO(rvargas) crbug/417532: don't store ProcessHandles!.
356 GpuProcessHost
* host
= g_gpu_process_hosts
[i
];
357 if (host
&& ValidateHost(host
))
358 handles
.push_back(host
->process_
->GetProcess().Handle());
360 BrowserThread::PostTask(
363 base::Bind(callback
, handles
));
367 void GpuProcessHost::SendOnIO(GpuProcessKind kind
,
368 CauseForGpuLaunch cause
,
369 IPC::Message
* message
) {
370 if (!BrowserThread::PostTask(
371 BrowserThread::IO
, FROM_HERE
,
373 &SendGpuProcessMessage
, kind
, cause
, message
))) {
378 GpuMainThreadFactoryFunction g_gpu_main_thread_factory
= NULL
;
380 void GpuProcessHost::RegisterGpuMainThreadFactory(
381 GpuMainThreadFactoryFunction create
) {
382 g_gpu_main_thread_factory
= create
;
386 GpuProcessHost
* GpuProcessHost::FromID(int host_id
) {
387 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
389 for (int i
= 0; i
< GPU_PROCESS_KIND_COUNT
; ++i
) {
390 GpuProcessHost
* host
= g_gpu_process_hosts
[i
];
391 if (host
&& host
->host_id_
== host_id
&& ValidateHost(host
))
398 GpuProcessHost::GpuProcessHost(int host_id
, GpuProcessKind kind
)
402 swiftshader_rendering_(false),
404 process_launched_(false),
406 uma_memory_stats_received_(false) {
407 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
408 switches::kSingleProcess
) ||
409 base::CommandLine::ForCurrentProcess()->HasSwitch(
410 switches::kInProcessGPU
)) {
414 // If the 'single GPU process' policy ever changes, we still want to maintain
415 // it for 'gpu thread' mode and only create one instance of host and thread.
416 DCHECK(!in_process_
|| g_gpu_process_hosts
[kind
] == NULL
);
418 g_gpu_process_hosts
[kind
] = this;
420 // Post a task to create the corresponding GpuProcessHostUIShim. The
421 // GpuProcessHostUIShim will be destroyed if either the browser exits,
422 // in which case it calls GpuProcessHostUIShim::DestroyAll, or the
423 // GpuProcessHost is destroyed, which happens when the corresponding GPU
424 // process terminates or fails to launch.
425 BrowserThread::PostTask(
428 base::Bind(base::IgnoreResult(&GpuProcessHostUIShim::Create
), host_id
));
430 process_
.reset(new BrowserChildProcessHostImpl(PROCESS_TYPE_GPU
, this));
433 GpuProcessHost::~GpuProcessHost() {
434 DCHECK(CalledOnValidThread());
436 SendOutstandingReplies();
438 // In case we never started, clean up.
439 while (!queued_messages_
.empty()) {
440 delete queued_messages_
.front();
441 queued_messages_
.pop();
444 #if defined(OS_MACOSX) && !defined(OS_IOS)
445 if (!io_surface_manager_token_
.IsZero()) {
446 BrowserIOSurfaceManager::GetInstance()->InvalidateGpuProcessToken();
447 io_surface_manager_token_
.SetZero();
451 // This is only called on the IO thread so no race against the constructor
452 // for another GpuProcessHost.
453 if (g_gpu_process_hosts
[kind_
] == this)
454 g_gpu_process_hosts
[kind_
] = NULL
;
456 // If there are any remaining offscreen contexts at the point the
457 // GPU process exits, assume something went wrong, and block their
458 // URLs from accessing client 3D APIs without prompting.
459 BlockLiveOffscreenContexts();
461 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitSurfaceCount",
462 GpuSurfaceTracker::Get()->GetSurfaceCount());
463 UMA_HISTOGRAM_BOOLEAN("GPU.AtExitReceivedMemoryStats",
464 uma_memory_stats_received_
);
466 if (uma_memory_stats_received_
) {
467 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitManagedMemoryClientCount",
468 uma_memory_stats_
.client_count
);
469 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitContextGroupCount",
470 uma_memory_stats_
.context_group_count
);
471 UMA_HISTOGRAM_CUSTOM_COUNTS(
472 "GPU.AtExitMBytesAllocated",
473 uma_memory_stats_
.bytes_allocated_current
/ 1024 / 1024, 1, 2000, 50);
474 UMA_HISTOGRAM_CUSTOM_COUNTS(
475 "GPU.AtExitMBytesAllocatedMax",
476 uma_memory_stats_
.bytes_allocated_max
/ 1024 / 1024, 1, 2000, 50);
477 UMA_HISTOGRAM_CUSTOM_COUNTS(
478 "GPU.AtExitMBytesLimit",
479 uma_memory_stats_
.bytes_limit
/ 1024 / 1024, 1, 2000, 50);
485 base::TerminationStatus status
= process_
->GetTerminationStatus(
486 false /* known_dead */, &exit_code
);
487 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessTerminationStatus",
489 base::TERMINATION_STATUS_MAX_ENUM
);
491 if (status
== base::TERMINATION_STATUS_NORMAL_TERMINATION
||
492 status
== base::TERMINATION_STATUS_ABNORMAL_TERMINATION
) {
493 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessExitCode",
495 RESULT_CODE_LAST_CODE
);
499 case base::TERMINATION_STATUS_NORMAL_TERMINATION
:
500 message
= "The GPU process exited normally. Everything is okay.";
502 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION
:
503 message
= base::StringPrintf(
504 "The GPU process exited with code %d.",
507 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED
:
508 message
= "You killed the GPU process! Why?";
510 #if defined(OS_CHROMEOS)
511 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM
:
512 message
= "The GUP process was killed due to out of memory.";
515 case base::TERMINATION_STATUS_PROCESS_CRASHED
:
516 message
= "The GPU process crashed!";
523 BrowserThread::PostTask(BrowserThread::UI
,
525 base::Bind(&GpuProcessHostUIShim::Destroy
,
530 bool GpuProcessHost::Init() {
531 init_start_time_
= base::TimeTicks::Now();
533 TRACE_EVENT_INSTANT0("gpu", "LaunchGpuProcess", TRACE_EVENT_SCOPE_THREAD
);
535 std::string channel_id
= process_
->GetHost()->CreateChannel();
536 if (channel_id
.empty())
540 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
541 DCHECK(g_gpu_main_thread_factory
);
542 in_process_gpu_thread_
.reset(
543 g_gpu_main_thread_factory(InProcessChildThreadParams(
544 channel_id
, base::MessageLoop::current()->task_runner())));
545 base::Thread::Options options
;
547 // WGL needs to create its own window and pump messages on it.
548 options
.message_loop_type
= base::MessageLoop::TYPE_UI
;
550 in_process_gpu_thread_
->StartWithOptions(options
);
552 OnProcessLaunched(); // Fake a callback that the process is ready.
553 } else if (!LaunchGpuProcess(channel_id
)) {
557 if (!Send(new GpuMsg_Initialize()))
560 #if defined(OS_MACOSX) && !defined(OS_IOS)
561 io_surface_manager_token_
=
562 BrowserIOSurfaceManager::GetInstance()->GenerateGpuProcessToken();
563 // Note: A valid IOSurface manager token needs to be sent to the Gpu process
564 // before any GpuMemoryBuffer allocation requests can be sent.
565 Send(new ChildProcessMsg_SetIOSurfaceManagerToken(io_surface_manager_token_
));
571 void GpuProcessHost::RouteOnUIThread(const IPC::Message
& message
) {
572 BrowserThread::PostTask(
575 base::Bind(&RouteToGpuProcessHostUIShimTask
, host_id_
, message
));
578 bool GpuProcessHost::Send(IPC::Message
* msg
) {
579 DCHECK(CalledOnValidThread());
580 if (process_
->GetHost()->IsChannelOpening()) {
581 queued_messages_
.push(msg
);
585 bool result
= process_
->Send(msg
);
587 // Channel is hosed, but we may not get destroyed for a while. Send
588 // outstanding channel creation failures now so that the caller can restart
589 // with a new process/channel without waiting.
590 SendOutstandingReplies();
595 void GpuProcessHost::AddFilter(IPC::MessageFilter
* filter
) {
596 DCHECK(CalledOnValidThread());
597 process_
->GetHost()->AddFilter(filter
);
600 bool GpuProcessHost::OnMessageReceived(const IPC::Message
& message
) {
601 DCHECK(CalledOnValidThread());
602 IPC_BEGIN_MESSAGE_MAP(GpuProcessHost
, message
)
603 IPC_MESSAGE_HANDLER(GpuHostMsg_Initialized
, OnInitialized
)
604 IPC_MESSAGE_HANDLER(GpuHostMsg_ChannelEstablished
, OnChannelEstablished
)
605 IPC_MESSAGE_HANDLER(GpuHostMsg_CommandBufferCreated
, OnCommandBufferCreated
)
606 IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyCommandBuffer
, OnDestroyCommandBuffer
)
607 IPC_MESSAGE_HANDLER(GpuHostMsg_GpuMemoryBufferCreated
,
608 OnGpuMemoryBufferCreated
)
609 IPC_MESSAGE_HANDLER(GpuHostMsg_DidCreateOffscreenContext
,
610 OnDidCreateOffscreenContext
)
611 IPC_MESSAGE_HANDLER(GpuHostMsg_DidLoseContext
, OnDidLoseContext
)
612 IPC_MESSAGE_HANDLER(GpuHostMsg_DidDestroyOffscreenContext
,
613 OnDidDestroyOffscreenContext
)
614 IPC_MESSAGE_HANDLER(GpuHostMsg_GpuMemoryUmaStats
,
615 OnGpuMemoryUmaStatsReceived
)
616 #if defined(OS_MACOSX)
617 IPC_MESSAGE_HANDLER_GENERIC(GpuHostMsg_AcceleratedSurfaceBuffersSwapped
,
618 OnAcceleratedSurfaceBuffersSwapped(message
))
620 IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyChannel
,
622 IPC_MESSAGE_HANDLER(GpuHostMsg_CacheShader
,
625 IPC_MESSAGE_UNHANDLED(RouteOnUIThread(message
))
626 IPC_END_MESSAGE_MAP()
631 void GpuProcessHost::OnChannelConnected(int32 peer_pid
) {
632 TRACE_EVENT0("gpu", "GpuProcessHost::OnChannelConnected");
634 while (!queued_messages_
.empty()) {
635 Send(queued_messages_
.front());
636 queued_messages_
.pop();
640 void GpuProcessHost::EstablishGpuChannel(
642 uint64_t client_tracing_id
,
644 bool allow_future_sync_points
,
645 const EstablishChannelCallback
& callback
) {
646 DCHECK(CalledOnValidThread());
647 TRACE_EVENT0("gpu", "GpuProcessHost::EstablishGpuChannel");
649 // If GPU features are already blacklisted, no need to establish the channel.
650 if (!GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL
)) {
651 DVLOG(1) << "GPU blacklisted, refusing to open a GPU channel.";
652 callback
.Run(IPC::ChannelHandle(), gpu::GPUInfo());
656 if (Send(new GpuMsg_EstablishChannel(client_id
, client_tracing_id
,
658 allow_future_sync_points
))) {
659 channel_requests_
.push(callback
);
661 DVLOG(1) << "Failed to send GpuMsg_EstablishChannel.";
662 callback
.Run(IPC::ChannelHandle(), gpu::GPUInfo());
665 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
666 switches::kDisableGpuShaderDiskCache
)) {
667 CreateChannelCache(client_id
);
671 void GpuProcessHost::CreateViewCommandBuffer(
672 const gfx::GLSurfaceHandle
& compositing_surface
,
675 const GPUCreateCommandBufferConfig
& init_params
,
677 const CreateCommandBufferCallback
& callback
) {
678 TRACE_EVENT0("gpu", "GpuProcessHost::CreateViewCommandBuffer");
680 DCHECK(CalledOnValidThread());
682 if (!compositing_surface
.is_null() &&
683 Send(new GpuMsg_CreateViewCommandBuffer(
684 compositing_surface
, surface_id
, client_id
, init_params
, route_id
))) {
685 create_command_buffer_requests_
.push(callback
);
686 surface_refs_
.insert(std::make_pair(surface_id
,
687 GpuSurfaceTracker::GetInstance()->GetSurfaceRefForSurface(surface_id
)));
689 // Could distinguish here between compositing_surface being NULL
690 // and Send failing, if desired.
691 callback
.Run(CREATE_COMMAND_BUFFER_FAILED_AND_CHANNEL_LOST
);
695 void GpuProcessHost::CreateGpuMemoryBuffer(
696 gfx::GpuMemoryBufferId id
,
697 const gfx::Size
& size
,
698 gfx::BufferFormat format
,
699 gfx::BufferUsage usage
,
702 const CreateGpuMemoryBufferCallback
& callback
) {
703 TRACE_EVENT0("gpu", "GpuProcessHost::CreateGpuMemoryBuffer");
705 DCHECK(CalledOnValidThread());
707 GpuMsg_CreateGpuMemoryBuffer_Params params
;
710 params
.format
= format
;
711 params
.usage
= usage
;
712 params
.client_id
= client_id
;
713 params
.surface_handle
=
714 GpuSurfaceTracker::GetInstance()->GetSurfaceHandle(surface_id
).handle
;
715 if (Send(new GpuMsg_CreateGpuMemoryBuffer(params
))) {
716 create_gpu_memory_buffer_requests_
.push(callback
);
717 create_gpu_memory_buffer_surface_refs_
.push(surface_id
);
719 surface_refs_
.insert(std::make_pair(
720 surface_id
, GpuSurfaceTracker::GetInstance()->GetSurfaceRefForSurface(
724 callback
.Run(gfx::GpuMemoryBufferHandle());
728 void GpuProcessHost::DestroyGpuMemoryBuffer(gfx::GpuMemoryBufferId id
,
731 TRACE_EVENT0("gpu", "GpuProcessHost::DestroyGpuMemoryBuffer");
733 DCHECK(CalledOnValidThread());
735 Send(new GpuMsg_DestroyGpuMemoryBuffer(id
, client_id
, sync_point
));
738 void GpuProcessHost::OnInitialized(bool result
, const gpu::GPUInfo
& gpu_info
) {
739 UMA_HISTOGRAM_BOOLEAN("GPU.GPUProcessInitialized", result
);
740 initialized_
= result
;
743 GpuDataManagerImpl::GetInstance()->OnGpuProcessInitFailure();
744 else if (!in_process_
)
745 GpuDataManagerImpl::GetInstance()->UpdateGpuInfo(gpu_info
);
748 void GpuProcessHost::OnChannelEstablished(
749 const IPC::ChannelHandle
& channel_handle
) {
750 TRACE_EVENT0("gpu", "GpuProcessHost::OnChannelEstablished");
752 if (channel_requests_
.empty()) {
753 // This happens when GPU process is compromised.
754 RouteOnUIThread(GpuHostMsg_OnLogMessage(
755 logging::LOG_WARNING
,
757 "Received a ChannelEstablished message but no requests in queue."));
760 EstablishChannelCallback callback
= channel_requests_
.front();
761 channel_requests_
.pop();
763 // Currently if any of the GPU features are blacklisted, we don't establish a
765 if (!channel_handle
.name
.empty() &&
766 !GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL
)) {
767 Send(new GpuMsg_CloseChannel(channel_handle
));
768 callback
.Run(IPC::ChannelHandle(), gpu::GPUInfo());
769 RouteOnUIThread(GpuHostMsg_OnLogMessage(
770 logging::LOG_WARNING
,
772 "Hardware acceleration is unavailable."));
776 callback
.Run(channel_handle
,
777 GpuDataManagerImpl::GetInstance()->GetGPUInfo());
780 void GpuProcessHost::OnCommandBufferCreated(CreateCommandBufferResult result
) {
781 TRACE_EVENT0("gpu", "GpuProcessHost::OnCommandBufferCreated");
783 if (create_command_buffer_requests_
.empty())
786 CreateCommandBufferCallback callback
=
787 create_command_buffer_requests_
.front();
788 create_command_buffer_requests_
.pop();
789 callback
.Run(result
);
792 void GpuProcessHost::OnDestroyCommandBuffer(int32 surface_id
) {
793 TRACE_EVENT0("gpu", "GpuProcessHost::OnDestroyCommandBuffer");
794 SurfaceRefMap::iterator it
= surface_refs_
.find(surface_id
);
795 if (it
!= surface_refs_
.end()) {
796 surface_refs_
.erase(it
);
800 void GpuProcessHost::OnGpuMemoryBufferCreated(
801 const gfx::GpuMemoryBufferHandle
& handle
) {
802 TRACE_EVENT0("gpu", "GpuProcessHost::OnGpuMemoryBufferCreated");
804 if (create_gpu_memory_buffer_requests_
.empty())
807 CreateGpuMemoryBufferCallback callback
=
808 create_gpu_memory_buffer_requests_
.front();
809 create_gpu_memory_buffer_requests_
.pop();
810 callback
.Run(handle
);
812 int32 surface_id
= create_gpu_memory_buffer_surface_refs_
.front();
813 create_gpu_memory_buffer_surface_refs_
.pop();
814 SurfaceRefMap::iterator it
= surface_refs_
.find(surface_id
);
815 if (it
!= surface_refs_
.end()) {
816 surface_refs_
.erase(it
);
820 void GpuProcessHost::OnDidCreateOffscreenContext(const GURL
& url
) {
821 urls_with_live_offscreen_contexts_
.insert(url
);
824 void GpuProcessHost::OnDidLoseContext(bool offscreen
,
825 gpu::error::ContextLostReason reason
,
827 // TODO(kbr): would be nice to see the "offscreen" flag too.
828 TRACE_EVENT2("gpu", "GpuProcessHost::OnDidLoseContext",
831 url
.possibly_invalid_spec());
833 if (!offscreen
|| url
.is_empty()) {
834 // Assume that the loss of the compositor's or accelerated canvas'
835 // context is a serious event and blame the loss on all live
836 // offscreen contexts. This more robustly handles situations where
837 // the GPU process may not actually detect the context loss in the
838 // offscreen context.
839 BlockLiveOffscreenContexts();
843 GpuDataManagerImpl::DomainGuilt guilt
;
845 case gpu::error::kGuilty
:
846 guilt
= GpuDataManagerImpl::DOMAIN_GUILT_KNOWN
;
848 case gpu::error::kUnknown
:
849 guilt
= GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN
;
851 case gpu::error::kInnocent
:
858 GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(url
, guilt
);
861 void GpuProcessHost::OnDidDestroyOffscreenContext(const GURL
& url
) {
862 urls_with_live_offscreen_contexts_
.erase(url
);
865 void GpuProcessHost::OnGpuMemoryUmaStatsReceived(
866 const GPUMemoryUmaStats
& stats
) {
867 TRACE_EVENT0("gpu", "GpuProcessHost::OnGpuMemoryUmaStatsReceived");
868 uma_memory_stats_received_
= true;
869 uma_memory_stats_
= stats
;
872 #if defined(OS_MACOSX)
873 void GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped(
874 const IPC::Message
& message
) {
875 RenderWidgetResizeHelper::Get()->PostGpuProcessMsg(host_id_
, message
);
879 void GpuProcessHost::OnProcessLaunched() {
880 UMA_HISTOGRAM_TIMES("GPU.GPUProcessLaunchTime",
881 base::TimeTicks::Now() - init_start_time_
);
884 void GpuProcessHost::OnProcessLaunchFailed() {
885 RecordProcessCrash();
888 void GpuProcessHost::OnProcessCrashed(int exit_code
) {
889 SendOutstandingReplies();
890 RecordProcessCrash();
891 GpuDataManagerImpl::GetInstance()->ProcessCrashed(
892 process_
->GetTerminationStatus(true /* known_dead */, NULL
));
895 GpuProcessHost::GpuProcessKind
GpuProcessHost::kind() {
899 void GpuProcessHost::ForceShutdown() {
900 // This is only called on the IO thread so no race against the constructor
901 // for another GpuProcessHost.
902 if (g_gpu_process_hosts
[kind_
] == this)
903 g_gpu_process_hosts
[kind_
] = NULL
;
905 #if defined(OS_MACOSX) && !defined(OS_IOS)
906 if (!io_surface_manager_token_
.IsZero()) {
907 BrowserIOSurfaceManager::GetInstance()->InvalidateGpuProcessToken();
908 io_surface_manager_token_
.SetZero();
912 process_
->ForceShutdown();
915 void GpuProcessHost::StopGpuProcess() {
916 Send(new GpuMsg_Finalize());
919 void GpuProcessHost::BeginFrameSubscription(
921 base::WeakPtr
<RenderWidgetHostViewFrameSubscriber
> subscriber
) {
922 frame_subscribers_
[surface_id
] = subscriber
;
925 void GpuProcessHost::EndFrameSubscription(int surface_id
) {
926 frame_subscribers_
.erase(surface_id
);
929 bool GpuProcessHost::LaunchGpuProcess(const std::string
& channel_id
) {
930 if (!(gpu_enabled_
&&
931 GpuDataManagerImpl::GetInstance()->ShouldUseSwiftShader()) &&
932 !hardware_gpu_enabled_
) {
933 SendOutstandingReplies();
937 const base::CommandLine
& browser_command_line
=
938 *base::CommandLine::ForCurrentProcess();
940 base::CommandLine::StringType gpu_launcher
=
941 browser_command_line
.GetSwitchValueNative(switches::kGpuLauncher
);
943 #if defined(OS_ANDROID)
944 // crbug.com/447735. readlink("self/proc/exe") sometimes fails on Android
945 // at startup with EACCES. As a workaround ignore this here, since the
946 // executable name is actually not used or useful anyways.
947 base::CommandLine
* cmd_line
=
948 new base::CommandLine(base::CommandLine::NO_PROGRAM
);
950 #if defined(OS_LINUX)
951 int child_flags
= gpu_launcher
.empty() ? ChildProcessHost::CHILD_ALLOW_SELF
:
952 ChildProcessHost::CHILD_NORMAL
;
954 int child_flags
= ChildProcessHost::CHILD_NORMAL
;
957 base::FilePath exe_path
= ChildProcessHost::GetChildPath(child_flags
);
958 if (exe_path
.empty())
961 base::CommandLine
* cmd_line
= new base::CommandLine(exe_path
);
963 cmd_line
->AppendSwitchASCII(switches::kProcessType
, switches::kGpuProcess
);
964 cmd_line
->AppendSwitchASCII(switches::kProcessChannelID
, channel_id
);
966 if (kind_
== GPU_PROCESS_KIND_UNSANDBOXED
)
967 cmd_line
->AppendSwitch(switches::kDisableGpuSandbox
);
969 // If you want a browser command-line switch passed to the GPU process
970 // you need to add it to |kSwitchNames| at the beginning of this file.
971 cmd_line
->CopySwitchesFrom(browser_command_line
, kSwitchNames
,
972 arraysize(kSwitchNames
));
973 cmd_line
->CopySwitchesFrom(
974 browser_command_line
, switches::kGpuSwitches
, switches::kNumGpuSwitches
);
975 cmd_line
->CopySwitchesFrom(
976 browser_command_line
, switches::kGLSwitchesCopiedFromGpuProcessHost
,
977 switches::kGLSwitchesCopiedFromGpuProcessHostNumSwitches
);
979 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
980 cmd_line
, process_
->GetData().id
);
982 GpuDataManagerImpl::GetInstance()->AppendGpuCommandLine(cmd_line
);
984 if (cmd_line
->HasSwitch(switches::kUseGL
)) {
985 swiftshader_rendering_
=
986 (cmd_line
->GetSwitchValueASCII(switches::kUseGL
) == "swiftshader");
989 UMA_HISTOGRAM_BOOLEAN("GPU.GPU.GPUProcessSoftwareRendering",
990 swiftshader_rendering_
);
992 // If specified, prepend a launcher program to the command line.
993 if (!gpu_launcher
.empty())
994 cmd_line
->PrependWrapper(gpu_launcher
);
997 new GpuSandboxedProcessLauncherDelegate(cmd_line
,
998 process_
->GetHost()),
1001 process_launched_
= true;
1003 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
1004 LAUNCHED
, GPU_PROCESS_LIFETIME_EVENT_MAX
);
1008 void GpuProcessHost::SendOutstandingReplies() {
1010 // First send empty channel handles for all EstablishChannel requests.
1011 while (!channel_requests_
.empty()) {
1012 EstablishChannelCallback callback
= channel_requests_
.front();
1013 channel_requests_
.pop();
1014 callback
.Run(IPC::ChannelHandle(), gpu::GPUInfo());
1017 while (!create_command_buffer_requests_
.empty()) {
1018 CreateCommandBufferCallback callback
=
1019 create_command_buffer_requests_
.front();
1020 create_command_buffer_requests_
.pop();
1021 callback
.Run(CREATE_COMMAND_BUFFER_FAILED_AND_CHANNEL_LOST
);
1024 while (!create_gpu_memory_buffer_requests_
.empty()) {
1025 CreateGpuMemoryBufferCallback callback
=
1026 create_gpu_memory_buffer_requests_
.front();
1027 create_gpu_memory_buffer_requests_
.pop();
1028 callback
.Run(gfx::GpuMemoryBufferHandle());
1032 void GpuProcessHost::BlockLiveOffscreenContexts() {
1033 for (std::multiset
<GURL
>::iterator iter
=
1034 urls_with_live_offscreen_contexts_
.begin();
1035 iter
!= urls_with_live_offscreen_contexts_
.end(); ++iter
) {
1036 GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(
1037 *iter
, GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN
);
1041 void GpuProcessHost::RecordProcessCrash() {
1042 // Maximum number of times the GPU process is allowed to crash in a session.
1043 // Once this limit is reached, any request to launch the GPU process will
1045 const int kGpuMaxCrashCount
= 3;
1047 // Last time the GPU process crashed.
1048 static base::Time last_gpu_crash_time
;
1050 bool disable_crash_limit
= base::CommandLine::ForCurrentProcess()->HasSwitch(
1051 switches::kDisableGpuProcessCrashLimit
);
1053 // Ending only acts as a failure if the GPU process was actually started and
1054 // was intended for actual rendering (and not just checking caps or other
1056 if (process_launched_
&& kind_
== GPU_PROCESS_KIND_SANDBOXED
) {
1057 if (swiftshader_rendering_
) {
1058 UMA_HISTOGRAM_ENUMERATION("GPU.SwiftShaderLifetimeEvents",
1059 DIED_FIRST_TIME
+ swiftshader_crash_count_
,
1060 GPU_PROCESS_LIFETIME_EVENT_MAX
);
1062 if (++swiftshader_crash_count_
>= kGpuMaxCrashCount
&&
1063 !disable_crash_limit
) {
1064 // SwiftShader is too unstable to use. Disable it for current session.
1065 gpu_enabled_
= false;
1069 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
1070 std::min(DIED_FIRST_TIME
+ gpu_crash_count_
,
1071 GPU_PROCESS_LIFETIME_EVENT_MAX
- 1),
1072 GPU_PROCESS_LIFETIME_EVENT_MAX
);
1074 // Allow about 1 GPU crash per hour to be removed from the crash count,
1075 // so very occasional crashes won't eventually add up and prevent the
1076 // GPU process from launching.
1077 ++gpu_recent_crash_count_
;
1078 base::Time current_time
= base::Time::Now();
1079 if (crashed_before_
) {
1080 int hours_different
= (current_time
- last_gpu_crash_time
).InHours();
1081 gpu_recent_crash_count_
=
1082 std::max(0, gpu_recent_crash_count_
- hours_different
);
1085 crashed_before_
= true;
1086 last_gpu_crash_time
= current_time
;
1088 if ((gpu_recent_crash_count_
>= kGpuMaxCrashCount
&&
1089 !disable_crash_limit
) ||
1091 #if !defined(OS_CHROMEOS)
1092 // The GPU process is too unstable to use. Disable it for current
1094 hardware_gpu_enabled_
= false;
1095 GpuDataManagerImpl::GetInstance()->DisableHardwareAcceleration();
1102 std::string
GpuProcessHost::GetShaderPrefixKey() {
1103 if (shader_prefix_key_
.empty()) {
1104 gpu::GPUInfo info
= GpuDataManagerImpl::GetInstance()->GetGPUInfo();
1106 std::string in_str
= GetContentClient()->GetProduct() + "-" +
1107 #if defined(OS_ANDROID)
1108 base::android::BuildInfo::GetInstance()->android_build_fp() + "-" +
1110 info
.gl_vendor
+ "-" + info
.gl_renderer
+ "-" +
1111 info
.driver_version
+ "-" + info
.driver_vendor
;
1113 base::Base64Encode(base::SHA1HashString(in_str
), &shader_prefix_key_
);
1116 return shader_prefix_key_
;
1119 void GpuProcessHost::LoadedShader(const std::string
& key
,
1120 const std::string
& data
) {
1121 std::string prefix
= GetShaderPrefixKey();
1122 if (!key
.compare(0, prefix
.length(), prefix
))
1123 Send(new GpuMsg_LoadedShader(data
));
1126 void GpuProcessHost::CreateChannelCache(int32 client_id
) {
1127 TRACE_EVENT0("gpu", "GpuProcessHost::CreateChannelCache");
1129 scoped_refptr
<ShaderDiskCache
> cache
=
1130 ShaderCacheFactory::GetInstance()->Get(client_id
);
1134 cache
->set_host_id(host_id_
);
1136 client_id_to_shader_cache_
[client_id
] = cache
;
1139 void GpuProcessHost::OnDestroyChannel(int32 client_id
) {
1140 TRACE_EVENT0("gpu", "GpuProcessHost::OnDestroyChannel");
1141 client_id_to_shader_cache_
.erase(client_id
);
1144 void GpuProcessHost::OnCacheShader(int32 client_id
,
1145 const std::string
& key
,
1146 const std::string
& shader
) {
1147 TRACE_EVENT0("gpu", "GpuProcessHost::OnCacheShader");
1148 ClientIdToShaderCacheMap::iterator iter
=
1149 client_id_to_shader_cache_
.find(client_id
);
1150 // If the cache doesn't exist then this is an off the record profile.
1151 if (iter
== client_id_to_shader_cache_
.end())
1153 iter
->second
->Cache(GetShaderPrefixKey() + ":" + key
, shader
);
1156 } // namespace content