* [RFC PATCH 1/5] dax/device: validate mmap offset alignment against dev_dax->align
2026-11-30 1:23 [RFC PATCH 0/5] virtio-pmem & device-dax: host-backed range discard via fallocate() / MADV_REMOVE Sourav Panda
@ 2026-11-30 1:23 ` Sourav Panda
2026-11-30 1:23 ` [RFC PATCH 2/5] virtio_pmem: add VIRTIO_PMEM_F_DISCARD and region discard hook Sourav Panda
` (3 subsequent siblings)
4 siblings, 0 replies; 6+ messages in thread
From: Sourav Panda @ 2026-11-30 1:23 UTC (permalink / raw)
To: djbw, vishal.l.verma, dave.jiang, alison.schofield,
pankaj.gupta.linux, mst, jasowangio, eperezma, viro, brauner
Cc: iweiny, jack, xuanzhuo, shuah, david, souravpanda, nvdimm,
linux-cxl, virtualization, linux-fsdevel, linux-kselftest,
linux-mm, linux-kernel
__check_vma() requires the start and end of a device-dax mapping to be
aligned to dev_dax->align, but it never looks at the file offset. A
caller that supplies an aligned address, either as a hint that happens
to be honoured or with MAP_FIXED, together with an offset that is only
page aligned gets a mapping. Its PMD and PUD faults then resolve to a
physical address that is not aligned to the fault size.
Reject offsets that are not a multiple of dev_dax->align at mmap() time.
Also make the PMD and PUD fault handlers refuse to install an entry for
an unaligned physical address, as a backstop in case an aligned offset
still translates to one.
Fixes: dee410792419 ("/dev/dax, core: file operations and dax-mmap")
Signed-off-by: Sourav Panda <souravpanda@google.com>
---
drivers/dax/device.c | 20 +++++++++++++-------
1 file changed, 13 insertions(+), 7 deletions(-)
diff --git a/drivers/dax/device.c b/drivers/dax/device.c
index e52f4886fbaa4..9c956085d9122 100644
--- a/drivers/dax/device.c
+++ b/drivers/dax/device.c
@@ -14,8 +14,8 @@
#include "bus.h"
static int __check_vma(struct dev_dax *dev_dax, vma_flags_t flags,
- unsigned long start, unsigned long end, struct file *file,
- const char *func)
+ unsigned long start, unsigned long end, pgoff_t pgoff,
+ struct file *file, const char *func)
{
struct device *dev = &dev_dax->dev;
unsigned long mask;
@@ -39,6 +39,12 @@ static int __check_vma(struct dev_dax *dev_dax, vma_flags_t flags,
mask);
return -EINVAL;
}
+ if (pgoff & (mask >> PAGE_SHIFT)) {
+ dev_info_ratelimited(dev,
+ "%s: %s: fail, unaligned offset (%#lx, %#lx)\n",
+ current->comm, func, pgoff, mask >> PAGE_SHIFT);
+ return -EINVAL;
+ }
if (!file_is_dax(file)) {
dev_info_ratelimited(dev,
@@ -54,7 +60,7 @@ static int check_vma(struct dev_dax *dev_dax, struct vm_area_struct *vma,
const char *func)
{
return __check_vma(dev_dax, vma->flags, vma->vm_start, vma->vm_end,
- vma->vm_file, func);
+ vma->vm_pgoff, vma->vm_file, func);
}
static void dax_set_mapping(struct vm_fault *vmf, unsigned long pfn,
@@ -148,7 +154,7 @@ static vm_fault_t __dev_dax_pmd_fault(struct dev_dax *dev_dax,
pgoff = linear_page_index(vmf->vma, pmd_addr);
phys = dax_pgoff_to_phys(dev_dax, pgoff, PMD_SIZE);
- if (phys == -1) {
+ if (phys == -1 || !IS_ALIGNED(phys, fault_size)) {
dev_dbg(dev, "pgoff_to_phys(%#lx) failed\n", pgoff);
return VM_FAULT_SIGBUS;
}
@@ -194,7 +200,7 @@ static vm_fault_t __dev_dax_pud_fault(struct dev_dax *dev_dax,
pgoff = linear_page_index(vmf->vma, pud_addr);
phys = dax_pgoff_to_phys(dev_dax, pgoff, PUD_SIZE);
- if (phys == -1) {
+ if (phys == -1 || !IS_ALIGNED(phys, fault_size)) {
dev_dbg(dev, "pgoff_to_phys(%#lx) failed\n", pgoff);
return VM_FAULT_SIGBUS;
}
@@ -283,8 +289,8 @@ static int dax_mmap_prepare(struct vm_area_desc *desc)
* fault time.
*/
id = dax_read_lock();
- rc = __check_vma(dev_dax, desc->vma_flags, desc->start, desc->end, filp,
- __func__);
+ rc = __check_vma(dev_dax, desc->vma_flags, desc->start, desc->end,
+ desc->pgoff, filp, __func__);
dax_read_unlock(id);
if (rc)
return rc;
--
2.56.1.839.g22a8290db9-goog
^ permalink raw reply [flat|nested] 6+ messages in thread* [RFC PATCH 2/5] virtio_pmem: add VIRTIO_PMEM_F_DISCARD and region discard hook
2026-11-30 1:23 [RFC PATCH 0/5] virtio-pmem & device-dax: host-backed range discard via fallocate() / MADV_REMOVE Sourav Panda
2026-11-30 1:23 ` [RFC PATCH 1/5] dax/device: validate mmap offset alignment against dev_dax->align Sourav Panda
@ 2026-11-30 1:23 ` Sourav Panda
2026-11-30 1:23 ` [RFC PATCH 3/5] vfs: allow fallocate() on character devices implementing ->fallocate() Sourav Panda
` (2 subsequent siblings)
4 siblings, 0 replies; 6+ messages in thread
From: Sourav Panda @ 2026-11-30 1:23 UTC (permalink / raw)
To: djbw, vishal.l.verma, dave.jiang, alison.schofield,
pankaj.gupta.linux, mst, jasowangio, eperezma, viro, brauner
Cc: iweiny, jack, xuanzhuo, shuah, david, souravpanda, nvdimm,
linux-cxl, virtualization, linux-fsdevel, linux-kselftest,
linux-mm, linux-kernel
A virtio-pmem guest can ask the host to flush the region, but it cannot
tell the host that part of the region is no longer needed. The host has
to preserve every page the guest ever touched for as long as the device
exists.
Add a discard request, negotiated with a new feature bit
VIRTIO_PMEM_F_DISCARD. The device advertises two config fields:
discard_granularity, the alignment in bytes that offsets and lengths
must respect, and max_discard_extents, the number of extents it accepts
per request. A request carries a count followed by {offset, len}
extents relative to the start of the region. The device validates every
extent before it releases anything and completes the request once all
of them are released, after which the guest reads zeroes from those
ranges. The status word, so far only zero or non-zero, gets named
values so the device can tell an invalid request from an I/O error.
The driver does not trust the advertised values. A granularity that is
not a power of two or is smaller than PAGE_SIZE, or an extent count of
zero, turns the feature off, both when features are validated and when
the config is read again in probe. A status the driver does not know is
treated as -EIO.
Flush and discard now share one submission path, virtio_pmem_submit(),
and remain serialized by flush_lock. A call with more ranges than the
device accepts is split into several requests, so a failure part way
through leaves the earlier requests applied.
So that device-dax does not need to know about virtio, the request is
exposed as an optional ->discard() callback and a granularity on the
nd_region, reached through nvdimm_discard() and
nvdimm_discard_granularity(). Device-dax starts using them in a later
patch, and pmem.c could use the same hook for REQ_OP_DISCARD.
Signed-off-by: Sourav Panda <souravpanda@google.com>
---
drivers/nvdimm/nd.h | 3 +
drivers/nvdimm/nd_virtio.c | 170 ++++++++++++++++++++++++++-----
drivers/nvdimm/region_devs.c | 61 +++++++++++
drivers/nvdimm/virtio_pmem.c | 44 ++++++++
drivers/nvdimm/virtio_pmem.h | 10 +-
include/linux/libnvdimm.h | 20 ++++
include/uapi/linux/virtio_pmem.h | 49 ++++++++-
7 files changed, 330 insertions(+), 27 deletions(-)
diff --git a/drivers/nvdimm/nd.h b/drivers/nvdimm/nd.h
index ed69dea5b75fd..8547b27f3f8d4 100644
--- a/drivers/nvdimm/nd.h
+++ b/drivers/nvdimm/nd.h
@@ -421,6 +421,9 @@ struct nd_region {
struct nd_interleave_set *nd_set;
struct nd_lane *lane;
int (*flush)(struct nd_region *nd_region, struct bio *bio);
+ int (*discard)(struct nd_region *nd_region, const struct range *ranges,
+ unsigned int nr);
+ u64 discard_granularity;
struct nd_mapping mapping[] __counted_by(ndr_mappings);
};
diff --git a/drivers/nvdimm/nd_virtio.c b/drivers/nvdimm/nd_virtio.c
index 3b8be79a20a0f..3b4b58f913032 100644
--- a/drivers/nvdimm/nd_virtio.c
+++ b/drivers/nvdimm/nd_virtio.c
@@ -38,7 +38,7 @@ static bool virtio_pmem_req_done(struct virtio_pmem_request *req)
static void virtio_pmem_complete_err(struct virtio_pmem_request *req)
{
- req->resp.ret = cpu_to_le32(1);
+ req->resp.ret = cpu_to_le32(VIRTIO_PMEM_RESP_TYPE_EIO);
virtio_pmem_signal_done(req);
}
@@ -138,16 +138,38 @@ void virtio_pmem_host_ack(struct virtqueue *vq)
}
EXPORT_SYMBOL_GPL(virtio_pmem_host_ack);
- /* The request submission function */
-static int virtio_pmem_flush(struct nd_region *nd_region)
+/* Translate a VIRTIO_PMEM_RESP_TYPE_* wire status into an errno. */
+static int virtio_pmem_resp_to_errno(u32 ret)
{
- struct virtio_device *vdev = nd_region->provider_data;
- struct virtio_pmem *vpmem = vdev->priv;
- struct virtio_pmem_request *req_data;
+ switch (ret) {
+ case VIRTIO_PMEM_RESP_TYPE_OK:
+ return 0;
+ case VIRTIO_PMEM_RESP_TYPE_EINVAL:
+ return -EINVAL;
+ case VIRTIO_PMEM_RESP_TYPE_ENOTSUP:
+ return -EOPNOTSUPP;
+ case VIRTIO_PMEM_RESP_TYPE_EIO:
+ default:
+ return -EIO;
+ }
+}
+
+/*
+ * Submit one request buffer to the device and wait for the host to complete
+ * it. Takes ownership of @req_data and drops the caller's kref before
+ * returning.
+ */
+static int virtio_pmem_submit(struct virtio_pmem *vpmem,
+ struct virtio_pmem_request *req_data,
+ void *req, size_t req_len)
+{
+ struct virtio_device *vdev = vpmem->vdev;
struct scatterlist *sgs[2], sg, ret;
unsigned long flags;
int err, err1;
+ kref_init(&req_data->kref);
+
guard(mutex)(&vpmem->flush_lock);
/*
@@ -156,23 +178,21 @@ static int virtio_pmem_flush(struct nd_region *nd_region)
*/
if (vdev->config->get_status(vdev) & VIRTIO_CONFIG_S_NEEDS_RESET) {
dev_info(&vdev->dev, "virtio pmem device needs a reset\n");
- return -EIO;
+ err = -EIO;
+ goto out_put;
}
- if (READ_ONCE(vpmem->broken))
- return -EIO;
-
- req_data = kmalloc_obj(*req_data, GFP_NOIO);
- if (!req_data)
- return -ENOMEM;
+ if (READ_ONCE(vpmem->broken)) {
+ err = -EIO;
+ goto out_put;
+ }
- kref_init(&req_data->kref);
+ req_data->resp.ret = cpu_to_le32(VIRTIO_PMEM_RESP_TYPE_EIO);
WRITE_ONCE(req_data->done, false);
init_waitqueue_head(&req_data->host_acked);
init_waitqueue_head(&req_data->wq_buf);
INIT_LIST_HEAD(&req_data->list);
- req_data->req.type = cpu_to_le32(VIRTIO_PMEM_REQ_TYPE_FLUSH);
- sg_init_one(&sg, &req_data->req, sizeof(req_data->req));
+ sg_init_one(&sg, req, req_len);
sgs[0] = &sg;
sg_init_one(&ret, &req_data->resp.ret, sizeof(req_data->resp));
sgs[1] = &ret;
@@ -246,15 +266,122 @@ static int virtio_pmem_flush(struct nd_region *nd_region)
virtio_pmem_req_done(req_data) ||
READ_ONCE(vpmem->broken));
if (virtio_pmem_req_done(req_data))
- err = le32_to_cpu(req_data->resp.ret);
+ err = virtio_pmem_resp_to_errno(le32_to_cpu(req_data->resp.ret));
else
err = -EIO;
}
+out_put:
kref_put(&req_data->kref, virtio_pmem_req_release);
return err;
+}
+
+/* The flush request submission function */
+static int virtio_pmem_flush(struct nd_region *nd_region)
+{
+ struct virtio_device *vdev = nd_region->provider_data;
+ struct virtio_pmem *vpmem = vdev->priv;
+ struct virtio_pmem_request *req_data;
+
+ req_data = kmalloc_obj(*req_data, GFP_NOIO);
+ if (!req_data)
+ return -ENOMEM;
+
+ req_data->req.type = cpu_to_le32(VIRTIO_PMEM_REQ_TYPE_FLUSH);
+ return virtio_pmem_submit(vpmem, req_data, &req_data->req,
+ sizeof(req_data->req));
+}
+
+struct virtio_pmem_discard_request {
+ struct virtio_pmem_request base;
+ struct virtio_pmem_discard_req dreq;
};
+/* virtio_pmem_req_release() frees the allocation through &base */
+static_assert(offsetof(struct virtio_pmem_discard_request, base) == 0);
+
+/**
+ * virtio_pmem_discard - ask the host to drop the backing store of ranges
+ * @nd_region: region created by virtio_pmem_probe()
+ * @ranges: physical address ranges (inclusive end) inside the region
+ * @nr: number of ranges, 1..ND_DISCARD_MAX_RANGES
+ *
+ * Only installed as nd_region->discard when VIRTIO_PMEM_F_DISCARD was
+ * negotiated. Every range must be aligned to vpmem->discard_granularity.
+ * Ranges are pre-validated and submitted in chunks of up to
+ * vpmem->max_discard_extents. The host releases the backing store of all
+ * extents (or none, on a validation failure) before completing each request;
+ * subsequent reads return zeroes.
+ */
+int virtio_pmem_discard(struct nd_region *nd_region, const struct range *ranges,
+ unsigned int nr)
+{
+ struct virtio_device *vdev = nd_region->provider_data;
+ struct virtio_pmem *vpmem = vdev->priv;
+ struct virtio_pmem_discard_request *vreq;
+ unsigned int i, off;
+ u64 region_end;
+ int err = 0;
+
+ if (!virtio_has_feature(vdev, VIRTIO_PMEM_F_DISCARD))
+ return -EOPNOTSUPP;
+ if (!nr || nr > ND_DISCARD_MAX_RANGES || !vpmem->size ||
+ !vpmem->discard_granularity || !vpmem->max_discard_extents)
+ return -EINVAL;
+ region_end = vpmem->start + vpmem->size - 1;
+ if (region_end < vpmem->start)
+ return -EINVAL;
+ for (i = 0; i < nr; i++) {
+ u64 len;
+
+ if (ranges[i].start > ranges[i].end)
+ return -EINVAL;
+ len = range_len(&ranges[i]);
+ if (ranges[i].start < vpmem->start || !len ||
+ ranges[i].end > region_end ||
+ !IS_ALIGNED(ranges[i].start - vpmem->start,
+ vpmem->discard_granularity) ||
+ !IS_ALIGNED(len, vpmem->discard_granularity))
+ return -EINVAL;
+ }
+
+ for (off = 0; off < nr; ) {
+ unsigned int chunk = min_t(unsigned int, nr - off,
+ vpmem->max_discard_extents);
+ size_t req_len = struct_size(&vreq->dreq, extents, chunk);
+
+ vreq = kzalloc(struct_size(vreq, dreq.extents, chunk),
+ GFP_NOIO);
+ if (!vreq)
+ return -ENOMEM;
+
+ vreq->dreq.type = cpu_to_le32(VIRTIO_PMEM_REQ_TYPE_DISCARD);
+ vreq->dreq.flags = 0;
+ vreq->dreq.count = cpu_to_le16(chunk);
+ for (i = 0; i < chunk; i++) {
+ vreq->dreq.extents[i].offset =
+ cpu_to_le64(ranges[off + i].start -
+ vpmem->start);
+ vreq->dreq.extents[i].len =
+ cpu_to_le64(range_len(&ranges[off + i]));
+ }
+
+ err = virtio_pmem_submit(vpmem, &vreq->base, &vreq->dreq,
+ req_len);
+ if (err) {
+ dev_warn_ratelimited(&vdev->dev,
+ "discard of %u extent(s) from %#llx failed: %d\n",
+ chunk,
+ ranges[off].start - vpmem->start,
+ err);
+ return err;
+ }
+ off += chunk;
+ }
+ return 0;
+}
+EXPORT_SYMBOL_GPL(virtio_pmem_discard);
+
static void virtio_pmem_flush_work(struct work_struct *work)
{
struct virtio_pmem_flush_work *flush;
@@ -262,8 +389,6 @@ static void virtio_pmem_flush_work(struct work_struct *work)
flush = container_of(work, struct virtio_pmem_flush_work, work);
err = virtio_pmem_flush(flush->nd_region);
- if (err > 0)
- err = -EIO;
if (err)
flush->bio->bi_status = errno_to_blk_status(err);
bio_endio(flush->bio);
@@ -277,7 +402,6 @@ int async_pmem_flush(struct nd_region *nd_region, struct bio *bio)
struct virtio_pmem *vpmem = vdev->priv;
struct virtio_pmem_flush_work *flush;
unsigned long flags;
- int err;
if (bio && bio->bi_iter.bi_sector != -1) {
flush = kmalloc_obj(*flush, GFP_NOIO);
@@ -299,11 +423,7 @@ int async_pmem_flush(struct nd_region *nd_region, struct bio *bio)
return NVDIMM_FLUSH_ASYNC;
}
- err = virtio_pmem_flush(nd_region);
- if (err > 0)
- return -EIO;
-
- return err;
+ return virtio_pmem_flush(nd_region);
};
EXPORT_SYMBOL_GPL(async_pmem_flush);
MODULE_DESCRIPTION("Virtio Persistent Memory Driver");
diff --git a/drivers/nvdimm/region_devs.c b/drivers/nvdimm/region_devs.c
index 09842ca681107..25ff8489313f9 100644
--- a/drivers/nvdimm/region_devs.c
+++ b/drivers/nvdimm/region_devs.c
@@ -1045,6 +1045,11 @@ static struct nd_region *nd_region_create(struct nvdimm_bus *nvdimm_bus,
nd_region->flush = ndr_desc->flush;
else
nd_region->flush = NULL;
+ if (ndr_desc->discard &&
+ nvdimm_discard_granularity_valid(ndr_desc->discard_granularity)) {
+ nd_region->discard = ndr_desc->discard;
+ nd_region->discard_granularity = ndr_desc->discard_granularity;
+ }
device_initialize(dev);
lockdep_set_class(&dev->mutex, &nvdimm_region_key);
@@ -1173,6 +1178,62 @@ int nvdimm_has_flush(struct nd_region *nd_region)
}
EXPORT_SYMBOL_GPL(nvdimm_has_flush);
+/**
+ * nvdimm_discard_granularity - return the discard alignment granularity in bytes
+ * @nd_region: pmem region
+ *
+ * Returns a power-of-2 byte granularity (>= PAGE_SIZE) if the region provider
+ * supports discarding physical ranges, or 0 if unsupported.
+ */
+u64 nvdimm_discard_granularity(struct nd_region *nd_region)
+{
+ if (!nd_region->discard)
+ return 0;
+ return nd_region->discard_granularity;
+}
+EXPORT_SYMBOL_GPL(nvdimm_discard_granularity);
+
+/**
+ * nvdimm_discard - return the backing store of physical ranges to the provider
+ * @nd_region: pmem region
+ * @ranges: physical address ranges (inclusive end), each inside the region
+ * @nr: number of ranges, 1..ND_DISCARD_MAX_RANGES
+ *
+ * Returns 0 on success, -EOPNOTSUPP when the provider has no discard
+ * capability, -EINVAL for ranges outside the region or unaligned to
+ * nd_region->discard_granularity.
+ */
+int nvdimm_discard(struct nd_region *nd_region, const struct range *ranges,
+ unsigned int nr)
+{
+ u64 gran = nd_region->discard_granularity;
+ unsigned int i;
+ u64 region_end;
+
+ if (!nd_region->discard || !gran)
+ return -EOPNOTSUPP;
+ if (!nr || nr > ND_DISCARD_MAX_RANGES || !nd_region->ndr_size)
+ return -EINVAL;
+ region_end = nd_region->ndr_start + nd_region->ndr_size - 1;
+ if (region_end < nd_region->ndr_start)
+ return -EINVAL;
+ for (i = 0; i < nr; i++) {
+ u64 len;
+
+ if (ranges[i].start > ranges[i].end)
+ return -EINVAL;
+ len = range_len(&ranges[i]);
+ if (ranges[i].start < nd_region->ndr_start || !len ||
+ ranges[i].end > region_end ||
+ !IS_ALIGNED(ranges[i].start - nd_region->ndr_start, gran) ||
+ !IS_ALIGNED(len, gran))
+ return -EINVAL;
+ }
+
+ return nd_region->discard(nd_region, ranges, nr);
+}
+EXPORT_SYMBOL_GPL(nvdimm_discard);
+
int nvdimm_has_cache(struct nd_region *nd_region)
{
return is_nd_pmem(&nd_region->dev) &&
diff --git a/drivers/nvdimm/virtio_pmem.c b/drivers/nvdimm/virtio_pmem.c
index 3e06ff34c4afc..7a97c963b7df2 100644
--- a/drivers/nvdimm/virtio_pmem.c
+++ b/drivers/nvdimm/virtio_pmem.c
@@ -56,6 +56,24 @@ static int virtio_pmem_validate(struct virtio_device *vdev)
VIRTIO_PMEM_SHMEM_REGION_ID);
__virtio_clear_bit(vdev, VIRTIO_PMEM_F_SHMEM_REGION);
}
+ if (virtio_has_feature(vdev, VIRTIO_PMEM_F_DISCARD)) {
+ u64 granularity = 0;
+ u32 max_extents = 0;
+
+ if (vdev->config->get) {
+ virtio_cread_le(vdev, struct virtio_pmem_config,
+ discard_granularity, &granularity);
+ virtio_cread_le(vdev, struct virtio_pmem_config,
+ max_discard_extents, &max_extents);
+ }
+ if (!nvdimm_discard_granularity_valid(granularity) ||
+ !max_extents) {
+ dev_notice(&vdev->dev,
+ "invalid discard config (granularity=%llu, max_extents=%u), disabling discard\n",
+ granularity, max_extents);
+ __virtio_clear_bit(vdev, VIRTIO_PMEM_F_DISCARD);
+ }
+ }
return 0;
}
@@ -133,6 +151,31 @@ static int virtio_pmem_probe(struct virtio_device *vdev)
}
ndr_desc.flush = async_pmem_flush;
+ if (virtio_has_feature(vdev, VIRTIO_PMEM_F_DISCARD)) {
+ u32 max_extents;
+
+ virtio_cread_le(vdev, struct virtio_pmem_config,
+ discard_granularity,
+ &vpmem->discard_granularity);
+ virtio_cread_le(vdev, struct virtio_pmem_config,
+ max_discard_extents, &max_extents);
+ vpmem->max_discard_extents =
+ min_t(u32, max_extents, VIRTIO_PMEM_DISCARD_MAX_EXTENTS);
+ /* The config was validated earlier but is re-read here */
+ if (nvdimm_discard_granularity_valid(vpmem->discard_granularity) &&
+ vpmem->max_discard_extents) {
+ ndr_desc.discard = virtio_pmem_discard;
+ ndr_desc.discard_granularity =
+ vpmem->discard_granularity;
+ dev_info(&vdev->dev,
+ "discard supported (granularity=%llu, max_extents=%u)\n",
+ vpmem->discard_granularity,
+ vpmem->max_discard_extents);
+ } else {
+ dev_notice(&vdev->dev,
+ "discard config changed after validation, disabling discard\n");
+ }
+ }
ndr_desc.provider_data = vdev;
set_bit(ND_REGION_PAGEMAP, &ndr_desc.flags);
set_bit(ND_REGION_ASYNC, &ndr_desc.flags);
@@ -219,6 +262,7 @@ static int virtio_pmem_restore(struct virtio_device *vdev)
static unsigned int features[] = {
VIRTIO_PMEM_F_SHMEM_REGION,
+ VIRTIO_PMEM_F_DISCARD,
};
static struct virtio_driver virtio_pmem_driver = {
diff --git a/drivers/nvdimm/virtio_pmem.h b/drivers/nvdimm/virtio_pmem.h
index 0b90777d7658b..51fc0fa4b0651 100644
--- a/drivers/nvdimm/virtio_pmem.h
+++ b/drivers/nvdimm/virtio_pmem.h
@@ -43,7 +43,7 @@ struct virtio_pmem {
/* Virtio pmem request queue */
struct virtqueue *req_vq;
- /* Serialize flush requests to the device. */
+ /* Serialize requests to the device. */
struct mutex flush_lock;
/* Complete asynchronous FUA flushes outside the submit path. */
@@ -68,10 +68,18 @@ struct virtio_pmem {
/* Memory region information */
__u64 start;
__u64 size;
+
+ /* Discard parameters negotiated via VIRTIO_PMEM_F_DISCARD */
+ u64 discard_granularity;
+ u32 max_discard_extents;
};
+#define VIRTIO_PMEM_DISCARD_MAX_EXTENTS ND_DISCARD_MAX_RANGES
+
void virtio_pmem_host_ack(struct virtqueue *vq);
void virtio_pmem_mark_broken(struct virtio_pmem *vpmem);
void virtio_pmem_drain(struct virtio_pmem *vpmem);
int async_pmem_flush(struct nd_region *nd_region, struct bio *bio);
+int virtio_pmem_discard(struct nd_region *nd_region, const struct range *ranges,
+ unsigned int nr);
#endif
diff --git a/include/linux/libnvdimm.h b/include/linux/libnvdimm.h
index d929d83abf3be..9214e395a07de 100644
--- a/include/linux/libnvdimm.h
+++ b/include/linux/libnvdimm.h
@@ -124,6 +124,7 @@ struct nd_mapping_desc {
};
struct bio;
+struct range;
struct resource;
struct nd_region;
@@ -149,6 +150,15 @@ struct nd_region_desc {
int memregion;
struct device_node *of_node;
int (*flush)(struct nd_region *nd_region, struct bio *bio);
+ /*
+ * Optional: return the backing store of @nr physical ranges to the
+ * provider (e.g. a virtio-pmem host punches holes in the backing
+ * file). Subsequent reads of the ranges return zeroes.
+ * @discard_granularity must be a power-of-2 byte alignment >= PAGE_SIZE.
+ */
+ int (*discard)(struct nd_region *nd_region, const struct range *ranges,
+ unsigned int nr);
+ u64 discard_granularity;
};
struct device;
@@ -310,6 +320,16 @@ u64 nd_fletcher64(void *addr, size_t len, bool le);
int nvdimm_flush(struct nd_region *nd_region, struct bio *bio);
int generic_nvdimm_flush(struct nd_region *nd_region);
int nvdimm_has_flush(struct nd_region *nd_region);
+/* Maximum number of ranges accepted by one nvdimm_discard() call */
+#define ND_DISCARD_MAX_RANGES 64
+static inline bool nvdimm_discard_granularity_valid(u64 gran)
+{
+ return gran >= PAGE_SIZE && gran <= S64_MAX && !(gran & (gran - 1));
+}
+
+u64 nvdimm_discard_granularity(struct nd_region *nd_region);
+int nvdimm_discard(struct nd_region *nd_region, const struct range *ranges,
+ unsigned int nr);
int nvdimm_has_cache(struct nd_region *nd_region);
int nvdimm_in_overwrite(struct nvdimm *nvdimm);
bool is_nvdimm_sync(struct nd_region *nd_region);
diff --git a/include/uapi/linux/virtio_pmem.h b/include/uapi/linux/virtio_pmem.h
index ede4f3564977d..2698f7a7410a2 100644
--- a/include/uapi/linux/virtio_pmem.h
+++ b/include/uapi/linux/virtio_pmem.h
@@ -17,6 +17,11 @@
/* Feature bits */
/* guest physical address range will be indicated as shared memory region 0 */
#define VIRTIO_PMEM_F_SHMEM_REGION 0
+/*
+ * Device supports VIRTIO_PMEM_REQ_TYPE_DISCARD: the guest can ask the host
+ * to release the backing store of ranges of the pmem region.
+ */
+#define VIRTIO_PMEM_F_DISCARD 1
/* shmid of the shared memory region corresponding to the pmem */
#define VIRTIO_PMEM_SHMEM_REGION_ID 0
@@ -24,12 +29,29 @@
struct virtio_pmem_config {
__le64 start;
__le64 size;
+ /*
+ * Valid when VIRTIO_PMEM_F_DISCARD is negotiated:
+ * @discard_granularity: power-of-2 byte alignment (>= PAGE_SIZE) for
+ * discard extent offsets and lengths.
+ * @max_discard_extents: maximum number of extents per discard request,
+ * 1..65535 (virtio_pmem_discard_req.count is 16 bits wide).
+ */
+ __le64 discard_granularity;
+ __le32 max_discard_extents;
+ __le32 reserved;
};
#define VIRTIO_PMEM_REQ_TYPE_FLUSH 0
+#define VIRTIO_PMEM_REQ_TYPE_DISCARD 1
+
+/* Host return status (struct virtio_pmem_resp.ret) */
+#define VIRTIO_PMEM_RESP_TYPE_OK 0
+#define VIRTIO_PMEM_RESP_TYPE_EIO 1
+#define VIRTIO_PMEM_RESP_TYPE_EINVAL 2
+#define VIRTIO_PMEM_RESP_TYPE_ENOTSUP 3
struct virtio_pmem_resp {
- /* Host return status corresponding to flush request */
+ /* Host return status corresponding to the request */
__le32 ret;
};
@@ -38,4 +60,29 @@ struct virtio_pmem_req {
__le32 type;
};
+struct virtio_pmem_discard_extent {
+ /* byte offset relative to the start of the pmem region */
+ __le64 offset;
+ /* number of bytes, non-zero */
+ __le64 len;
+};
+
+/*
+ * VIRTIO_PMEM_REQ_TYPE_DISCARD request. Offsets and lengths must be
+ * multiples of virtio_pmem_config.discard_granularity, and @count must be
+ * in 1..virtio_pmem_config.max_discard_extents. The device validates every
+ * extent before releasing any backing store (e.g. fallocate(FALLOC_FL_PUNCH_HOLE)
+ * on the host file) and only completes the request once all extents have
+ * been released; subsequent guest reads of the ranges return zeroes.
+ */
+struct virtio_pmem_discard_req {
+ /* VIRTIO_PMEM_REQ_TYPE_DISCARD */
+ __le32 type;
+ /* reserved, must be zero */
+ __le16 flags;
+ /* number of valid entries in @extents */
+ __le16 count;
+ struct virtio_pmem_discard_extent extents[];
+};
+
#endif
--
2.56.1.839.g22a8290db9-goog
^ permalink raw reply [flat|nested] 6+ messages in thread* [RFC PATCH 3/5] vfs: allow fallocate() on character devices implementing ->fallocate()
2026-11-30 1:23 [RFC PATCH 0/5] virtio-pmem & device-dax: host-backed range discard via fallocate() / MADV_REMOVE Sourav Panda
2026-11-30 1:23 ` [RFC PATCH 1/5] dax/device: validate mmap offset alignment against dev_dax->align Sourav Panda
2026-11-30 1:23 ` [RFC PATCH 2/5] virtio_pmem: add VIRTIO_PMEM_F_DISCARD and region discard hook Sourav Panda
@ 2026-11-30 1:23 ` Sourav Panda
2026-11-30 1:23 ` [RFC PATCH 4/5] dax/device: add fallocate() discard support Sourav Panda
2026-11-30 1:23 ` [RFC PATCH 5/5] selftests/dax: add devdax_discard tests Sourav Panda
4 siblings, 0 replies; 6+ messages in thread
From: Sourav Panda @ 2026-11-30 1:23 UTC (permalink / raw)
To: djbw, vishal.l.verma, dave.jiang, alison.schofield,
pankaj.gupta.linux, mst, jasowangio, eperezma, viro, brauner
Cc: iweiny, jack, xuanzhuo, shuah, david, souravpanda, nvdimm,
linux-cxl, virtualization, linux-fsdevel, linux-kselftest,
linux-mm, linux-kernel
vfs_fallocate() returns -ENODEV for anything that is not a regular file
or a block device, before it looks at f_op->fallocate. Let a character
device through when its driver implements ->fallocate(). All other
character devices keep returning -ENODEV, and since no character device
in the tree implements ->fallocate() today, nothing changes for existing
drivers.
The first user is device-dax, in a later patch, where punching a hole
releases device memory. An ioctl could do that too, but
madvise(MADV_REMOVE) is implemented by calling vfs_fallocate() with
FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE on the mapped file. Going
through ->fallocate() lets an allocator release part of a device-dax
mapping with the madvise() call it already uses for shmem.
The permission and sanity checks in vfs_fallocate() are unchanged and
still run before the driver is called.
Signed-off-by: Sourav Panda <souravpanda@google.com>
---
fs/open.c | 8 +++++++-
1 file changed, 7 insertions(+), 1 deletion(-)
diff --git a/fs/open.c b/fs/open.c
index bb484b07390ac..0f31caf9e7597 100644
--- a/fs/open.c
+++ b/fs/open.c
@@ -321,7 +321,13 @@ int vfs_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
if (S_ISDIR(inode->i_mode))
return -EISDIR;
- if (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))
+ /*
+ * Character devices that implement ->fallocate() (device-dax uses it
+ * for discard, see drivers/dax/device.c) are allowed through; all other
+ * character devices keep -ENODEV.
+ */
+ if (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode) &&
+ !(S_ISCHR(inode->i_mode) && file->f_op->fallocate))
return -ENODEV;
/* Check for wraparound */
--
2.56.1.839.g22a8290db9-goog
^ permalink raw reply [flat|nested] 6+ messages in thread
* [RFC PATCH 4/5] dax/device: add fallocate() discard support
2026-11-30 1:23 [RFC PATCH 0/5] virtio-pmem & device-dax: host-backed range discard via fallocate() / MADV_REMOVE Sourav Panda
` (2 preceding siblings ...)
2026-11-30 1:23 ` [RFC PATCH 3/5] vfs: allow fallocate() on character devices implementing ->fallocate() Sourav Panda
@ 2026-11-30 1:23 ` Sourav Panda
2026-11-30 1:23 ` [RFC PATCH 5/5] selftests/dax: add devdax_discard tests Sourav Panda
4 siblings, 0 replies; 6+ messages in thread
From: Sourav Panda @ 2026-11-30 1:23 UTC (permalink / raw)
To: djbw, vishal.l.verma, dave.jiang, alison.schofield,
pankaj.gupta.linux, mst, jasowangio, eperezma, viro, brauner
Cc: iweiny, jack, xuanzhuo, shuah, david, souravpanda, nvdimm,
linux-cxl, virtualization, linux-fsdevel, linux-kselftest,
linux-mm, linux-kernel
Memory handed out through a device-dax instance cannot be given back.
A process can stop using part of the device, but nothing tells the
provider, so a host backing the device for a guest keeps every page the
guest has touched.
Implement ->fallocate() for FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE.
When the dax_region has a discard callback, punching a hole releases the
backing of the range and it reads back as zeroes. dax_pmem installs the
callback if the nd_region provides one, which virtio-pmem does once
VIRTIO_PMEM_F_DISCARD is negotiated. madvise(MADV_REMOVE) ends up in
the same place.
Offset and length must be multiples of the provider's granularity, which
has nothing to do with dev_dax->align. It is exported in a new
read-only discard_granularity attribute; 0 means the device cannot
discard, and fallocate() then fails with -EOPNOTSUPP.
Before the provider is called the range has to be unreachable:
- Mappings are removed with unmap_mapping_range() over the range
rounded out to dev_dax->align. Device-dax only installs entries of
that size, so a 2M discard inside a 1G mapping zaps the 1G entry and
the next access faults it back in at 1G. Nothing is split.
- Faults must not repopulate the range while it is being released. A
per-device percpu rw-semaphore is held for write across the unmap and
the discard, and dev_dax_huge_fault() takes it for read. The
mapping's invalidate_lock would work as well, but with a shared rwsem
in the fault path 16 processes faulting on one device lost up to 64%
of their throughput to cache line contention in a fault-heavy
microbenchmark. With the percpu lock they match an unpatched kernel.
The cost moves to the write side: an isolated discard waits for an
RCU grace period (about 4ms instead of 0.3ms in the same setup),
while back-to-back discards do not. Devices that cannot discard do
not take the lock at all.
- Pages can still be referenced without being mapped, for example when
pinned for DMA or sitting in a pipe after vmsplice(). After the
unmap an idle folio has a refcount of one, so a higher count fails
the call with -EBUSY before any range is released.
A file opened under device_dax can outlive the driver binding, and by
then another dax driver may have marked the dax_device alive again.
dax_fallocate() therefore also checks that device_dax is still the bound
driver and returns -ENODEV if it is not.
Signed-off-by: Sourav Panda <souravpanda@google.com>
---
Documentation/ABI/testing/sysfs-bus-dax | 11 ++
drivers/dax/bus.c | 40 +++++
drivers/dax/bus.h | 5 +
drivers/dax/dax-private.h | 39 +++++
drivers/dax/device.c | 191 +++++++++++++++++++++++-
drivers/dax/pmem.c | 16 ++
6 files changed, 301 insertions(+), 1 deletion(-)
diff --git a/Documentation/ABI/testing/sysfs-bus-dax b/Documentation/ABI/testing/sysfs-bus-dax
index 60703fffa99e0..4d6399e29ced9 100644
--- a/Documentation/ABI/testing/sysfs-bus-dax
+++ b/Documentation/ABI/testing/sysfs-bus-dax
@@ -175,3 +175,14 @@ Description:
A device can only be onlined from the "unplugged" state, so a
device must be returned to "unplugged" before it can be onlined
into a different state.
+
+What: /sys/bus/dax/devices/daxX.Y/discard_granularity
+Date: November, 2026
+KernelVersion: v7.4
+Contact: nvdimm@lists.linux.dev
+Description:
+ (RO) Reports the discard alignment granularity in bytes for
+ fallocate(FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE) and
+ madvise(MADV_REMOVE) on this dax device. Returns a power-of-2
+ byte size (>= PAGE_SIZE) if the backing provider supports
+ discard, or "0" if discard is not supported.
diff --git a/drivers/dax/bus.c b/drivers/dax/bus.c
index e40c25401cf06..652541627dd78 100644
--- a/drivers/dax/bus.c
+++ b/drivers/dax/bus.c
@@ -690,6 +690,27 @@ struct dax_region *alloc_dax_region(struct device *parent, int region_id,
}
EXPORT_SYMBOL_GPL(alloc_dax_region);
+/**
+ * dax_region_set_discard - install a provider hook to return physical ranges
+ * @dax_region: region whose child devices gain fallocate() discard support
+ * @discard: callback releasing the backing store of physical ranges
+ * @granularity: power-of-2 byte alignment (>= PAGE_SIZE) for @discard
+ *
+ * Must be called before any dev_dax is created in @dax_region.
+ */
+void dax_region_set_discard(struct dax_region *dax_region,
+ int (*discard)(struct dax_region *dax_region,
+ const struct range *ranges,
+ unsigned int nr),
+ u64 granularity)
+{
+ if (!discard || !dax_discard_granularity_valid(granularity))
+ return;
+ dax_region->discard = discard;
+ dax_region->discard_granularity = granularity;
+}
+EXPORT_SYMBOL_GPL(dax_region_set_discard);
+
static void dax_mapping_release(struct device *dev)
{
struct dax_mapping *mapping = to_dax_mapping(dev);
@@ -1377,6 +1398,16 @@ static ssize_t memmap_on_memory_store(struct device *dev,
}
static DEVICE_ATTR_RW(memmap_on_memory);
+static ssize_t discard_granularity_show(struct device *dev,
+ struct device_attribute *attr,
+ char *buf)
+{
+ struct dev_dax *dev_dax = to_dev_dax(dev);
+
+ return sysfs_emit(buf, "%llu\n", dev_dax_discard_granularity(dev_dax));
+}
+static DEVICE_ATTR_RO(discard_granularity);
+
static umode_t dev_dax_visible(struct kobject *kobj, struct attribute *a, int n)
{
struct device *dev = container_of(kobj, struct device, kobj);
@@ -1404,6 +1435,7 @@ static struct attribute *dev_dax_attributes[] = {
&dev_attr_resource.attr,
&dev_attr_numa_node.attr,
&dev_attr_memmap_on_memory.attr,
+ &dev_attr_discard_granularity.attr,
NULL,
};
@@ -1425,6 +1457,7 @@ static void dev_dax_release(struct device *dev)
put_dax(dax_dev);
free_dev_dax_id(dev_dax);
kfree(dev_dax->pgmap);
+ percpu_free_rwsem(&dev_dax->discard_rwsem);
kfree(dev_dax);
}
@@ -1468,6 +1501,12 @@ static struct dev_dax *__devm_create_dev_dax(struct dev_dax_data *data)
return ERR_PTR(-ENOMEM);
dev_dax->region = dax_region;
+ if (dax_region->discard) {
+ rc = percpu_init_rwsem(&dev_dax->discard_rwsem);
+ if (rc)
+ goto err_id;
+ dev_dax->discard_granularity = dax_region->discard_granularity;
+ }
if (is_static(dax_region)) {
if (dev_WARN_ONCE(parent, data->id < 0,
"dynamic id specified to static region\n")) {
@@ -1564,6 +1603,7 @@ static struct dev_dax *__devm_create_dev_dax(struct dev_dax_data *data)
err_range:
free_dev_dax_id(dev_dax);
err_id:
+ percpu_free_rwsem(&dev_dax->discard_rwsem);
kfree(dev_dax);
return ERR_PTR(rc);
diff --git a/drivers/dax/bus.h b/drivers/dax/bus.h
index bfc31923f3ff4..aa6a607ebdf22 100644
--- a/drivers/dax/bus.h
+++ b/drivers/dax/bus.h
@@ -31,6 +31,11 @@ struct dev_dax_data {
};
struct dev_dax *devm_create_dev_dax(struct dev_dax_data *data);
+void dax_region_set_discard(struct dax_region *dax_region,
+ int (*discard)(struct dax_region *dax_region,
+ const struct range *ranges,
+ unsigned int nr),
+ u64 granularity);
enum dax_driver_type {
DAXDRV_KMEM_TYPE,
diff --git a/drivers/dax/dax-private.h b/drivers/dax/dax-private.h
index 607a53a91f58b..32bdf644f9e22 100644
--- a/drivers/dax/dax-private.h
+++ b/drivers/dax/dax-private.h
@@ -8,6 +8,9 @@
#include <linux/device.h>
#include <linux/cdev.h>
#include <linux/idr.h>
+#include <linux/percpu-rwsem.h>
+#include <linux/range.h>
+#include <linux/sizes.h>
/* private routines between core files */
struct dax_device;
@@ -27,6 +30,9 @@ void dax_bus_exit(void);
* @res: resource tree to track instance allocations
* @seed: allow userspace to find the first unbound seed device
* @youngest: allow userspace to find the most recently created device
+ * @discard: optional provider hook returning the backing store of a
+ * physical range (see dev_dax fallocate() support in device.c)
+ * @discard_granularity: power-of-2 byte alignment for @discard (0 if none)
*/
struct dax_region {
int id;
@@ -38,6 +44,9 @@ struct dax_region {
struct resource res;
struct device *seed;
struct device *youngest;
+ int (*discard)(struct dax_region *dax_region, const struct range *ranges,
+ unsigned int nr);
+ u64 discard_granularity;
};
/**
@@ -80,6 +89,13 @@ struct dev_dax_range {
* @memmap_on_memory: allow kmem to put the memmap in the memory
* @nr_range: size of @ranges
* @ranges: range tuples of memory used
+ * @device_dax_bound: device_dax is the bound driver (see dev_dax_probe())
+ * @discard_granularity: copy of the region's discard granularity, 0 if
+ * the region cannot discard; unlike @region it
+ * stays valid for as long as the dev_dax does
+ * @discard_rwsem: held for read by page faults and for write by
+ * dax_fallocate(); only initialized when
+ * @discard_granularity is non-zero
*/
struct dev_dax {
struct dax_region *region;
@@ -95,6 +111,9 @@ struct dev_dax {
bool memmap_on_memory;
int nr_range;
struct dev_dax_range *ranges;
+ bool device_dax_bound;
+ u64 discard_granularity;
+ struct percpu_rw_semaphore discard_rwsem;
};
/*
@@ -116,6 +135,26 @@ static inline struct dax_mapping *to_dax_mapping(struct device *dev)
phys_addr_t dax_pgoff_to_phys(struct dev_dax *dev_dax, pgoff_t pgoff, unsigned long size);
+static inline bool dax_discard_granularity_valid(u64 gran)
+{
+ return gran >= PAGE_SIZE && gran <= S64_MAX && !(gran & (gran - 1));
+}
+
+static inline u64 dev_dax_discard_granularity(struct dev_dax *dev_dax)
+{
+ return dev_dax->discard_granularity;
+}
+
+static inline u64 dev_dax_bytes(struct dev_dax *dev_dax)
+{
+ u64 size = 0;
+ int i;
+
+ for (i = 0; i < dev_dax->nr_range; i++)
+ size += range_len(&dev_dax->ranges[i].range);
+ return size;
+}
+
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
static inline bool dax_align_valid(unsigned long align)
{
diff --git a/drivers/dax/device.c b/drivers/dax/device.c
index 9c956085d9122..53192614bab3f 100644
--- a/drivers/dax/device.c
+++ b/drivers/dax/device.c
@@ -10,6 +10,7 @@
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/mman.h>
+#include <linux/falloc.h>
#include "dax-private.h"
#include "bus.h"
@@ -226,11 +227,18 @@ static vm_fault_t dev_dax_huge_fault(struct vm_fault *vmf, unsigned int order)
vm_fault_t rc = VM_FAULT_SIGBUS;
int id;
struct dev_dax *dev_dax = filp->private_data;
+ /*
+ * Only a discard-capable device has to exclude dax_fallocate(). The
+ * percpu rwsem keeps concurrent faults from sharing a cache line.
+ */
+ bool discard = dev_dax_discard_granularity(dev_dax);
dev_dbg(&dev_dax->dev, "%s: op=%s addr=%#lx order=%d\n", current->comm,
(vmf->flags & FAULT_FLAG_WRITE) ? "write" : "read",
vmf->address & ~((1UL << (order + PAGE_SHIFT)) - 1), order);
+ if (discard)
+ percpu_down_read(&dev_dax->discard_rwsem);
id = dax_read_lock();
if (order == 0)
rc = __dev_dax_pte_fault(dev_dax, vmf);
@@ -242,6 +250,8 @@ static vm_fault_t dev_dax_huge_fault(struct vm_fault *vmf, unsigned int order)
rc = VM_FAULT_SIGBUS;
dax_read_unlock(id);
+ if (discard)
+ percpu_up_read(&dev_dax->discard_rwsem);
return rc;
}
@@ -276,6 +286,180 @@ static const struct vm_operations_struct dax_vm_ops = {
.pagesize = dev_dax_pagesize,
};
+/*
+ * Discard support
+ *
+ * When a dev_dax's provider supports discard (see dax_region->discard):
+ * - fallocate(fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, offset, len)
+ * and madvise(MADV_REMOVE) release the backing store of the range so
+ * subsequent reads return zeroes.
+ * - Offsets and lengths must be multiples of dax_region->discard_granularity,
+ * independent of dev_dax->align. Devices without a discard provider reject
+ * fallocate() with -EOPNOTSUPP.
+ * - Serialization against concurrent faults and GUP/DMA pins uses
+ * dev_dax->discard_rwsem (write) + unmap_mapping_range() (aligned to
+ * dev_dax->align so huge mappings are zapped without splitting) followed by
+ * a folio_ref_count() > 1 check (-EBUSY if pinned or referenced).
+ */
+
+#define DEV_DAX_DISCARD_BATCH 16
+
+static bool dax_range_valid(struct dev_dax *dev_dax, loff_t offset, loff_t len,
+ u64 gran)
+{
+ u64 end;
+
+ if (offset < 0 || len <= 0)
+ return false;
+ if (!IS_ALIGNED(offset, gran) || !IS_ALIGNED(len, gran))
+ return false;
+ if (check_add_overflow((u64)offset, (u64)len, &end) ||
+ end > dev_dax_bytes(dev_dax))
+ return false;
+ return true;
+}
+
+static bool dax_range_busy(const struct range *r)
+{
+ unsigned long pfn = PHYS_PFN(r->start);
+ unsigned long end_pfn = PHYS_PFN(r->end) + 1;
+ unsigned long iter = 0;
+
+ /*
+ * After unmap_mapping_range() with discard_rwsem held for write, an
+ * unreferenced MEMORY_DEVICE_GENERIC folio has refcount == 1. Any
+ * higher refcount indicates an active FOLL_PIN (DMA/GUP) or FOLL_GET
+ * (e.g. vmsplice pipe) reference. A folio only partly covered by the
+ * range is conservatively checked as a whole.
+ */
+ while (pfn < end_pfn) {
+ struct folio *folio = pfn_folio(pfn);
+
+ if (folio_ref_count(folio) > 1)
+ return true;
+ pfn = folio_pfn(folio) + folio_nr_pages(folio);
+ if ((++iter & 1023) == 0)
+ cond_resched();
+ }
+ return false;
+}
+
+static bool dax_intersect_range(const struct dev_dax_range *dax_range,
+ u64 cur, u64 end, struct range *r, u64 *next)
+{
+ u64 rstart = (u64)dax_range->pgoff << PAGE_SHIFT;
+ u64 rend = rstart + range_len(&dax_range->range);
+ u64 cstart, cend;
+
+ if (rend <= cur || rstart >= end)
+ return false;
+ cstart = max(cur, rstart);
+ cend = min(end, rend);
+ r->start = dax_range->range.start + (cstart - rstart);
+ r->end = dax_range->range.start + (cend - rstart) - 1;
+ *next = cend;
+ return true;
+}
+
+/*
+ * Validate and discard device byte range [start, end); caller holds
+ * discard_rwsem for write and dax_read_lock(). Pre-validates alignment and
+ * DMA pin absence across every intersecting sub-range before issuing any
+ * batched discard to the provider.
+ */
+static int dax_discard_range(struct dev_dax *dev_dax, u64 start, u64 end,
+ u64 gran)
+{
+ struct dax_region *dax_region = dev_dax->region;
+ struct range batch[DEV_DAX_DISCARD_BATCH];
+ unsigned int nr = 0;
+ u64 cur = start;
+ int i, rc;
+
+ for (i = 0; i < dev_dax->nr_range && cur < end; i++) {
+ struct range r;
+
+ if (!dax_intersect_range(&dev_dax->ranges[i], cur, end, &r, &cur))
+ continue;
+ if (!IS_ALIGNED(r.start - dax_region->res.start, gran) ||
+ !IS_ALIGNED(range_len(&r), gran))
+ return -EINVAL;
+ if (dax_range_busy(&r))
+ return -EBUSY;
+ }
+ if (cur < end)
+ return -EINVAL;
+
+ cur = start;
+ for (i = 0; i < dev_dax->nr_range && cur < end; i++) {
+ if (!dax_intersect_range(&dev_dax->ranges[i], cur, end,
+ &batch[nr], &cur))
+ continue;
+ if (++nr == ARRAY_SIZE(batch)) {
+ rc = dax_region->discard(dax_region, batch, nr);
+ if (rc)
+ return rc;
+ nr = 0;
+ }
+ }
+ if (nr)
+ return dax_region->discard(dax_region, batch, nr);
+ return 0;
+}
+
+/*
+ * A file opened under device_dax can outlive the driver binding, and another
+ * dax driver (e.g. fsdev_dax) may mark the dax_device alive again after a
+ * rebind. Only discard while device_dax still owns the device. Caller holds
+ * dax_read_lock(): dev_dax_kill() clears device_dax_bound only after
+ * kill_dax() has waited for all readers.
+ */
+static bool dev_dax_discard_allowed(struct dev_dax *dev_dax)
+{
+ return dax_alive(dev_dax->dax_dev) &&
+ READ_ONCE(dev_dax->device_dax_bound);
+}
+
+static long dax_fallocate(struct file *filp, int mode, loff_t offset,
+ loff_t len)
+{
+ struct dev_dax *dev_dax = filp->private_data;
+ struct address_space *mapping = filp->f_mapping;
+ struct device *dev = &dev_dax->dev;
+ u64 start = offset, end, gran, unmap_start, unmap_end;
+ int rc, id;
+
+ if (mode != (FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE))
+ return -EOPNOTSUPP;
+ /* Fixed when the device is created; discard_rwsem exists only if set */
+ gran = dev_dax_discard_granularity(dev_dax);
+ if (!gran)
+ return -EOPNOTSUPP;
+
+ percpu_down_write(&dev_dax->discard_rwsem);
+ id = dax_read_lock();
+ if (!dev_dax_discard_allowed(dev_dax)) {
+ rc = -ENODEV;
+ goto out;
+ }
+ if (!dax_range_valid(dev_dax, offset, len, gran)) {
+ dev_dbg(dev, "%s: %s: invalid range %#llx+%#llx\n",
+ current->comm, __func__, offset, len);
+ rc = -EINVAL;
+ goto out;
+ }
+ end = start + len;
+ unmap_start = round_down(start, dev_dax->align);
+ unmap_end = round_up(end, dev_dax->align);
+ unmap_mapping_range(mapping, unmap_start, unmap_end - unmap_start, 1);
+
+ rc = dax_discard_range(dev_dax, start, end, gran);
+out:
+ dax_read_unlock(id);
+ percpu_up_write(&dev_dax->discard_rwsem);
+ return rc;
+}
+
static int dax_mmap_prepare(struct vm_area_desc *desc)
{
struct file *filp = desc->file;
@@ -370,6 +554,7 @@ static const struct file_operations dax_fops = {
.release = dax_release,
.get_unmapped_area = dax_get_unmapped_area,
.mmap_prepare = dax_mmap_prepare,
+ .fallocate = dax_fallocate,
.fop_flags = FOP_MMAP_SYNC,
};
@@ -378,9 +563,12 @@ static void dev_dax_cdev_del(void *cdev)
cdev_del(cdev);
}
-static void dev_dax_kill(void *dev_dax)
+static void dev_dax_kill(void *data)
{
+ struct dev_dax *dev_dax = data;
+
kill_dev_dax(dev_dax);
+ WRITE_ONCE(dev_dax->device_dax_bound, false);
}
static int dev_dax_probe(struct dev_dax *dev_dax)
@@ -454,6 +642,7 @@ static int dev_dax_probe(struct dev_dax *dev_dax)
if (rc)
return rc;
+ WRITE_ONCE(dev_dax->device_dax_bound, true);
run_dax(dax_dev);
return devm_add_action_or_reset(dev, dev_dax_kill, dev_dax);
}
diff --git a/drivers/dax/pmem.c b/drivers/dax/pmem.c
index bee93066a8497..d8f3176512d2f 100644
--- a/drivers/dax/pmem.c
+++ b/drivers/dax/pmem.c
@@ -4,8 +4,18 @@
#include <linux/module.h>
#include "../nvdimm/pfn.h"
#include "../nvdimm/nd.h"
+#include "dax-private.h"
#include "bus.h"
+/* Forward a dev_dax discard to the nd_region provider (e.g. virtio-pmem) */
+static int dax_pmem_discard(struct dax_region *dax_region,
+ const struct range *ranges, unsigned int nr)
+{
+ struct nd_region *nd_region = to_nd_region(dax_region->dev->parent);
+
+ return nvdimm_discard(nd_region, ranges, nr);
+}
+
static struct dev_dax *__dax_pmem_probe(struct device *dev)
{
struct range range;
@@ -20,6 +30,7 @@ static struct dev_dax *__dax_pmem_probe(struct device *dev)
struct nd_dax *nd_dax = to_nd_dax(dev);
struct nd_pfn *nd_pfn = &nd_dax->nd_pfn;
struct nd_region *nd_region = to_nd_region(dev->parent);
+ u64 discard_gran;
ndns = nvdimm_namespace_common_probe(dev);
if (IS_ERR(ndns))
@@ -56,6 +67,11 @@ static struct dev_dax *__dax_pmem_probe(struct device *dev)
IORESOURCE_DAX_STATIC);
if (!dax_region)
return ERR_PTR(-ENOMEM);
+ discard_gran = nvdimm_discard_granularity(nd_region);
+ if (discard_gran &&
+ IS_ALIGNED(range.start - nd_region->ndr_start, discard_gran))
+ dax_region_set_discard(dax_region, dax_pmem_discard,
+ discard_gran);
data = (struct dev_dax_data) {
.dax_region = dax_region,
--
2.56.1.839.g22a8290db9-goog
^ permalink raw reply [flat|nested] 6+ messages in thread* [RFC PATCH 5/5] selftests/dax: add devdax_discard tests
2026-11-30 1:23 [RFC PATCH 0/5] virtio-pmem & device-dax: host-backed range discard via fallocate() / MADV_REMOVE Sourav Panda
` (3 preceding siblings ...)
2026-11-30 1:23 ` [RFC PATCH 4/5] dax/device: add fallocate() discard support Sourav Panda
@ 2026-11-30 1:23 ` Sourav Panda
4 siblings, 0 replies; 6+ messages in thread
From: Sourav Panda @ 2026-11-30 1:23 UTC (permalink / raw)
To: djbw, vishal.l.verma, dave.jiang, alison.schofield,
pankaj.gupta.linux, mst, jasowangio, eperezma, viro, brauner
Cc: iweiny, jack, xuanzhuo, shuah, david, souravpanda, nvdimm,
linux-cxl, virtualization, linux-fsdevel, linux-kselftest,
linux-mm, linux-kernel
Add a kselftest for hole punching on device-dax. It needs a device
whose provider supports discard and skips otherwise. DAXDEV selects the
device and defaults to /dev/dax0.0.
The test checks that bad arguments are rejected (unaligned or
out-of-range offsets and lengths, and modes other than PUNCH_HOLE |
KEEP_SIZE), that mmap() refuses an offset that is not aligned to the
device, that fallocate() and madvise(MADV_REMOVE) zero exactly the
requested range and leave its neighbours alone, and that data survives
close() and munmap().
Signed-off-by: Sourav Panda <souravpanda@google.com>
---
tools/testing/selftests/dax/.gitignore | 2 +
tools/testing/selftests/dax/Makefile | 3 +-
tools/testing/selftests/dax/devdax_discard.c | 250 +++++++++++++++++++
3 files changed, 254 insertions(+), 1 deletion(-)
create mode 100644 tools/testing/selftests/dax/.gitignore
create mode 100644 tools/testing/selftests/dax/devdax_discard.c
diff --git a/tools/testing/selftests/dax/.gitignore b/tools/testing/selftests/dax/.gitignore
new file mode 100644
index 0000000000000..33e329fbff967
--- /dev/null
+++ b/tools/testing/selftests/dax/.gitignore
@@ -0,0 +1,2 @@
+# SPDX-License-Identifier: GPL-2.0-only
+devdax_discard
diff --git a/tools/testing/selftests/dax/Makefile b/tools/testing/selftests/dax/Makefile
index 25a4f3d73a5ba..e218839319319 100644
--- a/tools/testing/selftests/dax/Makefile
+++ b/tools/testing/selftests/dax/Makefile
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: GPL-2.0
-all:
+CFLAGS += -Wall -O2 $(KHDR_INCLUDES)
TEST_PROGS := dax-kmem-hotplug.sh
+TEST_GEN_PROGS := devdax_discard
include ../lib.mk
diff --git a/tools/testing/selftests/dax/devdax_discard.c b/tools/testing/selftests/dax/devdax_discard.c
new file mode 100644
index 0000000000000..4fae31b186d8d
--- /dev/null
+++ b/tools/testing/selftests/dax/devdax_discard.c
@@ -0,0 +1,250 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Selftests for device-dax fallocate() discard (drivers/dax/device.c).
+ *
+ * Requires a discard-capable device-dax instance (for example, a virtio-pmem
+ * backed device-dax instance with VIRTIO_PMEM_F_DISCARD negotiated). Select
+ * the device via DAXDEV=/dev/daxX.Y (default /dev/dax0.0); the tests skip
+ * when the device is absent or reports discard_granularity == 0.
+ *
+ * Semantics under test:
+ * fallocate(fd, PUNCH_HOLE|KEEP_SIZE, off, len) discard
+ * madvise(MADV_REMOVE) discard through a mapping
+ * close() / munmap() preserves data (PMEM)
+ */
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <linux/falloc.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <sys/sysmacros.h>
+#include <unistd.h>
+
+#include "../kselftest_harness.h"
+
+#define DEFAULT_DAXDEV "/dev/dax0.0"
+#define DISCARD (FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE)
+
+static const char *daxdev(void)
+{
+ const char *p = getenv("DAXDEV");
+
+ return p && *p ? p : DEFAULT_DAXDEV;
+}
+
+static int sysfs_read(int fd, const char *attr, char *buf, size_t len)
+{
+ struct stat st;
+ char path[256];
+ ssize_t n;
+ int sfd;
+
+ if (fstat(fd, &st) || !S_ISCHR(st.st_mode))
+ return -1;
+ snprintf(path, sizeof(path), "/sys/dev/char/%u:%u/%s",
+ major(st.st_rdev), minor(st.st_rdev), attr);
+ sfd = open(path, O_RDONLY);
+ if (sfd < 0)
+ return -1;
+ n = read(sfd, buf, len - 1);
+ close(sfd);
+ if (n < 0)
+ return -1;
+ buf[n] = '\0';
+ return 0;
+}
+
+static long long sysfs_num(int fd, const char *attr)
+{
+ char buf[64];
+
+ if (sysfs_read(fd, attr, buf, sizeof(buf)))
+ return -1;
+ return strtoll(buf, NULL, 0);
+}
+
+static int open_dev(void)
+{
+ return open(daxdev(), O_RDWR | O_CLOEXEC);
+}
+
+static int all_bytes(const unsigned char *p, size_t len, unsigned char v)
+{
+ size_t page = (size_t)sysconf(_SC_PAGESIZE);
+ size_t i;
+
+ for (i = 0; i < len; i += page)
+ if (p[i] != v || p[i + page - 1] != v)
+ return 0;
+ return 1;
+}
+
+FIXTURE(dax)
+{
+ int fd;
+ size_t size; /* device size */
+ size_t align; /* device mapping alignment */
+ size_t granularity; /* provider discard granularity */
+ size_t region; /* test window: >= align and >= 4 * granularity */
+};
+
+FIXTURE_SETUP(dax)
+{
+ long long gran, sz, al;
+
+ self->fd = open_dev();
+ if (self->fd < 0)
+ SKIP(return, "cannot open %s: %s", daxdev(), strerror(errno));
+ gran = sysfs_num(self->fd, "discard_granularity");
+ if (gran <= 0)
+ SKIP(return, "%s: discard_granularity <= 0", daxdev());
+ sz = sysfs_num(self->fd, "size");
+ al = sysfs_num(self->fd, "align");
+ ASSERT_GT(sz, 0LL);
+ ASSERT_GT(al, 0LL);
+ self->granularity = (size_t)gran;
+ self->size = (size_t)sz;
+ self->align = (size_t)al;
+ self->region = self->align > 4 * self->granularity ?
+ self->align : 4 * self->granularity;
+ if (self->region % self->align)
+ self->region = ((self->region + self->align - 1) /
+ self->align) * self->align;
+ ASSERT_LE(self->region, self->size);
+}
+
+FIXTURE_TEARDOWN(dax)
+{
+ if (self->fd >= 0) {
+ close(self->fd);
+ self->fd = -1;
+ }
+}
+
+TEST_F(dax, invalid_arguments)
+{
+ size_t g = self->granularity;
+ size_t page = (size_t)sysconf(_SC_PAGESIZE);
+
+ EXPECT_EQ(fallocate(self->fd, 0, 0, g), -1);
+ EXPECT_EQ(errno, EOPNOTSUPP);
+ if (g > page) {
+ EXPECT_EQ(fallocate(self->fd, DISCARD, page, g), -1);
+ EXPECT_EQ(errno, EINVAL);
+ EXPECT_EQ(fallocate(self->fd, DISCARD, 0, g + page), -1);
+ EXPECT_EQ(errno, EINVAL);
+ }
+ EXPECT_EQ(fallocate(self->fd, DISCARD, self->size, g), -1);
+ EXPECT_EQ(errno, EINVAL);
+ EXPECT_EQ(fallocate(self->fd, DISCARD, self->size - g, 2 * g), -1);
+ EXPECT_EQ(errno, EINVAL);
+ EXPECT_EQ(fallocate(self->fd, FALLOC_FL_ZERO_RANGE, 0, g), -1);
+ EXPECT_EQ(errno, EOPNOTSUPP);
+ EXPECT_EQ(fallocate(self->fd, FALLOC_FL_PUNCH_HOLE, 0, g), -1);
+ EXPECT_EQ(errno, EOPNOTSUPP);
+}
+
+TEST_F(dax, mmap_rejects_unaligned_offset)
+{
+ size_t page = (size_t)sysconf(_SC_PAGESIZE);
+ void *res, *hint, *p;
+
+ if (self->align <= page || self->size < self->align + self->granularity)
+ SKIP(return, "device align/size too small for unaligned offset test");
+
+ /* Obtain an align-aligned VA hint without relying on kernel placement. */
+ res = mmap(NULL, 2 * self->align, PROT_NONE,
+ MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+ ASSERT_NE(res, MAP_FAILED);
+ hint = (void *)(((uintptr_t)res + self->align - 1) &
+ ~(self->align - 1));
+ ASSERT_EQ(munmap(res, 2 * self->align), 0);
+
+ /* Page-aligned but sub-align offset must fail even with aligned VA. */
+ p = mmap(hint, self->align, PROT_READ | PROT_WRITE, MAP_SHARED,
+ self->fd, page);
+ EXPECT_EQ(p, MAP_FAILED);
+ EXPECT_EQ(errno, EINVAL);
+ if (p != MAP_FAILED)
+ munmap(p, self->align);
+
+ /*
+ * On align > granularity (e.g. 1 GiB align with 2 MiB discard),
+ * a granularity-aligned offset is still unaligned for the device's
+ * compound folio size and must fail.
+ */
+ if (self->align > self->granularity) {
+ p = mmap(hint, self->align, PROT_READ | PROT_WRITE, MAP_SHARED,
+ self->fd, self->granularity);
+ EXPECT_EQ(p, MAP_FAILED);
+ EXPECT_EQ(errno, EINVAL);
+ if (p != MAP_FAILED)
+ munmap(p, self->align);
+ }
+}
+
+TEST_F(dax, discard_reads_zero)
+{
+ size_t g = self->granularity;
+ unsigned char *p;
+
+ p = mmap(NULL, self->region, PROT_READ | PROT_WRITE, MAP_SHARED,
+ self->fd, 0);
+ ASSERT_NE(p, MAP_FAILED);
+
+ memset(p, 0xa5, 3 * g);
+ ASSERT_TRUE(all_bytes(p, 3 * g, 0xa5));
+
+ /* explicit discard of the first granularity unit */
+ ASSERT_EQ(fallocate(self->fd, DISCARD, 0, g), 0);
+ EXPECT_TRUE(all_bytes(p, g, 0));
+ EXPECT_TRUE(all_bytes(p + g, 2 * g, 0xa5));
+
+ /* madvise(MADV_REMOVE) of the second unit goes through the same path */
+ ASSERT_EQ(madvise(p + g, g, MADV_REMOVE), 0);
+ EXPECT_TRUE(all_bytes(p + g, g, 0));
+ EXPECT_TRUE(all_bytes(p + 2 * g, g, 0xa5));
+
+ /* the discarded range is still usable afterwards */
+ memset(p, 0x3c, g);
+ EXPECT_TRUE(all_bytes(p, g, 0x3c));
+
+ EXPECT_EQ(munmap(p, self->region), 0);
+}
+
+TEST_F(dax, close_preserves_data)
+{
+ size_t g = self->granularity;
+ unsigned char *p;
+ int fd2;
+
+ p = mmap(NULL, self->region, PROT_READ | PROT_WRITE, MAP_SHARED,
+ self->fd, 0);
+ ASSERT_NE(p, MAP_FAILED);
+ memset(p + 2 * g, 0xee, g);
+
+ ASSERT_EQ(munmap(p, self->region), 0);
+ ASSERT_EQ(close(self->fd), 0);
+ self->fd = -1;
+
+ /* Reopening must observe previously written data until discarded. */
+ fd2 = open_dev();
+ ASSERT_GE(fd2, 0);
+ p = mmap(NULL, self->region, PROT_READ | PROT_WRITE, MAP_SHARED, fd2,
+ 0);
+ ASSERT_NE(p, MAP_FAILED);
+ EXPECT_TRUE(all_bytes(p + 2 * g, g, 0xee));
+
+ /* Clean up with an explicit discard. */
+ EXPECT_EQ(fallocate(fd2, DISCARD, 2 * g, g), 0);
+ EXPECT_TRUE(all_bytes(p + 2 * g, g, 0));
+ EXPECT_EQ(munmap(p, self->region), 0);
+ EXPECT_EQ(close(fd2), 0);
+}
+
+TEST_HARNESS_MAIN
--
2.56.1.839.g22a8290db9-goog
^ permalink raw reply [flat|nested] 6+ messages in thread