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
#pragma once
#include <atomic>
#include <memory>
#include <mutex>
#include "common/concurrent_vector.h"
#include "common/constants.h"
#include "common/types/types.h"
namespace lbug {
namespace storage {
// A VMRegion holds a virtual memory region of a certain size allocated through mmap.
// The region is divided into frame groups, each of which is a group of frames of the same size.
// Each FileHandle should grab a frame group each time when they add a new file page group (see
// `FileHandle::addNewPageGroupWithoutLock`). In this way, each file page group uniquely
// corresponds to a frame group, thus, a page also uniquely corresponds to a frame in a VMRegion.
class VMRegion {
friend class BufferManager;
public:
explicit VMRegion(common::PageSizeClass pageSizeClass, uint64_t maxRegionSize);
~VMRegion();
common::frame_group_idx_t addNewFrameGroup();
// Mark the frame as resident. Returns the number of bytes that should be charged to the
// buffer pool for this frame.
uint64_t claimFrame(common::frame_idx_t frameIdx);
// Use `MADV_DONTNEED` to release physical memory associated with this frame.
// Returns the number of bytes that should be released from the buffer pool accounting.
uint64_t releaseFrame(common::frame_idx_t frameIdx);
// Returns true if the memory address is within the reserved virtual memory region
bool contains(const uint8_t* address) const {
return address >= region && address < region + getMaxRegionSize();
}
inline uint8_t* getFrame(common::frame_idx_t frameIdx) const {
return region + (static_cast<std::uint64_t>(frameIdx) * frameSize);
}
private:
inline uint64_t getMaxRegionSize() const {
return maxNumFrameGroups * frameSize * common::StorageConstants::PAGE_GROUP_SIZE;
}
inline uint64_t getFrameGroupSize() const {
return static_cast<uint64_t>(frameSize) * common::StorageConstants::PAGE_GROUP_SIZE;
}
uint64_t getDiscardGranuleIdxInFrameGroup(common::frame_idx_t frameIdx) const;
uint64_t getFrameGroupIdx(common::frame_idx_t frameIdx) const;
private:
std::mutex mtx;
uint8_t* region;
uint32_t frameSize;
uint64_t discardGranuleSize;
uint64_t numDiscardGranulesPerFrameGroup;
std::atomic<uint64_t> numFrameGroups;
uint64_t maxNumFrameGroups;
// Grown under `mtx` but read without it by claimFrame/releaseFrame, which only index groups
// whose index was published to the caller after addNewFrameGroup returned. ConcurrentVector
// never moves or frees existing elements on growth, so those readers stay valid.
common::ConcurrentVector<std::unique_ptr<std::atomic<uint16_t>[]>>
residentFramesPerDiscardGranule;
};
} // namespace storage
} // namespace lbug