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