diff --git a/hw/char/Kconfig b/hw/char/Kconfig index 020c0a84bb..1262084bd0 100644 --- a/hw/char/Kconfig +++ b/hw/char/Kconfig @@ -95,3 +95,8 @@ config IP_OCTAL_232 bool default y depends on IPACK + +config DIALOG_UART + bool + depends on HAVE_RUST + select X_DIALOG_UART_RUST diff --git a/hw/cr16c/Kconfig b/hw/cr16c/Kconfig index 0e38a02a76..8118288ae1 100644 --- a/hw/cr16c/Kconfig +++ b/hw/cr16c/Kconfig @@ -1,6 +1,8 @@ config VIRT bool select UNIMP + select DIALOG_UART config DE410 bool + select DIALOG_UART diff --git a/hw/cr16c/meson.build b/hw/cr16c/meson.build index 43bb8b3e6f..e956fa0326 100644 --- a/hw/cr16c/meson.build +++ b/hw/cr16c/meson.build @@ -1,6 +1,7 @@ cr16c_ss = ss.source_set() cr16c_ss.add(files('virt.c')) cr16c_ss.add(files('sc14461.c')) +cr16c_ss.add(files('sc14480.c')) cr16c_ss.add(files('de410.c')) cr16c_ss.add(files('boot.c')) hw_arch += {'cr16c': cr16c_ss} diff --git a/hw/cr16c/sc14480.c b/hw/cr16c/sc14480.c new file mode 100644 index 0000000000..ef0dc4f08e --- /dev/null +++ b/hw/cr16c/sc14480.c @@ -0,0 +1,67 @@ +#include "sc14480.h" +#include "cpu-qom.h" +#include "system/address-spaces.h" +#include "hw/core/cpu.h" +#include "hw/cr16c/boot.h" +#include "qapi/error.h" +#include "qemu/datadir.h" +#include "qemu/units.h" + + +static void sc14480_realize(DeviceState* dev, Error** errp) +{ + SC14480McuState* s = SC14480_MCU(dev); + + object_initialize_child(OBJECT(dev), "cpu", &s->cpu, TYPE_CR16C_CPU); + object_property_set_bool(OBJECT(&s->cpu), "realized", true, &error_abort); + + memory_region_init_ram(&s->non_shared_ram_or_icache, OBJECT(dev), "non_shared_ram_or_icache", 24*KiB, &error_fatal); + memory_region_init_ram(&s->non_shared_ram_or_dcache, OBJECT(dev), "non_shared_ram_or_dcache", 8*KiB, &error_fatal); + memory_region_init_ram(&s->shared_int_ram, OBJECT(dev), "shared_int_ram", 64*KiB, &error_fatal); + memory_region_init_rom(&s->boot_rom, OBJECT(dev), "boot_rom", 2*KiB, &error_fatal); + memory_region_add_subregion(get_system_memory(), 0x00000, &s->non_shared_ram_or_icache); + memory_region_add_subregion(get_system_memory(), 0x08000, &s->non_shared_ram_or_dcache); + memory_region_add_subregion(get_system_memory(), 0x10000, &s->shared_int_ram); + memory_region_add_subregion(get_system_memory(), 0xFEF00, &s->boot_rom); + + char* bios_path = qemu_find_file(QEMU_FILE_TYPE_BIOS, "sc14480-bios.img"); + if (!cr16c_load_firmware(&s->cpu, &s->boot_rom, bios_path)) { + exit(1); + } +} + +static void sc14480_reset_hold(Object *obj, ResetType type) { + SC14480McuClass* mcu_class = SC14480_MCU_GET_CLASS(obj); + SC14480McuState* mcu_state = SC14480_MCU(obj); + CR16CCPU* cpu = &mcu_state->cpu; + CPUState* cpu_state = CPU(cpu); + + if (mcu_class->parent_phases.hold) { + mcu_class->parent_phases.hold(obj, type); + } + + cpu_reset(cpu_state); + cpu_set_pc(cpu_state, 0xFEF00); +} + +static void sc14480_class_init(ObjectClass* oc, const void* data) +{ + DeviceClass* dc = DEVICE_CLASS(oc); + SC14480McuClass* sc14480 = SC14480_MCU_CLASS(oc); + ResettableClass *rc = RESETTABLE_CLASS(oc); + + resettable_class_set_parent_phases(rc, NULL, sc14480_reset_hold, NULL, &sc14480->parent_phases); + + dc->realize = sc14480_realize; +} + +static const TypeInfo sc14480_mcu_types[] = { + { + .name = TYPE_SC14480_MCU, + .parent = TYPE_SYS_BUS_DEVICE, + .instance_size = sizeof(SC14480McuState), + .class_size = sizeof(SC14480McuClass), + .class_init = sc14480_class_init, + }, +}; +DEFINE_TYPES(sc14480_mcu_types) diff --git a/hw/cr16c/sc14480.h b/hw/cr16c/sc14480.h new file mode 100644 index 0000000000..54fad26104 --- /dev/null +++ b/hw/cr16c/sc14480.h @@ -0,0 +1,30 @@ +#ifndef HW_SC14480_H +#define HW_SC14480_H + +#include "cpu.h" +#include "hw/sysbus.h" + +#define TYPE_SC14480_MCU "SC14480" + +typedef struct SC14480McuState SC14480McuState; +DECLARE_INSTANCE_CHECKER(SC14480McuState, SC14480_MCU, TYPE_SC14480_MCU) + +struct SC14480McuState { + SysBusDevice parent_obj; + + CR16CCPU cpu; + + MemoryRegion non_shared_ram_or_icache; + MemoryRegion non_shared_ram_or_dcache; + MemoryRegion shared_int_ram; + MemoryRegion boot_rom; +}; + +typedef struct SC14480McuClass { + SysBusDeviceClass parent_class; + + ResettablePhases parent_phases; +} SC14480McuClass; +DECLARE_CLASS_CHECKERS(SC14480McuClass, SC14480_MCU, TYPE_SC14480_MCU) + +#endif /* HW_SC14480_H */ diff --git a/hw/cr16c/virt.c b/hw/cr16c/virt.c index 1a05ba0956..4d3a375876 100644 --- a/hw/cr16c/virt.c +++ b/hw/cr16c/virt.c @@ -6,6 +6,7 @@ #include "qapi/error.h" #include "qemu/units.h" #include "qom/object.h" +#include "system/system.h" typedef struct VirtMachineState { MachineState parent_obj; @@ -22,8 +23,36 @@ typedef struct VirtMachineClass { DECLARE_OBJ_CHECKERS(VirtMachineState, VirtMachineClass, VIRT_MACHINE, TYPE_VIRT_MACHINE) +// SC14480 vectors, all with exception priority 4 +enum { + // lowest + ACCESS12_INT = 16, + KEYB_INT = 17, + DMA1_INT = 17, // secondary function with DINT + // RESERVED_INT = 18, + CT_CLASSD_INT = 19, + UART_RI_INT = 20, + DMA2_INT = 20, // secondary function with DINT + UART_TI_INT = 21, + DMA3_INT = 21, // secondary function with DINT + SPI_INT = 22, + DMA0_INT = 22, // secondary function with DINT + TIM0_INT = 23, + TIM1_INT = 24, + CLK100_INT = 25, + DIP_INT = 26, + AD_INT = 27, + SPI2_INT = 28, + DSP_INT = 29, + // RESERVED = 30, + // highest +}; +// TODO map these from qemu irqs somewhere + +DeviceState *sc144uart_create(hwaddr addr, qemu_irq irq, Chardev *chr); static void virt_init(MachineState* machine) { + VirtMachineState* m_state = VIRT_MACHINE(machine); object_initialize_child(OBJECT(machine), "cpu", &m_state->cpu, TYPE_CR16C_CPU); @@ -32,7 +61,14 @@ static void virt_init(MachineState* machine) memory_region_init_ram(&m_state->flash, NULL, "flash", 16*MiB - 64*KiB, &error_fatal); memory_region_add_subregion(get_system_memory(), 0, &m_state->flash); - create_unimplemented_device("mmio", 0xFF0000, 0xFFBFFF - 0xFF0000); + create_unimplemented_device("mmio", 0xFF0000, 0xFFFBFF - 0xFF0000); + + qemu_irq pic[10]; // TODO pick a reasonable value and name it + for (int n = 0; n < 10; n++) { + pic[n] = qdev_get_gpio_in(&m_state->cpu.parent_obj.parent_obj, n); + } + (void)pic; + sc144uart_create(0xFF4900, pic[0], NULL);//serial_hd(0)); //memory_region_init_alias(&m_state->mmio_alias, NULL, "mmio_alias", &m_state->flash, 0xF0000, 0xFFFFF - 0xF0000); create_unimplemented_device("icu", 0xFFFC00, 0xFFFFFF - 0xFFFC00); // interrupt controller unit diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 0c1df625df..7efd85822d 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -1,6 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "anyhow" @@ -91,6 +91,25 @@ dependencies = [ "qemu_macros", ] +[[package]] +name = "dialog_uart" +version = "0.1.0" +dependencies = [ + "bilge", + "bilge-impl", + "bits", + "bql", + "chardev", + "common", + "glib-sys", + "hwcore", + "migration", + "qom", + "system", + "trace", + "util", +] + [[package]] name = "either" version = "1.12.0" diff --git a/rust/Cargo.toml b/rust/Cargo.toml index ace0baf9bd..bb0133f641 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -2,6 +2,7 @@ resolver = "2" members = [ "hw/char/pl011", + "hw/char/dialog_uart", "hw/timer/hpet", "tests", ] diff --git a/rust/hw/char/Kconfig b/rust/hw/char/Kconfig index 5fe800c480..15de52dc9b 100644 --- a/rust/hw/char/Kconfig +++ b/rust/hw/char/Kconfig @@ -1,2 +1,5 @@ config X_PL011_RUST bool + +config X_DIALOG_UART_RUST + bool diff --git a/rust/hw/char/dialog_uart/Cargo.toml b/rust/hw/char/dialog_uart/Cargo.toml new file mode 100644 index 0000000000..282ce246b0 --- /dev/null +++ b/rust/hw/char/dialog_uart/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "dialog_uart" +version = "0.1.0" +authors = ["fridtjof ", "Manos Pitsidianakis "] +description = "dialog_uart device model for QEMU" +resolver = "2" +publish = false + +edition.workspace = true +homepage.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[dependencies] +glib-sys.workspace = true +bilge = { version = "0.2.0" } +bilge-impl = { version = "0.2.0" } +bits = { path = "../../../bits" } +common = { path = "../../../common" } +util = { path = "../../../util" } +bql = { path = "../../../bql" } +migration = { path = "../../../migration" } +qom = { path = "../../../qom" } +chardev = { path = "../../../chardev" } +system = { path = "../../../system" } +hwcore = { path = "../../../hw/core" } +trace = { path = "../../../trace" } + +[lints] +workspace = true diff --git a/rust/hw/char/dialog_uart/build.rs b/rust/hw/char/dialog_uart/build.rs new file mode 120000 index 0000000000..5f5060db35 --- /dev/null +++ b/rust/hw/char/dialog_uart/build.rs @@ -0,0 +1 @@ +../../../util/build.rs \ No newline at end of file diff --git a/rust/hw/char/dialog_uart/meson.build b/rust/hw/char/dialog_uart/meson.build new file mode 100644 index 0000000000..1e2aef20ac --- /dev/null +++ b/rust/hw/char/dialog_uart/meson.build @@ -0,0 +1,51 @@ +# TODO: Remove this comment when the clang/libclang mismatch issue is solved. +# +# Rust bindings generation with `bindgen` might fail in some cases where the +# detected `libclang` does not match the expected `clang` version/target. In +# this case you must pass the path to `clang` and `libclang` to your build +# command invocation using the environment variables CLANG_PATH and +# LIBCLANG_PATH +_libdialog_uart_bindings_inc_rs = rust.bindgen( + input: 'wrapper.h', + dependencies: common_ss.all_dependencies(), + output: 'bindings.inc.rs', + include_directories: bindings_incdir, + bindgen_version: ['>=0.60.0'], + args: bindgen_args_common, + c_args: bindgen_c_args, +) + +_libdialog_uart_rs = static_library( + 'dialog_uart', + structured_sources( + [ + 'src/lib.rs', + 'src/bindings.rs', + 'src/device.rs', + 'src/registers.rs', + ], + {'.' : _libdialog_uart_bindings_inc_rs}, + ), + override_options: ['rust_std=2021', 'build.rust_std=2021'], + rust_abi: 'rust', + dependencies: [ + bilge_rs, + bilge_impl_rs, + bits_rs, + common_rs, + glib_sys_rs, + util_rs, + migration_rs, + bql_rs, + qom_rs, + chardev_rs, + system_rs, + hwcore_rs, + trace_rs + ], +) + +rust_devices_ss.add(when: 'CONFIG_X_DIALOG_UART_RUST', if_true: [declare_dependency( + link_whole: [_libdialog_uart_rs], + variables: {'crate': 'dialog_uart'}, +)]) diff --git a/rust/hw/char/dialog_uart/src/bindings.rs b/rust/hw/char/dialog_uart/src/bindings.rs new file mode 100644 index 0000000000..654be9185b --- /dev/null +++ b/rust/hw/char/dialog_uart/src/bindings.rs @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +#![allow( + dead_code, + improper_ctypes_definitions, + improper_ctypes, + non_camel_case_types, + non_snake_case, + non_upper_case_globals, + unnecessary_transmutes, + unsafe_op_in_unsafe_fn, + clippy::pedantic, + clippy::restriction, + clippy::style, + clippy::missing_const_for_fn, + clippy::ptr_offset_with_cast, + clippy::useless_transmute, + clippy::missing_safety_doc, + clippy::too_many_arguments +)] + +//! `bindgen`-generated declarations. + +use glib_sys::{ + gboolean, guint, GArray, GByteArray, GHashTable, GHashTableIter, GIOCondition, GList, + GMainContext, GPollFD, GPtrArray, GSList, GSource, GSourceFunc, GString, +}; + +#[cfg(MESON)] +include!("bindings.inc.rs"); + +#[cfg(not(MESON))] +include!(concat!(env!("OUT_DIR"), "/bindings.inc.rs")); diff --git a/rust/hw/char/dialog_uart/src/device.rs b/rust/hw/char/dialog_uart/src/device.rs new file mode 100644 index 0000000000..c3c0c89f75 --- /dev/null +++ b/rust/hw/char/dialog_uart/src/device.rs @@ -0,0 +1,505 @@ +// Copyright 2024, Linaro Limited +// Copyright 2026, fridtjof +// Author(s): Manos Pitsidianakis , fridtjof +// SPDX-License-Identifier: GPL-2.0-or-later + +use std::{ffi::CStr}; + +use bql::BqlRefCell; +use chardev::{CharFrontend, Chardev, Event}; +use common::uninit_field_mut; +use hwcore::{ + Clock, ClockEvent, DeviceImpl, DeviceMethods, DeviceState, IRQState, InterruptSource, + ResetType, ResettablePhasesImpl, SysBusDevice, SysBusDeviceImpl, SysBusDeviceMethods, +}; +use migration::{ + impl_vmstate_forward, impl_vmstate_struct, vmstate_fields, vmstate_of, + vmstate_subsections, vmstate_unused, VMStateDescription, VMStateDescriptionBuilder, +}; +use qom::{prelude::*, ObjectImpl, Owned, ParentField, ParentInit}; +use system::{hwaddr, MemoryRegion, MemoryRegionOps, MemoryRegionOpsBuilder}; +use util::{log::Log, log_mask_ln, ResultExt}; + +use crate::registers::{self, Interrupt, RegisterOffset}; + +// TODO: You must disable the UART before any of the control registers are +// reprogrammed. When the UART is disabled in the middle of transmission or +// reception, it completes the current character before stopping + +/// QEMU sourced constant. +pub const PL011_FIFO_DEPTH: u32 = 16; + +// FIFOs use 32-bit indices instead of usize, for compatibility with +// the migration stream produced by the C version of this device. +#[repr(transparent)] +#[derive(Debug, Default)] +pub struct Fifo([registers::Data; PL011_FIFO_DEPTH as usize]); +impl_vmstate_forward!(Fifo); + +impl Fifo { + const fn len(&self) -> u32 { + self.0.len() as u32 + } +} + +impl std::ops::IndexMut for Fifo { + fn index_mut(&mut self, idx: u32) -> &mut Self::Output { + &mut self.0[idx as usize] + } +} + +impl std::ops::Index for Fifo { + type Output = registers::Data; + + fn index(&self, idx: u32) -> &Self::Output { + &self.0[idx as usize] + } +} + +#[repr(C)] +#[derive(Debug, Default)] +pub struct SC144UartRegisters { + #[doc(alias = "ctrl")] + pub control: registers::Control, + pub dmacr: u32, + pub int_enabled: Interrupt, + pub int_level: Interrupt, + pub read_fifo: Fifo, + pub ilpr: u32, + pub ifl: u32, + pub read_pos: u32, + pub read_count: u32, + pub read_trigger: u32, +} + +#[repr(C)] +#[derive(qom::Object, hwcore::Device)] +/// PL011 Device Model in QEMU +pub struct SC144UartState { + pub parent_obj: ParentField, + pub iomem: MemoryRegion, + #[doc(alias = "chr")] + #[property(rename = "chardev")] + pub char_backend: CharFrontend, + pub regs: BqlRefCell, + /// QEMU interrupts + /// + /// ```text + /// * sysbus MMIO region 0: device registers + /// * sysbus IRQ 0: `UARTINTR` (combined interrupt line) + /// * sysbus IRQ 1: `UARTRXINTR` (receive FIFO interrupt line) + /// * sysbus IRQ 2: `UARTTXINTR` (transmit FIFO interrupt line) + /// * sysbus IRQ 3: `UARTRTINTR` (receive timeout interrupt line) + /// * sysbus IRQ 4: `UARTMSINTR` (momem status interrupt line) + /// * sysbus IRQ 5: `UARTEINTR` (error interrupt line) + /// ``` + #[doc(alias = "irq")] + pub interrupts: [InterruptSource; IRQMASK.len()], + #[doc(alias = "clk")] + pub clock: Owned, + #[doc(alias = "migrate_clk")] + #[property(rename = "migrate-clk", default = true)] + pub migrate_clock: bool, +} + +qom_isa!(SC144UartState : SysBusDevice, DeviceState, Object); + +#[repr(C)] +pub struct SC144UartClass { + parent_class: ::Class, +} + +trait PL011Impl: SysBusDeviceImpl + IsA {} + +impl SC144UartClass { + fn class_init(&mut self) { + self.parent_class.class_init::(); + } +} + +unsafe impl ObjectType for SC144UartState { + type Class = SC144UartClass; + const TYPE_NAME: &'static CStr = crate::TYPE_SC144UART; +} + +impl PL011Impl for SC144UartState {} + +impl ObjectImpl for SC144UartState { + type ParentType = SysBusDevice; + + const INSTANCE_INIT: Option)> = Some(Self::init); + const INSTANCE_POST_INIT: Option = Some(Self::post_init); + const CLASS_INIT: fn(&mut Self::Class) = Self::Class::class_init::; +} + +impl DeviceImpl for SC144UartState { + const VMSTATE: Option> = Some(VMSTATE_SC144UART); + const REALIZE: Option util::Result<()>> = Some(Self::realize); +} + +impl ResettablePhasesImpl for SC144UartState { + const HOLD: Option = Some(Self::reset_hold); +} + +impl SysBusDeviceImpl for SC144UartState {} + +impl SC144UartRegisters { + pub(self) fn read(&mut self, offset: RegisterOffset) -> (bool, u16) { + use RegisterOffset::*; + + let mut update_irq = false; + let result = match offset { + CTRL => u16::from(self.control).into(), + RXTX => self.read_data_register(&mut update_irq), + CLEAR_TX_INT | CLEAR_RX_INT => 0, + ERROR => 0, // TODO par_status, dma_parity_error + }; + (update_irq, result) + } + + pub(self) fn write( + &mut self, + offset: RegisterOffset, + value: u16, + _char_frontend: &CharFrontend, + ) -> bool { + eprintln!("write offset {offset:?} value {value}"); + use RegisterOffset::*; + match offset { + RXTX => return self.write_data_register(value), + CTRL => { + // ??? Need to implement the enable bit. + self.control = value.into(); + }, + CLEAR_TX_INT | CLEAR_RX_INT => todo!(), + ERROR => todo!() + } + false + } + + fn read_data_register(&mut self, update: &mut bool) -> u16 { + let c = self.read_fifo[self.read_pos]; + + if self.read_count > 0 { + self.read_count -= 1; + self.read_pos = (self.read_pos + 1) & (self.fifo_depth() - 1); + } + if self.read_count == 0 { + } + if self.read_count + 1 == self.read_trigger { + self.int_level &= !Interrupt::RX; + } + *update = true; + u16::from(c) + } + + fn write_data_register(&mut self, value: u16) -> bool { + if !self.control.enable_transmit() { + log_mask_ln!(Log::GuestError, " SC144 UART data written to disabled TX UART"); + } + // interrupts always checked + let _ = false && self.fifo_rx_put(value.into()); + self.int_level |= Interrupt::TX; + true + } + + pub fn reset(&mut self) { + self.dmacr = 0; + self.int_enabled = 0.into(); + self.int_level = 0.into(); + self.ilpr = 0; + self.read_trigger = 1; + self.ifl = 0x12; + self.control.reset(); + self.reset_rx_fifo(); + self.reset_tx_fifo(); + } + + pub fn reset_rx_fifo(&mut self) { + self.read_count = 0; + self.read_pos = 0; + } + + pub fn reset_tx_fifo(&mut self) {} + + #[inline] + pub fn fifo_enabled(&self) -> bool { + false + } + + #[inline] + pub fn fifo_depth(&self) -> u32 { + 1 + } + + #[must_use] + pub fn fifo_rx_put(&mut self, value: registers::Data) -> bool { + let depth = self.fifo_depth(); + assert!(depth > 0); + let slot = (self.read_pos + self.read_count) & (depth - 1); + self.read_fifo[slot] = value; + self.read_count += 1; + if self.read_count == depth {} + + if self.read_count == self.read_trigger { + self.int_level |= Interrupt::RX; + return true; + } + false + } + + pub fn post_load(&mut self) -> Result<(), migration::InvalidError> { + /* Sanity-check input state */ + if self.read_pos >= self.read_fifo.len() || self.read_count > self.read_fifo.len() { + return Err(migration::InvalidError); + } + + 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; + } + + Ok(()) + } +} + +impl SC144UartState { + /// Initializes a pre-allocated, uninitialized instance of `SC144UartState`. + /// + /// # Safety + /// + /// `self` must point to a correctly sized and aligned location for the + /// `SC144UartState` type. It must not be called more than once on the same + /// location/instance. All its fields are expected to hold uninitialized + /// values with the sole exception of `parent_obj`. + unsafe fn init(mut this: ParentInit) { + static PL011_OPS: MemoryRegionOps = MemoryRegionOpsBuilder::::new() + .read(&SC144UartState::read) + .write(&SC144UartState::write) + .native_endian() + .impl_sizes(2, 2) + .build(); + + // SAFETY: this and this.iomem are guaranteed to be valid at this point + MemoryRegion::init_io( + &mut uninit_field_mut!(*this, iomem), + &PL011_OPS, + "sc144uart", + 10, + ); + + uninit_field_mut!(*this, regs).write(Default::default()); + + let clock = DeviceState::init_clock_in( + &mut this, + "clk", + &Self::clock_update, + ClockEvent::ClockUpdate, + ); + uninit_field_mut!(*this, clock).write(clock); + } + + const fn clock_update(&self, _event: ClockEvent) { + /* pl011_trace_baudrate_change(s); */ + } + + pub fn clock_needed(&self) -> bool { + self.migrate_clock + } + + fn post_init(&self) { + self.init_mmio(&self.iomem); + for irq in self.interrupts.iter() { + self.init_irq(irq); + } + } + + fn read(&self, offset: hwaddr, _size: u32) -> u64 { + match RegisterOffset::try_from(offset) { + Err(_) => { + log_mask_ln!(Log::GuestError, "SC144UartState::read: Bad offset {offset}"); + 0 + } + Ok(field) => { + let (update_irq, result) = self.regs.borrow_mut().read(field); + if update_irq { + self.update(); + self.char_backend.accept_input(); + } + result.into() + } + } + } + + fn write(&self, offset: hwaddr, value: u64, _size: u32) { + let mut update_irq = false; + if let Ok(field) = RegisterOffset::try_from(offset) { + // qemu_chr_fe_write_all() calls into the can_receive + // callback, so handle writes before entering PL011Registers. + if field == RegisterOffset::RXTX { + // ??? Check if transmitter is enabled. + let ch: [u8; 1] = [value as u8]; + // XXX this blocks entire thread. Rewrite to use + // qemu_chr_fe_write and background I/O callbacks + let _ = self.char_backend.write_all(&ch); + } + + update_irq = self + .regs + .borrow_mut() + .write(field, value as u16, &self.char_backend); + } else { + log_mask_ln!( + Log::GuestError, + "SC144UartState::write: Bad offset {offset} value {value}" + ); + } + if update_irq { + self.update(); + } + } + + fn can_receive(&self) -> u32 { + let regs = self.regs.borrow(); + // trace_pl011_can_receive(s->lcr, s->read_count, r); + regs.fifo_depth() - regs.read_count + } + + fn receive(&self, buf: &[u8]) { + let mut regs = self.regs.borrow_mut(); + + let mut update_irq = false; + for &c in buf { + let c: u16 = c.into(); + update_irq |= regs.fifo_rx_put(c.into()); + } + + // Release the BqlRefCell before calling self.update() + drop(regs); + if update_irq { + self.update(); + } + } + + fn event(&self, _event: Event) { + let update_irq = false; + let regs = self.regs.borrow_mut(); + // Release the BqlRefCell before calling self.update() + drop(regs); + + if update_irq { + self.update() + } + } + + fn realize(&self) -> util::Result<()> { + self.char_backend + .enable_handlers(self, Self::can_receive, Self::receive, Self::event); + Ok(()) + } + + fn reset_hold(&self, _type: ResetType) { + self.regs.borrow_mut().reset(); + } + + fn update(&self) { + let regs = self.regs.borrow(); + let flags = regs.int_level & regs.int_enabled; + for (irq, i) in self.interrupts.iter().zip(IRQMASK) { + irq.set(flags.any_set(i)); + } + } + + pub fn post_load(&self, _version_id: u8) -> Result<(), migration::InvalidError> { + self.regs.borrow_mut().post_load() + } +} + +/// Which bits in the interrupt status matter for each outbound IRQ line ? +const IRQMASK: [Interrupt; 6] = [ + Interrupt::all(), + Interrupt::RX, + Interrupt::TX, + Interrupt::RT, + Interrupt::MS, + Interrupt::E, +]; + +/// # Safety +/// +/// We expect the FFI user of this function to pass a valid pointer for `chr` +/// and `irq`. +#[no_mangle] +pub unsafe extern "C" fn sc144uart_create( + addr: u64, + irq: *mut IRQState, + chr: *mut Chardev, +) -> *mut DeviceState { + // SAFETY: The callers promise that they have owned references. + // They do not gift them to sc144uart_create, so use `Owned::from`. + let irq = unsafe { Owned::::from(&*irq) }; + + let dev = SC144UartState::new(); + if !chr.is_null() { + let chr = unsafe { Owned::::from(&*chr) }; + dev.prop_set_chr("chardev", &chr); + } + dev.sysbus_realize().unwrap_fatal(); + dev.mmio_map(0, addr); + dev.connect_irq(0, &irq); + + // The pointer is kept alive by the QOM tree; drop the owned ref + dev.as_mut_ptr() +} + +/// Migration subsection for [`SC144UartState`] clock. +static VMSTATE_SC144UART_CLOCK: VMStateDescription = + VMStateDescriptionBuilder::::new() + .name(c"sc144uart/clock") + .version_id(1) + .minimum_version_id(1) + .needed(&SC144UartState::clock_needed) // needed: Some(sc144uart_clock_needed), + .fields(vmstate_fields! { + vmstate_of!(SC144UartState, clock), + }) + .build(); + +impl_vmstate_struct!( + SC144UartRegisters, + VMStateDescriptionBuilder::::new() + .name(c"sc144uart/regs") + .version_id(2) + .minimum_version_id(2) + .fields(vmstate_fields! { + vmstate_of!(SC144UartRegisters, control), + vmstate_of!(SC144UartRegisters, dmacr), + vmstate_of!(SC144UartRegisters, int_enabled), + vmstate_of!(SC144UartRegisters, int_level), + vmstate_of!(SC144UartRegisters, read_fifo), + vmstate_of!(SC144UartRegisters, ilpr), + vmstate_of!(SC144UartRegisters, ifl), + vmstate_of!(SC144UartRegisters, read_pos), + vmstate_of!(SC144UartRegisters, read_count), + vmstate_of!(SC144UartRegisters, read_trigger), + }) + .build() +); + +pub const VMSTATE_SC144UART: VMStateDescription = + VMStateDescriptionBuilder::::new() + .name(c"pl011") + .version_id(2) + .minimum_version_id(2) + .post_load(&SC144UartState::post_load) + .fields(vmstate_fields! { + vmstate_unused!(core::mem::size_of::()), + vmstate_of!(SC144UartState, regs), + }) + .subsections(vmstate_subsections! { + VMSTATE_SC144UART_CLOCK + }) + .build(); diff --git a/rust/hw/char/dialog_uart/src/lib.rs b/rust/hw/char/dialog_uart/src/lib.rs new file mode 100644 index 0000000000..58452e559d --- /dev/null +++ b/rust/hw/char/dialog_uart/src/lib.rs @@ -0,0 +1,21 @@ +// Copyright 2024, Linaro Limited +// Author(s): Manos Pitsidianakis +// SPDX-License-Identifier: GPL-2.0-or-later + +//! SC144xx UART QEMU Device Model +//! +//! This library implements a device model for the UART device +//! found in SC144xx DECT SoCs in QEMU. +//! +//! # Library crate +//! +//! See [`SC144State`](crate::device::SC144State) for the device model type and +//! the [`registers`] module for register types. + +mod device; +mod registers; +mod bindings; + +pub use device::sc144uart_create; + +pub const TYPE_SC144UART: &::std::ffi::CStr = c"sc144uart"; diff --git a/rust/hw/char/dialog_uart/src/registers.rs b/rust/hw/char/dialog_uart/src/registers.rs new file mode 100644 index 0000000000..aeadb00497 --- /dev/null +++ b/rust/hw/char/dialog_uart/src/registers.rs @@ -0,0 +1,195 @@ +// Copyright 2024, Linaro Limited +// Author(s): Manos Pitsidianakis +// SPDX-License-Identifier: GPL-2.0-or-later + +//! Device registers exposed as typed structs which are backed by arbitrary +//! integer bitmaps. [`Data`], [`Control`], [`LineControl`], etc. + +// For more detail see the PL011 Technical Reference Manual DDI0183: +// https://developer.arm.com/documentation/ddi0183/latest/ + +use bilge::prelude::*; +use bits::bits; +use migration::{impl_vmstate_bitsized, impl_vmstate_forward}; + +/*;; UART registers + +sfr = "UART_CTRL_REG", "Memory", 0xFF4900, 2, base=16 +sfr = "UART_CTRL_REG.UART_REN", "Memory", 0xFF4900, 2, base=16, bitRange=0 +sfr = "UART_CTRL_REG.UART_TEN", "Memory", 0xFF4900, 2, base=16, bitRange=1 +sfr = "UART_CTRL_REG.BAUDRATE", "Memory", 0xFF4900, 2, base=16, bitRange=2-4 +sfr = "UART_CTRL_REG.TI", "Memory", 0xFF4900, 2, base=16, bitRange=5 +sfr = "UART_CTRL_REG.RI", "Memory", 0xFF4900, 2, base=16, bitRange=6 +sfr = "UART_CTRL_REG.UART_MODE", "Memory", 0xFF4900, 2, base=16, bitRange=7 +sfr = "UART_CTRL_REG.IRDA_EN", "Memory", 0xFF4900, 2, base=16, bitRange=8 +sfr = "UART_CTRL_REG.INV_URX", "Memory", 0xFF4900, 2, base=16, bitRange=9 +sfr = "UART_CTRL_REG.INV_UTX", "Memory", 0xFF4900, 2, base=16, bitRange=10 + +sfr = "UART_ERROR_REG", "Memory", 0xFF4908, 2, base=16 +sfr = "UART_ERROR_REG.PAR_STATUS", "Memory", 0xFF4908, 2, base=16, bitRange=0 +sfr = "UART_ERROR_REG.DMA_PARITY_ERROR", "Memory", 0xFF4908, 2, base=16, bitRange=1*/ + +/// Offset of each register from the base memory address of the device. +#[doc(alias = "offset")] +#[allow(non_camel_case_types)] +#[repr(u64)] +#[derive(Debug, Eq, PartialEq, common::TryInto)] +pub enum RegisterOffset { + /// Data Register + /// + /// has a bunch of bitflags + #[doc(alias = "UART_CTRL_REG")] + CTRL = 0x000, + /// RX/TX Register + #[doc(alias = "UART_RX_TX_REG")] + RXTX = 0x002, + /// Clear TX Interrupt Register + #[doc(alias = "UART_CLEAR_TX_INT_REG")] + CLEAR_TX_INT = 0x004, + /// Clear RX Interrupt Register + #[doc(alias = "UART_CLEAR_RX_INT_REG")] + CLEAR_RX_INT = 0x006, + /// Error Register + #[doc(alias = "UART_ERROR_REG")] + ERROR = 0x008, +} + +/// Data Register, `UART_RX_TX_REG` +/// +/// The `UART_RX_TX_REG` register is the data register; +/// write for TX and read for RX. +/// It is an 8-bit register, where bits 7..0 are the data. +#[bitsize(16)] +#[derive(Clone, Copy, Default, DebugBits, FromBits)] +#[doc(alias = "UART_RX_TX_REG")] +pub struct Data { + pub data: u8, + _reserved: u8, +} +impl_vmstate_bitsized!(Data); + +/// Control Register, `UART_CTRL_REG` +/// +/// The `UART_CTRL_REG` register is the control register. It contains various +/// enable bits, and the bits to write to set the usual outbound RS232 +/// modem control signals. All bits reset to 0 except TXE and RXE. +#[bitsize(16)] +#[doc(alias = "UART_CTRL_REG")] +#[derive(Clone, Copy, DebugBits, FromBits)] +pub struct Control { + /// `UART_REN` Receive enable + pub enable_receive: bool, + /// `UART_TEN` Transmit enable + pub enable_transmit: bool, + /// `BAUDRATE` Baudrate + pub baudrate: BaudRate, + /// `TI` Transmit interrupt. Read only + pub tx_interrupt: bool, + /// `RI` Receive interrupt. Read only + pub rx_interrupt: bool, + /// `UART_MODE` + pub uart_mode: u1, + /// `IRDA_EN` enable RZI mode for IrDA. + /// QEMU does not model this. + pub enable_irda: bool, + /// `INV_URX` + pub invert_rx: bool, + /// `INV_UTX` + pub invert_tx: bool, + /// 15:11 - Reserved, do not modify, read as zero. + _reserved_zero_no_modify: u5, +} +impl_vmstate_bitsized!(Control); + +impl Control { + pub fn reset(&mut self) { + *self = 0.into(); + } +} + +impl Default for Control { + fn default() -> Self { + let mut ret: Self = 0.into(); + ret.reset(); + ret + } +} + +#[bitsize(3)] +#[derive(Clone, Copy, Debug, Eq, FromBits, PartialEq)] +/// `UART_MODE` "Enable FIFOs" or Device mode, field of [Line Control +/// register](LineControl). +pub enum BaudRate { + Baud9600 = 0b000, + Baud19200 = 0b001, + Baud57600 = 0b010, + Baud115200 = 0b011, + BaudFSYS = 0b100, // See datasheet + Reserved1 = 0b101, + Reserved2 = 0b110, + Reserved3 = 0b111, +} + +/// Error Register, `UART_ERROR_REG` +/// +/// The `UART_ERROR_REG` register is the error register. +/// It contains bits related to parity errors. +/// All bits reset to 0 except TXE and RXE. +#[bitsize(16)] +#[doc(alias = "UART_ERROR_REG")] +#[derive(Clone, Copy, DebugBits, FromBits)] +pub struct ErrorReg { + /// `PAR_STATUS` Indicates a parity error, updated every byte + pub parity_status: bool, + /// `DMA_PARITY_ERROR` TODO + pub dma_parity_error: bool, + /// 15:2 - Reserved, do not modify, read as zero. + _reserved_zero_no_modify: u14, +} +impl_vmstate_bitsized!(ErrorReg); + +impl ErrorReg { + pub fn reset(&mut self) { + *self = 0.into(); + } +} + +impl Default for ErrorReg { + fn default() -> Self { + let mut ret: Self = 0.into(); + ret.reset(); + ret + } +} + +#[bitsize(1)] +#[derive(Clone, Copy, Debug, Eq, FromBits, PartialEq)] +/// `UART_MODE` "Enable FIFOs" or Device mode, field of [Line Control +/// register](LineControl). +pub enum Mode { + Character = 0, + /// 1 = transmit and receive FIFO buffers are enabled (FIFO mode). + FIFO = 1, +} + +bits! { + /// Interrupt status bits in UARTRIS, UARTMIS, UARTIMSC + #[derive(Default)] + pub struct Interrupt(u32) { + OE = 1 << 10, + BE = 1 << 9, + PE = 1 << 8, + FE = 1 << 7, + RT = 1 << 6, + TX = 1 << 5, + RX = 1 << 4, + DSR = 1 << 3, + DCD = 1 << 2, + CTS = 1 << 1, + RI = 1 << 0, + + E = bits!(Self as u32: OE | BE | PE | FE), + MS = bits!(Self as u32: RI | DSR | DCD | CTS), + } +} +impl_vmstate_forward!(Interrupt); diff --git a/rust/hw/char/dialog_uart/wrapper.h b/rust/hw/char/dialog_uart/wrapper.h new file mode 100644 index 0000000000..87a5a589c8 --- /dev/null +++ b/rust/hw/char/dialog_uart/wrapper.h @@ -0,0 +1,51 @@ +/* + * QEMU System Emulator + * + * Copyright (c) 2024 Linaro Ltd. + * + * Authors: Manos Pitsidianakis + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + + +/* + * This header file is meant to be used as input to the `bindgen` application + * in order to generate C FFI compatible Rust bindings. + */ + +#ifndef __CLANG_STDATOMIC_H +#define __CLANG_STDATOMIC_H +/* + * Fix potential missing stdatomic.h error in case bindgen does not insert the + * correct libclang header paths on its own. We do not use stdatomic.h symbols + * in QEMU code, so it's fine to declare dummy types instead. + */ +typedef enum memory_order { + memory_order_relaxed, + memory_order_consume, + memory_order_acquire, + memory_order_release, + memory_order_acq_rel, + memory_order_seq_cst, +} memory_order; +#endif /* __CLANG_STDATOMIC_H */ + +#include "qemu/osdep.h" +#include "hw/char/pl011.h" diff --git a/rust/hw/char/meson.build b/rust/hw/char/meson.build index 5716dc43ef..c54529c186 100644 --- a/rust/hw/char/meson.build +++ b/rust/hw/char/meson.build @@ -1 +1,2 @@ +subdir('dialog_uart') subdir('pl011') diff --git a/target/cr16c/cpu.c b/target/cr16c/cpu.c index fee48363b1..eb816f9d6f 100644 --- a/target/cr16c/cpu.c +++ b/target/cr16c/cpu.c @@ -137,8 +137,35 @@ static int cr16c_cpu_mmu_index(CPUState *cs, bool ifetch) return 0; } +// Priority: +// DBG > IAD > NMI > Interrupt > ISE > PSR.P = 1, some instruction suspend stuff +// interrupt dispatch vectors +#define INT_RESERVED_0 0 +#define INT_NMI 1 +#define INT_RESERVED_2 2 +#define INT_RESERVED_3 3 +#define INT_RESERVED_4 4 +#define INT_SVC 5 // Supervisor Call Trap +#define INT_DVZ 6 // Divide By Zero +#define INT_FLG 7 // Flag +#define INT_BPT 8 // Breakpoint +#define INT_TRC 9 // Trace +#define INT_UND 10 // Undefined instruction +#define INT_RESERVED_11 11 +#define INT_IAD 12 // Illegal Address +#define INT_RESERVED_13 13 +#define INT_DBG 14 // Debug +#define INT_ISE 15 // In-System Emulator +#define INT_MASKABLE_MIN 16 +#define INT_MASKABLE_MAX 127 + static bool cr16c_cpu_exec_interrupt(CPUState *cs, int interrupt_request) { + //CPUCR16CState *env = cpu_env(cs); + + if (interrupt_request & CPU_INTERRUPT_HARD) { + + } // TODO return false; } @@ -169,8 +196,7 @@ bool cr16c_cpu_tlb_fill(CPUState *cs, vaddr addr, int size, void cr16c_restore_state_to_opc(CPUState *cpu, const TranslationBlock *tb, const uint64_t *data) { - qemu_printf("idk what im doing!!!!!!\n"); - // TODO figure out what this is supposed to do and implement it + cpu_env(cpu)->pc = data[0]; } @@ -214,6 +240,21 @@ static void cr16c_cpu_class_init(ObjectClass *oc, const void *data) cc->tcg_ops = &cr16c_tcg_ops; } +static void cr16c_cpu_set_int(void *opaque, int irq, int level) +{ + // TODO +} + +static void cr16c_cpu_initfn(Object *obj) +{ + CR16CCPU *cpu = CR16C_CPU(obj); + + /* Set the number of interrupts supported by the CPU. */ + qdev_init_gpio_in(DEVICE(cpu), cr16c_cpu_set_int, + //sizeof(cpu->env.intsrc) * 8); + 127 - 15); +} + static const TypeInfo cr16c_cpu_archs[] = { { .name = TYPE_CR16C_CPU, @@ -221,6 +262,7 @@ static const TypeInfo cr16c_cpu_archs[] = { .instance_size = sizeof(CR16CCPU), .class_size = sizeof(CR16CCPUClass), .class_init = cr16c_cpu_class_init, + .instance_init = cr16c_cpu_initfn }, }; diff --git a/target/cr16c/disas.c b/target/cr16c/disas.c index 623564d1bf..1460411d09 100644 --- a/target/cr16c/disas.c +++ b/target/cr16c/disas.c @@ -139,10 +139,120 @@ output(mnemonic, format, ##__VA_ARGS__); \ return true; \ } -/*static const char width[] = { - 'x', 'B', 'W', 'x', 'D' -};*/ +/* +static const char* width[] = { + "x", "B", "W", "x", "D" +}; -//INSN(MOV_imm, "MOV" width[a->width], "$0x%x, r%d", width[a->width], a->imm, a->rd) -//INSN(MOV_reg, "MOV" width[a->width], "r%d, r%d", width[a->width], a->rs, a->rd) -//INSN(MOVD_reg, "MOVD", "r%d, r%d", a->rs, a->rd) +INSN(UNIMPLEMENTED, "") + +INSN(LOAD, "") +INSN(LOAD_rrp, "") +INSN(LOAD_abs, "") +INSN(LOAD_ind_abs, "") +//INSN(LOADD, "") +INSN(STOR, "") +INSN(STOR_rrp, "") +INSN(STOR_rrp_imm, "") +INSN(STOR_abs, "") +INSN(STOR_ind_abs, "") +INSN(STOR_abs_imm, "") +INSN(STOR_abs_rrp_imm, "") +//INSN(STORD, "") +INSN(STOR_imm, "$0x%x, r%d", a->imm, a->ra) +INSN(LOADM, "$0x%x", a->cnt) +//INSN(LOADMP, "$0x%x", a->cnt) +INSN(STORM, "$0x%x", a->cnt) +//INSN(STORMP, "$0x%x", a->cnt) + +INSN(MOV_reg, "%s r%d, r%d", width[a->width], a->rs, a->rd) +INSN(MOV_imm, "%s $0x%x, r%d", width[a->width], a->imm, a->rd) +INSN(MOVD_reg, "r%dr%d, r%dr%d", a->rs + 1, a->rs, a->rd + 1, a->rd) +INSN(MOVXB, "r%d, r%d", a->rs, a->rd) +INSN(MOVZB, "r%d, r%d", a->rs, a->rd) +INSN(MOVXW, "r%d, r%d", a->rs, a->rd) +INSN(MOVZW, "r%d, r%d", a->rs, a->rd) + +INSN(ADD_imm, "$0x%x, r%d", a->imm, a->rd) +INSN(ADD_reg, "r%d, r%d", a->rs, a->rd) +INSN(ADDU_imm, "$0x%x, r%d", a->imm, a->rd) +INSN(ADDU_reg, "r%d, r%d", a->rs, a->rd) +//INSN(ADDC_imm, "") +//INSN(ADDC_reg, "r%d, r%d", a->rs, a->rd) +INSN(ADDD_imm, "$0x%x, r%dr%d", a->imm, a->rd + 1, a->rd) +INSN(ADDD_rp, "r%dr%d, r%dr%d", a->rs + 1, a->rs, a->rd + 1, a->rd) + +INSN(MACQW, "") +INSN(MACSW, "") +INSN(MACUW, "") +INSN(MUL_imm, "") +INSN(MULB_reg, "r%d, r%d", a->rs, a->rd) +INSN(MULW_reg, "r%d, r%d", a->rs, a->rd) +INSN(MULSB_reg, "r%d, r%d", a->rs, a->rd) +INSN(MULSW_reg, "r%d, r%d", a->rs, a->rd) +INSN(MULUW_reg, "r%d, r%d", a->rs, a->rd) +INSN(SUB_imm, "") +INSN(SUB_reg, "r%d, r%d", a->rs, a->rd) +INSN(SUBD_imm, "") +INSN(SUBD_rp, "") +//INSN(SUBC_imm, "") +//INSN(SUBC_reg, "") + +INSN(CMP_imm, "") +INSN(CMP_reg, "") +//INSN(CMPD_imm, "") +INSN(CMPD_reg, "") +INSN(BR0, "") // BEQ0, BNE0 + +INSN(AND_imm, "") +INSN(AND_reg, "") +INSN(ANDD_imm, "") +INSN(ANDD_rp, "") +INSN(OR_imm, "") +INSN(OR_reg, "") +INSN(ORD_imm, "") +INSN(ORD_rp, "") +INSN(XOR_imm, "") +INSN(XOR_reg, "") +INSN(XORD_imm, "") +INSN(XORD_rp, "") +INSN(SCOND, "") + +INSN(ASHU_imm_l, "") +INSN(ASHU_imm_r, "") +INSN(ASHU_reg, "") +INSN(ASHUD_imm_l, "") +INSN(ASHUD_imm_r, "") +INSN(ASHUD_rp, "") +INSN(LSH_imm_r, "") +INSN(LSH_reg, "") +INSN(LSHD_imm_r, "") +INSN(LSHD_rp, "") + +// TODO +//INSN(TBIT, "") +INSN(SBIT_abs, "") +INSN(CBIT_abs, "") + +// TODO +INSN(LPR, "") +INSN(LPRD, "") +INSN(SPR, "") +INSN(SPRD, "") + +INSN(BRCOND, "") +INSN(BAL_ra, "") +// INSN(BR, "") // BRCOND condition "ALWAYS" +INSN(EXCP, "") +INSN(JCOND, "") +//INSN(JAL, "") +//INSN(JUMP, "") // JCOND condition "ALWAYS" +//INSN(JUSR, "") +//INSN(RETX, "") +INSN(push, "") +INSN(pop, "") + +//INSN(CINV, "") +//INSN(NOP, "") +//INSN(WAIT, "") +*/ diff --git a/target/cr16c/insn.decode b/target/cr16c/insn.decode index d2681318b1..9e041f4c7d 100644 --- a/target/cr16c/insn.decode +++ b/target/cr16c/insn.decode @@ -257,6 +257,8 @@ BR0 0000 11 word:1 ne:1 dest:4 src:4 JCOND 0000 1010 cond:4 ra:4 +#JAL 0000 0000 1101 .... + EXCP 0000 0000 1100 id:4 &bal dest @@ -279,7 +281,7 @@ push 0000 0001 .... .... @push # fmt 14 &load rd ra dbase disp width &load_rrp rd rrp disp width -&load_abs rd addr width +&load_abs rd addr width remap &load_ind_abs rd ri addr width %load_disp20 40:4 16:s16 @@ -291,10 +293,10 @@ push 0000 0001 .... .... @push # fmt 14 @load_disp20_reg .... .... .... .... .... .... rd:4 ra:4 .... .... .... .... disp=%load_disp20 &load @load_disp20_rrp .... .... .... .... .... .... rd:4 rrp:4 .... .... .... .... disp=%load_disp20 &load_rrp @load_disp20_rp .... .... .... .... .... .... rd:4 ra:4 .... .... .... .... disp=%load_disp20 &load -@load_abs20 .... .... rd:4 .... .... .... .... .... addr=%addr_abs20 &load_abs +@load_abs20 .... .... rd:4 .... .... .... .... .... addr=%addr_abs20 remap=1 &load_abs @load_ind_abs .... ... ri:1 rd:4 addr:20 &load_ind_abs @load_disp4_reg .... .... rd:4 ra:4 &load -@load_abs24 .... .... .... .... .... .... rd:4 .... .... .... .... .... addr=%addr_disp24 &load_abs +@load_abs24 .... .... .... .... .... .... rd:4 .... .... .... .... .... addr=%addr_disp24 remap=0 &load_abs #@load_disp14_rrp .... .... .... rrp:4 .... .... rd:4 .... disp=%load_disp14 &load_rrp { diff --git a/target/cr16c/translate.c b/target/cr16c/translate.c index fc6c8543e4..d93302a27f 100644 --- a/target/cr16c/translate.c +++ b/target/cr16c/translate.c @@ -218,10 +218,7 @@ static void gen_compute_rrp_addr(TCGv_i32 dest, uint8_t rrp, uint32_t disp) { /* Moves */ static bool trans_MOV_imm(DisasContext* ctx, arg_MOV_imm* a) { - int len = (a->width == 4 ? 2 : a->width) * 8; - //tcg_gen_deposit_i32(r[a->rd], r[a->rd], tcg_constant_i32(a->imm), 0, len); - //tcg_gen_deposit_z_i32(); - tcg_gen_deposit_z_i32(r[a->rd], tcg_constant_i32(a->imm), 0, len); + tcg_gen_deposit_i32(r[a->rd], r[a->rd], tcg_constant_i32(a->imm), 0, a->width * 8); if (a->width == 4 && a->rd < CR16C_FIRST_32B_REG) { tcg_gen_movi_i32(r[a->rd + 1], a->imm >> 16); } @@ -746,14 +743,19 @@ static bool trans_CMP_reg(DisasContext *ctx, arg_CMP_reg *a) { } static bool trans_CMPD_reg(DisasContext *ctx, arg_CMPD_reg *a) { + TCGv tmp_a = tcg_temp_new_i32(); + TCGv tmp_b = tcg_temp_new_i32(); + tcg_gen_mov_i32(tmp_a, r[a->rs1]); + tcg_gen_mov_i32(tmp_b, r[a->rs2]); + if (a->rs1 < CR16C_FIRST_32B_REG) { - tcg_gen_deposit_i32(r[a->rs1], r[a->rs1], r[a->rs1+1], 16, 16); + tcg_gen_deposit_i32(tmp_a, tmp_a, r[a->rs1+1], 16, 16); } if (a->rs2 < CR16C_FIRST_32B_REG) { - tcg_gen_deposit_i32(r[a->rs2], r[a->rs2], r[a->rs2+1], 16, 16); + tcg_gen_deposit_i32(tmp_b, tmp_b, r[a->rs2+1], 16, 16); } - gen_cmp(r[a->rs2], r[a->rs1]); + gen_cmp(tmp_b, tmp_a); return true; } @@ -1396,10 +1398,23 @@ static bool trans_LOAD(DisasContext *ctx, arg_LOAD *a) { return true; } +// TODO this should already be in reloc_abs20. see how to replace this in the decoder +static int abs20_remap(int addr) { + if (addr > 0xEFFFF) + return addr | 0xF00000; + return addr; +} + static bool trans_LOAD_abs(DisasContext *ctx, arg_LOAD_abs *a) { TCGv_i32 temp = tcg_temp_new_i32(); - tcg_gen_qemu_ld_i32(temp, tcg_constant_i32(a->addr), 0, unsigned_op_by_width[a->width]); + // See Table 5-7, footnote f, which applies for abs20 + int addr = a->addr; + if (a->remap) { + addr = abs20_remap(addr); + } + + tcg_gen_qemu_ld_i32(temp, tcg_constant_i32(addr), 0, unsigned_op_by_width[a->width]); gen_move_dest(temp, a->rd, a->width); return true; @@ -1453,7 +1468,6 @@ static bool trans_STOR(DisasContext *ctx, arg_STOR *a) { gen_compute_addr_disp(temp, a->ra, a->disp, a->dbase); gen_combine_rp(a->rs, a->width); tcg_gen_qemu_st_i32(r[a->rs], temp, 0, unsigned_op_by_width[a->width]); - tcg_gen_andi_tl(r[a->rs], r[a->rs], 0xffff); /* make it 16 bits */ return true; } @@ -1464,18 +1478,10 @@ static bool trans_STOR_rrp(DisasContext *ctx, arg_STOR_rrp *a) { gen_compute_rrp_addr(temp, a->rrp, a->disp); gen_combine_rp(a->rs, a->width); tcg_gen_qemu_st_i32(r[a->rs], temp, 0, unsigned_op_by_width[a->width]); - tcg_gen_andi_tl(r[a->rs], r[a->rs], 0xffff); /* make it 16 bits */ return true; } -// TODO this should already be in reloc_abs20. see how to replace this in the decoder -static int abs20_remap(int addr) { - if (addr > 0xEFFFF) - return addr | 0xF00000; - return addr; -} - static bool trans_STOR_abs(DisasContext *ctx, arg_STOR_abs *a) { int32_t addr = a->addr; @@ -1489,7 +1495,6 @@ static bool trans_STOR_abs(DisasContext *ctx, arg_STOR_abs *a) { gen_combine_rp(a->rs, a->width); tcg_gen_qemu_st_i32(r[a->rs], tcg_constant_i32(addr), 0, unsigned_op_by_width[a->width]); - tcg_gen_andi_tl(r[a->rs], r[a->rs], 0xffff); /* make it 16 bits */ return true; } @@ -1499,7 +1504,6 @@ static bool trans_STOR_ind_abs(DisasContext *ctx, arg_STOR_ind_abs *a) { tcg_gen_addi_i32(temp, r[12 + a->ri], a->addr); gen_combine_rp(a->rs, a->width); tcg_gen_qemu_st_i32(r[a->rs], temp, 0, unsigned_op_by_width[a->width]); - tcg_gen_andi_tl(r[a->rs], r[a->rs], 0xffff); /* make it 16 bits */ return true; } @@ -1670,9 +1674,8 @@ static bool trans_pop(DisasContext *ctx, arg_pop *a) { // basically, JUMP RA ctx->base.is_jmp = DISAS_NORETURN; - tcg_gen_goto_tb(0); tcg_gen_mov_i32(pc, r[CR16C_REGNO_RA]); - tcg_gen_exit_tb(ctx->base.tb, 0); + tcg_gen_lookup_and_goto_ptr(); } return true; }