Debian Codegraph @

src/gpu/graphite/GlobalCache.cpp

raw ◀ ▶
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> result;
181 {
182 SkAutoSpinlock lock{fSpinLock};
183
•184 sk_sp<GraphicsPipeline>* entry = fGraphicsPipelineCache.find(key);
185 if (entry) {
•186 result = *entry;
187
188 if (result->didAsyncCompilationFail()) SK_UNLIKELY {
189 // If the pipeline failed, remove it from the cache and let it be regenerated.
•190 this->removeGraphicsPipeline(result.get());
191 return nullptr;
192 }
193 #if defined(GPU_TEST_UTILS)
194 ++fStats.fGraphicsCacheHits;
195 #endif
196
•197 if (result->epoch() != fEpochCounter) {
198 result->markEpoch(fEpochCounter); // update epoch due to use in a new epoch
199 ++fStats.fPipelineUsesInEpoch;
200 }
•201 if (!forPrecompile && result->fromPrecompile() && !result->wasUsed()) {
202 ++fStats.fNormalPreemptedByPrecompile;
203 }
204
•205 result->updateAccessTime();
206 result->markUsed();
207
208 #if defined(SK_PIPELINE_LIFETIME_LOGGING)
209 static const char* kNames[2] = { "CacheHitForN", "CacheHitForP" };
210 TRACE_EVENT_INSTANT2("skia.gpu",
211 TRACE_STR_STATIC(kNames[forPrecompile]),
212 TRACE_EVENT_SCOPE_THREAD,
213 "key", key.hash(),
•214 "compilationID", result->getPipelineInfo().fCompilationID);
215 #endif
216 } else {
217 #if defined(GPU_TEST_UTILS)
218 ++fStats.fGraphicsCacheMisses;
219 #endif
220
221 if (compilationID) {
222 // This is a cache miss so we know the next step is going to be a Pipeline
223 // creation. Create the compilationID here so we can use it in the "CacheMissFor"
224 // trace event.
225 *compilationID = next_compilation_id();
226
227 #if defined(SK_PIPELINE_LIFETIME_LOGGING)
228 static const char* kNames[2] = { "CacheMissForN", "CacheMissForP" };
229 TRACE_EVENT_INSTANT2("skia.gpu",
230 TRACE_STR_STATIC(kNames[forPrecompile]),
231 TRACE_EVENT_SCOPE_THREAD,
232 "key", key.hash(),
233 "compilationID", *compilationID);
234 #endif
235 }
236 }
237 }
238
•239 if (result) {
240 this->invokePipelineCallback(ContextOptions::PipelineCacheOp::kPipelineFound, result.get());
241 }
242
•243 return result;
244 }
245
246 #if SK_HISTOGRAMS_ENABLED
247 // These values are persisted to logs. Entries should not be renumbered and
248 // numeric values should never be reused.
249 //
250 // LINT.IfChange(PipelineCreationRace)
251 enum class PipelineCreationRace {
252 // The <First>Over<Second> enum names mean the first type of compilation won a compilation race
253 // over the second type of compilation and ended up in the cache.
254 kNormalOverNormal = 0, // can happen w/ multiple Recorders on different threads
255 kNormalOverPrecompilation = 1,
256 kPrecompilationOverNormal = 2,
257 kPrecompilationOverPrecompilation = 3, // can happen with multiple threaded precompilation calls
258
259 kMaxValue = kPrecompilationOverPrecompilation,
260 };
261 // LINT.ThenChange(//tools/metrics/histograms/enums.xml:SkiaPipelineCreationRace)
262
263 [[maybe_unused]] static constexpr int kPipelineCreationRaceCount =
264 static_cast<int>(PipelineCreationRace::kMaxValue) + 1;
265 #endif // SK_HISTOGRAMS_ENABLED
266
267 std::pair<sk_sp<GraphicsPipeline>, bool> GlobalCache::addGraphicsPipeline(
268 const UniqueKey& key,
269 sk_sp<GraphicsPipeline> pipeline) {
270 SkAutoSpinlock lock{fSpinLock};
271
272 sk_sp<GraphicsPipeline>* entry = fGraphicsPipelineCache.find(key);
273 if (!entry) {
274 // No equivalent pipeline was stored in the cache between a previous call to
275 // findGraphicsPipeline() that returned null (triggering the pipeline creation) and this
276 // later adding to the cache.
277 entry = fGraphicsPipelineCache.insert(key, std::move(pipeline));
278
279 #if defined(GPU_TEST_UTILS)
280 ++fStats.fGraphicsCacheAdditions;
281 #endif
282
283 SkASSERT((*entry)->epoch() == 0);
284 (*entry)->markEpoch(fEpochCounter); // mark w/ epoch in which it was created
285 ++fStats.fPipelineUsesInEpoch;
286
287 if ((*entry)->fromPrecompile()) {
288 ++fStats.fUnpreemptedPrecompilePipelines;
289 }
290
291 // Precompile Pipelines are only marked as used when they get a cache hit in
292 // findGraphicsPipeline
293 if (!(*entry)->fromPrecompile()) {
294 (*entry)->updateAccessTime();
295 (*entry)->markUsed();
296 }
297
298 #if defined(SK_PIPELINE_LIFETIME_LOGGING)
299 static const char* kNames[2] = { "AddedN", "AddedP" };
300 TRACE_EVENT_INSTANT2("skia.gpu",
301 TRACE_STR_STATIC(kNames[(*entry)->fromPrecompile()]),
302 TRACE_EVENT_SCOPE_THREAD,
303 "key", key.hash(),
304 "compilationID", (*entry)->getPipelineInfo().fCompilationID);
305 #endif
306
307 return {*entry, true};
308 } else {
309 #if defined(GPU_TEST_UTILS)
310 // else there was a race creating the same pipeline and this thread lost, so return
311 // the winner
312 ++fStats.fGraphicsRaces;
313 #endif
314
315 [[maybe_unused]] int race = (*entry)->fromPrecompile() * 2 + pipeline->fromPrecompile();
316
317 #if defined(SK_PIPELINE_LIFETIME_LOGGING)
318 static const char* kNames[4] = {
319 "NWonRaceOverN",
320 "NWonRaceOverP",
321 "PWonRaceOverN",
322 "PWonRaceOverP"
323 };
324 TRACE_EVENT_INSTANT2("skia.gpu",
325 TRACE_STR_STATIC(kNames[race]),
326 TRACE_EVENT_SCOPE_THREAD,
327 "key", key.hash(),
328 // The losing compilation
329 "compilationID", pipeline->getPipelineInfo().fCompilationID);
330 #endif
331
332 SK_HISTOGRAM_ENUMERATION("Graphite.PipelineCreationRace",
333 race,
334 kPipelineCreationRaceCount);
335
336 return {*entry, false};
337 }
338 }
339
340 // Requires that the caller must have locked 'fSpinLock'
341 void GlobalCache::removeGraphicsPipeline(const GraphicsPipeline* pipeline) {
342
343 skia_private::STArray<1, skgpu::UniqueKey> toRemove;
344 // This is only called when a pipeline failed to compile, so it is not performance critical.
345 fGraphicsPipelineCache.foreach([&toRemove, pipeline](const UniqueKey* key,
346 const sk_sp<GraphicsPipeline>* inCache) {
347 // Since inCache is ref'ed by GlobalCache, we can safely compare direct addresses and not
348 // worry about a new GraphicsPipeline being allocated at an address that was still here.
349 if ((*inCache).get() == pipeline) {
350 toRemove.push_back(*key);
351 }
352 });
353
354 // The pipeline shouldn't have multiple unique keys, but this is structured to clean up every
355 // occurrence of pipeline in fGraphicsPipelineCache in release builds.
356 SkASSERT(toRemove.size() <= 1);
357
358 for (const skgpu::UniqueKey& k : toRemove) {
359 fGraphicsPipelineCache.remove(k);
360 }
361 }
362
363 void GlobalCache::purgePipelinesNotUsedSince(StdSteadyClock::time_point purgeTime) {
364 SkAutoSpinlock lock{fSpinLock};
365
366 skia_private::TArray<skgpu::UniqueKey> toRemove;
367
368 // This is probably fine for now but is looping from most-recently-used to least-recently-used.
369 // It seems like a reverse loop with an early out could be more efficient.
370 fGraphicsPipelineCache.foreach([&toRemove, purgeTime](const UniqueKey* key,
371 const sk_sp<GraphicsPipeline>* pipeline) {
372 if ((*pipeline)->lastAccessTime() < purgeTime) {
373 toRemove.push_back(*key);
374 }
375 });
376
377 for (const skgpu::UniqueKey& k : toRemove) {
378 #if defined(GPU_TEST_UTILS)
379 ++fStats.fGraphicsPurges;
380 #endif
381 fGraphicsPipelineCache.remove(k);
382 }
383
384 // TODO: add purging of Compute Pipelines (b/389073204)
385 }
386
387 void GlobalCache::reportPrecompileStats() {
388 SkAutoSpinlock lock{fSpinLock};
389
390 uint32_t numUnusedInCache = 0;
391
392 fGraphicsPipelineCache.foreach([&numUnusedInCache](const UniqueKey* key,
393 const sk_sp<GraphicsPipeline>* pipeline) {
394 if (!(*pipeline)->wasUsed()) {
395 SkASSERT((*pipeline)->fromPrecompile());
396 ++numUnusedInCache;
397 }
398 });
399
400 // From local testing we expect these UMA stats to comfortably fit in the specified ranges.
401 // If we see a lot of the counts hitting the over and under-flow buckets something
402 // unexpected is happening and we would need to figure it out and, possibly, create
403 // new UMA statistics for the observed range.
404 SK_HISTOGRAM_CUSTOM_EXACT_LINEAR("Graphite.Precompile.NormalPreemptedByPrecompile",
405 fStats.fNormalPreemptedByPrecompile,
406 /* countMin= */ 1,
407 /* countMax= */ 51,
408 /* bucketCount= */ 52);
409 SK_HISTOGRAM_CUSTOM_EXACT_LINEAR("Graphite.Precompile.UnpreemptedPrecompilePipelines",
410 fStats.fUnpreemptedPrecompilePipelines,
411 /* countMin= */ 100,
412 /* countMax= */ 150,
413 /* bucketCount= */ 52);
414 SK_HISTOGRAM_CUSTOM_EXACT_LINEAR("Graphite.Precompile.UnusedPrecompiledPipelines",
415 fStats.fPurgedUnusedPrecompiledPipelines + numUnusedInCache,
416 /* countMin= */ 50,
417 /* countMax= */ 100,
418 /* bucketCount= */ 52);
419 }
420
421 void GlobalCache::reportCacheStats() {
422 SkAutoSpinlock lock{fSpinLock};
423
424 SK_HISTOGRAM_CUSTOM_EXACT_LINEAR("Graphite.PipelineCache.PipelineUsesInEpoch",
425 fStats.fPipelineUsesInEpoch,
426 /* countMin= */ 1,
427 /* countMax= */ 1001,
428 /* bucketCount= */ 102); // 10/bucket
429
430 // Set up for a new epoch
431 fStats.fPipelineUsesInEpoch = 0;
432 ++fEpochCounter;
433 if (!fEpochCounter) {
434 // The epoch counter has wrapped around - this should be *very* rare. Reset the cache.
435 fGraphicsPipelineCache.foreach([](const UniqueKey* key,
436 const sk_sp<GraphicsPipeline>* pipeline) {
437 (*pipeline)->markEpoch(0);
438 });
439 fEpochCounter = 1;
440 }
441 }
442
443 #if defined(GPU_TEST_UTILS)
444 int GlobalCache::numGraphicsPipelines() const {
445 SkAutoSpinlock lock{fSpinLock};
446
447 return fGraphicsPipelineCache.count();
448 }
449
450 void GlobalCache::resetGraphicsPipelines() {
451 SkAutoSpinlock lock{fSpinLock};
452
453 fGraphicsPipelineCache.reset();
454 }
455
456 void GlobalCache::forEachGraphicsPipeline(
457 const std::function<void(const UniqueKey&, const GraphicsPipeline*)>& fn) {
458 SkAutoSpinlock lock{fSpinLock};
459
460 fGraphicsPipelineCache.foreach([&](const UniqueKey* k, const sk_sp<GraphicsPipeline>* v) {
461 fn(*k, v->get());
462 });
463 }
464
465 uint16_t GlobalCache::getEpoch() const {
466 SkAutoSpinlock lock{fSpinLock};
467
468 return fEpochCounter;
469 }
470
471 // The next reportCacheStats call after this will overflow
472 void GlobalCache::forceNextEpochOverflow() {
473 SkAutoSpinlock lock{fSpinLock};
474
475 fEpochCounter = std::numeric_limits<uint16_t>::max();
476 }
477
478 // Get the offsets and sizes of the renderstep static uploads.
479 void GlobalCache::testingOnly_SetStaticVertexInfo(
480 skia_private::TArray<StaticVertexCopyRanges> vertBufferInfo, const Buffer* vertBuffer) {
481 SkAutoSpinlock lock{fSpinLock};
482
483 fStaticVertexInfo = vertBufferInfo;
484 fStaticVertexBuffer = vertBuffer;
485 }
486
487 SkSpan<const GlobalCache::StaticVertexCopyRanges> GlobalCache::getStaticVertexCopyRanges() const {
488 SkAutoSpinlock lock{fSpinLock};
489
490 return SkSpan<const GlobalCache::StaticVertexCopyRanges>(fStaticVertexInfo);
491 }
492
493 sk_sp<Buffer> GlobalCache::getStaticVertexBuffer() {
494 SkAutoSpinlock lock{fSpinLock};
495
496 return sk_ref_sp(fStaticVertexBuffer);
497 }
498
499 #endif // defined(GPU_TEST_UTILS)
500
501 GlobalCache::PipelineStats GlobalCache::getStats() const {
502 SkAutoSpinlock lock{fSpinLock};
503
504 return fStats;
505 }
506
507 sk_sp<ComputePipeline> GlobalCache::findComputePipeline(const UniqueKey& key) {
508 SkAutoSpinlock lock{fSpinLock};
509
510 sk_sp<ComputePipeline>* entry = fComputePipelineCache.find(key);
511 return entry ? *entry : nullptr;
512 }
513
514 sk_sp<ComputePipeline> GlobalCache::addComputePipeline(const UniqueKey& key,
515 sk_sp<ComputePipeline> pipeline) {
516 SkAutoSpinlock lock{fSpinLock};
517
518 sk_sp<ComputePipeline>* entry = fComputePipelineCache.find(key);
519 if (!entry) {
520 entry = fComputePipelineCache.insert(key, std::move(pipeline));
521 }
522 return *entry;
523 }
524
525 void GlobalCache::addStaticResource(sk_sp<Resource> resource) {
526 SkAutoSpinlock lock{fSpinLock};
527
528 fStaticResource.push_back(std::move(resource));
529 }
530
531 } // namespace skgpu::graphite