Simplify ChildProcessLauncher
[chromium-blink-merge.git] / content / browser / gpu / gpu_process_host.cc
blobbe1437451b93cfe3bf8cc80ddd54259721a1b88b
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/sandboxed_process_launcher_delegate.h"
39 #include "gpu/command_buffer/service/gpu_switches.h"
40 #include "ipc/ipc_channel_handle.h"
41 #include "ipc/ipc_switches.h"
42 #include "ipc/message_filter.h"
43 #include "media/base/media_switches.h"
44 #include "ui/base/ui_base_switches.h"
45 #include "ui/events/latency_info.h"
46 #include "ui/gl/gl_switches.h"
48 #if defined(OS_WIN)
49 #include "base/win/windows_version.h"
50 #include "content/common/sandbox_win.h"
51 #include "sandbox/win/src/sandbox_policy.h"
52 #include "ui/gfx/switches.h"
53 #endif
55 #if defined(USE_OZONE)
56 #include "ui/ozone/public/ozone_switches.h"
57 #endif
59 #if defined(USE_X11) && !defined(OS_CHROMEOS)
60 #include "ui/gfx/x/x11_switches.h"
61 #endif
63 namespace content {
65 bool GpuProcessHost::gpu_enabled_ = true;
66 bool GpuProcessHost::hardware_gpu_enabled_ = true;
67 int GpuProcessHost::gpu_crash_count_ = 0;
68 int GpuProcessHost::gpu_recent_crash_count_ = 0;
69 bool GpuProcessHost::crashed_before_ = false;
70 int GpuProcessHost::swiftshader_crash_count_ = 0;
72 namespace {
74 // Command-line switches to propagate to the GPU process.
75 static const char* const kSwitchNames[] = {
76 switches::kDisableAcceleratedVideoDecode,
77 switches::kDisableBreakpad,
78 switches::kDisableGpuSandbox,
79 switches::kDisableGpuWatchdog,
80 switches::kDisableLogging,
81 switches::kDisableSeccompFilterSandbox,
82 #if defined(ENABLE_WEBRTC)
83 switches::kDisableWebRtcHWEncoding,
84 #endif
85 switches::kEnableLogging,
86 switches::kEnableShareGroupAsyncTextureUpload,
87 #if defined(OS_CHROMEOS)
88 switches::kDisableVaapiAcceleratedVideoEncode,
89 #endif
90 switches::kGpuStartupDialog,
91 switches::kGpuSandboxAllowSysVShm,
92 switches::kGpuSandboxFailuresFatal,
93 switches::kGpuSandboxStartEarly,
94 switches::kIgnoreResolutionLimitsForAcceleratedVideoDecode,
95 switches::kLoggingLevel,
96 switches::kEnableLowEndDeviceMode,
97 switches::kDisableLowEndDeviceMode,
98 switches::kNoSandbox,
99 switches::kProfilerTiming,
100 switches::kTestGLLib,
101 switches::kTraceStartup,
102 switches::kTraceToConsole,
103 switches::kV,
104 switches::kVModule,
105 #if defined(OS_MACOSX)
106 switches::kDisableRemoteCoreAnimation,
107 switches::kEnableSandboxLogging,
108 #endif
109 #if defined(USE_AURA)
110 switches::kUIPrioritizeInGpuProcess,
111 #endif
112 #if defined(USE_OZONE)
113 switches::kOzonePlatform,
114 switches::kOzoneUseSurfaceless,
115 #endif
116 #if defined(USE_X11) && !defined(OS_CHROMEOS)
117 switches::kX11Display,
118 #endif
121 enum GPUProcessLifetimeEvent {
122 LAUNCHED,
123 DIED_FIRST_TIME,
124 DIED_SECOND_TIME,
125 DIED_THIRD_TIME,
126 DIED_FOURTH_TIME,
127 GPU_PROCESS_LIFETIME_EVENT_MAX = 100
130 // Indexed by GpuProcessKind. There is one of each kind maximum. This array may
131 // only be accessed from the IO thread.
132 GpuProcessHost* g_gpu_process_hosts[GpuProcessHost::GPU_PROCESS_KIND_COUNT];
135 void SendGpuProcessMessage(GpuProcessHost::GpuProcessKind kind,
136 CauseForGpuLaunch cause,
137 IPC::Message* message) {
138 GpuProcessHost* host = GpuProcessHost::Get(kind, cause);
139 if (host) {
140 host->Send(message);
141 } else {
142 delete message;
146 // NOTE: changes to this class need to be reviewed by the security team.
147 class GpuSandboxedProcessLauncherDelegate
148 : public SandboxedProcessLauncherDelegate {
149 public:
150 GpuSandboxedProcessLauncherDelegate(base::CommandLine* cmd_line,
151 ChildProcessHost* host)
152 #if defined(OS_WIN)
153 : cmd_line_(cmd_line) {}
154 #elif defined(OS_POSIX)
155 : ipc_fd_(host->TakeClientFileDescriptor()) {}
156 #endif
158 ~GpuSandboxedProcessLauncherDelegate() override {}
160 #if defined(OS_WIN)
161 virtual bool ShouldSandbox() override {
162 bool sandbox = !cmd_line_->HasSwitch(switches::kDisableGpuSandbox);
163 if(! sandbox) {
164 DVLOG(1) << "GPU sandbox is disabled";
166 return sandbox;
169 virtual void PreSandbox(bool* disable_default_policy,
170 base::FilePath* exposed_dir) override {
171 *disable_default_policy = true;
174 // For the GPU process we gotten as far as USER_LIMITED. The next level
175 // which is USER_RESTRICTED breaks both the DirectX backend and the OpenGL
176 // backend. Note that the GPU process is connected to the interactive
177 // desktop.
178 virtual void PreSpawnTarget(sandbox::TargetPolicy* policy,
179 bool* success) {
180 if (base::win::GetVersion() > base::win::VERSION_XP) {
181 if (cmd_line_->GetSwitchValueASCII(switches::kUseGL) ==
182 gfx::kGLImplementationDesktopName) {
183 // Open GL path.
184 policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
185 sandbox::USER_LIMITED);
186 SetJobLevel(*cmd_line_, sandbox::JOB_UNPROTECTED, 0, policy);
187 policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
188 } else {
189 policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
190 sandbox::USER_LIMITED);
192 // UI restrictions break when we access Windows from outside our job.
193 // However, we don't want a proxy window in this process because it can
194 // introduce deadlocks where the renderer blocks on the gpu, which in
195 // turn blocks on the browser UI thread. So, instead we forgo a window
196 // message pump entirely and just add job restrictions to prevent child
197 // processes.
198 SetJobLevel(*cmd_line_,
199 sandbox::JOB_LIMITED_USER,
200 JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS |
201 JOB_OBJECT_UILIMIT_DESKTOP |
202 JOB_OBJECT_UILIMIT_EXITWINDOWS |
203 JOB_OBJECT_UILIMIT_DISPLAYSETTINGS,
204 policy);
206 policy->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
208 } else {
209 SetJobLevel(*cmd_line_, sandbox::JOB_UNPROTECTED, 0, policy);
210 policy->SetTokenLevel(sandbox::USER_UNPROTECTED,
211 sandbox::USER_LIMITED);
214 // Allow the server side of GPU sockets, which are pipes that have
215 // the "chrome.gpu" namespace and an arbitrary suffix.
216 sandbox::ResultCode result = policy->AddRule(
217 sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
218 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
219 L"\\\\.\\pipe\\chrome.gpu.*");
220 if (result != sandbox::SBOX_ALL_OK) {
221 *success = false;
222 return;
225 // Block this DLL even if it is not loaded by the browser process.
226 policy->AddDllToUnload(L"cmsetac.dll");
228 #ifdef USE_AURA
229 // GPU also needs to add sections to the browser for aura
230 // TODO(jschuh): refactor the GPU channel to remove this. crbug.com/128786
231 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
232 sandbox::TargetPolicy::HANDLES_DUP_BROKER,
233 L"Section");
234 if (result != sandbox::SBOX_ALL_OK) {
235 *success = false;
236 return;
238 #endif
240 if (cmd_line_->HasSwitch(switches::kEnableLogging)) {
241 base::string16 log_file_path = logging::GetLogFileFullPath();
242 if (!log_file_path.empty()) {
243 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
244 sandbox::TargetPolicy::FILES_ALLOW_ANY,
245 log_file_path.c_str());
246 if (result != sandbox::SBOX_ALL_OK) {
247 *success = false;
248 return;
253 #elif defined(OS_POSIX)
255 base::ScopedFD TakeIpcFd() override { return ipc_fd_.Pass(); }
256 #endif // OS_WIN
258 private:
259 #if defined(OS_WIN)
260 base::CommandLine* cmd_line_;
261 #elif defined(OS_POSIX)
262 base::ScopedFD ipc_fd_;
263 #endif // OS_WIN
266 } // anonymous namespace
268 // static
269 bool GpuProcessHost::ValidateHost(GpuProcessHost* host) {
270 // The Gpu process is invalid if it's not using SwiftShader, the card is
271 // blacklisted, and we can kill it and start over.
272 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
273 switches::kSingleProcess) ||
274 base::CommandLine::ForCurrentProcess()->HasSwitch(
275 switches::kInProcessGPU) ||
276 (host->valid_ &&
277 (host->swiftshader_rendering_ ||
278 !GpuDataManagerImpl::GetInstance()->ShouldUseSwiftShader()))) {
279 return true;
282 host->ForceShutdown();
283 return false;
286 // static
287 GpuProcessHost* GpuProcessHost::Get(GpuProcessKind kind,
288 CauseForGpuLaunch cause) {
289 DCHECK_CURRENTLY_ON(BrowserThread::IO);
291 // Don't grant further access to GPU if it is not allowed.
292 GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
293 DCHECK(gpu_data_manager);
294 if (!gpu_data_manager->GpuAccessAllowed(NULL))
295 return NULL;
297 if (g_gpu_process_hosts[kind] && ValidateHost(g_gpu_process_hosts[kind]))
298 return g_gpu_process_hosts[kind];
300 if (cause == CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH)
301 return NULL;
303 static int last_host_id = 0;
304 int host_id;
305 host_id = ++last_host_id;
307 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLaunchCause",
308 cause,
309 CAUSE_FOR_GPU_LAUNCH_MAX_ENUM);
311 GpuProcessHost* host = new GpuProcessHost(host_id, kind);
312 if (host->Init())
313 return host;
315 delete host;
316 return NULL;
319 // static
320 void GpuProcessHost::GetProcessHandles(
321 const GpuDataManager::GetGpuProcessHandlesCallback& callback) {
322 if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
323 BrowserThread::PostTask(
324 BrowserThread::IO,
325 FROM_HERE,
326 base::Bind(&GpuProcessHost::GetProcessHandles, callback));
327 return;
329 std::list<base::ProcessHandle> handles;
330 for (size_t i = 0; i < arraysize(g_gpu_process_hosts); ++i) {
331 // TODO(rvargas) crbug/417532: don't store ProcessHandles!.
332 GpuProcessHost* host = g_gpu_process_hosts[i];
333 if (host && ValidateHost(host))
334 handles.push_back(host->process_->GetProcess().Handle());
336 BrowserThread::PostTask(
337 BrowserThread::UI,
338 FROM_HERE,
339 base::Bind(callback, handles));
342 // static
343 void GpuProcessHost::SendOnIO(GpuProcessKind kind,
344 CauseForGpuLaunch cause,
345 IPC::Message* message) {
346 if (!BrowserThread::PostTask(
347 BrowserThread::IO, FROM_HERE,
348 base::Bind(
349 &SendGpuProcessMessage, kind, cause, message))) {
350 delete message;
354 GpuMainThreadFactoryFunction g_gpu_main_thread_factory = NULL;
356 void GpuProcessHost::RegisterGpuMainThreadFactory(
357 GpuMainThreadFactoryFunction create) {
358 g_gpu_main_thread_factory = create;
361 // static
362 GpuProcessHost* GpuProcessHost::FromID(int host_id) {
363 DCHECK_CURRENTLY_ON(BrowserThread::IO);
365 for (int i = 0; i < GPU_PROCESS_KIND_COUNT; ++i) {
366 GpuProcessHost* host = g_gpu_process_hosts[i];
367 if (host && host->host_id_ == host_id && ValidateHost(host))
368 return host;
371 return NULL;
374 GpuProcessHost::GpuProcessHost(int host_id, GpuProcessKind kind)
375 : host_id_(host_id),
376 valid_(true),
377 in_process_(false),
378 swiftshader_rendering_(false),
379 kind_(kind),
380 process_launched_(false),
381 initialized_(false),
382 gpu_crash_recorded_(false),
383 uma_memory_stats_received_(false) {
384 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
385 switches::kSingleProcess) ||
386 base::CommandLine::ForCurrentProcess()->HasSwitch(
387 switches::kInProcessGPU)) {
388 in_process_ = true;
391 // If the 'single GPU process' policy ever changes, we still want to maintain
392 // it for 'gpu thread' mode and only create one instance of host and thread.
393 DCHECK(!in_process_ || g_gpu_process_hosts[kind] == NULL);
395 g_gpu_process_hosts[kind] = this;
397 // Post a task to create the corresponding GpuProcessHostUIShim. The
398 // GpuProcessHostUIShim will be destroyed if either the browser exits,
399 // in which case it calls GpuProcessHostUIShim::DestroyAll, or the
400 // GpuProcessHost is destroyed, which happens when the corresponding GPU
401 // process terminates or fails to launch.
402 BrowserThread::PostTask(
403 BrowserThread::UI,
404 FROM_HERE,
405 base::Bind(base::IgnoreResult(&GpuProcessHostUIShim::Create), host_id));
407 process_.reset(new BrowserChildProcessHostImpl(PROCESS_TYPE_GPU, this));
410 GpuProcessHost::~GpuProcessHost() {
411 DCHECK(CalledOnValidThread());
413 SendOutstandingReplies();
415 RecordProcessCrash();
417 // In case we never started, clean up.
418 while (!queued_messages_.empty()) {
419 delete queued_messages_.front();
420 queued_messages_.pop();
423 // This is only called on the IO thread so no race against the constructor
424 // for another GpuProcessHost.
425 if (g_gpu_process_hosts[kind_] == this)
426 g_gpu_process_hosts[kind_] = NULL;
428 // If there are any remaining offscreen contexts at the point the
429 // GPU process exits, assume something went wrong, and block their
430 // URLs from accessing client 3D APIs without prompting.
431 BlockLiveOffscreenContexts();
433 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitSurfaceCount",
434 GpuSurfaceTracker::Get()->GetSurfaceCount());
435 UMA_HISTOGRAM_BOOLEAN("GPU.AtExitReceivedMemoryStats",
436 uma_memory_stats_received_);
438 if (uma_memory_stats_received_) {
439 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitManagedMemoryClientCount",
440 uma_memory_stats_.client_count);
441 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitContextGroupCount",
442 uma_memory_stats_.context_group_count);
443 UMA_HISTOGRAM_CUSTOM_COUNTS(
444 "GPU.AtExitMBytesAllocated",
445 uma_memory_stats_.bytes_allocated_current / 1024 / 1024, 1, 2000, 50);
446 UMA_HISTOGRAM_CUSTOM_COUNTS(
447 "GPU.AtExitMBytesAllocatedMax",
448 uma_memory_stats_.bytes_allocated_max / 1024 / 1024, 1, 2000, 50);
449 UMA_HISTOGRAM_CUSTOM_COUNTS(
450 "GPU.AtExitMBytesLimit",
451 uma_memory_stats_.bytes_limit / 1024 / 1024, 1, 2000, 50);
454 std::string message;
455 if (!in_process_) {
456 int exit_code;
457 base::TerminationStatus status = process_->GetTerminationStatus(
458 false /* known_dead */, &exit_code);
459 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessTerminationStatus",
460 status,
461 base::TERMINATION_STATUS_MAX_ENUM);
463 if (status == base::TERMINATION_STATUS_NORMAL_TERMINATION ||
464 status == base::TERMINATION_STATUS_ABNORMAL_TERMINATION) {
465 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessExitCode",
466 exit_code,
467 RESULT_CODE_LAST_CODE);
470 switch (status) {
471 case base::TERMINATION_STATUS_NORMAL_TERMINATION:
472 message = "The GPU process exited normally. Everything is okay.";
473 break;
474 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
475 message = base::StringPrintf(
476 "The GPU process exited with code %d.",
477 exit_code);
478 break;
479 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED:
480 message = "You killed the GPU process! Why?";
481 break;
482 case base::TERMINATION_STATUS_PROCESS_CRASHED:
483 message = "The GPU process crashed!";
484 break;
485 default:
486 break;
490 BrowserThread::PostTask(BrowserThread::UI,
491 FROM_HERE,
492 base::Bind(&GpuProcessHostUIShim::Destroy,
493 host_id_,
494 message));
497 bool GpuProcessHost::Init() {
498 init_start_time_ = base::TimeTicks::Now();
500 TRACE_EVENT_INSTANT0("gpu", "LaunchGpuProcess", TRACE_EVENT_SCOPE_THREAD);
502 std::string channel_id = process_->GetHost()->CreateChannel();
503 if (channel_id.empty())
504 return false;
506 if (in_process_) {
507 DCHECK_CURRENTLY_ON(BrowserThread::IO);
508 DCHECK(g_gpu_main_thread_factory);
509 in_process_gpu_thread_.reset(
510 g_gpu_main_thread_factory(InProcessChildThreadParams(
511 channel_id, base::MessageLoop::current()->task_runner())));
512 base::Thread::Options options;
513 #if defined(OS_WIN)
514 // WGL needs to create its own window and pump messages on it.
515 options.message_loop_type = base::MessageLoop::TYPE_UI;
516 #endif
517 in_process_gpu_thread_->StartWithOptions(options);
519 OnProcessLaunched(); // Fake a callback that the process is ready.
520 } else if (!LaunchGpuProcess(channel_id)) {
521 return false;
524 if (!Send(new GpuMsg_Initialize()))
525 return false;
527 return true;
530 void GpuProcessHost::RouteOnUIThread(const IPC::Message& message) {
531 BrowserThread::PostTask(
532 BrowserThread::UI,
533 FROM_HERE,
534 base::Bind(&RouteToGpuProcessHostUIShimTask, host_id_, message));
537 bool GpuProcessHost::Send(IPC::Message* msg) {
538 DCHECK(CalledOnValidThread());
539 if (process_->GetHost()->IsChannelOpening()) {
540 queued_messages_.push(msg);
541 return true;
544 bool result = process_->Send(msg);
545 if (!result) {
546 // Channel is hosed, but we may not get destroyed for a while. Send
547 // outstanding channel creation failures now so that the caller can restart
548 // with a new process/channel without waiting.
549 SendOutstandingReplies();
551 return result;
554 void GpuProcessHost::AddFilter(IPC::MessageFilter* filter) {
555 DCHECK(CalledOnValidThread());
556 process_->GetHost()->AddFilter(filter);
559 bool GpuProcessHost::OnMessageReceived(const IPC::Message& message) {
560 DCHECK(CalledOnValidThread());
561 IPC_BEGIN_MESSAGE_MAP(GpuProcessHost, message)
562 IPC_MESSAGE_HANDLER(GpuHostMsg_Initialized, OnInitialized)
563 IPC_MESSAGE_HANDLER(GpuHostMsg_ChannelEstablished, OnChannelEstablished)
564 IPC_MESSAGE_HANDLER(GpuHostMsg_CommandBufferCreated, OnCommandBufferCreated)
565 IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyCommandBuffer, OnDestroyCommandBuffer)
566 IPC_MESSAGE_HANDLER(GpuHostMsg_GpuMemoryBufferCreated,
567 OnGpuMemoryBufferCreated)
568 IPC_MESSAGE_HANDLER(GpuHostMsg_DidCreateOffscreenContext,
569 OnDidCreateOffscreenContext)
570 IPC_MESSAGE_HANDLER(GpuHostMsg_DidLoseContext, OnDidLoseContext)
571 IPC_MESSAGE_HANDLER(GpuHostMsg_DidDestroyOffscreenContext,
572 OnDidDestroyOffscreenContext)
573 IPC_MESSAGE_HANDLER(GpuHostMsg_GpuMemoryUmaStats,
574 OnGpuMemoryUmaStatsReceived)
575 #if defined(OS_MACOSX)
576 IPC_MESSAGE_HANDLER_GENERIC(GpuHostMsg_AcceleratedSurfaceBuffersSwapped,
577 OnAcceleratedSurfaceBuffersSwapped(message))
578 #endif
579 IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyChannel,
580 OnDestroyChannel)
581 IPC_MESSAGE_HANDLER(GpuHostMsg_CacheShader,
582 OnCacheShader)
584 IPC_MESSAGE_UNHANDLED(RouteOnUIThread(message))
585 IPC_END_MESSAGE_MAP()
587 return true;
590 void GpuProcessHost::OnChannelConnected(int32 peer_pid) {
591 TRACE_EVENT0("gpu", "GpuProcessHost::OnChannelConnected");
593 while (!queued_messages_.empty()) {
594 Send(queued_messages_.front());
595 queued_messages_.pop();
599 void GpuProcessHost::EstablishGpuChannel(
600 int client_id,
601 bool share_context,
602 bool allow_future_sync_points,
603 const EstablishChannelCallback& callback) {
604 DCHECK(CalledOnValidThread());
605 TRACE_EVENT0("gpu", "GpuProcessHost::EstablishGpuChannel");
607 // If GPU features are already blacklisted, no need to establish the channel.
608 if (!GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL)) {
609 DVLOG(1) << "GPU blacklisted, refusing to open a GPU channel.";
610 callback.Run(IPC::ChannelHandle(), gpu::GPUInfo());
611 return;
614 if (Send(new GpuMsg_EstablishChannel(
615 client_id, share_context, allow_future_sync_points))) {
616 channel_requests_.push(callback);
617 } else {
618 DVLOG(1) << "Failed to send GpuMsg_EstablishChannel.";
619 callback.Run(IPC::ChannelHandle(), gpu::GPUInfo());
622 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
623 switches::kDisableGpuShaderDiskCache)) {
624 CreateChannelCache(client_id);
628 void GpuProcessHost::CreateViewCommandBuffer(
629 const gfx::GLSurfaceHandle& compositing_surface,
630 int surface_id,
631 int client_id,
632 const GPUCreateCommandBufferConfig& init_params,
633 int route_id,
634 const CreateCommandBufferCallback& callback) {
635 TRACE_EVENT0("gpu", "GpuProcessHost::CreateViewCommandBuffer");
637 DCHECK(CalledOnValidThread());
639 if (!compositing_surface.is_null() &&
640 Send(new GpuMsg_CreateViewCommandBuffer(
641 compositing_surface, surface_id, client_id, init_params, route_id))) {
642 create_command_buffer_requests_.push(callback);
643 surface_refs_.insert(std::make_pair(surface_id,
644 GpuSurfaceTracker::GetInstance()->GetSurfaceRefForSurface(surface_id)));
645 } else {
646 // Could distinguish here between compositing_surface being NULL
647 // and Send failing, if desired.
648 callback.Run(CREATE_COMMAND_BUFFER_FAILED_AND_CHANNEL_LOST);
652 void GpuProcessHost::CreateGpuMemoryBuffer(
653 gfx::GpuMemoryBufferId id,
654 const gfx::Size& size,
655 gfx::GpuMemoryBuffer::Format format,
656 gfx::GpuMemoryBuffer::Usage usage,
657 int client_id,
658 int32 surface_id,
659 const CreateGpuMemoryBufferCallback& callback) {
660 TRACE_EVENT0("gpu", "GpuProcessHost::CreateGpuMemoryBuffer");
662 DCHECK(CalledOnValidThread());
664 GpuMsg_CreateGpuMemoryBuffer_Params params;
665 params.id = id;
666 params.size = size;
667 params.format = format;
668 params.usage = usage;
669 params.client_id = client_id;
670 params.surface_handle =
671 GpuSurfaceTracker::GetInstance()->GetSurfaceHandle(surface_id).handle;
672 if (Send(new GpuMsg_CreateGpuMemoryBuffer(params))) {
673 create_gpu_memory_buffer_requests_.push(callback);
674 create_gpu_memory_buffer_surface_refs_.push(surface_id);
675 if (surface_id) {
676 surface_refs_.insert(std::make_pair(
677 surface_id, GpuSurfaceTracker::GetInstance()->GetSurfaceRefForSurface(
678 surface_id)));
680 } else {
681 callback.Run(gfx::GpuMemoryBufferHandle());
685 void GpuProcessHost::DestroyGpuMemoryBuffer(gfx::GpuMemoryBufferId id,
686 int client_id,
687 int sync_point) {
688 TRACE_EVENT0("gpu", "GpuProcessHost::DestroyGpuMemoryBuffer");
690 DCHECK(CalledOnValidThread());
692 Send(new GpuMsg_DestroyGpuMemoryBuffer(id, client_id, sync_point));
695 void GpuProcessHost::OnInitialized(bool result, const gpu::GPUInfo& gpu_info) {
696 UMA_HISTOGRAM_BOOLEAN("GPU.GPUProcessInitialized", result);
697 initialized_ = result;
699 if (!initialized_)
700 GpuDataManagerImpl::GetInstance()->OnGpuProcessInitFailure();
701 else if (!in_process_)
702 GpuDataManagerImpl::GetInstance()->UpdateGpuInfo(gpu_info);
705 void GpuProcessHost::OnChannelEstablished(
706 const IPC::ChannelHandle& channel_handle) {
707 TRACE_EVENT0("gpu", "GpuProcessHost::OnChannelEstablished");
709 if (channel_requests_.empty()) {
710 // This happens when GPU process is compromised.
711 RouteOnUIThread(GpuHostMsg_OnLogMessage(
712 logging::LOG_WARNING,
713 "WARNING",
714 "Received a ChannelEstablished message but no requests in queue."));
715 return;
717 EstablishChannelCallback callback = channel_requests_.front();
718 channel_requests_.pop();
720 // Currently if any of the GPU features are blacklisted, we don't establish a
721 // GPU channel.
722 if (!channel_handle.name.empty() &&
723 !GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL)) {
724 Send(new GpuMsg_CloseChannel(channel_handle));
725 callback.Run(IPC::ChannelHandle(), gpu::GPUInfo());
726 RouteOnUIThread(GpuHostMsg_OnLogMessage(
727 logging::LOG_WARNING,
728 "WARNING",
729 "Hardware acceleration is unavailable."));
730 return;
733 callback.Run(channel_handle,
734 GpuDataManagerImpl::GetInstance()->GetGPUInfo());
737 void GpuProcessHost::OnCommandBufferCreated(CreateCommandBufferResult result) {
738 TRACE_EVENT0("gpu", "GpuProcessHost::OnCommandBufferCreated");
740 if (create_command_buffer_requests_.empty())
741 return;
743 CreateCommandBufferCallback callback =
744 create_command_buffer_requests_.front();
745 create_command_buffer_requests_.pop();
746 callback.Run(result);
749 void GpuProcessHost::OnDestroyCommandBuffer(int32 surface_id) {
750 TRACE_EVENT0("gpu", "GpuProcessHost::OnDestroyCommandBuffer");
751 SurfaceRefMap::iterator it = surface_refs_.find(surface_id);
752 if (it != surface_refs_.end()) {
753 surface_refs_.erase(it);
757 void GpuProcessHost::OnGpuMemoryBufferCreated(
758 const gfx::GpuMemoryBufferHandle& handle) {
759 TRACE_EVENT0("gpu", "GpuProcessHost::OnGpuMemoryBufferCreated");
761 if (create_gpu_memory_buffer_requests_.empty())
762 return;
764 CreateGpuMemoryBufferCallback callback =
765 create_gpu_memory_buffer_requests_.front();
766 create_gpu_memory_buffer_requests_.pop();
767 callback.Run(handle);
769 int32 surface_id = create_gpu_memory_buffer_surface_refs_.front();
770 create_gpu_memory_buffer_surface_refs_.pop();
771 SurfaceRefMap::iterator it = surface_refs_.find(surface_id);
772 if (it != surface_refs_.end()) {
773 surface_refs_.erase(it);
777 void GpuProcessHost::OnDidCreateOffscreenContext(const GURL& url) {
778 urls_with_live_offscreen_contexts_.insert(url);
781 void GpuProcessHost::OnDidLoseContext(bool offscreen,
782 gpu::error::ContextLostReason reason,
783 const GURL& url) {
784 // TODO(kbr): would be nice to see the "offscreen" flag too.
785 TRACE_EVENT2("gpu", "GpuProcessHost::OnDidLoseContext",
786 "reason", reason,
787 "url",
788 url.possibly_invalid_spec());
790 if (!offscreen || url.is_empty()) {
791 // Assume that the loss of the compositor's or accelerated canvas'
792 // context is a serious event and blame the loss on all live
793 // offscreen contexts. This more robustly handles situations where
794 // the GPU process may not actually detect the context loss in the
795 // offscreen context.
796 BlockLiveOffscreenContexts();
797 return;
800 GpuDataManagerImpl::DomainGuilt guilt;
801 switch (reason) {
802 case gpu::error::kGuilty:
803 guilt = GpuDataManagerImpl::DOMAIN_GUILT_KNOWN;
804 break;
805 case gpu::error::kUnknown:
806 guilt = GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN;
807 break;
808 case gpu::error::kInnocent:
809 return;
810 default:
811 NOTREACHED();
812 return;
815 GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(url, guilt);
818 void GpuProcessHost::OnDidDestroyOffscreenContext(const GURL& url) {
819 urls_with_live_offscreen_contexts_.erase(url);
822 void GpuProcessHost::OnGpuMemoryUmaStatsReceived(
823 const GPUMemoryUmaStats& stats) {
824 TRACE_EVENT0("gpu", "GpuProcessHost::OnGpuMemoryUmaStatsReceived");
825 uma_memory_stats_received_ = true;
826 uma_memory_stats_ = stats;
829 #if defined(OS_MACOSX)
830 void GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped(
831 const IPC::Message& message) {
832 RenderWidgetResizeHelper::Get()->PostGpuProcessMsg(host_id_, message);
834 #endif
836 void GpuProcessHost::OnProcessLaunched() {
837 UMA_HISTOGRAM_TIMES("GPU.GPUProcessLaunchTime",
838 base::TimeTicks::Now() - init_start_time_);
841 void GpuProcessHost::OnProcessCrashed(int exit_code) {
842 SendOutstandingReplies();
843 RecordProcessCrash();
844 GpuDataManagerImpl::GetInstance()->ProcessCrashed(
845 process_->GetTerminationStatus(true /* known_dead */, NULL));
848 GpuProcessHost::GpuProcessKind GpuProcessHost::kind() {
849 return kind_;
852 void GpuProcessHost::ForceShutdown() {
853 // This is only called on the IO thread so no race against the constructor
854 // for another GpuProcessHost.
855 if (g_gpu_process_hosts[kind_] == this)
856 g_gpu_process_hosts[kind_] = NULL;
858 process_->ForceShutdown();
861 void GpuProcessHost::BeginFrameSubscription(
862 int surface_id,
863 base::WeakPtr<RenderWidgetHostViewFrameSubscriber> subscriber) {
864 frame_subscribers_[surface_id] = subscriber;
867 void GpuProcessHost::EndFrameSubscription(int surface_id) {
868 frame_subscribers_.erase(surface_id);
871 bool GpuProcessHost::LaunchGpuProcess(const std::string& channel_id) {
872 if (!(gpu_enabled_ &&
873 GpuDataManagerImpl::GetInstance()->ShouldUseSwiftShader()) &&
874 !hardware_gpu_enabled_) {
875 SendOutstandingReplies();
876 return false;
879 const base::CommandLine& browser_command_line =
880 *base::CommandLine::ForCurrentProcess();
882 base::CommandLine::StringType gpu_launcher =
883 browser_command_line.GetSwitchValueNative(switches::kGpuLauncher);
885 #if defined(OS_ANDROID)
886 // crbug.com/447735. readlink("self/proc/exe") sometimes fails on Android
887 // at startup with EACCES. As a workaround ignore this here, since the
888 // executable name is actually not used or useful anyways.
889 base::CommandLine* cmd_line =
890 new base::CommandLine(base::CommandLine::NO_PROGRAM);
891 #else
892 #if defined(OS_LINUX)
893 int child_flags = gpu_launcher.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
894 ChildProcessHost::CHILD_NORMAL;
895 #else
896 int child_flags = ChildProcessHost::CHILD_NORMAL;
897 #endif
899 base::FilePath exe_path = ChildProcessHost::GetChildPath(child_flags);
900 if (exe_path.empty())
901 return false;
903 base::CommandLine* cmd_line = new base::CommandLine(exe_path);
904 #endif
905 cmd_line->AppendSwitchASCII(switches::kProcessType, switches::kGpuProcess);
906 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
908 if (kind_ == GPU_PROCESS_KIND_UNSANDBOXED)
909 cmd_line->AppendSwitch(switches::kDisableGpuSandbox);
911 // If you want a browser command-line switch passed to the GPU process
912 // you need to add it to |kSwitchNames| at the beginning of this file.
913 cmd_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
914 arraysize(kSwitchNames));
915 cmd_line->CopySwitchesFrom(
916 browser_command_line, switches::kGpuSwitches, switches::kNumGpuSwitches);
917 cmd_line->CopySwitchesFrom(
918 browser_command_line, switches::kGLSwitchesCopiedFromGpuProcessHost,
919 switches::kGLSwitchesCopiedFromGpuProcessHostNumSwitches);
921 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
922 cmd_line, process_->GetData().id);
924 GpuDataManagerImpl::GetInstance()->AppendGpuCommandLine(cmd_line);
926 if (cmd_line->HasSwitch(switches::kUseGL)) {
927 swiftshader_rendering_ =
928 (cmd_line->GetSwitchValueASCII(switches::kUseGL) == "swiftshader");
931 UMA_HISTOGRAM_BOOLEAN("GPU.GPU.GPUProcessSoftwareRendering",
932 swiftshader_rendering_);
934 // If specified, prepend a launcher program to the command line.
935 if (!gpu_launcher.empty())
936 cmd_line->PrependWrapper(gpu_launcher);
938 process_->Launch(
939 new GpuSandboxedProcessLauncherDelegate(cmd_line,
940 process_->GetHost()),
941 cmd_line,
942 true);
943 process_launched_ = true;
945 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
946 LAUNCHED, GPU_PROCESS_LIFETIME_EVENT_MAX);
947 return true;
950 void GpuProcessHost::SendOutstandingReplies() {
951 valid_ = false;
952 // First send empty channel handles for all EstablishChannel requests.
953 while (!channel_requests_.empty()) {
954 EstablishChannelCallback callback = channel_requests_.front();
955 channel_requests_.pop();
956 callback.Run(IPC::ChannelHandle(), gpu::GPUInfo());
959 while (!create_command_buffer_requests_.empty()) {
960 CreateCommandBufferCallback callback =
961 create_command_buffer_requests_.front();
962 create_command_buffer_requests_.pop();
963 callback.Run(CREATE_COMMAND_BUFFER_FAILED_AND_CHANNEL_LOST);
966 while (!create_gpu_memory_buffer_requests_.empty()) {
967 CreateGpuMemoryBufferCallback callback =
968 create_gpu_memory_buffer_requests_.front();
969 create_gpu_memory_buffer_requests_.pop();
970 callback.Run(gfx::GpuMemoryBufferHandle());
974 void GpuProcessHost::BlockLiveOffscreenContexts() {
975 for (std::multiset<GURL>::iterator iter =
976 urls_with_live_offscreen_contexts_.begin();
977 iter != urls_with_live_offscreen_contexts_.end(); ++iter) {
978 GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(
979 *iter, GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN);
983 void GpuProcessHost::RecordProcessCrash() {
984 // Skip if a GPU process crash was already counted.
985 if (gpu_crash_recorded_)
986 return;
988 // Maximum number of times the GPU process is allowed to crash in a session.
989 // Once this limit is reached, any request to launch the GPU process will
990 // fail.
991 const int kGpuMaxCrashCount = 3;
993 // Last time the GPU process crashed.
994 static base::Time last_gpu_crash_time;
996 bool disable_crash_limit = base::CommandLine::ForCurrentProcess()->HasSwitch(
997 switches::kDisableGpuProcessCrashLimit);
999 // Ending only acts as a failure if the GPU process was actually started and
1000 // was intended for actual rendering (and not just checking caps or other
1001 // options).
1002 if (process_launched_ && kind_ == GPU_PROCESS_KIND_SANDBOXED) {
1003 gpu_crash_recorded_ = true;
1004 if (swiftshader_rendering_) {
1005 UMA_HISTOGRAM_ENUMERATION("GPU.SwiftShaderLifetimeEvents",
1006 DIED_FIRST_TIME + swiftshader_crash_count_,
1007 GPU_PROCESS_LIFETIME_EVENT_MAX);
1009 if (++swiftshader_crash_count_ >= kGpuMaxCrashCount &&
1010 !disable_crash_limit) {
1011 // SwiftShader is too unstable to use. Disable it for current session.
1012 gpu_enabled_ = false;
1014 } else {
1015 ++gpu_crash_count_;
1016 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
1017 std::min(DIED_FIRST_TIME + gpu_crash_count_,
1018 GPU_PROCESS_LIFETIME_EVENT_MAX - 1),
1019 GPU_PROCESS_LIFETIME_EVENT_MAX);
1021 // Allow about 1 GPU crash per hour to be removed from the crash count,
1022 // so very occasional crashes won't eventually add up and prevent the
1023 // GPU process from launching.
1024 ++gpu_recent_crash_count_;
1025 base::Time current_time = base::Time::Now();
1026 if (crashed_before_) {
1027 int hours_different = (current_time - last_gpu_crash_time).InHours();
1028 gpu_recent_crash_count_ =
1029 std::max(0, gpu_recent_crash_count_ - hours_different);
1032 crashed_before_ = true;
1033 last_gpu_crash_time = current_time;
1035 if ((gpu_recent_crash_count_ >= kGpuMaxCrashCount &&
1036 !disable_crash_limit) ||
1037 !initialized_) {
1038 #if !defined(OS_CHROMEOS)
1039 // The GPU process is too unstable to use. Disable it for current
1040 // session.
1041 hardware_gpu_enabled_ = false;
1042 GpuDataManagerImpl::GetInstance()->DisableHardwareAcceleration();
1043 #endif
1049 std::string GpuProcessHost::GetShaderPrefixKey() {
1050 if (shader_prefix_key_.empty()) {
1051 gpu::GPUInfo info = GpuDataManagerImpl::GetInstance()->GetGPUInfo();
1053 std::string in_str = GetContentClient()->GetProduct() + "-" +
1054 info.gl_vendor + "-" + info.gl_renderer + "-" +
1055 info.driver_version + "-" + info.driver_vendor;
1057 base::Base64Encode(base::SHA1HashString(in_str), &shader_prefix_key_);
1060 return shader_prefix_key_;
1063 void GpuProcessHost::LoadedShader(const std::string& key,
1064 const std::string& data) {
1065 std::string prefix = GetShaderPrefixKey();
1066 if (!key.compare(0, prefix.length(), prefix))
1067 Send(new GpuMsg_LoadedShader(data));
1070 void GpuProcessHost::CreateChannelCache(int32 client_id) {
1071 TRACE_EVENT0("gpu", "GpuProcessHost::CreateChannelCache");
1073 scoped_refptr<ShaderDiskCache> cache =
1074 ShaderCacheFactory::GetInstance()->Get(client_id);
1075 if (!cache.get())
1076 return;
1078 cache->set_host_id(host_id_);
1080 client_id_to_shader_cache_[client_id] = cache;
1083 void GpuProcessHost::OnDestroyChannel(int32 client_id) {
1084 TRACE_EVENT0("gpu", "GpuProcessHost::OnDestroyChannel");
1085 client_id_to_shader_cache_.erase(client_id);
1088 void GpuProcessHost::OnCacheShader(int32 client_id,
1089 const std::string& key,
1090 const std::string& shader) {
1091 TRACE_EVENT0("gpu", "GpuProcessHost::OnCacheShader");
1092 ClientIdToShaderCacheMap::iterator iter =
1093 client_id_to_shader_cache_.find(client_id);
1094 // If the cache doesn't exist then this is an off the record profile.
1095 if (iter == client_id_to_shader_cache_.end())
1096 return;
1097 iter->second->Cache(GetShaderPrefixKey() + ":" + key, shader);
1100 } // namespace content