Rust device model patches and misc cleanups
Subsystems (2)
cover Rust device model patches and misc cleanups
Hello everyone, the pathological corrosion of QEMU code continues.
This series expands the device model harness work performed in the initial Rust work from the previous month. In particular:
- A new derive proc macro, Device, is introduced and the Object derive macro is heavily expanded upon. Many hack-like macros and fixups to declare FFI code for QEMU to consume were removed and now everything is generated by macros in the qemu-api-macros procmacro crate.
- Add support for device migration by allowing device models to declare their VMState description, fields, subsections like in C code. This should also allow new qemu versions to transparently migrate any VMs that used C device models that were afterwards ported to Rust.
- Add a small logging interface in qemu-api crate to allow calling qemu_log() and qemu_log_mask() from Rust code.
- Some minor code cleanups in the Rust pl011 device, and also port of one fix patch and one log prints addition patch that was added in the C pl011.
In the future if we go forward with rewriting device models in Rust, and keep having both of them in-tree while Rust is not required for building QEMU, we could alter checkpatch.pl to produce a warning if a C device model has changes but the corresponding Rust implementation doesn't.
Code and functionality duplication is not fun, and pl011 was mostly done as a proof of concept for a Rust device because of its small complexity. As of this moment we have not decided on a policy for how to handle these things and it is not in **scope for this patch series anyway**.
In the meantime there are lots of TODOs written in my personal notes, my personal repos, in the QEMU wiki, in mailing list threads. I plan on consolidating them all in gitlab issues to streamline things and who-does-what to avoid duplicating work.
---
Manos Pitsidianakis (11):
Revert "rust: add PL011 device model"
rust: add PL011 device model rust/qemu-api-macros: introduce Device proc macro
rust: add support for migration in device models rust/pl011: move CLK_NAME static to function scope rust/pl011: add TYPE_PL011_LUMINARY device rust/pl011: move pub callback decl to local scope rust/pl011: remove commented out C code rust/pl011: Use correct masks for IBRD and FBRD rust/qemu-api: add log module
rust/pl011: log guest/unimp errors
rust/wrapper.h | 1 + rust/hw/char/pl011/src/device.rs | 419 +++++++++++++++++--------- rust/hw/char/pl011/src/device_class.rs | 70 ----- rust/hw/char/pl011/src/lib.rs | 2 +- rust/qemu-api-macros/src/device.rs | 370 +++++++++++++++++++++++ rust/qemu-api-macros/src/lib.rs | 46 +-- rust/qemu-api-macros/src/object.rs | 107 +++++++ rust/qemu-api-macros/src/symbols.rs | 57 ++++ rust/qemu-api-macros/src/utilities.rs | 152 ++++++++++ rust/qemu-api-macros/src/vmstate.rs | 113 +++++++ rust/qemu-api/meson.build | 5 +- rust/qemu-api/src/definitions.rs | 97 ------ rust/qemu-api/src/device_class.rs | 128 -------- rust/qemu-api/src/lib.rs | 10 +- rust/qemu-api/src/log.rs | 140 +++++++++ rust/qemu-api/src/objects.rs | 90 ++++++ rust/qemu-api/src/tests.rs | 49 --- rust/qemu-api/src/vmstate.rs | 403 +++++++++++++++++++++++++ subprojects/packagefiles/syn-2-rs/meson.build | 1 + 19 files changed, 1726 insertions(+), 534 deletions(-)
---
base-commit: 55522f72149fbf95ee3b057f1419da0cad46d0dd
change-id: 20241024-rust-round-2-69fa10c9a0c9
--
γαῖα πυρί μιχθήτω
PATCH 1/11 Revert "rust: add PL011 device model"
Patch was applied with invalid authorship by accident, which confuses git tooling that look at git blame for contributors etc.
Patch will be re-applied with correct authorship right after this commit.
This reverts commit d0f0cd5b1f7e9780753344548e17ad4df9fcf5d8.
--- MAINTAINERS | 5 - meson.build | 24 - hw/arm/Kconfig | 30 +- rust/Kconfig | 1 - rust/hw/Kconfig | 2 - rust/hw/char/Kconfig | 3 - rust/hw/char/meson.build | 1 - rust/hw/char/pl011/.gitignore | 2 - rust/hw/char/pl011/Cargo.lock | 134 ----- rust/hw/char/pl011/Cargo.toml | 26 - rust/hw/char/pl011/README.md | 31 -- rust/hw/char/pl011/meson.build | 26 - rust/hw/char/pl011/src/device.rs | 599 --------------------- rust/hw/char/pl011/src/device_class.rs | 70 --- rust/hw/char/pl011/src/lib.rs | 586 -------------------- rust/hw/char/pl011/src/memory_ops.rs | 59 -- rust/hw/meson.build | 1 - rust/meson.build | 2 - scripts/archive-source.sh | 4 +- scripts/make-release | 4 +- scripts/rust/rust_root_crate.sh | 13 - subprojects/.gitignore | 7 - subprojects/arbitrary-int-1-rs.wrap | 7 - subprojects/bilge-0.2-rs.wrap | 7 - subprojects/bilge-impl-0.2-rs.wrap | 7 - subprojects/either-1-rs.wrap | 7 - subprojects/itertools-0.11-rs.wrap | 7 - .../packagefiles/arbitrary-int-1-rs/meson.build | 19 - subprojects/packagefiles/bilge-0.2-rs/meson.build | 29 - .../packagefiles/bilge-impl-0.2-rs/meson.build | 45 -- subprojects/packagefiles/either-1-rs/meson.build | 24 - .../packagefiles/itertools-0.11-rs/meson.build | 30 -- .../packagefiles/proc-macro-error-1-rs/meson.build | 40 -- .../proc-macro-error-attr-1-rs/meson.build | 32 -- .../packagefiles/unicode-ident-1-rs/meson.build | 20 - subprojects/proc-macro-error-1-rs.wrap | 7 - subprojects/proc-macro-error-attr-1-rs.wrap | 7 - 37 files changed, 12 insertions(+), 1906 deletions(-)
MAINTAINERS +0 -5
@@ -1137,11 +1137,6 @@ F: include/hw/*/microbit*.h F: tests/qtest/microbit-test.c F: docs/system/arm/nrf.rst -ARM PL011 Rust device -M: Manos Pitsidianakis <[email protected]> -S: Maintained -F: rust/hw/char/pl011/ - AVR Machines -------------
meson.build +0 -24
@@ -3520,7 +3520,6 @@ qom_ss = ss.source_set() system_ss = ss.source_set() specific_fuzz_ss = ss.source_set() specific_ss = ss.source_set() -rust_devices_ss = ss.source_set() stub_ss = ss.source_set() trace_ss = ss.source_set() user_ss = ss.source_set()
@@ -4068,29 +4067,6 @@ foreach target : target_dirs arch_srcs += target_specific.sources() arch_deps += target_specific.dependencies() - if have_rust and have_system - target_rust = rust_devices_ss.apply(config_target, strict: false) - crates = [] - foreach dep : target_rust.dependencies() - crates += dep.get_variable('crate') - endforeach - if crates.length() > 0 - rlib_rs = custom_target('rust_' + target.underscorify() + '.rs', - output: 'rust_' + target.underscorify() + '.rs', - command: [find_program('scripts/rust/rust_root_crate.sh')] + crates, - capture: true, - build_by_default: true, - build_always_stale: true) - rlib = static_library('rust_' + target.underscorify(), - rlib_rs, - dependencies: target_rust.dependencies(), - override_options: ['rust_std=2021', 'build.rust_std=2021'], - rust_args: rustc_args, - rust_abi: 'c') - arch_deps += declare_dependency(link_whole: [rlib]) - endif - endif - # allow using headers from the dependencies but do not include the sources, # because this emulator only needs those in "objects". For external # dependencies, the full dependency is included below in the executable.
hw/arm/Kconfig +10 -20
@@ -20,8 +20,7 @@ config ARM_VIRT select PCI_EXPRESS select PCI_EXPRESS_GENERIC_BRIDGE select PFLASH_CFI01 - select PL011 if !HAVE_RUST # UART - select X_PL011_RUST if HAVE_RUST # UART + select PL011 # UART select PL031 # RTC select PL061 # GPIO select GPIO_PWR
@@ -74,8 +73,7 @@ config HIGHBANK select AHCI select ARM_TIMER # sp804 select ARM_V7M - select PL011 if !HAVE_RUST # UART - select X_PL011_RUST if HAVE_RUST # UART + select PL011 # UART select PL022 # SPI select PL031 # RTC select PL061 # GPIO
@@ -88,8 +86,7 @@ config INTEGRATOR depends on TCG && ARM select ARM_TIMER select INTEGRATOR_DEBUG - select PL011 if !HAVE_RUST # UART - select X_PL011_RUST if HAVE_RUST # UART + select PL011 # UART select PL031 # RTC select PL041 # audio select PL050 # keyboard/mouse
@@ -107,8 +104,7 @@ config MUSCA default y depends on TCG && ARM select ARMSSE - select PL011 if !HAVE_RUST # UART - select X_PL011_RUST if HAVE_RUST # UART + select PL011 select PL031 select SPLIT_IRQ select UNIMP
@@ -172,8 +168,7 @@ config REALVIEW select WM8750 # audio codec select LSI_SCSI_PCI select PCI - select PL011 if !HAVE_RUST # UART - select X_PL011_RUST if HAVE_RUST # UART + select PL011 # UART select PL031 # RTC select PL041 # audio codec select PL050 # keyboard/mouse
@@ -198,8 +193,7 @@ config SBSA_REF select PCI_EXPRESS select PCI_EXPRESS_GENERIC_BRIDGE select PFLASH_CFI01 - select PL011 if !HAVE_RUST # UART - select X_PL011_RUST if HAVE_RUST # UART + select PL011 # UART select PL031 # RTC select PL061 # GPIO select USB_XHCI_SYSBUS
@@ -223,8 +217,7 @@ config STELLARIS select ARM_V7M select CMSDK_APB_WATCHDOG select I2C - select PL011 if !HAVE_RUST # UART - select X_PL011_RUST if HAVE_RUST # UART + select PL011 # UART select PL022 # SPI select PL061 # GPIO select SSD0303 # OLED display
@@ -284,8 +277,7 @@ config VEXPRESS select ARM_TIMER # sp804 select LAN9118 select PFLASH_CFI01 - select PL011 if !HAVE_RUST # UART - select X_PL011_RUST if HAVE_RUST # UART + select PL011 # UART select PL041 # audio codec select PL181 # display select REALVIEW
@@ -370,8 +362,7 @@ config RASPI default y depends on TCG && ARM select FRAMEBUFFER - select PL011 if !HAVE_RUST # UART - select X_PL011_RUST if HAVE_RUST # UART + select PL011 # UART select SDHCI select USB_DWC2 select BCM2835_SPI
@@ -447,8 +438,7 @@ config XLNX_VERSAL select ARM_GIC select CPU_CLUSTER select DEVICE_TREE - select PL011 if !HAVE_RUST # UART - select X_PL011_RUST if HAVE_RUST # UART + select PL011 select CADENCE select VIRTIO_MMIO select UNIMP
rust/Kconfig +0 -1
@@ -1 +0,0 @@ -source hw/Kconfig
rust/hw/Kconfig deleted +0 -2
@@ -1,2 +0,0 @@ -# devices Kconfig -source char/Kconfig
rust/hw/char/Kconfig deleted +0 -3
@@ -1,3 +0,0 @@ -config X_PL011_RUST - bool - default y if HAVE_RUST
rust/hw/char/meson.build deleted +0 -1
@@ -1 +0,0 @@ -subdir('pl011')
rust/hw/char/pl011/.gitignore deleted +0 -2
@@ -1,2 +0,0 @@ -# Ignore generated bindings file overrides. -src/bindings.rs.inc
rust/hw/char/pl011/Cargo.lock deleted +0 -134
134 lines not on this page · raw message
rust/hw/char/pl011/Cargo.toml deleted +0 -26
@@ -1,26 +0,0 @@ -[package] -name = "pl011" -version = "0.1.0" -edition = "2021" -authors = ["Manos Pitsidianakis <[email protected]>"] -license = "GPL-2.0-or-later" -readme = "README.md" -homepage = "https://www.qemu.org" -description = "pl011 device model for QEMU" -repository = "https://gitlab.com/epilys/rust-for-qemu" -resolver = "2" -publish = false -keywords = [] -categories = [] - -[lib] -crate-type = ["staticlib"] - -[dependencies] -bilge = { version = "0.2.0" } -bilge-impl = { version = "0.2.0" } -qemu_api = { path = "../../../qemu-api" } -qemu_api_macros = { path = "../../../qemu-api-macros" } - -# Do not include in any global workspace -[workspace]
rust/hw/char/pl011/README.md deleted +0 -31
@@ -1,31 +0,0 @@ -# PL011 QEMU Device Model - -This library implements a device model for the PrimeCell® UART (PL011) -device in QEMU. - -## Build static lib - -Host build target must be explicitly specified: - -```sh -cargo build --target x86_64-unknown-linux-gnu -``` - -Replace host target triplet if necessary. - -## Generate Rust documentation - -To generate docs for this crate, including private items: - -```sh -cargo doc --no-deps --document-private-items --target x86_64-unknown-linux-gnu -``` - -To include direct dependencies like `bilge` (bitmaps for register types): - -```sh -cargo tree --depth 1 -e normal --prefix none \ - | cut -d' ' -f1 \ - | xargs printf -- '-p %s\n' \ - | xargs cargo doc --no-deps --document-private-items --target x86_64-unknown-linux-gnu -```
rust/hw/char/pl011/meson.build deleted +0 -26
@@ -1,26 +0,0 @@ -subproject('bilge-0.2-rs', required: true) -subproject('bilge-impl-0.2-rs', required: true) - -bilge_dep = dependency('bilge-0.2-rs') -bilge_impl_dep = dependency('bilge-impl-0.2-rs') - -_libpl011_rs = static_library( - 'pl011', - files('src/lib.rs'), - override_options: ['rust_std=2021', 'build.rust_std=2021'], - rust_abi: 'rust', - dependencies: [ - bilge_dep, - bilge_impl_dep, - qemu_api, - qemu_api_macros, - ], -) - -rust_devices_ss.add(when: 'CONFIG_X_PL011_RUST', if_true: [declare_dependency( - link_whole: [_libpl011_rs], - # Putting proc macro crates in `dependencies` is necessary for Meson to find - # them when compiling the root per-target static rust lib. - dependencies: [bilge_impl_dep, qemu_api_macros], - variables: {'crate': 'pl011'}, -)])
rust/hw/char/pl011/src/device.rs deleted +0 -599
599 lines not on this page · raw message
rust/hw/char/pl011/src/device_class.rs deleted +0 -70
70 lines not on this page · raw message
rust/hw/char/pl011/src/lib.rs deleted +0 -586
586 lines not on this page · raw message
rust/hw/char/pl011/src/memory_ops.rs deleted +0 -59
59 lines not on this page · raw message
rust/hw/meson.build deleted +0 -1
@@ -1 +0,0 @@ -subdir('char')
rust/meson.build +0 -2
@@ -1,4 +1,2 @@ subdir('qemu-api-macros') subdir('qemu-api') - -subdir('hw')
scripts/archive-source.sh +1 -3
@@ -27,9 +27,7 @@ sub_file="${sub_tdir}/submodule.tar" # in their checkout, because the build environment is completely # different to the host OS. subprojects="keycodemapdb libvfio-user berkeley-softfloat-3 - berkeley-testfloat-3 arbitrary-int-1-rs bilge-0.2-rs - bilge-impl-0.2-rs either-1-rs itertools-0.11-rs proc-macro2-1-rs - proc-macro-error-1-rs proc-macro-error-attr-1-rs quote-1-rs + berkeley-testfloat-3 proc-macro2-1-rs quote-1-rs syn-2-rs unicode-ident-1-rs" sub_deinit=""
scripts/make-release +1 -3
@@ -18,9 +18,7 @@ fi # Only include wraps that are invoked with subproject() SUBPROJECTS="libvfio-user keycodemapdb berkeley-softfloat-3 - berkeley-testfloat-3 arbitrary-int-1-rs bilge-0.2-rs - bilge-impl-0.2-rs either-1-rs itertools-0.11-rs proc-macro2-1-rs - proc-macro-error-1-rs proc-macro-error-attr-1-rs quote-1-rs + berkeley-testfloat-3 proc-macro2-1-rs quote-1-rs syn-2-rs unicode-ident-1-rs" src="$1"
scripts/rust/rust_root_crate.sh deleted +0 -13
@@ -1,13 +0,0 @@ -#!/bin/sh - -set -eu - -cat <<EOF -// @generated -// This file is autogenerated by scripts/rust_root_crate.sh - -EOF - -for crate in $*; do - echo "extern crate $crate;" -done
subprojects/.gitignore +0 -7
@@ -6,13 +6,6 @@ /keycodemapdb /libvfio-user /slirp -/arbitrary-int-1.2.7 -/bilge-0.2.0 -/bilge-impl-0.2.0 -/either-1.12.0 -/itertools-0.11.0 -/proc-macro-error-1.0.4 -/proc-macro-error-attr-1.0.4 /proc-macro2-1.0.84 /quote-1.0.36 /syn-2.0.66
subprojects/arbitrary-int-1-rs.wrap deleted +0 -7
@@ -1,7 +0,0 @@ -[wrap-file] -directory = arbitrary-int-1.2.7 -source_url = https://crates.io/api/v1/crates/arbitrary-int/1.2.7/download -source_filename = arbitrary-int-1.2.7.tar.gz -source_hash = c84fc003e338a6f69fbd4f7fe9f92b535ff13e9af8997f3b14b6ddff8b1df46d -#method = cargo -patch_directory = arbitrary-int-1-rs
subprojects/bilge-0.2-rs.wrap deleted +0 -7
@@ -1,7 +0,0 @@ -[wrap-file] -directory = bilge-0.2.0 -source_url = https://crates.io/api/v1/crates/bilge/0.2.0/download -source_filename = bilge-0.2.0.tar.gz -source_hash = dc707ed8ebf81de5cd6c7f48f54b4c8621760926cdf35a57000747c512e67b57 -#method = cargo -patch_directory = bilge-0.2-rs
subprojects/bilge-impl-0.2-rs.wrap deleted +0 -7
@@ -1,7 +0,0 @@ -[wrap-file] -directory = bilge-impl-0.2.0 -source_url = https://crates.io/api/v1/crates/bilge-impl/0.2.0/download -source_filename = bilge-impl-0.2.0.tar.gz -source_hash = feb11e002038ad243af39c2068c8a72bcf147acf05025dcdb916fcc000adb2d8 -#method = cargo -patch_directory = bilge-impl-0.2-rs
subprojects/either-1-rs.wrap deleted +0 -7
@@ -1,7 +0,0 @@ -[wrap-file] -directory = either-1.12.0 -source_url = https://crates.io/api/v1/crates/either/1.12.0/download -source_filename = either-1.12.0.tar.gz -source_hash = 3dca9240753cf90908d7e4aac30f630662b02aebaa1b58a3cadabdb23385b58b -#method = cargo -patch_directory = either-1-rs
subprojects/itertools-0.11-rs.wrap deleted +0 -7
@@ -1,7 +0,0 @@ -[wrap-file] -directory = itertools-0.11.0 -source_url = https://crates.io/api/v1/crates/itertools/0.11.0/download -source_filename = itertools-0.11.0.tar.gz -source_hash = b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57 -#method = cargo -patch_directory = itertools-0.11-rs
subprojects/packagefiles/arbitrary-int-1-rs/meson.build deleted +0 -19
@@ -1,19 +0,0 @@ -project('arbitrary-int-1-rs', 'rust', - version: '1.2.7', - license: 'MIT', - default_options: []) - -_arbitrary_int_rs = static_library( - 'arbitrary_int', - files('src/lib.rs'), - gnu_symbol_visibility: 'hidden', - override_options: ['rust_std=2021', 'build.rust_std=2021'], - rust_abi: 'rust', - dependencies: [], -) - -arbitrary_int_dep = declare_dependency( - link_with: _arbitrary_int_rs, -) - -meson.override_dependency('arbitrary-int-1-rs', arbitrary_int_dep)
subprojects/packagefiles/bilge-0.2-rs/meson.build deleted +0 -29
@@ -1,29 +0,0 @@ -project( - 'bilge-0.2-rs', - 'rust', - version : '0.2.0', - license : 'MIT or Apache-2.0', -) - -subproject('arbitrary-int-1-rs', required: true) -subproject('bilge-impl-0.2-rs', required: true) - -arbitrary_int_dep = dependency('arbitrary-int-1-rs') -bilge_impl_dep = dependency('bilge-impl-0.2-rs') - -lib = static_library( - 'bilge', - 'src/lib.rs', - override_options : ['rust_std=2021', 'build.rust_std=2021'], - rust_abi : 'rust', - dependencies: [ - arbitrary_int_dep, - bilge_impl_dep, - ], -) - -bilge_dep = declare_dependency( - link_with : [lib], -) - -meson.override_dependency('bilge-0.2-rs', bilge_dep)
subprojects/packagefiles/bilge-impl-0.2-rs/meson.build deleted +0 -45
45 lines not on this page · raw message
subprojects/packagefiles/either-1-rs/meson.build deleted +0 -24
@@ -1,24 +0,0 @@ -project('either-1-rs', 'rust', - version: '1.12.0', - license: 'MIT OR Apache-2.0', - default_options: []) - -_either_rs = static_library( - 'either', - files('src/lib.rs'), - gnu_symbol_visibility: 'hidden', - override_options: ['rust_std=2018', 'build.rust_std=2018'], - rust_abi: 'rust', - rust_args: [ - '--cfg', 'feature="use_std"', - '--cfg', 'feature="use_alloc"', - ], - dependencies: [], - native: true, -) - -either_dep = declare_dependency( - link_with: _either_rs, -) - -meson.override_dependency('either-1-rs', either_dep, native: true)
subprojects/packagefiles/itertools-0.11-rs/meson.build deleted +0 -30
@@ -1,30 +0,0 @@ -project('itertools-0.11-rs', 'rust', - version: '0.11.0', - license: 'MIT OR Apache-2.0', - default_options: []) - -subproject('either-1-rs', required: true) - -either_dep = dependency('either-1-rs', native: true) - -_itertools_rs = static_library( - 'itertools', - files('src/lib.rs'), - gnu_symbol_visibility: 'hidden', - override_options: ['rust_std=2018', 'build.rust_std=2018'], - rust_abi: 'rust', - rust_args: [ - '--cfg', 'feature="use_std"', - '--cfg', 'feature="use_alloc"', - ], - dependencies: [ - either_dep, - ], - native: true, -) - -itertools_dep = declare_dependency( - link_with: _itertools_rs, -) - -meson.override_dependency('itertools-0.11-rs', itertools_dep, native: true)
subprojects/packagefiles/proc-macro-error-1-rs/meson.build deleted +0 -40
@@ -1,40 +0,0 @@ -project('proc-macro-error-1-rs', 'rust', - version: '1.0.4', - license: 'MIT OR Apache-2.0', - default_options: []) - -subproject('proc-macro-error-attr-1-rs', required: true) -subproject('quote-1-rs', required: true) -subproject('syn-2-rs', required: true) -subproject('proc-macro2-1-rs', required: true) - -proc_macro_error_attr_dep = dependency('proc-macro-error-attr-1-rs', native: true) -proc_macro2_dep = dependency('proc-macro2-1-rs', native: true) -quote_dep = dependency('quote-1-rs', native: true) -syn_dep = dependency('syn-2-rs', native: true) - -_proc_macro_error_rs = static_library( - 'proc_macro_error', - files('src/lib.rs'), - override_options: ['rust_std=2018', 'build.rust_std=2018'], - rust_abi: 'rust', - rust_args: [ - '--cfg', 'use_fallback', - '--cfg', 'feature="syn-error"', - '--cfg', 'feature="proc-macro"', - '-A', 'non_fmt_panics' - ], - dependencies: [ - proc_macro_error_attr_dep, - proc_macro2_dep, - quote_dep, - syn_dep, - ], - native: true, -) - -proc_macro_error_dep = declare_dependency( - link_with: _proc_macro_error_rs, -) - -meson.override_dependency('proc-macro-error-1-rs', proc_macro_error_dep, native: true)
subprojects/packagefiles/proc-macro-error-attr-1-rs/meson.build deleted +0 -32
@@ -1,32 +0,0 @@ -project('proc-macro-error-attr-1-rs', 'rust', - version: '1.12.0', - license: 'MIT OR Apache-2.0', - default_options: []) - -subproject('proc-macro2-1-rs', required: true) -subproject('quote-1-rs', required: true) - -proc_macro2_dep = dependency('proc-macro2-1-rs', native: true) -quote_dep = dependency('quote-1-rs', native: true) - -rust = import('rust') -_proc_macro_error_attr_rs = rust.proc_macro( - 'proc_macro_error_attr', - files('src/lib.rs'), - override_options: ['rust_std=2018', 'build.rust_std=2018'], - rust_args: [ - '--cfg', 'use_fallback', - '--cfg', 'feature="syn-error"', - '--cfg', 'feature="proc-macro"' - ], - dependencies: [ - proc_macro2_dep, - quote_dep, - ], -) - -proc_macro_error_attr_dep = declare_dependency( - link_with: _proc_macro_error_attr_rs, -) - -meson.override_dependency('proc-macro-error-attr-1-rs', proc_macro_error_attr_dep, native: true)
subprojects/packagefiles/unicode-ident-1-rs/meson.build deleted +0 -20
@@ -1,20 +0,0 @@ -project('unicode-ident-1-rs', 'rust', - version: '1.0.12', - license: '(MIT OR Apache-2.0) AND Unicode-DFS-2016', - default_options: []) - -_unicode_ident_rs = static_library( - 'unicode_ident', - files('src/lib.rs'), - gnu_symbol_visibility: 'hidden', - override_options: ['rust_std=2021', 'build.rust_std=2021'], - rust_abi: 'rust', - dependencies: [], - native: true, -) - -unicode_ident_dep = declare_dependency( - link_with: _unicode_ident_rs, -) - -meson.override_dependency('unicode-ident-1-rs', unicode_ident_dep, native: true)
subprojects/proc-macro-error-1-rs.wrap deleted +0 -7
@@ -1,7 +0,0 @@ -[wrap-file] -directory = proc-macro-error-1.0.4 -source_url = https://crates.io/api/v1/crates/proc-macro-error/1.0.4/download -source_filename = proc-macro-error-1.0.4.tar.gz -source_hash = da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c -#method = cargo -patch_directory = proc-macro-error-1-rs
subprojects/proc-macro-error-attr-1-rs.wrap deleted +0 -7
@@ -1,7 +0,0 @@ -[wrap-file] -directory = proc-macro-error-attr-1.0.4 -source_url = https://crates.io/api/v1/crates/proc-macro-error-attr/1.0.4/download -source_filename = proc-macro-error-attr-1.0.4.tar.gz -source_hash = a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869 -#method = cargo -patch_directory = proc-macro-error-attr-1-rs
Signature · 1 line
2.45.2
PATCH 2/11 rust: add PL011 device model
In reply to Manos PitsidianakisThis commit adds a re-implementation of hw/char/pl011.c in Rust.
How to build:
1. Configure a QEMU build with:
--enable-system --target-list=aarch64-softmmu --enable-rust
2. Launching a VM with qemu-system-aarch64 should use the Rust version of the pl011 device
--- MAINTAINERS | 5 + meson.build | 24 + hw/arm/Kconfig | 30 +- rust/Kconfig | 1 + rust/hw/Kconfig | 2 + rust/hw/char/Kconfig | 3 + rust/hw/char/meson.build | 1 + rust/hw/char/pl011/.gitignore | 2 + rust/hw/char/pl011/Cargo.lock | 134 +++++ rust/hw/char/pl011/Cargo.toml | 26 + rust/hw/char/pl011/README.md | 31 ++ rust/hw/char/pl011/meson.build | 26 + rust/hw/char/pl011/src/device.rs | 599 +++++++++++++++++++++ rust/hw/char/pl011/src/device_class.rs | 70 +++ rust/hw/char/pl011/src/lib.rs | 586 ++++++++++++++++++++ rust/hw/char/pl011/src/memory_ops.rs | 59 ++ rust/hw/meson.build | 1 + rust/meson.build | 2 + scripts/archive-source.sh | 4 +- scripts/make-release | 4 +- scripts/rust/rust_root_crate.sh | 13 + subprojects/.gitignore | 7 + subprojects/arbitrary-int-1-rs.wrap | 7 + subprojects/bilge-0.2-rs.wrap | 7 + subprojects/bilge-impl-0.2-rs.wrap | 7 + subprojects/either-1-rs.wrap | 7 + subprojects/itertools-0.11-rs.wrap | 7 + .../packagefiles/arbitrary-int-1-rs/meson.build | 19 + subprojects/packagefiles/bilge-0.2-rs/meson.build | 29 + .../packagefiles/bilge-impl-0.2-rs/meson.build | 45 ++ subprojects/packagefiles/either-1-rs/meson.build | 24 + .../packagefiles/itertools-0.11-rs/meson.build | 30 ++ .../packagefiles/proc-macro-error-1-rs/meson.build | 40 ++ .../proc-macro-error-attr-1-rs/meson.build | 32 ++ .../packagefiles/unicode-ident-1-rs/meson.build | 20 + subprojects/proc-macro-error-1-rs.wrap | 7 + subprojects/proc-macro-error-attr-1-rs.wrap | 7 + 37 files changed, 1906 insertions(+), 12 deletions(-)
MAINTAINERS +5 -0
@@ -1137,6 +1137,11 @@ F: include/hw/*/microbit*.h F: tests/qtest/microbit-test.c F: docs/system/arm/nrf.rst +ARM PL011 Rust device +M: Manos Pitsidianakis <[email protected]> +S: Maintained +F: rust/hw/char/pl011/ + AVR Machines -------------
meson.build +24 -0
@@ -3520,6 +3520,7 @@ qom_ss = ss.source_set() system_ss = ss.source_set() specific_fuzz_ss = ss.source_set() specific_ss = ss.source_set() +rust_devices_ss = ss.source_set() stub_ss = ss.source_set() trace_ss = ss.source_set() user_ss = ss.source_set()
@@ -4067,6 +4068,29 @@ foreach target : target_dirs arch_srcs += target_specific.sources() arch_deps += target_specific.dependencies() + if have_rust and have_system + target_rust = rust_devices_ss.apply(config_target, strict: false) + crates = [] + foreach dep : target_rust.dependencies() + crates += dep.get_variable('crate') + endforeach + if crates.length() > 0 + rlib_rs = custom_target('rust_' + target.underscorify() + '.rs', + output: 'rust_' + target.underscorify() + '.rs', + command: [find_program('scripts/rust/rust_root_crate.sh')] + crates, + capture: true, + build_by_default: true, + build_always_stale: true) + rlib = static_library('rust_' + target.underscorify(), + rlib_rs, + dependencies: target_rust.dependencies(), + override_options: ['rust_std=2021', 'build.rust_std=2021'], + rust_args: rustc_args, + rust_abi: 'c') + arch_deps += declare_dependency(link_whole: [rlib]) + endif + endif + # allow using headers from the dependencies but do not include the sources, # because this emulator only needs those in "objects". For external # dependencies, the full dependency is included below in the executable.
hw/arm/Kconfig +20 -10
@@ -20,7 +20,8 @@ config ARM_VIRT select PCI_EXPRESS select PCI_EXPRESS_GENERIC_BRIDGE select PFLASH_CFI01 - select PL011 # UART + select PL011 if !HAVE_RUST # UART + select X_PL011_RUST if HAVE_RUST # UART select PL031 # RTC select PL061 # GPIO select GPIO_PWR
@@ -73,7 +74,8 @@ config HIGHBANK select AHCI select ARM_TIMER # sp804 select ARM_V7M - select PL011 # UART + select PL011 if !HAVE_RUST # UART + select X_PL011_RUST if HAVE_RUST # UART select PL022 # SPI select PL031 # RTC select PL061 # GPIO
@@ -86,7 +88,8 @@ config INTEGRATOR depends on TCG && ARM select ARM_TIMER select INTEGRATOR_DEBUG - select PL011 # UART + select PL011 if !HAVE_RUST # UART + select X_PL011_RUST if HAVE_RUST # UART select PL031 # RTC select PL041 # audio select PL050 # keyboard/mouse
@@ -104,7 +107,8 @@ config MUSCA default y depends on TCG && ARM select ARMSSE - select PL011 + select PL011 if !HAVE_RUST # UART + select X_PL011_RUST if HAVE_RUST # UART select PL031 select SPLIT_IRQ select UNIMP
@@ -168,7 +172,8 @@ config REALVIEW select WM8750 # audio codec select LSI_SCSI_PCI select PCI - select PL011 # UART + select PL011 if !HAVE_RUST # UART + select X_PL011_RUST if HAVE_RUST # UART select PL031 # RTC select PL041 # audio codec select PL050 # keyboard/mouse
@@ -193,7 +198,8 @@ config SBSA_REF select PCI_EXPRESS select PCI_EXPRESS_GENERIC_BRIDGE select PFLASH_CFI01 - select PL011 # UART + select PL011 if !HAVE_RUST # UART + select X_PL011_RUST if HAVE_RUST # UART select PL031 # RTC select PL061 # GPIO select USB_XHCI_SYSBUS
@@ -217,7 +223,8 @@ config STELLARIS select ARM_V7M select CMSDK_APB_WATCHDOG select I2C - select PL011 # UART + select PL011 if !HAVE_RUST # UART + select X_PL011_RUST if HAVE_RUST # UART select PL022 # SPI select PL061 # GPIO select SSD0303 # OLED display
@@ -277,7 +284,8 @@ config VEXPRESS select ARM_TIMER # sp804 select LAN9118 select PFLASH_CFI01 - select PL011 # UART + select PL011 if !HAVE_RUST # UART + select X_PL011_RUST if HAVE_RUST # UART select PL041 # audio codec select PL181 # display select REALVIEW
@@ -362,7 +370,8 @@ config RASPI default y depends on TCG && ARM select FRAMEBUFFER - select PL011 # UART + select PL011 if !HAVE_RUST # UART + select X_PL011_RUST if HAVE_RUST # UART select SDHCI select USB_DWC2 select BCM2835_SPI
@@ -438,7 +447,8 @@ config XLNX_VERSAL select ARM_GIC select CPU_CLUSTER select DEVICE_TREE - select PL011 + select PL011 if !HAVE_RUST # UART + select X_PL011_RUST if HAVE_RUST # UART select CADENCE select VIRTIO_MMIO select UNIMP
rust/Kconfig +1 -0
@@ -0,0 +1 @@ +source hw/Kconfig
rust/hw/Kconfig new file +2 -0
@@ -0,0 +1,2 @@ +# devices Kconfig +source char/Kconfig
rust/hw/char/Kconfig new file +3 -0
@@ -0,0 +1,3 @@ +config X_PL011_RUST + bool + default y if HAVE_RUST
rust/hw/char/meson.build new file +1 -0
@@ -0,0 +1 @@ +subdir('pl011')
rust/hw/char/pl011/.gitignore new file +2 -0
@@ -0,0 +1,2 @@ +# Ignore generated bindings file overrides. +src/bindings.rs.inc
rust/hw/char/pl011/Cargo.lock new file +134 -0
134 lines not on this page · raw message
rust/hw/char/pl011/Cargo.toml new file +26 -0
@@ -0,0 +1,26 @@ +[package] +name = "pl011" +version = "0.1.0" +edition = "2021" +authors = ["Manos Pitsidianakis <[email protected]>"] +license = "GPL-2.0-or-later" +readme = "README.md" +homepage = "https://www.qemu.org" +description = "pl011 device model for QEMU" +repository = "https://gitlab.com/epilys/rust-for-qemu" +resolver = "2" +publish = false +keywords = [] +categories = [] + +[lib] +crate-type = ["staticlib"] + +[dependencies] +bilge = { version = "0.2.0" } +bilge-impl = { version = "0.2.0" } +qemu_api = { path = "../../../qemu-api" } +qemu_api_macros = { path = "../../../qemu-api-macros" } + +# Do not include in any global workspace +[workspace]
rust/hw/char/pl011/README.md new file +31 -0
@@ -0,0 +1,31 @@ +# PL011 QEMU Device Model + +This library implements a device model for the PrimeCell® UART (PL011) +device in QEMU. + +## Build static lib + +Host build target must be explicitly specified: + +```sh +cargo build --target x86_64-unknown-linux-gnu +``` + +Replace host target triplet if necessary. + +## Generate Rust documentation + +To generate docs for this crate, including private items: + +```sh +cargo doc --no-deps --document-private-items --target x86_64-unknown-linux-gnu +``` + +To include direct dependencies like `bilge` (bitmaps for register types): + +```sh +cargo tree --depth 1 -e normal --prefix none \ + | cut -d' ' -f1 \ + | xargs printf -- '-p %s\n' \ + | xargs cargo doc --no-deps --document-private-items --target x86_64-unknown-linux-gnu +```
rust/hw/char/pl011/meson.build new file +26 -0
@@ -0,0 +1,26 @@ +subproject('bilge-0.2-rs', required: true) +subproject('bilge-impl-0.2-rs', required: true) + +bilge_dep = dependency('bilge-0.2-rs') +bilge_impl_dep = dependency('bilge-impl-0.2-rs') + +_libpl011_rs = static_library( + 'pl011', + files('src/lib.rs'), + override_options: ['rust_std=2021', 'build.rust_std=2021'], + rust_abi: 'rust', + dependencies: [ + bilge_dep, + bilge_impl_dep, + qemu_api, + qemu_api_macros, + ], +) + +rust_devices_ss.add(when: 'CONFIG_X_PL011_RUST', if_true: [declare_dependency( + link_whole: [_libpl011_rs], + # Putting proc macro crates in `dependencies` is necessary for Meson to find + # them when compiling the root per-target static rust lib. + dependencies: [bilge_impl_dep, qemu_api_macros], + variables: {'crate': 'pl011'}, +)])
rust/hw/char/pl011/src/device.rs new file +599 -0
599 lines not on this page · raw message
rust/hw/char/pl011/src/device_class.rs new file +70 -0
70 lines not on this page · raw message
rust/hw/char/pl011/src/lib.rs new file +586 -0
586 lines not on this page · raw message
rust/hw/char/pl011/src/memory_ops.rs new file +59 -0
59 lines not on this page · raw message
rust/hw/meson.build new file +1 -0
@@ -0,0 +1 @@ +subdir('char')
rust/meson.build +2 -0
@@ -1,2 +1,4 @@ subdir('qemu-api-macros') subdir('qemu-api') + +subdir('hw')
scripts/archive-source.sh +3 -1
@@ -27,7 +27,9 @@ sub_file="${sub_tdir}/submodule.tar" # in their checkout, because the build environment is completely # different to the host OS. subprojects="keycodemapdb libvfio-user berkeley-softfloat-3 - berkeley-testfloat-3 proc-macro2-1-rs quote-1-rs + berkeley-testfloat-3 arbitrary-int-1-rs bilge-0.2-rs + bilge-impl-0.2-rs either-1-rs itertools-0.11-rs proc-macro2-1-rs + proc-macro-error-1-rs proc-macro-error-attr-1-rs quote-1-rs syn-2-rs unicode-ident-1-rs" sub_deinit=""
scripts/make-release +3 -1
@@ -18,7 +18,9 @@ fi # Only include wraps that are invoked with subproject() SUBPROJECTS="libvfio-user keycodemapdb berkeley-softfloat-3 - berkeley-testfloat-3 proc-macro2-1-rs quote-1-rs + berkeley-testfloat-3 arbitrary-int-1-rs bilge-0.2-rs + bilge-impl-0.2-rs either-1-rs itertools-0.11-rs proc-macro2-1-rs + proc-macro-error-1-rs proc-macro-error-attr-1-rs quote-1-rs syn-2-rs unicode-ident-1-rs" src="$1"
scripts/rust/rust_root_crate.sh new file +13 -0
@@ -0,0 +1,13 @@ +#!/bin/sh + +set -eu + +cat <<EOF +// @generated +// This file is autogenerated by scripts/rust_root_crate.sh + +EOF + +for crate in $*; do + echo "extern crate $crate;" +done
subprojects/.gitignore +7 -0
@@ -6,6 +6,13 @@ /keycodemapdb /libvfio-user /slirp +/arbitrary-int-1.2.7 +/bilge-0.2.0 +/bilge-impl-0.2.0 +/either-1.12.0 +/itertools-0.11.0 +/proc-macro-error-1.0.4 +/proc-macro-error-attr-1.0.4 /proc-macro2-1.0.84 /quote-1.0.36 /syn-2.0.66
subprojects/arbitrary-int-1-rs.wrap new file +7 -0
@@ -0,0 +1,7 @@ +[wrap-file] +directory = arbitrary-int-1.2.7 +source_url = https://crates.io/api/v1/crates/arbitrary-int/1.2.7/download +source_filename = arbitrary-int-1.2.7.tar.gz +source_hash = c84fc003e338a6f69fbd4f7fe9f92b535ff13e9af8997f3b14b6ddff8b1df46d +#method = cargo +patch_directory = arbitrary-int-1-rs
subprojects/bilge-0.2-rs.wrap new file +7 -0
@@ -0,0 +1,7 @@ +[wrap-file] +directory = bilge-0.2.0 +source_url = https://crates.io/api/v1/crates/bilge/0.2.0/download +source_filename = bilge-0.2.0.tar.gz +source_hash = dc707ed8ebf81de5cd6c7f48f54b4c8621760926cdf35a57000747c512e67b57 +#method = cargo +patch_directory = bilge-0.2-rs
subprojects/bilge-impl-0.2-rs.wrap new file +7 -0
@@ -0,0 +1,7 @@ +[wrap-file] +directory = bilge-impl-0.2.0 +source_url = https://crates.io/api/v1/crates/bilge-impl/0.2.0/download +source_filename = bilge-impl-0.2.0.tar.gz +source_hash = feb11e002038ad243af39c2068c8a72bcf147acf05025dcdb916fcc000adb2d8 +#method = cargo +patch_directory = bilge-impl-0.2-rs
subprojects/either-1-rs.wrap new file +7 -0
@@ -0,0 +1,7 @@ +[wrap-file] +directory = either-1.12.0 +source_url = https://crates.io/api/v1/crates/either/1.12.0/download +source_filename = either-1.12.0.tar.gz +source_hash = 3dca9240753cf90908d7e4aac30f630662b02aebaa1b58a3cadabdb23385b58b +#method = cargo +patch_directory = either-1-rs
subprojects/itertools-0.11-rs.wrap new file +7 -0
@@ -0,0 +1,7 @@ +[wrap-file] +directory = itertools-0.11.0 +source_url = https://crates.io/api/v1/crates/itertools/0.11.0/download +source_filename = itertools-0.11.0.tar.gz +source_hash = b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57 +#method = cargo +patch_directory = itertools-0.11-rs
subprojects/packagefiles/arbitrary-int-1-rs/meson.build new file +19 -0
@@ -0,0 +1,19 @@ +project('arbitrary-int-1-rs', 'rust', + version: '1.2.7', + license: 'MIT', + default_options: []) + +_arbitrary_int_rs = static_library( + 'arbitrary_int', + files('src/lib.rs'), + gnu_symbol_visibility: 'hidden', + override_options: ['rust_std=2021', 'build.rust_std=2021'], + rust_abi: 'rust', + dependencies: [], +) + +arbitrary_int_dep = declare_dependency( + link_with: _arbitrary_int_rs, +) + +meson.override_dependency('arbitrary-int-1-rs', arbitrary_int_dep)
subprojects/packagefiles/bilge-0.2-rs/meson.build new file +29 -0
@@ -0,0 +1,29 @@ +project( + 'bilge-0.2-rs', + 'rust', + version : '0.2.0', + license : 'MIT or Apache-2.0', +) + +subproject('arbitrary-int-1-rs', required: true) +subproject('bilge-impl-0.2-rs', required: true) + +arbitrary_int_dep = dependency('arbitrary-int-1-rs') +bilge_impl_dep = dependency('bilge-impl-0.2-rs') + +lib = static_library( + 'bilge', + 'src/lib.rs', + override_options : ['rust_std=2021', 'build.rust_std=2021'], + rust_abi : 'rust', + dependencies: [ + arbitrary_int_dep, + bilge_impl_dep, + ], +) + +bilge_dep = declare_dependency( + link_with : [lib], +) + +meson.override_dependency('bilge-0.2-rs', bilge_dep)
subprojects/packagefiles/bilge-impl-0.2-rs/meson.build new file +45 -0
45 lines not on this page · raw message
subprojects/packagefiles/either-1-rs/meson.build new file +24 -0
@@ -0,0 +1,24 @@ +project('either-1-rs', 'rust', + version: '1.12.0', + license: 'MIT OR Apache-2.0', + default_options: []) + +_either_rs = static_library( + 'either', + files('src/lib.rs'), + gnu_symbol_visibility: 'hidden', + override_options: ['rust_std=2018', 'build.rust_std=2018'], + rust_abi: 'rust', + rust_args: [ + '--cfg', 'feature="use_std"', + '--cfg', 'feature="use_alloc"', + ], + dependencies: [], + native: true, +) + +either_dep = declare_dependency( + link_with: _either_rs, +) + +meson.override_dependency('either-1-rs', either_dep, native: true)
subprojects/packagefiles/itertools-0.11-rs/meson.build new file +30 -0
@@ -0,0 +1,30 @@ +project('itertools-0.11-rs', 'rust', + version: '0.11.0', + license: 'MIT OR Apache-2.0', + default_options: []) + +subproject('either-1-rs', required: true) + +either_dep = dependency('either-1-rs', native: true) + +_itertools_rs = static_library( + 'itertools', + files('src/lib.rs'), + gnu_symbol_visibility: 'hidden', + override_options: ['rust_std=2018', 'build.rust_std=2018'], + rust_abi: 'rust', + rust_args: [ + '--cfg', 'feature="use_std"', + '--cfg', 'feature="use_alloc"', + ], + dependencies: [ + either_dep, + ], + native: true, +) + +itertools_dep = declare_dependency( + link_with: _itertools_rs, +) + +meson.override_dependency('itertools-0.11-rs', itertools_dep, native: true)
subprojects/packagefiles/proc-macro-error-1-rs/meson.build new file +40 -0
@@ -0,0 +1,40 @@ +project('proc-macro-error-1-rs', 'rust', + version: '1.0.4', + license: 'MIT OR Apache-2.0', + default_options: []) + +subproject('proc-macro-error-attr-1-rs', required: true) +subproject('quote-1-rs', required: true) +subproject('syn-2-rs', required: true) +subproject('proc-macro2-1-rs', required: true) + +proc_macro_error_attr_dep = dependency('proc-macro-error-attr-1-rs', native: true) +proc_macro2_dep = dependency('proc-macro2-1-rs', native: true) +quote_dep = dependency('quote-1-rs', native: true) +syn_dep = dependency('syn-2-rs', native: true) + +_proc_macro_error_rs = static_library( + 'proc_macro_error', + files('src/lib.rs'), + override_options: ['rust_std=2018', 'build.rust_std=2018'], + rust_abi: 'rust', + rust_args: [ + '--cfg', 'use_fallback', + '--cfg', 'feature="syn-error"', + '--cfg', 'feature="proc-macro"', + '-A', 'non_fmt_panics' + ], + dependencies: [ + proc_macro_error_attr_dep, + proc_macro2_dep, + quote_dep, + syn_dep, + ], + native: true, +) + +proc_macro_error_dep = declare_dependency( + link_with: _proc_macro_error_rs, +) + +meson.override_dependency('proc-macro-error-1-rs', proc_macro_error_dep, native: true)
subprojects/packagefiles/proc-macro-error-attr-1-rs/meson.build new file +32 -0
@@ -0,0 +1,32 @@ +project('proc-macro-error-attr-1-rs', 'rust', + version: '1.12.0', + license: 'MIT OR Apache-2.0', + default_options: []) + +subproject('proc-macro2-1-rs', required: true) +subproject('quote-1-rs', required: true) + +proc_macro2_dep = dependency('proc-macro2-1-rs', native: true) +quote_dep = dependency('quote-1-rs', native: true) + +rust = import('rust') +_proc_macro_error_attr_rs = rust.proc_macro( + 'proc_macro_error_attr', + files('src/lib.rs'), + override_options: ['rust_std=2018', 'build.rust_std=2018'], + rust_args: [ + '--cfg', 'use_fallback', + '--cfg', 'feature="syn-error"', + '--cfg', 'feature="proc-macro"' + ], + dependencies: [ + proc_macro2_dep, + quote_dep, + ], +) + +proc_macro_error_attr_dep = declare_dependency( + link_with: _proc_macro_error_attr_rs, +) + +meson.override_dependency('proc-macro-error-attr-1-rs', proc_macro_error_attr_dep, native: true)
subprojects/packagefiles/unicode-ident-1-rs/meson.build new file +20 -0
@@ -0,0 +1,20 @@ +project('unicode-ident-1-rs', 'rust', + version: '1.0.12', + license: '(MIT OR Apache-2.0) AND Unicode-DFS-2016', + default_options: []) + +_unicode_ident_rs = static_library( + 'unicode_ident', + files('src/lib.rs'), + gnu_symbol_visibility: 'hidden', + override_options: ['rust_std=2021', 'build.rust_std=2021'], + rust_abi: 'rust', + dependencies: [], + native: true, +) + +unicode_ident_dep = declare_dependency( + link_with: _unicode_ident_rs, +) + +meson.override_dependency('unicode-ident-1-rs', unicode_ident_dep, native: true)
subprojects/proc-macro-error-1-rs.wrap new file +7 -0
@@ -0,0 +1,7 @@ +[wrap-file] +directory = proc-macro-error-1.0.4 +source_url = https://crates.io/api/v1/crates/proc-macro-error/1.0.4/download +source_filename = proc-macro-error-1.0.4.tar.gz +source_hash = da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c +#method = cargo +patch_directory = proc-macro-error-1-rs
subprojects/proc-macro-error-attr-1-rs.wrap new file +7 -0
@@ -0,0 +1,7 @@ +[wrap-file] +directory = proc-macro-error-attr-1.0.4 +source_url = https://crates.io/api/v1/crates/proc-macro-error-attr/1.0.4/download +source_filename = proc-macro-error-attr-1.0.4.tar.gz +source_hash = a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869 +#method = cargo +patch_directory = proc-macro-error-attr-1-rs
Signature · 1 line
2.45.2
PATCH 3/11 rust/qemu-api-macros: introduce Device proc macro
In reply to Manos PitsidianakisAdd a new derive procedural macro to declare device models. Add corresponding DeviceImpl trait after already existing ObjectImpl trait. At the same time, add instance_init, instance_post_init, instance_finalize methods to the ObjectImpl trait and call them from the ObjectImplUnsafe trait, which is generated by the procedural macro.
This allows all the boilerplate device model registration to be handled by macros, and all pertinent details to be declared through proc macro attributes or trait associated constants and methods.
The device class can now be generated automatically and the name can be optionally overridden:
------------------------ >8 ------------------------
#[repr(C)]
#[derive(Debug, qemu_api_macros::Object, qemu_api_macros::Device)] #[device(class_name_override = PL011Class)]
/// PL011 Device Model in QEMU
pub struct PL011State {
------------------------ >8 ------------------------
Properties are now marked as field attributes:
------------------------ >8 ------------------------
#[property(name = c"chardev", qdev_prop = qdev_prop_chr)] pub char_backend: CharBackend,
------------------------ >8 ------------------------
Object methods (instance_init, etc) methods are now trait methods:
------------------------ >8 ------------------------
/// Trait a type must implement to be registered with QEMU.
pub trait ObjectImpl {
type Class: ClassImpl;
const TYPE_NAME: &'static CStr;
const PARENT_TYPE_NAME: Option<&'static CStr>;
const ABSTRACT: bool;
unsafe fn instance_init(&mut self) {}
fn instance_post_init(&mut self) {}
fn instance_finalize(&mut self) {} }
------------------------ >8 ------------------------
Device methods (realize/reset etc) are now safe idiomatic trait methods:
------------------------ >8 ------------------------
/// Implementation methods for device types.
pub trait DeviceImpl: ObjectImpl {
fn realize(&mut self) {}
fn reset(&mut self) {} }
------------------------ >8 ------------------------
The derive Device macro is responsible for creating all the extern "C" FFI functions that QEMU needs to call these methods.
--- rust/hw/char/pl011/src/device.rs | 124 +++----- rust/hw/char/pl011/src/device_class.rs | 70 ----- rust/hw/char/pl011/src/lib.rs | 1 - rust/qemu-api-macros/src/device.rs | 433 ++++++++++++++++++++++++++ rust/qemu-api-macros/src/lib.rs | 45 +-- rust/qemu-api-macros/src/object.rs | 107 +++++++ rust/qemu-api-macros/src/symbols.rs | 55 ++++ rust/qemu-api-macros/src/utilities.rs | 152 +++++++++ rust/qemu-api/meson.build | 3 +- rust/qemu-api/src/definitions.rs | 97 ------ rust/qemu-api/src/device_class.rs | 128 -------- rust/qemu-api/src/lib.rs | 6 +- rust/qemu-api/src/objects.rs | 90 ++++++ rust/qemu-api/src/tests.rs | 49 --- subprojects/packagefiles/syn-2-rs/meson.build | 1 + 15 files changed, 902 insertions(+), 459 deletions(-)
rust/hw/char/pl011/src/device.rs +50 -74
@@ -9,7 +9,7 @@use qemu_api::{ bindings::{self, *}, - definitions::ObjectImpl , + objects::*, };use crate ::{
@@ -26,7 +26,8 @@pub const PL011_FIFO_DEPTH :usize =16_usize ;#[repr( C )] -#[derive( Debug , qemu_api_macros:: Object )] +#[derive( Debug , qemu_api_macros:: Object , qemu_api_macros:: Device )] +#[device(class_name_override = PL011Class )] /// PL011 Device Model in QEMU pub struct PL011State {pub parent_obj:SysBusDevice ,
@@ -51,6 +52,7 @@ pub struct PL011State { pub read_count: usize, pub read_trigger: usize,#[doc(alias = "chr" )] +#[property(name = c"chardev" , qdev_prop = qdev_prop_chr)] pub char_backend: CharBackend,/// QEMU interrupts ///
@@ -68,38 +70,17 @@ pub struct PL011State {#[doc(alias = "clk" )] pub clock: NonNull<Clock>,#[doc(alias = "migrate_clk" )] +#[property(name = c"migrate-clk" , qdev_prop = qdev_prop_bool)] pub migrate_clock: bool, }impl ObjectImpl for PL011State {type Class =PL011Class ; -const TYPE_INFO : qemu_api::bindings::TypeInfo = qemu_api::type_info! {Self }; +const TYPE_NAME : &'staticCStr =crate ::TYPE_PL011 ;const PARENT_TYPE_NAME :Option <&'staticCStr > =Some (TYPE_SYS_BUS_DEVICE );const ABSTRACT :bool =false ; -const INSTANCE_INIT :Option <unsafe extern "C" fn (obj: *mut Object )> =Some (pl011_init); -const INSTANCE_POST_INIT :Option <unsafe extern "C" fn (obj: *mut Object )> =None ; -const INSTANCE_FINALIZE :Option <unsafe extern "C" fn (obj: *mut Object )> =None ; -} -#[repr( C )] -pub struct PL011Class { - _inner: [u8 ;0 ], -} - -impl qemu_api::definitions::Class for PL011Class { -const CLASS_INIT :Option < -unsafe extern "C" fn (klass: *mut ObjectClass , data: *mut core::ffi::c_void ), - > =Some (crate ::device_class::pl011_class_init); -const CLASS_BASE_INIT :Option < -unsafe extern "C" fn (klass: *mut ObjectClass , data: *mut core::ffi::c_void ), - > =None ; -} - -#[used] -pub static CLK_NAME : &CStr =c"clk" ; - -impl PL011State {/// Initializes a pre-allocated, unitialized instance of `PL011State`. /// /// # Safety
@@ -108,7 +89,7 @@ impl PL011State {/// `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`. -pub unsafe fn init (&mut self) { +unsafe fn instance_init (&mut self) {let dev =addr_of_mut! (*self).cast ::<DeviceState >();// SAFETY: //
@@ -120,7 +101,7 @@ pub unsafe fn init(&mut self) { addr_of_mut!(*self).cast::<Object>(), &PL011_OPS, addr_of_mut!(*self).cast::<c_void>(), - Self::TYPE_INFO.name, + Self::TYPE_NAME.as_ptr(), 0x1000, );let sbd =addr_of_mut! (*self).cast ::<SysBusDevice >();
@@ -147,7 +128,49 @@ pub unsafe fn init(&mut self) { .unwrap(); } } +} +impl DeviceImpl for PL011State { +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 , + ); + } + } + +fn reset (&mut self) { + self.line_control.reset (); + self.receive_status_error_clear.reset (); + self.dmacr =0 ; + self.int_enabled =0 ; + self.int_level =0 ; + self.ilpr =0 ; + self.ibrd =0 ; + self.fbrd =0 ; + self.read_trigger =1 ; + self.ifl =0x12 ; + self.control.reset (); + self.flags =0 .into (); + self.reset_fifo (); + } +} + +impl qemu_api::objects::Migrateable for PL011State {} + +#[used] +pub static CLK_NAME : &CStr =c"clk" ; + +impl PL011State {pub fn read ( &mut self, offset: hwaddr,
@@ -394,39 +417,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 (); - self.dmacr =0 ; - self.int_enabled =0 ; - self.int_level =0 ; - self.ilpr =0 ; - self.ibrd =0 ; - self.fbrd =0 ; - self.read_trigger =1 ; - self.ifl =0x12 ; - self.control.reset (); - self.flags =0 .into (); - self.reset_fifo (); - } -pub fn reset_fifo (&mut self) { self.read_count =0 ; self.read_pos =0 ;
@@ -583,17 +573,3 @@ pub fn update(&self) { dev } } - -/// # Safety -/// -/// We expect the FFI user of this function to pass a valid pointer, that has -/// the same size as [`PL011State`]. We also expect the device is -/// readable/writeable from one thread at any time. -#[no_mangle] -pub unsafe extern "C" fn pl011_init (obj: *mut Object ) { -unsafe { -debug_assert! (!obj.is_null ()); -let mut state =NonNull ::new_unchecked (obj.cast ::<PL011State >()); - state.as_mut ().init (); - } -}
rust/hw/char/pl011/src/device_class.rs deleted +0 -70
70 lines not on this page · raw message
rust/hw/char/pl011/src/lib.rs +0 -1
@@ -42,7 +42,6 @@extern crate qemu_api;pub mod device; -pub mod device_class;pub mod memory_ops;pub const TYPE_PL011 : &::core::ffi::CStr =c"pl011" ;
rust/qemu-api-macros/src/device.rs new file +433 -0
433 lines not on this page · raw message
rust/qemu-api-macros/src/lib.rs +12 -33
54 lines not on this page · raw message
rust/qemu-api-macros/src/object.rs new file +107 -0
107 lines not on this page · raw message
rust/qemu-api-macros/src/symbols.rs new file +55 -0
55 lines not on this page · raw message
rust/qemu-api-macros/src/utilities.rs new file +152 -0
152 lines not on this page · raw message
rust/qemu-api/meson.build +1 -2
@@ -3,8 +3,7 @@ _qemu_api_rs = static_library( structured_sources( [ 'src/lib.rs', - 'src/definitions.rs', - 'src/device_class.rs', + 'src/objects.rs', ], {'.' : bindings_rs}, ),
rust/qemu-api/src/definitions.rs deleted +0 -97
97 lines not on this page · raw message
rust/qemu-api/src/device_class.rs deleted +0 -128
128 lines not on this page · raw message
rust/qemu-api/src/lib.rs +1 -5
@@ -27,11 +27,7 @@ unsafe impl Sync for bindings::Property {}unsafe impl Sync for bindings::TypeInfo {}unsafe impl Sync for bindings::VMStateDescription {} -pub mod definitions; -pub mod device_class; - -#[cfg(test)] -mod tests; +pub mod objects;use std::alloc::{GlobalAlloc ,Layout };
rust/qemu-api/src/objects.rs new file +90 -0
90 lines not on this page · raw message
rust/qemu-api/src/tests.rs deleted +0 -49
49 lines not on this page · raw message
subprojects/packagefiles/syn-2-rs/meson.build +1 -0
@@ -24,6 +24,7 @@ _syn_rs = static_library( '--cfg', 'feature="printing"', '--cfg', 'feature="clone-impls"', '--cfg', 'feature="proc-macro"', + '--cfg', 'feature="extra-traits"', ], dependencies: [ quote_dep,
Signature · 1 line
2.45.2
Re: [PATCH 03/11] rust/qemu-api-macros: introduce Device proc macro
Quoted 67 lines · Manos Pitsidianakis
Add a new derive procedural macro to declare device models. Add corresponding DeviceImpl trait after already existing ObjectImpl trait. At the same time, add
instance_init,instance_post_init,instance_finalizemethods to the ObjectImpl trait and call them from the ObjectImplUnsafe trait, which is generated by the procedural macro.This allows all the boilerplate device model registration to be handled by macros, and all pertinent details to be declared through proc macro attributes or trait associated constants and methods.
The device class can now be generated automatically and the name can be optionally overridden:
------------------------ >8 ------------------------
#[repr(C)]
#[derive(Debug,qemu_api_macros::Object,qemu_api_macros::Device)] #[device(class_name_override = PL011Class)]
/// PL011 Device Model in QEMU
pub struct PL011State {
------------------------ >8 ------------------------Properties are now marked as field attributes:
------------------------ >8 ------------------------
#[property(name = c"chardev",qdev_prop=qdev_prop_chr)] pubchar_backend: CharBackend,
------------------------ >8 ------------------------Object methods (
instance_init, etc) methods are now trait methods:------------------------ >8 ------------------------
/// Trait a type must implement to be registered with QEMU.pub trait ObjectImpl { type Class: ClassImpl; const TYPE_NAME: &'static CStr; const PARENT_TYPE_NAME: Option<&'static CStr>; const ABSTRACT: bool; unsafe fn instance_init(&mut self) {} fn instance_post_init(&mut self) {} fn instance_finalize(&mut self) {}}
------------------------ >8 ------------------------Device methods (realize/reset etc) are now safe idiomatic trait methods:
------------------------ >8 ------------------------
/// Implementation methods for device types.pub trait DeviceImpl: ObjectImpl { fn realize(&mut self) {} fn reset(&mut self) {}}
------------------------ >8 ------------------------The derive Device macro is responsible for creating all the extern "C" FFI functions that QEMU needs to call these methods.
Signed-off-by Manos Pitsidianakis <[email protected]>--- rust/hw/char/pl011/src/device.rs | 124 +++----- rust/hw/char/pl011/src/device_class.rs | 70 ----- rust/hw/char/pl011/src/lib.rs | 1 - rust/qemu-api-macros/src/device.rs | 433 ++++++++++++++++++++++++++ rust/qemu-api-macros/src/lib.rs | 45 +-- rust/qemu-api-macros/src/object.rs | 107 +++++++ rust/qemu-api-macros/src/symbols.rs | 55 ++++ rust/qemu-api-macros/src/utilities.rs | 152 +++++++++
Quoted 8 lines
rust/qemu-api/meson.build | 3 +- rust/qemu-api/src/definitions.rs | 97 ------ rust/qemu-api/src/device_class.rs | 128 -------- rust/qemu-api/src/lib.rs | 6 +- rust/qemu-api/src/objects.rs | 90 ++++++ rust/qemu-api/src/tests.rs | 49 --- subprojects/packagefiles/syn-2-rs/meson.build | 1 + 15 files changed, 902 insertions(+), 459 deletions(-)
My initial reaction is these patches are getting quite large because we are doing several things at once. Is it possible to split them so:
- we bring in one macro at a time (with unit tests)
- we then convert pl011 to the new idiom
?
Signature · 2 lines
Alex Bennée Virtualisation Tech Lead @ Linaro
Re: [PATCH 03/11] rust/qemu-api-macros: introduce Device proc macro
Quoted 79 lines · Alex Bennée
Quoted 67 lines · Manos Pitsidianakis
Add a new derive procedural macro to declare device models. Add corresponding DeviceImpl trait after already existing ObjectImpl trait. At the same time, add
instance_init,instance_post_init,instance_finalizemethods to the ObjectImpl trait and call them from the ObjectImplUnsafe trait, which is generated by the procedural macro.This allows all the boilerplate device model registration to be handled by macros, and all pertinent details to be declared through proc macro attributes or trait associated constants and methods.
The device class can now be generated automatically and the name can be optionally overridden:
------------------------ >8 ------------------------
#[repr(C)]
#[derive(Debug,qemu_api_macros::Object,qemu_api_macros::Device)] #[device(class_name_override = PL011Class)]
/// PL011 Device Model in QEMU
pub struct PL011State {
------------------------ >8 ------------------------Properties are now marked as field attributes:
------------------------ >8 ------------------------
#[property(name = c"chardev",qdev_prop=qdev_prop_chr)] pubchar_backend: CharBackend,
------------------------ >8 ------------------------Object methods (
instance_init, etc) methods are now trait methods:------------------------ >8 ------------------------
/// Trait a type must implement to be registered with QEMU.pub trait ObjectImpl { type Class: ClassImpl; const TYPE_NAME: &'static CStr; const PARENT_TYPE_NAME: Option<&'static CStr>; const ABSTRACT: bool; unsafe fn instance_init(&mut self) {} fn instance_post_init(&mut self) {} fn instance_finalize(&mut self) {}}
------------------------ >8 ------------------------Device methods (realize/reset etc) are now safe idiomatic trait methods:
------------------------ >8 ------------------------
/// Implementation methods for device types.pub trait DeviceImpl: ObjectImpl { fn realize(&mut self) {} fn reset(&mut self) {}}
------------------------ >8 ------------------------The derive Device macro is responsible for creating all the extern "C" FFI functions that QEMU needs to call these methods.
Signed-off-by Manos Pitsidianakis <[email protected]>--- rust/hw/char/pl011/src/device.rs | 124 +++----- rust/hw/char/pl011/src/device_class.rs | 70 ----- rust/hw/char/pl011/src/lib.rs | 1 - rust/qemu-api-macros/src/device.rs | 433 ++++++++++++++++++++++++++ rust/qemu-api-macros/src/lib.rs | 45 +-- rust/qemu-api-macros/src/object.rs | 107 +++++++ rust/qemu-api-macros/src/symbols.rs | 55 ++++ rust/qemu-api-macros/src/utilities.rs | 152 +++++++++Quoted 8 lines
rust/qemu-api/meson.build | 3 +- rust/qemu-api/src/definitions.rs | 97 ------ rust/qemu-api/src/device_class.rs | 128 -------- rust/qemu-api/src/lib.rs | 6 +- rust/qemu-api/src/objects.rs | 90 ++++++ rust/qemu-api/src/tests.rs | 49 --- subprojects/packagefiles/syn-2-rs/meson.build | 1 + 15 files changed, 902 insertions(+), 459 deletions(-)
Quoted 5 lines
My initial reaction is these patches are getting quite large because we are doing several things at once. Is it possible to split them so:
- we bring in one macro at a time (with unit tests)
- we then convert pl011 to the new idiom
Sure, I think it's possible to split them on some level. (Make changes on the existing Object derive macro and then introduce the Device macro) We can't unfortunately do changes without pl011 not being updated though, since it uses the code.
As for unit tests, the only way to test proc macros is to match generated code output to expected output. Otherwise they are indirectly tested by the device not breaking other qemu tests. What do you think should be our unit testing approach for this instance?
Re: [PATCH 03/11] rust/qemu-api-macros: introduce Device proc macro
In reply to Manos PitsidianakisQuoted 20 lines · Manos Pitsidianakis
Add a new derive procedural macro to declare device models. Add corresponding DeviceImpl trait after already existing ObjectImpl trait. At the same time, add
instance_init,instance_post_init,instance_finalizemethods to the ObjectImpl trait and call them from the ObjectImplUnsafe trait, which is generated by the procedural macro.This allows all the boilerplate device model registration to be handled by macros, and all pertinent details to be declared through proc macro attributes or trait associated constants and methods.
The device class can now be generated automatically and the name can be optionally overridden:------------------------ >8 ------------------------ #[repr(C)] #[derive(Debug, qemu_api_macros::Object, qemu_api_macros::Device)] #[device(class_name_override = PL011Class)] /// PL011 Device Model in QEMU pub struct PL011State { ------------------------ >8 ------------------------
Quoted 6 lines
Properties are now marked as field attributes:
------------------------ >8 ------------------------#[property(name = c"chardev",
qdev_prop=qdev_prop_chr)] pubchar_backend: CharBackend,
------------------------ >8 ------------------------
Let's look at this from the point of view of separating the code into multiple patches.
This part is probably the easiest to extract. We can start the device impl trait with just the properties:
pub trait DeviceImpl {
const PROPERTIES: &[Property] = &[];
}and then the device_class_init! macro can use <$type as DeviceImpl>::PROPERTIES instead of $props.
qemu_api::device_class_init! {
- pl011_class_init,
- props => PL011_PROPERTIES,
+ PL011State, pl011_class_init,
realize_fn => Some(pl011_realize),
legacy_reset_fn => Some(pl011_reset),
vmsd => VMSTATE_PL011,}
Quoted 13 lines
Object methods (
instance_init, etc) methods are now trait methods:------------------------ >8 ------------------------ /// Trait a type must implement to be registered with QEMU. pub trait ObjectImpl { type Class: ClassImpl; const TYPE_NAME: &'static CStr; const PARENT_TYPE_NAME: Option<&'static CStr>; const ABSTRACT: bool; unsafe fn instance_init(&mut self) {} fn instance_post_init(&mut self) {} fn instance_finalize(&mut self) {}
Quoted 2 lines
}
------------------------ >8 ------------------------
Some comments here:
- instance_init should take either "instance: *mut self" or even better "instance: &mut MaybeUninit<self>".
- for all Rust objects the implementation of instance_finalize() should just be ptr::drop_in_place(obj), so this need not be included in the trait.
TYPE_NAME/PARENT_TYPE_NAME/ABSTRACT could be passed to the #[derive(Object)] macro, for example:
#[derive(Object)]
// abstract can be optional
#[object(type_name="pl011", parent_type=DeviceState, abstract=false,
class_type=PL011Class)]
while the "fn instance_init()" remains as a trait implementation in pl011/src/device.rs.
Because a trait can be implemented only once, this suggests separating the trait(s) in two: one for the constants that can be generated from the macro, one for the functions that form the vtable. This is true for both objects and devices:
pub trait ObjectInfo {
type Class: ClassImpl;
const TYPE_NAME: &'static CStr;
const PARENT_TYPE_NAME: Option<&'static CStr>;
const ABSTRACT: bool;
}pub trait ObjectImpl: ObjectInfo {
unsafe fn instance_init(instance: &mut MaybeUninit<self>) {}
}and likewise:
Quoted 9 lines
Device methods (realize/reset etc) are now safe idiomatic trait methods:
------------------------ >8 ------------------------ /// Implementation methods for device types. pub trait DeviceImpl: ObjectImpl { fn realize(&mut self) {} fn reset(&mut self) {} } ------------------------ >8 ------------------------
pub trait DeviceInfo {
const PROPERTIES: &[Property] = &[];
}pub trait DeviceImpl: ObjectImpl + DeviceInfo {
fn realize(&mut self) {}
fn reset(&mut self) {}
const VMSTATE: Option<VMStateDescription> = None;
}(Generally, don't read too much in the code - the syntax might have issues but you get the idea).
Anyhow, going forward to the property attribute:
Quoted 1 line
+ #[property(name = c"migrate-clk",
qdev_prop=qdev_prop_bool)]
There are two issues here:
First, the default is true, so 1) this has to be fixed in QEMU (will do), 2) it is important to support it in #[property()].
Second, this provides a false sense of safety, because I could specify qdev_prop_chr here. Instead, the qdev_prop type should be derived by the field type.
Third, since we are at it there's no need to use c"" in the attribute. The c_str!() macro that I am adding for backwards compatibility to old versions of Rust might actually come in handy here.
The part where I have most comments, and some ideas of how to make your work a little more maintainable, is the implementation of class_init (and all that depends on it).
Let's start with these generated functions:
Quoted 9 lines
rust/qemu-api-macros/src/device.rs new file +9
-0+ pub unsafe extern "C" fn #realize_fn( + dev: *mut ::qemu_api::bindings::DeviceState , + errp: *mut *mut ::qemu_api::bindings::Error , + ) { + let mut instance = NonNull::new(dev.cast::<#name>()).expect(concat!("Expected dev to be a non-null pointer of type ", stringify!(#name))); +unsafe { + ::qemu_api::objects::DeviceImpl ::realize (instance.as_mut ()); + } + }
rust/qemu-api-macros/src/device.rs line 169
Quoted 10 lines
rust/qemu-api-macros/src/device.rs new file +10
-0+ +#[no_mangle] + pub unsafe extern "C" fn #reset_fn( + dev: *mut ::qemu_api::bindings::DeviceState , + ) { + let mut instance = NonNull::new(dev.cast::<#name>()).expect(concat!("Expected dev to be a non-null pointer of type ", stringify!(#name))); +unsafe { + ::qemu_api::objects::DeviceImpl ::reset (instance.as_mut ()); + } + }
This can be handled entirely in Rust code, outside the macro. If you add:
unsafe extern "C" fn realize_fn_unsafe<T: DeviceImpl>(
dev: *mut DeviceState,
errp: *mut *mut Error,
) {
let mut instance = NonNull::new(dev.cast::<T>()).
expect("Expected dev to be a non-null pointer");
unsafe {
::qemu_api::objects::DeviceImpl::realize(instance.as_mut());
}
}unsafe extern "C" fn reset_fn_unsafe<T: DeviceImpl>(
dev: *mut ::qemu_api::bindings::DeviceState,
) {
let mut instance = NonNull::new(dev.cast::<T>()).
expect("Expected dev to be a non-null pointer");
unsafe {
::qemu_api::objects::DeviceImpl::reset(instance.as_mut());
}
}then the functions can be used directly instead of #realize_fn and #reset_fn with a blanket implementation of DeviceImplUnsafe:
unsafe impl DeviceImplUnsafe for T: DeviceImpl {
const REALIZE: ... = Some(realize_fn_unsafe::<T>);
const RESET: ... = Some(realize_fn_unsafe::<T>);
}Going on to the implementation of the safe functions:
rust/hw/char/pl011/src/device.rs pub unsafe fn init(&mut self) { · line 134
Quoted 2 lines
rust/hw/char/pl011/src/device.rs +2
-0+impl DeviceImpl for PL011State { +fn realize (&mut self) {
These are not quite traits. First, you can implement only some of the functions. Second, if you don't implement them they are not overwritten by the class_init method.
So this points to a different implementation as an attribute macro, which is able to rewrite everything in the body of the impl. For example:
#[qom_class_init]
impl DeviceImpl for PL011State {
fn realize(&mut self) { ... }
fn reset(&mut self) { ... }
const VMSTATE: ... = {}
const CATEGORY: ... = {}
}can be transformed into:
#[qom_class_init]
impl DeviceImpl for PL011State {
// fns are wrapped and transformed into consts
const REALIZE: Option<fn(&mut self)> = {
fn realize(&mut self) { ... }
Some(realize)
};
const RESET: Option<fn(&mut self)> = {
fn reset(&mut self) { ... }
Some(reset)
};
// while associated consts (and perhaps types?) remain as is
const VMSTATE: ... = {}
const CATEGORY: ... = {}
}The above blanket implementation of DeviceImplUnsafe is easily adjusted to support non-overridden methods:
unsafe impl DeviceImplUnsafe for T: DeviceImpl {
const REALIZE: ... = <T as DeviceImpl>::REALIZE::map(
|| realize_fn_unsafe::<T>);
const RESET: ... = <T as DeviceImpl>::RESET::map(
|| realize_fn_unsafe::<T>);
}You can also keep out of the macro the class_init method itself. Here I'm adding it to DeviceImplUnsafe:
pub trait DeviceImplUnsafe {
unsafe fn class_init(klass: *mut ObjectClass, data: *mut c_void) {
let mut dc = NonNull::new(klass.cast::<DeviceClass>()).unwrap();
unsafe {
dc.as_mut().realize = Self::REALIZE;
bindings::device_class_set_legacy_reset(
dc.as_mut(), Self::RESET);
device_class_set_props(dc.as_mut(),
<Self as DeviceInfo>::PROPS);
if let Some(vmsd) = <Self as DeviceInfo>::VMSTATE {
dc.as_mut().vmsd = vmsd;
}
if let Some(cat) = <Self as DeviceInfo>::CATEGORY {
dc.as_mut().category = cat;
}
// maybe in the future for unparent
// <Self as ObjectImplUnsafe>::class_init(klass, data)
}
}
}And with all this machinery in place the device_class_init! macro becomes simply
device_class_init!(PL011State);
(because the arguments have moved to DeviceInfo or DeviceImpl).
Why is this important? Because the only code transformation is the generation of properties and vtables, and the bindings can be developed almost entirely in qemu_api instead of qemu_api_macros. This has several advantages:
1) it's much easier: simpler error messages, no macro indirection, no super long global crate paths
2) it allows simplifying the pl011 code piecewise, even before introducing procedural macro code
3) it's easier to add comments
It also becomes much easier to separate the work in separate patches, or even separate series. Replacing the arguments to device_class_init!() with DeviceImpl + DeviceImplUnsafe can be introduced first: posted, reviewed, merged. All the remaining tasks are pretty much independent:
1) splitting out ObjectInfo and introducing #[object] to automate it (i.e. extending derive(Object))
2) splitting out DeviceInfo and introducing #[property] to automate it (i.e. derive(Device))
3) the #[qom_class_init] macro
A final word: I absolutely don't want you to think that your work is of no value. It's totally okay to throw away the first version of something. You showed that it _is_ possible to have idiomatic code with the help of procedural macros. Even if the implementation can be improved, the _idea_ remains yours.
Paolo
Re: [PATCH 03/11] rust/qemu-api-macros: introduce Device proc macro
Quoted 5 lines · Paolo Bonzini
(Generally, don't read too much in the code - the syntax might have issues but you get the idea).
Quoted 8 lines
Anyhow, going forward to the property attribute:
Quoted 1 line
+ #[property(name = c"migrate-clk",
qdev_prop=qdev_prop_bool)]There are two issues here:
First, the default is true, so 1) this has to be fixed in QEMU (will do), 2) it is important to support it in #[property()].
TODO, it was not ignored just planned as next
Quoted 4 lines
Second, this provides a false sense of safety, because I could specify
qdev_prop_chrhere. Instead, theqdev_proptype should be derived by the field type.
TODO, if you recall we had that discussion about external statics, that was what I was looking into back then.
Quoted 3 lines
Third, since we are at it there's no need to use c"" in the attribute. The c_str!() macro that I am adding for backwards compatibility to old versions of Rust might actually come in handy here.
TODO, you can you use both LitStr and LitCStr in the macro
Quoted 27 lines
The part where I have most comments, and some ideas of how to make your work a little more maintainable, is the implementation of
class_init(and all that depends on it).Let's start with these generated functions:
Quoted 9 lines
rust/qemu-api-macros/src/device.rs new file +9
-0+ pub unsafe extern "C" fn #realize_fn( + dev: *mut ::qemu_api::bindings::DeviceState , + errp: *mut *mut ::qemu_api::bindings::Error , + ) { + let mut instance = NonNull::new(dev.cast::<#name>()).expect(concat!("Expected dev to be a non-null pointer of type ", stringify!(#name))); +unsafe { + ::qemu_api::objects::DeviceImpl ::realize (instance.as_mut ()); + } + }rust/qemu-api-macros/src/device.rs line 169
Quoted 10 lines
rust/qemu-api-macros/src/device.rs new file +10
-0+ +#[no_mangle] + pub unsafe extern "C" fn #reset_fn( + dev: *mut ::qemu_api::bindings::DeviceState , + ) { + let mut instance = NonNull::new(dev.cast::<#name>()).expect(concat!("Expected dev to be a non-null pointer of type ", stringify!(#name))); +unsafe { + ::qemu_api::objects::DeviceImpl ::reset (instance.as_mut ()); + } + }
Quoted 1 line
This can be handled entirely in Rust code, outside the macro. If you add:
Why? I don't understand what this solves. These are *just* trampoline functions to call the Rust-abi code.
Quoted 22 lines
unsafe extern "C" fn realize_fn_unsafe<T: DeviceImpl>(
dev: *mut DeviceState,
errp: *mut *mut Error,) { let mut instance = NonNull::new(dev.cast::<T>()). expect("Expected dev to be a non-null pointer"); unsafe { ::qemu_api::objects::DeviceImpl::realize(instance.as_mut()); } }unsafe extern "C" fn reset_fn_unsafe<T: DeviceImpl>(
dev: *mut ::qemu_api::bindings::DeviceState,) { let mut instance = NonNull::new(dev.cast::<T>()). expect("Expected dev to be a non-null pointer"); unsafe { ::qemu_api::objects::DeviceImpl::reset(instance.as_mut()); } }
Quoted 3 lines
then the functions can be used directly instead of #realize_fn and #reset_fn with a blanket implementation of DeviceImplUnsafe:
So just rename them and put a generic argument. Still not seeing any gain here.
Quoted 6 lines
unsafe impl DeviceImplUnsafe for T: DeviceImpl {
const REALIZE: ... = Some(realize_fn_unsafe::<T>); const RESET: ... = Some(realize_fn_unsafe::<T>); }
Quoted 7 lines
Going on to the implementation of the safe functions:
rust/hw/char/pl011/src/device.rs pub unsafe fn init(&mut self) { · line 134
Quoted 2 lines
rust/hw/char/pl011/src/device.rs +2
-0+impl DeviceImpl for PL011State { +fn realize (&mut self) {These are not quite traits. First, you can implement only some of the functions.
This is called "default implementations" in Rust
Quoted 2 lines
Second, if you don't implement them they are not overwritten by the
class_initmethod.
WYM overwritten? That we hook up the empty stub instead of a NULL function pointer?
Quoted 75 lines
So this points to a different implementation as an attribute macro, which is able to rewrite everything in the body of the impl. For example:
#[qom_class_init]
impl DeviceImpl for PL011State { fn realize(&mut self) { ... } fn reset(&mut self) { ... } const VMSTATE: ... = {} const CATEGORY: ... = {} }can be transformed into:
#[qom_class_init]
impl DeviceImpl for PL011State { // fns are wrapped and transformed into consts const REALIZE: Option<fn(&mut self)> = { fn realize(&mut self) { ... } Some(realize) }; const RESET: Option<fn(&mut self)> = { fn reset(&mut self) { ... } Some(reset) }; // while associated consts (and perhaps types?) remain as is const VMSTATE: ... = {} const CATEGORY: ... = {} }The above blanket implementation of DeviceImplUnsafe is easily adjusted to support non-overridden methods:
unsafe impl DeviceImplUnsafe for T: DeviceImpl {
const REALIZE: ... = <T as DeviceImpl>::REALIZE::map( || realize_fn_unsafe::<T>); const RESET: ... = <T as DeviceImpl>::RESET::map( || realize_fn_unsafe::<T>); }You can also keep out of the macro the
class_initmethod itself. Here I'm adding it to DeviceImplUnsafe:pub trait DeviceImplUnsafe { unsafe fn class_init(klass: *mut ObjectClass, data: *mut c_void) { let mut dc = NonNull::new(klass.cast::<DeviceClass>()).unwrap(); unsafe { dc.as_mut().realize = Self::REALIZE; bindings::device_class_set_legacy_reset( dc.as_mut(), Self::RESET); device_class_set_props(dc.as_mut(), <Self as DeviceInfo>::PROPS); if let Some(vmsd) = <Self as DeviceInfo>::VMSTATE { dc.as_mut().vmsd = vmsd; } if let Some(cat) = <Self as DeviceInfo>::CATEGORY { dc.as_mut().category = cat; } // maybe in the future for unparent // <Self as ObjectImplUnsafe>::class_init(klass, data) } } }And with all this machinery in place the
device_class_init! macro becomes simplydevice_class_init!(PL011State);(because the arguments have moved to DeviceInfo or DeviceImpl).
Quoted 7 lines
Why is this important? Because the only code transformation is the generation of properties and vtables, and the bindings can be developed almost entirely in
qemu_apiinstead ofqemu_api_macros. This has several advantages:1) it's much easier: simpler error messages, no macro indirection, no super long global crate paths
Hard no, sorry. Error messages can definitely be generated from proc macros. Long crate paths; that's just a matter of using imports or changing names.
Quoted 3 lines
2) it allows simplifying the pl011 code piecewise, even before introducing procedural macro code
Not sure how that is relevant can you explain?
Quoted 9 lines
3) it's easier to add comments
It also becomes much easier to separate the work in separate patches, or even separate series. Replacing the arguments to device_class_init!() with DeviceImpl + DeviceImplUnsafe can be introduced first: posted, reviewed, merged. All the remaining tasks are pretty much independent:
Quoted 7 lines
1) splitting out ObjectInfo and introducing #[object] to automate it (i.e. extending derive(Object))
2) splitting out DeviceInfo and introducing #[property] to automate it (i.e. derive(Device))
3) the #[qom_class_init] macro
I disagree with this approach at the moment. This patch is in an acceptable state albeit a bit longish while all these suggestions would merely cause more running around making changes for no real gain while also delaying review and merging.
Quoted 6 lines
A final word: I absolutely don't want you to think that your work is of no value. It's totally okay to throw away the first version of something. You showed that it _is_ possible to have idiomatic code with the help of procedural macros. Even if the implementation can be improved, the _idea_ remains yours.
I don't know what this is in reference to :P What work and throwing away are you talking about?
Quoted 2 lines
Paolo
Re: [PATCH 03/11] rust/qemu-api-macros: introduce Device proc macro
[snipping to concentrate on the QOM code generation]
Quoted 26 lines · Manos Pitsidianakis
Quoted 26 lines
The part where I have most comments, and some ideas of how to make your work a little more maintainable, is the implementation of
class_init(and all that depends on it).Let's start with these generated functions:
Quoted 19 lines
rust/qemu-api-macros/src/device.rs new file +19
-0+ pub unsafe extern "C" fn #realize_fn( + dev: *mut ::qemu_api::bindings::DeviceState , + errp: *mut *mut ::qemu_api::bindings::Error , + ) { + let mut instance = NonNull::new(dev.cast::<#name>()).expect(concat!("Expected dev to be a non-null pointer of type ", stringify!(#name))); +unsafe { +DeviceImpl ::realize (instance.as_mut ()); + } + } + +#[no_mangle] + pub unsafe extern "C" fn #reset_fn( + dev: *mut ::qemu_api::bindings::DeviceState , + ) { + let mut instance = NonNull::new(dev.cast::<#name>()).expect(concat!("Expected dev to be a non-null pointer of type ", stringify!(#name))); +unsafe { +DeviceImpl ::reset (instance.as_mut ()); + } + }
Quoted 4 lines
Quoted 1 line
This can be handled entirely in Rust code, outside the macro. If you add:
Why? I don't understand what this solves. These are *just* trampoline functions to call the Rust-abi code.
Yes, and there is no need to place them in the procedural macros.
Generally it's a good rule to do as little as possible in procedural macros, and move as much code as possible outside; this often means to generic functions or a declarative macros. For some examples you can look at Linux; in rust/macros/zeroable.rs for example the only "quote!" is
quote! {
::kernel::__derive_zeroable!(
parse_input:
@sig(#(#rest)*),
@impl_generics(#(#new_impl_generics)*),
@ty_generics(#(#ty_generics)*),
@body(#last),
);
}For more information, see https://www.youtube.com/watch?v=DMLBBZBlKis
Quoted 4 lines
Quoted 2 lines
unsafe extern "C" fn realize_fn_unsafe<T: DeviceImpl>(...) {} unsafe extern "C" fn reset_fn_unsafe<T: DeviceImpl>(...) {}
So just rename them and put a generic argument. Still not seeing any gain here.
The gain is that you have a much shorter macro implementation, a shorter expansion which makes it easier to debug the macro, and an implementation of realize_fn_unsafe<>() and reset_fn_unsafe<>() that is isolated.
Quoted 9 lines
Quoted 7 lines
Going on to the implementation of the safe functions:
rust/hw/char/pl011/src/device.rs pub unsafe fn init(&mut self) { · line 134
Quoted 2 lines
rust/hw/char/pl011/src/device.rs +2
-0+impl DeviceImpl for PL011State { +fn realize (&mut self) {These are not quite traits. First, you can implement only some of the functions.
This is called "default implementations" in Rust
Sort of. Yes, this is related to default implementations, but the default implementation of a QOM method is not "call whatever is declared in the trait". It's "call whatever is defined by the superclass", which is represented by None.
Quoted 5 lines
Quoted 2 lines
Second, if you don't implement them they are not overwritten by the
class_initmethod.WYM overwritten? That we hook up the empty stub instead of a NULL function pointer?
Not really the NULL function pointer: the value left by the superclass. In other words, the class_init function should not have
// realize is a function in a trait
dc.as_mut().realize = Self::realize;but rather
// realize is a constant Option<fn(...)> in a trait
if let Some(realize_fn) = Self::REALIZE {
dc.as_mut().realize = Self::realize_fn;
}Quoted 11 lines
Quoted 7 lines
Why is this important? Because the only code transformation is the generation of properties and vtables, and the bindings can be developed almost entirely in
qemu_apiinstead ofqemu_api_macros. This has several advantages:1) it's much easier: simpler error messages, no macro indirection, no super long global crate paths
Hard no, sorry. Error messages can definitely be generated from proc macros. Long crate paths; that's just a matter of using imports or changing names.
I don't mean error messages from proc macros. I mean that debugging macros that are this complex (does not matter if procedural or declarative) is hell. If you move code outside the macro, to generic functions and blanket trait implementations, error messages from the compiler are simpler.
One additional benefit is that the code is compiled _always_, not just if the macro hits a specific code path. It simplifies the testing noticeably.
Finally, without -Zmacro-backtrace (nightly only) debugging procedural macros is a tedious matter of using "cargo expand". With -Zmacro-backtrace it's better but we don't want developers to install nightly to develop QEMU. Note that this code is not write-once; it will be extended for example as soon as we have a device that can fail realization.
Quoted 2 lines
Long crate paths; that's just a matter of using imports or changing names.
Only to some extent. See how many ::core::ffi:: or ::core::mem:: are there in the current macros.
Quoted 4 lines
Quoted 2 lines
2) it allows simplifying the pl011 code piecewise, even before introducing procedural macro code
Not sure how that is relevant can you explain?
Alex asked for a way to validate the expansion of the macro. If the procedural macro is simple and the code is outside, then reviewers can easily compare the pl011 code and the qemu-api-macros code, and see that they expand to the same thing.
Try to put yourself into the mindset of the reviewer. If I see a patch like
+#[qom_class_init]
impl DeviceImpl for PL011State {
- const REALIZE: Option<fn(&mut self)> = {
fn realize(&mut self) { ... }- Some(realize)
- };
- const RESET: Option<fn(&mut self)> = {
fn reset(&mut self) { ... }- Some(reset)
- };
const VMSTATE: ... = ...;
const CATEGORY: ... = ...;}
... then it's quite obvious what to expect from the expansion of the #[qom_class_init] attribute macro.
Quoted 11 lines
Quoted 11 lines
It also becomes much easier to separate the work in separate patches, or even separate series. Replacing the arguments to device_class_init!() with DeviceImpl + DeviceImplUnsafe can be introduced first: posted, reviewed, merged. All the remaining tasks are pretty much independent:
1) splitting out ObjectInfo and introducing #[object] to automate it (i.e. extending derive(Object))
2) splitting out DeviceInfo and introducing #[property] to automate it (i.e. derive(Device))
Quoted 6 lines
Quoted 1 line
3) the #[qom_class_init] macro
I disagree with this approach at the moment. This patch is in an acceptable state albeit a bit longish while all these suggestions would merely cause more running around making changes for no real gain while also delaying review and merging.
I will be very clear: no, this patch is very far from an acceptable state. It's a wonderful prototype, just like hw/char/pl011, but at this point we're not accepting prototype-quality Rust code anymore:
we're turning the existing prototype, which has a manageable but still large size, into the real thing.
To sum up the basic points underlying the suggestions, my review comments are:
- the syntax of #[device(...)] is arbitrary. You are keeping things that obviously refer to the QOM object (type name, parent type name) far from #[derive(Object)]. You are putting in #[device()] things that apply to the QOM object class (e.g. class_name_override) rather than the QOM device class. Finally, you are putting in #[device()] the vmstate, which is not self-contained (due to subsections).
- the split in modules needs more work. For example, why is Migrateable under qemu_api::objects instead of qemu_api::device_class?
- the part that would require the fewest changes is probably #[property], but we need to be careful about not introducing "fake safety".
- to simplify splitting the patches, start by moving code out of the existing declarative macros and into generic code or declarative macros
- to simply reviewing the patches, only use the procedural macros as a syntactic sugar, and do as little code generation as possible in the procedural macros themselves
- splitting the ObjectImpl/DeviceImpl traits in two (one for code generated by derive-macros; one for stuff that is definde outside the struct declaration) could be a way to work incrementally, adding more and more parts of the class definition to the procedural macro but without doing everything at once
- it must be possible to specify non-overridden DeviceClass or ObjectClass functions
The suggestions are just a way to achieve these objectives. In particular, the suggestions are about how to achieve the bullets in the above list starting from the third.
Also, this series *must* come after the other cleanups and CI integration that have been posted, for several reasons.
As to the cleanups, right now we *already* have in the tree code that is duplicate, dead or untested. Removing that, and ensuring that it does not regress, is a priority over everything else.
As to CI integration, first, changes like this one must be fully bisectable, which requires having working CI before. Second, if we want to advertise 9.2 as supporting --enable-rust (even if experimental), we need a way to run automated tests on at least _some_ of the platforms that we support.
So my plan right now is to post a pull request for part 1 next week, and to include part 2 (including your work on migration and Luminary, but without the procedural macro) in -rc1. This work is for 10.0.
Quoted 8 lines
Quoted 5 lines
A final word: I absolutely don't want you to think that your work is of no value. It's totally okay to throw away the first version of something. You showed that it _is_ possible to have idiomatic code with the help of procedural macros. Even if the implementation can be improved, the _idea_ remains yours.
I don't know what this is in reference to :P What work and throwing away are you talking about?
I was talking in general. When working in Rust I often found that the first thing I came up with was crap, and the main value of it was in learning. Sometimes I came up with the second version on my own, sometimes it was pointed out during review. But even if it's pointed out during review, the reviewer doesn't in any way think bad of you or your work.
Paolo
Re: [PATCH 03/11] rust/qemu-api-macros: introduce Device proc macro
I disagree with your points, Paolo. A patch review should not be "Fear Uncertainty and Doubt" but point out actual problems with the code. Please do not proceed with this conversation since it's not productive.
If this series misses softfreeze because of code problems or by people delaying the review/merge, we can figure out what to do when we get to it.
Re: [PATCH 03/11] rust/qemu-api-macros: introduce Device proc macro
In reply to Manos PitsidianakisHello,
here is my second attempt to review this, this time placing the remarks as close as possible to the code that is affected. However, the meat is the same as in my previous replies to the 03/11 thread.
I hope this shows that I have practical concerns about the patch and it's not just FUD that it's not acceptable.
Quoted 13 lines · Manos Pitsidianakis
Add a new derive procedural macro to declare device models. Add corresponding DeviceImpl trait after already existing ObjectImpl trait. At the same time, add
instance_init,instance_post_init,instance_finalizemethods to the ObjectImpl trait and call them from the ObjectImplUnsafe trait, which is generated by the procedural macro.This allows all the boilerplate device model registration to be handled by macros, and all pertinent details to be declared through proc macro attributes or trait associated constants and methods.
The device class can now be generated automatically and the name can be optionally overridden:
Quoted 6 lines
------------------------ >8 ------------------------
#[repr(C)]
#[derive(Debug, qemu_api_macros::Object, qemu_api_macros::Device)]
#[device(class_name_override = PL011Class)]
/// PL011 Device Model in QEMU
pub struct PL011State {The first design issue is already visible here in this example. I could place the same comment when the code appears in rust/hw/char/pl011, but it's easier to do it here.
You have two derive macros, Object and Device. Object is derived by all objects (even if right now we have only devices), Device is derived by devices only.
The class name is a property of any object, not just devices. It should not be part of the #[device()] attribute. #[derive(Device)] and #[device()] instead should take care of properties and categories (and possibly vmstate, but I'm not sure about that and there's already enough to say about this patch).
You also have no documentation, which means that users will have no idea of what are the other sub-attributes of #[device()], including the difference between class_name and class_name_override, or how categories are defined.
Even if we don't have support for rustdoc yet in tree, we should have all the needed documentation as soon as the API moves from "ad hoc usage of C symbols" to idiomatic.
Quoted 9 lines
Object methods (
instance_init, etc) methods are now trait methods:------------------------ >8 ------------------------ /// Trait a type must implement to be registered with QEMU. pub trait ObjectImpl { type Class: ClassImpl; const TYPE_NAME: &'static CStr; const PARENT_TYPE_NAME: Option<&'static CStr>; const ABSTRACT: bool;
Class, TYPE_NAME, PARENT_TYPE_NAME, ABSTRACT should be defined via #[object()].
But actually, there is already room for defining a separate trait:
/// # Safety
///
/// - the first field of the struct must be of Object type,
/// or derived from it
///
/// - TYPE must match the type name used in the TypeInfo (no matter
/// if it is defined in C or Rust).
///
/// - the struct must be #[repr(C)]
pub unsafe trait ObjectType {
type Class: ClassImpl;
const TYPE_NAME: &'static CStr;
}... because you can implement it even for classes that are defined in C code. Then #[derive(Object)] can find the TYPE_NAME directly from the first field of the struct, i.e.
parent_obj: SysBusDevice;
becomes
const PARENT_TYPE_NAME: Option<&'static CStr> =
Some(<SysBusDevice as TypeImpl>::TYPE_NAME);
while #[object()] would be just
#[object(class_type = PL011Class, type_name = "pl011")]
Accessing the type of the first field is easy using the get_fields() function that Junjie added at https://lore.kernel.org/qemu-devel/[email protected]/
This shows another reason why I prefer to get CI to work first. Having to do simple, but still non-trivial work, often provides code that can be reused in more complex setups.
Quoted 4 lines
unsafe fn instance_init(&mut self) {} fn instance_post_init(&mut self) {} fn instance_finalize(&mut self) {}}
In the trait, having a default implementation that is empty works (unlike for realize/reset, as we'll see later). So this is a bit simpler. However, instance_finalize should have a non-empty default implementation:
std::ptr::drop_in_place(self);
which should be okay for most devices.
Alternatively, leave out instance_post_init() and instance_finalize() until we need them, and put the drop_in_place() call directly in the unsafe function that goes in the TypeInfo.
Quoted 11 lines
------------------------ >8 ------------------------Device methods (realize/reset etc) are now safe idiomatic trait methods:
------------------------ >8 ------------------------ /// Implementation methods for device types. pub trait DeviceImpl: ObjectImpl { fn realize(&mut self) {} fn reset(&mut self) {} } ------------------------ >8 ------------------------
This is an incorrect definition of the trait. The default definition of device methods is not "empty", it's "just reuse the superclass implementation". In particular, this means that PL011LuminaryState right now cannot use #[derive(Device)].
Quoted 2 lines
The derive Device macro is responsible for creating all the extern "C" FFI functions that QEMU needs to call these methods.
This is unnecessary. It is perfectly possible to write the extern "C" functions (class_init, realize, reset) just once as either type-generic functions, or functions in a trait. More on this later.
Quoted 12 lines
rust/qemu-api/src/objects.rs new file +6
-0@@ -0,0 +1,90 @@ +// Copyright 2024, Linaro Limited +// Author(s): Manos Pitsidianakis <[email protected]> +// SPDX-License-Identifier: GPL-2.0-or-later + +//! Implementation traits for QEMU objects, devices. +
rust/qemu-api/src/objects.rs line 16
Quoted 10 lines
rust/qemu-api/src/objects.rs new file +10
-0+use ::core::ffi::{c_int, c_void,CStr }; + +use crate ::bindings::{DeviceState ,Error ,MigrationPriority ,Object ,ObjectClass ,TypeInfo }; + +/// Trait a type must implement to be registered with QEMU. +pub trait ObjectImpl { +type Class :ClassImpl ; +const TYPE_NAME : &'staticCStr ; +const PARENT_TYPE_NAME :Option <&'staticCStr >; +const ABSTRACT :bool ;
These consts should entirely be derived from the #[object()] attribute.
You can facilitate the split by having two traits, one for things derived from the attribute (the above four), and one for the vtable.
rust/qemu-api/src/objects.rs line 21
Quoted 4 lines
rust/qemu-api/src/objects.rs new file +4
-0+unsafe fn instance_init (&mut self) {} +fn instance_post_init (&mut self) {} +fn instance_finalize (&mut self) {} +}
See above remark on the default implementation of instance_finalize.
rust/qemu-api/src/objects.rs line 32
Quoted 10 lines
rust/qemu-api/src/objects.rs new file +10
-0+/// The `extern`/`unsafe` analogue of [`ObjectImpl`]; it is used internally by `#[derive(Object)]` +/// and should not be implemented manually. +pub unsafe trait ObjectImplUnsafe { +const TYPE_INFO :TypeInfo ; + +const INSTANCE_INIT :Option <unsafe extern "C" fn (obj: *mut Object )>; +const INSTANCE_POST_INIT :Option <unsafe extern "C" fn (obj: *mut Object )>; +const INSTANCE_FINALIZE :Option <unsafe extern "C" fn (obj: *mut Object )>; +} +
This trait is not needed at all, because it really has juts one implementation. The fact that there is just one implementation is hidden by the fact that you are generating the code instead of relying on the type system.
All you need is a single function, which will be called via the module_init mechanism:
fn rust_type_register<T: ObjectImpl>() {
let TypeInfo ti = ...;
unsafe { type_register(&ti); }
}rust/qemu-api/src/objects.rs line 40
Quoted 9 lines
rust/qemu-api/src/objects.rs new file +8
-0+/// Methods for QOM class types. +pub trait ClassImpl { +type Object :ObjectImpl ; + +unsafe fn class_init (&mut self, _data: *mut core::ffi::c_void ) {} +unsafe fn class_base_init (&mut self, _data: *mut core::ffi::c_void ) {} +} +
This trait (or more precisely class_init and class_base_init) is not needed. class_base_init is only needed in very special cases, we can just decide they won't be available in Rust for now and possible for ever.
As to class_init device XYZ would only need a non-empty class_init method if we added support for the _data argument. But then we would need a way to provide the type of _data, and to cast _data to the appropriate type; we would also need a way to provide a mapping from multiple data objects to multiple type names, which is hard to do because right now each Rust struct has a single type name associated.
So, let's just keep only the auto-generated class_init for simplicity. If we can just decide that, if device XYZ has superclass FooDevice, it implements FooDeviceImpl and class_init is provided by the FooDevice bindings.
I can't really say if the "type Object" part is needed. I couldn't offhand find anything that uses it, but I may have missed it. If so, it can be in ClassImplUnsafe.
rust/qemu-api/src/objects.rs line 48
Quoted 8 lines
rust/qemu-api/src/objects.rs new file +8
-0+/// The `extern`/`unsafe` analogue of [`ClassImpl`]; it is used internally by `#[derive(Object)]` +/// and should not be implemented manually. +pub unsafe trait ClassImplUnsafe { +const CLASS_INIT :Option <unsafe extern "C" fn (klass: *mut ObjectClass , data: *mut c_void )>; +const CLASS_BASE_INIT :Option < +unsafe extern "C" fn (klass: *mut ObjectClass , data: *mut c_void ), + >; +}
Again, no need to have CLASS_BASE_INIT here.
rust/qemu-api/src/objects.rs line 54
Quoted 5 lines
rust/qemu-api/src/objects.rs new file +5
-0+/// Implementation methods for device types. +pub trait DeviceImpl :ObjectImpl { +fn realize (&mut self) {} +fn reset (&mut self) {} +}
These unfortunately cannot be functions. Doing so forces the class_init method to assign both dc->reset and dc->realize for _all_ classes, whereas for example PL011LuminaryClass would not override either.
Therefore, the definition must be
pub trait DeviceImpl: ObjectImpl {
const REALIZE: Option<fn realize(&mut self)> = None;
const RESET: Option<fn realize(&mut self)> = None;
}Yes, it's uglier, but we cannot escape the fact that we're implementing something that Rust doesn't have natively (inheritance). :( So we cannot use language features meant for a completely different kind of polymorphism.
rust/qemu-api/src/objects.rs line 61
Quoted 6 lines
rust/qemu-api/src/objects.rs new file +6
-0+/// The `extern`/`unsafe` analogue of [`DeviceImpl`]; it is used internally by `#[derive(Device)]` +/// and should not be implemented manually. +pub unsafe trait DeviceImplUnsafe { +const REALIZE :Option <unsafe extern "C" fn (dev: *mut DeviceState , _errp: *mut *mut Error )>; +const RESET :Option <unsafe extern "C" fn (dev: *mut DeviceState )>; +}
This trait is also unnecessary, because all that you need is a single function:
fn rust_device_class_init<T: DeviceImpl>(
klass: *mut ObjectClass, _data: *mut c_void)
defined outside the procedural macro. #[derive(Device)] can define ClassImplUnsafe to point CLASS_INIT to rust_device_class_init.
(Later, rust_device_class_init() can be moved into a trait so that it's possible to define other classes of devices, for example PCI devices. Note that such an extension would be much easier, than if it was _required_ to touch the procedural macro).
Quoted 19 lines
rust/qemu-api/src/objects.rs new file +18
-0+/// Constant metadata and implementation methods for types with device migration state. +pub trait Migrateable :DeviceImplUnsafe { +const NAME :Option <&'staticCStr > =None ; +const UNMIGRATABLE :bool =true ; +const EARLY_SETUP :bool =false ; +const VERSION_ID :c_int =1 ; +const MINIMUM_VERSION_ID :c_int =1 ; +const PRIORITY :MigrationPriority =MigrationPriority ::MIG_PRI_DEFAULT ; + +unsafe fn pre_load (&mut self) ->c_int { +0 + } +unsafe fn post_load (&mut self, _version_id:c_int ) ->c_int { +0 + } +unsafe fn pre_save (&mut self) ->c_int { +0 + }
rust/qemu-api/src/objects.rs line 90
Quoted 10 lines
rust/qemu-api/src/objects.rs new file +10
-0+unsafe fn post_save (&mut self) ->c_int { +0 + } +unsafe fn needed (&mut self) ->bool { +false + } +unsafe fn dev_unplug_pending (&mut self) ->bool { +false + } +}
Premature. No need to add this trait until you add support for migration.
rust/qemu-api/src/tests.rs
Quoted 6 lines
rust/qemu-api/src/tests.rs deleted +0
-0@@ -1,49 +0,0 @@
Nope. Fix the test, don't remove it.
rust/qemu-api/src/tests.rs pub struct PL011State { · line 55
Quoted 11 lines
rust/qemu-api/src/tests.rs deleted +3
-1-#[derive( Debug , qemu_api_macros:: Object )] +#[derive( Debug , qemu_api_macros:: Object , qemu_api_macros:: Device )] +#[device(class_name_override = PL011Class )] /// PL011 Device Model in QEMU pub struct PL011State {pub parent_obj:SysBusDevice ,@@ -51,6 +52,7 @@ pub struct PL011State { pub read_count: usize, pub read_trigger: usize,#[doc(alias = "chr" )] +#[property(name = c"chardev" , qdev_prop = qdev_prop_chr)]
(See earlier comments on accepting only a LitStr and deriving qdev_prop from the type).
rust/qemu-api/src/tests.rs pub struct PL011State {
Quoted 8 lines
rust/qemu-api/src/tests.rs deleted +8
-0+impl DeviceImpl for PL011State { +fn realize (&mut self) { + ... + } + +fn reset (&mut self) { + ... + }
This extractions of code into DeviceImpl is good. However, as I said above, I'm not sure about the trait itself. I'll remark later when I encounter the definition.
Quoted 1 line
+impl
qemu_api::objects::Migrateablefor PL011State {}
Premature.
Before moving on to the procedural macro code, my proposal to split the patches is:
1) introduce the trait ObjectType, define it for Object, DeviceState and SysBusDevice.
2) introduce the traits ObjectImpl, DeviceImpl and ClassImplUnsafe. Define the first two for PL011State.
3) add to common code the wrappers that call into DeviceImpl, removing them from PL011State
4) introduce the functions rust_type_register and rust_device_class_init that use the traits.
5) remove most arguments of device_class_init!(), using the infrastructure introduced in the previous two steps
6) split ObjectImpl into a part that will be covered by #[object()], let's call it ObjectInfo
7) add implementation of #[object()], replace PL011State's implementation of ObjectInfo with #[object()]
8) split DeviceImpl into a part that will be covered by #[device()] (properties and categories), let's call it DeviceInfo
9) add #[derive(Device) and implementation of #[device()], replace PL011State's implementation of DeviceInfo with #[device()]
Where 1-5 should be submitted as a separate series, one that does not touch procedural macros *at all* and just generalizes the pl011 code that defines QOM types.
Anyhow, I'll continue reviewing the procedural macro code.
rust/qemu-api/src/tests.rs
Quoted 6 lines
rust/qemu-api/src/tests.rs deleted +6
-0+#[derive( Debug , Default )] +struct DeriveContainer { + category:Option <syn::Path >, + class_name:Option <syn::Ident >, + class_name_override:Option <syn::Ident >, +}
Rename to DeviceAttribute.
rust/qemu-api/src/tests.rs
Quoted 2 lines
rust/qemu-api/src/tests.rs deleted +2
-0+impl Parse for DeriveContainer { +fn parse (input:ParseStream ) ->Result <Self > {
syn::Result represents a parse error, not an error in the allowed syntax of the attribute. Below, you're using panic! and unwrap(), but probably instead of syn::Result we need to have something like
pub enum Error {
CompileError(syn::Span, String),
ParseError(syn::Error)
}
which extends the CompileError enum of https://lore.kernel.org/qemu-devel/[email protected]/ and is amenable to use with "?". In particular, note the idiom used by the root derive_offsets() functions:
let input = parse_macro_input!(input as DeriveInput);
let expanded = derive_offsets_or_error(input).
unwrap_or_else(Into::into);
TokenStream::from(expanded)which works via an "impl From<CompileError> for proc_macro2::TokenStream".
I believe that most of the benefit of this series (basically, all except the #[property] attribute) can be obtained without the procedural macro.
Therefore, once we do add the procedural macro, we should not have it
panic on errors.
Quoted 8 lines
rust/qemu-api/src/tests.rs deleted +8
-0+let _: syn::Token ![#] = input.parse ()?; +let bracketed; + _ = syn::bracketed!(bracketed in input); +assert_eq! (DEVICE , bracketed.parse ::<syn::Ident >()?); +let mut retval =Self { + category:None , + class_name:None , + class_name_override:None ,
rust/qemu-api/src/tests.rs
Quoted 10 lines
rust/qemu-api/src/tests.rs deleted +10
-0+ }; +let content; + _ = syn::parenthesized!(content in bracketed); +while !content.is_empty () { +let value: syn::Ident = content.parse ()?; +if value ==CLASS_NAME { +let _: syn::Token ![=] = content.parse ()?; +if retval.class_name.is_some () { +panic! ("{} can only be used at most once" ,CLASS_NAME ); + }
No panic!, instead we need to return a compile_error!() TokenStream, or as above a Result<> that can be converted to compile_error!() up in the chain.
Quoted 1 line
+ retval.class_name = Some(content.parse()?);
Please make this function a separate trait in utilities:
trait AttributeParsing {
const NAME: Symbol;
fn set(&mut self, key: &syn::Ident, input: &ParseStream) -> Result<()>;
fn parse(input: ParseStream) -> Result<Self> { ... }
}Then the "if" can move to the struct-specific implementation of AttributeParsing::set, while the rest can move to the default implementation of AttributeParsing::parse.
#[property()] and #[device()] (and also the proposed #[object()]) can then share the implementation of AttributeParsing::parse.
rust/qemu-api/src/tests.rs
Quoted 12 lines
rust/qemu-api/src/tests.rs deleted +12
-0+ }else if value ==CLASS_NAME_OVERRIDE { +let _: syn::Token ![=] = content.parse ()?; +if retval.class_name_override.is_some () { +panic! ("{} can only be used at most once" ,CLASS_NAME_OVERRIDE ); + }> + retval.class_name_override = Some(content.parse()?); + }else if value ==CATEGORY { +let _: syn::Token ![=] = content.parse ()?; +if retval.category.is_some () { +panic! ("{} can only be used at most once" ,CATEGORY ); + } +let lit: syn::LitStr = content.parse ()?; +let path: syn::Path = lit.parse ()?;
Do I understand that this would be
category = "foo::bar::Baz"
? If so, why the extra quotes? There can actually be more than one category, so at least add a TODO here.
rust/qemu-api/src/tests.rs
Quoted 3 lines
rust/qemu-api/src/tests.rs deleted +3
-0+#[derive( Debug )] +struct QdevProperty { + name:Option <syn::LitCStr >,
Just LitStr. Convert it to CString in the macro. You can reuse the c_str!() macro that I'm adding in the series to fix CI and support old rustc, i.e. quote! { ::qemu_api::c_str!(#name) } or something like that.
Quoted 28 lines
rust/qemu-api/src/tests.rs deleted +28
-0+ qdev_prop: Option<syn::Path>, +} + +impl Parse for QdevProperty { +fn parse (input:ParseStream ) ->Result <Self > { +let _: syn::Token ![#] = input.parse ()?; +let bracketed; + _ = syn::bracketed!(bracketed in input); +assert_eq! (PROPERTY , bracketed.parse ::<syn::Ident >()?); +let mut retval =Self { + name:None , + qdev_prop:None , + }; +let content; + _ = syn::parenthesized!(content in bracketed); +while !content.is_empty () { +let value: syn::Ident = content.parse ()?; +if value ==NAME { +let _: syn::Token ![=] = content.parse ()?; +if retval.name.is_some () { +panic! ("{} can only be used at most once" ,NAME ); + } + retval.name =Some (content.parse ()?); + }else if value ==QDEV_PROP { +let _: syn::Token ![=] = content.parse ()?; +if retval.qdev_prop.is_some () { +panic! ("{} can only be used at most once" ,QDEV_PROP ); + }
rust/qemu-api/src/tests.rs
Quoted 10 lines
rust/qemu-api/src/tests.rs deleted +10
-0+ retval.qdev_prop =Some (content.parse ()?); + }else { +panic! ("unrecognized token `{}`" , value); + } + +if !content.is_empty () { +let _: syn::Token ![,] = content.parse ()?; + } + } +Ok (retval)
See above with respect to the duplicated code with #[device()].
rust/qemu-api/src/tests.rs
Quoted 7 lines
rust/qemu-api/src/tests.rs deleted +7
-0+let derive_container:DeriveContainer = input + .attrs + .iter () + .find (|a| a.path () ==DEVICE ) + .map (|a| syn::parse (a.to_token_stream ().into ()).expect ("could not parse device attr" )) + .unwrap_or_default (); +let (qdev_properties_static, qdev_properties_expanded) =make_qdev_properties (&input);
Please put functions before their callers.
Quoted 7 lines
rust/qemu-api/src/tests.rs deleted +7
-0+let realize_fn =format_ident! ("__{}_realize_generated" , name); +let reset_fn =format_ident! ("__{}_reset_generated" , name); + +let expanded =quote! { +unsafe impl ::qemu_api::objects::DeviceImplUnsafe for #name { +const REALIZE : ::core::option::Option < +unsafe extern "C" fn (
rust/qemu-api/src/tests.rs
Quoted 10 lines
rust/qemu-api/src/tests.rs deleted +10
-0+ dev: *mut ::qemu_api::bindings::DeviceState, + errp: *mut *mut ::qemu_api::bindings::Error, + ), + > = Some(#realize_fn); +const RESET : ::core::option::Option < +unsafe extern "C" fn (dev: *mut ::qemu_api::bindings::DeviceState ), + > = Some(#reset_fn); + } + +#[no_mangle]
Not needed.
rust/qemu-api/src/tests.rs
Quoted 11 lines
rust/qemu-api/src/tests.rs deleted +11
-0+ pub unsafe extern "C" fn #realize_fn( + dev: *mut ::qemu_api::bindings::DeviceState , + errp: *mut *mut ::qemu_api::bindings::Error , + ) { + let mut instance = NonNull::new(dev.cast::<#name>()).expect(concat!("Expected dev to be a non-null pointer of type ", stringify!(#name))); +unsafe { + ::qemu_api::objects::DeviceImpl ::realize (instance.as_mut ()); + } + } + +#[no_mangle]
Not needed.
rust/qemu-api/src/tests.rs
Quoted 8 lines
rust/qemu-api/src/tests.rs deleted +8
-0+ pub unsafe extern "C" fn #reset_fn( + dev: *mut ::qemu_api::bindings::DeviceState , + ) { + let mut instance = NonNull::new(dev.cast::<#name>()).expect(concat!("Expected dev to be a non-null pointer of type ", stringify!(#name))); +unsafe { + ::qemu_api::objects::DeviceImpl ::reset (instance.as_mut ()); + } + }
All this code depends on nothing but #name. This is not the C preprocessor; the way to do it in Rust is monomorphization as described above.
Quoted 16 lines
rust/qemu-api/src/tests.rs deleted +16
-0+fn gen_device_class ( + derive_container:DeriveContainer , + qdev_properties_static: syn::Ident , + name: &syn::Ident , +) -> proc_macro2::TokenStream { +let (class_name, class_def) =match ( + derive_container.class_name_override, + derive_container.class_name, + ) { + (Some (class_name), _) => { +let class_expanded =quote! { +#[repr( C )] +pub struct #class_name { + _inner: [u8 ;0 ], + } + };
rust/qemu-api/src/tests.rs
Quoted 10 lines
rust/qemu-api/src/tests.rs deleted +10
-0+ (class_name, class_expanded) + } + (None, Some(class_name)) => (class_name, quote! {}), + (None, None) => { +let class_name =format_ident! ("{}Class" , name); +let class_expanded =quote! { +#[repr( C )] +pub struct #class_name { + _inner: [u8 ;0 ], + }
This should have a DeviceClass member, it should not be a dummy 0-byte type.
Also, this should be generated by #[derive(Object)].
Quoted 11 lines
rust/qemu-api/src/tests.rs deleted +11
-0+ }; + (class_name, class_expanded) + } + }; +let class_init_fn =format_ident! ("__{}_class_init_generated" , class_name); +let class_base_init_fn =format_ident! ("__{}_class_base_init_generated" , class_name); + +let (vmsd, vmsd_impl) = { +let (i, vmsd) =make_vmstate (name); + (quote! { &#i }, vmsd) + };
rust/qemu-api/src/tests.rs
Quoted 10 lines
rust/qemu-api/src/tests.rs deleted +10
-0+let category =if let Some (category) = derive_container.category { +quote! { +const BITS_PER_LONG :u32 = ::core::ffi::c_ulong::BITS ; +let _: ::qemu_api::bindings::DeviceCategory = #category; +let nr: ::core::ffi::c_ulong = #categoryas _ ; +let mask =1 << (nras u32 %BITS_PER_LONG ); +let p = ::core::ptr::addr_of_mut!(dc.as_mut ().categories).offset ((nras u32 /BITS_PER_LONG )as isize ); +let p: *mut ::core::ffi::c_ulong = p.cast (); +let categories = p.read_unaligned (); + p.write_unaligned (categories | mask);
What's wrong with
const BITS_PER_ELEMENT: u32 =
::core::mem::sizeof(dc.categories) /
dc.categories.len() * 8;dc.categories[((nr as u32) / BITS_PER_ELEMENT) as usize]
|= 1 << ((nr as u32) % BITS_PER_ELEMENT);
?
rust/qemu-api/src/tests.rs
Quoted 6 lines
rust/qemu-api/src/tests.rs deleted +6
-0+#[no_mangle] + pub unsafe extern "C" fn #class_init_fn(klass: *mut ObjectClass, data: *mut core::ffi::c_void) { + { + { +let mut dc = + ::core::ptr::NonNull ::new (klass.cast ::<::qemu_api::bindings::DeviceClass >()).unwrap ();
And then "let mut dc = dc.as_mut()". Just write the conversion once.
rust/qemu-api/src/tests.rs
Quoted 7 lines
rust/qemu-api/src/tests.rs deleted +7
-0+unsafe { + dc.as_mut ().realize = + <#name as ::qemu_api::objects::DeviceImplUnsafe>::REALIZE; + ::qemu_api::bindings::device_class_set_legacy_reset ( + dc.as_mut (), + <#name as ::qemu_api::objects::DeviceImplUnsafe>::RESET + );
As written elsewhere, these should be conditional.
rust/qemu-api/src/tests.rs
Quoted 4 lines
rust/qemu-api/src/tests.rs deleted +4
-0+ dc.as_mut().vmsd = #vmsd; + #props + #category + }> + }
All this code should be outside the macro, and should use trait consts instead of quoting.
Quoted 11 lines
rust/qemu-api/src/tests.rs deleted +11
-0+ let mut klass = NonNull::new(klass.cast::<#class_name>()).expect(concat!("Expected klass to be a non-null pointer of type ", stringify!(#class_name))); +unsafe { + ::qemu_api::objects::ClassImpl ::class_init (klass.as_mut (), data); + } + } + } +#[no_mangle] + pub unsafe extern "C" fn #class_base_init_fn(klass: *mut ObjectClass, data: *mut core::ffi::c_void) { + { + let mut klass = NonNull::new(klass.cast::<#class_name>()).expect(concat!("Expected klass to be a non-null pointer of type ", stringify!(#class_name))); +unsafe {
rust/qemu-api/src/tests.rs
Quoted 10 lines
rust/qemu-api/src/tests.rs deleted +10
-0+ ::qemu_api::objects::ClassImpl ::class_base_init (klass.as_mut (), data); + } + } + } + + #vmsd_impl + } +} + +fn make_vmstate (name: &syn::Ident ) -> (syn::Ident , proc_macro2::TokenStream ) {
Not needed. Just let the user provide a VMStateDescription in DeviceImpl. I'm not sure if it's possible to make it a const; if not, it can be a function returning a &'static VMStateDescription.
rust/qemu-api/src/tests.rs
Quoted 12 lines
rust/qemu-api/src/tests.rs deleted +12
-0+let vmstate_description_ident =format_ident! ("__VMSTATE_{}" , name); + +let pre_load =format_ident! ("__{}_pre_load_generated" , name); +let post_load =format_ident! ("__{}_post_load_generated" , name); +let pre_save =format_ident! ("__{}_pre_save_generated" , name); +let post_save =format_ident! ("__{}_post_save_generated" , name); +let needed =format_ident! ("__{}_needed_generated" , name); +let dev_unplug_pending =format_ident! ("__{}_dev_unplug_pending_generated" , name); + +let migrateable_fish =quote! {<#name as ::qemu_api::objects::Migrateable >}; +let vmstate_description =quote! { +#[used]
Attribute not needed.
Quoted 13 lines
rust/qemu-api/src/tests.rs deleted +13
-0+#[allow(non_upper_case_globals)] + pub static #vmstate_description_ident: ::qemu_api::bindings::VMStateDescription = ::qemu_api::bindings::VMStateDescription { + name: if let Some(name) = #migrateable_fish::NAME { + name.as_ptr () + }else { + <#name as ::qemu_api::objects::ObjectImplUnsafe>::TYPE_INFO.name + }, + unmigratable: #migrateable_fish::UNMIGRATABLE, + early_setup: #migrateable_fish::EARLY_SETUP, + version_id: #migrateable_fish::VERSION_ID, + minimum_version_id: #migrateable_fish::MINIMUM_VERSION_ID, + priority: #migrateable_fish::PRIORITY, + pre_load: Some(#pre_load),
rust/qemu-api/src/tests.rs
Quoted 10 lines
rust/qemu-api/src/tests.rs deleted +10
-0+ post_load: Some(#post_load), + pre_save: Some(#pre_save), + post_save: Some(#post_save), + needed: Some(#needed), + dev_unplug_pending: Some(#dev_unplug_pending), + fields: ::core::ptr::null(), + subsections: ::core::ptr::null(), + }; + +#[no_mangle]
Not needed (other occurrences below).
rust/qemu-api/src/tests.rs
Quoted 11 lines
rust/qemu-api/src/tests.rs deleted +11
-0+ pub unsafe extern "C" fn #pre_load(opaque: *mut ::core::ffi::c_void) -> ::core::ffi::c_int { + let mut instance = NonNull::new(opaque.cast::<#name>()).expect(concat!("Expected opaque to be a non-null pointer of type ", stringify!(#name), "::Object")); +unsafe { + ::qemu_api::objects::Migrateable ::pre_load (instance.as_mut ()) + } + } +#[no_mangle] + pub unsafe extern "C" fn #post_load(opaque: *mut ::core::ffi::c_void, version_id: core::ffi::c_int) -> ::core::ffi::c_int { + let mut instance = NonNull::new(opaque.cast::<#name>()).expect(concat!("Expected opaque to be a non-null pointer of type ", stringify!(#name), "::Object")); +unsafe { + ::qemu_api::objects::Migrateable ::post_load (instance.as_mut (), version_id)
Again, introducing the Migrateable code and all these thunks is premature; but in any case, this can only return 0 or -1 so make Migrateable::post_load() return Result<(), ()>.
rust/qemu-api/src/tests.rs
Quoted 9 lines
rust/qemu-api/src/tests.rs deleted +9
-0+ } + } +#[no_mangle] + pub unsafe extern "C" fn #pre_save(opaque: *mut ::core::ffi::c_void) -> ::core::ffi::c_int { + let mut instance = NonNull::new(opaque.cast::<#name>()).expect(concat!("Expected opaque to be a non-null pointer of type ", stringify!(#name), "::Object")); +unsafe { + ::qemu_api::objects::Migrateable ::pre_save (instance.as_mut ()) + } + }
Likewise.
rust/qemu-api/src/tests.rs
Quoted 7 lines
rust/qemu-api/src/tests.rs deleted +7
-0+#[no_mangle] + pub unsafe extern "C" fn #post_save(opaque: *mut ::core::ffi::c_void) -> ::core::ffi::c_int { + let mut instance = NonNull::new(opaque.cast::<#name>()).expect(concat!("Expected opaque to be a non-null pointer of type ", stringify!(#name), "::Object")); +unsafe { + ::qemu_api::objects::Migrateable ::post_save (instance.as_mut ()) + } + }
Likewise.
Quoted 26 lines
rust/qemu-api/src/tests.rs deleted +21
-0+#[no_mangle] + pub unsafe extern "C" fn #needed(opaque: *mut ::core::ffi::c_void) -> bool { + let mut instance = NonNull::new(opaque.cast::<#name>()).expect(concat!("Expected opaque to be a non-null pointer of type ", stringify!(#name), "::Object")); +unsafe { + ::qemu_api::objects::Migrateable ::needed (instance.as_mut ()) + } + } +#[no_mangle] + pub unsafe extern "C" fn #dev_unplug_pending(opaque: *mut ::core::ffi::c_void) -> bool { + let mut instance = NonNull::new(opaque.cast::<#name>()).expect(concat!("Expected opaque to be a non-null pointer of type ", stringify!(#name), "::Object")); +unsafe { + ::qemu_api::objects::Migrateable ::dev_unplug_pending (instance.as_mut ()) + } + } + }; + +let expanded =quote! { + #vmstate_description + }; + (vmstate_description_ident, expanded) +}rust/qemu-api-macros/src/lib.rs +0
-0
rust/qemu-api-macros/src/lib.rs line 5
Quoted 4 lines
rust/qemu-api-macros/src/lib.rs +1
-0@@ -2,42 +2,21 @@// Author(s): Manos Pitsidianakis <[email protected]> // SPDX-License-Identifier: GPL-2.0-or-later +#![allow(dead_code)]
Why?
Quoted 32 lines
rust/qemu-api-macros/src/lib.rs +5
-23use proc_macro::TokenStream ; -use quote::{format_ident, quote}; -use syn::{parse_macro_input,DeriveInput }; + +mod device; +mod object; +mod symbols; +mod utilities;#[proc_macro_derive( Object )] pub fn derive_object (input:TokenStream ) ->TokenStream { -let input =parse_macro_input! (inputas DeriveInput ); - -let name = input.ident; -let module_static =format_ident! ("__{}_LOAD_MODULE" , name); - -let expanded =quote! { -#[allow(non_upper_case_globals)] -#[used] -#[cfg_attr(target_os = "linux" , link_section = ".ctors" )] -#[cfg_attr(target_os = "macos" , link_section = "__DATA,__mod_init_func" )] -#[cfg_attr(target_os = "windows" , link_section = ".CRT$XCU" )] -pub static #module_static:extern "C" fn () = { -extern "C" fn __register () { -unsafe { - ::qemu_api::bindings::type_register_static (&<#name as ::qemu_api::definitions::ObjectImpl >::TYPE_INFO ); - } - } - -extern "C" fn __load () { -unsafe { - ::qemu_api::bindings::register_module_init(
rust/qemu-api-macros/src/lib.rs line 16
Quoted 10 lines
rust/qemu-api-macros/src/lib.rs +1
-9- Some(__register), - ::qemu_api::bindings::module_init_type::MODULE_INIT_QOM - ); - } - } - - __load - }; - }; + object::derive_object (input)
Moving code to a separate file should be a separate patch from modifying the expansion of the macro.
Quoted 15 lines
rust/qemu-api-macros/src/symbols.rs new file +9
-0@@ -0,0 +1,55 @@ +// Copyright 2024, Linaro Limited +// Author(s): Manos Pitsidianakis <[email protected]> +// SPDX-License-Identifier: GPL-2.0-or-later + +use core::fmt; +use syn::{Ident ,Path }; + +#[derive( Copy , Clone , Debug )] +pub struct Symbol (&'staticstr );
rust/qemu-api-macros/src/symbols.rs line 19
Quoted 10 lines
rust/qemu-api-macros/src/symbols.rs new file +10
-0+ +pub const DEVICE :Symbol =Symbol ("device" ); +pub const NAME :Symbol =Symbol ("name" ); +pub const CATEGORY :Symbol =Symbol ("category" ); +pub const CLASS_NAME :Symbol =Symbol ("class_name" ); +pub const CLASS_NAME_OVERRIDE :Symbol =Symbol ("class_name_override" ); +pub const QDEV_PROP :Symbol =Symbol ("qdev_prop" ); +pub const MIGRATEABLE :Symbol =Symbol ("migrateable" ); +pub const PROPERTIES :Symbol =Symbol ("properties" ); +pub const PROPERTY :Symbol =Symbol ("property" );
Declare these in device.rs as needed, not here. This avoids "use symbols::*". It also allows making them not "pub", so that dead ones are detected by the compiler (e.g. MIGRATEABLE, PROPERTIES).
rust/qemu-api-macros/src/symbols.rs line 20
Quoted 1 line
rust/qemu-api-macros/src/symbols.rs new file +1
-0+pub fn assert_is_repr_c_struct (input: &DeriveInput , derive_macro: &'staticstr ) {
Nice but a bit overengineered. Unless you think/know that you'll have a use for Repr elsewhere, try sharing code with Junjie's macro https://lore.kernel.org/qemu-devel/[email protected]/.
Paolo
Re: [PATCH 03/11] rust/qemu-api-macros: introduce Device proc macro
Thank you for the review comments Paolo. I will address any bits I did wrong and not much the rest, it's obvious you have a disagreement over how things are done and that's fine. This series does not attempt to solve everything at once and arguing again and again over "this Trait should have been OtherTrait and this thing should have been thing!()" is not productive. Your review style of relentless disagreement after disagreement is tiresome and impossible to deal with; it's like a denial of service for other human beings. I suggest you take a step back and take a deep breath before reviewing Rust patches again. I assure you I will make sure to address all your comments either in code, TODO comments, or patch messages.
In the meantime, take it easy.
Quoted 921 lines · Paolo Bonzini
Hello,
here is my second attempt to review this, this time placing the remarks as close as possible to the code that is affected. However, the meat is the same as in my previous replies to the 03/11 thread.
I hope this shows that I have practical concerns about the patch and it's not just FUD that it's not acceptable.
Quoted 13 lines · Manos Pitsidianakis
Add a new derive procedural macro to declare device models. Add corresponding DeviceImpl trait after already existing ObjectImpl trait. At the same time, add
instance_init,instance_post_init,instance_finalizemethods to the ObjectImpl trait and call them from the ObjectImplUnsafe trait, which is generated by the procedural macro.This allows all the boilerplate device model registration to be handled by macros, and all pertinent details to be declared through proc macro attributes or trait associated constants and methods.
The device class can now be generated automatically and the name can be optionally overridden:
Quoted 6 lines
------------------------ >8 ------------------------ #[repr(C)] #[derive(Debug, qemu_api_macros::Object, qemu_api_macros::Device)] #[device(class_name_override = PL011Class)] /// PL011 Device Model in QEMU pub struct PL011State {The first design issue is already visible here in this example. I could place the same comment when the code appears in
rust/hw/char/pl011, but it's easier to do it here.You have two derive macros, Object and Device. Object is derived by all objects (even if right now we have only devices), Device is derived by devices only.
The class name is a property of any object, not just devices. It should not be part of the #[device()] attribute. #[derive(Device)] and #[device()] instead should take care of properties and categories (and possibly vmstate, but I'm not sure about that and there's already enough to say about this patch).
You also have no documentation, which means that users will have no idea of what are the other sub-attributes of #[device()], including the difference between
class_nameandclass_name_override, or how categories are defined.Even if we don't have support for rustdoc yet in tree, we should have all the needed documentation as soon as the API moves from "ad hoc usage of C symbols" to idiomatic.
Quoted 9 lines
Object methods (
instance_init, etc) methods are now trait methods:------------------------ >8 ------------------------ /// Trait a type must implement to be registered with QEMU. pub trait ObjectImpl { type Class: ClassImpl; const TYPE_NAME: &'static CStr; const PARENT_TYPE_NAME: Option<&'static CStr>; const ABSTRACT: bool;Class,
TYPE_NAME,PARENT_TYPE_NAME, ABSTRACT should be defined via #[object()].But actually, there is already room for defining a separate trait:
/// # Safety
///
/// - the first field of the struct must be ofObjecttype,
/// or derived from it
///
/// -TYPEmust match the type name used in theTypeInfo(no matter
/// if it is defined in C or Rust).
///
/// - the struct must be#[repr(C)]pub unsafe trait ObjectType { type Class: ClassImpl; const TYPE_NAME: &'static CStr; }... because you can implement it even for classes that are defined in C code. Then #[derive(Object)] can find the
TYPE_NAMEdirectly from the first field of the struct, i.e.parent_obj: SysBusDevice;becomes
const
PARENT_TYPE_NAME: Option<&'static CStr> =
Some(<SysBusDevice as TypeImpl>::TYPE_NAME);while #[object()] would be just
#[object(class_type = PL011Class,
type_name= "pl011")]Accessing the type of the first field is easy using the
get_fields()function that Junjie added at
https://lore.kernel.org/qemu-devel/[email protected]/This shows another reason why I prefer to get CI to work first. Having to do simple, but still non-trivial work, often provides code that can be reused in more complex setups.
Quoted 4 lines
unsafe fn instance_init(&mut self) {} fn instance_post_init(&mut self) {} fn instance_finalize(&mut self) {}}
In the trait, having a default implementation that is empty works (unlike for realize/reset, as we'll see later). So this is a bit simpler. However,
instance_finalizeshould have a non-empty default implementation:std::ptr::drop_in_place(self);which should be okay for most devices.
Alternatively, leave out
instance_post_init()andinstance_finalize()until we need them, and put thedrop_in_place()call directly in the unsafe function that goes in the TypeInfo.Quoted 11 lines
------------------------ >8 ------------------------Device methods (realize/reset etc) are now safe idiomatic trait methods:
------------------------ >8 ------------------------ /// Implementation methods for device types. pub trait DeviceImpl: ObjectImpl { fn realize(&mut self) {} fn reset(&mut self) {} } ------------------------ >8 ------------------------This is an incorrect definition of the trait. The default definition of device methods is not "empty", it's "just reuse the superclass implementation". In particular, this means that PL011LuminaryState right now cannot use #[derive(Device)].
Quoted 2 lines
The derive Device macro is responsible for creating all the extern "C" FFI functions that QEMU needs to call these methods.
This is unnecessary. It is perfectly possible to write the extern "C" functions (
class_init, realize, reset) just once as either type-generic functions, or functions in a trait. More on this later.Quoted 12 lines
rust/qemu-api/src/objects.rs new file +6
-0@@ -0,0 +1,90 @@ +// Copyright 2024, Linaro Limited +// Author(s): Manos Pitsidianakis <[email protected]> +// SPDX-License-Identifier: GPL-2.0-or-later + +//! Implementation traits for QEMU objects, devices. +rust/qemu-api/src/objects.rs line 16
Quoted 10 lines
rust/qemu-api/src/objects.rs new file +10
-0+use ::core::ffi::{c_int, c_void,CStr }; + +use crate ::bindings::{DeviceState ,Error ,MigrationPriority ,Object ,ObjectClass ,TypeInfo }; + +/// Trait a type must implement to be registered with QEMU. +pub trait ObjectImpl { +type Class :ClassImpl ; +const TYPE_NAME : &'staticCStr ; +const PARENT_TYPE_NAME :Option <&'staticCStr >; +const ABSTRACT :bool ;These consts should entirely be derived from the #[object()] attribute. You can facilitate the split by having two traits, one for things derived from the attribute (the above four), and one for the vtable.
rust/qemu-api/src/objects.rs line 21
Quoted 4 lines
rust/qemu-api/src/objects.rs new file +4
-0+unsafe fn instance_init (&mut self) {} +fn instance_post_init (&mut self) {} +fn instance_finalize (&mut self) {} +}See above remark on the default implementation of
instance_finalize.rust/qemu-api/src/objects.rs line 32
Quoted 10 lines
rust/qemu-api/src/objects.rs new file +10
-0+/// The `extern`/`unsafe` analogue of [`ObjectImpl`]; it is used internally by `#[derive(Object)]` +/// and should not be implemented manually. +pub unsafe trait ObjectImplUnsafe { +const TYPE_INFO :TypeInfo ; + +const INSTANCE_INIT :Option <unsafe extern "C" fn (obj: *mut Object )>; +const INSTANCE_POST_INIT :Option <unsafe extern "C" fn (obj: *mut Object )>; +const INSTANCE_FINALIZE :Option <unsafe extern "C" fn (obj: *mut Object )>; +} +This trait is not needed at all, because it really has juts one implementation. The fact that there is just one implementation is hidden by the fact that you are generating the code instead of relying on the type system.
All you need is a single function, which will be called via the
module_initmechanism:fn rust_type_register<T: ObjectImpl>() { let TypeInfo ti = ...; unsafe { type_register(&ti); } }rust/qemu-api/src/objects.rs line 40
Quoted 9 lines
rust/qemu-api/src/objects.rs new file +8
-0+/// Methods for QOM class types. +pub trait ClassImpl { +type Object :ObjectImpl ; + +unsafe fn class_init (&mut self, _data: *mut core::ffi::c_void ) {} +unsafe fn class_base_init (&mut self, _data: *mut core::ffi::c_void ) {} +} +This trait (or more precisely
class_initandclass_base_init) is not needed.class_base_initis only needed in very special cases, we can just decide they won't be available in Rust for now and possible for ever.As to
class_initdevice XYZ would only need a non-emptyclass_initmethod if we added support for the_dataargument. But then we would need a way to provide the type of_data, and to cast_datato the appropriate type; we would also need a way to provide a mapping from multiple data objects to multiple type names, which is hard to do because right now each Rust struct has a single type name associated.So, let's just keep only the auto-generated
class_initfor simplicity. If we can just decide that, if device XYZ has superclass FooDevice, it implements FooDeviceImpl andclass_initis provided by the FooDevice bindings.I can't really say if the "type Object" part is needed. I couldn't offhand find anything that uses it, but I may have missed it. If so, it can be in ClassImplUnsafe.
rust/qemu-api/src/objects.rs line 48
Quoted 8 lines
rust/qemu-api/src/objects.rs new file +8
-0+/// The `extern`/`unsafe` analogue of [`ClassImpl`]; it is used internally by `#[derive(Object)]` +/// and should not be implemented manually. +pub unsafe trait ClassImplUnsafe { +const CLASS_INIT :Option <unsafe extern "C" fn (klass: *mut ObjectClass , data: *mut c_void )>; +const CLASS_BASE_INIT :Option < +unsafe extern "C" fn (klass: *mut ObjectClass , data: *mut c_void ), + >; +}Again, no need to have
CLASS_BASE_INIThere.rust/qemu-api/src/objects.rs line 54
Quoted 5 lines
rust/qemu-api/src/objects.rs new file +5
-0+/// Implementation methods for device types. +pub trait DeviceImpl :ObjectImpl { +fn realize (&mut self) {} +fn reset (&mut self) {} +}These unfortunately cannot be functions. Doing so forces the
class_initmethod to assign bothdc->resetanddc->realizefor _all_ classes, whereas for example PL011LuminaryClass would not override either.Therefore, the definition must be
pub trait DeviceImpl: ObjectImpl { const REALIZE: Option<fn realize(&mut self)> = None; const RESET: Option<fn realize(&mut self)> = None; }Yes, it's uglier, but we cannot escape the fact that we're implementing something that Rust doesn't have natively (inheritance). :( So we cannot use language features meant for a completely different kind of polymorphism.
rust/qemu-api/src/objects.rs line 61
Quoted 6 lines
rust/qemu-api/src/objects.rs new file +6
-0+/// The `extern`/`unsafe` analogue of [`DeviceImpl`]; it is used internally by `#[derive(Device)]` +/// and should not be implemented manually. +pub unsafe trait DeviceImplUnsafe { +const REALIZE :Option <unsafe extern "C" fn (dev: *mut DeviceState , _errp: *mut *mut Error )>; +const RESET :Option <unsafe extern "C" fn (dev: *mut DeviceState )>; +}This trait is also unnecessary, because all that you need is a single function:
fn rust_device_class_init<T: DeviceImpl>(
klass: *mut ObjectClass,_data: *mutc_void)defined outside the procedural macro. #[derive(Device)] can define ClassImplUnsafe to point
CLASS_INITtorust_device_class_init.(Later,
rust_device_class_init()can be moved into a trait so that it's possible to define other classes of devices, for example PCI devices. Note that such an extension would be much easier, than if it was _required_ to touch the procedural macro).Quoted 19 lines
rust/qemu-api/src/objects.rs new file +18
-0+/// Constant metadata and implementation methods for types with device migration state. +pub trait Migrateable :DeviceImplUnsafe { +const NAME :Option <&'staticCStr > =None ; +const UNMIGRATABLE :bool =true ; +const EARLY_SETUP :bool =false ; +const VERSION_ID :c_int =1 ; +const MINIMUM_VERSION_ID :c_int =1 ; +const PRIORITY :MigrationPriority =MigrationPriority ::MIG_PRI_DEFAULT ; + +unsafe fn pre_load (&mut self) ->c_int { +0 + } +unsafe fn post_load (&mut self, _version_id:c_int ) ->c_int { +0 + } +unsafe fn pre_save (&mut self) ->c_int { +0 + }rust/qemu-api/src/objects.rs line 90
Quoted 10 lines
rust/qemu-api/src/objects.rs new file +10
-0+unsafe fn post_save (&mut self) ->c_int { +0 + } +unsafe fn needed (&mut self) ->bool { +false + } +unsafe fn dev_unplug_pending (&mut self) ->bool { +false + } +}Premature. No need to add this trait until you add support for migration.
rust/qemu-api/src/tests.rs
Quoted 6 lines
rust/qemu-api/src/tests.rs deleted +0
-0@@ -1,49 +0,0 @@Nope. Fix the test, don't remove it.
rust/qemu-api/src/tests.rs pub struct PL011State { · line 55
Quoted 11 lines
rust/qemu-api/src/tests.rs deleted +3
-1-#[derive( Debug , qemu_api_macros:: Object )] +#[derive( Debug , qemu_api_macros:: Object , qemu_api_macros:: Device )] +#[device(class_name_override = PL011Class )] /// PL011 Device Model in QEMU pub struct PL011State {pub parent_obj:SysBusDevice ,@@ -51,6 +52,7 @@ pub struct PL011State { pub read_count: usize, pub read_trigger: usize,#[doc(alias = "chr" )] +#[property(name = c"chardev" , qdev_prop = qdev_prop_chr)] (See earlier comments on accepting only a LitStr and deriving
qdev_propfrom the type).rust/qemu-api/src/tests.rs pub struct PL011State {
Quoted 8 lines
rust/qemu-api/src/tests.rs deleted +8
-0+impl DeviceImpl for PL011State { +fn realize (&mut self) { + ... + } + +fn reset (&mut self) { + ... + }This extractions of code into DeviceImpl is good. However, as I said above, I'm not sure about the trait itself. I'll remark later when I encounter the definition.
Quoted 1 line
+impl
qemu_api::objects::Migrateablefor PL011State {}Premature.
Before moving on to the procedural macro code, my proposal to split the patches is:
1) introduce the trait ObjectType, define it for Object, DeviceState and SysBusDevice.
2) introduce the traits ObjectImpl, DeviceImpl and ClassImplUnsafe. Define the first two for PL011State.
3) add to common code the wrappers that call into DeviceImpl, removing them from PL011State
4) introduce the functions
rust_type_registerandrust_device_class_initthat use the traits.5) remove most arguments of device_class_init!(), using the infrastructure introduced in the previous two steps
6) split ObjectImpl into a part that will be covered by #[object()], let's call it ObjectInfo
7) add implementation of #[object()], replace PL011State's implementation of ObjectInfo with #[object()]
8) split DeviceImpl into a part that will be covered by #[device()] (properties and categories), let's call it DeviceInfo
9) add #[derive(Device) and implementation of #[device()], replace PL011State's implementation of DeviceInfo with #[device()]
Where 1-5 should be submitted as a separate series, one that does not touch procedural macros *at all* and just generalizes the pl011 code that defines QOM types.
Anyhow, I'll continue reviewing the procedural macro code.
rust/qemu-api/src/tests.rs
Quoted 6 lines
rust/qemu-api/src/tests.rs deleted +6
-0+#[derive( Debug , Default )] +struct DeriveContainer { + category:Option <syn::Path >, + class_name:Option <syn::Ident >, + class_name_override:Option <syn::Ident >, +}Rename to DeviceAttribute.
rust/qemu-api/src/tests.rs
Quoted 2 lines
rust/qemu-api/src/tests.rs deleted +2
-0+impl Parse for DeriveContainer { +fn parse (input:ParseStream ) ->Result <Self > {
syn::Resultrepresents a parse error, not an error in the allowed syntax of the attribute. Below, you're using panic! andunwrap(), but probably instead ofsyn::Resultwe need to have something likepub enum Error {
CompileError(syn::Span, String),
ParseError(syn::Error)
}which extends the CompileError enum of
https://lore.kernel.org/qemu-devel/[email protected]/
and is amenable to use with "?". In particular, note the idiom used by the rootderive_offsets()functions:let input = parse_macro_input!(input as DeriveInput); let expanded = derive_offsets_or_error(input). unwrap_or_else(Into::into); TokenStream::from(expanded)which works via an "impl From<CompileError> for
proc_macro2::TokenStream".I believe that most of the benefit of this series (basically, all except the #[property] attribute) can be obtained without the procedural macro.
Therefore, once we do add the procedural macro, we should not have it
panic on errors.Quoted 8 lines
rust/qemu-api/src/tests.rs deleted +8
-0+let _: syn::Token ![#] = input.parse ()?; +let bracketed; + _ = syn::bracketed!(bracketed in input); +assert_eq! (DEVICE , bracketed.parse ::<syn::Ident >()?); +let mut retval =Self { + category:None , + class_name:None , + class_name_override:None ,rust/qemu-api/src/tests.rs
Quoted 10 lines
rust/qemu-api/src/tests.rs deleted +10
-0+ }; +let content; + _ = syn::parenthesized!(content in bracketed); +while !content.is_empty () { +let value: syn::Ident = content.parse ()?; +if value ==CLASS_NAME { +let _: syn::Token ![=] = content.parse ()?; +if retval.class_name.is_some () { +panic! ("{} can only be used at most once" ,CLASS_NAME ); + }No panic!, instead we need to return a compile_error!() TokenStream, or as above a Result<> that can be converted to compile_error!() up in the chain.
Quoted 1 line
+ retval.class_name = Some(content.parse()?);
Please make this function a separate trait in utilities:
trait AttributeParsing { const NAME: Symbol; fn set(&mut self, key: &syn::Ident, input: &ParseStream) -> Result<()>; fn parse(input: ParseStream) -> Result<Self> { ... } }Then the "if" can move to the struct-specific implementation of
AttributeParsing::set, while the rest can move to the default implementation ofAttributeParsing::parse.#[property()] and #[device()] (and also the proposed #[object()]) can then share the implementation of
AttributeParsing::parse.rust/qemu-api/src/tests.rs
Quoted 12 lines
rust/qemu-api/src/tests.rs deleted +12
-0+ }else if value ==CLASS_NAME_OVERRIDE { +let _: syn::Token ![=] = content.parse ()?; +if retval.class_name_override.is_some () { +panic! ("{} can only be used at most once" ,CLASS_NAME_OVERRIDE ); + }> + retval.class_name_override = Some(content.parse()?); + }else if value ==CATEGORY { +let _: syn::Token ![=] = content.parse ()?; +if retval.category.is_some () { +panic! ("{} can only be used at most once" ,CATEGORY ); + } +let lit: syn::LitStr = content.parse ()?; +let path: syn::Path = lit.parse ()?;Do I understand that this would be
category = "foo::bar::Baz"? If so, why the extra quotes? There can actually be more than one category, so at least add a TODO here.
rust/qemu-api/src/tests.rs
Quoted 3 lines
rust/qemu-api/src/tests.rs deleted +3
-0+#[derive( Debug )] +struct QdevProperty { + name:Option <syn::LitCStr >,Just LitStr. Convert it to CString in the macro. You can reuse the c_str!() macro that I'm adding in the series to fix CI and support old rustc, i.e. quote! { ::qemu_api::c_str!(#name) } or something like that.
Quoted 28 lines
rust/qemu-api/src/tests.rs deleted +28
-0+ qdev_prop: Option<syn::Path>, +} + +impl Parse for QdevProperty { +fn parse (input:ParseStream ) ->Result <Self > { +let _: syn::Token ![#] = input.parse ()?; +let bracketed; + _ = syn::bracketed!(bracketed in input); +assert_eq! (PROPERTY , bracketed.parse ::<syn::Ident >()?); +let mut retval =Self { + name:None , + qdev_prop:None , + }; +let content; + _ = syn::parenthesized!(content in bracketed); +while !content.is_empty () { +let value: syn::Ident = content.parse ()?; +if value ==NAME { +let _: syn::Token ![=] = content.parse ()?; +if retval.name.is_some () { +panic! ("{} can only be used at most once" ,NAME ); + } + retval.name =Some (content.parse ()?); + }else if value ==QDEV_PROP { +let _: syn::Token ![=] = content.parse ()?; +if retval.qdev_prop.is_some () { +panic! ("{} can only be used at most once" ,QDEV_PROP ); + }rust/qemu-api/src/tests.rs
Quoted 10 lines
rust/qemu-api/src/tests.rs deleted +10
-0+ retval.qdev_prop =Some (content.parse ()?); + }else { +panic! ("unrecognized token `{}`" , value); + } + +if !content.is_empty () { +let _: syn::Token ![,] = content.parse ()?; + } + } +Ok (retval)See above with respect to the duplicated code with #[device()].
rust/qemu-api/src/tests.rs
Quoted 7 lines
rust/qemu-api/src/tests.rs deleted +7
-0+let derive_container:DeriveContainer = input + .attrs + .iter () + .find (|a| a.path () ==DEVICE ) + .map (|a| syn::parse (a.to_token_stream ().into ()).expect ("could not parse device attr" )) + .unwrap_or_default (); +let (qdev_properties_static, qdev_properties_expanded) =make_qdev_properties (&input);Please put functions before their callers.
Quoted 7 lines
rust/qemu-api/src/tests.rs deleted +7
-0+let realize_fn =format_ident! ("__{}_realize_generated" , name); +let reset_fn =format_ident! ("__{}_reset_generated" , name); + +let expanded =quote! { +unsafe impl ::qemu_api::objects::DeviceImplUnsafe for #name { +const REALIZE : ::core::option::Option < +unsafe extern "C" fn (rust/qemu-api/src/tests.rs
Quoted 10 lines
rust/qemu-api/src/tests.rs deleted +10
-0+ dev: *mut ::qemu_api::bindings::DeviceState, + errp: *mut *mut ::qemu_api::bindings::Error, + ), + > = Some(#realize_fn); +const RESET : ::core::option::Option < +unsafe extern "C" fn (dev: *mut ::qemu_api::bindings::DeviceState ), + > = Some(#reset_fn); + } + +#[no_mangle] Not needed.
rust/qemu-api/src/tests.rs
Quoted 11 lines
rust/qemu-api/src/tests.rs deleted +11
-0+ pub unsafe extern "C" fn #realize_fn( + dev: *mut ::qemu_api::bindings::DeviceState , + errp: *mut *mut ::qemu_api::bindings::Error , + ) { + let mut instance = NonNull::new(dev.cast::<#name>()).expect(concat!("Expected dev to be a non-null pointer of type ", stringify!(#name))); +unsafe { + ::qemu_api::objects::DeviceImpl ::realize (instance.as_mut ()); + } + } + +#[no_mangle] Not needed.
rust/qemu-api/src/tests.rs
Quoted 8 lines
rust/qemu-api/src/tests.rs deleted +8
-0+ pub unsafe extern "C" fn #reset_fn( + dev: *mut ::qemu_api::bindings::DeviceState , + ) { + let mut instance = NonNull::new(dev.cast::<#name>()).expect(concat!("Expected dev to be a non-null pointer of type ", stringify!(#name))); +unsafe { + ::qemu_api::objects::DeviceImpl ::reset (instance.as_mut ()); + } + }All this code depends on nothing but #name. This is not the C preprocessor; the way to do it in Rust is monomorphization as described above.
Quoted 16 lines
rust/qemu-api/src/tests.rs deleted +16
-0+fn gen_device_class ( + derive_container:DeriveContainer , + qdev_properties_static: syn::Ident , + name: &syn::Ident , +) -> proc_macro2::TokenStream { +let (class_name, class_def) =match ( + derive_container.class_name_override, + derive_container.class_name, + ) { + (Some (class_name), _) => { +let class_expanded =quote! { +#[repr( C )] +pub struct #class_name { + _inner: [u8 ;0 ], + } + };rust/qemu-api/src/tests.rs
Quoted 10 lines
rust/qemu-api/src/tests.rs deleted +10
-0+ (class_name, class_expanded) + } + (None, Some(class_name)) => (class_name, quote! {}), + (None, None) => { +let class_name =format_ident! ("{}Class" , name); +let class_expanded =quote! { +#[repr( C )] +pub struct #class_name { + _inner: [u8 ;0 ], + }This should have a DeviceClass member, it should not be a dummy 0-byte type.
Also, this should be generated by #[derive(Object)].
Quoted 11 lines
rust/qemu-api/src/tests.rs deleted +11
-0+ }; + (class_name, class_expanded) + } + }; +let class_init_fn =format_ident! ("__{}_class_init_generated" , class_name); +let class_base_init_fn =format_ident! ("__{}_class_base_init_generated" , class_name); + +let (vmsd, vmsd_impl) = { +let (i, vmsd) =make_vmstate (name); + (quote! { &#i }, vmsd) + };rust/qemu-api/src/tests.rs
Quoted 10 lines
rust/qemu-api/src/tests.rs deleted +10
-0+let category =if let Some (category) = derive_container.category { +quote! { +const BITS_PER_LONG :u32 = ::core::ffi::c_ulong::BITS ; +let _: ::qemu_api::bindings::DeviceCategory = #category; +let nr: ::core::ffi::c_ulong = #categoryas _ ; +let mask =1 << (nras u32 %BITS_PER_LONG ); +let p = ::core::ptr::addr_of_mut!(dc.as_mut ().categories).offset ((nras u32 /BITS_PER_LONG )as isize ); +let p: *mut ::core::ffi::c_ulong = p.cast (); +let categories = p.read_unaligned (); + p.write_unaligned (categories | mask);What's wrong with
const
BITS_PER_ELEMENT: u32 =::core::mem::sizeof(dc.categories) / dc.categories.len() * 8;dc.categories[((nr as u32) /
BITS_PER_ELEMENT) as usize]|= 1 << ((nr as u32) % BITS_PER_ELEMENT);?
rust/qemu-api/src/tests.rs
Quoted 6 lines
rust/qemu-api/src/tests.rs deleted +6
-0+#[no_mangle] + pub unsafe extern "C" fn #class_init_fn(klass: *mut ObjectClass, data: *mut core::ffi::c_void) { + { + { +let mut dc = + ::core::ptr::NonNull ::new (klass.cast ::<::qemu_api::bindings::DeviceClass >()).unwrap ();And then "let mut dc =
dc.as_mut()". Just write the conversion once.rust/qemu-api/src/tests.rs
Quoted 7 lines
rust/qemu-api/src/tests.rs deleted +7
-0+unsafe { + dc.as_mut ().realize = + <#name as ::qemu_api::objects::DeviceImplUnsafe>::REALIZE; + ::qemu_api::bindings::device_class_set_legacy_reset ( + dc.as_mut (), + <#name as ::qemu_api::objects::DeviceImplUnsafe>::RESET + );As written elsewhere, these should be conditional.
rust/qemu-api/src/tests.rs
Quoted 4 lines
rust/qemu-api/src/tests.rs deleted +4
-0+ dc.as_mut().vmsd = #vmsd; + #props + #category + }> + }All this code should be outside the macro, and should use trait consts instead of quoting.
Quoted 11 lines
rust/qemu-api/src/tests.rs deleted +11
-0+ let mut klass = NonNull::new(klass.cast::<#class_name>()).expect(concat!("Expected klass to be a non-null pointer of type ", stringify!(#class_name))); +unsafe { + ::qemu_api::objects::ClassImpl ::class_init (klass.as_mut (), data); + } + } + } +#[no_mangle] + pub unsafe extern "C" fn #class_base_init_fn(klass: *mut ObjectClass, data: *mut core::ffi::c_void) { + { + let mut klass = NonNull::new(klass.cast::<#class_name>()).expect(concat!("Expected klass to be a non-null pointer of type ", stringify!(#class_name))); +unsafe {rust/qemu-api/src/tests.rs
Quoted 10 lines
rust/qemu-api/src/tests.rs deleted +10
-0+ ::qemu_api::objects::ClassImpl ::class_base_init (klass.as_mut (), data); + } + } + } + + #vmsd_impl + } +} + +fn make_vmstate (name: &syn::Ident ) -> (syn::Ident , proc_macro2::TokenStream ) {Not needed. Just let the user provide a VMStateDescription in DeviceImpl. I'm not sure if it's possible to make it a const; if not, it can be a function returning a &'static VMStateDescription.
rust/qemu-api/src/tests.rs
Quoted 12 lines
rust/qemu-api/src/tests.rs deleted +12
-0+let vmstate_description_ident =format_ident! ("__VMSTATE_{}" , name); + +let pre_load =format_ident! ("__{}_pre_load_generated" , name); +let post_load =format_ident! ("__{}_post_load_generated" , name); +let pre_save =format_ident! ("__{}_pre_save_generated" , name); +let post_save =format_ident! ("__{}_post_save_generated" , name); +let needed =format_ident! ("__{}_needed_generated" , name); +let dev_unplug_pending =format_ident! ("__{}_dev_unplug_pending_generated" , name); + +let migrateable_fish =quote! {<#name as ::qemu_api::objects::Migrateable >}; +let vmstate_description =quote! { +#[used] Attribute not needed.
Quoted 13 lines
rust/qemu-api/src/tests.rs deleted +13
-0+#[allow(non_upper_case_globals)] + pub static #vmstate_description_ident: ::qemu_api::bindings::VMStateDescription = ::qemu_api::bindings::VMStateDescription { + name: if let Some(name) = #migrateable_fish::NAME { + name.as_ptr () + }else { + <#name as ::qemu_api::objects::ObjectImplUnsafe>::TYPE_INFO.name + }, + unmigratable: #migrateable_fish::UNMIGRATABLE, + early_setup: #migrateable_fish::EARLY_SETUP, + version_id: #migrateable_fish::VERSION_ID, + minimum_version_id: #migrateable_fish::MINIMUM_VERSION_ID, + priority: #migrateable_fish::PRIORITY, + pre_load: Some(#pre_load),rust/qemu-api/src/tests.rs
Quoted 10 lines
rust/qemu-api/src/tests.rs deleted +10
-0+ post_load: Some(#post_load), + pre_save: Some(#pre_save), + post_save: Some(#post_save), + needed: Some(#needed), + dev_unplug_pending: Some(#dev_unplug_pending), + fields: ::core::ptr::null(), + subsections: ::core::ptr::null(), + }; + +#[no_mangle] Not needed (other occurrences below).
rust/qemu-api/src/tests.rs
Quoted 11 lines
rust/qemu-api/src/tests.rs deleted +11
-0+ pub unsafe extern "C" fn #pre_load(opaque: *mut ::core::ffi::c_void) -> ::core::ffi::c_int { + let mut instance = NonNull::new(opaque.cast::<#name>()).expect(concat!("Expected opaque to be a non-null pointer of type ", stringify!(#name), "::Object")); +unsafe { + ::qemu_api::objects::Migrateable ::pre_load (instance.as_mut ()) + } + } +#[no_mangle] + pub unsafe extern "C" fn #post_load(opaque: *mut ::core::ffi::c_void, version_id: core::ffi::c_int) -> ::core::ffi::c_int { + let mut instance = NonNull::new(opaque.cast::<#name>()).expect(concat!("Expected opaque to be a non-null pointer of type ", stringify!(#name), "::Object")); +unsafe { + ::qemu_api::objects::Migrateable ::post_load (instance.as_mut (), version_id)Again, introducing the Migrateable code and all these thunks is premature; but in any case, this can only return 0 or -1 so make
Migrateable::post_load()return Result<(), ()>.rust/qemu-api/src/tests.rs
Quoted 9 lines
rust/qemu-api/src/tests.rs deleted +9
-0+ } + } +#[no_mangle] + pub unsafe extern "C" fn #pre_save(opaque: *mut ::core::ffi::c_void) -> ::core::ffi::c_int { + let mut instance = NonNull::new(opaque.cast::<#name>()).expect(concat!("Expected opaque to be a non-null pointer of type ", stringify!(#name), "::Object")); +unsafe { + ::qemu_api::objects::Migrateable ::pre_save (instance.as_mut ()) + } + }Likewise.
rust/qemu-api/src/tests.rs
Quoted 7 lines
rust/qemu-api/src/tests.rs deleted +7
-0+#[no_mangle] + pub unsafe extern "C" fn #post_save(opaque: *mut ::core::ffi::c_void) -> ::core::ffi::c_int { + let mut instance = NonNull::new(opaque.cast::<#name>()).expect(concat!("Expected opaque to be a non-null pointer of type ", stringify!(#name), "::Object")); +unsafe { + ::qemu_api::objects::Migrateable ::post_save (instance.as_mut ()) + } + }Likewise.
Quoted 26 lines
rust/qemu-api/src/tests.rs deleted +21
-0+#[no_mangle] + pub unsafe extern "C" fn #needed(opaque: *mut ::core::ffi::c_void) -> bool { + let mut instance = NonNull::new(opaque.cast::<#name>()).expect(concat!("Expected opaque to be a non-null pointer of type ", stringify!(#name), "::Object")); +unsafe { + ::qemu_api::objects::Migrateable ::needed (instance.as_mut ()) + } + } +#[no_mangle] + pub unsafe extern "C" fn #dev_unplug_pending(opaque: *mut ::core::ffi::c_void) -> bool { + let mut instance = NonNull::new(opaque.cast::<#name>()).expect(concat!("Expected opaque to be a non-null pointer of type ", stringify!(#name), "::Object")); +unsafe { + ::qemu_api::objects::Migrateable ::dev_unplug_pending (instance.as_mut ()) + } + } + }; + +let expanded =quote! { + #vmstate_description + }; + (vmstate_description_ident, expanded) +}rust/qemu-api-macros/src/lib.rs +0
-0rust/qemu-api-macros/src/lib.rs line 5
Quoted 4 lines
rust/qemu-api-macros/src/lib.rs +1
-0@@ -2,42 +2,21 @@// Author(s): Manos Pitsidianakis <[email protected]> // SPDX-License-Identifier: GPL-2.0-or-later +#![allow(dead_code)] Why?
Quoted 32 lines
rust/qemu-api-macros/src/lib.rs +5
-23use proc_macro::TokenStream ; -use quote::{format_ident, quote}; -use syn::{parse_macro_input,DeriveInput }; + +mod device; +mod object; +mod symbols; +mod utilities;#[proc_macro_derive( Object )] pub fn derive_object (input:TokenStream ) ->TokenStream { -let input =parse_macro_input! (inputas DeriveInput ); - -let name = input.ident; -let module_static =format_ident! ("__{}_LOAD_MODULE" , name); - -let expanded =quote! { -#[allow(non_upper_case_globals)] -#[used] -#[cfg_attr(target_os = "linux" , link_section = ".ctors" )] -#[cfg_attr(target_os = "macos" , link_section = "__DATA,__mod_init_func" )] -#[cfg_attr(target_os = "windows" , link_section = ".CRT$XCU" )] -pub static #module_static:extern "C" fn () = { -extern "C" fn __register () { -unsafe { - ::qemu_api::bindings::type_register_static (&<#name as ::qemu_api::definitions::ObjectImpl >::TYPE_INFO ); - } - } - -extern "C" fn __load () { -unsafe { - ::qemu_api::bindings::register_module_init(rust/qemu-api-macros/src/lib.rs line 16
Quoted 10 lines
rust/qemu-api-macros/src/lib.rs +1
-9- Some(__register), - ::qemu_api::bindings::module_init_type::MODULE_INIT_QOM - ); - } - } - - __load - }; - }; + object::derive_object (input)Moving code to a separate file should be a separate patch from modifying the expansion of the macro.
Quoted 15 lines
rust/qemu-api-macros/src/symbols.rs new file +9
-0@@ -0,0 +1,55 @@ +// Copyright 2024, Linaro Limited +// Author(s): Manos Pitsidianakis <[email protected]> +// SPDX-License-Identifier: GPL-2.0-or-later + +use core::fmt; +use syn::{Ident ,Path }; + +#[derive( Copy , Clone , Debug )] +pub struct Symbol (&'staticstr );rust/qemu-api-macros/src/symbols.rs line 19
Quoted 10 lines
rust/qemu-api-macros/src/symbols.rs new file +10
-0+ +pub const DEVICE :Symbol =Symbol ("device" ); +pub const NAME :Symbol =Symbol ("name" ); +pub const CATEGORY :Symbol =Symbol ("category" ); +pub const CLASS_NAME :Symbol =Symbol ("class_name" ); +pub const CLASS_NAME_OVERRIDE :Symbol =Symbol ("class_name_override" ); +pub const QDEV_PROP :Symbol =Symbol ("qdev_prop" ); +pub const MIGRATEABLE :Symbol =Symbol ("migrateable" ); +pub const PROPERTIES :Symbol =Symbol ("properties" ); +pub const PROPERTY :Symbol =Symbol ("property" );Declare these in
device.rsas needed, not here. This avoids "use symbols::*". It also allows making them not "pub", so that dead ones are detected by the compiler (e.g. MIGRATEABLE, PROPERTIES).rust/qemu-api-macros/src/symbols.rs line 20
Quoted 1 line
rust/qemu-api-macros/src/symbols.rs new file +1
-0+pub fn assert_is_repr_c_struct (input: &DeriveInput , derive_macro: &'staticstr ) {Nice but a bit overengineered. Unless you think/know that you'll have a use for Repr elsewhere, try sharing code with Junjie's macro
https://lore.kernel.org/qemu-devel/[email protected]/.Paolo
Re: [PATCH 03/11] rust/qemu-api-macros: introduce Device proc macro
Manos,
I understand your desire to make fast progress, at the same time I can't stress enough the importance of building on a shared design. Each architectural decision we make now - whether about trait hierarchies, macro designs, or API patterns - will significantly impact future maintenance and development work.
The suggestions about how to split the implementation into smaller patches aim to facilitate smaller and easier discussions about specific aspects, and they are only examples and in no way the only possible solution. However, with respect to design choices I think I pointed out major issues that can't be treated simply as wanting to "do everything at once". Dismissing design discussions as mere disagreements about style, or responding confrontationally that you will address "bits that are wrong and not much else" won't help us move forward. Code reviews, especially for core APIs, necessarily include discussion of design choices and language usage.
This isn't the first time our technical discussions have become tense, and we're talking past each other at this point. My suggestion is that you try to explain your point of view to a third person, that can help you understand the patch review process and what is requested of both code contributors and reviewers.
Thanks,
Paolo
Il dom 27 ott 2024, 23:40 Manos Pitsidianakis <
[email protected]> ha scritto:
Quoted 15 lines
Thank you for the review comments Paolo. I will address any bits I did wrong and not much the rest, it's obvious you have a disagreement over how things are done and that's fine. This series does not attempt to solve everything at once and arguing again and again over "this Trait should have been OtherTrait and this thing should have been thing!()" is not productive. Your review style of relentless disagreement after disagreement is tiresome and impossible to deal with; it's like a denial of service for other human beings. I suggest you take a step back and take a deep breath before reviewing Rust patches again. I assure you I will make sure to address all your comments either in code, TODO comments, or patch messages.
In the meantime, take it easy.
PATCH 4/11 rust: add support for migration in device models
In reply to Manos PitsidianakisThis commit adds support for declaring migration state to device models in Rust. This is done through different but related parts:
- The Device derive macro gains new attributes vmstate_fields and vmstate_subsections. This allows the device declaration to include the vmstate fields directly at the struct definition.
- a new qemu_api module, vmstate was added. There a bunch of Rust macros declared there that are equivalent in spirit to the C macros declared in include/migration/vmstate.h.
For example the Rust of equivalent of the C macro:
VMSTATE_UINT32(field_name, struct_name)
is:
vmstate_uint32!(field_name, StructName)
This breathtaking development now allows us to not have to define VMStateDescription ourselves but split the notion of migration to two parts:
- A Migrateable trait that allows a type to define version_ids, name, priority, override methods like pre_load, post_load, pre_save etc.
- Define the actual vmstate fields and subsections through the Device derive macro right there with the struct definition:
------------------------ >8 ------------------------
#[repr(C)]
#[derive(Debug, qemu_api_macros::Object, qemu_api_macros::Device)]
+#[device(
+ class_name_override = PL011Class,
+ vmstate_fields = vmstate_fields!{
+ vmstate_unused!(u32::BITS as u64), + vmstate_uint32!(flags, PL011State), + vmstate_uint32!(line_control, PL011State), + vmstate_uint32!(receive_status_error_clear, PL011State), + vmstate_uint32!(control, PL011State), + vmstate_uint32!(dmacr, PL011State), + vmstate_uint32!(int_enabled, PL011State), + vmstate_uint32!(int_level, PL011State), + vmstate_uint32_array!(read_fifo, PL011State, PL011_FIFO_DEPTH), + vmstate_uint32!(ilpr, PL011State), + vmstate_uint32!(ibrd, PL011State), + vmstate_uint32!(fbrd, PL011State), + vmstate_uint32!(ifl, PL011State), + vmstate_int32!(read_pos, PL011State), + vmstate_int32!(read_count, PL011State), + vmstate_int32!(read_trigger, PL011State),
+ },
+ vmstate_subsections = vmstate_subsections!{
+ VMSTATE_PL011_CLOCK
+ }
+)]
/// PL011 Device Model in QEMU
pub struct PL011State {
pub parent_obj: SysBusDevice,
------------------------ >8 ------------------------
--- rust/hw/char/pl011/src/device.rs | 92 +++++++- rust/qemu-api-macros/src/device.rs | 111 +++------- rust/qemu-api-macros/src/lib.rs | 1 + rust/qemu-api-macros/src/symbols.rs | 2 + rust/qemu-api-macros/src/vmstate.rs | 113 ++++++++++ rust/qemu-api/meson.build | 1 + rust/qemu-api/src/lib.rs | 3 + rust/qemu-api/src/vmstate.rs | 403 ++++++++++++++++++++++++++++++++++++ 8 files changed, 637 insertions(+), 89 deletions(-)
rust/hw/char/pl011/src/device.rs +90 -2
@@ -10,6 +10,8 @@use qemu_api::{ bindings::{self, *}, objects::*, + vmstate_clock, vmstate_fields, vmstate_int32, vmstate_subsections, vmstate_uint32, + vmstate_uint32_array, vmstate_unused, };use crate ::{
@@ -20,14 +22,74 @@static PL011_ID_ARM : [c_uchar ;8 ] = [0x11 ,0x10 ,0x14 ,0x00 ,0x0d ,0xf0 ,0x05 ,0xb1 ]; +/// Integer Baud Rate Divider, `UARTIBRD` +const IBRD_MASK :u32 =0x3f ; + +/// Fractional Baud Rate Divider, `UARTFBRD` +const FBRD_MASK :u32 =0xffff ; +const DATA_BREAK :u32 =1 <<10 ;/// QEMU sourced constant. pub const PL011_FIFO_DEPTH :usize =16_usize ; +#[no_mangle] +extern "C" fn pl011_clock_needed (opaque: *mut c_void ) ->bool { +unsafe { +debug_assert! (!opaque.is_null ()); +let state =NonNull ::new_unchecked (opaque.cast ::<PL011State >()); + state.as_ref ().migrate_clock + } +} + +qemu_api::vmstate_description! { +/// Migration subsection for [`PL011State`] clock. +pub static VMSTATE_PL011_CLOCK :VMStateDescription =VMStateDescription { + name:c"pl011/clock" , + unmigratable:false , + early_setup:false , + version_id:1 , + minimum_version_id:1 , + priority:MigrationPriority ::MIG_PRI_DEFAULT , + pre_load:None , + post_load:None , + pre_save:None , + post_save:None , + needed:Some (pl011_clock_needed), + dev_unplug_pending:None , + fields:vmstate_fields! { +vmstate_clock! (clock,PL011State ), + }, + subsections: ::core::ptr::null (), + }; +} +#[repr( C )] #[derive( Debug , qemu_api_macros:: Object , qemu_api_macros:: Device )] -#[device(class_name_override = PL011Class )] +#[device( +class_name_override = PL011Class , +vmstate_fields = vmstate_fields!{ +vmstate_unused!( u32 :: BITS as u64 ), +vmstate_uint32!(flags, PL011State ), +vmstate_uint32!(line_control, PL011State ), +vmstate_uint32!(receive_status_error_clear, PL011State ), +vmstate_uint32!(control, PL011State ), +vmstate_uint32!(dmacr, PL011State ), +vmstate_uint32!(int_enabled, PL011State ), +vmstate_uint32!(int_level, PL011State ), +vmstate_uint32_array!(read_fifo, PL011State , PL011_FIFO_DEPTH ), +vmstate_uint32!(ilpr, PL011State ), +vmstate_uint32!(ibrd, PL011State ), +vmstate_uint32!(fbrd, PL011State ), +vmstate_uint32!(ifl, PL011State ), +vmstate_int32!(read_pos, PL011State ), +vmstate_int32!(read_count, PL011State ), +vmstate_int32!(read_trigger, PL011State ), +}, +vmstate_subsections = vmstate_subsections!{ +VMSTATE_PL011_CLOCK +} +)] /// PL011 Device Model in QEMU pub struct PL011State {pub parent_obj:SysBusDevice ,
@@ -165,7 +227,33 @@ fn reset(&mut self) { } } -impl qemu_api::objects::Migrateable for PL011State {} +impl qemu_api::objects::Migrateable for PL011State { +const NAME :Option <&'staticCStr > =Some (c"pl011" ); +const UNMIGRATABLE :bool =false ; +const VERSION_ID :c_int =2 ; +const MINIMUM_VERSION_ID :c_int =2 ; + +unsafe fn post_load (&mut self, _version_id:c_int ) ->c_int { +/* Sanity-check input state */ +if self.read_pos >= self.read_fifo.len () || self.read_count > self.read_fifo.len () { +return -1 ; + } + +if !self.fifo_enabled () && self.read_count >0 && self.read_pos >0 { +// Older versions of PL011 didn't ensure that the single +// character in the FIFO in FIFO-disabled mode is in +// element 0 of the array; convert to follow the current +// code's assumptions. + self.read_fifo[0 ] = self.read_fifo[self.read_pos]; + self.read_pos =0 ; + } + + self.ibrd &=IBRD_MASK ; + self.fbrd &=FBRD_MASK ; + +0 + } +}#[used] pub static CLK_NAME : &CStr =c"clk" ;
rust/qemu-api-macros/src/device.rs +24 -87
142 lines not on this page · raw message
rust/qemu-api-macros/src/lib.rs +1 -0
@@ -10,6 +10,7 @@mod object;mod symbols;mod utilities; +mod vmstate;#[proc_macro_derive( Object )] pub fn derive_object (input:TokenStream ) ->TokenStream {
rust/qemu-api-macros/src/symbols.rs +2 -0
@@ -15,6 +15,8 @@pub const CLASS_NAME_OVERRIDE :Symbol =Symbol ("class_name_override" );pub const QDEV_PROP :Symbol =Symbol ("qdev_prop" );pub const MIGRATEABLE :Symbol =Symbol ("migrateable" ); +pub const VMSTATE_FIELDS :Symbol =Symbol ("vmstate_fields" ); +pub const VMSTATE_SUBSECTIONS :Symbol =Symbol ("vmstate_subsections" );pub const PROPERTIES :Symbol =Symbol ("properties" );pub const PROPERTY :Symbol =Symbol ("property" );
rust/qemu-api-macros/src/vmstate.rs new file +113 -0
113 lines not on this page · raw message
rust/qemu-api/meson.build +1 -0
@@ -4,6 +4,7 @@ _qemu_api_rs = static_library( [ 'src/lib.rs', 'src/objects.rs', + 'src/vmstate.rs', ], {'.' : bindings_rs}, ),
rust/qemu-api/src/lib.rs +3 -0
@@ -26,8 +26,11 @@ unsafe impl Send for bindings::Property {}unsafe impl Sync for bindings::Property {}unsafe impl Sync for bindings::TypeInfo {}unsafe impl Sync for bindings::VMStateDescription {} +unsafe impl Sync for bindings::VMStateField {} +unsafe impl Sync for bindings::VMStateInfo {}pub mod objects; +pub mod vmstate;use std::alloc::{GlobalAlloc ,Layout };
rust/qemu-api/src/vmstate.rs new file +403 -0
403 lines not on this page · raw message
Signature · 1 line
2.45.2
PATCH 5/11 rust/pl011: move CLK_NAME static to function scope
In reply to Manos PitsidianakisWe do not need to have CLK_NAME public nor a static. No functional change.
--- rust/hw/char/pl011/src/device.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-)
rust/hw/char/pl011/src/device.rs +2 -3
@@ -152,6 +152,8 @@ impl ObjectImpl for PL011State {/// location/instance. All its fields are expected to hold unitialized /// values with the sole exception of `parent_obj`. unsafe fn instance_init (&mut self) { +const CLK_NAME : &CStr =c"clk" ; +let dev =addr_of_mut! (*self).cast ::<DeviceState >();// SAFETY: //
@@ -255,9 +257,6 @@ unsafe fn post_load(&mut self, _version_id: c_int) -> c_int { } } -#[used] -pub static CLK_NAME : &CStr =c"clk" ; -impl PL011State {pub fn read ( &mut self,
Signature · 1 line
2.45.2
PATCH 6/11 rust/pl011: add TYPE_PL011_LUMINARY device
In reply to Manos PitsidianakisAdd a device specialization for the Luminary UART device.
This commit adds a DeviceId enum that utilizes the Index trait to return different bytes depending on what device id the UART has (Arm -default- or Luminary)
--- rust/hw/char/pl011/src/device.rs | 59 ++++++++++++++++++++++++++++++++++++++-- rust/hw/char/pl011/src/lib.rs | 1 + 2 files changed, 57 insertions(+), 3 deletions(-)
rust/hw/char/pl011/src/device.rs +56 -3
@@ -20,8 +20,6 @@ RegisterOffset, }; -static PL011_ID_ARM : [c_uchar ;8 ] = [0x11 ,0x10 ,0x14 ,0x00 ,0x0d ,0xf0 ,0x05 ,0xb1 ]; -/// Integer Baud Rate Divider, `UARTIBRD` const IBRD_MASK :u32 =0x3f ;
@@ -64,6 +62,29 @@ extern "C" fn pl011_clock_needed(opaque: *mut c_void) -> bool { }; } +#[derive( Clone , Copy , Debug )] +enum DeviceId { +#[allow(dead_code)] +Arm =0 , +Luminary , +} + +impl std::ops::Index <hwaddr >for DeviceId { +type Output =c_uchar ; + +fn index (&self, idx:hwaddr ) -> &Self ::Output { +match self { +Self ::Arm => &Self ::PL011_ID_ARM [idxas usize ], +Self ::Luminary => &Self ::PL011_ID_LUMINARY [idxas usize ], + } + } +} + +impl DeviceId { +const PL011_ID_ARM : [c_uchar ;8 ] = [0x11 ,0x10 ,0x14 ,0x00 ,0x0d ,0xf0 ,0x05 ,0xb1 ]; +const PL011_ID_LUMINARY : [c_uchar ;8 ] = [0x11 ,0x00 ,0x18 ,0x01 ,0x0d ,0xf0 ,0x05 ,0xb1 ]; +} +#[repr( C )] #[derive( Debug , qemu_api_macros:: Object , qemu_api_macros:: Device )] #[device(
@@ -134,6 +155,8 @@ pub struct PL011State {#[doc(alias = "migrate_clk" )] #[property(name = c"migrate-clk" , qdev_prop = qdev_prop_bool)] pub migrate_clock: bool, +/// The byte string that identifies the device. + device_id: DeviceId, }impl ObjectImpl for PL011State {
@@ -267,7 +290,7 @@ pub fn read( std::ops::ControlFlow ::Break (match RegisterOffset ::try_from (offset) {Err (v)if (0x3f8 ..0x400 ).contains (&v) => { - u64::from (PL011_ID_ARM [((offset -0xfe0 ) >>2 )as usize ]) + u64::from (self.device_id[(offset -0xfe0 ) >>2 ]) }Err (_) => {// qemu_log_mask(LOG_GUEST_ERROR, "pl011_read: Bad offset 0x%x\n", (int)offset);
@@ -660,3 +683,33 @@ pub fn update(&self) { dev } } + +#[repr( C )] +#[derive( Debug , qemu_api_macros:: Object , qemu_api_macros:: Device )] +/// PL011 Luminary device model. +pub struct PL011Luminary { + parent_obj:PL011State , +} + +impl ObjectImpl for PL011Luminary { +type Class =PL011LuminaryClass ; + +const TYPE_NAME : &'staticCStr =crate ::TYPE_PL011_LUMINARY ; +const PARENT_TYPE_NAME :Option <&'staticCStr > =Some (crate ::TYPE_PL011 ); +const ABSTRACT :bool =false ; + +/// Initializes a pre-allocated, unitialized instance of `PL011Luminary`. +/// +/// # Safety +/// +/// `self` must point to a correctly sized and aligned location for the +/// `PL011Luminary` 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 instance_init (&mut self) { + self.parent_obj.device_id =DeviceId ::Luminary ; + } +} + +impl DeviceImpl for PL011Luminary {} +impl qemu_api::objects::Migrateable for PL011Luminary {}
rust/hw/char/pl011/src/lib.rs +1 -0
@@ -45,6 +45,7 @@pub mod memory_ops;pub const TYPE_PL011 : &::core::ffi::CStr =c"pl011" ; +pub const TYPE_PL011_LUMINARY : &::core::ffi::CStr =c"pl011_luminary" ;/// Offset of each register from the base memory address of the device. ///
Signature · 1 line
2.45.2
Re: [PATCH 06/11] rust/pl011: add TYPE_PL011_LUMINARY device
Quoted 11 lines · Manos Pitsidianakis
Date: Thu, 24 Oct 2024 17:03:04 +0300
From: Manos Pitsidianakis <[email protected]>
Subject: [PATCH 06/11]rust/pl011: addTYPE_PL011_LUMINARYdevice
X-Mailer: b4 0.15-dev-12fc5Add a device specialization for the Luminary UART device.
This commit adds a DeviceId enum that utilizes the Index trait to return different bytes depending on what device id the UART has (Arm -default- or Luminary)
Quoted 6 lines
Signed-off-by Manos Pitsidianakis <[email protected]>--- rust/hw/char/pl011/src/device.rs | 59 ++++++++++++++++++++++++++++++++++++++-- rust/hw/char/pl011/src/lib.rs | 1 + 2 files changed, 57 insertions(+), 3 deletions(-)
This device type is required by qtest-arm/qom-test & qtest-aarch64/qom-test! I will pick it up for testing on my side.
PATCH 7/11 rust/pl011: move pub callback decl to local scope
In reply to Manos Pitsidianakisextern "C" callbacks in instance_init() do not need to be public. Move them to local function scope instead.
No functional change.
--- rust/hw/char/pl011/src/device.rs | 104 +++++++++++++++++++-------------------- 1 file changed, 50 insertions(+), 54 deletions(-)
rust/hw/char/pl011/src/device.rs +50 -54
@@ -219,6 +219,56 @@ unsafe fn instance_init(&mut self) {impl DeviceImpl for PL011State {fn realize (&mut self) { +/// # Safety +/// +/// We expect the FFI user of this function to pass a valid pointer, that has +/// the same size as [`PL011State`]. We also expect the device is +/// readable/writeable from one thread at any time. +unsafe extern "C" fn pl011_can_receive (opaque: *mut c_void ) ->c_int { +unsafe { +debug_assert! (!opaque.is_null ()); +let state =NonNull ::new_unchecked (opaque.cast ::<PL011State >()); + state.as_ref ().can_receive ().into () + } + } +/// # Safety +/// +/// We expect the FFI user of this function to pass a valid pointer, that has +/// the same size as [`PL011State`]. We also expect the device is +/// readable/writeable from one thread at any time. +/// +/// The buffer and size arguments must also be valid. +unsafe extern "C" fn pl011_receive ( + opaque: *mut core::ffi::c_void , + buf: *const u8 , + size: core::ffi::c_int , + ) { +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 ())) + } + } + } + +/// # Safety +/// +/// We expect the FFI user of this function to pass a valid pointer, that has +/// the same size as [`PL011State`]. We also expect the device is +/// readable/writeable from one thread at any time. +unsafe extern "C" fn pl011_event (opaque: *mut core::ffi::c_void , event:QEMUChrEvent ) { +unsafe { +debug_assert! (!opaque.is_null ()); +let mut state =NonNull ::new_unchecked (opaque.cast ::<PL011State >()); + state.as_mut ().event (event) + } + } +// SAFETY: self.char_backend has the correct size and alignment for a // CharBackend object, and its callbacks are of the correct types. unsafe {
@@ -611,60 +661,6 @@ pub fn update(&self) {/// # Safety /// -/// We expect the FFI user of this function to pass a valid pointer, that has -/// the same size as [`PL011State`]. We also expect the device is -/// readable/writeable from one thread at any time. -#[no_mangle] -pub unsafe extern "C" fn pl011_can_receive (opaque: *mut c_void ) ->c_int { -unsafe { -debug_assert! (!opaque.is_null ()); -let state =NonNull ::new_unchecked (opaque.cast ::<PL011State >()); - state.as_ref ().can_receive ().into () - } -} - -/// # Safety -/// -/// We expect the FFI user of this function to pass a valid pointer, that has -/// the same size as [`PL011State`]. We also expect the device is -/// readable/writeable from one thread at any time. -/// -/// The buffer and size arguments must also be valid. -#[no_mangle] -pub unsafe extern "C" fn pl011_receive ( - opaque: *mut core::ffi::c_void , - buf: *const u8 , - size: core::ffi::c_int , -) { -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 ())) - } - } -} - -/// # Safety -/// -/// We expect the FFI user of this function to pass a valid pointer, that has -/// the same size as [`PL011State`]. We also expect the device is -/// readable/writeable from one thread at any time. -#[no_mangle] -pub unsafe extern "C" fn pl011_event (opaque: *mut core::ffi::c_void , event:QEMUChrEvent ) { -unsafe { -debug_assert! (!opaque.is_null ()); -let mut state =NonNull ::new_unchecked (opaque.cast ::<PL011State >()); - state.as_mut ().event (event) - } -} - -/// # Safety -/// /// We expect the FFI user of this function to pass a valid pointer for `chr`. #[no_mangle] pub unsafe extern "C" fn pl011_create(
Signature · 1 line
2.45.2
PATCH 8/11 rust/pl011: remove commented out C code
In reply to Manos PitsidianakisThis code juxtaposed what should be happening according to the C device model but is not needed now that this has been reviewed (I hope) and its validity checked against what the C device does (I hope, again).
No functional change.
--- rust/hw/char/pl011/src/device.rs | 16 ---------------- 1 file changed, 16 deletions(-)
rust/hw/char/pl011/src/device.rs +0 -16
@@ -347,7 +347,6 @@ pub fn read(0 } Ok(DR) => { -// s->flags &= ~PL011_FLAG_RXFF; self.flags.set_receive_fifo_full (false );let c = self.read_fifo[self.read_pos];if self.read_count >0 {
@@ -355,11 +354,9 @@ pub fn read( self.read_pos = (self.read_pos +1 ) & (self.fifo_depth () -1 ); }if self.read_count ==0 { -// self.flags |= PL011_FLAG_RXFE; self.flags.set_receive_fifo_empty (true ); }if self.read_count +1 == self.read_trigger { -//self.int_level &= ~ INT_RX; self.int_level &= !registers::INT_RX ; }// Update error bits.
@@ -529,13 +526,6 @@ fn loopback_mdmctrl(&mut self) { * dealt with here. */ -//fr = s->flags & ~(PL011_FLAG_RI | PL011_FLAG_DCD | -// PL011_FLAG_DSR | PL011_FLAG_CTS); -//fr |= (cr & CR_OUT2) ? PL011_FLAG_RI : 0; -//fr |= (cr & CR_OUT1) ? PL011_FLAG_DCD : 0; -//fr |= (cr & CR_RTS) ? PL011_FLAG_CTS : 0; -//fr |= (cr & CR_DTR) ? PL011_FLAG_DSR : 0; -// self.flags.set_ring_indicator (self.control.out_2 ()); self.flags.set_data_carrier_detect (self.control.out_1 ()); self.flags.set_clear_to_send (self.control.request_to_send ());
@@ -546,10 +536,6 @@ fn loopback_mdmctrl(&mut self) {let mut il = self.int_level; il &= !Interrupt ::MS ; -//il |= (fr & PL011_FLAG_DSR) ? INT_DSR : 0; -//il |= (fr & PL011_FLAG_DCD) ? INT_DCD : 0; -//il |= (fr & PL011_FLAG_CTS) ? INT_CTS : 0; -//il |= (fr & PL011_FLAG_RI) ? INT_RI : 0; if self.flags.data_set_ready () { il |=Interrupt ::DSR as u32 ;
@@ -622,10 +608,8 @@ pub fn put_fifo(&mut self, value: c_uint) {let slot = (self.read_pos + self.read_count) & (depth -1 ); self.read_fifo[slot] = value; self.read_count +=1 ; -// s->flags &= ~PL011_FLAG_RXFE; self.flags.set_receive_fifo_empty (false );if self.read_count == depth { -//s->flags |= PL011_FLAG_RXFF; self.flags.set_receive_fifo_full (true ); }
Signature · 1 line
2.45.2
PATCH 9/11 rust/pl011: Use correct masks for IBRD and FBRD
In reply to Manos PitsidianakisPort fix from commit cd247eae16ab1b9ce97fd34c000c1b883feeda45 "hw/char/pl011: Use correct masks for IBRD and FBRD"
Related issue: <https://gitlab.com/qemu-project/qemu/-/issues/2610>
--- rust/hw/char/pl011/src/device.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
rust/hw/char/pl011/src/device.rs +2 -2
@@ -21,10 +21,10 @@ };/// Integer Baud Rate Divider, `UARTIBRD` -const IBRD_MASK :u32 =0x3f ; +const IBRD_MASK :u32 =0xffff ;/// Fractional Baud Rate Divider, `UARTFBRD` -const FBRD_MASK :u32 =0xffff ; +const FBRD_MASK :u32 =0x3f ;const DATA_BREAK :u32 =1 <<10 ;
Signature · 1 line
2.45.2
PATCH 10/11 rust/qemu-api: add log module
In reply to Manos PitsidianakisLogging in QEMU is done by function-like C macros, which we cannot use directly from Rust with bindgen.
This commit adds a new qemu_api module, log, that provides the following interfaces:
- a LogMask enum type that uses the mask values from the generated bindings, and makes sure the rust enum variant names and values will match.
- LogMask aliases LogMask::GUEST_ERROR and LogMask::UNIMPLEMENTED for convenience.
- a private qemu_loglevel_mask() function, counterpart of qemu_loglevel_mask in include/qemu/log-for-trace.h, which we cannot use from bindgen since it's a static inline item.
- public qemu_log(), qemu_log_mask() and qemu_log_mask_and_addr() functions that should act like the C equivalent:
pub fn qemu_log_mask_and_addr(log_mask: LogMask, address: u64, str: &str); pub fn qemu_log_mask(log_mask: LogMask, str: &str); pub fn qemu_log(str: &str);
It takes a 'static or allocated string slice as argument, but in the feature we will introduce better log macros in Rust that make use of Rust's format arguments. This is not really a bad compromise since generating a log item is not a hot path so allocating here is fine.
Example usage will be:
```rust
qemu_log_mask(LogMask::GUEST_ERROR, "device XYZ failed spectacularly");
qemu_log_mask(
LogMask::UNIMPLEMENTED,
&format!(
"We haven't implemented this feature in {file}:{line} out of pure laziness.",
file = file!(),
line = line!()
)
);
```--- rust/wrapper.h | 1 + rust/qemu-api/meson.build | 1 + rust/qemu-api/src/lib.rs | 1 + rust/qemu-api/src/log.rs | 140 ++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 143 insertions(+)
rust/wrapper.h +1 -0
@@ -32,6 +32,7 @@#include "qemu/osdep.h" #include "qemu/module.h" +#include "qemu/log.h" #include "qemu-io.h" #include "sysemu/sysemu.h" #include "hw/sysbus.h"
rust/qemu-api/meson.build +1 -0
@@ -3,6 +3,7 @@ _qemu_api_rs = static_library( structured_sources( [ 'src/lib.rs', + 'src/log.rs', 'src/objects.rs', 'src/vmstate.rs', ],
rust/qemu-api/src/lib.rs +1 -0
@@ -29,6 +29,7 @@ unsafe impl Sync for bindings::VMStateDescription {}unsafe impl Sync for bindings::VMStateField {}unsafe impl Sync for bindings::VMStateInfo {} +pub mod log;pub mod objects;pub mod vmstate;
rust/qemu-api/src/log.rs new file +140 -0
140 lines not on this page · raw message
Signature · 1 line
2.45.2
PATCH 11/11 rust/pl011: log guest/unimp errors
In reply to Manos PitsidianakisUse the qemu_log_mask() functions introduced in previous commit to log errors like the C pl011 device does.
--- rust/hw/char/pl011/src/device.rs | 37 +++++++++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 6 deletions(-)
rust/hw/char/pl011/src/device.rs +31 -6
@@ -9,6 +9,7 @@use qemu_api::{ bindings::{self, *}, + log::*, objects::*, vmstate_clock, vmstate_fields, vmstate_int32, vmstate_subsections, vmstate_uint32, vmstate_uint32_array, vmstate_unused,
@@ -343,7 +344,14 @@ pub fn read( u64::from (self.device_id[(offset -0xfe0 ) >>2 ]) } Err(_) => { -// qemu_log_mask(LOG_GUEST_ERROR, "pl011_read: Bad offset 0x%x\n", (int)offset); +qemu_log_mask ( +LogMask ::GUEST_ERROR , + &format! ( +"pl011:{file}:{line}: Bad offset 0x{offset:x}" , + file =file! (), + line =line! (), + ), + );0 } Ok(DR) => {
@@ -389,15 +397,30 @@ pub fn read( }pub fn write (&mut self, offset:hwaddr , value:u64 ) { -// eprintln!("write offset {offset} value {value}"); use RegisterOffset ::*;let value:u32 = valueas u32 ;match RegisterOffset ::try_from (offset) {Err (_bad_offset) => { -eprintln! ("write bad offset {offset} value {value}" ); +qemu_log_mask ( +LogMask ::GUEST_ERROR , + &format! ( +"pl011:{file}:{line}: Bad write offset 0x{offset:x} of value 0x:{value:x}" , + file =file! (), + line =line! (), + ), + ); }Ok (DR ) => { -// ??? Check if transmitter is enabled. +// Check if transmitter is enabled. +if !self.control.enable_uart () { +qemu_log_mask (LogMask ::GUEST_ERROR ,"PL011 data written to disabled UART" ); + } +if !self.control.enable_transmit () { +qemu_log_mask ( +LogMask ::GUEST_ERROR , +"PL011 data written to disabled TX UART" , + ); + }let ch:u8 = valueas u8 ;// XXX this blocks entire thread. Rewrite to use // qemu_chr_fe_write and background I/O callbacks
@@ -474,8 +497,10 @@ pub fn write(&mut self, offset: hwaddr, value: u64) { Ok(DMACR) => { self.dmacr = value;if value &3 >0 { -// qemu_log_mask(LOG_UNIMP, "pl011: DMA not implemented\n"); -eprintln! ("pl011: DMA not implemented" ); +qemu_log_mask ( +LogMask ::UNIMPLEMENTED , +"pl011: DMA functionality is not implemented" , + ); } } }
Signature · 1 line
2.45.2
Quoted 3 lines · Manos Pitsidianakis
Hello everyone, the pathological corrosion of QEMU code continues. This series expands the device model harness work performed in the initial Rust work from the previous month. In particular:
Wow, there's a lot of stuff here!
The very good news is that it's basically all the code that is needed to get CI running, after which we can start with the fun stuff. At the same time, "the fun stuff" is also the one that risks introducing technical debt, so we need to switch to quality-over-quantity mode and have a serious design discussion about it. I'll do that later as a reply to the patches.
Quoted 5 lines
Code and functionality duplication is not fun, and pl011 was mostly done as a proof of concept for a Rust device because of its small complexity. As of this moment we have not decided on a policy for how to handle these things and it is not in **scope for this patch series anyway**.
That's fine.
Looking at the currently posted series, it seems that we have three main themes:
1) small scale cleanups: duplicated and useless code, improved testing. These are in https://lore.kernel.org/qemu-devel/[email protected]/T/ and they have been reviewed already. But these two:
Quoted 2 lines
Revert "rust: add PL011 device model"
rust: add PL011 device model
... should definitely be moved on top to clean up the authorship in "git blame" and other similar tools. Sorry about that.
2) allow using older rustc/bindgen, extend CI to cover it. This is https://lore.kernel.org/qemu-devel/[email protected]/T/ which still needs review. These five:
Quoted 5 lines
rust: add support for migration in device models
rust/pl011: moveCLK_NAMEstatic to function scoperust/pl011: addTYPE_PL011_LUMINARYdevicerust/pl011: remove commented out C coderust/pl011: Use correct masks for IBRD and FBRD
(minus the usage of #[derive()] should be included in that series, so that qtests pass. It's not a huge amount of work and I can extract it, of course with proper attribution/authorship.
The rest are future work:
Quoted 1 line
rust/qemu-api-macros: introduce Device proc macro
This is useful as a starting point but it has the limit of being very device-specific. This is of course okay with properties and vmstate, but in my opinion the implementation of class_init should be as generic as possible, and not too specialized for methods in Object or Device.
As I said above, we first need to agree on the design.
Quoted 1 line
rust/pl011: move pub callback decl to local scope
This depends a lot on how we go implementing bindings to chardev. For example if the callbacks turn out to be a trait, it would have to be undone. Possibly the C callback wrappers would move to rust/qemu-api/chardev. For now I'd leave it aside.
Quoted 2 lines
rust/qemu-api: add log module
rust/pl011: log guest/unimp errors
This also needs design discussion. Do we want the API to be the same as C, i.e. keep the qemu_* prefix? Do we want wrapper macros that include the format!() call?
You also have "pub enum LogMask" to work around the fact that log masks are preprocessor macros. Is that okay, or do we want to modify C code to make the bindings nicer? I for example would prefer the latter and then declaring LogMask as a bitfield in bindgen.
Thanks,
Paolo
Quoted 30 lines
rust/wrapper.h | 1 + rust/hw/char/pl011/src/device.rs | 419 +++++++++++++++++--------- rust/hw/char/pl011/src/device_class.rs | 70 ----- rust/hw/char/pl011/src/lib.rs | 2 +- rust/qemu-api-macros/src/device.rs | 370 +++++++++++++++++++++++ rust/qemu-api-macros/src/lib.rs | 46 +-- rust/qemu-api-macros/src/object.rs | 107 +++++++ rust/qemu-api-macros/src/symbols.rs | 57 ++++ rust/qemu-api-macros/src/utilities.rs | 152 ++++++++++ rust/qemu-api-macros/src/vmstate.rs | 113 +++++++ rust/qemu-api/meson.build | 5 +- rust/qemu-api/src/definitions.rs | 97 ------ rust/qemu-api/src/device_class.rs | 128 -------- rust/qemu-api/src/lib.rs | 10 +- rust/qemu-api/src/log.rs | 140 +++++++++ rust/qemu-api/src/objects.rs | 90 ++++++ rust/qemu-api/src/tests.rs | 49 --- rust/qemu-api/src/vmstate.rs | 403 +++++++++++++++++++++++++ subprojects/packagefiles/syn-2-rs/meson.build | 1 + 19 files changed, 1726 insertions(+), 534 deletions(-)---
base-commit:55522f72149fbf95ee3b057f1419da0cad46d0dd
change-id: 20241024-rust-round-2-69fa10c9a0c9--
γαῖα πυρί μιχθήτω
Hi Paolo,
Please reply with review comments underneath individual patches, this is hard to follow and I might miss some points.
Quoted 31 lines · Paolo Bonzini
Quoted 3 lines · Manos Pitsidianakis
Hello everyone, the pathological corrosion of QEMU code continues. This series expands the device model harness work performed in the initial Rust work from the previous month. In particular:
Wow, there's a lot of stuff here!
The very good news is that it's basically all the code that is needed to get CI running, after which we can start with the fun stuff. At the same time, "the fun stuff" is also the one that risks introducing technical debt, so we need to switch to quality-over-quantity mode and have a serious design discussion about it. I'll do that later as a reply to the patches.
Quoted 5 lines
Code and functionality duplication is not fun, and pl011 was mostly done as a proof of concept for a Rust device because of its small complexity. As of this moment we have not decided on a policy for how to handle these things and it is not in **scope for this patch series anyway**.
That's fine.
Looking at the currently posted series, it seems that we have three main themes:
1) small scale cleanups: duplicated and useless code, improved testing. These are in
https://lore.kernel.org/qemu-devel/[email protected]/T/
and they have been reviewed already. But these two:
Quoted 5 lines
Quoted 2 lines
Revert "rust: add PL011 device model"
rust: add PL011 device model... should definitely be moved on top to clean up the authorship in "git blame" and other similar tools. Sorry about that.
I will send them on a separate series and merge them from my tree when reviewed.
Quoted 11 lines
2) allow using older rustc/bindgen, extend CI to cover it. This is
https://lore.kernel.org/qemu-devel/[email protected]/T/
which still needs review. These five:Quoted 5 lines
rust: add support for migration in device models
rust/pl011: moveCLK_NAMEstatic to function scoperust/pl011: addTYPE_PL011_LUMINARYdevicerust/pl011: remove commented out C coderust/pl011: Use correct masks for IBRD and FBRD
Quoted 3 lines
(minus the usage of #[derive()] should be included in that series, so that qtests pass. It's not a huge amount of work and I can extract it, of course with proper attribution/authorship.
These are independent from CI; i.e. you can merge your CI patches after those.
Quoted 11 lines
The rest are future work:
Quoted 1 line
rust/qemu-api-macros: introduce Device proc macroThis is useful as a starting point but it has the limit of being very device-specific. This is of course okay with properties and vmstate, but in my opinion the implementation of
class_initshould be as generic as possible, and not too specialized for methods in Object or Device.As I said above, we first need to agree on the design.
Post your review under the patches please,
Quoted 7 lines
Quoted 2 lines
rust/pl011: move pub callback decl to local scopeThis depends a lot on how we go implementing bindings to chardev. For example if the callbacks turn out to be a trait, it would have to be undone. Possibly the C callback wrappers would move to
rust/qemu-api/chardev. For now I'd leave it aside.
This patch moves the callbacks scope from public to inside the function, no functional change related. It doesn't change or have anything to do with chardev interfaces
Quoted 7 lines
Quoted 3 lines
rust/qemu-api: add log module
rust/pl011: log guest/unimp errorsThis also needs design discussion. Do we want the API to be the same as C, i.e. keep the qemu_* prefix? Do we want wrapper macros that include the format!() call?
I'm guessing you did not see the patch messages, which cover these points. Post your review under the patches please,
Quoted 5 lines
You also have "pub enum LogMask" to work around the fact that log masks are preprocessor macros. Is that okay, or do we want to modify C code to make the bindings nicer? I for example would prefer the latter and then declaring LogMask as a bitfield in bindgen.
A bindgen type is definitely preferred but for a Rust idiomatic interface a wrapper type is a UX improvement (CPU_LOG_PCALL? LOG_GUEST_ERROR? We can use friendlier symbols in the LogMask variants for that)
Thanks, Manos
Quoted 36 lines
Thanks,
Paolo
Quoted 30 lines
rust/wrapper.h | 1 + rust/hw/char/pl011/src/device.rs | 419 +++++++++++++++++--------- rust/hw/char/pl011/src/device_class.rs | 70 ----- rust/hw/char/pl011/src/lib.rs | 2 +- rust/qemu-api-macros/src/device.rs | 370 +++++++++++++++++++++++ rust/qemu-api-macros/src/lib.rs | 46 +-- rust/qemu-api-macros/src/object.rs | 107 +++++++ rust/qemu-api-macros/src/symbols.rs | 57 ++++ rust/qemu-api-macros/src/utilities.rs | 152 ++++++++++ rust/qemu-api-macros/src/vmstate.rs | 113 +++++++ rust/qemu-api/meson.build | 5 +- rust/qemu-api/src/definitions.rs | 97 ------ rust/qemu-api/src/device_class.rs | 128 -------- rust/qemu-api/src/lib.rs | 10 +- rust/qemu-api/src/log.rs | 140 +++++++++ rust/qemu-api/src/objects.rs | 90 ++++++ rust/qemu-api/src/tests.rs | 49 --- rust/qemu-api/src/vmstate.rs | 403 +++++++++++++++++++++++++ subprojects/packagefiles/syn-2-rs/meson.build | 1 + 19 files changed, 1726 insertions(+), 534 deletions(-)---
base-commit:55522f72149fbf95ee3b057f1419da0cad46d0dd
change-id: 20241024-rust-round-2-69fa10c9a0c9--
γαῖα πυρί μιχθήτω
Quoted 2 lines · Manos Pitsidianakis
Please reply with review comments underneath individual patches, this is hard to follow and I might miss some points.
Will do.
Quoted 7 lines
Quoted 5 lines
Quoted 2 lines
Revert "rust: add PL011 device model"
rust: add PL011 device model... should definitely be moved on top to clean up the authorship in "git blame" and other similar tools. Sorry about that.
I will send them on a separate series and merge them from my tree when reviewed.
Those are trivial to review, just "git diff HEAD^^". No need to separate them into a new submission.
Quoted 11 lines
Quoted 9 lines
Quoted 5 lines
rust: add support for migration in device models
rust/pl011: moveCLK_NAMEstatic to function scoperust/pl011: addTYPE_PL011_LUMINARYdevicerust/pl011: remove commented out C coderust/pl011: Use correct masks for IBRD and FBRD(minus the usage of #[derive()] should be included in that series, so that qtests pass. It's not a huge amount of work and I can extract it, of course with proper attribution/authorship.
These are independent from CI; i.e. you can merge your CI patches after those.
That's what I did: I put them at the beginning of the series of pending patches, so they _are_ indeed merged after the CI patches. The only issue here is that patch 4 ("rust: add support for migration in device models") was dependent on the Device proc macro, but that was easy enough to extract.
Quoted 8 lines
Quoted 6 lines
The rest are future work:
Quoted 1 line
rust/qemu-api-macros: introduce Device proc macroAs I said above, we first need to agree on the design.
Post your review under the patches please,
Yep.
Quoted 10 lines
Quoted 6 lines
Quoted 1 line
rust/pl011: move pub callback decl to local scopeThis depends a lot on how we go implementing bindings to chardev. For example if the callbacks turn out to be a trait, it would have to be undone. Possibly the C callback wrappers would move to
rust/qemu-api/chardev. For now I'd leave it aside.This patch moves the callbacks scope from public to inside the function, no functional change related. It doesn't change or have anything to do with chardev interfaces
I understand. My point is that the callbacks you move (pl011_can_receive, pl011_receive, pl011_event) in the end will belong into the C<->Rust chardev bindings. A patch to remove "pub" would have basically the same benefit without the churn in indentation.
Quoted 9 lines
Quoted 6 lines
Quoted 2 lines
rust/qemu-api: add log module
rust/pl011: log guest/unimp errorsThis also needs design discussion. Do we want the API to be the same as C, i.e. keep the qemu_* prefix? Do we want wrapper macros that include the format!() call?
I'm guessing you did not see the patch messages, which cover these points. Post your review under the patches please,
I will but for now I'll say that the commit messages do not address the questions I'm asking above.
More in general, we need to establish conventions on what the Rust APIs look like (about qemu_* prefixes, for example). Personally I prefer to have APIs that, while easy enough to connect to the C ones, are idiomatic. But you can post these two patches separately and we can discuss it there.
Quoted 9 lines
Quoted 4 lines
You also have "pub enum LogMask" to work around the fact that log masks are preprocessor macros. Is that okay, or do we want to modify C code to make the bindings nicer? I for example would prefer the latter and then declaring LogMask as a bitfield in bindgen.
A bindgen type is definitely preferred but for a Rust idiomatic interface a wrapper type is a UX improvement (
CPU_LOG_PCALL?LOG_GUEST_ERROR? We can use friendlier symbols in the LogMask variants for that)
What I'm saying is that these are discussions where we need to reach an agreement on, and document the choices.
Paolo