DevTools: cut host and port from webSocketDebuggerUrl in addition to ws:// prefix
[chromium-blink-merge.git] / content / browser / gpu / gpu_process_host.cc
blob6fff587506cfcfb94c44e2700ab0eab7c99b0ef0
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/gpu/gpu_process_host.h"
7 #include "base/base64.h"
8 #include "base/base_switches.h"
9 #include "base/basictypes.h"
10 #include "base/bind.h"
11 #include "base/callback_helpers.h"
12 #include "base/command_line.h"
13 #include "base/logging.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/metrics/histogram.h"
16 #include "base/sha1.h"
17 #include "base/threading/thread.h"
18 #include "base/trace_event/trace_event.h"
19 #include "content/browser/browser_child_process_host_impl.h"
20 #include "content/browser/gpu/compositor_util.h"
21 #include "content/browser/gpu/gpu_data_manager_impl.h"
22 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
23 #include "content/browser/gpu/shader_disk_cache.h"
24 #include "content/browser/renderer_host/render_widget_host_impl.h"
25 #include "content/browser/renderer_host/render_widget_resize_helper.h"
26 #include "content/common/child_process_host_impl.h"
27 #include "content/common/gpu/gpu_messages.h"
28 #include "content/common/in_process_child_thread_params.h"
29 #include "content/common/view_messages.h"
30 #include "content/public/browser/browser_thread.h"
31 #include "content/public/browser/content_browser_client.h"
32 #include "content/public/browser/render_process_host.h"
33 #include "content/public/browser/render_widget_host_view.h"
34 #include "content/public/browser/render_widget_host_view_frame_subscriber.h"
35 #include "content/public/common/content_client.h"
36 #include "content/public/common/content_switches.h"
37 #include "content/public/common/result_codes.h"
38 #include "content/public/common/sandbox_type.h"
39 #include "content/public/common/sandboxed_process_launcher_delegate.h"
40 #include "gpu/command_buffer/service/gpu_switches.h"
41 #include "ipc/ipc_channel_handle.h"
42 #include "ipc/ipc_switches.h"
43 #include "ipc/message_filter.h"
44 #include "media/base/media_switches.h"
45 #include "ui/base/ui_base_switches.h"
46 #include "ui/events/latency_info.h"
47 #include "ui/gl/gl_switches.h"
49 #if defined(OS_ANDROID)
50 #include "base/android/build_info.h"
51 #endif
53 #if defined(OS_WIN)
54 #include "base/win/windows_version.h"
55 #include "content/common/sandbox_win.h"
56 #include "sandbox/win/src/sandbox_policy.h"
57 #include "ui/gfx/switches.h"
58 #endif
60 #if defined(USE_OZONE)
61 #include "ui/ozone/public/ozone_switches.h"
62 #endif
64 #if defined(USE_X11) && !defined(OS_CHROMEOS)
65 #include "ui/gfx/x/x11_switches.h"
66 #endif
68 #if defined(OS_MACOSX) && !defined(OS_IOS)
69 #include "content/browser/browser_io_surface_manager_mac.h"
70 #include "content/common/child_process_messages.h"
71 #endif
73 namespace content {
75 bool GpuProcessHost::gpu_enabled_ = true;
76 bool GpuProcessHost::hardware_gpu_enabled_ = true;
77 int GpuProcessHost::gpu_crash_count_ = 0;
78 int GpuProcessHost::gpu_recent_crash_count_ = 0;
79 bool GpuProcessHost::crashed_before_ = false;
80 int GpuProcessHost::swiftshader_crash_count_ = 0;
82 namespace {
84 // Command-line switches to propagate to the GPU process.
85 static const char* const kSwitchNames[] = {
86 switches::kDisableAcceleratedVideoDecode,
87 switches::kDisableBreakpad,
88 switches::kDisableGpuSandbox,
89 switches::kDisableGpuWatchdog,
90 switches::kDisableGLExtensions,
91 switches::kDisableLogging,
92 switches::kDisableSeccompFilterSandbox,
93 #if defined(ENABLE_WEBRTC)
94 switches::kDisableWebRtcHWEncoding,
95 #endif
96 switches::kEnableLogging,
97 switches::kEnableShareGroupAsyncTextureUpload,
98 #if defined(OS_CHROMEOS)
99 switches::kDisableVaapiAcceleratedVideoEncode,
100 #endif
101 switches::kGpuStartupDialog,
102 switches::kGpuSandboxAllowSysVShm,
103 switches::kGpuSandboxFailuresFatal,
104 switches::kGpuSandboxStartEarly,
105 switches::kLoggingLevel,
106 switches::kEnableLowEndDeviceMode,
107 switches::kDisableLowEndDeviceMode,
108 switches::kNoSandbox,
109 switches::kProfilerTiming,
110 switches::kTestGLLib,
111 switches::kTraceStartup,
112 switches::kTraceToConsole,
113 switches::kV,
114 switches::kVModule,
115 #if defined(OS_MACOSX)
116 switches::kDisableRemoteCoreAnimation,
117 switches::kDisableNSCGLSurfaceApi,
118 switches::kForceNSCGLSurfaceApi,
119 switches::kEnableSandboxLogging,
120 #endif
121 #if defined(USE_AURA)
122 switches::kUIPrioritizeInGpuProcess,
123 #endif
124 #if defined(USE_OZONE)
125 switches::kOzonePlatform,
126 switches::kOzoneUseSurfaceless,
127 #endif
128 #if defined(USE_X11) && !defined(OS_CHROMEOS)
129 switches::kX11Display,
130 #endif
133 enum GPUProcessLifetimeEvent {
134 LAUNCHED,
135 DIED_FIRST_TIME,
136 DIED_SECOND_TIME,
137 DIED_THIRD_TIME,
138 DIED_FOURTH_TIME,
139 GPU_PROCESS_LIFETIME_EVENT_MAX = 100
142 // Indexed by GpuProcessKind. There is one of each kind maximum. This array may
143 // only be accessed from the IO thread.
144 GpuProcessHost* g_gpu_process_hosts[GpuProcessHost::GPU_PROCESS_KIND_COUNT];
147 void SendGpuProcessMessage(GpuProcessHost::GpuProcessKind kind,
148 CauseForGpuLaunch cause,
149 IPC::Message* message) {
150 GpuProcessHost* host = GpuProcessHost::Get(kind, cause);
151 if (host) {
152 host->Send(message);
153 } else {
154 delete message;
158 // NOTE: changes to this class need to be reviewed by the security team.
159 class GpuSandboxedProcessLauncherDelegate
160 : public SandboxedProcessLauncherDelegate {
161 public:
162 GpuSandboxedProcessLauncherDelegate(base::CommandLine* cmd_line,
163 ChildProcessHost* host)
164 #if defined(OS_WIN)
165 : cmd_line_(cmd_line) {}
166 #elif defined(OS_POSIX)
167 : ipc_fd_(host->TakeClientFileDescriptor()) {}
168 #endif
170 ~GpuSandboxedProcessLauncherDelegate() override {}
172 #if defined(OS_WIN)
173 bool ShouldSandbox() override {
174 bool sandbox = !cmd_line_->HasSwitch(switches::kDisableGpuSandbox);
175 if(! sandbox) {
176 DVLOG(1) << "GPU sandbox is disabled";
178 return sandbox;
181 void PreSandbox(bool* disable_default_policy,
182 base::FilePath* exposed_dir) override {
183 *disable_default_policy = true;
186 // For the GPU process we gotten as far as USER_LIMITED. The next level
187 // which is USER_RESTRICTED breaks both the DirectX backend and the OpenGL
188 // backend. Note that the GPU process is connected to the interactive
189 // desktop.
190 void PreSpawnTarget(sandbox::TargetPolicy* policy, bool* success) override {
191 if (base::win::GetVersion() > base::win::VERSION_XP) {
192 if (cmd_line_->GetSwitchValueASCII(switches::kUseGL) ==
193 gfx::kGLImplementationDesktopName) {
194 // Open GL path.
195 policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
196 sandbox::USER_LIMITED);
197 SetJobLevel(*cmd_line_, sandbox::JOB_UNPROTECTED, 0, policy);
198 policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
199 } else {
200 policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
201 sandbox::USER_LIMITED);
203 // UI restrictions break when we access Windows from outside our job.
204 // However, we don't want a proxy window in this process because it can
205 // introduce deadlocks where the renderer blocks on the gpu, which in
206 // turn blocks on the browser UI thread. So, instead we forgo a window
207 // message pump entirely and just add job restrictions to prevent child
208 // processes.
209 SetJobLevel(*cmd_line_,
210 sandbox::JOB_LIMITED_USER,
211 JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS |
212 JOB_OBJECT_UILIMIT_DESKTOP |
213 JOB_OBJECT_UILIMIT_EXITWINDOWS |
214 JOB_OBJECT_UILIMIT_DISPLAYSETTINGS,
215 policy);
217 policy->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
219 } else {
220 SetJobLevel(*cmd_line_, sandbox::JOB_UNPROTECTED, 0, policy);
221 policy->SetTokenLevel(sandbox::USER_UNPROTECTED,
222 sandbox::USER_LIMITED);
225 // Allow the server side of GPU sockets, which are pipes that have
226 // the "chrome.gpu" namespace and an arbitrary suffix.
227 sandbox::ResultCode result = policy->AddRule(
228 sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
229 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
230 L"\\\\.\\pipe\\chrome.gpu.*");
231 if (result != sandbox::SBOX_ALL_OK) {
232 *success = false;
233 return;
236 // Block this DLL even if it is not loaded by the browser process.
237 policy->AddDllToUnload(L"cmsetac.dll");
239 #ifdef USE_AURA
240 // GPU also needs to add sections to the browser for aura
241 // TODO(jschuh): refactor the GPU channel to remove this. crbug.com/128786
242 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
243 sandbox::TargetPolicy::HANDLES_DUP_BROKER,
244 L"Section");
245 if (result != sandbox::SBOX_ALL_OK) {
246 *success = false;
247 return;
249 #endif
251 if (cmd_line_->HasSwitch(switches::kEnableLogging)) {
252 base::string16 log_file_path = logging::GetLogFileFullPath();
253 if (!log_file_path.empty()) {
254 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
255 sandbox::TargetPolicy::FILES_ALLOW_ANY,
256 log_file_path.c_str());
257 if (result != sandbox::SBOX_ALL_OK) {
258 *success = false;
259 return;
264 #elif defined(OS_POSIX)
266 base::ScopedFD TakeIpcFd() override { return ipc_fd_.Pass(); }
267 #endif // OS_WIN
269 SandboxType GetSandboxType() override {
270 return SANDBOX_TYPE_GPU;
273 private:
274 #if defined(OS_WIN)
275 base::CommandLine* cmd_line_;
276 #elif defined(OS_POSIX)
277 base::ScopedFD ipc_fd_;
278 #endif // OS_WIN
281 } // anonymous namespace
283 // static
284 bool GpuProcessHost::ValidateHost(GpuProcessHost* host) {
285 // The Gpu process is invalid if it's not using SwiftShader, the card is
286 // blacklisted, and we can kill it and start over.
287 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
288 switches::kSingleProcess) ||
289 base::CommandLine::ForCurrentProcess()->HasSwitch(
290 switches::kInProcessGPU) ||
291 (host->valid_ &&
292 (host->swiftshader_rendering_ ||
293 !GpuDataManagerImpl::GetInstance()->ShouldUseSwiftShader()))) {
294 return true;
297 host->ForceShutdown();
298 return false;
301 // static
302 GpuProcessHost* GpuProcessHost::Get(GpuProcessKind kind,
303 CauseForGpuLaunch cause) {
304 DCHECK_CURRENTLY_ON(BrowserThread::IO);
306 // Don't grant further access to GPU if it is not allowed.
307 GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
308 DCHECK(gpu_data_manager);
309 if (!gpu_data_manager->GpuAccessAllowed(NULL))
310 return NULL;
312 if (g_gpu_process_hosts[kind] && ValidateHost(g_gpu_process_hosts[kind]))
313 return g_gpu_process_hosts[kind];
315 if (cause == CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH)
316 return NULL;
318 static int last_host_id = 0;
319 int host_id;
320 host_id = ++last_host_id;
322 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLaunchCause",
323 cause,
324 CAUSE_FOR_GPU_LAUNCH_MAX_ENUM);
326 GpuProcessHost* host = new GpuProcessHost(host_id, kind);
327 if (host->Init())
328 return host;
330 delete host;
331 return NULL;
334 // static
335 void GpuProcessHost::GetProcessHandles(
336 const GpuDataManager::GetGpuProcessHandlesCallback& callback) {
337 if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
338 BrowserThread::PostTask(
339 BrowserThread::IO,
340 FROM_HERE,
341 base::Bind(&GpuProcessHost::GetProcessHandles, callback));
342 return;
344 std::list<base::ProcessHandle> handles;
345 for (size_t i = 0; i < arraysize(g_gpu_process_hosts); ++i) {
346 // TODO(rvargas) crbug/417532: don't store ProcessHandles!.
347 GpuProcessHost* host = g_gpu_process_hosts[i];
348 if (host && ValidateHost(host))
349 handles.push_back(host->process_->GetProcess().Handle());
351 BrowserThread::PostTask(
352 BrowserThread::UI,
353 FROM_HERE,
354 base::Bind(callback, handles));
357 // static
358 void GpuProcessHost::SendOnIO(GpuProcessKind kind,
359 CauseForGpuLaunch cause,
360 IPC::Message* message) {
361 if (!BrowserThread::PostTask(
362 BrowserThread::IO, FROM_HERE,
363 base::Bind(
364 &SendGpuProcessMessage, kind, cause, message))) {
365 delete message;
369 GpuMainThreadFactoryFunction g_gpu_main_thread_factory = NULL;
371 void GpuProcessHost::RegisterGpuMainThreadFactory(
372 GpuMainThreadFactoryFunction create) {
373 g_gpu_main_thread_factory = create;
376 // static
377 GpuProcessHost* GpuProcessHost::FromID(int host_id) {
378 DCHECK_CURRENTLY_ON(BrowserThread::IO);
380 for (int i = 0; i < GPU_PROCESS_KIND_COUNT; ++i) {
381 GpuProcessHost* host = g_gpu_process_hosts[i];
382 if (host && host->host_id_ == host_id && ValidateHost(host))
383 return host;
386 return NULL;
389 GpuProcessHost::GpuProcessHost(int host_id, GpuProcessKind kind)
390 : host_id_(host_id),
391 valid_(true),
392 in_process_(false),
393 swiftshader_rendering_(false),
394 kind_(kind),
395 process_launched_(false),
396 initialized_(false),
397 gpu_crash_recorded_(false),
398 uma_memory_stats_received_(false) {
399 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
400 switches::kSingleProcess) ||
401 base::CommandLine::ForCurrentProcess()->HasSwitch(
402 switches::kInProcessGPU)) {
403 in_process_ = true;
406 // If the 'single GPU process' policy ever changes, we still want to maintain
407 // it for 'gpu thread' mode and only create one instance of host and thread.
408 DCHECK(!in_process_ || g_gpu_process_hosts[kind] == NULL);
410 g_gpu_process_hosts[kind] = this;
412 // Post a task to create the corresponding GpuProcessHostUIShim. The
413 // GpuProcessHostUIShim will be destroyed if either the browser exits,
414 // in which case it calls GpuProcessHostUIShim::DestroyAll, or the
415 // GpuProcessHost is destroyed, which happens when the corresponding GPU
416 // process terminates or fails to launch.
417 BrowserThread::PostTask(
418 BrowserThread::UI,
419 FROM_HERE,
420 base::Bind(base::IgnoreResult(&GpuProcessHostUIShim::Create), host_id));
422 process_.reset(new BrowserChildProcessHostImpl(PROCESS_TYPE_GPU, this));
425 GpuProcessHost::~GpuProcessHost() {
426 DCHECK(CalledOnValidThread());
428 SendOutstandingReplies();
430 RecordProcessCrash();
432 // In case we never started, clean up.
433 while (!queued_messages_.empty()) {
434 delete queued_messages_.front();
435 queued_messages_.pop();
438 #if defined(OS_MACOSX) && !defined(OS_IOS)
439 if (!io_surface_manager_token_.IsZero()) {
440 BrowserIOSurfaceManager::GetInstance()->InvalidateGpuProcessToken();
441 io_surface_manager_token_.SetZero();
443 #endif
445 // This is only called on the IO thread so no race against the constructor
446 // for another GpuProcessHost.
447 if (g_gpu_process_hosts[kind_] == this)
448 g_gpu_process_hosts[kind_] = NULL;
450 // If there are any remaining offscreen contexts at the point the
451 // GPU process exits, assume something went wrong, and block their
452 // URLs from accessing client 3D APIs without prompting.
453 BlockLiveOffscreenContexts();
455 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitSurfaceCount",
456 GpuSurfaceTracker::Get()->GetSurfaceCount());
457 UMA_HISTOGRAM_BOOLEAN("GPU.AtExitReceivedMemoryStats",
458 uma_memory_stats_received_);
460 if (uma_memory_stats_received_) {
461 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitManagedMemoryClientCount",
462 uma_memory_stats_.client_count);
463 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitContextGroupCount",
464 uma_memory_stats_.context_group_count);
465 UMA_HISTOGRAM_CUSTOM_COUNTS(
466 "GPU.AtExitMBytesAllocated",
467 uma_memory_stats_.bytes_allocated_current / 1024 / 1024, 1, 2000, 50);
468 UMA_HISTOGRAM_CUSTOM_COUNTS(
469 "GPU.AtExitMBytesAllocatedMax",
470 uma_memory_stats_.bytes_allocated_max / 1024 / 1024, 1, 2000, 50);
471 UMA_HISTOGRAM_CUSTOM_COUNTS(
472 "GPU.AtExitMBytesLimit",
473 uma_memory_stats_.bytes_limit / 1024 / 1024, 1, 2000, 50);
476 std::string message;
477 if (!in_process_) {
478 int exit_code;
479 base::TerminationStatus status = process_->GetTerminationStatus(
480 false /* known_dead */, &exit_code);
481 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessTerminationStatus",
482 status,
483 base::TERMINATION_STATUS_MAX_ENUM);
485 if (status == base::TERMINATION_STATUS_NORMAL_TERMINATION ||
486 status == base::TERMINATION_STATUS_ABNORMAL_TERMINATION) {
487 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessExitCode",
488 exit_code,
489 RESULT_CODE_LAST_CODE);
492 switch (status) {
493 case base::TERMINATION_STATUS_NORMAL_TERMINATION:
494 message = "The GPU process exited normally. Everything is okay.";
495 break;
496 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
497 message = base::StringPrintf(
498 "The GPU process exited with code %d.",
499 exit_code);
500 break;
501 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED:
502 message = "You killed the GPU process! Why?";
503 break;
504 #if defined(OS_CHROMEOS)
505 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM:
506 message = "The GUP process was killed due to out of memory.";
507 break;
508 #endif
509 case base::TERMINATION_STATUS_PROCESS_CRASHED:
510 message = "The GPU process crashed!";
511 break;
512 default:
513 break;
517 BrowserThread::PostTask(BrowserThread::UI,
518 FROM_HERE,
519 base::Bind(&GpuProcessHostUIShim::Destroy,
520 host_id_,
521 message));
524 bool GpuProcessHost::Init() {
525 init_start_time_ = base::TimeTicks::Now();
527 TRACE_EVENT_INSTANT0("gpu", "LaunchGpuProcess", TRACE_EVENT_SCOPE_THREAD);
529 std::string channel_id = process_->GetHost()->CreateChannel();
530 if (channel_id.empty())
531 return false;
533 if (in_process_) {
534 DCHECK_CURRENTLY_ON(BrowserThread::IO);
535 DCHECK(g_gpu_main_thread_factory);
536 in_process_gpu_thread_.reset(
537 g_gpu_main_thread_factory(InProcessChildThreadParams(
538 channel_id, base::MessageLoop::current()->task_runner())));
539 base::Thread::Options options;
540 #if defined(OS_WIN)
541 // WGL needs to create its own window and pump messages on it.
542 options.message_loop_type = base::MessageLoop::TYPE_UI;
543 #endif
544 in_process_gpu_thread_->StartWithOptions(options);
546 OnProcessLaunched(); // Fake a callback that the process is ready.
547 } else if (!LaunchGpuProcess(channel_id)) {
548 return false;
551 if (!Send(new GpuMsg_Initialize()))
552 return false;
554 #if defined(OS_MACOSX) && !defined(OS_IOS)
555 io_surface_manager_token_ =
556 BrowserIOSurfaceManager::GetInstance()->GenerateGpuProcessToken();
557 // Note: A valid IOSurface manager token needs to be sent to the Gpu process
558 // before any GpuMemoryBuffer allocation requests can be sent.
559 Send(new ChildProcessMsg_SetIOSurfaceManagerToken(io_surface_manager_token_));
560 #endif
562 return true;
565 void GpuProcessHost::RouteOnUIThread(const IPC::Message& message) {
566 BrowserThread::PostTask(
567 BrowserThread::UI,
568 FROM_HERE,
569 base::Bind(&RouteToGpuProcessHostUIShimTask, host_id_, message));
572 bool GpuProcessHost::Send(IPC::Message* msg) {
573 DCHECK(CalledOnValidThread());
574 if (process_->GetHost()->IsChannelOpening()) {
575 queued_messages_.push(msg);
576 return true;
579 bool result = process_->Send(msg);
580 if (!result) {
581 // Channel is hosed, but we may not get destroyed for a while. Send
582 // outstanding channel creation failures now so that the caller can restart
583 // with a new process/channel without waiting.
584 SendOutstandingReplies();
586 return result;
589 void GpuProcessHost::AddFilter(IPC::MessageFilter* filter) {
590 DCHECK(CalledOnValidThread());
591 process_->GetHost()->AddFilter(filter);
594 bool GpuProcessHost::OnMessageReceived(const IPC::Message& message) {
595 DCHECK(CalledOnValidThread());
596 IPC_BEGIN_MESSAGE_MAP(GpuProcessHost, message)
597 IPC_MESSAGE_HANDLER(GpuHostMsg_Initialized, OnInitialized)
598 IPC_MESSAGE_HANDLER(GpuHostMsg_ChannelEstablished, OnChannelEstablished)
599 IPC_MESSAGE_HANDLER(GpuHostMsg_CommandBufferCreated, OnCommandBufferCreated)
600 IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyCommandBuffer, OnDestroyCommandBuffer)
601 IPC_MESSAGE_HANDLER(GpuHostMsg_GpuMemoryBufferCreated,
602 OnGpuMemoryBufferCreated)
603 IPC_MESSAGE_HANDLER(GpuHostMsg_DidCreateOffscreenContext,
604 OnDidCreateOffscreenContext)
605 IPC_MESSAGE_HANDLER(GpuHostMsg_DidLoseContext, OnDidLoseContext)
606 IPC_MESSAGE_HANDLER(GpuHostMsg_DidDestroyOffscreenContext,
607 OnDidDestroyOffscreenContext)
608 IPC_MESSAGE_HANDLER(GpuHostMsg_GpuMemoryUmaStats,
609 OnGpuMemoryUmaStatsReceived)
610 #if defined(OS_MACOSX)
611 IPC_MESSAGE_HANDLER_GENERIC(GpuHostMsg_AcceleratedSurfaceBuffersSwapped,
612 OnAcceleratedSurfaceBuffersSwapped(message))
613 #endif
614 IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyChannel,
615 OnDestroyChannel)
616 IPC_MESSAGE_HANDLER(GpuHostMsg_CacheShader,
617 OnCacheShader)
619 IPC_MESSAGE_UNHANDLED(RouteOnUIThread(message))
620 IPC_END_MESSAGE_MAP()
622 return true;
625 void GpuProcessHost::OnChannelConnected(int32 peer_pid) {
626 TRACE_EVENT0("gpu", "GpuProcessHost::OnChannelConnected");
628 while (!queued_messages_.empty()) {
629 Send(queued_messages_.front());
630 queued_messages_.pop();
634 void GpuProcessHost::EstablishGpuChannel(
635 int client_id,
636 bool share_context,
637 bool allow_future_sync_points,
638 const EstablishChannelCallback& callback) {
639 DCHECK(CalledOnValidThread());
640 TRACE_EVENT0("gpu", "GpuProcessHost::EstablishGpuChannel");
642 // If GPU features are already blacklisted, no need to establish the channel.
643 if (!GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL)) {
644 DVLOG(1) << "GPU blacklisted, refusing to open a GPU channel.";
645 callback.Run(IPC::ChannelHandle(), gpu::GPUInfo());
646 return;
649 if (Send(new GpuMsg_EstablishChannel(
650 client_id, share_context, allow_future_sync_points))) {
651 channel_requests_.push(callback);
652 } else {
653 DVLOG(1) << "Failed to send GpuMsg_EstablishChannel.";
654 callback.Run(IPC::ChannelHandle(), gpu::GPUInfo());
657 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
658 switches::kDisableGpuShaderDiskCache)) {
659 CreateChannelCache(client_id);
663 void GpuProcessHost::CreateViewCommandBuffer(
664 const gfx::GLSurfaceHandle& compositing_surface,
665 int surface_id,
666 int client_id,
667 const GPUCreateCommandBufferConfig& init_params,
668 int route_id,
669 const CreateCommandBufferCallback& callback) {
670 TRACE_EVENT0("gpu", "GpuProcessHost::CreateViewCommandBuffer");
672 DCHECK(CalledOnValidThread());
674 if (!compositing_surface.is_null() &&
675 Send(new GpuMsg_CreateViewCommandBuffer(
676 compositing_surface, surface_id, client_id, init_params, route_id))) {
677 create_command_buffer_requests_.push(callback);
678 surface_refs_.insert(std::make_pair(surface_id,
679 GpuSurfaceTracker::GetInstance()->GetSurfaceRefForSurface(surface_id)));
680 } else {
681 // Could distinguish here between compositing_surface being NULL
682 // and Send failing, if desired.
683 callback.Run(CREATE_COMMAND_BUFFER_FAILED_AND_CHANNEL_LOST);
687 void GpuProcessHost::CreateGpuMemoryBuffer(
688 gfx::GpuMemoryBufferId id,
689 const gfx::Size& size,
690 gfx::GpuMemoryBuffer::Format format,
691 gfx::GpuMemoryBuffer::Usage usage,
692 int client_id,
693 int32 surface_id,
694 const CreateGpuMemoryBufferCallback& callback) {
695 TRACE_EVENT0("gpu", "GpuProcessHost::CreateGpuMemoryBuffer");
697 DCHECK(CalledOnValidThread());
699 GpuMsg_CreateGpuMemoryBuffer_Params params;
700 params.id = id;
701 params.size = size;
702 params.format = format;
703 params.usage = usage;
704 params.client_id = client_id;
705 params.surface_handle =
706 GpuSurfaceTracker::GetInstance()->GetSurfaceHandle(surface_id).handle;
707 if (Send(new GpuMsg_CreateGpuMemoryBuffer(params))) {
708 create_gpu_memory_buffer_requests_.push(callback);
709 create_gpu_memory_buffer_surface_refs_.push(surface_id);
710 if (surface_id) {
711 surface_refs_.insert(std::make_pair(
712 surface_id, GpuSurfaceTracker::GetInstance()->GetSurfaceRefForSurface(
713 surface_id)));
715 } else {
716 callback.Run(gfx::GpuMemoryBufferHandle());
720 void GpuProcessHost::DestroyGpuMemoryBuffer(gfx::GpuMemoryBufferId id,
721 int client_id,
722 int sync_point) {
723 TRACE_EVENT0("gpu", "GpuProcessHost::DestroyGpuMemoryBuffer");
725 DCHECK(CalledOnValidThread());
727 Send(new GpuMsg_DestroyGpuMemoryBuffer(id, client_id, sync_point));
730 void GpuProcessHost::OnInitialized(bool result, const gpu::GPUInfo& gpu_info) {
731 UMA_HISTOGRAM_BOOLEAN("GPU.GPUProcessInitialized", result);
732 initialized_ = result;
734 if (!initialized_)
735 GpuDataManagerImpl::GetInstance()->OnGpuProcessInitFailure();
736 else if (!in_process_)
737 GpuDataManagerImpl::GetInstance()->UpdateGpuInfo(gpu_info);
740 void GpuProcessHost::OnChannelEstablished(
741 const IPC::ChannelHandle& channel_handle) {
742 TRACE_EVENT0("gpu", "GpuProcessHost::OnChannelEstablished");
744 if (channel_requests_.empty()) {
745 // This happens when GPU process is compromised.
746 RouteOnUIThread(GpuHostMsg_OnLogMessage(
747 logging::LOG_WARNING,
748 "WARNING",
749 "Received a ChannelEstablished message but no requests in queue."));
750 return;
752 EstablishChannelCallback callback = channel_requests_.front();
753 channel_requests_.pop();
755 // Currently if any of the GPU features are blacklisted, we don't establish a
756 // GPU channel.
757 if (!channel_handle.name.empty() &&
758 !GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL)) {
759 Send(new GpuMsg_CloseChannel(channel_handle));
760 callback.Run(IPC::ChannelHandle(), gpu::GPUInfo());
761 RouteOnUIThread(GpuHostMsg_OnLogMessage(
762 logging::LOG_WARNING,
763 "WARNING",
764 "Hardware acceleration is unavailable."));
765 return;
768 callback.Run(channel_handle,
769 GpuDataManagerImpl::GetInstance()->GetGPUInfo());
772 void GpuProcessHost::OnCommandBufferCreated(CreateCommandBufferResult result) {
773 TRACE_EVENT0("gpu", "GpuProcessHost::OnCommandBufferCreated");
775 if (create_command_buffer_requests_.empty())
776 return;
778 CreateCommandBufferCallback callback =
779 create_command_buffer_requests_.front();
780 create_command_buffer_requests_.pop();
781 callback.Run(result);
784 void GpuProcessHost::OnDestroyCommandBuffer(int32 surface_id) {
785 TRACE_EVENT0("gpu", "GpuProcessHost::OnDestroyCommandBuffer");
786 SurfaceRefMap::iterator it = surface_refs_.find(surface_id);
787 if (it != surface_refs_.end()) {
788 surface_refs_.erase(it);
792 void GpuProcessHost::OnGpuMemoryBufferCreated(
793 const gfx::GpuMemoryBufferHandle& handle) {
794 TRACE_EVENT0("gpu", "GpuProcessHost::OnGpuMemoryBufferCreated");
796 if (create_gpu_memory_buffer_requests_.empty())
797 return;
799 CreateGpuMemoryBufferCallback callback =
800 create_gpu_memory_buffer_requests_.front();
801 create_gpu_memory_buffer_requests_.pop();
802 callback.Run(handle);
804 int32 surface_id = create_gpu_memory_buffer_surface_refs_.front();
805 create_gpu_memory_buffer_surface_refs_.pop();
806 SurfaceRefMap::iterator it = surface_refs_.find(surface_id);
807 if (it != surface_refs_.end()) {
808 surface_refs_.erase(it);
812 void GpuProcessHost::OnDidCreateOffscreenContext(const GURL& url) {
813 urls_with_live_offscreen_contexts_.insert(url);
816 void GpuProcessHost::OnDidLoseContext(bool offscreen,
817 gpu::error::ContextLostReason reason,
818 const GURL& url) {
819 // TODO(kbr): would be nice to see the "offscreen" flag too.
820 TRACE_EVENT2("gpu", "GpuProcessHost::OnDidLoseContext",
821 "reason", reason,
822 "url",
823 url.possibly_invalid_spec());
825 if (!offscreen || url.is_empty()) {
826 // Assume that the loss of the compositor's or accelerated canvas'
827 // context is a serious event and blame the loss on all live
828 // offscreen contexts. This more robustly handles situations where
829 // the GPU process may not actually detect the context loss in the
830 // offscreen context.
831 BlockLiveOffscreenContexts();
832 return;
835 GpuDataManagerImpl::DomainGuilt guilt;
836 switch (reason) {
837 case gpu::error::kGuilty:
838 guilt = GpuDataManagerImpl::DOMAIN_GUILT_KNOWN;
839 break;
840 case gpu::error::kUnknown:
841 guilt = GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN;
842 break;
843 case gpu::error::kInnocent:
844 return;
845 default:
846 NOTREACHED();
847 return;
850 GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(url, guilt);
853 void GpuProcessHost::OnDidDestroyOffscreenContext(const GURL& url) {
854 urls_with_live_offscreen_contexts_.erase(url);
857 void GpuProcessHost::OnGpuMemoryUmaStatsReceived(
858 const GPUMemoryUmaStats& stats) {
859 TRACE_EVENT0("gpu", "GpuProcessHost::OnGpuMemoryUmaStatsReceived");
860 uma_memory_stats_received_ = true;
861 uma_memory_stats_ = stats;
864 #if defined(OS_MACOSX)
865 void GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped(
866 const IPC::Message& message) {
867 RenderWidgetResizeHelper::Get()->PostGpuProcessMsg(host_id_, message);
869 #endif
871 void GpuProcessHost::OnProcessLaunched() {
872 UMA_HISTOGRAM_TIMES("GPU.GPUProcessLaunchTime",
873 base::TimeTicks::Now() - init_start_time_);
876 void GpuProcessHost::OnProcessCrashed(int exit_code) {
877 SendOutstandingReplies();
878 RecordProcessCrash();
879 GpuDataManagerImpl::GetInstance()->ProcessCrashed(
880 process_->GetTerminationStatus(true /* known_dead */, NULL));
883 GpuProcessHost::GpuProcessKind GpuProcessHost::kind() {
884 return kind_;
887 void GpuProcessHost::ForceShutdown() {
888 // This is only called on the IO thread so no race against the constructor
889 // for another GpuProcessHost.
890 if (g_gpu_process_hosts[kind_] == this)
891 g_gpu_process_hosts[kind_] = NULL;
893 #if defined(OS_MACOSX) && !defined(OS_IOS)
894 if (!io_surface_manager_token_.IsZero()) {
895 BrowserIOSurfaceManager::GetInstance()->InvalidateGpuProcessToken();
896 io_surface_manager_token_.SetZero();
898 #endif
900 process_->ForceShutdown();
903 void GpuProcessHost::BeginFrameSubscription(
904 int surface_id,
905 base::WeakPtr<RenderWidgetHostViewFrameSubscriber> subscriber) {
906 frame_subscribers_[surface_id] = subscriber;
909 void GpuProcessHost::EndFrameSubscription(int surface_id) {
910 frame_subscribers_.erase(surface_id);
913 bool GpuProcessHost::LaunchGpuProcess(const std::string& channel_id) {
914 if (!(gpu_enabled_ &&
915 GpuDataManagerImpl::GetInstance()->ShouldUseSwiftShader()) &&
916 !hardware_gpu_enabled_) {
917 SendOutstandingReplies();
918 return false;
921 const base::CommandLine& browser_command_line =
922 *base::CommandLine::ForCurrentProcess();
924 base::CommandLine::StringType gpu_launcher =
925 browser_command_line.GetSwitchValueNative(switches::kGpuLauncher);
927 #if defined(OS_ANDROID)
928 // crbug.com/447735. readlink("self/proc/exe") sometimes fails on Android
929 // at startup with EACCES. As a workaround ignore this here, since the
930 // executable name is actually not used or useful anyways.
931 base::CommandLine* cmd_line =
932 new base::CommandLine(base::CommandLine::NO_PROGRAM);
933 #else
934 #if defined(OS_LINUX)
935 int child_flags = gpu_launcher.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
936 ChildProcessHost::CHILD_NORMAL;
937 #else
938 int child_flags = ChildProcessHost::CHILD_NORMAL;
939 #endif
941 base::FilePath exe_path = ChildProcessHost::GetChildPath(child_flags);
942 if (exe_path.empty())
943 return false;
945 base::CommandLine* cmd_line = new base::CommandLine(exe_path);
946 #endif
947 cmd_line->AppendSwitchASCII(switches::kProcessType, switches::kGpuProcess);
948 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
950 if (kind_ == GPU_PROCESS_KIND_UNSANDBOXED)
951 cmd_line->AppendSwitch(switches::kDisableGpuSandbox);
953 // If you want a browser command-line switch passed to the GPU process
954 // you need to add it to |kSwitchNames| at the beginning of this file.
955 cmd_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
956 arraysize(kSwitchNames));
957 cmd_line->CopySwitchesFrom(
958 browser_command_line, switches::kGpuSwitches, switches::kNumGpuSwitches);
959 cmd_line->CopySwitchesFrom(
960 browser_command_line, switches::kGLSwitchesCopiedFromGpuProcessHost,
961 switches::kGLSwitchesCopiedFromGpuProcessHostNumSwitches);
963 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
964 cmd_line, process_->GetData().id);
966 GpuDataManagerImpl::GetInstance()->AppendGpuCommandLine(cmd_line);
968 if (cmd_line->HasSwitch(switches::kUseGL)) {
969 swiftshader_rendering_ =
970 (cmd_line->GetSwitchValueASCII(switches::kUseGL) == "swiftshader");
973 UMA_HISTOGRAM_BOOLEAN("GPU.GPU.GPUProcessSoftwareRendering",
974 swiftshader_rendering_);
976 // If specified, prepend a launcher program to the command line.
977 if (!gpu_launcher.empty())
978 cmd_line->PrependWrapper(gpu_launcher);
980 process_->Launch(
981 new GpuSandboxedProcessLauncherDelegate(cmd_line,
982 process_->GetHost()),
983 cmd_line,
984 true);
985 process_launched_ = true;
987 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
988 LAUNCHED, GPU_PROCESS_LIFETIME_EVENT_MAX);
989 return true;
992 void GpuProcessHost::SendOutstandingReplies() {
993 valid_ = false;
994 // First send empty channel handles for all EstablishChannel requests.
995 while (!channel_requests_.empty()) {
996 EstablishChannelCallback callback = channel_requests_.front();
997 channel_requests_.pop();
998 callback.Run(IPC::ChannelHandle(), gpu::GPUInfo());
1001 while (!create_command_buffer_requests_.empty()) {
1002 CreateCommandBufferCallback callback =
1003 create_command_buffer_requests_.front();
1004 create_command_buffer_requests_.pop();
1005 callback.Run(CREATE_COMMAND_BUFFER_FAILED_AND_CHANNEL_LOST);
1008 while (!create_gpu_memory_buffer_requests_.empty()) {
1009 CreateGpuMemoryBufferCallback callback =
1010 create_gpu_memory_buffer_requests_.front();
1011 create_gpu_memory_buffer_requests_.pop();
1012 callback.Run(gfx::GpuMemoryBufferHandle());
1016 void GpuProcessHost::BlockLiveOffscreenContexts() {
1017 for (std::multiset<GURL>::iterator iter =
1018 urls_with_live_offscreen_contexts_.begin();
1019 iter != urls_with_live_offscreen_contexts_.end(); ++iter) {
1020 GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(
1021 *iter, GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN);
1025 void GpuProcessHost::RecordProcessCrash() {
1026 // Skip if a GPU process crash was already counted.
1027 if (gpu_crash_recorded_)
1028 return;
1030 // Maximum number of times the GPU process is allowed to crash in a session.
1031 // Once this limit is reached, any request to launch the GPU process will
1032 // fail.
1033 const int kGpuMaxCrashCount = 3;
1035 // Last time the GPU process crashed.
1036 static base::Time last_gpu_crash_time;
1038 bool disable_crash_limit = base::CommandLine::ForCurrentProcess()->HasSwitch(
1039 switches::kDisableGpuProcessCrashLimit);
1041 // Ending only acts as a failure if the GPU process was actually started and
1042 // was intended for actual rendering (and not just checking caps or other
1043 // options).
1044 if (process_launched_ && kind_ == GPU_PROCESS_KIND_SANDBOXED) {
1045 gpu_crash_recorded_ = true;
1046 if (swiftshader_rendering_) {
1047 UMA_HISTOGRAM_ENUMERATION("GPU.SwiftShaderLifetimeEvents",
1048 DIED_FIRST_TIME + swiftshader_crash_count_,
1049 GPU_PROCESS_LIFETIME_EVENT_MAX);
1051 if (++swiftshader_crash_count_ >= kGpuMaxCrashCount &&
1052 !disable_crash_limit) {
1053 // SwiftShader is too unstable to use. Disable it for current session.
1054 gpu_enabled_ = false;
1056 } else {
1057 ++gpu_crash_count_;
1058 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
1059 std::min(DIED_FIRST_TIME + gpu_crash_count_,
1060 GPU_PROCESS_LIFETIME_EVENT_MAX - 1),
1061 GPU_PROCESS_LIFETIME_EVENT_MAX);
1063 // Allow about 1 GPU crash per hour to be removed from the crash count,
1064 // so very occasional crashes won't eventually add up and prevent the
1065 // GPU process from launching.
1066 ++gpu_recent_crash_count_;
1067 base::Time current_time = base::Time::Now();
1068 if (crashed_before_) {
1069 int hours_different = (current_time - last_gpu_crash_time).InHours();
1070 gpu_recent_crash_count_ =
1071 std::max(0, gpu_recent_crash_count_ - hours_different);
1074 crashed_before_ = true;
1075 last_gpu_crash_time = current_time;
1077 if ((gpu_recent_crash_count_ >= kGpuMaxCrashCount &&
1078 !disable_crash_limit) ||
1079 !initialized_) {
1080 #if !defined(OS_CHROMEOS)
1081 // The GPU process is too unstable to use. Disable it for current
1082 // session.
1083 hardware_gpu_enabled_ = false;
1084 GpuDataManagerImpl::GetInstance()->DisableHardwareAcceleration();
1085 #endif
1091 std::string GpuProcessHost::GetShaderPrefixKey() {
1092 if (shader_prefix_key_.empty()) {
1093 gpu::GPUInfo info = GpuDataManagerImpl::GetInstance()->GetGPUInfo();
1095 std::string in_str = GetContentClient()->GetProduct() + "-" +
1096 #if defined(OS_ANDROID)
1097 base::android::BuildInfo::GetInstance()->android_build_fp() + "-" +
1098 #endif
1099 info.gl_vendor + "-" + info.gl_renderer + "-" +
1100 info.driver_version + "-" + info.driver_vendor;
1102 base::Base64Encode(base::SHA1HashString(in_str), &shader_prefix_key_);
1105 return shader_prefix_key_;
1108 void GpuProcessHost::LoadedShader(const std::string& key,
1109 const std::string& data) {
1110 std::string prefix = GetShaderPrefixKey();
1111 if (!key.compare(0, prefix.length(), prefix))
1112 Send(new GpuMsg_LoadedShader(data));
1115 void GpuProcessHost::CreateChannelCache(int32 client_id) {
1116 TRACE_EVENT0("gpu", "GpuProcessHost::CreateChannelCache");
1118 scoped_refptr<ShaderDiskCache> cache =
1119 ShaderCacheFactory::GetInstance()->Get(client_id);
1120 if (!cache.get())
1121 return;
1123 cache->set_host_id(host_id_);
1125 client_id_to_shader_cache_[client_id] = cache;
1128 void GpuProcessHost::OnDestroyChannel(int32 client_id) {
1129 TRACE_EVENT0("gpu", "GpuProcessHost::OnDestroyChannel");
1130 client_id_to_shader_cache_.erase(client_id);
1133 void GpuProcessHost::OnCacheShader(int32 client_id,
1134 const std::string& key,
1135 const std::string& shader) {
1136 TRACE_EVENT0("gpu", "GpuProcessHost::OnCacheShader");
1137 ClientIdToShaderCacheMap::iterator iter =
1138 client_id_to_shader_cache_.find(client_id);
1139 // If the cache doesn't exist then this is an off the record profile.
1140 if (iter == client_id_to_shader_cache_.end())
1141 return;
1142 iter->second->Cache(GetShaderPrefixKey() + ":" + key, shader);
1145 } // namespace content