command_buffer_stub.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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_COMMAND_BUFFER_STUB_H_
  5. #define GPU_IPC_SERVICE_COMMAND_BUFFER_STUB_H_
  6. #include <stddef.h>
  7. #include <stdint.h>
  8. #include <memory>
  9. #include <string>
  10. #include <vector>
  11. #include "base/callback.h"
  12. #include "base/memory/raw_ptr.h"
  13. #include "base/memory/weak_ptr.h"
  14. #include "base/observer_list.h"
  15. #include "base/time/time.h"
  16. #include "base/timer/timer.h"
  17. #include "build/build_config.h"
  18. #include "gpu/command_buffer/common/command_buffer_id.h"
  19. #include "gpu/command_buffer/common/constants.h"
  20. #include "gpu/command_buffer/common/gpu_memory_allocation.h"
  21. #include "gpu/command_buffer/common/mailbox.h"
  22. #include "gpu/command_buffer/service/command_buffer_service.h"
  23. #include "gpu/command_buffer/service/context_group.h"
  24. #include "gpu/command_buffer/service/decoder_client.h"
  25. #include "gpu/command_buffer/service/program_cache.h"
  26. #include "gpu/command_buffer/service/scheduler_task_runner.h"
  27. #include "gpu/command_buffer/service/sequence_id.h"
  28. #include "gpu/ipc/common/gpu_channel.mojom.h"
  29. #include "gpu/ipc/common/surface_handle.h"
  30. #include "gpu/ipc/service/context_url.h"
  31. #include "gpu/ipc/service/gpu_ipc_service_export.h"
  32. #include "mojo/public/cpp/bindings/associated_receiver.h"
  33. #include "mojo/public/cpp/bindings/shared_associated_remote.h"
  34. #include "third_party/abseil-cpp/absl/types/optional.h"
  35. #include "ui/gfx/geometry/size.h"
  36. #include "ui/gfx/gpu_memory_buffer.h"
  37. #include "ui/gfx/swap_result.h"
  38. #include "ui/gl/gl_share_group.h"
  39. #include "ui/gl/gl_surface.h"
  40. #include "ui/gl/gpu_preference.h"
  41. #include "url/gurl.h"
  42. namespace gpu {
  43. class DecoderContext;
  44. class MemoryTracker;
  45. struct SyncToken;
  46. struct WaitForCommandState;
  47. class GpuChannel;
  48. class SyncPointClientState;
  49. // CommandBufferStub is a base class for different CommandBuffer backends
  50. // (e.g. GLES2, Raster, WebGPU) within the GPU service. Each instance lives on
  51. // the main thread and receives IPCs there, either dispatched to the default
  52. // main thread TaskRunner, or a specific main-thread sequence on the GPU
  53. // Scheduler.
  54. //
  55. // For every CommandBufferStub instance, there's a corresponding
  56. // CommandBufferProxyImpl client.
  57. class GPU_IPC_SERVICE_EXPORT CommandBufferStub
  58. : public CommandBufferServiceClient,
  59. public DecoderClient,
  60. public mojom::CommandBuffer,
  61. public base::SupportsWeakPtr<CommandBufferStub> {
  62. public:
  63. class DestructionObserver {
  64. public:
  65. // Called in Destroy(), before the context/surface are released.
  66. // If |have_context| is false, then the context cannot be made current, else
  67. // it already is.
  68. virtual void OnWillDestroyStub(bool have_context) = 0;
  69. protected:
  70. virtual ~DestructionObserver() = default;
  71. };
  72. CommandBufferStub(GpuChannel* channel,
  73. const mojom::CreateCommandBufferParams& init_params,
  74. CommandBufferId command_buffer_id,
  75. SequenceId sequence_id,
  76. int32_t stream_id,
  77. int32_t route_id);
  78. CommandBufferStub(const CommandBufferStub&) = delete;
  79. CommandBufferStub& operator=(const CommandBufferStub&) = delete;
  80. ~CommandBufferStub() override;
  81. // Exposes a SequencedTaskRunner which can be used to schedule tasks in
  82. // sequence with this CommandBufferStub -- that is, on the same gpu::Scheduler
  83. // sequence. Does not support nested loops or delayed tasks.
  84. scoped_refptr<base::SequencedTaskRunner> task_runner() const {
  85. return scheduler_task_runner_;
  86. }
  87. // This must leave the GL context associated with the newly-created
  88. // CommandBufferStub current, so the GpuChannel can initialize
  89. // the gpu::Capabilities.
  90. virtual gpu::ContextResult Initialize(
  91. CommandBufferStub* share_group,
  92. const mojom::CreateCommandBufferParams& params,
  93. base::UnsafeSharedMemoryRegion shared_state_shm) = 0;
  94. // Establish Mojo bindings for the receiver and client endpoints.
  95. void BindEndpoints(
  96. mojo::PendingAssociatedReceiver<mojom::CommandBuffer> receiver,
  97. mojo::PendingAssociatedRemote<mojom::CommandBufferClient> client,
  98. scoped_refptr<base::SingleThreadTaskRunner> io_task_runner);
  99. MemoryTracker* GetMemoryTracker() const;
  100. virtual MemoryTracker* GetContextGroupMemoryTracker() const = 0;
  101. // Executes a DeferredRequest routed to this command buffer by a GpuChannel.
  102. void ExecuteDeferredRequest(
  103. mojom::DeferredCommandBufferRequestParams& params);
  104. // Instructs the CommandBuffer to wait asynchronously until the reader has
  105. // updated the token value to be within the [start, end] range (inclusive).
  106. // `callback` is invoked with the last known State once this occurs, or with
  107. // an invalid State if the CommandBuffer is destroyed first.
  108. using WaitForStateCallback =
  109. base::OnceCallback<void(const gpu::CommandBuffer::State&)>;
  110. void WaitForTokenInRange(int32_t start,
  111. int32_t end,
  112. WaitForStateCallback callback);
  113. // Instructs the CommandBuffer to wait asynchronously until the reader has
  114. // reached a get offset within the range [start, end] (inclusive). `callback`
  115. // is invoked with the last known State once this occurs, or with an invalid
  116. // State if the CommandBuffer is destroyed first.
  117. void WaitForGetOffsetInRange(uint32_t set_get_buffer_count,
  118. int32_t start,
  119. int32_t end,
  120. WaitForStateCallback callback);
  121. // CommandBufferServiceClient implementation:
  122. CommandBatchProcessedResult OnCommandBatchProcessed() override;
  123. void OnParseError() override;
  124. // DecoderClient implementation:
  125. void OnConsoleMessage(int32_t id, const std::string& message) override;
  126. void CacheBlob(gpu::GpuDiskCacheType type,
  127. const std::string& key,
  128. const std::string& blob) override;
  129. void OnFenceSyncRelease(uint64_t release) override;
  130. void OnDescheduleUntilFinished() override;
  131. void OnRescheduleAfterFinished() override;
  132. void ScheduleGrContextCleanup() override;
  133. void HandleReturnData(base::span<const uint8_t> data) override;
  134. using MemoryTrackerFactory =
  135. base::RepeatingCallback<std::unique_ptr<MemoryTracker>()>;
  136. // Overrides the way CreateMemoryTracker() uses to create a MemoryTracker.
  137. // This is intended for mocking the MemoryTracker in tests.
  138. static void SetMemoryTrackerFactoryForTesting(MemoryTrackerFactory factory);
  139. scoped_refptr<Buffer> GetTransferBuffer(int32_t id);
  140. void RegisterTransferBufferForTest(int32_t id, scoped_refptr<Buffer> buffer);
  141. // Whether this command buffer can currently handle IPC messages.
  142. bool IsScheduled();
  143. // Whether there are commands in the buffer that haven't been processed.
  144. bool HasUnprocessedCommands();
  145. DecoderContext* decoder_context() const { return decoder_context_.get(); }
  146. GpuChannel* channel() const { return channel_; }
  147. // Unique command buffer ID for this command buffer stub.
  148. CommandBufferId command_buffer_id() const { return command_buffer_id_; }
  149. SequenceId sequence_id() const { return sequence_id_; }
  150. int32_t stream_id() const { return stream_id_; }
  151. gl::GLSurface* surface() const { return surface_.get(); }
  152. ContextType context_type() const { return context_type_; }
  153. void AddDestructionObserver(DestructionObserver* observer);
  154. void RemoveDestructionObserver(DestructionObserver* observer);
  155. void MarkContextLost();
  156. scoped_refptr<gl::GLShareGroup> share_group() { return share_group_; }
  157. protected:
  158. // Scoper to help with setup and teardown boilerplate around operations which
  159. // may require the context to be current and which may need to process pending
  160. // queries or schedule other delayed work after completion. This makes the
  161. // context current on construction if possible.
  162. class ScopedContextOperation {
  163. public:
  164. explicit ScopedContextOperation(CommandBufferStub& stub);
  165. ~ScopedContextOperation();
  166. // Making the context current on construction may fail, in which case the
  167. // caller may wish to avoid doing work. This indicates whether it succeeded
  168. // or failed.
  169. bool is_context_current() const { return cache_use_.has_value(); }
  170. private:
  171. CommandBufferStub& stub_;
  172. bool have_context_ = false;
  173. absl::optional<gles2::ProgramCache::ScopedCacheUse> cache_use_;
  174. };
  175. mojom::CommandBufferClient& client() { return *client_.get(); }
  176. // mojom::CommandBuffer:
  177. void SetGetBuffer(int32_t shm_id) override;
  178. void RegisterTransferBuffer(
  179. int32_t id,
  180. base::UnsafeSharedMemoryRegion transfer_buffer) override;
  181. void CreateGpuFenceFromHandle(uint32_t id,
  182. gfx::GpuFenceHandle handle) override;
  183. void GetGpuFenceHandle(uint32_t id,
  184. GetGpuFenceHandleCallback callback) override;
  185. void SignalSyncToken(const SyncToken& sync_token, uint32_t id) override;
  186. void SignalQuery(uint32_t query, uint32_t id) override;
  187. void BindMediaReceiver(mojo::GenericPendingAssociatedReceiver receiver,
  188. BindMediaReceiverCallback callback) override;
  189. virtual void OnTakeFrontBuffer(const Mailbox& mailbox) {}
  190. virtual void OnReturnFrontBuffer(const Mailbox& mailbox, bool is_lost) {}
  191. std::unique_ptr<MemoryTracker> CreateMemoryTracker() const;
  192. // Must be called during Initialize(). Takes ownership to co-ordinate
  193. // teardown in Destroy().
  194. void set_decoder_context(std::unique_ptr<DecoderContext> decoder_context) {
  195. decoder_context_ = std::move(decoder_context);
  196. }
  197. void CheckContextLost();
  198. // Sets |active_url_| as the active GPU process URL.
  199. void UpdateActiveUrl();
  200. bool MakeCurrent();
  201. // The lifetime of objects of this class is managed by a GpuChannel. The
  202. // GpuChannels destroy all the CommandBufferStubs that they own when
  203. // they are destroyed. So a raw pointer is safe.
  204. const raw_ptr<GpuChannel> channel_;
  205. ContextType context_type_;
  206. ContextUrl active_url_;
  207. bool initialized_;
  208. const SurfaceHandle surface_handle_;
  209. bool use_virtualized_gl_context_;
  210. std::unique_ptr<CommandBufferService> command_buffer_;
  211. // Have an ownership of the memory tracker used in children class. This is to
  212. // ensure that the memory tracker outlives the objects that uses it, for
  213. // example the ContextGroup referenced both in the Decoder and the
  214. // CommandBufferStub.
  215. std::unique_ptr<gpu::MemoryTracker> memory_tracker_;
  216. scoped_refptr<gl::GLSurface> surface_;
  217. scoped_refptr<SyncPointClientState> sync_point_client_state_;
  218. scoped_refptr<gl::GLShareGroup> share_group_;
  219. const CommandBufferId command_buffer_id_;
  220. const SequenceId sequence_id_;
  221. const scoped_refptr<SchedulerTaskRunner> scheduler_task_runner_;
  222. const int32_t stream_id_;
  223. const int32_t route_id_;
  224. private:
  225. void Destroy();
  226. gles2::ProgramCache::ScopedCacheUse CreateCacheUse();
  227. // Message handlers:
  228. void OnAsyncFlush(int32_t put_offset,
  229. uint32_t flush_id,
  230. const std::vector<SyncToken>& sync_token_fences);
  231. void OnDestroyTransferBuffer(int32_t id);
  232. void OnSignalAck(uint32_t id);
  233. void ReportState();
  234. // Poll the command buffer to execute work.
  235. void PollWork();
  236. void PerformWork();
  237. // Schedule processing of delayed work. This updates the time at which
  238. // delayed work should be processed. |process_delayed_work_time_| is
  239. // updated to current time + delay. Call this after processing some amount
  240. // of delayed work.
  241. void ScheduleDelayedWork(base::TimeDelta delay);
  242. void CheckCompleteWaits();
  243. // Set driver bug workarounds and disabled GL extensions to the context.
  244. static void SetContextGpuFeatureInfo(gl::GLContext* context,
  245. const GpuFeatureInfo& gpu_feature_info);
  246. static MemoryTrackerFactory GetMemoryTrackerFactory();
  247. // Overrides the way CreateMemoryTracker() uses to create a MemoryTracker. If
  248. // |factory| is base::NullCallback(), it returns the current
  249. // MemoryTrackerFactory (initially base::NullCallback() which
  250. // CreateMemoryTracker() should interpret as a signal to use the default).
  251. // This is intended for mocking the MemoryTracker in tests.
  252. static MemoryTrackerFactory SetOrGetMemoryTrackerFactory(
  253. MemoryTrackerFactory factory);
  254. std::unique_ptr<DecoderContext> decoder_context_;
  255. uint32_t last_flush_id_;
  256. base::ObserverList<DestructionObserver>::Unchecked destruction_observers_;
  257. base::DeadlineTimer process_delayed_work_timer_;
  258. uint32_t previous_processed_num_;
  259. base::TimeTicks last_idle_time_;
  260. std::unique_ptr<WaitForCommandState> wait_for_token_;
  261. std::unique_ptr<WaitForCommandState> wait_for_get_offset_;
  262. uint32_t wait_set_get_buffer_count_;
  263. mojo::AssociatedReceiver<mojom::CommandBuffer> receiver_{this};
  264. mojo::SharedAssociatedRemote<mojom::CommandBufferClient> client_;
  265. };
  266. } // namespace gpu
  267. #endif // GPU_IPC_SERVICE_COMMAND_BUFFER_STUB_H_