Debian Codegraph @

src/gpu/graphite/GlobalCache.cpp

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
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/GlobalCache.h"
9
10 #include "include/gpu/graphite/Context.h"
11 #include "include/private/base/SkTArray.h"
12 #include "src/core/SkTraceEvent.h"
13 #include "src/gpu/graphite/Buffer.h"
14 #include "src/gpu/graphite/ComputePipeline.h"
15 #include "src/gpu/graphite/ContextUtils.h"
16 #include "src/gpu/graphite/GraphicsPipeline.h"
17 #include "src/gpu/graphite/GraphicsPipelineDesc.h"
18 #include "src/gpu/graphite/RenderPassDesc.h"
19 #include "src/gpu/graphite/Resource.h"
20 #include "src/gpu/graphite/ResourceProvider.h"
21 #include "src/gpu/graphite/Sampler.h"
22 #include "src/gpu/graphite/SerializationUtils.h"
23 #include "src/gpu/graphite/SharedContext.h"
24
25 namespace {
26
27 uint32_t next_compilation_id() {
28 static std::atomic<uint32_t> nextId{0};
29 // Not worried about overflow since we don't expect that many GraphicsPipelines.
30 // Even if it wraps around to 0, this is solely for debug logging.
31 return nextId.fetch_add(1, std::memory_order_relaxed);
32 }
33
34 #if defined(GPU_TEST_UTILS)
35 // TODO(b/391403921): get rid of this special case once we've got color space transform shader
36 // specialization more under control
37 constexpr int kGlobalGraphicsPipelineCacheSizeLimit = 1 << 13;
38 constexpr int kGlobalComputePipelineCacheSizeLimit = 256;
39
40 #else
41 // TODO: find a good value for these limits
42 constexpr int kGlobalGraphicsPipelineCacheSizeLimit = 256;
43 constexpr int kGlobalComputePipelineCacheSizeLimit = 256;
44 #endif
45
46 } // anonymous namespace
47
48 namespace skgpu::graphite {
49
50 GlobalCache::GlobalCache()
51 : fGraphicsPipelineCache(kGlobalGraphicsPipelineCacheSizeLimit, &fStats)
52 , fComputePipelineCache(kGlobalComputePipelineCacheSizeLimit)
53 , fDynamicSamplers({}) {}
54
55 GlobalCache::~GlobalCache() {
56 // These should have been cleared out earlier by deleteResources().
57 SkDEBUGCODE(SkAutoSpinlock lock{fSpinLock});
58 SkASSERT(fGraphicsPipelineCache.count() == 0);
59 SkASSERT(fComputePipelineCache.count() == 0);
60 SkASSERT(fStaticResource.empty());
61 SkASSERT(fDynamicSamplers[0] == nullptr);
62 }
63
64 void GlobalCache::setPipelineCallback(PipelineCallbackContext context,
65 PipelineCallback callback,
66 DeprecatedPipelineCallback deprecatedCallback) {
67 // This should only ever be called once (in Context's constructor)
68 SkASSERT(!fPipelineCallbackContext && !fPipelineCallback && !fDeprecatedPipelineCallback);
69
70 fPipelineCallbackContext = context;
71 fPipelineCallback = callback;
72 fDeprecatedPipelineCallback = deprecatedCallback;
73 }
74
75 void GlobalCache::invokePipelineCallback(ContextOptions::PipelineCacheOp op,
76 const GraphicsPipeline* pipeline,
77 sk_sp<SkData> serializedKey) {
78 // If both callbacks are provided the new version preempts the old version
79 if (fPipelineCallback) {
80 (*fPipelineCallback)(fPipelineCallbackContext,
81 op,
82 pipeline->getLabel(),
83 pipeline->getPipelineInfo().fUniqueKeyHash,
84 pipeline->fromPrecompile(),
85 std::move(serializedKey));
86 } else if (fDeprecatedPipelineCallback && serializedKey) {
87 (*fDeprecatedPipelineCallback)(fPipelineCallbackContext, std::move(serializedKey));
88 }
89 }
90
91 void GlobalCache::deleteResources() {
92 SkAutoSpinlock lock{fSpinLock};
93
94 for (int i = 0; i < kNumDynamicSamplers; ++i) {
95 fDynamicSamplers[i] = nullptr;
96 }
97
98 fGraphicsPipelineCache.reset();
99 fComputePipelineCache.reset();
100 fStaticResource.clear();
101 }
102
103 bool GlobalCache::initializeDynamicSamplers(ResourceProvider* resourceProvider, const Caps* caps) {
104 SkAutoSpinlock lock{fSpinLock};
105
106 SkASSERT(fDynamicSamplers[0] == nullptr); // Must not already be initialized
107
108 static constexpr SkTileMode kTileModes[] = {SkTileMode::kClamp,
109 SkTileMode::kRepeat,
110 SkTileMode::kMirror,
111 SkTileMode::kDecal};
112 // Manually unroll the SkSamplingOptions that can be dynamic samplers to avoid nesting so many
113 // loops to create SamplerDescs. Cubic SkSamplingOptions do not need to contribute to this list.
114 // TODO: Support anisotropic filters
115 static constexpr SkSamplingOptions kSamplingOptions[] = {
116 {SkFilterMode::kNearest, SkMipmapMode::kNone},
117 {SkFilterMode::kLinear, SkMipmapMode::kNone},
118 {SkFilterMode::kNearest, SkMipmapMode::kNearest},
119 {SkFilterMode::kLinear, SkMipmapMode::kNearest},
120 {SkFilterMode::kNearest, SkMipmapMode::kLinear},
121 {SkFilterMode::kLinear, SkMipmapMode::kLinear}
122 };
123
124 const bool supportsClampToBorder = caps->clampToBorderSupport();
125 for (auto samplingOption : kSamplingOptions) {
126 for (auto tileX : kTileModes) {
127 for (auto tileY : kTileModes) {
128 if (!supportsClampToBorder && (tileX == SkTileMode::kDecal ||
129 tileY == SkTileMode::kDecal)) {
130 continue;
131 }
132
133 SamplerDesc dynamicDesc{samplingOption, {tileX, tileY}};
134 SkASSERT(!dynamicDesc.isImmutable() && dynamicDesc.asSpan().size() == 1);
135 sk_sp<Sampler> sampler =
136 resourceProvider->findOrCreateCompatibleSampler(dynamicDesc);
137 if (!sampler) {
138 return false;
139 }
140
141 // We already hold the spin lock, so add directly to fStaticResource
142 fStaticResource.emplace_back(sampler);
143 fDynamicSamplers[dynamicDesc.desc()] = sampler.get();
144 }
145 }
146 }
147
148 return true;
149 }
150
151 void GlobalCache::LogPurge(void* context, const UniqueKey& key, sk_sp<GraphicsPipeline>* p) {
152 PipelineStats* stats = static_cast<PipelineStats*>(context);
153
154 if ((*p)->fromPrecompile() && !(*p)->wasUsed()) {
155 ++stats->fPurgedUnusedPrecompiledPipelines;
156 }
157
158 #if defined(SK_PIPELINE_LIFETIME_LOGGING)
159 // A "Bad" Purge is one where the Pipeline was never retrieved from the Cache (i.e., unused
160 // overgeneration).
161 static const char* kNames[2][2] = { { "BadPurgedN", "BadPurgedP" },
162 { "PurgedN", "PurgedP"} };
163
164 TRACE_EVENT_INSTANT2("skia.gpu",
165 TRACE_STR_STATIC(kNames[(*p)->wasUsed()][(*p)->fromPrecompile()]),
166 TRACE_EVENT_SCOPE_THREAD,
167 "key", key.hash(),
168 "compilationID", (*p)->getPipelineInfo().fCompilationID);
169 #endif
170 }
171
172 sk_sp<GraphicsPipeline> GlobalCache::findGraphicsPipeline(
173 const UniqueKey& key,
174 SkEnumBitMask<PipelineCreationFlags> pipelineCreationFlags,
175 uint32_t *compilationID) {
176
177 [[maybe_unused]] bool forPrecompile =
178 SkToBool(pipelineCreationFlags & PipelineCreationFlags::kForPrecompilation);
179
180 sk_sp<GraphicsPipeline>* entry = nullptr;
181 {
182 SkAutoSpinlock lock{fSpinLock};
183
184 entry = fGraphicsPipelineCache.find(key);
185 if (entry) {
186 if ((*entry)->didAsyncCompilationFail()) SK_UNLIKELY {
187 // If the pipeline failed, remove it from the cache and let it be regenerated.
188 this->removeGraphicsPipeline((*entry).get());
189 return nullptr;
190 }
191 #if defined(GPU_TEST_UTILS)
192 ++fStats.fGraphicsCacheHits;
193 #endif
194
195 if ((*entry)->epoch() != fEpochCounter) {
196 (*entry)->markEpoch(fEpochCounter); // update epoch due to use in a new epoch
197 ++fStats.fPipelineUsesInEpoch;
198 }
199 if (!forPrecompile && (*entry)->fromPrecompile() && !(*entry)->wasUsed()) {
200 ++fStats.fNormalPreemptedByPrecompile;
201 }
202
203 (*entry)->updateAccessTime();
204 (*entry)->markUsed();
205
206 #if defined(SK_PIPELINE_LIFETIME_LOGGING)
207 static const char* kNames[2] = { "CacheHitForN", "CacheHitForP" };
208 TRACE_EVENT_INSTANT2("skia.gpu",
209 TRACE_STR_STATIC(kNames[forPrecompile]),
210 TRACE_EVENT_SCOPE_THREAD,
211 "key", key.hash(),
212 "compilationID", (*entry)->getPipelineInfo().fCompilationID);
213 #endif
214 } else {
215 #if defined(GPU_TEST_UTILS)
216 ++fStats.fGraphicsCacheMisses;
217 #endif
218
219 if (compilationID) {
220 // This is a cache miss so we know the next step is going to be a Pipeline
221 // creation. Create the compilationID here so we can use it in the "CacheMissFor"
222 // trace event.
223 *compilationID = next_compilation_id();
224
225 #if defined(SK_PIPELINE_LIFETIME_LOGGING)
226 static const char* kNames[2] = { "CacheMissForN", "CacheMissForP" };
227 TRACE_EVENT_INSTANT2("skia.gpu",
228 TRACE_STR_STATIC(kNames[forPrecompile]),
229 TRACE_EVENT_SCOPE_THREAD,
230 "key", key.hash(),
231 "compilationID", *compilationID);
232 #endif
233 }
234 }
235 }
236
237 if (entry) {
238 this->invokePipelineCallback(ContextOptions::PipelineCacheOp::kPipelineFound, entry->get());
239 return *entry;
240 }
241
242 return nullptr;
243 }
244
245 #if SK_HISTOGRAMS_ENABLED
246 // These values are persisted to logs. Entries should not be renumbered and
247 // numeric values should never be reused.
248 //
249 // LINT.IfChange(PipelineCreationRace)
250 enum class PipelineCreationRace {
251 // The <First>Over<Second> enum names mean the first type of compilation won a compilation race
252 // over the second type of compilation and ended up in the cache.
253 kNormalOverNormal = 0, // can happen w/ multiple Recorders on different threads
254 kNormalOverPrecompilation = 1,
255 kPrecompilationOverNormal = 2,
256 kPrecompilationOverPrecompilation = 3, // can happen with multiple threaded precompilation calls
257
258 kMaxValue = kPrecompilationOverPrecompilation,
259 };
260 // LINT.ThenChange(//tools/metrics/histograms/enums.xml:SkiaPipelineCreationRace)
261
262 [[maybe_unused]] static constexpr int kPipelineCreationRaceCount =
263 static_cast<int>(PipelineCreationRace::kMaxValue) + 1;
264 #endif // SK_HISTOGRAMS_ENABLED
265
266 std::pair<sk_sp<GraphicsPipeline>, bool> GlobalCache::addGraphicsPipeline(
267 const UniqueKey& key,
268 sk_sp<GraphicsPipeline> pipeline) {
269 SkAutoSpinlock lock{fSpinLock};
270
271 sk_sp<GraphicsPipeline>* entry = fGraphicsPipelineCache.find(key);
272 if (!entry) {
273 // No equivalent pipeline was stored in the cache between a previous call to
274 // findGraphicsPipeline() that returned null (triggering the pipeline creation) and this
275 // later adding to the cache.
276 entry = fGraphicsPipelineCache.insert(key, std::move(pipeline));
277
278 #if defined(GPU_TEST_UTILS)
279 ++fStats.fGraphicsCacheAdditions;
280 #endif
281
282 SkASSERT((*entry)->epoch() == 0);
283 (*entry)->markEpoch(fEpochCounter); // mark w/ epoch in which it was created
284 ++fStats.fPipelineUsesInEpoch;
285
286 if ((*entry)->fromPrecompile()) {
287 ++fStats.fUnpreemptedPrecompilePipelines;
288 }
289
290 // Precompile Pipelines are only marked as used when they get a cache hit in
291 // findGraphicsPipeline
292 if (!(*entry)->fromPrecompile()) {
293 (*entry)->updateAccessTime();
294 (*entry)->markUsed();
295 }
296
297 #if defined(SK_PIPELINE_LIFETIME_LOGGING)
298 static const char* kNames[2] = { "AddedN", "AddedP" };
299 TRACE_EVENT_INSTANT2("skia.gpu",
300 TRACE_STR_STATIC(kNames[(*entry)->fromPrecompile()]),
301 TRACE_EVENT_SCOPE_THREAD,
302 "key", key.hash(),
303 "compilationID", (*entry)->getPipelineInfo().fCompilationID);
304 #endif
305
306 return {*entry, true};
307 } else {
308 #if defined(GPU_TEST_UTILS)
309 // else there was a race creating the same pipeline and this thread lost, so return
310 // the winner
311 ++fStats.fGraphicsRaces;
312 #endif
313
314 [[maybe_unused]] int race = (*entry)->fromPrecompile() * 2 + pipeline->fromPrecompile();
315
316 #if defined(SK_PIPELINE_LIFETIME_LOGGING)
317 static const char* kNames[4] = {
318 "NWonRaceOverN",
319 "NWonRaceOverP",
320 "PWonRaceOverN",
321 "PWonRaceOverP"
322 };
323 TRACE_EVENT_INSTANT2("skia.gpu",
324 TRACE_STR_STATIC(kNames[race]),
325 TRACE_EVENT_SCOPE_THREAD,
326 "key", key.hash(),
327 // The losing compilation
328 "compilationID", pipeline->getPipelineInfo().fCompilationID);
329 #endif
330
331 SK_HISTOGRAM_ENUMERATION("Graphite.PipelineCreationRace",
332 race,
333 kPipelineCreationRaceCount);
334
335 return {*entry, false};
336 }
337 }
338
339 // Requires that the caller must have locked 'fSpinLock'
340 void GlobalCache::removeGraphicsPipeline(const GraphicsPipeline* pipeline) {
341
342 skia_private::STArray<1, skgpu::UniqueKey> toRemove;
343 // This is only called when a pipeline failed to compile, so it is not performance critical.
344 fGraphicsPipelineCache.foreach([&toRemove, pipeline](const UniqueKey* key,
345 const sk_sp<GraphicsPipeline>* inCache) {
346 // Since inCache is ref'ed by GlobalCache, we can safely compare direct addresses and not
347 // worry about a new GraphicsPipeline being allocated at an address that was still here.
348 if ((*inCache).get() == pipeline) {
349 toRemove.push_back(*key);
350 }
351 });
352
353 // The pipeline shouldn't have multiple unique keys, but this is structured to clean up every
354 // occurrence of pipeline in fGraphicsPipelineCache in release builds.
355 SkASSERT(toRemove.size() <= 1);
356
357 for (const skgpu::UniqueKey& k : toRemove) {
358 fGraphicsPipelineCache.remove(k);
359 }
360 }
361
362 void GlobalCache::purgePipelinesNotUsedSince(StdSteadyClock::time_point purgeTime) {
363 SkAutoSpinlock lock{fSpinLock};
364
365 skia_private::TArray<skgpu::UniqueKey> toRemove;
366
367 // This is probably fine for now but is looping from most-recently-used to least-recently-used.
368 // It seems like a reverse loop with an early out could be more efficient.
369 fGraphicsPipelineCache.foreach([&toRemove, purgeTime](const UniqueKey* key,
370 const sk_sp<GraphicsPipeline>* pipeline) {
371 if ((*pipeline)->lastAccessTime() < purgeTime) {
372 toRemove.push_back(*key);
373 }
374 });
375
376 for (const skgpu::UniqueKey& k : toRemove) {
377 #if defined(GPU_TEST_UTILS)
378 ++fStats.fGraphicsPurges;
379 #endif
380 fGraphicsPipelineCache.remove(k);
381 }
382
383 // TODO: add purging of Compute Pipelines (b/389073204)
384 }
385
386 void GlobalCache::reportPrecompileStats() {
387 SkAutoSpinlock lock{fSpinLock};
388
389 uint32_t numUnusedInCache = 0;
390
391 fGraphicsPipelineCache.foreach([&numUnusedInCache](const UniqueKey* key,
392 const sk_sp<GraphicsPipeline>* pipeline) {
393 if (!(*pipeline)->wasUsed()) {
394 SkASSERT((*pipeline)->fromPrecompile());
395 ++numUnusedInCache;
396 }
397 });
398
399 // From local testing we expect these UMA stats to comfortably fit in the specified ranges.
400 // If we see a lot of the counts hitting the over and under-flow buckets something
401 // unexpected is happening and we would need to figure it out and, possibly, create
402 // new UMA statistics for the observed range.
403 SK_HISTOGRAM_CUSTOM_EXACT_LINEAR("Graphite.Precompile.NormalPreemptedByPrecompile",
404 fStats.fNormalPreemptedByPrecompile,
405 /* countMin= */ 1,
406 /* countMax= */ 51,
407 /* bucketCount= */ 52);
408 SK_HISTOGRAM_CUSTOM_EXACT_LINEAR("Graphite.Precompile.UnpreemptedPrecompilePipelines",
409 fStats.fUnpreemptedPrecompilePipelines,
410 /* countMin= */ 100,
411 /* countMax= */ 150,
412 /* bucketCount= */ 52);
413 SK_HISTOGRAM_CUSTOM_EXACT_LINEAR("Graphite.Precompile.UnusedPrecompiledPipelines",
414 fStats.fPurgedUnusedPrecompiledPipelines + numUnusedInCache,
415 /* countMin= */ 50,
416 /* countMax= */ 100,
417 /* bucketCount= */ 52);
418 }
419
420 void GlobalCache::reportCacheStats() {
421 SkAutoSpinlock lock{fSpinLock};
422
423 SK_HISTOGRAM_CUSTOM_EXACT_LINEAR("Graphite.PipelineCache.PipelineUsesInEpoch",
424 fStats.fPipelineUsesInEpoch,
425 /* countMin= */ 1,
426 /* countMax= */ 1001,
427 /* bucketCount= */ 102); // 10/bucket
428
429 // Set up for a new epoch
430 fStats.fPipelineUsesInEpoch = 0;
431 ++fEpochCounter;
432 if (!fEpochCounter) {
433 // The epoch counter has wrapped around - this should be *very* rare. Reset the cache.
434 fGraphicsPipelineCache.foreach([](const UniqueKey* key,
435 const sk_sp<GraphicsPipeline>* pipeline) {
436 (*pipeline)->markEpoch(0);
437 });
438 fEpochCounter = 1;
439 }
440 }
441
442 #if defined(GPU_TEST_UTILS)
443 int GlobalCache::numGraphicsPipelines() const {
444 SkAutoSpinlock lock{fSpinLock};
445
446 return fGraphicsPipelineCache.count();
447 }
448
449 void GlobalCache::resetGraphicsPipelines() {
450 SkAutoSpinlock lock{fSpinLock};
451
452 fGraphicsPipelineCache.reset();
453 }
454
455 void GlobalCache::forEachGraphicsPipeline(
456 const std::function<void(const UniqueKey&, const GraphicsPipeline*)>& fn) {
457 SkAutoSpinlock lock{fSpinLock};
458
459 fGraphicsPipelineCache.foreach([&](const UniqueKey* k, const sk_sp<GraphicsPipeline>* v) {
460 fn(*k, v->get());
461 });
462 }
463
464 uint16_t GlobalCache::getEpoch() const {
465 SkAutoSpinlock lock{fSpinLock};
466
467 return fEpochCounter;
468 }
469
470 // The next reportCacheStats call after this will overflow
471 void GlobalCache::forceNextEpochOverflow() {
472 SkAutoSpinlock lock{fSpinLock};
473
474 fEpochCounter = std::numeric_limits<uint16_t>::max();
475 }
476
477 // Get the offsets and sizes of the renderstep static uploads.
478 void GlobalCache::testingOnly_SetStaticVertexInfo(
479 skia_private::TArray<StaticVertexCopyRanges> vertBufferInfo, const Buffer* vertBuffer) {
480 SkAutoSpinlock lock{fSpinLock};
481
482 fStaticVertexInfo = vertBufferInfo;
483 fStaticVertexBuffer = vertBuffer;
484 }
485
486 SkSpan<const GlobalCache::StaticVertexCopyRanges> GlobalCache::getStaticVertexCopyRanges() const {
487 SkAutoSpinlock lock{fSpinLock};
488
489 return SkSpan<const GlobalCache::StaticVertexCopyRanges>(fStaticVertexInfo);
490 }
491
492 sk_sp<Buffer> GlobalCache::getStaticVertexBuffer() {
493 SkAutoSpinlock lock{fSpinLock};
494
495 return sk_ref_sp(fStaticVertexBuffer);
496 }
497
498 #endif // defined(GPU_TEST_UTILS)
499
500 GlobalCache::PipelineStats GlobalCache::getStats() const {
501 SkAutoSpinlock lock{fSpinLock};
502
503 return fStats;
504 }
505
506 sk_sp<ComputePipeline> GlobalCache::findComputePipeline(const UniqueKey& key) {
507 SkAutoSpinlock lock{fSpinLock};
508
509 sk_sp<ComputePipeline>* entry = fComputePipelineCache.find(key);
510 return entry ? *entry : nullptr;
511 }
512
513 sk_sp<ComputePipeline> GlobalCache::addComputePipeline(const UniqueKey& key,
514 sk_sp<ComputePipeline> pipeline) {
515 SkAutoSpinlock lock{fSpinLock};
516
517 sk_sp<ComputePipeline>* entry = fComputePipelineCache.find(key);
518 if (!entry) {
519 entry = fComputePipelineCache.insert(key, std::move(pipeline));
520 }
521 return *entry;
522 }
523
524 void GlobalCache::addStaticResource(sk_sp<Resource> resource) {
525 SkAutoSpinlock lock{fSpinLock};
526
527 fStaticResource.push_back(std::move(resource));
528 }
529
530 } // namespace skgpu::graphite