From nobody Mon Nov 23 04:26:21 2026 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; arc=pass (i=1 dmarc=pass fromdomain=amd.com); dmarc=pass(p=quarantine dis=none) header.from=amd.com ARC-Seal: i=2; a=rsa-sha256; t=1793364822; cv=pass; d=zohomail.com; s=zohoarc; b=T5x8UWH29ydOdFBHZ4ltuWp6wcLHwSABlkSoPecAi/qWui1Jc2AYkIwSTu4ct67WFwk+LKKjqFtudj6nh9NCQe3VoYvpo3xzySbNZ6VzT9WvVJk2SfD1wHIklwG4jYtkG0CFqxePQnY572aYm1XsxY7EGcVjKt55QOxT1qXn7Ds= ARC-Message-Signature: i=2; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1793364822; h=Content-Type:Content-Transfer-Encoding:Cc:Cc:Date:Date:From:From:In-Reply-To:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:Sender:Subject:Subject:To:To:Message-Id:Reply-To; bh=lg2rGPpsazLeYxGfFI2aGtZJDGCcW0nt5cRKeDfWHvw=; b=ZQpNX+mmh9ot7yu3prJaqe2sT2qwuZElGXZEyd6sUCGo9SefveZD5QdpsugqU1AsqnH0UtRiFh0OQBY0IUZHT09XOkUI1EO+FSz5oO+O9CbWuemx7dJJcZJ1qxB5wDtSxPCgeyorzKjRt7YwFak6E2D+D4Ymv6soW8V3sMBRfjk= ARC-Authentication-Results: i=2; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; arc=pass (i=1 dmarc=pass fromdomain=amd.com); dmarc=pass header.from= (p=quarantine dis=none) Return-Path: Received: from lists1p.gnu.org (lists1p.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1793364822037621.6185866167465; Fri, 30 Oct 2026 05:53:42 -0700 (PDT) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists1p.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1xMm6g-0000aB-81; Fri, 30 Oct 2026 08:53:18 -0400 Received: from eggs.gnu.org ([2001:470:142:3::10]) by lists1p.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1xMm6e-0000Zz-Fb for qemu-devel@nongnu.org; Fri, 30 Oct 2026 08:53:17 -0400 Received: from mail-westus3azlp170100009.outbound.protection.outlook.com ([2a01:111:f403:c107::9] helo=PH7PR06CU001.outbound.protection.outlook.com) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1xMm6c-0002vz-5J for qemu-devel@nongnu.org; Fri, 30 Oct 2026 08:53:16 -0400 Received: from BY3PR04CA0022.namprd04.prod.outlook.com (2603:10b6:a03:217::27) by DSVPR12MB999126.namprd12.prod.outlook.com (2603:10b6:8:383::11) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.569.10; Fri, 30 Oct 2026 12:53:06 +0000 Received: from SJ1PEPF000023CB.namprd02.prod.outlook.com (2603:10b6:a03:217:cafe::4) by BY3PR04CA0022.outlook.office365.com (2603:10b6:a03:217::27) with Microsoft SMTP Server (version=TLS1_3, cipher=TLS_AES_256_GCM_SHA384) id 15.21.569.10 via Frontend Transport; Fri, 30 Oct 2026 12:53:06 +0000 Received: from satlexmb07.amd.com (165.204.84.17) by SJ1PEPF000023CB.mail.protection.outlook.com (10.167.244.5) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.569.4 via Frontend Transport; Fri, 30 Oct 2026 12:53:05 +0000 Received: from localhost (10.180.168.240) by satlexmb07.amd.com (10.181.42.216) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.2.2562.53; Fri, 30 Oct 2026 07:53:04 -0500 ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=A4KNlaHalRjgco1uCT48JKBqp/HfVjNulNK5GnKB1FgoAcq3mqiDRidri7ZCLHqoyhjdIPZt/ZVUgUWFqt2pZRqog/gnBh7Rh0aJkCmfW4C+OIYPq87mbuk0BrgAimq/nDVoSh7PnOHO4CLTt9OMr9wwm8VsKkNisIdNStE1AcF3fpXrdoFUwQrL7DitI2AmWRgd87vX09G45nNxuQM26NNdCTd7AQ+mfIl7PXl1xo4zXTThJaW1Z0pN2xw1MspmieLz3ZFWQLs191kphxKgIILSmvCo6m1mNR7dwaIq2sq6O0LS0NJJp+YnNncCK/plKrmDyFjDB/7khu8y8ivBUA== 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=lg2rGPpsazLeYxGfFI2aGtZJDGCcW0nt5cRKeDfWHvw=; b=iKhDOrpDim+yW2AVYUepztiV4fnV0ReH5YQlHpdw/9fi3SCArxcU5DNBlV9u+7No1aPNNgPlEsRckwPlyRglDZ7IX0WHLaGGlma+3yEb9UHPtmN110zRQP+If99EMNS9p5LNFmdMj1gYvgULAjX4omSeS9RekxJw5p7bWHWMJZAPlS6AEs4sOjlcVYESipG8c3ePR/VQrNbW5uQappYU9SAe/bWtL3WL/4mj8il1OkNQOXlwbzgI4iKquIhMb1VMHLCHJldVZyqlO+4oyfZeIbW5Dsz+s6s5DAJawjUbfpYQKkygJ74jQPVAwwU52+ryOiRt4wDtbAJCgU54s+M6Tg== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass (sender ip is 165.204.84.17) smtp.rcpttodomain=nongnu.org smtp.mailfrom=amd.com; dmarc=pass (p=quarantine sp=quarantine pct=100) action=none header.from=amd.com; dkim=none (message not signed); arc=none (0) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=amd.com; s=selector1; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=lg2rGPpsazLeYxGfFI2aGtZJDGCcW0nt5cRKeDfWHvw=; b=gxgc8mfNm09EBF/0a7R44VchingygbDoNNZiQ45B0l+i2r5e/WarGrzSoQHN8bd3PBPVOMN+j9H6UaKPu/uarulkHqw6aQPSGbsdFeaNvnuPE9r1ims224AI90NyvTP+a4N6Jx3zYxXHmQmi6wm3pBAD+uePVixZIaxJEkScPaI= X-MS-Exchange-Authentication-Results: mx.microsoft.com 1; spf=pass (sender IP is 165.204.84.17) smtp.mailfrom=amd.com; dkim=none (message not signed) header.d=none;dmarc=pass action=none header.from=amd.com; Received-SPF: pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists1p.gnu.org; Received-SPF: Pass (protection.outlook.com: domain of amd.com designates 165.204.84.17 as permitted sender) receiver=protection.outlook.com; client-ip=165.204.84.17; helo=satlexmb07.amd.com; pr=C From: Michael Roth To: CC: , , , , , Subject: [PATCH v4 1/3] hw/cpu: Add async_run_on_cpu_after_accel() Date: Fri, 30 Oct 2026 07:49:33 -0500 Message-ID: <20261030125228.2160752-2-michael.roth@amd.com> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20261030125228.2160752-1-michael.roth@amd.com> References: <20261030125228.2160752-1-michael.roth@amd.com> MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-Originating-IP: [10.180.168.240] X-ClientProxiedBy: satlexmb07.amd.com (10.181.42.216) To satlexmb07.amd.com (10.181.42.216) X-EOPAttributedMessage: 0 X-MS-PublicTrafficType: Email X-MS-TrafficTypeDiagnostic: SJ1PEPF000023CB:EE_|DSVPR12MB999126:EE_ X-MS-Office365-Filtering-Correlation-Id: 774345f1-0c9d-4ea7-147c-08df3684bdd0 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0; ARA:13230040|36860700016|82310400026|1800799024|376014|30052699003|23010399003|10067099003|11063799006|6133799003|261009223027099003|261028144727099003|261022105027099003|261022075727099003|261021121427099003|56012099006|261026121527099003|261026140227099003|22082099003|18002099003; X-Microsoft-Antispam-Message-Info: C2kGza0RCtDtilLXZ5GY7maZp3kpfLsnTW3BmHfjr7m3GpDDcullLq2/325HdTpOuq9Sb42AlVcnRra7wQv8GdtSJHspM18XPVHKzGpkXpsxgoaE7S7XPYT7MmTjrcfpXQYUGdrC6FHgHWdTiGmjLHje9aChom5VtekYVePTV4BMf8RQOM7SmGfEBexCo7GawPIil3w1pBRjOLpOgQfVklVRVU9Z5MeYqmn+0mNriShhBMJS736xBmHowC9uB+aS8+3zoD9YYl5YuXFQ33igFV/F96gVeLMGu9/xfTUlhcLRkfd3h95V1Vtu2fnVxRbRbrrMEQNhvP6cns1PfP/MBLyMCS63kOdD3pK2RRsc/DYF6drKOAdJgIXlt2xQ7EbFKEPlJ+tqs0X4BYl3rYi66y0+5kw/gDD7YVJ3sVuSXBCpERDwazgXoAW4OAM1V8iLMpgmKvWFPbjuPXhCMqhPbgpgcahR9f4wxGDPux2HVjSS9r4QMDQk18XTdEUKQV7S5t6tzUleQ5AsYgGZx9+g2/jzaZzrvtJNRb6F9sL4LqrK3Xrb4xoq0u17RIr1RH8MtLj08dAp4wuJcEFj3kyubNbr6AAA6OS0KDtYL088W6wkfq2hTSWppkcdyl9in0ZLtQFVKJnuVcL1ZyMQPs1DcvMHEDg2LqUT1mKzu+rE3/yZ1SAux7W8PW2Fh6vFaB/ykoNY71NQ5GFI9mRWDiPwHg== X-Forefront-Antispam-Report: CIP:165.204.84.17; CTRY:US; LANG:en; SCL:1; SRV:; IPV:NLI; SFV:NSPM; H:satlexmb07.amd.com; PTR:InfoDomainNonexistent; CAT:NONE; SFS:(13230040)(36860700016)(82310400026)(1800799024)(376014)(30052699003)(23010399003)(10067099003)(11063799006)(6133799003)(261009223027099003)(261028144727099003)(261022105027099003)(261022075727099003)(261021121427099003)(56012099006)(261026121527099003)(261026140227099003)(22082099003)(18002099003); DIR:OUT; SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: n39cxf+7Rv72k1vX8AfNqcVpjRVFoypg6vX/UvoRoBKOO+CKqkOJcnjmLx8MKB5XNWyNBKEQeZ6/xUmWu41q4HSYr4tSSQaCNSfoiiM8fvsqM/wbS22vsU0p2U6InOP2KxJwd/irNcpmGdG4iOmBvjcGVhPEl9wKV4AT5o0tHTTMKRJ6wpuT8VWldzPQDV4kSlw49fA95W1EZeaT2SCvWiNtgf7f3zrIE5p22+u2b5lmvAR9WP7gOjll4AEutBQmtpbqjwdrBvDiwhtrWSmVVgUIKa/qizU0VecRnIlgDjnGRmkfQU/y734F3lIttbHcsRWiSC7dHMafK2oaCXOGSoa/+KNjFaGyliqVm2uOJPIcJwH6vRZZGOhLF475BQE7ra0A438kRGXmnolyCt4n0vU3r43jk2H/pREJ0/az/tG8KWusUMod/tq0EVrNXCjG X-OriginatorOrg: amd.com X-MS-Exchange-CrossTenant-OriginalArrivalTime: 30 Oct 2026 12:53:05.6738 (UTC) X-MS-Exchange-CrossTenant-Network-Message-Id: 774345f1-0c9d-4ea7-147c-08df3684bdd0 X-MS-Exchange-CrossTenant-Id: 3dd8961f-e488-4e60-8e11-a82d994e183d X-MS-Exchange-CrossTenant-OriginalAttributedTenantConnectingIp: TenantId=3dd8961f-e488-4e60-8e11-a82d994e183d; Ip=[165.204.84.17]; Helo=[satlexmb07.amd.com] X-MS-Exchange-CrossTenant-AuthSource: SJ1PEPF000023CB.namprd02.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Anonymous X-MS-Exchange-CrossTenant-FromEntityHeader: HybridOnPrem X-MS-Exchange-Transport-CrossTenantHeadersStamped: DSVPR12MB999126 Received-SPF: pass client-ip=2a01:111:f403:c107::9; envelope-from=Michael.Roth@amd.com; helo=PH7PR06CU001.outbound.protection.outlook.com X-Spam_score_int: -20 X-Spam_score: -2.1 X-Spam_bar: -- X-Spam_report: (-2.1 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.001, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=ham autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: qemu development List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: qemu-devel-bounces+importer=patchew.org@nongnu.org X-ZohoMail-DKIM: pass (identity @amd.com) X-ZM-MESSAGEID: 1793364823537154100 Content-Type: text/plain; charset="utf-8" For some operations, hypervisors/accelerators like KVM might require calling back into the accelerator code prior to userspace being able to complete handling of certain operations. One common example is I/O emulation where the accelerator call may be necessary to complete pending work on the accelerator side, which then signals completion to userspace via another CPU exit, such is the case with KVM via the existing 'immediate_exit' machinery. In some cases however, userspace may need to perform additional work on behalf of the vCPU after the accelerator exits, requiring some kind of per-vCPU callback mechanism. async_run_on_cpu() already provides something very similar, but it forces an exit from the inner loop, and is processed at the start of the outer loop, so those callbacks might be issued before the accelerator has a chance to get called again. Introduce a new variant, async_run_on_cpu_after_accel(), that is designed to queue up work to be processed after the next accelerator exit, and without unnecessarily forcing an exit from the inner loop. The handling is via process_queued_cpu_accel_work(), which is left to accelerator/arch-specific code to implement in their inner loops where appropriate. KVM will use this general per-vCPU infrastructure to handle callbacks for these cases. Other accelerators may have other uses in the future. Signed-off-by: Michael Roth --- cpu-common.c | 66 +++++++++++++++++++++++++++++++++++++++++++ hw/core/cpu-common.c | 2 ++ include/hw/core/cpu.h | 33 ++++++++++++++++++++++ 3 files changed, 101 insertions(+) diff --git a/cpu-common.c b/cpu-common.c index adb76b3a78..0e735da673 100644 --- a/cpu-common.c +++ b/cpu-common.c @@ -141,6 +141,23 @@ static void queue_work_on_cpu(CPUState *cpu, struct qe= mu_work_item *wi) cpu_exit(cpu); } =20 +/* + * Queue work on a CPU to run after the next accelerator exit. + * + * This helper intentionally leaves the inner loop running rather than for= cing + * an exit via cpu_exit(), since the intention is to immediately call back= into + * the accelerator to process pending events, and then upon exiting issue + * callbacks/notifications to any CPUs that need to complete any work that= is + * pending on that accelerator call/exit. + */ +static void queue_accel_work_on_cpu(CPUState *cpu, struct qemu_work_item *= wi) +{ + assert(wi->free); + qemu_mutex_lock(&cpu->work_mutex); + QSIMPLEQ_INSERT_TAIL(&cpu->accel_work_list, wi, node); + qemu_mutex_unlock(&cpu->work_mutex); +} + void do_run_on_cpu(CPUState *cpu, run_on_cpu_func func, run_on_cpu_data da= ta, QemuMutex *mutex) { @@ -178,6 +195,24 @@ void async_run_on_cpu(CPUState *cpu, run_on_cpu_func f= unc, run_on_cpu_data data) queue_work_on_cpu(cpu, wi); } =20 +void async_run_on_cpu_after_accel(CPUState *cpu, run_on_cpu_func func, + run_on_cpu_data data) +{ + struct qemu_work_item *wi; + + wi =3D g_new0(struct qemu_work_item, 1); + + /* + * Only asynchronous accelerator work items are allowed. I.e. wi->free + * must be true. Subsequent code will assert this. + */ + wi->func =3D func; + wi->data =3D data; + wi->free =3D true; + + queue_accel_work_on_cpu(cpu, wi); +} + /* Wait for pending exclusive operations to complete. The CPU list lock must be held. */ static inline void exclusive_idle(void) @@ -349,6 +384,37 @@ void free_queued_cpu_work(CPUState *cpu) } } =20 +void free_queued_cpu_accel_work(CPUState *cpu) +{ + while (!QSIMPLEQ_EMPTY(&cpu->accel_work_list)) { + struct qemu_work_item *wi =3D QSIMPLEQ_FIRST(&cpu->accel_work_list= ); + QSIMPLEQ_REMOVE_HEAD(&cpu->accel_work_list, node); + assert(wi->free); + g_free(wi); + } +} + +void process_queued_cpu_accel_work(CPUState *cpu) +{ + struct qemu_work_item *wi; + + qemu_mutex_lock(&cpu->work_mutex); + + while (!QSIMPLEQ_EMPTY(&cpu->accel_work_list)) { + wi =3D QSIMPLEQ_FIRST(&cpu->accel_work_list); + QSIMPLEQ_REMOVE_HEAD(&cpu->accel_work_list, node); + + qemu_mutex_unlock(&cpu->work_mutex); + wi->func(cpu, wi->data); + qemu_mutex_lock(&cpu->work_mutex); + + assert(wi->free); + g_free(wi); + } + + qemu_mutex_unlock(&cpu->work_mutex); +} + void process_queued_cpu_work(CPUState *cpu) { struct qemu_work_item *wi; diff --git a/hw/core/cpu-common.c b/hw/core/cpu-common.c index 4f4c87f33a..599963a85d 100644 --- a/hw/core/cpu-common.c +++ b/hw/core/cpu-common.c @@ -304,6 +304,7 @@ static void cpu_common_initfn(Object *obj) qemu_mutex_init(&cpu->work_mutex); qemu_lockcnt_init(&cpu->in_ioctl_lock); QSIMPLEQ_INIT(&cpu->work_list); + QSIMPLEQ_INIT(&cpu->accel_work_list); QTAILQ_INIT(&cpu->breakpoints); QTAILQ_INIT(&cpu->watchpoints); =20 @@ -332,6 +333,7 @@ static void cpu_common_finalize(Object *obj) } #endif free_queued_cpu_work(cpu); + free_queued_cpu_accel_work(cpu); /* If cleanup didn't happen in context to gdb_unregister_coprocessor_a= ll */ if (cpu->gdb_regs) { g_array_free(cpu->gdb_regs, TRUE); diff --git a/include/hw/core/cpu.h b/include/hw/core/cpu.h index 5b7c330047..30cd88eb0f 100644 --- a/include/hw/core/cpu.h +++ b/include/hw/core/cpu.h @@ -523,6 +523,7 @@ struct CPUState { =20 QemuMutex work_mutex; QSIMPLEQ_HEAD(, qemu_work_item) work_list; + QSIMPLEQ_HEAD(, qemu_work_item) accel_work_list; =20 struct CPUAddressSpace *cpu_ases; AddressSpace *as; @@ -968,6 +969,24 @@ void run_on_cpu(CPUState *cpu, run_on_cpu_func func, r= un_on_cpu_data data); */ void async_run_on_cpu(CPUState *cpu, run_on_cpu_func func, run_on_cpu_data= data); =20 +/** + * async_run_on_cpu_after_accel: + * @cpu: The vCPU to run on. + * @func: The function to be executed. + * @data: Data to pass to the function. + * + * Schedules the function @func for execution on the vCPU @cpu asynchronou= sly, + * to be handled only after the next invocation of the configured accelera= tor. + * Unlike async_run_on_cpu(), @func will not be run with the BQL held; tak= ing + * the lock is instead left to @func to handle if needed. + * + * This does not guarantee any sort of expedited exiting from the accelera= tor + * or the inner loop; this aspect is instead left up to + * accelerator/arch-specific code. + */ +void async_run_on_cpu_after_accel(CPUState *cpu, run_on_cpu_func func, + run_on_cpu_data data); + /** * async_safe_run_on_cpu: * @cpu: The vCPU to run on. @@ -1115,12 +1134,26 @@ void cpu_remove_sync(CPUState *cpu); */ void free_queued_cpu_work(CPUState *cpu); =20 +/** + * free_queued_cpu_accel_work() - free all items on CPU accel work queue + * @cpu: The CPU which accel work queue to free. + */ +void free_queued_cpu_accel_work(CPUState *cpu); + /** * process_queued_cpu_work() - process all items on CPU work queue * @cpu: The CPU which work queue to process. */ void process_queued_cpu_work(CPUState *cpu); =20 +/** + * process_queued_cpu_accel_work() - process all items on CPU accel work q= ueue + * @cpu: The CPU which work queue to process. + * + * Must be called without the BQL held. + */ +void process_queued_cpu_accel_work(CPUState *cpu); + /** * cpu_exec_start: * @cpu: The CPU for the current thread. --=20 2.43.0 From nobody Mon Nov 23 04:26:21 2026 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; arc=pass (i=1 dmarc=pass fromdomain=amd.com); dmarc=pass(p=quarantine dis=none) header.from=amd.com ARC-Seal: i=2; a=rsa-sha256; t=1793364826; cv=pass; d=zohomail.com; s=zohoarc; b=Vktk+54gaY42vm2wIp8oH1QRAO50cVQKrqiQmbTroPXCyGbXheQUTH/biO8UGjmzZ25gYBGvrRJ6K7++BsOdlLxBVlMVcNXVIxH4e5RAIjAYuGRdRix9GfDg6pZ7Cqt6DKgarWAq0a6mef8qumhCqOUqseXnWE6XiCg/JJcw22A= ARC-Message-Signature: i=2; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1793364826; h=Content-Type:Content-Transfer-Encoding:Cc:Cc:Date:Date:From:From:In-Reply-To:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:Sender:Subject:Subject:To:To:Message-Id:Reply-To; bh=fAl7WnWk5TD7Ah8mt8vKlHCIhQl1PlsaHUx1rAE524M=; b=HbuP4zH9QGU4mRkTDbsruaKZRflPdpaokzEAqB+XjKDqUQKgivmbzi8JE1PwCkDfHBIUdGjQO0nFZyCFK6/xF1hVhmdF6IfhQPjcWtkC+sJgUFKvhcMVA0OgYNIOsdp3bzxdUWS/68+M2k5mJqB5v0evCvwFraiYI6sjA+xwMw4= ARC-Authentication-Results: i=2; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; arc=pass (i=1 dmarc=pass fromdomain=amd.com); dmarc=pass header.from= (p=quarantine dis=none) Return-Path: Received: from lists1p.gnu.org (lists1p.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1793364826405284.4478972367091; Fri, 30 Oct 2026 05:53:46 -0700 (PDT) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists1p.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1xMm6y-0000s8-UN; Fri, 30 Oct 2026 08:53:36 -0400 Received: from eggs.gnu.org ([2001:470:142:3::10]) by lists1p.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1xMm6x-0000rd-5r for qemu-devel@nongnu.org; Fri, 30 Oct 2026 08:53:35 -0400 Received: from mail-westcentralusazlp170100005.outbound.protection.outlook.com ([2a01:111:f403:c112::5] helo=CY7PR03CU001.outbound.protection.outlook.com) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1xMm6v-0002xP-79 for qemu-devel@nongnu.org; Fri, 30 Oct 2026 08:53:34 -0400 Received: from SJ0PR05CA0180.namprd05.prod.outlook.com (2603:10b6:a03:339::35) by SAWPR12MB999141.namprd12.prod.outlook.com (2603:10b6:806:4e1::14) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.546.22; Fri, 30 Oct 2026 12:53:26 +0000 Received: from SJ1PEPF000023CD.namprd02.prod.outlook.com (2603:10b6:a03:339:cafe::93) by SJ0PR05CA0180.outlook.office365.com (2603:10b6:a03:339::35) with Microsoft SMTP Server (version=TLS1_3, cipher=TLS_AES_256_GCM_SHA384) id 15.21.569.4 via Frontend Transport; Fri, 30 Oct 2026 12:53:26 +0000 Received: from satlexmb07.amd.com (165.204.84.17) by SJ1PEPF000023CD.mail.protection.outlook.com (10.167.244.8) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.569.4 via Frontend Transport; Fri, 30 Oct 2026 12:53:26 +0000 Received: from localhost (10.180.168.240) by satlexmb07.amd.com (10.181.42.216) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.2.2562.53; Fri, 30 Oct 2026 07:53:25 -0500 ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=oYBna5IYbb3LadpPX0ERPVOi5Pl2db80bd1CWNNztk9nhUFz0kFjaaaCiwdqOUioZjugxCNxTeoglGBAaDXXlNEaygl7hUf91XN9nKRsL6p24xyljPoD9fZ4uKFhtM8DjGo1LnOoGUu/N9v7z2J3Ib6nT9wQTk3X6YUVd2hUAxsOt66pYX4QjKgx6JWaDcoORv6yXOfA6JWsH5DDmhCgHhyZRgxCCQj0bY2MBV7lyyu3zWQpUlsMm0u5lXV4iGo/o6imf77Sib4qiiTWftTz5xFmWlSZmS0+Ewb6zYoU81LjAFgsggrAODI40AbN844sp0EHVq6uzBWt7N1vqC+SDw== 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=fAl7WnWk5TD7Ah8mt8vKlHCIhQl1PlsaHUx1rAE524M=; b=cmLO8VW5nGwdcGUkbONS2yLiakqADMX2qVhhjn3vR5Gv1Qlw8+TH0n/HKrMneHPKEBmWfldP093bJoDieS2tVPYeC7Q+O1N9je6IJMwSfsAVDXVGERKg6BZOEHi/Hz5T7d25bFYKOPXIHXQVBqVb1JFqRTOrwjS0p6ssWQzNRTLG2yblmGPyiDf91wXpmELJvLp2jxydZ5fkfCPF/cuUjbtP344vzZZP918fKAeW7VNjNuZu2cfXCGYeDTLCsPeupPsk034qOJKFn75qEUcECNJbyi+u8GT/8UncLEyLNNttho/hJkHtotWeqYvkZhelWUAwi2H4WhBILY3+zOUvxg== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass (sender ip is 165.204.84.17) smtp.rcpttodomain=nongnu.org smtp.mailfrom=amd.com; dmarc=pass (p=quarantine sp=quarantine pct=100) action=none header.from=amd.com; dkim=none (message not signed); arc=none (0) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=amd.com; s=selector1; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=fAl7WnWk5TD7Ah8mt8vKlHCIhQl1PlsaHUx1rAE524M=; b=0HO2yeOxqwpq2ffFuO0hrNDN5uWXNJne4HzDVzcBygDJOwB8X02ZhwixPYW+XaTnj4dXd2RHjhKhmub56SktPCYEdNsG/OAkMUJO6IGfyytDDEhPzVI1/p8vdoc8106JZ5Qif9aDzYeiuPJ5dxXYjanEKA70VM4BhT4u4zNwsfI= X-MS-Exchange-Authentication-Results: mx.microsoft.com 1; spf=pass (sender IP is 165.204.84.17) smtp.mailfrom=amd.com; dkim=none (message not signed) header.d=none;dmarc=pass action=none header.from=amd.com; Received-SPF: pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists1p.gnu.org; Received-SPF: Pass (protection.outlook.com: domain of amd.com designates 165.204.84.17 as permitted sender) receiver=protection.outlook.com; client-ip=165.204.84.17; helo=satlexmb07.amd.com; pr=C From: Michael Roth To: CC: , , , , , Subject: [PATCH v4 2/3] accel/kvm: Add kvm_immediate_exit callback infrastructure Date: Fri, 30 Oct 2026 07:49:34 -0500 Message-ID: <20261030125228.2160752-3-michael.roth@amd.com> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20261030125228.2160752-1-michael.roth@amd.com> References: <20261030125228.2160752-1-michael.roth@amd.com> MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-Originating-IP: [10.180.168.240] X-ClientProxiedBy: satlexmb07.amd.com (10.181.42.216) To satlexmb07.amd.com (10.181.42.216) X-EOPAttributedMessage: 0 X-MS-PublicTrafficType: Email X-MS-TrafficTypeDiagnostic: SJ1PEPF000023CD:EE_|SAWPR12MB999141:EE_ X-MS-Office365-Filtering-Correlation-Id: 3f942328-c2a0-4b81-32e6-08df3684ca22 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0; ARA:13230040|376014|36860700016|1800799024|23010399003|82310400026|22082099003|261026121527099003|18002099003|10067099003|11063799006|261028144727099003|261022105027099003|261022075727099003|261021121427099003|261009223027099003|261026140227099003|56012099006; X-Microsoft-Antispam-Message-Info: BvcHwh5iBYFyCgddOKpsWTMoz8iTf7ZrP2BItZBC//LIyebi6hGmknRA1AsByVEYPNiaLC7aaCGXLV1lojXinnI5zcf2Zn+PQZiqjqtHAzcd43Ar/ROff2ZoUGRDrfhdhx5eF9I5r6MP6kA+bFwCF09B214IgYljq79/UH4U1dnv8Sfx1sRW7xOGIRm/V9ldeZPWiwfakd6aSe5jzCUfbQ83CMgcN7LwsnfvqlI5TMkwP0Ksfa1Laz3BbjY0AA4Rir7072O5SqAyfWSVWYCuBiUokeBCc/PFtO05ZhBgEPWgUxppZPJH31WIHLLcVk0gTZ9iIh8cXIbx3mr3paEn8FLRK3S3NymrOZ7Jf7R8xiH0Od1W7Nf596aVeClI6BLYFf3j2NHLk6NNBxQ9LGdjKfWA0G8txFvQ12jdBTgd72h+j7wJ1P8687behEheBesCor2QXqSYq1517C4iCzAFy7q7ixagapee8nuK0wXxAb9T2SeCz9u8NwlUidPOztlRbUXjkzvcmck9RXIUlbnuPiIoSvOt1hTn7vSOHC67bzcoAKLlS4yxzG0Tmptem77Af1Uq2Luqh3+PT9pV1rotSfMldgT8nmGZQoJS2MC0/zJxCBGc1r/rn4fqe6P7cJ50diV+1TAUlGdoL+wzPJGhTyC4zIX0YHOORNSZsD6pbKg4LjLtn4JlV9DC9Kd/YF09DRe+odWBy++c7ITrcBUwEw== X-Forefront-Antispam-Report: CIP:165.204.84.17; CTRY:US; LANG:en; SCL:1; SRV:; IPV:NLI; SFV:NSPM; H:satlexmb07.amd.com; PTR:InfoDomainNonexistent; CAT:NONE; SFS:(13230040)(376014)(36860700016)(1800799024)(23010399003)(82310400026)(22082099003)(261026121527099003)(18002099003)(10067099003)(11063799006)(261028144727099003)(261022105027099003)(261022075727099003)(261021121427099003)(261009223027099003)(261026140227099003)(56012099006); DIR:OUT; SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: jZLq0RKVJtIeBd6XHOqQyFX37Zzq+dtqChlEUvhJy7LJ82WA2KFcwyRVOHak0YEaSmT7BJyWBxCSsfAMyAZPMMgW2fO1OuW+Ce6uTErD+JoomNnjBSjcgiksNWJxm1uN+LUc4xQEJPA6Gwe3vvUVLb0tGgsvEWs1UEyfmIQiDtNgHy2LWJtqrEZqBE89Q2lCYrRmgjdTiqdWmupQYYNB9hQCYspuoNVK4WeSds/WvPL8DqFULQta/2nfnP1cqQAItAWHwYPPH5lxt+ED5ENtWuSjTsVQlXuSSZFYgheLRB+qP/ojHfy65YQ9x+B9TZyrapKmWKCti+sLxe3OmUCrMSduZy5nBwwxsn3yoIW+xmWxQTt/5Pop42Fet4T1lfZ9vH3BcO+fBzwbyEx++cXWfJ6S8UxLp9rL04JCljOclmh6+9RKbWWY9U8gudLSOWVp X-OriginatorOrg: amd.com X-MS-Exchange-CrossTenant-OriginalArrivalTime: 30 Oct 2026 12:53:26.3461 (UTC) X-MS-Exchange-CrossTenant-Network-Message-Id: 3f942328-c2a0-4b81-32e6-08df3684ca22 X-MS-Exchange-CrossTenant-Id: 3dd8961f-e488-4e60-8e11-a82d994e183d X-MS-Exchange-CrossTenant-OriginalAttributedTenantConnectingIp: TenantId=3dd8961f-e488-4e60-8e11-a82d994e183d; Ip=[165.204.84.17]; Helo=[satlexmb07.amd.com] X-MS-Exchange-CrossTenant-AuthSource: SJ1PEPF000023CD.namprd02.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Anonymous X-MS-Exchange-CrossTenant-FromEntityHeader: HybridOnPrem X-MS-Exchange-Transport-CrossTenantHeadersStamped: SAWPR12MB999141 Received-SPF: pass client-ip=2a01:111:f403:c112::5; envelope-from=Michael.Roth@amd.com; helo=CY7PR03CU001.outbound.protection.outlook.com X-Spam_score_int: -20 X-Spam_score: -2.1 X-Spam_bar: -- X-Spam_report: (-2.1 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.001, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, SPF_HELO_PASS=-0.001, SPF_PASS=-0.001 autolearn=ham autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: qemu development List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: qemu-devel-bounces+importer=patchew.org@nongnu.org X-ZohoMail-DKIM: pass (identity @amd.com) X-ZM-MESSAGEID: 1793364827537158500 Content-Type: text/plain; charset="utf-8" Provide a generic mechanism so that users of struct kvm_run's 'immediate_exit' flag can register a callback that can be issued after returning from KVM. Utilize the recently-added async_run_on_cpu_after_accel() interface, with a small wrapper to set the 'immediate_exit' flag upon queuing of any new callbacks. As with async_run_on_cpu_after_accel(), these callbacks are not run with the BQL held; that is left to individual callback implementations when needed. Signed-off-by: Michael Roth Signed-off-by: Melody Wang --- accel/kvm/kvm-all.c | 21 +++++++++++++++++++++ include/system/kvm.h | 11 +++++++++++ 2 files changed, 32 insertions(+) diff --git a/accel/kvm/kvm-all.c b/accel/kvm/kvm-all.c index db8fba53f3..fd908f9b51 100644 --- a/accel/kvm/kvm-all.c +++ b/accel/kvm/kvm-all.c @@ -3449,6 +3449,19 @@ out_unref: return ret; } =20 +/* + * Queue up CPU work to run after the next call to KVM_RUN. + * + * Requires KVM_CAP_IMMEDIATE_EXIT. + */ +void kvm_add_immediate_exit_callback(CPUState *cpu, run_on_cpu_func cb, + run_on_cpu_data data) +{ + assert(kvm_immediate_exit); + async_run_on_cpu_after_accel(cpu, cb, data); + kvm_cpu_kick(cpu); +} + int kvm_cpu_exec(CPUState *cpu) { struct kvm_run *run =3D cpu->kvm_run; @@ -3511,6 +3524,14 @@ int kvm_cpu_exec(CPUState *cpu) if (run_ret =3D=3D -EINTR || run_ret =3D=3D -EAGAIN) { trace_kvm_io_window_exit(); kvm_eat_signals(cpu); + /* + * This will process any events queued by + * kvm_add_immediate_exit_callback(). This is intentionall= y run + * after the 'immediate_exit' field is cleared by + * kvm_eat_signals() so that queued accel work can requeue + * itself if needed. + */ + process_queued_cpu_accel_work(cpu); ret =3D EXCP_INTERRUPT; break; } diff --git a/include/system/kvm.h b/include/system/kvm.h index d29624034c..2c08992bce 100644 --- a/include/system/kvm.h +++ b/include/system/kvm.h @@ -21,6 +21,7 @@ #include "qemu/accel.h" #include "accel/accel-route.h" #include "qom/object.h" +#include "hw/core/cpu.h" =20 #ifdef COMPILING_PER_TARGET # ifdef CONFIG_KVM @@ -594,4 +595,14 @@ void kvm_vcpufd_add_change_notifier(NotifierWithReturn= *n); */ void kvm_vcpufd_remove_change_notifier(NotifierWithReturn *n); =20 +/** + * kvm_add_immediate_exit_callback - register a callback to be performed a= fter + * the next call to KVM_RUN (with immediate_exit set via kvm_cpu_kick()). + * @cpu: CPU to run the callback on. + * @cb: The callback to run. + * @data: The data to pass to the callback. + */ +void kvm_add_immediate_exit_callback(CPUState *cpu, run_on_cpu_func cb, + run_on_cpu_data data); + #endif --=20 2.43.0 From nobody Mon Nov 23 04:26:21 2026 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; arc=pass (i=1 dmarc=pass fromdomain=amd.com); dmarc=pass(p=quarantine dis=none) header.from=amd.com ARC-Seal: i=2; a=rsa-sha256; t=1793364849; cv=pass; d=zohomail.com; s=zohoarc; b=UsKlQ01Ni2bjDxwGZfQuO37FUmChs6Ax3iBn6jGxSGJn2dhV9HvQZGL+R2R/1btdO9mnTfh4Buh9L/jCRTcKrHzMtIHrc3MPPVp7reqjc7f3+ijqfLtdE03tKCaVhNmDu07EgSb/NxkEUXESx23OyjfIbd9oeSU7wfcFAlkoaCg= ARC-Message-Signature: i=2; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1793364849; h=Content-Type:Content-Transfer-Encoding:Cc:Cc:Date:Date:From:From:In-Reply-To:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:Sender:Subject:Subject:To:To:Message-Id:Reply-To; bh=bJLhspjSFr91ITYMgB/nJTNiPEjtjXOY7/FSIk3c3GY=; b=SfAvnao1AiNXDAHJQUmf0m06bA4/IGS79DRxYopvFPYonPR/0zW7B3bdSb425giOnswmejDL04am3EiyYIN7rWlKHWoCT277M/SjAcVKcf0KAGfzHUgR0Uns592617l3EiT3WYUHtHbPsvL0Q0Fi4VGxH77NUIBaqxOjIMcB4po= ARC-Authentication-Results: i=2; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; arc=pass (i=1 dmarc=pass fromdomain=amd.com); dmarc=pass header.from= (p=quarantine dis=none) Return-Path: Received: from lists1p.gnu.org (lists1p.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1793364849042356.98509427964814; Fri, 30 Oct 2026 05:54:09 -0700 (PDT) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists1p.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1xMm7Q-0001Zm-Gk; Fri, 30 Oct 2026 08:54:04 -0400 Received: from eggs.gnu.org ([2001:470:142:3::10]) by lists1p.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1xMm7M-0001Se-G4 for qemu-devel@nongnu.org; Fri, 30 Oct 2026 08:54:00 -0400 Received: from mail-southcentralusazlp170120001.outbound.protection.outlook.com ([2a01:111:f403:c10d::1] helo=SN4PR2101CU001.outbound.protection.outlook.com) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1xMm7H-0002zE-MY for qemu-devel@nongnu.org; Fri, 30 Oct 2026 08:54:00 -0400 Received: from SJ0PR05CA0168.namprd05.prod.outlook.com (2603:10b6:a03:339::23) by SA3PR12MB7781.namprd12.prod.outlook.com (2603:10b6:806:31a::13) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.569.10; Fri, 30 Oct 2026 12:53:47 +0000 Received: from SJ1PEPF000023D0.namprd02.prod.outlook.com (2603:10b6:a03:339:cafe::4) by SJ0PR05CA0168.outlook.office365.com (2603:10b6:a03:339::23) with Microsoft SMTP Server (version=TLS1_3, cipher=TLS_AES_256_GCM_SHA384) id 15.21.546.16 via Frontend Transport; Fri, 30 Oct 2026 12:53:47 +0000 Received: from satlexmb07.amd.com (165.204.84.17) by SJ1PEPF000023D0.mail.protection.outlook.com (10.167.244.4) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.569.4 via Frontend Transport; Fri, 30 Oct 2026 12:53:47 +0000 Received: from localhost (10.180.168.240) by satlexmb07.amd.com (10.181.42.216) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.2.2562.53; Fri, 30 Oct 2026 07:53:46 -0500 ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=v+Kfk1PL/CP3BKfs5JKDv8dlWhqm5WxJ8HnNAKfJFTmjgfwwvhy8QmG67ATeeq8Pi+kTjsy7y3dBJsDtvKCtcXyB4MjDSV7KfFSx/J1wV1M7JoVc4CJ2zhVzmTUVjoxmtGSjHjnzuWlMvHEoCcBI+G6B2dP+0MfQUVLHHHcwqmXxk+kUrmg/hhtAZxctPBY5618YR8tm4PnoZl1ThtHYK/+ZvzpUKqdx7GsxQdWRo4RcwHlzWt5Fr8tepX7pqVSxQgwm757HDA+FJEPIbA5HPgTfAtdhP/HTco3lG7lKQb2b95/P5uIIZZEOLUZJaLcUZRN9tleo1EDCmkKwi1OhiQ== 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=bJLhspjSFr91ITYMgB/nJTNiPEjtjXOY7/FSIk3c3GY=; b=yFinYuHHrjl7UbaKF6jGW16zPXDUrkex8/xSrNvMgbZ4PKDZUZIZzMUvRtip8YhpszQDhplCkGwoS2s0bJby0vMbBGsd7s5pg67bfK683+MJ8b4aWdclSJGS1FTFcbSJPeJ9WG4+4IIUErN5J6CwxTiioeEqCyWNUT5dBmCubN+JEYjn2/6/xUSw3T8cJHjdRR34lDwKF6yNDlSqb7BUMxYhNefRUCZd8WQJox7G+l8nGc8SJbjzeLvjuv22zcXgjxG3x2BJIj2D/WaC3xddFJALevSgvNKlHrb3nIYgitOAuPp3nROkaus3Uq5xVhZ56Kp5z8kdtFixDnoiahcmng== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass (sender ip is 165.204.84.17) smtp.rcpttodomain=nongnu.org smtp.mailfrom=amd.com; dmarc=pass (p=quarantine sp=quarantine pct=100) action=none header.from=amd.com; dkim=none (message not signed); arc=none (0) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=amd.com; s=selector1; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=bJLhspjSFr91ITYMgB/nJTNiPEjtjXOY7/FSIk3c3GY=; b=3hsU2mz4pUZJPJV/ffiUQzlqfiO4MRh5s11TCm4BAOZIe9H56CQ127geysyFQZ1SxSB5f9fUWXfuybDy+09EKajxKmYs/+BDzfMVnnzijSxlc/rbyN6Wg8Rb5Yd4BCIC79R0LztMSB+fBdXNqT/X8bKRvIrdkv9+j5BTQzDYIbs= X-MS-Exchange-Authentication-Results: mx.microsoft.com 1; spf=pass (sender IP is 165.204.84.17) smtp.mailfrom=amd.com; dkim=none (message not signed) header.d=none;dmarc=pass action=none header.from=amd.com; Received-SPF: pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists1p.gnu.org; Received-SPF: Pass (protection.outlook.com: domain of amd.com designates 165.204.84.17 as permitted sender) receiver=protection.outlook.com; client-ip=165.204.84.17; helo=satlexmb07.amd.com; pr=C From: Michael Roth To: CC: , , , , , Subject: [PATCH v4 3/3] i386/sev: Add KVM_EXIT_SNP_REQ_CERTS support for certificate-fetching Date: Fri, 30 Oct 2026 07:49:35 -0500 Message-ID: <20261030125228.2160752-4-michael.roth@amd.com> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20261030125228.2160752-1-michael.roth@amd.com> References: <20261030125228.2160752-1-michael.roth@amd.com> MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-Originating-IP: [10.180.168.240] X-ClientProxiedBy: satlexmb07.amd.com (10.181.42.216) To satlexmb07.amd.com (10.181.42.216) X-EOPAttributedMessage: 0 X-MS-PublicTrafficType: Email X-MS-TrafficTypeDiagnostic: SJ1PEPF000023D0:EE_|SA3PR12MB7781:EE_ X-MS-Office365-Filtering-Correlation-Id: c30082f1-0a36-4e93-79ca-08df3684d685 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0; ARA:13230040|36860700016|82310400026|23010399003|376014|1800799024|6133799003|22082099003|18002099003|32116099003|3023799007|13003099007|56012099006|11063799006|261026121527099003|261026140227099003|261028144727099003|10067099003|261021135927099003|261021123027099003|261021121427099003|261022113327099003|261022105027099003|261022075727099003|261009223027099003; X-Microsoft-Antispam-Message-Info: WtC98MeKI2NWEbgj3c+CMAr9axh4POX2JuJ8ceiPFbAT89DktjJpam1PVZSKFR7cUs/9rXpBGCOys/LTxAh1oQ/pHIxkNSnEUmojVwQjjo0uQBlEA6XDtWr2Bsudm6EgfQQqRN5BIB8KEfjrBWD28R7dFYR2sC/0ND9sFJvQDeponQYDmf8QiOfmx42cmmgqUZa4rdY+BeETO8TYW+Eg1spDFTMEE3Pn2Ue3C35jiTvnE5LtXR+bhsUweyVWPHW3OS7H403lZa401g3Ir7ieYDWgZhXfXrmWKpbTQZ5r5xjneKxD0YQ4ncZ07ShfWSFOKhUeUCf59G2z8wnbg+rMP4DAwQUn4fGeV+N53juBUDS9z+Nti8P5ltQrq2za+An8JK8gMkrXyInyisQ87qWmDLM/fLHMv/7jpf4suOWCaWSInC/0QHgfw1ZqR5955lakgE3TDdEIAz6d0M59zNtJVPhUMxX/ciFTKA5zaLLX43/x6d9zxLk3Hvx113vzIvQ2qaEuznwOHyXHMS8uYi7Bje3PmDkz7eYroyjGrdhkUUIcAmLP7OuzJFtcNNgcDPHpvg51Fkat1ACMUQlfnbeaTnOoKoQXtRgxJkWuTq+rnCOdphhfdSAj77GO5oH3uhk8ubm3b47Esb2j1jHmJ3puC5BHKhfmy9S47AQKLe85iH1+aKyyFDeW5v6uUQ8oFQTdYjGkhf94oFHzQbNVwKZ5ig== X-Forefront-Antispam-Report: CIP:165.204.84.17; CTRY:US; LANG:en; SCL:1; SRV:; IPV:NLI; SFV:NSPM; H:satlexmb07.amd.com; PTR:InfoDomainNonexistent; CAT:NONE; SFS:(13230040)(36860700016)(82310400026)(23010399003)(376014)(1800799024)(6133799003)(22082099003)(18002099003)(32116099003)(3023799007)(13003099007)(56012099006)(11063799006)(261026121527099003)(261026140227099003)(261028144727099003)(10067099003)(261021135927099003)(261021123027099003)(261021121427099003)(261022113327099003)(261022105027099003)(261022075727099003)(261009223027099003); DIR:OUT; SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: I3wURoSYbZp+K+6NFJV+2nPobPYBD1ZHKeWxJIl/uhzvDOpi1YduflVbA+cuLCrfywNaqP8xl7Ggam2Ee3iNIn5fMpUaAt0cr1XSxF7nt0lKJEh//pgglv2h3dp46ON7lCABIRsudArYaU6HhGKE5Id3jhoTNP7TbxhFV/2XKV2CRdnN5ByfK0N+Prnv/Q+UlEJvQo/ZXjQOe2jRUXUvES/uh+4qlkn9ESxw08q6qxa6OehIr4wAcgTMPDqA94bfQgm00sWElitxmr40gErThO2225ltknF3ZG8H9wBK6Pqad9j7TP4qOXSBr/q2cmJA8LDpMtemIJanHruixB+D6OldftLU8ybK0MHcbSgTt/wxyDMfEBoZi5g6yuExpuoGZQ+eFIME0E+opxuyR3r8iwHeUnz7/MjpRBlQT1k4oz50422iuywAbx5LweoXXkPZ X-OriginatorOrg: amd.com X-MS-Exchange-CrossTenant-OriginalArrivalTime: 30 Oct 2026 12:53:47.1267 (UTC) X-MS-Exchange-CrossTenant-Network-Message-Id: c30082f1-0a36-4e93-79ca-08df3684d685 X-MS-Exchange-CrossTenant-Id: 3dd8961f-e488-4e60-8e11-a82d994e183d X-MS-Exchange-CrossTenant-OriginalAttributedTenantConnectingIp: TenantId=3dd8961f-e488-4e60-8e11-a82d994e183d; Ip=[165.204.84.17]; Helo=[satlexmb07.amd.com] X-MS-Exchange-CrossTenant-AuthSource: SJ1PEPF000023D0.namprd02.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Anonymous X-MS-Exchange-CrossTenant-FromEntityHeader: HybridOnPrem X-MS-Exchange-Transport-CrossTenantHeadersStamped: SA3PR12MB7781 Received-SPF: pass client-ip=2a01:111:f403:c10d::1; envelope-from=Michael.Roth@amd.com; helo=SN4PR2101CU001.outbound.protection.outlook.com X-Spam_score_int: -20 X-Spam_score: -2.1 X-Spam_bar: -- X-Spam_report: (-2.1 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.001, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, SPF_HELO_PASS=-0.001, SPF_PASS=-0.001 autolearn=ham autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: qemu development List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: qemu-devel-bounces+importer=patchew.org@nongnu.org X-ZohoMail-DKIM: pass (identity @amd.com) X-ZM-MESSAGEID: 1793364849868158500 Content-Type: text/plain; charset="utf-8" The GHCB specification[1] defines a VMGEXIT-based Guest Request hypercall to allow an SNP guest to issue encrypted requests directly to SNP firmware to do things like query the attestation report for the guest. These are generally handled purely in the kernel. In some cases, it's useful for the host to be able to additionally supply the certificate chain for the signing key that SNP firmware uses to sign these attestation reports. To allow for this, the GHCB specification defines an Extended Guest Request where this certificate data (along with other accompanying data) can be provided in a special format described in the GHCB spec. This certificate data may be global or guest-specific depending on how the guest was configured. Rather than providing interfaces to manage these within the kernel, KVM provides a new KVM_EXIT_SNP_REQ_CERTS exit to request the certificate contents from userspace. Implement support for that in QEMU. To synchronize delivery of the certificates to the guest in a way where they will not be rendered invalid by updates to SNP firmware or attestation signing/endorsement keys by management tools outside the purview of QEMU, it is expected by users of KVM_EXIT_SNP_REQ_CERTS to obtain a shared/read lock on the certificate file prior to delivering them back to KVM. Only after this will the attestation report be retrieved from firmware and bundled with the certificate data, so QEMU must continue to hold the file lock until KVM confirms that the attestation report has been retrieved/bundled. This confirmation is done by way of the kvm_immediate_exit callback infrastructure that was introduced in a prior commit. Once the callback is issued (after the next KVM_RUN), the attestation report will have been fetched, so the report and certificate data fetched by QEMU should be consistent with one another, and the certificate lock can then be released. The included documentation updates have more details on how this is handled. [1] "Guest Hypervisor Communication Block (GHCB) Standardization", https://www.amd.com/en/developer/sev.html Co-developed-by: Melody Wang Signed-off-by: Melody Wang Signed-off-by: Michael Roth Acked-by: Markus Armbruster --- docs/system/i386/amd-memory-encryption.rst | 77 +++++ qapi/qom.json | 23 +- target/i386/kvm/kvm.c | 10 + target/i386/sev-system-stub.c | 5 + target/i386/sev.c | 363 +++++++++++++++++++++ target/i386/sev.h | 3 +- 6 files changed, 479 insertions(+), 2 deletions(-) diff --git a/docs/system/i386/amd-memory-encryption.rst b/docs/system/i386/= amd-memory-encryption.rst index 6c23f3535f..ea9ba43ab6 100644 --- a/docs/system/i386/amd-memory-encryption.rst +++ b/docs/system/i386/amd-memory-encryption.rst @@ -228,6 +228,83 @@ schema for the 'sev-snp-guest' object):: -machine ...,confidential-guest-support=3Dsev0 \ -object sev-snp-guest,id=3Dsev0,cbitpos=3D51,reduced-phys-bits=3D1 =20 +Certificate-fetching (SEV-SNP) +------------------------------ + +When an SEV-SNP guest requests an attestation report from the host, it may +optionally request that the host also deliver the certificates (and +potentially other accompanying data) as part of the response. + +QEMU can be configured to provide this certificate data in the following +manner:: + + # ${QEMU} \ + -machine ...,confidential-guest-support=3Dsev0 \ + -object sev-snp-guest,id=3Dsev0,cbitpos=3D51,reduced-phys-bits=3D1,cer= ts-filename=3D + +where the format of the file is defined in the SEV-ES Guest-Hypervisor +Communication Block Standardization (GHCB) v2.04, section 4.1.8.1, as:: + + Returned certificates are identified in a table starting at offset 0x0 of + [the file]. Each entry consists of a 16-byte GUID, a 4-byte offset from + [the file] to where the certificate data starts and a 4-byte length + representing the length of the certificate data. The table is terminated + with an entry containing all zeroes for the GUID, offset and length. + + struct cert_table { + struct { + unsigned char guid[16]; + uint32 offset; + uint32 length; + } cert_table_entry[]; + }; + +Because QEMU supplies the certificate to the hypervisor prior to the +hypervisor actually issuing an attestation request, there is potential for +the certificate data to become stale due to a firmware upgrade or other +host management activities. The ioctl which enables certificate-fetching +support via the KVM hypervisor, KVM_SEV_SNP_ENABLE_REQ_CERTS, documents +the following suggested scheme as part of its Linux documentation (v7.3 +at the time of this writing), and it is highly recommended that all softwa= re +interacting with these certificates, or performing operations that may +affect their validity, adopt this same scheme for interoperability:: + + The recommended scheme to do this is to use file locking (e.g. via + fcntl()'s F_OFD_SETLK) in the following manner: + + - Prior to obtaining/providing certificate data as part of servicing an + exit type of ``KVM_EXIT_SNP_REQ_CERTS``, the VMM should obtain a + shared/read or exclusive/write lock on the certificate blob file bef= ore + reading it and returning it to KVM, and continue to hold the lock un= til + the attestation request is actually sent to firmware. To facilitate + this, the VMM can set the ``immediate_exit`` flag of kvm_run just af= ter + supplying the certificate data, and just before resuming the vCPU. + This will ensure the vCPU will exit again to userspace with ``-EINTR= `` + after it finishes fetching the attestation request from firmware, at + which point the VMM can safely drop the file lock. + + - Tools/libraries that perform updates to SNP firmware TCB values or + endorsement keys (e.g. via /dev/sev interfaces such as ``SNP_COMMIT`= `, + ``SNP_SET_CONFIG``, or ``SNP_VLEK_LOAD``, see + Documentation/virt/coco/sev-guest.rst for more details) in such a way + that the certificate blob needs to be updated, should similarly take= an + exclusive lock on the certificate blob for the duration of any updat= es + to endorsement keys or the certificate blob contents to ensure that + VMMs using the above scheme will not return certificate blob data th= at + is out of sync with the endorsement key used by firmware at the time + the attestation request is actually issued. + + This scheme is recommended so that tools can use a fairly generic/natural + approach to synchronizing firmware/certificate updates via file-locking, + which should make it easier to maintain interoperability across + tools/VMMs/vendors. + +As such, QEMU implements this same scheme by waiting for a read-lock on the +file containing the certificate data before supplying any data it contains. +In order to ensure that the lock is not released until after the hypervisor +is finished fetching the attestation report for the guest, the lock is held +until a subsequent exit from the hypervisor that indicates the attestation +report has already been fetched, at which point QEMU will drop the lock. =20 Debugging --------- diff --git a/qapi/qom.json b/qapi/qom.json index 4810d53e58..065c3463bc 100644 --- a/qapi/qom.json +++ b/qapi/qom.json @@ -1104,6 +1104,25 @@ # @tsc-frequency: set secure TSC frequency. Only valid if Secure TSC # is enabled (default: zero) (since 11.1) # +# @certs-filename: Certificate data that can be passed to guests as +# part of an attestation request. See the +# :doc:`/system/i386/amd-memory-encryption` documentation for more +# details on the usage and file format. +# (default: none) (since: 11.2) +# +# @certs-timeout: Maximum time in milliseconds to wait to obtain a +# read lock on the certificate file specified by @certs-filename. +# This is not a cumulative value and only affects how long QEMU +# waits before returning execution to the vCPU and informing the +# guest of the timeout, so the guest can still continue retrying +# for as long as it likes, which for Linux guests at the time of +# this writing will be about 60 seconds before the guest gives +# up and disables further requests. If this guest-side timeout is +# insufficient, set this higher to allow more time to fetch the +# certificate. If the guest-side timeout is sufficient, +# set this lower to reduce the likelihood of soft lockups in the +# guest. (default: 100) (since: 11.2) +# # Since: 9.1 ## { 'struct': 'SevSnpGuestProperties', @@ -1117,7 +1136,9 @@ '*host-data': 'str', '*vcek-disabled': 'bool', '*secure-tsc': 'bool', - '*tsc-frequency': 'uint32' } } + '*tsc-frequency': 'uint32', + '*certs-filename': 'str', + '*certs-timeout': 'int' } } =20 ## # @TdxGuestProperties: diff --git a/target/i386/kvm/kvm.c b/target/i386/kvm/kvm.c index 072da8b9f1..4a0ab6c6eb 100644 --- a/target/i386/kvm/kvm.c +++ b/target/i386/kvm/kvm.c @@ -6651,6 +6651,16 @@ int kvm_arch_handle_exit(CPUState *cs, struct kvm_ru= n *run) break; } ret =3D 0; + break; + case KVM_EXIT_SNP_REQ_CERTS: + if (!sev_snp_enabled()) { + error_report("KVM: Encountered a certificate request exit for = a " + "non-SEV-SNP guest."); + ret =3D -1; + } else { + ret =3D kvm_handle_snp_req_certs(cs, run); + } + break; default: fprintf(stderr, "KVM: unknown exit reason %d\n", run->exit_reason); diff --git a/target/i386/sev-system-stub.c b/target/i386/sev-system-stub.c index d97536cca1..e53f1bbefc 100644 --- a/target/i386/sev-system-stub.c +++ b/target/i386/sev-system-stub.c @@ -34,3 +34,8 @@ int sev_es_save_reset_vector(void *flash_ptr, uint64_t fl= ash_size) void pc_system_parse_sev_metadata(uint8_t *flash_ptr, size_t flash_size) { } + +int kvm_handle_snp_req_certs(CPUState *cpu, struct kvm_run *run) +{ + g_assert_not_reached(); +} diff --git a/target/i386/sev.c b/target/i386/sev.c index 11072b00dc..028d45a4ec 100644 --- a/target/i386/sev.c +++ b/target/i386/sev.c @@ -186,6 +186,8 @@ struct SevSnpGuestState { uint8_t *id_auth; char *host_data; uint32_t tsc_khz; + char *certs_filename; + int64_t certs_timeout; =20 struct kvm_sev_snp_launch_start kvm_start_conf; struct kvm_sev_snp_launch_finish kvm_finish_conf; @@ -1701,6 +1703,278 @@ sev_snp_launch_finish(SevCommonState *sev_common) sev_set_guest_state(sev_common, SEV_STATE_RUNNING); } =20 +/* + * Cases where -EAGAIN is returned on an error path are expected to termin= ate + * after the next call (e.g. via a qemu_open() error) if they are not tran= sient + * issues. These potentially-transient issues are still logged however, si= nce + * they are not expected on a well-behaved system. + */ +static int open_certs_locked(SevSnpGuestState *sev_snp_guest) +{ + struct stat locked_file, current_file; + int fd, ret; + + fd =3D qemu_open(sev_snp_guest->certs_filename, O_RDONLY, NULL); + if (fd =3D=3D -1) { + error_report_once("Unable to open certificate file: %s", + strerror(errno)); + return -errno; + } + + if (fstat(fd, &locked_file) =3D=3D -1) { + error_report_once("Unable to check status of certificate file: %s", + strerror(errno)); + ret =3D -errno; + goto out_close; + } + + ret =3D qemu_lock_fd(fd, 0, 0, false); + if (ret =3D=3D -EACCES) { + /* + * F_SETLK is documented to potentially return either EACCES or EA= GAIN + * for contended file locks. + */ + ret =3D -EAGAIN; + } else if (ret =3D=3D -EDEADLK) { + error_report_once("Potential deadlock encountered while trying " + "to lock the certificate file"); + ret =3D -EAGAIN; + } + + if (ret) { + if (ret !=3D -EAGAIN) { + error_report_once("Error while trying to lock certificate file= : %s", + strerror(-ret)); + } + goto out_close; + } + + if (stat(sev_snp_guest->certs_filename, ¤t_file) =3D=3D -1) { + error_report_once("Certificate file no longer present: %s", + strerror(errno)); + ret =3D -EAGAIN; + goto out_close; + } + + /* + * Locked files should not be changing; this violates the locking + * protocol assumed by this implementation. Indicate the need to + * retry to the caller, but make sure to log it first. + */ + if (locked_file.st_ino !=3D current_file.st_ino || + locked_file.st_dev !=3D current_file.st_dev) { + error_report_once("Locked certificate file was recreated"); + ret =3D -EAGAIN; + goto out_close; + } + + /* + * The locked file is intact and as-expected, and it has not been repl= aced + * since then, so the fd should be okay to use. + */ + return fd; + +out_close: + close(fd); + return ret; +} + +static void close_certs(int fd) +{ + qemu_unlock_fd(fd, 0, 0); + close(fd); +} + +static ssize_t get_certs_size(int fd) +{ + ssize_t size; + + size =3D lseek(fd, 0, SEEK_END); + if (size =3D=3D -1) { + error_report_once("Error while determining the size of the certifi= cate file: %s", + strerror(errno)); + return -errno; + } + + return size; +} + +static int read_certs(int fd, void *buf, size_t buf_len) +{ + ssize_t n; + + n =3D lseek(fd, 0, SEEK_SET); + if (n =3D=3D -1) { + error_report_once("Error while setting certificate file position: = %s", + strerror(errno)); + return -errno; + } + + while ((n =3D read(fd, buf, buf_len)) !=3D 0) { + if (n =3D=3D -1) { + if (errno =3D=3D EINTR) { + continue; + } + + error_report_once("Error reading the certificate file: %s", + strerror(errno)); + return -errno; + } + buf +=3D n; + buf_len -=3D n; + } + + return 0; +} + +static void snp_release_certs_lock(CPUState *cpu, run_on_cpu_data data) +{ + close_certs(data.host_int); +} + +/* + * NOTE: It is not expected that the guest will call this in a tight loop + * where error reporting would flood logs. A failed certificate fetch resu= lts + * in a failed attestation request, which results in a disabled attestation + * driver in the guest usually. + * + * However, one instance of such an error is usually enough of a clue to + * roughly identify what went wrong. + * + * So, to guard against a malicious guest trying to flood host logs, while + * still providing reasonable debug/error information to the user, use + * error_report_once() throughout this function and its supporting helpers. + */ +int kvm_handle_snp_req_certs(CPUState *cpu, struct kvm_run *run) +{ + struct kvm_exit_snp_req_certs *req_certs =3D &run->snp_req_certs; + SevSnpGuestState *sev_snp_guest; + ssize_t certs_size; + uint32_t npages; + void *guest_buf; + int64_t t0_ms; + hwaddr buf_sz; + int ret, fd; + hwaddr gpa; + + gpa =3D req_certs->gpa; + npages =3D req_certs->npages; + + sev_snp_guest =3D SEV_SNP_GUEST(MACHINE(qdev_get_machine())->cgs); + if (!sev_snp_guest->certs_filename) { + req_certs->ret =3D 0; + return 0; + } + + /* + * By default, any errors encountered below will be forwarded to the g= uest + * as an EIO. This will likely result in the guest disabling its drive= r, but + * it's better than crashing QEMU. + * + * Leave the special cases, SUCCESS/ENOSPC/EAGAIN, to re-set the guest + * return code as-needed. + * + * Errors that are useful for debugging QEMU will still be logged, wit= h care + * to avoid busy/EAGAIN paths/etc. + */ + req_certs->ret =3D EIO; + + /* + * -EAGAIN from open_certs_locked() indicates that a lock could not be + * obtained on the certificate file. It would be possible to set + * req_certs->ret =3D EAGAIN to immediately inform the requesting vCPU= of + * this condition so that it can retry again later, however, Linux gue= sts + * are currently hard-limited to a 60 second timeout, at which point t= hey + * will assume misbehavior and refuse to continue issuing attestation + * requests from that point forward. + * + * Avoid risking triggering this by instead busy-waiting on the QEMU s= ide, + * which allows more time for QEMU to wait on potentially long-running + * tasks like SNP firmware updates/etc. which may be holding an exclus= ive + * lock on the certificate file. + * + * The down-side to doing things this way is that too long of a busy-w= ait + * will result in soft-lockups in the guest, but the guest will otherw= ise + * continue normally afterward. + * + * If the QEMU-side timeout is reached, then just go ahead and indicate + * EAGAIN to the guest, at which point the above-mentioned guest-side + * timeout will trigger if QEMU's timeout exceeds that of the guest. B= ut + * that's better than killing the vCPU, which is the only viable + * alternative at that point. + */ + t0_ms =3D g_get_monotonic_time() / 1000; + + do { + fd =3D open_certs_locked(sev_snp_guest); + + if (fd =3D=3D -EAGAIN) { + int64_t t1_ms =3D g_get_monotonic_time() / 1000; + + if (t1_ms - t0_ms > sev_snp_guest->certs_timeout) { + req_certs->ret =3D EAGAIN; + return 0; + } + + /* + * If some other process (QEMU only ever takes a read lock) ha= s an + * exclusive lock on the certificate file, then it is likely b= ecause + * a firmware update or other long-running operation is taking= place; + * it's a waste to re-try at a high rate. + */ + g_usleep(1000); + } else if (fd < 0) { + return 0; + } + } while (fd =3D=3D -EAGAIN); + + certs_size =3D get_certs_size(fd); + if (certs_size < 0) { + goto err_close; + } + + buf_sz =3D (hwaddr)npages * TARGET_PAGE_SIZE; + if (buf_sz < certs_size) { + /* Communicate to guest that more pages are needed. */ + req_certs->ret =3D ENOSPC; + req_certs->npages =3D DIV_ROUND_UP(certs_size, TARGET_PAGE_SIZE); + goto err_close; + } + + guest_buf =3D address_space_map(&address_space_memory, gpa, &buf_sz, t= rue, + MEMTXATTRS_UNSPECIFIED); + if (!guest_buf) { + error_report_once("Unable to map guest buffer to provide " + "certificate data."); + goto err_close; + } + + if (buf_sz < (hwaddr)npages * TARGET_PAGE_SIZE) { + error_report_once("Unable to map the full guest buffer to provide " + "certificate data."); + address_space_unmap(&address_space_memory, guest_buf, buf_sz, true= , 0); + goto err_close; + } + + ret =3D read_certs(fd, guest_buf, buf_sz); + address_space_unmap(&address_space_memory, guest_buf, buf_sz, true, bu= f_sz); + + if (!ret) { + /* + * Looks good, return the certificate to the guest and prepare to + * release the file lock once KVM signals completion. + */ + kvm_add_immediate_exit_callback(cpu, snp_release_certs_lock, + RUN_ON_CPU_HOST_INT(fd)); + + req_certs->ret =3D 0; + return 0; + } + +err_close: + close_certs(fd); + return 0; +} =20 static void sev_vm_state_change(void *opaque, bool running, RunState state) @@ -2051,6 +2325,41 @@ static int sev_snp_kvm_init(ConfidentialGuestSupport= *cgs, Error **errp) g_free(sev_snp_guest->kernel_hashes_data); sev_snp_guest->kernel_hashes_data =3D NULL; =20 + if (sev_snp_guest->certs_filename) { + unsigned long certs_attr; + struct kvm_device_attr attr =3D { + .group =3D KVM_X86_GRP_SEV, + .attr =3D KVM_X86_SEV_SNP_REQ_CERTS, + .addr =3D (unsigned long) &certs_attr + }; + int ret; + + if (!kvm_check_extension(kvm_state, KVM_CAP_SYS_ATTRIBUTES) || + !kvm_check_extension(kvm_state, KVM_CAP_IMMEDIATE_EXIT)) { + return -EINVAL; + } + + ret =3D kvm_ioctl(kvm_state, KVM_GET_DEVICE_ATTR, &attr); + if (ret < 0) { + error_setg(errp, "Certificate-fetching attribute not present."= ); + return ret; + } + + if (!certs_attr) { + error_setg(errp, "Certificate-fetching attribute not set."); + return -EINVAL; + } + + ret =3D sev_ioctl(SEV_COMMON(sev_snp_guest)->sev_fd, + KVM_SEV_SNP_ENABLE_REQ_CERTS, + NULL, NULL); + if (ret) { + error_setg(errp, "Failed to enable support for SEV-SNP " + "certificate-fetching requests."); + return ret; + } + } + return 0; } =20 @@ -3320,6 +3629,51 @@ sev_snp_guest_set_tsc_frequency(Object *obj, Visitor= *v, const char *name, SEV_SNP_GUEST(obj)->tsc_khz =3D value / 1000; } =20 +static char * +sev_snp_guest_get_certs_filename(Object *obj, Error **errp) +{ + SevSnpGuestState *sev_snp_guest =3D SEV_SNP_GUEST(obj); + + return g_strdup(sev_snp_guest->certs_filename); +} + +static void +sev_snp_guest_set_certs_filename(Object *obj, const char *value, Error **e= rrp) +{ + SevSnpGuestState *sev_snp_guest =3D SEV_SNP_GUEST(obj); + + if (sev_snp_guest->certs_filename) { + g_free(sev_snp_guest->certs_filename); + } + + sev_snp_guest->certs_filename =3D value ? g_strdup(value) : NULL; +} + +static void +sev_snp_guest_get_certs_timeout(Object *obj, Visitor *v, const char *name, + void *opaque, Error **errp) +{ + visit_type_int(v, name, &SEV_SNP_GUEST(obj)->certs_timeout, errp); +} + +static void +sev_snp_guest_set_certs_timeout(Object *obj, Visitor *v, const char *name, + void *opaque, Error **errp) +{ + int64_t value; + + if (!visit_type_int(v, name, &value, errp)) { + return; + } + + if (value < 0) { + error_setg(errp, "Property '%s' must be 0 or greater", name); + return; + } + + SEV_SNP_GUEST(obj)->certs_timeout =3D value; +} + static void sev_snp_guest_class_init(ObjectClass *oc, const void *data) { @@ -3361,6 +3715,12 @@ sev_snp_guest_class_init(ObjectClass *oc, const void= *data) object_class_property_add(oc, "tsc-frequency", "uint32", sev_snp_guest_get_tsc_frequency, sev_snp_guest_set_tsc_frequency, NULL, NULL); + object_class_property_add_str(oc, "certs-filename", + sev_snp_guest_get_certs_filename, + sev_snp_guest_set_certs_filename); + object_class_property_add(oc, "certs-timeout", "int", + sev_snp_guest_get_certs_timeout, + sev_snp_guest_set_certs_timeout, NULL, NULL); } =20 static void @@ -3374,6 +3734,8 @@ sev_snp_guest_instance_init(Object *obj) /* default init/start/finish params for kvm */ sev_snp_guest->kvm_start_conf.policy =3D DEFAULT_SEV_SNP_POLICY; sev_set_feature(SEV_COMMON(sev_snp_guest), SVM_SEV_FEAT_SNP_ACTIVE, tr= ue); + + sev_snp_guest->certs_timeout =3D 100; } =20 static void @@ -3387,6 +3749,7 @@ sev_snp_guest_finalize(Object *obj) g_free(sev_snp_guest->id_auth_base64); g_free(sev_snp_guest->id_auth); g_free(sev_snp_guest->host_data); + g_free(sev_snp_guest->certs_filename); } =20 /* guest info specific to sev-snp */ diff --git a/target/i386/sev.h b/target/i386/sev.h index 7725f92e19..4d9e9b44b4 100644 --- a/target/i386/sev.h +++ b/target/i386/sev.h @@ -15,6 +15,7 @@ #define I386_SEV_H =20 #include "target/i386/svm.h" +#include "system/kvm.h" =20 #ifndef CONFIG_USER_ONLY #include CONFIG_DEVICES /* CONFIG_SEV */ @@ -198,5 +199,5 @@ void pc_system_parse_sev_metadata(uint8_t *flash_ptr, s= ize_t flash_size); =20 uint32_t sev_get_cbit_position(void); uint32_t sev_get_reduced_phys_bits(void); - +int kvm_handle_snp_req_certs(CPUState *cpu, struct kvm_run *run); #endif --=20 2.43.0