Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / content / browser / gpu / gpu_data_manager_impl_private.cc
1 // Copyright (c) 2013 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_data_manager_impl_private.h"
6
7 #include "base/bind.h"
8 #include "base/bind_helpers.h"
9 #include "base/command_line.h"
10 #include "base/debug/trace_event.h"
11 #include "base/metrics/field_trial.h"
12 #include "base/metrics/histogram.h"
13 #include "base/metrics/sparse_histogram.h"
14 #include "base/strings/string_number_conversions.h"
15 #include "base/strings/stringprintf.h"
16 #include "base/sys_info.h"
17 #include "base/version.h"
18 #include "cc/base/switches.h"
19 #include "content/browser/gpu/gpu_process_host.h"
20 #include "content/common/gpu/gpu_messages.h"
21 #include "content/public/browser/browser_thread.h"
22 #include "content/public/browser/gpu_data_manager_observer.h"
23 #include "content/public/common/content_client.h"
24 #include "content/public/common/content_constants.h"
25 #include "content/public/common/content_switches.h"
26 #include "gpu/command_buffer/service/gpu_switches.h"
27 #include "gpu/config/gpu_control_list_jsons.h"
28 #include "gpu/config/gpu_driver_bug_workaround_type.h"
29 #include "gpu/config/gpu_feature_type.h"
30 #include "gpu/config/gpu_info_collector.h"
31 #include "gpu/config/gpu_util.h"
32 #include "ui/base/ui_base_switches.h"
33 #include "ui/gl/gl_implementation.h"
34 #include "ui/gl/gl_switches.h"
35 #include "ui/gl/gpu_switching_manager.h"
36 #include "webkit/common/webpreferences.h"
37
38 #if defined(OS_MACOSX)
39 #include <ApplicationServices/ApplicationServices.h>
40 #endif  // OS_MACOSX
41 #if defined(OS_WIN)
42 #include "base/win/windows_version.h"
43 #endif  // OS_WIN
44 #if defined(OS_ANDROID)
45 #include "ui/gfx/android/device_display_info.h"
46 #endif  // OS_ANDROID
47
48 namespace content {
49
50 namespace {
51
52 enum GpuFeatureStatus {
53     kGpuFeatureEnabled = 0,
54     kGpuFeatureBlacklisted = 1,
55     kGpuFeatureDisabled = 2,  // disabled by user but not blacklisted
56     kGpuFeatureNumStatus
57 };
58
59 #if defined(OS_WIN)
60
61 enum WinSubVersion {
62   kWinOthers = 0,
63   kWinXP,
64   kWinVista,
65   kWin7,
66   kWin8,
67   kNumWinSubVersions
68 };
69
70 int GetGpuBlacklistHistogramValueWin(GpuFeatureStatus status) {
71   static WinSubVersion sub_version = kNumWinSubVersions;
72   if (sub_version == kNumWinSubVersions) {
73     sub_version = kWinOthers;
74     std::string version_str = base::SysInfo::OperatingSystemVersion();
75     size_t pos = version_str.find_first_not_of("0123456789.");
76     if (pos != std::string::npos)
77       version_str = version_str.substr(0, pos);
78     Version os_version(version_str);
79     if (os_version.IsValid() && os_version.components().size() >= 2) {
80       const std::vector<uint16>& version_numbers = os_version.components();
81       if (version_numbers[0] == 5)
82         sub_version = kWinXP;
83       else if (version_numbers[0] == 6 && version_numbers[1] == 0)
84         sub_version = kWinVista;
85       else if (version_numbers[0] == 6 && version_numbers[1] == 1)
86         sub_version = kWin7;
87       else if (version_numbers[0] == 6 && version_numbers[1] == 2)
88         sub_version = kWin8;
89     }
90   }
91   int entry_index = static_cast<int>(sub_version) * kGpuFeatureNumStatus;
92   switch (status) {
93     case kGpuFeatureEnabled:
94       break;
95     case kGpuFeatureBlacklisted:
96       entry_index++;
97       break;
98     case kGpuFeatureDisabled:
99       entry_index += 2;
100       break;
101   }
102   return entry_index;
103 }
104 #endif  // OS_WIN
105
106 // Send UMA histograms about the enabled features and GPU properties.
107 void UpdateStats(const gpu::GPUInfo& gpu_info,
108                  const gpu::GpuBlacklist* blacklist,
109                  const std::set<int>& blacklisted_features) {
110   uint32 max_entry_id = blacklist->max_entry_id();
111   if (max_entry_id == 0) {
112     // GPU Blacklist was not loaded.  No need to go further.
113     return;
114   }
115
116   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
117   bool disabled = false;
118
119   // Use entry 0 to capture the total number of times that data
120   // was recorded in this histogram in order to have a convenient
121   // denominator to compute blacklist percentages for the rest of the
122   // entries.
123   UMA_HISTOGRAM_ENUMERATION("GPU.BlacklistTestResultsPerEntry",
124       0, max_entry_id + 1);
125
126   if (blacklisted_features.size() != 0) {
127     std::vector<uint32> flag_entries;
128     blacklist->GetDecisionEntries(&flag_entries, disabled);
129     DCHECK_GT(flag_entries.size(), 0u);
130     for (size_t i = 0; i < flag_entries.size(); ++i) {
131       UMA_HISTOGRAM_ENUMERATION("GPU.BlacklistTestResultsPerEntry",
132           flag_entries[i], max_entry_id + 1);
133     }
134   }
135
136   // This counts how many users are affected by a disabled entry - this allows
137   // us to understand the impact of an entry before enable it.
138   std::vector<uint32> flag_disabled_entries;
139   disabled = true;
140   blacklist->GetDecisionEntries(&flag_disabled_entries, disabled);
141   for (size_t i = 0; i < flag_disabled_entries.size(); ++i) {
142     UMA_HISTOGRAM_ENUMERATION("GPU.BlacklistTestResultsPerDisabledEntry",
143         flag_disabled_entries[i], max_entry_id + 1);
144   }
145
146   const gpu::GpuFeatureType kGpuFeatures[] = {
147       gpu::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS,
148       gpu::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING,
149       gpu::GPU_FEATURE_TYPE_WEBGL
150   };
151   const std::string kGpuBlacklistFeatureHistogramNames[] = {
152       "GPU.BlacklistFeatureTestResults.Accelerated2dCanvas",
153       "GPU.BlacklistFeatureTestResults.AcceleratedCompositing",
154       "GPU.BlacklistFeatureTestResults.Webgl",
155   };
156   const bool kGpuFeatureUserFlags[] = {
157       command_line.HasSwitch(switches::kDisableAccelerated2dCanvas),
158       command_line.HasSwitch(switches::kDisableAcceleratedCompositing),
159       command_line.HasSwitch(switches::kDisableExperimentalWebGL),
160   };
161 #if defined(OS_WIN)
162   const std::string kGpuBlacklistFeatureHistogramNamesWin[] = {
163       "GPU.BlacklistFeatureTestResultsWindows.Accelerated2dCanvas",
164       "GPU.BlacklistFeatureTestResultsWindows.AcceleratedCompositing",
165       "GPU.BlacklistFeatureTestResultsWindows.Webgl",
166   };
167 #endif
168   const size_t kNumFeatures =
169       sizeof(kGpuFeatures) / sizeof(gpu::GpuFeatureType);
170   for (size_t i = 0; i < kNumFeatures; ++i) {
171     // We can't use UMA_HISTOGRAM_ENUMERATION here because the same name is
172     // expected if the macro is used within a loop.
173     GpuFeatureStatus value = kGpuFeatureEnabled;
174     if (blacklisted_features.count(kGpuFeatures[i]))
175       value = kGpuFeatureBlacklisted;
176     else if (kGpuFeatureUserFlags[i])
177       value = kGpuFeatureDisabled;
178     base::HistogramBase* histogram_pointer = base::LinearHistogram::FactoryGet(
179         kGpuBlacklistFeatureHistogramNames[i],
180         1, kGpuFeatureNumStatus, kGpuFeatureNumStatus + 1,
181         base::HistogramBase::kUmaTargetedHistogramFlag);
182     histogram_pointer->Add(value);
183 #if defined(OS_WIN)
184     histogram_pointer = base::LinearHistogram::FactoryGet(
185         kGpuBlacklistFeatureHistogramNamesWin[i],
186         1, kNumWinSubVersions * kGpuFeatureNumStatus,
187         kNumWinSubVersions * kGpuFeatureNumStatus + 1,
188         base::HistogramBase::kUmaTargetedHistogramFlag);
189     histogram_pointer->Add(GetGpuBlacklistHistogramValueWin(value));
190 #endif
191   }
192
193   UMA_HISTOGRAM_SPARSE_SLOWLY("GPU.GLResetNotificationStrategy",
194       gpu_info.gl_reset_notification_strategy);
195 }
196
197 // Combine the integers into a string, seperated by ','.
198 std::string IntSetToString(const std::set<int>& list) {
199   std::string rt;
200   for (std::set<int>::const_iterator it = list.begin();
201        it != list.end(); ++it) {
202     if (!rt.empty())
203       rt += ",";
204     rt += base::IntToString(*it);
205   }
206   return rt;
207 }
208
209 #if defined(OS_MACOSX)
210 void DisplayReconfigCallback(CGDirectDisplayID display,
211                              CGDisplayChangeSummaryFlags flags,
212                              void* gpu_data_manager) {
213   if (flags == kCGDisplayBeginConfigurationFlag)
214     return; // This call contains no information about the display change
215
216   GpuDataManagerImpl* manager =
217       reinterpret_cast<GpuDataManagerImpl*>(gpu_data_manager);
218   DCHECK(manager);
219
220   uint32_t displayCount;
221   CGGetActiveDisplayList(0, NULL, &displayCount);
222
223   bool fireGpuSwitch = flags & kCGDisplayAddFlag;
224
225   if (displayCount != manager->GetDisplayCount()) {
226     manager->SetDisplayCount(displayCount);
227     fireGpuSwitch = true;
228   }
229
230   if (fireGpuSwitch)
231     manager->HandleGpuSwitch();
232 }
233 #endif  // OS_MACOSX
234
235 #if defined(OS_ANDROID)
236 void ApplyAndroidWorkarounds(const gpu::GPUInfo& gpu_info,
237                              CommandLine* command_line) {
238   std::string vendor(StringToLowerASCII(gpu_info.gl_vendor));
239   std::string renderer(StringToLowerASCII(gpu_info.gl_renderer));
240   bool is_img =
241       gpu_info.gl_vendor.find("Imagination") != std::string::npos;
242
243   gfx::DeviceDisplayInfo info;
244   int default_tile_size = 256;
245
246   // TODO(epenner): Now that this is somewhat generic, maybe we can
247   // unify this for all platforms (http://crbug.com/159524)
248
249   bool real_size_supported = true;
250   int display_width = info.GetPhysicalDisplayWidth();
251   int display_height = info.GetPhysicalDisplayHeight();
252   if (display_width == 0 || display_height == 0) {
253     real_size_supported = false;
254     display_width = info.GetDisplayWidth();
255     display_height = info.GetDisplayHeight();
256   }
257
258   int portrait_width = std::min(display_width, display_height);
259   int landscape_width = std::max(display_width, display_height);
260
261   if (real_size_supported) {
262     // Maximum HD dimensions should be 768x1280
263     // Maximum FHD dimensions should be 1200x1920
264     if (portrait_width > 768 || landscape_width > 1280)
265        default_tile_size = 384;
266     if (portrait_width > 1200 || landscape_width > 1920)
267        default_tile_size = 512;
268
269     // Adjust for some resolutions that barely straddle an extra
270     // tile when in portrait mode. This helps worst case scroll/raster
271     // by not needing a full extra tile for each row.
272     if (default_tile_size == 256 && portrait_width == 768)
273       default_tile_size += 32;
274     if (default_tile_size == 384 && portrait_width == 1200)
275       default_tile_size += 32;
276   } else {
277     // We don't know the exact resolution due to screen controls etc.
278     // So this just estimates the values above using tile counts.
279     int numTiles = (display_width * display_height) / (256 * 256);
280     if (numTiles > 16)
281       default_tile_size = 384;
282     if (numTiles >= 40)
283       default_tile_size = 512;
284   }
285
286   // IMG: Fast async texture uploads only work with non-power-of-two,
287   // but still multiple-of-eight sizes.
288   // http://crbug.com/168099
289   if (is_img)
290     default_tile_size -= 8;
291
292   // Set the command line if it isn't already set and we changed
293   // the default tile size.
294   if (default_tile_size != 256 &&
295       !command_line->HasSwitch(switches::kDefaultTileWidth) &&
296       !command_line->HasSwitch(switches::kDefaultTileHeight)) {
297     std::stringstream size;
298     size << default_tile_size;
299     command_line->AppendSwitchASCII(
300         switches::kDefaultTileWidth, size.str());
301     command_line->AppendSwitchASCII(
302         switches::kDefaultTileHeight, size.str());
303   }
304 }
305 #endif  // OS_ANDROID
306
307 // Overwrite force gpu workaround if a commandline switch exists.
308 void AdjustGpuSwitchingOption(std::set<int>* workarounds) {
309   DCHECK(workarounds);
310   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
311   std::string option = command_line.GetSwitchValueASCII(
312       switches::kGpuSwitching);
313   if (option == switches::kGpuSwitchingOptionNameForceDiscrete) {
314     workarounds->erase(gpu::FORCE_INTEGRATED_GPU);
315     workarounds->insert(gpu::FORCE_DISCRETE_GPU);
316   } else if (option == switches::kGpuSwitchingOptionNameForceIntegrated) {
317     workarounds->erase(gpu::FORCE_DISCRETE_GPU);
318     workarounds->insert(gpu::FORCE_INTEGRATED_GPU);
319   }
320 }
321
322 // Block all domains' use of 3D APIs for this many milliseconds if
323 // approaching a threshold where system stability might be compromised.
324 const int64 kBlockAllDomainsMs = 10000;
325 const int kNumResetsWithinDuration = 1;
326
327 // Enums for UMA histograms.
328 enum BlockStatusHistogram {
329   BLOCK_STATUS_NOT_BLOCKED,
330   BLOCK_STATUS_SPECIFIC_DOMAIN_BLOCKED,
331   BLOCK_STATUS_ALL_DOMAINS_BLOCKED,
332   BLOCK_STATUS_MAX
333 };
334
335 }  // namespace anonymous
336
337 void GpuDataManagerImplPrivate::InitializeForTesting(
338     const std::string& gpu_blacklist_json,
339     const gpu::GPUInfo& gpu_info) {
340   // This function is for testing only, so disable histograms.
341   update_histograms_ = false;
342
343   // Prevent all further initialization.
344   finalized_ = true;
345
346   InitializeImpl(gpu_blacklist_json, std::string(), gpu_info);
347 }
348
349 bool GpuDataManagerImplPrivate::IsFeatureBlacklisted(int feature) const {
350 #if defined(OS_CHROMEOS)
351   if (feature == gpu::GPU_FEATURE_TYPE_PANEL_FITTING &&
352       CommandLine::ForCurrentProcess()->HasSwitch(
353           switches::kDisablePanelFitting)) {
354     return true;
355   }
356 #endif  // OS_CHROMEOS
357   if (use_swiftshader_) {
358     // Skia's software rendering is probably more efficient than going through
359     // software emulation of the GPU, so use that.
360     if (feature == gpu::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS)
361       return true;
362     return false;
363   }
364
365   return (blacklisted_features_.count(feature) == 1);
366 }
367
368 bool GpuDataManagerImplPrivate::IsDriverBugWorkaroundActive(int feature) const {
369   return (gpu_driver_bugs_.count(feature) == 1);
370 }
371
372 size_t GpuDataManagerImplPrivate::GetBlacklistedFeatureCount() const {
373   if (use_swiftshader_)
374     return 1;
375   return blacklisted_features_.size();
376 }
377
378 void GpuDataManagerImplPrivate::SetDisplayCount(unsigned int display_count) {
379   display_count_ = display_count;
380 }
381
382 unsigned int GpuDataManagerImplPrivate::GetDisplayCount() const {
383   return display_count_;
384 }
385
386 gpu::GPUInfo GpuDataManagerImplPrivate::GetGPUInfo() const {
387   return gpu_info_;
388 }
389
390 void GpuDataManagerImplPrivate::GetGpuProcessHandles(
391     const GpuDataManager::GetGpuProcessHandlesCallback& callback) const {
392   GpuProcessHost::GetProcessHandles(callback);
393 }
394
395 bool GpuDataManagerImplPrivate::GpuAccessAllowed(
396     std::string* reason) const {
397   if (use_swiftshader_)
398     return true;
399
400   if (!gpu_process_accessible_) {
401     if (reason) {
402       *reason = "GPU process launch failed.";
403     }
404     return false;
405   }
406
407   if (card_blacklisted_) {
408     if (reason) {
409       *reason = "GPU access is disabled ";
410       CommandLine* command_line = CommandLine::ForCurrentProcess();
411       if (command_line->HasSwitch(switches::kDisableGpu))
412         *reason += "through commandline switch --disable-gpu.";
413       else
414         *reason += "in chrome://settings.";
415     }
416     return false;
417   }
418
419   // We only need to block GPU process if more features are disallowed other
420   // than those in the preliminary gpu feature flags because the latter work
421   // through renderer commandline switches.
422   std::set<int> features = preliminary_blacklisted_features_;
423   gpu::MergeFeatureSets(&features, blacklisted_features_);
424   if (features.size() > preliminary_blacklisted_features_.size()) {
425     if (reason) {
426       *reason = "Features are disabled upon full but not preliminary GPU info.";
427     }
428     return false;
429   }
430
431   if (blacklisted_features_.size() == gpu::NUMBER_OF_GPU_FEATURE_TYPES) {
432     // On Linux, we use cached GL strings to make blacklist decsions at browser
433     // startup time. We need to launch the GPU process to validate these
434     // strings even if all features are blacklisted. If all GPU features are
435     // disabled, the GPU process will only initialize GL bindings, create a GL
436     // context, and collect full GPU info.
437 #if !defined(OS_LINUX)
438     if (reason) {
439       *reason = "All GPU features are blacklisted.";
440     }
441     return false;
442 #endif
443   }
444
445   return true;
446 }
447
448 void GpuDataManagerImplPrivate::RequestCompleteGpuInfoIfNeeded() {
449   if (complete_gpu_info_already_requested_ || gpu_info_.finalized)
450     return;
451   complete_gpu_info_already_requested_ = true;
452
453   GpuProcessHost::SendOnIO(
454 #if defined(OS_WIN)
455       GpuProcessHost::GPU_PROCESS_KIND_UNSANDBOXED,
456 #else
457       GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
458 #endif
459       CAUSE_FOR_GPU_LAUNCH_GPUDATAMANAGER_REQUESTCOMPLETEGPUINFOIFNEEDED,
460       new GpuMsg_CollectGraphicsInfo());
461 }
462
463 bool GpuDataManagerImplPrivate::IsCompleteGpuInfoAvailable() const {
464   return gpu_info_.finalized;
465 }
466
467 void GpuDataManagerImplPrivate::RequestVideoMemoryUsageStatsUpdate() const {
468   GpuProcessHost::SendOnIO(
469       GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
470       CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH,
471       new GpuMsg_GetVideoMemoryUsageStats());
472 }
473
474 bool GpuDataManagerImplPrivate::ShouldUseSwiftShader() const {
475   return use_swiftshader_;
476 }
477
478 void GpuDataManagerImplPrivate::RegisterSwiftShaderPath(
479     const base::FilePath& path) {
480   swiftshader_path_ = path;
481   EnableSwiftShaderIfNecessary();
482 }
483
484 void GpuDataManagerImplPrivate::AddObserver(GpuDataManagerObserver* observer) {
485   GpuDataManagerImpl::UnlockedSession session(owner_);
486   observer_list_->AddObserver(observer);
487 }
488
489 void GpuDataManagerImplPrivate::RemoveObserver(
490     GpuDataManagerObserver* observer) {
491   GpuDataManagerImpl::UnlockedSession session(owner_);
492   observer_list_->RemoveObserver(observer);
493 }
494
495 void GpuDataManagerImplPrivate::UnblockDomainFrom3DAPIs(const GURL& url) {
496   // This method must do two things:
497   //
498   //  1. If the specific domain is blocked, then unblock it.
499   //
500   //  2. Reset our notion of how many GPU resets have occurred recently.
501   //     This is necessary even if the specific domain was blocked.
502   //     Otherwise, if we call Are3DAPIsBlocked with the same domain right
503   //     after unblocking it, it will probably still be blocked because of
504   //     the recent GPU reset caused by that domain.
505   //
506   // These policies could be refined, but at a certain point the behavior
507   // will become difficult to explain.
508   std::string domain = GetDomainFromURL(url);
509
510   blocked_domains_.erase(domain);
511   timestamps_of_gpu_resets_.clear();
512 }
513
514 void GpuDataManagerImplPrivate::DisableGpuWatchdog() {
515   GpuProcessHost::SendOnIO(
516       GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
517       CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH,
518       new GpuMsg_DisableWatchdog);
519 }
520
521 void GpuDataManagerImplPrivate::SetGLStrings(const std::string& gl_vendor,
522                                              const std::string& gl_renderer,
523                                              const std::string& gl_version) {
524   if (gl_vendor.empty() && gl_renderer.empty() && gl_version.empty())
525     return;
526
527   // If GPUInfo already got GL strings, do nothing.  This is for the rare
528   // situation where GPU process collected GL strings before this call.
529   if (!gpu_info_.gl_vendor.empty() ||
530       !gpu_info_.gl_renderer.empty() ||
531       !gpu_info_.gl_version_string.empty())
532     return;
533
534   gpu::GPUInfo gpu_info = gpu_info_;
535
536   gpu_info.gl_vendor = gl_vendor;
537   gpu_info.gl_renderer = gl_renderer;
538   gpu_info.gl_version_string = gl_version;
539
540   gpu::CollectDriverInfoGL(&gpu_info);
541
542   UpdateGpuInfo(gpu_info);
543   UpdateGpuSwitchingManager(gpu_info);
544   UpdatePreliminaryBlacklistedFeatures();
545 }
546
547 void GpuDataManagerImplPrivate::GetGLStrings(std::string* gl_vendor,
548                                              std::string* gl_renderer,
549                                              std::string* gl_version) {
550   DCHECK(gl_vendor && gl_renderer && gl_version);
551
552   *gl_vendor = gpu_info_.gl_vendor;
553   *gl_renderer = gpu_info_.gl_renderer;
554   *gl_version = gpu_info_.gl_version_string;
555 }
556
557 void GpuDataManagerImplPrivate::Initialize() {
558   TRACE_EVENT0("startup", "GpuDataManagerImpl::Initialize");
559   if (finalized_) {
560     DVLOG(0) << "GpuDataManagerImpl marked as finalized; skipping Initialize";
561     return;
562   }
563
564   const CommandLine* command_line = CommandLine::ForCurrentProcess();
565   if (command_line->HasSwitch(switches::kSkipGpuDataLoading))
566     return;
567
568   gpu::GPUInfo gpu_info;
569   if (command_line->GetSwitchValueASCII(
570           switches::kUseGL) == gfx::kGLImplementationOSMesaName) {
571     // If using the OSMesa GL implementation, use fake vendor and device ids to
572     // make sure it never gets blacklisted. This is better than simply
573     // cancelling GPUInfo gathering as it allows us to proceed with loading the
574     // blacklist below which may have non-device specific entries we want to
575     // apply anyways (e.g., OS version blacklisting).
576     gpu_info.gpu.vendor_id = 0xffff;
577     gpu_info.gpu.device_id = 0xffff;
578
579     // Also declare the driver_vendor to be osmesa to be able to specify
580     // exceptions based on driver_vendor==osmesa for some blacklist rules.
581     gpu_info.driver_vendor = gfx::kGLImplementationOSMesaName;
582   } else {
583     TRACE_EVENT0("startup",
584       "GpuDataManagerImpl::Initialize:CollectBasicGraphicsInfo");
585     gpu::CollectBasicGraphicsInfo(&gpu_info);
586   }
587 #if defined(ARCH_CPU_X86_FAMILY)
588   if (!gpu_info.gpu.vendor_id || !gpu_info.gpu.device_id)
589     gpu_info.finalized = true;
590 #endif
591
592   std::string gpu_blacklist_string;
593   std::string gpu_driver_bug_list_string;
594   if (!command_line->HasSwitch(switches::kIgnoreGpuBlacklist) &&
595       !command_line->HasSwitch(switches::kUseGpuInTests)) {
596     gpu_blacklist_string = gpu::kSoftwareRenderingListJson;
597   }
598   if (!command_line->HasSwitch(switches::kDisableGpuDriverBugWorkarounds)) {
599     gpu_driver_bug_list_string = gpu::kGpuDriverBugListJson;
600   }
601   InitializeImpl(gpu_blacklist_string,
602                  gpu_driver_bug_list_string,
603                  gpu_info);
604 }
605
606 void GpuDataManagerImplPrivate::UpdateGpuInfo(const gpu::GPUInfo& gpu_info) {
607   // No further update of gpu_info if falling back to SwiftShader.
608   if (use_swiftshader_)
609     return;
610
611   gpu::MergeGPUInfo(&gpu_info_, gpu_info);
612   complete_gpu_info_already_requested_ =
613       complete_gpu_info_already_requested_ || gpu_info_.finalized;
614
615   GetContentClient()->SetGpuInfo(gpu_info_);
616
617   if (gpu_blacklist_) {
618     std::set<int> features = gpu_blacklist_->MakeDecision(
619         gpu::GpuControlList::kOsAny, std::string(), gpu_info_);
620     if (update_histograms_)
621       UpdateStats(gpu_info_, gpu_blacklist_.get(), features);
622
623     UpdateBlacklistedFeatures(features);
624   }
625   if (gpu_driver_bug_list_) {
626     gpu_driver_bugs_ = gpu_driver_bug_list_->MakeDecision(
627         gpu::GpuControlList::kOsAny, std::string(), gpu_info_);
628   }
629   AdjustGpuSwitchingOption(&gpu_driver_bugs_);
630
631   // We have to update GpuFeatureType before notify all the observers.
632   NotifyGpuInfoUpdate();
633 }
634
635 void GpuDataManagerImplPrivate::UpdateVideoMemoryUsageStats(
636     const GPUVideoMemoryUsageStats& video_memory_usage_stats) {
637   GpuDataManagerImpl::UnlockedSession session(owner_);
638   observer_list_->Notify(&GpuDataManagerObserver::OnVideoMemoryUsageStatsUpdate,
639                          video_memory_usage_stats);
640 }
641
642 void GpuDataManagerImplPrivate::AppendRendererCommandLine(
643     CommandLine* command_line) const {
644   DCHECK(command_line);
645
646   if (IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING) &&
647       !command_line->HasSwitch(switches::kDisableAcceleratedCompositing))
648     command_line->AppendSwitch(switches::kDisableAcceleratedCompositing);
649   if (IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_ACCELERATED_VIDEO_DECODE) &&
650       !command_line->HasSwitch(switches::kDisableAcceleratedVideoDecode))
651     command_line->AppendSwitch(switches::kDisableAcceleratedVideoDecode);
652 #if defined(ENABLE_WEBRTC)
653   if (IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_ACCELERATED_VIDEO_ENCODE) &&
654       !command_line->HasSwitch(switches::kDisableWebRtcHWEncoding))
655     command_line->AppendSwitch(switches::kDisableWebRtcHWEncoding);
656 #endif
657
658   if (use_software_compositor_ &&
659       !command_line->HasSwitch(switches::kEnableSoftwareCompositing))
660     command_line->AppendSwitch(switches::kEnableSoftwareCompositing);
661
662 #if defined(USE_AURA)
663   if (!CanUseGpuBrowserCompositor())
664     command_line->AppendSwitch(switches::kDisableGpuCompositing);
665 #endif
666 }
667
668 void GpuDataManagerImplPrivate::AppendGpuCommandLine(
669     CommandLine* command_line) const {
670   DCHECK(command_line);
671
672   std::string use_gl =
673       CommandLine::ForCurrentProcess()->GetSwitchValueASCII(switches::kUseGL);
674   base::FilePath swiftshader_path =
675       CommandLine::ForCurrentProcess()->GetSwitchValuePath(
676           switches::kSwiftShaderPath);
677   if (gpu_driver_bugs_.find(gpu::DISABLE_D3D11) != gpu_driver_bugs_.end())
678     command_line->AppendSwitch(switches::kDisableD3D11);
679   if (use_swiftshader_) {
680     command_line->AppendSwitchASCII(switches::kUseGL, "swiftshader");
681     if (swiftshader_path.empty())
682       swiftshader_path = swiftshader_path_;
683   } else if ((IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_WEBGL) ||
684               IsFeatureBlacklisted(
685                   gpu::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING) ||
686               IsFeatureBlacklisted(
687                   gpu::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS)) &&
688       (use_gl == "any")) {
689     command_line->AppendSwitchASCII(
690         switches::kUseGL, gfx::kGLImplementationOSMesaName);
691   } else if (!use_gl.empty()) {
692     command_line->AppendSwitchASCII(switches::kUseGL, use_gl);
693   }
694   if (ui::GpuSwitchingManager::GetInstance()->SupportsDualGpus())
695     command_line->AppendSwitchASCII(switches::kSupportsDualGpus, "true");
696   else
697     command_line->AppendSwitchASCII(switches::kSupportsDualGpus, "false");
698
699   if (!swiftshader_path.empty()) {
700     command_line->AppendSwitchPath(switches::kSwiftShaderPath,
701                                    swiftshader_path);
702   }
703
704   if (!gpu_driver_bugs_.empty()) {
705     command_line->AppendSwitchASCII(switches::kGpuDriverBugWorkarounds,
706                                     IntSetToString(gpu_driver_bugs_));
707   }
708
709   if (IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_ACCELERATED_VIDEO_DECODE) &&
710       !command_line->HasSwitch(switches::kDisableAcceleratedVideoDecode)) {
711     command_line->AppendSwitch(switches::kDisableAcceleratedVideoDecode);
712   }
713 #if defined(ENABLE_WEBRTC)
714   if (IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_ACCELERATED_VIDEO_ENCODE) &&
715       !command_line->HasSwitch(switches::kDisableWebRtcHWEncoding)) {
716     command_line->AppendSwitch(switches::kDisableWebRtcHWEncoding);
717   }
718 #endif
719
720   // Pass GPU and driver information to GPU process. We try to avoid full GPU
721   // info collection at GPU process startup, but we need gpu vendor_id,
722   // device_id, driver_vendor, driver_version for deciding whether we need to
723   // collect full info (on Linux) and for crash reporting purpose.
724   command_line->AppendSwitchASCII(switches::kGpuVendorID,
725       base::StringPrintf("0x%04x", gpu_info_.gpu.vendor_id));
726   command_line->AppendSwitchASCII(switches::kGpuDeviceID,
727       base::StringPrintf("0x%04x", gpu_info_.gpu.device_id));
728   command_line->AppendSwitchASCII(switches::kGpuDriverVendor,
729       gpu_info_.driver_vendor);
730   command_line->AppendSwitchASCII(switches::kGpuDriverVersion,
731       gpu_info_.driver_version);
732 }
733
734 void GpuDataManagerImplPrivate::AppendPluginCommandLine(
735     CommandLine* command_line) const {
736   DCHECK(command_line);
737
738 #if defined(OS_MACOSX)
739   // TODO(jbauman): Add proper blacklist support for core animation plugins so
740   // special-casing this video card won't be necessary. See
741   // http://crbug.com/134015
742   if (IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING) ||
743       CommandLine::ForCurrentProcess()->HasSwitch(
744           switches::kDisableAcceleratedCompositing)) {
745     if (!command_line->HasSwitch(
746            switches::kDisableCoreAnimationPlugins))
747       command_line->AppendSwitch(
748           switches::kDisableCoreAnimationPlugins);
749   }
750 #endif
751 }
752
753 void GpuDataManagerImplPrivate::UpdateRendererWebPrefs(
754     WebPreferences* prefs) const {
755   DCHECK(prefs);
756
757   if (IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING))
758     prefs->accelerated_compositing_enabled = false;
759   if (IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_WEBGL)) {
760     prefs->experimental_webgl_enabled = false;
761     prefs->pepper_3d_enabled = false;
762   }
763   if (IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_FLASH3D))
764     prefs->flash_3d_enabled = false;
765   if (IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_FLASH_STAGE3D)) {
766     prefs->flash_stage3d_enabled = false;
767     prefs->flash_stage3d_baseline_enabled = false;
768   }
769   if (IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_FLASH_STAGE3D_BASELINE))
770     prefs->flash_stage3d_baseline_enabled = false;
771   if (IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS))
772     prefs->accelerated_2d_canvas_enabled = false;
773   if (IsDriverBugWorkaroundActive(gpu::DISABLE_MULTISAMPLING) ||
774       (IsDriverBugWorkaroundActive(gpu::DISABLE_MULTIMONITOR_MULTISAMPLING) &&
775           display_count_ > 1))
776     prefs->gl_multisampling_enabled = false;
777   if (IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_3D_CSS)) {
778     prefs->accelerated_compositing_for_3d_transforms_enabled = false;
779     prefs->accelerated_compositing_for_animation_enabled = false;
780   }
781   if (IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_ACCELERATED_VIDEO))
782     prefs->accelerated_compositing_for_video_enabled = false;
783
784   // Accelerated video and animation are slower than regular when using
785   // SwiftShader. 3D CSS or Pepper 3D may also be too slow to be worthwhile.
786   if (ShouldUseSwiftShader()) {
787     prefs->accelerated_compositing_for_video_enabled = false;
788     prefs->accelerated_compositing_for_animation_enabled = false;
789     prefs->accelerated_compositing_for_3d_transforms_enabled = false;
790     prefs->accelerated_compositing_for_plugins_enabled = false;
791     prefs->pepper_3d_enabled = false;
792   }
793
794   if (use_software_compositor_) {
795     prefs->force_compositing_mode = true;
796     prefs->accelerated_compositing_enabled = true;
797     prefs->accelerated_compositing_for_3d_transforms_enabled = true;
798     prefs->accelerated_compositing_for_plugins_enabled = true;
799     prefs->accelerated_compositing_for_video_enabled = true;
800   }
801
802 #if defined(USE_AURA)
803   if (!CanUseGpuBrowserCompositor()) {
804     prefs->accelerated_2d_canvas_enabled = false;
805     prefs->pepper_3d_enabled = false;
806   }
807 #endif
808 }
809
810 void GpuDataManagerImplPrivate::DisableHardwareAcceleration() {
811   card_blacklisted_ = true;
812
813   for (int i = 0; i < gpu::NUMBER_OF_GPU_FEATURE_TYPES; ++i)
814     blacklisted_features_.insert(i);
815
816   EnableSwiftShaderIfNecessary();
817   NotifyGpuInfoUpdate();
818 }
819
820 std::string GpuDataManagerImplPrivate::GetBlacklistVersion() const {
821   if (gpu_blacklist_)
822     return gpu_blacklist_->version();
823   return "0";
824 }
825
826 std::string GpuDataManagerImplPrivate::GetDriverBugListVersion() const {
827   if (gpu_driver_bug_list_)
828     return gpu_driver_bug_list_->version();
829   return "0";
830 }
831
832 void GpuDataManagerImplPrivate::GetBlacklistReasons(
833     base::ListValue* reasons) const {
834   if (gpu_blacklist_)
835     gpu_blacklist_->GetReasons(reasons);
836 }
837
838 void GpuDataManagerImplPrivate::GetDriverBugWorkarounds(
839     base::ListValue* workarounds) const {
840   for (std::set<int>::const_iterator it = gpu_driver_bugs_.begin();
841        it != gpu_driver_bugs_.end(); ++it) {
842     workarounds->AppendString(
843         gpu::GpuDriverBugWorkaroundTypeToString(
844             static_cast<gpu::GpuDriverBugWorkaroundType>(*it)));
845   }
846 }
847
848 void GpuDataManagerImplPrivate::AddLogMessage(
849     int level, const std::string& header, const std::string& message) {
850   log_messages_.push_back(LogMessage(level, header, message));
851 }
852
853 void GpuDataManagerImplPrivate::ProcessCrashed(
854     base::TerminationStatus exit_code) {
855   if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
856     // Unretained is ok, because it's posted to UI thread, the thread
857     // where the singleton GpuDataManagerImpl lives until the end.
858     BrowserThread::PostTask(
859         BrowserThread::UI,
860         FROM_HERE,
861         base::Bind(&GpuDataManagerImpl::ProcessCrashed,
862                    base::Unretained(owner_),
863                    exit_code));
864     return;
865   }
866   {
867     GpuDataManagerImpl::UnlockedSession session(owner_);
868     observer_list_->Notify(
869         &GpuDataManagerObserver::OnGpuProcessCrashed, exit_code);
870   }
871 }
872
873 base::ListValue* GpuDataManagerImplPrivate::GetLogMessages() const {
874   base::ListValue* value = new base::ListValue;
875   for (size_t ii = 0; ii < log_messages_.size(); ++ii) {
876     base::DictionaryValue* dict = new base::DictionaryValue();
877     dict->SetInteger("level", log_messages_[ii].level);
878     dict->SetString("header", log_messages_[ii].header);
879     dict->SetString("message", log_messages_[ii].message);
880     value->Append(dict);
881   }
882   return value;
883 }
884
885 void GpuDataManagerImplPrivate::HandleGpuSwitch() {
886   GpuDataManagerImpl::UnlockedSession session(owner_);
887   observer_list_->Notify(&GpuDataManagerObserver::OnGpuSwitching);
888 }
889
890 bool GpuDataManagerImplPrivate::CanUseGpuBrowserCompositor() const {
891   return !ShouldUseSwiftShader() &&
892          !IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING) &&
893          !IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_FORCE_COMPOSITING_MODE);
894 }
895
896 void GpuDataManagerImplPrivate::BlockDomainFrom3DAPIs(
897     const GURL& url, GpuDataManagerImpl::DomainGuilt guilt) {
898   BlockDomainFrom3DAPIsAtTime(url, guilt, base::Time::Now());
899 }
900
901 bool GpuDataManagerImplPrivate::Are3DAPIsBlocked(const GURL& url,
902                                                  int render_process_id,
903                                                  int render_view_id,
904                                                  ThreeDAPIType requester) {
905   bool blocked = Are3DAPIsBlockedAtTime(url, base::Time::Now()) !=
906       GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_NOT_BLOCKED;
907   if (blocked) {
908     // Unretained is ok, because it's posted to UI thread, the thread
909     // where the singleton GpuDataManagerImpl lives until the end.
910     BrowserThread::PostTask(
911         BrowserThread::UI, FROM_HERE,
912         base::Bind(&GpuDataManagerImpl::Notify3DAPIBlocked,
913                    base::Unretained(owner_), url, render_process_id,
914                    render_view_id, requester));
915   }
916
917   return blocked;
918 }
919
920 void GpuDataManagerImplPrivate::DisableDomainBlockingFor3DAPIsForTesting() {
921   domain_blocking_enabled_ = false;
922 }
923
924 // static
925 GpuDataManagerImplPrivate* GpuDataManagerImplPrivate::Create(
926     GpuDataManagerImpl* owner) {
927   return new GpuDataManagerImplPrivate(owner);
928 }
929
930 GpuDataManagerImplPrivate::GpuDataManagerImplPrivate(
931     GpuDataManagerImpl* owner)
932     : complete_gpu_info_already_requested_(false),
933       observer_list_(new GpuDataManagerObserverList),
934       use_swiftshader_(false),
935       card_blacklisted_(false),
936       update_histograms_(true),
937       window_count_(0),
938       domain_blocking_enabled_(true),
939       owner_(owner),
940       display_count_(0),
941       gpu_process_accessible_(true),
942       use_software_compositor_(false),
943       finalized_(false) {
944   DCHECK(owner_);
945   CommandLine* command_line = CommandLine::ForCurrentProcess();
946   if (command_line->HasSwitch(switches::kDisableAcceleratedCompositing)) {
947     command_line->AppendSwitch(switches::kDisableAccelerated2dCanvas);
948     command_line->AppendSwitch(switches::kDisableAcceleratedLayers);
949   }
950   if (command_line->HasSwitch(switches::kDisableGpu))
951     DisableHardwareAcceleration();
952   if (command_line->HasSwitch(switches::kEnableSoftwareCompositing))
953     use_software_compositor_ = true;
954   // TODO(jbauman): enable for Chrome OS
955 #if (defined(USE_AURA) && !defined(OS_CHROMEOS)) || defined(OS_MACOSX)
956   use_software_compositor_ = true;
957 #endif
958
959 #if defined(OS_MACOSX)
960   CGGetActiveDisplayList (0, NULL, &display_count_);
961   CGDisplayRegisterReconfigurationCallback(DisplayReconfigCallback, owner_);
962 #endif  // OS_MACOSX
963
964   // For testing only.
965   if (command_line->HasSwitch(switches::kDisableDomainBlockingFor3DAPIs)) {
966     domain_blocking_enabled_ = false;
967   }
968 }
969
970 GpuDataManagerImplPrivate::~GpuDataManagerImplPrivate() {
971 #if defined(OS_MACOSX)
972   CGDisplayRemoveReconfigurationCallback(DisplayReconfigCallback, owner_);
973 #endif
974 }
975
976 void GpuDataManagerImplPrivate::InitializeImpl(
977     const std::string& gpu_blacklist_json,
978     const std::string& gpu_driver_bug_list_json,
979     const gpu::GPUInfo& gpu_info) {
980   const bool log_gpu_control_list_decisions =
981       CommandLine::ForCurrentProcess()->HasSwitch(
982           switches::kLogGpuControlListDecisions);
983
984   if (!gpu_blacklist_json.empty()) {
985     gpu_blacklist_.reset(gpu::GpuBlacklist::Create());
986     if (log_gpu_control_list_decisions)
987       gpu_blacklist_->enable_control_list_logging("gpu_blacklist");
988     bool success = gpu_blacklist_->LoadList(
989         gpu_blacklist_json, gpu::GpuControlList::kCurrentOsOnly);
990     DCHECK(success);
991   }
992   if (!gpu_driver_bug_list_json.empty()) {
993     gpu_driver_bug_list_.reset(gpu::GpuDriverBugList::Create());
994     if (log_gpu_control_list_decisions)
995       gpu_driver_bug_list_->enable_control_list_logging("gpu_driver_bug_list");
996     bool success = gpu_driver_bug_list_->LoadList(
997         gpu_driver_bug_list_json, gpu::GpuControlList::kCurrentOsOnly);
998     DCHECK(success);
999   }
1000
1001   gpu_info_ = gpu_info;
1002   UpdateGpuInfo(gpu_info);
1003   UpdateGpuSwitchingManager(gpu_info);
1004   UpdatePreliminaryBlacklistedFeatures();
1005
1006 #if defined(OS_ANDROID)
1007   ApplyAndroidWorkarounds(gpu_info, CommandLine::ForCurrentProcess());
1008 #endif  // OS_ANDROID
1009 }
1010
1011 void GpuDataManagerImplPrivate::UpdateBlacklistedFeatures(
1012     const std::set<int>& features) {
1013   CommandLine* command_line = CommandLine::ForCurrentProcess();
1014   blacklisted_features_ = features;
1015
1016   // Force disable using the GPU for these features, even if they would
1017   // otherwise be allowed.
1018   if (card_blacklisted_ ||
1019       command_line->HasSwitch(switches::kBlacklistAcceleratedCompositing)) {
1020     blacklisted_features_.insert(
1021         gpu::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING);
1022   }
1023   if (card_blacklisted_ ||
1024       command_line->HasSwitch(switches::kBlacklistWebGL)) {
1025     blacklisted_features_.insert(gpu::GPU_FEATURE_TYPE_WEBGL);
1026   }
1027
1028   EnableSwiftShaderIfNecessary();
1029 }
1030
1031 void GpuDataManagerImplPrivate::UpdatePreliminaryBlacklistedFeatures() {
1032   preliminary_blacklisted_features_ = blacklisted_features_;
1033 }
1034
1035 void GpuDataManagerImplPrivate::UpdateGpuSwitchingManager(
1036     const gpu::GPUInfo& gpu_info) {
1037   ui::GpuSwitchingManager::GetInstance()->SetGpuCount(
1038       gpu_info.secondary_gpus.size() + 1);
1039
1040   if (ui::GpuSwitchingManager::GetInstance()->SupportsDualGpus()) {
1041     if (gpu_driver_bugs_.count(gpu::FORCE_DISCRETE_GPU) == 1)
1042       ui::GpuSwitchingManager::GetInstance()->ForceUseOfDiscreteGpu();
1043     else if (gpu_driver_bugs_.count(gpu::FORCE_INTEGRATED_GPU) == 1)
1044       ui::GpuSwitchingManager::GetInstance()->ForceUseOfIntegratedGpu();
1045   }
1046 }
1047
1048 void GpuDataManagerImplPrivate::NotifyGpuInfoUpdate() {
1049   observer_list_->Notify(&GpuDataManagerObserver::OnGpuInfoUpdate);
1050 }
1051
1052 void GpuDataManagerImplPrivate::EnableSwiftShaderIfNecessary() {
1053   if (!GpuAccessAllowed(NULL) ||
1054       blacklisted_features_.count(gpu::GPU_FEATURE_TYPE_WEBGL)) {
1055     if (!swiftshader_path_.empty() &&
1056         !CommandLine::ForCurrentProcess()->HasSwitch(
1057              switches::kDisableSoftwareRasterizer))
1058       use_swiftshader_ = true;
1059   }
1060 }
1061
1062 std::string GpuDataManagerImplPrivate::GetDomainFromURL(
1063     const GURL& url) const {
1064   // For the moment, we just use the host, or its IP address, as the
1065   // entry in the set, rather than trying to figure out the top-level
1066   // domain. This does mean that a.foo.com and b.foo.com will be
1067   // treated independently in the blocking of a given domain, but it
1068   // would require a third-party library to reliably figure out the
1069   // top-level domain from a URL.
1070   if (!url.has_host()) {
1071     return std::string();
1072   }
1073
1074   return url.host();
1075 }
1076
1077 void GpuDataManagerImplPrivate::BlockDomainFrom3DAPIsAtTime(
1078     const GURL& url,
1079     GpuDataManagerImpl::DomainGuilt guilt,
1080     base::Time at_time) {
1081   if (!domain_blocking_enabled_)
1082     return;
1083
1084   std::string domain = GetDomainFromURL(url);
1085
1086   DomainBlockEntry& entry = blocked_domains_[domain];
1087   entry.last_guilt = guilt;
1088   timestamps_of_gpu_resets_.push_back(at_time);
1089 }
1090
1091 GpuDataManagerImpl::DomainBlockStatus
1092 GpuDataManagerImplPrivate::Are3DAPIsBlockedAtTime(
1093     const GURL& url, base::Time at_time) const {
1094   if (!domain_blocking_enabled_)
1095     return GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_NOT_BLOCKED;
1096
1097   // Note: adjusting the policies in this code will almost certainly
1098   // require adjusting the associated unit tests.
1099   std::string domain = GetDomainFromURL(url);
1100
1101   DomainBlockMap::const_iterator iter = blocked_domains_.find(domain);
1102   if (iter != blocked_domains_.end()) {
1103     // Err on the side of caution, and assume that if a particular
1104     // domain shows up in the block map, it's there for a good
1105     // reason and don't let its presence there automatically expire.
1106
1107     UMA_HISTOGRAM_ENUMERATION("GPU.BlockStatusForClient3DAPIs",
1108                               BLOCK_STATUS_SPECIFIC_DOMAIN_BLOCKED,
1109                               BLOCK_STATUS_MAX);
1110
1111     return GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_BLOCKED;
1112   }
1113
1114   // Look at the timestamps of the recent GPU resets to see if there are
1115   // enough within the threshold which would cause us to blacklist all
1116   // domains. This doesn't need to be overly precise -- if time goes
1117   // backward due to a system clock adjustment, that's fine.
1118   //
1119   // TODO(kbr): make this pay attention to the TDR thresholds in the
1120   // Windows registry, but make sure it continues to be testable.
1121   {
1122     std::list<base::Time>::iterator iter = timestamps_of_gpu_resets_.begin();
1123     int num_resets_within_timeframe = 0;
1124     while (iter != timestamps_of_gpu_resets_.end()) {
1125       base::Time time = *iter;
1126       base::TimeDelta delta_t = at_time - time;
1127
1128       // If this entry has "expired", just remove it.
1129       if (delta_t.InMilliseconds() > kBlockAllDomainsMs) {
1130         iter = timestamps_of_gpu_resets_.erase(iter);
1131         continue;
1132       }
1133
1134       ++num_resets_within_timeframe;
1135       ++iter;
1136     }
1137
1138     if (num_resets_within_timeframe >= kNumResetsWithinDuration) {
1139       UMA_HISTOGRAM_ENUMERATION("GPU.BlockStatusForClient3DAPIs",
1140                                 BLOCK_STATUS_ALL_DOMAINS_BLOCKED,
1141                                 BLOCK_STATUS_MAX);
1142
1143       return GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_ALL_DOMAINS_BLOCKED;
1144     }
1145   }
1146
1147   UMA_HISTOGRAM_ENUMERATION("GPU.BlockStatusForClient3DAPIs",
1148                             BLOCK_STATUS_NOT_BLOCKED,
1149                             BLOCK_STATUS_MAX);
1150
1151   return GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_NOT_BLOCKED;
1152 }
1153
1154 int64 GpuDataManagerImplPrivate::GetBlockAllDomainsDurationInMs() const {
1155   return kBlockAllDomainsMs;
1156 }
1157
1158 void GpuDataManagerImplPrivate::Notify3DAPIBlocked(const GURL& url,
1159                                                    int render_process_id,
1160                                                    int render_view_id,
1161                                                    ThreeDAPIType requester) {
1162   GpuDataManagerImpl::UnlockedSession session(owner_);
1163   observer_list_->Notify(&GpuDataManagerObserver::DidBlock3DAPIs,
1164                          url, render_process_id, render_view_id, requester);
1165 }
1166
1167 void GpuDataManagerImplPrivate::OnGpuProcessInitFailure() {
1168   gpu_process_accessible_ = false;
1169   gpu_info_.finalized = true;
1170   complete_gpu_info_already_requested_ = true;
1171   // Some observers might be waiting.
1172   NotifyGpuInfoUpdate();
1173 }
1174
1175 }  // namespace content