Program Listing for File cmem_buffer.cpp

Return to documentation for file (cmem_buffer.cpp)

#include <fstream>
#include <iostream>
#include <regex>
#include <cstdlib> // malloc/free
#include <cstdio>
#include <format>

#include "cmem_buffer.hpp"
#include "flxcard/FlxCard.h"

CmemBuffer::CmemBuffer(size_t mem_size, const std::string& cmem_name): DmaBuffer(mem_size), m_cmem_name(cmem_name) {

    try{
        m_cmem_driver.unlock_and_free_memory(cmem_name);
        ERS_INFO(std::format("Freeing previous CMEM buffer: {}", cmem_name));
    } catch (const std::exception &e){
        ERS_DEBUG(1, std::format("Found no CMEM buffers with name {} to reuse. exception: {} ", cmem_name, e.what()));
    }


    ERS_DEBUG(1, std::format("Allocating CMEM buffer {}", cmem_name.c_str()));

    // No try catch here, if things go wrong the application throws an error and terminates because the state is unrecoverable
    std::tie(paddr, vaddr) = m_cmem_driver.allocate_memory(mem_size, cmem_name);

    try{
        m_cmem_driver.lock_memory();
    } catch (const std::exception &e) {
        ers::warning(felix_log::cmem_buffer_issue("Failed locking memory -> ", e.what()));
    }
}


CmemBuffer::~CmemBuffer() {
    try {
        m_cmem_driver.unlock_memory();
    } catch (const std::exception &e) {
        ers::error(felix_log::cmem_buffer_issue("Failed unlocking memory -> ", e.what()));
    }
}


VmemBuffer::VmemBuffer(size_t mem_size) : DmaBuffer(mem_size) {
    ptr = malloc(mem_size);
    if (!ptr) {
        ers::error(felix_log::cmem_buffer_issue(std::format("Error vmem memory allocation of {} failed", mem_size)));
        throw std::runtime_error("Cannot allocate vmem buffer");
    }
    paddr = 0;
    vaddr = reinterpret_cast<uint64_t>(ptr);
}


VmemBuffer::~VmemBuffer() {
    if (vaddr) {
        free(ptr);
        vaddr = 0;
        ptr = 0;
    }
}