1 // Copyright (C) 2024 The Android Open Source Project 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 #pragma once 16 17 #include <memory> 18 #include <variant> 19 20 #ifdef GFXSTREAM_BUILD_WITH_SNAPSHOT_FRONTEND_SUPPORT 21 #include "VirtioGpuResourceSnapshot.pb.h" 22 #endif 23 #include "aemu/base/AlignedBuf.h" 24 #include "aemu/base/memory/SharedMemory.h" 25 26 namespace gfxstream { 27 namespace host { 28 29 // LINT.IfChange(virtio_gpu_ring_blob) 30 31 struct AlignedMemory { 32 void* addr = nullptr; 33 AlignedMemoryAlignedMemory34 AlignedMemory(size_t align, size_t size) : addr(android::aligned_buf_alloc(align, size)) {} 35 ~AlignedMemoryAlignedMemory36 ~AlignedMemory() { 37 if (addr != nullptr) { 38 android::aligned_buf_free(addr); 39 } 40 } 41 42 // AlignedMemory is neither copyable nor movable. 43 AlignedMemory(const AlignedMemory& other) = delete; 44 AlignedMemory& operator=(const AlignedMemory& other) = delete; 45 AlignedMemory(AlignedMemory&& other) = delete; 46 AlignedMemory& operator=(AlignedMemory&& other) = delete; 47 }; 48 49 // Memory used as a ring buffer for communication between the guest and host. 50 class RingBlob { 51 public: 52 static std::unique_ptr<RingBlob> CreateWithShmem(uint32_t id, uint64_t size); 53 static std::unique_ptr<RingBlob> CreateWithHostMemory(uint32_t, uint64_t size, uint64_t alignment); 54 55 bool isExportable() const; 56 57 // Only valid if `isExportable()` returns `true`. 58 android::base::SharedMemory::handle_type releaseHandle(); 59 60 void* map(); 61 size()62 uint64_t size() const { return mSize; } 63 64 #ifdef GFXSTREAM_BUILD_WITH_SNAPSHOT_FRONTEND_SUPPORT 65 std::optional<gfxstream::host::snapshot::VirtioGpuRingBlobSnapshot> Snapshot(); 66 67 static std::optional<std::unique_ptr<RingBlob>> Restore( 68 const gfxstream::host::snapshot::VirtioGpuRingBlobSnapshot& snapshot); 69 #endif 70 71 private: 72 RingBlob(uint32_t id, 73 uint64_t size, 74 uint64_t alignment, 75 std::variant<std::unique_ptr<AlignedMemory>, 76 std::unique_ptr<android::base::SharedMemory>> memory); 77 78 const uint64_t mId; 79 const uint64_t mSize; 80 const uint64_t mAlignment; 81 std::variant<std::unique_ptr<AlignedMemory>, 82 std::unique_ptr<android::base::SharedMemory>> mMemory; 83 }; 84 85 // LINT.ThenChange(VirtioGpuRingBlobSnapshot.h:virtio_gpu_ring_blob) 86 87 } // namespace host 88 } // namespace gfxstream 89