Skip to content

Commit fc0aaeb

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 FULL mode because some frontends do not set FUA when their write cache is disabled. Also use FULL for explicit FUA writes and flushes. Restore the original mode even if the transaction fails. Test initialization on new and reopened disks. Verify that flushes and FUA writes commit in FULL mode even when starting in NORMAL. Check that commit errors propagate and the original mode is restored. Signed-off-by: Anatol Belski <anbelski@linux.microsoft.com>
1 parent 66bdba0 commit fc0aaeb

3 files changed

Lines changed: 213 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: 210 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@
55
//!
66
//! At this time, **this layer is only designed for use in dev/test scenarios!**
77
//!
8+
//! Writable connections use full synchronization, including for writes that
9+
//! do not request Force Unit Access (FUA).
10+
//!
811
//! # DISCLAIMER: Stability
912
//!
1013
//! There are no stability guarantees around the on-disk data format! The schema
@@ -224,6 +227,11 @@ impl SqliteDiskLayer {
224227
serde_json::from_str(&data)?
225228
};
226229

230+
if !read_only {
231+
// Some frontends do not set FUA when their write cache is disabled.
232+
conn.pragma_update(None, "synchronous", "FULL")?;
233+
}
234+
227235
Ok(SqliteDiskLayer {
228236
conn: Arc::new(Mutex::new(conn)),
229237
meta,
@@ -235,6 +243,7 @@ impl SqliteDiskLayer {
235243
buffers: &RequestBuffers<'_>,
236244
sector: u64,
237245
overwrite: bool,
246+
fua: bool,
238247
) -> Result<(), DiskError> {
239248
assert!(!(overwrite && self.meta.logically_read_only));
240249

@@ -249,9 +258,18 @@ impl SqliteDiskLayer {
249258

250259
let buf = buffers.reader().read_all()?;
251260
unblock({
252-
let conn = self.conn.clone().lock_owned().await;
261+
let mut conn = self.conn.clone().lock_owned().await;
253262
let sector_size = self.meta.sector_size;
254-
move || write_sectors(conn, sector_size, sector, buf, overwrite)
263+
move || {
264+
let write = |conn: &mut Connection| {
265+
write_sectors(conn, sector_size, sector, buf, overwrite)
266+
};
267+
if fua {
268+
with_full_synchronous(&mut conn, write)
269+
} else {
270+
write(&mut conn)
271+
}
272+
}
255273
})
256274
.await
257275
.map_err(|e| DiskError::Io(std::io::Error::other(e)))?;
@@ -318,7 +336,7 @@ impl LayerIo for SqliteDiskLayer {
318336
}
319337

320338
fn is_fua_respected(&self) -> bool {
321-
false
339+
true
322340
}
323341

324342
async fn read(
@@ -362,9 +380,9 @@ impl LayerIo for SqliteDiskLayer {
362380
&self,
363381
buffers: &RequestBuffers<'_>,
364382
sector: u64,
365-
_fua: bool,
383+
fua: bool,
366384
) -> Result<(), DiskError> {
367-
self.write_maybe_overwrite(buffers, sector, true).await
385+
self.write_maybe_overwrite(buffers, sector, true, fua).await
368386
}
369387

370388
fn write_no_overwrite(&self) -> Option<impl WriteNoOverwrite> {
@@ -376,15 +394,13 @@ impl LayerIo for SqliteDiskLayer {
376394

377395
unblock({
378396
let mut conn = self.conn.clone().lock_owned().await;
379-
move || -> rusqlite::Result<()> {
397+
move || {
380398
// https://sqlite-users.sqlite.narkive.com/LX75NOma/forcing-a-manual-fsync-in-wal-normal-mode
381-
conn.pragma_update(None, "synchronous", "FULL")?;
382-
{
399+
with_full_synchronous(&mut conn, |conn| {
383400
let tx = conn.transaction()?;
384401
tx.pragma_update(None, "user_version", "0")?;
385-
}
386-
conn.pragma_update(None, "synchronous", "NORMAL")?;
387-
Ok(())
402+
tx.commit()
403+
})
388404
}
389405
})
390406
.await
@@ -428,7 +444,8 @@ impl WriteNoOverwrite for SqliteDiskLayer {
428444
buffers: &RequestBuffers<'_>,
429445
sector: u64,
430446
) -> Result<(), DiskError> {
431-
self.write_maybe_overwrite(buffers, sector, false).await
447+
self.write_maybe_overwrite(buffers, sector, false, false)
448+
.await
432449
}
433450
}
434451

@@ -475,9 +492,20 @@ fn read_sectors(
475492
Ok(res)
476493
}
477494

495+
fn with_full_synchronous(
496+
conn: &mut Connection,
497+
operation: impl FnOnce(&mut Connection) -> rusqlite::Result<()>,
498+
) -> rusqlite::Result<()> {
499+
let previous_mode: u32 = conn.pragma_query_value(None, "synchronous", |row| row.get(0))?;
500+
conn.pragma_update(None, "synchronous", "FULL")?;
501+
let result = operation(conn);
502+
let restore_result = conn.pragma_update(None, "synchronous", previous_mode);
503+
result.and(restore_result)
504+
}
505+
478506
// FUTURE: write into sqlite directly from `RequestBuffers`.
479507
fn write_sectors(
480-
mut conn: OwnedMutexGuard<Connection>,
508+
conn: &mut Connection,
481509
sector_size: u32,
482510
mut sector: u64,
483511
buf: Vec<u8>,
@@ -585,10 +613,23 @@ mod tests {
585613
use crate::FormatParams;
586614
use crate::SqliteDiskLayer;
587615
use disk_backend::Disk;
616+
use disk_backend::DiskError;
588617
use disk_layered::DiskLayer;
589618
use disk_layered::LayerConfiguration;
619+
use disk_layered::LayerIo;
590620
use disk_layered::LayeredDisk;
621+
use guestmem::GuestMemory;
591622
use pal_async::async_test;
623+
use rusqlite::Connection;
624+
use rusqlite::hooks::AuthAction;
625+
use rusqlite::hooks::AuthContext;
626+
use rusqlite::hooks::Authorization;
627+
use scsi_buffers::OwnedRequestBuffers;
628+
use std::sync::Arc;
629+
use std::sync::atomic::AtomicBool;
630+
use std::sync::atomic::AtomicU8;
631+
use std::sync::atomic::Ordering;
632+
use test_with_tracing::test;
592633

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

0 commit comments

Comments
 (0)