1 | // SPDX-License-Identifier: GPL-3.0-or-later |
2 | |
3 | #include "ramdisk.hpp" |
4 | |
5 | #include <abi-bits/vm-flags.h> |
6 | #include <string.h> |
7 | #include <sys/mman.h> |
8 | |
9 | RAMDisk::RAMDisk(const size_t nbytes) : m_nbytes(nbytes), m_nblocks(nbytes / BLOCKDEV_BLOCK_SIZE) |
10 | { |
11 | m_data = (uint8_t *) mmap(NULL, nbytes, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); |
12 | } |
13 | |
14 | RAMDisk::~RAMDisk() |
15 | { |
16 | munmap(m_data, m_nbytes); |
17 | } |
18 | |
19 | size_t RAMDisk::read_block(const size_t block, const size_t nblocks, uint8_t *buf) |
20 | { |
21 | if (block + nblocks > m_nblocks) |
22 | return 0; |
23 | |
24 | memcpy(dest: buf, src: m_data + block * BLOCKDEV_BLOCK_SIZE, size: nblocks * BLOCKDEV_BLOCK_SIZE); |
25 | return nblocks; |
26 | } |
27 | |
28 | size_t RAMDisk::write_block(const size_t block, const size_t nblocks, const uint8_t *buf) |
29 | { |
30 | if (block + nblocks > m_nblocks) |
31 | return 0; |
32 | |
33 | memcpy(dest: m_data + block * BLOCKDEV_BLOCK_SIZE, src: buf, size: nblocks * BLOCKDEV_BLOCK_SIZE); |
34 | return nblocks; |
35 | } |
36 | |