From nobody Fri Apr 26 00:20:53 2024 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; dkim=fail header.i=@amazon.com; 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; dmarc=pass(p=none dis=none) header.from=nongnu.org ARC-Seal: i=1; a=rsa-sha256; t=1610453993; cv=none; d=zohomail.com; s=zohoarc; b=VpkHXpe1j6qeQaacfxeD7UTdECJaAoTFktV/3BtuETJ09Vb1Ny5swCxRhslo/vD5dWK/gIDhdbR5KzCrIvvuMvYcfT0uMZ3wHwfYtfDRlhotodyMpXNAxMiBvpOEDGY5os1xnJZlf0a3LbHD+cPyZLXIzllZTcRvHOmNRvWY+cg= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1610453993; h=Content-Type:Cc:Date:From:In-Reply-To:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:Reply-To:References:Sender:Subject:To; bh=0ldrdKg26EexMTh8D0EIzFcuMjN4BVIAzO3jszvttOM=; b=JJD+SIuOpmcgpsnkNcpcTyxXqMsYrdEOjmunzoQAUonsA2Q1h/s6g9GWsrPlvuE0PwbgKz2mGJbHruOHD8Jgwaf150Ch2g6fLiBokgYP9zocroung7p45gNTy8cfJqg0TyuZWAKZ0CSDozImLfCz+rH60DZ4UDrmU655p0wd4BQ= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=fail header.i=@amazon.com; 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; dmarc=pass header.from= (p=none dis=none) header.from= Return-Path: Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1610453993530428.9388351125607; Tue, 12 Jan 2021 04:19:53 -0800 (PST) Received: from localhost ([::1]:58754 helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1kzIeO-0003Af-96 for importer@patchew.org; Tue, 12 Jan 2021 07:19:52 -0500 Received: from eggs.gnu.org ([2001:470:142:3::10]:48440) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1kzIbj-0001nx-Rj for qemu-devel@nongnu.org; Tue, 12 Jan 2021 07:17:07 -0500 Received: from smtp-fw-6002.amazon.com ([52.95.49.90]:21028) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1kzIbW-0001Fx-AR for qemu-devel@nongnu.org; Tue, 12 Jan 2021 07:17:05 -0500 Received: from iad12-co-svc-p1-lb1-vlan2.amazon.com (HELO email-inbound-relay-1d-5dd976cd.us-east-1.amazon.com) ([10.43.8.2]) by smtp-border-fw-out-6002.iad6.amazon.com with ESMTP; 12 Jan 2021 12:16:46 +0000 Received: from EX13D08EUB004.ant.amazon.com (iad12-ws-svc-p26-lb9-vlan3.iad.amazon.com [10.40.163.38]) by email-inbound-relay-1d-5dd976cd.us-east-1.amazon.com (Postfix) with ESMTPS id EB1D9A1B73; Tue, 12 Jan 2021 12:16:43 +0000 (UTC) Received: from uf6ed9c851f4556.ant.amazon.com (10.43.161.68) by EX13D08EUB004.ant.amazon.com (10.43.166.158) with Microsoft SMTP Server (TLS) id 15.0.1497.2; Tue, 12 Jan 2021 12:16:29 +0000 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=amazon.com; i=@amazon.com; q=dns/txt; s=amazon201209; t=1610453814; x=1641989814; h=from:to:cc:subject:date:message-id:in-reply-to: references:mime-version; bh=0ldrdKg26EexMTh8D0EIzFcuMjN4BVIAzO3jszvttOM=; b=PbQwEg8euRb4Qy3eEsCEvGJ8pAUZKDz6klIzYsTaCq1YemITRtCo7Dl1 eCiZkvuH4bcvFyy8f48Bkgd5+cFy/pLFmDW/ezSq8e01ORLPU0TyhzHI5 lvxkAGSrbZsF0YmV5nxSOj+kj2hOcw0Id5Oepg++SDO71RCX/HQsY+rDd s=; X-IronPort-AV: E=Sophos;i="5.79,341,1602547200"; d="scan'208";a="77011780" To: , , , , Subject: [PATCH v4 1/2] drivers/misc: sysgenid: add system generation id driver Date: Tue, 12 Jan 2021 14:15:59 +0200 Message-ID: <1610453760-13812-2-git-send-email-acatan@amazon.com> X-Mailer: git-send-email 2.7.4 In-Reply-To: <1610453760-13812-1-git-send-email-acatan@amazon.com> References: <1610453760-13812-1-git-send-email-acatan@amazon.com> MIME-Version: 1.0 X-Originating-IP: [10.43.161.68] X-ClientProxiedBy: EX13D50UWC001.ant.amazon.com (10.43.162.96) To EX13D08EUB004.ant.amazon.com (10.43.166.158) Precedence: Bulk 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=lists.gnu.org; Received-SPF: pass client-ip=52.95.49.90; envelope-from=prvs=639db6d60=acatan@amazon.com; helo=smtp-fw-6002.amazon.com X-Spam_score_int: -120 X-Spam_score: -12.1 X-Spam_bar: ------------ X-Spam_report: (-12.1 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.251, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_MED=-2.3, RCVD_IN_MSPIKE_H4=0.001, RCVD_IN_MSPIKE_WL=0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001, USER_IN_DEF_SPF_WL=-7.5 autolearn=ham autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.23 List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: Jason@zx2c4.com, dgunigun@redhat.com, mst@redhat.com, ghammer@redhat.com, vijaysun@ca.ibm.com, 0x7f454c46@gmail.com, mhocko@kernel.org, oridgar@gmail.com, avagin@gmail.com, pavel@ucw.cz, ptikhomirov@virtuozzo.com, corbet@lwn.net, mpe@ellerman.id.au, rafael@kernel.org, ebiggers@kernel.org, borntraeger@de.ibm.com, sblbir@amazon.com, bonzini@gnu.org, arnd@arndb.de, jannh@google.com, raduweis@amazon.com, asmehra@redhat.com, Adrian Catangiu , graf@amazon.com, rppt@kernel.org, luto@kernel.org, gil@azul.com, colmmacc@amazon.com, tytso@mit.edu, gregkh@linuxfoundation.org, areber@redhat.com, ebiederm@xmission.com, ovzxemul@gmail.com, w@1wt.eu, dwmw@amazon.co.uk Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: "Qemu-devel" Reply-to: Adrian Catangiu From: Adrian Catangiu via X-ZohoMail-DKIM: fail (Header signature does not verify) Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" - Background and problem The System Generation ID feature is required in virtualized or containerized environments by applications that work with local copies or caches of world-unique data such as random values, uuids, monotonically increasing counters, etc. Such applications can be negatively affected by VM or container snapshotting when the VM or container is either cloned or returned to an earlier point in time. Furthermore, simply finding out about a system generation change is only the starting point of a process to renew internal states of possibly multiple applications across the system. This process could benefit from a driver that provides an interface through which orchestration can be easily done. - Solution The System Generation ID is a simple concept meant to alleviate the issue by providing a monotonically increasing u32 counter that changes each time the VM or container is restored from a snapshot. The `sysgenid` driver exposes a monotonic incremental System Generation u32 counter via a char-dev FS interface that provides sync and async SysGen counter updates notifications. It also provides SysGen counter retrieval and confirmation mechanisms. The counter starts from zero when the driver is initialized and monotonically increments every time the system generation changes. The `sysgenid` driver exports the `void sysgenid_bump_generation()` symbol which can be used by backend drivers to drive system generation changes based on hardware events. System generation changes can also be driven by userspace software through a dedicated driver ioctl. Userspace applications or libraries can then (a)synchronously consume the system generation counter through the provided FS interface to make any necessary internal adjustments following a system generation update. Signed-off-by: Adrian Catangiu --- Documentation/misc-devices/sysgenid.rst | 240 +++++++++++++++++++++++++ drivers/misc/Kconfig | 16 ++ drivers/misc/Makefile | 1 + drivers/misc/sysgenid.c | 298 ++++++++++++++++++++++++++++= ++++ include/uapi/linux/sysgenid.h | 18 ++ 5 files changed, 573 insertions(+) create mode 100644 Documentation/misc-devices/sysgenid.rst create mode 100644 drivers/misc/sysgenid.c create mode 100644 include/uapi/linux/sysgenid.h diff --git a/Documentation/misc-devices/sysgenid.rst b/Documentation/misc-d= evices/sysgenid.rst new file mode 100644 index 0000000..0b31ccf --- /dev/null +++ b/Documentation/misc-devices/sysgenid.rst @@ -0,0 +1,240 @@ +.. SPDX-License-Identifier: GPL-2.0 + +=3D=3D=3D=3D=3D=3D=3D=3D +SYSGENID +=3D=3D=3D=3D=3D=3D=3D=3D + +The System Generation ID feature is required in virtualized or +containerized environments by applications that work with local copies +or caches of world-unique data such as random values, UUIDs, +monotonically increasing counters, etc. +Such applications can be negatively affected by VM or container +snapshotting when the VM or container is either cloned or returned to +an earlier point in time. + +The System Generation ID is a simple concept meant to alleviate the +issue by providing a monotonically increasing counter that changes +each time the VM or container is restored from a snapshot. +The driver for it lives at ``drivers/misc/sysgenid.c``. + +The ``sysgenid`` driver exposes a monotonic incremental System +Generation u32 counter via a char-dev FS interface accessible through +``/dev/sysgenid`` that provides sync and async SysGen counter updates +notifications. It also provides SysGen counter retrieval and +confirmation mechanisms. + +The counter starts from zero when the driver is initialized and +monotonically increments every time the system generation changes. + +The ``sysgenid`` driver exports the ``void sysgenid_bump_generation()`` +symbol which can be used by backend drivers to drive system generation +changes based on hardware events. +System generation changes can also be driven by userspace software +through a dedicated driver ioctl. + +Userspace applications or libraries can (a)synchronously consume the +system generation counter through the provided FS interface, to make +any necessary internal adjustments following a system generation update. + +Driver FS interface: + +``open()``: + When the device is opened, a copy of the current Sys-Gen-Id (counter) + is associated with the open file descriptor. The driver now tracks + this file as an independent *watcher*. The driver tracks how many + watchers are aware of the latest Sys-Gen-Id counter and how many of + them are *outdated*; outdated being those that have lived through + a Sys-Gen-Id change but not yet confirmed the new generation counter. + +``read()``: + Read is meant to provide the *new* system generation counter when a + generation change takes place. The read operation blocks until the + associated counter is no longer up to date, at which point the new + counter is provided/returned. + Nonblocking ``read()`` uses ``EAGAIN`` to signal that there is no + *new* counter value available. The generation counter is considered + *new* for each open file descriptor that hasn't confirmed the new + value following a generation change. Therefore, once a generation + change takes place, all ``read()`` calls will immediately return the + new generation counter and will continue to do so until the + new value is confirmed back to the driver through ``write()``. + Partial reads are not allowed - read buffer needs to be at least + ``sizeof(unsigned)`` in size. + +``write()``: + Write is used to confirm the up-to-date Sys Gen counter back to the + driver. + Following a VM generation change, all existing watchers are marked + as *outdated*. Each file descriptor will maintain the *outdated* + status until a ``write()`` confirms the up-to-date counter back to + the driver. + Partial writes are not allowed - write buffer should be exactly + ``sizeof(unsigned)`` in size. + +``poll()``: + Poll is implemented to allow polling for generation counter updates. + Such updates result in ``EPOLLIN`` polling status until the new + up-to-date counter is confirmed back to the driver through a + ``write()``. + +``ioctl()``: + The driver also adds support for tracking count of open file + descriptors that haven't acknowledged a generation counter update, + as well as a mechanism for userspace to *force* a generation update: + + - SYSGENID_GET_OUTDATED_WATCHERS: immediately returns the number of + *outdated* watchers - number of file descriptors that were open + during a system generation change, and which have not yet confirmed + the new generation counter. + - SYSGENID_WAIT_WATCHERS: blocks until there are no more *outdated* + watchers, or if a ``timeout`` argument is provided, until the + timeout expires. + If the current caller is *outdated* or a generation change happens + while waiting (thus making current caller *outdated*), the ioctl + returns ``-EINTR`` to signal the user to handle event and retry. + - SYSGENID_FORCE_GEN_UPDATE: forces a generation counter increment. + It takes a ``minimum-generation`` argument which represents the + minimum value the generation counter will be incremented to. For + example if current generation is ``5`` and ``SYSGENID_FORCE_GEN_UPDATE= (8)`` + is called, the generation counter will increment to ``8``. + This IOCTL can only be used by processes with CAP_CHECKPOINT_RESTORE + or CAP_SYS_ADMIN capabilities. + +``mmap()``: + The driver supports ``PROT_READ, MAP_SHARED`` mmaps of a single page + in size. The first 4 bytes of the mapped page will contain an + up-to-date u32 copy of the system generation counter. + The mapped memory can be used as a low-latency generation counter + probe mechanism in critical sections - see examples. + +``close()``: + Removes the file descriptor as a system generation counter *watcher*. + +Example application workflows +----------------------------- + +1) Watchdog thread simplified example:: + + void watchdog_thread_handler(int *thread_active) + { + unsigned genid; + int fd =3D open("/dev/sysgenid", O_RDWR | O_CLOEXEC, S_IRUSR | S_IWUSR); + + do { + // read new gen ID - blocks until VM generation changes + read(fd, &genid, sizeof(genid)); + + // because of VM generation change, we need to rebuild world + reseed_app_env(); + + // confirm we're done handling gen ID update + write(fd, &genid, sizeof(genid)); + } while (atomic_read(thread_active)); + + close(fd); + } + +2) ASYNC simplified example:: + + void handle_io_on_sysgenfd(int sysgenfd) + { + unsigned genid; + + // read new gen ID - we need it to confirm we've handled update + read(fd, &genid, sizeof(genid)); + + // because of VM generation change, we need to rebuild world + reseed_app_env(); + + // confirm we're done handling the gen ID update + write(fd, &genid, sizeof(genid)); + } + + int main() { + int epfd, sysgenfd; + struct epoll_event ev; + + epfd =3D epoll_create(EPOLL_QUEUE_LEN); + + sysgenfd =3D open("/dev/sysgenid", + O_RDWR | O_CLOEXEC | O_NONBLOCK, + S_IRUSR | S_IWUSR); + + // register sysgenid for polling + ev.events =3D EPOLLIN; + ev.data.fd =3D sysgenfd; + epoll_ctl(epfd, EPOLL_CTL_ADD, sysgenfd, &ev); + + // register other parts of your app for polling + // ... + + while (1) { + // wait for something to do... + int nfds =3D epoll_wait(epfd, events, + MAX_EPOLL_EVENTS_PER_RUN, + EPOLL_RUN_TIMEOUT); + if (nfds < 0) die("Error in epoll_wait!"); + + // for each ready fd + for(int i =3D 0; i < nfds; i++) { + int fd =3D events[i].data.fd; + + if (fd =3D=3D sysgenfd) + handle_io_on_sysgenfd(sysgenfd); + else + handle_some_other_part_of_the_app(fd); + } + } + + return 0; + } + +3) Mapped memory polling simplified example:: + + /* + * app/library function that provides cached secrets + */ + char * safe_cached_secret(app_data_t *app) + { + char *secret; + volatile unsigned *const genid_ptr =3D get_sysgenid_mapping(app); + again: + secret =3D __cached_secret(app); + + if (unlikely(*genid_ptr !=3D app->cached_genid)) { + app->cached_genid =3D *genid_ptr; + barrier(); + + // rebuild world then confirm the genid update (thru write) + rebuild_caches(app); + + ack_sysgenid_update(app); + + goto again; + } + + return secret; + } + +4) Orchestrator simplified example:: + + /* + * orchestrator - manages multiple applications and libraries used by + * a service and tries to make sure all sensitive components gracefully + * handle VM generation changes. + * Following function is called on detection of a VM generation change. + */ + int handle_sysgen_update(int sysgen_fd, unsigned new_gen_id) + { + // pause until all components have handled event + pause_service(); + + // confirm *this* watcher as up-to-date + write(sysgen_fd, &new_gen_id, sizeof(unsigned)); + + // wait for all *others* for at most 5 seconds. + ioctl(sysgen_fd, VMGENID_WAIT_WATCHERS, 5000); + + // all applications on the system have rebuilt worlds + resume_service(); + } diff --git a/drivers/misc/Kconfig b/drivers/misc/Kconfig index fafa8b0..931d716 100644 --- a/drivers/misc/Kconfig +++ b/drivers/misc/Kconfig @@ -456,6 +456,22 @@ config PVPANIC a paravirtualized device provided by QEMU; it lets a virtual machine (guest) communicate panic events to the host. =20 +config SYSGENID + tristate "System Generation ID driver" + default N + help + This is a System Generation ID driver which provides a system + generation counter. The driver exposes FS ops on /dev/sysgenid + through which it can provide information and notifications on system + generation changes that happen because of VM or container snapshots + or cloning. + This enables applications and libraries that store or cache + sensitive information, to know that they need to regenerate it + after process memory has been exposed to potential copying. + + To compile this driver as a module, choose M here: the + module will be called sysgenid. + config HISI_HIKEY_USB tristate "USB GPIO Hub on HiSilicon Hikey 960/970 Platform" depends on (OF && GPIOLIB) || COMPILE_TEST diff --git a/drivers/misc/Makefile b/drivers/misc/Makefile index d23231e..4b4933d 100644 --- a/drivers/misc/Makefile +++ b/drivers/misc/Makefile @@ -57,3 +57,4 @@ obj-$(CONFIG_HABANA_AI) +=3D habanalabs/ obj-$(CONFIG_UACCE) +=3D uacce/ obj-$(CONFIG_XILINX_SDFEC) +=3D xilinx_sdfec.o obj-$(CONFIG_HISI_HIKEY_USB) +=3D hisi_hikey_usb.o +obj-$(CONFIG_SYSGENID) +=3D sysgenid.o diff --git a/drivers/misc/sysgenid.c b/drivers/misc/sysgenid.c new file mode 100644 index 0000000..dd64099 --- /dev/null +++ b/drivers/misc/sysgenid.c @@ -0,0 +1,298 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * System Generation ID driver + * + * Copyright (C) 2020 Amazon. All rights reserved. + * + * Authors: + * Adrian Catangiu + * + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct sysgenid_data { + unsigned long map_buf; + wait_queue_head_t read_waitq; + atomic_t generation_counter; + + unsigned int watchers; + atomic_t outdated_watchers; + wait_queue_head_t outdated_waitq; + spinlock_t lock; +}; +static struct sysgenid_data sysgenid_data; + +struct file_data { + unsigned int acked_gen_counter; +}; + +static int equals_gen_counter(unsigned int counter) +{ + return counter =3D=3D atomic_read(&sysgenid_data.generation_counter); +} + +static void _bump_generation(int min_gen) +{ + unsigned long flags; + int counter; + + spin_lock_irqsave(&sysgenid_data.lock, flags); + counter =3D max(min_gen, 1 + atomic_read(&sysgenid_data.generation_counte= r)); + atomic_set(&sysgenid_data.generation_counter, counter); + *((int *) sysgenid_data.map_buf) =3D counter; + atomic_set(&sysgenid_data.outdated_watchers, sysgenid_data.watchers); + + wake_up_interruptible(&sysgenid_data.read_waitq); + wake_up_interruptible(&sysgenid_data.outdated_waitq); + spin_unlock_irqrestore(&sysgenid_data.lock, flags); +} + +void sysgenid_bump_generation(void) +{ + _bump_generation(0); +} +EXPORT_SYMBOL(sysgenid_bump_generation); + +static void put_outdated_watchers(void) +{ + if (atomic_dec_and_test(&sysgenid_data.outdated_watchers)) + wake_up_interruptible(&sysgenid_data.outdated_waitq); +} + +static int sysgenid_open(struct inode *inode, struct file *file) +{ + struct file_data *fdata =3D kzalloc(sizeof(struct file_data), GFP_KERNEL); + unsigned long flags; + + if (!fdata) + return -ENOMEM; + + spin_lock_irqsave(&sysgenid_data.lock, flags); + fdata->acked_gen_counter =3D atomic_read(&sysgenid_data.generation_counte= r); + ++sysgenid_data.watchers; + spin_unlock_irqrestore(&sysgenid_data.lock, flags); + + file->private_data =3D fdata; + + return 0; +} + +static int sysgenid_close(struct inode *inode, struct file *file) +{ + struct file_data *fdata =3D file->private_data; + unsigned long flags; + + spin_lock_irqsave(&sysgenid_data.lock, flags); + if (!equals_gen_counter(fdata->acked_gen_counter)) + put_outdated_watchers(); + --sysgenid_data.watchers; + spin_unlock_irqrestore(&sysgenid_data.lock, flags); + + kfree(fdata); + + return 0; +} + +static ssize_t sysgenid_read(struct file *file, char __user *ubuf, + size_t nbytes, loff_t *ppos) +{ + struct file_data *fdata =3D file->private_data; + ssize_t ret; + int gen_counter; + + if (nbytes =3D=3D 0) + return 0; + /* disallow partial reads */ + if (nbytes < sizeof(gen_counter)) + return -EINVAL; + + if (equals_gen_counter(fdata->acked_gen_counter)) { + if (file->f_flags & O_NONBLOCK) + return -EAGAIN; + ret =3D wait_event_interruptible( + sysgenid_data.read_waitq, + !equals_gen_counter(fdata->acked_gen_counter) + ); + if (ret) + return ret; + } + + gen_counter =3D atomic_read(&sysgenid_data.generation_counter); + ret =3D copy_to_user(ubuf, &gen_counter, sizeof(gen_counter)); + if (ret) + return -EFAULT; + + return sizeof(gen_counter); +} + +static ssize_t sysgenid_write(struct file *file, const char __user *ubuf, + size_t count, loff_t *ppos) +{ + struct file_data *fdata =3D file->private_data; + unsigned int new_acked_gen; + unsigned long flags; + + /* disallow partial writes */ + if (count !=3D sizeof(new_acked_gen)) + return -EINVAL; + if (copy_from_user(&new_acked_gen, ubuf, count)) + return -EFAULT; + + spin_lock_irqsave(&sysgenid_data.lock, flags); + /* wrong gen-counter acknowledged */ + if (!equals_gen_counter(new_acked_gen)) { + spin_unlock_irqrestore(&sysgenid_data.lock, flags); + return -EINVAL; + } + if (!equals_gen_counter(fdata->acked_gen_counter)) { + fdata->acked_gen_counter =3D new_acked_gen; + put_outdated_watchers(); + } + spin_unlock_irqrestore(&sysgenid_data.lock, flags); + + return (ssize_t)count; +} + +static __poll_t sysgenid_poll(struct file *file, poll_table *wait) +{ + __poll_t mask =3D 0; + struct file_data *fdata =3D file->private_data; + + if (!equals_gen_counter(fdata->acked_gen_counter)) + return EPOLLIN | EPOLLRDNORM; + + poll_wait(file, &sysgenid_data.read_waitq, wait); + + if (!equals_gen_counter(fdata->acked_gen_counter)) + mask =3D EPOLLIN | EPOLLRDNORM; + + return mask; +} + +static long sysgenid_ioctl(struct file *file, + unsigned int cmd, unsigned long arg) +{ + struct file_data *fdata =3D file->private_data; + unsigned long timeout_ns, min_gen; + ktime_t until; + int ret =3D 0; + + switch (cmd) { + case SYSGENID_GET_OUTDATED_WATCHERS: + ret =3D atomic_read(&sysgenid_data.outdated_watchers); + break; + case SYSGENID_WAIT_WATCHERS: + timeout_ns =3D arg * NSEC_PER_MSEC; + until =3D timeout_ns ? ktime_set(0, timeout_ns) : KTIME_MAX; + + ret =3D wait_event_interruptible_hrtimeout( + sysgenid_data.outdated_waitq, + (!atomic_read(&sysgenid_data.outdated_watchers) || + !equals_gen_counter(fdata->acked_gen_counter)), + until + ); + if (atomic_read(&sysgenid_data.outdated_watchers)) + ret =3D -EINTR; + else + ret =3D 0; + break; + case SYSGENID_FORCE_GEN_UPDATE: + if (!checkpoint_restore_ns_capable(current_user_ns())) + return -EACCES; + min_gen =3D arg; + _bump_generation(min_gen); + break; + default: + ret =3D -EINVAL; + break; + } + return ret; +} + +static int sysgenid_mmap(struct file *file, struct vm_area_struct *vma) +{ + struct file_data *fdata =3D file->private_data; + + if (vma->vm_pgoff !=3D 0 || vma_pages(vma) > 1) + return -EINVAL; + + if ((vma->vm_flags & VM_WRITE) !=3D 0) + return -EPERM; + + vma->vm_flags |=3D VM_DONTEXPAND | VM_DONTDUMP; + vma->vm_flags &=3D ~VM_MAYWRITE; + vma->vm_private_data =3D fdata; + + return vm_insert_page(vma, vma->vm_start, + virt_to_page(sysgenid_data.map_buf)); +} + +static const struct file_operations fops =3D { + .owner =3D THIS_MODULE, + .mmap =3D sysgenid_mmap, + .open =3D sysgenid_open, + .release =3D sysgenid_close, + .read =3D sysgenid_read, + .write =3D sysgenid_write, + .poll =3D sysgenid_poll, + .unlocked_ioctl =3D sysgenid_ioctl, +}; + +static struct miscdevice sysgenid_misc =3D { + .minor =3D MISC_DYNAMIC_MINOR, + .name =3D "sysgenid", + .fops =3D &fops, +}; + +static int __init sysgenid_init(void) +{ + int ret; + + sysgenid_data.map_buf =3D get_zeroed_page(GFP_KERNEL); + if (!sysgenid_data.map_buf) + return -ENOMEM; + + atomic_set(&sysgenid_data.generation_counter, 0); + atomic_set(&sysgenid_data.outdated_watchers, 0); + init_waitqueue_head(&sysgenid_data.read_waitq); + init_waitqueue_head(&sysgenid_data.outdated_waitq); + spin_lock_init(&sysgenid_data.lock); + + ret =3D misc_register(&sysgenid_misc); + if (ret < 0) { + pr_err("misc_register() failed for sysgenid\n"); + goto err; + } + + return 0; + +err: + free_pages(sysgenid_data.map_buf, 0); + sysgenid_data.map_buf =3D 0; + + return ret; +} + +static void __exit sysgenid_exit(void) +{ + misc_deregister(&sysgenid_misc); + free_pages(sysgenid_data.map_buf, 0); + sysgenid_data.map_buf =3D 0; +} + +module_init(sysgenid_init); +module_exit(sysgenid_exit); + +MODULE_AUTHOR("Adrian Catangiu"); +MODULE_DESCRIPTION("System Generation ID"); +MODULE_LICENSE("GPL"); +MODULE_VERSION("0.1"); diff --git a/include/uapi/linux/sysgenid.h b/include/uapi/linux/sysgenid.h new file mode 100644 index 0000000..ea38fd3 --- /dev/null +++ b/include/uapi/linux/sysgenid.h @@ -0,0 +1,18 @@ +/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ + +#ifndef _UAPI_LINUX_SYSGENID_H +#define _UAPI_LINUX_SYSGENID_H + +#include + +#define SYSGENID_IOCTL 0x2d +#define SYSGENID_GET_OUTDATED_WATCHERS _IO(SYSGENID_IOCTL, 1) +#define SYSGENID_WAIT_WATCHERS _IO(SYSGENID_IOCTL, 2) +#define SYSGENID_FORCE_GEN_UPDATE _IO(SYSGENID_IOCTL, 3) + +#ifdef __KERNEL__ +void sysgenid_bump_generation(void); +#endif /* __KERNEL__ */ + +#endif /* _UAPI_LINUX_SYSGENID_H */ + --=20 2.7.4 Amazon Development Center (Romania) S.R.L. registered office: 27A Sf. Lazar= Street, UBC5, floor 2, Iasi, Iasi County, 700045, Romania. Registered in R= omania. Registration number J22/2621/2005. From nobody Fri Apr 26 00:20:53 2024 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; dkim=fail header.i=@amazon.com; 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; dmarc=pass(p=none dis=none) header.from=nongnu.org ARC-Seal: i=1; a=rsa-sha256; t=1610453993; cv=none; d=zohomail.com; s=zohoarc; b=JngR5A4PmmniTnYvRs4GnjVkQc4ardGJwzU73OJzGbKDL9O1J+ODMENhpQKKbFZwzmHRhspZ9ZhI4vvY160/KYY24oCbb4E8sW1jcyP09mQZmY1ViF2ifEI0Fzwla7BDrtvf3ecTskPvQSEPH8qQMSj0fqhG1j2EFZ7FEtmMpa4= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1610453993; h=Content-Type:Cc:Date:From:In-Reply-To:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:Reply-To:References:Sender:Subject:To; bh=EOW6juggGEXAs6hvV4WJ47XDoCr9RDgvKznLdz0LphA=; b=XWwFSu5yJpbahMYuSd92tuUtmAHxgHRLUZk2TgRnEXevXLe89/Qwxe3j/MGpNHEo/FyjlfbJiVsQU9jT+OEyE1bYVa268CjFlgJ1/b1kWmXUh3rBYnUOUvEY03CL9TQg2URMXwlNkR19sRsT0cyuPVZLMqYDCiWXz4qW0NgcMLI= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=fail header.i=@amazon.com; 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; dmarc=pass header.from= (p=none dis=none) header.from= Return-Path: Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1610453993728677.7307195469278; Tue, 12 Jan 2021 04:19:53 -0800 (PST) Received: from localhost ([::1]:58820 helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1kzIeO-0003CQ-HA for importer@patchew.org; Tue, 12 Jan 2021 07:19:52 -0500 Received: from eggs.gnu.org ([2001:470:142:3::10]:48496) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1kzIbu-0001q7-Sp for qemu-devel@nongnu.org; Tue, 12 Jan 2021 07:17:22 -0500 Received: from smtp-fw-6002.amazon.com ([52.95.49.90]:21319) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1kzIbh-0001I6-OG for qemu-devel@nongnu.org; Tue, 12 Jan 2021 07:17:18 -0500 Received: from iad12-co-svc-p1-lb1-vlan2.amazon.com (HELO email-inbound-relay-1a-715bee71.us-east-1.amazon.com) ([10.43.8.2]) by smtp-border-fw-out-6002.iad6.amazon.com with ESMTP; 12 Jan 2021 12:17:00 +0000 Received: from EX13D08EUB004.ant.amazon.com (iad12-ws-svc-p26-lb9-vlan2.iad.amazon.com [10.40.163.34]) by email-inbound-relay-1a-715bee71.us-east-1.amazon.com (Postfix) with ESMTPS id 2965EA1DB6; Tue, 12 Jan 2021 12:16:57 +0000 (UTC) Received: from uf6ed9c851f4556.ant.amazon.com (10.43.161.68) by EX13D08EUB004.ant.amazon.com (10.43.166.158) with Microsoft SMTP Server (TLS) id 15.0.1497.2; Tue, 12 Jan 2021 12:16:43 +0000 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=amazon.com; i=@amazon.com; q=dns/txt; s=amazon201209; t=1610453825; x=1641989825; h=from:to:cc:subject:date:message-id:in-reply-to: references:mime-version; bh=EOW6juggGEXAs6hvV4WJ47XDoCr9RDgvKznLdz0LphA=; b=WXpSbC2LDnJQRo/mWyXrwjY+vzJAjZBsW5EgH3ofB1fXBtg9ps6E7nZx 0HmXjEuccJhM9kb4AsgSPwWoAgGoWCeLPO2TZxIB0X55/4vuVXi2LR6eM hOY3soP+lFDiSsHCSys/+cMp5Wgr4Md3Vk0x5qG6XCbKAojV6H/rILR3e w=; X-IronPort-AV: E=Sophos;i="5.79,341,1602547200"; d="scan'208";a="77011827" To: , , , , Subject: [PATCH v4 2/2] drivers/virt: vmgenid: add vm generation id driver Date: Tue, 12 Jan 2021 14:16:00 +0200 Message-ID: <1610453760-13812-3-git-send-email-acatan@amazon.com> X-Mailer: git-send-email 2.7.4 In-Reply-To: <1610453760-13812-1-git-send-email-acatan@amazon.com> References: <1610453760-13812-1-git-send-email-acatan@amazon.com> MIME-Version: 1.0 X-Originating-IP: [10.43.161.68] X-ClientProxiedBy: EX13D50UWC001.ant.amazon.com (10.43.162.96) To EX13D08EUB004.ant.amazon.com (10.43.166.158) Precedence: Bulk 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=lists.gnu.org; Received-SPF: pass client-ip=52.95.49.90; envelope-from=prvs=639db6d60=acatan@amazon.com; helo=smtp-fw-6002.amazon.com X-Spam_score_int: -120 X-Spam_score: -12.1 X-Spam_bar: ------------ X-Spam_report: (-12.1 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.251, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_MED=-2.3, RCVD_IN_MSPIKE_H4=0.001, RCVD_IN_MSPIKE_WL=0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001, USER_IN_DEF_SPF_WL=-7.5 autolearn=ham autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.23 List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: Jason@zx2c4.com, dgunigun@redhat.com, mst@redhat.com, ghammer@redhat.com, vijaysun@ca.ibm.com, 0x7f454c46@gmail.com, mhocko@kernel.org, oridgar@gmail.com, avagin@gmail.com, pavel@ucw.cz, ptikhomirov@virtuozzo.com, corbet@lwn.net, mpe@ellerman.id.au, rafael@kernel.org, ebiggers@kernel.org, borntraeger@de.ibm.com, sblbir@amazon.com, bonzini@gnu.org, arnd@arndb.de, jannh@google.com, raduweis@amazon.com, asmehra@redhat.com, Adrian Catangiu , graf@amazon.com, rppt@kernel.org, luto@kernel.org, gil@azul.com, colmmacc@amazon.com, tytso@mit.edu, gregkh@linuxfoundation.org, areber@redhat.com, ebiederm@xmission.com, ovzxemul@gmail.com, w@1wt.eu, dwmw@amazon.co.uk Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: "Qemu-devel" Reply-to: Adrian Catangiu From: Adrian Catangiu via X-ZohoMail-DKIM: fail (Header signature does not verify) Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" - Background The VM Generation ID is a feature defined by Microsoft (paper: http://go.microsoft.com/fwlink/?LinkId=3D260709) and supported by multiple hypervisor vendors. The feature can be used to drive the `sysgenid` mechanism required in virtualized environments by software that works with local copies and caches of world-unique data such as random values, uuids, monotonically increasing counters, etc. - Solution The VM Generation ID is a hypervisor/hardware provided 128-bit unique ID that changes each time the VM is restored from a snapshot. It can be used to differentiate between VMs or different generations of the same VM. This VM Generation ID is exposed through an ACPI device by multiple hypervisor vendors. The `vmgenid` driver uses ACPI events to be notified by hardware changes to the 128-bit Vm Gen Id HW UUID. The UUID is not exposed to userspace, it is added by the driver as device randomness to improve kernel entropy following VM snapshot events. This driver also acts as a backend for the `sysgenid` kernel module (`drivers/misc/sysgenid.c`, `Documentation/misc-devices/sysgenid.rst`) to drive changes to the "System Generation Id" which is further exposed to userspace as a system-wide monotonically increasing counter. This patch builds on top of Or Idgar 's proposal https://lkml.org/lkml/2018/3/1/498 - Future improvements Ideally we would want the driver to register itself based on devices' _CID and not _HID, but unfortunately I couldn't find a way to do that. The problem is that ACPI device matching is done by '__acpi_match_device()' which exclusively looks at 'acpi_hardware_id *hwid'. There is a path for platform devices to match on _CID when _HID is 'PRP0001' - but this is not the case for the Qemu vmgenid device. Guidance and help here would be greatly appreciated. Signed-off-by: Adrian Catangiu --- Documentation/virt/vmgenid.rst | 34 +++++++++ drivers/virt/Kconfig | 14 ++++ drivers/virt/Makefile | 1 + drivers/virt/vmgenid.c | 153 +++++++++++++++++++++++++++++++++++++= ++++ 4 files changed, 202 insertions(+) create mode 100644 Documentation/virt/vmgenid.rst create mode 100644 drivers/virt/vmgenid.c diff --git a/Documentation/virt/vmgenid.rst b/Documentation/virt/vmgenid.rst new file mode 100644 index 0000000..2106354 --- /dev/null +++ b/Documentation/virt/vmgenid.rst @@ -0,0 +1,34 @@ +.. SPDX-License-Identifier: GPL-2.0 + +=3D=3D=3D=3D=3D=3D=3D +VMGENID +=3D=3D=3D=3D=3D=3D=3D + +The VM Generation ID is a feature defined by Microsoft (paper: +http://go.microsoft.com/fwlink/?LinkId=3D260709) and supported by +multiple hypervisor vendors. + +The feature is required in virtualized environments by applications +that work with local copies/caches of world-unique data such as random +values, UUIDs, monotonically increasing counters, etc. +Such applications can be negatively affected by VM snapshotting when +the VM is either cloned or returned to an earlier point in time. + +The VM Generation ID is a simple concept meant to alleviate the issue +by providing a unique ID that changes each time the VM is restored +from a snapshot. The hardware provided UUID value can be used to +differentiate between VMs or different generations of the same VM. + +The VM Generation ID is exposed through an ACPI device by multiple +hypervisor vendors. The driver for it lives at +``drivers/virt/vmgenid.c`` + +The ``vmgenid`` driver uses ACPI events to be notified by hardware +changes to the 128-bit Vm Gen Id UUID. This UUID is not exposed to +userspace, it is added by the driver as device randomness to improve +kernel entropy following VM snapshot events. + +This driver also acts as a backend for the ``sysgenid`` kernel module +(``drivers/misc/sysgenid.c``, ``Documentation/misc-devices/sysgenid.rst``) +to drive changes to the "System Generation Id" which is further exposed +to userspace as a monotonically increasing counter. diff --git a/drivers/virt/Kconfig b/drivers/virt/Kconfig index 80c5f9c1..4771633 100644 --- a/drivers/virt/Kconfig +++ b/drivers/virt/Kconfig @@ -13,6 +13,20 @@ menuconfig VIRT_DRIVERS =20 if VIRT_DRIVERS =20 +config VMGENID + tristate "Virtual Machine Generation ID driver" + depends on ACPI && SYSGENID + default N + help + The driver uses the hypervisor provided Virtual Machine Generation ID + to drive the system generation counter mechanism exposed by sysgenid. + The vmgenid changes on VM snapshots or VM cloning. The hypervisor + provided 128-bit vmgenid is also used as device randomness to improve + kernel entropy following VM snapshot events. + + To compile this driver as a module, choose M here: the + module will be called vmgenid. + config FSL_HV_MANAGER tristate "Freescale hypervisor management driver" depends on FSL_SOC diff --git a/drivers/virt/Makefile b/drivers/virt/Makefile index f28425c..889be01 100644 --- a/drivers/virt/Makefile +++ b/drivers/virt/Makefile @@ -4,6 +4,7 @@ # =20 obj-$(CONFIG_FSL_HV_MANAGER) +=3D fsl_hypervisor.o +obj-$(CONFIG_VMGENID) +=3D vmgenid.o obj-y +=3D vboxguest/ =20 obj-$(CONFIG_NITRO_ENCLAVES) +=3D nitro_enclaves/ diff --git a/drivers/virt/vmgenid.c b/drivers/virt/vmgenid.c new file mode 100644 index 0000000..d9d089a --- /dev/null +++ b/drivers/virt/vmgenid.c @@ -0,0 +1,153 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Virtual Machine Generation ID driver + * + * Copyright (C) 2018 Red Hat Inc. All rights reserved. + * + * Copyright (C) 2020 Amazon. All rights reserved. + * + * Authors: + * Adrian Catangiu + * Or Idgar + * Gal Hammer + * + */ +#include +#include +#include +#include +#include +#include + +#define DEV_NAME "vmgenid" +ACPI_MODULE_NAME(DEV_NAME); + +struct vmgenid_data { + uuid_t uuid; + void *uuid_iomap; +}; +static struct vmgenid_data vmgenid_data; + +static int vmgenid_acpi_map(struct vmgenid_data *priv, acpi_handle handle) +{ + int i; + phys_addr_t phys_addr; + struct acpi_buffer buffer =3D { ACPI_ALLOCATE_BUFFER, NULL }; + acpi_status status; + union acpi_object *pss; + union acpi_object *element; + + status =3D acpi_evaluate_object(handle, "ADDR", NULL, &buffer); + if (ACPI_FAILURE(status)) { + ACPI_EXCEPTION((AE_INFO, status, "Evaluating ADDR")); + return -ENODEV; + } + pss =3D buffer.pointer; + if (!pss || pss->type !=3D ACPI_TYPE_PACKAGE || pss->package.count !=3D 2) + return -EINVAL; + + phys_addr =3D 0; + for (i =3D 0; i < pss->package.count; i++) { + element =3D &(pss->package.elements[i]); + if (element->type !=3D ACPI_TYPE_INTEGER) + return -EINVAL; + phys_addr |=3D element->integer.value << i * 32; + } + + priv->uuid_iomap =3D acpi_os_map_memory(phys_addr, sizeof(uuid_t)); + if (!priv->uuid_iomap) { + pr_err("Could not map memory at 0x%llx, size %u\n", + phys_addr, + (u32) sizeof(uuid_t)); + return -ENOMEM; + } + + memcpy_fromio(&priv->uuid, priv->uuid_iomap, sizeof(uuid_t)); + + return 0; +} + +static int vmgenid_acpi_add(struct acpi_device *device) +{ + int ret; + + if (!device) + return -EINVAL; + device->driver_data =3D &vmgenid_data; + + ret =3D vmgenid_acpi_map(device->driver_data, device->handle); + if (ret < 0) { + pr_err("vmgenid: failed to map acpi device\n"); + device->driver_data =3D NULL; + } + + return ret; +} + +static int vmgenid_acpi_remove(struct acpi_device *device) +{ + if (!device || acpi_driver_data(device) !=3D &vmgenid_data) + return -EINVAL; + device->driver_data =3D NULL; + + if (vmgenid_data.uuid_iomap) + acpi_os_unmap_memory(vmgenid_data.uuid_iomap, sizeof(uuid_t)); + vmgenid_data.uuid_iomap =3D NULL; + + return 0; +} + +static void vmgenid_acpi_notify(struct acpi_device *device, u32 event) +{ + uuid_t old_uuid; + + if (!device || acpi_driver_data(device) !=3D &vmgenid_data) { + pr_err("VMGENID notify with unexpected driver private data\n"); + return; + } + + /* update VM Generation UUID */ + old_uuid =3D vmgenid_data.uuid; + memcpy_fromio(&vmgenid_data.uuid, vmgenid_data.uuid_iomap, sizeof(uuid_t)= ); + + if (memcmp(&old_uuid, &vmgenid_data.uuid, sizeof(uuid_t))) { + /* HW uuid updated */ + sysgenid_bump_generation(); + add_device_randomness(&vmgenid_data.uuid, sizeof(uuid_t)); + } +} + +static const struct acpi_device_id vmgenid_ids[] =3D { + {"VMGENID", 0}, + {"QEMUVGID", 0}, + {"", 0}, +}; + +static struct acpi_driver acpi_vmgenid_driver =3D { + .name =3D "vm_generation_id", + .ids =3D vmgenid_ids, + .owner =3D THIS_MODULE, + .ops =3D { + .add =3D vmgenid_acpi_add, + .remove =3D vmgenid_acpi_remove, + .notify =3D vmgenid_acpi_notify, + } +}; + +static int __init vmgenid_init(void) +{ + return acpi_bus_register_driver(&acpi_vmgenid_driver); +} + +static void __exit vmgenid_exit(void) +{ + acpi_bus_unregister_driver(&acpi_vmgenid_driver); +} + +module_init(vmgenid_init); +module_exit(vmgenid_exit); + +MODULE_AUTHOR("Adrian Catangiu"); +MODULE_DESCRIPTION("Virtual Machine Generation ID"); +MODULE_LICENSE("GPL"); +MODULE_VERSION("0.1"); --=20 2.7.4 Amazon Development Center (Romania) S.R.L. registered office: 27A Sf. Lazar= Street, UBC5, floor 2, Iasi, Iasi County, 700045, Romania. Registered in R= omania. Registration number J22/2621/2005.