From mboxrd@z Thu Jan 1 00:00:00 1970 Authentication-Results: smtp.subspace.kernel.org; arc=pass header.oldest-pass=0 smtp.remote-ip=52.101.95.120 ARC-Seal: i=2; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=pass; t=1796227125; b=Lmd0JCmo2P+7UCjrQXV0pD2Liz+TNZfMy74AdziKDlt61BWjMilfSB4wd6iSLIMY9ai4 iInU+3BrU/uZtf9whSoMRcalUQOiftoMNLv6gEqe3RwBGU+JvFmDRzaNKMn3WKf9tqORm lU5FX/EJo3EQPzKykS4ou/9+8AyyfWBvOPQuBRWO3xGmIcDzyw9YTiAXPxlQwbs2huSSS XUztObBkyjvvyoOnxxPTaTy0Q13Zn1RAuDOUovcCCMi6WY9wRuid3viZv7oxBIHuDCnKA kpWW36O4UsAjyPvuAPbEKoACKSC8DCLOBlCnUNKszxDCLSnZK3Ez6uoAK7WsUuX7x+Q== ARC-Message-Signature: i=2; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796227125; h=DMARC-Filter:DKIM-Signature:Received:Received: Content-Transfer-Encoding:Content-Type:Date:Message-Id:Cc:Subject: From:To:X-Mailer:References:In-Reply-To:X-ClientProxiedBy: MIME-Version:X-MS-PublicTrafficType:X-MS-TrafficTypeDiagnostic: X-MS-Office365-Filtering-Correlation-Id:X-MS-Exchange-SenderADCheck: X-MS-Exchange-AntiSpam-Relay:X-Microsoft-Antispam: X-Microsoft-Antispam-Message-Info:X-Forefront-Antispam-Report: X-MS-Exchange-AntiSpam-MessageData-ChunkCount: X-MS-Exchange-AntiSpam-MessageData-0:X-OriginatorOrg: X-MS-Exchange-CrossTenant-Network-Message-Id: X-MS-Exchange-CrossTenant-AuthSource:X-MS-Exchange-CrossTenant-AuthAs: X-MS-Exchange-CrossTenant-OriginalArrivalTime: X-MS-Exchange-CrossTenant-FromEntityHeader: X-MS-Exchange-CrossTenant-Id:X-MS-Exchange-CrossTenant-MailboxType: X-MS-Exchange-CrossTenant-UserPrincipalName: X-MS-Exchange-Transport-CrossTenantHeadersStamped; bh=lGt4vHzDQv5crnRiQuirKxeQ0ng2IBVMApihO2EYJnU=; b=hSOE6Xh3RQKD/5ToiaJ1xsHygQDSxs84jOb1xJ7ue1xzzKPhA+5EB18pEb/SdkQNoQts Uu+yI94sGRHoeoN4ma9yBdzlknNI6H8BirGqDqhw4QvVIBh7QdpnHjfkf7MY6KWs94JfO xpReX9n3HxfdxpX+uI/VfLeFuJwuRXtWHJBfWuKNhRir9NX8u57C5cLmVbe3P74XSQlgy O8DyHRcsAJjqhRn1lZN/+/i+UpSx5IWlww5tL2zFy9bIu4Dvy+T0tcO9GdlUmueIQI2PY /g0uez2lgfCUtQLCO55Gg7GjECRLfWVM3F4sDKxOI17nVDR/j8qr+cZ+XexbLTiAdSQ== ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass header.from=garyguo.net; spf=pass smtp.mailfrom=garyguo.net; dkim=pass header.d=garyguo.net header.i=@garyguo.net header.a=rsa-sha256 header.s=selector1 header.b=IvmMO041; arc=pass header.oldest-pass=0 smtp.remote-ip=52.101.95.120 Received: from LO2P265CU024.outbound.protection.outlook.com (mail-uksouthazon11021120.outbound.protection.outlook.com [52.101.95.120]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange ECDHE (secp384r1) server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 71B82606A322; Wed, 2 Dec 2026 15:58:43 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 71B82606A322 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=garyguo.net Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key, unprotected) header.d=garyguo.net header.i=@garyguo.net header.a=rsa-sha256 header.s=selector1 header.b=IvmMO041 ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=PLSBQ8D2Xl7GigqnadGqtqBI4R+KmWeMy04lrUWbccPMza29KjN3D75z2v4qgjgy/Y2ukcE7c+rfAA5gIULjHAsNiirLgUf7IMv7n6chJNkOB6Fq1uG4ZoXpra9xtASfJpr/Rp9pBZs6YCggoVycMDu5pWS1FOHowLnPLCBSeLYUH1JoY9MVWcJxvyWwvuFWo9UbzWURxCD1v0S+yemn0oUIPHIg6m4Gzr5YL01XGOaDIXP9j0f3jNTuYBmRaNiZ4eJ2samM3xlkkWA9zbnQ38KjJAXG+BguQuAr8/297ytOzw6cdtNjw0C9rBsyQpdyKsh26cB9P/s64rVEptLozg== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=microsoft.com; s=arcselector10001; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-AntiSpam-MessageData-ChunkCount:X-MS-Exchange-AntiSpam-MessageData-0:X-MS-Exchange-AntiSpam-MessageData-1; bh=lGt4vHzDQv5crnRiQuirKxeQ0ng2IBVMApihO2EYJnU=; b=vWLPoyk4xUhXVLGwZI48Zg300L46gKkyzRv6GsQZkFhsRCls3KyP/Wf/5j4pLxHywcscV/+iO/8Z44GuMN0Y9c2c1GDy6aPXJ+nFHI8dR8cAsvK0twr64Kbt52dTofPf+QM1LILTCPecv1bDwE4qZDA7HCEM+fvpXftp/jkIVlLU+Of4PpAeX96OGnxR9uXUbNAJQHSXYStyIKUL73OlEQOAFjSHjxfx0RVnDsgn+3ZjWAEAcZmXIE6bGLkrH1/28vUJcc/aK+ytIghEyZAvAb2Hbc8TRTiONKiCbtTQSYHvP6X/l8b8prqJQprOdwy2hNoYxTildzaqalVpE9Futw== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=garyguo.net; dmarc=pass action=none header.from=garyguo.net; dkim=pass header.d=garyguo.net; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=garyguo.net; s=selector1; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=lGt4vHzDQv5crnRiQuirKxeQ0ng2IBVMApihO2EYJnU=; b=IvmMO0413CKhrHSWBphZ+MsmKWdu89OvzdqxukDEe3vdWsaPU/GjspiyDBOFnUTSwJKMLrGAt+YNAQLV2OttwaUux7K5jZ3REHYM9u9dr5VsoL9wfOvrbb30/VTcB/3hYmiKH1F4evKrO+vWWLteBFEjj22mdbJbv1HYAQa6XRc= Authentication-Results: mx.microsoft.com 1; dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=garyguo.net; Received: from CWLP265MB6051.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:1cb::9) by LO2P265MB2814.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:178::11) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.688.11; Wed, 2 Dec 2026 15:58:38 +0000 Received: from CWLP265MB6051.GBRP265.PROD.OUTLOOK.COM ([fe80::55f6:f98b:7fad:c6e3]) by CWLP265MB6051.GBRP265.PROD.OUTLOOK.COM ([fe80::55f6:f98b:7fad:c6e3%2]) with mapi id 15.21.0688.009; Wed, 2 Dec 2026 15:58:38 +0000 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset=UTF-8 Date: Wed, 02 Dec 2026 15:58:37 +0000 Message-Id: Cc: "Zhi Wang" , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , "Liam R. Howlett" , , "Lorenzo Stoakes" Subject: Re: [PATCH v4 1/5] rust: vfio: add common VFIO device handling From: "Gary Guo" To: "Simon Song" , , , , , , X-Mailer: aerc 0.22.0 References: <20261127224928.1511382-1-xinmengs@nvidia.com> <20261127224928.1511382-2-xinmengs@nvidia.com> In-Reply-To: <20261127224928.1511382-2-xinmengs@nvidia.com> X-ClientProxiedBy: LO6P265CA0026.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:2ff::16) To CWLP265MB6051.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:1cb::9) X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 X-MS-PublicTrafficType: Email X-MS-TrafficTypeDiagnostic: CWLP265MB6051:EE_|LO2P265MB2814:EE_ X-MS-Office365-Filtering-Correlation-Id: 3b3a485e-efe3-42df-cbc3-08df508d20f8 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|1800799024|376014|10070799003|7416014|23010399003|366016|4143699003|5023799004|6133799003|261009223027099003|22082099003|18002099003|10067099003|56012099006|261102123227099003|261026121527099003|261026140227099003|261022105027099003|261022075727099003|261021123027099003|261021121427099003|261028144727099003; X-Microsoft-Antispam-Message-Info: batty1DIm+rLcmzmE4LMq+WroQtQIAzZymuBd9DHmnLRjjuICkgD/yNIN78d/FQn0OcxBcW8kJlmbLZFe+Og627VuMYLZ0kvIQDmVP0ZOy/wcry30Co4h03RjCeFTUN/csZKR2lcRGTw4XhBa4ew9sUkmCaDc63oIcmZ0/v3cBziOQBE9aYNK1gbSU5xj/hgiC3bHw0etGs0Lnnz2jk9542jt+QZPz+mrniPpvpiF4ac54yzjS2xgHBWHCmY83ZuG3+mGxoXPR9SG9MOnZxsl/h61+TsiHS1NMG8MNcsyrk+2j/vEZu6uJY/qvRTaCVz8CEtJkozpFiAyvYO/h5T31UiwFFXihSCA39YIakxC5RhrUJNMAz6IdRtUDnCHJzjKjx9HZaS/wTycSmW5cAHQ6EiszctPz0IUXcd5oiS8oUEF0+bEPGuZpBWvYxgQTa6arMzvWB4ebXphuWBlupOeWqlc/fN90Us/h3Fra2oX/ygtQfE1v8/z7JBFJhMNET9UeU6JiL/yeRp/6MHNrBc/lwHTtgGYIT7f9a8tvNO75vsgcqw7unfrx3jeBF2Upu44m6Cu6MDtpRwRZyiEjcqmAx7SYrwXWzADiwjp4X4eqfzyB8GnqDae37whX+kh3f0UQGCe95z9jWOwY0szv4ijykuYAwSBQD3WgKNAWlR9sY= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:CWLP265MB6051.GBRP265.PROD.OUTLOOK.COM;PTR:;CAT:NONE;SFS:(13230040)(1800799024)(376014)(10070799003)(7416014)(23010399003)(366016)(4143699003)(5023799004)(6133799003)(261009223027099003)(22082099003)(18002099003)(10067099003)(56012099006)(261102123227099003)(261026121527099003)(261026140227099003)(261022105027099003)(261022075727099003)(261021123027099003)(261021121427099003)(261028144727099003);DIR:OUT;SFP:1102; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?elN1SWJLYU81U2k1ZkJ3K3BlaEZGM0JBUnlsMHdYVG5jRU5OUWNKMGNPUXp1?= =?utf-8?B?S3k4UHloT1NML054WjBvbVZXNkJSa0EzSFQwMEJHcTg3dVpVckQ1TW9VNi8y?= =?utf-8?B?SXUyOUNIRDVxMkxyN29Iei9SbGFiNERyZC9RSXE3YnhjRXZtOEpLZHRFUmVs?= =?utf-8?B?RThCOTNpNjJ1VWMvVGpLMlYrenZHSngyRHVhdU5mVlk2Y1JiSFJ2NFYzZ1Vx?= =?utf-8?B?aTlBRlpPMHVrUEFjMGpYU2dRQ2FyQmRsS25Mb1ZDUlcxQ2R4WVdvSXNkUjhK?= =?utf-8?B?RzlJWnJWRzRnemtlRGxuZ3FvMUVlaHV4ZzRrMCtYc0NEam5JTnJudE8vWHhH?= =?utf-8?B?VkgzSWhYakhydzhGTG5URXdxR1F2bXlYUFlYZmR2Zk9ZUWc1eEx1a1poRmY1?= =?utf-8?B?NGlZWnQzUThJcnpwVjFuOWtLSy9oSUg2VVhkYTl5UjRyREI4VUxOeHFnYnBH?= =?utf-8?B?Y2hWMm84Z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f-8?B?Y0hZNncrczlkdVlJUHVMaG9XRnlKY0pBdkh2RUE3SEk1ZUwrUVBVUT09?= X-OriginatorOrg: garyguo.net X-MS-Exchange-CrossTenant-Network-Message-Id: 3b3a485e-efe3-42df-cbc3-08df508d20f8 X-MS-Exchange-CrossTenant-AuthSource: CWLP265MB6051.GBRP265.PROD.OUTLOOK.COM X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 02 Dec 2026 15:58:38.6148 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: bbc898ad-b10f-4e10-8552-d9377b823d45 X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: Y/8H6vzOf1xgqsAED3wYDTG+jLRd5Qvhv+mcEsORai8CElKfxsr/wcDOaWsUuzBg4B5oSGs3Oj+r+B+mUPGltw== X-MS-Exchange-Transport-CrossTenantHeadersStamped: LO2P265MB2814 On Fri Nov 27, 2026 at 10:49 PM GMT, Simon Song wrote: > From: Zhi Wang > > A VFIO PCI device contains a VFIO device. Expose that relationship in > Rust so common device handling is independent of PCI resources. > > Add vfio::DeviceBase, a C VFIO device structure followed by pointers to > callback data, and vfio::Device, its alias for struct vfio_device. The > data is registration data and data kept from the first successful open > until the last close, which can borrow the former. Share reference > counting and callback-data lifetime handling in vfio. > > The helpers are unused until the next patch adds the PCI abstraction. > > Signed-off-by: Zhi Wang > Signed-off-by: Simon Song > --- > rust/bindings/bindings_helper.h | 2 + > rust/kernel/lib.rs | 2 + > rust/kernel/vfio.rs | 454 ++++++++++++++++++++++++++++++++ I'd prefer this to be placed in vfio/mod.rs so it's in the same directory a= s vfio/pci.rs. > 3 files changed, 458 insertions(+) > create mode 100644 rust/kernel/vfio.rs > > diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_hel= per.h > index 3791af0aadc73..a5781bc1ea85f 100644 > --- a/rust/bindings/bindings_helper.h > +++ b/rust/bindings/bindings_helper.h > @@ -93,6 +93,7 @@ > #include > #include > #include > +#include > #include > #include > #include > @@ -115,6 +116,7 @@ > const size_t RUST_CONST_HELPER_ARCH_SLAB_MINALIGN =3D ARCH_SLAB_MINALIGN= ; > const size_t RUST_CONST_HELPER_ARCH_KMALLOC_MINALIGN =3D ARCH_KMALLOC_MI= NALIGN; > const size_t RUST_CONST_HELPER_PAGE_SIZE =3D PAGE_SIZE; > +const unsigned int RUST_CONST_HELPER_VFIO_DEVICE_RESET =3D VFIO_DEVICE_R= ESET; > const size_t RUST_CONST_HELPER_GENLMSG_DEFAULT_SIZE =3D GENLMSG_DEFAULT_= SIZE; > const gfp_t RUST_CONST_HELPER_GFP_ATOMIC =3D GFP_ATOMIC; > const gfp_t RUST_CONST_HELPER_GFP_KERNEL =3D GFP_KERNEL; > diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs > index f7f720b9888a4..9f7789ce0db43 100644 > --- a/rust/kernel/lib.rs > +++ b/rust/kernel/lib.rs > @@ -150,6 +150,8 @@ > pub mod uaccess; > #[cfg(CONFIG_USB =3D "y")] > pub mod usb; > +#[cfg(CONFIG_VFIO =3D "y")] > +pub mod vfio; > pub mod workqueue; > pub mod xarray; > =20 > diff --git a/rust/kernel/vfio.rs b/rust/kernel/vfio.rs > new file mode 100644 > index 0000000000000..f49ff5931df56 > --- /dev/null > +++ b/rust/kernel/vfio.rs > @@ -0,0 +1,454 @@ > +// SPDX-License-Identifier: GPL-2.0 > + > +//! Virtual Function I/O (VFIO) devices and callback data. > +//! > +//! `DeviceBase` combines a C VFIO device structure with the data its ca= llbacks use. > +//! [`Device`] is an alias of it for `struct vfio_device`. `DeviceBase` is mentioned here in public-facing documentation while the typ= e itself is hidden. > +//! > +//! C header: [`include/linux/vfio.h`](srctree/include/linux/vfio.h) > + > +use crate::{ > + bindings, > + prelude::*, > + sync::aref::AlwaysRefCounted, > + types::{ > + ForeignOwnable, > + NotThreadSafe, > + Opaque, // > + }, > + uaccess::{ > + UserPtr, > + UserSlice, // > + }, // > +}; > +use core::{ > + cell::UnsafeCell, > + marker::PhantomData, > + ops::Range, > + ptr::NonNull, // > +}; > + > +/// Reset the VFIO device. > +pub const DEVICE_RESET: u32 =3D bindings::VFIO_DEVICE_RESET; > + > +/// The context in which a VFIO device reference is valid. > +/// > +/// Callback views can only be borrowed from the corresponding VFIO tram= poline. > +/// They cannot be refcounted or shared across threads. > +pub trait DeviceContext: private::Sealed {} > + > +/// A callback context in which VFIO keeps the device open. > +/// > +/// Registration data and open data are available throughout such a call= back. > +pub trait IoContext: DeviceContext {} > + > +/// An ordinary device reference, without callback-specific operations. > +pub struct Normal; > + > +/// The device is undergoing its exclusive first-open callback. > +pub struct Open; > + > +/// The device is borrowed for a VFIO ioctl callback on the current thre= ad. > +pub struct Ioctl; > + > +/// The device is borrowed for a VFIO read callback on the current threa= d. > +pub struct Read; > + > +/// The device is borrowed for a VFIO write callback on the current thre= ad. > +pub struct Write; > + > +/// The device is borrowed for a VFIO mmap callback on the current threa= d. > +pub struct Mmap; > + > +/// The device is borrowed for a VFIO region-info callback on the curren= t thread. > +pub struct GetRegionInfo; That's a lot of type states. It looks like all of these are only used to en= sure only corresponding vfio_pci_core callbacks can be delegated to. Are these r= eally needed for soundness? I can understand that the `Open` one might be needed,= but the rest might be mergeable? > + > +mod private { > + pub trait Sealed {} > + > + impl Sealed for super::Normal {} > + impl Sealed for super::Open {} > + impl Sealed for super::Write {} > + impl Sealed for super::Mmap {} > + impl Sealed for super::Ioctl {} > + impl Sealed for super::Read {} > + impl Sealed for super::GetRegionInfo {} > +} > + > +impl DeviceContext for Normal {} > +impl DeviceContext for Open {} > +impl DeviceContext for Write {} > +impl DeviceContext for Mmap {} > +impl DeviceContext for Ioctl {} > +impl DeviceContext for Read {} > +impl DeviceContext for GetRegionInfo {} > + > +impl IoContext for Write {} > +impl IoContext for Mmap {} > +impl IoContext for Ioctl {} > +impl IoContext for Read {} > +impl IoContext for GetRegionInfo {} > + > +/// The data the driver of a [`Device`] shares with its callbacks. > +/// > +/// Bus-specific operations traits extend this trait. > +pub trait Operations: Sized + Send + Sync + 'static { > + /// Data owned by the registration and passed to VFIO callbacks. > + /// > + /// It can borrow resources of the driver's binding for `'reg`. Per-= device state lives here. > + type RegistrationData<'reg>: Send + Sync + 'reg; > + > + /// Data shared by callbacks from the first successful open until th= e last close. > + /// > + /// It can borrow the registration data, of lifetime `'reg`, for `'o= pen`. > + type OpenData<'open, 'reg: 'open>: Send + Sync + 'open; The lifetime here is confusing. `'open` is actually the lifetime borrowed f= rom `'reg`, and the `'reg` is lifetime borrowed (usually) from the device. > +} > + > +/// Callback data stored after the C device structure. > +/// > +/// The registration data and the open data of `T` are both written with= the placeholder > +/// lifetime `'static`, because the device has no lifetime to name. > +/// > +/// # Invariants > +/// > +/// `reg_data` is `None` until a registration publishes its data, and is= not changed again. The > +/// data is pinned and remains valid while the device is registered. Aft= er unregistration or a > +/// failed registration attempt, the pointer may dangle; its pointee mus= t never again be > +/// accessed through this device. > +/// `open_data` is `None` outside a successful first open, otherwise it = owns a pinned allocation > +/// until the last close. The bus-specific layer drains callbacks before= either is released. > +struct CallbackData { > + reg_data: UnsafeCell>>>, > + open_data: UnsafeCell>>= >, > +} > + > +/// A C VFIO device structure `Raw`, followed by the callback data of th= e driver `T`. > +/// > +/// `raw` is the first field, so the `vfio_device` at the beginning of `= Raw` is also at the > +/// beginning of `Self`, as `vfio_alloc_device()` requires. > +/// > +/// Use the alias [`Device`]. > +/// > +/// # Invariants > +/// > +/// - `Raw` is a C structure that begins with its `struct vfio_device`. > +/// - The data stored is only valid as described for `CallbackData`. > +/// - `raw` is initialized and remains alive while borrowed. The referen= ce count of its embedded > +/// `vfio_device` owns the allocation. > +/// - For [`Open`] and [`IoContext`] references, registration data is pu= blished and remains > +/// valid for the reference's lifetime. > +#[doc(hidden)] > +#[repr(C)] > +pub struct DeviceBase= { > + raw: Opaque, > + data: CallbackData, > + _context: PhantomData<(T, Ctx, NotThreadSafe)>, > +} > + > +/// A VFIO device, wrapping `struct vfio_device`. > +pub type Device =3D DeviceBase; > + > +#[expect(dead_code)] > +impl DeviceBase { > + /// Initializes the Rust fields of a newly allocated device. > + /// > + /// # Safety > + /// > + /// `this` must point to an allocation with the size and alignment o= f `Self`, whose `raw` > + /// has been initialized. `Raw` must be a C structure that begins wi= th its > + /// `struct vfio_device`. Nothing else may access the allocation dur= ing this call. > + unsafe fn init(this: *mut Self) { > + // SAFETY: The caller provides exclusive access to a suitable al= location. > + // INVARIANT: No data is published, and no open data exists. > + unsafe { > + (&raw mut (*this).data).write(CallbackData { > + reg_data: UnsafeCell::new(None), > + open_data: UnsafeCell::new(None), > + }) > + }; > + // SAFETY: By the same reasoning above, `_context` can be writte= n. > + unsafe { (&raw mut (*this)._context).write(PhantomData) }; > + } > + > + /// Recovers `&Self` from the `vfio_device` VFIO passes to a callbac= k. > + /// > + /// # Safety > + /// > + /// `vdev` must point to the `vfio_device` at the beginning of a `Se= lf` that remains alive > + /// for `'a`. The caller must provide the guarantees of `Ctx` throug= hout the borrow. > + unsafe fn from_raw_vfio<'a>(vdev: *mut bindings::vfio_device) -> &'a= Self { > + // SAFETY: By the type invariants, `Raw` begins with its `vfio_d= evice`, and `raw` is the > + // first field of `Self`. The caller guarantees validity. > + // INVARIANT: The caller provides the guarantees of `Ctx`. > + unsafe { &*vdev.cast() } > + } > + > + fn as_raw(&self) -> *mut Raw { > + self.raw.get() > + } > + > + fn as_raw_vfio(&self) -> *mut bindings::vfio_device { > + // By the type invariants, `Raw` begins with its `vfio_device`. > + self.as_raw().cast() > + } > +} > + > +#[expect(dead_code)] > +impl DeviceBase { > + /// Publishes the registration data passed to callbacks. > + /// > + /// Returns [`EBUSY`] if registration data has been published before= , so that a device can > + /// be registered at most once. > + /// > + /// # Safety > + /// > + /// The caller must serialize calls for this device. `data` must poi= nt to pinned data that > + /// remains valid until the device has been unregistered or, if regi= stration fails, is not > + /// accessed through this device. > + unsafe fn publish_registration_data<'reg>( > + &self, > + data: NonNull>, > + ) -> Result { > + // SAFETY: The caller serializes publication, and callbacks only= read the slot. > + if unsafe { (*self.data.reg_data.get()).is_some() } { > + return Err(EBUSY); > + } This looks quite strange. I believe this is only here so you can never call `Registration::new()` twi= ce. But this raises the question on why you'd want the user to create the devic= e first before giving it to the registration. I think this should be one of the either approach: - Never allow user to create the device directly. Create it inside registra= tion and expose it to the user via registration only. - (drm approach) If there're some configuration needed on the device before registering, create a `UnregisteredDevice` (or `UnpublishedRegistration`) type. It is then converted to a `Registration`. Basically, here you're creating a runtime failure path that is ALWAYS a bug= . [ Both the suggested approach above should eventually allow getting rid of= the `RegistrationData` associated type. You can have the type implementing `Operations` itself becoming the type for RegistrationData, so you'd do #[pin_data] struct NovaVgpuReg<'a> { pdev: &'a pci::Device, vgpu: Option>, fb_bar: Option, #[pin] state: Mutex, #[pin] reset_done: CondVar, } // I picked vfio::Driver not vfio::Operations to align with other class // devices. // If you have any specific reason to pick Operations let me know. impl<'a> vfio::Driver for NovaVgpuReg<'a> { // Note that the bound becomes an conventional `Self: 'lt` bound. type OpenData<'open> =3D NovaVgpuOpenData<'open, 'a> where Self: 'o= pen; } impl<'a> vfio::pci::Driver for NovaVgpuReg<'a> { ... } // Construction vfio::pci::Registration::new( pdev, try_pin_init!(NovaVgpuReg { ... }) ) But I think this is currently not possible due to some limitation due to 's= tatic bounds. Probably I should introduce an unsafe lifetime-erasing feature in pin-init so people stop using `'static` to mean erased lifetimes. ] > + // SAFETY: The slot is unpublished, so the device has not been r= egistered and no > + // callback can read the slot. > + // INVARIANT: The slot is written once; the caller keeps `data` = valid. > + unsafe { *self.data.reg_data.get() =3D Some(data.cast()) }; > + Ok(()) > + } > + > + /// Destroys the open data. > + /// > + /// # Safety > + /// > + /// Call once after a successful [`DeviceBase::open`], with all I/O = callbacks drained and > + /// the next first open excluded. Registration data and the resource= s the open data borrows > + /// must remain alive. > + unsafe fn close(&self) { > + // SAFETY: The last close exclusively takes the allocation publi= shed by `open()`. > + let raw =3D unsafe { &mut *self.data.open_data.get() } > + .take() > + .expect("VFIO OpenData is expected to be populated."); > + // SAFETY: `raw` came from `into_foreign()` in `open()` and is n= ot used again. The > + // allocation is destroyed without moving it. > + drop(unsafe { > + >>>::from_foreign(raw= .as_ptr().cast()) > + }); > + } > +} > + > +#[expect(dead_code)] > +impl DeviceBase { > + /// Creates the open data from the registration data. > + /// > + /// The [`Open`] context guarantees an exclusive first open of a reg= istered device, whose > + /// registration data remains valid until the last close. > + /// > + /// # Safety > + /// > + /// - No open data may exist. > + /// - The caller chooses `'a` and `'reg`; this function cannot tie e= ither to the time the > + /// data is valid. `init` must therefore use the registration data= parametrically, as a > + /// function generic over its lifetimes does: nothing borrowed fro= m it may escape, other > + /// than into the returned open data. > + /// - `init` must not capture references that are only valid for the= callback and store > + /// them in the open data, which outlives the callback. > + /// - The open data must be destroyed with [`DeviceBase::close`] at = the last close. > + unsafe fn open<'a, 'reg: 'a, I>( > + &'a self, > + init: impl FnOnce(&'a T::RegistrationData<'reg>) -> I, > + ) -> Result > + where > + I: PinInit, Error>, `Device` can escape into `T::OpenData` and break the invariants. You = need to change `pci::Operations::open_device` to give `dev` an anonymous lifetim= e. > + { > + // SAFETY: By the type invariants, an `Open` reference only exis= ts for a registered > + // device, which has published registration data that nothing ch= anges anymore. The > + // data remains valid until the last close. > + let reg_data =3D unsafe { *self.data.reg_data.get() } > + .expect("VFIO registration data is expected to be published.= "); > + // SAFETY: By the same reasoning above, the registration data is= valid; only its > + // lifetime is named here. > + let reg_data =3D unsafe { reg_data.cast::>().as_ref() }; > + > + // Allocate before calling the driver so allocation failure cann= ot follow open. > + let data =3D KBox::pin_init(pin_init::pin_init_scope(|| Ok(init(= reg_data))), GFP_KERNEL)?; > + // The stored type only differs in lifetimes, which do not affec= t the layout. > + let raw =3D data.into_foreign().cast::>(); > + // SAFETY: The first open is exclusive, and no I/O callback runs= before it returns. > + // INVARIANT: The allocation is pinned and owned by the slot unt= il `close()`. > + unsafe { *self.data.open_data.get() =3D NonNull::new(raw) }; > + Ok(()) > + } > +} > + > +#[expect(dead_code)] > +impl DeviceBase { > + /// Returns the registration data and the open data, for an I/O call= back. > + /// > + /// # Safety > + /// > + /// The data is named with the placeholder lifetime `'static`, which= is not the time the > + /// data is valid. The caller must use both parametrically, as a fun= ction generic over > + /// their lifetimes does: nothing borrowed from them may outlive the= callback, and nothing > + /// borrowed for the callback may be stored in them. > + unsafe fn callback_data( > + &self, > + ) -> ( > + &T::RegistrationData<'static>, > + Pin<&T::OpenData<'static, 'static>>, > + ) { > + // SAFETY: By the type invariants, an `IoContext` reference only= exists during an I/O > + // callback on an open, registered device. VFIO excludes the las= t close and > + // unregistration for its duration, so by the type invariants of= `CallbackData` both > + // slots hold valid data that nothing changes, and the open data= is pinned. > + let reg_data =3D unsafe { *self.data.reg_data.get() } > + .expect("VFIO registration data is expected to be published.= "); > + // SAFETY: By the same reasoning above, nothing changes the open= data slot. > + let open_data =3D unsafe { *self.data.open_data.get() } > + .expect("VFIO OpenData is expected to be populated."); > + // SAFETY: By the same reasoning above, the registration data is= valid for this callback. > + let reg_data =3D unsafe { reg_data.as_ref() }; > + // SAFETY: By the same reasoning above, the open data is valid f= or this callback. > + let open_data =3D unsafe { open_data.as_ref() }; > + // SAFETY: By the same reasoning above, the open data is pinned = until the last close. > + (reg_data, unsafe { Pin::new_unchecked(open_data) }) > + } > +} > + > +// SAFETY: VFIO uses the embedded class device's refcount to own the ful= l allocation. > +unsafe impl AlwaysRefCounted for DeviceBase = { > + fn inc_ref(&self) { > + // SAFETY: A shared reference keeps the initialized VFIO device = alive. > + unsafe { bindings::get_device(&raw mut (*self.as_raw_vfio()).dev= ice) }; > + } > + > + unsafe fn dec_ref(obj: NonNull) { > + // By the type invariants, `Raw` begins with its `vfio_device`, = and `raw` is the first > + // field of `Self`. > + let vdev =3D obj.as_ptr().cast::(); > + // SAFETY: The caller owns the VFIO reference being released. > + unsafe { bindings::put_device(&raw mut (*vdev).device) }; > + } > +} > + > +// SAFETY: VFIO serializes open/close transitions, and callback data is = `Send + Sync`. > +unsafe impl Send for DeviceBase {} > + > +// SAFETY: Shared access only changes the embedded class device's refere= nce count. I/O callbacks > +// share `Sync` data; VFIO excludes them from mutations of `open_data` d= uring first open and > +// last close, and registration data follows the registration lifetime. = Mutable C state is > +// managed by the VFIO core. > +unsafe impl Sync for DeviceBase {} > + > +/// Capability buffer supplied by VFIO for a region-info callback. > +pub struct InfoCap<'a> { > + #[expect(dead_code)] > + raw: &'a mut bindings::vfio_info_cap, > +} Any reason that this isn't #[repr(transparent) pub struct InfoCap { raw: Opaque, } ? > + > +/// Opaque wrapper around a `char __user *` buffer from a VFIO read or w= rite callback. > +/// > +/// Provides bounds-checked copying of kernel data into the user-space b= uffer. > +/// > +/// This type cannot be constructed by driver code =E2=80=94 it is only = created by the > +/// callback trampoline. > +pub struct UserBuf { > + ptr: UserPtr, > + count: usize, > +} No ad-hoc infrastructure for what's supposed to be in uaccess please. This = looks like like it should just be `User<[u8]>` (the generic user pointer type tha= t integrates with I/O projection); I have that in my plan and I can prioritiz= e it. Best, Gary > + > +impl UserBuf { > + /// Returns the buffer length in bytes. > + pub fn len(&self) -> usize { > + self.count > + } > + > + /// Returns `true` when the buffer is empty. > + pub fn is_empty(&self) -> bool { > + self.count =3D=3D 0 > + } > + > + /// Limit this callback's transfer to at most `count` bytes. > + pub fn truncate(&mut self, count: usize) { > + self.count =3D self.count.min(count); > + } > + > + /// Overwrite the part of `data` that overlaps a completed region re= ad. > + /// > + /// `read_offset` is the starting region offset and `read_len` is th= e number of > + /// bytes returned by the read. `data_offset` locates `data` within = the same region. > + pub fn write_overlapping( > + &self, > + read_offset: u64, > + read_len: usize, > + data_offset: u64, > + data: &[u8], > + ) -> Result { > + if read_len > self.len() { > + return Err(EINVAL); > + } > + let read_end =3D read_offset.checked_add(read_len as u64).ok_or(= EOVERFLOW)?; > + let data_end =3D data_offset > + .checked_add(data.len() as u64) > + .ok_or(EOVERFLOW)?; > + let start =3D read_offset.max(data_offset); > + let end =3D read_end.min(data_end); > + if start >=3D end { > + return Ok(()); > + } > + > + // These differences are bounded by `read_len` and `data.len()`. > + let buf_offset =3D (start - read_offset) as usize; > + let data_start =3D (start - data_offset) as usize; > + let data_end =3D (end - data_offset) as usize; > + self.write_at(buf_offset, &data[data_start..data_end]) > + } > + > + /// Copy the part of a pending region write that overlaps `data` int= o `data`. > + /// > + /// `write_offset` is the starting region offset of the write. `data= _offset` locates > + /// `data` within the same region. Returns the range of `data` that = was filled. > + pub fn read_overlapping( > + &self, > + write_offset: u64, > + data_offset: u64, > + data: &mut [u8], > + ) -> Result> { > + let write_end =3D write_offset > + .checked_add(self.len() as u64) > + .ok_or(EOVERFLOW)?; > + let data_end =3D data_offset > + .checked_add(data.len() as u64) > + .ok_or(EOVERFLOW)?; > + let start =3D write_offset.max(data_offset); > + let end =3D write_end.min(data_end); > + if start >=3D end { > + return Ok(0..0); > + } > + > + // These differences are bounded by `self.len()` and `data.len()= `. > + let src =3D self.ptr.wrapping_byte_add((start - write_offset) as= usize); > + let range =3D (start - data_offset) as usize..(end - data_offset= ) as usize; > + UserSlice::new(src, range.len()) > + .reader() > + .read_slice(&mut data[range.clone()])?; > + Ok(range) > + } > + > + /// Copy `data` to the user buffer at byte offset `offset`. > + /// > + /// Returns [`EFAULT`] if the copy fails, [`EINVAL`] if the write wo= uld > + /// exceed the buffer bounds. > + fn write_at(&self, offset: usize, data: &[u8]) -> Result { > + let end =3D offset.checked_add(data.len()).ok_or(EOVERFLOW)?; > + if end > self.count { > + return Err(EINVAL); > + } > + let dest =3D self.ptr.wrapping_byte_add(offset); > + let mut writer =3D UserSlice::new(dest, data.len()).writer(); > + writer.write_slice(data) > + } > +}