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.57.15 ARC-Seal: i=2; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=pass; t=1796357945; b=ETggDLa8Y9Vi5zZ8hQNm9TQ0QTKKs645s5E1C2cOmWW+/S+4mzvO+0gyCQZYONBNdr+L Ah0mlT98eGrOkZ6khWLBrg8Oqz6M7Q2ayJCJ0EpwxF414OdY6WiwKAAYZ4BRBz2fQ9SCK ZD6MI66aTY7x1EyXg9GL9t8MhrG9fM48rG1wDygmV5mmEGdIPo9W7PyT44n1S6xPQ3WHG Z7Jf5EDlB5KzCdGtsGs7hi2dMqni/zNM22toPHBugyVYxvzht5jb5xFS2284zkxadIoJ1 gdJwC89ACSksEV3Q+TtFbh0g2SsMSbMBAV3KREbR+Fihjvac17boAeAh4aAEw6JOg3w== ARC-Message-Signature: i=2; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796357945; h=DMARC-Filter:DKIM-Signature:Received:Received: X-MS-Exchange-Authentication-Results:Received-SPF:Received:Received: Received:From:To:CC:Subject:Date:Message-ID:X-Mailer:In-Reply-To: References:MIME-Version:Content-Transfer-Encoding:Content-Type: X-Originating-IP:X-ClientProxiedBy:X-EOPAttributedMessage: 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-OriginalArrivalTime: X-MS-Exchange-CrossTenant-Network-Message-Id: X-MS-Exchange-CrossTenant-Id: X-MS-Exchange-CrossTenant-OriginalAttributedTenantConnectingIp: X-MS-Exchange-CrossTenant-AuthSource:X-MS-Exchange-CrossTenant-AuthAs: X-MS-Exchange-CrossTenant-FromEntityHeader: X-MS-Exchange-Transport-CrossTenantHeadersStamped; bh=8EsWSv7ywxsgVPWJi90Jl+LzHATSHnSoqyWpXZnkbgU=; b=sp8JDm8Eq+g2Lj0EYodKyvU+BcA0wUa//dDP4TPCVLnUO4qYcvGqgqg/1jmMg3N7Em4P nfYZRzdLFJyfwnuhn4Q08KUKz1m2Qk/YH0rA/9gRKx8h8IJfGgTCf+NS7vKiNlYKlbiqy P4F7dEcwnxrIWyFZeJTuW4S+TTYXhHL6fUP5qPQo7/QY40mj3MIPwkciGftXmej0euxKF 8tpZTlSFH/e5Zs+lkVM/ogyVpTcjBaakanpJlzuDJLif/03paGCBx0vl08E50DiNhzcEM tS0+4bJ1M1WK3fDJQndcG501kJZr+XR58hYcJfPGtu4qHxUzOT3+PsSW4het9sjixfw== ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass header.from=nvidia.com; spf=fail smtp.mailfrom=nvidia.com; dkim=pass header.d=Nvidia.com header.i=@Nvidia.com header.a=rsa-sha256 header.s=selector2 header.b=dnHVxBjn; arc=pass header.oldest-pass=0 smtp.remote-ip=52.101.57.15 Received: from BN8PR05CU002.outbound.protection.outlook.com (mail-eastus2azon11011015.outbound.protection.outlook.com [52.101.57.15]) (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 4A203606A33D for ; Fri, 4 Dec 2026 04:18:55 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 4A203606A33D Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=nvidia.com Authentication-Results: smtp.subspace.kernel.org; spf=fail smtp.mailfrom=nvidia.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key, unprotected) header.d=Nvidia.com header.i=@Nvidia.com header.a=rsa-sha256 header.s=selector2 header.b=dnHVxBjn ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=nmtcvr4DdwDzLdyYVarOLDMe1zagycPyNDUsYRHgwChntQgontMGxIIbzV0+o6Xyty03doknmLtIHai/YElo18+n/O9eUco3FLSF9gBBiA8zgXXI7Nf1fWPuKnzII3FPnisY6gFq9wWTZLfyBYN2uKtiA9jwCpigSrdPTimNh0kDopCerrGEnR9ehdz93rCUTgWOJTX3YF8qY7AtwifrbG2K5OqXPLrl5ECX7yHwNn9nG43YBxM3tN7LEk4Fj2oJI+GBWvNZSfMRcAJwl5LAVNGS9CZiAIO35W45EK0ArROOzyKSzMyH/GMw5/rzW+2FSD/d6Fi90v/db6UJzDMbgg== 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=8EsWSv7ywxsgVPWJi90Jl+LzHATSHnSoqyWpXZnkbgU=; b=Qb7FoBs7g+wXACKvE1KMcFUBhiROoCQksHm2f4ccOizDsJP6+7Xr8wGwoc88RXtGpBtaEjm2TATQOmVZqaQD6vNqGBnUzYYSWHBt3lY3/K+Tszs6BkXZWJ73Y8f9D9vzxzFVypsCPg8GycA2I/TI8cn5MYttMm0AdLmJQQsfuKZPb4Bfcj1JFgAOP590KJW9QgNSLXzCIbYnWka1Cb9TwDscTF+dpPZUn+iEIzyrxZEkBCxRPHBt/XQxPD9tOtfA//+o2xXhqm5OSVngNCk7kbrmIDegbJkKtxgTrbv8HglOLuGkIL2R4x4hv4LD3bJKJNzXwFNmYTWctmzvPK9g5A== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass (sender ip is 216.228.117.161) smtp.rcpttodomain=kernel.org smtp.mailfrom=nvidia.com; dmarc=pass (p=reject sp=reject pct=100) action=none header.from=nvidia.com; dkim=none (message not signed); arc=none (0) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=Nvidia.com; s=selector2; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=8EsWSv7ywxsgVPWJi90Jl+LzHATSHnSoqyWpXZnkbgU=; b=dnHVxBjnn4liNauC/h6CzIzej+dhiEHbuld580YchMUd7zOmGZVKOf4bxblo/5gPK56B6yDyD4RxAxUWtHHxlQ/y0efiMqe05CAw28MIk1w8vbbIt1Q7esyUVrBc5WA+pKgGOYS8iYw8jd7dWowcH8k1/peArbtDZRaR6M9nVcjF5Kgd/WJYRxiCUkvNfeAeCrGd1BiPwmoZrtfkeLdsoHSaLV/eG5QoSz/wxeKIIyIcexS3ahtIhFFoZNCbux2c8YH6/cUB5nGqdW3++7pCh+/IBU0pdyYb15HJzRsOBvAOXo4ZoJxo8g+1BJTg3qvg8RnmX5baIcQxYNAm8l/K0A== Received: from BN9PR03CA0044.namprd03.prod.outlook.com (2603:10b6:408:fb::19) by PH0PR12MB8821.namprd12.prod.outlook.com (2603:10b6:510:28d::19) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.688.10; Fri, 4 Dec 2026 04:18:45 +0000 Received: from BL6PEPF0006C3DE.namprd02.prod.outlook.com (2603:10b6:408:fb:cafe::6c) by BN9PR03CA0044.outlook.office365.com (2603:10b6:408:fb::19) with Microsoft SMTP Server (version=TLS1_3, cipher=TLS_AES_256_GCM_SHA384) id 15.21.688.12 via Frontend Transport; Fri, 4 Dec 2026 04:18:45 +0000 X-MS-Exchange-Authentication-Results: mx.microsoft.com 1; spf=pass (sender IP is 216.228.117.161) smtp.mailfrom=nvidia.com; dkim=none (message not signed) header.d=none;dmarc=pass action=none header.from=nvidia.com; Received-SPF: Pass (protection.outlook.com: domain of nvidia.com designates 216.228.117.161 as permitted sender) receiver=protection.outlook.com; client-ip=216.228.117.161; helo=mail.nvidia.com; pr=C Received: from mail.nvidia.com (216.228.117.161) by BL6PEPF0006C3DE.mail.protection.outlook.com (10.167.249.233) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.709.6 via Frontend Transport; Fri, 4 Dec 2026 04:18:45 +0000 Received: from rnnvmail201.nvidia.com (10.129.68.8) by mail.nvidia.com (10.129.200.67) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.2.2562.57; Thu, 3 Dec 2026 20:18:24 -0800 Received: from xinmengs-dev-vm-linux.nvidia.com (10.126.231.37) by rnnvmail201.nvidia.com (10.129.68.8) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.2.2562.57; Thu, 3 Dec 2026 20:18:22 -0800 From: Simon Song To: , , , , , CC: Zhi Wang , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , "Liam R. Howlett" , , Lorenzo Stoakes Subject: [PATCH v5 2/4] rust: vfio: add common VFIO device handling Date: Thu, 3 Dec 2026 20:17:22 -0800 Message-ID: <20261204041727.4021092-3-xinmengs@nvidia.com> X-Mailer: git-send-email 2.43.7 In-Reply-To: <20261204041727.4021092-1-xinmengs@nvidia.com> References: <20261204041727.4021092-1-xinmengs@nvidia.com> X-Mailing-List: nova-gpu@lists.linux.dev List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: 8bit Content-Type: text/plain X-ClientProxiedBy: rnnvmail203.nvidia.com (10.129.68.9) To rnnvmail201.nvidia.com (10.129.68.8) X-EOPAttributedMessage: 0 X-MS-PublicTrafficType: Email X-MS-TrafficTypeDiagnostic: BL6PEPF0006C3DE:EE_|PH0PR12MB8821:EE_ X-MS-Office365-Filtering-Correlation-Id: da711d08-1ea4-4271-5cc8-08df51bdb017 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|82310400026|1800799024|376014|7416014|36860700016|23010399003|11063799006|5023799004|6133799003|18002099003|22082099003|261021121427099003|10067099003|261026140227099003|56012099006|261026121527099003|261022105027099003|261009223027099003|261102123227099003|261022075727099003|261028144727099003; X-Microsoft-Antispam-Message-Info: zksos7z719FP9iXyGj898qgRxuprRtvDsmjnGIr+W5DPujIYVycyh7M4g9SaXz3aO41fEf+v1w11+wxdFymUa/5EcmQu2VEBg9YxlUEGOUumQZXblgSK9jHl920yOohF2AftrZsdVYjl0fk4WDtKFs+BQWk4DHNXM+PHmeGEFrYzFlseEc1HGCaWcJt2DoR8dcg+yd1tdDVFEpbuscxV5ALjCsBv8PAgXZ4FegMaouSWKdwhWPFozCUC1ozSj9YP6HSw8gh2OvTpIHwFfA3uvvhGwEttj73jZmbYg+nEFOBUrbcXOKfp6ZmbABOH9vliCmywVFMEmTFkRjW2UCkKNho19IPPapIY5S3AQTQjIoM+aSoel2xYrF5PIzCDGqVou4XbTw33khbJbODSb7/58/MogZzOHkPPV68IJfNZzAk+JIA0Twt5yJfOz8MWeLpTmD1gi/W5YqdDl/DqHRW6J3M+DQ+6Y+Bl19DMzxh27ybs/Lo8zOvdcbO9sGvR/B2fMF3S0uRYvacnnat9kJPWBKxwhmD7yx5ZMTw2EkQEWuQ+NViKUBpeFY5ZMN4knYYWi3p1Hgt6ndkrhBQzL0PSuK/EbCiEHe81sM8AzAFzXP29iTXzFGpeuXIprgGA+IPHxmZ6RzMeR2aQF4gpNEu9o90ICQIel+g5So/xbieM+aCd05WiUuB/aoA8Ha8XB2jzdMhIcs8htsc69ZGj2mJb9w== X-Forefront-Antispam-Report: CIP:216.228.117.161;CTRY:US;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:mail.nvidia.com;PTR:dc6edge2.nvidia.com;CAT:NONE;SFS:(13230040)(82310400026)(1800799024)(376014)(7416014)(36860700016)(23010399003)(11063799006)(5023799004)(6133799003)(18002099003)(22082099003)(261021121427099003)(10067099003)(261026140227099003)(56012099006)(261026121527099003)(261022105027099003)(261009223027099003)(261102123227099003)(261022075727099003)(261028144727099003);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: Uk2kyuVel01aJAdEpj+VqRD0lrr2phBtQR0c/W+/sTEdaFSf0VvG3R60Cx4O3vz+TaNSgSRqsDyDU9kG3H8fimB5euTfWmPa1JU6GnED3N29btm335Fdiz28v1Fa6SYrSvD6w+Ao2iF2MgEwfwOe1hvM3EaseKgUU9s5SaPmalq6G7Qdux4DWA+urdqwRO+GaJ2Z5AYJkYU6nTaNFYo6aQe+IcgLvzBQcDnOWfcmQfN3/h6VCYBPRtQ23/NBUvVimmP96k/8WhSYcvI0KilxlU1Xg7TzP/fswcycqrGASQx6JQYH3Wipir78q03wohaNS1dkWxcG0TshXAsguesQtb3IaoiifOnveMKzaD9/LfrwS86FhrC6I5RueMfRK2dHZcuwBl6oLX7IYUVdpeFL0E9X6Nz2hmp8bUO996bS/o3wWTjwp2FUd6YGhNhPq5go X-OriginatorOrg: Nvidia.com X-MS-Exchange-CrossTenant-OriginalArrivalTime: 04 Dec 2026 04:18:45.3476 (UTC) X-MS-Exchange-CrossTenant-Network-Message-Id: da711d08-1ea4-4271-5cc8-08df51bdb017 X-MS-Exchange-CrossTenant-Id: 43083d15-7273-40c1-b7db-39efd9ccc17a X-MS-Exchange-CrossTenant-OriginalAttributedTenantConnectingIp: TenantId=43083d15-7273-40c1-b7db-39efd9ccc17a;Ip=[216.228.117.161];Helo=[mail.nvidia.com] X-MS-Exchange-CrossTenant-AuthSource: BL6PEPF0006C3DE.namprd02.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Anonymous X-MS-Exchange-CrossTenant-FromEntityHeader: HybridOnPrem X-MS-Exchange-Transport-CrossTenantHeadersStamped: PH0PR12MB8821 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 | 357 ++++++++++++++++++++++++++++++++ 3 files changed, 361 insertions(+) create mode 100644 rust/kernel/vfio.rs diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index 3791af0aadc7..a5781bc1ea85 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 = ARCH_SLAB_MINALIGN; const size_t RUST_CONST_HELPER_ARCH_KMALLOC_MINALIGN = ARCH_KMALLOC_MINALIGN; const size_t RUST_CONST_HELPER_PAGE_SIZE = PAGE_SIZE; +const unsigned int RUST_CONST_HELPER_VFIO_DEVICE_RESET = VFIO_DEVICE_RESET; const size_t RUST_CONST_HELPER_GENLMSG_DEFAULT_SIZE = GENLMSG_DEFAULT_SIZE; const gfp_t RUST_CONST_HELPER_GFP_ATOMIC = GFP_ATOMIC; const gfp_t RUST_CONST_HELPER_GFP_KERNEL = GFP_KERNEL; diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 1ab41129d557..061e22fb09cf 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -147,6 +147,8 @@ pub mod uaccess; #[cfg(CONFIG_USB = "y")] pub mod usb; +#[cfg(CONFIG_VFIO = "y")] +pub mod vfio; pub mod workqueue; pub mod xarray; diff --git a/rust/kernel/vfio.rs b/rust/kernel/vfio.rs new file mode 100644 index 000000000000..30a593634a72 --- /dev/null +++ b/rust/kernel/vfio.rs @@ -0,0 +1,357 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Virtual Function I/O (VFIO) devices and callback data. +//! +//! A [`Device`] wraps a C `struct vfio_device` together with the data its driver's callbacks +//! use. +//! +//! C header: [`include/linux/vfio.h`](srctree/include/linux/vfio.h) + +// The PCI abstraction is currently the only user of these helpers. +#![expect(dead_code)] + +use crate::{ + bindings, + prelude::*, + sync::aref::AlwaysRefCounted, + types::{ + ForeignOwnable, + NotThreadSafe, + Opaque, // + }, // +}; +use core::{ + cell::UnsafeCell, + marker::PhantomData, + ptr::NonNull, // +}; + +/// Reset the VFIO device. +pub const DEVICE_RESET: u32 = bindings::VFIO_DEVICE_RESET; + +/// The context in which a VFIO device reference is valid. +/// +/// Callback views can only be borrowed from the corresponding VFIO trampoline. +/// 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 callback. +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 thread. +pub struct Ioctl; + +/// The device is borrowed for a VFIO read callback on the current thread. +pub struct Read; + +/// The device is borrowed for a VFIO write callback on the current thread. +pub struct Write; + +/// The device is borrowed for a VFIO mmap callback on the current thread. +pub struct Mmap; + +/// The device is borrowed for a VFIO region-info callback on the current thread. +pub struct GetRegionInfo; + +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 `'res`. Per-device state lives here. + type RegistrationData<'res>: Send + Sync + 'res; + + /// Data shared by callbacks from the first successful open until the last close. + /// + /// It can borrow the registration data for `'reg`. + type OpenData<'reg, 'res: 'reg>: Send + Sync + 'reg; +} + +/// 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. After unregistration or a +/// failed registration attempt, the pointer may dangle; its pointee must 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 the 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 reference count of its embedded +/// `vfio_device` owns the allocation. +/// - For [`Open`] and [`IoContext`] references, registration data is published 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 = DeviceBase; + +impl DeviceBase { + /// Initializes the Rust fields of a newly allocated device. + /// + /// # Safety + /// + /// `this` must point to an allocation with the size and alignment of `Self`, whose `raw` + /// has been initialized. `Raw` must be a C structure that begins with its + /// `struct vfio_device`. Nothing else may access the allocation during this call. + unsafe fn init(this: *mut Self) { + // SAFETY: The caller provides exclusive access to a suitable allocation. + // 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 written. + unsafe { (&raw mut (*this)._context).write(PhantomData) }; + } + + /// Recovers `&Self` from the `vfio_device` VFIO passes to a callback. + /// + /// # Safety + /// + /// `vdev` must point to the `vfio_device` at the beginning of a `Self` that remains alive + /// for `'a`. The caller must provide the guarantees of `Ctx` throughout the borrow. + #[inline] + unsafe fn from_raw_vfio<'a>(vdev: *mut bindings::vfio_device) -> &'a Self { + // SAFETY: By the type invariants, `Raw` begins with its `vfio_device`, and `raw` is the + // first field of `Self`. The caller guarantees validity. + // INVARIANT: The caller provides the guarantees of `Ctx`. + unsafe { &*vdev.cast() } + } + + #[inline] + fn as_raw(&self) -> *mut Raw { + self.raw.get() + } + + #[inline] + fn as_raw_vfio(&self) -> *mut bindings::vfio_device { + // By the type invariants, `Raw` begins with its `vfio_device`. + self.as_raw().cast() + } +} + +impl DeviceBase { + /// Publishes the registration data passed to callbacks. + /// + /// # Safety + /// + /// The device must not have been registered, and this must be the only call for it. + /// `data` must point to pinned data that remains valid until the device has been + /// unregistered or, if registration fails, is not accessed through this device. + unsafe fn publish_registration_data<'res>(&self, data: NonNull>) { + // SAFETY: The device has not been registered, so no callback can read the slot, and + // this is the only call that writes it. + // INVARIANT: The slot is written once; the caller keeps `data` valid. + unsafe { *self.data.reg_data.get() = Some(data.cast()) }; + } + + /// 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 resources the open data borrows + /// must remain alive. + unsafe fn close(&self) { + // SAFETY: The last close exclusively takes the allocation published by `open()`. + let raw = 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 not used again. The + // allocation is destroyed without moving it. + drop(unsafe { + >>>::from_foreign(raw.as_ptr().cast()) + }); + } +} + +impl DeviceBase { + /// Creates the open data from the registration data. + /// + /// The [`Open`] context guarantees an exclusive first open of a registered device, whose + /// registration data remains valid until the last close. + /// + /// # Safety + /// + /// - No open data may exist. + /// - The caller chooses `'a` and `'res`; this function cannot tie either 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 from 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, 'res: 'a, I>( + &'a self, + init: impl FnOnce(&'a T::RegistrationData<'res>) -> I, + ) -> Result + where + I: PinInit, Error>, + { + // SAFETY: By the type invariants, an `Open` reference only exists for a registered + // device, which has published registration data that nothing changes anymore. The + // data remains valid until the last close. + let reg_data = 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 = unsafe { reg_data.cast::>().as_ref() }; + + // Allocate before calling the driver so allocation failure cannot follow open. + let data = KBox::pin_init(pin_init::pin_init_scope(|| Ok(init(reg_data))), GFP_KERNEL)?; + // The stored type only differs in lifetimes, which do not affect the layout. + let raw = 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 until `close()`. + unsafe { *self.data.open_data.get() = NonNull::new(raw) }; + Ok(()) + } +} + +impl DeviceBase { + /// Returns the registration data and the open data, for an I/O callback. + /// + /// # 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 function 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 last 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 = 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 = 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 = unsafe { reg_data.as_ref() }; + // SAFETY: By the same reasoning above, the open data is valid for this callback. + let open_data = 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 full allocation. +unsafe impl AlwaysRefCounted for DeviceBase { + #[inline] + fn inc_ref(&self) { + // SAFETY: A shared reference keeps the initialized VFIO device alive. + unsafe { bindings::get_device(&raw mut (*self.as_raw_vfio()).device) }; + } + + #[inline] + 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 = 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 reference count. I/O callbacks +// share `Sync` data; VFIO excludes them from mutations of `open_data` during 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. +#[repr(transparent)] +pub struct InfoCap(Opaque); + +impl InfoCap { + /// Creates a reference to an [`InfoCap`] from a raw pointer. + /// + /// # Safety + /// + /// `ptr` must point to a `struct vfio_info_cap` that satisfies the VFIO core's invariants, + /// remains valid for `'a` and is not accessed in any other way for the duration of `'a`. + #[inline] + pub(crate) unsafe fn from_raw<'a>(ptr: *mut bindings::vfio_info_cap) -> &'a mut Self { + // SAFETY: `Self` is a transparent wrapper around `struct vfio_info_cap`. The caller + // guarantees that `ptr` is valid and exclusively accessible for `'a`. + unsafe { &mut *ptr.cast() } + } + + /// Returns a raw pointer to the `struct vfio_info_cap`. + #[inline] + pub(crate) fn as_raw(&self) -> *mut bindings::vfio_info_cap { + self.0.get() + } +} -- 2.43.7