dma-buf: heaps: Add support for Tegra VPR
Subsystems (16)
Thierry Reding
maintainerv6 cover dma-buf: heaps: Add support for Tegra VPR
This series adds support for the video protection region (VPR) used on Tegra SoC devices. It's a special region of memory that is protected from accesses by the CPU and used to store DRM protected content (both decrypted stream data as well as decoded video frames).
Patches 1 through 3 add DT binding documentation for the VPR and add the VPR to the list of memory-region items for display, host1x and NVDEC.
The set_direct_map_*_noflush() functions that will be used later in this series are exported in patch 4 so that the drivers that use them can be built as a module.
Patch 5 adds bitmap_allocate(), which is like bitmap_allocate_region() but works on sizes that are not a power of two.
The of_node_to_nid() function is exported in patch 6 because it is used in a later patch adding a driver that can be built as a module.
Patch 7 introduces new APIs needed by the Tegra VPR implementation that allow memory to be allocated at a fixed offset within a CMA area. Tegra VPR needs this in order to implement its own allocator on top of CMA to meet the strict hardware requirements. This replaces the dynamic CMA area creation patch from earlier versions.
Patch 8 adds some infrastructure for DMA heap implementations to provide information through debugfs.
The Tegra VPR implementation is added in patch 9. See its commit message for more details about the specifics of this implementation.
Finally, patches 10-12 add the VPR placeholder node on Tegra234 and Tegra264 and hook it up to the host1x node so that it can make use of this region.
Changes in v6:
- refactor cma_alloc_at() to maximize code reuse
- allow building Tegra VPR support as a module
- requires two new patches to export symbols
- Link to v5: https://patch.msgid.link/[email protected]
Changes in v5:
- use a single CMA area in combination with the new cma_alloc_at() API
- drop dynamic CMA area allocation patch
- various cleanups
- Link to v4: https://patch.msgid.link/[email protected]
Changes in v4:
- Link to v3: https://patch.msgid.link/[email protected]
- fully remove from linear map while chunks are active
- address checkpatch.pl and Sashiko comments
- improve error handling
- remove freezer support
Changes in v3:
- Link to v2: https://patch.msgid.link/[email protected]
- introduce set_memory_device() and set_memory_normal()
- rename VPR nodes to "protected"
- add Tegra264 placeholder nodes
Changes in v2:
- Link to v1: https://patch.msgid.link/[email protected]
- Tegra VPR implementation is now more optimized to reduce the number of (very slow) resize operations, and allows cross-chunk allocations
- dynamic CMA areas are now trackd separately from static ones, but the global number of CMA pages accounts for all areas
Thierry
---
Thierry Reding (12):
dt-bindings: reserved-memory: Document Tegra VPR
dt-bindings: display: tegra: Document memory regions
dt-bindings: gpu: host1x: Document memory-regions for NVDEC arm64/mm: Export set_direct_map_*_noflush() APIs
bitmap: Add bitmap_allocate() function
of: Export of_node_to_nid()
mm/cma: Introduce cma_alloc_at() API
dma-buf: heaps: Add debugfs support
dma-buf: heaps: Add support for Tegra VPR
arm64: tegra: Add VPR placeholder node on Tegra234
arm64: tegra: Hook up VPR to host1x
arm64: tegra: Add VPR placeholder node on Tegra264
.../display/tegra/nvidia,tegra124-vic.yaml | 8 + .../bindings/display/tegra/nvidia,tegra186-dc.yaml | 10 + .../bindings/display/tegra/nvidia,tegra20-dc.yaml | 10 +- .../display/tegra/nvidia,tegra20-host1x.yaml | 7 + .../bindings/gpu/host1x/nvidia,tegra234-nvdec.yaml | 8 + .../nvidia,tegra-video-protection-region.yaml | 75 ++ arch/arm64/boot/dts/nvidia/tegra234.dtsi | 45 + arch/arm64/boot/dts/nvidia/tegra264.dtsi | 33 + arch/arm64/mm/pageattr.c | 2 + drivers/dma-buf/dma-heap.c | 52 + drivers/dma-buf/heaps/Kconfig | 12 + drivers/dma-buf/heaps/Makefile | 10 + drivers/dma-buf/heaps/tegra-vpr-init.c | 133 +++ drivers/dma-buf/heaps/tegra-vpr.c | 1210 ++++++++++++++++++++ drivers/dma-buf/heaps/tegra-vpr.h | 73 ++ drivers/of/of_numa.c | 1 + include/linux/bitmap.h | 25 +- include/linux/cma.h | 4 + include/linux/dma-heap.h | 2 + include/trace/events/cma.h | 77 +- include/trace/events/tegra_vpr.h | 57 + mm/cma.c | 88 +- 22 files changed, 1913 insertions(+), 29 deletions(-)
---
base-commit: 850de4c714df026eb4c869fdb01dd722003e1ae3
change-id: 20260507-tegra-vpr-cd4bc2509c4c
Best regards,
Signature · 1 line
Thierry Reding <[email protected]>
Thierry Reding
maintainerPATCH v6 1/12 dt-bindings: reserved-memory: Document Tegra VPR
From: Thierry Reding <[email protected]>
The Video Protection Region (VPR) found on NVIDIA Tegra chips is a region of memory that is protected from CPU accesses. It is used to decode and play back DRM protected content.
It is a standard reserved memory region that can exist in two forms:
static VPR where the base address and size are fixed (uses the "reg" property to describe the memory) and a resizable VPR where only the size is known upfront and the OS can allocate it wherever it can be accomodated.
---
Changes in v4:
- move oneOf into allOf for a bit more tidiness
- fix example "reg" property
Changes in v3:
- add examples for fixed and resizable VPR
--- .../nvidia,tegra-video-protection-region.yaml | 75 ++++++++++++++++++++++ 1 file changed, 75 insertions(+)
Documentation/devicetree/bindings/reserved-memory/nvidia,tegra-video-protection-region.yaml new file +75 -0
@@ -0,0 +1,75 @@ +# SPDX-License-Identifier: (GPL-2.0 OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/reserved-memory/nvidia,tegra-video-protection-region.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: NVIDIA Tegra Video Protection Region (VPR) + +maintainers: + - Thierry Reding <[email protected]> + - Jon Hunter <[email protected]> + +description: | + NVIDIA Tegra chips have long supported a mechanism to protect a single, + contiguous memory region from non-secure memory accesses. Typically this + region is used for decoding and playback of DRM protected content. Various + devices, such as the display controller and multimedia engines (video + decoder) can access this region in a secure way. Access from the CPU is + generally forbidden. + + Two variants exist for VPR: one is fixed in both the base address and size, + while the other is resizable. Fixed VPR can be described by just a "reg" + property specifying the base address and size, whereas the resizable VPR + is defined by a size/alignment pair of properties. For resizable VPR the + memory is reusable by the rest of the system when it's unused for VPR and + therefore the "reusable" property must be specified along with it. For a + fixed VPR, the memory is permanently protected, and therefore it's not + reusable and must also be marked as "no-map" to prevent any (including + speculative) accesses to it. + +allOf: + - $ref: reserved-memory.yaml + - oneOf: + - required: + - compatible + - reg + + - required: + - compatible + - size + +properties: + compatible: + const: nvidia,tegra-video-protection-region + +dependencies: + size: [alignment, reusable] + alignment: [size, reusable] + reusable: [alignment, size] + + reg: [no-map] + no-map: [reg] + +unevaluatedProperties: false + +examples: + - | + /* resizable VPR */ + protected { + compatible = "nvidia,tegra-video-protection-region"; + + size = <0x0 0x70000000>; + alignment = <0x0 0x100000>; + reusable; + }; + + - | + /* fixed VPR */ + protected@a8000000 { + compatible = "nvidia,tegra-video-protection-region"; + + /* fixed VPR */ + reg = <0xa8000000 0x70000000>; + no-map; + };
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v6 01/12] dt-bindings: reserved-memory: Document Tegra VPR
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] The examples fail to provide a `reserved-memory` parent node to establish the `#address-cells` and…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] The examples fail to provide a reserved-memory parent node to establish the #address-cells and #size-cells context, leading to schema validation failures. --
commit f2d3906971093a4dcbac5c42465c2d0d7ce5d0a8
Author: Thierry Reding <[email protected]>
dt-bindings: reserved-memory: Document Tegra VPR
This commit adds device tree bindings for the NVIDIA Tegra Video Protection Region (VPR), documenting both fixed and resizable variants.
Quoted 5 lines
Documentation/devicetree/bindings/reserved-memory/nvidia,tegra-video-protection-region.yaml new file +0
-0
[ ... ]
Documentation/devicetree/bindings/reserved-memory/nvidia,tegra-video-protection-region.yaml line 62
Quoted 7 lines
Documentation/devicetree/bindings/reserved-memory/nvidia,tegra-video-protection-region.yaml new file +7
-0+examples: + - | + /* resizable VPR */ + protected { + compatible = "nvidia,tegra-video-protection-region"; + + size = <0x0 0x70000000>;
[Severity: Low]
Will this fail make dt_binding_check during schema validation?
Since the example lacks an explicit reserved-memory parent node to establish the #address-cells and #size-cells context, dtschema wraps this in a dummy root node with a default of #size-cells = <1>. Supplying 2 cells for the size here exceeds that implicit constraint.
Quoted 1 line
+ alignment = <
0x00x100000>;
[Severity: Low]
Similarly, does this 2-cell alignment array violate the implicit #size-cells = <1> constraint for the same reason?
Documentation/devicetree/bindings/reserved-memory/nvidia,tegra-video-protection-region.yaml line 73
Quoted 10 lines
Documentation/devicetree/bindings/reserved-memory/nvidia,tegra-video-protection-region.yaml new file +10
-0+ reusable; + }; + + - | + /* fixed VPR */ + protected@a8000000 { + compatible = "nvidia,tegra-video-protection-region"; + + /* fixed VPR */ + reg = <0xa8000000 0x70000000>;
[Severity: Low]
Without a shared parent node to explicitly declare #address-cells and #size-cells contexts, does this 2-cell reg property parse under the default 1-cell context (treating address=0xa8000000 and size=0x70000000)?
This creates a semantic mismatch with the 64-bit lengths intended in the first example. Wrapping the examples in a reserved-memory parent node might resolve these context issues.
Quoted 2 lines
Documentation/devicetree/bindings/reserved-memory/nvidia,tegra-video-protection-region.yaml new file +2
-0+ no-map; + };
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
Thierry Reding
maintainerPATCH v6 2/12 dt-bindings: display: tegra: Document memory regions
In reply to Thierry RedingFrom: Thierry Reding <[email protected]>
Add the memory-region and memory-region-names properties to the bindings for the display controllers and the host1x engine found on various Tegra generations. These memory regions are used to access firmware-provided framebuffer memory as well as the video protection region.
---
Changes in v4:
- typofix
Changes in v3:
- document properties for VIC
--- .../devicetree/bindings/display/tegra/nvidia,tegra124-vic.yaml | 8 ++++++++ .../devicetree/bindings/display/tegra/nvidia,tegra186-dc.yaml | 10 ++++++++++ .../devicetree/bindings/display/tegra/nvidia,tegra20-dc.yaml | 10 +++++++++- .../bindings/display/tegra/nvidia,tegra20-host1x.yaml | 7 +++++++ 4 files changed, 34 insertions(+), 1 deletion(-)
Documentation/devicetree/bindings/display/tegra/nvidia,tegra124-vic.yaml +8 -0
@@ -68,6 +68,14 @@ properties: - const: dma-mem # read - const: write + memory-region: + items: + - description: reference to the video protection memory region + + memory-region-names: + items: + - const: protected + dma-coherent: true additionalProperties: false
Documentation/devicetree/bindings/display/tegra/nvidia,tegra186-dc.yaml +10 -0
@@ -57,6 +57,16 @@ properties: - const: dma-mem # read-0 - const: read-1 + memory-region: + minItems: 1 + maxItems: 2 + + memory-region-names: + items: + enum: [ framebuffer, protected ] + minItems: 1 + maxItems: 2 + nvidia,outputs: description: A list of phandles of outputs that this display controller can drive.
Documentation/devicetree/bindings/display/tegra/nvidia,tegra20-dc.yaml +9 -1
@@ -65,7 +65,15 @@ properties: items: - description: phandle to the core power domain - memory-region: true + memory-region: + minItems: 1 + maxItems: 2 + + memory-region-names: + items: + enum: [ framebuffer, protected ] + minItems: 1 + maxItems: 2 nvidia,head: $ref: /schemas/types.yaml#/definitions/uint32
Documentation/devicetree/bindings/display/tegra/nvidia,tegra20-host1x.yaml +7 -0
@@ -98,6 +98,13 @@ properties: items: - description: phandle to the HEG or core power domain + memory-region: + maxItems: 1 + + memory-region-names: + items: + - const: protected + required: - compatible - interrupts
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v6 02/12] dt-bindings: display: tegra: Document memory regions
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 9 lines
From: Thierry Reding <[email protected]>
Add the memory-region and memory-region-names properties to the bindings for the display controllers and the host1x engine found on various Tegra generations. These memory regions are used to access firmware-provided framebuffer memory as well as the video protection region.
Reviewed-by Rob Herring (Arm) <[email protected]>Signed-off-by Thierry Reding <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
Thierry Reding
maintainerPATCH v6 3/12 dt-bindings: gpu: host1x: Document memory-regions for NVDEC
In reply to Thierry RedingFrom: Thierry Reding <[email protected]>
The video protection region is a reserved memory region that can be used for secure video playback. NVDEC can access this region to decode images into securely.
--- .../devicetree/bindings/gpu/host1x/nvidia,tegra234-nvdec.yaml | 8 ++++++++ 1 file changed, 8 insertions(+)
Documentation/devicetree/bindings/gpu/host1x/nvidia,tegra234-nvdec.yaml +8 -0
@@ -60,6 +60,14 @@ properties: - const: dma-mem - const: write + memory-region: + items: + - description: reference to the video protection memory region + + memory-region-names: + items: + - const: protected + nvidia,memory-controller: $ref: /schemas/types.yaml#/definitions/phandle description:
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v6 03/12] dt-bindings: gpu: host1x: Document memory-regions for NVDEC
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] The `memory-region` and `memory-region-names` properties for the Video Protection Region (VPR)…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] The memory-region and memory-region-names properties for the Video Protection Region (VPR) were added to the Tegra234 NVDEC binding but omitted from the older NVDEC binding (nvidia,tegra210-nvdec.yaml) which covers Tegra210, Tegra186, and Tegra194. Other hardware blocks on these older chips (such as VIC and DC) already document and use memory-region for the VPR, indicating that the hardware shares the same capability. Failing to update the related YAML files in the same family causes schema validation to fail for complete device trees. --
commit c5ee297bfa8219c2a7d714b86f0738c220914705
Author: Thierry Reding <[email protected]>
dt-bindings: gpu: host1x: Document memory-regions for NVDEC
The video protection region is a reserved memory region that can be used for secure video playback. NVDEC can access this region to decode images into securely.
Quoted 5 lines
Documentation/devicetree/bindings/gpu/host1x/nvidia,tegra234-nvdec.yaml +0
-0
Documentation/devicetree/bindings/gpu/host1x/nvidia,tegra234-nvdec.yaml properties: · line 69
Quoted 10 lines
Documentation/devicetree/bindings/gpu/host1x/nvidia,tegra234-nvdec.yaml +7
-0@@ -60,6 +60,14 @@ properties: - const: dma-mem - const: write + memory-region: + items: + - description: reference to the video protection memory region + + memory-region-names: + items: + - const: protected
[Severity: Medium]
Should these properties also be added to the older NVDEC binding (nvidia,tegra210-nvdec.yaml) which covers Tegra210, Tegra186, and Tegra194?
Other hardware blocks on these older chips (such as VIC and DC) already document and use memory-region for the Video Protection Region, indicating that the hardware shares the same capability.
If a device tree for Tegra210, Tegra186, or Tegra194 correctly specifies the Video Protection Region for NVDEC, will it fail schema validation because the properties are undocumented and additionalProperties: false is set in the older binding?
Quoted 4 lines
Documentation/devicetree/bindings/gpu/host1x/nvidia,tegra234-nvdec.yaml +1
-0+ nvidia,memory-controller: $ref: /schemas/types.yaml#/definitions/phandle description:
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
Thierry Reding
maintainerRe: [PATCH v6 03/12] dt-bindings: gpu: host1x: Document memory-regions for NVDEC
Quoted 33 lines · On Fri, Sep 04, 2026 at 11:03:59AM +0000, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Thememory-regionandmemory-region-namesproperties for the Video Protection Region (VPR) were added to the Tegra234 NVDEC binding but omitted from the older NVDEC binding (nvidia,tegra210-nvdec.yaml) which covers Tegra210, Tegra186, and Tegra194. Other hardware blocks on these older chips (such as VIC and DC) already document and usememory-regionfor the VPR, indicating that the hardware shares the same capability. Failing to update the related YAML files in the same family causes schema validation to fail for complete device trees. --commit
c5ee297bfa8219c2a7d714b86f0738c220914705
Author: Thierry Reding <[email protected]>dt-bindings: gpu: host1x: Document memory-regions for NVDEC
The video protection region is a reserved memory region that can be used for secure video playback. NVDEC can access this region to decode images into securely.
Quoted 5 lines
Documentation/devicetree/bindings/gpu/host1x/nvidia,tegra234-nvdec.yaml +0
-0Documentation/devicetree/bindings/gpu/host1x/nvidia,tegra234-nvdec.yaml properties: · line 69
Quoted 10 lines
Documentation/devicetree/bindings/gpu/host1x/nvidia,tegra234-nvdec.yaml +7
-0@@ -60,6 +60,14 @@ properties: - const: dma-mem - const: write + memory-region: + items: + - description: reference to the video protection memory region + + memory-region-names: + items: + - const: protected[Severity: Medium]
Should these properties also be added to the older NVDEC binding (nvidia,tegra210-nvdec.yaml) which covers Tegra210, Tegra186, and Tegra194?
Quoted 8 lines
Other hardware blocks on these older chips (such as VIC and DC) already document and use memory-region for the Video Protection Region, indicating that the hardware shares the same capability.
If a device tree for Tegra210, Tegra186, or Tegra194 correctly specifies the Video Protection Region for NVDEC, will it fail schema validation because the properties are undocumented and additionalProperties: false is set in the older binding?
For the record: we'll add this to the Tegra210 NVDEC bindings in due time. It's currently only been tested on Tegra234, hence why only that binding is updated.
Thierry
Thierry Reding
maintainerPATCH v6 4/12 arm64/mm: Export set_direct_map_*_noflush() APIs
In reply to Thierry RedingFrom: Thierry Reding <[email protected]>
Drivers that use this may want to be built as a module, so export them.
--- arch/arm64/mm/pageattr.c | 2 ++ 1 file changed, 2 insertions(+)
arch/arm64/mm/pageattr.c +2 -0
@@ -262,6 +262,7 @@ int set_direct_map_invalid_noflush(struct page *page, unsigned int numpages)return update_range_prot ((unsigned long )page_address (page),PAGE_SIZE * numpages, set_mask, clear_mask); } +EXPORT_SYMBOL (set_direct_map_invalid_noflush);int set_direct_map_default_noflush (struct page *page,unsigned int numpages) {
@@ -274,6 +275,7 @@ int set_direct_map_default_noflush(struct page *page, unsigned int numpages)return update_range_prot ((unsigned long )page_address (page),PAGE_SIZE * numpages, set_mask, clear_mask); } +EXPORT_SYMBOL (set_direct_map_default_noflush); static int __set_memory_enc_dec(unsigned long addr, int numpages,
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v6 04/12] arm64/mm: Export set_direct_map_*_noflush() APIs
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] Exporting `set_direct_map_*_noflush` APIs without exporting `can_set_direct_map` forces loadable…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Exporting set_direct_map_*_noflush APIs without exporting can_set_direct_map forces loadable modules to silently fail to protect memory on ARM64, breaking security guarantees. --
commit 6a5f6422ed6de263b9c669919e175cc7d1ac6c09
Author: Thierry Reding <[email protected]>
arm64/mm: Export set_direct_map_*_noflush() APIs
Drivers that use this may want to be built as a module, so export them.
arch/arm64/mm/pageattr.c int set_direct_map_invalid_noflush(struct page *page, unsigned int numpages) · line 265
Quoted 9 lines
arch/arm64/mm/pageattr.c +1
-0@@ -262,6 +262,7 @@ int set_direct_map_invalid_noflush(struct page *page, unsigned int numpages)return update_range_prot ((unsigned long )page_address (page),PAGE_SIZE * numpages, set_mask, clear_mask); } +EXPORT_SYMBOL (set_direct_map_invalid_noflush);
[Severity: High]
Are loadable modules going to silently fail to protect memory when using this exported API?
If the kernel boots with a configuration where can_set_direct_map() is false (e.g., rodata_full and debug_pagealloc are disabled), set_direct_map_invalid_noflush() returns 0 without modifying the page tables:
arch/arm64/mm/pageattr.c:set_direct_map_invalid_noflush() {
...
if (!can_set_direct_map())
return 0;
...
}Because can_set_direct_map() is not exported, a module cannot check this capability itself. The module will receive 0 (success) and mistakenly assume the memory was successfully isolated.
For security features, this means content-protected memory remains accessible in the kernel's linear mapping. This can break DRM guarantees by allowing the CPU to read protected memory, or cause a kernel panic if the hardware enforces protection but the CPU speculatively accesses the region via stale linear map PTEs.
arch/arm64/mm/pageattr.c int set_direct_map_default_noflush(struct page *page, unsigned int numpages) · line 278
Quoted 8 lines
arch/arm64/mm/pageattr.c +1
-0int set_direct_map_default_noflush (struct page *page,unsigned int numpages) {@@ -274,6 +275,7 @@ int set_direct_map_default_noflush(struct page *page, unsigned int numpages)return update_range_prot ((unsigned long )page_address (page),PAGE_SIZE * numpages, set_mask, clear_mask); } +EXPORT_SYMBOL (set_direct_map_default_noflush);
[Severity: High]
Does this apply the same silent failure logic when a module attempts to restore the mapping?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
Re: [PATCH v6 04/12] arm64/mm: Export set_direct_map_*_noflush() APIs
In reply to Thierry RedingQuoted 3 lines · Thierry Reding
From: Thierry Reding <[email protected]>
Drivers that use this may want to be built as a module, so export them.
That's one of the worst commit log ever. No, we don't just export core symbols dealing with the kernel direct map because "Drivers that use this may want to be built as a module".
For one exporting this at all needs a very good justification and not just hand waiving. But more importantly if we can't avoid exporting it, it needs to be exported at the tightest sensible scope. E.g. for a given module if it is so special, or a namespace if it's not that special. But in doubt we should have a proper core abstraction instead of opening up direct map manipulation to random modules.
Thierry Reding
maintainerRe: [PATCH v6 04/12] arm64/mm: Export set_direct_map_*_noflush() APIs
Quoted 9 lines · Christoph Hellwig
Quoted 3 lines · Thierry Reding
From: Thierry Reding <[email protected]>
Drivers that use this may want to be built as a module, so export them.
That's one of the worst commit log ever. No, we don't just export core symbols dealing with the kernel direct map because "Drivers that use this may want to be built as a module".
Quoted 7 lines
For one exporting this at all needs a very good justification and not just hand waiving. But more importantly if we can't avoid exporting it, it needs to be exported at the tightest sensible scope. E.g. for a given module if it is so special, or a namespace if it's not that special. But in doubt we should have a proper core abstraction instead of opening up direct map manipulation to random modules.
Fair points. In an earlier set of patches this was abstracted behind a set of set_memory_*() functions, modelled after set_memory_encrypted() and set_memory_decrypted(), which I think I'd still prefer, too.
Is that more along the lines of what you had in mind?
Thanks,
Thierry
Thierry Reding
maintainerPATCH v6 5/12 bitmap: Add bitmap_allocate() function
In reply to Thierry RedingFrom: Thierry Reding <[email protected]>
This is similar to bitmap_allocate_region() but allows allocation of non-power of two pages/bits.
While at it, reimplement bitmap_allocate_region() in terms of this new helper to remove a sliver of code duplication.
--- include/linux/bitmap.h | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-)
include/linux/bitmap.h +20 -5
@@ -716,10 +716,10 @@ void bitmap_release_region(unsigned long *bitmap, unsigned int pos, int order) }/** -* bitmap_allocate_region - allocate bitmap region +* bitmap_allocate - allocate bitmap region * @bitmap: array of unsigned longs corresponding to the bitmap * @pos: beginning of bit region to allocate -* @order: region size (log base 2 of number of bits) to allocate +* @len: number of bits to allocate * * Allocate (set bits in) a specified region of a bitmap. *
@@ -727,16 +727,31 @@ void bitmap_release_region(unsigned long *bitmap, unsigned int pos, int order)* free (not all bits were zero). */ static __always_inline -int bitmap_allocate_region(unsigned long *bitmap, unsigned int pos, int order) +int bitmap_allocate(unsigned long *bitmap, unsigned int pos, unsigned int len) { -unsigned int len =BIT (order); -if (find_next_bit (bitmap, pos + len, pos) < pos + len)return -EBUSY ;bitmap_set (bitmap, pos, len);return 0 ; } +/** +* bitmap_allocate_region - allocate bitmap region +* @bitmap: array of unsigned longs corresponding to the bitmap +* @pos: beginning of bit region to allocate +* @order: region size (log base 2 of number of bits) to allocate +* +* Allocate (set bits in) a specified region of a bitmap. +* +* Returns: 0 on success, or %-EBUSY if specified region wasn't +* free (not all bits were zero). +*/ +static __always_inline +int bitmap_allocate_region(unsigned long *bitmap, unsigned int pos, int order) +{ +return bitmap_allocate (bitmap, pos,BIT (order)); +} +/** * bitmap_find_free_region - find a contiguous aligned mem region * @bitmap: array of unsigned longs corresponding to the bitmap
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v6 05/12] bitmap: Add bitmap_allocate() function
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 9 lines
From: Thierry Reding <[email protected]>
This is similar to
bitmap_allocate_region()but allows allocation of non-power of two pages/bits.While at it, reimplement
bitmap_allocate_region()in terms of this new helper to remove a sliver of code duplication.Signed-off-by Thierry Reding <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
Thierry Reding
maintainerPATCH v6 6/12 of: Export of_node_to_nid()
In reply to Thierry RedingFrom: Thierry Reding <[email protected]>
Drivers buildable as a module may want to use this, so export it.
--- drivers/of/of_numa.c | 1 + 1 file changed, 1 insertion(+)
drivers/of/of_numa.c +1 -0
@@ -171,6 +171,7 @@ int of_node_to_nid(struct device_node *device)return NUMA_NO_NODE ; } +EXPORT_SYMBOL (of_node_to_nid);int __init of_numa_init (void ) {
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v6 06/12] of: Export of_node_to_nid()
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] Missing #include <linux/export.h> for EXPORT_SYMBOL macro. --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] Missing #include <linux/export.h> for EXPORT_SYMBOL macro.
--
commit 44baf41b1565a3ea5c2669a320dc9b29217d32c3
Author: Thierry Reding <[email protected]>
of: Export of_node_to_nid()
This commit exports of_node_to_nid() so that drivers buildable as modules can use it.
drivers/of/of_numa.c int of_node_to_nid(struct device_node *device) · line 174
Quoted 9 lines
drivers/of/of_numa.c +1
-0@@ -171,6 +171,7 @@ int of_node_to_nid(struct device_node *device)return NUMA_NO_NODE ; } +EXPORT_SYMBOL (of_node_to_nid);
[Severity: Low]
Should this file explicitly include <linux/export.h> or <linux/module.h>?
Using EXPORT_SYMBOL without explicitly including its defining header relies on transitive includes. This could potentially cause build failures if those implicit includes change in the future on certain configurations or architectures.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
Rob Herring
maintainerRe: [PATCH v6 06/12] of: Export of_node_to_nid()
In reply to Thierry RedingQuoted 3 lines · Thierry Reding
From: Thierry Reding <[email protected]>
Drivers buildable as a module may want to use this, so export it.
We need a specific reason/driver. Otherwise, that's every API function.
It doesn't look to me like the VPR driver ever actually uses the NID.
Quoted 11 lines
Signed-off-by Thierry Reding <[email protected]>--- drivers/of/of_numa.c | 1 + 1 file changed, 1 insertion(+)drivers/of/of_numa.c +0
-0
drivers/of/of_numa.c int of_node_to_nid(struct device_node *device) · line 174
Quoted 4 lines
drivers/of/of_numa.c +1
-0@@ -171,6 +171,7 @@ int of_node_to_nid(struct device_node *device)return NUMA_NO_NODE ; } +EXPORT_SYMBOL (of_node_to_nid);
Assuming this is still needed, EXPORT_SYMBOL_GPL.
Rob
Thierry Reding
maintainerRe: [PATCH v6 06/12] of: Export of_node_to_nid()
Quoted 8 lines · Rob Herring
Quoted 3 lines · Thierry Reding
From: Thierry Reding <[email protected]>
Drivers buildable as a module may want to use this, so export it.
We need a specific reason/driver. Otherwise, that's every API function.
It doesn't look to me like the VPR driver ever actually uses the NID.
You're right, we currently don't need this. The plan is to use this to differentiate between VPR instances on NUMA systems, but we don't have any such system yet. I'll drop this patch for now.
Thierry
Thierry Reding
maintainerPATCH v6 7/12 mm/cma: Introduce cma_alloc_at() API
In reply to Thierry RedingFrom: Thierry Reding <[email protected]>
This API can be used to allocate a number of CMA pages starting at a fixed offset. This is useful, for example, if the CMA area is used as backing storage for a nested allocator that has stricter requirements than CMA itself.
In order to reuse most of the existing code, the cma_range_alloc() function is enhanced to take as inputs a range of pages to look for a free region. If this range encompasses the entire CMA range, the behavior is as before, but the range can also be specified to match the offset and size passed in from cma_alloc_at(), in which case that is the range that will be allocated (or allocation will fail if the range is not available).
---
Changes in v6:
- refactor cma_range_alloc() so it can be reused for _at() code paths
--- include/linux/cma.h | 4 +++ include/trace/events/cma.h | 77 ++++++++++++++++++++++++++++++++++++++-- mm/cma.c | 88 +++++++++++++++++++++++++++++++++++----------- 3 files changed, 146 insertions(+), 23 deletions(-)
include/linux/cma.h +4 -0
@@ -49,11 +49,15 @@ extern int cma_init_reserved_mem(phys_addr_t base, phys_addr_t size, struct cma **res_cma);extern struct page *cma_alloc (struct cma *cma,unsigned long count,unsigned int align,bool no_warn); +extern struct page *cma_alloc_at (struct cma *cma,unsigned long offset, +unsigned long count,bool no_warn);extern bool cma_release (struct cma *cma,const struct page *pages,unsigned long count);struct page *cma_alloc_frozen (struct cma *cma,unsigned long count,unsigned int align,bool no_warn);struct page *cma_alloc_frozen_compound (struct cma *cma,unsigned int order); +struct page *cma_alloc_at_frozen (struct cma *cma,unsigned long offset, +unsigned long count,bool no_warn);bool cma_release_frozen (struct cma *cma,const struct page *pages,unsigned long count);
include/trace/events/cma.h +74 -3
107 lines not on this page · raw message
mm/cma.c +68 -20
173 lines not on this page · raw message
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v6 07/12] mm/cma: Introduce cma_alloc_at() API
Thank you for your contribution! Sashiko AI review found 6 potential issue(s) to consider: - [Critical] Infinite loop in `cma_range_alloc()` when the found page range is not contiguous. - [High]…
Thank you for your contribution! Sashiko AI review found 6 potential issue(s) to consider:
- [Critical] Infinite loop in cma_range_alloc() when the found page range is not contiguous.
- [High] Unit mismatch in cma_range_alloc() causes out-of-bounds bitmap accesses when cma->order_per_bit > 0.
- [Medium] __cma_alloc_frozen() dereferences the cma pointer before verifying that it is not NULL.
- [Medium] cma_alloc_at() with offset 0 bypasses multi-range protection, allowing incorrect fallback allocations.
- [Medium] cma_alloc_at() lacks alignment validation for offset, leading to silent truncation.
- [Low] The newly defined trace events cma_alloc_at_start and cma_alloc_at_finish are never emitted. --
commit 14084cc27d73ffca7f55e0856f2f9a10ae91ca42
Author: Thierry Reding <[email protected]> Date: Fri Sep 4 10:44:58 2026 +0000
mm/cma: Introduce cma_alloc_at() API
This commit introduces a new cma_alloc_at() API to allocate contiguous memory starting at a fixed page offset. The cma_range_alloc() function is refactored to support range-bounded allocations, enabling the new API to reuse the existing allocation path.
Quoted 4 lines
include/trace/events/cma.h +0
-0
[ ... ]
include/trace/events/cma.h TRACE_EVENT(cma_alloc_busy_retry, · line 147
Quoted 9 lines
include/trace/events/cma.h +5
-0@@ -132,6 +140,69 @@ TRACE_EVENT(cma_alloc_busy_retry, __entry->align) ); +TRACE_EVENT(cma_alloc_at_start, + + TP_PROTO(const char *name, unsigned long pfn, + unsigned long request_count, unsigned long available_count, + unsigned long total_count),
[Severity: Low]
Are these new trace events actually emitted anywhere?
It looks like cma_alloc_at() calls __cma_alloc_frozen(), which continues to use the existing trace_cma_alloc_start() and trace_cma_alloc_finish() events. Do we need these new definitions if they remain unused?
Quoted 4 lines
mm/cma.c +0
-0
[ ... ]
Quoted 26 lines
static int cma_range_alloc(struct cma *cma, struct
cma_memrange*cmr,mm/cma.c +7
-6- unsigned long count, unsigned int align, - struct page **pagep, gfp_t gfp) + unsigned long start, unsigned long end, + unsigned long count, unsigned int align, + struct page **pagep, gfp_t gfp) { unsigned long bitmap_maxno, bitmap_no, bitmap_count; -unsigned long start, pfn, mask, offset; -int ret = -EBUSY ; +unsigned long pfn, mask, offset;struct page *page =NULL ; +int ret = -EBUSY ; mask =cma_bitmap_aligned_mask (cma, align); offset =cma_bitmap_aligned_offset (cma, cmr, align); - bitmap_maxno =cma_bitmap_maxno (cma, cmr); + bitmap_maxno = (end > start) ? end :cma_bitmap_maxno (cma, cmr); bitmap_count =cma_bitmap_pages_to_bits (cma, count);if (bitmap_count > bitmap_maxno) goto out; -for (start =0 ; ; start = bitmap_no + mask +1 ) { +while (true) {spin_lock_irq (&cma->lock);
[ ... ]
mm/cma.c
Quoted 3 lines
mm/cma.c +3
-0+ bitmap_no =bitmap_find_next_zero_area_off (cmr->bitmap, + bitmap_maxno, start, bitmap_count, mask, + offset);
[Severity: High]
Does this code use page counts where bit indices are expected?
The end and start parameters are passed in as unscaled page counts from cma_alloc_at(), and end is assigned directly to bitmap_maxno. If cma->order_per_bit > 0, a single bit represents multiple pages.
Passing unscaled page counts directly as bit indices to bitmap_find_next_zero_area_off() could cause it to read past the end of the bitmap, and subsequently cause bitmap_set() to write out of bounds.
Quoted 9 lines
mm/cma.c +0
-0if (bitmap_no >= bitmap_maxno) {spin_unlock_irq (&cma->lock);break ; } pfn = cmr->base_pfn + (bitmap_no << cma->order_per_bit); page =pfn_to_page (pfn);/*
mm/cma.c
Quoted 10 lines
mm/cma.c +0
-0* Do not hand out page ranges that are not contiguous, so * callers can just iterate the pages without having to worry * about these corner cases. */ if (!page_range_contiguous (page, count)) {spin_unlock_irq (&cma->lock);pr_warn_ratelimited ("%s: %s: skipping incompatible area [0x%lx-0x%lx]" , __func__, cma->name, pfn, pfn + count -1 );continue ; }
[Severity: Critical]
Could this continue statement cause an infinite loop?
Since this was changed from a for loop to a while (true) loop, the continue statement jumps directly back to the loop condition. This skips the 'start = bitmap_no + mask + 1;' update at the end of the loop body.
The loop will retry with the exact same start index and unmodified bitmap state, find the exact same incompatible area, and loop without terminating.
[ ... ]
Quoted 4 lines
mm/cma.c +2
-2-static struct page *__cma_alloc_frozen (struct cma *cma, -unsigned long count,unsigned int align,gfp_t gfp) +static struct page *__cma_alloc_frozen(struct cma *cma, unsigned long start, + unsigned long end, unsigned long count,
mm/cma.c static int cma_range_alloc(struct cma *cma, struct cma_memrange *cmr, · line 888
Quoted 10 lines
mm/cma.c +5
-1+ unsigned int align, gfp_t gfp) {struct page *page =NULL ;int ret = -ENOMEM , r;unsigned long i; -const char *name = cma ? cma->name :NULL ; + +/* cma_alloc_at() and friends will only work with single-range CMA */ +if (WARN_ON_ONCE (start >0 && cma->nranges !=1 )) +return page;
[Severity: Medium]
Is there a risk of a NULL pointer dereference here?
If __cma_alloc_frozen() is called with a NULL cma pointer and a non-zero start offset via the exported cma_alloc_at() API, cma->nranges is evaluated before the '!cma || !cma->count' safety check below it.
[Severity: Medium]
Does this check properly guard exact-offset allocations if offset is 0?
If a caller requests an allocation exactly at offset 0, start will be 0, which evaluates to false for the 'start > 0' condition.
This bypasses the single-range enforcement. If the first range is busy, the code could erroneously fall back and iterate over subsequent ranges, potentially returning an allocation at an arbitrary physical offset.
Quoted 3 lines
mm/cma.c +0
-0if (!cma || !cma->count)return page;
[ ... ]
mm/cma.c struct page *cma_alloc(struct cma *cma, unsigned long count, · line 999
Quoted 13 lines
mm/cma.c +13
-0+/** +* cma_alloc_at() - allocate pages from contiguous area at fixed offset +* @cma: Contiguous memory region for which the allocation is performed. +* @offset: Index of the first page to allocate. +* @count: Requested number of pages (in PAGE_SIZE order). +* @no_warn: Avoid printing message about failed allocation. +* +* This function allocates a part of the contiguous memory on a specific +* contiguous memory area. +*/ +struct page *cma_alloc_at (struct cma *cma,unsigned long offset, +unsigned long count,bool no_warn) +{
[Severity: Medium]
Does this API need to validate that the requested offset is aligned with the CMA block size?
CMA allocates memory in chunks of (1 << cma->order_per_bit) pages. The offset is passed in pages without validation. If properly scaled to bits later, an unaligned offset would be silently truncated, allocating a block at a rounded-down physical address instead of the exact requested offset.
Quoted 9 lines
mm/cma.c +9
-0+struct page *page; + + page =cma_alloc_at_frozen (cma, offset, count, no_warn); +if (page) +set_pages_refcounted (page, count); + +return page; +} +EXPORT_SYMBOL_GPL (cma_alloc_at);
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
Re: [PATCH v6 07/12] mm/cma: Introduce cma_alloc_at() API
In reply to Thierry RedingQuoted 15 lines · Thierry Reding
From: Thierry Reding <[email protected]>
This API can be used to allocate a number of CMA pages starting at a fixed offset. This is useful, for example, if the CMA area is used as backing storage for a nested allocator that has stricter requirements than CMA itself.
In order to reuse most of the existing code, the
cma_range_alloc()function is enhanced to take as inputs a range of pages to look for a free region. If this range encompasses the entire CMA range, the behavior is as before, but the range can also be specified to match the offset and size passed in fromcma_alloc_at(), in which case that is the range that will be allocated (or allocation will fail if the range is not available).
Quoted 2 lines
Suggested-by Marek Szyprowski <[email protected]>Signed-off-by Thierry Reding <[email protected]>
Quoted 318 lines
---
Changes in v6:
- refactorcma_range_alloc()so it can be reused for_at()code paths--- include/linux/cma.h | 4 +++ include/trace/events/cma.h | 77 ++++++++++++++++++++++++++++++++++++++-- mm/cma.c | 88 +++++++++++++++++++++++++++++++++++----------- 3 files changed, 146 insertions(+), 23 deletions(-)include/linux/cma.h +4
-0@@ -49,11 +49,15 @@ extern int cma_init_reserved_mem(phys_addr_t base, phys_addr_t size, struct cma **res_cma);extern struct page *cma_alloc (struct cma *cma,unsigned long count,unsigned int align,bool no_warn); +extern struct page *cma_alloc_at (struct cma *cma,unsigned long offset, +unsigned long count,bool no_warn);extern bool cma_release (struct cma *cma,const struct page *pages,unsigned long count);struct page *cma_alloc_frozen (struct cma *cma,unsigned long count,unsigned int align,bool no_warn);struct page *cma_alloc_frozen_compound (struct cma *cma,unsigned int order); +struct page *cma_alloc_at_frozen (struct cma *cma,unsigned long offset, +unsigned long count,bool no_warn);bool cma_release_frozen (struct cma *cma,const struct page *pages,unsigned long count);include/trace/events/cma.h +74
-3@@ -38,13 +38,17 @@ TRACE_EVENT(cma_release, TRACE_EVENT(cma_alloc_start, - TP_PROTO(const char *name, unsigned long request_count, unsigned long available_count, + TP_PROTO(const char *name, unsigned long start, unsigned long end, + unsigned long request_count, unsigned long available_count, unsigned long total_count, unsigned int align), - TP_ARGS(name, request_count, available_count, total_count, align), + TP_ARGS(name, start, end, request_count, available_count, total_count, + align), TP_STRUCT__entry( __string(name, name) + __field(unsigned long, start) + __field(unsigned long, end) __field(unsigned long, request_count) __field(unsigned long, available_count) __field(unsigned long, total_count)@@ -53,14 +57,18 @@ TRACE_EVENT(cma_alloc_start,TP_fast_assign ( __assign_str(name); + __entry->start = start; + __entry->end = end; __entry->request_count = request_count; __entry->available_count = available_count; __entry->total_count = total_count; __entry->align = align; ), - TP_printk("name=%s request_count=%lu available_count=%lu total_count=%lu align=%u", + TP_printk("name=%s start=%lu end=%lu request_count=%lu available_count=%lu total_count=%lu align=%u", __get_str(name), + __entry->start, + __entry->end, __entry->request_count, __entry->available_count, __entry->total_count,@@ -132,6 +140,69 @@ TRACE_EVENT(cma_alloc_busy_retry, __entry->align) ); +TRACE_EVENT (cma_alloc_at_start, + + TP_PROTO(const char *name, unsigned long pfn, + unsigned long request_count, unsigned long available_count, + unsigned long total_count), + +TP_ARGS (name, pfn, request_count, available_count, total_count), + +TP_STRUCT__entry ( + __string(name, name) + __field(unsigned long, pfn) + __field(unsigned long, request_count) + __field(unsigned long, available_count) + __field(unsigned long, total_count) + ), + +TP_fast_assign ( + __assign_str(name); + __entry->pfn = pfn; + __entry->request_count = request_count; + __entry->available_count = available_count; + __entry->total_count = total_count; + ), + +TP_printk ("name=%s pfn=%lx, request_count=%lu available_count=%lu total_count=%lu" , +__get_str (name), + __entry->pfn, + __entry->request_count, + __entry->available_count, + __entry->total_count) +); + +TRACE_EVENT (cma_alloc_at_finish, + + TP_PROTO(const char *name, unsigned long pfn, const struct page *page, + unsigned long count, int errorno), + +TP_ARGS (name, pfn, page, count, errorno), + +TP_STRUCT__entry ( + __string(name, name) + __field(unsigned long, pfn) + __field(const struct page *, page) + __field(unsigned long, count) +__field (int, errorno) + ), + +TP_fast_assign ( + __assign_str(name); + __entry->pfn = pfn; + __entry->page = page; + __entry->count = count; + __entry->errorno = errorno; + ), + +TP_printk ("name=%s pfn=0x%lx page=%p count=%lu errorno=%d" , +__get_str (name), + __entry->pfn, + __entry->page, + __entry->count, + __entry->errorno) +); +#endif /* _TRACE_CMA_H */ /* This part must be outside protection */ mm/cma.c +61
-20@@ -783,25 +783,32 @@ static void cma_debug_show_areas(struct cma *cma)spin_unlock_irq (&cma->lock); } +/* +* Searches the CMA memrange, from @start to @end, for a free region of +* @count bits. If @end is less or equal to @start, will search the entire +* memrange. +*/ static int cma_range_alloc (struct cma *cma,struct cma_memrange *cmr, -unsigned long count,unsigned int align, -struct page **pagep,gfp_t gfp) +unsigned long start,unsigned long end, +unsigned long count,unsigned int align, +struct page **pagep,gfp_t gfp) {unsigned long bitmap_maxno, bitmap_no, bitmap_count; -unsigned long start, pfn, mask, offset; -int ret = -EBUSY ; +unsigned long pfn, mask, offset;struct page *page =NULL ; +int ret = -EBUSY ; mask =cma_bitmap_aligned_mask (cma, align); offset =cma_bitmap_aligned_offset (cma, cmr, align); - bitmap_maxno =cma_bitmap_maxno (cma, cmr); + bitmap_maxno = (end > start) ? end :cma_bitmap_maxno (cma, cmr); bitmap_count =cma_bitmap_pages_to_bits (cma, count);if (bitmap_count > bitmap_maxno) goto out; -for (start =0 ; ; start = bitmap_no + mask +1 ) { +while (true) {spin_lock_irq (&cma->lock); +/* * If the request is larger than the available number * of pages, stop right away. @@ -810,6 +817,7 @@ static int cma_range_alloc(struct cma *cma, struct cma_memrange *cmr,spin_unlock_irq (&cma->lock);break ; } + bitmap_no =bitmap_find_next_zero_area_off (cmr->bitmap, bitmap_maxno, start, bitmap_count, mask, offset);@@ -835,10 +843,11 @@ static int cma_range_alloc(struct cma *cma, struct cma_memrange *cmr,bitmap_set (cmr->bitmap, bitmap_no, bitmap_count); cma->available_count -= count; +/* -* It's safe to drop the lock here. We've marked this region for -* our exclusive use. If the migration fails we will take the -* lock again and unmark it. +* It's safe to drop the lock here. We've marked this region +* for our exclusive use. If the migration fails we will take +* the lock again and unmark it. */ spin_unlock_irq (&cma->lock);@@ -856,37 +865,45 @@ static int cma_range_alloc(struct cma *cma, struct cma_memrange *cmr, __func__, pfn, page);trace_cma_alloc_busy_retry (cma->name, pfn, page, count, align); + start = bitmap_no + mask +1 ; } + out:if (!ret) *pagep = page; +return ret; } -static struct page *__cma_alloc_frozen (struct cma *cma, -unsigned long count,unsigned int align,gfp_t gfp) +static struct page *__cma_alloc_frozen (struct cma *cma,unsigned long start, +unsigned long end,unsigned long count, +unsigned int align,gfp_t gfp) {struct page *page =NULL ;int ret = -ENOMEM , r;unsigned long i; -const char *name = cma ? cma->name :NULL ; + +/* cma_alloc_at() and friends will only work with single-range CMA */ +if (WARN_ON_ONCE (start >0 && cma->nranges !=1 )) +return page;if (!cma || !cma->count)return page; -pr_debug ("%s(cma %p, name: %s, count %lu, align %d)\n" , __func__, - (void *)cma, cma->name, count, align); +pr_debug ("%s(cma %p, name: %s, start %lu, end %lu, count %lu, align %d)\n" , + __func__, (void *)cma, cma->name, start, end, count, align);if (!count)return page; -trace_cma_alloc_start (name, count, cma->available_count, cma->count, align); +trace_cma_alloc_start (cma->name, start, end, count, + cma->available_count, cma->count, align);for (r =0 ; r < cma->nranges; r++) { page =NULL ; - ret =cma_range_alloc (cma, &cma->ranges[r], count, align, - &page, gfp); + ret =cma_range_alloc (cma, &cma->ranges[r], start, end, + count, align, &page, gfp);if (ret != -EBUSY || page)break ; }@@ -908,7 +925,7 @@ static struct page *__cma_alloc_frozen(struct cma *cma, }pr_debug ("%s(): returned %p\n" , __func__, page); -trace_cma_alloc_finish (name, page ?page_to_pfn (page) :0 , +trace_cma_alloc_finish (cma->name, page ?page_to_pfn (page) :0 , page, count, align, ret);if (page) {count_vm_event (CMA_ALLOC_SUCCESS );@@ -926,14 +943,22 @@ struct page *cma_alloc_frozen(struct cma *cma, unsigned long count, {gfp_t gfp =GFP_KERNEL | (no_warn ? __GFP_NOWARN :0 ); -return __cma_alloc_frozen (cma, count, align, gfp); +return __cma_alloc_frozen (cma,0 ,0 , count, align, gfp); }struct page *cma_alloc_frozen_compound (struct cma *cma,unsigned int order) {gfp_t gfp =GFP_KERNEL | __GFP_COMP | __GFP_NOWARN; -return __cma_alloc_frozen (cma,1 << order, order, gfp); +return __cma_alloc_frozen (cma,0 ,0 ,1 << order, order, gfp); +} + +struct page *cma_alloc_at_frozen (struct cma *cma,unsigned long offset, +unsigned long count,bool no_warn) +{ +gfp_t gfp =GFP_KERNEL | (no_warn ? __GFP_NOWARN :0 ); + +return __cma_alloc_frozen (cma, offset, offset + count, count,0 , gfp); }/** @@ -959,6 +984,29 @@ struct page *cma_alloc(struct cma *cma, unsigned long count, }EXPORT_SYMBOL_GPL (cma_alloc); +/** +* cma_alloc_at() - allocate pages from contiguous area at fixed offset +* @cma: Contiguous memory region for which the allocation is performed. +* @offset: Index of the first page to allocate. +* @count: Requested number of pages (in PAGE_SIZE order). +* @no_warn: Avoid printing message about failed allocation. +* +* This function allocates a part of the contiguous memory on a specific +* contiguous memory area. +*/ +struct page *cma_alloc_at (struct cma *cma,unsigned long offset, +unsigned long count,bool no_warn) +{ +struct page *page; + + page =cma_alloc_at_frozen (cma, offset, count, no_warn);
mm/cma.c struct page *cma_alloc(struct cma *cma, unsigned long count, · line 1012
Quoted 10 lines
mm/cma.c +7
-0+if (page) +set_pages_refcounted (page, count); + +return page; +} +EXPORT_SYMBOL_GPL (cma_alloc_at); +static struct cma_memrange *find_cma_memrange (struct cma *cma,const struct page *pages,unsigned long count) {
Best regards
Signature · 2 lines
Marek Szyprowski, PhD Samsung R&D Institute Poland
Thierry Reding
maintainerPATCH v6 8/12 dma-buf: heaps: Add debugfs support
In reply to Thierry RedingFrom: Thierry Reding <[email protected]>
Add a callback to struct dma_heap_ops that heap providers can implement to show information about the state of the heap in debugfs. A top-level directory named "dma_heap" is created in debugfs and individual files will be named after the heaps.
---
Changes in v5:
- fix failure handling during debugfs root directory creation
- add more cleanup to the newly introduced dma_heap_exit()
--- drivers/dma-buf/dma-heap.c | 52 ++++++++++++++++++++++++++++++++++++++++++++++ include/linux/dma-heap.h | 2 ++ 2 files changed, 54 insertions(+)
drivers/dma-buf/dma-heap.c +52 -0
@@ -7,6 +7,7 @@*/ #include <linux/cdev.h> +#include <linux/debugfs.h> #include <linux/device.h> #include <linux/dma-buf.h> #include <linux/dma-heap.h>
@@ -225,6 +226,40 @@ const char *dma_heap_get_name(struct dma_heap *heap) }EXPORT_SYMBOL_NS_GPL (dma_heap_get_name,"DMA_BUF_HEAP" ); +#ifdef CONFIG_DEBUG_FS +static int dma_heap_debug_show (struct seq_file *s,void *unused) +{ +struct dma_heap *heap = s->private; +int err =0 ; + +if (heap->ops && heap->ops->show) + err = heap->ops->show (s, heap); + +return err; +} +DEFINE_SHOW_ATTRIBUTE (dma_heap_debug); + +static struct dentry *dma_heap_debugfs_dir; + +static void dma_heap_init_debugfs (void ) +{ + dma_heap_debugfs_dir =debugfs_create_dir ("dma_heap" ,NULL ); +} + +static void dma_heap_exit_debugfs (void ) +{ +debugfs_remove_recursive (dma_heap_debugfs_dir); +} +#else +static void dma_heap_init_debugfs (void ) +{ +} + +static void dma_heap_exit_debugfs (void ) +{ +} +#endif +/** * dma_heap_add - adds a heap to dmabuf heaps * @exp_info: information needed to register this heap
@@ -299,6 +334,13 @@ struct dma_heap *dma_heap_add(const struct dma_heap_export_info *exp_info)/* Add heap to the list */ list_add (&heap->list, &heap_list); + +#ifdef CONFIG_DEBUG_FS +if (heap->ops && heap->ops->show) +debugfs_create_file (heap->name,0444 , dma_heap_debugfs_dir, + heap, &dma_heap_debug_fops); +#endif +mutex_unlock (&heap_list_lock);return heap;
@@ -335,6 +377,16 @@ static int dma_heap_init(void) } dma_heap_class->devnode = dma_heap_devnode; +dma_heap_init_debugfs (); +return 0 ; }subsys_initcall (dma_heap_init); + +static void __exit dma_heap_exit(void) +{ +dma_heap_exit_debugfs (); +class_destroy (dma_heap_class); +unregister_chrdev_region (dma_heap_devt,NUM_HEAP_MINORS ); +} +__exitcall (dma_heap_exit);
include/linux/dma-heap.h +2 -0
@@ -12,6 +12,7 @@#include <linux/types.h> struct dma_heap ; +struct seq_file ;/** * struct dma_heap_ops - ops to operate on a given heap
@@ -24,6 +25,7 @@ struct dma_heap_ops {unsigned long len, u32 fd_flags, u64 heap_flags); +int (*show)(struct seq_file *s,struct dma_heap *heap); };/**
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v6 08/12] dma-buf: heaps: Add debugfs support
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
New issues:
- [Medium] Incomplete resource cleanup in the newly added dma_heap_exit() leaves dynamically allocated heaps, character devices, and sysfs devices active but orphaned.
Pre-existing issues:
- [High] Race condition in dma_heap_add error path leads to a critical Use-After-Free of struct dma_heap due to premature device exposure. --
commit e23fa30f3769a236faddd443565a8ccf6a9af125
Author: Thierry Reding <[email protected]>
dma-buf: heaps: Add debugfs support
This commit adds a callback to struct dma_heap_ops to show heap state in debugfs. It creates a top-level dma_heap directory where individual heap files are registered. A new dma_heap_exit() function is also introduced to clean up the class and debugfs directory on module exit.
Quoted 4 lines
drivers/dma-buf/dma-heap.c +0
-0
[ ... ]
Quoted 4 lines
drivers/dma-buf/dma-heap.c +0
-0@@ -299,6 +334,13 @@ struct dma_heap *dma_heap_add(const struct dma_heap_export_info *exp_info)/* Add heap to the list */ list_add (&heap->list, &heap_list);
drivers/dma-buf/dma-heap.c struct dma_heap *dma_heap_add(const struct dma_heap_export_info *exp_info) · line 346
Quoted 10 lines
drivers/dma-buf/dma-heap.c +7
-0+ +#ifdef CONFIG_DEBUG_FS +if (heap->ops && heap->ops->show) +debugfs_create_file (heap->name,0444 , dma_heap_debugfs_dir, + heap, &dma_heap_debug_fops); +#endif +mutex_unlock (&heap_list_lock);return heap;
[Severity: High]
This isn't a bug introduced by this patch, but is it possible for a concurrent userspace process to trigger a use-after-free during the error path of dma_heap_add()?
Earlier in dma_heap_add(), the character device is exposed to userspace before the name uniqueness check is performed:
ret = cdev_add(&heap->heap_cdev, heap->heap_devt, 1);
...
dev_ret = device_create(dma_heap_class, ...);
...
/* check the name is unique */
list_for_each_entry(h, &heap_list, list) {
if (!strcmp(h->name, exp_info->name)) {
...
goto err3;
}
}If another driver attempts to register a heap with a duplicate name, could a userspace process open the device before the uniqueness check fails? This would store the heap pointer in the open file descriptor. When the uniqueness check then fails, the error path executes kfree(heap), leaving the open file descriptor pointing to freed memory.
[ ... ]
Quoted 4 lines
drivers/dma-buf/dma-heap.c +0
-0@@ -335,6 +377,16 @@ static int dma_heap_init(void) } dma_heap_class->devnode = dma_heap_devnode;
drivers/dma-buf/dma-heap.c static int dma_heap_init(void) · line 389
Quoted 10 lines
drivers/dma-buf/dma-heap.c +7
-0+dma_heap_init_debugfs (); +return 0 ; }subsys_initcall (dma_heap_init); + +static void __exit dma_heap_exit(void) +{ +dma_heap_exit_debugfs (); +class_destroy (dma_heap_class);
[Severity: Medium]
Does this successfully tear down the resources if there are dynamically allocated heaps still registered?
The dma_heap_exit() function destroys the sysfs class by calling class_destroy(), but it doesn't appear to iterate over heap_list to cleanly tear down the individual registered heaps.
Can this leave dangling references and lead to sysfs issues, since device_destroy() and cdev_del() are never called for any active heaps before the class is destroyed?
Quoted 3 lines
drivers/dma-buf/dma-heap.c +3
-0+unregister_chrdev_region (dma_heap_devt,NUM_HEAP_MINORS ); +} +__exitcall (dma_heap_exit);
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
A message that is not in the archive (sent off-list or not yet received): [email protected]
Re: [PATCH v6 08/12] dma-buf: heaps: Add debugfs support
Since AMDs mail servers blocked me from sending this out, here once more from my gmail account.
Regards,
Christian.
Quoted 136 lines · Christian König
Quoted 9 lines · Thierry Reding
From: Thierry Reding <[email protected]>
Add a callback to struct
dma_heap_opsthat heap providers can implement to show information about the state of the heap in debugfs. A top-level directory named "dma_heap" is created in debugfs and individual files will be named after the heaps.Reviewed-by Maxime Ripard <[email protected]>Signed-off-by Thierry Reding <[email protected]>One minimal nit pick below, with that taken care of Reviewed-by: Christian König <[email protected]>.
Quoted 106 lines
---
Changes in v5:
- fix failure handling during debugfs root directory creation
- add more cleanup to the newly introduceddma_heap_exit()--- drivers/dma-buf/dma-heap.c | 52 ++++++++++++++++++++++++++++++++++++++++++++++ include/linux/dma-heap.h | 2 ++ 2 files changed, 54 insertions(+)drivers/dma-buf/dma-heap.c +52
-0@@ -7,6 +7,7 @@*/ #include <linux/cdev.h> +#include <linux/debugfs.h> #include <linux/device.h> #include <linux/dma-buf.h> #include <linux/dma-heap.h> @@ -225,6 +226,40 @@ const char *dma_heap_get_name(struct dma_heap *heap) }EXPORT_SYMBOL_NS_GPL (dma_heap_get_name,"DMA_BUF_HEAP" ); +#ifdef CONFIG_DEBUG_FS +static int dma_heap_debug_show (struct seq_file *s,void *unused) +{ +struct dma_heap *heap = s->private; +int err =0 ; + +if (heap->ops && heap->ops->show) + err = heap->ops->show (s, heap); + +return err; +} +DEFINE_SHOW_ATTRIBUTE (dma_heap_debug); + +static struct dentry *dma_heap_debugfs_dir; + +static void dma_heap_init_debugfs (void ) +{ + dma_heap_debugfs_dir =debugfs_create_dir ("dma_heap" ,NULL ); +} + +static void dma_heap_exit_debugfs (void ) +{ +debugfs_remove_recursive (dma_heap_debugfs_dir); +} +#else +static void dma_heap_init_debugfs (void ) +{ +} + +static void dma_heap_exit_debugfs (void ) +{ +} +#endif +/** * dma_heap_add - adds a heap to dmabuf heaps * @exp_info: information needed to register this heap @@ -299,6 +334,13 @@ struct dma_heap *dma_heap_add(const struct dma_heap_export_info *exp_info)/* Add heap to the list */ list_add (&heap->list, &heap_list); + +#ifdef CONFIG_DEBUG_FS +if (heap->ops && heap->ops->show) +debugfs_create_file (heap->name,0444 , dma_heap_debugfs_dir, + heap, &dma_heap_debug_fops); +#endif +mutex_unlock (&heap_list_lock);return heap;@@ -335,6 +377,16 @@ static int dma_heap_init(void) } dma_heap_class->devnode = dma_heap_devnode; +dma_heap_init_debugfs (); +return 0 ; }subsys_initcall (dma_heap_init); + +static void __exit dma_heap_exit(void) +{ +dma_heap_exit_debugfs (); +class_destroy (dma_heap_class); +unregister_chrdev_region (dma_heap_devt,NUM_HEAP_MINORS ); +} +__exitcall (dma_heap_exit);include/linux/dma-heap.h +1
-0@@ -12,6 +12,7 @@#include <linux/types.h> struct dma_heap ; +struct seq_file ;/** * struct dma_heap_ops - ops to operate on a given heap include/linux/dma-heap.h struct dma_heap_ops { · line 28
Quoted 4 lines
include/linux/dma-heap.h +1
-0@@ -24,6 +25,7 @@ struct dma_heap_ops {unsigned long len, u32 fd_flags, u64 heap_flags); +int (*show)(struct seq_file *s,struct dma_heap *heap);I found it good coding practice for objects ops pointer tables to have the object the function works with as first parameter.
Absolutely not a must have, but just looks a little bit more consistent.
Regards,
Christian.Quoted 4 lines
include/linux/dma-heap.h +0
-0};/**
Thierry Reding
maintainerRe: [PATCH v6 08/12] dma-buf: heaps: Add debugfs support
Quoted 133 lines · Christian König
Since AMDs mail servers blocked me from sending this out, here once more from my gmail account.
Regards,
Christian.Quoted 127 lines · Christian König
Quoted 9 lines · Thierry Reding
From: Thierry Reding <[email protected]>
Add a callback to struct
dma_heap_opsthat heap providers can implement to show information about the state of the heap in debugfs. A top-level directory named "dma_heap" is created in debugfs and individual files will be named after the heaps.Reviewed-by Maxime Ripard <[email protected]>Signed-off-by Thierry Reding <[email protected]>One minimal nit pick below, with that taken care of Reviewed-by: Christian König <[email protected]>.
Quoted 106 lines
---
Changes in v5:
- fix failure handling during debugfs root directory creation
- add more cleanup to the newly introduceddma_heap_exit()--- drivers/dma-buf/dma-heap.c | 52 ++++++++++++++++++++++++++++++++++++++++++++++ include/linux/dma-heap.h | 2 ++ 2 files changed, 54 insertions(+)drivers/dma-buf/dma-heap.c +52
-0@@ -7,6 +7,7 @@*/ #include <linux/cdev.h> +#include <linux/debugfs.h> #include <linux/device.h> #include <linux/dma-buf.h> #include <linux/dma-heap.h> @@ -225,6 +226,40 @@ const char *dma_heap_get_name(struct dma_heap *heap) }EXPORT_SYMBOL_NS_GPL (dma_heap_get_name,"DMA_BUF_HEAP" ); +#ifdef CONFIG_DEBUG_FS +static int dma_heap_debug_show (struct seq_file *s,void *unused) +{ +struct dma_heap *heap = s->private; +int err =0 ; + +if (heap->ops && heap->ops->show) + err = heap->ops->show (s, heap); + +return err; +} +DEFINE_SHOW_ATTRIBUTE (dma_heap_debug); + +static struct dentry *dma_heap_debugfs_dir; + +static void dma_heap_init_debugfs (void ) +{ + dma_heap_debugfs_dir =debugfs_create_dir ("dma_heap" ,NULL ); +} + +static void dma_heap_exit_debugfs (void ) +{ +debugfs_remove_recursive (dma_heap_debugfs_dir); +} +#else +static void dma_heap_init_debugfs (void ) +{ +} + +static void dma_heap_exit_debugfs (void ) +{ +} +#endif +/** * dma_heap_add - adds a heap to dmabuf heaps * @exp_info: information needed to register this heap @@ -299,6 +334,13 @@ struct dma_heap *dma_heap_add(const struct dma_heap_export_info *exp_info)/* Add heap to the list */ list_add (&heap->list, &heap_list); + +#ifdef CONFIG_DEBUG_FS +if (heap->ops && heap->ops->show) +debugfs_create_file (heap->name,0444 , dma_heap_debugfs_dir, + heap, &dma_heap_debug_fops); +#endif +mutex_unlock (&heap_list_lock);return heap;@@ -335,6 +377,16 @@ static int dma_heap_init(void) } dma_heap_class->devnode = dma_heap_devnode; +dma_heap_init_debugfs (); +return 0 ; }subsys_initcall (dma_heap_init); + +static void __exit dma_heap_exit(void) +{ +dma_heap_exit_debugfs (); +class_destroy (dma_heap_class); +unregister_chrdev_region (dma_heap_devt,NUM_HEAP_MINORS ); +} +__exitcall (dma_heap_exit);include/linux/dma-heap.h +1
-0@@ -12,6 +12,7 @@#include <linux/types.h> struct dma_heap ; +struct seq_file ;/** * struct dma_heap_ops - ops to operate on a given heap include/linux/dma-heap.h struct dma_heap_ops { · line 28
Quoted 4 lines
include/linux/dma-heap.h +1
-0@@ -24,6 +25,7 @@ struct dma_heap_ops {unsigned long len, u32 fd_flags, u64 heap_flags); +int (*show)(struct seq_file *s,struct dma_heap *heap);I found it good coding practice for objects ops pointer tables to have the object the function works with as first parameter.
Absolutely not a must have, but just looks a little bit more consistent.
Agreed, I generally prefer that too. However, in this case I thought it more important to model this after how pretty much every debugfs file operation works, which is to take the seq_file as first parameter. It's the same order as for the main dma_heap_debug_show() entry point that this is called from, so it's consistent that way.
I guess an alternative way to think about it is that in this case the object that we're really working with is the seq_file and the dma_heap is what gets written to that seq_file.
Thierry
Thierry Reding
maintainerPATCH v6 9/12 dma-buf: heaps: Add support for Tegra VPR
In reply to Thierry RedingFrom: Thierry Reding <[email protected]>
NVIDIA Tegra SoCs commonly define a Video-Protection-Region, which is a region of memory dedicated to content-protected video decode and playback. This memory cannot be accessed by the CPU and only certain hardware devices have access to it.
Expose the VPR as a DMA heap so that applications and drivers can allocate buffers from this region for use-cases that require this kind of protected memory.
VPR has a few very critical peculiarities. First, it must be a single contiguous region of memory (there is a single pair of registers that set the base address and size of the region), which is configured by calling back into the secure monitor. The memory region also needs to quite large for some use-cases because it needs to fit multiple video frames (8K video should be supported), so VPR sizes of ~2 GiB are expected. However, some devices cannot afford to reserve this amount of memory for a particular use-case, and therefore the VPR must be resizable.
Unfortunately, resizing the VPR is slightly tricky because the GPU found on Tegra SoCs must be in reset during the VPR resize operation. This is currently implemented by freezing all userspace processes and calling invoking the GPU's freeze() implementation, resizing and the thawing the GPU and userspace processes. This is quite heavy-handed, so eventually it might be better to implement thawing/freezing in the GPU driver in such a way that they block accesses to the GPU so that the VPR resize operation can happen without suspending all userspace.
In order to balance the memory usage versus the amount of resizing that needs to happen, the VPR is divided into multiple chunks. Each chunk is implemented as a section of the CMA area that is completely allocated on first use to guarantee the contiguity of the VPR. Once all buffers from a chunk have been freed, the subsection is freed and the memory returned to the system.
The Tegra VPR driver is split into two pieces: one tiny part of the driver is always built-in and sets up the CMA area during early boot, whereas the second, larger, part provides the DMA heap implementation and can be built as a module. Note that tearing down VPR is tricky and usually not necessary, so it can currently not be unloaded.
---
Changes in v6:
- split code into a small core and the main chunk so the latter can be built as a module
Changes in v5:
- use newly introduced cma_alloc_at() and work with a single CMA area
- setup CMA early and initialize VPR later during boot
- remove some unused variables
- use kalloc_objs()
Changes in v4:
- address Sashiko and checkpatch comments
- fully remove from linear map while chunks are allocated
- improve error handling
- remove freezer support
Changes in v3:
- use set_memory_device() and set_memory_normal() helpers
- use kzalloc_obj() instead of kzalloc() with sizeof()
Changes in v2:
- cluster allocations to reduce the number of resize operations
- support cross-chunk allocation
--- drivers/dma-buf/heaps/Kconfig | 12 + drivers/dma-buf/heaps/Makefile | 10 + drivers/dma-buf/heaps/tegra-vpr-init.c | 133 ++++ drivers/dma-buf/heaps/tegra-vpr.c | 1210 ++++++++++++++++++++++++++++++++ drivers/dma-buf/heaps/tegra-vpr.h | 73 ++ include/trace/events/tegra_vpr.h | 57 ++ 6 files changed, 1495 insertions(+)
drivers/dma-buf/heaps/Kconfig +12 -0
@@ -20,3 +20,15 @@ config DMABUF_HEAPS_CMA Choose this option to enable dma-buf CMA heap. This heap is backed by the Contiguous Memory Allocator (CMA). If your system has these regions, you should say Y here. + +config DMABUF_HEAPS_TEGRA_VPR + tristate "NVIDIA Tegra Video-Protected-Region DMA-BUF Heap" + depends on DMABUF_HEAPS && DMA_CMA + help + Choose this option to enable Video-Protected-Region (VPR) support on + a range of NVIDIA Tegra devices. Access to VPR memory is limited to + a subset of hardware engines and specifically disallowed from the + CPU. The region can be fixed, in which case no linear mapping exists + for the memory, or it can be resizable on systems that want to reuse + the memory for other uses when content-protected video is not played + back.
drivers/dma-buf/heaps/Makefile +10 -0
@@ -1,3 +1,13 @@ # SPDX-License-Identifier: GPL-2.0 obj-$(CONFIG_DMABUF_HEAPS_SYSTEM) += system_heap.o obj-$(CONFIG_DMABUF_HEAPS_CMA) += cma_heap.o + +# +# The reserved-memory bits always need to be built-in so that the CMA +# initialization runs during early boot. The VPR driver itself can be +# built as a module. +# +ifneq ($(CONFIG_DMABUF_HEAPS_TEGRA_VPR),) +obj-y += tegra-vpr-init.o +obj-$(CONFIG_DMABUF_HEAPS_TEGRA_VPR) += tegra-vpr.o +endif
drivers/dma-buf/heaps/tegra-vpr-init.c new file +133 -0
133 lines not on this page · raw message
drivers/dma-buf/heaps/tegra-vpr.c new file +1210 -0
1,210 lines not on this page · raw message
drivers/dma-buf/heaps/tegra-vpr.h new file +73 -0
73 lines not on this page · raw message
include/trace/events/tegra_vpr.h new file +57 -0
57 lines not on this page · raw message
Signature · 1 line
2.55.0
[email protected]
AI reviewThank you for your contribution! Sashiko AI review found 15 potential issue(s) to consider: - [High] Calling `cma_init_reserved_mem` on a `no-map` region causes a boot-time kernel panic. - [High]…
Thank you for your contribution! Sashiko AI review found 15 potential issue(s) to consider:
- [High] Calling cma_init_reserved_mem on a no-map region causes a boot-time kernel panic.
- [High] Memory allocated with kvmalloc_array() is incorrectly freed with kfree().
- [High] Calling dma_map_sgtable() with an SG list containing a NULL page maps garbage physical addresses.
- [High] Direct invocation of system PM callbacks (pm_generic_freeze/thaw) bypasses the PM core.
- [High] 0-sized chunks generate an integer underflow that permanently breaks VPR buffer allocation.
- [High] Pointer arithmetic on struct page arrays across MAX_ORDER / memory sections causes panics on SPARSEMEM.
- [High] Direct map corruption when returning partially invalidated pages to the CMA allocator.
- [High] Integer overflow in allocation size allows a zero-sized allocation that permanently bricks the heap.
- [High] Shrinking VPR restores linear mapping before the hardware protection is removed, risking speculative SErrors.
- [Medium] Memory and reference leaks on the error path of tegra_vpr_add_heap().
- [Medium] Missing lock acquisition when traversing vpr->buffers list in tegra_vpr_debugfs_show_chunks.
- [Medium] Dereferencing dev->driver->pm without checking if dev->driver is valid.
- [Low] Off-by-one error in VPR end_page calculation permanently wastes the last page.
- [Low] Use of dynamically sized Variable Length Arrays (VLAs) via DECLARE_BITMAP.
- [Low] The commit message claims userspace processes are frozen during resize, but the code does not implement this. --
commit 08e43ed119b9e546aa530f96844c1805cc1597a2
Author: Thierry Reding <[email protected]>
Subject: dma-buf: heaps: Add support for Tegra VPR
This commit introduces DMA-BUF heap support for the NVIDIA Tegra Video Protection Region (VPR). It adds initialization for CMA memory during boot and a heap driver for dynamically allocating and resizing chunks of this protected memory.
Quoted 5 lines
Unfortunately, resizing the VPR is slightly tricky because the GPU found on Tegra SoCs must be in reset during the VPR resize operation. This is currently implemented by freezing all userspace processes and calling invoking the GPU's
freeze()implementation, resizing and the thawing the GPU and userspace processes. This is quite heavy-handed, so eventually
[Severity: Low]
The commit message states that userspace processes are frozen during resize, but this doesn't seem to be implemented in the code (perhaps removed in v4?). Could the commit message be updated to reflect the current behavior?
Quoted 4 lines
drivers/dma-buf/heaps/tegra-vpr-init.c new file +0
-0@@ -0,0 +1,133 @@
[ ... ]
Quoted 8 lines
drivers/dma-buf/heaps/tegra-vpr-init.c new file +8
-0+static int __init tegra_vpr_node_init (unsigned long offset, +struct reserved_mem *rmem) +{ +struct cma *cma; +int err; + +if (!IS_ALIGNED (rmem->base,SZ_1M )) { +pr_err ("%s: base is not aligned to 1 MiB\n" , rmem->name);
drivers/dma-buf/heaps/tegra-vpr-init.c line 35
Quoted 10 lines
drivers/dma-buf/heaps/tegra-vpr-init.c new file +10
-0+return -EINVAL ; + } + +if (!IS_ALIGNED (rmem->size,SZ_1M )) { +pr_err ("%s: size is not aligned to 1 MiB\n" , rmem->name); +return -EINVAL ; + } + + err =cma_init_reserved_mem (rmem->base, rmem->size,0 , rmem->name, + &cma);
[Severity: High]
Can this cause a panic during early boot if the firmware configures a fixed VPR using the no-map property? A no-map region is removed from the linear memory map (no struct page allocation), but cma_init_reserved_mem() is called unconditionally. When CMA later tries to return pages to the buddy allocator via pfn_to_page(), won't it access invalid pointers?
[ ... ]
drivers/dma-buf/heaps/tegra-vpr-init.c line 66
Quoted 3 lines
drivers/dma-buf/heaps/tegra-vpr-init.c new file +3
-0+static int tegra_vpr_device_init (struct reserved_mem *rmem,struct device *dev) +{ +const struct dev_pm_ops *pm = dev->driver->pm;
[Severity: Medium]
Is it safe to blindly dereference dev->driver here? If this is called on a device node without a bound driver, dev->driver would be NULL, causing a panic. Should we verify dev->driver is valid first?
Quoted 4 lines
drivers/dma-buf/heaps/tegra-vpr.c new file +0
-0@@ -0,0 +1,1210 @@
[ ... ]
Quoted 14 lines
drivers/dma-buf/heaps/tegra-vpr.c new file +14
-0+static int tegra_vpr_resize (struct tegra_vpr *vpr) +{ +struct tegra_vpr_device *node; +phys_addr_t base, size; +int err, status =0 ; + + err =tegra_vpr_get_extents (vpr, &base, &size); +if (err <0 ) { +pr_err ("%s(): failed to get VPR extents: %d\n" , __func__, err); +return err; + } + +list_for_each_entry (node, &vpr->devices, node) { + err =pm_generic_freeze (node->dev);
[ ... ]
drivers/dma-buf/heaps/tegra-vpr.c line 138
Quoted 2 lines
drivers/dma-buf/heaps/tegra-vpr.c new file +2
-0+list_for_each_entry_continue_reverse (node, &vpr->devices, node) { + err =pm_generic_thaw (node->dev);
[Severity: High]
Does calling pm_generic_freeze() and pm_generic_thaw() directly bypass the PM core's synchronization? Normally these are coordinated under device_lock. If a device's driver is concurrently unbinding, dev->driver might become NULL during the callback, which could lead to a kernel panic. Should this be coordinated with the PM core instead?
[ ... ]
drivers/dma-buf/heaps/tegra-vpr.c line 260
Quoted 5 lines
drivers/dma-buf/heaps/tegra-vpr.c new file +5
-0+static bool tegra_vpr_chunk_overlaps (struct tegra_vpr_chunk *chunk, +unsigned int start,unsigned int limit) +{ +unsigned int first = chunk->offset; +unsigned int last = chunk->offset + chunk->num_pages -1 ;
[Severity: High]
Could chunk->num_pages be 0 for trailing chunks if the total VPR size doesn't evenly divide into num_chunks?
Looking at tegra_vpr_setup_chunks():
size = min_t(size_t, size, max_size);
end = start + size - 1;If the remaining size is 0, this would cause chunk->num_pages to be 0, making the calculation underflow to UINT_MAX. This would cause the 0-sized chunk to falsely overlap all future allocations and break the VPR heap.
[ ... ]
drivers/dma-buf/heaps/tegra-vpr.c line 271
Quoted 4 lines
drivers/dma-buf/heaps/tegra-vpr.c new file +4
-0+static int tegra_vpr_activate_chunks (struct tegra_vpr *vpr, +struct tegra_vpr_buffer *buffer) +{ +DECLARE_BITMAP (dirty, vpr->num_chunks);
[Severity: Low]
Since vpr->num_chunks is evaluated at runtime, doesn't DECLARE_BITMAP create a Variable Length Array (VLA) on the stack? The kernel globally forbids VLAs and this will likely cause a build failure with -Werror=vla.
Quoted 11 lines
drivers/dma-buf/heaps/tegra-vpr.c new file +11
-0+unsigned int i, bottom, top; +int err =0 , ret; + +bitmap_zero (dirty, vpr->num_chunks); + +/* activate any inactive chunks that overlap this buffer */ +for_each_set_bit (i, buffer->chunks, vpr->num_chunks) { +struct tegra_vpr_chunk *chunk = &vpr->chunks[i]; + +if (chunk->active) +continue ;
drivers/dma-buf/heaps/tegra-vpr.c line 292
Quoted 10 lines
drivers/dma-buf/heaps/tegra-vpr.c new file +10
-0+ + err =tegra_vpr_chunk_alloc (chunk); +if (err <0 ) + goto deactivate; + + err =tegra_vpr_chunk_activate (chunk); +if (err <0 ) { +tegra_vpr_chunk_release (chunk); + goto deactivate; + }
[Severity: High]
If set_direct_map_invalid_noflush() fails partially, tegra_vpr_chunk_activate() returns an error, and the caller immediately invokes tegra_vpr_chunk_release(). Will this return partially invalidated pages back to the CMA allocator without restoring the linear mapping? Subsequent allocations of these pages could trigger direct map faults.
[ ... ]
drivers/dma-buf/heaps/tegra-vpr.c line 418
Quoted 7 lines
drivers/dma-buf/heaps/tegra-vpr.c new file +7
-0+static int tegra_vpr_find_free_region (struct tegra_vpr *vpr, +unsigned int num_pages, +unsigned long align) +{ +return tegra_vpr_find_free_region_in_range (vpr,0 , vpr->num_pages -1 , + num_pages, align); +}
[Severity: Low]
Is there an off-by-one error here? tegra_vpr_find_free_region_in_range() expects end_page as an exclusive upper bound, but passing vpr->num_pages - 1 means an allocation perfectly reaching the end of the region will be incorrectly rejected.
[ ... ]
Quoted 3 lines
drivers/dma-buf/heaps/tegra-vpr.c new file +3
-0+static struct tegra_vpr_buffer * +tegra_vpr_buffer_allocate (struct tegra_vpr *vpr,size_t size) +{
[ ... ]
drivers/dma-buf/heaps/tegra-vpr.c line 610
Quoted 10 lines
drivers/dma-buf/heaps/tegra-vpr.c new file +10
-0+ buffer->pages =kvmalloc_array (buffer->num_pages, +sizeof (*buffer->pages), +GFP_KERNEL ); +if (!buffer->pages) { + err = -ENOMEM ; + goto free; + } + +for (i =0 ; i < buffer->num_pages; i++) + buffer->pages[i] = &vpr->start_page[pageno + i];
[Severity: High]
Is it safe to perform direct pointer arithmetic on struct page arrays across potentially massive VPR regions? On platforms using the SPARSEMEM memory model without VMEMMAP, struct page objects are only contiguous within a single memory section. A 2 GiB VPR region crosses many section boundaries, so this arithmetic could point into unmapped memory and crash the kernel when accessed.
[ ... ]
Quoted 2 lines
drivers/dma-buf/heaps/tegra-vpr.c new file +2
-0+static void tegra_vpr_buffer_release (struct tegra_vpr_buffer *buffer) +{
[ ... ]
drivers/dma-buf/heaps/tegra-vpr.c line 641
Quoted 3 lines
drivers/dma-buf/heaps/tegra-vpr.c new file +3
-0+kfree (buffer->pages); +kfree (buffer); +}
[Severity: High]buffer->pages is allocated using kvmalloc_array(), which may fall back to vmalloc space. Shouldn't this be freed with kvfree()? Calling kfree() on a vmalloc'd pointer will cause a SLUB panic or memory corruption.
[ ... ]
Quoted 3 lines
drivers/dma-buf/heaps/tegra-vpr.c new file +3
-0+static int tegra_vpr_attach (struct dma_buf *buf, +struct dma_buf_attachment *attachment) +{
[ ... ]
drivers/dma-buf/heaps/tegra-vpr.c line 709
Quoted 10 lines
drivers/dma-buf/heaps/tegra-vpr.c new file +10
-0+ }else { +if (sg_alloc_table (&attach->sgt,1 ,GFP_KERNEL )) { + err = -ENOMEM ; + goto free; + } + +sg_set_page (attach->sgt.sgl,NULL , buffer->size,0 ); +sg_dma_address (attach->sgt.sgl) = buffer->start; +sg_dma_len (attach->sgt.sgl) = buffer->size; + }
[Severity: High]
For static VPR setups, the SG list is populated with a NULL page. When tegra_vpr_map_dma_buf() later calls dma_map_sgtable(), the IOMMU DMA mapping code relies on sg_phys(), which calculates page_to_phys(NULL) + offset. This usually results in physical address 0. The IOMMU will be programmed to map address 0 instead of the actual VPR hardware address, breaking DMA.
[ ... ]
drivers/dma-buf/heaps/tegra-vpr.c line 768
Quoted 5 lines
drivers/dma-buf/heaps/tegra-vpr.c new file +5
-0+static void tegra_vpr_recycle (struct tegra_vpr *vpr) +{ +DECLARE_BITMAP (dirty, vpr->num_chunks); +unsigned int i; +int err;
[Severity: Low]
Here is another DECLARE_BITMAP using vpr->num_chunks that creates a VLA.
[ ... ]
Quoted 1 line
drivers/dma-buf/heaps/tegra-vpr.c new file +1
-0+ err =tegra_vpr_chunk_deactivate (chunk);
[ ... ]
drivers/dma-buf/heaps/tegra-vpr.c
Quoted 2 lines
drivers/dma-buf/heaps/tegra-vpr.c new file +2
-0+if (!bitmap_empty (dirty, vpr->num_chunks)) { + err =tegra_vpr_resize (vpr);
[Severity: High]tegra_vpr_chunk_deactivate() is called before tegra_vpr_resize(). This restores the CPU's linear mapping to the memory while the hardware firewall is still active. Does this inverted ordering create a race window where speculative CPU accesses to the direct map could trigger a fatal bus fault / SError before the hardware firewall is shrunk?
[ ... ]
drivers/dma-buf/heaps/tegra-vpr.c line 902
Quoted 7 lines
drivers/dma-buf/heaps/tegra-vpr.c new file +7
-0+static struct dma_buf *tegra_vpr_allocate (struct dma_heap *heap, +unsigned long len,u32 fd_flags, +u64 heap_flags) +{ +struct tegra_vpr *vpr =dma_heap_get_drvdata (heap); +struct tegra_vpr_buffer *buffer, *entry; +size_t size =ALIGN (len, vpr->align);
[Severity: High]
Could ALIGN(len, vpr->align) overflow to 0 if an unprivileged user requests a massive len? A 0-sized allocation might succeed and eventually underflow vpr->last when it computes vpr->last = limit - 1 with limit = 0. This would permanently corrupt the heap tracking bounds and break future clustered allocations.
[ ... ]
Quoted 9 lines
drivers/dma-buf/heaps/tegra-vpr.c new file +9
-0+static void tegra_vpr_debugfs_show_chunks (struct tegra_vpr *vpr, +struct seq_file *s) +{ +struct tegra_vpr_buffer *buffer; +unsigned int i; +char buf[16 ]; + +for (i =0 ; i < vpr->num_chunks; i++) { +const struct tegra_vpr_chunk *chunk = &vpr->chunks[i];
drivers/dma-buf/heaps/tegra-vpr.c line 985
Quoted 10 lines
drivers/dma-buf/heaps/tegra-vpr.c new file +10
-0+ +string_get_size (chunk->size,1 ,STRING_UNITS_2 , buf, +sizeof (buf)); +seq_printf (s," %pap-%pap (%s) (%s, %u buffers)\n" , + &chunk->start, &chunk->limit, buf, + chunk->active ?"active" :"inactive" , + chunk->num_buffers); + } + +list_for_each_entry (buffer, &vpr->buffers, list) {
[Severity: Medium]
This iterates over the vpr->buffers linked list without holding vpr->lock. If a user reads this debugfs file concurrently with heap allocations or frees, could this race with list mutations and cause use-after-free or list corruption panics?
[ ... ]
Quoted 3 lines
drivers/dma-buf/heaps/tegra-vpr.c new file +3
-0+static int tegra_vpr_add_heap (struct reserved_mem *rmem, +struct device_node *np) +{
[ ... ]
Quoted 1 line
drivers/dma-buf/heaps/tegra-vpr.c new file +1
-0+ vpr->dev_node =of_node_get (np);
[ ... ]
Quoted 7 lines
drivers/dma-buf/heaps/tegra-vpr.c new file +7
-0+if (vpr->resizable) + err =tegra_vpr_setup_chunks (vpr, rmem->name); +else + err =tegra_vpr_setup_static (vpr); + +if (err <0 ) + goto free;
[ ... ]
drivers/dma-buf/heaps/tegra-vpr.c line 1174
Quoted 5 lines
drivers/dma-buf/heaps/tegra-vpr.c new file +5
-0+free: +bitmap_free (vpr->bitmap); +kfree (vpr); +return err; +}
[Severity: Medium]
There appear to be multiple leaks in the error paths here. If tegra_vpr_setup_chunks() fails, it jumps to free without calling of_node_put(vpr->dev_node). Additionally, if dma_heap_add() fails, the cleanup path calls tegra_vpr_free_chunks(), which correctly frees the chunks array but forgets to free the vpr->active bitmap allocated during setup.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
Rob Herring
maintainerQuoted 1,383 lines · Thierry Reding
From: Thierry Reding <[email protected]>
NVIDIA Tegra SoCs commonly define a Video-Protection-Region, which is a region of memory dedicated to content-protected video decode and playback. This memory cannot be accessed by the CPU and only certain hardware devices have access to it.
Expose the VPR as a DMA heap so that applications and drivers can allocate buffers from this region for use-cases that require this kind of protected memory.
VPR has a few very critical peculiarities. First, it must be a single contiguous region of memory (there is a single pair of registers that set the base address and size of the region), which is configured by calling back into the secure monitor. The memory region also needs to quite large for some use-cases because it needs to fit multiple video frames (8K video should be supported), so VPR sizes of ~2 GiB are expected. However, some devices cannot afford to reserve this amount of memory for a particular use-case, and therefore the VPR must be resizable.
Unfortunately, resizing the VPR is slightly tricky because the GPU found on Tegra SoCs must be in reset during the VPR resize operation. This is currently implemented by freezing all userspace processes and calling invoking the GPU's
freeze()implementation, resizing and the thawing the GPU and userspace processes. This is quite heavy-handed, so eventually it might be better to implement thawing/freezing in the GPU driver in such a way that they block accesses to the GPU so that the VPR resize operation can happen without suspending all userspace.In order to balance the memory usage versus the amount of resizing that needs to happen, the VPR is divided into multiple chunks. Each chunk is implemented as a section of the CMA area that is completely allocated on first use to guarantee the contiguity of the VPR. Once all buffers from a chunk have been freed, the subsection is freed and the memory returned to the system.
The Tegra VPR driver is split into two pieces: one tiny part of the driver is always built-in and sets up the CMA area during early boot, whereas the second, larger, part provides the DMA heap implementation and can be built as a module. Note that tearing down VPR is tricky and usually not necessary, so it can currently not be unloaded.
Signed-off-by Thierry Reding <[email protected]>---
Changes in v6:
- split code into a small core and the main chunk so the latter can be built as a moduleChanges in v5:
- use newly introducedcma_alloc_at()and work with a single CMA area
- setup CMA early and initialize VPR later during boot
- remove some unused variables
- usekalloc_objs()Changes in v4:
- address Sashiko and checkpatch comments
- fully remove from linear map while chunks are allocated
- improve error handling
- remove freezer supportChanges in v3:
- useset_memory_device()andset_memory_normal()helpers
- usekzalloc_obj()instead ofkzalloc()withsizeof()Changes in v2:
- cluster allocations to reduce the number of resize operations
- support cross-chunk allocation--- drivers/dma-buf/heaps/Kconfig | 12 + drivers/dma-buf/heaps/Makefile | 10 + drivers/dma-buf/heaps/tegra-vpr-init.c | 133 ++++ drivers/dma-buf/heaps/tegra-vpr.c | 1210 ++++++++++++++++++++++++++++++++ drivers/dma-buf/heaps/tegra-vpr.h | 73 ++ include/trace/events/tegra_vpr.h | 57 ++ 6 files changed, 1495 insertions(+)drivers/dma-buf/heaps/Kconfig +12
-0@@ -20,3 +20,15 @@ config DMABUF_HEAPS_CMA Choose this option to enable dma-buf CMA heap. This heap is backed by the Contiguous Memory Allocator (CMA). If your system has these regions, you should say Y here. + +config DMABUF_HEAPS_TEGRA_VPR + tristate "NVIDIA Tegra Video-Protected-Region DMA-BUF Heap" + depends on DMABUF_HEAPS && DMA_CMA + help + Choose this option to enable Video-Protected-Region (VPR) support on + a range of NVIDIA Tegra devices. Access to VPR memory is limited to + a subset of hardware engines and specifically disallowed from the + CPU. The region can be fixed, in which case no linear mapping exists + for the memory, or it can be resizable on systems that want to reuse + the memory for other uses when content-protected video is not played + back.drivers/dma-buf/heaps/Makefile +10
-0@@ -1,3 +1,13 @@ # SPDX-License-Identifier: GPL-2.0 obj-$(CONFIG_DMABUF_HEAPS_SYSTEM) += system_heap.o obj-$(CONFIG_DMABUF_HEAPS_CMA) += cma_heap.o + +# +# The reserved-memory bits always need to be built-in so that the CMA +# initialization runs during early boot. The VPR driver itself can be +# built as a module. +# +ifneq ($(CONFIG_DMABUF_HEAPS_TEGRA_VPR),) +obj-y += tegra-vpr-init.o +obj-$(CONFIG_DMABUF_HEAPS_TEGRA_VPR) += tegra-vpr.o +endifdrivers/dma-buf/heaps/tegra-vpr-init.c new file +133
-0@@ -0,0 +1,133 @@ +// SPDX-License-Identifier: GPL-2.0 +/* +* DMA-BUF restricted heap exporter for NVIDIA Video-Protection-Region (VPR) +* +* Copyright (C) 2024-2026 NVIDIA Corporation +*/ + +#define pr_fmt (fmt) "tegra-vpr: " fmt + +#include "tegra-vpr.h" + +#include <linux/cma.h> +#include <linux/of_reserved_mem.h> + +static DEFINE_MUTEX (vpr_lock); +static LIST_HEAD_GUARDED(vpr_list, vpr_lock); + +static int __init tegra_vpr_node_init (unsigned long offset, +struct reserved_mem *rmem) +{ +struct cma *cma; +int err; + +if (!IS_ALIGNED (rmem->base,SZ_1M )) { +pr_err ("%s: base is not aligned to 1 MiB\n" , rmem->name); +return -EINVAL ; + } + +if (!IS_ALIGNED (rmem->size,SZ_1M )) { +pr_err ("%s: size is not aligned to 1 MiB\n" , rmem->name); +return -EINVAL ; + } + + err =cma_init_reserved_mem (rmem->base, rmem->size,0 , rmem->name, + &cma); +if (err <0 ) { +pr_err ("%s: failed to initialize CMA: %d\n" , __func__, err); +return err; + } + + rmem->priv = cma; + +return 0 ; +} + +static struct tegra_vpr *tegra_vpr_lookup (struct cma *cma) +{ +struct tegra_vpr *vpr; + +mutex_lock (&vpr_lock); + +list_for_each_entry (vpr, &vpr_list, list) { +if (vpr->cma == cma) { +mutex_unlock (&vpr_lock); +return vpr; + } + } + +mutex_unlock (&vpr_lock); + +return ERR_PTR (-EPROBE_DEFER ); +} + +static int tegra_vpr_device_init (struct reserved_mem *rmem,struct device *dev) +{ +const struct dev_pm_ops *pm = dev->driver->pm; +struct tegra_vpr_device *node; +struct cma *cma = rmem->priv; +struct tegra_vpr *vpr; + + vpr =tegra_vpr_lookup (cma); +if (IS_ERR (vpr)) +return PTR_ERR (vpr); + +if (!pm || !pm->freeze || !pm->thaw) +return -EINVAL ; + + node =kzalloc_obj (*node,GFP_KERNEL ); +if (!node) +return -ENOMEM ; + +INIT_LIST_HEAD (&node->node); + node->dev = dev; + +mutex_lock (&vpr->lock); +list_add_tail (&node->node, &vpr->devices); +mutex_unlock (&vpr->lock); + +return 0 ; +} + +static void tegra_vpr_device_release (struct reserved_mem *rmem, +struct device *dev) +{ +struct tegra_vpr_device *node, *tmp; +struct cma *cma = rmem->priv; +struct tegra_vpr *vpr; + + vpr =tegra_vpr_lookup (cma); +if (IS_ERR (vpr)) { +dev_WARN (dev,"failed to find VPR for CMA '%s'\n" , +cma_get_name (cma)); +return ; + } + +mutex_lock (&vpr->lock); + +list_for_each_entry_safe (node, tmp, &vpr->devices, node) { +if (node->dev == dev) { +list_del (&node->node); +kfree (node); + } + } + +mutex_unlock (&vpr->lock); +} + +static const struct reserved_mem_ops tegra_vpr_rmem_ops = { + .node_init = tegra_vpr_node_init, + .device_init = tegra_vpr_device_init, + .device_release = tegra_vpr_device_release, +}; + +RESERVEDMEM_OF_DECLARE (tegra_vpr,"nvidia,tegra-video-protection-region" , + &tegra_vpr_rmem_ops); + +void tegra_vpr_add (struct tegra_vpr *vpr) +{ +mutex_lock (&vpr_lock); +list_add_tail (&vpr->list, &vpr_list); +mutex_unlock (&vpr_lock); +} +EXPORT_SYMBOL (tegra_vpr_add);drivers/dma-buf/heaps/tegra-vpr.c new file +1123
-0@@ -0,0 +1,1210 @@ +// SPDX-License-Identifier: GPL-2.0 +/* +* DMA-BUF restricted heap exporter for NVIDIA Video-Protection-Region (VPR) +* +* Copyright (C) 2024-2026 NVIDIA Corporation +*/ + +#define pr_fmt (fmt) "tegra-vpr: " fmt + +#include <linux/arm-smccc.h> +#include <linux/cma.h> +#include <linux/debugfs.h> +#include <linux/dma-buf.h> +#include <linux/dma-heap.h> +#include <linux/find.h> +#include <linux/memory.h> +#include <linux/of_reserved_mem.h> +#include <linux/platform_device.h> +#include <linux/pm_runtime.h> +#include <linux/reset.h> +#include <linux/set_memory.h> + +#include "tegra-vpr.h" + +MODULE_IMPORT_NS ("DMA_BUF_HEAP" ); +MODULE_IMPORT_NS ("DMA_BUF" ); + +#define CREATE_TRACE_POINTS +#include <trace/events/tegra_vpr.h> + +#define TEGRA_VPR_MAX_CHUNKS 64 + +struct tegra_vpr_buffer { +struct list_head attachments; +struct tegra_vpr *vpr; +struct list_head list; + +/** +* @lock: Protects concurrent access to the list of attachments. +*/ +struct mutex lock; + +struct page **pages; +pgoff_t num_pages; +phys_addr_t start; +phys_addr_t limit; +size_t size; +int pageno; +int order; + + DECLARE_BITMAP(chunks, TEGRA_VPR_MAX_CHUNKS); +}; + +struct tegra_vpr_attachment { +struct device *dev; +struct sg_table sgt; +struct list_head list; +}; + +#define ARM_SMCCC_TE_FUNC_PROGRAM_VPR 0x3 + +#define ARM_SMCCC_VENDOR_SIP_TE_PROGRAM_VPR_FUNC_ID \ + ARM_SMCCC_CALL_VAL(ARM_SMCCC_FAST_CALL, \ + ARM_SMCCC_SMC_32, \ + ARM_SMCCC_OWNER_SIP, \ + ARM_SMCCC_TE_FUNC_PROGRAM_VPR) + +static int tegra_vpr_set (phys_addr_t base,phys_addr_t size) +{ +struct arm_smccc_res res; + +arm_smccc_smc (ARM_SMCCC_VENDOR_SIP_TE_PROGRAM_VPR_FUNC_ID , base, size, +0 ,0 ,0 ,0 ,0 , &res); + +return res.a0; +} + +static int tegra_vpr_get_extents (struct tegra_vpr *vpr,phys_addr_t *base, +phys_addr_t *size) +{ +phys_addr_t start = ~0 , limit =0 ; +unsigned int i; + +for (i =0 ; i < vpr->num_chunks; i++) { +struct tegra_vpr_chunk *chunk = &vpr->chunks[i]; + +if (chunk->active) { +if (chunk->start < start) + start = chunk->start; + +if (chunk->limit > limit) + limit = chunk->limit; + } + } + +if (limit > start) { + *size = limit - start; + *base = start; + }else { + *base = *size =0 ; + } + +return 0 ; +} + +static int tegra_vpr_resize (struct tegra_vpr *vpr) +{ +struct tegra_vpr_device *node; +phys_addr_t base, size; +int err, status =0 ; + + err =tegra_vpr_get_extents (vpr, &base, &size); +if (err <0 ) { +pr_err ("%s(): failed to get VPR extents: %d\n" , __func__, err); +return err; + } + +list_for_each_entry (node, &vpr->devices, node) { + err =pm_generic_freeze (node->dev); +if (err <0 ) { +pr_err ("failed to freeze %s: %d\n" , +dev_name (node->dev), err); + status = err; + goto thaw; + } + } + +trace_tegra_vpr_set (base, size); + + err =tegra_vpr_set (base, size); +if (err <0 ) { +pr_err ("failed to secure VPR: %d\n" , err); + status = err; + } + +thaw: +list_for_each_entry_continue_reverse (node, &vpr->devices, node) { + err =pm_generic_thaw (node->dev); +if (err <0 ) { +pr_err ("failed to thaw %s: %d\n" , +dev_name (node->dev), err); +continue ; + } + } + +return status; +} + +static int tegra_vpr_chunk_init (struct tegra_vpr *vpr, +struct tegra_vpr_chunk *chunk, +phys_addr_t start,size_t size, +unsigned int order,const char *name) +{ + chunk->start = start; + chunk->limit = start + size; + chunk->size = size; + chunk->vpr = vpr; + + chunk->offset = (start - vpr->base) >>PAGE_SHIFT ; + chunk->num_pages = size >>PAGE_SHIFT ; + chunk->num_buffers =0 ; + +/* CMA area is not reserved yet */ + chunk->start_page =NULL ; + chunk->virt =0 ; + +return 0 ; +} + +static void tegra_vpr_chunk_free (struct tegra_vpr_chunk *chunk) +{ +} + +static inline bool tegra_vpr_chunk_is_last (const struct tegra_vpr_chunk *chunk) +{ +phys_addr_t limit = chunk->vpr->base + chunk->vpr->size; + +return chunk->limit == limit; +} + +static inline bool tegra_vpr_chunk_is_leaf (const struct tegra_vpr_chunk *chunk) +{ +const struct tegra_vpr_chunk *next = chunk +1 ; + +if (tegra_vpr_chunk_is_last (chunk)) +return true; + +return !next->active; +} + +static int tegra_vpr_chunk_alloc (struct tegra_vpr_chunk *chunk) +{ + chunk->start_page =cma_alloc_at (chunk->vpr->cma, chunk->offset, + chunk->num_pages, false); +if (!chunk->start_page) +return -ENOMEM ; + + chunk->virt = (unsigned long )page_to_virt (chunk->start_page); + +return 0 ; +} + +static int tegra_vpr_chunk_activate (struct tegra_vpr_chunk *chunk) +{ +int err; + +trace_tegra_vpr_chunk_activate (chunk->start, chunk->limit); + + err =set_direct_map_invalid_noflush (chunk->start_page, + chunk->num_pages); +if (err) +return err; + +flush_tlb_kernel_range (chunk->virt, chunk->virt + chunk->size); + chunk->invalid = false; + chunk->active = true; + +return 0 ; +} + +static int tegra_vpr_chunk_deactivate (struct tegra_vpr_chunk *chunk) +{ +int err; + +if (!chunk->active) +return 0 ; + +/* do not deactivate if there are buffers left in this chunk */ +if (WARN_ON (chunk->num_buffers >0 )) +return -EBUSY ; + +trace_tegra_vpr_chunk_deactivate (chunk->start, chunk->limit); + + err =set_direct_map_default_noflush (chunk->start_page, + chunk->num_pages); +if (err) +return err; + +flush_tlb_kernel_range (chunk->virt, chunk->virt + chunk->size); + chunk->invalid = false; + chunk->active = false; + +return 0 ; +} + +static void tegra_vpr_chunk_release (struct tegra_vpr_chunk *chunk) +{ +if (!WARN_ON (chunk->active || chunk->invalid)) { +cma_release (chunk->vpr->cma, chunk->start_page, + chunk->num_pages); + chunk->start_page =NULL ; + chunk->virt =0 ; + } +} + +static bool tegra_vpr_chunk_overlaps (struct tegra_vpr_chunk *chunk, +unsigned int start,unsigned int limit) +{ +unsigned int first = chunk->offset; +unsigned int last = chunk->offset + chunk->num_pages -1 ; + +if (last < start || first >= limit) +return false; + +return true; +} + +static int tegra_vpr_activate_chunks (struct tegra_vpr *vpr, +struct tegra_vpr_buffer *buffer) +{ +DECLARE_BITMAP (dirty, vpr->num_chunks); +unsigned int i, bottom, top; +int err =0 , ret; + +bitmap_zero (dirty, vpr->num_chunks); + +/* activate any inactive chunks that overlap this buffer */ +for_each_set_bit (i, buffer->chunks, vpr->num_chunks) { +struct tegra_vpr_chunk *chunk = &vpr->chunks[i]; + +if (chunk->active) +continue ; + + err =tegra_vpr_chunk_alloc (chunk); +if (err <0 ) + goto deactivate; + + err =tegra_vpr_chunk_activate (chunk); +if (err <0 ) { +tegra_vpr_chunk_release (chunk); + goto deactivate; + } + +set_bit (i, vpr->active); +set_bit (i, dirty); + } + +/* +* Activating chunks above may have created holes, but since the VPR +* can only ever be a single contiguous region, make sure to activate +* any missing chunks. +*/ +for_each_clear_bitrange (bottom, top, vpr->active, vpr->num_chunks) { +/* inactive chunks at the bottom or the top are harmless */ +if (bottom ==0 || top == vpr->num_chunks) +continue ; + +for (i = bottom; i < top; i++) { +struct tegra_vpr_chunk *chunk = &vpr->chunks[i]; + + err =tegra_vpr_chunk_alloc (chunk); +if (err <0 ) + goto deactivate; + + err =tegra_vpr_chunk_activate (chunk); +if (err <0 ) { +tegra_vpr_chunk_release (chunk); + goto deactivate; + } + +set_bit (i, vpr->active); +set_bit (i, dirty); + } + } + +/* if any chunks have been activated, VPR needs to be resized */ +if (!bitmap_empty (dirty, vpr->num_chunks)) { + err =tegra_vpr_resize (vpr); +if (err <0 ) { +pr_err ("failed to grow VPR: %d\n" , err); + goto deactivate; + } + } + +/* increment buffer count for each chunk */ +for_each_set_bit (i, buffer->chunks, vpr->num_chunks) + vpr->chunks[i].num_buffers++; + +return 0 ; + +deactivate: +/* deactivate any of the previously inactive chunks on failure */ +for_each_set_bit (i, dirty, vpr->num_chunks) { +struct tegra_vpr_chunk *chunk = &vpr->chunks[i]; + + ret =tegra_vpr_chunk_deactivate (chunk); +if (WARN_ON (ret <0 )) { +pr_err ("failed to deactivate chunk #%u: %d\n" , i, ret); + }else { +tegra_vpr_chunk_release (chunk); +clear_bit (i, vpr->active); + } + } + +return err; +} + +/* +* Retrieve the range of pages within the activate region of the VPR. +*/ +static bool tegra_vpr_get_active_range (struct tegra_vpr *vpr, +unsigned int *first, +unsigned int *last) +{ +unsigned long i, j; + + i =find_first_bit (vpr->active, vpr->num_chunks); +if (i >= vpr->num_chunks) +return false; + + j =find_last_bit (vpr->active, vpr->num_chunks); +if (j >= vpr->num_chunks) +return false; + + *first = vpr->chunks[i].offset; + *last = vpr->chunks[j].offset + vpr->chunks[j].num_pages; + +return true; +} + +/* +* Try to find and allocate a free region within a specific page range. +* Returns the page number if successful, -ENOSPC otherwise. +* +* This function mimics bitmap_find_free_region() but restricts the search +* to a specific range to enable allocation within individual chunks. +*/ +static int tegra_vpr_find_free_region_in_range (struct tegra_vpr *vpr, +unsigned int start_page, +unsigned int end_page, +unsigned int num_pages, +unsigned int align) +{ +unsigned int pos, next =ALIGN (start_page, align); + +/* Scan through aligned positions, trying to allocate at each one */ +for (pos = next; pos + num_pages <= end_page; pos = next) { + next =find_next_bit (vpr->bitmap, pos + num_pages, pos); + +if (next >= pos + num_pages) { +bitmap_set (vpr->bitmap, pos, num_pages); +return pos; + } + + next =find_next_zero_bit (vpr->bitmap, vpr->num_pages, next); + next =ALIGN (next, align); + } + +return -ENOSPC ; +} + +static int tegra_vpr_find_free_region (struct tegra_vpr *vpr, +unsigned int num_pages, +unsigned long align) +{ +return tegra_vpr_find_free_region_in_range (vpr,0 , vpr->num_pages -1 , + num_pages, align); +} + +static int tegra_vpr_find_free_region_clustered (struct tegra_vpr *vpr, +unsigned int num_pages, +unsigned int align) +{ +unsigned int target, first, last; +int pageno; + +/* +* If there are no allocations, abort the clustered allocation scheme +* and use the generic allocation scheme instead. +*/ +if (vpr->first > vpr->last) +return -ENOSPC ; + +/* +* First, try to allocate within the currently allocated region. This +* keeps allocations tightly packed and minimizes the VPR size needed. +*/ + pageno =tegra_vpr_find_free_region_in_range (vpr, vpr->first, + vpr->last +1 , num_pages, + align); +if (pageno >=0 ) +return pageno; + +/* +* If not enough free space exists within the currently allocated +* region, check to see if the allocation fits anywhere within the +* active region, avoiding the need to resize the VPR. +*/ +if (tegra_vpr_get_active_range (vpr, &first, &last)) { + pageno =tegra_vpr_find_free_region_in_range (vpr, first, last, + num_pages, align); +if (pageno >=0 ) +return pageno; + } + +/* +* If not enough free space exists within the currently active region, +* try to allocate adjacent to it to grow it contiguously and ensure +* optimal packing. +*/ + +/* +* Calculate where the allocation should start to end right at the +* first allocated page, with proper alignment. +*/ +if (vpr->first >= num_pages) { + target =ALIGN_DOWN (vpr->first - num_pages, align); + +if (!bitmap_allocate (vpr->bitmap, target, num_pages)) +return target; + } + +/* Try after the last allocation */ + target =ALIGN (vpr->last +1 , align); + +if (target + num_pages <= vpr->num_pages && + !bitmap_allocate (vpr->bitmap, target, num_pages)) +return target; + +/* +* Couldn't allocate at the ideal adjacent position, search for any +* available space before the first allocated page. +*/ + pageno =tegra_vpr_find_free_region_in_range (vpr,0 , vpr->first, + num_pages, align); +if (pageno >=0 ) +return pageno; + +/* +* Couldn't allocate at the ideal adjacent position, search +* for any available space after the last allocated page. +*/ + pageno =tegra_vpr_find_free_region_in_range (vpr, vpr->last +1 , + vpr->num_pages, num_pages, + align); +if (pageno >=0 ) +return pageno; + +return -ENOSPC ; +} + +/* +* Find a free region, preferring locations near existing allocations to +* minimize VPR fragmentation. The allocation strategy is to first allocate +* within or adjacent to the existing region to keep allocations clustered. +* Otherwise fall back to a generic allocation using the first available +* space. +* +* This approach focuses on page-level allocation first, then the chunk +* system determines which chunks need to be activated based on where the +* pages ended up. +*/ +static int tegra_vpr_allocate_region (struct tegra_vpr *vpr, +unsigned int num_pages, +unsigned int align) +{ +int pageno; + +/* +* For non-resizable VPR (no chunks), use simple first-fit allocation. +* Clustering optimization is only beneficial for resizable VPR where +* keeping allocations together minimizes the active VPR size. +*/ +if (!vpr->resizable) +return tegra_vpr_find_free_region (vpr, num_pages, align); + +/* +* Check if there are any existing allocations in the bitmap. If so, +* try to allocate near them to minimize fragmentation. +*/ + pageno =tegra_vpr_find_free_region_clustered (vpr, num_pages, align); +if (pageno >=0 ) +return pageno; + +/* +* If there are no existing allocations, or no space adjacent to them, +* fall back to the first available space anywhere in the VPR. +*/ + pageno =tegra_vpr_find_free_region (vpr, num_pages, align); +if (pageno >=0 ) +return pageno; + +return -ENOSPC ; +} + +static struct tegra_vpr_buffer * +tegra_vpr_buffer_allocate (struct tegra_vpr *vpr,size_t size) +{ +unsigned int num_pages = size >>PAGE_SHIFT ; +unsigned int order =get_order (size); +struct tegra_vpr_buffer *buffer; +unsigned long first, last; +int pageno, err; + +/* +* Quick sanity check that we're not trying to allocate a buffer that +* has no chance of fitting into the VPR. +*/ +if (size > vpr->size) +return ERR_PTR (-EINVAL ); + +/* +* "order" defines the alignment and size, so this may result in +* fragmented memory depending on the allocation patterns. However, +* since this is used primarily for video frames, it is expected that +* a number of buffers of the same size will be allocated, so +* fragmentation should be negligible. +*/ + pageno =tegra_vpr_allocate_region (vpr, num_pages,1 ); +if (pageno <0 ) +return ERR_PTR (pageno); + + first =find_first_bit (vpr->bitmap, vpr->num_pages); + last =find_last_bit (vpr->bitmap, vpr->num_pages); + + buffer =kzalloc_obj (*buffer,GFP_KERNEL ); +if (!buffer) { + err = -ENOMEM ; + goto release; + } + +INIT_LIST_HEAD (&buffer->attachments); +INIT_LIST_HEAD (&buffer->list); +mutex_init (&buffer->lock); + buffer->start = vpr->base + (pageno <<PAGE_SHIFT ); + buffer->limit = buffer->start + size; + buffer->size = size; + buffer->num_pages = num_pages; + buffer->pageno = pageno; + buffer->order = order; + +/* track which chunks this buffer overlaps */ +if (vpr->resizable) { +unsigned int limit = buffer->pageno + buffer->num_pages; +pgoff_t i; + +/* +* Memory is backed by struct page, so track which ones we +* use. +*/ + buffer->pages =kvmalloc_array (buffer->num_pages, +sizeof (*buffer->pages), +GFP_KERNEL ); +if (!buffer->pages) { + err = -ENOMEM ; + goto free; + } + +for (i =0 ; i < buffer->num_pages; i++) + buffer->pages[i] = &vpr->start_page[pageno + i]; + +for (i =0 ; i < vpr->num_chunks; i++) { +struct tegra_vpr_chunk *chunk = &vpr->chunks[i]; + +if (tegra_vpr_chunk_overlaps (chunk, pageno, limit)) +set_bit (i, buffer->chunks); + } + +/* activate chunks if necessary */ + err =tegra_vpr_activate_chunks (vpr, buffer); +if (err <0 ) { +kfree (buffer->pages); + goto free; + } + +/* track first and last allocated pages */ +if (buffer->pageno < vpr->first) + vpr->first = buffer->pageno; + +if (limit -1 > vpr->last) + vpr->last = limit -1 ; + } + +return buffer; + +free: +kfree (buffer); +release: +bitmap_clear (vpr->bitmap, pageno, num_pages); +return ERR_PTR (err); +} + +static void tegra_vpr_buffer_release (struct tegra_vpr_buffer *buffer) +{ +struct tegra_vpr *vpr = buffer->vpr; +struct tegra_vpr_buffer *entry; +unsigned int i; + +/* +* Decrement buffer count for each overlapping chunk. Note that chunks +* are not deactivated here yet, that's done in tegra_vpr_recycle() +* instead. +*/ +for_each_set_bit (i, buffer->chunks, vpr->num_chunks) { +if (!WARN_ON (vpr->chunks[i].num_buffers ==0 )) + vpr->chunks[i].num_buffers--; + } + +/* track first and last allocated pages */ +if (list_is_first (&buffer->list, &vpr->buffers) && +list_is_last (&buffer->list, &vpr->buffers)) { +/* if there are no remaining buffers after this, reset */ + vpr->first = ~0U ; + vpr->last =0U ; + }else if (list_is_first (&buffer->list, &vpr->buffers)) { + entry =list_next_entry (buffer, list); + vpr->first = entry->pageno; + }else if (list_is_last (&buffer->list, &vpr->buffers)) { + entry =list_prev_entry (buffer, list); + vpr->last = entry->pageno + entry->num_pages -1 ; + } + +bitmap_clear (vpr->bitmap, buffer->pageno, buffer->num_pages); +list_del (&buffer->list); +kfree (buffer->pages); +kfree (buffer); +} + +static int tegra_vpr_attach (struct dma_buf *buf, +struct dma_buf_attachment *attachment) +{ +struct tegra_vpr_buffer *buffer = buf->priv; +struct tegra_vpr_attachment *attach; +int err; + + attach =kzalloc_obj (*attach,GFP_KERNEL ); +if (!attach) +return -ENOMEM ; + +/* +* For resizable VPR, the memory is backed by struct page, so we can +* use the convenient helper to create the SG table. +*/ +if (buffer->pages) { + err =sg_alloc_table_from_pages (&attach->sgt, buffer->pages, + buffer->num_pages,0 , + buffer->size,GFP_KERNEL ); +if (err <0 ) + goto free; + }else { +if (sg_alloc_table (&attach->sgt,1 ,GFP_KERNEL )) { + err = -ENOMEM ; + goto free; + } + +sg_set_page (attach->sgt.sgl,NULL , buffer->size,0 ); +sg_dma_address (attach->sgt.sgl) = buffer->start; +sg_dma_len (attach->sgt.sgl) = buffer->size; + } + + attach->dev = attachment->dev; +INIT_LIST_HEAD (&attach->list); + attachment->priv = attach; + +mutex_lock (&buffer->lock); +list_add (&attach->list, &buffer->attachments); +mutex_unlock (&buffer->lock); + +return 0 ; + +free: +kfree (attach); +return err; +} + +static void tegra_vpr_detach (struct dma_buf *buf, +struct dma_buf_attachment *attachment) +{ +struct tegra_vpr_buffer *buffer = buf->priv; +struct tegra_vpr_attachment *attach = attachment->priv; + +mutex_lock (&buffer->lock); +list_del (&attach->list); +mutex_unlock (&buffer->lock); + +sg_free_table (&attach->sgt); +kfree (attach); +} + +static struct sg_table * +tegra_vpr_map_dma_buf (struct dma_buf_attachment *attachment, +enum dma_data_direction direction) +{ +struct tegra_vpr_attachment *attach = attachment->priv; +struct sg_table *sgt = &attach->sgt; +int err; + + err =dma_map_sgtable (attachment->dev, sgt, direction, +DMA_ATTR_SKIP_CPU_SYNC ); +if (err <0 ) +return ERR_PTR (err); + +return sgt; +} + +static void tegra_vpr_unmap_dma_buf (struct dma_buf_attachment *attachment, +struct sg_table *sgt, +enum dma_data_direction direction) +{ +dma_unmap_sgtable (attachment->dev, sgt, direction, +DMA_ATTR_SKIP_CPU_SYNC ); +} + +static void tegra_vpr_recycle (struct tegra_vpr *vpr) +{ +DECLARE_BITMAP (dirty, vpr->num_chunks); +unsigned int i; +int err; + +if (!vpr->resizable) +return ; + +bitmap_zero (dirty, vpr->num_chunks); + +/* +* Deactivate any unused chunks from the bottom... +*/ +for (i =0 ; i < vpr->num_chunks; i++) { +struct tegra_vpr_chunk *chunk = &vpr->chunks[i]; + +if (!chunk->active) +continue ; + +if (chunk->num_buffers >0 ) +break ; + + err =tegra_vpr_chunk_deactivate (chunk); +if (err <0 ) { +pr_err ("failed to deactivate chunk #%u: %d\n" , i, err); + goto activate; + }else { +clear_bit (i, vpr->active); +set_bit (i, dirty); + } + } + +/* +* ... and the top. +*/ +for (i =0 ; i < vpr->num_chunks; i++) { +unsigned int index = vpr->num_chunks - i -1 ; +struct tegra_vpr_chunk *chunk = &vpr->chunks[index]; + +if (!chunk->active) +continue ; + +if (chunk->num_buffers >0 ) +break ; + + err =tegra_vpr_chunk_deactivate (chunk); +if (err <0 ) { +pr_err ("failed to deactivate chunk #%u: %d\n" , index, + err); + goto activate; + }else { +clear_bit (index, vpr->active); +set_bit (index, dirty); + } + } + +if (!bitmap_empty (dirty, vpr->num_chunks)) { + err =tegra_vpr_resize (vpr); +if (err <0 ) { +pr_err ("failed to shrink VPR: %d\n" , err); + goto activate; + } + } + +/* release the CMA memory associated with deactivated chunks */ +for_each_set_bit (i, dirty, vpr->num_chunks) +tegra_vpr_chunk_release (&vpr->chunks[i]); + +return ; + +activate: +for_each_set_bit (i, dirty, vpr->num_chunks) { + err =tegra_vpr_chunk_activate (&vpr->chunks[i]); +if (WARN_ON (err <0 )) +pr_err ("failed to activate chunk #%u: %d\n" , i, err); + +/* +* This may not be fully activated at this point, but we need +* to keep track of it anyway to make sure the CMA region can +* eventually be released. The WARN_ON above tells us when it +* happens: here be dragons. +*/ +set_bit (i, vpr->active); + } +} + +static void tegra_vpr_release (struct dma_buf *buf) +{ +struct tegra_vpr_buffer *buffer = buf->priv; +struct tegra_vpr *vpr = buffer->vpr; + +mutex_lock (&vpr->lock); + +tegra_vpr_buffer_release (buffer); +tegra_vpr_recycle (vpr); + +mutex_unlock (&vpr->lock); +} + +/* +* Prohibit userspace mapping because the CPU cannot access this memory +* anyway. +*/ +static int tegra_vpr_begin_cpu_access (struct dma_buf *buf, +enum dma_data_direction direction) +{ +return -EPERM ; +} + +static int tegra_vpr_end_cpu_access (struct dma_buf *buf, +enum dma_data_direction direction) +{ +return -EPERM ; +} + +static int tegra_vpr_mmap (struct dma_buf *buf,struct vm_area_struct *vma) +{ +return -EPERM ; +} + +static const struct dma_buf_ops tegra_vpr_buf_ops = { + .attach = tegra_vpr_attach, + .detach = tegra_vpr_detach, + .map_dma_buf = tegra_vpr_map_dma_buf, + .unmap_dma_buf = tegra_vpr_unmap_dma_buf, + .release = tegra_vpr_release, + .begin_cpu_access = tegra_vpr_begin_cpu_access, + .end_cpu_access = tegra_vpr_end_cpu_access, + .mmap = tegra_vpr_mmap, +}; + +static struct dma_buf *tegra_vpr_allocate (struct dma_heap *heap, +unsigned long len,u32 fd_flags, +u64 heap_flags) +{ +struct tegra_vpr *vpr =dma_heap_get_drvdata (heap); +struct tegra_vpr_buffer *buffer, *entry; +size_t size =ALIGN (len, vpr->align); +DEFINE_DMA_BUF_EXPORT_INFO (export); +struct dma_buf *buf; + +mutex_lock (&vpr->lock); + + buffer =tegra_vpr_buffer_allocate (vpr, size); +if (IS_ERR (buffer)) { +mutex_unlock (&vpr->lock); +return ERR_CAST (buffer); + } + +/* insert in the correct order */ +if (!list_empty (&vpr->buffers)) { +list_for_each_entry (entry, &vpr->buffers, list) { +if (buffer->pageno < entry->pageno) { +list_add_tail (&buffer->list, &entry->list); +break ; + } + } + } + +if (list_empty (&buffer->list)) +list_add_tail (&buffer->list, &vpr->buffers); + + buffer->vpr = vpr; + +/* +* If a valid buffer was allocated, wrap it in a dma_buf +* and return it. +*/ + export.exp_name =dma_heap_get_name (heap); + export.ops = &tegra_vpr_buf_ops; + export.size = buffer->size; + export.flags = fd_flags; + export.priv = buffer; + + buf =dma_buf_export (&export); +if (IS_ERR (buf)) { +tegra_vpr_buffer_release (buffer); +tegra_vpr_recycle (vpr); + } + +mutex_unlock (&vpr->lock); +return buf; +} + +static void tegra_vpr_debugfs_show_buffers (struct tegra_vpr *vpr, +struct seq_file *s) +{ +struct tegra_vpr_buffer *buffer; +char buf[16 ]; + +mutex_lock (&vpr->lock); + +list_for_each_entry (buffer, &vpr->buffers, list) { +string_get_size (buffer->size,1 ,STRING_UNITS_2 , buf, +sizeof (buf)); +seq_printf (s," %pap-%pap (%s)\n" , &buffer->start, + &buffer->limit, buf); + } + +mutex_unlock (&vpr->lock); +} + +static void tegra_vpr_debugfs_show_chunks (struct tegra_vpr *vpr, +struct seq_file *s) +{ +struct tegra_vpr_buffer *buffer; +unsigned int i; +char buf[16 ]; + +for (i =0 ; i < vpr->num_chunks; i++) { +const struct tegra_vpr_chunk *chunk = &vpr->chunks[i]; + +string_get_size (chunk->size,1 ,STRING_UNITS_2 , buf, +sizeof (buf)); +seq_printf (s," %pap-%pap (%s) (%s, %u buffers)\n" , + &chunk->start, &chunk->limit, buf, + chunk->active ?"active" :"inactive" , + chunk->num_buffers); + } + +list_for_each_entry (buffer, &vpr->buffers, list) { +string_get_size (buffer->size,1 ,STRING_UNITS_2 , buf, +sizeof (buf)); +seq_printf (s,"%pap-%pap (%s, chunks: %*pbl)\n" , + &buffer->start, &buffer->limit, buf, + vpr->num_chunks, buffer->chunks); + } +} + +static int tegra_vpr_debugfs_show (struct seq_file *s,struct dma_heap *heap) +{ +struct tegra_vpr *vpr =dma_heap_get_drvdata (heap); +phys_addr_t limit = vpr->base + vpr->size; +char buf[16 ]; + +string_get_size (vpr->size,1 ,STRING_UNITS_2 , buf,sizeof (buf)); +seq_printf (s,"%pap-%pap (%s)\n" , &vpr->base, &limit, buf); + +if (!vpr->resizable) +tegra_vpr_debugfs_show_buffers (vpr, s); +else +tegra_vpr_debugfs_show_chunks (vpr, s); + +return 0 ; +} + +static const struct dma_heap_ops tegra_vpr_heap_ops = { + .allocate = tegra_vpr_allocate, + .show = tegra_vpr_debugfs_show, +}; + +static int tegra_vpr_setup_chunks (struct tegra_vpr *vpr,const char *name) +{ +phys_addr_t start, limit; +unsigned int order, i =0 ; +size_t max_size; +int err; + +/* Memory is backed by struct page, so track the first one. */ + vpr->start_page =phys_to_page (vpr->base); + +/* This seems a reasonable value, so hard-code it for now. */ + vpr->num_chunks =4 ; + + vpr->chunks =kzalloc_objs (*vpr->chunks, vpr->num_chunks); +if (!vpr->chunks) +return -ENOMEM ; + + vpr->active =bitmap_zalloc (vpr->num_chunks,GFP_KERNEL ); +if (!vpr->active) { + err = -ENOMEM ; + goto free; + } + + max_size =PAGE_SIZE << (get_order (vpr->size) -ilog2 (vpr->num_chunks)); + order =get_order (vpr->align); + +/* +* Allocate CMA areas for VPR. All areas will be roughtly the same +* size, with the last area taking up the rest. +*/ + start = vpr->base; + limit = vpr->base + vpr->size; + +pr_debug ("VPR: %pap-%pap (%lu pages, %u chunks, %lu MiB)\n" , &start, + &limit, vpr->num_pages, vpr->num_chunks, + (unsigned long )vpr->size /1024 /1024 ); + +for (i =0 ; i < vpr->num_chunks; i++) { +size_t size = limit - start; +phys_addr_t end; + + size =min_t (size_t, size, max_size); + end = start + size -1 ; + + err =tegra_vpr_chunk_init (vpr, &vpr->chunks[i], start, size, + order, name); +if (err <0 ) { +pr_err ("failed to create VPR chunk: %d\n" , err); + goto free; + } + +pr_debug (" %2u: %pap-%pap (%lu MiB)\n" , i, &start, &end, + size /1024 /1024 ); + start += size; + } + + vpr->first = ~0U ; + vpr->last =0U ; + +return 0 ; + +free: +while (i--) +tegra_vpr_chunk_free (&vpr->chunks[i]); + +kfree (vpr->active); +kfree (vpr->chunks); +return err; +} + +static void tegra_vpr_free_chunks (struct tegra_vpr *vpr) +{ +unsigned int i; + +for (i =0 ; i < vpr->num_chunks; i++) +tegra_vpr_chunk_free (&vpr->chunks[i]); + +kfree (vpr->chunks); +} + +static int tegra_vpr_setup_static (struct tegra_vpr *vpr) +{ +phys_addr_t start, limit; + + start = vpr->base; + limit = vpr->base + vpr->size; + +pr_debug ("VPR: %pap-%pap (%lu pages, %lu MiB)\n" , &start, &limit, + vpr->num_pages, (unsigned long )vpr->size /1024 /1024 ); + +return 0 ; +} + +static int tegra_vpr_add_heap (struct reserved_mem *rmem, +struct device_node *np) +{ +struct dma_heap_export_info info = {}; +unsigned long first, last; +struct dma_heap *heap; +struct tegra_vpr *vpr; +int err; + + vpr =kzalloc_obj (*vpr,GFP_KERNEL ); +if (!vpr) +return -ENOMEM ; + +INIT_LIST_HEAD (&vpr->list); +INIT_LIST_HEAD (&vpr->buffers);
drivers/dma-buf/heaps/tegra-vpr.c line 1133
Quoted 10 lines
drivers/dma-buf/heaps/tegra-vpr.c new file +10
-0+INIT_LIST_HEAD (&vpr->devices); +mutex_init (&vpr->lock); + + vpr->resizable = !of_property_read_bool (np,"no-map" ); + vpr->dev_node =of_node_get (np); + vpr->align =PAGE_SIZE ; + vpr->base = rmem->base; + vpr->size = rmem->size; + vpr->num_pages = vpr->size >>PAGE_SHIFT ; + vpr->nid =of_node_to_nid (np);
If this gets used, I can't find it.
Rob
Thierry Reding
maintainerPATCH v6 10/12 arm64: tegra: Add VPR placeholder node on Tegra234
In reply to Thierry RedingFrom: Thierry Reding <[email protected]>
This node contains two sets of properties, one for the case where the VPR is resizable (in which case the VPR region will be dynamically allocated at boot time) and another case where the VPR is fixed in size and initialized by early firmware.
The firmware running on the device is responsible for updating the node with the real physical address for the fixed VPR case and remove the properties needed only for resizable VPR. Similarly, if the VPR is resizable, the firmware should remove the "reg" property since it is no longer needed.
---
Changes in v3:
- comment out fixed VPR properties, assume resizable by default
- rename node to "protected"
--- arch/arm64/boot/dts/nvidia/tegra234.dtsi | 39 ++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+)
arch/arm64/boot/dts/nvidia/tegra234.dtsi +39 -0
@@ -29,6 +29,45 @@ aliases { i2c8 = &dp_aux_ch3_i2c; }; + reserved-memory { + #address-cells = <2>; + #size-cells = <2>; + ranges; + + vpr: protected { + compatible = "nvidia,tegra-video-protection-region"; + status = "disabled"; + + /* + * Two variants exist for this. For fixed VPR, the + * firmware is supposed to update the "reg" property + * with the fixed memory region configured as VPR. + * + * For resizable VPR we don't care about the exact + * address and instead want a reserved region to be + * allocated with a certain size and alignment at + * boot time. + * + * The below assumes resizable VPR by default. If the + * firmwares sets up fixed VPR, it is responsible for + * adding the missing "reg" property, removing any of + * the unused properties, as well as adding a unit- + * address matching the "reg" property. + */ + + /* fixed VPR */ + /* + reg = <0x0 0x0 0x0 0x0>; + no-map; + */ + + /* resizable VPR */ + size = <0x0 0x70000000>; + alignment = <0x0 0x100000>; + reusable; + }; + }; + bus@0 { compatible = "simple-bus";
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v6 10/12] arm64: tegra: Add VPR placeholder node on Tegra234
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [Critical] The newly introduced `cma_alloc_at()` API does not validate if the requested allocation range…
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [Critical] The newly introduced cma_alloc_at() API does not validate if the requested allocation range exceeds the bounds of the CMA region and mismatches bit/page units, leading to an out-of-bounds read and write in the CMA bitmap.
- [High] The tegra_vpr_set() function passes 64-bit physical addresses and sizes to a 32-bit SMC call, which truncates them, misconfiguring hardware protection.
- [High] Missing mutex lock in tegra_vpr_debugfs_show_chunks() when iterating over the vpr->buffers list.
- [High] A negative left shift occurs in tegra_vpr_setup_chunks() if the configured VPR size is small, leading to undefined behavior.
--
commit 4d64d0d8b755f60422c65bdb111c671e4013a472
Author: Thierry Reding <[email protected]>
arm64: tegra: Add VPR placeholder node on Tegra234
This node contains two sets of properties, one for the case where the VPR is resizable (in which case the VPR region will be dynamically allocated at boot time) and another case where the VPR is fixed in size and initialized by early firmware.
Quoted 5 lines
arch/arm64/boot/dts/nvidia/tegra234.dtsi +0
-0
arch/arm64/boot/dts/nvidia/tegra234.dtsi aliases { · line 38
Quoted 10 lines
arch/arm64/boot/dts/nvidia/tegra234.dtsi +7
-0@@ -29,6 +29,45 @@ aliases { i2c8 = &dp_aux_ch3_i2c; }; + reserved-memory { + #address-cells = <2>; + #size-cells = <2>; + ranges; + + vpr: protected { + compatible = "nvidia,tegra-video-protection-region";
[Severity: High]
Is it possible for the shift operand to become negative when the VPR size is small?
If the VPR size configured in the device tree is small (e.g., 4KB or 8KB), get_order(vpr->size) is 0 or 1. Since vpr->num_chunks is hardcoded to 4, ilog2(4) is 2. The shift operand can evaluate without bounds checking:
drivers/dma-buf/heaps/tegra-vpr.c:tegra_vpr_setup_chunks() {
...
max_size = PAGE_SIZE << (get_order(vpr->size) - ilog2(vpr->num_chunks));
...
}Can this evaluate to a negative number (e.g., 0 - 2 or 1 - 2) and cause a negative shift during driver initialization based on device tree inputs? On arm64, a negative shift count often wraps around, resulting in a very large max_size.
[Severity: High]
Could passing these 64-bit addresses to the SMC32 call cause truncation?
The 64-bit parameters base and size are passed directly into an SMC32 call:
drivers/dma-buf/heaps/tegra-vpr.c:tegra_vpr_set() {
...
arm_smccc_smc(ARM_SMCCC_VENDOR_SIP_TE_PROGRAM_VPR_FUNC_ID, base, size,
0, 0, 0, 0, 0, &res);
...
}The ARM_SMCCC_VENDOR_SIP_TE_PROGRAM_VPR_FUNC_ID uses ARM_SMCCC_SMC_32, meaning the SMC instruction adheres to the 32-bit calling convention, natively truncating the upper 32 bits of base and size inside the secure monitor. Since CMA regions on arm64 frequently reside above the 4GB boundary, can this misconfigure hardware protection by locking down the wrong physical memory?
[Severity: High]
Is it safe to iterate the vpr->buffers list here without acquiring a lock?
drivers/dma-buf/heaps/tegra-vpr.c:tegra_vpr_debugfs_show_chunks() {
...
list_for_each_entry(buffer, &vpr->buffers, list) {
...
}This iteration accesses a shared, mutable linked list without acquiring vpr->lock. If another process performs a DMA-BUF allocation or release concurrently, it modifies the vpr->buffers list under vpr->lock. Can this result in list corruption or a use-after-free if modified or freed nodes are encountered mid-traversal?
[Severity: Critical]
Are the offset and count units mismatched when calling cma_range_alloc()?
The exported cma_alloc_at API passes page-based offset and count to cma_range_alloc():
mm/cma.c:cma_alloc_at() {
...
page = cma_alloc_at_frozen(cma, offset, count, no_warn);
...
}In cma_range_alloc(), this sets the max limit for the bitmap scan to end without bounds checking:
mm/cma.c:cma_range_alloc() {
...
bitmap_maxno = (end > start) ? end : cma_bitmap_maxno(cma, cmr);
...
}cma_alloc_at_frozen() passes offset and offset + count (which are in pages) to cma_range_alloc(), but cma_range_alloc() incorrectly assumes end is always passed in bits instead of pages. Any driver calling cma_alloc_at() with an offset + count exceeding the CMA region size could bypass length validation.
Will this scan past the end of the allocated CMA bitmap and allow bitmap_set() to write out-of-bounds?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
Thierry Reding
maintainerPATCH v6 11/12 arm64: tegra: Hook up VPR to host1x
In reply to Thierry RedingFrom: Thierry Reding <[email protected]>
The host1x needs access to the VPR region, so make sure to reference it via the memory-region property.
--- arch/arm64/boot/dts/nvidia/tegra234.dtsi | 6 ++++++ 1 file changed, 6 insertions(+)
arch/arm64/boot/dts/nvidia/tegra234.dtsi +6 -0
@@ -4479,6 +4479,9 @@ vic@15340000 { interconnect-names = "dma-mem", "write"; iommus = <&smmu_niso1 TEGRA234_SID_VIC>; dma-coherent; + + memory-region = <&vpr>; + memory-region-names = "protected"; }; nvdec@15480000 {
@@ -4497,6 +4500,9 @@ nvdec@15480000 { iommus = <&smmu_niso1 TEGRA234_SID_NVDEC>; dma-coherent; + memory-region = <&vpr>; + memory-region-names = "protected"; + nvidia,memory-controller = <&mc>; /*
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v6 11/12] arm64: tegra: Hook up VPR to host1x
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [High] The VPR driver assumes `set_direct_map_invalid_noflush()` successfully unmaps memory from the…
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [High] The VPR driver assumes set_direct_map_invalid_noflush() successfully unmaps memory from the linear map if it returns 0. However, on arm64 with rodata_full disabled, the function is a silent no-op (returns 0 without modifying PTEs).
- [High] For static VPR allocations without page-backing, dma_map_sgtable() is unconditionally called with a NULL page pointer, which will generate a bogus DMA address and corrupt the mapping.
- [High] Memory allocated with kvmalloc_array() is incorrectly freed with kfree(), which will cause a kernel panic if the allocation fell back to vmalloc.
- [Medium] The vpr->active bitmap leaks on the error path if dma_heap_add() fails.
--
commit 41cac70cac0869723195f2732d0c1395995f6880
Author: Thierry Reding <[email protected]>
arm64: tegra: Hook up VPR to host1x
The host1x needs access to the VPR region, so make sure to reference it via the memory-region property.
arch/arm64/boot/dts/nvidia/tegra234.dtsi vic@15340000 { · line 4484
Quoted 11 lines
arch/arm64/boot/dts/nvidia/tegra234.dtsi +3
-0@@ -4479,6 +4479,9 @@ vic@15340000 { interconnect-names = "dma-mem", "write"; iommus = <&smmu_niso1 TEGRA234_SID_VIC>; dma-coherent; + + memory-region = <&vpr>; + memory-region-names = "protected";
[Severity: High]
Does hooking up the VPR driver here expose an issue where set_direct_map_invalid_noflush() is assumed to invalidate memory, but silently fails on arm64?
In drivers/dma-buf/heaps/tegra-vpr.c:tegra_vpr_chunk_activate():
err = set_direct_map_invalid_noflush(chunk->start_page, chunk->num_pages); if (err) return err;
On arm64, if rodata_full is disabled, can_set_direct_map() returns false, causing set_direct_map_invalid_noflush() to return 0 without actually modifying PTEs. Since this returns 0, the driver assumes success and continues.
If the CPU speculatively accesses memory that is supposed to be protected by the VPR, could the hardware memory controller block the access and fault?
[Severity: High]
Does enabling VPR also trigger an issue where dma_map_sgtable() overwrites manually crafted SG entries containing NULL page pointers?
In drivers/dma-buf/heaps/tegra-vpr.c:tegra_vpr_map_dma_buf():
err = dma_map_sgtable(attachment->dev, sgt, direction, DMA_ATTR_SKIP_CPU_SYNC);
For static VPR allocations without page-backing, the driver creates an SG table and explicitly sets sg_set_page() to NULL in tegra_vpr_attach(), manually populating sg_dma_address.
However, the unconditional call to dma_map_sgtable() will iterate over the SG table, extract the physical address via sg_page() (which resolves to PA 0), and map it, overwriting the driver's manually populated sg_dma_address.
Can this corrupt the DMA mapping and potentially cause an IOMMU fault?
[Severity: High]
Is it safe to free memory allocated with kvmalloc_array() using kfree()?
In drivers/dma-buf/heaps/tegra-vpr.c:tegra_vpr_buffer_allocate():
buffer->pages = kvmalloc_array(buffer->num_pages,
sizeof(*buffer->pages),
GFP_KERNEL);
...
err = tegra_vpr_activate_chunks(vpr, buffer);
if (err < 0) {
kfree(buffer->pages);
goto free;
}And also in tegra_vpr_buffer_release():
bitmap_clear(vpr->bitmap, buffer->pageno, buffer->num_pages); list_del(&buffer->list); kfree(buffer->pages); kfree(buffer);
If the kvmalloc_array() allocation falls back to vmalloc(), calling kfree() on a vmalloc address will trigger a kernel bug. Since video buffers are typically large, isn't the vmalloc() fallback highly likely?
[Severity: Medium]
Does the vpr->active bitmap leak on the error path if dma_heap_add() fails?
In drivers/dma-buf/heaps/tegra-vpr.c:tegra_vpr_add_heap(), if dma_heap_add() fails, it jumps to cleanup:
cleanup:
if (vpr->resizable) tegra_vpr_free_chunks(vpr);
But tegra_vpr_free_chunks() fails to clean up the bitmap allocated in tegra_vpr_setup_chunks():
vpr->active = bitmap_zalloc(vpr->num_chunks, GFP_KERNEL);
Should there be a corresponding bitmap_free(vpr->active) in tegra_vpr_free_chunks()?
Quoted 3 lines
arch/arm64/boot/dts/nvidia/tegra234.dtsi +0
-0}; nvdec@15480000 {
[ ... ]
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
Thierry Reding
maintainerPATCH v6 12/12 arm64: tegra: Add VPR placeholder node on Tegra264
In reply to Thierry RedingFrom: Thierry Reding <[email protected]>
This node contains two sets of properties, one for the case where the VPR is resizable (in which case the VPR region will be dynamically allocated at boot time) and another case where the VPR is fixed in size and initialized by early firmware.
The firmware running on the device is responsible for updating the node with the real physical address for the fixed VPR case and remove the properties needed only for resizable VPR. Similarly, if the VPR is resizable, the firmware should remove the "reg" property since it is no longer needed.
---
Changes in v3:
- comment out fixed VPR properties, assume resizable by default
- rename node to "protected"
--- arch/arm64/boot/dts/nvidia/tegra264.dtsi | 33 ++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+)
arch/arm64/boot/dts/nvidia/tegra264.dtsi +33 -0
@@ -24,6 +24,39 @@ shmem_bpmp: shmem@86070000 { reg = <0x0 0x86070000 0x0 0x2000>; no-map; }; + + vpr: protected { + compatible = "nvidia,tegra-video-protection-region"; + status = "disabled"; + + /* + * Two variants exist for this. For fixed VPR, the + * firmware is supposed to update the "reg" property + * with the fixed memory region configured as VPR. + * + * For resizable VPR we don't care about the exact + * address and instead want a reserved region to be + * allocated with a certain size and alignment at + * boot time. + * + * The below assumes resizable VPR by default. If the + * firmwares sets up fixed VPR, it is responsible for + * adding the missing "reg" property, removing any of + * the unused properties, as well as adding a unit- + * address matching the "reg" property. + */ + + /* fixed VPR */ + /* + reg = <0x0 0x0 0x0 0x0>; + no-map; + */ + + /* resizable VPR */ + size = <0x0 0x70000000>; + alignment = <0x0 0x100000>; + reusable; + }; }; /* SYSTEM MMIO */
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v6 12/12] arm64: tegra: Add VPR placeholder node on Tegra264
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 7 lines
From: Thierry Reding <[email protected]>
This node contains two sets of properties, one for the case where the VPR is resizable (in which case the VPR region will be dynamically allocated at boot time) and another case where the VPR is fixed in size and initialized by early firmware.
Quoted 7 lines
The firmware running on the device is responsible for updating the node with the real physical address for the fixed VPR case and remove the properties needed only for resizable VPR. Similarly, if the VPR is resizable, the firmware should remove the "reg" property since it is no longer needed.
Signed-off-by Thierry Reding <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
Will Deacon
maintainerHi Thierry,
Quoted 15 lines · Thierry Reding
This series adds support for the video protection region (VPR) used on Tegra SoC devices. It's a special region of memory that is protected from accesses by the CPU and used to store DRM protected content (both decrypted stream data as well as decoded video frames).
Patches 1 through 3 add DT binding documentation for the VPR and add the VPR to the list of memory-region items for display, host1x and NVDEC.
The set_direct_map_*_noflush() functions that will be used later in this series are exported in patch 4 so that the drivers that use them can be built as a module.
Patch 5 adds
bitmap_allocate(), which is likebitmap_allocate_region()but works on sizes that are not a power of two.
Quoted 8 lines
The
of_node_to_nid()function is exported in patch 6 because it is used in a later patch adding a driver that can be built as a module.Patch 7 introduces new APIs needed by the Tegra VPR implementation that allow memory to be allocated at a fixed offset within a CMA area. Tegra VPR needs this in order to implement its own allocator on top of CMA to meet the strict hardware requirements. This replaces the dynamic CMA area creation patch from earlier versions.
Did you get a chance to see how this could work with Vincent's series:
https://lore.kernel.org/r/[email protected]
? I think that should remove your reliance on can_set_direct_map() and mean that you can retain block mappings for most of the linear mapping.
Looks like you forgot to cc him, so I added him here.
Cheers,
Will
Thierry Reding
maintainerQuoted 27 lines · Will Deacon
Hi Thierry,
Quoted 15 lines · Thierry Reding
This series adds support for the video protection region (VPR) used on Tegra SoC devices. It's a special region of memory that is protected from accesses by the CPU and used to store DRM protected content (both decrypted stream data as well as decoded video frames).
Patches 1 through 3 add DT binding documentation for the VPR and add the VPR to the list of memory-region items for display, host1x and NVDEC.
The set_direct_map_*_noflush() functions that will be used later in this series are exported in patch 4 so that the drivers that use them can be built as a module.
Patch 5 adds
bitmap_allocate(), which is likebitmap_allocate_region()but works on sizes that are not a power of two.Quoted 8 lines
The
of_node_to_nid()function is exported in patch 6 because it is used in a later patch adding a driver that can be built as a module.Patch 7 introduces new APIs needed by the Tegra VPR implementation that allow memory to be allocated at a fixed offset within a CMA area. Tegra VPR needs this in order to implement its own allocator on top of CMA to meet the strict hardware requirements. This replaces the dynamic CMA area creation patch from earlier versions.
Quoted 6 lines
Did you get a chance to see how this could work with Vincent's series:
https://lore.kernel.org/r/[email protected]
? I think that should remove your reliance on
can_set_direct_map()and mean that you can retain block mappings for most of the linear mapping.
I'm not sure if it would help all that much. Yes, if we mark the VPR region as LLMAP (or PTE_MAP, whichever it ends up being), it should make the checks for can_set_direct_map() redundant. However, from what I can tell, Vincent's series still forces page-granularity on these regions, so it won't retain block mappings at all for them.
The block mappings can be retained for the non-VPR memory, so that's nice. It also reduces the amount of external prerequisites, but I had kind of hoped that we could go one step further and keep block mappings even for the VPR memory if the region happened to be a multiple of the block size.
The recent addition of page count to the set_direct_map_*() functions helps reduce the amount of checks that need to be run, so maybe there's not too much to be gained from removing whole block mappings at once from the linear map.
Thierry
Quoted 47 lines · Thierry Reding
Quoted 27 lines · Will Deacon
Hi Thierry,
Quoted 15 lines · Thierry Reding
This series adds support for the video protection region (VPR) used on Tegra SoC devices. It's a special region of memory that is protected from accesses by the CPU and used to store DRM protected content (both decrypted stream data as well as decoded video frames).
Patches 1 through 3 add DT binding documentation for the VPR and add the VPR to the list of memory-region items for display, host1x and NVDEC.
The set_direct_map_*_noflush() functions that will be used later in this series are exported in patch 4 so that the drivers that use them can be built as a module.
Patch 5 adds
bitmap_allocate(), which is likebitmap_allocate_region()but works on sizes that are not a power of two.Quoted 8 lines
The
of_node_to_nid()function is exported in patch 6 because it is used in a later patch adding a driver that can be built as a module.Patch 7 introduces new APIs needed by the Tegra VPR implementation that allow memory to be allocated at a fixed offset within a CMA area. Tegra VPR needs this in order to implement its own allocator on top of CMA to meet the strict hardware requirements. This replaces the dynamic CMA area creation patch from earlier versions.
Quoted 6 lines
Did you get a chance to see how this could work with Vincent's series:
https://lore.kernel.org/r/[email protected]
? I think that should remove your reliance on
can_set_direct_map()and mean that you can retain block mappings for most of the linear mapping.I'm not sure if it would help all that much. Yes, if we mark the VPR region as LLMAP (or
PTE_MAP, whichever it ends up being), it should make the checks forcan_set_direct_map()redundant. However, from what I can tell, Vincent's series still forces page-granularity on these regions, so it won't retain block mappings at all for them.The block mappings can be retained for the non-VPR memory, so that's nice. It also reduces the amount of external prerequisites, but I had kind of hoped that we could go one step further and keep block mappings even for the VPR memory if the region happened to be a multiple of the block size.
Quoted 6 lines
The recent addition of page count to the set_direct_map_*() functions helps reduce the amount of checks that need to be run, so maybe there's not too much to be gained from removing whole block mappings at once from the linear map.
Thierry
I should be able to add PMD_SIZE mapping support to the series. That was actually my original idea as we can easily force the CMA allocation granule to be PMD_SIZE too.
I didn't implement it as I thought there were not much interest in the end (and also as contiguous.c is always using PAGE_SIZE granularity).
But now as I have implemented a specific pool (and do not use contiguous.c as originally planned), if you believe it is important for the VPR driver, let me see if I can extend the support in a V2.
Signature · 1 line
Vincent
Thierry Reding
maintainerQuoted 59 lines · Vincent Donnefort
Quoted 47 lines · Thierry Reding
Quoted 27 lines · Will Deacon
Hi Thierry,
Quoted 15 lines · Thierry Reding
This series adds support for the video protection region (VPR) used on Tegra SoC devices. It's a special region of memory that is protected from accesses by the CPU and used to store DRM protected content (both decrypted stream data as well as decoded video frames).
Patches 1 through 3 add DT binding documentation for the VPR and add the VPR to the list of memory-region items for display, host1x and NVDEC.
The set_direct_map_*_noflush() functions that will be used later in this series are exported in patch 4 so that the drivers that use them can be built as a module.
Patch 5 adds
bitmap_allocate(), which is likebitmap_allocate_region()but works on sizes that are not a power of two.Quoted 8 lines
The
of_node_to_nid()function is exported in patch 6 because it is used in a later patch adding a driver that can be built as a module.Patch 7 introduces new APIs needed by the Tegra VPR implementation that allow memory to be allocated at a fixed offset within a CMA area. Tegra VPR needs this in order to implement its own allocator on top of CMA to meet the strict hardware requirements. This replaces the dynamic CMA area creation patch from earlier versions.
Quoted 6 lines
Did you get a chance to see how this could work with Vincent's series:
https://lore.kernel.org/r/[email protected]
? I think that should remove your reliance on
can_set_direct_map()and mean that you can retain block mappings for most of the linear mapping.I'm not sure if it would help all that much. Yes, if we mark the VPR region as LLMAP (or
PTE_MAP, whichever it ends up being), it should make the checks forcan_set_direct_map()redundant. However, from what I can tell, Vincent's series still forces page-granularity on these regions, so it won't retain block mappings at all for them.The block mappings can be retained for the non-VPR memory, so that's nice. It also reduces the amount of external prerequisites, but I had kind of hoped that we could go one step further and keep block mappings even for the VPR memory if the region happened to be a multiple of the block size.
Quoted 6 lines
The recent addition of page count to the set_direct_map_*() functions helps reduce the amount of checks that need to be run, so maybe there's not too much to be gained from removing whole block mappings at once from the linear map.
Thierry
I should be able to add
PMD_SIZEmapping support to the series. That was actually my original idea as we can easily force the CMA allocation granule to bePMD_SIZEtoo.
Quoted 6 lines
I didn't implement it as I thought there were not much interest in the end (and also as
contiguous.cis always usingPAGE_SIZEgranularity).But now as I have implemented a specific pool (and do not use
contiguous.cas originally planned), if you believe it is important for the VPR driver, let me see if I can extend the support in a V2.
I don't think it needs to be part of a v2 and can be a follow-up. It should be transparent from an API point of view and merely be an optimisation for that specific case.
Eventually it'd be nice to have, though it might also be worth checking what the actually gains are.
Thierry
Quoted 67 lines · Thierry Reding
Quoted 59 lines · Vincent Donnefort
Quoted 47 lines · Thierry Reding
Quoted 27 lines · Will Deacon
Hi Thierry,
Quoted 15 lines · Thierry Reding
This series adds support for the video protection region (VPR) used on Tegra SoC devices. It's a special region of memory that is protected from accesses by the CPU and used to store DRM protected content (both decrypted stream data as well as decoded video frames).
Patches 1 through 3 add DT binding documentation for the VPR and add the VPR to the list of memory-region items for display, host1x and NVDEC.
The set_direct_map_*_noflush() functions that will be used later in this series are exported in patch 4 so that the drivers that use them can be built as a module.
Patch 5 adds
bitmap_allocate(), which is likebitmap_allocate_region()but works on sizes that are not a power of two.Quoted 8 lines
The
of_node_to_nid()function is exported in patch 6 because it is used in a later patch adding a driver that can be built as a module.Patch 7 introduces new APIs needed by the Tegra VPR implementation that allow memory to be allocated at a fixed offset within a CMA area. Tegra VPR needs this in order to implement its own allocator on top of CMA to meet the strict hardware requirements. This replaces the dynamic CMA area creation patch from earlier versions.
Quoted 6 lines
Did you get a chance to see how this could work with Vincent's series:
https://lore.kernel.org/r/[email protected]
? I think that should remove your reliance on
can_set_direct_map()and mean that you can retain block mappings for most of the linear mapping.I'm not sure if it would help all that much. Yes, if we mark the VPR region as LLMAP (or
PTE_MAP, whichever it ends up being), it should make the checks forcan_set_direct_map()redundant. However, from what I can tell, Vincent's series still forces page-granularity on these regions, so it won't retain block mappings at all for them.The block mappings can be retained for the non-VPR memory, so that's nice. It also reduces the amount of external prerequisites, but I had kind of hoped that we could go one step further and keep block mappings even for the VPR memory if the region happened to be a multiple of the block size.
Quoted 6 lines
The recent addition of page count to the set_direct_map_*() functions helps reduce the amount of checks that need to be run, so maybe there's not too much to be gained from removing whole block mappings at once from the linear map.
Thierry
I should be able to add
PMD_SIZEmapping support to the series. That was actually my original idea as we can easily force the CMA allocation granule to bePMD_SIZEtoo.Quoted 6 lines
I didn't implement it as I thought there were not much interest in the end (and also as
contiguous.cis always usingPAGE_SIZEgranularity).But now as I have implemented a specific pool (and do not use
contiguous.cas originally planned), if you believe it is important for the VPR driver, let me see if I can extend the support in a V2.
Quoted 8 lines
I don't think it needs to be part of a v2 and can be a follow-up. It should be transparent from an API point of view and merely be an optimisation for that specific case.
Eventually it'd be nice to have, though it might also be worth checking what the actually gains are.
Thierry
Ack. I'll keep it as is then and we will see later how to extend it, if it is necessary.
Signature · 1 line
Vincent
Thierry Reding
maintainerQuoted 47 lines · Thierry Reding
Quoted 27 lines · Will Deacon
Hi Thierry,
Quoted 15 lines · Thierry Reding
This series adds support for the video protection region (VPR) used on Tegra SoC devices. It's a special region of memory that is protected from accesses by the CPU and used to store DRM protected content (both decrypted stream data as well as decoded video frames).
Patches 1 through 3 add DT binding documentation for the VPR and add the VPR to the list of memory-region items for display, host1x and NVDEC.
The set_direct_map_*_noflush() functions that will be used later in this series are exported in patch 4 so that the drivers that use them can be built as a module.
Patch 5 adds
bitmap_allocate(), which is likebitmap_allocate_region()but works on sizes that are not a power of two.Quoted 8 lines
The
of_node_to_nid()function is exported in patch 6 because it is used in a later patch adding a driver that can be built as a module.Patch 7 introduces new APIs needed by the Tegra VPR implementation that allow memory to be allocated at a fixed offset within a CMA area. Tegra VPR needs this in order to implement its own allocator on top of CMA to meet the strict hardware requirements. This replaces the dynamic CMA area creation patch from earlier versions.
Quoted 6 lines
Did you get a chance to see how this could work with Vincent's series:
https://lore.kernel.org/r/[email protected]
? I think that should remove your reliance on
can_set_direct_map()and mean that you can retain block mappings for most of the linear mapping.I'm not sure if it would help all that much. Yes, if we mark the VPR region as LLMAP (or
PTE_MAP, whichever it ends up being), it should make the checks forcan_set_direct_map()redundant. However, from what I can tell, Vincent's series still forces page-granularity on these regions, so it won't retain block mappings at all for them.The block mappings can be retained for the non-VPR memory, so that's nice. It also reduces the amount of external prerequisites, but I had kind of hoped that we could go one step further and keep block mappings even for the VPR memory if the region happened to be a multiple of the block size.
Quoted 4 lines
The recent addition of page count to the set_direct_map_*() functions helps reduce the amount of checks that need to be run, so maybe there's not too much to be gained from removing whole block mappings at once from the linear map.
I don't think everyone received Sashiko's review, so let me discuss this here. Sashiko rightly pointed out that set_direct_map_invalid_noflush() and set_direct_map_default_noflush() return 0 when can_set_direct_map() fails and that code will then simply continue to work as if the pages had been removed (or added back) even though they weren't.
arch/arm64/mm/pageattr.c:set_direct_map_invalid_noflush() {
...
if (!can_set_direct_map())
return 0;
...
}Looking into this a bit, it looks like this is maybe a remnant from the early days when the check was simpler ("if (!rodata_full)", though I'm not sure the 0 return value made sense even then), but it seems wrong indeed for this to result in success when clearly the operation was skipped.
None of the other architectures seem to have similar checks, except for clear cases of no-ops (like the address being outside the linear mapping, the number of pages being 0 or there not being any actual changes). All of the three callers seem to be prepared to deal with failure, so I think we should just make these fail instead of returning 0.
Any thought?
Thierry