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=40.93.195.21 ARC-Seal: i=2; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=pass; t=1796200668; b=XDBPN4BtaLJFGgPUXE25Gv2IBZn75kv5khStOk+asEj4Cm7qaOMnAJ2oUeUzB92g8pSN txyQ2tezXav0I8fDzPNeU4Im6HUCc1uUn7oxjIFB5ZZJahO/OU5JAC7TWBYdDvDCgAwLo Ovp3JFIpIP3iDvMXYJGFturpqDGidO8vKtMEqUrcTg5K/YnL84JZE5yQB/yk+Cw1LXeTa ge+zxs/w3spy4aqTf7MqPOOiVF8X+qaZSWrWr1hsjZjhXFkOKf+Yq+SfGbGj+T46bO9cS MOoXhoOaRoycRlhzm2kWDmwQKvssWM2OCqklKRv8xTpGT8qgQQTHa3ziruDHuiig7qw== ARC-Message-Signature: i=2; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796200668; 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=zKrNbsjIvg51sHw3xNYtZbh+QsDblJETWZEdZ7HW+Ow=; b=FpZoN3dMXnyMrE4tm9rG+EFueSA+bDAJNFysOYl+Nhb7XsSeLEnNVq3pB5sJCkBSBlEU 4BBjlcGzZBvKJ87KEFA4VkchkPzRW4qadqiai5AuaZaa6CK/HlJat/Fu2mBevB/LXXRsx iX2bzF1EG9yh+x3npS2GWNezNBIJ+iHJSZV3aI/eRFUpQV4LOsB/e38tG9tsMkrc8fzAD WspjujoyNoZX5NVIxm/ySJWCyFwI2jNhffKxTUM495HHCODMvaEsOLQMU8ZxqaoR08W5J yziFnJ3Ybht6rPQRe0FNDFMKqjQXdqBV1UCVBkdCVhBMVncJuVuPb49QVmL8IN1ehwg== 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=lCEV4yiO; arc=pass header.oldest-pass=0 smtp.remote-ip=40.93.195.21 Received: from SN4PR2101CU001.outbound.protection.outlook.com (mail-southcentralusazon11012021.outbound.protection.outlook.com [40.93.195.21]) (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 C3C07606A336; Wed, 2 Dec 2026 08:37:46 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org C3C07606A336 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=lCEV4yiO ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=ImNuUYPhVFXrg7k753f7LViIuqJQqW5acxXE+p2DBDEJLV1ZVM8Ab88rdGNsD2h9L4cfKRJ171364uGk7zII5vUi+OxWr5iSQ1KuN+b+EmIBOujwQ4w6gikDW+JHLXWzsHXBcpXA02IyGiHenQJyhtViR09aGCI653wbVLhlHHQIIUvGqFhDQi42aPzFeoB7C7j76idhhVHPlhWgX/jcY1J7THRD4H9QF0KhsTRg6/HTDq6IEJBWXXlDzkvGKh7aFncfi+lsQ+UG6qNhE3+bc376XWivLfbRBTI8ICKi5sC1K82Nuh7AEwcIRgPj/AQ4KZonqHfowBU3kFXkkIVgSQ== 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=zKrNbsjIvg51sHw3xNYtZbh+QsDblJETWZEdZ7HW+Ow=; b=j+jbSLPosGOU0nJ+fnk/Gz6pe7A3CywSZEG14IkahDsMYviB78HnSXdforbnURCUILjU5OGOZ/DkG/4Ai7S4BoTnV3qicWhrURedpaonXoAlrOEz5nC32gt2mEhbUvkrsDaEZ4nmkZePdJTq3XHkYDPeYkmRR40KbEFOiA5Xz/GobXzWohFyuoQU40/4WVyc3e835All/neEZw1YY8GDopOqyerPmPVuI02zmRFF1KDWzw+C0yYlabDIICtukZb7OXsc8hBc5HUupSDKtt+WPdDHXRffdKTH7bcJFsnPia2/luNG2gweD6wNZskfkN3uclyKsUd0uR4p7Y6MHgFkng== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass (sender ip is 216.228.117.160) 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=zKrNbsjIvg51sHw3xNYtZbh+QsDblJETWZEdZ7HW+Ow=; b=lCEV4yiOe4NnbejFLlQfhHzW1rjQytHGvqda7CBJn7ZTbt9GRQmbwHxIBlsANQhGdT0AS0aUjaCJ1dYdWDKOtQKhIcwvQtDsr1wbytPRCrYT5/whnzpjxK5V2fKWs5Gr/9n2KX2lvwJ9k6t0/yYi/ALumiJbNvthYUk0Sj2csaWMKQ22X7cYtyXW2LF+Zl8BwbbnKaCw/sC3zBZOiqx796Bf0Jt6kQmyMvlYmOembJrMVE0V8Dzy3mIEHiMKp/MIlZYYu1PEDnU4C1CNxv+XoYjompV6lS75iemxA5CCH4vilxSuuAhQFWdcd38CLK2GBSBcr6u6ZKAl0/AAkdR8AA== Received: from SJ0PR13CA0074.namprd13.prod.outlook.com (2603:10b6:a03:2c4::19) by SJ0PR12MB6991.namprd12.prod.outlook.com (2603:10b6:a03:47c::17) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.662.13; Wed, 2 Dec 2026 08:37:39 +0000 Received: from BY1PEPF0001AE1C.namprd04.prod.outlook.com (2603:10b6:a03:2c4:cafe::92) by SJ0PR13CA0074.outlook.office365.com (2603:10b6:a03:2c4::19) with Microsoft SMTP Server (version=TLS1_3, cipher=TLS_AES_256_GCM_SHA384) id 15.21.688.9 via Frontend Transport; Wed, 2 Dec 2026 08:37:39 +0000 X-MS-Exchange-Authentication-Results: mx.microsoft.com 1; spf=pass (sender IP is 216.228.117.160) 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.160 as permitted sender) receiver=protection.outlook.com; client-ip=216.228.117.160; helo=mail.nvidia.com; pr=C Received: from mail.nvidia.com (216.228.117.160) by BY1PEPF0001AE1C.mail.protection.outlook.com (10.167.242.105) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.688.5 via Frontend Transport; Wed, 2 Dec 2026 08:37:39 +0000 Received: from rnnvmail201.nvidia.com (10.129.68.8) by mail.nvidia.com (10.129.200.66) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.2.2562.57; Wed, 2 Dec 2026 00:37:24 -0800 Received: from kalok-SPC741D16QM3.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; Wed, 2 Dec 2026 00:37:10 -0800 From: Alok Kumar To: , , , , , CC: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , Subject: [PATCH v6 22/34] gpu: nova-core: vgpu: add instance create/destroy Date: Wed, 2 Dec 2026 13:58:46 +0530 Message-ID: X-Mailer: git-send-email 2.53.0 In-Reply-To: References: 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 Content-Transfer-Encoding: 8bit Content-Type: text/plain X-ClientProxiedBy: rnnvmail202.nvidia.com (10.129.68.7) To rnnvmail201.nvidia.com (10.129.68.8) X-EOPAttributedMessage: 0 X-MS-PublicTrafficType: Email X-MS-TrafficTypeDiagnostic: BY1PEPF0001AE1C:EE_|SJ0PR12MB6991:EE_ X-MS-Office365-Filtering-Correlation-Id: 17a32d1b-26fe-42f5-9c17-08df504f8625 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|7416014|376014|82310400026|36860700016|1800799024|23010399003|11063799006|6133799003|261009223027099003|18002099003|22082099003|3023799007|10067099003|56012099006|261026140227099003|261102123227099003|261026121527099003|261028144727099003|261021123027099003|261022105027099003|261021121427099003|261022113327099003|261022075727099003; X-Microsoft-Antispam-Message-Info: zgIsE6KUhXS8muxZaNBDfrInstcI4l7NgAMx4/X/zEPL5YqH/J4Me6MNA/2RY/iaRV1Acb2+CHXcOb0OriPJOXUe5wYVv2kN57mZW1nD3eNUuEj6h1uye1e37P5WHlDkFlw6Ac/F5E15Cl2oetcN7R5CUQ5ETMQ32X/L9Iq1ZKuHF7ZZ45LwFWNvXVjIqdqdvOKRPTlqFDr+Bcv1WQjHFcZvvQHtYxQqoY5cY33/pD8NDxtijD9rvtqRJkS2m1axxmJ00uQah+ta5mxCDwsSKqChg8+Lsyeyr1iXMlWQ8q9U3dwrhERlP+012zbvV6RpOKkRkfZVauvp14OXYcFZ4vvB5EfEX6xcuhlsjm59Y/mqODcH1txSV927MQVFtN18kZWzNNsbCiD6pwbO/oZMZiq/9CHjYX9KzjiLJ6iYm2s9Bx0fOZW6d+iUda84di/KdXxbf2pwTWQUDqyFJ+t2GjcTp3otGkEML4AN76HcE3K4jKWrhtzq0T0V3DLMdGHsNrHOCt//vnYRQWjRNk0EpuuWq5ntWLyQ6bWGcioaZVaKex3UYl9Mu+Q2xj5kp9aZ/OPYtkWbDNqG/J+ITCdZKL6uvRdJGRX5b7rPDX/0YhaJGUzQi9RBzEKY+TsIDw/aFPBKsvNaxelcZhNHkY1YluMW0V27pkhTmZ3rqRMURKjjRfJ2gXnLIUDtiUBDBA5q58rfY0b3WVp1FUxAojYAag== X-Forefront-Antispam-Report: CIP:216.228.117.160;CTRY:US;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:mail.nvidia.com;PTR:dc6edge1.nvidia.com;CAT:NONE;SFS:(13230040)(7416014)(376014)(82310400026)(36860700016)(1800799024)(23010399003)(11063799006)(6133799003)(261009223027099003)(18002099003)(22082099003)(3023799007)(10067099003)(56012099006)(261026140227099003)(261102123227099003)(261026121527099003)(261028144727099003)(261021123027099003)(261022105027099003)(261021121427099003)(261022113327099003)(261022075727099003);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: I+G8ukG1dzPp6r9i1xk3d3xTP9gZwGaGVfcvJLvO9s/7HLSM43DJVh6WM97CR9TVX+Xvyqx91K09ZT935OFPDEkXSNB09r+56PSbYqBu3nemd6Wlbp8uuEvRvgDBxG1s6IJTcC4eT0JGhwl1DJwSRuslmPkwZZk36MmmxobTKcR+Sh927o/oqLvp5Qi8JRITurIVEnoQ0xhx5FZbQHckKaPkEAnqV5SzHs7vk6Dl7J9F9Es9UrLCrQj46CrRHZUSedjQvPQ7EBIMy4McPQQlkCxt8ad9vYBSaT6O4nNrlyTIucidURpmsH6V6bz8ScpiHVlQgPnv0vU4f5APa9efiZ9ulxxhDuM6hq+4yAFvntCeW7lzpFMGohv3b8xZNNeDH+a6fMM9vB7HY4rftqzE9wmhBKzsVxmhFHhpAl5yalU5n+xFFsaBO7DJJ3OqbQdH X-OriginatorOrg: Nvidia.com X-MS-Exchange-CrossTenant-OriginalArrivalTime: 02 Dec 2026 08:37:39.2890 (UTC) X-MS-Exchange-CrossTenant-Network-Message-Id: 17a32d1b-26fe-42f5-9c17-08df504f8625 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.160];Helo=[mail.nvidia.com] X-MS-Exchange-CrossTenant-AuthSource: BY1PEPF0001AE1C.namprd04.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Anonymous X-MS-Exchange-CrossTenant-FromEntityHeader: HybridOnPrem X-MS-Exchange-Transport-CrossTenantHeadersStamped: SJ0PR12MB6991 From: Zhi Wang A vGPU instance needs channel IDs and framebuffer and management-heap regions determined by its assigned type. Let instances own their channel reservations and borrow their VRAM regions from a manager-owned pool. Keep the pinned pool and its instance registry together. The registry borrows the pool through a pin-init self-reference and drops its instances before the pool's backing VramBlock is released. Keep those borrows inside the owning object through scoped projections. Reject duplicate GFID or DBDF entries and enforce the profile's instance limit. Reserve registry capacity before acquiring instance resources. Removing an instance releases its channel reservation and makes its VRAM slot available for reuse. Keep the pool cached when the last instance is removed. Replace it for a different layout only when no instances remain, releasing the old backing allocation before reserving the new one. Signed-off-by: Zhi Wang Co-developed-by: Alexandre Courbot Signed-off-by: Alexandre Courbot Signed-off-by: Alok Kumar --- drivers/gpu/nova-core/gpu.rs | 50 +++-- drivers/gpu/nova-core/mm.rs | 1 - drivers/gpu/nova-core/vgpu.rs | 56 +++-- drivers/gpu/nova-core/vgpu/instance.rs | 291 +++++++++++++++++++++++++ drivers/gpu/nova-core/vgpu/vram.rs | 1 - 5 files changed, 363 insertions(+), 36 deletions(-) create mode 100644 drivers/gpu/nova-core/vgpu/instance.rs diff --git a/drivers/gpu/nova-core/gpu.rs b/drivers/gpu/nova-core/gpu.rs index 549a0a90d244..40cc326b5cf2 100644 --- a/drivers/gpu/nova-core/gpu.rs +++ b/drivers/gpu/nova-core/gpu.rs @@ -51,6 +51,7 @@ bar_user::BarUser, pagetable::MmuVersion, GpuMm, + SharedGpuMm, VramAddress, // }, timer::{ @@ -63,7 +64,6 @@ }, }; -#[cfg_attr(not(CONFIG_KUNIT = "y"), expect(dead_code))] pub(crate) mod channel; mod hal; mod regs; @@ -390,7 +390,9 @@ unsafe fn new( #[pin_data] pub(crate) struct Gpu<'gpu> { pub(crate) spec: Spec, - vgpu: Option>, + /// Drops before the MM and BAR1 mappings needed for instance teardown. + #[uses('bar_user, 'chid_pool)] + vgpu: Option>>>, /// GSP event interrupt registration, and the enable of its subtree. /// /// Must be kept declared *before* `gsp_resources`, so that the handler is unregistered, and @@ -403,7 +405,8 @@ pub(crate) struct Gpu<'gpu> { /// /// Must be kept declared *before* `gsp_resources`, so that its components are dropped while /// the GSP is still operational. - mm: GpuMm<'gpu>, + #[pin] + mm: SharedGpuMm<'gpu>, /// BAR1 user interface for CPU access to GPU virtual memory. #[pin] bar_user: BarUser<'gpu>, @@ -568,7 +571,7 @@ pub(crate) fn new<'a>( }, // Create GPU memory manager owning memory management resources. - mm: { + mm <- { let info = &gsp_resources.boot_result.static_info; let usable_vram = info.usable_fb_regions.first().ok_or(ENODEV)?; let buddy_params = GpuBuddyParams { @@ -577,12 +580,12 @@ pub(crate) fn new<'a>( chunk_size: Alignment::SZ_4K, }; - GpuMm::new( + SharedGpuMm::new(GpuMm::new( bar, gsp_resources.spec.chipset, buddy_params, VramAddress::from_raw(info.total_fb_end), - )? + )?) }, // Create BAR1 user interface for CPU access to GPU virtual memory. @@ -604,15 +607,18 @@ pub(crate) fn new<'a>( let info = &gsp_resources.boot_result.static_info; match gsp_resources.vgpu_state { VgpuState::Disabled => None, - VgpuState::Enabled { .. } => Some(VgpuManager::new( - chid_pool.get_ref(), - &info.fifo_engine_list(), - info.vmmu_segment_size, - TOTAL_CHANNELS, - )), + VgpuState::Enabled { .. } => Some(KBox::pin_init( + VgpuManager::new( + mm.get_ref(), + chid_pool.get_ref(), + &info.fifo_engine_list(), + info.vmmu_segment_size, + TOTAL_CHANNELS, + ), + GFP_KERNEL, + )?), } }, - }) } @@ -645,14 +651,16 @@ pub(crate) fn run_selftests(self: Pin<&mut Self>, pdev: &pci::Device impl<'gpu> SharedGpuMm<'gpu> { /// Creates a pin-initializer sharing `mm`. - #[expect(dead_code)] pub(crate) fn new(mm: GpuMm<'gpu>) -> impl PinInit + 'gpu { pin_init!(Self { inner <- new_mutex!(mm, "nova-core::gpu-mm"), diff --git a/drivers/gpu/nova-core/vgpu.rs b/drivers/gpu/nova-core/vgpu.rs index 5688d6bf1e08..e7b4f1f3a614 100644 --- a/drivers/gpu/nova-core/vgpu.rs +++ b/drivers/gpu/nova-core/vgpu.rs @@ -6,8 +6,10 @@ use kernel::{ bitfield, device, + new_mutex, pci, - prelude::*, // + prelude::*, + sync::Mutex, // }; use crate::{ @@ -20,11 +22,15 @@ Chipset, // }, gsp::commands::FifoEngineList, // + mm::{ + SharedGpuMm, // + }, // }; mod commands; mod fw; mod hal; +mod instance; mod vram; bitfield! { @@ -99,32 +105,56 @@ fn query_state( } } +use self::instance::VgpuInstances; + /// Runtime resources for an enabled vGPU boot. -pub(crate) struct VgpuManager<'gpu> { - #[expect(dead_code)] +#[pin_data] +pub(crate) struct VgpuManager<'gpu> +where + // Hide the invariant resource lifetime of the instance registry so `VgpuManager` remains + // covariant. + exists<'res>: 'gpu, +{ + #[pin] + #[uses('res: invariant)] + inner: VgpuManagerInner<'res>, +} + +/// Inner state of [`VgpuManager`]. +/// +/// The instances kept in the registry borrow the GPU resources below, which makes this type +/// invariant over `'gpu`. +#[pin_data] +struct VgpuManagerInner<'gpu> { + #[pin] + instances: Mutex>, + mm: &'gpu SharedGpuMm<'gpu>, chid_pool: &'gpu ChannelIdPool, /// VMMU segment size in bytes, or zero if GSP-RM omitted it. - #[expect(dead_code)] vmmu_segment_size: u64, - #[expect(dead_code)] total_channels: u32, - #[expect(dead_code)] fifo_engine_list: FifoEngineList, } impl<'gpu> VgpuManager<'gpu> { /// Retains runtime parameters from a completed vGPU-enabled GSP boot. pub(crate) fn new( + mm: &'gpu SharedGpuMm<'gpu>, chid_pool: &'gpu ChannelIdPool, fifo_engine_list: &FifoEngineList, vmmu_segment_size: u64, total_channels: u32, - ) -> Self { - Self { - chid_pool, - vmmu_segment_size, - total_channels, - fifo_engine_list: *fifo_engine_list, - } + ) -> impl PinInit + use<'gpu> { + let fifo_engine_list = *fifo_engine_list; + pin_init!(Self { + inner <- pin_init!(VgpuManagerInner { + instances <- new_mutex!(VgpuInstances::new(), "nova-core::vgpu-instances"), + mm, + chid_pool, + vmmu_segment_size, + total_channels, + fifo_engine_list, + }), + }) } } diff --git a/drivers/gpu/nova-core/vgpu/instance.rs b/drivers/gpu/nova-core/vgpu/instance.rs new file mode 100644 index 000000000000..40f32da359d5 --- /dev/null +++ b/drivers/gpu/nova-core/vgpu/instance.rs @@ -0,0 +1,291 @@ +// SPDX-License-Identifier: GPL-2.0 +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + +use core::num::{ + NonZero, + NonZeroUsize, // +}; + +use kernel::{ + prelude::*, + ptr::Alignment, + sizes::SizeConstants, // +}; + +use crate::{ + gpu::channel::ChannelIdReservation, + mm::GpuMm, // + num::FromSafeCast, +}; + +use super::{ + fw::commands::VgpuProperties, + vram::{ + VgpuVramLayout, + VgpuVramSlot, + VgpuVramSlotPool, // + }, + Dbdf, + VgpuManagerInner, // +}; + +/// Guest Function ID validated against one device's total number of VFs. +/// +/// GFID 0 is reserved for the PF; VFs start at 1. Keeping the nonzero `u16` +/// preserves the PCI SR-IOV range when forming a plugin doorbell handle. +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) struct Gfid(NonZero); + +impl Gfid { + /// Validates an external GFID for a device supporting `total_vfs` VFs. + #[expect(dead_code)] + pub(super) fn new(gfid: u32, total_vfs: NonZero) -> Result { + let gfid = u16::try_from(gfid).map_err(|_| EINVAL)?; + let gfid = NonZero::new(gfid).ok_or(EINVAL)?; + + if gfid > total_vfs { + Err(EINVAL) + } else { + Ok(Self(gfid)) + } + } + + #[expect(dead_code)] + pub(super) const fn get(self) -> u16 { + self.0.get() + } +} + +/// Resource requirements for one vGPU type. +struct VgpuType { + vgpu_type_id: u32, + max_instance: u32, + fb_length: u64, + gsp_heap_size: u64, +} + +impl From<&VgpuProperties> for VgpuType { + fn from(properties: &VgpuProperties) -> Self { + Self { + vgpu_type_id: properties.type_id, + max_instance: properties.max_instance, + fb_length: properties.fb_length, + gsp_heap_size: properties.gsp_heap_size, + } + } +} + +/// A vGPU instance and the resources reserved for it. +#[expect(dead_code)] +struct VgpuInstance<'pool, 'gpu> { + gfid: Gfid, + dbdf: Dbdf, + vgpu_type: VgpuType, + vm_pid: u32, + chids: ChannelIdReservation<'gpu>, + vram_slot: VgpuVramSlot<'pool>, +} + +/// Identity and firmware profile used to allocate an instance. +pub(super) struct InstanceInfo { + gfid: Gfid, + dbdf: Dbdf, + vgpu_type: VgpuType, + vm_pid: u32, +} + +#[expect(dead_code)] +impl InstanceInfo { + pub(super) fn new(gfid: Gfid, dbdf: Dbdf, properties: &VgpuProperties, vm_pid: u32) -> Self { + Self { + gfid, + dbdf, + vgpu_type: VgpuType::from(properties), + vm_pid, + } + } +} + +/// Instance registry and cached VRAM pool for one physical GPU. +pub(super) struct VgpuInstances<'gpu> { + pool: Option>>>, +} + +/// Instances borrow the pool, and are destroyed before its backing allocation. +#[pin_data] +struct VgpuInstancePool<'gpu> { + // Preserve the pool lifetime when inserting new borrowed regions into the registry. + #[uses('pool: invariant)] + registry: InstanceRegistry<'pool, 'gpu>, + #[pin] + pool: VgpuVramSlotPool, +} + +impl<'gpu> VgpuInstancePool<'gpu> { + fn new(mm: &GpuMm<'_>, layout: VgpuVramLayout) -> Result> { + let pool = VgpuVramSlotPool::new(mm, layout)?; + Ok(try_pin_init!(Self { + pool <- pool, + registry: InstanceRegistry { + instances: KVec::new(), + pool: pool.get_ref(), + }, + })) + } +} + +#[expect(dead_code)] +impl<'gpu> VgpuInstances<'gpu> { + pub(super) const fn new() -> Self { + Self { pool: None } + } + + fn create_instance(&mut self, vgpu: &VgpuManagerInner<'gpu>, info: InstanceInfo) -> Result { + let layout = VgpuVramLayout::new( + info.vgpu_type.vgpu_type_id, + info.vgpu_type.max_instance, + info.vgpu_type.fb_length, + info.vgpu_type.gsp_heap_size, + vgpu.vmmu_segment_size, + )?; + let replace = match self.pool.as_ref() { + Some(pool) => pool.as_ref().with_project_ref(|this| { + if this.pool.matches_layout(layout) { + Ok(false) + } else if this.registry.instances.is_empty() { + Ok(true) + } else { + Err(EBUSY) + } + })?, + None => true, + }; + if replace { + // Release the old reservation only after all its borrowers are gone. + self.pool = None; + self.pool = Some(vgpu.mm.with_locked(|mm| { + KBox::pin_init(VgpuInstancePool::new(mm, layout)?, GFP_KERNEL) + })?); + } + self.pool + .as_mut() + .ok_or(EIO)? + .as_mut() + .with_project(|this| this.registry.create_instance(vgpu, info)) + } + + fn destroy_instance(&mut self, gfid: Gfid) -> Result { + self.pool + .as_mut() + .ok_or(ENOENT)? + .as_mut() + .with_project(|this| this.registry.destroy_instance(gfid)) + } +} + +/// Registry of instances borrowing one layout's pool. +struct InstanceRegistry<'pool, 'gpu> { + instances: KVec>, + pool: &'pool VgpuVramSlotPool, +} + +impl<'pool, 'gpu> InstanceRegistry<'pool, 'gpu> { + fn alloc_vram_slot(&self) -> Result> { + let index = (0..self.pool.max_slots()) + .find(|i| !self.instances.iter().any(|inst| inst.vram_slot.index == *i)) + .ok_or(ENOSPC)?; + self.pool.slot(index) + } + + /// Creates and returns a [`VgpuInstance`]. + fn allocate_instance( + &mut self, + vgpu: &VgpuManagerInner<'gpu>, + info: InstanceInfo, + ) -> Result> { + let InstanceInfo { + gfid, + dbdf, + vgpu_type, + vm_pid, + } = info; + + let instance_exists = self + .instances + .iter() + .any(|instance| instance.gfid == gfid || instance.dbdf == dbdf); + if instance_exists { + return Err(EEXIST); + } + + let type_id = vgpu_type.vgpu_type_id; + let num_type_instances = self + .instances + .iter() + .filter(|instance| instance.vgpu_type.vgpu_type_id == type_id) + .count(); + if num_type_instances >= usize::from_safe_cast(vgpu_type.max_instance) { + return Err(ENOSPC); + } + + let channels_per_instance = vgpu + .total_channels + .checked_div(vgpu_type.max_instance) + .map(usize::from_safe_cast) + .and_then(NonZeroUsize::new) + .ok_or(EINVAL)?; + let chids = vgpu + .chid_pool + .reserve_ids(channels_per_instance, Alignment::SZ_1)?; + + let vram_slot = self.alloc_vram_slot()?; + + Ok(VgpuInstance { + gfid, + dbdf, + vgpu_type, + vm_pid, + chids, + vram_slot, + }) + } + + /// Remove an instance and release its channel and VRAM reservations. + fn destroy_instance(&mut self, gfid: Gfid) -> Result { + let instance_index = self + .instances + .iter() + .position(|instance| instance.gfid == gfid) + .ok_or(ENOENT)?; + let instance = self.instances.remove(instance_index).map_err(|_| EIO)?; + drop(instance); + Ok(()) + } + + /// Allocate, register, and activate a vGPU instance. + /// + /// Keep the registry locked through creation or rollback so duplicate checks and + /// type limits remain stable. MM and BAR-user locks are acquired only within + /// individual memory operations, in that order. + fn create_instance(&mut self, vgpu: &VgpuManagerInner<'gpu>, info: InstanceInfo) -> Result { + // Reserve capacity before acquiring resources so registration cannot allocate. + self.instances.reserve(1, GFP_KERNEL)?; + + let instance = self.allocate_instance(vgpu, info)?; + + // Register live instances, and failed ones whose resources firmware may still own. + self.instances + .push_within_capacity(instance) + .map_err(|_| EIO)?; + + Ok(()) + } +} + +impl VgpuManagerInner<'_> { + #[expect(dead_code)] + fn create_instance(&self, info: InstanceInfo) -> Result { + self.instances.lock().create_instance(self, info) + } +} diff --git a/drivers/gpu/nova-core/vgpu/vram.rs b/drivers/gpu/nova-core/vgpu/vram.rs index b6356a9765e2..a6d3f02341da 100644 --- a/drivers/gpu/nova-core/vgpu/vram.rs +++ b/drivers/gpu/nova-core/vgpu/vram.rs @@ -94,7 +94,6 @@ pub(super) struct VgpuVramSlotPool { fb_region_size: u64, } -#[expect(dead_code)] impl VgpuVramSlotPool { /// Reserve the VRAM for all possible slots of `layout`, and returns a [`VgpuVramSlotPool`] that /// can provide these slots.