AI Trajectory


Trajectory: (Expand/Collapse All)
Seq Timestamp Type Name Duration
0/0 2026/11/20 23:06 flow patch-triage
3m Args:
null

Results:
{
  "EnableConfigs": [
    "CGROUPS",
    "MEMCG",
    "DMABUF_HEAPS",
    "DMABUF_HEAPS_SYSTEM"
  ],
  "FocusSymbols": [
    "dma_buf_xfer_charge",
    "dma_heap_ioctl_allocate",
    "system_heap_allocate",
    "get_obj_cgroup_from_fd",
    "obj_cgroup_transfer_charge",
    "obj_cgroup_reserve_dmabuf",
    "obj_cgroup_cancel_dmabuf",
    "mem_cgroup_commit_dmabuf",
    "mem_cgroup_uncharge_dmabuf"
  ],
  "KMSANReasoning": "The patch series implements memory cgroup (memcg) accounting for dma-buf allocations and allows transferring charges between cgroups via DMA_BUF_IOCTL_XFER_CHARGE and an extended DMA_HEAP_IOCTL_ALLOC.\n\nKMSAN vs KASAN Applicability Analysis:\n1. KMSAN is specifically designed to catch reads of uninitialized stack, heap, or page allocations and uninitialized info-leaks to userspace.\n2. The user-facing structures touched or added:\n   - `struct dma_buf_transfer_charge` is strictly an input structure (_IOW) composed of two `__u32` members (`flags` and `charge_fd`) totaling 8 bytes, with no padding holes and never copied back to userspace.\n   - `struct dma_heap_allocation_data` is updated to include `__u32 charge_fd` and `__u32 __padding`. With members `len` (8B), `fd` (4B), `fd_flags` (4B), `heap_flags` (8B), `charge_fd` (4B), and `__padding` (4B), the struct size is exactly 32 bytes with natural alignment and zero compiler padding holes. In `dma_heap_ioctl()`, any delta between kernel and userspace argument size is explicitly zeroed with `memset` before any potential `copy_to_user()`.\n3. In-kernel allocations (e.g. `dma_buf`, `system_heap_buffer`) continue to use zero-allocating APIs (`kzalloc()`, `kzalloc_obj()`).\n4. All local variables and pointers introduced in `mm/memcontrol.c` and `drivers/dma-buf/` are explicitly initialized or set by reference prior to being evaluated or dereferenced.\n5. The core risks of these changes involve reference counting (`obj_cgroup_get`/`put`, `css_tryget_online`), locking (`dma_resv_lock`), permissions (LSM hooks and `capable(CAP_SYS_RESOURCE)`), and memory accounting limits (`try_charge`), which fall under functional testing, LOCKDEP, and KASAN.\n\nBecause there are no uninitialized memory risks or info-leaks, spawning a dedicated KMSAN fuzzing session is not justified.",
  "NeedsKMSAN": false,
  "Reasoning": "The patch series implements cgroup-based memory accounting for DMA buffers and DMA heaps. It introduces a new ioctl DMA_BUF_IOCTL_XFER_CHARGE to transfer buffer memory charges between cgroups (using pidfds or cgroupfds), modifies DMA_HEAP_IOCTL_ALLOC to allow allocating dma-bufs charged directly to a specified cgroup, and adds new memcg/objcg accounting functions. These paths are directly reachable from userspace via /dev/dma_heap/system and exported dma-buf file descriptors in standard QEMU/virtualized environments. Fuzzing is warranted to test object cgroup reference counting, cross-cgroup charge transfers, and concurrent ioctl operations.",
  "WorthFuzzing": true
}

1/1 2026/11/20 23:06 action read-patch-diff
0m Args:
null

Results:
{
  "PatchDiff": "commit d5ea44c8586e67c2b98673186f76297f7f795f2b\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Fri Nov 20 23:06:42 2026 +0000\n\n    syz-cluster: applied patch under review\n\ndiff --git a/Documentation/admin-guide/cgroup-v2.rst b/Documentation/admin-guide/cgroup-v2.rst\nindex 9e3c67b02ae2e1..8d10ff7ac745ac 100644\n--- a/Documentation/admin-guide/cgroup-v2.rst\n+++ b/Documentation/admin-guide/cgroup-v2.rst\n@@ -1666,6 +1666,12 @@ The following nested keys are defined.\n \t\tAmount of memory used for storing in-kernel data\n \t\tstructures.\n \n+\t  dmabuf (npn)\n+\t\tAmount of memory used for exported DMA buffers allocated by or on\n+\t\tbehalf of the cgroup, this currently includes system heap\n+\t\tallocations. Stays with the cgroup regardless of how the buffer\n+\t\tis shared, unless moved with DMA_BUF_IOCTL_XFER_CHARGE.\n+\n \t  workingset_refault_anon\n \t\tNumber of refaults of previously evicted anonymous pages.\n \ndiff --git a/drivers/dma-buf/dma-buf.c b/drivers/dma-buf/dma-buf.c\nindex 36cdc342627ee8..5d4b55b67e995c 100644\n--- a/drivers/dma-buf/dma-buf.c\n+++ b/drivers/dma-buf/dma-buf.c\n@@ -14,6 +14,7 @@\n #include \u003clinux/fs.h\u003e\n #include \u003clinux/slab.h\u003e\n #include \u003clinux/dma-buf.h\u003e\n+#include \u003clinux/memcontrol.h\u003e\n #include \u003clinux/dma-fence.h\u003e\n #include \u003clinux/dma-fence-unwrap.h\u003e\n #include \u003clinux/anon_inodes.h\u003e\n@@ -182,6 +183,8 @@ static void dma_buf_release(struct dentry *dentry)\n \n \tdmabuf-\u003eops-\u003erelease(dmabuf);\n \n+\tmem_cgroup_uncharge_dmabuf(dmabuf);\n+\n \tif (dmabuf-\u003eresv == (struct dma_resv *)\u0026dmabuf[1])\n \t\tdma_resv_fini(dmabuf-\u003eresv);\n \n@@ -537,6 +540,42 @@ static long dma_buf_import_sync_file(struct dma_buf *dmabuf,\n }\n #endif\n \n+/* Transfer a dma-buf's memcg charge; see struct dma_buf_transfer_charge */\n+static long dma_buf_xfer_charge(struct dma_buf *dmabuf,\n+\t\t\t\tconst void __user *user_data)\n+{\n+\tstruct dma_buf_transfer_charge arg;\n+\tstruct obj_cgroup *objcg;\n+\tunsigned int nr_pages;\n+\tint ret = 0;\n+\n+\tif (copy_from_user(\u0026arg, user_data, sizeof(arg)))\n+\t\treturn -EFAULT;\n+\n+\tif (arg.flags != 0)\n+\t\treturn -EINVAL;\n+\n+\tobjcg = get_obj_cgroup_from_fd(arg.charge_fd);\n+\tif (IS_ERR(objcg))\n+\t\treturn PTR_ERR(objcg);\n+\n+\tdma_resv_lock(dmabuf-\u003eresv, NULL);\n+\n+\tif (!dmabuf-\u003eobjcg) {\n+\t\tret = -EOPNOTSUPP;\n+\t\tgoto out;\n+\t}\n+\n+\tnr_pages = PAGE_ALIGN(dmabuf-\u003esize) \u003e\u003e PAGE_SHIFT;\n+\tif (!obj_cgroup_transfer_charge(\u0026dmabuf-\u003eobjcg, objcg, MEMCG_DMABUF, nr_pages))\n+\t\tret = -ENOMEM;\n+\n+out:\n+\tdma_resv_unlock(dmabuf-\u003eresv);\n+\tobj_cgroup_put(objcg);\n+\treturn ret;\n+}\n+\n static long dma_buf_ioctl(struct file *file,\n \t\t\t  unsigned int cmd, unsigned long arg)\n {\n@@ -587,6 +626,9 @@ static long dma_buf_ioctl(struct file *file,\n \t\treturn dma_buf_import_sync_file(dmabuf, (const void __user *)arg);\n #endif\n \n+\tcase DMA_BUF_IOCTL_XFER_CHARGE:\n+\t\treturn dma_buf_xfer_charge(dmabuf, (const void __user *)arg);\n+\n \tdefault:\n \t\treturn -ENOTTY;\n \t}\n@@ -747,6 +789,7 @@ struct dma_buf *dma_buf_export(const struct dma_buf_export_info *exp_info)\n \tdmabuf-\u003esize = exp_info-\u003esize;\n \tdmabuf-\u003eexp_name = exp_info-\u003eexp_name;\n \tdmabuf-\u003eowner = exp_info-\u003eowner;\n+\tdmabuf-\u003eobjcg = exp_info-\u003eobjcg;\n \tspin_lock_init(\u0026dmabuf-\u003ename_lock);\n \tinit_waitqueue_head(\u0026dmabuf-\u003epoll);\n \tdmabuf-\u003ecb_in.poll = dmabuf-\u003ecb_out.poll = \u0026dmabuf-\u003epoll;\n@@ -768,6 +811,8 @@ struct dma_buf *dma_buf_export(const struct dma_buf_export_info *exp_info)\n \n \tDMA_BUF_TRACE(trace_dma_buf_export, dmabuf);\n \n+\tmem_cgroup_commit_dmabuf(dmabuf);\n+\n \treturn dmabuf;\n \n err_file:\ndiff --git a/drivers/dma-buf/dma-heap.c b/drivers/dma-buf/dma-heap.c\nindex 8a6c2b6e0cc608..2f53bc95a45a81 100644\n--- a/drivers/dma-buf/dma-heap.c\n+++ b/drivers/dma-buf/dma-heap.c\n@@ -10,6 +10,7 @@\n #include \u003clinux/device.h\u003e\n #include \u003clinux/dma-buf.h\u003e\n #include \u003clinux/dma-heap.h\u003e\n+#include \u003clinux/memcontrol.h\u003e\n #include \u003clinux/err.h\u003e\n #include \u003clinux/export.h\u003e\n #include \u003clinux/list.h\u003e\n@@ -78,6 +79,7 @@ static struct dma_buf *dma_heap_ioctl_allocate(struct file *file, void *data)\n \tstruct dma_heap_allocation_data *heap_allocation = data;\n \tstruct dma_heap *heap = file-\u003eprivate_data;\n \tstruct dma_buf *dmabuf;\n+\tstruct obj_cgroup *objcg = NULL;\n \tint fd;\n \tsize_t len;\n \n@@ -90,15 +92,34 @@ static struct dma_buf *dma_heap_ioctl_allocate(struct file *file, void *data)\n \tif (heap_allocation-\u003eheap_flags \u0026 ~DMA_HEAP_VALID_HEAP_FLAGS)\n \t\treturn ERR_PTR(-EINVAL);\n \n+\tif (heap_allocation-\u003e__padding != 0)\n+\t\treturn ERR_PTR(-EINVAL);\n+\n+\tif (heap_allocation-\u003echarge_fd) {\n+\t\tobjcg = get_obj_cgroup_from_fd(heap_allocation-\u003echarge_fd);\n+\t\tif (IS_ERR(objcg))\n+\t\t\treturn ERR_CAST(objcg);\n+\t}\n+\n+\tif (!objcg \u0026\u0026 mem_accounting \u0026\u0026 !mem_cgroup_disabled())\n+\t\tobjcg = get_obj_cgroup_from_current();\n+\n \tlen = PAGE_ALIGN(heap_allocation-\u003elen);\n-\tif (!len)\n+\tif (!len) {\n+\t\tobj_cgroup_put(objcg);\n \t\treturn ERR_PTR(-EINVAL);\n+\t}\n \n \tdmabuf = heap-\u003eops-\u003eallocate(heap, len, heap_allocation-\u003efd_flags,\n-\t\t\t\t     heap_allocation-\u003eheap_flags);\n+\t\t\t\t     heap_allocation-\u003eheap_flags, objcg);\n \n-\tif (IS_ERR(dmabuf))\n+\tif (IS_ERR(dmabuf)) {\n+\t\tobj_cgroup_put(objcg);\n \t\treturn dmabuf;\n+\t}\n+\n+\tif (!dmabuf-\u003eobjcg)\n+\t\tobj_cgroup_put(objcg);\n \n \tfd = get_unused_fd_flags(heap_allocation-\u003efd_flags);\n \tif (fd \u003c 0) {\ndiff --git a/drivers/dma-buf/heaps/cma_heap.c b/drivers/dma-buf/heaps/cma_heap.c\nindex 3fb4b946c91a6e..6c08dc25b17725 100644\n--- a/drivers/dma-buf/heaps/cma_heap.c\n+++ b/drivers/dma-buf/heaps/cma_heap.c\n@@ -281,7 +281,8 @@ static const struct dma_buf_ops cma_heap_buf_ops = {\n static struct dma_buf *cma_heap_allocate(struct dma_heap *heap,\n \t\t\t\t\t unsigned long len,\n \t\t\t\t\t u32 fd_flags,\n-\t\t\t\t\t u64 heap_flags)\n+\t\t\t\t\t u64 heap_flags,\n+\t\t\t\t\t struct obj_cgroup *objcg)\n {\n \tstruct cma_heap *cma_heap = dma_heap_get_drvdata(heap);\n \tstruct cma_heap_buffer *buffer;\ndiff --git a/drivers/dma-buf/heaps/system_heap.c b/drivers/dma-buf/heaps/system_heap.c\nindex c8959eadc71d18..ad94bb5be73670 100644\n--- a/drivers/dma-buf/heaps/system_heap.c\n+++ b/drivers/dma-buf/heaps/system_heap.c\n@@ -17,6 +17,7 @@\n #include \u003clinux/err.h\u003e\n #include \u003clinux/highmem.h\u003e\n #include \u003clinux/mem_encrypt.h\u003e\n+#include \u003clinux/memcontrol.h\u003e\n #include \u003clinux/mm.h\u003e\n #include \u003clinux/set_memory.h\u003e\n #include \u003clinux/module.h\u003e\n@@ -388,8 +389,6 @@ static struct page *alloc_largest_available(unsigned long size,\n \t\tif (max_order \u003c orders[i])\n \t\t\tcontinue;\n \t\tflags = order_flags[i];\n-\t\tif (mem_accounting)\n-\t\t\tflags |= __GFP_ACCOUNT;\n \t\tpage = alloc_pages(flags, orders[i]);\n \t\tif (!page)\n \t\t\tcontinue;\n@@ -401,11 +400,13 @@ static struct page *alloc_largest_available(unsigned long size,\n static struct dma_buf *system_heap_allocate(struct dma_heap *heap,\n \t\t\t\t\t    unsigned long len,\n \t\t\t\t\t    u32 fd_flags,\n-\t\t\t\t\t    u64 heap_flags)\n+\t\t\t\t\t    u64 heap_flags,\n+\t\t\t\t\t    struct obj_cgroup *objcg)\n {\n \tstruct system_heap_buffer *buffer;\n \tDEFINE_DMA_BUF_EXPORT_INFO(exp_info);\n \tunsigned long size_remaining = len;\n+\tunsigned long nr_pages = PAGE_ALIGN(len) \u003e\u003e PAGE_SHIFT;\n \tunsigned int max_order = orders[0];\n \tstruct system_heap_priv *priv = dma_heap_get_drvdata(heap);\n \tbool cc_shared = priv-\u003ecc_shared;\n@@ -416,10 +417,15 @@ static struct dma_buf *system_heap_allocate(struct dma_heap *heap,\n \tstruct page *page, *tmp_page;\n \tint i, ret = -ENOMEM;\n \n-\tbuffer = kzalloc_obj(*buffer);\n-\tif (!buffer)\n+\tif (!obj_cgroup_reserve_dmabuf(objcg, GFP_KERNEL, nr_pages))\n \t\treturn ERR_PTR(-ENOMEM);\n \n+\tbuffer = kzalloc_obj(*buffer);\n+\tif (!buffer) {\n+\t\tret = -ENOMEM;\n+\t\tgoto cancel_charge;\n+\t}\n+\n \tINIT_LIST_HEAD(\u0026buffer-\u003eattachments);\n \tmutex_init(\u0026buffer-\u003elock);\n \tbuffer-\u003eheap = heap;\n@@ -473,6 +479,7 @@ static struct dma_buf *system_heap_allocate(struct dma_heap *heap,\n \texp_info.size = buffer-\u003elen;\n \texp_info.flags = fd_flags;\n \texp_info.priv = buffer;\n+\texp_info.objcg = objcg;\n \tdmabuf = dma_buf_export(\u0026exp_info);\n \tif (IS_ERR(dmabuf)) {\n \t\tret = PTR_ERR(dmabuf);\n@@ -498,6 +505,8 @@ static struct dma_buf *system_heap_allocate(struct dma_heap *heap,\n \tlist_for_each_entry_safe(page, tmp_page, \u0026pages, lru)\n \t\t__free_pages(page, compound_order(page));\n \tkfree(buffer);\n+cancel_charge:\n+\tobj_cgroup_cancel_dmabuf(objcg, nr_pages);\n \n \treturn ERR_PTR(ret);\n }\ndiff --git a/drivers/tee/tee_heap.c b/drivers/tee/tee_heap.c\nindex 007c001565204b..83fd14a0aaec2d 100644\n--- a/drivers/tee/tee_heap.c\n+++ b/drivers/tee/tee_heap.c\n@@ -167,7 +167,8 @@ static const struct dma_buf_ops tee_heap_buf_ops = {\n \n static struct dma_buf *tee_dma_heap_alloc(struct dma_heap *heap,\n \t\t\t\t\t  unsigned long len, u32 fd_flags,\n-\t\t\t\t\t  u64 heap_flags)\n+\t\t\t\t\t  u64 heap_flags,\n+\t\t\t\t\t  struct obj_cgroup *objcg)\n {\n \tstruct tee_dma_heap *h = dma_heap_get_drvdata(heap);\n \tDEFINE_DMA_BUF_EXPORT_INFO(exp_info);\ndiff --git a/include/linux/dma-buf.h b/include/linux/dma-buf.h\nindex d15b2b31d3c91e..916d73ae6a511f 100644\n--- a/include/linux/dma-buf.h\n+++ b/include/linux/dma-buf.h\n@@ -27,6 +27,7 @@\n struct device;\n struct dma_buf;\n struct dma_buf_attachment;\n+struct obj_cgroup;\n \n /**\n  * struct dma_buf_ops - operations possible on struct dma_buf\n@@ -429,6 +430,9 @@ struct dma_buf {\n \n \t\t__poll_t active;\n \t} cb_in, cb_out;\n+\n+\t/** @objcg: object cgroup to which this buffer is currently attributed */\n+\tstruct obj_cgroup *objcg;\n };\n \n /**\n@@ -501,6 +505,11 @@ struct dma_buf_attachment {\n  * @flags:\tmode flags for the file\n  * @resv:\treservation-object, NULL to allocate default one\n  * @priv:\tAttach private data of allocator to this buffer\n+ * @objcg:\tobject cgroup to charge for this buffer's memory. Set only for\n+ *\t\tbuffers backed by system memory, not accounted elsewhere, where\n+ *\t\t@size reflects the actual allocation in bytes. The buffer takes\n+ *\t\tover the caller's reference. Enables charge transfer via\n+ *\t\tDMA_BUF_IOCTL_XFER_CHARGE.\n  *\n  * This structure holds the information required to export the buffer. Used\n  * with dma_buf_export() only.\n@@ -513,6 +522,7 @@ struct dma_buf_export_info {\n \tint flags;\n \tstruct dma_resv *resv;\n \tvoid *priv;\n+\tstruct obj_cgroup *objcg;\n };\n \n /**\ndiff --git a/include/linux/dma-heap.h b/include/linux/dma-heap.h\nindex 648328a64b27ea..b5a42b49c68d04 100644\n--- a/include/linux/dma-heap.h\n+++ b/include/linux/dma-heap.h\n@@ -12,6 +12,7 @@\n #include \u003clinux/types.h\u003e\n \n struct dma_heap;\n+struct obj_cgroup;\n \n /**\n  * struct dma_heap_ops - ops to operate on a given heap\n@@ -23,7 +24,8 @@ struct dma_heap_ops {\n \tstruct dma_buf *(*allocate)(struct dma_heap *heap,\n \t\t\t\t    unsigned long len,\n \t\t\t\t    u32 fd_flags,\n-\t\t\t\t    u64 heap_flags);\n+\t\t\t\t    u64 heap_flags,\n+\t\t\t\t    struct obj_cgroup *objcg);\n };\n \n /**\ndiff --git a/include/linux/lsm_hook_defs.h b/include/linux/lsm_hook_defs.h\nindex 87d9d06710cb26..3b254b4e60ec74 100644\n--- a/include/linux/lsm_hook_defs.h\n+++ b/include/linux/lsm_hook_defs.h\n@@ -43,6 +43,8 @@ LSM_HOOK(int, 0, capset, struct cred *new, const struct cred *old,\n \t const kernel_cap_t *permitted)\n LSM_HOOK(int, 0, capable, const struct cred *cred, struct user_namespace *ns,\n \t int cap, unsigned int opts)\n+LSM_HOOK(int, 0, memcg_charge_task, const struct cred *from, const struct cred *to)\n+LSM_HOOK(int, 0, memcg_charge_cgroup, const struct cred *cred, const struct file *file)\n LSM_HOOK(int, 0, quotactl, int cmds, int type, int id, const struct super_block *sb)\n LSM_HOOK(int, 0, quota_on, struct dentry *dentry)\n LSM_HOOK(int, 0, syslog, int type)\ndiff --git a/include/linux/memcontrol.h b/include/linux/memcontrol.h\nindex 69e1bcc67c588d..37c81be349b89d 100644\n--- a/include/linux/memcontrol.h\n+++ b/include/linux/memcontrol.h\n@@ -10,6 +10,9 @@\n \n #ifndef _LINUX_MEMCONTROL_H\n #define _LINUX_MEMCONTROL_H\n+\n+struct dma_buf;\n+\n #include \u003clinux/cgroup.h\u003e\n #include \u003clinux/vm_event_item.h\u003e\n #include \u003clinux/hardirq.h\u003e\n@@ -41,6 +44,7 @@ enum memcg_stat_item {\n \tMEMCG_ZSWAP_B,\n \tMEMCG_ZSWAPPED,\n \tMEMCG_ZSWAP_INCOMP,\n+\tMEMCG_DMABUF,\n \tMEMCG_NR_STAT,\n };\n \n@@ -688,6 +692,9 @@ int mem_cgroup_charge_hugetlb(struct folio *folio, struct mm_struct *mm,\n int mem_cgroup_swapin_charge_folio(struct folio *folio, unsigned short id,\n \t\t\t\t   struct mm_struct *mm, gfp_t gfp);\n \n+bool obj_cgroup_reserve_dmabuf(struct obj_cgroup *objcg, gfp_t gfp,\n+\t\t\t       unsigned long nr_pages);\n+\n void __mem_cgroup_uncharge(struct folio *folio);\n \n /**\n@@ -703,6 +710,11 @@ static inline void mem_cgroup_uncharge(struct folio *folio)\n \t__mem_cgroup_uncharge(folio);\n }\n \n+void obj_cgroup_cancel_dmabuf(struct obj_cgroup *objcg, unsigned long nr_pages);\n+\n+void mem_cgroup_commit_dmabuf(struct dma_buf *dmabuf);\n+void mem_cgroup_uncharge_dmabuf(struct dma_buf *dmabuf);\n+\n void __mem_cgroup_uncharge_folios(struct folio_batch *folios);\n static inline void mem_cgroup_uncharge_folios(struct folio_batch *folios)\n {\n@@ -1203,10 +1215,30 @@ static inline int mem_cgroup_swapin_charge_folio(struct folio *folio,\n \treturn 0;\n }\n \n+static inline bool obj_cgroup_reserve_dmabuf(struct obj_cgroup *objcg,\n+\t\t\t\t\t     gfp_t gfp,\n+\t\t\t\t\t     unsigned long nr_pages)\n+{\n+\treturn true;\n+}\n+\n+static inline void obj_cgroup_cancel_dmabuf(struct obj_cgroup *objcg,\n+\t\t\t\t\t    unsigned long nr_pages)\n+{\n+}\n+\n+static inline void mem_cgroup_commit_dmabuf(struct dma_buf *dmabuf)\n+{\n+}\n+\n static inline void mem_cgroup_uncharge(struct folio *folio)\n {\n }\n \n+static inline void mem_cgroup_uncharge_dmabuf(struct dma_buf *dmabuf)\n+{\n+}\n+\n static inline void mem_cgroup_uncharge_folios(struct folio_batch *folios)\n {\n }\n@@ -1780,6 +1812,7 @@ void __memcg_kmem_uncharge_page(struct page *page, int order);\n  */\n struct obj_cgroup *current_obj_cgroup(void);\n struct obj_cgroup *get_obj_cgroup_from_folio(const struct folio *folio);\n+struct obj_cgroup *get_obj_cgroup_from_fd(int fd);\n \n static inline struct obj_cgroup *get_obj_cgroup_from_current(void)\n {\n@@ -1794,6 +1827,11 @@ static inline struct obj_cgroup *get_obj_cgroup_from_current(void)\n int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size);\n void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size);\n \n+bool obj_cgroup_transfer_charge(struct obj_cgroup **ptr_objcg,\n+\t\t\t\tstruct obj_cgroup *new_objcg,\n+\t\t\t\tenum memcg_stat_item item,\n+\t\t\t\tunsigned int nr_pages);\n+\n extern struct static_key_false memcg_bpf_enabled_key;\n static inline bool memcg_bpf_enabled(void)\n {\n@@ -1887,6 +1925,24 @@ static inline struct obj_cgroup *get_obj_cgroup_from_folio(const struct folio *f\n \treturn NULL;\n }\n \n+static inline struct obj_cgroup *get_obj_cgroup_from_fd(int fd)\n+{\n+\treturn ERR_PTR(-EOPNOTSUPP);\n+}\n+\n+static inline struct obj_cgroup *get_obj_cgroup_from_current(void)\n+{\n+\treturn NULL;\n+}\n+\n+static inline bool obj_cgroup_transfer_charge(struct obj_cgroup **ptr_objcg,\n+\t\t\t\t\t      struct obj_cgroup *new_objcg,\n+\t\t\t\t\t      enum memcg_stat_item item,\n+\t\t\t\t\t      unsigned int nr_pages)\n+{\n+\treturn true;\n+}\n+\n static inline bool memcg_bpf_enabled(void)\n {\n \treturn false;\ndiff --git a/include/linux/security.h b/include/linux/security.h\nindex 40831fab54709a..d1cd6c324ffd73 100644\n--- a/include/linux/security.h\n+++ b/include/linux/security.h\n@@ -352,6 +352,9 @@ int security_capable(const struct cred *cred,\n \t\t       struct user_namespace *ns,\n \t\t       int cap,\n \t\t       unsigned int opts);\n+int security_memcg_charge_task(const struct cred *from, const struct cred *to);\n+int security_memcg_charge_cgroup(const struct cred *cred,\n+\t\t\t\t const struct file *file);\n int security_quotactl(int cmds, int type, int id, const struct super_block *sb);\n int security_quota_on(struct dentry *dentry);\n int security_syslog(int type);\n@@ -710,6 +713,18 @@ static inline int security_capable(const struct cred *cred,\n \treturn cap_capable(cred, ns, cap, opts);\n }\n \n+static inline int security_memcg_charge_task(const struct cred *from,\n+\t\t\t\t\t     const struct cred *to)\n+{\n+\treturn 0;\n+}\n+\n+static inline int security_memcg_charge_cgroup(const struct cred *cred,\n+\t\t\t\t\t       const struct file *file)\n+{\n+\treturn 0;\n+}\n+\n static inline int security_quotactl(int cmds, int type, int id,\n \t\t\t\t     const struct super_block *sb)\n {\ndiff --git a/include/uapi/linux/dma-buf.h b/include/uapi/linux/dma-buf.h\nindex e827c9d20c5d35..0aaf2e7d593b9c 100644\n--- a/include/uapi/linux/dma-buf.h\n+++ b/include/uapi/linux/dma-buf.h\n@@ -168,6 +168,31 @@ struct dma_buf_import_sync_file {\n \t__s32 fd;\n };\n \n+/**\n+ * struct dma_buf_transfer_charge - Transfer a dma-buf's memcg charge\n+ *\n+ * Any holder of a dma-buf file descriptor can perform a\n+ * DMA_BUF_IOCTL_XFER_CHARGE to attribute the buffer's memory\n+ * cost to a specific cgroup, or move it from one cgroup to\n+ * another.  The ioctl charges the new cgroup before uncharging\n+ * the old one atomically.  On failure the original charge is\n+ * preserved.  If the buffer has no existing memcg charge, the\n+ * ioctl returns -EOPNOTSUPP.\n+ */\n+struct dma_buf_transfer_charge {\n+\t/** @flags: Reserved, must be zero */\n+\t__u32 flags; /* unused for now */\n+\t/**\n+\t * @charge_fd: File descriptor identifying the target cgroup.\n+\t *\n+\t * May be either a pidfd, in which case the charge moves to the\n+\t * memory cgroup of the referenced process, or a cgroupfd obtained\n+\t * by opening a cgroup v2 directory, in which case the charge moves\n+\t * directly to that cgroup's memory controller.\n+\t */\n+\t__u32 charge_fd;\n+};\n+\n #define DMA_BUF_BASE\t\t'b'\n #define DMA_BUF_IOCTL_SYNC\t_IOW(DMA_BUF_BASE, 0, struct dma_buf_sync)\n \n@@ -179,5 +204,6 @@ struct dma_buf_import_sync_file {\n #define DMA_BUF_SET_NAME_B\t_IOW(DMA_BUF_BASE, 1, __u64)\n #define DMA_BUF_IOCTL_EXPORT_SYNC_FILE\t_IOWR(DMA_BUF_BASE, 2, struct dma_buf_export_sync_file)\n #define DMA_BUF_IOCTL_IMPORT_SYNC_FILE\t_IOW(DMA_BUF_BASE, 3, struct dma_buf_import_sync_file)\n+#define DMA_BUF_IOCTL_XFER_CHARGE\t_IOW(DMA_BUF_BASE, 4, struct dma_buf_transfer_charge)\n \n #endif\ndiff --git a/include/uapi/linux/dma-heap.h b/include/uapi/linux/dma-heap.h\nindex a4cf716a49fa68..bfcd1c25bc7ea0 100644\n--- a/include/uapi/linux/dma-heap.h\n+++ b/include/uapi/linux/dma-heap.h\n@@ -29,6 +29,11 @@\n  *\t\t\thandle to the allocated dma-buf\n  * @fd_flags:\t\tfile descriptor flags used when allocating\n  * @heap_flags:\t\tflags passed to heap\n+ * @charge_fd:\t\toptional pidfd or cgroupfd whose cgroup should be\n+ *\t\t\tcharged for this allocation; 0 means charge the calling\n+ *\t\t\tprocess's cgroup when the mem_accounting module parameter\n+ *\t\t\tis enabled, or skip charging otherwise\n+ * @__padding:\t\treserved, must be zero\n  *\n  * Provided by userspace as an argument to the ioctl\n  */\n@@ -37,6 +42,8 @@ struct dma_heap_allocation_data {\n \t__u32 fd;\n \t__u32 fd_flags;\n \t__u64 heap_flags;\n+\t__u32 charge_fd;\n+\t__u32 __padding;\n };\n \n #define DMA_HEAP_IOC_MAGIC\t\t'H'\ndiff --git a/mm/memcontrol.c b/mm/memcontrol.c\nindex a05d9a8baa1b6b..693f0b2877bf16 100644\n--- a/mm/memcontrol.c\n+++ b/mm/memcontrol.c\n@@ -49,6 +49,7 @@\n #include \u003clinux/slab.h\u003e\n #include \u003clinux/swapops.h\u003e\n #include \u003clinux/spinlock.h\u003e\n+#include \u003clinux/file.h\u003e\n #include \u003clinux/fs.h\u003e\n #include \u003clinux/seq_file.h\u003e\n #include \u003clinux/vmpressure.h\u003e\n@@ -59,6 +60,7 @@\n #include \u003clinux/lockdep.h\u003e\n #include \u003clinux/resume_user_mode.h\u003e\n #include \u003clinux/psi.h\u003e\n+#include \u003clinux/security.h\u003e\n #include \u003clinux/seq_buf.h\u003e\n #include \u003clinux/sched/isolation.h\u003e\n #include \u003clinux/kmemleak.h\u003e\n@@ -70,6 +72,7 @@\n #include \u003cnet/ip.h\u003e\n #include \"slab.h\"\n #include \"memcontrol-v1.h\"\n+#include \u003clinux/dma-buf.h\u003e\n \n #include \u003clinux/uaccess.h\u003e\n \n@@ -459,6 +462,7 @@ static const unsigned int memcg_stat_items[] = {\n \tMEMCG_ZSWAP_B,\n \tMEMCG_ZSWAPPED,\n \tMEMCG_ZSWAP_INCOMP,\n+\tMEMCG_DMABUF,\n };\n \n #define NR_MEMCG_NODE_STAT_ITEMS ARRAY_SIZE(memcg_node_stat_items)\n@@ -1644,6 +1648,7 @@ static const struct memory_stat memory_stats[] = {\n #ifdef CONFIG_HUGETLB_PAGE\n \t{ \"hugetlb\",\t\t\tNR_HUGETLB\t\t\t},\n #endif\n+\t{ \"dmabuf\",\t\t\tMEMCG_DMABUF\t\t\t},\n \n \t/* The memory events */\n \t{ \"workingset_refault_anon\",\tWORKINGSET_REFAULT_ANON\t\t},\n@@ -3165,6 +3170,163 @@ struct obj_cgroup *get_obj_cgroup_from_folio(const struct folio *folio)\n \treturn objcg;\n }\n \n+/*\n+ * Charging outside the caller's own memcg subtree can escape its limits\n+ * or push reclaim and OOM onto other cgroups.\n+ */\n+static bool mem_cgroup_may_charge(struct mem_cgroup *memcg)\n+{\n+\tstruct mem_cgroup *self = get_mem_cgroup_from_current();\n+\tbool ret = mem_cgroup_is_descendant(memcg, self);\n+\n+\tmem_cgroup_put(self);\n+\treturn ret || capable(CAP_SYS_RESOURCE);\n+}\n+\n+/**\n+ * get_obj_cgroup_from_fd - resolve an object cgroup from a cgroupfd or pidfd\n+ * @fd: file descriptor (cgroupfd or pidfd)\n+ *\n+ * Tries @fd as a cgroupfd first; if that fails, tries it as a pidfd. Only\n+ * cgroup2 directories are accepted as cgroupfds, any other fd is tried as a\n+ * pidfd.\n+ *\n+ * Resolving a memcg outside the caller's own subtree requires CAP_SYS_RESOURCE.\n+ *\n+ * On success returns a referenced objcg pointer. On failure returns\n+ * an ERR_PTR.\n+ */\n+struct obj_cgroup *get_obj_cgroup_from_fd(int fd)\n+{\n+\tstruct cgroup_subsys_state *css;\n+\tconst struct cred *tcred;\n+\tstruct obj_cgroup *objcg;\n+\tstruct mem_cgroup *memcg;\n+\tstruct task_struct *task;\n+\tunsigned int pidfd_flags;\n+\tint ret;\n+\n+\tif (mem_cgroup_disabled())\n+\t\treturn ERR_PTR(-EOPNOTSUPP);\n+\n+\tCLASS(fd_raw, f)(fd);\n+\tif (fd_empty(f))\n+\t\treturn ERR_PTR(-EBADF);\n+\n+\tcss = css_tryget_online_from_dir(fd_file(f)-\u003ef_path.dentry,\n+\t\t\t\t\t \u0026memory_cgrp_subsys);\n+\tif (!IS_ERR(css) \u0026\u0026 !cgroup_on_dfl(css-\u003ecgroup)) {\n+\t\tcss_put(css);\n+\t\tcss = ERR_PTR(-EBADF);\n+\t}\n+\n+\tif (!IS_ERR(css)) {\n+\t\t/* fd is a cgroupfd */\n+\t\tret = security_memcg_charge_cgroup(current_cred(), fd_file(f));\n+\t\tif (ret) {\n+\t\t\tcss_put(css);\n+\t\t\treturn ERR_PTR(ret);\n+\t\t}\n+\t} else {\n+\t\tif (PTR_ERR(css) != -EBADF)\n+\t\t\treturn ERR_CAST(css);\n+\n+\t\t/* fd is a pidfd */\n+\t\ttask = pidfd_get_task(fd, \u0026pidfd_flags);\n+\t\tif (IS_ERR(task))\n+\t\t\treturn ERR_CAST(task);\n+\n+\t\ttcred = get_task_cred(task);\n+\t\tret = security_memcg_charge_task(current_cred(), tcred);\n+\t\tput_cred(tcred);\n+\t\tif (ret) {\n+\t\t\tput_task_struct(task);\n+\t\t\treturn ERR_PTR(ret);\n+\t\t}\n+\n+\t\trcu_read_lock();\n+\t\tcss = task_css(task, memory_cgrp_id);\n+\t\tput_task_struct(task);\n+\t\tif (!css || !css_tryget_online(css)) {\n+\t\t\trcu_read_unlock();\n+\t\t\treturn ERR_PTR(-ENOENT);\n+\t\t}\n+\t\trcu_read_unlock();\n+\t}\n+\n+\tmemcg = mem_cgroup_from_css(css);\n+\tif (!mem_cgroup_may_charge(memcg)) {\n+\t\tmem_cgroup_put(memcg);\n+\t\treturn ERR_PTR(-EPERM);\n+\t}\n+\n+\tobjcg = get_obj_cgroup_from_memcg(memcg, numa_node_id());\n+\tmem_cgroup_put(memcg);\n+\n+\tif (!objcg)\n+\t\treturn ERR_PTR(-ENOENT);\n+\n+\treturn objcg;\n+}\n+\n+/**\n+ * obj_cgroup_transfer_charge - move a charge between object cgroups\n+ * @ptr_objcg: pointer to the object cgroup to transfer from\n+ * @new_objcg: target object cgroup; caller must hold a reference\n+ * @item: memcg stat counter to adjust; must not be a node stat\n+ * @nr_pages: number of pages to transfer\n+ *\n+ * Transfers @nr_pages of charge from *@ptr_objcg to @new_objcg and, on\n+ * success, stores @new_objcg in *@ptr_objcg. Does nothing if both resolve\n+ * to the same memcg; *@ptr_objcg is left untouched in that case.\n+ *\n+ * Updates to *@ptr_objcg must be serialized by the caller.\n+ * Returns %true on success, %false if the charge against @new_objcg\n+ * failed.\n+ */\n+bool obj_cgroup_transfer_charge(struct obj_cgroup **ptr_objcg,\n+\t\t\t\tstruct obj_cgroup *new_objcg,\n+\t\t\t\tenum memcg_stat_item item,\n+\t\t\t\tunsigned int nr_pages)\n+{\n+\tstruct obj_cgroup *old_objcg = *ptr_objcg;\n+\tstruct mem_cgroup *old_memcg = NULL, *new_memcg;\n+\tbool ret = true;\n+\n+\tif (!new_objcg || mem_cgroup_disabled())\n+\t\treturn true;\n+\n+\tnew_memcg = get_mem_cgroup_from_objcg(new_objcg);\n+\tif (old_objcg)\n+\t\told_memcg = get_mem_cgroup_from_objcg(old_objcg);\n+\n+\tif (old_memcg == new_memcg)\n+\t\tgoto out;\n+\n+\tif (try_charge(new_memcg, GFP_KERNEL, nr_pages)) {\n+\t\tret = false;\n+\t\tgoto out;\n+\t}\n+\n+\tmod_memcg_state(new_memcg, item, nr_pages);\n+\n+\tif (old_objcg) {\n+\t\t/* Uncharge old cgroup */\n+\t\tmod_memcg_state(old_memcg, item, -nr_pages);\n+\t\tif (!mem_cgroup_is_root(old_memcg))\n+\t\t\trefill_stock(old_memcg, nr_pages);\n+\t}\n+\n+\tobj_cgroup_get(new_objcg);\n+\t*ptr_objcg = new_objcg;\n+\tobj_cgroup_put(old_objcg);\n+\n+out:\n+\tmem_cgroup_put(new_memcg);\n+\tmem_cgroup_put(old_memcg);\n+\treturn ret;\n+}\n+\n #ifdef CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC\n static inline void account_kmem_nmi_safe(struct mem_cgroup *memcg, int val)\n {\n@@ -5821,6 +5983,115 @@ void mem_cgroup_flush_workqueue(void)\n \tflush_workqueue(memcg_wq);\n }\n \n+/**\n+ * obj_cgroup_reserve_dmabuf - charge an object cgroup for a dma-buf allocation\n+ * @objcg: object cgroup to charge (may be %NULL)\n+ * @gfp_mask: reclaim mode\n+ * @nr_pages: number of pages to charge\n+ *\n+ * Charges @nr_pages against @objcg. Call this before allocating pages so\n+ * the cgroup limit is enforced up front. On success the caller must\n+ * finalize the charge with the MEMCG_DMABUF stat update, or call\n+ * obj_cgroup_cancel_dmabuf() to undo it.\n+ *\n+ * @nr_pages is derived from the buffer size, which may be controlled by\n+ * userspace, so it is taken as unsigned long and rejected above what\n+ * a single memcg charge can account.\n+ *\n+ * Returns %true on success, %false if @nr_pages is too large or the\n+ * charge would exceed the limit.\n+ */\n+bool obj_cgroup_reserve_dmabuf(struct obj_cgroup *objcg, gfp_t gfp_mask,\n+\t\t\t       unsigned long nr_pages)\n+{\n+\tstruct mem_cgroup *memcg;\n+\tint ret;\n+\n+\tif (!objcg || mem_cgroup_disabled())\n+\t\treturn true;\n+\n+\t/* a single memcg charge accounts at most INT_MAX pages */\n+\tif (nr_pages \u003e INT_MAX)\n+\t\treturn false;\n+\n+\tmemcg = get_mem_cgroup_from_objcg(objcg);\n+\tret = try_charge(memcg, gfp_mask, nr_pages);\n+\tmem_cgroup_put(memcg);\n+\treturn !ret;\n+}\n+EXPORT_SYMBOL_GPL(obj_cgroup_reserve_dmabuf);\n+\n+/**\n+ * obj_cgroup_cancel_dmabuf - undo a dma-buf charge\n+ * @objcg: object cgroup to uncharge (may be %NULL)\n+ * @nr_pages: same value passed to obj_cgroup_reserve_dmabuf()\n+ *\n+ * Returns @nr_pages of charge to @objcg. Use when the allocation fails\n+ * after obj_cgroup_reserve_dmabuf().\n+ */\n+void obj_cgroup_cancel_dmabuf(struct obj_cgroup *objcg, unsigned long nr_pages)\n+{\n+\tstruct mem_cgroup *memcg;\n+\n+\tif (!objcg)\n+\t\treturn;\n+\n+\tmemcg = get_mem_cgroup_from_objcg(objcg);\n+\tif (!mem_cgroup_is_root(memcg))\n+\t\trefill_stock(memcg, nr_pages);\n+\tmem_cgroup_put(memcg);\n+}\n+EXPORT_SYMBOL_GPL(obj_cgroup_cancel_dmabuf);\n+\n+/**\n+ * mem_cgroup_commit_dmabuf - finalize a dma-buf charge\n+ * @dmabuf: buffer whose charge is being finalized\n+ *\n+ * Adds @dmabuf's size to the %MEMCG_DMABUF stat of the cgroup its object\n+ * cgroup currently resolves to. Call after obj_cgroup_reserve_dmabuf()\n+ * succeeded and the buffer is about to be exported. Safe to call when\n+ * @dmabuf-\u003eobjcg is %NULL.\n+ */\n+void mem_cgroup_commit_dmabuf(struct dma_buf *dmabuf)\n+{\n+\tstruct mem_cgroup *memcg;\n+\n+\tif (!dmabuf-\u003eobjcg)\n+\t\treturn;\n+\n+\tmemcg = get_mem_cgroup_from_objcg(dmabuf-\u003eobjcg);\n+\tmod_memcg_state(memcg, MEMCG_DMABUF,\n+\t\t\tPAGE_ALIGN(dmabuf-\u003esize) \u003e\u003e PAGE_SHIFT);\n+\tmem_cgroup_put(memcg);\n+}\n+\n+/**\n+ * mem_cgroup_uncharge_dmabuf - uncharge a dma-buf from its object cgroup\n+ * @dmabuf: buffer to uncharge\n+ *\n+ * Reverses a finalized dma-buf charge. Drops the object cgroup\n+ * reference stored in @dmabuf-\u003eobjcg and clears the pointer.\n+ * Safe to call when @dmabuf-\u003eobjcg is %NULL.\n+ */\n+void mem_cgroup_uncharge_dmabuf(struct dma_buf *dmabuf)\n+{\n+\tstruct obj_cgroup *objcg = dmabuf-\u003eobjcg;\n+\tstruct mem_cgroup *memcg;\n+\tunsigned long nr_pages;\n+\n+\tif (!objcg)\n+\t\treturn;\n+\n+\tmemcg = get_mem_cgroup_from_objcg(objcg);\n+\tnr_pages = PAGE_ALIGN(dmabuf-\u003esize) \u003e\u003e PAGE_SHIFT;\n+\tmod_memcg_state(memcg, MEMCG_DMABUF, -nr_pages);\n+\tif (!mem_cgroup_is_root(memcg))\n+\t\trefill_stock(memcg, nr_pages);\n+\tmem_cgroup_put(memcg);\n+\tobj_cgroup_put(objcg);\n+\tdmabuf-\u003eobjcg = NULL;\n+}\n+\n static int __init cgroup_memory(char *s)\n {\n \tchar *token;\ndiff --git a/security/security.c b/security/security.c\nindex f6583d50739592..925b6c00305943 100644\n--- a/security/security.c\n+++ b/security/security.c\n@@ -674,6 +674,41 @@ int security_capable(const struct cred *cred,\n \treturn call_int_hook(capable, cred, ns, cap, opts);\n }\n \n+/**\n+ * security_memcg_charge_task() - Check if cross-cgroup memory charging is allowed\n+ * @from: credentials of the process requesting the charge\n+ * @to: credentials of the process to charge\n+ *\n+ * Check whether the process with credentials @from is allowed to charge\n+ * memory to the cgroup of the process with credentials @to.\n+ *\n+ * Return: Returns 0 if permission is granted.\n+ */\n+int security_memcg_charge_task(const struct cred *from, const struct cred *to)\n+{\n+\treturn call_int_hook(memcg_charge_task, from, to);\n+}\n+\n+/**\n+ * security_memcg_charge_cgroup() - Check if charging memory to a cgroup is allowed\n+ * @cred: credentials of the process requesting the charge\n+ * @file: open file of the cgroup directory to charge\n+ *\n+ * Check whether the process with credentials @cred is allowed to charge\n+ * memory to the cgroup referenced by @file. Called when userspace passes a\n+ * cgroupfd to identify the charge target instead of a pidfd. @file is the\n+ * file the cgroup was resolved from, so the check applies to the object\n+ * that is actually charged. It must have been already validated by the\n+ * caller.\n+ *\n+ * Return: Returns 0 if permission is granted.\n+ */\n+int security_memcg_charge_cgroup(const struct cred *cred,\n+\t\t\t\t const struct file *file)\n+{\n+\treturn call_int_hook(memcg_charge_cgroup, cred, file);\n+}\n+\n /**\n  * security_quotactl() - Check if a quotactl() syscall is allowed for this fs\n  * @cmds: commands\ndiff --git a/security/selinux/hooks.c b/security/selinux/hooks.c\nindex 6168dd5f91c227..fcf0b03a588dfe 100644\n--- a/security/selinux/hooks.c\n+++ b/security/selinux/hooks.c\n@@ -2204,6 +2204,21 @@ static int selinux_capable(const struct cred *cred, struct user_namespace *ns,\n \treturn cred_has_capability(cred, cap, opts, ns == \u0026init_user_ns);\n }\n \n+static int selinux_memcg_charge_task(const struct cred *from, const struct cred *to)\n+{\n+\treturn avc_has_perm(cred_sid(from), cred_sid(to),\n+\t\t\t    SECCLASS_PROCESS2, PROCESS2__CHARGE_TO, NULL);\n+}\n+\n+static int selinux_memcg_charge_cgroup(const struct cred *cred,\n+\t\t\t\t       const struct file *file)\n+{\n+\tstruct inode_security_struct *isec = inode_security(file_inode(file));\n+\n+\treturn avc_has_perm(cred_sid(cred), isec-\u003esid, SECCLASS_CGROUP,\n+\t\t\t    CGROUP__CHARGE_TO, NULL);\n+}\n+\n static int selinux_quotactl(int cmds, int type, int id, const struct super_block *sb)\n {\n \tconst struct cred *cred = current_cred();\n@@ -7681,6 +7696,8 @@ static struct security_hook_list selinux_hooks[] __ro_after_init = {\n \tLSM_HOOK_INIT(capget, selinux_capget),\n \tLSM_HOOK_INIT(capset, selinux_capset),\n \tLSM_HOOK_INIT(capable, selinux_capable),\n+\tLSM_HOOK_INIT(memcg_charge_task, selinux_memcg_charge_task),\n+\tLSM_HOOK_INIT(memcg_charge_cgroup, selinux_memcg_charge_cgroup),\n \tLSM_HOOK_INIT(quotactl, selinux_quotactl),\n \tLSM_HOOK_INIT(quota_on, selinux_quota_on),\n \tLSM_HOOK_INIT(syslog, selinux_syslog),\ndiff --git a/security/selinux/include/classmap.h b/security/selinux/include/classmap.h\nindex 90cb61b1642563..32dd95de509a04 100644\n--- a/security/selinux/include/classmap.h\n+++ b/security/selinux/include/classmap.h\n@@ -60,7 +60,7 @@ const struct security_class_mapping secclass_map[] = {\n \t    \"siginh\",\t    \"setrlimit\",     \"rlimitinh\",   \"dyntransition\",\n \t    \"setcurrent\",   \"execmem\",\t     \"execstack\",   \"execheap\",\n \t    \"setkeycreate\", \"setsockcreate\", \"getrlimit\",   NULL } },\n-\t{ \"process2\", { \"nnp_transition\", \"nosuid_transition\", NULL } },\n+\t{ \"process2\", { \"nnp_transition\", \"nosuid_transition\", \"charge_to\", NULL } },\n \t{ \"system\",\n \t  { \"ipc_info\", \"syslog_read\", \"syslog_mod\", \"syslog_console\",\n \t    \"module_request\", \"module_load\", \"firmware_load\",\n@@ -181,6 +181,7 @@ const struct security_class_mapping secclass_map[] = {\n \t{ \"user_namespace\", { \"create\", NULL } },\n \t{ \"memfd_file\",\n \t  { COMMON_FILE_PERMS, \"execute_no_trans\", \"entrypoint\", NULL } },\n+\t{ \"cgroup\", { \"charge_to\", NULL } },\n \t/* last one */ { NULL, {} }\n };\n \ndiff --git a/tools/testing/selftests/cgroup/Makefile b/tools/testing/selftests/cgroup/Makefile\nindex e01584c2189ac1..9edfc9f1de5c43 100644\n--- a/tools/testing/selftests/cgroup/Makefile\n+++ b/tools/testing/selftests/cgroup/Makefile\n@@ -1,5 +1,5 @@\n # SPDX-License-Identifier: GPL-2.0\n-CFLAGS += -Wall -pthread\n+CFLAGS += -Wall -pthread $(KHDR_INCLUDES)\n \n all: ${HELPER_PROGS}\n \ndiff --git a/tools/testing/selftests/cgroup/test_memcontrol.c b/tools/testing/selftests/cgroup/test_memcontrol.c\nindex bb673012dcf089..f612726bd9af7e 100644\n--- a/tools/testing/selftests/cgroup/test_memcontrol.c\n+++ b/tools/testing/selftests/cgroup/test_memcontrol.c\n@@ -18,8 +18,15 @@\n #include \u003cnetdb.h\u003e\n #include \u003cerrno.h\u003e\n #include \u003csys/mman.h\u003e\n+#include \u003csys/prctl.h\u003e\n #include \u003csys/sysinfo.h\u003e\n \n+#include \u003clinux/dma-buf.h\u003e\n+#include \u003clinux/dma-heap.h\u003e\n+#include \u003csignal.h\u003e\n+#include \u003csys/ioctl.h\u003e\n+\n+#include \"../pidfd/pidfd.h\"\n #include \"kselftest.h\"\n #include \"cgroup_util.h\"\n \n@@ -27,6 +34,13 @@\n #define MEMCG_FLUSH_BYTES\t\\\n \t(2 * sysconf(_SC_PAGESIZE) * MEMCG_CHARGE_BATCH * get_nprocs())\n \n+#define DMA_HEAP_SYSTEM\t\t\"/dev/dma_heap/system\"\n+#define ONE_MEG\t\t\t(1024 * 1024)\n+\n+#define MEMCG_SOCKSTAT_WAIT_RETRIES        30\n+#define MEMCG_DMABUF_WAIT_RETRIES          30\n+#define MEMCG_DMABUF_DEAD_WAIT_RETRIES     80\n+\n static bool has_localevents;\n static bool has_recursiveprot;\n static int page_size;\n@@ -1797,6 +1811,417 @@ static int test_memcg_inotify_delete_dir(const char *root)\n \treturn ret;\n }\n \n+static int memcg_dmabuf_child(const char *cgroup, void *arg)\n+{\n+\tpid_t *parent_pid = arg;\n+\n+\tprctl(PR_SET_PDEATHSIG, SIGKILL);\n+\tif (getppid() != *parent_pid)\n+\t\treturn 0;\n+\n+\tpause();\n+\treturn 0;\n+}\n+\n+/*\n+ * This test allocates a dma-buf via DMA_HEAP_IOCTL_ALLOC with a pidfd\n+ * pointing to a child process in a separate cgroup, then checks that\n+ * memory.stat[dmabuf] in the child's cgroup rises by the allocation size\n+ * and returns to zero after the buffer fd is closed.\n+ */\n+static int test_memcg_dmabuf(const char *root)\n+{\n+\tchar *parent = NULL, *child_cg = NULL;\n+\tint ret = KSFT_FAIL;\n+\tint heap_fd = -1, dmabuf_fd = -1, pidfd = -1;\n+\tpid_t child_pid, parent_pid = getpid();\n+\tint child_status;\n+\tlong dmabuf_stat;\n+\tstruct dma_heap_allocation_data alloc = {\n+\t\t.len      = ONE_MEG,\n+\t\t.fd_flags = O_RDWR | O_CLOEXEC,\n+\t};\n+\n+\tif (access(DMA_HEAP_SYSTEM, R_OK | W_OK)) {\n+\t\tret = KSFT_SKIP;\n+\t\tgoto cleanup;\n+\t}\n+\n+\tparent = cg_name(root, \"dmabuf_memcg_test\");\n+\tif (!parent)\n+\t\tgoto cleanup;\n+\n+\tif (cg_create(parent))\n+\t\tgoto cleanup_parent;\n+\n+\tif (cg_write(parent, \"cgroup.subtree_control\", \"+memory\"))\n+\t\tgoto cleanup_parent;\n+\n+\tchild_cg = cg_name(parent, \"child\");\n+\tif (!child_cg)\n+\t\tgoto cleanup_parent;\n+\n+\tif (cg_create(child_cg))\n+\t\tgoto cleanup_parent;\n+\n+\tchild_pid = cg_run_nowait(child_cg, memcg_dmabuf_child, \u0026parent_pid);\n+\tif (child_pid \u003c 0)\n+\t\tgoto cleanup_child;\n+\n+\tif (cg_wait_for_proc_count(child_cg, 1))\n+\t\tgoto cleanup_kill;\n+\n+\tpidfd = sys_pidfd_open(child_pid, 0);\n+\tif (pidfd \u003c 0) {\n+\t\tret = KSFT_SKIP;\n+\t\tgoto cleanup_kill;\n+\t}\n+\n+\theap_fd = open(DMA_HEAP_SYSTEM, O_RDWR);\n+\tif (heap_fd \u003c 0) {\n+\t\tret = KSFT_SKIP;\n+\t\tgoto cleanup_pidfd;\n+\t}\n+\n+\talloc.charge_fd = (__u32)pidfd;\n+\tif (ioctl(heap_fd, DMA_HEAP_IOCTL_ALLOC, \u0026alloc) \u003c 0) {\n+\t\tif (errno == EINVAL || errno == ENOTTY || errno == EOPNOTSUPP)\n+\t\t\tret = KSFT_SKIP;\n+\t\tgoto cleanup_heap;\n+\t}\n+\tdmabuf_fd = (int)alloc.fd;\n+\n+\tdmabuf_stat = cg_read_key_long(child_cg, \"memory.stat\", \"dmabuf \");\n+\tif (dmabuf_stat == -1) {\n+\t\tret = KSFT_SKIP;\n+\t\tgoto cleanup_dmabuf;\n+\t}\n+\tif (dmabuf_stat != ONE_MEG)\n+\t\tdmabuf_stat = cg_read_key_long_poll(child_cg, \"memory.stat\",\n+\t\t\t\t\t\t    \"dmabuf \", ONE_MEG,\n+\t\t\t\t\t\t    MEMCG_DMABUF_WAIT_RETRIES,\n+\t\t\t\t\t\t    DEFAULT_WAIT_INTERVAL_US);\n+\tif (dmabuf_stat != ONE_MEG) {\n+\t\tfprintf(stderr, \"Expected dmabuf stat %d, got %ld\\n\",\n+\t\t\tONE_MEG, dmabuf_stat);\n+\t\tgoto cleanup_dmabuf;\n+\t}\n+\n+\tclose(dmabuf_fd);\n+\tdmabuf_fd = -1;\n+\n+\tdmabuf_stat = cg_read_key_long_poll(child_cg, \"memory.stat\",\n+\t\t\t\t\t    \"dmabuf \", 0,\n+\t\t\t\t\t    MEMCG_DMABUF_WAIT_RETRIES,\n+\t\t\t\t\t    DEFAULT_WAIT_INTERVAL_US);\n+\tif (dmabuf_stat != 0) {\n+\t\tfprintf(stderr, \"Expected dmabuf stat 0 after close, got %ld\\n\",\n+\t\t\tdmabuf_stat);\n+\t\tgoto cleanup_heap;\n+\t}\n+\n+\tret = KSFT_PASS;\n+\n+cleanup_dmabuf:\n+\tif (dmabuf_fd \u003e= 0)\n+\t\tclose(dmabuf_fd);\n+cleanup_heap:\n+\tclose(heap_fd);\n+cleanup_pidfd:\n+\tclose(pidfd);\n+cleanup_kill:\n+\tkill(child_pid, SIGTERM);\n+\twaitpid(child_pid, \u0026child_status, 0);\n+cleanup_child:\n+\tcg_destroy(child_cg);\n+\tfree(child_cg);\n+cleanup_parent:\n+\tcg_destroy(parent);\n+\tfree(parent);\n+cleanup:\n+\treturn ret;\n+}\n+\n+/*\n+ * Allocate a dma-buf in cgroup A, set memory.max on cgroup B below the\n+ * buffer size, then attempt DMA_BUF_IOCTL_XFER_CHARGE to B. The transfer\n+ * must fail with ENOMEM and the charge must remain in A.\n+ */\n+static int test_memcg_dmabuf_xfer_at_limit(const char *root)\n+{\n+\tchar *parent = NULL, *cg_a = NULL, *cg_b = NULL;\n+\tint ret = KSFT_FAIL;\n+\tint heap_fd = -1, dmabuf_fd = -1, cg_b_fd = -1;\n+\tpid_t child_pid, parent_pid = getpid();\n+\tint child_status;\n+\tlong stat_a;\n+\tstruct dma_heap_allocation_data alloc = {\n+\t\t.len      = ONE_MEG,\n+\t\t.fd_flags = O_RDWR | O_CLOEXEC,\n+\t};\n+\tstruct dma_buf_transfer_charge xfer = { 0 };\n+\n+\tif (access(DMA_HEAP_SYSTEM, R_OK | W_OK)) {\n+\t\tret = KSFT_SKIP;\n+\t\tgoto cleanup;\n+\t}\n+\n+\tparent = cg_name(root, \"dmabuf_xfer_limit_test\");\n+\tif (!parent)\n+\t\tgoto cleanup;\n+\n+\tif (cg_create(parent))\n+\t\tgoto cleanup_parent;\n+\n+\tif (cg_write(parent, \"cgroup.subtree_control\", \"+memory\"))\n+\t\tgoto cleanup_parent;\n+\n+\tcg_a = cg_name(parent, \"cg_a\");\n+\tcg_b = cg_name(parent, \"cg_b\");\n+\tif (!cg_a || !cg_b)\n+\t\tgoto cleanup_cgs;\n+\n+\tif (cg_create(cg_a) || cg_create(cg_b))\n+\t\tgoto cleanup_cgs;\n+\n+\tif (cg_write(cg_b, \"memory.max\", \"524288\"))\n+\t\tgoto cleanup_cgs;\n+\n+\tchild_pid = cg_run_nowait(cg_a, memcg_dmabuf_child, \u0026parent_pid);\n+\tif (child_pid \u003c 0)\n+\t\tgoto cleanup_cgs;\n+\n+\tif (cg_wait_for_proc_count(cg_a, 1))\n+\t\tgoto cleanup_kill;\n+\n+\theap_fd = open(DMA_HEAP_SYSTEM, O_RDWR);\n+\tif (heap_fd \u003c 0) {\n+\t\tret = KSFT_SKIP;\n+\t\tgoto cleanup_kill;\n+\t}\n+\n+\talloc.charge_fd = (__u32)sys_pidfd_open(child_pid, 0);\n+\tif ((int)alloc.charge_fd \u003c 0) {\n+\t\tret = KSFT_SKIP;\n+\t\tgoto cleanup_heap;\n+\t}\n+\n+\tif (ioctl(heap_fd, DMA_HEAP_IOCTL_ALLOC, \u0026alloc) \u003c 0) {\n+\t\tclose(alloc.charge_fd);\n+\t\tgoto cleanup_heap;\n+\t}\n+\tclose(alloc.charge_fd);\n+\tdmabuf_fd = (int)alloc.fd;\n+\n+\tstat_a = cg_read_key_long(cg_a, \"memory.stat\", \"dmabuf \");\n+\tif (stat_a == -1) {\n+\t\tret = KSFT_SKIP;\n+\t\tgoto cleanup_dmabuf;\n+\t}\n+\tif (stat_a != ONE_MEG)\n+\t\tstat_a = cg_read_key_long_poll(cg_a, \"memory.stat\",\n+\t\t\t\t\t       \"dmabuf \", ONE_MEG,\n+\t\t\t\t\t       MEMCG_DMABUF_WAIT_RETRIES,\n+\t\t\t\t\t       DEFAULT_WAIT_INTERVAL_US);\n+\tif (stat_a != ONE_MEG) {\n+\t\tfprintf(stderr, \"Charge not in A after alloc: expected %d, got %ld\\n\",\n+\t\t\tONE_MEG, stat_a);\n+\t\tgoto cleanup_dmabuf;\n+\t}\n+\n+\tcg_b_fd = open(cg_b, O_RDONLY | O_DIRECTORY);\n+\tif (cg_b_fd \u003c 0)\n+\t\tgoto cleanup_dmabuf;\n+\n+\txfer.charge_fd = (__u32)cg_b_fd;\n+\tif (ioctl(dmabuf_fd, DMA_BUF_IOCTL_XFER_CHARGE, \u0026xfer) == 0) {\n+\t\tfprintf(stderr, \"xfer_charge should have failed at limit\\n\");\n+\t\tgoto cleanup_cgfd;\n+\t}\n+\tif (errno != ENOMEM) {\n+\t\tfprintf(stderr, \"Expected ENOMEM, got %s\\n\", strerror(errno));\n+\t\tgoto cleanup_cgfd;\n+\t}\n+\n+\tstat_a = cg_read_key_long_poll(cg_a, \"memory.stat\",\n+\t\t\t\t       \"dmabuf \", ONE_MEG,\n+\t\t\t\t       MEMCG_DMABUF_WAIT_RETRIES,\n+\t\t\t\t       DEFAULT_WAIT_INTERVAL_US);\n+\tif (stat_a != ONE_MEG) {\n+\t\tfprintf(stderr, \"Charge leaked from A: expected %d, got %ld\\n\",\n+\t\t\tONE_MEG, stat_a);\n+\t\tgoto cleanup_cgfd;\n+\t}\n+\n+\tret = KSFT_PASS;\n+\n+cleanup_cgfd:\n+\tclose(cg_b_fd);\n+cleanup_dmabuf:\n+\tif (dmabuf_fd \u003e= 0)\n+\t\tclose(dmabuf_fd);\n+cleanup_heap:\n+\tclose(heap_fd);\n+cleanup_kill:\n+\tkill(child_pid, SIGTERM);\n+\twaitpid(child_pid, \u0026child_status, 0);\n+cleanup_cgs:\n+\tif (cg_a) {\n+\t\tcg_destroy(cg_a);\n+\t\tfree(cg_a);\n+\t}\n+\tif (cg_b) {\n+\t\tcg_destroy(cg_b);\n+\t\tfree(cg_b);\n+\t}\n+cleanup_parent:\n+\tcg_destroy(parent);\n+\tfree(parent);\n+cleanup:\n+\treturn ret;\n+}\n+\n+/*\n+ * Allocate a dma-buf charged to a cgroup, then remove that cgroup while\n+ * the buffer is still open. The charge is held by an object cgroup,\n+ * which is reparented, so the removed cgroup must be released instead of\n+ * lingering as a dying descendant until the buffer is closed.\n+ */\n+static int test_memcg_dmabuf_dead_cgroup(const char *root)\n+{\n+\tchar *parent = NULL, *child_cg = NULL;\n+\tint ret = KSFT_FAIL;\n+\tint heap_fd = -1, dmabuf_fd = -1, cg_fd = -1;\n+\tlong dmabuf_stat, dying;\n+\tstruct dma_heap_allocation_data alloc = {\n+\t\t.len      = ONE_MEG,\n+\t\t.fd_flags = O_RDWR | O_CLOEXEC,\n+\t};\n+\n+\tif (access(DMA_HEAP_SYSTEM, R_OK | W_OK)) {\n+\t\tret = KSFT_SKIP;\n+\t\tgoto cleanup;\n+\t}\n+\n+\tparent = cg_name(root, \"dmabuf_dead_cgroup_test\");\n+\tif (!parent)\n+\t\tgoto cleanup;\n+\n+\tif (cg_create(parent))\n+\t\tgoto cleanup_parent;\n+\n+\tif (cg_write(parent, \"cgroup.subtree_control\", \"+memory\"))\n+\t\tgoto cleanup_parent;\n+\n+\tchild_cg = cg_name(parent, \"child\");\n+\tif (!child_cg)\n+\t\tgoto cleanup_parent;\n+\n+\tif (cg_create(child_cg))\n+\t\tgoto cleanup_child;\n+\n+\theap_fd = open(DMA_HEAP_SYSTEM, O_RDWR);\n+\tif (heap_fd \u003c 0) {\n+\t\tret = KSFT_SKIP;\n+\t\tgoto cleanup_child;\n+\t}\n+\n+\tcg_fd = open(child_cg, O_RDONLY | O_DIRECTORY);\n+\tif (cg_fd \u003c 0)\n+\t\tgoto cleanup_heap;\n+\n+\talloc.charge_fd = (__u32)cg_fd;\n+\tif (ioctl(heap_fd, DMA_HEAP_IOCTL_ALLOC, \u0026alloc) \u003c 0) {\n+\t\tif (errno == EINVAL || errno == ENOTTY || errno == EOPNOTSUPP)\n+\t\t\tret = KSFT_SKIP;\n+\t\tgoto cleanup_cgfd;\n+\t}\n+\t/* The buffer holds the charge; the fd must not hold the cgroup. */\n+\tclose(cg_fd);\n+\tcg_fd = -1;\n+\tdmabuf_fd = (int)alloc.fd;\n+\n+\tdmabuf_stat = cg_read_key_long(child_cg, \"memory.stat\", \"dmabuf \");\n+\tif (dmabuf_stat == -1) {\n+\t\tret = KSFT_SKIP;\n+\t\tgoto cleanup_dmabuf;\n+\t}\n+\tif (dmabuf_stat != ONE_MEG)\n+\t\tdmabuf_stat = cg_read_key_long_poll(child_cg, \"memory.stat\",\n+\t\t\t\t\t\t    \"dmabuf \", ONE_MEG,\n+\t\t\t\t\t\t    MEMCG_DMABUF_WAIT_RETRIES,\n+\t\t\t\t\t\t    DEFAULT_WAIT_INTERVAL_US);\n+\tif (dmabuf_stat != ONE_MEG) {\n+\t\tfprintf(stderr, \"Expected dmabuf stat %d, got %ld\\n\",\n+\t\t\tONE_MEG, dmabuf_stat);\n+\t\tgoto cleanup_dmabuf;\n+\t}\n+\n+\tif (cg_destroy(child_cg)) {\n+\t\tfprintf(stderr, \"Failed to remove charged cgroup\\n\");\n+\t\tgoto cleanup_dmabuf;\n+\t}\n+\n+\tdying = cg_read_key_long_poll(parent, \"cgroup.stat\",\n+\t\t\t\t      \"nr_dying_descendants \", 0,\n+\t\t\t\t      MEMCG_DMABUF_DEAD_WAIT_RETRIES,\n+\t\t\t\t      DEFAULT_WAIT_INTERVAL_US);\n+\tif (dying) {\n+\t\tfprintf(stderr, \"Removed cgroup still dying with buffer open\\n\");\n+\t\tgoto cleanup_dmabuf;\n+\t}\n+\n+\t/* The charge must have moved to the parent with the cgroup. */\n+\tdmabuf_stat = cg_read_key_long(parent, \"memory.stat\", \"dmabuf \");\n+\tif (dmabuf_stat != ONE_MEG)\n+\t\tdmabuf_stat = cg_read_key_long_poll(parent, \"memory.stat\",\n+\t\t\t\t\t\t    \"dmabuf \", ONE_MEG,\n+\t\t\t\t\t\t    MEMCG_DMABUF_WAIT_RETRIES,\n+\t\t\t\t\t\t    DEFAULT_WAIT_INTERVAL_US);\n+\tif (dmabuf_stat != ONE_MEG) {\n+\t\tfprintf(stderr, \"Charge not in parent after removal: expected %d, got %ld\\n\",\n+\t\t\tONE_MEG, dmabuf_stat);\n+\t\tgoto cleanup_dmabuf;\n+\t}\n+\n+\t/* Uncharge through the reparented object cgroup. */\n+\tclose(dmabuf_fd);\n+\tdmabuf_fd = -1;\n+\n+\tdmabuf_stat = cg_read_key_long(parent, \"memory.stat\", \"dmabuf \");\n+\tif (dmabuf_stat != 0)\n+\t\tdmabuf_stat = cg_read_key_long_poll(parent, \"memory.stat\",\n+\t\t\t\t\t\t    \"dmabuf \", 0,\n+\t\t\t\t\t\t    MEMCG_DMABUF_WAIT_RETRIES,\n+\t\t\t\t\t\t    DEFAULT_WAIT_INTERVAL_US);\n+\tif (dmabuf_stat != 0) {\n+\t\tfprintf(stderr, \"Expected dmabuf stat 0 after close, got %ld\\n\",\n+\t\t\tdmabuf_stat);\n+\t\tgoto cleanup_heap;\n+\t}\n+\n+\tret = KSFT_PASS;\n+\n+cleanup_dmabuf:\n+\tif (dmabuf_fd \u003e= 0)\n+\t\tclose(dmabuf_fd);\n+cleanup_cgfd:\n+\tif (cg_fd \u003e= 0)\n+\t\tclose(cg_fd);\n+cleanup_heap:\n+\tclose(heap_fd);\n+cleanup_child:\n+\tif (child_cg) {\n+\t\tcg_destroy(child_cg);\n+\t\tfree(child_cg);\n+\t}\n+cleanup_parent:\n+\tcg_destroy(parent);\n+\tfree(parent);\n+cleanup:\n+\treturn ret;\n+}\n+\n #define T(x) { x, #x }\n struct memcg_test {\n \tint (*fn)(const char *root);\n@@ -1818,13 +2243,20 @@ struct memcg_test {\n \tT(test_memcg_oom_group_score_events),\n \tT(test_memcg_inotify_delete_file),\n \tT(test_memcg_inotify_delete_dir),\n+\tT(test_memcg_dmabuf),\n+\tT(test_memcg_dmabuf_xfer_at_limit),\n+\tT(test_memcg_dmabuf_dead_cgroup),\n };\n #undef T\n \n int main(int argc, char **argv)\n {\n \tchar root[PATH_MAX];\n-\tint i, proc_status;\n+\tint i, proc_status, count = ARRAY_SIZE(tests);\n+\tconst char *filter = NULL;\n+\n+\tif (argc \u003e 1)\n+\t\tfilter = argv[1];\n \n \tpage_size = sysconf(_SC_PAGE_SIZE);\n \tif (page_size \u003c= 0)\n@@ -1855,8 +2287,19 @@ int main(int argc, char **argv)\n \t\tksft_exit_skip(\"Failed to query cgroup mount option\\n\");\n \thas_localevents = proc_status;\n \n-\tksft_set_plan(ARRAY_SIZE(tests));\n+\tif (filter) {\n+\t\tcount = 0;\n+\t\tfor (i = 0; i \u003c ARRAY_SIZE(tests); i++) {\n+\t\t\tif (!strcmp(tests[i].name, filter))\n+\t\t\t\tcount++;\n+\t\t}\n+\t\tif (!count)\n+\t\t\tksft_exit_fail_msg(\"unknown test '%s'\\n\", filter);\n+\t}\n+\tksft_set_plan(count);\n \tfor (i = 0; i \u003c ARRAY_SIZE(tests); i++) {\n+\t\tif (filter \u0026\u0026 strcmp(tests[i].name, filter))\n+\t\t\tcontinue;\n \t\tswitch (tests[i].fn(root)) {\n \t\tcase KSFT_PASS:\n \t\t\tksft_test_result_pass(\"%s\\n\", tests[i].name);\ndiff --git a/tools/testing/selftests/dmabuf-heaps/config b/tools/testing/selftests/dmabuf-heaps/config\nindex be091f1cdfa04e..94c8f33b71a28d 100644\n--- a/tools/testing/selftests/dmabuf-heaps/config\n+++ b/tools/testing/selftests/dmabuf-heaps/config\n@@ -1,3 +1,4 @@\n+CONFIG_MEMCG=y\n CONFIG_DMABUF_HEAPS=y\n CONFIG_DMABUF_HEAPS_SYSTEM=y\n CONFIG_DRM_VGEM=y\ndiff --git a/tools/testing/selftests/dmabuf-heaps/dmabuf-heap.c b/tools/testing/selftests/dmabuf-heaps/dmabuf-heap.c\nindex 1d49df6719198a..44e3f33acf8775 100644\n--- a/tools/testing/selftests/dmabuf-heaps/dmabuf-heap.c\n+++ b/tools/testing/selftests/dmabuf-heaps/dmabuf-heap.c\n@@ -3,6 +3,7 @@\n #include \u003cdirent.h\u003e\n #include \u003cerrno.h\u003e\n #include \u003cfcntl.h\u003e\n+#include \u003csignal.h\u003e\n #include \u003cstdio.h\u003e\n #include \u003cstdlib.h\u003e\n #include \u003cstdint.h\u003e\n@@ -10,11 +11,16 @@\n #include \u003cunistd.h\u003e\n #include \u003csys/ioctl.h\u003e\n #include \u003csys/mman.h\u003e\n+#include \u003csys/prctl.h\u003e\n+#include \u003csys/syscall.h\u003e\n #include \u003csys/types.h\u003e\n+#include \u003csys/wait.h\u003e\n \n #include \u003clinux/dma-buf.h\u003e\n #include \u003clinux/dma-heap.h\u003e\n+#include \u003clinux/limits.h\u003e\n #include \u003cdrm/drm.h\u003e\n+#include \"../pidfd/pidfd.h\"\n #include \"kselftest.h\"\n \n #define DEVPATH \"/dev/dma_heap\"\n@@ -320,6 +326,8 @@ static int dmabuf_heap_alloc_newer(int fd, size_t len, unsigned int flags,\n \t\t__u32 fd;\n \t\t__u32 fd_flags;\n \t\t__u64 heap_flags;\n+\t\t__u32 charge_fd;\n+\t\t__u32 __padding;\n \t\t__u64 garbage1;\n \t\t__u64 garbage2;\n \t\t__u64 garbage3;\n@@ -328,6 +336,8 @@ static int dmabuf_heap_alloc_newer(int fd, size_t len, unsigned int flags,\n \t\t.fd = 0,\n \t\t.fd_flags = O_RDWR | O_CLOEXEC,\n \t\t.heap_flags = flags,\n+\t\t.charge_fd = 0,\n+\t\t.__padding = 0,\n \t\t.garbage1 = 0xffffffff,\n \t\t.garbage2 = 0x88888888,\n \t\t.garbage3 = 0x11111111,\n@@ -496,6 +506,227 @@ static void test_alloc_no_fd_leak_on_efault(char *heap_name)\n \tksft_test_result(fd_before == fd_after,\n \t\t\t \"fd leak on EFAULT: before=%d after=%d\\n\",\n \t\t\t fd_before, fd_after);\n+\n+out:\n+\tclose(heap_fd);\n+}\n+\n+static int dmabuf_heap_alloc_pidfd(int fd, size_t len, unsigned int heap_flags,\n+\t\t\t\t   unsigned int charge_fd, int *dmabuf_fd)\n+{\n+\tstruct dma_heap_allocation_data data = {\n+\t\t.len = len,\n+\t\t.fd = 0,\n+\t\t.fd_flags = O_RDWR | O_CLOEXEC,\n+\t\t.heap_flags = heap_flags,\n+\t\t.charge_fd = charge_fd,\n+\t};\n+\tint ret;\n+\n+\tif (!dmabuf_fd)\n+\t\treturn -EINVAL;\n+\n+\tret = ioctl(fd, DMA_HEAP_IOCTL_ALLOC, \u0026data);\n+\tif (ret \u003c 0)\n+\t\treturn ret;\n+\t*dmabuf_fd = (int)data.fd;\n+\treturn ret;\n+}\n+\n+/*\n+ * Probe whether the kernel honours charge_fd in DMA_HEAP_IOCTL_ALLOC.\n+ */\n+static bool pidfd_alloc_supported(int heap_fd)\n+{\n+\tint devnull_fd, dmabuf_fd = -1, ret;\n+\n+\tdevnull_fd = open(\"/dev/null\", O_RDONLY);\n+\tif (devnull_fd \u003c 0)\n+\t\treturn false;\n+\n+\tret = dmabuf_heap_alloc_pidfd(heap_fd, ONE_MEG, 0, devnull_fd, \u0026dmabuf_fd);\n+\tif (dmabuf_fd \u003e= 0) {\n+\t\tclose(dmabuf_fd);\n+\t\tdmabuf_fd = -1;\n+\t}\n+\tclose(devnull_fd);\n+\treturn ret \u003c 0;\n+}\n+\n+/*\n+ * Test: allocate charging the calling process's own cgroup via a self pidfd.\n+ */\n+static void test_alloc_pidfd_self(char *heap_name)\n+{\n+\tint heap_fd = -1, pidfd = -1, dmabuf_fd = -1, ret;\n+\n+\theap_fd = dmabuf_heap_open(heap_name);\n+\n+\tif (!pidfd_alloc_supported(heap_fd)) {\n+\t\tksft_test_result_skip(\"charge_fd not supported by this kernel\\n\");\n+\t\tgoto out;\n+\t}\n+\n+\tpidfd = sys_pidfd_open(getpid(), 0);\n+\tif (pidfd \u003c 0) {\n+\t\tksft_test_result_skip(\"pidfd_open not available\\n\");\n+\t\tgoto out;\n+\t}\n+\n+\tret = dmabuf_heap_alloc_pidfd(heap_fd, ONE_MEG, 0, pidfd, \u0026dmabuf_fd);\n+\tksft_test_result(!ret, \"Allocation with self pidfd %d\\n\", ret);\n+\tif (dmabuf_fd \u003e= 0)\n+\t\tclose(dmabuf_fd);\n+\tclose(pidfd);\n+out:\n+\tclose(heap_fd);\n+}\n+\n+/*\n+ * Test: allocate charging a child process's cgroup via a child pidfd.\n+ */\n+static void test_alloc_pidfd_child(char *heap_name)\n+{\n+\tint heap_fd = -1, pidfd = -1, dmabuf_fd = -1;\n+\tpid_t child_pid, parent_pid;\n+\tint status, ret;\n+\n+\theap_fd = dmabuf_heap_open(heap_name);\n+\n+\tif (!pidfd_alloc_supported(heap_fd)) {\n+\t\tksft_test_result_skip(\"charge_fd not supported by this kernel\\n\");\n+\t\tgoto out;\n+\t}\n+\n+\tparent_pid = getpid();\n+\tchild_pid = fork();\n+\tif (child_pid == 0) {\n+\t\tprctl(PR_SET_PDEATHSIG, SIGKILL);\n+\t\tif (getppid() != parent_pid)\n+\t\t\t_exit(0);\n+\t\tpause();\n+\t\t_exit(0);\n+\t}\n+\tif (child_pid \u003c 0)\n+\t\tksft_exit_fail_msg(\"fork failed: %s\\n\", strerror(errno));\n+\n+\tpidfd = sys_pidfd_open(child_pid, 0);\n+\tif (pidfd \u003c 0) {\n+\t\tkill(child_pid, SIGTERM);\n+\t\twaitpid(child_pid, \u0026status, 0);\n+\t\tksft_test_result_skip(\"pidfd_open for child failed\\n\");\n+\t\tgoto out;\n+\t}\n+\n+\tret = dmabuf_heap_alloc_pidfd(heap_fd, ONE_MEG, 0, pidfd, \u0026dmabuf_fd);\n+\tksft_test_result(!ret, \"Allocation with child pidfd %d\\n\", ret);\n+\tif (dmabuf_fd \u003e= 0)\n+\t\tclose(dmabuf_fd);\n+\tclose(pidfd);\n+\tkill(child_pid, SIGTERM);\n+\twaitpid(child_pid, \u0026status, 0);\n+out:\n+\tclose(heap_fd);\n+}\n+\n+static int open_self_cgroupfd(void)\n+{\n+\tchar cgroup_path[PATH_MAX];\n+\tchar line[PATH_MAX];\n+\tint ret = -1;\n+\tFILE *f;\n+\n+\tf = fopen(\"/proc/self/cgroup\", \"r\");\n+\tif (!f)\n+\t\treturn -1;\n+\twhile (fgets(line, sizeof(line), f)) {\n+\t\tif (strncmp(line, \"0::\", 3))\n+\t\t\tcontinue;\n+\t\tline[strcspn(line, \"\\n\")] = '\\0';\n+\t\tif (snprintf(cgroup_path, sizeof(cgroup_path),\n+\t\t\t     \"/sys/fs/cgroup%s\", line + 3) \u003c PATH_MAX)\n+\t\t\tret = 0;\n+\t\tbreak;\n+\t}\n+\tfclose(f);\n+\n+\tif (ret)\n+\t\treturn -1;\n+\n+\treturn open(cgroup_path, O_RDONLY | O_DIRECTORY);\n+}\n+\n+/*\n+ * Test: allocate charging the calling process's own cgroup via a cgroupfd.\n+ */\n+static void test_alloc_cgroupfd_self(char *heap_name)\n+{\n+\tint heap_fd = -1, cgroup_fd = -1, dmabuf_fd = -1, ret;\n+\n+\theap_fd = dmabuf_heap_open(heap_name);\n+\n+\tif (!pidfd_alloc_supported(heap_fd)) {\n+\t\tksft_test_result_skip(\"charge_fd not supported by this kernel\\n\");\n+\t\tgoto out;\n+\t}\n+\n+\tcgroup_fd = open_self_cgroupfd();\n+\tif (cgroup_fd \u003c 0) {\n+\t\tksft_test_result_skip(\"cannot open self cgroupfd\\n\");\n+\t\tgoto out;\n+\t}\n+\n+\tret = dmabuf_heap_alloc_pidfd(heap_fd, ONE_MEG, 0, cgroup_fd, \u0026dmabuf_fd);\n+\tksft_test_result(!ret, \"Allocation with cgroupfd %d\\n\", ret);\n+\tif (dmabuf_fd \u003e= 0)\n+\t\tclose(dmabuf_fd);\n+\tclose(cgroup_fd);\n+out:\n+\tclose(heap_fd);\n+}\n+\n+/*\n+ * Test: transfer a dma-buf's charge to self cgroup via DMA_BUF_IOCTL_XFER_CHARGE.\n+ */\n+static void test_xfer_charge_cgroupfd_self(char *heap_name)\n+{\n+\tint heap_fd = -1, cgroup_fd = -1, dmabuf_fd = -1, ret;\n+\tstruct dma_buf_transfer_charge xfer = { 0 };\n+\n+\theap_fd = dmabuf_heap_open(heap_name);\n+\n+\tif (!pidfd_alloc_supported(heap_fd)) {\n+\t\tksft_test_result_skip(\"charge_fd not supported by this kernel\\n\");\n+\t\tgoto out;\n+\t}\n+\n+\tret = dmabuf_heap_alloc(heap_fd, ONE_MEG, 0, \u0026dmabuf_fd);\n+\tif (ret) {\n+\t\tksft_test_result_fail(\"Allocation failed %d\\n\", ret);\n+\t\tgoto out;\n+\t}\n+\n+\tcgroup_fd = open_self_cgroupfd();\n+\tif (cgroup_fd \u003c 0) {\n+\t\tksft_test_result_skip(\"cannot open self cgroupfd\\n\");\n+\t\tclose(dmabuf_fd);\n+\t\tgoto out;\n+\t}\n+\n+\txfer.charge_fd = cgroup_fd;\n+\tret = ioctl(dmabuf_fd, DMA_BUF_IOCTL_XFER_CHARGE, \u0026xfer);\n+\tif (!ret)\n+\t\tksft_test_result_pass(\"XFER_CHARGE to self cgroupfd\\n\");\n+\telse if (errno == EOPNOTSUPP)\n+\t\tksft_test_result_skip(\"buffer not memcg-charged (mem_accounting=0?)\\n\");\n+\telse if (errno == ENOTTY || errno == EINVAL)\n+\t\tksft_test_result_skip(\"XFER_CHARGE not supported: %s\\n\",\n+\t\t\t\t      strerror(errno));\n+\telse\n+\t\tksft_test_result_fail(\"XFER_CHARGE failed: %s\\n\", strerror(errno));\n+\n+\tclose(cgroup_fd);\n+\tclose(dmabuf_fd);\n out:\n \tclose(heap_fd);\n }\n@@ -530,7 +761,7 @@ int main(void)\n \t\treturn KSFT_SKIP;\n \t}\n \n-\tksft_set_plan(12 * numer_of_heaps());\n+\tksft_set_plan(16 * numer_of_heaps());\n \n \twhile ((dir = readdir(d))) {\n \t\tif (!strncmp(dir-\u003ed_name, \".\", 2))\n@@ -546,6 +777,10 @@ int main(void)\n \t\ttest_alloc_compat(dir-\u003ed_name);\n \t\ttest_alloc_errors(dir-\u003ed_name);\n \t\ttest_alloc_no_fd_leak_on_efault(dir-\u003ed_name);\n+\t\ttest_alloc_pidfd_self(dir-\u003ed_name);\n+\t\ttest_alloc_pidfd_child(dir-\u003ed_name);\n+\t\ttest_alloc_cgroupfd_self(dir-\u003ed_name);\n+\t\ttest_xfer_charge_cgroupfd_self(dir-\u003ed_name);\n \t}\n \tclosedir(d);\n \ndiff --git a/tools/testing/selftests/dmabuf-heaps/vmtest.sh b/tools/testing/selftests/dmabuf-heaps/vmtest.sh\nnew file mode 100755\nindex 00000000000000..3574b71ca83e85\n--- /dev/null\n+++ b/tools/testing/selftests/dmabuf-heaps/vmtest.sh\n@@ -0,0 +1,226 @@\n+#!/bin/bash\n+# SPDX-License-Identifier: GPL-2.0\n+#\n+# Copyright (c) 2026 Red Hat\n+#\n+# Dependencies:\n+#\t\t* virtme-ng\n+#\t\t* qemu\t(used by virtme-ng)\n+\n+readonly SCRIPT_DIR=\"$(cd -P -- \"$(dirname -- \"${BASH_SOURCE[0]}\")\" \u0026\u0026 pwd -P)\"\n+readonly KERNEL_CHECKOUT=$(realpath \"${SCRIPT_DIR}\"/../../../../)\n+readonly CGROUP_DIR=\"${KERNEL_CHECKOUT}/tools/testing/selftests/cgroup\"\n+\n+source \"${SCRIPT_DIR}\"/../kselftest/ktap_helpers.sh\n+\n+readonly DMABUF_HEAP_TEST=\"${SCRIPT_DIR}\"/dmabuf-heap\n+readonly MEMCONTROL_TEST=\"${CGROUP_DIR}\"/test_memcontrol\n+readonly TMP_DIR=$(mktemp -d /tmp/dmabuf-vmtest.XXXXXXXX)\n+\n+VERBOSE=false\n+BUILD=false\n+BUILD_HOST=\"\"\n+BUILD_HOST_PODMAN_CONTAINER_NAME=\"\"\n+SHELL_MODE=false\n+\n+usage() {\n+\techo\n+\techo \"$0 [OPTIONS]\"\n+\techo\n+\techo \"Options\"\n+\techo \"  -b: build the kernel from the current source tree and use it for the VM\"\n+\techo \"  -H: hostname for remote build host (used with -b)\"\n+\techo \"  -p: podman container name for remote build host (used with -b)\"\n+\techo \"      Example: -H beefyserver -p vng\"\n+\techo \"  -s: drop into an interactive shell in the VM instead of running tests\"\n+\techo \"  -v: enable verbose vng/qemu output\"\n+\techo\n+\n+\texit 1\n+}\n+\n+die() {\n+\techo \"$*\" \u003e\u00262\n+\texit \"${KSFT_FAIL}\"\n+}\n+\n+cleanup() {\n+\trm -rf \"${TMP_DIR}\"\n+}\n+\n+check_deps() {\n+\tfor dep in vng make; do\n+\t\tif [[ ! -x $(command -v \"${dep}\") ]]; then\n+\t\t\techo -e \"skip:    dependency ${dep} not found!\\n\"\n+\t\t\texit \"${KSFT_SKIP}\"\n+\t\tfi\n+\tdone\n+\n+\tif ${SHELL_MODE}; then\n+\t\treturn\n+\tfi\n+\n+\tif [[ ! -x \"${DMABUF_HEAP_TEST}\" ]]; then\n+\t\tprintf \"skip:    %s not found!\" \"${DMABUF_HEAP_TEST}\"\n+\t\tprintf \" Please build the kselftest dmabuf-heaps target (or use -b).\\n\"\n+\t\texit \"${KSFT_SKIP}\"\n+\tfi\n+\n+\tif [[ ! -x \"${MEMCONTROL_TEST}\" ]]; then\n+\t\tprintf \"skip:    %s not found!\" \"${MEMCONTROL_TEST}\"\n+\t\tprintf \" Please build the kselftest cgroup target (or use -b).\\n\"\n+\t\texit \"${KSFT_SKIP}\"\n+\tfi\n+}\n+\n+check_vng() {\n+\tlocal tested_versions=(\"1.36\" \"1.37\")\n+\tlocal version\n+\tlocal ok=0\n+\n+\tversion=\"$(vng --version)\"\n+\tfor tv in \"${tested_versions[@]}\"; do\n+\t\tif [[ \"${version}\" == *\"${tv}\"* ]]; then\n+\t\t\tok=1\n+\t\t\tbreak\n+\t\tfi\n+\tdone\n+\n+\tif [[ \"${ok}\" -eq 0 ]]; then\n+\t\tprintf \"warning: vng version '%s' has not been tested and may \" \"${version}\" \u003e\u00262\n+\t\tprintf \"not function properly.\\n\\tThe following versions have been tested: \" \u003e\u00262\n+\t\techo \"${tested_versions[@]}\" \u003e\u00262\n+\tfi\n+}\n+\n+build_selftests() {\n+\tmake -C \"${KERNEL_CHECKOUT}\" headers_install \\\n+\t\tINSTALL_HDR_PATH=\"${TMP_DIR}/usr\" -j\"$(nproc)\"\n+\n+\tlocal khdr=\"-isystem ${TMP_DIR}/usr/include\"\n+\n+\tif ! make -C \"${SCRIPT_DIR}\" KHDR_INCLUDES=\"${khdr}\" -j\"$(nproc)\"; then\n+\t\tdie \"failed to build dmabuf-heaps selftests\"\n+\tfi\n+\n+\tif ! make -C \"${CGROUP_DIR}\" KHDR_INCLUDES=\"${khdr}\" \\\n+\t\t\"${MEMCONTROL_TEST}\" -j\"$(nproc)\"; then\n+\t\tdie \"failed to build cgroup/test_memcontrol selftest\"\n+\tfi\n+}\n+\n+handle_build() {\n+\tif ! ${BUILD}; then\n+\t\treturn\n+\tfi\n+\n+\tif [[ ! -d \"${KERNEL_CHECKOUT}\" ]]; then\n+\t\techo \"-b requires vmtest.sh called from the kernel source tree\" \u003e\u00262\n+\t\texit 1\n+\tfi\n+\n+\tpushd \"${KERNEL_CHECKOUT}\" \u0026\u003e/dev/null\n+\n+\tif ! vng --kconfig --config \"${SCRIPT_DIR}/config\"; then\n+\t\tdie \"failed to generate .config for kernel source tree (${KERNEL_CHECKOUT})\"\n+\tfi\n+\n+\tlocal vng_args=(\"-v\" \"--config\" \"${SCRIPT_DIR}/config\" \"--build\")\n+\n+\tif [[ -n \"${BUILD_HOST}\" ]]; then\n+\t\tvng_args+=(\"--build-host\" \"${BUILD_HOST}\")\n+\tfi\n+\n+\tif [[ -n \"${BUILD_HOST_PODMAN_CONTAINER_NAME}\" ]]; then\n+\t\tvng_args+=(\"--build-host-exec-prefix\" \\\n+\t\t\t   \"podman exec -ti ${BUILD_HOST_PODMAN_CONTAINER_NAME}\")\n+\tfi\n+\n+\tif ! vng \"${vng_args[@]}\"; then\n+\t\tdie \"failed to build kernel from source tree (${KERNEL_CHECKOUT})\"\n+\tfi\n+\n+\tbuild_selftests\n+\n+\tpopd \u0026\u003e/dev/null\n+}\n+\n+make_runner() {\n+\t# virtme-ng shares the host filesystem, so TMP_DIR is accessible\n+\t# inside the VM at the same absolute path.\n+\tcat \u003e \"${TMP_DIR}/run_tests.sh\" \u003c\u003c-EOF\n+\t#!/bin/sh\n+\tset -u\n+\n+\t# Enable memory controller for child cgroups\n+\techo +memory \u003e /sys/fs/cgroup/cgroup.subtree_control 2\u003e/dev/null\n+\n+\tPASS=0; FAIL=0; SKIP=0; N=0\n+\n+\trun() {\n+\t\tname=\"\\$1\"; shift\n+\t\tN=\\$((N+1))\n+\t\t\"\\$@\"; rc=\\$?\n+\t\tif   [ \\$rc -eq 0 ]; then echo \"ok \\$N \\$name\";        PASS=\\$((PASS+1))\n+\t\telif [ \\$rc -eq 4 ]; then echo \"ok \\$N \\$name # SKIP\"; SKIP=\\$((SKIP+1))\n+\t\telse                      echo \"not ok \\$N \\$name\";    FAIL=\\$((FAIL+1))\n+\t\tfi\n+\t}\n+\n+\trun \"dmabuf-heap charge_fd ioctl\"\t${DMABUF_HEAP_TEST}\n+\trun \"memcontrol dma-buf memcg\"\t${MEMCONTROL_TEST} test_memcg_dmabuf\n+\trun \"memcontrol dma-buf xfer limit\" \\\n+\t\t${MEMCONTROL_TEST} test_memcg_dmabuf_xfer_at_limit\n+\techo \"# PASS=\\$PASS SKIP=\\$SKIP FAIL=\\$FAIL\"\n+\t[ \\$FAIL -eq 0 ]\n+\tEOF\n+\tchmod +x \"${TMP_DIR}/run_tests.sh\"\n+}\n+\n+run_vm() {\n+\tlocal verbose_opt=\"\"\n+\tlocal kernel_opt=\"\"\n+\n+\t${VERBOSE} \u0026\u0026 verbose_opt=\"--verbose\"\n+\n+\t# If we are running from within the kernel source tree, use the kernel\n+\t# source tree as the kernel to boot, otherwise use the running kernel.\n+\tif [[ \"$(realpath \"$(pwd)\")\" == \"${KERNEL_CHECKOUT}\"* ]]; then\n+\t\tkernel_opt=\"${KERNEL_CHECKOUT}\"\n+\tfi\n+\n+\tif ${SHELL_MODE}; then\n+\t\techo \"Starting interactive shell in VM. Exit to stop VM.\"\n+\t\tvng --run ${kernel_opt} ${verbose_opt} --user root --memory 512M \\\n+\t\t\t--append \"dma_heap.mem_accounting=1\" \\\n+\t\t\t-- bash --noprofile --norc\n+\t\texit \"${KSFT_PASS}\"\n+\tfi\n+\n+\tvng --run ${kernel_opt} ${verbose_opt} --user root --memory 512M \\\n+\t\t--append \"dma_heap.mem_accounting=1\" \\\n+\t\t--exec \"${TMP_DIR}/run_tests.sh\"\n+}\n+\n+while getopts :hvsbH:p: o\n+do\n+\tcase $o in\n+\tv) VERBOSE=true;;\n+\tb) BUILD=true;;\n+\ts) SHELL_MODE=true;;\n+\tH) BUILD_HOST=$OPTARG;;\n+\tp) BUILD_HOST_PODMAN_CONTAINER_NAME=$OPTARG;;\n+\th|*) usage;;\n+\tesac\n+done\n+shift $((OPTIND-1))\n+\n+trap cleanup EXIT\n+\n+check_deps\n+check_vng\n+handle_build\n+make_runner\n+\n+echo \"Booting VM and running tests...\"\n+run_vm\n"
}

2/1 2026/11/20 23:06 agent patch-evaluator
1m Model:
core

Args:
null

Results:
{
  "EnableConfigs": [
    "CGROUPS",
    "MEMCG",
    "DMABUF_HEAPS",
    "DMABUF_HEAPS_SYSTEM"
  ],
  "FocusSymbols": [
    "dma_buf_xfer_charge",
    "dma_heap_ioctl_allocate",
    "system_heap_allocate",
    "get_obj_cgroup_from_fd",
    "obj_cgroup_transfer_charge",
    "obj_cgroup_reserve_dmabuf",
    "obj_cgroup_cancel_dmabuf",
    "mem_cgroup_commit_dmabuf",
    "mem_cgroup_uncharge_dmabuf"
  ],
  "Reasoning": "The patch series implements cgroup-based memory accounting for DMA buffers and DMA heaps. It introduces a new ioctl DMA_BUF_IOCTL_XFER_CHARGE to transfer buffer memory charges between cgroups (using pidfds or cgroupfds), modifies DMA_HEAP_IOCTL_ALLOC to allow allocating dma-bufs charged directly to a specified cgroup, and adds new memcg/objcg accounting functions. These paths are directly reachable from userspace via /dev/dma_heap/system and exported dma-buf file descriptors in standard QEMU/virtualized environments. Fuzzing is warranted to test object cgroup reference counting, cross-cgroup charge transfers, and concurrent ioctl operations.",
  "WorthFuzzing": true
}

Instruction:
You are an expert Linux kernel maintainer and security engineer.
Your job is to review a provided patch series and evaluate whether it warrants fuzzing with syzkaller.

IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in
your workspace. Do NOT rely on internal assumptions. You must actively use your code access
tools to inspect the actual source code, callers, and surrounding context.

================================================================================
1. CORE TRIAGE PHILOSOPHY
================================================================================
The goal of patch fuzzing is to discover crashes, regressions, exposed latent bugs,
and newly triggered assertions introduced by the patch series.

- REACHABILITY IS THE PRIMARY GATE:
  Fuzzing can only discover bugs in code that can actually execute in standard virtualized
  environments (GCE or QEMU, utilizing software-emulated devices like USB gadgets, netdev, tun/tap).
  If the modified code is structurally unreachable (see Section 2), it MUST NOT be fuzzed,
  regardless of whether it adds assertions or complex logic.

- DO NOT BLINDLY TRUST "NO FUNCTIONAL CHANGE" (NFCI) OR "REFACTORING" CLAIMS:
  Patch authors routinely label changes as "cleanups", "refactorings", or state
  "No functional change intended". Do NOT take these claims at face value.
  Code refactorings that rearrange logic, introduce helper functions, or alter state management
  in core subsystems frequently introduce subtle semantic shifts or uncover latent kernel bugs.
  If reachable executable code is modified or refactored, it MUST be fuzzed.

- NEW OR MODIFIED ASSERTIONS IN REACHABLE CODE MUST BE FUZZED:
  When a patch introduces or modifies runtime checks or assertions (e.g., WARN_ON*, VM_WARN_ON*,
  BUG_ON*, lockdep_assert*) in reachable code paths, it enforces new or stricter invariants.
  Even if the author believes the invariant always holds, fuzzing is essential to verify whether
  an unusual sequence of operations can violate it.

================================================================================
2. WHEN TO RETURN WorthFuzzing=false (NEGATIVE CRITERIA)
================================================================================
Return WorthFuzzing=false ONLY IF all modified code falls strictly into one or more of these categories:

- Non-kernel and non-executable changes:
  * Modifications to Documentation/, comments, or spelling fixes.
  * User-space directories, self-tests, samples, or scripts (e.g., tools/, samples/, scripts/, usr/)
    that do not affect the compiled kernel image (vmlinux) or kernel modules.
  * Purely decorative logging (e.g., message strings in pr_err, printk, dev_info) or tracepoints
    that do not alter control flow or data structures.
  * Build system or Kconfig changes that do not alter compiled C logic.
- Structurally unreachable hardware:
  * Vendor-specific PCIe switches, SmartNICs, or GPU drivers (e.g., mlxsw, pds_core, qed,
    ionic, amdgpu) requiring physical ASIC/PCIe cards not emulated in standard QEMU.
- Unreachable execution paths:
  * Driver teardown callbacks (.remove, .shutdown, pci_unregister_driver) executed only during
    physical PCI hot-unplug or manual sysfs driver unbinding.
  * Code paths exclusive to architectures other than the target architecture.

================================================================================
3. WHEN TO RETURN WorthFuzzing=true (POSITIVE CRITERIA)
================================================================================
Return WorthFuzzing=true whenever the patch touches reachable executable code, including:
- Core Subsystems:
  * Any logic modifications in memory management (mm/), synchronization/locking (kernel/locking/),
    BPF, scheduler, core networking, VFS, or syscall handling.
- Refactorings and Code Cleanups:
  * Any restructuring of reachable data structures, helper abstractions, or algorithm flows.
- Runtime Assertions and Defensive Checks:
  * Any introduction or alteration of assertions (WARN_ON*, VM_WARN_ON*, BUG_ON*, etc.) in reachable paths.
- Reachable Drivers and Protocols:
  * Drivers accessible via virtual buses (virtio, USB gadget, loopback, netlink, binder, sockets, etc.).

================================================================================
4. EXTRACTING FocusSymbols (PREVENTING DILUTION)
================================================================================
When WorthFuzzing=true, you must extract specific kernel functions into FocusSymbols to guide the fuzzer:

- AVOID UBIQUITOUS LIFECYCLE HOT-PATHS:
  Do NOT list generic, ubiquitous functions called by almost every program in the corpus
  (including, but not limited to: general memory allocators and deallocators, page fault
  and trap handlers, or core synchronization primitives; this is not an exhaustive list).
  Listing ubiquitous functions causes the fuzzer to classify thousands of unrelated tests as "focused",
  which severely dilutes fuzzing effort away from the actual changes.

- TARGET SPECIFIC FEATURE LOGIC AND ENTRYPOINTS:
  List functions that specifically implement the logic being added or altered, or direct API entrypoints
  for the subsystem feature under review.

- HANDLING STATIC INLINE FUNCTIONS IN HEADERS (.h):
  Compiler-inlined static functions (such as static inlines in mm/*.h or include/linux/*.h) lack
  distinct symbol addresses in vmlinux and cannot be targeted directly by symbol coverage filters.
  If the changes are primarily in static inline helpers, identify non-static, feature-specific caller
  functions in .c files that exercise them (avoiding ubiquitous lifecycle wrappers).

================================================================================
5. IDENTIFYING EnableConfigs
================================================================================
Identify any specific CONFIG_ options required to properly compile and reach the modified code:
- Inspect Kconfig files and #ifdef guards; do not make assumptions.
- Check "depends on" lines in Kconfig to include any non-standard parent subsystem configs needed.
- Strip any 'CONFIG_' prefix (e.g., return "NET_IPV4" instead of "CONFIG_NET_IPV4").
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit d5ea44c8586e67c2b98673186f76297f7f795f2b
Author: syz-cluster <triage@syzkaller.com>
Date:   Fri Nov 20 23:06:42 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/admin-guide/cgroup-v2.rst b/Documentation/admin-guide/cgroup-v2.rst
index 9e3c67b02ae2e1..8d10ff7ac745ac 100644
--- a/Documentation/admin-guide/cgroup-v2.rst
+++ b/Documentation/admin-guide/cgroup-v2.rst
@@ -1666,6 +1666,12 @@ The following nested keys are defined.
 		Amount of memory used for storing in-kernel data
 		structures.
 
+	  dmabuf (npn)
+		Amount of memory used for exported DMA buffers allocated by or on
+		behalf of the cgroup, this currently includes system heap
+		allocations. Stays with the cgroup regardless of how the buffer
+		is shared, unless moved with DMA_BUF_IOCTL_XFER_CHARGE.
+
 	  workingset_refault_anon
 		Number of refaults of previously evicted anonymous pages.
 
diff --git a/drivers/dma-buf/dma-buf.c b/drivers/dma-buf/dma-buf.c
index 36cdc342627ee8..5d4b55b67e995c 100644
--- a/drivers/dma-buf/dma-buf.c
+++ b/drivers/dma-buf/dma-buf.c
@@ -14,6 +14,7 @@
 #include <linux/fs.h>
 #include <linux/slab.h>
 #include <linux/dma-buf.h>
+#include <linux/memcontrol.h>
 #include <linux/dma-fence.h>
 #include <linux/dma-fence-unwrap.h>
 #include <linux/anon_inodes.h>
@@ -182,6 +183,8 @@ static void dma_buf_release(struct dentry *dentry)
 
 	dmabuf->ops->release(dmabuf);
 
+	mem_cgroup_uncharge_dmabuf(dmabuf);
+
 	if (dmabuf->resv == (struct dma_resv *)&dmabuf[1])
 		dma_resv_fini(dmabuf->resv);
 
@@ -537,6 +540,42 @@ static long dma_buf_import_sync_file(struct dma_buf *dmabuf,
 }
 #endif
 
+/* Transfer a dma-buf's memcg charge; see struct dma_buf_transfer_charge */
+static long dma_buf_xfer_charge(struct dma_buf *dmabuf,
+				const void __user *user_data)
+{
+	struct dma_buf_transfer_charge arg;
+	struct obj_cgroup *objcg;
+	unsigned int nr_pages;
+	int ret = 0;
+
+	if (copy_from_user(&arg, user_data, sizeof(arg)))
+		return -EFAULT;
+
+	if (arg.flags != 0)
+		return -EINVAL;
+
+	objcg = get_obj_cgroup_from_fd(arg.charge_fd);
+	if (IS_ERR(objcg))
+		return PTR_ERR(objcg);
+
+	dma_resv_lock(dmabuf->resv, NULL);
+
+	if (!dmabuf->objcg) {
+		ret = -EOPNOTSUPP;
+		goto out;
+	}
+
+	nr_pages = PAGE_ALIGN(dmabuf->size) >> PAGE_SHIFT;
+	if (!obj_cgroup_transfer_charge(&dmabuf->objcg, objcg, MEMCG_DMABUF, nr_pages))
+		ret = -ENOMEM;
+
+out:
+	dma_resv_unlock(dmabuf->resv);
+	obj_cgroup_put(objcg);
+	return ret;
+}
+
 static long dma_buf_ioctl(struct file *file,
 			  unsigned int cmd, unsigned long arg)
 {
@@ -587,6 +626,9 @@ static long dma_buf_ioctl(struct file *file,
 		return dma_buf_import_sync_file(dmabuf, (const void __user *)arg);
 #endif
 
+	case DMA_BUF_IOCTL_XFER_CHARGE:
+		return dma_buf_xfer_charge(dmabuf, (const void __user *)arg);
+
 	default:
 		return -ENOTTY;
 	}
@@ -747,6 +789,7 @@ struct dma_buf *dma_buf_export(const struct dma_buf_export_info *exp_info)
 	dmabuf->size = exp_info->size;
 	dmabuf->exp_name = exp_info->exp_name;
 	dmabuf->owner = exp_info->owner;
+	dmabuf->objcg = exp_info->objcg;
 	spin_lock_init(&dmabuf->name_lock);
 	init_waitqueue_head(&dmabuf->poll);
 	dmabuf->cb_in.poll = dmabuf->cb_out.poll = &dmabuf->poll;
@@ -768,6 +811,8 @@ struct dma_buf *dma_buf_export(const struct dma_buf_export_info *exp_info)
 
 	DMA_BUF_TRACE(trace_dma_buf_export, dmabuf);
 
+	mem_cgroup_commit_dmabuf(dmabuf);
+
 	return dmabuf;
 
 err_file:
diff --git a/drivers/dma-buf/dma-heap.c b/drivers/dma-buf/dma-heap.c
index 8a6c2b6e0cc608..2f53bc95a45a81 100644
--- a/drivers/dma-buf/dma-heap.c
+++ b/drivers/dma-buf/dma-heap.c
@@ -10,6 +10,7 @@
 #include <linux/device.h>
 #include <linux/dma-buf.h>
 #include <linux/dma-heap.h>
+#include <linux/memcontrol.h>
 #include <linux/err.h>
 #include <linux/export.h>
 #include <linux/list.h>
@@ -78,6 +79,7 @@ static struct dma_buf *dma_heap_ioctl_allocate(struct file *file, void *data)
 	struct dma_heap_allocation_data *heap_allocation = data;
 	struct dma_heap *heap = file->private_data;
 	struct dma_buf *dmabuf;
+	struct obj_cgroup *objcg = NULL;
 	int fd;
 	size_t len;
 
@@ -90,15 +92,34 @@ static struct dma_buf *dma_heap_ioctl_allocate(struct file *file, void *data)
 	if (heap_allocation->heap_flags & ~DMA_HEAP_VALID_HEAP_FLAGS)
 		return ERR_PTR(-EINVAL);
 
+	if (heap_allocation->__padding != 0)
+		return ERR_PTR(-EINVAL);
+
+	if (heap_allocation->charge_fd) {
+		objcg = get_obj_cgroup_from_fd(heap_allocation->charge_fd);
+		if (IS_ERR(objcg))
+			return ERR_CAST(objcg);
+	}
+
+	if (!objcg && mem_accounting && !mem_cgroup_disabled())
+		objcg = get_obj_cgroup_from_current();
+
 	len = PAGE_ALIGN(heap_allocation->len);
-	if (!len)
+	if (!len) {
+		obj_cgroup_put(objcg);
 		return ERR_PTR(-EINVAL);
+	}
 
 	dmabuf = heap->ops->allocate(heap, len, heap_allocation->fd_flags,
-				     heap_allocation->heap_flags);
+				     heap_allocation->heap_flags, objcg);
 
-	if (IS_ERR(dmabuf))
+	if (IS_ERR(dmabuf)) {
+		obj_cgroup_put(objcg);
 		return dmabuf;
+	}
+
+	if (!dmabuf->objcg)
+		obj_cgroup_put(objcg);
 
 	fd = get_unused_fd_flags(heap_allocation->fd_flags);
 	if (fd < 0) {
diff --git a/drivers/dma-buf/heaps/cma_heap.c b/drivers/dma-buf/heaps/cma_heap.c
index 3fb4b946c91a6e..6c08dc25b17725 100644
--- a/drivers/dma-buf/heaps/cma_heap.c
+++ b/drivers/dma-buf/heaps/cma_heap.c
@@ -281,7 +281,8 @@ static const struct dma_buf_ops cma_heap_buf_ops = {
 static struct dma_buf *cma_heap_allocate(struct dma_heap *heap,
 					 unsigned long len,
 					 u32 fd_flags,
-					 u64 heap_flags)
+					 u64 heap_flags,
+					 struct obj_cgroup *objcg)
 {
 	struct cma_heap *cma_heap = dma_heap_get_drvdata(heap);
 	struct cma_heap_buffer *buffer;
diff --git a/drivers/dma-buf/heaps/system_heap.c b/drivers/dma-buf/heaps/system_heap.c
index c8959eadc71d18..ad94bb5be73670 100644
--- a/drivers/dma-buf/heaps/system_heap.c
+++ b/drivers/dma-buf/heaps/system_heap.c
@@ -17,6 +17,7 @@
 #include <linux/err.h>
 #include <linux/highmem.h>
 #include <linux/mem_encrypt.h>
+#include <linux/memcontrol.h>
 #include <linux/mm.h>
 #include <linux/set_memory.h>
 #include <linux/module.h>
@@ -388,8 +389,6 @@ static struct page *alloc_largest_available(unsigned long size,
 		if (max_order < orders[i])
 			continue;
 		flags = order_flags[i];
-		if (mem_accounting)
-			flags |= __GFP_ACCOUNT;
 		page = alloc_pages(flags, orders[i]);
 		if (!page)
 			continue;
@@ -401,11 +400,13 @@ static struct page *alloc_largest_available(unsigned long size,
 static struct dma_buf *system_heap_allocate(struct dma_heap *heap,
 					    unsigned long len,
 					    u32 fd_flags,
-					    u64 heap_flags)
+					    u64 heap_flags,
+					    struct obj_cgroup *objcg)
 {
 	struct system_heap_buffer *buffer;
 	DEFINE_DMA_BUF_EXPORT_INFO(exp_info);
 	unsigned long size_remaining = len;
+	unsigned long nr_pages = PAGE_ALIGN(len) >> PAGE_SHIFT;
 	unsigned int max_order = orders[0];
 	struct system_heap_priv *priv = dma_heap_get_drvdata(heap);
 	bool cc_shared = priv->cc_shared;
@@ -416,10 +417,15 @@ static struct dma_buf *system_heap_allocate(struct dma_heap *heap,
 	struct page *page, *tmp_page;
 	int i, ret = -ENOMEM;
 
-	buffer = kzalloc_obj(*buffer);
-	if (!buffer)
+	if (!obj_cgroup_reserve_dmabuf(objcg, GFP_KERNEL, nr_pages))
 		return ERR_PTR(-ENOMEM);
 
+	buffer = kzalloc_obj(*buffer);
+	if (!buffer) {
+		ret = -ENOMEM;
+		goto cancel_charge;
+	}
+
 	INIT_LIST_HEAD(&buffer->attachments);
 	mutex_init(&buffer->lock);
 	buffer->heap = heap;
@@ -473,6 +479,7 @@ static struct dma_buf *system_heap_allocate(struct dma_heap *heap,
 	exp_info.size = buffer->len;
 	exp_info.flags = fd_flags;
 	exp_info.priv = buffer;
+	exp_info.objcg = objcg;
 	dmabuf = dma_buf_export(&exp_info);
 	if (IS_ERR(dmabuf)) {
 		ret = PTR_ERR(dmabuf);
@@ -498,6 +505,8 @@ static struct dma_buf *system_heap_allocate(struct dma_heap *heap,
 	list_for_each_entry_safe(page, tmp_page, &pages, lru)
 		__free_pages(page, compound_order(page));
 	kfree(buffer);
+cancel_charge:
+	obj_cgroup_cancel_dmabuf(objcg, nr_pages);
 
 	return ERR_PTR(ret);
 }
diff --git a/drivers/tee/tee_heap.c b/drivers/tee/tee_heap.c
index 007c001565204b..83fd14a0aaec2d 100644
--- a/drivers/tee/tee_heap.c
+++ b/drivers/tee/tee_heap.c
@@ -167,7 +167,8 @@ static const struct dma_buf_ops tee_heap_buf_ops = {
 
 static struct dma_buf *tee_dma_heap_alloc(struct dma_heap *heap,
 					  unsigned long len, u32 fd_flags,
-					  u64 heap_flags)
+					  u64 heap_flags,
+					  struct obj_cgroup *objcg)
 {
 	struct tee_dma_heap *h = dma_heap_get_drvdata(heap);
 	DEFINE_DMA_BUF_EXPORT_INFO(exp_info);
diff --git a/include/linux/dma-buf.h b/include/linux/dma-buf.h
index d15b2b31d3c91e..916d73ae6a511f 100644
--- a/include/linux/dma-buf.h
+++ b/include/linux/dma-buf.h
@@ -27,6 +27,7 @@
 struct device;
 struct dma_buf;
 struct dma_buf_attachment;
+struct obj_cgroup;
 
 /**
  * struct dma_buf_ops - operations possible on struct dma_buf
@@ -429,6 +430,9 @@ struct dma_buf {
 
 		__poll_t active;
 	} cb_in, cb_out;
+
+	/** @objcg: object cgroup to which this buffer is currently attributed */
+	struct obj_cgroup *objcg;
 };
 
 /**
@@ -501,6 +505,11 @@ struct dma_buf_attachment {
  * @flags:	mode flags for the file
  * @resv:	reservation-object, NULL to allocate default one
  * @priv:	Attach private data of allocator to this buffer
+ * @objcg:	object cgroup to charge for this buffer's memory. Set only for
+ *		buffers backed by system memory, not accounted elsewhere, where
+ *		@size reflects the actual allocation in bytes. The buffer takes
+ *		over the caller's reference. Enables charge transfer via
+ *		DMA_BUF_IOCTL_XFER_CHARGE.
  *
  * This structure holds the information required to export the buffer. Used
  * with dma_buf_export() only.
@@ -513,6 +522,7 @@ struct dma_buf_export_info {
 	int flags;
 	struct dma_resv *resv;
 	void *priv;
+	struct obj_cgroup *objcg;
 };
 
 /**
diff --git a/include/linux/dma-heap.h b/include/linux/dma-heap.h
index 648328a64b27ea..b5a42b49c68d04 100644
--- a/include/linux/dma-heap.h
+++ b/include/linux/dma-heap.h
@@ -12,6 +12,7 @@
 #include <linux/types.h>
 
 struct dma_heap;
+struct obj_cgroup;
 
 /**
  * struct dma_heap_ops - ops to operate on a given heap
@@ -23,7 +24,8 @@ struct dma_heap_ops {
 	struct dma_buf *(*allocate)(struct dma_heap *heap,
 				    unsigned long len,
 				    u32 fd_flags,
-				    u64 heap_flags);
+				    u64 heap_flags,
+				    struct obj_cgroup *objcg);
 };
 
 /**
diff --git a/include/linux/lsm_hook_defs.h b/include/linux/lsm_hook_defs.h
index 87d9d06710cb26..3b254b4e60ec74 100644
--- a/include/linux/lsm_hook_defs.h
+++ b/include/linux/lsm_hook_defs.h
@@ -43,6 +43,8 @@ LSM_HOOK(int, 0, capset, struct cred *new, const struct cred *old,
 	 const kernel_cap_t *permitted)
 LSM_HOOK(int, 0, capable, const struct cred *cred, struct user_namespace *ns,
 	 int cap, unsigned int opts)
+LSM_HOOK(int, 0, memcg_charge_task, const struct cred *from, const struct cred *to)
+LSM_HOOK(int, 0, memcg_charge_cgroup, const struct cred *cred, const struct file *file)
 LSM_HOOK(int, 0, quotactl, int cmds, int type, int id, const struct super_block *sb)
 LSM_HOOK(int, 0, quota_on, struct dentry *dentry)
 LSM_HOOK(int, 0, syslog, int type)
diff --git a/include/linux/memcontrol.h b/include/linux/memcontrol.h
index 69e1bcc67c588d..37c81be349b89d 100644
--- a/include/linux/memcontrol.h
+++ b/include/linux/memcontrol.h
@@ -10,6 +10,9 @@
 
 #ifndef _LINUX_MEMCONTROL_H
 #define _LINUX_MEMCONTROL_H
+
+struct dma_buf;
+
 #include <linux/cgroup.h>
 #include <linux/vm_event_item.h>
 #include <linux/hardirq.h>
@@ -41,6 +44,7 @@ enum memcg_stat_item {
 	MEMCG_ZSWAP_B,
 	MEMCG_ZSWAPPED,
 	MEMCG_ZSWAP_INCOMP,
+	MEMCG_DMABUF,
 	MEMCG_NR_STAT,
 };
 
@@ -688,6 +692,9 @@ int mem_cgroup_charge_hugetlb(struct folio *folio, struct mm_struct *mm,
 int mem_cgroup_swapin_charge_folio(struct folio *folio, unsigned short id,
 				   struct mm_struct *mm, gfp_t gfp);
 
+bool obj_cgroup_reserve_dmabuf(struct obj_cgroup *objcg, gfp_t gfp,
+			       unsigned long nr_pages);
+
 void __mem_cgroup_uncharge(struct folio *folio);
 
 /**
@@ -703,6 +710,11 @@ static inline void mem_cgroup_uncharge(struct folio *folio)
 	__mem_cgroup_uncharge(folio);
 }
 
+void obj_cgroup_cancel_dmabuf(struct obj_cgroup *objcg, unsigned long nr_pages);
+
+void mem_cgroup_commit_dmabuf(struct dma_buf *dmabuf);
+void mem_cgroup_uncharge_dmabuf(struct dma_buf *dmabuf);
+
 void __mem_cgroup_uncharge_folios(struct folio_batch *folios);
 static inline void mem_cgroup_uncharge_folios(struct folio_batch *folios)
 {
@@ -1203,10 +1215,30 @@ static inline int mem_cgroup_swapin_charge_folio(struct folio *folio,
 	return 0;
 }
 
+static inline bool obj_cgroup_reserve_dmabuf(struct obj_cgroup *objcg,
+					     gfp_t gfp,
+					     unsigned long nr_pages)
+{
+	return true;
+}
+
+static inline void obj_cgroup_cancel_dmabuf(struct obj_cgroup *objcg,
+					    unsigned long nr_pages)
+{
+}
+
+static inline void mem_cgroup_commit_dmabuf(struct dma_buf *dmabuf)
+{
+}
+
 static inline void mem_cgroup_uncharge(struct folio *folio)
 {
 }
 
+static inline void mem_cgroup_uncharge_dmabuf(struct dma_buf *dmabuf)
+{
+}
+
 static inline void mem_cgroup_uncharge_folios(struct folio_batch *folios)
 {
 }
@@ -1780,6 +1812,7 @@ void __memcg_kmem_uncharge_page(struct page *page, int order);
  */
 struct obj_cgroup *current_obj_cgroup(void);
 struct obj_cgroup *get_obj_cgroup_from_folio(const struct folio *folio);
+struct obj_cgroup *get_obj_cgroup_from_fd(int fd);
 
 static inline struct obj_cgroup *get_obj_cgroup_from_current(void)
 {
@@ -1794,6 +1827,11 @@ static inline struct obj_cgroup *get_obj_cgroup_from_current(void)
 int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size);
 void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size);
 
+bool obj_cgroup_transfer_charge(struct obj_cgroup **ptr_objcg,
+				struct obj_cgroup *new_objcg,
+				enum memcg_stat_item item,
+				unsigned int nr_pages);
+
 extern struct static_key_false memcg_bpf_enabled_key;
 static inline bool memcg_bpf_enabled(void)
 {
@@ -1887,6 +1925,24 @@ static inline struct obj_cgroup *get_obj_cgroup_from_folio(const struct folio *f
 	return NULL;
 }
 
+static inline struct obj_cgroup *get_obj_cgroup_from_fd(int fd)
+{
+	return ERR_PTR(-EOPNOTSUPP);
+}
+
+static inline struct obj_cgroup *get_obj_cgroup_from_current(void)
+{
+	return NULL;
+}
+
+static inline bool obj_cgroup_transfer_charge(struct obj_cgroup **ptr_objcg,
+					      struct obj_cgroup *new_objcg,
+					      enum memcg_stat_item item,
+					      unsigned int nr_pages)
+{
+	return true;
+}
+
 static inline bool memcg_bpf_enabled(void)
 {
 	return false;
diff --git a/include/linux/security.h b/include/linux/security.h
index 40831fab54709a..d1cd6c324ffd73 100644
--- a/include/linux/security.h
+++ b/include/linux/security.h
@@ -352,6 +352,9 @@ int security_capable(const struct cred *cred,
 		       struct user_namespace *ns,
 		       int cap,
 		       unsigned int opts);
+int security_memcg_charge_task(const struct cred *from, const struct cred *to);
+int security_memcg_charge_cgroup(const struct cred *cred,
+				 const struct file *file);
 int security_quotactl(int cmds, int type, int id, const struct super_block *sb);
 int security_quota_on(struct dentry *dentry);
 int security_syslog(int type);
@@ -710,6 +713,18 @@ static inline int security_capable(const struct cred *cred,
 	return cap_capable(cred, ns, cap, opts);
 }
 
+static inline int security_memcg_charge_task(const struct cred *from,
+					     const struct cred *to)
+{
+	return 0;
+}
+
+static inline int security_memcg_charge_cgroup(const struct cred *cred,
+					       const struct file *file)
+{
+	return 0;
+}
+
 static inline int security_quotactl(int cmds, int type, int id,
 				     const struct super_block *sb)
 {
diff --git a/include/uapi/linux/dma-buf.h b/include/uapi/linux/dma-buf.h
index e827c9d20c5d35..0aaf2e7d593b9c 100644
--- a/include/uapi/linux/dma-buf.h
+++ b/include/uapi/linux/dma-buf.h
@@ -168,6 +168,31 @@ struct dma_buf_import_sync_file {
 	__s32 fd;
 };
 
+/**
+ * struct dma_buf_transfer_charge - Transfer a dma-buf's memcg charge
+ *
+ * Any holder of a dma-buf file descriptor can perform a
+ * DMA_BUF_IOCTL_XFER_CHARGE to attribute the buffer's memory
+ * cost to a specific cgroup, or move it from one cgroup to
+ * another.  The ioctl charges the new cgroup before uncharging
+ * the old one atomically.  On failure the original charge is
+ * preserved.  If the buffer has no existing memcg charge, the
+ * ioctl returns -EOPNOTSUPP.
+ */
+struct dma_buf_transfer_charge {
+	/** @flags: Reserved, must be zero */
+	__u32 flags; /* unused for now */
+	/**
+	 * @charge_fd: File descriptor identifying the target cgroup.
+	 *
+	 * May be either a pidfd, in which case the charge moves to the
+	 * memory cgroup of the referenced process, or a cgroupfd obtained
+	 * by opening a cgroup v2 directory, in which case the charge moves
+	 * directly to that cgroup's memory controller.
+	 */
+	__u32 charge_fd;
+};
+
 #define DMA_BUF_BASE		'b'
 #define DMA_BUF_IOCTL_SYNC	_IOW(DMA_BUF_BASE, 0, struct dma_buf_sync)
 
@@ -179,5 +204,6 @@ struct dma_buf_import_sync_file {
 #define DMA_BUF_SET_NAME_B	_IOW(DMA_BUF_BASE, 1, __u64)
 #define DMA_BUF_IOCTL_EXPORT_SYNC_FILE	_IOWR(DMA_BUF_BASE, 2, struct dma_buf_export_sync_file)
 #define DMA_BUF_IOCTL_IMPORT_SYNC_FILE	_IOW(DMA_BUF_BASE, 3, struct dma_buf_import_sync_file)
+#define DMA_BUF_IOCTL_XFER_CHARGE	_IOW(DMA_BUF_BASE, 4, struct dma_buf_transfer_charge)
 
 #endif
diff --git a/include/uapi/linux/dma-heap.h b/include/uapi/linux/dma-heap.h
index a4cf716a49fa68..bfcd1c25bc7ea0 100644
--- a/include/uapi/linux/dma-heap.h
+++ b/include/uapi/linux/dma-heap.h
@@ -29,6 +29,11 @@
  *			handle to the allocated dma-buf
  * @fd_flags:		file descriptor flags used when allocating
  * @heap_flags:		flags passed to heap
+ * @charge_fd:		optional pidfd or cgroupfd whose cgroup should be
+ *			charged for this allocation; 0 means charge the calling
+ *			process's cgroup when the mem_accounting module parameter
+ *			is enabled, or skip charging otherwise
+ * @__padding:		reserved, must be zero
  *
  * Provided by userspace as an argument to the ioctl
  */
@@ -37,6 +42,8 @@ struct dma_heap_allocation_data {
 	__u32 fd;
 	__u32 fd_flags;
 	__u64 heap_flags;
+	__u32 charge_fd;
+	__u32 __padding;
 };
 
 #define DMA_HEAP_IOC_MAGIC		'H'
diff --git a/mm/memcontrol.c b/mm/memcontrol.c
index a05d9a8baa1b6b..693f0b2877bf16 100644
--- a/mm/memcontrol.c
+++ b/mm/memcontrol.c
@@ -49,6 +49,7 @@
 #include <linux/slab.h>
 #include <linux/swapops.h>
 #include <linux/spinlock.h>
+#include <linux/file.h>
 #include <linux/fs.h>
 #include <linux/seq_file.h>
 #include <linux/vmpressure.h>
@@ -59,6 +60,7 @@
 #include <linux/lockdep.h>
 #include <linux/resume_user_mode.h>
 #include <linux/psi.h>
+#include <linux/security.h>
 #include <linux/seq_buf.h>
 #include <linux/sched/isolation.h>
 #include <linux/kmemleak.h>
@@ -70,6 +72,7 @@
 #include <net/ip.h>
 #include "slab.h"
 #include "memcontrol-v1.h"
+#include <linux/dma-buf.h>
 
 #include <linux/uaccess.h>
 
@@ -459,6 +462,7 @@ static const unsigned int memcg_stat_items[] = {
 	MEMCG_ZSWAP_B,
 	MEMCG_ZSWAPPED,
 	MEMCG_ZSWAP_INCOMP,
+	MEMCG_DMABUF,
 };
 
 #define NR_MEMCG_NODE_STAT_ITEMS ARRAY_SIZE(memcg_node_stat_items)
@@ -1644,6 +1648,7 @@ static const struct memory_stat memory_stats[] = {
 #ifdef CONFIG_HUGETLB_PAGE
 	{ "hugetlb",			NR_HUGETLB			},
 #endif
+	{ "dmabuf",			MEMCG_DMABUF			},
 
 	/* The memory events */
 	{ "workingset_refault_anon",	WORKINGSET_REFAULT_ANON		},
@@ -3165,6 +3170,163 @@ struct obj_cgroup *get_obj_cgroup_from_folio(const struct folio *folio)
 	return objcg;
 }
 
+/*
+ * Charging outside the caller's own memcg subtree can escape its limits
+ * or push reclaim and OOM onto other cgroups.
+ */
+static bool mem_cgroup_may_charge(struct mem_cgroup *memcg)
+{
+	struct mem_cgroup *self = get_mem_cgroup_from_current();
+	bool ret = mem_cgroup_is_descendant(memcg, self);
+
+	mem_cgroup_put(self);
+	return ret || capable(CAP_SYS_RESOURCE);
+}
+
+/**
+ * get_obj_cgroup_from_fd - resolve an object cgroup from a cgroupfd or pidfd
+ * @fd: file descriptor (cgroupfd or pidfd)
+ *
+ * Tries @fd as a cgroupfd first; if that fails, tries it as a pidfd. Only
+ * cgroup2 directories are accepted as cgroupfds, any other fd is tried as a
+ * pidfd.
+ *
+ * Resolving a memcg outside the caller's own subtree requires CAP_SYS_RESOURCE.
+ *
+ * On success returns a referenced objcg pointer. On failure returns
+ * an ERR_PTR.
+ */
+struct obj_cgroup *get_obj_cgroup_from_fd(int fd)
+{
+	struct cgroup_subsys_state *css;
+	const struct cred *tcred;
+	struct obj_cgroup *objcg;
+	struct mem_cgroup *memcg;
+	struct task_struct *task;
+	unsigned int pidfd_flags;
+	int ret;
+
+	if (mem_cgroup_disabled())
+		return ERR_PTR(-EOPNOTSUPP);
+
+	CLASS(fd_raw, f)(fd);
+	if (fd_empty(f))
+		return ERR_PTR(-EBADF);
+
+	css = css_tryget_online_from_dir(fd_file(f)->f_path.dentry,
+					 &memory_cgrp_subsys);
+	if (!IS_ERR(css) && !cgroup_on_dfl(css->cgroup)) {
+		css_put(css);
+		css = ERR_PTR(-EBADF);
+	}
+
+	if (!IS_ERR(css)) {
+		/* fd is a cgroupfd */
+		ret = security_memcg_charge_cgroup(current_cred(), fd_file(f));
+		if (ret) {
+			css_put(css);
+			return ERR_PTR(ret);
+		}
+	} else {
+		if (PTR_ERR(css) != -EBADF)
+			return ERR_CAST(css);
+
+		/* fd is a pidfd */
+		task = pidfd_get_task(fd, &pidfd_flags);
+		if (IS_ERR(task))
+			return ERR_CAST(task);
+
+		tcred = get_task_cred(task);
+		ret = security_memcg_charge_task(current_cred(), tcred);
+		put_cred(tcred);
+		if (ret) {
+			put_task_struct(task);
+			return ERR_PTR(ret);
+		}
+
+		rcu_read_lock();
+		css = task_css(task, memory_cgrp_id);
+		put_task_struct(task);
+		if (!css || !css_tryget_online(css)) {
+			rcu_read_unlock();
+			return ERR_PTR(-ENOENT);
+		}
+		rcu_read_unlock();
+	}
+
+	memcg = mem_cgroup_from_css(css);
+	if (!mem_cgroup_may_charge(memcg)) {
+		mem_cgroup_put(memcg);
+		return ERR_PTR(-EPERM);
+	}
+
+	objcg = get_obj_cgroup_from_memcg(memcg, numa_node_id());
+	mem_cgroup_put(memcg);
+
+	if (!objcg)
+		return ERR_PTR(-ENOENT);
+
+	return objcg;
+}
+
+/**
+ * obj_cgroup_transfer_charge - move a charge between object cgroups
+ * @ptr_objcg: pointer to the object cgroup to transfer from
+ * @new_objcg: target object cgroup; caller must hold a reference
+ * @item: memcg stat counter to adjust; must not be a node stat
+ * @nr_pages: number of pages to transfer
+ *
+ * Transfers @nr_pages of charge from *@ptr_objcg to @new_objcg and, on
+ * success, stores @new_objcg in *@ptr_objcg. Does nothing if both resolve
+ * to the same memcg; *@ptr_objcg is left untouched in that case.
+ *
+ * Updates to *@ptr_objcg must be serialized by the caller.
+ * Returns %true on success, %false if the charge against @new_objcg
+ * failed.
+ */
+bool obj_cgroup_transfer_charge(struct obj_cgroup **ptr_objcg,
+				struct obj_cgroup *new_objcg,
+				enum memcg_stat_item item,
+				unsigned int nr_pages)
+{
+	struct obj_cgroup *old_objcg = *ptr_objcg;
+	struct mem_cgroup *old_memcg = NULL, *new_memcg;
+	bool ret = true;
+
+	if (!new_objcg || mem_cgroup_disabled())
+		return true;
+
+	new_memcg = get_mem_cgroup_from_objcg(new_objcg);
+	if (old_objcg)
+		old_memcg = get_mem_cgroup_from_objcg(old_objcg);
+
+	if (old_memcg == new_memcg)
+		goto out;
+
+	if (try_charge(new_memcg, GFP_KERNEL, nr_pages)) {
+		ret = false;
+		goto out;
+	}
+
+	mod_memcg_state(new_memcg, item, nr_pages);
+
+	if (old_objcg) {
+		/* Uncharge old cgroup */
+		mod_memcg_state(old_memcg, item, -nr_pages);
+		if (!mem_cgroup_is_root(old_memcg))
+			refill_stock(old_memcg, nr_pages);
+	}
+
+	obj_cgroup_get(new_objcg);
+	*ptr_objcg = new_objcg;
+	obj_cgroup_put(old_objcg);
+
+out:
+	mem_cgroup_put(new_memcg);
+	mem_cgroup_put(old_memcg);
+	return ret;
+}
+
 #ifdef CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC
 static inline void account_kmem_nmi_safe(struct mem_cgroup *memcg, int val)
 {
@@ -5821,6 +5983,115 @@ void mem_cgroup_flush_workqueue(void)
 	flush_workqueue(memcg_wq);
 }
 
+/**
+ * obj_cgroup_reserve_dmabuf - charge an object cgroup for a dma-buf allocation
+ * @objcg: object cgroup to charge (may be %NULL)
+ * @gfp_mask: reclaim mode
+ * @nr_pages: number of pages to charge
+ *
+ * Charges @nr_pages against @objcg. Call this before allocating pages so
+ * the cgroup limit is enforced up front. On success the caller must
+ * finalize the charge with the MEMCG_DMABUF stat update, or call
+ * obj_cgroup_cancel_dmabuf() to undo it.
+ *
+ * @nr_pages is derived from the buffer size, which may be controlled by
+ * userspace, so it is taken as unsigned long and rejected above what
+ * a single memcg charge can account.
+ *
+ * Returns %true on success, %false if @nr_pages is too large or the
+ * charge would exceed the limit.
+ */
+bool obj_cgroup_reserve_dmabuf(struct obj_cgroup *objcg, gfp_t gfp_mask,
+			       unsigned long nr_pages)
+{
+	struct mem_cgroup *memcg;
+	int ret;
+
+	if (!objcg || mem_cgroup_disabled())
+		return true;
+
+	/* a single memcg charge accounts at most INT_MAX pages */
+	if (nr_pages > INT_MAX)
+		return false;
+
+	memcg = get_mem_cgroup_from_objcg(objcg);
+	ret = try_charge(memcg, gfp_mask, nr_pages);
+	mem_cgroup_put(memcg);
+	return !ret;
+}
+EXPORT_SYMBOL_GPL(obj_cgroup_reserve_dmabuf);
+
+/**
+ * obj_cgroup_cancel_dmabuf - undo a dma-buf charge
+ * @objcg: object cgroup to uncharge (may be %NULL)
+ * @nr_pages: same value passed to obj_cgroup_reserve_dmabuf()
+ *
+ * Returns @nr_pages of charge to @objcg. Use when the allocation fails
+ * after obj_cgroup_reserve_dmabuf().
+ */
+void obj_cgroup_cancel_dmabuf(struct obj_cgroup *objcg, unsigned long nr_pages)
+{
+	struct mem_cgroup *memcg;
+
+	if (!objcg)
+		return;
+
+	memcg = get_mem_cgroup_from_objcg(objcg);
+	if (!mem_cgroup_is_root(memcg))
+		refill_stock(memcg, nr_pages);
+	mem_cgroup_put(memcg);
+}
+EXPORT_SYMBOL_GPL(obj_cgroup_cancel_dmabuf);
+
+/**
+ * mem_cgroup_commit_dmabuf - finalize a dma-buf charge
+ * @dmabuf: buffer whose charge is being finalized
+ *
+ * Adds @dmabuf's size to the %MEMCG_DMABUF stat of the cgroup its object
+ * cgroup currently resolves to. Call after obj_cgroup_reserve_dmabuf()
+ * succeeded and the buffer is about to be exported. Safe to call when
+ * @dmabuf->objcg is %NULL.
+ */
+void mem_cgroup_commit_dmabuf(struct dma_buf *dmabuf)
+{
+	struct mem_cgroup *memcg;
+
+	if (!dmabuf->objcg)
+		return;
+
+	memcg = get_mem_cgroup_from_objcg(dmabuf->objcg);
+	mod_memcg_state(memcg, MEMCG_DMABUF,
+			PAGE_ALIGN(dmabuf->size) >> PAGE_SHIFT);
+	mem_cgroup_put(memcg);
+}
+
+/**
+ * mem_cgroup_uncharge_dmabuf - uncharge a dma-buf from its object cgroup
+ * @dmabuf: buffer to uncharge
+ *
+ * Reverses a finalized dma-buf charge. Drops the object cgroup
+ * reference stored in @dmabuf->objcg and clears the pointer.
+ * Safe to call when @dmabuf->objcg is %NULL.
+ */
+void mem_cgroup_uncharge_dmabuf(struct dma_buf *dmabuf)
+{
+	struct obj_cgroup *objcg = dmabuf->objcg;
+	struct mem_cgroup *memcg;
+	unsigned long nr_pages;
+
+	if (!objcg)
+		return;
+
+	memcg = get_mem_cgroup_from_objcg(objcg);
+	nr_pages = PAGE_ALIGN(dmabuf->size) >> PAGE_SHIFT;
+	mod_memcg_state(memcg, MEMCG_DMABUF, -nr_pages);
+	if (!mem_cgroup_is_root(memcg))
+		refill_stock(memcg, nr_pages);
+	mem_cgroup_put(memcg);
+	obj_cgroup_put(objcg);
+	dmabuf->objcg = NULL;
+}
+
 static int __init cgroup_memory(char *s)
 {
 	char *token;
diff --git a/security/security.c b/security/security.c
index f6583d50739592..925b6c00305943 100644
--- a/security/security.c
+++ b/security/security.c
@@ -674,6 +674,41 @@ int security_capable(const struct cred *cred,
 	return call_int_hook(capable, cred, ns, cap, opts);
 }
 
+/**
+ * security_memcg_charge_task() - Check if cross-cgroup memory charging is allowed
+ * @from: credentials of the process requesting the charge
+ * @to: credentials of the process to charge
+ *
+ * Check whether the process with credentials @from is allowed to charge
+ * memory to the cgroup of the process with credentials @to.
+ *
+ * Return: Returns 0 if permission is granted.
+ */
+int security_memcg_charge_task(const struct cred *from, const struct cred *to)
+{
+	return call_int_hook(memcg_charge_task, from, to);
+}
+
+/**
+ * security_memcg_charge_cgroup() - Check if charging memory to a cgroup is allowed
+ * @cred: credentials of the process requesting the charge
+ * @file: open file of the cgroup directory to charge
+ *
+ * Check whether the process with credentials @cred is allowed to charge
+ * memory to the cgroup referenced by @file. Called when userspace passes a
+ * cgroupfd to identify the charge target instead of a pidfd. @file is the
+ * file the cgroup was resolved from, so the check applies to the object
+ * that is actually charged. It must have been already validated by the
+ * caller.
+ *
+ * Return: Returns 0 if permission is granted.
+ */
+int security_memcg_charge_cgroup(const struct cred *cred,
+				 const struct file *file)
+{
+	return call_int_hook(memcg_charge_cgroup, cred, file);
+}
+
 /**
  * security_quotactl() - Check if a quotactl() syscall is allowed for this fs
  * @cmds: commands
diff --git a/security/selinux/hooks.c b/security/selinux/hooks.c
index 6168dd5f91c227..fcf0b03a588dfe 100644
--- a/security/selinux/hooks.c
+++ b/security/selinux/hooks.c
@@ -2204,6 +2204,21 @@ static int selinux_capable(const struct cred *cred, struct user_namespace *ns,
 	return cred_has_capability(cred, cap, opts, ns == &init_user_ns);
 }
 
+static int selinux_memcg_charge_task(const struct cred *from, const struct cred *to)
+{
+	return avc_has_perm(cred_sid(from), cred_sid(to),
+			    SECCLASS_PROCESS2, PROCESS2__CHARGE_TO, NULL);
+}
+
+static int selinux_memcg_charge_cgroup(const struct cred *cred,
+				       const struct file *file)
+{
+	struct inode_security_struct *isec = inode_security(file_inode(file));
+
+	return avc_has_perm(cred_sid(cred), isec->sid, SECCLASS_CGROUP,
+			    CGROUP__CHARGE_TO, NULL);
+}
+
 static int selinux_quotactl(int cmds, int type, int id, const struct super_block *sb)
 {
 	const struct cred *cred = current_cred();
@@ -7681,6 +7696,8 @@ static struct security_hook_list selinux_hooks[] __ro_after_init = {
 	LSM_HOOK_INIT(capget, selinux_capget),
 	LSM_HOOK_INIT(capset, selinux_capset),
 	LSM_HOOK_INIT(capable, selinux_capable),
+	LSM_HOOK_INIT(memcg_charge_task, selinux_memcg_charge_task),
+	LSM_HOOK_INIT(memcg_charge_cgroup, selinux_memcg_charge_cgroup),
 	LSM_HOOK_INIT(quotactl, selinux_quotactl),
 	LSM_HOOK_INIT(quota_on, selinux_quota_on),
 	LSM_HOOK_INIT(syslog, selinux_syslog),
diff --git a/security/selinux/include/classmap.h b/security/selinux/include/classmap.h
index 90cb61b1642563..32dd95de509a04 100644
--- a/security/selinux/include/classmap.h
+++ b/security/selinux/include/classmap.h
@@ -60,7 +60,7 @@ const struct security_class_mapping secclass_map[] = {
 	    "siginh",	    "setrlimit",     "rlimitinh",   "dyntransition",
 	    "setcurrent",   "execmem",	     "execstack",   "execheap",
 	    "setkeycreate", "setsockcreate", "getrlimit",   NULL } },
-	{ "process2", { "nnp_transition", "nosuid_transition", NULL } },
+	{ "process2", { "nnp_transition", "nosuid_transition", "charge_to", NULL } },
 	{ "system",
 	  { "ipc_info", "syslog_read", "syslog_mod", "syslog_console",
 	    "module_request", "module_load", "firmware_load",
@@ -181,6 +181,7 @@ const struct security_class_mapping secclass_map[] = {
 	{ "user_namespace", { "create", NULL } },
 	{ "memfd_file",
 	  { COMMON_FILE_PERMS, "execute_no_trans", "entrypoint", NULL } },
+	{ "cgroup", { "charge_to", NULL } },
 	/* last one */ { NULL, {} }
 };
 
diff --git a/tools/testing/selftests/cgroup/Makefile b/tools/testing/selftests/cgroup/Makefile
index e01584c2189ac1..9edfc9f1de5c43 100644
--- a/tools/testing/selftests/cgroup/Makefile
+++ b/tools/testing/selftests/cgroup/Makefile
@@ -1,5 +1,5 @@
 # SPDX-License-Identifier: GPL-2.0
-CFLAGS += -Wall -pthread
+CFLAGS += -Wall -pthread $(KHDR_INCLUDES)
 
 all: ${HELPER_PROGS}
 
diff --git a/tools/testing/selftests/cgroup/test_memcontrol.c b/tools/testing/selftests/cgroup/test_memcontrol.c
index bb673012dcf089..f612726bd9af7e 100644
--- a/tools/testing/selftests/cgroup/test_memcontrol.c
+++ b/tools/testing/selftests/cgroup/test_memcontrol.c
@@ -18,8 +18,15 @@
 #include <netdb.h>
 #include <errno.h>
 #include <sys/mman.h>
+#include <sys/prctl.h>
 #include <sys/sysinfo.h>
 
+#include <linux/dma-buf.h>
+#include <linux/dma-heap.h>
+#include <signal.h>
+#include <sys/ioctl.h>
+
+#include "../pidfd/pidfd.h"
 #include "kselftest.h"
 #include "cgroup_util.h"
 
@@ -27,6 +34,13 @@
 #define MEMCG_FLUSH_BYTES	\
 	(2 * sysconf(_SC_PAGESIZE) * MEMCG_CHARGE_BATCH * get_nprocs())
 
+#define DMA_HEAP_SYSTEM		"/dev/dma_heap/system"
+#define ONE_MEG			(1024 * 1024)
+
+#define MEMCG_SOCKSTAT_WAIT_RETRIES        30
+#define MEMCG_DMABUF_WAIT_RETRIES          30
+#define MEMCG_DMABUF_DEAD_WAIT_RETRIES     80
+
 static bool has_localevents;
 static bool has_recursiveprot;
 static int page_size;
@@ -1797,6 +1811,417 @@ static int test_memcg_inotify_delete_dir(const char *root)
 	return ret;
 }
 
+static int memcg_dmabuf_child(const char *cgroup, void *arg)
+{
+	pid_t *parent_pid = arg;
+
+	prctl(PR_SET_PDEATHSIG, SIGKILL);
+	if (getppid() != *parent_pid)
+		return 0;
+
+	pause();
+	return 0;
+}
+
+/*
+ * This test allocates a dma-buf via DMA_HEAP_IOCTL_ALLOC with a pidfd
+ * pointing to a child process in a separate cgroup, then checks that
+ * memory.stat[dmabuf] in the child's cgroup rises by the allocation size
+ * and returns to zero after the buffer fd is closed.
+ */
+static int test_memcg_dmabuf(const char *root)
+{
+	char *parent = NULL, *child_cg = NULL;
+	int ret = KSFT_FAIL;
+	int heap_fd = -1, dmabuf_fd = -1, pidfd = -1;
+	pid_t child_pid, parent_pid = getpid();
+	int child_status;
+	long dmabuf_stat;
+	struct dma_heap_allocation_data alloc = {
+		.len      = ONE_MEG,
+		.fd_flags = O_RDWR | O_CLOEXEC,
+	};
+
+	if (access(DMA_HEAP_SYSTEM, R_OK | W_OK)) {
+		ret = KSFT_SKIP;
+		goto cleanup;
+	}
+
+	parent = cg_name(root, "dmabuf_memcg_test");
+	if (!parent)
+		goto cleanup;
+
+	if (cg_create(parent))
+		goto cleanup_parent;
+
+	if (cg_write(parent, "cgroup.subtree_control", "+memory"))
+		goto cleanup_parent;
+
+	child_cg = cg_name(parent, "child");
+	if (!child_cg)
+		goto cleanup_parent;
+
+	if (cg_create(child_cg))
+		goto cleanup_parent;
+
+	child_pid = cg_run_nowait(child_cg, memcg_dmabuf_child, &parent_pid);
+	if (child_pid < 0)
+		goto cleanup_child;
+
+	if (cg_wait_for_proc_count(child_cg, 1))
+		goto cleanup_kill;
+
+	pidfd = sys_pidfd_open(child_pid, 0);
+	if (pidfd < 0) {
+		ret = KSFT_SKIP;
+		goto cleanup_kill;
+	}
+
+	heap_fd = open(DMA_HEAP_SYSTEM, O_RDWR);
+	if (heap_fd < 0) {
+		ret = KSFT_SKIP;
+		goto cleanup_pidfd;
+	}
+
+	alloc.charge_fd = (__u32)pidfd;
+	if (ioctl(heap_fd, DMA_HEAP_IOCTL_ALLOC, &alloc) < 0) {
+		if (errno == EINVAL || errno == ENOTTY || errno == EOPNOTSUPP)
+			ret = KSFT_SKIP;
+		goto cleanup_heap;
+	}
+	dmabuf_fd = (int)alloc.fd;
+
+	dmabuf_stat = cg_read_key_long(child_cg, "memory.stat", "dmabuf ");
+	if (dmabuf_stat == -1) {
+		ret = KSFT_SKIP;
+		goto cleanup_dmabuf;
+	}
+	if (dmabuf_stat != ONE_MEG)
+		dmabuf_stat = cg_read_key_long_poll(child_cg, "memory.stat",
+						    "dmabuf ", ONE_MEG,
+						    MEMCG_DMABUF_WAIT_RETRIES,
+						    DEFAULT_WAIT_INTERVAL_US);
+	if (dmabuf_stat != ONE_MEG) {
+		fprintf(stderr, "Expected dmabuf stat %d, got %ld\n",
+			ONE_MEG, dmabuf_stat);
+		goto cleanup_dmabuf;
+	}
+
+	close(dmabuf_fd);
+	dmabuf_fd = -1;
+
+	dmabuf_stat = cg_read_key_long_poll(child_cg, "memory.stat",
+					    "dmabuf ", 0,
+					    MEMCG_DMABUF_WAIT_RETRIES,
+					    DEFAULT_WAIT_INTERVAL_US);
+	if (dmabuf_stat != 0) {
+		fprintf(stderr, "Expected dmabuf stat 0 after close, got %ld\n",
+			dmabuf_stat);
+		goto cleanup_heap;
+	}
+
+	ret = KSFT_PASS;
+
+cleanup_dmabuf:
+	if (dmabuf_fd >= 0)
+		close(dmabuf_fd);
+cleanup_heap:
+	close(heap_fd);
+cleanup_pidfd:
+	close(pidfd);
+cleanup_kill:
+	kill(child_pid, SIGTERM);
+	waitpid(child_pid, &child_status, 0);
+cleanup_child:
+	cg_destroy(child_cg);
+	free(child_cg);
+cleanup_parent:
+	cg_destroy(parent);
+	free(parent);
+cleanup:
+	return ret;
+}
+
+/*
+ * Allocate a dma-buf in cgroup A, set memory.max on cgroup B below the
+ * buffer size, then attempt DMA_BUF_IOCTL_XFER_CHARGE to B. The transfer
+ * must fail with ENOMEM and the charge must remain in A.
+ */
+static int test_memcg_dmabuf_xfer_at_limit(const char *root)
+{
+	char *parent = NULL, *cg_a = NULL, *cg_b = NULL;
+	int ret = KSFT_FAIL;
+	int heap_fd = -1, dmabuf_fd = -1, cg_b_fd = -1;
+	pid_t child_pid, parent_pid = getpid();
+	int child_status;
+	long stat_a;
+	struct dma_heap_allocation_data alloc = {
+		.len      = ONE_MEG,
+		.fd_flags = O_RDWR | O_CLOEXEC,
+	};
+	struct dma_buf_transfer_charge xfer = { 0 };
+
+	if (access(DMA_HEAP_SYSTEM, R_OK | W_OK)) {
+		ret = KSFT_SKIP;
+		goto cleanup;
+	}
+
+	parent = cg_name(root, "dmabuf_xfer_limit_test");
+	if (!parent)
+		goto cleanup;
+
+	if (cg_create(parent))
+		goto cleanup_parent;
+
+	if (cg_write(parent, "cgroup.subtree_control", "+memory"))
+		goto cleanup_parent;
+
+	cg_a = cg_name(parent, "cg_a");
+	cg_b = cg_name(parent, "cg_b");
+	if (!cg_a || !cg_b)
+		goto cleanup_cgs;
+
+	if (cg_create(cg_a) || cg_create(cg_b))
+		goto cleanup_cgs;
+
+	if (cg_write(cg_b, "memory.max", "524288"))
+		goto cleanup_cgs;
+
+	child_pid = cg_run_nowait(cg_a, memcg_dmabuf_child, &parent_pid);
+	if (child_pid < 0)
+		goto cleanup_cgs;
+
+	if (cg_wait_for_proc_count(cg_a, 1))
+		goto cleanup_kill;
+
+	heap_fd = open(DMA_HEAP_SYSTEM, O_RDWR);
+	if (heap_fd < 0) {
+		ret = KSFT_SKIP;
+		goto cleanup_kill;
+	}
+
+	alloc.charge_fd = (__u32)sys_pidfd_open(child_pid, 0);
+	if ((int)alloc.charge_fd < 0) {
+		ret = KSFT_SKIP;
+		goto cleanup_heap;
+	}
+
+	if (ioctl(heap_fd, DMA_HEAP_IOCTL_ALLOC, &alloc) < 0) {
+		close(alloc.charge_fd);
+		goto cleanup_heap;
+	}
+	close(alloc.charge_fd);
+	dmabuf_fd = (int)alloc.fd;
+
+	stat_a = cg_read_key_long(cg_a, "memory.stat", "dmabuf ");
+	if (stat_a == -1) {
+		ret = KSFT_SKIP;
+		goto cleanup_dmabuf;
+	}
+	if (stat_a != ONE_MEG)
+		stat_a = cg_read_key_long_poll(cg_a, "memory.stat",
+					       "dmabuf ", ONE_MEG,
+					       MEMCG_DMABUF_WAIT_RETRIES,
+					       DEFAULT_WAIT_INTERVAL_US);
+	if (stat_a != ONE_MEG) {
+		fprintf(stderr, "Charge not in A after alloc: expected %d, got %ld\n",
+			ONE_MEG, stat_a);
+		goto cleanup_dmabuf;
+	}
+
+	cg_b_fd = open(cg_b, O_RDONLY | O_DIRECTORY);
+	if (cg_b_fd < 0)
+		goto cleanup_dmabuf;
+
+	xfer.charge_fd = (__u32)cg_b_fd;
+	if (ioctl(dmabuf_fd, DMA_BUF_IOCTL_XFER_CHARGE, &xfer) == 0) {
+		fprintf(stderr, "xfer_charge should have failed at limit\n");
+		goto cleanup_cgfd;
+	}
+	if (errno != ENOMEM) {
+		fprintf(stderr, "Expected ENOMEM, got %s\n", strerror(errno));
+		goto cleanup_cgfd;
+	}
+
+	stat_a = cg_read_key_long_poll(cg_a, "memory.stat",
+				       "dmabuf ", ONE_MEG,
+				       MEMCG_DMABUF_WAIT_RETRIES,
+				       DEFAULT_WAIT_INTERVAL_US);
+	if (stat_a != ONE_MEG) {
+		fprintf(stderr, "Charge leaked from A: expected %d, got %ld\n",
+			ONE_MEG, stat_a);
+		goto cleanup_cgfd;
+	}
+
+	ret = KSFT_PASS;
+
+cleanup_cgfd:
+	close(cg_b_fd);
+cleanup_dmabuf:
+	if (dmabuf_fd >= 0)
+		close(dmabuf_fd);
+cleanup_heap:
+	close(heap_fd);
+cleanup_kill:
+	kill(child_pid, SIGTERM);
+	waitpid(child_pid, &child_status, 0);
+cleanup_cgs:
+	if (cg_a) {
+		cg_destroy(cg_a);
+		free(cg_a);
+	}
+	if (cg_b) {
+		cg_destroy(cg_b);
+		free(cg_b);
+	}
+cleanup_parent:
+	cg_destroy(parent);
+	free(parent);
+cleanup:
+	return ret;
+}
+
+/*
+ * Allocate a dma-buf charged to a cgroup, then remove that cgroup while
+ * the buffer is still open. The charge is held by an object cgroup,
+ * which is reparented, so the removed cgroup must be released instead of
+ * lingering as a dying descendant until the buffer is closed.
+ */
+static int test_memcg_dmabuf_dead_cgroup(const char *root)
+{
+	char *parent = NULL, *child_cg = NULL;
+	int ret = KSFT_FAIL;
+	int heap_fd = -1, dmabuf_fd = -1, cg_fd = -1;
+	long dmabuf_stat, dying;
+	struct dma_heap_allocation_data alloc = {
+		.len      = ONE_MEG,
+		.fd_flags = O_RDWR | O_CLOEXEC,
+	};
+
+	if (access(DMA_HEAP_SYSTEM, R_OK | W_OK)) {
+		ret = KSFT_SKIP;
+		goto cleanup;
+	}
+
+	parent = cg_name(root, "dmabuf_dead_cgroup_test");
+	if (!parent)
+		goto cleanup;
+
+	if (cg_create(parent))
+		goto cleanup_parent;
+
+	if (cg_write(parent, "cgroup.subtree_control", "+memory"))
+		goto cleanup_parent;
+
+	child_cg = cg_name(parent, "child");
+	if (!child_cg)
+		goto cleanup_parent;
+
+	if (cg_create(child_cg))
+		goto cleanup_child;
+
+	heap_fd = open(DMA_HEAP_SYSTEM, O_RDWR);
+	if (heap_fd < 0) {
+		ret = KSFT_SKIP;
+		goto cleanup_child;
+	}
+
+	cg_fd = open(child_cg, O_RDONLY | O_DIRECTORY);
+	if (cg_fd < 0)
+		goto cleanup_heap;
+
+	alloc.charge_fd = (__u32)cg_fd;
+	if (ioctl(heap_fd, DMA_HEAP_IOCTL_ALLOC, &alloc) < 0) {
+		if (errno == EINVAL || errno == ENOTTY || errno == EOPNOTSUPP)
+			ret = KSFT_SKIP;
+		goto cleanup_cgfd;
+	}
+	/* The buffer holds the charge; the fd must not hold the cgroup. */
+	close(cg_fd);
+	cg_fd = -1;
+	dmabuf_fd = (int)alloc.fd;
+
+	dmabuf_stat = cg_read_key_long(child_cg, "memory.stat", "dmabuf ");
+	if (dmabuf_stat == -1) {
+		ret = KSFT_SKIP;
+		goto cleanup_dmabuf;
+	}
+	if (dmabuf_stat != ONE_MEG)
+		dmabuf_stat = cg_read_key_long_poll(child_cg, "memory.stat",
+						    "dmabuf ", ONE_MEG,
+						    MEMCG_DMABUF_WAIT_RETRIES,
+						    DEFAULT_WAIT_INTERVAL_US);
+	if (dmabuf_stat != ONE_MEG) {
+		fprintf(stderr, "Expected dmabuf stat %d, got %ld\n",
+			ONE_MEG, dmabuf_stat);
+		goto cleanup_dmabuf;
+	}
+
+	if (cg_destroy(child_cg)) {
+		fprintf(stderr, "Failed to remove charged cgroup\n");
+		goto cleanup_dmabuf;
+	}
+
+	dying = cg_read_key_long_poll(parent, "cgroup.stat",
+				      "nr_dying_descendants ", 0,
+				      MEMCG_DMABUF_DEAD_WAIT_RETRIES,
+				      DEFAULT_WAIT_INTERVAL_US);
+	if (dying) {
+		fprintf(stderr, "Removed cgroup still dying with buffer open\n");
+		goto cleanup_dmabuf;
+	}
+
+	/* The charge must have moved to the parent with the cgroup. */
+	dmabuf_stat = cg_read_key_long(parent, "memory.stat", "dmabuf ");
+	if (dmabuf_stat != ONE_MEG)
+		dmabuf_stat = cg_read_key_long_poll(parent, "memory.stat",
+						    "dmabuf ", ONE_MEG,
+						    MEMCG_DMABUF_WAIT_RETRIES,
+						    DEFAULT_WAIT_INTERVAL_US);
+	if (dmabuf_stat != ONE_MEG) {
+		fprintf(stderr, "Charge not in parent after removal: expected %d, got %ld\n",
+			ONE_MEG, dmabuf_stat);
+		goto cleanup_dmabuf;
+	}
+
+	/* Uncharge through the reparented object cgroup. */
+	close(dmabuf_fd);
+	dmabuf_fd = -1;
+
+	dmabuf_stat = cg_read_key_long(parent, "memory.stat", "dmabuf ");
+	if (dmabuf_stat != 0)
+		dmabuf_stat = cg_read_key_long_poll(parent, "memory.stat",
+						    "dmabuf ", 0,
+						    MEMCG_DMABUF_WAIT_RETRIES,
+						    DEFAULT_WAIT_INTERVAL_US);
+	if (dmabuf_stat != 0) {
+		fprintf(stderr, "Expected dmabuf stat 0 after close, got %ld\n",
+			dmabuf_stat);
+		goto cleanup_heap;
+	}
+
+	ret = KSFT_PASS;
+
+cleanup_dmabuf:
+	if (dmabuf_fd >= 0)
+		close(dmabuf_fd);
+cleanup_cgfd:
+	if (cg_fd >= 0)
+		close(cg_fd);
+cleanup_heap:
+	close(heap_fd);
+cleanup_child:
+	if (child_cg) {
+		cg_destroy(child_cg);
+		free(child_cg);
+	}
+cleanup_parent:
+	cg_destroy(parent);
+	free(parent);
+cleanup:
+	return ret;
+}
+
 #define T(x) { x, #x }
 struct memcg_test {
 	int (*fn)(const char *root);
@@ -1818,13 +2243,20 @@ struct memcg_test {
 	T(test_memcg_oom_group_score_events),
 	T(test_memcg_inotify_delete_file),
 	T(test_memcg_inotify_delete_dir),
+	T(test_memcg_dmabuf),
+	T(test_memcg_dmabuf_xfer_at_limit),
+	T(test_memcg_dmabuf_dead_cgroup),
 };
 #undef T
 
 int main(int argc, char **argv)
 {
 	char root[PATH_MAX];
-	int i, proc_status;
+	int i, proc_status, count = ARRAY_SIZE(tests);
+	const char *filter = NULL;
+
+	if (argc > 1)
+		filter = argv[1];
 
 	page_size = sysconf(_SC_PAGE_SIZE);
 	if (page_size <= 0)
@@ -1855,8 +2287,19 @@ int main(int argc, char **argv)
 		ksft_exit_skip("Failed to query cgroup mount option\n");
 	has_localevents = proc_status;
 
-	ksft_set_plan(ARRAY_SIZE(tests));
+	if (filter) {
+		count = 0;
+		for (i = 0; i < ARRAY_SIZE(tests); i++) {
+			if (!strcmp(tests[i].name, filter))
+				count++;
+		}
+		if (!count)
+			ksft_exit_fail_msg("unknown test '%s'\n", filter);
+	}
+	ksft_set_plan(count);
 	for (i = 0; i < ARRAY_SIZE(tests); i++) {
+		if (filter && strcmp(tests[i].name, filter))
+			continue;
 		switch (tests[i].fn(root)) {
 		case KSFT_PASS:
 			ksft_test_result_pass("%s\n", tests[i].name);
diff --git a/tools/testing/selftests/dmabuf-heaps/config b/tools/testing/selftests/dmabuf-heaps/config
index be091f1cdfa04e..94c8f33b71a28d 100644
--- a/tools/testing/selftests/dmabuf-heaps/config
+++ b/tools/testing/selftests/dmabuf-heaps/config
@@ -1,3 +1,4 @@
+CONFIG_MEMCG=y
 CONFIG_DMABUF_HEAPS=y
 CONFIG_DMABUF_HEAPS_SYSTEM=y
 CONFIG_DRM_VGEM=y
diff --git a/tools/testing/selftests/dmabuf-heaps/dmabuf-heap.c b/tools/testing/selftests/dmabuf-heaps/dmabuf-heap.c
index 1d49df6719198a..44e3f33acf8775 100644
--- a/tools/testing/selftests/dmabuf-heaps/dmabuf-heap.c
+++ b/tools/testing/selftests/dmabuf-heaps/dmabuf-heap.c
@@ -3,6 +3,7 @@
 #include <dirent.h>
 #include <errno.h>
 #include <fcntl.h>
+#include <signal.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <stdint.h>
@@ -10,11 +11,16 @@
 #include <unistd.h>
 #include <sys/ioctl.h>
 #include <sys/mman.h>
+#include <sys/prctl.h>
+#include <sys/syscall.h>
 #include <sys/types.h>
+#include <sys/wait.h>
 
 #include <linux/dma-buf.h>
 #include <linux/dma-heap.h>
+#include <linux/limits.h>
 #include <drm/drm.h>
+#include "../pidfd/pidfd.h"
 #include "kselftest.h"
 
 #define DEVPATH "/dev/dma_heap"
@@ -320,6 +326,8 @@ static int dmabuf_heap_alloc_newer(int fd, size_t len, unsigned int flags,
 		__u32 fd;
 		__u32 fd_flags;
 		__u64 heap_flags;
+		__u32 charge_fd;
+		__u32 __padding;
 		__u64 garbage1;
 		__u64 garbage2;
 		__u64 garbage3;
@@ -328,6 +336,8 @@ static int dmabuf_heap_alloc_newer(int fd, size_t len, unsigned int flags,
 		.fd = 0,
 		.fd_flags = O_RDWR | O_CLOEXEC,
 		.heap_flags = flags,
+		.charge_fd = 0,
+		.__padding = 0,
 		.garbage1 = 0xffffffff,
 		.garbage2 = 0x88888888,
 		.garbage3 = 0x11111111,
@@ -496,6 +506,227 @@ static void test_alloc_no_fd_leak_on_efault(char *heap_name)
 	ksft_test_result(fd_before == fd_after,
 			 "fd leak on EFAULT: before=%d after=%d\n",
 			 fd_before, fd_after);
+
+out:
+	close(heap_fd);
+}
+
+static int dmabuf_heap_alloc_pidfd(int fd, size_t len, unsigned int heap_flags,
+				   unsigned int charge_fd, int *dmabuf_fd)
+{
+	struct dma_heap_allocation_data data = {
+		.len = len,
+		.fd = 0,
+		.fd_flags = O_RDWR | O_CLOEXEC,
+		.heap_flags = heap_flags,
+		.charge_fd = charge_fd,
+	};
+	int ret;
+
+	if (!dmabuf_fd)
+		return -EINVAL;
+
+	ret = ioctl(fd, DMA_HEAP_IOCTL_ALLOC, &data);
+	if (ret < 0)
+		return ret;
+	*dmabuf_fd = (int)data.fd;
+	return ret;
+}
+
+/*
+ * Probe whether the kernel honours charge_fd in DMA_HEAP_IOCTL_ALLOC.
+ */
+static bool pidfd_alloc_supported(int heap_fd)
+{
+	int devnull_fd, dmabuf_fd = -1, ret;
+
+	devnull_fd = open("/dev/null", O_RDONLY);
+	if (devnull_fd < 0)
+		return false;
+
+	ret = dmabuf_heap_alloc_pidfd(heap_fd, ONE_MEG, 0, devnull_fd, &dmabuf_fd);
+	if (dmabuf_fd >= 0) {
+		close(dmabuf_fd);
+		dmabuf_fd = -1;
+	}
+	close(devnull_fd);
+	return ret < 0;
+}
+
+/*
+ * Test: allocate charging the calling process's own cgroup via a self pidfd.
+ */
+static void test_alloc_pidfd_self(char *heap_name)
+{
+	int heap_fd = -1, pidfd = -1, dmabuf_fd = -1, ret;
+
+	heap_fd = dmabuf_heap_open(heap_name);
+
+	if (!pidfd_alloc_supported(heap_fd)) {
+		ksft_test_result_skip("charge_fd not supported by this kernel\n");
+		goto out;
+	}
+
+	pidfd = sys_pidfd_open(getpid(), 0);
+	if (pidfd < 0) {
+		ksft_test_result_skip("pidfd_open not available\n");
+		goto out;
+	}
+
+	ret = dmabuf_heap_alloc_pidfd(heap_fd, ONE_MEG, 0, pidfd, &dmabuf_fd);
+	ksft_test_result(!ret, "Allocation with self pidfd %d\n", ret);
+	if (dmabuf_fd >= 0)
+		close(dmabuf_fd);
+	close(pidfd);
+out:
+	close(heap_fd);
+}
+
+/*
+ * Test: allocate charging a child process's cgroup via a child pidfd.
+ */
+static void test_alloc_pidfd_child(char *heap_name)
+{
+	int heap_fd = -1, pidfd = -1, dmabuf_fd = -1;
+	pid_t child_pid, parent_pid;
+	int status, ret;
+
+	heap_fd = dmabuf_heap_open(heap_name);
+
+	if (!pidfd_alloc_supported(heap_fd)) {
+		ksft_test_result_skip("charge_fd not supported by this kernel\n");
+		goto out;
+	}
+
+	parent_pid = getpid();
+	child_pid = fork();
+	if (child_pid == 0) {
+		prctl(PR_SET_PDEATHSIG, SIGKILL);
+		if (getppid() != parent_pid)
+			_exit(0);
+		pause();
+		_exit(0);
+	}
+	if (child_pid < 0)
+		ksft_exit_fail_msg("fork failed: %s\n", strerror(errno));
+
+	pidfd = sys_pidfd_open(child_pid, 0);
+	if (pidfd < 0) {
+		kill(child_pid, SIGTERM);
+		waitpid(child_pid, &status, 0);
+		ksft_test_result_skip("pidfd_open for child failed\n");
+		goto out;
+	}
+
+	ret = dmabuf_heap_alloc_pidfd(heap_fd, ONE_MEG, 0, pidfd, &dmabuf_fd);
+	ksft_test_result(!ret, "Allocation with child pidfd %d\n", ret);
+	if (dmabuf_fd >= 0)
+		close(dmabuf_fd);
+	close(pidfd);
+	kill(child_pid, SIGTERM);
+	waitpid(child_pid, &status, 0);
+out:
+	close(heap_fd);
+}
+
+static int open_self_cgroupfd(void)
+{
+	char cgroup_path[PATH_MAX];
+	char line[PATH_MAX];
+	int ret = -1;
+	FILE *f;
+
+	f = fopen("/proc/self/cgroup", "r");
+	if (!f)
+		return -1;
+	while (fgets(line, sizeof(line), f)) {
+		if (strncmp(line, "0::", 3))
+			continue;
+		line[strcspn(line, "\n")] = '\0';
+		if (snprintf(cgroup_path, sizeof(cgroup_path),
+			     "/sys/fs/cgroup%s", line + 3) < PATH_MAX)
+			ret = 0;
+		break;
+	}
+	fclose(f);
+
+	if (ret)
+		return -1;
+
+	return open(cgroup_path, O_RDONLY | O_DIRECTORY);
+}
+
+/*
+ * Test: allocate charging the calling process's own cgroup via a cgroupfd.
+ */
+static void test_alloc_cgroupfd_self(char *heap_name)
+{
+	int heap_fd = -1, cgroup_fd = -1, dmabuf_fd = -1, ret;
+
+	heap_fd = dmabuf_heap_open(heap_name);
+
+	if (!pidfd_alloc_supported(heap_fd)) {
+		ksft_test_result_skip("charge_fd not supported by this kernel\n");
+		goto out;
+	}
+
+	cgroup_fd = open_self_cgroupfd();
+	if (cgroup_fd < 0) {
+		ksft_test_result_skip("cannot open self cgroupfd\n");
+		goto out;
+	}
+
+	ret = dmabuf_heap_alloc_pidfd(heap_fd, ONE_MEG, 0, cgroup_fd, &dmabuf_fd);
+	ksft_test_result(!ret, "Allocation with cgroupfd %d\n", ret);
+	if (dmabuf_fd >= 0)
+		close(dmabuf_fd);
+	close(cgroup_fd);
+out:
+	close(heap_fd);
+}
+
+/*
+ * Test: transfer a dma-buf's charge to self cgroup via DMA_BUF_IOCTL_XFER_CHARGE.
+ */
+static void test_xfer_charge_cgroupfd_self(char *heap_name)
+{
+	int heap_fd = -1, cgroup_fd = -1, dmabuf_fd = -1, ret;
+	struct dma_buf_transfer_charge xfer = { 0 };
+
+	heap_fd = dmabuf_heap_open(heap_name);
+
+	if (!pidfd_alloc_supported(heap_fd)) {
+		ksft_test_result_skip("charge_fd not supported by this kernel\n");
+		goto out;
+	}
+
+	ret = dmabuf_heap_alloc(heap_fd, ONE_MEG, 0, &dmabuf_fd);
+	if (ret) {
+		ksft_test_result_fail("Allocation failed %d\n", ret);
+		goto out;
+	}
+
+	cgroup_fd = open_self_cgroupfd();
+	if (cgroup_fd < 0) {
+		ksft_test_result_skip("cannot open self cgroupfd\n");
+		close(dmabuf_fd);
+		goto out;
+	}
+
+	xfer.charge_fd = cgroup_fd;
+	ret = ioctl(dmabuf_fd, DMA_BUF_IOCTL_XFER_CHARGE, &xfer);
+	if (!ret)
+		ksft_test_result_pass("XFER_CHARGE to self cgroupfd\n");
+	else if (errno == EOPNOTSUPP)
+		ksft_test_result_skip("buffer not memcg-charged (mem_accounting=0?)\n");
+	else if (errno == ENOTTY || errno == EINVAL)
+		ksft_test_result_skip("XFER_CHARGE not supported: %s\n",
+				      strerror(errno));
+	else
+		ksft_test_result_fail("XFER_CHARGE failed: %s\n", strerror(errno));
+
+	close(cgroup_fd);
+	close(dmabuf_fd);
 out:
 	close(heap_fd);
 }
@@ -530,7 +761,7 @@ int main(void)
 		return KSFT_SKIP;
 	}
 
-	ksft_set_plan(12 * numer_of_heaps());
+	ksft_set_plan(16 * numer_of_heaps());
 
 	while ((dir = readdir(d))) {
 		if (!strncmp(dir->d_name, ".", 2))
@@ -546,6 +777,10 @@ int main(void)
 		test_alloc_compat(dir->d_name);
 		test_alloc_errors(dir->d_name);
 		test_alloc_no_fd_leak_on_efault(dir->d_name);
+		test_alloc_pidfd_self(dir->d_name);
+		test_alloc_pidfd_child(dir->d_name);
+		test_alloc_cgroupfd_self(dir->d_name);
+		test_xfer_charge_cgroupfd_self(dir->d_name);
 	}
 	closedir(d);
 
diff --git a/tools/testing/selftests/dmabuf-heaps/vmtest.sh b/tools/testing/selftests/dmabuf-heaps/vmtest.sh
new file mode 100755
index 00000000000000..3574b71ca83e85
--- /dev/null
+++ b/tools/testing/selftests/dmabuf-heaps/vmtest.sh
@@ -0,0 +1,226 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Copyright (c) 2026 Red Hat
+#
+# Dependencies:
+#		* virtme-ng
+#		* qemu	(used by virtme-ng)
+
+readonly SCRIPT_DIR="$(cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
+readonly KERNEL_CHECKOUT=$(realpath "${SCRIPT_DIR}"/../../../../)
+readonly CGROUP_DIR="${KERNEL_CHECKOUT}/tools/testing/selftests/cgroup"
+
+source "${SCRIPT_DIR}"/../kselftest/ktap_helpers.sh
+
+readonly DMABUF_HEAP_TEST="${SCRIPT_DIR}"/dmabuf-heap
+readonly MEMCONTROL_TEST="${CGROUP_DIR}"/test_memcontrol
+readonly TMP_DIR=$(mktemp -d /tmp/dmabuf-vmtest.XXXXXXXX)
+
+VERBOSE=false
+BUILD=false
+BUILD_HOST=""
+BUILD_HOST_PODMAN_CONTAINER_NAME=""
+SHELL_MODE=false
+
+usage() {
+	echo
+	echo "$0 [OPTIONS]"
+	echo
+	echo "Options"
+	echo "  -b: build the kernel from the current source tree and use it for the VM"
+	echo "  -H: hostname for remote build host (used with -b)"
+	echo "  -p: podman container name for remote build host (used with -b)"
+	echo "      Example: -H beefyserver -p vng"
+	echo "  -s: drop into an interactive shell in the VM instead of running tests"
+	echo "  -v: enable verbose vng/qemu output"
+	echo
+
+	exit 1
+}
+
+die() {
+	echo "$*" >&2
+	exit "${KSFT_FAIL}"
+}
+
+cleanup() {
+	rm -rf "${TMP_DIR}"
+}
+
+check_deps() {
+	for dep in vng make; do
+		if [[ ! -x $(command -v "${dep}") ]]; then
+			echo -e "skip:    dependency ${dep} not found!\n"
+			exit "${KSFT_SKIP}"
+		fi
+	done
+
+	if ${SHELL_MODE}; then
+		return
+	fi
+
+	if [[ ! -x "${DMABUF_HEAP_TEST}" ]]; then
+		printf "skip:    %s not found!" "${DMABUF_HEAP_TEST}"
+		printf " Please build the kselftest dmabuf-heaps target (or use -b).\n"
+		exit "${KSFT_SKIP}"
+	fi
+
+	if [[ ! -x "${MEMCONTROL_TEST}" ]]; then
+		printf "skip:    %s not found!" "${MEMCONTROL_TEST}"
+		printf " Please build the kselftest cgroup target (or use -b).\n"
+		exit "${KSFT_SKIP}"
+	fi
+}
+
+check_vng() {
+	local tested_versions=("1.36" "1.37")
+	local version
+	local ok=0
+
+	version="$(vng --version)"
+	for tv in "${tested_versions[@]}"; do
+		if [[ "${version}" == *"${tv}"* ]]; then
+			ok=1
+			break
+		fi
+	done
+
+	if [[ "${ok}" -eq 0 ]]; then
+		printf "warning: vng version '%s' has not been tested and may " "${version}" >&2
+		printf "not function properly.\n\tThe following versions have been tested: " >&2
+		echo "${tested_versions[@]}" >&2
+	fi
+}
+
+build_selftests() {
+	make -C "${KERNEL_CHECKOUT}" headers_install \
+		INSTALL_HDR_PATH="${TMP_DIR}/usr" -j"$(nproc)"
+
+	local khdr="-isystem ${TMP_DIR}/usr/include"
+
+	if ! make -C "${SCRIPT_DIR}" KHDR_INCLUDES="${khdr}" -j"$(nproc)"; then
+		die "failed to build dmabuf-heaps selftests"
+	fi
+
+	if ! make -C "${CGROUP_DIR}" KHDR_INCLUDES="${khdr}" \
+		"${MEMCONTROL_TEST}" -j"$(nproc)"; then
+		die "failed to build cgroup/test_memcontrol selftest"
+	fi
+}
+
+handle_build() {
+	if ! ${BUILD}; then
+		return
+	fi
+
+	if [[ ! -d "${KERNEL_CHECKOUT}" ]]; then
+		echo "-b requires vmtest.sh called from the kernel source tree" >&2
+		exit 1
+	fi
+
+	pushd "${KERNEL_CHECKOUT}" &>/dev/null
+
+	if ! vng --kconfig --config "${SCRIPT_DIR}/config"; then
+		die "failed to generate .config for kernel source tree (${KERNEL_CHECKOUT})"
+	fi
+
+	local vng_args=("-v" "--config" "${SCRIPT_DIR}/config" "--build")
+
+	if [[ -n "${BUILD_HOST}" ]]; then
+		vng_args+=("--build-host" "${BUILD_HOST}")
+	fi
+
+	if [[ -n "${BUILD_HOST_PODMAN_CONTAINER_NAME}" ]]; then
+		vng_args+=("--build-host-exec-prefix" \
+			   "podman exec -ti ${BUILD_HOST_PODMAN_CONTAINER_NAME}")
+	fi
+
+	if ! vng "${vng_args[@]}"; then
+		die "failed to build kernel from source tree (${KERNEL_CHECKOUT})"
+	fi
+
+	build_selftests
+
+	popd &>/dev/null
+}
+
+make_runner() {
+	# virtme-ng shares the host filesystem, so TMP_DIR is accessible
+	# inside the VM at the same absolute path.
+	cat > "${TMP_DIR}/run_tests.sh" <<-EOF
+	#!/bin/sh
+	set -u
+
+	# Enable memory controller for child cgroups
+	echo +memory > /sys/fs/cgroup/cgroup.subtree_control 2>/dev/null
+
+	PASS=0; FAIL=0; SKIP=0; N=0
+
+	run() {
+		name="\$1"; shift
+		N=\$((N+1))
+		"\$@"; rc=\$?
+		if   [ \$rc -eq 0 ]; then echo "ok \$N \$name";        PASS=\$((PASS+1))
+		elif [ \$rc -eq 4 ]; then echo "ok \$N \$name # SKIP"; SKIP=\$((SKIP+1))
+		else                      echo "not ok \$N \$name";    FAIL=\$((FAIL+1))
+		fi
+	}
+
+	run "dmabuf-heap charge_fd ioctl"	${DMABUF_HEAP_TEST}
+	run "memcontrol dma-buf memcg"	${MEMCONTROL_TEST} test_memcg_dmabuf
+	run "memcontrol dma-buf xfer limit" \
+		${MEMCONTROL_TEST} test_memcg_dmabuf_xfer_at_limit
+	echo "# PASS=\$PASS SKIP=\$SKIP FAIL=\$FAIL"
+	[ \$FAIL -eq 0 ]
+	EOF
+	chmod +x "${TMP_DIR}/run_tests.sh"
+}
+
+run_vm() {
+	local verbose_opt=""
+	local kernel_opt=""
+
+	${VERBOSE} && verbose_opt="--verbose"
+
+	# If we are running from within the kernel source tree, use the kernel
+	# source tree as the kernel to boot, otherwise use the running kernel.
+	if [[ "$(realpath "$(pwd)")" == "${KERNEL_CHECKOUT}"* ]]; then
+		kernel_opt="${KERNEL_CHECKOUT}"
+	fi
+
+	if ${SHELL_MODE}; then
+		echo "Starting interactive shell in VM. Exit to stop VM."
+		vng --run ${kernel_opt} ${verbose_opt} --user root --memory 512M \
+			--append "dma_heap.mem_accounting=1" \
+			-- bash --noprofile --norc
+		exit "${KSFT_PASS}"
+	fi
+
+	vng --run ${kernel_opt} ${verbose_opt} --user root --memory 512M \
+		--append "dma_heap.mem_accounting=1" \
+		--exec "${TMP_DIR}/run_tests.sh"
+}
+
+while getopts :hvsbH:p: o
+do
+	case $o in
+	v) VERBOSE=true;;
+	b) BUILD=true;;
+	s) SHELL_MODE=true;;
+	H) BUILD_HOST=$OPTARG;;
+	p) BUILD_HOST_PODMAN_CONTAINER_NAME=$OPTARG;;
+	h|*) usage;;
+	esac
+done
+shift $((OPTIND-1))
+
+trap cleanup EXIT
+
+check_deps
+check_vng
+handle_build
+make_runner
+
+echo "Booting VM and running tests..."
+run_vm

3/2 2026/11/20 23:06 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 27508
							output: 21
							thoughts: 728
						

Thoughts:
**DMA-Buf Cgroup Accounting: A Worthy Target**

Okay, so this patch series is adding DMA-buf cgroup accounting. Let me break down my understanding. Essentially, we're introducing the capability to track and manage DMA-buf usage within cgroups, specifically focusing on memory consumption.

My analysis started with the code changes. I see additions and modifications across the board:

*   **Documentation:** This suggests a new feature that will need to be understood by developers and administrators. The documentation update to `/Documentation/admin-guide/cgroup-v2.rst` shows that this is an integrated feature.
*   **Core dma-buf operations:** `dma_buf_release`, `dma_buf_xfer_charge`, and `dma_buf_export` are modified to interact with the memcg subsystem, with calls to `mem_cgroup_uncharge_dmabuf`, `mem_cgroup_commit_dmabuf`, etc. This means we're charging and uncharging DMA-buf usage against specific cgroups.
*   **dma-heap interaction:** The `dma_heap_ioctl_allocate` now handles `charge_fd`, retrieving an `objcg` (object cgroup) and passing it to the allocation operation. This is crucial for linking DMA-heap allocations with cgroup accounting.
*   **System Heap Integration:** The system heap is specifically noted, with `system_heap_allocate` now taking an `objcg` and calling `obj_cgroup_reserve_dmabuf`, etc. This shows how DMA heaps, in particular, will be integrated.
*   **Signatures and changes:** I'm also seeing signature changes in `cma_heap.c` and `tee_heap.c`, indicating the new cgroup-aware allocation logic is affecting different heap types.
*   **memcontrol.c: The Heart of the Matter:**  This is where the real accounting happens. The introduction of functions like `mem_cgroup_may_charge`, `get_obj_cgroup_from_fd`, `obj_cgroup_transfer_charge`, `obj_cgroup_reserve_dmabuf`, `obj_cgroup_cancel_dmabuf`, `mem_cgroup_commit_dmabuf`, and `mem_cgroup_uncharge_dmabuf` confirms that the memory management core has been enhanced to handle DMA-buf usage. This looks like the critical piece.
*   **Security Context:** The presence of LSM hooks (`security/security.c`, `security/selinux/hooks.c`) is important, meaning this impacts security considerations.
*   **User-Space API:** Changes to the `dma-buf.h` and `dma-heap.h` headers, especially `DMA_BUF_IOCTL_XFER_CHARGE` and the `charge_fd` in the `dma_heap_allocation_data` struct, signify the introduction of new user-space ioctls or modification of existing ones. This will be how userspace interacts with the new functionality.

Based on this, **WorthFuzzing** is definitely true. The reachability is great: DMA-buf and dma-heap (especially the system heap) are fundamental virtual mechanisms accessible in standard environments like QEMU.  Access is done via character devices such as `/dev/dma_heap/system`. The code touches core subsystems: `mm/memcontrol.c`, `drivers/dma-buf/dma-buf.c`, `drivers/dma-buf/dma-heap.c`, `system_heap.c`, and security. I see new or modified ioctls: `DMA_BUF_IOCTL_XFER_CHARGE` and modifications to `DMA_HEAP_IOCTL_ALLOC` plus the new `obj_cgroup` and memcg accounting logic.

Now, I need to check the required configs.  I'll need to figure out the dependencies on `DMABUF_HEAPS` and `DMABUF_HEAPS_SYSTEM` to see if there are any specific kernel build configurations required to enable this new functionality.



4/2 2026/11/20 23:06 tool grepper
0m Args:
{
  "Expression": "config DMABUF_HEAPS"
}

Results:
{
  "Output": "drivers/dma-buf/Kconfig=52=config DMABUF_KUNIT_TEST\n--\ndrivers/dma-buf/Kconfig-59-\ndrivers/dma-buf/Kconfig:60:menuconfig DMABUF_HEAPS\ndrivers/dma-buf/Kconfig-61-\tbool \"DMA-BUF Userland Memory Heaps\"\n--\ndrivers/dma-buf/heaps/Kconfig:1:config DMABUF_HEAPS_SYSTEM\ndrivers/dma-buf/heaps/Kconfig-2-\ttristate \"DMA-BUF System Heap\"\n--\ndrivers/dma-buf/heaps/Kconfig-7-\ndrivers/dma-buf/heaps/Kconfig:8:config DMABUF_HEAPS_SYSTEM_CC_SHARED\ndrivers/dma-buf/heaps/Kconfig-9-\tbool \"DMA-BUF System Heap for decrypted CoCo VMs\"\n--\ndrivers/dma-buf/heaps/Kconfig-15-\ndrivers/dma-buf/heaps/Kconfig:16:config DMABUF_HEAPS_CMA\ndrivers/dma-buf/heaps/Kconfig-17-\ttristate \"DMA-BUF CMA Heap\"\n"
}

5/2 2026/11/20 23:07 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 29453
							output: 36
							thoughts: 27
						

Thoughts:
Okay, here's my interpretation of those thoughts, crafted with the understanding that I'm speaking to a fellow expert:

**Diving into DMA-BUF Configuration**

Alright, my brain just kicked in and said, "Time to take a look at the DMA-BUF configuration options." Specifically, I need to drill down into the Kconfig files. First up, I want to see what's defined in `drivers/dma-buf/Kconfig`. That's the core of the DMA-BUF driver configuration, so that's obviously where I should start. Then, since DMA-BUF is heavily integrated with memory management heaps, the next logical step is `drivers/dma-buf/heaps/Kconfig`. This should give me a solid view of how the configuration is structured and what options are available for the heaps themselves. Let's see what's new or changed. Time to get my hands dirty.



6/2 2026/11/20 23:07 tool read-file
0m Args:
{
  "File": "drivers/dma-buf/Kconfig",
  "FirstLine": 55,
  "LineCount": 40
}

Results:
{
  "Contents": "  55:\t\tselect DMA_SHARED_BUFFER\n  56:\t\tdefault KUNIT_ALL_TESTS\n  57:\t\thelp\n  58:\t\t   Enable kunit tests for DMA-BUF\n  59:\t\n  60:\tmenuconfig DMABUF_HEAPS\n  61:\t\tbool \"DMA-BUF Userland Memory Heaps\"\n  62:\t\tselect DMA_SHARED_BUFFER\n  63:\t\thelp\n  64:\t\t  Choose this option to enable the DMA-BUF userland memory heaps.\n  65:\t\t  This options creates per heap chardevs in /dev/dma_heap/ which\n  66:\t\t  allows userspace to allocate dma-bufs that can be shared\n  67:\t\t  between drivers.\n  68:\t\n  69:\tsource \"drivers/dma-buf/heaps/Kconfig\"\n  70:\t\n  71:\tendmenu\n"
}

7/2 2026/11/20 23:07 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 29945
							output: 38
							thoughts: 17
						

Thoughts:
Here's a first-person summary, tailored for an expert audience, of the provided thought process:

**Diving into the Driver Configurations**

Okay, so I need to get a handle on the DMA-BUF heap configuration within the driver framework. Let's start by methodically checking the `drivers/dma-buf/heaps/Kconfig` file. I'm thinking this is the place where I'll find the core options related to the system's DMA-BUF heap allocations. I expect to see the basic settings, maybe some sub-options, and any dependencies outlined here. It's the standard entry point for understanding how these specific heap configurations are exposed to the kernel build system. From here, I can trace dependencies to see how they link up, and where, I can make changes without breaking the whole build. This seems like a reasonable and focused starting point.



8/2 2026/11/20 23:07 tool read-file
0m Args:
{
  "File": "drivers/dma-buf/heaps/Kconfig",
  "FirstLine": 1,
  "LineCount": 40
}

Results:
{
  "Contents": "   1:\tconfig DMABUF_HEAPS_SYSTEM\n   2:\t\ttristate \"DMA-BUF System Heap\"\n   3:\t\tdepends on DMABUF_HEAPS\n   4:\t\thelp\n   5:\t\t  Choose this option to enable the system dmabuf heap. The system heap\n   6:\t\t  is backed by pages from the buddy allocator. If in doubt, say Y.\n   7:\t\n   8:\tconfig DMABUF_HEAPS_SYSTEM_CC_SHARED\n   9:\t\tbool \"DMA-BUF System Heap for decrypted CoCo VMs\"\n  10:\t\tdepends on DMABUF_HEAPS \u0026\u0026 ARCH_HAS_MEM_ENCRYPT \u0026\u0026 DMABUF_HEAPS_SYSTEM=y\n  11:\t\thelp\n  12:\t\t  Choose this option to enable the system_cc_shared dmabuf heap. This\n  13:\t\t  allows allocating shared (decrypted) memory for confidential computing\n  14:\t\t  (CoCo) VMs.\n  15:\t\n  16:\tconfig DMABUF_HEAPS_CMA\n  17:\t\ttristate \"DMA-BUF CMA Heap\"\n  18:\t\tdepends on DMABUF_HEAPS \u0026\u0026 DMA_CMA\n  19:\t\thelp\n  20:\t\t  Choose this option to enable dma-buf CMA heap. This heap is backed\n  21:\t\t  by the Contiguous Memory Allocator (CMA). If your system has these\n  22:\t\t  regions, you should say Y here.\n"
}

9/2 2026/11/20 23:07 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 30551
							output: 30
							thoughts: 56
						

Thoughts:
Okay, here's my thought process on this, distilled into a first-person summary as you requested, geared towards a fellow expert:

**Investigating Memory Accounting Configuration**

Alright, I'm thinking we need to dig into the memory accounting configuration to get a clearer picture. My immediate thought is to check the `MEMCG` configuration. That's usually set in either `init/Kconfig` or `mm/Kconfig`, so I'll start by taking a look there. My hunch is that it's probably related to how memory is tracked and managed.

Then, since we are examining a heap, the next logical step is to see if any `mem_accounting` parameters are influencing the `dma-heap` or `system_heap` behavior. This should give us a specific location to examine more closely.

So, I'll run a quick `grep` for `mem_accounting` across the relevant kernel source trees to rapidly identify all instances. That should hopefully pinpoint exactly where this functionality is being defined and how it's being used within the memory management framework.



10/2 2026/11/20 23:07 tool grepper
0m Args:
{
  "Expression": "mem_accounting",
  "PathPrefixes": [
    "drivers/dma-buf"
  ]
}

Results:
{
  "Output": "drivers/dma-buf/dma-heap.c=52=static DEFINE_XARRAY_ALLOC(dma_heap_minors);\ndrivers/dma-buf/dma-heap.c-53-\ndrivers/dma-buf/dma-heap.c:54:bool __read_mostly mem_accounting;\ndrivers/dma-buf/dma-heap.c:55:module_param(mem_accounting, bool, 0444);\ndrivers/dma-buf/dma-heap.c:56:MODULE_PARM_DESC(mem_accounting,\ndrivers/dma-buf/dma-heap.c-57-\t\t \"Enable cgroup-based memory accounting for dma-buf heap allocations (default=false).\");\ndrivers/dma-buf/dma-heap.c:58:EXPORT_SYMBOL_NS_GPL(mem_accounting, \"DMA_BUF_HEAP\");\ndrivers/dma-buf/dma-heap.c-59-\n--\ndrivers/dma-buf/dma-heap.c=77=static struct dma_buf *dma_heap_ioctl_allocate(struct file *file, void *data)\n--\ndrivers/dma-buf/dma-heap.c-103-\ndrivers/dma-buf/dma-heap.c:104:\tif (!objcg \u0026\u0026 mem_accounting \u0026\u0026 !mem_cgroup_disabled())\ndrivers/dma-buf/dma-heap.c-105-\t\tobjcg = get_obj_cgroup_from_current();\n"
}

11/2 2026/11/20 23:07 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 31253
							output: 26
							thoughts: 152
						

Thoughts:
**Analyzing the DMA Heap Allocation Function**

Okay, so I'm diving into this `dma_heap_ioctl_allocate` function and immediately a potential vulnerability or at least, an unexpected path, catches my eye.  I'm seeing that it checks `heap_allocation->charge_fd` *before* it even considers `mem_accounting`. The crucial thing here is that regardless of whether memory accounting is enabled or not, it's checking for a charge file descriptor.

If there's a file descriptor (`heap_allocation->charge_fd`), it's attempting to grab an object cgroup (`objcg`) from it.  A failure here will short-circuit the function. Now, if *that* condition isn't met, and memory accounting *is* enabled and memcg isn't disabled, then the function uses `get_obj_cgroup_from_current()` to try to associate this allocation with the current process's cgroup.

It's making me think about the MEMCG configuration. It seems like the code expects MEMCG to be configured, since it checks this, so let me quickly verify the Kconfig to confirm my assumption regarding MEMCG.



12/2 2026/11/20 23:07 tool grepper
0m Args:
{
  "Expression": "config MEMCG",
  "PathPrefixes": [
    "init/"
  ]
}

Results:
{
  "Output": "init/Kconfig=871=config CGROUP_FAVOR_DYNMODS\n--\ninit/Kconfig-880-\ninit/Kconfig:881:config MEMCG\ninit/Kconfig-882-\tbool \"Memory controller\"\n--\ninit/Kconfig-889-\ninit/Kconfig:890:config MEMCG_NMI_UNSAFE\ninit/Kconfig-891-\tbool\n--\ninit/Kconfig-896-\ninit/Kconfig:897:config MEMCG_NMI_SAFETY_REQUIRES_ATOMIC\ninit/Kconfig-898-\tbool\n--\ninit/Kconfig-903-\ninit/Kconfig:904:config MEMCG_V1\ninit/Kconfig-905-\tbool \"Legacy cgroup v1 memory controller\"\n"
}

13/2 2026/11/20 23:07 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 31896
							output: 34
							thoughts: 105
						

Thoughts:
**Analyzing DMA-BUF Configuration Options**

Okay, let's dive into this. I need to figure out which configurations are relevant to my current setup regarding `dma-buf`. First, I'm thinking about `MEMCG` – that's crucial, obviously, given its dependence on cgroups and related infrastructure. Next, I need to look at `DMABUF_HEAPS`. I'm also thinking I need to look at `DMABUF_HEAPS_SYSTEM`, or even just a combination of `DMABUF_HEAPS` and `DMABUF_HEAPS_SYSTEM`. Ah, right, and `DMA_SHARED_BUFFER` is selected by `DMABUF_HEAPS`, so that's something to keep in mind. Now, I should probably check for any other related configurations for the `dma-buf` framework. Finally, a quick peek inside the `drivers/dma-buf/Makefile` should give me a good overview of how everything hangs together.



14/2 2026/11/20 23:07 tool read-file
0m Args:
{
  "File": "drivers/dma-buf/Makefile",
  "FirstLine": 1,
  "LineCount": 30
}

Results:
{
  "Contents": "   1:\t# SPDX-License-Identifier: GPL-2.0-only\n   2:\tobj-y := dma-buf.o dma-fence.o dma-fence-array.o dma-fence-chain.o \\\n   3:\t\t dma-fence-unwrap.o dma-resv.o dma-buf-mapping.o dma-buf-io.o\n   4:\tobj-$(CONFIG_DMABUF_HEAPS)\t+= dma-heap.o\n   5:\tobj-$(CONFIG_DMABUF_HEAPS)\t+= heaps/\n   6:\tobj-$(CONFIG_SYNC_FILE)\t\t+= sync_file.o\n   7:\tobj-$(CONFIG_SW_SYNC)\t\t+= sw_sync.o sync_debug.o\n   8:\tobj-$(CONFIG_UDMABUF)\t\t+= udmabuf.o\n   9:\t\n  10:\tdmabuf_kunit-y := \\\n  11:\t\tst-dma-fence.o \\\n  12:\t\tst-dma-fence-chain.o \\\n  13:\t\tst-dma-fence-unwrap.o \\\n  14:\t\tst-dma-resv.o\n  15:\t\n  16:\tobj-$(CONFIG_DMABUF_KUNIT_TEST) += dmabuf_kunit.o\n"
}

15/2 2026/11/20 23:07 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 32588
							output: 41
							thoughts: 738
						

Thoughts:
**Analyzing DMA-BUF and Memory Control in the Kernel**

Okay, let's break this down systematically. I'm focusing on the interaction between DMA-BUF, memory control groups (memcgs), and security aspects. My initial observation is that `dma-buf.o` becomes an `obj-y` target if DMA-BUF is either compiled directly or selected. With `CONFIG_DMABUF_HEAPS` set, the kernel compiles `dma-heap.o` and the `heaps/` directory, and notably, within `heaps/`, `system_heap.o` is tied to `CONFIG_DMABUF_HEAPS_SYSTEM`. I should also keep SELinux in mind; its LSM hooks are controlled by `CONFIG_SECURITY_SELINUX`, so I'll bear that in mind, though it is optional.

To get a clearer picture of configuration, I'm going to look at the test config at `tools/testing/selftests/dmabuf-heaps/config`, which sets `CONFIG_MEMCG=y`, `CONFIG_DMABUF_HEAPS_SYSTEM=y`, and `CONFIG_DRM_VGEM=y`. This means that `MEMCG`, `DMABUF_HEAPS`, and `DMABUF_HEAPS_SYSTEM` are the crucial configurations for understanding this area.

Now, let's dig into the relevant functions and symbols. In `drivers/dma-buf/dma-buf.c`, I see a few key players: `dma_buf_xfer_charge` (which is static and called by `dma_buf_ioctl` under `DMA_BUF_IOCTL_XFER_CHARGE`), `dma_buf_ioctl` (the main ioctl entry point, which seems specific to dma-buf file descriptor ioctls), `dma_buf_export`, and `dma_buf_release`. Moving on to `drivers/dma-buf/dma-heap.c`, `dma_heap_ioctl_allocate` (another static function, called by `dma_heap_ioctl` under `DMA_HEAP_IOCTL_ALLOC`) and `dma_heap_ioctl` are important, and `system_heap_allocate` in `drivers/dma-buf/heaps/system_heap.c` is also important.

The `mm/memcontrol.c` file is particularly interesting because it contains several functions that seem to be managing memory accounting and charging in the context of memory cgroups: `get_obj_cgroup_from_fd`, `obj_cgroup_transfer_charge`, `obj_cgroup_reserve_dmabuf`, `obj_cgroup_cancel_dmabuf`, `mem_cgroup_commit_dmabuf`, `mem_cgroup_uncharge_dmabuf`, and the static function `mem_cgroup_may_charge`.

Finally, on the security side, `security/security.c` includes `security_memcg_charge_task` and `security_memcg_charge_cgroup`, while `security/selinux/hooks.c` has `selinux_memcg_charge_task` and `selinux_memcg_charge_cgroup`. These functions suggest a tight integration between memory control and security policies.

My next step is to determine the scope of these functions by checking if they are static or exported symbols. For example, `dma_buf_xfer_charge` is static within `dma-buf.c`. Could the compiler potentially inline it into `dma_buf_ioctl`? I'll need to double-check `dma_buf_ioctl` itself in `drivers/dma-buf/dma-buf.c`.


16/2 2026/11/20 23:07 tool read-file
0m Args:
{
  "File": "drivers/dma-buf/dma-buf.c",
  "FirstLine": 570,
  "LineCount": 65
}

Results:
{
  "Contents": " 570:\t\tif (!obj_cgroup_transfer_charge(\u0026dmabuf-\u003eobjcg, objcg, MEMCG_DMABUF, nr_pages))\n 571:\t\t\tret = -ENOMEM;\n 572:\t\n 573:\tout:\n 574:\t\tdma_resv_unlock(dmabuf-\u003eresv);\n 575:\t\tobj_cgroup_put(objcg);\n 576:\t\treturn ret;\n 577:\t}\n 578:\t\n 579:\tstatic long dma_buf_ioctl(struct file *file,\n 580:\t\t\t\t  unsigned int cmd, unsigned long arg)\n 581:\t{\n 582:\t\tstruct dma_buf *dmabuf;\n 583:\t\tstruct dma_buf_sync sync;\n 584:\t\tenum dma_data_direction direction;\n 585:\t\tint ret;\n 586:\t\n 587:\t\tdmabuf = file-\u003eprivate_data;\n 588:\t\n 589:\t\tswitch (cmd) {\n 590:\t\tcase DMA_BUF_IOCTL_SYNC:\n 591:\t\t\tif (copy_from_user(\u0026sync, (void __user *) arg, sizeof(sync)))\n 592:\t\t\t\treturn -EFAULT;\n 593:\t\n 594:\t\t\tif (sync.flags \u0026 ~DMA_BUF_SYNC_VALID_FLAGS_MASK)\n 595:\t\t\t\treturn -EINVAL;\n 596:\t\n 597:\t\t\tswitch (sync.flags \u0026 DMA_BUF_SYNC_RW) {\n 598:\t\t\tcase DMA_BUF_SYNC_READ:\n 599:\t\t\t\tdirection = DMA_FROM_DEVICE;\n 600:\t\t\t\tbreak;\n 601:\t\t\tcase DMA_BUF_SYNC_WRITE:\n 602:\t\t\t\tdirection = DMA_TO_DEVICE;\n 603:\t\t\t\tbreak;\n 604:\t\t\tcase DMA_BUF_SYNC_RW:\n 605:\t\t\t\tdirection = DMA_BIDIRECTIONAL;\n 606:\t\t\t\tbreak;\n 607:\t\t\tdefault:\n 608:\t\t\t\treturn -EINVAL;\n 609:\t\t\t}\n 610:\t\n 611:\t\t\tif (sync.flags \u0026 DMA_BUF_SYNC_END)\n 612:\t\t\t\tret = dma_buf_end_cpu_access(dmabuf, direction);\n 613:\t\t\telse\n 614:\t\t\t\tret = dma_buf_begin_cpu_access(dmabuf, direction);\n 615:\t\n 616:\t\t\treturn ret;\n 617:\t\n 618:\t\tcase DMA_BUF_SET_NAME_A:\n 619:\t\tcase DMA_BUF_SET_NAME_B:\n 620:\t\t\treturn dma_buf_set_name(dmabuf, (const char __user *)arg);\n 621:\t\n 622:\t#if IS_ENABLED(CONFIG_SYNC_FILE)\n 623:\t\tcase DMA_BUF_IOCTL_EXPORT_SYNC_FILE:\n 624:\t\t\treturn dma_buf_export_sync_file(dmabuf, (void __user *)arg);\n 625:\t\tcase DMA_BUF_IOCTL_IMPORT_SYNC_FILE:\n 626:\t\t\treturn dma_buf_import_sync_file(dmabuf, (const void __user *)arg);\n 627:\t#endif\n 628:\t\n 629:\t\tcase DMA_BUF_IOCTL_XFER_CHARGE:\n 630:\t\t\treturn dma_buf_xfer_charge(dmabuf, (const void __user *)arg);\n 631:\t\n 632:\t\tdefault:\n 633:\t\t\treturn -ENOTTY;\n 634:\t\t}\n"
}

17/2 2026/11/20 23:07 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 35169
							output: 41
							thoughts: 98
						

Thoughts:
Okay, here's my understanding, tailored for an expert like yourself:

**Diving into DMA-BUF IOCTL Handling**

Right, let's break this down. My initial thought process is focusing on how data transfers involving `dma_buf` objects are managed, especially concerning resource charging. I know `dma_buf_xfer_charge` is a key function here, and I'm tracing its call path. From what I recall, `dma_buf_xfer_charge` is definitely invoked somewhere within `dma_buf_ioctl`, which is the ultimate destination for ioctl requests related to these buffers.

Now, if I remember correctly, `dma_buf_ioctl` is the dedicated ioctl handler for the `dma_buf` file operations. Specifically, that would mean `dma_buf_fops.unlocked_ioctl` points directly to `dma_buf_ioctl`. That makes the connection explicit.

But then my mind wanders: what about the integration with `dma-heap`? I need to quickly recall the interaction between these two subsystems, and the best way is to scan `dma-heap.c` for any related ioctl handling. I'll need to check the code around `dma_heap_ioctl` to understand how `dma_heap` might interplay with `dma_buf` operations, resource charging, and so forth. That should reveal the bigger picture.



18/2 2026/11/20 23:07 tool read-file
0m Args:
{
  "File": "drivers/dma-buf/dma-heap.c",
  "FirstLine": 120,
  "LineCount": 50
}

Results:
{
  "Contents": " 120:\t\n 121:\t\tif (!dmabuf-\u003eobjcg)\n 122:\t\t\tobj_cgroup_put(objcg);\n 123:\t\n 124:\t\tfd = get_unused_fd_flags(heap_allocation-\u003efd_flags);\n 125:\t\tif (fd \u003c 0) {\n 126:\t\t\tdma_buf_put(dmabuf);\n 127:\t\t\treturn ERR_PTR(fd);\n 128:\t\t}\n 129:\t\n 130:\t\theap_allocation-\u003efd = fd;\n 131:\t\n 132:\t\treturn dmabuf;\n 133:\t}\n 134:\t\n 135:\tstatic unsigned int dma_heap_ioctl_cmds[] = {\n 136:\t\tDMA_HEAP_IOCTL_ALLOC,\n 137:\t};\n 138:\t\n 139:\tstatic long dma_heap_ioctl(struct file *file, unsigned int ucmd,\n 140:\t\t\t\t   unsigned long arg)\n 141:\t{\n 142:\t\tchar stack_kdata[128];\n 143:\t\tchar *kdata = stack_kdata;\n 144:\t\tunsigned int kcmd;\n 145:\t\tunsigned int in_size, out_size, drv_size, ksize;\n 146:\t\tint nr = _IOC_NR(ucmd);\n 147:\t\tint ret = 0;\n 148:\t\tint fd;\n 149:\t\tstruct dma_buf *dmabuf;\n 150:\t\n 151:\t\tif (nr \u003e= ARRAY_SIZE(dma_heap_ioctl_cmds))\n 152:\t\t\treturn -EINVAL;\n 153:\t\n 154:\t\tnr = array_index_nospec(nr, ARRAY_SIZE(dma_heap_ioctl_cmds));\n 155:\t\t/* Get the kernel ioctl cmd that matches */\n 156:\t\tkcmd = dma_heap_ioctl_cmds[nr];\n 157:\t\n 158:\t\t/* Figure out the delta between user cmd size and kernel cmd size */\n 159:\t\tdrv_size = _IOC_SIZE(kcmd);\n 160:\t\tout_size = _IOC_SIZE(ucmd);\n 161:\t\tin_size = out_size;\n 162:\t\tif ((ucmd \u0026 kcmd \u0026 IOC_IN) == 0)\n 163:\t\t\tin_size = 0;\n 164:\t\tif ((ucmd \u0026 kcmd \u0026 IOC_OUT) == 0)\n 165:\t\t\tout_size = 0;\n 166:\t\tksize = max3(in_size, out_size, drv_size);\n 167:\t\n 168:\t\t/* If necessary, allocate buffer for ioctl argument */\n 169:\t\tif (ksize \u003e sizeof(stack_kdata)) {\n"
}

19/2 2026/11/20 23:07 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 36384
							output: 20
							thoughts: 1363
						

Thoughts:
**Focus Symbol Selection for DMA-BUF Cgroup Charging**

Okay, let's break this down for fuzzing. We're adding cgroup charging to DMA-BUF, so the goal is to identify the *right* functions to guide the fuzzer.  I need to avoid the "ubiquitous lifecycle hot-paths" trap – we don't want the fuzzer getting lost in generic allocators or core synchronization primitives. We need to target specific feature logic and entrypoints.

First, I identified key functions related to this feature: `dma_heap_ioctl_allocate`, `dma_heap_ioctl` (in the `dma-buf` and `dma-buf/heaps` directories, respectively), and the system heap's `system_heap_allocate`. Then I found these in `mm/memcontrol.c`: `get_obj_cgroup_from_fd`, `obj_cgroup_transfer_charge`, `obj_cgroup_reserve_dmabuf`, `obj_cgroup_cancel_dmabuf`, `mem_cgroup_commit_dmabuf`, and `mem_cgroup_uncharge_dmabuf`. These all seem highly relevant.  Crucially, they're *new* functions specifically crafted for this DMA-BUF cgroup charging.

Now, let's confirm if those functions are called ubiquitously.  `get_obj_cgroup_from_fd` is only called by `dma_buf_xfer_charge` and `dma_heap_ioctl_allocate`. `obj_cgroup_transfer_charge` is called by `dma_buf_xfer_charge`. `obj_cgroup_reserve_dmabuf` and `obj_cgroup_cancel_dmabuf` are called by `system_heap_allocate`. `mem_cgroup_commit_dmabuf` and `mem_cgroup_uncharge_dmabuf` are only called by `dma_buf_export` and `dma_buf_release`, respectively. `dma_buf_xfer_charge` is called by `dma_buf_ioctl`. And `dma_heap_ioctl_allocate` called by `dma_heap_ioctl`. It looks like these functions are not ubiquitous. They are only invoked in very specific places.

Regarding security hooks, `security_memcg_charge_task`, `security_memcg_charge_cgroup`, `selinux_memcg_charge_task`, and `selinux_memcg_charge_cgroup` are also highly relevant.

Based on this, the promising `FocusSymbols` are:
*   `dma_buf_xfer_charge`
*   `dma_heap_ioctl_allocate`
*   `system_heap_allocate`
*   `get_obj_cgroup_from_fd`
*   `obj_cgroup_transfer_charge`
*   `obj_cgroup_reserve_dmabuf`
*   `mem_cgroup_commit_dmabuf`
*   `mem_cgroup_uncharge_dmabuf`

Let's double-check if `dma_buf_xfer_charge` and `dma_heap_ioctl_allocate` are good candidates.  We need to make sure we're not missing any caller inlining. `dma_buf_ioctl` and `dma_heap_ioctl` are not ubiquitous.  They are only executed when opening a dma_buf or dma_heap file descriptor and issuing an ioctl on it. The more specific, the better.

`dma_buf_export` and `dma_buf_release` deal with the DMA-BUF lifecycle. The critical logic seems to be within `dma_buf_xfer_charge`.  Even if there's inlining, modern compilers often help Syzkaller. Including `dma_buf_ioctl` and `dma_heap_ioctl` provides additional focus.

Finally, a quick review of configs: We have `DMABUF_HEAPS`, `DMABUF_HEAPS_SYSTEM`, and `MEMCG` enabled. `DMA_SHARED_BUFFER` is selected by `DMABUF_HEAPS`, but it is good to confirm if it is user selectable.



20/2 2026/11/20 23:08 tool grepper
0m Args:
{
  "Expression": "config DMA_SHARED_BUFFER"
}

Results:
{
  "Output": "drivers/base/Kconfig=213=source \"drivers/base/regmap/Kconfig\"\ndrivers/base/Kconfig-214-\ndrivers/base/Kconfig:215:config DMA_SHARED_BUFFER\ndrivers/base/Kconfig-216-\tbool\n"
}

21/2 2026/11/20 23:08 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 38789
							output: 33
							thoughts: 52
						

Thoughts:
Okay, here's my take on those thoughts, framed as my own mental processing:

**Analyzing DMA Buffer Configuration**

Alright, so `DMA_SHARED_BUFFER` doesn't have a prompt associated with it directly. That means its selection is likely driven by dependencies or other configuration options, like `DMABUF_HEAPS`. I need to figure out the connection. Let's dig into the CGROUPS configuration first. I know `MEMCG` relies on `CGROUPS`, so that's a logical starting point. I need to understand if there's a direct or indirect relationship between `MEMCG` and how the DMA buffer option is enabled. I'll need to check the `init/Kconfig` file and specifically look for the `config MEMCG` options and their influence. This should illuminate the configuration path for all of this. I’m thinking there is a relationship but I need to be sure.



22/2 2026/11/20 23:08 tool grepper
0m Args:
{
  "Expression": "depends on.*MEMCG",
  "PathPrefixes": [
    "init/",
    "mm/"
  ]
}

Results:
{
  "Output": "init/Kconfig=890=config MEMCG_NMI_UNSAFE\ninit/Kconfig-891-\tbool\ninit/Kconfig:892:\tdepends on MEMCG\ninit/Kconfig-893-\tdepends on HAVE_NMI\n--\ninit/Kconfig=897=config MEMCG_NMI_SAFETY_REQUIRES_ATOMIC\ninit/Kconfig-898-\tbool\ninit/Kconfig:899:\tdepends on MEMCG\ninit/Kconfig-900-\tdepends on HAVE_NMI\n--\ninit/Kconfig=904=config MEMCG_V1\ninit/Kconfig-905-\tbool \"Legacy cgroup v1 memory controller\"\ninit/Kconfig:906:\tdepends on MEMCG\ninit/Kconfig-907-\tdefault n\n--\ninit/Kconfig=943=config CGROUP_WRITEBACK\ninit/Kconfig-944-\tbool\ninit/Kconfig:945:\tdepends on MEMCG \u0026\u0026 BLK_CGROUP\ninit/Kconfig-946-\tdefault y\n"
}

23/2 2026/11/20 23:08 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 39347
							output: 32
							thoughts: 17
						

Thoughts:
Okay, here's my take on those thoughts, tailored for an expert audience:

**Examining MEMCG Configuration Dependencies**

Alright, let's dive in. My immediate thought is to trace the configuration dependencies for `MEMCG`. We need to be absolutely certain we understand all the prerequisites defined in `init/Kconfig` before even *thinking* about building or deploying. This is crucial for verifying the intended configuration of `MEMCG` and its relationships within the kernel build system. Understanding these dependencies is the bedrock of correctly enabling and utilizing this important subsystem. We need to be absolutely certain that there aren't any hidden surprises or incorrect flags that could cause compatibility issues downstream. So, `init/Kconfig` it is. Let's see what we can find.



24/2 2026/11/20 23:08 tool read-file
0m Args:
{
  "File": "init/Kconfig",
  "FirstLine": 875,
  "LineCount": 20
}

Results:
{
  "Contents": " 875:\t\t  which reduces the latencies of dynamic cgroup modifications such\n 876:\t\t  as task migrations and controller on/offs at the cost of making\n 877:\t\t  hot path operations such as forks and exits more expensive.\n 878:\t\n 879:\t\t  Say N if unsure.\n 880:\t\n 881:\tconfig MEMCG\n 882:\t\tbool \"Memory controller\"\n 883:\t\tselect PAGE_COUNTER\n 884:\t\tselect EVENTFD\n 885:\t\tselect SLAB_OBJ_EXT\n 886:\t\tselect VM_EVENT_COUNTERS\n 887:\t\thelp\n 888:\t\t  Provides control over the memory footprint of tasks in a cgroup.\n 889:\t\n 890:\tconfig MEMCG_NMI_UNSAFE\n 891:\t\tbool\n 892:\t\tdepends on MEMCG\n 893:\t\tdepends on HAVE_NMI\n 894:\t\tdepends on !ARCH_HAS_NMI_SAFE_THIS_CPU_OPS \u0026\u0026 !ARCH_HAVE_NMI_SAFE_CMPXCHG\n"
}

25/2 2026/11/20 23:08 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 39850
							output: 33
							thoughts: 33
						

Thoughts:
Okay, let's break this down.

**Navigating the Menu Structure**

My initial thought is to figure out the contextual location of the menu item. Where does this specific element reside? I need to understand its enclosing structure, the specific menu or section it's nested within. This will help me grasp its purpose and potential dependencies. Let's see... looking at line 881, it looks like it's nested under an `if CGROUPS` statement. I will verify that assumption now.



26/2 2026/11/20 23:08 tool grepper
0m Args:
{
  "Expression": "menuconfig CGROUPS|if CGROUPS",
  "PathPrefixes": [
    "init/"
  ]
}

Results:
{
  "Output": "init/Kconfig=849=config SLAB_OBJ_EXT\n--\ninit/Kconfig-851-\ninit/Kconfig:852:menuconfig CGROUPS\ninit/Kconfig-853-\tbool \"Control Group support\"\n--\ninit/Kconfig-865-\ninit/Kconfig:866:if CGROUPS\ninit/Kconfig-867-\n"
}

27/2 2026/11/20 23:08 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 40133
							output: 316
							thoughts: 533
						

Thoughts:
**My Analysis of DMA-BUF Cgroup Integration Patch**

Okay, so we're dealing with a patch that introduces cgroup-based memory accounting for DMA buffers and system heaps. First, I confirmed that `CGROUPS` is the root, and thus, alongside it, `MEMCG` is required. Then, I dug into the dependencies of `DMABUF_HEAPS` and `DMABUF_HEAPS_SYSTEM`. Good, no other dependencies for `DMABUF_HEAPS` – confirmed via `menuconfig`. `DMABUF_HEAPS_SYSTEM` correctly depends on `DMABUF_HEAPS`. Therefore, my `EnableConfigs` are: `CGROUPS`, `MEMCG`, `DMABUF_HEAPS`, and `DMABUF_HEAPS_SYSTEM`.

The reasoning is solid: The patch leverages `ioctl DMA_BUF_IOCTL_XFER_CHARGE` for cgroup charge transfers, uses `charge_fd` in `DMA_HEAP_IOCTL_ALLOC`, and integrates memcontrol and security. The code paths are user-accessible via `/dev/dma_heap/system` and dma-buf file descriptors, particularly in virtualized environments. This definitely warrants fuzzing. I need to test for refcounting issues, lockdep violations, race conditions, and memory accounting inconsistencies.

Reviewing the `set-results` parameters, everything aligns. We need `WorthFuzzing: true`, and the `EnableConfigs` are correct. The `FocusSymbols` list captures the crucial functions like `dma_buf_xfer_charge`, `dma_heap_ioctl_allocate`, `system_heap_allocate`, the `get_obj_cgroup_from_fd` family of functions, and the memory cgroup charge/uncharge functions: all are essential for this analysis. The `Reasoning` is concise and captures the essence.

Time to invoke `set-results`.



28/2 2026/11/20 23:08 tool set-results
0m Args:
{
  "EnableConfigs": [
    "CGROUPS",
    "MEMCG",
    "DMABUF_HEAPS",
    "DMABUF_HEAPS_SYSTEM"
  ],
  "FocusSymbols": [
    "dma_buf_xfer_charge",
    "dma_heap_ioctl_allocate",
    "system_heap_allocate",
    "get_obj_cgroup_from_fd",
    "obj_cgroup_transfer_charge",
    "obj_cgroup_reserve_dmabuf",
    "obj_cgroup_cancel_dmabuf",
    "mem_cgroup_commit_dmabuf",
    "mem_cgroup_uncharge_dmabuf"
  ],
  "Reasoning": "The patch series implements cgroup-based memory accounting for DMA buffers and DMA heaps. It introduces a new ioctl DMA_BUF_IOCTL_XFER_CHARGE to transfer buffer memory charges between cgroups (using pidfds or cgroupfds), modifies DMA_HEAP_IOCTL_ALLOC to allow allocating dma-bufs charged directly to a specified cgroup, and adds new memcg/objcg accounting functions. These paths are directly reachable from userspace via /dev/dma_heap/system and exported dma-buf file descriptors in standard QEMU/virtualized environments. Fuzzing is warranted to test object cgroup reference counting, cross-cgroup charge transfers, and concurrent ioctl operations.",
  "WorthFuzzing": true
}

Results:
{
  "EnableConfigs": [
    "CGROUPS",
    "MEMCG",
    "DMABUF_HEAPS",
    "DMABUF_HEAPS_SYSTEM"
  ],
  "FocusSymbols": [
    "dma_buf_xfer_charge",
    "dma_heap_ioctl_allocate",
    "system_heap_allocate",
    "get_obj_cgroup_from_fd",
    "obj_cgroup_transfer_charge",
    "obj_cgroup_reserve_dmabuf",
    "obj_cgroup_cancel_dmabuf",
    "mem_cgroup_commit_dmabuf",
    "mem_cgroup_uncharge_dmabuf"
  ],
  "Reasoning": "The patch series implements cgroup-based memory accounting for DMA buffers and DMA heaps. It introduces a new ioctl DMA_BUF_IOCTL_XFER_CHARGE to transfer buffer memory charges between cgroups (using pidfds or cgroupfds), modifies DMA_HEAP_IOCTL_ALLOC to allow allocating dma-bufs charged directly to a specified cgroup, and adds new memcg/objcg accounting functions. These paths are directly reachable from userspace via /dev/dma_heap/system and exported dma-buf file descriptors in standard QEMU/virtualized environments. Fuzzing is warranted to test object cgroup reference counting, cross-cgroup charge transfers, and concurrent ioctl operations.",
  "WorthFuzzing": true
}

29/1 2026/11/20 23:08 action If
2m Args:
{
  "WorthFuzzing": true
}

Results:
null

30/2 2026/11/20 23:08 agent kmsan-evaluator
2m Model:
core

Args:
null

Results:
{
  "KMSANReasoning": "The patch series implements memory cgroup (memcg) accounting for dma-buf allocations and allows transferring charges between cgroups via DMA_BUF_IOCTL_XFER_CHARGE and an extended DMA_HEAP_IOCTL_ALLOC.\n\nKMSAN vs KASAN Applicability Analysis:\n1. KMSAN is specifically designed to catch reads of uninitialized stack, heap, or page allocations and uninitialized info-leaks to userspace.\n2. The user-facing structures touched or added:\n   - `struct dma_buf_transfer_charge` is strictly an input structure (_IOW) composed of two `__u32` members (`flags` and `charge_fd`) totaling 8 bytes, with no padding holes and never copied back to userspace.\n   - `struct dma_heap_allocation_data` is updated to include `__u32 charge_fd` and `__u32 __padding`. With members `len` (8B), `fd` (4B), `fd_flags` (4B), `heap_flags` (8B), `charge_fd` (4B), and `__padding` (4B), the struct size is exactly 32 bytes with natural alignment and zero compiler padding holes. In `dma_heap_ioctl()`, any delta between kernel and userspace argument size is explicitly zeroed with `memset` before any potential `copy_to_user()`.\n3. In-kernel allocations (e.g. `dma_buf`, `system_heap_buffer`) continue to use zero-allocating APIs (`kzalloc()`, `kzalloc_obj()`).\n4. All local variables and pointers introduced in `mm/memcontrol.c` and `drivers/dma-buf/` are explicitly initialized or set by reference prior to being evaluated or dereferenced.\n5. The core risks of these changes involve reference counting (`obj_cgroup_get`/`put`, `css_tryget_online`), locking (`dma_resv_lock`), permissions (LSM hooks and `capable(CAP_SYS_RESOURCE)`), and memory accounting limits (`try_charge`), which fall under functional testing, LOCKDEP, and KASAN.\n\nBecause there are no uninitialized memory risks or info-leaks, spawning a dedicated KMSAN fuzzing session is not justified.",
  "NeedsKMSAN": false
}

Instruction:
You are an expert Linux kernel security engineer specializing in kernel memory
error detectors (KASAN and KMSAN). Your job is to review the provided patch series and
determine if the code changes justify spawning a dedicated KMSAN (KernelMemorySanitizer)
fuzzing session in addition to standard KASAN fuzzing.

CRITICAL DISTINCTION BETWEEN KASAN AND KMSAN:
- Standard KASAN kernel builds (upstream-apparmor-kasan.config) already enable
  a comprehensive suite of debugging tools and sanitizers, including KASAN
  (out-of-bounds accesses, use-after-free, double free, invalid free), LOCKDEP
  (locking bugs and deadlocks), UB-sanitizers, and memory corruption checks.
- KMSAN (KernelMemorySanitizer) detects reads of UNINITIALIZED memory (stack, heap,
  or page allocations) and kernel-to-user memory info-leaks.

Rule: THERE IS NO SENSE IN RUNNING A KMSAN SESSION IF A BUG CAN BE CAUGHT BY KASAN,
LOCKDEP, OR OTHER STANDARD BUG DETECTORS.
A dedicated KMSAN fuzzing session incurs significant resource costs. You must ONLY
set NeedsKMSAN=true if the code changes introduce or expose UNINITIALIZED MEMORY risks
that are detected ONLY by KMSAN.

Look holistically at the patch series and surrounding code. Even if no direct
uninitialized field accesses or new buffer allocations are added in the diff itself,
a patch may alter control flow, bounds checking, or data length calculations in ways
that change how the rest of the code operates on existing buffers (e.g. allowing
uninitialized stack/heap memory to be read, copied to user space, or used in control
flow). Do not hesitate to use your code access tools to inspect the surrounding code,
called functions, and callers.

Set NeedsKMSAN=true ONLY IF the patch introduces or modifies:
1. Kernel structures sent to user space (via copy_to_user, put_user, netlink skb
   attributes, ioctl output arguments, socket options, or BPF buffers) where fields
   or structure padding might not be fully initialized/zeroed.
2. Conditional logic or branching that depends on potentially uninitialized variables
   or struct fields.
3. Allocation or initialization of complex data structures where uninitialized fields
   could be read later in reachable code paths.
4. Bounds checks, lengths, or logic in a way that allows surrounding code to access
   uninitialized bytes of existing buffers.

Set NeedsKMSAN=false IF:
- The code changes primarily risk out-of-bounds access, array overflows, NULL pointer
  dereferences, locking deadlocks, or use-after-free bugs (these are already caught
  by KASAN, LOCKDEP, or standard bug detectors).
- All stack/heap structures touched or introduced by the patch are fully zeroed
  or initialized (e.g. using = {0}, memset, kzalloc) before being read or copied.
- The patch does not introduce any risk of uninitialized memory usage or info-leaks.

Use your code access tools to inspect the surrounding code if necessary, then provide
detailed KMSANReasoning contrasting KASAN vs KMSAN applicability for this patch.
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit d5ea44c8586e67c2b98673186f76297f7f795f2b
Author: syz-cluster <triage@syzkaller.com>
Date:   Fri Nov 20 23:06:42 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/admin-guide/cgroup-v2.rst b/Documentation/admin-guide/cgroup-v2.rst
index 9e3c67b02ae2e1..8d10ff7ac745ac 100644
--- a/Documentation/admin-guide/cgroup-v2.rst
+++ b/Documentation/admin-guide/cgroup-v2.rst
@@ -1666,6 +1666,12 @@ The following nested keys are defined.
 		Amount of memory used for storing in-kernel data
 		structures.
 
+	  dmabuf (npn)
+		Amount of memory used for exported DMA buffers allocated by or on
+		behalf of the cgroup, this currently includes system heap
+		allocations. Stays with the cgroup regardless of how the buffer
+		is shared, unless moved with DMA_BUF_IOCTL_XFER_CHARGE.
+
 	  workingset_refault_anon
 		Number of refaults of previously evicted anonymous pages.
 
diff --git a/drivers/dma-buf/dma-buf.c b/drivers/dma-buf/dma-buf.c
index 36cdc342627ee8..5d4b55b67e995c 100644
--- a/drivers/dma-buf/dma-buf.c
+++ b/drivers/dma-buf/dma-buf.c
@@ -14,6 +14,7 @@
 #include <linux/fs.h>
 #include <linux/slab.h>
 #include <linux/dma-buf.h>
+#include <linux/memcontrol.h>
 #include <linux/dma-fence.h>
 #include <linux/dma-fence-unwrap.h>
 #include <linux/anon_inodes.h>
@@ -182,6 +183,8 @@ static void dma_buf_release(struct dentry *dentry)
 
 	dmabuf->ops->release(dmabuf);
 
+	mem_cgroup_uncharge_dmabuf(dmabuf);
+
 	if (dmabuf->resv == (struct dma_resv *)&dmabuf[1])
 		dma_resv_fini(dmabuf->resv);
 
@@ -537,6 +540,42 @@ static long dma_buf_import_sync_file(struct dma_buf *dmabuf,
 }
 #endif
 
+/* Transfer a dma-buf's memcg charge; see struct dma_buf_transfer_charge */
+static long dma_buf_xfer_charge(struct dma_buf *dmabuf,
+				const void __user *user_data)
+{
+	struct dma_buf_transfer_charge arg;
+	struct obj_cgroup *objcg;
+	unsigned int nr_pages;
+	int ret = 0;
+
+	if (copy_from_user(&arg, user_data, sizeof(arg)))
+		return -EFAULT;
+
+	if (arg.flags != 0)
+		return -EINVAL;
+
+	objcg = get_obj_cgroup_from_fd(arg.charge_fd);
+	if (IS_ERR(objcg))
+		return PTR_ERR(objcg);
+
+	dma_resv_lock(dmabuf->resv, NULL);
+
+	if (!dmabuf->objcg) {
+		ret = -EOPNOTSUPP;
+		goto out;
+	}
+
+	nr_pages = PAGE_ALIGN(dmabuf->size) >> PAGE_SHIFT;
+	if (!obj_cgroup_transfer_charge(&dmabuf->objcg, objcg, MEMCG_DMABUF, nr_pages))
+		ret = -ENOMEM;
+
+out:
+	dma_resv_unlock(dmabuf->resv);
+	obj_cgroup_put(objcg);
+	return ret;
+}
+
 static long dma_buf_ioctl(struct file *file,
 			  unsigned int cmd, unsigned long arg)
 {
@@ -587,6 +626,9 @@ static long dma_buf_ioctl(struct file *file,
 		return dma_buf_import_sync_file(dmabuf, (const void __user *)arg);
 #endif
 
+	case DMA_BUF_IOCTL_XFER_CHARGE:
+		return dma_buf_xfer_charge(dmabuf, (const void __user *)arg);
+
 	default:
 		return -ENOTTY;
 	}
@@ -747,6 +789,7 @@ struct dma_buf *dma_buf_export(const struct dma_buf_export_info *exp_info)
 	dmabuf->size = exp_info->size;
 	dmabuf->exp_name = exp_info->exp_name;
 	dmabuf->owner = exp_info->owner;
+	dmabuf->objcg = exp_info->objcg;
 	spin_lock_init(&dmabuf->name_lock);
 	init_waitqueue_head(&dmabuf->poll);
 	dmabuf->cb_in.poll = dmabuf->cb_out.poll = &dmabuf->poll;
@@ -768,6 +811,8 @@ struct dma_buf *dma_buf_export(const struct dma_buf_export_info *exp_info)
 
 	DMA_BUF_TRACE(trace_dma_buf_export, dmabuf);
 
+	mem_cgroup_commit_dmabuf(dmabuf);
+
 	return dmabuf;
 
 err_file:
diff --git a/drivers/dma-buf/dma-heap.c b/drivers/dma-buf/dma-heap.c
index 8a6c2b6e0cc608..2f53bc95a45a81 100644
--- a/drivers/dma-buf/dma-heap.c
+++ b/drivers/dma-buf/dma-heap.c
@@ -10,6 +10,7 @@
 #include <linux/device.h>
 #include <linux/dma-buf.h>
 #include <linux/dma-heap.h>
+#include <linux/memcontrol.h>
 #include <linux/err.h>
 #include <linux/export.h>
 #include <linux/list.h>
@@ -78,6 +79,7 @@ static struct dma_buf *dma_heap_ioctl_allocate(struct file *file, void *data)
 	struct dma_heap_allocation_data *heap_allocation = data;
 	struct dma_heap *heap = file->private_data;
 	struct dma_buf *dmabuf;
+	struct obj_cgroup *objcg = NULL;
 	int fd;
 	size_t len;
 
@@ -90,15 +92,34 @@ static struct dma_buf *dma_heap_ioctl_allocate(struct file *file, void *data)
 	if (heap_allocation->heap_flags & ~DMA_HEAP_VALID_HEAP_FLAGS)
 		return ERR_PTR(-EINVAL);
 
+	if (heap_allocation->__padding != 0)
+		return ERR_PTR(-EINVAL);
+
+	if (heap_allocation->charge_fd) {
+		objcg = get_obj_cgroup_from_fd(heap_allocation->charge_fd);
+		if (IS_ERR(objcg))
+			return ERR_CAST(objcg);
+	}
+
+	if (!objcg && mem_accounting && !mem_cgroup_disabled())
+		objcg = get_obj_cgroup_from_current();
+
 	len = PAGE_ALIGN(heap_allocation->len);
-	if (!len)
+	if (!len) {
+		obj_cgroup_put(objcg);
 		return ERR_PTR(-EINVAL);
+	}
 
 	dmabuf = heap->ops->allocate(heap, len, heap_allocation->fd_flags,
-				     heap_allocation->heap_flags);
+				     heap_allocation->heap_flags, objcg);
 
-	if (IS_ERR(dmabuf))
+	if (IS_ERR(dmabuf)) {
+		obj_cgroup_put(objcg);
 		return dmabuf;
+	}
+
+	if (!dmabuf->objcg)
+		obj_cgroup_put(objcg);
 
 	fd = get_unused_fd_flags(heap_allocation->fd_flags);
 	if (fd < 0) {
diff --git a/drivers/dma-buf/heaps/cma_heap.c b/drivers/dma-buf/heaps/cma_heap.c
index 3fb4b946c91a6e..6c08dc25b17725 100644
--- a/drivers/dma-buf/heaps/cma_heap.c
+++ b/drivers/dma-buf/heaps/cma_heap.c
@@ -281,7 +281,8 @@ static const struct dma_buf_ops cma_heap_buf_ops = {
 static struct dma_buf *cma_heap_allocate(struct dma_heap *heap,
 					 unsigned long len,
 					 u32 fd_flags,
-					 u64 heap_flags)
+					 u64 heap_flags,
+					 struct obj_cgroup *objcg)
 {
 	struct cma_heap *cma_heap = dma_heap_get_drvdata(heap);
 	struct cma_heap_buffer *buffer;
diff --git a/drivers/dma-buf/heaps/system_heap.c b/drivers/dma-buf/heaps/system_heap.c
index c8959eadc71d18..ad94bb5be73670 100644
--- a/drivers/dma-buf/heaps/system_heap.c
+++ b/drivers/dma-buf/heaps/system_heap.c
@@ -17,6 +17,7 @@
 #include <linux/err.h>
 #include <linux/highmem.h>
 #include <linux/mem_encrypt.h>
+#include <linux/memcontrol.h>
 #include <linux/mm.h>
 #include <linux/set_memory.h>
 #include <linux/module.h>
@@ -388,8 +389,6 @@ static struct page *alloc_largest_available(unsigned long size,
 		if (max_order < orders[i])
 			continue;
 		flags = order_flags[i];
-		if (mem_accounting)
-			flags |= __GFP_ACCOUNT;
 		page = alloc_pages(flags, orders[i]);
 		if (!page)
 			continue;
@@ -401,11 +400,13 @@ static struct page *alloc_largest_available(unsigned long size,
 static struct dma_buf *system_heap_allocate(struct dma_heap *heap,
 					    unsigned long len,
 					    u32 fd_flags,
-					    u64 heap_flags)
+					    u64 heap_flags,
+					    struct obj_cgroup *objcg)
 {
 	struct system_heap_buffer *buffer;
 	DEFINE_DMA_BUF_EXPORT_INFO(exp_info);
 	unsigned long size_remaining = len;
+	unsigned long nr_pages = PAGE_ALIGN(len) >> PAGE_SHIFT;
 	unsigned int max_order = orders[0];
 	struct system_heap_priv *priv = dma_heap_get_drvdata(heap);
 	bool cc_shared = priv->cc_shared;
@@ -416,10 +417,15 @@ static struct dma_buf *system_heap_allocate(struct dma_heap *heap,
 	struct page *page, *tmp_page;
 	int i, ret = -ENOMEM;
 
-	buffer = kzalloc_obj(*buffer);
-	if (!buffer)
+	if (!obj_cgroup_reserve_dmabuf(objcg, GFP_KERNEL, nr_pages))
 		return ERR_PTR(-ENOMEM);
 
+	buffer = kzalloc_obj(*buffer);
+	if (!buffer) {
+		ret = -ENOMEM;
+		goto cancel_charge;
+	}
+
 	INIT_LIST_HEAD(&buffer->attachments);
 	mutex_init(&buffer->lock);
 	buffer->heap = heap;
@@ -473,6 +479,7 @@ static struct dma_buf *system_heap_allocate(struct dma_heap *heap,
 	exp_info.size = buffer->len;
 	exp_info.flags = fd_flags;
 	exp_info.priv = buffer;
+	exp_info.objcg = objcg;
 	dmabuf = dma_buf_export(&exp_info);
 	if (IS_ERR(dmabuf)) {
 		ret = PTR_ERR(dmabuf);
@@ -498,6 +505,8 @@ static struct dma_buf *system_heap_allocate(struct dma_heap *heap,
 	list_for_each_entry_safe(page, tmp_page, &pages, lru)
 		__free_pages(page, compound_order(page));
 	kfree(buffer);
+cancel_charge:
+	obj_cgroup_cancel_dmabuf(objcg, nr_pages);
 
 	return ERR_PTR(ret);
 }
diff --git a/drivers/tee/tee_heap.c b/drivers/tee/tee_heap.c
index 007c001565204b..83fd14a0aaec2d 100644
--- a/drivers/tee/tee_heap.c
+++ b/drivers/tee/tee_heap.c
@@ -167,7 +167,8 @@ static const struct dma_buf_ops tee_heap_buf_ops = {
 
 static struct dma_buf *tee_dma_heap_alloc(struct dma_heap *heap,
 					  unsigned long len, u32 fd_flags,
-					  u64 heap_flags)
+					  u64 heap_flags,
+					  struct obj_cgroup *objcg)
 {
 	struct tee_dma_heap *h = dma_heap_get_drvdata(heap);
 	DEFINE_DMA_BUF_EXPORT_INFO(exp_info);
diff --git a/include/linux/dma-buf.h b/include/linux/dma-buf.h
index d15b2b31d3c91e..916d73ae6a511f 100644
--- a/include/linux/dma-buf.h
+++ b/include/linux/dma-buf.h
@@ -27,6 +27,7 @@
 struct device;
 struct dma_buf;
 struct dma_buf_attachment;
+struct obj_cgroup;
 
 /**
  * struct dma_buf_ops - operations possible on struct dma_buf
@@ -429,6 +430,9 @@ struct dma_buf {
 
 		__poll_t active;
 	} cb_in, cb_out;
+
+	/** @objcg: object cgroup to which this buffer is currently attributed */
+	struct obj_cgroup *objcg;
 };
 
 /**
@@ -501,6 +505,11 @@ struct dma_buf_attachment {
  * @flags:	mode flags for the file
  * @resv:	reservation-object, NULL to allocate default one
  * @priv:	Attach private data of allocator to this buffer
+ * @objcg:	object cgroup to charge for this buffer's memory. Set only for
+ *		buffers backed by system memory, not accounted elsewhere, where
+ *		@size reflects the actual allocation in bytes. The buffer takes
+ *		over the caller's reference. Enables charge transfer via
+ *		DMA_BUF_IOCTL_XFER_CHARGE.
  *
  * This structure holds the information required to export the buffer. Used
  * with dma_buf_export() only.
@@ -513,6 +522,7 @@ struct dma_buf_export_info {
 	int flags;
 	struct dma_resv *resv;
 	void *priv;
+	struct obj_cgroup *objcg;
 };
 
 /**
diff --git a/include/linux/dma-heap.h b/include/linux/dma-heap.h
index 648328a64b27ea..b5a42b49c68d04 100644
--- a/include/linux/dma-heap.h
+++ b/include/linux/dma-heap.h
@@ -12,6 +12,7 @@
 #include <linux/types.h>
 
 struct dma_heap;
+struct obj_cgroup;
 
 /**
  * struct dma_heap_ops - ops to operate on a given heap
@@ -23,7 +24,8 @@ struct dma_heap_ops {
 	struct dma_buf *(*allocate)(struct dma_heap *heap,
 				    unsigned long len,
 				    u32 fd_flags,
-				    u64 heap_flags);
+				    u64 heap_flags,
+				    struct obj_cgroup *objcg);
 };
 
 /**
diff --git a/include/linux/lsm_hook_defs.h b/include/linux/lsm_hook_defs.h
index 87d9d06710cb26..3b254b4e60ec74 100644
--- a/include/linux/lsm_hook_defs.h
+++ b/include/linux/lsm_hook_defs.h
@@ -43,6 +43,8 @@ LSM_HOOK(int, 0, capset, struct cred *new, const struct cred *old,
 	 const kernel_cap_t *permitted)
 LSM_HOOK(int, 0, capable, const struct cred *cred, struct user_namespace *ns,
 	 int cap, unsigned int opts)
+LSM_HOOK(int, 0, memcg_charge_task, const struct cred *from, const struct cred *to)
+LSM_HOOK(int, 0, memcg_charge_cgroup, const struct cred *cred, const struct file *file)
 LSM_HOOK(int, 0, quotactl, int cmds, int type, int id, const struct super_block *sb)
 LSM_HOOK(int, 0, quota_on, struct dentry *dentry)
 LSM_HOOK(int, 0, syslog, int type)
diff --git a/include/linux/memcontrol.h b/include/linux/memcontrol.h
index 69e1bcc67c588d..37c81be349b89d 100644
--- a/include/linux/memcontrol.h
+++ b/include/linux/memcontrol.h
@@ -10,6 +10,9 @@
 
 #ifndef _LINUX_MEMCONTROL_H
 #define _LINUX_MEMCONTROL_H
+
+struct dma_buf;
+
 #include <linux/cgroup.h>
 #include <linux/vm_event_item.h>
 #include <linux/hardirq.h>
@@ -41,6 +44,7 @@ enum memcg_stat_item {
 	MEMCG_ZSWAP_B,
 	MEMCG_ZSWAPPED,
 	MEMCG_ZSWAP_INCOMP,
+	MEMCG_DMABUF,
 	MEMCG_NR_STAT,
 };
 
@@ -688,6 +692,9 @@ int mem_cgroup_charge_hugetlb(struct folio *folio, struct mm_struct *mm,
 int mem_cgroup_swapin_charge_folio(struct folio *folio, unsigned short id,
 				   struct mm_struct *mm, gfp_t gfp);
 
+bool obj_cgroup_reserve_dmabuf(struct obj_cgroup *objcg, gfp_t gfp,
+			       unsigned long nr_pages);
+
 void __mem_cgroup_uncharge(struct folio *folio);
 
 /**
@@ -703,6 +710,11 @@ static inline void mem_cgroup_uncharge(struct folio *folio)
 	__mem_cgroup_uncharge(folio);
 }
 
+void obj_cgroup_cancel_dmabuf(struct obj_cgroup *objcg, unsigned long nr_pages);
+
+void mem_cgroup_commit_dmabuf(struct dma_buf *dmabuf);
+void mem_cgroup_uncharge_dmabuf(struct dma_buf *dmabuf);
+
 void __mem_cgroup_uncharge_folios(struct folio_batch *folios);
 static inline void mem_cgroup_uncharge_folios(struct folio_batch *folios)
 {
@@ -1203,10 +1215,30 @@ static inline int mem_cgroup_swapin_charge_folio(struct folio *folio,
 	return 0;
 }
 
+static inline bool obj_cgroup_reserve_dmabuf(struct obj_cgroup *objcg,
+					     gfp_t gfp,
+					     unsigned long nr_pages)
+{
+	return true;
+}
+
+static inline void obj_cgroup_cancel_dmabuf(struct obj_cgroup *objcg,
+					    unsigned long nr_pages)
+{
+}
+
+static inline void mem_cgroup_commit_dmabuf(struct dma_buf *dmabuf)
+{
+}
+
 static inline void mem_cgroup_uncharge(struct folio *folio)
 {
 }
 
+static inline void mem_cgroup_uncharge_dmabuf(struct dma_buf *dmabuf)
+{
+}
+
 static inline void mem_cgroup_uncharge_folios(struct folio_batch *folios)
 {
 }
@@ -1780,6 +1812,7 @@ void __memcg_kmem_uncharge_page(struct page *page, int order);
  */
 struct obj_cgroup *current_obj_cgroup(void);
 struct obj_cgroup *get_obj_cgroup_from_folio(const struct folio *folio);
+struct obj_cgroup *get_obj_cgroup_from_fd(int fd);
 
 static inline struct obj_cgroup *get_obj_cgroup_from_current(void)
 {
@@ -1794,6 +1827,11 @@ static inline struct obj_cgroup *get_obj_cgroup_from_current(void)
 int obj_cgroup_charge(struct obj_cgroup *objcg, gfp_t gfp, size_t size);
 void obj_cgroup_uncharge(struct obj_cgroup *objcg, size_t size);
 
+bool obj_cgroup_transfer_charge(struct obj_cgroup **ptr_objcg,
+				struct obj_cgroup *new_objcg,
+				enum memcg_stat_item item,
+				unsigned int nr_pages);
+
 extern struct static_key_false memcg_bpf_enabled_key;
 static inline bool memcg_bpf_enabled(void)
 {
@@ -1887,6 +1925,24 @@ static inline struct obj_cgroup *get_obj_cgroup_from_folio(const struct folio *f
 	return NULL;
 }
 
+static inline struct obj_cgroup *get_obj_cgroup_from_fd(int fd)
+{
+	return ERR_PTR(-EOPNOTSUPP);
+}
+
+static inline struct obj_cgroup *get_obj_cgroup_from_current(void)
+{
+	return NULL;
+}
+
+static inline bool obj_cgroup_transfer_charge(struct obj_cgroup **ptr_objcg,
+					      struct obj_cgroup *new_objcg,
+					      enum memcg_stat_item item,
+					      unsigned int nr_pages)
+{
+	return true;
+}
+
 static inline bool memcg_bpf_enabled(void)
 {
 	return false;
diff --git a/include/linux/security.h b/include/linux/security.h
index 40831fab54709a..d1cd6c324ffd73 100644
--- a/include/linux/security.h
+++ b/include/linux/security.h
@@ -352,6 +352,9 @@ int security_capable(const struct cred *cred,
 		       struct user_namespace *ns,
 		       int cap,
 		       unsigned int opts);
+int security_memcg_charge_task(const struct cred *from, const struct cred *to);
+int security_memcg_charge_cgroup(const struct cred *cred,
+				 const struct file *file);
 int security_quotactl(int cmds, int type, int id, const struct super_block *sb);
 int security_quota_on(struct dentry *dentry);
 int security_syslog(int type);
@@ -710,6 +713,18 @@ static inline int security_capable(const struct cred *cred,
 	return cap_capable(cred, ns, cap, opts);
 }
 
+static inline int security_memcg_charge_task(const struct cred *from,
+					     const struct cred *to)
+{
+	return 0;
+}
+
+static inline int security_memcg_charge_cgroup(const struct cred *cred,
+					       const struct file *file)
+{
+	return 0;
+}
+
 static inline int security_quotactl(int cmds, int type, int id,
 				     const struct super_block *sb)
 {
diff --git a/include/uapi/linux/dma-buf.h b/include/uapi/linux/dma-buf.h
index e827c9d20c5d35..0aaf2e7d593b9c 100644
--- a/include/uapi/linux/dma-buf.h
+++ b/include/uapi/linux/dma-buf.h
@@ -168,6 +168,31 @@ struct dma_buf_import_sync_file {
 	__s32 fd;
 };
 
+/**
+ * struct dma_buf_transfer_charge - Transfer a dma-buf's memcg charge
+ *
+ * Any holder of a dma-buf file descriptor can perform a
+ * DMA_BUF_IOCTL_XFER_CHARGE to attribute the buffer's memory
+ * cost to a specific cgroup, or move it from one cgroup to
+ * another.  The ioctl charges the new cgroup before uncharging
+ * the old one atomically.  On failure the original charge is
+ * preserved.  If the buffer has no existing memcg charge, the
+ * ioctl returns -EOPNOTSUPP.
+ */
+struct dma_buf_transfer_charge {
+	/** @flags: Reserved, must be zero */
+	__u32 flags; /* unused for now */
+	/**
+	 * @charge_fd: File descriptor identifying the target cgroup.
+	 *
+	 * May be either a pidfd, in which case the charge moves to the
+	 * memory cgroup of the referenced process, or a cgroupfd obtained
+	 * by opening a cgroup v2 directory, in which case the charge moves
+	 * directly to that cgroup's memory controller.
+	 */
+	__u32 charge_fd;
+};
+
 #define DMA_BUF_BASE		'b'
 #define DMA_BUF_IOCTL_SYNC	_IOW(DMA_BUF_BASE, 0, struct dma_buf_sync)
 
@@ -179,5 +204,6 @@ struct dma_buf_import_sync_file {
 #define DMA_BUF_SET_NAME_B	_IOW(DMA_BUF_BASE, 1, __u64)
 #define DMA_BUF_IOCTL_EXPORT_SYNC_FILE	_IOWR(DMA_BUF_BASE, 2, struct dma_buf_export_sync_file)
 #define DMA_BUF_IOCTL_IMPORT_SYNC_FILE	_IOW(DMA_BUF_BASE, 3, struct dma_buf_import_sync_file)
+#define DMA_BUF_IOCTL_XFER_CHARGE	_IOW(DMA_BUF_BASE, 4, struct dma_buf_transfer_charge)
 
 #endif
diff --git a/include/uapi/linux/dma-heap.h b/include/uapi/linux/dma-heap.h
index a4cf716a49fa68..bfcd1c25bc7ea0 100644
--- a/include/uapi/linux/dma-heap.h
+++ b/include/uapi/linux/dma-heap.h
@@ -29,6 +29,11 @@
  *			handle to the allocated dma-buf
  * @fd_flags:		file descriptor flags used when allocating
  * @heap_flags:		flags passed to heap
+ * @charge_fd:		optional pidfd or cgroupfd whose cgroup should be
+ *			charged for this allocation; 0 means charge the calling
+ *			process's cgroup when the mem_accounting module parameter
+ *			is enabled, or skip charging otherwise
+ * @__padding:		reserved, must be zero
  *
  * Provided by userspace as an argument to the ioctl
  */
@@ -37,6 +42,8 @@ struct dma_heap_allocation_data {
 	__u32 fd;
 	__u32 fd_flags;
 	__u64 heap_flags;
+	__u32 charge_fd;
+	__u32 __padding;
 };
 
 #define DMA_HEAP_IOC_MAGIC		'H'
diff --git a/mm/memcontrol.c b/mm/memcontrol.c
index a05d9a8baa1b6b..693f0b2877bf16 100644
--- a/mm/memcontrol.c
+++ b/mm/memcontrol.c
@@ -49,6 +49,7 @@
 #include <linux/slab.h>
 #include <linux/swapops.h>
 #include <linux/spinlock.h>
+#include <linux/file.h>
 #include <linux/fs.h>
 #include <linux/seq_file.h>
 #include <linux/vmpressure.h>
@@ -59,6 +60,7 @@
 #include <linux/lockdep.h>
 #include <linux/resume_user_mode.h>
 #include <linux/psi.h>
+#include <linux/security.h>
 #include <linux/seq_buf.h>
 #include <linux/sched/isolation.h>
 #include <linux/kmemleak.h>
@@ -70,6 +72,7 @@
 #include <net/ip.h>
 #include "slab.h"
 #include "memcontrol-v1.h"
+#include <linux/dma-buf.h>
 
 #include <linux/uaccess.h>
 
@@ -459,6 +462,7 @@ static const unsigned int memcg_stat_items[] = {
 	MEMCG_ZSWAP_B,
 	MEMCG_ZSWAPPED,
 	MEMCG_ZSWAP_INCOMP,
+	MEMCG_DMABUF,
 };
 
 #define NR_MEMCG_NODE_STAT_ITEMS ARRAY_SIZE(memcg_node_stat_items)
@@ -1644,6 +1648,7 @@ static const struct memory_stat memory_stats[] = {
 #ifdef CONFIG_HUGETLB_PAGE
 	{ "hugetlb",			NR_HUGETLB			},
 #endif
+	{ "dmabuf",			MEMCG_DMABUF			},
 
 	/* The memory events */
 	{ "workingset_refault_anon",	WORKINGSET_REFAULT_ANON		},
@@ -3165,6 +3170,163 @@ struct obj_cgroup *get_obj_cgroup_from_folio(const struct folio *folio)
 	return objcg;
 }
 
+/*
+ * Charging outside the caller's own memcg subtree can escape its limits
+ * or push reclaim and OOM onto other cgroups.
+ */
+static bool mem_cgroup_may_charge(struct mem_cgroup *memcg)
+{
+	struct mem_cgroup *self = get_mem_cgroup_from_current();
+	bool ret = mem_cgroup_is_descendant(memcg, self);
+
+	mem_cgroup_put(self);
+	return ret || capable(CAP_SYS_RESOURCE);
+}
+
+/**
+ * get_obj_cgroup_from_fd - resolve an object cgroup from a cgroupfd or pidfd
+ * @fd: file descriptor (cgroupfd or pidfd)
+ *
+ * Tries @fd as a cgroupfd first; if that fails, tries it as a pidfd. Only
+ * cgroup2 directories are accepted as cgroupfds, any other fd is tried as a
+ * pidfd.
+ *
+ * Resolving a memcg outside the caller's own subtree requires CAP_SYS_RESOURCE.
+ *
+ * On success returns a referenced objcg pointer. On failure returns
+ * an ERR_PTR.
+ */
+struct obj_cgroup *get_obj_cgroup_from_fd(int fd)
+{
+	struct cgroup_subsys_state *css;
+	const struct cred *tcred;
+	struct obj_cgroup *objcg;
+	struct mem_cgroup *memcg;
+	struct task_struct *task;
+	unsigned int pidfd_flags;
+	int ret;
+
+	if (mem_cgroup_disabled())
+		return ERR_PTR(-EOPNOTSUPP);
+
+	CLASS(fd_raw, f)(fd);
+	if (fd_empty(f))
+		return ERR_PTR(-EBADF);
+
+	css = css_tryget_online_from_dir(fd_file(f)->f_path.dentry,
+					 &memory_cgrp_subsys);
+	if (!IS_ERR(css) && !cgroup_on_dfl(css->cgroup)) {
+		css_put(css);
+		css = ERR_PTR(-EBADF);
+	}
+
+	if (!IS_ERR(css)) {
+		/* fd is a cgroupfd */
+		ret = security_memcg_charge_cgroup(current_cred(), fd_file(f));
+		if (ret) {
+			css_put(css);
+			return ERR_PTR(ret);
+		}
+	} else {
+		if (PTR_ERR(css) != -EBADF)
+			return ERR_CAST(css);
+
+		/* fd is a pidfd */
+		task = pidfd_get_task(fd, &pidfd_flags);
+		if (IS_ERR(task))
+			return ERR_CAST(task);
+
+		tcred = get_task_cred(task);
+		ret = security_memcg_charge_task(current_cred(), tcred);
+		put_cred(tcred);
+		if (ret) {
+			put_task_struct(task);
+			return ERR_PTR(ret);
+		}
+
+		rcu_read_lock();
+		css = task_css(task, memory_cgrp_id);
+		put_task_struct(task);
+		if (!css || !css_tryget_online(css)) {
+			rcu_read_unlock();
+			return ERR_PTR(-ENOENT);
+		}
+		rcu_read_unlock();
+	}
+
+	memcg = mem_cgroup_from_css(css);
+	if (!mem_cgroup_may_charge(memcg)) {
+		mem_cgroup_put(memcg);
+		return ERR_PTR(-EPERM);
+	}
+
+	objcg = get_obj_cgroup_from_memcg(memcg, numa_node_id());
+	mem_cgroup_put(memcg);
+
+	if (!objcg)
+		return ERR_PTR(-ENOENT);
+
+	return objcg;
+}
+
+/**
+ * obj_cgroup_transfer_charge - move a charge between object cgroups
+ * @ptr_objcg: pointer to the object cgroup to transfer from
+ * @new_objcg: target object cgroup; caller must hold a reference
+ * @item: memcg stat counter to adjust; must not be a node stat
+ * @nr_pages: number of pages to transfer
+ *
+ * Transfers @nr_pages of charge from *@ptr_objcg to @new_objcg and, on
+ * success, stores @new_objcg in *@ptr_objcg. Does nothing if both resolve
+ * to the same memcg; *@ptr_objcg is left untouched in that case.
+ *
+ * Updates to *@ptr_objcg must be serialized by the caller.
+ * Returns %true on success, %false if the charge against @new_objcg
+ * failed.
+ */
+bool obj_cgroup_transfer_charge(struct obj_cgroup **ptr_objcg,
+				struct obj_cgroup *new_objcg,
+				enum memcg_stat_item item,
+				unsigned int nr_pages)
+{
+	struct obj_cgroup *old_objcg = *ptr_objcg;
+	struct mem_cgroup *old_memcg = NULL, *new_memcg;
+	bool ret = true;
+
+	if (!new_objcg || mem_cgroup_disabled())
+		return true;
+
+	new_memcg = get_mem_cgroup_from_objcg(new_objcg);
+	if (old_objcg)
+		old_memcg = get_mem_cgroup_from_objcg(old_objcg);
+
+	if (old_memcg == new_memcg)
+		goto out;
+
+	if (try_charge(new_memcg, GFP_KERNEL, nr_pages)) {
+		ret = false;
+		goto out;
+	}
+
+	mod_memcg_state(new_memcg, item, nr_pages);
+
+	if (old_objcg) {
+		/* Uncharge old cgroup */
+		mod_memcg_state(old_memcg, item, -nr_pages);
+		if (!mem_cgroup_is_root(old_memcg))
+			refill_stock(old_memcg, nr_pages);
+	}
+
+	obj_cgroup_get(new_objcg);
+	*ptr_objcg = new_objcg;
+	obj_cgroup_put(old_objcg);
+
+out:
+	mem_cgroup_put(new_memcg);
+	mem_cgroup_put(old_memcg);
+	return ret;
+}
+
 #ifdef CONFIG_MEMCG_NMI_SAFETY_REQUIRES_ATOMIC
 static inline void account_kmem_nmi_safe(struct mem_cgroup *memcg, int val)
 {
@@ -5821,6 +5983,115 @@ void mem_cgroup_flush_workqueue(void)
 	flush_workqueue(memcg_wq);
 }
 
+/**
+ * obj_cgroup_reserve_dmabuf - charge an object cgroup for a dma-buf allocation
+ * @objcg: object cgroup to charge (may be %NULL)
+ * @gfp_mask: reclaim mode
+ * @nr_pages: number of pages to charge
+ *
+ * Charges @nr_pages against @objcg. Call this before allocating pages so
+ * the cgroup limit is enforced up front. On success the caller must
+ * finalize the charge with the MEMCG_DMABUF stat update, or call
+ * obj_cgroup_cancel_dmabuf() to undo it.
+ *
+ * @nr_pages is derived from the buffer size, which may be controlled by
+ * userspace, so it is taken as unsigned long and rejected above what
+ * a single memcg charge can account.
+ *
+ * Returns %true on success, %false if @nr_pages is too large or the
+ * charge would exceed the limit.
+ */
+bool obj_cgroup_reserve_dmabuf(struct obj_cgroup *objcg, gfp_t gfp_mask,
+			       unsigned long nr_pages)
+{
+	struct mem_cgroup *memcg;
+	int ret;
+
+	if (!objcg || mem_cgroup_disabled())
+		return true;
+
+	/* a single memcg charge accounts at most INT_MAX pages */
+	if (nr_pages > INT_MAX)
+		return false;
+
+	memcg = get_mem_cgroup_from_objcg(objcg);
+	ret = try_charge(memcg, gfp_mask, nr_pages);
+	mem_cgroup_put(memcg);
+	return !ret;
+}
+EXPORT_SYMBOL_GPL(obj_cgroup_reserve_dmabuf);
+
+/**
+ * obj_cgroup_cancel_dmabuf - undo a dma-buf charge
+ * @objcg: object cgroup to uncharge (may be %NULL)
+ * @nr_pages: same value passed to obj_cgroup_reserve_dmabuf()
+ *
+ * Returns @nr_pages of charge to @objcg. Use when the allocation fails
+ * after obj_cgroup_reserve_dmabuf().
+ */
+void obj_cgroup_cancel_dmabuf(struct obj_cgroup *objcg, unsigned long nr_pages)
+{
+	struct mem_cgroup *memcg;
+
+	if (!objcg)
+		return;
+
+	memcg = get_mem_cgroup_from_objcg(objcg);
+	if (!mem_cgroup_is_root(memcg))
+		refill_stock(memcg, nr_pages);
+	mem_cgroup_put(memcg);
+}
+EXPORT_SYMBOL_GPL(obj_cgroup_cancel_dmabuf);
+
+/**
+ * mem_cgroup_commit_dmabuf - finalize a dma-buf charge
+ * @dmabuf: buffer whose charge is being finalized
+ *
+ * Adds @dmabuf's size to the %MEMCG_DMABUF stat of the cgroup its object
+ * cgroup currently resolves to. Call after obj_cgroup_reserve_dmabuf()
+ * succeeded and the buffer is about to be exported. Safe to call when
+ * @dmabuf->objcg is %NULL.
+ */
+void mem_cgroup_commit_dmabuf(struct dma_buf *dmabuf)
+{
+	struct mem_cgroup *memcg;
+
+	if (!dmabuf->objcg)
+		return;
+
+	memcg = get_mem_cgroup_from_objcg(dmabuf->objcg);
+	mod_memcg_state(memcg, MEMCG_DMABUF,
+			PAGE_ALIGN(dmabuf->size) >> PAGE_SHIFT);
+	mem_cgroup_put(memcg);
+}
+
+/**
+ * mem_cgroup_uncharge_dmabuf - uncharge a dma-buf from its object cgroup
+ * @dmabuf: buffer to uncharge
+ *
+ * Reverses a finalized dma-buf charge. Drops the object cgroup
+ * reference stored in @dmabuf->objcg and clears the pointer.
+ * Safe to call when @dmabuf->objcg is %NULL.
+ */
+void mem_cgroup_uncharge_dmabuf(struct dma_buf *dmabuf)
+{
+	struct obj_cgroup *objcg = dmabuf->objcg;
+	struct mem_cgroup *memcg;
+	unsigned long nr_pages;
+
+	if (!objcg)
+		return;
+
+	memcg = get_mem_cgroup_from_objcg(objcg);
+	nr_pages = PAGE_ALIGN(dmabuf->size) >> PAGE_SHIFT;
+	mod_memcg_state(memcg, MEMCG_DMABUF, -nr_pages);
+	if (!mem_cgroup_is_root(memcg))
+		refill_stock(memcg, nr_pages);
+	mem_cgroup_put(memcg);
+	obj_cgroup_put(objcg);
+	dmabuf->objcg = NULL;
+}
+
 static int __init cgroup_memory(char *s)
 {
 	char *token;
diff --git a/security/security.c b/security/security.c
index f6583d50739592..925b6c00305943 100644
--- a/security/security.c
+++ b/security/security.c
@@ -674,6 +674,41 @@ int security_capable(const struct cred *cred,
 	return call_int_hook(capable, cred, ns, cap, opts);
 }
 
+/**
+ * security_memcg_charge_task() - Check if cross-cgroup memory charging is allowed
+ * @from: credentials of the process requesting the charge
+ * @to: credentials of the process to charge
+ *
+ * Check whether the process with credentials @from is allowed to charge
+ * memory to the cgroup of the process with credentials @to.
+ *
+ * Return: Returns 0 if permission is granted.
+ */
+int security_memcg_charge_task(const struct cred *from, const struct cred *to)
+{
+	return call_int_hook(memcg_charge_task, from, to);
+}
+
+/**
+ * security_memcg_charge_cgroup() - Check if charging memory to a cgroup is allowed
+ * @cred: credentials of the process requesting the charge
+ * @file: open file of the cgroup directory to charge
+ *
+ * Check whether the process with credentials @cred is allowed to charge
+ * memory to the cgroup referenced by @file. Called when userspace passes a
+ * cgroupfd to identify the charge target instead of a pidfd. @file is the
+ * file the cgroup was resolved from, so the check applies to the object
+ * that is actually charged. It must have been already validated by the
+ * caller.
+ *
+ * Return: Returns 0 if permission is granted.
+ */
+int security_memcg_charge_cgroup(const struct cred *cred,
+				 const struct file *file)
+{
+	return call_int_hook(memcg_charge_cgroup, cred, file);
+}
+
 /**
  * security_quotactl() - Check if a quotactl() syscall is allowed for this fs
  * @cmds: commands
diff --git a/security/selinux/hooks.c b/security/selinux/hooks.c
index 6168dd5f91c227..fcf0b03a588dfe 100644
--- a/security/selinux/hooks.c
+++ b/security/selinux/hooks.c
@@ -2204,6 +2204,21 @@ static int selinux_capable(const struct cred *cred, struct user_namespace *ns,
 	return cred_has_capability(cred, cap, opts, ns == &init_user_ns);
 }
 
+static int selinux_memcg_charge_task(const struct cred *from, const struct cred *to)
+{
+	return avc_has_perm(cred_sid(from), cred_sid(to),
+			    SECCLASS_PROCESS2, PROCESS2__CHARGE_TO, NULL);
+}
+
+static int selinux_memcg_charge_cgroup(const struct cred *cred,
+				       const struct file *file)
+{
+	struct inode_security_struct *isec = inode_security(file_inode(file));
+
+	return avc_has_perm(cred_sid(cred), isec->sid, SECCLASS_CGROUP,
+			    CGROUP__CHARGE_TO, NULL);
+}
+
 static int selinux_quotactl(int cmds, int type, int id, const struct super_block *sb)
 {
 	const struct cred *cred = current_cred();
@@ -7681,6 +7696,8 @@ static struct security_hook_list selinux_hooks[] __ro_after_init = {
 	LSM_HOOK_INIT(capget, selinux_capget),
 	LSM_HOOK_INIT(capset, selinux_capset),
 	LSM_HOOK_INIT(capable, selinux_capable),
+	LSM_HOOK_INIT(memcg_charge_task, selinux_memcg_charge_task),
+	LSM_HOOK_INIT(memcg_charge_cgroup, selinux_memcg_charge_cgroup),
 	LSM_HOOK_INIT(quotactl, selinux_quotactl),
 	LSM_HOOK_INIT(quota_on, selinux_quota_on),
 	LSM_HOOK_INIT(syslog, selinux_syslog),
diff --git a/security/selinux/include/classmap.h b/security/selinux/include/classmap.h
index 90cb61b1642563..32dd95de509a04 100644
--- a/security/selinux/include/classmap.h
+++ b/security/selinux/include/classmap.h
@@ -60,7 +60,7 @@ const struct security_class_mapping secclass_map[] = {
 	    "siginh",	    "setrlimit",     "rlimitinh",   "dyntransition",
 	    "setcurrent",   "execmem",	     "execstack",   "execheap",
 	    "setkeycreate", "setsockcreate", "getrlimit",   NULL } },
-	{ "process2", { "nnp_transition", "nosuid_transition", NULL } },
+	{ "process2", { "nnp_transition", "nosuid_transition", "charge_to", NULL } },
 	{ "system",
 	  { "ipc_info", "syslog_read", "syslog_mod", "syslog_console",
 	    "module_request", "module_load", "firmware_load",
@@ -181,6 +181,7 @@ const struct security_class_mapping secclass_map[] = {
 	{ "user_namespace", { "create", NULL } },
 	{ "memfd_file",
 	  { COMMON_FILE_PERMS, "execute_no_trans", "entrypoint", NULL } },
+	{ "cgroup", { "charge_to", NULL } },
 	/* last one */ { NULL, {} }
 };
 
diff --git a/tools/testing/selftests/cgroup/Makefile b/tools/testing/selftests/cgroup/Makefile
index e01584c2189ac1..9edfc9f1de5c43 100644
--- a/tools/testing/selftests/cgroup/Makefile
+++ b/tools/testing/selftests/cgroup/Makefile
@@ -1,5 +1,5 @@
 # SPDX-License-Identifier: GPL-2.0
-CFLAGS += -Wall -pthread
+CFLAGS += -Wall -pthread $(KHDR_INCLUDES)
 
 all: ${HELPER_PROGS}
 
diff --git a/tools/testing/selftests/cgroup/test_memcontrol.c b/tools/testing/selftests/cgroup/test_memcontrol.c
index bb673012dcf089..f612726bd9af7e 100644
--- a/tools/testing/selftests/cgroup/test_memcontrol.c
+++ b/tools/testing/selftests/cgroup/test_memcontrol.c
@@ -18,8 +18,15 @@
 #include <netdb.h>
 #include <errno.h>
 #include <sys/mman.h>
+#include <sys/prctl.h>
 #include <sys/sysinfo.h>
 
+#include <linux/dma-buf.h>
+#include <linux/dma-heap.h>
+#include <signal.h>
+#include <sys/ioctl.h>
+
+#include "../pidfd/pidfd.h"
 #include "kselftest.h"
 #include "cgroup_util.h"
 
@@ -27,6 +34,13 @@
 #define MEMCG_FLUSH_BYTES	\
 	(2 * sysconf(_SC_PAGESIZE) * MEMCG_CHARGE_BATCH * get_nprocs())
 
+#define DMA_HEAP_SYSTEM		"/dev/dma_heap/system"
+#define ONE_MEG			(1024 * 1024)
+
+#define MEMCG_SOCKSTAT_WAIT_RETRIES        30
+#define MEMCG_DMABUF_WAIT_RETRIES          30
+#define MEMCG_DMABUF_DEAD_WAIT_RETRIES     80
+
 static bool has_localevents;
 static bool has_recursiveprot;
 static int page_size;
@@ -1797,6 +1811,417 @@ static int test_memcg_inotify_delete_dir(const char *root)
 	return ret;
 }
 
+static int memcg_dmabuf_child(const char *cgroup, void *arg)
+{
+	pid_t *parent_pid = arg;
+
+	prctl(PR_SET_PDEATHSIG, SIGKILL);
+	if (getppid() != *parent_pid)
+		return 0;
+
+	pause();
+	return 0;
+}
+
+/*
+ * This test allocates a dma-buf via DMA_HEAP_IOCTL_ALLOC with a pidfd
+ * pointing to a child process in a separate cgroup, then checks that
+ * memory.stat[dmabuf] in the child's cgroup rises by the allocation size
+ * and returns to zero after the buffer fd is closed.
+ */
+static int test_memcg_dmabuf(const char *root)
+{
+	char *parent = NULL, *child_cg = NULL;
+	int ret = KSFT_FAIL;
+	int heap_fd = -1, dmabuf_fd = -1, pidfd = -1;
+	pid_t child_pid, parent_pid = getpid();
+	int child_status;
+	long dmabuf_stat;
+	struct dma_heap_allocation_data alloc = {
+		.len      = ONE_MEG,
+		.fd_flags = O_RDWR | O_CLOEXEC,
+	};
+
+	if (access(DMA_HEAP_SYSTEM, R_OK | W_OK)) {
+		ret = KSFT_SKIP;
+		goto cleanup;
+	}
+
+	parent = cg_name(root, "dmabuf_memcg_test");
+	if (!parent)
+		goto cleanup;
+
+	if (cg_create(parent))
+		goto cleanup_parent;
+
+	if (cg_write(parent, "cgroup.subtree_control", "+memory"))
+		goto cleanup_parent;
+
+	child_cg = cg_name(parent, "child");
+	if (!child_cg)
+		goto cleanup_parent;
+
+	if (cg_create(child_cg))
+		goto cleanup_parent;
+
+	child_pid = cg_run_nowait(child_cg, memcg_dmabuf_child, &parent_pid);
+	if (child_pid < 0)
+		goto cleanup_child;
+
+	if (cg_wait_for_proc_count(child_cg, 1))
+		goto cleanup_kill;
+
+	pidfd = sys_pidfd_open(child_pid, 0);
+	if (pidfd < 0) {
+		ret = KSFT_SKIP;
+		goto cleanup_kill;
+	}
+
+	heap_fd = open(DMA_HEAP_SYSTEM, O_RDWR);
+	if (heap_fd < 0) {
+		ret = KSFT_SKIP;
+		goto cleanup_pidfd;
+	}
+
+	alloc.charge_fd = (__u32)pidfd;
+	if (ioctl(heap_fd, DMA_HEAP_IOCTL_ALLOC, &alloc) < 0) {
+		if (errno == EINVAL || errno == ENOTTY || errno == EOPNOTSUPP)
+			ret = KSFT_SKIP;
+		goto cleanup_heap;
+	}
+	dmabuf_fd = (int)alloc.fd;
+
+	dmabuf_stat = cg_read_key_long(child_cg, "memory.stat", "dmabuf ");
+	if (dmabuf_stat == -1) {
+		ret = KSFT_SKIP;
+		goto cleanup_dmabuf;
+	}
+	if (dmabuf_stat != ONE_MEG)
+		dmabuf_stat = cg_read_key_long_poll(child_cg, "memory.stat",
+						    "dmabuf ", ONE_MEG,
+						    MEMCG_DMABUF_WAIT_RETRIES,
+						    DEFAULT_WAIT_INTERVAL_US);
+	if (dmabuf_stat != ONE_MEG) {
+		fprintf(stderr, "Expected dmabuf stat %d, got %ld\n",
+			ONE_MEG, dmabuf_stat);
+		goto cleanup_dmabuf;
+	}
+
+	close(dmabuf_fd);
+	dmabuf_fd = -1;
+
+	dmabuf_stat = cg_read_key_long_poll(child_cg, "memory.stat",
+					    "dmabuf ", 0,
+					    MEMCG_DMABUF_WAIT_RETRIES,
+					    DEFAULT_WAIT_INTERVAL_US);
+	if (dmabuf_stat != 0) {
+		fprintf(stderr, "Expected dmabuf stat 0 after close, got %ld\n",
+			dmabuf_stat);
+		goto cleanup_heap;
+	}
+
+	ret = KSFT_PASS;
+
+cleanup_dmabuf:
+	if (dmabuf_fd >= 0)
+		close(dmabuf_fd);
+cleanup_heap:
+	close(heap_fd);
+cleanup_pidfd:
+	close(pidfd);
+cleanup_kill:
+	kill(child_pid, SIGTERM);
+	waitpid(child_pid, &child_status, 0);
+cleanup_child:
+	cg_destroy(child_cg);
+	free(child_cg);
+cleanup_parent:
+	cg_destroy(parent);
+	free(parent);
+cleanup:
+	return ret;
+}
+
+/*
+ * Allocate a dma-buf in cgroup A, set memory.max on cgroup B below the
+ * buffer size, then attempt DMA_BUF_IOCTL_XFER_CHARGE to B. The transfer
+ * must fail with ENOMEM and the charge must remain in A.
+ */
+static int test_memcg_dmabuf_xfer_at_limit(const char *root)
+{
+	char *parent = NULL, *cg_a = NULL, *cg_b = NULL;
+	int ret = KSFT_FAIL;
+	int heap_fd = -1, dmabuf_fd = -1, cg_b_fd = -1;
+	pid_t child_pid, parent_pid = getpid();
+	int child_status;
+	long stat_a;
+	struct dma_heap_allocation_data alloc = {
+		.len      = ONE_MEG,
+		.fd_flags = O_RDWR | O_CLOEXEC,
+	};
+	struct dma_buf_transfer_charge xfer = { 0 };
+
+	if (access(DMA_HEAP_SYSTEM, R_OK | W_OK)) {
+		ret = KSFT_SKIP;
+		goto cleanup;
+	}
+
+	parent = cg_name(root, "dmabuf_xfer_limit_test");
+	if (!parent)
+		goto cleanup;
+
+	if (cg_create(parent))
+		goto cleanup_parent;
+
+	if (cg_write(parent, "cgroup.subtree_control", "+memory"))
+		goto cleanup_parent;
+
+	cg_a = cg_name(parent, "cg_a");
+	cg_b = cg_name(parent, "cg_b");
+	if (!cg_a || !cg_b)
+		goto cleanup_cgs;
+
+	if (cg_create(cg_a) || cg_create(cg_b))
+		goto cleanup_cgs;
+
+	if (cg_write(cg_b, "memory.max", "524288"))
+		goto cleanup_cgs;
+
+	child_pid = cg_run_nowait(cg_a, memcg_dmabuf_child, &parent_pid);
+	if (child_pid < 0)
+		goto cleanup_cgs;
+
+	if (cg_wait_for_proc_count(cg_a, 1))
+		goto cleanup_kill;
+
+	heap_fd = open(DMA_HEAP_SYSTEM, O_RDWR);
+	if (heap_fd < 0) {
+		ret = KSFT_SKIP;
+		goto cleanup_kill;
+	}
+
+	alloc.charge_fd = (__u32)sys_pidfd_open(child_pid, 0);
+	if ((int)alloc.charge_fd < 0) {
+		ret = KSFT_SKIP;
+		goto cleanup_heap;
+	}
+
+	if (ioctl(heap_fd, DMA_HEAP_IOCTL_ALLOC, &alloc) < 0) {
+		close(alloc.charge_fd);
+		goto cleanup_heap;
+	}
+	close(alloc.charge_fd);
+	dmabuf_fd = (int)alloc.fd;
+
+	stat_a = cg_read_key_long(cg_a, "memory.stat", "dmabuf ");
+	if (stat_a == -1) {
+		ret = KSFT_SKIP;
+		goto cleanup_dmabuf;
+	}
+	if (stat_a != ONE_MEG)
+		stat_a = cg_read_key_long_poll(cg_a, "memory.stat",
+					       "dmabuf ", ONE_MEG,
+					       MEMCG_DMABUF_WAIT_RETRIES,
+					       DEFAULT_WAIT_INTERVAL_US);
+	if (stat_a != ONE_MEG) {
+		fprintf(stderr, "Charge not in A after alloc: expected %d, got %ld\n",
+			ONE_MEG, stat_a);
+		goto cleanup_dmabuf;
+	}
+
+	cg_b_fd = open(cg_b, O_RDONLY | O_DIRECTORY);
+	if (cg_b_fd < 0)
+		goto cleanup_dmabuf;
+
+	xfer.charge_fd = (__u32)cg_b_fd;
+	if (ioctl(dmabuf_fd, DMA_BUF_IOCTL_XFER_CHARGE, &xfer) == 0) {
+		fprintf(stderr, "xfer_charge should have failed at limit\n");
+		goto cleanup_cgfd;
+	}
+	if (errno != ENOMEM) {
+		fprintf(stderr, "Expected ENOMEM, got %s\n", strerror(errno));
+		goto cleanup_cgfd;
+	}
+
+	stat_a = cg_read_key_long_poll(cg_a, "memory.stat",
+				       "dmabuf ", ONE_MEG,
+				       MEMCG_DMABUF_WAIT_RETRIES,
+				       DEFAULT_WAIT_INTERVAL_US);
+	if (stat_a != ONE_MEG) {
+		fprintf(stderr, "Charge leaked from A: expected %d, got %ld\n",
+			ONE_MEG, stat_a);
+		goto cleanup_cgfd;
+	}
+
+	ret = KSFT_PASS;
+
+cleanup_cgfd:
+	close(cg_b_fd);
+cleanup_dmabuf:
+	if (dmabuf_fd >= 0)
+		close(dmabuf_fd);
+cleanup_heap:
+	close(heap_fd);
+cleanup_kill:
+	kill(child_pid, SIGTERM);
+	waitpid(child_pid, &child_status, 0);
+cleanup_cgs:
+	if (cg_a) {
+		cg_destroy(cg_a);
+		free(cg_a);
+	}
+	if (cg_b) {
+		cg_destroy(cg_b);
+		free(cg_b);
+	}
+cleanup_parent:
+	cg_destroy(parent);
+	free(parent);
+cleanup:
+	return ret;
+}
+
+/*
+ * Allocate a dma-buf charged to a cgroup, then remove that cgroup while
+ * the buffer is still open. The charge is held by an object cgroup,
+ * which is reparented, so the removed cgroup must be released instead of
+ * lingering as a dying descendant until the buffer is closed.
+ */
+static int test_memcg_dmabuf_dead_cgroup(const char *root)
+{
+	char *parent = NULL, *child_cg = NULL;
+	int ret = KSFT_FAIL;
+	int heap_fd = -1, dmabuf_fd = -1, cg_fd = -1;
+	long dmabuf_stat, dying;
+	struct dma_heap_allocation_data alloc = {
+		.len      = ONE_MEG,
+		.fd_flags = O_RDWR | O_CLOEXEC,
+	};
+
+	if (access(DMA_HEAP_SYSTEM, R_OK | W_OK)) {
+		ret = KSFT_SKIP;
+		goto cleanup;
+	}
+
+	parent = cg_name(root, "dmabuf_dead_cgroup_test");
+	if (!parent)
+		goto cleanup;
+
+	if (cg_create(parent))
+		goto cleanup_parent;
+
+	if (cg_write(parent, "cgroup.subtree_control", "+memory"))
+		goto cleanup_parent;
+
+	child_cg = cg_name(parent, "child");
+	if (!child_cg)
+		goto cleanup_parent;
+
+	if (cg_create(child_cg))
+		goto cleanup_child;
+
+	heap_fd = open(DMA_HEAP_SYSTEM, O_RDWR);
+	if (heap_fd < 0) {
+		ret = KSFT_SKIP;
+		goto cleanup_child;
+	}
+
+	cg_fd = open(child_cg, O_RDONLY | O_DIRECTORY);
+	if (cg_fd < 0)
+		goto cleanup_heap;
+
+	alloc.charge_fd = (__u32)cg_fd;
+	if (ioctl(heap_fd, DMA_HEAP_IOCTL_ALLOC, &alloc) < 0) {
+		if (errno == EINVAL || errno == ENOTTY || errno == EOPNOTSUPP)
+			ret = KSFT_SKIP;
+		goto cleanup_cgfd;
+	}
+	/* The buffer holds the charge; the fd must not hold the cgroup. */
+	close(cg_fd);
+	cg_fd = -1;
+	dmabuf_fd = (int)alloc.fd;
+
+	dmabuf_stat = cg_read_key_long(child_cg, "memory.stat", "dmabuf ");
+	if (dmabuf_stat == -1) {
+		ret = KSFT_SKIP;
+		goto cleanup_dmabuf;
+	}
+	if (dmabuf_stat != ONE_MEG)
+		dmabuf_stat = cg_read_key_long_poll(child_cg, "memory.stat",
+						    "dmabuf ", ONE_MEG,
+						    MEMCG_DMABUF_WAIT_RETRIES,
+						    DEFAULT_WAIT_INTERVAL_US);
+	if (dmabuf_stat != ONE_MEG) {
+		fprintf(stderr, "Expected dmabuf stat %d, got %ld\n",
+			ONE_MEG, dmabuf_stat);
+		goto cleanup_dmabuf;
+	}
+
+	if (cg_destroy(child_cg)) {
+		fprintf(stderr, "Failed to remove charged cgroup\n");
+		goto cleanup_dmabuf;
+	}
+
+	dying = cg_read_key_long_poll(parent, "cgroup.stat",
+				      "nr_dying_descendants ", 0,
+				      MEMCG_DMABUF_DEAD_WAIT_RETRIES,
+				      DEFAULT_WAIT_INTERVAL_US);
+	if (dying) {
+		fprintf(stderr, "Removed cgroup still dying with buffer open\n");
+		goto cleanup_dmabuf;
+	}
+
+	/* The charge must have moved to the parent with the cgroup. */
+	dmabuf_stat = cg_read_key_long(parent, "memory.stat", "dmabuf ");
+	if (dmabuf_stat != ONE_MEG)
+		dmabuf_stat = cg_read_key_long_poll(parent, "memory.stat",
+						    "dmabuf ", ONE_MEG,
+						    MEMCG_DMABUF_WAIT_RETRIES,
+						    DEFAULT_WAIT_INTERVAL_US);
+	if (dmabuf_stat != ONE_MEG) {
+		fprintf(stderr, "Charge not in parent after removal: expected %d, got %ld\n",
+			ONE_MEG, dmabuf_stat);
+		goto cleanup_dmabuf;
+	}
+
+	/* Uncharge through the reparented object cgroup. */
+	close(dmabuf_fd);
+	dmabuf_fd = -1;
+
+	dmabuf_stat = cg_read_key_long(parent, "memory.stat", "dmabuf ");
+	if (dmabuf_stat != 0)
+		dmabuf_stat = cg_read_key_long_poll(parent, "memory.stat",
+						    "dmabuf ", 0,
+						    MEMCG_DMABUF_WAIT_RETRIES,
+						    DEFAULT_WAIT_INTERVAL_US);
+	if (dmabuf_stat != 0) {
+		fprintf(stderr, "Expected dmabuf stat 0 after close, got %ld\n",
+			dmabuf_stat);
+		goto cleanup_heap;
+	}
+
+	ret = KSFT_PASS;
+
+cleanup_dmabuf:
+	if (dmabuf_fd >= 0)
+		close(dmabuf_fd);
+cleanup_cgfd:
+	if (cg_fd >= 0)
+		close(cg_fd);
+cleanup_heap:
+	close(heap_fd);
+cleanup_child:
+	if (child_cg) {
+		cg_destroy(child_cg);
+		free(child_cg);
+	}
+cleanup_parent:
+	cg_destroy(parent);
+	free(parent);
+cleanup:
+	return ret;
+}
+
 #define T(x) { x, #x }
 struct memcg_test {
 	int (*fn)(const char *root);
@@ -1818,13 +2243,20 @@ struct memcg_test {
 	T(test_memcg_oom_group_score_events),
 	T(test_memcg_inotify_delete_file),
 	T(test_memcg_inotify_delete_dir),
+	T(test_memcg_dmabuf),
+	T(test_memcg_dmabuf_xfer_at_limit),
+	T(test_memcg_dmabuf_dead_cgroup),
 };
 #undef T
 
 int main(int argc, char **argv)
 {
 	char root[PATH_MAX];
-	int i, proc_status;
+	int i, proc_status, count = ARRAY_SIZE(tests);
+	const char *filter = NULL;
+
+	if (argc > 1)
+		filter = argv[1];
 
 	page_size = sysconf(_SC_PAGE_SIZE);
 	if (page_size <= 0)
@@ -1855,8 +2287,19 @@ int main(int argc, char **argv)
 		ksft_exit_skip("Failed to query cgroup mount option\n");
 	has_localevents = proc_status;
 
-	ksft_set_plan(ARRAY_SIZE(tests));
+	if (filter) {
+		count = 0;
+		for (i = 0; i < ARRAY_SIZE(tests); i++) {
+			if (!strcmp(tests[i].name, filter))
+				count++;
+		}
+		if (!count)
+			ksft_exit_fail_msg("unknown test '%s'\n", filter);
+	}
+	ksft_set_plan(count);
 	for (i = 0; i < ARRAY_SIZE(tests); i++) {
+		if (filter && strcmp(tests[i].name, filter))
+			continue;
 		switch (tests[i].fn(root)) {
 		case KSFT_PASS:
 			ksft_test_result_pass("%s\n", tests[i].name);
diff --git a/tools/testing/selftests/dmabuf-heaps/config b/tools/testing/selftests/dmabuf-heaps/config
index be091f1cdfa04e..94c8f33b71a28d 100644
--- a/tools/testing/selftests/dmabuf-heaps/config
+++ b/tools/testing/selftests/dmabuf-heaps/config
@@ -1,3 +1,4 @@
+CONFIG_MEMCG=y
 CONFIG_DMABUF_HEAPS=y
 CONFIG_DMABUF_HEAPS_SYSTEM=y
 CONFIG_DRM_VGEM=y
diff --git a/tools/testing/selftests/dmabuf-heaps/dmabuf-heap.c b/tools/testing/selftests/dmabuf-heaps/dmabuf-heap.c
index 1d49df6719198a..44e3f33acf8775 100644
--- a/tools/testing/selftests/dmabuf-heaps/dmabuf-heap.c
+++ b/tools/testing/selftests/dmabuf-heaps/dmabuf-heap.c
@@ -3,6 +3,7 @@
 #include <dirent.h>
 #include <errno.h>
 #include <fcntl.h>
+#include <signal.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <stdint.h>
@@ -10,11 +11,16 @@
 #include <unistd.h>
 #include <sys/ioctl.h>
 #include <sys/mman.h>
+#include <sys/prctl.h>
+#include <sys/syscall.h>
 #include <sys/types.h>
+#include <sys/wait.h>
 
 #include <linux/dma-buf.h>
 #include <linux/dma-heap.h>
+#include <linux/limits.h>
 #include <drm/drm.h>
+#include "../pidfd/pidfd.h"
 #include "kselftest.h"
 
 #define DEVPATH "/dev/dma_heap"
@@ -320,6 +326,8 @@ static int dmabuf_heap_alloc_newer(int fd, size_t len, unsigned int flags,
 		__u32 fd;
 		__u32 fd_flags;
 		__u64 heap_flags;
+		__u32 charge_fd;
+		__u32 __padding;
 		__u64 garbage1;
 		__u64 garbage2;
 		__u64 garbage3;
@@ -328,6 +336,8 @@ static int dmabuf_heap_alloc_newer(int fd, size_t len, unsigned int flags,
 		.fd = 0,
 		.fd_flags = O_RDWR | O_CLOEXEC,
 		.heap_flags = flags,
+		.charge_fd = 0,
+		.__padding = 0,
 		.garbage1 = 0xffffffff,
 		.garbage2 = 0x88888888,
 		.garbage3 = 0x11111111,
@@ -496,6 +506,227 @@ static void test_alloc_no_fd_leak_on_efault(char *heap_name)
 	ksft_test_result(fd_before == fd_after,
 			 "fd leak on EFAULT: before=%d after=%d\n",
 			 fd_before, fd_after);
+
+out:
+	close(heap_fd);
+}
+
+static int dmabuf_heap_alloc_pidfd(int fd, size_t len, unsigned int heap_flags,
+				   unsigned int charge_fd, int *dmabuf_fd)
+{
+	struct dma_heap_allocation_data data = {
+		.len = len,
+		.fd = 0,
+		.fd_flags = O_RDWR | O_CLOEXEC,
+		.heap_flags = heap_flags,
+		.charge_fd = charge_fd,
+	};
+	int ret;
+
+	if (!dmabuf_fd)
+		return -EINVAL;
+
+	ret = ioctl(fd, DMA_HEAP_IOCTL_ALLOC, &data);
+	if (ret < 0)
+		return ret;
+	*dmabuf_fd = (int)data.fd;
+	return ret;
+}
+
+/*
+ * Probe whether the kernel honours charge_fd in DMA_HEAP_IOCTL_ALLOC.
+ */
+static bool pidfd_alloc_supported(int heap_fd)
+{
+	int devnull_fd, dmabuf_fd = -1, ret;
+
+	devnull_fd = open("/dev/null", O_RDONLY);
+	if (devnull_fd < 0)
+		return false;
+
+	ret = dmabuf_heap_alloc_pidfd(heap_fd, ONE_MEG, 0, devnull_fd, &dmabuf_fd);
+	if (dmabuf_fd >= 0) {
+		close(dmabuf_fd);
+		dmabuf_fd = -1;
+	}
+	close(devnull_fd);
+	return ret < 0;
+}
+
+/*
+ * Test: allocate charging the calling process's own cgroup via a self pidfd.
+ */
+static void test_alloc_pidfd_self(char *heap_name)
+{
+	int heap_fd = -1, pidfd = -1, dmabuf_fd = -1, ret;
+
+	heap_fd = dmabuf_heap_open(heap_name);
+
+	if (!pidfd_alloc_supported(heap_fd)) {
+		ksft_test_result_skip("charge_fd not supported by this kernel\n");
+		goto out;
+	}
+
+	pidfd = sys_pidfd_open(getpid(), 0);
+	if (pidfd < 0) {
+		ksft_test_result_skip("pidfd_open not available\n");
+		goto out;
+	}
+
+	ret = dmabuf_heap_alloc_pidfd(heap_fd, ONE_MEG, 0, pidfd, &dmabuf_fd);
+	ksft_test_result(!ret, "Allocation with self pidfd %d\n", ret);
+	if (dmabuf_fd >= 0)
+		close(dmabuf_fd);
+	close(pidfd);
+out:
+	close(heap_fd);
+}
+
+/*
+ * Test: allocate charging a child process's cgroup via a child pidfd.
+ */
+static void test_alloc_pidfd_child(char *heap_name)
+{
+	int heap_fd = -1, pidfd = -1, dmabuf_fd = -1;
+	pid_t child_pid, parent_pid;
+	int status, ret;
+
+	heap_fd = dmabuf_heap_open(heap_name);
+
+	if (!pidfd_alloc_supported(heap_fd)) {
+		ksft_test_result_skip("charge_fd not supported by this kernel\n");
+		goto out;
+	}
+
+	parent_pid = getpid();
+	child_pid = fork();
+	if (child_pid == 0) {
+		prctl(PR_SET_PDEATHSIG, SIGKILL);
+		if (getppid() != parent_pid)
+			_exit(0);
+		pause();
+		_exit(0);
+	}
+	if (child_pid < 0)
+		ksft_exit_fail_msg("fork failed: %s\n", strerror(errno));
+
+	pidfd = sys_pidfd_open(child_pid, 0);
+	if (pidfd < 0) {
+		kill(child_pid, SIGTERM);
+		waitpid(child_pid, &status, 0);
+		ksft_test_result_skip("pidfd_open for child failed\n");
+		goto out;
+	}
+
+	ret = dmabuf_heap_alloc_pidfd(heap_fd, ONE_MEG, 0, pidfd, &dmabuf_fd);
+	ksft_test_result(!ret, "Allocation with child pidfd %d\n", ret);
+	if (dmabuf_fd >= 0)
+		close(dmabuf_fd);
+	close(pidfd);
+	kill(child_pid, SIGTERM);
+	waitpid(child_pid, &status, 0);
+out:
+	close(heap_fd);
+}
+
+static int open_self_cgroupfd(void)
+{
+	char cgroup_path[PATH_MAX];
+	char line[PATH_MAX];
+	int ret = -1;
+	FILE *f;
+
+	f = fopen("/proc/self/cgroup", "r");
+	if (!f)
+		return -1;
+	while (fgets(line, sizeof(line), f)) {
+		if (strncmp(line, "0::", 3))
+			continue;
+		line[strcspn(line, "\n")] = '\0';
+		if (snprintf(cgroup_path, sizeof(cgroup_path),
+			     "/sys/fs/cgroup%s", line + 3) < PATH_MAX)
+			ret = 0;
+		break;
+	}
+	fclose(f);
+
+	if (ret)
+		return -1;
+
+	return open(cgroup_path, O_RDONLY | O_DIRECTORY);
+}
+
+/*
+ * Test: allocate charging the calling process's own cgroup via a cgroupfd.
+ */
+static void test_alloc_cgroupfd_self(char *heap_name)
+{
+	int heap_fd = -1, cgroup_fd = -1, dmabuf_fd = -1, ret;
+
+	heap_fd = dmabuf_heap_open(heap_name);
+
+	if (!pidfd_alloc_supported(heap_fd)) {
+		ksft_test_result_skip("charge_fd not supported by this kernel\n");
+		goto out;
+	}
+
+	cgroup_fd = open_self_cgroupfd();
+	if (cgroup_fd < 0) {
+		ksft_test_result_skip("cannot open self cgroupfd\n");
+		goto out;
+	}
+
+	ret = dmabuf_heap_alloc_pidfd(heap_fd, ONE_MEG, 0, cgroup_fd, &dmabuf_fd);
+	ksft_test_result(!ret, "Allocation with cgroupfd %d\n", ret);
+	if (dmabuf_fd >= 0)
+		close(dmabuf_fd);
+	close(cgroup_fd);
+out:
+	close(heap_fd);
+}
+
+/*
+ * Test: transfer a dma-buf's charge to self cgroup via DMA_BUF_IOCTL_XFER_CHARGE.
+ */
+static void test_xfer_charge_cgroupfd_self(char *heap_name)
+{
+	int heap_fd = -1, cgroup_fd = -1, dmabuf_fd = -1, ret;
+	struct dma_buf_transfer_charge xfer = { 0 };
+
+	heap_fd = dmabuf_heap_open(heap_name);
+
+	if (!pidfd_alloc_supported(heap_fd)) {
+		ksft_test_result_skip("charge_fd not supported by this kernel\n");
+		goto out;
+	}
+
+	ret = dmabuf_heap_alloc(heap_fd, ONE_MEG, 0, &dmabuf_fd);
+	if (ret) {
+		ksft_test_result_fail("Allocation failed %d\n", ret);
+		goto out;
+	}
+
+	cgroup_fd = open_self_cgroupfd();
+	if (cgroup_fd < 0) {
+		ksft_test_result_skip("cannot open self cgroupfd\n");
+		close(dmabuf_fd);
+		goto out;
+	}
+
+	xfer.charge_fd = cgroup_fd;
+	ret = ioctl(dmabuf_fd, DMA_BUF_IOCTL_XFER_CHARGE, &xfer);
+	if (!ret)
+		ksft_test_result_pass("XFER_CHARGE to self cgroupfd\n");
+	else if (errno == EOPNOTSUPP)
+		ksft_test_result_skip("buffer not memcg-charged (mem_accounting=0?)\n");
+	else if (errno == ENOTTY || errno == EINVAL)
+		ksft_test_result_skip("XFER_CHARGE not supported: %s\n",
+				      strerror(errno));
+	else
+		ksft_test_result_fail("XFER_CHARGE failed: %s\n", strerror(errno));
+
+	close(cgroup_fd);
+	close(dmabuf_fd);
 out:
 	close(heap_fd);
 }
@@ -530,7 +761,7 @@ int main(void)
 		return KSFT_SKIP;
 	}
 
-	ksft_set_plan(12 * numer_of_heaps());
+	ksft_set_plan(16 * numer_of_heaps());
 
 	while ((dir = readdir(d))) {
 		if (!strncmp(dir->d_name, ".", 2))
@@ -546,6 +777,10 @@ int main(void)
 		test_alloc_compat(dir->d_name);
 		test_alloc_errors(dir->d_name);
 		test_alloc_no_fd_leak_on_efault(dir->d_name);
+		test_alloc_pidfd_self(dir->d_name);
+		test_alloc_pidfd_child(dir->d_name);
+		test_alloc_cgroupfd_self(dir->d_name);
+		test_xfer_charge_cgroupfd_self(dir->d_name);
 	}
 	closedir(d);
 
diff --git a/tools/testing/selftests/dmabuf-heaps/vmtest.sh b/tools/testing/selftests/dmabuf-heaps/vmtest.sh
new file mode 100755
index 00000000000000..3574b71ca83e85
--- /dev/null
+++ b/tools/testing/selftests/dmabuf-heaps/vmtest.sh
@@ -0,0 +1,226 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+#
+# Copyright (c) 2026 Red Hat
+#
+# Dependencies:
+#		* virtme-ng
+#		* qemu	(used by virtme-ng)
+
+readonly SCRIPT_DIR="$(cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
+readonly KERNEL_CHECKOUT=$(realpath "${SCRIPT_DIR}"/../../../../)
+readonly CGROUP_DIR="${KERNEL_CHECKOUT}/tools/testing/selftests/cgroup"
+
+source "${SCRIPT_DIR}"/../kselftest/ktap_helpers.sh
+
+readonly DMABUF_HEAP_TEST="${SCRIPT_DIR}"/dmabuf-heap
+readonly MEMCONTROL_TEST="${CGROUP_DIR}"/test_memcontrol
+readonly TMP_DIR=$(mktemp -d /tmp/dmabuf-vmtest.XXXXXXXX)
+
+VERBOSE=false
+BUILD=false
+BUILD_HOST=""
+BUILD_HOST_PODMAN_CONTAINER_NAME=""
+SHELL_MODE=false
+
+usage() {
+	echo
+	echo "$0 [OPTIONS]"
+	echo
+	echo "Options"
+	echo "  -b: build the kernel from the current source tree and use it for the VM"
+	echo "  -H: hostname for remote build host (used with -b)"
+	echo "  -p: podman container name for remote build host (used with -b)"
+	echo "      Example: -H beefyserver -p vng"
+	echo "  -s: drop into an interactive shell in the VM instead of running tests"
+	echo "  -v: enable verbose vng/qemu output"
+	echo
+
+	exit 1
+}
+
+die() {
+	echo "$*" >&2
+	exit "${KSFT_FAIL}"
+}
+
+cleanup() {
+	rm -rf "${TMP_DIR}"
+}
+
+check_deps() {
+	for dep in vng make; do
+		if [[ ! -x $(command -v "${dep}") ]]; then
+			echo -e "skip:    dependency ${dep} not found!\n"
+			exit "${KSFT_SKIP}"
+		fi
+	done
+
+	if ${SHELL_MODE}; then
+		return
+	fi
+
+	if [[ ! -x "${DMABUF_HEAP_TEST}" ]]; then
+		printf "skip:    %s not found!" "${DMABUF_HEAP_TEST}"
+		printf " Please build the kselftest dmabuf-heaps target (or use -b).\n"
+		exit "${KSFT_SKIP}"
+	fi
+
+	if [[ ! -x "${MEMCONTROL_TEST}" ]]; then
+		printf "skip:    %s not found!" "${MEMCONTROL_TEST}"
+		printf " Please build the kselftest cgroup target (or use -b).\n"
+		exit "${KSFT_SKIP}"
+	fi
+}
+
+check_vng() {
+	local tested_versions=("1.36" "1.37")
+	local version
+	local ok=0
+
+	version="$(vng --version)"
+	for tv in "${tested_versions[@]}"; do
+		if [[ "${version}" == *"${tv}"* ]]; then
+			ok=1
+			break
+		fi
+	done
+
+	if [[ "${ok}" -eq 0 ]]; then
+		printf "warning: vng version '%s' has not been tested and may " "${version}" >&2
+		printf "not function properly.\n\tThe following versions have been tested: " >&2
+		echo "${tested_versions[@]}" >&2
+	fi
+}
+
+build_selftests() {
+	make -C "${KERNEL_CHECKOUT}" headers_install \
+		INSTALL_HDR_PATH="${TMP_DIR}/usr" -j"$(nproc)"
+
+	local khdr="-isystem ${TMP_DIR}/usr/include"
+
+	if ! make -C "${SCRIPT_DIR}" KHDR_INCLUDES="${khdr}" -j"$(nproc)"; then
+		die "failed to build dmabuf-heaps selftests"
+	fi
+
+	if ! make -C "${CGROUP_DIR}" KHDR_INCLUDES="${khdr}" \
+		"${MEMCONTROL_TEST}" -j"$(nproc)"; then
+		die "failed to build cgroup/test_memcontrol selftest"
+	fi
+}
+
+handle_build() {
+	if ! ${BUILD}; then
+		return
+	fi
+
+	if [[ ! -d "${KERNEL_CHECKOUT}" ]]; then
+		echo "-b requires vmtest.sh called from the kernel source tree" >&2
+		exit 1
+	fi
+
+	pushd "${KERNEL_CHECKOUT}" &>/dev/null
+
+	if ! vng --kconfig --config "${SCRIPT_DIR}/config"; then
+		die "failed to generate .config for kernel source tree (${KERNEL_CHECKOUT})"
+	fi
+
+	local vng_args=("-v" "--config" "${SCRIPT_DIR}/config" "--build")
+
+	if [[ -n "${BUILD_HOST}" ]]; then
+		vng_args+=("--build-host" "${BUILD_HOST}")
+	fi
+
+	if [[ -n "${BUILD_HOST_PODMAN_CONTAINER_NAME}" ]]; then
+		vng_args+=("--build-host-exec-prefix" \
+			   "podman exec -ti ${BUILD_HOST_PODMAN_CONTAINER_NAME}")
+	fi
+
+	if ! vng "${vng_args[@]}"; then
+		die "failed to build kernel from source tree (${KERNEL_CHECKOUT})"
+	fi
+
+	build_selftests
+
+	popd &>/dev/null
+}
+
+make_runner() {
+	# virtme-ng shares the host filesystem, so TMP_DIR is accessible
+	# inside the VM at the same absolute path.
+	cat > "${TMP_DIR}/run_tests.sh" <<-EOF
+	#!/bin/sh
+	set -u
+
+	# Enable memory controller for child cgroups
+	echo +memory > /sys/fs/cgroup/cgroup.subtree_control 2>/dev/null
+
+	PASS=0; FAIL=0; SKIP=0; N=0
+
+	run() {
+		name="\$1"; shift
+		N=\$((N+1))
+		"\$@"; rc=\$?
+		if   [ \$rc -eq 0 ]; then echo "ok \$N \$name";        PASS=\$((PASS+1))
+		elif [ \$rc -eq 4 ]; then echo "ok \$N \$name # SKIP"; SKIP=\$((SKIP+1))
+		else                      echo "not ok \$N \$name";    FAIL=\$((FAIL+1))
+		fi
+	}
+
+	run "dmabuf-heap charge_fd ioctl"	${DMABUF_HEAP_TEST}
+	run "memcontrol dma-buf memcg"	${MEMCONTROL_TEST} test_memcg_dmabuf
+	run "memcontrol dma-buf xfer limit" \
+		${MEMCONTROL_TEST} test_memcg_dmabuf_xfer_at_limit
+	echo "# PASS=\$PASS SKIP=\$SKIP FAIL=\$FAIL"
+	[ \$FAIL -eq 0 ]
+	EOF
+	chmod +x "${TMP_DIR}/run_tests.sh"
+}
+
+run_vm() {
+	local verbose_opt=""
+	local kernel_opt=""
+
+	${VERBOSE} && verbose_opt="--verbose"
+
+	# If we are running from within the kernel source tree, use the kernel
+	# source tree as the kernel to boot, otherwise use the running kernel.
+	if [[ "$(realpath "$(pwd)")" == "${KERNEL_CHECKOUT}"* ]]; then
+		kernel_opt="${KERNEL_CHECKOUT}"
+	fi
+
+	if ${SHELL_MODE}; then
+		echo "Starting interactive shell in VM. Exit to stop VM."
+		vng --run ${kernel_opt} ${verbose_opt} --user root --memory 512M \
+			--append "dma_heap.mem_accounting=1" \
+			-- bash --noprofile --norc
+		exit "${KSFT_PASS}"
+	fi
+
+	vng --run ${kernel_opt} ${verbose_opt} --user root --memory 512M \
+		--append "dma_heap.mem_accounting=1" \
+		--exec "${TMP_DIR}/run_tests.sh"
+}
+
+while getopts :hvsbH:p: o
+do
+	case $o in
+	v) VERBOSE=true;;
+	b) BUILD=true;;
+	s) SHELL_MODE=true;;
+	H) BUILD_HOST=$OPTARG;;
+	p) BUILD_HOST_PODMAN_CONTAINER_NAME=$OPTARG;;
+	h|*) usage;;
+	esac
+done
+shift $((OPTIND-1))
+
+trap cleanup EXIT
+
+check_deps
+check_vng
+handle_build
+make_runner
+
+echo "Booting VM and running tests..."
+run_vm

31/3 2026/11/20 23:08 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 26720
							output: 42
							thoughts: 608
						

Thoughts:
**Analyzing the DMA-BUF Memcg Accounting Patch**

Okay, so this patch is adding memcg accounting for dma-buf allocations and transfer of charges. My initial thought is to go through this with a fine-toothed comb, looking for potential vulnerabilities – uninitialized memory reads, kernel information leaks, anything that KMSAN or KASAN might flag. Let's see what we've got.

First, I'll start with the documentation, `Documentation/admin-guide/cgroup-v2.rst`, to get the high-level picture. Then, I'll dive into the code.

Looking at `drivers/dma-buf/dma-buf.c`, I see a few key functions: `dma_buf_release`, `dma_buf_xfer_charge`, and `dma_buf_export`. 

In `dma_buf_release`, it's calling `mem_cgroup_uncharge_dmabuf(dmabuf);` which seems straightforward – releasing the memcg charge when the buffer is freed. Good.

`dma_buf_xfer_charge` is where things might get interesting. It takes a `struct dma_buf_transfer_charge` from userspace using `copy_from_user`. Crucially, this is *only* a read from user space; the data isn't being copied back. That's good, less chance of leaking kernel data. The `DMA_BUF_IOCTL_XFER_CHARGE` ioctl is `_IOW` which confirms it's input-only.

Then, there's `dma_buf_export`, which looks like it's setting the `objcg` and calling `mem_cgroup_commit_dmabuf(dmabuf)`. This seems to be the core of the charge/commit process.

Now, a quick jump to `drivers/dma-buf/dma-heap.c`. I see `dma_heap_ioctl_allocate` which receives `heap_allocation` through the `void *data` parameter. I need to understand where that `data` comes from within `dma_heap_ioctl` to be sure it's valid. Gotta be careful with userspace data coming in. I'll use `grepper` or `read-file` to check the `dma-heap.c` file and understand how the function is called.



32/3 2026/11/20 23:08 tool grepper
0m Args:
{
  "Expression": "dma_heap_ioctl_allocate",
  "PathPrefixes": [
    "drivers/dma-buf/dma-heap.c"
  ]
}

Results:
{
  "Output": "drivers/dma-buf/dma-heap.c=60=static int dma_heap_open(struct inode *inode, struct file *file)\n--\ndrivers/dma-buf/dma-heap.c-76-\ndrivers/dma-buf/dma-heap.c:77:static struct dma_buf *dma_heap_ioctl_allocate(struct file *file, void *data)\ndrivers/dma-buf/dma-heap.c-78-{\n--\ndrivers/dma-buf/dma-heap.c=139=static long dma_heap_ioctl(struct file *file, unsigned int ucmd,\n--\ndrivers/dma-buf/dma-heap.c-185-\tcase DMA_HEAP_IOCTL_ALLOC:\ndrivers/dma-buf/dma-heap.c:186:\t\tdmabuf = dma_heap_ioctl_allocate(file, kdata);\ndrivers/dma-buf/dma-heap.c-187-\n"
}

33/3 2026/11/20 23:08 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 28151
							output: 41
							thoughts: 35
						

Thoughts:
Here's a summary of my thought process, as requested:

**Diving into `dma-heap.c` for IOCTL Analysis**

Okay, let's get down to brass tacks. I need to understand the interaction with the DMA heap, specifically how userspace interacts with it. My instinct tells me to check the `dma_heap_ioctl` function. It's usually the go-to point for user-space control and configuration in these types of device drivers. I'm going to navigate directly to line 139 in `drivers/dma-buf/dma-heap.c`. That should put me right at the heart of the IOCTL handler. From there, I can dissect the specific commands, parameters, and error handling to form a solid understanding of the driver's interface.



34/3 2026/11/20 23:08 tool read-file
0m Args:
{
  "File": "drivers/dma-buf/dma-heap.c",
  "FirstLine": 140,
  "LineCount": 60
}

Results:
{
  "Contents": " 140:\t\t\t\t   unsigned long arg)\n 141:\t{\n 142:\t\tchar stack_kdata[128];\n 143:\t\tchar *kdata = stack_kdata;\n 144:\t\tunsigned int kcmd;\n 145:\t\tunsigned int in_size, out_size, drv_size, ksize;\n 146:\t\tint nr = _IOC_NR(ucmd);\n 147:\t\tint ret = 0;\n 148:\t\tint fd;\n 149:\t\tstruct dma_buf *dmabuf;\n 150:\t\n 151:\t\tif (nr \u003e= ARRAY_SIZE(dma_heap_ioctl_cmds))\n 152:\t\t\treturn -EINVAL;\n 153:\t\n 154:\t\tnr = array_index_nospec(nr, ARRAY_SIZE(dma_heap_ioctl_cmds));\n 155:\t\t/* Get the kernel ioctl cmd that matches */\n 156:\t\tkcmd = dma_heap_ioctl_cmds[nr];\n 157:\t\n 158:\t\t/* Figure out the delta between user cmd size and kernel cmd size */\n 159:\t\tdrv_size = _IOC_SIZE(kcmd);\n 160:\t\tout_size = _IOC_SIZE(ucmd);\n 161:\t\tin_size = out_size;\n 162:\t\tif ((ucmd \u0026 kcmd \u0026 IOC_IN) == 0)\n 163:\t\t\tin_size = 0;\n 164:\t\tif ((ucmd \u0026 kcmd \u0026 IOC_OUT) == 0)\n 165:\t\t\tout_size = 0;\n 166:\t\tksize = max3(in_size, out_size, drv_size);\n 167:\t\n 168:\t\t/* If necessary, allocate buffer for ioctl argument */\n 169:\t\tif (ksize \u003e sizeof(stack_kdata)) {\n 170:\t\t\tkdata = kmalloc(ksize, GFP_KERNEL);\n 171:\t\t\tif (!kdata)\n 172:\t\t\t\treturn -ENOMEM;\n 173:\t\t}\n 174:\t\n 175:\t\tif (copy_from_user(kdata, (void __user *)arg, in_size) != 0) {\n 176:\t\t\tret = -EFAULT;\n 177:\t\t\tgoto err;\n 178:\t\t}\n 179:\t\n 180:\t\t/* zero out any difference between the kernel/user structure size */\n 181:\t\tif (ksize \u003e in_size)\n 182:\t\t\tmemset(kdata + in_size, 0, ksize - in_size);\n 183:\t\n 184:\t\tswitch (kcmd) {\n 185:\t\tcase DMA_HEAP_IOCTL_ALLOC:\n 186:\t\t\tdmabuf = dma_heap_ioctl_allocate(file, kdata);\n 187:\t\n 188:\t\t\tif (IS_ERR(dmabuf)) {\n 189:\t\t\t\tret = PTR_ERR(dmabuf);\n 190:\t\t\t\tbreak;\n 191:\t\t\t}\n 192:\t\n 193:\t\t\tfd = ((struct dma_heap_allocation_data *)kdata)-\u003efd;\n 194:\t\t\tif (copy_to_user((void __user *)arg, kdata, out_size) != 0) {\n 195:\t\t\t\tput_unused_fd(fd);\n 196:\t\t\t\tdma_buf_put(dmabuf);\n 197:\t\t\t\tret = -EFAULT;\n 198:\t\t\t} else {\n 199:\t\t\t\tdma_buf_fd_install(dmabuf, fd);\n"
}

35/3 2026/11/20 23:08 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 29366
							output: 41
							thoughts: 173
						

Thoughts:
**Analyzing `dma_heap_ioctl` for Command Structure**

Okay, let's break this down. I'm looking at `dma_heap_ioctl` and immediately my brain starts dissecting the command structure. First, I see the size calculations: `drv_size`, `out_size`, `in_size`. Those are clearly derived from the kernel and user commands, `kcmd` and `ucmd` respectively, using the `_IOC_SIZE` macro. It makes sense, we're trying to figure out the memory footprint of the command.

Ah, conditional logic... that's where things get interesting. The code's checking the `IOC_IN` and `IOC_OUT` flags on the commands. If those flags aren't set in both the user and kernel commands for input, the `in_size` is set to zero. Similarly for output, effectively determining which direction data transfer is allowed to occur in for the command. Then, we determine `ksize` based on the maximum of `in_size`, `out_size`, and `drv_size`, which is fairly standard for determining the total size needed for a command.

But, hang on a second. I need to refresh my memory on what `dma_heap_ioctl_cmds` actually is. I'm going to have to go and look at line 120-140 in `drivers/dma-buf/dma-heap.c` for some context; I have a feeling that's where I need to be. I'll need to know what those commands are to correctly understand what these size calculations are for.



36/3 2026/11/20 23:08 tool read-file
0m Args:
{
  "File": "drivers/dma-buf/dma-heap.c",
  "FirstLine": 120,
  "LineCount": 25
}

Results:
{
  "Contents": " 120:\t\n 121:\t\tif (!dmabuf-\u003eobjcg)\n 122:\t\t\tobj_cgroup_put(objcg);\n 123:\t\n 124:\t\tfd = get_unused_fd_flags(heap_allocation-\u003efd_flags);\n 125:\t\tif (fd \u003c 0) {\n 126:\t\t\tdma_buf_put(dmabuf);\n 127:\t\t\treturn ERR_PTR(fd);\n 128:\t\t}\n 129:\t\n 130:\t\theap_allocation-\u003efd = fd;\n 131:\t\n 132:\t\treturn dmabuf;\n 133:\t}\n 134:\t\n 135:\tstatic unsigned int dma_heap_ioctl_cmds[] = {\n 136:\t\tDMA_HEAP_IOCTL_ALLOC,\n 137:\t};\n 138:\t\n 139:\tstatic long dma_heap_ioctl(struct file *file, unsigned int ucmd,\n 140:\t\t\t\t   unsigned long arg)\n 141:\t{\n 142:\t\tchar stack_kdata[128];\n 143:\t\tchar *kdata = stack_kdata;\n 144:\t\tunsigned int kcmd;\n"
}

37/3 2026/11/20 23:08 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 30270
							output: 40
							thoughts: 416
						

Thoughts:
**Analyzing the DMA Heap Allocation Structure**

Okay, hold on a second. Let's really dig into this `DMA_HEAP_IOCTL_ALLOC` situation. Right, first, I need to check `include/uapi/linux/dma-heap.h`. I'm seeing changes to the `struct dma_heap_allocation_data` structure. Let me see... yes, the patch is modifying the structure itself.

I'm noticing the addition of two new fields to `struct dma_heap_allocation_data`: `charge_fd` and `__padding`. The `charge_fd` field is interesting; it looks like this new field will allow for the allocation to be charged to a specific pidfd or cgroupfd. A value of 0 seems to indicate that the calling process's cgroup should be charged, but only if the `mem_accounting` module parameter is enabled, otherwise no charge at all. Then there is the `__padding` field, reserved, must be zero. This is pretty standard for ABI compatibility. Alright, so I've got a good handle on the struct itself. Now, let's just make sure I have the context of the definition. Now I need to check the lines 40-55 of `include/uapi/linux/dma-heap.h` to make sure I am on the same page.



38/3 2026/11/20 23:08 tool read-file
0m Args:
{
  "File": "include/uapi/linux/dma-heap.h",
  "FirstLine": 35,
  "LineCount": 25
}

Results:
{
  "Contents": "  35:\t *\t\t\tis enabled, or skip charging otherwise\n  36:\t * @__padding:\t\treserved, must be zero\n  37:\t *\n  38:\t * Provided by userspace as an argument to the ioctl\n  39:\t */\n  40:\tstruct dma_heap_allocation_data {\n  41:\t\t__u64 len;\n  42:\t\t__u32 fd;\n  43:\t\t__u32 fd_flags;\n  44:\t\t__u64 heap_flags;\n  45:\t\t__u32 charge_fd;\n  46:\t\t__u32 __padding;\n  47:\t};\n  48:\t\n  49:\t#define DMA_HEAP_IOC_MAGIC\t\t'H'\n  50:\t\n  51:\t/**\n  52:\t * DOC: DMA_HEAP_IOCTL_ALLOC - allocate memory from pool\n  53:\t *\n  54:\t * Takes a dma_heap_allocation_data struct and returns it with the fd field\n  55:\t * populated with the dmabuf handle of the allocation.\n  56:\t */\n  57:\t#define DMA_HEAP_IOCTL_ALLOC\t_IOWR(DMA_HEAP_IOC_MAGIC, 0x0,\\\n  58:\t\t\t\t\t      struct dma_heap_allocation_data)\n  59:\t\n"
}

39/3 2026/11/20 23:08 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 31374
							output: 41
							thoughts: 2175
						

Thoughts:
**Analyzing DMA Heap IOCTL and DMA-BUF Data Structures and Usage**

Okay, so I'm looking at this `DMA_HEAP_IOCTL_ALLOC` definition – it's an I/O control command, and the associated data structure `struct dma_heap_allocation_data` has been updated. Initially, it was 24 bytes, and now it's 32 bytes due to the addition of `charge_fd` and padding. I need to understand the implications of this change, especially since older user-space applications might be sending data expecting the old structure size.

The kernel's `dma_heap_ioctl` function is the point of interest. It uses `dma_heap_ioctl_cmds[0]` to map `DMA_HEAP_IOCTL_ALLOC`. The code retrieves the kernel command size (`drv_size`), which now reflects the 32-byte struct. It calculates the sizes: `in_size` (from the user-space command) and `out_size`.  The crux of the matter is the `memset` call after `copy_from_user`. This clears out any difference between the user-provided data and the kernel struct size.

If an older user space app sends 24 bytes, `in_size` and `out_size` are 24. Then `drv_size` is 32, and `ksize` becomes 32,  `copy_from_user` copies 24 bytes, and the  `memset` zeroes the extra 8 bytes, specifically `charge_fd` and the padding. This means it's safe: the potentially uninitialized values will be zeroed out. The kernel copies back 24 bytes which is safe too.

What if the output size is bigger than the input? Let's say, 24 bytes for input and 32 bytes for output. The `memset` still zeroes the last 8 bytes after `copy_from_user`, guaranteeing that the output buffer is fully initialized before the data is copied back to user space.  Even if the user specifies a larger output size than the kernel structure, the kernel either zeros everything (if there's no input) or zeros any extra space.

I've examined the `dma_heap_ioctl_allocate` function. It checks `heap_flags` and also the  `__padding` field of the `dma_heap_allocation_data` struct to make sure it's zero. This is a crucial safety check to prevent misuse of uninitialized memory. Also, `charge_fd` check is done to get and use the `obj_cgroup` for it.

I did a deep dive into the `struct dma_heap_allocation_data` to ensure there are no compiler padding issues. The fields are aligned correctly: `len` takes 8 bytes, then `fd` and `fd_flags` take 4 each, `heap_flags` is 8 bytes, then `charge_fd` and `__padding` are 4 bytes each, for a total of 32 bytes with no unexpected gaps. The structure size is a multiple of 8, so there shouldn't be any alignment problems on any architecture.

Also, it's important to realize that `kdata` is either allocated on the stack (if `ksize` is small enough, up to 128 bytes) or allocated dynamically with `kmalloc`. The critical point is that, regardless of stack or heap allocation, *before* the kernel copies anything back to user space, it is fully initialized.  In the specific case of `dma_heap_ioctl_allocate`, only the `fd` field is modified based on the kernel's operation, the other fields are unchanged.  The kernel then copies back 32 bytes (or `out_size` bytes) to the user.

Let's also look at `dma_buf_xfer_charge` function. I see that the kernel copies from user space into `arg` (stack).  There is no data copied back to user space here.  The function returns an integer return value. Therefore the safety checks are still fine.

And what about `dma_buf_export`? I should probably check that one too. I'll read around line 747 in `drivers/dma-buf/dma-buf.c` to look.

Ultimately, by zeroing the data either explicitly, or initializing it from user space, the `dma_heap_ioctl` function is robust to older user-space applications or potentially larger output buffers.  I'm confident in the security of this I/O control handling.



40/3 2026/11/20 23:09 tool read-file
0m Args:
{
  "File": "drivers/dma-buf/dma-buf.c",
  "FirstLine": 730,
  "LineCount": 90
}

Results:
{
  "Contents": " 730:\t */\n 731:\t\n 732:\t/**\n 733:\t * dma_buf_export - Creates a new dma_buf, and associates an anon file\n 734:\t * with this buffer, so it can be exported.\n 735:\t * Also connect the allocator specific data and ops to the buffer.\n 736:\t * Additionally, provide a name string for exporter; useful in debugging.\n 737:\t *\n 738:\t * @exp_info:\t[in]\tholds all the export related information provided\n 739:\t *\t\t\tby the exporter. see \u0026struct dma_buf_export_info\n 740:\t *\t\t\tfor further details.\n 741:\t *\n 742:\t * Returns, on success, a newly created struct dma_buf object, which wraps the\n 743:\t * supplied private data and operations for struct dma_buf_ops. On either\n 744:\t * missing ops, or error in allocating struct dma_buf, will return negative\n 745:\t * error.\n 746:\t *\n 747:\t * For most cases the easiest way to create @exp_info is through the\n 748:\t * %DEFINE_DMA_BUF_EXPORT_INFO macro.\n 749:\t */\n 750:\tstruct dma_buf *dma_buf_export(const struct dma_buf_export_info *exp_info)\n 751:\t{\n 752:\t\tstruct dma_buf *dmabuf;\n 753:\t\tstruct dma_resv *resv = exp_info-\u003eresv;\n 754:\t\tstruct file *file;\n 755:\t\tsize_t alloc_size = sizeof(struct dma_buf);\n 756:\t\tint ret;\n 757:\t\n 758:\t\tif (WARN_ON(!exp_info-\u003epriv || !exp_info-\u003eops\n 759:\t\t\t    || !exp_info-\u003eops-\u003emap_dma_buf\n 760:\t\t\t    || !exp_info-\u003eops-\u003eunmap_dma_buf\n 761:\t\t\t    || !exp_info-\u003eops-\u003erelease))\n 762:\t\t\treturn ERR_PTR(-EINVAL);\n 763:\t\n 764:\t\tif (WARN_ON(!exp_info-\u003eops-\u003epin != !exp_info-\u003eops-\u003eunpin))\n 765:\t\t\treturn ERR_PTR(-EINVAL);\n 766:\t\n 767:\t\tif (!try_module_get(exp_info-\u003eowner))\n 768:\t\t\treturn ERR_PTR(-ENOENT);\n 769:\t\n 770:\t\tfile = dma_buf_getfile(exp_info-\u003esize, exp_info-\u003eflags);\n 771:\t\tif (IS_ERR(file)) {\n 772:\t\t\tret = PTR_ERR(file);\n 773:\t\t\tgoto err_module;\n 774:\t\t}\n 775:\t\n 776:\t\tif (!exp_info-\u003eresv)\n 777:\t\t\talloc_size += sizeof(struct dma_resv);\n 778:\t\telse\n 779:\t\t\t/* prevent \u0026dma_buf[1] == dma_buf-\u003eresv */\n 780:\t\t\talloc_size += 1;\n 781:\t\tdmabuf = kzalloc(alloc_size, GFP_KERNEL);\n 782:\t\tif (!dmabuf) {\n 783:\t\t\tret = -ENOMEM;\n 784:\t\t\tgoto err_file;\n 785:\t\t}\n 786:\t\n 787:\t\tdmabuf-\u003epriv = exp_info-\u003epriv;\n 788:\t\tdmabuf-\u003eops = exp_info-\u003eops;\n 789:\t\tdmabuf-\u003esize = exp_info-\u003esize;\n 790:\t\tdmabuf-\u003eexp_name = exp_info-\u003eexp_name;\n 791:\t\tdmabuf-\u003eowner = exp_info-\u003eowner;\n 792:\t\tdmabuf-\u003eobjcg = exp_info-\u003eobjcg;\n 793:\t\tspin_lock_init(\u0026dmabuf-\u003ename_lock);\n 794:\t\tinit_waitqueue_head(\u0026dmabuf-\u003epoll);\n 795:\t\tdmabuf-\u003ecb_in.poll = dmabuf-\u003ecb_out.poll = \u0026dmabuf-\u003epoll;\n 796:\t\tdmabuf-\u003ecb_in.active = dmabuf-\u003ecb_out.active = 0;\n 797:\t\tINIT_LIST_HEAD(\u0026dmabuf-\u003eattachments);\n 798:\t\n 799:\t\tif (!resv) {\n 800:\t\t\tdmabuf-\u003eresv = (struct dma_resv *)\u0026dmabuf[1];\n 801:\t\t\tdma_resv_init(dmabuf-\u003eresv);\n 802:\t\t} else {\n 803:\t\t\tdmabuf-\u003eresv = resv;\n 804:\t\t}\n 805:\t\n 806:\t\tfile-\u003eprivate_data = dmabuf;\n 807:\t\tfile-\u003ef_path.dentry-\u003ed_fsdata = dmabuf;\n 808:\t\tdmabuf-\u003efile = file;\n 809:\t\n 810:\t\t__dma_buf_list_add(dmabuf);\n 811:\t\n 812:\t\tDMA_BUF_TRACE(trace_dma_buf_export, dmabuf);\n 813:\t\n 814:\t\tmem_cgroup_commit_dmabuf(dmabuf);\n 815:\t\n 816:\t\treturn dmabuf;\n 817:\t\n 818:\terr_file:\n 819:\t\tfput(file);\n"
}

41/3 2026/11/20 23:09 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 36074
							output: 43
							thoughts: 118
						

Thoughts:
**Investigating the DMA Buffer Export Initialization**

Okay, so I'm looking at this `dmabuf = kzalloc(alloc_size, GFP_KERNEL)` allocation. Right, it's a kernel zeroed allocation. Good practice. And it looks like `dmabuf->objcg = exp_info->objcg;` is explicitly set, or at least the `objcg` is set. Of course, `kzalloc` would initialize it anyway. But what about all the other things related to `dma_buf_export`? I need to check the callers of `dma_buf_export`, because I can't be sure this is the only code that sets `objcg`.

I see that `DEFINE_DMA_BUF_EXPORT_INFO(exp_info);` is used. I've got to check where *that* is defined. Let me just jump over to `include/linux/dma-buf.h`... that should have the macro definition. I'll take a look in there.



42/3 2026/11/20 23:09 tool grepper
0m Args:
{
  "Expression": "#define DEFINE_DMA_BUF_EXPORT_INFO",
  "PathPrefixes": [
    "include/linux/dma-buf.h"
  ]
}

Results:
{
  "Output": "include/linux/dma-buf.h=517=struct dma_buf_export_info {\n--\ninclude/linux/dma-buf.h-534- */\ninclude/linux/dma-buf.h:535:#define DEFINE_DMA_BUF_EXPORT_INFO(name)\t\\\ninclude/linux/dma-buf.h-536-\tstruct dma_buf_export_info name = { .exp_name = KBUILD_MODNAME, \\\n"
}

43/3 2026/11/20 23:09 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 36586
							output: 43
							thoughts: 210
						

Thoughts:
**DMA Buffer Export Info: A Quick Mental Audit**

Okay, so `DEFINE_DMA_BUF_EXPORT_INFO(name)` sets up `.exp_name` to be `KBUILD_MODNAME` and the `.owner` to `THIS_MODULE`. Standard stuff. The beauty of C is that any unspecified members in the initialization get set to zero, or `NULL` in this case. So, that means `objcg` will be `NULL` for any code that uses this macro. Seems logical.

But hold on a second... what about those heap implementations, `cma_heap.c` and `tee_heap.c`? I seem to remember seeing `objcg` being used somewhere in the `cma_heap` code... let me just double-check that. Let's dig into `cma_heap.c`, I'll start with the `cma_heap_allocate` function to refresh my memory, since that's the likely spot to find it.



44/3 2026/11/20 23:09 tool grepper
0m Args:
{
  "Expression": "cma_heap_allocate",
  "PathPrefixes": [
    "drivers/dma-buf/heaps/cma_heap.c"
  ]
}

Results:
{
  "Output": "drivers/dma-buf/heaps/cma_heap.c=268=static const struct dma_buf_ops cma_heap_buf_ops = {\n--\ndrivers/dma-buf/heaps/cma_heap.c-280-\ndrivers/dma-buf/heaps/cma_heap.c:281:static struct dma_buf *cma_heap_allocate(struct dma_heap *heap,\ndrivers/dma-buf/heaps/cma_heap.c-282-\t\t\t\t\t unsigned long len,\n--\ndrivers/dma-buf/heaps/cma_heap.c=369=static const struct dma_heap_ops cma_heap_ops = {\ndrivers/dma-buf/heaps/cma_heap.c:370:\t.allocate = cma_heap_allocate,\ndrivers/dma-buf/heaps/cma_heap.c-371-};\n"
}

45/3 2026/11/20 23:09 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 37296
							output: 21
							thoughts: 965
						

Thoughts:
**Analyzing Object Cgroup Handling in DMA Heap Allocation**

Okay, so I'm looking at this `cma_heap.c` code, and something immediately jumped out at me. The `objcg` is accepted, but it doesn't get assigned to `exp_info.objcg`, meaning `dmabuf->objcg` ends up as NULL. That's a red flag.

Then I checked out `dma_heap_ioctl_allocate`. I see that the `objcg` is passed into the `allocate` function.  It's passed like this:

dmabuf = heap->ops->allocate(heap, len, heap_allocation->fd_flags,
                             heap_allocation->heap_flags, objcg);

Then, the code checks if allocation returned an error:

if (IS_ERR(dmabuf)) {
    obj_cgroup_put(objcg);
    return dmabuf;
}

If not, and if `!dmabuf->objcg` is true, it calls `obj_cgroup_put(objcg)`. This means that if `dmabuf->objcg` isn't set (which we already know it might not be), it drops the reference that was acquired earlier. This seems wrong.  It looks like there's a potential use-after-free situation, or at least a reference counting bug. The driver may be returning a valid `dmabuf`, but the `objcg` is being released because the assignment didn't happen as expected, and the caller is still holding a reference that's now invalid.

Next, I needed to understand where this `objcg` comes from, so I dug into `mm/memcontrol.c` and found `get_obj_cgroup_from_fd(int fd)`. This is the function that seems to be pulling the `objcg` from a file descriptor. I can see that it handles both cgroup file descriptors and pidfds. It does some security checks and handles grabbing the cgroup from the fd.

I see it calls `pidfd_get_task(fd, &pidfd_flags)` and then checks the result of this call.  Wait a minute... is `pidfd_flags` actually used? It's passed as an out-parameter. I need to check the function signature for `pidfd_get_task` to confirm that.


46/3 2026/11/20 23:09 tool grepper
0m Args:
{
  "Expression": "pidfd_get_task\\("
}

Results:
{
  "Output": "include/linux/pid.h=85=struct pid *pidfd_get_pid(unsigned int fd, unsigned int *flags);\ninclude/linux/pid.h:86:struct task_struct *pidfd_get_task(int pidfd, unsigned int *flags);\ninclude/linux/pid.h-87-int pidfd_prepare(struct pid *pid, unsigned int flags, struct file **ret_file);\n--\nkernel/pid.c=594=struct pid *pidfd_get_pid(unsigned int fd, unsigned int *flags)\n--\nkernel/pid.c-610-/**\nkernel/pid.c:611: * pidfd_get_task() - Get the task associated with a pidfd\nkernel/pid.c-612- *\n--\nkernel/pid.c-621- */\nkernel/pid.c:622:struct task_struct *pidfd_get_task(int pidfd, unsigned int *flags)\nkernel/pid.c-623-{\n--\nmm/madvise.c=2106=SYSCALL_DEFINE5(process_madvise, int, pidfd, const struct iovec __user *, vec,\n--\nmm/madvise.c-2125-\nmm/madvise.c:2126:\ttask = pidfd_get_task(pidfd, \u0026f_flags);\nmm/madvise.c-2127-\tif (IS_ERR(task)) {\n--\nmm/memcontrol.c=3199=struct obj_cgroup *get_obj_cgroup_from_fd(int fd)\n--\nmm/memcontrol.c-3234-\t\t/* fd is a pidfd */\nmm/memcontrol.c:3235:\t\ttask = pidfd_get_task(fd, \u0026pidfd_flags);\nmm/memcontrol.c-3236-\t\tif (IS_ERR(task))\n--\nmm/oom_kill.c=1188=SYSCALL_DEFINE2(process_mrelease, int, pidfd, unsigned int, flags)\n--\nmm/oom_kill.c-1200-\nmm/oom_kill.c:1201:\ttask = pidfd_get_task(pidfd, \u0026f_flags);\nmm/oom_kill.c-1202-\tif (IS_ERR(task))\n"
}

47/3 2026/11/20 23:09 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 39386
							output: 33
							thoughts: 30
						

Thoughts:
Okay, let's dive into this. Here's how I'd approach that kernel code:

**Diving into `pidfd_get_task` in `kernel/pid.c`**

Alright, I need to refresh my memory on the inner workings of `pidfd_get_task`. The system calls related to `pidfd` can be tricky with the whole task management abstraction and all, so let's start by pinpointing the relevant code. I'm going to head directly to `kernel/pid.c` and specifically line 622 – that should be a good starting point. I want to make sure I really understand *exactly* what `pidfd_get_task` is doing under the hood, particularly how it relates to task retrieval. There are subtle details that can be easy to miss, and my understanding of the implications of those nuances is critical to any potential debugging or optimization I might need to do. I need to refresh the details of the logic to refresh how `pidfd_get_task` interacts with the PID namespace, and task structure dereferencing. Let's see if there are any gotchas in there.



48/3 2026/11/20 23:09 tool read-file
0m Args:
{
  "File": "kernel/pid.c",
  "FirstLine": 620,
  "LineCount": 25
}

Results:
{
  "Contents": " 620:\t *\t   On error, a negative errno number will be returned.\n 621:\t */\n 622:\tstruct task_struct *pidfd_get_task(int pidfd, unsigned int *flags)\n 623:\t{\n 624:\t\tunsigned int f_flags = 0;\n 625:\t\tstruct pid *pid;\n 626:\t\tstruct task_struct *task;\n 627:\t\tenum pid_type type;\n 628:\t\n 629:\t\tswitch (pidfd) {\n 630:\t\tcase  PIDFD_SELF_THREAD:\n 631:\t\t\ttype = PIDTYPE_PID;\n 632:\t\t\tpid = get_task_pid(current, type);\n 633:\t\t\tbreak;\n 634:\t\tcase  PIDFD_SELF_THREAD_GROUP:\n 635:\t\t\ttype = PIDTYPE_TGID;\n 636:\t\t\tpid = get_task_pid(current, type);\n 637:\t\t\tbreak;\n 638:\t\tdefault:\n 639:\t\t\tpid = pidfd_get_pid(pidfd, \u0026f_flags);\n 640:\t\t\tif (IS_ERR(pid))\n 641:\t\t\t\treturn ERR_CAST(pid);\n 642:\t\t\ttype = PIDTYPE_TGID;\n 643:\t\t\tbreak;\n 644:\t\t}\n"
}

49/3 2026/11/20 23:09 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 40059
							output: 30
							thoughts: 654
						

Thoughts:
**Analyzing Memory Accounting in the DMA-BUF Subsystem**

Okay, let's break this down. My initial observation is about `pidfd_get_task`. It sets a `flags` pointer if it's not NULL, but it appears that the value itself isn't used within the context of `get_obj_cgroup_from_fd`. That's a potential area for cleanup, though I need to understand the larger context to be certain it's truly dead code.

Now, let's shift focus to `obj_cgroup_transfer_charge`. This is where the core memory accounting logic resides, and it's getting called with the `dmabuf->objcg` in `dma_buf_xfer_charge`. The function itself manages transferring memory charges between object cgroups. The key is in how it interacts with the memcg hierarchy. I see that it attempts to "charge" the new memcg using `try_charge`. If that fails, it returns. If it succeeds, it modifies the memcg state (using `mod_memcg_state`) and *uncharges* the old memcg if there was one. It looks like it's taking care of the object cgroup references, too, with get/put operations to ensure correct refcounting. Crucially, the transfer is locked under `dma_resv_lock`, so that's good to see.

The relevant item is `MEMCG_DMABUF`, which is associated with "dmabuf" in the `memory.stat` output. My next thought is how these dmabuf stats are actually exposed. Are they visible via seq_file or sysfs? I need to track down how `memory_stats` is read to understand the user-visible information and the flow of this data. A quick search within the code should reveal where `memory_stat_show` (or a similar function) reads from the `memory_stats` array. That should give me the complete picture of what's being accounted for and how it's being presented to the user.



50/3 2026/11/20 23:09 tool grepper
0m Args:
{
  "Expression": "memory_stats",
  "PathPrefixes": [
    "mm/memcontrol.c"
  ]
}

Results:
{
  "Output": "mm/memcontrol.c=1609=struct memory_stat {\n--\nmm/memcontrol.c-1613-\nmm/memcontrol.c:1614:static const struct memory_stat memory_stats[] = {\nmm/memcontrol.c-1615-\t{ \"anon\",\t\t\tNR_ANON_MAPPED\t\t\t},\n--\nmm/memcontrol.c=1762=static void memcg_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)\n--\nmm/memcontrol.c-1777-\nmm/memcontrol.c:1778:\tfor (i = 0; i \u003c ARRAY_SIZE(memory_stats); i++) {\nmm/memcontrol.c-1779-\t\tu64 size;\n--\nmm/memcontrol.c-1781-#ifdef CONFIG_HUGETLB_PAGE\nmm/memcontrol.c:1782:\t\tif (unlikely(memory_stats[i].idx == NR_HUGETLB) \u0026\u0026\nmm/memcontrol.c-1783-\t\t\t!memcg_accounts_hugetlb())\n--\nmm/memcontrol.c-1785-#endif\nmm/memcontrol.c:1786:\t\tsize = memcg_page_state_output(memcg, memory_stats[i].idx);\nmm/memcontrol.c:1787:\t\tseq_buf_printf(s, \"%s %llu\\n\", memory_stats[i].name, size);\nmm/memcontrol.c-1788-\nmm/memcontrol.c:1789:\t\tif (unlikely(memory_stats[i].idx == NR_SLAB_UNRECLAIMABLE_B)) {\nmm/memcontrol.c-1790-\t\t\tsize += memcg_page_state_output(memcg,\n--\nmm/memcontrol.c=5292=static int memory_numa_stat_show(struct seq_file *m, void *v)\n--\nmm/memcontrol.c-5298-\nmm/memcontrol.c:5299:\tfor (i = 0; i \u003c ARRAY_SIZE(memory_stats); i++) {\nmm/memcontrol.c-5300-\t\tint nid;\nmm/memcontrol.c-5301-\nmm/memcontrol.c:5302:\t\tif (memory_stats[i].idx \u003e= NR_VM_NODE_STAT_ITEMS)\nmm/memcontrol.c-5303-\t\t\tcontinue;\nmm/memcontrol.c-5304-\nmm/memcontrol.c:5305:\t\tseq_printf(m, \"%s\", memory_stats[i].name);\nmm/memcontrol.c-5306-\t\tfor_each_node_state(nid, N_MEMORY) {\n--\nmm/memcontrol.c-5311-\t\t\tsize = lruvec_page_state_output(lruvec,\nmm/memcontrol.c:5312:\t\t\t\t\t\t\tmemory_stats[i].idx);\nmm/memcontrol.c-5313-\t\t\tseq_printf(m, \" N%d=%llu\", nid, size);\n"
}

51/3 2026/11/20 23:09 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 41968
							output: 31
							thoughts: 162
						

Thoughts:
**Investigating a Potential Memory Accounting Discrepancy in the memcg Subsystem**

Okay, so I'm looking at this `memcg_stat_format` function and it's using `%s %llu\n` to print the output. The `size` that it's printing comes from `memcg_page_state_output`, which is where things get interesting. I remember seeing this function used in the context of memory NUMA statistics too – `memory_numa_stat_show`, specifically. And in *that* function there's a check: `if (memory_stats[i].idx >= NR_VM_NODE_STAT_ITEMS) continue;`. That's the key. Now, `MEMCG_DMABUF` is defined as `MEMCG_NR_STAT - 1`, which means it's probably *greater* than or equal to `NR_VM_NODE_STAT_ITEMS`, depending on the value of the constants. Hmmm, that could lead to some stats being skipped and uncounted. Wait, let's back up, I need to verify how `memcg_page_state_output` actually *handles* `MEMCG_DMABUF`. So, I'm going to search for the function `memcg_page_state_output` right now. Need to see if there's any special handling or if it's being missed entirely.



52/3 2026/11/20 23:09 tool grepper
0m Args:
{
  "Expression": "memcg_page_state_output",
  "PathPrefixes": [
    "mm/"
  ]
}

Results:
{
  "Output": "mm/bpf_memcontrol.c=145=__bpf_kfunc unsigned long bpf_mem_cgroup_page_state(struct mem_cgroup *memcg, int idx)\n--\nmm/bpf_memcontrol.c-149-\nmm/bpf_memcontrol.c:150:\treturn memcg_page_state_output(memcg, idx);\nmm/bpf_memcontrol.c-151-}\n--\nmm/memcontrol-v1.c=1885=void memcg1_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)\n--\nmm/memcontrol-v1.c-1924-\nmm/memcontrol-v1.c:1925:\t\tnr = memcg_page_state_output(memcg, memcg1_stats[i]);\nmm/memcontrol-v1.c-1926-\t\tseq_buf_printf(s, \"total_%s %llu\\n\", memcg1_stat_names[i],\n--\nmm/memcontrol.c=1681=static int memcg_page_state_unit(int item)\n--\nmm/memcontrol.c-1696-/* Translate stat items to the correct unit for memory.stat output */\nmm/memcontrol.c:1697:static int memcg_page_state_output_unit(int item)\nmm/memcontrol.c-1698-{\n--\nmm/memcontrol.c-1735-\nmm/memcontrol.c:1736:unsigned long memcg_page_state_output(const struct mem_cgroup *memcg, int item)\nmm/memcontrol.c-1737-{\nmm/memcontrol.c-1738-\treturn memcg_page_state(memcg, item) *\nmm/memcontrol.c:1739:\t\tmemcg_page_state_output_unit(item);\nmm/memcontrol.c-1740-}\n--\nmm/memcontrol.c=1743=unsigned long memcg_page_state_local_output(const struct mem_cgroup *memcg, int item)\n--\nmm/memcontrol.c-1745-\treturn memcg_page_state_local(memcg, item) *\nmm/memcontrol.c:1746:\t\tmemcg_page_state_output_unit(item);\nmm/memcontrol.c-1747-}\n--\nmm/memcontrol.c=1762=static void memcg_stat_format(struct mem_cgroup *memcg, struct seq_buf *s)\n--\nmm/memcontrol.c-1785-#endif\nmm/memcontrol.c:1786:\t\tsize = memcg_page_state_output(memcg, memory_stats[i].idx);\nmm/memcontrol.c-1787-\t\tseq_buf_printf(s, \"%s %llu\\n\", memory_stats[i].name, size);\n--\nmm/memcontrol.c-1789-\t\tif (unlikely(memory_stats[i].idx == NR_SLAB_UNRECLAIMABLE_B)) {\nmm/memcontrol.c:1790:\t\t\tsize += memcg_page_state_output(memcg,\nmm/memcontrol.c-1791-\t\t\t\t\t\t\tNR_SLAB_RECLAIMABLE_B);\n--\nmm/memcontrol.c=5285=static inline unsigned long lruvec_page_state_output(struct lruvec *lruvec,\n--\nmm/memcontrol.c-5288-\treturn lruvec_page_state(lruvec, item) *\nmm/memcontrol.c:5289:\t\tmemcg_page_state_output_unit(item);\nmm/memcontrol.c-5290-}\n"
}

53/3 2026/11/20 23:09 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 43414
							output: 35
							thoughts: 19
						

Thoughts:
Here's a summary of my thought process, as requested:

**Diving into `memcg_page_state_output_unit(item)`**

Okay, time to get a closer look at this `memcg_page_state_output_unit(item)` function. My intuition tells me this likely plays a crucial role in how memory cgroup page state information is formatted and presented. I'm probably looking at the core logic for unit conversion or formatting of page state counters, maybe for reporting purposes. It’s either handling the raw page count or converting it into a more human-readable format, such as kilobytes, megabytes, or even gigabytes, depending on the context. I'll need to dissect its implementation to understand precisely how it operates and where it fits within the larger memory accounting picture. Let's see how it handles the different `item` types that it accepts as input.



54/3 2026/11/20 23:10 tool read-file
0m Args:
{
  "File": "mm/memcontrol.c",
  "FirstLine": 1696,
  "LineCount": 40
}

Results:
{
  "Contents": "1696:\t/* Translate stat items to the correct unit for memory.stat output */\n1697:\tstatic int memcg_page_state_output_unit(int item)\n1698:\t{\n1699:\t\t/*\n1700:\t\t * Workingset state is actually in pages, but we export it to userspace\n1701:\t\t * as a scalar count of events, so special case it here.\n1702:\t\t *\n1703:\t\t * Demotion and promotion activities are exported in pages, consistent\n1704:\t\t * with their global counterparts.\n1705:\t\t */\n1706:\t\tswitch (item) {\n1707:\t\tcase WORKINGSET_REFAULT_ANON:\n1708:\t\tcase WORKINGSET_REFAULT_FILE:\n1709:\t\tcase WORKINGSET_ACTIVATE_ANON:\n1710:\t\tcase WORKINGSET_ACTIVATE_FILE:\n1711:\t\tcase WORKINGSET_RESTORE_ANON:\n1712:\t\tcase WORKINGSET_RESTORE_FILE:\n1713:\t\tcase WORKINGSET_NODERECLAIM:\n1714:\t\tcase PGDEMOTE_KSWAPD:\n1715:\t\tcase PGDEMOTE_DIRECT:\n1716:\t\tcase PGDEMOTE_KHUGEPAGED:\n1717:\t\tcase PGDEMOTE_PROACTIVE:\n1718:\t\tcase PGSTEAL_KSWAPD:\n1719:\t\tcase PGSTEAL_DIRECT:\n1720:\t\tcase PGSTEAL_KHUGEPAGED:\n1721:\t\tcase PGSTEAL_PROACTIVE:\n1722:\t\tcase PGSCAN_KSWAPD:\n1723:\t\tcase PGSCAN_DIRECT:\n1724:\t\tcase PGSCAN_KHUGEPAGED:\n1725:\t\tcase PGSCAN_PROACTIVE:\n1726:\t\tcase PGREFILL:\n1727:\t#ifdef CONFIG_NUMA_BALANCING\n1728:\t\tcase PGPROMOTE_SUCCESS:\n1729:\t#endif\n1730:\t\t\treturn 1;\n1731:\t\tdefault:\n1732:\t\t\treturn memcg_page_state_unit(item);\n1733:\t\t}\n1734:\t}\n1735:\t\n"
}

55/3 2026/11/20 23:10 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 44255
							output: 35
							thoughts: 38
						

Thoughts:
Okay, let's dive into this.

**Investigating `memcg_page_state_unit`**

Alright, so `memcg_page_state_unit`... it's a piece of the puzzle I'm not immediately familiar with. Time to get my hands dirty. I'll head straight to the source. Lines 1675-1695 of `mm/memcontrol.c` are likely where I'll find its definition and usage. That's usually the best starting point for understanding these core memory management structures. I'm expecting to find its data structure and usage. From there, I can likely infer its purpose in the overall memory control scheme. Let's see what's what.



56/3 2026/11/20 23:10 tool read-file
0m Args:
{
  "File": "mm/memcontrol.c",
  "FirstLine": 1675,
  "LineCount": 25
}

Results:
{
  "Contents": "1675:\t#ifdef CONFIG_NUMA_BALANCING\n1676:\t\t{ \"pgpromote_success\",\t\tPGPROMOTE_SUCCESS\t},\n1677:\t#endif\n1678:\t};\n1679:\t\n1680:\t/* The actual unit of the state item, not the same as the output unit */\n1681:\tstatic int memcg_page_state_unit(int item)\n1682:\t{\n1683:\t\tswitch (item) {\n1684:\t\tcase MEMCG_PERCPU_B:\n1685:\t\tcase MEMCG_ZSWAP_B:\n1686:\t\tcase NR_SLAB_RECLAIMABLE_B:\n1687:\t\tcase NR_SLAB_UNRECLAIMABLE_B:\n1688:\t\t\treturn 1;\n1689:\t\tcase NR_KERNEL_STACK_KB:\n1690:\t\t\treturn SZ_1K;\n1691:\t\tdefault:\n1692:\t\t\treturn PAGE_SIZE;\n1693:\t\t}\n1694:\t}\n1695:\t\n1696:\t/* Translate stat items to the correct unit for memory.stat output */\n1697:\tstatic int memcg_page_state_output_unit(int item)\n1698:\t{\n1699:\t\t/*\n"
}

57/3 2026/11/20 23:10 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 44842
							output: 530
							thoughts: 2370
						

Thoughts:
**KMSAN Assessment: No Uninitialized Memory Risks Detected**

Alright, let's break this down. My goal here is to determine whether this patch series warrants a KMSAN (Kernel Memory Sanitizer) fuzzing session. The guiding principle is clear: KMSAN is a costly tool, so it's only justified if the changes introduce *new* risks specifically detectable by KMSAN – uninitialized memory reads, or information leaks to userspace – that wouldn't be caught by KASAN, LOCKDEP, or standard bug detectors.

First, I need to understand the patch's scope. It's focused on introducing memory cgroup (memcg) accounting and charge transfer mechanisms for dma-buf allocations.  This involves adding new `DMA_BUF_IOCTL_XFER_CHARGE` and `charge_fd` fields to existing structures, along with the necessary hooks into the LSM (Linux Security Modules) and memcg tracking functions.

Now, the critical part: let's analyze the structures that interact with userspace.  I'm looking for any potential for uninitialized data to leak.  `struct dma_buf_transfer_charge` is input-only (`_IOW`), accepting `flags` and `charge_fd`.  A quick check reveals no padding holes, meaning the 8 bytes are accounted for. This is a non-issue.  `struct dma_heap_allocation_data` is bidirectional (`_IOWR`). Adding `charge_fd` and `__padding` (which is zeroed) doesn't introduce padding holes, thanks to natural alignment and the architecture's inherent data layout.  Furthermore, I see that the `dma_heap_ioctl()` code explicitly sanitizes and zero-initializes the kernel buffer via `memset()` before `copy_to_user()`, addressing older user-space structs.

Next, I need to meticulously review the kernel-side code paths.  Are any uninitialized stack or heap variables being read or used in conditional logic? No, nothing jumps out. All allocations use zero-initializing allocators like `kzalloc` or `kzalloc_obj`, and variables are assigned before use.

Finally, I have to consider any possibility of information leaks via bounds checks or length calculations that might expose uninitialized heap or stack memory. The code uses `PAGE_ALIGN` and `PAGE_SHIFT` to calculate the number of pages for memcg accounting, which does not result in an indexing into any buffer.

My conclusion is clear.  This patch series does *not* introduce or expose any uninitialized memory risks.  The changes primarily involve resource accounting, permissions, and error handling.  Therefore, potential bugs in this patch series will fall under standard bug detectors such as KASAN and LOCKDEP. KMSAN is overkill.  KMSAN would be a waste of resources, and likely would not have found any bugs specific to this patch.

I will now call `set-results` and provide the relevant reasoning to justify this finding.



58/3 2026/11/20 23:10 tool set-results
0m Args:
{
  "KMSANReasoning": "The patch series implements memory cgroup (memcg) accounting for dma-buf allocations and allows transferring charges between cgroups via DMA_BUF_IOCTL_XFER_CHARGE and an extended DMA_HEAP_IOCTL_ALLOC.\n\nKMSAN vs KASAN Applicability Analysis:\n1. KMSAN is specifically designed to catch reads of uninitialized stack, heap, or page allocations and uninitialized info-leaks to userspace.\n2. The user-facing structures touched or added:\n   - `struct dma_buf_transfer_charge` is strictly an input structure (_IOW) composed of two `__u32` members (`flags` and `charge_fd`) totaling 8 bytes, with no padding holes and never copied back to userspace.\n   - `struct dma_heap_allocation_data` is updated to include `__u32 charge_fd` and `__u32 __padding`. With members `len` (8B), `fd` (4B), `fd_flags` (4B), `heap_flags` (8B), `charge_fd` (4B), and `__padding` (4B), the struct size is exactly 32 bytes with natural alignment and zero compiler padding holes. In `dma_heap_ioctl()`, any delta between kernel and userspace argument size is explicitly zeroed with `memset` before any potential `copy_to_user()`.\n3. In-kernel allocations (e.g. `dma_buf`, `system_heap_buffer`) continue to use zero-allocating APIs (`kzalloc()`, `kzalloc_obj()`).\n4. All local variables and pointers introduced in `mm/memcontrol.c` and `drivers/dma-buf/` are explicitly initialized or set by reference prior to being evaluated or dereferenced.\n5. The core risks of these changes involve reference counting (`obj_cgroup_get`/`put`, `css_tryget_online`), locking (`dma_resv_lock`), permissions (LSM hooks and `capable(CAP_SYS_RESOURCE)`), and memory accounting limits (`try_charge`), which fall under functional testing, LOCKDEP, and KASAN.\n\nBecause there are no uninitialized memory risks or info-leaks, spawning a dedicated KMSAN fuzzing session is not justified.",
  "NeedsKMSAN": false
}

Results:
{
  "KMSANReasoning": "The patch series implements memory cgroup (memcg) accounting for dma-buf allocations and allows transferring charges between cgroups via DMA_BUF_IOCTL_XFER_CHARGE and an extended DMA_HEAP_IOCTL_ALLOC.\n\nKMSAN vs KASAN Applicability Analysis:\n1. KMSAN is specifically designed to catch reads of uninitialized stack, heap, or page allocations and uninitialized info-leaks to userspace.\n2. The user-facing structures touched or added:\n   - `struct dma_buf_transfer_charge` is strictly an input structure (_IOW) composed of two `__u32` members (`flags` and `charge_fd`) totaling 8 bytes, with no padding holes and never copied back to userspace.\n   - `struct dma_heap_allocation_data` is updated to include `__u32 charge_fd` and `__u32 __padding`. With members `len` (8B), `fd` (4B), `fd_flags` (4B), `heap_flags` (8B), `charge_fd` (4B), and `__padding` (4B), the struct size is exactly 32 bytes with natural alignment and zero compiler padding holes. In `dma_heap_ioctl()`, any delta between kernel and userspace argument size is explicitly zeroed with `memset` before any potential `copy_to_user()`.\n3. In-kernel allocations (e.g. `dma_buf`, `system_heap_buffer`) continue to use zero-allocating APIs (`kzalloc()`, `kzalloc_obj()`).\n4. All local variables and pointers introduced in `mm/memcontrol.c` and `drivers/dma-buf/` are explicitly initialized or set by reference prior to being evaluated or dereferenced.\n5. The core risks of these changes involve reference counting (`obj_cgroup_get`/`put`, `css_tryget_online`), locking (`dma_resv_lock`), permissions (LSM hooks and `capable(CAP_SYS_RESOURCE)`), and memory accounting limits (`try_charge`), which fall under functional testing, LOCKDEP, and KASAN.\n\nBecause there are no uninitialized memory risks or info-leaks, spawning a dedicated KMSAN fuzzing session is not justified.",
  "NeedsKMSAN": false
}

LLM Calls Summary:
Total Calls Total Tokens Avg Tokens Total Duration (Seconds) Avg Duration (Seconds)
Tool Calls Summary:
Total Calls Total Duration (Seconds) Avg Duration (Seconds)