Skip to contentSkip to conversation

kernel/cgroups: Add "dmem" memory accounting cgroup.

PATCH In review Maarten Lankhorst 9 participants 38 messages Dec 4, 2024 – Jan 14, 2025

Subsystems (11)
lore
Share & tools
lore

Maarten Lankhorst

author maintainer
#0 lore raw

v2 cover kernel/cgroups: Add "dmem" memory accounting cgroup.

New update. Instead of calling it the 'dev' cgroup, it's now the 'dmem' cgroup.

Because it only deals with memory regions, the UAPI has been updated to use dmem.min/low/max/current, and to make the API cleaner, the names are changed too.

dmem.current could contain a line like:
"drm/0000:03:00.0/vram0 1073741824"

But I think using "drm/card0/vram0" instead of PCIID would perhaps be good too. I'm open to changing it to that based on feedback.

I've created an IGT test for min and max, and found the changes from Friedrich Vock sent as feedback were needed. I've integrated those into the first patch.

Maarten Lankhorst (5):
kernel/cgroup: Add "dmem" memory accounting cgroup drm/ttm: Handle cgroup based eviction in TTM drm/xe: Implement cgroup for vram
drm/amdgpu: Add cgroups implementation
drm/xe: Hack to test with mapped pages instead of vram.

Maxime Ripard (2):
drm/drv: Add drmm managed registration helper for dmem cgroups. drm/gem: Add cgroup memory accounting for VRAM helper.

 Documentation/admin-guide/cgroup-v2.rst       |  58 +-
 Documentation/core-api/cgroup.rst             |   9 +
 Documentation/core-api/index.rst              |   1 +
 Documentation/gpu/drm-compute.rst             |  54 ++
 drivers/gpu/drm/amd/amdgpu/amdgpu_vram_mgr.c  |   4 +
 drivers/gpu/drm/drm_drv.c                     |  32 +
 drivers/gpu/drm/drm_gem_vram_helper.c         |  15 +-
 drivers/gpu/drm/ttm/tests/ttm_bo_test.c       |  18 +-
 .../gpu/drm/ttm/tests/ttm_bo_validate_test.c  |   4 +-
 drivers/gpu/drm/ttm/tests/ttm_resource_test.c |   2 +-
 drivers/gpu/drm/ttm/ttm_bo.c                  |  54 +-
 drivers/gpu/drm/ttm/ttm_resource.c            |  23 +-
 drivers/gpu/drm/xe/xe_ttm_sys_mgr.c           |   5 +
 drivers/gpu/drm/xe/xe_ttm_vram_mgr.c          |   8 +
 include/drm/drm_drv.h                         |   5 +
 include/drm/ttm/ttm_resource.h                |  12 +-
 include/linux/cgroup_dmem.h                   |  67 ++
 include/linux/cgroup_subsys.h                 |   4 +
 include/linux/page_counter.h                  |   2 +-
 init/Kconfig                                  |  10 +
 kernel/cgroup/Makefile                        |   1 +
 kernel/cgroup/dmem.c                          | 861 ++++++++++++++++++
 mm/page_counter.c                             |   4 +-
 23 files changed, 1219 insertions(+), 34 deletions(-)
 create mode 100644 Documentation/core-api/cgroup.rst
 create mode 100644 Documentation/gpu/drm-compute.rst
 create mode 100644 include/linux/cgroup_dmem.h
 create mode 100644 kernel/cgroup/dmem.c
Signature · 1 line
2.43.0
author maintainer
#1 lore raw

PATCH v2 1/7 kernel/cgroup: Add "dmem" memory accounting cgroup

This code is based on the RDMA and misc cgroup initially, but now uses page_counter. It uses the same min/low/max semantics as the memory cgroup as a result.

There's a small mismatch as TTM uses u64, and page_counter long pages. In practice it's not a problem. 32-bits systems don't really come with

Quoted 1 line

=4GB cards and as long as we're consistently wrong with units, it's

fine. The device page size may not be in the same units as kernel page size, and each region might also have a different page size (VRAM vs GART for example).

The interface is simple:
- Call dmem_cgroup_register_region()
- Use dmem_cgroup_try_charge to check if you can allocate a chunk of memory, use dmem_cgroup__uncharge when freeing it. This may return an error code, or -EAGAIN when the cgroup limit is reached. In that case a reference to the limiting pool is returned.
- The limiting cs can be used as compare function for dmem_cgroup_state_evict_valuable.
- After having evicted enough, drop reference to limiting cs with dmem_cgroup_pool_state_put.

This API allows you to limit device resources with cgroups. You can see the supported cards in /sys/fs/cgroup/dmem.capacity You need to echo +dmem to cgroup.subtree_control, and then you can partition device memory.

---
 Documentation/admin-guide/cgroup-v2.rst |  58 +-
 Documentation/core-api/cgroup.rst       |   9 +
 Documentation/core-api/index.rst        |   1 +
 Documentation/gpu/drm-compute.rst       |  54 ++
 include/linux/cgroup_dmem.h             |  67 ++
 include/linux/cgroup_subsys.h           |   4 +
 include/linux/page_counter.h            |   2 +-
 init/Kconfig                            |  10 +
 kernel/cgroup/Makefile                  |   1 +
 kernel/cgroup/dmem.c                    | 861 ++++++++++++++++++++++++
 mm/page_counter.c                       |   4 +-
 11 files changed, 1061 insertions(+), 10 deletions(-)
 create mode 100644 Documentation/core-api/cgroup.rst
 create mode 100644 Documentation/gpu/drm-compute.rst
 create mode 100644 include/linux/cgroup_dmem.h
 create mode 100644 kernel/cgroup/dmem.c
Documentation/admin-guide/cgroup-v2.rst +51 -7
index 315ede811c9d0..cb1b4e759b7e2 100644
@@ -64,13 +64,14 @@ v1 is available under :ref:`Documentation/admin-guide/cgroup-v1/index.rst <cgrou
      5-6. Device
      5-7. RDMA
        5-7-1. RDMA Interface Files
-     5-8. HugeTLB
-       5.8-1. HugeTLB Interface Files
-     5-9. Misc
-       5.9-1 Miscellaneous cgroup Interface Files
-       5.9-2 Migration and Ownership
-     5-10. Others
-       5-10-1. perf_event
+     5-8. DMEM
+     5-9. HugeTLB
+       5.9-1. HugeTLB Interface Files
+     5-10. Misc
+       5.10-1 Miscellaneous cgroup Interface Files
+       5.10-2 Migration and Ownership
+     5-11. Others
+       5-11-1. perf_event
      5-N. Non-normative information
        5-N-1. CPU controller root cgroup process behaviour
        5-N-2. IO controller root cgroup process behaviour
@@ -2626,6 +2627,49 @@ RDMA Interface Files
 	  mlx4_0 hca_handle=1 hca_object=20
 	  ocrdma1 hca_handle=1 hca_object=23
 
+DMEM
+----
+
+The "dmem" controller regulates the distribution and accounting of
+device memory regions. Because each memory region may have its own page size,
+which does not have to be equal to the system page size, the units are always bytes.
+
+DMEM Interface Files
+~~~~~~~~~~~~~~~~~~~~
+
+  dmem.max, dmem.min, dmem.low
+	A readwrite nested-keyed file that exists for all the cgroups
+	except root that describes current configured resource limit
+	for a region.
+
+	An example for xe follows::
+
+	  drm/0000:03:00.0/vram0 1073741824
+	  drm/0000:03:00.0/stolen max
+
+	The semantics are the same as for the memory cgroup controller, and are
+	calculated in the same way.
+
+  dmem.capacity
+	A read-only file that describes maximum region capacity.
+	It only exists on the root cgroup. Not all memory can be
+	allocated by cgroups, as the kernel reserves some for
+	internal use.
+
+	An example for xe follows::
+
+	  drm/0000:03:00.0/vram0 8514437120
+	  drm/0000:03:00.0/stolen 67108864
+
+  dmem.current
+	A read-only file that describes current resource usage.
+	It exists for all the cgroup except root.
+
+	An example for xe follows::
+
+	  drm/0000:03:00.0/vram0 12550144
+	  drm/0000:03:00.0/stolen 8650752
+
 HugeTLB
 -------
 
Documentation/core-api/cgroup.rst new file +9 -0
new file mode 100644
index 0000000000000..8696e9513f511
@@ -0,0 +1,9 @@
+==================
+Cgroup Kernel APIs
+==================
+
+Device Memory Cgroup API (dmemcg)
+=========================
+.. kernel-doc:: kernel/cgroup/dmem.c
+   :export:
+
Documentation/core-api/index.rst +1 -0
index 563b8fc0002f7..913d91feaf760 100644
@@ -109,6 +109,7 @@ more memory-management documentation in Documentation/mm/index.rst.
    dma-isa-lpc
    swiotlb
    mm-api
+   cgroup
    genalloc
    pin_user_pages
    boot-time-mm
Documentation/gpu/drm-compute.rst new file +54 -0

54 lines not on this page · raw message

include/linux/cgroup_dmem.h new file +67 -0

67 lines not on this page · raw message

include/linux/cgroup_subsys.h +4 -0
index 4452354872307..3fd0bcbf30803 100644
@@ -65,6 +65,10 @@ SUBSYS(rdma)
 SUBSYS(misc)
 #endif
 
+#if IS_ENABLED(CONFIG_CGROUP_DMEM)
+SUBSYS(dmem)
+#endif
+
 /*
  * The following subsystems are not supported on the default hierarchy.
  */
include/linux/page_counter.h +1 -1
index 79dbd8bc35a72..46406f3fe34d0 100644
@@ -96,7 +96,7 @@ static inline void page_counter_reset_watermark(struct page_counter *counter)
 	counter->watermark = usage;
 }
 
-#ifdef CONFIG_MEMCG
+#if IS_ENABLED(CONFIG_MEMCG) || IS_ENABLED(CONFIG_CGROUP_DMEM)
 void page_counter_calculate_protection(struct page_counter *root,
 				       struct page_counter *counter,
 				       bool recursive_protection);
init/Kconfig +10 -0
index a20e6efd3f0fb..61f50cafa8151 100644
@@ -1128,6 +1128,7 @@ config CGROUP_PIDS
 
 config CGROUP_RDMA
 	bool "RDMA controller"
+	select PAGE_COUNTER
 	help
 	  Provides enforcement of RDMA resources defined by IB stack.
 	  It is fairly easy for consumers to exhaust RDMA resources, which
@@ -1136,6 +1137,15 @@ config CGROUP_RDMA
 	  Attaching processes with active RDMA resources to the cgroup
 	  hierarchy is allowed even if can cross the hierarchy's limit.
 
+config CGROUP_DMEM
+	bool "Device memory controller (DMEM)"
+	help
+	  The DMEM controller allows compatible devices to restrict device
+	  memory usage based on the cgroup hierarchy.
+
+	  As an example, it allows you to restrict VRAM usage for applications
+	  in the DRM subsystem.
+
 config CGROUP_FREEZER
 	bool "Freezer controller"
 	help
kernel/cgroup/Makefile +1 -0
index a5c9359d516f8..ede31601a363a 100644
@@ -7,4 +7,5 @@ obj-$(CONFIG_CGROUP_RDMA) += rdma.o
 obj-$(CONFIG_CPUSETS) += cpuset.o
 obj-$(CONFIG_CPUSETS_V1) += cpuset-v1.o
 obj-$(CONFIG_CGROUP_MISC) += misc.o
+obj-$(CONFIG_CGROUP_DMEM) += dmem.o
 obj-$(CONFIG_CGROUP_DEBUG) += debug.o
kernel/cgroup/dmem.c new file +861 -0

861 lines not on this page · raw message

mm/page_counter.c +2 -2
index b249d15af9dd8..af23f927611b7 100644
@@ -288,7 +288,7 @@ int page_counter_memparse(const char *buf, const char *max,
 }
 
 
-#ifdef CONFIG_MEMCG
+#if IS_ENABLED(CONFIG_MEMCG) || IS_ENABLED(CONFIG_CGROUP_DMEM)
 /*
  * This function calculates an individual page counter's effective
  * protection which is derived from its own memory.min/low, its
@@ -460,4 +460,4 @@ void page_counter_calculate_protection(struct page_counter *root,
 			atomic_long_read(&parent->children_low_usage),
 			recursive_protection));
 }
-#endif /* CONFIG_MEMCG */
+#endif /* CONFIG_MEMCG || CONFIG_CGROUP_DMEM */
Signature · 1 line
2.43.0
author maintainer
#2 lore raw

PATCH 1/1 kernel/cgroup: Add "dmem" memory accounting cgroup

This code is based on the RDMA and misc cgroup initially, but now uses page_counter. It uses the same min/low/max semantics as the memory cgroup as a result.

There's a small mismatch as TTM uses u64, and page_counter long pages. In practice it's not a problem. 32-bits systems don't really come with

Quoted 1 line

=4GB cards and as long as we're consistently wrong with units, it's

fine. The device page size may not be in the same units as kernel page size, and each region might also have a different page size (VRAM vs GART for example).

The interface is simple:
- Call dmem_cgroup_register_region()
- Use dmem_cgroup_try_charge to check if you can allocate a chunk of memory, use dmem_cgroup__uncharge when freeing it. This may return an error code, or -EAGAIN when the cgroup limit is reached. In that case a reference to the limiting pool is returned.
- The limiting cs can be used as compare function for dmem_cgroup_state_evict_valuable.
- After having evicted enough, drop reference to limiting cs with dmem_cgroup_pool_state_put.

This API allows you to limit device resources with cgroups. You can see the supported cards in /sys/fs/cgroup/dmem.capacity You need to echo +dmem to cgroup.subtree_control, and then you can partition device memory.

---
I completely messed up the !CONFIG_CGROUP_DMEM path. Resending just this patch to compile cleanly without CONFIG_CGROUP_DMEM enabled.

 Documentation/admin-guide/cgroup-v2.rst |  58 +-
 Documentation/core-api/cgroup.rst       |   9 +
 Documentation/core-api/index.rst        |   1 +
 Documentation/gpu/drm-compute.rst       |  54 ++
 include/linux/cgroup_dmem.h             |  66 ++
 include/linux/cgroup_subsys.h           |   4 +
 include/linux/page_counter.h            |   2 +-
 init/Kconfig                            |  10 +
 kernel/cgroup/Makefile                  |   1 +
 kernel/cgroup/dmem.c                    | 861 ++++++++++++++++++++++++
 mm/page_counter.c                       |   4 +-
 11 files changed, 1060 insertions(+), 10 deletions(-)
 create mode 100644 Documentation/core-api/cgroup.rst
 create mode 100644 Documentation/gpu/drm-compute.rst
 create mode 100644 include/linux/cgroup_dmem.h
 create mode 100644 kernel/cgroup/dmem.c
Documentation/admin-guide/cgroup-v2.rst +51 -7
index 315ede811c9d0..cb1b4e759b7e2 100644
@@ -64,13 +64,14 @@ v1 is available under :ref:`Documentation/admin-guide/cgroup-v1/index.rst <cgrou
      5-6. Device
      5-7. RDMA
        5-7-1. RDMA Interface Files
-     5-8. HugeTLB
-       5.8-1. HugeTLB Interface Files
-     5-9. Misc
-       5.9-1 Miscellaneous cgroup Interface Files
-       5.9-2 Migration and Ownership
-     5-10. Others
-       5-10-1. perf_event
+     5-8. DMEM
+     5-9. HugeTLB
+       5.9-1. HugeTLB Interface Files
+     5-10. Misc
+       5.10-1 Miscellaneous cgroup Interface Files
+       5.10-2 Migration and Ownership
+     5-11. Others
+       5-11-1. perf_event
      5-N. Non-normative information
        5-N-1. CPU controller root cgroup process behaviour
        5-N-2. IO controller root cgroup process behaviour
@@ -2626,6 +2627,49 @@ RDMA Interface Files
 	  mlx4_0 hca_handle=1 hca_object=20
 	  ocrdma1 hca_handle=1 hca_object=23
 
+DMEM
+----
+
+The "dmem" controller regulates the distribution and accounting of
+device memory regions. Because each memory region may have its own page size,
+which does not have to be equal to the system page size, the units are always bytes.
+
+DMEM Interface Files
+~~~~~~~~~~~~~~~~~~~~
+
+  dmem.max, dmem.min, dmem.low
+	A readwrite nested-keyed file that exists for all the cgroups
+	except root that describes current configured resource limit
+	for a region.
+
+	An example for xe follows::
+
+	  drm/0000:03:00.0/vram0 1073741824
+	  drm/0000:03:00.0/stolen max
+
+	The semantics are the same as for the memory cgroup controller, and are
+	calculated in the same way.
+
+  dmem.capacity
+	A read-only file that describes maximum region capacity.
+	It only exists on the root cgroup. Not all memory can be
+	allocated by cgroups, as the kernel reserves some for
+	internal use.
+
+	An example for xe follows::
+
+	  drm/0000:03:00.0/vram0 8514437120
+	  drm/0000:03:00.0/stolen 67108864
+
+  dmem.current
+	A read-only file that describes current resource usage.
+	It exists for all the cgroup except root.
+
+	An example for xe follows::
+
+	  drm/0000:03:00.0/vram0 12550144
+	  drm/0000:03:00.0/stolen 8650752
+
 HugeTLB
 -------
 
Documentation/core-api/cgroup.rst new file +9 -0
new file mode 100644
index 0000000000000..8696e9513f511
@@ -0,0 +1,9 @@
+==================
+Cgroup Kernel APIs
+==================
+
+Device Memory Cgroup API (dmemcg)
+=========================
+.. kernel-doc:: kernel/cgroup/dmem.c
+   :export:
+
Documentation/core-api/index.rst +1 -0
index 563b8fc0002f7..913d91feaf760 100644
@@ -109,6 +109,7 @@ more memory-management documentation in Documentation/mm/index.rst.
    dma-isa-lpc
    swiotlb
    mm-api
+   cgroup
    genalloc
    pin_user_pages
    boot-time-mm
Documentation/gpu/drm-compute.rst new file +54 -0

54 lines not on this page · raw message

include/linux/cgroup_dmem.h new file +66 -0

66 lines not on this page · raw message

include/linux/cgroup_subsys.h +4 -0
index 4452354872307..3fd0bcbf30803 100644
@@ -65,6 +65,10 @@ SUBSYS(rdma)
 SUBSYS(misc)
 #endif
 
+#if IS_ENABLED(CONFIG_CGROUP_DMEM)
+SUBSYS(dmem)
+#endif
+
 /*
  * The following subsystems are not supported on the default hierarchy.
  */
include/linux/page_counter.h +1 -1
index 79dbd8bc35a72..46406f3fe34d0 100644
@@ -96,7 +96,7 @@ static inline void page_counter_reset_watermark(struct page_counter *counter)
 	counter->watermark = usage;
 }
 
-#ifdef CONFIG_MEMCG
+#if IS_ENABLED(CONFIG_MEMCG) || IS_ENABLED(CONFIG_CGROUP_DMEM)
 void page_counter_calculate_protection(struct page_counter *root,
 				       struct page_counter *counter,
 				       bool recursive_protection);
init/Kconfig +10 -0
index a20e6efd3f0fb..61f50cafa8151 100644
@@ -1128,6 +1128,7 @@ config CGROUP_PIDS
 
 config CGROUP_RDMA
 	bool "RDMA controller"
+	select PAGE_COUNTER
 	help
 	  Provides enforcement of RDMA resources defined by IB stack.
 	  It is fairly easy for consumers to exhaust RDMA resources, which
@@ -1136,6 +1137,15 @@ config CGROUP_RDMA
 	  Attaching processes with active RDMA resources to the cgroup
 	  hierarchy is allowed even if can cross the hierarchy's limit.
 
+config CGROUP_DMEM
+	bool "Device memory controller (DMEM)"
+	help
+	  The DMEM controller allows compatible devices to restrict device
+	  memory usage based on the cgroup hierarchy.
+
+	  As an example, it allows you to restrict VRAM usage for applications
+	  in the DRM subsystem.
+
 config CGROUP_FREEZER
 	bool "Freezer controller"
 	help
kernel/cgroup/Makefile +1 -0
index a5c9359d516f8..ede31601a363a 100644
@@ -7,4 +7,5 @@ obj-$(CONFIG_CGROUP_RDMA) += rdma.o
 obj-$(CONFIG_CPUSETS) += cpuset.o
 obj-$(CONFIG_CPUSETS_V1) += cpuset-v1.o
 obj-$(CONFIG_CGROUP_MISC) += misc.o
+obj-$(CONFIG_CGROUP_DMEM) += dmem.o
 obj-$(CONFIG_CGROUP_DEBUG) += debug.o
kernel/cgroup/dmem.c new file +861 -0

861 lines not on this page · raw message

mm/page_counter.c +2 -2
index b249d15af9dd8..af23f927611b7 100644
@@ -288,7 +288,7 @@ int page_counter_memparse(const char *buf, const char *max,
 }
 
 
-#ifdef CONFIG_MEMCG
+#if IS_ENABLED(CONFIG_MEMCG) || IS_ENABLED(CONFIG_CGROUP_DMEM)
 /*
  * This function calculates an individual page counter's effective
  * protection which is derived from its own memory.min/low, its
@@ -460,4 +460,4 @@ void page_counter_calculate_protection(struct page_counter *root,
 			atomic_long_read(&parent->children_low_usage),
 			recursive_protection));
 }
-#endif /* CONFIG_MEMCG */
+#endif /* CONFIG_MEMCG || CONFIG_CGROUP_DMEM */
Signature · 1 line
2.43.0
#3 lore raw

Re: [PATCH v2.1 1/1] kernel/cgroup: Add "dmem" memory accounting cgroup

kernel test robot noticed the following build warnings:

Hi Maarten,

kernel test robot noticed the following build warnings:

[auto build test WARNING on tj-cgroup/for-next]
[also build test WARNING on akpm-mm/mm-everything linus/master v6.13-rc1 next-20241204] [cannot apply to drm-misc/drm-misc-next drm-tip/drm-tip]
[If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Maarten-Lankhorst/kernel-cgroup-Add-dmem-memory-accounting-cgroup/20241204-233207
base:   https://git.kernel.org/pub/scm/linux/kernel/git/tj/cgroup.git for-next
patch link:    https://lore.kernel.org/r/20241204143112.1250983-1-dev%40lankhorst.se
patch subject: [PATCH v2.1 1/1] kernel/cgroup: Add "dmem" memory accounting cgroup
config: sh-allmodconfig (https://download.01.org/0day-ci/archive/20241205/[email protected]/config)
compiler: sh4-linux-gcc (GCC) 14.2.0
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20241205/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All warnings (new ones prefixed by >>):

kernel/cgroup/dmem.c: In function 'dmem_cgroup_state_evict_valuable':

>> kernel/cgroup/dmem.c:302:30: warning: variable 'climit' set but not used [-Wunused-but-set-variable]
     302 |         struct page_counter *climit, *ctest;
         |                              ^~~~~~
--
>> kernel/cgroup/dmem.c:300: warning: Excess function parameter 'dev' description in 'dmem_cgroup_state_evict_valuable'
>> kernel/cgroup/dmem.c:300: warning: Excess function parameter 'index' description in 'dmem_cgroup_state_evict_valuable'
>> kernel/cgroup/dmem.c:635: warning: Function parameter or struct member 'region' not described in 'dmem_cgroup_try_charge'
>> kernel/cgroup/dmem.c:635: warning: Excess function parameter 'dev' description in 'dmem_cgroup_try_charge'

vim +/climit +302 kernel/cgroup/dmem.c

280
281 /**
282 * dmem_cgroup_state_evict_valuable() - Check if we should evict from test_pool
283 * @dev: &dmem_cgroup_region
284 * @index: The index number of the region being tested.
285 * @limit_pool: The pool for which we hit limits
286 * @test_pool: The pool for which to test
287 * @ignore_low: Whether we have to respect low watermarks.
288 * @ret_hit_low: Pointer to whether it makes sense to consider low watermark.
289 *
290 * This function returns true if we can evict from @test_pool, false if not.
291 * When returning false and @ignore_low is false, @ret_hit_low may
292 * be set to true to indicate this function can be retried with @ignore_low
293 * set to true.
294 *
295 * Return: bool
296 */
297 bool dmem_cgroup_state_evict_valuable(struct dmem_cgroup_pool_state *limit_pool,
298 struct dmem_cgroup_pool_state *test_pool,
299 bool ignore_low, bool *ret_hit_low)

 > 300	{
   301		struct dmem_cgroup_pool_state *pool = test_pool;
 > 302		struct page_counter *climit, *ctest;

303 u64 used, min, low;
304
305 /* Can always evict from current pool, despite limits */
306 if (limit_pool == test_pool)
307 return true;
308
309 if (limit_pool) {
310 if (!parent_dmemcs(limit_pool->cs))
311 return true;
312
313 for (pool = test_pool; pool && limit_pool != pool; pool = pool_parent(pool))
314 {}
315
316 if (!pool)
317 return false;
318 } else {
319 /*
320 * If there is no cgroup limiting memory usage, use the root
321 * cgroup instead for limit calculations.
322 */
323 for (limit_pool = test_pool; pool_parent(limit_pool); limit_pool = pool_parent(limit_pool))
324 {}
325 }
326
327 climit = &limit_pool->cnt;
328 ctest = &test_pool->cnt;
329
330 dmem_cgroup_calculate_protection(limit_pool, test_pool);
331
332 used = page_counter_read(ctest);
333 min = READ_ONCE(ctest->emin);
334
335 if (used <= min)
336 return false;
337
338 if (!ignore_low) {
339 low = READ_ONCE(ctest->elow);
340 if (used > low)
341 return true;
342
343 *ret_hit_low = true;
344 return false;
345 }
346 return true;
347 }
348 EXPORT_SYMBOL_GPL(dmem_cgroup_state_evict_valuable);
349

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
#4 lore raw

Re: [PATCH v2.1 1/1] kernel/cgroup: Add "dmem" memory accounting cgroup

In reply to Maarten Lankhorst
kernel test robot noticed the following build errors:

Hi Maarten,

kernel test robot noticed the following build errors:

[auto build test ERROR on tj-cgroup/for-next]
[also build test ERROR on akpm-mm/mm-everything linus/master v6.13-rc1 next-20241204] [cannot apply to drm-misc/drm-misc-next drm-tip/drm-tip]
[If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Maarten-Lankhorst/kernel-cgroup-Add-dmem-memory-accounting-cgroup/20241204-233207
base:   https://git.kernel.org/pub/scm/linux/kernel/git/tj/cgroup.git for-next
patch link:    https://lore.kernel.org/r/20241204143112.1250983-1-dev%40lankhorst.se
patch subject: [PATCH v2.1 1/1] kernel/cgroup: Add "dmem" memory accounting cgroup
config: um-randconfig-r061-20241205 (https://download.01.org/0day-ci/archive/20241205/[email protected]/config)
compiler: gcc-12 (Debian 12.2.0-14) 12.2.0
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20241205/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

/usr/bin/ld: kernel/cgroup/dmem.o: in function `set_resource_min':

>> kernel/cgroup/dmem.c:115: undefined reference to `page_counter_set_min'
   /usr/bin/ld: kernel/cgroup/dmem.o: in function `set_resource_low':
>> kernel/cgroup/dmem.c:121: undefined reference to `page_counter_set_low'
   /usr/bin/ld: kernel/cgroup/dmem.o: in function `set_resource_max':
>> kernel/cgroup/dmem.c:127: undefined reference to `page_counter_set_max'
   /usr/bin/ld: kernel/cgroup/dmem.o: in function `reset_all_resource_limits':
>> kernel/cgroup/dmem.c:115: undefined reference to `page_counter_set_min'
>> /usr/bin/ld: kernel/cgroup/dmem.c:121: undefined reference to `page_counter_set_low'
>> /usr/bin/ld: kernel/cgroup/dmem.c:127: undefined reference to `page_counter_set_max'
   /usr/bin/ld: kernel/cgroup/dmem.o: in function `dmem_cgroup_uncharge':
>> kernel/cgroup/dmem.c:607: undefined reference to `page_counter_uncharge'
   /usr/bin/ld: kernel/cgroup/dmem.o: in function `dmem_cgroup_calculate_protection':
>> kernel/cgroup/dmem.c:275: undefined reference to `page_counter_calculate_protection'
   /usr/bin/ld: kernel/cgroup/dmem.o: in function `dmem_cgroup_try_charge':
>> kernel/cgroup/dmem.c:657: undefined reference to `page_counter_try_charge'

collect2: error: ld returned 1 exit status

Kconfig warnings: (for reference only)
WARNING: unmet direct dependencies detected for GET_FREE_REGION Depends on [n]: SPARSEMEM [=n]
Selected by [y]:
- RESOURCE_KUNIT_TEST [=y] && RUNTIME_TESTING_MENU [=y] && KUNIT [=y]

vim +115 kernel/cgroup/dmem.c

111
112 static void
113 set_resource_min(struct dmem_cgroup_pool_state *pool, u64 val)
114 {

 > 115		page_counter_set_min(&pool->cnt, val);
   116	}
   117	
   118	static void
   119	set_resource_low(struct dmem_cgroup_pool_state *pool, u64 val)
   120	{
 > 121		page_counter_set_low(&pool->cnt, val);
   122	}
   123	
   124	static void
   125	set_resource_max(struct dmem_cgroup_pool_state *pool, u64 val)
   126	{
 > 127		page_counter_set_max(&pool->cnt, val);
   128	}
   129	
   130	static u64 get_resource_low(struct dmem_cgroup_pool_state *pool)
   131	{
   132		return pool ? READ_ONCE(pool->cnt.low) : 0;
   133	}
   134	
   135	static u64 get_resource_min(struct dmem_cgroup_pool_state *pool)
   136	{
   137		return pool ? READ_ONCE(pool->cnt.min) : 0;
   138	}
   139	
   140	static u64 get_resource_max(struct dmem_cgroup_pool_state *pool)
   141	{
   142		return pool ? READ_ONCE(pool->cnt.max) : PAGE_COUNTER_MAX;
   143	}
   144	
   145	static u64 get_resource_current(struct dmem_cgroup_pool_state *pool)
   146	{
   147		return pool ? page_counter_read(&pool->cnt) : 0;
   148	}
   149	
   150	static void reset_all_resource_limits(struct dmem_cgroup_pool_state *rpool)
   151	{
   152		set_resource_min(rpool, 0);
   153		set_resource_low(rpool, 0);
   154		set_resource_max(rpool, PAGE_COUNTER_MAX);
   155	}
   156	
   157	static void dmemcs_offline(struct cgroup_subsys_state *css)
   158	{
   159		struct dmemcg_state *dmemcs = css_to_dmemcs(css);
   160		struct dmem_cgroup_pool_state *pool;
   161	
   162		rcu_read_lock();
   163		list_for_each_entry_rcu(pool, &dmemcs->pools, css_node)
   164			reset_all_resource_limits(pool);
   165		rcu_read_unlock();
   166	}
   167	
   168	static void dmemcs_free(struct cgroup_subsys_state *css)
   169	{
   170		struct dmemcg_state *dmemcs = css_to_dmemcs(css);
   171		struct dmem_cgroup_pool_state *pool, *next;
   172	
   173		spin_lock(&dmemcg_lock);
   174		list_for_each_entry_safe(pool, next, &dmemcs->pools, css_node) {
   175			/*
   176			 *The pool is dead and all references are 0,
   177			 * no need for RCU protection with list_del_rcu or freeing.
   178			 */
   179			list_del(&pool->css_node);
   180			free_cg_pool(pool);
   181		}
   182		spin_unlock(&dmemcg_lock);
   183	
   184		kfree(dmemcs);
   185	}
   186	
   187	static struct cgroup_subsys_state *
   188	dmemcs_alloc(struct cgroup_subsys_state *parent_css)
   189	{
   190		struct dmemcg_state *dmemcs = kzalloc(sizeof(*dmemcs), GFP_KERNEL);
   191		if (!dmemcs)
   192			return ERR_PTR(-ENOMEM);
   193	
   194		INIT_LIST_HEAD(&dmemcs->pools);
   195		return &dmemcs->css;
   196	}
   197	
   198	static struct dmem_cgroup_pool_state *
   199	find_cg_pool_locked(struct dmemcg_state *dmemcs, struct dmem_cgroup_region *region)
   200	{
   201		struct dmem_cgroup_pool_state *pool;
   202	
   203		list_for_each_entry_rcu(pool, &dmemcs->pools, css_node, spin_is_locked(&dmemcg_lock))
   204			if (pool->region == region)
   205				return pool;
   206	
   207		return NULL;
   208	}
   209	
   210	static struct dmem_cgroup_pool_state *pool_parent(struct dmem_cgroup_pool_state *pool)
   211	{
   212		if (!pool->cnt.parent)
   213			return NULL;
   214	
   215		return container_of(pool->cnt.parent, typeof(*pool), cnt);
   216	}
   217	
   218	static void
   219	dmem_cgroup_calculate_protection(struct dmem_cgroup_pool_state *limit_pool,
   220					 struct dmem_cgroup_pool_state *test_pool)
   221	{
   222		struct page_counter *climit;
   223		struct cgroup_subsys_state *css, *next_css;
   224		struct dmemcg_state *dmemcg_iter;
   225		struct dmem_cgroup_pool_state *pool, *parent_pool;
   226		bool found_descendant;
   227	
   228		climit = &limit_pool->cnt;
   229	
   230		rcu_read_lock();
   231		parent_pool = pool = limit_pool;
   232		css = &limit_pool->cs->css;
   233	
   234		/*
   235		 * This logic is roughly equivalent to css_foreach_descendant_pre,
   236		 * except we also track the parent pool to find out which pool we need
   237		 * to calculate protection values for.
   238		 *
   239		 * We can stop the traversal once we find test_pool among the
   240		 * descendants since we don't really care about any others.
   241		 */
   242		while (pool != test_pool) {
   243			next_css = css_next_child(NULL, css);
   244			if (next_css) {
   245				parent_pool = pool;
   246			} else {
   247				while (css != &limit_pool->cs->css) {
   248					next_css = css_next_child(css, css->parent);
   249					if (next_css)
   250						break;
   251					css = css->parent;
   252					parent_pool = pool_parent(parent_pool);
   253				}
   254				/*
   255				 * We can only hit this when test_pool is not a
   256				 * descendant of limit_pool.
   257				 */
   258				if (WARN_ON_ONCE(css == &limit_pool->cs->css))
   259					break;
   260			}
   261			css = next_css;
   262	
   263			found_descendant = false;
   264			dmemcg_iter = container_of(css, struct dmemcg_state, css);
   265	
   266			list_for_each_entry_rcu(pool, &dmemcg_iter->pools, css_node) {
   267				if (pool_parent(pool) == parent_pool) {
   268					found_descendant = true;
   269					break;
   270				}
   271			}
   272			if (!found_descendant)
   273				continue;
   274	
 > 275			page_counter_calculate_protection(

276 climit, &pool->cnt, true);
277 }
278 rcu_read_unlock();
279 }
280

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
author maintainer
#5 lore raw

Re: [PATCH v2.1 1/1] kernel/cgroup: Add "dmem" memory accounting cgroup

Hey,

Missing a select PAGE_COUNTER in init/Kconfig. I thought I had fixed it, but I must have forgotten to commit those changes when developing between 2 machines.

Cheers,
~Maarten

Den 2024-12-05 kl. 03:27, skrev kernel test robot:

Quoted 224 lines

Hi Maarten,

kernel test robot noticed the following build errors:

[auto build test ERROR on tj-cgroup/for-next]
[also build test ERROR on akpm-mm/mm-everything linus/master v6.13-rc1 next-20241204] [cannot apply to drm-misc/drm-misc-next drm-tip/drm-tip]
[If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Maarten-Lankhorst/kernel-cgroup-Add-dmem-memory-accounting-cgroup/20241204-233207
base:   https://git.kernel.org/pub/scm/linux/kernel/git/tj/cgroup.git for-next
patch link:    https://lore.kernel.org/r/20241204143112.1250983-1-dev%40lankhorst.se
patch subject: [PATCH v2.1 1/1] kernel/cgroup: Add "dmem" memory accounting cgroup
config: um-randconfig-r061-20241205 (https://download.01.org/0day-ci/archive/20241205/[email protected]/config)
compiler: gcc-12 (Debian 12.2.0-14) 12.2.0
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20241205/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

/usr/bin/ld: kernel/cgroup/dmem.o: in function `set_resource_min':

Quoted 1 line
Quoted 1 line

kernel/cgroup/dmem.c:115: undefined reference to `page_counter_set_min'

/usr/bin/ld: kernel/cgroup/dmem.o: in function `set_resource_low':

Quoted 1 line
Quoted 1 line

kernel/cgroup/dmem.c:121: undefined reference to `page_counter_set_low'

/usr/bin/ld: kernel/cgroup/dmem.o: in function `set_resource_max':

Quoted 1 line
Quoted 1 line

kernel/cgroup/dmem.c:127: undefined reference to `page_counter_set_max'

/usr/bin/ld: kernel/cgroup/dmem.o: in function `reset_all_resource_limits':

Quoted 3 lines
Quoted 3 lines

kernel/cgroup/dmem.c:115: undefined reference to page_counter_set_min' /usr/bin/ld: kernel/cgroup/dmem.c:121: undefined reference to page_counter_set_low' /usr/bin/ld: kernel/cgroup/dmem.c:127: undefined reference to `page_counter_set_max'

/usr/bin/ld: kernel/cgroup/dmem.o: in function `dmem_cgroup_uncharge':

Quoted 1 line
Quoted 1 line

kernel/cgroup/dmem.c:607: undefined reference to `page_counter_uncharge'

/usr/bin/ld: kernel/cgroup/dmem.o: in function `dmem_cgroup_calculate_protection':

Quoted 1 line
Quoted 1 line

kernel/cgroup/dmem.c:275: undefined reference to `page_counter_calculate_protection'

/usr/bin/ld: kernel/cgroup/dmem.o: in function `dmem_cgroup_try_charge':

Quoted 1 line
Quoted 1 line

kernel/cgroup/dmem.c:657: undefined reference to `page_counter_try_charge'

collect2: error: ld returned 1 exit status

Kconfig warnings: (for reference only)
WARNING: unmet direct dependencies detected for GET_FREE_REGION Depends on [n]: SPARSEMEM [=n]
Selected by [y]:
- RESOURCE_KUNIT_TEST [=y] && RUNTIME_TESTING_MENU [=y] && KUNIT [=y]

vim +115 kernel/cgroup/dmem.c

    111	
    112	static void
    113	set_resource_min(struct dmem_cgroup_pool_state *pool, u64 val)
    114	{
Quoted 1 line

115 page_counter_set_min(&pool->cnt, val);

    116	}
    117	
    118	static void
    119	set_resource_low(struct dmem_cgroup_pool_state *pool, u64 val)
    120	{
Quoted 1 line

121 page_counter_set_low(&pool->cnt, val);

    122	}
    123	
    124	static void
    125	set_resource_max(struct dmem_cgroup_pool_state *pool, u64 val)
    126	{
Quoted 1 line

127 page_counter_set_max(&pool->cnt, val);

    128	}
    129	
    130	static u64 get_resource_low(struct dmem_cgroup_pool_state *pool)
    131	{
    132		return pool ? READ_ONCE(pool->cnt.low) : 0;
    133	}
    134	
    135	static u64 get_resource_min(struct dmem_cgroup_pool_state *pool)
    136	{
    137		return pool ? READ_ONCE(pool->cnt.min) : 0;
    138	}
    139	
    140	static u64 get_resource_max(struct dmem_cgroup_pool_state *pool)
    141	{
    142		return pool ? READ_ONCE(pool->cnt.max) : PAGE_COUNTER_MAX;
    143	}
    144	
    145	static u64 get_resource_current(struct dmem_cgroup_pool_state *pool)
    146	{
    147		return pool ? page_counter_read(&pool->cnt) : 0;
    148	}
    149	
    150	static void reset_all_resource_limits(struct dmem_cgroup_pool_state *rpool)
    151	{
    152		set_resource_min(rpool, 0);
    153		set_resource_low(rpool, 0);
    154		set_resource_max(rpool, PAGE_COUNTER_MAX);
    155	}
    156	
    157	static void dmemcs_offline(struct cgroup_subsys_state *css)
    158	{
    159		struct dmemcg_state *dmemcs = css_to_dmemcs(css);
    160		struct dmem_cgroup_pool_state *pool;
    161	
    162		rcu_read_lock();
    163		list_for_each_entry_rcu(pool, &dmemcs->pools, css_node)
    164			reset_all_resource_limits(pool);
    165		rcu_read_unlock();
    166	}
    167	
    168	static void dmemcs_free(struct cgroup_subsys_state *css)
    169	{
    170		struct dmemcg_state *dmemcs = css_to_dmemcs(css);
    171		struct dmem_cgroup_pool_state *pool, *next;
    172	
    173		spin_lock(&dmemcg_lock);
    174		list_for_each_entry_safe(pool, next, &dmemcs->pools, css_node) {
    175			/*
    176			 *The pool is dead and all references are 0,
    177			 * no need for RCU protection with list_del_rcu or freeing.
    178			 */
    179			list_del(&pool->css_node);
    180			free_cg_pool(pool);
    181		}
    182		spin_unlock(&dmemcg_lock);
    183	
    184		kfree(dmemcs);
    185	}
    186	
    187	static struct cgroup_subsys_state *
    188	dmemcs_alloc(struct cgroup_subsys_state *parent_css)
    189	{
    190		struct dmemcg_state *dmemcs = kzalloc(sizeof(*dmemcs), GFP_KERNEL);
    191		if (!dmemcs)
    192			return ERR_PTR(-ENOMEM);
    193	
    194		INIT_LIST_HEAD(&dmemcs->pools);
    195		return &dmemcs->css;
    196	}
    197	
    198	static struct dmem_cgroup_pool_state *
    199	find_cg_pool_locked(struct dmemcg_state *dmemcs, struct dmem_cgroup_region *region)
    200	{
    201		struct dmem_cgroup_pool_state *pool;
    202	
    203		list_for_each_entry_rcu(pool, &dmemcs->pools, css_node, spin_is_locked(&dmemcg_lock))
    204			if (pool->region == region)
    205				return pool;
    206	
    207		return NULL;
    208	}
    209	
    210	static struct dmem_cgroup_pool_state *pool_parent(struct dmem_cgroup_pool_state *pool)
    211	{
    212		if (!pool->cnt.parent)
    213			return NULL;
    214	
    215		return container_of(pool->cnt.parent, typeof(*pool), cnt);
    216	}
    217	
    218	static void
    219	dmem_cgroup_calculate_protection(struct dmem_cgroup_pool_state *limit_pool,
    220					 struct dmem_cgroup_pool_state *test_pool)
    221	{
    222		struct page_counter *climit;
    223		struct cgroup_subsys_state *css, *next_css;
    224		struct dmemcg_state *dmemcg_iter;
    225		struct dmem_cgroup_pool_state *pool, *parent_pool;
    226		bool found_descendant;
    227	
    228		climit = &limit_pool->cnt;
    229	
    230		rcu_read_lock();
    231		parent_pool = pool = limit_pool;
    232		css = &limit_pool->cs->css;
    233	
    234		/*
    235		 * This logic is roughly equivalent to css_foreach_descendant_pre,
    236		 * except we also track the parent pool to find out which pool we need
    237		 * to calculate protection values for.
    238		 *
    239		 * We can stop the traversal once we find test_pool among the
    240		 * descendants since we don't really care about any others.
    241		 */
    242		while (pool != test_pool) {
    243			next_css = css_next_child(NULL, css);
    244			if (next_css) {
    245				parent_pool = pool;
    246			} else {
    247				while (css != &limit_pool->cs->css) {
    248					next_css = css_next_child(css, css->parent);
    249					if (next_css)
    250						break;
    251					css = css->parent;
    252					parent_pool = pool_parent(parent_pool);
    253				}
    254				/*
    255				 * We can only hit this when test_pool is not a
    256				 * descendant of limit_pool.
    257				 */
    258				if (WARN_ON_ONCE(css == &limit_pool->cs->css))
    259					break;
    260			}
    261			css = next_css;
    262	
    263			found_descendant = false;
    264			dmemcg_iter = container_of(css, struct dmemcg_state, css);
    265	
    266			list_for_each_entry_rcu(pool, &dmemcg_iter->pools, css_node) {
    267				if (pool_parent(pool) == parent_pool) {
    268					found_descendant = true;
    269					break;
    270				}
    271			}
    272			if (!found_descendant)
    273				continue;
    274	
Quoted 1 line

275 page_counter_calculate_protection(

    276				climit, &pool->cnt, true);
    277		}
    278		rcu_read_unlock();
    279	}
    280	
#6 lore raw

Re: [PATCH v2.1 1/1] kernel/cgroup: Add "dmem" memory accounting cgroup

In reply to Maarten Lankhorst

Hi Maarten,

Quoted 27 lines · Maarten Lankhorst

This code is based on the RDMA and misc cgroup initially, but now uses page_counter. It uses the same min/low/max semantics as the memory cgroup as a result.

There's a small mismatch as TTM uses u64, and page_counter long pages. In practice it's not a problem. 32-bits systems don't really come with

Quoted 1 line

=4GB cards and as long as we're consistently wrong with units, it's

fine. The device page size may not be in the same units as kernel page size, and each region might also have a different page size (VRAM vs GART for example).

The interface is simple:
- Call dmem_cgroup_register_region()
- Use dmem_cgroup_try_charge to check if you can allocate a chunk of memory, use dmem_cgroup__uncharge when freeing it. This may return an error code, or -EAGAIN when the cgroup limit is reached. In that case a reference to the limiting pool is returned.
- The limiting cs can be used as compare function for dmem_cgroup_state_evict_valuable.
- After having evicted enough, drop reference to limiting cs with dmem_cgroup_pool_state_put.

This API allows you to limit device resources with cgroups. You can see the supported cards in /sys/fs/cgroup/dmem.capacity You need to echo +dmem to cgroup.subtree_control, and then you can partition device memory.

Quoted 5 lines

Thanks for your patch, which is now commit b168ed458ddecc17 ("kernel/cgroup: Add "dmem" memory accounting cgroup") in drm/drm-next.

init/Kconfig config CGROUP_PIDS · line 1131

Quoted 7 lines
init/Kconfig +1 -0
@@ -1128,6 +1128,7 @@ config CGROUP_PIDS
 
 config CGROUP_RDMA
        bool "RDMA controller"
+       select PAGE_COUNTER

This change looks unrelated?

Oh, reading your response to the build error, this should have been below?

Quoted 6 lines
init/Kconfig +0 -0
        help
          Provides enforcement of RDMA resources defined by IB stack.
          It is fairly easy for consumers to exhaust RDMA resources, which
@@ -1136,6 +1137,15 @@ config CGROUP_RDMA
          Attaching processes with active RDMA resources to the cgroup
          hierarchy is allowed even if can cross the hierarchy's limit.

init/Kconfig config CGROUP_RDMA · line 1148

Quoted 10 lines
init/Kconfig +9 -0
 
+config CGROUP_DMEM
+       bool "Device memory controller (DMEM)"
+       help
+         The DMEM controller allows compatible devices to restrict device
+         memory usage based on the cgroup hierarchy.
+
+         As an example, it allows you to restrict VRAM usage for applications
+         in the DRM subsystem.
+

Do you envision other users than DRM?
Perhaps this should depend on DRM for now?

Gr{oetje,eeting}s,

Geert

--
Geert Uytterhoeven -- There's lots of Linux beyond ia32 -- [email protected]

In personal conversations with technical people, I call myself a hacker. But when I'm talking to journalists I just say "programmer" or something like that.
-- Linus Torvalds

maintainer
#7 lore raw

Re: [PATCH v2.1 1/1] kernel/cgroup: Add "dmem" memory accounting cgroup

Hi Geert,

Quoted 43 lines · Geert Uytterhoeven

Hi Maarten,

Quoted 27 lines · Maarten Lankhorst

This code is based on the RDMA and misc cgroup initially, but now uses page_counter. It uses the same min/low/max semantics as the memory cgroup as a result.

There's a small mismatch as TTM uses u64, and page_counter long pages. In practice it's not a problem. 32-bits systems don't really come with

Quoted 1 line

=4GB cards and as long as we're consistently wrong with units, it's

fine. The device page size may not be in the same units as kernel page size, and each region might also have a different page size (VRAM vs GART for example).

The interface is simple:
- Call dmem_cgroup_register_region()
- Use dmem_cgroup_try_charge to check if you can allocate a chunk of memory, use dmem_cgroup__uncharge when freeing it. This may return an error code, or -EAGAIN when the cgroup limit is reached. In that case a reference to the limiting pool is returned.
- The limiting cs can be used as compare function for dmem_cgroup_state_evict_valuable.
- After having evicted enough, drop reference to limiting cs with dmem_cgroup_pool_state_put.

This API allows you to limit device resources with cgroups. You can see the supported cards in /sys/fs/cgroup/dmem.capacity You need to echo +dmem to cgroup.subtree_control, and then you can partition device memory.

Quoted 5 lines

Thanks for your patch, which is now commit b168ed458ddecc17 ("kernel/cgroup: Add "dmem" memory accounting cgroup") in drm/drm-next.

Quoted 4 lines
init/Kconfig +0 -0
@@ -1128,6 +1128,7 @@ config CGROUP_PIDS
 
Quoted 7 lines

init/Kconfig config CGROUP_PIDS · line 1131

Quoted 3 lines
init/Kconfig +1 -0
 config CGROUP_RDMA
        bool "RDMA controller"
+       select PAGE_COUNTER

This change looks unrelated?

Oh, reading your response to the build error, this should have been below?

Indeed, good catch.

Quoted 7 lines
Quoted 7 lines
init/Kconfig +0 -0
        help
          Provides enforcement of RDMA resources defined by IB stack.
          It is fairly easy for consumers to exhaust RDMA resources, which
@@ -1136,6 +1137,15 @@ config CGROUP_RDMA
          Attaching processes with active RDMA resources to the cgroup
          hierarchy is allowed even if can cross the hierarchy's limit.
 
Quoted 12 lines

init/Kconfig config CGROUP_RDMA · line 1148

Quoted 9 lines
init/Kconfig +9 -0
+config CGROUP_DMEM
+       bool "Device memory controller (DMEM)"
+       help
+         The DMEM controller allows compatible devices to restrict device
+         memory usage based on the cgroup hierarchy.
+
+         As an example, it allows you to restrict VRAM usage for applications
+         in the DRM subsystem.
+

Do you envision other users than DRM?
Perhaps this should depend on DRM for now?

dma-buf heaps and v4l2 support are in progress right now.

Maxime

maintainer
#8 lore raw

Re: [PATCH v2 1/7] kernel/cgroup: Add "dmem" memory accounting cgroup

In reply to Maarten Lankhorst

Hello.

Quoted 20 lines · Maarten Lankhorst
kernel/cgroup/dmem.c new file +19 -0
+bool dmem_cgroup_state_evict_valuable(struct dmem_cgroup_pool_state *limit_pool,
+				      struct dmem_cgroup_pool_state *test_pool,
+				      bool ignore_low, bool *ret_hit_low)
+{
+	struct dmem_cgroup_pool_state *pool = test_pool;
+	struct page_counter *climit, *ctest;
+	u64 used, min, low;
+
+	/* Can always evict from current pool, despite limits */
+	if (limit_pool == test_pool)
+		return true;
+
 
+	if (limit_pool) {
+		if (!parent_dmemcs(limit_pool->cs))
+			return true;
+
+		for (pool = test_pool; pool && limit_pool != pool; pool = pool_parent(pool))
+			{}
+

kernel/cgroup/dmem.c line 325

Quoted 10 lines
kernel/cgroup/dmem.c new file +10 -0
+		if (!pool)
+			return false;
+	} else {
+		/*
+		 * If there is no cgroup limiting memory usage, use the root
+		 * cgroup instead for limit calculations.
+		 */
+		for (limit_pool = test_pool; pool_parent(limit_pool); limit_pool = pool_parent(limit_pool))
+			{}
+	}

I'm trying to understand the two branches above. If limit_pool is a root one, eviction is granted and no protection is evaluated.

Then it checks that test_pool is below limit_pool (can this ever fail, given the limit_pool must have been above when charging in test_pool?). (OK, this may be called arbitrarily by modules.)

I think it could be simplified and corrected like this:

	/* Resolve NULL limit_pool */
	if (!limit_pool)
		for (limit_pool = test_pool; pool_parent(limit_pool); limit_pool = pool_parent(limit_pool));
	
	/* Check ancestry */
	if (!cgroup_is_descendant(test_pool->cs->css.cgroup, limit_pool->cs->css.cgroup))
		return false;

HTH,
Michal

author maintainer
#9 lore raw

PATCH v2 2/7 drm/drv: Add drmm managed registration helper for dmem cgroups.

In reply to Maarten Lankhorst

From: Maxime Ripard <[email protected]>

Drivers will need to register dmem regions at probe time, so let's give them a drm-managed helper.

---
 drivers/gpu/drm/drm_drv.c | 32 ++++++++++++++++++++++++++++++++
 include/drm/drm_drv.h     |  5 +++++
 2 files changed, 37 insertions(+)
drivers/gpu/drm/drm_drv.c +32 -0
index c2c172eb25df7..3cf440eee8a2a 100644
@@ -26,6 +26,7 @@
  * DEALINGS IN THE SOFTWARE.
  */
 
+#include <linux/cgroup_dmem.h>
 #include <linux/debugfs.h>
 #include <linux/fs.h>
 #include <linux/module.h>
@@ -820,6 +821,37 @@ void drm_dev_put(struct drm_device *dev)
 }
 EXPORT_SYMBOL(drm_dev_put);
 
+static void drmm_cg_unregister_region(struct drm_device *dev, void *arg)
+{
+	dmem_cgroup_unregister_region(arg);
+}
+
+/**
+ * drmm_cgroup_register_region - Register a region of a DRM device to cgroups
+ * @dev: device for region
+ * @region_name: Region name for registering
+ * @size: Size of region in bytes
+ *
+ * This decreases the ref-count of @dev by one. The device is destroyed if the
+ * ref-count drops to zero.
+ */
+struct dmem_cgroup_region *drmm_cgroup_register_region(struct drm_device *dev, const char *region_name, u64 size)
+{
+	struct dmem_cgroup_region *region;
+	int ret;
+
+	region = dmem_cgroup_register_region(size, "drm/%s/%s", dev->unique, region_name);
+	if (IS_ERR_OR_NULL(region))
+		return region;
+
+	ret = drmm_add_action_or_reset(dev, drmm_cg_unregister_region, region);
+	if (ret)
+		return ERR_PTR(ret);
+
+	return region;
+}
+EXPORT_SYMBOL_GPL(drmm_cgroup_register_region);
+
 static int create_compat_control_link(struct drm_device *dev)
 {
 	struct drm_minor *minor;
include/drm/drm_drv.h +5 -0
index 1bbbcb8e2d231..7dd49d9ab5058 100644
@@ -34,6 +34,7 @@
 
 #include <drm/drm_device.h>
 
+struct dmem_cgroup_region;
 struct drm_fb_helper;
 struct drm_fb_helper_surface_size;
 struct drm_file;
@@ -438,6 +439,10 @@ void *__devm_drm_dev_alloc(struct device *parent,
 			   const struct drm_driver *driver,
 			   size_t size, size_t offset);
 
+struct dmem_cgroup_region *
+drmm_cgroup_register_region(struct drm_device *dev,
+			    const char *region_name, u64 size);
+
 /**
  * devm_drm_dev_alloc - Resource managed allocation of a &drm_device instance
  * @parent: Parent device object
Signature · 1 line
2.43.0
author maintainer
#10 lore raw

PATCH v2 3/7 drm/ttm: Handle cgroup based eviction in TTM

In reply to Maarten Lankhorst

cgroup resource allocation has to be handled in TTM, so -EAGAIN from cgroups can be converted into -ENOSPC, and the limitcg can be properly evicted in ttm code.

When hitting a resource limit through -EAGAIN, the cgroup for which the limit is hit is also returned. This allows eviction to delete only from cgroups which are a subgroup of the current cgroup.

The returned CSS is used to determine if eviction is valuable for a given resource, and allows TTM to only target specific resources to lower memory usage.

---
 drivers/gpu/drm/ttm/tests/ttm_bo_test.c       | 18 +++----
 .../gpu/drm/ttm/tests/ttm_bo_validate_test.c  |  4 +-
 drivers/gpu/drm/ttm/tests/ttm_resource_test.c |  2 +-
 drivers/gpu/drm/ttm/ttm_bo.c                  | 54 ++++++++++++++++---
 drivers/gpu/drm/ttm/ttm_resource.c            | 23 +++++++-
 include/drm/ttm/ttm_resource.h                | 12 ++++-
 6 files changed, 90 insertions(+), 23 deletions(-)
drivers/gpu/drm/ttm/tests/ttm_bo_test.c +9 -9
index 3139fd9128d84..f8f20d2f61740 100644
@@ -258,13 +258,13 @@ static void ttm_bo_unreserve_basic(struct kunit *test)
 	bo = ttm_bo_kunit_init(test, test->priv, BO_SIZE, NULL);
 	bo->priority = bo_prio;
 
-	err = ttm_resource_alloc(bo, place, &res1);
+	err = ttm_resource_alloc(bo, place, &res1, NULL);
 	KUNIT_ASSERT_EQ(test, err, 0);
 
 	bo->resource = res1;
 
 	/* Add a dummy resource to populate LRU */
-	ttm_resource_alloc(bo, place, &res2);
+	ttm_resource_alloc(bo, place, &res2, NULL);
 
 	dma_resv_lock(bo->base.resv, NULL);
 	ttm_bo_unreserve(bo);
@@ -300,12 +300,12 @@ static void ttm_bo_unreserve_pinned(struct kunit *test)
 	dma_resv_lock(bo->base.resv, NULL);
 	ttm_bo_pin(bo);
 
-	err = ttm_resource_alloc(bo, place, &res1);
+	err = ttm_resource_alloc(bo, place, &res1, NULL);
 	KUNIT_ASSERT_EQ(test, err, 0);
 	bo->resource = res1;
 
 	/* Add a dummy resource to the pinned list */
-	err = ttm_resource_alloc(bo, place, &res2);
+	err = ttm_resource_alloc(bo, place, &res2, NULL);
 	KUNIT_ASSERT_EQ(test, err, 0);
 	KUNIT_ASSERT_EQ(test,
 			list_is_last(&res2->lru.link, &priv->ttm_dev->unevictable), 1);
@@ -355,7 +355,7 @@ static void ttm_bo_unreserve_bulk(struct kunit *test)
 	ttm_bo_set_bulk_move(bo1, &lru_bulk_move);
 	dma_resv_unlock(bo1->base.resv);
 
-	err = ttm_resource_alloc(bo1, place, &res1);
+	err = ttm_resource_alloc(bo1, place, &res1, NULL);
 	KUNIT_ASSERT_EQ(test, err, 0);
 	bo1->resource = res1;
 
@@ -363,7 +363,7 @@ static void ttm_bo_unreserve_bulk(struct kunit *test)
 	ttm_bo_set_bulk_move(bo2, &lru_bulk_move);
 	dma_resv_unlock(bo2->base.resv);
 
-	err = ttm_resource_alloc(bo2, place, &res2);
+	err = ttm_resource_alloc(bo2, place, &res2, NULL);
 	KUNIT_ASSERT_EQ(test, err, 0);
 	bo2->resource = res2;
 
@@ -401,7 +401,7 @@ static void ttm_bo_put_basic(struct kunit *test)
 	bo = ttm_bo_kunit_init(test, test->priv, BO_SIZE, NULL);
 	bo->type = ttm_bo_type_device;
 
-	err = ttm_resource_alloc(bo, place, &res);
+	err = ttm_resource_alloc(bo, place, &res, NULL);
 	KUNIT_ASSERT_EQ(test, err, 0);
 	bo->resource = res;
 
@@ -518,7 +518,7 @@ static void ttm_bo_pin_unpin_resource(struct kunit *test)
 
 	bo = ttm_bo_kunit_init(test, test->priv, BO_SIZE, NULL);
 
-	err = ttm_resource_alloc(bo, place, &res);
+	err = ttm_resource_alloc(bo, place, &res, NULL);
 	KUNIT_ASSERT_EQ(test, err, 0);
 	bo->resource = res;
 
@@ -569,7 +569,7 @@ static void ttm_bo_multiple_pin_one_unpin(struct kunit *test)
 
 	bo = ttm_bo_kunit_init(test, test->priv, BO_SIZE, NULL);
 
-	err = ttm_resource_alloc(bo, place, &res);
+	err = ttm_resource_alloc(bo, place, &res, NULL);
 	KUNIT_ASSERT_EQ(test, err, 0);
 	bo->resource = res;
 
drivers/gpu/drm/ttm/tests/ttm_bo_validate_test.c +2 -2
index 1adf18481ea05..3148f5d3dbd66 100644
@@ -542,7 +542,7 @@ static void ttm_bo_validate_no_placement_signaled(struct kunit *test)
 		bo->ttm = old_tt;
 	}
 
-	err = ttm_resource_alloc(bo, place, &bo->resource);
+	err = ttm_resource_alloc(bo, place, &bo->resource, NULL);
 	KUNIT_EXPECT_EQ(test, err, 0);
 	KUNIT_ASSERT_EQ(test, man->usage, size);
 
@@ -603,7 +603,7 @@ static void ttm_bo_validate_no_placement_not_signaled(struct kunit *test)
 	bo = ttm_bo_kunit_init(test, test->priv, size, NULL);
 	bo->type = params->bo_type;
 
-	err = ttm_resource_alloc(bo, place, &bo->resource);
+	err = ttm_resource_alloc(bo, place, &bo->resource, NULL);
 	KUNIT_EXPECT_EQ(test, err, 0);
 
 	placement = kunit_kzalloc(test, sizeof(*placement), GFP_KERNEL);
drivers/gpu/drm/ttm/tests/ttm_resource_test.c +1 -1
index a9f4b81921c3c..e6ea2bd01f07a 100644
@@ -302,7 +302,7 @@ static void ttm_sys_man_free_basic(struct kunit *test)
 	res = kunit_kzalloc(test, sizeof(*res), GFP_KERNEL);
 	KUNIT_ASSERT_NOT_NULL(test, res);
 
-	ttm_resource_alloc(bo, place, &res);
+	ttm_resource_alloc(bo, place, &res, NULL);
 
 	man = ttm_manager_type(priv->devs->ttm_dev, mem_type);
 	man->func->free(man, res);
drivers/gpu/drm/ttm/ttm_bo.c +46 -8

141 lines not on this page · raw message

drivers/gpu/drm/ttm/ttm_resource.c +21 -2
index a87665eb28a62..cc29bbf3eabb1 100644
@@ -26,6 +26,7 @@
 #include <linux/io-mapping.h>
 #include <linux/iosys-map.h>
 #include <linux/scatterlist.h>
+#include <linux/cgroup_dmem.h>
 
 #include <drm/ttm/ttm_bo.h>
 #include <drm/ttm/ttm_placement.h>
@@ -350,15 +351,28 @@ EXPORT_SYMBOL(ttm_resource_fini);
 
 int ttm_resource_alloc(struct ttm_buffer_object *bo,
 		       const struct ttm_place *place,
-		       struct ttm_resource **res_ptr)
+		       struct ttm_resource **res_ptr,
+		       struct dmem_cgroup_pool_state **ret_limit_pool)
 {
 	struct ttm_resource_manager *man =
 		ttm_manager_type(bo->bdev, place->mem_type);
+	struct dmem_cgroup_pool_state *pool = NULL;
 	int ret;
 
+	if (man->cg) {
+		ret = dmem_cgroup_try_charge(man->cg, bo->base.size, &pool, ret_limit_pool);
+		if (ret)
+			return ret;
+	}
+
 	ret = man->func->alloc(man, bo, place, res_ptr);
-	if (ret)
+	if (ret) {
+		if (pool)
+			dmem_cgroup_uncharge(pool, bo->base.size);
 		return ret;
+	}
+
+	(*res_ptr)->css = pool;
 
 	spin_lock(&bo->bdev->lru_lock);
 	ttm_resource_add_bulk_move(*res_ptr, bo);
@@ -370,6 +384,7 @@ EXPORT_SYMBOL_FOR_TESTS_ONLY(ttm_resource_alloc);
 void ttm_resource_free(struct ttm_buffer_object *bo, struct ttm_resource **res)
 {
 	struct ttm_resource_manager *man;
+	struct dmem_cgroup_pool_state *pool;
 
 	if (!*res)
 		return;
@@ -377,9 +392,13 @@ void ttm_resource_free(struct ttm_buffer_object *bo, struct ttm_resource **res)
 	spin_lock(&bo->bdev->lru_lock);
 	ttm_resource_del_bulk_move(*res, bo);
 	spin_unlock(&bo->bdev->lru_lock);
+
+	pool = (*res)->css;
 	man = ttm_manager_type(bo->bdev, (*res)->mem_type);
 	man->func->free(man, *res);
 	*res = NULL;
+	if (man->cg)
+		dmem_cgroup_uncharge(pool, bo->base.size);
 }
 EXPORT_SYMBOL(ttm_resource_free);
 
include/drm/ttm/ttm_resource.h +11 -1
index be034be56ba1b..ee688d0c029b3 100644
@@ -38,6 +38,7 @@
 #define TTM_MAX_BO_PRIORITY	4U
 #define TTM_NUM_MEM_TYPES 8
 
+struct dmem_cgroup_device;
 struct ttm_device;
 struct ttm_resource_manager;
 struct ttm_resource;
@@ -211,6 +212,11 @@ struct ttm_resource_manager {
 	 * bdev->lru_lock.
 	 */
 	uint64_t usage;
+
+	/**
+	 * @cg: &dmem_cgroup_region used for memory accounting, if not NULL.
+	 */
+	struct dmem_cgroup_region *cg;
 };
 
 /**
@@ -239,6 +245,7 @@ struct ttm_bus_placement {
  * @placement: Placement flags.
  * @bus: Placement on io bus accessible to the CPU
  * @bo: weak reference to the BO, protected by ttm_device::lru_lock
+ * @css: cgroup state this resource is charged to
  *
  * Structure indicating the placement and space resources used by a
  * buffer object.
@@ -251,6 +258,8 @@ struct ttm_resource {
 	struct ttm_bus_placement bus;
 	struct ttm_buffer_object *bo;
 
+	struct dmem_cgroup_pool_state *css;
+
 	/**
 	 * @lru: Least recently used list, see &ttm_resource_manager.lru
 	 */
@@ -432,7 +441,8 @@ void ttm_resource_fini(struct ttm_resource_manager *man,
 
 int ttm_resource_alloc(struct ttm_buffer_object *bo,
 		       const struct ttm_place *place,
-		       struct ttm_resource **res);
+		       struct ttm_resource **res,
+		       struct dmem_cgroup_pool_state **ret_limit_pool);
 void ttm_resource_free(struct ttm_buffer_object *bo, struct ttm_resource **res);
 bool ttm_resource_intersects(struct ttm_device *bdev,
 			     struct ttm_resource *res,
Signature · 1 line
2.43.0
author maintainer
#11 lore raw

PATCH v2 4/7 drm/xe: Implement cgroup for vram

In reply to Maarten Lankhorst

Add vram based cgroup eviction to Xe.
Most hardware with VRAM uses TTM for its management, and can be similarly trivially enabled.

---
 drivers/gpu/drm/xe/xe_ttm_vram_mgr.c | 8 ++++++++
 1 file changed, 8 insertions(+)
drivers/gpu/drm/xe/xe_ttm_vram_mgr.c +8 -0
index c95728c45ea48..f4a16e5fa7700 100644
@@ -5,6 +5,7 @@
  */
 
 #include <drm/drm_managed.h>
+#include <drm/drm_drv.h>
 
 #include <drm/ttm/ttm_placement.h>
 #include <drm/ttm/ttm_range_manager.h>
@@ -311,6 +312,13 @@ int __xe_ttm_vram_mgr_init(struct xe_device *xe, struct xe_ttm_vram_mgr *mgr,
 	struct ttm_resource_manager *man = &mgr->manager;
 	int err;
 
+	if (mem_type != XE_PL_STOLEN) {
+		const char *name = mem_type == XE_PL_VRAM0 ? "vram0" : "vram1";
+		man->cg = drmm_cgroup_register_region(&xe->drm, name, size);
+		if (IS_ERR(man->cg))
+			return PTR_ERR(man->cg);
+	}
+
 	man->func = &xe_ttm_vram_mgr_func;
 	mgr->mem_type = mem_type;
 	mutex_init(&mgr->lock);
Signature · 1 line
2.43.0
maintainer
#12 lore raw

Re: [PATCH v2 4/7] drm/xe: Implement cgroup for vram

Hi Lucas, Thomas, Rodrigo,

We forgot to Cc you on this series, sorry. Could you have a look at it, and especially the following patch?

Quoted 40 lines · Maarten Lankhorst

Add vram based cgroup eviction to Xe.
Most hardware with VRAM uses TTM for its management, and can be similarly trivially enabled.

---
 drivers/gpu/drm/xe/xe_ttm_vram_mgr.c | 8 ++++++++
 1 file changed, 8 insertions(+)
drivers/gpu/drm/xe/xe_ttm_vram_mgr.c +8 -0
index c95728c45ea48..f4a16e5fa7700 100644
@@ -5,6 +5,7 @@
  */
 
 #include <drm/drm_managed.h>
+#include <drm/drm_drv.h>
 
 #include <drm/ttm/ttm_placement.h>
 #include <drm/ttm/ttm_range_manager.h>
@@ -311,6 +312,13 @@ int __xe_ttm_vram_mgr_init(struct xe_device *xe, struct xe_ttm_vram_mgr *mgr,
 	struct ttm_resource_manager *man = &mgr->manager;
 	int err;
 
+	if (mem_type != XE_PL_STOLEN) {
+		const char *name = mem_type == XE_PL_VRAM0 ? "vram0" : "vram1";
+		man->cg = drmm_cgroup_register_region(&xe->drm, name, size);
+		if (IS_ERR(man->cg))
+			return PTR_ERR(man->cg);
+	}
+
 	man->func = &xe_ttm_vram_mgr_func;
 	mgr->mem_type = mem_type;
 	mutex_init(&mgr->lock);
Signature · 1 line
2.43.0
maintainer Acked-by
#13 lore raw

Re: [PATCH v2 4/7] drm/xe: Implement cgroup for vram

Quoted 4 lines · Maxime Ripard

Hi Lucas, Thomas, Rodrigo,

We forgot to Cc you on this series, sorry. Could you have a look at it, and especially the following patch?

I'm sorry for the delay here.
I was following the thread on the side.
I'm glad to see that we are finally going to get some cgroups support!

Fell free to push this through any tree...

Quoted 44 lines · Maarten Lankhorst
Quoted 40 lines

Add vram based cgroup eviction to Xe.
Most hardware with VRAM uses TTM for its management, and can be similarly trivially enabled.

---
 drivers/gpu/drm/xe/xe_ttm_vram_mgr.c | 8 ++++++++
 1 file changed, 8 insertions(+)
drivers/gpu/drm/xe/xe_ttm_vram_mgr.c +8 -0
index c95728c45ea48..f4a16e5fa7700 100644
@@ -5,6 +5,7 @@
  */
 
 #include <drm/drm_managed.h>
+#include <drm/drm_drv.h>
 
 #include <drm/ttm/ttm_placement.h>
 #include <drm/ttm/ttm_range_manager.h>
@@ -311,6 +312,13 @@ int __xe_ttm_vram_mgr_init(struct xe_device *xe, struct xe_ttm_vram_mgr *mgr,
 	struct ttm_resource_manager *man = &mgr->manager;
 	int err;
 
+	if (mem_type != XE_PL_STOLEN) {
+		const char *name = mem_type == XE_PL_VRAM0 ? "vram0" : "vram1";
+		man->cg = drmm_cgroup_register_region(&xe->drm, name, size);
+		if (IS_ERR(man->cg))
+			return PTR_ERR(man->cg);
+	}
+
 	man->func = &xe_ttm_vram_mgr_func;
 	mgr->mem_type = mem_type;
 	mutex_init(&mgr->lock);
Signature · 1 line
2.43.0
author maintainer
#14 lore raw

PATCH v2 5/7 drm/amdgpu: Add cgroups implementation

In reply to Maarten Lankhorst

Similar to xe, enable some simple management of VRAM only.

---
 drivers/gpu/drm/amd/amdgpu/amdgpu_vram_mgr.c | 4 ++++
 1 file changed, 4 insertions(+)
drivers/gpu/drm/amd/amdgpu/amdgpu_vram_mgr.c +4 -0
index 7d26a962f811c..f1703a746cadd 100644
@@ -24,6 +24,7 @@
 
 #include <linux/dma-mapping.h>
 #include <drm/ttm/ttm_range_manager.h>
+#include <drm/drm_drv.h>
 
 #include "amdgpu.h"
 #include "amdgpu_vm.h"
@@ -908,6 +909,9 @@ int amdgpu_vram_mgr_init(struct amdgpu_device *adev)
 	struct ttm_resource_manager *man = &mgr->manager;
 	int err;
 
+	man->cg = drmm_cgroup_register_region(adev_to_drm(adev), "vram", adev->gmc.real_vram_size);
+	if (IS_ERR(man->cg))
+		return PTR_ERR(man->cg);
 	ttm_resource_manager_init(man, &adev->mman.bdev,
 				  adev->gmc.real_vram_size);
 
Signature · 1 line
2.43.0
maintainer
#15 lore raw

Re: [PATCH v2 5/7] drm/amdgpu: Add cgroups implementation

Hi Alex, Christian, Xinhui,

We forgot to Cc you on that series, sorry. Could you have a look at the following patch?

Thanks!
Maxime

Quoted 34 lines · Maarten Lankhorst

Similar to xe, enable some simple management of VRAM only.

---
 drivers/gpu/drm/amd/amdgpu/amdgpu_vram_mgr.c | 4 ++++
 1 file changed, 4 insertions(+)
drivers/gpu/drm/amd/amdgpu/amdgpu_vram_mgr.c +4 -0
index 7d26a962f811c..f1703a746cadd 100644
@@ -24,6 +24,7 @@
 
 #include <linux/dma-mapping.h>
 #include <drm/ttm/ttm_range_manager.h>
+#include <drm/drm_drv.h>
 
 #include "amdgpu.h"
 #include "amdgpu_vm.h"
@@ -908,6 +909,9 @@ int amdgpu_vram_mgr_init(struct amdgpu_device *adev)
 	struct ttm_resource_manager *man = &mgr->manager;
 	int err;
 
+	man->cg = drmm_cgroup_register_region(adev_to_drm(adev), "vram", adev->gmc.real_vram_size);
+	if (IS_ERR(man->cg))
+		return PTR_ERR(man->cg);
 	ttm_resource_manager_init(man, &adev->mman.bdev,
 				  adev->gmc.real_vram_size);
 
Signature · 1 line
2.43.0
author maintainer
#16 lore raw

PATCH v2 6/7 drm/xe: Hack to test with mapped pages instead of vram.

In reply to Maarten Lankhorst

We will probably want to make this a proper region in TTM for everything, so that we can charge VRAM twice, once for mapped in sysmem, once for mapped in vram. That way we don't need to deal with evict failing from lack of available memory in mapped.

---
 drivers/gpu/drm/xe/xe_ttm_sys_mgr.c | 5 +++++
 1 file changed, 5 insertions(+)
drivers/gpu/drm/xe/xe_ttm_sys_mgr.c +5 -0
index 9844a8edbfe19..5450caaef52ad 100644
@@ -11,6 +11,7 @@
 #include <drm/ttm/ttm_placement.h>
 #include <drm/ttm/ttm_range_manager.h>
 #include <drm/ttm/ttm_tt.h>
+#include <drm/drm_drv.h>
 
 #include "xe_bo.h"
 #include "xe_gt.h"
@@ -112,6 +113,10 @@ int xe_ttm_sys_mgr_init(struct xe_device *xe)
 	/* TTM limits allocation of all TTM devices by 50% of system memory */
 	gtt_size /= 2;
 
+	man->cg = drmm_cgroup_register_region(&xe->drm, "mapped", gtt_size);
+	if (IS_ERR(man->cg))
+		return PTR_ERR(man->cg);
+
 	man->use_tt = true;
 	man->func = &xe_ttm_sys_mgr_func;
 	ttm_resource_manager_init(man, &xe->ttm, gtt_size >> PAGE_SHIFT);
Signature · 1 line
2.43.0
author maintainer
#17 lore raw

PATCH v2 7/7 drm/gem: Add cgroup memory accounting for VRAM helper.

In reply to Maarten Lankhorst

From: Maxime Ripard <[email protected]>

This allows any driver using the VRAM helper to set limits on VRAM using cgroup.

---
 drivers/gpu/drm/drm_gem_vram_helper.c | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)
drivers/gpu/drm/drm_gem_vram_helper.c +14 -1
index 22b1fe9c03b81..70979523ee984 100644
@@ -925,6 +925,7 @@ EXPORT_SYMBOL(drm_vram_mm_debugfs_init);
 static int drm_vram_mm_init(struct drm_vram_mm *vmm, struct drm_device *dev,
 			    uint64_t vram_base, size_t vram_size)
 {
+	struct ttm_resource_manager *man;
 	int ret;
 
 	vmm->vram_base = vram_base;
@@ -939,8 +940,20 @@ static int drm_vram_mm_init(struct drm_vram_mm *vmm, struct drm_device *dev,
 
 	ret = ttm_range_man_init(&vmm->bdev, TTM_PL_VRAM,
 				 false, vram_size >> PAGE_SHIFT);
-	if (ret)
+	if (ret) {
+		ttm_device_fini(&vmm->bdev);
 		return ret;
+	}
+
+	man = ttm_manager_type(&vmm->bdev, TTM_PL_VRAM);
+	man->cg = drmm_register_region(dev, "vram", size);
+	if (IS_ERR(man->cg)) {
+		ret = PTR_ERR(man->cg);
+
+		ttm_range_man_fini(&vmm->bdev, TTM_PL_VRAM);
+		ttm_device_fini(&vmm->bdev);
+		return ret;
+	}
 
 	return 0;
 }
Signature · 1 line
2.43.0
#18 lore raw

✓ CI.Patch_applied: success for kernel/cgroups: Add "dmem" memory accounting cgroup.

In reply to Maarten Lankhorst
== Series Details ==

== Series Details ==

Series: kernel/cgroups: Add "dmem" memory accounting cgroup.
URL : https://patchwork.freedesktop.org/series/142111/
State : success

== Summary ==

=== Applying kernel patches on branch 'drm-tip' with base: ===
Base commit: c8df5caf278d drm-tip: 2024y-12m-04d-11h-45m-26s UTC integration manifest === git am output follows ===
.git/rebase-apply/patch:109: new blank line at EOF.
+
warning: 1 line adds whitespace errors.
Applying: kernel/cgroup: Add "dmem" memory accounting cgroup
Applying: drm/drv: Add drmm managed registration helper for dmem cgroups.
Applying: drm/ttm: Handle cgroup based eviction in TTM
Applying: drm/xe: Implement cgroup for vram
Applying: drm/amdgpu: Add cgroups implementation
Applying: drm/xe: Hack to test with mapped pages instead of vram.
Applying: drm/gem: Add cgroup memory accounting for VRAM helper.

#19 lore raw

✗ CI.checkpatch: warning for kernel/cgroups: Add "dmem" memory accounting cgroup.

In reply to Maarten Lankhorst
== Series Details ==

== Series Details ==

Series: kernel/cgroups: Add "dmem" memory accounting cgroup.
URL : https://patchwork.freedesktop.org/series/142111/
State : warning

== Summary ==

+ KERNEL=/kernel
+ git clone https://gitlab.freedesktop.org/drm/maintainer-tools mt Cloning into 'mt'...
warning: redirecting to https://gitlab.freedesktop.org/drm/maintainer-tools.git/
+ git -C mt rev-list -n1 origin/master 30ab6715fc09baee6cc14cb3c89ad8858688d474
+ cd /kernel
+ git config --global --add safe.directory /kernel
+ git log -n1
commit f33553698b4dd8f10b4b0e36a4731bf42e1cd727

Author: Maxime Ripard <[email protected]>
Date:   Wed Dec 4 14:44:07 2024 +0100

drm/gem: Add cgroup memory accounting for VRAM helper.

This allows any driver using the VRAM helper to set limits on VRAM using cgroup.

+ /mt/dim checkpatch c8df5caf278df4f9ca0aba627047c5ee4318fc0d drm-intel
5f0160b3585e kernel/cgroup: Add "dmem" memory accounting cgroup
-:19: WARNING:COMMIT_LOG_LONG_LINE: Prefer a maximum 75 chars per line (possible unwrapped commit description?) #19:
- Use dmem_cgroup_try_charge to check if you can allocate a chunk of memory,

-:116: WARNING:FILE_PATH_CHANGES: added, moved or deleted file(s), does MAINTAINERS need updating? #116:
new file mode 100644

-:121: WARNING:SPDX_LICENSE_TAG: Missing or malformed SPDX-License-Identifier tag in line 1 #121: FILE: Documentation/core-api/cgroup.rst:1:
+==================

-:148: WARNING:SPDX_LICENSE_TAG: Missing or malformed SPDX-License-Identifier tag in line 1 #148: FILE: Documentation/gpu/drm-compute.rst:1:
+==================================

-:225: WARNING:LONG_LINE: line length of 106 exceeds 100 columns
#225: FILE: include/linux/cgroup_dmem.h:18:
+struct dmem_cgroup_region *dmem_cgroup_register_region(u64 size, const char *name_fmt, ...) __printf(2,3);

-:225: ERROR:SPACING: space required after that ',' (ctx:VxV) #225: FILE: include/linux/cgroup_dmem.h:18:

+struct dmem_cgroup_region *dmem_cgroup_register_region(u64 size, const char *name_fmt, ...) __printf(2,3);
                                                                                                       ^

-:238: ERROR:SPACING: space required after that ',' (ctx:VxV) #238: FILE: include/linux/cgroup_dmem.h:31:

+dmem_cgroup_register_region(u64 size, const char *name_fmt, ...) __printf(2,3);
                                                                            ^

-:368: WARNING:TYPO_SPELLING: 'succesful' may be misspelled - perhaps 'successful'? #368: FILE: kernel/cgroup/dmem.c:22:
+ * Keeps the region reference alive after a succesful RCU lookup.
^^^^^^^^^

-:537: WARNING:LINE_SPACING: Missing a blank line after declarations #537: FILE: kernel/cgroup/dmem.c:191:
+ struct dmemcg_state *dmemcs = kzalloc(sizeof(*dmemcs), GFP_KERNEL);
+ if (!dmemcs)

-:549: WARNING:USE_LOCKDEP: Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked #549: FILE: kernel/cgroup/dmem.c:203:
+ list_for_each_entry_rcu(pool, &dmemcs->pools, css_node, spin_is_locked(&dmemcg_lock))

-:577: CHECK:MULTIPLE_ASSIGNMENTS: multiple assignments should be avoided #577: FILE: kernel/cgroup/dmem.c:231:
+ parent_pool = pool = limit_pool;

-:621: CHECK:OPEN_ENDED_LINE: Lines should not end with a '(' #621: FILE: kernel/cgroup/dmem.c:275:
+ page_counter_calculate_protection(

-:659: ERROR:OPEN_BRACE: that open brace { should be on the previous line #659: FILE: kernel/cgroup/dmem.c:313:
+ for (pool = test_pool; pool && limit_pool != pool; pool = pool_parent(pool))
+ {}

-:669: WARNING:LONG_LINE: line length of 107 exceeds 100 columns #669: FILE: kernel/cgroup/dmem.c:323:
+ for (limit_pool = test_pool; pool_parent(limit_pool); limit_pool = pool_parent(limit_pool))

-:669: ERROR:OPEN_BRACE: that open brace { should be on the previous line #669: FILE: kernel/cgroup/dmem.c:323:
+ for (limit_pool = test_pool; pool_parent(limit_pool); limit_pool = pool_parent(limit_pool))
+ {}

-:758: CHECK:MULTIPLE_ASSIGNMENTS: multiple assignments should be avoided #758: FILE: kernel/cgroup/dmem.c:412:
+ retpool = pool = find_cg_pool_locked(dmemcs, region);

-:880: WARNING:LONG_LINE: line length of 104 exceeds 100 columns #880: FILE: kernel/cgroup/dmem.c:534:
+ list_for_each_entry_rcu(region, &dmem_cgroup_regions, region_node, spin_is_locked(&dmemcg_lock))

-:880: WARNING:USE_LOCKDEP: Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked #880: FILE: kernel/cgroup/dmem.c:534:
+ list_for_each_entry_rcu(region, &dmem_cgroup_regions, region_node, spin_is_locked(&dmemcg_lock))

-:979: CHECK:PARENTHESIS_ALIGNMENT: Alignment should match open parenthesis #979: FILE: kernel/cgroup/dmem.c:633:
+int dmem_cgroup_try_charge(struct dmem_cgroup_region *region, u64 size,
+ struct dmem_cgroup_pool_state **ret_pool,

-:1053: CHECK:PARENTHESIS_ALIGNMENT: Alignment should match open parenthesis #1053: FILE: kernel/cgroup/dmem.c:707:
+static ssize_t dmemcg_limit_write(struct kernfs_open_file *of,
+ char *buf, size_t nbytes, loff_t off,

-:1104: CHECK:LINE_SPACING: Please don't use multiple blank lines #1104: FILE: kernel/cgroup/dmem.c:758:
+
+

-:1109: CHECK:PARENTHESIS_ALIGNMENT: Alignment should match open parenthesis #1109: FILE: kernel/cgroup/dmem.c:763:
+static int dmemcg_limit_show(struct seq_file *sf, void *v,
+ u64 (*fn)(struct dmem_cgroup_pool_state *))

-:1143: CHECK:PARENTHESIS_ALIGNMENT: Alignment should match open parenthesis #1143: FILE: kernel/cgroup/dmem.c:797:
+static ssize_t dmem_cgroup_region_min_write(struct kernfs_open_file *of,
+ char *buf, size_t nbytes, loff_t off)

-:1154: CHECK:PARENTHESIS_ALIGNMENT: Alignment should match open parenthesis #1154: FILE: kernel/cgroup/dmem.c:808:
+static ssize_t dmem_cgroup_region_low_write(struct kernfs_open_file *of,
+ char *buf, size_t nbytes, loff_t off)

-:1165: CHECK:PARENTHESIS_ALIGNMENT: Alignment should match open parenthesis #1165: FILE: kernel/cgroup/dmem.c:819:
+static ssize_t dmem_cgroup_region_max_write(struct kernfs_open_file *of,
+ char *buf, size_t nbytes, loff_t off)

total: 4 errors, 11 warnings, 10 checks, 1126 lines checked
493168326e7e drm/drv: Add drmm managed registration helper for dmem cgroups.
-:43: WARNING:LONG_LINE: line length of 113 exceeds 100 columns
#43: FILE: drivers/gpu/drm/drm_drv.c:838:
+struct dmem_cgroup_region *drmm_cgroup_register_region(struct drm_device *dev, const char *region_name, u64 size)

total: 0 errors, 1 warnings, 0 checks, 61 lines checked f9fa211e6a94 drm/ttm: Handle cgroup based eviction in TTM -:224: CHECK:MULTIPLE_ASSIGNMENTS: multiple assignments should be avoided #224: FILE: drivers/gpu/drm/ttm/ttm_bo.c:588:
+ evict_walk.try_low = evict_walk.hit_low = false;

total: 0 errors, 0 warnings, 1 checks, 333 lines checked 5c5a29d9a35b drm/xe: Implement cgroup for vram
-:32: WARNING:LINE_SPACING: Missing a blank line after declarations #32: FILE: drivers/gpu/drm/xe/xe_ttm_vram_mgr.c:317:
+ const char *name = mem_type == XE_PL_VRAM0 ? "vram0" : "vram1";
+ man->cg = drmm_cgroup_register_region(&xe->drm, name, size);

total: 0 errors, 1 warnings, 0 checks, 20 lines checked b8fe12b3fb5b drm/amdgpu: Add cgroups implementation 50ff0bed93f7 drm/xe: Hack to test with mapped pages instead of vram. f33553698b4d drm/gem: Add cgroup memory accounting for VRAM helper.

#20 lore raw

✗ CI.KUnit: failure for kernel/cgroups: Add "dmem" memory accounting cgroup.

In reply to Maarten Lankhorst
== Series Details ==

== Series Details ==

Series: kernel/cgroups: Add "dmem" memory accounting cgroup.
URL : https://patchwork.freedesktop.org/series/142111/
State : failure

== Summary ==

+ trap cleanup EXIT
+ /kernel/tools/testing/kunit/kunit.py run --kunitconfig /kernel/drivers/gpu/drm/xe/.kunitconfig ERROR:root:In file included from ../drivers/gpu/drm/ttm/ttm_bo.c:45:
../include/linux/cgroup_dmem.h:32:1: error: expected identifier or ‘(’ before ‘{’ token

   32 | {
      | ^
../include/linux/cgroup_dmem.h:42:1: error: expected identifier or ‘(’ before ‘{’ token
   42 | {
      | ^
../drivers/gpu/drm/ttm/ttm_bo.c: In function ‘ttm_bo_evict_cb’:
../drivers/gpu/drm/ttm/ttm_bo.c:518:57: error: passing argument 1 of ‘dmem_cgroup_state_evict_valuable’ from incompatible pointer type [-Werror=incompatible-pointer-types]
  518 |         if (!dmem_cgroup_state_evict_valuable(evict_walk->limit_pool, bo->resource->css,
      |                                               ~~~~~~~~~~^~~~~~~~~~~~
      |                                                         |
      |                                                         struct dmem_cgroup_pool_state *
../include/linux/cgroup_dmem.h:55:66: note: expected ‘struct dmem_cgroup_device *’ but argument is of type ‘struct dmem_cgroup_pool_state *’
   55 | bool dmem_cgroup_state_evict_valuable(struct dmem_cgroup_device *region,
      |                                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~
../drivers/gpu/drm/ttm/ttm_bo.c:519:57: error: incompatible type for argument 3 of ‘dmem_cgroup_state_evict_valuable’
  519 |                                               evict_walk->try_low, &evict_walk->hit_low))
      |                                               ~~~~~~~~~~^~~~~~~~~
      |                                                         |
      |                                                         bool {aka _Bool}
../include/linux/cgroup_dmem.h:57:70: note: expected ‘struct dmem_cgroup_pool_state *’ but argument is of type ‘bool’ {aka ‘_Bool’}
   57 |                                       struct dmem_cgroup_pool_state *test_pool,
      |                                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~
../drivers/gpu/drm/ttm/ttm_bo.c:519:47: warning: the comparison will always evaluate as ‘true’ for the address of ‘hit_low’ will never be NULL [-Waddress]
  519 |                                               evict_walk->try_low, &evict_walk->hit_low))
      |                                               ^~~~~~~~~~
../drivers/gpu/drm/ttm/ttm_bo.c:509:14: note: ‘hit_low’ declared here
  509 |         bool hit_low;
      |              ^~~~~~~
../drivers/gpu/drm/ttm/ttm_bo.c:518:14: error: too few arguments to function ‘dmem_cgroup_state_evict_valuable’
  518 |         if (!dmem_cgroup_state_evict_valuable(evict_walk->limit_pool, bo->resource->css,
      |              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../include/linux/cgroup_dmem.h:55:6: note: declared here
   55 | bool dmem_cgroup_state_evict_valuable(struct dmem_cgroup_device *region,
      |      ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../include/linux/cgroup_dmem.h: At top level:
../include/linux/cgroup_dmem.h:31:1: warning: ‘dmem_cgroup_register_region’ declared ‘static’ but never defined [-Wunused-function]
   31 | dmem_cgroup_register_region(u64 size, const char *name_fmt, ...) __printf(2,3);
      | ^~~~~~~~~~~~~~~~~~~~~~~~~~~
../include/linux/cgroup_dmem.h:39:12: warning: ‘dmem_cgroup_try_charge’ declared ‘static’ but never defined [-Wunused-function]
   39 | static int dmem_cgroup_try_charge(struct dmem_cgroup_device *cgdev, u64 size,
      |            ^~~~~~~~~~~~~~~~~~~~~~

cc1: some warnings being treated as errors
make[7]: *** [../scripts/Makefile.build:194: drivers/gpu/drm/ttm/ttm_bo.o] Error 1 make[7]: *** Waiting for unfinished jobs....
make[6]: *** [../scripts/Makefile.build:440: drivers/gpu/drm/ttm] Error 2 make[6]: *** Waiting for unfinished jobs....
../lib/iomap.c:156:5: warning: no previous prototype for ‘ioread64_lo_hi’ [-Wmissing-prototypes]
156 | u64 ioread64_lo_hi(const void __iomem *addr)

      |     ^~~~~~~~~~~~~~
../lib/iomap.c:163:5: warning: no previous prototype for ‘ioread64_hi_lo’ [-Wmissing-prototypes]
  163 | u64 ioread64_hi_lo(const void __iomem *addr)
      |     ^~~~~~~~~~~~~~
../lib/iomap.c:170:5: warning: no previous prototype for ‘ioread64be_lo_hi’ [-Wmissing-prototypes]
  170 | u64 ioread64be_lo_hi(const void __iomem *addr)
      |     ^~~~~~~~~~~~~~~~
../lib/iomap.c:178:5: warning: no previous prototype for ‘ioread64be_hi_lo’ [-Wmissing-prototypes]
  178 | u64 ioread64be_hi_lo(const void __iomem *addr)
      |     ^~~~~~~~~~~~~~~~
../lib/iomap.c:264:6: warning: no previous prototype for ‘iowrite64_lo_hi’ [-Wmissing-prototypes]
  264 | void iowrite64_lo_hi(u64 val, void __iomem *addr)
      |      ^~~~~~~~~~~~~~~
../lib/iomap.c:272:6: warning: no previous prototype for ‘iowrite64_hi_lo’ [-Wmissing-prototypes]
  272 | void iowrite64_hi_lo(u64 val, void __iomem *addr)
      |      ^~~~~~~~~~~~~~~
../lib/iomap.c:280:6: warning: no previous prototype for ‘iowrite64be_lo_hi’ [-Wmissing-prototypes]
  280 | void iowrite64be_lo_hi(u64 val, void __iomem *addr)
      |      ^~~~~~~~~~~~~~~~~
../lib/iomap.c:288:6: warning: no previous prototype for ‘iowrite64be_hi_lo’ [-Wmissing-prototypes]
  288 | void iowrite64be_hi_lo(u64 val, void __iomem *addr)
      |      ^~~~~~~~~~~~~~~~~

make[5]: *** [../scripts/Makefile.build:440: drivers/gpu/drm] Error 2 make[4]: *** [../scripts/Makefile.build:440: drivers/gpu] Error 2 make[3]: *** [../scripts/Makefile.build:440: drivers] Error 2 make[2]: *** [/kernel/Makefile:1989: .] Error 2
make[1]: *** [/kernel/Makefile:251: __sub-make] Error 2
make: *** [Makefile:251: __sub-make] Error 2

[14:06:51] Configuring KUnit Kernel ...
Generating .config ...
Populating config with:

$ make ARCH=um O=.kunit olddefconfig
[14:06:55] Building KUnit Kernel ...
Populating config with:
$ make ARCH=um O=.kunit olddefconfig
Building with:
$ make all compile_commands.json ARCH=um O=.kunit --jobs=48
+ cleanup
++ stat -c %u:%g /kernel
+ chown -R 1003:1003 /kernel
#21 lore raw
In reply to Maarten Lankhorst

Hi,

Quoted 1 line · Maarten Lankhorst

New update. Instead of calling it the 'dev' cgroup, it's now the 'dmem' cgroup.

Thanks! I think this version looks pretty good.

Quoted 7 lines

Because it only deals with memory regions, the UAPI has been updated to use dmem.min/low/max/current, and to make the API cleaner, the names are changed too.

dmem.current could contain a line like:
"drm/0000:03:00.0/vram0 1073741824"

But I think using "drm/card0/vram0" instead of PCIID would perhaps be good too. I'm open to changing it to that based on feedback.

Agree, allowing userspace to reference DRM devices via "cardN" syntax sounds good. What about other subsystems potentially using dmem cgroups? I'm not familiar with the media subsystem, but I imagine we might be dealing with things like USB devices there? Is something like a "deviceN" possible there as well, or would device IDs look completely different?

Regards,
Friedrich

Quoted 45 lines

I've created an IGT test for min and max, and found the changes from Friedrich Vock sent as feedback were needed. I've integrated those into the first patch.

Maarten Lankhorst (5):
kernel/cgroup: Add "dmem" memory accounting cgroup drm/ttm: Handle cgroup based eviction in TTM drm/xe: Implement cgroup for vram
drm/amdgpu: Add cgroups implementation
drm/xe: Hack to test with mapped pages instead of vram.

Maxime Ripard (2):
drm/drv: Add drmm managed registration helper for dmem cgroups. drm/gem: Add cgroup memory accounting for VRAM helper.

  Documentation/admin-guide/cgroup-v2.rst       |  58 +-
  Documentation/core-api/cgroup.rst             |   9 +
  Documentation/core-api/index.rst              |   1 +
  Documentation/gpu/drm-compute.rst             |  54 ++
  drivers/gpu/drm/amd/amdgpu/amdgpu_vram_mgr.c  |   4 +
  drivers/gpu/drm/drm_drv.c                     |  32 +
  drivers/gpu/drm/drm_gem_vram_helper.c         |  15 +-
  drivers/gpu/drm/ttm/tests/ttm_bo_test.c       |  18 +-
  .../gpu/drm/ttm/tests/ttm_bo_validate_test.c  |   4 +-
  drivers/gpu/drm/ttm/tests/ttm_resource_test.c |   2 +-
  drivers/gpu/drm/ttm/ttm_bo.c                  |  54 +-
  drivers/gpu/drm/ttm/ttm_resource.c            |  23 +-
  drivers/gpu/drm/xe/xe_ttm_sys_mgr.c           |   5 +
  drivers/gpu/drm/xe/xe_ttm_vram_mgr.c          |   8 +
  include/drm/drm_drv.h                         |   5 +
  include/drm/ttm/ttm_resource.h                |  12 +-
  include/linux/cgroup_dmem.h                   |  67 ++
  include/linux/cgroup_subsys.h                 |   4 +
  include/linux/page_counter.h                  |   2 +-
  init/Kconfig                                  |  10 +
  kernel/cgroup/Makefile                        |   1 +
  kernel/cgroup/dmem.c                          | 861 ++++++++++++++++++
  mm/page_counter.c                             |   4 +-
  23 files changed, 1219 insertions(+), 34 deletions(-)

create mode 100644 Documentation/core-api/cgroup.rst create mode 100644 Documentation/gpu/drm-compute.rst create mode 100644 include/linux/cgroup_dmem.h create mode 100644 kernel/cgroup/dmem.c

maintainer
#22 lore raw
Quoted 14 lines · Friedrich Vock

Hi,

Quoted 9 lines · Maarten Lankhorst

Because it only deals with memory regions, the UAPI has been updated to use dmem.min/low/max/current, and to make the API cleaner, the names are changed too.

dmem.current could contain a line like:
"drm/0000:03:00.0/vram0 1073741824"

But I think using "drm/card0/vram0" instead of PCIID would perhaps be good too. I'm open to changing it to that based on feedback.

Quoted 8 lines

Agree, allowing userspace to reference DRM devices via "cardN" syntax sounds good.

What about other subsystems potentially using dmem cgroups? I'm not familiar with the media subsystem, but I imagine we might be dealing with things like USB devices there? Is something like a "deviceN" possible there as well, or would device IDs look completely different?

I have some patches to enable the cgroup in GEM-based drivers, media ones and dma-buf heaps. The dma-buf heaps are simple enough since the heaps names are supposed to be stable.

I don't think using card0 vs card1 (or v4l0 vs v4l1 for example) will work because I don't think we have any sort of guarantee that these names will always point to the same devices across reboots or updates.

If the module is loaded later than it used to for example, we could very well end up in a situation where card0 and card1 are swapped, while the constraints apply to the previous situation.

Maxime

author maintainer
#23 lore raw

Hey,

Den 2024-12-13 kl. 14:07, skrev Maxime Ripard:

Quoted 15 lines · Friedrich Vock
Quoted 14 lines

Hi,

Quoted 9 lines · Maarten Lankhorst

Because it only deals with memory regions, the UAPI has been updated to use dmem.min/low/max/current, and to make the API cleaner, the names are changed too.

dmem.current could contain a line like:
"drm/0000:03:00.0/vram0 1073741824"

But I think using "drm/card0/vram0" instead of PCIID would perhaps be good too. I'm open to changing it to that based on feedback.

Quoted 8 lines
Quoted 8 lines

Agree, allowing userspace to reference DRM devices via "cardN" syntax sounds good.

What about other subsystems potentially using dmem cgroups? I'm not familiar with the media subsystem, but I imagine we might be dealing with things like USB devices there? Is something like a "deviceN" possible there as well, or would device IDs look completely different?

I'd just take what makes sense for each driver. dev_name() would be a good approximation.

I agree that cardN is not stable.

Quoted 3 lines
Quoted 1 line

I have some patches to enable the cgroup in GEM-based drivers, media

ones and dma-buf heaps. The dma-buf heaps are simple enough since the heaps names are supposed to be stable.

I've used your patch as a base enable cgroup in drivers that use the VRAM manager. I didn't want to enable it for all of GEM, because it would conflict with drivers using TTM. Some more discussion is needed first.

For DMA-BUF heaps, I think it's fine and there is a lot less need of discussion. I just felt it should be sent separately from the initial enablement.

Quoted 7 lines

I don't think using card0 vs card1 (or v4l0 vs v4l1 for example) will work because I don't think we have any sort of guarantee that these names will always point to the same devices across reboots or updates.

If the module is loaded later than it used to for example, we could very well end up in a situation where card0 and card1 are swapped, while the constraints apply to the previous situation.

I agree, just put it out there for discussion. I don't think the benefits weigh up against the downsides :-)

Cheers,
~Maarten

maintainer
#24 lore raw
Quoted 21 lines · Maarten Lankhorst

Hey,

Den 2024-12-13 kl. 14:07, skrev Maxime Ripard:

Quoted 18 lines · Friedrich Vock
Quoted 17 lines

Hi,

Quoted 9 lines · Maarten Lankhorst

Because it only deals with memory regions, the UAPI has been updated to use dmem.min/low/max/current, and to make the API cleaner, the names are changed too.

dmem.current could contain a line like:
"drm/0000:03:00.0/vram0 1073741824"

But I think using "drm/card0/vram0" instead of PCIID would perhaps be good too. I'm open to changing it to that based on feedback.

Agree, allowing userspace to reference DRM devices via "cardN" syntax sounds good.

Quoted 8 lines
Quoted 5 lines
Quoted 5 lines

What about other subsystems potentially using dmem cgroups? I'm not familiar with the media subsystem, but I imagine we might be dealing with things like USB devices there? Is something like a "deviceN" possible there as well, or would device IDs look completely different?

I'd just take what makes sense for each driver. dev_name() would be a good approximation.

Yeah, dev_name() seems good enough to me too.

Quoted 6 lines

I agree that cardN is not stable.

Quoted 3 lines
Quoted 1 line

I have some patches to enable the cgroup in GEM-based drivers, media

ones and dma-buf heaps. The dma-buf heaps are simple enough since the heaps names are supposed to be stable.

Quoted 7 lines

I've used your patch as a base enable cgroup in drivers that use the VRAM manager. I didn't want to enable it for all of GEM, because it would conflict with drivers using TTM. Some more discussion is needed first.

For DMA-BUF heaps, I think it's fine and there is a lot less need of discussion. I just felt it should be sent separately from the initial enablement.

Definitely.

Quoted 10 lines
Quoted 7 lines

I don't think using card0 vs card1 (or v4l0 vs v4l1 for example) will work because I don't think we have any sort of guarantee that these names will always point to the same devices across reboots or updates.

If the module is loaded later than it used to for example, we could very well end up in a situation where card0 and card1 are swapped, while the constraints apply to the previous situation.

I agree, just put it out there for discussion. I don't think the benefits weigh up against the downsides :-)

Oh absolutely. The way to define a stable name is going to be framework specific anyway. My point was that we wanted to have a stable name.

Maxime

maintainer
#25 lore raw
In reply to Maarten Lankhorst

Hi,

Thanks for the new update!

Quoted 6 lines · Maarten Lankhorst

New update. Instead of calling it the 'dev' cgroup, it's now the 'dmem' cgroup.

Because it only deals with memory regions, the UAPI has been updated to use dmem.min/low/max/current, and to make the API cleaner, the names are changed too.

The API is much nicer, and fits much better into other frameworks too.

Quoted 5 lines

dmem.current could contain a line like:
"drm/0000:03:00.0/vram0 1073741824"

But I think using "drm/card0/vram0" instead of PCIID would perhaps be good too. I'm open to changing it to that based on feedback.

Do we have any sort of guarantee over the name card0 being stable across reboots?

I also wonder if we should have a "total" device that limits the amount of memory we can allocate from any region?

Maxime

author maintainer
#26 lore raw

Den 2024-12-13 kl. 14:03, skrev Maxime Ripard:

Quoted 17 lines

Hi,

Thanks for the new update!

Quoted 6 lines · Maarten Lankhorst

New update. Instead of calling it the 'dev' cgroup, it's now the 'dmem' cgroup.

Because it only deals with memory regions, the UAPI has been updated to use dmem.min/low/max/current, and to make the API cleaner, the names are changed too.

The API is much nicer, and fits much better into other frameworks too.

Quoted 3 lines

dmem.current could contain a line like:
"drm/0000:03:00.0/vram0 1073741824"

Quoted 8 lines
Quoted 2 lines

But I think using "drm/card0/vram0" instead of PCIID would perhaps be good too. I'm open to changing it to that based on feedback.

Do we have any sort of guarantee over the name card0 being stable across reboots?

I also wonder if we should have a "total" device that limits the amount of memory we can allocate from any region?

I don't think it is useful. Say your app can use 1 GB of main memory or 2 GB of VRAM, it wouldn't make sense to limit the total of those. In a lot of cases there is only 1 region, so the total of that would still be the same.

On top, we just separated the management of each region, adding a 'total' would require unseparating it again. :-)

I'm happy with this version I think. I don't think more changes for the base are needed.

Cheers,
~Maarten

maintainer
#27 lore raw
Quoted 29 lines · Maarten Lankhorst

Den 2024-12-13 kl. 14:03, skrev Maxime Ripard:

Quoted 17 lines

Hi,

Thanks for the new update!

Quoted 6 lines · Maarten Lankhorst

New update. Instead of calling it the 'dev' cgroup, it's now the 'dmem' cgroup.

Because it only deals with memory regions, the UAPI has been updated to use dmem.min/low/max/current, and to make the API cleaner, the names are changed too.

The API is much nicer, and fits much better into other frameworks too.

Quoted 3 lines

dmem.current could contain a line like:
"drm/0000:03:00.0/vram0 1073741824"

Quoted 8 lines
Quoted 2 lines

But I think using "drm/card0/vram0" instead of PCIID would perhaps be good too. I'm open to changing it to that based on feedback.

Do we have any sort of guarantee over the name card0 being stable across reboots?

I also wonder if we should have a "total" device that limits the amount of memory we can allocate from any region?

Quoted 6 lines

I don't think it is useful. Say your app can use 1 GB of main memory or 2 GB of VRAM, it wouldn't make sense to limit the total of those. In a lot of cases there is only 1 region, so the total of that would still be the same.

On top, we just separated the management of each region, adding a 'total' would require unseparating it again. :-)

I didn't mean the total for a device, but for the system. It would definitely not make sense for a VRAM, but for CMA for example, you have a single, limited, allocator that will be accessible from heaps, v4l2 and DRM devices.

If an application has to allocate both from v4l2 and DRM buffers, we should be able to limit its total usage of CMA, not just on a single device.

Maxime

author maintainer
#28 lore raw

Hey,

Den 2024-12-13 kl. 16:21, skrev Maxime Ripard:

Quoted 37 lines · Maarten Lankhorst
Quoted 29 lines

Den 2024-12-13 kl. 14:03, skrev Maxime Ripard:

Quoted 17 lines

Hi,

Thanks for the new update!

Quoted 6 lines · Maarten Lankhorst

New update. Instead of calling it the 'dev' cgroup, it's now the 'dmem' cgroup.

Because it only deals with memory regions, the UAPI has been updated to use dmem.min/low/max/current, and to make the API cleaner, the names are changed too.

The API is much nicer, and fits much better into other frameworks too.

Quoted 3 lines

dmem.current could contain a line like:
"drm/0000:03:00.0/vram0 1073741824"

Quoted 8 lines
Quoted 2 lines

But I think using "drm/card0/vram0" instead of PCIID would perhaps be good too. I'm open to changing it to that based on feedback.

Do we have any sort of guarantee over the name card0 being stable across reboots?

I also wonder if we should have a "total" device that limits the amount of memory we can allocate from any region?

Quoted 6 lines

I don't think it is useful. Say your app can use 1 GB of main memory or 2 GB of VRAM, it wouldn't make sense to limit the total of those. In a lot of cases there is only 1 region, so the total of that would still be the same.

On top, we just separated the management of each region, adding a 'total' would require unseparating it again. :-)

Quoted 8 lines

I didn't mean the total for a device, but for the system. It would definitely not make sense for a VRAM, but for CMA for example, you have a single, limited, allocator that will be accessible from heaps, v4l2 and DRM devices.

If an application has to allocate both from v4l2 and DRM buffers, we should be able to limit its total usage of CMA, not just on a single device.

In this case, I think it makes more sense if CMA creates a region, then use that region in both v4l2 and DRM instead of a separate region for both, with CMA being responsible for lifetime.

Cheers,
~Maarten

maintainer
#29 lore raw
Quoted 45 lines · Maarten Lankhorst

Hey,

Den 2024-12-13 kl. 16:21, skrev Maxime Ripard:

Quoted 42 lines · Maarten Lankhorst
Quoted 29 lines

Den 2024-12-13 kl. 14:03, skrev Maxime Ripard:

Quoted 17 lines

Hi,

Thanks for the new update!

Quoted 6 lines · Maarten Lankhorst

New update. Instead of calling it the 'dev' cgroup, it's now the 'dmem' cgroup.

Because it only deals with memory regions, the UAPI has been updated to use dmem.min/low/max/current, and to make the API cleaner, the names are changed too.

The API is much nicer, and fits much better into other frameworks too.

Quoted 3 lines

dmem.current could contain a line like:
"drm/0000:03:00.0/vram0 1073741824"

Quoted 8 lines
Quoted 2 lines

But I think using "drm/card0/vram0" instead of PCIID would perhaps be good too. I'm open to changing it to that based on feedback.

Do we have any sort of guarantee over the name card0 being stable across reboots?

I also wonder if we should have a "total" device that limits the amount of memory we can allocate from any region?

Quoted 6 lines

I don't think it is useful. Say your app can use 1 GB of main memory or 2 GB of VRAM, it wouldn't make sense to limit the total of those. In a lot of cases there is only 1 region, so the total of that would still be the same.

On top, we just separated the management of each region, adding a 'total' would require unseparating it again. :-)

I didn't mean the total for a device, but for the system. It would definitely not make sense for a VRAM, but for CMA for example, you have a single, limited, allocator that will be accessible from heaps, v4l2 and DRM devices.

Quoted 7 lines
Quoted 3 lines

If an application has to allocate both from v4l2 and DRM buffers, we should be able to limit its total usage of CMA, not just on a single device.

In this case, I think it makes more sense if CMA creates a region, then use that region in both v4l2 and DRM instead of a separate region for both, with CMA being responsible for lifetime.

Ack, thanks for your feedback :)

Maxime

author maintainer
#30 lore raw

Hey,

Now that all patches look good, what is needed to merge the series? Without patch 6/7 as it is a hack for testing.

I've also posted a IGT for verifying read/write works (rule out copy/paste errors) and min, max semantics work as intended.

https://lists.freedesktop.org/archives/igt-dev/2024-December/083345.html

Cheers,
~Maarten

Den 2024-12-17 kl. 08:46, skrev Maxime Ripard:

Quoted 57 lines · Maarten Lankhorst
Quoted 45 lines

Hey,

Den 2024-12-13 kl. 16:21, skrev Maxime Ripard:

Quoted 42 lines · Maarten Lankhorst
Quoted 29 lines

Den 2024-12-13 kl. 14:03, skrev Maxime Ripard:

Quoted 17 lines

Hi,l

Thanks for the new update!

Quoted 6 lines · Maarten Lankhorst

New update. Instead of calling it the 'dev' cgroup, it's now the 'dmem' cgroup.

Because it only deals with memory regions, the UAPI has been updated to use dmem.min/low/max/current, and to make the API cleaner, the names are changed too.

The API is much nicer, and fits much better into other frameworks too.

Quoted 3 lines

dmem.current could contain a line like:
"drm/0000:03:00.0/vram0 1073741824"

Quoted 8 lines
Quoted 2 lines

But I think using "drm/card0/vram0" instead of PCIID would perhaps be good too. I'm open to changing it to that based on feedback.

Do we have any sort of guarantee over the name card0 being stable across reboots?

I also wonder if we should have a "total" device that limits the amount of memory we can allocate from any region?

Quoted 6 lines

I don't think it is useful. Say your app can use 1 GB of main memory or 2 GB of VRAM, it wouldn't make sense to limit the total of those. In a lot of cases there is only 1 region, so the total of that would still be the same.

On top, we just separated the management of each region, adding a 'total' would require unseparating it again. :-)

I didn't mean the total for a device, but for the system. It would definitely not make sense for a VRAM, but for CMA for example, you have a single, limited, allocator that will be accessible from heaps, v4l2 and DRM devices.

Quoted 7 lines
Quoted 3 lines

If an application has to allocate both from v4l2 and DRM buffers, we should be able to limit its total usage of CMA, not just on a single device.

In this case, I think it makes more sense if CMA creates a region, then use that region in both v4l2 and DRM instead of a separate region for both, with CMA being responsible for lifetime.

Ack, thanks for your feedback :)

Maxime

maintainer
#31 lore raw
Quoted 2 lines · Maarten Lankhorst

Now that all patches look good, what is needed to merge the series? Without patch 6/7 as it is a hack for testing.

There were some questions raised about device naming. One thing we want to get right from the beginning is the basic interface.

Thanks.

Signature · 1 line
tejun
maintainer
#32 lore raw
Quoted 6 lines · Tejun Heo
Quoted 2 lines · Maarten Lankhorst

Now that all patches look good, what is needed to merge the series? Without patch 6/7 as it is a hack for testing.

There were some questions raised about device naming. One thing we want to get right from the beginning is the basic interface.

We decided on the previous version to use dmem and I believe this version has switched to it. Do you have any concern still?

Maxime

author maintainer
#33 lore raw
In reply to Tejun Heo

Den 2024-12-17 kl. 18:11, skrev Tejun Heo:

Quoted 9 lines · Maarten Lankhorst
Quoted 2 lines

Now that all patches look good, what is needed to merge the series? Without patch 6/7 as it is a hack for testing.

There were some questions raised about device naming. One thing we want to get right from the beginning is the basic interface.

Thanks.

I believe it was solved. The conclusion appears to be that we go with how we defined it in this series. drm/$pciid/$regionname. With the only regions defined now being VRAM. Main memory will be a followup, but requires some discussions on hwo to be prevent double accounting, and what to do with the limited amount of mappable memory.

Cheers,
~Maarten

maintainer Acked-by
#34 lore raw

Hello,

Quoted 8 lines · Maarten Lankhorst

Den 2024-12-17 kl. 18:11, skrev Tejun Heo:

Quoted 7 lines · Maarten Lankhorst
Quoted 2 lines

Now that all patches look good, what is needed to merge the series? Without patch 6/7 as it is a hack for testing.

There were some questions raised about device naming. One thing we want to get right from the beginning is the basic interface.

Quoted 7 lines
Quoted 2 lines

Thanks.

I believe it was solved. The conclusion appears to be that we go with how we defined it in this series. drm/$pciid/$regionname. With the only regions defined now being VRAM. Main memory will be a followup, but requires some discussions on hwo to be prevent double accounting, and what to do with the limited amount of mappable memory.

Provided Johannes is okay with the series, how do you want to route the series? If you want to route it through drm, that's fine by me and please feel free to add:

Thanks.

Signature · 1 line
tejun
author maintainer
#35 lore raw

Hey,

Den 2024-12-17 kl. 19:23, skrev Tejun Heo:

Quoted 19 lines

Hello,

Quoted 8 lines · Maarten Lankhorst

Den 2024-12-17 kl. 18:11, skrev Tejun Heo:

Quoted 7 lines · Maarten Lankhorst
Quoted 2 lines

Now that all patches look good, what is needed to merge the series? Without patch 6/7 as it is a hack for testing.

There were some questions raised about device naming. One thing we want to get right from the beginning is the basic interface.

Quoted 7 lines
Quoted 2 lines

Thanks.

I believe it was solved. The conclusion appears to be that we go with how we defined it in this series. drm/$pciid/$regionname. With the only regions defined now being VRAM. Main memory will be a followup, but requires some discussions on hwo to be prevent double accounting, and what to do with the limited amount of mappable memory.

Quoted 8 lines

Provided Johannes is okay with the series, how do you want to route the series? If you want to route it through drm, that's fine by me and please feel free to add:

Thanks.

Thank you!

I've discussed this with the DRM maintainers. What was suggested is to create a topic branch, merge it to drm-misc whichwhere it will be picked up into drm.git during the next pull request. At the same time the topic branch can be also be merged into the cgroup tree if needed.

The drm-misc tree already handles dma-buf and fbdev core, think DMEM could fit in there too.

Cheers,
~Maarten

maintainer
#36 lore raw
Quoted 33 lines · Maarten Lankhorst

Hey,

Den 2024-12-17 kl. 19:23, skrev Tejun Heo:

Quoted 19 lines

Hello,

Quoted 8 lines · Maarten Lankhorst

Den 2024-12-17 kl. 18:11, skrev Tejun Heo:

Quoted 7 lines · Maarten Lankhorst
Quoted 2 lines

Now that all patches look good, what is needed to merge the series? Without patch 6/7 as it is a hack for testing.

There were some questions raised about device naming. One thing we want to get right from the beginning is the basic interface.

Quoted 7 lines
Quoted 2 lines

Thanks.

I believe it was solved. The conclusion appears to be that we go with how we defined it in this series. drm/$pciid/$regionname. With the only regions defined now being VRAM. Main memory will be a followup, but requires some discussions on hwo to be prevent double accounting, and what to do with the limited amount of mappable memory.

Quoted 8 lines

Provided Johannes is okay with the series, how do you want to route the series? If you want to route it through drm, that's fine by me and please feel free to add:

Thanks.

Thank you!

Quoted 7 lines

I've discussed this with the DRM maintainers. What was suggested is to create a topic branch, merge it to drm-misc whichwhere it will be picked up into drm.git during the next pull request. At the same time the topic branch can be also be merged into the cgroup tree if needed.

The drm-misc tree already handles dma-buf and fbdev core, think DMEM could fit in there too.

FTR, I sent the PR Maarten mentioned yesterday:

https://lore.kernel.org/dri-devel/20250106-shaggy-solid-dogfish-e88ebc@houat/

Maxime

#37 lore raw
In reply to Maarten Lankhorst
Quoted 8 lines · Maarten Lankhorst

Den 2024-12-17 kl. 18:11, skrev Tejun Heo:

Quoted 5 lines · Maarten Lankhorst
Quoted 3 lines

Now that all patches look good, what is needed to merge the series? Without
patch 6/7 as it is a hack for testing.

Quoted 8 lines
Quoted 6 lines

There were some questions raised about device naming. One thing we want to
get right from the beginning is the basic interface.

Thanks.

I believe it was solved. The conclusion appears to be that we go with how we defined it in this series. drm/$pciid/$regionname.

Yeah, I'd agree. Using PCI IDs works, and the objection about cardN syntax being unstable when driver load order changes is a good point.

Friedrich

Quoted 7 lines

With the only
regions defined now being VRAM. Main memory will be a followup, but requires some discussions on hwo to be prevent double accounting, and what to do with the limited amount of mappable memory.

Cheers,
~Maarten