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/view_messages.h"
29 #include "content/public/browser/browser_thread.h"
30 #include "content/public/browser/content_browser_client.h"
31 #include "content/public/browser/render_process_host.h"
32 #include "content/public/browser/render_widget_host_view.h"
33 #include "content/public/browser/render_widget_host_view_frame_subscriber.h"
34 #include "content/public/common/content_client.h"
35 #include "content/public/common/content_switches.h"
36 #include "content/public/common/result_codes.h"
37 #include "content/public/common/sandboxed_process_launcher_delegate.h"
38 #include "gpu/command_buffer/service/gpu_switches.h"
39 #include "ipc/ipc_channel_handle.h"
40 #include "ipc/ipc_switches.h"
41 #include "ipc/message_filter.h"
42 #include "media/base/media_switches.h"
43 #include "ui/base/ui_base_switches.h"
44 #include "ui/events/latency_info.h"
45 #include "ui/gl/gl_switches.h"
48 #include "base/win/windows_version.h"
49 #include "content/common/sandbox_win.h"
50 #include "sandbox/win/src/sandbox_policy.h"
51 #include "ui/gfx/switches.h"
54 #if defined(USE_OZONE)
55 #include "ui/ozone/public/ozone_switches.h"
58 #if defined(USE_X11) && !defined(OS_CHROMEOS)
59 #include "ui/gfx/x/x11_switches.h"
64 bool GpuProcessHost::gpu_enabled_
= true;
65 bool GpuProcessHost::hardware_gpu_enabled_
= true;
66 int GpuProcessHost::gpu_crash_count_
= 0;
67 int GpuProcessHost::gpu_recent_crash_count_
= 0;
68 bool GpuProcessHost::crashed_before_
= false;
69 int GpuProcessHost::swiftshader_crash_count_
= 0;
73 // Command-line switches to propagate to the GPU process.
74 static const char* const kSwitchNames
[] = {
75 switches::kDisableAcceleratedVideoDecode
,
76 switches::kDisableBreakpad
,
77 switches::kDisableGpuSandbox
,
78 switches::kDisableGpuWatchdog
,
79 switches::kDisableLogging
,
80 switches::kDisableSeccompFilterSandbox
,
81 #if defined(ENABLE_WEBRTC)
82 switches::kDisableWebRtcHWEncoding
,
84 switches::kEnableLogging
,
85 switches::kEnableShareGroupAsyncTextureUpload
,
86 #if defined(OS_CHROMEOS)
87 switches::kDisableVaapiAcceleratedVideoEncode
,
89 switches::kGpuStartupDialog
,
90 switches::kGpuSandboxAllowSysVShm
,
91 switches::kGpuSandboxFailuresFatal
,
92 switches::kGpuSandboxStartEarly
,
93 switches::kIgnoreResolutionLimitsForAcceleratedVideoDecode
,
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 virtual bool ShouldSandbox() override
{
161 bool sandbox
= !cmd_line_
->HasSwitch(switches::kDisableGpuSandbox
);
163 DVLOG(1) << "GPU sandbox is disabled";
168 virtual 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 virtual void PreSpawnTarget(sandbox::TargetPolicy
* policy
,
179 if (base::win::GetVersion() > base::win::VERSION_XP
) {
180 if (cmd_line_
->GetSwitchValueASCII(switches::kUseGL
) ==
181 gfx::kGLImplementationDesktopName
) {
183 policy
->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS
,
184 sandbox::USER_LIMITED
);
185 SetJobLevel(*cmd_line_
, sandbox::JOB_UNPROTECTED
, 0, policy
);
186 policy
->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW
);
188 policy
->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS
,
189 sandbox::USER_LIMITED
);
191 // UI restrictions break when we access Windows from outside our job.
192 // However, we don't want a proxy window in this process because it can
193 // introduce deadlocks where the renderer blocks on the gpu, which in
194 // turn blocks on the browser UI thread. So, instead we forgo a window
195 // message pump entirely and just add job restrictions to prevent child
197 SetJobLevel(*cmd_line_
,
198 sandbox::JOB_LIMITED_USER
,
199 JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS
|
200 JOB_OBJECT_UILIMIT_DESKTOP
|
201 JOB_OBJECT_UILIMIT_EXITWINDOWS
|
202 JOB_OBJECT_UILIMIT_DISPLAYSETTINGS
,
205 policy
->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW
);
208 SetJobLevel(*cmd_line_
, sandbox::JOB_UNPROTECTED
, 0, policy
);
209 policy
->SetTokenLevel(sandbox::USER_UNPROTECTED
,
210 sandbox::USER_LIMITED
);
213 // Allow the server side of GPU sockets, which are pipes that have
214 // the "chrome.gpu" namespace and an arbitrary suffix.
215 sandbox::ResultCode result
= policy
->AddRule(
216 sandbox::TargetPolicy::SUBSYS_NAMED_PIPES
,
217 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY
,
218 L
"\\\\.\\pipe\\chrome.gpu.*");
219 if (result
!= sandbox::SBOX_ALL_OK
) {
224 // Block this DLL even if it is not loaded by the browser process.
225 policy
->AddDllToUnload(L
"cmsetac.dll");
228 // GPU also needs to add sections to the browser for aura
229 // TODO(jschuh): refactor the GPU channel to remove this. crbug.com/128786
230 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES
,
231 sandbox::TargetPolicy::HANDLES_DUP_BROKER
,
233 if (result
!= sandbox::SBOX_ALL_OK
) {
239 if (cmd_line_
->HasSwitch(switches::kEnableLogging
)) {
240 base::string16 log_file_path
= logging::GetLogFileFullPath();
241 if (!log_file_path
.empty()) {
242 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_FILES
,
243 sandbox::TargetPolicy::FILES_ALLOW_ANY
,
244 log_file_path
.c_str());
245 if (result
!= sandbox::SBOX_ALL_OK
) {
252 #elif defined(OS_POSIX)
254 base::ScopedFD
TakeIpcFd() override
{ return ipc_fd_
.Pass(); }
259 base::CommandLine
* cmd_line_
;
260 #elif defined(OS_POSIX)
261 base::ScopedFD ipc_fd_
;
265 } // anonymous namespace
268 bool GpuProcessHost::ValidateHost(GpuProcessHost
* host
) {
269 // The Gpu process is invalid if it's not using SwiftShader, the card is
270 // blacklisted, and we can kill it and start over.
271 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
272 switches::kSingleProcess
) ||
273 base::CommandLine::ForCurrentProcess()->HasSwitch(
274 switches::kInProcessGPU
) ||
276 (host
->swiftshader_rendering_
||
277 !GpuDataManagerImpl::GetInstance()->ShouldUseSwiftShader()))) {
281 host
->ForceShutdown();
286 GpuProcessHost
* GpuProcessHost::Get(GpuProcessKind kind
,
287 CauseForGpuLaunch cause
) {
288 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
290 // Don't grant further access to GPU if it is not allowed.
291 GpuDataManagerImpl
* gpu_data_manager
= GpuDataManagerImpl::GetInstance();
292 DCHECK(gpu_data_manager
);
293 if (!gpu_data_manager
->GpuAccessAllowed(NULL
))
296 if (g_gpu_process_hosts
[kind
] && ValidateHost(g_gpu_process_hosts
[kind
]))
297 return g_gpu_process_hosts
[kind
];
299 if (cause
== CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH
)
302 static int last_host_id
= 0;
304 host_id
= ++last_host_id
;
306 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLaunchCause",
308 CAUSE_FOR_GPU_LAUNCH_MAX_ENUM
);
310 GpuProcessHost
* host
= new GpuProcessHost(host_id
, kind
);
319 void GpuProcessHost::GetProcessHandles(
320 const GpuDataManager::GetGpuProcessHandlesCallback
& callback
) {
321 if (!BrowserThread::CurrentlyOn(BrowserThread::IO
)) {
322 BrowserThread::PostTask(
325 base::Bind(&GpuProcessHost::GetProcessHandles
, callback
));
328 std::list
<base::ProcessHandle
> handles
;
329 for (size_t i
= 0; i
< arraysize(g_gpu_process_hosts
); ++i
) {
330 // TODO(rvargas) crbug/417532: don't store ProcessHandles!.
331 GpuProcessHost
* host
= g_gpu_process_hosts
[i
];
332 if (host
&& ValidateHost(host
))
333 handles
.push_back(host
->process_
->GetProcess().Handle());
335 BrowserThread::PostTask(
338 base::Bind(callback
, handles
));
342 void GpuProcessHost::SendOnIO(GpuProcessKind kind
,
343 CauseForGpuLaunch cause
,
344 IPC::Message
* message
) {
345 if (!BrowserThread::PostTask(
346 BrowserThread::IO
, FROM_HERE
,
348 &SendGpuProcessMessage
, kind
, cause
, message
))) {
353 GpuMainThreadFactoryFunction g_gpu_main_thread_factory
= NULL
;
355 void GpuProcessHost::RegisterGpuMainThreadFactory(
356 GpuMainThreadFactoryFunction create
) {
357 g_gpu_main_thread_factory
= create
;
361 GpuProcessHost
* GpuProcessHost::FromID(int host_id
) {
362 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
364 for (int i
= 0; i
< GPU_PROCESS_KIND_COUNT
; ++i
) {
365 GpuProcessHost
* host
= g_gpu_process_hosts
[i
];
366 if (host
&& host
->host_id_
== host_id
&& ValidateHost(host
))
373 GpuProcessHost::GpuProcessHost(int host_id
, GpuProcessKind kind
)
377 swiftshader_rendering_(false),
379 process_launched_(false),
381 gpu_crash_recorded_(false),
382 uma_memory_stats_received_(false) {
383 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
384 switches::kSingleProcess
) ||
385 base::CommandLine::ForCurrentProcess()->HasSwitch(
386 switches::kInProcessGPU
)) {
390 // If the 'single GPU process' policy ever changes, we still want to maintain
391 // it for 'gpu thread' mode and only create one instance of host and thread.
392 DCHECK(!in_process_
|| g_gpu_process_hosts
[kind
] == NULL
);
394 g_gpu_process_hosts
[kind
] = this;
396 // Post a task to create the corresponding GpuProcessHostUIShim. The
397 // GpuProcessHostUIShim will be destroyed if either the browser exits,
398 // in which case it calls GpuProcessHostUIShim::DestroyAll, or the
399 // GpuProcessHost is destroyed, which happens when the corresponding GPU
400 // process terminates or fails to launch.
401 BrowserThread::PostTask(
404 base::Bind(base::IgnoreResult(&GpuProcessHostUIShim::Create
), host_id
));
406 process_
.reset(new BrowserChildProcessHostImpl(PROCESS_TYPE_GPU
, this));
409 GpuProcessHost::~GpuProcessHost() {
410 DCHECK(CalledOnValidThread());
412 SendOutstandingReplies();
414 RecordProcessCrash();
416 // In case we never started, clean up.
417 while (!queued_messages_
.empty()) {
418 delete queued_messages_
.front();
419 queued_messages_
.pop();
422 // This is only called on the IO thread so no race against the constructor
423 // for another GpuProcessHost.
424 if (g_gpu_process_hosts
[kind_
] == this)
425 g_gpu_process_hosts
[kind_
] = NULL
;
427 // If there are any remaining offscreen contexts at the point the
428 // GPU process exits, assume something went wrong, and block their
429 // URLs from accessing client 3D APIs without prompting.
430 BlockLiveOffscreenContexts();
432 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitSurfaceCount",
433 GpuSurfaceTracker::Get()->GetSurfaceCount());
434 UMA_HISTOGRAM_BOOLEAN("GPU.AtExitReceivedMemoryStats",
435 uma_memory_stats_received_
);
437 if (uma_memory_stats_received_
) {
438 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitManagedMemoryClientCount",
439 uma_memory_stats_
.client_count
);
440 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitContextGroupCount",
441 uma_memory_stats_
.context_group_count
);
442 UMA_HISTOGRAM_CUSTOM_COUNTS(
443 "GPU.AtExitMBytesAllocated",
444 uma_memory_stats_
.bytes_allocated_current
/ 1024 / 1024, 1, 2000, 50);
445 UMA_HISTOGRAM_CUSTOM_COUNTS(
446 "GPU.AtExitMBytesAllocatedMax",
447 uma_memory_stats_
.bytes_allocated_max
/ 1024 / 1024, 1, 2000, 50);
448 UMA_HISTOGRAM_CUSTOM_COUNTS(
449 "GPU.AtExitMBytesLimit",
450 uma_memory_stats_
.bytes_limit
/ 1024 / 1024, 1, 2000, 50);
456 base::TerminationStatus status
= process_
->GetTerminationStatus(
457 false /* known_dead */, &exit_code
);
458 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessTerminationStatus",
460 base::TERMINATION_STATUS_MAX_ENUM
);
462 if (status
== base::TERMINATION_STATUS_NORMAL_TERMINATION
||
463 status
== base::TERMINATION_STATUS_ABNORMAL_TERMINATION
) {
464 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessExitCode",
466 RESULT_CODE_LAST_CODE
);
470 case base::TERMINATION_STATUS_NORMAL_TERMINATION
:
471 message
= "The GPU process exited normally. Everything is okay.";
473 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION
:
474 message
= base::StringPrintf(
475 "The GPU process exited with code %d.",
478 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED
:
479 message
= "You killed the GPU process! Why?";
481 case base::TERMINATION_STATUS_PROCESS_CRASHED
:
482 message
= "The GPU process crashed!";
489 BrowserThread::PostTask(BrowserThread::UI
,
491 base::Bind(&GpuProcessHostUIShim::Destroy
,
496 bool GpuProcessHost::Init() {
497 init_start_time_
= base::TimeTicks::Now();
499 TRACE_EVENT_INSTANT0("gpu", "LaunchGpuProcess", TRACE_EVENT_SCOPE_THREAD
);
501 std::string channel_id
= process_
->GetHost()->CreateChannel();
502 if (channel_id
.empty())
506 DCHECK(g_gpu_main_thread_factory
);
507 in_process_gpu_thread_
.reset(g_gpu_main_thread_factory(channel_id
));
508 base::Thread::Options options
;
510 // WGL needs to create its own window and pump messages on it.
511 options
.message_loop_type
= base::MessageLoop::TYPE_UI
;
513 in_process_gpu_thread_
->StartWithOptions(options
);
515 OnProcessLaunched(); // Fake a callback that the process is ready.
516 } else if (!LaunchGpuProcess(channel_id
)) {
520 if (!Send(new GpuMsg_Initialize()))
526 void GpuProcessHost::RouteOnUIThread(const IPC::Message
& message
) {
527 BrowserThread::PostTask(
530 base::Bind(&RouteToGpuProcessHostUIShimTask
, host_id_
, message
));
533 bool GpuProcessHost::Send(IPC::Message
* msg
) {
534 DCHECK(CalledOnValidThread());
535 if (process_
->GetHost()->IsChannelOpening()) {
536 queued_messages_
.push(msg
);
540 bool result
= process_
->Send(msg
);
542 // Channel is hosed, but we may not get destroyed for a while. Send
543 // outstanding channel creation failures now so that the caller can restart
544 // with a new process/channel without waiting.
545 SendOutstandingReplies();
550 void GpuProcessHost::AddFilter(IPC::MessageFilter
* filter
) {
551 DCHECK(CalledOnValidThread());
552 process_
->GetHost()->AddFilter(filter
);
555 bool GpuProcessHost::OnMessageReceived(const IPC::Message
& message
) {
556 DCHECK(CalledOnValidThread());
557 IPC_BEGIN_MESSAGE_MAP(GpuProcessHost
, message
)
558 IPC_MESSAGE_HANDLER(GpuHostMsg_Initialized
, OnInitialized
)
559 IPC_MESSAGE_HANDLER(GpuHostMsg_ChannelEstablished
, OnChannelEstablished
)
560 IPC_MESSAGE_HANDLER(GpuHostMsg_CommandBufferCreated
, OnCommandBufferCreated
)
561 IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyCommandBuffer
, OnDestroyCommandBuffer
)
562 IPC_MESSAGE_HANDLER(GpuHostMsg_GpuMemoryBufferCreated
,
563 OnGpuMemoryBufferCreated
)
564 IPC_MESSAGE_HANDLER(GpuHostMsg_DidCreateOffscreenContext
,
565 OnDidCreateOffscreenContext
)
566 IPC_MESSAGE_HANDLER(GpuHostMsg_DidLoseContext
, OnDidLoseContext
)
567 IPC_MESSAGE_HANDLER(GpuHostMsg_DidDestroyOffscreenContext
,
568 OnDidDestroyOffscreenContext
)
569 IPC_MESSAGE_HANDLER(GpuHostMsg_GpuMemoryUmaStats
,
570 OnGpuMemoryUmaStatsReceived
)
571 #if defined(OS_MACOSX)
572 IPC_MESSAGE_HANDLER_GENERIC(GpuHostMsg_AcceleratedSurfaceBuffersSwapped
,
573 OnAcceleratedSurfaceBuffersSwapped(message
))
575 IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyChannel
,
577 IPC_MESSAGE_HANDLER(GpuHostMsg_CacheShader
,
580 IPC_MESSAGE_UNHANDLED(RouteOnUIThread(message
))
581 IPC_END_MESSAGE_MAP()
586 void GpuProcessHost::OnChannelConnected(int32 peer_pid
) {
587 TRACE_EVENT0("gpu", "GpuProcessHost::OnChannelConnected");
589 while (!queued_messages_
.empty()) {
590 Send(queued_messages_
.front());
591 queued_messages_
.pop();
595 void GpuProcessHost::EstablishGpuChannel(
598 bool allow_future_sync_points
,
599 const EstablishChannelCallback
& callback
) {
600 DCHECK(CalledOnValidThread());
601 TRACE_EVENT0("gpu", "GpuProcessHost::EstablishGpuChannel");
603 // If GPU features are already blacklisted, no need to establish the channel.
604 if (!GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL
)) {
605 DVLOG(1) << "GPU blacklisted, refusing to open a GPU channel.";
606 callback
.Run(IPC::ChannelHandle(), gpu::GPUInfo());
610 if (Send(new GpuMsg_EstablishChannel(
611 client_id
, share_context
, allow_future_sync_points
))) {
612 channel_requests_
.push(callback
);
614 DVLOG(1) << "Failed to send GpuMsg_EstablishChannel.";
615 callback
.Run(IPC::ChannelHandle(), gpu::GPUInfo());
618 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
619 switches::kDisableGpuShaderDiskCache
)) {
620 CreateChannelCache(client_id
);
624 void GpuProcessHost::CreateViewCommandBuffer(
625 const gfx::GLSurfaceHandle
& compositing_surface
,
628 const GPUCreateCommandBufferConfig
& init_params
,
630 const CreateCommandBufferCallback
& callback
) {
631 TRACE_EVENT0("gpu", "GpuProcessHost::CreateViewCommandBuffer");
633 DCHECK(CalledOnValidThread());
635 if (!compositing_surface
.is_null() &&
636 Send(new GpuMsg_CreateViewCommandBuffer(
637 compositing_surface
, surface_id
, client_id
, init_params
, route_id
))) {
638 create_command_buffer_requests_
.push(callback
);
639 surface_refs_
.insert(std::make_pair(surface_id
,
640 GpuSurfaceTracker::GetInstance()->GetSurfaceRefForSurface(surface_id
)));
642 // Could distinguish here between compositing_surface being NULL
643 // and Send failing, if desired.
644 callback
.Run(CREATE_COMMAND_BUFFER_FAILED_AND_CHANNEL_LOST
);
648 void GpuProcessHost::CreateGpuMemoryBuffer(
649 gfx::GpuMemoryBufferId id
,
650 const gfx::Size
& size
,
651 gfx::GpuMemoryBuffer::Format format
,
652 gfx::GpuMemoryBuffer::Usage usage
,
655 const CreateGpuMemoryBufferCallback
& callback
) {
656 TRACE_EVENT0("gpu", "GpuProcessHost::CreateGpuMemoryBuffer");
658 DCHECK(CalledOnValidThread());
660 GpuMsg_CreateGpuMemoryBuffer_Params params
;
663 params
.format
= format
;
664 params
.usage
= usage
;
665 params
.client_id
= client_id
;
666 params
.surface_handle
=
667 GpuSurfaceTracker::GetInstance()->GetSurfaceHandle(surface_id
).handle
;
668 if (Send(new GpuMsg_CreateGpuMemoryBuffer(params
))) {
669 create_gpu_memory_buffer_requests_
.push(callback
);
670 create_gpu_memory_buffer_surface_refs_
.push(surface_id
);
672 surface_refs_
.insert(std::make_pair(
673 surface_id
, GpuSurfaceTracker::GetInstance()->GetSurfaceRefForSurface(
677 callback
.Run(gfx::GpuMemoryBufferHandle());
681 void GpuProcessHost::DestroyGpuMemoryBuffer(gfx::GpuMemoryBufferId id
,
684 TRACE_EVENT0("gpu", "GpuProcessHost::DestroyGpuMemoryBuffer");
686 DCHECK(CalledOnValidThread());
688 Send(new GpuMsg_DestroyGpuMemoryBuffer(id
, client_id
, sync_point
));
691 void GpuProcessHost::OnInitialized(bool result
, const gpu::GPUInfo
& gpu_info
) {
692 UMA_HISTOGRAM_BOOLEAN("GPU.GPUProcessInitialized", result
);
693 initialized_
= result
;
696 GpuDataManagerImpl::GetInstance()->OnGpuProcessInitFailure();
697 else if (!in_process_
)
698 GpuDataManagerImpl::GetInstance()->UpdateGpuInfo(gpu_info
);
701 void GpuProcessHost::OnChannelEstablished(
702 const IPC::ChannelHandle
& channel_handle
) {
703 TRACE_EVENT0("gpu", "GpuProcessHost::OnChannelEstablished");
705 if (channel_requests_
.empty()) {
706 // This happens when GPU process is compromised.
707 RouteOnUIThread(GpuHostMsg_OnLogMessage(
708 logging::LOG_WARNING
,
710 "Received a ChannelEstablished message but no requests in queue."));
713 EstablishChannelCallback callback
= channel_requests_
.front();
714 channel_requests_
.pop();
716 // Currently if any of the GPU features are blacklisted, we don't establish a
718 if (!channel_handle
.name
.empty() &&
719 !GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL
)) {
720 Send(new GpuMsg_CloseChannel(channel_handle
));
721 callback
.Run(IPC::ChannelHandle(), gpu::GPUInfo());
722 RouteOnUIThread(GpuHostMsg_OnLogMessage(
723 logging::LOG_WARNING
,
725 "Hardware acceleration is unavailable."));
729 callback
.Run(channel_handle
,
730 GpuDataManagerImpl::GetInstance()->GetGPUInfo());
733 void GpuProcessHost::OnCommandBufferCreated(CreateCommandBufferResult result
) {
734 TRACE_EVENT0("gpu", "GpuProcessHost::OnCommandBufferCreated");
736 if (create_command_buffer_requests_
.empty())
739 CreateCommandBufferCallback callback
=
740 create_command_buffer_requests_
.front();
741 create_command_buffer_requests_
.pop();
742 callback
.Run(result
);
745 void GpuProcessHost::OnDestroyCommandBuffer(int32 surface_id
) {
746 TRACE_EVENT0("gpu", "GpuProcessHost::OnDestroyCommandBuffer");
747 SurfaceRefMap::iterator it
= surface_refs_
.find(surface_id
);
748 if (it
!= surface_refs_
.end()) {
749 surface_refs_
.erase(it
);
753 void GpuProcessHost::OnGpuMemoryBufferCreated(
754 const gfx::GpuMemoryBufferHandle
& handle
) {
755 TRACE_EVENT0("gpu", "GpuProcessHost::OnGpuMemoryBufferCreated");
757 if (create_gpu_memory_buffer_requests_
.empty())
760 CreateGpuMemoryBufferCallback callback
=
761 create_gpu_memory_buffer_requests_
.front();
762 create_gpu_memory_buffer_requests_
.pop();
763 callback
.Run(handle
);
765 int32 surface_id
= create_gpu_memory_buffer_surface_refs_
.front();
766 create_gpu_memory_buffer_surface_refs_
.pop();
767 SurfaceRefMap::iterator it
= surface_refs_
.find(surface_id
);
768 if (it
!= surface_refs_
.end()) {
769 surface_refs_
.erase(it
);
773 void GpuProcessHost::OnDidCreateOffscreenContext(const GURL
& url
) {
774 urls_with_live_offscreen_contexts_
.insert(url
);
777 void GpuProcessHost::OnDidLoseContext(bool offscreen
,
778 gpu::error::ContextLostReason reason
,
780 // TODO(kbr): would be nice to see the "offscreen" flag too.
781 TRACE_EVENT2("gpu", "GpuProcessHost::OnDidLoseContext",
784 url
.possibly_invalid_spec());
786 if (!offscreen
|| url
.is_empty()) {
787 // Assume that the loss of the compositor's or accelerated canvas'
788 // context is a serious event and blame the loss on all live
789 // offscreen contexts. This more robustly handles situations where
790 // the GPU process may not actually detect the context loss in the
791 // offscreen context.
792 BlockLiveOffscreenContexts();
796 GpuDataManagerImpl::DomainGuilt guilt
;
798 case gpu::error::kGuilty
:
799 guilt
= GpuDataManagerImpl::DOMAIN_GUILT_KNOWN
;
801 case gpu::error::kUnknown
:
802 guilt
= GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN
;
804 case gpu::error::kInnocent
:
811 GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(url
, guilt
);
814 void GpuProcessHost::OnDidDestroyOffscreenContext(const GURL
& url
) {
815 urls_with_live_offscreen_contexts_
.erase(url
);
818 void GpuProcessHost::OnGpuMemoryUmaStatsReceived(
819 const GPUMemoryUmaStats
& stats
) {
820 TRACE_EVENT0("gpu", "GpuProcessHost::OnGpuMemoryUmaStatsReceived");
821 uma_memory_stats_received_
= true;
822 uma_memory_stats_
= stats
;
825 #if defined(OS_MACOSX)
826 void GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped(
827 const IPC::Message
& message
) {
828 RenderWidgetResizeHelper::Get()->PostGpuProcessMsg(host_id_
, message
);
832 void GpuProcessHost::OnProcessLaunched() {
833 UMA_HISTOGRAM_TIMES("GPU.GPUProcessLaunchTime",
834 base::TimeTicks::Now() - init_start_time_
);
837 void GpuProcessHost::OnProcessCrashed(int exit_code
) {
838 SendOutstandingReplies();
839 RecordProcessCrash();
840 GpuDataManagerImpl::GetInstance()->ProcessCrashed(
841 process_
->GetTerminationStatus(true /* known_dead */, NULL
));
844 GpuProcessHost::GpuProcessKind
GpuProcessHost::kind() {
848 void GpuProcessHost::ForceShutdown() {
849 // This is only called on the IO thread so no race against the constructor
850 // for another GpuProcessHost.
851 if (g_gpu_process_hosts
[kind_
] == this)
852 g_gpu_process_hosts
[kind_
] = NULL
;
854 process_
->ForceShutdown();
857 void GpuProcessHost::BeginFrameSubscription(
859 base::WeakPtr
<RenderWidgetHostViewFrameSubscriber
> subscriber
) {
860 frame_subscribers_
[surface_id
] = subscriber
;
863 void GpuProcessHost::EndFrameSubscription(int surface_id
) {
864 frame_subscribers_
.erase(surface_id
);
867 bool GpuProcessHost::LaunchGpuProcess(const std::string
& channel_id
) {
868 if (!(gpu_enabled_
&&
869 GpuDataManagerImpl::GetInstance()->ShouldUseSwiftShader()) &&
870 !hardware_gpu_enabled_
) {
871 SendOutstandingReplies();
875 const base::CommandLine
& browser_command_line
=
876 *base::CommandLine::ForCurrentProcess();
878 base::CommandLine::StringType gpu_launcher
=
879 browser_command_line
.GetSwitchValueNative(switches::kGpuLauncher
);
881 #if defined(OS_ANDROID)
882 // crbug.com/447735. readlink("self/proc/exe") sometimes fails on Android
883 // at startup with EACCES. As a workaround ignore this here, since the
884 // executable name is actually not used or useful anyways.
885 base::CommandLine
* cmd_line
=
886 new base::CommandLine(base::CommandLine::NO_PROGRAM
);
888 #if defined(OS_LINUX)
889 int child_flags
= gpu_launcher
.empty() ? ChildProcessHost::CHILD_ALLOW_SELF
:
890 ChildProcessHost::CHILD_NORMAL
;
892 int child_flags
= ChildProcessHost::CHILD_NORMAL
;
895 base::FilePath exe_path
= ChildProcessHost::GetChildPath(child_flags
);
896 if (exe_path
.empty())
899 base::CommandLine
* cmd_line
= new base::CommandLine(exe_path
);
901 cmd_line
->AppendSwitchASCII(switches::kProcessType
, switches::kGpuProcess
);
902 cmd_line
->AppendSwitchASCII(switches::kProcessChannelID
, channel_id
);
904 if (kind_
== GPU_PROCESS_KIND_UNSANDBOXED
)
905 cmd_line
->AppendSwitch(switches::kDisableGpuSandbox
);
907 // If you want a browser command-line switch passed to the GPU process
908 // you need to add it to |kSwitchNames| at the beginning of this file.
909 cmd_line
->CopySwitchesFrom(browser_command_line
, kSwitchNames
,
910 arraysize(kSwitchNames
));
911 cmd_line
->CopySwitchesFrom(
912 browser_command_line
, switches::kGpuSwitches
, switches::kNumGpuSwitches
);
913 cmd_line
->CopySwitchesFrom(
914 browser_command_line
, switches::kGLSwitchesCopiedFromGpuProcessHost
,
915 switches::kGLSwitchesCopiedFromGpuProcessHostNumSwitches
);
917 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
918 cmd_line
, process_
->GetData().id
);
920 GpuDataManagerImpl::GetInstance()->AppendGpuCommandLine(cmd_line
);
922 if (cmd_line
->HasSwitch(switches::kUseGL
)) {
923 swiftshader_rendering_
=
924 (cmd_line
->GetSwitchValueASCII(switches::kUseGL
) == "swiftshader");
927 UMA_HISTOGRAM_BOOLEAN("GPU.GPU.GPUProcessSoftwareRendering",
928 swiftshader_rendering_
);
930 // If specified, prepend a launcher program to the command line.
931 if (!gpu_launcher
.empty())
932 cmd_line
->PrependWrapper(gpu_launcher
);
935 new GpuSandboxedProcessLauncherDelegate(cmd_line
,
936 process_
->GetHost()),
938 process_launched_
= true;
940 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
941 LAUNCHED
, GPU_PROCESS_LIFETIME_EVENT_MAX
);
945 void GpuProcessHost::SendOutstandingReplies() {
947 // First send empty channel handles for all EstablishChannel requests.
948 while (!channel_requests_
.empty()) {
949 EstablishChannelCallback callback
= channel_requests_
.front();
950 channel_requests_
.pop();
951 callback
.Run(IPC::ChannelHandle(), gpu::GPUInfo());
954 while (!create_command_buffer_requests_
.empty()) {
955 CreateCommandBufferCallback callback
=
956 create_command_buffer_requests_
.front();
957 create_command_buffer_requests_
.pop();
958 callback
.Run(CREATE_COMMAND_BUFFER_FAILED_AND_CHANNEL_LOST
);
961 while (!create_gpu_memory_buffer_requests_
.empty()) {
962 CreateGpuMemoryBufferCallback callback
=
963 create_gpu_memory_buffer_requests_
.front();
964 create_gpu_memory_buffer_requests_
.pop();
965 callback
.Run(gfx::GpuMemoryBufferHandle());
969 void GpuProcessHost::BlockLiveOffscreenContexts() {
970 for (std::multiset
<GURL
>::iterator iter
=
971 urls_with_live_offscreen_contexts_
.begin();
972 iter
!= urls_with_live_offscreen_contexts_
.end(); ++iter
) {
973 GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(
974 *iter
, GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN
);
978 void GpuProcessHost::RecordProcessCrash() {
979 // Skip if a GPU process crash was already counted.
980 if (gpu_crash_recorded_
)
983 // Maximum number of times the GPU process is allowed to crash in a session.
984 // Once this limit is reached, any request to launch the GPU process will
986 const int kGpuMaxCrashCount
= 3;
988 // Last time the GPU process crashed.
989 static base::Time last_gpu_crash_time
;
991 bool disable_crash_limit
= base::CommandLine::ForCurrentProcess()->HasSwitch(
992 switches::kDisableGpuProcessCrashLimit
);
994 // Ending only acts as a failure if the GPU process was actually started and
995 // was intended for actual rendering (and not just checking caps or other
997 if (process_launched_
&& kind_
== GPU_PROCESS_KIND_SANDBOXED
) {
998 gpu_crash_recorded_
= true;
999 if (swiftshader_rendering_
) {
1000 UMA_HISTOGRAM_ENUMERATION("GPU.SwiftShaderLifetimeEvents",
1001 DIED_FIRST_TIME
+ swiftshader_crash_count_
,
1002 GPU_PROCESS_LIFETIME_EVENT_MAX
);
1004 if (++swiftshader_crash_count_
>= kGpuMaxCrashCount
&&
1005 !disable_crash_limit
) {
1006 // SwiftShader is too unstable to use. Disable it for current session.
1007 gpu_enabled_
= false;
1011 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
1012 std::min(DIED_FIRST_TIME
+ gpu_crash_count_
,
1013 GPU_PROCESS_LIFETIME_EVENT_MAX
- 1),
1014 GPU_PROCESS_LIFETIME_EVENT_MAX
);
1016 // Allow about 1 GPU crash per hour to be removed from the crash count,
1017 // so very occasional crashes won't eventually add up and prevent the
1018 // GPU process from launching.
1019 ++gpu_recent_crash_count_
;
1020 base::Time current_time
= base::Time::Now();
1021 if (crashed_before_
) {
1022 int hours_different
= (current_time
- last_gpu_crash_time
).InHours();
1023 gpu_recent_crash_count_
=
1024 std::max(0, gpu_recent_crash_count_
- hours_different
);
1027 crashed_before_
= true;
1028 last_gpu_crash_time
= current_time
;
1030 if ((gpu_recent_crash_count_
>= kGpuMaxCrashCount
&&
1031 !disable_crash_limit
) ||
1033 #if !defined(OS_CHROMEOS)
1034 // The GPU process is too unstable to use. Disable it for current
1036 hardware_gpu_enabled_
= false;
1037 GpuDataManagerImpl::GetInstance()->DisableHardwareAcceleration();
1044 std::string
GpuProcessHost::GetShaderPrefixKey() {
1045 if (shader_prefix_key_
.empty()) {
1046 gpu::GPUInfo info
= GpuDataManagerImpl::GetInstance()->GetGPUInfo();
1048 std::string in_str
= GetContentClient()->GetProduct() + "-" +
1049 info
.gl_vendor
+ "-" + info
.gl_renderer
+ "-" +
1050 info
.driver_version
+ "-" + info
.driver_vendor
;
1052 base::Base64Encode(base::SHA1HashString(in_str
), &shader_prefix_key_
);
1055 return shader_prefix_key_
;
1058 void GpuProcessHost::LoadedShader(const std::string
& key
,
1059 const std::string
& data
) {
1060 std::string prefix
= GetShaderPrefixKey();
1061 if (!key
.compare(0, prefix
.length(), prefix
))
1062 Send(new GpuMsg_LoadedShader(data
));
1065 void GpuProcessHost::CreateChannelCache(int32 client_id
) {
1066 TRACE_EVENT0("gpu", "GpuProcessHost::CreateChannelCache");
1068 scoped_refptr
<ShaderDiskCache
> cache
=
1069 ShaderCacheFactory::GetInstance()->Get(client_id
);
1073 cache
->set_host_id(host_id_
);
1075 client_id_to_shader_cache_
[client_id
] = cache
;
1078 void GpuProcessHost::OnDestroyChannel(int32 client_id
) {
1079 TRACE_EVENT0("gpu", "GpuProcessHost::OnDestroyChannel");
1080 client_id_to_shader_cache_
.erase(client_id
);
1083 void GpuProcessHost::OnCacheShader(int32 client_id
,
1084 const std::string
& key
,
1085 const std::string
& shader
) {
1086 TRACE_EVENT0("gpu", "GpuProcessHost::OnCacheShader");
1087 ClientIdToShaderCacheMap::iterator iter
=
1088 client_id_to_shader_cache_
.find(client_id
);
1089 // If the cache doesn't exist then this is an off the record profile.
1090 if (iter
== client_id_to_shader_cache_
.end())
1092 iter
->second
->Cache(GetShaderPrefixKey() + ":" + key
, shader
);
1095 } // namespace content