Add a FrameHostMsg_BeginNavigation IPC
[chromium-blink-merge.git] / content / browser / gpu / gpu_process_host.cc
blob578bde432b0cd3e6a80bd84720d793bbccea358d
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/gpu/gpu_process_host.h"
7 #include "base/base64.h"
8 #include "base/base_switches.h"
9 #include "base/basictypes.h"
10 #include "base/bind.h"
11 #include "base/callback_helpers.h"
12 #include "base/command_line.h"
13 #include "base/debug/trace_event.h"
14 #include "base/logging.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/metrics/histogram.h"
17 #include "base/sha1.h"
18 #include "base/threading/thread.h"
19 #include "content/browser/browser_child_process_host_impl.h"
20 #include "content/browser/gpu/gpu_data_manager_impl.h"
21 #include "content/browser/gpu/gpu_process_host_ui_shim.h"
22 #include "content/browser/gpu/shader_disk_cache.h"
23 #include "content/browser/renderer_host/render_widget_helper.h"
24 #include "content/browser/renderer_host/render_widget_host_impl.h"
25 #include "content/common/child_process_host_impl.h"
26 #include "content/common/gpu/gpu_messages.h"
27 #include "content/common/view_messages.h"
28 #include "content/public/browser/browser_thread.h"
29 #include "content/public/browser/content_browser_client.h"
30 #include "content/public/browser/render_process_host.h"
31 #include "content/public/browser/render_widget_host_view.h"
32 #include "content/public/browser/render_widget_host_view_frame_subscriber.h"
33 #include "content/public/common/content_client.h"
34 #include "content/public/common/content_switches.h"
35 #include "content/public/common/result_codes.h"
36 #include "content/public/common/sandboxed_process_launcher_delegate.h"
37 #include "gpu/command_buffer/service/gpu_switches.h"
38 #include "ipc/ipc_channel_handle.h"
39 #include "ipc/ipc_switches.h"
40 #include "ipc/message_filter.h"
41 #include "media/base/media_switches.h"
42 #include "ui/events/latency_info.h"
43 #include "ui/gl/gl_switches.h"
46 #if defined(OS_WIN)
47 #include "base/win/windows_version.h"
48 #include "content/common/sandbox_win.h"
49 #include "sandbox/win/src/sandbox_policy.h"
50 #include "ui/gfx/switches.h"
51 #endif
53 #if defined(USE_OZONE)
54 #include "ui/ozone/public/ozone_switches.h"
55 #endif
57 #if defined(USE_X11) && !defined(OS_CHROMEOS)
58 #include "ui/gfx/x/x11_switches.h"
59 #endif
61 namespace content {
63 bool GpuProcessHost::gpu_enabled_ = true;
64 bool GpuProcessHost::hardware_gpu_enabled_ = true;
66 namespace {
68 enum GPUProcessLifetimeEvent {
69 LAUNCHED,
70 DIED_FIRST_TIME,
71 DIED_SECOND_TIME,
72 DIED_THIRD_TIME,
73 DIED_FOURTH_TIME,
74 GPU_PROCESS_LIFETIME_EVENT_MAX = 100
77 // Indexed by GpuProcessKind. There is one of each kind maximum. This array may
78 // only be accessed from the IO thread.
79 GpuProcessHost* g_gpu_process_hosts[GpuProcessHost::GPU_PROCESS_KIND_COUNT];
82 void SendGpuProcessMessage(GpuProcessHost::GpuProcessKind kind,
83 CauseForGpuLaunch cause,
84 IPC::Message* message) {
85 GpuProcessHost* host = GpuProcessHost::Get(kind, cause);
86 if (host) {
87 host->Send(message);
88 } else {
89 delete message;
93 // NOTE: changes to this class need to be reviewed by the security team.
94 class GpuSandboxedProcessLauncherDelegate
95 : public SandboxedProcessLauncherDelegate {
96 public:
97 GpuSandboxedProcessLauncherDelegate(CommandLine* cmd_line,
98 ChildProcessHost* host)
99 #if defined(OS_WIN)
100 : cmd_line_(cmd_line) {}
101 #elif defined(OS_POSIX)
102 : ipc_fd_(host->TakeClientFileDescriptor()) {}
103 #endif
105 virtual ~GpuSandboxedProcessLauncherDelegate() {}
107 #if defined(OS_WIN)
108 virtual bool ShouldSandbox() OVERRIDE {
109 bool sandbox = !cmd_line_->HasSwitch(switches::kDisableGpuSandbox);
110 if(! sandbox) {
111 DVLOG(1) << "GPU sandbox is disabled";
113 return sandbox;
116 virtual void PreSandbox(bool* disable_default_policy,
117 base::FilePath* exposed_dir) OVERRIDE {
118 *disable_default_policy = true;
121 // For the GPU process we gotten as far as USER_LIMITED. The next level
122 // which is USER_RESTRICTED breaks both the DirectX backend and the OpenGL
123 // backend. Note that the GPU process is connected to the interactive
124 // desktop.
125 virtual void PreSpawnTarget(sandbox::TargetPolicy* policy,
126 bool* success) {
127 if (base::win::GetVersion() > base::win::VERSION_XP) {
128 if (cmd_line_->GetSwitchValueASCII(switches::kUseGL) ==
129 gfx::kGLImplementationDesktopName) {
130 // Open GL path.
131 policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
132 sandbox::USER_LIMITED);
133 SetJobLevel(*cmd_line_, sandbox::JOB_UNPROTECTED, 0, policy);
134 policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
135 } else {
136 policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
137 sandbox::USER_LIMITED);
139 // UI restrictions break when we access Windows from outside our job.
140 // However, we don't want a proxy window in this process because it can
141 // introduce deadlocks where the renderer blocks on the gpu, which in
142 // turn blocks on the browser UI thread. So, instead we forgo a window
143 // message pump entirely and just add job restrictions to prevent child
144 // processes.
145 SetJobLevel(*cmd_line_,
146 sandbox::JOB_LIMITED_USER,
147 JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS |
148 JOB_OBJECT_UILIMIT_DESKTOP |
149 JOB_OBJECT_UILIMIT_EXITWINDOWS |
150 JOB_OBJECT_UILIMIT_DISPLAYSETTINGS,
151 policy);
153 policy->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
155 } else {
156 SetJobLevel(*cmd_line_, sandbox::JOB_UNPROTECTED, 0, policy);
157 policy->SetTokenLevel(sandbox::USER_UNPROTECTED,
158 sandbox::USER_LIMITED);
161 // Allow the server side of GPU sockets, which are pipes that have
162 // the "chrome.gpu" namespace and an arbitrary suffix.
163 sandbox::ResultCode result = policy->AddRule(
164 sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
165 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
166 L"\\\\.\\pipe\\chrome.gpu.*");
167 if (result != sandbox::SBOX_ALL_OK) {
168 *success = false;
169 return;
172 // Block this DLL even if it is not loaded by the browser process.
173 policy->AddDllToUnload(L"cmsetac.dll");
175 #ifdef USE_AURA
176 // GPU also needs to add sections to the browser for aura
177 // TODO(jschuh): refactor the GPU channel to remove this. crbug.com/128786
178 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
179 sandbox::TargetPolicy::HANDLES_DUP_BROKER,
180 L"Section");
181 if (result != sandbox::SBOX_ALL_OK) {
182 *success = false;
183 return;
185 #endif
187 if (cmd_line_->HasSwitch(switches::kEnableLogging)) {
188 base::string16 log_file_path = logging::GetLogFileFullPath();
189 if (!log_file_path.empty()) {
190 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
191 sandbox::TargetPolicy::FILES_ALLOW_ANY,
192 log_file_path.c_str());
193 if (result != sandbox::SBOX_ALL_OK) {
194 *success = false;
195 return;
200 #elif defined(OS_POSIX)
202 virtual int GetIpcFd() OVERRIDE {
203 return ipc_fd_;
205 #endif // OS_WIN
207 private:
208 #if defined(OS_WIN)
209 CommandLine* cmd_line_;
210 #elif defined(OS_POSIX)
211 int ipc_fd_;
212 #endif // OS_WIN
215 } // anonymous namespace
217 // static
218 bool GpuProcessHost::ValidateHost(GpuProcessHost* host) {
219 // The Gpu process is invalid if it's not using SwiftShader, the card is
220 // blacklisted, and we can kill it and start over.
221 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess) ||
222 CommandLine::ForCurrentProcess()->HasSwitch(switches::kInProcessGPU) ||
223 (host->valid_ &&
224 (host->swiftshader_rendering_ ||
225 !GpuDataManagerImpl::GetInstance()->ShouldUseSwiftShader()))) {
226 return true;
229 host->ForceShutdown();
230 return false;
233 // static
234 GpuProcessHost* GpuProcessHost::Get(GpuProcessKind kind,
235 CauseForGpuLaunch cause) {
236 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
238 // Don't grant further access to GPU if it is not allowed.
239 GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
240 DCHECK(gpu_data_manager);
241 if (!gpu_data_manager->GpuAccessAllowed(NULL))
242 return NULL;
244 if (g_gpu_process_hosts[kind] && ValidateHost(g_gpu_process_hosts[kind]))
245 return g_gpu_process_hosts[kind];
247 if (cause == CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH)
248 return NULL;
250 static int last_host_id = 0;
251 int host_id;
252 host_id = ++last_host_id;
254 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLaunchCause",
255 cause,
256 CAUSE_FOR_GPU_LAUNCH_MAX_ENUM);
258 GpuProcessHost* host = new GpuProcessHost(host_id, kind);
259 if (host->Init())
260 return host;
262 delete host;
263 return NULL;
266 // static
267 void GpuProcessHost::GetProcessHandles(
268 const GpuDataManager::GetGpuProcessHandlesCallback& callback) {
269 if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
270 BrowserThread::PostTask(
271 BrowserThread::IO,
272 FROM_HERE,
273 base::Bind(&GpuProcessHost::GetProcessHandles, callback));
274 return;
276 std::list<base::ProcessHandle> handles;
277 for (size_t i = 0; i < arraysize(g_gpu_process_hosts); ++i) {
278 GpuProcessHost* host = g_gpu_process_hosts[i];
279 if (host && ValidateHost(host))
280 handles.push_back(host->process_->GetHandle());
282 BrowserThread::PostTask(
283 BrowserThread::UI,
284 FROM_HERE,
285 base::Bind(callback, handles));
288 // static
289 void GpuProcessHost::SendOnIO(GpuProcessKind kind,
290 CauseForGpuLaunch cause,
291 IPC::Message* message) {
292 if (!BrowserThread::PostTask(
293 BrowserThread::IO, FROM_HERE,
294 base::Bind(
295 &SendGpuProcessMessage, kind, cause, message))) {
296 delete message;
300 GpuMainThreadFactoryFunction g_gpu_main_thread_factory = NULL;
302 void GpuProcessHost::RegisterGpuMainThreadFactory(
303 GpuMainThreadFactoryFunction create) {
304 g_gpu_main_thread_factory = create;
307 // static
308 GpuProcessHost* GpuProcessHost::FromID(int host_id) {
309 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
311 for (int i = 0; i < GPU_PROCESS_KIND_COUNT; ++i) {
312 GpuProcessHost* host = g_gpu_process_hosts[i];
313 if (host && host->host_id_ == host_id && ValidateHost(host))
314 return host;
317 return NULL;
320 GpuProcessHost::GpuProcessHost(int host_id, GpuProcessKind kind)
321 : host_id_(host_id),
322 valid_(true),
323 in_process_(false),
324 swiftshader_rendering_(false),
325 kind_(kind),
326 process_launched_(false),
327 initialized_(false),
328 uma_memory_stats_received_(false) {
329 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess) ||
330 CommandLine::ForCurrentProcess()->HasSwitch(switches::kInProcessGPU)) {
331 in_process_ = true;
334 // If the 'single GPU process' policy ever changes, we still want to maintain
335 // it for 'gpu thread' mode and only create one instance of host and thread.
336 DCHECK(!in_process_ || g_gpu_process_hosts[kind] == NULL);
338 g_gpu_process_hosts[kind] = this;
340 // Post a task to create the corresponding GpuProcessHostUIShim. The
341 // GpuProcessHostUIShim will be destroyed if either the browser exits,
342 // in which case it calls GpuProcessHostUIShim::DestroyAll, or the
343 // GpuProcessHost is destroyed, which happens when the corresponding GPU
344 // process terminates or fails to launch.
345 BrowserThread::PostTask(
346 BrowserThread::UI,
347 FROM_HERE,
348 base::Bind(base::IgnoreResult(&GpuProcessHostUIShim::Create), host_id));
350 process_.reset(new BrowserChildProcessHostImpl(PROCESS_TYPE_GPU, this));
353 GpuProcessHost::~GpuProcessHost() {
354 DCHECK(CalledOnValidThread());
356 SendOutstandingReplies();
358 // Maximum number of times the gpu process is allowed to crash in a session.
359 // Once this limit is reached, any request to launch the gpu process will
360 // fail.
361 const int kGpuMaxCrashCount = 3;
363 // Number of times the gpu process has crashed in the current browser session.
364 static int gpu_crash_count = 0;
365 static int gpu_recent_crash_count = 0;
366 static base::Time last_gpu_crash_time;
367 static bool crashed_before = false;
368 static int swiftshader_crash_count = 0;
370 bool disable_crash_limit = CommandLine::ForCurrentProcess()->HasSwitch(
371 switches::kDisableGpuProcessCrashLimit);
373 // Ending only acts as a failure if the GPU process was actually started and
374 // was intended for actual rendering (and not just checking caps or other
375 // options).
376 if (process_launched_ && kind_ == GPU_PROCESS_KIND_SANDBOXED) {
377 if (swiftshader_rendering_) {
378 UMA_HISTOGRAM_ENUMERATION("GPU.SwiftShaderLifetimeEvents",
379 DIED_FIRST_TIME + swiftshader_crash_count,
380 GPU_PROCESS_LIFETIME_EVENT_MAX);
382 if (++swiftshader_crash_count >= kGpuMaxCrashCount &&
383 !disable_crash_limit) {
384 // SwiftShader is too unstable to use. Disable it for current session.
385 gpu_enabled_ = false;
387 } else {
388 ++gpu_crash_count;
389 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
390 std::min(DIED_FIRST_TIME + gpu_crash_count,
391 GPU_PROCESS_LIFETIME_EVENT_MAX - 1),
392 GPU_PROCESS_LIFETIME_EVENT_MAX);
394 // Allow about 1 GPU crash per hour to be removed from the crash count,
395 // so very occasional crashes won't eventually add up and prevent the
396 // GPU process from launching.
397 ++gpu_recent_crash_count;
398 base::Time current_time = base::Time::Now();
399 if (crashed_before) {
400 int hours_different = (current_time - last_gpu_crash_time).InHours();
401 gpu_recent_crash_count =
402 std::max(0, gpu_recent_crash_count - hours_different);
405 crashed_before = true;
406 last_gpu_crash_time = current_time;
408 if ((gpu_recent_crash_count >= kGpuMaxCrashCount && !disable_crash_limit)
409 || !initialized_) {
410 #if !defined(OS_CHROMEOS)
411 // The gpu process is too unstable to use. Disable it for current
412 // session.
413 hardware_gpu_enabled_ = false;
414 GpuDataManagerImpl::GetInstance()->DisableHardwareAcceleration();
415 #endif
420 // In case we never started, clean up.
421 while (!queued_messages_.empty()) {
422 delete queued_messages_.front();
423 queued_messages_.pop();
426 // This is only called on the IO thread so no race against the constructor
427 // for another GpuProcessHost.
428 if (g_gpu_process_hosts[kind_] == this)
429 g_gpu_process_hosts[kind_] = NULL;
431 // If there are any remaining offscreen contexts at the point the
432 // GPU process exits, assume something went wrong, and block their
433 // URLs from accessing client 3D APIs without prompting.
434 BlockLiveOffscreenContexts();
436 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitSurfaceCount",
437 GpuSurfaceTracker::Get()->GetSurfaceCount());
438 UMA_HISTOGRAM_BOOLEAN("GPU.AtExitReceivedMemoryStats",
439 uma_memory_stats_received_);
441 if (uma_memory_stats_received_) {
442 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitManagedMemoryClientCount",
443 uma_memory_stats_.client_count);
444 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitContextGroupCount",
445 uma_memory_stats_.context_group_count);
446 UMA_HISTOGRAM_CUSTOM_COUNTS(
447 "GPU.AtExitMBytesAllocated",
448 uma_memory_stats_.bytes_allocated_current / 1024 / 1024, 1, 2000, 50);
449 UMA_HISTOGRAM_CUSTOM_COUNTS(
450 "GPU.AtExitMBytesAllocatedMax",
451 uma_memory_stats_.bytes_allocated_max / 1024 / 1024, 1, 2000, 50);
452 UMA_HISTOGRAM_CUSTOM_COUNTS(
453 "GPU.AtExitMBytesLimit",
454 uma_memory_stats_.bytes_limit / 1024 / 1024, 1, 2000, 50);
457 std::string message;
458 if (!in_process_) {
459 int exit_code;
460 base::TerminationStatus status = process_->GetTerminationStatus(
461 false /* known_dead */, &exit_code);
462 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessTerminationStatus",
463 status,
464 base::TERMINATION_STATUS_MAX_ENUM);
466 if (status == base::TERMINATION_STATUS_NORMAL_TERMINATION ||
467 status == base::TERMINATION_STATUS_ABNORMAL_TERMINATION) {
468 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessExitCode",
469 exit_code,
470 RESULT_CODE_LAST_CODE);
473 switch (status) {
474 case base::TERMINATION_STATUS_NORMAL_TERMINATION:
475 message = "The GPU process exited normally. Everything is okay.";
476 break;
477 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
478 message = base::StringPrintf(
479 "The GPU process exited with code %d.",
480 exit_code);
481 break;
482 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED:
483 message = "You killed the GPU process! Why?";
484 break;
485 case base::TERMINATION_STATUS_PROCESS_CRASHED:
486 message = "The GPU process crashed!";
487 break;
488 default:
489 break;
493 BrowserThread::PostTask(BrowserThread::UI,
494 FROM_HERE,
495 base::Bind(&GpuProcessHostUIShim::Destroy,
496 host_id_,
497 message));
500 bool GpuProcessHost::Init() {
501 init_start_time_ = base::TimeTicks::Now();
503 TRACE_EVENT_INSTANT0("gpu", "LaunchGpuProcess", TRACE_EVENT_SCOPE_THREAD);
505 std::string channel_id = process_->GetHost()->CreateChannel();
506 if (channel_id.empty())
507 return false;
509 if (in_process_) {
510 DCHECK(g_gpu_main_thread_factory);
511 CommandLine* command_line = CommandLine::ForCurrentProcess();
512 command_line->AppendSwitch(switches::kDisableGpuWatchdog);
514 GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
515 DCHECK(gpu_data_manager);
516 gpu_data_manager->AppendGpuCommandLine(command_line);
518 in_process_gpu_thread_.reset(g_gpu_main_thread_factory(channel_id));
519 in_process_gpu_thread_->Start();
521 OnProcessLaunched(); // Fake a callback that the process is ready.
522 } else if (!LaunchGpuProcess(channel_id)) {
523 return false;
526 if (!Send(new GpuMsg_Initialize()))
527 return false;
529 return true;
532 void GpuProcessHost::RouteOnUIThread(const IPC::Message& message) {
533 BrowserThread::PostTask(
534 BrowserThread::UI,
535 FROM_HERE,
536 base::Bind(&RouteToGpuProcessHostUIShimTask, host_id_, message));
539 bool GpuProcessHost::Send(IPC::Message* msg) {
540 DCHECK(CalledOnValidThread());
541 if (process_->GetHost()->IsChannelOpening()) {
542 queued_messages_.push(msg);
543 return true;
546 bool result = process_->Send(msg);
547 if (!result) {
548 // Channel is hosed, but we may not get destroyed for a while. Send
549 // outstanding channel creation failures now so that the caller can restart
550 // with a new process/channel without waiting.
551 SendOutstandingReplies();
553 return result;
556 void GpuProcessHost::AddFilter(IPC::MessageFilter* filter) {
557 DCHECK(CalledOnValidThread());
558 process_->GetHost()->AddFilter(filter);
561 bool GpuProcessHost::OnMessageReceived(const IPC::Message& message) {
562 DCHECK(CalledOnValidThread());
563 IPC_BEGIN_MESSAGE_MAP(GpuProcessHost, message)
564 IPC_MESSAGE_HANDLER(GpuHostMsg_Initialized, OnInitialized)
565 IPC_MESSAGE_HANDLER(GpuHostMsg_ChannelEstablished, OnChannelEstablished)
566 IPC_MESSAGE_HANDLER(GpuHostMsg_CommandBufferCreated, OnCommandBufferCreated)
567 IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyCommandBuffer, OnDestroyCommandBuffer)
568 IPC_MESSAGE_HANDLER(GpuHostMsg_ImageCreated, OnImageCreated)
569 IPC_MESSAGE_HANDLER(GpuHostMsg_GpuMemoryBufferCreated,
570 OnGpuMemoryBufferCreated)
571 IPC_MESSAGE_HANDLER(GpuHostMsg_DidCreateOffscreenContext,
572 OnDidCreateOffscreenContext)
573 IPC_MESSAGE_HANDLER(GpuHostMsg_DidLoseContext, OnDidLoseContext)
574 IPC_MESSAGE_HANDLER(GpuHostMsg_DidDestroyOffscreenContext,
575 OnDidDestroyOffscreenContext)
576 IPC_MESSAGE_HANDLER(GpuHostMsg_GpuMemoryUmaStats,
577 OnGpuMemoryUmaStatsReceived)
578 #if defined(OS_MACOSX)
579 IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceBuffersSwapped,
580 OnAcceleratedSurfaceBuffersSwapped)
581 #endif
582 IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyChannel,
583 OnDestroyChannel)
584 IPC_MESSAGE_HANDLER(GpuHostMsg_CacheShader,
585 OnCacheShader)
587 IPC_MESSAGE_UNHANDLED(RouteOnUIThread(message))
588 IPC_END_MESSAGE_MAP()
590 return true;
593 void GpuProcessHost::OnChannelConnected(int32 peer_pid) {
594 TRACE_EVENT0("gpu", "GpuProcessHost::OnChannelConnected");
596 while (!queued_messages_.empty()) {
597 Send(queued_messages_.front());
598 queued_messages_.pop();
602 void GpuProcessHost::EstablishGpuChannel(
603 int client_id,
604 bool share_context,
605 bool allow_future_sync_points,
606 const EstablishChannelCallback& callback) {
607 DCHECK(CalledOnValidThread());
608 TRACE_EVENT0("gpu", "GpuProcessHost::EstablishGpuChannel");
610 // If GPU features are already blacklisted, no need to establish the channel.
611 if (!GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL)) {
612 DVLOG(1) << "GPU blacklisted, refusing to open a GPU channel.";
613 callback.Run(IPC::ChannelHandle(), gpu::GPUInfo());
614 return;
617 if (Send(new GpuMsg_EstablishChannel(
618 client_id, share_context, allow_future_sync_points))) {
619 channel_requests_.push(callback);
620 } else {
621 DVLOG(1) << "Failed to send GpuMsg_EstablishChannel.";
622 callback.Run(IPC::ChannelHandle(), gpu::GPUInfo());
625 if (!CommandLine::ForCurrentProcess()->HasSwitch(
626 switches::kDisableGpuShaderDiskCache)) {
627 CreateChannelCache(client_id);
631 void GpuProcessHost::CreateViewCommandBuffer(
632 const gfx::GLSurfaceHandle& compositing_surface,
633 int surface_id,
634 int client_id,
635 const GPUCreateCommandBufferConfig& init_params,
636 int route_id,
637 const CreateCommandBufferCallback& callback) {
638 TRACE_EVENT0("gpu", "GpuProcessHost::CreateViewCommandBuffer");
640 DCHECK(CalledOnValidThread());
642 if (!compositing_surface.is_null() &&
643 Send(new GpuMsg_CreateViewCommandBuffer(
644 compositing_surface, surface_id, client_id, init_params, route_id))) {
645 create_command_buffer_requests_.push(callback);
646 surface_refs_.insert(std::make_pair(surface_id,
647 GpuSurfaceTracker::GetInstance()->GetSurfaceRefForSurface(surface_id)));
648 } else {
649 // Could distinguish here between compositing_surface being NULL
650 // and Send failing, if desired.
651 callback.Run(CREATE_COMMAND_BUFFER_FAILED_AND_CHANNEL_LOST);
655 void GpuProcessHost::CreateImage(gfx::PluginWindowHandle window,
656 int client_id,
657 int image_id,
658 const CreateImageCallback& callback) {
659 TRACE_EVENT0("gpu", "GpuProcessHost::CreateImage");
661 DCHECK(CalledOnValidThread());
663 if (Send(new GpuMsg_CreateImage(window, client_id, image_id))) {
664 create_image_requests_.push(callback);
665 } else {
666 callback.Run(gfx::Size());
670 void GpuProcessHost::DeleteImage(int client_id,
671 int image_id,
672 int sync_point) {
673 TRACE_EVENT0("gpu", "GpuProcessHost::DeleteImage");
675 DCHECK(CalledOnValidThread());
677 Send(new GpuMsg_DeleteImage(client_id, image_id, sync_point));
680 void GpuProcessHost::CreateGpuMemoryBuffer(
681 const gfx::GpuMemoryBufferHandle& handle,
682 const gfx::Size& size,
683 unsigned internalformat,
684 unsigned usage,
685 const CreateGpuMemoryBufferCallback& callback) {
686 TRACE_EVENT0("gpu", "GpuProcessHost::CreateGpuMemoryBuffer");
688 DCHECK(CalledOnValidThread());
690 if (Send(new GpuMsg_CreateGpuMemoryBuffer(
691 handle, size, internalformat, usage))) {
692 create_gpu_memory_buffer_requests_.push(callback);
693 } else {
694 callback.Run(gfx::GpuMemoryBufferHandle());
698 void GpuProcessHost::DestroyGpuMemoryBuffer(
699 const gfx::GpuMemoryBufferHandle& handle,
700 int sync_point) {
701 TRACE_EVENT0("gpu", "GpuProcessHost::DestroyGpuMemoryBuffer");
703 DCHECK(CalledOnValidThread());
705 Send(new GpuMsg_DestroyGpuMemoryBuffer(handle, sync_point));
708 void GpuProcessHost::OnInitialized(bool result, const gpu::GPUInfo& gpu_info) {
709 UMA_HISTOGRAM_BOOLEAN("GPU.GPUProcessInitialized", result);
710 initialized_ = result;
712 if (!initialized_)
713 GpuDataManagerImpl::GetInstance()->OnGpuProcessInitFailure();
714 else if (!in_process_)
715 GpuDataManagerImpl::GetInstance()->UpdateGpuInfo(gpu_info);
718 void GpuProcessHost::OnChannelEstablished(
719 const IPC::ChannelHandle& channel_handle) {
720 TRACE_EVENT0("gpu", "GpuProcessHost::OnChannelEstablished");
722 if (channel_requests_.empty()) {
723 // This happens when GPU process is compromised.
724 RouteOnUIThread(GpuHostMsg_OnLogMessage(
725 logging::LOG_WARNING,
726 "WARNING",
727 "Received a ChannelEstablished message but no requests in queue."));
728 return;
730 EstablishChannelCallback callback = channel_requests_.front();
731 channel_requests_.pop();
733 // Currently if any of the GPU features are blacklisted, we don't establish a
734 // GPU channel.
735 if (!channel_handle.name.empty() &&
736 !GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL)) {
737 Send(new GpuMsg_CloseChannel(channel_handle));
738 callback.Run(IPC::ChannelHandle(), gpu::GPUInfo());
739 RouteOnUIThread(GpuHostMsg_OnLogMessage(
740 logging::LOG_WARNING,
741 "WARNING",
742 "Hardware acceleration is unavailable."));
743 return;
746 callback.Run(channel_handle,
747 GpuDataManagerImpl::GetInstance()->GetGPUInfo());
750 void GpuProcessHost::OnCommandBufferCreated(CreateCommandBufferResult result) {
751 TRACE_EVENT0("gpu", "GpuProcessHost::OnCommandBufferCreated");
753 if (create_command_buffer_requests_.empty())
754 return;
756 CreateCommandBufferCallback callback =
757 create_command_buffer_requests_.front();
758 create_command_buffer_requests_.pop();
759 callback.Run(result);
762 void GpuProcessHost::OnDestroyCommandBuffer(int32 surface_id) {
763 TRACE_EVENT0("gpu", "GpuProcessHost::OnDestroyCommandBuffer");
764 SurfaceRefMap::iterator it = surface_refs_.find(surface_id);
765 if (it != surface_refs_.end()) {
766 surface_refs_.erase(it);
770 void GpuProcessHost::OnImageCreated(const gfx::Size size) {
771 TRACE_EVENT0("gpu", "GpuProcessHost::OnImageCreated");
773 if (create_image_requests_.empty())
774 return;
776 CreateImageCallback callback = create_image_requests_.front();
777 create_image_requests_.pop();
778 callback.Run(size);
781 void GpuProcessHost::OnGpuMemoryBufferCreated(
782 const gfx::GpuMemoryBufferHandle& handle) {
783 TRACE_EVENT0("gpu", "GpuProcessHost::OnGpuMemoryBufferCreated");
785 if (create_gpu_memory_buffer_requests_.empty())
786 return;
788 CreateGpuMemoryBufferCallback callback =
789 create_gpu_memory_buffer_requests_.front();
790 create_gpu_memory_buffer_requests_.pop();
791 callback.Run(handle);
794 void GpuProcessHost::OnDidCreateOffscreenContext(const GURL& url) {
795 urls_with_live_offscreen_contexts_.insert(url);
798 void GpuProcessHost::OnDidLoseContext(bool offscreen,
799 gpu::error::ContextLostReason reason,
800 const GURL& url) {
801 // TODO(kbr): would be nice to see the "offscreen" flag too.
802 TRACE_EVENT2("gpu", "GpuProcessHost::OnDidLoseContext",
803 "reason", reason,
804 "url",
805 url.possibly_invalid_spec());
807 if (!offscreen || url.is_empty()) {
808 // Assume that the loss of the compositor's or accelerated canvas'
809 // context is a serious event and blame the loss on all live
810 // offscreen contexts. This more robustly handles situations where
811 // the GPU process may not actually detect the context loss in the
812 // offscreen context.
813 BlockLiveOffscreenContexts();
814 return;
817 GpuDataManagerImpl::DomainGuilt guilt;
818 switch (reason) {
819 case gpu::error::kGuilty:
820 guilt = GpuDataManagerImpl::DOMAIN_GUILT_KNOWN;
821 break;
822 case gpu::error::kUnknown:
823 guilt = GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN;
824 break;
825 case gpu::error::kInnocent:
826 return;
827 default:
828 NOTREACHED();
829 return;
832 GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(url, guilt);
835 void GpuProcessHost::OnDidDestroyOffscreenContext(const GURL& url) {
836 urls_with_live_offscreen_contexts_.erase(url);
839 void GpuProcessHost::OnGpuMemoryUmaStatsReceived(
840 const GPUMemoryUmaStats& stats) {
841 TRACE_EVENT0("gpu", "GpuProcessHost::OnGpuMemoryUmaStatsReceived");
842 uma_memory_stats_received_ = true;
843 uma_memory_stats_ = stats;
846 #if defined(OS_MACOSX)
847 void GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped(
848 const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params) {
849 TRACE_EVENT0("gpu", "GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped");
851 if (!ui::LatencyInfo::Verify(params.latency_info,
852 "GpuHostMsg_AcceleratedSurfaceBuffersSwapped"))
853 return;
855 gfx::AcceleratedWidget native_widget =
856 GpuSurfaceTracker::Get()->AcquireNativeWidget(params.surface_id);
857 if (native_widget) {
858 RenderWidgetHelper::OnNativeSurfaceBuffersSwappedOnIOThread(this, params);
859 return;
862 gfx::GLSurfaceHandle surface_handle =
863 GpuSurfaceTracker::Get()->GetSurfaceHandle(params.surface_id);
864 // Compositor window is always gfx::kNullPluginWindow.
865 // TODO(jbates) http://crbug.com/105344 This will be removed when there are no
866 // plugin windows.
867 if (surface_handle.handle != gfx::kNullPluginWindow ||
868 surface_handle.transport_type == gfx::TEXTURE_TRANSPORT) {
869 RouteOnUIThread(GpuHostMsg_AcceleratedSurfaceBuffersSwapped(params));
870 return;
873 AcceleratedSurfaceMsg_BufferPresented_Params ack_params;
874 ack_params.sync_point = 0;
876 int render_process_id = 0;
877 int render_widget_id = 0;
878 if (!GpuSurfaceTracker::Get()->GetRenderWidgetIDForSurface(
879 params.surface_id, &render_process_id, &render_widget_id)) {
880 Send(new AcceleratedSurfaceMsg_BufferPresented(params.route_id,
881 ack_params));
882 return;
884 RenderWidgetHelper* helper =
885 RenderWidgetHelper::FromProcessHostID(render_process_id);
886 if (!helper) {
887 Send(new AcceleratedSurfaceMsg_BufferPresented(params.route_id,
888 ack_params));
889 return;
892 // Pass the SwapBuffers on to the RenderWidgetHelper to wake up the UI thread
893 // if the browser is waiting for a new frame. Otherwise the RenderWidgetHelper
894 // will forward to the RenderWidgetHostView via RenderProcessHostImpl and
895 // RenderWidgetHostImpl.
896 ViewHostMsg_CompositorSurfaceBuffersSwapped_Params view_params;
897 view_params.surface_id = params.surface_id;
898 view_params.surface_handle = params.surface_handle;
899 view_params.route_id = params.route_id;
900 view_params.size = params.size;
901 view_params.scale_factor = params.scale_factor;
902 view_params.gpu_process_host_id = host_id_;
903 view_params.latency_info = params.latency_info;
904 helper->DidReceiveBackingStoreMsg(ViewHostMsg_CompositorSurfaceBuffersSwapped(
905 render_widget_id,
906 view_params));
908 #endif // OS_MACOSX
910 void GpuProcessHost::OnProcessLaunched() {
911 UMA_HISTOGRAM_TIMES("GPU.GPUProcessLaunchTime",
912 base::TimeTicks::Now() - init_start_time_);
915 void GpuProcessHost::OnProcessCrashed(int exit_code) {
916 SendOutstandingReplies();
917 GpuDataManagerImpl::GetInstance()->ProcessCrashed(
918 process_->GetTerminationStatus(true /* known_dead */, NULL));
921 GpuProcessHost::GpuProcessKind GpuProcessHost::kind() {
922 return kind_;
925 void GpuProcessHost::ForceShutdown() {
926 // This is only called on the IO thread so no race against the constructor
927 // for another GpuProcessHost.
928 if (g_gpu_process_hosts[kind_] == this)
929 g_gpu_process_hosts[kind_] = NULL;
931 process_->ForceShutdown();
934 void GpuProcessHost::BeginFrameSubscription(
935 int surface_id,
936 base::WeakPtr<RenderWidgetHostViewFrameSubscriber> subscriber) {
937 frame_subscribers_[surface_id] = subscriber;
940 void GpuProcessHost::EndFrameSubscription(int surface_id) {
941 frame_subscribers_.erase(surface_id);
944 bool GpuProcessHost::LaunchGpuProcess(const std::string& channel_id) {
945 if (!(gpu_enabled_ &&
946 GpuDataManagerImpl::GetInstance()->ShouldUseSwiftShader()) &&
947 !hardware_gpu_enabled_) {
948 SendOutstandingReplies();
949 return false;
952 const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
954 CommandLine::StringType gpu_launcher =
955 browser_command_line.GetSwitchValueNative(switches::kGpuLauncher);
957 #if defined(OS_LINUX)
958 int child_flags = gpu_launcher.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
959 ChildProcessHost::CHILD_NORMAL;
960 #else
961 int child_flags = ChildProcessHost::CHILD_NORMAL;
962 #endif
964 base::FilePath exe_path = ChildProcessHost::GetChildPath(child_flags);
965 if (exe_path.empty())
966 return false;
968 CommandLine* cmd_line = new CommandLine(exe_path);
969 cmd_line->AppendSwitchASCII(switches::kProcessType, switches::kGpuProcess);
970 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
972 if (kind_ == GPU_PROCESS_KIND_UNSANDBOXED)
973 cmd_line->AppendSwitch(switches::kDisableGpuSandbox);
975 // Propagate relevant command line switches.
976 static const char* const kSwitchNames[] = {
977 switches::kDisableAcceleratedVideoDecode,
978 switches::kDisableBreakpad,
979 switches::kDisableGpuSandbox,
980 switches::kDisableGpuWatchdog,
981 switches::kDisableLogging,
982 switches::kDisableSeccompFilterSandbox,
983 #if defined(ENABLE_WEBRTC)
984 switches::kDisableWebRtcHWEncoding,
985 #endif
986 switches::kEnableLogging,
987 switches::kEnableShareGroupAsyncTextureUpload,
988 #if defined(OS_CHROMEOS)
989 switches::kEnableVaapiAcceleratedVideoEncode,
990 #endif
991 switches::kGpuStartupDialog,
992 switches::kGpuSandboxAllowSysVShm,
993 switches::kGpuSandboxFailuresFatal,
994 switches::kGpuSandboxStartEarly,
995 switches::kIgnoreResolutionLimitsForAcceleratedVideoDecode,
996 switches::kLoggingLevel,
997 switches::kLowEndDeviceMode,
998 switches::kNoSandbox,
999 switches::kTestGLLib,
1000 switches::kTraceStartup,
1001 switches::kTraceToConsole,
1002 switches::kV,
1003 switches::kVModule,
1004 #if defined(OS_MACOSX)
1005 switches::kEnableSandboxLogging,
1006 #endif
1007 #if defined(USE_AURA)
1008 switches::kUIPrioritizeInGpuProcess,
1009 #endif
1010 #if defined(USE_OZONE)
1011 switches::kOzonePlatform,
1012 #endif
1013 #if defined(USE_X11) && !defined(OS_CHROMEOS)
1014 switches::kX11Display,
1015 #endif
1017 cmd_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1018 arraysize(kSwitchNames));
1019 cmd_line->CopySwitchesFrom(
1020 browser_command_line, switches::kGpuSwitches, switches::kNumGpuSwitches);
1021 cmd_line->CopySwitchesFrom(
1022 browser_command_line, switches::kGLSwitchesCopiedFromGpuProcessHost,
1023 switches::kGLSwitchesCopiedFromGpuProcessHostNumSwitches);
1025 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
1026 cmd_line, process_->GetData().id);
1028 GpuDataManagerImpl::GetInstance()->AppendGpuCommandLine(cmd_line);
1030 if (cmd_line->HasSwitch(switches::kUseGL)) {
1031 swiftshader_rendering_ =
1032 (cmd_line->GetSwitchValueASCII(switches::kUseGL) == "swiftshader");
1035 UMA_HISTOGRAM_BOOLEAN("GPU.GPU.GPUProcessSoftwareRendering",
1036 swiftshader_rendering_);
1038 // If specified, prepend a launcher program to the command line.
1039 if (!gpu_launcher.empty())
1040 cmd_line->PrependWrapper(gpu_launcher);
1042 process_->Launch(
1043 new GpuSandboxedProcessLauncherDelegate(cmd_line,
1044 process_->GetHost()),
1045 cmd_line);
1046 process_launched_ = true;
1048 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
1049 LAUNCHED, GPU_PROCESS_LIFETIME_EVENT_MAX);
1050 return true;
1053 void GpuProcessHost::SendOutstandingReplies() {
1054 valid_ = false;
1055 // First send empty channel handles for all EstablishChannel requests.
1056 while (!channel_requests_.empty()) {
1057 EstablishChannelCallback callback = channel_requests_.front();
1058 channel_requests_.pop();
1059 callback.Run(IPC::ChannelHandle(), gpu::GPUInfo());
1062 while (!create_command_buffer_requests_.empty()) {
1063 CreateCommandBufferCallback callback =
1064 create_command_buffer_requests_.front();
1065 create_command_buffer_requests_.pop();
1066 callback.Run(CREATE_COMMAND_BUFFER_FAILED_AND_CHANNEL_LOST);
1070 void GpuProcessHost::BlockLiveOffscreenContexts() {
1071 for (std::multiset<GURL>::iterator iter =
1072 urls_with_live_offscreen_contexts_.begin();
1073 iter != urls_with_live_offscreen_contexts_.end(); ++iter) {
1074 GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(
1075 *iter, GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN);
1079 std::string GpuProcessHost::GetShaderPrefixKey() {
1080 if (shader_prefix_key_.empty()) {
1081 gpu::GPUInfo info = GpuDataManagerImpl::GetInstance()->GetGPUInfo();
1083 std::string in_str = GetContentClient()->GetProduct() + "-" +
1084 info.gl_vendor + "-" + info.gl_renderer + "-" +
1085 info.driver_version + "-" + info.driver_vendor;
1087 base::Base64Encode(base::SHA1HashString(in_str), &shader_prefix_key_);
1090 return shader_prefix_key_;
1093 void GpuProcessHost::LoadedShader(const std::string& key,
1094 const std::string& data) {
1095 std::string prefix = GetShaderPrefixKey();
1096 if (!key.compare(0, prefix.length(), prefix))
1097 Send(new GpuMsg_LoadedShader(data));
1100 void GpuProcessHost::CreateChannelCache(int32 client_id) {
1101 TRACE_EVENT0("gpu", "GpuProcessHost::CreateChannelCache");
1103 scoped_refptr<ShaderDiskCache> cache =
1104 ShaderCacheFactory::GetInstance()->Get(client_id);
1105 if (!cache.get())
1106 return;
1108 cache->set_host_id(host_id_);
1110 client_id_to_shader_cache_[client_id] = cache;
1113 void GpuProcessHost::OnDestroyChannel(int32 client_id) {
1114 TRACE_EVENT0("gpu", "GpuProcessHost::OnDestroyChannel");
1115 client_id_to_shader_cache_.erase(client_id);
1118 void GpuProcessHost::OnCacheShader(int32 client_id,
1119 const std::string& key,
1120 const std::string& shader) {
1121 TRACE_EVENT0("gpu", "GpuProcessHost::OnCacheShader");
1122 ClientIdToShaderCacheMap::iterator iter =
1123 client_id_to_shader_cache_.find(client_id);
1124 // If the cache doesn't exist then this is an off the record profile.
1125 if (iter == client_id_to_shader_cache_.end())
1126 return;
1127 iter->second->Cache(GetShaderPrefixKey() + ":" + key, shader);
1130 } // namespace content