From b76d0e8b50fbdcbe52476442142d923e9e791790 Mon Sep 17 00:00:00 2001 From: Bo Chen Date: Mon, 11 Sep 2023 12:18:40 -0700 Subject: [PATCH] virtio-devices: block: Fix latency counter for average read/write The cumulative average formula [1] requires to use signed integers for proper calculations, while calculated result (e.g. cumulative average) is always positive. This patch reflects the above requirements in our code. [1] https://en.wikipedia.org/wiki/Moving_average#Cumulative_average Fixes: #5745 Signed-off-by: Bo Chen --- virtio-devices/src/block.rs | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/virtio-devices/src/block.rs b/virtio-devices/src/block.rs index edf023186..a9557b1a0 100644 --- a/virtio-devices/src/block.rs +++ b/virtio-devices/src/block.rs @@ -309,9 +309,13 @@ impl BlockEpollHandler { read_avg = if read_avg == u64::MAX { latency * LATENCY_SCALE } else { - read_avg - + ((latency * LATENCY_SCALE) - read_avg) - / (read_ops_last + read_ops.0) + // Cumulative average is guaranteed to be + // positive if being calculated properly + (read_avg as i64 + + ((latency * LATENCY_SCALE) as i64 - read_avg as i64) + / (read_ops_last + read_ops.0) as i64) + .try_into() + .unwrap() }; } RequestType::Out => { @@ -339,10 +343,14 @@ impl BlockEpollHandler { write_avg = if write_avg == u64::MAX { latency * LATENCY_SCALE } else { - write_avg - + ((latency * LATENCY_SCALE) - write_avg) - / (write_ops_last + write_ops.0) - }; + // Cumulative average is guaranteed to be + // positive if being calculated properly + (write_avg as i64 + + ((latency * LATENCY_SCALE) as i64 - write_avg as i64) + / (write_ops_last + write_ops.0) as i64) + .try_into() + .unwrap() + } } _ => {} }