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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
use crate::memory_fs::allocator::{AllocatedChunk, CHUNKS_ALLOCATOR};
use crate::memory_fs::file::flush::GlobalFlush;
use crate::memory_fs::flushable_buffer::{FileFlushMode, FlushableItem};
use dashmap::DashMap;
use filebuffer::FileBuffer;
use lazy_static::lazy_static;
use nightly_quirks::utils::NightlyUtils;
use parking_lot::lock_api::{ArcRwLockReadGuard, ArcRwLockWriteGuard, RawMutex};
use parking_lot::{Mutex, RawRwLock, RwLock, RwLockReadGuard};
use replace_with::replace_with_or_abort;
use std::cmp::min;
use std::collections::BTreeMap;
use std::fs::{remove_file, File, OpenOptions};
use std::io::Write;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Weak};
lazy_static! {
static ref MEMORY_MAPPED_FILES: DashMap<PathBuf, Arc<RwLock<MemoryFileInternal>>> =
DashMap::new();
}
pub static SWAPPABLE_FILES: Mutex<
Option<BTreeMap<(usize, PathBuf), Weak<RwLock<MemoryFileInternal>>>>,
> = Mutex::const_new(parking_lot::RawMutex::INIT, None);
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum MemoryFileMode {
AlwaysMemory,
PreferMemory { swap_priority: usize },
DiskOnly,
}
#[derive(Copy, Clone, Eq, PartialEq)]
pub enum OpenMode {
None,
Read,
Write,
}
struct RwLockIterator<'a, A, B, I: Iterator<Item = B>> {
_lock: RwLockReadGuard<'a, A>,
iterator: I,
}
impl<'a, A, B, I: Iterator<Item = B>> Iterator for RwLockIterator<'a, A, B, I> {
type Item = B;
fn next(&mut self) -> Option<Self::Item> {
self.iterator.next()
}
}
pub struct MemoryFileChunksIterator<'a, I: Iterator<Item = &'a mut [u8]>> {
iter: I,
}
impl<'a, I: Iterator<Item = &'a mut [u8]>> Iterator for MemoryFileChunksIterator<'a, I> {
type Item = &'a mut [u8];
#[inline(always)]
fn next(&mut self) -> Option<Self::Item> {
self.iter.next()
}
}
pub enum FileChunk {
OnDisk { offset: u64, len: usize },
OnMemory { chunk: AllocatedChunk },
}
impl FileChunk {
pub fn get_length(&self) -> usize {
match self {
FileChunk::OnDisk { len, .. } => *len,
FileChunk::OnMemory { chunk } => chunk.len(),
}
}
#[inline(always)]
pub fn get_ptr(&self, file: &UnderlyingFile, prefetch: Option<usize>) -> *const u8 {
unsafe {
match self {
FileChunk::OnDisk { offset, .. } => {
if let UnderlyingFile::ReadMode(file) = file {
let file = file.as_ref().unwrap();
if let Some(prefetch) = prefetch {
let remaining_length = file.len() - *offset as usize;
let prefetch_length = min(remaining_length, prefetch);
file.prefetch(*offset as usize, prefetch_length);
}
file.as_ptr().add(*offset as usize)
} else {
panic!("Error, wrong underlying file!");
}
}
FileChunk::OnMemory { chunk } => chunk.get_mut_ptr() as *const u8,
}
}
}
}
pub enum UnderlyingFile {
NotOpened,
MemoryOnly,
MemoryPreferred,
WriteMode {
file: Arc<(PathBuf, Mutex<File>)>,
chunk_position: usize,
},
ReadMode(Option<FileBuffer>),
}
pub struct MemoryFileInternal {
path: PathBuf,
file: UnderlyingFile,
memory_mode: MemoryFileMode,
open_mode: (OpenMode, usize),
memory: Vec<Arc<RwLock<FileChunk>>>,
on_swap_list: AtomicBool,
can_flush: bool,
}
impl MemoryFileInternal {
pub fn create_new(path: impl AsRef<Path>, memory_mode: MemoryFileMode) -> Arc<RwLock<Self>> {
let new_file = Arc::new(RwLock::new(Self {
path: path.as_ref().into(),
file: UnderlyingFile::NotOpened,
memory_mode,
open_mode: (OpenMode::None, 0),
memory: Vec::new(),
on_swap_list: AtomicBool::new(false),
can_flush: true,
}));
MEMORY_MAPPED_FILES.insert(path.as_ref().into(), new_file.clone());
new_file
}
pub fn create_from_fs(path: impl AsRef<Path>) -> Option<Arc<RwLock<Self>>> {
if !path.as_ref().exists() || !path.as_ref().is_file() {
return None;
}
let len = path.as_ref().metadata().ok()?.len() as usize;
let new_file = Arc::new(RwLock::new(Self {
path: path.as_ref().into(),
file: UnderlyingFile::NotOpened,
memory_mode: MemoryFileMode::DiskOnly,
open_mode: (OpenMode::None, 0),
memory: vec![Arc::new(RwLock::new(FileChunk::OnDisk { offset: 0, len }))],
on_swap_list: AtomicBool::new(false),
can_flush: false,
}));
MEMORY_MAPPED_FILES.insert(path.as_ref().into(), new_file.clone());
Some(new_file)
}
pub fn debug_dump_files() {
for file in MEMORY_MAPPED_FILES.iter() {
let file = file.read();
println!(
"File '{}' => chunks: {}",
file.path.display(),
file.memory.len()
);
}
}
pub fn is_on_disk(&self) -> bool {
self.memory_mode == MemoryFileMode::DiskOnly
}
pub fn is_memory_preferred(&self) -> bool {
if let MemoryFileMode::PreferMemory { .. } = self.memory_mode {
true
} else {
false
}
}
pub fn get_chunk(&self, index: usize) -> Arc<RwLock<FileChunk>> {
self.memory[index].clone()
}
pub fn get_chunks_count(&self) -> usize {
self.memory.len()
}
pub fn retrieve_reference(path: impl AsRef<Path>) -> Option<Arc<RwLock<Self>>> {
MEMORY_MAPPED_FILES.get(path.as_ref()).map(|f| f.clone())
}
pub fn active_files_count() -> usize {
MEMORY_MAPPED_FILES.len()
}
pub fn delete(path: impl AsRef<Path>, remove_fs: bool) -> bool {
if let Some(file) = MEMORY_MAPPED_FILES.remove(path.as_ref()) {
if remove_fs {
match file.1.read().memory_mode {
MemoryFileMode::AlwaysMemory => {}
MemoryFileMode::PreferMemory { swap_priority } => {
NightlyUtils::mutex_get_or_init(&mut SWAPPABLE_FILES.lock(), || {
BTreeMap::new()
})
.remove(&(swap_priority, path.as_ref().to_path_buf()));
}
MemoryFileMode::DiskOnly => {
let _ = remove_file(path);
}
}
}
true
} else {
false
}
}
fn create_writing_underlying_file(path: &Path) -> UnderlyingFile {
let _ = remove_file(path);
UnderlyingFile::WriteMode {
file: Arc::new((
path.to_path_buf(),
Mutex::new(
OpenOptions::new()
.create(true)
.write(true)
.append(false)
.open(path)
.unwrap(),
),
)),
chunk_position: 0,
}
}
pub fn open(&mut self, mode: OpenMode) -> Result<(), String> {
if self.open_mode.0 == mode {
self.open_mode.1 += 1;
return Ok(());
}
if self.open_mode.0 != OpenMode::None {
return Err(format!("File {} is already opened!", self.path.display()));
}
{
replace_with_or_abort(&mut self.file, |file| {
match mode {
OpenMode::None => UnderlyingFile::NotOpened,
OpenMode::Read => {
self.open_mode = (OpenMode::Read, 1);
self.can_flush = false;
if self.memory_mode != MemoryFileMode::DiskOnly {
UnderlyingFile::MemoryOnly
} else {
for chunk in self.memory.iter() {
drop(chunk.read());
}
if let UnderlyingFile::WriteMode { file, .. } = file {
file.1.lock().flush().unwrap();
}
UnderlyingFile::ReadMode(FileBuffer::open(&self.path).ok())
}
}
OpenMode::Write => {
self.open_mode = (OpenMode::Write, 1);
match self.memory_mode {
MemoryFileMode::AlwaysMemory => UnderlyingFile::MemoryOnly,
MemoryFileMode::PreferMemory { .. } => UnderlyingFile::MemoryPreferred,
MemoryFileMode::DiskOnly => {
Self::create_writing_underlying_file(&self.path)
}
}
}
}
});
}
Ok(())
}
pub fn close(&mut self) {
self.open_mode.1 -= 1;
if self.open_mode.1 == 0 {
self.open_mode.0 = OpenMode::None;
match &self.file {
UnderlyingFile::WriteMode { file, .. } => {
file.1.lock().flush().unwrap();
}
_ => {}
}
}
}
fn put_on_swappable_list(self_: &ArcRwLockWriteGuard<RawRwLock, Self>) {
if let MemoryFileMode::PreferMemory { swap_priority } = self_.memory_mode {
if !self_.on_swap_list.swap(true, Ordering::Relaxed) {
NightlyUtils::mutex_get_or_init(&mut SWAPPABLE_FILES.lock(), || BTreeMap::new())
.insert(
(swap_priority, self_.path.clone()),
Arc::downgrade(ArcRwLockWriteGuard::rwlock(self_)),
);
}
}
}
pub fn reserve_space(
self_: &Arc<RwLock<Self>>,
last_chunk: AllocatedChunk,
out_chunks: &mut Vec<(Option<ArcRwLockReadGuard<RawRwLock, FileChunk>>, &mut [u8])>,
mut size: usize,
el_size: usize,
) -> AllocatedChunk {
let mut chunk = last_chunk;
loop {
let rem_bytes = chunk.remaining_bytes();
let rem_elements = rem_bytes / el_size;
let el_bytes = min(size, rem_elements * el_size);
assert!(chunk.max_len() >= el_size);
let space = if el_bytes > 0 {
Some(unsafe { chunk.prealloc_bytes_single_thread(el_bytes) })
} else {
None
};
size -= el_bytes;
let mut self_ = self_.write_arc();
if size > 0 {
self_
.memory
.push(Arc::new(RwLock::new(FileChunk::OnMemory { chunk })));
if let Some(space) = space {
let chunk_guard = self_.memory.last().unwrap().read_arc();
out_chunks.push((Some(chunk_guard), space));
}
Self::put_on_swappable_list(&self_);
chunk = CHUNKS_ALLOCATOR.request_chunk(chunk_usage!(FileBuffer {
path: std::panic::Location::caller().to_string()
}));
} else {
if let Some(space) = space {
out_chunks.push((None, space));
}
return chunk;
}
}
}
pub fn get_underlying_file(&self) -> &UnderlyingFile {
&self.file
}
pub fn add_chunk(self_: &Arc<RwLock<Self>>, chunk: AllocatedChunk) {
let mut self_ = self_.write_arc();
self_
.memory
.push(Arc::new(RwLock::new(FileChunk::OnMemory { chunk })));
Self::put_on_swappable_list(&self_);
}
pub fn flush_chunks(&mut self, limit: usize) -> usize {
if !self.can_flush {
return 0;
}
match &self.file {
UnderlyingFile::NotOpened | UnderlyingFile::MemoryPreferred => {
self.file = Self::create_writing_underlying_file(&self.path);
}
_ => {}
}
if let UnderlyingFile::WriteMode {
file,
chunk_position,
} = &mut self.file
{
{
let mut flushed_count = 0;
while flushed_count < limit {
if *chunk_position >= self.memory.len() {
return flushed_count;
}
if let Some(flushable_chunk) = self.memory[*chunk_position].try_write_arc() {
GlobalFlush::add_item_to_flush_queue(FlushableItem {
underlying_file: file.clone(),
mode: FileFlushMode::Append {
chunk: flushable_chunk,
},
});
*chunk_position += 1;
flushed_count += 1;
} else {
return flushed_count;
}
}
return flushed_count;
}
}
return 0;
}
pub fn flush_pending_chunks_count(&self) -> usize {
match &self.file {
UnderlyingFile::NotOpened
| UnderlyingFile::MemoryOnly
| UnderlyingFile::ReadMode(_) => 0,
UnderlyingFile::WriteMode { chunk_position, .. } => {
self.get_chunks_count() - *chunk_position
}
UnderlyingFile::MemoryPreferred => self.get_chunks_count(),
}
}
#[inline(always)]
pub fn has_flush_pending_chunks(&self) -> bool {
self.flush_pending_chunks_count() > 0
}
pub fn change_to_disk_only(&mut self) {
if self.is_memory_preferred() {
self.memory_mode = MemoryFileMode::DiskOnly;
self.file = Self::create_writing_underlying_file(&self.path);
}
}
#[inline(always)]
pub fn has_only_one_chunk(&self) -> bool {
self.memory.len() == 1
}
#[inline(always)]
pub fn get_path(&self) -> &Path {
self.path.as_ref()
}
#[inline(always)]
pub fn len(&self) -> usize {
self.memory
.iter()
.map(|x| match x.read().deref() {
FileChunk::OnDisk { len, .. } => *len,
FileChunk::OnMemory { chunk } => chunk.len(),
})
.sum::<usize>()
}
}
unsafe impl Sync for MemoryFileInternal {}
unsafe impl Send for MemoryFileInternal {}