From patchwork Wed Aug 28 04:11:43 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Manos Pitsidianakis X-Patchwork-Id: 13780498 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id DF06FC5472D for ; Wed, 28 Aug 2024 04:14:34 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1sjA2v-0006Am-CW; Wed, 28 Aug 2024 00:12:37 -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 1sjA2r-0005wU-CP for qemu-devel@nongnu.org; Wed, 28 Aug 2024 00:12:33 -0400 Received: from mail-lj1-x22a.google.com ([2a00:1450:4864:20::22a]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_128_GCM_SHA256:128) (Exim 4.90_1) (envelope-from ) id 1sjA2b-0000lN-44 for qemu-devel@nongnu.org; Wed, 28 Aug 2024 00:12:32 -0400 Received: by mail-lj1-x22a.google.com with SMTP id 38308e7fff4ca-2f3f68dd44bso71360031fa.3 for ; Tue, 27 Aug 2024 21:12:16 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1724818335; x=1725423135; darn=nongnu.org; h=cc:to:in-reply-to:references:message-id:content-transfer-encoding :mime-version:subject:date:from:from:to:cc:subject:date:message-id :reply-to; bh=9WoYTkRlZjZ2IZzUB0XlbV4XpCuF84zvKRFt/cs2e0E=; b=uUmg8zxk7iICXM/rHzrsLZiTVwUpZc/LaogpiInIRxm2TMyQT8fsJnEQUUOrMc/mPM Hr/jtLYjQ9nQP7bH3UmqWnKYyEiEC1RlTwzTLlbgqIt5q1UIVGwZI2VS4QCYxalew1A5 dcgUMtT/RvHAlsFBua68jnRfbFE5iLDiV5A8EfYQycSNRLfLZRtWdQakcdlIpMKu7N4A QjEb92AwSUVdSe451Fb1uzUY5aKXSfMJXRCtMi1U6giWdwWN1ONY04p3Gg3FhlPfPZOA 5mns0sPKn2VOGLEru5moXn5sYMZxSI5bSyxPzykQDn3jQpBFW2N1hKw54vx/5848LneJ dMuw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1724818335; x=1725423135; h=cc:to:in-reply-to:references:message-id:content-transfer-encoding :mime-version:subject:date:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=9WoYTkRlZjZ2IZzUB0XlbV4XpCuF84zvKRFt/cs2e0E=; b=IgbSGsD1ln3zjEUYYt7JgVF8L1iAvn7WcEybOPeoY71Dwz0GmLUv2Ct2xoDXWUBdbZ 8KDbkhBou+99TU/eJRFln/xcoWwndzqzXqjqG2PRVVKVBKv6hrs+q9a5BrvXX+x1UBJR mfMeMc+C4xzWQ4YjjJZJmMVZYkWKreBSZqvxJjSPZyhUwUkTq9L4nO/kmIuDEPYx+ewg S5fWwcTCyqWdiUxPHLukKJv+bbtw80HYA7bt5stMtl4E3HV/Oqea75UU/qXLfeR2epbZ Org1ETfab9q8wcHcExBdTFoXCkuiT+Yed4uDa2IZZpaEbe0/jkO2RZO8W/TMWIcokiKq mUJQ== X-Gm-Message-State: AOJu0Yyt1FWdp6iZC3UwmDRvfWs26izkw1wSY5Wj5tzpGTkCFF5ATDi0 eBP3smurMGElE1J2/esUlk2aJp3pshflhYARXiimOxgyTjSrgShvL1prrXj7szs= X-Google-Smtp-Source: AGHT+IGzVWr2eP+ZnL9PCFFkpa0auntXgXcG10Mtkv6A3g/V+jfXbdDPzO9WOtrKyLdtzsLgze+wDg== X-Received: by 2002:a2e:9ec7:0:b0:2f5:6b4:1d2b with SMTP id 38308e7fff4ca-2f55b68e409mr3487811fa.13.1724818334330; Tue, 27 Aug 2024 21:12:14 -0700 (PDT) Received: from [127.0.1.1] (adsl-98.109.242.227.tellas.gr. [109.242.227.98]) by smtp.gmail.com with ESMTPSA id 4fb4d7f45d1cf-5c0bb1c29b9sm1712814a12.18.2024.08.27.21.12.10 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 27 Aug 2024 21:12:13 -0700 (PDT) From: Manos Pitsidianakis Date: Wed, 28 Aug 2024 07:11:43 +0300 Subject: [PATCH RESEND v9 2/9] build-sys: Add rust feature option MIME-Version: 1.0 Message-Id: <20240828-rust-pl011-v9-2-35579191f17c@linaro.org> References: <20240828-rust-pl011-v9-0-35579191f17c@linaro.org> In-Reply-To: <20240828-rust-pl011-v9-0-35579191f17c@linaro.org> To: qemu-devel@nongnu.org Cc: Paolo Bonzini , =?utf-8?q?Marc-Andr=C3=A9_Lureau?= , =?utf-8?q?Daniel_P=2E_Berrang=C3=A9?= , Thomas Huth , =?utf-8?q?Philippe_Mathieu-Daud=C3=A9?= , Pierrick Bouvier , Richard Henderson , Gustavo Romero , =?utf-8?q?Alex_Benn=C3=A9e?= , Peter Maydell , Junjie Mao , Zhao Liu , Manos Pitsidianakis X-Mailer: b4 0.15-dev-c2c95 X-Developer-Signature: v=1; a=openpgp-sha256; l=5802; i=manos.pitsidianakis@linaro.org; h=from:subject:message-id; bh=Yp49pdC3qe7SuaqJZKWE381hHC9X4adl+M5esNSQkcc=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0VCYlFLUy9aQU5Bd0FLQVhjcHgzQi9mZ 25RQWNzbVlnQm16cU9MSTYyL1QzbGZQREVLNFRqYjhMYXoyYkh1CnFPalc0ZDBJVVRybU02b3Zu N1dKQWpNRUFBRUtBQjBXSVFUTVhCdE9SS0JXODRkd0hSQjNLY2R3ZjM0SjBBVUMKWnM2aml3QUt DUkIzS2Nkd2YzNEowRE0xRUFDV3dJOFYvOG96NFdvK1MwL2NDTFcwbndwYmF5dktjdjNmdHNyTA plNFAzK3RTRGlVM2ovbWMyYjlGcC8xcy9FcCs3dkxNR1ZNUlF2NkNWWHdUNHozZHdCZHhZUklFd Dc1V1RQZEZVCm9adFphUUFQSjN4UlhZcmZ4bjQzTWlSWHRQMTgyNGRjYUU4Rm42KzZmYmN5SWtC YlJRMXBXd3ZCREhQbDZTN0MKNkxucjdZKzJVWFhOWXdYajlMQ0FaNWw4YkhpRTBNcXkreE9Fa2Z NWTQxNUR4N2tqQVpUTU5SVmY4U1JKSmNxMgo5aFJ0c29ZVmZobytxVk9QSm96ZFNGRWtUU2N2aT B4MHQrb2JLNVY5aTV2cGUxK2NudnA5VDA3ZE9zQXVncFMzCmRQQkx2cGQ0Y3RuTHBDM3lvaXFzd TdvOW1TbWlZRE1hMENsQXE0NXkzS3p5d1R5NTUrUnkwMWpCTk5YMUIrUGoKNmNTc2hjTTFtK1R3 MjJYRHRzUWVHaE9mRjlvejZSTFUvSU16S3FPWW1INGRNaE1JZnR6dUdSTndlcEdJUkp5Qgo3U0V keGZkclJjNm1qWUluUkptN1JVQk5UNjV2a2lpVURBbkcrWE9pTlNnV0FuUGM2dGhveklJN2YrSl ZhMXBECnRDUjhrNEFwaEdPNDRQbGRxdmtCVy9IVkJTNWgyeHRTVHZHRWIzU2MzV3hhNE90Q20ze XUvMThrTEYxZnVyVXIKNUh0bHFHd1hNRzg1K0lCUEdLT3Q0TVBuTW9lMUtkUVQvQTNFdjBsUWlI SnBGNEcveksvd2hIWDRvUGRwL29WdgpsTk9MNVo5RDBabEpoSERNRVkwS2VGNWFqRlEwQm9uM0J yQUt6aTRGR0NKdm5YYUoydkM0ZWNuUHYwNy9BR0s4CnVjYkZ6UT09Cj1SOHdnCi0tLS0tRU5EIF BHUCBNRVNTQUdFLS0tLS0K X-Developer-Key: i=manos.pitsidianakis@linaro.org; a=openpgp; fpr=7C721DF9DB3CC7182311C0BF68BC211D47B421E1 Received-SPF: pass client-ip=2a00:1450:4864:20::22a; envelope-from=manos.pitsidianakis@linaro.org; helo=mail-lj1-x22a.google.com X-Spam_score_int: -20 X-Spam_score: -2.1 X-Spam_bar: -- X-Spam_report: (-2.1 / 5.0 requ) BAYES_00=-1.9, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, SPF_HELO_NONE=0.001, SPF_PASS=-0.001, T_SCC_BODY_TEXT_LINE=-0.01 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+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Add rust feature in meson.build, configure, to prepare for adding Rust code in the followup commits. Signed-off-by: Manos Pitsidianakis Reviewed-by: Alex Bennée --- MAINTAINERS | 5 +++++ meson.build | 25 ++++++++++++++++++++++++- Kconfig | 1 + Kconfig.host | 3 +++ meson_options.txt | 3 +++ rust/Kconfig | 0 scripts/meson-buildoptions.sh | 3 +++ 7 files changed, 39 insertions(+), 1 deletion(-) diff --git a/MAINTAINERS b/MAINTAINERS index 3584d6a6c6da9a3210150534d640d29ddf329dce..0bc8e515daf7e63320620b52b42a799b99dbe035 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -4243,6 +4243,11 @@ F: docs/sphinx/ F: docs/_templates/ F: docs/devel/docs.rst +Rust build system integration +M: Manos Pitsidianakis +S: Maintained +F: rust/Kconfig + Miscellaneous ------------- Performance Tools and Tests diff --git a/meson.build b/meson.build index 7eb4b8a41c0a667cacf693cfa2764f326ba72b1f..67eb4eda649d5f0566de2b75466b5a9d9ca87ab4 100644 --- a/meson.build +++ b/meson.build @@ -70,6 +70,22 @@ if host_os == 'darwin' and \ all_languages += ['objc'] objc = meson.get_compiler('objc') endif +if get_option('rust').enabled() and meson.version().version_compare('<1.0.0') + error('Rust support requires Meson version >=1.0.0') +endif +have_rust = false +if not get_option('rust').disabled() and add_languages('rust', required: get_option('rust'), native: false) + rustc = meson.get_compiler('rust') + have_rust = true + if rustc.version().version_compare('<1.80.0') + if get_option('rust').enabled() + error('rustc version ' + rustc.version() + ' is unsupported: Please upgrade to at least 1.80.0') + else + warning('rustc version ' + rustc.version() + ' is unsupported: Disabling Rust compilation. Please upgrade to at least 1.80.0 to use Rust.') + have_rust = false + endif + endif +endif dtrace = not_found stap = not_found @@ -2131,6 +2147,7 @@ endif config_host_data = configuration_data() +config_host_data.set('CONFIG_HAVE_RUST', have_rust) audio_drivers_selected = [] if have_system audio_drivers_available = { @@ -3076,7 +3093,8 @@ host_kconfig = \ (host_os == 'linux' ? ['CONFIG_LINUX=y'] : []) + \ (multiprocess_allowed ? ['CONFIG_MULTIPROCESS_ALLOWED=y'] : []) + \ (vfio_user_server_allowed ? ['CONFIG_VFIO_USER_SERVER_ALLOWED=y'] : []) + \ - (hv_balloon ? ['CONFIG_HV_BALLOON_POSSIBLE=y'] : []) + (hv_balloon ? ['CONFIG_HV_BALLOON_POSSIBLE=y'] : []) + \ + (have_rust ? ['CONFIG_HAVE_RUST=y'] : []) ignored = [ 'TARGET_XML_FILES', 'TARGET_ABI_DIR', 'TARGET_ARCH' ] @@ -4287,6 +4305,11 @@ if 'objc' in all_languages else summary_info += {'Objective-C compiler': false} endif +summary_info += {'Rust support': have_rust} +if have_rust + summary_info += {'rustc version': rustc.version()} + summary_info += {'rustc': ' '.join(rustc.cmd_array())} +endif option_cflags = (get_option('debug') ? ['-g'] : []) if get_option('optimization') != 'plain' option_cflags += ['-O' + get_option('optimization')] diff --git a/Kconfig b/Kconfig index fb6a24a2de8c3ff11d4ee432d65ad000ba9d6c4d..63ca7f46df788144864b26ef5a64b29ad6547435 100644 --- a/Kconfig +++ b/Kconfig @@ -4,3 +4,4 @@ source accel/Kconfig source target/Kconfig source hw/Kconfig source semihosting/Kconfig +source rust/Kconfig diff --git a/Kconfig.host b/Kconfig.host index 17f405004b3bc765890688304322a1937ca8c01c..4ade7899d67a5ed91928f8ee1e287f5ba3331949 100644 --- a/Kconfig.host +++ b/Kconfig.host @@ -52,3 +52,6 @@ config VFIO_USER_SERVER_ALLOWED config HV_BALLOON_POSSIBLE bool + +config HAVE_RUST + bool diff --git a/meson_options.txt b/meson_options.txt index 0269fa0f16ed6b6f734fcefa2cfa94aa029fa837..fa94a5ce97bb14ab108e21cccb651923ac6a58f8 100644 --- a/meson_options.txt +++ b/meson_options.txt @@ -371,3 +371,6 @@ option('hexagon_idef_parser', type : 'boolean', value : true, option('x86_version', type : 'combo', choices : ['0', '1', '2', '3', '4'], value: '1', description: 'tweak required x86_64 architecture version beyond compiler default') + +option('rust', type: 'feature', value: 'auto', + description: 'Rust support') diff --git a/rust/Kconfig b/rust/Kconfig new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/scripts/meson-buildoptions.sh b/scripts/meson-buildoptions.sh index c97079a38c9e4ed24a0fe9b44e492b7108481048..5e8a225a6b343cf506950a3146af718d52a6c1a0 100644 --- a/scripts/meson-buildoptions.sh +++ b/scripts/meson-buildoptions.sh @@ -170,6 +170,7 @@ meson_options_help() { printf "%s\n" ' rbd Ceph block device driver' printf "%s\n" ' rdma Enable RDMA-based migration' printf "%s\n" ' replication replication support' + printf "%s\n" ' rust Rust support' printf "%s\n" ' rutabaga-gfx rutabaga_gfx support' printf "%s\n" ' sdl SDL user interface' printf "%s\n" ' sdl-image SDL Image support for icons' @@ -452,6 +453,8 @@ _meson_option_parse() { --disable-replication) printf "%s" -Dreplication=disabled ;; --enable-rng-none) printf "%s" -Drng_none=true ;; --disable-rng-none) printf "%s" -Drng_none=false ;; + --enable-rust) printf "%s" -Drust=enabled ;; + --disable-rust) printf "%s" -Drust=disabled ;; --enable-rutabaga-gfx) printf "%s" -Drutabaga_gfx=enabled ;; --disable-rutabaga-gfx) printf "%s" -Drutabaga_gfx=disabled ;; --enable-safe-stack) printf "%s" -Dsafe_stack=true ;; From patchwork Wed Aug 28 04:11:44 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Manos Pitsidianakis X-Patchwork-Id: 13780492 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id 7D1D2C5474A for ; Wed, 28 Aug 2024 04:14:04 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1sjA2h-0005Qk-7I; Wed, 28 Aug 2024 00:12:23 -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 1sjA2g-0005Px-Da for qemu-devel@nongnu.org; Wed, 28 Aug 2024 00:12:22 -0400 Received: from mail-ed1-x52d.google.com ([2a00:1450:4864:20::52d]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_128_GCM_SHA256:128) (Exim 4.90_1) (envelope-from ) id 1sjA2d-0000ld-Rv for qemu-devel@nongnu.org; Wed, 28 Aug 2024 00:12:22 -0400 Received: by mail-ed1-x52d.google.com with SMTP id 4fb4d7f45d1cf-5c210e23651so679586a12.3 for ; Tue, 27 Aug 2024 21:12:19 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1724818338; x=1725423138; darn=nongnu.org; h=cc:to:in-reply-to:references:message-id:content-transfer-encoding :mime-version:subject:date:from:from:to:cc:subject:date:message-id :reply-to; bh=21QEmzDujIgpkUBwy6KBNuVdg09H8SzoucFGAIhOGAk=; b=ZIKQYxmHgMUabne88e4vlGnl9W5mghbK3usGhLHyBO+sQzGgraWN6FOH2zd366pC6B u9qMgAELqKYtT1tlW1EOIZqgvE9kiw6dVbglyRgTBWt1vVIPa373Jod4nG6Xen61p6fN IDRV+dFcrBJNwPFtyohNht5rLbLGtUSNnOcxuxb0R9ysT272mKX+CieszGBqvV4JFZaX 5AyKQckcqEdfiI+4aHpKY2VjVJyAeOXq5Pit/H4GnbLG2suokfdPjR1Sw8clE3iqc9rO tDG0p9dI7vOWSekqqoGhsK8AZNeFZej48JevWxLHJ3/c4Q4zuFkxGZaIZUMhTPxNvUZ9 VNrQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1724818338; x=1725423138; h=cc:to:in-reply-to:references:message-id:content-transfer-encoding :mime-version:subject:date:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=21QEmzDujIgpkUBwy6KBNuVdg09H8SzoucFGAIhOGAk=; b=NnZmMx4dSSidiU8GArUSbH5tQEUQ1ZrHB6xFH88OlvDsMwzcMT3vuo2zqa2Ioe7MpR e6FfB0m5jKY69BPty4cI3qOdK4uJBZ06FnP1hy5xDBRBgQvmpgLErJG383jcwLhTUsFC 84txqhLSIZ8/jvx0ezJzdjDR3ptTQXOKLUfKgaGjS3IaOeQoXjD9iryGKRCeSEkPHJLX 5s5HIT9oSSM1Cmr9pXsEiMaUeQO7vHAVbC62vibetwpyp8+xtVzf2VttFttSTV2AjMdV gNsRHgNqo0sqVDwxReaeigeidm7d+3tq+EbM2llzx5J9JRsROTO80ra0rbaPeFaFZko+ lPLQ== X-Gm-Message-State: AOJu0YwskzSyXM1aAcvg86neFPcKlSYR3N0W/eYZfV+dKBWgcZv3M9Bm 99Rx/NnQPFt25mJT6qXnmBge6LU6s4INggAuejccmKD5ojyVn+cwWmIrDxr9Q+0= X-Google-Smtp-Source: AGHT+IH9KE1oN1ihGD9nOTi3dVn+vAk+brW/aIeBd1kD8yPAYNLaAzQNNPObQ2CPic2OSUiet0PiZw== X-Received: by 2002:a05:6402:2546:b0:5be:eb19:ee56 with SMTP id 4fb4d7f45d1cf-5c214c597c2mr471528a12.24.1724818337807; Tue, 27 Aug 2024 21:12:17 -0700 (PDT) Received: from [127.0.1.1] (adsl-98.109.242.227.tellas.gr. [109.242.227.98]) by smtp.gmail.com with ESMTPSA id 4fb4d7f45d1cf-5c0bb1c29b9sm1712814a12.18.2024.08.27.21.12.14 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 27 Aug 2024 21:12:17 -0700 (PDT) From: Manos Pitsidianakis Date: Wed, 28 Aug 2024 07:11:44 +0300 Subject: [PATCH RESEND v9 3/9] configure, meson: detect Rust toolchain MIME-Version: 1.0 Message-Id: <20240828-rust-pl011-v9-3-35579191f17c@linaro.org> References: <20240828-rust-pl011-v9-0-35579191f17c@linaro.org> In-Reply-To: <20240828-rust-pl011-v9-0-35579191f17c@linaro.org> To: qemu-devel@nongnu.org Cc: Paolo Bonzini , =?utf-8?q?Marc-Andr=C3=A9_Lureau?= , =?utf-8?q?Daniel_P=2E_Berrang=C3=A9?= , Thomas Huth , =?utf-8?q?Philippe_Mathieu-Daud=C3=A9?= , Pierrick Bouvier , Richard Henderson , Gustavo Romero , =?utf-8?q?Alex_Benn=C3=A9e?= , Peter Maydell , Junjie Mao , Zhao Liu , Manos Pitsidianakis X-Mailer: b4 0.15-dev-c2c95 X-Developer-Signature: v=1; a=openpgp-sha256; l=6904; i=manos.pitsidianakis@linaro.org; h=from:subject:message-id; bh=qISo7oo0rfeUGD0BnZly+vsOKnxOKDn62ksH0VVpgRc=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0VCYlFLUy9aQU5Bd0FLQVhjcHgzQi9mZ 25RQWNzbVlnQm16cU9MUy9ObUxaYjViQm9UaUhHY0hxNVFTU0xUCnhNNndHQ0ttL25oSnJvd0g5 WWlKQWpNRUFBRUtBQjBXSVFUTVhCdE9SS0JXODRkd0hSQjNLY2R3ZjM0SjBBVUMKWnM2aml3QUt DUkIzS2Nkd2YzNEowTnp3RC85Z0RFYjN5SVdKNmtaZFRMK3ZNMFJaUWJ1OHNyOWU0cXZnMzFoVA orSHZ5YTMzSXViajNiU3NrRGhjb0FNS2M1dGhDR21vWE1PVEtQWWg3b2U2cXBtMHRrWUV5aWtrZ k1LNGY5R0c1CnlmRnNYM2ZGbjFub1V1WnM0aVVYM3dGalpJckNzcEtWMlJIYU5sZnduUUZKUTJ1 aHU1UVFBRFVkKys4Nkt6bnIKYXYvYVRTNVVVY2Y4T0pKVENaSE0venNQbE8xSFliVjVMS1Ivblh 0U2pxUlFIK3EyVFV6N2UrMGhvd1ArLzFrawpGcnMwcDczVzhjcllCMXNXSmxaSGUvc29BWE5rUE xDTHNuRmhIa1JnNFl0OTYvcjk5WDNuNDZ3U25kSmhROFVjCmliN2l3TlBoK1N4aXRkb3Rod012Z TZpLy9pUC8ydFMrUDdNYy94UkRZRHBEWDYrZlVlZkVqamg3MHpWUENBS0YKUWZtdUxLaS80MTFm dE1FR1ZTY1U0NnBwZGVoYUk4OTFXaTBMcUc0RHREU3BtR2lBRWtKOFZFZ09KaHoyT1pGSQp1WG5 MaXptb2Fjc1hOVGhMTTZWME5qTEpxMDlPeWJDNlJ1SzA4TnRjU0VXVEdqYTA4WVRaaTdPZkNLRE J4QmFpCjhsYVR5bkVPNEU5SXlmQW95V045QXhnNlZwdXVaaWVHajhzcVVyZzVQd2c4K1RNUTNLN UphWDIya0JEVGlXaFoKb2dZN1hVMjNLanZuNWdMcjV1UisyWHpudFhEY2lTelNPRDFaNXRlUVdO aW9lTDNIMHBReVJSYzVGM0RqVUhxYwpwaDJsdDhiYnE0ampwa3FYeVR5dktudlBWVmZ1N1hTWjF MaUtPYkhVaUVJcUFyYnpqWktWekhJbmptYlhXTUQzCng4N0k1UT09Cj16ano2Ci0tLS0tRU5EIF BHUCBNRVNTQUdFLS0tLS0K X-Developer-Key: i=manos.pitsidianakis@linaro.org; a=openpgp; fpr=7C721DF9DB3CC7182311C0BF68BC211D47B421E1 Received-SPF: pass client-ip=2a00:1450:4864:20::52d; envelope-from=manos.pitsidianakis@linaro.org; helo=mail-ed1-x52d.google.com X-Spam_score_int: -20 X-Spam_score: -2.1 X-Spam_bar: -- X-Spam_report: (-2.1 / 5.0 requ) BAYES_00=-1.9, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001, T_SCC_BODY_TEXT_LINE=-0.01 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+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org From: Paolo Bonzini Include the correct path and arguments to rustc in the native and cross files (native compilation is needed for procedural macros). Signed-off-by: Paolo Bonzini --- configure | 50 ++++++++++++++++++++++++++++++++++++++++++++++++-- meson.build | 8 +++----- 2 files changed, 51 insertions(+), 7 deletions(-) diff --git a/configure b/configure index 019fcbd0ef7b07e7b0280b358099cae72c73aa98..9ef6005c557fc627c7c6c732b4c92ed1b934f474 100755 --- a/configure +++ b/configure @@ -207,6 +207,8 @@ for opt do ;; --objcc=*) objcc="$optarg" ;; + --rustc=*) RUSTC="$optarg" + ;; --cpu=*) cpu="$optarg" ;; --extra-cflags=*) @@ -252,6 +254,9 @@ python= download="enabled" skip_meson=no use_containers="yes" +# do not enable by default because cross compilation requires --rust-target-triple +rust="disabled" +rust_target_triple="" gdb_bin=$(command -v "gdb-multiarch" || command -v "gdb") gdb_arches="" @@ -317,6 +322,8 @@ windmc="${WINDMC-${cross_prefix}windmc}" pkg_config="${PKG_CONFIG-${cross_prefix}pkg-config}" sdl2_config="${SDL2_CONFIG-${cross_prefix}sdl2-config}" +rustc="${RUSTC-rustc}" + check_define() { cat > $TMPC < "${TMPDIR1}/${TMPB}.out"; then + rust_host_triple=$(sed -n 's/^host: //p' "${TMPDIR1}/${TMPB}.out") +else + if test "$rust" = enabled; then + error_exit "could not execute rustc binary \"$rustc\"" + fi + rust=disabled +fi +if test "$rust" != disabled && test -z "$rust_target_triple"; then + rust_target_triple=$rust_host_triple +fi + +########################################## # functions to probe cross compilers container="no" @@ -1604,6 +1636,9 @@ if test "$container" != no; then echo "RUNC=$runc" >> $config_host_mak fi echo "SUBDIRS=$subdirs" >> $config_host_mak +if test "$rust" != disabled; then + echo "RUST_TARGET_TRIPLE=$rust_target_triple" >> $config_host_mak +fi echo "PYTHON=$python" >> $config_host_mak echo "MKVENV_ENSUREGROUP=$mkvenv ensuregroup $mkvenv_online_flag" >> $config_host_mak echo "GENISOIMAGE=$genisoimage" >> $config_host_mak @@ -1735,6 +1770,13 @@ if test "$skip_meson" = no; then echo "c = [$(meson_quote $cc $CPU_CFLAGS)]" >> $cross test -n "$cxx" && echo "cpp = [$(meson_quote $cxx $CPU_CFLAGS)]" >> $cross test -n "$objcc" && echo "objc = [$(meson_quote $objcc $CPU_CFLAGS)]" >> $cross + if test "$rust" != disabled; then + if test "$rust_host_triple" != "$rust_target_triple"; then + echo "rust = [$(meson_quote $rustc --target "$rust_target_triple")]" >> $cross + else + echo "rust = [$(meson_quote $rustc)]" >> $cross + fi + fi echo "ar = [$(meson_quote $ar)]" >> $cross echo "dlltool = [$(meson_quote $dlltool)]" >> $cross echo "nm = [$(meson_quote $nm)]" >> $cross @@ -1770,6 +1812,9 @@ if test "$skip_meson" = no; then echo "# Automatically generated by configure - do not modify" > $native echo "[binaries]" >> $native echo "c = [$(meson_quote $host_cc)]" >> $native + if test "$rust" != disabled; then + echo "rust = [$(meson_quote $rustc)]" >> $cross + fi mv $native config-meson.native meson_option_add --native-file meson_option_add config-meson.native @@ -1788,6 +1833,7 @@ if test "$skip_meson" = no; then test "$pie" = no && meson_option_add -Db_pie=false # QEMU options + test "$rust" != "auto" && meson_option_add "-Drust=$rust" test "$cfi" != false && meson_option_add "-Dcfi=$cfi" "-Db_lto=$cfi" test "$docs" != auto && meson_option_add "-Ddocs=$docs" test -n "${LIB_FUZZING_ENGINE+xxx}" && meson_option_add "-Dfuzzing_engine=$LIB_FUZZING_ENGINE" diff --git a/meson.build b/meson.build index 67eb4eda649d5f0566de2b75466b5a9d9ca87ab4..065739ccb7300f4f0d487602485802f9f68fb095 100644 --- a/meson.build +++ b/meson.build @@ -70,9 +70,6 @@ if host_os == 'darwin' and \ all_languages += ['objc'] objc = meson.get_compiler('objc') endif -if get_option('rust').enabled() and meson.version().version_compare('<1.0.0') - error('Rust support requires Meson version >=1.0.0') -endif have_rust = false if not get_option('rust').disabled() and add_languages('rust', required: get_option('rust'), native: false) rustc = meson.get_compiler('rust') @@ -4307,8 +4304,9 @@ else endif summary_info += {'Rust support': have_rust} if have_rust - summary_info += {'rustc version': rustc.version()} - summary_info += {'rustc': ' '.join(rustc.cmd_array())} + summary_info += {'rustc version': rustc.version()} + summary_info += {'rustc': ' '.join(rustc.cmd_array())} + summary_info += {'Rust target': config_host['RUST_TARGET_TRIPLE']} endif option_cflags = (get_option('debug') ? ['-g'] : []) if get_option('optimization') != 'plain' From patchwork Wed Aug 28 04:11:45 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Manos Pitsidianakis X-Patchwork-Id: 13780491 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id 43D74C5472D for ; Wed, 28 Aug 2024 04:13:16 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1sjA2m-0005eH-AH; Wed, 28 Aug 2024 00:12:28 -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 1sjA2j-0005Xx-5P for qemu-devel@nongnu.org; Wed, 28 Aug 2024 00:12:25 -0400 Received: from mail-ed1-x52f.google.com ([2a00:1450:4864:20::52f]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_128_GCM_SHA256:128) (Exim 4.90_1) (envelope-from ) id 1sjA2g-0000lj-OL for qemu-devel@nongnu.org; Wed, 28 Aug 2024 00:12:24 -0400 Received: by mail-ed1-x52f.google.com with SMTP id 4fb4d7f45d1cf-5bed83487aeso6445871a12.2 for ; Tue, 27 Aug 2024 21:12:22 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1724818341; x=1725423141; darn=nongnu.org; h=cc:to:in-reply-to:references:message-id:content-transfer-encoding :mime-version:subject:date:from:from:to:cc:subject:date:message-id :reply-to; bh=RIA2mzchFzu/rUsSqz24xC7Y44yMs6m0u27dIMBYc38=; b=t5A8+XmSlfCJS4vgQar51xkbMII7VeKqkM1ztWtbO4xlNoL0VJ7nM+maGkzr2mVhIh 3nW6rWvZeJVhxDGUpE4cgVRLV8+aNtZcNEYoVbsubCwu8KdCA8NHGFb+Y7yqKeYUsieV MwBJQY9GsJyL8M0fTkxIAEusZt733kgD1dy/0Gocfm9zEyho1g2t6EsZOQKTkvrUWM2Z eY6GwVh2MExNhDWlBWWdOS36Q+ouATFFhcmB+kcGiMPhVcqeGBaietc2PR7814qNqnFv wExJuZkttvY7s0lWDG4eMVuGEcucBT5NiZznq4jLoivsXfhJjrdGImk22kFGPQNbPWPx 7oJg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1724818341; x=1725423141; h=cc:to:in-reply-to:references:message-id:content-transfer-encoding :mime-version:subject:date:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=RIA2mzchFzu/rUsSqz24xC7Y44yMs6m0u27dIMBYc38=; b=URxyz7LnWjxCxz8hOwrYgAKSY19VkHpUtqYVKuHldBzIiOk3tQjU7T9ZkOo+PNKJXy W4hUlt0cbz8wnqlonKJJVkzMaGsUJZY147E0P+TtXriFEGW4dL9uR159occXDTcPwGXy GBPCv8PaeOonfIc0oxIpl7AQBBhj+iy4pqRjJRPSqdl5y1vmkYw4LTVjOjXOntkEU0aK h8A6OYIvgNs3xO9kuuBpbUp6Qfc5b34Uv6f407xvdAVUx8yKZTUGKbEA75jn5nBm8CQH u8Bn9b61mpYqmPuVgomrSQg2sxdy5ALQL1OrtJtuJ7AOC4HO21hsEcF1CM/KHVLoPjFz iiKw== X-Gm-Message-State: AOJu0YzOpmb690TkAHC2hjLr8xG1iYLuOC0j52rXB53dse9B5UMPVuMT ujbK/XhaD95SWULVRqQiObc0Wh//W7YyjE3MBdwRndqs9JCsG2SQzEekF7c+V/c= X-Google-Smtp-Source: AGHT+IGKtYLx6YS+1gz4uUlPfaPg/3NOAO1eIcUXua0DthPh2OnRIR+HH3o3EVA/Iwh/CYLv5H+rnA== X-Received: by 2002:a05:6402:2187:b0:5a4:6dec:cd41 with SMTP id 4fb4d7f45d1cf-5c214c55462mr415481a12.28.1724818340602; Tue, 27 Aug 2024 21:12:20 -0700 (PDT) Received: from [127.0.1.1] (adsl-98.109.242.227.tellas.gr. [109.242.227.98]) by smtp.gmail.com with ESMTPSA id 4fb4d7f45d1cf-5c0bb1c29b9sm1712814a12.18.2024.08.27.21.12.18 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 27 Aug 2024 21:12:20 -0700 (PDT) From: Manos Pitsidianakis Date: Wed, 28 Aug 2024 07:11:45 +0300 Subject: [PATCH RESEND v9 4/9] rust: add bindgen step as a meson dependency MIME-Version: 1.0 Message-Id: <20240828-rust-pl011-v9-4-35579191f17c@linaro.org> References: <20240828-rust-pl011-v9-0-35579191f17c@linaro.org> In-Reply-To: <20240828-rust-pl011-v9-0-35579191f17c@linaro.org> To: qemu-devel@nongnu.org Cc: Paolo Bonzini , =?utf-8?q?Marc-Andr=C3=A9_Lureau?= , =?utf-8?q?Daniel_P=2E_Berrang=C3=A9?= , Thomas Huth , =?utf-8?q?Philippe_Mathieu-Daud=C3=A9?= , Pierrick Bouvier , Richard Henderson , Gustavo Romero , =?utf-8?q?Alex_Benn=C3=A9e?= , Peter Maydell , Junjie Mao , Zhao Liu , Manos Pitsidianakis X-Mailer: b4 0.15-dev-c2c95 X-Developer-Signature: v=1; a=openpgp-sha256; l=8085; i=manos.pitsidianakis@linaro.org; h=from:subject:message-id; bh=PQJSezN8Fa5GrXoUGvLqQ4JAqn06+ukoNNi+seooUts=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0VCYlFLUy9aQU5Bd0FLQVhjcHgzQi9mZ 25RQWNzbVlnQm16cU9MZW95OUtReHZuUUt2M3hma2kwcnAwQm9uCjRtc2ZheFhlVElJSy9YT3VZ QWVKQWpNRUFBRUtBQjBXSVFUTVhCdE9SS0JXODRkd0hSQjNLY2R3ZjM0SjBBVUMKWnM2aml3QUt DUkIzS2Nkd2YzNEowQnZDRC85ckVGcVd6alJqTTdaaGJwQkVMbzVmTHhCSEE1MHlsWUZwQWlkeQ poOGIzVjZINDk1TlUvcXJ0RXN3Nkt3VFNIa2xSdjFYT3JRMWJkallIblJhcW9xOUpubEpTcUVOQ ldUd3d4bTJVCmZLdUtqYm1oSUthdWtkR1JsQ25GOE5DbGV6cWZQWWZ2L0hVaGdPdVZGYmFHd0ll SSs4cXljRHQwUUVORTl3azMKeU9IeUJZdXFrSEwxQ2p4Rjc3SkhMTnJuSXZNTlQwblQ4S1YxS0V BaStlZGRiRSs1N01kalA0OWRLZGY1cE1SOQp1bjhxNVVOS3c2OGZkZC9SN2V5UU9zNGNoMXVheG lMY21PVkpDSE55dUFta2gyNFcxeDJjT0cvem8rbzVkYTR3CjArbDNmM05rdmNLdkNISlRMWkE0O EwyZUFsSGwzK3BvUUNNS0gwSEt0MlcxUFRHQlVIMm42MHlkNnU1WDdyd00KZkxBdEI2cDBKNmNn WmZjQkNpZTdDZlFCOGN0Uy96cWdvN3p6ZXA1azU2VVl3Z1owVys1NkhTelZFR1prRmVyUgpIc2p PSHJFSVVndVVKRlFZUW5zN0w4UEQ3RndPM20ycUgrUlhGVFpnVStDeVVjY2VYcnNlQVBGWDNWM0 F4eU01CllyeTZMZmRGbEJPWFdkL0Y3MlpUSVBqY1hzOFFzYzhjZ3NTcW4rdU1wRzJWK2pQZG1ZO XdlWDQ2c3lHY3doQTkKNGlZUGRVZ0piaWR0bm1RdVpXRDVaSy9oeVAwamdQSFF5Q3JqOXpBOE5L VzhUSlZLSUxuYUZ6SU1abldkSWp0bApQMGVnaXpHZHZ4Qms5d3JheFNrYXlFOG9ybnRuQUJ1R3I wQUZwcGRJeDEvNnhRTndDWVFtWms5Z3VhbW9mSm5ECkdYWGJOUT09Cj04cENjCi0tLS0tRU5EIF BHUCBNRVNTQUdFLS0tLS0K X-Developer-Key: i=manos.pitsidianakis@linaro.org; a=openpgp; fpr=7C721DF9DB3CC7182311C0BF68BC211D47B421E1 Received-SPF: pass client-ip=2a00:1450:4864:20::52f; envelope-from=manos.pitsidianakis@linaro.org; helo=mail-ed1-x52f.google.com X-Spam_score_int: -20 X-Spam_score: -2.1 X-Spam_bar: -- X-Spam_report: (-2.1 / 5.0 requ) BAYES_00=-1.9, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001, T_SCC_BODY_TEXT_LINE=-0.01 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+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Add bindings_rs target for generating rust bindings to target-independent qemu C APIs. The bindings need be created before any rust crate that uses them is compiled. The bindings.rs file will end up in BUILDDIR/bindings.rs and have the same name as a target: ninja bindings.rs Signed-off-by: Paolo Bonzini Signed-off-by: Manos Pitsidianakis --- MAINTAINERS | 4 +++ meson.build | 34 +++++++++++++++++++ rust/wrapper.h | 39 +++++++++++++++++++++ rust/.gitignore | 3 ++ rust/meson.build | 0 scripts/rust/rustc_args.py | 84 ++++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 164 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index 0bc8e515daf7e63320620b52b42a799b99dbe035..642c07a9ff2ed2422ac50d1419751f92f81690bd 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -4246,7 +4246,11 @@ F: docs/devel/docs.rst Rust build system integration M: Manos Pitsidianakis S: Maintained +F: scripts/rust/ +F: rust/.gitignore F: rust/Kconfig +F: rust/meson.build +F: rust/wrapper.h Miscellaneous ------------- diff --git a/meson.build b/meson.build index 065739ccb7300f4f0d487602485802f9f68fb095..05446acbc684a7521ecc9b3f80b98e2cec1a60cf 100644 --- a/meson.build +++ b/meson.build @@ -3871,6 +3871,40 @@ common_all = static_library('common', implicit_include_directories: false, dependencies: common_ss.all_dependencies()) +if have_rust and have_system + rustc_config_args = run_command( + find_program('scripts/rust/rustc_args.py'), + '--config-headers', meson.project_build_root() / 'config-host.h', + capture : true, + check: true).stdout().strip().split() + + bindings_rs = import('rust').bindgen( + input: 'rust/wrapper.h', + dependencies: common_ss.all_dependencies(), + output: 'bindings.rs', + include_directories: include_directories('.', 'include'), + bindgen_version: ['>=0.69.4'], + args: [ + '--disable-header-comment', + '--raw-line', '// @generated', + '--ctypes-prefix', 'core::ffi', + '--formatter', 'rustfmt', + '--generate-block', + '--generate-cstr', + '--impl-debug', + '--merge-extern-blocks', + '--no-doc-comments', + '--use-core', + '--with-derive-default', + '--allowlist-file', meson.project_source_root() + '/include/.*', + '--allowlist-file', meson.project_source_root() + '/.*', + '--allowlist-file', meson.project_build_root() + '/.*' + ], + ) + subdir('rust') +endif + + feature_to_c = find_program('scripts/feature_to_c.py') if host_os == 'darwin' diff --git a/rust/wrapper.h b/rust/wrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..51985f0ef1550a7e0eb8b2ea5273a832fed8eec8 --- /dev/null +++ b/rust/wrapper.h @@ -0,0 +1,39 @@ +/* + * QEMU System Emulator + * + * Copyright 2024 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. + */ + +#include "qemu/osdep.h" +#include "qemu/module.h" +#include "qemu-io.h" +#include "sysemu/sysemu.h" +#include "hw/sysbus.h" +#include "exec/memory.h" +#include "chardev/char-fe.h" +#include "hw/clock.h" +#include "hw/qdev-clock.h" +#include "hw/qdev-properties.h" +#include "hw/qdev-properties-system.h" +#include "hw/irq.h" +#include "qapi/error.h" +#include "migration/vmstate.h" +#include "chardev/char-serial.h" diff --git a/rust/.gitignore b/rust/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..1bf71b1f68e7791f4b7b40b61fa0fdb5ddbab373 --- /dev/null +++ b/rust/.gitignore @@ -0,0 +1,3 @@ +# Ignore any cargo development build artifacts; for qemu-wide builds, all build +# artifacts will go to the meson build directory. +target diff --git a/rust/meson.build b/rust/meson.build new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/scripts/rust/rustc_args.py b/scripts/rust/rustc_args.py new file mode 100644 index 0000000000000000000000000000000000000000..e4cc9720e16a18cb3f7ad370d4464233336b129a --- /dev/null +++ b/scripts/rust/rustc_args.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 + +"""Generate rustc arguments for meson rust builds. + +This program generates --cfg compile flags for the configuration headers passed +as arguments. + +Copyright (c) 2024 Linaro Ltd. + +Authors: + Manos Pitsidianakis + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +""" + +import argparse +import logging + +from typing import List + + +def generate_cfg_flags(header: str) -> List[str]: + """Converts defines from config[..].h headers to rustc --cfg flags.""" + + def cfg_name(name: str) -> str: + """Filter function for C #defines""" + if ( + name.startswith("CONFIG_") + or name.startswith("TARGET_") + or name.startswith("HAVE_") + ): + return name + return "" + + with open(header, encoding="utf-8") as cfg: + config = [l.split()[1:] for l in cfg if l.startswith("#define")] + + cfg_list = [] + for cfg in config: + name = cfg_name(cfg[0]) + if not name: + continue + if len(cfg) >= 2 and cfg[1] != "1": + continue + cfg_list.append("--cfg") + cfg_list.append(name) + return cfg_list + + +def main() -> None: + # pylint: disable=missing-function-docstring + parser = argparse.ArgumentParser() + parser.add_argument("-v", "--verbose", action="store_true") + parser.add_argument( + "--config-headers", + metavar="CONFIG_HEADER", + action="append", + dest="config_headers", + help="paths to any configuration C headers (*.h files), if any", + required=False, + default=[], + ) + args = parser.parse_args() + if args.verbose: + logging.basicConfig(level=logging.DEBUG) + logging.debug("args: %s", args) + for header in args.config_headers: + for tok in generate_cfg_flags(header): + print(tok) + + +if __name__ == "__main__": + main() From patchwork Wed Aug 28 04:11:46 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Manos Pitsidianakis X-Patchwork-Id: 13780493 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id 3131AC5474E for ; Wed, 28 Aug 2024 04:14:06 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1sjA2p-0005qD-Nx; Wed, 28 Aug 2024 00:12:31 -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 1sjA2l-0005dU-Na for qemu-devel@nongnu.org; Wed, 28 Aug 2024 00:12:28 -0400 Received: from mail-ed1-x52c.google.com ([2a00:1450:4864:20::52c]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_128_GCM_SHA256:128) (Exim 4.90_1) (envelope-from ) id 1sjA2j-0000lz-AV for qemu-devel@nongnu.org; Wed, 28 Aug 2024 00:12:26 -0400 Received: by mail-ed1-x52c.google.com with SMTP id 4fb4d7f45d1cf-5bed0a2ae0fso7798190a12.1 for ; Tue, 27 Aug 2024 21:12:24 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1724818343; x=1725423143; darn=nongnu.org; h=cc:to:in-reply-to:references:message-id:content-transfer-encoding :mime-version:subject:date:from:from:to:cc:subject:date:message-id :reply-to; bh=HKQ+Tr9nd7UKxDYpE7u+hcEQP2VtRBhfmqRFJl+mGfQ=; b=cXHt+fvqkSgvrFfhFXannXESVhwh+HkBiiykV+NWl6JGfV3sY/00YiajS5EBJQyPmZ MT+Cc/HaQTi0jt+hllMbinAqaXl51zfNteRelLCQi4Ip3hT7bys+Yxf0fNjhbiQiTDvz cMTQUFvcbLcv9t6sNx4UxsdmsUXDEzbmSmq4axXIlNRmvnu5tZq/R9Rt9tX78g07Q+DN PGOs/lCvCsBuyyzrBJaQMppzgRiRxDWmUftyhIuj6rk9fhqeTOtjKb/p5h18T0/rFRO5 RnFjfoetUZfbCM8A9NbVB5z+ig4Bwxdp/D/brH/LCvhSlucSZj1TqXYs9aXhiQuw3p4h Jg2g== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1724818343; x=1725423143; h=cc:to:in-reply-to:references:message-id:content-transfer-encoding :mime-version:subject:date:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=HKQ+Tr9nd7UKxDYpE7u+hcEQP2VtRBhfmqRFJl+mGfQ=; b=L3ghVDbm+qFc24R4ccBTWBN6nduwk4H6shGoz3ROiuMOKrqJ9g2LlNMLzwIXGcGAlV UDhQn456y6U9nyyAkHbTGEWkJX+zWpVtT4HOsq42R117DQqOU84C7Pz8pARrWyZKheWF KgUo9nDkLOGJpQnw8rLzap3iMwCwc8UUwjypRa592h9jb6Rqg6IPTIO1J4CMdRfE8Waa S6Gnindcf/7kyaDyzDCrTW8/e9Pp4Jw3b1lk3SAaXN8yOiI7elhiUGXWbAuwuHCqx+iU GsufJXUOvOuwkISOSdYS9HGeTJ2u3Hw9TlQZIpa1rdZ2wEXIQhyEay0Z/pfaBVyio5in y/bw== X-Gm-Message-State: AOJu0Yy4iCbM2leDpvLEyFI8RbaGb9bIZ9iiub4FvaW5PDNYiGIRhH1S eTUNGUNVHYaZgNgBSPqcYdhwdE4Qy7C7Gv17Ids4qh1zWVUk/Zq1v/1lIFly3GY= X-Google-Smtp-Source: AGHT+IEUzNsQxp3ZqdRsr7sMoP9R2SQEJ3xyJ6H0QOgKKa+CwR11MoaIuufOYhscZQLBVH6kSrl1Eg== X-Received: by 2002:a05:6402:27cf:b0:5a3:8c9:3c1d with SMTP id 4fb4d7f45d1cf-5c089165f5bmr10395941a12.14.1724818343161; Tue, 27 Aug 2024 21:12:23 -0700 (PDT) Received: from [127.0.1.1] (adsl-98.109.242.227.tellas.gr. [109.242.227.98]) by smtp.gmail.com with ESMTPSA id 4fb4d7f45d1cf-5c0bb1c29b9sm1712814a12.18.2024.08.27.21.12.20 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 27 Aug 2024 21:12:22 -0700 (PDT) From: Manos Pitsidianakis Date: Wed, 28 Aug 2024 07:11:46 +0300 Subject: [PATCH RESEND v9 5/9] .gitattributes: add Rust diff and merge attributes MIME-Version: 1.0 Message-Id: <20240828-rust-pl011-v9-5-35579191f17c@linaro.org> References: <20240828-rust-pl011-v9-0-35579191f17c@linaro.org> In-Reply-To: <20240828-rust-pl011-v9-0-35579191f17c@linaro.org> To: qemu-devel@nongnu.org Cc: Paolo Bonzini , =?utf-8?q?Marc-Andr=C3=A9_Lureau?= , =?utf-8?q?Daniel_P=2E_Berrang=C3=A9?= , Thomas Huth , =?utf-8?q?Philippe_Mathieu-Daud=C3=A9?= , Pierrick Bouvier , Richard Henderson , Gustavo Romero , =?utf-8?q?Alex_Benn=C3=A9e?= , Peter Maydell , Junjie Mao , Zhao Liu , Manos Pitsidianakis X-Mailer: b4 0.15-dev-c2c95 X-Developer-Signature: v=1; a=openpgp-sha256; l=797; i=manos.pitsidianakis@linaro.org; h=from:subject:message-id; bh=cb5hfvQlqbMpu1WXDHeHVpn8WY1kxaNKXHZwF2lZXrU=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0VCYlFLUy9aQU5Bd0FLQVhjcHgzQi9mZ 25RQWNzbVlnQm16cU9MeTVHdkRvQmhGWDUrRlVIZFhMZEE1c0tOCnpOUW8ydTlrc1BJVjVXOVM0 Q0NKQWpNRUFBRUtBQjBXSVFUTVhCdE9SS0JXODRkd0hSQjNLY2R3ZjM0SjBBVUMKWnM2aml3QUt DUkIzS2Nkd2YzNEowTzZ6RUFDVW8rZWpMZ0JXSzFyL2ViL1FuUmRMdzJ5TGN5bEd3aCsyNDRJdQ owa205ckp6WG1SZFBRc21FWVpTNUg2N0h2YmNZZW9vL0ZMdzRud1BMZWNyZ3FKbnp6MGdqc1BLS EVFS3dtWHhRClR3T2xZdjBXNHEveVlWeTMvWlNpODIwcTdsZXFBSlFVRHRobFlNL0p6TGQweXVT OEZ2QmNZMEpFWlV0N0JLNk4KTlhtMHVhVHNXSTBaK2d6M0NzNHN5bmNwYUR5Z3JmZy95d3N2STJ WMW41OTZvSWlwbVhoYVRaV0JqU2pSd1ZaeApsMk5KWitHaUo4YWFQRzFJR0dwY1YyNm5SMzEwUi tXTFhlSnpqaXNRWWVITGw3QTdRdjJqOURiUW1hZ1hOYzhtClRoZjlGeHBqOVJ0bjJSOHBPT1BlK 2c5enB5V2pSYWVTMnVHK3gzeHNUU1ZRUFBLMU9mWlNBRzhibEZSY1kxWVoKNlBKeGx3VWp1ek9Y MjdJSGtITW1RMGVHY3hUTTFyUTU3bFROLzVBc1k3YUh4WnJ6dGxoSUY1OEswM1JkVVlGbApjSEd xNzhabWppR1c4OVMxWVhCWGRCcW1TdHQxcVFiRlZUQU51bU90ekhibGpoNzQzRDhYTzZjcG1LRF MxTjRSCi9zWlhRMmh1RGh1SFVDeFhmM2lJd29qUTB6UVl3Qm1SelB0aVVvQkdqN0Z6ZEtQekh5e lJCQXZPVVhCYklrOXgKOGJGZ3FvVXRIOE5mN0g0QlU0TzRVVkFjQnFuSERXbXBGYS9FTEQ2Qlg3 UXZyL0ZQUHVDK1ZURnJ6ZkM3bUZhawp2U0F3Q0R2ZEVKZUxCZGk3Rm8rdmgvMzhqOUMrblEwbU1 RMWwxUHBRMnZmN3YvcE5GWTNwaWlNb3BiOHJMYUo5CnpUY1Zndz09Cj1SSHRECi0tLS0tRU5EIF BHUCBNRVNTQUdFLS0tLS0K X-Developer-Key: i=manos.pitsidianakis@linaro.org; a=openpgp; fpr=7C721DF9DB3CC7182311C0BF68BC211D47B421E1 Received-SPF: pass client-ip=2a00:1450:4864:20::52c; envelope-from=manos.pitsidianakis@linaro.org; helo=mail-ed1-x52c.google.com X-Spam_score_int: -20 X-Spam_score: -2.1 X-Spam_bar: -- X-Spam_report: (-2.1 / 5.0 requ) BAYES_00=-1.9, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001, T_SCC_BODY_TEXT_LINE=-0.01 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+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Set rust source code to diff=rust (built-in with new git versions) and merge=binary for Cargo.lock files (they should not be merged but auto-generated by cargo) Reviewed-by: Alex Bennée Reviewed-by: Zhao Liu Signed-off-by: Manos Pitsidianakis --- .gitattributes | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitattributes b/.gitattributes index a217cb7bfe96ff6c8548f510c62c6e16b2d5faa9..6dc6383d3d1199eca5479353cedb6d83d98d95ce 100644 --- a/.gitattributes +++ b/.gitattributes @@ -2,3 +2,6 @@ *.h.inc diff=c *.m diff=objc *.py diff=python +*.rs diff=rust +*.rs.inc diff=rust +Cargo.lock diff=toml merge=binary From patchwork Wed Aug 28 04:11:47 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Manos Pitsidianakis X-Patchwork-Id: 13780495 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id 2A89DC5474E for ; Wed, 28 Aug 2024 04:14:11 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1sjA2v-0006AN-4T; Wed, 28 Aug 2024 00:12:37 -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 1sjA2n-0005kq-JN for qemu-devel@nongnu.org; Wed, 28 Aug 2024 00:12:31 -0400 Received: from mail-ed1-x533.google.com ([2a00:1450:4864:20::533]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_128_GCM_SHA256:128) (Exim 4.90_1) (envelope-from ) id 1sjA2l-0000m9-GN for qemu-devel@nongnu.org; Wed, 28 Aug 2024 00:12:29 -0400 Received: by mail-ed1-x533.google.com with SMTP id 4fb4d7f45d1cf-5bec4fc82b0so327342a12.1 for ; Tue, 27 Aug 2024 21:12:27 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1724818346; x=1725423146; darn=nongnu.org; h=cc:to:in-reply-to:references:message-id:content-transfer-encoding :mime-version:subject:date:from:from:to:cc:subject:date:message-id :reply-to; bh=5XXJiXERznBbe2Mo2VGN/xNFPalflSWfdtbpmX6ccVY=; b=b4Zd/Y+sPS5TVkXknSc5vWjEVPm6cwiDOqN2fN9O22tmsieZBi3Ggl2utnm0Zuzs4F 1l4bRXoqqBNVfCZE8l+hhDKDu4KoBQ/uyUeFgcicjGwHwxTcmumeiKxiEfMzwU+EcaJH hEpdec5b5cnbaxlna9QhDe947uE7+WHdh/isEXOpM4kl385hW6wC8zbVwho5M6DuWU5p aMYxPiCqiaKwpcORaQ5KEHif1MNDpYZYAcUpIsxIfBmDQwrJ6gjD0ef1XufmjHgrYV2P 2Ggl6I0TPgFmJ/8GRxSD/M0ikq5P84Y2JLKoU0TyeAMfxk9pSLiLwcBpXIyWlRgFZQMi 2K8g== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1724818346; x=1725423146; h=cc:to:in-reply-to:references:message-id:content-transfer-encoding :mime-version:subject:date:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=5XXJiXERznBbe2Mo2VGN/xNFPalflSWfdtbpmX6ccVY=; b=Pij+TNJozjgzvLfZhvfrgGOMQCMBsYSnH205g/wbnaaB9u+wthLRqdv82I5yDRXUAX ldeEfS8JhoE2KIRPPt2X9yEW5r4JqGM8UhXPjMSS5PKsmlmgwYyamM0tcxxh5JQeisZY 3yOmoBwPwqXP9j0uWDxagmhAE1o2uGVUDSgqdxsMjD8tZTn4pfGZ8Z0z/V/eF9JLyRgX xXu/rrSzwNT+4MdRU/WqDp/rq1vuiJPqHSd2gMoXCAYTGwlijo+DB8lsgNiW1R06k4Rk 9U45+CeIy97FCQ1BODdxEfOwT8Di71ZwhxyzJdeKoff2Rn0zxE62cnvl0QY9fNkzLI91 Hz5w== X-Gm-Message-State: AOJu0YwFR+3qcefE6ogqvY7fgbzfEHVBnDEymYeTQrtxcvAAzLnUoVsW D8eO29P5AdaKH75Fti0OF6iPRx3bx/ozSYExQOCYPuXqTKGJEuVvX7tLba2+YXs= X-Google-Smtp-Source: AGHT+IHOYjEaxmdaiXBY7N9GbkdeDZfZVN2F3sLw/HGKwypfRG0THc9O33akkdI5yen5DeQaOq/r5A== X-Received: by 2002:a05:6402:2709:b0:5c0:c6a7:1c58 with SMTP id 4fb4d7f45d1cf-5c212ab30a0mr785096a12.15.1724818345591; Tue, 27 Aug 2024 21:12:25 -0700 (PDT) Received: from [127.0.1.1] (adsl-98.109.242.227.tellas.gr. [109.242.227.98]) by smtp.gmail.com with ESMTPSA id 4fb4d7f45d1cf-5c0bb1c29b9sm1712814a12.18.2024.08.27.21.12.23 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 27 Aug 2024 21:12:25 -0700 (PDT) From: Manos Pitsidianakis Date: Wed, 28 Aug 2024 07:11:47 +0300 Subject: [PATCH RESEND v9 6/9] meson.build: add HAVE_GLIB_WITH_ALIGNED_ALLOC flag MIME-Version: 1.0 Message-Id: <20240828-rust-pl011-v9-6-35579191f17c@linaro.org> References: <20240828-rust-pl011-v9-0-35579191f17c@linaro.org> In-Reply-To: <20240828-rust-pl011-v9-0-35579191f17c@linaro.org> To: qemu-devel@nongnu.org Cc: Paolo Bonzini , =?utf-8?q?Marc-Andr=C3=A9_Lureau?= , =?utf-8?q?Daniel_P=2E_Berrang=C3=A9?= , Thomas Huth , =?utf-8?q?Philippe_Mathieu-Daud=C3=A9?= , Pierrick Bouvier , Richard Henderson , Gustavo Romero , =?utf-8?q?Alex_Benn=C3=A9e?= , Peter Maydell , Junjie Mao , Zhao Liu , Manos Pitsidianakis X-Mailer: b4 0.15-dev-c2c95 X-Developer-Signature: v=1; a=openpgp-sha256; l=1783; i=manos.pitsidianakis@linaro.org; h=from:subject:message-id; bh=m74JGdAON2yLb93RBa4Z+R4byBd/4OHukWLHC7W6c78=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0VCYlFLUy9aQU5Bd0FLQVhjcHgzQi9mZ 25RQWNzbVlnQm16cU9MUktHK3diTXd3ZkFkci9QWGNocEc4S3cyCnRzS1VTbER3aG1LbXFTYVlW OUdKQWpNRUFBRUtBQjBXSVFUTVhCdE9SS0JXODRkd0hSQjNLY2R3ZjM0SjBBVUMKWnM2aml3QUt DUkIzS2Nkd2YzNEowRkNYRC85Q3VENStia2FVVTdiT29ZeWhuc25Yck9YTXQ4eEM4WUxLVnlKVg owV0FPRFFOaTZtcWlhcW1IR2I1dFN5MCtmUURlaFBsSTFzeDZCVlZmcnJDN0NIK0NNd040SCtwO WF1ZUpaT1h5CkhWZnBkQUptb1hadUd2bzRmdzN2ZE0xWjZMZXAzemVEdUhnOXVlMlF5S2dScHV6 ZEFpNWFweGQ1WmhYVlJCT1EKcGpaZW9Bc0Y3dFJTblVCM01La0p3YllQeDRsZDVseEdBbkRzTE9 qdGZIcUJBVy9sckRCNzR5OGs4YzdWQnRFcwpTR0Rhamt2ZTZKdFBySTRZWklNMEdxMmh2NXp6Ni 9hUFZDV3ZGN1ZSV1I5QVBHMExzRDdsY2N5QVE2aTdIMEJiCkFxTnI1TnZ2Nm43MHBYUTFGdloyN 2RPWFN3bHdhU2JoR1RlQmJha3JzdklSaVNGOWEyYTJvc1dXcTVwa3BQcTMKQ1QzamNuN0VaSDNB OC92YmFiQ09ucGtURGdVL2h5WmFNR1NxRmJxdm5vL1Q4QW1RNE5tNzJRekxieW9WbWVZTQpiWlg 5RHFHQVhuNE4zUmlyMm5sM2lkdlByZnliWXJZNml2Vklmbm4yRGFwR3A1TEhYQlQvWVk3ejlxcX c0clBlCmt1aVB1Zm5PTG4vREo2VitMM3l4ZEtmdStkVG9YZTVIU29tV2RkMHV6TWQvdTAySVdYN klKTk81SS9iREVtOGwKN1hIaUtJOEtIVm9YTmFrU3FBUXZnVUZHRFpSQzBvbDJ1aGVRQmNkb2hG Tmw3bGhIUUlzZnQvZHNtSVNYbDFYUApBcFRibXFxeU9FRE1ad21oN2EwNUdIYXlLMi9NZlVXeFN 5aHY3SVlaQmlZcmpsY3djT2ljeW5KSWowUnU2aURzCm0rVDlhdz09Cj1ETHVhCi0tLS0tRU5EIF BHUCBNRVNTQUdFLS0tLS0K X-Developer-Key: i=manos.pitsidianakis@linaro.org; a=openpgp; fpr=7C721DF9DB3CC7182311C0BF68BC211D47B421E1 Received-SPF: pass client-ip=2a00:1450:4864:20::533; envelope-from=manos.pitsidianakis@linaro.org; helo=mail-ed1-x533.google.com X-Spam_score_int: -20 X-Spam_score: -2.1 X-Spam_bar: -- X-Spam_report: (-2.1 / 5.0 requ) BAYES_00=-1.9, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001, T_SCC_BODY_TEXT_LINE=-0.01 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+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Rust crates, introduced from the next commit onwards, use the glib allocator API and need to know whether g_aligned_alloc etc are available. This commit adds a define in config_host_data that depends on glib version >= 2.72. Signed-off-by: Manos Pitsidianakis Reviewed-by: Alex Bennée --- meson.build | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/meson.build b/meson.build index 05446acbc684a7521ecc9b3f80b98e2cec1a60cf..7f05466d128776ad8dbf403179734e6831b023c0 100644 --- a/meson.build +++ b/meson.build @@ -979,6 +979,9 @@ glib = declare_dependency(dependencies: [glib_pc, gmodule], # TODO: remove this check and the corresponding workaround (qtree) when # the minimum supported glib is >= 2.75.3 glib_has_gslice = glib.version().version_compare('<2.75.3') +# Check whether glib has the aligned_alloc family of functions. +# +glib_has_aligned_alloc = glib.version().version_compare('>=2.72.0') # override glib dep to include the above refinements meson.override_dependency('glib-2.0', glib) @@ -2508,6 +2511,7 @@ config_host_data.set('CONFIG_TIMERFD', cc.has_function('timerfd_create')) config_host_data.set('HAVE_COPY_FILE_RANGE', cc.has_function('copy_file_range')) config_host_data.set('HAVE_GETIFADDRS', cc.has_function('getifaddrs')) config_host_data.set('HAVE_GLIB_WITH_SLICE_ALLOCATOR', glib_has_gslice) +config_host_data.set('HAVE_GLIB_WITH_ALIGNED_ALLOC', glib_has_aligned_alloc) config_host_data.set('HAVE_OPENPTY', cc.has_function('openpty', dependencies: util)) config_host_data.set('HAVE_STRCHRNUL', cc.has_function('strchrnul')) config_host_data.set('HAVE_SYSTEM_FUNCTION', cc.has_function('system', prefix: '#include ')) From patchwork Wed Aug 28 04:11:48 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Manos Pitsidianakis X-Patchwork-Id: 13780497 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id 68341C5472D for ; Wed, 28 Aug 2024 04:14:25 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1sjA2y-0006MG-9U; Wed, 28 Aug 2024 00:12:40 -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 1sjA2v-0006BC-Cg for qemu-devel@nongnu.org; Wed, 28 Aug 2024 00:12:37 -0400 Received: from mail-ed1-x531.google.com ([2a00:1450:4864:20::531]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_128_GCM_SHA256:128) (Exim 4.90_1) (envelope-from ) id 1sjA2q-0000mM-89 for qemu-devel@nongnu.org; Wed, 28 Aug 2024 00:12:36 -0400 Received: by mail-ed1-x531.google.com with SMTP id 4fb4d7f45d1cf-5bed0a2ae0fso7798258a12.1 for ; Tue, 27 Aug 2024 21:12:30 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1724818349; x=1725423149; darn=nongnu.org; h=cc:to:in-reply-to:references:message-id:content-transfer-encoding :mime-version:subject:date:from:from:to:cc:subject:date:message-id :reply-to; bh=D+2125XN2k4UAK4IVwcG/R+FKK4RRBoX0YoCGazraC0=; b=xzQqaxRJhjl44poSht/JscbEGz91FBWgjOWInulqSIFVPCnQ6hEA+r/fVZHfPuzP/m 7WPj4keXq0WDNYC5y/1YZq+car1/UHP3ELArE9Sk+1fh5A29dfg3fQBKmYke8uEcG43c EUu+lYxNRPDhkKUdnLwyEy1mNhTTO2WLd2crAx3Dyu6XtEHtlqurdouZKg3VEgxUjaUU CMc6dT1MTXrvZTMUHP/+r6g+G+6ScKgy0zr2A1oO+OllO5Y4BCEyV5FPeZL+0hWhOL8z 0tXZ5vDAVP4amhutUZXTX+vYPpGF37mgmUR5RFY0YWnSPyAyM+JZ3XUIt5lI53I+AvV6 uCJg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1724818349; x=1725423149; h=cc:to:in-reply-to:references:message-id:content-transfer-encoding :mime-version:subject:date:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=D+2125XN2k4UAK4IVwcG/R+FKK4RRBoX0YoCGazraC0=; b=dAGSZTFjxCa+G1wVAoIpdd7/RRfia5gV1AqibXjFq1KGrf6bbqCpqGWafF8ksrHYeB Gr0GYwGaRBU60sxZDcsqrdK9Xyv4nCTRvUCnfoeY/1px3Ziemh+5qeVnx75EnwrxFmr0 ySU3E4x4LTsV7Rmd84rtvb0UwD5cdXQPDqwShvC/jtn3WXRSAtLZVXSadiv/pW8w0fFV qLlsZ2dMC+TE5FF9Ou5INaayL7W/G3rAweD3bd5X55RfrOZJ99t0Jlg7kdwvyzP1R58t HKFRm/pdUhd0eAUaM4iV9RRJ5ygxhYG0YXCHt1zR1TBGKm+1pgbDZ2TZqBJ8tEPh5q+r vXUQ== X-Gm-Message-State: AOJu0Yyl474pd8PQu8wNO9q4pVg3toxqispVWbBBNgbs1VzQYwgpI8+1 j8lF7+Hrh+1+j8rn9JEUKE/pkVrWVAlYFFUjJJlOsFwYEHLCg7aTMCtXy1AAeIz+3+KdMB4g3N2 aALM= X-Google-Smtp-Source: AGHT+IG4atA9IZeG9D1/lDzLiWPuhorNDYsNDEY5ExBMIMhWGM7WcdCJB6exi7E4KE42SQU5LvrSzg== X-Received: by 2002:a05:6402:3581:b0:5be:c8ad:af9a with SMTP id 4fb4d7f45d1cf-5c089164a15mr11477993a12.11.1724818348496; Tue, 27 Aug 2024 21:12:28 -0700 (PDT) Received: from [127.0.1.1] (adsl-98.109.242.227.tellas.gr. [109.242.227.98]) by smtp.gmail.com with ESMTPSA id 4fb4d7f45d1cf-5c0bb1c29b9sm1712814a12.18.2024.08.27.21.12.25 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 27 Aug 2024 21:12:27 -0700 (PDT) From: Manos Pitsidianakis Date: Wed, 28 Aug 2024 07:11:48 +0300 Subject: [PATCH RESEND v9 7/9] rust: add crate to expose bindings and interfaces MIME-Version: 1.0 Message-Id: <20240828-rust-pl011-v9-7-35579191f17c@linaro.org> References: <20240828-rust-pl011-v9-0-35579191f17c@linaro.org> In-Reply-To: <20240828-rust-pl011-v9-0-35579191f17c@linaro.org> To: qemu-devel@nongnu.org Cc: Paolo Bonzini , =?utf-8?q?Marc-Andr=C3=A9_Lureau?= , =?utf-8?q?Daniel_P=2E_Berrang=C3=A9?= , Thomas Huth , =?utf-8?q?Philippe_Mathieu-Daud=C3=A9?= , Pierrick Bouvier , Richard Henderson , Gustavo Romero , =?utf-8?q?Alex_Benn=C3=A9e?= , Peter Maydell , Junjie Mao , Zhao Liu , Manos Pitsidianakis X-Mailer: b4 0.15-dev-c2c95 X-Developer-Signature: v=1; a=openpgp-sha256; l=22242; i=manos.pitsidianakis@linaro.org; h=from:subject:message-id; bh=AZEGhKKQxL64kTo3gPkBVHNXbPu+xlUEjOX6RXtEd7M=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0VCYlFLUy9aQU5Bd0FLQVhjcHgzQi9mZ 25RQWNzbVlnQm16cU9MSEtnVjY4K0l6WFJjOHJYdXJhV3U5bUxwCnNNOU85OGFNTm00eTFLZDVT TldKQWpNRUFBRUtBQjBXSVFUTVhCdE9SS0JXODRkd0hSQjNLY2R3ZjM0SjBBVUMKWnM2aml3QUt DUkIzS2Nkd2YzNEowRVpGRC8wUTk5R1Y4UWw1TjdRbXZCY21VNUxpUXpteFVGcVVYQmNSSFI0Sg pGd3VBU0tROHZyZ0xKN1h3c29EZHRaUm9GV1RISmFGNWxLNURYY2lTenlXMFM5eGZVT3dOWTJQW DYxQkh0SzR5CmxyMFhRc24yQjJYeWR1VXAzWmh6eFdhU0RxMlNIeDVPMTJkR24wdmU2N3o3U1pr NENhVURKdmphS25YVDRGUFIKMmU3eUZDTE1Hd2lDUWpFRWY0WWdNSnJrOTh5UU1WOWdreHZiMjF wQVhpN2hOMEd3d0VaSDlNYkVtd1pwaWRkdApDdGJJRWprWXR0WXpOd084R1l4TFJLVzBsa0xFdn orOWlvMExpT3IrbjArTHZKMVpzcXFyVnhuaEJCQ2dIK3pNCmgyQUlGc2U0NzVoZ2tCM1o4QW5RM DhyUGpaaU5QeG9wcGRlODFuM3VYeThDcjZsZG1xZ3VIZG11U1dxTHZOVFIKRHZpbS9IeG5ReUZM Q3RTVXpQYmswdmV6NkxXbFBFd3NwYjYwNDdmcG1PSW93L0VPUEE2ZmlEcjVSYmJyK0ViSgpmOXp YMW1KOWxUdjhnK0EzdEREaE8xNEMwSHpuVnVrSUE2eCt1UmRsb29LeDdQcHYwTnNFQnBwZkU0ZT dYMUFECkZNSnc1WmNMVmFCU1hLQTRHend1U0FHa2I3M2t1MTRnUmpoZis4b2pDOC9KRG1Ib2NuU llsNGp0YVFmb3dvck0KVTdNLzVzZERaanFJWGN5MmQ1dDg0R1VuaXlwTldobExjZEpwNkJVK3dh N2d2dlBoQllYM05nK0VRQW5qdTk1ZgpHTFQxaTVUSXV3cldhVmJwc3UzcFJITWtoSm9SQUQxKzg waXhRcDFIdDM2eGt1RmR6b3JPaStoZWhzaWcwcGFjCmdoU3FDdz09Cj1jS2dHCi0tLS0tRU5EIF BHUCBNRVNTQUdFLS0tLS0K X-Developer-Key: i=manos.pitsidianakis@linaro.org; a=openpgp; fpr=7C721DF9DB3CC7182311C0BF68BC211D47B421E1 Received-SPF: pass client-ip=2a00:1450:4864:20::531; envelope-from=manos.pitsidianakis@linaro.org; helo=mail-ed1-x531.google.com X-Spam_score_int: -20 X-Spam_score: -2.1 X-Spam_bar: -- X-Spam_report: (-2.1 / 5.0 requ) BAYES_00=-1.9, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001, T_SCC_BODY_TEXT_LINE=-0.01 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+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Add rust/qemu-api, which exposes rust-bindgen generated FFI bindings and provides some declaration macros for symbols visible to the rest of QEMU. 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 --- MAINTAINERS | 6 ++ rust/meson.build | 1 + rust/qemu-api/.gitignore | 2 + rust/qemu-api/Cargo.lock | 7 ++ rust/qemu-api/Cargo.toml | 26 +++++++ rust/qemu-api/README.md | 17 +++++ rust/qemu-api/build.rs | 14 ++++ rust/qemu-api/meson.build | 21 ++++++ rust/qemu-api/src/definitions.rs | 109 +++++++++++++++++++++++++++ rust/qemu-api/src/device_class.rs | 128 +++++++++++++++++++++++++++++++ rust/qemu-api/src/lib.rs | 154 ++++++++++++++++++++++++++++++++++++++ rust/qemu-api/src/tests.rs | 49 ++++++++++++ rust/rustfmt.toml | 7 ++ 13 files changed, 541 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index 642c07a9ff2ed2422ac50d1419751f92f81690bd..d35e9f6b20bb23c7580de488ebaabc6c031343d2 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -3348,6 +3348,12 @@ F: hw/core/register.c F: include/hw/register.h F: include/hw/registerfields.h +Rust +M: Manos Pitsidianakis +S: Maintained +F: rust/qemu-api +F: rust/rustfmt.toml + SLIRP M: Samuel Thibault S: Maintained diff --git a/rust/meson.build b/rust/meson.build index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..4a58d106b1dd1d7bee39dd129f57ddb5a95bd9b7 100644 --- a/rust/meson.build +++ b/rust/meson.build @@ -0,0 +1 @@ +subdir('qemu-api') diff --git a/rust/qemu-api/.gitignore b/rust/qemu-api/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..b9e7e004c867bd1b5d44e69634d78fdafbfc1306 --- /dev/null +++ b/rust/qemu-api/.gitignore @@ -0,0 +1,2 @@ +# Ignore generated bindings file overrides. +src/bindings.rs diff --git a/rust/qemu-api/Cargo.lock b/rust/qemu-api/Cargo.lock new file mode 100644 index 0000000000000000000000000000000000000000..e9c51a243a85499cfa3ce2f9da225184ddf05d24 --- /dev/null +++ b/rust/qemu-api/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "qemu_api" +version = "0.1.0" diff --git a/rust/qemu-api/Cargo.toml b/rust/qemu-api/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..efc369e5ae926fd5c63e38a68e621ff3ad3b6e3b --- /dev/null +++ b/rust/qemu-api/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "qemu_api" +version = "0.1.0" +edition = "2021" +authors = ["Manos Pitsidianakis "] +license = "GPL-2.0-or-later" +readme = "README.md" +homepage = "https://www.qemu.org" +description = "Rust bindings for QEMU" +repository = "https://gitlab.com/qemu-project/qemu/" +resolver = "2" +publish = false +keywords = [] +categories = [] + +[dependencies] + +[features] +default = ["allocator"] +allocator = [] + +# Do not include in any global workspace +[workspace] + +[lints.rust] +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(MESON)', 'cfg(HAVE_GLIB_WITH_ALIGNED_ALLOC)'] } diff --git a/rust/qemu-api/README.md b/rust/qemu-api/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7588fa29ef37e29d424fc7c333ea1c9c6139181b --- /dev/null +++ b/rust/qemu-api/README.md @@ -0,0 +1,17 @@ +# QEMU bindings and API wrappers + +This library exports helper Rust types, Rust macros and C FFI bindings for internal QEMU APIs. + +The C bindings can be generated with `bindgen`, using this build target: + +```console +$ ninja bindings.rs +``` + +## Generate Rust documentation + +To generate docs for this crate, including private items: + +```sh +cargo doc --no-deps --document-private-items +``` diff --git a/rust/qemu-api/build.rs b/rust/qemu-api/build.rs new file mode 100644 index 0000000000000000000000000000000000000000..419b154c2d267a4b067b66f17b882bed0e65493a --- /dev/null +++ b/rust/qemu-api/build.rs @@ -0,0 +1,14 @@ +// Copyright 2024, Linaro Limited +// Author(s): Manos Pitsidianakis +// SPDX-License-Identifier: GPL-2.0-or-later + +use std::path::Path; + +fn main() { + if !Path::new("src/bindings.rs").exists() { + panic!( + "No generated C bindings found! Either build them manually with bindgen or with meson \ + (`ninja bindings.rs`) and copy them to src/bindings.rs, or build through meson." + ); + } +} diff --git a/rust/qemu-api/meson.build b/rust/qemu-api/meson.build new file mode 100644 index 0000000000000000000000000000000000000000..cf2b465e9f7cc7fb10af0d3aac469b58211cd64e --- /dev/null +++ b/rust/qemu-api/meson.build @@ -0,0 +1,21 @@ +_qemu_api_rs = static_library( + 'qemu_api', + structured_sources( + [ + 'src/lib.rs', + 'src/definitions.rs', + 'src/device_class.rs', + ], + {'.' : bindings_rs}, + ), + override_options: ['rust_std=2021', 'build.rust_std=2021'], + rust_abi: 'rust', + rust_args: rustc_config_args + [ + '--cfg', 'MESON', + '--cfg', 'feature="allocator"', + ], +) + +qemu_api = declare_dependency( + link_with: _qemu_api_rs, +) diff --git a/rust/qemu-api/src/definitions.rs b/rust/qemu-api/src/definitions.rs new file mode 100644 index 0000000000000000000000000000000000000000..4abd0253bd1ff4f3f2e11528329709ef54a43c24 --- /dev/null +++ b/rust/qemu-api/src/definitions.rs @@ -0,0 +1,109 @@ +// Copyright 2024, Linaro Limited +// Author(s): Manos Pitsidianakis +// SPDX-License-Identifier: GPL-2.0-or-later + +//! Definitions required by QEMU when registering a device. + +/// Trait a type must implement to be registered with QEMU. +pub trait ObjectImpl { + type Class; + const TYPE_INFO: crate::bindings::TypeInfo; + const TYPE_NAME: &'static ::core::ffi::CStr; + const PARENT_TYPE_NAME: Option<&'static ::core::ffi::CStr>; + const INSTANCE_INIT: ::core::option::Option< + unsafe extern "C" fn(obj: *mut crate::bindings::Object), + >; + const INSTANCE_POST_INIT: ::core::option::Option< + unsafe extern "C" fn(obj: *mut crate::bindings::Object), + >; + const INSTANCE_FINALIZE: ::core::option::Option< + unsafe extern "C" fn(obj: *mut crate::bindings::Object), + >; + const ABSTRACT: bool; +} + +pub trait Class { + const CLASS_INIT: ::core::option::Option< + unsafe extern "C" fn( + klass: *mut crate::bindings::ObjectClass, + data: *mut core::ffi::c_void, + ), + >; + const CLASS_BASE_INIT: ::core::option::Option< + unsafe extern "C" fn( + klass: *mut crate::bindings::ObjectClass, + data: *mut core::ffi::c_void, + ), + >; +} + +#[macro_export] +macro_rules! module_init { + ($func:expr, $type:expr) => { + #[used] + #[cfg_attr(target_os = "linux", link_section = ".ctors")] + #[cfg_attr(target_os = "macos", link_section = "__DATA,__mod_init_func")] + #[cfg_attr(target_os = "windows", link_section = ".CRT$XCU")] + pub static LOAD_MODULE: extern "C" fn() = { + assert!($type < $crate::bindings::module_init_type_MODULE_INIT_MAX); + + extern "C" fn __load() { + unsafe { + $crate::bindings::register_module_init(Some($func), $type); + } + } + + __load + }; + }; + (qom: $func:ident => $body:block) => { + // NOTE: To have custom identifiers for the ctor func we need to either supply + // them directly as a macro argument or create them with a proc macro. + #[used] + #[cfg_attr(target_os = "linux", link_section = ".ctors")] + #[cfg_attr(target_os = "macos", link_section = "__DATA,__mod_init_func")] + #[cfg_attr(target_os = "windows", link_section = ".CRT$XCU")] + pub static LOAD_MODULE: extern "C" fn() = { + extern "C" fn __load() { + #[no_mangle] + unsafe extern "C" fn $func() { + $body + } + + unsafe { + $crate::bindings::register_module_init( + Some($func), + $crate::bindings::module_init_type_MODULE_INIT_QOM, + ); + } + } + + __load + }; + }; +} + +#[macro_export] +macro_rules! type_info { + ($t:ty) => { + $crate::bindings::TypeInfo { + name: <$t as $crate::definitions::ObjectImpl>::TYPE_NAME.as_ptr(), + parent: if let Some(pname) = <$t as $crate::definitions::ObjectImpl>::PARENT_TYPE_NAME { + pname.as_ptr() + } else { + ::core::ptr::null_mut() + }, + instance_size: ::core::mem::size_of::<$t>(), + instance_align: ::core::mem::align_of::<$t>(), + instance_init: <$t as $crate::definitions::ObjectImpl>::INSTANCE_INIT, + instance_post_init: <$t as $crate::definitions::ObjectImpl>::INSTANCE_POST_INIT, + instance_finalize: <$t as $crate::definitions::ObjectImpl>::INSTANCE_FINALIZE, + abstract_: <$t as $crate::definitions::ObjectImpl>::ABSTRACT, + class_size: ::core::mem::size_of::<<$t as $crate::definitions::ObjectImpl>::Class>(), + class_init: <<$t as $crate::definitions::ObjectImpl>::Class as $crate::definitions::Class>::CLASS_INIT, + class_base_init: <<$t as $crate::definitions::ObjectImpl>::Class as $crate::definitions::Class>::CLASS_BASE_INIT, + class_data: ::core::ptr::null_mut(), + interfaces: ::core::ptr::null_mut(), + }; + } +} diff --git a/rust/qemu-api/src/device_class.rs b/rust/qemu-api/src/device_class.rs new file mode 100644 index 0000000000000000000000000000000000000000..69ee912c333c3dce8bc127a286acaadd57ca20b3 --- /dev/null +++ b/rust/qemu-api/src/device_class.rs @@ -0,0 +1,128 @@ +// Copyright 2024, Linaro Limited +// Author(s): Manos Pitsidianakis +// SPDX-License-Identifier: GPL-2.0-or-later + +use std::sync::OnceLock; + +use crate::bindings::Property; + +#[macro_export] +macro_rules! device_class_init { + ($func:ident, props => $props:ident, realize_fn => $realize_fn:expr, reset_fn => $reset_fn:expr, vmsd => $vmsd:ident$(,)*) => { + #[no_mangle] + pub unsafe extern "C" fn $func( + klass: *mut $crate::bindings::ObjectClass, + _: *mut ::core::ffi::c_void, + ) { + let mut dc = + ::core::ptr::NonNull::new(klass.cast::<$crate::bindings::DeviceClass>()).unwrap(); + dc.as_mut().realize = $realize_fn; + dc.as_mut().reset = $reset_fn; + dc.as_mut().vmsd = &$vmsd; + $crate::bindings::device_class_set_props(dc.as_mut(), $props.as_mut_ptr()); + } + }; +} + +#[macro_export] +macro_rules! define_property { + ($name:expr, $state:ty, $field:expr, $prop:expr, $type:expr, default = $defval:expr$(,)*) => { + $crate::bindings::Property { + name: { + #[used] + static _TEMP: &::core::ffi::CStr = $name; + _TEMP.as_ptr() + }, + info: $prop, + offset: ::core::mem::offset_of!($state, $field) + .try_into() + .expect("Could not fit offset value to type"), + bitnr: 0, + bitmask: 0, + set_default: true, + defval: $crate::bindings::Property__bindgen_ty_1 { u: $defval.into() }, + arrayoffset: 0, + arrayinfo: ::core::ptr::null(), + arrayfieldsize: 0, + link_type: ::core::ptr::null(), + } + }; + ($name:expr, $state:ty, $field:expr, $prop:expr, $type:expr$(,)*) => { + $crate::bindings::Property { + name: { + #[used] + static _TEMP: &::core::ffi::CStr = $name; + _TEMP.as_ptr() + }, + info: $prop, + offset: ::core::mem::offset_of!($state, $field) + .try_into() + .expect("Could not fit offset value to type"), + bitnr: 0, + bitmask: 0, + set_default: false, + defval: $crate::bindings::Property__bindgen_ty_1 { i: 0 }, + arrayoffset: 0, + arrayinfo: ::core::ptr::null(), + arrayfieldsize: 0, + link_type: ::core::ptr::null(), + } + }; +} + +#[repr(C)] +pub struct Properties(pub OnceLock<[Property; N]>, pub fn() -> [Property; N]); + +impl Properties { + pub fn as_mut_ptr(&mut self) -> *mut Property { + _ = self.0.get_or_init(self.1); + self.0.get_mut().unwrap().as_mut_ptr() + } +} + +#[macro_export] +macro_rules! declare_properties { + ($ident:ident, $($prop:expr),*$(,)*) => { + + const fn _calc_prop_len() -> usize { + let mut len = 1; + $({ + _ = stringify!($prop); + len += 1; + })* + len + } + const PROP_LEN: usize = _calc_prop_len(); + + fn _make_properties() -> [$crate::bindings::Property; PROP_LEN] { + [ + $($prop),*, + unsafe { ::core::mem::MaybeUninit::<$crate::bindings::Property>::zeroed().assume_init() }, + ] + } + + #[no_mangle] + pub static mut $ident: $crate::device_class::Properties = $crate::device_class::Properties(::std::sync::OnceLock::new(), _make_properties); + }; +} + +#[macro_export] +macro_rules! vm_state_description { + ($(#[$outer:meta])* + $name:ident, + $(name: $vname:expr,)* + $(unmigratable: $um_val:expr,)* + ) => { + #[used] + $(#[$outer])* + pub static $name: $crate::bindings::VMStateDescription = $crate::bindings::VMStateDescription { + $(name: { + #[used] + static VMSTATE_NAME: &::core::ffi::CStr = $vname; + $vname.as_ptr() + },)* + unmigratable: true, + ..unsafe { ::core::mem::MaybeUninit::<$crate::bindings::VMStateDescription>::zeroed().assume_init() } + }; + } +} diff --git a/rust/qemu-api/src/lib.rs b/rust/qemu-api/src/lib.rs new file mode 100644 index 0000000000000000000000000000000000000000..26637024907dc23d5ca81a8ce21cd9c307c022ea --- /dev/null +++ b/rust/qemu-api/src/lib.rs @@ -0,0 +1,154 @@ +// Copyright 2024, Linaro Limited +// Author(s): Manos Pitsidianakis +// SPDX-License-Identifier: GPL-2.0-or-later + +#![cfg_attr(not(MESON), doc = include_str!("../README.md"))] + +#[allow( + dead_code, + improper_ctypes_definitions, + improper_ctypes, + non_camel_case_types, + non_snake_case, + non_upper_case_globals, + clippy::missing_const_for_fn, + clippy::too_many_arguments, + clippy::approx_constant, + clippy::use_self, + clippy::useless_transmute, + clippy::missing_safety_doc, +)] +#[rustfmt::skip] +pub mod bindings; + +unsafe impl Send for bindings::Property {} +unsafe impl Sync for bindings::Property {} +unsafe impl Sync for bindings::TypeInfo {} +unsafe impl Sync for bindings::VMStateDescription {} + +pub mod definitions; +pub mod device_class; + +#[cfg(test)] +mod tests; + +use std::alloc::{GlobalAlloc, Layout}; + +#[cfg(HAVE_GLIB_WITH_ALIGNED_ALLOC)] +extern "C" { + fn g_aligned_alloc0( + n_blocks: bindings::gsize, + n_block_bytes: bindings::gsize, + alignment: bindings::gsize, + ) -> bindings::gpointer; + fn g_aligned_free(mem: bindings::gpointer); +} + +#[cfg(not(HAVE_GLIB_WITH_ALIGNED_ALLOC))] +extern "C" { + fn qemu_memalign(alignment: usize, size: usize) -> *mut ::core::ffi::c_void; + fn qemu_vfree(ptr: *mut ::core::ffi::c_void); +} + +extern "C" { + fn g_malloc0(n_bytes: bindings::gsize) -> bindings::gpointer; + fn g_free(mem: bindings::gpointer); +} + +/// An allocator that uses the same allocator as QEMU in C. +/// +/// It is enabled by default with the `allocator` feature. +/// +/// To set it up manually as a global allocator in your crate: +/// +/// ```ignore +/// use qemu_api::QemuAllocator; +/// +/// #[global_allocator] +/// static GLOBAL: QemuAllocator = QemuAllocator::new(); +/// ``` +#[derive(Clone, Copy, Debug)] +#[repr(C)] +pub struct QemuAllocator { + _unused: [u8; 0], +} + +#[cfg_attr(all(feature = "allocator", not(test)), global_allocator)] +pub static GLOBAL: QemuAllocator = QemuAllocator::new(); + +impl QemuAllocator { + // From the glibc documentation, on GNU systems, malloc guarantees 16-byte + // alignment on 64-bit systems and 8-byte alignment on 32-bit systems. See + // https://www.gnu.org/software/libc/manual/html_node/Malloc-Examples.html. + // This alignment guarantee also applies to Windows and Android. On Darwin + // and OpenBSD, the alignment is 16 bytes on both 64-bit and 32-bit systems. + #[cfg(all( + target_pointer_width = "32", + not(any(target_os = "macos", target_os = "openbsd")) + ))] + pub const DEFAULT_ALIGNMENT_BYTES: Option = Some(8); + #[cfg(all( + target_pointer_width = "64", + not(any(target_os = "macos", target_os = "openbsd")) + ))] + pub const DEFAULT_ALIGNMENT_BYTES: Option = Some(16); + #[cfg(all( + any(target_pointer_width = "32", target_pointer_width = "64"), + any(target_os = "macos", target_os = "openbsd") + ))] + pub const DEFAULT_ALIGNMENT_BYTES: Option = Some(16); + #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))] + pub const DEFAULT_ALIGNMENT_BYTES: Option = None; + + pub const fn new() -> Self { + Self { _unused: [] } + } +} + +impl Default for QemuAllocator { + fn default() -> Self { + Self::new() + } +} + +// Sanity check. +const _: [(); 8] = [(); ::core::mem::size_of::<*mut ::core::ffi::c_void>()]; + +unsafe impl GlobalAlloc for QemuAllocator { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + if matches!(Self::DEFAULT_ALIGNMENT_BYTES, Some(default) if default.checked_rem(layout.align()) == Some(0)) + { + g_malloc0(layout.size().try_into().unwrap()).cast::() + } else { + #[cfg(HAVE_GLIB_WITH_ALIGNED_ALLOC)] + { + g_aligned_alloc0( + layout.size().try_into().unwrap(), + 1, + (8 * layout.align()).try_into().unwrap(), + ) + .cast::() + } + #[cfg(not(HAVE_GLIB_WITH_ALIGNED_ALLOC))] + { + qemu_memalign(8 * layout.align(), layout.size()).cast::() + } + } + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + if matches!(Self::DEFAULT_ALIGNMENT_BYTES, Some(default) if default.checked_rem(layout.align()) == Some(0)) + { + g_free(ptr.cast::<_>()) + } else { + #[cfg(HAVE_GLIB_WITH_ALIGNED_ALLOC)] + { + g_aligned_free(ptr.cast::<_>()) + } + #[cfg(not(HAVE_GLIB_WITH_ALIGNED_ALLOC))] + { + qemu_vfree(ptr.cast::<_>()) + } + } + } +} diff --git a/rust/qemu-api/src/tests.rs b/rust/qemu-api/src/tests.rs new file mode 100644 index 0000000000000000000000000000000000000000..df54edbd4e27e7d2aafc243355d1826d52497c21 --- /dev/null +++ b/rust/qemu-api/src/tests.rs @@ -0,0 +1,49 @@ +// Copyright 2024, Linaro Limited +// Author(s): Manos Pitsidianakis +// SPDX-License-Identifier: GPL-2.0-or-later + +use crate::{ + bindings::*, declare_properties, define_property, device_class_init, vm_state_description, +}; + +#[test] +fn test_device_decl_macros() { + // Test that macros can compile. + vm_state_description! { + VMSTATE, + name: c"name", + unmigratable: true, + } + + #[repr(C)] + pub struct DummyState { + pub char_backend: CharBackend, + pub migrate_clock: bool, + } + + declare_properties! { + DUMMY_PROPERTIES, + define_property!( + c"chardev", + DummyState, + char_backend, + unsafe { &qdev_prop_chr }, + CharBackend + ), + define_property!( + c"migrate-clk", + DummyState, + migrate_clock, + unsafe { &qdev_prop_bool }, + bool + ), + } + + device_class_init! { + dummy_class_init, + props => DUMMY_PROPERTIES, + realize_fn => None, + reset_fn => None, + vmsd => VMSTATE, + } +} diff --git a/rust/rustfmt.toml b/rust/rustfmt.toml new file mode 100644 index 0000000000000000000000000000000000000000..ebecb99fe09e010d66c06b324f43d77b8ee00ea9 --- /dev/null +++ b/rust/rustfmt.toml @@ -0,0 +1,7 @@ +edition = "2021" +format_generated_files = false +format_code_in_doc_comments = true +format_strings = true +imports_granularity = "Crate" +group_imports = "StdExternalCrate" +wrap_comments = true From patchwork Wed Aug 28 04:11:49 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Manos Pitsidianakis X-Patchwork-Id: 13780499 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id 3AD49C5474A for ; Wed, 28 Aug 2024 04:14:50 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1sjA2y-0006KW-5q; Wed, 28 Aug 2024 00:12:40 -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 1sjA2t-00064a-FZ for qemu-devel@nongnu.org; Wed, 28 Aug 2024 00:12:35 -0400 Received: from mail-ed1-x532.google.com ([2a00:1450:4864:20::532]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_128_GCM_SHA256:128) (Exim 4.90_1) (envelope-from ) id 1sjA2r-0000mU-1y for qemu-devel@nongnu.org; Wed, 28 Aug 2024 00:12:35 -0400 Received: by mail-ed1-x532.google.com with SMTP id 4fb4d7f45d1cf-5a10835487fso9291766a12.1 for ; Tue, 27 Aug 2024 21:12:32 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1724818351; x=1725423151; darn=nongnu.org; h=cc:to:in-reply-to:references:message-id:content-transfer-encoding :mime-version:subject:date:from:from:to:cc:subject:date:message-id :reply-to; bh=PS8BB3FWvG/qWytireMjd1erjq7vy7tFLolrwsIWluI=; b=HqNUkX+lovLV6UcUj8TFSu1GS2B4nIXOTtCorl/xZY6xZZ3kahS41UcuYemUa9qDuP 7tsJnocuP5t189i1j9T15R0pPXW9a/pWgXsQSXOypdiWcUDHaG7TF/hbUO9YE894oPfV N04LjVTVQwsm2Sw2KPXu/ddmv/0TYjl59a2pNcogm9UDPHM9r/ZWp77/hps6rM3X+Pul zuH/sM2I43y+67AhsFe1U5ZzyvEhsw+Yt6pqAsvbbdU8b+Pnu0eVNLfGm4p1bixdx1ed rSiqQKzz7/3109aEiK17fcquUg8VjUUXBj71lnBeWthwPL4H4OhUjQ9RY3d/KRpX2LBP eL6Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1724818351; x=1725423151; h=cc:to:in-reply-to:references:message-id:content-transfer-encoding :mime-version:subject:date:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=PS8BB3FWvG/qWytireMjd1erjq7vy7tFLolrwsIWluI=; b=v+DwFzL1Mlb46yZNKZp1NKZqXrW1PEcbtRE5AbkDlrlPHGNA3KWXfO+3H5FQVsdAig dLMpD5PF1bxRT7oYZjcb/5mUyioTyhmJK/2PUNuvkt+FFTidiJab1AUDt7pGu01HGbwO 0iwKKleGR9OEnDf4ykAfATZpcn/By7sLqkeJntNbveDoCIHNdbh8cuVeuT5eQLBvdBf5 f8T9lyrljK2zvUn1E/hUw/jgrla27hmIswJrwzwWA96SrpVKWVpHwbSD4cnmeUK9gRqZ JNsOdUyxIV55JZYYX0Iq7EgsAHHE9gli3h5yfR+m5l3FbHU6A/qoc43XAHgLP9Magcr/ xzWA== X-Gm-Message-State: AOJu0YyhDijhZ4MgbotgCzpoPkV6iTRf6gsqJh6xMDwv4RAfy6IcWkza pXNfBYLtaJiTempY6wZzOaavWTlcAR+++L7xFa8tlehBoZVPaX1lICZ0LslPkcA= X-Google-Smtp-Source: AGHT+IG0F+v9RLfkDxmCogKyohbRv4HN/JSfXRuG/k5c7DYt81vKAXl+hJXm5aWNs9OgY5xMKmIKag== X-Received: by 2002:a05:6402:1941:b0:5bf:dd0:93ad with SMTP id 4fb4d7f45d1cf-5c0891a293amr8774775a12.27.1724818351072; Tue, 27 Aug 2024 21:12:31 -0700 (PDT) Received: from [127.0.1.1] (adsl-98.109.242.227.tellas.gr. [109.242.227.98]) by smtp.gmail.com with ESMTPSA id 4fb4d7f45d1cf-5c0bb1c29b9sm1712814a12.18.2024.08.27.21.12.28 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 27 Aug 2024 21:12:30 -0700 (PDT) From: Manos Pitsidianakis Date: Wed, 28 Aug 2024 07:11:49 +0300 Subject: [PATCH RESEND v9 8/9] rust: add utility procedural macro crate MIME-Version: 1.0 Message-Id: <20240828-rust-pl011-v9-8-35579191f17c@linaro.org> References: <20240828-rust-pl011-v9-0-35579191f17c@linaro.org> In-Reply-To: <20240828-rust-pl011-v9-0-35579191f17c@linaro.org> To: qemu-devel@nongnu.org Cc: Paolo Bonzini , =?utf-8?q?Marc-Andr=C3=A9_Lureau?= , =?utf-8?q?Daniel_P=2E_Berrang=C3=A9?= , Thomas Huth , =?utf-8?q?Philippe_Mathieu-Daud=C3=A9?= , Pierrick Bouvier , Richard Henderson , Gustavo Romero , =?utf-8?q?Alex_Benn=C3=A9e?= , Peter Maydell , Junjie Mao , Zhao Liu , Manos Pitsidianakis X-Mailer: b4 0.15-dev-c2c95 X-Developer-Signature: v=1; a=openpgp-sha256; l=7543; i=manos.pitsidianakis@linaro.org; h=from:subject:message-id; bh=ZxB9ieSoYRaqCxkSAitiBS3RFAT8Cug415DHJ1Rmjvo=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0VCYlFLUy9aQU5Bd0FLQVhjcHgzQi9mZ 25RQWNzbVlnQm16cU9MMXF0N2hzU0FDUXgrQjFOL3oxZ3pzQW9rCkJzQXlMd3RXMXluU0dncUhx YStKQWpNRUFBRUtBQjBXSVFUTVhCdE9SS0JXODRkd0hSQjNLY2R3ZjM0SjBBVUMKWnM2aml3QUt DUkIzS2Nkd2YzNEowRm5KRUFDWFRKblpoODl6S2NBNjhRTkdKNFBuNkIzbm10UTE4NmlzZSsyMw pFUDE0V3pYQlhNcWd4azEySjdHTGlYdEJBT2Fpdm9ldk5RNDdBT1NzWWdiNFZaSXVpV2lNUGJsN 3E1UGJhbXMzCkVkdTVJNnNvVDV4V1JwanNyUnVYUFZ5UVUrQjdrQnB4VW8vL3N5dFA3U1dTS3NQ VGErWU1SSmdoZmU1bFNvMUgKRmVzY1pXM0FRSFJIME9IUWMrYmtqQk5kaXZla082a095Z0pxSFh IS3pkdGNSeEROV0grb3RQMFNLdmpaWEJvVQpQSDkxOHlWTUNQQXhuVnZOemdGT2ZFOEtkblQvVF gwanVSSU1Ua0NNT2tnZUJyeUNGNTU0aGlLNWllbXpBNzBhCmJDenRTY2VmVjJ6RkUwT00xbjVpN TQ5U1BxQXpUWVRUNjZmTklsbnlSOStmRjRIa253R3FKeE9RR2NUYTVLT2MKR3IvMmtMNFlTellj ZHZhcW1ONmZzMDB4MC83RnAyTU15Q3ZkS3pVT0V2RzFaWjFjWVo5UmFiSUJRamVVWms2TApnOEV UNkI1Mm5YSldRdTV3RkNOMzl1VHpTN3ZBNFVrSlNsd04vQktwbS8ycTN6bkhjWGdwLzY3M3NFUV EwSGdkCnNIeGEzK0hubmNNV09WQ1hKU3htRDBVSndPcjBTdXE4Z3ZMMVR2UXY3bGVqL2RZSEY3R UhZejY2Qnd0Z1laVUwKNWZHOUJWcGNRMDJWVkJxZkc3dUZkN2N2YlVwQTR3b1hQbjNkR0JlY3My d3lueVZtK0tFcTYvdGxQWEJndzRJKwpEWEFwQUNmVXNRL2dCUHlXVVhSVHo5M202cXRUYzFMaSt hai96MTM0Q05VQVVYbTJ6RVV5RzVvZDRvRjVXdG0rCnhlSHFhQT09Cj1VdnRrCi0tLS0tRU5EIF BHUCBNRVNTQUdFLS0tLS0K X-Developer-Key: i=manos.pitsidianakis@linaro.org; a=openpgp; fpr=7C721DF9DB3CC7182311C0BF68BC211D47B421E1 Received-SPF: pass client-ip=2a00:1450:4864:20::532; envelope-from=manos.pitsidianakis@linaro.org; helo=mail-ed1-x532.google.com X-Spam_score_int: -20 X-Spam_score: -2.1 X-Spam_bar: -- X-Spam_report: (-2.1 / 5.0 requ) BAYES_00=-1.9, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001, T_SCC_BODY_TEXT_LINE=-0.01 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+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org This commit adds a helper crate library, qemu-api-macros for derive (and other procedural) macros to be used along qemu-api. It needs to be a separate library because in Rust, procedural macros, or macros that can generate arbitrary code, need to be special separate compilation units. Only one macro is introduced in this patch, #[derive(Object)]. It generates a constructor to register a QOM TypeInfo on init and it must be used on types that implement qemu_api::definitions::ObjectImpl trait. Signed-off-by: Manos Pitsidianakis --- MAINTAINERS | 1 + rust/meson.build | 1 + rust/qemu-api-macros/Cargo.lock | 47 ++++++++++++++++++++++++++++++++++++++++ rust/qemu-api-macros/Cargo.toml | 25 +++++++++++++++++++++ rust/qemu-api-macros/README.md | 1 + rust/qemu-api-macros/meson.build | 25 +++++++++++++++++++++ rust/qemu-api-macros/src/lib.rs | 43 ++++++++++++++++++++++++++++++++++++ rust/qemu-api/meson.build | 3 +++ 8 files changed, 146 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index d35e9f6b20bb23c7580de488ebaabc6c031343d2..727f3a7a2cfe600ffdb861bafada7db415d020e5 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -3352,6 +3352,7 @@ Rust M: Manos Pitsidianakis S: Maintained F: rust/qemu-api +F: rust/qemu-api-macros F: rust/rustfmt.toml SLIRP diff --git a/rust/meson.build b/rust/meson.build index 4a58d106b1dd1d7bee39dd129f57ddb5a95bd9b7..7a32b1b195083571931ad589965c10ddaf6383b1 100644 --- a/rust/meson.build +++ b/rust/meson.build @@ -1 +1,2 @@ +subdir('qemu-api-macros') subdir('qemu-api') diff --git a/rust/qemu-api-macros/Cargo.lock b/rust/qemu-api-macros/Cargo.lock new file mode 100644 index 0000000000000000000000000000000000000000..fdc0fce116c795da63fff3cfcddab164c98d47fa --- /dev/null +++ b/rust/qemu-api-macros/Cargo.lock @@ -0,0 +1,47 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "proc-macro2" +version = "1.0.86" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "qemu_api_macros" +version = "0.1.0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "quote" +version = "1.0.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "syn" +version = "2.0.72" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc4b9b9bf2add8093d3f2c0204471e951b2285580335de42f9d2534f3ae7a8af" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" diff --git a/rust/qemu-api-macros/Cargo.toml b/rust/qemu-api-macros/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..144cc3650fa04b2fa35a1185d970e1bab210a4eb --- /dev/null +++ b/rust/qemu-api-macros/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "qemu_api_macros" +version = "0.1.0" +edition = "2021" +authors = ["Manos Pitsidianakis "] +license = "GPL-2.0-or-later" +readme = "README.md" +homepage = "https://www.qemu.org" +description = "Rust bindings for QEMU - Utility macros" +repository = "https://gitlab.com/qemu-project/qemu/" +resolver = "2" +publish = false +keywords = [] +categories = [] + +[lib] +proc-macro = true + +[dependencies] +proc-macro2 = "1" +quote = "1" +syn = "2" + +# Do not include in any global workspace +[workspace] diff --git a/rust/qemu-api-macros/README.md b/rust/qemu-api-macros/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f60f54ac4be08ccfbcfea8e21ceb15d25012dfc3 --- /dev/null +++ b/rust/qemu-api-macros/README.md @@ -0,0 +1 @@ +# `qemu-api-macros` - Utility macros for defining QEMU devices diff --git a/rust/qemu-api-macros/meson.build b/rust/qemu-api-macros/meson.build new file mode 100644 index 0000000000000000000000000000000000000000..48af91ed389120ddd6e15f6ee002f5da7063e329 --- /dev/null +++ b/rust/qemu-api-macros/meson.build @@ -0,0 +1,25 @@ +add_languages('rust', required: true, native: true) + +quote_dep = dependency('quote-1-rs', native: true) +syn_dep = dependency('syn-2-rs', native: true) +proc_macro2_dep = dependency('proc-macro2-1-rs', native: true) + +_qemu_api_macros_rs = import('rust').proc_macro( + 'qemu_api_macros', + files('src/lib.rs'), + override_options: ['rust_std=2021', 'build.rust_std=2021'], + rust_args: [ + '--cfg', 'use_fallback', + '--cfg', 'feature="syn-error"', + '--cfg', 'feature="proc-macro"', + ], + dependencies: [ + proc_macro2_dep, + quote_dep, + syn_dep, + ], +) + +qemu_api_macros = declare_dependency( + link_with: _qemu_api_macros_rs, +) diff --git a/rust/qemu-api-macros/src/lib.rs b/rust/qemu-api-macros/src/lib.rs new file mode 100644 index 0000000000000000000000000000000000000000..331bc9e215e0115191865cb8a29c4605e03fdaa8 --- /dev/null +++ b/rust/qemu-api-macros/src/lib.rs @@ -0,0 +1,43 @@ +// Copyright 2024, Linaro Limited +// Author(s): Manos Pitsidianakis +// SPDX-License-Identifier: GPL-2.0-or-later + +use proc_macro::TokenStream; +use quote::{format_ident, quote}; +use syn::{parse_macro_input, DeriveInput}; + +#[proc_macro_derive(Object)] +pub fn derive_object(input: TokenStream) -> TokenStream { + let input = parse_macro_input!(input as DeriveInput); + + let name = input.ident; + let module_static = format_ident!("__{}_LOAD_MODULE", name); + + let expanded = quote! { + #[allow(non_upper_case_globals)] + #[used] + #[cfg_attr(target_os = "linux", link_section = ".ctors")] + #[cfg_attr(target_os = "macos", link_section = "__DATA,__mod_init_func")] + #[cfg_attr(target_os = "windows", link_section = ".CRT$XCU")] + pub static #module_static: extern "C" fn() = { + extern "C" fn __register() { + unsafe { + ::qemu_api::bindings::type_register_static(&<#name as ::qemu_api::definitions::ObjectImpl>::TYPE_INFO); + } + } + + extern "C" fn __load() { + unsafe { + ::qemu_api::bindings::register_module_init( + Some(__register), + ::qemu_api::bindings::module_init_type_MODULE_INIT_QOM + ); + } + } + + __load + }; + }; + + TokenStream::from(expanded) +} diff --git a/rust/qemu-api/meson.build b/rust/qemu-api/meson.build index cf2b465e9f7cc7fb10af0d3aac469b58211cd64e..2030c24ed980596da0d53944252409e535510195 100644 --- a/rust/qemu-api/meson.build +++ b/rust/qemu-api/meson.build @@ -14,6 +14,9 @@ _qemu_api_rs = static_library( '--cfg', 'MESON', '--cfg', 'feature="allocator"', ], + dependencies: [ + qemu_api_macros, + ], ) qemu_api = declare_dependency( From patchwork Wed Aug 28 04:11:50 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Manos Pitsidianakis X-Patchwork-Id: 13780494 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.lore.kernel.org (Postfix) with ESMTPS id 80EB5C5472D for ; Wed, 28 Aug 2024 04:14:05 +0000 (UTC) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1sjA33-0006f7-17; Wed, 28 Aug 2024 00:12:45 -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 1sjA31-0006a3-Mq for qemu-devel@nongnu.org; Wed, 28 Aug 2024 00:12:43 -0400 Received: from mail-ed1-x529.google.com ([2a00:1450:4864:20::529]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_128_GCM_SHA256:128) (Exim 4.90_1) (envelope-from ) id 1sjA2v-0000mj-VM for qemu-devel@nongnu.org; Wed, 28 Aug 2024 00:12:43 -0400 Received: by mail-ed1-x529.google.com with SMTP id 4fb4d7f45d1cf-5c0a9f2b967so3286560a12.2 for ; Tue, 27 Aug 2024 21:12:37 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; t=1724818356; x=1725423156; darn=nongnu.org; h=cc:to:in-reply-to:references:message-id:content-transfer-encoding :mime-version:subject:date:from:from:to:cc:subject:date:message-id :reply-to; bh=hbFkkA2m1mWh6CYnu+oLTySkKf4EG7o54jtbhmo/J18=; b=X4q6/UZ1UuLQXjJ1jpAMy71tp0+zioPZXfXy/dfrVYawalx2wbK4H88sn/Ac1ESPlS vDFrAyY+2B4DvgphWz4tHAHQlzqM6kZeV7LMb+4rO85gySTMMsSQG+iTOqMfkmjL/kB1 4nM5nADh5omGJKKSNjSn5xQNh23fGzE3sPLjUzKCCSNXmvi7afddBx1yA4EpV1qkyaV1 lD/3vLdL4i5O+5nig7ExBMrg/vFazbRjjtz9x19mzdB1Kkb2txctEypfqSrxKzKLThiY AMpH5bZLK02ZfG2B44qT5DRi3oVjy5xWMml0gBXmYd/e+coSk52ncKMLl34HVgzWSf9d wakA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1724818356; x=1725423156; h=cc:to:in-reply-to:references:message-id:content-transfer-encoding :mime-version:subject:date:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=hbFkkA2m1mWh6CYnu+oLTySkKf4EG7o54jtbhmo/J18=; b=k/nKR/htSC04EmJx/m6ifOqGTVlURPgUgCbsDxzVEt5aqDz/7/oETSjYj6TZrHPUXo abchjcG1IwF0isTHM77zFfWyPYe60VQhrhDq1hpTRYZAnwnxSAKJ5y+L6vqLpE+hcoWX iKH1HQcmpM+WwL6+GMc4K8y0N4wNcSJGmV1WZIVTtJX6WXKSNqgOQgMk0G1bbKZIFjV7 ctb7Pop1YYXlB9+j/JoBJZnDyxxFrADTvoMABYaVdOIEGsr/XZFZj7Hb2cwSsNInkxA5 3eLiqNzFe2ebuGk2YkIQdFXmVvHMjDcB8yTQ7EHLrKfaFLTaGVRA/FL+STP0IzzgRnZ2 AxGg== X-Gm-Message-State: AOJu0Yz+f8Q9Oy/eUf0Xknc/qn95bRl7ZXfrI/pdMRQKBGq1f4IuhY82 yqxyX5d/7lBSX/vG6Kdk25RR5t2ppLt3A5mMINuMEJTWPZcNIK/V+HE7KP2JDdw= X-Google-Smtp-Source: AGHT+IG3WrP+nTPwgBw4DUSYhKU6UDAauMQEyeZyFoYT6b8v6uQUWXNx1b3W1mUlU60nOTP7q3nyGA== X-Received: by 2002:a05:6402:2807:b0:5be:fb85:38d1 with SMTP id 4fb4d7f45d1cf-5c21466ef13mr432367a12.18.1724818355216; Tue, 27 Aug 2024 21:12:35 -0700 (PDT) Received: from [127.0.1.1] (adsl-98.109.242.227.tellas.gr. [109.242.227.98]) by smtp.gmail.com with ESMTPSA id 4fb4d7f45d1cf-5c0bb1c29b9sm1712814a12.18.2024.08.27.21.12.31 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 27 Aug 2024 21:12:34 -0700 (PDT) From: Manos Pitsidianakis Date: Wed, 28 Aug 2024 07:11:50 +0300 Subject: [PATCH RESEND v9 9/9] rust: add PL011 device model MIME-Version: 1.0 Message-Id: <20240828-rust-pl011-v9-9-35579191f17c@linaro.org> References: <20240828-rust-pl011-v9-0-35579191f17c@linaro.org> In-Reply-To: <20240828-rust-pl011-v9-0-35579191f17c@linaro.org> To: qemu-devel@nongnu.org Cc: Paolo Bonzini , =?utf-8?q?Marc-Andr=C3=A9_Lureau?= , =?utf-8?q?Daniel_P=2E_Berrang=C3=A9?= , Thomas Huth , =?utf-8?q?Philippe_Mathieu-Daud=C3=A9?= , Pierrick Bouvier , Richard Henderson , Gustavo Romero , =?utf-8?q?Alex_Benn=C3=A9e?= , Peter Maydell , Junjie Mao , Zhao Liu , Manos Pitsidianakis X-Mailer: b4 0.15-dev-c2c95 X-Developer-Signature: v=1; a=openpgp-sha256; l=91643; i=manos.pitsidianakis@linaro.org; h=from:subject:message-id; bh=HQNktfVLiqhTk7PXsGPxU/5OZoorE//I99vyOJMPYrM=; b=LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tCgpvd0VCYlFLUy9aQU5Bd0FLQVhjcHgzQi9mZ 25RQWNzbVlnQm16cU9NRWlpNWIyUG1QV0dKNFE4MlJUVGNoTWlMClhUSzkrV1N6RzNxQWxIeXVL VjJKQWpNRUFBRUtBQjBXSVFUTVhCdE9SS0JXODRkd0hSQjNLY2R3ZjM0SjBBVUMKWnM2ampBQUt DUkIzS2Nkd2YzNEowQW5WRC85M2JXbGVWNllHMUJHMXBjTFJpUU15a1UrUHhFUEtTQnNvc256Ng phZ1RBVlRhWTM1NVpBVU5keUFCZHRUWG5HamNIc1h6NHJOZXFIQzhaSk1vZFhLeWh6T0U0OFNrS EpiZW9vQldLCmhpNVd1Qnp4T29DNWNIYStzSnhuUHFxalA3bllqajdpRkhkcFdPS3lhaGZ4YkFq c3dlVEJvb2I2T0FUZWQyUisKZGlJN1BRaWltc0x1dVF2YTE2dGNseE1HNXp0bnpIdmlkUExFQXB CaG9ENkd6MXdJNUpuWlhVM0dablBialYxZwp6bTY0NU5FYUNyT2laVVNKNUptbGRYaEZMd0RrZ0 dDc2xMeFp5cHl3S3Z0MG1xUmVIUG5HK0MxMTF6SFBWTnlMCnB0dy9TTmhWRUQvRks5cHEzd2pNb 1pJTnBlYlZkZnBsdFRNV2Uyb0xMMGNWVzR4TlNOVi9Cc0prMjlxREZlZE0Kc1lvcnF3YlJCRnR6 K0prdzBCWms1SkY5b083K2h2bklScXdiQ0d0ekxiajQxN3E2ckdXVkpUNFJ4N1pEQ24rQgpqSUd saUZnTi96U29Wd0tkMnR1cXVXaEl2cVlrcVREdXdjSExySjNWS1JQME1GdENiT254S2g4UUlncG J2VXhWCko5eUU3aGgyT3pzeWhyWVNqWXJSZEp1akliNWdyU0paYmdNUHBSTTJYNGFTYStmaFdTR WozYUZqbkRxeU5ldWIKY3RQZ1dDd1JnbThCU2pjdk41UTV2U1FSTWFHSC9tVVdhQlduWHllalha cVpUN05ZSjZLQks4akd6K01kL2tSMwp1dVArMTRsbzF6c3FNaEtBU1VkbU9hMzFYVTdWeUZmQkV Yai8xZ3luS3VUald0SXNYTzBWOUNWMHF6cm9GMmsvCk1oMVZ5Zz09Cj1jT3dzCi0tLS0tRU5EIF BHUCBNRVNTQUdFLS0tLS0K X-Developer-Key: i=manos.pitsidianakis@linaro.org; a=openpgp; fpr=7C721DF9DB3CC7182311C0BF68BC211D47B421E1 Received-SPF: pass client-ip=2a00:1450:4864:20::529; envelope-from=manos.pitsidianakis@linaro.org; helo=mail-ed1-x529.google.com X-Spam_score_int: -20 X-Spam_score: -2.1 X-Spam_bar: -- X-Spam_report: (-2.1 / 5.0 requ) BAYES_00=-1.9, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001, T_SCC_BODY_TEXT_LINE=-0.01 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+qemu-devel=archiver.kernel.org@nongnu.org Sender: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org 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=aarch64-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 --- MAINTAINERS | 5 + meson.build | 24 + hw/arm/Kconfig | 33 +- 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/definitions.rs | 20 + rust/hw/char/pl011/src/device.rs | 594 +++++++++++++++++++++ rust/hw/char/pl011/src/device_class.rs | 59 ++ rust/hw/char/pl011/src/lib.rs | 585 ++++++++++++++++++++ rust/hw/char/pl011/src/memory_ops.rs | 57 ++ rust/hw/meson.build | 1 + rust/meson.build | 2 + scripts/archive-source.sh | 5 +- scripts/make-release | 5 +- scripts/rust/rust_root_crate.sh | 13 + subprojects/.gitignore | 11 + subprojects/arbitrary-int-1-rs.wrap | 7 + subprojects/bilge-0.2-rs.wrap | 7 + subprojects/bilge-impl-0.2-rs.wrap | 7 + subprojects/either-1-rs.wrap | 7 + subprojects/itertools-0.11-rs.wrap | 7 + .../packagefiles/arbitrary-int-1-rs/meson.build | 19 + subprojects/packagefiles/bilge-0.2-rs/meson.build | 29 + .../packagefiles/bilge-impl-0.2-rs/meson.build | 45 ++ subprojects/packagefiles/either-1-rs/meson.build | 24 + .../packagefiles/itertools-0.11-rs/meson.build | 30 ++ .../packagefiles/proc-macro-error-1-rs/meson.build | 40 ++ .../proc-macro-error-attr-1-rs/meson.build | 32 ++ .../packagefiles/proc-macro2-1-rs/meson.build | 31 ++ subprojects/packagefiles/quote-1-rs/meson.build | 29 + subprojects/packagefiles/syn-2-rs/meson.build | 40 ++ .../packagefiles/unicode-ident-1-rs/meson.build | 20 + subprojects/proc-macro-error-1-rs.wrap | 7 + subprojects/proc-macro-error-attr-1-rs.wrap | 7 + subprojects/proc-macro2-1-rs.wrap | 7 + subprojects/quote-1-rs.wrap | 7 + subprojects/syn-2-rs.wrap | 7 + subprojects/unicode-ident-1-rs.wrap | 7 + 45 files changed, 2043 insertions(+), 13 deletions(-) diff --git a/MAINTAINERS b/MAINTAINERS index 727f3a7a2cfe600ffdb861bafada7db415d020e5..cb65018b4bf3958952ecd7c8d703abee838cc265 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -1189,6 +1189,11 @@ F: include/hw/*/microbit*.h F: tests/qtest/microbit-test.c F: docs/system/arm/nrf.rst +ARM PL011 Rust device +M: Manos Pitsidianakis +S: Maintained +F: rust/hw/char/pl011/ + AVR Machines ------------- diff --git a/meson.build b/meson.build index 7f05466d128776ad8dbf403179734e6831b023c0..a4249fc24f77526b14a2fc570498d5ea34f48bbe 100644 --- a/meson.build +++ b/meson.build @@ -3489,6 +3489,7 @@ qom_ss = ss.source_set() system_ss = ss.source_set() specific_fuzz_ss = ss.source_set() specific_ss = ss.source_set() +rust_devices_ss = ss.source_set() stub_ss = ss.source_set() trace_ss = ss.source_set() user_ss = ss.source_set() @@ -4002,6 +4003,29 @@ foreach target : target_dirs arch_srcs += target_specific.sources() arch_deps += target_specific.dependencies() + if have_rust and have_system + target_rust = rust_devices_ss.apply(config_target, strict: false) + crates = [] + foreach dep : target_rust.dependencies() + crates += dep.get_variable('crate') + endforeach + if crates.length() > 0 + rlib_rs = custom_target('rust_' + target.underscorify() + '.rs', + output: 'rust_' + target.underscorify() + '.rs', + command: [find_program('scripts/rust/rust_root_crate.sh')] + crates, + capture: true, + build_by_default: true, + build_always_stale: true) + rlib = static_library('rust_' + target.underscorify(), + rlib_rs, + dependencies: target_rust.dependencies(), + override_options: ['rust_std=2021', 'build.rust_std=2021'], + rust_args: rustc_config_args, + rust_abi: 'c') + arch_deps += declare_dependency(link_whole: [rlib]) + endif + endif + # allow using headers from the dependencies but do not include the sources, # because this emulator only needs those in "objects". For external # dependencies, the full dependency is included below in the executable. diff --git a/hw/arm/Kconfig b/hw/arm/Kconfig index 1ad60da7aa2d1fcb157561461c229cb486b65e3a..45438c1bc4b842f6d28005c7efa0a3ac32272d37 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 @@ -80,7 +81,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 @@ -93,7 +95,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 @@ -119,7 +122,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 @@ -228,7 +232,8 @@ config Z2 depends on TCG && ARM select PFLASH_CFI01 select WM8750 - select PL011 # UART + select PL011 if !HAVE_RUST # UART + select X_PL011_RUST if HAVE_RUST # UART select PXA2XX config REALVIEW @@ -248,7 +253,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 @@ -273,7 +279,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 @@ -297,7 +304,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 @@ -356,7 +364,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 @@ -440,7 +449,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 @@ -515,7 +525,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 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..f9f5c3909887451f71360a7986d79e57fdb43c91 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 0000000000000000000000000000000000000000..4d934f30afe13ddff418db8ec9e8b8eb25a9e8d0 --- /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 0000000000000000000000000000000000000000..a1732a9e97fe3211547e30bc9319382e6394ed5b --- /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 0000000000000000000000000000000000000000..5716dc43ef6facdcf1cc963108347bbf4d12cf0e --- /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 0000000000000000000000000000000000000000..71eaff2035d5a65b57ae32dfeecf3d87bbc7b396 --- /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 0000000000000000000000000000000000000000..b58cebb186e99efe184117bb931a341543d4466b --- /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 = 3 + +[[package]] +name = "arbitrary-int" +version = "1.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c84fc003e338a6f69fbd4f7fe9f92b535ff13e9af8997f3b14b6ddff8b1df46d" + +[[package]] +name = "bilge" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc707ed8ebf81de5cd6c7f48f54b4c8621760926cdf35a57000747c512e67b57" +dependencies = [ + "arbitrary-int", + "bilge-impl", +] + +[[package]] +name = "bilge-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "feb11e002038ad243af39c2068c8a72bcf147acf05025dcdb916fcc000adb2d8" +dependencies = [ + "itertools", + "proc-macro-error", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "either" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3dca9240753cf90908d7e4aac30f630662b02aebaa1b58a3cadabdb23385b58b" + +[[package]] +name = "itertools" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57" +dependencies = [ + "either", +] + +[[package]] +name = "pl011" +version = "0.1.0" +dependencies = [ + "bilge", + "bilge-impl", + "qemu_api", + "qemu_api_macros", +] + +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + +[[package]] +name = "proc-macro2" +version = "1.0.84" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec96c6a92621310b51366f1e28d05ef11489516e93be030060e5fc12024a49d6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "qemu_api" +version = "0.1.0" + +[[package]] +name = "qemu_api_macros" +version = "0.1.0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "quote" +version = "1.0.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "syn" +version = "2.0.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c42f3f41a2de00b01c0aaad383c5a45241efc8b2d1eda5661812fda5f3cdcff5" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" + +[[package]] +name = "version_check" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" diff --git a/rust/hw/char/pl011/Cargo.toml b/rust/hw/char/pl011/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..b089e3dded623131ee13b4af8145b84388755df7 --- /dev/null +++ b/rust/hw/char/pl011/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "pl011" +version = "0.1.0" +edition = "2021" +authors = ["Manos Pitsidianakis "] +license = "GPL-2.0-or-later" +readme = "README.md" +homepage = "https://www.qemu.org" +description = "pl011 device model for QEMU" +repository = "https://gitlab.com/epilys/rust-for-qemu" +resolver = "2" +publish = false +keywords = [] +categories = [] + +[lib] +crate-type = ["staticlib"] + +[dependencies] +bilge = { version = "0.2.0" } +bilge-impl = { version = "0.2.0" } +qemu_api = { path = "../../../qemu-api" } +qemu_api_macros = { path = "../../../qemu-api-macros" } + +# Do not include in any global workspace +[workspace] diff --git a/rust/hw/char/pl011/README.md b/rust/hw/char/pl011/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cd7dea31634241cbf96b0be13f21d52bbd8ae750 --- /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® UART (PL011) +device in QEMU. + +## Build static lib + +Host build target must be explicitly specified: + +```sh +cargo build --target x86_64-unknown-linux-gnu +``` + +Replace host target triplet if necessary. + +## Generate Rust documentation + +To generate docs for this crate, including private items: + +```sh +cargo doc --no-deps --document-private-items --target x86_64-unknown-linux-gnu +``` + +To include direct dependencies like `bilge` (bitmaps for register types): + +```sh +cargo tree --depth 1 -e normal --prefix none \ + | cut -d' ' -f1 \ + | xargs printf -- '-p %s\n' \ + | xargs cargo doc --no-deps --document-private-items --target x86_64-unknown-linux-gnu +``` diff --git a/rust/hw/char/pl011/meson.build b/rust/hw/char/pl011/meson.build new file mode 100644 index 0000000000000000000000000000000000000000..547cca5a96f7eef284caf1949380b65f7d015d92 --- /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 = dependency('bilge-0.2-rs') +bilge_impl_dep = dependency('bilge-impl-0.2-rs') + +_libpl011_rs = static_library( + 'pl011', + files('src/lib.rs'), + override_options: ['rust_std=2021', 'build.rust_std=2021'], + rust_abi: 'rust', + dependencies: [ + bilge_dep, + bilge_impl_dep, + qemu_api, + qemu_api_macros, + ], +) + +rust_devices_ss.add(when: 'CONFIG_X_PL011_RUST', if_true: [declare_dependency( + link_whole: [_libpl011_rs], + # Putting proc macro crates in `dependencies` is necessary for Meson to find + # them when compiling the root per-target static rust lib. + dependencies: [bilge_impl_dep, qemu_api_macros], + variables: {'crate': 'pl011'}, +)]) diff --git a/rust/hw/char/pl011/src/definitions.rs b/rust/hw/char/pl011/src/definitions.rs new file mode 100644 index 0000000000000000000000000000000000000000..baafe1d3908e695a895c3f8ef4cae3e390654f1f --- /dev/null +++ b/rust/hw/char/pl011/src/definitions.rs @@ -0,0 +1,20 @@ +// Copyright 2024, Linaro Limited +// Author(s): Manos Pitsidianakis +// SPDX-License-Identifier: GPL-2.0-or-later + +//! Definitions required by QEMU when registering the device. + +use core::mem::MaybeUninit; + +use qemu_api::{bindings::*, definitions::ObjectImpl}; + +use crate::device::PL011State; + +pub const TYPE_PL011: &std::ffi::CStr = c"pl011"; + +#[used] +pub static VMSTATE_PL011: VMStateDescription = VMStateDescription { + name: PL011State::TYPE_INFO.name, + unmigratable: true, + ..unsafe { MaybeUninit::::zeroed().assume_init() } +}; diff --git a/rust/hw/char/pl011/src/device.rs b/rust/hw/char/pl011/src/device.rs new file mode 100644 index 0000000000000000000000000000000000000000..07cf2fa4e1f3985b24a25e7cf86223bf699cf022 --- /dev/null +++ b/rust/hw/char/pl011/src/device.rs @@ -0,0 +1,594 @@ +// 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] = [0x11, 0x10, 0x14, 0x00, 0x0d, 0xf0, 0x05, 0xb1]; + +const DATA_BREAK: u32 = 1 << 10; + +/// QEMU sourced constant. +pub const PL011_FIFO_DEPTH: usize = 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, + pub readbuff: u32, + #[doc(alias = "fr")] + pub flags: registers::Flags, + #[doc(alias = "lcr")] + pub line_control: registers::LineControl, + #[doc(alias = "rsr")] + pub receive_status_error_clear: registers::ReceiveStatusErrorClear, + #[doc(alias = "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 = "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 = "irq")] + pub interrupts: [qemu_irq; 6usize], + #[doc(alias = "clk")] + pub clock: NonNull, + #[doc(alias = "migrate_clk")] + pub migrate_clock: bool, +} + +impl ObjectImpl for PL011State { + type Class = PL011Class; + const TYPE_INFO: qemu_api::bindings::TypeInfo = qemu_api::type_info! { Self }; + const TYPE_NAME: &'static CStr = c"pl011"; + const PARENT_TYPE_NAME: Option<&'static CStr> = Some(TYPE_SYS_BUS_DEVICE); + const ABSTRACT: bool = false; + const INSTANCE_INIT: Option = Some(pl011_init); + const INSTANCE_POST_INIT: Option = None; + const INSTANCE_FINALIZE: Option = None; +} + +#[repr(C)] +pub struct PL011Class { + _inner: [u8; 0], +} + +impl qemu_api::definitions::Class for PL011Class { + const CLASS_INIT: Option< + unsafe extern "C" fn(klass: *mut ObjectClass, data: *mut core::ffi::c_void), + > = Some(crate::device_class::pl011_class_init); + const CLASS_BASE_INIT: Option< + unsafe extern "C" fn(klass: *mut ObjectClass, data: *mut core::ffi::c_void), + > = None; +} + +#[used] +pub static CLK_NAME: &CStr = c"clk"; + +impl PL011State { + pub fn init(&mut self) { + let dev = addr_of_mut!(*self).cast::(); + // SAFETY: + // + // self and self.iomem are guaranteed to be valid at this point since callers + // must make sure the `self` reference is valid. + unsafe { + memory_region_init_io( + addr_of_mut!(self.iomem), + addr_of_mut!(*self).cast::(), + &PL011_OPS, + addr_of_mut!(*self).cast::(), + Self::TYPE_INFO.name, + 0x1000, + ); + let sbd = 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 which + // calls this function to initialize the fields; therefore no code is + // able to access an invalid self.clock value. + unsafe { + self.clock = NonNull::new(qdev_init_clock_in( + dev, + CLK_NAME.as_ptr(), + None, /* pl011_clock_update */ + addr_of_mut!(*self).cast::(), + ClockEvent_ClockUpdate, + )) + .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) => { + u64::from(PL011_ID_ARM[((offset - 0xfe0) >> 2) as usize]) + } + Err(_) => { + // qemu_log_mask(LOG_GUEST_ERROR, "pl011_read: Bad offset 0x%x\n", (int)offset); + 0 + } + Ok(DR) => { + // s->flags &= ~PL011_FLAG_RXFF; + self.flags.set_receive_fifo_full(false); + let c = self.read_fifo[self.read_pos]; + if self.read_count > 0 { + self.read_count -= 1; + self.read_pos = (self.read_pos + 1) & (self.fifo_depth() - 1); + } + if self.read_count == 0 { + // self.flags |= PL011_FLAG_RXFE; + self.flags.set_receive_fifo_empty(true); + } + if self.read_count + 1 == self.read_trigger { + //self.int_level &= ~ INT_RX; + self.int_level &= !registers::INT_RX; + } + // Update error bits. + self.receive_status_error_clear = c.to_be_bytes()[3].into(); + self.update(); + // Must call qemu_chr_fe_accept_input, so return Continue: + return std::ops::ControlFlow::Continue(c.into()); + } + Ok(RSR) => u8::from(self.receive_status_error_clear).into(), + Ok(FR) => u16::from(self.flags).into(), + Ok(FBRD) => self.fbrd.into(), + Ok(ILPR) => self.ilpr.into(), + Ok(IBRD) => self.ibrd.into(), + Ok(LCR_H) => u16::from(self.line_control).into(), + Ok(CR) => { + // We exercise our self-control. + u16::from(self.control).into() + } + Ok(FLS) => self.ifl.into(), + Ok(IMSC) => self.int_enabled.into(), + Ok(RIS) => self.int_level.into(), + Ok(MIS) => u64::from(self.int_level & self.int_enabled), + Ok(ICR) => { + // "The UARTICR Register is the interrupt clear register and is write-only" + // Source: ARM DDI 0183G 3.3.13 Interrupt Clear Register, UARTICR + 0 + } + Ok(DMACR) => self.dmacr.into(), + }) + } + + pub fn write(&mut self, offset: hwaddr, value: u64) { + // eprintln!("write offset {offset} value {value}"); + use RegisterOffset::*; + let value: u32 = value as u32; + match RegisterOffset::try_from(offset) { + Err(_bad_offset) => { + eprintln!("write bad offset {offset} value {value}"); + } + Ok(DR) => { + // ??? Check if transmitter is enabled. + let ch: u8 = 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 instance 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 |= registers::INT_TX; + self.update(); + } + Ok(RSR) => { + self.receive_status_error_clear = 0.into(); + } + Ok(FR) => { + // flag writes are ignored + } + Ok(ILPR) => { + self.ilpr = value; + } + Ok(IBRD) => { + self.ibrd = value; + } + Ok(FBRD) => { + self.fbrd = value; + } + Ok(LCR_H) => { + let value = value as u16; + let new_val: registers::LineControl = 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 = new_val.send_break().into(); + // SAFETY: self.char_backend is a valid CharBackend instance 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 = new_val; + self.set_read_trigger(); + } + Ok(CR) => { + // ??? Need to implement the enable bit. + let value = value as u16; + self.control = value.into(); + self.loopback_mdmctrl(); + } + Ok(FLS) => { + self.ifl = value; + self.set_read_trigger(); + } + Ok(IMSC) => { + self.int_enabled = value; + self.update(); + } + Ok(RIS) => {} + Ok(MIS) => {} + Ok(ICR) => { + self.int_level &= !value; + self.update(); + } + Ok(DMACR) => { + self.dmacr = value; + if value & 3 > 0 { + // qemu_log_mask(LOG_UNIMP, "pl011: DMA not implemented\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 <= CR.Out2 + * FR.DCD <= CR.Out1 + * FR.CTS <= CR.RTS + * FR.DSR <= 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 = s->flags & ~(PL011_FLAG_RI | PL011_FLAG_DCD | + // PL011_FLAG_DSR | PL011_FLAG_CTS); + //fr |= (cr & CR_OUT2) ? PL011_FLAG_RI : 0; + //fr |= (cr & CR_OUT1) ? PL011_FLAG_DCD : 0; + //fr |= (cr & CR_RTS) ? PL011_FLAG_CTS : 0; + //fr |= (cr & CR_DTR) ? PL011_FLAG_DSR : 0; + // + self.flags.set_ring_indicator(self.control.out_2()); + self.flags.set_data_carrier_detect(self.control.out_1()); + self.flags.set_clear_to_send(self.control.request_to_send()); + self.flags + .set_data_set_ready(self.control.data_transmit_ready()); + + // Change interrupts based on updated FR + let mut il = self.int_level; + + il &= !Interrupt::MS; + //il |= (fr & PL011_FLAG_DSR) ? INT_DSR : 0; + //il |= (fr & PL011_FLAG_DCD) ? INT_DCD : 0; + //il |= (fr & PL011_FLAG_CTS) ? INT_CTS : 0; + //il |= (fr & PL011_FLAG_RI) ? INT_RI : 0; + + if self.flags.data_set_ready() { + il |= Interrupt::DSR as u32; + } + if self.flags.data_carrier_detect() { + il |= Interrupt::DCD as u32; + } + if self.flags.clear_to_send() { + il |= Interrupt::CTS as u32; + } + if self.flags.ring_indicator() { + il |= Interrupt::RI as u32; + } + self.int_level = il; + self.update(); + } + + fn loopback_break(&mut self, enable: bool) { + if enable { + self.loopback_tx(DATA_BREAK); + } + } + + fn set_read_trigger(&mut self) { + //#if 0 + // /* The docs say the RX interrupt is triggered when the FIFO exceeds + // the threshold. However linux only reads the FIFO in response to an + // interrupt. Triggering the interrupt when the FIFO is non-empty seems + // to make things work. */ + // if (s->lcr & LCR_FEN) + // s->read_trigger = (s->ifl >> 1) & 0x1c; + // else + //#endif + self.read_trigger = 1; + } + + pub fn realize(&mut self) { + // SAFETY: self.char_backend has the correct size and alignment for a + // CharBackend object, and its callbacks are of the correct types. + unsafe { + qemu_chr_fe_set_handlers( + addr_of_mut!(self.char_backend), + Some(pl011_can_receive), + Some(pl011_receive), + Some(pl011_event), + None, + addr_of_mut!(*self).cast::(), + core::ptr::null_mut(), + true, + ); + } + } + + pub fn reset(&mut self) { + self.line_control.reset(); + self.receive_status_error_clear.reset(); + self.dmacr = 0; + self.int_enabled = 0; + self.int_level = 0; + self.ilpr = 0; + self.ibrd = 0; + self.fbrd = 0; + self.read_trigger = 1; + self.ifl = 0x12; + self.control.reset(); + self.flags = 0.into(); + self.reset_fifo(); + } + + pub fn reset_fifo(&mut self) { + self.read_count = 0; + self.read_pos = 0; + + /* 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 == bindings::QEMUChrEvent_CHR_EVENT_BREAK && !self.fifo_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 = 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; + // s->flags &= ~PL011_FLAG_RXFE; + self.flags.set_receive_fifo_empty(false); + if self.read_count == depth { + //s->flags |= PL011_FLAG_RXFF; + self.flags.set_receive_fifo_full(true); + } + + if self.read_count == self.read_trigger { + self.int_level |= registers::INT_RX; + self.update(); + } + } + + pub fn update(&mut self) { + let flags = 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 != 0)) }; + } + } +} + +/// Which bits in the interrupt status matter for each outbound IRQ line ? +pub const IRQMASK: [u32; 6] = [ + /* combined IRQ */ + Interrupt::E + | Interrupt::MS + | Interrupt::RT as u32 + | Interrupt::TX as u32 + | Interrupt::RX as u32, + Interrupt::RX as u32, + Interrupt::TX as u32, + Interrupt::RT as u32, + Interrupt::MS, + Interrupt::E, +]; + +/// # 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 { + assert!(!opaque.is_null()); + let state = 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, +) { + assert!(!opaque.is_null()); + let mut state = NonNull::new_unchecked(opaque.cast::()); + if state.as_ref().loopback_enabled() { + return; + } + if size > 0 { + assert!(!buf.is_null()); + state + .as_mut() + .put_fifo(c_uint::from(unsafe { 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) { + assert!(!opaque.is_null()); + let mut state = 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 `chr`. +#[no_mangle] +pub unsafe extern "C" fn pl011_create( + addr: u64, + irq: qemu_irq, + chr: *mut Chardev, +) -> *mut DeviceState { + let dev: *mut DeviceState = unsafe { qdev_new(PL011State::TYPE_INFO.name) }; + assert!(!dev.is_null()); + let sysbus: *mut SysBusDevice = dev as *mut SysBusDevice; + + qdev_prop_set_chr(dev, bindings::TYPE_CHARDEV.as_ptr(), chr); + sysbus_realize_and_unref(sysbus, addr_of!(error_fatal) as *mut *mut 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) { + assert!(!obj.is_null()); + let mut state = 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/src/device_class.rs new file mode 100644 index 0000000000000000000000000000000000000000..631d276e72d444011ef5ef28ce169815439011d6 --- /dev/null +++ b/rust/hw/char/pl011/src/device_class.rs @@ -0,0 +1,59 @@ +// Copyright 2024, Linaro Limited +// Author(s): Manos Pitsidianakis +// SPDX-License-Identifier: GPL-2.0-or-later + +use core::ptr::NonNull; + +use qemu_api::bindings::*; + +use crate::{definitions::VMSTATE_PL011, device::PL011State}; + +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 => PL011_PROPERTIES, + realize_fn => Some(pl011_realize), + reset_fn => Some(pl011_reset), + vmsd => 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) { + assert!(!dev.is_null()); + let mut state = 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) { + assert!(!dev.is_null()); + let mut state = 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 0000000000000000000000000000000000000000..54de89538a59c6f29a419279200f75d516913bad --- /dev/null +++ b/rust/hw/char/pl011/src/lib.rs @@ -0,0 +1,585 @@ +// 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® UART (PL011) +// device in QEMU. +// +#![doc = include_str!("../README.md")] +//! # Library crate +//! +//! See [`PL011State`](crate::device::PL011State) for the device model type 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 definitions; +pub mod device; +pub mod device_class; +pub mod memory_ops; + +/// Offset of each register from the base memory address of the device. +/// +/// # Source +/// ARM DDI 0183G, Table 3-1 p.3-3 +#[doc(alias = "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 = "UARTDR")] + DR = 0x000, + /// Receive Status Register or Error Clear Register + #[doc(alias = "UARTRSR")] + #[doc(alias = "UARTECR")] + RSR = 0x004, + /// Flag Register + /// + /// A read of this register shows if transmission is complete + #[doc(alias = "UARTFR")] + FR = 0x018, + /// Fractional Baud Rate Register + /// + /// responsible for baud rate speed + #[doc(alias = "UARTFBRD")] + FBRD = 0x028, + /// `IrDA` Low-Power Counter Register + #[doc(alias = "UARTILPR")] + ILPR = 0x020, + /// Integer Baud Rate Register + /// + /// Responsible for baud rate speed + #[doc(alias = "UARTIBRD")] + IBRD = 0x024, + /// line control register (data frame format) + #[doc(alias = "UARTLCR_H")] + LCR_H = 0x02C, + /// Toggle UART, transmission or reception + #[doc(alias = "UARTCR")] + CR = 0x030, + /// Interrupt FIFO Level Select Register + #[doc(alias = "UARTIFLS")] + FLS = 0x034, + /// Interrupt Mask Set/Clear Register + #[doc(alias = "UARTIMSC")] + IMSC = 0x038, + /// Raw Interrupt Status Register + #[doc(alias = "UARTRIS")] + RIS = 0x03C, + /// Masked Interrupt Status Register + #[doc(alias = "UARTMIS")] + MIS = 0x040, + /// Interrupt Clear Register + #[doc(alias = "UARTICR")] + ICR = 0x044, + /// DMA control Register + #[doc(alias = "UARTDMACR")] + DMACR = 0x048, + ///// Reserved, offsets `0x04C` to `0x07C`. + //Reserved = 0x04C, +} + +impl core::convert::TryFrom for RegisterOffset { + type Error = u64; + + fn try_from(value: u64) -> Result { + macro_rules! case { + ($($discriminant:ident),*$(,)*) => { + /* check that matching on all macro arguments compiles, which means we are not + * missing any enum value; if the type definition ever changes this will stop + * compiling. + */ + const fn _assert_exhaustive(val: RegisterOffset) { + match val { + $(RegisterOffset::$discriminant => (),)* + } + } + + match value { + $(x if x == Self::$discriminant as u64 => Ok(Self::$discriminant),)* + _ => 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 arbitrary + //! integer bitmaps. [`Data`], [`Control`], [`LineControl`], etc. + //! + //! All PL011 registers are essentially 32-bit wide, but are typed here 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 pushed 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 (break, + /// 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 stored in + /// the receiving + /// holding register (the bottom word of the receive FIFO). + /// + /// The received data byte is read by performing reads from the `UARTDR` + /// register along with the corresponding status information. The status + /// 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 before + /// stopping. + /// + /// # Source + /// ARM DDI 0183G 3.3.1 Data Register, UARTDR + #[bitsize(16)] + #[derive(Clone, Copy, DebugBits, FromBits)] + #[doc(alias = "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 associated + /// 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. However, + /// 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 = 0.into(); + } + } + + impl Default for ReceiveStatusErrorClear { + fn default() -> Self { + 0.into() + } + } + + #[bitsize(16)] + #[derive(Clone, Copy, DebugBits, FromBits)] + /// Flag Register, `UARTFR` + #[doc(alias = "UARTFR")] + pub struct Flags { + /// CTS Clear to send. This bit is the complement of the UART clear 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 data set + /// ready, `nUARTDSR`, modem status input. That is, the bit is 1 when + /// `nUARTDSR` is LOW. + pub data_set_ready: bool, + /// DCD Data carrier detect. This bit is the complement of the UART data + /// carrier detect, `nUARTDCD`, modem status input. That is, the bit 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 state 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 are 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 = 0.into(); + ret.reset(); + ret + } + } + + #[bitsize(16)] + #[derive(Clone, Copy, DebugBits, FromBits)] + /// Line Control Register, `UARTLCR_H` + #[doc(alias = "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 = stick parity is disabled + /// 1 = either: + /// • if the EPS bit is 0 then the parity bit is transmitted and checked + /// as a 1 • 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 = 8 bits + /// b10 = 7 bits + /// b01 = 6 bits + /// b00 = 5 bits. + pub word_length: WordLength, + /// FEN Enable FIFOs: + /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become + /// 1-byte-deep holding registers 1 = 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 uses + /// during transmission and reception: + /// - 0 = odd parity. The UART generates or checks for an odd number of + /// 1s in the data and parity bits. + /// - 1 = 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 checking + /// and generation. See Table 3-11 on page 3-14 for the parity + /// truth table. + pub parity: Parity, + /// 1 PEN Parity enable: + /// + /// - 0 = parity is disabled and no parity bit added to the data frame + /// - 1 = 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 on the + /// `UARTTXD` output, after completing transmission of the + /// current character. For the proper execution of the break command, + /// 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 = 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 = odd parity. The UART generates or checks for an odd number of + /// 1s in the data and parity bits. + Odd = 0, + /// - 1 = even parity. The UART generates or checks for an even number + /// of 1s in the data and parity bits. + Even = 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 = FIFOs are disabled (character mode) that is, the FIFOs become + /// 1-byte-deep holding registers + Character = 0, + /// 1 = transmit and receive FIFO buffers are enabled (FIFO mode). + FIFO = 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 received in a + /// frame as follows: + pub enum WordLength { + /// b11 = 8 bits + _8Bits = 0b11, + /// b10 = 7 bits + _7Bits = 0b10, + /// b01 = 6 bits + _6Bits = 0b01, + /// b00 = 5 bits. + _5Bits = 0b00, + } + + /// Control Register, `UARTCR` + /// + /// The `UARTCR` register is the control register. All the bits are cleared + /// 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 = "UARTCR")] + #[derive(Clone, Copy, DebugBits, FromBits)] + pub struct Control { + /// `UARTEN` UART enable: 0 = UART is disabled. If the UART is disabled + /// in the middle of transmission or reception, it completes the current + /// character before stopping. 1 = the UART is enabled. Data + /// transmission and reception occurs for either UART signals or SIR + /// signals depending on the setting of the SIREN bit. + pub enable_uart: bool, + /// `SIREN` `SIR` enable: 0 = IrDA SIR ENDEC is disabled. `nSIROUT` + /// remains LOW (no light pulse generated), and signal transitions on + /// SIRIN have no effect. 1 = 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 status + /// 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 encoding + /// mode. If this bit is cleared to 0, low-level bits are transmitted 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 pulse + /// width that is 3 times the period of the IrLPBaud16 input signal, + /// 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 bit is + /// set to 1 and the SIRTEST bit in the Test Control register, UARTTCR + /// on page 4-5 is set to 1, then the nSIROUT path is inverted, and fed + /// through to the SIRIN path. The SIRTEST bit in the test register 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 loopback + /// testing is finished. This feature reduces the amount of external + /// 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 to the + /// UARTRXD path. In either SIR mode or UART mode, when this bit is set, + /// the modem outputs are also fed through to the modem inputs. This 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 section + /// of the UART is enabled. Data transmission occurs for either UART + /// 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 section + /// of the UART is enabled. Data reception occurs for either UART + /// signals or SIR signals depending on the setting of the SIREN bit. + /// When the UART is disabled in the middle of reception, it completes + /// the current character before stopping. + pub enable_receive: bool, + /// `DTR` Data transmit ready. This bit is the complement of the UART + /// 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, when 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 to 1, + /// RTS hardware flow control is enabled. Data is only requested when + /// 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 to 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 = 0.into(); + self.set_enable_receive(true); + self.set_enable_transmit(true); + } + } + + impl Default for Control { + fn default() -> Self { + let mut ret: Self = 0.into(); + ret.reset(); + ret + } + } + + /// Interrupt status bits in UARTRIS, UARTMIS, UARTIMSC + pub const INT_OE: u32 = 1 << 10; + pub const INT_BE: u32 = 1 << 9; + pub const INT_PE: u32 = 1 << 8; + pub const INT_FE: u32 = 1 << 7; + pub const INT_RT: u32 = 1 << 6; + pub const INT_TX: u32 = 1 << 5; + pub const INT_RX: u32 = 1 << 4; + pub const INT_DSR: u32 = 1 << 3; + pub const INT_DCD: u32 = 1 << 2; + pub const INT_CTS: u32 = 1 << 1; + pub const INT_RI: u32 = 1 << 0; + pub const INT_E: u32 = INT_OE | INT_BE | INT_PE | INT_FE; + pub const INT_MS: u32 = INT_RI | INT_DSR | INT_DCD | INT_CTS; + + #[repr(u32)] + pub enum Interrupt { + 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, + } + + impl Interrupt { + pub const E: u32 = INT_OE | INT_BE | INT_PE | INT_FE; + pub const MS: u32 = 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 0000000000000000000000000000000000000000..a2552ba58ecf2b33a07f4cced5e7c5e3c3cdfcff --- /dev/null +++ b/rust/hw/char/pl011/src/memory_ops.rs @@ -0,0 +1,57 @@ +// 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 = 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 = NonNull::new_unchecked(opaque.cast::()); + let val = state.as_mut().read(addr, size); + match val { + std::ops::ControlFlow::Break(val) => val, + std::ops::ControlFlow::Continue(val) => { + // SAFETY: self.char_backend is a valid CharBackend instance after it's been + // initialized in realize(). + let cb_ptr = 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, +) { + assert!(!opaque.is_null()); + let mut state = 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 0000000000000000000000000000000000000000..860196645e719624d2e2e6bc301b62b81ab2e19b --- /dev/null +++ b/rust/hw/meson.build @@ -0,0 +1 @@ +subdir('char') diff --git a/rust/meson.build b/rust/meson.build index 7a32b1b195083571931ad589965c10ddaf6383b1..def77389cddc52f5d4503840e9bdfb1207586fa2 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 65af8063e4bddc89ea4bdf05716ebc9ed108e7fb..8b06c162307ec89739775cf6b8c15f9734367dd3 100755 --- a/scripts/archive-source.sh +++ b/scripts/archive-source.sh @@ -26,7 +26,10 @@ sub_file="${sub_tdir}/submodule.tar" # independent of what the developer currently has initialized # in their checkout, because the build environment is completely # different to the host OS. -subprojects="keycodemapdb libvfio-user berkeley-softfloat-3 berkeley-testfloat-3" +subprojects="keycodemapdb libvfio-user berkeley-softfloat-3 + berkeley-testfloat-3 arbitrary-int-1.2.7 bilge-0.2.0 bilge-impl-0.2.0 + either-1.12.0 itertools-0.11.0 proc-macro2-1.0.84 proc-macro-error-1.0.4 + proc-macro-error-attr-1.0.4 quote-1.0.36 syn-2.0.66 unicode-ident-1.0.12" sub_deinit="" function cleanup() { diff --git a/scripts/make-release b/scripts/make-release index 6e0433de24dc8a37cefae6d828a2958309bbf1c1..841404274b066cc26c90656150ab01fa46cbd219 100755 --- a/scripts/make-release +++ b/scripts/make-release @@ -17,7 +17,10 @@ if [ $# -ne 2 ]; then fi # Only include wraps that are invoked with subproject() -SUBPROJECTS="libvfio-user keycodemapdb berkeley-softfloat-3 berkeley-testfloat-3" +SUBPROJECTS="libvfio-user keycodemapdb berkeley-softfloat-3 berkeley-testfloat-3 + arbitrary-int-1.2.7 bilge-0.2.0 bilge-impl-0.2.0 either-1.12.0 itertools-0.11.0 + proc-macro2-1.0.84 proc-macro-error-1.0.4 proc-macro-error-attr-1.0.4 + quote-1.0.36 syn-2.0.66 unicode-ident-1.0.12" src="$1" version="$2" diff --git a/scripts/rust/rust_root_crate.sh b/scripts/rust/rust_root_crate.sh new file mode 100755 index 0000000000000000000000000000000000000000..975bddf7f1a4c6ca7770f800bdc894cdff1f3ab1 --- /dev/null +++ b/scripts/rust/rust_root_crate.sh @@ -0,0 +1,13 @@ +#!/bin/sh + +set -eu + +cat <