Debian Codegraph @

src/gpu/graphite/QueueManager.cpp

raw
1 /*
2 * Copyright 2022 Google LLC
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "src/gpu/graphite/QueueManager.h"
9
10 #include "include/gpu/GpuTypes.h"
11 #include "include/gpu/graphite/Recording.h"
12 #include "src/core/SkTraceEvent.h"
13 #include "src/gpu/GpuTypesPriv.h"
14 #include "src/gpu/RefCntedCallback.h"
15 #include "src/gpu/graphite/Buffer.h"
16 #include "src/gpu/graphite/Caps.h"
17 #include "src/gpu/graphite/CommandBuffer.h"
18 #include "src/gpu/graphite/ContextPriv.h"
19 #include "src/gpu/graphite/GpuWorkSubmission.h"
20 #include "src/gpu/graphite/Log.h"
21 #include "src/gpu/graphite/RecordingPriv.h"
22 #include "src/gpu/graphite/Surface_Graphite.h"
23 #include "src/gpu/graphite/UploadBufferManager.h"
24 #include "src/gpu/graphite/task/Task.h"
25 #include "src/gpu/graphite/task/TaskList.h"
26
27 namespace skgpu::graphite {
28
29 // This constant determines how many OutstandingSubmissions are allocated together as a block in
30 // the deque. As such it needs to balance allocating too much memory vs. incurring
31 // allocation/deallocation thrashing. It should roughly correspond to the max number of outstanding
32 // submissions we expect to see.
33 static constexpr int kDefaultOutstandingAllocCnt = 8;
34
35 QueueManager::QueueManager(const SharedContext* sharedContext)
36 : fSharedContext(sharedContext)
37 , fOutstandingSubmissions(sizeof(OutstandingSubmission), kDefaultOutstandingAllocCnt) {
38 }
39
40 QueueManager::~QueueManager() {
41 if (fSharedContext->caps()->allowCpuSync()) {
42 this->checkForFinishedWork(SyncToCpu::kYes);
43 } else if (!fOutstandingSubmissions.empty()) {
44 SKGPU_LOG_F("When ContextOptions::fNeverYieldToWebGPU is specified all GPU work must be "
45 "finished before destroying Context.");
46 }
47 }
48
49 std::vector<std::unique_ptr<CommandBuffer>>*
50 QueueManager::getAvailableCommandBufferList(Protected isProtected) {
51 return isProtected == Protected::kNo ? &fAvailableCommandBuffers
52 : &fAvailableProtectedCommandBuffers;
53 }
54
55
56 bool QueueManager::setupCommandBuffer(ResourceProvider* resourceProvider, Protected isProtected) {
57 if (!fCurrentCommandBuffer) {
58 std::vector<std::unique_ptr<CommandBuffer>>* bufferList =
59 this->getAvailableCommandBufferList(isProtected);
60 if (!bufferList->empty()) {
61 fCurrentCommandBuffer = std::move(bufferList->back());
62 bufferList->pop_back();
63 if (!fCurrentCommandBuffer->setNewCommandBufferResources()) {
64 fCurrentCommandBuffer.reset();
65 }
66 }
67 } else {
68 if (fCurrentCommandBuffer->isProtected() != isProtected) {
69 // If we're doing things where we are switching between using protected and unprotected
70 // command buffers, it is our job to make sure previous work was submitted.
71 SKGPU_LOG_E("Trying to use a CommandBuffer with protectedness that differs from our "
72 "current active command buffer.");
73 return false;
74 }
75 }
76 if (!fCurrentCommandBuffer) {
77 fCurrentCommandBuffer = this->getNewCommandBuffer(resourceProvider, isProtected);
78 }
79 if (!fCurrentCommandBuffer) {
80 return false;
81 }
82
83 return true;
84 }
85
86 InsertStatus QueueManager::addRecording(const InsertRecordingInfo& info, Context* context) {
87 TRACE_EVENT0_ALWAYS("skia.gpu", TRACE_FUNC);
88
89 // Configure the callback before validation so that failures are propagated to the finish
90 // procs that were registered on `info` as well.
91 bool addTimerQuery = false;
92 sk_sp<RefCntedCallback> callback;
93 if (info.fFinishedWithStatsProc) {
94 addTimerQuery = info.fGpuStatsFlags & GpuStatsFlags::kElapsedTime;
95 if (addTimerQuery && !(context->supportedGpuStats() & GpuStatsFlags::kElapsedTime)) {
96 addTimerQuery = false;
97 SKGPU_LOG_W("Requested elapsed time reporting but not supported by Context.");
98 }
99 callback = RefCntedCallback::Make(info.fFinishedWithStatsProc, info.fFinishedContext);
100 } else if (info.fFinishedProc) {
101 callback = RefCntedCallback::Make(info.fFinishedProc, info.fFinishedContext);
102 }
103
104 #define RETURN_FAIL_IF(failureCase, status, fmt, ...) \
105 if (failureCase) { \
106 if (callback) { callback->setFailureResult(); } \
107 info.fRecording->priv().setFailureResultForFinishedProcs(); \
108 info.fRecording->priv().deinstantiateVolatileLazyProxies(); \
109 SKGPU_LOG_E(fmt, ##__VA_ARGS__); \
110 return status; \
111 } do {} while(false)
112 #define SIMULATE_FAIL(status) \
113 RETURN_FAIL_IF(info.fSimulatedStatus == status, status, "Simulating '" #status "' failure")
114
115 RETURN_FAIL_IF(!info.fRecording,
116 InsertStatus::kInvalidRecording,
117 "No valid Recording passed into addRecording call");
118
119 // Recordings from a Recorder that requires ordered recordings will have a valid recorder ID.
120 // Recordings that don't have any required order are assigned SK_InvalidID.
121 uint32_t recorderID = info.fRecording->priv().recorderID();
122 if (recorderID != SK_InvalidGenID) {
123 uint32_t* recordingID = fLastAddedRecordingIDs.find(recorderID);
124 RETURN_FAIL_IF(recordingID && info.fRecording->priv().uniqueID() != *recordingID + 1,
125 InsertStatus::kOutOfOrderRecording,
126 "Recordings are expected to be replayed in order");
127
128 // Note the new Recording ID.
129 fLastAddedRecordingIDs.set(recorderID, info.fRecording->priv().uniqueID());
130 }
131
132 RETURN_FAIL_IF(info.fTargetSurface && !asSB(info.fTargetSurface)->isGraphiteBacked(),
133 InsertStatus::kInvalidRecording,
134 "Target surface passed into addRecording call is not Graphite-backed");
135
136 SIMULATE_FAIL(InsertStatus::kInvalidRecording);
137
138 auto resourceProvider = context->priv().resourceProvider();
139 // Technically no commands have been added yet, but if this fails, things are in a bad state
140 // so signal the unrecoverable status.
141 RETURN_FAIL_IF(!this->setupCommandBuffer(resourceProvider, fSharedContext->isProtected()),
142 InsertStatus::kAddCommandsFailed,
143 "CommandBuffer creation failed");
144
145 // This must happen before instantiating the lazy proxies, because the target for draws in this
146 // recording may itself be a lazy proxy whose instantiation must be handled specially here.
147 // We must also make sure the lazy proxies are instantiated successfully before we make any
148 // modifications to the current command buffer, so we can't just do all this work in
149 // Recording::addCommands below.
150 TextureProxy* deferredTargetProxy = info.fRecording->priv().deferredTargetProxy();
151 AutoDeinstantiateTextureProxy autoDeinstantiateTargetProxy(deferredTargetProxy);
152 const Texture* replayTarget = nullptr;
153 if (deferredTargetProxy) {
154 RETURN_FAIL_IF(!info.fTargetSurface,
155 InsertStatus::kPromiseImageInstantiationFailed,
156 "No surface provided to instantiate deferred replay target");
157
158 replayTarget = info.fRecording->priv().setupDeferredTarget(
159 resourceProvider,
160 static_cast<Surface*>(info.fTargetSurface),
161 info.fTargetTranslation,
162 info.fTargetClip);
163
164 RETURN_FAIL_IF(!replayTarget,
165 InsertStatus::kPromiseImageInstantiationFailed,
166 "Failed to set up deferred replay target");
167 }
168
169 RETURN_FAIL_IF(info.fRecording->priv().hasNonVolatileLazyProxies() &&
170 !info.fRecording->priv().instantiateNonVolatileLazyProxies(resourceProvider),
171 InsertStatus::kPromiseImageInstantiationFailed,
172 "Non-volatile PromiseImage instantiation has failed");
173
174 RETURN_FAIL_IF(info.fRecording->priv().hasVolatileLazyProxies() &&
175 !info.fRecording->priv().instantiateVolatileLazyProxies(resourceProvider),
176 InsertStatus::kPromiseImageInstantiationFailed,
177 "Volitile PromiseImage instantiation has failed");
178
179 SIMULATE_FAIL(InsertStatus::kPromiseImageInstantiationFailed);
180
181 if (addTimerQuery) {
182 fCurrentCommandBuffer->startTimerQuery();
183 }
184 fCurrentCommandBuffer->addWaitSemaphores(info.fNumWaitSemaphores, info.fWaitSemaphores);
185 if (!info.fRecording->priv().addCommands(context,
186 fCurrentCommandBuffer.get(),
187 replayTarget,
188 info.fTargetTranslation,
189 info.fTargetClip)) {
190 // If the commands failed, iterate over all the used pipelines to see if their async
191 // compilation was the reason for failure. Clients that manage pipeline disk caches may
192 // want to handle the failure differently than when any other GPU command failed.
193 const bool validPipelines = info.fRecording->priv().taskList()->visitPipelines(
194 [](const GraphicsPipeline* pipeline) {
195 return !pipeline->didAsyncCompilationFail();
196 });
197
198 // We are already definitely going to fail, it's just a matter of which status to return
199 RETURN_FAIL_IF(validPipelines,
200 InsertStatus::kAddCommandsFailed,
201 "Adding Recording commands to the CommandBuffer has failed");
202 RETURN_FAIL_IF(true,
203 InsertStatus::kAsyncShaderCompilesFailed,
204 "Async pipeline compiles failed, unable to add Recording commands");
205 }
206
207 SIMULATE_FAIL(InsertStatus::kAddCommandsFailed);
208 SIMULATE_FAIL(InsertStatus::kAsyncShaderCompilesFailed);
209
210 fCurrentCommandBuffer->addSignalSemaphores(info.fNumSignalSemaphores, info.fSignalSemaphores);
211 if (info.fTargetTextureState) {
212 fCurrentCommandBuffer->prepareSurfaceForStateUpdate(info.fTargetSurface,
213 info.fTargetTextureState);
214 }
215 if (addTimerQuery) {
216 fCurrentCommandBuffer->endTimerQuery();
217 }
218
219 if (callback) {
220 fCurrentCommandBuffer->addFinishedProc(std::move(callback));
221 }
222
223 info.fRecording->priv().deinstantiateVolatileLazyProxies();
224
225 // If we got here, the simulated status should be kSuccess or it means we missed returning the
226 // simulated error earlier.
227 SkASSERT(info.fSimulatedStatus == InsertStatus::kSuccess);
228 return InsertStatus::kSuccess;
229 }
230
231 bool QueueManager::addTask(Task* task,
232 Context* context,
233 Protected isProtected) {
234 SkASSERT(task);
235 if (!task) {
236 SKGPU_LOG_E("No valid Task passed into addTask call");
237 return false;
238 }
239
240 if (!this->setupCommandBuffer(context->priv().resourceProvider(), isProtected)) {
241 SKGPU_LOG_E("CommandBuffer creation failed");
242 return false;
243 }
244
245 if (task->addCommands(context, fCurrentCommandBuffer.get(), {}) == Task::Status::kFail) {
246 SKGPU_LOG_E("Adding Task commands to the CommandBuffer has failed");
247 return false;
248 }
249
250 return true;
251 }
252
253 bool QueueManager::addFinishInfo(const InsertFinishInfo& info,
254 ResourceProvider* resourceProvider,
255 SkSpan<const sk_sp<Buffer>> buffersToAsyncMap) {
256 sk_sp<RefCntedCallback> callback;
257 if (info.fFinishedProc) {
258 callback = RefCntedCallback::Make(info.fFinishedProc, info.fFinishedContext);
259 }
260
261 if (!this->setupCommandBuffer(resourceProvider, fSharedContext->isProtected())) {
262 if (callback) {
263 callback->setFailureResult();
264 }
265 SKGPU_LOG_E("CommandBuffer creation failed");
266 return false;
267 }
268
269 if (callback) {
270 fCurrentCommandBuffer->addFinishedProc(std::move(callback));
271 }
272 fCurrentCommandBuffer->addBuffersToAsyncMapOnSubmit(buffersToAsyncMap);
273
274 return true;
275 }
276
277 bool QueueManager::submitToGpu(const SubmitInfo& submitInfo) {
278 TRACE_EVENT0_ALWAYS("skia.gpu", TRACE_FUNC);
279
280 if (!fCurrentCommandBuffer) {
281 // We warn because this probably representative of a bad client state, where they don't
282 // need to submit but didn't notice, but technically the submit itself is fine (no-op), so
283 // we return true.
284 SKGPU_LOG_D("Submit called with no active command buffer!");
285 return true;
286 }
287
288 #ifdef SK_DEBUG
289 if (!fCurrentCommandBuffer->hasWork()) {
290 SKGPU_LOG_D("Submitting empty command buffer!");
291 }
292 #endif
293
294 auto submission = this->onSubmitToGpu(submitInfo);
295 if (!submission) {
296 return false;
297 }
298
299 new (fOutstandingSubmissions.push_back()) OutstandingSubmission(std::move(submission));
300 return true;
301 }
302
303 bool QueueManager::hasUnfinishedGpuWork() { return !fOutstandingSubmissions.empty(); }
304
305 void QueueManager::checkForFinishedWork(SyncToCpu sync) {
306 TRACE_EVENT1("skia.gpu", TRACE_FUNC, "sync", sync == SyncToCpu::kYes);
307
308 if (sync == SyncToCpu::kYes) {
309 SkASSERT(fSharedContext->caps()->allowCpuSync());
310 // wait for the last submission to finish
311 OutstandingSubmission* back = (OutstandingSubmission*)fOutstandingSubmissions.back();
312 if (back) {
313 (*back)->waitUntilFinished(fSharedContext);
314 }
315 }
316
317 // Iterate over all the outstanding submissions to see if any have finished. The work
318 // submissions are in order from oldest to newest, so we start at the front to check if they
319 // have finished. If so we pop it off and move onto the next.
320 // Repeat till we find a submission that has not finished yet (and all others afterwards are
321 // also guaranteed to not have finished).
322 OutstandingSubmission* front = (OutstandingSubmission*)fOutstandingSubmissions.front();
323 while (front && (*front)->isFinished(fSharedContext)) {
324 // Make sure we remove before deleting as deletion might try to kick off another submit
325 // (though hopefully *not* in Graphite).
326 fOutstandingSubmissions.pop_front();
327
328 // Since we used placement new we are responsible for calling the destructor manually.
329 front->~OutstandingSubmission();
330 front = (OutstandingSubmission*)fOutstandingSubmissions.front();
331 }
332 SkASSERT(sync == SyncToCpu::kNo || fOutstandingSubmissions.empty());
333 }
334
335 void QueueManager::returnCommandBuffer(std::unique_ptr<CommandBuffer> commandBuffer) {
336 std::vector<std::unique_ptr<CommandBuffer>>* bufferList =
337 this->getAvailableCommandBufferList(commandBuffer->isProtected());
338 bufferList->push_back(std::move(commandBuffer));
339 }
340
341 void QueueManager::addUploadBufferManagerRefs(UploadBufferManager* uploadManager) {
342 SkASSERT(fCurrentCommandBuffer);
343 uploadManager->transferToCommandBuffer(fCurrentCommandBuffer.get());
344 }
345
346
347 } // namespace skgpu::graphite