From nobody Thu Apr 9 18:48:03 2026 Received: from mail-wr1-f74.google.com (mail-wr1-f74.google.com [209.85.221.74]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 1CD853C0639 for ; Wed, 8 Apr 2026 12:20:59 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.221.74 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1775650860; cv=none; b=Rz81mFTWpY98SdSF9uFc4vnHbNzlC8b6LfqM5J2AAI6QesWR8xHQ70tSPvtRM/3ZowUvKjIxdIYCkzyavhx3+4jqO5ZCwXFNwRv4Rr7XnRjkFAJl+oebEWXMnjrJuMt+VigF8J2IbiHPCbZYsHWjQyehFb7EUO+D9hh6rtNUE3o= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1775650860; c=relaxed/simple; bh=wZSfHnb0WFA82Shw+hfej3jBicvTJMZBLptOwNaRHVM=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=EEXe7u8OLTBq+oyLXK/81J3gCzuE5jEOSpY+WGbrrDyByu+jraO9yJjcrk3YeWMyhtMhKM+Kr0N+6gF4pxRzNDNPqtdt6Lz1g4ODcOaKR9oYMVL1r7+jf4AxCG02vmtXVFGgi2fnXq4ja8LX4Q0a26oj96eZhUjU4jjV7sHYiYE= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=demiRG6n; arc=none smtp.client-ip=209.85.221.74 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="demiRG6n" Received: by mail-wr1-f74.google.com with SMTP id ffacd0b85a97d-43d1fec59c9so550327f8f.0 for ; Wed, 08 Apr 2026 05:20:58 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20251104; t=1775650857; x=1776255657; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=XkmVhqTIndPqmzNXhrJEUquBBrmigEyy/3MslXmYI/0=; b=demiRG6nEI1CaIBR0j7Cbn9H+teeBr1q91isDFZT+8R5vN1ydo4TUTAWHFFjr1VFRf uM0Ql495BWd/iOwo0vvL3ksiDJ4qc/yUZlOYf6oTseKtCrMIB/P9abotxnBc5ZReaeTv P4usKjeNLQXtMXalBrz58hmKP8Zl3un0me84a4RreWZSDS66H21s9Zih9CeWXQUrVNn1 V8eUqLM67G8CUEhwiO8l//JpJXTo7fTWodOi8JT9pqrF1vigWjqMkFIcNx9MOqQWToJu eyaqnIFKgZvXd6G/Ex177OL9uwKxR5pfv8fhLnHhEMEZZWaD8IqpeZTOt8P6vGlRPjHx JDjQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20251104; t=1775650857; x=1776255657; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=XkmVhqTIndPqmzNXhrJEUquBBrmigEyy/3MslXmYI/0=; b=OeeyV8ZVH8hnRgiEfduVhWaYxTO4cq8EVXHX8+Uyfnv9QpS4dWc8ozCOB77Igdzqid ut4N+hq3c6RrdsTRaj/XMha2VXhznFtaSzfaLRgWeXkLqzYejms/mKPM6I7LEkDlcZFJ 9MoeQNLs6jr7mnlKn+CtYLhcOPfcSCm6m98fPsX+DpsALKZrKfpOpYN+oFeOtsFbZfHS G5qam/4rWfFqPdrwtMSz/6D8ZIXw2PcsbZOqcVBaBFWocC/CIMjF8vjaIpFRUWoIoUwH Acw2hpFCKP5gqQAiD3uDbUfBk2Y1ZZjyWutjP++txa2E+70SzudUSTHLxmolVLrb+OP9 RfVg== X-Gm-Message-State: AOJu0Yw0DJC+SZKm+wCDcoX0etGRnGbzdCkLdMaxWyGywV7jkxQchklV 1flWqi6woZnWeo42wB3RG8PKeeEKwEcO1ahCqFAK3Tu+6hVh5PBf8Qif2KZS5uAW2qS9lhidW1f jIcTW0QrhzeQTOmURsg== X-Received: from wrpd7.prod.google.com ([2002:adf:f2c7:0:b0:43b:465d:97b6]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:6000:401e:b0:43c:cda2:4f2a with SMTP id ffacd0b85a97d-43d28f8df8dmr30840975f8f.4.1775650857410; Wed, 08 Apr 2026 05:20:57 -0700 (PDT) Date: Wed, 08 Apr 2026 12:20:45 +0000 In-Reply-To: <20260408-binder-netlink-v2-0-c0d327d15435@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20260408-binder-netlink-v2-0-c0d327d15435@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=7631; i=aliceryhl@google.com; h=from:subject:message-id; bh=wZSfHnb0WFA82Shw+hfej3jBicvTJMZBLptOwNaRHVM=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBp1kgkY6hKLbppEH2Jt3n4927kVD63A9S+doFBU 26tKNv0Am+JAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCadZIJAAKCRAEWL7uWMY5 Rq3aD/9e2btAznxLvztedA8gQSPhb2OdjrzgL0ehqRSj5nIIP2ygd2ctrV5KvSOhvQVjWC9VSn2 GeawxnqPJFOylVBpsmMBefGtqvn6dQpP5QqT6NFtFW9ebRIrTg5goipwLZ5gthWHguBjWgRE1oO W/R+0q4KY9wM4DNjfm1TmFLNHCGtPqJeWqrYz5IJhEuYav4mQfDCvXAKB/Ft5zZaL3rTAzAhI7I oBv+07xhiza57bCUNVlKu5RDpC3lD0QVsaCWxpO7XjO/6aRBkAtEleFDN20lHxKCjblilIpzrGi BuXglnUIL2JdZ1ajuP0eNVSVDjdhd3QuXjWgAMcCjhCQ7ngdpejZJ1lBBz9WI3lObMZLn47cvAy xHnC1RRPMFW8oBvz6HtGgGALi47FxChBnIJLybhUzoHKM4xJf7DDh+YVyg4D1w5XkUMSBo6H7BJ k7TXWofSs1ZTqcwc1pr6tqZZiyBQ4FQjceQxKeR9frSkADGyic7huXg35LuJX6BvVD/IrP97PQ7 TS5HwhrctdRwKNb5FYpxMS3Nr1mngCzsm+Mc0Gepq70XykcHePr4PshYdaZRsC9qx8O9Mr7XmXh zry+xv/jUb69MpoORGu5SS8pSU3myK9RP4Wbju0mpaFN2Hh0tt54RZJ1kIapNXWHI+cWu6QhxtJ BoKwBN6CbLJYfTA== X-Mailer: b4 0.14.3 Message-ID: <20260408-binder-netlink-v2-2-c0d327d15435@google.com> Subject: [PATCH v2 2/4] ynl_gen: generate Rust files from yaml files From: Alice Ryhl To: Miguel Ojeda , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Trevor Gross , Danilo Krummrich , Donald Hunter , Jakub Kicinski , "David S. Miller" , Eric Dumazet , Paolo Abeni , Simon Horman , Greg Kroah-Hartman , "=?utf-8?q?Arve_Hj=C3=B8nnev=C3=A5g?=" , Todd Kjos , Christian Brauner , Carlos Llamas Cc: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, netdev@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable To generate netlink frames from Rust code easily, generate Rust libraries with methods for generating different netlink messages as appropriate. The new 'rust' type corresponds to a Rust version of the C target 'kernel'. There is no Rust version of the 'uapi' target since Rust code exports its uapi via C headers - choice of language is opaque to userspace. This logic is kept in the existing ynl_gen_c.py file to reuse CodeWriter and other shared pieces of logic in the existing python file. This has the disadvantage that the gen_c part of the name is now wrong, as it also generates Rust. One possible solution to this could be to rename the file. Signed-off-by: Alice Ryhl --- tools/net/ynl/pyynl/ynl_gen_c.py | 132 +++++++++++++++++++++++++++++++++++= +++- tools/net/ynl/ynl-regen.sh | 2 +- 2 files changed, 132 insertions(+), 2 deletions(-) diff --git a/tools/net/ynl/pyynl/ynl_gen_c.py b/tools/net/ynl/pyynl/ynl_gen= _c.py index 0e1e486c1185..702d34727b6e 100755 --- a/tools/net/ynl/pyynl/ynl_gen_c.py +++ b/tools/net/ynl/pyynl/ynl_gen_c.py @@ -19,6 +19,7 @@ import pathlib import os import re import shutil +import subprocess import sys import tempfile import yaml as pyyaml @@ -1744,6 +1745,19 @@ class CodeWriter: else: self.p('}' + line) =20 + def array_start(self, line=3D''): + if line: + line =3D line + ' ' + self.p(line + '[') + self._ind +=3D 1 + + def array_end(self, line=3D''): + if line and line[0] not in {';', ','}: + line =3D ' ' + line + self._ind -=3D 1 + self._nl =3D False + self.p(']' + line) + def write_doc_line(self, doc, indent=3DTrue): words =3D doc.split() line =3D ' *' @@ -3415,10 +3429,119 @@ def find_kernel_root(full_path): return full_path, sub_path[:-1] =20 =20 +def render_rust(family, cw): + cw.p('#![allow(unreachable_pub, clippy::wrong_self_convention)]') + cw.p('use kernel::netlink::{Family, MulticastGroup};') + cw.p('use kernel::prelude::*;') + cw.nl() + + family_upper =3D c_upper(family.ident_name) + family_name =3D f'{family_upper}_NL_FAMILY' + mcgrps_name =3D f'{family_name}_MCGRPS' + + cw.p(f'pub static {family_name}: Family =3D Family::const_new(') + cw._ind +=3D 1 + cw.p('&crate::THIS_MODULE,') + cw.p(f'kernel::uapi::{family.fam_key},') + cw.p(f'kernel::uapi::{family.ver_key},') + cw.p(f'&{mcgrps_name},') + cw._ind -=3D 1 + cw.p(');') + cw.nl() + + if family.mcgrps['list']: + cw.array_start(f'static {mcgrps_name}: [MulticastGroup; {len(famil= y.mcgrps["list"])}] =3D ') + for grp in family.mcgrps['list']: + cw.p(f'MulticastGroup::const_new(c"{grp["name"]}"),') + cw.array_end(';') + cw.nl() + + for idx, (op_name, op) in enumerate(item for item in family.msgs.items= () if 'event' in item[1]): + struct_name =3D op_name.capitalize() + + if 'doc' in op: + doc_lines =3D op['doc'].strip().split('\n') + for line in doc_lines: + cw.p(f'/// {line.strip()}') + + cw.block_start(f'pub struct {struct_name}') + cw.p('skb: kernel::netlink::GenlMsg,') + cw.block_end() + cw.nl() + + cw.block_start(f'impl {struct_name}') + cw.p('/// Create a new multicast message.') + cw.p('pub fn new(') + cw._ind +=3D 1 + cw.p('size: usize,') + cw.p('portid: u32,') + cw.p('seq: u32,') + cw.p('flags: kernel::alloc::Flags,') + cw._ind -=3D 1 + cw.block_start(') -> Result') + cw.p(f'const {op.enum_name}: u8 =3D kernel::uapi::{op.enum_name} a= s u8;') + cw.p('let skb =3D kernel::netlink::NetlinkSkBuff::new(size, flags)= ?;') + cw.p(f'let skb =3D skb.genlmsg_put(portid, seq, &{family_name}, {o= p.enum_name})?;') + cw.p('Ok(Self { skb })') + cw.block_end() + cw.nl() + + cw.p('/// Broadcast this message.') + cw.block_start('pub fn multicast(self, portid: u32, flags: kernel:= :alloc::Flags) -> Result') + cw.p(f'self.skb.multicast(&{family_name}, portid, {idx}, flags)') + cw.block_end() + cw.nl() + + cw.p('/// Check if this message type has listeners.') + cw.block_start('pub fn has_listeners() -> bool') + cw.p(f'{family_name}.has_listeners({idx})') + cw.block_end() + + attr_set_name =3D op['attribute-set'] + attr_set =3D family.attr_sets[attr_set_name] + event_attrs =3D op['event']['attributes'] + + for attr_name in event_attrs: + attr =3D attr_set[attr_name] + method_name =3D attr_name.replace('-', '_') + + if attr.type =3D=3D 'u32': + put_fn =3D 'put_u32' + arg_str =3D ', val' + method_args =3D '(&mut self, val: u32)' + elif attr.type =3D=3D 'string': + put_fn =3D 'put_string' + arg_str =3D ', val' + method_args =3D '(&mut self, val: &CStr)' + elif attr.type =3D=3D 'flag': + put_fn =3D 'put_flag' + arg_str =3D '' + method_args =3D '(&mut self)' + else: + put_fn =3D 'put_u32' + arg_str =3D ', val' + method_args =3D f'(&mut self, val: {attr.type})' + + cw.nl() + if 'doc' in attr.yaml: + doc_lines =3D attr.yaml['doc'].strip().split('\n') + for line in doc_lines: + cw.p(f'/// {line.strip()}') + + cw.block_start(f'pub fn {method_name}{method_args} -> Result') + cw.p(f'const {attr.enum_name}: c_int =3D kernel::uapi::{attr.e= num_name} as c_int;') + cw.p(f'self.skb.{put_fn}({attr.enum_name}{arg_str})') + cw.block_end() + + cw.block_end() + cw.nl() + cw.p(' ') + + def main(): parser =3D argparse.ArgumentParser(description=3D'Netlink simple parsi= ng generator') parser.add_argument('--mode', dest=3D'mode', type=3Dstr, required=3DTr= ue, - choices=3D('user', 'kernel', 'uapi')) + choices=3D('user', 'kernel', 'uapi', 'rust')) parser.add_argument('--spec', dest=3D'spec', type=3Dstr, required=3DTr= ue) parser.add_argument('--header', dest=3D'header', action=3D'store_true'= , default=3DNone) parser.add_argument('--source', dest=3D'header', action=3D'store_false= ') @@ -3471,6 +3594,13 @@ def main(): render_uapi(parsed, cw) return =20 + if args.mode =3D=3D 'rust': + render_rust(parsed, cw) + cw.close_out_file() + if args.out_file: + subprocess.run(['rustfmt', '--edition', '2021', args.out_file]) + return + hdr_prot =3D f"_LINUX_{parsed.c_name.upper()}_GEN_H" if args.header: cw.p('#ifndef ' + hdr_prot) diff --git a/tools/net/ynl/ynl-regen.sh b/tools/net/ynl/ynl-regen.sh index d9809276db98..4f5ceb4fe147 100755 --- a/tools/net/ynl/ynl-regen.sh +++ b/tools/net/ynl/ynl-regen.sh @@ -17,7 +17,7 @@ done KDIR=3D$(dirname $(dirname $(dirname $(dirname $(realpath $0))))) pushd ${search:-$KDIR} >>/dev/null =20 -files=3D$(git grep --files-with-matches '^/\* YNL-GEN \(kernel\|uapi\|user= \)') +files=3D$(git grep --files-with-matches '^/\* YNL-GEN \(kernel\|uapi\|user= \|rust\)') for f in $files; do # params: 0 1 2 3 # $YAML YNL-GEN kernel $mode --=20 2.53.0.1213.gd9a14994de-goog