Skip to contentSkip to conversation

migration: Remove VMSTATE_VALIDATE() and VMS_MUST_EXIST

PATCH New Peter Xu 1 participant 10 messages Nov 26 Rust

lore
Share & tools
lore

Peter Xu

author
#0 lore raw

v2 cover migration: Remove VMSTATE_VALIDATE() and VMS_MUST_EXIST

CI: https://gitlab.com/peterx/qemu/-/pipelines/3120617486

v2:
- Patch "hw/gpio/zaurus: Move VMSTATE_VALIDATE() check into post_load_errp()":
- Unwrap vmstate_scoop_validate() [PeterM]
- Patch "rust: Replace vmstate_validate with post_load"
- Replaced by three patches from Zhao's v1 at the beginning as dependency

    https://lore.kernel.org/r/[email protected]

- Patch "arm/machine: Move all VMSTATE_VALIDATE() usages into post_load"
- Move all checks into the cpu_post_load() [PeterM]
- Added one more dependency patch to make cpu_post_load() take errp
- Patch "hpet: Move VMSTATE_VALIDATE() check into post_load"
- NOTE: I didn't touch this patch, assuming what we check doesn't really matter.. I kept it to make it still aligned with Rust change.

This is for QEMU 12.0 material only.

===8<===

Peter Maydell reported an unwanted assertion on source QEMU due to a failed check in VMSTATE_VALIDATE():

https://lore.kernel.org/r/[email protected]

I decided to look at this in a slightly broader range, because I always thought hijacking field_exists() is very error prone and hard to follow, and VMSTATE_VALIDATE() is the only user of it (VMS_MUST_EXIST). Meanwhile it is the only VMSTATE_*() macro that does not carry a real entity of data stream, so it's not really a FIELD, but some checker we added adhoc inline into the VMSD fields. It might be confusing to anyone new reading VMSD code, including myself when reading it first time.

Instead of updating the source behavior, let's directly wipe that code out. I think it's not making a lot of sense doing device state check in save(), because those sanity check should be done in emulation code, not after seding all RAM, which is extremely awkward. post_load() OTOH still makes some sense to sanity check fields, so I moved all VALIDATE there.

Any comment welcomed, thanks.

Peter Xu (6):
pcie/aer: Remove the usage of VMSTATE_VALIDATE() hw/gpio/zaurus: Move VMSTATE_VALIDATE() check into post_load_errp()
hpet: Move VMSTATE_VALIDATE() check into post_load arm/machine: Convert cpu_post_load() to take Error** arm/machine: Move all VMSTATE_VALIDATE() usages into post_load
migration: Drop VMSTATE_VALIDATE() and VMS_MUST_EXIST

Zhao Liu (3):
rust/migration: Allow usize as the length of a varray rust/hpet: Move vmstate_validate!() check into post_load rust/migration: Remove vmstate_validate!() macro and test

 include/migration/vmstate.h       |  11 ---
 hw/gpio/zaurus.c                  |  24 +++--
 hw/pci/pcie_aer.c                 |  40 +++++++--
 hw/timer/hpet.c                   |  18 ++--
 migration/savevm.c                |   5 --
 migration/vmstate.c               |  12 ---
 target/arm/machine.c              | 142 ++++++++++++++----------------
 rust/hw/timer/hpet/src/device.rs  |  45 +++++-----
 rust/migration/src/prelude.rs     |   1 -
 rust/migration/src/vmstate.rs     |  33 +++----
 rust/tests/tests/vmstate_tests.rs |  72 +++++----------
 11 files changed, 181 insertions(+), 222 deletions(-)
Signature · 1 line
2.56.0
author
#1 lore raw

PATCH v2 1/9 rust/migration: Allow usize as the length of a varray

From: Zhao Liu <[email protected]>

Since commit f9f70b50e3eb ("migration: Introduce VMStateStructMember") and commit 1f0b40dccfe5 ("Rmigration: Remove redundant flags"), the length of a varray is no longer tied to a specific integer type.

This makes it possible to use usize type for varray length. It's safe since it is used only to resolve varray lengths in the local vmstate code and is not used for migration.

Thus, implement a "dummy" VMState for usize so that it can provide VARRAY_FLAG, and panic when anyone tries to define VMStateField with usize type (including integers, pointers, [usize; N], Box<usize>, BqlCell<usize>, etc).

In addition, add a test case for such case.

---
 rust/migration/src/vmstate.rs     | 16 ++++++++--
 rust/tests/tests/vmstate_tests.rs | 49 +++++++++++++++++++++++++++++++
 2 files changed, 63 insertions(+), 2 deletions(-)
rust/migration/src/vmstate.rs +14 -2
index 5ed061f2ab..0b05db4e70 100644
@@ -97,8 +97,8 @@ pub unsafe trait VMState {
 
     /// A flag that is added to another field's `VMStateField` to specify the
     /// length's type in a variable-sized array.  If this is not a supported
-    /// type for the length (i.e. if it is not `u8`, `u16`, `u32`), using it
-    /// in a call to [`vmstate_of!`](crate::vmstate_of) will cause a
+    /// type for the length (i.e. if it is not `u8`, `u16`, `u32`, `usize`),
+    /// using it in a call to [`vmstate_of!`](crate::vmstate_of) will cause a
     /// compile-time error.
     #[doc(hidden)] // https://github.com/rust-lang/rust/issues/149635
     const VARRAY_FLAG: VMStateFlags = {
@@ -256,6 +256,18 @@ unsafe impl $crate::vmstate::VMState for $type {
 impl_vmstate_scalar!(vmstate_info_uint64, u64);
 impl_vmstate_scalar!(vmstate_info_timer, util::timer::Timer);
 
+// SAFETY: BASE is never produced (any use of a usize as migrated data will
+// always result in a compile-time error). VARRAY_FLAG only tells the C code to
+// read `size_of::<usize>()` bytes (see `size_of_field_type!`) at the length's
+// offset.
+unsafe impl VMState for usize {
+    #[doc(hidden)] // https://github.com/rust-lang/rust/issues/149635
+    const BASE: VMStateField = {
+        panic!("usize cannot be migrated, use a fixed-size integer type");
+    };
+    const VARRAY_FLAG: VMStateFlags = VMStateFlags::VMS_VARRAY;
+}
+
 #[macro_export]
 macro_rules! impl_vmstate_c_struct {
     ($type:ty, $vmsd:expr) => {
rust/tests/tests/vmstate_tests.rs +49 -0

52 lines not on this page · raw message

Signature · 1 line
2.56.0
author
#2 lore raw

PATCH v2 2/9 rust/hpet: Move vmstate_validate!() check into post_load

In reply to Peter Xu

From: Zhao Liu <[email protected]>

To pave way for removing VMSTATE_VALIDATE() (and vmstate_validate!()), move the usage of hpet into post_load. To make it safer, loading the timers with the num_timers, then only check against the wire number at last.

In addition, drop the test_fn() in the VMStateField of HPETState.timers
- this was duplicated, but now the check in post_load is enough (and test_fn should not be used for validation).

---
 rust/hw/timer/hpet/src/device.rs | 45 ++++++++++++++++----------------
 1 file changed, 23 insertions(+), 22 deletions(-)
rust/hw/timer/hpet/src/device.rs +23 -22
index 89ba7a5c4d..c7a2b7f6c2 100644
@@ -934,10 +934,15 @@ fn pre_save(&self) -> Result<(), migration::Infallible> {
         Ok(())
     }
 
-    fn post_load(&self, _version_id: u8) -> Result<(), migration::Infallible> {
+    fn post_load(&self, _version_id: u8) -> Result<(), migration::InvalidError> {
         let mut regs = self.regs.borrow_mut();
         let cnt = regs.counter;
 
+        /* FIXME: use post_load_errp() to print error message. */
+        if !self.validate_num_timers() {
+            return Err(migration::InvalidError);
+        }
+
         for tn_regs in regs.tn_regs.iter_mut().take(self.num_timers) {
             tn_regs.update_cmp64(cnt);
             tn_regs.last = CLOCK_VIRTUAL.get_ns() - NANOSECONDS_PER_SECOND;
@@ -956,7 +961,7 @@ fn is_offset_needed(&self) -> bool {
         self.regs.borrow().is_hpet_enabled()
     }
 
-    fn validate_num_timers(&self, _version_id: u8) -> bool {
+    fn validate_num_timers(&self) -> bool {
         self.num_timers == self.num_timers_save.get().into()
     }
 }
@@ -1082,8 +1087,6 @@ fn restore_migrated_state(
 
 impl_vmstate_struct!(HPETTimerMigration, VMSTATE_HPET_TIMER);
 
-const VALIDATE_TIMERS_NAME: &CStr = c"num_timers must match";
-
 // HPETRegistersMigration is generated by ToMigrationState macro.
 impl_vmstate_struct!(
     HPETRegistersMigration,
@@ -1099,24 +1102,22 @@ fn restore_migrated_state(
         .build()
 );
 
-const VMSTATE_HPET: VMStateDescription<HPETState> =
-    VMStateDescriptionBuilder::<HPETState>::new()
-        .name(c"hpet")
-        .version_id(2)
-        .minimum_version_id(2)
-        .pre_save(&HPETState::pre_save)
-        .post_load(&HPETState::post_load)
-        .fields(vmstate_fields! {
-            vmstate_of!(HPETState, regs),
-            vmstate_of!(HPETState, num_timers_save),
-            vmstate_validate!(HPETState, VALIDATE_TIMERS_NAME, HPETState::validate_num_timers),
-            vmstate_of!(HPETState, timers[0 .. num_timers_save], HPETState::validate_num_timers).with_version_id(0),
-        })
-        .subsections(vmstate_subsections!(
-            VMSTATE_HPET_RTC_IRQ_LEVEL,
-            VMSTATE_HPET_OFFSET,
-        ))
-        .build();
+const VMSTATE_HPET: VMStateDescription<HPETState> = VMStateDescriptionBuilder::<HPETState>::new()
+    .name(c"hpet")
+    .version_id(2)
+    .minimum_version_id(2)
+    .pre_save(&HPETState::pre_save)
+    .post_load(&HPETState::post_load)
+    .fields(vmstate_fields! {
+        vmstate_of!(HPETState, regs),
+        vmstate_of!(HPETState, num_timers_save),
+        vmstate_of!(HPETState, timers[0 .. num_timers]).with_version_id(0),
+    })
+    .subsections(vmstate_subsections!(
+        VMSTATE_HPET_RTC_IRQ_LEVEL,
+        VMSTATE_HPET_OFFSET,
+    ))
+    .build();
 
 impl DeviceImpl for HPETState {
     const VMSTATE: Option<VMStateDescription<Self>> = Some(VMSTATE_HPET);
Signature · 1 line
2.56.0
author
#3 lore raw

PATCH v2 3/9 rust/migration: Remove vmstate_validate!() macro and test

In reply to Peter Xu

From: Zhao Liu <[email protected]>

We have moved all users (in Rust side) to other API, now they're never used.

After the related test (originally FOOD) was removed, rename FOOE to new FOOD test.

---
 rust/migration/src/prelude.rs     |  1 -
 rust/migration/src/vmstate.rs     | 17 ------
 rust/tests/tests/vmstate_tests.rs | 93 +++----------------------------
 3 files changed, 8 insertions(+), 103 deletions(-)
rust/migration/src/prelude.rs +0 -1
index 797e7ec59d..e2cbbda43e 100644
@@ -16,4 +16,3 @@
 pub use crate::vmstate_of;
 pub use crate::vmstate_subsections;
 pub use crate::vmstate_unused;
-pub use crate::vmstate_validate;
rust/migration/src/vmstate.rs +0 -17
index 0b05db4e70..ec8b712cbf 100644
@@ -384,23 +384,6 @@ macro_rules! vmstate_fields {
     }}
 }
 
-#[doc(alias = "VMSTATE_VALIDATE")]
-#[macro_export]
-macro_rules! vmstate_validate {
-    ($struct_name:ty, $test_name:expr, $test_fn:expr $(,)?) => {
-        $crate::bindings::VMStateField {
-            name: ::std::ffi::CStr::as_ptr($test_name),
-            field_exists: $crate::vmstate_exist_fn!($struct_name, $test_fn),
-            flags: $crate::bindings::VMStateFlags(
-                $crate::bindings::VMStateFlags::VMS_MUST_EXIST.0
-                    | $crate::bindings::VMStateFlags::VMS_NO_STATE.0,
-            ),
-            num: 0, // 0 elements: no data, only run test_fn callback
-            ..::common::zeroable::Zeroable::ZERO
-        }
-    };
-}
-
 /// Helper macro to allow using a struct in [`vmstate_of!`]
 ///
 /// # Safety
rust/tests/tests/vmstate_tests.rs +8 -85

127 lines not on this page · raw message

Signature · 1 line
2.56.0
author
#4 lore raw

PATCH v2 4/9 pcie/aer: Remove the usage of VMSTATE_VALIDATE()

In reply to Peter Xu

Paving way removing it. We can replace it with a post_load_errp() instead. Tested with migration with "-device ioh3420,id=rp0" against pre-patch, which means migration compatibility is unaffected.

Cc "Michael S. Tsirkin" <[email protected]>
---
 hw/pci/pcie_aer.c | 40 +++++++++++++++++++++++++++++++++++-----
 1 file changed, 35 insertions(+), 5 deletions(-)
hw/pci/pcie_aer.c +35 -5
index 43b14c1f22..87248556d4 100644
@@ -807,21 +807,51 @@ static const VMStateDescription vmstate_pcie_aer_err = {
     }
 };
 
-static bool pcie_aer_state_log_num_valid(void *opaque, int version_id)
-{
-    PCIEAERLog *s = opaque;
+typedef struct {
+    uint16_t v;
+} tmp_u16;
 
+static bool pcie_aer_state_log_num_valid(PCIEAERLog *s)
+{
     return s->log_num <= s->log_max;
 }
 
+static bool pcie_aer_state_log_num_post_load(void *opaque, int version,
+                                             Error **errp)
+{
+    PCIEAERLog *s = container_of(opaque, PCIEAERLog, log_num);
+
+    if (!pcie_aer_state_log_num_valid(s)) {
+        error_setg(errp, "PCIe AER log num too big: log_num > log_max");
+        return false;
+    }
+
+    return true;
+}
+
+static const VMStateDescription vmstate_pcie_aer_log_num = {
+    .name = "PCIE_AER_ERROR_LOG/NUM",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .post_load_errp = pcie_aer_state_log_num_post_load,
+    .fields = (const VMStateField[]) {
+        VMSTATE_UINT16(v, tmp_u16),
+        VMSTATE_END_OF_LIST()
+    }
+};
+
 const VMStateDescription vmstate_pcie_aer_log = {
     .name = "PCIE_AER_ERROR_LOG",
     .version_id = 1,
     .minimum_version_id = 1,
     .fields = (const VMStateField[]) {
-        VMSTATE_UINT16(log_num, PCIEAERLog),
+        /*
+         * Only to use STRUCT for a post_load_errp().  New code should try
+         * to use something look better, e.g. subsections in order.
+         */
+        VMSTATE_STRUCT(log_num, PCIEAERLog, 1,
+                       vmstate_pcie_aer_log_num, uint16_t),
         VMSTATE_UINT16_EQUAL(log_max, PCIEAERLog),
-        VMSTATE_VALIDATE("log_num <= log_max", pcie_aer_state_log_num_valid),
         VMSTATE_STRUCT_VARRAY_POINTER_UINT16(log, PCIEAERLog, log_num,
                               vmstate_pcie_aer_err, PCIEAERErr),
         VMSTATE_END_OF_LIST()
Signature · 1 line
2.56.0
author
#5 lore raw

PATCH v2 5/9 hw/gpio/zaurus: Move VMSTATE_VALIDATE() check into post_load_errp()

In reply to Peter Xu

To pave way for removing VMSTATE_VALIDATE(), remove the use in this file by moving it into the post_load_errp().

---
 hw/gpio/zaurus.c | 24 +++++++++++-------------
 1 file changed, 11 insertions(+), 13 deletions(-)
hw/gpio/zaurus.c +11 -13
index 3cf626a550..ede28f0929 100644
@@ -23,6 +23,7 @@
 #include "qemu/module.h"
 #include "qemu/log.h"
 #include "qom/object.h"
+#include "qapi/error.h"
 
 /* SCOOP devices */
 
@@ -188,12 +189,19 @@ static void scoop_init(Object *obj)
     sysbus_init_mmio(sbd, &s->iomem);
 }
 
-static int scoop_post_load(void *opaque, int version_id)
+static bool scoop_post_load(void *opaque, int version_id, Error **errp)
 {
     ScoopInfo *s = (ScoopInfo *) opaque;
     int i;
     uint32_t level;
 
+    if (s->prev_level & 0xffff0000 ||
+        s->gpio_level & 0xffff0000 ||
+        s->gpio_dir & 0xffff0000) {
+        error_setg(errp, "irq levels are not 16-bits");
+        return false;
+    }
+
     level = s->gpio_level & s->gpio_dir;
 
     for (i = 0; i < 16; i++) {
@@ -202,7 +210,7 @@ static int scoop_post_load(void *opaque, int version_id)
 
     s->prev_level = level;
 
-    return 0;
+    return true;
 }
 
 static bool is_version_0(void *opaque, int version_id)
@@ -210,27 +218,17 @@ static bool is_version_0(void *opaque, int version_id)
     return version_id == 0;
 }
 
-static bool vmstate_scoop_validate(void *opaque, int version_id)
-{
-    ScoopInfo *s = opaque;
-
-    return !(s->prev_level & 0xffff0000) &&
-        !(s->gpio_level & 0xffff0000) &&
-        !(s->gpio_dir & 0xffff0000);
-}
-
 static const VMStateDescription vmstate_scoop_regs = {
     .name = "scoop",
     .version_id = 1,
     .minimum_version_id = 0,
-    .post_load = scoop_post_load,
+    .post_load_errp = scoop_post_load,
     .fields = (const VMStateField[]) {
         VMSTATE_UINT16(status, ScoopInfo),
         VMSTATE_UINT16(power, ScoopInfo),
         VMSTATE_UINT32(gpio_level, ScoopInfo),
         VMSTATE_UINT32(gpio_dir, ScoopInfo),
         VMSTATE_UINT32(prev_level, ScoopInfo),
-        VMSTATE_VALIDATE("irq levels are 16 bit", vmstate_scoop_validate),
         VMSTATE_UINT16(mcr, ScoopInfo),
         VMSTATE_UINT16(cdr, ScoopInfo),
         VMSTATE_UINT16(ccr, ScoopInfo),
Signature · 1 line
2.56.0
author
#6 lore raw

PATCH v2 6/9 hpet: Move VMSTATE_VALIDATE() check into post_load

In reply to Peter Xu

To pave way for removing VMSTATE_VALIDATE(), move the usage of hpet into post_load. To make it safer, loading the timers with the num_timers, then only check against the wire number at last.

Cc "Michael S. Tsirkin" <[email protected]>
Cc Paolo Bonzini <[email protected]>
---
 hw/timer/hpet.c | 18 ++++++++++--------
 1 file changed, 10 insertions(+), 8 deletions(-)
hw/timer/hpet.c +10 -8
index 42285cff76..85cd26a454 100644
@@ -254,25 +254,28 @@ static int hpet_pre_save(void *opaque)
     return 0;
 }
 
-static bool hpet_validate_num_timers(void *opaque, int version_id)
+static bool hpet_validate_num_timers(HPETState *s)
 {
-    HPETState *s = opaque;
-
     return s->num_timers == s->num_timers_save;
 }
 
-static int hpet_post_load(void *opaque, int version_id)
+static bool hpet_post_load(void *opaque, int version_id, Error **errp)
 {
     HPETState *s = opaque;
     int i;
 
+    if (!hpet_validate_num_timers(s)) {
+        error_setg(errp, "num_timers must match");
+        return false;
+    }
+
     for (i = 0; i < s->num_timers; i++) {
         HPETTimer *t = &s->timer[i];
         t->cmp64 = hpet_calculate_cmp64(t, s->hpet_counter, t->cmp);
         t->last = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) - NANOSECONDS_PER_SECOND;
     }
 
-    return 0;
+    return true;
 }
 
 static bool hpet_offset_needed(void *opaque)
@@ -332,14 +335,13 @@ static const VMStateDescription vmstate_hpet = {
     .version_id = 2,
     .minimum_version_id = 2,
     .pre_save = hpet_pre_save,
-    .post_load = hpet_post_load,
+    .post_load_errp = hpet_post_load,
     .fields = (const VMStateField[]) {
         VMSTATE_UINT64(config, HPETState),
         VMSTATE_UINT64(isr, HPETState),
         VMSTATE_UINT64(hpet_counter, HPETState),
         VMSTATE_UINT8(num_timers_save, HPETState),
-        VMSTATE_VALIDATE("num_timers must match", hpet_validate_num_timers),
-        VMSTATE_STRUCT_VARRAY_UINT8(timer, HPETState, num_timers_save, 0,
+        VMSTATE_STRUCT_VARRAY_UINT8(timer, HPETState, num_timers, 0,
                                     vmstate_hpet_timer, HPETTimer),
         VMSTATE_END_OF_LIST()
     },
Signature · 1 line
2.56.0
author
#7 lore raw

PATCH v2 7/9 arm/machine: Convert cpu_post_load() to take Error**

In reply to Peter Xu

Convert it to post_load_errp() version, so as to be able to report verbose errors when hit.

A few things to mention:

- The old "fail" count won't work with Error**, switch to fail and return immediately, assuming we should stop migration immediately hitting the 1st error.

- Alone the way, handle_cpreg_only_in_incoming_stream() return value is flipped to make it match QEMU's normal coding style (return true for success, false for error, not vice versa).

- Provide simple error strings for the cases where the lower function doesn't yet take an Error**.

---
 target/arm/machine.c | 52 ++++++++++++++++++++++++--------------------
 1 file changed, 29 insertions(+), 23 deletions(-)
target/arm/machine.c +29 -23
index 02a2b78506..e86fa85a9b 100644
@@ -11,6 +11,7 @@
 #include "migration/qemu-file-types.h"
 #include "migration/vmstate.h"
 #include "target/arm/gtimer.h"
+#include "qapi/error.h"
 
 static bool vfp_needed(void *opaque)
 {
@@ -1151,10 +1152,11 @@ static void handle_cpreg_missing_in_incoming_stream(ARMCPU *cpu, uint64_t kvmidx
  * Handle the situation where @kvmidx is in the incoming
  * stream but not on destination. This fails the migration if
  * no cpreg mig tolerance is matched for this @kvmidx
- * Return true if the migration should eventually fail
+ * Return true if success, false otherwise.
  */
 static bool
-handle_cpreg_only_in_incoming_stream(ARMCPU *cpu, uint64_t kvmidx, uint64_t value)
+handle_cpreg_only_in_incoming_stream(ARMCPU *cpu, uint64_t kvmidx, uint64_t value,
+                                     Error **errp)
 {
     g_autofree gchar *name = print_register_name(kvmidx);
 
@@ -1163,18 +1165,17 @@ handle_cpreg_only_in_incoming_stream(ARMCPU *cpu, uint64_t kvmidx, uint64_t valu
         arm_cpu_match_cpreg_mig_tolerance(cpu, kvmidx,
                                           value, 0, ToleranceOnlySrcTestValue)) {
         trace_tolerate_cpreg_only_in_incoming_stream(name);
-        return false;
+        return true;
     }
-    error_report("%s: %s in the incoming stream but unknown on the "
-                 "destination: fail migration", __func__, name);
-    return true;
+    error_setg(errp, "cpreg %s in the incoming stream but unknown on the "
+               "destination", name);
+    return false;
 }
 
-static int cpu_post_load(void *opaque, int version_id)
+static bool cpu_post_load(void *opaque, int version_id, Error **errp)
 {
     ARMCPU *cpu = opaque;
     CPUARMState *env = &cpu->env;
-    bool fail = false;
     bool ignore_s_regs;
     int i, v;
 
@@ -1229,9 +1230,11 @@ static int cpu_post_load(void *opaque, int version_id)
             continue;
         }
         if (cpu->cpreg_vmstate_indexes[v] < cpu->cpreg_indexes[i]) {
-            fail = handle_cpreg_only_in_incoming_stream(cpu,
-                                                        cpu->cpreg_vmstate_indexes[v],
-                                                        cpu->cpreg_vmstate_values[v]);
+            if (!handle_cpreg_only_in_incoming_stream(
+                    cpu, cpu->cpreg_vmstate_indexes[v],
+                    cpu->cpreg_vmstate_values[v], errp)) {
+                return false;
+            }
             v++;
             continue;
         }
@@ -1278,21 +1281,22 @@ static int cpu_post_load(void *opaque, int version_id)
      * still regs in the input stream, continue parsing the vmstate array
      */
     for ( ; v < cpu->cpreg_vmstate_array_len; v++) {
-        fail = handle_cpreg_only_in_incoming_stream(cpu,
-                                                    cpu->cpreg_vmstate_indexes[v],
-                                                    cpu->cpreg_vmstate_values[v]);
-    }
-    if (fail) {
-        return -1;
+        if (!handle_cpreg_only_in_incoming_stream(
+                cpu, cpu->cpreg_vmstate_indexes[v],
+                cpu->cpreg_vmstate_values[v], errp)) {
+            return false;
+        }
     }
 
     if (kvm_enabled()) {
         if (!kvm_arm_cpu_post_load(cpu)) {
-            return -1;
+            error_setg(errp, "kvm_arm_cpu_post_load() failed");
+            return false;
         }
     } else {
         if (!write_list_to_cpustate(cpu)) {
-            return -1;
+            error_setg(errp, "write_list_to_cpustate() failed");
+            return false;
         }
     }
 
@@ -1307,7 +1311,8 @@ static int cpu_post_load(void *opaque, int version_id)
      * thumb_tr_translate_insn().
      */
     if (!is_a64(env) && env->thumb && (env->regs[15] & 1)) {
-        return -1;
+        error_setg(errp, "Misaligned thumb pc");
+        return false;
     }
 
     if (tcg_enabled()) {
@@ -1325,7 +1330,8 @@ static int cpu_post_load(void *opaque, int version_id)
                       FPCR_LTPSIZE_SHIFT, FPCR_LTPSIZE_LENGTH) != 4 ||
             extract32(env->v7m.fpdscr[M_REG_S],
                       FPCR_LTPSIZE_SHIFT, FPCR_LTPSIZE_LENGTH) != 4) {
-            return -1;
+            error_setg(errp, "Bogus fpdscr[] values");
+            return false;
         }
     }
 
@@ -1337,7 +1343,7 @@ static int cpu_post_load(void *opaque, int version_id)
         arm_rebuild_hflags(env);
     }
 
-    return 0;
+    return true;
 }
 
 const VMStateDescription vmstate_arm_cpu = {
@@ -1347,7 +1353,7 @@ const VMStateDescription vmstate_arm_cpu = {
     .pre_save = cpu_pre_save,
     .post_save = cpu_post_save,
     .pre_load = cpu_pre_load,
-    .post_load = cpu_post_load,
+    .post_load_errp = cpu_post_load,
     .fields = (const VMStateField[]) {
         VMSTATE_UINT32_ARRAY(env.regs, ARMCPU, 16),
         VMSTATE_UINT64_ARRAY(env.xregs, ARMCPU, 32),
Signature · 1 line
2.56.0
author
#8 lore raw

PATCH v2 8/9 arm/machine: Move all VMSTATE_VALIDATE() usages into post_load

In reply to Peter Xu

To pave way removing VMSTATE_VALIDATE(), move all four such uses into a post_load hook instead.

---
 target/arm/machine.c | 90 ++++++++++++++++++--------------------------
 1 file changed, 37 insertions(+), 53 deletions(-)
target/arm/machine.c +37 -53
index e86fa85a9b..b401593496 100644
@@ -407,14 +407,6 @@ static const VMStateDescription vmstate_m_faultmask_primask = {
  * just non-secure, we transfer both banks here rather than putting
  * the secure banked version in the m-security subsection.
  */
-static bool csselr_vmstate_validate(void *opaque, int version_id)
-{
-    ARMCPU *cpu = opaque;
-
-    return cpu->env.v7m.csselr[M_REG_NS] <= R_V7M_CSSELR_INDEX_MASK
-        && cpu->env.v7m.csselr[M_REG_S] <= R_V7M_CSSELR_INDEX_MASK;
-}
-
 static bool m_csselr_needed(void *opaque)
 {
     ARMCPU *cpu = opaque;
@@ -429,7 +421,6 @@ static const VMStateDescription vmstate_m_csselr = {
     .needed = m_csselr_needed,
     .fields = (const VMStateField[]) {
         VMSTATE_UINT32_ARRAY(env.v7m.csselr, ARMCPU, M_REG_NUM_BANKS),
-        VMSTATE_VALIDATE("CSSELR is valid", csselr_vmstate_validate),
         VMSTATE_END_OF_LIST()
     }
 };
@@ -590,18 +581,6 @@ static bool pmsav7_needed(void *opaque)
            !arm_feature(env, ARM_FEATURE_V8);
 }
 
-static bool pmsav7_rgnr_vmstate_validate(void *opaque, int version_id)
-{
-    ARMCPU *cpu = opaque;
-
-    /*
-     * Check MPU_RNR in-bounds. If no MPU, we still migrate this field
-     * but number of regions == 0 and MPU_RNR is RAZ/WI so also 0
-     */
-    return cpu->env.pmsav7.rnr[M_REG_NS] < cpu->pmsav7_dregion ||
-        (cpu->pmsav7_dregion == 0 && cpu->env.pmsav7.rnr[M_REG_NS] == 0);
-}
-
 static const VMStateDescription vmstate_pmsav7 = {
     .name = "cpu/pmsav7",
     .version_id = 1,
@@ -614,7 +593,6 @@ static const VMStateDescription vmstate_pmsav7 = {
                               vmstate_info_uint32, uint32_t),
         VMSTATE_VARRAY_UINT32(env.pmsav7.dracr, ARMCPU, pmsav7_dregion, 0,
                               vmstate_info_uint32, uint32_t),
-        VMSTATE_VALIDATE("rgnr is valid", pmsav7_rgnr_vmstate_validate),
         VMSTATE_END_OF_LIST()
     }
 };
@@ -695,31 +673,6 @@ static const VMStateDescription vmstate_pmsav8 = {
     }
 };
 
-static bool s_rnr_vmstate_validate(void *opaque, int version_id)
-{
-    ARMCPU *cpu = opaque;
-
-    /*
-     * Check MPU_RNR in-bounds. If no MPU, we still migrate this field
-     * but number of regions == 0 and MPU_RNR is RAZ/WI so also 0
-     */
-    return cpu->env.pmsav7.rnr[M_REG_S] < cpu->pmsav7_dregion ||
-        (cpu->pmsav7_dregion == 0 && cpu->env.pmsav7.rnr[M_REG_S] == 0);
-}
-
-static bool sau_rnr_vmstate_validate(void *opaque, int version_id)
-{
-    ARMCPU *cpu = opaque;
-
-    /*
-     * Check SAU_RNR in-bounds. If no SAU regions are implemented,
-     * we still migrate this field, but number of regions == 0 and
-     * SAU_RNR is RAZ/WI so also 0
-     */
-    return cpu->env.sau.rnr < cpu->sau_sregion ||
-        (cpu->sau_sregion == 0 && cpu->env.sau.rnr == 0);
-}
-
 static bool m_security_needed(void *opaque)
 {
     ARMCPU *cpu = opaque;
@@ -749,7 +702,6 @@ static const VMStateDescription vmstate_m_security = {
         VMSTATE_VARRAY_UINT32(env.pmsav8.rlar[M_REG_S], ARMCPU, pmsav7_dregion,
                               0, vmstate_info_uint32, uint32_t),
         VMSTATE_UINT32(env.pmsav7.rnr[M_REG_S], ARMCPU),
-        VMSTATE_VALIDATE("secure MPU_RNR is valid", s_rnr_vmstate_validate),
         VMSTATE_UINT32(env.v7m.mpu_ctrl[M_REG_S], ARMCPU),
         VMSTATE_UINT32(env.v7m.ccr[M_REG_S], ARMCPU),
         VMSTATE_UINT32(env.v7m.mmfar[M_REG_S], ARMCPU),
@@ -761,7 +713,6 @@ static const VMStateDescription vmstate_m_security = {
         VMSTATE_VARRAY_UINT32(env.sau.rlar, ARMCPU, sau_sregion, 0,
                               vmstate_info_uint32, uint32_t),
         VMSTATE_UINT32(env.sau.rnr, ARMCPU),
-        VMSTATE_VALIDATE("SAU_RNR is valid", sau_rnr_vmstate_validate),
         VMSTATE_UINT32(env.sau.ctrl, ARMCPU),
         VMSTATE_UINT32(env.v7m.scr[M_REG_S], ARMCPU),
         /* AIRCR is not secure-only, but our implementation is R/O if the
@@ -1177,11 +1128,48 @@ static bool cpu_post_load(void *opaque, int version_id, Error **errp)
     ARMCPU *cpu = opaque;
     CPUARMState *env = &cpu->env;
     bool ignore_s_regs;
+    bool valid;
     int i, v;
 
     trace_cpu_post_load(cpu->cpreg_vmstate_array_len,
                         cpu->cpreg_array_len);
 
+    if (env->v7m.csselr[M_REG_NS] > R_V7M_CSSELR_INDEX_MASK ||
+        env->v7m.csselr[M_REG_S] > R_V7M_CSSELR_INDEX_MASK) {
+        error_setg(errp, "CSSELR is invalid");
+        return false;
+    }
+
+    /*
+     * Check MPU_RNR in-bounds. If no MPU, we still migrate these fields
+     * but number of regions == 0 and MPU_RNR is RAZ/WI so also 0
+     */
+    valid = env->pmsav7.rnr[M_REG_NS] < cpu->pmsav7_dregion ||
+        (cpu->pmsav7_dregion == 0 && env->pmsav7.rnr[M_REG_NS] == 0);
+    if (!valid) {
+        error_setg(errp, "rgnr is invalid");
+        return false;
+    }
+
+    valid = env->pmsav7.rnr[M_REG_S] < cpu->pmsav7_dregion ||
+        (cpu->pmsav7_dregion == 0 && env->pmsav7.rnr[M_REG_S] == 0);
+    if (!valid) {
+        error_setg(errp, "secure MPU_RNR is invalid");
+        return false;
+    }
+
+    /*
+     * Check SAU_RNR in-bounds. If no SAU regions are implemented,
+     * we still migrate this field, but number of regions == 0 and
+     * SAU_RNR is RAZ/WI so also 0
+     */
+    valid = env->sau.rnr < cpu->sau_sregion ||
+        (cpu->sau_sregion == 0 && env->sau.rnr == 0);
+    if (!valid) {
+        error_setg(errp, "SAU_RNR is invalid");
+        return false;
+    }
+
     /*
      * Handle migration compatibility from old QEMU which didn't
      * send the irq-line-state subsection. A QEMU without it did not
@@ -1426,10 +1414,6 @@ const VMStateDescription vmstate_arm_cpu = {
         &vmstate_vfp,
         &vmstate_m,
         &vmstate_thumb2ee,
-        /* pmsav7_rnr must come before pmsav7 so that we have the
-         * region number before we test it in the VMSTATE_VALIDATE
-         * in vmstate_pmsav7.
-         */
         &vmstate_pmsav7_rnr,
         &vmstate_pmsav7,
         &vmstate_pmsav8,
Signature · 1 line
2.56.0
author
#9 lore raw

PATCH v2 9/9 migration: Drop VMSTATE_VALIDATE() and VMS_MUST_EXIST

In reply to Peter Xu

We have moved all users to other API, now they're never used.

---
 include/migration/vmstate.h | 11 -----------
 migration/savevm.c          |  5 -----
 migration/vmstate.c         | 12 ------------
 3 files changed, 28 deletions(-)
include/migration/vmstate.h +0 -11
index 2901877308..de7a957140 100644
@@ -130,10 +130,6 @@ enum VMStateFlags {
      * allocated. Only valid in combination with VMS_VBUFFER. */
     VMS_MULTIPLY         = 0x200,
 
-    /* Fail loading the serialised VM state if this field is missing
-     * from the input. */
-    VMS_MUST_EXIST       = 0x1000,
-
     /* When loading serialised VM state, allocate memory for the
      * (entire) field. Only valid in combination with
      * VMS_POINTER. Note: Not all combinations with other flags are
@@ -458,13 +454,6 @@ extern const VMStateInfo vmstate_info_g_byte_array;
     .offset       = vmstate_offset_value(_state, _field, _type),     \
 }
 
-/* Validate state using a boolean predicate. */
-#define VMSTATE_VALIDATE(_name, _test) { \
-    .name         = (_name),                                         \
-    .field_exists = (_test),                                         \
-    .flags        = VMS_MUST_EXIST | VMS_NO_STATE,                   \
-}
-
 #define VMSTATE_POINTER(_field, _state, _version, _info, _type) {    \
     .name       = (stringify(_field)),                               \
     .version_id = (_version),                                        \
migration/savevm.c +0 -5
index fe94ba96e4..e4f614cc86 100644
@@ -622,11 +622,6 @@ static void dump_vmstate_vmsd(FILE *out_file,
         fprintf(out_file, ",\n%*s\"Fields\": [\n", indent, "");
         first = true;
         while (field->name != NULL) {
-            if (field->flags & VMS_MUST_EXIST) {
-                /* Ignore VMSTATE_VALIDATE bits; these don't get migrated */
-                field++;
-                continue;
-            }
             if (!first) {
                 fprintf(out_file, ",\n");
             }
migration/vmstate.c +0 -12
index 24004565bf..7734caab06 100644
@@ -116,8 +116,6 @@ static uint64_t vmstate_n_elems(void *opaque, const VMStateField *field)
         n_elems = field->num;
     } else if (field->flags & VMS_VARRAY) {
         n_elems = vmstate_read_from_offset(&field->num_indirect, opaque);
-    } else if (field->flags & VMS_MUST_EXIST && field->flags & VMS_NO_STATE) {
-        n_elems = 0;
     } else {
         n_elems = 1;
     }
@@ -430,10 +428,6 @@ bool vmstate_load_vmsd(QEMUFile *f, const VMStateDescription *vmsd,
                     return false;
                 }
             }
-        } else if (field->flags & VMS_MUST_EXIST) {
-            error_setg(errp, "Input validation failed: %s/%s version_id: %d",
-                       vmsd->name, field->name, vmsd->version_id);
-            return false;
         }
         field++;
     }
@@ -810,12 +804,6 @@ static bool vmstate_save_vmsd_v(QEMUFile *f, const VMStateDescription *vmsd,
                     vmdesc_loop = NULL;
                 }
             }
-        } else {
-            if (field->flags & VMS_MUST_EXIST) {
-                error_report("Output state validation failed: %s/%s",
-                        vmsd->name, field->name);
-                assert(!(field->flags & VMS_MUST_EXIST));
-            }
         }
         field++;
     }
Signature · 1 line
2.56.0