Revert 268405 "Make sure that ScratchBuffer::Allocate() always r..."
[chromium-blink-merge.git] / content / browser / gpu / gpu_process_host.cc
blob008987a4aca3cfdd4aafb11a9c13870fa229056b
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 "ui/events/latency_info.h"
42 #include "ui/gl/gl_switches.h"
45 #if defined(OS_WIN)
46 #include "base/win/windows_version.h"
47 #include "content/common/sandbox_win.h"
48 #include "sandbox/win/src/sandbox_policy.h"
49 #include "ui/gfx/switches.h"
50 #endif
52 #if defined(USE_OZONE)
53 #include "ui/ozone/ozone_switches.h"
54 #endif
56 namespace content {
58 bool GpuProcessHost::gpu_enabled_ = true;
59 bool GpuProcessHost::hardware_gpu_enabled_ = true;
61 namespace {
63 enum GPUProcessLifetimeEvent {
64 LAUNCHED,
65 DIED_FIRST_TIME,
66 DIED_SECOND_TIME,
67 DIED_THIRD_TIME,
68 DIED_FOURTH_TIME,
69 GPU_PROCESS_LIFETIME_EVENT_MAX = 100
72 // Indexed by GpuProcessKind. There is one of each kind maximum. This array may
73 // only be accessed from the IO thread.
74 GpuProcessHost* g_gpu_process_hosts[GpuProcessHost::GPU_PROCESS_KIND_COUNT];
77 void SendGpuProcessMessage(GpuProcessHost::GpuProcessKind kind,
78 CauseForGpuLaunch cause,
79 IPC::Message* message) {
80 GpuProcessHost* host = GpuProcessHost::Get(kind, cause);
81 if (host) {
82 host->Send(message);
83 } else {
84 delete message;
88 // NOTE: changes to this class need to be reviewed by the security team.
89 class GpuSandboxedProcessLauncherDelegate
90 : public SandboxedProcessLauncherDelegate {
91 public:
92 GpuSandboxedProcessLauncherDelegate(CommandLine* cmd_line,
93 ChildProcessHost* host)
94 #if defined(OS_WIN)
95 : cmd_line_(cmd_line) {}
96 #elif defined(OS_POSIX)
97 : ipc_fd_(host->TakeClientFileDescriptor()) {}
98 #endif
100 virtual ~GpuSandboxedProcessLauncherDelegate() {}
102 #if defined(OS_WIN)
103 virtual bool ShouldSandbox() OVERRIDE {
104 bool sandbox = !cmd_line_->HasSwitch(switches::kDisableGpuSandbox);
105 if(! sandbox) {
106 DVLOG(1) << "GPU sandbox is disabled";
108 return sandbox;
111 virtual void PreSandbox(bool* disable_default_policy,
112 base::FilePath* exposed_dir) OVERRIDE {
113 *disable_default_policy = true;
116 // For the GPU process we gotten as far as USER_LIMITED. The next level
117 // which is USER_RESTRICTED breaks both the DirectX backend and the OpenGL
118 // backend. Note that the GPU process is connected to the interactive
119 // desktop.
120 virtual void PreSpawnTarget(sandbox::TargetPolicy* policy,
121 bool* success) {
122 if (base::win::GetVersion() > base::win::VERSION_XP) {
123 if (cmd_line_->GetSwitchValueASCII(switches::kUseGL) ==
124 gfx::kGLImplementationDesktopName) {
125 // Open GL path.
126 policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
127 sandbox::USER_LIMITED);
128 SetJobLevel(*cmd_line_, sandbox::JOB_UNPROTECTED, 0, policy);
129 policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
130 } else {
131 policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
132 sandbox::USER_LIMITED);
134 // UI restrictions break when we access Windows from outside our job.
135 // However, we don't want a proxy window in this process because it can
136 // introduce deadlocks where the renderer blocks on the gpu, which in
137 // turn blocks on the browser UI thread. So, instead we forgo a window
138 // message pump entirely and just add job restrictions to prevent child
139 // processes.
140 SetJobLevel(*cmd_line_,
141 sandbox::JOB_LIMITED_USER,
142 JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS |
143 JOB_OBJECT_UILIMIT_DESKTOP |
144 JOB_OBJECT_UILIMIT_EXITWINDOWS |
145 JOB_OBJECT_UILIMIT_DISPLAYSETTINGS,
146 policy);
148 policy->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
150 } else {
151 SetJobLevel(*cmd_line_, sandbox::JOB_UNPROTECTED, 0, policy);
152 policy->SetTokenLevel(sandbox::USER_UNPROTECTED,
153 sandbox::USER_LIMITED);
156 // Allow the server side of GPU sockets, which are pipes that have
157 // the "chrome.gpu" namespace and an arbitrary suffix.
158 sandbox::ResultCode result = policy->AddRule(
159 sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
160 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
161 L"\\\\.\\pipe\\chrome.gpu.*");
162 if (result != sandbox::SBOX_ALL_OK) {
163 *success = false;
164 return;
167 // Block this DLL even if it is not loaded by the browser process.
168 policy->AddDllToUnload(L"cmsetac.dll");
170 #ifdef USE_AURA
171 // GPU also needs to add sections to the browser for aura
172 // TODO(jschuh): refactor the GPU channel to remove this. crbug.com/128786
173 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
174 sandbox::TargetPolicy::HANDLES_DUP_BROKER,
175 L"Section");
176 if (result != sandbox::SBOX_ALL_OK) {
177 *success = false;
178 return;
180 #endif
182 if (cmd_line_->HasSwitch(switches::kEnableLogging)) {
183 base::string16 log_file_path = logging::GetLogFileFullPath();
184 if (!log_file_path.empty()) {
185 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
186 sandbox::TargetPolicy::FILES_ALLOW_ANY,
187 log_file_path.c_str());
188 if (result != sandbox::SBOX_ALL_OK) {
189 *success = false;
190 return;
195 #elif defined(OS_POSIX)
197 virtual int GetIpcFd() OVERRIDE {
198 return ipc_fd_;
200 #endif // OS_WIN
202 private:
203 #if defined(OS_WIN)
204 CommandLine* cmd_line_;
205 #elif defined(OS_POSIX)
206 int ipc_fd_;
207 #endif // OS_WIN
210 } // anonymous namespace
212 // static
213 bool GpuProcessHost::ValidateHost(GpuProcessHost* host) {
214 // The Gpu process is invalid if it's not using SwiftShader, the card is
215 // blacklisted, and we can kill it and start over.
216 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess) ||
217 CommandLine::ForCurrentProcess()->HasSwitch(switches::kInProcessGPU) ||
218 (host->valid_ &&
219 (host->swiftshader_rendering_ ||
220 !GpuDataManagerImpl::GetInstance()->ShouldUseSwiftShader()))) {
221 return true;
224 host->ForceShutdown();
225 return false;
228 // static
229 GpuProcessHost* GpuProcessHost::Get(GpuProcessKind kind,
230 CauseForGpuLaunch cause) {
231 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
233 // Don't grant further access to GPU if it is not allowed.
234 GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
235 DCHECK(gpu_data_manager);
236 if (!gpu_data_manager->GpuAccessAllowed(NULL))
237 return NULL;
239 if (g_gpu_process_hosts[kind] && ValidateHost(g_gpu_process_hosts[kind]))
240 return g_gpu_process_hosts[kind];
242 if (cause == CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH)
243 return NULL;
245 static int last_host_id = 0;
246 int host_id;
247 host_id = ++last_host_id;
249 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLaunchCause",
250 cause,
251 CAUSE_FOR_GPU_LAUNCH_MAX_ENUM);
253 GpuProcessHost* host = new GpuProcessHost(host_id, kind);
254 if (host->Init())
255 return host;
257 delete host;
258 return NULL;
261 // static
262 void GpuProcessHost::GetProcessHandles(
263 const GpuDataManager::GetGpuProcessHandlesCallback& callback) {
264 if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
265 BrowserThread::PostTask(
266 BrowserThread::IO,
267 FROM_HERE,
268 base::Bind(&GpuProcessHost::GetProcessHandles, callback));
269 return;
271 std::list<base::ProcessHandle> handles;
272 for (size_t i = 0; i < arraysize(g_gpu_process_hosts); ++i) {
273 GpuProcessHost* host = g_gpu_process_hosts[i];
274 if (host && ValidateHost(host))
275 handles.push_back(host->process_->GetHandle());
277 BrowserThread::PostTask(
278 BrowserThread::UI,
279 FROM_HERE,
280 base::Bind(callback, handles));
283 // static
284 void GpuProcessHost::SendOnIO(GpuProcessKind kind,
285 CauseForGpuLaunch cause,
286 IPC::Message* message) {
287 if (!BrowserThread::PostTask(
288 BrowserThread::IO, FROM_HERE,
289 base::Bind(
290 &SendGpuProcessMessage, kind, cause, message))) {
291 delete message;
295 GpuMainThreadFactoryFunction g_gpu_main_thread_factory = NULL;
297 void GpuProcessHost::RegisterGpuMainThreadFactory(
298 GpuMainThreadFactoryFunction create) {
299 g_gpu_main_thread_factory = create;
302 // static
303 GpuProcessHost* GpuProcessHost::FromID(int host_id) {
304 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
306 for (int i = 0; i < GPU_PROCESS_KIND_COUNT; ++i) {
307 GpuProcessHost* host = g_gpu_process_hosts[i];
308 if (host && host->host_id_ == host_id && ValidateHost(host))
309 return host;
312 return NULL;
315 GpuProcessHost::GpuProcessHost(int host_id, GpuProcessKind kind)
316 : host_id_(host_id),
317 valid_(true),
318 in_process_(false),
319 swiftshader_rendering_(false),
320 kind_(kind),
321 process_launched_(false),
322 initialized_(false),
323 uma_memory_stats_received_(false) {
324 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess) ||
325 CommandLine::ForCurrentProcess()->HasSwitch(switches::kInProcessGPU)) {
326 in_process_ = true;
329 // If the 'single GPU process' policy ever changes, we still want to maintain
330 // it for 'gpu thread' mode and only create one instance of host and thread.
331 DCHECK(!in_process_ || g_gpu_process_hosts[kind] == NULL);
333 g_gpu_process_hosts[kind] = this;
335 // Post a task to create the corresponding GpuProcessHostUIShim. The
336 // GpuProcessHostUIShim will be destroyed if either the browser exits,
337 // in which case it calls GpuProcessHostUIShim::DestroyAll, or the
338 // GpuProcessHost is destroyed, which happens when the corresponding GPU
339 // process terminates or fails to launch.
340 BrowserThread::PostTask(
341 BrowserThread::UI,
342 FROM_HERE,
343 base::Bind(base::IgnoreResult(&GpuProcessHostUIShim::Create), host_id));
345 process_.reset(new BrowserChildProcessHostImpl(PROCESS_TYPE_GPU, this));
348 GpuProcessHost::~GpuProcessHost() {
349 DCHECK(CalledOnValidThread());
351 SendOutstandingReplies();
353 // Maximum number of times the gpu process is allowed to crash in a session.
354 // Once this limit is reached, any request to launch the gpu process will
355 // fail.
356 const int kGpuMaxCrashCount = 3;
358 // Number of times the gpu process has crashed in the current browser session.
359 static int gpu_crash_count = 0;
360 static int gpu_recent_crash_count = 0;
361 static base::Time last_gpu_crash_time;
362 static bool crashed_before = false;
363 static int swiftshader_crash_count = 0;
365 bool disable_crash_limit = CommandLine::ForCurrentProcess()->HasSwitch(
366 switches::kDisableGpuProcessCrashLimit);
368 // Ending only acts as a failure if the GPU process was actually started and
369 // was intended for actual rendering (and not just checking caps or other
370 // options).
371 if (process_launched_ && kind_ == GPU_PROCESS_KIND_SANDBOXED) {
372 if (swiftshader_rendering_) {
373 UMA_HISTOGRAM_ENUMERATION("GPU.SwiftShaderLifetimeEvents",
374 DIED_FIRST_TIME + swiftshader_crash_count,
375 GPU_PROCESS_LIFETIME_EVENT_MAX);
377 if (++swiftshader_crash_count >= kGpuMaxCrashCount &&
378 !disable_crash_limit) {
379 // SwiftShader is too unstable to use. Disable it for current session.
380 gpu_enabled_ = false;
382 } else {
383 ++gpu_crash_count;
384 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
385 std::min(DIED_FIRST_TIME + gpu_crash_count,
386 GPU_PROCESS_LIFETIME_EVENT_MAX - 1),
387 GPU_PROCESS_LIFETIME_EVENT_MAX);
389 // Allow about 1 GPU crash per hour to be removed from the crash count,
390 // so very occasional crashes won't eventually add up and prevent the
391 // GPU process from launching.
392 ++gpu_recent_crash_count;
393 base::Time current_time = base::Time::Now();
394 if (crashed_before) {
395 int hours_different = (current_time - last_gpu_crash_time).InHours();
396 gpu_recent_crash_count =
397 std::max(0, gpu_recent_crash_count - hours_different);
400 crashed_before = true;
401 last_gpu_crash_time = current_time;
403 if ((gpu_recent_crash_count >= kGpuMaxCrashCount && !disable_crash_limit)
404 || !initialized_) {
405 #if !defined(OS_CHROMEOS)
406 // The gpu process is too unstable to use. Disable it for current
407 // session.
408 hardware_gpu_enabled_ = false;
409 GpuDataManagerImpl::GetInstance()->DisableHardwareAcceleration();
410 #endif
415 // In case we never started, clean up.
416 while (!queued_messages_.empty()) {
417 delete queued_messages_.front();
418 queued_messages_.pop();
421 // This is only called on the IO thread so no race against the constructor
422 // for another GpuProcessHost.
423 if (g_gpu_process_hosts[kind_] == this)
424 g_gpu_process_hosts[kind_] = NULL;
426 // If there are any remaining offscreen contexts at the point the
427 // GPU process exits, assume something went wrong, and block their
428 // URLs from accessing client 3D APIs without prompting.
429 BlockLiveOffscreenContexts();
431 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitSurfaceCount",
432 GpuSurfaceTracker::Get()->GetSurfaceCount());
433 UMA_HISTOGRAM_BOOLEAN("GPU.AtExitReceivedMemoryStats",
434 uma_memory_stats_received_);
436 if (uma_memory_stats_received_) {
437 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitManagedMemoryClientCount",
438 uma_memory_stats_.client_count);
439 UMA_HISTOGRAM_COUNTS_100("GPU.AtExitContextGroupCount",
440 uma_memory_stats_.context_group_count);
441 UMA_HISTOGRAM_CUSTOM_COUNTS(
442 "GPU.AtExitMBytesAllocated",
443 uma_memory_stats_.bytes_allocated_current / 1024 / 1024, 1, 2000, 50);
444 UMA_HISTOGRAM_CUSTOM_COUNTS(
445 "GPU.AtExitMBytesAllocatedMax",
446 uma_memory_stats_.bytes_allocated_max / 1024 / 1024, 1, 2000, 50);
447 UMA_HISTOGRAM_CUSTOM_COUNTS(
448 "GPU.AtExitMBytesLimit",
449 uma_memory_stats_.bytes_limit / 1024 / 1024, 1, 2000, 50);
452 std::string message;
453 if (!in_process_) {
454 int exit_code;
455 base::TerminationStatus status = process_->GetTerminationStatus(
456 false /* known_dead */, &exit_code);
457 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessTerminationStatus",
458 status,
459 base::TERMINATION_STATUS_MAX_ENUM);
461 if (status == base::TERMINATION_STATUS_NORMAL_TERMINATION ||
462 status == base::TERMINATION_STATUS_ABNORMAL_TERMINATION) {
463 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessExitCode",
464 exit_code,
465 RESULT_CODE_LAST_CODE);
468 switch (status) {
469 case base::TERMINATION_STATUS_NORMAL_TERMINATION:
470 message = "The GPU process exited normally. Everything is okay.";
471 break;
472 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
473 message = base::StringPrintf(
474 "The GPU process exited with code %d.",
475 exit_code);
476 break;
477 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED:
478 message = "You killed the GPU process! Why?";
479 break;
480 case base::TERMINATION_STATUS_PROCESS_CRASHED:
481 message = "The GPU process crashed!";
482 break;
483 default:
484 break;
488 BrowserThread::PostTask(BrowserThread::UI,
489 FROM_HERE,
490 base::Bind(&GpuProcessHostUIShim::Destroy,
491 host_id_,
492 message));
495 bool GpuProcessHost::Init() {
496 init_start_time_ = base::TimeTicks::Now();
498 TRACE_EVENT_INSTANT0("gpu", "LaunchGpuProcess", TRACE_EVENT_SCOPE_THREAD);
500 std::string channel_id = process_->GetHost()->CreateChannel();
501 if (channel_id.empty())
502 return false;
504 if (in_process_) {
505 DCHECK(g_gpu_main_thread_factory);
506 CommandLine* command_line = CommandLine::ForCurrentProcess();
507 command_line->AppendSwitch(switches::kDisableGpuWatchdog);
509 GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
510 DCHECK(gpu_data_manager);
511 gpu_data_manager->AppendGpuCommandLine(command_line);
513 in_process_gpu_thread_.reset(g_gpu_main_thread_factory(channel_id));
514 in_process_gpu_thread_->Start();
516 OnProcessLaunched(); // Fake a callback that the process is ready.
517 } else if (!LaunchGpuProcess(channel_id)) {
518 return false;
521 if (!Send(new GpuMsg_Initialize()))
522 return false;
524 return true;
527 void GpuProcessHost::RouteOnUIThread(const IPC::Message& message) {
528 BrowserThread::PostTask(
529 BrowserThread::UI,
530 FROM_HERE,
531 base::Bind(&RouteToGpuProcessHostUIShimTask, host_id_, message));
534 bool GpuProcessHost::Send(IPC::Message* msg) {
535 DCHECK(CalledOnValidThread());
536 if (process_->GetHost()->IsChannelOpening()) {
537 queued_messages_.push(msg);
538 return true;
541 bool result = process_->Send(msg);
542 if (!result) {
543 // Channel is hosed, but we may not get destroyed for a while. Send
544 // outstanding channel creation failures now so that the caller can restart
545 // with a new process/channel without waiting.
546 SendOutstandingReplies();
548 return result;
551 void GpuProcessHost::AddFilter(IPC::MessageFilter* filter) {
552 DCHECK(CalledOnValidThread());
553 process_->GetHost()->AddFilter(filter);
556 bool GpuProcessHost::OnMessageReceived(const IPC::Message& message) {
557 DCHECK(CalledOnValidThread());
558 IPC_BEGIN_MESSAGE_MAP(GpuProcessHost, message)
559 IPC_MESSAGE_HANDLER(GpuHostMsg_Initialized, OnInitialized)
560 IPC_MESSAGE_HANDLER(GpuHostMsg_ChannelEstablished, OnChannelEstablished)
561 IPC_MESSAGE_HANDLER(GpuHostMsg_CommandBufferCreated, OnCommandBufferCreated)
562 IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyCommandBuffer, OnDestroyCommandBuffer)
563 IPC_MESSAGE_HANDLER(GpuHostMsg_ImageCreated, OnImageCreated)
564 IPC_MESSAGE_HANDLER(GpuHostMsg_DidCreateOffscreenContext,
565 OnDidCreateOffscreenContext)
566 IPC_MESSAGE_HANDLER(GpuHostMsg_DidLoseContext, OnDidLoseContext)
567 IPC_MESSAGE_HANDLER(GpuHostMsg_DidDestroyOffscreenContext,
568 OnDidDestroyOffscreenContext)
569 IPC_MESSAGE_HANDLER(GpuHostMsg_GpuMemoryUmaStats,
570 OnGpuMemoryUmaStatsReceived)
571 #if defined(OS_MACOSX)
572 IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceBuffersSwapped,
573 OnAcceleratedSurfaceBuffersSwapped)
574 #endif
575 IPC_MESSAGE_HANDLER(GpuHostMsg_DestroyChannel,
576 OnDestroyChannel)
577 IPC_MESSAGE_HANDLER(GpuHostMsg_CacheShader,
578 OnCacheShader)
580 IPC_MESSAGE_UNHANDLED(RouteOnUIThread(message))
581 IPC_END_MESSAGE_MAP()
583 return true;
586 void GpuProcessHost::OnChannelConnected(int32 peer_pid) {
587 TRACE_EVENT0("gpu", "GpuProcessHost::OnChannelConnected");
589 while (!queued_messages_.empty()) {
590 Send(queued_messages_.front());
591 queued_messages_.pop();
595 void GpuProcessHost::EstablishGpuChannel(
596 int client_id,
597 bool share_context,
598 const EstablishChannelCallback& callback) {
599 DCHECK(CalledOnValidThread());
600 TRACE_EVENT0("gpu", "GpuProcessHost::EstablishGpuChannel");
602 // If GPU features are already blacklisted, no need to establish the channel.
603 if (!GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL)) {
604 DVLOG(1) << "GPU blacklisted, refusing to open a GPU channel.";
605 callback.Run(IPC::ChannelHandle(), gpu::GPUInfo());
606 return;
609 if (Send(new GpuMsg_EstablishChannel(client_id, share_context))) {
610 channel_requests_.push(callback);
611 } else {
612 DVLOG(1) << "Failed to send GpuMsg_EstablishChannel.";
613 callback.Run(IPC::ChannelHandle(), gpu::GPUInfo());
616 if (!CommandLine::ForCurrentProcess()->HasSwitch(
617 switches::kDisableGpuShaderDiskCache)) {
618 CreateChannelCache(client_id);
622 void GpuProcessHost::CreateViewCommandBuffer(
623 const gfx::GLSurfaceHandle& compositing_surface,
624 int surface_id,
625 int client_id,
626 const GPUCreateCommandBufferConfig& init_params,
627 int route_id,
628 const CreateCommandBufferCallback& callback) {
629 TRACE_EVENT0("gpu", "GpuProcessHost::CreateViewCommandBuffer");
631 DCHECK(CalledOnValidThread());
633 if (!compositing_surface.is_null() &&
634 Send(new GpuMsg_CreateViewCommandBuffer(
635 compositing_surface, surface_id, client_id, init_params, route_id))) {
636 create_command_buffer_requests_.push(callback);
637 surface_refs_.insert(std::make_pair(surface_id,
638 GpuSurfaceTracker::GetInstance()->GetSurfaceRefForSurface(surface_id)));
639 } else {
640 callback.Run(false);
644 void GpuProcessHost::CreateImage(gfx::PluginWindowHandle window,
645 int client_id,
646 int image_id,
647 const CreateImageCallback& callback) {
648 TRACE_EVENT0("gpu", "GpuProcessHost::CreateImage");
650 DCHECK(CalledOnValidThread());
652 if (Send(new GpuMsg_CreateImage(window, client_id, image_id))) {
653 create_image_requests_.push(callback);
654 } else {
655 callback.Run(gfx::Size());
659 void GpuProcessHost::DeleteImage(int client_id,
660 int image_id,
661 int sync_point) {
662 TRACE_EVENT0("gpu", "GpuProcessHost::DeleteImage");
664 DCHECK(CalledOnValidThread());
666 Send(new GpuMsg_DeleteImage(client_id, image_id, sync_point));
669 void GpuProcessHost::OnInitialized(bool result, const gpu::GPUInfo& gpu_info) {
670 UMA_HISTOGRAM_BOOLEAN("GPU.GPUProcessInitialized", result);
671 initialized_ = result;
673 if (!initialized_)
674 GpuDataManagerImpl::GetInstance()->OnGpuProcessInitFailure();
675 else if (!in_process_)
676 GpuDataManagerImpl::GetInstance()->UpdateGpuInfo(gpu_info);
679 void GpuProcessHost::OnChannelEstablished(
680 const IPC::ChannelHandle& channel_handle) {
681 TRACE_EVENT0("gpu", "GpuProcessHost::OnChannelEstablished");
683 if (channel_requests_.empty()) {
684 // This happens when GPU process is compromised.
685 RouteOnUIThread(GpuHostMsg_OnLogMessage(
686 logging::LOG_WARNING,
687 "WARNING",
688 "Received a ChannelEstablished message but no requests in queue."));
689 return;
691 EstablishChannelCallback callback = channel_requests_.front();
692 channel_requests_.pop();
694 // Currently if any of the GPU features are blacklisted, we don't establish a
695 // GPU channel.
696 if (!channel_handle.name.empty() &&
697 !GpuDataManagerImpl::GetInstance()->GpuAccessAllowed(NULL)) {
698 Send(new GpuMsg_CloseChannel(channel_handle));
699 callback.Run(IPC::ChannelHandle(), gpu::GPUInfo());
700 RouteOnUIThread(GpuHostMsg_OnLogMessage(
701 logging::LOG_WARNING,
702 "WARNING",
703 "Hardware acceleration is unavailable."));
704 return;
707 callback.Run(channel_handle,
708 GpuDataManagerImpl::GetInstance()->GetGPUInfo());
711 void GpuProcessHost::OnCommandBufferCreated(bool succeeded) {
712 TRACE_EVENT0("gpu", "GpuProcessHost::OnCommandBufferCreated");
714 if (create_command_buffer_requests_.empty())
715 return;
717 CreateCommandBufferCallback callback =
718 create_command_buffer_requests_.front();
719 create_command_buffer_requests_.pop();
720 callback.Run(succeeded);
723 void GpuProcessHost::OnDestroyCommandBuffer(int32 surface_id) {
724 TRACE_EVENT0("gpu", "GpuProcessHost::OnDestroyCommandBuffer");
725 SurfaceRefMap::iterator it = surface_refs_.find(surface_id);
726 if (it != surface_refs_.end()) {
727 surface_refs_.erase(it);
731 void GpuProcessHost::OnImageCreated(const gfx::Size size) {
732 TRACE_EVENT0("gpu", "GpuProcessHost::OnImageCreated");
734 if (create_image_requests_.empty())
735 return;
737 CreateImageCallback callback = create_image_requests_.front();
738 create_image_requests_.pop();
739 callback.Run(size);
742 void GpuProcessHost::OnDidCreateOffscreenContext(const GURL& url) {
743 urls_with_live_offscreen_contexts_.insert(url);
746 void GpuProcessHost::OnDidLoseContext(bool offscreen,
747 gpu::error::ContextLostReason reason,
748 const GURL& url) {
749 // TODO(kbr): would be nice to see the "offscreen" flag too.
750 TRACE_EVENT2("gpu", "GpuProcessHost::OnDidLoseContext",
751 "reason", reason,
752 "url",
753 url.possibly_invalid_spec());
755 if (!offscreen || url.is_empty()) {
756 // Assume that the loss of the compositor's or accelerated canvas'
757 // context is a serious event and blame the loss on all live
758 // offscreen contexts. This more robustly handles situations where
759 // the GPU process may not actually detect the context loss in the
760 // offscreen context.
761 BlockLiveOffscreenContexts();
762 return;
765 GpuDataManagerImpl::DomainGuilt guilt;
766 switch (reason) {
767 case gpu::error::kGuilty:
768 guilt = GpuDataManagerImpl::DOMAIN_GUILT_KNOWN;
769 break;
770 case gpu::error::kUnknown:
771 guilt = GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN;
772 break;
773 case gpu::error::kInnocent:
774 return;
775 default:
776 NOTREACHED();
777 return;
780 GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(url, guilt);
783 void GpuProcessHost::OnDidDestroyOffscreenContext(const GURL& url) {
784 urls_with_live_offscreen_contexts_.erase(url);
787 void GpuProcessHost::OnGpuMemoryUmaStatsReceived(
788 const GPUMemoryUmaStats& stats) {
789 TRACE_EVENT0("gpu", "GpuProcessHost::OnGpuMemoryUmaStatsReceived");
790 uma_memory_stats_received_ = true;
791 uma_memory_stats_ = stats;
794 #if defined(OS_MACOSX)
795 void GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped(
796 const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params) {
797 TRACE_EVENT0("gpu", "GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped");
799 if (!ui::LatencyInfo::Verify(params.latency_info,
800 "GpuHostMsg_AcceleratedSurfaceBuffersSwapped"))
801 return;
803 gfx::GLSurfaceHandle surface_handle =
804 GpuSurfaceTracker::Get()->GetSurfaceHandle(params.surface_id);
805 // Compositor window is always gfx::kNullPluginWindow.
806 // TODO(jbates) http://crbug.com/105344 This will be removed when there are no
807 // plugin windows.
808 if (surface_handle.handle != gfx::kNullPluginWindow ||
809 surface_handle.transport_type == gfx::TEXTURE_TRANSPORT) {
810 RouteOnUIThread(GpuHostMsg_AcceleratedSurfaceBuffersSwapped(params));
811 return;
814 AcceleratedSurfaceMsg_BufferPresented_Params ack_params;
815 ack_params.sync_point = 0;
817 int render_process_id = 0;
818 int render_widget_id = 0;
819 if (!GpuSurfaceTracker::Get()->GetRenderWidgetIDForSurface(
820 params.surface_id, &render_process_id, &render_widget_id)) {
821 Send(new AcceleratedSurfaceMsg_BufferPresented(params.route_id,
822 ack_params));
823 return;
825 RenderWidgetHelper* helper =
826 RenderWidgetHelper::FromProcessHostID(render_process_id);
827 if (!helper) {
828 Send(new AcceleratedSurfaceMsg_BufferPresented(params.route_id,
829 ack_params));
830 return;
833 // Pass the SwapBuffers on to the RenderWidgetHelper to wake up the UI thread
834 // if the browser is waiting for a new frame. Otherwise the RenderWidgetHelper
835 // will forward to the RenderWidgetHostView via RenderProcessHostImpl and
836 // RenderWidgetHostImpl.
837 ViewHostMsg_CompositorSurfaceBuffersSwapped_Params view_params;
838 view_params.surface_id = params.surface_id;
839 view_params.surface_handle = params.surface_handle;
840 view_params.route_id = params.route_id;
841 view_params.size = params.size;
842 view_params.scale_factor = params.scale_factor;
843 view_params.gpu_process_host_id = host_id_;
844 view_params.latency_info = params.latency_info;
845 helper->DidReceiveBackingStoreMsg(ViewHostMsg_CompositorSurfaceBuffersSwapped(
846 render_widget_id,
847 view_params));
849 #endif // OS_MACOSX
851 void GpuProcessHost::OnProcessLaunched() {
852 UMA_HISTOGRAM_TIMES("GPU.GPUProcessLaunchTime",
853 base::TimeTicks::Now() - init_start_time_);
856 void GpuProcessHost::OnProcessCrashed(int exit_code) {
857 SendOutstandingReplies();
858 GpuDataManagerImpl::GetInstance()->ProcessCrashed(
859 process_->GetTerminationStatus(true /* known_dead */, NULL));
862 GpuProcessHost::GpuProcessKind GpuProcessHost::kind() {
863 return kind_;
866 void GpuProcessHost::ForceShutdown() {
867 // This is only called on the IO thread so no race against the constructor
868 // for another GpuProcessHost.
869 if (g_gpu_process_hosts[kind_] == this)
870 g_gpu_process_hosts[kind_] = NULL;
872 process_->ForceShutdown();
875 void GpuProcessHost::BeginFrameSubscription(
876 int surface_id,
877 base::WeakPtr<RenderWidgetHostViewFrameSubscriber> subscriber) {
878 frame_subscribers_[surface_id] = subscriber;
881 void GpuProcessHost::EndFrameSubscription(int surface_id) {
882 frame_subscribers_.erase(surface_id);
885 bool GpuProcessHost::LaunchGpuProcess(const std::string& channel_id) {
886 if (!(gpu_enabled_ &&
887 GpuDataManagerImpl::GetInstance()->ShouldUseSwiftShader()) &&
888 !hardware_gpu_enabled_) {
889 SendOutstandingReplies();
890 return false;
893 const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
895 CommandLine::StringType gpu_launcher =
896 browser_command_line.GetSwitchValueNative(switches::kGpuLauncher);
898 #if defined(OS_LINUX)
899 int child_flags = gpu_launcher.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
900 ChildProcessHost::CHILD_NORMAL;
901 #else
902 int child_flags = ChildProcessHost::CHILD_NORMAL;
903 #endif
905 base::FilePath exe_path = ChildProcessHost::GetChildPath(child_flags);
906 if (exe_path.empty())
907 return false;
909 CommandLine* cmd_line = new CommandLine(exe_path);
910 cmd_line->AppendSwitchASCII(switches::kProcessType, switches::kGpuProcess);
911 cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
913 if (kind_ == GPU_PROCESS_KIND_UNSANDBOXED)
914 cmd_line->AppendSwitch(switches::kDisableGpuSandbox);
916 // Propagate relevant command line switches.
917 static const char* const kSwitchNames[] = {
918 switches::kDisableAcceleratedVideoDecode,
919 switches::kDisableBreakpad,
920 switches::kDisableGpuSandbox,
921 switches::kDisableGpuWatchdog,
922 switches::kDisableLogging,
923 switches::kDisableSeccompFilterSandbox,
924 #if defined(ENABLE_WEBRTC)
925 switches::kDisableWebRtcHWEncoding,
926 #endif
927 switches::kEnableLogging,
928 switches::kEnableShareGroupAsyncTextureUpload,
929 switches::kGpuStartupDialog,
930 switches::kGpuSandboxAllowSysVShm,
931 switches::kGpuSandboxFailuresFatal,
932 switches::kGpuSandboxStartAfterInitialization,
933 switches::kLoggingLevel,
934 switches::kNoSandbox,
935 switches::kTestGLLib,
936 switches::kTraceStartup,
937 switches::kV,
938 switches::kVModule,
939 #if defined(OS_MACOSX)
940 switches::kEnableSandboxLogging,
941 #endif
942 #if defined(USE_AURA)
943 switches::kUIPrioritizeInGpuProcess,
944 #endif
945 #if defined(USE_OZONE)
946 switches::kOzonePlatform,
947 #endif
948 #if defined(OS_WIN)
949 switches::kHighDPISupport,
950 #endif
952 cmd_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
953 arraysize(kSwitchNames));
954 cmd_line->CopySwitchesFrom(
955 browser_command_line, switches::kGpuSwitches, switches::kNumGpuSwitches);
956 cmd_line->CopySwitchesFrom(
957 browser_command_line, switches::kGLSwitchesCopiedFromGpuProcessHost,
958 switches::kGLSwitchesCopiedFromGpuProcessHostNumSwitches);
960 GetContentClient()->browser()->AppendExtraCommandLineSwitches(
961 cmd_line, process_->GetData().id);
963 GpuDataManagerImpl::GetInstance()->AppendGpuCommandLine(cmd_line);
965 if (cmd_line->HasSwitch(switches::kUseGL)) {
966 swiftshader_rendering_ =
967 (cmd_line->GetSwitchValueASCII(switches::kUseGL) == "swiftshader");
970 UMA_HISTOGRAM_BOOLEAN("GPU.GPU.GPUProcessSoftwareRendering",
971 swiftshader_rendering_);
973 // If specified, prepend a launcher program to the command line.
974 if (!gpu_launcher.empty())
975 cmd_line->PrependWrapper(gpu_launcher);
977 process_->Launch(
978 new GpuSandboxedProcessLauncherDelegate(cmd_line,
979 process_->GetHost()),
980 cmd_line);
981 process_launched_ = true;
983 UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
984 LAUNCHED, GPU_PROCESS_LIFETIME_EVENT_MAX);
985 return true;
988 void GpuProcessHost::SendOutstandingReplies() {
989 valid_ = false;
990 // First send empty channel handles for all EstablishChannel requests.
991 while (!channel_requests_.empty()) {
992 EstablishChannelCallback callback = channel_requests_.front();
993 channel_requests_.pop();
994 callback.Run(IPC::ChannelHandle(), gpu::GPUInfo());
997 while (!create_command_buffer_requests_.empty()) {
998 CreateCommandBufferCallback callback =
999 create_command_buffer_requests_.front();
1000 create_command_buffer_requests_.pop();
1001 callback.Run(false);
1005 void GpuProcessHost::BlockLiveOffscreenContexts() {
1006 for (std::multiset<GURL>::iterator iter =
1007 urls_with_live_offscreen_contexts_.begin();
1008 iter != urls_with_live_offscreen_contexts_.end(); ++iter) {
1009 GpuDataManagerImpl::GetInstance()->BlockDomainFrom3DAPIs(
1010 *iter, GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN);
1014 std::string GpuProcessHost::GetShaderPrefixKey() {
1015 if (shader_prefix_key_.empty()) {
1016 gpu::GPUInfo info = GpuDataManagerImpl::GetInstance()->GetGPUInfo();
1018 std::string in_str = GetContentClient()->GetProduct() + "-" +
1019 info.gl_vendor + "-" + info.gl_renderer + "-" +
1020 info.driver_version + "-" + info.driver_vendor;
1022 base::Base64Encode(base::SHA1HashString(in_str), &shader_prefix_key_);
1025 return shader_prefix_key_;
1028 void GpuProcessHost::LoadedShader(const std::string& key,
1029 const std::string& data) {
1030 std::string prefix = GetShaderPrefixKey();
1031 if (!key.compare(0, prefix.length(), prefix))
1032 Send(new GpuMsg_LoadedShader(data));
1035 void GpuProcessHost::CreateChannelCache(int32 client_id) {
1036 TRACE_EVENT0("gpu", "GpuProcessHost::CreateChannelCache");
1038 scoped_refptr<ShaderDiskCache> cache =
1039 ShaderCacheFactory::GetInstance()->Get(client_id);
1040 if (!cache.get())
1041 return;
1043 cache->set_host_id(host_id_);
1045 client_id_to_shader_cache_[client_id] = cache;
1048 void GpuProcessHost::OnDestroyChannel(int32 client_id) {
1049 TRACE_EVENT0("gpu", "GpuProcessHost::OnDestroyChannel");
1050 client_id_to_shader_cache_.erase(client_id);
1053 void GpuProcessHost::OnCacheShader(int32 client_id,
1054 const std::string& key,
1055 const std::string& shader) {
1056 TRACE_EVENT0("gpu", "GpuProcessHost::OnCacheShader");
1057 ClientIdToShaderCacheMap::iterator iter =
1058 client_id_to_shader_cache_.find(client_id);
1059 // If the cache doesn't exist then this is an off the record profile.
1060 if (iter == client_id_to_shader_cache_.end())
1061 return;
1062 iter->second->Cache(GetShaderPrefixKey() + ":" + key, shader);
1065 } // namespace content