Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions core/kyty/graphics/host_gpu/graphicContext.h
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ struct GraphicContext {
vk::Device device = nullptr;
VmaAllocator allocator = nullptr;
bool memory_budget_ext_enabled = false;
bool partial_textures_enabled = false;
bool host_import_enabled = false;
uint64_t host_import_alignment = 0;
bool compute_subgroup_size_control_enabled = false;
Expand Down Expand Up @@ -131,6 +132,13 @@ struct GraphicContext {
[[nodiscard]] uint64_t GetDeviceMemoryUsage() const;
[[nodiscard]] uint64_t GetTotalMemoryBudget() const;

struct DeviceLocalBudget {
uint64_t usage = 0;
uint64_t budget = 0;
uint64_t reserve = 0;
};
[[nodiscard]] DeviceLocalBudget GetDeviceLocalBudget() const;

struct HeapUsage {
uint64_t usage = 0;
uint64_t budget = 0;
Expand All @@ -139,6 +147,10 @@ struct GraphicContext {
};
[[nodiscard]] uint32_t GetHeapUsage(std::span<HeapUsage, VK_MAX_MEMORY_HEAPS> heaps) const;
[[nodiscard]] bool CreateImage(const vk::ImageCreateInfo& info, VulkanImage& image);
[[nodiscard]] bool CreatePartialImage(const vk::ImageCreateInfo& info, uint32_t first_level, VulkanImage& image);
[[nodiscard]] bool BindOmittedLevels(VulkanImage& image);
[[nodiscard]] uint64_t FlushSparseBinds();
[[nodiscard]] vk::Semaphore SparseBindSemaphore() const noexcept { return m_sparse_semaphore; }
void DeleteImage(VulkanImage& image);

uint32_t screen_width = 0;
Expand All @@ -152,6 +164,20 @@ struct GraphicContext {
vk::ImageCreateFlags>,
std::pair<vk::Result, vk::ImageFormatProperties>>
m_image_format_properties;

struct SparseBind {
vk::Image image = nullptr;
std::vector<vk::SparseImageMemoryBind> levels;
std::vector<vk::SparseMemoryBind> tails;
};
[[nodiscard]] bool QueueLevelBinds(VulkanImage& image, uint32_t first_level, uint32_t end_level,
bool bind_tail, bool within_budget, VmaAllocation& allocation);
void WaitSparseBinds(vk::Image image);

std::mutex m_sparse_mutex;
std::vector<SparseBind> m_sparse_pending;
vk::Semaphore m_sparse_semaphore = nullptr;
uint64_t m_sparse_value = 0;
};

struct VulkanImageState {
Expand All @@ -176,7 +202,9 @@ struct VulkanImage {
VulkanImageState state;
std::vector<VulkanImageState> subresource_states;
VmaAllocation allocation = nullptr;
VmaAllocation omitted_allocation = nullptr;
bool recyclable = false;
uint32_t first_resident_level = 0;
};


Expand Down
41 changes: 38 additions & 3 deletions core/kyty/graphics/host_gpu/renderer/cache/textureCache.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1202,6 +1202,8 @@ void TextureCache::CopyImage(ImageId destination_id, ImageId source_id) {
RefreshCopySource(source_id);
auto& destination = m_slot_images[destination_id];
auto& source = m_slot_images[source_id];
MakeResident(source);
MakeResident(destination);
TrackImage(destination_id);
if (source.backing.samples != destination.backing.samples) {
EXIT("TextureCache: cannot issue an unequal-sample image copy\n");
Expand Down Expand Up @@ -1245,6 +1247,8 @@ void TextureCache::CopyImageMip(ImageId destination_id, ImageId source_id, uint3
}
auto& destination = m_slot_images[destination_id];
auto& source = m_slot_images[source_id];
MakeResident(source);
MakeResident(destination);
TrackImage(destination_id);
if (source.IsBufferModified() || source.backing.samples != destination.backing.samples) {
EXIT("TextureCache: invalid mip-copy ownership or sample count\n");
Expand Down Expand Up @@ -1663,7 +1667,25 @@ bool TextureCache::CanDownload(const Image& image) const {
info.LinearSize() != 0;
}

void TextureCache::UploadImage(Image& image, Buffer& source, uint64_t source_offset) {
void TextureCache::MakeResident(Image& image) {
if (!image.IsPartiallyResident()) {
return;
}
const auto omitted = image.backing.first_resident_level;
if (!image.MakeResident()) {
EXIT("TextureCache: could not back the omitted levels of image 0x%016" PRIx64 "\n",
image.info.data.address);
}
const auto [source, source_offset] =
m_buffer_cache.ObtainBufferForImage(image.info.data.address, image.info.data.size);
if (source == nullptr) {
EXIT("TextureCache: failed to obtain the upload source of omitted levels\n");
}
UploadImage(image, *source, source_offset, omitted);
}

void TextureCache::UploadImage(Image& image, Buffer& source, uint64_t source_offset,
uint32_t level_end) {
auto& destination = image.depth_id ? m_slot_images[image.depth_id] : image;
const auto& info = image.info;
const auto binding = image.depth_id ? BindingType::DepthTarget : UploadBinding(image);
Expand All @@ -1674,14 +1696,18 @@ void TextureCache::UploadImage(Image& image, Buffer& source, uint64_t source_off
EXIT("TextureCache: invalid color-attachment upload\n");
}
const auto linear = m_tiler.Detile(source.Handle(), source_offset, info);
const auto copies = info.BufferCopies(linear.offset);
auto copies = info.BufferCopies(linear.offset);
std::erase_if(copies, [level_end](const vk::BufferImageCopy& copy) {
return copy.imageSubresource.mipLevel >= level_end;
});
EXIT_IF(copies.empty());
destination.Upload(copies, linear.buffer, linear.offset, linear.size);
Common::DebugCounters::Add(Common::DebugCounters::Counter::TextureUploadBytes, linear.size);
return;
}

if (destination.backing.samples != 1 || info.resources.layers == 0 ||
info.data.size % info.resources.layers != 0 ||
info.data.size % info.resources.layers != 0 || level_end != UINT32_MAX ||
Prospero::NumBytesPerElement(info.guest_format) != info.bytes_per_block) {
EXIT("TextureCache: invalid depth upload\n");
}
Expand Down Expand Up @@ -2761,6 +2787,9 @@ vk::ImageView TextureCache::FindTexture(ImageId id, const ImageDesc& desc) {
EXIT("TextureCache: texture requires rediscovery before final acquisition\n");
}
RefreshImage(id);
if (desc.type != BindingType::Texture || image.ReachesOmittedLevels(desc.view_info)) {
MakeResident(image);
}
if (image.info.HasStencil() &&
desc.info.data.address >= image.info.stencil.address &&
desc.info.data.End() <= image.info.stencil.End()) {
Expand Down Expand Up @@ -2792,6 +2821,7 @@ vk::ImageView TextureCache::FindRenderTarget(ImageId id, const ImageDesc& desc)
image.StateChanged();
}
RefreshImage(id);
MakeResident(image);
CommitGpuWrite(image);
TrackImageDownload(id, image);
return image.FindView(desc.view_info);
Expand Down Expand Up @@ -2834,6 +2864,7 @@ vk::ImageView TextureCache::FindDepthTarget(ImageId id, const ImageDesc& desc, I
m_meta_epoch.fetch_add(1, std::memory_order_relaxed);
}
RefreshImage(id);
MakeResident(image);
CommitGpuWrite(image);
if (desc.info.HasStencil()) {
const auto association = AssociateStencil(id, desc.info.stencil);
Expand Down Expand Up @@ -2974,6 +3005,7 @@ bool TextureCache::ClearImageFromBuffer(CommandBuffer& command, uint64_t address
void TextureCache::ClearImage(CommandBuffer& command, ImageId id, vk::Format format,
const vk::ImageSubresourceRange& range, const vk::ClearValue& clear) {
auto& image = m_slot_images[id];
MakeResident(image);
const auto aspects = image.info.IsDepth() ? ImageViewOps::DepthAspectMask(image.backing.format)
: vk::ImageAspectFlagBits::eColor;
EXIT_IF(range.baseMipLevel >= image.info.resources.levels);
Expand Down Expand Up @@ -3037,6 +3069,7 @@ vk::Rect2D TextureCache::BeginColorRendering(Image& image, vk::Format format, ui
uint32_t layer, uint32_t layers,
const vk::ClearValue* clear,
const CommandRecorder& command) {
MakeResident(image);
ImageViewInfo view {};
view.format = format;
view.type = layers == 1 ? vk::ImageViewType::e2D : vk::ImageViewType::e2DArray;
Expand Down Expand Up @@ -3068,6 +3101,7 @@ vk::Rect2D TextureCache::BeginColorRendering(Image& image, vk::Format format, ui
}

void TextureCache::DownloadDepth(Image& image, Buffer& destination, uint64_t destination_offset) {
MakeResident(image);
const auto& info = image.info;
const auto layers = info.resources.layers;
const auto full_slice_size = info.linear_slice_stride != 0 ? info.linear_slice_stride
Expand Down Expand Up @@ -3139,6 +3173,7 @@ void TextureCache::DownloadDepth(Image& image, Buffer& destination, uint64_t des

void TextureCache::DownloadImage(Image& image, Buffer& destination, uint64_t destination_offset,
uint64_t destination_size, uint32_t levels) {
MakeResident(image);
if (UploadBinding(image) == BindingType::DepthTarget) {
EXIT_IF(destination_size != image.info.data.size || levels != image.info.resources.levels);
DownloadDepth(image, destination, destination_offset);
Expand Down
4 changes: 3 additions & 1 deletion core/kyty/graphics/host_gpu/renderer/cache/textureCache.h
Original file line number Diff line number Diff line change
Expand Up @@ -386,7 +386,9 @@ class TextureCache {
uint32_t metadata_base_layer);
void InitializeImage(ImageId id);
[[nodiscard]] bool CanDownload(const Image& image) const;
void UploadImage(Image& image, Buffer& source, uint64_t source_offset);
void UploadImage(Image& image, Buffer& source, uint64_t source_offset,
uint32_t level_end = UINT32_MAX);
void MakeResident(Image& image);
void DownloadImage(Image& image, Buffer& destination, uint64_t destination_offset,
uint64_t destination_size, uint32_t levels);
void DownloadDepth(Image& image, Buffer& destination, uint64_t destination_offset);
Expand Down
3 changes: 3 additions & 0 deletions core/kyty/graphics/host_gpu/renderer/commandScheduler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,9 @@ void CommandScheduler::QueueSubmit(vk::CommandBuffer buffer, SubmitInfo& submit,
auto& graphics = m_graphics;
EXIT_IF(graphics.queue == nullptr);
submit.AddSignal(m_master.Handle(), tick);
if (const auto sparse = graphics.FlushSparseBinds(); sparse != 0) {
submit.AddWait(graphics.SparseBindSemaphore(), sparse);
}

vk::TimelineSemaphoreSubmitInfo timeline_info {};
timeline_info.waitSemaphoreValueCount = submit.num_wait_semaphores;
Expand Down
70 changes: 69 additions & 1 deletion core/kyty/graphics/host_gpu/renderer/image/image.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@
#include <algorithm>
#include <array>
#include <atomic>
#include <cinttypes>
#include <cstdint>
#include <cstdlib>
#include <vector>
#include <fmt/format.h>
#include <xxhash.h>

Expand Down Expand Up @@ -52,6 +55,26 @@ ImageCreateFlags(const GraphicContext& graphics, const ImageInfo& info, vk::Imag
return static_cast<bool>(properties.optimalTilingFeatures & feature);
}

[[nodiscard]] static uint32_t PartialFirstLevel(GraphicContext& graphics, const ImageInfo& info,
const vk::ImageCreateInfo& create) {
static const uint64_t threshold_mb = [] {
const char* value = std::getenv("KYTY_PARTIAL_TEXTURE_MB");
return value != nullptr && value[0] != '\0' ? std::strtoull(value, nullptr, 10) : UINT64_MAX;
}();
if (threshold_mb == 0 || !graphics.partial_textures_enabled || !graphics.CanReportMemoryUsage() ||
!info.IsBlock() || create.imageType != vk::ImageType::e2D || create.samples != vk::SampleCountFlagBits::e1 ||
create.mipLevels < 3 || std::max(create.extent.width, create.extent.height) < 512) {
return 0;
}
const auto memory = graphics.GetDeviceLocalBudget();
const uint64_t start = threshold_mb != UINT64_MAX ? std::min(threshold_mb, UINT64_MAX >> 20u) << 20u
: memory.budget - memory.reserve;
if (memory.budget == 0 || memory.usage < start) {
return 0;
}
return memory.usage >= start + (memory.budget - std::min(memory.budget, start)) / 2u ? 2u : 1u;
}

[[nodiscard]] vk::ImageUsageFlags ImageUsageFlags(GraphicContext& graphics, const ImageInfo& info) {
auto usage = vk::ImageUsageFlagBits::eTransferSrc | vk::ImageUsageFlagBits::eTransferDst;
if (info.IsBlock()) {
Expand Down Expand Up @@ -287,6 +310,18 @@ void Image::Transit(vk::ImageLayout destination_layout, vk::AccessFlags2 destina
void Image::Upload(std::span<const vk::BufferImageCopy> copies, vk::Buffer buffer, uint64_t offset,
uint64_t size) {
EXIT_IF(copies.empty() || buffer == nullptr || size == 0);
std::vector<vk::BufferImageCopy> resident;
if (backing.first_resident_level != 0) {
for (const auto& copy: copies) {
if (copy.imageSubresource.mipLevel >= backing.first_resident_level) {
resident.push_back(copy);
}
}
if (resident.empty()) {
return;
}
copies = resident;
}
m_scheduler.EndRendering();
vk::BufferMemoryBarrier2 buffer_barrier {};
buffer_barrier.srcStageMask = vk::PipelineStageFlagBits2::eAllCommands;
Expand Down Expand Up @@ -321,9 +356,33 @@ void Image::Upload(std::span<const vk::BufferImageCopy> copies, vk::Buffer buffe
command.pipelineBarrier2(dependency);
}

void Image::RequireResident(const Image& source) const {
if (IsPartiallyResident() || source.IsPartiallyResident()) {
EXIT("Image: a transfer reaches the omitted levels of a partially resident image "
"(guest 0x%016" PRIx64 ", source 0x%016" PRIx64 ")\n",
info.data.address, source.info.data.address);
}
}

bool Image::MakeResident() {
if (!IsPartiallyResident()) {
return true;
}
if (!m_graphics.BindOmittedLevels(backing)) {
return false;
}
for (const auto& cached: views) {
m_retired_views.push_back(cached.view);
}
views.clear();
HeapChanged();
return true;
}

void Image::Download(std::span<const vk::BufferImageCopy> copies, vk::Buffer buffer,
uint64_t offset, uint64_t size) {
EXIT_IF(copies.empty() || buffer == nullptr || size == 0);
RequireResident(*this);
m_scheduler.EndRendering();
vk::BufferMemoryBarrier2 buffer_barrier {};
buffer_barrier.srcStageMask = vk::PipelineStageFlagBits2::eAllCommands;
Expand Down Expand Up @@ -383,6 +442,7 @@ std::pair<uint32_t, uint32_t> Image::SanitizeCopyLayers(const Image& source,

void Image::CopyImage(Image& source) {
EXIT_IF(source.backing.samples != backing.samples);
RequireResident(source);
m_scheduler.EndRendering();
const uint32_t levels = std::min(source.backing.mip_levels, backing.mip_levels);
uint32_t base_depth = source.backing.extent.depth;
Expand Down Expand Up @@ -440,6 +500,7 @@ void Image::Resolve(Image& source, const ImageSubresourceRange& source_range,
destination_range.base_level >= backing.mip_levels ||
source_range.base_layer >= source.backing.layers ||
destination_range.base_layer >= backing.layers);
RequireResident(source);
const auto layers = std::min({source_range.layer_count, destination_range.layer_count,
source.backing.layers - source_range.base_layer,
backing.layers - destination_range.base_layer});
Expand Down Expand Up @@ -499,6 +560,7 @@ uint32_t Image::CopyRows(uint64_t row_size, uint32_t rows, uint64_t capacity) no

void Image::CopyImageWithBuffer(Image& source, Buffer& buffer, TileManager& tiler) {
EXIT_IF(buffer.Handle() == nullptr || source.backing.samples != 1 || backing.samples != 1);
RequireResident(source);
m_scheduler.EndRendering();
const uint32_t levels = std::min(source.backing.mip_levels, backing.mip_levels);
const auto source_aspect =
Expand Down Expand Up @@ -599,6 +661,7 @@ void Image::CopyImageWithBuffer(Image& source, Buffer& buffer, TileManager& tile
void Image::CopyMip(Image& source, uint32_t mip, uint32_t layer) {
EXIT_IF(source.backing.samples != backing.samples || mip >= backing.mip_levels ||
layer >= backing.layers);
RequireResident(source);
m_scheduler.EndRendering();
const auto width = std::max(backing.extent.width >> mip, 1u);
const auto height = std::max(backing.extent.height >> mip, 1u);
Expand Down Expand Up @@ -749,7 +812,9 @@ Image::Image(GraphicContext& graphics, CommandScheduler& scheduler, const ImageI
static_cast<vk::ImageCreateFlags::MaskType>(create.flags), info.samples);
}

if (!graphics.CreateImage(create, backing)) {
const auto first_level = PartialFirstLevel(graphics, info, create);
if ((first_level == 0 || !graphics.CreatePartialImage(create, first_level, backing)) &&
!graphics.CreateImage(create, backing)) {
EXIT("failed to create image: extent=%ux%ux%u format=%d layers=%u levels=%u\n",
create.extent.width, create.extent.height, create.extent.depth,
static_cast<int>(create.format), create.arrayLayers, create.mipLevels);
Expand Down Expand Up @@ -786,6 +851,9 @@ Image::~Image() {
for (const auto& cached: views) {
m_graphics.device.destroyImageView(cached.view, nullptr);
}
for (const auto view: m_retired_views) {
m_graphics.device.destroyImageView(view, nullptr);
}
if (backing.image != nullptr) {
m_graphics.DeleteImage(backing);
}
Expand Down
10 changes: 10 additions & 0 deletions core/kyty/graphics/host_gpu/renderer/image/image.h
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,13 @@ class Image final {
const ImageSubresourceRange& destination_range);
void CopyImageWithBuffer(Image& source, Buffer& buffer, TileManager& tiler);
void CopyMip(Image& source, uint32_t mip, uint32_t layer);
[[nodiscard]] bool IsPartiallyResident() const noexcept { return backing.first_resident_level != 0; }
[[nodiscard]] bool ReachesOmittedLevels(const ImageViewInfo& view) const noexcept {
return IsPartiallyResident() &&
(static_cast<bool>(view.usage & ~vk::ImageUsageFlagBits::eSampled) ||
view.base_level + view.level_count <= backing.first_resident_level);
}
[[nodiscard]] bool MakeResident();

[[nodiscard]] static uint64_t CpuDirtyEpoch() noexcept {
return s_cpu_dirty_epoch.load(std::memory_order_relaxed);
Expand Down Expand Up @@ -262,8 +269,11 @@ class Image final {
[[nodiscard]] static std::pair<uint32_t, uint32_t>
SanitizeCopyLayers(const Image& source, const Image& destination, uint32_t depth);

void RequireResident(const Image& source) const;

GraphicContext& m_graphics;
CommandScheduler& m_scheduler;
std::vector<vk::ImageView> m_retired_views;
uint64_t m_maybe_cpu_hash = 0;
bool m_cpu_dirty = false;
bool m_maybe_cpu_dirty = false;
Expand Down
Loading
Loading