Skip to contentSkip to conversation

rust: pl011: correctly use interior mutability

PATCH In review Paolo Bonzini 2 participants 29 messages Jan 17, 2025 – Jan 23, 2025 Rust

lore
Share & tools
lore
#0 lore raw

cover rust: pl011: correctly use interior mutability

QOM devices are aliased from the moment that they are added to the QOM tree, and therefore must not use &mut. This has been a known issue since the beginning of the Rust in QEMU project, and since then a solution was developed in the form of BqlCell and BqlRefCell.

This series moves the MMIO code and registers from PL011State to a new struct PL011Registers, which is wrapped with BqlRefCell. This also allows to remove device-specific code from the device's MemoryRegionOps callbacks, paving the way for MemoryRegionOps bindings.

I am making this series a prerequisite to the usage of Resettable, because it allows reset to reset take a shared reference to the device. Thus the Resettable implementation will not have to temporarily take a mut reference.

Paolo

Paolo Bonzini (10):
rust: pl011: remove unnecessary "extern crate"
rust: pl011: hide unnecessarily "pub" items from outside pl011::device
rust: pl011: extract conversion to RegisterOffset
rust: pl011: extract CharBackend receive logic into a separate function
rust: pl011: pull interrupt updates out of read/write ops
rust: pl011: extract PL011Registers
rust: pl011: wrap registers with BqlRefCell
rust: pl011: remove duplicate definitions
rust: pl011: pull device-specific code out of MemoryRegionOps callbacks
rust: qdev: make reset take a shared reference

 rust/hw/char/pl011/src/device.rs       | 458 ++++++++++++++-----------
 rust/hw/char/pl011/src/device_class.rs |  52 +--
 rust/hw/char/pl011/src/lib.rs          |  61 ++--
 rust/hw/char/pl011/src/memory_ops.rs   |  23 +-
 rust/qemu-api/src/qdev.rs              |   2 +-
 5 files changed, 314 insertions(+), 282 deletions(-)
Signature · 1 line
2.47.1
#1 lore raw

PATCH 1/10 rust: pl011: remove unnecessary "extern crate"

---
 rust/hw/char/pl011/src/lib.rs | 4 ----
 1 file changed, 4 deletions(-)
rust/hw/char/pl011/src/lib.rs +0 -4
index f30f9850ad4..d10f0805aac 100644
@@ -25,10 +25,6 @@
 #![allow(clippy::upper_case_acronyms)]
 #![allow(clippy::result_unit_err)]
 
-extern crate bilge;
-extern crate bilge_impl;
-extern crate qemu_api;
-
 use qemu_api::c_str;
 
 pub mod device;
Signature · 1 line
2.47.1
Reviewed-by on v1 1/10
#2 lore raw

Re: [PATCH 01/10] rust: pl011: remove unnecessary "extern crate"

Quoted 9 lines · Paolo Bonzini

Date: Fri, 17 Jan 2025 10:26:48 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 01/10] rust: pl011: remove unnecessary "extern crate"
X-Mailer: git-send-email 2.47.1

---
 rust/hw/char/pl011/src/lib.rs | 4 ----
 1 file changed, 4 deletions(-)

Yes, it's unnecessary from Rust 2018.

#3 lore raw

PATCH 2/10 rust: pl011: hide unnecessarily "pub" items from outside pl011::device

In reply to Paolo Bonzini

The only public interfaces for pl011 are TYPE_PL011 and pl011_create. Remove pub from everything else.

Note: the "allow(dead_code)" is removed later.

---
 rust/hw/char/pl011/src/device.rs       |  2 +-
 rust/hw/char/pl011/src/device_class.rs |  2 +-
 rust/hw/char/pl011/src/lib.rs          | 13 ++++++++-----
 3 files changed, 10 insertions(+), 7 deletions(-)
rust/hw/char/pl011/src/device.rs +1 -1
index 11a87664c7a..e85e46ba0bb 100644
@@ -565,7 +565,7 @@ pub fn post_load(&mut self, _version_id: u32) -> Result<(), ()> {
 }
 
 /// Which bits in the interrupt status matter for each outbound IRQ line ?
-pub const IRQMASK: [u32; 6] = [
+const IRQMASK: [u32; 6] = [
     /* combined IRQ */
     Interrupt::E
         | Interrupt::MS
rust/hw/char/pl011/src/device_class.rs +1 -1
index b052d98803f..2fd805fd12d 100644
@@ -21,7 +21,7 @@ extern "C" fn pl011_clock_needed(opaque: *mut c_void) -> bool {
 }
 
 /// Migration subsection for [`PL011State`] clock.
-pub static VMSTATE_PL011_CLOCK: VMStateDescription = VMStateDescription {
+static VMSTATE_PL011_CLOCK: VMStateDescription = VMStateDescription {
     name: c_str!("pl011/clock").as_ptr(),
     version_id: 1,
     minimum_version_id: 1,
rust/hw/char/pl011/src/lib.rs +8 -5
index d10f0805aac..2baacba2306 100644
@@ -27,9 +27,11 @@
 
 use qemu_api::c_str;
 
-pub mod device;
-pub mod device_class;
-pub mod memory_ops;
+mod device;
+mod device_class;
+mod memory_ops;
+
+pub use device::pl011_create;
 
 pub const TYPE_PL011: &::std::ffi::CStr = c_str!("pl011");
 pub const TYPE_PL011_LUMINARY: &::std::ffi::CStr = c_str!("pl011_luminary");
@@ -42,7 +44,7 @@
 #[allow(non_camel_case_types)]
 #[repr(u64)]
 #[derive(Debug, qemu_api_macros::TryInto)]
-pub enum RegisterOffset {
+enum RegisterOffset {
     /// Data Register
     ///
     /// A write to this register initiates the actual data transmission
@@ -98,7 +100,8 @@ pub enum RegisterOffset {
     //Reserved = 0x04C,
 }
 
-pub mod registers {
+#[allow(dead_code)]
+mod registers {
     //! Device registers exposed as typed structs which are backed by arbitrary
     //! integer bitmaps. [`Data`], [`Control`], [`LineControl`], etc.
     use bilge::prelude::*;
Signature · 1 line
2.47.1
Reviewed-by on v1 2/10
#4 lore raw

Re: [PATCH 02/10] rust: pl011: hide unnecessarily "pub" items from outside pl011::device

Quoted 9 lines · Paolo Bonzini

Date: Fri, 17 Jan 2025 10:26:49 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 02/10] rust: pl011: hide unnecessarily "pub" items from
outside pl011::device
X-Mailer: git-send-email 2.47.1

The only public interfaces for pl011 are TYPE_PL011 and pl011_create. Remove pub from everything else.

Quoted 9 lines

Note: the "allow(dead_code)" is removed later.

---
 rust/hw/char/pl011/src/device.rs       |  2 +-
 rust/hw/char/pl011/src/device_class.rs |  2 +-
 rust/hw/char/pl011/src/lib.rs          | 13 ++++++++-----
 3 files changed, 10 insertions(+), 7 deletions(-)
#5 lore raw

PATCH 3/10 rust: pl011: extract conversion to RegisterOffset

In reply to Paolo Bonzini

As an added bonus, this also makes the new function return u32 instead of u64, thus factoring some casts into a single place.

---
 rust/hw/char/pl011/src/device.rs | 114 +++++++++++++++++--------------
 1 file changed, 63 insertions(+), 51 deletions(-)
rust/hw/char/pl011/src/device.rs +63 -51
index e85e46ba0bb..6d662865182 100644
@@ -5,6 +5,7 @@
 use core::ptr::{addr_of_mut, NonNull};
 use std::{
     ffi::CStr,
+    ops::ControlFlow,
     os::raw::{c_int, c_uint, c_void},
 };
 
@@ -214,19 +215,11 @@ fn post_init(&self) {
         }
     }
 
-    pub fn read(&mut self, offset: hwaddr, _size: c_uint) -> std::ops::ControlFlow<u64, u64> {
+    fn regs_read(&mut self, offset: RegisterOffset) -> ControlFlow<u32, u32> {
         use RegisterOffset::*;
 
-        let value = match RegisterOffset::try_from(offset) {
-            Err(v) if (0x3f8..0x400).contains(&(v >> 2)) => {
-                let device_id = self.get_class().device_id;
-                u32::from(device_id[(offset - 0xfe0) >> 2])
-            }
-            Err(_) => {
-                // qemu_log_mask(LOG_GUEST_ERROR, "pl011_read: Bad offset 0x%x\n", (int)offset);
-                0
-            }
-            Ok(DR) => {
+        std::ops::ControlFlow::Break(match offset {
+            DR => {
                 self.flags.set_receive_fifo_full(false);
                 let c = self.read_fifo[self.read_pos];
                 if self.read_count > 0 {
@@ -243,39 +236,33 @@ pub fn read(&mut self, offset: hwaddr, _size: c_uint) -> std::ops::ControlFlow<u
                 self.receive_status_error_clear.set_from_data(c);
                 self.update();
                 // Must call qemu_chr_fe_accept_input, so return Continue:
-                let c = u32::from(c);
-                return std::ops::ControlFlow::Continue(u64::from(c));
-            }
-            Ok(RSR) => u32::from(self.receive_status_error_clear),
-            Ok(FR) => u32::from(self.flags),
-            Ok(FBRD) => self.fbrd,
-            Ok(ILPR) => self.ilpr,
-            Ok(IBRD) => self.ibrd,
-            Ok(LCR_H) => u32::from(self.line_control),
-            Ok(CR) => u32::from(self.control),
-            Ok(FLS) => self.ifl,
-            Ok(IMSC) => self.int_enabled,
-            Ok(RIS) => self.int_level,
-            Ok(MIS) => self.int_level & self.int_enabled,
-            Ok(ICR) => {
+                return ControlFlow::Continue(u32::from(c));
+            },
+            RSR => u32::from(self.receive_status_error_clear),
+            FR => u32::from(self.flags),
+            FBRD => self.fbrd,
+            ILPR => self.ilpr,
+            IBRD => self.ibrd,
+            LCR_H => u32::from(self.line_control),
+            CR => u32::from(self.control),
+            FLS => self.ifl,
+            IMSC => self.int_enabled,
+            RIS => self.int_level,
+            MIS => self.int_level & self.int_enabled,
+            ICR => {
                 // "The UARTICR Register is the interrupt clear register and is write-only"
                 // Source: ARM DDI 0183G 3.3.13 Interrupt Clear Register, UARTICR
                 0
-            }
-            Ok(DMACR) => self.dmacr,
-        };
-        std::ops::ControlFlow::Break(value.into())
+            },
+            DMACR => self.dmacr,
+        })
     }
 
-    pub fn write(&mut self, offset: hwaddr, value: u64) {
+    fn regs_write(&mut self, offset: RegisterOffset, value: u32) {
         // eprintln!("write offset {offset} value {value}");
         use RegisterOffset::*;
-        let value: u32 = value as u32;
-        match RegisterOffset::try_from(offset) {
-            Err(_bad_offset) => {
-                eprintln!("write bad offset {offset} value {value}");
-            }
-            Ok(DR) => {
+        match offset {
+            DR => {
                 // ??? Check if transmitter is enabled.
                 let ch: u8 = value as u8;
                 // XXX this blocks entire thread. Rewrite to use
@@ -290,22 +277,22 @@ pub fn write(&mut self, offset: hwaddr, value: u64) {
                 self.int_level |= registers::INT_TX;
                 self.update();
             }
-            Ok(RSR) => {
-                self.receive_status_error_clear.reset();
+            RSR => {
+                self.receive_status_error_clear = 0.into();
             }
-            Ok(FR) => {
+            FR => {
                 // flag writes are ignored
             }
-            Ok(ILPR) => {
+            ILPR => {
                 self.ilpr = value;
             }
-            Ok(IBRD) => {
+            IBRD => {
                 self.ibrd = value;
             }
-            Ok(FBRD) => {
+            FBRD => {
                 self.fbrd = value;
             }
-            Ok(LCR_H) => {
+            LCR_H => {
                 let new_val: registers::LineControl = value.into();
                 // Reset the FIFO state on FIFO enable or disable
                 if self.line_control.fifos_enabled() != new_val.fifos_enabled() {
@@ -328,26 +315,26 @@ pub fn write(&mut self, offset: hwaddr, value: u64) {
                 self.line_control = new_val;
                 self.set_read_trigger();
             }
-            Ok(CR) => {
+            CR => {
                 // ??? Need to implement the enable bit.
                 self.control = value.into();
                 self.loopback_mdmctrl();
             }
-            Ok(FLS) => {
+            FLS => {
                 self.ifl = value;
                 self.set_read_trigger();
             }
-            Ok(IMSC) => {
+            IMSC => {
                 self.int_enabled = value;
                 self.update();
             }
-            Ok(RIS) => {}
-            Ok(MIS) => {}
-            Ok(ICR) => {
+            RIS => {}
+            MIS => {}
+            ICR => {
                 self.int_level &= !value;
                 self.update();
             }
-            Ok(DMACR) => {
+            DMACR => {
                 self.dmacr = value;
                 if value & 3 > 0 {
                     // qemu_log_mask(LOG_UNIMP, "pl011: DMA not implemented\n");
@@ -562,6 +549,31 @@ pub fn post_load(&mut self, _version_id: u32) -> Result<(), ()> {
 
         Ok(())
     }
+
+    pub fn read(&mut self, offset: hwaddr, _size: u32) -> ControlFlow<u64, u64> {
+        match RegisterOffset::try_from(offset) {
+            Err(v) if (0x3f8..0x400).contains(&(v >> 2)) => {
+                let device_id = self.get_class().device_id;
+                ControlFlow::Break(u64::from(device_id[(offset - 0xfe0) >> 2]))
+            }
+            Err(_) => {
+                // qemu_log_mask(LOG_GUEST_ERROR, "pl011_read: Bad offset 0x%x\n", (int)offset);
+                ControlFlow::Break(0)
+            }
+            Ok(field) => match self.regs_read(field) {
+                ControlFlow::Break(value) => ControlFlow::Break(value.into()),
+                ControlFlow::Continue(value) => ControlFlow::Continue(value.into()),
+            }
+        }
+    }
+
+    pub fn write(&mut self, offset: hwaddr, value: u64) {
+        if let Ok(field) = RegisterOffset::try_from(offset) {
+           self.regs_write(field, value as u32);
+        } else {
+            eprintln!("write bad offset {offset} value {value}");
+        }
+    }
 }
 
 /// Which bits in the interrupt status matter for each outbound IRQ line ?
Signature · 1 line
2.47.1
Reviewed-by on v1 3/10
#6 lore raw

Re: [PATCH 03/10] rust: pl011: extract conversion to RegisterOffset

Quoted 12 lines · Paolo Bonzini

Date: Fri, 17 Jan 2025 10:26:50 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 03/10] rust: pl011: extract conversion to RegisterOffset
X-Mailer: git-send-email 2.47.1

As an added bonus, this also makes the new function return u32 instead of u64, thus factoring some casts into a single place.

---
 rust/hw/char/pl011/src/device.rs | 114 +++++++++++++++++--------------
 1 file changed, 63 insertions(+), 51 deletions(-)

[snip]

rust/hw/char/pl011/src/device.rs fn post_init(&self) { · line 219

Quoted 3 lines
rust/hw/char/pl011/src/device.rs +1 -1
-    pub fn read(&mut self, offset: hwaddr, _size: c_uint) -> std::ops::ControlFlow<u64, u64> {
+    fn regs_read(&mut self, offset: RegisterOffset) -> ControlFlow<u32, u32> {
         use RegisterOffset::*;

Can we move this "use" to the start of the file?

IMO, placing it in the local scope appears unnecessary and somewhat fragmented.

rust/hw/char/pl011/src/device.rs fn post_init(&self) { · line 221

Quoted 11 lines
rust/hw/char/pl011/src/device.rs +1 -10
-        let value = match RegisterOffset::try_from(offset) {
-            Err(v) if (0x3f8..0x400).contains(&(v >> 2)) => {
-                let device_id = self.get_class().device_id;
-                u32::from(device_id[(offset - 0xfe0) >> 2])
-            }
-            Err(_) => {
-                // qemu_log_mask(LOG_GUEST_ERROR, "pl011_read: Bad offset 0x%x\n", (int)offset);
-                0
-            }
-            Ok(DR) => {
+        std::ops::ControlFlow::Break(match offset {

std::ops can be omitted now.

Quoted 4 lines
+            DR => {
                 self.flags.set_receive_fifo_full(false);
                 let c = self.read_fifo[self.read_pos];
                 if self.read_count > 0 {

[snip]

Quoted 16 lines
rust/hw/char/pl011/src/device.rs +3 -7
-    pub fn write(&mut self, offset: hwaddr, value: u64) {
+    fn regs_write(&mut self, offset: RegisterOffset, value: u32) {
         // eprintln!("write offset {offset} value {value}");
         use RegisterOffset::*;
-        let value: u32 = value as u32;
-        match RegisterOffset::try_from(offset) {
-            Err(_bad_offset) => {
-                eprintln!("write bad offset {offset} value {value}");
-            }
-            Ok(DR) => {
+        match offset {
+            DR => {
                 // ??? Check if transmitter is enabled.
                 let ch: u8 = value as u8;
                 // XXX this blocks entire thread. Rewrite to use

rust/hw/char/pl011/src/device.rs pub fn write(&mut self, offset: hwaddr, value: u64) { · line 281

Quoted 7 lines
rust/hw/char/pl011/src/device.rs +2 -2
@@ -290,22 +277,22 @@ pub fn write(&mut self, offset: hwaddr, value: u64) {
                 self.int_level |= registers::INT_TX;
                 self.update();
             }
-            Ok(RSR) => {
-                self.receive_status_error_clear.reset();
+            RSR => {
+                self.receive_status_error_clear = 0.into();

Emm, why do we use 0.into() instead of reset() here? It looks they're same.

[snip]

rust/hw/char/pl011/src/device.rs pub fn post_load(&mut self, _version_id: u32) -> Result<(), ()> { · line 553

Quoted 6 lines
rust/hw/char/pl011/src/device.rs +2 -0
@@ -562,6 +549,31 @@ pub fn post_load(&mut self, _version_id: u32) -> Result<(), ()> {
 
         Ok(())
     }
+
+    pub fn read(&mut self, offset: hwaddr, _size: u32) -> ControlFlow<u64, u64> {

Maybe pub(crate)? But both are fine for me :-)

Quoted 6 lines
rust/hw/char/pl011/src/device.rs +6 -0
+        match RegisterOffset::try_from(offset) {
+            Err(v) if (0x3f8..0x400).contains(&(v >> 2)) => {
+                let device_id = self.get_class().device_id;
+                ControlFlow::Break(u64::from(device_id[(offset - 0xfe0) >> 2]))
+            }
+            Err(_) => {

rust/hw/char/pl011/src/device.rs pub fn post_load(&mut self, _version_id: u32) -> Result<(), ()> { · line 569

Quoted 10 lines
rust/hw/char/pl011/src/device.rs +10 -0
+                // qemu_log_mask(LOG_GUEST_ERROR, "pl011_read: Bad offset 0x%x\n", (int)offset);
+                ControlFlow::Break(0)
+            }
+            Ok(field) => match self.regs_read(field) {
+                ControlFlow::Break(value) => ControlFlow::Break(value.into()),
+                ControlFlow::Continue(value) => ControlFlow::Continue(value.into()),
+            }
+        }
+    }
+

Look good to me,

#7 lore raw

Re: [PATCH 03/10] rust: pl011: extract conversion to RegisterOffset

Quoted 14 lines · Zhao Liu
Quoted 5 lines · Paolo Bonzini

Date: Fri, 17 Jan 2025 10:26:50 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 03/10] rust: pl011: extract conversion to RegisterOffset
X-Mailer: git-send-email 2.47.1

Quoted 7 lines

As an added bonus, this also makes the new function return u32 instead of u64, thus factoring some casts into a single place.

---
  rust/hw/char/pl011/src/device.rs | 114 +++++++++++++++++--------------
  1 file changed, 63 insertions(+), 51 deletions(-)
Quoted 7 lines

[snip]

rust/hw/char/pl011/src/device.rs fn post_init(&self) { · line 219

Quoted 3 lines
rust/hw/char/pl011/src/device.rs +1 -1
-    pub fn read(&mut self, offset: hwaddr, _size: c_uint) -> std::ops::ControlFlow<u64, u64> {
+    fn regs_read(&mut self, offset: RegisterOffset) -> ControlFlow<u32, u32> {
          use RegisterOffset::*;

Can we move this "use" to the start of the file?

I don't think it's a good idea to make the register names visible globally... "use Enum::*" before a match statement is relatively common. For example: https://doc.rust-lang.org/src/std/io/error.rs.html#436

Quoted 3 lines
Quoted 1 line

+ std::ops::ControlFlow::Break(match offset {

std::ops can be omitted now.

Done, add added a patch to get rid of ControlFlow completely.

Quoted 7 lines

rust/hw/char/pl011/src/device.rs pub fn write(&mut self, offset: hwaddr, value: u64) { · line 281

Quoted 4 lines
rust/hw/char/pl011/src/device.rs +2 -2
-            Ok(RSR) => {
-                self.receive_status_error_clear.reset();
+            RSR => {
+                self.receive_status_error_clear = 0.into();

Emm, why do we use 0.into() instead of reset() here? It looks they're same.

Fixed.

Quoted 3 lines
Quoted 1 line

+ pub fn read(&mut self, offset: hwaddr, _size: u32) -> ControlFlow<u64, u64> {

Maybe pub(crate)? But both are fine for me :-)

The struct is not public outside the crate, so it doesn't make a difference, does it?

Quoted 1 line

Thanks, I'll post a quick v2 anyway once you've finished reviewing.

Paolo

#8 lore raw

Re: [PATCH 03/10] rust: pl011: extract conversion to RegisterOffset

Quoted 9 lines
Quoted 5 lines

rust/hw/char/pl011/src/device.rs fn post_init(&self) { · line 219

Quoted 3 lines
rust/hw/char/pl011/src/device.rs +1 -1
-    pub fn read(&mut self, offset: hwaddr, _size: c_uint) -> std::ops::ControlFlow<u64, u64> {
+    fn regs_read(&mut self, offset: RegisterOffset) -> ControlFlow<u32, u32> {
          use RegisterOffset::*;

Can we move this "use" to the start of the file?

I don't think it's a good idea to make the register names visible globally... "use Enum::*" before a match statement is relatively common. For example: https://doc.rust-lang.org/src/std/io/error.rs.html#436

Thanks!

Quoted 6 lines
Quoted 3 lines
Quoted 1 line

+ pub fn read(&mut self, offset: hwaddr, _size: u32) -> ControlFlow<u64, u64> {

Maybe pub(crate)? But both are fine for me :-)

The struct is not public outside the crate, so it doesn't make a difference, does it?

You're right.

Quoted 4 lines
Quoted 1 line

Thanks, I'll post a quick v2 anyway once you've finished reviewing.

The remaining critical ones, I'll go through them all tomorrow.

Regerds,
Zhao

#9 lore raw

PATCH 4/10 rust: pl011: extract CharBackend receive logic into a separate function

In reply to Paolo Bonzini

Prepare for moving all references to the registers and the FIFO into a separate struct.

---
 rust/hw/char/pl011/src/device.rs | 15 +++++++++------
 1 file changed, 9 insertions(+), 6 deletions(-)
rust/hw/char/pl011/src/device.rs +9 -6
index 6d662865182..2e8707aef97 100644
@@ -6,7 +6,7 @@
 use std::{
     ffi::CStr,
     ops::ControlFlow,
-    os::raw::{c_int, c_uint, c_void},
+    os::raw::{c_int, c_void},
 };
 
 use qemu_api::{
@@ -480,6 +480,12 @@ pub fn can_receive(&self) -> bool {
         self.read_count < self.fifo_depth()
     }
 
+    pub fn receive(&mut self, ch: u32) {
+        if !self.loopback_enabled() {
+            self.put_fifo(ch)
+        }
+    }
+
     pub fn event(&mut self, event: QEMUChrEvent) {
         if event == bindings::QEMUChrEvent::CHR_EVENT_BREAK && !self.loopback_enabled() {
             self.put_fifo(registers::Data::BREAK.into());
@@ -505,7 +511,7 @@ pub fn fifo_depth(&self) -> u32 {
         1
     }
 
-    pub fn put_fifo(&mut self, value: c_uint) {
+    pub fn put_fifo(&mut self, value: u32) {
         let depth = self.fifo_depth();
         assert!(depth > 0);
         let slot = (self.read_pos + self.read_count) & (depth - 1);
@@ -615,12 +621,9 @@ pub fn write(&mut self, offset: hwaddr, value: u64) {
     unsafe {
         debug_assert!(!opaque.is_null());
         let mut state = NonNull::new_unchecked(opaque.cast::<PL011State>());
-        if state.as_ref().loopback_enabled() {
-            return;
-        }
         if size > 0 {
             debug_assert!(!buf.is_null());
-            state.as_mut().put_fifo(c_uint::from(buf.read_volatile()))
+            state.as_mut().receive(u32::from(buf.read_volatile()));
         }
     }
 }
Signature · 1 line
2.47.1
Reviewed-by on v1 4/10
#10 lore raw

Re: [PATCH 04/10] rust: pl011: extract CharBackend receive logic into a separate function

Quoted 13 lines · Paolo Bonzini

Date: Fri, 17 Jan 2025 10:26:51 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 04/10] rust: pl011: extract CharBackend receive logic into
a separate function
X-Mailer: git-send-email 2.47.1

Prepare for moving all references to the registers and the FIFO into a separate struct.

---
 rust/hw/char/pl011/src/device.rs | 15 +++++++++------
 1 file changed, 9 insertions(+), 6 deletions(-)

[snip]

Quoted 6 lines
rust/hw/char/pl011/src/device.rs +1 -1
-    pub fn put_fifo(&mut self, value: c_uint) {
+    pub fn put_fifo(&mut self, value: u32) {
         let depth = self.fifo_depth();
         assert!(depth > 0);
         let slot = (self.read_pos + self.read_count) & (depth - 1);

rust/hw/char/pl011/src/device.rs pub fn write(&mut self, offset: hwaddr, value: u64) { · line 623

Quoted 9 lines
rust/hw/char/pl011/src/device.rs +0 -4
@@ -615,12 +621,9 @@ pub fn write(&mut self, offset: hwaddr, value: u64) {
     unsafe {
         debug_assert!(!opaque.is_null());
         let mut state = NonNull::new_unchecked(opaque.cast::<PL011State>());
-        if state.as_ref().loopback_enabled() {
-            return;
-        }
         if size > 0 {
             debug_assert!(!buf.is_null());
-            state.as_mut().put_fifo(c_uint::from(buf.read_volatile()))

An extra question...here I'm not sure, do we really need read_volatile?

rust/hw/char/pl011/src/device.rs pub fn write(&mut self, offset: hwaddr, value: u64) { · line 629

Quoted 4 lines
rust/hw/char/pl011/src/device.rs +1 -0
+            state.as_mut().receive(u32::from(buf.read_volatile()));
         }
     }
 }

Patch is fine for me,

#11 lore raw

Re: [PATCH 04/10] rust: pl011: extract CharBackend receive logic into a separate function

Quoted 5 lines · Zhao Liu
Quoted 3 lines
          if size > 0 {
              debug_assert!(!buf.is_null());

- state.as_mut().put_fifo(c_uint::from(buf.read_volatile()))

An extra question...here I'm not sure, do we really need read_volatile?

No, the buffer is not guest visible. It will certainly go away together with chardev bindings.

Paolo

#12 lore raw

PATCH 5/10 rust: pl011: pull interrupt updates out of read/write ops

In reply to Paolo Bonzini

qemu_irqs are not part of the vmstate, therefore they will remain in PL011State. Update them if needed after regs_read()/regs_write().

Apply #[must_use] to functions that return whether the interrupt state could have changed, so that it's harder to forget the call to update().

---
 rust/hw/char/pl011/src/device.rs | 68 ++++++++++++++++++--------------
 1 file changed, 38 insertions(+), 30 deletions(-)
rust/hw/char/pl011/src/device.rs +38 -30
index 2e8707aef97..67c3e63baa1 100644
@@ -234,7 +234,6 @@ fn regs_read(&mut self, offset: RegisterOffset) -> ControlFlow<u32, u32> {
                 }
                 // Update error bits.
                 self.receive_status_error_clear.set_from_data(c);
-                self.update();
                 // Must call qemu_chr_fe_accept_input, so return Continue:
                 return ControlFlow::Continue(u32::from(c));
             },
@@ -258,7 +257,7 @@ fn regs_read(&mut self, offset: RegisterOffset) -> ControlFlow<u32, u32> {
         })
     }
 
-    fn regs_write(&mut self, offset: RegisterOffset, value: u32) {
+    fn regs_write(&mut self, offset: RegisterOffset, value: u32) -> bool {
         // eprintln!("write offset {offset} value {value}");
         use RegisterOffset::*;
         match offset {
@@ -273,9 +272,10 @@ fn regs_write(&mut self, offset: RegisterOffset, value: u32) {
                 unsafe {
                     qemu_chr_fe_write_all(addr_of_mut!(self.char_backend), &ch, 1);
                 }
-                self.loopback_tx(value);
+                // interrupts always checked
+                let _ = self.loopback_tx(value);
                 self.int_level |= registers::INT_TX;
-                self.update();
+                return true;
             }
             RSR => {
                 self.receive_status_error_clear = 0.into();
@@ -299,7 +299,7 @@ fn regs_write(&mut self, offset: RegisterOffset, value: u32) {
                     self.reset_rx_fifo();
                     self.reset_tx_fifo();
                 }
-                if self.line_control.send_break() ^ new_val.send_break() {
+                let update = (self.line_control.send_break() != new_val.send_break()) && {
                     let mut break_enable: c_int = new_val.send_break().into();
                     // SAFETY: self.char_backend is a valid CharBackend instance after it's been
                     // initialized in realize().
@@ -310,15 +310,16 @@ fn regs_write(&mut self, offset: RegisterOffset, value: u32) {
                             addr_of_mut!(break_enable).cast::<c_void>(),
                         );
                     }
-                    self.loopback_break(break_enable > 0);
-                }
+                    self.loopback_break(break_enable > 0)
+                };
                 self.line_control = new_val;
                 self.set_read_trigger();
+                return update;
             }
             CR => {
                 // ??? Need to implement the enable bit.
                 self.control = value.into();
-                self.loopback_mdmctrl();
+                return self.loopback_mdmctrl();
             }
             FLS => {
                 self.ifl = value;
@@ -326,13 +327,13 @@ fn regs_write(&mut self, offset: RegisterOffset, value: u32) {
             }
             IMSC => {
                 self.int_enabled = value;
-                self.update();
+                return true;
             }
             RIS => {}
             MIS => {}
             ICR => {
                 self.int_level &= !value;
-                self.update();
+                return true;
             }
             DMACR => {
                 self.dmacr = value;
@@ -342,14 +343,12 @@ fn regs_write(&mut self, offset: RegisterOffset, value: u32) {
                 }
             }
         }
+        false
     }
 
     #[inline]
-    fn loopback_tx(&mut self, value: u32) {
-        if !self.loopback_enabled() {
-            return;
-        }
-
+    #[must_use]
+    fn loopback_tx(&mut self, value: u32) -> bool {
         // Caveat:
         //
         // In real hardware, TX loopback happens at the serial-bit level
@@ -367,12 +366,13 @@ fn loopback_tx(&mut self, value: u32) {
         // hardware flow-control is enabled.
         //
         // For simplicity, the above described is not emulated.
-        self.put_fifo(value);
+        self.loopback_enabled() && self.put_fifo(value)
     }
 
-    fn loopback_mdmctrl(&mut self) {
+    #[must_use]
+    fn loopback_mdmctrl(&mut self) -> bool {
         if !self.loopback_enabled() {
-            return;
+            return false;
         }
 
         /*
@@ -413,13 +413,11 @@ fn loopback_mdmctrl(&mut self) {
             il |= Interrupt::RI as u32;
         }
         self.int_level = il;
-        self.update();
+        true
     }
 
-    fn loopback_break(&mut self, enable: bool) {
-        if enable {
-            self.loopback_tx(registers::Data::BREAK.into());
-        }
+    fn loopback_break(&mut self, enable: bool) -> bool {
+        enable && self.loopback_tx(registers::Data::BREAK.into())
     }
 
     fn set_read_trigger(&mut self) {
@@ -481,14 +479,17 @@ pub fn can_receive(&self) -> bool {
     }
 
     pub fn receive(&mut self, ch: u32) {
-        if !self.loopback_enabled() {
-            self.put_fifo(ch)
+        if !self.loopback_enabled() && self.put_fifo(ch) {
+            self.update();
         }
     }
 
     pub fn event(&mut self, event: QEMUChrEvent) {
         if event == bindings::QEMUChrEvent::CHR_EVENT_BREAK && !self.loopback_enabled() {
-            self.put_fifo(registers::Data::BREAK.into());
+            let update = self.put_fifo(registers::Data::BREAK.into());
+            if update {
+                self.update();
+            }
         }
     }
 
@@ -511,7 +512,8 @@ pub fn fifo_depth(&self) -> u32 {
         1
     }
 
-    pub fn put_fifo(&mut self, value: u32) {
+    #[must_use]
+    pub fn put_fifo(&mut self, value: u32) -> bool {
         let depth = self.fifo_depth();
         assert!(depth > 0);
         let slot = (self.read_pos + self.read_count) & (depth - 1);
@@ -524,8 +526,9 @@ pub fn put_fifo(&mut self, value: u32) {
 
         if self.read_count == self.read_trigger {
             self.int_level |= registers::INT_RX;
-            self.update();
+            return true;
         }
+        false
     }
 
     pub fn update(&self) {
@@ -568,14 +571,19 @@ pub fn read(&mut self, offset: hwaddr, _size: u32) -> ControlFlow<u64, u64> {
             }
             Ok(field) => match self.regs_read(field) {
                 ControlFlow::Break(value) => ControlFlow::Break(value.into()),
-                ControlFlow::Continue(value) => ControlFlow::Continue(value.into()),
+                ControlFlow::Continue(value) => {
+                    self.update();
+                    ControlFlow::Continue(value.into())
+                },
             }
         }
     }
 
     pub fn write(&mut self, offset: hwaddr, value: u64) {
         if let Ok(field) = RegisterOffset::try_from(offset) {
-           self.regs_write(field, value as u32);
+            if self.regs_write(field, value as u32) {
+                self.update();
+            }
         } else {
             eprintln!("write bad offset {offset} value {value}");
         }
Signature · 1 line
2.47.1
Reviewed-by on v1 5/10
#13 lore raw

Re: [PATCH 05/10] rust: pl011: pull interrupt updates out of read/write ops

Quoted 17 lines · Paolo Bonzini

Date: Fri, 17 Jan 2025 10:26:52 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 05/10] rust: pl011: pull interrupt updates out of
read/write ops
X-Mailer: git-send-email 2.47.1

qemu_irqs are not part of the vmstate, therefore they will remain in PL011State. Update them if needed after regs_read()/regs_write().

Apply #[must_use] to functions that return whether the interrupt state could have changed, so that it's harder to forget the call to update().

---
 rust/hw/char/pl011/src/device.rs | 68 ++++++++++++++++++--------------
 1 file changed, 38 insertions(+), 30 deletions(-)

[snip]

rust/hw/char/pl011/src/device.rs pub fn can_receive(&self) -> bool { · line 489

Quoted 5 lines
 
     pub fn event(&mut self, event: QEMUChrEvent) {
         if event == bindings::QEMUChrEvent::CHR_EVENT_BREAK && !self.loopback_enabled() {
rust/hw/char/pl011/src/device.rs +1 -1
-            self.put_fifo(registers::Data::BREAK.into());
+            let update = self.put_fifo(registers::Data::BREAK.into());

We can omit this update variable.

rust/hw/char/pl011/src/device.rs pub fn can_receive(&self) -> bool { · line 494

Quoted 5 lines
rust/hw/char/pl011/src/device.rs +3 -0
+            if update {
+                self.update();
+            }
         }
     }

Nice refactoring!

author Reviewed-by Zhao Liu
#14 lore raw

Re: [PATCH 05/10] rust: pl011: pull interrupt updates out of read/write ops

Il mer 22 gen 2025, 17:31 Zhao Liu <[email protected]> ha scritto:

Quoted 7 lines
Quoted 1 line
         if event == bindings::QEMUChrEvent::CHR_EVENT_BREAK &&

!self.loopback_enabled() {

rust/hw/char/pl011/src/device.rs pub fn can_receive(&self) -> bool { · line 489

Quoted 2 lines
rust/hw/char/pl011/src/device.rs +1 -1
-            self.put_fifo(registers::Data::BREAK.into());
+            let update = self.put_fifo(registers::Data::BREAK.into());

We can omit this update variable.

Indeed, but sometimes I left it because of long lines or to clarify the meaning of the "bool" (or both).

Paolo

#15 lore raw

PATCH 6/10 rust: pl011: extract PL011Registers

In reply to Paolo Bonzini

Pull all the mutable fields of PL011State into a separate struct.

---
 rust/hw/char/pl011/src/device.rs       | 251 ++++++++++++++-----------
 rust/hw/char/pl011/src/device_class.rs |  46 +++--
 2 files changed, 168 insertions(+), 129 deletions(-)
rust/hw/char/pl011/src/device.rs +140 -111
index 67c3e63baa1..476abe765a9 100644
@@ -78,11 +78,8 @@ fn index(&self, idx: u32) -> &Self::Output {
 }
 
 #[repr(C)]
-#[derive(Debug, qemu_api_macros::Object, qemu_api_macros::offsets)]
-/// PL011 Device Model in QEMU
-pub struct PL011State {
-    pub parent_obj: ParentField<SysBusDevice>,
-    pub iomem: MemoryRegion,
+#[derive(Debug, Default, qemu_api_macros::offsets)]
+pub struct PL011Registers {
     #[doc(alias = "fr")]
     pub flags: registers::Flags,
     #[doc(alias = "lcr")]
@@ -102,8 +99,17 @@ pub struct PL011State {
     pub read_pos: u32,
     pub read_count: u32,
     pub read_trigger: u32,
+}
+
+#[repr(C)]
+#[derive(Debug, qemu_api_macros::Object, qemu_api_macros::offsets)]
+/// PL011 Device Model in QEMU
+pub struct PL011State {
+    pub parent_obj: ParentField<SysBusDevice>,
+    pub iomem: MemoryRegion,
     #[doc(alias = "chr")]
     pub char_backend: CharBackend,
+    pub regs: PL011Registers,
     /// QEMU interrupts
     ///
     /// ```text
@@ -161,61 +167,8 @@ fn vmsd() -> Option<&'static VMStateDescription> {
     const RESET: Option<fn(&mut Self)> = Some(Self::reset);
 }
 
-impl PL011State {
-    /// Initializes a pre-allocated, unitialized instance of `PL011State`.
-    ///
-    /// # Safety
-    ///
-    /// `self` must point to a correctly sized and aligned location for the
-    /// `PL011State` type. It must not be called more than once on the same
-    /// location/instance. All its fields are expected to hold unitialized
-    /// values with the sole exception of `parent_obj`.
-    unsafe fn init(&mut self) {
-        const CLK_NAME: &CStr = c_str!("clk");
-
-        // SAFETY:
-        //
-        // self and self.iomem are guaranteed to be valid at this point since callers
-        // must make sure the `self` reference is valid.
-        unsafe {
-            memory_region_init_io(
-                addr_of_mut!(self.iomem),
-                addr_of_mut!(*self).cast::<Object>(),
-                &PL011_OPS,
-                addr_of_mut!(*self).cast::<c_void>(),
-                Self::TYPE_NAME.as_ptr(),
-                0x1000,
-            );
-        }
-
-        // SAFETY:
-        //
-        // self.clock is not initialized at this point; but since `NonNull<_>` is Copy,
-        // we can overwrite the undefined value without side effects. This is
-        // safe since all PL011State instances are created by QOM code which
-        // calls this function to initialize the fields; therefore no code is
-        // able to access an invalid self.clock value.
-        unsafe {
-            let dev: &mut DeviceState = self.upcast_mut();
-            self.clock = NonNull::new(qdev_init_clock_in(
-                dev,
-                CLK_NAME.as_ptr(),
-                None, /* pl011_clock_update */
-                addr_of_mut!(*self).cast::<c_void>(),
-                ClockEvent::ClockUpdate.0,
-            ))
-            .unwrap();
-        }
-    }
-
-    fn post_init(&self) {
-        self.init_mmio(&self.iomem);
-        for irq in self.interrupts.iter() {
-            self.init_irq(irq);
-        }
-    }
-
-    fn regs_read(&mut self, offset: RegisterOffset) -> ControlFlow<u32, u32> {
+impl PL011Registers {
+    pub(self) fn read(&mut self, offset: RegisterOffset) -> ControlFlow<u32, u32> {
         use RegisterOffset::*;
 
         std::ops::ControlFlow::Break(match offset {
@@ -257,7 +210,12 @@ fn regs_read(&mut self, offset: RegisterOffset) -> ControlFlow<u32, u32> {
         })
     }
 
-    fn regs_write(&mut self, offset: RegisterOffset, value: u32) -> bool {
+    pub(self) fn write(
+        &mut self,
+        offset: RegisterOffset,
+        value: u32,
+        char_backend: *mut CharBackend,
+    ) -> bool {
         // eprintln!("write offset {offset} value {value}");
         use RegisterOffset::*;
         match offset {
@@ -267,10 +225,10 @@ fn regs_write(&mut self, offset: RegisterOffset, value: u32) -> bool {
                 // XXX this blocks entire thread. Rewrite to use
                 // qemu_chr_fe_write and background I/O callbacks
 
-                // SAFETY: self.char_backend is a valid CharBackend instance after it's been
+                // SAFETY: char_backend is a valid CharBackend instance after it's been
                 // initialized in realize().
                 unsafe {
-                    qemu_chr_fe_write_all(addr_of_mut!(self.char_backend), &ch, 1);
+                    qemu_chr_fe_write_all(char_backend, &ch, 1);
                 }
                 // interrupts always checked
                 let _ = self.loopback_tx(value);
@@ -305,7 +263,7 @@ fn regs_write(&mut self, offset: RegisterOffset, value: u32) -> bool {
                     // initialized in realize().
                     unsafe {
                         qemu_chr_fe_ioctl(
-                            addr_of_mut!(self.char_backend),
+                            char_backend,
                             CHR_IOCTL_SERIAL_SET_BREAK as i32,
                             addr_of_mut!(break_enable).cast::<c_void>(),
                         );
@@ -424,23 +382,6 @@ fn set_read_trigger(&mut self) {
         self.read_trigger = 1;
     }
 
-    pub fn realize(&mut self) {
-        // SAFETY: self.char_backend has the correct size and alignment for a
-        // CharBackend object, and its callbacks are of the correct types.
-        unsafe {
-            qemu_chr_fe_set_handlers(
-                addr_of_mut!(self.char_backend),
-                Some(pl011_can_receive),
-                Some(pl011_receive),
-                Some(pl011_event),
-                None,
-                addr_of_mut!(*self).cast::<c_void>(),
-                core::ptr::null_mut(),
-                true,
-            );
-        }
-    }
-
     pub fn reset(&mut self) {
         self.line_control.reset();
         self.receive_status_error_clear.reset();
@@ -473,26 +414,6 @@ pub fn reset_tx_fifo(&mut self) {
         self.flags.set_transmit_fifo_empty(true);
     }
 
-    pub fn can_receive(&self) -> bool {
-        // trace_pl011_can_receive(s->lcr, s->read_count, r);
-        self.read_count < self.fifo_depth()
-    }
-
-    pub fn receive(&mut self, ch: u32) {
-        if !self.loopback_enabled() && self.put_fifo(ch) {
-            self.update();
-        }
-    }
-
-    pub fn event(&mut self, event: QEMUChrEvent) {
-        if event == bindings::QEMUChrEvent::CHR_EVENT_BREAK && !self.loopback_enabled() {
-            let update = self.put_fifo(registers::Data::BREAK.into());
-            if update {
-                self.update();
-            }
-        }
-    }
-
     #[inline]
     pub fn fifo_enabled(&self) -> bool {
         self.line_control.fifos_enabled() == registers::Mode::FIFO
@@ -531,14 +452,7 @@ pub fn put_fifo(&mut self, value: u32) -> bool {
         false
     }
 
-    pub fn update(&self) {
-        let flags = self.int_level & self.int_enabled;
-        for (irq, i) in self.interrupts.iter().zip(IRQMASK) {
-            irq.set(flags & i != 0);
-        }
-    }
-
-    pub fn post_load(&mut self, _version_id: u32) -> Result<(), ()> {
+    pub fn post_load(&mut self) -> Result<(), ()> {
         /* Sanity-check input state */
         if self.read_pos >= self.read_fifo.len() || self.read_count > self.read_fifo.len() {
             return Err(());
@@ -558,8 +472,66 @@ pub fn post_load(&mut self, _version_id: u32) -> Result<(), ()> {
 
         Ok(())
     }
+}
+
+impl PL011State {
+    /// Initializes a pre-allocated, unitialized instance of `PL011State`.
+    ///
+    /// # Safety
+    ///
+    /// `self` must point to a correctly sized and aligned location for the
+    /// `PL011State` type. It must not be called more than once on the same
+    /// location/instance. All its fields are expected to hold unitialized
+    /// values with the sole exception of `parent_obj`.
+    unsafe fn init(&mut self) {
+        const CLK_NAME: &CStr = c_str!("clk");
+
+        // SAFETY:
+        //
+        // self and self.iomem are guaranteed to be valid at this point since callers
+        // must make sure the `self` reference is valid.
+        unsafe {
+            memory_region_init_io(
+                addr_of_mut!(self.iomem),
+                addr_of_mut!(*self).cast::<Object>(),
+                &PL011_OPS,
+                addr_of_mut!(*self).cast::<c_void>(),
+                Self::TYPE_NAME.as_ptr(),
+                0x1000,
+            );
+        }
+
+        self.regs = Default::default();
+
+        // SAFETY:
+        //
+        // self.clock is not initialized at this point; but since `NonNull<_>` is Copy,
+        // we can overwrite the undefined value without side effects. This is
+        // safe since all PL011State instances are created by QOM code which
+        // calls this function to initialize the fields; therefore no code is
+        // able to access an invalid self.clock value.
+        unsafe {
+            let dev: &mut DeviceState = self.upcast_mut();
+            self.clock = NonNull::new(qdev_init_clock_in(
+                dev,
+                CLK_NAME.as_ptr(),
+                None, /* pl011_clock_update */
+                addr_of_mut!(*self).cast::<c_void>(),
+                ClockEvent::ClockUpdate.0,
+            ))
+            .unwrap();
+        }
+    }
+
+    fn post_init(&self) {
+        self.init_mmio(&self.iomem);
+        for irq in self.interrupts.iter() {
+            self.init_irq(irq);
+        }
+    }
 
     pub fn read(&mut self, offset: hwaddr, _size: u32) -> ControlFlow<u64, u64> {
+        let regs = &mut self.regs;
         match RegisterOffset::try_from(offset) {
             Err(v) if (0x3f8..0x400).contains(&(v >> 2)) => {
                 let device_id = self.get_class().device_id;
@@ -569,7 +541,7 @@ pub fn read(&mut self, offset: hwaddr, _size: u32) -> ControlFlow<u64, u64> {
                 // qemu_log_mask(LOG_GUEST_ERROR, "pl011_read: Bad offset 0x%x\n", (int)offset);
                 ControlFlow::Break(0)
             }
-            Ok(field) => match self.regs_read(field) {
+            Ok(field) => match regs.read(field) {
                 ControlFlow::Break(value) => ControlFlow::Break(value.into()),
                 ControlFlow::Continue(value) => {
                     self.update();
@@ -580,14 +552,71 @@ pub fn read(&mut self, offset: hwaddr, _size: u32) -> ControlFlow<u64, u64> {
     }
 
     pub fn write(&mut self, offset: hwaddr, value: u64) {
+        let regs = &mut self.regs;
         if let Ok(field) = RegisterOffset::try_from(offset) {
-            if self.regs_write(field, value as u32) {
+            if regs.write(field, value as u32, &mut self.char_backend) {
                 self.update();
             }
         } else {
             eprintln!("write bad offset {offset} value {value}");
         }
     }
+
+    pub fn can_receive(&self) -> bool {
+        // trace_pl011_can_receive(s->lcr, s->read_count, r);
+        let regs = &self.regs;
+        regs.read_count < regs.fifo_depth()
+    }
+
+    pub fn receive(&mut self, ch: u32) {
+        let regs = &mut self.regs;
+        if !regs.loopback_enabled() && regs.put_fifo(ch) {
+            self.update();
+        }
+    }
+
+    pub fn event(&mut self, event: QEMUChrEvent) {
+        let regs = &mut self.regs;
+        if event == bindings::QEMUChrEvent::CHR_EVENT_BREAK && !regs.loopback_enabled() {
+            let update = regs.put_fifo(registers::Data::BREAK.into());
+            if update {
+                self.update()
+            }
+        }
+    }
+
+    pub fn realize(&mut self) {
+        // SAFETY: self.char_backend has the correct size and alignment for a
+        // CharBackend object, and its callbacks are of the correct types.
+        unsafe {
+            qemu_chr_fe_set_handlers(
+                addr_of_mut!(self.char_backend),
+                Some(pl011_can_receive),
+                Some(pl011_receive),
+                Some(pl011_event),
+                None,
+                addr_of_mut!(*self).cast::<c_void>(),
+                core::ptr::null_mut(),
+                true,
+            );
+        }
+    }
+
+    pub fn reset(&mut self) {
+        self.regs.reset();
+    }
+
+    pub fn update(&self) {
+        let regs = &self.regs;
+        let flags = regs.int_level & regs.int_enabled;
+        for (irq, i) in self.interrupts.iter().zip(IRQMASK) {
+            irq.set(flags & i != 0);
+        }
+    }
+
+    pub fn post_load(&mut self, _version_id: u32) -> Result<(), ()> {
+        self.regs.post_load()
+    }
 }
 
 /// Which bits in the interrupt status matter for each outbound IRQ line ?
rust/hw/char/pl011/src/device_class.rs +28 -18

66 lines not on this page · raw message

Signature · 1 line
2.47.1
Reviewed-by on v1 6/10
#16 lore raw

Re: [PATCH 06/10] rust: pl011: extract PL011Registers

rust/hw/char/pl011/src/device_class.rs line 9

Quoted 9 lines
rust/hw/char/pl011/src/device_class.rs +1 -2
@@ -6,11 +6,11 @@
 use std::os::raw::{c_int, c_void};
 
 use qemu_api::{
-    bindings::*, c_str, vmstate_clock, vmstate_fields, vmstate_of, vmstate_subsections,
-    vmstate_unused, zeroable::Zeroable,
+    bindings::*, c_str, vmstate_clock, vmstate_fields, vmstate_of, vmstate_struct,

Oops, I forgot to clean up this bindings::*.

rust/hw/char/pl011/src/device_class.rs line 12

Quoted 3 lines
rust/hw/char/pl011/src/device_class.rs +1 -0
+    vmstate_subsections, vmstate_unused, zeroable::Zeroable,
 };
 

Very good example!

#17 lore raw

Re: [PATCH 06/10] rust: pl011: extract PL011Registers

Il gio 23 gen 2025, 04:25 Zhao Liu <[email protected]> ha scritto:

Quoted 5 lines
Quoted 5 lines
rust/hw/char/pl011/src/device_class.rs +0 -0
@@ -6,11 +6,11 @@
 use std::os::raw::{c_int, c_void};
 
Quoted 9 lines

rust/hw/char/pl011/src/device_class.rs line 9

Quoted 2 lines
rust/hw/char/pl011/src/device_class.rs +0 -1
 use qemu_api::{
-    bindings::*, c_str, vmstate_clock, vmstate_fields, vmstate_of,

vmstate_subsections,

rust/hw/char/pl011/src/device_class.rs line 9

Quoted 2 lines
rust/hw/char/pl011/src/device_class.rs +1 -1
-    vmstate_unused, zeroable::Zeroable,
+    bindings::*, c_str, vmstate_clock, vmstate_fields, vmstate_of,

vmstate_struct,

Oops, I forgot to clean up this bindings::*.

No big deal (it's a secondary file and will probably be merged into device.rs as soon as VMState bindings are more complete).

Paolo

Quoted 9 lines

+ vmstate_subsections, vmstate_unused, zeroable::Zeroable,

rust/hw/char/pl011/src/device_class.rs line 11

Quoted 2 lines
rust/hw/char/pl011/src/device_class.rs +0 -0
 };
 

Very good example!

#18 lore raw

PATCH 7/10 rust: pl011: wrap registers with BqlRefCell

In reply to Paolo Bonzini

This is a step towards making memory ops use a shared reference to the device type; it's not yet possible due to the calls to character device functions.

---
 rust/hw/char/pl011/src/device.rs       | 38 +++++++++++++-------------
 rust/hw/char/pl011/src/device_class.rs |  8 +++---
 rust/hw/char/pl011/src/memory_ops.rs   |  2 +-
 3 files changed, 24 insertions(+), 24 deletions(-)
rust/hw/char/pl011/src/device.rs +19 -19
index 476abe765a9..1d3da59e481 100644
@@ -102,14 +102,14 @@ pub struct PL011Registers {
 }
 
 #[repr(C)]
-#[derive(Debug, qemu_api_macros::Object, qemu_api_macros::offsets)]
+#[derive(qemu_api_macros::Object, qemu_api_macros::offsets)]
 /// PL011 Device Model in QEMU
 pub struct PL011State {
     pub parent_obj: ParentField<SysBusDevice>,
     pub iomem: MemoryRegion,
     #[doc(alias = "chr")]
     pub char_backend: CharBackend,
-    pub regs: PL011Registers,
+    pub regs: BqlRefCell<PL011Registers>,
     /// QEMU interrupts
     ///
     /// ```text
@@ -530,8 +530,8 @@ fn post_init(&self) {
         }
     }
 
+    #[allow(clippy::needless_pass_by_ref_mut)]
     pub fn read(&mut self, offset: hwaddr, _size: u32) -> ControlFlow<u64, u64> {
-        let regs = &mut self.regs;
         match RegisterOffset::try_from(offset) {
             Err(v) if (0x3f8..0x400).contains(&(v >> 2)) => {
                 let device_id = self.get_class().device_id;
@@ -541,7 +541,7 @@ pub fn read(&mut self, offset: hwaddr, _size: u32) -> ControlFlow<u64, u64> {
                 // qemu_log_mask(LOG_GUEST_ERROR, "pl011_read: Bad offset 0x%x\n", (int)offset);
                 ControlFlow::Break(0)
             }
-            Ok(field) => match regs.read(field) {
+            Ok(field) => match self.regs.borrow_mut().read(field) {
                 ControlFlow::Break(value) => ControlFlow::Break(value.into()),
                 ControlFlow::Continue(value) => {
                     self.update();
@@ -552,7 +552,7 @@ pub fn read(&mut self, offset: hwaddr, _size: u32) -> ControlFlow<u64, u64> {
     }
 
     pub fn write(&mut self, offset: hwaddr, value: u64) {
-        let regs = &mut self.regs;
+        let mut regs = self.regs.borrow_mut();
         if let Ok(field) = RegisterOffset::try_from(offset) {
             if regs.write(field, value as u32, &mut self.char_backend) {
                 self.update();
@@ -564,19 +564,19 @@ pub fn write(&mut self, offset: hwaddr, value: u64) {
 
     pub fn can_receive(&self) -> bool {
         // trace_pl011_can_receive(s->lcr, s->read_count, r);
-        let regs = &self.regs;
+        let regs = self.regs.borrow();
         regs.read_count < regs.fifo_depth()
     }
 
-    pub fn receive(&mut self, ch: u32) {
-        let regs = &mut self.regs;
+    pub fn receive(&self, ch: u32) {
+        let mut regs = self.regs.borrow_mut();
         if !regs.loopback_enabled() && regs.put_fifo(ch) {
             self.update();
         }
     }
 
-    pub fn event(&mut self, event: QEMUChrEvent) {
-        let regs = &mut self.regs;
+    pub fn event(&self, event: QEMUChrEvent) {
+        let mut regs = self.regs.borrow_mut();
         if event == bindings::QEMUChrEvent::CHR_EVENT_BREAK && !regs.loopback_enabled() {
             let update = regs.put_fifo(registers::Data::BREAK.into());
             if update {
@@ -603,19 +603,19 @@ pub fn realize(&mut self) {
     }
 
     pub fn reset(&mut self) {
-        self.regs.reset();
+        self.regs.borrow_mut().reset();
     }
 
     pub fn update(&self) {
-        let regs = &self.regs;
+        let regs = self.regs.borrow();
         let flags = regs.int_level & regs.int_enabled;
         for (irq, i) in self.interrupts.iter().zip(IRQMASK) {
             irq.set(flags & i != 0);
         }
     }
 
-    pub fn post_load(&mut self, _version_id: u32) -> Result<(), ()> {
-        self.regs.post_load()
+    pub fn post_load(&self, _version_id: u32) -> Result<(), ()> {
+        self.regs.borrow_mut().post_load()
     }
 }
 
@@ -657,10 +657,10 @@ pub fn post_load(&mut self, _version_id: u32) -> Result<(), ()> {
 pub unsafe extern "C" fn pl011_receive(opaque: *mut c_void, buf: *const u8, size: c_int) {
     unsafe {
         debug_assert!(!opaque.is_null());
-        let mut state = NonNull::new_unchecked(opaque.cast::<PL011State>());
+        let state = NonNull::new_unchecked(opaque.cast::<PL011State>());
         if size > 0 {
             debug_assert!(!buf.is_null());
-            state.as_mut().receive(u32::from(buf.read_volatile()));
+            state.as_ref().receive(u32::from(buf.read_volatile()));
         }
     }
 }
@@ -673,8 +673,8 @@ pub fn post_load(&mut self, _version_id: u32) -> Result<(), ()> {
 pub unsafe extern "C" fn pl011_event(opaque: *mut c_void, event: QEMUChrEvent) {
     unsafe {
         debug_assert!(!opaque.is_null());
-        let mut state = NonNull::new_unchecked(opaque.cast::<PL011State>());
-        state.as_mut().event(event)
+        let state = NonNull::new_unchecked(opaque.cast::<PL011State>());
+        state.as_ref().event(event)
     }
 }
 
@@ -700,7 +700,7 @@ pub fn post_load(&mut self, _version_id: u32) -> Result<(), ()> {
 }
 
 #[repr(C)]
-#[derive(Debug, qemu_api_macros::Object)]
+#[derive(qemu_api_macros::Object)]
 /// PL011 Luminary device model.
 pub struct PL011Luminary {
     parent_obj: ParentField<PL011State>,
rust/hw/char/pl011/src/device_class.rs +4 -4
index e25645ceb0d..06178778a8e 100644
@@ -6,7 +6,7 @@
 use std::os::raw::{c_int, c_void};
 
 use qemu_api::{
-    bindings::*, c_str, vmstate_clock, vmstate_fields, vmstate_of, vmstate_struct,
+    bindings::*, c_str, prelude::*, vmstate_clock, vmstate_fields, vmstate_of, vmstate_struct,
     vmstate_subsections, vmstate_unused, zeroable::Zeroable,
 };
 
@@ -35,8 +35,8 @@ extern "C" fn pl011_clock_needed(opaque: *mut c_void) -> bool {
 extern "C" fn pl011_post_load(opaque: *mut c_void, version_id: c_int) -> c_int {
     unsafe {
         debug_assert!(!opaque.is_null());
-        let mut state = NonNull::new_unchecked(opaque.cast::<PL011State>());
-        let result = state.as_mut().post_load(version_id as u32);
+        let state = NonNull::new_unchecked(opaque.cast::<PL011State>());
+        let result = state.as_ref().post_load(version_id as u32);
         if result.is_err() {
             -1
         } else {
@@ -76,7 +76,7 @@ extern "C" fn pl011_post_load(opaque: *mut c_void, version_id: c_int) -> c_int {
     post_load: Some(pl011_post_load),
     fields: vmstate_fields! {
         vmstate_unused!(core::mem::size_of::<u32>()),
-        vmstate_struct!(PL011State, regs, &VMSTATE_PL011_REGS, PL011Registers),
+        vmstate_struct!(PL011State, regs, &VMSTATE_PL011_REGS, BqlRefCell<PL011Registers>),
     },
     subsections: vmstate_subsections! {
         VMSTATE_PL011_CLOCK
rust/hw/char/pl011/src/memory_ops.rs +1 -1
index c4e8599ba43..8f66c8d492c 100644
@@ -26,7 +26,7 @@
 unsafe extern "C" fn pl011_read(opaque: *mut c_void, addr: hwaddr, size: c_uint) -> u64 {
     assert!(!opaque.is_null());
     let mut state = unsafe { NonNull::new_unchecked(opaque.cast::<PL011State>()) };
-    let val = unsafe { state.as_mut().read(addr, size) };
+    let val = unsafe { state.as_mut() }.read(addr, size);
     match val {
         std::ops::ControlFlow::Break(val) => val,
         std::ops::ControlFlow::Continue(val) => {
Signature · 1 line
2.47.1
Reviewed-by on v1 7/10
#19 lore raw

Re: [PATCH 07/10] rust: pl011: wrap registers with BqlRefCell

Quoted 21 lines · Paolo Bonzini

Date: Fri, 17 Jan 2025 10:26:54 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 07/10] rust: pl011: wrap registers with BqlRefCell
X-Mailer: git-send-email 2.47.1

This is a step towards making memory ops use a shared reference to the device type; it's not yet possible due to the calls to character device functions.

---
 rust/hw/char/pl011/src/device.rs       | 38 +++++++++++++-------------
 rust/hw/char/pl011/src/device_class.rs |  8 +++---
 rust/hw/char/pl011/src/memory_ops.rs   |  2 +-
 3 files changed, 24 insertions(+), 24 deletions(-)
rust/hw/char/pl011/src/device.rs +0 -0
index 476abe765a9..1d3da59e481 100644

rust/hw/char/pl011/src/device.rs pub struct PL011Registers { · line 105

Quoted 4 lines
rust/hw/char/pl011/src/device.rs +0 -1
@@ -102,14 +102,14 @@ pub struct PL011Registers {
 }
 
 #[repr(C)]
-#[derive(Debug, qemu_api_macros::Object, qemu_api_macros::offsets)]

This is the issue I also met, so why not drive "Debug" for BqlRefCell?

I tried to do this in [*]. Do we need to reconsider this?

[*]: https://lore.kernel.org/qemu-devel/[email protected]/

rust/hw/char/pl011/src/device.rs pub struct PL011Registers { · line 112

Quoted 9 lines
rust/hw/char/pl011/src/device.rs +2 -1
+#[derive(qemu_api_macros::Object, qemu_api_macros::offsets)]
 /// PL011 Device Model in QEMU
 pub struct PL011State {
     pub parent_obj: ParentField<SysBusDevice>,
     pub iomem: MemoryRegion,
     #[doc(alias = "chr")]
     pub char_backend: CharBackend,
-    pub regs: PL011Registers,
+    pub regs: BqlRefCell<PL011Registers>,

This is a good example on the usage of BqlRefCell!

//! BqlRefCell is best suited for data that is primarily accessed by the //! device's own methods, where multiple reads and writes can be grouped within //! a single borrow and a mutable reference can be passed around. "

rust/hw/char/pl011/src/device.rs fn post_init(&self) { · line 533

Quoted 8 lines
rust/hw/char/pl011/src/device.rs +1 -0
     /// QEMU interrupts
     ///
     /// ```text
@@ -530,8 +530,8 @@ fn post_init(&self) {
         }
     }
 
+    #[allow(clippy::needless_pass_by_ref_mut)]

How did you trigger this lint error? I switched to 1.84 and didn't get any errors (I noticed that 1.84 fixed the issue of ignoring self [*], but it still doesn't seem to work on my side).

[*]: https://github.com/rust-lang/rust-clippy/pull/12693

Quoted 14 lines
rust/hw/char/pl011/src/device.rs +1 -2
     pub fn read(&mut self, offset: hwaddr, _size: u32) -> ControlFlow<u64, u64> {
-        let regs = &mut self.regs;
         match RegisterOffset::try_from(offset) {
             Err(v) if (0x3f8..0x400).contains(&(v >> 2)) => {
                 let device_id = self.get_class().device_id;
@@ -541,7 +541,7 @@ pub fn read(&mut self, offset: hwaddr, _size: u32) -> ControlFlow<u64, u64> {
                 // qemu_log_mask(LOG_GUEST_ERROR, "pl011_read: Bad offset 0x%x\n", (int)offset);
                 ControlFlow::Break(0)
             }
-            Ok(field) => match regs.read(field) {
+            Ok(field) => match self.regs.borrow_mut().read(field) {
                 ControlFlow::Break(value) => ControlFlow::Break(value.into()),
                 ControlFlow::Continue(value) => {
                     self.update();

[snip]

rust/hw/char/pl011/src/device.rs pub fn realize(&mut self) { · line 605

Quoted 4 lines
rust/hw/char/pl011/src/device.rs +0 -0
@@ -603,19 +603,19 @@ pub fn realize(&mut self) {
     }
 
     pub fn reset(&mut self) {

In principle, this place should also trigger needless_pass_by_ref_mut.

Quoted 3 lines
rust/hw/char/pl011/src/device.rs +1 -1
-        self.regs.reset();
+        self.regs.borrow_mut().reset();
     }

[snip]

rust/hw/char/pl011/src/device.rs pub fn post_load(&mut self, _version_id: u32) -> Result<(), ()> { · line 660

Quoted 6 lines
rust/hw/char/pl011/src/device.rs +1 -1
@@ -657,10 +657,10 @@ pub fn post_load(&mut self, _version_id: u32) -> Result<(), ()> {
 pub unsafe extern "C" fn pl011_receive(opaque: *mut c_void, buf: *const u8, size: c_int) {
     unsafe {
         debug_assert!(!opaque.is_null());
-        let mut state = NonNull::new_unchecked(opaque.cast::<PL011State>());
+        let state = NonNull::new_unchecked(opaque.cast::<PL011State>());

Perhaps we can use NonNull::new and unwrap()? Then debug_assert! is unnecessary.

let state = unsafe { NonNull::new(opaque.cast::<PL011State>()).unwrap().as_ref() };

rust/hw/char/pl011/src/device.rs pub fn post_load(&mut self, _version_id: u32) -> Result<(), ()> { · line 674

Quoted 10 lines
rust/hw/char/pl011/src/device.rs +1 -1
         if size > 0 {
             debug_assert!(!buf.is_null());
-            state.as_mut().receive(u32::from(buf.read_volatile()));
+            state.as_ref().receive(u32::from(buf.read_volatile()));
         }
     }
 }
@@ -673,8 +673,8 @@ pub fn post_load(&mut self, _version_id: u32) -> Result<(), ()> {
 pub unsafe extern "C" fn pl011_event(opaque: *mut c_void, event: QEMUChrEvent) {
     unsafe {

I think we could narrow the unsafe scope next.

Quoted 7 lines
rust/hw/char/pl011/src/device.rs +2 -2
         debug_assert!(!opaque.is_null());
-        let mut state = NonNull::new_unchecked(opaque.cast::<PL011State>());
-        state.as_mut().event(event)
+        let state = NonNull::new_unchecked(opaque.cast::<PL011State>());
+        state.as_ref().event(event)
     }
 }

[snip]

rust/hw/char/pl011/src/memory_ops.rs line 29

Quoted 10 lines
rust/hw/char/pl011/src/memory_ops.rs +1 -1
index c4e8599ba43..8f66c8d492c 100644
@@ -26,7 +26,7 @@
 unsafe extern "C" fn pl011_read(opaque: *mut c_void, addr: hwaddr, size: c_uint) -> u64 {
     assert!(!opaque.is_null());
     let mut state = unsafe { NonNull::new_unchecked(opaque.cast::<PL011State>()) };
-    let val = unsafe { state.as_mut().read(addr, size) };
+    let val = unsafe { state.as_mut() }.read(addr, size);

Nice cleanup.

rust/hw/char/pl011/src/memory_ops.rs line 32

Quoted 4 lines
rust/hw/char/pl011/src/memory_ops.rs +0 -0
     match val {
         std::ops::ControlFlow::Break(val) => val,
         std::ops::ControlFlow::Continue(val) => {

Nice transition! This is an important step. (Even my comments above didn't affect the main work of the patch :-) )

So,

#20 lore raw

Re: [PATCH 07/10] rust: pl011: wrap registers with BqlRefCell

Il gio 23 gen 2025, 06:27 Zhao Liu <[email protected]> ha scritto:

Quoted 25 lines · Paolo Bonzini

rust/hw/char/pl011/src/

Quoted 17 lines

Date: Fri, 17 Jan 2025 10:26:54 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 07/10] rust: pl011: wrap registers with BqlRefCell
X-Mailer: git-send-email 2.47.1

This is a step towards making memory ops use a shared reference to the device type; it's not yet possible due to the calls to character device functions.

---
 rust/hw/char/pl011/src/device.rs       | 38 +++++++++++++-------------
 rust/hw/char/pl011/src/device_class.rs |  8 +++---
 rust/hw/char/pl011/src/memory_ops.rs   |  2 +-
 3 files changed, 24 insertions(+), 24 deletions(-)
rust/hw/char/pl011/src/ renamed from rust/hw/char/pl011/src/device.rs +0 -0

device.rs

Quoted 6 lines

index 476abe765a9..1d3da59e481 100644

rust/hw/char/pl011/src/device.rs +0 -0
@@ -102,14 +102,14 @@ pub struct PL011Registers {
 }
 
Quoted 5 lines

rust/hw/char/pl011/src/device.rs pub struct PL011Registers { · line 105

Quoted 2 lines
rust/hw/char/pl011/src/device.rs +0 -1
 #[repr(C)]
-#[derive(Debug, qemu_api_macros::Object, qemu_api_macros::offsets)]

This is the issue I also met, so why not drive "Debug" for BqlRefCell?

Because it is not entirely possible to do it safely--there could be outstanding borrows that break invariants and cause debug() to fail. Maybe we could implement it on BqlRefCell<PL011Registers> with a custom derive macro...

RefCell doesn't implement Debug either for the same reason.

I tried to do this in [*]. Do we need to reconsider this?

Quoted 14 lines

[*]:
https://lore.kernel.org/qemu-devel/[email protected]/

rust/hw/char/pl011/src/device.rs pub struct PL011Registers { · line 112

Quoted 9 lines
rust/hw/char/pl011/src/device.rs +2 -1
+#[derive(qemu_api_macros::Object, qemu_api_macros::offsets)]
 /// PL011 Device Model in QEMU
 pub struct PL011State {
     pub parent_obj: ParentField<SysBusDevice>,
     pub iomem: MemoryRegion,
     #[doc(alias = "chr")]
     pub char_backend: CharBackend,
-    pub regs: PL011Registers,
+    pub regs: BqlRefCell<PL011Registers>,
Quoted 7 lines

This is a good example on the usage of BqlRefCell!

//! BqlRefCell is best suited for data that is primarily accessed by the //! device's own methods, where multiple reads and writes can be grouped within
//! a single borrow and a mutable reference can be passed around. "

Yeah, the comment was inspired by this usage and not vice versa. :D

Quoted 7 lines
     /// QEMU interrupts
Quoted 6 lines
rust/hw/char/pl011/src/device.rs +0 -0
     ///
     /// ```text
@@ -530,8 +530,8 @@ fn post_init(&self) {
         }
     }
 
Quoted 6 lines

rust/hw/char/pl011/src/device.rs fn post_init(&self) { · line 533

Quoted 1 line
rust/hw/char/pl011/src/device.rs +1 -0
+    #[allow(clippy::needless_pass_by_ref_mut)]

How did you trigger this lint error? I switched to 1.84 and didn't get any errors (I noticed that 1.84 fixed the issue of ignoring self [*], but it still doesn't seem to work on my side).

I will double check. But I do see that there is no mut access inside, at least not until the qemu_chr_fe_accept_input() is moved here. Unfortunately until all MemoryRegion and CharBackend bindings are available the uses of &mut and the casts to *mut are really really wonky.

(On the other hand it wouldn't be possible to have a grip on the qemu_api code without users).

Paolo

Quoted 7 lines
(quoted diff) +0 -0
@@ -603,19 +603,19 @@ pub fn realize(&mut self) {
 >      }

rust/hw/char/pl011/src/device.rs pub fn realize(&mut self) { · line 605

Quoted 2 lines
rust/hw/char/pl011/src/device.rs +0 -0
     pub fn reset(&mut self) {

In principle, this place should also trigger needless_pass_by_ref_mut.

Yes but clippy hides it because this function is assigned to a function pointer const. At least I think so---the point is more generally that you can't change &mut to & without breaking compilation.

Quoted 13 lines
Quoted 3 lines
rust/hw/char/pl011/src/device.rs +1 -1
-        self.regs.reset();
+        self.regs.borrow_mut().reset();
     }

[snip]

rust/hw/char/pl011/src/device.rs pub fn post_load(&mut self, _version_id: u32) ->

Quoted 1 line
rust/hw/char/pl011/src/device.rs +0 -0
@@ -657,10 +657,10 @@ pub fn post_load(&mut self, _version_id: u32) ->

Result<(), ()> {

rust/hw/char/pl011/src/device.rs pub fn post_load(&mut self, _version_id: u32) -> · line 657

Quoted 1 line
rust/hw/char/pl011/src/device.rs +0 -0
 pub unsafe extern "C" fn pl011_receive(opaque: *mut c_void, buf: *const

u8, size: c_int) {

rust/hw/char/pl011/src/device.rs pub fn post_load(&mut self, _version_id: u32) -> Result<(), ()> {

Quoted 3 lines
rust/hw/char/pl011/src/device.rs +0 -1
     unsafe {
         debug_assert!(!opaque.is_null());
-        let mut state =
Quoted 9 lines

NonNull::new_unchecked(opaque.cast::<PL011State>());

rust/hw/char/pl011/src/device.rs pub fn post_load(&mut self, _version_id: u32) -> · line 660

Quoted 1 line
rust/hw/char/pl011/src/device.rs +1 -0
+        let state = NonNull::new_unchecked(opaque.cast::<PL011State>());

Perhaps we can use NonNull::new and unwrap()? Then debug_assert! is unnecessary.

let state = unsafe { NonNull::new(opaque.cast::<PL011State>()).unwrap().as_ref() };

Yeah, though that's preexisting and it's code that will go away relatively soon. I tried to minimize unrelated changes and changes to these temporary unsafe functions, but in some cases there were some that sneaked in.

Let me know what you prefer.

Paolo

#21 lore raw

Re: [PATCH 07/10] rust: pl011: wrap registers with BqlRefCell

Quoted 6 lines
Quoted 5 lines
Quoted 2 lines

#[repr(C)]
-#[derive(Debug, qemu_api_macros::Object, qemu_api_macros::offsets)]

This is the issue I also met, so why not drive "Debug" for BqlRefCell?

Quoted 6 lines

Because it is not entirely possible to do it safely--there could be outstanding borrows that break invariants and cause debug() to fail. Maybe we could implement it on BqlRefCell<PL011Registers> with a custom derive macro...

RefCell doesn't implement Debug either for the same reason.

Thank you for the clarification, I understand now (I was indeed puzzled as to why RefCell didn't do this).

Quoted 39 lines

I tried to do this in [*]. Do we need to reconsider this?

Quoted 14 lines

[*]:
https://lore.kernel.org/qemu-devel/[email protected]/

rust/hw/char/pl011/src/device.rs pub struct PL011Registers { · line 112

Quoted 9 lines
rust/hw/char/pl011/src/device.rs +2 -1
+#[derive(qemu_api_macros::Object, qemu_api_macros::offsets)]
 /// PL011 Device Model in QEMU
 pub struct PL011State {
     pub parent_obj: ParentField<SysBusDevice>,
     pub iomem: MemoryRegion,
     #[doc(alias = "chr")]
     pub char_backend: CharBackend,
-    pub regs: PL011Registers,
+    pub regs: BqlRefCell<PL011Registers>,
Quoted 7 lines

This is a good example on the usage of BqlRefCell!

//! BqlRefCell is best suited for data that is primarily accessed by the //! device's own methods, where multiple reads and writes can be grouped within
//! a single borrow and a mutable reference can be passed around. "

Yeah, the comment was inspired by this usage and not vice versa. :D

Quoted 7 lines
     /// QEMU interrupts
Quoted 6 lines
     ///
     /// ```text
(quoted diff) +0 -0
@@ -530,8 +530,8 @@ fn post_init(&self) {
         }
     }
 
Quoted 6 lines

rust/hw/char/pl011/src/device.rs fn post_init(&self) { · line 533

Quoted 1 line
rust/hw/char/pl011/src/device.rs +1 -0
+    #[allow(clippy::needless_pass_by_ref_mut)]

How did you trigger this lint error? I switched to 1.84 and didn't get any errors (I noticed that 1.84 fixed the issue of ignoring self [*], but it still doesn't seem to work on my side).

Quoted 4 lines

I will double check. But I do see that there is no mut access inside, at least not until the qemu_chr_fe_accept_input() is moved here. Unfortunately until all MemoryRegion and CharBackend bindings are available the uses of &mut and the casts to *mut are really really wonky.

yes, I agree here we should remove mut :-). (if needless_pass_by_ref_mut doesn't work on this place, I think we can drop it.)

Quoted 8 lines

(On the other hand it wouldn't be possible to have a grip on the qemu_api code without users).

Paolo

Quoted 3 lines
(quoted diff) +0 -0
@@ -603,19 +603,19 @@ pub fn realize(&mut self) {
 >      }
Quoted 1 line
Quoted 8 lines
Quoted 4 lines
Quoted 1 line
     pub fn reset(&mut self) {

In principle, this place should also trigger needless_pass_by_ref_mut.

Yes but clippy hides it because this function is assigned to a function pointer const. At least I think so---the point is more generally that you can't change &mut to & without breaking compilation.

Make sense!

Quoted 23 lines
Quoted 13 lines
Quoted 3 lines
rust/hw/char/pl011/src/device.rs +1 -1
-        self.regs.reset();
+        self.regs.borrow_mut().reset();
     }

[snip]

Review pub fn post_load(&mut self, _version_id: u32) ->

Quoted 1 line
(quoted diff) +0 -0
@@ -657,10 +657,10 @@ pub fn post_load(&mut self, _version_id: u32) ->

Result<(), ()> {

Review pub fn post_load(&mut self, _version_id: u32) -> · line 657

Quoted 1 line
(quoted diff) +0 -0
 pub unsafe extern "C" fn pl011_receive(opaque: *mut c_void, buf: *const

u8, size: c_int) {

rust/hw/char/pl011/src/device.rs pub fn post_load(&mut self, _version_id: u32) -> Result<(), ()> {

Quoted 3 lines
rust/hw/char/pl011/src/device.rs +0 -1
     unsafe {
         debug_assert!(!opaque.is_null());
-        let mut state =
Quoted 9 lines

NonNull::new_unchecked(opaque.cast::<PL011State>());

Review pub fn post_load(&mut self, _version_id: u32) -> · line 660

Quoted 1 line
(quoted diff) +1 -0
+        let state = NonNull::new_unchecked(opaque.cast::<PL011State>());

Perhaps we can use NonNull::new and unwrap()? Then debug_assert! is unnecessary.

let state = unsafe { NonNull::new(opaque.cast::<PL011State>()).unwrap().as_ref() };

Quoted 6 lines

Yeah, though that's preexisting and it's code that will go away relatively soon. I tried to minimize unrelated changes and changes to these temporary unsafe functions, but in some cases there were some that sneaked in.

Let me know what you prefer.

I prefer to use NonNull::new and unwrap(). Too much assert() pattern is not user-friendly. I also think it's unnecessary to change NonNull interface in this patch, we can see what's left when you're done with the most QAPI work.

Thanks,
Zhao

#22 lore raw

Re: [PATCH 07/10] rust: pl011: wrap registers with BqlRefCell

Il gio 23 gen 2025, 10:05 Zhao Liu <[email protected]> ha scritto:

Quoted 9 lines
Quoted 2 lines

I will double check. But I do see that there is no mut access inside, at least not until the qemu_chr_fe_accept_input() is moved here.

Unfortunately

Quoted 2 lines

until all MemoryRegion and CharBackend bindings are available the uses of &mut and the casts to *mut are really really wonky.

yes, I agree here we should remove mut :-). (if needless_pass_by_ref_mut doesn't work on this place, I think we can drop it.)

&mut is not needed here, but it is needed in write(). After accept_input() is moved to out of memory_ops.rs, the #[allow] can be removed.

I will do that in v2.

Paolo

Quoted 65 lines
Quoted 11 lines

(On the other hand it wouldn't be possible to have a grip on the qemu_api code without users).

Paolo

Quoted 6 lines
(quoted diff) +0 -0
@@ -603,19 +603,19 @@ pub fn realize(&mut self) {
 >      }
Quoted 2 lines
     pub fn reset(&mut self) {

In principle, this place should also trigger

needless_pass_by_ref_mut.

Quoted 5 lines
Quoted 1 line

Yes but clippy hides it because this function is assigned to a function pointer const. At least I think so---the point is more generally that you can't change &mut to & without breaking compilation.

Make sense!

Quoted 7 lines
Quoted 7 lines
Quoted 3 lines
rust/hw/char/pl011/src/device.rs +1 -1
-        self.regs.reset();
+        self.regs.borrow_mut().reset();
     }

[snip]

Review pub fn post_load(&mut self, _version_id: u32)

Quoted 1 line
(quoted diff) +0 -0
@@ -657,10 +657,10 @@ pub fn post_load(&mut self, _version_id: u32)

->

Quoted 2 lines
Quoted 2 lines

Result<(), ()> {

Quoted 1 line
(quoted diff) +0 -0
 pub unsafe extern "C" fn pl011_receive(opaque: *mut c_void, buf:

*const

Quoted 6 lines
Quoted 6 lines

u8, size: c_int) {

rust/hw/char/pl011/src/device.rs pub fn post_load(&mut self, _version_id: u32) -> Result<(), ()> {

Quoted 3 lines
rust/hw/char/pl011/src/device.rs +0 -1
     unsafe {
         debug_assert!(!opaque.is_null());
-        let mut state =

NonNull::new_unchecked(opaque.cast::<PL011State>());

Quoted 1 line
(quoted diff) +1 -0
+        let state =

NonNull::new_unchecked(opaque.cast::<PL011State>());

Quoted 9 lines
Quoted 7 lines

Perhaps we can use NonNull::new and unwrap()? Then debug_assert! is unnecessary.

let state = unsafe { NonNull::new(opaque.cast::<PL011State>()).unwrap().as_ref() };

Yeah, though that's preexisting and it's code that will go away

relatively

Quoted 1 line

soon. I tried to minimize unrelated changes and changes to these

temporary

Quoted 4 lines

unsafe functions, but in some cases there were some that sneaked in.

Let me know what you prefer.

I prefer to use NonNull::new and unwrap(). Too much assert() pattern is not user-friendly. I also think it's unnecessary to change NonNull interface in this patch, we can see what's left when you're done with the most QAPI work.

Thanks,
Zhao

#23 lore raw

PATCH 8/10 rust: pl011: remove duplicate definitions

In reply to Paolo Bonzini

Unify the "Interrupt" enum and the "INT_*" constants with a struct that contains the bits. The "int_level" and "int_enabled" fields could use a crate such as "bitflags".

---
 rust/hw/char/pl011/src/device.rs | 36 ++++++++++++-------------
 rust/hw/char/pl011/src/lib.rs    | 46 +++++++++++---------------------
 2 files changed, 33 insertions(+), 49 deletions(-)
rust/hw/char/pl011/src/device.rs +18 -18
index 1d3da59e481..6ecbfb9ac84 100644
@@ -183,7 +183,7 @@ pub(self) fn read(&mut self, offset: RegisterOffset) -> ControlFlow<u32, u32> {
                     self.flags.set_receive_fifo_empty(true);
                 }
                 if self.read_count + 1 == self.read_trigger {
-                    self.int_level &= !registers::INT_RX;
+                    self.int_level &= !Interrupt::RX.0;
                 }
                 // Update error bits.
                 self.receive_status_error_clear.set_from_data(c);
@@ -232,7 +232,7 @@ pub(self) fn write(
                 }
                 // interrupts always checked
                 let _ = self.loopback_tx(value);
-                self.int_level |= registers::INT_TX;
+                self.int_level |= Interrupt::TX.0;
                 return true;
             }
             RSR => {
@@ -356,19 +356,19 @@ fn loopback_mdmctrl(&mut self) -> bool {
         // Change interrupts based on updated FR
         let mut il = self.int_level;
 
-        il &= !Interrupt::MS;
+        il &= !Interrupt::MS.0;
 
         if self.flags.data_set_ready() {
-            il |= Interrupt::DSR as u32;
+            il |= Interrupt::DSR.0;
         }
         if self.flags.data_carrier_detect() {
-            il |= Interrupt::DCD as u32;
+            il |= Interrupt::DCD.0;
         }
         if self.flags.clear_to_send() {
-            il |= Interrupt::CTS as u32;
+            il |= Interrupt::CTS.0;
         }
         if self.flags.ring_indicator() {
-            il |= Interrupt::RI as u32;
+            il |= Interrupt::RI.0;
         }
         self.int_level = il;
         true
@@ -446,7 +446,7 @@ pub fn put_fifo(&mut self, value: u32) -> bool {
         }
 
         if self.read_count == self.read_trigger {
-            self.int_level |= registers::INT_RX;
+            self.int_level |= Interrupt::RX.0;
             return true;
         }
         false
@@ -622,16 +622,16 @@ pub fn post_load(&self, _version_id: u32) -> Result<(), ()> {
 /// Which bits in the interrupt status matter for each outbound IRQ line ?
 const IRQMASK: [u32; 6] = [
     /* combined IRQ */
-    Interrupt::E
-        | Interrupt::MS
-        | Interrupt::RT as u32
-        | Interrupt::TX as u32
-        | Interrupt::RX as u32,
-    Interrupt::RX as u32,
-    Interrupt::TX as u32,
-    Interrupt::RT as u32,
-    Interrupt::MS,
-    Interrupt::E,
+    Interrupt::E.0
+        | Interrupt::MS.0
+        | Interrupt::RT.0
+        | Interrupt::TX.0
+        | Interrupt::RX.0,
+    Interrupt::RX.0,
+    Interrupt::TX.0,
+    Interrupt::RT.0,
+    Interrupt::MS.0,
+    Interrupt::E.0,
 ];
 
 /// # Safety
rust/hw/char/pl011/src/lib.rs +15 -31

60 lines not on this page · raw message

Signature · 1 line
2.47.1
Reviewed-by on v1 8/10
#24 lore raw

Re: [PATCH 08/10] rust: pl011: remove duplicate definitions

Quoted 9 lines · Paolo Bonzini

Date: Fri, 17 Jan 2025 10:26:55 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 08/10] rust: pl011: remove duplicate definitions
X-Mailer: git-send-email 2.47.1

Unify the "Interrupt" enum and the "INT_*" constants with a struct that contains the bits. The "int_level" and "int_enabled" fields could use a crate such as "bitflags".

Quoted 6 lines
---
 rust/hw/char/pl011/src/device.rs | 36 ++++++++++++-------------
 rust/hw/char/pl011/src/lib.rs    | 46 +++++++++++---------------------
 2 files changed, 33 insertions(+), 49 deletions(-)
#25 lore raw

PATCH 9/10 rust: pl011: pull device-specific code out of MemoryRegionOps callbacks

In reply to Paolo Bonzini

read() can now return a simple u64.

---
 rust/hw/char/pl011/src/device.rs     | 16 +++++++++-------
 rust/hw/char/pl011/src/memory_ops.rs | 23 ++++-------------------
 2 files changed, 13 insertions(+), 26 deletions(-)
rust/hw/char/pl011/src/device.rs +9 -7
index 6ecbfb9ac84..af0f451deb2 100644
@@ -171,7 +171,7 @@ impl PL011Registers {
     pub(self) fn read(&mut self, offset: RegisterOffset) -> ControlFlow<u32, u32> {
         use RegisterOffset::*;
 
-        std::ops::ControlFlow::Break(match offset {
+        ControlFlow::Break(match offset {
             DR => {
                 self.flags.set_receive_fifo_full(false);
                 let c = self.read_fifo[self.read_pos];
@@ -530,22 +530,24 @@ fn post_init(&self) {
         }
     }
 
-    #[allow(clippy::needless_pass_by_ref_mut)]
-    pub fn read(&mut self, offset: hwaddr, _size: u32) -> ControlFlow<u64, u64> {
+    pub fn read(&mut self, offset: hwaddr, _size: u32) -> u64 {
         match RegisterOffset::try_from(offset) {
             Err(v) if (0x3f8..0x400).contains(&(v >> 2)) => {
                 let device_id = self.get_class().device_id;
-                ControlFlow::Break(u64::from(device_id[(offset - 0xfe0) >> 2]))
+                u64::from(device_id[(offset - 0xfe0) >> 2])
             }
             Err(_) => {
                 // qemu_log_mask(LOG_GUEST_ERROR, "pl011_read: Bad offset 0x%x\n", (int)offset);
-                ControlFlow::Break(0)
+                0
             }
             Ok(field) => match self.regs.borrow_mut().read(field) {
-                ControlFlow::Break(value) => ControlFlow::Break(value.into()),
+                ControlFlow::Break(value) => value.into(),
                 ControlFlow::Continue(value) => {
                     self.update();
-                    ControlFlow::Continue(value.into())
+                    unsafe {
+                        qemu_chr_fe_accept_input(&mut self.char_backend);
+                    }
+                    value.into()
                 },
             }
         }
rust/hw/char/pl011/src/memory_ops.rs +4 -19
index 8f66c8d492c..95b4df794e4 100644
@@ -26,26 +26,11 @@
 unsafe extern "C" fn pl011_read(opaque: *mut c_void, addr: hwaddr, size: c_uint) -> u64 {
     assert!(!opaque.is_null());
     let mut state = unsafe { NonNull::new_unchecked(opaque.cast::<PL011State>()) };
-    let val = unsafe { state.as_mut() }.read(addr, size);
-    match val {
-        std::ops::ControlFlow::Break(val) => val,
-        std::ops::ControlFlow::Continue(val) => {
-            // SAFETY: self.char_backend is a valid CharBackend instance after it's been
-            // initialized in realize().
-            let cb_ptr = unsafe { core::ptr::addr_of_mut!(state.as_mut().char_backend) };
-            unsafe {
-                qemu_chr_fe_accept_input(cb_ptr);
-            }
-
-            val
-        }
-    }
+    unsafe { state.as_mut() }.read(addr, size)
 }
 
 unsafe extern "C" fn pl011_write(opaque: *mut c_void, addr: hwaddr, data: u64, _size: c_uint) {
-    unsafe {
-        assert!(!opaque.is_null());
-        let mut state = NonNull::new_unchecked(opaque.cast::<PL011State>());
-        state.as_mut().write(addr, data)
-    }
+    assert!(!opaque.is_null());
+    let mut state = unsafe { NonNull::new_unchecked(opaque.cast::<PL011State>()) };
+    unsafe { state.as_mut() }.write(addr, data);
 }
Signature · 1 line
2.47.1
Reviewed-by on v1 9/10
#26 lore raw

Re: [PATCH 09/10] rust: pl011: pull device-specific code out of MemoryRegionOps callbacks

Quoted 6 lines · Paolo Bonzini

Date: Fri, 17 Jan 2025 10:26:56 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 09/10] rust: pl011: pull device-specific code out of
MemoryRegionOps callbacks
X-Mailer: git-send-email 2.47.1

Quoted 8 lines

read() can now return a simple u64.

---
 rust/hw/char/pl011/src/device.rs     | 16 +++++++++-------
 rust/hw/char/pl011/src/memory_ops.rs | 23 ++++-------------------
 2 files changed, 13 insertions(+), 26 deletions(-)
#27 lore raw

PATCH 10/10 rust: qdev: make reset take a shared reference

In reply to Paolo Bonzini

Because register reset is within a borrow_mut() call, reset does not need anymore a mut reference to the PL011State.

---
 rust/hw/char/pl011/src/device.rs | 4 ++--
 rust/qemu-api/src/qdev.rs        | 2 +-
 2 files changed, 3 insertions(+), 3 deletions(-)
rust/hw/char/pl011/src/device.rs +2 -2
index af0f451deb2..019c1617807 100644
@@ -164,7 +164,7 @@ fn vmsd() -> Option<&'static VMStateDescription> {
         Some(&device_class::VMSTATE_PL011)
     }
     const REALIZE: Option<fn(&mut Self)> = Some(Self::realize);
-    const RESET: Option<fn(&mut Self)> = Some(Self::reset);
+    const RESET: Option<fn(&Self)> = Some(Self::reset);
 }
 
 impl PL011Registers {
@@ -604,7 +604,7 @@ pub fn realize(&mut self) {
         }
     }
 
-    pub fn reset(&mut self) {
+    pub fn reset(&self) {
         self.regs.borrow_mut().reset();
     }
 
rust/qemu-api/src/qdev.rs +1 -1
index 686054e737a..4658409bebb 100644
@@ -30,7 +30,7 @@ pub trait DeviceImpl {
     ///
     /// Rust does not yet support the three-phase reset protocol; this is
     /// usually okay for leaf classes.
-    const RESET: Option<fn(&mut Self)> = None;
+    const RESET: Option<fn(&Self)> = None;
 
     /// An array providing the properties that the user can set on the
     /// device.  Not a `const` because referencing statics in constants
Signature · 1 line
2.47.1
Reviewed-by on v1 10/10
#28 lore raw

Re: [PATCH 10/10] rust: qdev: make reset take a shared reference

Quoted 5 lines · Paolo Bonzini

Date: Fri, 17 Jan 2025 10:26:57 +0100
From: Paolo Bonzini <[email protected]>
Subject: [PATCH 10/10] rust: qdev: make reset take a shared reference
X-Mailer: git-send-email 2.47.1

Quoted 9 lines

Because register reset is within a borrow_mut() call, reset does not need anymore a mut reference to the PL011State.

---
 rust/hw/char/pl011/src/device.rs | 4 ++--
 rust/qemu-api/src/qdev.rs        | 2 +-
 2 files changed, 3 insertions(+), 3 deletions(-)