Fix memory offset bug in RamBuffer

This commit is contained in:
2020-09-22 10:15:20 +02:00
parent cb7f37f08b
commit d858b4dc56
2 changed files with 34 additions and 16 deletions
+27 -13
View File
@@ -16,33 +16,34 @@ RamBuffer::RamBuffer(
detector_name_(detector_name),
n_modules_(n_modules),
n_slots_(n_slots),
meta_size_(sizeof(ModuleFrame) * n_modules_),
image_size_(MODULE_N_BYTES * n_modules_),
buffer_size_((meta_size_ + image_size_) * n_slots_)
meta_bytes_(sizeof(ModuleFrame) * n_modules_),
image_bytes_(MODULE_N_BYTES * n_modules_),
buffer_bytes_((meta_bytes_ + image_bytes_) * n_slots_)
{
shm_fd_ = shm_open(detector_name_.c_str(), O_RDWR | O_CREAT, 0777);
if (shm_fd_ < 0) {
throw runtime_error(strerror(errno));
}
if ((ftruncate(shm_fd_, buffer_size_)) == -1) {
if ((ftruncate(shm_fd_, buffer_bytes_)) == -1) {
throw runtime_error(strerror(errno));
}
// TODO: Test with MAP_HUGETLB
buffer_ = mmap(NULL, buffer_size_, PROT_WRITE, MAP_SHARED, shm_fd_, 0);
buffer_ = mmap(NULL, buffer_bytes_, PROT_WRITE, MAP_SHARED, shm_fd_, 0);
if (buffer_ == MAP_FAILED) {
throw runtime_error(strerror(errno));
}
// Metadata buffer is located at the start of the memory region.
meta_buffer_ = (ModuleFrame *) buffer_;
// Image buffer start right after metadata buffer.
image_buffer_ = (char*)buffer_ + (meta_size_ * n_slots_);
image_buffer_ = (char*)buffer_ + (meta_bytes_ * n_slots_);
}
RamBuffer::~RamBuffer()
{
munmap(buffer_, buffer_size_);
munmap(buffer_, buffer_bytes_);
close(shm_fd_);
shm_unlink(detector_name_.c_str());
}
@@ -54,27 +55,40 @@ void RamBuffer::write_frame(
const int slot_n = src_meta->pulse_id % n_slots_;
ModuleFrame *dst_meta = meta_buffer_ +
(meta_size_ * slot_n) +
(n_modules_ * slot_n) +
src_meta->module_id;
char *dst_data = image_buffer_ +
(image_size_ * slot_n) +
(image_bytes_ * slot_n) +
(MODULE_N_BYTES * src_meta->module_id);
memcpy(dst_meta, src_meta, sizeof(ModuleFrame));
memcpy(dst_data, src_data, MODULE_N_BYTES);
}
void RamBuffer::read_frame(
const uint64_t pulse_id,
const uint64_t module_id,
ModuleFrame*& meta,
char*& data) const
{
const size_t slot_n = pulse_id % n_slots_;
meta = meta_buffer_ + (n_modules_ * slot_n) + module_id;
data = image_buffer_ +
(image_bytes_ * slot_n) +
(MODULE_N_BYTES * module_id);
}
char* RamBuffer::read_image(const uint64_t pulse_id,
ImageMetadata &image_meta) const
{
const size_t slot_n = pulse_id % n_slots_;
ModuleFrame *src_meta = meta_buffer_ +
(meta_size_ * slot_n);
ModuleFrame *src_meta = meta_buffer_ + (n_modules_ * slot_n);
char *src_data = image_buffer_ +
(image_size_ * slot_n);
char *src_data = image_buffer_ + (image_bytes_ * slot_n);
auto is_pulse_init = false;
auto is_good_image = true;