From nobody Sat Apr 18 01:59:18 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id D3F8D1AC44D; Thu, 12 Feb 2026 08:25:29 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770884729; cv=none; b=GVQkPxFfkzoFCjCyo5jhyinnaSxXEjrdj8kjirVhL2zwrQS+iU5PGml85d4siLQiH/VxK4qm6fGDGJTyrUGZOkrcNAvTNuZMcgmnkxHALp1pR7GXkyHhvr3bIAHui4rUqixLuLbV8tj0Wl5hxuy+y/7tyRapb2XL6rtZixZ5ejM= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770884729; c=relaxed/simple; bh=+U+p2Z/uUpt8RAU6nY6WDOUeBR8Psa2pT13SYRVgxIs=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=ra7+S5XXmcjDlQIzgFCEUyhsbKMX5r329AjzYhkSYAUVd6NpCk1COK/hwDdFVgggmbbMtIAT1oUjzKcEIB17K8AlLQcZOfissobhzGjq7E7e/wnvL+g6uDI1zMVeKD0gD3yMzs5OfXThubQttP7U/jIcu570OMAt1NUV2ldahog= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=YBTsj6mV; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="YBTsj6mV" Received: by smtp.kernel.org (Postfix) with ESMTPS id 91D31C2BC87; Thu, 12 Feb 2026 08:25:29 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1770884729; bh=+U+p2Z/uUpt8RAU6nY6WDOUeBR8Psa2pT13SYRVgxIs=; h=From:Date:Subject:References:In-Reply-To:To:Cc:Reply-To:From; b=YBTsj6mV+SCiqvZvIq/p/xLjsChWCdLJzjGycyLUviI/GlVz3iQXxVYjqR+wWh2mb p2Qar+xL/PlGsAldpnrcuNVODK4w2XoVPoTRSc58OARfGdVeBOgmLK00HzKG0/12Il z64ScUPICL4chGvUaUyVzuovhu/h9oD0M9Hun27DxgREHS1lvWbwjra3o4nIXL0zXu kWrJ3DJ0bZukGKy9QuABGi9r2YntWTo3LOPXlVssRvI93T6QmQC9fyLFTVYphxouOm KmEvw3icsHWKa3hnhbxcY/L2v1hRZeN86JH9ixPCZSS/DqdDXLFamfusuhzQj9yyat Ik+nrM+ca6b4w== Received: from aws-us-west-2-korg-lkml-1.web.codeaurora.org (localhost.localdomain [127.0.0.1]) by smtp.lore.kernel.org (Postfix) with ESMTP id 7BB3BEDF057; Thu, 12 Feb 2026 08:25:29 +0000 (UTC) From: Shivam Kalra via B4 Relay Date: Thu, 12 Feb 2026 13:47:07 +0530 Subject: [PATCH v4 1/3] rust: kvec: implement shrink_to for KVVec Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260212-binder-shrink-vec-v3-v4-1-bd02f06bf2cd@zohomail.in> References: <20260212-binder-shrink-vec-v3-v4-0-bd02f06bf2cd@zohomail.in> In-Reply-To: <20260212-binder-shrink-vec-v3-v4-0-bd02f06bf2cd@zohomail.in> To: Danilo Krummrich , Lorenzo Stoakes , Vlastimil Babka , "Liam R. Howlett" , Uladzislau Rezki , Miguel Ojeda , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Greg Kroah-Hartman , =?utf-8?q?Arve_Hj=C3=B8nnev=C3=A5g?= , Todd Kjos , Christian Brauner , Carlos Llamas Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Shivam Kalra X-Mailer: b4 0.14.3 X-Developer-Signature: v=1; a=ed25519-sha256; t=1770884727; l=4766; i=shivamkalra98@zohomail.in; s=20260212; h=from:subject:message-id; bh=1lmOoNDN5k5Y6BEWGGmNH2kzUdtUf76G0aStHL8oIVA=; b=xJMLNeITnl+KLCAJHk6yXl87VBNwc4sEfJttzmOGUN2f7M6ibXpJI+sRUXDFCsCDAF9rL2q1E yPexhxYkR2VAVfyTmwkqsCb848DVmC60710WSWlfWYqgX366tmw1R8O X-Developer-Key: i=shivamkalra98@zohomail.in; a=ed25519; pk=9Q+S1LD/xjbjL7bEaLIlwRADBwU/6LJq7lYm8LFrkQE= X-Endpoint-Received: by B4 Relay for shivamkalra98@zohomail.in/20260212 with auth_id=633 X-Original-From: Shivam Kalra Reply-To: shivamkalra98@zohomail.in From: Shivam Kalra Implement shrink_to method specifically for `KVVec` (i.e., `Vec`). `shrink_to` reduces the vector's capacity to a specified minimum, but only performs shrinking when it would free at least one page of memory. This prevents unnecessary allocations while allowing reclamation of unused memory. The implementation uses explicit alloc+copy+free because `vrealloc` does not yet support in-place shrinking. A TODO note marks this for future replacement with a generic shrink_to for all allocators that uses `A::realloc()` once the underlying allocators properly support shrinking via realloc. Suggested-by: Alice Ryhl Suggested-by: Danilo Krummrich Signed-off-by: Shivam Kalra --- rust/kernel/alloc/kvec.rs | 78 +++++++++++++++++++++++++++++++++++++++++++= +++- 1 file changed, 77 insertions(+), 1 deletion(-) diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs index ac8d6f763ae81..8524f9f3dff0a 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -9,7 +9,7 @@ }; use crate::{ fmt, - page::AsPageIter, // + page::{AsPageIter, PAGE_SIZE}, }; use core::{ borrow::{Borrow, BorrowMut}, @@ -734,6 +734,82 @@ pub fn retain(&mut self, mut f: impl FnMut(&mut T) -> = bool) { self.truncate(num_kept); } } +// TODO: This is a temporary KVVec-specific implementation. It should be r= eplaced with a generic +// `shrink_to()` for `impl Vec` that uses `A::reall= oc()` once the +// underlying allocators properly support shrinking via realloc. +impl Vec { + /// Shrinks the capacity of the vector with a lower bound. + /// + /// The capacity will remain at least as large as both the length and = the supplied value. + /// If the current capacity is less than the lower limit, this is a no= -op. + /// + /// Shrinking only occurs if the operation would free at least one pag= e of memory. + /// + /// # Examples + /// + /// ``` + /// // Allocate enough capacity to span multiple pages. + /// let elements_per_page =3D kernel::page::PAGE_SIZE / core::mem::siz= e_of::(); + /// let mut v =3D KVVec::with_capacity(elements_per_page * 4, GFP_KERN= EL)?; + /// v.push(1, GFP_KERNEL)?; + /// v.push(2, GFP_KERNEL)?; + /// + /// v.shrink_to(0, GFP_KERNEL)?; + /// # Ok::<(), Error>(()) + /// ``` + pub fn shrink_to(&mut self, min_capacity: usize, flags: Flags) -> Resu= lt<(), AllocError> { + let target_cap =3D core::cmp::max(self.len(), min_capacity); + + if self.capacity() <=3D target_cap { + return Ok(()); + } + + if Self::is_zst() { + return Ok(()); + } + + // Only shrink if we would free at least one page. + let current_size =3D self.capacity() * core::mem::size_of::(); + let target_size =3D target_cap * core::mem::size_of::(); + let current_pages =3D current_size.div_ceil(PAGE_SIZE); + let target_pages =3D target_size.div_ceil(PAGE_SIZE); + + if current_pages <=3D target_pages { + return Ok(()); + } + + if target_cap =3D=3D 0 { + if !self.layout.is_empty() { + // SAFETY: `self.ptr` was allocated with `KVmalloc`, layou= t matches. + unsafe { KVmalloc::free(self.ptr.cast(), self.layout.into(= )) }; + } + self.ptr =3D NonNull::dangling(); + self.layout =3D ArrayLayout::empty(); + return Ok(()); + } + + // SAFETY: `target_cap <=3D self.capacity()` and original capacity= was valid. + let new_layout =3D unsafe { ArrayLayout::::new_unchecked(target= _cap) }; + + // TODO: Once vrealloc supports in-place shrinking (mm/vmalloc.c:4= 316), this + // explicit alloc+copy+free can potentially be replaced with reall= oc. + let new_ptr =3D KVmalloc::alloc(new_layout.into(), flags, NumaNode= ::NO_NODE)?; + + // SAFETY: Both pointers are valid, non-overlapping, and properly = aligned. + unsafe { + ptr::copy_nonoverlapping(self.as_ptr(), new_ptr.as_ptr().cast:= :(), self.len); + } + + // SAFETY: `self.ptr` was allocated with `KVmalloc`, layout matche= s. + unsafe { KVmalloc::free(self.ptr.cast(), self.layout.into()) }; + + // SAFETY: `new_ptr` is non-null because `KVmalloc::alloc` succeed= ed. + self.ptr =3D unsafe { NonNull::new_unchecked(new_ptr.as_ptr().cast= ::()) }; + self.layout =3D new_layout; + + Ok(()) + } +} =20 impl Vec { /// Extend the vector by `n` clones of `value`. --=20 2.43.0 From nobody Sat Apr 18 01:59:18 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id D4AA21D61BC; Thu, 12 Feb 2026 08:25:29 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770884729; cv=none; b=XwFY9LxOi5yVagj7LjmPcDEsAV0t0uapijjxPTFAYfTply7L5ymXxeEmTuL11TShbEy4jiZmV7ZIqJaGzinvQdwFVjpH7M3LZo7ZrZsEVMXzbx50ha1wPETkIL2plAjCgMnetyzLtc+dAMTO+Beluw8yF3zl5Rbvit3rp4Pyf/4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770884729; c=relaxed/simple; bh=Nhuwb8Qlgw/27lqKry0LC8M8GZuoPjdo0qzwMJep4DY=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=cxVFjdeFxGAEtkhrfSE0Ej/Y5EFqvDNT73AolNAeH+9lmvQqljq9J/UzjxSPbXuWUtEvwgn9vGk3HzFdqa/tBWkJC2kRczzNiA31DCLOiur3vPE3sH/EAZunXSar6tTIlGnkKSkY5qjAZWG6k8RM5mq68Ifs0sNkW+BGSo6w2JM= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=N+DJ8f1m; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="N+DJ8f1m" Received: by smtp.kernel.org (Postfix) with ESMTPS id A5102C19424; Thu, 12 Feb 2026 08:25:29 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1770884729; bh=Nhuwb8Qlgw/27lqKry0LC8M8GZuoPjdo0qzwMJep4DY=; h=From:Date:Subject:References:In-Reply-To:To:Cc:Reply-To:From; b=N+DJ8f1mfzd+O+7QHJro0FqopHlwpWTeSLMeA5JxE7PIkIUl7GNgroQSamWudnc3T O9EX+vwtSJUmYGGbZ5GYwU3lwF19tDT+2+KXH/Pjn626YNVzBXEzSBL2lM/3rnfVZm ZA8YB58l+fg14+D6e0Ze3sfLb7O+URMmCpNN7r50y/Da2nyfZWPI74hTmSOvboidu7 P70N7Si3Sv70rcPv3tdFOf58fxyVJBuM1vBdneHYg26+jUdGv9hRhmzitz9N4dkvXI RTehYhTxb+aerP2p4JwIZ/hSYE5COBbJLw7YC0JN0Tr6DwS+JAgz90E6P4BkZIt5c9 EXbz59zDpvohg== Received: from aws-us-west-2-korg-lkml-1.web.codeaurora.org (localhost.localdomain [127.0.0.1]) by smtp.lore.kernel.org (Postfix) with ESMTP id 95605EDF05A; Thu, 12 Feb 2026 08:25:29 +0000 (UTC) From: Shivam Kalra via B4 Relay Date: Thu, 12 Feb 2026 13:47:08 +0530 Subject: [PATCH v4 2/3] rust: alloc: add KUnit tests for KVVec shrink_to Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260212-binder-shrink-vec-v3-v4-2-bd02f06bf2cd@zohomail.in> References: <20260212-binder-shrink-vec-v3-v4-0-bd02f06bf2cd@zohomail.in> In-Reply-To: <20260212-binder-shrink-vec-v3-v4-0-bd02f06bf2cd@zohomail.in> To: Danilo Krummrich , Lorenzo Stoakes , Vlastimil Babka , "Liam R. Howlett" , Uladzislau Rezki , Miguel Ojeda , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Greg Kroah-Hartman , =?utf-8?q?Arve_Hj=C3=B8nnev=C3=A5g?= , Todd Kjos , Christian Brauner , Carlos Llamas Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Shivam Kalra X-Mailer: b4 0.14.3 X-Developer-Signature: v=1; a=ed25519-sha256; t=1770884727; l=4784; i=shivamkalra98@zohomail.in; s=20260212; h=from:subject:message-id; bh=2QVEAhtM4EYkLAdeVfP5HSGd+aJKKYsshbr35ZHZtV8=; b=6/UvYjHgkd/gQqNE/CED2qqQ1s3tKidz79s7gC1vRIYMT0KgVhFjf6Fzz0S4dZKjbNT1bqvyA zZuEFu5bgU5D9tRG0no+6Q8JpB9QyHS3EYJw9Wn9INDeGxkVN6y2N6h X-Developer-Key: i=shivamkalra98@zohomail.in; a=ed25519; pk=9Q+S1LD/xjbjL7bEaLIlwRADBwU/6LJq7lYm8LFrkQE= X-Endpoint-Received: by B4 Relay for shivamkalra98@zohomail.in/20260212 with auth_id=633 X-Original-From: Shivam Kalra Reply-To: shivamkalra98@zohomail.in From: Shivam Kalra Add comprehensive KUnit tests for the shrink_to method for KVVec. The tests verify: - Basic shrinking from multiple pages to fewer pages with data integrity preservation - Empty vector shrinking to zero capacity - No-op behavior when shrinking to a larger capacity than current - Respect for min_capacity parameter when larger than vector length These tests ensure that the shrinking logic correctly identifies when memory can be reclaimed (by freeing at least one page) and that data integrity is maintained throughout shrink operations. Signed-off-by: Shivam Kalra --- rust/kernel/alloc/kvec.rs | 112 ++++++++++++++++++++++++++++++++++++++++++= ++++ 1 file changed, 112 insertions(+) diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs index 8524f9f3dff0..d28f8fccd30f 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -1474,4 +1474,116 @@ fn add(value: &mut [bool]) { func.push_within_capacity(false).unwrap(); } } + + #[test] + fn test_kvvec_shrink_to() { + use crate::page::PAGE_SIZE; + + // Calculate elements per page for u32. + let elements_per_page =3D PAGE_SIZE / core::mem::size_of::(); + + // Create a vector with capacity spanning multiple pages. + let mut v =3D KVVec::::with_capacity(elements_per_page * 4, G= FP_KERNEL).unwrap(); + + // Add a few elements. + v.push(1, GFP_KERNEL).unwrap(); + v.push(2, GFP_KERNEL).unwrap(); + v.push(3, GFP_KERNEL).unwrap(); + + let initial_capacity =3D v.capacity(); + assert!(initial_capacity >=3D elements_per_page * 4); + + // Shrink to a capacity that would free at least one page. + v.shrink_to(elements_per_page, GFP_KERNEL).unwrap(); + + // Capacity should have been reduced. + assert!(v.capacity() < initial_capacity); + assert!(v.capacity() >=3D elements_per_page); + + // Elements should be preserved. + assert_eq!(v.len(), 3); + assert_eq!(v[0], 1); + assert_eq!(v[1], 2); + assert_eq!(v[2], 3); + + // Shrink to zero (should shrink to len). + v.shrink_to(0, GFP_KERNEL).unwrap(); + + // Capacity should be at least the length. + assert!(v.capacity() >=3D v.len()); + + // Elements should still be preserved. + assert_eq!(v.len(), 3); + assert_eq!(v[0], 1); + assert_eq!(v[1], 2); + assert_eq!(v[2], 3); + } + + #[test] + fn test_kvvec_shrink_to_empty() { + use crate::page::PAGE_SIZE; + + let elements_per_page =3D PAGE_SIZE / core::mem::size_of::(); + + // Create a vector with large capacity but no elements. + let mut v =3D KVVec::::with_capacity(elements_per_page * 4, G= FP_KERNEL).unwrap(); + + assert!(v.is_empty()); + let initial_capacity =3D v.capacity(); + + // Shrink empty vector to zero. + v.shrink_to(0, GFP_KERNEL).unwrap(); + + // Should have freed the allocation. + assert!(v.capacity() < initial_capacity); + assert!(v.is_empty()); + } + + #[test] + fn test_kvvec_shrink_to_no_op() { + use crate::page::PAGE_SIZE; + + let elements_per_page =3D PAGE_SIZE / core::mem::size_of::(); + + // Create a small vector. + let mut v =3D KVVec::::with_capacity(elements_per_page, GFP_K= ERNEL).unwrap(); + v.push(1, GFP_KERNEL).unwrap(); + + let capacity_before =3D v.capacity(); + + // Try to shrink to a capacity larger than current - should be no-= op. + v.shrink_to(capacity_before + 100, GFP_KERNEL).unwrap(); + + assert_eq!(v.capacity(), capacity_before); + assert_eq!(v.len(), 1); + assert_eq!(v[0], 1); + } + + #[test] + fn test_kvvec_shrink_to_respects_min_capacity() { + use crate::page::PAGE_SIZE; + + let elements_per_page =3D PAGE_SIZE / core::mem::size_of::(); + + // Create a vector with large capacity. + let mut v =3D KVVec::::with_capacity(elements_per_page * 4, G= FP_KERNEL).unwrap(); + + // Add some elements. + for i in 0..10 { + v.push(i, GFP_KERNEL).unwrap(); + } + + // Shrink to a min_capacity larger than length. + let min_cap =3D elements_per_page * 2; + v.shrink_to(min_cap, GFP_KERNEL).unwrap(); + + // Capacity should be at least min_capacity. + assert!(v.capacity() >=3D min_cap); + + // All elements preserved. + assert_eq!(v.len(), 10); + for i in 0..10 { + assert_eq!(v[i as usize], i); + } + } } --=20 2.43.0 From nobody Sat Apr 18 01:59:18 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E460C23F424; Thu, 12 Feb 2026 08:25:29 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770884730; cv=none; b=MVshdGLwWkjurcYzIBzwm8T6+ZSC2lFOeP3sYp3JCU6eU9P3OAGYXprGQpJVk8+F2xA17DBtuQnI76BeqXcvmoq76zi5qZ8Ru3Y17dd4VeQS/dKP9E8Rghtahl02K6oAf3CLdSaRv18PCddjzlM+sHGXGFCZyUgg9vEzur5Bkn4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1770884730; c=relaxed/simple; bh=nWOQOPNlF2NKalrXxoDvWR77eWVnEKgX2SJPRdaxPMc=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=L70R9eP3lYeJCP9UxEmx+BpJ/phzHT0GX1ExzXqlrtTd1uqJT9A7U6fzi7Wz+GeXu8MBTWCl4yn+0qZEvCRK5GnIonxKjQOb8L6alIFKMGAygX1f+iukMdyeyO8byXnNaXcU3teSPdHk+9ShKujN4qoy6pZsfctw/0LNNCiDwOo= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=LMs4PCpB; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="LMs4PCpB" Received: by smtp.kernel.org (Postfix) with ESMTPS id BED89C2BCB0; Thu, 12 Feb 2026 08:25:29 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1770884729; bh=nWOQOPNlF2NKalrXxoDvWR77eWVnEKgX2SJPRdaxPMc=; h=From:Date:Subject:References:In-Reply-To:To:Cc:Reply-To:From; b=LMs4PCpBElB98lsfw3EN9PlVqhkdTQaz1VkqtXXsbF99QG16ghQ2G439gtFfHMP3J y71eXAJzoNKni+vjWkGM7KoBc92O/LkqO3NDTi/Z2ExEdczlCi91LQUPi1UQX46PzY 9SW29EC/u8y4/p050ck9hWTiuSNe5R/Stw4+jk3EjR5dCianD8UOb2LxpP0/nBSo5+ LkVoJOZFb9LRbCRskCpBMhcaNjXA9xbgqJCGX0IjPvAbwyeMgCT/E7bXaLGvmYEl1d 1Xk+Ie8MWoW3SxbOTrMBr3NOp6W95dGI73UuhkdyeeI8Iq+ulyOb94KKEW6xrtZ/QT WWKfm3IuTBDHw== Received: from aws-us-west-2-korg-lkml-1.web.codeaurora.org (localhost.localdomain [127.0.0.1]) by smtp.lore.kernel.org (Postfix) with ESMTP id B1839EDF058; Thu, 12 Feb 2026 08:25:29 +0000 (UTC) From: Shivam Kalra via B4 Relay Date: Thu, 12 Feb 2026 13:47:09 +0530 Subject: [PATCH v4 3/3] rust_binder: shrink all_procs when deregistering processes Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260212-binder-shrink-vec-v3-v4-3-bd02f06bf2cd@zohomail.in> References: <20260212-binder-shrink-vec-v3-v4-0-bd02f06bf2cd@zohomail.in> In-Reply-To: <20260212-binder-shrink-vec-v3-v4-0-bd02f06bf2cd@zohomail.in> To: Danilo Krummrich , Lorenzo Stoakes , Vlastimil Babka , "Liam R. Howlett" , Uladzislau Rezki , Miguel Ojeda , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Greg Kroah-Hartman , =?utf-8?q?Arve_Hj=C3=B8nnev=C3=A5g?= , Todd Kjos , Christian Brauner , Carlos Llamas Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Shivam Kalra X-Mailer: b4 0.14.3 X-Developer-Signature: v=1; a=ed25519-sha256; t=1770884727; l=2022; i=shivamkalra98@zohomail.in; s=20260212; h=from:subject:message-id; bh=ofWhi1ML9enjnPcwalc0CgCX2PLEBs7iFFyc8twE/GY=; b=T+06K77mrVOTOH6io1OMTpMjZQldVsZxOxg3z5IVqorzVVHDHS8u/IV7Sp18h/0dGAlv8I11k /Lu8sZySgDdBpZ4Zb4KLcmLmCwuVb+x3eSIGRfuPCKYwG6n4/x+F3nk X-Developer-Key: i=shivamkalra98@zohomail.in; a=ed25519; pk=9Q+S1LD/xjbjL7bEaLIlwRADBwU/6LJq7lYm8LFrkQE= X-Endpoint-Received: by B4 Relay for shivamkalra98@zohomail.in/20260212 with auth_id=633 X-Original-From: Shivam Kalra Reply-To: shivamkalra98@zohomail.in From: Shivam Kalra When a process is deregistered from the binder context, the all_procs vector may have significant unused capacity. Add logic to shrink the vector using a conservative strategy that prevents shrink-then-regrow oscillation. The shrinking strategy triggers when length drops below 1/4 of capacity, and shrinks to 1/2 of capacity rather than to the exact length. This provides hysteresis to avoid repeated reallocations when the process count fluctuates. The shrink operation uses GFP_KERNEL and is allowed to fail gracefully since it is purely an optimization. The vector remains valid and functional even if shrinking fails. Suggested-by: Alice Ryhl Signed-off-by: Shivam Kalra --- drivers/android/binder/context.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/drivers/android/binder/context.rs b/drivers/android/binder/con= text.rs index 9cf437c025a20..399dab475728b 100644 --- a/drivers/android/binder/context.rs +++ b/drivers/android/binder/context.rs @@ -94,6 +94,17 @@ pub(crate) fn deregister_process(self: &Arc, proc:= &Arc) { } let mut manager =3D self.manager.lock(); manager.all_procs.retain(|p| !Arc::ptr_eq(p, proc)); + + // Shrink the vector if it has significant unused capacity to avoi= d memory waste, + // but use a conservative strategy to prevent shrink-then-regrow o= scillation. + // Only shrink when length drops below 1/4 of capacity, and shrink= to 1/2 capacity. + let len =3D manager.all_procs.len(); + let cap =3D manager.all_procs.capacity(); + if len < cap / 4 { + // Shrink to half capacity. Ignore allocation failures since t= his is just an + // optimization; the vector remains valid even if shrinking fa= ils. + let _ =3D manager.all_procs.shrink_to(cap / 2, GFP_KERNEL); + } } =20 pub(crate) fn set_manager_node(&self, node_ref: NodeRef) -> Result { --=20 2.43.0