Repository navigation
Expand file tree
/
Copy pathMultisampleTarget.cpp
More file actions
1832 lines (1700 loc) · 112 KB
/
Copy pathMultisampleTarget.cpp
File metadata and controls
1832 lines (1700 loc) · 112 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "prx/libSceAgcDriver/Graphics/include/MemoryAccounting.hpp"
#include <shared_mutex>
#include "prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp"
#include "prx/libSceAgcDriver/Graphics/include/ColorTargetLayout.hpp"
#include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp"
#include "prx/libSceAgcDriver/Graphics/include/FirstSampleCopy.hpp"
#include "prx/libSceAgcDriver/Graphics/include/BufferPool.hpp"
#include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Pipeline.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Resources.hpp"
#include "prx/libSceAgcDriver/Graphics/include/SampleOrder.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp"
#include "prx/libSceAgcDriver/Graphics/include/TextureFormat.hpp"
#include "prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp"
#include "prx/libSceAgcDriver/Graphics/include/MultisampleTextureLayout.hpp"
#include "IntermediateRepresentation/IrMetadata/BufferFormat.hpp"
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include "prx/libc/include/GuestAllocations.hpp"
#include "prx/libc/include/PrimedSharedMutex.hpp"
#include <algorithm>
#include <array>
#include <atomic>
#include <bit>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <limits>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <span>
#include <utility>
#include <vector>
namespace AgcDriver::Graphics {
namespace {
VkFormat uintStorageViewFormat(VkFormat format) {
switch (format) {
case VK_FORMAT_R8G8_SINT: return VK_FORMAT_R8G8_UINT;
case VK_FORMAT_R8G8B8A8_SINT: return VK_FORMAT_R8G8B8A8_UINT;
case VK_FORMAT_R16_SINT:
case VK_FORMAT_R16_SFLOAT: return VK_FORMAT_R16_UINT;
case VK_FORMAT_R16G16_SINT:
case VK_FORMAT_R16G16_SFLOAT: return VK_FORMAT_R16G16_UINT;
case VK_FORMAT_R16G16B16A16_SINT:
case VK_FORMAT_R16G16B16A16_SFLOAT: return VK_FORMAT_R16G16B16A16_UINT;
case VK_FORMAT_R32_SINT: return VK_FORMAT_R32_UINT;
case VK_FORMAT_R32G32_SINT: return VK_FORMAT_R32G32_UINT;
case VK_FORMAT_R32G32B32A32_SINT: return VK_FORMAT_R32G32B32A32_UINT;
default: return VK_FORMAT_UNDEFINED;
}
}
std::uint32_t MultisampledBlockLog2(ColorTileMode mode) {
switch (mode) {
case ColorTileMode::Standard4KB: return 12u;
case ColorTileMode::Standard64KB: case ColorTileMode::Z64KBX: case ColorTileMode::D64KBX: case ColorTileMode::RenderTarget: return 16u;
default: return 0u;
}
}
std::uint64_t collectBlocks(std::uint64_t address, std::size_t bytes) {
constexpr std::uint64_t block = 65536;
const auto first = address & ~(block - 1);
const auto stop = (address + bytes + block - 1) & ~(block - 1);
const auto generation = GuestMemory::CollectWritesUncached(first, static_cast<std::size_t>(stop - first));
return generation != 0 ? generation : GuestMemory::CollectWritesUncached(address, bytes);
}
GuestTextureResource fmaskSnapshotResource(const GuestTextureResource& resource) {
Require(resource.format == static_cast<std::uint32_t>(ShaderRecompiler::IrBufferFormat::Format32UInt) && resource.fmaskCmaskAddress != 0u, "FMASK image format read semantics are not implemented");
Require(resource.dimension == TextureDimension::k2D || resource.dimension == TextureDimension::k2DArray, "FMASK image dimension is not implemented");
Require(resource.tileMode == TextureTileMode::kZ64KBX && (resource.pipeBankXor & ~0xcf00u) == 0u, "FMASK image swizzle or pipe/bank XOR is not implemented");
Require(resource.width != 0u && resource.width <= 16384u && resource.height != 0u && resource.height <= 16384u && resource.depthOrLastArray < 8192u && resource.baseArray <= resource.depthOrLastArray, "invalid FMASK image extent or layer range");
Require(resource.dimension == TextureDimension::k2DArray || (resource.depthOrLastArray == 0u && resource.baseArray == 0u), "FMASK 2D image has an array range");
Require(resource.mipCount == 1u && resource.allocatedMipCount == 1u && resource.baseLevel == 0u && resource.lastLevel == 0u && resource.minLod == 0u, "FMASK image mip fields are not implemented");
Require(resource.fmaskCmaskAddress == 0u || resource.dccPipeAligned, "FMASK image CMASK must be pipe aligned");
for (const auto selector : {resource.dstSelX, resource.dstSelY, resource.dstSelZ, resource.dstSelW}) Require(selector == 0u || selector == 1u || selector == 4u, "FMASK image selects an unverified channel");
auto snapshot = resource;
snapshot.format = static_cast<std::uint32_t>(ShaderRecompiler::IrBufferFormat::Format32UInt);
snapshot.tileMode = TextureTileMode::kLinear;
snapshot.pipeBankXor = 0u;
snapshot.dccAddress = 0u;
snapshot.fmaskCmaskAddress = 0u;
snapshot.dccAlphaOnMsb = false;
snapshot.dccPipeAligned = false;
return snapshot;
}
GuestTextureResource fmaskResource(const ColorTarget& target) {
GuestTextureResource resource{};
resource.baseAddress = target.fmaskAddress;
resource.width = target.extent.width;
resource.height = target.extent.height;
resource.mipCount = 1u;
resource.allocatedMipCount = 1u;
resource.tileMode = TextureTileMode::kZ64KBX;
resource.dimension = TextureDimension::k2D;
resource.format = static_cast<std::uint32_t>(ShaderRecompiler::IrBufferFormat::Format32UInt);
resource.dstSelX = 4u;
resource.pipeBankXor = target.fmaskPipeBankXor;
resource.fmaskCmaskAddress = target.cmaskAddress;
resource.dccPipeAligned = true;
return resource;
}
bool sameTarget(const ColorTarget& a, const ColorTarget& b) {
return a.surfaceAddress == b.surfaceAddress && a.format == b.format && a.extent.width == b.extent.width && a.extent.height == b.extent.height && a.samples == b.samples && a.eqaaFragments == b.eqaaFragments;
}
std::uint32_t storedFragments(const ColorTarget& target) {
return target.eqaaFragments != 0 ? target.eqaaFragments : target.samples;
}
constexpr char fmaskPlane[] = "the FMASK of EQAA color target";
std::uint64_t fmaskBytes(const ColorTarget& target) {
const auto bitsPerSample = std::bit_ceil(static_cast<std::uint32_t>(std::bit_width(target.eqaaFragments)));
return ColorTargetLayout(target.extent.width, target.extent.height, ColorTileMode::Z64KBX, std::max(1u, target.samples * bitsPerSample / 8u)).Bytes();
}
std::string eqaaReadRefusal(const char* access, const ColorTarget& rendered, const GuestTextureResource& resource) {
char text[288];
std::snprintf(text, sizeof(text), "AGC graphics: %s EQAA color target 0x%llx (%ux%u, %u samples, %u fragments) through a %ux%u texture of %u samples is not implemented", access, static_cast<unsigned long long>(resource.baseAddress), rendered.extent.width, rendered.extent.height, rendered.samples, rendered.eqaaFragments, resource.width, resource.height, resource.samples);
return text;
}
constexpr VkImageUsageFlags twinViewUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
VkFormat colorTwinFormat(const Context& context, VkFormat format) {
if (const auto srgb = SrgbTwinFormat(context, format); srgb != VK_FORMAT_UNDEFINED) return srgb;
for (const auto unorm : {VK_FORMAT_R8_UNORM, VK_FORMAT_R8G8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_A8B8G8R8_UNORM_PACK32}) {
if (SrgbTwinFormat(context, unorm) == format) return unorm;
}
return VK_FORMAT_UNDEFINED;
}
bool recreated(const ColorTarget& resident, const ColorTarget& use) {
return use.dccAddress != 0 && use.pipeBankXor != resident.pipeBankXor && use.address == resident.address && use.dccAddress == resident.dccAddress && use.dccControl == resident.dccControl && use.dccAlphaOnMsb == resident.dccAlphaOnMsb && use.dccPipeAligned == resident.dccPipeAligned && use.cmaskAddress == resident.cmaskAddress && use.cmaskBytes == resident.cmaskBytes && use.tileMode == resident.tileMode && use.elementBytes == resident.elementBytes;
}
VkClearColorValue fastClearColor(const ColorTarget& target) {
Require(target.elementBytes != 0 && target.elementBytes <= sizeof(target.clearWords) && 16u % target.elementBytes == 0, "the fast clear of a multisampled target over 64-bit texels is not modeled");
std::array<std::byte, 16> texels{};
for (std::size_t offset = 0; offset < texels.size(); offset += target.elementBytes) std::memcpy(texels.data() + offset, target.clearWords.data(), target.elementBytes);
std::array<std::uint32_t, 4> pattern{};
std::memcpy(pattern.data(), texels.data(), texels.size());
VkClearColorValue clear{};
Require(ClearColorForTexel(target.format, target.elementBytes, pattern, clear), "the fast-clear color of a multisampled target has no exact clear value in its format");
return clear;
}
std::uint64_t guardedColorBytes(const ColorTarget& target) {
const auto fragments = storedFragments(target);
auto bytes = std::max<std::uint64_t>(target.bytes * fragments, static_cast<std::uint64_t>(target.extent.width) * target.extent.height * target.elementBytes * fragments);
if (MultisampledBlockLog2(target.tileMode) == 16u && target.tileMode != ColorTileMode::Standard64KB && std::has_single_bit(target.elementBytes) && std::has_single_bit(fragments)) {
const auto log2Fragments = std::countr_zero(fragments);
const auto log2Pixels = 16u - std::countr_zero(target.elementBytes) - log2Fragments;
const auto log2Width = (log2Pixels + ((log2Fragments & 1u) == 0u ? 1u : 0u)) / 2u;
const auto blockWidth = 1u << log2Width;
const auto blockHeight = 1u << (log2Pixels - log2Width);
const auto align = [](std::uint32_t extent, std::uint32_t block) { return (static_cast<std::uint64_t>(extent) + block - 1u) / block * block; };
bytes = align(target.extent.width, blockWidth) * align(target.extent.height, blockHeight) * target.elementBytes * fragments;
}
return bytes;
}
std::optional<std::uint8_t> texelByte(VkFormat format, const VkClearColorValue& value) {
if (format == VK_FORMAT_R8_UINT) return value.uint32[0] <= 255u ? std::optional<std::uint8_t>(static_cast<std::uint8_t>(value.uint32[0])) : std::nullopt;
if (format != VK_FORMAT_R8_UNORM) return std::nullopt;
const auto code = std::lround(value.float32[0] * 255.0f);
if (code < 0 || code > 255 || static_cast<float>(code) / 255.0f != value.float32[0]) return std::nullopt;
return static_cast<std::uint8_t>(code);
}
template<typename Record>
void recordCommands(const Context& context, Record&& record) {
auto* recorder = Recorder::Active();
if (recorder != nullptr && recorder->Device() != context.device) recorder = nullptr;
std::unique_ptr<CommandBatch> batch;
if (recorder == nullptr) batch = std::make_unique<CommandBatch>(context);
record(recorder != nullptr ? recorder->Commands() : batch->Handle(), recorder);
if (batch) batch->SubmitAndWait();
}
struct TargetUse {
std::atomic<bool> hostOnly{true};
std::atomic<std::uint64_t> writes{0};
std::atomic<bool> claimed{false};
};
class MultisampleTarget : public std::enable_shared_from_this<MultisampleTarget> {
public:
MultisampleTarget(const Context& context, const ColorTarget& target, bool guestSamples = false) : context(context), target(target), cmask(target.cmaskAddress, target.cmaskBytes), colorFill(target) {
this->context.bufferPool.reset();
if (target.dccAddress != 0) metadataValid = std::make_shared<std::atomic<bool>>(true);
const auto initial = initialDccClear(target);
if (target.dccAddress != 0) cleared = initial;
const auto samples = static_cast<VkSampleCountFlagBits>(target.samples);
Require((context.limits.framebufferColorSampleCounts & samples) != 0, "the device cannot render color with the target's sample count");
VkFormatProperties properties{};
context.formatProperties(context.physical, target.format, &properties);
Require((properties.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) != 0, "multisampled render-target format cannot be a color attachment");
usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
orderFormat = MayReorderSamples(context, target.samples) ? SampleOrderStorageFormat(context, target.format, target.elementBytes, target.samples) : VK_FORMAT_UNDEFINED;
const VkImageCreateFlags orderFlags = orderFormat != VK_FORMAT_UNDEFINED ? VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT | VK_IMAGE_CREATE_EXTENDED_USAGE_BIT : 0u;
if (orderFormat != VK_FORMAT_UNDEFINED) usage |= VK_IMAGE_USAGE_STORAGE_BIT;
VkImageFormatProperties supported{};
sampleable = (properties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) != 0 && context.imageFormatProperties(context.physical, target.format, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, usage | VK_IMAGE_USAGE_SAMPLED_BIT, orderFlags, &supported) == VK_SUCCESS && (supported.sampleCounts & samples) != 0;
if (sampleable) usage |= VK_IMAGE_USAGE_SAMPLED_BIT;
Check(context.imageFormatProperties(context.physical, target.format, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, usage, orderFlags, &supported), "vkGetPhysicalDeviceImageFormatProperties multisampled target");
Require((supported.sampleCounts & samples) != 0 && target.extent.width <= supported.maxExtent.width && target.extent.height <= supported.maxExtent.height, "multisampled render target exceeds device image limits");
storageFormat = HostStorageFormat(context, target.format);
const auto uintFormat = uintStorageViewFormat(storageFormat);
storageFlags = storageFormat != target.format || (uintFormat != VK_FORMAT_UNDEFINED && uintFormat != target.format) ? VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT | VK_IMAGE_CREATE_EXTENDED_USAGE_BIT : 0u;
const auto storageSupports = [&](VkFormat format, VkImageUsageFlags formatUsage, VkImageCreateFlags flags) {
VkImageFormatProperties properties{};
return context.imageFormatProperties(context.physical, format, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, formatUsage, flags, &properties) == VK_SUCCESS && (properties.sampleCounts & samples) != 0;
};
const auto uintStorageSupported = [&] {
if (uintFormat == VK_FORMAT_UNDEFINED) return true;
VkFormatProperties uintProperties{};
context.formatProperties(context.physical, uintFormat, &uintProperties);
return (uintProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) != 0 && storageSupports(uintFormat, VK_IMAGE_USAGE_STORAGE_BIT, 0u);
};
if (storageFormat != VK_FORMAT_UNDEFINED && (!context.storageImageMultisample || !storageSupports(storageFormat, VK_IMAGE_USAGE_STORAGE_BIT, 0u) || !storageSupports(target.format, usage | VK_IMAGE_USAGE_STORAGE_BIT, storageFlags) || !uintStorageSupported())) storageFormat = VK_FORMAT_UNDEFINED;
VkImageCreateFlags flags = orderFlags;
std::shared_ptr<Buffer> upload;
const auto elementFormat = guestSamples ? TextureDetiler::ImageElementFormat(target.elementBytes) : VK_FORMAT_UNDEFINED;
const auto alignment = std::max<VkDeviceSize>({4u, target.elementBytes, context.limits.minStorageBufferOffsetAlignment});
const auto stride = context.limits.maxStorageBufferRange / alignment * alignment;
if (guestSamples) {
Require(context.detiler != nullptr && context.storageImageMultisample && context.storageImageWriteWithoutFormat, "uploading multisampled guest color requires formatless multisampled storage image writes");
Require(stride != 0, "uploading multisampled guest color needs a storage range of at least one aligned element");
flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT | VK_IMAGE_CREATE_EXTENDED_USAGE_BIT;
Require(storageSupports(elementFormat, VK_IMAGE_USAGE_STORAGE_BIT, 0u) && storageSupports(target.format, usage | VK_IMAGE_USAGE_STORAGE_BIT, flags), "the device cannot upload multisampled guest color through an unsigned storage view");
usage |= VK_IMAGE_USAGE_STORAGE_BIT;
upload = guestSampleUpload(target);
}
twinFormat = colorTwinFormat(context, target.format);
if (twinFormat != VK_FORMAT_UNDEFINED) {
VkFormatProperties twinProperties{};
context.formatProperties(context.physical, twinFormat, &twinProperties);
const VkImageCreateFlags twinFlags = flags | VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT;
if ((twinProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) == 0 || !storageSupports(target.format, usage, twinFlags) || !storageSupports(twinFormat, twinViewUsage, twinFlags)) twinFormat = VK_FORMAT_UNDEFINED;
}
try {
const auto created = allocate(usage, flags);
image = created.image;
memory = created.memory;
view = created.view;
allocationBytes = created.bytes;
if (upload) {
VkImageViewUsageCreateInfo storageUsage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO};
storageUsage.usage = VK_IMAGE_USAGE_STORAGE_BIT;
VkImageViewCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
info.pNext = &storageUsage;
info.image = image;
info.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY;
info.format = elementFormat;
info.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
Check(context.Function<PFN_vkCreateImageView>("vkCreateImageView")(context.device, &info, nullptr, &uploadView), "vkCreateImageView multisampled guest color upload");
}
recordCommands(context, [&](VkCommandBuffer commands, Recorder* recorder) {
if (!upload) {
recordToGeneral(commands, image);
const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
context.Resolved(&DeviceFunctions::cmdClearColorImage, "vkCmdClearColorImage")(commands, image, VK_IMAGE_LAYOUT_GENERAL, &initial, 1, &range);
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT);
if (recorder != nullptr) Recorder::CountBarriers(Recorder::CommandClass::Draw, 2);
return;
}
recordToGeneral(commands, image, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT);
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT);
const auto bytes = static_cast<std::uint64_t>(target.extent.width) * target.extent.height * target.samples * target.elementBytes;
for (std::uint64_t offset = 0; offset < bytes; offset += stride) {
const auto count = std::min<std::uint64_t>(stride, bytes - offset);
context.detiler->DispatchMultisampleImage(commands, target.elementBytes, upload->Handle(), offset, (count + 3u) & ~std::uint64_t{3}, uploadView, target.extent.width, target.extent.height, 1u, target.samples, static_cast<std::uint32_t>(offset / target.elementBytes), static_cast<std::uint32_t>(count / target.elementBytes));
}
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT);
if (recorder != nullptr) {
recorder->Keep(upload, upload->Bytes().size());
Recorder::CountBarriers(Recorder::CommandClass::Draw, 3);
}
});
} catch (...) {
release();
throw;
}
}
~MultisampleTarget() { release(); }
MultisampleTarget(const MultisampleTarget&) = delete;
MultisampleTarget& operator=(const MultisampleTarget&) = delete;
struct Allocation {
VkImage image = VK_NULL_HANDLE;
VkDeviceMemory memory = VK_NULL_HANDLE;
VkImageView view = VK_NULL_HANDLE;
VkDeviceSize bytes = 0;
};
Allocation allocate(VkImageUsageFlags imageUsage, VkImageCreateFlags flags) {
Allocation created;
try {
VkImageCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
info.flags = flags;
const std::array<VkFormat, 2> viewFormats{target.format, twinFormat};
VkImageFormatListCreateInfo formatList{VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO};
if (twinFormat != VK_FORMAT_UNDEFINED) {
if ((flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT) == 0 && context.imageFormatList) {
formatList.viewFormatCount = static_cast<std::uint32_t>(viewFormats.size());
formatList.pViewFormats = viewFormats.data();
info.pNext = &formatList;
}
info.flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT;
}
info.imageType = VK_IMAGE_TYPE_2D;
info.format = target.format;
info.extent = {target.extent.width, target.extent.height, 1};
info.mipLevels = 1;
info.arrayLayers = 1;
info.samples = static_cast<VkSampleCountFlagBits>(target.samples);
info.tiling = VK_IMAGE_TILING_OPTIMAL;
info.usage = imageUsage;
info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
Check(context.Function<PFN_vkCreateImage>("vkCreateImage")(context.device, &info, nullptr, &created.image), "vkCreateImage multisampled target");
VkMemoryRequirements requirements{};
context.Function<PFN_vkGetImageMemoryRequirements>("vkGetImageMemoryRequirements")(context.device, created.image, &requirements);
VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
allocation.allocationSize = requirements.size;
created.bytes = requirements.size;
allocation.memoryTypeIndex = context.MemoryType(requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
created.memory = AllocateImageMemory(context, allocation, requirements.memoryTypeBits, "vkAllocateMemory multisampled target");
Check(context.Function<PFN_vkBindImageMemory>("vkBindImageMemory")(context.device, created.image, created.memory, 0), "vkBindImageMemory multisampled target");
VkImageViewCreateInfo viewInfo{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
viewInfo.image = created.image;
viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
viewInfo.format = target.format;
viewInfo.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
VkImageViewUsageCreateInfo viewUsage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO};
viewUsage.usage = imageUsage & ~VK_IMAGE_USAGE_STORAGE_BIT;
if ((imageUsage & VK_IMAGE_USAGE_STORAGE_BIT) != 0) viewInfo.pNext = &viewUsage;
Check(context.Function<PFN_vkCreateImageView>("vkCreateImageView")(context.device, &viewInfo, nullptr, &created.view), "vkCreateImageView multisampled target");
} catch (...) {
destroy(created);
throw;
}
return created;
}
void destroy(const Allocation& allocation) noexcept {
if (allocation.view) context.Function<PFN_vkDestroyImageView>("vkDestroyImageView")(context.device, allocation.view, nullptr);
if (allocation.image) context.Function<PFN_vkDestroyImage>("vkDestroyImage")(context.device, allocation.image, nullptr);
if (allocation.memory) MemoryAccounting::Free(context, allocation.memory);
}
void recordToGeneral(VkCommandBuffer commands, VkImage destination, VkPipelineStageFlags destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT, VkAccessFlags destinationAccess = VK_ACCESS_TRANSFER_WRITE_BIT) {
VkImageMemoryBarrier toGeneral{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
toGeneral.dstAccessMask = destinationAccess;
toGeneral.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
toGeneral.newLayout = VK_IMAGE_LAYOUT_GENERAL;
toGeneral.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
toGeneral.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
toGeneral.image = destination;
toGeneral.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
context.Resolved(&DeviceFunctions::cmdPipelineBarrier, "vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, destinationStage, 0, 0, nullptr, 0, nullptr, 1, &toGeneral);
}
void makeStorable(Recorder& recorder) {
if ((usage & VK_IMAGE_USAGE_STORAGE_BIT) != 0) return;
const auto storable = allocate(usage | VK_IMAGE_USAGE_STORAGE_BIT, storageFlags);
const auto source = image;
recordToGeneral(recorder.Commands(), storable.image);
RecordMemoryBarrier(context, recorder.Commands(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT);
VkImageCopy region{};
region.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
region.dstSubresource = region.srcSubresource;
region.extent = {target.extent.width, target.extent.height, 1};
context.Function<PFN_vkCmdCopyImage>("vkCmdCopyImage")(recorder.Commands(), source, VK_IMAGE_LAYOUT_GENERAL, storable.image, VK_IMAGE_LAYOUT_GENERAL, 1, ®ion);
RecordMemoryBarrier(context, recorder.Commands(), VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT);
Recorder::CountBarriers(Recorder::CommandClass::Draw, 3);
for (auto& [key, texture] : textures) retiredTextures.push_back(std::move(texture));
textures.clear();
retired.push_back({VK_NULL_HANDLE, VK_NULL_HANDLE, std::exchange(twinView, VK_NULL_HANDLE)});
retired.push_back({image, memory, view});
image = storable.image;
memory = storable.memory;
view = storable.view;
usage |= VK_IMAGE_USAGE_STORAGE_BIT;
allocationBytes += storable.bytes;
recorder.Keep(shared_from_this(), static_cast<std::size_t>(storable.bytes));
}
std::shared_ptr<Texture> FmaskSampled(const GuestTextureResource& resource, VkComponentMapping components) {
const auto snapshot = fmaskSnapshotResource(resource);
Require(target.samples == 8u && target.dccAddress != 0u && fmaskRange.has_value(), "native FMASK sampling requires a tracked eight-fragment DCC target");
Require(target.tileMode == ColorTileMode::RenderTarget && target.depth == 1u && target.depthSlice == 0u && target.layers == 1u && target.arrayLastSlice == 0u && target.arraySlice == 0u && target.mip == 0u && target.mipCount == 1u, "native FMASK target layout is not implemented");
Require(target.fmaskAddress == resource.baseAddress && target.fmaskPipeBankXor == resource.pipeBankXor && target.cmaskAddress == resource.fmaskCmaskAddress, "native FMASK descriptor does not match its resident target");
Require(target.extent.width == resource.width && target.extent.height == resource.height && resource.baseArray == 0u && resource.depthOrLastArray == 0u, "native FMASK extent or subresource does not match its resident target");
auto* recorder = Recorder::Active();
Require(recorder != nullptr && recorder->Device() == context.device && !Recorder::InCompletion(), "native FMASK sampling requires its device's active recorder outside completion");
ApplyFastClear(target);
Keep();
const std::array<std::uint32_t, 5> key{static_cast<std::uint32_t>(components.r), static_cast<std::uint32_t>(components.g), static_cast<std::uint32_t>(components.b), static_cast<std::uint32_t>(components.a), static_cast<std::uint32_t>(resource.dimension)};
auto& texture = fmaskTextures[key];
if (texture == nullptr) {
const auto geometry = DescribeSurface(snapshot);
std::vector<std::byte> bytes(geometry.guestBytes);
constexpr std::uint32_t expanded = 0x76543210u;
for (std::size_t offset = 0; offset < bytes.size(); offset += sizeof(expanded)) std::memcpy(bytes.data() + offset, &expanded, sizeof(expanded));
texture = std::make_unique<Texture>(context, *context.detiler, snapshot, components, bytes);
}
return {shared_from_this(), texture.get()};
}
void Keep() {
if (auto* recorder = Recorder::Active(); recorder != nullptr && recorder->Device() == context.device) {
recorder->Keep(shared_from_this());
recorder->KeepBytes(this, allocationBytes);
}
}
void ApplyFastClear(const ColorTarget& use) {
VkClearColorValue clear{};
const bool refilled = absorbDccFill(use, clear);
checkDccCurrent(use, refilled);
if (!refilled && !TakeMultisampledClear(cmask, colorFill, use, clear)) return;
Keep();
recordCommands(context, [&](VkCommandBuffer commands, Recorder* recorder) {
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT);
const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
context.Resolved(&DeviceFunctions::cmdClearColorImage, "vkCmdClearColorImage")(commands, image, VK_IMAGE_LAYOUT_GENERAL, &clear, 1, &range);
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT);
if (recorder != nullptr) Recorder::CountBarriers(Recorder::CommandClass::Draw, 2);
});
cleared = clear;
drawn = false;
++contents;
}
void Recreate(const ColorTarget& use) {
SettleStorageWrites();
target = use;
cmask = MultisampledCmask(use.cmaskAddress, use.cmaskBytes);
colorFill = MultisampledColorFill(use);
fromTexture = false;
dccRanges.clear();
dccCopies.clear();
fmaskRange.reset();
fmaskCopy = {};
metadataValid = std::make_shared<std::atomic<bool>>(true);
const auto initial = initialDccClear(use);
cleared = initial;
drawn = false;
++contents;
recordCommands(context, [&](VkCommandBuffer commands, Recorder* recorder) {
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT);
const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
context.Resolved(&DeviceFunctions::cmdClearColorImage, "vkCmdClearColorImage")(commands, image, VK_IMAGE_LAYOUT_GENERAL, &initial, 1, &range);
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT);
if (recorder != nullptr) Recorder::CountBarriers(Recorder::CommandClass::Draw, 2);
});
}
void SettleStorageWrites() {
if (!storageWritten) return;
storageWritten = false;
recordCommands(context, [&](VkCommandBuffer commands, Recorder* recorder) {
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT);
if (recorder != nullptr) Recorder::CountBarriers(Recorder::CommandClass::Draw, 1);
});
}
VkImageView Storage(VkFormat format, bool uintStorage) {
Require(storageFormat != VK_FORMAT_UNDEFINED, "the device cannot write the multisampled color target's format as a storage image at its sample count");
Require(format == storageFormat, "a storage image access to a multisampled color target in another format than the target's storage form is not implemented");
Require(cmask.Refusal().empty(), cmask.Refusal());
Require(htileRefusal.empty(), htileRefusal);
Require(cmask.Keys() != DccKeys::Clear0000, "a storage image access to a multisampled color target whose CMASK fast clear no draw has applied is not implemented");
auto* recording = Recorder::Active();
Require(recording != nullptr && recording->Device() == context.device, "a multisampled color target is only written by recorded dispatches on its device");
Keep();
makeStorable(*recording);
ApplyFastClear(target);
const auto uintFormat = uintStorage ? uintStorageViewFormat(storageFormat) : VK_FORMAT_UNDEFINED;
const bool useUintStorage = uintStorage && uintFormat != VK_FORMAT_UNDEFINED;
auto& selectedView = useUintStorage ? uintStorageView : storageView;
if (selectedView == VK_NULL_HANDLE) {
VkImageViewCreateInfo viewInfo{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
viewInfo.image = image;
viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
viewInfo.format = useUintStorage ? uintFormat : storageFormat;
viewInfo.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
VkImageViewUsageCreateInfo viewUsage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO};
if (useUintStorage) {
viewUsage.usage = VK_IMAGE_USAGE_STORAGE_BIT;
viewInfo.pNext = &viewUsage;
}
Check(context.Function<PFN_vkCreateImageView>("vkCreateImageView")(context.device, &viewInfo, nullptr, &selectedView), "vkCreateImageView multisampled target storage");
}
recordCommands(context, [&](VkCommandBuffer commands, Recorder* recorder) {
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT);
if (recorder != nullptr) Recorder::CountBarriers(Recorder::CommandClass::Draw, 1);
});
storageWritten = true;
drawn = true;
++contents;
return selectedView;
}
bool Storable() const {
return (usage & VK_IMAGE_USAGE_STORAGE_BIT) != 0;
}
VkImageView OrderView() {
Require(orderFormat != VK_FORMAT_UNDEFINED, "the multisampled color target has no storage view to put its samples in the guest's order");
if (orderView != VK_NULL_HANDLE) return orderView;
VkImageViewCreateInfo viewInfo{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
viewInfo.image = image;
viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
viewInfo.format = orderFormat;
viewInfo.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
VkImageViewUsageCreateInfo viewUsage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO};
viewUsage.usage = VK_IMAGE_USAGE_STORAGE_BIT;
viewInfo.pNext = &viewUsage;
Check(context.Function<PFN_vkCreateImageView>("vkCreateImageView")(context.device, &viewInfo, nullptr, &orderView), "vkCreateImageView multisampled target storage");
return orderView;
}
void NoteMetadataFill(std::uint64_t fillAddress, std::size_t fillBytes, std::uint32_t pattern) {
const auto note = [&](std::uint64_t address, std::uint64_t bytes, std::optional<std::uint32_t>& filled) {
if (address == 0 || fillAddress >= address + bytes || address >= fillAddress + fillBytes) return;
filled = fillAddress <= address && fillAddress + fillBytes >= address + bytes ? std::optional<std::uint32_t>(pattern) : std::nullopt;
};
note(target.dccAddress, MultisampledDccBytes(target), dccFill);
note(target.cmaskAddress, target.cmaskBytes, cmaskFill);
}
std::shared_ptr<Texture> Sampled(VkComponentMapping components, VkImageViewType viewType = VK_IMAGE_VIEW_TYPE_2D) {
Require(sampleable, "the device cannot sample the multisampled color target's format at its sample count");
Require(cmask.Refusal().empty(), cmask.Refusal());
Require(htileRefusal.empty(), htileRefusal);
Require(cmask.Keys() != DccKeys::Clear0000, "sampling a multisampled color target whose CMASK fast clear no draw has applied is not implemented");
auto* recording = Recorder::Active();
Require(recording != nullptr && recording->Device() == context.device, "a multisampled color target is only sampled by recorded draws and dispatches on its device");
Keep();
SettleStorageWrites();
ApplyFastClear(target);
recordCommands(context, [&](VkCommandBuffer commands, Recorder*) {
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT);
Recorder::CountBarriers(Recorder::CommandClass::Draw, 1);
});
const std::array<std::uint32_t, 5> key{static_cast<std::uint32_t>(components.r), static_cast<std::uint32_t>(components.g), static_cast<std::uint32_t>(components.b), static_cast<std::uint32_t>(components.a), static_cast<std::uint32_t>(viewType)};
auto& texture = textures[key];
if (texture == nullptr) texture = std::make_shared<Texture>(context, image, target.format, VK_IMAGE_ASPECT_COLOR_BIT, components, viewType, 0, std::shared_ptr<OwnedImage>{}, orderFormat != VK_FORMAT_UNDEFINED ? VK_IMAGE_USAGE_SAMPLED_BIT : VkImageUsageFlags{0});
return {shared_from_this(), texture.get()};
}
std::shared_ptr<Texture> FirstSample(VkComponentMapping components) {
const auto source = Sampled({});
if (firstSampleCopy == nullptr) firstSampleCopy = std::make_unique<FirstSampleCopy>(context, target.format, target.extent);
firstSampleCopy->Record(*Recorder::Active(), source->View(), source->Layout());
const std::array<std::uint32_t, 4> key{static_cast<std::uint32_t>(components.r), static_cast<std::uint32_t>(components.g), static_cast<std::uint32_t>(components.b), static_cast<std::uint32_t>(components.a)};
auto& texture = firstSampleTextures[key];
if (texture == nullptr) {
texture = std::make_shared<Texture>(context, firstSampleCopy->Image(), target.format, VK_IMAGE_ASPECT_COLOR_BIT, components);
texture->MarkRefreshedPerUse();
}
return {shared_from_this(), texture.get()};
}
VkImageView View(VkFormat format) {
if (format == target.format) return view;
Require(twinFormat != VK_FORMAT_UNDEFINED && format == twinFormat, "a multisampled color target is only viewed in its own format or its sRGB twin");
if (twinView == VK_NULL_HANDLE) {
VkImageViewCreateInfo viewInfo{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
viewInfo.image = image;
viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
viewInfo.format = twinFormat;
viewInfo.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
VkImageViewUsageCreateInfo viewUsage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO};
viewUsage.usage = twinViewUsage;
viewInfo.pNext = &viewUsage;
Check(context.Function<PFN_vkCreateImageView>("vkCreateImageView")(context.device, &viewInfo, nullptr, &twinView), "vkCreateImageView multisampled target twin");
}
return twinView;
}
bool Serves(const ColorTarget& use) const {
if (use.format == target.format) return sameTarget(target, use);
auto twin = use;
twin.format = target.format;
return twinFormat != VK_FORMAT_UNDEFINED && use.format == twinFormat && sameTarget(target, twin);
}
VkRenderPass ResolvePass(VkFormat format) {
auto& resolvePass = resolvePasses[format];
if (resolvePass != VK_NULL_HANDLE) return resolvePass;
std::array<VkAttachmentDescription, 2> attachments{};
attachments[0].format = format;
attachments[0].samples = static_cast<VkSampleCountFlagBits>(target.samples);
attachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
attachments[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachments[1].format = format;
attachments[1].samples = VK_SAMPLE_COUNT_1_BIT;
attachments[1].loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachments[1].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
for (auto& attachment : attachments) {
attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachment.initialLayout = VK_IMAGE_LAYOUT_GENERAL;
attachment.finalLayout = VK_IMAGE_LAYOUT_GENERAL;
}
const VkAttachmentReference color{0, VK_IMAGE_LAYOUT_GENERAL};
const VkAttachmentReference resolve{1, VK_IMAGE_LAYOUT_GENERAL};
VkSubpassDescription subpass{};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &color;
subpass.pResolveAttachments = &resolve;
VkRenderPassCreateInfo info{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO};
info.attachmentCount = static_cast<std::uint32_t>(attachments.size());
info.pAttachments = attachments.data();
info.subpassCount = 1;
info.pSubpasses = &subpass;
Check(context.Function<PFN_vkCreateRenderPass>("vkCreateRenderPass")(context.device, &info, nullptr, &resolvePass), "vkCreateRenderPass resolve");
return resolvePass;
}
Context context;
std::shared_ptr<std::atomic<bool>> active = std::make_shared<std::atomic<bool>>(true);
std::shared_ptr<TargetUse> use = std::make_shared<TargetUse>();
std::shared_ptr<std::atomic<bool>> metadataValid;
ColorTarget target;
VkImage image = VK_NULL_HANDLE;
VkDeviceMemory memory = VK_NULL_HANDLE;
VkImageView view = VK_NULL_HANDLE;
std::map<VkFormat, VkRenderPass> resolvePasses;
MultisampledCmask cmask;
MultisampledColorFill colorFill;
bool fromTexture = false;
VkFormat orderFormat = VK_FORMAT_UNDEFINED;
VkImageView orderView = VK_NULL_HANDLE;
std::uint64_t htileAddress = 0;
std::uint64_t htileBytes = 0;
std::string htileRefusal;
std::optional<VkClearColorValue> cleared;
bool drawn = false;
std::uint64_t contents = 0;
MultisampleColorAlias Alias() const {
MultisampleColorAlias alias{target.address, guardedColorBytes(target), target.format, target.samples};
alias.active = active;
alias.contents = contents;
alias.fills = colorFill.Noted();
alias.sameRun = colorFill.SameRun();
const auto newest = [&](MultisampleColorContent content, std::optional<VkClearColorValue> value) {
alias.newest = content;
alias.value = value;
alias.byte = value ? texelByte(target.format, *value) : std::nullopt;
return alias;
};
if (!cmask.Refusal().empty() || !colorFill.Refusal().empty() || !htileRefusal.empty() || dccFill || cmaskFill) return newest(MultisampleColorContent::Unknown, std::nullopt);
if (cmask.Keys() == DccKeys::Clear0000) {
try {
return newest(MultisampleColorContent::FastClear, fastClearColor(target));
} catch (const std::exception&) {
return newest(MultisampleColorContent::Unknown, std::nullopt);
}
}
if (const auto fill = colorFill.Pending()) {
VkClearColorValue clear{};
alias.filledBytes = MultisampledColorBytes(target);
return MultisampledFillClearColor(target, *fill, clear) ? newest(MultisampleColorContent::Fill, clear) : newest(MultisampleColorContent::Unknown, std::nullopt);
}
if (drawn) return newest(MultisampleColorContent::Drawn, std::nullopt);
return newest(cleared ? MultisampleColorContent::Clear : MultisampleColorContent::Unknown, cleared);
}
private:
bool sampleable = false;
VkImageUsageFlags usage = 0;
VkFormat storageFormat = VK_FORMAT_UNDEFINED;
VkImageCreateFlags storageFlags = 0;
VkFormat twinFormat = VK_FORMAT_UNDEFINED;
VkImageView twinView = VK_NULL_HANDLE;
std::vector<Allocation> retired;
VkImageView storageView = VK_NULL_HANDLE;
VkImageView uintStorageView = VK_NULL_HANDLE;
bool storageWritten = false;
VkDeviceSize allocationBytes = 0;
std::optional<GuestMemory::UnchangedQuery> fmaskRange;
std::map<std::array<std::uint32_t, 5>, std::unique_ptr<Texture>> fmaskTextures;
std::map<std::array<std::uint32_t, 5>, std::shared_ptr<Texture>> textures;
std::vector<std::shared_ptr<Texture>> retiredTextures;
std::unique_ptr<FirstSampleCopy> firstSampleCopy;
std::map<std::array<std::uint32_t, 4>, std::shared_ptr<Texture>> firstSampleTextures;
std::vector<GuestMemory::UnchangedQuery> dccRanges;
struct DccCopy {
bool compared = false;
std::vector<std::byte> bytes;
std::uint64_t stamp = 0;
std::array<std::uint64_t, 2> checked{};
};
mutable std::vector<DccCopy> dccCopies;
mutable DccCopy fmaskCopy;
std::optional<std::uint32_t> dccFill;
std::optional<std::uint32_t> cmaskFill;
bool compared(std::size_t index) const {
return index < dccCopies.size() && dccCopies[index].compared;
}
static DccCopy comparedCopy(const GuestMemory::UnchangedQuery& range, std::vector<std::byte> bytes) {
return {true, std::move(bytes), GuestMemory::NewestStamp(range.address, range.bytes), {}};
}
static bool copyCurrent(const GuestMemory::UnchangedQuery& range, DccCopy& copy) {
if (GuestMemory::NewestStamp(range.address, range.bytes) != copy.stamp) return false;
const auto epoch = GuestMemory::CollectEpoch();
const std::array<std::uint64_t, 2> seen{epoch, GuestMemory::ForgetSerial()};
if (epoch != 0 && (seen[1] & 1u) == 0 && copy.checked == seen) return true;
if (!GuestMemory::EqualsCommittedUnsynced(range.address, copy.bytes)) return false;
copy.checked = seen;
return true;
}
bool absorbDccFill(const ColorTarget& use, VkClearColorValue& clear) {
const auto dcc = std::exchange(dccFill, std::nullopt);
const auto cmaskPattern = std::exchange(cmaskFill, std::nullopt);
if (dccRanges.size() < 2 || !dcc || use.dccAddress != target.dccAddress || use.cmaskAddress != target.cmaskAddress || use.cmaskBytes != target.cmaskBytes) return false;
const auto keys = LandedUniformMetadataByte(dccRanges[1].address, dccRanges[1].bytes);
if (!keys || *dcc != *keys * 0x01010101u) return false;
std::uint8_t cmaskKeys = 0;
if (dccRanges.size() > 2) {
const auto& range = dccRanges[2];
auto* recorder = Recorder::Active();
const bool unchanged = compared(2) ? copyCurrent(range, dccCopies[2]) : GuestMemory::UnchangedSince(range.address, range.bytes, range.generation);
const bool written = !unchanged || (recorder != nullptr && recorder->PendingWriteOverlaps(range.address, range.bytes));
const auto landed = LandedUniformMetadataByte(range.address, range.bytes);
if (!landed || (written && (!cmaskPattern || *cmaskPattern != *landed * 0x01010101u))) return false;
cmaskKeys = *landed;
}
std::vector<GuestMemory::UnchangedQuery> metadata(dccRanges.begin() + 1, dccRanges.end());
std::vector<bool> comparedMetadata(metadata.size(), false);
for (std::size_t index = 0; index < metadata.size(); ++index) {
auto& range = metadata[index];
if (!GuestMemory::Watched(range.address, range.bytes)) {
if (!compared(index + 1) && !ComparedHostImportCovers(context, range.address, range.bytes)) return false;
comparedMetadata[index] = true;
range.generation = 0;
continue;
}
range.generation = collectBlocks(range.address, range.bytes);
if (range.generation == 0) return false;
}
std::array<std::vector<std::byte>, 2> landedBytes{std::vector<std::byte>(dccRanges[1].bytes, std::byte{*keys}), std::vector<std::byte>(use.cmaskBytes, std::byte{cmaskKeys})};
clear = MultisampledDccClear(use, landedBytes[0], landedBytes[1]);
std::copy(metadata.begin(), metadata.end(), dccRanges.begin() + 1);
dccCopies.resize(dccRanges.size());
for (std::size_t index = 0; index < metadata.size(); ++index) dccCopies[index + 1] = comparedMetadata[index] ? comparedCopy(dccRanges[index + 1], std::move(landedBytes[index])) : DccCopy{};
return true;
}
VkImageView uploadView = VK_NULL_HANDLE;
std::shared_ptr<Buffer> guestSampleUpload(const ColorTarget& use) {
Require(use.cmaskAddress == 0 && use.dccAddress == 0, "uploading multisampled guest color under compression metadata is not implemented");
Require(use.layers == 1u && use.arraySlice == 0u && use.arrayLastSlice == 0u && use.depth == 1u && use.depthSlice == 0u && use.mipCount == 1u && use.mip == 0u && !use.mipTail, "uploading multisampled guest color of arrays, volumes or mips is not implemented");
Require(use.tileMode == ColorTileMode::RenderTarget || use.tileMode == ColorTileMode::Z64KBX, "non-uniform multisampled guest color tiling is not implemented");
const MultisampleTextureLayout layout(use.tileMode == ColorTileMode::Z64KBX ? TextureTileMode::kZ64KBX : TextureTileMode::kR64KBX, use.elementBytes, use.samples, use.extent.width, use.extent.height, 1u, use.pipeBankXor);
Require(layout.Bytes() == MultisampledColorBytes(use) && layout.Bytes() <= std::numeric_limits<std::size_t>::max(), "the multisampled guest color layout and footprint differ");
Require(layout.LinearBytes() / use.elementBytes <= std::numeric_limits<std::uint32_t>::max(), "the multisampled guest color element count is unsupported");
std::vector<std::byte> guest(static_cast<std::size_t>(layout.Bytes()));
GuestMemory::Read(use.address, guest);
auto staging = std::make_shared<Buffer>(context, static_cast<std::size_t>((layout.LinearBytes() + 3u) & ~std::uint64_t{3}), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
layout.Detile(guest, staging->Bytes().first(static_cast<std::size_t>(layout.LinearBytes())));
return staging;
}
VkClearColorValue initialDccClear(const ColorTarget& use) {
if (use.dccAddress == 0) return {};
const auto dccBytes = MultisampledDccBytes(use);
Require((use.dccAddress & 4095u) == 0, "multisampled DCC metadata base alignment is not implemented");
Require(use.cmaskAddress == 0 ? use.cmaskBytes == 0 : use.cmaskBytes == CmaskBytes(use.extent.width, use.extent.height), "multisampled DCC CMASK footprint is invalid");
const auto colorBytes = MultisampledColorBytes(use);
Require(colorBytes != 0, "multisampled DCC color footprint is not implemented");
dccRanges.push_back({use.address, static_cast<std::size_t>(colorBytes), 0});
dccRanges.push_back({use.dccAddress, dccBytes, 0});
if (use.cmaskAddress != 0) dccRanges.push_back({use.cmaskAddress, use.cmaskBytes, 0});
dccCopies.assign(dccRanges.size(), {});
std::vector<GuestMemory::UnchangedQuery> watched;
for (std::size_t index = 0; index < dccRanges.size(); ++index) {
auto& range = dccRanges[index];
GuestMemory::CheckRange(reinterpret_cast<const void*>(range.address), range.bytes, 256);
if (!WatchedAfterSettle(context, range.address, range.bytes) && ComparedHostImportCovers(context, range.address, range.bytes)) {
dccCopies[index].compared = true;
continue;
}
Require(GuestMemory::Watched(range.address, range.bytes), "initial multisampled DCC contents require watched guest memory");
range.generation = collectBlocks(range.address, range.bytes);
Require(range.generation != 0, "initial multisampled DCC contents have no write generation");
watched.push_back(range);
}
for (std::size_t first = 0; first < dccRanges.size(); ++first) {
for (std::size_t second = first + 1; second < dccRanges.size(); ++second) {
const auto& a = dccRanges[first];
const auto& b = dccRanges[second];
Require(a.address >= b.address + b.bytes || b.address >= a.address + a.bytes, "overlapping multisampled DCC color or metadata ranges are not implemented");
}
}
if (use.samples == 8u && use.fmaskAddress != 0u && use.cmaskAddress != 0u) {
const auto resource = fmaskResource(use);
static_cast<void>(fmaskSnapshotResource(resource));
fmaskRange = GuestMemory::UnchangedQuery{use.fmaskAddress, static_cast<std::size_t>(DescribeSurface(resource).guestBytes), 0};
auto& range = *fmaskRange;
GuestMemory::CheckRange(reinterpret_cast<const void*>(range.address), range.bytes, 65536u);
fmaskCopy.compared = !WatchedAfterSettle(context, range.address, range.bytes) && ComparedHostImportCovers(context, range.address, range.bytes);
Require(fmaskCopy.compared || GuestMemory::Watched(range.address, range.bytes), "native FMASK contents require watched guest memory");
if (!fmaskCopy.compared) {
range.generation = GuestMemory::CollectWritesUncached(range.address, range.bytes);
Require(range.generation != 0, "native FMASK contents have no write generation");
}
for (const auto& other : dccRanges) Require(range.address >= other.address + other.bytes || other.address >= range.address + range.bytes, "native FMASK overlaps its color or metadata planes");
}
std::array<std::vector<std::byte>, 3> bytes{};
for (std::size_t index = 0; index < dccRanges.size(); ++index) {
if (index == 0 && !compared(0)) continue;
bytes[index].resize(dccRanges[index].bytes);
GuestMemory::Read(dccRanges[index].address, bytes[index]);
}
std::vector<std::byte> fmaskBytes(fmaskCopy.compared ? fmaskRange->bytes : 0u);
if (fmaskCopy.compared) GuestMemory::Read(fmaskRange->address, fmaskBytes);
const auto clear = MultisampledDccClear(use, bytes[1], bytes[2]);
Require((watched.empty() || GuestMemory::UnchangedSinceAll(watched)) && (!fmaskRange || fmaskCopy.compared || GuestMemory::UnchangedSinceAll(std::span(&*fmaskRange, 1u))), "initial multisampled DCC contents changed during import");
for (std::size_t index = 0; index < dccRanges.size(); ++index) {
if (compared(index)) dccCopies[index] = comparedCopy(dccRanges[index], std::move(bytes[index]));
}
if (fmaskCopy.compared) fmaskCopy = comparedCopy(*fmaskRange, std::move(fmaskBytes));
return clear;
}
void requireDccRange(bool valid, const GuestMemory::UnchangedQuery& range, const char* reason) const {
if (valid) return;
const auto* plane = range.address == target.address ? "color" : range.address == target.dccAddress ? "DCC" : range.address == target.fmaskAddress ? "FMASK" : "CMASK";
char text[384];
std::snprintf(text, sizeof(text), "%s (%s range 0x%llx+0x%zx, %u samples)", reason, plane, static_cast<unsigned long long>(range.address), range.bytes, target.samples);
Require(false, text);
}
void checkDccCurrent(const ColorTarget& use, bool metadataRefilled) const {
if (dccRanges.empty()) {
Require(use.dccAddress == 0, "adding DCC to a resident multisampled color target is not implemented");
return;
}
Require(metadataValid->load(std::memory_order_acquire), "multisampled DCC metadata was released while its color target remains resident");
static_cast<void>(MultisampledDccBytes(use));
Require(use.address == target.address && use.dccAddress == target.dccAddress && use.dccControl == target.dccControl && use.dccAlphaOnMsb == target.dccAlphaOnMsb && use.dccPipeAligned == target.dccPipeAligned && use.cmaskAddress == target.cmaskAddress && use.cmaskBytes == target.cmaskBytes && use.tileMode == target.tileMode && use.elementBytes == target.elementBytes && use.pipeBankXor == target.pipeBankXor, "multisampled DCC target layout or metadata changed");
const auto ranges = metadataRefilled ? std::size_t{1} : dccRanges.size();
for (std::size_t index = 0; index < ranges; ++index) requireDccRange(compared(index) || GuestMemory::Watched(dccRanges[index].address, dccRanges[index].bytes), dccRanges[index], "multisampled DCC target reuse requires watched guest memory");
for (std::size_t index = 0; index < ranges; ++index) {
const auto& range = dccRanges[index];
if (compared(index)) {
requireDccRange(copyCurrent(range, dccCopies[index]), range, "writes to a resident multisampled DCC target or its metadata are not implemented");
} else {
GuestMemory::CollectWritesUncached(range.address, range.bytes);
requireDccRange(GuestMemory::UnchangedSince(range.address, range.bytes, range.generation) || !GuestMemory::StoredOver(range.address, range.bytes, range.generation), range, "writes to a resident multisampled DCC target or its metadata are not implemented");
}
if (auto* recorder = Recorder::Active(); recorder != nullptr) requireDccRange(!recorder->PendingWriteOverlaps(range.address, range.bytes), range, "pending writes to a resident multisampled DCC target or its metadata are not implemented");
}
if (fmaskRange) {
Require(use.fmaskAddress == target.fmaskAddress && use.fmaskPipeBankXor == target.fmaskPipeBankXor, "native FMASK target layout changed");
const auto& range = *fmaskRange;
requireDccRange(fmaskCopy.compared || WatchedAfterSettle(context, range.address, range.bytes), range, "native FMASK sampling requires watched guest memory");
if (fmaskCopy.compared) {
requireDccRange(copyCurrent(range, fmaskCopy), range, "writes to a resident native FMASK are not implemented");
} else {
GuestMemory::CollectWritesUncached(range.address, range.bytes);
requireDccRange(GuestMemory::UnchangedSince(range.address, range.bytes, range.generation) || !GuestMemory::StoredOver(range.address, range.bytes, range.generation), range, "writes to a resident native FMASK are not implemented");
}
if (auto* recorder = Recorder::Active(); recorder != nullptr) requireDccRange(!recorder->PendingWriteOverlaps(range.address, range.bytes), range, "pending writes to a resident native FMASK are not implemented");
}
}
void release() noexcept {
fmaskTextures.clear();
textures.clear();
retiredTextures.clear();
firstSampleTextures.clear();
firstSampleCopy.reset();
for (const auto& [format, resolvePass] : resolvePasses) context.Function<PFN_vkDestroyRenderPass>("vkDestroyRenderPass")(context.device, resolvePass, nullptr);
if (uploadView) context.Function<PFN_vkDestroyImageView>("vkDestroyImageView")(context.device, uploadView, nullptr);
if (orderView) context.Function<PFN_vkDestroyImageView>("vkDestroyImageView")(context.device, orderView, nullptr);
if (twinView) context.Function<PFN_vkDestroyImageView>("vkDestroyImageView")(context.device, twinView, nullptr);
if (storageView) context.Function<PFN_vkDestroyImageView>("vkDestroyImageView")(context.device, storageView, nullptr);
if (uintStorageView) context.Function<PFN_vkDestroyImageView>("vkDestroyImageView")(context.device, uintStorageView, nullptr);
destroy({image, memory, view});
for (const auto& allocation : retired) destroy(allocation);
}
};
struct GuardedRange {
VkDevice device;
std::uint64_t address;
std::uint64_t bytes;
std::uint32_t samples;
std::shared_ptr<std::atomic<bool>> active;
std::shared_ptr<std::atomic<bool>> metadataValid;
std::shared_ptr<TargetUse> use;
bool fmask = false;
const char* plane = "multisampled color target";
};
std::shared_mutex& guardedMutex() {
static PrimedSharedMutex mutex;
return mutex;
}
std::vector<GuardedRange>& guarded() {
static std::vector<GuardedRange> ranges;
return ranges;
}
std::atomic<bool>& anyGuarded() {
static std::atomic<bool> any{false};
return any;
}
std::atomic<std::uint64_t>& guardedGeneration() {
static std::atomic<std::uint64_t> generation{0};
return generation;
}
void guardReads(std::uint64_t address, std::size_t bytes) {
RequireNoMultisampleTarget(address, bytes, "a CPU read");
}
struct RecordedSingleClear {
std::uint64_t surface = 0;
std::uint32_t pipeBankXor = 0;
std::uint32_t width = 0;
std::uint32_t height = 0;
std::uint32_t samples = 0;
std::array<std::uint32_t, 4> color{};
};
std::mutex& singleClearsMutex() {
static std::mutex mutex;
return mutex;
}
std::vector<RecordedSingleClear>& singleClears() {
static std::vector<RecordedSingleClear> list;
return list;
}
std::atomic<bool>& anySingleClears() {
static std::atomic<bool> any{false};
return any;
}
void forgetSingleClears(std::uintptr_t address, std::size_t bytes) {
std::lock_guard lock(singleClearsMutex());
std::erase_if(singleClears(), [&](const RecordedSingleClear& clear) { return clear.surface >= address && clear.surface - address < bytes; });
anySingleClears().store(!singleClears().empty(), std::memory_order_release);
}
void retireUnmapped(std::uintptr_t address, std::size_t bytes) {
forgetSingleClears(address, bytes);
RetireUnmappedDepth_nid_no_patch(address, bytes);
std::unique_lock lock(guardedMutex());
bool metadataChanged = false;
const auto invalidated = std::erase_if(guarded(), [&](const auto& range) {
if (range.metadataValid && address < range.address + range.bytes && range.address < address + bytes) {
range.metadataValid->store(false, std::memory_order_release);
metadataChanged = true;
}
if (range.address < address || range.address - address > bytes || range.bytes > bytes - (range.address - address)) return false;
if (!range.metadataValid) range.active->store(false, std::memory_order_release);
return true;
});
const auto stale = std::erase_if(guarded(), [](const auto& range) { return !range.active->load(std::memory_order_acquire); });
if (metadataChanged || invalidated != 0 || stale != 0) guardedGeneration().fetch_add(1, std::memory_order_release);
anyGuarded().store(!guarded().empty(), std::memory_order_release);
}
void claimOverlapping(std::uint64_t address, std::uint64_t bytes, const TargetUse* claimant) {
for (const auto& range : guarded()) {
if (!range.fmask && range.use.get() != claimant && address < range.address + range.bytes && range.address < address + bytes) range.use->claimed.store(true, std::memory_order_release);
}
}
void stampUse(TargetUse& use, std::uint64_t address, std::uint64_t bytes) {
use.claimed.store(false, std::memory_order_release);
if (bytes == 0) return;