Skip to content

Commit cecc381

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. Enable fullfsync on writable macOS connections so SQLite requests F_FULLFSYNC for FUA writes and explicit flushes. 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 9a093fa commit cecc381

3 files changed

Lines changed: 228 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: 225 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@
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+
//! On macOS, writable connections request `F_FULLFSYNC` for SQLite syncs.
11+
//!
812
//! # DISCLAIMER: Stability
913
//!
1014
//! There are no stability guarantees around the on-disk data format! The schema
@@ -174,6 +178,16 @@ impl SqliteDiskLayer {
174178
flags
175179
})?;
176180

181+
#[cfg(target_os = "macos")]
182+
if !read_only {
183+
conn.pragma_update(None, "fullfsync", "ON")
184+
.context("enabling SQLite fullfsync")?;
185+
let fullfsync: bool = conn
186+
.pragma_query_value(None, "fullfsync", |row| row.get(0))
187+
.context("checking SQLite fullfsync")?;
188+
anyhow::ensure!(fullfsync, "SQLite fullfsync is not enabled");
189+
}
190+
177191
let meta = if let Some(FormatParams {
178192
logically_read_only,
179193
len,
@@ -224,6 +238,11 @@ impl SqliteDiskLayer {
224238
serde_json::from_str(&data)?
225239
};
226240

241+
if !read_only {
242+
// Some frontends do not set FUA when their write cache is disabled.
243+
conn.pragma_update(None, "synchronous", "FULL")?;
244+
}
245+
227246
Ok(SqliteDiskLayer {
228247
conn: Arc::new(Mutex::new(conn)),
229248
meta,
@@ -235,6 +254,7 @@ impl SqliteDiskLayer {
235254
buffers: &RequestBuffers<'_>,
236255
sector: u64,
237256
overwrite: bool,
257+
fua: bool,
238258
) -> Result<(), DiskError> {
239259
assert!(!(overwrite && self.meta.logically_read_only));
240260

@@ -249,9 +269,18 @@ impl SqliteDiskLayer {
249269

250270
let buf = buffers.reader().read_all()?;
251271
unblock({
252-
let conn = self.conn.clone().lock_owned().await;
272+
let mut conn = self.conn.clone().lock_owned().await;
253273
let sector_size = self.meta.sector_size;
254-
move || write_sectors(conn, sector_size, sector, buf, overwrite)
274+
move || {
275+
let write = |conn: &mut Connection| {
276+
write_sectors(conn, sector_size, sector, buf, overwrite)
277+
};
278+
if fua {
279+
with_full_synchronous(&mut conn, write)
280+
} else {
281+
write(&mut conn)
282+
}
283+
}
255284
})
256285
.await
257286
.map_err(|e| DiskError::Io(std::io::Error::other(e)))?;
@@ -318,7 +347,7 @@ impl LayerIo for SqliteDiskLayer {
318347
}
319348

320349
fn is_fua_respected(&self) -> bool {
321-
false
350+
true
322351
}
323352

324353
async fn read(
@@ -362,9 +391,9 @@ impl LayerIo for SqliteDiskLayer {
362391
&self,
363392
buffers: &RequestBuffers<'_>,
364393
sector: u64,
365-
_fua: bool,
394+
fua: bool,
366395
) -> Result<(), DiskError> {
367-
self.write_maybe_overwrite(buffers, sector, true).await
396+
self.write_maybe_overwrite(buffers, sector, true, fua).await
368397
}
369398

370399
fn write_no_overwrite(&self) -> Option<impl WriteNoOverwrite> {
@@ -376,15 +405,13 @@ impl LayerIo for SqliteDiskLayer {
376405

377406
unblock({
378407
let mut conn = self.conn.clone().lock_owned().await;
379-
move || -> rusqlite::Result<()> {
408+
move || {
380409
// https://sqlite-users.sqlite.narkive.com/LX75NOma/forcing-a-manual-fsync-in-wal-normal-mode
381-
conn.pragma_update(None, "synchronous", "FULL")?;
382-
{
410+
with_full_synchronous(&mut conn, |conn| {
383411
let tx = conn.transaction()?;
384412
tx.pragma_update(None, "user_version", "0")?;
385-
}
386-
conn.pragma_update(None, "synchronous", "NORMAL")?;
387-
Ok(())
413+
tx.commit()
414+
})
388415
}
389416
})
390417
.await
@@ -428,7 +455,8 @@ impl WriteNoOverwrite for SqliteDiskLayer {
428455
buffers: &RequestBuffers<'_>,
429456
sector: u64,
430457
) -> Result<(), DiskError> {
431-
self.write_maybe_overwrite(buffers, sector, false).await
458+
self.write_maybe_overwrite(buffers, sector, false, false)
459+
.await
432460
}
433461
}
434462

@@ -475,9 +503,20 @@ fn read_sectors(
475503
Ok(res)
476504
}
477505

506+
fn with_full_synchronous(
507+
conn: &mut Connection,
508+
operation: impl FnOnce(&mut Connection) -> rusqlite::Result<()>,
509+
) -> rusqlite::Result<()> {
510+
let previous_mode: u32 = conn.pragma_query_value(None, "synchronous", |row| row.get(0))?;
511+
conn.pragma_update(None, "synchronous", "FULL")?;
512+
let result = operation(conn);
513+
let restore_result = conn.pragma_update(None, "synchronous", previous_mode);
514+
result.and(restore_result)
515+
}
516+
478517
// FUTURE: write into sqlite directly from `RequestBuffers`.
479518
fn write_sectors(
480-
mut conn: OwnedMutexGuard<Connection>,
519+
conn: &mut Connection,
481520
sector_size: u32,
482521
mut sector: u64,
483522
buf: Vec<u8>,
@@ -585,10 +624,23 @@ mod tests {
585624
use crate::FormatParams;
586625
use crate::SqliteDiskLayer;
587626
use disk_backend::Disk;
627+
use disk_backend::DiskError;
588628
use disk_layered::DiskLayer;
589629
use disk_layered::LayerConfiguration;
630+
use disk_layered::LayerIo;
590631
use disk_layered::LayeredDisk;
632+
use guestmem::GuestMemory;
591633
use pal_async::async_test;
634+
use rusqlite::Connection;
635+
use rusqlite::hooks::AuthAction;
636+
use rusqlite::hooks::AuthContext;
637+
use rusqlite::hooks::Authorization;
638+
use scsi_buffers::OwnedRequestBuffers;
639+
use std::sync::Arc;
640+
use std::sync::atomic::AtomicBool;
641+
use std::sync::atomic::AtomicU8;
642+
use std::sync::atomic::Ordering;
643+
use test_with_tracing::test;
592644

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

0 commit comments

Comments
 (0)