blob: aa56c22092010fb0162b65c4a7b64f7c9c31ad0c (
plain)
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
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
/*
* Copyright (C) 2023, Raspberry Pi Ltd
*
* shared_mem_object.h - Helper class for shared memory allocations
*/
#pragma once
#include <cstddef>
#include <fcntl.h>
#include <string>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <utility>
#include <libcamera/base/class.h>
#include <libcamera/base/shared_fd.h>
namespace libcamera {
namespace RPi {
template<class T>
class SharedMemObject
{
public:
static constexpr std::size_t SIZE = sizeof(T);
SharedMemObject()
: obj_(nullptr)
{
}
template<class... Args>
SharedMemObject(const std::string &name, Args &&...args)
: name_(name), obj_(nullptr)
{
void *mem;
int ret;
ret = memfd_create(name_.c_str(), MFD_CLOEXEC);
if (ret < 0)
return;
fd_ = SharedFD(std::move(ret));
if (!fd_.isValid())
return;
ret = ftruncate(fd_.get(), SIZE);
if (ret < 0)
return;
mem = mmap(nullptr, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED,
fd_.get(), 0);
if (mem == MAP_FAILED)
return;
obj_ = new (mem) T(std::forward<Args>(args)...);
}
SharedMemObject(SharedMemObject<T> &&rhs)
{
this->name_ = std::move(rhs.name_);
this->fd_ = std::move(rhs.fd_);
this->obj_ = rhs.obj_;
rhs.obj_ = nullptr;
}
~SharedMemObject()
{
if (obj_) {
obj_->~T();
munmap(obj_, SIZE);
}
}
/* Make SharedMemObject non-copyable for now. */
LIBCAMERA_DISABLE_COPY(SharedMemObject)
SharedMemObject<T> &operator=(SharedMemObject<T> &&rhs)
{
this->name_ = std::move(rhs.name_);
this->fd_ = std::move(rhs.fd_);
this->obj_ = rhs.obj_;
rhs.obj_ = nullptr;
return *this;
}
T *operator->()
{
return obj_;
}
const T *operator->() const
{
return obj_;
}
T &operator*()
{
return *obj_;
}
const T &operator*() const
{
return *obj_;
}
const SharedFD &fd() const
{
return fd_;
}
explicit operator bool() const
{
return !!obj_;
}
private:
std::string name_;
SharedFD fd_;
T *obj_;
};
} /* namespace RPi */
} /* namespace libcamera */
|