gpu_channel_manager.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. #ifndef GPU_IPC_SERVICE_GPU_CHANNEL_MANAGER_H_
  5. #define GPU_IPC_SERVICE_GPU_CHANNEL_MANAGER_H_
  6. #include <stdint.h>
  7. #include <memory>
  8. #include <string>
  9. #include <vector>
  10. #include "base/containers/flat_map.h"
  11. #include "base/memory/memory_pressure_listener.h"
  12. #include "base/memory/raw_ptr.h"
  13. #include "base/memory/ref_counted.h"
  14. #include "base/memory/weak_ptr.h"
  15. #include "base/process/process_handle.h"
  16. #include "base/task/single_thread_task_runner.h"
  17. #include "base/threading/thread_checker.h"
  18. #include "base/time/time.h"
  19. #include "base/unguessable_token.h"
  20. #include "build/build_config.h"
  21. #include "gpu/command_buffer/common/activity_flags.h"
  22. #include "gpu/command_buffer/common/constants.h"
  23. #include "gpu/command_buffer/service/gr_cache_controller.h"
  24. #include "gpu/command_buffer/service/gr_shader_cache.h"
  25. #include "gpu/command_buffer/service/memory_tracking.h"
  26. #include "gpu/command_buffer/service/passthrough_discardable_manager.h"
  27. #include "gpu/command_buffer/service/service_discardable_manager.h"
  28. #include "gpu/command_buffer/service/shader_translator_cache.h"
  29. #include "gpu/command_buffer/service/shared_context_state.h"
  30. #include "gpu/config/gpu_driver_bug_workarounds.h"
  31. #include "gpu/config/gpu_feature_info.h"
  32. #include "gpu/config/gpu_preferences.h"
  33. #include "gpu/ipc/common/gpu_disk_cache_type.h"
  34. #include "gpu/ipc/common/gpu_peak_memory.h"
  35. #include "gpu/ipc/service/gpu_ipc_service_export.h"
  36. #include "third_party/abseil-cpp/absl/types/optional.h"
  37. #include "ui/gfx/gpu_memory_buffer.h"
  38. #include "ui/gfx/native_widget_types.h"
  39. #include "ui/gl/gl_surface.h"
  40. #include "url/gurl.h"
  41. namespace base {
  42. namespace trace_event {
  43. class TracedValue;
  44. } // namespace trace_event
  45. } // namespace base
  46. namespace gl {
  47. class GLShareGroup;
  48. }
  49. namespace gpu {
  50. class SharedImageManager;
  51. struct GpuPreferences;
  52. struct SyncToken;
  53. class GpuChannel;
  54. class GpuChannelManagerDelegate;
  55. class GpuMemoryAblationExperiment;
  56. class GpuMemoryBufferFactory;
  57. class GpuWatchdogThread;
  58. class ImageDecodeAcceleratorWorker;
  59. class MailboxManager;
  60. class Scheduler;
  61. class SyncPointManager;
  62. struct VideoMemoryUsageStats;
  63. namespace gles2 {
  64. class Outputter;
  65. class ProgramCache;
  66. } // namespace gles2
  67. // A GpuChannelManager is a thread responsible for issuing rendering commands
  68. // managing the lifetimes of GPU channels and forwarding IPC requests from the
  69. // browser process to them based on the corresponding renderer ID.
  70. class GPU_IPC_SERVICE_EXPORT GpuChannelManager
  71. : public raster::GrShaderCache::Client {
  72. public:
  73. using OnMemoryAllocatedChangeCallback =
  74. base::OnceCallback<void(gpu::CommandBufferId id,
  75. uint64_t old_size,
  76. uint64_t new_size,
  77. gpu::GpuPeakMemoryAllocationSource source)>;
  78. GpuChannelManager(
  79. const GpuPreferences& gpu_preferences,
  80. GpuChannelManagerDelegate* delegate,
  81. GpuWatchdogThread* watchdog,
  82. scoped_refptr<base::SingleThreadTaskRunner> task_runner,
  83. scoped_refptr<base::SingleThreadTaskRunner> io_task_runner,
  84. Scheduler* scheduler,
  85. SyncPointManager* sync_point_manager,
  86. SharedImageManager* shared_image_manager,
  87. GpuMemoryBufferFactory* gpu_memory_buffer_factory,
  88. const GpuFeatureInfo& gpu_feature_info,
  89. GpuProcessActivityFlags activity_flags,
  90. scoped_refptr<gl::GLSurface> default_offscreen_surface,
  91. ImageDecodeAcceleratorWorker* image_decode_accelerator_worker,
  92. viz::VulkanContextProvider* vulkan_context_provider = nullptr,
  93. viz::MetalContextProvider* metal_context_provider = nullptr,
  94. viz::DawnContextProvider* dawn_context_provider = nullptr);
  95. GpuChannelManager(const GpuChannelManager&) = delete;
  96. GpuChannelManager& operator=(const GpuChannelManager&) = delete;
  97. ~GpuChannelManager() override;
  98. GpuChannelManagerDelegate* delegate() const { return delegate_; }
  99. GpuWatchdogThread* watchdog() const { return watchdog_; }
  100. GpuChannel* EstablishChannel(const base::UnguessableToken& channel_token,
  101. int client_id,
  102. uint64_t client_tracing_id,
  103. bool is_gpu_host);
  104. void SetChannelClientPid(int client_id, base::ProcessId client_pid);
  105. void SetChannelDiskCacheHandle(int client_id,
  106. const gpu::GpuDiskCacheHandle& handle);
  107. void OnDiskCacheHandleDestoyed(const gpu::GpuDiskCacheHandle& handle);
  108. void PopulateCache(const gpu::GpuDiskCacheHandle& handle,
  109. const std::string& key,
  110. const std::string& program);
  111. void DestroyGpuMemoryBuffer(gfx::GpuMemoryBufferId id,
  112. int client_id,
  113. const SyncToken& sync_token);
  114. #if BUILDFLAG(IS_ANDROID)
  115. void WakeUpGpu();
  116. #endif
  117. void DestroyAllChannels();
  118. // Remove the channel for a particular renderer.
  119. void RemoveChannel(int client_id);
  120. void OnContextLost(bool synthetic_loss);
  121. const GpuPreferences& gpu_preferences() const { return gpu_preferences_; }
  122. const GpuDriverBugWorkarounds& gpu_driver_bug_workarounds() const {
  123. return gpu_driver_bug_workarounds_;
  124. }
  125. const GpuFeatureInfo& gpu_feature_info() const { return gpu_feature_info_; }
  126. ServiceDiscardableManager* discardable_manager() {
  127. return &discardable_manager_;
  128. }
  129. PassthroughDiscardableManager* passthrough_discardable_manager() {
  130. return &passthrough_discardable_manager_;
  131. }
  132. gles2::Outputter* outputter();
  133. gles2::ProgramCache* program_cache();
  134. gles2::ShaderTranslatorCache* shader_translator_cache() {
  135. return &shader_translator_cache_;
  136. }
  137. gles2::FramebufferCompletenessCache* framebuffer_completeness_cache() {
  138. return &framebuffer_completeness_cache_;
  139. }
  140. GpuChannel* LookupChannel(int32_t client_id) const;
  141. gl::GLSurface* default_offscreen_surface() const {
  142. return default_offscreen_surface_.get();
  143. }
  144. GpuMemoryBufferFactory* gpu_memory_buffer_factory() {
  145. return gpu_memory_buffer_factory_;
  146. }
  147. MemoryTracker::Observer* peak_memory_monitor() {
  148. return &peak_memory_monitor_;
  149. }
  150. GpuProcessActivityFlags* activity_flags() { return &activity_flags_; }
  151. #if BUILDFLAG(IS_ANDROID)
  152. void DidAccessGpu();
  153. void OnBackgroundCleanup();
  154. #endif
  155. void OnApplicationBackgrounded();
  156. MailboxManager* mailbox_manager() const { return mailbox_manager_.get(); }
  157. gl::GLShareGroup* share_group() const { return share_group_.get(); }
  158. SyncPointManager* sync_point_manager() const { return sync_point_manager_; }
  159. SharedImageManager* shared_image_manager() const {
  160. return shared_image_manager_;
  161. }
  162. // Retrieve GPU Resource consumption statistics for the task manager
  163. void GetVideoMemoryUsageStats(
  164. VideoMemoryUsageStats* video_memory_usage_stats) const;
  165. // Starts tracking the peak memory across all MemoryTrackers for
  166. // |sequence_num|. Repeated calls with the same value are ignored.
  167. void StartPeakMemoryMonitor(uint32_t sequence_num);
  168. // Ends the tracking for |sequence_num| and returns the peak memory per
  169. // allocation source. Along with the total |out_peak_memory|.
  170. base::flat_map<GpuPeakMemoryAllocationSource, uint64_t> GetPeakMemoryUsage(
  171. uint32_t sequence_num,
  172. uint64_t* out_peak_memory);
  173. scoped_refptr<SharedContextState> GetSharedContextState(
  174. ContextResult* result);
  175. void ScheduleGrContextCleanup();
  176. raster::GrShaderCache* gr_shader_cache() {
  177. return gr_shader_cache_ ? &*gr_shader_cache_ : nullptr;
  178. }
  179. // raster::GrShaderCache::Client implementation.
  180. void StoreShader(const std::string& key, const std::string& shader) override;
  181. void SetImageDecodeAcceleratorWorkerForTesting(
  182. ImageDecodeAcceleratorWorker* worker);
  183. void LoseAllContexts();
  184. SharedContextState::ContextLostCallback GetContextLostCallback();
  185. GpuChannelManager::OnMemoryAllocatedChangeCallback
  186. GetOnMemoryAllocatedChangeCallback();
  187. private:
  188. friend class GpuChannelManagerTest;
  189. // Observes changes in GPU memory, and tracks the peak usage for clients. The
  190. // client is responsible for providing a unique |sequence_num| for each time
  191. // period in which it wishes to track memory usage.
  192. class GPU_IPC_SERVICE_EXPORT GpuPeakMemoryMonitor
  193. : public MemoryTracker::Observer {
  194. public:
  195. GpuPeakMemoryMonitor(
  196. GpuChannelManager* channel_manager,
  197. scoped_refptr<base::SingleThreadTaskRunner> task_runner);
  198. GpuPeakMemoryMonitor(const GpuPeakMemoryMonitor&) = delete;
  199. GpuPeakMemoryMonitor& operator=(const GpuPeakMemoryMonitor&) = delete;
  200. ~GpuPeakMemoryMonitor() override;
  201. base::flat_map<GpuPeakMemoryAllocationSource, uint64_t> GetPeakMemoryUsage(
  202. uint32_t sequence_num,
  203. uint64_t* out_peak_memory);
  204. void StartGpuMemoryTracking(uint32_t sequence_num);
  205. void StopGpuMemoryTracking(uint32_t sequence_num);
  206. base::WeakPtr<MemoryTracker::Observer> GetWeakPtr();
  207. void InvalidateWeakPtrs();
  208. private:
  209. struct SequenceTracker {
  210. public:
  211. SequenceTracker(uint64_t current_memory,
  212. base::flat_map<GpuPeakMemoryAllocationSource, uint64_t>
  213. current_memory_per_source);
  214. SequenceTracker(const SequenceTracker&);
  215. ~SequenceTracker();
  216. uint64_t initial_memory_ = 0u;
  217. uint64_t total_memory_ = 0u;
  218. base::flat_map<GpuPeakMemoryAllocationSource, uint64_t>
  219. initial_memory_per_source_;
  220. base::flat_map<GpuPeakMemoryAllocationSource, uint64_t>
  221. peak_memory_per_source_;
  222. };
  223. std::unique_ptr<base::trace_event::TracedValue> StartTrackingTracedValue();
  224. std::unique_ptr<base::trace_event::TracedValue> StopTrackingTracedValue(
  225. SequenceTracker& sequence);
  226. // MemoryTracker::Observer:
  227. void OnMemoryAllocatedChange(
  228. CommandBufferId id,
  229. uint64_t old_size,
  230. uint64_t new_size,
  231. GpuPeakMemoryAllocationSource source =
  232. GpuPeakMemoryAllocationSource::UNKNOWN) override;
  233. // Tracks all currently requested sequences mapped to the peak memory seen.
  234. base::flat_map<uint32_t, SequenceTracker> sequence_trackers_;
  235. // Tracks the total current memory across all MemoryTrackers.
  236. uint64_t current_memory_ = 0u;
  237. base::flat_map<GpuPeakMemoryAllocationSource, uint64_t>
  238. current_memory_per_source_;
  239. std::unique_ptr<GpuMemoryAblationExperiment> ablation_experiment_;
  240. base::WeakPtrFactory<GpuPeakMemoryMonitor> weak_factory_;
  241. };
  242. void InternalDestroyGpuMemoryBuffer(gfx::GpuMemoryBufferId id, int client_id);
  243. #if BUILDFLAG(IS_ANDROID)
  244. void ScheduleWakeUpGpu();
  245. void DoWakeUpGpu();
  246. #endif
  247. void HandleMemoryPressure(
  248. base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level);
  249. // These objects manage channels to individual renderer processes. There is
  250. // one channel for each renderer process that has connected to this GPU
  251. // process.
  252. base::flat_map<int32_t, std::unique_ptr<GpuChannel>> gpu_channels_;
  253. scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
  254. scoped_refptr<base::SingleThreadTaskRunner> io_task_runner_;
  255. const GpuPreferences gpu_preferences_;
  256. const GpuDriverBugWorkarounds gpu_driver_bug_workarounds_;
  257. const raw_ptr<GpuChannelManagerDelegate> delegate_;
  258. raw_ptr<GpuWatchdogThread> watchdog_;
  259. scoped_refptr<gl::GLShareGroup> share_group_;
  260. std::unique_ptr<MailboxManager> mailbox_manager_;
  261. std::unique_ptr<gles2::Outputter> outputter_;
  262. raw_ptr<Scheduler> scheduler_;
  263. // SyncPointManager guaranteed to outlive running MessageLoop.
  264. const raw_ptr<SyncPointManager> sync_point_manager_;
  265. const raw_ptr<SharedImageManager> shared_image_manager_;
  266. std::unique_ptr<gles2::ProgramCache> program_cache_;
  267. gles2::ShaderTranslatorCache shader_translator_cache_;
  268. gles2::FramebufferCompletenessCache framebuffer_completeness_cache_;
  269. scoped_refptr<gl::GLSurface> default_offscreen_surface_;
  270. const raw_ptr<GpuMemoryBufferFactory> gpu_memory_buffer_factory_;
  271. GpuFeatureInfo gpu_feature_info_;
  272. ServiceDiscardableManager discardable_manager_;
  273. PassthroughDiscardableManager passthrough_discardable_manager_;
  274. #if BUILDFLAG(IS_ANDROID)
  275. // Last time we know the GPU was powered on. Global for tracking across all
  276. // transport surfaces.
  277. base::TimeTicks last_gpu_access_time_;
  278. base::TimeTicks begin_wake_up_time_;
  279. #endif
  280. raw_ptr<ImageDecodeAcceleratorWorker> image_decode_accelerator_worker_ =
  281. nullptr;
  282. // Flags which indicate GPU process activity. Read by the browser process
  283. // on GPU process crash.
  284. GpuProcessActivityFlags activity_flags_;
  285. base::MemoryPressureListener memory_pressure_listener_;
  286. // The SharedContextState is shared across all RasterDecoders. Note
  287. // that this class needs to be ref-counted to conveniently manage the lifetime
  288. // of the shared context in the case of a context loss. While the
  289. // GpuChannelManager strictly outlives the RasterDecoders, in the event of a
  290. // context loss the clients need to re-create the GpuChannel and command
  291. // buffers once notified. In this interim state we can have multiple instances
  292. // of the SharedContextState, for the lost and recovered clients. In
  293. // order to avoid having the GpuChannelManager keep the lost context state
  294. // alive until all clients have recovered, we use a ref-counted object and
  295. // allow the decoders to manage its lifetime.
  296. absl::optional<raster::GrShaderCache> gr_shader_cache_;
  297. scoped_refptr<SharedContextState> shared_context_state_;
  298. // With --enable-vulkan, |vulkan_context_provider_| will be set from
  299. // viz::GpuServiceImpl. The raster decoders will use it for rasterization if
  300. // features::Vulkan is used.
  301. raw_ptr<viz::VulkanContextProvider> vulkan_context_provider_ = nullptr;
  302. // If features::Metal, |metal_context_provider_| will be set from
  303. // viz::GpuServiceImpl. The raster decoders will use it for rasterization.
  304. raw_ptr<viz::MetalContextProvider> metal_context_provider_ = nullptr;
  305. // With features::SkiaDawn, |dawn_context_provider_| will be set from
  306. // viz::GpuServiceImpl. The raster decoders will use it for rasterization.
  307. raw_ptr<viz::DawnContextProvider> dawn_context_provider_ = nullptr;
  308. GpuPeakMemoryMonitor peak_memory_monitor_;
  309. // Creation time of GpuChannelManger.
  310. const base::TimeTicks creation_time_ = base::TimeTicks::Now();
  311. // Context lost time since creation of |GpuChannelManger|.
  312. base::TimeDelta context_lost_time_;
  313. // Count of context lost.
  314. int context_lost_count_ = 0;
  315. THREAD_CHECKER(thread_checker_);
  316. // Member variables should appear before the WeakPtrFactory, to ensure
  317. // that any WeakPtrs to Controller are invalidated before its members
  318. // variable's destructors are executed, rendering them invalid.
  319. base::WeakPtrFactory<GpuChannelManager> weak_factory_{this};
  320. };
  321. } // namespace gpu
  322. #endif // GPU_IPC_SERVICE_GPU_CHANNEL_MANAGER_H_