Skip to content

Commit a31e203

Browse files
committed
disklayer_sqlite: Commit the cache flush transaction
Commit the WAL transaction with synchronous set to FULL. The transaction was previously rolled back on drop, so sync_cache could return success without syncing cached writes. Start writable connections in NORMAL mode to avoid a WAL sync on ordinary writes. Commit FUA writes in FULL mode so callers can rely on their durability. Restore the original mode after a flush or FUA write, even if the transaction fails. Test initialization on new and reopened disks. Verify that flushes and FUA writes commit in FULL mode and that ordinary writes commit in NORMAL mode. Check that commit errors propagate and the mode is restored. Signed-off-by: Anatol Belski <anbelski@linux.microsoft.com>
1 parent 66bdba0 commit a31e203

3 files changed

Lines changed: 208 additions & 13 deletions

File tree

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1869,6 +1869,7 @@ dependencies = [
18691869
"serde_json",
18701870
"storage_tests",
18711871
"tempfile",
1872+
"test_with_tracing",
18721873
"tracing",
18731874
"vm_resource",
18741875
]

‎vm/devices/storage/disklayer_sqlite/Cargo.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,9 @@ tracing.workspace = true
3737

3838
[dev-dependencies]
3939
pal_async.workspace = true
40+
rusqlite = { workspace = true, features = ["hooks"] }
4041
storage_tests.workspace = true
42+
test_with_tracing.workspace = true
4143

4244
# Building SQLite from source needs a C toolchain for the target, which the
4345
# macOS cross-compile lint job does not have. That job only lints and never

‎vm/devices/storage/disklayer_sqlite/src/lib.rs‎

Lines changed: 205 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
//!
66
//! At this time, **this layer is only designed for use in dev/test scenarios!**
77
//!
8+
//! Writes that request Force Unit Access (FUA) are synced before they complete.
9+
//!
810
//! # DISCLAIMER: Stability
911
//!
1012
//! There are no stability guarantees around the on-disk data format! The schema
@@ -224,6 +226,10 @@ impl SqliteDiskLayer {
224226
serde_json::from_str(&data)?
225227
};
226228

229+
if !read_only {
230+
conn.pragma_update(None, "synchronous", "NORMAL")?;
231+
}
232+
227233
Ok(SqliteDiskLayer {
228234
conn: Arc::new(Mutex::new(conn)),
229235
meta,
@@ -235,6 +241,7 @@ impl SqliteDiskLayer {
235241
buffers: &RequestBuffers<'_>,
236242
sector: u64,
237243
overwrite: bool,
244+
fua: bool,
238245
) -> Result<(), DiskError> {
239246
assert!(!(overwrite && self.meta.logically_read_only));
240247

@@ -249,9 +256,18 @@ impl SqliteDiskLayer {
249256

250257
let buf = buffers.reader().read_all()?;
251258
unblock({
252-
let conn = self.conn.clone().lock_owned().await;
259+
let mut conn = self.conn.clone().lock_owned().await;
253260
let sector_size = self.meta.sector_size;
254-
move || write_sectors(conn, sector_size, sector, buf, overwrite)
261+
move || {
262+
let write = |conn: &mut Connection| {
263+
write_sectors(conn, sector_size, sector, buf, overwrite)
264+
};
265+
if fua {
266+
with_full_synchronous(&mut conn, write)
267+
} else {
268+
write(&mut conn)
269+
}
270+
}
255271
})
256272
.await
257273
.map_err(|e| DiskError::Io(std::io::Error::other(e)))?;
@@ -318,7 +334,7 @@ impl LayerIo for SqliteDiskLayer {
318334
}
319335

320336
fn is_fua_respected(&self) -> bool {
321-
false
337+
true
322338
}
323339

324340
async fn read(
@@ -362,9 +378,9 @@ impl LayerIo for SqliteDiskLayer {
362378
&self,
363379
buffers: &RequestBuffers<'_>,
364380
sector: u64,
365-
_fua: bool,
381+
fua: bool,
366382
) -> Result<(), DiskError> {
367-
self.write_maybe_overwrite(buffers, sector, true).await
383+
self.write_maybe_overwrite(buffers, sector, true, fua).await
368384
}
369385

370386
fn write_no_overwrite(&self) -> Option<impl WriteNoOverwrite> {
@@ -376,15 +392,13 @@ impl LayerIo for SqliteDiskLayer {
376392

377393
unblock({
378394
let mut conn = self.conn.clone().lock_owned().await;
379-
move || -> rusqlite::Result<()> {
395+
move || {
380396
// https://sqlite-users.sqlite.narkive.com/LX75NOma/forcing-a-manual-fsync-in-wal-normal-mode
381-
conn.pragma_update(None, "synchronous", "FULL")?;
382-
{
397+
with_full_synchronous(&mut conn, |conn| {
383398
let tx = conn.transaction()?;
384399
tx.pragma_update(None, "user_version", "0")?;
385-
}
386-
conn.pragma_update(None, "synchronous", "NORMAL")?;
387-
Ok(())
400+
tx.commit()
401+
})
388402
}
389403
})
390404
.await
@@ -428,7 +442,8 @@ impl WriteNoOverwrite for SqliteDiskLayer {
428442
buffers: &RequestBuffers<'_>,
429443
sector: u64,
430444
) -> Result<(), DiskError> {
431-
self.write_maybe_overwrite(buffers, sector, false).await
445+
self.write_maybe_overwrite(buffers, sector, false, false)
446+
.await
432447
}
433448
}
434449

@@ -475,9 +490,20 @@ fn read_sectors(
475490
Ok(res)
476491
}
477492

493+
fn with_full_synchronous(
494+
conn: &mut Connection,
495+
operation: impl FnOnce(&mut Connection) -> rusqlite::Result<()>,
496+
) -> rusqlite::Result<()> {
497+
let previous_mode: u32 = conn.pragma_query_value(None, "synchronous", |row| row.get(0))?;
498+
conn.pragma_update(None, "synchronous", "FULL")?;
499+
let result = operation(conn);
500+
let restore_result = conn.pragma_update(None, "synchronous", previous_mode);
501+
result.and(restore_result)
502+
}
503+
478504
// FUTURE: write into sqlite directly from `RequestBuffers`.
479505
fn write_sectors(
480-
mut conn: OwnedMutexGuard<Connection>,
506+
conn: &mut Connection,
481507
sector_size: u32,
482508
mut sector: u64,
483509
buf: Vec<u8>,
@@ -585,10 +611,23 @@ mod tests {
585611
use crate::FormatParams;
586612
use crate::SqliteDiskLayer;
587613
use disk_backend::Disk;
614+
use disk_backend::DiskError;
588615
use disk_layered::DiskLayer;
589616
use disk_layered::LayerConfiguration;
617+
use disk_layered::LayerIo;
590618
use disk_layered::LayeredDisk;
619+
use guestmem::GuestMemory;
591620
use pal_async::async_test;
621+
use rusqlite::Connection;
622+
use rusqlite::hooks::AuthAction;
623+
use rusqlite::hooks::AuthContext;
624+
use rusqlite::hooks::Authorization;
625+
use scsi_buffers::OwnedRequestBuffers;
626+
use std::sync::Arc;
627+
use std::sync::atomic::AtomicBool;
628+
use std::sync::atomic::AtomicU8;
629+
use std::sync::atomic::Ordering;
630+
use test_with_tracing::test;
592631

593632
const SECTOR_SIZE: u32 = 512;
594633
const DISK_SIZE: u64 = 1024 * 1024;
@@ -632,4 +671,157 @@ mod tests {
632671
let dir = tempfile::tempdir().unwrap();
633672
storage_tests::sector_range::test_layer_sector_range(&new_layer(&dir)).await;
634673
}
674+
675+
#[async_test]
676+
async fn writable_connection_starts_in_normal_mode() {
677+
let dir = tempfile::tempdir().unwrap();
678+
let layer = new_layer(&dir);
679+
for layer in [
680+
layer,
681+
SqliteDiskLayer::new(&dir.path().join("test.dbhd"), false, None).unwrap(),
682+
] {
683+
let mode: u32 = layer
684+
.conn
685+
.lock()
686+
.await
687+
.pragma_query_value(None, "synchronous", |row| row.get(0))
688+
.unwrap();
689+
assert_eq!(mode, 1, "expected synchronous=NORMAL");
690+
}
691+
}
692+
693+
fn track_synchronous_full(conn: &Connection) -> Arc<AtomicBool> {
694+
let synchronous_full = Arc::new(AtomicBool::new(false));
695+
let mode = synchronous_full.clone();
696+
// The commit hook cannot query the connection. Track mode changes
697+
// through the authorizer as SQLite prepares each PRAGMA assignment.
698+
conn.authorizer(Some(move |ctx: AuthContext<'_>| {
699+
if let AuthAction::Pragma {
700+
pragma_name,
701+
pragma_value: Some(value),
702+
} = ctx.action
703+
&& pragma_name.eq_ignore_ascii_case("synchronous")
704+
{
705+
mode.store(
706+
value.eq_ignore_ascii_case("FULL") || value == "2",
707+
Ordering::Relaxed,
708+
);
709+
}
710+
Authorization::Allow
711+
}));
712+
synchronous_full
713+
}
714+
715+
#[async_test]
716+
async fn fua_writes_commit_in_full_and_restore_normal() {
717+
let dir = tempfile::tempdir().unwrap();
718+
let layer = new_layer(&dir);
719+
let synchronous_full = track_synchronous_full(&*layer.conn.lock().await);
720+
let mem = GuestMemory::allocate(SECTOR_SIZE as usize);
721+
let buffers = OwnedRequestBuffers::linear(0, SECTOR_SIZE as usize, false);
722+
mem.write_at(0, &[0xa5; SECTOR_SIZE as usize]).unwrap();
723+
724+
for (fua, reject_commit) in [(true, false), (true, true), (false, false)] {
725+
let observed_mode = Arc::new(AtomicU8::new(0));
726+
let observed = observed_mode.clone();
727+
let mode = synchronous_full.clone();
728+
layer.conn.lock().await.commit_hook(Some(move || {
729+
observed.store(
730+
if mode.load(Ordering::Relaxed) { 2 } else { 1 },
731+
Ordering::Relaxed,
732+
);
733+
reject_commit
734+
}));
735+
736+
let result = layer.write(&buffers.buffer(&mem), 7, fua).await;
737+
if reject_commit {
738+
assert!(matches!(result, Err(DiskError::Io(_))));
739+
} else {
740+
result.unwrap();
741+
}
742+
assert_eq!(
743+
observed_mode.load(Ordering::Relaxed),
744+
if fua { 2 } else { 1 },
745+
"unexpected synchronous mode at commit"
746+
);
747+
748+
let mode: u32 = layer
749+
.conn
750+
.lock()
751+
.await
752+
.pragma_query_value(None, "synchronous", |row| row.get(0))
753+
.unwrap();
754+
assert_eq!(mode, 1, "expected synchronous=NORMAL after write");
755+
}
756+
}
757+
758+
#[async_test]
759+
async fn sync_cache_commits_wal_transaction() {
760+
let dir = tempfile::tempdir().unwrap();
761+
let layer = new_layer(&dir);
762+
let synchronous_full = track_synchronous_full(&*layer.conn.lock().await);
763+
let observer = Connection::open(dir.path().join("test.dbhd")).unwrap();
764+
let mem = GuestMemory::allocate(SECTOR_SIZE as usize);
765+
let buffers = OwnedRequestBuffers::linear(0, SECTOR_SIZE as usize, false);
766+
767+
for pattern in [0x5a, 0xa5] {
768+
mem.write_at(0, &[pattern; SECTOR_SIZE as usize]).unwrap();
769+
layer.write(&buffers.buffer(&mem), 7, false).await.unwrap();
770+
let before: u32 = observer
771+
.pragma_query_value(None, "data_version", |row| row.get(0))
772+
.unwrap();
773+
774+
let synchronous_full = synchronous_full.clone();
775+
layer
776+
.conn
777+
.lock()
778+
.await
779+
.commit_hook(Some(move || !synchronous_full.load(Ordering::Relaxed)));
780+
layer
781+
.sync_cache()
782+
.await
783+
.expect("cache flush must commit with synchronous=FULL");
784+
layer.conn.lock().await.commit_hook(None::<fn() -> bool>);
785+
786+
let after: u32 = observer
787+
.pragma_query_value(None, "data_version", |row| row.get(0))
788+
.unwrap();
789+
assert_ne!(
790+
before, after,
791+
"cache flush did not commit a WAL transaction"
792+
);
793+
}
794+
}
795+
796+
#[async_test]
797+
async fn sync_cache_reports_commit_error() {
798+
let dir = tempfile::tempdir().unwrap();
799+
let layer = new_layer(&dir);
800+
for (mode, expected) in [("NORMAL", 1), ("FULL", 2)] {
801+
{
802+
let conn = layer.conn.lock().await;
803+
conn.pragma_update(None, "synchronous", mode).unwrap();
804+
conn.commit_hook(Some(|| true));
805+
}
806+
807+
assert!(matches!(layer.sync_cache().await, Err(DiskError::Io(_))));
808+
809+
layer.conn.lock().await.commit_hook(None::<fn() -> bool>);
810+
for flush_succeeded in [false, true] {
811+
if flush_succeeded {
812+
layer.sync_cache().await.unwrap();
813+
}
814+
let synchronous: u32 = layer
815+
.conn
816+
.lock()
817+
.await
818+
.pragma_query_value(None, "synchronous", |row| row.get(0))
819+
.unwrap();
820+
assert_eq!(
821+
synchronous, expected,
822+
"expected synchronous={mode} after flush (success={flush_succeeded})"
823+
);
824+
}
825+
}
826+
}
635827
}

0 commit comments

Comments
 (0)