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/debug/trace_event.h"
14 #include "base/logging.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/metrics/histogram.h"
17 #include "base/sha1.h"
18 #include "base/threading/thread.h"
19 #include "content/browser/browser_child_process_host_impl.h"
20 #include "content/browser/gpu/gpu_data_manager_impl.h"
21 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
22 #include "content/browser/gpu/shader_disk_cache.h"
23 #include "content/browser/renderer_host/render_widget_helper.h"
24 #include "content/browser/renderer_host/render_widget_host_impl.h"
25 #include "content/common/child_process_host_impl.h"
26 #include "content/common/gpu/gpu_messages.h"
27 #include "content/common/view_messages.h"
28 #include "content/port/browser/render_widget_host_view_frame_subscriber.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/common/content_client.h"
34 #include "content/public/common/content_switches.h"
35 #include "content/public/common/result_codes.h"
36 #include "content/public/common/sandboxed_process_launcher_delegate.h"
37 #include "gpu/command_buffer/service/gpu_switches.h"
38 #include "ipc/ipc_channel_handle.h"
39 #include "ipc/ipc_switches.h"
40 #include "ui/events/latency_info.h"
41 #include "ui/gl/gl_switches.h"
45 #include "base/win/windows_version.h"
46 #include "content/common/sandbox_win.h"
47 #include "sandbox/win/src/sandbox_policy.h"
48 #include "ui/gfx/switches.h"
51 #if defined(USE_OZONE)
52 #include "ui/ozone/ozone_switches.h"
57 bool GpuProcessHost::gpu_enabled_
= true;
58 bool GpuProcessHost::hardware_gpu_enabled_
= true;
62 enum GPUProcessLifetimeEvent
{
68 GPU_PROCESS_LIFETIME_EVENT_MAX
= 100
71 // Indexed by GpuProcessKind. There is one of each kind maximum. This array may
72 // only be accessed from the IO thread.
73 GpuProcessHost
* g_gpu_process_hosts
[GpuProcessHost::GPU_PROCESS_KIND_COUNT
];
76 void SendGpuProcessMessage(GpuProcessHost::GpuProcessKind kind
,
77 CauseForGpuLaunch cause
,
78 IPC::Message
* message
) {
79 GpuProcessHost
* host
= GpuProcessHost::Get(kind
, cause
);
87 void AcceleratedSurfaceBuffersSwappedCompletedForGPU(
91 base::TimeTicks vsync_timebase
,
92 base::TimeDelta vsync_interval
) {
93 if (!BrowserThread::CurrentlyOn(BrowserThread::IO
)) {
94 BrowserThread::PostTask(
97 base::Bind(&AcceleratedSurfaceBuffersSwappedCompletedForGPU
,
106 GpuProcessHost
* host
= GpuProcessHost::FromID(host_id
);
109 AcceleratedSurfaceMsg_BufferPresented_Params ack_params
;
110 ack_params
.sync_point
= 0;
112 ack_params
.vsync_timebase
= vsync_timebase
;
113 ack_params
.vsync_interval
= vsync_interval
;
116 new AcceleratedSurfaceMsg_BufferPresented(route_id
, ack_params
));
118 host
->ForceShutdown();
124 // This sends a ViewMsg_SwapBuffers_ACK directly to the renderer process
126 void AcceleratedSurfaceBuffersSwappedCompletedForRenderer(
128 base::TimeTicks timebase
,
129 base::TimeDelta interval
,
130 const std::vector
<ui::LatencyInfo
>& latency_info
) {
131 if (!BrowserThread::CurrentlyOn(BrowserThread::UI
)) {
132 BrowserThread::PostTask(
135 base::Bind(&AcceleratedSurfaceBuffersSwappedCompletedForRenderer
,
136 surface_id
, timebase
, interval
, latency_info
));
140 int render_process_id
= 0;
141 int render_widget_id
= 0;
142 if (!GpuSurfaceTracker::Get()->GetRenderWidgetIDForSurface(
143 surface_id
, &render_process_id
, &render_widget_id
)) {
144 RenderWidgetHostImpl::CompositorFrameDrawn(latency_info
);
147 RenderWidgetHost
* rwh
=
148 RenderWidgetHost::FromID(render_process_id
, render_widget_id
);
151 RenderWidgetHostImpl::From(rwh
)->AcknowledgeSwapBuffersToRenderer();
152 if (interval
!= base::TimeDelta())
153 RenderWidgetHostImpl::From(rwh
)->UpdateVSyncParameters(timebase
, interval
);
154 for (size_t i
= 0; i
< latency_info
.size(); i
++)
155 RenderWidgetHostImpl::From(rwh
)->FrameSwapped(latency_info
[i
]);
156 RenderWidgetHostImpl::From(rwh
)->DidReceiveRendererFrame();
159 void AcceleratedSurfaceBuffersSwappedCompleted(
164 base::TimeTicks timebase
,
165 base::TimeDelta interval
,
166 const std::vector
<ui::LatencyInfo
>& latency_info
) {
167 AcceleratedSurfaceBuffersSwappedCompletedForGPU(
168 host_id
, route_id
, alive
, timebase
, interval
);
169 AcceleratedSurfaceBuffersSwappedCompletedForRenderer(
170 surface_id
, timebase
, interval
, latency_info
);
174 // NOTE: changes to this class need to be reviewed by the security team.
175 class GpuSandboxedProcessLauncherDelegate
176 : public SandboxedProcessLauncherDelegate
{
178 GpuSandboxedProcessLauncherDelegate(CommandLine
* cmd_line
,
179 ChildProcessHost
* host
)
181 : cmd_line_(cmd_line
) {}
182 #elif defined(OS_POSIX)
183 : ipc_fd_(host
->TakeClientFileDescriptor()) {}
186 virtual ~GpuSandboxedProcessLauncherDelegate() {}
189 virtual bool ShouldSandbox() OVERRIDE
{
190 bool sandbox
= !cmd_line_
->HasSwitch(switches::kDisableGpuSandbox
);
192 DVLOG(1) << "GPU sandbox is disabled";
197 virtual void PreSandbox(bool* disable_default_policy
,
198 base::FilePath
* exposed_dir
) OVERRIDE
{
199 *disable_default_policy
= true;
202 // For the GPU process we gotten as far as USER_LIMITED. The next level
203 // which is USER_RESTRICTED breaks both the DirectX backend and the OpenGL
204 // backend. Note that the GPU process is connected to the interactive
206 virtual void PreSpawnTarget(sandbox::TargetPolicy
* policy
,
208 if (base::win::GetVersion() > base::win::VERSION_XP
) {
209 if (cmd_line_
->GetSwitchValueASCII(switches::kUseGL
) ==
210 gfx::kGLImplementationDesktopName
) {
212 policy
->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS
,
213 sandbox::USER_LIMITED
);
214 SetJobLevel(*cmd_line_
, sandbox::JOB_UNPROTECTED
, 0, policy
);
215 policy
->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW
);
217 policy
->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS
,
218 sandbox::USER_LIMITED
);
220 // UI restrictions break when we access Windows from outside our job.
221 // However, we don't want a proxy window in this process because it can
222 // introduce deadlocks where the renderer blocks on the gpu, which in
223 // turn blocks on the browser UI thread. So, instead we forgo a window
224 // message pump entirely and just add job restrictions to prevent child
226 SetJobLevel(*cmd_line_
,
227 sandbox::JOB_LIMITED_USER
,
228 JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS
|
229 JOB_OBJECT_UILIMIT_DESKTOP
|
230 JOB_OBJECT_UILIMIT_EXITWINDOWS
|
231 JOB_OBJECT_UILIMIT_DISPLAYSETTINGS
,
234 policy
->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW
);
237 SetJobLevel(*cmd_line_
, sandbox::JOB_UNPROTECTED
, 0, policy
);
238 policy
->SetTokenLevel(sandbox::USER_UNPROTECTED
,
239 sandbox::USER_LIMITED
);
242 // Allow the server side of GPU sockets, which are pipes that have
243 // the "chrome.gpu" namespace and an arbitrary suffix.
244 sandbox::ResultCode result
= policy
->AddRule(
245 sandbox::TargetPolicy::SUBSYS_NAMED_PIPES
,
246 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY
,
247 L
"\\\\.\\pipe\\chrome.gpu.*");
248 if (result
!= sandbox::SBOX_ALL_OK
) {
253 // Block this DLL even if it is not loaded by the browser process.
254 policy
->AddDllToUnload(L
"cmsetac.dll");
257 // GPU also needs to add sections to the browser for aura
258 // TODO(jschuh): refactor the GPU channel to remove this. crbug.com/128786
259 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES
,
260 sandbox::TargetPolicy::HANDLES_DUP_BROKER
,
262 if (result
!= sandbox::SBOX_ALL_OK
) {
268 if (cmd_line_
->HasSwitch(switches::kEnableLogging
)) {
269 base::string16 log_file_path
= logging::GetLogFileFullPath();
270 if (!log_file_path
.empty()) {
271 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_FILES
,
272 sandbox::TargetPolicy::FILES_ALLOW_ANY
,
273 log_file_path
.c_str());
274 if (result
!= sandbox::SBOX_ALL_OK
) {
281 #elif defined(OS_POSIX)
283 virtual int GetIpcFd() OVERRIDE
{
290 CommandLine
* cmd_line_
;
291 #elif defined(OS_POSIX)
296 } // anonymous namespace
299 bool GpuProcessHost::ValidateHost(GpuProcessHost
* host
) {
300 // The Gpu process is invalid if it's not using SwiftShader, the card is
301 // blacklisted, and we can kill it and start over.
302 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess
) ||
303 CommandLine::ForCurrentProcess()->HasSwitch(switches::kInProcessGPU
) ||
305 (host
->swiftshader_rendering_
||
306 !GpuDataManagerImpl::GetInstance()->ShouldUseSwiftShader()))) {
310 host
->ForceShutdown();
315 GpuProcessHost
* GpuProcessHost::Get(GpuProcessKind kind
,
316 CauseForGpuLaunch cause
) {
317 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
319 // Don't grant further access to GPU if it is not allowed.
320 GpuDataManagerImpl
* gpu_data_manager
= GpuDataManagerImpl::GetInstance();
321 DCHECK(gpu_data_manager
);
322 if (!gpu_data_manager
->GpuAccessAllowed(NULL
))
325 if (g_gpu_process_hosts
[kind
] && ValidateHost(g_gpu_process_hosts
[kind
]))
326 return g_gpu_process_hosts
[kind
];
328 if (cause
== CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH
)
331 static int last_host_id
= 0;
333 host_id
= ++last_host_id
;
335 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLaunchCause",
337 CAUSE_FOR_GPU_LAUNCH_MAX_ENUM
);
339 GpuProcessHost
* host
= new GpuProcessHost(host_id
, kind
);
348 void GpuProcessHost::GetProcessHandles(
349 const GpuDataManager::GetGpuProcessHandlesCallback
& callback
) {
350 if (!BrowserThread::CurrentlyOn(BrowserThread::IO
)) {
351 BrowserThread::PostTask(
354 base::Bind(&GpuProcessHost::GetProcessHandles
, callback
));
357 std::list
<base::ProcessHandle
> handles
;
358 for (size_t i
= 0; i
< arraysize(g_gpu_process_hosts
); ++i
) {
359 GpuProcessHost
* host
= g_gpu_process_hosts
[i
];
360 if (host
&& ValidateHost(host
))
361 handles
.push_back(host
->process_
->GetHandle());
363 BrowserThread::PostTask(
366 base::Bind(callback
, handles
));
370 void GpuProcessHost::SendOnIO(GpuProcessKind kind
,
371 CauseForGpuLaunch cause
,
372 IPC::Message
* message
) {
373 if (!BrowserThread::PostTask(
374 BrowserThread::IO
, FROM_HERE
,
376 &SendGpuProcessMessage
, kind
, cause
, message
))) {
381 GpuMainThreadFactoryFunction g_gpu_main_thread_factory
= NULL
;
383 void GpuProcessHost::RegisterGpuMainThreadFactory(
384 GpuMainThreadFactoryFunction create
) {
385 g_gpu_main_thread_factory
= create
;
389 GpuProcessHost
* GpuProcessHost::FromID(int host_id
) {
390 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
392 for (int i
= 0; i
< GPU_PROCESS_KIND_COUNT
; ++i
) {
393 GpuProcessHost
* host
= g_gpu_process_hosts
[i
];
394 if (host
&& host
->host_id_
== host_id
&& ValidateHost(host
))
401 GpuProcessHost::GpuProcessHost(int host_id
, GpuProcessKind kind
)
405 swiftshader_rendering_(false),
407 process_launched_(false),
409 uma_memory_stats_received_(false) {
410 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess
) ||
411 CommandLine::ForCurrentProcess()->HasSwitch(switches::kInProcessGPU
)) {
415 // If the 'single GPU process' policy ever changes, we still want to maintain
416 // it for 'gpu thread' mode and only create one instance of host and thread.
417 DCHECK(!in_process_
|| g_gpu_process_hosts
[kind
] == NULL
);
419 g_gpu_process_hosts
[kind
] = this;
421 // Post a task to create the corresponding GpuProcessHostUIShim. The
422 // GpuProcessHostUIShim will be destroyed if either the browser exits,
423 // in which case it calls GpuProcessHostUIShim::DestroyAll, or the
424 // GpuProcessHost is destroyed, which happens when the corresponding GPU
425 // process terminates or fails to launch.
426 BrowserThread::PostTask(
429 base::Bind(base::IgnoreResult(&GpuProcessHostUIShim::Create
), host_id
));
431 process_
.reset(new BrowserChildProcessHostImpl(PROCESS_TYPE_GPU
, this));
434 GpuProcessHost::~GpuProcessHost() {
435 DCHECK(CalledOnValidThread());
437 SendOutstandingReplies();
439 // Maximum number of times the gpu process is allowed to crash in a session.
440 // Once this limit is reached, any request to launch the gpu process will
442 const int kGpuMaxCrashCount
= 3;
444 // Number of times the gpu process has crashed in the current browser session.
445 static int gpu_crash_count
= 0;
446 static int gpu_recent_crash_count
= 0;
447 static base::Time last_gpu_crash_time
;
448 static bool crashed_before
= false;
449 static int swiftshader_crash_count
= 0;
451 bool disable_crash_limit
= CommandLine::ForCurrentProcess()->HasSwitch(
452 switches::kDisableGpuProcessCrashLimit
);
454 // Ending only acts as a failure if the GPU process was actually started and
455 // was intended for actual rendering (and not just checking caps or other
457 if (process_launched_
&& kind_
== GPU_PROCESS_KIND_SANDBOXED
) {
458 if (swiftshader_rendering_
) {
459 UMA_HISTOGRAM_ENUMERATION("GPU.SwiftShaderLifetimeEvents",
460 DIED_FIRST_TIME
+ swiftshader_crash_count
,
461 GPU_PROCESS_LIFETIME_EVENT_MAX
);
463 if (++swiftshader_crash_count
>= kGpuMaxCrashCount
&&
464 !disable_crash_limit
) {
465 // SwiftShader is too unstable to use. Disable it for current session.
466 gpu_enabled_
= false;
470 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
471 std::min(DIED_FIRST_TIME
+ gpu_crash_count
,
472 GPU_PROCESS_LIFETIME_EVENT_MAX
- 1),
473 GPU_PROCESS_LIFETIME_EVENT_MAX
);
475 // Allow about 1 GPU crash per hour to be removed from the crash count,
476 // so very occasional crashes won't eventually add up and prevent the
477 // GPU process from launching.
478 ++gpu_recent_crash_count
;
479 base::Time current_time
= base::Time::Now();
480 if (crashed_before
) {
481 int hours_different
= (current_time
- last_gpu_crash_time
).InHours();
482 gpu_recent_crash_count
=
483 std::max(0, gpu_recent_crash_count
- hours_different
);
486 crashed_before
= true;
487 last_gpu_crash_time
= current_time
;
489 if ((gpu_recent_crash_count
>= kGpuMaxCrashCount
&& !disable_crash_limit
)
491 #if !defined(OS_CHROMEOS)
492 // The gpu process is too unstable to use. Disable it for current
494 hardware_gpu_enabled_
= false;
495 GpuDataManagerImpl::GetInstance()->DisableHardwareAcceleration();
501 // In case we never started, clean up.
502 while (!queued_messages_
.empty()) {
503 delete queued_messages_
.front();
504 queued_messages_
.pop();
507 // This is only called on the IO thread so no race against the constructor
508 // for another GpuProcessHost.
509 if (g_gpu_process_hosts
[kind_
] == this)
510 g_gpu_process_hosts
[kind_
] = NULL
;
512 // If there are any remaining offscreen contexts at the point the
513 // GPU process exits, assume something went wrong, and block their
514 // URLs from accessing client 3D APIs without prompting.
515 BlockLiveOffscreenContexts();
517 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitSurfaceCount",
518 GpuSurfaceTracker::Get()->GetSurfaceCount());
519 UMA_HISTOGRAM_BOOLEAN("GPU.AtExitReceivedMemoryStats",
520 uma_memory_stats_received_
);
522 if (uma_memory_stats_received_
) {
523 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitManagedMemoryClientCount",
524 uma_memory_stats_
.client_count
);
525 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitContextGroupCount",
526 uma_memory_stats_
.context_group_count
);
527 UMA_HISTOGRAM_CUSTOM_COUNTS(
528 "GPU.AtExitMBytesAllocated",
529 uma_memory_stats_
.bytes_allocated_current
/ 1024 / 1024, 1, 2000, 50);
530 UMA_HISTOGRAM_CUSTOM_COUNTS(
531 "GPU.AtExitMBytesAllocatedMax",
532 uma_memory_stats_
.bytes_allocated_max
/ 1024 / 1024, 1, 2000, 50);
533 UMA_HISTOGRAM_CUSTOM_COUNTS(
534 "GPU.AtExitMBytesLimit",
535 uma_memory_stats_
.bytes_limit
/ 1024 / 1024, 1, 2000, 50);
541 base::TerminationStatus status
= process_
->GetTerminationStatus(
542 false /* known_dead */, &exit_code
);
543 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessTerminationStatus",
545 base::TERMINATION_STATUS_MAX_ENUM
);
547 if (status
== base::TERMINATION_STATUS_NORMAL_TERMINATION
||
548 status
== base::TERMINATION_STATUS_ABNORMAL_TERMINATION
) {
549 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessExitCode",
551 RESULT_CODE_LAST_CODE
);
555 case base::TERMINATION_STATUS_NORMAL_TERMINATION
:
556 message
= "The GPU process exited normally. Everything is okay.";
558 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION
:
559 message
= base::StringPrintf(
560 "The GPU process exited with code %d.",
563 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED
:
564 message
= "You killed the GPU process! Why?";
566 case base::TERMINATION_STATUS_PROCESS_CRASHED
:
567 message
= "The GPU process crashed!";
574 BrowserThread::PostTask(BrowserThread::UI
,
576 base::Bind(&GpuProcessHostUIShim::Destroy
,
581 bool GpuProcessHost::Init() {
582 init_start_time_
= base::TimeTicks::Now();
584 TRACE_EVENT_INSTANT0("gpu", "LaunchGpuProcess", TRACE_EVENT_SCOPE_THREAD
);
586 std::string channel_id
= process_
->GetHost()->CreateChannel();
587 if (channel_id
.empty())
591 DCHECK(g_gpu_main_thread_factory
);
592 CommandLine
* command_line
= CommandLine::ForCurrentProcess();
593 command_line
->AppendSwitch(switches::kDisableGpuWatchdog
);
595 GpuDataManagerImpl
* gpu_data_manager
= GpuDataManagerImpl::GetInstance();
596 DCHECK(gpu_data_manager
);
597 gpu_data_manager
->AppendGpuCommandLine(command_line
);
599 in_process_gpu_thread_
.reset(g_gpu_main_thread_factory(channel_id
));
600 in_process_gpu_thread_
->Start();
602 OnProcessLaunched(); // Fake a callback that the process is ready.
603 } else if (!LaunchGpuProcess(channel_id
)) {
607 if (!Send(new GpuMsg_Initialize()))
613 void GpuProcessHost::RouteOnUIThread(const IPC::Message
& message
) {
614 BrowserThread::PostTask(
617 base::Bind(&RouteToGpuProcessHostUIShimTask
, host_id_
, message
));
620 bool GpuProcessHost::Send(IPC::Message
* msg
) {
621 DCHECK(CalledOnValidThread());
622 if (process_
->GetHost()->IsChannelOpening()) {
623 queued_messages_
.push(msg
);
627 bool result
= process_
->Send(msg
);
629 // Channel is hosed, but we may not get destroyed for a while. Send
630 // outstanding channel creation failures now so that the caller can restart
631 // with a new process/channel without waiting.
632 SendOutstandingReplies();
637 void GpuProcessHost::AddFilter(IPC::ChannelProxy::MessageFilter
* filter
) {
638 DCHECK(CalledOnValidThread());
639 process_
->GetHost()->AddFilter(filter
);
642 bool GpuProcessHost::OnMessageReceived(const IPC::Message
& message
) {
643 DCHECK(CalledOnValidThread());
644 IPC_BEGIN_MESSAGE_MAP(GpuProcessHost
, message
)
645 IPC_MESSAGE_HANDLER(GpuHostMsg_Initialized
, OnInitialized
)
646 IPC_MESSAGE_HANDLER(GpuHostMsg_ChannelEstablished
, OnChannelEstablished
)
647 IPC_MESSAGE_HANDLER(GpuHostMsg_CommandBufferCreated
, OnCommandBufferCreated
)
648 IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyCommandBuffer
, OnDestroyCommandBuffer
)
649 IPC_MESSAGE_HANDLER(GpuHostMsg_ImageCreated
, OnImageCreated
)
650 IPC_MESSAGE_HANDLER(GpuHostMsg_DidCreateOffscreenContext
,
651 OnDidCreateOffscreenContext
)
652 IPC_MESSAGE_HANDLER(GpuHostMsg_DidLoseContext
, OnDidLoseContext
)
653 IPC_MESSAGE_HANDLER(GpuHostMsg_DidDestroyOffscreenContext
,
654 OnDidDestroyOffscreenContext
)
655 IPC_MESSAGE_HANDLER(GpuHostMsg_GpuMemoryUmaStats
,
656 OnGpuMemoryUmaStatsReceived
)
657 #if defined(OS_MACOSX)
658 IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceBuffersSwapped
,
659 OnAcceleratedSurfaceBuffersSwapped
)
662 IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceBuffersSwapped
,
663 OnAcceleratedSurfaceBuffersSwapped
)
664 IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfacePostSubBuffer
,
665 OnAcceleratedSurfacePostSubBuffer
)
666 IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceSuspend
,
667 OnAcceleratedSurfaceSuspend
)
668 IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceRelease
,
669 OnAcceleratedSurfaceRelease
)
671 IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyChannel
,
673 IPC_MESSAGE_HANDLER(GpuHostMsg_CacheShader
,
676 IPC_MESSAGE_UNHANDLED(RouteOnUIThread(message
))
677 IPC_END_MESSAGE_MAP()
682 void GpuProcessHost::OnChannelConnected(int32 peer_pid
) {
683 TRACE_EVENT0("gpu", "GpuProcessHost::OnChannelConnected");
685 while (!queued_messages_
.empty()) {
686 Send(queued_messages_
.front());
687 queued_messages_
.pop();
691 void GpuProcessHost::EstablishGpuChannel(
694 const EstablishChannelCallback
& callback
) {
695 DCHECK(CalledOnValidThread());
696 TRACE_EVENT0("gpu", "GpuProcessHost::EstablishGpuChannel");
698 // If GPU features are already blacklisted, no need to establish the channel.
699 if (!GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL
)) {
700 DVLOG(1) << "GPU blacklisted, refusing to open a GPU channel.";
701 callback
.Run(IPC::ChannelHandle(), gpu::GPUInfo());
705 if (Send(new GpuMsg_EstablishChannel(client_id
, share_context
))) {
706 channel_requests_
.push(callback
);
708 DVLOG(1) << "Failed to send GpuMsg_EstablishChannel.";
709 callback
.Run(IPC::ChannelHandle(), gpu::GPUInfo());
712 if (!CommandLine::ForCurrentProcess()->HasSwitch(
713 switches::kDisableGpuShaderDiskCache
)) {
714 CreateChannelCache(client_id
);
718 void GpuProcessHost::CreateViewCommandBuffer(
719 const gfx::GLSurfaceHandle
& compositing_surface
,
722 const GPUCreateCommandBufferConfig
& init_params
,
723 const CreateCommandBufferCallback
& callback
) {
724 TRACE_EVENT0("gpu", "GpuProcessHost::CreateViewCommandBuffer");
726 DCHECK(CalledOnValidThread());
728 if (!compositing_surface
.is_null() &&
729 Send(new GpuMsg_CreateViewCommandBuffer(
730 compositing_surface
, surface_id
, client_id
, init_params
))) {
731 create_command_buffer_requests_
.push(callback
);
732 surface_refs_
.insert(std::make_pair(surface_id
,
733 GpuSurfaceTracker::GetInstance()->GetSurfaceRefForSurface(surface_id
)));
735 callback
.Run(MSG_ROUTING_NONE
);
739 void GpuProcessHost::CreateImage(gfx::PluginWindowHandle window
,
742 const CreateImageCallback
& callback
) {
743 TRACE_EVENT0("gpu", "GpuProcessHost::CreateImage");
745 DCHECK(CalledOnValidThread());
747 if (Send(new GpuMsg_CreateImage(window
, client_id
, image_id
))) {
748 create_image_requests_
.push(callback
);
750 callback
.Run(gfx::Size());
754 void GpuProcessHost::DeleteImage(int client_id
,
757 TRACE_EVENT0("gpu", "GpuProcessHost::DeleteImage");
759 DCHECK(CalledOnValidThread());
761 Send(new GpuMsg_DeleteImage(client_id
, image_id
, sync_point
));
764 void GpuProcessHost::OnInitialized(bool result
, const gpu::GPUInfo
& gpu_info
) {
765 UMA_HISTOGRAM_BOOLEAN("GPU.GPUProcessInitialized", result
);
766 initialized_
= result
;
769 GpuDataManagerImpl::GetInstance()->OnGpuProcessInitFailure();
770 else if (!in_process_
)
771 GpuDataManagerImpl::GetInstance()->UpdateGpuInfo(gpu_info
);
774 void GpuProcessHost::OnChannelEstablished(
775 const IPC::ChannelHandle
& channel_handle
) {
776 TRACE_EVENT0("gpu", "GpuProcessHost::OnChannelEstablished");
778 if (channel_requests_
.empty()) {
779 // This happens when GPU process is compromised.
780 RouteOnUIThread(GpuHostMsg_OnLogMessage(
781 logging::LOG_WARNING
,
783 "Received a ChannelEstablished message but no requests in queue."));
786 EstablishChannelCallback callback
= channel_requests_
.front();
787 channel_requests_
.pop();
789 // Currently if any of the GPU features are blacklisted, we don't establish a
791 if (!channel_handle
.name
.empty() &&
792 !GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL
)) {
793 Send(new GpuMsg_CloseChannel(channel_handle
));
794 callback
.Run(IPC::ChannelHandle(), gpu::GPUInfo());
795 RouteOnUIThread(GpuHostMsg_OnLogMessage(
796 logging::LOG_WARNING
,
798 "Hardware acceleration is unavailable."));
802 callback
.Run(channel_handle
,
803 GpuDataManagerImpl::GetInstance()->GetGPUInfo());
806 void GpuProcessHost::OnCommandBufferCreated(const int32 route_id
) {
807 TRACE_EVENT0("gpu", "GpuProcessHost::OnCommandBufferCreated");
809 if (create_command_buffer_requests_
.empty())
812 CreateCommandBufferCallback callback
=
813 create_command_buffer_requests_
.front();
814 create_command_buffer_requests_
.pop();
815 callback
.Run(route_id
);
818 void GpuProcessHost::OnDestroyCommandBuffer(int32 surface_id
) {
819 TRACE_EVENT0("gpu", "GpuProcessHost::OnDestroyCommandBuffer");
820 SurfaceRefMap::iterator it
= surface_refs_
.find(surface_id
);
821 if (it
!= surface_refs_
.end()) {
822 surface_refs_
.erase(it
);
826 void GpuProcessHost::OnImageCreated(const gfx::Size size
) {
827 TRACE_EVENT0("gpu", "GpuProcessHost::OnImageCreated");
829 if (create_image_requests_
.empty())
832 CreateImageCallback callback
= create_image_requests_
.front();
833 create_image_requests_
.pop();
837 void GpuProcessHost::OnDidCreateOffscreenContext(const GURL
& url
) {
838 urls_with_live_offscreen_contexts_
.insert(url
);
841 void GpuProcessHost::OnDidLoseContext(bool offscreen
,
842 gpu::error::ContextLostReason reason
,
844 // TODO(kbr): would be nice to see the "offscreen" flag too.
845 TRACE_EVENT2("gpu", "GpuProcessHost::OnDidLoseContext",
848 url
.possibly_invalid_spec());
850 if (!offscreen
|| url
.is_empty()) {
851 // Assume that the loss of the compositor's or accelerated canvas'
852 // context is a serious event and blame the loss on all live
853 // offscreen contexts. This more robustly handles situations where
854 // the GPU process may not actually detect the context loss in the
855 // offscreen context.
856 BlockLiveOffscreenContexts();
860 GpuDataManagerImpl::DomainGuilt guilt
;
862 case gpu::error::kGuilty
:
863 guilt
= GpuDataManagerImpl::DOMAIN_GUILT_KNOWN
;
865 case gpu::error::kUnknown
:
866 guilt
= GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN
;
868 case gpu::error::kInnocent
:
875 GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(url
, guilt
);
878 void GpuProcessHost::OnDidDestroyOffscreenContext(const GURL
& url
) {
879 urls_with_live_offscreen_contexts_
.erase(url
);
882 void GpuProcessHost::OnGpuMemoryUmaStatsReceived(
883 const GPUMemoryUmaStats
& stats
) {
884 TRACE_EVENT0("gpu", "GpuProcessHost::OnGpuMemoryUmaStatsReceived");
885 uma_memory_stats_received_
= true;
886 uma_memory_stats_
= stats
;
889 #if defined(OS_MACOSX)
890 void GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped(
891 const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params
& params
) {
892 TRACE_EVENT0("gpu", "GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped");
894 if (!ui::LatencyInfo::Verify(params
.latency_info
,
895 "GpuHostMsg_AcceleratedSurfaceBuffersSwapped"))
898 gfx::GLSurfaceHandle surface_handle
=
899 GpuSurfaceTracker::Get()->GetSurfaceHandle(params
.surface_id
);
900 // Compositor window is always gfx::kNullPluginWindow.
901 // TODO(jbates) http://crbug.com/105344 This will be removed when there are no
903 if (surface_handle
.handle
!= gfx::kNullPluginWindow
||
904 surface_handle
.transport_type
== gfx::TEXTURE_TRANSPORT
) {
905 RouteOnUIThread(GpuHostMsg_AcceleratedSurfaceBuffersSwapped(params
));
909 base::ScopedClosureRunner
scoped_completion_runner(
910 base::Bind(&AcceleratedSurfaceBuffersSwappedCompletedForGPU
,
911 host_id_
, params
.route_id
,
912 true /* alive */, base::TimeTicks(), base::TimeDelta()));
914 int render_process_id
= 0;
915 int render_widget_id
= 0;
916 if (!GpuSurfaceTracker::Get()->GetRenderWidgetIDForSurface(
917 params
.surface_id
, &render_process_id
, &render_widget_id
)) {
920 RenderWidgetHelper
* helper
=
921 RenderWidgetHelper::FromProcessHostID(render_process_id
);
925 // Pass the SwapBuffers on to the RenderWidgetHelper to wake up the UI thread
926 // if the browser is waiting for a new frame. Otherwise the RenderWidgetHelper
927 // will forward to the RenderWidgetHostView via RenderProcessHostImpl and
928 // RenderWidgetHostImpl.
929 ignore_result(scoped_completion_runner
.Release());
931 ViewHostMsg_CompositorSurfaceBuffersSwapped_Params view_params
;
932 view_params
.surface_id
= params
.surface_id
;
933 view_params
.surface_handle
= params
.surface_handle
;
934 view_params
.route_id
= params
.route_id
;
935 view_params
.size
= params
.size
;
936 view_params
.scale_factor
= params
.scale_factor
;
937 view_params
.gpu_process_host_id
= host_id_
;
938 view_params
.latency_info
= params
.latency_info
;
939 helper
->DidReceiveBackingStoreMsg(ViewHostMsg_CompositorSurfaceBuffersSwapped(
946 void GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped(
947 const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params
& params
) {
948 TRACE_EVENT0("gpu", "GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped");
950 if (!ui::LatencyInfo::Verify(params
.latency_info
,
951 "GpuHostMsg_AcceleratedSurfaceBuffersSwapped"))
954 base::ScopedClosureRunner
scoped_completion_runner(
955 base::Bind(&AcceleratedSurfaceBuffersSwappedCompleted
,
956 host_id_
, params
.route_id
, params
.surface_id
,
957 true, base::TimeTicks(), base::TimeDelta(),
958 std::vector
<ui::LatencyInfo
>()));
960 gfx::GLSurfaceHandle handle
=
961 GpuSurfaceTracker::Get()->GetSurfaceHandle(params
.surface_id
);
963 if (handle
.is_null())
966 if (handle
.transport_type
== gfx::TEXTURE_TRANSPORT
) {
967 TRACE_EVENT1("gpu", "SurfaceIDNotFound_RoutingToUI",
968 "surface_id", params
.surface_id
);
969 // This is a content area swap, send it on to the UI thread.
970 ignore_result(scoped_completion_runner
.Release());
971 RouteOnUIThread(GpuHostMsg_AcceleratedSurfaceBuffersSwapped(params
));
976 "EarlyOut_NativeWindowNotFound",
979 ignore_result(scoped_completion_runner
.Release());
980 AcceleratedSurfaceBuffersSwappedCompleted(host_id_
,
986 params
.latency_info
);
989 void GpuProcessHost::OnAcceleratedSurfacePostSubBuffer(
990 const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params
& params
) {
991 TRACE_EVENT0("gpu", "GpuProcessHost::OnAcceleratedSurfacePostSubBuffer");
993 if (!ui::LatencyInfo::Verify(params
.latency_info
,
994 "GpuHostMsg_AcceleratedSurfacePostSubBuffer"))
1000 void GpuProcessHost::OnAcceleratedSurfaceSuspend(int32 surface_id
) {
1001 TRACE_EVENT0("gpu", "GpuProcessHost::OnAcceleratedSurfaceSuspend");
1003 gfx::PluginWindowHandle handle
=
1004 GpuSurfaceTracker::Get()->GetSurfaceHandle(surface_id
).handle
;
1007 #if defined(USE_AURA)
1008 RouteOnUIThread(GpuHostMsg_AcceleratedSurfaceSuspend(surface_id
));
1014 void GpuProcessHost::OnAcceleratedSurfaceRelease(
1015 const GpuHostMsg_AcceleratedSurfaceRelease_Params
& params
) {
1016 TRACE_EVENT0("gpu", "GpuProcessHost::OnAcceleratedSurfaceRelease");
1018 gfx::PluginWindowHandle handle
=
1019 GpuSurfaceTracker::Get()->GetSurfaceHandle(params
.surface_id
).handle
;
1021 #if defined(USE_AURA)
1022 RouteOnUIThread(GpuHostMsg_AcceleratedSurfaceRelease(params
));
1030 void GpuProcessHost::OnProcessLaunched() {
1031 UMA_HISTOGRAM_TIMES("GPU.GPUProcessLaunchTime",
1032 base::TimeTicks::Now() - init_start_time_
);
1035 void GpuProcessHost::OnProcessCrashed(int exit_code
) {
1036 SendOutstandingReplies();
1037 GpuDataManagerImpl::GetInstance()->ProcessCrashed(
1038 process_
->GetTerminationStatus(true /* known_dead */, NULL
));
1041 GpuProcessHost::GpuProcessKind
GpuProcessHost::kind() {
1045 void GpuProcessHost::ForceShutdown() {
1046 // This is only called on the IO thread so no race against the constructor
1047 // for another GpuProcessHost.
1048 if (g_gpu_process_hosts
[kind_
] == this)
1049 g_gpu_process_hosts
[kind_
] = NULL
;
1051 process_
->ForceShutdown();
1054 void GpuProcessHost::BeginFrameSubscription(
1056 base::WeakPtr
<RenderWidgetHostViewFrameSubscriber
> subscriber
) {
1057 frame_subscribers_
[surface_id
] = subscriber
;
1060 void GpuProcessHost::EndFrameSubscription(int surface_id
) {
1061 frame_subscribers_
.erase(surface_id
);
1064 bool GpuProcessHost::LaunchGpuProcess(const std::string
& channel_id
) {
1065 if (!(gpu_enabled_
&&
1066 GpuDataManagerImpl::GetInstance()->ShouldUseSwiftShader()) &&
1067 !hardware_gpu_enabled_
) {
1068 SendOutstandingReplies();
1072 const CommandLine
& browser_command_line
= *CommandLine::ForCurrentProcess();
1074 CommandLine::StringType gpu_launcher
=
1075 browser_command_line
.GetSwitchValueNative(switches::kGpuLauncher
);
1077 #if defined(OS_LINUX)
1078 int child_flags
= gpu_launcher
.empty() ? ChildProcessHost::CHILD_ALLOW_SELF
:
1079 ChildProcessHost::CHILD_NORMAL
;
1081 int child_flags
= ChildProcessHost::CHILD_NORMAL
;
1084 base::FilePath exe_path
= ChildProcessHost::GetChildPath(child_flags
);
1085 if (exe_path
.empty())
1088 CommandLine
* cmd_line
= new CommandLine(exe_path
);
1089 cmd_line
->AppendSwitchASCII(switches::kProcessType
, switches::kGpuProcess
);
1090 cmd_line
->AppendSwitchASCII(switches::kProcessChannelID
, channel_id
);
1092 if (kind_
== GPU_PROCESS_KIND_UNSANDBOXED
)
1093 cmd_line
->AppendSwitch(switches::kDisableGpuSandbox
);
1095 // Propagate relevant command line switches.
1096 static const char* const kSwitchNames
[] = {
1097 switches::kDisableAcceleratedVideoDecode
,
1098 switches::kDisableBreakpad
,
1099 switches::kDisableGLDrawingForTests
,
1100 switches::kDisableGpuSandbox
,
1101 switches::kDisableGpuWatchdog
,
1102 switches::kDisableLogging
,
1103 switches::kDisableSeccompFilterSandbox
,
1104 #if defined(ENABLE_WEBRTC)
1105 switches::kDisableWebRtcHWEncoding
,
1107 switches::kEnableLogging
,
1108 switches::kEnableShareGroupAsyncTextureUpload
,
1109 switches::kGpuStartupDialog
,
1110 switches::kGpuSandboxAllowSysVShm
,
1111 switches::kGpuSandboxFailuresFatal
,
1112 switches::kGpuSandboxStartAfterInitialization
,
1113 switches::kLoggingLevel
,
1114 switches::kNoSandbox
,
1115 switches::kTestGLLib
,
1116 switches::kTraceStartup
,
1119 #if defined(OS_MACOSX)
1120 switches::kEnableSandboxLogging
,
1122 #if defined(USE_AURA)
1123 switches::kUIPrioritizeInGpuProcess
,
1125 #if defined(USE_OZONE)
1126 switches::kOzonePlatform
,
1129 switches::kHighDPISupport
,
1132 cmd_line
->CopySwitchesFrom(browser_command_line
, kSwitchNames
,
1133 arraysize(kSwitchNames
));
1134 cmd_line
->CopySwitchesFrom(
1135 browser_command_line
, switches::kGpuSwitches
, switches::kNumGpuSwitches
);
1136 cmd_line
->CopySwitchesFrom(
1137 browser_command_line
, switches::kGLSwitchesCopiedFromGpuProcessHost
,
1138 switches::kGLSwitchesCopiedFromGpuProcessHostNumSwitches
);
1140 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
1141 cmd_line
, process_
->GetData().id
);
1143 GpuDataManagerImpl::GetInstance()->AppendGpuCommandLine(cmd_line
);
1145 if (cmd_line
->HasSwitch(switches::kUseGL
)) {
1146 swiftshader_rendering_
=
1147 (cmd_line
->GetSwitchValueASCII(switches::kUseGL
) == "swiftshader");
1150 UMA_HISTOGRAM_BOOLEAN("GPU.GPU.GPUProcessSoftwareRendering",
1151 swiftshader_rendering_
);
1153 // If specified, prepend a launcher program to the command line.
1154 if (!gpu_launcher
.empty())
1155 cmd_line
->PrependWrapper(gpu_launcher
);
1158 new GpuSandboxedProcessLauncherDelegate(cmd_line
,
1159 process_
->GetHost()),
1161 process_launched_
= true;
1163 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
1164 LAUNCHED
, GPU_PROCESS_LIFETIME_EVENT_MAX
);
1168 void GpuProcessHost::SendOutstandingReplies() {
1170 // First send empty channel handles for all EstablishChannel requests.
1171 while (!channel_requests_
.empty()) {
1172 EstablishChannelCallback callback
= channel_requests_
.front();
1173 channel_requests_
.pop();
1174 callback
.Run(IPC::ChannelHandle(), gpu::GPUInfo());
1177 while (!create_command_buffer_requests_
.empty()) {
1178 CreateCommandBufferCallback callback
=
1179 create_command_buffer_requests_
.front();
1180 create_command_buffer_requests_
.pop();
1181 callback
.Run(MSG_ROUTING_NONE
);
1185 void GpuProcessHost::BlockLiveOffscreenContexts() {
1186 for (std::multiset
<GURL
>::iterator iter
=
1187 urls_with_live_offscreen_contexts_
.begin();
1188 iter
!= urls_with_live_offscreen_contexts_
.end(); ++iter
) {
1189 GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(
1190 *iter
, GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN
);
1194 std::string
GpuProcessHost::GetShaderPrefixKey() {
1195 if (shader_prefix_key_
.empty()) {
1196 gpu::GPUInfo info
= GpuDataManagerImpl::GetInstance()->GetGPUInfo();
1198 std::string in_str
= GetContentClient()->GetProduct() + "-" +
1199 info
.gl_vendor
+ "-" + info
.gl_renderer
+ "-" +
1200 info
.driver_version
+ "-" + info
.driver_vendor
;
1202 base::Base64Encode(base::SHA1HashString(in_str
), &shader_prefix_key_
);
1205 return shader_prefix_key_
;
1208 void GpuProcessHost::LoadedShader(const std::string
& key
,
1209 const std::string
& data
) {
1210 std::string prefix
= GetShaderPrefixKey();
1211 if (!key
.compare(0, prefix
.length(), prefix
))
1212 Send(new GpuMsg_LoadedShader(data
));
1215 void GpuProcessHost::CreateChannelCache(int32 client_id
) {
1216 TRACE_EVENT0("gpu", "GpuProcessHost::CreateChannelCache");
1218 scoped_refptr
<ShaderDiskCache
> cache
=
1219 ShaderCacheFactory::GetInstance()->Get(client_id
);
1223 cache
->set_host_id(host_id_
);
1225 client_id_to_shader_cache_
[client_id
] = cache
;
1228 void GpuProcessHost::OnDestroyChannel(int32 client_id
) {
1229 TRACE_EVENT0("gpu", "GpuProcessHost::OnDestroyChannel");
1230 client_id_to_shader_cache_
.erase(client_id
);
1233 void GpuProcessHost::OnCacheShader(int32 client_id
,
1234 const std::string
& key
,
1235 const std::string
& shader
) {
1236 TRACE_EVENT0("gpu", "GpuProcessHost::OnCacheShader");
1237 ClientIdToShaderCacheMap::iterator iter
=
1238 client_id_to_shader_cache_
.find(client_id
);
1239 // If the cache doesn't exist then this is an off the record profile.
1240 if (iter
== client_id_to_shader_cache_
.end())
1242 iter
->second
->Cache(GetShaderPrefixKey() + ":" + key
, shader
);
1245 } // namespace content