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/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,
83 switches::kEnableWebRtcHWVp8Encoding,
85 switches::kEnableLogging,
86 switches::kEnableShareGroupAsyncTextureUpload,
87 #if defined(OS_CHROMEOS)
88 switches::kDisableVaapiAcceleratedVideoEncode,
90 switches::kGpuStartupDialog,
91 switches::kGpuSandboxAllowSysVShm,
92 switches::kGpuSandboxFailuresFatal,
93 switches::kGpuSandboxStartEarly,
94 switches::kIgnoreResolutionLimitsForAcceleratedVideoDecode,
95 switches::kLoggingLevel,
96 switches::kLowEndDeviceMode,
99 switches::kTraceStartup,
100 switches::kTraceToConsole,
103 #if defined(OS_MACOSX)
104 switches::kDisableRemoteCoreAnimation,
105 switches::kEnableSandboxLogging,
107 #if defined(USE_AURA)
108 switches::kUIPrioritizeInGpuProcess,
110 #if defined(USE_OZONE)
111 switches::kOzonePlatform,
112 switches::kOzoneUseSurfaceless,
114 #if defined(USE_X11) && !defined(OS_CHROMEOS)
115 switches::kX11Display,
119 enum GPUProcessLifetimeEvent {
125 GPU_PROCESS_LIFETIME_EVENT_MAX = 100
128 // Indexed by GpuProcessKind. There is one of each kind maximum. This array may
129 // only be accessed from the IO thread.
130 GpuProcessHost* g_gpu_process_hosts[GpuProcessHost::GPU_PROCESS_KIND_COUNT];
133 void SendGpuProcessMessage(GpuProcessHost::GpuProcessKind kind,
134 CauseForGpuLaunch cause,
135 IPC::Message* message) {
136 GpuProcessHost* host = GpuProcessHost::Get(kind, cause);
144 // NOTE: changes to this class need to be reviewed by the security team.
145 class GpuSandboxedProcessLauncherDelegate
146 : public SandboxedProcessLauncherDelegate {
148 GpuSandboxedProcessLauncherDelegate(base::CommandLine* cmd_line,
149 ChildProcessHost* host)
151 : cmd_line_(cmd_line) {}
152 #elif defined(OS_POSIX)
153 : ipc_fd_(host->TakeClientFileDescriptor()) {}
156 ~GpuSandboxedProcessLauncherDelegate() override {}
159 virtual bool ShouldSandbox() override {
160 bool sandbox = !cmd_line_->HasSwitch(switches::kDisableGpuSandbox);
162 DVLOG(1) << "GPU sandbox is disabled";
167 virtual void PreSandbox(bool* disable_default_policy,
168 base::FilePath* exposed_dir) override {
169 *disable_default_policy = true;
172 // For the GPU process we gotten as far as USER_LIMITED. The next level
173 // which is USER_RESTRICTED breaks both the DirectX backend and the OpenGL
174 // backend. Note that the GPU process is connected to the interactive
176 virtual void PreSpawnTarget(sandbox::TargetPolicy* policy,
178 if (base::win::GetVersion() > base::win::VERSION_XP) {
179 if (cmd_line_->GetSwitchValueASCII(switches::kUseGL) ==
180 gfx::kGLImplementationDesktopName) {
182 policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
183 sandbox::USER_LIMITED);
184 SetJobLevel(*cmd_line_, sandbox::JOB_UNPROTECTED, 0, policy);
185 policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
187 policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
188 sandbox::USER_LIMITED);
190 // UI restrictions break when we access Windows from outside our job.
191 // However, we don't want a proxy window in this process because it can
192 // introduce deadlocks where the renderer blocks on the gpu, which in
193 // turn blocks on the browser UI thread. So, instead we forgo a window
194 // message pump entirely and just add job restrictions to prevent child
196 SetJobLevel(*cmd_line_,
197 sandbox::JOB_LIMITED_USER,
198 JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS |
199 JOB_OBJECT_UILIMIT_DESKTOP |
200 JOB_OBJECT_UILIMIT_EXITWINDOWS |
201 JOB_OBJECT_UILIMIT_DISPLAYSETTINGS,
204 policy->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
207 SetJobLevel(*cmd_line_, sandbox::JOB_UNPROTECTED, 0, policy);
208 policy->SetTokenLevel(sandbox::USER_UNPROTECTED,
209 sandbox::USER_LIMITED);
212 // Allow the server side of GPU sockets, which are pipes that have
213 // the "chrome.gpu" namespace and an arbitrary suffix.
214 sandbox::ResultCode result = policy->AddRule(
215 sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
216 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
217 L"\\\\.\\pipe\\chrome.gpu.*");
218 if (result != sandbox::SBOX_ALL_OK) {
223 // Block this DLL even if it is not loaded by the browser process.
224 policy->AddDllToUnload(L"cmsetac.dll");
227 // GPU also needs to add sections to the browser for aura
228 // TODO(jschuh): refactor the GPU channel to remove this. crbug.com/128786
229 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
230 sandbox::TargetPolicy::HANDLES_DUP_BROKER,
232 if (result != sandbox::SBOX_ALL_OK) {
238 if (cmd_line_->HasSwitch(switches::kEnableLogging)) {
239 base::string16 log_file_path = logging::GetLogFileFullPath();
240 if (!log_file_path.empty()) {
241 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
242 sandbox::TargetPolicy::FILES_ALLOW_ANY,
243 log_file_path.c_str());
244 if (result != sandbox::SBOX_ALL_OK) {
251 #elif defined(OS_POSIX)
253 base::ScopedFD TakeIpcFd() override { return ipc_fd_.Pass(); }
258 base::CommandLine* cmd_line_;
259 #elif defined(OS_POSIX)
260 base::ScopedFD ipc_fd_;
264 } // anonymous namespace
267 bool GpuProcessHost::ValidateHost(GpuProcessHost* host) {
268 // The Gpu process is invalid if it's not using SwiftShader, the card is
269 // blacklisted, and we can kill it and start over.
270 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
271 switches::kSingleProcess) ||
272 base::CommandLine::ForCurrentProcess()->HasSwitch(
273 switches::kInProcessGPU) ||
275 (host->swiftshader_rendering_ ||
276 !GpuDataManagerImpl::GetInstance()->ShouldUseSwiftShader()))) {
280 host->ForceShutdown();
285 GpuProcessHost* GpuProcessHost::Get(GpuProcessKind kind,
286 CauseForGpuLaunch cause) {
287 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
289 // Don't grant further access to GPU if it is not allowed.
290 GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
291 DCHECK(gpu_data_manager);
292 if (!gpu_data_manager->GpuAccessAllowed(NULL))
295 if (g_gpu_process_hosts[kind] && ValidateHost(g_gpu_process_hosts[kind]))
296 return g_gpu_process_hosts[kind];
298 if (cause == CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH)
301 static int last_host_id = 0;
303 host_id = ++last_host_id;
305 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLaunchCause",
307 CAUSE_FOR_GPU_LAUNCH_MAX_ENUM);
309 GpuProcessHost* host = new GpuProcessHost(host_id, kind);
318 void GpuProcessHost::GetProcessHandles(
319 const GpuDataManager::GetGpuProcessHandlesCallback& callback) {
320 if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
321 BrowserThread::PostTask(
324 base::Bind(&GpuProcessHost::GetProcessHandles, callback));
327 std::list<base::ProcessHandle> handles;
328 for (size_t i = 0; i < arraysize(g_gpu_process_hosts); ++i) {
329 GpuProcessHost* host = g_gpu_process_hosts[i];
330 if (host && ValidateHost(host))
331 handles.push_back(host->process_->GetHandle());
333 BrowserThread::PostTask(
336 base::Bind(callback, handles));
340 void GpuProcessHost::SendOnIO(GpuProcessKind kind,
341 CauseForGpuLaunch cause,
342 IPC::Message* message) {
343 if (!BrowserThread::PostTask(
344 BrowserThread::IO, FROM_HERE,
346 &SendGpuProcessMessage, kind, cause, message))) {
351 GpuMainThreadFactoryFunction g_gpu_main_thread_factory = NULL;
353 void GpuProcessHost::RegisterGpuMainThreadFactory(
354 GpuMainThreadFactoryFunction create) {
355 g_gpu_main_thread_factory = create;
359 GpuProcessHost* GpuProcessHost::FromID(int host_id) {
360 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
362 for (int i = 0; i < GPU_PROCESS_KIND_COUNT; ++i) {
363 GpuProcessHost* host = g_gpu_process_hosts[i];
364 if (host && host->host_id_ == host_id && ValidateHost(host))
371 GpuProcessHost::GpuProcessHost(int host_id, GpuProcessKind kind)
375 swiftshader_rendering_(false),
377 process_launched_(false),
379 gpu_crash_recorded_(false),
380 uma_memory_stats_received_(false) {
381 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
382 switches::kSingleProcess) ||
383 base::CommandLine::ForCurrentProcess()->HasSwitch(
384 switches::kInProcessGPU)) {
388 // If the 'single GPU process' policy ever changes, we still want to maintain
389 // it for 'gpu thread' mode and only create one instance of host and thread.
390 DCHECK(!in_process_ || g_gpu_process_hosts[kind] == NULL);
392 g_gpu_process_hosts[kind] = this;
394 // Post a task to create the corresponding GpuProcessHostUIShim. The
395 // GpuProcessHostUIShim will be destroyed if either the browser exits,
396 // in which case it calls GpuProcessHostUIShim::DestroyAll, or the
397 // GpuProcessHost is destroyed, which happens when the corresponding GPU
398 // process terminates or fails to launch.
399 BrowserThread::PostTask(
402 base::Bind(base::IgnoreResult(&GpuProcessHostUIShim::Create), host_id));
404 process_.reset(new BrowserChildProcessHostImpl(PROCESS_TYPE_GPU, this));
407 GpuProcessHost::~GpuProcessHost() {
408 DCHECK(CalledOnValidThread());
410 SendOutstandingReplies();
412 RecordProcessCrash();
414 // In case we never started, clean up.
415 while (!queued_messages_.empty()) {
416 delete queued_messages_.front();
417 queued_messages_.pop();
420 // This is only called on the IO thread so no race against the constructor
421 // for another GpuProcessHost.
422 if (g_gpu_process_hosts[kind_] == this)
423 g_gpu_process_hosts[kind_] = NULL;
425 // If there are any remaining offscreen contexts at the point the
426 // GPU process exits, assume something went wrong, and block their
427 // URLs from accessing client 3D APIs without prompting.
428 BlockLiveOffscreenContexts();
430 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitSurfaceCount",
431 GpuSurfaceTracker::Get()->GetSurfaceCount());
432 UMA_HISTOGRAM_BOOLEAN("GPU.AtExitReceivedMemoryStats",
433 uma_memory_stats_received_);
435 if (uma_memory_stats_received_) {
436 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitManagedMemoryClientCount",
437 uma_memory_stats_.client_count);
438 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitContextGroupCount",
439 uma_memory_stats_.context_group_count);
440 UMA_HISTOGRAM_CUSTOM_COUNTS(
441 "GPU.AtExitMBytesAllocated",
442 uma_memory_stats_.bytes_allocated_current / 1024 / 1024, 1, 2000, 50);
443 UMA_HISTOGRAM_CUSTOM_COUNTS(
444 "GPU.AtExitMBytesAllocatedMax",
445 uma_memory_stats_.bytes_allocated_max / 1024 / 1024, 1, 2000, 50);
446 UMA_HISTOGRAM_CUSTOM_COUNTS(
447 "GPU.AtExitMBytesLimit",
448 uma_memory_stats_.bytes_limit / 1024 / 1024, 1, 2000, 50);
454 base::TerminationStatus status = process_->GetTerminationStatus(
455 false /* known_dead */, &exit_code);
456 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessTerminationStatus",
458 base::TERMINATION_STATUS_MAX_ENUM);
460 if (status == base::TERMINATION_STATUS_NORMAL_TERMINATION ||
461 status == base::TERMINATION_STATUS_ABNORMAL_TERMINATION) {
462 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessExitCode",
464 RESULT_CODE_LAST_CODE);
468 case base::TERMINATION_STATUS_NORMAL_TERMINATION:
469 message = "The GPU process exited normally. Everything is okay.";
471 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
472 message = base::StringPrintf(
473 "The GPU process exited with code %d.",
476 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED:
477 message = "You killed the GPU process! Why?";
479 case base::TERMINATION_STATUS_PROCESS_CRASHED:
480 message = "The GPU process crashed!";
487 BrowserThread::PostTask(BrowserThread::UI,
489 base::Bind(&GpuProcessHostUIShim::Destroy,
494 bool GpuProcessHost::Init() {
495 init_start_time_ = base::TimeTicks::Now();
497 TRACE_EVENT_INSTANT0("gpu", "LaunchGpuProcess", TRACE_EVENT_SCOPE_THREAD);
499 std::string channel_id = process_->GetHost()->CreateChannel();
500 if (channel_id.empty())
504 DCHECK(g_gpu_main_thread_factory);
505 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
506 command_line->AppendSwitch(switches::kDisableGpuWatchdog);
508 GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
509 DCHECK(gpu_data_manager);
510 gpu_data_manager->AppendGpuCommandLine(command_line);
512 in_process_gpu_thread_.reset(g_gpu_main_thread_factory(channel_id));
513 base::Thread::Options options;
515 // WGL needs to create its own window and pump messages on it.
516 options.message_loop_type = base::MessageLoop::TYPE_UI;
518 in_process_gpu_thread_->StartWithOptions(options);
520 OnProcessLaunched(); // Fake a callback that the process is ready.
521 } else if (!LaunchGpuProcess(channel_id)) {
525 if (!Send(new GpuMsg_Initialize()))
531 void GpuProcessHost::RouteOnUIThread(const IPC::Message& message) {
532 BrowserThread::PostTask(
535 base::Bind(&RouteToGpuProcessHostUIShimTask, host_id_, message));
538 bool GpuProcessHost::Send(IPC::Message* msg) {
539 DCHECK(CalledOnValidThread());
540 if (process_->GetHost()->IsChannelOpening()) {
541 queued_messages_.push(msg);
545 bool result = process_->Send(msg);
547 // Channel is hosed, but we may not get destroyed for a while. Send
548 // outstanding channel creation failures now so that the caller can restart
549 // with a new process/channel without waiting.
550 SendOutstandingReplies();
555 void GpuProcessHost::AddFilter(IPC::MessageFilter* filter) {
556 DCHECK(CalledOnValidThread());
557 process_->GetHost()->AddFilter(filter);
560 bool GpuProcessHost::OnMessageReceived(const IPC::Message& message) {
561 DCHECK(CalledOnValidThread());
562 IPC_BEGIN_MESSAGE_MAP(GpuProcessHost, message)
563 IPC_MESSAGE_HANDLER(GpuHostMsg_Initialized, OnInitialized)
564 IPC_MESSAGE_HANDLER(GpuHostMsg_ChannelEstablished, OnChannelEstablished)
565 IPC_MESSAGE_HANDLER(GpuHostMsg_CommandBufferCreated, OnCommandBufferCreated)
566 IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyCommandBuffer, OnDestroyCommandBuffer)
567 IPC_MESSAGE_HANDLER(GpuHostMsg_GpuMemoryBufferCreated,
568 OnGpuMemoryBufferCreated)
569 IPC_MESSAGE_HANDLER(GpuHostMsg_DidCreateOffscreenContext,
570 OnDidCreateOffscreenContext)
571 IPC_MESSAGE_HANDLER(GpuHostMsg_DidLoseContext, OnDidLoseContext)
572 IPC_MESSAGE_HANDLER(GpuHostMsg_DidDestroyOffscreenContext,
573 OnDidDestroyOffscreenContext)
574 IPC_MESSAGE_HANDLER(GpuHostMsg_GpuMemoryUmaStats,
575 OnGpuMemoryUmaStatsReceived)
576 #if defined(OS_MACOSX)
577 IPC_MESSAGE_HANDLER_GENERIC(GpuHostMsg_AcceleratedSurfaceBuffersSwapped,
578 OnAcceleratedSurfaceBuffersSwapped(message))
580 IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyChannel,
582 IPC_MESSAGE_HANDLER(GpuHostMsg_CacheShader,
585 IPC_MESSAGE_UNHANDLED(RouteOnUIThread(message))
586 IPC_END_MESSAGE_MAP()
591 void GpuProcessHost::OnChannelConnected(int32 peer_pid) {
592 TRACE_EVENT0("gpu", "GpuProcessHost::OnChannelConnected");
594 while (!queued_messages_.empty()) {
595 Send(queued_messages_.front());
596 queued_messages_.pop();
600 void GpuProcessHost::EstablishGpuChannel(
603 bool allow_future_sync_points,
604 const EstablishChannelCallback& callback) {
605 DCHECK(CalledOnValidThread());
606 TRACE_EVENT0("gpu", "GpuProcessHost::EstablishGpuChannel");
608 // If GPU features are already blacklisted, no need to establish the channel.
609 if (!GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL)) {
610 DVLOG(1) << "GPU blacklisted, refusing to open a GPU channel.";
611 callback.Run(IPC::ChannelHandle(), gpu::GPUInfo());
615 if (Send(new GpuMsg_EstablishChannel(
616 client_id, share_context, allow_future_sync_points))) {
617 channel_requests_.push(callback);
619 DVLOG(1) << "Failed to send GpuMsg_EstablishChannel.";
620 callback.Run(IPC::ChannelHandle(), gpu::GPUInfo());
623 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
624 switches::kDisableGpuShaderDiskCache)) {
625 CreateChannelCache(client_id);
629 void GpuProcessHost::CreateViewCommandBuffer(
630 const gfx::GLSurfaceHandle& compositing_surface,
633 const GPUCreateCommandBufferConfig& init_params,
635 const CreateCommandBufferCallback& callback) {
636 TRACE_EVENT0("gpu", "GpuProcessHost::CreateViewCommandBuffer");
638 DCHECK(CalledOnValidThread());
640 if (!compositing_surface.is_null() &&
641 Send(new GpuMsg_CreateViewCommandBuffer(
642 compositing_surface, surface_id, client_id, init_params, route_id))) {
643 create_command_buffer_requests_.push(callback);
644 surface_refs_.insert(std::make_pair(surface_id,
645 GpuSurfaceTracker::GetInstance()->GetSurfaceRefForSurface(surface_id)));
647 // Could distinguish here between compositing_surface being NULL
648 // and Send failing, if desired.
649 callback.Run(CREATE_COMMAND_BUFFER_FAILED_AND_CHANNEL_LOST);
653 void GpuProcessHost::CreateGpuMemoryBuffer(
654 gfx::GpuMemoryBufferType type,
655 gfx::GpuMemoryBufferId id,
656 const gfx::Size& size,
657 gfx::GpuMemoryBuffer::Format format,
658 gfx::GpuMemoryBuffer::Usage usage,
660 const CreateGpuMemoryBufferCallback& callback) {
661 TRACE_EVENT0("gpu", "GpuProcessHost::CreateGpuMemoryBuffer");
663 DCHECK(CalledOnValidThread());
665 GpuMsg_CreateGpuMemoryBuffer_Params params;
669 params.format = format;
670 params.usage = usage;
671 params.client_id = client_id;
672 if (Send(new GpuMsg_CreateGpuMemoryBuffer(params))) {
673 create_gpu_memory_buffer_requests_.push(callback);
675 callback.Run(gfx::GpuMemoryBufferHandle());
679 void GpuProcessHost::DestroyGpuMemoryBuffer(gfx::GpuMemoryBufferType type,
680 gfx::GpuMemoryBufferId id,
683 TRACE_EVENT0("gpu", "GpuProcessHost::DestroyGpuMemoryBuffer");
685 DCHECK(CalledOnValidThread());
687 Send(new GpuMsg_DestroyGpuMemoryBuffer(type, id, client_id, sync_point));
690 void GpuProcessHost::OnInitialized(bool result, const gpu::GPUInfo& gpu_info) {
691 UMA_HISTOGRAM_BOOLEAN("GPU.GPUProcessInitialized", result);
692 initialized_ = result;
695 GpuDataManagerImpl::GetInstance()->OnGpuProcessInitFailure();
696 else if (!in_process_)
697 GpuDataManagerImpl::GetInstance()->UpdateGpuInfo(gpu_info);
700 void GpuProcessHost::OnChannelEstablished(
701 const IPC::ChannelHandle& channel_handle) {
702 TRACE_EVENT0("gpu", "GpuProcessHost::OnChannelEstablished");
704 if (channel_requests_.empty()) {
705 // This happens when GPU process is compromised.
706 RouteOnUIThread(GpuHostMsg_OnLogMessage(
707 logging::LOG_WARNING,
709 "Received a ChannelEstablished message but no requests in queue."));
712 EstablishChannelCallback callback = channel_requests_.front();
713 channel_requests_.pop();
715 // Currently if any of the GPU features are blacklisted, we don't establish a
717 if (!channel_handle.name.empty() &&
718 !GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL)) {
719 Send(new GpuMsg_CloseChannel(channel_handle));
720 callback.Run(IPC::ChannelHandle(), gpu::GPUInfo());
721 RouteOnUIThread(GpuHostMsg_OnLogMessage(
722 logging::LOG_WARNING,
724 "Hardware acceleration is unavailable."));
728 callback.Run(channel_handle,
729 GpuDataManagerImpl::GetInstance()->GetGPUInfo());
732 void GpuProcessHost::OnCommandBufferCreated(CreateCommandBufferResult result) {
733 TRACE_EVENT0("gpu", "GpuProcessHost::OnCommandBufferCreated");
735 if (create_command_buffer_requests_.empty())
738 CreateCommandBufferCallback callback =
739 create_command_buffer_requests_.front();
740 create_command_buffer_requests_.pop();
741 callback.Run(result);
744 void GpuProcessHost::OnDestroyCommandBuffer(int32 surface_id) {
745 TRACE_EVENT0("gpu", "GpuProcessHost::OnDestroyCommandBuffer");
746 SurfaceRefMap::iterator it = surface_refs_.find(surface_id);
747 if (it != surface_refs_.end()) {
748 surface_refs_.erase(it);
752 void GpuProcessHost::OnGpuMemoryBufferCreated(
753 const gfx::GpuMemoryBufferHandle& handle) {
754 TRACE_EVENT0("gpu", "GpuProcessHost::OnGpuMemoryBufferCreated");
756 if (create_gpu_memory_buffer_requests_.empty())
759 CreateGpuMemoryBufferCallback callback =
760 create_gpu_memory_buffer_requests_.front();
761 create_gpu_memory_buffer_requests_.pop();
762 callback.Run(handle);
765 void GpuProcessHost::OnDidCreateOffscreenContext(const GURL& url) {
766 urls_with_live_offscreen_contexts_.insert(url);
769 void GpuProcessHost::OnDidLoseContext(bool offscreen,
770 gpu::error::ContextLostReason reason,
772 // TODO(kbr): would be nice to see the "offscreen" flag too.
773 TRACE_EVENT2("gpu", "GpuProcessHost::OnDidLoseContext",
776 url.possibly_invalid_spec());
778 if (!offscreen || url.is_empty()) {
779 // Assume that the loss of the compositor's or accelerated canvas'
780 // context is a serious event and blame the loss on all live
781 // offscreen contexts. This more robustly handles situations where
782 // the GPU process may not actually detect the context loss in the
783 // offscreen context.
784 BlockLiveOffscreenContexts();
788 GpuDataManagerImpl::DomainGuilt guilt;
790 case gpu::error::kGuilty:
791 guilt = GpuDataManagerImpl::DOMAIN_GUILT_KNOWN;
793 case gpu::error::kUnknown:
794 guilt = GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN;
796 case gpu::error::kInnocent:
803 GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(url, guilt);
806 void GpuProcessHost::OnDidDestroyOffscreenContext(const GURL& url) {
807 urls_with_live_offscreen_contexts_.erase(url);
810 void GpuProcessHost::OnGpuMemoryUmaStatsReceived(
811 const GPUMemoryUmaStats& stats) {
812 TRACE_EVENT0("gpu", "GpuProcessHost::OnGpuMemoryUmaStatsReceived");
813 uma_memory_stats_received_ = true;
814 uma_memory_stats_ = stats;
817 #if defined(OS_MACOSX)
818 void GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped(
819 const IPC::Message& message) {
820 RenderWidgetResizeHelper::Get()->PostGpuProcessMsg(host_id_, message);
824 void GpuProcessHost::OnProcessLaunched() {
825 UMA_HISTOGRAM_TIMES("GPU.GPUProcessLaunchTime",
826 base::TimeTicks::Now() - init_start_time_);
829 void GpuProcessHost::OnProcessCrashed(int exit_code) {
830 SendOutstandingReplies();
831 RecordProcessCrash();
832 GpuDataManagerImpl::GetInstance()->ProcessCrashed(
833 process_->GetTerminationStatus(true /* known_dead */, NULL));
836 GpuProcessHost::GpuProcessKind GpuProcessHost::kind() {
840 void GpuProcessHost::ForceShutdown() {
841 // This is only called on the IO thread so no race against the constructor
842 // for another GpuProcessHost.
843 if (g_gpu_process_hosts[kind_] == this)
844 g_gpu_process_hosts[kind_] = NULL;
846 process_->ForceShutdown();
849 void GpuProcessHost::BeginFrameSubscription(
851 base::WeakPtr<RenderWidgetHostViewFrameSubscriber> subscriber) {
852 frame_subscribers_[surface_id] = subscriber;
855 void GpuProcessHost::EndFrameSubscription(int surface_id) {
856 frame_subscribers_.erase(surface_id);
859 bool GpuProcessHost::LaunchGpuProcess(const std::string& channel_id) {
860 if (!(gpu_enabled_ &&
861 GpuDataManagerImpl::GetInstance()->ShouldUseSwiftShader()) &&
862 !hardware_gpu_enabled_) {
863 SendOutstandingReplies();
867 const base::CommandLine& browser_command_line =
868 *base::CommandLine::ForCurrentProcess();
870 base::CommandLine::StringType gpu_launcher =
871 browser_command_line.GetSwitchValueNative(switches::kGpuLauncher);
873 #if defined(OS_LINUX)
874 int child_flags = gpu_launcher.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
875 ChildProcessHost::CHILD_NORMAL;
877 int child_flags = ChildProcessHost::CHILD_NORMAL;
880 base::FilePath exe_path = ChildProcessHost::GetChildPath(child_flags);
881 if (exe_path.empty())
884 base::CommandLine* cmd_line = new base::CommandLine(exe_path);
885 cmd_line->AppendSwitchASCII(switches::kProcessType, switches::kGpuProcess);
886 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
888 if (kind_ == GPU_PROCESS_KIND_UNSANDBOXED)
889 cmd_line->AppendSwitch(switches::kDisableGpuSandbox);
891 // If you want a browser command-line switch passed to the GPU process
892 // you need to add it to |kSwitchNames| at the beginning of this file.
893 cmd_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
894 arraysize(kSwitchNames));
895 cmd_line->CopySwitchesFrom(
896 browser_command_line, switches::kGpuSwitches, switches::kNumGpuSwitches);
897 cmd_line->CopySwitchesFrom(
898 browser_command_line, switches::kGLSwitchesCopiedFromGpuProcessHost,
899 switches::kGLSwitchesCopiedFromGpuProcessHostNumSwitches);
901 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
902 cmd_line, process_->GetData().id);
904 GpuDataManagerImpl::GetInstance()->AppendGpuCommandLine(cmd_line);
906 if (cmd_line->HasSwitch(switches::kUseGL)) {
907 swiftshader_rendering_ =
908 (cmd_line->GetSwitchValueASCII(switches::kUseGL) == "swiftshader");
911 UMA_HISTOGRAM_BOOLEAN("GPU.GPU.GPUProcessSoftwareRendering",
912 swiftshader_rendering_);
914 // If specified, prepend a launcher program to the command line.
915 if (!gpu_launcher.empty())
916 cmd_line->PrependWrapper(gpu_launcher);
919 new GpuSandboxedProcessLauncherDelegate(cmd_line,
920 process_->GetHost()),
922 process_launched_ = true;
924 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
925 LAUNCHED, GPU_PROCESS_LIFETIME_EVENT_MAX);
929 void GpuProcessHost::SendOutstandingReplies() {
931 // First send empty channel handles for all EstablishChannel requests.
932 while (!channel_requests_.empty()) {
933 EstablishChannelCallback callback = channel_requests_.front();
934 channel_requests_.pop();
935 callback.Run(IPC::ChannelHandle(), gpu::GPUInfo());
938 while (!create_command_buffer_requests_.empty()) {
939 CreateCommandBufferCallback callback =
940 create_command_buffer_requests_.front();
941 create_command_buffer_requests_.pop();
942 callback.Run(CREATE_COMMAND_BUFFER_FAILED_AND_CHANNEL_LOST);
945 while (!create_gpu_memory_buffer_requests_.empty()) {
946 CreateGpuMemoryBufferCallback callback =
947 create_gpu_memory_buffer_requests_.front();
948 create_gpu_memory_buffer_requests_.pop();
949 callback.Run(gfx::GpuMemoryBufferHandle());
953 void GpuProcessHost::BlockLiveOffscreenContexts() {
954 for (std::multiset<GURL>::iterator iter =
955 urls_with_live_offscreen_contexts_.begin();
956 iter != urls_with_live_offscreen_contexts_.end(); ++iter) {
957 GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(
958 *iter, GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN);
962 void GpuProcessHost::RecordProcessCrash() {
963 // Skip if a GPU process crash was already counted.
964 if (gpu_crash_recorded_)
967 // Maximum number of times the GPU process is allowed to crash in a session.
968 // Once this limit is reached, any request to launch the GPU process will
970 const int kGpuMaxCrashCount = 3;
972 // Last time the GPU process crashed.
973 static base::Time last_gpu_crash_time;
975 bool disable_crash_limit = base::CommandLine::ForCurrentProcess()->HasSwitch(
976 switches::kDisableGpuProcessCrashLimit);
978 // Ending only acts as a failure if the GPU process was actually started and
979 // was intended for actual rendering (and not just checking caps or other
981 if (process_launched_ && kind_ == GPU_PROCESS_KIND_SANDBOXED) {
982 gpu_crash_recorded_ = true;
983 if (swiftshader_rendering_) {
984 UMA_HISTOGRAM_ENUMERATION("GPU.SwiftShaderLifetimeEvents",
985 DIED_FIRST_TIME + swiftshader_crash_count_,
986 GPU_PROCESS_LIFETIME_EVENT_MAX);
988 if (++swiftshader_crash_count_ >= kGpuMaxCrashCount &&
989 !disable_crash_limit) {
990 // SwiftShader is too unstable to use. Disable it for current session.
991 gpu_enabled_ = false;
995 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
996 std::min(DIED_FIRST_TIME + gpu_crash_count_,
997 GPU_PROCESS_LIFETIME_EVENT_MAX - 1),
998 GPU_PROCESS_LIFETIME_EVENT_MAX);
1000 // Allow about 1 GPU crash per hour to be removed from the crash count,
1001 // so very occasional crashes won't eventually add up and prevent the
1002 // GPU process from launching.
1003 ++gpu_recent_crash_count_;
1004 base::Time current_time = base::Time::Now();
1005 if (crashed_before_) {
1006 int hours_different = (current_time - last_gpu_crash_time).InHours();
1007 gpu_recent_crash_count_ =
1008 std::max(0, gpu_recent_crash_count_ - hours_different);
1011 crashed_before_ = true;
1012 last_gpu_crash_time = current_time;
1014 if ((gpu_recent_crash_count_ >= kGpuMaxCrashCount &&
1015 !disable_crash_limit) ||
1017 #if !defined(OS_CHROMEOS)
1018 // The GPU process is too unstable to use. Disable it for current
1020 hardware_gpu_enabled_ = false;
1021 GpuDataManagerImpl::GetInstance()->DisableHardwareAcceleration();
1028 std::string GpuProcessHost::GetShaderPrefixKey() {
1029 if (shader_prefix_key_.empty()) {
1030 gpu::GPUInfo info = GpuDataManagerImpl::GetInstance()->GetGPUInfo();
1032 std::string in_str = GetContentClient()->GetProduct() + "-" +
1033 info.gl_vendor + "-" + info.gl_renderer + "-" +
1034 info.driver_version + "-" + info.driver_vendor;
1036 base::Base64Encode(base::SHA1HashString(in_str), &shader_prefix_key_);
1039 return shader_prefix_key_;
1042 void GpuProcessHost::LoadedShader(const std::string& key,
1043 const std::string& data) {
1044 std::string prefix = GetShaderPrefixKey();
1045 if (!key.compare(0, prefix.length(), prefix))
1046 Send(new GpuMsg_LoadedShader(data));
1049 void GpuProcessHost::CreateChannelCache(int32 client_id) {
1050 TRACE_EVENT0("gpu", "GpuProcessHost::CreateChannelCache");
1052 scoped_refptr<ShaderDiskCache> cache =
1053 ShaderCacheFactory::GetInstance()->Get(client_id);
1057 cache->set_host_id(host_id_);
1059 client_id_to_shader_cache_[client_id] = cache;
1062 void GpuProcessHost::OnDestroyChannel(int32 client_id) {
1063 TRACE_EVENT0("gpu", "GpuProcessHost::OnDestroyChannel");
1064 client_id_to_shader_cache_.erase(client_id);
1067 void GpuProcessHost::OnCacheShader(int32 client_id,
1068 const std::string& key,
1069 const std::string& shader) {
1070 TRACE_EVENT0("gpu", "GpuProcessHost::OnCacheShader");
1071 ClientIdToShaderCacheMap::iterator iter =
1072 client_id_to_shader_cache_.find(client_id);
1073 // If the cache doesn't exist then this is an off the record profile.
1074 if (iter == client_id_to_shader_cache_.end())
1076 iter->second->Cache(GetShaderPrefixKey() + ":" + key, shader);
1079 } // namespace content