From mboxrd@z Thu Jan 1 00:00:00 1970 Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.subspace.kernel.org (Postfix) with ESMTP id 53FE7606A322 for ; Fri, 4 Dec 2026 23:12:20 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key, unprotected) header.d=shazbot.org header.i=@shazbot.org header.a=rsa-sha256 header.s=fm3 header.b=EKGVPNHW; dkim=pass (2048-bit key, unprotected) header.d=messagingengine.com header.i=@messagingengine.com header.a=rsa-sha256 header.s=fm1 header.b=x9Zd7RcV Received: by kanga.kvack.org (Postfix) id 210E66B00EF; Fri, 4 Dec 2026 18:12:19 -0500 (EST) Received: by kanga.kvack.org (Postfix, from userid 40) id 1E7B66B05B1; Fri, 4 Dec 2026 18:12:19 -0500 (EST) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 059106B05B2; Fri, 4 Dec 2026 18:12:19 -0500 (EST) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0015.hostedemail.com [216.40.44.15]) by kanga.kvack.org (Postfix) with ESMTP id 847EA6B00EF for ; Fri, 4 Dec 2026 18:12:18 -0500 (EST) Received: from smtpin14.hostedemail.com (lb01a-stub [10.200.18.249]) by unirelay02.hostedemail.com (Postfix) with ESMTP id 098D21205FD for ; Fri, 4 Dec 2026 23:12:18 +0000 (UTC) X-FDA: 85507851156.14.7B55C26 Received: from flow-b3-smtp.messagingengine.com (flow-b3-smtp.messagingengine.com [202.12.124.138]) by imf27.hostedemail.com (Postfix) with ESMTP id B23F640006 for ; Fri, 4 Dec 2026 23:12:15 +0000 (UTC) Authentication-Results: imf27.hostedemail.com; dkim=pass header.d=shazbot.org header.s=fm3 header.b=EKGVPNHW; dkim=pass header.d=messagingengine.com header.s=fm1 header.b="x 9Zd7Rc"; dmarc=pass (policy=none) header.from=shazbot.org; spf=pass (imf27.hostedemail.com: domain of alex@shazbot.org designates 202.12.124.138 as permitted sender) smtp.mailfrom=alex@shazbot.org ARC-Seal: i=1; a=rsa-sha256; d=hostedemail.com; s=arc-20220608; cv=none; t=1796425936; b=3CiCKT+zQuARgRI2/LZh5jSkfQ90DQfuOLvpB5JSasDYOQanQODnKNySGTxtY7Lff1WTE+ quXvUy/Ub+F1VfHKopoRhTkgdv4YGpkWXApA+WBDTRVdEdxFYoBFWi2sbtIcZkADfxDUj1 6hwXIJJ9+Q2mNBeqbyfmsbCMaTE5O7c= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1796425936; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=e/fYEwns6+Z+ABkGU1gEx4xsPB0na02n+3HwicAx5Ng=; b=J4AmRYx5rS1C9cSMNS5R9q0YxWXj4+wPLTXIja1n9O5mAqkZmrX3/G1SLpSDHtf6GUXgdZ 0H79ycWV1Fho4DDI+JP1ju3kPsjr+ImeGrVh4xSzPvLCON40NEniT5njtaOnyE/Af8NOau ZcpxpzDg9+7U79LonTl11c0MSyvzUww= ARC-Authentication-Results: i=1; imf27.hostedemail.com; dkim=pass header.d=shazbot.org header.s=fm3 header.b=EKGVPNHW; dkim=pass header.d=messagingengine.com header.s=fm1 header.b="x 9Zd7Rc"; dmarc=pass (policy=none) header.from=shazbot.org; spf=pass (imf27.hostedemail.com: domain of alex@shazbot.org designates 202.12.124.138 as permitted sender) smtp.mailfrom=alex@shazbot.org Received: from phl-compute-06.internal (phl-compute-06.internal [10.202.2.46]) by mailflow.stl.internal (Postfix) with ESMTP id EC214130057C for ; Fri, 4 Dec 2026 18:12:14 -0500 (EST) Received: from phl-frontend-03 ([10.202.2.162]) by phl-compute-06.internal (MEProxy); Fri, 04 Dec 2026 18:12:14 -0500 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=shazbot.org; h= cc:cc:content-transfer-encoding:content-type:content-type:date :date:from:from:in-reply-to:in-reply-to:message-id:mime-version :references:reply-to:subject:subject:to:to; s=fm3; t=1796425927; x=1796433127; bh=e/fYEwns6+Z+ABkGU1gEx4xsPB0na02n+3HwicAx5Ng=; b= EKGVPNHWeEspVV1CN7UM7RFeI70e6lDUv/kCKr7UQLxArPM0yXHaFlyrczQLKg3E HRMV8ofCpwgiMgWDPzk9F8F4K9oGAwq1TnkCEvHTw4nL+1DC2WP5XrXOzhtDyv5D OFI04Nw4kPSOBgiX3u2RqGbMv1GIaQXyHiqSwc/pKpHJhdlF5KVn00Z6eLzzBcsR ZWd2eJZ5lq5ZlL9hP7aBjaxTfILD+ZmLS3VSupFijpept0/Z0Q3aw1qrCpoqPNEc Mgvms9Y2a8bF8WlUUhggyWsqObpywS6gvLukRculivUdUBWV7deZqyM0vVyynPQn jnPzXbkKiMFWz3xsT3yViA== DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d= messagingengine.com; h=cc:cc:content-transfer-encoding :content-type:content-type:date:date:feedback-id:feedback-id :from:from:in-reply-to:in-reply-to:message-id:mime-version :references:reply-to:subject:subject:to:to:x-me-proxy :x-me-sender:x-me-sender:x-sasl-enc; s=fm1; t=1796425927; x= 1796433127; bh=e/fYEwns6+Z+ABkGU1gEx4xsPB0na02n+3HwicAx5Ng=; b=x 9Zd7RcVNqyy7geZc6VoXErgwlcUA0boRKolY9HcYyaPBQS8v1Yam7IoWHdbNdxOS ca8iYNVjQCqLIqwF2KBZ+loTNtMx8S6VOo7LQ9yBBxD9Y0Gih0eA25K7rp2s7oZS gf3K1ro/vxosTcSsWvWJksF9OTfR1kZjpDz0kzgbk4MYDipKAF7/DMb2xsK2J7ST ut8fKMKvZgo1SSwNIMQ3r6lo4ylpaewhFbDAORm6yx5tZ6/eeVONjryYkOnCwsmW JL28we+sTinUM46Yixk7aSwyZJfAcpBQmGakFi//NI5NZHhkc9L5DQzTourw7UbH eN+GKRFJHApnydP+5i64w== X-DKIM2-Info: draft=ietf-dkim-dkim2-spec-09; repo=github.com/dkim2wg/interop; date=2026-11-03; sw=lmtpprox; action=sign d=shazbot.org a=rsa-sha256; DKIM2-Signature: i=1; m=1; t=1796425927; d=shazbot.org; mf=PGFsZXhAc2hhemJvdC5vcmc+; rt=PGxpbnV4LW1tQGt2YWNrLm9yZz4=; s=fm3:rsa-sha256:Luv/HurYQoBTOSC1a2x35WP2QsBffLt5dzKuOObEGoX1agE IQ6+E81ZL+yFgMLayZh9QvxbQJBS0PUMGXbRF4jMukSzlukjPEdhsUqsOSoGyOmE 2dFDcyVN0Wa9+ufO7Y7EtIwtW5WEkkBCf1NravqIFpkyXrvOm0TPqB+L1w7PaDOC ZcRl91I2XW8u09XHLoHDx3dzbVU4kXT52ChO2t63/wC1oqQggVtHe56s5c9a5RAv A+7Ld+2wKh1bTr8xuYT9PDeEiGmIKngq3F/jK+9RvbbrnWvxBxvKIkUru376MkLA 2EHH13/PQtfmCHgAuGM/E+ldpl6j225r5Q2unxg==; X-DKIM2-Info: draft=ietf-dkim-dkim2-spec-09; repo=github.com/dkim2wg/interop; date=2026-11-03; sw=lmtpprox; action=mi-m=1; hc=12; hn=cc,content-transfer-encoding,content-type,date,feedback-id, from,in-reply-to,message-id,mime-version,references,subject,to; Message-Instance: m=1; h=sha256:aZYCnzrGvpMV/0M1PCtp8xtTEa/D4b7HpAflUXeFwiw=:sQwKA8XU1xiiRbGiSdD32xqPa7HdNcdbuwtUM9XLHYI=; X-ME-Sender: X-ME-Received: X-ME-Proxy-Cause: dmFkZTFAkGs79KPyk+SzeMc3LMqGalNJZOSRRLiivD6t6CdsVukG/ExDMhh7adUMxs+aJI k0+tw3fyHs9oHPOVpcJ684hOKBGooPLtHeQMJamd/4SeNHwdZyKTDT/0T9GZXBWMeyWilH Q0a6u6JlD1tH+PDOQptIzZ+XKHiu77BWnATCteyG0afV7bfpCINxjnsdan7Ncy95aM/0ru KFf2v16JKtcOVEuySoAWkamZRwkAFQ4pEnJeQXJvliCzl8rNE/2JK5O2JrZAQTMQHfYsci p2Fg1E4EMVoSy4fi4hAqJipBxJG/53onRgsVdLeNma8PewfoXnhlomEhdmMTrLyxB3xmOn KVQ8y4asEkPctbIkAxoMWRw87x2b5xMfLKL7L4SkDdlfXaUCy9doLnw6P9ut+GRKwCVnpV M2ckv2ZDj+B9EXftAa3tcMX9IqFMqmiQ0C6TPrG/w02RuRo9XDX4Du3hGNMMJdUA65AysZ +SCKnEzYDmHp8AAWNfZpb2qc4+2F1oxtC1OGsuMqbTchhEfPU6FP43c9Y/Sr6CtGROTB5m GH1WJmxYX5XqWoq4dPYwtQWLgieD2BW+FztNSAGh/HwzNq6yjrZAoL6g065TNcyIj3Ggmw 7jx+9yM/u2LG0apZR+d9SwUvnsBr/B79X4SvPs958W0diD+AwdXL9ADgF32g X-ME-Proxy: Feedback-ID: i03f14258:Fastmail Received: by mail.messagingengine.com (Postfix) with ESMTPA; Fri, 4 Dec 2026 18:12:02 -0500 (EST) Date: Fri, 4 Dec 2026 16:12:00 -0700 From: Alex Williamson To: Simon Song Cc: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , "Liam R. Howlett" , , Lorenzo Stoakes , alex@shazbot.org, Manish Honap Subject: Re: [PATCH v5 2/2] vfio/nova-vgpu: add the Rust VFIO variant driver Message-ID: <20261204161200.59447621@shazbot.org> In-Reply-To: <20261204144900.286240-3-xinmengs@nvidia.com> References: <20261204144900.286240-1-xinmengs@nvidia.com> <20261204144900.286240-3-xinmengs@nvidia.com> X-Mailer: Claws Mail 4.4.0 (GTK 3.24.52; x86_64-pc-linux-gnu) X-Archived-By: MIME-Version: 1.0 Content-Type: text/plain; charset=US-ASCII Content-Transfer-Encoding: 7bit X-Rspamd-Server: rspam11 X-Rspam-User: X-Stat-Signature: 67acrdbcwdi9rp6bf7dewnykk8igqb1a X-Spam-Status: No, score=-12.5 required=3.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,HEADER_FROM_DIFFERENT_DOMAINS,INCLUDES_PATCH, MAILING_LIST_MULTI,SPF_HELO_PASS,SPF_PASS,USER_AGENT_SANE_2 autolearn=ham autolearn_force=no version=4.0.1 X-Rspamd-Queue-Id: B23F640006 X-HE-Tag: 1796425935-611177 X-HE-Meta: U2FsdGVkX1+hCZW31HQC4IJt2Dwvy4AAtogdp5swXUHIn/PLyYpj7zDZYfconSKfTDt0IFaRT5cSwbvf942l7q1cWnz9fM46exlXI35Ux/AL/cOL4tGPxQediCgBaQl2TBVBByU/Z14Dxl66mCf+lO/gcAHOfeuQ6wthPkLG8nd2xlhiLsOnQ5VZXeFKqIFWmqTBfD1/bNZxYcbGMCLQw3pZeBhr5whYru9avP7MguBV8xCmpEnWUhEq8wukJNyiUlPxRrucKTgqfM12MZILG46AItt40PBy01TAtiiX2qsm+gP13QASTCChfeknsC7psMaGGfM5VfBBB9T3u+c2N58h8p9YSjQUEGow2rKijfRxfYsEH1bs7QCa6TPuT9DfsbZKYFWmAn6yG5Eiz3EIazQ/ZXIl6zaAtp011a3j4zp7s60jNg39R97UbLAotYoEzPzNyw+n7BpRu7erF/iN4TdXwZsNSI74xhX0PrewEUaEhmnqVZIvJRKhoDgc5KqYQSRKikucHCkxxwon6vUrXrd/sOMKXTZ5XADpsLOLVZfgcqPYCA16xGGVxcWYLGU0P21E24eIq9JRSVXk1/PSRMt5qMxG3rvlD84U6/bYfnu2abiNHuVoX5g1vFdbKcPYEQbE4cj0wnrW5EmvCfKwPjyHltEYAjUgDwnkKEWjIBeCHU6/FWZSAJMrd5HHlPT3YVmq9rAGeB7rMo2gg8cwV2XDApK9Eq1ijZ6xyaAm9B8AE/5gZD9JF9W9xyASR3WnUlg3L7EuYW0ZSmdDohy3ZaHVVbOfanJ2k0RQy/9B6mR8Mz/mHVBojb34GzRDfE//9d3GzQzNdGZMX3Qr18I0UPLp0PVyvsGq2SoWqm49E+Z9w9HRPuaNVXmA/9Q2tyITk2XQcmOlOZuJbRU7QsdyEQpvcNIca26JXVrdQMIEZNZgikTn5lmj4eHhOyfyL12KGm72tZnVlstGYfJNRwP AakmPSc8 nYA/cR4kXEpcS1D2Py9PVLL7hI26S5HiNKXNSQ6Nv9FfW7Nrs4YyUZ62DT8aSnfifr94/0tWgQqnF1FDereLGWGolpel/F2YPt2DhpXvnrcHNLNPHA8pE9lTKdkJr3KkJU2RhOZlNqmaN9lO7wDgtFkorVS2VGR4ovjLyu8rpsRp6N2pf+RZtrJZZtaVKd9HgBG36pEa3+yl+ys1iuPWYGm+YaRQe7pqACDvwWTio+hkyqtpzV5OpO8MdIxBf9pabokMCACbyEkvUG8Ym9tRjAIDF2FJqXO3Rp6m0Ch5/9LcJz0u8pM3AHj+mBZVdXb5VSl/TY6Zjz3tETyVrKzqBxt1UM4f/6+rkFKaO5E/uXXBQZmfKs4G8/jIJ6vpSKOMHIAq5A8si50bcyQK822vk8XMjO0ukFiBGBzZ2/r+qWhOtYQqeQUMpFi8l/BPK7r6qYCffGwOSyQifThvS4eKdKWg3gyAXPqEUwrCFe4dULIh/XliwYISCQjjz0N0RIkhA9o9/3agbM3g38/FtEeRZnuAbP+GBYNvAOUL6WqeNUgOLbioYZD2TQNOOVKoLxj3lpYe/0wvBbDFIDclqNo9cZxxxB3ElwH9TqK76Y0EzGbg5WPC+Z26FqVwAU398KDwRmbUnijg3Nvs7u4gJ8eAsCLdtupyjv10zPHB9/ZxeNotRpDSmc5EPpPQWRLWawVqRiCNuLHK/F+2hlik4TJJkvp8PSuygBrTXW4eU0LSB7m1by94rzpobPiaVSg9pnF6x2U6n2NZjhpd0tPVQXJHxAwdbFTKtUEQW3437+ftIx2UpHtue6GRfeFc2pw== Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: X-Spam-Checker-Version: SpamAssassin 4.0.1 (2024-03-26) on aws-us-west-2-korg-listserv-alma10-1 On Fri, 4 Dec 2026 06:48:55 -0800 Simon Song wrote: > diff --git a/drivers/vfio/pci/Makefile b/drivers/vfio/pci/Makefile > index 6138f1bf241df..1d9fb11eb3c21 100644 > --- a/drivers/vfio/pci/Makefile > +++ b/drivers/vfio/pci/Makefile > @@ -24,3 +24,5 @@ obj-$(CONFIG_NVGRACE_GPU_VFIO_PCI) += nvgrace-gpu/ > obj-$(CONFIG_QAT_VFIO_PCI) += qat/ > > obj-$(CONFIG_XE_VFIO_PCI) += xe/ > + > +# nova-vgpu is built from drivers/gpu/Makefile for nova-core crate linkage. > diff --git a/drivers/vfio/pci/nova-vgpu/Kconfig b/drivers/vfio/pci/nova-vgpu/Kconfig > new file mode 100644 > index 0000000000000..29fad96340ce6 > --- /dev/null > +++ b/drivers/vfio/pci/nova-vgpu/Kconfig > @@ -0,0 +1,20 @@ > +# SPDX-License-Identifier: GPL-2.0-only > +config NOVA_VGPU_VFIO_PCI > + tristate "VFIO support for the NVIDIA vGPU" > + depends on NOVA_CORE && PCI_IOV && RUST > + depends on VFIO_PCI_CORE=y Why do we require VFIO_PCI_CORE is builtin? This is not really an acceptable requirement. > + help > + This option enables VFIO (Virtual Function I/O) support for > + NVIDIA virtual GPUs (vGPU). It allows the assignment of a virtual > + GPU instance to userspace applications via VFIO, typically used > + with hypervisors such as KVM and device emulators like QEMU. > + > + Devices without an available Nova vGPU interface use ordinary PCI > + passthrough. Both paths use the VFIO PCI core defaults; vfio-pci > + module options do not apply. > + > + The NVIDIA vGPU allows a physical GPU to be partitioned into > + multiple virtual GPUs, each of which can be passed to a virtual > + machine as a PCI device using the standard VFIO infrastructure. > + > + If you don't know what to do here, say N. ... > diff --git a/drivers/vfio/pci/nova-vgpu/nova_vgpu.rs b/drivers/vfio/pci/nova-vgpu/nova_vgpu.rs > new file mode 100644 > index 0000000000000..21d3ad70c84ef > --- /dev/null > +++ b/drivers/vfio/pci/nova-vgpu/nova_vgpu.rs We've been harassed previously for naming redundancy, which is why newer variant drivers are using main.c for the variant driver code rather than duplicating the directory name. Can we do similar here? > @@ -0,0 +1,522 @@ > +// SPDX-License-Identifier: GPL-2.0 > +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. > + > +//! NVIDIA vGPU VFIO variant driver. > +//! > +//! Nova VFs own an instance between the first VFIO open and last close. Other > +//! matching devices use ordinary PCI passthrough. > + > +use core::ops::Range; > +use kernel::{ > + bindings, > + device::{ > + Bound, > + Core, // > + }, > + io::resource::Flags, > + pci, > + prelude::*, > + sync::{ > + CondVar, > + Mutex, > + MutexGuard, // > + }, > + uaccess::{ > + UserSlice, > + UserSliceReader, > + UserSliceWriter, // > + }, > + vfio::{ > + self, > + pci::{ > + GetRegionInfo, > + Ioctl, > + Mapping, > + Mmap, > + Open, > + Position, > + Read, > + RegionInfo, > + Write, // > + }, // > + }, // > +}; > +use nova_core::{ > + NovaCoreVfApi, > + NovaCoreVfApiHandle, > + VgpuInstance, // > +}; > + > +struct NovaVgpuOps; > + > +struct VgpuRegistration<'a> { > + api: NovaCoreVfApiHandle<'a>, > + gfid: u32, > +} > + > +#[derive(Default)] > +struct InstanceState { > + active: bool, > + resetting: bool, > + reset_error: Option, > + fb_bar_reg: u64, > +} > + > +#[pin_data] > +struct NovaVgpuRegData<'a> { > + pdev: &'a pci::Device, > + vgpu: Option>, > + fb_bar: Option, > + #[pin] > + state: Mutex, > + #[pin] > + reset_done: CondVar, > +} > + > +impl NovaVgpuRegData<'_> { > + fn lock_instance(&self) -> MutexGuard<'_, InstanceState> { > + let mut state = self.state.lock(); > + while state.resetting { > + self.reset_done.wait(&mut state); > + } > + state > + } > +} > + > +struct NovaVgpuOpenData<'a, 'res> { > + registration: &'a NovaVgpuRegData<'res>, > + instance: Option>, > +} > + > +impl<'a, 'res> NovaVgpuOpenData<'a, 'res> { > + fn new( > + dev: &vfio::pci::Device, > + rd: &'a NovaVgpuRegData<'res>, > + ) -> Result { > + let mut state = rd.lock_instance(); > + let instance = match &rd.vgpu { > + Some(vgpu) => { > + // The firmware DBDF format has a 16-bit PCI segment field. > + let segment = u16::try_from(rd.pdev.domain_nr()).map_err(|_| EOVERFLOW)?; > + let dbdf = (u32::from(segment) << 16) | u32::from(rd.pdev.dev_id().into_raw()); > + let vm_pid = kernel::current!().tgid().try_into()?; > + let instance = vgpu.api.open(vgpu.gfid, dbdf, vm_pid)?; > + let info = instance.type_info(); A comment here explaining the scheme of instance providing the device ID would be useful, it's potentially confusing that the host VF device ID and guest VF device ID don't necessarily match... or do they? > + dev.set_device_id(info.pci_dev_id as u16); > + state.active = true; > + state.reset_error = None; > + state.fb_bar_reg = 0; > + Some(instance) > + } > + None => None, > + }; > + Ok(Self { > + registration: rd, > + instance, > + }) > + } > + > + fn bar1_size(&self) -> Result> { > + let (Some(instance), Some(fb_bar)) = (&self.instance, self.registration.fb_bar) else { > + return Ok(None); > + }; > + let physical = self.registration.pdev.resource_len(fb_bar)?; > + let size = instance > + .type_info() > + .bar1_length > + .checked_mul(1 << 20) > + .ok_or(EOVERFLOW)?; > + if size != 0 && !size.is_power_of_two() { > + return Err(EINVAL); > + } > + Ok(Some(size.min(physical))) > + } Why do we choose to clamp the BAR1 size rather than expose the physical VF BAR size and restrict access to the unimplemented extent? Consider for example Manish's excluded ranges series[1]. If this variant driver exposed the full BAR, but registered the unimplemented extent as an excluded range with READ/WRITE/MMAP restriction, the excluded range support would handle read, write, mmap, the sparse memory capability, dmabuf, and even ioeventfd. Additionally, we could drop trapping config space for BAR sizing and the region_info handling. And, as another bonus, you'd give Manish the opportunity to have an MMAP exclusion user before vfio-cxl lands. It seems like a win-win-win situation. The variant driver reduces to open/close/reset handling, and just the subsystem ID in config space. Allowing a variant driver to mark that as virtual might be a better long term solution than open coding that handling. [1]https://lore.kernel.org/all/20261202093250.1683744-1-mhonap@nvidia.com/ > + > + /// Returns the length to which a `len`-byte access at `position` has to be shortened to > + /// stay within the vGPU's BAR1, or `None` if the access needs no limit. > + fn bar1_limit(&self, len: usize, position: &Position<'_>) -> Result> { > + if len == 0 || Some(position.region_index()) != self.registration.fb_bar { > + return Ok(None); > + } > + if let Some(size) = self.bar1_size()? { > + let offset = position.region_offset(); > + if offset >= size { > + return Err(EINVAL); > + } > + if size - offset < len as u64 { > + return Ok(Some((size - offset) as usize)); > + } > + } > + Ok(None) > + } > +} > + > +/// Overrides fields of a completed region read in the user buffer. > +/// > +/// The fields must not overlap and have to be passed in ascending offset order, as the buffer > +/// is only walked forward. > +struct ReadOverride { > + writer: UserSliceWriter, > + /// Region offset of the writer's current position. > + offset: u64, > +} > + > +impl ReadOverride { > + /// `writer` starts at region offset `offset`, where a read returned `count` bytes. > + fn new(mut writer: UserSliceWriter, offset: u64, count: usize) -> Self { > + writer.truncate(count); > + Self { writer, offset } > + } > + > + /// Replaces the bytes of the read that overlap `data`, located at `data_offset` in the > + /// region. > + fn apply(&mut self, data_offset: u64, data: &[u8]) -> Result { > + let read_end = self > + .offset > + .checked_add(self.writer.len() as u64) > + .ok_or(EOVERFLOW)?; > + let data_end = data_offset > + .checked_add(data.len() as u64) > + .ok_or(EOVERFLOW)?; > + let start = self.offset.max(data_offset); > + let end = read_end.min(data_end); > + if start >= end { > + return Ok(()); > + } > + > + // These differences are bounded by the writer's length and `data.len()`. > + self.writer.skip((start - self.offset) as usize)?; > + self.writer > + .write_slice(&data[(start - data_offset) as usize..(end - data_offset) as usize])?; > + self.offset = end; > + Ok(()) > + } > +} > + > +/// Copies the bytes of a pending region write that overlap `data` into `data`. > +/// > +/// `reader` holds the data of a write at region offset `write_offset`; it is not advanced. > +/// `data_offset` locates `data` within the same region. Returns the range of `data` that was > +/// filled. > +fn peek_write( > + reader: &UserSliceReader, > + write_offset: u64, > + data_offset: u64, > + data: &mut [u8], > +) -> Result> { > + let write_end = write_offset > + .checked_add(reader.len() as u64) > + .ok_or(EOVERFLOW)?; > + let data_end = data_offset > + .checked_add(data.len() as u64) > + .ok_or(EOVERFLOW)?; > + let start = write_offset.max(data_offset); > + let end = write_end.min(data_end); > + if start >= end { > + return Ok(0..0); > + } > + > + // These differences are bounded by `reader.len()` and `data.len()`. > + let range = (start - data_offset) as usize..(end - data_offset) as usize; > + // The VFIO core fetches the write from user space again, so the copy made here may differ > + // from what it stores. Use it for the driver's own bookkeeping only. > + let mut peek = reader.clone_reader(); > + peek.skip((start - write_offset) as usize)?; > + peek.read_slice(&mut data[range.clone()])?; > + Ok(range) > +} > + > +impl Drop for NovaVgpuOpenData<'_, '_> { > + fn drop(&mut self) { > + let mut state = self.registration.lock_instance(); > + state.active = false; > + drop(self.instance.take()); > + } > +} > + > +impl vfio::Operations for NovaVgpuOps { > + type RegistrationData<'res> = NovaVgpuRegData<'res>; > + type OpenData<'reg, 'res: 'reg> = NovaVgpuOpenData<'reg, 'res>; > +} > + > +#[vtable] > +impl vfio::pci::Operations for NovaVgpuOps { > + const NAME: &'static CStr = c"nova-vgpu-vfio-pci"; > + > + fn open_device<'a, 'res: 'a>( > + dev: &vfio::pci::Device, > + rd: &'a NovaVgpuRegData<'res>, > + ) -> impl PinInit, Error> + 'a { > + NovaVgpuOpenData::new(dev, rd) > + } > + > + fn ioctl<'res>( > + dev: &vfio::pci::Device, > + rd: &NovaVgpuRegData<'res>, > + open_data: Pin<&Self::OpenData<'_, 'res>>, > + cmd: u32, > + arg: usize, > + ) -> Result { > + // The core checks ioeventfd bounds against the physical BAR and writes > + // without calling write(), bypassing the vGPU's bar1_limit() check. > + // Checking a copy here could race with the core's later copy from userspace. > + // On rejection, QEMU falls back to its userspace eventfd handler, whose > + // writes pass through write() and bar1_limit(). > + if cmd == vfio::DEVICE_IOEVENTFD && open_data.instance.is_some() { > + return Err(ENOTTY); > + } > + let result = dev.core_ioctl(cmd, arg)?; > + if cmd == vfio::DEVICE_RESET { > + if let Some(error) = rd.state.lock().reset_error { > + return Err(error); > + } > + } > + Ok(result) > + } > + > + fn read<'res>( > + dev: &vfio::pci::Device, > + rd: &NovaVgpuRegData<'res>, > + open_data: Pin<&Self::OpenData<'_, 'res>>, > + buf: UserSlice, > + position: &mut Position<'_>, > + ) -> Result { > + let mut writer = buf.writer(); > + if let Some(instance) = &open_data.instance { > + if position.region_index() == vfio::pci::CONFIG_REGION_INDEX { > + let offset = position.region_offset(); > + return position.with_temporary(|next| { > + let count = dev.core_read(&writer, next)?; > + // The fields overridden below do not overlap and are in ascending config > + // space offset order. > + let mut overrides = ReadOverride::new(writer, offset, count.try_into()?); > + if let (Some(size), Some(fb_bar)) = (open_data.bar1_size()?, rd.fb_bar) { > + let reg = rd.state.lock().fb_bar_reg & !size.wrapping_sub(1); > + // Byte 0 holds only the flag bits, which the core has filled in. > + overrides.apply( > + u64::from(bindings::PCI_BASE_ADDRESS_0) + 4 * u64::from(fb_bar) + 1, > + ®.to_le_bytes()[1..], > + )?; > + } > + // A VF has no device ID of its own, so the core keeps it in vconfig, where > + // it is set once at open. The core reads the subsystem ID from the hardware, > + // as a firmware update can change it there, so replace it on every read. > + overrides.apply( > + u64::from(bindings::PCI_SUBSYSTEM_ID), > + &(instance.type_info().pci_subsys_id as u16).to_le_bytes(), > + )?; > + Ok(count) > + }); > + } > + } > + if let Some(limit) = open_data.bar1_limit(writer.len(), position)? { > + writer.truncate(limit); > + } > + dev.core_read(&writer, position) > + } > + > + fn write<'res>( > + dev: &vfio::pci::Device, > + rd: &NovaVgpuRegData<'res>, > + open_data: Pin<&Self::OpenData<'_, 'res>>, > + buf: UserSlice, > + position: &mut Position<'_>, > + ) -> Result { > + let mut reader = buf.reader(); > + if let Some(fb_bar) = rd.fb_bar { > + if position.region_index() == vfio::pci::CONFIG_REGION_INDEX { > + let mut written = [0; 8]; > + let range = peek_write( > + &reader, > + position.region_offset(), > + u64::from(bindings::PCI_BASE_ADDRESS_0) + 4 * u64::from(fb_bar), > + &mut written, > + )?; > + if !range.is_empty() { > + let mut state = rd.state.lock(); > + let mut reg = state.fb_bar_reg.to_le_bytes(); > + reg[range.clone()].copy_from_slice(&written[range]); > + state.fb_bar_reg = u64::from_le_bytes(reg); > + } > + } > + } > + if let Some(limit) = open_data.bar1_limit(reader.len(), position)? { > + reader.truncate(limit); > + } > + dev.core_write(&reader, position) > + } > + > + fn mmap<'res>( > + dev: &vfio::pci::Device, > + rd: &NovaVgpuRegData<'res>, > + open_data: Pin<&Self::OpenData<'_, 'res>>, > + mapping: &mut Mapping<'_>, > + ) -> Result { > + if Some(mapping.region_index()) == rd.fb_bar { > + if let Some(size) = open_data.bar1_size()? { > + if mapping.region_end()? > size { > + return Err(EINVAL); > + } > + } > + } > + dev.core_mmap(mapping) > + } > + > + fn get_region_info<'res>( > + dev: &vfio::pci::Device, > + rd: &NovaVgpuRegData<'res>, > + open_data: Pin<&Self::OpenData<'_, 'res>>, > + info: &mut RegionInfo, > + caps: &mut vfio::InfoCap, > + ) -> Result { > + dev.core_get_region_info(info, caps)?; > + if Some(info.index()) == rd.fb_bar && info.size() != 0 { > + if let Some(size) = open_data.bar1_size()? { > + info.set_size(info.size().min(size)); > + } > + } > + Ok(()) > + } > + > + fn dmabuf_len<'res>( > + rd: &NovaVgpuRegData<'res>, > + open_data: Pin<&Self::OpenData<'_, 'res>>, > + region_index: u32, > + ) -> Result> { > + if Some(region_index) == rd.fb_bar { > + return open_data.bar1_size(); > + } > + Ok(None) > + } > + > + fn reset_prepare(rd: &NovaVgpuRegData<'_>) { > + // PCI holds the device lock, and VFIO may hold its memory lock. Open and > + // close release this mutex before entering the VFIO core. > + let mut state = rd.state.lock(); > + state.resetting = true; > + state.reset_error = None; > + // A VF FLR is reported to the GSP firmware, but does not release all > + // guest resources or scrub the framebuffer. That work can exceed the > + // FLR time budget and delay other vGPUs if done in the FLR handler. > + // Request it first through nova-core, which owns the PF's firmware > + // interface, to quiesce the vGPU before its VF is reset. > + // > + // Using PCI's prepare callback also covers host sysfs function > + // resets, in addition to VFIO ioctl and config-space resets. Only while the VF is bound to this driver. > + // An error is recorded but cannot veto the PCI reset attempt. > + if state.active { > + if let Some(vgpu) = &rd.vgpu { > + state.reset_error = vgpu.api.reset(vgpu.gfid).err(); > + } > + } > + } > + > + fn reset_done(rd: &NovaVgpuRegData<'_>) -> Result { > + let mut state = rd.state.lock(); > + let error = state.reset_error; > + state.resetting = false; > + rd.reset_done.notify_all(); > + error.map_or(Ok(()), Err) > + } > +} > + > +struct NovaVgpuDriver; > + > +kernel::pci_device_table!( > + PCI_TABLE, > + ::IdInfo, > + [ > + ( > + pci::DeviceId::from_id_vfio_override(pci::Vendor::NVIDIA, 0x2bb3), > + (), > + ), > + ( > + pci::DeviceId::from_id_vfio_override(pci::Vendor::NVIDIA, 0x2bb5), > + (), > + ), > + ] > +); > + > +#[pin_data] > +struct NovaVgpuData<'bound> { > + reg: vfio::pci::Registration<'bound, NovaVgpuOps>, > +} > + > +#[vtable] > +impl pci::Driver for NovaVgpuDriver { > + type IdInfo = (); > + type Data<'bound> = NovaVgpuData<'bound>; > + const ID_TABLE: pci::IdTable = &PCI_TABLE; > + // SAFETY: VFIO hands the DMA ownership of the device to userspace. This driver never uses > + // the kernel DMA API for its devices, directly or through helpers. > + const DRIVER_MANAGED_DMA: Option> = > + Some(unsafe { pci::DriverManagedDma::new() }); Note Uwe's series[2]. If this makes v7.5, there will need to be some post integration work to add support_driver_override during the rc cycle. [2]https://lore.kernel.org/all/cover.1796376468.git.u.kleine-koenig@baylibre.com/ Thanks, Alex