Make USB permissions work in the new permission message system
[chromium-blink-merge.git] / content / browser / gpu / gpu_process_host.cc
blob4c05b639b8b5c5a74bae5101693fec87cfd1c121
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::kTraceStartup,
117 switches::kTraceToConsole,
118 switches::kV,
119 switches::kVModule,
120 #if defined(OS_MACOSX)
121 switches::kDisableRemoteCoreAnimation,
122 switches::kDisableMacOverlays,
123 switches::kEnableSandboxLogging,
124 switches::kShowMacOverlayBorders,
125 #endif
126 #if defined(USE_AURA)
127 switches::kUIPrioritizeInGpuProcess,
128 #endif
129 #if defined(USE_OZONE)
130 switches::kOzonePlatform,
131 switches::kOzoneUseSurfaceless,
132 #endif
133 #if defined(USE_X11) && !defined(OS_CHROMEOS)
134 switches::kX11Display,
135 #endif
138 enum GPUProcessLifetimeEvent {
139 LAUNCHED,
140 DIED_FIRST_TIME,
141 DIED_SECOND_TIME,
142 DIED_THIRD_TIME,
143 DIED_FOURTH_TIME,
144 GPU_PROCESS_LIFETIME_EVENT_MAX = 100
147 // Indexed by GpuProcessKind. There is one of each kind maximum. This array may
148 // only be accessed from the IO thread.
149 GpuProcessHost* g_gpu_process_hosts[GpuProcessHost::GPU_PROCESS_KIND_COUNT];
152 void SendGpuProcessMessage(GpuProcessHost::GpuProcessKind kind,
153 CauseForGpuLaunch cause,
154 IPC::Message* message) {
155 GpuProcessHost* host = GpuProcessHost::Get(kind, cause);
156 if (host) {
157 host->Send(message);
158 } else {
159 delete message;
163 // NOTE: changes to this class need to be reviewed by the security team.
164 class GpuSandboxedProcessLauncherDelegate
165 : public SandboxedProcessLauncherDelegate {
166 public:
167 GpuSandboxedProcessLauncherDelegate(base::CommandLine* cmd_line,
168 ChildProcessHost* host)
169 #if defined(OS_WIN)
170 : cmd_line_(cmd_line) {}
171 #elif defined(OS_POSIX)
172 : ipc_fd_(host->TakeClientFileDescriptor()) {}
173 #endif
175 ~GpuSandboxedProcessLauncherDelegate() override {}
177 #if defined(OS_WIN)
178 bool ShouldSandbox() override {
179 bool sandbox = !cmd_line_->HasSwitch(switches::kDisableGpuSandbox);
180 if(! sandbox) {
181 DVLOG(1) << "GPU sandbox is disabled";
183 return sandbox;
186 void PreSandbox(bool* disable_default_policy,
187 base::FilePath* exposed_dir) override {
188 *disable_default_policy = true;
191 // For the GPU process we gotten as far as USER_LIMITED. The next level
192 // which is USER_RESTRICTED breaks both the DirectX backend and the OpenGL
193 // backend. Note that the GPU process is connected to the interactive
194 // desktop.
195 void PreSpawnTarget(sandbox::TargetPolicy* policy, bool* success) override {
196 if (base::win::GetVersion() > base::win::VERSION_XP) {
197 if (cmd_line_->GetSwitchValueASCII(switches::kUseGL) ==
198 gfx::kGLImplementationDesktopName) {
199 // Open GL path.
200 policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
201 sandbox::USER_LIMITED);
202 SetJobLevel(*cmd_line_, sandbox::JOB_UNPROTECTED, 0, policy);
203 policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
204 } else {
205 policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
206 sandbox::USER_LIMITED);
208 // UI restrictions break when we access Windows from outside our job.
209 // However, we don't want a proxy window in this process because it can
210 // introduce deadlocks where the renderer blocks on the gpu, which in
211 // turn blocks on the browser UI thread. So, instead we forgo a window
212 // message pump entirely and just add job restrictions to prevent child
213 // processes.
214 SetJobLevel(*cmd_line_,
215 sandbox::JOB_LIMITED_USER,
216 JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS |
217 JOB_OBJECT_UILIMIT_DESKTOP |
218 JOB_OBJECT_UILIMIT_EXITWINDOWS |
219 JOB_OBJECT_UILIMIT_DISPLAYSETTINGS,
220 policy);
222 policy->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
224 } else {
225 SetJobLevel(*cmd_line_, sandbox::JOB_UNPROTECTED, 0, policy);
226 policy->SetTokenLevel(sandbox::USER_UNPROTECTED,
227 sandbox::USER_LIMITED);
230 // Allow the server side of GPU sockets, which are pipes that have
231 // the "chrome.gpu" namespace and an arbitrary suffix.
232 sandbox::ResultCode result = policy->AddRule(
233 sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
234 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
235 L"\\\\.\\pipe\\chrome.gpu.*");
236 if (result != sandbox::SBOX_ALL_OK) {
237 *success = false;
238 return;
241 // Block this DLL even if it is not loaded by the browser process.
242 policy->AddDllToUnload(L"cmsetac.dll");
244 #ifdef USE_AURA
245 // GPU also needs to add sections to the browser for aura
246 // TODO(jschuh): refactor the GPU channel to remove this. crbug.com/128786
247 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
248 sandbox::TargetPolicy::HANDLES_DUP_BROKER,
249 L"Section");
250 if (result != sandbox::SBOX_ALL_OK) {
251 *success = false;
252 return;
254 #endif
256 if (cmd_line_->HasSwitch(switches::kEnableLogging)) {
257 base::string16 log_file_path = logging::GetLogFileFullPath();
258 if (!log_file_path.empty()) {
259 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
260 sandbox::TargetPolicy::FILES_ALLOW_ANY,
261 log_file_path.c_str());
262 if (result != sandbox::SBOX_ALL_OK) {
263 *success = false;
264 return;
269 #elif defined(OS_POSIX)
271 base::ScopedFD TakeIpcFd() override { return ipc_fd_.Pass(); }
272 #endif // OS_WIN
274 SandboxType GetSandboxType() override {
275 return SANDBOX_TYPE_GPU;
278 private:
279 #if defined(OS_WIN)
280 base::CommandLine* cmd_line_;
281 #elif defined(OS_POSIX)
282 base::ScopedFD ipc_fd_;
283 #endif // OS_WIN
286 } // anonymous namespace
288 // static
289 bool GpuProcessHost::ValidateHost(GpuProcessHost* host) {
290 // The Gpu process is invalid if it's not using SwiftShader, the card is
291 // blacklisted, and we can kill it and start over.
292 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
293 switches::kSingleProcess) ||
294 base::CommandLine::ForCurrentProcess()->HasSwitch(
295 switches::kInProcessGPU) ||
296 (host->valid_ &&
297 (host->swiftshader_rendering_ ||
298 !GpuDataManagerImpl::GetInstance()->ShouldUseSwiftShader()))) {
299 return true;
302 host->ForceShutdown();
303 return false;
306 // static
307 GpuProcessHost* GpuProcessHost::Get(GpuProcessKind kind,
308 CauseForGpuLaunch cause) {
309 DCHECK_CURRENTLY_ON(BrowserThread::IO);
311 // Don't grant further access to GPU if it is not allowed.
312 GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
313 DCHECK(gpu_data_manager);
314 if (!gpu_data_manager->GpuAccessAllowed(NULL))
315 return NULL;
317 if (g_gpu_process_hosts[kind] && ValidateHost(g_gpu_process_hosts[kind]))
318 return g_gpu_process_hosts[kind];
320 if (cause == CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH)
321 return NULL;
323 static int last_host_id = 0;
324 int host_id;
325 host_id = ++last_host_id;
327 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLaunchCause",
328 cause,
329 CAUSE_FOR_GPU_LAUNCH_MAX_ENUM);
331 GpuProcessHost* host = new GpuProcessHost(host_id, kind);
332 if (host->Init())
333 return host;
335 // TODO(sievers): Revisit this behavior. It's not really a crash, but we also
336 // want the fallback-to-sw behavior if we cannot initialize the GPU.
337 host->RecordProcessCrash();
339 delete host;
340 return NULL;
343 // static
344 void GpuProcessHost::GetProcessHandles(
345 const GpuDataManager::GetGpuProcessHandlesCallback& callback) {
346 if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
347 BrowserThread::PostTask(
348 BrowserThread::IO,
349 FROM_HERE,
350 base::Bind(&GpuProcessHost::GetProcessHandles, callback));
351 return;
353 std::list<base::ProcessHandle> handles;
354 for (size_t i = 0; i < arraysize(g_gpu_process_hosts); ++i) {
355 // TODO(rvargas) crbug/417532: don't store ProcessHandles!.
356 GpuProcessHost* host = g_gpu_process_hosts[i];
357 if (host && ValidateHost(host))
358 handles.push_back(host->process_->GetProcess().Handle());
360 BrowserThread::PostTask(
361 BrowserThread::UI,
362 FROM_HERE,
363 base::Bind(callback, handles));
366 // static
367 void GpuProcessHost::SendOnIO(GpuProcessKind kind,
368 CauseForGpuLaunch cause,
369 IPC::Message* message) {
370 if (!BrowserThread::PostTask(
371 BrowserThread::IO, FROM_HERE,
372 base::Bind(
373 &SendGpuProcessMessage, kind, cause, message))) {
374 delete message;
378 GpuMainThreadFactoryFunction g_gpu_main_thread_factory = NULL;
380 void GpuProcessHost::RegisterGpuMainThreadFactory(
381 GpuMainThreadFactoryFunction create) {
382 g_gpu_main_thread_factory = create;
385 // static
386 GpuProcessHost* GpuProcessHost::FromID(int host_id) {
387 DCHECK_CURRENTLY_ON(BrowserThread::IO);
389 for (int i = 0; i < GPU_PROCESS_KIND_COUNT; ++i) {
390 GpuProcessHost* host = g_gpu_process_hosts[i];
391 if (host && host->host_id_ == host_id && ValidateHost(host))
392 return host;
395 return NULL;
398 GpuProcessHost::GpuProcessHost(int host_id, GpuProcessKind kind)
399 : host_id_(host_id),
400 valid_(true),
401 in_process_(false),
402 swiftshader_rendering_(false),
403 kind_(kind),
404 process_launched_(false),
405 initialized_(false),
406 uma_memory_stats_received_(false) {
407 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
408 switches::kSingleProcess) ||
409 base::CommandLine::ForCurrentProcess()->HasSwitch(
410 switches::kInProcessGPU)) {
411 in_process_ = true;
414 // If the 'single GPU process' policy ever changes, we still want to maintain
415 // it for 'gpu thread' mode and only create one instance of host and thread.
416 DCHECK(!in_process_ || g_gpu_process_hosts[kind] == NULL);
418 g_gpu_process_hosts[kind] = this;
420 // Post a task to create the corresponding GpuProcessHostUIShim. The
421 // GpuProcessHostUIShim will be destroyed if either the browser exits,
422 // in which case it calls GpuProcessHostUIShim::DestroyAll, or the
423 // GpuProcessHost is destroyed, which happens when the corresponding GPU
424 // process terminates or fails to launch.
425 BrowserThread::PostTask(
426 BrowserThread::UI,
427 FROM_HERE,
428 base::Bind(base::IgnoreResult(&GpuProcessHostUIShim::Create), host_id));
430 process_.reset(new BrowserChildProcessHostImpl(PROCESS_TYPE_GPU, this));
433 GpuProcessHost::~GpuProcessHost() {
434 DCHECK(CalledOnValidThread());
436 SendOutstandingReplies();
438 // In case we never started, clean up.
439 while (!queued_messages_.empty()) {
440 delete queued_messages_.front();
441 queued_messages_.pop();
444 #if defined(OS_MACOSX) && !defined(OS_IOS)
445 if (!io_surface_manager_token_.IsZero()) {
446 BrowserIOSurfaceManager::GetInstance()->InvalidateGpuProcessToken();
447 io_surface_manager_token_.SetZero();
449 #endif
451 // This is only called on the IO thread so no race against the constructor
452 // for another GpuProcessHost.
453 if (g_gpu_process_hosts[kind_] == this)
454 g_gpu_process_hosts[kind_] = NULL;
456 // If there are any remaining offscreen contexts at the point the
457 // GPU process exits, assume something went wrong, and block their
458 // URLs from accessing client 3D APIs without prompting.
459 BlockLiveOffscreenContexts();
461 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitSurfaceCount",
462 GpuSurfaceTracker::Get()->GetSurfaceCount());
463 UMA_HISTOGRAM_BOOLEAN("GPU.AtExitReceivedMemoryStats",
464 uma_memory_stats_received_);
466 if (uma_memory_stats_received_) {
467 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitManagedMemoryClientCount",
468 uma_memory_stats_.client_count);
469 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitContextGroupCount",
470 uma_memory_stats_.context_group_count);
471 UMA_HISTOGRAM_CUSTOM_COUNTS(
472 "GPU.AtExitMBytesAllocated",
473 uma_memory_stats_.bytes_allocated_current / 1024 / 1024, 1, 2000, 50);
474 UMA_HISTOGRAM_CUSTOM_COUNTS(
475 "GPU.AtExitMBytesAllocatedMax",
476 uma_memory_stats_.bytes_allocated_max / 1024 / 1024, 1, 2000, 50);
477 UMA_HISTOGRAM_CUSTOM_COUNTS(
478 "GPU.AtExitMBytesLimit",
479 uma_memory_stats_.bytes_limit / 1024 / 1024, 1, 2000, 50);
482 std::string message;
483 if (!in_process_) {
484 int exit_code;
485 base::TerminationStatus status = process_->GetTerminationStatus(
486 false /* known_dead */, &exit_code);
487 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessTerminationStatus",
488 status,
489 base::TERMINATION_STATUS_MAX_ENUM);
491 if (status == base::TERMINATION_STATUS_NORMAL_TERMINATION ||
492 status == base::TERMINATION_STATUS_ABNORMAL_TERMINATION) {
493 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessExitCode",
494 exit_code,
495 RESULT_CODE_LAST_CODE);
498 switch (status) {
499 case base::TERMINATION_STATUS_NORMAL_TERMINATION:
500 message = "The GPU process exited normally. Everything is okay.";
501 break;
502 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
503 message = base::StringPrintf(
504 "The GPU process exited with code %d.",
505 exit_code);
506 break;
507 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED:
508 message = "You killed the GPU process! Why?";
509 break;
510 #if defined(OS_CHROMEOS)
511 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM:
512 message = "The GUP process was killed due to out of memory.";
513 break;
514 #endif
515 case base::TERMINATION_STATUS_PROCESS_CRASHED:
516 message = "The GPU process crashed!";
517 break;
518 default:
519 break;
523 BrowserThread::PostTask(BrowserThread::UI,
524 FROM_HERE,
525 base::Bind(&GpuProcessHostUIShim::Destroy,
526 host_id_,
527 message));
530 bool GpuProcessHost::Init() {
531 init_start_time_ = base::TimeTicks::Now();
533 TRACE_EVENT_INSTANT0("gpu", "LaunchGpuProcess", TRACE_EVENT_SCOPE_THREAD);
535 std::string channel_id = process_->GetHost()->CreateChannel();
536 if (channel_id.empty())
537 return false;
539 if (in_process_) {
540 DCHECK_CURRENTLY_ON(BrowserThread::IO);
541 DCHECK(g_gpu_main_thread_factory);
542 in_process_gpu_thread_.reset(
543 g_gpu_main_thread_factory(InProcessChildThreadParams(
544 channel_id, base::MessageLoop::current()->task_runner())));
545 base::Thread::Options options;
546 #if defined(OS_WIN)
547 // WGL needs to create its own window and pump messages on it.
548 options.message_loop_type = base::MessageLoop::TYPE_UI;
549 #endif
550 in_process_gpu_thread_->StartWithOptions(options);
552 OnProcessLaunched(); // Fake a callback that the process is ready.
553 } else if (!LaunchGpuProcess(channel_id)) {
554 return false;
557 if (!Send(new GpuMsg_Initialize()))
558 return false;
560 #if defined(OS_MACOSX) && !defined(OS_IOS)
561 io_surface_manager_token_ =
562 BrowserIOSurfaceManager::GetInstance()->GenerateGpuProcessToken();
563 // Note: A valid IOSurface manager token needs to be sent to the Gpu process
564 // before any GpuMemoryBuffer allocation requests can be sent.
565 Send(new ChildProcessMsg_SetIOSurfaceManagerToken(io_surface_manager_token_));
566 #endif
568 return true;
571 void GpuProcessHost::RouteOnUIThread(const IPC::Message& message) {
572 BrowserThread::PostTask(
573 BrowserThread::UI,
574 FROM_HERE,
575 base::Bind(&RouteToGpuProcessHostUIShimTask, host_id_, message));
578 bool GpuProcessHost::Send(IPC::Message* msg) {
579 DCHECK(CalledOnValidThread());
580 if (process_->GetHost()->IsChannelOpening()) {
581 queued_messages_.push(msg);
582 return true;
585 bool result = process_->Send(msg);
586 if (!result) {
587 // Channel is hosed, but we may not get destroyed for a while. Send
588 // outstanding channel creation failures now so that the caller can restart
589 // with a new process/channel without waiting.
590 SendOutstandingReplies();
592 return result;
595 void GpuProcessHost::AddFilter(IPC::MessageFilter* filter) {
596 DCHECK(CalledOnValidThread());
597 process_->GetHost()->AddFilter(filter);
600 bool GpuProcessHost::OnMessageReceived(const IPC::Message& message) {
601 DCHECK(CalledOnValidThread());
602 IPC_BEGIN_MESSAGE_MAP(GpuProcessHost, message)
603 IPC_MESSAGE_HANDLER(GpuHostMsg_Initialized, OnInitialized)
604 IPC_MESSAGE_HANDLER(GpuHostMsg_ChannelEstablished, OnChannelEstablished)
605 IPC_MESSAGE_HANDLER(GpuHostMsg_CommandBufferCreated, OnCommandBufferCreated)
606 IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyCommandBuffer, OnDestroyCommandBuffer)
607 IPC_MESSAGE_HANDLER(GpuHostMsg_GpuMemoryBufferCreated,
608 OnGpuMemoryBufferCreated)
609 IPC_MESSAGE_HANDLER(GpuHostMsg_DidCreateOffscreenContext,
610 OnDidCreateOffscreenContext)
611 IPC_MESSAGE_HANDLER(GpuHostMsg_DidLoseContext, OnDidLoseContext)
612 IPC_MESSAGE_HANDLER(GpuHostMsg_DidDestroyOffscreenContext,
613 OnDidDestroyOffscreenContext)
614 IPC_MESSAGE_HANDLER(GpuHostMsg_GpuMemoryUmaStats,
615 OnGpuMemoryUmaStatsReceived)
616 #if defined(OS_MACOSX)
617 IPC_MESSAGE_HANDLER_GENERIC(GpuHostMsg_AcceleratedSurfaceBuffersSwapped,
618 OnAcceleratedSurfaceBuffersSwapped(message))
619 #endif
620 IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyChannel,
621 OnDestroyChannel)
622 IPC_MESSAGE_HANDLER(GpuHostMsg_CacheShader,
623 OnCacheShader)
625 IPC_MESSAGE_UNHANDLED(RouteOnUIThread(message))
626 IPC_END_MESSAGE_MAP()
628 return true;
631 void GpuProcessHost::OnChannelConnected(int32 peer_pid) {
632 TRACE_EVENT0("gpu", "GpuProcessHost::OnChannelConnected");
634 while (!queued_messages_.empty()) {
635 Send(queued_messages_.front());
636 queued_messages_.pop();
640 void GpuProcessHost::EstablishGpuChannel(
641 int client_id,
642 uint64_t client_tracing_id,
643 bool share_context,
644 bool allow_future_sync_points,
645 const EstablishChannelCallback& callback) {
646 DCHECK(CalledOnValidThread());
647 TRACE_EVENT0("gpu", "GpuProcessHost::EstablishGpuChannel");
649 // If GPU features are already blacklisted, no need to establish the channel.
650 if (!GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL)) {
651 DVLOG(1) << "GPU blacklisted, refusing to open a GPU channel.";
652 callback.Run(IPC::ChannelHandle(), gpu::GPUInfo());
653 return;
656 if (Send(new GpuMsg_EstablishChannel(client_id, client_tracing_id,
657 share_context,
658 allow_future_sync_points))) {
659 channel_requests_.push(callback);
660 } else {
661 DVLOG(1) << "Failed to send GpuMsg_EstablishChannel.";
662 callback.Run(IPC::ChannelHandle(), gpu::GPUInfo());
665 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
666 switches::kDisableGpuShaderDiskCache)) {
667 CreateChannelCache(client_id);
671 void GpuProcessHost::CreateViewCommandBuffer(
672 const gfx::GLSurfaceHandle& compositing_surface,
673 int surface_id,
674 int client_id,
675 const GPUCreateCommandBufferConfig& init_params,
676 int route_id,
677 const CreateCommandBufferCallback& callback) {
678 TRACE_EVENT0("gpu", "GpuProcessHost::CreateViewCommandBuffer");
680 DCHECK(CalledOnValidThread());
682 if (!compositing_surface.is_null() &&
683 Send(new GpuMsg_CreateViewCommandBuffer(
684 compositing_surface, surface_id, client_id, init_params, route_id))) {
685 create_command_buffer_requests_.push(callback);
686 surface_refs_.insert(std::make_pair(surface_id,
687 GpuSurfaceTracker::GetInstance()->GetSurfaceRefForSurface(surface_id)));
688 } else {
689 // Could distinguish here between compositing_surface being NULL
690 // and Send failing, if desired.
691 callback.Run(CREATE_COMMAND_BUFFER_FAILED_AND_CHANNEL_LOST);
695 void GpuProcessHost::CreateGpuMemoryBuffer(
696 gfx::GpuMemoryBufferId id,
697 const gfx::Size& size,
698 gfx::BufferFormat format,
699 gfx::BufferUsage usage,
700 int client_id,
701 int32 surface_id,
702 const CreateGpuMemoryBufferCallback& callback) {
703 TRACE_EVENT0("gpu", "GpuProcessHost::CreateGpuMemoryBuffer");
705 DCHECK(CalledOnValidThread());
707 GpuMsg_CreateGpuMemoryBuffer_Params params;
708 params.id = id;
709 params.size = size;
710 params.format = format;
711 params.usage = usage;
712 params.client_id = client_id;
713 params.surface_handle =
714 GpuSurfaceTracker::GetInstance()->GetSurfaceHandle(surface_id).handle;
715 if (Send(new GpuMsg_CreateGpuMemoryBuffer(params))) {
716 create_gpu_memory_buffer_requests_.push(callback);
717 create_gpu_memory_buffer_surface_refs_.push(surface_id);
718 if (surface_id) {
719 surface_refs_.insert(std::make_pair(
720 surface_id, GpuSurfaceTracker::GetInstance()->GetSurfaceRefForSurface(
721 surface_id)));
723 } else {
724 callback.Run(gfx::GpuMemoryBufferHandle());
728 void GpuProcessHost::DestroyGpuMemoryBuffer(gfx::GpuMemoryBufferId id,
729 int client_id,
730 int sync_point) {
731 TRACE_EVENT0("gpu", "GpuProcessHost::DestroyGpuMemoryBuffer");
733 DCHECK(CalledOnValidThread());
735 Send(new GpuMsg_DestroyGpuMemoryBuffer(id, client_id, sync_point));
738 void GpuProcessHost::OnInitialized(bool result, const gpu::GPUInfo& gpu_info) {
739 UMA_HISTOGRAM_BOOLEAN("GPU.GPUProcessInitialized", result);
740 initialized_ = result;
742 if (!initialized_)
743 GpuDataManagerImpl::GetInstance()->OnGpuProcessInitFailure();
744 else if (!in_process_)
745 GpuDataManagerImpl::GetInstance()->UpdateGpuInfo(gpu_info);
748 void GpuProcessHost::OnChannelEstablished(
749 const IPC::ChannelHandle& channel_handle) {
750 TRACE_EVENT0("gpu", "GpuProcessHost::OnChannelEstablished");
752 if (channel_requests_.empty()) {
753 // This happens when GPU process is compromised.
754 RouteOnUIThread(GpuHostMsg_OnLogMessage(
755 logging::LOG_WARNING,
756 "WARNING",
757 "Received a ChannelEstablished message but no requests in queue."));
758 return;
760 EstablishChannelCallback callback = channel_requests_.front();
761 channel_requests_.pop();
763 // Currently if any of the GPU features are blacklisted, we don't establish a
764 // GPU channel.
765 if (!channel_handle.name.empty() &&
766 !GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL)) {
767 Send(new GpuMsg_CloseChannel(channel_handle));
768 callback.Run(IPC::ChannelHandle(), gpu::GPUInfo());
769 RouteOnUIThread(GpuHostMsg_OnLogMessage(
770 logging::LOG_WARNING,
771 "WARNING",
772 "Hardware acceleration is unavailable."));
773 return;
776 callback.Run(channel_handle,
777 GpuDataManagerImpl::GetInstance()->GetGPUInfo());
780 void GpuProcessHost::OnCommandBufferCreated(CreateCommandBufferResult result) {
781 TRACE_EVENT0("gpu", "GpuProcessHost::OnCommandBufferCreated");
783 if (create_command_buffer_requests_.empty())
784 return;
786 CreateCommandBufferCallback callback =
787 create_command_buffer_requests_.front();
788 create_command_buffer_requests_.pop();
789 callback.Run(result);
792 void GpuProcessHost::OnDestroyCommandBuffer(int32 surface_id) {
793 TRACE_EVENT0("gpu", "GpuProcessHost::OnDestroyCommandBuffer");
794 SurfaceRefMap::iterator it = surface_refs_.find(surface_id);
795 if (it != surface_refs_.end()) {
796 surface_refs_.erase(it);
800 void GpuProcessHost::OnGpuMemoryBufferCreated(
801 const gfx::GpuMemoryBufferHandle& handle) {
802 TRACE_EVENT0("gpu", "GpuProcessHost::OnGpuMemoryBufferCreated");
804 if (create_gpu_memory_buffer_requests_.empty())
805 return;
807 CreateGpuMemoryBufferCallback callback =
808 create_gpu_memory_buffer_requests_.front();
809 create_gpu_memory_buffer_requests_.pop();
810 callback.Run(handle);
812 int32 surface_id = create_gpu_memory_buffer_surface_refs_.front();
813 create_gpu_memory_buffer_surface_refs_.pop();
814 SurfaceRefMap::iterator it = surface_refs_.find(surface_id);
815 if (it != surface_refs_.end()) {
816 surface_refs_.erase(it);
820 void GpuProcessHost::OnDidCreateOffscreenContext(const GURL& url) {
821 urls_with_live_offscreen_contexts_.insert(url);
824 void GpuProcessHost::OnDidLoseContext(bool offscreen,
825 gpu::error::ContextLostReason reason,
826 const GURL& url) {
827 // TODO(kbr): would be nice to see the "offscreen" flag too.
828 TRACE_EVENT2("gpu", "GpuProcessHost::OnDidLoseContext",
829 "reason", reason,
830 "url",
831 url.possibly_invalid_spec());
833 if (!offscreen || url.is_empty()) {
834 // Assume that the loss of the compositor's or accelerated canvas'
835 // context is a serious event and blame the loss on all live
836 // offscreen contexts. This more robustly handles situations where
837 // the GPU process may not actually detect the context loss in the
838 // offscreen context.
839 BlockLiveOffscreenContexts();
840 return;
843 GpuDataManagerImpl::DomainGuilt guilt;
844 switch (reason) {
845 case gpu::error::kGuilty:
846 guilt = GpuDataManagerImpl::DOMAIN_GUILT_KNOWN;
847 break;
848 case gpu::error::kUnknown:
849 guilt = GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN;
850 break;
851 case gpu::error::kInnocent:
852 return;
853 default:
854 NOTREACHED();
855 return;
858 GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(url, guilt);
861 void GpuProcessHost::OnDidDestroyOffscreenContext(const GURL& url) {
862 urls_with_live_offscreen_contexts_.erase(url);
865 void GpuProcessHost::OnGpuMemoryUmaStatsReceived(
866 const GPUMemoryUmaStats& stats) {
867 TRACE_EVENT0("gpu", "GpuProcessHost::OnGpuMemoryUmaStatsReceived");
868 uma_memory_stats_received_ = true;
869 uma_memory_stats_ = stats;
872 #if defined(OS_MACOSX)
873 void GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped(
874 const IPC::Message& message) {
875 RenderWidgetResizeHelper::Get()->PostGpuProcessMsg(host_id_, message);
877 #endif
879 void GpuProcessHost::OnProcessLaunched() {
880 UMA_HISTOGRAM_TIMES("GPU.GPUProcessLaunchTime",
881 base::TimeTicks::Now() - init_start_time_);
884 void GpuProcessHost::OnProcessLaunchFailed() {
885 RecordProcessCrash();
888 void GpuProcessHost::OnProcessCrashed(int exit_code) {
889 SendOutstandingReplies();
890 RecordProcessCrash();
891 GpuDataManagerImpl::GetInstance()->ProcessCrashed(
892 process_->GetTerminationStatus(true /* known_dead */, NULL));
895 GpuProcessHost::GpuProcessKind GpuProcessHost::kind() {
896 return kind_;
899 void GpuProcessHost::ForceShutdown() {
900 // This is only called on the IO thread so no race against the constructor
901 // for another GpuProcessHost.
902 if (g_gpu_process_hosts[kind_] == this)
903 g_gpu_process_hosts[kind_] = NULL;
905 #if defined(OS_MACOSX) && !defined(OS_IOS)
906 if (!io_surface_manager_token_.IsZero()) {
907 BrowserIOSurfaceManager::GetInstance()->InvalidateGpuProcessToken();
908 io_surface_manager_token_.SetZero();
910 #endif
912 process_->ForceShutdown();
915 void GpuProcessHost::StopGpuProcess() {
916 Send(new GpuMsg_Finalize());
919 void GpuProcessHost::BeginFrameSubscription(
920 int surface_id,
921 base::WeakPtr<RenderWidgetHostViewFrameSubscriber> subscriber) {
922 frame_subscribers_[surface_id] = subscriber;
925 void GpuProcessHost::EndFrameSubscription(int surface_id) {
926 frame_subscribers_.erase(surface_id);
929 bool GpuProcessHost::LaunchGpuProcess(const std::string& channel_id) {
930 if (!(gpu_enabled_ &&
931 GpuDataManagerImpl::GetInstance()->ShouldUseSwiftShader()) &&
932 !hardware_gpu_enabled_) {
933 SendOutstandingReplies();
934 return false;
937 const base::CommandLine& browser_command_line =
938 *base::CommandLine::ForCurrentProcess();
940 base::CommandLine::StringType gpu_launcher =
941 browser_command_line.GetSwitchValueNative(switches::kGpuLauncher);
943 #if defined(OS_ANDROID)
944 // crbug.com/447735. readlink("self/proc/exe") sometimes fails on Android
945 // at startup with EACCES. As a workaround ignore this here, since the
946 // executable name is actually not used or useful anyways.
947 base::CommandLine* cmd_line =
948 new base::CommandLine(base::CommandLine::NO_PROGRAM);
949 #else
950 #if defined(OS_LINUX)
951 int child_flags = gpu_launcher.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
952 ChildProcessHost::CHILD_NORMAL;
953 #else
954 int child_flags = ChildProcessHost::CHILD_NORMAL;
955 #endif
957 base::FilePath exe_path = ChildProcessHost::GetChildPath(child_flags);
958 if (exe_path.empty())
959 return false;
961 base::CommandLine* cmd_line = new base::CommandLine(exe_path);
962 #endif
963 cmd_line->AppendSwitchASCII(switches::kProcessType, switches::kGpuProcess);
964 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
966 if (kind_ == GPU_PROCESS_KIND_UNSANDBOXED)
967 cmd_line->AppendSwitch(switches::kDisableGpuSandbox);
969 // If you want a browser command-line switch passed to the GPU process
970 // you need to add it to |kSwitchNames| at the beginning of this file.
971 cmd_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
972 arraysize(kSwitchNames));
973 cmd_line->CopySwitchesFrom(
974 browser_command_line, switches::kGpuSwitches, switches::kNumGpuSwitches);
975 cmd_line->CopySwitchesFrom(
976 browser_command_line, switches::kGLSwitchesCopiedFromGpuProcessHost,
977 switches::kGLSwitchesCopiedFromGpuProcessHostNumSwitches);
979 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
980 cmd_line, process_->GetData().id);
982 GpuDataManagerImpl::GetInstance()->AppendGpuCommandLine(cmd_line);
984 if (cmd_line->HasSwitch(switches::kUseGL)) {
985 swiftshader_rendering_ =
986 (cmd_line->GetSwitchValueASCII(switches::kUseGL) == "swiftshader");
989 UMA_HISTOGRAM_BOOLEAN("GPU.GPU.GPUProcessSoftwareRendering",
990 swiftshader_rendering_);
992 // If specified, prepend a launcher program to the command line.
993 if (!gpu_launcher.empty())
994 cmd_line->PrependWrapper(gpu_launcher);
996 process_->Launch(
997 new GpuSandboxedProcessLauncherDelegate(cmd_line,
998 process_->GetHost()),
999 cmd_line,
1000 true);
1001 process_launched_ = true;
1003 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
1004 LAUNCHED, GPU_PROCESS_LIFETIME_EVENT_MAX);
1005 return true;
1008 void GpuProcessHost::SendOutstandingReplies() {
1009 valid_ = false;
1010 // First send empty channel handles for all EstablishChannel requests.
1011 while (!channel_requests_.empty()) {
1012 EstablishChannelCallback callback = channel_requests_.front();
1013 channel_requests_.pop();
1014 callback.Run(IPC::ChannelHandle(), gpu::GPUInfo());
1017 while (!create_command_buffer_requests_.empty()) {
1018 CreateCommandBufferCallback callback =
1019 create_command_buffer_requests_.front();
1020 create_command_buffer_requests_.pop();
1021 callback.Run(CREATE_COMMAND_BUFFER_FAILED_AND_CHANNEL_LOST);
1024 while (!create_gpu_memory_buffer_requests_.empty()) {
1025 CreateGpuMemoryBufferCallback callback =
1026 create_gpu_memory_buffer_requests_.front();
1027 create_gpu_memory_buffer_requests_.pop();
1028 callback.Run(gfx::GpuMemoryBufferHandle());
1032 void GpuProcessHost::BlockLiveOffscreenContexts() {
1033 for (std::multiset<GURL>::iterator iter =
1034 urls_with_live_offscreen_contexts_.begin();
1035 iter != urls_with_live_offscreen_contexts_.end(); ++iter) {
1036 GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(
1037 *iter, GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN);
1041 void GpuProcessHost::RecordProcessCrash() {
1042 // Maximum number of times the GPU process is allowed to crash in a session.
1043 // Once this limit is reached, any request to launch the GPU process will
1044 // fail.
1045 const int kGpuMaxCrashCount = 3;
1047 // Last time the GPU process crashed.
1048 static base::Time last_gpu_crash_time;
1050 bool disable_crash_limit = base::CommandLine::ForCurrentProcess()->HasSwitch(
1051 switches::kDisableGpuProcessCrashLimit);
1053 // Ending only acts as a failure if the GPU process was actually started and
1054 // was intended for actual rendering (and not just checking caps or other
1055 // options).
1056 if (process_launched_ && kind_ == GPU_PROCESS_KIND_SANDBOXED) {
1057 if (swiftshader_rendering_) {
1058 UMA_HISTOGRAM_ENUMERATION("GPU.SwiftShaderLifetimeEvents",
1059 DIED_FIRST_TIME + swiftshader_crash_count_,
1060 GPU_PROCESS_LIFETIME_EVENT_MAX);
1062 if (++swiftshader_crash_count_ >= kGpuMaxCrashCount &&
1063 !disable_crash_limit) {
1064 // SwiftShader is too unstable to use. Disable it for current session.
1065 gpu_enabled_ = false;
1067 } else {
1068 ++gpu_crash_count_;
1069 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
1070 std::min(DIED_FIRST_TIME + gpu_crash_count_,
1071 GPU_PROCESS_LIFETIME_EVENT_MAX - 1),
1072 GPU_PROCESS_LIFETIME_EVENT_MAX);
1074 // Allow about 1 GPU crash per hour to be removed from the crash count,
1075 // so very occasional crashes won't eventually add up and prevent the
1076 // GPU process from launching.
1077 ++gpu_recent_crash_count_;
1078 base::Time current_time = base::Time::Now();
1079 if (crashed_before_) {
1080 int hours_different = (current_time - last_gpu_crash_time).InHours();
1081 gpu_recent_crash_count_ =
1082 std::max(0, gpu_recent_crash_count_ - hours_different);
1085 crashed_before_ = true;
1086 last_gpu_crash_time = current_time;
1088 if ((gpu_recent_crash_count_ >= kGpuMaxCrashCount &&
1089 !disable_crash_limit) ||
1090 !initialized_) {
1091 #if !defined(OS_CHROMEOS)
1092 // The GPU process is too unstable to use. Disable it for current
1093 // session.
1094 hardware_gpu_enabled_ = false;
1095 GpuDataManagerImpl::GetInstance()->DisableHardwareAcceleration();
1096 #endif
1102 std::string GpuProcessHost::GetShaderPrefixKey() {
1103 if (shader_prefix_key_.empty()) {
1104 gpu::GPUInfo info = GpuDataManagerImpl::GetInstance()->GetGPUInfo();
1106 std::string in_str = GetContentClient()->GetProduct() + "-" +
1107 #if defined(OS_ANDROID)
1108 base::android::BuildInfo::GetInstance()->android_build_fp() + "-" +
1109 #endif
1110 info.gl_vendor + "-" + info.gl_renderer + "-" +
1111 info.driver_version + "-" + info.driver_vendor;
1113 base::Base64Encode(base::SHA1HashString(in_str), &shader_prefix_key_);
1116 return shader_prefix_key_;
1119 void GpuProcessHost::LoadedShader(const std::string& key,
1120 const std::string& data) {
1121 std::string prefix = GetShaderPrefixKey();
1122 if (!key.compare(0, prefix.length(), prefix))
1123 Send(new GpuMsg_LoadedShader(data));
1126 void GpuProcessHost::CreateChannelCache(int32 client_id) {
1127 TRACE_EVENT0("gpu", "GpuProcessHost::CreateChannelCache");
1129 scoped_refptr<ShaderDiskCache> cache =
1130 ShaderCacheFactory::GetInstance()->Get(client_id);
1131 if (!cache.get())
1132 return;
1134 cache->set_host_id(host_id_);
1136 client_id_to_shader_cache_[client_id] = cache;
1139 void GpuProcessHost::OnDestroyChannel(int32 client_id) {
1140 TRACE_EVENT0("gpu", "GpuProcessHost::OnDestroyChannel");
1141 client_id_to_shader_cache_.erase(client_id);
1144 void GpuProcessHost::OnCacheShader(int32 client_id,
1145 const std::string& key,
1146 const std::string& shader) {
1147 TRACE_EVENT0("gpu", "GpuProcessHost::OnCacheShader");
1148 ClientIdToShaderCacheMap::iterator iter =
1149 client_id_to_shader_cache_.find(client_id);
1150 // If the cache doesn't exist then this is an off the record profile.
1151 if (iter == client_id_to_shader_cache_.end())
1152 return;
1153 iter->second->Cache(GetShaderPrefixKey() + ":" + key, shader);
1156 } // namespace content