From nobody Fri Dec 19 14:37:46 2025 Received: from mail-wm1-f73.google.com (mail-wm1-f73.google.com [209.85.128.73]) (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 C31A328937B for ; Mon, 19 May 2025 16:17:33 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.73 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747671455; cv=none; b=eo3u7BdIXFteJKWum+lr9UN2GSzrhcOm7CsGjQsy1FYhjetQGawcW7ZjKgBJuOrm32vE+pNsfUkO1kpaau1UVix71jzzWAseSACE31y4Vs4rVCIbAE7BsQI3/xEAdjuG8Bam7nMiL5PQ0cx7cm7PEswG3DdV8vV4ODEarEAoHoo= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747671455; c=relaxed/simple; bh=AGiPPLwtKkHyIil5nX5UwvjN3gwIsKNADdoIbt4a+GM=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=G+OE6T80/I8+CecF+sQW7uKlVoMk9ZFYx9JRfLCVdWncxI1+m0SQg8aI+yDctfpAq1Qhnw71tGL3uNLXxUOAeby078OB5QFC62jGp/VXwq53ANvdmVP9dJzL4636zjk2lQ4EQ5+8ED6rKqTZ+A5aRfDcZAR/9hR1Hm+KQ5yWA/c= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--bqe.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=SJC0inxF; arc=none smtp.client-ip=209.85.128.73 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--bqe.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="SJC0inxF" Received: by mail-wm1-f73.google.com with SMTP id 5b1f17b1804b1-43d007b2c79so36730815e9.2 for ; Mon, 19 May 2025 09:17:33 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1747671452; x=1748276252; 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=TV/U6hOZ4/6jhNCFGPyepIdJ6+QNwHJqLnSNzUB1aUM=; b=SJC0inxFkNMufCHqNwkn5SSIoYbSW6QIB8NzO6Zf75cULBVayaoY10U1DjP4XyxCf4 zp6eRl/ySz3jOJ7XFxM0RraVqlXOVXnxx1htXXiYbgl28f+4Syhg1RRD2URxE1yD4dkz /ez+TyOP51z6fG7nxBqrLNDrXBVR6pwr9eVQ+UVzyZL5rxZabFgWqVsE5onzu+4Wq8y0 RHEZHi02l3JQjZXKzb5DEtffew2bRsDiGbZXa2oE0mpDfT2y+6NU+2EM7dB/7i9tgzun EP98TUU2Hh9ZqHqs0PGpTLunmlnUMDGoLPiiIutrqfLO5rhs7zbQpuK+WL3hrDfqv0Bx b8vg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1747671452; x=1748276252; 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=TV/U6hOZ4/6jhNCFGPyepIdJ6+QNwHJqLnSNzUB1aUM=; b=wLTrzl0G6q1D9WPjHNJlGvE/H/XOEWd1hTO48ta6eMMGVjYpXNynrZkqYDRX5zpvQH /6gu40cdQCRF27T/qTGNgpNIzELgKQxvBIpkQS5iFytreKDSZ5e4UmqeBx3nBVxt2DLw I7m9wrYyfiDTrOkZtrRPfUBaND2UJjYnBSszcdHNU3LARO64uxSAfkLewLFxxofN4fe4 /ePC1SoSgJ/Fo6CYFZTsmydh5GgGtEdBnZ2gQ73DdBpHViS2cOyK93t2RIMUHhAcuENg gPC/EvJvM21FZdO8DCKEMWoDOpdOPzczM9zUms58GeNa/Gj1gIADUTDfWrvtnGJSnmw/ rjzw== X-Forwarded-Encrypted: i=1; AJvYcCXxr/Fd3oMI83S/lbISEOQjsfNtaqUdmkLU6m+euudprFAZks7EKseQbup9fPSVvO7/9oyBpcn8W9gxw+Y=@vger.kernel.org X-Gm-Message-State: AOJu0YyfSNlvrk7a3zeNSYxJd9qOp2XDABe0mQDS+FWn05VAnspw3Mg3 PGAk0w/30u4nliwon7y0FoNKXcLoeTBphRTzTUozIpRdWlzvzN1x404reGuvhWQlFVx+gw== X-Google-Smtp-Source: AGHT+IHcEWGvOdJO9xFxXMdY5FMhyx8Fhjz4I9MlF5gLqk0an+OT/w+E/WP9CLdn10WpcEfgMtZ1wgM= X-Received: from wmbes7.prod.google.com ([2002:a05:600c:8107:b0:43d:9035:df36]) (user=bqe job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:45cf:b0:43c:f470:7605 with SMTP id 5b1f17b1804b1-442fd610128mr130095715e9.12.1747671452177; Mon, 19 May 2025 09:17:32 -0700 (PDT) Date: Mon, 19 May 2025 16:17:01 +0000 In-Reply-To: <20250519161712.2609395-1-bqe@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250519161712.2609395-1-bqe@google.com> X-Mailer: git-send-email 2.49.0.1101.gccaa498523-goog Message-ID: <20250519161712.2609395-2-bqe@google.com> Subject: [PATCH v8 1/5] rust: add bindings for bitmap.h From: Burak Emir To: Yury Norov , Kees Cook Cc: Burak Emir , Rasmus Villemoes , Viresh Kumar , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , "=?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?=" , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , "Gustavo A . R . Silva" , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-hardening@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Makes the bitmap_copy_and_extend inline function available to Rust. Adds F: to existing MAINTAINERS section BITMAP API BINDINGS [RUST]. Suggested-by: Alice Ryhl Suggested-by: Yury Norov Signed-off-by: Burak Emir Acked-by: Yury Norov [NVIDIA] --- MAINTAINERS | 1 + rust/bindings/bindings_helper.h | 1 + rust/helpers/bitmap.c | 9 +++++++++ rust/helpers/helpers.c | 1 + 4 files changed, 12 insertions(+) create mode 100644 rust/helpers/bitmap.c diff --git a/MAINTAINERS b/MAINTAINERS index d48dd6726fe6..86cae0ca5287 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -4124,6 +4124,7 @@ F: tools/lib/find_bit.c BITMAP API BINDINGS [RUST] M: Yury Norov S: Maintained +F: rust/helpers/bitmap.c F: rust/helpers/cpumask.c =20 BITOPS API diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helpe= r.h index ab37e1d35c70..b6bf3b039c1b 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -7,6 +7,7 @@ */ =20 #include +#include #include #include #include diff --git a/rust/helpers/bitmap.c b/rust/helpers/bitmap.c new file mode 100644 index 000000000000..a50e2f082e47 --- /dev/null +++ b/rust/helpers/bitmap.c @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include + +void rust_helper_bitmap_copy_and_extend(unsigned long *to, const unsigned = long *from, + unsigned int count, unsigned int size) +{ + bitmap_copy_and_extend(to, from, count, size); +} diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index 1e7c84df7252..92721d165e35 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -7,6 +7,7 @@ * Sorted alphabetically. */ =20 +#include "bitmap.c" #include "blk.c" #include "bug.c" #include "build_assert.c" --=20 2.49.0.1101.gccaa498523-goog From nobody Fri Dec 19 14:37:46 2025 Received: from mail-wm1-f73.google.com (mail-wm1-f73.google.com [209.85.128.73]) (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 8B1DB289820 for ; Mon, 19 May 2025 16:17:35 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.73 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747671458; cv=none; b=Rpl5InhOVlx1c5DwuaMggmBSly7D7+duSR2LWj4+ABr+FJi8UtGOQtO0+/ewkvabCkxOxKTPqSeJ42E6oGcdz7WUd8lRuLYRnPmur0SF+G59WaaAGhWaYklPuSoOkf9j3xv1u8Ke+IlxuW+iV2lXgRr+hg9tECY6QxfXEY55MAI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747671458; c=relaxed/simple; bh=9OXo2mm4zTvrDpEWPXsdwUcmAvEmqVu3gp27qTaR1DA=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=Ly6puZB1MDpIUKVNuGj5ziz8leS7778E/jl+d+UcK/eODpvs5+DbA/VX8vNfC/mkWkO/4PLnJLFZEIaFEFIKjN62ScGehIl6xwjjMSxuOwvsgnr0RMfSofKLDSULe3imUNHPij+QdiU9kYnJJRW+0mp2iTohlJxsQPZoFe41atE= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--bqe.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=vdYjXcTD; arc=none smtp.client-ip=209.85.128.73 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--bqe.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="vdYjXcTD" Received: by mail-wm1-f73.google.com with SMTP id 5b1f17b1804b1-442ffaa7dbeso4019665e9.3 for ; Mon, 19 May 2025 09:17:35 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1747671454; x=1748276254; 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=Xi3xovkHr/TA/Q9MkIz3HdK8OZ1bO8szRf5CN1p75gk=; b=vdYjXcTDDISeVsfBvQTVFrw8dCJH31nmCkVZOhA02GrxuIYxGZJ0jxbPIoEIxxmyey VGw7lyGicVNsi9gTU69xcew4pQKtyQy/C8piB5f9x1z+d0Xw9dbIKpqlmqFkk7qXfpcb IBEZCfQolmlYcoAdxDQrIW/rqrutw2ulEs1hck2iiCL/3CbvnoOZ7osCzETzTE8zw4zG O3NMyVI9TIu83npYJvYbG/8wECMVk9pHrCD/Nbjgqa+1hyK4whGjfVBSVELXfcC51pKw QM1mWKt0JXI4Peo1adCVRmDLyDwLmO+Tn4L2tyUvfJ5L8U5lYcj2xUlzvcnHhYWaf82M OsxA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1747671454; x=1748276254; 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=Xi3xovkHr/TA/Q9MkIz3HdK8OZ1bO8szRf5CN1p75gk=; b=UlqjezIxaU4jO4Dk3oiUA+0v5zBDoVsR+Qp8qMRzaQt3ThMJYCUep6OVkF9LN4ren3 PiaLu7pnqPEMk4ZOEcEf04g/iiBA08YRD8+HXtv8hpFDR9B6VcYHMyGMZoEDjkXjeo+c ibfvwdm0TNGKDOeeyZAMkRX9DdUuzYw1h2H9tUI9jPygEZTCb7pYsxNhDZO49d1Ib6ys Ol0Xpi5EtiD2LdxqAXb8FrqQd9+EmgzX3wLMXD8DweyNY5jTMCfmCGENpqYgZrmrql3q p3O+HTdcMo/hyvEn68yZASFWh6aCGAV9xmEx8/XiarxDtBZ1QhHmCtG2D+dNs3S+e6DL 5QPw== X-Forwarded-Encrypted: i=1; AJvYcCXJ3iW3nIkSH2mStEoadXt+E1xmqIGYm6bHzy/snAr6coF3DP7Sp7V2+/qEDP0RAv0k8aYwwklVA4eMsmw=@vger.kernel.org X-Gm-Message-State: AOJu0YxUtJvAjJkDIM+rwwKqD7wTC3yar66rFnUkF4QWRmbe58DueMfp wstQ7ha7m2fnl+XRNpJHkyAnD3k6rLBtrwaps+Iegb9RXsuh6zaMGaXC1MavPQlTWMQQ4A== X-Google-Smtp-Source: AGHT+IEDywwP0TbHb8rwq4xsvkZ8rXPn0wk9YIEpc/zYAcY8JgnR07Gpr6ugUtORaX2FrzcOWh/6rQc= X-Received: from wmbay27.prod.google.com ([2002:a05:600c:1e1b:b0:442:dd0d:556b]) (user=bqe job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:4688:b0:43d:2230:300f with SMTP id 5b1f17b1804b1-442fd5a160amr147107165e9.0.1747671453952; Mon, 19 May 2025 09:17:33 -0700 (PDT) Date: Mon, 19 May 2025 16:17:02 +0000 In-Reply-To: <20250519161712.2609395-1-bqe@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250519161712.2609395-1-bqe@google.com> X-Mailer: git-send-email 2.49.0.1101.gccaa498523-goog Message-ID: <20250519161712.2609395-3-bqe@google.com> Subject: [PATCH v8 2/5] rust: add bindings for bitops.h From: Burak Emir To: Yury Norov , Kees Cook Cc: Burak Emir , Rasmus Villemoes , Viresh Kumar , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , "=?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?=" , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , "Gustavo A . R . Silva" , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-hardening@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Makes atomic set_bit and clear_bit inline functions as well as the non-atomic variants __set_bit and __clear_bit available to Rust. Adds a new MAINTAINERS section BITOPS API BINDINGS [RUST]. Suggested-by: Alice Ryhl Suggested-by: Yury Norov Signed-off-by: Burak Emir Acked-by: Yury Norov [NVIDIA] --- MAINTAINERS | 5 +++++ rust/helpers/bitops.c | 23 +++++++++++++++++++++++ rust/helpers/helpers.c | 1 + 3 files changed, 29 insertions(+) create mode 100644 rust/helpers/bitops.c diff --git a/MAINTAINERS b/MAINTAINERS index 86cae0ca5287..04d6727e944c 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -4141,6 +4141,11 @@ F: include/linux/bitops.h F: lib/test_bitops.c F: tools/*/bitops* =20 +BITOPS API BINDINGS [RUST] +M: Yury Norov +S: Maintained +F: rust/helpers/bitops.c + BLINKM RGB LED DRIVER M: Jan-Simon Moeller S: Maintained diff --git a/rust/helpers/bitops.c b/rust/helpers/bitops.c new file mode 100644 index 000000000000..1fe9e3b23a39 --- /dev/null +++ b/rust/helpers/bitops.c @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include + +void rust_helper___set_bit(unsigned int nr, unsigned long *addr) +{ + __set_bit(nr, addr); +} + +void rust_helper___clear_bit(unsigned int nr, unsigned long *addr) +{ + __clear_bit(nr, addr); +} + +void rust_helper_set_bit(unsigned int nr, volatile unsigned long *addr) +{ + set_bit(nr, addr); +} + +void rust_helper_clear_bit(unsigned int nr, volatile unsigned long *addr) +{ + clear_bit(nr, addr); +} diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index 92721d165e35..4de8ac390241 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -8,6 +8,7 @@ */ =20 #include "bitmap.c" +#include "bitops.c" #include "blk.c" #include "bug.c" #include "build_assert.c" --=20 2.49.0.1101.gccaa498523-goog From nobody Fri Dec 19 14:37:46 2025 Received: from mail-wm1-f73.google.com (mail-wm1-f73.google.com [209.85.128.73]) (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 468A9289E15 for ; Mon, 19 May 2025 16:17:37 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.73 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747671461; cv=none; b=W6Kd8eATqY0tBbQmcd1hmGMmpNHgKYaJLmdd1LuO41h44d6oIFa1IKlbb7ZOkAgwE1A0GvGZ7GBoV0ce7M5Ax9bJNWAh+Cq1VJ5mibsPDZy/Pn8hQSoG9U3meCFHamObXuxHUiK6W0mjjxX19QsL1fc323rRI8KmLB88DRvqqZM= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747671461; c=relaxed/simple; bh=QT8ZMTctfr1J+XzRoTakz5AJSOlWu121wMMwbdqDl8M=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=HZkTcE6b4GMEMurPaBDfQdg00Ljp2fQWItBJmBRhNVeVtncDRBO1/eJkanK+PE1gytybvszM404hNOlQVJDP//orBx/NYJBn0yY7mdoQAQCCnBsMhiaxAO/kFVCEXbn3EGA/KaC/z3g7cI9zO2jUx6jEc2BX4LWxyYgMSIAX4o8= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--bqe.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=eLz34hD+; arc=none smtp.client-ip=209.85.128.73 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--bqe.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="eLz34hD+" Received: by mail-wm1-f73.google.com with SMTP id 5b1f17b1804b1-442f4a3851fso41590825e9.1 for ; Mon, 19 May 2025 09:17:36 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1747671455; x=1748276255; 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=yfz9nEc/hxUJIcLaKW3k+sD8V+u1a0TDbRDrs80xXFA=; b=eLz34hD+y+7ZUOZnkno6THEosVRbXIZOIYWZsttB8p33rw4NNDuqY6MXKEZJw9iJiI zgKbUyCf0nygotQLGyzKCwzy6TuxZ3GyXniV3wVA9kMkPMcq2g/Pb9IU6EfBOCtt8xOJ b5vbZ+GY7Nm8NUii2Ir0Ix8p/dbo9L1lje4WwmRoxrMuukOY1YSkC6wBOMK1be7SI7cA ZwmSeM3zuasU8pChGZbDM0W4t3F+HEyedrEoH1NMPd53IvF665ucE7JZRNY3stmh7uZX 1fLCgXBnkx2lH8RlQN6dVbsJf7pQtiVQFWTm/V3niBeKmZtfNm/o+iCdPuqzqIWJnYPQ 2oeA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1747671455; x=1748276255; 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=yfz9nEc/hxUJIcLaKW3k+sD8V+u1a0TDbRDrs80xXFA=; b=H51yhTNX8uc4QbXVAGU4sHlqiLXp/92IxIVi9j9E8g3Tya41rQJZL/AtwvrEzMW64y GQ7UvmeMtqSmtdbAnDSUxb2tt0WNXQ3/AwAIc8rcC4KTc5jSXsXs6VwpBDxlX952ktVv sAvCwLwr9qqJFFJHgpGRmHNu5Rq1HI46mumAfSDumzGQIlkr8elYmZgghg3b8fKNRhms Df9TsRgg/sP2cyTN2/Xu3X4jjgjUoP87BjShHGsnUTpJQSOjfaA19jLAAzmDZX0zmnug tfz5Vl+37Uv+jKl98np1aVOwK2QMJD9Qak56EC72J3x09DF9jKLxTs1Zj4AZHzwnrMdo mtAQ== X-Forwarded-Encrypted: i=1; AJvYcCX0C76F3i77PvLTyTJmCFKbrgGEib+XyBYFTcZI/aifTW1rz/y0Te+++Qh+Ml5W+UZbZa159JOwwISUUoQ=@vger.kernel.org X-Gm-Message-State: AOJu0YyE9t//9H+uILpwSeBSoJqBsR7PQo7g6yCDfxTGcIHSZs3tgxU+ Arc1q/MN2UIj580/Wnqs60e/RKlwP0HvLskpLSEWbub/p6L87lwlbOWlFjxVcGwpncF8EA== X-Google-Smtp-Source: AGHT+IGAeGn+PW2xEgj73EmbMuX5za13/vJqJ3FsRLehDvShqwrYK2lypzy1YOfhlXF1UW5TV8gf0EQ= X-Received: from wmbgw24.prod.google.com ([2002:a05:600c:8518:b0:440:68cb:bd4]) (user=bqe job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:c1b:b0:43c:e481:3353 with SMTP id 5b1f17b1804b1-442feffbb8dmr143562675e9.17.1747671455773; Mon, 19 May 2025 09:17:35 -0700 (PDT) Date: Mon, 19 May 2025 16:17:03 +0000 In-Reply-To: <20250519161712.2609395-1-bqe@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250519161712.2609395-1-bqe@google.com> X-Mailer: git-send-email 2.49.0.1101.gccaa498523-goog Message-ID: <20250519161712.2609395-4-bqe@google.com> Subject: [PATCH v8 3/5] rust: add bitmap API. From: Burak Emir To: Yury Norov , Kees Cook Cc: Burak Emir , Rasmus Villemoes , Viresh Kumar , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , "=?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?=" , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , "Gustavo A . R . Silva" , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-hardening@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Provides an abstraction for C bitmap API and bitops operations. We follow the C Bitmap API closely in naming and semantics, with a few differences that take advantage of Rust language facilities and idioms: * We leverage Rust type system guarantees as follows: * Ownership transfer of a Bitmap is restricted so that it cannot be passed between threads (does not implement `Send`). * all (non-atomic) mutating operations require a &mut reference which amounts to exclusive access. * It is permissible to pass shared references &Bitmap between threads, and we expose atomic operations through interior mutability. Since these atomic operations do not provide any ordering guarantees, we mark these as `unsafe`. Anyone who calls the atomic methods needs to document that the lack of ordering is safe. * The Rust API offers `{set,clear}_bit` vs `{set,clear}_bit_atomic`, which is different from the C naming convention (set_bit vs __set_bit). * we include enough operations for the API to be useful, but not all operations are exposed yet in order to avoid dead code. This commit includes enough to enable a Rust implementation of an Android Binder data structure that was introduced in commit 15d9da3f818c ("binder: use bitmap for faster descriptor lookup"), which can be found in drivers/android/dbitmap.h. We need this in order to upstream the Rust port of Android Binder driver. * We follow the C API closely and fine-grained approach to safety: * Low-level bit-ops methods get a safe API with bounds checks. * methods correspond to find_* C methods tolerate out-of-bounds arguments. Since these are already safe we the same behavior, and return results using `Option` types to represent "not found". * the Rust API is optimized to represent the bitmap inline if it would take the space of a pointer. This saves allocations which is relevant in the Binder use case. * Bounds checks where out-of-bounds values would not result in immediate access faults are configured via a RUST_BITMAP_HARDENED config. The underlying C bitmap is *not* exposed, and must never be exposed (except in tests). Exposing the representation would lose all static guarantees, and moreover would prevent the optimized representation of short bitmaps. An alternative route of vendoring an existing Rust bitmap package was considered but suboptimal overall. Reusing the C implementation is preferable for a basic data structure like bitmaps. It enables Rust code to be a lot more similar and predictable with respect to C code that uses the same data structures and enables the use of code that has been tried-and-tested in the kernel, with the same performance characteristics whenever possible. We use the `usize` type for sizes and indices into the bitmap, because Rust generally always uses that type for indices and lengths and it will be more convenient if the API accepts that type. This means that we need to perform some casts to/from u32 and usize, since the C headers use unsigned int instead of size_t/unsigned long for these numbers in some places. Adds new MAINTAINERS section BITMAP API [RUST]. Suggested-by: Alice Ryhl Suggested-by: Yury Norov Signed-off-by: Burak Emir --- MAINTAINERS | 7 + rust/kernel/bitmap.rs | 415 +++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + security/Kconfig.hardening | 9 + 4 files changed, 432 insertions(+) create mode 100644 rust/kernel/bitmap.rs diff --git a/MAINTAINERS b/MAINTAINERS index 04d6727e944c..565eaa015d9e 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -4127,6 +4127,13 @@ S: Maintained F: rust/helpers/bitmap.c F: rust/helpers/cpumask.c =20 +BITMAP API [RUST] +M: Alice Ryhl +M: Burak Emir +R: Yury Norov +S: Maintained +F: rust/kernel/bitmap.rs + BITOPS API M: Yury Norov R: Rasmus Villemoes diff --git a/rust/kernel/bitmap.rs b/rust/kernel/bitmap.rs new file mode 100644 index 000000000000..943dbef7948b --- /dev/null +++ b/rust/kernel/bitmap.rs @@ -0,0 +1,415 @@ +// SPDX-License-Identifier: GPL-2.0 + +// Copyright (C) 2025 Google LLC. + +//! Rust API for bitmap. +//! +//! C headers: [`include/linux/bitmap.h`](srctree/include/linux/bitmap.h). + +use crate::alloc::{AllocError, Flags}; +use crate::bindings; +use core::ptr::NonNull; + +/// Holds either a pointer to array of `unsigned long` or a small bitmap. +#[repr(C)] +union BitmapRepr { + bitmap: usize, + ptr: NonNull, +} + +macro_rules! bitmap_hardening_assert { + ($cond:expr, $($arg:tt)+) =3D> { + #[cfg(RUST_BITMAP_HARDENED)] + assert!($e, $($arg)*); + } +} + +/// Represents a bitmap. +/// +/// Wraps underlying C bitmap API. +/// +/// # Examples +/// +/// Basic usage +/// +/// ``` +/// use kernel::alloc::flags::GFP_KERNEL; +/// use kernel::bitmap::Bitmap; +/// +/// let mut b =3D Bitmap::new(16, GFP_KERNEL)?; +/// +/// assert_eq!(16, b.len()); +/// for i in 0..16 { +/// if i % 4 =3D=3D 0 { +/// b.set_bit(i); +/// } +/// } +/// assert_eq!(Some(0), b.next_bit(0)); +/// assert_eq!(Some(1), b.next_zero_bit(0)); +/// assert_eq!(Some(4), b.next_bit(1)); +/// assert_eq!(Some(5), b.next_zero_bit(4)); +/// assert_eq!(Some(12), b.last_bit()); +/// # Ok::<(), Error>(()) +/// ``` +/// +/// # Invariants +/// +/// * `nbits` is `<=3D i32::MAX` and never changes. +/// * if `nbits <=3D bindings::BITS_PER_LONG`, then `repr` is a bitmap. +/// * otherwise, `repr` holds a non-null pointer that was obtained from a +/// successful call to `bitmap_zalloc` and holds the address of an initi= alized +/// array of `unsigned long` that is large enough to hold `nbits` bits. +pub struct Bitmap { + /// Representation of bitmap. + repr: BitmapRepr, + /// Length of this bitmap. Must be `<=3D i32::MAX`. + nbits: usize, +} + +/// Enable unsynchronized concurrent access to [`Bitmap`] through shared r= eferences. +/// +/// # Safety +/// +/// * When no thread performs any mutations, concurrent access is safe. +/// * Mutations are permitted through atomic operations and interior mutab= ility. +/// All such methods are marked unsafe, to account for the lack of order= ing +/// guarantees. Callers must acknowledge that updates may be observed in= any +/// order. +unsafe impl Sync for Bitmap {} + +impl Drop for Bitmap { + fn drop(&mut self) { + if self.nbits <=3D bindings::BITS_PER_LONG as _ { + return; + } + // SAFETY: `self.ptr` was returned by the C `bitmap_zalloc`. + // + // INVARIANT: there is no other use of the `self.ptr` after this + // call and the value is being dropped so the broken invariant is + // not observable on function exit. + unsafe { bindings::bitmap_free(self.as_mut_ptr()) }; + } +} + +impl Bitmap { + /// Constructs a new [`Bitmap`]. + /// + /// Fails with [`AllocError`] when the [`Bitmap`] could not be allocat= ed. This + /// includes the case when `nbits` is greater than `i32::MAX`. + #[inline] + pub fn new(nbits: usize, flags: Flags) -> Result { + if nbits <=3D bindings::BITS_PER_LONG as _ { + return Ok(Bitmap { + repr: BitmapRepr { bitmap: 0 }, + nbits, + }); + } + if nbits > i32::MAX.try_into().unwrap() { + return Err(AllocError); + } + let nbits_u32 =3D u32::try_from(nbits).unwrap(); + // SAFETY: `bindings::BITS_PER_LONG < nbits` and `nbits <=3D i32::= MAX`. + let ptr =3D unsafe { bindings::bitmap_zalloc(nbits_u32, flags.as_r= aw()) }; + let ptr =3D NonNull::new(ptr).ok_or(AllocError)?; + // INVARIANT: `ptr` returned by C `bitmap_zalloc` and `nbits` chec= ked. + return Ok(Bitmap { + repr: BitmapRepr { ptr }, + nbits, + }); + } + + /// Returns length of this [`Bitmap`]. + #[inline] + pub fn len(&self) -> usize { + self.nbits + } + + /// Returns a mutable raw pointer to the backing [`Bitmap`]. + #[inline] + fn as_mut_ptr(&mut self) -> *mut usize { + if self.nbits <=3D bindings::BITS_PER_LONG as _ { + // SAFETY: Bitmap is represented inline. + unsafe { core::ptr::addr_of_mut!(self.repr.bitmap) } + } else { + // SAFETY: Bitmap is represented as array of `unsigned long`. + unsafe { self.repr.ptr.as_mut() } + } + } + + /// Returns a raw pointer to the backing [`Bitmap`]. + #[inline] + fn as_ptr(&self) -> *const usize { + if self.nbits <=3D bindings::BITS_PER_LONG as _ { + // SAFETY: Bitmap is represented inline. + unsafe { core::ptr::addr_of!(self.repr.bitmap) } + } else { + // SAFETY: Bitmap is represented as array of `unsigned long`. + unsafe { self.repr.ptr.as_ptr() } + } + } + + /// Set bit with index `index`. + /// + /// ATTENTION: `set_bit` is non-atomic, which differs from the naming + /// convention in C code. The corresponding C function is `__set_bit`. + /// + /// # Panics + /// + /// Panics if `index` is greater than or equal to `self.nbits`. + #[inline] + pub fn set_bit(&mut self, index: usize) { + assert!( + index < self.nbits, + "Bit `index` must be < {}, was {}", + self.nbits, + index + ); + // SAFETY: Bit `index` is within bounds. + unsafe { bindings::__set_bit(index as u32, self.as_mut_ptr()) }; + } + + /// Set bit with index `index`, atomically. + /// + /// ATTENTION: The naming convention differs from C, where the corresp= onding + /// function is called `set_bit`. + /// + /// # Safety + /// + /// This is a relaxed atomic operation (no implied memory barriers, no + /// ordering guarantees). The caller must ensure that this is safe, as + /// the compiler cannot prevent code with an exclusive reference from + /// calling atomic operations. + /// + /// # Panics + /// + /// Panics if `index` is greater than or equal to `self.nbits`. + #[inline] + pub unsafe fn set_bit_atomic(&self, index: usize) { + assert!( + index < self.nbits, + "Bit `index` must be < {}, was {}", + self.nbits, + index + ); + // SAFETY: `index` is within bounds and the caller has ensured that + // there is no mix of non-atomic and atomic operations. + unsafe { bindings::set_bit(index as u32, self.as_ptr() as *mut usi= ze) }; + } + + /// Clear `index` bit. + /// + /// ATTENTION: `clear_bit` is non-atomic, which differs from the naming + /// convention in C code. The corresponding C function is `__clear_bit= `. + /// # Panics + /// + /// Panics if `index` is greater than or equal to `self.nbits`. + #[inline] + pub fn clear_bit(&mut self, index: usize) { + assert!( + index < self.nbits, + "Bit `index` must be < {}, was {}", + self.nbits, + index + ); + // SAFETY: `index` is within bounds. + unsafe { bindings::__clear_bit(index as u32, self.as_mut_ptr()) }; + } + + /// Clear `index` bit, atomically. + /// + /// ATTENTION: The naming convention differs from C, where the corresp= onding + /// function is called `clear_bit`. + /// + /// # Safety + /// + /// This is a relaxed atomic operation (no implied memory barriers, no + /// ordering guarantees). The caller must ensure that this is safe, as + /// the compiler cannot prevent code with an exclusive reference from + /// calling atomic operations. + /// + /// # Panics + /// + /// Panics if `index` is greater than or equal to `self.nbits`. + #[inline] + pub unsafe fn clear_bit_atomic(&self, index: usize) { + assert!( + index < self.nbits, + "Bit `index` must be < {}, was {}", + self.nbits, + index + ); + // SAFETY: `index` is within bounds and the caller has ensured that + // there is no mix of non-atomic and atomic operations. + unsafe { bindings::clear_bit(index as u32, self.as_ptr() as *mut u= size) }; + } + + /// Copy `src` into this [`Bitmap`] and set any remaining bits to zero. + /// + /// # Examples + /// + /// ``` + /// use kernel::alloc::{AllocError, flags::GFP_KERNEL}; + /// use kernel::bitmap::Bitmap; + /// + /// let mut long_bitmap =3D Bitmap::new(256, GFP_KERNEL)?; + // + /// assert_eq!(None, long_bitmap.last_bit()); + // + /// let mut short_bitmap =3D Bitmap::new(16, GFP_KERNEL)?; + // + /// short_bitmap.set_bit(7); + /// long_bitmap.copy_and_extend(&short_bitmap); + /// assert_eq!(Some(7), long_bitmap.last_bit()); + /// + /// # Ok::<(), AllocError>(()) + /// ``` + #[inline] + pub fn copy_and_extend(&mut self, src: &Bitmap) { + let len =3D core::cmp::min(src.nbits, self.nbits); + // SAFETY: access to `self` and `src` is within bounds. + unsafe { + bindings::bitmap_copy_and_extend( + self.as_mut_ptr(), + src.as_ptr(), + len as u32, + self.nbits as u32, + ) + }; + } + + /// Finds last set bit. + /// + /// # Examples + /// + /// ``` + /// use kernel::alloc::{AllocError, flags::GFP_KERNEL}; + /// use kernel::bitmap::Bitmap; + /// + /// let bitmap =3D Bitmap::new(64, GFP_KERNEL)?; + /// + /// match bitmap.last_bit() { + /// Some(idx) =3D> { + /// pr_info!("The last bit has index {idx}.\n"); + /// } + /// None =3D> { + /// pr_info!("All bits in this bitmap are 0.\n"); + /// } + /// } + /// # Ok::<(), AllocError>(()) + /// ``` + #[inline] + pub fn last_bit(&self) -> Option { + // SAFETY: `_find_next_bit` access is within bounds due to invaria= nt. + let index =3D unsafe { bindings::_find_last_bit(self.as_ptr(), sel= f.nbits) }; + if index >=3D self.nbits { + None + } else { + Some(index) + } + } + + /// Finds next set bit, starting from `start`. + /// Returns `None` if `start` is greater of equal than `self.nbits`. + #[inline] + pub fn next_bit(&self, start: usize) -> Option { + bitmap_hardening_assert!(start < self.nbits, "`start` must be < {}= was {}", self.nbits, start); + // SAFETY: `_find_next_bit` tolerates out-of-bounds arguments and = returns a + // value larger than or equal to `self.nbits` in that case. + let index =3D unsafe { bindings::_find_next_bit(self.as_ptr(), sel= f.nbits, start) }; + if index >=3D self.nbits { + None + } else { + Some(index) + } + } + + /// Finds next zero bit, starting from `start`. + /// Returns `None` if `start` is greater than or equal to `self.nbits`. + #[inline] + pub fn next_zero_bit(&self, start: usize) -> Option { + bitmap_hardening_assert!(start < self.nbits, "`start` must be < {}= was {}", self.nbits, start); + // SAFETY: `_find_next_zero_bit` tolerates out-of-bounds arguments= and returns a + // value larger than or equal to `self.nbits` in that case. + let index =3D unsafe { bindings::_find_next_zero_bit(self.as_ptr()= , self.nbits, start) }; + if index >=3D self.nbits { + None + } else { + Some(index) + } + } +} + +use macros::kunit_tests; + +#[kunit_tests(rust_kernel_bitmap)] +mod tests { + use super::*; + use kernel::alloc::flags::GFP_KERNEL; + + #[test] + fn bitmap_new() { + let b =3D Bitmap::new(0, GFP_KERNEL).unwrap(); + assert_eq!(0, b.len()); + + let b =3D Bitmap::new(3, GFP_KERNEL).unwrap(); + assert_eq!(3, b.len()); + + let b =3D Bitmap::new(1024, GFP_KERNEL).unwrap(); + assert_eq!(1024, b.len()); + + // Requesting too large values results in [`AllocError`]. + let b =3D Bitmap::new(1 << 31, GFP_KERNEL); + assert!(b.is_err()); + } + + #[test] + fn bitmap_set_clear_find() { + let mut b =3D Bitmap::new(128, GFP_KERNEL).unwrap(); + + // Zero-initialized + assert_eq!(None, b.last_bit()); + + b.set_bit(17); + + assert_eq!(Some(17), b.next_bit(0)); + assert_eq!(Some(17), b.last_bit()); + + b.set_bit(107); + + assert_eq!(Some(17), b.next_bit(0)); + assert_eq!(Some(17), b.next_bit(17)); + assert_eq!(Some(107), b.next_bit(18)); + assert_eq!(Some(107), b.last_bit()); + + b.clear_bit(17); + + assert_eq!(Some(107), b.next_bit(0)); + assert_eq!(Some(107), b.last_bit()); + } + + #[test] + fn bitmap_out_of_bounds() { + let mut b =3D Bitmap::new(128, GFP_KERNEL).unwrap(); + + assert_eq!(None, b.next_bit(2048)); + assert_eq!(None, b.next_zero_bit(2048)); + assert_eq!(None, b.last_bit(2048)); + } + + #[test] + fn bitmap_copy_and_extend() { + let mut long_bitmap =3D Bitmap::new(256, GFP_KERNEL).unwrap(); + + long_bitmap.set_bit(3); + long_bitmap.set_bit(200); + + let mut short_bitmap =3D Bitmap::new(32, GFP_KERNEL).unwrap(); + + short_bitmap.set_bit(17); + + long_bitmap.copy_and_extend(&short_bitmap); + // The larger bits have been cleared. + assert_eq!(Some(17), long_bitmap.next_bit(0)); + assert_eq!(Some(17), long_bitmap.last_bit()); + } +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index de07aadd1ff5..8c4161cd82ac 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -38,6 +38,7 @@ pub use ffi; =20 pub mod alloc; +pub mod bitmap; #[cfg(CONFIG_BLOCK)] pub mod block; #[doc(hidden)] diff --git a/security/Kconfig.hardening b/security/Kconfig.hardening index 3fe9d7b945c4..926665bbc8f2 100644 --- a/security/Kconfig.hardening +++ b/security/Kconfig.hardening @@ -324,6 +324,15 @@ config LIST_HARDENED =20 If unsure, say N. =20 +config RUST_BITMAP_HARDENED + bool "Check integrity of linked list manipulation" + help + Enables additional assertions in the Rust Bitmap API to catch + arguments that are not guaranteed to result in an immediate access + fault. + + If unsure, say N. + config BUG_ON_DATA_CORRUPTION bool "Trigger a BUG when data corruption is detected" select LIST_HARDENED --=20 2.49.0.1101.gccaa498523-goog From nobody Fri Dec 19 14:37:46 2025 Received: from mail-wm1-f74.google.com (mail-wm1-f74.google.com [209.85.128.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 0977928A1CB for ; Mon, 19 May 2025 16:17:38 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.74 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747671461; cv=none; b=IFJzYO3XH/mTlwqcy2rie6gugsRMzZjkxfNCqbqWQgCVA2dfySRFlmomwtlAy9edR5VBamun/qA9xpiReQ5JQ6aO0DGMDF3HlyIu2hMajPikb/Eqhqte7g/qwk7F+cWyYUyp02y/82BNlZ6GldUvejdj2YD7tZPp1MKEzenGXvw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747671461; c=relaxed/simple; bh=A2vcimdo91Db/C+CJNN9YS7LNgV+bE3hpqZjImDFRQw=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=R8rz2eUavcgfHer3xS8xn2KN3gS/0s2UJ8tZFcl0Ah8l2Geq2X+AJ8HFk97s4xvp37WSra+W88SAIKof1SmcLyqXdO4mmnB55D6mu09O3umNt9YVUAf60MUPwGkZuss2CA5w685Ge9DETJ7B56yTwto9QOnoxaHnghA6ahw4q1E= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--bqe.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=Hfhd0+E9; arc=none smtp.client-ip=209.85.128.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--bqe.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="Hfhd0+E9" Received: by mail-wm1-f74.google.com with SMTP id 5b1f17b1804b1-43e9a3d2977so34439065e9.1 for ; Mon, 19 May 2025 09:17:38 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1747671457; x=1748276257; 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=MSmVioyXmmwvYcQv1eghQliH8ReaGKH9UaRa1j6LEaY=; b=Hfhd0+E9wMYuhbvT7h6X3I6WOGqazT+SDQT0lYzgmpXbiox0OgvxkBaQy2vYkA4owS Kv7xyNdcFaZF5TDvOYrnujrNIQp1NMPNE2RneP30YwIkPZ5AFDA0AoyF2p8egZlnr8Ql 5agFyzdbiNINcQ1W1ed/Y3WLwVXd0Ts+YDGABhJC/chdxtMoIrWaicEYUx1gknzE/hdJ 7ldyIyXCrvpAyfwubKrIvCbSdEJbMacwgIAwwbAknyGZVIzClGasFo+H+XmF18DOIug/ Ve+Z5zWXrBQlW4GGuVAMn/BTyINhJR+lSDSXGyh0HHXmvxPxIftatI08w7HWhiUsdGJ0 dcLg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1747671457; x=1748276257; 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=MSmVioyXmmwvYcQv1eghQliH8ReaGKH9UaRa1j6LEaY=; b=LxQHwGAHb+3mxuB8CE3K1JxikbZ1/gHQUmD5ZD9QuL5IOA6zGX5WEtqZ4LNIX/jMNr WCzjTpOH4/szx+sFutUSmA67jTHH8G3uu7I+Cerchwlf5Wb9sa+VJPs0T7phqQGPcK2A yd43xr4IEaMvkvr8pHvIlfvpP2HMW58c2x/mSCaBybtKWjSlNY/SYm36kvYGNOkKglC4 qaWFp5vr/0vpCGOq/0D4iG+hvEdnXmC/XXzyaMv+UyL5lGHlO4vhR4VS1tvfjxUoT+tt OPZryd9m7PKi5RStPmceZ9hESS5z8+pJI4d9Ra66tShVbuzMVX+heXYQPoZFGgfAkWn8 zJpg== X-Forwarded-Encrypted: i=1; AJvYcCXeJFHtLkWBMPpcHYZlTq4WJkj8AzzjXFIsVsc3gzZQ4EQj5zNo4obDv0FUYGCJVYn4RurALfFQmM1iEPM=@vger.kernel.org X-Gm-Message-State: AOJu0Yx0XKYKRIocJ7ZgO7czlKWjB7ZELOzGxhBVit4GM8gfMMxPTwyV uxtWR3Pb/9UsGsfmo8xZT8N7pA8BBSV+hKiCWexftT26cQdP8vqPDOGU4cdx7gZRyHNvFw== X-Google-Smtp-Source: AGHT+IGml/YtjllhNJ54nIk+Ysxm78efQivAD3ThoIWPXeVgkiOEHYcUO6jbPJ9gyRT2W4tdao3tzLw= X-Received: from wmqb16.prod.google.com ([2002:a05:600c:4e10:b0:440:68aa:44b]) (user=bqe job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:8889:20b0:442:f44f:66f with SMTP id 5b1f17b1804b1-442fd672542mr85780545e9.31.1747671457562; Mon, 19 May 2025 09:17:37 -0700 (PDT) Date: Mon, 19 May 2025 16:17:04 +0000 In-Reply-To: <20250519161712.2609395-1-bqe@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250519161712.2609395-1-bqe@google.com> X-Mailer: git-send-email 2.49.0.1101.gccaa498523-goog Message-ID: <20250519161712.2609395-5-bqe@google.com> Subject: [PATCH v8 4/5] rust: add find_bit_benchmark_rust module. From: Burak Emir To: Yury Norov , Kees Cook Cc: Burak Emir , Rasmus Villemoes , Viresh Kumar , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , "=?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?=" , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , "Gustavo A . R . Silva" , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-hardening@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Microbenchmark protected by a config FIND_BIT_BENCHMARK_RUST, following `find_bit_benchmark.c` but testing the Rust Bitmap API. We add a fill_random() method protected by the config in order to maintain the abstraction. Suggested-by: Alice Ryhl Suggested-by: Yury Norov Signed-off-by: Burak Emir --- MAINTAINERS | 1 + lib/Kconfig.debug | 13 +++++ lib/Makefile | 1 + lib/find_bit_benchmark_rust.rs | 94 +++++++++++++++++++++++++++++++++ rust/bindings/bindings_helper.h | 1 + rust/kernel/bitmap.rs | 14 +++++ 6 files changed, 124 insertions(+) create mode 100644 lib/find_bit_benchmark_rust.rs diff --git a/MAINTAINERS b/MAINTAINERS index 565eaa015d9e..943d85ed1876 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -4132,6 +4132,7 @@ M: Alice Ryhl M: Burak Emir R: Yury Norov S: Maintained +F: lib/find_bit_benchmark_rust.rs F: rust/kernel/bitmap.rs =20 BITOPS API diff --git a/lib/Kconfig.debug b/lib/Kconfig.debug index f9051ab610d5..37a07559243e 100644 --- a/lib/Kconfig.debug +++ b/lib/Kconfig.debug @@ -2605,6 +2605,19 @@ config FIND_BIT_BENCHMARK =20 If unsure, say N. =20 +config FIND_BIT_BENCHMARK_RUST + tristate "Test find_bit functions in Rust" + help + This builds the "find_bit_benchmark_rust" module. It is a micro + benchmark that measures the performance of Rust functions that + correspond to the find_*_bit() operations in C. It follows the + FIND_BIT_BENCHMARK closely but will in general not yield same + numbers due to extra bounds checks and overhead of foreign + function calls. + + If unsure, say N. + + config TEST_FIRMWARE tristate "Test firmware loading via userspace interface" depends on FW_LOADER diff --git a/lib/Makefile b/lib/Makefile index f07b24ce1b3f..99e49a8f5bf8 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -62,6 +62,7 @@ obj-y +=3D hexdump.o obj-$(CONFIG_TEST_HEXDUMP) +=3D test_hexdump.o obj-y +=3D kstrtox.o obj-$(CONFIG_FIND_BIT_BENCHMARK) +=3D find_bit_benchmark.o +obj-$(CONFIG_FIND_BIT_BENCHMARK_RUST) +=3D find_bit_benchmark_rust.o obj-$(CONFIG_TEST_BPF) +=3D test_bpf.o test_dhry-objs :=3D dhry_1.o dhry_2.o dhry_run.o obj-$(CONFIG_TEST_DHRY) +=3D test_dhry.o diff --git a/lib/find_bit_benchmark_rust.rs b/lib/find_bit_benchmark_rust.rs new file mode 100644 index 000000000000..13830477a8d2 --- /dev/null +++ b/lib/find_bit_benchmark_rust.rs @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: GPL-2.0 +//! Benchmark for find_bit-like methods in Bitmap Rust API. + +use kernel::alloc::flags::GFP_KERNEL; +use kernel::bindings; +use kernel::bitmap::Bitmap; +use kernel::error::{code, Result}; +use kernel::pr_err; +use kernel::prelude::module; +use kernel::time::Ktime; +use kernel::ThisModule; + +const BITMAP_LEN: usize =3D 4096 * 8 * 10; +// Reciprocal of the fraction of bits that are set in sparse bitmap. +const SPARSENESS: usize =3D 500; + +/// Test module that benchmarks performance of traversing bitmaps. +struct FindBitBenchmarkModule(); + +fn test_next_bit(bitmap: &Bitmap) { + let mut time =3D Ktime::ktime_get(); + let mut cnt =3D 0; + let mut i =3D 0; + + while let Some(index) =3D bitmap.next_bit(i) { + cnt +=3D 1; + i =3D index + 1; + } + + time =3D Ktime::ktime_get() - time; + pr_err!( + "next_bit: {:18} ns, {:6} iterations\n", + time.to_ns(), + cnt + ); +} + +fn test_next_zero_bit(bitmap: &Bitmap) { + let mut time =3D Ktime::ktime_get(); + let mut cnt =3D 0; + let mut i =3D 0; + + while let Some(index) =3D bitmap.next_zero_bit(i) { + cnt +=3D 1; + i =3D index + 1; + } + + time =3D Ktime::ktime_get() - time; + pr_err!( + "next_zero_bit: {:18} ns, {:6} iterations\n", + time.to_ns(), + cnt + ); +} + +fn find_bit_test() { + pr_err!("Start testing find_bit() Rust with random-filled bitmap\n"); + + let mut bitmap =3D Bitmap::new(BITMAP_LEN, GFP_KERNEL).expect("alloc b= itmap failed"); + bitmap.fill_random(); + + test_next_bit(&bitmap); + test_next_zero_bit(&bitmap); + + pr_err!("Start testing find_bit() Rust with sparse bitmap\n"); + + let mut bitmap =3D Bitmap::new(BITMAP_LEN, GFP_KERNEL).expect("alloc s= parse bitmap failed"); + let nbits =3D BITMAP_LEN / SPARSENESS; + for _i in 0..nbits { + // SAFETY: BITMAP_LEN fits in 32 bits. + let bit: usize =3D + unsafe { bindings::__get_random_u32_below(BITMAP_LEN.try_into(= ).unwrap()) as _ }; + bitmap.set_bit(bit); + } + + test_next_bit(&bitmap); + test_next_zero_bit(&bitmap); +} + +impl kernel::Module for FindBitBenchmarkModule { + fn init(_module: &'static ThisModule) -> Result { + find_bit_test(); + // Return error so test module can be inserted again without rmmod. + Err(code::EINVAL) + } +} + +module! { + type: FindBitBenchmarkModule, + name: "find_bit_benchmark_rust_module", + authors: ["Rust for Linux Contributors"], + description: "Module with benchmark for bitmap code!", + license: "GPL v2", +} diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helpe= r.h index b6bf3b039c1b..f6ca7f1dd08b 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -31,6 +31,7 @@ #include #include #include +#include #include #include #include diff --git a/rust/kernel/bitmap.rs b/rust/kernel/bitmap.rs index 943dbef7948b..fb0c687420cd 100644 --- a/rust/kernel/bitmap.rs +++ b/rust/kernel/bitmap.rs @@ -124,6 +124,20 @@ pub fn len(&self) -> usize { self.nbits } =20 + /// Fills this `Bitmap` with random bits. + #[cfg(CONFIG_FIND_BIT_BENCHMARK_RUST)] + pub fn fill_random(&mut self) { + // SAFETY: `self.as_mut_ptr` points to either an array of the + // appropriate length or one usize. + unsafe { + bindings::get_random_bytes( + self.as_mut_ptr() as *mut ffi::c_void, + usize::div_ceil(self.nbits, bindings::BITS_PER_LONG as usi= ze) + * bindings::BITS_PER_LONG as usize, + ); + } + } + /// Returns a mutable raw pointer to the backing [`Bitmap`]. #[inline] fn as_mut_ptr(&mut self) -> *mut usize { --=20 2.49.0.1101.gccaa498523-goog From nobody Fri Dec 19 14:37:46 2025 Received: from mail-wm1-f73.google.com (mail-wm1-f73.google.com [209.85.128.73]) (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 0157E28A1E3 for ; Mon, 19 May 2025 16:17:40 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.73 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747671462; cv=none; b=trRcoWEaSaF59Ko0opteniGoNpxh8E/wAgszC5uNS7l2GEtxozs2g1i98eXDmVBGPrOkSxhTbUl83ElywHutmpHk9MQKu7YdxPcPWu/zPbm3hrpLJaEfNj637mQ8vCVEJGYYaWQBZ4UUueauFwL9eiy9slsRVY6e4slihI9BJrY= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1747671462; c=relaxed/simple; bh=rHUxzB2Bwi+2jlKp4urPGDKcCylqhDAV9PHNICkE1AM=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=ebUKIRXbmJsu/t3DBfJ5CS3JxTrTu2jSnOz6r5Raci648zKO0JcJErWI8BEz3UIG86RD2u5wrXUltfgQ00MS5qlj5+B3/ovB5IZoK6UIUBADaQpBd1N9WQfXfHHXKidJDC1z5eBafLdkDboKytpKmExHwItiMVEOW69Uh+JQu8w= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--bqe.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=QL1YDF5F; arc=none smtp.client-ip=209.85.128.73 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--bqe.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="QL1YDF5F" Received: by mail-wm1-f73.google.com with SMTP id 5b1f17b1804b1-43d734da1a3so25195425e9.0 for ; Mon, 19 May 2025 09:17:40 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1747671459; x=1748276259; 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=zRmZrCz4QpMiECwxwWyXnnAcIyfbi3oIrpsYNgBmqlI=; b=QL1YDF5FRrVyQG5Mqn5MfgOfwsLL+ZL01joP1us5ZT8X7nMCzh+JCNji/cYMSUhu1a XqMOs4RSeuxqkASbtkVFIAqyDzzSqZ4trkHIfmJ+KSGN80jsYZPxkUouoq3osUGfIb8k C3ZX5S2UXrtoP6JzlzNsUGJp7WlLtaw9v08i2wfTgm8+gr+D2L/f0eIyBQ2aVfxkpb/L xIRfh4Yltpnhc9k/QRLbukvTDSS3IEBSXQn/8urA0zuqY0WsIjPvB4wuu41ppipvRPpc PyDLQULIHtDrM9DaxHBO+x7zCa0xkAIfNUjoQWY6mETBQLT7vRWqG5+ccpA1CUfb7MJD Oy0Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1747671459; x=1748276259; 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=zRmZrCz4QpMiECwxwWyXnnAcIyfbi3oIrpsYNgBmqlI=; b=GEr/ejoh2xoY1Ui2Sw4+FYjwcjtOPq2NJ8IBCNZ0ynuQZPYxvhW7hkENNzGaYPtEAD Wbo/rUwXez/WDFuyRsnbhCYPSjW55DwawMLOOsZi01tVyyI+YuSXDETc4+yhCOTParGd u3x2jjaLxgVRiaMAMgjfnlu8lN27HeKgCGNNKE+df3rMp4w9mwr1Tnr4O/0gdrMbbE0z GiizXwwbh17CCG4A0itV22nfjHw1+wa6Xv5TaJE6x0dZcNP+0vwztH7zrT+HohPzoqys oQ82bQuVlSTroX1aXBMfGbymdnOnLmOI9YUodWCpHL1XAjny1sVok6X70Fwo+Iukfgdp mXzw== X-Forwarded-Encrypted: i=1; AJvYcCUyEsLUaId0TSt6GCfWKbXCsLYVShEyFhUFYpChRA/ylp9aUTdn52UOoWHu/9+pAA7EeKkYailZfZ+6Vjw=@vger.kernel.org X-Gm-Message-State: AOJu0Yw+lNOmbQLaANCk2aIKDnDoPai8TLHnIONn2jkGz2AEfKKhA6Y3 MqYSu4C8SmxjmFhtuQfhDP78wO5nY/AVo7DgNfBZ+9TPzebJOsVOvJ6kkEeJ/TNGGp1RxA== X-Google-Smtp-Source: AGHT+IFyBZQy4NfRKtT3XwWN6zobbmN0oZUd8mI/AD9F82y7coNWR9BSlEwIZv+kecL0Ld+zemnMy6w= X-Received: from wmdd3.prod.google.com ([2002:a05:600c:a203:b0:445:1cd2:5e5f]) (user=bqe job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:a46:b0:442:dc6f:2f11 with SMTP id 5b1f17b1804b1-442ff032533mr80126215e9.25.1747671459299; Mon, 19 May 2025 09:17:39 -0700 (PDT) Date: Mon, 19 May 2025 16:17:05 +0000 In-Reply-To: <20250519161712.2609395-1-bqe@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250519161712.2609395-1-bqe@google.com> X-Mailer: git-send-email 2.49.0.1101.gccaa498523-goog Message-ID: <20250519161712.2609395-6-bqe@google.com> Subject: [PATCH v8 5/5] rust: add dynamic ID pool abstraction for bitmap From: Burak Emir To: Yury Norov , Kees Cook Cc: Burak Emir , Rasmus Villemoes , Viresh Kumar , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , "=?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?=" , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , "Gustavo A . R . Silva" , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-hardening@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" This is a port of the Binder data structure introduced in commit 15d9da3f818c ("binder: use bitmap for faster descriptor lookup") to Rust. Like drivers/android/dbitmap.h, the ID pool abstraction lets clients acquire and release IDs. The implementation uses a bitmap to know what IDs are in use, and gives clients fine-grained control over the time of allocation. This fine-grained control is needed in the Android Binder. We provide an example that release a spinlock for allocation and unit tests (rustdoc examples). The implementation is not aware that the underlying Bitmap abstraction handles lengths below BITS_PER_LONG without allocation. Suggested-by: Alice Ryhl Suggested-by: Yury Norov Signed-off-by: Burak Emir --- MAINTAINERS | 1 + rust/kernel/id_pool.rs | 201 +++++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 3 files changed, 203 insertions(+) create mode 100644 rust/kernel/id_pool.rs diff --git a/MAINTAINERS b/MAINTAINERS index 943d85ed1876..bc95d98f266b 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -4134,6 +4134,7 @@ R: Yury Norov S: Maintained F: lib/find_bit_benchmark_rust.rs F: rust/kernel/bitmap.rs +F: rust/kernel/id_pool.rs =20 BITOPS API M: Yury Norov diff --git a/rust/kernel/id_pool.rs b/rust/kernel/id_pool.rs new file mode 100644 index 000000000000..8f07526bb580 --- /dev/null +++ b/rust/kernel/id_pool.rs @@ -0,0 +1,201 @@ +// SPDX-License-Identifier: GPL-2.0 + +// Copyright (C) 2025 Google LLC. + +//! Rust API for an ID pool backed by a `Bitmap`. + +use crate::alloc::{AllocError, Flags}; +use crate::bitmap::Bitmap; + +/// Represents a dynamic ID pool backed by a `Bitmap`. +/// +/// Clients acquire and release IDs from zero bits in a bitmap. +/// +/// The ID pool can grow or shrink as needed. It has been designed +/// to support the scenario where users need to control the time +/// of allocation of a new backing bitmap, which may require release +/// of locks. +/// These operations then, are verified to determine if the grow or +/// shrink is sill valid. +/// +/// # Examples +/// +/// Basic usage +/// +/// ``` +/// use kernel::alloc::{AllocError, flags::GFP_KERNEL}; +/// use kernel::id_pool::IdPool; +/// +/// let mut pool =3D IdPool::new(64, GFP_KERNEL)?; +/// for i in 0..64 { +/// assert_eq!(i, pool.acquire_next_id(i).ok_or(ENOSPC)?); +/// } +/// +/// pool.release_id(23); +/// assert_eq!(23, pool.acquire_next_id(0).ok_or(ENOSPC)?); +/// +/// assert_eq!(None, pool.acquire_next_id(0)); // time to realloc. +/// let resizer =3D pool.grow_alloc().alloc(GFP_KERNEL)?; +/// pool.grow(resizer); +/// +/// assert_eq!(pool.acquire_next_id(0), Some(64)); +/// # Ok::<(), Error>(()) +/// ``` +/// +/// Releasing spinlock to grow the pool +/// +/// ```no_run +/// use kernel::alloc::{AllocError, flags::GFP_KERNEL}; +/// use kernel::sync::{new_spinlock, SpinLock}; +/// use kernel::id_pool::IdPool; +/// +/// fn get_id_maybe_alloc(guarded_pool: &SpinLock) -> Result { +/// let mut pool =3D guarded_pool.lock(); +/// loop { +/// match pool.acquire_next_id(0) { +/// Some(index) =3D> return Ok(index), +/// None =3D> { +/// let alloc_request =3D pool.grow_alloc(); +/// drop(pool); +/// let resizer =3D alloc_request.alloc(GFP_KERNEL)?; +/// pool =3D guarded_pool.lock(); +/// pool.grow(resizer) +/// } +/// } +/// } +/// } +/// ``` +pub struct IdPool { + map: Bitmap, +} + +/// Returned when the `IdPool` should change size. +pub struct AllocRequest { + nbits: usize, +} + +/// Contains an allocated `Bitmap` for resizing `IdPool`. +pub struct PoolResizer { + new: Bitmap, +} + +impl AllocRequest { + /// Allocates a new `Bitmap` for `IdPool`. + pub fn alloc(&self, flags: Flags) -> Result { + let new =3D Bitmap::new(self.nbits, flags)?; + Ok(PoolResizer { new }) + } +} + +impl IdPool { + /// Constructs a new `[IdPool]`. + #[inline] + pub fn new(nbits: usize, flags: Flags) -> Result { + let map =3D Bitmap::new(nbits, flags)?; + Ok(Self { map }) + } + + /// Returns how many IDs this pool can currently have. + #[inline] + pub fn len(&self) -> usize { + self.map.len() + } + + /// Returns an [`AllocRequest`] if the [`IdPool`] can be shrunk, [`Non= e`] otherwise. + /// + /// # Examples + /// + /// ``` + /// use kernel::alloc::{AllocError, flags::GFP_KERNEL}; + /// use kernel::id_pool::{AllocRequest, IdPool}; + /// + /// let mut pool =3D IdPool::new(1024, GFP_KERNEL)?; + /// let alloc_request =3D pool.shrink_alloc().ok_or(AllocError)?; + /// let resizer =3D alloc_request.alloc(GFP_KERNEL)?; + /// pool.shrink(resizer); + /// assert_eq!(pool.len(), kernel::bindings::BITS_PER_LONG as usize); + /// # Ok::<(), AllocError>(()) + /// ``` + #[inline] + pub fn shrink_alloc(&self) -> Option { + let len =3D self.map.len(); + if len <=3D bindings::BITS_PER_LONG as usize { + return None; + } + /* + * Determine if the bitmap can shrink based on the position of + * its last set bit. If the bit is within the first quarter of + * the bitmap then shrinking is possible. In this case, the + * bitmap should shrink to half its current size. + */ + match self.map.last_bit() { + Some(bit) =3D> { + if bit < (len >> 2) { + Some(AllocRequest { nbits: len >> 1 }) + } else { + None + } + } + None =3D> Some(AllocRequest { + nbits: bindings::BITS_PER_LONG as usize, + }), + } + } + + /// Shrinks pool by using a new `Bitmap`, if still possible. + #[inline] + pub fn shrink(&mut self, mut resizer: PoolResizer) { + // Verify that shrinking is still possible. The `resizer` + // bitmap might have been allocated without locks, so this call + // could now be outdated. In this case, drop `resizer` and move on. + if let Some(AllocRequest { nbits }) =3D self.shrink_alloc() { + if nbits <=3D resizer.new.len() { + resizer.new.copy_and_extend(&self.map); + self.map =3D resizer.new; + return; + } + } + } + + /// Returns an `AllocRequest` for growing this `IdPool`. + #[inline] + pub fn grow_alloc(&self) -> AllocRequest { + AllocRequest { + nbits: self.map.len() << 1, + } + } + + /// Grows pool by using a new `Bitmap`, if still necessary. + #[inline] + pub fn grow(&mut self, mut resizer: PoolResizer) { + // `resizer` bitmap might have been allocated without locks, + // so this call could now be outdated. In this case, drop + // `resizer` and move on. + if resizer.new.len() <=3D self.map.len() { + return; + } + + resizer.new.copy_and_extend(&self.map); + self.map =3D resizer.new; + } + + /// Acquires a new ID by finding and setting the next zero bit in the + /// bitmap. Upon success, returns its index. Otherwise, returns `None` + /// to indicate that a `grow_alloc` is needed. + #[inline] + pub fn acquire_next_id(&mut self, offset: usize) -> Option { + match self.map.next_zero_bit(offset) { + res @ Some(nr) =3D> { + self.map.set_bit(nr); + res + } + None =3D> None, + } + } + + /// Releases an ID. + #[inline] + pub fn release_id(&mut self, id: usize) { + self.map.clear_bit(id); + } +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 8c4161cd82ac..d7def807900a 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -54,6 +54,7 @@ #[cfg(CONFIG_RUST_FW_LOADER_ABSTRACTIONS)] pub mod firmware; pub mod fs; +pub mod id_pool; pub mod init; pub mod io; pub mod ioctl; --=20 2.49.0.1101.gccaa498523-goog