Hyprland/src/protocols/core/Shm.cpp

237 lines
7.5 KiB
C++
Raw Normal View History

#include "Shm.hpp"
#include <algorithm>
#include <sys/mman.h>
#include <sys/stat.h>
#include <drm_fourcc.h>
#include "../../render/Texture.hpp"
#include "../types/WLBuffer.hpp"
#include "../../helpers/Format.hpp"
#include "../../render/Renderer.hpp"
core: begin using CFileDescriptor from hyprutils (#9122) * config: make fd use CFileDescriptor make use of the new hyprutils CFileDescriptor instead of manual FD handling. * hyprctl: make fd use CFileDescriptor make use of the new hyprutils CFileDescriptor instead of manual FD handling. * ikeyboard: make fd use CFileDescriptor make use of the new CFileDescriptor instead of manual FD handling, also in sendKeymap remove dead code, it already early returns if keyboard isnt valid, and dont try to close the FD that ikeyboard owns. * core: make SHMFile functions use CFileDescriptor make SHMFile misc functions use CFileDescriptor and its associated usage in dmabuf and keyboard. * core: make explicit sync use CFileDescriptor begin using CFileDescriptor in explicit sync and its timelines and eglsync usage in opengl, there is still a bit left with manual handling that requires future aquamarine change aswell. * eventmgr: make fd and sockets use CFileDescriptor make use of the hyprutils CFileDescriptor instead of manual FD and socket handling and closing. * eventloopmgr: make timerfd use CFileDescriptor make the timerfd use CFileDescriptor instead of manual fd handling * opengl: make gbm fd use CFileDescriptor make the gbm rendernode fd use CFileDescriptor instead of manual fd handling * core: make selection source/offer use CFileDescriptor make data selection source and offers use CFileDescriptor and its associated use in xwm and protocols * protocols: convert protocols fd to CFileDescriptor make most fd handling use CFileDescriptor in protocols * shm: make SHMPool use CfileDescriptor make SHMPool use CFileDescriptor instead of manual fd handling. * opengl: duplicate fd with CFileDescriptor duplicate fenceFD with CFileDescriptor duplicate instead. * xwayland: make sockets and fds use CFileDescriptor instead of manual opening/closing make sockets and fds use CFileDescriptor * keybindmgr: make sockets and fds use CFileDescriptor make sockets and fds use CFileDescriptor instead of manual handling.
2025-01-30 12:30:12 +01:00
using namespace Hyprutils::OS;
CWLSHMBuffer::CWLSHMBuffer(SP<CWLSHMPoolResource> pool_, uint32_t id, int32_t offset_, const Vector2D& size_, int32_t stride_, uint32_t fmt_) {
if UNLIKELY (!pool_->m_pool->m_data)
return;
g_pHyprRenderer->makeEGLCurrent();
size = size_;
m_pool = pool_->m_pool;
m_stride = stride_;
m_fmt = fmt_;
m_offset = offset_;
m_opaque = NFormatUtils::isFormatOpaque(NFormatUtils::shmToDRM(fmt_));
m_resource = CWLBufferResource::create(makeShared<CWlBuffer>(pool_->m_resource->client(), 1, id));
m_listeners.bufferResourceDestroy = events.destroy.listen([this] {
m_listeners.bufferResourceDestroy.reset();
PROTO::shm->destroyResource(this);
});
}
syncobj: use eventfd instead of stalling fd checks (#9437) * syncobj: cleanup and use uniqueptrs cleanup a bit missing removals if resource not good, erasing from containers etc. make use of unique ptrs instead. and add default destructors. * syncobj: rework syncobj entirerly remove early buffer release that was breaking explicit sync, the buffer needs to exist until the surface commit event has been emitted and draw calls added egl sync points, move to eventfd signaling instead of stalling sync point checks, and recommit pending commits if waiting on a signal. add a CDRMSyncPointState helper class. move a few weak pointers to shared pointers so they dont destruct before we need to use them. * syncobj: queue pending states for eventfd eventfd requires us to queue pending stats until ready and then apply to current, and also when no ready state exist commit the client commit on the current existing buffer, if there is one. * syncobj: clear current buffer damage clear current buffer damage on current buffer commits. * syncobj: cleanup code and fix hyprlock remove unused code, and ensure we dont commit a empty texture causing locksession protocol and gtk4-layer-shell misbehaving. * syncobj: ensure buffers are cleaned up ensure the containers having the various buffers actually gets cleaned up from their containers, incase the CSignal isnt signaled because of expired smart pointers or just wrong order destruction because mishaps. also move the acquire/point setting to buffer attaching. instead of on precommit. * syncobj: remove unused code, optimize remove unused code and merge sync fds if fence is valid, remove manual directscanout buffer dropping that signals release point on pageflip, it can cause us to signal the release point while still keeping the current buffer and rendering it yet again causing wrong things. * syncobj: delay buffer release on non syncobj delay buffer releases on non syncobj surfaces until next commit, and check on async buffers if syncobj and drop and signal the release point on backend buffer release. * syncobj: ensure we follow protocol ensure we follow protocol by replacing acquire/release points if they arrive late and replace already existing ones. also remove unneded brackets, and dont try to manual lock/release buffers when it comes to explicit protocol. it doesnt care about buffer releases only about acquire and release points and signaling them. * syncobj: lets not complicate things set points in precommit, before checking protocol errors and we catch any pending acquire/release points arriving late. * syncobj: move SSurfaceState to types remove destructor resource destroying, let resources destroys them on their events, and move SSurfaceStates to types/SurfaceState.hpp * syncobj: actually store the merged fd have to actually store the mergedfd to use it. * syncobj: cleanup a bit around fences ensure the current asynchronous buffer is actually released on pageflip not the previous. cleanup a bit FD handling in commitPendingAndDoExplicitSync, and reuse the in fence when syncing surfaces. * syncobjs: ensure fence FD doesnt leak calling resetexplicitfence without properly ensuring the FD is closed before will leak it, store it per monitor and let it close itself with the CFileDescriptor class. * syncobj: ensure buffers are actually released buffers were never being sent released properly. * types: Defer buffer sync releaser until unlock * syncobj: store directscanout fence in monitor ensure the infence fd survives the scope of attemptdirectscanout so it doesnt close before it should have. * syncobj: check if if acquire is expired we might hit a race to finish on exit where the timeline just has destructed but the buffer waiter is still pending. and such we removeAllWaiters null dereferences. * syncobj: code style changes remove quack comment, change to m_foo and use a std::vector and weakpointer in the waiter for removal instead of a std::list. * syncobj: remove unused async buffer drop remove unused async buffer drop, only related to directscanout and is handled elsewhere. --------- Co-authored-by: Lee Bousfield <ljbousfield@gmail.com>
2025-03-14 15:08:20 +01:00
CWLSHMBuffer::~CWLSHMBuffer() {
if (m_resource)
m_resource->sendRelease();
syncobj: use eventfd instead of stalling fd checks (#9437) * syncobj: cleanup and use uniqueptrs cleanup a bit missing removals if resource not good, erasing from containers etc. make use of unique ptrs instead. and add default destructors. * syncobj: rework syncobj entirerly remove early buffer release that was breaking explicit sync, the buffer needs to exist until the surface commit event has been emitted and draw calls added egl sync points, move to eventfd signaling instead of stalling sync point checks, and recommit pending commits if waiting on a signal. add a CDRMSyncPointState helper class. move a few weak pointers to shared pointers so they dont destruct before we need to use them. * syncobj: queue pending states for eventfd eventfd requires us to queue pending stats until ready and then apply to current, and also when no ready state exist commit the client commit on the current existing buffer, if there is one. * syncobj: clear current buffer damage clear current buffer damage on current buffer commits. * syncobj: cleanup code and fix hyprlock remove unused code, and ensure we dont commit a empty texture causing locksession protocol and gtk4-layer-shell misbehaving. * syncobj: ensure buffers are cleaned up ensure the containers having the various buffers actually gets cleaned up from their containers, incase the CSignal isnt signaled because of expired smart pointers or just wrong order destruction because mishaps. also move the acquire/point setting to buffer attaching. instead of on precommit. * syncobj: remove unused code, optimize remove unused code and merge sync fds if fence is valid, remove manual directscanout buffer dropping that signals release point on pageflip, it can cause us to signal the release point while still keeping the current buffer and rendering it yet again causing wrong things. * syncobj: delay buffer release on non syncobj delay buffer releases on non syncobj surfaces until next commit, and check on async buffers if syncobj and drop and signal the release point on backend buffer release. * syncobj: ensure we follow protocol ensure we follow protocol by replacing acquire/release points if they arrive late and replace already existing ones. also remove unneded brackets, and dont try to manual lock/release buffers when it comes to explicit protocol. it doesnt care about buffer releases only about acquire and release points and signaling them. * syncobj: lets not complicate things set points in precommit, before checking protocol errors and we catch any pending acquire/release points arriving late. * syncobj: move SSurfaceState to types remove destructor resource destroying, let resources destroys them on their events, and move SSurfaceStates to types/SurfaceState.hpp * syncobj: actually store the merged fd have to actually store the mergedfd to use it. * syncobj: cleanup a bit around fences ensure the current asynchronous buffer is actually released on pageflip not the previous. cleanup a bit FD handling in commitPendingAndDoExplicitSync, and reuse the in fence when syncing surfaces. * syncobjs: ensure fence FD doesnt leak calling resetexplicitfence without properly ensuring the FD is closed before will leak it, store it per monitor and let it close itself with the CFileDescriptor class. * syncobj: ensure buffers are actually released buffers were never being sent released properly. * types: Defer buffer sync releaser until unlock * syncobj: store directscanout fence in monitor ensure the infence fd survives the scope of attemptdirectscanout so it doesnt close before it should have. * syncobj: check if if acquire is expired we might hit a race to finish on exit where the timeline just has destructed but the buffer waiter is still pending. and such we removeAllWaiters null dereferences. * syncobj: code style changes remove quack comment, change to m_foo and use a std::vector and weakpointer in the waiter for removal instead of a std::list. * syncobj: remove unused async buffer drop remove unused async buffer drop, only related to directscanout and is handled elsewhere. --------- Co-authored-by: Lee Bousfield <ljbousfield@gmail.com>
2025-03-14 15:08:20 +01:00
}
Aquamarine::eBufferCapability CWLSHMBuffer::caps() {
return Aquamarine::eBufferCapability::BUFFER_CAPABILITY_DATAPTR;
}
Aquamarine::eBufferType CWLSHMBuffer::type() {
return Aquamarine::eBufferType::BUFFER_TYPE_SHM;
}
bool CWLSHMBuffer::isSynchronous() {
return true;
}
Aquamarine::SSHMAttrs CWLSHMBuffer::shm() {
Aquamarine::SSHMAttrs attrs;
attrs.success = true;
attrs.fd = m_pool->m_fd.get();
attrs.format = NFormatUtils::shmToDRM(m_fmt);
attrs.size = size;
attrs.stride = m_stride;
attrs.offset = m_offset;
return attrs;
}
std::tuple<uint8_t*, uint32_t, size_t> CWLSHMBuffer::beginDataPtr(uint32_t flags) {
return {sc<uint8_t*>(m_pool->m_data) + m_offset, m_fmt, m_stride * size.y};
}
void CWLSHMBuffer::endDataPtr() {
;
}
bool CWLSHMBuffer::good() {
return true;
}
void CWLSHMBuffer::update(const CRegion& damage) {
;
}
CSHMPool::CSHMPool(CFileDescriptor fd_, size_t size_) : m_fd(std::move(fd_)), m_size(size_), m_data(mmap(nullptr, m_size, PROT_READ | PROT_WRITE, MAP_SHARED, m_fd.get(), 0)) {
;
}
CSHMPool::~CSHMPool() {
munmap(m_data, m_size);
}
void CSHMPool::resize(size_t size_) {
LOGM(LOG, "Resizing a SHM pool from {} to {}", m_size, size_);
if (m_data)
munmap(m_data, m_size);
m_size = size_;
m_data = mmap(nullptr, m_size, PROT_READ | PROT_WRITE, MAP_SHARED, m_fd.get(), 0);
if UNLIKELY (m_data == MAP_FAILED)
LOGM(ERR, "Couldn't mmap {} bytes from fd {} of shm client", m_size, m_fd.get());
}
core: begin using CFileDescriptor from hyprutils (#9122) * config: make fd use CFileDescriptor make use of the new hyprutils CFileDescriptor instead of manual FD handling. * hyprctl: make fd use CFileDescriptor make use of the new hyprutils CFileDescriptor instead of manual FD handling. * ikeyboard: make fd use CFileDescriptor make use of the new CFileDescriptor instead of manual FD handling, also in sendKeymap remove dead code, it already early returns if keyboard isnt valid, and dont try to close the FD that ikeyboard owns. * core: make SHMFile functions use CFileDescriptor make SHMFile misc functions use CFileDescriptor and its associated usage in dmabuf and keyboard. * core: make explicit sync use CFileDescriptor begin using CFileDescriptor in explicit sync and its timelines and eglsync usage in opengl, there is still a bit left with manual handling that requires future aquamarine change aswell. * eventmgr: make fd and sockets use CFileDescriptor make use of the hyprutils CFileDescriptor instead of manual FD and socket handling and closing. * eventloopmgr: make timerfd use CFileDescriptor make the timerfd use CFileDescriptor instead of manual fd handling * opengl: make gbm fd use CFileDescriptor make the gbm rendernode fd use CFileDescriptor instead of manual fd handling * core: make selection source/offer use CFileDescriptor make data selection source and offers use CFileDescriptor and its associated use in xwm and protocols * protocols: convert protocols fd to CFileDescriptor make most fd handling use CFileDescriptor in protocols * shm: make SHMPool use CfileDescriptor make SHMPool use CFileDescriptor instead of manual fd handling. * opengl: duplicate fd with CFileDescriptor duplicate fenceFD with CFileDescriptor duplicate instead. * xwayland: make sockets and fds use CFileDescriptor instead of manual opening/closing make sockets and fds use CFileDescriptor * keybindmgr: make sockets and fds use CFileDescriptor make sockets and fds use CFileDescriptor instead of manual handling.
2025-01-30 12:30:12 +01:00
static int shmIsSizeValid(CFileDescriptor& fd, size_t size) {
struct stat st;
core: begin using CFileDescriptor from hyprutils (#9122) * config: make fd use CFileDescriptor make use of the new hyprutils CFileDescriptor instead of manual FD handling. * hyprctl: make fd use CFileDescriptor make use of the new hyprutils CFileDescriptor instead of manual FD handling. * ikeyboard: make fd use CFileDescriptor make use of the new CFileDescriptor instead of manual FD handling, also in sendKeymap remove dead code, it already early returns if keyboard isnt valid, and dont try to close the FD that ikeyboard owns. * core: make SHMFile functions use CFileDescriptor make SHMFile misc functions use CFileDescriptor and its associated usage in dmabuf and keyboard. * core: make explicit sync use CFileDescriptor begin using CFileDescriptor in explicit sync and its timelines and eglsync usage in opengl, there is still a bit left with manual handling that requires future aquamarine change aswell. * eventmgr: make fd and sockets use CFileDescriptor make use of the hyprutils CFileDescriptor instead of manual FD and socket handling and closing. * eventloopmgr: make timerfd use CFileDescriptor make the timerfd use CFileDescriptor instead of manual fd handling * opengl: make gbm fd use CFileDescriptor make the gbm rendernode fd use CFileDescriptor instead of manual fd handling * core: make selection source/offer use CFileDescriptor make data selection source and offers use CFileDescriptor and its associated use in xwm and protocols * protocols: convert protocols fd to CFileDescriptor make most fd handling use CFileDescriptor in protocols * shm: make SHMPool use CfileDescriptor make SHMPool use CFileDescriptor instead of manual fd handling. * opengl: duplicate fd with CFileDescriptor duplicate fenceFD with CFileDescriptor duplicate instead. * xwayland: make sockets and fds use CFileDescriptor instead of manual opening/closing make sockets and fds use CFileDescriptor * keybindmgr: make sockets and fds use CFileDescriptor make sockets and fds use CFileDescriptor instead of manual handling.
2025-01-30 12:30:12 +01:00
if UNLIKELY (fstat(fd.get(), &st) == -1) {
LOGM(ERR, "Couldn't get stat for fd {} of shm client", fd.get());
return 0;
}
return sc<size_t>(st.st_size) >= size;
}
CWLSHMPoolResource::CWLSHMPoolResource(SP<CWlShmPool> resource_, CFileDescriptor fd_, size_t size_) : m_resource(resource_) {
if UNLIKELY (!good())
return;
if UNLIKELY (!shmIsSizeValid(fd_, size_)) {
resource_->error(-1, "The size of the file is not big enough for the shm pool");
return;
}
m_pool = makeShared<CSHMPool>(std::move(fd_), size_);
m_resource->setDestroy([this](CWlShmPool* r) { PROTO::shm->destroyResource(this); });
m_resource->setOnDestroy([this](CWlShmPool* r) { PROTO::shm->destroyResource(this); });
m_resource->setResize([this](CWlShmPool* r, int32_t size_) {
if UNLIKELY (size_ < sc<int32_t>(m_pool->m_size)) {
r->error(-1, "Shrinking a shm pool is illegal");
return;
}
if UNLIKELY (!shmIsSizeValid(m_pool->m_fd, size_)) {
r->error(-1, "The size of the file is not big enough for the shm pool");
return;
}
m_pool->resize(size_);
});
m_resource->setCreateBuffer([this](CWlShmPool* r, uint32_t id, int32_t offset, int32_t w, int32_t h, int32_t stride, uint32_t fmt) {
if UNLIKELY (!m_pool || !m_pool->m_data) {
r->error(-1, "The provided shm pool failed to allocate properly");
return;
}
if UNLIKELY (std::ranges::find(PROTO::shm->m_shmFormats, fmt) == PROTO::shm->m_shmFormats.end()) {
r->error(WL_SHM_ERROR_INVALID_FORMAT, "Format invalid");
return;
}
if UNLIKELY (offset < 0 || w <= 0 || h <= 0 || stride <= 0) {
r->error(WL_SHM_ERROR_INVALID_STRIDE, "Invalid stride, w, h, or offset");
return;
}
const auto RESOURCE = PROTO::shm->m_buffers.emplace_back(makeShared<CWLSHMBuffer>(m_self.lock(), id, offset, Vector2D{w, h}, stride, fmt));
if UNLIKELY (!RESOURCE->good()) {
r->noMemory();
PROTO::shm->m_buffers.pop_back();
return;
}
// append instance so that buffer knows its owner
RESOURCE->m_resource->m_buffer = RESOURCE;
});
if UNLIKELY (m_pool->m_data == MAP_FAILED)
m_resource->error(WL_SHM_ERROR_INVALID_FD, "Couldn't mmap from fd");
}
bool CWLSHMPoolResource::good() {
return m_resource->resource();
}
CWLSHMResource::CWLSHMResource(SP<CWlShm> resource_) : m_resource(resource_) {
if UNLIKELY (!good())
return;
m_resource->setOnDestroy([this](CWlShm* r) { PROTO::shm->destroyResource(this); });
m_resource->setCreatePool([](CWlShm* r, uint32_t id, int32_t fd, int32_t size) {
core: begin using CFileDescriptor from hyprutils (#9122) * config: make fd use CFileDescriptor make use of the new hyprutils CFileDescriptor instead of manual FD handling. * hyprctl: make fd use CFileDescriptor make use of the new hyprutils CFileDescriptor instead of manual FD handling. * ikeyboard: make fd use CFileDescriptor make use of the new CFileDescriptor instead of manual FD handling, also in sendKeymap remove dead code, it already early returns if keyboard isnt valid, and dont try to close the FD that ikeyboard owns. * core: make SHMFile functions use CFileDescriptor make SHMFile misc functions use CFileDescriptor and its associated usage in dmabuf and keyboard. * core: make explicit sync use CFileDescriptor begin using CFileDescriptor in explicit sync and its timelines and eglsync usage in opengl, there is still a bit left with manual handling that requires future aquamarine change aswell. * eventmgr: make fd and sockets use CFileDescriptor make use of the hyprutils CFileDescriptor instead of manual FD and socket handling and closing. * eventloopmgr: make timerfd use CFileDescriptor make the timerfd use CFileDescriptor instead of manual fd handling * opengl: make gbm fd use CFileDescriptor make the gbm rendernode fd use CFileDescriptor instead of manual fd handling * core: make selection source/offer use CFileDescriptor make data selection source and offers use CFileDescriptor and its associated use in xwm and protocols * protocols: convert protocols fd to CFileDescriptor make most fd handling use CFileDescriptor in protocols * shm: make SHMPool use CfileDescriptor make SHMPool use CFileDescriptor instead of manual fd handling. * opengl: duplicate fd with CFileDescriptor duplicate fenceFD with CFileDescriptor duplicate instead. * xwayland: make sockets and fds use CFileDescriptor instead of manual opening/closing make sockets and fds use CFileDescriptor * keybindmgr: make sockets and fds use CFileDescriptor make sockets and fds use CFileDescriptor instead of manual handling.
2025-01-30 12:30:12 +01:00
CFileDescriptor poolFd{fd};
const auto RESOURCE = PROTO::shm->m_pools.emplace_back(makeShared<CWLSHMPoolResource>(makeShared<CWlShmPool>(r->client(), r->version(), id), std::move(poolFd), size));
if UNLIKELY (!RESOURCE->good()) {
r->noMemory();
PROTO::shm->m_pools.pop_back();
return;
}
RESOURCE->m_self = RESOURCE;
});
// send a few supported formats. No need for any other I think?
for (auto const& s : PROTO::shm->m_shmFormats) {
m_resource->sendFormat(sc<wl_shm_format>(s));
}
}
bool CWLSHMResource::good() {
return m_resource->resource();
}
CWLSHMProtocol::CWLSHMProtocol(const wl_interface* iface, const int& ver, const std::string& name) : IWaylandProtocol(iface, ver, name) {
;
}
void CWLSHMProtocol::bindManager(wl_client* client, void* data, uint32_t ver, uint32_t id) {
if (m_shmFormats.empty()) {
m_shmFormats.push_back(WL_SHM_FORMAT_ARGB8888);
m_shmFormats.push_back(WL_SHM_FORMAT_XRGB8888);
static const std::array<DRMFormat, 6> supportedShmFourccFormats = {
DRM_FORMAT_XBGR8888, DRM_FORMAT_ABGR8888, DRM_FORMAT_XRGB2101010, DRM_FORMAT_ARGB2101010, DRM_FORMAT_XBGR2101010, DRM_FORMAT_ABGR2101010,
};
for (auto const& fmt : supportedShmFourccFormats) {
m_shmFormats.push_back(fmt);
}
}
const auto RESOURCE = m_managers.emplace_back(makeShared<CWLSHMResource>(makeShared<CWlShm>(client, ver, id)));
if UNLIKELY (!RESOURCE->good()) {
wl_client_post_no_memory(client);
m_managers.pop_back();
return;
}
}
void CWLSHMProtocol::destroyResource(CWLSHMResource* resource) {
std::erase_if(m_managers, [&](const auto& other) { return other.get() == resource; });
}
void CWLSHMProtocol::destroyResource(CWLSHMPoolResource* resource) {
std::erase_if(m_pools, [&](const auto& other) { return other.get() == resource; });
}
void CWLSHMProtocol::destroyResource(CWLSHMBuffer* resource) {
std::erase_if(m_buffers, [&](const auto& other) { return other.get() == resource; });
}