Clear webapp storage when site data is cleared
[chromium-blink-merge.git] / content / browser / gpu / gpu_process_host.cc
blobab6a3e5f5f60898e0d2f347f3e409d1df51a810e
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/gpu/gpu_process_host.h"
7 #include "base/base64.h"
8 #include "base/base_switches.h"
9 #include "base/basictypes.h"
10 #include "base/bind.h"
11 #include "base/callback_helpers.h"
12 #include "base/command_line.h"
13 #include "base/logging.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/metrics/histogram.h"
16 #include "base/sha1.h"
17 #include "base/threading/thread.h"
18 #include "base/trace_event/trace_event.h"
19 #include "components/tracing/tracing_switches.h"
20 #include "content/browser/browser_child_process_host_impl.h"
21 #include "content/browser/gpu/compositor_util.h"
22 #include "content/browser/gpu/gpu_data_manager_impl.h"
23 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
24 #include "content/browser/gpu/shader_disk_cache.h"
25 #include "content/browser/renderer_host/render_widget_host_impl.h"
26 #include "content/browser/renderer_host/render_widget_resize_helper.h"
27 #include "content/common/child_process_host_impl.h"
28 #include "content/common/gpu/gpu_messages.h"
29 #include "content/common/in_process_child_thread_params.h"
30 #include "content/common/view_messages.h"
31 #include "content/public/browser/browser_thread.h"
32 #include "content/public/browser/content_browser_client.h"
33 #include "content/public/browser/render_process_host.h"
34 #include "content/public/browser/render_widget_host_view.h"
35 #include "content/public/browser/render_widget_host_view_frame_subscriber.h"
36 #include "content/public/common/content_client.h"
37 #include "content/public/common/content_switches.h"
38 #include "content/public/common/result_codes.h"
39 #include "content/public/common/sandbox_type.h"
40 #include "content/public/common/sandboxed_process_launcher_delegate.h"
41 #include "gpu/command_buffer/service/gpu_switches.h"
42 #include "ipc/ipc_channel_handle.h"
43 #include "ipc/ipc_switches.h"
44 #include "ipc/message_filter.h"
45 #include "media/base/media_switches.h"
46 #include "ui/base/ui_base_switches.h"
47 #include "ui/events/latency_info.h"
48 #include "ui/gl/gl_switches.h"
50 #if defined(OS_ANDROID)
51 #include "base/android/build_info.h"
52 #endif
54 #if defined(OS_WIN)
55 #include "base/win/windows_version.h"
56 #include "content/common/sandbox_win.h"
57 #include "sandbox/win/src/sandbox_policy.h"
58 #include "ui/gfx/switches.h"
59 #endif
61 #if defined(USE_OZONE)
62 #include "ui/ozone/public/ozone_switches.h"
63 #endif
65 #if defined(USE_X11) && !defined(OS_CHROMEOS)
66 #include "ui/gfx/x/x11_switches.h"
67 #endif
69 #if defined(OS_MACOSX) && !defined(OS_IOS)
70 #include "content/browser/browser_io_surface_manager_mac.h"
71 #include "content/common/child_process_messages.h"
72 #endif
74 namespace content {
76 bool GpuProcessHost::gpu_enabled_ = true;
77 bool GpuProcessHost::hardware_gpu_enabled_ = true;
78 int GpuProcessHost::gpu_crash_count_ = 0;
79 int GpuProcessHost::gpu_recent_crash_count_ = 0;
80 bool GpuProcessHost::crashed_before_ = false;
81 int GpuProcessHost::swiftshader_crash_count_ = 0;
83 namespace {
85 // Command-line switches to propagate to the GPU process.
86 static const char* const kSwitchNames[] = {
87 switches::kDisableAcceleratedVideoDecode,
88 switches::kDisableBreakpad,
89 switches::kDisableGpuSandbox,
90 switches::kDisableGpuWatchdog,
91 switches::kDisableGLExtensions,
92 switches::kDisableLogging,
93 switches::kDisableSeccompFilterSandbox,
94 #if defined(ENABLE_WEBRTC)
95 switches::kDisableWebRtcHWEncoding,
96 #endif
97 #if defined(OS_WIN)
98 switches::kEnableAcceleratedVpxDecode,
99 #endif
100 switches::kEnableLogging,
101 switches::kEnableShareGroupAsyncTextureUpload,
102 #if defined(OS_CHROMEOS)
103 switches::kDisableVaapiAcceleratedVideoEncode,
104 #endif
105 switches::kGpuStartupDialog,
106 switches::kGpuSandboxAllowSysVShm,
107 switches::kGpuSandboxFailuresFatal,
108 switches::kGpuSandboxStartEarly,
109 switches::kLoggingLevel,
110 switches::kEnableLowEndDeviceMode,
111 switches::kDisableLowEndDeviceMode,
112 switches::kEnableMemoryBenchmarking,
113 switches::kNoSandbox,
114 switches::kProfilerTiming,
115 switches::kTestGLLib,
116 switches::kTraceConfigFile,
117 switches::kTraceStartup,
118 switches::kTraceToConsole,
119 switches::kV,
120 switches::kVModule,
121 #if defined(OS_MACOSX)
122 switches::kDisableRemoteCoreAnimation,
123 switches::kDisableMacOverlays,
124 switches::kEnableSandboxLogging,
125 switches::kShowMacOverlayBorders,
126 #endif
127 #if defined(USE_AURA)
128 switches::kUIPrioritizeInGpuProcess,
129 #endif
130 #if defined(USE_OZONE)
131 switches::kOzonePlatform,
132 switches::kOzoneUseSurfaceless,
133 #endif
134 #if defined(USE_X11) && !defined(OS_CHROMEOS)
135 switches::kX11Display,
136 #endif
139 enum GPUProcessLifetimeEvent {
140 LAUNCHED,
141 DIED_FIRST_TIME,
142 DIED_SECOND_TIME,
143 DIED_THIRD_TIME,
144 DIED_FOURTH_TIME,
145 GPU_PROCESS_LIFETIME_EVENT_MAX = 100
148 // Indexed by GpuProcessKind. There is one of each kind maximum. This array may
149 // only be accessed from the IO thread.
150 GpuProcessHost* g_gpu_process_hosts[GpuProcessHost::GPU_PROCESS_KIND_COUNT];
153 void SendGpuProcessMessage(GpuProcessHost::GpuProcessKind kind,
154 CauseForGpuLaunch cause,
155 IPC::Message* message) {
156 GpuProcessHost* host = GpuProcessHost::Get(kind, cause);
157 if (host) {
158 host->Send(message);
159 } else {
160 delete message;
164 // NOTE: changes to this class need to be reviewed by the security team.
165 class GpuSandboxedProcessLauncherDelegate
166 : public SandboxedProcessLauncherDelegate {
167 public:
168 GpuSandboxedProcessLauncherDelegate(base::CommandLine* cmd_line,
169 ChildProcessHost* host)
170 #if defined(OS_WIN)
171 : cmd_line_(cmd_line) {}
172 #elif defined(OS_POSIX)
173 : ipc_fd_(host->TakeClientFileDescriptor()) {}
174 #endif
176 ~GpuSandboxedProcessLauncherDelegate() override {}
178 #if defined(OS_WIN)
179 bool ShouldSandbox() override {
180 bool sandbox = !cmd_line_->HasSwitch(switches::kDisableGpuSandbox);
181 if(! sandbox) {
182 DVLOG(1) << "GPU sandbox is disabled";
184 return sandbox;
187 void PreSandbox(bool* disable_default_policy,
188 base::FilePath* exposed_dir) override {
189 *disable_default_policy = true;
192 // For the GPU process we gotten as far as USER_LIMITED. The next level
193 // which is USER_RESTRICTED breaks both the DirectX backend and the OpenGL
194 // backend. Note that the GPU process is connected to the interactive
195 // desktop.
196 void PreSpawnTarget(sandbox::TargetPolicy* policy, bool* success) override {
197 if (base::win::GetVersion() > base::win::VERSION_XP) {
198 if (cmd_line_->GetSwitchValueASCII(switches::kUseGL) ==
199 gfx::kGLImplementationDesktopName) {
200 // Open GL path.
201 policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
202 sandbox::USER_LIMITED);
203 SetJobLevel(*cmd_line_, sandbox::JOB_UNPROTECTED, 0, policy);
204 policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
205 } else {
206 policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
207 sandbox::USER_LIMITED);
209 // UI restrictions break when we access Windows from outside our job.
210 // However, we don't want a proxy window in this process because it can
211 // introduce deadlocks where the renderer blocks on the gpu, which in
212 // turn blocks on the browser UI thread. So, instead we forgo a window
213 // message pump entirely and just add job restrictions to prevent child
214 // processes.
215 SetJobLevel(*cmd_line_,
216 sandbox::JOB_LIMITED_USER,
217 JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS |
218 JOB_OBJECT_UILIMIT_DESKTOP |
219 JOB_OBJECT_UILIMIT_EXITWINDOWS |
220 JOB_OBJECT_UILIMIT_DISPLAYSETTINGS,
221 policy);
223 policy->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
225 } else {
226 SetJobLevel(*cmd_line_, sandbox::JOB_UNPROTECTED, 0, policy);
227 policy->SetTokenLevel(sandbox::USER_UNPROTECTED,
228 sandbox::USER_LIMITED);
231 // Allow the server side of GPU sockets, which are pipes that have
232 // the "chrome.gpu" namespace and an arbitrary suffix.
233 sandbox::ResultCode result = policy->AddRule(
234 sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
235 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
236 L"\\\\.\\pipe\\chrome.gpu.*");
237 if (result != sandbox::SBOX_ALL_OK) {
238 *success = false;
239 return;
242 // Block this DLL even if it is not loaded by the browser process.
243 policy->AddDllToUnload(L"cmsetac.dll");
245 #ifdef USE_AURA
246 // GPU also needs to add sections to the browser for aura
247 // TODO(jschuh): refactor the GPU channel to remove this. crbug.com/128786
248 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
249 sandbox::TargetPolicy::HANDLES_DUP_BROKER,
250 L"Section");
251 if (result != sandbox::SBOX_ALL_OK) {
252 *success = false;
253 return;
255 #endif
257 if (cmd_line_->HasSwitch(switches::kEnableLogging)) {
258 base::string16 log_file_path = logging::GetLogFileFullPath();
259 if (!log_file_path.empty()) {
260 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
261 sandbox::TargetPolicy::FILES_ALLOW_ANY,
262 log_file_path.c_str());
263 if (result != sandbox::SBOX_ALL_OK) {
264 *success = false;
265 return;
270 #elif defined(OS_POSIX)
272 base::ScopedFD TakeIpcFd() override { return ipc_fd_.Pass(); }
273 #endif // OS_WIN
275 SandboxType GetSandboxType() override {
276 return SANDBOX_TYPE_GPU;
279 private:
280 #if defined(OS_WIN)
281 base::CommandLine* cmd_line_;
282 #elif defined(OS_POSIX)
283 base::ScopedFD ipc_fd_;
284 #endif // OS_WIN
287 } // anonymous namespace
289 // static
290 bool GpuProcessHost::ValidateHost(GpuProcessHost* host) {
291 // The Gpu process is invalid if it's not using SwiftShader, the card is
292 // blacklisted, and we can kill it and start over.
293 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
294 switches::kSingleProcess) ||
295 base::CommandLine::ForCurrentProcess()->HasSwitch(
296 switches::kInProcessGPU) ||
297 (host->valid_ &&
298 (host->swiftshader_rendering_ ||
299 !GpuDataManagerImpl::GetInstance()->ShouldUseSwiftShader()))) {
300 return true;
303 host->ForceShutdown();
304 return false;
307 // static
308 GpuProcessHost* GpuProcessHost::Get(GpuProcessKind kind,
309 CauseForGpuLaunch cause) {
310 DCHECK_CURRENTLY_ON(BrowserThread::IO);
312 // Don't grant further access to GPU if it is not allowed.
313 GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
314 DCHECK(gpu_data_manager);
315 if (!gpu_data_manager->GpuAccessAllowed(NULL))
316 return NULL;
318 if (g_gpu_process_hosts[kind] && ValidateHost(g_gpu_process_hosts[kind]))
319 return g_gpu_process_hosts[kind];
321 if (cause == CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH)
322 return NULL;
324 static int last_host_id = 0;
325 int host_id;
326 host_id = ++last_host_id;
328 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLaunchCause",
329 cause,
330 CAUSE_FOR_GPU_LAUNCH_MAX_ENUM);
332 GpuProcessHost* host = new GpuProcessHost(host_id, kind);
333 if (host->Init())
334 return host;
336 // TODO(sievers): Revisit this behavior. It's not really a crash, but we also
337 // want the fallback-to-sw behavior if we cannot initialize the GPU.
338 host->RecordProcessCrash();
340 delete host;
341 return NULL;
344 // static
345 void GpuProcessHost::GetProcessHandles(
346 const GpuDataManager::GetGpuProcessHandlesCallback& callback) {
347 if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
348 BrowserThread::PostTask(
349 BrowserThread::IO,
350 FROM_HERE,
351 base::Bind(&GpuProcessHost::GetProcessHandles, callback));
352 return;
354 std::list<base::ProcessHandle> handles;
355 for (size_t i = 0; i < arraysize(g_gpu_process_hosts); ++i) {
356 // TODO(rvargas) crbug/417532: don't store ProcessHandles!.
357 GpuProcessHost* host = g_gpu_process_hosts[i];
358 if (host && ValidateHost(host))
359 handles.push_back(host->process_->GetProcess().Handle());
361 BrowserThread::PostTask(
362 BrowserThread::UI,
363 FROM_HERE,
364 base::Bind(callback, handles));
367 // static
368 void GpuProcessHost::SendOnIO(GpuProcessKind kind,
369 CauseForGpuLaunch cause,
370 IPC::Message* message) {
371 if (!BrowserThread::PostTask(
372 BrowserThread::IO, FROM_HERE,
373 base::Bind(
374 &SendGpuProcessMessage, kind, cause, message))) {
375 delete message;
379 GpuMainThreadFactoryFunction g_gpu_main_thread_factory = NULL;
381 void GpuProcessHost::RegisterGpuMainThreadFactory(
382 GpuMainThreadFactoryFunction create) {
383 g_gpu_main_thread_factory = create;
386 // static
387 GpuProcessHost* GpuProcessHost::FromID(int host_id) {
388 DCHECK_CURRENTLY_ON(BrowserThread::IO);
390 for (int i = 0; i < GPU_PROCESS_KIND_COUNT; ++i) {
391 GpuProcessHost* host = g_gpu_process_hosts[i];
392 if (host && host->host_id_ == host_id && ValidateHost(host))
393 return host;
396 return NULL;
399 GpuProcessHost::GpuProcessHost(int host_id, GpuProcessKind kind)
400 : host_id_(host_id),
401 valid_(true),
402 in_process_(false),
403 swiftshader_rendering_(false),
404 kind_(kind),
405 process_launched_(false),
406 initialized_(false),
407 uma_memory_stats_received_(false) {
408 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
409 switches::kSingleProcess) ||
410 base::CommandLine::ForCurrentProcess()->HasSwitch(
411 switches::kInProcessGPU)) {
412 in_process_ = true;
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(
427 BrowserThread::UI,
428 FROM_HERE,
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 // In case we never started, clean up.
440 while (!queued_messages_.empty()) {
441 delete queued_messages_.front();
442 queued_messages_.pop();
445 #if defined(OS_MACOSX) && !defined(OS_IOS)
446 if (!io_surface_manager_token_.IsZero()) {
447 BrowserIOSurfaceManager::GetInstance()->InvalidateGpuProcessToken();
448 io_surface_manager_token_.SetZero();
450 #endif
452 // This is only called on the IO thread so no race against the constructor
453 // for another GpuProcessHost.
454 if (g_gpu_process_hosts[kind_] == this)
455 g_gpu_process_hosts[kind_] = NULL;
457 // If there are any remaining offscreen contexts at the point the
458 // GPU process exits, assume something went wrong, and block their
459 // URLs from accessing client 3D APIs without prompting.
460 BlockLiveOffscreenContexts();
462 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitSurfaceCount",
463 GpuSurfaceTracker::Get()->GetSurfaceCount());
464 UMA_HISTOGRAM_BOOLEAN("GPU.AtExitReceivedMemoryStats",
465 uma_memory_stats_received_);
467 if (uma_memory_stats_received_) {
468 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitManagedMemoryClientCount",
469 uma_memory_stats_.client_count);
470 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitContextGroupCount",
471 uma_memory_stats_.context_group_count);
472 UMA_HISTOGRAM_CUSTOM_COUNTS(
473 "GPU.AtExitMBytesAllocated",
474 uma_memory_stats_.bytes_allocated_current / 1024 / 1024, 1, 2000, 50);
475 UMA_HISTOGRAM_CUSTOM_COUNTS(
476 "GPU.AtExitMBytesAllocatedMax",
477 uma_memory_stats_.bytes_allocated_max / 1024 / 1024, 1, 2000, 50);
478 UMA_HISTOGRAM_CUSTOM_COUNTS(
479 "GPU.AtExitMBytesLimit",
480 uma_memory_stats_.bytes_limit / 1024 / 1024, 1, 2000, 50);
483 std::string message;
484 if (!in_process_) {
485 int exit_code;
486 base::TerminationStatus status = process_->GetTerminationStatus(
487 false /* known_dead */, &exit_code);
488 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessTerminationStatus",
489 status,
490 base::TERMINATION_STATUS_MAX_ENUM);
492 if (status == base::TERMINATION_STATUS_NORMAL_TERMINATION ||
493 status == base::TERMINATION_STATUS_ABNORMAL_TERMINATION) {
494 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessExitCode",
495 exit_code,
496 RESULT_CODE_LAST_CODE);
499 switch (status) {
500 case base::TERMINATION_STATUS_NORMAL_TERMINATION:
501 message = "The GPU process exited normally. Everything is okay.";
502 break;
503 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
504 message = base::StringPrintf(
505 "The GPU process exited with code %d.",
506 exit_code);
507 break;
508 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED:
509 message = "You killed the GPU process! Why?";
510 break;
511 #if defined(OS_CHROMEOS)
512 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM:
513 message = "The GUP process was killed due to out of memory.";
514 break;
515 #endif
516 case base::TERMINATION_STATUS_PROCESS_CRASHED:
517 message = "The GPU process crashed!";
518 break;
519 case base::TERMINATION_STATUS_LAUNCH_FAILED:
520 message = "The GPU process failed to start!";
521 break;
522 default:
523 break;
527 BrowserThread::PostTask(BrowserThread::UI,
528 FROM_HERE,
529 base::Bind(&GpuProcessHostUIShim::Destroy,
530 host_id_,
531 message));
534 bool GpuProcessHost::Init() {
535 init_start_time_ = base::TimeTicks::Now();
537 TRACE_EVENT_INSTANT0("gpu", "LaunchGpuProcess", TRACE_EVENT_SCOPE_THREAD);
539 std::string channel_id = process_->GetHost()->CreateChannel();
540 if (channel_id.empty())
541 return false;
543 if (in_process_) {
544 DCHECK_CURRENTLY_ON(BrowserThread::IO);
545 DCHECK(g_gpu_main_thread_factory);
546 in_process_gpu_thread_.reset(
547 g_gpu_main_thread_factory(InProcessChildThreadParams(
548 channel_id, base::MessageLoop::current()->task_runner())));
549 base::Thread::Options options;
550 #if defined(OS_WIN)
551 // WGL needs to create its own window and pump messages on it.
552 options.message_loop_type = base::MessageLoop::TYPE_UI;
553 #endif
554 in_process_gpu_thread_->StartWithOptions(options);
556 OnProcessLaunched(); // Fake a callback that the process is ready.
557 } else if (!LaunchGpuProcess(channel_id)) {
558 return false;
561 if (!Send(new GpuMsg_Initialize()))
562 return false;
564 #if defined(OS_MACOSX) && !defined(OS_IOS)
565 io_surface_manager_token_ =
566 BrowserIOSurfaceManager::GetInstance()->GenerateGpuProcessToken();
567 // Note: A valid IOSurface manager token needs to be sent to the Gpu process
568 // before any GpuMemoryBuffer allocation requests can be sent.
569 Send(new ChildProcessMsg_SetIOSurfaceManagerToken(io_surface_manager_token_));
570 #endif
572 return true;
575 void GpuProcessHost::RouteOnUIThread(const IPC::Message& message) {
576 BrowserThread::PostTask(
577 BrowserThread::UI,
578 FROM_HERE,
579 base::Bind(&RouteToGpuProcessHostUIShimTask, host_id_, message));
582 bool GpuProcessHost::Send(IPC::Message* msg) {
583 DCHECK(CalledOnValidThread());
584 if (process_->GetHost()->IsChannelOpening()) {
585 queued_messages_.push(msg);
586 return true;
589 bool result = process_->Send(msg);
590 if (!result) {
591 // Channel is hosed, but we may not get destroyed for a while. Send
592 // outstanding channel creation failures now so that the caller can restart
593 // with a new process/channel without waiting.
594 SendOutstandingReplies();
596 return result;
599 void GpuProcessHost::AddFilter(IPC::MessageFilter* filter) {
600 DCHECK(CalledOnValidThread());
601 process_->GetHost()->AddFilter(filter);
604 bool GpuProcessHost::OnMessageReceived(const IPC::Message& message) {
605 DCHECK(CalledOnValidThread());
606 IPC_BEGIN_MESSAGE_MAP(GpuProcessHost, message)
607 IPC_MESSAGE_HANDLER(GpuHostMsg_Initialized, OnInitialized)
608 IPC_MESSAGE_HANDLER(GpuHostMsg_ChannelEstablished, OnChannelEstablished)
609 IPC_MESSAGE_HANDLER(GpuHostMsg_CommandBufferCreated, OnCommandBufferCreated)
610 IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyCommandBuffer, OnDestroyCommandBuffer)
611 IPC_MESSAGE_HANDLER(GpuHostMsg_GpuMemoryBufferCreated,
612 OnGpuMemoryBufferCreated)
613 IPC_MESSAGE_HANDLER(GpuHostMsg_DidCreateOffscreenContext,
614 OnDidCreateOffscreenContext)
615 IPC_MESSAGE_HANDLER(GpuHostMsg_DidLoseContext, OnDidLoseContext)
616 IPC_MESSAGE_HANDLER(GpuHostMsg_DidDestroyOffscreenContext,
617 OnDidDestroyOffscreenContext)
618 IPC_MESSAGE_HANDLER(GpuHostMsg_GpuMemoryUmaStats,
619 OnGpuMemoryUmaStatsReceived)
620 #if defined(OS_MACOSX)
621 IPC_MESSAGE_HANDLER_GENERIC(GpuHostMsg_AcceleratedSurfaceBuffersSwapped,
622 OnAcceleratedSurfaceBuffersSwapped(message))
623 #endif
624 IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyChannel,
625 OnDestroyChannel)
626 IPC_MESSAGE_HANDLER(GpuHostMsg_CacheShader,
627 OnCacheShader)
629 IPC_MESSAGE_UNHANDLED(RouteOnUIThread(message))
630 IPC_END_MESSAGE_MAP()
632 return true;
635 void GpuProcessHost::OnChannelConnected(int32 peer_pid) {
636 TRACE_EVENT0("gpu", "GpuProcessHost::OnChannelConnected");
638 while (!queued_messages_.empty()) {
639 Send(queued_messages_.front());
640 queued_messages_.pop();
644 void GpuProcessHost::EstablishGpuChannel(
645 int client_id,
646 uint64_t client_tracing_id,
647 bool share_context,
648 bool allow_future_sync_points,
649 bool allow_real_time_streams,
650 const EstablishChannelCallback& callback) {
651 DCHECK(CalledOnValidThread());
652 TRACE_EVENT0("gpu", "GpuProcessHost::EstablishGpuChannel");
654 // If GPU features are already blacklisted, no need to establish the channel.
655 if (!GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL)) {
656 DVLOG(1) << "GPU blacklisted, refusing to open a GPU channel.";
657 callback.Run(IPC::ChannelHandle(), gpu::GPUInfo());
658 return;
661 if (Send(new GpuMsg_EstablishChannel(client_id, client_tracing_id,
662 share_context, allow_future_sync_points,
663 allow_real_time_streams))) {
664 channel_requests_.push(callback);
665 } else {
666 DVLOG(1) << "Failed to send GpuMsg_EstablishChannel.";
667 callback.Run(IPC::ChannelHandle(), gpu::GPUInfo());
670 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
671 switches::kDisableGpuShaderDiskCache)) {
672 CreateChannelCache(client_id);
676 void GpuProcessHost::CreateViewCommandBuffer(
677 const gfx::GLSurfaceHandle& compositing_surface,
678 int surface_id,
679 int client_id,
680 const GPUCreateCommandBufferConfig& init_params,
681 int route_id,
682 const CreateCommandBufferCallback& callback) {
683 TRACE_EVENT0("gpu", "GpuProcessHost::CreateViewCommandBuffer");
685 DCHECK(CalledOnValidThread());
687 if (!compositing_surface.is_null() &&
688 Send(new GpuMsg_CreateViewCommandBuffer(
689 compositing_surface, surface_id, client_id, init_params, route_id))) {
690 create_command_buffer_requests_.push(callback);
691 surface_refs_.insert(std::make_pair(surface_id,
692 GpuSurfaceTracker::GetInstance()->GetSurfaceRefForSurface(surface_id)));
693 } else {
694 // Could distinguish here between compositing_surface being NULL
695 // and Send failing, if desired.
696 callback.Run(CREATE_COMMAND_BUFFER_FAILED_AND_CHANNEL_LOST);
700 void GpuProcessHost::CreateGpuMemoryBuffer(
701 gfx::GpuMemoryBufferId id,
702 const gfx::Size& size,
703 gfx::BufferFormat format,
704 gfx::BufferUsage usage,
705 int client_id,
706 int32 surface_id,
707 const CreateGpuMemoryBufferCallback& callback) {
708 TRACE_EVENT0("gpu", "GpuProcessHost::CreateGpuMemoryBuffer");
710 DCHECK(CalledOnValidThread());
712 GpuMsg_CreateGpuMemoryBuffer_Params params;
713 params.id = id;
714 params.size = size;
715 params.format = format;
716 params.usage = usage;
717 params.client_id = client_id;
718 params.surface_handle =
719 GpuSurfaceTracker::GetInstance()->GetSurfaceHandle(surface_id).handle;
720 if (Send(new GpuMsg_CreateGpuMemoryBuffer(params))) {
721 create_gpu_memory_buffer_requests_.push(callback);
722 create_gpu_memory_buffer_surface_refs_.push(surface_id);
723 if (surface_id) {
724 surface_refs_.insert(std::make_pair(
725 surface_id, GpuSurfaceTracker::GetInstance()->GetSurfaceRefForSurface(
726 surface_id)));
728 } else {
729 callback.Run(gfx::GpuMemoryBufferHandle());
733 void GpuProcessHost::DestroyGpuMemoryBuffer(gfx::GpuMemoryBufferId id,
734 int client_id,
735 int sync_point) {
736 TRACE_EVENT0("gpu", "GpuProcessHost::DestroyGpuMemoryBuffer");
738 DCHECK(CalledOnValidThread());
740 Send(new GpuMsg_DestroyGpuMemoryBuffer(id, client_id, sync_point));
743 void GpuProcessHost::OnInitialized(bool result, const gpu::GPUInfo& gpu_info) {
744 UMA_HISTOGRAM_BOOLEAN("GPU.GPUProcessInitialized", result);
745 initialized_ = result;
747 if (!initialized_)
748 GpuDataManagerImpl::GetInstance()->OnGpuProcessInitFailure();
749 else if (!in_process_)
750 GpuDataManagerImpl::GetInstance()->UpdateGpuInfo(gpu_info);
753 void GpuProcessHost::OnChannelEstablished(
754 const IPC::ChannelHandle& channel_handle) {
755 TRACE_EVENT0("gpu", "GpuProcessHost::OnChannelEstablished");
757 if (channel_requests_.empty()) {
758 // This happens when GPU process is compromised.
759 RouteOnUIThread(GpuHostMsg_OnLogMessage(
760 logging::LOG_WARNING,
761 "WARNING",
762 "Received a ChannelEstablished message but no requests in queue."));
763 return;
765 EstablishChannelCallback callback = channel_requests_.front();
766 channel_requests_.pop();
768 // Currently if any of the GPU features are blacklisted, we don't establish a
769 // GPU channel.
770 if (!channel_handle.name.empty() &&
771 !GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL)) {
772 Send(new GpuMsg_CloseChannel(channel_handle));
773 callback.Run(IPC::ChannelHandle(), gpu::GPUInfo());
774 RouteOnUIThread(GpuHostMsg_OnLogMessage(
775 logging::LOG_WARNING,
776 "WARNING",
777 "Hardware acceleration is unavailable."));
778 return;
781 callback.Run(channel_handle,
782 GpuDataManagerImpl::GetInstance()->GetGPUInfo());
785 void GpuProcessHost::OnCommandBufferCreated(CreateCommandBufferResult result) {
786 TRACE_EVENT0("gpu", "GpuProcessHost::OnCommandBufferCreated");
788 if (create_command_buffer_requests_.empty())
789 return;
791 CreateCommandBufferCallback callback =
792 create_command_buffer_requests_.front();
793 create_command_buffer_requests_.pop();
794 callback.Run(result);
797 void GpuProcessHost::OnDestroyCommandBuffer(int32 surface_id) {
798 TRACE_EVENT0("gpu", "GpuProcessHost::OnDestroyCommandBuffer");
799 SurfaceRefMap::iterator it = surface_refs_.find(surface_id);
800 if (it != surface_refs_.end()) {
801 surface_refs_.erase(it);
805 void GpuProcessHost::OnGpuMemoryBufferCreated(
806 const gfx::GpuMemoryBufferHandle& handle) {
807 TRACE_EVENT0("gpu", "GpuProcessHost::OnGpuMemoryBufferCreated");
809 if (create_gpu_memory_buffer_requests_.empty())
810 return;
812 CreateGpuMemoryBufferCallback callback =
813 create_gpu_memory_buffer_requests_.front();
814 create_gpu_memory_buffer_requests_.pop();
815 callback.Run(handle);
817 int32 surface_id = create_gpu_memory_buffer_surface_refs_.front();
818 create_gpu_memory_buffer_surface_refs_.pop();
819 SurfaceRefMap::iterator it = surface_refs_.find(surface_id);
820 if (it != surface_refs_.end()) {
821 surface_refs_.erase(it);
825 void GpuProcessHost::OnDidCreateOffscreenContext(const GURL& url) {
826 urls_with_live_offscreen_contexts_.insert(url);
829 void GpuProcessHost::OnDidLoseContext(bool offscreen,
830 gpu::error::ContextLostReason reason,
831 const GURL& url) {
832 // TODO(kbr): would be nice to see the "offscreen" flag too.
833 TRACE_EVENT2("gpu", "GpuProcessHost::OnDidLoseContext",
834 "reason", reason,
835 "url",
836 url.possibly_invalid_spec());
838 if (!offscreen || url.is_empty()) {
839 // Assume that the loss of the compositor's or accelerated canvas'
840 // context is a serious event and blame the loss on all live
841 // offscreen contexts. This more robustly handles situations where
842 // the GPU process may not actually detect the context loss in the
843 // offscreen context.
844 BlockLiveOffscreenContexts();
845 return;
848 GpuDataManagerImpl::DomainGuilt guilt;
849 switch (reason) {
850 case gpu::error::kGuilty:
851 guilt = GpuDataManagerImpl::DOMAIN_GUILT_KNOWN;
852 break;
853 case gpu::error::kUnknown:
854 guilt = GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN;
855 break;
856 case gpu::error::kInnocent:
857 return;
858 default:
859 NOTREACHED();
860 return;
863 GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(url, guilt);
866 void GpuProcessHost::OnDidDestroyOffscreenContext(const GURL& url) {
867 urls_with_live_offscreen_contexts_.erase(url);
870 void GpuProcessHost::OnGpuMemoryUmaStatsReceived(
871 const GPUMemoryUmaStats& stats) {
872 TRACE_EVENT0("gpu", "GpuProcessHost::OnGpuMemoryUmaStatsReceived");
873 uma_memory_stats_received_ = true;
874 uma_memory_stats_ = stats;
877 #if defined(OS_MACOSX)
878 void GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped(
879 const IPC::Message& message) {
880 RenderWidgetResizeHelper::Get()->PostGpuProcessMsg(host_id_, message);
882 #endif
884 void GpuProcessHost::OnProcessLaunched() {
885 UMA_HISTOGRAM_TIMES("GPU.GPUProcessLaunchTime",
886 base::TimeTicks::Now() - init_start_time_);
889 void GpuProcessHost::OnProcessLaunchFailed() {
890 RecordProcessCrash();
893 void GpuProcessHost::OnProcessCrashed(int exit_code) {
894 SendOutstandingReplies();
895 RecordProcessCrash();
896 GpuDataManagerImpl::GetInstance()->ProcessCrashed(
897 process_->GetTerminationStatus(true /* known_dead */, NULL));
900 GpuProcessHost::GpuProcessKind GpuProcessHost::kind() {
901 return kind_;
904 void GpuProcessHost::ForceShutdown() {
905 // This is only called on the IO thread so no race against the constructor
906 // for another GpuProcessHost.
907 if (g_gpu_process_hosts[kind_] == this)
908 g_gpu_process_hosts[kind_] = NULL;
910 #if defined(OS_MACOSX) && !defined(OS_IOS)
911 if (!io_surface_manager_token_.IsZero()) {
912 BrowserIOSurfaceManager::GetInstance()->InvalidateGpuProcessToken();
913 io_surface_manager_token_.SetZero();
915 #endif
917 process_->ForceShutdown();
920 void GpuProcessHost::StopGpuProcess() {
921 Send(new GpuMsg_Finalize());
924 void GpuProcessHost::BeginFrameSubscription(
925 int surface_id,
926 base::WeakPtr<RenderWidgetHostViewFrameSubscriber> subscriber) {
927 frame_subscribers_[surface_id] = subscriber;
930 void GpuProcessHost::EndFrameSubscription(int surface_id) {
931 frame_subscribers_.erase(surface_id);
934 bool GpuProcessHost::LaunchGpuProcess(const std::string& channel_id) {
935 if (!(gpu_enabled_ &&
936 GpuDataManagerImpl::GetInstance()->ShouldUseSwiftShader()) &&
937 !hardware_gpu_enabled_) {
938 SendOutstandingReplies();
939 return false;
942 const base::CommandLine& browser_command_line =
943 *base::CommandLine::ForCurrentProcess();
945 base::CommandLine::StringType gpu_launcher =
946 browser_command_line.GetSwitchValueNative(switches::kGpuLauncher);
948 #if defined(OS_ANDROID)
949 // crbug.com/447735. readlink("self/proc/exe") sometimes fails on Android
950 // at startup with EACCES. As a workaround ignore this here, since the
951 // executable name is actually not used or useful anyways.
952 base::CommandLine* cmd_line =
953 new base::CommandLine(base::CommandLine::NO_PROGRAM);
954 #else
955 #if defined(OS_LINUX)
956 int child_flags = gpu_launcher.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
957 ChildProcessHost::CHILD_NORMAL;
958 #else
959 int child_flags = ChildProcessHost::CHILD_NORMAL;
960 #endif
962 base::FilePath exe_path = ChildProcessHost::GetChildPath(child_flags);
963 if (exe_path.empty())
964 return false;
966 base::CommandLine* cmd_line = new base::CommandLine(exe_path);
967 #endif
968 cmd_line->AppendSwitchASCII(switches::kProcessType, switches::kGpuProcess);
969 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
971 if (kind_ == GPU_PROCESS_KIND_UNSANDBOXED)
972 cmd_line->AppendSwitch(switches::kDisableGpuSandbox);
974 // If you want a browser command-line switch passed to the GPU process
975 // you need to add it to |kSwitchNames| at the beginning of this file.
976 cmd_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
977 arraysize(kSwitchNames));
978 cmd_line->CopySwitchesFrom(
979 browser_command_line, switches::kGpuSwitches, switches::kNumGpuSwitches);
980 cmd_line->CopySwitchesFrom(
981 browser_command_line, switches::kGLSwitchesCopiedFromGpuProcessHost,
982 switches::kGLSwitchesCopiedFromGpuProcessHostNumSwitches);
984 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
985 cmd_line, process_->GetData().id);
987 GpuDataManagerImpl::GetInstance()->AppendGpuCommandLine(cmd_line);
989 if (cmd_line->HasSwitch(switches::kUseGL)) {
990 swiftshader_rendering_ =
991 (cmd_line->GetSwitchValueASCII(switches::kUseGL) == "swiftshader");
994 UMA_HISTOGRAM_BOOLEAN("GPU.GPU.GPUProcessSoftwareRendering",
995 swiftshader_rendering_);
997 // If specified, prepend a launcher program to the command line.
998 if (!gpu_launcher.empty())
999 cmd_line->PrependWrapper(gpu_launcher);
1001 process_->Launch(
1002 new GpuSandboxedProcessLauncherDelegate(cmd_line,
1003 process_->GetHost()),
1004 cmd_line,
1005 true);
1006 process_launched_ = true;
1008 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
1009 LAUNCHED, GPU_PROCESS_LIFETIME_EVENT_MAX);
1010 return true;
1013 void GpuProcessHost::SendOutstandingReplies() {
1014 valid_ = false;
1015 // First send empty channel handles for all EstablishChannel requests.
1016 while (!channel_requests_.empty()) {
1017 EstablishChannelCallback callback = channel_requests_.front();
1018 channel_requests_.pop();
1019 callback.Run(IPC::ChannelHandle(), gpu::GPUInfo());
1022 while (!create_command_buffer_requests_.empty()) {
1023 CreateCommandBufferCallback callback =
1024 create_command_buffer_requests_.front();
1025 create_command_buffer_requests_.pop();
1026 callback.Run(CREATE_COMMAND_BUFFER_FAILED_AND_CHANNEL_LOST);
1029 while (!create_gpu_memory_buffer_requests_.empty()) {
1030 CreateGpuMemoryBufferCallback callback =
1031 create_gpu_memory_buffer_requests_.front();
1032 create_gpu_memory_buffer_requests_.pop();
1033 callback.Run(gfx::GpuMemoryBufferHandle());
1037 void GpuProcessHost::BlockLiveOffscreenContexts() {
1038 for (std::multiset<GURL>::iterator iter =
1039 urls_with_live_offscreen_contexts_.begin();
1040 iter != urls_with_live_offscreen_contexts_.end(); ++iter) {
1041 GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(
1042 *iter, GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN);
1046 void GpuProcessHost::RecordProcessCrash() {
1047 // Maximum number of times the GPU process is allowed to crash in a session.
1048 // Once this limit is reached, any request to launch the GPU process will
1049 // fail.
1050 const int kGpuMaxCrashCount = 3;
1052 // Last time the GPU process crashed.
1053 static base::Time last_gpu_crash_time;
1055 bool disable_crash_limit = base::CommandLine::ForCurrentProcess()->HasSwitch(
1056 switches::kDisableGpuProcessCrashLimit);
1058 // Ending only acts as a failure if the GPU process was actually started and
1059 // was intended for actual rendering (and not just checking caps or other
1060 // options).
1061 if (process_launched_ && kind_ == GPU_PROCESS_KIND_SANDBOXED) {
1062 if (swiftshader_rendering_) {
1063 UMA_HISTOGRAM_ENUMERATION("GPU.SwiftShaderLifetimeEvents",
1064 DIED_FIRST_TIME + swiftshader_crash_count_,
1065 GPU_PROCESS_LIFETIME_EVENT_MAX);
1067 if (++swiftshader_crash_count_ >= kGpuMaxCrashCount &&
1068 !disable_crash_limit) {
1069 // SwiftShader is too unstable to use. Disable it for current session.
1070 gpu_enabled_ = false;
1072 } else {
1073 ++gpu_crash_count_;
1074 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
1075 std::min(DIED_FIRST_TIME + gpu_crash_count_,
1076 GPU_PROCESS_LIFETIME_EVENT_MAX - 1),
1077 GPU_PROCESS_LIFETIME_EVENT_MAX);
1079 // Allow about 1 GPU crash per hour to be removed from the crash count,
1080 // so very occasional crashes won't eventually add up and prevent the
1081 // GPU process from launching.
1082 ++gpu_recent_crash_count_;
1083 base::Time current_time = base::Time::Now();
1084 if (crashed_before_) {
1085 int hours_different = (current_time - last_gpu_crash_time).InHours();
1086 gpu_recent_crash_count_ =
1087 std::max(0, gpu_recent_crash_count_ - hours_different);
1090 crashed_before_ = true;
1091 last_gpu_crash_time = current_time;
1093 if ((gpu_recent_crash_count_ >= kGpuMaxCrashCount &&
1094 !disable_crash_limit) ||
1095 !initialized_) {
1096 #if !defined(OS_CHROMEOS)
1097 // The GPU process is too unstable to use. Disable it for current
1098 // session.
1099 hardware_gpu_enabled_ = false;
1100 GpuDataManagerImpl::GetInstance()->DisableHardwareAcceleration();
1101 #endif
1107 std::string GpuProcessHost::GetShaderPrefixKey() {
1108 if (shader_prefix_key_.empty()) {
1109 gpu::GPUInfo info = GpuDataManagerImpl::GetInstance()->GetGPUInfo();
1111 std::string in_str = GetContentClient()->GetProduct() + "-" +
1112 #if defined(OS_ANDROID)
1113 base::android::BuildInfo::GetInstance()->android_build_fp() + "-" +
1114 #endif
1115 info.gl_vendor + "-" + info.gl_renderer + "-" +
1116 info.driver_version + "-" + info.driver_vendor;
1118 base::Base64Encode(base::SHA1HashString(in_str), &shader_prefix_key_);
1121 return shader_prefix_key_;
1124 void GpuProcessHost::LoadedShader(const std::string& key,
1125 const std::string& data) {
1126 std::string prefix = GetShaderPrefixKey();
1127 if (!key.compare(0, prefix.length(), prefix))
1128 Send(new GpuMsg_LoadedShader(data));
1131 void GpuProcessHost::CreateChannelCache(int32 client_id) {
1132 TRACE_EVENT0("gpu", "GpuProcessHost::CreateChannelCache");
1134 scoped_refptr<ShaderDiskCache> cache =
1135 ShaderCacheFactory::GetInstance()->Get(client_id);
1136 if (!cache.get())
1137 return;
1139 cache->set_host_id(host_id_);
1141 client_id_to_shader_cache_[client_id] = cache;
1144 void GpuProcessHost::OnDestroyChannel(int32 client_id) {
1145 TRACE_EVENT0("gpu", "GpuProcessHost::OnDestroyChannel");
1146 client_id_to_shader_cache_.erase(client_id);
1149 void GpuProcessHost::OnCacheShader(int32 client_id,
1150 const std::string& key,
1151 const std::string& shader) {
1152 TRACE_EVENT0("gpu", "GpuProcessHost::OnCacheShader");
1153 ClientIdToShaderCacheMap::iterator iter =
1154 client_id_to_shader_cache_.find(client_id);
1155 // If the cache doesn't exist then this is an off the record profile.
1156 if (iter == client_id_to_shader_cache_.end())
1157 return;
1158 iter->second->Cache(GetShaderPrefixKey() + ":" + key, shader);
1161 } // namespace content