From nobody Sun Nov 24 01:12:53 2024 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=pass(p=none dis=none) header.from=redhat.com ARC-Seal: i=1; a=rsa-sha256; t=1728667190; cv=none; d=zohomail.com; s=zohoarc; b=V0VsXC0BS6Akc9R89qiXkhnmCfXZGdHYqpMs8SZDouiBaWmtwW+VJ4ri7l5tDvoxOnqStxHXCm8pVQ697nbYuhK2v3++EmKrW2Zvo5SlIyhnwYMbkirpCaZqkLr+2WxfBVPlJ5fVTClkSzVDRfhs1rfQ9ZpSRF/jQZzlwIcbrxk= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1728667190; h=Content-Type:Content-Transfer-Encoding:Cc:Cc:Date:Date:From:From:In-Reply-To:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:References:Sender:Subject:Subject:To:To:Message-Id:Reply-To; bh=rz3jn5FX9Jc0luzY69WgdjEVqkkvUpzKTT0y9sZddvk=; b=LEXdiopHqA7+irzMeGdYNg7lLyAmQ8oXaLbUThKDF1bedlIplXhrLyb1Nhmf0+3jpnCIw72jdBFNWyzxQpfrqfiylAUqTip4g0Akbg+qAzmuhYwdNOr8hTJCNyXMtHFQRR+51C3jiB1+rcTmCl/KV61xG64uiTTpL/jv0YxCD2o= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=pass header.from= (p=none dis=none) Return-Path: Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1728667188102432.02611961240666; Fri, 11 Oct 2024 10:19:48 -0700 (PDT) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1szJ4d-0001K9-M5; Fri, 11 Oct 2024 13:05:07 -0400 Received: from eggs.gnu.org ([2001:470:142:3::10]) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1szJ4R-0000wP-Dj for qemu-devel@nongnu.org; Fri, 11 Oct 2024 13:04:55 -0400 Received: from us-smtp-delivery-124.mimecast.com ([170.10.133.124]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1szHdw-0007FK-7U for qemu-devel@nongnu.org; Fri, 11 Oct 2024 11:33:33 -0400 Received: from mail-ed1-f69.google.com (mail-ed1-f69.google.com [209.85.208.69]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-352-_AOHzmuQNnq8odPWaXUKRw-1; Fri, 11 Oct 2024 11:33:22 -0400 Received: by mail-ed1-f69.google.com with SMTP id 4fb4d7f45d1cf-5c937403b2bso1312167a12.1 for ; Fri, 11 Oct 2024 08:33:22 -0700 (PDT) Received: from avogadro.local ([151.81.124.37]) by smtp.gmail.com with ESMTPSA id 4fb4d7f45d1cf-5c93711adacsm2050199a12.37.2024.10.11.08.33.12 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Fri, 11 Oct 2024 08:33:12 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1728660806; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=rz3jn5FX9Jc0luzY69WgdjEVqkkvUpzKTT0y9sZddvk=; b=PgLxtAs8ZcXiiepfmgjSjiViGCVRIUX/CyFa77cKLV8ztFnVffhKUUbXLQ7AW1IsQhZ4uj Pk8zRM8cVV9o1W88Luyo4/Aqsz1pBv9Ypb8mlrdn0PfxOASTEBZNWCErU8hw5VMDcSvcEm s/To3UpH4PM9t08J5aTQcGa+vSmNxp8= X-MC-Unique: _AOHzmuQNnq8odPWaXUKRw-1 X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1728660800; x=1729265600; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=rz3jn5FX9Jc0luzY69WgdjEVqkkvUpzKTT0y9sZddvk=; b=LIhDLbuWw7BWDwpwP1MNVX7e5n2YK42kdLFkjwHtACKGirl34rBiLb4b8x1pAwyP2H nsT7GMm/skn0wXbmGXAVohZEIU4a35TN67VhnMnh2YKd6vNn8RxfNGsWY16sjJ7FjuSz u72/7gKO76HyJfU9vvyVtuMwMuTGpcp3HqXXPdYah9JdUoVytdlhm5RnMOfLHcY2L4od pi9CayngsPhrETCR36OMMXNZYkflVz9wHUYLLxp4gfroZ/i+EIWvnohNPGPD+6vbtpgK 3CdHwp0Cs8kQmuXKnMBhTqSeMq7LPkWsBRM6Xzm8SAV2fTAqBLGBdDlv1QLTJr3+P4AO FYFg== X-Gm-Message-State: AOJu0Yy9phw1b4Y2WcBzH1q2J5b23ljaPX8VoRxRJE7xo+6XA9iCJnlA soArKkRZ919HmpvuUwspmU1V/z0zEHQXm7//q/MLW5drDx3FqyIpbEDCvNT3HmNMGhkvBLG4Ctc QGK9tGxjR2lb8P731/9b3fEa74rZU5vIbfP+AG2ipCJssIb4TMkCajcudTd3EaIjDZybXa6IvIk nJVFj6C5fYV4JYvqYfhYVxKfHeJfFn1nfYqhavVkU= X-Received: by 2002:a05:6402:358e:b0:5c8:8cf5:e979 with SMTP id 4fb4d7f45d1cf-5c948cc9f93mr1805780a12.19.1728660799135; Fri, 11 Oct 2024 08:33:19 -0700 (PDT) X-Google-Smtp-Source: AGHT+IGMCB2GfrzSDGfLlW1aoIHcA1dbFxYuF8WPUp0LlTuhe84d/1gpl+SFbZzEYlEf4/nYodAZkw== X-Received: by 2002:a05:6402:358e:b0:5c8:8cf5:e979 with SMTP id 4fb4d7f45d1cf-5c948cc9f93mr1805743a12.19.1728660797990; Fri, 11 Oct 2024 08:33:17 -0700 (PDT) From: Paolo Bonzini To: qemu-devel@nongnu.org Cc: Junjie Mao , Manos Pitsidianakis Subject: [PULL v3 10/18] rust: add PL011 device model Date: Fri, 11 Oct 2024 17:32:18 +0200 Message-ID: <20241011153227.81770-11-pbonzini@redhat.com> X-Mailer: git-send-email 2.46.2 In-Reply-To: <20241011153227.81770-1-pbonzini@redhat.com> References: <20241011153227.81770-1-pbonzini@redhat.com> MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Received-SPF: pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists.gnu.org; Received-SPF: pass client-ip=170.10.133.124; envelope-from=pbonzini@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -21 X-Spam_score: -2.2 X-Spam_bar: -- X-Spam_report: (-2.2 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.15, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, RCVD_IN_MSPIKE_H3=0.001, RCVD_IN_MSPIKE_WL=0.001, RCVD_IN_VALIDITY_CERTIFIED_BLOCKED=0.001, RCVD_IN_VALIDITY_RPBL_BLOCKED=0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=ham autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: qemu-devel-bounces+importer=patchew.org@nongnu.org X-ZohoMail-DKIM: pass (identity @redhat.com) X-ZM-MESSAGEID: 1728667191708116600 This 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=3Daarch64-softmmu --enable-rust 2. Launching a VM with qemu-system-aarch64 should use the Rust version of the pl011 device Co-authored-by: Junjie Mao Co-authored-by: Paolo Bonzini Signed-off-by: Junjie Mao Signed-off-by: Paolo Bonzini Signed-off-by: Manos Pitsidianakis Link: https://lore.kernel.org/r/6ec1d4fb8db2a1d7ba94c73e65d9770371b7857d.17= 27961605.git.manos.pitsidianakis@linaro.org Signed-off-by: Paolo Bonzini --- 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 + .../arbitrary-int-1-rs/meson.build | 19 + .../packagefiles/bilge-0.2-rs/meson.build | 29 + .../bilge-impl-0.2-rs/meson.build | 45 ++ .../packagefiles/either-1-rs/meson.build | 24 + .../itertools-0.11-rs/meson.build | 30 + .../proc-macro-error-1-rs/meson.build | 40 ++ .../proc-macro-error-attr-1-rs/meson.build | 32 + .../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(-) create mode 100644 rust/hw/Kconfig create mode 100644 rust/hw/char/Kconfig create mode 100644 rust/hw/char/meson.build create mode 100644 rust/hw/char/pl011/.gitignore create mode 100644 rust/hw/char/pl011/Cargo.lock create mode 100644 rust/hw/char/pl011/Cargo.toml create mode 100644 rust/hw/char/pl011/README.md create mode 100644 rust/hw/char/pl011/meson.build create mode 100644 rust/hw/char/pl011/src/device.rs create mode 100644 rust/hw/char/pl011/src/device_class.rs create mode 100644 rust/hw/char/pl011/src/lib.rs create mode 100644 rust/hw/char/pl011/src/memory_ops.rs create mode 100644 rust/hw/meson.build create mode 100755 scripts/rust/rust_root_crate.sh create mode 100644 subprojects/arbitrary-int-1-rs.wrap create mode 100644 subprojects/bilge-0.2-rs.wrap create mode 100644 subprojects/bilge-impl-0.2-rs.wrap create mode 100644 subprojects/either-1-rs.wrap create mode 100644 subprojects/itertools-0.11-rs.wrap create mode 100644 subprojects/packagefiles/arbitrary-int-1-rs/meson.build create mode 100644 subprojects/packagefiles/bilge-0.2-rs/meson.build create mode 100644 subprojects/packagefiles/bilge-impl-0.2-rs/meson.build create mode 100644 subprojects/packagefiles/either-1-rs/meson.build create mode 100644 subprojects/packagefiles/itertools-0.11-rs/meson.build create mode 100644 subprojects/packagefiles/proc-macro-error-1-rs/meson.bu= ild create mode 100644 subprojects/packagefiles/proc-macro-error-attr-1-rs/mes= on.build create mode 100644 subprojects/packagefiles/unicode-ident-1-rs/meson.build create mode 100644 subprojects/proc-macro-error-1-rs.wrap create mode 100644 subprojects/proc-macro-error-attr-1-rs.wrap diff --git a/MAINTAINERS b/MAINTAINERS index dbc56c5c612..539d59c1954 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -1139,6 +1139,11 @@ F: include/hw/*/microbit*.h F: tests/qtest/microbit-test.c F: docs/system/arm/nrf.rst =20 +ARM PL011 Rust device +M: Manos Pitsidianakis +S: Maintained +F: rust/hw/char/pl011/ + AVR Machines ------------- =20 diff --git a/meson.build b/meson.build index aea419a8317..b91863736ea 100644 --- a/meson.build +++ b/meson.build @@ -3512,6 +3512,7 @@ qom_ss =3D ss.source_set() system_ss =3D ss.source_set() specific_fuzz_ss =3D ss.source_set() specific_ss =3D ss.source_set() +rust_devices_ss =3D ss.source_set() stub_ss =3D ss.source_set() trace_ss =3D ss.source_set() user_ss =3D ss.source_set() @@ -4059,6 +4060,29 @@ foreach target : target_dirs arch_srcs +=3D target_specific.sources() arch_deps +=3D target_specific.dependencies() =20 + if have_rust and have_system + target_rust =3D rust_devices_ss.apply(config_target, strict: false) + crates =3D [] + foreach dep : target_rust.dependencies() + crates +=3D dep.get_variable('crate') + endforeach + if crates.length() > 0 + rlib_rs =3D custom_target('rust_' + target.underscorify() + '.rs', + output: 'rust_' + target.underscorify() + '.= rs', + command: [find_program('scripts/rust/rust_ro= ot_crate.sh')] + crates, + capture: true, + build_by_default: true, + build_always_stale: true) + rlib =3D static_library('rust_' + target.underscorify(), + rlib_rs, + dependencies: target_rust.dependencies(), + override_options: ['rust_std=3D2021', 'build.r= ust_std=3D2021'], + rust_args: rustc_args, + rust_abi: 'c') + arch_deps +=3D declare_dependency(link_whole: [rlib]) + endif + endif + # allow using headers from the dependencies but do not include the sourc= es, # because this emulator only needs those in "objects". For external # dependencies, the full dependency is included below in the executable. diff --git a/hw/arm/Kconfig b/hw/arm/Kconfig index eac5070514f..e7b9cfb59c0 100644 --- a/hw/arm/Kconfig +++ b/hw/arm/Kconfig @@ -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 @@ -169,7 +173,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 @@ -194,7 +199,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 @@ -218,7 +224,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 @@ -278,7 +285,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 @@ -437,7 +446,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 diff --git a/rust/Kconfig b/rust/Kconfig index e69de29bb2d..f9f5c390988 100644 --- a/rust/Kconfig +++ b/rust/Kconfig @@ -0,0 +1 @@ +source hw/Kconfig diff --git a/rust/hw/Kconfig b/rust/hw/Kconfig new file mode 100644 index 00000000000..4d934f30afe --- /dev/null +++ b/rust/hw/Kconfig @@ -0,0 +1,2 @@ +# devices Kconfig +source char/Kconfig diff --git a/rust/hw/char/Kconfig b/rust/hw/char/Kconfig new file mode 100644 index 00000000000..a1732a9e97f --- /dev/null +++ b/rust/hw/char/Kconfig @@ -0,0 +1,3 @@ +config X_PL011_RUST + bool + default y if HAVE_RUST diff --git a/rust/hw/char/meson.build b/rust/hw/char/meson.build new file mode 100644 index 00000000000..5716dc43ef6 --- /dev/null +++ b/rust/hw/char/meson.build @@ -0,0 +1 @@ +subdir('pl011') diff --git a/rust/hw/char/pl011/.gitignore b/rust/hw/char/pl011/.gitignore new file mode 100644 index 00000000000..71eaff2035d --- /dev/null +++ b/rust/hw/char/pl011/.gitignore @@ -0,0 +1,2 @@ +# Ignore generated bindings file overrides. +src/bindings.rs.inc diff --git a/rust/hw/char/pl011/Cargo.lock b/rust/hw/char/pl011/Cargo.lock new file mode 100644 index 00000000000..b58cebb186e --- /dev/null +++ b/rust/hw/char/pl011/Cargo.lock @@ -0,0 +1,134 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version =3D 3 + +[[package]] +name =3D "arbitrary-int" +version =3D "1.2.7" +source =3D "registry+https://github.com/rust-lang/crates.io-index" +checksum =3D "c84fc003e338a6f69fbd4f7fe9f92b535ff13e9af8997f3b14b6ddff8b1d= f46d" + +[[package]] +name =3D "bilge" +version =3D "0.2.0" +source =3D "registry+https://github.com/rust-lang/crates.io-index" +checksum =3D "dc707ed8ebf81de5cd6c7f48f54b4c8621760926cdf35a57000747c512e6= 7b57" +dependencies =3D [ + "arbitrary-int", + "bilge-impl", +] + +[[package]] +name =3D "bilge-impl" +version =3D "0.2.0" +source =3D "registry+https://github.com/rust-lang/crates.io-index" +checksum =3D "feb11e002038ad243af39c2068c8a72bcf147acf05025dcdb916fcc000ad= b2d8" +dependencies =3D [ + "itertools", + "proc-macro-error", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name =3D "either" +version =3D "1.12.0" +source =3D "registry+https://github.com/rust-lang/crates.io-index" +checksum =3D "3dca9240753cf90908d7e4aac30f630662b02aebaa1b58a3cadabdb23385= b58b" + +[[package]] +name =3D "itertools" +version =3D "0.11.0" +source =3D "registry+https://github.com/rust-lang/crates.io-index" +checksum =3D "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3= fe57" +dependencies =3D [ + "either", +] + +[[package]] +name =3D "pl011" +version =3D "0.1.0" +dependencies =3D [ + "bilge", + "bilge-impl", + "qemu_api", + "qemu_api_macros", +] + +[[package]] +name =3D "proc-macro-error" +version =3D "1.0.4" +source =3D "registry+https://github.com/rust-lang/crates.io-index" +checksum =3D "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5c= e38c" +dependencies =3D [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "version_check", +] + +[[package]] +name =3D "proc-macro-error-attr" +version =3D "1.0.4" +source =3D "registry+https://github.com/rust-lang/crates.io-index" +checksum =3D "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35= f869" +dependencies =3D [ + "proc-macro2", + "quote", + "version_check", +] + +[[package]] +name =3D "proc-macro2" +version =3D "1.0.84" +source =3D "registry+https://github.com/rust-lang/crates.io-index" +checksum =3D "ec96c6a92621310b51366f1e28d05ef11489516e93be030060e5fc12024a= 49d6" +dependencies =3D [ + "unicode-ident", +] + +[[package]] +name =3D "qemu_api" +version =3D "0.1.0" + +[[package]] +name =3D "qemu_api_macros" +version =3D "0.1.0" +dependencies =3D [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name =3D "quote" +version =3D "1.0.36" +source =3D "registry+https://github.com/rust-lang/crates.io-index" +checksum =3D "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208ac= aca7" +dependencies =3D [ + "proc-macro2", +] + +[[package]] +name =3D "syn" +version =3D "2.0.66" +source =3D "registry+https://github.com/rust-lang/crates.io-index" +checksum =3D "c42f3f41a2de00b01c0aaad383c5a45241efc8b2d1eda5661812fda5f3cd= cff5" +dependencies =3D [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name =3D "unicode-ident" +version =3D "1.0.12" +source =3D "registry+https://github.com/rust-lang/crates.io-index" +checksum =3D "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0f= ee4b" + +[[package]] +name =3D "version_check" +version =3D "0.9.4" +source =3D "registry+https://github.com/rust-lang/crates.io-index" +checksum =3D "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e= 483f" diff --git a/rust/hw/char/pl011/Cargo.toml b/rust/hw/char/pl011/Cargo.toml new file mode 100644 index 00000000000..b089e3dded6 --- /dev/null +++ b/rust/hw/char/pl011/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name =3D "pl011" +version =3D "0.1.0" +edition =3D "2021" +authors =3D ["Manos Pitsidianakis "] +license =3D "GPL-2.0-or-later" +readme =3D "README.md" +homepage =3D "https://www.qemu.org" +description =3D "pl011 device model for QEMU" +repository =3D "https://gitlab.com/epilys/rust-for-qemu" +resolver =3D "2" +publish =3D false +keywords =3D [] +categories =3D [] + +[lib] +crate-type =3D ["staticlib"] + +[dependencies] +bilge =3D { version =3D "0.2.0" } +bilge-impl =3D { version =3D "0.2.0" } +qemu_api =3D { path =3D "../../../qemu-api" } +qemu_api_macros =3D { path =3D "../../../qemu-api-macros" } + +# Do not include in any global workspace +[workspace] diff --git a/rust/hw/char/pl011/README.md b/rust/hw/char/pl011/README.md new file mode 100644 index 00000000000..cd7dea31634 --- /dev/null +++ b/rust/hw/char/pl011/README.md @@ -0,0 +1,31 @@ +# PL011 QEMU Device Model + +This library implements a device model for the PrimeCell=C2=AE 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-unkn= own-linux-gnu +``` diff --git a/rust/hw/char/pl011/meson.build b/rust/hw/char/pl011/meson.build new file mode 100644 index 00000000000..547cca5a96f --- /dev/null +++ b/rust/hw/char/pl011/meson.build @@ -0,0 +1,26 @@ +subproject('bilge-0.2-rs', required: true) +subproject('bilge-impl-0.2-rs', required: true) + +bilge_dep =3D dependency('bilge-0.2-rs') +bilge_impl_dep =3D dependency('bilge-impl-0.2-rs') + +_libpl011_rs =3D static_library( + 'pl011', + files('src/lib.rs'), + override_options: ['rust_std=3D2021', 'build.rust_std=3D2021'], + 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_depende= ncy( + 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'}, +)]) diff --git a/rust/hw/char/pl011/src/device.rs b/rust/hw/char/pl011/src/devi= ce.rs new file mode 100644 index 00000000000..c7193b41bee --- /dev/null +++ b/rust/hw/char/pl011/src/device.rs @@ -0,0 +1,599 @@ +// Copyright 2024, Linaro Limited +// Author(s): Manos Pitsidianakis +// SPDX-License-Identifier: GPL-2.0-or-later + +use core::{ + ffi::{c_int, c_uchar, c_uint, c_void, CStr}, + ptr::{addr_of, addr_of_mut, NonNull}, +}; + +use qemu_api::{ + bindings::{self, *}, + definitions::ObjectImpl, +}; + +use crate::{ + memory_ops::PL011_OPS, + registers::{self, Interrupt}, + RegisterOffset, +}; + +static PL011_ID_ARM: [c_uchar; 8] =3D [0x11, 0x10, 0x14, 0x00, 0x0d, 0xf0,= 0x05, 0xb1]; + +const DATA_BREAK: u32 =3D 1 << 10; + +/// QEMU sourced constant. +pub const PL011_FIFO_DEPTH: usize =3D 16_usize; + +#[repr(C)] +#[derive(Debug, qemu_api_macros::Object)] +/// PL011 Device Model in QEMU +pub struct PL011State { + pub parent_obj: SysBusDevice, + pub iomem: MemoryRegion, + #[doc(alias =3D "fr")] + pub flags: registers::Flags, + #[doc(alias =3D "lcr")] + pub line_control: registers::LineControl, + #[doc(alias =3D "rsr")] + pub receive_status_error_clear: registers::ReceiveStatusErrorClear, + #[doc(alias =3D "cr")] + pub control: registers::Control, + pub dmacr: u32, + pub int_enabled: u32, + pub int_level: u32, + pub read_fifo: [u32; PL011_FIFO_DEPTH], + pub ilpr: u32, + pub ibrd: u32, + pub fbrd: u32, + pub ifl: u32, + pub read_pos: usize, + pub read_count: usize, + pub read_trigger: usize, + #[doc(alias =3D "chr")] + pub char_backend: CharBackend, + /// 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 =3D "irq")] + pub interrupts: [qemu_irq; 6usize], + #[doc(alias =3D "clk")] + pub clock: NonNull, + #[doc(alias =3D "migrate_clk")] + pub migrate_clock: bool, +} + +impl ObjectImpl for PL011State { + type Class =3D PL011Class; + const TYPE_INFO: qemu_api::bindings::TypeInfo =3D qemu_api::type_info!= { Self }; + const TYPE_NAME: &'static CStr =3D crate::TYPE_PL011; + const PARENT_TYPE_NAME: Option<&'static CStr> =3D Some(TYPE_SYS_BUS_DE= VICE); + const ABSTRACT: bool =3D false; + const INSTANCE_INIT: Option = =3D Some(pl011_init); + const INSTANCE_POST_INIT: Option =3D None; + const INSTANCE_FINALIZE: Option =3D 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), + > =3D 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), + > =3D None; +} + +#[used] +pub static CLK_NAME: &CStr =3D c"clk"; + +impl PL011State { + /// Initializes a pre-allocated, unitialized instance of `PL011State`. + /// + /// # Safety + /// + /// `self` must point to a correctly sized and aligned location for the + /// `PL011State` type. It must not be called more than once on the same + /// location/instance. All its fields are expected to hold unitialized + /// values with the sole exception of `parent_obj`. + pub unsafe fn init(&mut self) { + let dev =3D addr_of_mut!(*self).cast::(); + // SAFETY: + // + // self and self.iomem are guaranteed to be valid at this point si= nce callers + // must make sure the `self` reference is valid. + unsafe { + memory_region_init_io( + addr_of_mut!(self.iomem), + addr_of_mut!(*self).cast::(), + &PL011_OPS, + addr_of_mut!(*self).cast::(), + Self::TYPE_INFO.name, + 0x1000, + ); + let sbd =3D addr_of_mut!(*self).cast::(); + sysbus_init_mmio(sbd, addr_of_mut!(self.iomem)); + for irq in self.interrupts.iter_mut() { + sysbus_init_irq(sbd, irq); + } + } + // SAFETY: + // + // self.clock is not initialized at this point; but since `NonNull= <_>` is Copy, + // we can overwrite the undefined value without side effects. This= is + // safe since all PL011State instances are created by QOM code whi= ch + // calls this function to initialize the fields; therefore no code= is + // able to access an invalid self.clock value. + unsafe { + self.clock =3D NonNull::new(qdev_init_clock_in( + dev, + CLK_NAME.as_ptr(), + None, /* pl011_clock_update */ + addr_of_mut!(*self).cast::(), + ClockEvent::ClockUpdate.0, + )) + .unwrap(); + } + } + + pub fn read( + &mut self, + offset: hwaddr, + _size: core::ffi::c_uint, + ) -> std::ops::ControlFlow { + use RegisterOffset::*; + + std::ops::ControlFlow::Break(match RegisterOffset::try_from(offset= ) { + Err(v) if (0x3f8..0x400).contains(&v) =3D> { + u64::from(PL011_ID_ARM[((offset - 0xfe0) >> 2) as usize]) + } + Err(_) =3D> { + // qemu_log_mask(LOG_GUEST_ERROR, "pl011_read: Bad offset = 0x%x\n", (int)offset); + 0 + } + Ok(DR) =3D> { + // s->flags &=3D ~PL011_FLAG_RXFF; + self.flags.set_receive_fifo_full(false); + let c =3D self.read_fifo[self.read_pos]; + if self.read_count > 0 { + self.read_count -=3D 1; + self.read_pos =3D (self.read_pos + 1) & (self.fifo_dep= th() - 1); + } + if self.read_count =3D=3D 0 { + // self.flags |=3D PL011_FLAG_RXFE; + self.flags.set_receive_fifo_empty(true); + } + if self.read_count + 1 =3D=3D self.read_trigger { + //self.int_level &=3D ~ INT_RX; + self.int_level &=3D !registers::INT_RX; + } + // Update error bits. + self.receive_status_error_clear =3D c.to_be_bytes()[3].int= o(); + self.update(); + // Must call qemu_chr_fe_accept_input, so return Continue: + return std::ops::ControlFlow::Continue(c.into()); + } + Ok(RSR) =3D> u8::from(self.receive_status_error_clear).into(), + Ok(FR) =3D> u16::from(self.flags).into(), + Ok(FBRD) =3D> self.fbrd.into(), + Ok(ILPR) =3D> self.ilpr.into(), + Ok(IBRD) =3D> self.ibrd.into(), + Ok(LCR_H) =3D> u16::from(self.line_control).into(), + Ok(CR) =3D> { + // We exercise our self-control. + u16::from(self.control).into() + } + Ok(FLS) =3D> self.ifl.into(), + Ok(IMSC) =3D> self.int_enabled.into(), + Ok(RIS) =3D> self.int_level.into(), + Ok(MIS) =3D> u64::from(self.int_level & self.int_enabled), + Ok(ICR) =3D> { + // "The UARTICR Register is the interrupt clear register a= nd is write-only" + // Source: ARM DDI 0183G 3.3.13 Interrupt Clear Register, = UARTICR + 0 + } + Ok(DMACR) =3D> self.dmacr.into(), + }) + } + + pub fn write(&mut self, offset: hwaddr, value: u64) { + // eprintln!("write offset {offset} value {value}"); + use RegisterOffset::*; + let value: u32 =3D value as u32; + match RegisterOffset::try_from(offset) { + Err(_bad_offset) =3D> { + eprintln!("write bad offset {offset} value {value}"); + } + Ok(DR) =3D> { + // ??? Check if transmitter is enabled. + let ch: u8 =3D value as u8; + // XXX this blocks entire thread. Rewrite to use + // qemu_chr_fe_write and background I/O callbacks + + // SAFETY: self.char_backend is a valid CharBackend instan= ce after it's been + // initialized in realize(). + unsafe { + qemu_chr_fe_write_all(addr_of_mut!(self.char_backend),= &ch, 1); + } + self.loopback_tx(value); + self.int_level |=3D registers::INT_TX; + self.update(); + } + Ok(RSR) =3D> { + self.receive_status_error_clear =3D 0.into(); + } + Ok(FR) =3D> { + // flag writes are ignored + } + Ok(ILPR) =3D> { + self.ilpr =3D value; + } + Ok(IBRD) =3D> { + self.ibrd =3D value; + } + Ok(FBRD) =3D> { + self.fbrd =3D value; + } + Ok(LCR_H) =3D> { + let value =3D value as u16; + let new_val: registers::LineControl =3D value.into(); + // Reset the FIFO state on FIFO enable or disable + if bool::from(self.line_control.fifos_enabled()) + ^ bool::from(new_val.fifos_enabled()) + { + self.reset_fifo(); + } + if self.line_control.send_break() ^ new_val.send_break() { + let mut break_enable: c_int =3D new_val.send_break().i= nto(); + // SAFETY: self.char_backend is a valid CharBackend in= stance after it's been + // initialized in realize(). + unsafe { + qemu_chr_fe_ioctl( + addr_of_mut!(self.char_backend), + CHR_IOCTL_SERIAL_SET_BREAK as i32, + addr_of_mut!(break_enable).cast::(), + ); + } + self.loopback_break(break_enable > 0); + } + self.line_control =3D new_val; + self.set_read_trigger(); + } + Ok(CR) =3D> { + // ??? Need to implement the enable bit. + let value =3D value as u16; + self.control =3D value.into(); + self.loopback_mdmctrl(); + } + Ok(FLS) =3D> { + self.ifl =3D value; + self.set_read_trigger(); + } + Ok(IMSC) =3D> { + self.int_enabled =3D value; + self.update(); + } + Ok(RIS) =3D> {} + Ok(MIS) =3D> {} + Ok(ICR) =3D> { + self.int_level &=3D !value; + self.update(); + } + Ok(DMACR) =3D> { + self.dmacr =3D value; + if value & 3 > 0 { + // qemu_log_mask(LOG_UNIMP, "pl011: DMA not implemente= d\n"); + eprintln!("pl011: DMA not implemented"); + } + } + } + } + + #[inline] + fn loopback_tx(&mut self, value: u32) { + if !self.loopback_enabled() { + return; + } + + // Caveat: + // + // In real hardware, TX loopback happens at the serial-bit level + // and then reassembled by the RX logics back into bytes and placed + // into the RX fifo. That is, loopback happens after TX fifo. + // + // Because the real hardware TX fifo is time-drained at the frame + // rate governed by the configured serial format, some loopback + // bytes in TX fifo may still be able to get into the RX fifo + // that could be full at times while being drained at software + // pace. + // + // In such scenario, the RX draining pace is the major factor + // deciding which loopback bytes get into the RX fifo, unless + // hardware flow-control is enabled. + // + // For simplicity, the above described is not emulated. + self.put_fifo(value); + } + + fn loopback_mdmctrl(&mut self) { + if !self.loopback_enabled() { + return; + } + + /* + * Loopback software-driven modem control outputs to modem status = inputs: + * FR.RI <=3D CR.Out2 + * FR.DCD <=3D CR.Out1 + * FR.CTS <=3D CR.RTS + * FR.DSR <=3D CR.DTR + * + * The loopback happens immediately even if this call is triggered + * by setting only CR.LBE. + * + * CTS/RTS updates due to enabled hardware flow controls are not + * dealt with here. + */ + + //fr =3D s->flags & ~(PL011_FLAG_RI | PL011_FLAG_DCD | + // PL011_FLAG_DSR | PL011_FLAG_CTS); + //fr |=3D (cr & CR_OUT2) ? PL011_FLAG_RI : 0; + //fr |=3D (cr & CR_OUT1) ? PL011_FLAG_DCD : 0; + //fr |=3D (cr & CR_RTS) ? PL011_FLAG_CTS : 0; + //fr |=3D (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()); + self.flags + .set_data_set_ready(self.control.data_transmit_ready()); + + // Change interrupts based on updated FR + let mut il =3D self.int_level; + + il &=3D !Interrupt::MS; + //il |=3D (fr & PL011_FLAG_DSR) ? INT_DSR : 0; + //il |=3D (fr & PL011_FLAG_DCD) ? INT_DCD : 0; + //il |=3D (fr & PL011_FLAG_CTS) ? INT_CTS : 0; + //il |=3D (fr & PL011_FLAG_RI) ? INT_RI : 0; + + if self.flags.data_set_ready() { + il |=3D Interrupt::DSR as u32; + } + if self.flags.data_carrier_detect() { + il |=3D Interrupt::DCD as u32; + } + if self.flags.clear_to_send() { + il |=3D Interrupt::CTS as u32; + } + if self.flags.ring_indicator() { + il |=3D Interrupt::RI as u32; + } + self.int_level =3D il; + self.update(); + } + + fn loopback_break(&mut self, enable: bool) { + if enable { + self.loopback_tx(DATA_BREAK); + } + } + + fn set_read_trigger(&mut self) { + self.read_trigger =3D 1; + } + + pub fn realize(&mut self) { + // SAFETY: self.char_backend has the correct size and alignment fo= r 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::(), + core::ptr::null_mut(), + true, + ); + } + } + + pub fn reset(&mut self) { + self.line_control.reset(); + self.receive_status_error_clear.reset(); + self.dmacr =3D 0; + self.int_enabled =3D 0; + self.int_level =3D 0; + self.ilpr =3D 0; + self.ibrd =3D 0; + self.fbrd =3D 0; + self.read_trigger =3D 1; + self.ifl =3D 0x12; + self.control.reset(); + self.flags =3D 0.into(); + self.reset_fifo(); + } + + pub fn reset_fifo(&mut self) { + self.read_count =3D 0; + self.read_pos =3D 0; + + /* Reset FIFO flags */ + self.flags.reset(); + } + + pub fn can_receive(&self) -> bool { + // trace_pl011_can_receive(s->lcr, s->read_count, r); + self.read_count < self.fifo_depth() + } + + pub fn event(&mut self, event: QEMUChrEvent) { + if event =3D=3D bindings::QEMUChrEvent::CHR_EVENT_BREAK && !self.f= ifo_enabled() { + self.put_fifo(DATA_BREAK); + self.receive_status_error_clear.set_break_error(true); + } + } + + #[inline] + pub fn fifo_enabled(&self) -> bool { + matches!(self.line_control.fifos_enabled(), registers::Mode::FIFO) + } + + #[inline] + pub fn loopback_enabled(&self) -> bool { + self.control.enable_loopback() + } + + #[inline] + pub fn fifo_depth(&self) -> usize { + // Note: FIFO depth is expected to be power-of-2 + if self.fifo_enabled() { + return PL011_FIFO_DEPTH; + } + 1 + } + + pub fn put_fifo(&mut self, value: c_uint) { + let depth =3D self.fifo_depth(); + assert!(depth > 0); + let slot =3D (self.read_pos + self.read_count) & (depth - 1); + self.read_fifo[slot] =3D value; + self.read_count +=3D 1; + // s->flags &=3D ~PL011_FLAG_RXFE; + self.flags.set_receive_fifo_empty(false); + if self.read_count =3D=3D depth { + //s->flags |=3D PL011_FLAG_RXFF; + self.flags.set_receive_fifo_full(true); + } + + if self.read_count =3D=3D self.read_trigger { + self.int_level |=3D registers::INT_RX; + self.update(); + } + } + + pub fn update(&self) { + let flags =3D self.int_level & self.int_enabled; + for (irq, i) in self.interrupts.iter().zip(IRQMASK) { + // SAFETY: self.interrupts have been initialized in init(). + unsafe { qemu_set_irq(*irq, i32::from(flags & i !=3D 0)) }; + } + } +} + +/// Which bits in the interrupt status matter for each outbound IRQ line ? +pub const IRQMASK: [u32; 6] =3D [ + /* combined IRQ */ + Interrupt::E + | Interrupt::MS + | Interrupt::RT as u32 + | Interrupt::TX as u32 + | Interrupt::RX as u32, + Interrupt::RX as u32, + Interrupt::TX as u32, + Interrupt::RT as u32, + Interrupt::MS, + Interrupt::E, +]; + +/// # 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 =3D NonNull::new_unchecked(opaque.cast::()); + 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 =3D NonNull::new_unchecked(opaque.cast::= ()); + 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 =3D NonNull::new_unchecked(opaque.cast::= ()); + state.as_mut().event(event) + } +} + +/// # Safety +/// +/// We expect the FFI user of this function to pass a valid pointer for `c= hr`. +#[no_mangle] +pub unsafe extern "C" fn pl011_create( + addr: u64, + irq: qemu_irq, + chr: *mut Chardev, +) -> *mut DeviceState { + unsafe { + let dev: *mut DeviceState =3D qdev_new(PL011State::TYPE_INFO.name); + let sysbus: *mut SysBusDevice =3D dev.cast::(); + + qdev_prop_set_chr(dev, bindings::TYPE_CHARDEV.as_ptr(), chr); + sysbus_realize_and_unref(sysbus, addr_of!(error_fatal) as *mut *mu= t Error); + sysbus_mmio_map(sysbus, 0, addr); + sysbus_connect_irq(sysbus, 0, irq); + 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 =3D NonNull::new_unchecked(obj.cast::()); + state.as_mut().init(); + } +} diff --git a/rust/hw/char/pl011/src/device_class.rs b/rust/hw/char/pl011/sr= c/device_class.rs new file mode 100644 index 00000000000..b7ab31af02d --- /dev/null +++ b/rust/hw/char/pl011/src/device_class.rs @@ -0,0 +1,70 @@ +// Copyright 2024, Linaro Limited +// Author(s): Manos Pitsidianakis +// SPDX-License-Identifier: GPL-2.0-or-later + +use core::ptr::NonNull; + +use qemu_api::{bindings::*, definitions::ObjectImpl}; + +use crate::device::PL011State; + +#[used] +pub static VMSTATE_PL011: VMStateDescription =3D VMStateDescription { + name: PL011State::TYPE_INFO.name, + unmigratable: true, + ..unsafe { ::core::mem::MaybeUninit::::zeroed().as= sume_init() } +}; + +qemu_api::declare_properties! { + PL011_PROPERTIES, + qemu_api::define_property!( + c"chardev", + PL011State, + char_backend, + unsafe { &qdev_prop_chr }, + CharBackend + ), + qemu_api::define_property!( + c"migrate-clk", + PL011State, + migrate_clock, + unsafe { &qdev_prop_bool }, + bool + ), +} + +qemu_api::device_class_init! { + pl011_class_init, + props =3D> PL011_PROPERTIES, + realize_fn =3D> Some(pl011_realize), + legacy_reset_fn =3D> Some(pl011_reset), + vmsd =3D> VMSTATE_PL011, +} + +/// # 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_realize(dev: *mut DeviceState, _errp: *mut = *mut Error) { + unsafe { + assert!(!dev.is_null()); + let mut state =3D NonNull::new_unchecked(dev.cast::()); + state.as_mut().realize(); + } +} + +/// # 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_reset(dev: *mut DeviceState) { + unsafe { + assert!(!dev.is_null()); + let mut state =3D NonNull::new_unchecked(dev.cast::()); + state.as_mut().reset(); + } +} diff --git a/rust/hw/char/pl011/src/lib.rs b/rust/hw/char/pl011/src/lib.rs new file mode 100644 index 00000000000..2939ee50c99 --- /dev/null +++ b/rust/hw/char/pl011/src/lib.rs @@ -0,0 +1,586 @@ +// Copyright 2024, Linaro Limited +// Author(s): Manos Pitsidianakis +// SPDX-License-Identifier: GPL-2.0-or-later +// +// PL011 QEMU Device Model +// +// This library implements a device model for the PrimeCell=C2=AE UART (PL= 011) +// device in QEMU. +// +#![doc =3D include_str!("../README.md")] +//! # Library crate +//! +//! See [`PL011State`](crate::device::PL011State) for the device model typ= e and +//! the [`registers`] module for register types. + +#![deny( + rustdoc::broken_intra_doc_links, + rustdoc::redundant_explicit_links, + clippy::correctness, + clippy::suspicious, + clippy::complexity, + clippy::perf, + clippy::cargo, + clippy::nursery, + clippy::style, + // restriction group + clippy::dbg_macro, + clippy::as_underscore, + clippy::assertions_on_result_states, + // pedantic group + clippy::doc_markdown, + clippy::borrow_as_ptr, + clippy::cast_lossless, + clippy::option_if_let_else, + clippy::missing_const_for_fn, + clippy::cognitive_complexity, + clippy::missing_safety_doc, + )] + +extern crate bilge; +extern crate bilge_impl; +extern crate qemu_api; + +pub mod device; +pub mod device_class; +pub mod memory_ops; + +pub const TYPE_PL011: &::core::ffi::CStr =3D c"pl011"; + +/// Offset of each register from the base memory address of the device. +/// +/// # Source +/// ARM DDI 0183G, Table 3-1 p.3-3 +#[doc(alias =3D "offset")] +#[allow(non_camel_case_types)] +#[repr(u64)] +#[derive(Debug)] +pub enum RegisterOffset { + /// Data Register + /// + /// A write to this register initiates the actual data transmission + #[doc(alias =3D "UARTDR")] + DR =3D 0x000, + /// Receive Status Register or Error Clear Register + #[doc(alias =3D "UARTRSR")] + #[doc(alias =3D "UARTECR")] + RSR =3D 0x004, + /// Flag Register + /// + /// A read of this register shows if transmission is complete + #[doc(alias =3D "UARTFR")] + FR =3D 0x018, + /// Fractional Baud Rate Register + /// + /// responsible for baud rate speed + #[doc(alias =3D "UARTFBRD")] + FBRD =3D 0x028, + /// `IrDA` Low-Power Counter Register + #[doc(alias =3D "UARTILPR")] + ILPR =3D 0x020, + /// Integer Baud Rate Register + /// + /// Responsible for baud rate speed + #[doc(alias =3D "UARTIBRD")] + IBRD =3D 0x024, + /// line control register (data frame format) + #[doc(alias =3D "UARTLCR_H")] + LCR_H =3D 0x02C, + /// Toggle UART, transmission or reception + #[doc(alias =3D "UARTCR")] + CR =3D 0x030, + /// Interrupt FIFO Level Select Register + #[doc(alias =3D "UARTIFLS")] + FLS =3D 0x034, + /// Interrupt Mask Set/Clear Register + #[doc(alias =3D "UARTIMSC")] + IMSC =3D 0x038, + /// Raw Interrupt Status Register + #[doc(alias =3D "UARTRIS")] + RIS =3D 0x03C, + /// Masked Interrupt Status Register + #[doc(alias =3D "UARTMIS")] + MIS =3D 0x040, + /// Interrupt Clear Register + #[doc(alias =3D "UARTICR")] + ICR =3D 0x044, + /// DMA control Register + #[doc(alias =3D "UARTDMACR")] + DMACR =3D 0x048, + ///// Reserved, offsets `0x04C` to `0x07C`. + //Reserved =3D 0x04C, +} + +impl core::convert::TryFrom for RegisterOffset { + type Error =3D u64; + + fn try_from(value: u64) -> Result { + macro_rules! case { + ($($discriminant:ident),*$(,)*) =3D> { + /* check that matching on all macro arguments compiles, wh= ich means we are not + * missing any enum value; if the type definition ever cha= nges this will stop + * compiling. + */ + const fn _assert_exhaustive(val: RegisterOffset) { + match val { + $(RegisterOffset::$discriminant =3D> (),)* + } + } + + match value { + $(x if x =3D=3D Self::$discriminant as u64 =3D> Ok(Sel= f::$discriminant),)* + _ =3D> Err(value), + } + } + } + case! { DR, RSR, FR, FBRD, ILPR, IBRD, LCR_H, CR, FLS, IMSC, RIS, = MIS, ICR, DMACR } + } +} + +pub mod registers { + //! Device registers exposed as typed structs which are backed by arbi= trary + //! integer bitmaps. [`Data`], [`Control`], [`LineControl`], etc. + //! + //! All PL011 registers are essentially 32-bit wide, but are typed her= e as + //! bitmaps with only the necessary width. That is, if a struct bitmap + //! in this module is for example 16 bits long, it should be conceived + //! as a 32-bit register where the unmentioned higher bits are always + //! unused thus treated as zero when read or written. + use bilge::prelude::*; + + // TODO: FIFO Mode has different semantics + /// Data Register, `UARTDR` + /// + /// The `UARTDR` register is the data register. + /// + /// For words to be transmitted: + /// + /// - if the FIFOs are enabled, data written to this location is pushe= d onto + /// the transmit + /// FIFO + /// - if the FIFOs are not enabled, data is stored in the transmitter + /// holding register (the + /// bottom word of the transmit FIFO). + /// + /// The write operation initiates transmission from the UART. The data= is + /// prefixed with a start bit, appended with the appropriate parity bit + /// (if parity is enabled), and a stop bit. The resultant word is then + /// transmitted. + /// + /// For received words: + /// + /// - if the FIFOs are enabled, the data byte and the 4-bit status (br= eak, + /// frame, parity, + /// and overrun) is pushed onto the 12-bit wide receive FIFO + /// - if the FIFOs are not enabled, the data byte and status are store= d in + /// the receiving + /// holding register (the bottom word of the receive FIFO). + /// + /// The received data byte is read by performing reads from the `UARTD= R` + /// register along with the corresponding status information. The stat= us + /// information can also be read by a read of the `UARTRSR/UARTECR` + /// register. + /// + /// # Note + /// + /// 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 befo= re + /// stopping. + /// + /// # Source + /// ARM DDI 0183G 3.3.1 Data Register, UARTDR + #[bitsize(16)] + #[derive(Clone, Copy, DebugBits, FromBits)] + #[doc(alias =3D "UARTDR")] + pub struct Data { + _reserved: u4, + pub data: u8, + pub framing_error: bool, + pub parity_error: bool, + pub break_error: bool, + pub overrun_error: bool, + } + + // TODO: FIFO Mode has different semantics + /// Receive Status Register / Error Clear Register, `UARTRSR/UARTECR` + /// + /// The UARTRSR/UARTECR register is the receive status register/error = clear + /// register. Receive status can also be read from the `UARTRSR` + /// register. If the status is read from this register, then the status + /// information for break, framing and parity corresponds to the + /// data character read from the [Data register](Data), `UARTDR` prior= to + /// reading the UARTRSR register. The status information for overrun is + /// set immediately when an overrun condition occurs. + /// + /// + /// # Note + /// The received data character must be read first from the [Data + /// Register](Data), `UARTDR` before reading the error status associat= ed + /// with that data character from the `UARTRSR` register. This read + /// sequence cannot be reversed, because the `UARTRSR` register is + /// updated only when a read occurs from the `UARTDR` register. Howeve= r, + /// the status information can also be obtained by reading the `UARTDR` + /// register + /// + /// # Source + /// ARM DDI 0183G 3.3.2 Receive Status Register/Error Clear Register, + /// UARTRSR/UARTECR + #[bitsize(8)] + #[derive(Clone, Copy, DebugBits, FromBits)] + pub struct ReceiveStatusErrorClear { + pub framing_error: bool, + pub parity_error: bool, + pub break_error: bool, + pub overrun_error: bool, + _reserved_unpredictable: u4, + } + + impl ReceiveStatusErrorClear { + pub fn reset(&mut self) { + // All the bits are cleared to 0 on reset. + *self =3D 0.into(); + } + } + + impl Default for ReceiveStatusErrorClear { + fn default() -> Self { + 0.into() + } + } + + #[bitsize(16)] + #[derive(Clone, Copy, DebugBits, FromBits)] + /// Flag Register, `UARTFR` + #[doc(alias =3D "UARTFR")] + pub struct Flags { + /// CTS Clear to send. This bit is the complement of the UART clea= r to + /// send, `nUARTCTS`, modem status input. That is, the bit is 1 + /// when `nUARTCTS` is LOW. + pub clear_to_send: bool, + /// DSR Data set ready. This bit is the complement of the UART dat= a set + /// ready, `nUARTDSR`, modem status input. That is, the bit is 1 w= hen + /// `nUARTDSR` is LOW. + pub data_set_ready: bool, + /// DCD Data carrier detect. This bit is the complement of the UAR= T data + /// carrier detect, `nUARTDCD`, modem status input. That is, the b= it is + /// 1 when `nUARTDCD` is LOW. + pub data_carrier_detect: bool, + /// BUSY UART busy. If this bit is set to 1, the UART is busy + /// transmitting data. This bit remains set until the complete + /// byte, including all the stop bits, has been sent from the + /// shift register. This bit is set as soon as the transmit FIFO + /// becomes non-empty, regardless of whether the UART is enabled + /// or not. + pub busy: bool, + /// RXFE Receive FIFO empty. The meaning of this bit depends on the + /// state of the FEN bit in the UARTLCR_H register. If the FIFO + /// is disabled, this bit is set when the receive holding + /// register is empty. If the FIFO is enabled, the RXFE bit is + /// set when the receive FIFO is empty. + pub receive_fifo_empty: bool, + /// TXFF Transmit FIFO full. The meaning of this bit depends on the + /// state of the FEN bit in the UARTLCR_H register. If the FIFO + /// is disabled, this bit is set when the transmit holding + /// register is full. If the FIFO is enabled, the TXFF bit is + /// set when the transmit FIFO is full. + pub transmit_fifo_full: bool, + /// RXFF Receive FIFO full. The meaning of this bit depends on the= state + /// of the FEN bit in the UARTLCR_H register. If the FIFO is + /// disabled, this bit is set when the receive holding register + /// is full. If the FIFO is enabled, the RXFF bit is set when + /// the receive FIFO is full. + pub receive_fifo_full: bool, + /// Transmit FIFO empty. The meaning of this bit depends on the st= ate of + /// the FEN bit in the [Line Control register](LineControl), + /// `UARTLCR_H`. If the FIFO is disabled, this bit is set when the + /// transmit holding register is empty. If the FIFO is enabled, + /// the TXFE bit is set when the transmit FIFO is empty. This + /// bit does not indicate if there is data in the transmit shift + /// register. + pub transmit_fifo_empty: bool, + /// `RI`, is `true` when `nUARTRI` is `LOW`. + pub ring_indicator: bool, + _reserved_zero_no_modify: u7, + } + + impl Flags { + pub fn reset(&mut self) { + // After reset TXFF, RXFF, and BUSY are 0, and TXFE and RXFE a= re 1 + self.set_receive_fifo_full(false); + self.set_transmit_fifo_full(false); + self.set_busy(false); + self.set_receive_fifo_empty(true); + self.set_transmit_fifo_empty(true); + } + } + + impl Default for Flags { + fn default() -> Self { + let mut ret: Self =3D 0.into(); + ret.reset(); + ret + } + } + + #[bitsize(16)] + #[derive(Clone, Copy, DebugBits, FromBits)] + /// Line Control Register, `UARTLCR_H` + #[doc(alias =3D "UARTLCR_H")] + pub struct LineControl { + /// 15:8 - Reserved, do not modify, read as zero. + _reserved_zero_no_modify: u8, + /// 7 SPS Stick parity select. + /// 0 =3D stick parity is disabled + /// 1 =3D either: + /// =E2=80=A2 if the EPS bit is 0 then the parity bit is transmitt= ed and checked + /// as a 1 =E2=80=A2 if the EPS bit is 1 then the parity bit is + /// transmitted and checked as a 0. This bit has no effect when + /// the PEN bit disables parity checking and generation. See Table= 3-11 + /// on page 3-14 for the parity truth table. + pub sticky_parity: bool, + /// WLEN Word length. These bits indicate the number of data bits + /// transmitted or received in a frame as follows: b11 =3D 8 bits + /// b10 =3D 7 bits + /// b01 =3D 6 bits + /// b00 =3D 5 bits. + pub word_length: WordLength, + /// FEN Enable FIFOs: + /// 0 =3D FIFOs are disabled (character mode) that is, the FIFOs b= ecome + /// 1-byte-deep holding registers 1 =3D transmit and receive FIFO + /// buffers are enabled (FIFO mode). + pub fifos_enabled: Mode, + /// 3 STP2 Two stop bits select. If this bit is set to 1, two stop= bits + /// are transmitted at the end of the frame. The receive + /// logic does not check for two stop bits being received. + pub two_stops_bits: bool, + /// EPS Even parity select. Controls the type of parity the UART u= ses + /// during transmission and reception: + /// - 0 =3D odd parity. The UART generates or checks for an odd nu= mber of + /// 1s in the data and parity bits. + /// - 1 =3D even parity. The UART generates or checks for an even = number + /// of 1s in the data and parity bits. + /// This bit has no effect when the `PEN` bit disables parity chec= king + /// and generation. See Table 3-11 on page 3-14 for the parity + /// truth table. + pub parity: Parity, + /// 1 PEN Parity enable: + /// + /// - 0 =3D parity is disabled and no parity bit added to the data= frame + /// - 1 =3D parity checking and generation is enabled. + /// + /// See Table 3-11 on page 3-14 for the parity truth table. + pub parity_enabled: bool, + /// BRK Send break. + /// + /// If this bit is set to `1`, a low-level is continually output o= n the + /// `UARTTXD` output, after completing transmission of the + /// current character. For the proper execution of the break comma= nd, + /// the software must set this bit for at least two complete + /// frames. For normal use, this bit must be cleared to `0`. + pub send_break: bool, + } + + impl LineControl { + pub fn reset(&mut self) { + // All the bits are cleared to 0 when reset. + *self =3D 0.into(); + } + } + + impl Default for LineControl { + fn default() -> Self { + 0.into() + } + } + + #[bitsize(1)] + #[derive(Clone, Copy, Debug, Eq, FromBits, PartialEq)] + /// `EPS` "Even parity select", field of [Line Control + /// register](LineControl). + pub enum Parity { + /// - 0 =3D odd parity. The UART generates or checks for an odd nu= mber of + /// 1s in the data and parity bits. + Odd =3D 0, + /// - 1 =3D even parity. The UART generates or checks for an even = number + /// of 1s in the data and parity bits. + Even =3D 1, + } + + #[bitsize(1)] + #[derive(Clone, Copy, Debug, Eq, FromBits, PartialEq)] + /// `FEN` "Enable FIFOs" or Device mode, field of [Line Control + /// register](LineControl). + pub enum Mode { + /// 0 =3D FIFOs are disabled (character mode) that is, the FIFOs b= ecome + /// 1-byte-deep holding registers + Character =3D 0, + /// 1 =3D transmit and receive FIFO buffers are enabled (FIFO mode= ). + FIFO =3D 1, + } + + impl From for bool { + fn from(val: Mode) -> Self { + matches!(val, Mode::FIFO) + } + } + + #[bitsize(2)] + #[derive(Clone, Copy, Debug, Eq, FromBits, PartialEq)] + /// `WLEN` Word length, field of [Line Control register](LineControl). + /// + /// These bits indicate the number of data bits transmitted or receive= d in a + /// frame as follows: + pub enum WordLength { + /// b11 =3D 8 bits + _8Bits =3D 0b11, + /// b10 =3D 7 bits + _7Bits =3D 0b10, + /// b01 =3D 6 bits + _6Bits =3D 0b01, + /// b00 =3D 5 bits. + _5Bits =3D 0b00, + } + + /// Control Register, `UARTCR` + /// + /// The `UARTCR` register is the control register. All the bits are cl= eared + /// to `0` on reset except for bits `9` and `8` that are set to `1`. + /// + /// # Source + /// ARM DDI 0183G, 3.3.8 Control Register, `UARTCR`, Table 3-12 + #[bitsize(16)] + #[doc(alias =3D "UARTCR")] + #[derive(Clone, Copy, DebugBits, FromBits)] + pub struct Control { + /// `UARTEN` UART enable: 0 =3D UART is disabled. If the UART is d= isabled + /// in the middle of transmission or reception, it completes the c= urrent + /// character before stopping. 1 =3D the UART is enabled. Data + /// transmission and reception occurs for either UART signals or S= IR + /// signals depending on the setting of the SIREN bit. + pub enable_uart: bool, + /// `SIREN` `SIR` enable: 0 =3D IrDA SIR ENDEC is disabled. `nSIRO= UT` + /// remains LOW (no light pulse generated), and signal transitions= on + /// SIRIN have no effect. 1 =3D IrDA SIR ENDEC is enabled. Data is + /// transmitted and received on nSIROUT and SIRIN. UARTTXD remains= HIGH, + /// in the marking state. Signal transitions on UARTRXD or modem s= tatus + /// inputs have no effect. This bit has no effect if the UARTEN bit + /// disables the UART. + pub enable_sir: bool, + /// `SIRLP` SIR low-power IrDA mode. This bit selects the IrDA enc= oding + /// mode. If this bit is cleared to 0, low-level bits are transmit= ted as + /// an active high pulse with a width of 3/ 16th of the bit period= . If + /// this bit is set to 1, low-level bits are transmitted with a pu= lse + /// width that is 3 times the period of the IrLPBaud16 input signa= l, + /// regardless of the selected bit rate. Setting this bit uses less + /// power, but might reduce transmission distances. + pub sir_lowpower_irda_mode: u1, + /// Reserved, do not modify, read as zero. + _reserved_zero_no_modify: u4, + /// `LBE` Loopback enable. If this bit is set to 1 and the SIREN b= it is + /// set to 1 and the SIRTEST bit in the Test Control register, UAR= TTCR + /// on page 4-5 is set to 1, then the nSIROUT path is inverted, an= d fed + /// through to the SIRIN path. The SIRTEST bit in the test registe= r must + /// be set to 1 to override the normal half-duplex SIR operation. = This + /// must be the requirement for accessing the test registers during + /// normal operation, and SIRTEST must be cleared to 0 when loopba= ck + /// testing is finished. This feature reduces the amount of extern= al + /// coupling required during system test. If this bit is set to 1,= and + /// the SIRTEST bit is set to 0, the UARTTXD path is fed through t= o the + /// UARTRXD path. In either SIR mode or UART mode, when this bit i= s set, + /// the modem outputs are also fed through to the modem inputs. Th= is bit + /// is cleared to 0 on reset, to disable loopback. + pub enable_loopback: bool, + /// `TXE` Transmit enable. If this bit is set to 1, the transmit s= ection + /// of the UART is enabled. Data transmission occurs for either UA= RT + /// signals, or SIR signals depending on the setting of the SIREN = bit. + /// When the UART is disabled in the middle of transmission, it + /// completes the current character before stopping. + pub enable_transmit: bool, + /// `RXE` Receive enable. If this bit is set to 1, the receive sec= tion + /// of the UART is enabled. Data reception occurs for either UART + /// signals or SIR signals depending on the setting of the SIREN b= it. + /// When the UART is disabled in the middle of reception, it compl= etes + /// the current character before stopping. + pub enable_receive: bool, + /// `DTR` Data transmit ready. This bit is the complement of the U= ART + /// data transmit ready, `nUARTDTR`, modem status output. That is,= when + /// the bit is programmed to a 1 then `nUARTDTR` is LOW. + pub data_transmit_ready: bool, + /// `RTS` Request to send. This bit is the complement of the UART + /// request to send, `nUARTRTS`, modem status output. That is, whe= n the + /// bit is programmed to a 1 then `nUARTRTS` is LOW. + pub request_to_send: bool, + /// `Out1` This bit is the complement of the UART Out1 (`nUARTOut1= `) + /// modem status output. That is, when the bit is programmed to a = 1 the + /// output is 0. For DTE this can be used as Data Carrier Detect (= DCD). + pub out_1: bool, + /// `Out2` This bit is the complement of the UART Out2 (`nUARTOut2= `) + /// modem status output. That is, when the bit is programmed to a = 1, the + /// output is 0. For DTE this can be used as Ring Indicator (RI). + pub out_2: bool, + /// `RTSEn` RTS hardware flow control enable. If this bit is set t= o 1, + /// RTS hardware flow control is enabled. Data is only requested w= hen + /// there is space in the receive FIFO for it to be received. + pub rts_hardware_flow_control_enable: bool, + /// `CTSEn` CTS hardware flow control enable. If this bit is set t= o 1, + /// CTS hardware flow control is enabled. Data is only transmitted= when + /// the `nUARTCTS` signal is asserted. + pub cts_hardware_flow_control_enable: bool, + } + + impl Control { + pub fn reset(&mut self) { + *self =3D 0.into(); + self.set_enable_receive(true); + self.set_enable_transmit(true); + } + } + + impl Default for Control { + fn default() -> Self { + let mut ret: Self =3D 0.into(); + ret.reset(); + ret + } + } + + /// Interrupt status bits in UARTRIS, UARTMIS, UARTIMSC + pub const INT_OE: u32 =3D 1 << 10; + pub const INT_BE: u32 =3D 1 << 9; + pub const INT_PE: u32 =3D 1 << 8; + pub const INT_FE: u32 =3D 1 << 7; + pub const INT_RT: u32 =3D 1 << 6; + pub const INT_TX: u32 =3D 1 << 5; + pub const INT_RX: u32 =3D 1 << 4; + pub const INT_DSR: u32 =3D 1 << 3; + pub const INT_DCD: u32 =3D 1 << 2; + pub const INT_CTS: u32 =3D 1 << 1; + pub const INT_RI: u32 =3D 1 << 0; + pub const INT_E: u32 =3D INT_OE | INT_BE | INT_PE | INT_FE; + pub const INT_MS: u32 =3D INT_RI | INT_DSR | INT_DCD | INT_CTS; + + #[repr(u32)] + pub enum Interrupt { + OE =3D 1 << 10, + BE =3D 1 << 9, + PE =3D 1 << 8, + FE =3D 1 << 7, + RT =3D 1 << 6, + TX =3D 1 << 5, + RX =3D 1 << 4, + DSR =3D 1 << 3, + DCD =3D 1 << 2, + CTS =3D 1 << 1, + RI =3D 1 << 0, + } + + impl Interrupt { + pub const E: u32 =3D INT_OE | INT_BE | INT_PE | INT_FE; + pub const MS: u32 =3D INT_RI | INT_DSR | INT_DCD | INT_CTS; + } +} + +// 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 diff --git a/rust/hw/char/pl011/src/memory_ops.rs b/rust/hw/char/pl011/src/= memory_ops.rs new file mode 100644 index 00000000000..8d066ebf6d0 --- /dev/null +++ b/rust/hw/char/pl011/src/memory_ops.rs @@ -0,0 +1,59 @@ +// Copyright 2024, Linaro Limited +// Author(s): Manos Pitsidianakis +// SPDX-License-Identifier: GPL-2.0-or-later + +use core::{mem::MaybeUninit, ptr::NonNull}; + +use qemu_api::bindings::*; + +use crate::device::PL011State; + +pub static PL011_OPS: MemoryRegionOps =3D MemoryRegionOps { + read: Some(pl011_read), + write: Some(pl011_write), + read_with_attrs: None, + write_with_attrs: None, + endianness: device_endian::DEVICE_NATIVE_ENDIAN, + valid: unsafe { MaybeUninit::::zeroed()= .assume_init() }, + impl_: MemoryRegionOps__bindgen_ty_2 { + min_access_size: 4, + max_access_size: 4, + ..unsafe { MaybeUninit::::zeroed().= assume_init() } + }, +}; + +#[no_mangle] +unsafe extern "C" fn pl011_read( + opaque: *mut core::ffi::c_void, + addr: hwaddr, + size: core::ffi::c_uint, +) -> u64 { + assert!(!opaque.is_null()); + let mut state =3D unsafe { NonNull::new_unchecked(opaque.cast::()) }; + let val =3D unsafe { state.as_mut().read(addr, size) }; + match val { + std::ops::ControlFlow::Break(val) =3D> val, + std::ops::ControlFlow::Continue(val) =3D> { + // SAFETY: self.char_backend is a valid CharBackend instance a= fter it's been + // initialized in realize(). + let cb_ptr =3D unsafe { core::ptr::addr_of_mut!(state.as_mut()= .char_backend) }; + unsafe { qemu_chr_fe_accept_input(cb_ptr) }; + + val + } + } +} + +#[no_mangle] +unsafe extern "C" fn pl011_write( + opaque: *mut core::ffi::c_void, + addr: hwaddr, + data: u64, + _size: core::ffi::c_uint, +) { + unsafe { + assert!(!opaque.is_null()); + let mut state =3D NonNull::new_unchecked(opaque.cast::= ()); + state.as_mut().write(addr, data) + } +} diff --git a/rust/hw/meson.build b/rust/hw/meson.build new file mode 100644 index 00000000000..860196645e7 --- /dev/null +++ b/rust/hw/meson.build @@ -0,0 +1 @@ +subdir('char') diff --git a/rust/meson.build b/rust/meson.build index 7a32b1b1950..def77389cdd 100644 --- a/rust/meson.build +++ b/rust/meson.build @@ -1,2 +1,4 @@ subdir('qemu-api-macros') subdir('qemu-api') + +subdir('hw') diff --git a/scripts/archive-source.sh b/scripts/archive-source.sh index 62a2cf45d28..30677c3ec90 100755 --- a/scripts/archive-source.sh +++ b/scripts/archive-source.sh @@ -27,7 +27,9 @@ sub_file=3D"${sub_tdir}/submodule.tar" # in their checkout, because the build environment is completely # different to the host OS. subprojects=3D"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=3D"" =20 diff --git a/scripts/make-release b/scripts/make-release index cf7d694ef73..8dc939124c4 100755 --- a/scripts/make-release +++ b/scripts/make-release @@ -18,7 +18,9 @@ fi =20 # Only include wraps that are invoked with subproject() SUBPROJECTS=3D"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" =20 src=3D"$1" diff --git a/scripts/rust/rust_root_crate.sh b/scripts/rust/rust_root_crate= .sh new file mode 100755 index 00000000000..975bddf7f1a --- /dev/null +++ b/scripts/rust/rust_root_crate.sh @@ -0,0 +1,13 @@ +#!/bin/sh + +set -eu + +cat <