2016-04-14 13:24:32 +05:30
|
|
|
#include "block-cache/mem_pool.h"
|
|
|
|
|
2016-05-07 16:17:40 +05:30
|
|
|
#include <sstream>
|
|
|
|
#include <stdexcept>
|
2016-04-14 13:24:32 +05:30
|
|
|
#include <stdlib.h>
|
|
|
|
|
|
|
|
using namespace bcache;
|
|
|
|
using namespace boost;
|
|
|
|
using namespace mempool_detail;
|
2016-05-07 16:17:40 +05:30
|
|
|
using namespace std;
|
2016-04-14 13:24:32 +05:30
|
|
|
|
|
|
|
//----------------------------------------------------------------
|
|
|
|
|
2016-05-07 16:17:40 +05:30
|
|
|
mempool::mempool(size_t block_size, size_t total_mem, size_t alignment)
|
2016-04-14 13:24:32 +05:30
|
|
|
{
|
2016-05-07 16:17:40 +05:30
|
|
|
mem_ = alloc_aligned(total_mem, alignment);
|
2016-04-14 13:24:32 +05:30
|
|
|
|
|
|
|
unsigned nr_blocks = total_mem / block_size;
|
|
|
|
for (auto i = 0u; i < nr_blocks; i++)
|
|
|
|
free(static_cast<unsigned char *>(mem_) + (block_size * i));
|
|
|
|
}
|
|
|
|
|
|
|
|
mempool::~mempool()
|
|
|
|
{
|
2016-05-07 16:17:40 +05:30
|
|
|
free_.clear();
|
2016-04-14 13:24:32 +05:30
|
|
|
::free(mem_);
|
|
|
|
}
|
|
|
|
|
2016-06-01 19:16:27 +05:30
|
|
|
void *
|
2016-04-14 13:24:32 +05:30
|
|
|
mempool::alloc()
|
|
|
|
{
|
|
|
|
if (free_.empty())
|
2016-06-01 19:16:27 +05:30
|
|
|
return nullptr;
|
2016-04-14 13:24:32 +05:30
|
|
|
|
|
|
|
mempool_detail::alloc_block &b = free_.front();
|
|
|
|
free_.pop_front();
|
2016-06-01 19:16:27 +05:30
|
|
|
return reinterpret_cast<void *>(&b);
|
2016-04-14 13:24:32 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
void
|
|
|
|
mempool::free(void *data)
|
|
|
|
{
|
|
|
|
mempool_detail::alloc_block *b = reinterpret_cast<mempool_detail::alloc_block *>(data);
|
|
|
|
free_.push_front(*b);
|
|
|
|
}
|
|
|
|
|
|
|
|
void *
|
|
|
|
mempool::alloc_aligned(size_t len, size_t alignment)
|
|
|
|
{
|
|
|
|
void *result = NULL;
|
|
|
|
int r = posix_memalign(&result, alignment, len);
|
2016-05-07 16:17:40 +05:30
|
|
|
if (r) {
|
|
|
|
ostringstream out;
|
|
|
|
out << "posix_memalign failed: len = " << len << ", alignment = " << alignment << ", r = " << r << "\n";
|
|
|
|
throw runtime_error(out.str());
|
|
|
|
}
|
2016-04-14 13:24:32 +05:30
|
|
|
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
//----------------------------------------------------------------
|
|
|
|
|