On Mon, Nov 23, 2026 at 6:45 PM Qiliang Yuan <qiliang.yuan(a)linux.dev> wrote:
>
> udmabuf maps the ranges of a buffer that are backed by huge pages with
> PMDs, provided the mapping covers whole PMDs at an aligned address.
>
> The existing tests of huge page backed buffers only map a few pages, so
> they never get a PMD mapping or check what is read through one.
>
> Map a 64 MiB udmabuf backed by 2 MiB huge pages and read back what was
> written to the memfd, with a different pattern in each huge page: through
> a mapping of the whole buffer, which must be PMD aligned for a 64-bit
> task when THP support is built in, through a mapping at an unaligned
> offset, and from a forked child that inherits the mapping of the whole
> buffer.
>
> Signed-off-by: Qiliang Yuan <qiliang.yuan(a)linux.dev>
> ---
> tools/testing/selftests/drivers/dma-buf/udmabuf.c | 97 ++++++++++++++++++++++-
> 1 file changed, 96 insertions(+), 1 deletion(-)
>
> diff --git a/tools/testing/selftests/drivers/dma-buf/udmabuf.c b/tools/testing/selftests/drivers/dma-buf/udmabuf.c
> index d78aec662586b..6eaef1b3aee01 100644
> --- a/tools/testing/selftests/drivers/dma-buf/udmabuf.c
> +++ b/tools/testing/selftests/drivers/dma-buf/udmabuf.c
> @@ -14,6 +14,7 @@
> #include <sys/ioctl.h>
> #include <sys/syscall.h>
> #include <sys/mman.h>
> +#include <sys/wait.h>
> #include <linux/memfd.h>
> #include <linux/udmabuf.h>
> #include "kselftest.h"
> @@ -130,6 +131,98 @@ static int compare_chunks(void *addr1, void *addr2, off64_t memfd_size)
> return ret;
> }
>
> +#define HPAGE_SIZE (2UL << 20)
This isn't true on 16k or 64k PAGE_SIZE arm64. Can we read
hpage_pmd_size for the PMD alignment and Hugepagesize: from
/proc/meminfo for the MFD_HUGETLB backing size?
> +#define HUGE_BUF_SIZE (32 * HPAGE_SIZE)
I think we only really need 8 of these for the sub-range test, and
this gets huge for 16k or 64k base pages.
> +/* Check that @len bytes mapped at @addr match @mem at @off */
> +static bool check_huge_mapping(char *addr, char *mem, off_t off, size_t len)
> +{
> + size_t i;
> +
> + for (i = 0; i < len; i += getpagesize()) {
> + if (addr[i] != mem[off + i])
> + return false;
> + }
> + return true;
> +}
> +
> +/* Check that @len bytes of @buf at @off read back what was written to @mem */
> +static bool check_huge_range(int buf, char *mem, off_t off, size_t len)
> +{
> + char *addr;
> + bool ok;
> +
> + addr = mmap(NULL, len, PROT_READ, MAP_SHARED, buf, off);
> + if (addr == MAP_FAILED)
> + return false;
> +
> + ok = check_huge_mapping(addr, mem, off, len);
> + munmap(addr, len);
> + return ok;
> +}
> +
> +/*
> + * Map a udmabuf backed by 2MB huge pages, which can be mapped with PMDs, and
> + * read it back from a PMD-aligned address, a sub-range at an unaligned offset
> + * and a forked child that inherits the mapping.
> + */
> +static void test_huge_mapping(int devfd)
> +{
> + struct udmabuf_create create = {};
> + int memfd, buf, status;
> + bool thp, aligned, ok;
> + char *mem, *addr;
> + pid_t pid;
> + size_t i;
> +
> + memfd = create_memfd_with_seals(HUGE_BUF_SIZE, true);
> + mem = mmap_fd(memfd, HUGE_BUF_SIZE);
> + /* Give each huge page its own pattern */
> + for (i = 0; i < HUGE_BUF_SIZE; i += getpagesize())
> + mem[i] = (char)(i / getpagesize() + i / HPAGE_SIZE);
> +
> + create.memfd = memfd;
> + create.size = HUGE_BUF_SIZE;
> + buf = ioctl(devfd, UDMABUF_CREATE, &create);
> + if (buf < 0) {
> + ksft_test_result_fail("%s: [FAIL,test-8]\n", TEST_PREFIX);
> + ksft_test_result_skip("%s: [SKIP,test-9]\n", TEST_PREFIX);
> + goto out;
> + }
> +
> + /* The address is only aligned for 64-bit tasks with THP support */
> + thp = sizeof(long) == 8 &&
> + !access("/sys/kernel/mm/transparent_hugepage", F_OK);
> + addr = mmap(NULL, HUGE_BUF_SIZE, PROT_READ, MAP_SHARED, buf, 0);
> + aligned = addr != MAP_FAILED &&
> + (!thp || !((unsigned long)addr % HPAGE_SIZE));
> + ok = aligned && check_huge_mapping(addr, mem, 0, HUGE_BUF_SIZE);
> + if (ok)
> + ksft_test_result_pass("%s: [PASS,test-8]\n", TEST_PREFIX);
> + else
> + ksft_test_result_fail("%s: [FAIL,test-8]\n", TEST_PREFIX);
> +
> + ok = check_huge_range(buf, mem, HPAGE_SIZE + getpagesize(),
> + 5 * HPAGE_SIZE + 3 * getpagesize());
We should probably also have a test with create.offset = getpagesize()
to exercise the misaligned PFN fallback.
Also a test that faults a PMD, then disables THP and then faults
elsewhere to cover the v1 bug.
On Mon, Nov 23, 2026 at 6:45 PM Qiliang Yuan <qiliang.yuan(a)linux.dev> wrote:
>
> QEMU and crosvm hand guest memory to the host renderer and display as
> udmabufs for virtio-gpu blob resources. The guest memory is a memfd that
> is often backed by 2 MiB huge pages, and the host process mmap()s the
> dma-buf to access it with the CPU.
>
> udmabuf maps every page with its own PTE: the first fault inserts a PFN
> for each 4 KiB page of the whole VMA. Mapping and touching 4 GiB this way
> takes over 200 ms and a million PTEs, although the memory behind it is
> 2048 huge pages.
>
> Add a ->huge_fault() handler that maps a PMD-sized range with one PMD
> when it is backed by an aligned run of contiguous PFNs, and falls back to
> PTEs otherwise. Have the pre-mapping on the first fault skip the ranges
> the handler will map, so that their PTEs don't take the place of the
> PMDs. Once THP is disabled for the VMA, the ranges already mapped with a
> PMD keep it, so pre-map only the PMD-sized range of the fault then.
>
> Mapping a udmabuf over a memfd filled with data and reading a byte of
> each 4 KiB page through the mapping, base and patched kernels alternating
> over 3 rounds of 5 runs (7 for shmem 4K), median of the per-round medians
> and range in parentheses:
>
> backing size before (ms) after (ms) change
> hugetlb 256M 13.3 (13.3-13.7) 1.7 (1.7-1.8) -87%
> hugetlb 1G 53.6 (53.0-53.7) 6.5 (4.2-6.6) -88%
> hugetlb 4G 211 (211-212) 23.6 (17.6-25.2) -89%
> hugetlb 8G 423 (422-424) 45.8 (45.8-47.2) -89%
> shmem THP 1G 52.8 (52.5-53.1) 6.3 (5.8-6.8) -88%
> shmem THP 4G 210 (207-214) 20.7 (19.5-21.1) -90%
> shmem 4K 1G 52.0 (51.6-52.7) 51.8 (51.5-52.9) 0%
> shmem 4K 4G 209 (209-211) 208 (208-209) 0%
>
> Signed-off-by: Qiliang Yuan <qiliang.yuan(a)linux.dev>
This commit message should explicitly say this patch depends on
Lorenzo's series in addition to mentioning it in the cover letter (for
merging / backporting). The mm/core hashes may change, so just by the
series title or patch subjects for now.
> ---
> drivers/dma-buf/udmabuf.c | 85 ++++++++++++++++++++++++++++++++++++++++++++---
> 1 file changed, 81 insertions(+), 4 deletions(-)
>
> diff --git a/drivers/dma-buf/udmabuf.c b/drivers/dma-buf/udmabuf.c
> index 018937435356e..9f53d33fbdd9a 100644
> --- a/drivers/dma-buf/udmabuf.c
> +++ b/drivers/dma-buf/udmabuf.c
> @@ -44,12 +44,63 @@ struct udmabuf {
> struct miscdevice *device;
> };
>
> +/*
> + * Return whether the PMD-sized range of @vma at @addr is backed by one aligned
> + * run of contiguous PFNs, which can then be mapped with a single PMD.
> + */
> +static bool udmabuf_pmd_mappable(struct vm_area_struct *vma, unsigned long addr,
> + unsigned long *pfn)
> +{
> + struct udmabuf *ubuf = vma->vm_private_data;
> + const pgoff_t nr = PMD_SIZE >> PAGE_SHIFT;
> + unsigned long first;
> + pgoff_t pgoff, i;
> +
> + if (!IS_ENABLED(CONFIG_ARCH_SUPPORTS_PMD_PFNMAP))
> + return false;
> +
> + if (!IS_ALIGNED(addr, PMD_SIZE) || addr < vma->vm_start ||
> + vma->vm_end - addr < PMD_SIZE)
> + return false;
> +
> + pgoff = vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT);
> + if (pgoff >= ubuf->pagecount || ubuf->pagecount - pgoff < nr)
> + return false;
> +
> + first = page_to_pfn(ubuf->pages[pgoff]);
> + if (!IS_ALIGNED(first, nr))
> + return false;
> +
> + for (i = 1; i < nr; i++) {
> + if (page_to_pfn(ubuf->pages[pgoff + i]) != first + i)
> + return false;
> + }
> +
> + *pfn = first;
> + return true;
> +}
> +
> +#ifdef CONFIG_ARCH_SUPPORTS_HUGE_PFNMAP
> +static vm_fault_t udmabuf_vm_huge_fault(struct vm_fault *vmf,
> + unsigned int order)
> +{
> + unsigned long pfn;
> +
> + if (order != PMD_ORDER ||
> + !udmabuf_pmd_mappable(vmf->vma, vmf->address & PMD_MASK, &pfn))
> + return VM_FAULT_FALLBACK;
> +
> + return vmf_insert_pfn_pmd(vmf, pfn, vmf->flags & FAULT_FLAG_WRITE);
> +}
> +#endif
> +
> static vm_fault_t udmabuf_vm_fault(struct vm_fault *vmf)
> {
> struct vm_area_struct *vma = vmf->vma;
> struct udmabuf *ubuf = vma->vm_private_data;
> pgoff_t pgoff = vmf->pgoff;
> - unsigned long addr, pfn;
> + unsigned long addr, end, pfn;
> + bool pmd_ok;
> vm_fault_t ret;
>
> if (pgoff >= ubuf->pagecount)
> @@ -61,14 +112,37 @@ static vm_fault_t udmabuf_vm_fault(struct vm_fault *vmf)
> if (ret & VM_FAULT_ERROR)
> return ret;
>
> - /* pre fault */
> - pgoff = vma->vm_pgoff;
> + /*
> + * Pre-fault the rest of the VMA, except for the ranges that
> + * udmabuf_vm_huge_fault() maps with a PMD once they are accessed.
> + */
> + pmd_ok = thp_vma_allowable_order(vma, vma->vm_flags, TVA_PAGEFAULT,
> + PMD_ORDER);
> addr = vma->vm_start;
> + end = vma->vm_end;
>
> - for (; addr < vma->vm_end; pgoff++, addr += PAGE_SIZE) {
> + /*
> + * Ranges mapped with a PMD before THP was disabled for the VMA keep
> + * their PMD, so pre-fault only the PMD-sized range of the fault.
> + */
> + if (IS_ENABLED(CONFIG_ARCH_SUPPORTS_PMD_PFNMAP) && !pmd_ok) {
> + addr = max(addr, vmf->address & PMD_MASK);
> + end = min(end, (vmf->address & PMD_MASK) + PMD_SIZE);
> + }
This fixes the v1 problem, but it means that a task with THP disabled
takes a fault per PMD size instead of the whole VMA. Including buffers
that are entirely backed by 4k pages. That partially undoes the
f0bbcc258e81 ("udmabuf: pre-fault when first page fault") behavior.
That's probably fine (would be good to see results for shmem 4K under
PR_SET_THP_DISABLE), but I think the commit message should mention
this also applies to 4k buffers.
Also probably worth mentioning / commenting that
/sys/kernel/mm/transparent_hugepage/enabled = never (we use that)
doesn't get you here because the THP tuneables are bypassed for
VM_PFNMAP VMAs with huge_fault().
If we stick with this behavior when THP is disabled, can we just do it
unconditionally (using pmd_addr_end(vmf->address, vma->vm_end))? That
would eliminate pmd_ok, the thp_vma_allowable_order() call, the skip
branch below, and keep udmabuf_vm_fault() within the faulting PMD's
page table and avoid repeated full-VMA scans (e.g. post
MADV_DONTNEED), which seems like it might be worth the extra faults.
Worth checking the shmem 4k numbers to see if the extra per-PMD faults
are negligible though.
> + pgoff = vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT);
> +
> + for (; addr < end; pgoff++, addr += PAGE_SIZE) {
> if (addr == vmf->address)
> continue;
>
> + if (pmd_ok && IS_ALIGNED(addr, PMD_SIZE) &&
> + (vmf->address & PMD_MASK) != addr &&
> + udmabuf_pmd_mappable(vma, addr, &pfn)) {
> + pgoff += (PMD_SIZE >> PAGE_SHIFT) - 1;
> + addr += PMD_SIZE - PAGE_SIZE;
> + continue;
> + }
> +
> if (WARN_ON(pgoff >= ubuf->pagecount))
> break;
>
> @@ -89,6 +163,9 @@ static vm_fault_t udmabuf_vm_fault(struct vm_fault *vmf)
>
> static const struct vm_operations_struct udmabuf_vm_ops = {
> .fault = udmabuf_vm_fault,
> +#ifdef CONFIG_ARCH_SUPPORTS_HUGE_PFNMAP
> + .huge_fault = udmabuf_vm_huge_fault,
> +#endif
> };
>
> static int mmap_udmabuf(struct dma_buf *buf, struct vm_area_struct *vma)
>
> --
> 2.43.0
>
On Mon, Nov 23, 2026 at 6:45 PM Qiliang Yuan <qiliang.yuan(a)linux.dev> wrote:
>
> A dma-buf exporter whose buffer is backed by physically contiguous memory
> can map it with PMDs from a ->huge_fault() handler, which only works where
> the user address and the buffer offset are aligned alike to PMD_SIZE.
>
> dma_buf_fops has no ->get_unmapped_area(), so mmap() places a dma-buf at
> whatever page aligned address the default allocator returns. A 4 GiB
> udmabuf, for one, lands 616 KiB past a 2 MiB boundary, and then none of
> its PMD-sized ranges can be mapped with a PMD.
>
> Use thp_get_unmapped_area(), as filesystems that support huge mappings
> do. It aligns a mapping that covers at least one whole PMD to the buffer
> offset and leaves smaller mappings where they would be placed anyway.
>
> Signed-off-by: Qiliang Yuan <qiliang.yuan(a)linux.dev>
> Reviewed-by: Christian König <christian.koenig(a)amd.com>
Reviewed-by: T.J. Mercier <tjmercier(a)google.com>
On 11/24/26 07:23, Alistair Popple wrote:
> On 2026-11-24 at 05:37 +1100, Christian König <christian.koenig(a)amd.com> wrote...
>> On 11/23/26 17:57, Jason Gunthorpe wrote:
>>> On Mon, Nov 23, 2026 at 02:36:46PM +0100, Christian König wrote:
>>>> On 11/20/26 06:55, Alistair Popple wrote:
>>>>> From: Jason Gunthorpe <jgg(a)nvidia.com>
>>>>>
>>>>> The SGT (Scatter Gather Table) DMA mapping type represents the existing
>>>>> sg_table/scatterlist based DMA mapping. For now it continues to use a
>>>>> sg_table for map/unmap, but this will allow a future patch series to
>>>>> convert to using a different data structure for importers without having
>>>>> to convert all at once.
>>>>
>>>> I strongly think we shouldn't have an SGT mapping type in the new DMA-buf mapping API.
>>>>
>>>> Instead we should have something like either an array or an xarray
>>>> of DMA addresses.
>>>
>>> My plan was always to get there, but I don't think it is reasonable to
>>> start there? There are too many places all over the place that are
>>> just hardwired to do SGT right now.
>
> Right. There are around 70 drivers upstream that make use of the sg_table handed
> down via a dma-buf import, so I don't think it's tractable to convert them all
> in one go. So obviously we will need some way of phasing this in to give time
> for each driver change to be implemented, reviewed, etc.
My suggestion is not to convert all drivers in one go, but rather to come up with some sane representation of the DMA addresses instead of using an SGT in the new interface.
> Obviously some of those will share a common structure/helper and conversions
> will be similar, so that is an over-estimate. But based on an initial poke
> around there are plenty of drivers that bake the sg_table more deeply into their
> data structures.
>
>>> Part of the design of this series was to allow the conversion away
>>> from SGT to be done incrementally without breaking compatibility.
>>
>> Do you know the joke from the hitchhikers guide to the galaxy where the dolphins are happy for exactly the same reasons?
>>
>> I'm pushing against this plan for exactly the same reason because I think it will make the conversation away from SGT even more problematic than it already is.
>>
>>> So it is effectively this:
>>>
>>>> The framework should then either connect the SGT directly if both
>>>> importer and export are using the "classic" interface
>>
>> Yeah but that should not be a separate mapping type, it's rather that we just convert back and forth from DMA addresses to SGT for compatibility reasons.
>
> Right, I think this is actually fairly close to my plan, which is to provide a type
> for each address class an exporter can produce - either a CPU physical address
> or some device context + P2P/MMIO address but in future could be some other
> interconnect type.
>
> The core then negotiates compatible types and adds converters between them,
I have strong objections to that plan and would potentially NAK it.
DMA-buf should *NEVER* accept CPU physical addresses nor provide conversion between different address types.
Keep in mind that DMA-buf is solely a container for DMA addresses, nothing else and it should not provide any mapping functionality whatsoever.
> and having SGT as a type is what allows that. It only exists for unconverted
> exporters and importers and eventually goes away once everything is converted.
> The idea being we don't have to convert everything all at once, whilst also being
> able to add support for different interconnect types. Are you ok with the SGT
> type if it is just transitional?
Not really, it just complicate things.
What we should do with the mapping interface is to add the information in which domain the DMA addresses are to be used.
The conversion between SGT and DMA address array is an exception we can make to aid transition between the old and the new interface, but that is basically a 1 to 1 copy between different data structures.
> As discussed a bit previously types also add enforcement of the rules around when
> the exporter type/location can change.
>
> I do have most of this coded up, so can post a mega series of all patches if
> it's helpful to see the overall direction in code form. I didn't do that because
> this conversion of exporters to not return sg_tables makes it quite a large
> patch series, so I was going to post them as separate RFCs building on top of
> this. Not sure if you have a preference there?
I think we should have the core interface plus some test cases and at least one driver converted over as example of how the new interface would be used.
>>> And this:
>>>
>>>> or convert
>>>> from DMA-addr array to SGT and back if either of them are using this
>>>> new interface.
>>>look like
>>> Is something I imagined as a followup series.
>>>
>>> As this is actually quite complicated and needs discussion exactly
>>> what it will look like.
>>
>> Actually that is the easy step I think because quite a lot of drivers already convert the SGT to a DMA addr array outside of the DMA-buf framework anyway.
>>
>> The more complicated one is then starting to come up with more bus types and doing optimization work.
>
> Individually the actual data structure conversion isn't that hard, but there's
> a lot of them and the mapping types allow you to do them incrementally without
> breaking some unconverted importer importing from a converted exporter.
Breaking classic users is actually completely intentional because we most likely still have people abusing the struct page inside the SGT.
And those will need to be converted over to be using pure DMA addresses similar to how MSM has switched over recently.
So the whole idea is when you have classic to classic interface pass along the SGT between exporter and importer. Then move as much as possible drivers over to the new interface and start identifying where and why some drivers have problems.
Regards,
Christian.
>
> That is also why I think adding the types now rather than later is reasonable.
> The rules for when an exporter may change type or placement are what most of the
> previous review discussion has been about, and I didn't want to drop them.
>
> Thanks for looking.
>
> - Alistair
>
>> Christian.
>>
>>>
>>> Jason
>>
Hi Mark,
The current drm-misc tree has a semantic conflict with the broadcom
tree that breaks the build:
drivers/platform/raspberrypi/vc-sm-cma/vc_sm.c:217:3: error: call to undeclared function 'dma_buf_unmap_attachment_unlocked'
drivers/platform/raspberrypi/vc-sm-cma/vc_sm.c:438:8: error: call to undeclared function 'dma_buf_map_attachment_unlocked'
77e0b2d2f4f3 ("treewide: Rename dma_buf_(un)map_attachment() to
dma_buf_(un)map_sgt()") in the drm-misc tree renames the functions, and
6e0a8f1a8347 ("platform/raspberrypi: Add VideoCore shared memory
support") in the broadcom tree adds a new user of the old names. It is
the only caller in next-20261123 that the rename doesn't cover.
The fix for the merge:
diff --git a/drivers/platform/raspberrypi/vc-sm-cma/vc_sm.c b/drivers/platform/raspberrypi/vc-sm-cma/vc_sm.c
--- a/drivers/platform/raspberrypi/vc-sm-cma/vc_sm.c
+++ b/drivers/platform/raspberrypi/vc-sm-cma/vc_sm.c
@@ -214,9 +214,8 @@ static void vc_sm_clean_up_dmabuf(struct vc_sm_buffer *buffer)
{
/* Handle cleaning up imported dmabufs */
if (buffer->sgt) {
- dma_buf_unmap_attachment_unlocked(buffer->attach,
- buffer->sgt,
- DMA_BIDIRECTIONAL);
+ dma_buf_unmap_sgt_unlocked(buffer->attach, buffer->sgt,
+ DMA_BIDIRECTIONAL);
buffer->sgt = NULL;
}
if (buffer->attach) {
@@ -435,7 +434,7 @@ vc_sm_cma_import_dmabuf_internal(struct dma_buf *dma_buf,
goto error;
}
- sgt = dma_buf_map_attachment_unlocked(attach, DMA_BIDIRECTIONAL);
+ sgt = dma_buf_map_sgt_unlocked(attach, DMA_BIDIRECTIONAL);
if (IS_ERR(sgt)) {
ret = PTR_ERR(sgt);
goto error;
@@ -550,8 +549,7 @@ vc_sm_cma_import_dmabuf_internal(struct dma_buf *dma_buf,
free_kernel_id(import.kernel_id);
kfree(buffer);
if (sgt)
- dma_buf_unmap_attachment_unlocked(attach, sgt,
- DMA_BIDIRECTIONAL);
+ dma_buf_unmap_sgt_unlocked(attach, sgt, DMA_BIDIRECTIONAL);
if (attach)
dma_buf_detach(dma_buf, attach);
dma_buf_put(dma_buf);
--
Thanks,
Sasha
On 11/20/26 06:55, Alistair Popple wrote:
> From: Jason Gunthorpe <jgg(a)nvidia.com>
>
> The SGT (Scatter Gather Table) DMA mapping type represents the existing
> sg_table/scatterlist based DMA mapping. For now it continues to use a
> sg_table for map/unmap, but this will allow a future patch series to
> convert to using a different data structure for importers without having
> to convert all at once.
I strongly think we shouldn't have an SGT mapping type in the new DMA-buf mapping API.
Instead we should have something like either an array or an xarray of DMA addresses.
The framework should then either connect the SGT directly if both importer and export are using the "classic" interface or convert from DMA-addr array to SGT and back if either of them are using this new interface.
The next step should then probably be to switch over the DRM drivers to use this interface and exercise if everything still works fine.
That should be relatively straight forward because TTM drivers already use a DMA-addr array internally anyway (see function drm_prime_sg_to_dma_addr_array()).
I can also put somebody on that task should we agree that this is the way forward.
Regards,
Christian.
>
> dma_buf_sgt_compat_match_mapping() is used during the conversion of
> exporters to transparently wrap an unaware exporter's sg_table. It is
> removed later in this series once all exporters have been converted.
>
> A mapping is an object allocated by an exporter which embeds the generic
> struct dma_buf_mapping type header which core dma-buf code fills in. For
> the SGT type that is currently a struct dma_buf_sgt_mapping embedding a
> struct sg_table.
>
> Importers continue to receive a struct sg_table from dma_buf_map_sgt()
> and are unaffected. A future series will convert the embedded sg_table
> into a list of DMA addresses more appropriate for importers.
>
> Signed-off-by: Jason Gunthorpe <jgg(a)nvidia.com>
> Signed-off-by: Alistair Popple <apopple(a)nvidia.com>
>
> ---
>
> Changes for v3:
>
> - PCIe P2P will be added as its own type in future, so dropped the P2P
> flags from the SGT type.
> - Exporters allocate and return struct dma_buf_sgt_mapping with the
> sg_table embedded instead of a bare struct sg_table. This ensures
> an unmap happens against the correct type once multiple mapping types
> are possible.
> ---
> drivers/dma-buf/dma-buf-mapping.c | 104 +++++++++++++++++++++++++++++
> include/linux/dma-buf-mapping.h | 135 ++++++++++++++++++++++++++++++++++++++
> include/linux/dma-buf.h | 6 +-
> 3 files changed, 244 insertions(+), 1 deletion(-)
>
> diff --git a/drivers/dma-buf/dma-buf-mapping.c b/drivers/dma-buf/dma-buf-mapping.c
> index d27f02610c2a..cc3d8d6fe009 100644
> --- a/drivers/dma-buf/dma-buf-mapping.c
> +++ b/drivers/dma-buf/dma-buf-mapping.c
> @@ -6,6 +6,7 @@
> #include <linux/dma-buf-mapping.h>
> #include <linux/dma-resv.h>
> #include <linux/dma-buf.h>
> +#include <linux/seq_file.h>
> #include <linux/overflow.h>
> #include <linux/align.h>
>
> @@ -322,3 +323,106 @@ int dma_buf_match_mapping(struct dma_buf_match_args *args,
> return 0;
> }
> EXPORT_SYMBOL_NS_GPL(dma_buf_match_mapping, "DMA_BUF");
> +
> +static void
> +dma_buf_sgt_finish_match(struct dma_buf_match_args *args,
> + const struct dma_buf_mapping_match *exp,
> + const struct dma_buf_mapping_match *imp,
> + struct dma_buf_mapping_match *match)
> +{
> + struct dma_buf_attachment *attach = args->attach;
> +
> + *match = (struct dma_buf_mapping_match) {
> + .type = &dma_buf_mapping_sgt_type,
> + .exp_ops = exp->exp_ops,
> + .sgt_data = {
> + .importing_dma_device = args->dev,
> + },
> + };
> +
> + /*
> + * Setup the SGT type variables stored in attach because importers and
> + * exporters that do not natively use mappings expect them to be there.
> + * When converting to use mappings users should use the match versions
> + * of these instead.
> + */
> + attach->dev = args->dev;
> +}
> +
> +static void dma_buf_sgt_debugfs_dump(struct seq_file *s,
> + struct dma_buf_attachment *attach)
> +{
> + seq_printf(s, " %s", dev_name(dma_buf_sgt_dma_device(attach)));
> +}
> +
> +const struct dma_buf_mapping_type dma_buf_mapping_sgt_type = {
> + .name = "DMA Mapped Scatter Gather Table",
> + .finish_match = dma_buf_sgt_finish_match,
> + .debugfs_dump = dma_buf_sgt_debugfs_dump,
> +};
> +EXPORT_SYMBOL_NS_GPL(dma_buf_mapping_sgt_type, "DMA_BUF");
> +
> +/* An unaware exporter's sg_table presented as an SGT mapping */
> +struct dma_buf_sgt_compat_mapping {
> + struct dma_buf_sgt_mapping mapping;
> + struct sg_table *sgt;
> +};
> +
> +static struct dma_buf_sgt_mapping *
> +dma_buf_sgt_compat_map_dma_buf(struct dma_buf_attachment *attach,
> + enum dma_data_direction dir)
> +{
> + struct dma_buf_sgt_compat_mapping *compat;
> + struct sg_table *sgt;
> +
> + sgt = attach->dmabuf->ops->map_dma_buf(attach, dir);
> + if (!sgt)
> + return ERR_PTR(-ENOMEM);
> + if (IS_ERR(sgt))
> + return ERR_CAST(sgt);
> +
> + compat = kzalloc_obj(*compat);
> + if (!compat) {
> + attach->dmabuf->ops->unmap_dma_buf(attach, sgt, dir);
> + return ERR_PTR(-ENOMEM);
> + }
> +
> + /* The exporter keeps its table; the mapping shares its entries */
> + compat->sgt = sgt;
> + compat->mapping.sgt = *sgt;
> + return &compat->mapping;
> +}
> +
> +static void dma_buf_sgt_compat_unmap_dma_buf(struct dma_buf_attachment *attach,
> + struct dma_buf_sgt_mapping *mapping,
> + enum dma_data_direction dir)
> +{
> + struct dma_buf_sgt_compat_mapping *compat =
> + container_of(mapping, struct dma_buf_sgt_compat_mapping, mapping);
> +
> + attach->dmabuf->ops->unmap_dma_buf(attach, compat->sgt, dir);
> + kfree(compat);
> +}
> +
> +/* Route the classic map/unmap ops through the exp ops for old importers */
> +static const struct dma_buf_mapping_sgt_exp_ops dma_buf_sgt_compat_exp_ops = {
> + .map_dma_buf = dma_buf_sgt_compat_map_dma_buf,
> + .unmap_dma_buf = dma_buf_sgt_compat_unmap_dma_buf,
> +};
> +
> +/*
> + * This entry is used for unaware exporters that do not support
> + * match_mapping(). It wraps the dma_buf ops for SGT mappings into a mapping
> + * type so aware importers can transparently work with unaware exporters. This
> + * does not require p2p because old exporters will check it through the
> + * attach->peer2peer mechanism.
> + */
> +static const struct dma_buf_mapping_match dma_buf_sgt_exp_compat_matches[] = {
> + DMA_BUF_EMAPPING_SGT(&dma_buf_sgt_compat_exp_ops),
> +};
> +
> +int dma_buf_sgt_compat_match_mapping(struct dma_buf_match_args *args)
> +{
> + return dma_buf_match_mapping(args, dma_buf_sgt_exp_compat_matches,
> + ARRAY_SIZE(dma_buf_sgt_exp_compat_matches));
> +}
> diff --git a/include/linux/dma-buf-mapping.h b/include/linux/dma-buf-mapping.h
> index bb826bdc2911..8be03b4ba6cc 100644
> --- a/include/linux/dma-buf-mapping.h
> +++ b/include/linux/dma-buf-mapping.h
> @@ -84,6 +84,30 @@ struct dma_buf_mapping_type {
> struct dma_buf_attachment *attach);
> };
>
> +/**
> + * struct dma_buf_mapping - header of a mapping made through an attachment
> + * @match: The match set entry the mapping was made with
> + *
> + * A mapping is an object allocated by whoever produces it, the exporter for
> + * the SGT type, embedding this header. The core fills the header in once the
> + * producer's map callback has returned and reads it to tear the mapping down.
> + */
> +struct dma_buf_mapping {
> + const struct dma_buf_mapping_match *match;
> +};
> +
> +/**
> + * dma_buf_mapping_type_of - The type a mapping was made with
> + * @mapping: the mapping
> + *
> + * Returns: the type of the match set entry recorded in @mapping.
> + */
> +static inline const struct dma_buf_mapping_type *
> +dma_buf_mapping_type_of(const struct dma_buf_mapping *mapping)
> +{
> + return mapping->match->type;
> +}
> +
> struct sg_table *dma_buf_phys_vec_to_sgt(struct dma_buf_attachment *attach,
> struct p2pdma_provider *provider,
> struct phys_vec *phys_vec,
> @@ -109,4 +133,115 @@ dma_buf_attach_map_type(const struct dma_buf_attachment *attach)
> return &attach->matches[0];
> }
>
> +/*
> + * DMA Mapped Scatterlist Type
> + *
> + * When this type is matched the map/unmap functions are:
> + *
> + * dma_buf_map_sgt()
> + * dma_buf_unmap_sgt()
> + *
> + * The struct sg_table returned by those functions has only the DMA portions
> + * available. The caller must not try to use the struct page * information.
> + *
> + * importing_dma_device is the device passed to dma_buf_dynamic_attach(),
> + * recorded at match time, and is passed to the DMA API to provide the
> + * dma_addr_t's.
> + */
> +extern const struct dma_buf_mapping_type dma_buf_mapping_sgt_type;
> +
> +/**
> + * struct dma_buf_sgt_mapping - A mapping of the SGT type
> + * @base: Common header, filled in by the core
> + * @sgt: The DMA mapped scatterlist, filled in by the exporter
> + *
> + * Allocated by the exporter's &dma_buf_mapping_sgt_exp_ops.map_dma_buf, which
> + * may embed it in a larger structure of its own, and released by its
> + * unmap_dma_buf. The core only fills in @base, with the same values for every
> + * map of an attachment, so an exporter that keeps one table per attachment
> + * may keep one of these per attachment and return it on every map. A mapping
> + * must not be shared between attachments. Importers are handed @sgt by
> + * dma_buf_map_sgt().
> + */
> +struct dma_buf_sgt_mapping {
> + struct dma_buf_mapping base;
> + struct sg_table sgt;
> +};
> +
> +/**
> + * struct dma_buf_mapping_sgt_exp_ops - Exporter ops of the SGT type
> + * @ops: Type tag
> + * @map_dma_buf: Produce a &struct dma_buf_sgt_mapping for @attach, with
> + * &dma_buf_sgt_mapping.sgt mapped for the device returned by
> + * dma_buf_sgt_dma_device(). Called with the dma_resv lock held.
> + * Returns the mapping, or an ERR_PTR; NULL is taken as -ENOMEM.
> + * @unmap_dma_buf: Unmap and release a mapping returned by @map_dma_buf.
> + */
> +struct dma_buf_mapping_sgt_exp_ops {
> + struct dma_buf_mapping_exp_ops ops;
> + struct dma_buf_sgt_mapping *(*map_dma_buf)(struct dma_buf_attachment *attach,
> + enum dma_data_direction dir);
> + void (*unmap_dma_buf)(struct dma_buf_attachment *attach,
> + struct dma_buf_sgt_mapping *mapping,
> + enum dma_data_direction dir);
> +};
> +
> +/**
> + * dma_buf_sgt_dma_device - Return the device to use for DMA mapping
> + * @attach: sgt mapping type attachment
> + *
> + * Called by the exporter to get the struct device to pass to the DMA API
> + * during the map callback. The unmap callback takes it from the mapping with
> + * dma_buf_sgt_mapping_dma_device().
> + *
> + * Returns: the importing device, or NULL if the attachment is not mapped with
> + * the SGT type.
> + */
> +static inline struct device *
> +dma_buf_sgt_dma_device(struct dma_buf_attachment *attach)
> +{
> + if (dma_buf_attach_map_type(attach)->type != &dma_buf_mapping_sgt_type)
> + return NULL;
> + return dma_buf_attach_map_type(attach)->sgt_data.importing_dma_device;
> +}
> +
> +static inline const struct dma_buf_mapping_sgt_exp_ops *
> +dma_buf_get_sgt_ops(struct dma_buf_attachment *attach)
> +{
> + if (dma_buf_attach_map_type(attach)->type != &dma_buf_mapping_sgt_type)
> + return NULL;
> + return container_of(dma_buf_attach_map_type(attach)->exp_ops,
> + struct dma_buf_mapping_sgt_exp_ops, ops);
> +}
> +
> +/**
> + * dma_buf_sgt_mapping_dma_device - Return the device a mapping was made for
> + * @mapping: the mapping passed to the exporter's unmap callback
> + *
> + * Called by the exporter to get the struct device to pass to the DMA API
> + * during the unmap callback. It comes from the match set entry recorded in
> + * the mapping, so it is the device the mapping was DMA mapped for whatever
> + * the attachment is mapped with by the time of the unmap.
> + *
> + * Returns: the device the mapping was DMA mapped for.
> + */
> +static inline struct device *
> +dma_buf_sgt_mapping_dma_device(const struct dma_buf_sgt_mapping *mapping)
> +{
> + return mapping->base.match->sgt_data.importing_dma_device;
> +}
> +
> +/*
> + * Importer SGT entry. Usable in a static table: the importing device is
> + * supplied by dma_buf_dynamic_attach() and recorded in the matched entry.
> + */
> +#define DMA_BUF_IMAPPING_SGT() \
> + ((struct dma_buf_mapping_match){ .type = &dma_buf_mapping_sgt_type })
> +#define DMA_BUF_EMAPPING_SGT(_exp_ops) \
> + ((struct dma_buf_mapping_match){ .type = &dma_buf_mapping_sgt_type, \
> + .exp_ops = &((_exp_ops)->ops) })
> +
> +/* Match on behalf of an exporter that has no match_mapping() */
> +int dma_buf_sgt_compat_match_mapping(struct dma_buf_match_args *args);
> +
> #endif
> diff --git a/include/linux/dma-buf.h b/include/linux/dma-buf.h
> index 81bbcd420d60..6b423e22174a 100644
> --- a/include/linux/dma-buf.h
> +++ b/include/linux/dma-buf.h
> @@ -46,7 +46,11 @@ struct dma_buf_mapping_match {
> const struct dma_buf_mapping_type *type;
> const struct dma_buf_mapping_exp_ops *exp_ops;
> union {
> - /* Each mapping_type has unique match parameters here */
> + /* For dma_buf_mapping_sgt_type */
> + struct {
> + /* Filled from the attaching device, not by importers */
> + struct device *importing_dma_device;
> + } sgt_data;
> };
> };
>
>
This series tightens the alignment requirements for buffers that are shared
between confidential-computing guests and the host, and adds a common
allocator for host-shared memory.
When a guest runs with private memory, buffers shared with the hypervisor
are not only accessed by the guest. They are also accessed by the host
kernel, and the host may manage the corresponding shared/private state at a
granularity larger than the guest page size.
Architectures such as Arm can detect incorrect accesses to Realm physical
address space PFNs through GPC faults. However, relying on that as the only
line of defence is fragile and can still lead to kernel crashes. The risk
is especially visible for shared buffers that are later mmapped into
userspace, such as guest_memfd or dma-buf backed allocations. Once
userspace can access the mapping, the kernel cannot guarantee that
applications will only touch the intended 4K region rather than the whole
host page mapped into their address space. Those userspace addresses may
also be passed back into the kernel and accessed through the linear map,
resulting in a GPC fault.
To avoid this, host-shared buffers must satisfy two constraints:
- the address must be aligned to the CoCo shared-granule size
- the size must be a multiple of that granule size
The series adds a common CoCo shared-memory layer for enforcing these
constraints. It provides shared-granule geometry and range-validation
helpers, byte-oriented private/shared transition helpers, and
alloc_cc_shared_pages(). The allocator rounds a request to the architecture
shared granule, allocates suitably aligned contiguous pages, transitions
the complete allocation to shared state, and returns the transitioned size
alongside the page.
The corresponding free helper restores the complete allocation to private
state before returning it to the buddy allocator. If private state cannot
be restored safely, the allocation is deliberately leaked rather than
returning potentially shared memory for unrelated use.
The series also makes zeroing part of private-to-shared transitions, with
each architecture clearing memory at the appropriate point. Callers must
therefore initialize shared buffers after the transition; existing contents
are not preserved.
The shared-granule size defaults to PAGE_SIZE and can be overridden by an
architecture. The arm64 CCA changes to discover the host's IPA state change
alignment are not included in this series.
GIC ITS command queues and tables and the dma-buf system_cc_shared heap
use the common allocator. DMA direct, atomic DMA pools and SWIOTLB retain
their allocation paths and use the common layout or transition helpers.
Restricted DMA pools are checked for shared-granule alignment.
Hyper-V users of set_memory_encrypted() and set_memory_decrypted() are not
changed to use cc_make_shared() by this series. Those paths are not
currently used by the arm64 CCA code path, and therefore are not part of
the arm64 CCA IPA state change alignment problem addressed here.
Notes:
* Codex assisted with implementation, review and series organization.
Changes from v9:
https://lore.kernel.org/all/20261104164555.3555725-1-aneesh.kumar@kernel.org
* Leak allocations after failed sharing in the common allocator and SWIOTLB.
* Move x86 zeroing from the AMD, TDX and Hyper-V vTOM callbacks to
set_memory_decrypted(), after a successful transition
* Add set_memory_decrypted_nozero() for VGA mappings, which must change
memory attributes without clearing device memory.
* Zero memory even when encryption is inactive in the generic, arm64 and
pSeries implementations of set_memory_decrypted().
* Move pSeries zeroing after sharing. Document why pKVM and s390 must clear
private contents before sharing
* Drop the GIC ITS VPE L1 preallocation patch from this series.
This issue predates the series and will be addressed separately.
* Add mm/cc_shared.c and include/linux/cc_shared.h to the TSM MAINTAINERS
entry.
Changes from v8:
https://lore.kernel.org/all/20260924100529.1398790-1-aneesh.kumar@kernel.org
* Rebase onto the 7.4-rc1
* Move TDX and AMD (including SEV-SNP) zeroing to their finish callbacks
so private-to-shared transitions clear the final shared mapping.
* Clear __GFP_MOVABLE for shared allocations, which cannot be migrated.
* Resolve NUMA_NO_NODE in the common ITS allocation helper to preserve
placement for all ITS callers.
* Stop SWIOTLB allocation retries when the reduced pool would fall below
the shared granule size, avoiding an allocation retry loop.
Changes from v7:
https://lore.kernel.org/all/20260921144847.501151-1-aneesh.kumar@kernel.org
* Add the following new patches:
* "irqchip/gic-v3-its: Preallocate VPE L1 tables"
* "mm: Assert CoCo shared allocations may sleep"
* "mm: Zero memory during shared memory transitions"
* Drop the arm64 RHI and shared granule size patches so that the series can
be rebased on top of upstream to enable Shashiko review.
Changes from v6:
https://lore.kernel.org/all/20260904103452.1197239-1-aneesh.kumar@kernel.org
* Add a common allocator and geometry/transition helpers for CoCo host-shared
memory.
* Convert GIC ITS, dma-direct, atomic DMA pools, and the dma-buf
system_cc_shared heap to the common allocator.
* Limit dma-buf scatterlist entries to the requested buffer size so rounded
backing is not exposed to importers.
Changes from v5:
https://lore.kernel.org/all/20260706060432.1375570-1-aneesh.kumar@kernel.org
* Rebased to latest kernel
* Drop patch arm64: realm: Move Realm memory encryption ops to RSI code
Changes from v4:
https://lore.kernel.org/all/20260427063108.909019-1-aneesh.kumar@kernel.org
* Rename the helpers to use CoCo terminology
(mem_cc_shared_granule_size() / mem_cc_align_to_shared_granule() instead of
mem_decrypt_granule_size() / mem_decrypt_align()).
* Use __DMA_ATTR_ALLOC_CC_SHARED to pass CoCo shared allocation requirements
down to CMA-based allocation helpers.
* Add validation for restricted DMA pools to reject pools that are not aligned
to the shared granule size.
* Add dma-buf system heap handling for cc-shared buffers.
* Split the previous combined DMA/SWIOTLB/ITS change into smaller subsystem
patches covering ITS, DMA direct, SWIOTLB, restricted DMA pools, dma-buf
system heap, and arm64 Realm support.
* Rework arm64 Realm support by moving Realm memory encryption ops into RSI
code and exposing the CCA shared granule size through arm64_mem_crypt_ops.
Changes from v3:
https://lore.kernel.org/all/20260309102625.2315725-1-aneesh.kumar@kernel.org
* Fix build error reported by kernel test robot <lkp(a)intel.com>
Changes from v2:
https://lore.kernel.org/all/20251221160920.297689-1-aneesh.kumar@kernel.org
* Rebase to latest kernel
* Consider swiotlb always decrypted and don't align when allocating from swiotlb.
Changes from v1:
* Rename the helper to mem_encrypt_align
* Improve the commit message
* Handle DMA allocations from contiguous memory
* Handle DMA allocations from the pool
* swiotlb is still considered unencrypted. Support for an encrypted swiotlb pool
is left as TODO and is independent of this series.
Cc: Andrew Morton <akpm(a)linux-foundation.org>
Cc: Baoquan He <baoquan.he(a)linux.dev>
Cc: Mike Rapoport <rppt(a)kernel.org>
Cc: Pasha Tatashin <pasha.tatashin(a)soleen.com>
Cc: Pratyush Yadav <pratyush(a)kernel.org>
Cc: Catalin Marinas <catalin.marinas(a)arm.com>
Cc: "Christian König" <christian.koenig(a)amd.com>
Cc: Jason Gunthorpe <jgg(a)ziepe.ca>
Cc: Joerg Roedel (AMD) <joro(a)8bytes.org>
Cc: Marc Zyngier <maz(a)kernel.org>
Cc: Marek Szyprowski <m.szyprowski(a)samsung.com>
Cc: Robin Murphy <robin.murphy(a)arm.com>
Cc: Steven Price <steven.price(a)arm.com>
Cc: Sumit Semwal <sumit.semwal(a)linaro.org>
Cc: Suzuki K Poulose <suzuki.poulose(a)arm.com>
Cc: Thomas Gleixner <tglx(a)kernel.org>
Cc: Will Deacon <will(a)kernel.org>
Cc: Russell King <linux(a)armlinux.org.uk>
Cc: Benjamin Gaignard <benjamin.gaignard(a)collabora.com>
Cc: Brian Starkey <Brian.Starkey(a)arm.com>
Cc: John Stultz <jstultz(a)google.com>
Cc: Mark Rutland <mark.rutland(a)arm.com>
Cc: Radu Rendec <radu(a)rendec.net>
Cc: "T.J. Mercier" <tjmercier(a)google.com>
Cc: Madhavan Srinivasan <maddy(a)linux.ibm.com>
Cc: Michael Ellerman <mpe(a)ellerman.id.au>
Cc: Nicholas Piggin <npiggin(a)gmail.com>
Cc: Christophe Leroy (CS GROUP) <chleroy(a)kernel.org>
Cc: Ritesh Harjani (IBM) <ritesh.list(a)gmail.com>
Cc: Shrikanth Hegde <sshegde(a)linux.ibm.com>
Cc: Alexander Gordeev <agordeev(a)linux.ibm.com>
Cc: Gerald Schaefer <gerald.schaefer(a)linux.ibm.com>
Cc: Heiko Carstens <hca(a)linux.ibm.com>
Cc: Vasily Gorbik <gor(a)linux.ibm.com>
Cc: Christian Borntraeger <borntraeger(a)linux.ibm.com>
Cc: Sven Schnelle <svens(a)linux.ibm.com>
Cc: Ingo Molnar <mingo(a)redhat.com>
Cc: Borislav Petkov <bp(a)alien8.de>
Cc: Dave Hansen <dave.hansen(a)linux.intel.com>
Cc: x86(a)kernel.org
Cc: H. Peter Anvin <hpa(a)zytor.com>
Cc: Kiryl Shutsemau <kas(a)kernel.org>
Cc: Rick Edgecombe <rick.p.edgecombe(a)intel.com>
Cc: K. Y. Srinivasan <kys(a)microsoft.com>
Cc: Haiyang Zhang <haiyangz(a)microsoft.com>
Cc: Wei Liu <wei.liu(a)kernel.org>
Cc: Dexuan Cui <decui(a)microsoft.com>
Cc: Long Li <longli(a)microsoft.com>
Cc: Paolo Bonzini <pbonzini(a)redhat.com>
Cc: Vitaly Kuznetsov <vkuznets(a)redhat.com>
Cc: Andy Lutomirski <luto(a)kernel.org>
Cc: Peter Zijlstra <peterz(a)infradead.org>
Cc: dri-devel(a)lists.freedesktop.org
Cc: iommu(a)lists.linux.dev
Cc: linaro-mm-sig(a)lists.linaro.org
Cc: linux-arm-kernel(a)lists.infradead.org
Cc: linux-media(a)vger.kernel.org
Cc: linux-mm(a)kvack.org
Cc: kvmarm(a)lists.linux.dev
Cc: patches(a)lists.linux.dev
Aneesh Kumar K.V (Arm) (13):
mm: Add an allocator for CoCo shared memory
mm: Zero memory during shared memory transitions
irqchip/gic-v3-its: Resolve the default NUMA node explicitly
irqchip/gic-v3-its: Allocate shared tables using CoCo shared memory
allocator
dma-contiguous: Derive shared alignment from DMA attributes
dma-pool: Allocate CoCo atomic pools using CoCo shared memory
allocator
dma-direct: Align CoCo shared DMA allocations to the shared granule
size
swiotlb: Align shared IO TLB pools to the shared granule size
swiotlb: Reject misaligned restricted DMA pools for CoCo guests
dma-buf: system_heap: Limit scatterlist entries to the buffer size
dma-buf: system_heap: Allocate shared buffers using CoCo shared memory
allocator
swiotlb: Make rounded shared pool capacity allocatable
mm: Assert CoCo shared allocations may sleep
MAINTAINERS | 2 +
arch/arm/mm/dma-mapping.c | 5 +-
arch/arm64/mm/mem_encrypt.c | 8 +-
arch/powerpc/platforms/pseries/svm.c | 13 +-
arch/s390/mm/init.c | 7 +
arch/x86/hyperv/hv_init.c | 6 +-
arch/x86/include/asm/set_memory.h | 1 +
arch/x86/include/asm/vga.h | 4 +-
arch/x86/kernel/kvmclock.c | 6 +-
arch/x86/mm/mem_encrypt_amd.c | 1 +
arch/x86/mm/pat/set_memory.c | 19 +-
drivers/dma-buf/heaps/system_heap.c | 128 +++++-----
drivers/firmware/arm_rmm/rsi.c | 9 +
drivers/hv/connection.c | 41 ++-
drivers/hv/hv.c | 11 +-
drivers/hv/hv_common.c | 2 -
drivers/iommu/dma-iommu.c | 2 +-
drivers/irqchip/irq-gic-v3-its.c | 42 ++--
drivers/virt/coco/pkvm-guest/arm-pkvm-guest.c | 4 +
include/linux/cc_shared.h | 39 +++
include/linux/dma-map-ops.h | 9 +-
include/linux/set_memory.h | 8 +-
kernel/dma/contiguous.c | 41 ++-
kernel/dma/direct.c | 73 ++++--
kernel/dma/ops_helpers.c | 2 +-
kernel/dma/pool.c | 27 +-
kernel/dma/swiotlb.c | 94 ++++---
kernel/kexec_file.c | 3 +-
mm/Makefile | 1 +
mm/cc_shared.c | 238 ++++++++++++++++++
30 files changed, 635 insertions(+), 211 deletions(-)
create mode 100644 include/linux/cc_shared.h
create mode 100644 mm/cc_shared.c
base-commit: aebb7274476403040d582c61478df8f4a7bf9cd3
prerequisite-patch-id: 121492d71cc22b2adbfdedd668868c5a449ad764
prerequisite-patch-id: ed31fd728f0adba3d60dcd6f3bae8da1a2193bcc
--
2.43.0
Shared-memory allocator services (e.g., Android's gralloc)
allocate dma-bufs on behalf of client processes in different
cgroups. Today those allocations are charged to the allocator's
own cgroup, leaving client cgroups with no visibility into their
actual memory consumption and defeating resource limits.
This series adds memory cgroup accounting for dma-buf allocations,
building on T.J. Mercier's earlier series [1] and incorporating
feedback from previous versions and LPC discussions [2].
Patch 1 introduces the MEMCG_DMABUF stat and the
obj_cgroup_reserve_dmabuf()/obj_cgroup_cancel_dmabuf() and
mem_cgroup_commit_dmabuf()/mem_cgroup_uncharge_dmabuf() helpers
in mm/memcontrol.c
Patch 2 wires up the charging policy: dma_buf_export() stores
exp_info.objcg and updates the stat, a new charge_fd field in
DMA_HEAP_IOCTL_ALLOC accepts a pidfd or cgroupfd to identify
the target cgroup, and __GFP_ACCOUNT is removed from system-heap
allocations to avoid double counting.
Patch 3 adds DMA_BUF_IOCTL_XFER_CHARGE, a general ioctl on any
dma-buf fd to transfer charges post-allocation. This covers the
double-hop allocator case (SurfaceFlinger -> gralloc -> kernel)
and works for buffers from any exporter that opts in. Charging
is gated by dmabuf->objcg being set at export time, ensuring that
transfer is only applied for buffers backed by system memory where
size reflects actual bytes. If the receiving cgroup lacks capacity
for the charge, the ioctl returns -ENOMEM and the original charge
is preserved.
Patches 4-6 add access control for cross-cgroup charging. Letting
userspace decide who to charge needs to be a privileged operation
because it has material impact on OOM decisions and resource limits.
Charging outside the caller's own memcg subtree requires
CAP_SYS_RESOURCE. On top of that, LSM hooks gate the two charge_fd
flavours: security_current_memcg_charge_task() for the pidfd path
and security_current_memcg_charge_cgroup() for the cgroupfd path.
Both flavours ultimately charge a cgroup, so the SELinux
implementation gates the two with a single cgroup:charge_to
permission. The target type keeps the distinction.
The checks run at target resolution, before the CAP_SYS_RESOURCE
baseline, and cover the caller's own subtree, so policy needs
a rule even for self-charging. The SELinux controls are covered
by new selinux-testsuite tests [4].
Patch 7 adds selftests. The tests and vmtest script were mostly
written by an LLM, closely following the style of the surrounding
tests and the virtme-ng setup. All code has been reviewed and tested.
Known limitations:
- Single-owner model: a dma-buf carries one memcg charge regardless
of how many processes share it. The owner is deterministic, set
at allocation time and moved only by an explicit XFER_CHARGE.
- Only memcg accounting. CMA heaps would additionally need dmem
controller integration.
- If a transfer fails (e.g., the receiving cgroup is at its limit),
the buffer remains charged to the original cgroup. The allocator
(userspace) is expected to handle failures (retry, free, ...).
- The LSM hooks are intentionally narrow. Broader cgroup access
controls (e.g., for the memfd/kexec handover case [2]) could be
a separate effort reusing the same pattern.
- Only system heap sets exp_info.objcg today. Other exporters
(DRM, V4L2, etc.) can opt in by setting it, but are not
covered by this series.
- Related to the above: lazy backing-store allocation is not supported.
This can be extended later, e.g., by adding a flag on the dma-buf
struct for explicitly marking when memory is committed.
Note on TTM/GPU accounting [3]: that effort charges system memory
allocated for GPU buffers per page, with its own stats (gpu_active
and gpu_reclaim). This series charges at the dma-buf level, for
memory with no memory.stat category of its own; exporters whose
memory is already charged by their allocator must not opt in, so
the two do not overlap.
[1] https://lore.kernel.org/cgroups/20230109213809.418135-1-tjmercier@google.co…
[2] https://lpc.events/event/20/contributions/2416/
[3] https://lore.kernel.org/all/20260706052330.1110909-1-airlied@gmail.com/
[4] https://github.com/SELinuxProject/selinux-testsuite/pull/111
Signed-off-by: Albert Esteve <aesteve(a)redhat.com>
---
Changes in v6:
- Unify SELinux perms into cgroup:charge_to
- Drop the current cred argument from the LSM hooks
and rename signatures to security_current_memcg_charge_*
- Add selinux-testsuite coverage for the charge_to controls
- Rebased to v7.4-rc4
- Link to v5: https://patch.msgid.link/20261117-v2_20230123_tjmercier_google_com-v5-0-1ce…
Changes in v5:
- Reject dma-buf reservations above INT_MAX pages to avoid
nr_pages truncation (Sashiko)
- Require CAP_SYS_RESOURCE for charge requests targeting outside
caller's own memcg subtree (Sashiko)
- Hold an obj_cgroup instead of a memcg in the dma-buf struct (Thomas Hellström)
- Restore mem_cgroup_commit_dmabuf() so dma_buf_export() does not
reach into memcg stat internals
- Resolve the cgroup and run the LSM check against the same file
in get_obj_cgroup_from_fd()
- The cgroupfd hook now takes the file and checks the inode SID,
so genfscon-labeled cgroups are covered
- Rename the LSM hooks to security_memcg_charge_{task,cgroup}()
- Replace dma_buf object class in SELinux with process2:charge_to
and cgroup:charge_to
- Link to v4: https://lore.kernel.org/r/20261104-v2_20230123_tjmercier_google_com-v4-0-18…
Changes in v4:
- Remove memcg_account flag; exp_info.memcg != NULL is the opt-in
- Centralize memcg bookkeeping in dma_buf_export()
- Drop mem_cgroup_commit_dmabuf()
- Make mem_cgroup_transfer_charge() generic (not dma-buf specific)
- Add EXPORT_SYMBOL_GPL for reserve/cancel (system_heap is tristate)
- Reorder: move xfer ioctl before LSM patches
- Serialize dmabuf->memcg updates with the dma-buf resv lock instead of cmpxchg
- Link to v3: https://lore.kernel.org/r/20261027-v2_20230123_tjmercier_google_com-v3-0-78…
Changes in v3:
- Split mem_cgroup_charge_dmabuf() into reserve/commit/cancel three-phase API
- Extract mem_cgroup_get_from_fd() helper shared by allocate and xfer paths
- Rename __padding to flags in struct dma_buf_transfer_charge
- Fix UAF race: move mod_memcg_state() before cmpxchg in transfer
- Add memcg_account opt-in flag; xfer returns -EOPNOTSUPP if unset
- Wrap dma_buf_charge_cgroup hook in #ifdef CONFIG_CGROUPS
- Fix TOCTOU in SELinux charge_cgroup xattr length handling
- Link to v2: https://lore.kernel.org/r/20261021-v2_20230123_tjmercier_google_com-v2-0-ef…
Changes in v2:
- Move charge_pid_fd to charge_fd, accepting cgroupfd in addition
to pidfd per Christian König.
- New DMA_BUF_IOCTL_XFER_CHARGE ioctl for post-allocation charge
transfer on any dma-buf, not just dma-heap buffers per Christian König
and T.J. Mercier.
- Moved __GFP_ACCOUNT removal to patch 1 per Barry Song.
- dma-buf charge/uncharge helpers take struct dma_buf * directly
to avoid the need for caller to manage size calculations.
- Added test_xfer_charge_cgroupfd_self to dmabuf-heap selftests.
- Added LSM and SELinux hooks for cgroupfd-based charging.
- Rebased to v7.3-rc7.
- Link to v1: https://lore.kernel.org/r/20260512-v2_20230123_tjmercier_google_com-v1-0-63…
---
Albert Esteve (6):
dma-heap: charge dma-buf memory via explicit memcg
dma-buf: transfer objcg charges via DMA_BUF_IOCTL_XFER_CHARGE
lsm: Add memcg_charge_task LSM hook
lsm: Add memcg_charge_cgroup LSM hook
selinux: Restrict cross-cgroup memcg charging
selftests/dmabuf-heaps: Add dma-buf memcg accounting tests
T.J. Mercier (1):
memcg: Add MEMCG_DMABUF accounting infrastructure
Documentation/admin-guide/cgroup-v2.rst | 6 +
drivers/dma-buf/dma-buf.c | 45 +++
drivers/dma-buf/dma-heap.c | 27 +-
drivers/dma-buf/heaps/cma_heap.c | 3 +-
drivers/dma-buf/heaps/system_heap.c | 19 +-
drivers/tee/tee_heap.c | 3 +-
include/linux/dma-buf.h | 10 +
include/linux/dma-heap.h | 4 +-
include/linux/lsm_hook_defs.h | 2 +
include/linux/memcontrol.h | 56 +++
include/linux/security.h | 12 +
include/uapi/linux/dma-buf.h | 26 ++
include/uapi/linux/dma-heap.h | 7 +
mm/memcontrol.c | 271 +++++++++++++
security/security.c | 31 ++
security/selinux/hooks.c | 19 +
security/selinux/include/classmap.h | 1 +
tools/testing/selftests/cgroup/Makefile | 2 +-
tools/testing/selftests/cgroup/test_memcontrol.c | 447 ++++++++++++++++++++-
tools/testing/selftests/dmabuf-heaps/config | 1 +
tools/testing/selftests/dmabuf-heaps/dmabuf-heap.c | 237 ++++++++++-
tools/testing/selftests/dmabuf-heaps/vmtest.sh | 226 +++++++++++
22 files changed, 1440 insertions(+), 15 deletions(-)
---
base-commit: 8d7fe9885c62fc9a95bf55d9db244d9672a8aadc
change-id: 20260508-v2_20230123_tjmercier_google_com-f44fcfb16530
Best regards,
--
Albert Esteve <aesteve(a)redhat.com>
On Fri, Nov 20, 2026 at 07:59:11PM +0100, Antoni Pokusinski wrote:
> Document the TX and RX DMA request channels featured
> by the OMAP I2C controller.
>
> Signed-off-by: Antoni Pokusinski <apokusinski01(a)gmail.com>
Missing Krzysztof's ack