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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
use crate::{error::Result, table::TableId};
use parking_lot::{RwLock, RwLockUpgradableReadGuard};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
#[cfg(target_os = "linux")]
fn disable_read_ahead(file: &std::fs::File) -> Result<()> {
use std::os::unix::io::AsRawFd;
let err = unsafe { libc::posix_fadvise(file.as_raw_fd(), 0, 0, libc::POSIX_FADV_RANDOM) };
if err != 0 {
Err(std::io::Error::from_raw_os_error(err).into())
} else {
Ok(())
}
}
#[cfg(target_os = "macos")]
fn disable_read_ahead(file: &std::fs::File) -> Result<()> {
use std::os::unix::io::AsRawFd;
if unsafe { libc::fcntl(file.as_raw_fd(), libc::F_RDAHEAD, 0) } != 0 {
Err(std::io::Error::last_os_error().into())
} else {
Ok(())
}
}
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
fn disable_read_ahead(_file: &std::fs::File) -> Result<()> {
Ok(())
}
#[cfg(target_os = "macos")]
fn fsync(file: &std::fs::File) -> Result<()> {
use std::os::unix::io::AsRawFd;
if unsafe { libc::fsync(file.as_raw_fd()) } != 0 {
Err(std::io::Error::last_os_error().into())
} else {
Ok(())
}
}
#[cfg(not(target_os = "macos"))]
fn fsync(file: &std::fs::File) -> Result<()> {
file.sync_data()?;
Ok(())
}
const GROW_SIZE_BYTES: u64 = 256 * 1024;
pub struct TableFile {
pub file: RwLock<Option<std::fs::File>>,
pub path: std::path::PathBuf,
pub capacity: AtomicU64,
pub dirty: AtomicBool,
pub id: TableId,
}
impl TableFile {
pub fn open(filepath: std::path::PathBuf, entry_size: u16, id: TableId) -> Result<Self> {
let mut capacity = 0u64;
let file = if std::fs::metadata(&filepath).is_ok() {
let file = std::fs::OpenOptions::new()
.create(true)
.read(true)
.write(true)
.open(filepath.as_path())?;
disable_read_ahead(&file)?;
let len = file.metadata()?.len();
if len == 0 {
capacity += GROW_SIZE_BYTES / entry_size as u64;
file.set_len(capacity * entry_size as u64)?;
} else {
capacity = len / entry_size as u64;
}
Some(file)
} else {
None
};
Ok(TableFile {
path: filepath,
file: RwLock::new(file),
capacity: AtomicU64::new(capacity),
dirty: AtomicBool::new(false),
id,
})
}
fn create_file(&self) -> Result<std::fs::File> {
log::debug!(target: "parity-db", "Created value table {}", self.id);
let file = std::fs::OpenOptions::new()
.create(true)
.read(true)
.write(true)
.open(self.path.as_path())?;
disable_read_ahead(&file)?;
Ok(file)
}
#[cfg(unix)]
pub fn read_at(&self, buf: &mut [u8], offset: u64) -> Result<()> {
use std::os::unix::fs::FileExt;
Ok(self.file.read().as_ref().unwrap().read_exact_at(buf, offset)?)
}
#[cfg(unix)]
pub fn write_at(&self, buf: &[u8], offset: u64) -> Result<()> {
use std::os::unix::fs::FileExt;
self.dirty.store(true, Ordering::Relaxed);
self.file.read().as_ref().unwrap().write_all_at(buf, offset)?;
Ok(())
}
#[cfg(windows)]
pub fn read_at(&self, mut buf: &mut [u8], mut offset: u64) -> Result<()> {
use crate::error::Error;
use std::{io, os::windows::fs::FileExt};
let file = self.file.read();
let file = file.as_ref().unwrap();
while !buf.is_empty() {
match file.seek_read(buf, offset) {
Ok(0) => break,
Ok(n) => {
buf = &mut buf[n..];
offset += n as u64;
},
Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {
},
Err(e) => return Err(Error::Io(e)),
}
}
if !buf.is_empty() {
Err(Error::Io(io::Error::new(
io::ErrorKind::UnexpectedEof,
"failed to fill whole buffer",
)))
} else {
Ok(())
}
}
#[cfg(windows)]
pub fn write_at(&self, mut buf: &[u8], mut offset: u64) -> Result<()> {
use crate::error::Error;
use std::{io, os::windows::fs::FileExt};
self.dirty.store(true, Ordering::Relaxed);
let file = self.file.read();
let file = file.as_ref().unwrap();
while !buf.is_empty() {
match file.seek_write(buf, offset) {
Ok(0) =>
return Err(Error::Io(io::Error::new(
io::ErrorKind::WriteZero,
"failed to write whole buffer",
))),
Ok(n) => {
buf = &buf[n..];
offset += n as u64;
},
Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {
},
Err(e) => return Err(Error::Io(e)),
}
}
Ok(())
}
pub fn grow(&self, entry_size: u16) -> Result<()> {
let mut capacity = self.capacity.load(Ordering::Relaxed);
capacity += GROW_SIZE_BYTES / entry_size as u64;
self.capacity.store(capacity, Ordering::Relaxed);
let mut file = self.file.upgradable_read();
if file.is_none() {
let mut wfile = RwLockUpgradableReadGuard::upgrade(file);
*wfile = Some(self.create_file()?);
file = parking_lot::RwLockWriteGuard::downgrade_to_upgradable(wfile);
}
file.as_ref().unwrap().set_len(capacity * entry_size as u64)?;
Ok(())
}
pub fn flush(&self) -> Result<()> {
if let Ok(true) =
self.dirty.compare_exchange(true, false, Ordering::Relaxed, Ordering::Relaxed)
{
if let Some(file) = self.file.read().as_ref() {
fsync(file)?;
}
}
Ok(())
}
}